/** 
AJAX : accept header 
**/

if (!Kwo) var Kwo = {};

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"]; },
  
  "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" == typeof options["confirm"] && 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 ; }
    }

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

    if ("container" in options) { 
      if (!$(options["container"])) { return alert('Oops! No Container (AJAX).'); }
      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 () { },
                                                 "requestHeaders": {"X-KWO-Referer": window.location.href, 
                                                                    "X-KWO-Request": "update"}});
                             }, timeout);
      return ;
    }

    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(); }
      },
      "onSuccess": function(t) { 
        var h = t.responseText.evalJSON();
        if (h["error"] >= 1) {
          if ("callback" in options) { 
            if (options["callback"] == true) {
              if ("msg" in h["result"]) alert(h["result"]["msg"]);
            }
            else {
              options["callback"].call(null, h); 
            }
          }
          else { 
            Kwo.warn("Oops!\n  " + h["result"]["msg"].join("\n  ")); 
          }
        }
        else {
          if ("callback" in options) { 
            if (options["callback"] == true) {
              if ("msg" in h["result"]) alert(h["result"]["msg"]);
              if ("url" in h["result"]) {
                if (h["result"]["url"] == "reload") Kwo.reload();
                else Kwo.go(h["result"]["url"]);
              }
            }
            else {
              options["callback"].call(null, h); 
            }
          }
          else { eval(h["result"]); }
          if ("reset" in options) {
            var f = $(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);
  },


  "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"] == 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"] || "570";
      options["popup"]["height"] = options["popup"]["height"] || "450";
      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;
  },

  "home": function() {
    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 (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 = script;
    document.body.appendChild(sc);
  }

};

Kwo.Share = {
  "sent": false,
  "send": function(elt) {
    if (Kwo.Share.sent === true) return ;
    Kwo.Share.sent = true;
    Kwo.exec("/share/notification.send", 
             elt, 
             {"toggle": "kwo-share-throbber", "reset": true});
  }
};

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

Kwo.Tooltip = {
  "hide": function(arg, id) {
    var elt = id === undefined ? $(arg).previous(".kwo-tooltip") : $(id);
    elt.hide();
  },

  "show": function(anchor, id) {
    anchor = $(anchor);
    var tooltip = id === undefined ? anchor.previous(".kwo-tooltip") : $(id);
    var anchor_pos = anchor.cumulativeOffset();
    var anchor_dim = anchor.getDimensions();
    var tooltip_dim = tooltip.getDimensions();
    var viewport = document.viewport.getDimensions();
    var viewportOffset = anchor.viewportOffset();
    var top, left;
    if (viewportOffset["top"] + tooltip_dim["height"] > viewport["height"]) {
      top = anchor_pos.top - tooltip_dim["height"] - 4 +10;// +10 pour que le curseur ne gene pas la lecture
    }
    else {
      top = anchor_pos.top + anchor_dim["height"] + 4 +10;
    }
    if (viewportOffset["left"] + tooltip_dim["width"] > viewport["width"]) {
      left = (anchor_pos.left + anchor_dim["width"]) - tooltip_dim["width"];
    }
    else {
      left = anchor_pos.left;
    }
    tooltip.setStyle({"top": top + "px", "left": left + "px"});
    tooltip.show();
  }
};

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

  "ChangeOnglet": function (active, nombre, tab_prefix, contenu_prefix) {
    for (var i=1; i < nombre + 1; i++) 
    {
        document.getElementById(contenu_prefix + i).style.display = 'none';
        document.getElementById(tab_prefix + i).className = '';
		document.getElementById(tab_prefix + i).style.borderBottom = '';
	}  
		document.getElementById(contenu_prefix+active).style.display = 'block';
		document.getElementById(tab_prefix+active).className = 'active';
		document.getElementById(tab_prefix+active).style.borderBottom = '1px solid #fff';
	},
  
  "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,
                   "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 || {}; 
    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 (typeof paint_method == "function") {
      paint_method.call(Kwo.getDialog(), args);
    }
    else if (paint_method != undefined) {
      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");
    }
  }

});


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);
  },
  
  "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 (this.callback === undefined) {
      return alert(path);
    }
    else if (typeof this.callback == "object" && "tagName" in this.callback) {
      if ("name_only" in this.opts) {
        path = path.basename();
      }
      $(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;
    $super(this.refresh, 
           {"model_id": args["model_id"], "record_id": args["record_id"]}, 
           {"height": 270});
    Kwo.setDialog(this);
  },
  
  "refresh": function(args) {
    Kwo.exec("/abuse/dialog", args, {"container": "support"});
  },

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

});

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

});

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

Kwo.Visitor.Locale = {
  "choose": function(arg) {
     $("kwo-locales-box").toggle();
    var pos = $(arg).cumulativeOffset();
    $("kwo-locales-box").setStyle({"top": (pos[1]+$(arg).getHeight())+"px",
                                   "left": pos[0]+"px"});
  },
  "set": function(locale, next) {
    Kwo.exec("/sys/visitor.set_lang", {"locale": locale, "next": next || ""});
  }
}

Kwo.Browser = {
  toggleTextSize: function() {
    Kwo.exec("/sys/visitor.set_text_size");
  },
  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);
  },
  
  "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(/[^\/\\]+$/);
  }
  
});



