
var Kwo = {

  "registry": {  },

  "init": function() {
    Object.extend(Kwo.obj.prototype, {"scheme": _scheme, 
                                      "extension": _extension, 
                                      "action": _action, 
                                      "root": "/"+_scheme+"/"+_extension});
  },

  "getDialog": function () { return Kwo._dialog; },
  "setDialog": function(o) { Kwo._dialog = o; return Kwo._dialog; },

  "getEditor": function () { return Kwo._editor; },
  "setEditor": function(o) { Kwo._editor = o; return Kwo._editor; },

  "toHash": function() {
    var ret = $H({}), n = arguments.length, arg;
    for (var i = 0; i < n; i++) {
      arg = arguments[i];
      if (arg === undefined || arg === null) {
        continue;
      }
      if ("string" == typeof arg) { 
        arg = arg.toQueryParams(); 
      }
      else if (typeof arg == "object" && arg instanceof Array) { 
        arg.each(function(item) {
          ret.merge(Kwo.toHash(item));
        });
      }
      else if ("object" == typeof arg && "tagName" in arg) { 
          if (arg.tagName == "FORM") { 
            arg = $(arg).serialize(true); 
          }
          else if ($(arg)) { 
            if ("form" in arg) {
              arg = Element.extend(arg.form).serialize(true);
            }
            else {
              var tmp = $(arg).up("form");
              if (tmp) arg = tmp.serialize(true);
            }
          }
      }
      ret.merge(arg);
    }
    return ret;
  },

  "exec": function (action, args, options) {
    options = options || {};

    if ("confirm" in options) { 
      var msg;
      if ("object" == typeof options["confirm"] && "tagName" in options["confirm"]) {
        msg = $(options["confirm"]).getAttribute("confirm");
      }
      else {
        msg = options["confirm"];
      }
      if (msg.length >= 2 && !confirm(msg.ucfirst())) { return; }
    }

    var params = Kwo.toHash(args, {__token: Math.random()});
    
    if ("prompt" in options) {
      var tmp = {}; 
      tmp[options["prompt"]["key"]] = prompt(options["prompt"]["msg"].ucfirst(), 
                                             options["prompt"]["default"] || "");
      if (tmp[options["prompt"]["key"]] == null) return ;
      //      var tmp = {}; tmp[options["prompt"]["key"]] = p;
      params.merge(tmp);
    }

    if ("container" in options) {
      if (!$(options["container"])) { alert('Oops! No Container (AJAX).'); }
      var timeout = 0;
      if ($($(options["container"]).parentNode).hasClassName("deck")) {
        $(options["container"]).parentNode.raise(options["container"]);
      }
      params["of"] = "null"; // output format
      if ("signal" in options) {
        $(options["container"]).update('<img src="/app/sys/pix/throbber-big.gif">');
        timeout = 300;
      }
      setTimeout(function() { new Ajax.Updater(options["container"], 
                                               action, 
                                               {"parameters": params,
                                                "evalScripts": true,
                                                "onComplete": function() { },
                                                "requestHeaders": {"X-KWO-Referer": window.location.href, 
                                                                   "X-KWO-Request": "update"}});
                             }, timeout);
      return ;
    }

    if (!("async" in options)) options.async = true;

    var opt = {
      "requestHeaders": {"X-KWO-Referer": window.location.href, "X-KWO-Request": "exec"},
      "asynchronous": options.async,
      "parameters": params,
      "onCreate": function() { 
        if (window.top.$("loading")) { window.top.$("loading").show(); }
        if ("toggle" in options) { $(options.toggle).toggle(); }
      },
      "onSuccess": function(t) {
        var res = t.responseText.evalJSON(); 
        if (res["error"] == 1) {
          if ("context" in options) {
            Kwo.Community.Account.setMessage(res["result"]);
          }
          else if ("goal" in options) {
            alert(t.responseText);
            return res;
          }
          else {
            Kwo.warn("Oops!\n"+res["result"]);
          }
        }
        else {
          if ("goal" in options) {
            return false;
          }
          eval(res["result"]);
          if ("reset" in options) {
            var f = $(args).up("form");
            if (f) f.reset();
          }
        }
      },
      "on404": function(t) { 
        Kwo.warn("AJAX 404 : "+t.statusText+" was not found"); 
      },
      "onFailure": function(t) { 
        Kwo.warn("AJAX Failure ["+t.status+"] : "+t.statusText); 
      },
      "onException": function(t, e) { 
        Kwo.warn("AJAX Exception ["+e.name+"] : "+e.message); 
      },
      "onComplete": function(t) {
        if (window.top.$("loading")) { window.top.$("loading").hide(); }
        if ("toggle" in options) { $(options.toggle).toggle(); }
      }
    };
    new Ajax.Request(action, opt);
  },

  "get": function(action, args) {
    return Kwo.exec(action, args, {"goal": "get", "async": false});
  },

  "go": function(action, args, options) {
    var url = action;
    options = options || {};
    
    if ("confirm" in options) { 
      var msg;
      if ("object" == typeof options["confirm"] && "tagName" in options["confirm"]) {
        msg = $(options["confirm"]).getAttribute("confirm");
      }
      else {
        msg = options["confirm"];
      }
      if (msg.length >= 2 && !confirm(msg.ucfirst())) { return; }
    }


    if (args !== undefined && args != null) {
       url = action+"?"+Kwo.toHash(args, {"ie": "utf8"}).toQueryString();
    }

    if ("open_right_flag" in options && options.open_right_flag == 1) {
      _right_iframe.location = url;
      return ; 
    }

    if ("target" in options) {
      if (options["target"] == "blank") {
        window.open(url);
      }
      else {
        $(options["target"]).src = url;
      }
      return ;
    }
    
    /*    if ("dialog" in options) {
      Kwo.d = new Kwo.Dialog("toto");
      return;
    }*/

    if ("popup" in options && 
        window.location.href.lastIndexOf("__popup") == -1) {
          if ("object" == typeof options.popup && "blank" in options.popup) {
            window.open(url);
            return;
          }
          var width = window._scheme ? "780" : "400";
          var height = "550";
          var popup_name = "_blank";
          if (url.indexOf("?") == -1) { url = url+"?"; }
          else { url = url+"&"; }
          url = url+"__popup="+popup_name;
          window.open(url, popup_name,
                      "width="+width+",height="+height+",directories=no,"+
                      "status=no,menubar=no,scrollbars=yes,"+
                      "resizable=no,copyhistory=no,hotkeys=no,"+
                      "toolbar=no,location=no");
          return;
        }
    else {
      window.location.assign(url); 
    }
    return false;
  },

  "home": function() {
    window.location.assign("/"); 
  },

  "namespace": function(name) {
    Kwo[name] = {};
  },

  "reload": function(action) {
    window.location.reload(); 
  },

  "text": function(code) {
    Kwo.go("/sys/text.view", {"code": code}, {"popup": true});
  }, 

  "warn": function(msg) {
    alert(msg.ucfirst()); 
  },

  "loadjs": function(script) {
    var sc = document.createElement("script");
    sc.type = "text/javascript";
    sc.src = "/app/"+script;
    document.getElementsByTagName("head")[0].appendChild(sc); 
  }
};

Event.observe(window, "load", function () {
  if ("obj" in Kwo) Kwo.init();
  if ("_init" in Kwo) Kwo._init();
});

Element.Methods.printZone = function(element) {
  var id = "print_zone";
  if (!top.$(id)) {
    var frm = window.top.document.createElement("iframe");
    frm.setAttribute("id", id);
    frm.setAttribute("name", id);
    frm.style.visibility = "hidden";
    window.top.document.getElementsByTagName("body")[0].appendChild(frm);
    window.top.frames[id].document.open("text/html");
    window.top.frames[id].document.writeln('<html><head>'+
                                           '<link href="/back/sys/ui.css" rel="stylesheet" type="text/css" />'+
                                           '</head><body></body></html>');
    window.top.frames[id].document.close();
    window.top.$(id).setStyle({"height": "1px", "width": "1px"});     
  }
  window.top.frames[id].onload = function() {
    window.top.frames[id].document.body.innerHTML = $(element).innerHTML;
    window.top.frames[id].focus();
    window.top.frames[id].print(); 
  }
}
Element.addMethods();

Kwo.Dialog = Class.create({

  "initialize": function(method, args, opts) {
    opts = opts || {};
    if (window.overlay === undefined) {
      window.overlay = window.document.createElement("div");
      window.overlay.setAttribute("id", "overlay");
      window.overlay.style.display = "none";
      window.overlay.onclick = this.close;
      window.document.getElementsByTagName("body")[0].appendChild(window.overlay);
      window.$("overlay").setOpacity(0.3);
      window.support = window.document.createElement("div");
      window.support.setAttribute("id", "support");
      window.support.style.display = "none";
      window.document.getElementsByTagName("body")[0].appendChild(window.support);
    }
    var size_arr = getPageSize();
    window.$("overlay").setStyle({"height": size_arr[1]+"px", "width": size_arr[0]+"px"}); 
    var width = ("width" in opts) ? opts["width"] : "400";
    var height = ("height" in opts) ? opts["height"] : "300";
    window.$("support").setStyle({"top": (document.viewport.getScrollOffsets().top + (size_arr[3] / 10))+"px",
                                  "left": (document.viewport.getScrollOffsets().left + (size_arr[2] - width) / 2)+"px",
                                  "width": width+"px",
                                  "height": height+"px"});
    Kwo.setDialog(this);
    this.name = "dialog";
    window.$("support").update('<div style="text-align:center;"><img src="/app/sys/pix/throbber.gif"/></div>');
    window.$("overlay").show();
    window.$("support").show();
    if (method === undefined) {
      
    }
    else if (typeof method == "function") {
      method.call(Kwo.getDialog(), args);
    }
    else {
      Kwo.exec(method, args, {"container": "support"});
    }
  },
  
  "close": function() {
    window.$("support").hide();
    window.$("overlay").hide(); 
  }

});


Kwo.Datepicker = Class.create(Kwo.Dialog, {

  "initialize": function($super, input) {
    this.input = input;
    $super(this.refresh, {"date": $F(input)}, {"height":210});
    Kwo.setDialog(this);
  },
  
  "refresh": function(args) {
    Kwo.exec("/sys/dialog.datepicker", args, {"container": "support"});
  },

  "setValue": function(date) {
    $(this.input).setValue(date);
    this.close();
  }

});

Kwo.Datetimepicker = Class.create(Kwo.Dialog, {

  "initialize": function($super, input) {
    this.input = input;
    $super(this.refresh, {"datetime": $F(input)}, {"height":230});
    Kwo.setDialog(this);
  },
  
  "refresh": function(args) {
    Kwo.exec("/sys/dialog.datetimepicker", args, {"container": "support"});
  },

  "setValue": function(date) {
    $(this.input).setValue(date);
    this.close();
  }

});

Kwo.Colorpicker = Class.create(Kwo.Dialog, {

  "initialize": function($super, input, opts) {
    this.opts = opts || {};
    this.input = input;
    $super("/sys/dialog.colorpicker", null, {"width": 230, "height":180});
    Kwo.setDialog(this);
  },
  
  "put": function(value) {
    if ("goal" in this.opts) {
      if (this.opts["goal"] == "bgcolor") {
        Kwo.getEditor().setBgColor("#"+value);
      }
      else {
        Kwo.getEditor().setFgColor("#"+value);
      }
    }
    else {
      $(this.input).setValue(value);
    }
    this.close();
  }

});


function getPageSize(){
  
  var xScroll, yScroll;
  if (window.innerHeight !== undefined && window.scrollMaxY !== undefined) {	
    //    xScroll = document.body.scrollWidth;
    xScroll = window.innerWidth + window.scrollMaxX;
    yScroll = window.innerHeight + window.scrollMaxY;
  } 
  else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
    xScroll = document.body.scrollWidth;
    yScroll = document.body.scrollHeight;
  } 
  else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
    xScroll = document.body.offsetWidth;
    yScroll = document.body.offsetHeight;
  }
  
  var windowWidth, windowHeight;
  if (self.innerHeight) {	// all except Explorer
    windowWidth = self.innerWidth;
    windowHeight = self.innerHeight;
  } 
  else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
    windowWidth = document.documentElement.clientWidth;
    windowHeight = document.documentElement.clientHeight;
  } 
  else if (document.body) { // other Explorers
    windowWidth = document.body.clientWidth;
    windowHeight = document.body.clientHeight;
  }	
  
  // for small pages with total height less then height of the viewport
  if(yScroll < windowHeight) {
    pageHeight = windowHeight;
  } 
  else { 
    pageHeight = yScroll;
  }
  
  // for small pages with total width less then width of the viewport
  if(xScroll < windowWidth){	
    pageWidth = windowWidth;
  } 
  else {
    pageWidth = xScroll;
  }
  // page : contient le scroll
  arrayPageSize = new Array(pageWidth, pageHeight, windowWidth, windowHeight) ;
  return arrayPageSize;
}

Kwo.Widget = {};

Kwo.Browser = {
  toggleTextSize: function() {
    //Kwo.openPopup();
    Kwo.exec("/sys/visitor.set_text_size");
  },
  setLang: function(lang_id) {
    Kwo.exec("/sys/visitor.set_lang", {"lang_id": lang_id});
  },
  setLocation: function(location_code) {
    Kwo.exec("/sys/visitor.set_location", {"location_code": location_code});
  }
}


Object.extend(String.prototype, { 

  "preg_match": function(pattern, option) {
    if (option === undefined) option = "gi";
    return this.match(new RegExp(pattern, option));
  },

 "preg_replace": function(pattern, replacement, option) {
   if (option === undefined) option = "gi";
   return this.replace(new RegExp(pattern, option), replacement);
 },

 "between": function(min, max) { 
   var n = parseInt(this);
   return (n > min && n < max);
 },

 "toInt": function() {
   return parseInt(this);
 },

 "ucfirst": function() {
   return this.charAt(0).toUpperCase() + this.substring(1);
 }

});


