Activsoft.Manager.register("activsoft.ajax.util");

var obj;

activsoft.ajax.util.xpathNodeList = function(expression,node,doc) {
  var isIE = false;
  var nodes = new Array();

  if(window.ActiveXObject) {
    isIE = true;
  }
  
  if (isIE) {
    var nodeList = node.selectNodes(expression);
    for(u=0;u<nodeList.length;u++) {
      nodes[u] = nodeList.item(u);
    }
  }
  else {
    if (node.selectNodes) {
      var nodeList = node.selectNodes(expression);
      for(u=0;u<nodeList.length;u++) {
        nodes[u] = nodeList.item(u);
      }
    }
    else {
      var xpath = new XPathEvaluator();
      var xpathresult = xpath.evaluate(expression, node, null, 7, null);
      for(u=0;u<xpathresult.snapshotLength;u++) {
        nodes[u] = xpathresult.snapshotItem(u);
      }
    }
  }
  
  return nodes;
}

activsoft.ajax.util.getChildData = function(parentEl) {
  if (parentEl == null) {
    return null;
  }
  var tempNode = parentEl.firstChild;
  var text="";
  
  while (tempNode != null) {
    switch (tempNode.nodeType) {
      case 3 /*TEXT_NODE*/ :
        text+=tempNode.nodeValue;
      break;

      case 4 /*CDATA_SECTION_NODE*/ :
        text+=tempNode.nodeValue;
      break;
      
      default :
      break;
    }
    tempNode = tempNode.nextSibling;
  }
  return text;
}

activsoft.ajax.util.WaitPanelObject = function() {
  if (!(document.getElementById('divAjaxWaitPanel'))) {
    var parentDiv = document.createElement("div");
    parentDiv.setAttribute("id", "divAjaxWaitPanel");
    parentDiv.style.display = "none";
    
    var imgDiv = document.createElement("div");
    imgDiv.setAttribute("id", "divAjaxWaitPanelStatePanel");
    imgDiv.className = "stateWait";
    parentDiv.appendChild(imgDiv);

    var imgDiv = document.createElement("div");
    imgDiv.setAttribute("id", "divAjaxWaitPanelContent");
    parentDiv.appendChild(imgDiv);
    
    document.body.appendChild(parentDiv);
  }
}

activsoft.ajax.util.getNextSiblingElement= function(element) {
  var el = element.nextSibling;
  while (el) {
  	if (el.nodeType==1) {
	  return el;
	}
  	el = el.nextSibling;
  }
  return null;  
}

activsoft.ajax.util.WaitPanelObject.prototype.showNextToMouse = function(state, message, event) {
  this.showInPosition(state, message, YAHOO.util.Event.getPageY(event), YAHOO.util.Event.getPageX(event));
}

activsoft.ajax.util.WaitPanelObject.prototype.showCenter = function(state, message) {
  var pan = document.getElementById('divAjaxWaitPanel');
  this.showInPosition(state, message, YAHOO.util.Dom.getDocumentHeight() / 2, (YAHOO.util.Dom.getClientWidth() / 2));  
}  

activsoft.ajax.util.WaitPanelObject.prototype.showCenterAtMouse = function(state, message, event) {
  var pan = document.getElementById('divAjaxWaitPanel');
  this.showInPosition(state, message, YAHOO.util.Event.getPageY(event), (YAHOO.util.Dom.getClientWidth() / 2));  
}  

activsoft.ajax.util.WaitPanelObject.prototype.showInPosition = function(state, message, top, left) {
  var pan = document.getElementById('divAjaxWaitPanel');

  pan.style.top = top + "px";
  pan.style.left = left + "px";

  if (state == "WAIT") {
    document.getElementById('divAjaxWaitPanelStatePanel').className = 'stateWait';
  }
  if (state == "FINISH") {
    document.getElementById('divAjaxWaitPanelStatePanel').className = 'stateFinish';
  }
  document.getElementById('divAjaxWaitPanelContent').innerHTML = message;
  pan.style.display = 'block';
  pan.style.left=pan.offsetLeft-(pan.offsetWidth/2)+'px';
}

activsoft.ajax.util.WaitPanelObject.prototype.hide = function() {
  var pan = document.getElementById('divAjaxWaitPanel');
  pan.style.display = 'none';
}

activsoft.ajax.util.PromptPanelObject = function() {
  if (!(document.getElementById('divAjaxPromptPanel'))) {
    var parentDiv = document.createElement("div");
    parentDiv.setAttribute("id", "divAjaxPromptPanel");
    parentDiv.style.display = "none";

    var field = document.createElement("fieldset");
    parentDiv.appendChild(field);    
    var enfant = document.createElement("label");
    enfant.setAttribute("for", "divAjaxPromptInput");
    field.appendChild(enfant);
    this._label = enfant;
    enfant = document.createElement("input");
    enfant.setAttribute("type", "text");
    enfant.setAttribute("name", "divAjavPromptInput");
    enfant.setAttribute("id", "divAjavPromptInput");
    enfant.setAttribute("value", "");
    this._input = enfant;
    field.appendChild(enfant);

    var act = document.createElement("div");
    act.className = "actionPanel";
    parentDiv.appendChild(act);
    enfant = document.createElement("div");
    enfant.className = "actionButton";
    enfant.setAttribute("id","divAjavPromptOk");
    enfant.appendChild(document.createTextNode("Ok"));
    act.appendChild(enfant);
    
    enfant = document.createElement("div");
    enfant.className = "actionButton";
    enfant.appendChild(document.createTextNode("Annuler"));
    enfant.setAttribute("id","divAjavPromptCancel");
    act.appendChild(enfant);

    YAHOO.util.Event.addListener("divAjavPromptOk", "click", function(event, me) {me.validation();}, this);
    YAHOO.util.Event.addListener("divAjavPromptCancel", "click", function(event, me) {me.cancel();}, this);

    document.body.appendChild(parentDiv);
  }
  if (!(document.getElementById('divAjaxPromptOverlayPanel'))) {
    var over = document.createElement("div");
    over.setAttribute("id", "divAjaxPromptOverlayPanel");
    var img = document.createElement("img");
    img.setAttribute("border","0");
    img.setAttribute("src", "img/0.gif");
    img.setAttribute("width", "100%");
    img.setAttribute("height", "100%");
    img.onclick = function() {return false;}
    img.style.display = "none";
    over.appendChild(img);
    document.body.appendChild(over);
  }
}

activsoft.ajax.util.PromptPanelObject.prototype.validation = function() {
  if (this.onValid) {
    this.onValid(this._input.value);
  }
  this.hide();
}

activsoft.ajax.util.PromptPanelObject.prototype.cancel = function() {
  if (this.onCancel) {
    this.onCancel();
  }
  this.hide();
}

activsoft.ajax.util.PromptPanelObject.prototype.hide = function() {
  var pan = document.getElementById('divAjaxPromptPanel');
  pan.style.display = 'none';
  document.getElementById('divAjaxPromptOverlayPanel').style.display = 'none';
}

activsoft.ajax.util.PromptPanelObject.prototype.showNextToMouse = function(label, defaultValue, onValid, onCancel) {
  this.showInPosition(label, defaultValue, onValid, onCancel, event.getY(), event.getX());
}

activsoft.ajax.util.PromptPanelObject.prototype.showCenter = function(label, defaultValue, onValid, onCancel) {
  if (document.body.clientHeight==0) {
    this.showInPosition(label, defaultValue, onValid, onCancel, document.body.clientHeight / 2, document.body.clientWidth / 2 - 300);
  }
  else {
    this.showInPosition(label, defaultValue, onValid, onCancel, 150, document.body.clientWidth / 2 - 300);
  }
}  

activsoft.ajax.util.PromptPanelObject.prototype.showInPosition = function(label, defaultValue, onValid, onCancel, top, left) {
  this.onValid = onValid;
  this.onCancel = onCancel;
  this._input.value = defaultValue;
  while (this._label.childNodes.length>0) {
    this._label.removeChild(this._label.firstChild);
  }
  this._label.appendChild(document.createTextNode(label));
  
  var pan = document.getElementById('divAjaxPromptPanel');

  pan.style.top = top + "px";
  pan.style.left = left + "px";

  document.getElementById('divAjaxPromptOverlayPanel').style.display = 'block';
  pan.style.display = 'block'; 
}

activsoft.ajax.util.WaitPanelObject.prototype.updateMessage = function(state, message) {
  var pan = document.getElementById('divAjaxWaitPanel');
  if (state == "WAIT") {
    document.getElementById('divAjaxWaitPanelStatePanel').className = 'stateWait';
  }
  if (state == "FINISH") {
    document.getElementById('divAjaxWaitPanelStatePanel').className = 'stateFinish';
  }
  document.getElementById('divAjaxWaitPanelContent').innerHTML = message;
}

activsoft.ajax.util.WaitPanelObject.prototype.updateMessageAndClose = function(state, message, timeToWait) {
  var pan = document.getElementById('divAjaxWaitPanel');
  if (state == "WAIT") {
    document.getElementById('divAjaxWaitPanelStatePanel').className = 'stateWait';
  }
  if (state == "FINISH") {
    document.getElementById('divAjaxWaitPanelStatePanel').className = 'stateFinish';
  }
  document.getElementById('divAjaxWaitPanelContent').innerHTML = message;
  
  obj=this;
  var t=setTimeout("obj.hide()",timeToWait)
}

activsoft.ajax.util.AutoComplete = function(objInput,page,callBackCreateFunction,startNodeXpath,xpathForText,xpathForValue,arrFieldMapping,validationMode,autoSelectIfOnlyOne,nbSeconds,nbCarac) {
  var divToShow = document.getElementById('autoComplete_' + objInput.name);
  if (!divToShow) {
    divToShow = document.createElement("div");    
    divToShow.setAttribute("id", "autoComplete_" + objInput.name);
    divToShow.style.display = 'none';
    //if (objInput == objInput.parentNode.lastChild) {
      //objInput.parentNode.appendChild(divToShow);
    //}
    //else {
      document.getElementById('auto').appendChild(divToShow);
      divToShow.style.top=findPosY(objInput)+20+'px';
      divToShow.style.left=findPosX(objInput)-10+'px';
    //}
  }
  this._buildRequest = callBackCreateFunction;
  this.el = divToShow;
  this.el.className = "autoCompleteDiv";

  this.instanceName = 'autoComplete_' + objInput.name;
  this.xmldoc=null;
  this.startNode=null;
  
  this.objInput=objInput;
  this._myPage = page;
  this.objInputId = objInput.getAttribute("id");
  
  this.nbCarac=nbCarac;
  if (!nbCarac) {
    this.nbCarac = 2;
  }
  this.nbSeconds = nbSeconds;
  if (!nbSeconds) {
    this.nbSeconds = 2;
  }

  this.startNodeXpath=startNodeXpath;
  this.xpathForText=xpathForText;
  this.xpathForValue=xpathForValue;
  this.autoSelectIfOnlyOne=autoSelectIfOnlyOne;
  this.arrFieldMapping=arrFieldMapping;
  this.lastElement = 0;
  
  var vMode = validationMode;
  if (!validationMode) {
    vMode = 'wait';
  }
  if (vMode == 'wait') {
    YAHOO.util.Event.addListener(objInput.getAttribute("id"),"keyup",this.update,this);
    this.objInput.returnFromWait = new YAHOO.util.CustomEvent("returnFromWait_" + this.objInput.name, this.objInput);
    this.objInput.returnFromWait.subscribe(this.returnFromEvent, this);
  }
  else {
    YAHOO.util.Event.addListener(objInput.getAttribute("id"),"keypress",this.updateEnter,this);
  } 
}

activsoft.ajax.util.AutoComplete.prototype.returnFromEvent = function(type, args, me) {
  if (me.lastElement == args[0]) {
    me.refresh();
  }
}

activsoft.ajax.util.AutoComplete.prototype.show = function() {
  this.el.style.display='block';
}

activsoft.ajax.util.AutoComplete.prototype.unshow = function() {
  this.el.style.display='none';
}

activsoft.ajax.util.AutoComplete.prototype.selectFromLi = function(event, arr) {
  arr[0].selectIt(arr[1]);
}

activsoft.ajax.util.AutoComplete.prototype.selectIt = function(idx) {
  this.unshow();
  if(this.startNode!=null && this.startNode.length>=idx) {
    var arr = activsoft.ajax.util.xpathNodeList(this.xpathForValue,this.startNode[idx],this.xmldoc);
    if(arr!=null && arr.length>0) {
      this.objInput.value=arr[0].firstChild.nodeValue;

      if(this.arrFieldMapping!=null) {
        for(var inputFieldAsString in this.arrFieldMapping) {
          if (document.getElementById(inputFieldAsString)) {
            var inputField = document.getElementById(inputFieldAsString);
            var arr = activsoft.ajax.util.xpathNodeList(this.arrFieldMapping[inputFieldAsString],this.startNode[idx],this.xmldoc);
            if(arr!=null && arr.length>0 && arr[0].firstChild!=null) {
              inputField.value = arr[0].firstChild.nodeValue;
            }
          }
        }
      }
    }
  }
}

activsoft.ajax.util.AutoComplete.prototype.update = function(event, autoComplete) {
  autoComplete.lastElement++;
  if (this.value.length>=autoComplete.nbCarac) {
    setTimeout("document.getElementById('" + autoComplete.objInputId + "').returnFromWait.fire(" + autoComplete.lastElement + ")", autoComplete.nbSeconds);
  }
}

activsoft.ajax.util.AutoComplete.prototype.updateEnter = function(event) {
  if (event.keyCode==13) {
    refresh();
  }
}

activsoft.ajax.util.AutoComplete.prototype.refresh = function() {
  this.unshow();
  if(this.objInput.value.length>=this.nbCarac) {
    var myRequest = new activsoft.ajax.RequestToSend();
    var obj = this;
    myRequest.nbTries = 3;
    myRequest.afterLoadCallBack = function(){
      obj.callBackRefresh(this.xmlDocumentLoaded);
    }
    myRequest.httpErrorCallBack = this.defaultHttpRequestErrorMethod;
    myRequest.page = this._myPage;    
    myRequest.request = this._buildRequest(this.objInput.value);
    this.show();
    this.el.innerHTML='Chargement en cours...';
    myRequest.send();
  }
}

activsoft.ajax.util.AutoComplete.prototype.makeURLParameter = function(newParamName, newParamValue) {
  return newParamName + '=' + newParamValue;
}

activsoft.ajax.util.AutoComplete.prototype.callBackRefresh = function(xmldocument) {
  this.xmldoc = xmldocument;
  if (this.startNodeXpath.substr(0,1)=="/") {
    this.startNodeXpath = this.startNodeXpath.substr(1);
  }
  this.startNode=activsoft.ajax.util.xpathNodeList(this.startNodeXpath, this.xmldoc, this.xmldoc);
  if(this.startNode!=null) {
    if(this.startNode.length==1 && this.autoSelectIfOnlyOne) {
      var arr = activsoft.ajax.util.xpathNodeList(this.xpathForText,this.startNode[0],this.xmldoc);
      if(arr.length>0) {
        this.selectIt(0);
      } 
    }
    else {
      while (this.el.childNodes.length>0) {
        this.el.removeChild(this.el.firstChild);
      }
      var ulEl = document.createElement("ul");
      var liEl = null;
      var trouve = false;
      for(var i=0;i<this.startNode.length;i++) {
        var arr = activsoft.ajax.util.xpathNodeList(this.xpathForText,this.startNode[i],this.xmldoc);  
        if(arr!=null && arr.length>0 && arr[0].firstChild!=null) {  
          var id = "autocomplete_li_" + this.objInput.name + "_" + i;
          trouve = true;
          liEl = document.createElement("li");
          liEl.setAttribute("id", id);
          args = new Array();
          args.push(this);
          args.push(i);
          YAHOO.util.Event.addListener(liEl, "click", this.selectFromLi, args);
          liEl.appendChild(document.createTextNode(arr[0].firstChild.nodeValue));
          ulEl.appendChild(liEl);
        }
      }
      document.getElementById('autoComplete_' + this.objInput.name).appendChild(ulEl);
      
      if(!trouve) {
        this.unshow();
      }
    }
  }
}

activsoft.ajax.util.AutoComplete.prototype.getHttpRequest = function() {
  var xmlhttp;
  if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
    xmlhttp = new XMLHttpRequest();
  }
  return xmlhttp;
}