/**
 * @author firejune, jhlee
 * 
 * Depends:
 *   jquery.js
 *   jquery.json.js
 *
**/
/* Local Storage Helper Class */
/*
 * $H(this.data).toJSON() : obj -> string
 * $.toJSON(this.data)  : obj -> string
 * JSON.stringify         : obj -> string 
 * 
 * this.data.evalJSON()    : string -> obj 
 * $.evalJSON(this.data) : string -> obj
 * JSON.parse              : string -> obj
 */

(function($){
var localstorage = function() {
  return {
    init: function(name, options){
      /*
      this.options = Object.extend({
          clearable: true, // automatically clear data if an error occurred
          delay: 2000, // save data to localStorage after the allotted time
          maximum: 5 // the maximum size in megabytes
        }, options);
      */
      options           = options || {};
      options.clearable = options.clearable || true;// automatically clear data if an error occurred
      options.delay     = options.delay || 2000;// save data to localStorage after the allotted time
      options.maximum   = options.maximum || 5;// the maximum size in megabytes
      this.options = options;

      if (typeof localStorage == "undefined" && typeof globalStorage != "undefined") 
        window.localStorage = globalStorage[location.hostname];
      this.localStorage = window.localStorage;
      // undefined localStorage if it doesn't already exist
      
      if (!this.localStorage)
        this.localStorage = {
          getItem: function(name){
            this.data = window.name ? $.evalJSON(window.name) : {};
            return $.toJSON(this.data[name] || (this.data[name] = {}));
          },
          setItem: function(name, data){
            this.data[name] = $.evalJSON(data);
            window.name = $.toJSON(this.data);
          },
          removeItem: function(name){
            delete this.data[name];
            window.name = $.toJSON(this.data);
          }
        };
        
      this.name = name || 'unnamed';
      this.data = this.get();
    },    
    // get item from localStorage
    get: function(){
      try {
        return $.evalJSON((this.localStorage.getItem(this.name) || '{}').toString());
      }
      catch (e) {
        this.options.clearable && this.set({});
      }
    },
    // set item to localStorage
    set: function(data){
      if (data) 
        this.data = data;
      this.timer && clearTimeout(this.timer);
      var self = this;
      this.timer = setTimeout(function(){
        if (self.size(true) > self.options.maximum * 1048576) 
          return;
        try {
          self.localStorage.setItem(self.name, $.toJSON(self.data));
        }
        catch (e) {
          self.options.clearable && self.set({});
        }
      }, this.options.delay)
    },
    // remove item
    remove: function(name){
      this.localStorage.removeItem(name || this.name);
    },
    // remove all items
    clear: function(){
      if (!this.localStorage.length) 
        window.name = '{}';
      else
        for (i = 0; i < this.localStorage.length; i++) 
          this.remove(this.localStorage.key(i));
    },
    // size of localStorage
    size: function(bytes){
      var data = $.toJSON(this.data).length;
    
      return bytes ? data : data > 1024 ? (function(){
        data = (data / 1024).round().toString();
        var reg = /(^[+-]?\d+)(\d{3})/;
        while (reg.test(data))
          data = data.replace(reg, '$1' + ',' + '$2');
        return data + 'kb';
      })() : data + 'bytes';
    }
  }
}

window.$R = $R = window.$R || {};
$.extend($R, {
  'localstorage': localstorage  
});

})(jQuery);


// helper By Browser
(function($){
function browser(lang, op) {
  lang = lang || 'ko';
  op = op || {};  

  browserExtend();
  
  var that = {};

  that.version = version;
  that.name = name;
  that.setText = setText;

  return that;

  function setText(box, op) {
    op.text = {'version' : version()};
    $(op.childs).each(function(i, className){
      var element = box.find('.' + className);
      element.html(op.text[className] || '');
      if (element.is('[tagName=A]')) element.attr('title', op.text[className]);    
    });
  }
  
  function browserExtend() {
    if(typeof $.browser.chrome != 'undefined'){
      return ;
    }
    
    var _browser = ''; //safari(safari || Chrome), opera, msie, mozilla    
    for (var name in $.browser) {
      if (typeof $.browser[name] == 'boolean' && $.browser[name]) _browser = name;         
    }
    
    var agent = navigator.userAgent;
    
    $.browser.chrome = false;
    if (_browser == 'safari' && agent.match(/chrome/i)) {// refer dojo.js
      $.browser.safari = false;
      $.browser.chrome = true;
      _browser = 'chrome';
    }
    
    $.browser.version = ({
      'safari' : agent.match(/Version[\/\s](\d+\.\d+)/),
      'opera'  : agent.match(/Version[\/\s](\d+\.\d+)/),
      'mozilla': agent.match(/Firefox[\/\s](\d+\.\d+)/),
      'chrome' : agent.match(/Chrome[\/\s](\d+\.\d+)/)
    }[_browser] || ['', $.browser.version])[1];
    
  }
  
  function name() {
    if (op.name) {// agent : view wait
      return {
        'InternetExplorer': 'msie',
        'Internet Explorer': 'msie',
        'Firefox': 'mozilla',
        'Safari': 'safari',
        'Chrome': 'chrome',
        'Opera': 'opera'
      }[op.name]
    }
    
    var _browser = ''; //safari, chrome, opera, msie, mozilla    
    for (var name in $.browser) {
      if (typeof $.browser[name] == 'boolean' && $.browser[name]) _browser = name;         
    }

    if (_browser.match(/msie/)) { // msie6 svc.chat.common.js
      _browser = 'msie';
    }

    return _browser;
  }
  
  function version() {
    if (op.version) {
      return op.name + '&nbsp' + op.version;
    }
    return {
      'msie'    : 'Internet Explorer',
      'mozilla' : 'Firefox',
      'safari'  : 'Safari',
      'chrome'  : 'Chrome',
      'opera'   : 'Opera'
    }[name()] + '&nbsp;' + $.browser.version;
  }
}

window.$R = $R = window.$R || {};
$.extend($R, {
  'browser': browser
});

})(jQuery);