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

var Kwo = {

  "registry": {  },

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

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

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

  "mergeArgs": function() {
    var h = new Hash({}), n = arguments.length, arg; 
    for (var i = 0; i < n; i++) {
      arg = arguments[i];
      if (arg === undefined || arg === null || arg === false || arg === true) {
        continue;
      }
      if (typeof arg == "string") { 
        arg = arg.toQueryParams();
        h.update(arg);
      }
      else if (typeof arg == "object") {
        if (arg instanceof Array) { 
          arg.each(function(item) {
            h.update(Kwo.mergeArgs(item));
          });
        }
        else if ("tagName" in arg) { 
          if (arg.tagName.toUpperCase() == "FORM") { 
            arg = $(arg).serialize(true); 
          }
          else if ($(arg)) { 
            if ("form" in arg && arg.form) {
              arg = Element.extend(arg.form).serialize(true);
            }
            else {
              var tmp = $(arg).up("form");
              arg = (tmp) ? tmp.serialize(true) : {};
            }
          }
          h.update(arg);
        }
        else {
          h.update(arg);
        }
      }
    }
    return h;
  },
  
  "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.mergeArgs(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.update(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.set("kof", ""); 
      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.toObject(),
                                                "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.toObject(),
      "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 {
            Kwo.warn("Oops!\n"+res["result"]);
          }
        }
        else {
          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);
  },


  "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.mergeArgs(args, {"kie": "utf8"}).toQueryString();
    }

    if ("target" in options) {
      if (options["target"] == "blank") {
        window.open(url);
      }
      else {
        $(options["target"]).src = url;
      }
      return ;
    }

    if ("popup" in options && 
        window.location.href.lastIndexOf("__popup") == -1) {
      if ("object" == typeof options.popup && "blank" in options.popup) {
        window.open(url);
        return;
      }
      options["popup"]["width"] = options["popup"]["width"] || "400";
      options["popup"]["height"] = options["popup"]["height"] || "550";
      options["popup"]["name"] = options["popup"]["name"] || "_blank";
      if (url.indexOf("?") == -1) { url = url+"?"; }
      else { url = url+"&"; }
      url = url+"__popup="+options["popup"]["name"];
      window.open(url, options["popup"]["name"],
                  "width="+options["popup"]["width"]+",height="+options["popup"]["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;
  },

  "anchor": function(name) {
    document.anchors[name].focus();
    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});
  }, 

  "error": function(args) {
    if (args instanceof Array) { 
      var out = "Oops!\n";
      args.each(function(item) {
        out += " - " + item + "\n";
      });
      alert(out);
    }
    else {
      alert(args.ucfirst()); 
    }
  },

  "warn": function(args) {
    if (args instanceof Array) { 
      var out = "";
      args.each(function(item) {
        out += item + "\n";
      });
      alert(out);
    }
    else {
      alert(args.ucfirst()); 
    }
  },

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

};

Kwo.Menu = {
  "opened": null,
  "binded": {},
  "timeout": null,
  "id": null,
  "bind": function() {
    $$(".bind-menu").each(function(item) {

      if (!$("menu-"+item.id)) return;

      item.observe("mouseover", function() {
        if (Kwo.Menu.id != null && Kwo.Menu.id != item.id) {
          $("menu-"+Kwo.Menu.id).hide();
        }
        Kwo.Menu.id = item.id;
        if (Kwo.Menu.timeout) {
          window.clearTimeout(Kwo.Menu.timeout);
        }
        Kwo.Menu.opened = $("menu-"+item.id);
        var pos = Position.cumulativeOffset(this);
        Kwo.Menu.opened.setStyle({top: (pos[1]+this.getHeight())+"px",
                                         left: pos[0]+"px"});
        if (!(Kwo.Menu.opened.id in Kwo.Menu.binded)) {
          Kwo.Menu.binded[Kwo.Menu.opened.id] = true;
          Kwo.Menu.opened.onmouseover = Kwo.Menu.over;
          Kwo.Menu.opened.onmouseout = Kwo.Menu.out;
        }
        Kwo.Menu.opened.show();
      });
      
      item.observe("mouseout", function() { 
        window.clearTimeout(Kwo.Menu.timeout);
        Kwo.Menu.timeout = setTimeout(function () { 
          Kwo.Menu.opened.hide(); 
        }, 1000);
      });
      
    });
  },

  "reset": function() {
    window.clearTimeout(Kwo.Menu.timeout); 
    if ($("menu-"+Kwo.Menu.id)) {
      $("menu-"+Kwo.Menu.id).hide();
    }
  },

  "out": function () { 
    window.clearTimeout(Kwo.Menu.timeout); 
    this.hide();
  },

  "over": function() {
    window.clearTimeout(Kwo.Menu.timeout); 
    this.show(); 
  }
};


Kwo.Editor = Class.create({

  "doc": null,
  "name": null,
  "range": null,
  "version": 0.9,
  "win": null,

  "initialize": function(name) {
    var actions = {"bold": false, "italic": false, "underline": false, "increasefontsize": false, 
                   "insertorderedlist":false, "insertunorderedlist":false, 
                   "createlink": false, "insertimage": false,
                   "removeformat": false};
    this.name = name;
        var dimensions = $(this.name).getDimensions();
    $(this.name).hide();
    var iframe = new Element("iframe", 
                             {"designmode": "on", "name": "_"+this.name, 
                              "class": "richtext"});
    iframe.setStyle({"width": dimensions.width+"px", "height": dimensions.height+"px"});

    $(this.name).insert({"after": iframe});
    if(Prototype.Browser.IE) {
      this.win = window.frames["_"+this.name];
      this.doc = this.win.document;
    }
    else {
      this.win = iframe.contentWindow;
      this.doc = iframe.contentDocument;
    }
    this.doc.open("text/html");
    this.doc.write("<html><head><style>"
                   +"BODY { background:"+$(this.name).getStyle("background-color")+"; "
                   +"       border:0; margin:0; color:#777; padding:0 4px; }"
                   +"</style></head><body>"+$F(this.name)+"</body></html>");
    this.doc.close();
    if (this.doc.designMode != "on") {
      this.doc.designMode = "on"; 
    }
    if (Prototype.Browser.Gecko || Prototype.Browser.WebKit) {
      this.doc.execCommand("styleWithCSS", false, false);
    }
    iframe.observe("mouseout", this.store.bindAsEventListener(this));
    var toolbar = new Element("div", {"class": "kwo-toolbar"}).setStyle({"width": dimensions.width+"px"});
    $(this.name).insert({"after": toolbar});
    for (key in actions) {
      if ((Prototype.Browser.IE ||  Prototype.Browser.WebKit) && 
          key == "increasefontsize") continue ;
      var a = new Element("img", {"src": "/app/sys/pix/editor/"+key+".png"});
      a.observe("click", this.exec.bind(this, key, actions[key]));
      toolbar.insert(a);
    };
    this.win.focus();
  },
  
  "store": function() {
    $(this.name).value = this.doc.body.innerHTML;
  },
  
  "exec": function(name, value) {
    this.win.focus();
    if (name == "createlink") {
      var url = (value != false) ? value : prompt("Adresse du site ?", "http://");
      if (url == null) return ; 
      this.doc.execCommand(name, false, url);
    }
    else if (name == "insertimage") {
      if (value == false) {
        if(Prototype.Browser.IE) { 
          this.range = this.doc.selection.createRange();
          if (this.range.boundingLeft <= 0) { return alert("Oops(1)!"); }
        }
        new Kwo.FileDialog(this.exec.bind(this));
        return ;
      }
      this.insertHTML('<img src="/'+value+'" />');
    }
    else {
      this.doc.execCommand(name, false, value);
    }
    if (Prototype.Browser.Gecko || Prototype.Browser.WebKit) { 
      this.win.getSelection().collapseToEnd();
    }
    this.store();
  },

  "insertHTML": function(content) {
    if (Prototype.Browser.IE) {
      if (this.range < 0) { return alert('Oops(2)!'); }
      this.range.pasteHTML(content);
      this.range.collapse(false);
      this.range = null;
    }
    else {
      this.doc.execCommand("insertHTML", false, content);
    }
  }
 
});

Kwo.Dialog = Class.create({

  "initialize": function(paint_method, args, opts) {
    opts = opts || {}; 
    if (window.overlay === undefined) {
      window.overlay = document.body.appendChild(new Element("div", {"id": "overlay"}).setStyle({
        "display": "none", "opacity": "0.1"}));

      window._support = document.body.appendChild(new Element("div", {"id": "ssupport"}).setStyle({
        "display": "none"}));

      var t = window._support.appendChild(new Element("div", {"id": "dialog-title"}));
      //t.update('hello');
      t.appendChild(new Element("img", {"src": "/app/sys/pix/close-dialog.gif", "id": "close-dialog"})).observe("click", this.close);
      t.appendChild(new Element("div")).innerHTML = this._title;

      window.support = window._support.appendChild(new Element("div", {"id": "support"}).setStyle({
        "display": "none"}));

      $("overlay").observe("click", this.close);
    }
    var sizes = getPageSize();
    $("overlay").setStyle({"height": sizes[1]+"px", "width": sizes[0]+"px"}); 
    var width = ("width" in opts) ? opts["width"] : "400";
    var height = ("height" in opts) ? opts["height"] : "300";
    var offsets = document.viewport.getScrollOffsets();
    $("ssupport").setStyle({"top": (offsets.top + (sizes[3] / 10))+"px",
                            "left": (offsets.left + (sizes[2] - width) / 2)+"px",
                            "width": (width)+"px",
                            "height": (height+22)+"px"});
    $("support").setStyle({"width": width+"px",
                            "height": height+"px"});
    Kwo.setDialog(this);
    this.name = "dialog";
    $("support").update('<div style="text-align:center;"><img src="/app/sys/pix/throbber.gif"/></div>');
    $("overlay", "ssupport", "support").invoke("show");
//    $("ssupport").show();
//    $("support").show();
    if (typeof paint_method == "function") {
      paint_method.call(Kwo.getDialog(), args);
    }
    else if (paint_method != undefined) {
      Kwo.exec(paint_method, args, {"container": "support"});
    }
  },

  "setTitle": function(s) {
    this._title = s;
  },
  
  "close": function() {
    $("support", "ssupport", "overlay").invoke("hide");
//    $("support").hide();
//    $("overlay").hide(); 
  }

});


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

  "initialize": function($super, callback, opts) {
    this.callback = callback;
    opts = opts || {}; 
    opts["width"] = 600;
    opts["height"] = 360;
    this.setTitle("");
    $super("/community/user.files", null, opts);
    Kwo.setDialog(this);
  },
  
  "refresh": function() {
    Kwo.exec("/community/user.files", null, {"container": "support"});
  },

  "set": function(path) {
    if (this.callback === undefined) {
      return alert(path);
    }
    else if (typeof this.callback == "object" && "tagName" in this.callback) {
      $(this.callback).value = path
    }
    else if (typeof this.callback == "function") {
      this.callback("insertimage", path);
    }
    this.close();
  }

});

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

  "initialize": function($super, args) {
    this.args = args;
    this.setTitle("");
    $super(this.refresh, 
           {"model_id": args['model_id'], 'record_id': args['record_id']}, 
           {"height": 210});
    Kwo.setDialog(this);
  },
  
  "refresh": function(args) {
    Kwo.exec("/abuse/compose", args, {"container": "support"});
  },

  "send": function(args) {
    Kwo.exec("/abuse/add", args);
  }

});

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

  "initialize": function($super, input) {
    this.input = input;
    this.setTitle("");
    $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;
    this.setTitle("");
    $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;
    this.setTitle("color");
    $super("/sys/dialog.colorpicker", null, {"width": 220, "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();
  }

});

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

  "initialize": function($super, input, opts) {
    this.input = input;
    this.setTitle("geo");
    $super("/sys/dialog.geoloc", null, {"width": 640, "height":480});
    Kwo.setDialog(this);
  },

  "getPoint": function () {
    if (this.input.value.match(',')) {
      return this.input.value.split(',');
    }
    return false;
  },

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

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();

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);
 },

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

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

});


