


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

  "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 ("object" == typeof arg && "tagName" in arg) { 
          if (arg.tagName == "FORM") { 
            arg = $(arg).serialize(true); 
          }
          else if ($(arg)) { 
            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 && $(options["container"])) {
      if ($($(options["container"]).parentNode).hasClassName("deck")) {
        $(options["container"]).parentNode.raise(options["container"]);
      }
      params["of"] = "null"; // output format
      new Ajax.Updater(options["container"], 
                       action, 
                       {"parameters": params, 
                        "requestHeaders": {"X-KWO-Referer": window.location.href, 
                                           "X-KWO-Request": "update"}
                       });
      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(); 
        eval(res["result"]);
        if (res["error"] != 1) {
          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, options) {
    alert("to implement");
  },

  "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("/"); 
  },
  
  //FIXME KG 2010-05-25
  "step": function(niv) {
    switch(niv) {
		case 1:
			Kwo.go("/sys/visitor.signin");
		break;
				
		case 2:
		case 3:
		case 4:
		case 5:
			Kwo.go("/sys/visitor.steps", {"step": niv});
		break;
		
		default:
			Kwo.go("/sys/visitor.steps", {"step": 2});
		break;	
	}
  },
  //

  "namespace": function(name) {
  },

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

  "update": function(action, args, container) {
    //    container = container || top.$("container");
    //    new Ajax.Updater(container, action, {"parameters": Kwo.toHash(args)});
    alert('Kwo.update() is deprecated');
  },

  "openMessage": function(code) {
    Kwo.go("/sys/msg.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 = "/pub/ext/"+script;
    document.getElementsByTagName("head")[0].appendChild(sc); 
  }
};

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

Kwo.Dialog.prototype = {

  initialize: function(method, args, options) {
    if (top.overlay === undefined) {
      top.overlay = top.document.createElement("div");
      top.overlay.setAttribute("id", "overlay");
      top.overlay.style.display = "none";
      top.overlay.onclick = function() { 
        top.$("support").hide(); 
        top.$("overlay").hide(); 
      }
      top.document.getElementsByTagName("body")[0].appendChild(top.overlay);
      top.$("overlay").setOpacity(0.1);
      // ---------------
      top.support = top.document.createElement("div");
      top.support.setAttribute("id", "support");
      top.support.style.display = "none";
      top.document.getElementsByTagName("body")[0].appendChild(top.support);
    }
    var size_arr = getPageSize();
    top.$("overlay").setStyle({"height": size_arr[1]+"px", "width": size_arr[0]+"px"}); 
    top.$("overlay").show();

    if (true) {
      var scroll_arr = getPageScroll();
      var sTop = scroll_arr[1] + (size_arr[3] / 10);
      top.$("support").setStyle({"top": sTop+"px"});
      top.$("support").innerHTML = "coucou";
      //      Kwo.update(top.$("support"), "/back/sys/calendar");
      top.$("support").show();
    }
    //    alert(size_arr[0]+"-"+ size_arr[1]+"-"+ size_arr[2]+"-"+ size_arr[3]);
    //    alert(scroll_arr[1]);
  }

}

function getPageScroll(){

  var yScroll;
  
  if (self.pageYOffset) {
    yScroll = self.pageYOffset;
  } 
  else if (parent.document.documentElement && 
           parent.document.documentElement.scrollTop) {	 // Explorer 6 Strict
    yScroll = parent.document.documentElement.scrollTop;
  } 
  else if (parent.document.body) { // all other Explorers
    yScroll = parent.document.body.scrollTop;
  }
  
  arrayPageScroll = new Array("", yScroll);
  return arrayPageScroll;
}

function getPageSize(){
  
  var xScroll, yScroll;
  
  if (top.window.innerHeight && top.window.scrollMaxY) {	
    xScroll = top.document.body.scrollWidth;
    yScroll = top.window.innerHeight + top.window.scrollMaxY;
  } 
  else if (top.document.body.scrollHeight > top.document.body.offsetHeight){ // all but Explorer Mac
    xScroll = top.document.body.scrollWidth;
    yScroll = top.document.body.scrollHeight;
  } 
  else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
    xScroll = top.document.body.offsetWidth;
    yScroll = top.document.body.offsetHeight;
  }
  
  var windowWidth, windowHeight;
  if (self.innerHeight) {	// all except Explorer
    windowWidth = self.innerWidth;
    windowHeight = self.innerHeight;
  } 
  else if (top.document.documentElement && top.document.documentElement.clientHeight) { // Explorer 6 Strict Mode
    windowWidth = top.document.documentElement.clientWidth;
    windowHeight = top.document.documentElement.clientHeight;
  } 
  else if (top.document.body) { // other Explorers
    windowWidth = top.document.body.clientWidth;
    windowHeight = top.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;
  }
  
  arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) ;
  return arrayPageSize;
}

function minMax(id) {	
	if($(id).style.display == 'none') {
		$(id).show();
	} else {
		$(id).hide();
	}
}

function minMaxIco(id, idIco) {
	if($(id).style.display == 'none') {
		$(id).show();
		$(idIco + '_max').hide();
		$(idIco + '_min').show();
	} else {
		$(id).hide();
		$(idIco + '_min').hide();
		$(idIco + '_max').show();
	}	
}


Kwo.Widget = {};

Kwo.User = {

  "forgotPassword": function() {
    Kwo.go("/sys/visitor.forgot_password");
  },

  "login": function(args) {
    Kwo.exec("/sys/user.auth", args);
  },

  "signin": function(args) {
    if ($("terms_of_use") && !$("terms_of_use").checked) {
      return Kwo.warn("Veuillez accepter les CGU / Please accept terms of use.");
    }
    Kwo.exec("/sys/user.auth", args);
  },

  "logoff": function(args) {
    Kwo.exec("/sys/user.logoff", null, {"confirm": args});
  },

  "sendPassword": function(args) {
    Kwo.exec("/sys/visitor.send_password", args);
    if ($("forget_area")) {
      $("forget_area").toggle();
      if ($("login")) $("login").focus();
    }
  },

  "signup": function () {
    Kwo.go("/sys/visitor.signin");
  },

  "updatePassword": function (args) {
    Kwo.exec("/sys/visitor.update_password", args);
  },

  "changePassword": function(args) {
    Kwo.exec("/sys/user.change_password", args, {"toggle": "panel_throbber", "reset": true});
  },

  "changeEmail": function(args) {
    Kwo.exec("/sys/user.change_email", args, {"toggle": "panel_throbber", "reset": true});
  },

  "version": 1
}

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

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

});

/*String.prototype.preg_replace = function(reg_exp, replace_str, opts) {
  if (typeof opts == "undefined") opts = "gi";
  return this.replace(new RegExp(reg_exp, opts), replace_str);
}

String.prototype.between = function(min, max) { 
  var n = parseInt(this);
  return (n > min && n < max);
}

String.prototype.toInt = function() {
  return parseInt(this);
}

String.prototype.ucfirst = function() {
  return this.charAt(0).toUpperCase() + this.substring(1);
}*/

/*String.prototype.utf8decode = function() {
  var string = "";
  var i = 0;
  var c = c1 = c2 = 0;
  var utftext = this;
  while ( i < utftext.length ) {
    c = utftext.charCodeAt(i);
    if (c < 128) {
      string += String.fromCharCode(c);
      i++;
    }
    else if((c > 191) && (c < 224)) {
      c2 = utftext.charCodeAt(i+1);
      string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
      i += 2;
    }
    else {
      c2 = utftext.charCodeAt(i+1);
      c3 = utftext.charCodeAt(i+2);
      string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
      i += 3;
    }
  }
  return string;
}*/

/*Ajax.Responders.register({
        onCreate: function() {
                if($("notification") && Ajax.activeRequestCount> 0)
                        Effect.Appear("notification",{duration: 0.25, queue: "end"});
        },
        onComplete: function() {
                if($("notification") && Ajax.activeRequestCount == 0)
                        Effect.Fade("notification",{duration: 0.25, queue: "end"});
        }
});*/


/*

db du genre : 
var jobs = {};
jobs["Finance-Comptabilité"] = {};
jobs["Finance-Comptabilité"]["Controleur"] = {};
jobs["Finance-Comptabilité"]["Controleur"]["51000-65000"] = {};
jobs["Finance-Comptabilité"]["Controleur"]["51000-65000"]["76"] = {};
jobs["Finance-Comptabilité"]["Controleur de Gestion Industriel"] = {};

sels : array de tous les select implique

sel : select d'ou provient l'evenemenet : this dans le onchange


  populate: function(sel, sels, db) {
    var id = sel.id;
    //    if ($F(id) == -1 || $F(id)=='0' || $F(id).blank()) return;
    var db2 = db;
    var index = sels.indexOf(id);
    for (var i = 0; i < sels.length; i++) {
      var item = sels[i];
      if (i <= index) {
        db2 = db2[$F(item)];
      }
      if (i >= (index+1)) {
        if (i > (index+1)) {
          $(item).options.length = 0;
        }
      }
      else if (id == item) {
        $(sels[index+1]).options.length = 0;
        if ($F(id) == -1 || $F(id)=='0' || $F(id).blank()) continue;
        $(sels[index+1]).options[$(sels[index+1]).options.length] = new Option("------", "0", false, false);
        $H(db2).each(function(pair) {
          $(sels[index+1]).options[$(sels[index+1]).options.length] = new Option(pair.key, pair.key, false, false);
        });
      }
    }

*/
