var MapRoute = {};

var gdir;
var geocoder = null;
var _mPreferMetric = true;
var addressMarker;


MapRoute = function (newObjectName, newBaseResponse)  
{  
    // ------- Variables de class ---------
    this.objectName = newObjectName;
    this.baseResponse = newBaseResponse;
    this.message = null;
    this.contentHtml = "";
    this.init(newBaseResponse);
    this.map = null;
    //this.internalId = Math.floor(Math.random()*10001); // id interne
};  


MapRoute.prototype =  
{  
     init: function(baseResponseId)  
    {     
        if (e = document.getElementById(baseResponseId))
            this.baseResponse = e;
        else alert('MapRoute : init ERROR');
    },
     
    printMessage : function()
    {
         this.baseResponse.innerHTML = "<p>"+this.message+"</p>"; 
    },
     
    afficheContentHtml : function(newLat, newLng, adrDepart, adrArrivee, titre, pays) {
    	if (pays != null) {
    		versionPays = pays;
    	} else {
    		versionPays = 'fr';
    	}
    	
    	if(versionPays == 'ch'){
    		adresseExemple = 'Rue de la Croix-Rouge 4, 1204 Genève';
    	} else {
    		adresseExemple = '2 avenue de la Providence, 75013 Paris';
    	}
    	
        if (isNaN(newLat) || isNaN(newLng)) {
            alert('MapRoute : Lat or Lng ERROR');
            return;
        }
        
        if (typeof(window['jsCst_titre_itineraire']) != "undefined" ) {
            titre = jsCst_titre_itineraire;
        }
        this.contentHtml = "<form method='post' action='#' onSubmit='" + this.objectName + ".setDirections(this.from.value, this.to.value, \"fr\"); return false'>"   
                          +     '<input type="hidden" id="toAddress" name="to" value="' + adrArrivee + ' @' + newLat + ", " + newLng + '">'
                          +        "<div class='tableau_itineraire' style='width:805px;height: 520px;margin-left:10px;margin-right:10px;margin-top:5px;margin-bottom:15px'>"                          
                          // ------------- bloc haut ----------------
                          +            "<div style='clear: both;'>"
                          +                "<div style='float:left;margin-bottom:13px' class='foncia_lightbox_titre'>" + titre + "</div>"
                          +                 "<div style='float:right' class='foncia_Impression_plan_fonctions'>"
                          +                    "<a href='javascript:jQuery(\".forImprim\").jqprint( {importCSS:true, operaSupport:true, printContainer:true});'>Imprimer cet itinéraire</a>"
                          +                    "&nbsp;&nbsp;|&nbsp;&nbsp;<a onclick='jQuery.facebox.close();'>Fermer</a> <img src='"+jsCst_PATH_ICON+"contenu/icone_fermer.gif' style='margin-left:10px;border:0px' onclick='jQuery.facebox.close();'/>"
                          +                "</div>"
                          +             "</div>"
                          +            "<div style='clear: both;'>"                          
                          +                "<div style='width:322px; float:left;margin-right:10px' class='foncia_MapRoute_saisie_texte'>Lieu de départ</div>"
                          +                "<div style='width:322px; float:left;' class='foncia_MapRoute_saisie_texte'>Lieu d'arrivée</div>"
                          +                "<div class='breaker'></div>"
                          +                "<div style='float:left;' ><input type='text' id='fromAddress' name='from' value='Adresse' class='foncia_MapRoute_saisie_input' style='width:326px;margin-right:10px' onfocus=\"if(this.value=='Adresse')this.value='';\" onblur=\"if(this.value=='')this.value='Adresse';\"></div>"
                          +                "<div style='width:322px; float:left; margin-right:10px;' class='foncia_MapRoute_destination'>" + adrArrivee + "</div>"
                          +                "<div class='foncia_btn' style='float:left; margin:2px 0 0 0;'><span class='left'>&nbsp;</span><span id='btn_ok'><input type='submit' name='Submit' value=\"Calculer l'itinéraire\" style='width:110px'></span><span class='right'>&nbsp;</span></div>"
                          +            "</div>"
                          +            "<div style='clear:both;'>"                          
                          +                "<div style='margin:3px 10px 0 0' class='foncia_ex'>ex. : "+adresseExemple+"</div>"
                          +            "</div>"
                          +            "<div style='margin-top:17px; width:100%; float: left'>"                          
                          // ------------- bloc carte ----------------
                          +                "<div style='width:400px; height:400px; float: left;'>"
                          +                    "<div class='forImprim foncia_lightbox_sous_titre'>Carte</div>"
                          +                    "<div id='map_canvas_route' class='foncia_details_bloc_MAP_nous_situer_border forImprim' style='width:400px; height:400px;'></div>"
                          +                 "</div>"
                          // ------------- bloc itineraire ----------------
                          +                "<div style='width:385px; height:400px; float: left;text-align:left;padding:0px;margin-left:16px'>"
                          +                    "<div class='forImprim foncia_lightbox_sous_titre'>Itinéraire détaillé</div>"
                          +                    "<div id='directions' class='forImprim' ><span style='font-size:12px'>Veuillez saisir le lieu de départ dans la zone ci-dessus.</span></div>"
                          +                 "</div>"
                          +            "</div>"   
                          +            "<div class='breaker'></div>"                         
                          +        "</div>"
                         + "</form>";                         
                             
         this.baseResponse.innerHTML = this.contentHtml + this._getContentCss();
    },        
    
    
    setDirections : function(fromAddress, toAddress, locale) {
        document.getElementById("directions").innerHTML = '';
        gdir.load("from: " + fromAddress + " to: " + toAddress, { "locale": locale });
    },

    initialize : function(map_div, newLat, newLng, config) {
        if (GBrowserIsCompatible())
        {             
            var hasConfig = (config != null && config != "" && isObject(config)) ? true : false;
            
            var conf_addSmallMap        = ((hasConfig && config.addSmallMap != undefined)        ? config.addSmallMap : true);
            var conf_addScale            = ((hasConfig && config.addScale != undefined)              ? config.addScale : true);
            var conf_addOverview        = ((hasConfig && config.addOverview != undefined)        ? config.addOverview : true);
            var conf_addTypeControl        = ((hasConfig && config.addTypeControl != undefined)    ? config.addTypeControl : false);
            var conf_addScrollZoom        = ((hasConfig && config.addScrollZoom != undefined)        ? config.addScrollZoom : true);
            var conf_addDefaultPoint    = ((hasConfig && config.addDefaultPoint != undefined)    ? config.addDefaultPoint : false);
                        
            this.map = new GMap2(document.getElementById(map_div));
            gdir = new GDirections(this.map, document.getElementById("directions"));
            //GEvent.addListener(gdir, "load", this.onGDirectionsLoad); <!-- Charge la partie pour les distances -->
            GEvent.addListener(gdir, "error", this.handleErrors); <!-- Charge la partie pour les messages d erreurs -->
            this.map.setCenter(new GLatLng(newLat, newLng), 16, G_NORMAL_MAP); //this.map.setCenter(new GLatLng(newLat, newLng), 15);
            
            if (conf_addSmallMap)
                this.map.addControl(new GSmallMapControl());
                
            if (conf_addScale)
                this.map.addControl(new GScaleControl());
                
            if (conf_addOverview) {    
                mini = new GOverviewMapControl();
                this.map.addControl(mini);
//                mini.hide();
            }
            
            if (conf_addScrollZoom)
                this.map.enableScrollWheelZoom();
            
            if (conf_addTypeControl)
                this.map.addControl(new GMapTypeControl());
                
            if (conf_addDefaultPoint)
                this.addMarker(newLat, newLng, "", null);
        }
    },
    
    
    changeCenter : function(newLat, newLng) {
        if (GBrowserIsCompatible())
        {             
            if (this.map != null) {
                this.map.setCenter(new GLatLng(newLat, newLng), 16, G_NORMAL_MAP);
            }
        }
    },    
    
    
    addMarker : function (newLat, newLng, infoHtml, mkParams) {
        var marker;
        var mkPoint = new GLatLng(newLat, newLng);
        if (mkParams != null && isObject(mkParams)) {
            marker = new GMarker(mkPoint, mkParams);
        }        
        else {
            marker = new GMarker(mkPoint);
        }
                
        if (infoHtml != "") {
            if (isArray(infoHtml)) 
                { GEvent.addListener(marker, "click", function() { marker.openInfoWindowTabsHtml(infoHtml); }); }
            else 
                { GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml(infoHtml); }); }
        }
        //points[counter] = point;
        //markers[counter] = marker;
        //counter++;
        //return marker;
        this.map.addOverlay(marker);
        return marker;
    },
    
            
    handleErrors : function() {
        /*
        if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
            alert("Aucune location géographique correspondante n'a pu être trouvée pour l'une des adresses spécifiées. Ce qui peut être du à une adresse récente, ou incorrecte.\nError code: " + gdir.getStatus().code);
        else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
            alert("La demande d'itinéraire n'a pu être calculée avec succès, aucune raison de l'échec n'est connu.\n Error code: " + gdir.getStatus().code);
        else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
            alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
        else if (gdir.getStatus().code == G_GEO_BAD_KEY)
            alert("La clé (Key) n'est pas valide ou ne correspond pas au nom de domaine. \n Error code: " + gdir.getStatus().code);
        else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
            alert("La demande d'itinéraire n'a pu être correctement parsé.\n Error code: " + gdir.getStatus().code);
        else alert("Une erreur inconnue est survenue.");
        */
        alert("Adresse invalide.");
    },
        
        
    onGDirectionsLoad : function() {
        var reg=new RegExp("&nbsp;", "g");
        kilometrage = gdir.getDistance().html;
        document.getElementById("km").value = kilometrage.replace(reg,' ');
    }, 
    
        
    // ---------- 
    // PRIVATE FUNCTIONS
    // ----------
    
    _getContentCss : function() {
        var tempContentCss     = "<style type='text/css' media='all'>"        
                             +      " div.tableau_itineraire td { font-size: 11px;}"
                             +     " #directions { width: 400px; height: 390px; text-align: left; font-size: 0.75em; margin:2px; overflow: auto; width: auto;padding:0px;}"
                             +  "</style>"    
                             +  "<style type='text/css' media='print'>"
                             +      " #directions { width: 400px; height: 400px; text-align: left; font-size: 10px; margin: 2px; overflow: visible;}"
                             +     " #btn_ok { display: none; }"
                             +     " #b_toto { display: none; }"
                             +  "</style>";
        return tempContentCss;
    }
     
          
}; 

function isArray(a) {return isObject(a) && a.constructor == Array;};

function isObject(a) {return (a && typeof a == 'object') || isFunction(a);};

function isFunction(a) {return typeof a == 'function';};