/** 
AJAX : accept header 
**/

Kwo = {
 
  "registry": {},
  "Class": {},
  "Visitor": {},
  
  "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"]; },
  
  "setContext": function (key, value) {
    window["_context"][key] = value;
  },

  "callbacks": {},
  "scripts": {},

  "hasError": function(h) { return h["error"] >= 1; },

  "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 (Object.isString(arg)) { 
        arg = arg.toQueryParams();
        h.update(arg);
      }
      else if (typeof arg == "object") {
        if (Object.isArray(arg)) { 
          arg.each(function (item) {
            h.update(Kwo.mergeArgs(item));
          });
        }
        else if (Object.isElement(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.isElement(options["confirm"])) {
        msg = $(options["confirm"]).getAttribute("confirm");
      }
      else {
        msg = options["confirm"] == true ? "êtes vous sûr ?" : options["confirm"];
      }
      if (msg.length >= 2 && !confirm(msg.ucfirst())) { return false; }
    }

    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 false;
      params.update(tmp);
    }

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

    var opts = {
      "requestHeaders": {"X-KWO-Referer": window.location.href,
                         "X-KWO-Request": "exec"},
      "asynchronous": "async" in options ? options["async"] : true,
      "evalJS": false,
      "evalJSON": false,
      "parameters": params.toObject(),
      "onCreate": function() { 
        if (window.top.$("loading")) { window.top.$("loading").show(); }
        if ("toggle" in options) { $(options.toggle).toggle(); }
        if ("disable" in options && Object.isElement(args) && args.tagName.toUpperCase() == "FORM") { 
          $(args).disable();
        }
      },
      "onSuccess": function(t) { 
        var h = t.responseText.evalJSON();
        if (options["callback"] == true) {
          options["callback"] = Kwo.callback;
        }
        if (Kwo.hasError(h)) {
          if ("callback" in options) { 
            options["callback"].call(null, h); 
          }
          else { 
            Kwo.error(h); 
          }
        }
        else {
          if ("callback" in options) { 
            options["callback"].call(null, h); 
          }
          else { 
            eval(h["result"]); 
          }
          if ("reset" in options) {
            var f = Object.isElement(args) && args.tagName.toUpperCase() == "FORM"
                  ? $(args)
                  : $(args).up("form");
            if (f) f.reset();
          }
        }
      },
      "on404": function(t) { 
        Kwo.warn("Oops!\nAJAX Error : " + t.statusText + " was not found"); 
      },
      "onFailure": function(t) { 
        Kwo.warn("Oops!\nAJAX Failure [" + t.status + "] : " + t.statusText); 
      },
      "onException": function(t, e) { 
        Kwo.warn("Oops!\nAJAX 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, opts);

    return false;
  },


  "go": function(action, args, options) {
    var url = action;
    options = options || {};
    
    if (!Object.isString(action) && "result" in action && "callback_url" in action["result"]) {
      url = action["result"]["callback_url"];
    }

    if ("confirm" in options) { 
      var msg;
//      if ("object" == typeof options["confirm"] && "tagName" in options["confirm"]) {
      if (Object.isElement(options["confirm"])) {
        msg = $(options["confirm"]).getAttribute("confirm");
      }
      else {
        msg = options["confirm"] == true ? "OK ?" : options["confirm"];
      }
      if (msg.length >= 2 && !confirm(msg.ucfirst())) return ;
    }
    
    
    if (args !== undefined && args != null) {
      
      args = Kwo.mergeArgs(args);
      var raw = args.keys().join("") + args.values().join("");
      var max = "~".charCodeAt(0);
      for (var i = 0; i < raw.length; i++) {
        if (raw.charCodeAt(i) > max) {
          args.set("kie", "utf8");
          break ;
        }
      }
      url = action + "?" + args.toQueryString();
    }

    if ("target" in options) {
      if (options["target"] == "blank") {
        window.open(url);
      }
      else {
        $(options["target"]).src = url;
      }
      return ;
    }
    
    if ("popup" in options) {
      options["popup"] = "object" == typeof options["popup"] ? options["popup"] : {};
      if ("blank" in options["popup"]) {
        return window.open(url);
      }
      options["popup"]["width"] = options["popup"]["width"] || "400";
      options["popup"]["height"] = options["popup"]["height"] || "550";
      options["popup"]["name"] = options["popup"]["name"] || "_blank";
      return 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");
    }
    window.location.href = url;
      /* window.location.replace(url); */
    return false;
  },

  "anchor": function(name) {
    document.anchors.item(name).scrollIntoView();
    //document.anchors[name].focus();
    return false;
  },

  "callback": function(h) {
    if (Kwo.hasError(h)) {
      return Kwo.error(h); 
    }
    if ("callback_msg" in h["result"]) {
      if ("callback_container" in h["result"]) {
        $(h["result"]["callback_container"]).update(h["result"]["callback_msg"]);
      }
      else {
        Kwo.warn(h);
      }
    }
    if ("callback_url" in h["result"]) {
      if (h["result"]["callback_url"] == "reload") {
        Kwo.reload();
      }
      else {
        Kwo.go(h["result"]["callback_url"]);
      }
      return ;
    }
    if (!("callback_msg" in h["result"]) && !("callback_url" in h["result"])) {
//      Kwo.reload();
    }
  },

  "home": function(h) {
    window.location.href= "/"; 
  },

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

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

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

  "error": function(args) {
    if (typeof args == "object" && "result" in args && "msg" in args["result"]) {
      args = args["result"]["msg"];
    }
    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 (typeof args == "object" && "result" in args && "callback_msg" in args["result"]) {
      args = args["result"]["callback_msg"];
    }
    if (args instanceof Array) { 
      var out = "";
      args.each(function(item) {
        out += item + "\n";
      });
      alert(out);
    }
    else {
      alert(args.ucfirst()); 
    }
  },

  "load": function(src, callback, args) {
    var lib = null;
    if (src.indexOf("/") == -1) {
      lib = src;
      src = "/app/" + src + "/controller.js";
    }
    Kwo.scripts[src] = true;
    var script = new Element("script", {"type": "text/javascript", "src": src});
    if (lib != null && callback != undefined) {    
      document.observe("kwo:" + lib + ":loaded", function() { 
        callback.call(this, args); 
      });
    }
    $$("head")[0].insert(script);
  }

};

Kwo.Locale = {

  "onOpen": function (elt) {
    $("kwo-locales-box").toggle();
    var pos = $(elt).cumulativeOffset();
    $("kwo-locales-box").setStyle({"top": (pos[1] + $(elt).getHeight()) + "px",
                                   "left": pos[0] + "px"});
  },

  "onSet": function (locale, fallback) {
    $("kwo-locales-box").toggle();
    Kwo.exec("/sys/locale.set", {"locale": locale}, 
             {"callback": Kwo.Locale.onCallback.curry(fallback)});
  },

  "onCallback": function (fallback, h) {
    if (fallback == undefined) {
      var parts = window.location.pathname.substring(1).split("/", 1);
      if (parts.length != 1 || parts[0].length != 2) {
        Kwo.reload();
        return ;
      }
      window.location.href = window.location.href.replace(new RegExp("/" + parts[0] + "(/|$)"),
                                                          "/" + h["result"]["locale"] + "/");
      return ;
    }
    Kwo.go(fallback);
  }

};

Kwo.BirthDate = {
  "change": function (elt) {
    var input = $(elt).previous("INPUT"), date = {}, tmp;
    tmp = input;
    for (var i = 1; i <= 3; i++) {
      tmp = tmp.next("SELECT");
      if (tmp.className.indexOf("day") != -1) date["day"] = $F(tmp);
      else if (tmp.className.indexOf("month") != -1) date["month"] = $F(tmp);
      else date["year"] = $F(tmp);
    }
    input.value = date["year"] + "-" + date["month"] + "-" + date["day"];
  }
};

Kwo.Tag = {

  "view": function(tag) {
    Kwo.Search.results(tag, 0);
  }

};

Kwo.Tooltip = {

  "elt": null,

  "hide": function(anchor, id) {
    document.stopObserving("mousemove", Kwo.Tooltip.onMouseMove);
    Kwo.Tooltip.elt.hide();
  },

  "show": function(anchor, id) {
    anchor = $(anchor);
    Kwo.Tooltip.elt = id === undefined
                    ? anchor.previous(".kwo-tooltip")
                    : $(id);
    document.observe("mousemove", Kwo.Tooltip.onMouseMove);
    Kwo.Tooltip.elt.show();
  },

  "onMouseMove": function(e) {
    var dim = document.viewport.getDimensions();
    var pos = document.viewport.getScrollOffsets();
    var size = Kwo.Tooltip.elt.getDimensions();
    var top = (Event.pointerY(e) + 10);
    var left = (Event.pointerX(e) + 10);
    if (left + size["width"] > dim["width"] + pos["left"]) {
      left -= (left + size["width"]) - (dim["width"] + pos["left"]) + 5;
    }
    if (top + size["height"] > dim["height"] + pos["top"]) {
      top -= size["height"] + 20;
    }
    Kwo.Tooltip.elt.setStyle({"top": top + "px", "left": left + "px"});
  }

};

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 = this.cumulativeOffset();
        Kwo.Menu.opened.setStyle({"top": (pos.top + this.getHeight()) + "px",
                                  "left": pos.left + "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,
  "iframe": null,
  "range": null,
  "version": 0.9,
  "win": null,
  "Class": {},

  "initialize": function(name) {
    if (!("execCommand" in window.document)) return ;
    var actions = {"bold": false, "italic": false, "underline": false, 
                   "increasefontsize": false, "indent":true,"outdent":true, 
                   "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, "id": "_" + this.name, 
                              "class": "richtext"});
    this.iframe = iframe;
    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;
    }
    if (!Prototype.Browser.Gecko) {
      this.doc.designMode = "on"; 
    }
    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; }"
                   + "BLOCKQUOTE { border-left:2px solid #eee; padding-left:4px; margin-left:4px; }"
                   + "</style></head><body></body></html>");
    this.doc.close();
    if (Prototype.Browser.Gecko) {
      this.doc.designMode = "on"; 
    }
    if ($F(this.name).length >= 1) {
      this.doc.body.innerHTML = $F(this.name);
    }
   if (Prototype.Browser.Gecko || Prototype.Browser.WebKit) {
      this.doc.execCommand("styleWithCSS", false, false);
    }
    iframe.observe("mouseout", this.store.bindAsEventListener(this));
    iframe.observe("mouseover", this.init.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);
    };
  },
  
  "init": function() {
    if (this.doc.designMode != "on") {
      this.doc.designMode = "on";
    }
  },

  "store": function() {
    $(this.name).value = this.doc.body.innerHTML;
  },
  
  "exec": function(name, value) {
    if (name == "createlink") {
      if (value == false) {
        this.saveRange();
        new Kwo.Prompt({title: "Adresse du site ?", prefix: "http://"}, this.exec.bind(this).curry(name));
        return ;
      }
      if (!Object.isString(value) || value.legnth < 5) return ; 
      if (!value.toLowerCase().startsWith("http://") || !value.toLowerCase().startsWith("https://")) {
        value = "http://" + value;
      }
      this.win.focus();
      if (Prototype.Browser.IE && this.range) {
        this.range.select();
      }
      this.doc.execCommand(name, false, value);
    }
    else if (name == "insertimage") {
      if (value == false) {
        this.saveRange();
        new Kwo.FileDialog(this.exec.bind(this));
        return ;
      }
      this.insertHTML('<img src="/' + value + '" />');
    }
    else {
      this.win.focus();
      this.doc.execCommand(name, false, value);
    }
    if (Prototype.Browser.Gecko || Prototype.Browser.WebKit) { 
      this.win.getSelection().collapseToEnd();
    }
    this.store();
  },

  "saveRange": function() {
    if (Prototype.Browser.IE) {
      this.range = null;
      if (this.doc.selection.createRange().text.length >= 1) {
        this.range = this.doc.selection.createRange();
      }
    }
  },

  "insertHTML": function(content) {
    this.win.focus();
    if (Prototype.Browser.IE) {
      if (this.range === null) {
        // tester le parent de la selection pour voir si on est dans le bon doc
        this.range = this.doc.selection.createRange();
      }
      this.range.pasteHTML(content);
      this.range.collapse(false);
      this.range = null;
    }
    else {
      this.doc.execCommand("insertHTML", false, content);
    }
  }
 
});

Kwo.Dialog = Class.create({

  "bind": null,
  "width": null,
  "height": null,

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

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

      window.subsupport.appendChild(new Element("img", 
                                                {"src": "/app/sys/pix/close-dialog2.gif", 
                                                 "id": "close-dialog"})).observe("click", this.close);

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

      $("overlay").observe("click", this.close);
    }

    this.opts = opts;
    this.place();
    this.bind = this.place.bindAsEventListener(this);

    Event.observe(window, "resize", this.bind);
    Event.observe(window, "scroll", this.bind);

    Kwo.setDialog(this);

    this.name = "dialog";
    if (Prototype.Browser.IE && navigator.userAgent.indexOf("MSIE 6") > -1) {
      $$("SELECT").invoke("hide");
    }
    $("support").update();
    if (Object.isFunction(paint_method)) {
      paint_method.call(Kwo.getDialog(), args);
    }
    else if (!Object.isUndefined(paint_method)) {
      Kwo.exec(paint_method, args, {"async": true, "container": "support"});
    }
    $("overlay", "subsupport", "support").invoke("show");
  },

  "place": function () {
    var dimensions = document.viewport.getDimensions();
    var offsets = document.viewport.getScrollOffsets();

    var width = "width" in this.opts ? parseInt(this.opts["width"]) : 460;
    var height = "height" in this.opts ? parseInt(this.opts["height"]) : 300;

    var left = offsets.left + ((dimensions.width / 2) - (width / 2));
    var top = offsets.top + ((dimensions.height / 2) - (height / 2));

    if (top < 0) { top = 0; }
    if (left < 0) { left = 0; }

    top += 15;

    $("overlay").setStyle({"width": dimensions.width+"px", 
                           "height": dimensions.height+"px",
                           "left": offsets.left+"px",
                           "top": offsets.top+"px"});

    $("subsupport").setStyle({"width": width+"px",
                            "height": height+"px",
                            "left": left+"px",
                            "top": top+"px"});

    $("support").setStyle({"width": width+"px",
                           "height": height+"px"});

  },
  
  "apply": function(value) {
    if (this.callback === undefined) alert(value);
    else if (Object.isElement(this.callback) && $(this.callback)) this.callback.value = value;
    else this.callback(value);
    this.close();
  },

  "close": function() {
    $("support", "subsupport", "overlay").invoke("hide");
    if (Prototype.Browser.IE && navigator.userAgent.indexOf("MSIE 6") > -1) {
      $$("SELECT").invoke("show");
    }
//    $(document.body).setStyle({"overflowY": "auto"});
  }

});


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

  "initialize": function($super, callback, opts) {
    this.callback = callback;
    opts = opts || {}; 
    opts["width"] = 600;
    opts["height"] = 360;
    $super("/community/files.dialog", null, opts);
    Kwo.setDialog(this);
  },
  
  "onUploadCompleted": function(file_path) {
    if (this.opts["mode"] == "upload") {
      this.apply(file_path);
    }
    else {
      this.refresh();
    }
  },
  
  "refresh": function() {
    $("support").innerHTML = "";
    Kwo.exec("/community/files.dialog", null, 
             {"container": "support"});
  },

  "preview": function(path) {
    path = "/" + path;
    if (path.indexOf(".jpg") > 0 || path.indexOf(".jpeg") > 0 || 
        path.indexOf(".png") > 0 || path.indexOf(".gif") > 0) {
      $("thumb").hide();
      var img = new Image();
      img.onload = function() {
        var max = 230;
        $("thumb").style.display = "block";
        $("thumb").src = this.src;
        if (this.width <= max && this.height <= max) {
          $("thumb").width = this.width;
          $("thumb").height = this.height;
        }
        else if (this.width > max || this.height > max) {
          if (this.width > this.height) {
            $("thumb").width = max;
            $("thumb").height = Math.ceil(this.height * (max / this.width));
          }
          else {
            $("thumb").width = Math.ceil(this.width * (max / this.height));
            $("thumb").height = max;
          }
        } 
        $("thumb").show();
      };
      img.src = path;
    }
    else {
      $("thumb").hide();
    }
  },
  
  "apply": function(path) {
    if (Object.isUndefined(this.callback)) {
      return alert(path);
    }
    else if (Object.isElement(this.callback)) {
      if ("name_only" in this.opts) {
        path = path.basename();
      }
      $(this.callback).value = path;
    }
    else if (Object.isFunction(this.callback)) {
      this.callback("insertimage", path);
    }
    this.close();
  }

});

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

  "initialize": function($super, args) {
    this.args = args;
    $super(this.refresh, 
           {"item_key": args["item_key"]}, 
           {"height": 280});
    Kwo.setDialog(this);
  },
  
  "refresh": function(args) {
    Kwo.exec("/abuse/dialog", args, {"container": "support"});
  },

  "apply": function(args) {
    Kwo.exec("/abuse/add", args);
    $("abuse-button", "abuse-status").invoke("toggle"); 
    $("abuse-form").reset()
    return false;
  }

});

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

  "initialize": function($super, args, callback) {
    this.callback = callback;
    if (Object.isString(args)) {
      args = {"title": args};
    }
    $super(this.refresh, args, {"height": 150});
    Kwo.setDialog(this);
  },
  
  "refresh": function(args) {
    Kwo.exec("/sys/dialog.prompt", args, {"container": "support"});
  }

});

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

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

});

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

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

});

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

  "initialize": function($super, input, opts) {
    this.input = input;
    opts = opts || {};
    opts["width"] = 220;
    opts["height"] = 180;
    $super("/sys/dialog.colorpicker", null, opts);
    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;
    $super("/sys/dialog.geoloc", null, {"width": 640, "height":480});
    Kwo.setDialog(this);
  },

  "getPoint": function () {
    if ($(this.input).up("tr") && $(this.input).up("tr").down("input.back")) {
      return new Array($(this.input).up("tr").down("input.latitude").value, 
                       $(this.input).up("tr").down("input.longitude").value, 
                       $(this.input).up("tr").down("input.zoom").value);
    } else {
      if (this.input.value.match(",")) {
        return this.input.value.split(",");
      }
    }
    return false;
  },

  "setValue": function(value) {
    if ($(this.input).up("tr") && $(this.input).up("tr").down("input.back")) {
      var values = value.split(",");
      $(this.input).up("tr").down("input.latitude").value = values[0];
      $(this.input).up("tr").down("input.longitude").value = values[1];
      $(this.input).up("tr").down("input.zoom").value = values[2];
    } else {
      $(this.input).setValue(value);
    }
    this.close();
  }

});

var KwoMethods = {
  
  "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(); 
    }
  },
  
  "getCaretPosition": function(element) {
    if (element.createTextRange) {
      var range = document.selection.createRange().duplicate();
      range.moveEnd("character", element.value.length);
      return range.text.empty() 
           ? element.value.length
           : element.value.lastIndexOf(range.text);
    }
    return element.selectionStart;
  }
  
};

Element.addMethods(KwoMethods);

Kwo.Visitor.Currency = {

  "choose": function(arg) {
    $("kwo-currencies").toggle();
    var pos = $(arg).cumulativeOffset();
    $("kwo-currencies").setStyle({"top": (pos[1] + $(arg).getHeight()) + "px",
                                  "left": pos[0] + "px"});
  },

  "set": function(code) {
    Kwo.exec("/sys/currency.set", {"code": code}, {"callback": true});
  }

}

if (!Array.prototype.filter) {
  Array.prototype.filter = function(fun) {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();
    var res = new Array();
    var thisp = arguments[1];
    for (var i = 0; i < len; i++) {
      if (i in this) {
        var val = this[i]; 
        if (fun.call(thisp, val, i, this))
          res.push(val);
      }
    }
    return res;
  };
}

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);
  },
  
  "asInt": function() {
    if (this.length < 1) return 0;
    return parseInt(this);
  },
  
  "toggle": function() {
    return parseInt(this) == 1 ? "0" : "1";
  },

  "ucfirst": function() {
   return this.charAt(0).toUpperCase()+this.substring(1);
  },
  
  "basename": function() {
    return this.match(/[^\/\\]+$/);
  }
  
});


