var CookieAccessor = {} //Class.create();
CookieAccessor.cache = null;
CookieAccessor.browserIsOpera =  (navigator.userAgent.toLowerCase().indexOf("opera") != -1); 
CookieAccessor.get = function(key) {
  if (!this.cache) { 
    this.cache = {};
    var cookies = $A(document.cookie.split("; "));
    cookies.each(function(cookie) {
      var split_cookie = cookie.split("=");
      var _key = split_cookie[0];
      var _value = split_cookie[1];
      this.cache[_key] = _value;
    }.bind(this));
  }
  if (!this.cache[key]) { return null }

  var result = this.cache[key];
  if (this.browserIsOpera) { result = result.replace(/%22/g, '"'); }

  return result
}

var SwitchByCookie = Class.create();
SwitchByCookie.cookies_cache = {};

SwitchByCookie.prototype = {
  initialize: function(id, options) {
    this.options = Object.extend({
      }, options || {});

    this.patterns = [];
    this.defaultText = "";
  },

  add: function(conditions, text) {
    this.patterns.push([$H(conditions), text])
  },

  add_default: function(text) {
    this.defaultText = text;
  },

  // 登録されたパターンにすべてマッチしたものをレンダリングする
  // 最初にマッチした1パターンのみレンダリングを行う
  render: function(id) {
    for (var i = 0; i < this.patterns.length; i ++) {
      var pattern = this.patterns[i]
      var detect_condition = true;
      var conditions = pattern[0].toArray();

      for (var j = 0; j < conditions.length; j++) {
        var condition = conditions[j];
        var key = condition[0];
        var values = condition[1];
        if ((typeof values) == "string") { values = [values] }

        var cookie_value = CookieAccessor.get(key);
        var detect = false;

        for (var k = 0; k < values.length; k ++) {
          var value = values[k];
          if (value == cookie_value) { detect = true; break; }
        }

        if (!detect) { detect_condition = false; break; }
      }

      if (detect_condition) {
        $(id).innerHTML = pattern[1];
        return;
      }
    };
    $(id).innerHTML = this.defaultText;
  }
}

