﻿ var Dom=YAHOO.util.Dom,
        Event=YAHOO.util.Event,gtc=new Object();
/*****************************/
/* Array.prototype.indexOf   */
/******************************/
if (!Array.prototype.indexOf)   
{   
  Array.prototype.indexOf = function(searchElement /*, fromIndex */)   
  {   
    "use strict";   
  
    if (this === void 0 || this === null)   
      throw new TypeError();   
  
    var t = Object(this);   
    var len = t.length >>> 0;   
    if (len === 0)   
      return -1;   
  
    var n = 0;   
    if (arguments.length > 0)   
    {   
      n = Number(arguments[1]);   
      if (n !== n)   
        n = 0;   
      else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))   
        n = (n > 0 || -1) * Math.floor(Math.abs(n));   
    }   
  
    if (n >= len)   
      return -1;   
  
    var k = n >= 0   
          ? n   
          : Math.max(len - Math.abs(n), 0);   
  
    for (; k < len; k++)   
    {   
      if (k in t && t[k] === searchElement)   // test Identity
        return k;   
    }   
    return -1;   
  };   
}  
/*****************************/
/* Array.prototype.indexValueOf   */
/******************************/
if (!Array.prototype.indexValueOf)   
{   
  Array.prototype.indexValueOf = function(searchElement /*, fromIndex */)   
  {   
    "use strict";   
  
    if (this === void 0 || this === null)   
      throw new TypeError();   
  
    var t = Object(this);   
    var len = t.length >>> 0;   
    if (len === 0)   
      return -1;   
  
    var n = 0;   
    if (arguments.length > 0)   
    {   
      n = Number(arguments[1]);   
      if (n !== n)   
        n = 0;   
      else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))   
        n = (n > 0 || -1) * Math.floor(Math.abs(n));   
    }   
  
    if (n >= len)   
      return -1;   
  
    var k = n >= 0   
          ? n   
          : Math.max(len - Math.abs(n), 0);   
  
    for (; k < len; k++)   
    {   
      if (k in t && t[k] == searchElement)     // test Equality
        return k;   
    }   
    return -1;   
  };   
}  

/**********************************************/
/* HTMLSelectElement.prototype.selectByValue  */
/**********************************************/
 if(HTMLSelectElement && !HTMLSelectElement.prototype.selectByValue)
  HTMLSelectElement.prototype.selectByValue=function(value){
	var optionsLength = this.options.length,selectedIndex=-1;
	for(var i = 0; i<optionsLength; i++) {
	    if (this.options[i].value == value) {
		  selectedIndex=i;
        	   break;	
		 };
	 }
	this.selectedIndex=selectedIndex;
	//this.options[i].selected = true;
	
}

function getElementsById(id,apply,o){
  var nodes = [];
  var tmpNode = document.getElementById(id);
  while(tmpNode){
    if(apply)
       apply.call(window,tmpNode,o);
    nodes.push(tmpNode);
    tmpNode.id = "";
    tmpNode = document.getElementById(id);
  }
  for(var x=0; x<nodes .length; x++){
    nodes[x].id = id;
  }
  return nodes;
}

var gtcEntete = {
    oMenuBar: null,
    panel: null,
    dialogCopy: null,
    isAsso: null,
    oListe: null,
    handleFailure: function (o) {
        if (o.status == 403 && o.getResponseHeader["X-GESTASSCLIC-LOGIN"] == "1") {
            window.location.href = "/gestassclic/login.aspx";
            return true;
        }
        if (o.responseText !== undefined) {
            var err = "<li>Transaction id: " + o.tId + "</li>";
            err += "<li>HTTP status: " + o.status + "</li>";
            err += "Status code message: " + o.statusText + "\n";
            err += "reponse:" + o.responseText;
            alert(err);
        }
    },
    showCopy: function () {
        var oCheck, oCheckList = gtcEntete.oListe.querySelectorAll('span.gtc-liste-check input[type="checkbox"]');
        if (oCheckList.length == 0) {
            alert("Copie impossible: il n'existe pas d'activité.");
            return;
        }
        for (var i = 0, len = oCheckList.length; i < len; i++) {
            if (oCheckList[i].checked) {
                oCheck = oCheckList[i];
                break;
            }
        }
        if (!oCheck) {
            alert("Veuillez sélectionner une activité!");
            return;
        }
        var oActivite = oCheck.parentNode.parentNode;
        var hideCopy = function () {
            this.hide();
        }
        if (!gtcEntete.dialogCopy) {
            gtcEntete.dialogCopy = new YAHOO.widget.SimpleDialog("gtcDialogCopyActivite",
			 { width: "400px",
			     context: ["gtcBtnNew", "tl", "tl"],
			     visible: false,
			     draggable: false,
			     close: false,
			     icon: YAHOO.widget.SimpleDialog.ICON_HELP,
			     constraintoviewport: true
			 });
            gtcEntete.dialogCopy.setHeader("Copier l'activité");
            gtcEntete.dialogCopy.render(gtcEntete.panel.body);
        }
        gtcEntete.dialogCopy.cfg.setProperty("buttons", [{ text: "Oui", handler: { fn: gtcEntete.copyActivite, obj: oActivite.id.split('_')[1] }, isDefault: true },
						  { text: "Non", handler: hideCopy}]);
        gtcEntete.dialogCopy.cfg.setProperty("text", Dom.getFirstChild(oActivite).innerHTML);
        gtcEntete.dialogCopy.show();
    },
    copyActivite: function (ev, NoActi) {
        this.hide();
        Dom.addClass("gtcEntete", "loading");
        window.location.href = "/gestassclic/activite/configuration.aspx?op=copy&no_acti=" + NoActi;
    },
    initPanel: function (load) {
        gtcEntete.oListe = document.getElementById("gtcListe");
        Event.addListener(gtcEntete.oListe, "click", gtcEntete.listeClick);
        gtcEntete.btnNew = new YAHOO.widget.Button("gtcBtnNew");
        gtcEntete.btnCopy = new YAHOO.widget.Button("gtcBtnCopy", { onclick: { fn: gtcEntete.showCopy} });
        gtcEntete.iptSearch = document.getElementById("gtcSearchIpt");
        gtcEntete.iptLoupe = document.getElementById("gtcLoupe");


        Event.on(gtcEntete.iptSearch, 'keyup', gtcEntete.preSearch);
        gtcEntete.panel = new YAHOO.widget.Panel("gtcPanel", { zIndex: 4, underlay: "none", visible: false, draggable: false, modal: true, fixedcenter: true });
        gtcEntete.panel.render();
        if (load)
            gtcEntete.loadPanel(1);
    },
    IdTimeoutSearch: null,
    IdConnectionSearch: null,
    preSearch: function (event) {
        if (event) {
            var iKeyCode = event.keyCode;
            if ((iKeyCode < 32 && iKeyCode != 8) || (iKeyCode >= 33 && iKeyCode < 46)
                   || (iKeyCode >= 112 && iKeyCode <= 123)) return; // on ignore
        }
        clearTimeout(gtcEntete.IdTimeoutSearch);
        if (gtcEntete.IdConnectionSearch != null) { YAHOO.util.Connect.abort(gtcEntete.IdConnectionSearch, {}, false); }
        gtcEntete.IdTimeoutSearch = setTimeout(gtcEntete.search, 200);
    },
    search: function () {
        gtcEntete.oListe.innerHTML = "";
        Dom.addClass(gtcEntete.oListe, "loading");
        var callback = {
            success: function (o) {
                if (o.getResponseHeader["X-GESTASS-LOGIN"]) {
                    window.location.href = "/gestassclic/login.aspx";
                    return;
                }
                gtcEntete.oListe.innerHTML = o.responseText.substring(o.responseText.indexOf("<div"), o.responseText.lastIndexOf("</form>"));
                Dom.removeClass(gtcEntete.oListe, "loading");
            },
            failure: gtcEntete.handleFailure,
            cache: false
        }
        var search=gtcEntete.iptSearch.value.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
        // Connect to our data source and load the data
        gtcEntete.IdConnectionSearch = YAHOO.util.Connect.asyncRequest("GET", "/gestassclic/" + (gtcEntete.isAsso == 1 ? "listerAsso.aspx?op=get&search=" + encodeURIComponent(search) : "listerActi.aspx?op=get"), callback);
    },
    loadPanel: function (isAsso) {
        var strHeader;
        if (isAsso == 1) {
            strHeader = "Choisir ou créer une association";
            gtcEntete.btnCopy.setStyle("visibility", "hidden");
            Dom.removeClass(gtcEntete.iptLoupe, "cacher");
        } else
            if (isAsso == 0) {
                strHeader = "Choisir, créer ou copier une activité";
                gtcEntete.btnCopy.setStyle("visibility", "inherit");
                Dom.addClass(gtcEntete.iptLoupe, "cacher");

            }
            else
                return;
        this.btnNew.set("label", "Créer une " + (isAsso == 1 ? "association" : " nouvelle activité"));
        this.btnNew.set("href", "/gestassclic/" + (isAsso == 1 ? "association" : "activite") + "/creer.aspx");
        this.panel.setHeader(strHeader);
        this.panel.show();
        this.isAsso = isAsso;
        if (isAsso)
            gtcEntete.iptSearch.select();
        this.preSearch();
    },
    initSession: function (tar) {
        this.panel.hide();
        Dom.addClass("gtcEntete", "loading");
        var NoId = tar.id.split('_')[1],
            sig = encodeURIComponent(tar.querySelector("span.gtc-sig").innerHTML),
            nom = encodeURIComponent(tar.querySelector("span.gtc-nom").innerHTML);
        window.location.href = "/gestassclic/" + (this.isAsso == 1 ? "listerAsso.aspx?op=set&noasso=" + NoId + "&sigle=" + sig + "&nom=" + nom : "listerActi.aspx?op=set&noacti=" + NoId + "&nom=" + nom);
    },
    listeClick: function (ev) {
        var tar = Event.getTarget(ev);
        while (tar && tar.id !== gtcEntete.oListe) {
            if (Dom.hasClass(tar, 'gtc-liste-check')) {
                break;
            }
            else
                if (Dom.hasClass(tar, 'gtc-l-ac') || Dom.hasClass(tar, 'gtc-l-as')) {
                    gtcEntete.initSession(tar);
                    break;
                }
            tar = tar.parentNode;
        }
    },
    enteteClick: function (ev) {
        var tar = Event.getTarget(ev);
        while (tar.id != "gtcEntete") {
            if (tar.id == "gtcAsso" && tar.className == "actif") {
                gtcEntete.loadPanel(1);
                break;
            } else
                if (tar.id == "gtcActi" && tar.className == "actif") {
                    gtcEntete.loadPanel(0);
                    break;
                }
            tar = tar.parentNode;
        }
    }

}

/**
 * Les blancs sont définis comme l'un de ces caractères
 *  "\t" TAB \u0009
 *  "\n" LF  \u000A
 *  "\r" CR  \u000D
 *  " "  SPC \u0020
 *
 * On n'utilise pas les "\s" de JavaScript car les espaces insécables
 * (et quelques autres caractères) en font partie.
 */


/**
 * Détermine si un nœud texte est entièrement composé de blancs
 *
 * @param nod  Un nœud implémentant l'interface |CharacterData| (c'est-à-dire,
 *             un nœud |Text|, |Comment| ou |CDATASection|)
 * @return     Vrai si tout le contenu texte de |nod| est composé de blancs,
 *             faux dans les autres cas.
 */
function is_all_ws( nod )
{
  // Utilisation des fonctionnalités String et RegExp d'ECMA-262 Edition 3
  return !(/[^\t\n\r ]/.test(nod.data));
}


/**
 * Détermine si un nœud devrait être ignoré par les fonctions itérateurs.
 *
 * @param nod  Un objet implémentant l'interface DOM1 |Node|.
 * @return     vrai si le nœud est :
 *                1) un nœud |Text| composé uniquement de blancs
 *                2) un nœud de commentaire |Comment|
 *             et faux dans les autres cas.
 */

function is_ignorable( nod )
{
  return ( nod.nodeType == 8) || // Un nœud de commentaire
         ( (nod.nodeType == 3) && is_all_ws(nod) ); // un nœud texte, uniquement des blancs
}
/**
 * Version de |previousSibling| qui passe les nœuds entièrement constitués
 * de blancs ou les commentaires. (Normalement |previousSibling| est une propriété
 * de tous les nœuds DOM qui donne le nœud du même niveau, qui est lethat is
 * un enfant du même parent, qui se trouve immédiatement avant le nœud
 * de référence.)
 *
 * @param sib  Le nœud de référence.
 * @return     Soit :
 *               1) Le nœud de même niveau le plus proche de |sib| qui n'est pas
 *                  ignorable d'après |is_ignorable|, ou
 *               2) null si un tel nœud n'existe pas.
 */
function node_before( sib )
{
  while ((sib = sib.previousSibling)) {
    if (!is_ignorable(sib)) return sib;
  }
  return null;
}

/**
 * Version de |nextSibling| qui passe les nœuds qui sont entièrement constitués de
 * blancs ou les commentaires.
 *
 * @param sib  Le nœud de référence.
 * @return     Soit :
 *               1) Le nœud suivant de même niveau le plus proche de |sib| qui n'est pas
 *                  ignorable selon |is_ignorable|, ou
 *               2) null si un tel nœud n'existe pas.
 */
function node_after( sib )
{
  while ((sib = sib.nextSibling)) {
    if (!is_ignorable(sib)) return sib;
  }
  return null;
}

/**
 * Version de |lastChild| qui passe les nœuds qui sont entièrement constitués de
 * blancs ou les commentaires.  (Normalement |lastChild| est une propriété
 * de tous les nœuds DOM qui donne le dernier des nœuds contenus directement
 * dans le nœud de référence.)
 *
 * @param sib  Le nœud de référence.
 * @return     Soit :
 *               1) Le dernier enfant de |sib| qui n'est pas
 *                  ignorable selon |is_ignorable|, ou
 *               2) null si un tel nœud n'existe pas.
 */
function last_child( par )
{
  var res=par.lastChild;
  while (res) {
    if (!is_ignorable(res)) return res;
    res = res.previousSibling;
  }
  return null;
}



function first_child( par)
{
  var res=par.firstChild;
  while (res) {
    if (!is_ignorable(res)) return res;
    res = res.nextSibling;
  }
  return null;
}


