﻿icon["defaulticon"] = new GIcon();
icon["defaulticon"].image = iconeDir + "marker.png";
icon["defaulticon"].shadow = "http://www.google.com/mapfiles/shadow50.png";
icon["defaulticon"].iconSize = new GSize(20, 34);
icon["defaulticon"].shadowSize = new GSize(37, 34);
icon["defaulticon"].iconAnchor = new GPoint(9, 34);
icon["defaulticon"].infoWindowAnchor = new GPoint(9, 2);
icon["defaulticon"].infoShadowAnchor = new GPoint(18, 25);

/******************************************************************/
/*                Fonctions pour les marqueurs                    */
/******************************************************************/
function LabelMark(produit, titre, description) {
    //On va chercher en ajax les informations de la fiche produit
    //url: leiv3/ficheLEI.php?champ1=181000290&xslfichier=xslt/fiche_std.xsl
    MarkLabel[produit] = "Chargement en cours...";
    resp = "<div class='bulle'><h2>" + titre + "</h2>" + description + "<div class='bulleOption'><a onclick='javascript:unPrintUnlessProduct(" + produit + ");' href='#' />Produits à proximité</a></div></div>";
    MarkLabel[produit] = resp;

    //var tableauArg = produit.split("-");
    //sendRequest('http://localhost:1207/Produit.aspx?cartoInit=p' + tableauArg[0], "get", function(resp) {
    //    MarkLabel[produit] = resp;
    //});
}

function getLabelOne(num) {
    return '<div style="margin-bottom:10px;color:#434343;font-size:0.9em;font-family:arial;">' + MarkLabel[num] + '</div>';
}

function getLabelTab(num, num_tab) {
    return '<div style="margin-bottom:10px;color:#434343;font-size:0.9em;font-family:arial;">' + MarkLabel[num] + '<input type="hidden" id="mult_prod" value="1"><input type="hidden" id="hid_produit_' + num_tab + '" value=' + num + '>' + '</div>';
}

function txtMaxUrl(produit, m_async, object_div) {
    var resp_lei;

    //On va chercher en ajax les informations de la fiche produit
    //url: leiv3/ficheLEI.php?champ1=181000290&xslfichier=xslt/fiche_std.xsl
    var myXHR = new XR({ async: m_async, method: 'get',
        onSuccess: function(resp) {
            resp_lei = resp;
        }
    }).send(urlMoteur + produit);
    return resp_lei;
}

function showMarker(marker, texte) {
    marker.openInfoWindowHtml(texte);
}

function showInfoWindowMap() {
    var info = document.createElement('div');
    info.setAttribute('id', 'info_load');
    var span = document.createElement('span');
    var text = document.createTextNode('Chargement des données en cours...');
    span.appendChild(text);
    info.appendChild(span);
    document.getElementById('MapLeiContentContainer').appendChild(info);
}

function hideInfoWindowMap() {
    var info = document.getElementById('info_load');
    document.getElementById('MapLeiContentContainer').removeChild(info);
}

/******************************************************************/
/*                Creation d'un objet marker                      */
/******************************************************************/
function createMarker(point, title, texte, numprod, typeprod, opt, id_mark) {

    var maxContentDiv = document.createElement('div');
    if (icon[typeprod]) {
        var marker = new GMarker(point, icon[typeprod]);
    } else {
        var marker = new GMarker(point, icon["i0"]); // icone par defaut
    }
    
    GEvent.addListener(marker, "click", function() {
        var pres = 0;
        var ficheEach = 0;
        var tabPoints = Array();

        for (cp = 0; cp < MarkTab.length; cp++) {
            if (MarkTab[cp] != this && IsNear(this, MarkTab[cp]) && MarkTabInfo[cp] != numprod && MarkTabInfoIsActive[cp] == true) {
                pres = 1;
                break;
            }
        }

        if (pres) {
            tabPoints.push(new GInfoWindowTab("Fiche 1", getLabelTab(numprod, 0)));
            var iTabF = 1;
            var iFiche = 1;
            for (cp = 0; cp < MarkTab.length; cp++) {
                if (MarkTab[cp] != this && IsNear(this, MarkTab[cp]) && MarkTabInfo[cp] != numprod && MarkTabInfoIsActive[cp] == true) {
                    ficheEach = 0;
                    for (cpt = cp + 1; cpt < MarkTab.length; cpt++) {
                        if (IsNear(MarkTab[cp], MarkTab[cpt]) && MarkTabInfo[cpt] == MarkTabInfo[cp]) {
                            ficheEach = 1;
                            break;
                        }
                    }
                    if (ficheEach == 0) {
                        pres = 1;
                        var i = tabPoints.length + 1;
                        iFiche++;
                        tabPoints.push(new GInfoWindowTab("Fiche " + iFiche, getLabelTab(MarkTabInfo[cp], iTabF)));
                        iTabF++;
                        if (i == 10) {
                            break;
                        }
                    }
                }
            }
        }

        if (!pres) {
            texte = "Chargement en cours...";
            texte = getLabelOne(numprod);
            marker.openInfoWindowHtml(texte, { maxWidth: 450, maxContent: maxContentDiv, maxTitle: title });
            var iw = map.getInfoWindow();
            //alert("test");
            if (!isNaN( parseInt (numprod)) ) {
                //alert(parseInt(numprod));
                var maxHandler = GEvent.addListener(iw, "maximizeclick",
                function() {
                    maxContentDiv.innerHTML = 'Chargement en cours...'
                    if (MarkTabDetail[numprod]) {
                        maxContentDiv.innerHTML = MarkTabDetail[numprod];
                    } else {
                        //alert("http://localhost:3912/Default.aspx?produit=" + numprod);
                        GDownloadUrl(urlMoteur + numprod , function(data) {
                            //alert(numprod);
                            MarkTabDetail[numprod] = data;
                            maxContentDiv.innerHTML = data;
                        });
                    }
                })
            }

        } else {
            var options = {
                maxWidth: 450,
                selectedTab: 0,
                maxContent: maxContentDiv 
            };
            marker.openInfoWindowTabsHtml(tabPoints, options);

            var iw = map.getInfoWindow();
            var maxHandler = GEvent.addListener(iw, "maximizeclick",
            function() {
                if (document.getElementById('mult_prod')) {
                    var iTab = map.getInfoWindow().getSelectedTab();
                    var id_hid = "hid_produit_" + (iTab);
                    var prod_data = document.getElementById(id_hid).value;
                    maxContentDiv.innerHTML = 'Chargement en cours...'
                    if (MarkTabDetail[prod_data]) {
                        maxContentDiv.innerHTML = MarkTabDetail[prod_data];
                    } else {
                        //alert("http://localhost:3912/Default.aspx?produit=" + prod_data);
                        GDownloadUrl(urlMoteur + prod_data, function(data) {
                            //alert(prod_data);
                            MarkTabDetail[prod_data] = data;
                            maxContentDiv.innerHTML = data;
                        });
                    }
                }
            })

            var minHandler = GEvent.addListener(iw, "restoreclick",
    	    function() {
    	        if (document.getElementById('mult_prod')) {
    	            var data = document.getElementById('table_geo_max');
    	            maxContentDiv.removeChild(data);
    	        }
    	    })
        }

        lock = true;
    });

    return marker;
}
/******************************************************************/
/*                Fonctions ajax pour la creation des marker     */
/******************************************************************/

// récupération des produits depuis une modalité
//Retourne le texte du panneau formatté
function printForModalite(modalites) {
    if (markLockLoading == false) {
        document.getElementById("LoaderDisplay").style.display = "block";
        markLockLoading = true;
        sendRequest('xml/xmlproduits.aspx?cartoInit=' + modalites, "get", test_xml);
    }
    return true;
}

function printForAutourDe(produit) {
    if (markLockLoading == false) {
        document.getElementById("LoaderDisplay").style.display = "block";
        markLockLoading = true;
        markLockMenu = true;
        sendRequest('xml/xmlproduitautourde.aspx?cartoInit=' + produit, "get", test_xml);
    }
    return true;
}

function sendRequest(my_url,my_method,fx,data) 
{
	//alert(typeof(fx));
	var url = my_url;
	var mymethod = my_method;
	var myAjax = new Ajax(url,{
			 method:mymethod,
			 data:data,	
			onComplete:fx
			 }).request();
}

function test_xml(xml)
{
    //alert(xml);
    if (window.ActiveXObject) {
        var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(xml);
    } else {
        var parser = new DOMParser();
        var xmlDoc = parser.parseFromString(xml, "text/xml");
    }

    var id = 0;
    var name = "";
    var longitude = 0.0;
    var latitude = 0.0;
    var icon = "defaulticon";
    var index = MarkTab.length;

    //alert(xmlDoc.getElementsByTagName("ID").length);
    for (k = 0; k < xmlDoc.getElementsByTagName("ID").length; k++) {
        id = xmlDoc.getElementsByTagName("ID")[k].childNodes[0].nodeValue;
        name = xmlDoc.getElementsByTagName("NOM")[k].childNodes[0].nodeValue;
        if (xmlDoc.getElementsByTagName("DESCRIPTION")[k].hasChildNodes()) {
            description = xmlDoc.getElementsByTagName("DESCRIPTION")[k].childNodes[0].nodeValue;
        } else {
            description = "";
        }
        longitude = xmlDoc.getElementsByTagName("LONGITUDE")[k].childNodes[0].nodeValue;
        latitude = xmlDoc.getElementsByTagName("LATITUDE")[k].childNodes[0].nodeValue;
        if (xmlDoc.getElementsByTagName("KML")[k].hasChildNodes()) {
            kml = xmlDoc.getElementsByTagName("KML")[k].childNodes[0].nodeValue;
        } else {
            kml = "";
        }
        if(xmlDoc.getElementsByTagName("MODALITE")[k].hasChildNodes()){
            icon = "i" + xmlDoc.getElementsByTagName("MODALITE")[k].childNodes[0].nodeValue;
            modalite = xmlDoc.getElementsByTagName("MODALITE")[k].childNodes[0].nodeValue;            
            createProduct(id, xmlDoc.getElementsByTagName("MODALITE")[k].childNodes[0].nodeValue, name, icon, longitude, latitude, description, kml);
        }else{
            modalite = xmlDoc.getElementsByTagName("ICONE")[k].childNodes[0].nodeValue;
            icon = "i" + modalite;
            createProduct(id, modalite, name, icon, longitude, latitude, description, kml);
        }
        //alert(modalite);
        //alert(id + "-" + modalite);



    }
    productSort();

    document.getElementById("LoaderDisplay").style.display = "none";
    markLockLoading = false;
    return true;
}

/* creation d'un produit de type kml ou marker */
function createProduct(id, modalite, name, icon, longitude, latitude, description, kml) {

    if (isMark(id, modalite) == -1) {
        if (kml != "") {
            var length = MarkTabInfo.length;
            MarkTabInfo[length] = id;
            MarkTabInfoModalite[length] = modalite;
            MarkTabInfoIsActive[length] = true; // pour le temps de chargement + on ne passe pas par la fonction enableMark
            MarkTabInfoType[length] = "kml";
            LabelMark(id, name, description);
            html=getLabelOne(id);
            MarkTab[length] = new EGeoXml("MarkTab[" + length + "]", map, kml, { name: name, sidebarid: "produits" });
            MarkTab[length].id = id;
            MarkTab[length].modalite = modalite;
            MarkTab[length].parse();

        } else {
            var length = MarkTabInfo.length;
            MarkTabInfo[length] = id;
            MarkTabInfoModalite[length] = modalite;
            MarkTabInfoIsActive[length] = false;
            MarkTabInfoType[length] = "marker";
            LabelMark(id, name, description);
            MarkTab[length] = createMarker(new GLatLng(latitude, longitude), name, '', id, icon, "{maxWidth:7}", length);
            createProductLine(id, modalite, name);
            enableMark(id, modalite);
        }
    } else {
        hiddeMark(id, modalite);
        enableMark(id, modalite);
    }
    return true;
}

/******************************************************************/
/*                Fonctions de gestion des markers                */
/******************************************************************/
function isMark(idProduit, modalite) {
    var i = 0;
    for (i = 0; i < MarkTabInfo.length; i++) {
        if (MarkTabInfo[i] == idProduit && MarkTabInfoModalite[i]== modalite) {
            return i;
        }
    }
    i = -1;
    return i;
}
// Masque une marque a partir de son id
function hiddeMark(idProduit, modalite) {
    var i = 0;
    for (i = 0; i < MarkTabInfo.length; i++) {
        if (MarkTabInfo[i] == idProduit && MarkTabInfoModalite[i] == modalite) {
            MarkTabInfoIsActive[i] = false;
            if (MarkTabInfoType[i] == "marker") {
                if (document.getElementById("pLine" + idProduit + "-" + modalite)) {
                    document.getElementById("pLine" + idProduit + "-" + modalite).style.display = "none";
                }
                map.removeOverlay(MarkTab[i]);
            } else {
                MarkTab[i].hide();
            }
            return true;
        }
    }
    return false;
}

// affiche une marque a partir de son id
function enableMark(idProduit, modalite) {
    var i = 0;
    for (i = 0; i < MarkTabInfo.length; i++) {
        if (MarkTabInfo[i] == idProduit && MarkTabInfoModalite[i] == modalite) {
            if (MarkTabInfoIsActive[i] == false) {
                MarkTabInfoIsActive[i] = true;
                if (MarkTabInfoType[i] == "marker") {
                    if (document.getElementById("pLine" + idProduit + "-" + modalite)) {
                        document.getElementById("pLine" + idProduit + "-" + modalite).style.display = "block";
                    }
                    map.addOverlay(MarkTab[i]);
                } else {
                    MarkTab[i].show();
                }
            }
            return true;
        }
    }
    return false;
}

// cache toutes les marks pour une modalite
function unPrintForModalite(modalite) {

    for (i = 0; i < MarkTabInfo.length; i++) {
        if (MarkTabInfoModalite[i] == modalite) {
            if (MarkTabInfoIsActive[i] == true) {
                MarkTabInfoIsActive[i] = false;
                if (MarkTabInfoType[i] == "marker") {
                    if (document.getElementById("pLine" + MarkTabInfo[i] + "-" + modalite)) {
                        document.getElementById("pLine" + MarkTabInfo[i] + "-" + MarkTabInfoModalite[i]).style.display = "none";
                    }
                    map.removeOverlay(MarkTab[i]);
                } else {
                    MarkTab[i].hide();
                }
                document.getElementById("alink"+MarkTabInfo[i]+"-"+MarkTabInfoModalite[i]).innerHTML="(+)";
            }
        }
    }
    return true;
}

////////////////////////////////////////////
/// Gestion des +/-
////////////////////////////////////////////

// restaure un état saint pour les produits
// Attention la fonction se rappel autant de fois que nécessaire pour parcourrir tous les produits
function restaurePrintMenu() {
   var print = false;var n = 0;
   for (l = 0; l < MarkTabInfo.length; l++) {
        if (document.getElementById("alink"+MarkTabInfo[l]+"-"+MarkTabInfoModalite[l]).innerHTML=="(-)") {

                    // on hidde tous les markers
                    for (i = 0; i < MarkTabInfo.length; i++) {
                        if (MarkTabInfoIsActive[i] == true) {
                            hiddeMark(MarkTabInfo[i], MarkTabInfoModalite[i]);
                        }
                    }

                    // On restaure la selection des menus
                    for (m = 0; m < MarkTabInfoModaliteBuffer.length; m++) {
                        if (document.getElementById(MarkTabInfoModaliteBuffer[m])) {
                            document.getElementById(MarkTabInfoModaliteBuffer[m]).className = "mooTree_node mooTree_selected";
                        }
                    }

                    // On réaffiche l'ancienne selection
                    for (m = 0; m < MarkTabInfoBuffer.length; m++) {
                        print=false;
                        n = MarkTabInfoBuffer[m];
                        for(c=0;c<MarkTabInfoModaliteBuffer.length; c++){
                            if(MarkTabInfoModaliteBuffer[c]==MarkTabInfoModalite[n]){
                                enableMark(MarkTabInfo[n], MarkTabInfoModalite[n]);
                                print=true;
                            }
                        }
                        if(print==false){
                            hiddeMark(MarkTabInfo[n], MarkTabInfoModalite[n]);
                        }
                    }
                    document.getElementById("alink"+MarkTabInfo[l]+"-"+MarkTabInfoModalite[l]).innerHTML="(+)";
        }
    }
}
function restaurePrint(){
    var print = false; var n = 0;
    for (l = 0; l < MarkTabInfo.length; l++) {
        if (document.getElementById("alink"+MarkTabInfo[l]+"-"+MarkTabInfoModalite[l]).innerHTML=="(-)") {

                    // On restaure la selection des menus
                    for (m = 0; m < MarkTabInfoModaliteBuffer.length; m++) {
                        if (document.getElementById(MarkTabInfoModaliteBuffer[m])) {
                            document.getElementById(MarkTabInfoModaliteBuffer[m]).className = "mooTree_node mooTree_selected";
                        }
                    }

                    // On réaffiche l'ancienne selection
                    for (m = 0; m < MarkTabInfoBuffer.length; m++) {
                        print=false;
                        n = MarkTabInfoBuffer[m];
                        for(c=0;c<MarkTabInfoModaliteBuffer.length; c++){
                            if(MarkTabInfoModaliteBuffer[c]==MarkTabInfoModalite[n]){
                                enableMark(MarkTabInfo[n], MarkTabInfoModalite[n]);
                                print=true;
                            }
                        }
                        if(print==false){
                            hiddeMark(MarkTabInfo[n], MarkTabInfoModalite[n]);
                        }
                    }
                    document.getElementById("alink"+MarkTabInfo[l]+"-"+MarkTabInfoModalite[l]).innerHTML="(+)";
        }
    }
}

// cache toutes les marks pour une modalite / ou les réaffiche
function unPrintUnlessProduct(product) {

    var proximit = true;
    for (i = 0; i < MarkTabInfo.length; i++) {
        if (MarkTabInfo[i] == product) {
            if (document.getElementById("alink"+MarkTabInfo[i]+"-"+MarkTabInfoModalite[i]).innerHTML=="(+)") {
                
                restaurePrint();

                enableMark(MarkTabInfo[i], MarkTabInfoModalite[i]);
                document.getElementById("alink"+MarkTabInfo[i]+"-"+MarkTabInfoModalite[i]).innerHTML="(-)";

                proximit = true;

                MarkTabInfoBuffer = new Array();
                MarkTabInfoModaliteBuffer = new Array();
                treeSlide.hide();
                navigationSlide.hide();
            }else{
                document.getElementById("alink"+MarkTabInfo[i]+"-"+MarkTabInfoModalite[i]).innerHTML="(+)";
                proximit = false;
                treeSlide.show();
                navigationSlide.show();
                markLockMenu = false;   // sert a empêcher l'ouverture du menu en +/-
            }
            break;
        }
    }

    // On efface tous les produits affichés sauf le produit en cours
    j = 0;
    for (i = 0; i < MarkTabInfo.length; i++) {
        if (MarkTabInfoIsActive[i] == true) {
            if (MarkTabInfo[i] != product) {
                hiddeMark(MarkTabInfo[i], MarkTabInfoModalite[i]);
            }
            if ( proximit == true){
                MarkTabInfoBuffer[j]=i; j++;
            }
        }
    }


    // Restauration / affichage des menus    
    j=0;
    if(proximit == true){

        /* On efface et on stock les menus */
        for(x in icon)
        {
            mod = x.substr(1, x.length);
            if(!isNaN(parseInt(mod))){
                if(document.getElementById(mod)){
                    if(document.getElementById(mod).className == "mooTree_node mooTree_selected"){
                        document.getElementById(mod).className = "mooTree_node";
                        MarkTabInfoModaliteBuffer[j]=mod; j++;
                        //alert(MarkTabInfoModalite[i] + "2");
                    }
                }
            }
        }
    }else{
        // On restaure la selection des menus
        for (i = 0; i < MarkTabInfoModaliteBuffer.length; i++) {
            if (document.getElementById(MarkTabInfoModalite[i])) {
                document.getElementById(MarkTabInfoModaliteBuffer[i]).className = "mooTree_node mooTree_selected";
            }
        }
    }

    // affichage des ancien marker ou chargment des nouveaux
    if(proximit == false){ 
        // On réaffiche l'ancienne selection
        for (i = 0; i < MarkTabInfoBuffer.length; i++) {
            k = MarkTabInfoBuffer[i];
            enableMark(MarkTabInfo[k], MarkTabInfoModalite[k]);
        }
    }else{
        printForAutourDe("p" + product );
    }
    
    
    return true;
}

/******************************************************************/
/*                Fonctions pour les produits / liste             */
/******************************************************************/
/* creation d'une ligne de produit dans la liste des produits */
function createProductLine(id, modalite, name) {

    var mainDiv = document.createElement('div');
    var link = document.createElement('a');
    var img = document.createElement('img');
    var txt = document.createTextNode( name );

    mainDiv.id = "pLine" + id + "-" + modalite;

    link.onclick = function() {
        productLineClick(id, modalite);
    }

    img.setAttribute('src', iconeDir + "icone_" + modalite + ".png");
    //img.width = "18px";
    //img.height = "18px";

    mainDiv.appendChild(img);
    link.appendChild(txt);
    mainDiv.appendChild(link);
    
    // On ajoute le boutton pour afficher ou non les produits approchants
    var a = document.createElement("a");
    var txt = document.createTextNode("(+)");
    a.appendChild(txt);
    a.className = "detailPlus";
    a.id = "alink"+id+"-"+modalite;
    a.setAttribute("title", "Voir les produits proches");
    // fonction d'appel des produits apporchants
    a.onclick = function() {
        eval ( 'unPrintUnlessProduct("'+ id + '")');
        //eval( 'printForAutourDe("p'+ id + '")');
    }
    mainDiv.appendChild(a);

    document.getElementById("produits").appendChild(mainDiv);
    return true;
}

// gestion d'un click depuis la liste des produits
function productLineClick(idProduit, modalite) {

    var i = 0;
    for (i = 0; i < MarkTabInfo.length; i++) {
        if (MarkTabInfo[i] == idProduit && MarkTabInfoModalite[i] == modalite) {
            //alert("ok");
            //treeSlide.open=true;
            //navigationSlide.open=true;
            isClick = true;
            // on centre la map sur le point selectionné
            map.panTo(MarkTab[i].getPoint(), map.getZoom());

            GEvent.trigger(MarkTab[i], "click");
            return true;
        }
    }
    return false;
}

// trie les produits par ordre alpha dans la liste
function productSort() {

    var min;
    var val;
    var ind;
    var i = 0;
    var j = 0;

    var contenair = document.getElementById("produits");
    for (i = (contenair.childNodes.length-1); i >=1 ; i -= 1 ) {
        min = val = null;
        ind = 0;
        for (j = i; j >= 1; j -= 1) {
            if (contenair.childNodes[j].hasChildNodes()) {
                name = contenair.childNodes[j].childNodes[1].childNodes[0].nodeValue;
            } else {
                name = "";
            }
            name = name.toLowerCase();
            if (min == null || name <= min) {
                ind = j;
                min = name;
            }
        }
        if (ind != 0) {
            var row = contenair.childNodes[ind];
            if (row) {
                contenair.removeChild(row);
                contenair.appendChild(row);
            }
        }
    }
}