// jtk stands for jobkoo tool kit
// @author  chrisyu[at]jokboo.com
// @require jquery.js
// @require i18n.js

// light box effect
var shadow = {
  getShadow: function() {
    if (!this.shadow) {
      this.shadow = $("<div/>").addClass('fixed').css({
        width: screen.width,
        height: screen.height,
        background: "#000",
        top: 0, left: 0,
        opacity: 0,
        zIndex: 5000,
        display: 'none'
      }).appendTo($("body"));

      // for which cannot support position: fixed
      if (this.shadow.css("position") != "fixed") {
        this.shadow.css({
          width:  $("body").width(),
          height: Math.max($("body").height(), $(window).height())
        }).removeClass("fixed").addClass("absolute");
      }
    }

    return this.shadow;
  },

  setBox: function(box, pos) {
    if (box) {
      if (this.getBox()) {
        box.preBox = this.getBox();
        box.preBox.hide();
      }
    }
    pos && box.data('pos', pos);
    this.box = box;
    
    return this;
  },

  getBox: function() {
    return this.box;
  },
  
  popup: function(opacity) {
    var inst = this.getShadow();
    // if shadow not show then show it
    inst.css('display') == 'none' && inst.show();
    if (opacity === undefined) {
      inst.css('opacity', 0.5);
    } else {
      inst.css('opacity', opacity);
    }
    // show box
    var box = this.getBox();
      
    box.addClass('fixed').appendTo($("body")).css({
      zIndex: 5555
    });

    box.fadeIn();

    var pos;
    if (box.data('pos')) {
      pos = box.data('pos');
    } else {
      pos = {
        top:  $(window).height() / 2 - box.height() / 2,
        left: $(window).width() / 2 - box.width() / 2
      };
      box.data('pos', pos);
    }

    if (pos.bottom) {
      box.css('bottom', pos.bottom + 'px');
    } else if(pos.top) {
      box.css('top', pos.top + 'px');
    }

    if (pos.right) {
      box.css('right', pos.right + 'px');
    } else if (pos.left) {
      box.css('left', pos.left + 'px');
    }

    box.children(".-shadow-focus").size()
      && box.children(".-shadow-focus").focus();

    if (box.css('position') != 'fixed') {
      autoScroll(box);
    }

    return this;
  },

  close: function(removeBoxCompletely) {
    this.getShadow().fadeOut().unbind('click');
    this.getBox().fadeOut();
    removeBoxCompletely && this.getBox().remove();
    return this.setBox(null); //this
  },

  // always used methods:
  message: function(msg, callback) {
    callback = callback || function() { shadow.close(true); };
    
    var box = this.predefined.box();
    box.append(this.predefined.btn.ok().click(callback))
       .children("p:first").html(msg)
    this.setBox(box);
    this.popup();
  },

  warning: function(msg, callback) {
    callback = callback || function() { shadow.close(true); };
    
    var box = this.predefined.box();
    box.append(this.predefined.btn.ok().click(callback))
       .children("p:first").html(msg)
       .css({
          background: 'url(/images/shadow-warning.gif) 25px 15px no-repeat'
        });
    this.setBox(box);
    this.popup();
  },
  
  confirm: function(msg, okCallback, cancelCallback) {
    cancelCallback = cancelCallback || function() { shadow.close(true); };
    
    var box = this.predefined.box();
    box.append(this.predefined.btn.ok().click(okCallback))
       .append(this.predefined.btn.cancel().click(cancelCallback))
       .children("p:first").html(msg)
       .css({
          background: 'url(/images/shadow-warning.gif) 25px 15px no-repeat'
        });
    this.setBox(box);
    this.popup();
  },
  
  predefined: {
    box: function() {
      return $("<div>").css({
               border: "3px solid #aaa",
               background: "#fff",
               textAlign: "center"
             }).append($("<p>").css({
               padding: "25px 25px 25px 100px",
               textAlign: "left",
               width: "300px",
               lineHeight: "25px"
             }));
    },
    
    btn: {
      ok: function() {
        var image = $('<img>').attr('alt', __('Ok'))
          .attr('src', '/images/shadow-ok-btn-' 
            + __('en_US')
            + '.gif');

        return $('<button class="-shadow-focus">')
          .css({
            margin: '10px',
            padding: 0,
            border: 0,
            background: 'transparent'
          }).append(image);
      },

      cancel: function() {
        var image = $('<img>').attr('alt', __('Cancel'))
          .attr('src', '/images/shadow-cancel-btn-' 
            + __('en_US')
            + '.gif');

        return $('<button>')
          .css({
             margin: '10px',
             padding: 0,
             border: 0,
             background: 'transparent'
          }).append(image);
      }
    }
  }
};

// store anything in cookie
// to replace the jsoncookie.js
var storage = {
  get: function(key, def) {
    var ret;
    if ((ret = $.cookie(key)) || typeof ret == "boolean") {
      try {
        return unserialize($.cookie(key));
      } catch (e) {
        return $.cookie(key);
      }
    } else {
      return def;
    }
  },

  set: function(key, val) {
    val = serialize(val);
    $.cookie(key, val, { expires: 90, domain: 'jobkoo.com', path: '/' });
    return this;
  }
}

function isKeyword(kw)
{
  return !/^[.\/\\ #@<>\-:;,?'"~!$%^*()+=|{}\[\]`]*$/
    .test(kw);
}

function isEmail(email)
{
  return /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i.test(email);
}

// like php's serialize function
// translate everything into a string
// maybe have bugs, be careful ...
function serialize(obj)
{
  if (!obj) return obj;
  if ($.isArray(obj)) {
    var tmp = [];
    $.each(obj, function(i, n) {
      tmp.push(serialize(n));
    });
    return '[' + tmp.join(',') + ']';
  } else if (typeof obj == 'object') {
    var tmp = [];
    $.each(obj, function(i, n) {
      tmp.push(i + ':' + serialize(n));
    });
    return '{' + tmp.join(',') + '}';
  } else if (typeof obj == 'string') {
    return '"' + obj.replace('\\', '\\\\').replace('"', '\\"') + '"';
  } else {
    return obj;
  }
}

// like php's unserialize
function unserialize(str)
{
  return eval('(' + str + ')');
}

// find a certain value's index in a array
// if not found return -1
// it supports complex data structure value
Array.prototype.getIndex = function(obj) {
  var obj2 = serialize(obj);

  var tmp = [];
  $.each(this, function(i, n) {
    tmp.push(serialize(n));
  });

  var ret = -1;
  $.each(tmp, function(i, n) {
    if (n == obj2) { // IE has no "indexOf" method, even IE7
      ret = i;
      return ; // break "$.each"
    }
  });
  return ret;
}

// check if a value exists in a array
Array.prototype.possesses = function(obj) {
  return this.getIndex(obj) > -1;
}
