// Copyright (C) 2002-2007 Logiciels Sys-Thèmes Inc. -->
// 30/01/2004 : Ajout d'une fonction remplirListe(controle, liste) pour remplissage avec format "XX, XX, XX" -> 7.1.0 --%>
// 02/02/2004 : Modif de setFocus() provenant de chez Chariot --> 7.2.0
// 25/02/2004 : Ajouter la fonctionnalité du F11 (ditto), ajout enter=tab, ajout chiffre du record --> 7.3.0
// 26/02/2004 : Fonctionnalité de changement d'onglet avec chiffre et position avec alt+chiffre --> 7.4.0
// 01/03/2004 : Changé chiffre pour position avec ctrl au lieu de alt --> 7.5.0
// 01/03/2004 : Nouvelle méthode ouvrirRecherche2 pour indexpatient --> 7.5.1
// 10-mai-2004 : Modifier lockfld2 , ajouter validation sur className --> 7.5.2
// 23/09/2004 : Changé lookup() pour tenir compte de l'opérateur ":" -> 7.6.2
// 23/09/2004 : Changer le ditto à innerText pour provoquer l'événement onchange --> 7.7.2
// 23/09/2004 : EditFrm() modifiée --> 7.7.3
// 23/09/2004 : Fonction ouvrirRecherche3 ajoutée --> 7.7.4 
// 02/11/2004 : Prend en compte une fonction qui sera éxécuté apres le lookup avec setLookupFuncToDo(func); -> 7.8.4
// 07/12/2004 : After cancel remet les champs non-rouge --> 7.9.4
// 13/04/2005 : Ajouté focusOn et focusOff (K) --> 7.10.4
// 15/04/2005 : Changé executeLoupe getMode() != "" --> 7.11.4
// 25/05/2005 : Utilise les touches "a", "u" et "q" pour add, update et query --> 7.12.4
// 26/05/2005 : Utilise les touches "n", "p" pour next, previous --> 7.13.4
// 08/06/2005 : Focus ailleurs sur ok pour forcer les validation javascript --> 7.14.4
// 29/06/2005 : Fonctions pour la gestion du F12 avec go() et wait() sur callPage() --> 7.15.4
// 19/08/2005 : Auto-go() sur OK quand on est en mode filtrer --> 7.16.4
// 09/09/2005 : Modif fonction getHiddenInfo() --> 8.0
// 31-07-2006 : Version AJAX 2 -> 8.0.0
// 21-09-2007 : Chg oldValueCreer et oldValueReset pour prendre les lables du current div -> 8.1
// 26-09-2007 : Added function afterDisplay() --> 8.2
// 04-10-2007 : Added call to function afterDisplay() in function changeOnglet() --> 8.3
// 05-10-2007 : Added call to function afterDisplay() in function moveListeXML() --> 8.4
// 18-10-2007 : Dans ouvrirRecherche(), changer vFonction pour escape(vFonction) pour pouvoir passer des paramêtres en string --> 8.5
// 05-11-2007 : Dans clearAllFldValue(), ajouter vérifier si une classe du Label est "alwaysDisplay", pour ne pas vider ce label --> 8.6
// 15-11-2007 : Ajouté variable inCalendar et les fonctions exitCalendar(), keepCalendar() et closeCalendar() pour fermer automatiquement les calendriers --> 8.7
// 01-02-2008 : Ajouter function getOldValue() --> 8.8
// 12-02-2008 : Modifer function allUpperCase() pour prendre les champs en erreur aussi --> 8.9
// 10-11-2008 : return false sur les catchs des after --> 8.10
// 10-11-2008 : ajouter le code pour faire les coins rond --> 8.11
//==== VARIABLES GLOBALES =====//
var champTarget;
var champRst;
var fonctionToDo;
var oldValue = new Array();
var oldValueLabels = new Array();
var pressOk = false;
var etatListe = 0;
var timer = null;
var waitForList = true;

var timeStamp1 = new Date();
var timeStamp2 = new Date();


xmlHttp_JS = new ActiveXObject("Msxml2.XMLHTTP");
xhr1 = null;
xhr2 = null;
xhr3 = null;

window.onunload=function(){
    try{
        //alert("clrsession.jsp");
        callPageJS("clrsession.jsp?wId="+ frmEdit.wId.value +"",false);
    }
    catch(e){
    }
}
window.onfocus=function(){

    try{
        
    }
    catch(e){
    }
}




docXMLListe_1 = new ActiveXObject("Microsoft.XMLDOM");
docXSL_1 = new ActiveXObject("Microsoft.XMLDOM");
docXMLListe_2 = new ActiveXObject("Microsoft.XMLDOM");
docXSL_2 = new ActiveXObject("Microsoft.XMLDOM");
docXMLListe_3 = new ActiveXObject("Microsoft.XMLDOM");
docXSL_3 = new ActiveXObject("Microsoft.XMLDOM");



function focusOn(obj,force){
    if (getMode() != "" || force != null){
        obj.style.borderColor = "Yellow";
        obj.style.backgroundColor = "Yellow";
    }
}
function focusOff(obj){  
    obj.style.borderColor = "";
    obj.style.backgroundColor = "";
}
function fermerFenetre(val){
    window.returnValue = val;
    self.close();
}
function checkMaxLen(maxLen){
   if ( event.keyCode == 13  ||
        (event.srcElement.value.length >= maxLen  &&  event.keyCode != 8  &&  event.keyCode != 9 )){
        //beep();
        event.returnValue = false;
   }
}

function reloadFrm(){
    parent.frames.bas.location.reload(true);
}

function clearAllFldValue(){
    //var nb = frmEdit.elements.length;
    var currentDiv = eval(frmEdit.tableActive.value + "_screen");
    var nb = currentDiv.all.length;
    
    for (var i=0; i < nb ;i++){
        if((currentDiv.all[i].className == "fieldDisabled" || currentDiv.all[i].className == "fieldEnabled") && (currentDiv.all[i].type == "text" || currentDiv.all[i].type == "password" || currentDiv.all[i].type == "textarea" || currentDiv.all[i].type == "select-one")){
            currentDiv.all[i].value = '';
        }
    }

    nb = currentDiv.all.length;
    for (var i=0; i < nb ;i++){
        if(currentDiv.all(i).tagName == "LABEL" && currentDiv.all(i).className != "money" && currentDiv.all(i).className.indexOf("alwaysDisplay") == -1)
            currentDiv.all(i).innerText = "";
    }

}
function setNoLimitLen(){
    //var nb = frmEdit.elements.length;

    var currentDiv = eval(frmEdit.tableActive.value + "_screen");
    var nb = currentDiv.all.length;

    for (var i=0; i < nb ;i++){
        if(currentDiv.all[i].type == "text"){
            currentDiv.all[i].maxLength = '5000';
        }
    }
}
function allUpperCase(){
    //var nb = frmEdit.elements.length;

    var currentDiv = eval(frmEdit.tableActive.value + "_screen");
    var nb = currentDiv.all.length;

    for (var i=0; i < nb ;i++){
        if((currentDiv.all[i].className == "fieldDisabled" || currentDiv.all[i].className == "fieldEnabled" || currentDiv.all[i].className == "fieldErreur") &&  (currentDiv.all[i].type == "text" || currentDiv.all[i].type == "password" || currentDiv.all[i].type == "textarea"  || currentDiv.all[i].type == "select-one")){
            if(currentDiv.all[i].style.textTransform != "none" )
                currentDiv.all[i].value = currentDiv.all[i].value.toUpperCase();
        }
    }
}

function allUpperCase_Find(){
    var nb = document.all.length;
    for (var i=0; i < nb ;i++){
        if(document.all[i].type == "text" || document.all[i].type == "password" || document.all[i].type == "textarea"  || document.all[i].type == "select-one"){
            if(document.all[i].style.textTransform != "none")
                document.all[i].value = document.all[i].value.toUpperCase();
        }
    }
}

function setFocus(){
    //var nb = frmEdit.elements.length;
    currentDiv = eval(frmEdit.tableActive.value + "_screen");
    var nb = currentDiv.all.length;
    var go = true;
    var index = 1;
    while(go){
        for (var i=0; i < nb ;i++){
            if(currentDiv.all[i].type == "text" || currentDiv.all[i].type == "password" || currentDiv.all[i].type == "textarea"  || currentDiv.all[i].type == "select-one"){
                if(currentDiv.all[i].tabIndex == index){                    
                    if((currentDiv.all[i].type == "text" && currentDiv.all[i].readOnly == false) || (currentDiv.all[i].type == "select-one" && currentDiv.all[i].disabled == false)){   
                        currentDiv.all[i].focus();
                        go = false;
                    }
                    break;
                }
            }
        }
        index++;
        if(index > nb)
            break;
    }
}

function lockAllFld(lock){
    //Curent div
    //balaye dans le div
    var currentDiv = eval(frmEdit.tableActive.value + "_screen");
    var nb = currentDiv.all.length;

    for (var i=0; i < nb ;i++){
        //alert(currentDiv.all[i].type);
        if(currentDiv.all[i].type == "text" || currentDiv.all[i].type == "password" || currentDiv.all[i].type == "textarea"  || currentDiv.all[i].type == "select-one"){
            //alert(currentDiv.all[i].name);
            lockFld2(currentDiv.all[i],lock);
        }
    }
}
function lockFld2(ctl,lock){
    if(ctl.className == "fieldDisabled" || ctl.className == "fieldEnabled" || ctl.className == "fieldErreur"){
        if(ctl.type == "select-one")
            ctl.disabled = lock;
        else
            ctl.readOnly = lock;
        if (lock)
            ctl.className = "fieldDisabled";
        else
            ctl.className = "fieldEnabled";
    }
    
    
}

function lockFld(ctl,lock){
    if (lock){
        ctl.className = "fieldDisabled";
        ctl.tabIndex = (-1 * ctl.tabIndex);
//        alert(ctl.tabIndex);
    }
    else{
        ctl.className = "fieldEnabled";
        ctl.tabIndex = Math.abs(ctl.tabIndex);
    }

    if(ctl.type == "select-one" || ctl.type == "textarea" ){
        ctl.disabled = lock;
    }
    else{
        ctl.readOnly = lock;
    }
}

/*function GetXmlHttpObject(handler)
{ 
    if (handler == stateChanged_JS || handler == stateChanged || handler == stateChangedListeXML_1 ||
        handler == stateChangedListeXML_2 || handler == stateChangedListeXML_3 || handler == stateChangedLookup){
    
        var objXmlHttp=null
        if (navigator.userAgent.indexOf("Opera")>=0)
           {
            alert("This example doesn't work in Opera") 
            return  
           }
        if (navigator.userAgent.indexOf("MSIE")>=0)
           { 
           var strName="Msxml2.XMLHTTP"
           if (navigator.appVersion.indexOf("MSIE 5.5")>=0)
              {
              strName="Microsoft.XMLHTTP"
              } 
           try
              { 
              objXmlHttp=new ActiveXObject(strName)
              objXmlHttp.onreadystatechange=handler 
              return objXmlHttp
              } 
           catch(e)
              { 
              alert("Error. Scripting for ActiveX might be disabled") 
              return 
              } 
            } 
        if (navigator.userAgent.indexOf("Mozilla")>=0)
           {
           objXmlHttp=new XMLHttpRequest()
           objXmlHttp.onload=handler
           objXmlHttp.onerror=handler 
           return objXmlHttp
        }
    }
} 
*/
function getXHR(){
    var xhr = null;
    if(window.XMLHttpRequest){ // Firefox et autres
        xhr = new XMLHttpRequest();
    }
    else if(window.ActiveXObject){
		xhr = new ActiveXObject("Microsoft.XMLHTTP");
        // Internet Explorer
		/*
		try {
			xhr = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e) {
			xhr = new ActiveXObject("Microsoft.XMLHTTP");
		}*/
    }
    else {
        // XMLHttpRequest non supporté par le navigateur
        alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest...");
        xhr = false;
    }
    return xhr
}
function submitNav(val){
    if(val == "Parcourir")
        beforeBrowse();
    else if (val == "Ordonner"){
        beforeOrderBy();
        callOrderByWindow(frmEdit.tableActive.value, eval("frmEdit."+frmEdit.tableActive.value +"_orderBy"), frmEdit.wId.value);
    }
    else {
        
        if(val == "Suivant"){  
            if(parseInt(frmEdit.txtPos.value) < parseInt(frmEdit.txtCount.value))
                frmEdit.newPosition.value = parseInt(frmEdit.txtPos.value) + 1;
            else
                return;
        }
        else if(val == "Premier"){
            if(parseInt(frmEdit.txtPos.value) > 1)
                frmEdit.newPosition.value = 1;
            else 
                return;
        }
        else if(val == "Precedent"){     
            if(parseInt(frmEdit.txtPos.value) > 1)
                frmEdit.newPosition.value = parseInt(frmEdit.txtPos.value) - 1;
            else
                return;
        }
        else if(val == "Dernier"){
            if(parseInt(frmEdit.txtPos.value) != parseInt(frmEdit.txtCount.value))
                frmEdit.newPosition.value = parseInt(frmEdit.txtCount.value);
            else
                return;
        }    
        else if(val == "Courant"){
            if(parseInt(frmEdit.txtPos.value) == 0){
                return;
            }
            else{
                frmEdit.newPosition.value = parseInt(frmEdit.txtPos.value);
            }
        }    
        frmEdit.txtPos.value = frmEdit.newPosition.value          
        val = "moveTo";
        doEvent("before","moveTo");
        frmEdit.command.value = val;
        appelBoutonCmd();
        //setTimeout("doEvent(\"after\", '"+ val +"')",10);
        doEvent("after", val);
        afterDisplay();
    }  
}

function callPageJS(pageName,continueScript){
    if (pageName.indexOf("?") < 0){
        pageName += "?";
    }
    try{
        pageName += "&wId=" + frmEdit.wId.value;
    }
    catch(e){ // le champs n'existe pas on fait rien
    }
    var laPage=""
    var param = "";
    laPage = pageName.substr(0,pageName.indexOf("?"));
    param = pageName.substr(pageName.indexOf("?")+1);
    var xhr = getXHR();
    xhr.onreadystatechange = function(){
        if (xhr.readyState==4 && xhr.status == 200){
            try{
                eval(xhr.responseText);
            }
            catch(e){
                alert("pageName:"+ pageName +"\n "+ e.name + " : " + e.message +"\n\n"+ xhr.responseText);
            }
        }
    }
    if(continueScript == null)
        continueScript = true;
    xhr.open("POST", laPage , continueScript) ;
   	xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    xhr.send(param);
}
function showLoader(){
    sys_loader.className = "ongletVisible";
}
function hideLoader(){
    sys_loader.className = "ongletHidden";
}
function appelBoutonCmd(){    

    sys_loader.className = "ongletVisible";
    var urlxml="";
	//var urlxml="boutoncmd.jsp?";
//    var urlxml=frmEdit.action+"?";
    //alert("test1");
    var champTemp = "";
    var valeurTemp = "";
    var calledBy="";
    
    for (i = 0; i < document.forms.length; i++){                
        for(j = 0; j < document.forms[i].elements.length; j++){ 
            //alert(document.forms[i].elements[j].type);
            if (document.forms[i].elements[j].type != "button"){
                champTemp = encodeURIComponent(document.forms[i].elements[j].name);
                valeurTemp = encodeURIComponent(document.forms[i].elements[j].value);
                /*
                champTemp = escape(document.forms[i].elements[j].name);
                valeurTemp = escape(document.forms[i].elements[j].value);
                */
                urlxml += "&" + champTemp + "=" + valeurTemp;    
                
            }                
        }
    }    
    var xhrCmd = getXHR();
    xhrCmd.onreadystatechange = function(){
        if (xhrCmd.readyState==4 && xhrCmd.status == 200){
			var docXML = new ActiveXObject("Microsoft.XMLDOM");
            try{ 
                docXML.loadXML(xhrCmd.responseText); 
            }
            catch(e){
                alert("appelBoutonCmd():"+ e.name + ":\n" + e.message);
            }

            var strTest = "";
            var strMessages = "";        
            var currentTable = "";
            
            if(docXML.documentElement.childNodes(0).text == "false"){
                //Une erreur est retournée par la table, on arrete ici.//
                strMessages = docXML.documentElement.childNodes(1).childNodes(0).childNodes(0).text; 
                frmEdit.proceed.value = "false";
            }
            else{
				
                frmEdit.proceed.value = "true";
                for (i = 0; i < docXML.documentElement.childNodes.length; i++){ 
    
                    if (docXML.documentElement.childNodes(i).nodeName != currentTable){   
                        currentTable = docXML.documentElement.childNodes(i).nodeName; 
                        
                        try{
                            eval("document.forms[0]." + currentTable + "_pos").value = docXML.documentElement.childNodes(i).childNodes(0).childNodes(0).text;
                            eval("document.forms[0]." + currentTable + "_count").value = docXML.documentElement.childNodes(i).childNodes(0).childNodes(1).text;
                            eval("document.forms[0]." + currentTable + "_calledBy").value = docXML.documentElement.childNodes(i).childNodes(0).childNodes(2).text;
                        }
                        catch(e){
                            //alert(e.name + ":\n" + e.message);
                        }
                    }
                    if (docXML.documentElement.childNodes(i).nodeName == document.forms[0].tableActive.value){                  
                        position = docXML.documentElement.childNodes(i).childNodes(0).childNodes(0).text;
                        count = docXML.documentElement.childNodes(i).childNodes(0).childNodes(1).text;
                        calledBy = docXML.documentElement.childNodes(i).childNodes(0).childNodes(2).text;   
                        
                    }
                    
                    if (docXML.documentElement.childNodes(i).nodeName == "MSG"){
                        strMessages = docXML.documentElement.childNodes(i).childNodes(0).childNodes(0).text;
                    }
                    if (docXML.documentElement.childNodes(i).nodeName == "EVALSECTION"){
                        //alert(docXML.documentElement.childNodes(i).childNodes(0).childNodes(0).text);
                        eval(docXML.documentElement.childNodes(i).childNodes(0).childNodes(0).text);
                    }
    
                    for (j = 0; j < docXML.documentElement.childNodes(i).childNodes.length; j++){
                        for (k = 0; k < docXML.documentElement.childNodes(i).childNodes(j).childNodes.length; k++){                
    
                            try{                            
                                eval("document.getElementById('" + docXML.documentElement.childNodes(i).childNodes(j).childNodes(k).nodeName + "')").value = docXML.documentElement.childNodes(i).childNodes(j).childNodes(k).text;                          
                            }
                            catch(e){
                                //alert(e.name + ":\n" + e.message);
                            }
                        }                
                    }   
                }        
                
                document.forms[0].txtPos.value = position;
                document.forms[0].txtCount.value = count;
                document.forms[0].calledBy.value = calledBy;
				
                afterMove();
                appelListeXML();
                oldValueCreer();            
                
            }
            sys_loader.className = "ongletHidden";
            afficheMessageErreur(strMessages);
        }
    }
    //prompt("",urlxml);
    xhrCmd.open("POST", frmEdit.action , false) ;
	xhrCmd.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	xhrCmd.send(urlxml);
}



function appelListeXML(){
    var fields = "";
    
    if (document.forms[0].listesActives.value != ""){        
        arrListes = frmEdit.listesActives.value.split(",");      
        if (arrListes.length > 0){
            xhr1 = getXHR();
            var table1 = arrListes[0].substring(arrListes[0].indexOf("_") + 1);            
            var urlxml_1 = "../../lib/jsp/listeXML.jsp?table=" + table1 + "&time=" + (new Date()).getTime() + "&wId=" + frmEdit.wId.value + "&fields=" + eval("frmEdit." + arrListes[0] + "_fields.value");
            
            xhr1.onreadystatechange = function(){
                if (xhr1.readyState==4 && xhr1.status == 200){
                    try{
                        var nomListe = frmEdit.listesActives.value.split(",")[0];
                        docXSL_1.async = false;
                        docXSL_1.load(nomListe + ".xsl");
                        docXMLListe_1.loadXML(xhr1.responseText);
                        eval(nomListe).innerHTML = docXMLListe_1.transformNode(docXSL_1);
                        eval(nomListe + "_div").scrollTop = arrScrolls[0];
                    }
                    catch(e){
                    }
                }
            }
            xhr1.open("POST", urlxml_1 , true) ;
            xhr1.send(null);
        }
        if (arrListes.length > 1){
            xhr2 = getXHR();
            var table2 = arrListes[1].substring(arrListes[1].indexOf("_") + 1);            
            var urlxml_2 = "../../lib/jsp/listeXML.jsp?table=" + table2 + "&time=" + (new Date()).getTime() + "&wId=" + frmEdit.wId.value + "&fields=" + eval("frmEdit." + arrListes[1] + "_fields.value");
            
            xhr2.onreadystatechange = function(){
                if (xhr2.readyState==4 && xhr2.status == 200){
                    try{
                        var nomListe = frmEdit.listesActives.value.split(",")[1];
                        docXSL_2.async = false;
                        docXSL_2.load(nomListe + ".xsl");
                        docXMLListe_2.loadXML(xhr2.responseText);
                        eval(nomListe).innerHTML = docXMLListe_2.transformNode(docXSL_2);
                        eval(nomListe + "_div").scrollTop = arrScrolls[1];
                    }
                    catch(e){
                    }
                }
            }
            xhr2.open("POST", urlxml_2 , true) ;
            xhr2.send(null);
        }
        

        if (arrListes.length > 2){
            xhr3 = getXHR();
            var table3 = arrListes[2].substring(arrListes[2].indexOf("_") + 1);            
            var urlxml_3 = "../../lib/jsp/listeXML.jsp?table=" + table2 + "&time=" + (new Date()).getTime() + "&wId=" + frmEdit.wId.value + "&fields=" + eval("frmEdit." + arrListes[2] + "_fields.value");
            
            xhr3.onreadystatechange = function(){
                if (xhr3.readyState==4 && xhr3.status == 200){
                    try{
                        var nomListe = frmEdit.listesActives.value.split(",")[2];
                        docXSL_3.async = false;
                        docXSL_3.load(nomListe + ".xsl");
                        docXMLListe_3.loadXML(xhr3.responseText);
                        eval(nomListe).innerHTML = docXMLListe_2.transformNode(docXSL_3);
                        eval(nomListe + "_div").scrollTop = arrScrolls[2];
                    }
                    catch(e){
                    }
                }
            }
            xhr3.open("POST", urlxml_3 , true) ;
            xhr3.send(null);
        }

    }
    
}
function transformXML(xmlUrl,xslUrl,nomSpan){
    var xhr1 = getXHR();
    xhr1.onreadystatechange = function(){
        if (xhr1.readyState==4 && xhr1.status == 200){
            try{
                docXMLListe = new ActiveXObject("Microsoft.XMLDOM");
                docXSL = new ActiveXObject("Microsoft.XMLDOM");
                docXSL.async = false;
                docXSL.load(xslUrl);
                docXMLListe.loadXML(xhr1.responseText);
                eval(nomSpan).innerHTML = docXMLListe.transformNode(docXSL);
                //eval(nomListe + "_div").scrollTop = arrScrolls[0];
            }
            catch(e){
				alert("transformXML:"+ e.message);
            }
        }
    }
    xhr1.open("GET", xmlUrl , true) ;
    xhr1.send(null);
}


function flashMode(){
    if (texteBouton.innerText == "Supprimer"){
        if (texteBouton.style.visibility == "hidden")
            texteBouton.style.visibility = "visible";
        else
            texteBouton.style.visibility = "hidden";
        setTimeout("flashMode()",600);
    }
}
function getOldValue(fld){
    if(fld.tagName == "LABEL"){
        return oldValueLabels[fld.sourceIndex];
    }
    else{
        return oldValue[fld.sourceIndex];
    }
}
function oldValueCreer(){
    
    var currentDiv = eval(frmEdit.tableActive.value + "_screen");
    var nb = currentDiv.all.length;

    for (var i=0; i < nb ;i++){
        if(currentDiv.all[i].tagName == "LABEL"){
            oldValueLabels[currentDiv.all[i].sourceIndex] = currentDiv.all[i].innerText;
        }
        else{
            oldValue[currentDiv.all[i].sourceIndex] = currentDiv.all[i].value;

        }
    }    
    /*
    
    nb = document.all.length;
    for (var i=0; i < nb ;i++){
        if(document.all(i).tagName == "LABEL"){
            oldValueLabels[document.all[i].sourceIndex] = document.all[i].innerText;
        }
    } 
    */   
}

function oldValueReset(){    
    var currentDiv = eval(frmEdit.tableActive.value + "_screen");
    var nb = currentDiv.all.length;
    for (var i=0; i < nb ;i++){ 
        //alert(currentDiv.all[i].sourceIndex);
        if(currentDiv.all[i].tagName == "LABEL"){
            currentDiv.all[i].innerText = oldValueLabels[currentDiv.all[i].sourceIndex];
        }
        else{
            currentDiv.all[i].value = oldValue[currentDiv.all[i].sourceIndex];        
        }
    }
    /*    
    nb = document.all.length;
    alert("nb all:"+ nb);
    for (var i=0; i < nb ;i++){
        
        if(document.all(i).tagName == "LABEL"){
            //document.all(i).innerText = "";
            //alert(document.all(i).innerText);
             document.all[i].innerText = oldValueLabels[document.all[i].sourceIndex];
        }
    }
    */   
    
}

function editFrm(command){
    var curCount = eval("frmEdit." + frmEdit.tableActive.value + "_count.value");
    
    if((command == "Modifier" || command == "Supprimer") && curCount == 0){
        afficheMessageErreur("Rien à " + command + "!");
    }
    else{
        if(doEvent("before",command)){
            
            oldValueCreer();

            setTabIndex();            
            maxLen();

            //alert("apres max len");

            texteBouton.style.visibility = "visible";    
            texteBouton.innerText = command;
            if(command !="Supprimer"){
                texteBouton.style.fontSize="12pt";
                texteBouton.style.color = "black";
                lockAllFld(false);
            }
            else{
                //beep();
                texteBouton.style.color = "#BC0000";
                texteBouton.style.fontSize ="18pt";
                flashMode();
            }
            
            frmEdit.command.value = command;        

            showOkCancel();

            if(command == "Ajouter" || command == "Filtrer")
                clearAllFldValue();
            if (command == "Filtrer")
                setNoLimitLen();

            doEvent("beforeEdit",command);
            
            lockFld(frmEdit.txtPos,true);
            
            //if(command != "Supprimer")
            //  setFocus();

                //alert("test");
        }
    }
}

function editFrmOk(){ 
    if(pressOk == false){
        frmEdit.txtPos.focus();
        allUpperCase();        
        if (getMode() == "Filtrer"){
            go();
        }        
        editFrmOk_1();
    }
}
function editFrmOk_1(){
    
    if(getReadySubmit() == "abort")
        return;
    if(getReadySubmit() == "true"){
        pressOk = true;
        wait(); 
        
        if(doEvent("afterEdit",frmEdit.command.value)){
            if(getReadySubmit() == "abort")
                return;

            if (frmEdit.calledBy.value.length == 0)
                frmEdit.calledBy.value = frmEdit.tableActive.value;             
            
            frmEdit.proceed.value = "wait";
            setTimeout("showLoader();",10);
            appelBoutonCmd();
            doEvent("after",frmEdit.command.value);
            afterDisplay();
            afterOK();
            setTimeout("hideLoader();",200);
        }
        else{
            pressOk = false;
            go();
        }
    }
    else{
        setTimeout("editFrmOk_1()",500);
    }
}

function afterOK(){
    if (frmEdit.proceed.value != "wait"){
        if (frmEdit.proceed.value == "true"){       
            texteBouton.innerText = '';            
            lockAllFld(true);

            hideOkCancel();
            lockFld(frmEdit.txtPos,false);
            frmEdit.txtPos.focus();
            frmEdit.txtPos.select();
            go();
            pressOk = false;
            //alert(frmEdit.txtPos.value);
            hideBtn(frmEdit.txtPos.value);
            //afterCancel();
        }
        else{
            pressOk = false;
            go();
        }
    }
    else{
        setTimeout("afterOK()",200);
    }
}

function wait(){     
    frmEdit.readySubmit.value = "false";
}

function go(){
    frmEdit.readySubmit.value = "true";
}

function abort(){
    pressOk = false;
    frmEdit.readySubmit.value = "abort";
}

function getReadySubmit(){
    return frmEdit.readySubmit.value;
}

function callPage(frame,page){    
    wait();
    eval("parent.parent."+ frame +".location = \""+ page + "\";");
}

function editFrmCancel(){
    if (beforeCancel()){
        
        if (position > 0){
            texteBouton.innerText = '';
            //frmEdit.reset();
            //Faire le reset "maison"
            oldValueReset();
            lockAllFld(true);
            hideOkCancel();
            lockFld(frmEdit.txtPos,false);
            frmEdit.txtPos.focus();
            frmEdit.txtPos.select();
            afterCancel();
            afficheMessageErreur("");
        }
        else{
            position0cancel();
        }
    }
}

function delMessage(){    
    afficheMessageErreur("");    
}

function showOkCancel(){
    
    frmEdit.ok.style.visibility = 'visible';
    frmEdit.cancel.style.visibility = 'visible';
    
    frmEdit.premier.style.visibility = "hidden";
    frmEdit.precedent.style.visibility = "hidden";
    frmEdit.suivant.style.visibility = "hidden";
    frmEdit.dernier.style.visibility = "hidden";
    frmEdit.ajouter.style.visibility = "hidden";
    frmEdit.modifier.style.visibility = "hidden";
    frmEdit.supprimer.style.visibility = "hidden";
    frmEdit.filtrer.style.visibility = "hidden";
    frmEdit.courant.style.visibility = "hidden";
    frmEdit.parcourir.style.visibility = "hidden";
    frmEdit.orderby.style.visibility = "hidden";
    showLoupe("visible");
}

function hideOkCancel(){    
    frmEdit.ok.style.visibility = 'hidden';
    frmEdit.cancel.style.visibility = 'hidden';

    frmEdit.premier.style.visibility = "visible";
    frmEdit.precedent.style.visibility = "visible";
    frmEdit.suivant.style.visibility = "visible";
    frmEdit.dernier.style.visibility = "visible";
    frmEdit.ajouter.style.visibility = "visible";
    frmEdit.modifier.style.visibility = "visible";
    frmEdit.supprimer.style.visibility = "visible";
    frmEdit.filtrer.style.visibility = "visible";
    frmEdit.courant.style.visibility = "visible";
    frmEdit.parcourir.style.visibility = "visible";
    frmEdit.orderby.style.visibility = "visible";
    showLoupe("hidden");
}

function hideBtn(position){
//alert(position);
    if(position ==0){
        frmEdit.premier.style.visibility = "hidden";
        frmEdit.precedent.style.visibility = "hidden";
        frmEdit.suivant.style.visibility = "hidden";
        frmEdit.dernier.style.visibility = "hidden";
        frmEdit.modifier.style.visibility = "hidden";
        frmEdit.supprimer.style.visibility = "hidden";
        frmEdit.courant.style.visibility = "hidden";
        frmEdit.parcourir.style.visibility = "hidden";
        frmEdit.orderby.style.visibility = "hidden";
        showLoupe("hidden");
    }
    else{
        frmEdit.premier.style.visibility = "visible";
        frmEdit.precedent.style.visibility = "visible";
        frmEdit.suivant.style.visibility = "visible";
        frmEdit.dernier.style.visibility = "visible";
        frmEdit.modifier.style.visibility = "visible";
        frmEdit.supprimer.style.visibility = "visible";
        frmEdit.courant.style.visibility = "visible";
        frmEdit.parcourir.style.visibility = "visible";
        frmEdit.orderby.style.visibility = "visible";
    }   
}

function maxLen(){
    try{
        eval(frmEdit.tableActive.value + "_maxLen();");
    }
    catch(e){}
}

function changeMode(command){
    if (command != "null")
        editFrm(command);

    frmEdit.txtPos.focus();
    frmEdit.txtPos.select();
}

function position0cancel(){    
    delMessage();

    showLoupe("hidden");
    texteBouton.innerText = '';

    oldValueReset();

    lockAllFld(true);
    frmEdit.ok.style.visibility = 'hidden';
    frmEdit.cancel.style.visibility = 'hidden';
    frmEdit.ajouter.style.visibility = "visible";
    frmEdit.filtrer.style.visibility = "visible";
    lockFld(frmEdit.txtPos,false);
    frmEdit.txtPos.focus();
    frmEdit.txtPos.select();
    afterCancel();   
}

function executeLoupe(nomLoupe){
    if(window.event.keyCode == "113" && getMode() != ""){           // F2
        eval("document.images."+ nomLoupe +".click()");
    }
}

function ouvrirRecherche2(pageName, w, h){
    //var vtop = (screen.height - 200)/2;
    var vtop = 100;
    var vleft = (screen.width - w) /2;
    var path = window.location.pathname.substring(0,window.location.pathname.lastIndexOf("/")+ 1);
    var wdir = path.substring(0, path.indexOf("/",1));
    path = wdir + "/lib/jsp/indexfind.jsp?pageName="+ path + pageName;
    var val = eval("window.showModalDialog('"+ path +"','find','dialogWidth: "+ w +"px;dialogHeight: "+ h +"px;dialogLeft:"+ vleft +";dialogTop:"+ vtop +"px;center: Yes;help: No;status: No')");
    
    return val;
}
function ouvrirAjaxWin(url, titre){
    if(aUtil != undefined){
        //alert(url);
        aUtil.href = url;
        aUtil.title = titre;
        aUtil.click();
    }
    else{
        alert("Veuillez creer le lien suivant:\n\n <a id=aUtil class=\"thickbox\" style=\"visibility:hidden\"></a>");
    }
}
function ouvrirRecherche(pageName,ctl,chmRst,vFonction,winId,variable){
    var vtop = (screen.height -500)/2;
    var vleft = (screen.width - 500) /2;    
    
    var path = window.location.pathname.substring(0,window.location.pathname.lastIndexOf("/")+ 1);
    var wdir = path.substring(0, path.indexOf("/",1));
    path = wdir + "/lib/jsp/indexfind.jsp?pageName="+ path + pageName + "&wId=" + winId +"&champRst="+ chmRst +"&champTarget="+ ctl +"&fonctionToDo="+vFonction + "&variable="+variable;
    var val = eval("window.showModalDialog('"+ path +"','find','dialogWidth: 500px;dialogHeight: 500px;dialogLeft:"+ vleft +";dialogTop:"+ vtop +"px;center: Yes;help: No;status: No')");
    
    if(val != null && val != ""){

        eval("frmEdit."+ ctl +".value = \""+ val + "\"");
        eval("frmEdit."+ ctl +".focus();");

        if(vFonction != null && vFonction != "")
            eval(vFonction);
    }
}

function ouvrirRecherche3(pageName,ctl,chmRst,vFonction,winId,variable,widht,height){
    var vtop = (screen.height - height)/2;
    var vleft = (screen.width - widht) /2;    
    
    var path = window.location.pathname.substring(0,window.location.pathname.lastIndexOf("/")+ 1);
    var wdir = path.substring(0, path.indexOf("/",1));
    path = wdir + "/lib/jsp/indexfind.jsp?pageName="+ path + pageName + "&wId=" + winId +"&champRst="+ chmRst +"&champTarget="+ ctl +"&fonctionToDo="+vFonction + "&variable="+variable;
    var val = eval("window.showModalDialog('"+ path +"','find','dialogWidth: "+ widht+" px;dialogHeight: "+ height +"px;dialogLeft:"+ vleft +";dialogTop:"+ vtop +"px;center: Yes;help: No;status=no')");
    if(val != null && val != ""){
        eval("frmEdit."+ ctl +".value = \""+ val + "\"");
        if(vFonction != null && vFonction != "")
            eval(vFonction);
    }
}

function ouvrirBrowserAJAX(purl,pheight,pwidth,wId,table, XSLFile){
    var vtop = (screen.height - pheight) /2;
    var vleft = (screen.width - pwidth) /2;
    //alert("window.open('"+ purl + "&wId="+ wId +"&premiereFois=true&table=' + table + '&browserXSL=' + XSLFile,'browser','width="+ pwidth +",height="+ pheight +",titlebar=no,toolbar=no,menubar=no,left="+ vleft +",top="+ vtop +"')");
    var browser = eval("window.open('"+ purl + "&wId="+ wId +"&premiereFois=true&table=' + table + '&browserXSL=' + XSLFile,'browser','width="+ pwidth +",height="+ pheight +",titlebar=no,toolbar=no,menubar=no,left="+ vleft +",top="+ vtop +"')");
    browser.opener = this;
}

function doEvent(beforeWhat,command){
    var returnVal = "";
    switch (command){
        case 'Modifier': 
            command = "Update";
            break;
        case 'Supprimer': 
            command = "Delete";
            break;
        case 'Ajouter': 
            command ="Add";
            break;
        case 'Filtrer': 
            command = "Query";
            break;
        case 'Suivant': 
            command = "Next";
            break;
        case 'Précédent': 
            command = "Previous";
            break;
        case 'Dernier': 
            command = "Last";
            break;
        case 'Premier': 
            command = "First";
            break;
        case 'moveTo': 
            command = "MoveTo";
            break;
        case 'Courant': 
            command = "Current";
            break;
        case 'changeOrderBy':
            command = "ChangeOrderBy";
            break;
    }

    returnVal = eval(beforeWhat+command+"()");
    return returnVal;
}

function afterCancel(){
    try{
        eval(frmEdit.tableActive.value + "_afterCancel()");
    }
    catch(e){}
}
function afterDisplay(){

    try{
        eval(frmEdit.tableActive.value + "_afterDisplay()");
    }
    catch(e){}
}
function afterEditUpdate(){
    try{
		if(typeof eval("window."+frmEdit.tableActive.value + "_afterEditUpdate") == 'function'){
			return eval(frmEdit.tableActive.value + "_afterEditUpdate()");
		}
		else{
			return true;
		}
    }
    catch(e){        
		alert("_afterEditUpdate()\n\n"+  e.name +"\n\n"+ e.message);
        return false;
    }
}

function afterEditDelete(){
    try{
		if(typeof eval("window."+frmEdit.tableActive.value + "_afterEditDelete") == 'function'){
			return eval(frmEdit.tableActive.value + "_afterEditDelete()");
		}
		else{
			return true;
		}
    }
    catch(e){        
		alert("_afterEditDelete()\n\n"+  e.name +"\n\n"+ e.message);
        return false;
    }
}

function afterEditQuery(){
    try{
		if(typeof eval("window."+frmEdit.tableActive.value + "_afterEditQuery") == 'function'){
			return eval(frmEdit.tableActive.value + "_afterEditQuery()");
		}
		else{
			return true;
		}
    }
    catch(e){        
		alert("_afterEditQuery()\n\n"+  e.name +"\n\n"+ e.message);
        return false;
    }
}
function afterEditAdd(){
	try{
		if(typeof eval("window."+frmEdit.tableActive.value + "_afterEditAdd") == 'function'){
			return eval(frmEdit.tableActive.value + "_afterEditAdd()");
		}
		else{
			return true;
		}
    }
    catch(e){        
		alert("_afterEditAdd()\n\n"+  e.name +"\n\n"+ e.message);
        return false;
    }
}
function afterUpdate(){
    try{
		if(typeof eval("window."+frmEdit.tableActive.value + "_afterUpdate") == 'function'){
			return eval(frmEdit.tableActive.value + "_afterUpdate()");
		}
		else{
			return true;
		}
    }
    catch(e){        
		alert("_afterUpdate()\n\n"+  e.name +"\n\n"+ e.message);
        return false;
    }
}

function afterDelete(){
    try{
		if(typeof eval("window."+frmEdit.tableActive.value + "_afterDelete") == 'function'){
			return eval(frmEdit.tableActive.value + "_afterDelete()");
		}
		else{
			return true;
		}
    }
    catch(e){        
		alert("_afterDelete()\n\n"+  e.name +"\n\n"+ e.message);
        return false;
    }
}

function afterQuery(){
	try{
		if(typeof eval("window."+frmEdit.tableActive.value + "_afterQuery") == 'function'){
			return eval(frmEdit.tableActive.value + "_afterQuery()");
		}
		else{
			return true;
		}
    }
    catch(e){        
		alert("_afterQuery()\n\n"+  e.name +"\n\n"+ e.message);
        return false;
    }
}

function afterAdd(){
    try{
		if(typeof eval("window."+frmEdit.tableActive.value + "_afterAdd") == 'function'){
			return eval(frmEdit.tableActive.value + "_afterAdd()");
		}
		else{
			return true;
		}
    }
    catch(e){        
		alert("_afterAdd()\n\n"+  e.name +"\n\n"+ e.message);
        return false;
    }
}

function afterNext(){ 
    try{
        return eval(frmEdit.tableActive.value + "_afterNext()");
    }
    catch(e){        
        afterMove(); 
    }    
}

function afterPrevious(){ 
    try{
        return eval(frmEdit.tableActive.value + "_afterPrevious()");
    }
    catch(e){        
        afterMove(); 
    }   
}

function afterFirst(){ 
    try{
        return eval(frmEdit.tableActive.value + "_afterFirst()");
    }
    catch(e){        
        afterMove(); 
    }   
}

function afterLast(){ 
    try{
        return eval(frmEdit.tableActive.value + "_afterLast()");
    }
    catch(e){        
        afterMove(); 
    } 
}

function afterCurrent(){ 
    try{
        return eval(frmEdit.tableActive.value + "_afterCurrent()");
    }
    catch(e){        
        afterMove(); 
    } 
}

function afterMoveTo(){
    try{
        return eval(frmEdit.tableActive.value + "_afterMoveTo()");
    }
    catch(e){        
        afterMove(); 
    } 
}

function afterChangeOrderBy(){
    try{
        eval(frmEdit.tableActive.value + "_afterChangeOrderBy()");
    }
    catch(e){}
}

function afterMove(){
    try{
        eval(frmEdit.tableActive.value + "_afterMove()");
    }
    catch(e){}   
}

function beforeNext(){
    try{
        var curPos = parseInt(eval("frmEdit." + frmEdit.tableActive.value + "_pos.value"));
        var curCount = parseInt(eval("frmEdit." + frmEdit.tableActive.value + "_count.value"));
        //alert(curPos + " : " + position);
        if (curPos < curCount){
            frmEdit.txtPos.value = curPos + 1;
            //alert(frmEdit.txtPos.value);
        }
        return eval(frmEdit.tableActive.value + "_beforeNext()");
    }
    catch(e){        
        return true;
    }
}

function beforeCurrent(){
    try{
        return eval(frmEdit.tableActive.value + "_beforeCurrent()");
    }
    catch(e){        
        return true;
    }
}

function beforePrevious(){
    try{
        return eval(frmEdit.tableActive.value + "_beforePrevious()");
    }
    catch(e){        
        return true;
    }
}

function beforeFirst(){
    try{
        return eval(frmEdit.tableActive.value + "_beforeFirst()");
    }
    catch(e){        
        return true;
    }
}

function beforeLast(){
    try{
        return eval(frmEdit.tableActive.value + "_beforeLast()");
    }
    catch(e){        
        return true;
    }
}

function beforeBrowse(){
    try{
        return eval(frmEdit.tableActive.value + "_beforeBrowse()");
    }
    catch(e){        
        return true;
    }
}

function beforeOrderBy(){
    try{
        return eval(frmEdit.tableActive.value + "_beforeOrderBy()");
    }
    catch(e){        
        return true;
    }
}

function beforeQuery(){
    try{
        return eval(frmEdit.tableActive.value + "_beforeQuery()");
    }
    catch(e){        
        return true;
    }
}

function beforeUpdate(){
    try{
        return eval(frmEdit.tableActive.value + "_beforeUpdate()");
    }
    catch(e){        
        return true;
    }
}

function beforeAdd(){
    try{
        return eval(frmEdit.tableActive.value + "_beforeAdd()");
    }
    catch(e){        
        return true;
    }
}

function beforeDelete(){
    try{        
        return eval(frmEdit.tableActive.value + "_beforeDelete()");
    }
    catch(e){           
        return true;
    }
}
function beforeMoveTo(){
    try{        
        return eval(frmEdit.tableActive.value + "_beforeMoveTo()");
    }
    catch(e){           
        return true;
    }
}
function beforeCancel(){    
    try{
        return eval(frmEdit.tableActive.value + "_beforeCancel()");
    }
    catch(e){        
        return true;
    }
}

function beforeChangeOrderBy(){
    try{
        return eval(frmEdit.tableActive.value + "_beforeChangeOrderBy()");
    }
    catch(e){        
        return true;
    }
}

function beforeEditDelete(){
    try{
        return eval(frmEdit.tableActive.value + "_beforeEditDelete()");
    }
    catch(e){        
        return true;
    }
}

function beforeEditUpdate(){
    try{
        return eval(frmEdit.tableActive.value + "_beforeEditUpdate()");
    }
    catch(e){        
        return true;
    }
}

function beforeEditAdd(){
    try{
        return eval(frmEdit.tableActive.value + "_beforeEditAdd()");
    }
    catch(e){        
        return true;
    }
}

function beforeEditQuery(){
    try{
        return eval(frmEdit.tableActive.value + "_beforeEditQuery()");
    }
    catch(e){        
        return true;
    }
}

function callOrderByWindow(table, origOrderBy, wId){
	var xdpi = screen.deviceXDPI;
	var ydpi = screen.deviceYDPI;
    var newOrderBy = window.showModalDialog('../../lib/jsp/orderBy.jsp?table=' + table + '&orderByOrig=' + origOrderBy.value,'orderby' + wId,"dialogHeight:"+ (xdpi / 96 * 500) +"px;dialogWidth:"+ (ydpi / 96 * 950) +"px;resizable:no");
    
    //alert(newOrderBy);
    if (newOrderBy != null){
        //var orderTable = eval(orderTable.value);
        //alert(origOrderBy.value);
        origOrderBy.value = newOrderBy;
        changeOrderBy(origOrderBy.value, table,false);
    }
}


function setTabIndex(){
    try{
        eval(frmEdit.tableActive.value + "_tabIndex();");
    }
    catch(e){}
}

function getMode(){
    try{
        return texteBouton.innerText;
    }
    catch(e){
        //retourne filtrer sur le textebouton n'existe pas dans les find ou ailleur
        return "Ajouter";
    }
}
function setMode(str){
    texteBouton.innerText = str;
}
var old_keyDown="";
function desactiveToucheOnglet(nFunction){
    old_keyDown = document.onkeydown;
    if(nFunction != null){
        document.onkeydown = nFunction;
    }
    else{
        document.onkeydown = null;        
    }
}
function activerToucheOnglet(){
    document.onkeydown = old_keyDown;
}
function onEventBase(){
    if (event.keyCode==13){ // enter = tab
        event.keyCode=9;
    }
}
function onEvent(){
    if(getMode() != ""){
        if (event.keyCode==13) // enter = tab
            event.keyCode=9;
        else{
            if(event.keyCode == 123) {// OK - F12
                frmEdit.txtPos.focus();
                frmEdit.ok.click();
				event.returnValue=false;
            }
            else
                if(event.keyCode == 120) // Cancel - F9
                    frmEdit.cancel.click();
                else
                    if(event.keyCode == 122){ // Ditto - F11
                        if(event.srcElement.type == "select-one"){
                            event.srcElement.value = oldValue[event.srcElement.sourceIndex];
                        }
                        else{
                            event.srcElement.innerText = oldValue[event.srcElement.sourceIndex];
                        }
                        event.keyCode = 9;
                    }
                    else
                        if(event.keyCode == 121) // - F10
                            event.returnValue=false;
                        // ***** la touche F10 ne fait rien*******
        }
    }
    else{

        event.returnValue = false;
        switch(event.keyCode){
            case 114: // F3 
                event.keyCode = 0;
                frmEdit.filtrer.click();
                break;
            case 115: // F4 
                frmEdit.parcourir.click();
                break;
            case 116: // F5
                event.keyCode =0;
                frmEdit.courant.click();
                break;
            case 117: // F6
                event.keyCode = 0;
                frmEdit.supprimer.click();
                break;
            case 118: // F7
                frmEdit.modifier.click();
                break;
            case 119: // F8
                frmEdit.ajouter.click();
                break;
            case 38: 
                frmEdit.precedent.click();
                break;
            case 40: 
                frmEdit.suivant.click();
                break;    
            case 37: 
                frmEdit.precedent.click();
                break;
            case 39: 
                frmEdit.suivant.click();
                break;
            case 36: 
                frmEdit.premier.click();
                break;
            case 35: 
                frmEdit.dernier.click();
                break;
            case 33: 
                frmEdit.precedent.click();
                break;
            case 34: 
                frmEdit.suivant.click();
                break;
            case 65:
                frmEdit.ajouter.click();
                break;
            case 85:
                frmEdit.modifier.click();
                break;
            case 81:
                event.keyCode = 0;
                frmEdit.filtrer.click();
                break;
            case 78: 
                frmEdit.suivant.click();
                break;    
            case 80: 
                frmEdit.precedent.click();
                break;
            default:
                
                if (((event.keyCode >48 && event.keyCode <58) || (event.keyCode >= 96 && event.keyCode <= 105)) && event.ctrlKey == false){
                    //alert(eval("document.getElementById(\"btn"+(event.keyCode -48)));
                    if (event.keyCode >48 && event.keyCode <58){
                        if (eval("document.anchors(\"btn"+(event.keyCode -48)+"\") !=null")){
                            eval("document.anchors(\"btn"+(event.keyCode -48)+"\").click();");
                        }
                    }
                    else if (event.keyCode >= 96 && event.keyCode <= 105){
                        
                        if (eval("document.anchors(\"btn"+(event.keyCode -96)+"\") !=null")){
                            eval("document.anchors(\"btn"+(event.keyCode -96)+"\").click();");
                        }
                    }
                    
                }
                else{
                    
                    if(((event.keyCode >=48 && event.keyCode <58) || (event.keyCode >= 96 && event.keyCode <= 105) || event.keyCode == 8) && event.ctrlKey){
                        //alert(event.keyCode + " : " + event.ctlKey);
                        
                        event.returnValue = false;
                        var kcode;
                        if (event.keyCode >=48 && event.keyCode <58){
                            kcode = event.keyCode - 48;
                        }
                        else{
                            if (event.keyCode == 8)                               
                                kcode = 100;                            
                            else
                                kcode = event.keyCode - 96;                            
                         }
                         
                         if (txtSelected){                            
                            frmEdit.txtPos.value = "";
                            txtSelected = false;
                         }
                         
                         if (kcode != 100)
                            frmEdit.txtPos.value += kcode;                         
                         else                           
                            frmEdit.txtPos.value = frmEdit.txtPos.value.substring(0, frmEdit.txtPos.value.length - 1);
                    }
                    else{
                        //alert(event.srcElement.name);                        
                        if(event.keyCode == 13 && event.srcElement.name.indexOf("txtPos") >= 0 ){
                            
                            event.returnValue=false;
                            onEnterPosition();
                        }   
                    }                        
                }               
            }
        }
}
function onEventFind(){
    if (event.keyCode==13) // enter = tab
        event.keyCode=9;
    else if(event.keyCode == 123) {// OK - F12
        document.getElementById("ok").click();
    }
    else if(event.keyCode == 120){ // Cancel - F9
        document.getElementById("cancel").click();
    }
}
function onEnterPosition(){
    if (frmEdit.txtPos.value.length != 0){
        
        if(parseInt(frmEdit.txtPos.value) > parseInt(frmEdit.txtCount.value))
            frmEdit.txtPos.value = frmEdit.txtCount.value;

        frmEdit.command.value = "moveTo";        
        frmEdit.newPosition.value = frmEdit.txtPos.value; 
        waitForList = false;
        appelBoutonCmd();
    }
}
function showResultat(){
    resultat.style.visibility = 'visible';
    formulaire.style.visibility = 'hidden';
}
function showFormulaire(){
    formulaire.style.visibility = 'visible';
    resultat.style.visibility = 'hidden';
}
function shownull(){
    showFormulaire();
}
function doHelp(){
    alert("Touches:\n F1 - Aide\n F2 - Ouvrir les loupes \n F3 - Recherche \n F4 - Liste courante \n\n F5 - Rafraichir \n F6 - Supprimer \n F7 - Modifier \n F8 - Créer (Ajouter) \n\n F9 - Annuler \n F10 -  \n F11 - Idem  \n F12 - Exécuter (OK)");
    event.returnValue = false;
}

//**** LOOKUP XML ****//
var XMLSelect = "";
var XMLDisplay = "";
var XMLDataSource = "";
var XMLFuncToDo = "";
function setLookupSelect(val){
    XMLSelect = val;
}

function setLookupDisplay(val){
    XMLDisplay = val;
}

function setLookupDataSource(val){
    XMLDataSource = val;
}

function setLookupFuncToDo(val){
    XMLFuncToDo = val;
}

function lookup(continueScript){
    var posVir,
        posPtVir,
        dataSource;

    if (getMode() == "Filtrer"){
        if (XMLSelect.indexOf("'=") >= 0  ||
            XMLSelect.indexOf("'!=") >= 0  ||
            XMLSelect.indexOf("'>") > 0  ||
            XMLSelect.indexOf(":") >= 0  ||
            XMLSelect.indexOf("'<") >= 0){
            go();
            return;
            }
    }
    wait();

    dataSource = XMLDataSource
    posVir = dataSource.indexOf(",");
    posPtVir = dataSource.indexOf(";");
    if(posVir >-1)
        dataSource = dataSource.substring(0,posVir);
    else
        if(posPtVir > -1)
            dataSource = dataSource.substring(0,posPtVir);
    
    var urlxml="../../lib/jsp/cache.jsp?wId=" + frmEdit.wId.value + "&select=" + XMLSelect + "&display=" + XMLDisplay + "&fld=" + XMLDataSource + "&fonction=" + XMLFuncToDo;    

    var xhr = getXHR();
    xhr.onreadystatechange = function(){
        if (xhr.readyState==4 && xhr.status == 200){
            eval(xhr.responseText);
        }
    }
    if(continueScript == null)
        continueScript = true;
    xhr.open("POST", urlxml , continueScript) ;
    xhr.send(null);
}



//**** LOOKUP *****//

var XMLSelectSup = new Array(10);
var XMLDisplaySup = new Array(10);
var XMLDataSourceSup = new Array(10);
var XMLFuncToDoSup = new Array(10);
var xmlHttpLookupSup = new Array(10);

function setLookupSelectSup(no, val){
    XMLSelectSup[no] = val;
}

function setLookupDisplaySup(no, val){
    XMLDisplaySup[no] = val;
}

function setLookupDataSourceSup(no, val){
    XMLDataSourceSup[no] = val;
}

function setLookupFuncToDoSup(no, val){
    XMLFuncToDoSup[no] = val;
}

function lookupSup(no){
    var posVir,
        posPtVir,
        dataSource;

    if (getMode() == "Filtrer"){
        if (XMLSelectSup[no].indexOf("'=") > -1  ||
            XMLSelectSup[no].indexOf("'!=") > -1  ||
            XMLSelectSup[no].indexOf("'>") > -1  ||
            XMLSelectSup[no].indexOf(":") > -1  ||
            XMLSelectSup[no].indexOf("'<") > -1){
            go();
            return;
            }
    }
    wait();

    dataSource = XMLDataSourceSup[no];
    posVir = dataSource.indexOf(",");
    posPtVir = dataSource.indexOf(";");
    if(posVir >-1)
        dataSource = dataSource.substring(0,posVir);
    else
        if(posPtVir > -1)
            dataSource = dataSource.substring(0,posPtVir);
        
        var urlxml="../../lib/jsp/cache.jsp?wId=" + frmEdit.wId.value + "&select=" + XMLSelectSup[no] + "&display=" + XMLDisplaySup[no] + "&fld=" + XMLDataSourceSup[no];    
        try{
            xmlHttpLookupSup[no] = new ActiveXObject("Msxml2.XMLHTTP"); //GetXmlHttpObject(stateChangedLookup);  
        }
        catch(e){
            alert(e.name + ":\n" + e.message);
        }
        //alert("1");   
        xmlHttpLookupSup[no].onreadystatechange = eval("stateChangedLookupSup" + no);
        //alert("2");  
        xmlHttpLookupSup[no].open("POST", urlxml , true) ;
        //alert("3");  
        xmlHttpLookupSup[no].send(null);
}

function stateChangedLookupSup2() 
{ 
    try{
        //alert(xmlHttpLookupSup[2].readyState);
        if (xmlHttpLookupSup[2].readyState==4 || xmlHttpLookup[2].readyState=="complete"){
            //alert("stateChangedLookup Sup2!");
            eval(xmlHttpLookupSup[2].responseText);
        }
    }
    catch(e){

    }
} 

function stateChangedLookupSup1() 
{ 
    try{
        //alert(xmlHttpLookupSup[1].readyState);
        if (xmlHttpLookupSup[1].readyState==4 || xmlHttpLookup[1].readyState=="complete"){
            //alert("stateChangedLookup Sup1!");
            eval(xmlHttpLookupSup[1].responseText);
        }
    }
    catch(e){

    }
} 


/*function lookupSup(no){
    var posVir,
        posPtVir,
        dataSource;
        
    var valeurSelect = eval("parent.parent.cache" + no + ".frmCache.select.value");

    if (getMode() == "Filtrer"){
        
        if (eval(valeurSelect + ".indexOf(\"'=\") > -1")  ||
            eval(valeurSelect + ".indexOf(\"'!=\") > -1")  ||
            eval(valeurSelect + ".indexOf(\"'>\") > -1")  ||
            eval(valeurSelect + ".indexOf(\"'<\") > -1"))
            return;
    }

    dataSource = eval("parent.parent.cache" + no + ".frmCache.fld.value");
    posVir = dataSource.indexOf(",");
    posPtVir = dataSource.indexOf(";");
    if(posVir >-1)
        dataSource = dataSource.substring(0,posVir);
    else
        if(posPtVir > -1)
            dataSource = dataSource.substring(0,posPtVir);
   
    eval("parent.parent.cache" + no + ".frmCache.submit()");

}*/

function remplirListe(controle, units){    
    var liste = eval(controle);
    for (var y = liste.options.length; y >= 0; y--){
        liste.options.remove(y);
    }

    var c, elem, prec;
    prec = 0;        

    for (var i = 0; i < units.length; i++){
        c = units.charAt(i);

        if (c == ","){                
            if (prec != 0)
                elem = units.substring(prec + 1, i);                
            else
                elem = units.substring(prec, i);                

            var oOpt = document.createElement("OPTION");
            oOpt.text = elem;
            oOpt.value = elem;
            liste.add(oOpt);
            prec = i + 1;                
        }
    }
    var oOpt = document.createElement("OPTION");  

    if (prec != 0)
        elem = units.substring(prec + 1, units.length);
    else
        elem = units.substring(prec, units.length);

    oOpt.text = elem;
    oOpt.value = elem;
    liste.add(oOpt);              
}

function getHiddenInfo(){
    var nb = frmEdit.elements.length;
    var strMessage = "";
    var x = 0;
    for (var i=0; i < nb ;i++){
        if(frmEdit.elements[i].type == "hidden"){
            if (x < 3){
                strMessage += frmEdit.elements[i].name + ": " + frmEdit.elements[i].value + "\t\t\t";
            }
            else{
                x = 0;
                strMessage += frmEdit.elements[i].name + ": " + frmEdit.elements[i].value + "\n";
            }
            x++;
        }
        
        
    }
    alert(strMessage);
}

/****** IMAGES SEARCH ******/
function showLoupe(val){
    var nb = document.images.length;
    for (var i =0; i<nb ;i++){
        if(document.images[i].className == "imgLoupe"){
            var parts = document.images[i].name.split("_");
            //alert(document.images[i].name);
            if (parts[0] == frmEdit.tableActive.value){
                document.images[i].style.visibility = val;
            }
        }
    }
}

/****** ONGLETS *******/

function changeOnglet(idClick){
    if (getMode() == ""){
        rep = true;
        try{
            rep = eval(idClick + "_beforeChangeOnglet()");
        }
        catch(e){}
        if(rep){
            var etat;
            var i =0;
            var ongletActif;
            var ongletInactif;
    
            //saveScrollTops();
            
            while(i < arrTables.length){
            
                ongletActif = eval(arrTables[i] + "_onglet_actif");
                ongletInactif = eval(arrTables[i] + "_onglet_inactif");
                
                if(arrTables[i] == idClick){  
                
                    ongletActif.className = ongletActif.className.replace("ongletVisible","").replace("ongletHidden","") + " ongletVisible";
                    ongletInactif.className = ongletInactif.className.replace("ongletVisible","").replace("ongletHidden","") + " ongletHidden";
                }
                else{                        
                    ongletActif.className = ongletActif.className.replace("ongletVisible","").replace("ongletHidden","") + " ongletHidden";
                    ongletInactif.className = ongletInactif.className.replace("ongletVisible","").replace("ongletHidden","") + " ongletVisible";
                }
                i++;
            }
    
            i = 0;
            var curDiv;
    
            while(i < arrTables.length){            
                curDiv = eval(arrTables[i] + "_screen")            
                curDiv.style.visibility = "hidden";
                
                i++;            
            }
    
            eval(idClick + "_screen").style.visibility = "visible";
            frmEdit.txtPos.value = eval("frmEdit." + idClick + "_pos").value;
            frmEdit.txtCount.value = eval("frmEdit." + idClick + "_count").value;
            frmEdit.tableActive.value = idClick;
            frmEdit.table.value = idClick;        
            frmEdit.listesActives.value = eval("frmEdit." + idClick + "_listes").value;
            frmEdit.calledBy.value = eval("frmEdit." + idClick + "_calledBy").value;
            
            appelListeXML();
            afficheMessageErreur("");
            
            hideBtn(frmEdit.txtPos.value);
            
            try{
                eval(idClick + "_lookupAll()");
            }
            catch(e){}
            try{
                eval(idClick + "_afterChangeOnglet()");
            }
            catch(e){}
            try{
                eval(idClick + "_afterDisplay()");
            }
            catch(e){}
        }
    }
}



//---------- CALENDRIER DE FORMULAIRE ----------------------------------//
var inCalendar = false;
function exitCalendar() {
    //alert("exitCalendar");
    inCalendar = false;
    setTimeout("closeCalendar()",1000);
}
function keepCalendar() {
    inCalendar = true;
    //alert("keepCalendar");
}
function closeCalendar() {
    if(inCalendar == false) {
        ds_hi();
    }
}
// <!-- <![CDATA[

// Project: Dynamic Date Selector (DtTvB) - 2006-03-16
// Script featured on JavaScript Kit- http://www.javascriptkit.com
// Code begin...
// Set the initial date.
var ds_i_date = new Date();
ds_c_month = ds_i_date.getMonth() + 1;
ds_c_year = ds_i_date.getFullYear();

// Get Element By Id
function ds_getel(id) {
	return document.getElementById(id);
}

// Get the left and the top of the element.
function ds_getleft(el) {
	var tmp = el.offsetLeft;
	el = el.offsetParent
	while(el) {
		tmp += el.offsetLeft;
		el = el.offsetParent;
	}
	return tmp;
}
function ds_gettop(el) {
	var tmp = el.offsetTop;
	el = el.offsetParent
	while(el) {
		tmp += el.offsetTop;
		el = el.offsetParent;
	}
	return tmp;
}

// Output Element
var ds_oe = ds_getel('ds_calclass');
// Container
var ds_ce = ds_getel('ds_conclass');

// Output Buffering
var ds_ob = ''; 
function ds_ob_clean() {
	ds_ob = '';
}
function ds_ob_flush() {
	ds_oe.innerHTML = ds_ob;
        //alert(ds_oe.innerHTML);
	ds_ob_clean();
}
function ds_echo(t) {
	ds_ob += t;
}

var ds_element; // Text Element...

var ds_monthnames = [
'Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin',
'Juillet', 'Aout', 'Septembre', 'Octobre', 'Novembre', 'Décembre'
]; // You can translate it for your language.

var ds_daynames = [
'Dim', 'Lun', 'Mar', 'Me', 'Jeu', 'Ven', 'Sam'
]; // You can translate it for your language.

// Calendar template
function ds_template_main_above(t) {
	return '<table cellpadding="3" cellspacing="1" class="ds_tbl">'
	     + '<tr>'
		 + '<td class="ds_head" style="cursor: pointer" onclick="ds_py();">&lt;&lt;</td>'
		 + '<td class="ds_head" style="cursor: pointer" onclick="ds_pm();">&lt;</td>'
		 + '<td class="ds_head" style="cursor: pointer" onclick="ds_hi();" colspan="3">[Fermer]</td>'
		 + '<td class="ds_head" style="cursor: pointer" onclick="ds_nm();">&gt;</td>'
		 + '<td class="ds_head" style="cursor: pointer" onclick="ds_ny();">&gt;&gt;</td>'
		 + '</tr>'
	     + '<tr>'
		 + '<td colspan="7" class="ds_head">' + t + '</td>'
		 + '</tr>'
		 + '<tr>';
}

function ds_template_day_row(t) {
	return '<td class="ds_subhead">' + t + '</td>';
	// Define width in CSS, XHTML 1.0 Strict doesn't have width property for it.
}

function ds_template_new_week() {
	return '</tr><tr>';
}

function ds_template_blank_cell(colspan) {
	return '<td colspan="' + colspan + '"></td>'
}

function ds_template_day(d, m, y) {
	return '<td class="ds_cell" onclick="ds_onclick(' + d + ',' + m + ',' + y + ')">' + d + '</td>';
	// Define width the day row.
}

function ds_template_main_below() {
	return '</tr>'
	     + '</table>';
}

// This one draws calendar...
function ds_draw_calendar(m, y) {
	// First clean the output buffer.
	ds_ob_clean();
	// Here we go, do the header
	ds_echo (ds_template_main_above(ds_monthnames[m - 1] + ' ' + y));
	for (i = 0; i < 7; i ++) {
		ds_echo (ds_template_day_row(ds_daynames[i]));
	}
	// Make a date object.
	var ds_dc_date = new Date();
	ds_dc_date.setMonth(m - 1);
	ds_dc_date.setFullYear(y);
	ds_dc_date.setDate(1);
	if (m == 1 || m == 3 || m == 5 || m == 7 || m == 8 || m == 10 || m == 12) {
		days = 31;
	} else if (m == 4 || m == 6 || m == 9 || m == 11) {
		days = 30;
	} else {
		days = (y % 4 == 0) ? 29 : 28;
	}
	var first_day = ds_dc_date.getDay();
	var first_loop = 1;
	// Start the first week
	ds_echo (ds_template_new_week());
	// If sunday is not the first day of the month, make a blank cell...
	if (first_day != 0) {
		ds_echo (ds_template_blank_cell(first_day));
	}
	var j = first_day;
	for (i = 0; i < days; i ++) {
		// Today is sunday, make a new week.
		// If this sunday is the first day of the month,
		// we've made a new row for you already.
		if (j == 0 && !first_loop) {
			// New week!!
			ds_echo (ds_template_new_week());
		}
		// Make a row of that day!
		ds_echo (ds_template_day(i + 1, m, y));
		// This is not first loop anymore...
		first_loop = 0;
		// What is the next day?
		j ++;
		j %= 7;
	}
	// Do the footer
	ds_echo (ds_template_main_below());
	// And let's display..
	ds_ob_flush();
	// Scroll it into view.
	//ds_ce.scrollIntoView();
}

// A function to show the calendar.
// When user click on the date, it will set the content of t.
function ds_sh(t,byPass) {
        if (getMode() != "" || byPass == true){
            // Set the element to set...
            ds_element = t;
            // Make a new date, and set the current month and year.
            var ds_sh_date = new Date();
            ds_c_month = ds_sh_date.getMonth() + 1;
            ds_c_year = ds_sh_date.getFullYear();
            // Draw the calendar
            ds_draw_calendar(ds_c_month, ds_c_year);
            // To change the position properly, we must show it first.
            ds_ce.style.display = '';
            // Move the calendar container!
            the_left = ds_getleft(t);
            the_top = ds_gettop(t) + t.offsetHeight;
            ds_ce.style.left = the_left + 'px';
            ds_ce.style.top = the_top + 'px';
            // Scroll it into view.
            //ds_ce.scrollIntoView();
        }
}

// Hide the calendar.
function ds_hi() {
	ds_ce.style.display = 'none';
}

// Moves to the next month...
function ds_nm() {
	// Increase the current month.
	ds_c_month ++;
	// We have passed December, let's go to the next year.
	// Increase the current year, and set the current month to January.
	if (ds_c_month > 12) {
		ds_c_month = 1; 
		ds_c_year++;
	}
	// Redraw the calendar.
	ds_draw_calendar(ds_c_month, ds_c_year);
}

// Moves to the previous month...
function ds_pm() {
	ds_c_month = ds_c_month - 1; // Can't use dash-dash here, it will make the page invalid.
	// We have passed January, let's go back to the previous year.
	// Decrease the current year, and set the current month to December.
	if (ds_c_month < 1) {
		ds_c_month = 12; 
		ds_c_year = ds_c_year - 1; // Can't use dash-dash here, it will make the page invalid.
	}
	// Redraw the calendar.
	ds_draw_calendar(ds_c_month, ds_c_year);
}

// Moves to the next year...
function ds_ny() {
	// Increase the current year.
	ds_c_year++;
	// Redraw the calendar.
	ds_draw_calendar(ds_c_month, ds_c_year);
}

// Moves to the previous year...
function ds_py() {
	// Decrease the current year.
	ds_c_year = ds_c_year - 1; // Can't use dash-dash here, it will make the page invalid.
	// Redraw the calendar.
	ds_draw_calendar(ds_c_month, ds_c_year);
}

// Format the date to output.
function ds_format_date(d, m, y) {
	// 2 digits month.
	m2 = '00' + m;
	m2 = m2.substr(m2.length - 2);
	// 2 digits day.
	d2 = '00' + d;
	d2 = d2.substr(d2.length - 2);
	// YYYY-MM-DD
	return y + '-' + m2 + '-' + d2;
	//return d2 + '-' + m2 + '-' + y;
}

// When the user clicks the day.
function ds_onclick(d, m, y) {
	// Hide the calendar.
	ds_hi();
	// Set the value of it, if we can.
	if (typeof(ds_element.value) != 'undefined') {
		ds_element.value = ds_format_date(d, m, y);
	// Maybe we want to set the HTML in it.
	} else if (typeof(ds_element.innerHTML) != 'undefined') {
		ds_element.innerHTML = ds_format_date(d, m, y);
	// I don't know how should we display it, just alert it to user.
	} else {
		alert (ds_format_date(d, m, y));
	}
}

// And here is the end.

// ]]> -->

// Copyright (C) 2002-2004 Logiciels Sys-Thèmes Inc. -->
// SysVersion : 7.1.0
// 26/02/2004 : Changement de l'onglet avec le pavé numérique possible même dans une liste --> 7.1.0

var arrScrolls = new Array();
var arrListes = new Array(); //frmEdit.listesActives.value.split(";");

function redirectTo(pageName,onglet,wId){
    parent.parent.main.location = ""+pageName+"?wId="+ wId;
    parent.parent.onglet.changeOnglet(onglet);
}
function changeOrderBy(newOrderBy, table, fromListe){

   // alert("changer order by :" + newOrderBy + " de la table " + table);
    var oldTable = frmEdit.table.value;
    var oldCalledBy = frmEdit.calledBy.value;
    var oldCommand = frmEdit.command.value;
    var oldOrderBy = frmEdit.orderBy.value;
        
    waitForList = false;
    if(fromListe==undefined){
        if(eval("frmEdit."+ table +"_orderBy").value.indexOf(" DESC") > 0){
            newOrderBy = newOrderBy.replace(" DESC","");
            newOrderBy = newOrderBy.replace(" ASC","");
        }
        else if(eval("frmEdit."+ table +"_orderBy").value.indexOf(" ASC") > 0){
            newOrderBy = newOrderBy.replace(" DESC","");
            newOrderBy = newOrderBy.replace(" ASC","");
            newOrderBy = newOrderBy +" DESC";
        }
        else{
            newOrderBy = newOrderBy.replace(" DESC","");
            newOrderBy = newOrderBy.replace(" ASC","");
            newOrderBy = newOrderBy +" DESC";
        }
    }
    //Stocker les scrollTop
    //saveScrollTops();   
    frmEdit.orderBy.value = newOrderBy;

    frmEdit.calledBy.value = eval("frmEdit." + table + "_calledBy.value");
    frmEdit.table.value = table; 
    //alert(eval("frmEdit." + table + "_calledBy.value"));
    //frmEdit.tableActive.value = table;     
    frmEdit.command.value = "changeOrderBy";
    //frmEdit.newPosition.value = newPosition;
    //alert(table);
    appelBoutonCmd();
    
    frmEdit.calledBy.value = oldCalledBy;
    frmEdit.table.value = oldTable;
    frmEdit.orderBy.value = oldOrderBy;
    eval("frmEdit."+ table +"_orderBy").value = newOrderBy;
    
    //frmEdit.tableActive.value = oldTable;
    //setTimeout("lookupAll()", 10);

}
function changeOrderByFind(val){
    frmEdit.orderBy.value = val;
    if(frmEdit.orderByDir.value == "")
        frmEdit.orderByDir.value = "DESC";
    else{/*
        if(frmEdit.orderByDir.value == "DESC")
            frmEdit.orderByDir.value = "ASC";
        else
            frmEdit.orderByDir.value = "DESC";
            */
        frmEdit.orderByDir.value = "";
    }
    frmEdit.submit();
}
function changeOrderByBrowser(newOrderBy, table){

    frmBrowse.scrollTop.value = eval("liste_" + table + "_div").scrollTop;
    //alert("moveListeXML('" + newPosition1 + "','" + orderBy1 + "','" + table1 + "','" + calledBy1 + "');");
    opener.execScript("changeOrderBy('" + newOrderBy + "','" + table + "',false);", "javascript");
    //alert("apres opener");
    //opener.execScript("kevin();");
    afficherListeBrowser(table);
    eval("liste_" + table + "_div").scrollTop =  frmBrowse.scrollTop.value;
    
}


function moveListeXML(newPosition,orderBy,table,calledBy){
    
    var oldTable = frmEdit.table.value;
    var oldCalledBy = frmEdit.calledBy.value;
    var oldCommand = frmEdit.command.value;
    //alert(orderBy);
    waitForList = false;

    //Stocker les scrollTop
    saveScrollTops();   
    frmEdit.calledBy.value = eval("frmEdit." + table + "_calledBy.value");
    frmEdit.table.value = table; 
    //frmEdit.tableActive.value = table;     
    frmEdit.command.value = "moveTo";
    frmEdit.newPosition.value = newPosition;
    appelBoutonCmd();
    frmEdit.calledBy.value = oldCalledBy;
    frmEdit.table.value = oldTable;
    try{
        eval(table + "_afterDisplay()");
    }
    catch(e){}
    //frmEdit.tableActive.value = oldTable;
    //setTimeout("lookupAll()", 10);
}



function saveScrollTops(){
    if (arrListes[0] != ""){
        for(i = 0; i < arrListes.length; i++){        
            arrScrolls[i] = eval(arrListes[i] + "_div").scrollTop;               
        }
    } 
}

function browserMove(newPosition,scroll){
    formHidden.command.value = "moveTo";
    formHidden.newPosition.value = newPosition;
    formHidden.scrollTop.value = scroll;
    formHidden.submit();
    /*
        var nomTable = formHidden.table.value;
        nomTable = nomTable.substring(0,1).toUpperCase() + nomTable.substring(1).toLowerCase();
        alert(nomTable);
        opener.location.reload(true);
        eval("opener.parent.parent.frames.onglet.document.images."+ nomTable +".click()");
    */
}

function browserMoveXML(newPosition1,orderBy1,table1,calledBy1){
    frmBrowse.scrollTop.value = eval("liste_" + table1 + "_div").scrollTop;
    opener.execScript("moveListeXML('" + newPosition1 + "','" + orderBy1 + "','" + table1 + "','" + calledBy1 + "');", "javascript");
    afficherListeBrowser(table1);
    eval("liste_" + table1 + "_div").scrollTop =  frmBrowse.scrollTop.value;
}


function afficherListeBrowser(tableBrowse){
    var fields = eval("opener.frmEdit." + tableBrowse + "_fieldsBrowse").value
    var pageName = "../../lib/jsp/listeXML.jsp?table=" + tableBrowse + "&wId=" + frmBrowse.wId.value + "&fields=" + fields;
    xmlHttpBrowse=getXHR();
    xmlHttpBrowse.onreadystatechange = function(){
        if (xmlHttpBrowse.readyState==4 || xmlHttpBrowse.readyState=="complete"){ 
            var nomBrowse = frmBrowse.browserXsl.value;
            docXML_browse = new ActiveXObject("Microsoft.XMLDOM");
            docXSL_browse = new ActiveXObject("Microsoft.XMLDOM");
            docXSL_browse.async = false;
            docXSL_browse.load(nomBrowse);
            docXML_browse.loadXML(xmlHttpBrowse.responseText);

            browsespan.innerHTML = docXML_browse.transformNode(docXSL_browse);        
        }
    }
    
    xmlHttpBrowse.open("POST", pageName , true) ;  
    xmlHttpBrowse.send(null);  

}
function onEventListe(){
    event.returnValue = false;
    if (event.keyCode >48 && event.keyCode <58){
        if (eval("parent.parent.onglet.document.anchors(\"btn"+(event.keyCode -48)+"\") !=null")){
            eval("parent.parent.onglet.document.anchors(\"btn"+(event.keyCode -48)+"\").click();");
        }
    }
    else if (event.keyCode >= 96 && event.keyCode <= 105){

        if (eval("parent.parent.onglet.document.anchors(\"btn"+(event.keyCode -96)+"\") !=null")){
            eval("parent.parent.onglet.document.anchors(\"btn"+(event.keyCode -96)+"\").click();");
        }
    }
}
function doHelpListe(){
    alert("Touches:\n F1 - Aide\n F2 \n F3 - Recherche \n F4 - Parcourir \n\n F5 - Rafraichir \n F6 - Supprimer \n F7 - Modifier \n F8 - Ajouter \n\n F9 - Cancel \n F10  \n F11  \n F12- OK");
    event.returnValue = false;
}

// Copyright (C) 2002-2004 Logiciels Sys-Thèmes Inc. 
// SysVersion : 7.5.6
// 20/02/2004 : Nouvelle version de la fonction chkdate(objName) -> 7.1.0 
// 02/04/2004 : valideHeure() et valideFld() updaté pour supporter les type heures -> 7.2.0
// 07/06/2004 : fonction de date sous format aaaa-mm-jj pour la RAMQ -> 7.2.1
// 18- juin 04: Ajout fonction trim() -> 7.2.2
// 2-aout -04:  Ajouter fonction valideTelephone -> 7.2.3
// 09/11/2004:  valide code postal n'ajoute pas d'espace -> 7.2.4
// 07/12/2004: La fonction validateDate() comprend l'opérateur : -> 7.3.4
// 07/01/2004: Changement des fonction addMonth() et addDay() pour aaaa-mm-jj -> 7.3.5
// 12/04/2005: Complete les dates de 6 chiffres avec 20 au début -> 7.3.6
// 31/01/2006: Ajouté fonction pour codepostal valideCP(objName) -> 7.4.6
// 05/04/2006: Date en mode jj-mm-aaaa pour standard -> 7.5.6
// -----------------------------------------------------------------------------
// Initializing script  - setting global variables
// -----------------------------------------------------------------------------
var checkObjects    = new Array(); 	
var errors          = ""; 
var returnVal       = false;
var message             = new Array(); 	
message.start           = "- ";
message.field           = " Le champs ";
message.require         = " est obligatoire";
message.min             = " doit contenir au moins ";
message.num             = " doit contenir un nombre ";
message.string          = " doit contenir une chaîne de caractères ";
message.email           = " doit contenir une adresse e-mail valide";
message.codepostal      = " doit avoir comme format (A9A 9A9) ou (A9A-9A9) ";
message.telephone       = " doit avoir comme format (0-000-000-0000 ou 000-000-0000 ou 000-0000) ";

var err             = 0;
var msgDate         = new Array();
msgDate[0]          = "";
msgDate[1]          = "La date n'est pas valide";
msgDate[2]          = "La date doit contenir un jour.";
msgDate[3]          = "La date doit contenir un mois.";
msgDate[4]          = "La date doit contenir une année.";
msgDate[5]          = "Le mois doit être entre 1 et 12.";
msgDate[6]          = "Le jour doit être entre 1 et 31.";
msgDate[7]          = "Le jour doit être entre 1 et 30.";
msgDate[8]          = "Le jour doit être plus grand ou égale à 1."
msgDate[9]          = "Le jour doit être entre 1 et 29."
msgDate[10]         = "Le jour doit être entre 1 et 28."
msgDate[11]         = "Le champs doit contenir une date."

// -----------------------------------------------------------------------------
// n = name of the input field (Required)
// type= string, num, email (Required)
// min = the value must have at least [min] characters (Optional)
// max = the value must have maximum [max] characters (Optional)
// d = (Optional)
// -----------------------------------------------------------------------------
function define(n,type,HTMLname,obligatoire,d){
    var p;
    var i;
    var x;
    if(!d) d=document;
    if((p=n.indexOf("?"))>0&&parent.frames.length){
        d=parent.frames[n.substring(p+1)].document;
        n=n.substring(0,p);
    }
    if(!(x=d[n])&&d.all) x=d.all[n];

    for (i=0;!x&&i<d.forms.length;i++){
        x=d.forms[i][n];
    }
    for(i=0;!x&&d.layers&&i<d.layers.length;i++){
        x=define(n,type,HTMLname,obligatoire,d.layers[i].document);
        return x;		
    }
    eval("V_"+n+" = new formResult(x,type,HTMLname,obligatoire);");
    checkObjects[eval(checkObjects.length)] = eval("V_"+n);
}
function clearDefine(){
    checkObjects = new Array();
}
function formResult(form,type,HTMLname,obligatoire){
    this.form = form;
    this.type = type;
    this.HTMLname = HTMLname;
    this.obligatoire = obligatoire;
}


// -----------------------------------------------------------------------------
// validate - Call this function onSubmit and return the "returnVal". (onSubmit="validate();return returnVal;")
// -----------------------------------------------------------------------------
function valideFld(){
    var tmpError;
    if(checkObjects.length>0){
        for(i=0;i<checkObjects.length;i++){
            validateObject 		= new Object();
            validateObject.form 	= checkObjects[i].form;
            validateObject.HTMLname     = checkObjects[i].HTMLname;
            validateObject.val 		= checkObjects[i].form.value;
//            validateObject.len 		= validateObject.val.length;
            validateObject.len 		= checkObjects[i].form.value.length;
            validateObject.obligatoire  = checkObjects[i].obligatoire;
            validateObject.type 	= checkObjects[i].type;

            //validateObject.form.value = validateObject.val.toUpperCase();
            tmpError = errors;
            if (validateObject.obligatoire == true && validateObject.len <= 0){
                errors+= message.field + validateObject.HTMLname + message.require + "\n";
            }
            else if(validateObject.type == "num"){
                if(isNaN(validateObject.val)){
                    errors+=message.field + validateObject.HTMLname + message.num+"\n";
                }
            }
            else if(validateObject.type == "email"){
                if((validateObject.val.indexOf("@") == -1) || (validateObject.val.charAt(0) == ".") || (validateObject.val.charAt(0) == "@") ||(validateObject.len < 6) || (validateObject.val.indexOf(".") == -1) || (validateObject.val.charAt(validateObject.val.indexOf("@")+1) == ".") || (validateObject.val.charAt(validateObject.val.indexOf("@")-1) == ".")){
                    errors+=message.field + validateObject.HTMLname + message.email + "\n";
                }
            }
            else if(validateObject.type == "codepostal"){
                if(validateObject.len > 0 ){
                    if( validateObject.val.len = 6 &&
                        isNaN(validateObject.val.charAt(0)) &&
                        !isNaN(validateObject.val.charAt(1)) &&
                        isNaN(validateObject.val.charAt(2)) &&
                        !isNaN(validateObject.val.charAt(3)) &&
                        isNaN(validateObject.val.charAt(4)) &&
                        !isNaN(validateObject.val.charAt(5))){                                
                            //validateObject.form.value = validateObject.val.substring(0,3) + " " + validateObject.val.substring(3);
                    }                            
                    else{
                        if( validateObject.val.len = 7 &&
                            isNaN(validateObject.val.charAt(0)) &&
                            !isNaN(validateObject.val.charAt(1)) &&
                            isNaN(validateObject.val.charAt(2)) &&
                            (validateObject.val.charAt(3) == " " || validateObject.val.charAt(3) == "-") &&
                            !isNaN(validateObject.val.charAt(4)) &&
                            isNaN(validateObject.val.charAt(5)) &&
                            !isNaN(validateObject.val.charAt(6))){
                        }
                        else{
                            errors+=message.field + validateObject.HTMLname + message.codepostal + "\n";
                        }
                    }
                }
            }
            else if(validateObject.type == "telephone"){                     
                if(validateObject.len > 0 ){
                    if ( validateObject.val.len = 12 &&    //    800-000-0000
                         validateObject.val.indexOf("-") == 3 &&
                         validateObject.val.indexOf("-",4) == 7 &&
                         !isNaN(validateObject.val.substring(0,3)) &&
                         !isNaN(validateObject.val.substring(4,7)) &&
                         !isNaN(validateObject.val.substring(8)) &&
                         validateObject.val.substring(8).length == 4){

                    }
                    else{
                        if ( validateObject.val.len = 8 &&   //   777-0000
                             validateObject.val.indexOf("-") == validateObject.val.lastIndexOf("-") &&
                             validateObject.val.indexOf("-") == 3 &&
                             !isNaN(validateObject.val.substring(0,3)) &&
                             !isNaN(validateObject.val.substring(4))){
                        }
                        else{
                            errors+=message.field + validateObject.HTMLname + message.telephone + "\n";
                        }
                    }
                }
            }
            else if(validateObject.type == "date"){
                if (!chkdate(validateObject.form)){
                    errors+=msgDate[err] + "\n";
                }
            }
            else if(validateObject.type == "heure"){
                if (validateObject.val.indexOf(":") < 0){
                    errors+="L'heure doit contenir le signe : \n";
                }
                else{
                    hh = validateObject.val.substring(0,validateObject.val.indexOf(":"));
                    mm = validateObject.val.substring(validateObject.val.indexOf(":")+ 1);
                    if (isNaN(hh) || hh > 24){
                        errors+="L'heure doit être plus petit que 24 : \n";
                    }
                    else if(isNaN(mm) || mm > 59){
                        errors+="Les minutes doit être plus petit que 60 : \n";
                    }
                }
            }
            champErreur(checkObjects[i].form,tmpError != errors);
        }
    }
    if(errors){
        afficheMessageErreur(errors);
        errors = "";
        returnVal = false;
    } 
    else {
        returnVal = true;
    }
    
    return returnVal;
}

function valideHeure(objName) {
    var val = objName.value;
    var returnValeur = true;

    if (getMode() == "Filtrer"){
        if (objName.value.substring(0,1) == "="  ||
            objName.value.substring(0,2) == "!="  ||
            objName.value.substring(0,1) == ">"  ||
            objName.value.substring(0,1) == "<" )
            return;
    }
    if (val.indexOf(":") < 0){
        afficheMessageErreur("L'heure doit contenir le signe :");
        returnValeur = false;
    }
    else{
        hh = val.substring(0,val.indexOf(":"));
        mm = val.substring(val.indexOf(":")+ 1);
        if (isNaN(hh) || hh > 24){
            afficheMessageErreur("L'heure doit être plus petit que 24");
            returnValeur = false;
        }
        else if(isNaN(mm) || mm > 59){
            afficheMessageErreur("Les minutes doit être plus petit que 60");
            returnValeur = false;
        }
    }
    champErreur(objName,!returnValeur);
    return returnValeur;
}
function valideTelephone(objName){
    if(objName.value.length > 8 && objName.value.indexOf("-") < 0)
        objName.value = objName.value.substring(0,3) + "-" + objName.value.substring(3,6) + "-" + objName.value.substring(6);

}
//------------VALIDATION DATE ---------------------
function valideDate(objName) {
    var datefield = objName;
    var returnValeur;

    if (getMode() == "Filtrer"){
        if (objName.value.substring(0,1) == "="  ||
            objName.value.substring(0,2) == "!="  ||
            objName.value.substring(0,1) == ">"  ||
            objName.value.substring(0,1) == "<" || 
            objName.value.indexOf(":") >= 0)
            return;
    }
    if (chkdate(objName) == false) {
        datefield.select();
        datefield.focus();
        returnValeur = false;
    }
    else {
        err = 0;
        returnValeur = true;
    }
    champErreur(objName,!returnValeur);
    afficheMessageErreur(msgDate[err]);
    return returnValeur;
}

function chkdate(objName) {
    var strDate;
    var strDateArray;
    var strDay;
    var strMonth;
    var strYear;
    var intday;
    var intMonth;
    var intYear;
    var booFound = false;
    var datefield = objName;
    var strSeparatorArray = new Array("-"," ","/",".");
    var intElementNr;

    strDate = datefield.value;
    if (strDate.length < 1) {
        return true;
    }
    if(objName.value.indexOf("-") < 0){
        if (objName.value.length < 8){
            objName.value = "20" + objName.value;
        }
        strDate = objName.value.substring(0,4) + "-" + objName.value.substring(4,6) + "-" + objName.value.substring(6);
        // --- Ancienne version dd-mm-yyyy
        //strDate = strDate = objName.value.substring(0,2) + "-" + objName.value.substring(2,4) + "-" + objName.value.substring(4);
    }
    for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) {
        if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) {
            strDateArray = strDate.split(strSeparatorArray[intElementNr]);
            if (strDateArray.length != 3) {
                err = 1;
                return false;
            }
            else {
                //strYear = strDateArray[0];
                //strMonth = strDateArray[1];
                //strDay = strDateArray[2];
                strDay = strDateArray[2];
                strMonth = strDateArray[1];
                strYear = strDateArray[0];
            }
            booFound = true;
        }
    }
    if (booFound == false) {
        err = 11;
        return false;
    }
    if (strYear.length == 2) {
        if(strYear > 50)
            strYear = '19' + strYear;
        else
            strYear = '20' + strYear;
    }
    else{
        if(strYear.length == 1){
            strYear = "200" + strYear;
        }
        else{
            if(strYear.length > 4){
                err = 12;
                return false;
            }
        }

    }
    intday = parseInt(strDay, 10);
    if (isNaN(intday)) {
        err = 2;
        return false;
    }
    intMonth = parseInt(strMonth, 10);
    if (isNaN(intMonth)) {
        err = 3;
        return false;
    }
    intYear = parseInt(strYear, 10);
    if (isNaN(intYear)) {
        err = 4;
        return false;
    }
    if (intMonth>12 || intMonth<1) {
        err = 5;
        return false;
    }
    if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1)) {
        err = 6;
        return false;
    }
    if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1)) {
        err = 7;
        return false;
    }
    if (intMonth == 2) {
        if (intday < 1) {
            err = 8;
            return false;
        }
        if (LeapYear(intYear) == true) {
            if (intday > 29) {
                err = 9;
                return false;
            }
        }
        else {
            if (intday > 28) {
                err = 10;
                return false;
            }
        }
    }
    if(intMonth <10)
        intMonth = "0"+intMonth;
    if(intday <10)
        intday = "0"  + intday;
    if(intYear > 9999){
        err = 12;
        return false;
    }
    //datefield.value = intday + "-" + intMonth + "-" + strYear;
    datefield.value = strYear + "-" + intMonth + "-" + intday ;
    return true;
}

function valideCP(objName) {
   
    var codepostal = objName;
    var returnValeur = true;

    if (getMode() == "Filtrer"){
        if (objName.value.substring(0,1) == "="  ||
            objName.value.substring(0,2) == "!="  ||
            objName.value.substring(0,1) == ">"  ||
            objName.value.substring(0,1) == "<" || 
            objName.value.indexOf(":") >= 0)
            return;
    }
    if (codepostal.value.length > 0){

        if (!chkCodePostal(objName)) {

            codepostal.select();
            codepostal.focus();
            afficheMessageErreur("Erreur dans le code postal");
            returnValeur = false;
        }
        else {
            err = 0;
            afficheMessageErreur("");
            returnValeur = true;
        }   
    }

    champErreur(objName,!returnValeur);    
    return returnValeur;
}

function chkCodePostal(objName){
    
    strCP = objName.value;   
    
    if (strCP.length < 6){
        return false;
    }

    if (strCP.length == 6){
        strCP = strCP.substring(0,3) + " " + strCP.substring(3, 6);
    }

    objName.value = strCP;    

    if(strCP.search(/[A-z][0-9][A-z]\s[0-9][A-z][0-9]/g) != -1){
        return true;
    }
    else{
        return false;
    }   
}


function getCookie( name ) {	var start = document.cookie.indexOf( name + "=" );	var len = start + name.length + 1;	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {		return null;	}	if ( start == -1 ) return null;	var end = document.cookie.indexOf( ';', len );	if ( end == -1 ) end = document.cookie.length;	return unescape( document.cookie.substring( len, end ) );}

function LeapYear(intYear) {
    if (intYear % 100 == 0) {
        if (intYear % 400 == 0) { return true; }
    }
    else {
        if ((intYear % 4) == 0) { return true; }
    }
    return false;
}
function getToday(sep){
    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth()+1;
    if (mm < 10)
        mm = "0" + mm;
    if (dd < 10)
        dd = "0" + dd;
    if(sep == null){
        return today.getYear() + "-" + mm + "-" + dd;
        //return dd + "-" + mm + "-" + today.getYear() ;
    }
    else{
        return today.getYear() + sep + mm + sep + dd;
    }   
}
function getTime(){
    var now = new Date();
    return now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();
}

//------------- FIN VALIDATION DATE ----------------


function toMoney(number){
    return (number == Math.floor(number)) ? number + '.00' : (  (number*10 == Math.floor(number*10)) ? number + '0' : number);
}

//***** DATE TOOL *******//
function toYMD(val){
    var yyyy="",
        mm="",
        dd="";
    var len =val.length;
    var temp = val.split("-");
    if(len > 0){
        dd = temp[0];
        mm = temp[1];
        yyyy = temp[2];
        return yyyy+"-"+mm+"-"+dd;
    }
    else
        return "";
        
}
function addDay(uneDate, nbJr){
    if(uneDate == "" || nbJr == "")
        return "";
    else{
        var arrDate = uneDate.split("-");
        var newDate = new Date(arrDate[2],arrDate[1]-1,arrDate[0]);
        var newDay = newDate.getDate();
        nbJr++;
        nbJr--;
        newDay = newDay + nbJr;
        newDate.setDate(newDay);
        var d = newDate.getDate();
        var m = newDate.getMonth()+1;
        var y = newDate.getYear();
        if(d < 10)
            d = "0" + d;
        if(m < 10)
            m = "0" + m;
        if(y < 100)
            y = y + 1900;
        return d+"-"+m+"-"+y;
    }
}
function addMonth(uneDate, nbMois){
    if(uneDate == "" || nbMois == "")
        return "";
    else{
        var arrDate = uneDate.split("-");
        var newDate = new Date(arrDate[2],arrDate[1]-1,arrDate[0]);
        var newMois = newDate.getMonth();
        nbMois++;
        nbMois--;
        newMois = newMois+ nbMois;
        newDate.setMonth(newMois);
        var d = newDate.getDate();
        var m = newDate.getMonth()+1;
        var y = newDate.getYear();
        if(d < 10)
            d = "0" + d;
        if(m < 10)
            m = "0" + m;
        if(y < 100)
            y = y + 1900;
        return d+"-"+m+"-"+y;
    }
}
function compareDate(date1,operateur,date2){
    var arrDate1 = date1.split("-");
    var newDate1 = new Date(arrDate1[2],arrDate1[1]-1,arrDate1[0]);
    var arrDate2 = date2.split("-");
    var newDate2 = new Date(arrDate2[2],arrDate2[1]-1,arrDate2[0]);
    return eval("(newDate1 "+ operateur +" newDate2)");
}
function champErreur(objName,bError){
    if(bError){
        objName.className = "fieldErreur";
    }
    else{
        /*if(objName.className == "fieldEnabled")
            objName.className = "fieldDisabled";
        else*/
            objName.className = "fieldEnabled";
    }
}

//*********** number tools ******************//
function formatNumber(Number,Decimals,Separator)
{
    Number += ""          // Force argument to string.
    Decimals += ""        // Force argument to string.
    Separator += ""       // Force argument to string.
    if((Separator == "") || (Separator.length > 1))
    Separator = "."
    if(Number.length == 0)
    Number = "0"
    var OriginalNumber = Number  // Save for number too large.
    var Sign = 1
    var Pad = ""
    var Count = 0
    // If no number passed, force number to 0.
    if(parseFloat(Number)){
    Number = parseFloat(Number)} else {
    Number = 0}
    // If no decimals passed, default decimals to 2.
    if((parseInt(Decimals,10)) || (parseInt(Decimals,10) == 0)){
    Decimals = parseInt(Decimals,10)} else {
        Decimals = 2}
    if(Number < 0){
        Sign = -1         // Remember sign of Number.
        Number *= Sign    // Force absolute value of Number.
    }
    if(Decimals < 0)
        Decimals *= -1    // Force absolute value of Decimals.
    // Next, convert number to rounded integer and force to string value.
    // (Number contains 1 extra digit used to force rounding)
    Number = "" + Math.floor(Number * Math.pow(10,Decimals + 1) + 5)
    if((Number.substring(1,2) == '.')||((Number + '')=='NaN'))
        return(OriginalNumber) // Number too large to format as specified.
    // If length of Number is less than number of decimals requested +1,
    // pad with zeros to requested length.
    if(Number.length < Decimals +1){
        for(Count = Number.length; Count <= Decimals; Count++)
            Pad += "0"
    }
    Number = Pad + Number // Pad number as needed.
    if(Decimals == 0){
        // Drop extra digit -- Decimal portion is formatted.
        Number = Number.substring(0, Number.length -1)} else {
        // Or, format number with decimal point and drop extra decimal digit.
        Number = Number.substring(0,Number.length - Decimals -1) + Separator +
          Number.substring(Number.length - Decimals -1,
          Number.length -1)}
    if((Number == "") || (parseFloat(Number) < 1))
        Number="0"+Number // Force leading 0 for |Number| less than 1.
    if(Sign == -1)
        Number = "-" + Number  // Set sign of number.
    
    return(Number)
}
function errorOnFld(ctl,msg){
    afficheMessageErreur(msg);
    ctl.focus();
    ctl.className="fieldErreur";
}
function clearStyle(){
    for(i=0;i<checkObjects.length;i++){
        champErreur(checkObjects[i].form,false);
    }
}

function afficheMessageErreur(strMsg){
    txtMessage.innerText = strMsg;
}
function afficheMessageErreurPied(strMsg){
    parent.parent.frames("piedpage").txtMessage.innerText = strMsg;
}
function trim(inputString) {
   // Removes leading and trailing spaces from the passed string. Also removes
   // consecutive spaces and replaces it with one space. If something besides
   // a string is passed in (null, custom object, etc.) then return the input.
   if (typeof inputString != "string") { return inputString; }
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
   while (ch == " ") { // Check for spaces at the beginning of the string
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length-1, retValue.length);
   while (ch == " ") { // Check for spaces at the end of the string
      retValue = retValue.substring(0, retValue.length-1);
      ch = retValue.substring(retValue.length-1, retValue.length);
   }
   while (retValue.indexOf("  ") != -1) { // Note that there are two spaces in the string - look for multiple spaces within the string
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); // Again, there are two spaces in each of the strings
   }
   return retValue; // Return the trimmed string back to the user
} // Ends the "trim" function

//Pour autocomplete
function autoComplete (field, select, property, forcematch) {
    var found = false;
    for (var i = 0; i < select.options.length; i++) {
        if (select.options[i][property].toUpperCase().indexOf(field.value.toUpperCase()) == 0) {
            found=true; break;
        }
    }
    if (found) { 
        select.selectedIndex = i; 
    }
    else { 
        select.selectedIndex = -1; 
    }
    if (field.createTextRange) {
        if (forcematch && !found) {
            field.value=field.value.substring(0,field.value.length-1); 
            return;
        }
        var cursorKeys ="8;46;37;38;39;40;33;34;35;36;45;";
        if (cursorKeys.indexOf(event.keyCode+";") == -1) {
            var r1 = field.createTextRange();
            var oldValue = r1.text;
            var newValue = found ? select.options[i][property] : oldValue;
            if (newValue != field.value) {
                field.value = newValue;
                var rNew = field.createTextRange();
                rNew.moveStart('character', oldValue.length) ;
                rNew.select();
            }
        }
    }
}
//Fin Pour autocomplete

//Pour faire les coins ronds
//source curvycorners.js
function browserdetect(){var A=navigator.userAgent.toLowerCase();this.isIE=A.indexOf("msie")>-1;this.ieVer=this.isIE?/msie\s(\d\.\d)/.exec(A)[1]:0;this.isMoz=A.indexOf("firefox")!=-1;this.isSafari=A.indexOf("safari")!=-1;this.quirksMode=this.isIE&&(!document.compatMode||document.compatMode.indexOf("BackCompat")>-1);this.isOp="opera" in window;this.isWebKit=A.indexOf("webkit")!=-1;if(this.isIE){this.get_style=function(D,F){if(!(F in D.currentStyle)){return""}var C=/^([\d.]+)(\w*)/.exec(D.currentStyle[F]);if(!C){return D.currentStyle[F]}if(C[1]==0){return"0"}if(C[2]&&C[2]!=="px"){var B=D.style.left;var E=D.runtimeStyle.left;D.runtimeStyle.left=D.currentStyle.left;D.style.left=C[1]+C[2];C[0]=D.style.pixelLeft;D.style.left=B;D.runtimeStyle.left=E}return C[0]}}else{this.get_style=function(B,C){C=C.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase();return document.defaultView.getComputedStyle(B,"").getPropertyValue(C)}}}var curvyBrowser=new browserdetect;if(curvyBrowser.isIE){try{document.execCommand("BackgroundImageCache",false,true)}catch(e){}}function curvyCnrSpec(A){this.selectorText=A;this.tlR=this.trR=this.blR=this.brR=0;this.tlu=this.tru=this.blu=this.bru="";this.antiAlias=true}curvyCnrSpec.prototype.setcorner=function(B,C,A,D){if(!B){this.tlR=this.trR=this.blR=this.brR=parseInt(A);this.tlu=this.tru=this.blu=this.bru=D}else{propname=B.charAt(0)+C.charAt(0);this[propname+"R"]=parseInt(A);this[propname+"u"]=D}};curvyCnrSpec.prototype.get=function(D){if(/^(t|b)(l|r)(R|u)$/.test(D)){return this[D]}if(/^(t|b)(l|r)Ru$/.test(D)){var C=D.charAt(0)+D.charAt(1);return this[C+"R"]+this[C+"u"]}if(/^(t|b)Ru?$/.test(D)){var B=D.charAt(0);B+=this[B+"lR"]>this[B+"rR"]?"l":"r";var A=this[B+"R"];if(D.length===3&&D.charAt(2)==="u"){A+=this[B="u"]}return A}throw new Error("Don't recognize property "+D)};curvyCnrSpec.prototype.radiusdiff=function(A){if(A!=="t"&&A!=="b"){throw new Error("Param must be 't' or 'b'")}return Math.abs(this[A+"lR"]-this[A+"rR"])};curvyCnrSpec.prototype.setfrom=function(A){this.tlu=this.tru=this.blu=this.bru="px";if("tl" in A){this.tlR=A.tl.radius}if("tr" in A){this.trR=A.tr.radius}if("bl" in A){this.blR=A.bl.radius}if("br" in A){this.brR=A.br.radius}if("antiAlias" in A){this.antiAlias=A.antiAlias}};curvyCnrSpec.prototype.cloneOn=function(G){var E=["tl","tr","bl","br"];var H=0;var C,A;for(C in E){if(!isNaN(C)){A=this[E[C]+"u"];if(A!==""&&A!=="px"){H=new curvyCnrSpec;break}}}if(!H){H=this}else{var B,D,F=curvyBrowser.get_style(G,"left");for(C in E){if(!isNaN(C)){B=E[C];A=this[B+"u"];D=this[B+"R"];if(A!=="px"){var F=G.style.left;G.style.left=D+A;D=G.style.pixelLeft;G.style.left=F}H[B+"R"]=D;H[B+"u"]="px"}}G.style.left=F}return H};curvyCnrSpec.prototype.radiusSum=function(A){if(A!=="t"&&A!=="b"){throw new Error("Param must be 't' or 'b'")}return this[A+"lR"]+this[A+"rR"]};curvyCnrSpec.prototype.radiusCount=function(A){var B=0;if(this[A+"lR"]){++B}if(this[A+"rR"]){++B}return B};curvyCnrSpec.prototype.cornerNames=function(){var A=[];if(this.tlR){A.push("tl")}if(this.trR){A.push("tr")}if(this.blR){A.push("bl")}if(this.brR){A.push("br")}return A};function operasheet(C){var A=document.styleSheets.item(C).ownerNode.text;A=A.replace(/\/\*(\n|\r|.)*?\*\//g,"");var D=new RegExp("^s*([\\w.#][-\\w.#, ]+)[\\n\\s]*\\{([^}]+border-((top|bottom)-(left|right)-)?radius[^}]*)\\}","mg");var G;this.rules=[];while((G=D.exec(A))!==null){var F=new RegExp("(..)border-((top|bottom)-(left|right)-)?radius:\\s*([\\d.]+)(in|em|px|ex|pt)","g");var E,B=new curvyCnrSpec(G[1]);while((E=F.exec(G[2]))!==null){if(E[1]!=="z-"){B.setcorner(E[3],E[4],E[5],E[6])}}this.rules.push(B)}}operasheet.contains_border_radius=function(A){return/border-((top|bottom)-(left|right)-)?radius/.test(document.styleSheets.item(A).ownerNode.text)};function curvyCorners(){var G,D,E,B,J;if(typeof arguments[0]!=="object"){throw curvyCorners.newError("First parameter of curvyCorners() must be an object.")}if(arguments[0] instanceof curvyCnrSpec){B=arguments[0];if(!B.selectorText&&typeof arguments[1]==="string"){B.selectorText=arguments[1]}}else{if(typeof arguments[1]!=="object"&&typeof arguments[1]!=="string"){throw curvyCorners.newError("Second parameter of curvyCorners() must be an object or a class name.")}D=arguments[1];if(typeof D!=="string"){D=""}if(D!==""&&D.charAt(0)!=="."&&"autoPad" in arguments[0]){D="."+D}B=new curvyCnrSpec(D);B.setfrom(arguments[0])}if(B.selectorText){J=0;var I=B.selectorText.replace(/\s+$/,"").split(/,\s*/);E=new Array;function A(M){var L=M.split("#");return(L.length===2?"#":"")+L.pop()}for(G=0;G<I.length;++G){var K=A(I[G]);var H=K.split(" ");switch(K.charAt(0)){case"#":D=H.length===1?K:H[0];D=document.getElementById(D.substr(1));if(D===null){curvyCorners.alert("No object with ID "+K+" exists yet.\nCall curvyCorners(settings, obj) when it is created.")}else{if(H.length===1){E.push(D)}else{E=E.concat(curvyCorners.getElementsByClass(H[1],D))}}break;default:if(H.length===1){E=E.concat(curvyCorners.getElementsByClass(K))}else{var C=curvyCorners.getElementsByClass(H[0]);for(D=0;D<C.length;++D){E=E.concat(curvyCorners.getElementsByClass(H[1],C))}}}}}else{J=1;E=arguments}for(G=J,D=E.length;G<D;++G){if(E[G]&&(!("IEborderRadius" in E[G].style)||E[G].style.IEborderRadius!="set")){if(E[G].className&&E[G].className.indexOf("curvyRedraw")!==-1){if(typeof curvyCorners.redrawList==="undefined"){curvyCorners.redrawList=new Array}curvyCorners.redrawList.push({node:E[G],spec:B,copy:E[G].cloneNode(false)})}E[G].style.IEborderRadius="set";var F=new curvyObject(B,E[G]);F.applyCorners()}}}curvyCorners.prototype.applyCornersToAll=function(){curvyCorners.alert("This function is now redundant. Just call curvyCorners(). See documentation.")};curvyCorners.redraw=function(){if(!curvyBrowser.isOp&&!curvyBrowser.isIE){return}if(!curvyCorners.redrawList){throw curvyCorners.newError("curvyCorners.redraw() has nothing to redraw.")}var E=curvyCorners.bock_redraw;curvyCorners.block_redraw=true;for(var A in curvyCorners.redrawList){if(isNaN(A)){continue}var D=curvyCorners.redrawList[A];if(!D.node.clientWidth){continue}var B=D.copy.cloneNode(false);for(var C=D.node.firstChild;C!=null;C=C.nextSibling){if(C.className==="autoPadDiv"){break}}if(!C){curvyCorners.alert("Couldn't find autoPad DIV");break}D.node.parentNode.replaceChild(B,D.node);while(C.firstChild){B.appendChild(C.removeChild(C.firstChild))}D=new curvyObject(D.spec,D.node=B);D.applyCorners()}curvyCorners.block_redraw=E};curvyCorners.adjust=function(obj,prop,newval){if(curvyBrowser.isOp||curvyBrowser.isIE){if(!curvyCorners.redrawList){throw curvyCorners.newError("curvyCorners.adjust() has nothing to adjust.")}var i,j=curvyCorners.redrawList.length;for(i=0;i<j;++i){if(curvyCorners.redrawList[i].node===obj){break}}if(i===j){throw curvyCorners.newError("Object not redrawable")}obj=curvyCorners.redrawList[i].copy}if(prop.indexOf(".")===-1){obj[prop]=newval}else{eval("obj."+prop+"='"+newval+"'")}};curvyCorners.handleWinResize=function(){if(!curvyCorners.block_redraw){curvyCorners.redraw()}};curvyCorners.setWinResize=function(A){curvyCorners.block_redraw=!A};curvyCorners.newError=function(A){return new Error("curvyCorners Error:\n"+A)};curvyCorners.alert=function(A){if(typeof curvyCornersVerbose==="undefined"||curvyCornersVerbose){alert(A)}};function curvyObject(){var U;this.box=arguments[1];this.settings=arguments[0];this.topContainer=this.bottomContainer=this.shell=U=null;var K=this.box.clientWidth;if(!K&&curvyBrowser.isIE){this.box.style.zoom=1;K=this.box.clientWidth}if(!K){if(!this.box.parentNode){throw this.newError("box has no parent!")}for(U=this.box;;U=U.parentNode){if(!U||U.tagName==="BODY"){this.applyCorners=function(){};curvyCorners.alert(this.errmsg("zero-width box with no accountable parent","warning"));return}if(U.style.display==="none"){break}}U.style.display="block";K=this.box.clientWidth}if(arguments[0] instanceof curvyCnrSpec){this.spec=arguments[0].cloneOn(this.box)}else{this.spec=new curvyCnrSpec("");this.spec.setfrom(this.settings)}var b=curvyBrowser.get_style(this.box,"borderTopWidth");var J=curvyBrowser.get_style(this.box,"borderBottomWidth");var D=curvyBrowser.get_style(this.box,"borderLeftWidth");var B=curvyBrowser.get_style(this.box,"borderRightWidth");var I=curvyBrowser.get_style(this.box,"borderTopColor");var G=curvyBrowser.get_style(this.box,"borderBottomColor");var A=curvyBrowser.get_style(this.box,"borderLeftColor");var E=curvyBrowser.get_style(this.box,"backgroundColor");var C=curvyBrowser.get_style(this.box,"backgroundImage");var Y=curvyBrowser.get_style(this.box,"backgroundRepeat");if(this.box.currentStyle&&this.box.currentStyle.backgroundPositionX){var R=curvyBrowser.get_style(this.box,"backgroundPositionX");var P=curvyBrowser.get_style(this.box,"backgroundPositionY")}else{var R=curvyBrowser.get_style(this.box,"backgroundPosition");R=R.split(" ");var P=R[1];R=R[0]}var O=curvyBrowser.get_style(this.box,"position");var Z=curvyBrowser.get_style(this.box,"paddingTop");var c=curvyBrowser.get_style(this.box,"paddingBottom");var Q=curvyBrowser.get_style(this.box,"paddingLeft");var a=curvyBrowser.get_style(this.box,"paddingRight");var S=curvyBrowser.get_style(this.box,"border");filter=curvyBrowser.ieVer>7?curvyBrowser.get_style(this.box,"filter"):null;var H=this.spec.get("tR");var M=this.spec.get("bR");var W=function(f){if(typeof f==="number"){return f}if(typeof f!=="string"){throw new Error("unexpected styleToNPx type "+typeof f)}var d=/^[-\d.]([a-z]+)$/.exec(f);if(d&&d[1]!="px"){throw new Error("Unexpected unit "+d[1])}if(isNaN(f=parseInt(f))){f=0}return f};var T=function(d){return d<=0?"0":d+"px"};try{this.borderWidth=W(b);this.borderWidthB=W(J);this.borderWidthL=W(D);this.borderWidthR=W(B);this.boxColour=curvyObject.format_colour(E);this.topPadding=W(Z);this.bottomPadding=W(c);this.leftPadding=W(Q);this.rightPadding=W(a);this.boxWidth=K;this.boxHeight=this.box.clientHeight;this.borderColour=curvyObject.format_colour(I);this.borderColourB=curvyObject.format_colour(G);this.borderColourL=curvyObject.format_colour(A);this.borderString=this.borderWidth+"px solid "+this.borderColour;this.borderStringB=this.borderWidthB+"px solid "+this.borderColourB;this.backgroundImage=((C!="none")?C:"");this.backgroundRepeat=Y}catch(X){throw this.newError("getMessage" in X?X.getMessage():X.message)}var F=this.boxHeight;var V=K;if(curvyBrowser.isOp){R=W(R);P=W(P);if(R){var N=V+this.borderWidthL+this.borderWidthR;if(R>N){R=N}R=(N/R*100)+"%"}if(P){var N=F+this.borderWidth+this.borderWidthB;if(P>N){P=N}P=(N/P*100)+"%"}}if(curvyBrowser.quirksMode){}else{this.boxWidth-=this.leftPadding+this.rightPadding;this.boxHeight-=this.topPadding+this.bottomPadding}this.contentContainer=document.createElement("div");if(filter){this.contentContainer.style.filter=filter}while(this.box.firstChild){this.contentContainer.appendChild(this.box.removeChild(this.box.firstChild))}if(O!="absolute"){this.box.style.position="relative"}this.box.style.padding="0";this.box.style.border=this.box.style.backgroundImage="none";this.box.style.backgroundColor="transparent";this.box.style.width=(V+this.borderWidthL+this.borderWidthR)+"px";this.box.style.height=(F+this.borderWidth+this.borderWidthB)+"px";var L=document.createElement("div");L.style.position="absolute";if(filter){L.style.filter=filter}if(curvyBrowser.quirksMode){L.style.width=(V+this.borderWidthL+this.borderWidthR)+"px"}else{L.style.width=V+"px"}L.style.height=T(F+this.borderWidth+this.borderWidthB-H-M);L.style.padding="0";L.style.top=H+"px";L.style.left="0";if(this.borderWidthL){L.style.borderLeft=this.borderWidthL+"px solid "+this.borderColourL}if(this.borderWidth&&!H){L.style.borderTop=this.borderWidth+"px solid "+this.borderColour}if(this.borderWidthR){L.style.borderRight=this.borderWidthR+"px solid "+this.borderColourL}if(this.borderWidthB&&!M){L.style.borderBottom=this.borderWidthB+"px solid "+this.borderColourB}L.style.backgroundColor=E;L.style.backgroundImage=this.backgroundImage;L.style.backgroundRepeat=this.backgroundRepeat;this.shell=this.box.appendChild(L);K=curvyBrowser.get_style(this.shell,"width");if(K===""||K==="auto"||K.indexOf("%")!==-1){throw this.newError("Shell width is "+K)}this.boxWidth=(K!=""&&K!="auto"&&K.indexOf("%")==-1)?parseInt(K):this.shell.clientWidth;this.applyCorners=function(){if(this.backgroundObject){var w=function(AO,i,t){if(AO===0){return 0}var k;if(AO==="right"||AO==="bottom"){return t-i}if(AO==="center"){return(t-i)/2}if(AO.indexOf("%")>0){return(t-i)*100/parseInt(AO)}return W(AO)};this.backgroundPosX=w(R,this.backgroundObject.width,V);this.backgroundPosY=w(P,this.backgroundObject.height,F)}else{if(this.backgroundImage){this.backgroundPosX=W(R);this.backgroundPosY=W(P)}}if(H){v=document.createElement("div");v.style.width=this.boxWidth+"px";v.style.fontSize="1px";v.style.overflow="hidden";v.style.position="absolute";v.style.paddingLeft=this.borderWidth+"px";v.style.paddingRight=this.borderWidth+"px";v.style.height=H+"px";v.style.top=-H+"px";v.style.left=-this.borderWidthL+"px";this.topContainer=this.shell.appendChild(v)}if(M){var v=document.createElement("div");v.style.width=this.boxWidth+"px";v.style.fontSize="1px";v.style.overflow="hidden";v.style.position="absolute";v.style.paddingLeft=this.borderWidthB+"px";v.style.paddingRight=this.borderWidthB+"px";v.style.height=M+"px";v.style.bottom=-M+"px";v.style.left=-this.borderWidthL+"px";this.bottomContainer=this.shell.appendChild(v)}var AG=this.spec.cornerNames();for(var AK in AG){if(!isNaN(AK)){var AC=AG[AK];var AD=this.spec[AC+"R"];var AE,AH,j,AF;if(AC=="tr"||AC=="tl"){AE=this.borderWidth;AH=this.borderColour;AF=this.borderWidth}else{AE=this.borderWidthB;AH=this.borderColourB;AF=this.borderWidthB}j=AD-AF;var u=document.createElement("div");u.style.height=this.spec.get(AC+"Ru");u.style.width=this.spec.get(AC+"Ru");u.style.position="absolute";u.style.fontSize="1px";u.style.overflow="hidden";var r,q,p;var n=filter?parseInt(/alpha\(opacity.(\d+)\)/.exec(filter)[1]):100;for(r=0;r<AD;++r){var m=(r+1>=j)?-1:Math.floor(Math.sqrt(Math.pow(j,2)-Math.pow(r+1,2)))-1;if(j!=AD){var h=(r>=j)?-1:Math.ceil(Math.sqrt(Math.pow(j,2)-Math.pow(r,2)));var f=(r+1>=AD)?-1:Math.floor(Math.sqrt(Math.pow(AD,2)-Math.pow((r+1),2)))-1}var d=(r>=AD)?-1:Math.ceil(Math.sqrt(Math.pow(AD,2)-Math.pow(r,2)));if(m>-1){this.drawPixel(r,0,this.boxColour,n,(m+1),u,true,AD)}if(j!=AD){if(this.spec.antiAlias){for(q=m+1;q<h;++q){if(this.backgroundImage!=""){var g=curvyObject.pixelFraction(r,q,j)*100;this.drawPixel(r,q,AH,n,1,u,g>=30,AD)}else{if(this.boxColour!=="transparent"){var AB=curvyObject.BlendColour(this.boxColour,AH,curvyObject.pixelFraction(r,q,j));this.drawPixel(r,q,AB,n,1,u,false,AD)}else{this.drawPixel(r,q,AH,n>>1,1,u,false,AD)}}}if(f>=h){if(h==-1){h=0}this.drawPixel(r,h,AH,n,(f-h+1),u,false,0)}p=AH;q=f}else{if(f>m){this.drawPixel(r,(m+1),AH,n,(f-m),u,false,0)}}}else{p=this.boxColour;q=m}if(this.spec.antiAlias){while(++q<d){this.drawPixel(r,q,p,(curvyObject.pixelFraction(r,q,AD)*n),1,u,AF<=0,AD)}}}for(var y=0,AJ=u.childNodes.length;y<AJ;++y){var s=u.childNodes[y];var AI=parseInt(s.style.top);var AM=parseInt(s.style.left);var AN=parseInt(s.style.height);if(AC=="tl"||AC=="bl"){s.style.left=(AD-AM-1)+"px"}if(AC=="tr"||AC=="tl"){s.style.top=(AD-AN-AI)+"px"}s.style.backgroundRepeat=this.backgroundRepeat;if(this.backgroundImage){switch(AC){case"tr":s.style.backgroundPosition=(this.backgroundPosX-this.borderWidthL+AD-V-AM)+"px "+(this.backgroundPosY+AN+AI+this.borderWidth-AD)+"px";break;case"tl":s.style.backgroundPosition=(this.backgroundPosX-AD+AM+this.borderWidthL)+"px "+(this.backgroundPosY-AD+AN+AI+this.borderWidth)+"px";break;case"bl":s.style.backgroundPosition=(this.backgroundPosX-AD+AM+1+this.borderWidthL)+"px "+(this.backgroundPosY-F-this.borderWidth+(curvyBrowser.quirksMode?AI:-AI)+AD)+"px";break;case"br":if(curvyBrowser.quirksMode){s.style.backgroundPosition=(this.backgroundPosX+this.borderWidthL-V+AD-AM)+"px "+(this.backgroundPosY-F-this.borderWidth+AI+AD)+"px"}else{s.style.backgroundPosition=(this.backgroundPosX-this.borderWidthL-V+AD-AM)+"px "+(this.backgroundPosY-F-this.borderWidth+AD-AI)+"px"}}}}switch(AC){case"tl":u.style.top=u.style.left="0";this.topContainer.appendChild(u);break;case"tr":u.style.top=u.style.right="0";this.topContainer.appendChild(u);break;case"bl":u.style.bottom=u.style.left="0";this.bottomContainer.appendChild(u);break;case"br":u.style.bottom=u.style.right="0";this.bottomContainer.appendChild(u)}}}var x={t:this.spec.radiusdiff("t"),b:this.spec.radiusdiff("b")};for(z in x){if(typeof z==="function"){continue}if(!this.spec.get(z+"R")){continue}if(x[z]){if(this.backgroundImage&&this.spec.radiusSum(z)!==x[z]){curvyCorners.alert(this.errmsg("Not supported: unequal non-zero top/bottom radii with background image"))}var AL=(this.spec[z+"lR"]<this.spec[z+"rR"])?z+"l":z+"r";var l=document.createElement("div");l.style.height=x[z]+"px";l.style.width=this.spec.get(AL+"Ru");l.style.position="absolute";l.style.fontSize="1px";l.style.overflow="hidden";l.style.backgroundColor=this.boxColour;switch(AL){case"tl":l.style.bottom=l.style.left="0";l.style.borderLeft=this.borderString;this.topContainer.appendChild(l);break;case"tr":l.style.bottom=l.style.right="0";l.style.borderRight=this.borderString;this.topContainer.appendChild(l);break;case"bl":l.style.top=l.style.left="0";l.style.borderLeft=this.borderStringB;this.bottomContainer.appendChild(l);break;case"br":l.style.top=l.style.right="0";l.style.borderRight=this.borderStringB;this.bottomContainer.appendChild(l)}}var o=document.createElement("div");if(filter){o.style.filter=filter}o.style.position="relative";o.style.fontSize="1px";o.style.overflow="hidden";o.style.width=this.fillerWidth(z);o.style.backgroundColor=this.boxColour;o.style.backgroundImage=this.backgroundImage;o.style.backgroundRepeat=this.backgroundRepeat;switch(z){case"t":if(this.topContainer){if(curvyBrowser.quirksMode){o.style.height=100+H+"px"}else{o.style.height=100+H-this.borderWidth+"px"}o.style.marginLeft=this.spec.tlR?(this.spec.tlR-this.borderWidthL)+"px":"0";o.style.borderTop=this.borderString;if(this.backgroundImage){var AA=this.spec.tlR?(this.backgroundPosX-(H-this.borderWidthL))+"px ":"0 ";o.style.backgroundPosition=AA+this.backgroundPosY+"px";this.shell.style.backgroundPosition=this.backgroundPosX+"px "+(this.backgroundPosY-H+this.borderWidthL)+"px"}this.topContainer.appendChild(o)}break;case"b":if(this.bottomContainer){if(curvyBrowser.quirksMode){o.style.height=M+"px"}else{o.style.height=M-this.borderWidthB+"px"}o.style.marginLeft=this.spec.blR?(this.spec.blR-this.borderWidthL)+"px":"0";o.style.borderBottom=this.borderStringB;if(this.backgroundImage){var AA=this.spec.blR?(this.backgroundPosX+this.borderWidthL-M)+"px ":this.backgroundPosX+"px ";o.style.backgroundPosition=AA+(this.backgroundPosY-F-this.borderWidth+M)+"px"}this.bottomContainer.appendChild(o)}}}this.contentContainer.style.position="absolute";this.contentContainer.className="autoPadDiv";this.contentContainer.style.left=this.borderWidthL+"px";this.contentContainer.style.paddingTop=this.topPadding+"px";this.contentContainer.style.top=this.borderWidth+"px";this.contentContainer.style.paddingLeft=this.leftPadding+"px";this.contentContainer.style.paddingRight=this.rightPadding+"px";z=V;if(!curvyBrowser.quirksMode){z-=this.leftPadding+this.rightPadding}this.contentContainer.style.width=z+"px";this.contentContainer.style.textAlign=curvyBrowser.get_style(this.box,"textAlign");this.box.style.textAlign="left";this.box.appendChild(this.contentContainer);if(U){U.style.display="none"}};if(this.backgroundImage){R=this.backgroundCheck(R);P=this.backgroundCheck(P);if(this.backgroundObject){this.backgroundObject.holdingElement=this;this.dispatch=this.applyCorners;this.applyCorners=function(){if(this.backgroundObject.complete){this.dispatch()}else{this.backgroundObject.onload=new Function("curvyObject.dispatch(this.holdingElement);")}}}}}curvyObject.prototype.backgroundCheck=function(B){if(B==="top"||B==="left"||parseInt(B)===0){return 0}if(!(/^[-\d.]+px$/.test(B))&&!this.backgroundObject){this.backgroundObject=new Image;var A=function(D){var C=/url\("?([^'"]+)"?\)/.exec(D);return(C?C[1]:D)};this.backgroundObject.src=A(this.backgroundImage)}return B};curvyObject.dispatch=function(A){if("dispatch" in A){A.dispatch()}else{throw A.newError("No dispatch function")}};curvyObject.prototype.drawPixel=function(J,G,A,F,H,I,C,E){var B=document.createElement("div");B.style.height=H+"px";B.style.width="1px";B.style.position="absolute";B.style.fontSize="1px";B.style.overflow="hidden";var D=this.spec.get("tR");B.style.backgroundColor=A;if(C&&this.backgroundImage!=""){B.style.backgroundImage=this.backgroundImage;B.style.backgroundPosition="-"+(this.boxWidth-(E-J)+this.borderWidth)+"px -"+((this.boxHeight+D+G)-this.borderWidth)+"px"}if(F!=100){curvyObject.setOpacity(B,F)}B.style.top=G+"px";B.style.left=J+"px";I.appendChild(B)};curvyObject.prototype.fillerWidth=function(A){var B=curvyBrowser.quirksMode?0:this.spec.radiusCount(A)*this.borderWidthL;return(this.boxWidth-this.spec.radiusSum(A)+B)+"px"};curvyObject.prototype.errmsg=function(C,D){var B="\ntag: "+this.box.tagName;if(this.box.id){B+="\nid: "+this.box.id}if(this.box.className){B+="\nclass: "+this.box.className}var A;if((A=this.box.parentNode)===null){B+="\n(box has no parent)"}else{B+="\nParent tag: "+A.tagName;if(A.id){B+="\nParent ID: "+A.id}if(A.className){B+="\nParent class: "+A.className}}if(D===undefined){D="warning"}return"curvyObject "+D+":\n"+C+B};curvyObject.prototype.newError=function(A){return new Error(this.errmsg(A,"exception"))};curvyObject.IntToHex=function(B){var A=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];return A[B>>>4]+""+A[B&15]};curvyObject.BlendColour=function(L,J,G){if(L==="transparent"||J==="transparent"){throw this.newError("Cannot blend with transparent")}if(L.charAt(0)!=="#"){L=curvyObject.format_colour(L)}if(J.charAt(0)!=="#"){J=curvyObject.format_colour(J)}var D=parseInt(L.substr(1,2),16);var K=parseInt(L.substr(3,2),16);var F=parseInt(L.substr(5,2),16);var C=parseInt(J.substr(1,2),16);var I=parseInt(J.substr(3,2),16);var E=parseInt(J.substr(5,2),16);if(G>1||G<0){G=1}var H=Math.round((D*G)+(C*(1-G)));if(H>255){H=255}if(H<0){H=0}var B=Math.round((K*G)+(I*(1-G)));if(B>255){B=255}if(B<0){B=0}var A=Math.round((F*G)+(E*(1-G)));if(A>255){A=255}if(A<0){A=0}return"#"+curvyObject.IntToHex(H)+curvyObject.IntToHex(B)+curvyObject.IntToHex(A)};curvyObject.pixelFraction=function(H,G,A){var J;var E=A*A;var B=new Array(2);var F=new Array(2);var I=0;var C="";var D=Math.sqrt(E-Math.pow(H,2));if(D>=G&&D<(G+1)){C="Left";B[I]=0;F[I]=D-G;++I}D=Math.sqrt(E-Math.pow(G+1,2));if(D>=H&&D<(H+1)){C+="Top";B[I]=D-H;F[I]=1;++I}D=Math.sqrt(E-Math.pow(H+1,2));if(D>=G&&D<(G+1)){C+="Right";B[I]=1;F[I]=D-G;++I}D=Math.sqrt(E-Math.pow(G,2));if(D>=H&&D<(H+1)){C+="Bottom";B[I]=D-H;F[I]=0}switch(C){case"LeftRight":J=Math.min(F[0],F[1])+((Math.max(F[0],F[1])-Math.min(F[0],F[1]))/2);break;case"TopRight":J=1-(((1-B[0])*(1-F[1]))/2);break;case"TopBottom":J=Math.min(B[0],B[1])+((Math.max(B[0],B[1])-Math.min(B[0],B[1]))/2);break;case"LeftBottom":J=F[0]*B[1]/2;break;default:J=1}return J};curvyObject.rgb2Array=function(A){var B=A.substring(4,A.indexOf(")"));return B.split(", ")};curvyObject.rgb2Hex=function(B){try{var C=curvyObject.rgb2Array(B);var G=parseInt(C[0]);var E=parseInt(C[1]);var A=parseInt(C[2]);var D="#"+curvyObject.IntToHex(G)+curvyObject.IntToHex(E)+curvyObject.IntToHex(A)}catch(F){var H="getMessage" in F?F.getMessage():F.message;throw new Error("Error ("+H+") converting RGB value to Hex in rgb2Hex")}return D};curvyObject.setOpacity=function(F,C){C=(C==100)?99.999:C;if(curvyBrowser.isSafari&&F.tagName!="IFRAME"){var B=curvyObject.rgb2Array(F.style.backgroundColor);var E=parseInt(B[0]);var D=parseInt(B[1]);var A=parseInt(B[2]);F.style.backgroundColor="rgba("+E+", "+D+", "+A+", "+C/100+")"}else{if(typeof F.style.opacity!=="undefined"){F.style.opacity=C/100}else{if(typeof F.style.MozOpacity!=="undefined"){F.style.MozOpacity=C/100}else{if(typeof F.style.filter!="undefined"){F.style.filter="alpha(opacity="+C+")"}else{if(typeof F.style.KHTMLOpacity!="undefined"){F.style.KHTMLOpacity=C/100}}}}}};function addEvent(D,C,B,A){if(D.addEventListener){D.addEventListener(C,B,A);return true}if(D.attachEvent){return D.attachEvent("on"+C,B)}D["on"+C]=B;return false}curvyObject.getComputedColour=function(E){var F=document.createElement("DIV");F.style.backgroundColor=E;document.body.appendChild(F);if(window.getComputedStyle){var D=document.defaultView.getComputedStyle(F,null).getPropertyValue("background-color");F.parentNode.removeChild(F);if(D.substr(0,3)==="rgb"){D=curvyObject.rgb2Hex(D)}return D}else{var A=document.body.createTextRange();A.moveToElementText(F);A.execCommand("ForeColor",false,E);var B=A.queryCommandValue("ForeColor");var C="rgb("+(B&255)+", "+((B&65280)>>8)+", "+((B&16711680)>>16)+")";F.parentNode.removeChild(F);A=null;return curvyObject.rgb2Hex(C)}};curvyObject.format_colour=function(A){if(A!=""&&A!="transparent"){if(A.substr(0,3)==="rgb"){A=curvyObject.rgb2Hex(A)}else{if(A.charAt(0)!=="#"){A=curvyObject.getComputedColour(A)}else{if(A.length===4){A="#"+A.charAt(1)+A.charAt(1)+A.charAt(2)+A.charAt(2)+A.charAt(3)+A.charAt(3)}}}}return A};curvyCorners.getElementsByClass=function(H,F){var E=new Array;if(F===undefined){F=document}H=H.split(".");var A="*";if(H.length===1){A=H[0];H=false}else{if(H[0]){A=H[0]}H=H[1]}var D,C,B;if(A.charAt(0)==="#"){C=document.getElementById(A.substr(1));if(C){E.push(C)}}else{C=F.getElementsByTagName(A);B=C.length;if(H){var G=new RegExp("(^|\\s)"+H+"(\\s|$)");for(D=0;D<B;++D){if(G.test(C[D].className)){E.push(C[D])}}}else{for(D=0;D<B;++D){E.push(C[D])}}}return E};if(curvyBrowser.isMoz||curvyBrowser.isWebKit){var curvyCornersNoAutoScan=true}else{curvyCorners.scanStyles=function(){function B(F){var G=/^[\d.]+(\w+)$/.exec(F);return G[1]}var E,D,C;if(curvyBrowser.isIE){function A(L){var J=L.style;if(curvyBrowser.ieVer>6){var H=J["-webkit-border-radius"]||0;var K=J["-webkit-border-top-right-radius"]||0;var F=J["-webkit-border-top-left-radius"]||0;var G=J["-webkit-border-bottom-right-radius"]||0;var M=J["-webkit-border-bottom-left-radius"]||0}else{var H=J["webkit-border-radius"]||0;var K=J["webkit-border-top-right-radius"]||0;var F=J["webkit-border-top-left-radius"]||0;var G=J["webkit-border-bottom-right-radius"]||0;var M=J["webkit-border-bottom-left-radius"]||0}if(H||F||K||G||M){var I=new curvyCnrSpec(L.selectorText);if(H){I.setcorner(null,null,parseInt(H),B(H))}else{if(K){I.setcorner("t","r",parseInt(K),B(K))}if(F){I.setcorner("t","l",parseInt(F),B(F))}if(M){I.setcorner("b","l",parseInt(M),B(M))}if(G){I.setcorner("b","r",parseInt(G),B(G))}}curvyCorners(I)}}for(E=0;E<document.styleSheets.length;++E){if(document.styleSheets[E].imports){for(D=0;D<document.styleSheets[E].imports.length;++D){for(C=0;C<document.styleSheets[E].imports[D].rules.length;++C){A(document.styleSheets[E].imports[D].rules[C])}}}for(D=0;D<document.styleSheets[E].rules.length;++D){A(document.styleSheets[E].rules[D])}}}else{if(curvyBrowser.isOp){for(E=0;E<document.styleSheets.length;++E){if(operasheet.contains_border_radius(E)){C=new operasheet(E);for(D in C.rules){if(!isNaN(D)){curvyCorners(C.rules[D])}}}}}else{curvyCorners.alert("Scanstyles does nothing in Webkit/Firefox")}}};curvyCorners.init=function(){if(arguments.callee.done){return}arguments.callee.done=true;if(curvyBrowser.isWebKit&&curvyCorners.init.timer){clearInterval(curvyCorners.init.timer);curvyCorners.init.timer=null}curvyCorners.scanStyles()}}if(typeof curvyCornersNoAutoScan==="undefined"||curvyCornersNoAutoScan===false){if(curvyBrowser.isOp){document.addEventListener("DOMContentLoaded",curvyCorners.init,false)}else{addEvent(window,"load",curvyCorners.init,false)}};
