﻿var hstAdressesRecherche = new Hashtable();
var hstAdressesSelection = new Hashtable();
var currentPageRechercheResultats = 1;
var currentPath;
var currentAdresseCount=0;
var mustResetAddress=true;
var zoomItineraireON = false;
var situerOnce = false;

function initPlanificateur()
{
    loadAdressesFromCookie();
    getLocalisations();
    initLangue();

    if (gup('situer') == '1') {
        $('AucunResultatRecherche').setStyle({
            display: 'none'
        });

        var cookieContent = readCookie('atrdsituer');
        var membreInfo = eval(cookieContent);
        loadAdresse(membreInfo[2], membreInfo[1], membreInfo[3], membreInfo[4], 'ListeAdressesRecherche');
    }
}

function gup(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return results[1];
}

function resetAddress()
{
    if (mustResetAddress == true)
    {
        mustResetAddress = false;
        $('txtAdresse').value = '';
        $('txtAdresse').setStyle({
            color: '#000000',
            fontStyle: 'normal'
        });
    }
}

function initLangue() {
    if (gup('l') == 'en') {
        $('btnSearchPromoteurs').value = recherche.RechercherEN;
        $('btnResetMap').value = recherche.ReiniitialiserEN;
        $('btnPrintDirections').value = recherche.ImprimerEN;
        $('AucunResultatRecherche').update(recherche.AucunResultatEN);
        $('RechercheEnCours').update(recherche.RechercheEnCoursEN);
        $('btnLoadAdresse').value = recherche.AjouterAdresseEN;
        $('btnPrintRetour').value = recherche.RetourRechercheEN;
        $('RetourSiteDuplessis').update(recherche.RetourDuplessisEN);
        $('SendItineraire').update(recherche.SendItineraireEN);

        $('lblFrom').update(recherche.FromMailEN);
        $('lblTo').update(recherche.ToMailEN);
        $('lblSubject').update(recherche.SubjectEN);
        $('lblMessage').update(recherche.MessageEN);
        $('btnSendDirectionsMail').value = recherche.SendEN;

        $('pageNext').update(recherche.ResultatsSuivantsEN);
        $('pageBack').update(recherche.ResultatsPrecedentsEN);

        $('txtAdresse').value = recherche.AdresseDepartEN;

        $('itineraireCourantTitre').update(recherche.ItineraireEN);

        var listeOption = new Element('option');
        listeOption.value = '';
        listeOption.update(recherche.SelectionnezCategorieEN);
        $('selectCategorie').insert(listeOption);

        var listeOption = new Element('option');
        listeOption.value = '';
        listeOption.update(recherche.SelectionnezMunicipaliteEN);
        $('selectLocalisation').insert(listeOption);
    }
    else {
        $('btnSearchPromoteurs').value = recherche.Rechercher;
        $('btnResetMap').value = recherche.Reiniitialiser;
        $('btnPrintDirections').value = recherche.Imprimer;
        $('AucunResultatRecherche').update(recherche.AucunResultat);
        $('RechercheEnCours').update(recherche.RechercheEnCours);
        $('btnLoadAdresse').value = recherche.AjouterAdresse;
        $('btnPrintRetour').value = recherche.RetourRecherche;
        $('RetourSiteDuplessis').update(recherche.RetourDuplessis);
        $('SendItineraire').update(recherche.SendItineraire);

        $('lblFrom').update(recherche.FromMail);
        $('lblTo').update(recherche.ToMail);
        $('lblSubject').update(recherche.Subject);
        $('lblMessage').update(recherche.Message);
        $('btnSendDirectionsMail').value = recherche.Send;

        $('pageNext').update(recherche.ResultatsSuivants);
        $('pageBack').update(recherche.ResultatsPrecedents);

        $('txtAdresse').value = recherche.AdresseDepart;

        $('itineraireCourantTitre').update(recherche.Itineraire);

        var listeOption = new Element('option');
        listeOption.value = '';
        listeOption.update(recherche.SelectionnezCategorie);
        $('selectCategorie').insert(listeOption);

        var listeOption = new Element('option');
        listeOption.value = '';
        listeOption.update(recherche.SelectionnezMunicipalite);
        $('selectLocalisation').insert(listeOption);
    }

    ATRD.atrdservice.getCategories(1, getCategoriesOnReceive, getCategoriesOnError);
}

function getCategoriesOnReceive(result)
{
    var myResultsArray = eval(result);
    var j = myResultsArray.length-1;
    
    for (var i=0; i <= j; i++)
    {
        addCategorie(myResultsArray[i]);
    }
}

function addCategorie(listeData)
{
    var listeOption = new Element('option');
    listeOption.value = listeData[0];
    listeOption.update(listeData[1]);
    $('selectCategorie').insert(listeOption);
}

function getMunicipalitesOnReceive(result)
{
    var myResultsArray = eval(result);
    var j = myResultsArray.length-1;
    
    for (var i=0; i <= j; i++)
    {
        addMunicipalite(myResultsArray[i]);
    }
}

function addMunicipalite(listeData)
{
    var listeOption = new Element('option');
    listeOption.value = listeData[0];
    listeOption.update(listeData[1]);
    $('selectLocalisation').insert(listeOption);
}

function getCategoriesOnError()
{
    alert('Erreur de communication avec le serveur');
}

function getMunicipalitesOnError()
{
    alert('Erreur de communication avec le serveur');
}

function getLocalisations()
{
    ATRD.atrdservice.getMunicipalites(getMunicipalitesOnReceive, searchPromoteursOnError);
}

function searchPromoteurs()
{
    $('AucunResultatRecherche').setStyle({
        display: 'none'
    });

    $('RechercheEnCours').setStyle({
        display: 'block'
    });

    ATRD.atrdservice.searchPromoteurs($('selectCategorie').value, '', $('selectLocalisation').value, currentPageRechercheResultats, searchPromoteursOnReceive, searchPromoteursOnError)
}

function loadAdressesFromCookie()
{
    var cookieContent = readCookie('atrdplanificateur');
    var cookieAdresses;

    if (cookieContent)
    {
        cookieContent = '[' + cookieContent + ']';
        cookieAdresses = eval(cookieContent);
        
        var j = cookieAdresses.length-1;
        var currentPromoteur;
        
        for (var i=0; i <= j; i++)
        {
            currentPromoteur = cookieAdresses[i];
            
            if (hstAdressesSelection.containsKey(currentPromoteur[0]) == false)
            {
                addAdresse(currentPromoteur[0],currentPromoteur[1],currentPromoteur[2],currentPromoteur[3],currentPromoteur[4],'ListeAdressesSelection');
            }
        }
    }
}

function writeAdressesToCookie()
{
    var cookieContent = '';

    var currentSelection = Sortable.sequence('ListeAdressesSelection');
    var currentAdresse;

    for(var i=0; i<currentSelection.length; i++)
    {
        currentAdresse = hstAdressesSelection.get(currentSelection[i]);

        if (cookieContent == '')
        {
            cookieContent = '["' + currentAdresse.adresseid + '","' + currentAdresse.nom + '","' + currentAdresse.adresse + '","' + currentAdresse.GoogleMapLatLng.lat() + '","' + currentAdresse.GoogleMapLatLng.lng() + '"]';
        }
        else
        {
            cookieContent = cookieContent + ',["' + currentAdresse.adresseid + '","' + currentAdresse.nom + '","' + currentAdresse.adresse + '","' + currentAdresse.GoogleMapLatLng.lat() + '","' + currentAdresse.GoogleMapLatLng.lng() + '"]';
        }
    }

    createCookie('atrdplanificateur',cookieContent,1);
}

function searchPromoteursOnReceive(result)
{
    var myResultsArray = eval(result);
    var myResultsParameters = myResultsArray[0];
    var myResultsPromoteurs = myResultsArray[1];
    var currentPromoteur;
    var j = myResultsPromoteurs.length-1;
    
    clearSearchAdresse();

    $('RechercheEnCours').setStyle({
        display: 'none'
    });
    
    if (j == 0)
    {
        $('AucunResultatRecherche').setStyle({
            display: 'block'
        });
    }
    else
    {
        $('AucunResultatRecherche').setStyle({
            display: 'none'
        });
    }
    
    if (myResultsParameters[0] == 1)
    {
        $('pageBack').setStyle({
            display: 'block'
        });
    }
    else
    {
        $('pageBack').setStyle({
            display: 'none'
        });
    }

    if (myResultsParameters[1] == 1)
    {
        $('pageNext').setStyle({
            display: 'block'
        });
    }
    else
    {
        $('pageNext').setStyle({
            display: 'none'
        });
    }
    
    for (var i=0; i <= j; i++)
    {
        currentPromoteur = myResultsPromoteurs[i];
        
        if (hstAdressesSelection.containsKey(currentPromoteur[0]) == false)
        {
            addAdresse(currentPromoteur[0],currentPromoteur[1],currentPromoteur[2],currentPromoteur[3],currentPromoteur[4],'ListeAdressesRecherche');
        }
    }
    
    $('selectCategorie').selectedIndex = 0;
    $('selectLocalisation').selectedIndex = 0;
}

function addRemoveAdresse(adresseid, removeMustDelete)
{
    if (hstAdressesSelection.containsKey(adresseid) == false)
    {
        hstAdressesSelection.put(adresseid, hstAdressesRecherche.get(adresseid));
        hstAdressesRecherche.remove(adresseid);
        
        hstAdressesSelection.get(adresseid).addSelection();
        $('ListeAdressesSelection').insert(hstAdressesSelection.get(adresseid).adresseDIV);
    }
    else
    {       
        if (removeMustDelete == false)
        {
            hstAdressesRecherche.put(adresseid, hstAdressesSelection.get(adresseid));
            $('ListeAdressesRecherche').insert(hstAdressesRecherche.get(adresseid).adresseDIV);
        }
        else
        {
            hstAdressesSelection.get(adresseid).adresseDIV.remove();
        }

        hstAdressesSelection.get(adresseid).removeSelection();
        hstAdressesSelection.remove(adresseid);
    }

    createSortableList();
    loadPath();
    writeAdressesToCookie();
}

function searchPromoteursOnError()
{
}

function clearSearchAdresse()
{
    hstAdressesRecherche.clear();
    while ( $('ListeAdressesRecherche').childNodes.length >= 1 )
    {
        $('ListeAdressesRecherche').removeChild( $('ListeAdressesRecherche').firstChild );       
    }
}

function resetPlanificateur()
{
    eraseCookie('atrdplanificateur');

    $('AucunResultatRecherche').setStyle({
        display: 'block'
    });

    $('pageBack').setStyle({
        display: 'none'
    });

    $('pageNext').setStyle({
        display: 'none'
    });
    
    $('RechercheEnCours').setStyle({
        display: 'none'
    });

    currentAdresseCount=0;
    hstAdressesRecherche.clear();
    hstAdressesSelection.clear();

    map.clearOverlays();

    while ($('map_directions').childNodes.length >= 1) {
        $('map_directions').removeChild($('map_directions').firstChild);
    }

    while ( $('ListeAdressesRecherche').childNodes.length >= 1 )
    {
        $('ListeAdressesRecherche').removeChild( $('ListeAdressesRecherche').firstChild );       
    }

    while ( $('ListeAdressesSelection').childNodes.length >= 1 )
    {
        $('ListeAdressesSelection').removeChild( $('ListeAdressesSelection').firstChild );       
    }
}

function loadPath()
{
    var currentSelection = Sortable.sequence('ListeAdressesSelection');
    
    var currentCoordinates = new Array();

    for(var i=0; i<currentSelection.length; i++)
    {
        currentCoordinates[i] = hstAdressesSelection.get(currentSelection[i]).GoogleMapLatLng;
    }

    if (i < 25)
    {
        if (currentPath)
        {
            currentPath.clear();
        }

        currentPath = new GDirections(map, $('map_directions'));

        GEvent.addListener(currentPath, "addoverlay", function () {
            //alert(currentPath);
            var i;
            var completeBodyMail = '';

            for (i = 0; i < currentPath.F.Directions.Routes[0].Steps.length; i++) {
            completeBodyMail = completeBodyMail + '<p>' + String(i + 1) + '- ' + currentPath.F.Directions.Routes[0].Steps[i].descriptionHtml + ' - ' + currentPath.F.Directions.Routes[0].Steps[i].Distance.html + '</p>';
            }

            $('txtDirectionsMail').value = completeBodyMail;
            $('inlineSendDirectionsMailContent').update(completeBodyMail);
        });

        /*
        currentPath.B.Directions.Routes[0].Steps[i].Distance.html
        currentPath.B.Directions.Routes[0].Steps[i].Duration.html
        currentPath.B.Directions.Routes[0].Steps[i].descriptionHtml
        */
        
        // Static map
        //GEvent.addListener(currentPath, "addoverlay", onGDirectionsLoad);

        if (gup('l') == 'en') {
            currentPath.loadFromWaypoints(currentCoordinates, { 'locale': 'en_US' });
        }
        else {
            currentPath.loadFromWaypoints(currentCoordinates, { 'locale': 'fr_CA' });
        }
        
    }
    else
    {
        alert('Vous pouvez sélectionner un maximum de 25 points sur la carte');
    }
}

function loadAdresse(tempAdresse, tempNom, myLatitude, myLongitude, tempContainer) {
    var checkAdresse;
    var checkNom;
    var checkContainer;

    if (tempAdresse == undefined) {
        checkAdresse = $('txtAdresse').value;
    }
    else {
        checkAdresse = tempAdresse;
    }

    if (tempNom == undefined) {
        checkNom = $('txtAdresse').value;
    }
    else {
        checkNom = tempNom;
    }

    if (tempContainer == undefined) {
        checkContainer = 'ListeAdressesSelection';
    }
    else {
        checkContainer = tempContainer;
    }

    checkAdresse = checkAdresse.replace(/%20/gi, ' ');
    checkNom = checkNom.replace(/%20/gi, ' ');

    if (hstAdressesSelection.containsKey(checkAdresse) == false) {
        currentAdresseCount = currentAdresseCount + 1;
        var adresseID = 'adresse' + currentAdresseCount;

        addAdresse($('txtAdresse').value, checkNom, checkAdresse, myLatitude, myLongitude, checkContainer);
    }
    else {
        alert('Cette adresse fait déjà partie des adresses sélectionnées.');
    }
}

function createSortableList()
{
    Sortable.create('ListeAdressesSelection', { tag: 'li', handle: 'handle', onUpdate: function()
            {
                loadPath();
            } 
        }
    );
}

function addAdresse(adresseID, nom, adresse, myLatitude, myLongitude, myContainer)
{
    var myCoordinates;
    
    if (myLatitude == '')
    {
        var geocoder = new GClientGeocoder();
        geocoder.getLatLng(adresse,
            function(point)
            {
//                if (!point)
//                {
//                    alert(adresse + " est introuvable");
//                }
//                else
//                {
//                    createAdresse(adresseID, nom, adresse, point, myContainer)
//                }
                if (point)
                {
                    createAdresse(adresseID, nom, adresse, point, myContainer)
                }
            }
        );
    }
    else
    {
        myCoordinates = new GLatLng(myLatitude, myLongitude)
        createAdresse(adresseID, nom, adresse, myCoordinates, myContainer)
    }
}

function gup(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return results[1];
}

function createAdresse(adresseID, nom, myadresse, myCoordinates, myContainer)
{
    if (myContainer == 'ListeAdressesSelection')
    {
        hstAdressesSelection.put(adresseID, new adresse(adresseID,nom,myadresse,myCoordinates,myContainer, true));
        hstAdressesSelection.get(adresseID).addSelection();

        createSortableList();
        loadPath();
        writeAdressesToCookie();
    }
    else
    {
        hstAdressesRecherche.put(adresseID, new adresse(adresseID,nom,myadresse,myCoordinates, myContainer, false));

        var currentMapMarker = createMarker(myCoordinates, nom + '<br/>' + myadresse, nom + '<br/>' + myadresse);
        map.addOverlay(currentMapMarker);

        if ((gup('situer') == '1') && (situerOnce == false)) {
            situerOnce = true
            map.setCenter(myCoordinates, 4);
        }

        currentMapMarker.setImage('images/yellow_Marker.png');
    }
}

function zoomItineraire()
{
    if (zoomItineraireON == false)
    {
        zoomItineraireON = true;
        
        $('RechercheAdressesFrame').setStyle({
            display: 'none'
        });
        $('btnPrintDirections').setStyle({
            display: 'none'
        });
        $('printMapDirections').setStyle({
            display: 'block',
            position: 'absolute',
            top: '602px',
            left: '0px',
            width: '99%',
            zIndex: 1000,
            backgroundColor: '#ffffff'
        });
        $('printMapDirections').update($('map_directions').innerHTML);
        
        $('MapFrame').setStyle({
            width: '99%',
            height: '600px'
        });
        $('map').setStyle({
            width: '99%',
            height: '600px'
        });
        $('map_directions_border').setStyle({
            display: 'none',
            width: '99%'
        });
        $('map_directions').setStyle({
            display: 'none',
            width: '95%'
        });            
    }
    else
    {
        zoomItineraireON = false;
        
        $('RechercheAdressesFrame').setStyle({
            display: 'block'
        });
        $('btnPrintDirections').setStyle({
            display: 'block'
        });
        
        $('printMapDirections').setStyle({
            display: 'none'
        });
        
        $('btnPrintRetour').setStyle({
            display: 'none'
        });
        
        $('MapFrame').setStyle({
            position: 'absolute',
            height: '511px'
        });
        $('map').setStyle({
            width: '500px',
            height: '370px'
        });
        $('map_directions_border').setStyle({
            display: 'block',
            width: '500px',
            height: '109px'
        });
        $('map_directions').setStyle({
            display: 'block',
            width: '490px',
            height: '99px'
        });

        $('printMapDirections').update('');        
    }

    map = new GMap2(document.getElementById("map"));
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    map.setCenter(new GLatLng(49.325122, -71.630859), 5);
    
    loadPath();
}

function printDirections()
{
    $('RechercheAdressesFrame').setStyle({
        display: 'none'
    });
    $('btnPrintDirections').setStyle({
        display: 'none'
    });
    $('btnPrintRetour').setStyle({
        display: 'block'
    });
    $('printMapDirections').setStyle({
        display: 'block',
        position: 'absolute',
        top: '372px',
        left: '0px',
        width: '602px',
        zIndex: 1000,
        backgroundColor: '#ffffff'
    });
    $('printMapDirections').update($('map_directions').innerHTML);
    
    $('MapFrame').setStyle({
        height: '400px'
    });
    $('map').setStyle({
        width: '600px'
    });
    $('map_directions_border').setStyle({
        display: 'none',
        width: '600px'
    });
    $('map_directions').setStyle({
        display: 'none',
        width: '590px'
    });
    
    window.print();
}

function retourRecherche()
{
    $('RechercheAdressesFrame').setStyle({
        display: 'block'
    });
    $('btnPrintDirections').setStyle({
        display: 'block'
    });
    
    $('printMapDirections').setStyle({
        display: 'none'
    });
    
    $('btnPrintRetour').setStyle({
        display: 'none'
    });
    
    $('MapFrame').setStyle({
        position: 'absolute',
        height: '511px'
    });
    $('map').setStyle({
        width: '500px'
    });
    $('map_directions_border').setStyle({
        display: 'block',
        width: '500px',
        height: '109px'
    });
    $('map_directions').setStyle({
        display: 'block',
        width: '490px',
        height: '99px'
    });

    $('printMapDirections').update('');
}
