var bSearchAuto = false;


var gLockSearch = false;
var gReloadSearch = false;

var gChangeTab = false;

var gPathLoadMedia = "/images/work.gif";
var gPathSuppMedia = "/images/trash.gif";

function searchPageLoad()
{
    gChangeTab = true;
    window.currentPrefix='id';
    DisplayTab('profil');
    loadIframe();
}

function fillFinanSelect()
{
    var finIframe = document.getElementById("finNomencIframe");

    //remplissage des select financiers
    fillFinancSelect(finIframe, "bilan", "financListBilan");
    fillFinancSelect(finIframe, "result", "financListResult");
    fillFinancSelect(finIframe, "annex", "financListAnnex");
    fillFinancSelect(finIframe, "analyse", "financListGrille");

    document.getElementById("loading").style.display="none";
}

function fillFinancSelect(pIframe, psTrId, psSelectId)
{
    var i, option;

    var oSelect2 = pIframe.contentWindow.document.getElementById(psSelectId);
    var optionList = oSelect2.getElementsByTagName("OPTION");
    var oSelect = document.getElementById(psSelectId);

    for (i = 0;i < optionList.length; i++)
    {
        option = document.createElement("OPTION");
        option.appendChild(document.createTextNode(optionList[i].firstChild.data));
        option.className = optionList[i].className;
        option.setAttribute("value",optionList[i].getAttribute("value"));
        option.setAttribute("percent",optionList[i].getAttribute("percent"));
        option.setAttribute("disp",optionList[i].getAttribute("disp"));
        oSelect.appendChild(option);
    }
    document.getElementById(psTrId).style.display="";
}

function displayAlert() {
    var oDiv = document.getElementById("exportAlert");
    if (!oDiv.style.top) {
        oDiv.style.top = "-84px";
    }
    var iTop = parseInt(oDiv.style.top);
    if (oDiv.style.top == "0px"){
        setTimeout("removeAlert()",10000);
        return;
    }
    var newTop = iTop + 3;
    oDiv.style.top = new String(newTop) + "px";
    setTimeout("displayAlert()",50);
}

function removeAlert() {
    var oDiv = document.getElementById("exportAlert");
    var iTop = parseInt(oDiv.style.top);
    if (oDiv.style.top == "-90px")
        return;
    var newTop = iTop - 3;
    oDiv.style.top = new String(newTop) + "px";
    setTimeout("removeAlert()",50);
}

function removeCol(mnem)
{
    document.getElementById('rmv').value = mnem;
    document.getElementById('rmvCol').submit();
}

function setSlice()
{
    document.getElementById('slice').value = document.getElementById('sliceSelect').value;
    document.getElementById('formSetSlice').submit();
}

/* Function that checks if the user navigator is "Internet Explorer 5.0" */
function checkNavigator(psNavigator) {
    var oRegexp = new RegExp(psNavigator);
    if (oRegexp.test(navigator.userAgent))  return true;
    return false
}

function checkMoreIE5()
{
    if (checkNavigator("MSIE 5.0"))
        g("Attention, la version de votre navigateur ne permet pas d'utiliser tous les critères.");

}


function DisplayTab(prefix)
{
    if (!gChangeTab)
        return;
    if (prefix == "act" || prefix == "place")
        checkMoreIE5()
    var tab, button;
    var id, id_button;
    id= prefix + "_table";
    id_button = prefix + "_button";
    tab = document.getElementById(id);
    button = document.getElementById(id_button);

    if(tab.getAttribute("sel"))
        return;
    tab.className = "";
    try {
        var e,b;
        e = document.getElementById(window.currentPrefix+"_table")
        b = document.getElementById(window.currentPrefix+"_button")
        e.removeAttribute("sel");
        e.className = "hidden";
        b.className = "tab"
    } catch (exception) {}
    //GenerateRquestFromTab();

    window.currentPrefix = prefix;

    tab.setAttribute("sel","true");
    button.className = "tab_selected"

    //remplissage des select si il s'agit de l'onglet postes financiers
    if (prefix == "fp")
        LoadMuchFinancialField()
}

function AddFieldToSearch(poEltAdd, pbNotSearch, pbClick)
{
    if (poEltAdd.nodeName == "INPUT")
        poEltAdd = poEltAdd.parentNode;

    //Supprimer son ancienne sauvergarde si elle existe
    //Parcourir les tab enregistrés
    var oDivSave = document.getElementById("SearchFieldList");
    var aTable = oDivSave.getElementsByTagName("table");
    var oTr = poEltAdd.parentNode;
    var sTabletab
    var sMyTab = poEltAdd.parentNode.getAttribute("myTab");
    //Critère invalide
    //alert(oTr.getAttribute("valid"))
    if (oTr.getAttribute("valid") == 0)
        return;
    var oButton = document.getElementById( sMyTab + "_button");
    for (var i=0;i<aTable.length; i++) {
        sTabletab = aTable[i].getAttribute("tab");

        if (sTabletab == sMyTab + "_table") {
            var myTable = aTable[i]; //Tableau
            var aTr = myTable.getElementsByTagName("tr")
            for (var j = 0; j<aTr.length ; j++) {
                if (aTr[j].getAttribute("name") == poEltAdd.parentNode.getAttribute("name"))
                    var myTr = aTr[j];
            }
            break;
        }
    }
    var sContent = GetInput(poEltAdd.parentNode, myTr, pbClick);
//alert(sContent)
    if (!sContent)
        sContent = GetSelect(poEltAdd.parentNode, myTr);

    if (!sContent) {
        if(myTr) {
            //retirer le critère de la recherche
            var oTrash = myTr.getElementsByTagName("img")[0];
            RemoveSearchField(oTrash.id);
        }
        return;
    }

    if (myTable) {
        if (!myTr) //ceci est un nouveau critère de recherche a ajouté au tab
            myTable.appendChild(sContent);
    }
    else {
        var tdToAdd = document.getElementById("tdToAdd");
        var tabtoAdd = GetDispTabMemo( sMyTab + "_table" , oButton, sContent); //on ajoute le titre du tab + le critère
        var PrevNode = tdToAdd.getElementsByTagName("TABLE")[0];
        tdToAdd.appendChild(tabtoAdd)
        var oDivSaveTop = document.getElementById("SearchFieldListTop");
        oDivSave.removeAttribute("style");
        oDivSaveTop.removeAttribute("style");
        oDivSaveTop.innerHTML += " "
    }

    if (document.all)
        oDivSave.innerHTML += "  "; //fixed bug with IE

    if (aTable.length>0 && !pbNotSearch )
        SearchValue();
}

/*********************************************************************************************/
/*Fonction qui liste les objets de type SELECT dans un tab*/
function GetSelect(oTr, poTrMemo) {
    var aSelect = oTr.getElementsByTagName("SELECT");
    var sContent;

    for (var i = 0; i<aSelect.length ; i++) {
        var oSelectField = new oSelectSearchField(aSelect[i] , i);
        if (oSelectField.oSelect.value =='-1' || !oSelectField.IsValid()) continue;
        if (oSelectField.IsMake()) //On check s'il n'a pas déja eté traité, ça peut etre le cas s'il s'agit d'un intervalle
        {
            oSelectField.oSelect.removeAttribute("make");
            continue;
        }
        oSelectField.SetMemoElement();
        if (!(oSelectField.Query || oSelectField.BranchFilter))
            return;
        recordField(oSelectField);
        sContent = GetDispFieldSearch(oTr, oSelectField , poTrMemo);
    }
    return sContent;
}
/*********************************************************************************************/
/*Fonction qui récupère la position de la valeur selectionné dans un élément de type select*/
function GetOptionPositionSelected(poSelect) {
    if (poSelect.value==-1) return null;
    var aOption = poSelect.getElementsByTagName("OPTION");
    for (var i=0; i < aOption.length ; i++) {
        if (aOption[i].selected)
            return i;
    }
}

/*********************************************************************************************/
/*Fonction qui check si au moins un filtre sur la recherche sur nom de l'entreprise est coché*/
function checkNameFilter() {
    var tdCheckbox = document.getElementById("filterNameBox");
    var aInput = tdCheckbox.getElementsByTagName("input")
    for(var i=0; i<aInput.length; i++)
    {
        if(aInput[i].checked)
            return true;
    }
    return false;
}

function GetExactQuery(psValue)
{
    var sValue="";
    aValue = psValue.split(" ");
    for (var i=0; i<aValue.length; i++)
    {
        if (sValue!="")
            sValue += " "
        sValue += aValue[i] + "^";
    }
    return sValue;
}

/*********************************************************************************************/
/*Fonction qui génère la requête sur Nom ONGLET Dirigeants*/
function GetExactDir(psValue, psMnem)
{
    var oExactDir = document.getElementById("exactfilterDIR");
    if (psValue && oExactDir.checked)
        psValue = GetExactQuery(psValue);
    return "[" + psMnem + "] = '" + psValue + "'";
}

/*********************************************************************************************/
/*Fonction qui génère la requête sur Prénom ONGLET Dirigeants*/
function GetExactPDir(psValue, psMnem)
{
    var oExactPdir = document.getElementById("exactfilterPDIR");
    if (psValue && oExactPdir.checked)
        psValue = GetExactQuery(psValue);
    return "[" + psMnem + "] = '" + psValue + "'";
}

/*********************************************************************************************/
/*Fonction qui génère la requête sur Actionnnaire ONGLET lien*/
function GetExactAct(psValue, psMnem)
{
    var oExactInp = document.getElementById("exactfilterACT");
    if (psValue && oExactInp.checked)
        psValue = GetExactQuery(psValue);
    return "[" + psMnem + "] = '" + psValue + "'";
}

/*********************************************************************************************/
/*Fonction qui génère la requête sur Filiale ONGLET lien*/
function GetExactPar(psValue, psMnem)
{
    var oExactInp = document.getElementById("exactfilterPAR");
    if (psValue && oExactInp.checked)
        psValue = GetExactQuery(psValue);
    return "[" + psMnem + "] = '" + psValue + "'";
}
/*********************************************************************************************/
/*********************************************************************************************/
/*Fonction qui génère la requête sur le siret (SIRT)*/
function GetSIRTReq(psValue, psMnem)
{
    return "[" + psMnem + "]=" + psValue.substr(0, 9) + " AND [NIC] =" + psValue.substr(9, 14);
}
/*********************************************************************************************/
/*Fonction qui génère la requête sur raison sociale à partir des filtres*/
function GetFilterNameQuery(psValue)
{
    var tdCheckbox = document.getElementById("filterNameBox");
    var aInput = tdCheckbox.getElementsByTagName("input")
    var oExactInp = document.getElementById("exactfilter");
    sQuery = ""
    if (psValue && oExactInp.checked)
        psValue = GetExactQuery(psValue);
    for(var i=0; i<aInput.length; i++)
    {
        if(aInput[i].checked)
        {
            if(!psValue)
            {
                if (sQuery !="")
                    sQuery += "||";
                sQuery += aInput[i].value;
                continue;
            }
            if (sQuery !="")
                sQuery += " OR ";
            sQuery += "[" + aInput[i].value + "] = '" + psValue + "'";
        }
    }
    return sQuery;
}

/*********************************************************************************************/
/*Fonction qui coche le filtre selon le mnem passé en paramêtre*/
function CheckFilterNameFromQuery(psMnem, psExactFilter)
{
    if(!psMnem)
        psMnem = "NOM"
    var aMnem = psMnem.split("||");
    var tdCheckbox = document.getElementById("filterNameBox");
    var aInput = tdCheckbox.getElementsByTagName("input")
    sQuery = ""
        for(var i=0; i<aInput.length; i++)
        {
            for(var j=0; j<aMnem.length; j++)
            {
            if(aInput[i].value == aMnem[j])
            {
                aInput[i].checked = true;
                break;
            }
            else
                aInput[i].checked = false;
            }
    }
    //alert(psExactFilter);
    document.getElementById("exactfilter").checked = (psExactFilter)?true:false;
}

/*********************************************************************************************/
/*Fonction qui liste les objets de type INPUT dans un tab*/
function GetInput(oTr, poTrMemo, pbClick) {
    var aInput = oTr.getElementsByTagName("INPUT");
    var sContent;

    for (var i = 0; i < aInput.length; i++) {
        aInput[i].setAttribute("used", (pbClick ? "true" : "false"));
        var oInputField = new oInputSearchField(aInput[i], i);
//alert(aInput[i].parentNode.parentNode.getAttribute("name") + '/'+aInput[i].getAttribute("cbfilter"));
        if (
            ( !oInputField.IsCheckboxfilter() && (oInputField.IsEmptyField() || !oInputField.IsValid()) )
            || (oInputField.IsCheckboxfilter() && !oInputField.IsUsed())
           ) continue;

        if(oInputField.GetFieldName() == "NOM" && !checkNameFilter()) {
            alert("Veuillez cocher un critère");
            continue;
        }

        //On check s'il n'a pas déja eté traité, ça peut etre le cas s'il s'agit d'un intervalle
        if (oInputField.IsMake()) {
            oInputField.Input.removeAttribute("make");
            continue;
        }

        oInputField.SetMemoElement();
        recordField(oInputField);
        sContent = GetDispFieldSearch(oTr, oInputField, poTrMemo);
    }
    return sContent;
}

/*********************************************************************************************/
/*Fonction retournant le tab selectionné*/
function GetActifTab(TabParent)
{
    return document.getElementById(window.currentPrefix+"_table");
}

/*********************************************************************************************/
/*Fonction vérifiant que la valeur saisie dans un objet INPUT est bien une chaîne numérique*/
function ckeckDigit(poInput)
{
    var oTd = poInput.parentNode;
    var oInputList = oTd.getElementsByTagName("input");
    var iNbNoDigits = 0;
    var iNotValid = 0;
    for (var i=0; i<oInputList.length; i++) {
        if (oInputList[i].getAttribute("valid")=="0")
        {
            iNotValid++;
            continue;
        }
        if (!StringOfDigits(oInputList[i].value) && !IsEmpty(oInputList[i]))
            DisplayError(oInputList[i]);
        else
            RemoveError(oInputList[i]);
    }
}

function DisplayError(oInput)
{
    var oSpan = oInput.nextSibling;
    if (oSpan.firstChild)
        oSpan.firstChild.data = "Incorrect";
    else
        oSpan.appendChild(document.createTextNode("Incorrect"));
    oInput.parentNode.parentNode.setAttribute("valid", "0");
}

function RemoveError(oInput)
{
    var oSpan = oInput.nextSibling;
    if (oSpan.firstChild)
        oSpan.removeChild(oSpan.firstChild);
    oInput.parentNode.parentNode.setAttribute("valid", "1");
}

//Get the number of selected criteria for the given tab
function getTabCristeriaNumber(sTab) {
    var oDivSave = document.getElementById("SearchFieldList");
    var aTable   = oDivSave.getElementsByTagName("table");
    var myTable  = null;
    var iNb      = 0;
    var sTabletab;

    for (var i=0;i<aTable.length; i++) {
        sTabletab = aTable[i].getAttribute("tab");

        if (sTabletab == sTab + "_table") {
            var myTable = aTable[i]; //Tableau
            var aTr = myTable.getElementsByTagName("tr")
            return (aTr.length > 0 ? aTr.length : 0);
        }
    }

    return 0;
}

/*Fonction générant une ligne pour critère recherché */
function GetDispFieldSearch(poTr, poField, poTrMemo)
{
    //Check if a localisation criteria has already been choosed.
    //Otherwise make impossible the adding of the criteria "Localisation > Etablissements secondaires"
    if (poTr.getAttribute("name") == "_branchfilter") {
        var sMyTab         = poTr.getAttribute("myTab");
        var iCriteriaTabNb = getTabCristeriaNumber(sMyTab);

        if (iCriteriaTabNb == 0)
            return;
    }
    var iBranchFilter = (!poField.BranchFilter ? 0 : poField.BranchFilter);
    if (poTrMemo) {
        poTrMemo.setAttribute("request", poField.Query);
        poTrMemo.setAttribute("branchfilter", iBranchFilter);
        var oInput = poTrMemo.getElementsByTagName("input")[0];
        //alert(oInput);
        var bCheck = oInput.checked;

        var firstTd = poTrMemo.getElementsByTagName("td")[1];
        firstTd.removeChild(firstTd.firstChild);
        firstTd.appendChild(poField.TextMemo);
        try {
            poTrMemo.innerHTML += "   ";
        } catch(err){}
        poTrMemo.getElementsByTagName("input")[0].checked = bCheck;
        return 1
    }
    var tr = document.createElement("TR");
    var td1 = document.createElement("TD");
    var td2 = document.createElement("TD");
    var td3 = document.createElement("TD");
    var input = document.createElement("INPUT");
    input.setAttribute("type","checkbox");
    if (poField.GetObjectElement().getAttribute("disabField")=="true") {
        input.defaultChecked = false;
        tr.setAttribute("disab","true");
        poField.GetObjectElement().removeAttribute("disabField");
    } else
        input.defaultChecked = true;
    input.setAttribute("onclick","DisabledSearchField(this)");
    input.setAttribute("title","Activer / Désactiver ce critère.");
    tr.setAttribute("name",poField.GetFieldName());
    tr.setAttribute("request", poField.Query);
    if (iBranchFilter > 0)
        tr.setAttribute("branchfilter", iBranchFilter);

    var img   = document.createElement("IMG");
    var sRmId = poTr.getAttribute("name") + "_rmimg";
    img.setAttribute("src",gPathSuppMedia);
    img.id        = sRmId;
    img.className = "imgHand";
    img.setAttribute("border","0");
    img.setAttribute("align","bottom");
    img.setAttribute("title","Supprimer ce critère.");
    img.setAttribute("onclick","RemoveSearchField('" + sRmId + "')");
    var data1     = document.createTextNode(poField.GetDispName());
    td1.className = "fieldSearch titlefieldmemo";
    td2.className = "titlevaluememo";
    td3.className = "titlefuncmemo";
    td1.appendChild(data1);
    td2.appendChild(poField.TextMemo);
    td3.appendChild(input);
    td3.appendChild(img);
    tr.appendChild(td1);
    tr.appendChild(td2);
    tr.appendChild(td3);

//	alert(tr.innerHTML);
    return tr;
}

/*Fonction générant une ligne pour le titre du tab dans le tableau mémo */
function GetDispTabTitleMemo(poButton)
{
    var tr = document.createElement("TR");
    var td1 = document.createElement("TD");
    var data1 = document.createTextNode( GetButtonText(poButton) );
    td1.className="titletabmemo";
    td1.appendChild(data1);
    td1.setAttribute("colspan","3");
    tr.appendChild(td1);
    return tr;
}

function GetButtonText(poButton)
{
    var oNode = poButton
    while(oNode.firstChild)
        oNode = oNode.firstChild;
    return oNode.data;

}

/*Fonction générant un tableau du tab recherché*/
function GetDispTabMemo(psTabId, poButton, psContent)
{
    var table = document.createElement("TABLE");
    table.setAttribute("tab",psTabId);
    table.setAttribute("border","0");
    table.setAttribute("cellpadding","0");
    table.setAttribute("cellspacing","0");
    table.style.marginTop ="1px";
    table.appendChild(GetDispTabTitleMemo(poButton));
    table.appendChild(psContent);
    return table;
}

/*********************************************************************************************/
/****************************************   SEARCH   *****************************************/
/*********************************************************************************************/
function SearchValue() {

    if (gLockSearch) //Une recherche est déja en cours
    {
        gReloadSearch = true //Une recherche devra être realancé une fois terminé
        return;
    }
    gLockSearch = true; //Aucune recherche ne peut être tant que celle-ci n'est pas terminée
    gReloadSearch = false; //Pas besoin de relancer la recherche

    var oDivSave = document.getElementById("SearchFieldList");
    var oDivSaveTop = document.getElementById("SearchFieldListTop");
    var aTr = oDivSave.getElementsByTagName("TR");
    var iBranchFilter = 0;
    var sRequest="";
    for (var i=0; i < aTr.length; i++ ) {
        if (aTr[i].getAttribute("request") || aTr[i].getAttribute("branchfilter"))
        {
            aTr[i].disabled = true;
            aTr[i].getElementsByTagName("input")[0].disabled = true;
            aTr[i].getElementsByTagName("img")[0].disabled = true;
        }
        if (!(aTr[i].getAttribute("request") || aTr[i].getAttribute("branchfilter")) || aTr[i].getAttribute("disab")=="true") continue;

        if (aTr[i].getAttribute("request")) {
            if (sRequest!="") sRequest += " AND ";
            sRequest += unescape(aTr[i].getAttribute("request"));
        }

        if (aTr[i].getAttribute("branchfilter"))
            iBranchFilter = aTr[i].getAttribute("branchfilter");
    }
    RemoveResultCount();
    CheckToDisplayResultCount();
    document.getElementById("requestSearch").value      = escape(sRequest);
    document.getElementById("requestInput").value       = escape(sRequest);
    document.getElementById("branchfilterSearch").value = iBranchFilter;
    document.getElementById("branchfilterInput").value  = iBranchFilter;
    if(sRequest.split("[SIRT]").length>1){
        document.getElementById("forsiret").value = "True";
    }else{
        document.getElementById("forsiret").value = "False";
    }
    window.setTimeout("document.getElementById(\"formSearch\").submit();",0);
}

function CheckToDisplayResultCount() {
    var oDivSave = document.getElementById("SearchFieldList");
    var oDivSaveTop = document.getElementById("SearchFieldListTop");
    var aTr = oDivSave.getElementsByTagName("TR");
    if (aTr.length==2)
    {
        oDivSaveTop.style.display = "none";
        oDivSave.style.display="none";
        gLockSearch = false;
        RemoveResultCount();
        return;
    }
}

function AddResultCount(piCountResult, bSearchBefore) {
    gLockSearch  = false;
    var oDivSave = document.getElementById("SearchFieldList");
    var aTr      = oDivSave.getElementsByTagName("TR");
    document.getElementById("resultmemo").firstChild.data    = piCountResult
    document.getElementById("resultmemo").className          = "resultmemo";
    document.getElementById("resultmemoTop").firstChild.data = piCountResult
    document.getElementById("resultmemoTop").className       = "resultmemo";


    for (var i=0; i < aTr.length ; i++ ) {
        if (aTr[i].getAttribute("request") || aTr[i].getAttribute("branchfilter")) {
            oDivSave.style.display                           = "block"; //Fix a IE problem (the criteria box didn't appear!)
            aTr[i].disabled                                  = false;
            aTr[i].getElementsByTagName("input")[0].disabled = false;
            aTr[i].getElementsByTagName("img")[0].disabled   = false;
        }
    }

    if (gReloadSearch) SearchValue();
    document.getElementById("dispButtonTop").disabled = (piCountResult==0);
    if(document.getElementById("dispButtonBot")) document.getElementById("dispButtonBot").disabled = (piCountResult==0);
    if(document.getElementById("dispButtonBot2") && document.getElementById("SousDispButton") && document.getElementById("FusDispButton") && document.getElementById("CroisDispButton")){
        document.getElementById("dispButtonBot2").disabled = (piCountResult==0);
        document.getElementById("SousDispButton").disabled = (piCountResult==0);
        document.getElementById("FusDispButton").disabled = (piCountResult==0);
        document.getElementById("CroisDispButton").disabled = (piCountResult==0);
    }

   /* if(bSearchBefore){
        document.getElementById("SousDispButton").style.display="none";
    }else{
        document.getElementById("SousDispButton").style.display="inline";
    }*/
    if (piCountResult==0) {
        if(document.getElementById("dispButtonBot2") && document.getElementById("SousDispButton") && document.getElementById("FusDispButton") && document.getElementById("CroisDispButton")){
            document.getElementById("SousDispButton").style.backgroundColor="#ECECEC";
            document.getElementById("FusDispButton").style.backgroundColor="#ECECEC";
            document.getElementById("CroisDispButton").style.backgroundColor="#ECECEC";
            document.getElementById("dispButtonBot2").style.backgroundColor="#ECECEC";
        }
        document.getElementById("dispButtonTop").style.backgroundColor="#ECECEC";
        if(document.getElementById("dispButtonBot")) document.getElementById("dispButtonBot").style.backgroundColor="#ECECEC";
    } else {
        if(document.getElementById("dispButtonBot2") && document.getElementById("SousDispButton") && document.getElementById("FusDispButton") && document.getElementById("CroisDispButton")){
            document.getElementById("SousDispButton").style.backgroundColor="#414141";
            document.getElementById("FusDispButton").style.backgroundColor="#414141";
            document.getElementById("CroisDispButton").style.backgroundColor="#414141";
            document.getElementById("dispButtonBot2").style.backgroundColor="#414141";
        }
        document.getElementById("dispButtonTop").style.backgroundColor="#414141";
        if(document.getElementById("dispButtonBot")) document.getElementById("dispButtonBot").style.backgroundColor="#414141";
    }

    if(bSearchAuto) {
        document.getElementById('speedQuery').value='';
        document.getElementById('viewSearch').submit();
    }
}

function RemoveResultCount()
{
   document.getElementById("resultmemo").className          = "searchWork";
   document.getElementById("resultmemo").firstChild.data    = ""
   document.getElementById("resultmemoTop").className       = "searchWork";
   document.getElementById("resultmemoTop").firstChild.data = ""
}


/*Function use to add the zip Field*/
function AddCopoField(poButton, psValue0, psValue1)
{
    if(!poButton)
        poButton = document.getElementById("COPO1");
    poTd = poButton.parentNode;
    var aInput = poTd.getElementsByTagName("input");
    oInput0 = aInput[0].cloneNode(true);
    oInput1 = aInput[1].cloneNode(true);
    oInput0.setAttribute("valid","0");
    oInput1.setAttribute("valid","0");

    if(!psValue0) psValue0 = "";
    if(!psValue1) psValue1 = "";
    oInput0.value = psValue0;
    oInput1.value = psValue1;
    oInput0.id = "";
    oInput1.id = "";


    var oDiv = document.createElement("div");
    var oSpan = document.createElement("span");
    oSpan.className = "errorDigit"
    oDiv.appendChild(oInput0);
    oDiv.appendChild(oSpan.cloneNode(true));
    oDiv.appendChild(oInput1);
    oDiv.appendChild(oSpan);
    poButton.parentNode.appendChild(oDiv);
}

function GetMultiZipQuery(psQuery, pbMemoText, pbMemoQuery)
{
    var oZipBox = document.getElementById("COPO1");
    var aDiv = oZipBox.parentNode.getElementsByTagName("div");

    if (!aDiv.length && pbMemoQuery) return "";
    if (!aDiv.length) return psQuery;

    var sQuery = "";
    var zipQuery = "";
    for (var i=0; i< aDiv.length;i++)
    {
        zipQuery = GetZipQuery(aDiv[i], pbMemoText, pbMemoQuery);
        if (!zipQuery)
            continue;
        if(pbMemoQuery)
        {
            if (sQuery !="") sQuery +="||";
            sQuery += zipQuery;
            continue;
        }
        if(!pbMemoText)
            sQuery += " OR (" + zipQuery + ")";
        else
            sQuery += " OU " + zipQuery + "";
    }
    if(pbMemoQuery) return sQuery;
    return "(" + psQuery + ")" + sQuery
}

function GetZipQuery(poDiv, pbMemoText, pbMemoQuery)
{
    var sFieldName = "COPO"
    aInput = poDiv.getElementsByTagName("input");
    oInput0 = aInput[0];
    if (!StringOfDigits(oInput0.value) && !IsEmpty(oInput0))
        return;
    oInput1 = aInput[1];
    if (!StringOfDigits(oInput1.value) && !IsEmpty(oInput1))
        return;
    if(IsEmpty(oInput0) && IsEmpty(oInput1))
        return;
    iValue0 = Number(oInput0.value)
    iValue1 = Number(oInput1.value)
    if (iValue0 > iValue1 && !IsEmpty(oInput1))
    {
        iValue1 = iValue0;
        oInput1.value = oInput0.value;
    }

    if(pbMemoQuery) return iValue0 + "#" + iValue1;

    if(!pbMemoText)
    {
        if (IsEmpty(oInput1))   return "[" + sFieldName + "] > " + iValue0;
        if (IsEmpty(oInput0))   return "[" + sFieldName + "] < " + iValue1;
        if (iValue1 == iValue0) return "[" + sFieldName + "] = " + iValue1;
        if (iValue1 > iValue0)  return "[" + sFieldName + "] > " + iValue0 + " AND [" + sFieldName + "] < " + iValue1;
    }
    else
    {
            if (IsEmpty(oInput1))   return "supérieur ou égal à "+ iValue0;
            if (IsEmpty(oInput0))   return "inférieur ou égal à "+ iValue1;
            if (iValue1 == iValue0) return iValue1;
            if (iValue1 > iValue0)  return "entre " + iValue0 + " et " + iValue1;
    }
}

function SetMultiZip(psZipRequest)
{
    var aZip = psZipRequest.split("||");
    var aVal;
    for(var i=0; i< aZip.length; i++)
    {
        aVal = aZip[i].split("#");
        AddCopoField(null, aVal[0], aVal[1]);
    }
}


/*******************************************************************************************************************************/
/*******************************************************************************************************************************/
/************************************ Gestion Des options de selection sur les nomeclature en arbre ****************************/
/*******************************************************************************************************************************/
/*******************************************************************************************************************************/

/***** RECHERCHE CONTEXTUELLE *****/

function searchContextLoca() {
    var oInput = document.getElementById("ncLabelLoca");
    if (IsEmpty(oInput))
        return;

    document.getElementById("locat").setAttribute("niv","0");

    window.oLocation.RemoveMemo();
    window.oLocation.AddWaitMedia();
    window.oLocation.SearchContentSelect('', '', oInput.value, '');
}

function searchContextActi() {
    var oInput = document.getElementById("ncLabelActi");
    if (IsEmpty(oInput))
        return;

    // search checked radio input
    var oBox = document.getElementById("actBoxRadio");
    var aInput = oBox.getElementsByTagName("input");
    for(var i=0; i<aInput.length; i++) {
        if(aInput[i].checked)
            break;
    }

    document.getElementById("acty").setAttribute("niv", "0");

    var sDirectory = aInput[i].getAttribute("sDirectory");
    window.oActivity.RemoveMemo();
    window.oActivity.AddWaitMedia();
    window.oActivity.SearchContentSelect(sDirectory, '', oInput.value, '');
}
/***** FIN DE RECHERCHE CONTEXTUELLE ****/

// copy selection from virtual window(psExplorerId) to main window (psSelect2Id)
function addLocat(psExplorerId, psSelect2Id) {
    var oSelect  = document.getElementById(psExplorerId);
    var oSelect2 = document.getElementById(psSelect2Id);
    oSelect2.style.display = "";

    var aItem = oSelect.getElementsByTagName("DIV");
    for (var i=0;i<aItem.length;i++) {
        if (aItem[i].selected) {
            var option = document.createElement("OPTION");
            if (aItem[i].childNodes.length > 1)
                option.appendChild(document.createTextNode(aItem[i].childNodes[1].firstChild.data));
            else
                option.appendChild(document.createTextNode(aItem[i].childNodes[0].firstChild.data));
            option.setAttribute("value", aItem[i].getAttribute("value"))
            option.setAttribute("mnem", aItem[i].getAttribute("mnem"))
            option.setAttribute("parent", aItem[i].getAttribute("parent"))

            oSelect2.appendChild(option);
            aItem[i].selected = false;
            aItem[i].className = "explorerItem";
            oCurrentWin.closeWin();
            oCurrentWin.showWin(true);
        }
    }
}

function addOption(poOption, sSelect2Id) {
    var oOption = poOption.cloneNode(true);
    var oSelect = document.getElementById(sSelect2Id);
    oSelect.appendChild(oOption);
}

function removeOption(poSelect)
{
    var aOption = poSelect.getElementsByTagName("OPTION");
    for (var i=0;i<aOption.length;i++)
    {
        if (aOption[i] != null && aOption[i].selected)
            poSelect.removeChild(aOption[i]);
    }
    if(!poSelect.options.length)
        poSelect.style.display="none";
}


function LoadLocationList()
{
    var oSelect =  document.getElementById("locat");

    if( !oSelect ) return;   //empêche une erreur quand l'utilisateur doit se logger

    document.getElementById("locat").setAttribute("niv","0");
    LoadLocation("locat", "LOC", 2, "locatvalue", "formUpdNomenc", "updLocation", "root");
}

function DisplayListActyConc(psValue)
{
    var oSelect = document.getElementById("acty");

    window.oActivity = new ExplorerObject(oSelect, "updActivity", "formUpdNomenc",  2);
    window.oActivity.SearchContentSelect("NAF", "", "", psValue.substr(0,3) );
}

function DisplayListActy(poInput) {
    if(!poInput) {
      var oBox = document.getElementById("actBoxRadio");
      if (!oBox) return;    //empêche une erreur quand l'utilisateur doit se logger
      var aInput = oBox.getElementsByTagName("input");
      for(var i=0; i<aInput.length; i++) {
        if(aInput[i].checked)
          break;
      }
      poInput = aInput[i];
    }
    else
      if (poInput.getAttribute("actif")) return;

    aInput = poInput.parentNode.getElementsByTagName("INPUT")
    for ( var i = 0; i<aInput.length; i++)
        aInput[i].removeAttribute("actif");
    poInput.setAttribute("actif","true");

    document.getElementById("acty").setAttribute("niv","0");

    iLevel = (poInput.getAttribute("sDirectory") == "NAF2" ? 4: 2);
    LoadActivity("acty", poInput.getAttribute("sDirectory"), iLevel, "actyvalue", "formUpdNomenc", "updActivity", "root");
}


function LoadLocation(psSelectId, psMnem, piLevel, psMemoId, psFormId, psFrameId, psValue)
{
    var oSelect = document.getElementById(psSelectId);
    window.oLocation = new ExplorerObject(oSelect, psFrameId, psFormId, piLevel, psMemoId);
    if(psMemoId)
    {
        window.oLocation.RemoveMemo();
        window.oLocation.AddWaitMedia();
    }
    window.oLocation.SearchContentSelect(psMnem, "", "", psValue );
}

function LoadActivity(psSelectId, psMnem, piLevel, psMemoId, psFormId, psFrameId, psValue) {
    var oSelect = document.getElementById(psSelectId);
    window.oActivity = new ExplorerObject(oSelect, psFrameId, psFormId, piLevel, psMemoId);
    if(psMemoId) {
        window.oActivity.RemoveMemo();
        window.oActivity.AddWaitMedia();
    }
    window.oActivity.SearchContentSelect(psMnem, "", "", psValue );
}



/****************************************************************************************/
/**************************************  LIST SETTING   **************************************/
/*********************************************************************************************/
/*fonction permettant de desactiver un critère de recherche*/
function DisabledSearchField(poCheckbox)
{
    if(poCheckbox.checked)
    {
        EnabledSearchField(poCheckbox);
        return;
    }
    var oTr = poCheckbox.parentNode.parentNode;
    oTr.setAttribute("disab","true");
    toggleRecordField(oTr.getAttribute("name"))

    var oTabForm = document.getElementById("listTab");
    var aTr = oTabForm.getElementsByTagName("tr");
    for (var i=0; i<aTr.length; i++) {
        if(aTr[i].getAttribute("name") == oTr.getAttribute("name"))
            break
    }
    var aSelect = aTr[i].getElementsByTagName("select");
    for ( i=0; i<aSelect.length; i++)
        aSelect[i].setAttribute("disabField","true");
    var aInput = aTr[i].getElementsByTagName("input");
    for ( i=0; i<aInput.length; i++)
        aInput[i].setAttribute("disabField","true");
    SearchValue();
}

/*fonction permettant d'activer un critère de recherche*/
function EnabledSearchField(poCheckbox) {
    var oTr = poCheckbox.parentNode.parentNode;
    oTr.removeAttribute("disab");
    toggleRecordField(oTr.getAttribute("name"))
    var oTabForm = document.getElementById("listTab");
    var aTr = oTabForm.getElementsByTagName("tr");
    for (var i=0; i<aTr.length; i++) {
        if(aTr[i].getAttribute("name") == oTr.getAttribute("name"))
            break;
    }
    var aSelect = aTr[i].getElementsByTagName("select");
    for ( i=0; i<aSelect.length; i++)
        aSelect[i].removeAttribute("disabField");
    var aInput = aTr[i].getElementsByTagName("input");
    for ( i=0; i<aInput.length; i++)
        aInput[i].removeAttribute("disabField");

    SearchValue();
}

function launchFilter(typeFilter){
    document.getElementById('speedQuery').value='';
    document.getElementById('filterResult').value=typeFilter;
    document.getElementById('viewSearch').submit();
}

function ResetSearch(bCombine) {
    var sCombine = "";
    if(bCombine) sCombine = "&combi=1";
    document.location.href = "/search/recherche.asp?reset=1"+sCombine;
}


/*fonction permettant de supprimer un critère de recherche*/
function RemoveSearchField(psImg) {
    var oImg             = document.getElementById(psImg);
    var oTr              = oImg.parentNode.parentNode;
    var oCriteriaTab     = oTr.parentNode;
    var oInputSelect     = oImg.parentNode.getElementsByTagName("input")[0];
    var bReloadSearch    = oInputSelect.checked;
    var sName            = oTr.getAttribute("name");
    var oBranchCriteria  = null;
    var bRemoveBranch    = false;
    var oTrForm, aTr, sRemoveImg;
    var i;

    //Get the Tab (and check if the parent node is 'tbody' - problem with IE)
    oCriteriaTab = (oCriteriaTab.nodeName.toLowerCase() == "tbody" ? oCriteriaTab.parentNode : oCriteriaTab);

    //Remove the criteria "Localisation > Etablissements secondaires" if necessary
    //(ie. when no other localisation criteria remains)
    if (oCriteriaTab.getAttribute("tab") == "place_table" && oTr.getAttribute("name") != "_branchfilter") {
        aTr = oCriteriaTab.getElementsByTagName("TR");
        for (i=0; i<aTr.length; i++) {
            if (aTr[i].getAttribute("name") == "_branchfilter")
                oBranchCriteria = aTr[i];
        }

        //Check if the only remaining items after removing the current criteria will be the branches ones
        if (oBranchCriteria && aTr.length-1 == 2)
            bRemoveBranch = true;
    }

    if (document.getElementById("listTab")) {
        aTr = document.getElementById("listTab").getElementsByTagName("TR");
        for (i= 0; i<aTr.length; i++) {
            if (aTr[i].getAttribute("name") == sName) {
                oTrForm = aTr[i];
                break;
            }
        }
    }

    if (oTrForm) {
        var aSelect = oTrForm.getElementsByTagName("SELECT");
        for (i=0;i<aSelect.length; i++)
            UnSelectOption(aSelect[i]);

        var aInput = oTrForm.getElementsByTagName("INPUT");
        for (i=0; i <aInput.length; i++) {
            if (aInput[i].getAttribute("valid") != "0")
                aInput[i].value = "";
            if (aInput[i].getAttribute("used"))
                aInput[i].removeAttribute("used");
        }
    }

    var oDivSave = document.getElementById("SearchFieldList");
    //Get the Tab (and check if the parent node is 'tbody' - problem with IE)
    var oTable = oTr.parentNode;
    oTable     = (oTable.nodeName.toLowerCase() == "tbody" ? oTable.parentNode : oTable);
    oTr.parentNode.removeChild(oTr);//Suppression du critère dans le mémo
    if (oTable.getElementsByTagName("TR").length == 1)
        oTable.parentNode.removeChild(oTable);//Suppression du tab dans le mémo

    removeRecordField(sName); //Suppression du critère dans la sauvegarde des critères

    if (bRemoveBranch) {
        sRemoveImg = oBranchCriteria.getElementsByTagName("img")[0].id;
        if(bReloadSearch)
          SearchValue();
        setTimeout("RemoveSearchField(\"" + sRemoveImg + "\");", 100);
    } else {
        CheckToDisplayResultCount();
        if(bReloadSearch)
          SearchValue();
    }
}

function UnSelectOption(poSelect)
{
    if (poSelect.getAttribute("operator") == "==")
    {
        while(poSelect.options.length)
            poSelect.options[0] = null;
        poSelect.style.display="none";
        return;
    }
    var aOption = poSelect.getElementsByTagName("OPTION");
    poSelect.value=0;
    for (var i=0;i<aOption.length;i++)
        aOption[i].selected=false;
}


/*********************************************************************************************/
/************************************** FINACIALS SETTING ************************************/
/*********************************************************************************************/
function addFinancialField(piIdSelect)
{
    var oSelect = document.getElementById(piIdSelect);
    var oElement = oSelect.parentNode.parentNode.parentNode
    var aTr = oElement.getElementsByTagName("tr")
    var isFinanc=false;
    for (var i=0; i<aTr.length; i++)
    {
        if(aTr[i].getAttribute("financ"))
            isFinanc=true;
        if (isFinanc && !aTr[i].getAttribute("financ"))
            break;
    }
    var lastTr = aTr[i];


    var posOption = GetOptionPositionSelected(oSelect);
    var oOption = oSelect.getElementsByTagName("OPTION")[posOption];
    var sMnem = oOption.value;
    var sPercent = (oOption.getAttribute("percent") == "true") ? "true" : "false";
    if (!sMnem)
        return;
    if (document.getElementById(sMnem + "1"))
        return;
    var sText = oOption.getAttribute("disp");

    var newTr = aTr[i-1].cloneNode(true);
    newTr.getElementsByTagName("TD")[0].firstChild.data = unescape(sText);
    newTr.setAttribute("name",sMnem);
    var inp0 = newTr.getElementsByTagName("INPUT")[0];
    var inp1 = newTr.getElementsByTagName("INPUT")[1];
    inp0.setAttribute("dispName",sText);
    inp1.setAttribute("dispName",sText);
    inp0.id = sMnem + "1";
    inp1.id = sMnem + "2";
    inp0.setAttribute("percent", sPercent);
    inp1.setAttribute("percent", sPercent);
    inp0.value = "";
    inp1.value = "";
    lastTr.parentNode.insertBefore(newTr,lastTr);
    document.getElementById("addmnem").value = 1;
    document.getElementById("newmnem").value = sMnem;
    if (sPercent == "true")
        document.getElementById("typepercent").value = "true";
    window.setTimeout("document.getElementById(\"formupdFinanc\").submit();",1);
}

function removeFinancialField(poImg)
{
    var oElement = poImg.parentNode.parentNode.parentNode;
    aTr = oElement.getElementsByTagName("TR");
    var iCount = 0;
    for (var i=0; i<aTr.length; i++)
    {
        if(aTr[i].getAttribute("financ"))
            iCount++;
    }
    if(iCount==1) return;
    var oTr = poImg.parentNode.parentNode;
    var SMnem = oTr.getAttribute("name");
    oTr.parentNode.removeChild(oTr);
    document.getElementById("addmnem").value = 0;
    document.getElementById("newmnem").value = SMnem;
    window.setTimeout("document.getElementById(\"formupdFinanc\").submit();",1);
}

/*********************************************************************************************/
/************************************** QUICK SEARCHES ***************************************/
/*********************************************************************************************/

/* Lance la recherche à partir des 2 champs dans la "frame" de gauche */
function launchQuickSearch(oEvent) {
    try {
        var oForm, oInput1, oInput2;
        oInput1 = document.getElementById("quickSearchField1");
        oInput2 = document.getElementById("quickSearchField2");
        var sValue = oInput1.value
//        sValue = removeAccents(sValue);
        sValue = sValue.replace(/\x2D/g, " ");
        var sStringValue = sValue.replace(/[^a-z0-9àâäçéèëêïîôù&@ ]/gi, "");
        var sNumericValue = sValue.replace(/\D/g, "");
        var sNumericValue2 = oInput2.value.replace(/\D/g, "");
        var sQuery = "";

        if (oEvent.keyCode != 13) return

        if (sStringValue == "" && sNumericValue == "" && sNumericValue2 == "") return
        if (sStringValue != "" || sNumericValue != "") {
            if (sNumericValue == "") sNumericValue = "0";
            sQuery += "( [ENSE] = '" + sStringValue + "' OR [SIGL] = '" + sStringValue + "' OR [NOM] = '" + sStringValue + "' OR [SIR] = " + sNumericValue + " )"; // " OR [DUNS] = " + sNumericValue + 
        }
        if (sNumericValue2 != "") {
            if (sQuery != "") sQuery += " AND ";
            sQuery += "([DEP] = '" + sNumericValue2 + "')";
        }
        oForm = document.getElementById("viewSearch");
        document.getElementById("speedField1").value        = sStringValue;
        document.getElementById("speedField2").value        = sNumericValue2;
        document.getElementById('speedQuery').value         = "1";
        document.getElementById("requestSearch").value      = sQuery;
        document.getElementById("branchfilterSearch").value = "0";
        oForm.submit();
    } catch (err) {
        alert(err);
    }
}


function removeAccents(sString) {
    var sReturn = sString.replace(/[éèêë]/gi,"e");
    sReturn = sReturn.replace(/[àäâ]/gi,"a");
    sReturn = sReturn.replace(/[îï]/gi,"i");
    sReturn = sReturn.replace(/[ùûü]/gi,"u");
    sReturn = sReturn.replace(/[ôö]/gi,"o");
    sReturn = sReturn.replace(/[ç]/gi,"c");
    sReturn = sReturn.replace(/[ñ]/gi,"n");
    return sReturn;
}


/*********************************************************************************************/
/*************************************** SAVE SEARCHES ***************************************/
/*********************************************************************************************/
function loadIframe()
{
    if ( !document.getElementById("frameLoad"))
        return;
    document.getElementById("frameLoad").setAttribute("src","loadSearchForm.asp")
}

/*Fonction parcourant le DOM du XML contenant la sauvegarde des critères puis effectue
la recherche dès que tous les critères ont été remplis*/
function loadSearchForm(poDocument)
{
    var aSpan = poDocument.getElementsByTagName("span");
    var oSpan;
    var sValue, sId, sMnem, sText;
    for (var i = 0 ; i<aSpan.length ; i++)
    {
        oSpan = aSpan[i];
        sId = oSpan.id;
        sValue = oSpan.getAttribute("value");
        sMnem = oSpan.getAttribute("mnem");

        /***************************** Cas Particulier ***********************************************/
        if (oSpan.getAttribute("filter") ||(sId == "NOM1" ))
            CheckFilterNameFromQuery(oSpan.getAttribute("filter"), oSpan.getAttribute("filterExact"));

        if (oSpan.getAttribute("filterExact") &&(sId == "NDIR1" ))
            document.getElementById("exactfilterDIR").checked = true;

        if (oSpan.getAttribute("filterExact") &&(sId == "PDIR1" ))
            document.getElementById("exactfilterPDIR").checked = true;

        if (oSpan.getAttribute("filterExact") &&(sId == "NPAR1" ))
            document.getElementById("exactfilterPAR").checked = true;

        if (oSpan.getAttribute("filterExact") &&(sId == "NACT1" ))
            document.getElementById("exactfilterACT").checked = true;

        if (oSpan.getAttribute("copoMulti") && sId == "COPO1")
            SetMultiZip(oSpan.getAttribute("copoMulti"));
        /*********************************************************************************************/

        sText = oSpan.getAttribute("text");
        loadField(sId, sValue, sMnem, sText, oSpan.getAttribute("disab") =="1");
    }
    var arrTd = document.getElementById("listTab").getElementsByTagName("TD");
    for (var i=0;i<arrTd.length;i++)
    {
        if (arrTd[i].className != "AddButton") continue;
        AddFieldToSearch(arrTd[i],true);
    }
    if (aSpan.length)
        SearchValue();
}

/*Fonction permettant de remplir le critère dans le formaulaire*/
function loadField(psId, psValue, psMnem, psText, pbDisab)
{
    var oElement = document.getElementById(psId);
    if (!oElement)
    {
        removeRecordField(psMnem)
        return;
    }
    if (oElement.nodeName=="INPUT")
    {
        if (pbDisab)
            oElement.setAttribute("disabField","true");
        if (oElement.getAttribute("typevalue") == "Date")
            oElement.value = psValue.substr(6,2) + "-" + psValue.substr(4,2) + "-" + psValue.substr(0,4);
        else
            oElement.value = unescape(psValue);
    }
    if (!psValue) //Il s'agit d'un select
    {
        oElement.selected = true;
        if (pbDisab)
            oElement.parentNode.setAttribute("disabField","true");
    }


    if (psText && psMnem)//Il s'agit de Departement et Activité
    {


        oElement.style.display = "";
        var option = document.createElement("OPTION");
        option.appendChild(document.createTextNode( unescape(psText) ));
        option.setAttribute("value", unescape(psValue) )
        option.setAttribute("mnem", unescape(psMnem) )
        oElement.appendChild(option);
        if (pbDisab)
            oElement.setAttribute("disabField","true");
    }

}

/*Fonction permettant de sauvegarder le critère ajouté à la recherche en cours*/
function recordField(poField) {
    var oValue = document.getElementById("valueSave")
    var oMnem = document.getElementById("mnemSave")
    var oText = document.getElementById("textSave")
    var oMnemParent = document.getElementById("mnemParent");
    var oType = document.getElementById("typeSave");
    var oPercent = document.getElementById("percentSave");
    var oOperator = document.getElementById("operatorSave");

    oPercent.value = (poField.GetObjectElement().getAttribute("percent"))?"1":"";
    oValue.value = "";
    oMnem.value = "";
    oText.value = "";
    document.getElementById("idSave").value= poField.xmlID;
    document.getElementById("offField").value= "";
    oMnemParent.value = poField.xmlMNEM;
    oType.value       = poField.GetObjectElement().getAttribute("typevalue");
    oOperator.value   = poField.GetOperator();

    if(poField.xmlMNEM=="NOM") {
        document.getElementById("filterName").value = GetFilterNameQuery();
        document.getElementById("filterExactName").value = (document.getElementById("exactfilter").checked)?"1":"";
    }
    if(poField.xmlMNEM=="NDIR")
        document.getElementById("filterExactName").value = (document.getElementById("exactfilterDIR").checked)?"1":"";
    if(poField.xmlMNEM=="PDIR")
        document.getElementById("filterExactName").value = (document.getElementById("exactfilterPDIR").checked)?"1":"";
    if(poField.xmlMNEM=="NACT")
        document.getElementById("filterExactName").value = (document.getElementById("exactfilterACT").checked)?"1":"";
    if(poField.xmlMNEM=="NPAR")
        document.getElementById("filterExactName").value = (document.getElementById("exactfilterPAR").checked)?"1":"";

    if(poField.xmlMNEM=="COPO")
        document.getElementById("copoMulti").value = GetMultiZipQuery( null, false, true);

    if (poField.xmlID && poField.xmlVALUE) //Save field of INPUT type
        document.getElementById("valueSave").value = escape(poField.xmlVALUE);

    if (poField.arrOption) //SELECT for location and ACTIVITY
    {
        oValue.value = "";
        oMnem.value = "";
        oText.value = "";
        for (var i = 0; i < poField.arrOption.length ; i++) {
            if (i > 0) {
                oValue.value += "||";
                oMnem.value  += "||";
                oText.value  += "||";
            }
            oValue.value += escape(poField.arrOption[i].value);
            oMnem.value  += escape(poField.arrOption[i].getAttribute("mnem"));
            oText.value  += escape(poField.arrOption[i].text);
        }
    }

    window.setTimeout("document.getElementById(\"formupdSearchForm\").submit();",0);
}

/*Fonction permettant de supprimer un critère à la sauvegarde*/
function removeRecordField(psMnem) {
    var oValue = document.getElementById("valueSave")
    var oMnem = document.getElementById("mnemSave")
    var oText = document.getElementById("textSave")
    var oMnemParent = document.getElementById("mnemParent");

//alert('oValue.value:'+oValue.value);
//alert('oMnemParent.value:'+oMnemParent.value);
//alert('document.getElementById("idSave").value:'+document.getElementById("idSave").value);
//alert(document.getElementById("formupdSearchForm").attributes.getNamedItem("action").value );

    document.getElementById("idSave").value= "";
    document.getElementById("offField").value= "";
    oValue.value = "";
    oMnem.value = "";
    oText.value = "";
    oMnemParent.value = psMnem;
    window.setTimeout("document.getElementById(\"formupdSearchForm\").submit();",0);
}

/*Fonction permettant de desactiver ou réactiver un critère dans la sauvegarde*/
function toggleRecordField(psMnem) {
    var oValue = document.getElementById("valueSave")
    var oMnem = document.getElementById("mnemSave")
    var oText = document.getElementById("textSave")
    var oMnemParent = document.getElementById("mnemParent");
    document.getElementById("idSave").value= "";
    document.getElementById("offField").value= "1";
    oValue.value = "";
    oMnem.value = "";
    oText.value = "";
    oMnemParent.value = psMnem;
    window.setTimeout("document.getElementById(\"formupdSearchForm\").submit();",0);
}


/*******************************************************************************/
/*************************************RESULT LIST*******************************/
/*******************************************************************************/

function displayResultListSetting(poHref)
{
    var myTr = poHref;
    while(myTr.nodeName.toLowerCase() !='tr')
        myTr = myTr.parentNode;
    var trToCollapsed = myTr.nextSibling;

    while(trToCollapsed.nodeName.toLowerCase() !='tr')
        trToCollapsed = trToCollapsed.nextSibling;
    if (trToCollapsed.style.display)
        trToCollapsed.style.display="";
    else
        trToCollapsed.style.display="none"
}

function SortList(psSlice, psSortOrder) {
    var iCount= Number(document.getElementById("rsCount").value);
    if (iCount > 1000) {
        alert("Merci d\'affiner votre recherche pour trier votre liste.")
        return;
    }
    var strBask = "";
    if( !IsEmpty(document.getElementById("DisplayBask") ) )
        strBask = "&DisplayBask=1"

    var img = document.createElement("img");
    img.setAttribute("src",gPathLoadMedia);
    var span = document.createElement("SPAN");
    span.appendChild(document.createTextNode ("Tri en cours..."));
    span.className = "waitMessage";
    var div = document.getElementById("resultDiv");
    while (div.firstChild)
        div.removeChild(div.firstChild)
    div.className = "waitMessage";
    div.appendChild(img);
    div.appendChild(span);

    document.location.href = "?slice=" + psSlice + "&sortOrder=" + psSortOrder + strBask
}


/*******************************************************************************/
/*************************************SIREN DUNS SETTING*******************************/
/*******************************************************************************/
function CheckValueBefore(poButton)
{
    var aInput = poButton.parentNode.getElementsByTagName("INPUT");
    for (var i = 0; i<aInput.length ; i++)
    {
        var oInputField = new oInputSearchField(aInput[i] , i);
        if (oInputField.IsEmptyField() || !oInputField.IsValid()) continue;
        var sName = oInputField.GetFieldName();
        if (sName=="TEL")
        {
           var sValue = oInputField.Input.value.replace(/[^0-9]/gi,"");
           if(sValue.length != 10)
            {
                alert("La valeur saisie n\'est pas correcte");
                return;
            }
        }
        else
        {
           var len;
           if(sName=="SIRT"){
               len = 14;
           }else{
               len = 9;
           }
           var sValue2 = "";
           for(var z=0; z<len;z++){
               sValue2 = sValue2 + "0";
           }
           sValue2 += oInputField.Input.value.replace(/[^0-9]/gi,"");
           var sValue = sValue2.substr(sValue2.length - len,len);
        }
        if (( sName=="SIR" && !checkSiren(sValue)) || ( sName=="SIRT" && !checkSiret(sValue)) || ( sName=="DUNS" && !checkDuns(sValue)))
        {
            alert("La valeur saisie n\'est pas correcte");
            return;
        }
        oInputField.Input.value = sValue;
    }
    AddFieldToSearch(poButton);
}

function ToggleSirenList(poButton)
{
    var tdSiren = poButton.parentNode;
    var tdChild = tdSiren.childNodes;
    var bIsDisp = false;
    //var aInput = tdSiren.getElementsByTagName("INPUT");
    for (var i=0; i < tdChild.length; i++)
    {
        if (tdChild[i].nodeType == 3) continue;
        if (tdChild[i].style.display == "none")
        {
            tdChild[i].style.display = ""
            //tdChild[i].removeAttribute("style");
            tdChild[i].setAttribute("valid",tdChild[i].getAttribute("dispName")?"1":"0");
            bIsDisp = true;
        }
        else
        {
            tdChild[i].setAttribute("valid","0");
            tdChild[i].style.display = "none";
        }
    }
    if (bIsDisp)
        return;
    var divList = document.getElementById("SirenList");
    var aChild = divList.childNodes;
    for (var i=0; i < aChild.length; i++)
        tdSiren.appendChild(aChild(i).cloneNode(true));
}

function addFormList(poImg, psName)
{
    try
    {
        var oTxt = poImg.parentNode.getElementsByTagName("TEXTAREA")[0];
        var sTxt = oTxt.value;
        var reg = new RegExp("[^0-9]","gi");
        var aTxt = sTxt.split("\n");
        var sOptionText;
        var oOption;
        var oSelect = poImg.parentNode.getElementsByTagName("SELECT")[0];
        var dataFalse = ""
        for (var i=0; i < aTxt.length ; i++)
        {
            sOptionText = aTxt[i].replace(/[^0-9]/gi,"");
            if (!sOptionText.length) continue;
            if (psName !="COVI" && psName !="TEL"){
                var len = 9;
                if(psName =="COVI"){
                    len = 5;
                }else if(psName =="SIRT"){
                    len = 14;
                }
                var sValue = "";
                for(var z=0; z<len;z++)
                    sValue = sValue + "0";

                sValue += sOptionText.replace(/[^0-9]/gi,"");
                sOptionText = sValue.substr(sValue.length - len,len);
            }else if (psName =="TEL"){
                if(sOptionText.length !=10)
                {
                    dataFalse += sOptionText+"\n";
                    continue;
                }
            }
            if (checkDoubleOption(oSelect, sOptionText))
            {
                sTxt = sTxt.replace(aTxt[i]+"\n","");
                continue;
            }
            if (psName=="SIR" && !checkSiren(sOptionText))
            {
                dataFalse += sOptionText+"\n";
                continue;
            }
            if (psName=="DUNS" && !checkDuns(sOptionText))
            {
                dataFalse += sOptionText+"\n";
                continue;
            }
            oOption = document.createElement("OPTION");
            oOption.setAttribute("mnem", psName);
            oOption.setAttribute("value", sOptionText);
            oOption.appendChild(document.createTextNode(sOptionText));
            oSelect.appendChild(oOption);
            sTxt = sTxt.replace(aTxt[i]+"\n","");
        }
        var msg = "";
        if (psName=="SIR")
            msg = "Siren ";
        else
            msg = "DUNS ";
        if (psName=="TEL")
            msg = "Numéro ";
        oTxt.value = sTxt;
        if (dataFalse!="")
            alert(msg + "non conformes :\n" + dataFalse);
    } catch (err) {
        alert("ERROR function addSirenList:\n" + err);
    }
}

function checkDoubleOption(poSelect, psValue)
{
    var aOption = poSelect.getElementsByTagName("OPTION");
    for (var i=0; i<aOption.length ; i++)
    {
        if (aOption[i].value == psValue)
            return true;
    }
    return false;
}


//Fonction vérifiant la validité du siren saisi
function checkSiren(piSiren){
    if(piSiren.length !=9)
        return false;
    return checkAlgoLuhn(piSiren);
}
function checkSiret(piSiret){
    if(piSiret.length !=14)
        return false;
    return checkAlgoLuhn(piSiret);
}
function checkAlgoLuhn(piNumber)
{
    try
    {
        var NumCar, Car, toModulo,ValCar, modCar, val
        toModulo = 0;
        for (var i=0; i<piNumber.length ; i++)
        {
            ValCar = Number(piNumber.substr(i,1));
            if (i%2!=0)
                ValCar = Number(ValCar)*2;
            if (ValCar > 9)
                toModulo += (ValCar-9);
            else
                toModulo += ValCar;
        }
        return (toModulo%10 == 0)
    } catch (err) {
        alert("ERROR function checkAlgoLuhn:\n" + err);
    }
}

function checkDuns(piDuns)
{
    try
    {
        if (piDuns.length !=9)
            return false;
        var result1 = new String(piDuns.substr(1, 1)*2);
        var result2 = new String(piDuns.substr(3, 1)*2);
        var result3 = new String(piDuns.substr(5, 1)*2);
        var result4 = new String(piDuns.substr(7, 1)*2);
        var result = Number(result1.substr(0, 1)) + Number(result2.substr(0, 1)) + Number(result3.substr(0, 1)) + Number(result4.substr(0, 1));
        if (Number(result1) > 9) result += Number(result1.substr(1, 1));
        if (Number(result2) > 9) result += Number(result2.substr(1, 1));
        if (Number(result3) > 9) result += Number(result3.substr(1, 1));
        if (Number(result4) > 9) result += Number(result4.substr(1, 1));
        var accum = result + Number(piDuns.substr(0, 1)) + Number(piDuns.substr(2, 1)) + Number(piDuns.substr(4, 1)) + Number(piDuns.substr(6, 1));

        var key = (accum % 10)
        if (key > 0)
            var key = 10 - key
        if (key == Number(piDuns.substr(8, 1)))
            return true;
        else {
            key += ((key>4)?-5:5);
            return key == Number(piDuns.substr(8, 1))
        }
    } catch (err) {
        alert("ERROR function checkDuns :\n" + err);
    }
}


//Utilikser pour le chargement du formulaire de la recherche concurrentielle
function loadConcForm(piTre, piCaps, piReg, psNaf, pbTimeOut) {
    var oInput= document.getElementById("FL2");
    var oTd = oInput.parentNode;
    var oSelect = document.getElementById("percent");
    oTd.appendChild(oSelect);
}

function updateCaps(oSelect, psValue) {
    var aOption = oSelect.getElementsByTagName("OPTION");
    for (var i=0; i < aOption.length ; i++) {
        if (aOption[i].selected)
            break;
    }
    var iPercent = aOption[i].value;
    document.getElementById("FL1").value= Math.round( psValue - ( psValue*(iPercent/100) ));
    document.getElementById("FL2").value= Math.round( psValue + (psValue*(iPercent/100) ));
}


//Fonction pour charger les deux selects pour la recherche avancée du DataPasse
function loadDpassAdvancedSearch()
{
    HideAllDpassForm();
    HideDpassForm(document.getElementById("acty_button"))
//    DisplayListActy();
}

function HideAllDpassForm()
{
    var oTable = document.getElementById("dpass_table");
    var aTr = oTable.getElementsByTagName("tr");
    for(var i=0; i<aTr.length; i++)
    {
        var oTr = aTr[i];
        if(oTr.getAttribute("type") != "group")
            oTr.style.display="none";
        else
        {
            try {
            oTr.getElementsByTagName("div")[0].className="formGroup";
            }
            catch(err){}
        }
    }

}

function HideDpassForm(poTd)
{
    oTr = poTd.parentNode;
    var iCount = 0;

    var oSelect = document.getElementById("financListBilan");
    var bNomencIsLoaded = (oSelect.getElementsByTagName("option").length > 0);


    while (oTr.nextSibling)
    {
        oTr = oTr.nextSibling;
        if(oTr.nodeName!= "TR" )
            continue;
        if(oTr.getAttribute("type") != "group")
        {
            if(oTr.style.display == "") //On replie le form
            {
                HideAllDpassForm();
                return;
            }
            else
            {
                if(iCount == 0)
                {
                    HideAllDpassForm();
                    poTd.getElementsByTagName("div")[0].className="formGroupSel";
                }
            }
            if( oTr.getAttribute("type") == "FinancNomenc" && !bNomencIsLoaded)
                continue;
            oTr.style.display="";
            iCount++;
        }
        else
            return;
    }
}


function openActivity(poEvt)
{
    closeAllVirtualWin();
    window.actiBox = new virtualWin("activityBox", poEvt, 380, 238);
    window.actiBox.showWin();
    if (!document.getElementById("acty").explorer)
        DisplayListActy();
}

function openPju(poEvt)
{
    closeAllVirtualWin();
    window.pjuBox = new virtualWin("pjuBox",poEvt, 380, 148);
    window.pjuBox.showWin();
    var oSelect = document.getElementById("pjuBox");
    window.oPju = new ExplorerObject(oSelect, null, null, 0, null);
}


function reloadActivityField() {
    AddFieldToSearch(document.getElementById('ActAddButton'));
}

function openLocation(poEvt)
{
    closeAllVirtualWin();
    window.locaBox = new virtualWin("locationBox",poEvt, 380, 225);
    window.locaBox.showWin();
    if (!document.getElementById("locat").explorer)
        LoadLocationList();
}
function openBankSearch(poEvt)
{
    closeAllVirtualWin();
    window.locaBox = new virtualWin("bankLocationBox",poEvt, 380, 225, 0, -50);
    window.locaBox.showWin();
    if (!document.getElementById("locat").explorer)
        LoadLocationList();
}

function openLocationConc(poEvt)
{
    closeAllVirtualWin();
    window.locaBox = new virtualWin("locationBox",poEvt, 380, 225);
    window.locaBox.showWin();
    if (!document.getElementById("locat").explorer)
        LoadLocationList();
}

function openActivityConc(poEvt, psNaf)
{
    closeAllVirtualWin();
    window.actiBox = new virtualWin("activityBox",poEvt, 380, 238);
    window.actiBox.showWin();
    if (!document.getElementById("acty").explorer)
        DisplayListActyConc(psNaf);
}



function reloadPjuField()
{
    AddFieldToSearch(document.getElementById('PjuAddButton'))
}


function reloadLocationField()
{
    AddFieldToSearch(document.getElementById('LocAddButton'))
}

function reloadBankField(){
    AddFieldToSearch(document.getElementById('BankAddButton'))
}
function addAllField(psTabId)
{
    oTr = document.getElementById(psTabId).parentNode;
    iCount = 0
    while (oTr.nextSibling)
    {
        oTr = oTr.nextSibling;
        if(oTr.nodeName!= "TR" )
            continue;
        if(oTr.getAttribute("type") != "group")
        {
            //Parcourir les td pour Ajouter le critère (Simuler le click sur le bouton AddButton)
            var aTd = oTr.getElementsByTagName("td");
            for (var i=0;i<aTd.length;i++)
            {
                if (aTd[i].className != "AddButton") continue;
                AddFieldToSearch(aTd[i],true);
                iCount +=1
            }

        }
        else
        {
            if (iCount > 0) SearchValue();
            return;
        }
    }
    if (iCount > 0) SearchValue();

}


function closeAllVirtualWin()
{
    try
    {
    if(oCurrentWin)
        oCurrentWin.closeWin();
    }
    catch(err){}
}

function LoadMuchFinancialField()
{
    if (document.getElementById("bilan").style.display != "none") return;
    document.getElementById("finNomencIframe").src = "/search/finNomenc.asp"
}

function printList()
{
    var strBask
    if( !IsEmpty(document.getElementById("DisplayBask") ) )
        strBask = "&DisplayBask=1"
    window.open("/search/resultList.asp?print=1"+strBask);
}

function SetBasket(psMisc)
{
    document.getElementById("basketIframe").setAttribute("src","/user/setBasket.asp?"+psMisc);
}

function showDiffButton(sSiren, sSiren2)
{
    document.getElementById('sirenDif').value           = sSiren;
    document.getElementById('sirenDif2').value          = sSiren2;
    document.getElementById('compbutton').style.display ="block";
}

function doDiffSearch()
{
    setTimeout("document.getElementById('dif_Form').submit();",10);
}

//Utiliser simplement pour ouvrir une POPUP aide
function GotoHelp(psLink)
{
    var x;
    var y;
    var win;
    var Largeur = 640;
    var Hauteur = 480;
    if (navigator.appName == 'Netscape') {
        adjWidth = Largeur ;
        adjHeight = Hauteur + 25;
    }
    else {
        adjWidth = Largeur ;
        adjHeight = Hauteur ;
    }

    if (win != null){
        win.close();
    }
    x = (screen.availWidth - Largeur) / 2 ;
    y = (screen.availHeight - Hauteur) / 2 ;
    win = window.open(psLink, 'Aide', 'left='+ x +',top='+ y +',toolbar=no,Resizable=Yes,menubar=no,location=no,Status=no,scrollbars=yes,width='+ adjWidth +',height='+ adjHeight +',alwaysRaised=yes');
    if (win.opener == null) win.opener = window;
    win.focus();
}
function switchSelectAllSubThis(obj){
    var opt;
    var bSwitch = false;
    var nbElement = obj.options.length;
    if(nbElement==0) return;
    for(var i=0 ; i<nbElement ; i++){
        opt = obj.options[i];
        if(parseInt(opt.value)==-1){
            bSwitch = opt.selected;
            opt.selected = false;
        }else{
            if(bSwitch) opt.selected = !opt.selected
        }
    }
}



var xhr_object = null;

function ajax(url, objDisplay, callFunction){
    xhr_object = null;
    if(window.XMLHttpRequest){ // Firefox
        xhr_object = new XMLHttpRequest();
    }else if(window.ActiveXObject){ // Internet Explorer
        xhr_object = new ActiveXObject("Microsoft.XMLHTTP");
    }else { // XMLHttpRequest non supporté par le navigateur
        alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest...");
        return;
    }
    xhr_object.open("GET", url, true);

    xhr_object.onreadystatechange = function() {
        if(xhr_object.readyState == 4){
            if(callFunction){
                eval(callFunction + "(objDisplay, xhr_object.responseText)");
            }else{
                objDisplay.innerHTML = xhr_object.responseText;
            }
        }
    }
    xhr_object.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
    xhr_object.send(null)
}
function getListTown(){
    var sSearch = document.getElementById("villeLabel").value;
    var objDisplay = document.getElementById("listville");
    if(!sSearch || sSearch.replace(" ","")==""){
        objDisplay.innerHTML ="";
        return;
    }
    var url = locationHref()+"rechbank.asp?search="+sSearch
    ajax(url, objDisplay);
}
function getListBank(sBankInsee){
    var objDisplay = document.getElementById("listbank");
    if(sBankInsee==""){
        objDisplay.innerHTML ="";
        return;
    }
    var url = locationHref()+"rechbank.asp?insee="+sBankInsee
    ajax(url, objDisplay);
}
function locationHref(){
    var aHref = location.href.split("/");
    aHref.pop();
    return aHref.join("/") + "/";
}
function goInMotherSearch(){
    var oSelect = document.getElementById('selectbanksearch');
    var oSelectRecept= document.getElementById('bankChoice');
    oSelectRecept.style.display = "";
    var optionSel;
    var oSelectReceptKey = [];
    for(var i=0;i<oSelectRecept.options.length;i++){
        oSelectReceptKey[oSelectRecept.options[i].value] = true;
    }
    for(var i=0;i<oSelect.options.length;i++){
        optionSel = oSelect.options[i];
        if(optionSel.selected){
            if(!oSelectReceptKey[optionSel.value]){
                optNew = document.createElement("OPTION");
                oSelectRecept.appendChild(optNew, null);
                optNew.setAttribute("mnem", "BANK");
                optNew.setAttribute("value", optionSel.value)
                optNew.appendChild(document.createTextNode(optionSel.text));
                optNew.setAttribute("class", "explorerItem");
            }
        }
    }
}

