/** 
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": {},

  "F": function(model) {
    model = model.toLowerCase();
    if (model in Kwo.registry) return Kwo.registry[model];
    Kwo.registry[model] = new Kwo.Class.Obj(model);
    return Kwo.registry[model];
  }, 

  "hasError": function(res) { 
    if (Object.isUndefined(res)) return false;
    return res["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 (Object.isElement(args) && args.tagName.toUpperCase() == "FORM" && $(args).hasClassName("kwo-disabled")) {
      return ;
    }

    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).addClassName("kwo-disabled");
          $(args).disable();
        }
      },
      "onSuccess": function(t) { 
        var h = t.responseText.evalJSON();
        if (options["callback"] == true) {
          if ((action.indexOf("/") == -1 && window.location.href.indexOf("/account/") != -1) || 
              action.indexOf("/account") != -1) {
            options["callback"] = Kwo.Account.refresh;
          }
          else {
            options["callback"] = Kwo.callback;
          }
        }
        if (Kwo.hasError(h)) {
          if ("callback" in options && !Object.isElement(options["callback"])) {
            options["callback"].call(null, h); 
          }
          else { 
            Kwo.error(h); 
          }
        }
        else {
          if ("callback" in options) { 
            if (Object.isElement(options["callback"]) && "onclick" in options["callback"]) {
              options["callback"].onclick();
            }
            else {
              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(); }
        if ("disable" in options && Object.isElement(args) && args.tagName.toUpperCase() == "FORM") {
          $(args).removeClassName("kwo-disabled");
          $(args).enable();
        }
      }
    };
    
    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.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() {
    window.location.reload(); 
  },

  "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()); 
    }
    return false;
  },

  "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()); 
    }
    return false;
  },

  "load": function(src, callback, args) {
    var lib = null;
    if (src.indexOf("/") == -1) {
      lib = src;
      src = "/app/" + src + "/controller.js";
    }
    var script = new Element("script", 
                            {"type": "text/javascript", 
                             "src": src});
    if (!Object.isUndefined(callback) && Kwo.scripts[src] != true) {
      if (!Object.isUndefined(args)) {
        callback = callback.curry(args);
      }
      if (Prototype.Browser.IE) {
        script.onreadystatechange = function() {
	  /loaded|complete/.test(script.readyState) && callback();
        }
      }
      else {
        script.onload = callback;
      }
      Kwo.scripts[src] = true;
    }
    $$("head")[0].insert(script);
  }

};