var bCarte=false; 
var bDetails=false; 
var sCarte='';

var ZOOM_MAX = 11;
var ZOOM_MIN = 6;


var geocoder = new GClientGeocoder();
var map28_pnk0i_0;
var divLoading;
var mapTypeCourant=null; //le type de carte courant
var aGeoXML = new Array();//tableau de tous les itinéraires et autres kml qui seront affichés sur la carte
var aBoutons = new Array();//on stocke les boutons dans un tableau pour savoir lesquels sont activés ou pas
var aOverlays = new Array(); // tableau des overlays chargés dynamiquement
var bCols=false;
var aPasTrouve = new Array();
var nav; // quel navigateur est utilisé : 1 = IE, 2 = Firefox, 3 = autre
var bJQueryGlobal = false;
var oRGA;
var oVA;
var oCDS;
var oDefaut;
var couleurTheme='vert';
var ggeo_num;
var aCommunes = new Array();
var aObjets = new Array();
var aCourant = null;

/*Extension de la classe Array*/

Array.prototype.contains = function (element) 
  {
          for (var i = 0; i < this.length; i++) 
       {
              if (this[i] == element) 
          {
                      return true;
              }
          }
          return false;
}



/*objets des cartes*/
function initObjects () {
  oDefaut = {
  			nom:"Défaut",
  			kml: new Array(),
  			coord:new Array(45.508984, 6.680396,10),
  			btnActif:new Array()
  			};
}




function setCheminSite(pchem) {
  cheminSite = pchem;
}

var oIti=null;//l'objet de l'itinéraire courant




/*initialisation des icones personnalisées*/

//OT
var iconeOt = new GIcon();
    iconeOt.image= cheminSite+'png/ot.png';
    iconeOt.shadow = cheminSite+'png/map/ombre.png';
    iconeOt.iconSize = new GSize(28, 28);
    iconeOt.shadowSize = new GSize(22, 20);
    iconeOt.iconAnchor = new GPoint(27, 7);
    iconeOt.infoWindowAnchor = new GPoint(20, 20);
    
    
var iconeOtOver = new GIcon();
    iconeOtOver.image= cheminSite+'png/ot.png';
    iconeOtOver.shadow = cheminSite+'png/map/ombre.png';
    iconeOtOver.iconSize = new GSize(33, 33);
    iconeOtOver.shadowSize = new GSize(22, 20);
    iconeOtOver.iconAnchor = new GPoint(27, 7);
    iconeOtOver.infoWindowAnchor = new GPoint(20, 20);

function setPicto(nom) {
  iconeOt.image= cheminSite+'img/info_'+nom+'.png';
  couleurTheme=nom;
}


function checkNavigateur() {
  if(navigator.userAgent.indexOf("MSIE 7") != -1)
    nav=1;
    else if(navigator.userAgent.indexOf("MSIE 6") != -1)
    nav=1;
    else if(navigator.userAgent.indexOf("Firefox/2") != -1)
    nav=2;
    else if(navigator.userAgent.indexOf("Firefox") != -1)
    nav=2;
    else if(navigator.userAgent.indexOf("Netscape/7") != -1)
    nav=2;
    else if(navigator.userAgent.indexOf("Netscape") != -1)
    nav=2;
    else if(navigator.userAgent.indexOf("Opera/9") != -1)
    nav=3;
    else if(navigator.userAgent.indexOf("Opera") != -1)
    nav=3;
  else
  nav=3; 
}

function initMap(bJQuery) {
  initObjects();
  checkNavigateur();
	bJQueryGlobal = bJQuery;
	$("#lienKML").slideUp("fast");
	//$("#panelCarte").slideUp("fast");
	$("#detailsObjet").slideUp("fast");
	$("#contenuBtnPanelCarte").slideUp("fast");
//	$("#liste_aptv").css("display","none");
	
	sCarte="Défaut";
	oIti = oDefaut;
	/*
	if(nav==2) { 
    oIti.coord[0] = oIti.coord[0];
    oIti.coord[1] = oIti.coord[1] + 1;
  }
	*/
   if (GBrowserIsCompatible()) {
    loading(true);
		var bSuite = false;
		bSuite = true;
		if(bSuite == true) {
  		var point=null;
  		var zoomCourant = null;
  		if(bJQuery==true) {
  			point = map28_pnk0i_0.getCenter();
  			zoomCourant = map28_pnk0i_0.getZoom();
  		}
  
   map28_pnk0i_0 = new GMap2(document.getElementById('map_aptv'));
   GEvent.addListener(map28_pnk0i_0,"load",onMapLoaded);
  map28_pnk0i_0.clearOverlays();
  aGeoXML = new Array();
  
					
	for(var i=0;i<oIti.kml.length;i++) {
	 var trompeCache = new Date();
    var ggeo =new GGeoXml(cheminBase+oIti.kml[i]+"?"+trompeCache.getMilliseconds());
		aGeoXML.push(ggeo);
	}

	
	map28_pnk0i_0.getContainer().style.overflow='hidden';
	
	point =(point==null)	?	new GLatLng( oIti.coord[0], oIti.coord[1])	:	point;
	map28_pnk0i_0.addControl(new GLargeMapControl());

 			var centerpoint = point;
	zoomCourant=(zoomCourant!=null)	?	zoomCourant	:	oIti.coord[2];
      map28_pnk0i_0.setCenter(centerpoint, zoomCourant);     
	
	if(mapTypeCourant == null) {
		map28_pnk0i_0.setMapType(G_PHYSICAL_MAP);
		mapTypeCourant = G_PHYSICAL_MAP;
	}else {
		map28_pnk0i_0.setMapType(mapTypeCourant);
	}

    	for(var j=0;j<aGeoXML.length;j++) {
    		map28_pnk0i_0.addOverlay(aGeoXML[j]);
    		aOverlays.push({obj:aGeoXML[j],iti:true});
    	}	  
  		  
			}	
			
			
      }

}


function onMapLoaded() {
  	if(!bJQueryGlobal) {
			 //on initialise JQuery
			 bSuite = initJQuery();
		  }else {
		    bSuite = true;
		  }
  loading(false);
	

}

function onKmlLoaded() {
}


function switchMap(val) {
	switch(val) {
		case 1 : 	mapTypeCourant = G_PHYSICAL_MAP;map28_pnk0i_0.setMapType(G_PHYSICAL_MAP);break;
		case 2 :	mapTypeCourant = G_SATELLITE_3D_MAP;map28_pnk0i_0.setMapType(G_SATELLITE_3D_MAP);break;
		default:	mapTypeCourant = G_PHYSICAL_MAP;map28_pnk0i_0.setMapType(G_PHYSICAL_MAP);break;
	}
}

function loading(bDisplay) {
	divLoading = document.getElementById("loading");
	if(bDisplay) {
		divLoading.style.display='block';
	}else {
		divLoading.style.display='none';
	}
}


function openKml(num) {
  if(!$("#bouton_"+num).hasClass("boutonKmlActif")) {
  loading(true);
  map28_pnk0i_0.clearOverlays();
  	  	
      var geoXml = new GGeoXml("http://www.savoie-tarentaise.com/php/sitra/trace_tarentaise.kml");
	  	map28_pnk0i_0.addOverlay(geoXml);
  activeBouton(num);
  }
  

  
}


function setBoutons(aSelection) {
  aBoutons = aSelection;
  
  for(var i=0; i<aBoutons.length;i++) {
  //on définit le hover sur les boutons
    $("#bouton_"+aBoutons[i]).hover(function(){
    //mouseover
    if(!$(this).hasClass("boutonKmlActif")) {
      
      $(this).addClass("boutonKmlHover",1000);
    }
    },function(){
    //mouseout
    $(this).removeClass("boutonKmlHover",1000);
    });
  }
  
  
}


function hoverBtn(num,bMouseOut) {
  if(!$("#bouton_"+num).hasClass("boutonKmlActif")) {
    if(bMouseOut==false) {
      $("#bouton_"+num).removeClass("boutonKmlHover",1000);
    }else {
      $("#bouton_"+num).addClass("boutonKmlHover",1000);
    }
  }
}

function activeBouton(num) {
  for(var i = 0;i<aBoutons.length;i++) {
    if(num!=aBoutons[i]) {
      $("#bouton_"+aBoutons[i]).removeClass("boutonKmlActif");
    }else {
      //si le bouton n'était pas activé, on l'active et on loade les données
      if(!$("#bouton_"+aBoutons[i]).hasClass("boutonKmlActif")) {
        
        $("#bouton_"+aBoutons[i]).addClass("boutonKmlActif",1000);
        $("#contenuBtnPanelCarte").slideDown("fast");
        $("#lienKML").slideDown("fast");
        var selCommunes = document.getElementById('selectCommune');
        if(selCommunes.length>0) {
          selCommunes.options[selCommunes.selectedIndex].selected = false;
          selCommunes.options[0].selected = true;
          selCommunes.selectedIndex = 0;
          //alert(selCommunes.selectedIndex);
        }
        afficheTexteLienKml(num);
        loadFichier(num);
      } else {
      //sinon on referme le tout
      $("#bouton_"+aBoutons[i]).removeClass("boutonKmlActif",1000);
      $("#contenuBtnPanelCarte").slideUp("fast");
      $("#lienKML").slideUp("fast");
      loading(false);
      
      }
    }
  }  
  
  
  
}

function afficheTexteLienKml (num) {

  $.ajax({
	   type: "GET",
	   url: cheminSite+"php/correspondances_numeros.php",
	   data: "action_num="+num,
	   dataType:"text",
	   success: function(obj){
     	// $("#lienKML").html("Télécharger <br /><strong>"+obj+"</strong><br />pour Google Earth");
			$("#lienKML").attr("href",cheminBase+"sitra/"+num+".kml");
			
	   },
	   complete:function (XMLHttpRequest, textStatus) {

		}
	 });
  
}

function loadFichier(num) {
  //on va chercher le fichier de la sélec, et une fois qu'il est chargé il appelle la fonction afficheDonnees
   $.ajax({
	   type: "GET",
	   url: cheminBase+"sitra/"+num+".php",
	   data: "carte="+oIti.nom,
	   dataType:"script",
	   success: function(obj){
			//aMarkers = obj;
			
	   },
	   complete:function (XMLHttpRequest, textStatus) {
    	loading(false);
		}
	 });

}

function afficheDonnees(aData) {
    /*
    Forme des objets JS : 
    {
      id
      nom
      desc
      lat
      lon
      commune
      cp
    }
  */
  aObjets = aData;
  aCommunes = new Array();    
    for(var i=0;i<aData.length;i++) {
      var obj = aData[i];
      
      showLatLng(obj.lon,obj.lat,obj.desc,obj.id,obj.nom);
      aCommunes.push({cp:obj.cp,commune:obj.commune});
    }
    


    
    
    trieCommunes();
    
    
    if($("#choixListe").hasClass("minChoixActif")) {
      afficherListe(aObjets);
      $("#lienKML").slideUp("fast");
    }

}

function afficheDonneesTriees(aData) {
    //map28_pnk0i_0.clearOverlays();
    geoXml = new GGeoXml("http://www.savoie-tarentaise.com/php/sitra/trace_tarentaise.kml");
	  	map28_pnk0i_0.addOverlay(geoXml);
    for(var i=0;i<aData.length;i++) {
      var obj = aData[i];    
      showLatLng(obj.lon,obj.lat,obj.desc,obj.id,obj.nom);
    }
    
    aCourant = aData;
    afficherListe(aData);
    if($("#choixListe").hasClass("minChoixActif")) {
     
      $("#lienKML").slideUp("fast");
    }
}


function trieCommunes() {
  var aTemp = new Array();
  var aCp = new Array();
  var i=0;
  for(i=0;i<aCommunes.length;i++) {
    if(!aTemp.contains(aCommunes[i].commune)) {
      aTemp.push(aCommunes[i].commune);
      aCp.push(aCommunes[i].cp);
    }
    /*
    for(var j=0;j<aTemp.length;j++) {
      if(aCommunes[i].commune != aTemp[j].commune)
    }
    */
  }
  
  aCommunes = new Array();
  var sel = document.getElementById('selectCommune');
  sel.options.length=0;
  sel.options[0] = new Option("Choisir un lieu...", "-999", true, true);
  aTemp.sort();
  for(i=0;i<aTemp.length;i++) {
    aCommunes.push({cp:aCp[i],commune:aTemp[i]});
    addSelect(sel,aCp[i],aTemp[i]);
  }
  
  
  sel.onchange = selectionCommune;
  /*if(sel.options[0].selected  ==  true)  {
    //sel.options[0].selected = true;
    //$(sel).trigger("change");
    afficheDonnees(aObjets);
    //afficherListe(aObjets);
  }
  */
  //selectionCommune();
  
}

function addSelect(selectElemObj,cp,ville) {
  selectElemObj.options[selectElemObj.options.length] = new Option(ville, cp, false, false)  ;
}


function selectionCommune() {

  var sel = document.getElementById('selectCommune');
  var valSel = sel.options[sel.selectedIndex].value;
  var labelSel = sel.options[sel.selectedIndex].text;

  if(valSel!='-999') {
    centerAddress(valSel+" "+labelSel);
    afficheObjetsTrieCommune(labelSel);
    
  } else {
    aCourant = null;
    afficheDonnees(aObjets);

   var  point =new GLatLng( oIti.coord[0], oIti.coord[1]);
   map28_pnk0i_0.setCenter(point,oIti.coord[2]);
  }
}

function afficheObjetsTrieCommune(commune) {
  var aTemp = new Array();
  var i=0;
  for(i=0;i<aObjets.length;i++) {
    //alert(commune.toUpperCase()+" vs. "+aObjets[i].commune.toUpperCase());
    if(aObjets[i].commune.toUpperCase() == commune.toUpperCase()) {
    
      aTemp.push(aObjets[i]);
    }
  }
  afficheDonneesTriees(aTemp);
  
}

function afficherProfil() {
  bCarte=false;
  
  //$("#btnCacherPanelCarte").html(":: CLIQUEZ SUR UN ONGLET POUR AFFICHER LES INFORMATIONS ::");
  
   /*$("#btnCacherPanelCarte").click(function () {
        if (bCarte==false) {
          
          $("#panelCarte").slideDown("fast",function () {
            bCarte=true;
          });
          $("#btnCacherPanelCarte").html(":: CLIQUEZ SUR UN ONGLET POUR AFFICHER LES INFORMATIONS ::");
          
        } else {
          $("#panelCarte").slideUp("fast",function () {
            bCarte=false;
            $("#btnCacherPanelCarte").html(":: AFFICHER LE MENU ::");
          });          
        }
  });*/
   
   $("#choixListe").hover(function (){
      if(!$(this).hasClass("minChoixActif")) {
        $(this).addClass("minChoixHover");
      }
      },function(){
      $(this).removeClass("minChoixHover");
  });
  
  $("#choixCarte").hover(function (){
      if(!$(this).hasClass("minChoixActif")) {
        $(this).addClass("minChoixHover");
      }
      },function(){
      $(this).removeClass("minChoixHover");
  });
   
   $("#choixListe").click(function (){
   $(this).removeClass("minChoixHover");
    if(!$("#choixListe").hasClass("minChoixActif")) {
        $("#choixListe").addClass("minChoixActif");
          var selCommunes = document.getElementById('selectCommune');
          selCommunes.options[selCommunes.selectedIndex].selected = false;
          selCommunes.options[0].selected = true;
          selCommunes.selectedIndex = 0;
        afficherListe(aObjets);
        $("#lienKML").slideUp("fast");
        $("#map_aptv").css("display","none");
        $("#liste_aptv").css("display","block");
        $("#choixCarte").removeClass("minChoixActif");
      } else {
      //sinon on referme le tout
      //$("#choixListe").removeClass("minChoixActif");
      
      
      }
   });
   $("#choixCarte").click(function (){
   $(this).removeClass("minChoixHover");
      if(!$("#choixCarte").hasClass("minChoixActif")) {
        $("#choixCarte").addClass("minChoixActif");
        $("#choixListe").removeClass("minChoixActif");
        $("#contenu_liste_aptv").html("Liste des Objets");
        $("#map_aptv").css("display","block");
        $("#lienKML").slideDown("fast");
        $("#liste_aptv").css("display","none");
      } else {
      //sinon on referme le tout
      //$("#choixCarte").removeClass("minChoixActif");
      
      }
   });
   
   $("#btnCacherPanelDetails").click(function () {
        $("#btnCacherPanelCarte").addClass("barrePanel");
        //$("#containerMenuPanel").slideDown();
          $("#detailsObjet").slideUp();      
   
   });
  
  return true;
}

function initJQuery() {
  var retour=false;
  retour = afficherProfil();  
 
  return retour;
  
}

function afficherListe(data) {
  //aData=(aCourant == null)?data:aCourant;
  aData=data;
  var contenu = ""; 
  var classe="";
  if(aData.length>0) {
  for(var i=0;i<aData.length;i++) {
    var obj = aData[i];
    classe=(classe=="")?"fondGris":"";
    contenu = contenu + "<span class='detailObjetListe' onclick='javascript:afficherDetailObjet(\""+obj.id+"\");'><img src='"+cheminSite+"img/details.png' title='Voir le détail'/></span><span class='carteObjetListe' onclick='javascript:afficherCarteCentrerObjet(\""+obj.id+"\");'><img src='"+cheminSite+"img/centrer_carte.png' title='Voir sur la carte'/></span><div class='objetListe "+classe+"' onclick='javascript:afficherDetailObjet(\""+obj.id+"\");'><p style='width:420px;'><strong>"+obj.nom+"</strong>, "+obj.commune+"</p></div>";
  }
  } else {
    contenu = contenu + "<div class='objetListe "+classe+"' ><p style='width:420px;'><strong>Aucune donnée</strong></p></div>";
  }
  
  
  $("#contenu_liste_aptv").html(contenu);
  $("span.objetListe").hover(function(){
    $(this).addClass("objetListeHover",1000);
  },function(){
    $(this).removeClass("objetListeHover",1000);
  });
   $("span.fondGris").hover(function(){
    $(this).css("backgroundColor","#e9ff87");

  },function(){
    $(this).css("backgroundColor","#eee");
  });
}

function supprOverlays()  {
  var aTemp = new Array();
  var i;
  for(i=0;i<aOverlays.length;i++) {
      if(aOverlays[i].iti) {
        aTemp.push(aOverlays[i]);
      }
  }
  
  for(i=0;i<aOverlays.length;i++) {
      if(!aOverlays[i].iti) {
        map28_pnk0i_0.removeOverlay(aOverlays[i]);
      }else {
      }
  }
  aOverlays = aTemp;
  
}

function afficherDetailObjet(id) {
  loading(true);
   $.ajax({
      	   type: "GET",
      	   url: cheminBase+"sitra/details_objet/details_objet.php",
      	   data: "objet="+id+"&couleur="+couleurTheme,
      	   dataType:"text/html",
      	   success: function(obj){
      			 $("#contenuDetailsObjet").html(obj);
      			 //$("#containerMenuPanel").slideUp();
      			 $("#detailsObjet").slideDown();
        	   },
        	   complete:function (XMLHttpRequest, textStatus) {
  
            loading(false);    	
      		}
      	 });
      	 
}


function afficherCarteCentrerObjet(id) {

  for(var i=0;i<aObjets.length;i++) {
    var obj = aObjets[i];
    if(obj.id == id) {
      $("#choixCarte").trigger("click");
      //centerAddress(obj.cp+" "+obj.commune);
      centerPoint(obj.id,obj.lat,obj.lon);
    }
  }
}
/*fonctions utilitaires*/

function htmlEnt(char,urlencodechars)
{
  var chars = new Array ('&','à','á','â','ã','ä','å','æ','ç','è','é',
                         'ê','ë','ì','í','î','ï','ð','ñ','ò','ó','ô',
                         'õ','ö','ø','ù','ú','û','ü','ý','þ','ÿ','À',
                         'Á','Â','Ã','Ä','Å','Æ','Ç','È','É','Ê','Ë',
                         'Ì','Í','Î','Ï','Ð','Ñ','Ò','Ó','Ô','Õ','Ö',
                         'Ø','Ù','Ú','Û','Ü','Ý','Þ','€','\"','ß','<',
                         '>','¢','£','¤','¥','¦','§','¨','©','ª','«',
                         '¬','­','®','¯','°','‘','²','³','´','µ','¶',
                         '·','¸','¹','º','»','¼','½','¾');
 
  var entities = new Array ('&','a','a','a','a','a','a','ae','c','e','e',
                         'e','e','i','i','i','i','o','n','o','o','o',
                         'o','o','o','u','u','u','u','u','þ','y','a',
                         'A','A','A','A','A','AE','C','E','E','E','E',
                         'I','I','I','I','D','N','O','O','O','O','O',
                         'O','U','U','U','U','Y','','euro','','','<',
                         '>','','','','','','','','','','',
                         '','','','','','','','','','','',
                         '','','','','','','','');
  
  var urlEncode = new Array ('&amp;','&agrave;','&acute;','&acirc;','&atilde;','&auml;','&aring;','&aelig;','&ccedil;','&egrave;','&eacute;',
                         '&ecirc;','&euml;','&igrave;','&iacute;','&icirc;','&iuml;','&ordm;','&ntilde;','&ograve;','&oacute;','&ocirc;',
                         '&otilde;','&ouml;','&oslash;','&ugrave;','&uacute;','&ucirc;','&uuml;','&yacute;','&THORN;','&yuml;','&Agrave;',
                         '&acute;','&Acirc;','&Atilde;','&Auml;','&Aring;','&AElig;','&Ccedil;','&Egrave;','&Eacute;','&Ecirc;','&Euml;',
                         '&Igrave;','&Iacute;','&Icirc;','&Iuml;','&ETH;','&Ntilde;','&Ograve;','&Oacute;','&Ocirc;','&Otilde;','&Ouml;',
                         '&Oslash;','&Ugrave;','&Uacute;','&Ucirc;','&Uuml;','&Yacute;','&thorn;','&euro;','\"','&Beta;','<',
                         '>','','','','','','','','','','',
                         '','','','','','','','','','','',
                         '','','','','','','','');
 
  newString = char;
  for (var i = 0; i < chars.length; i++)
  {
    myRegExp = new RegExp();
    myRegExp.compile(chars[i],'g')
	if(!urlencodechars) {
    	newString = newString.replace (myRegExp, '' + entities[i] + '');
	}else {
		newString = newString.replace (myRegExp, '' + urlEncode[i] + '');
	}
  }
  return newString;
}

		
function showLatLng(lon,lat,nom,id,titre) {
  				var obj={icon:iconeOt};
  				
  				// var objover={icon:iconeOtOver};
  				
  				var point = new GLatLng(lat,lon);
  				
  				var marker = new GMarker(point,obj);
  				map28_pnk0i_0.addOverlay(marker);
  				aOverlays.push(marker);
          
  				
  				GEvent.addListener(marker, "click", function() {    

  					titre = (!titre)  ? nom : titre;               
            
            
            afficherDetailObjet(id);
              
              //marker.openInfoWindowHtml("<b>" + nom + "</b>");  						//alert("on va initialiser thickbox");
  						
              //marker.openInfoWindowHtml("<b>" + nom + "</b><br /><span id='lien"+id+"' class='spanLien' onclick='openTb(\"lien"+id+"\",\""+cheminBase+"sitra/details_objet/details_objet.php?width=700"+String.fromCharCode(38)+"height=400"+String.fromCharCode(38)+"objet="+id+""+String.fromCharCode(38)+"\",\""+htmlEnt(titre)+"\");'>Plus d'infos</span>");  						//alert("on va initialiser thickbox");

  				});
  				
  				GEvent.addListener(marker, "mouseover", function() {
          marker.setImage(cheminSite+'img/info_defaut.png');
          marker.openInfoWindowHtml("<div class='infowindow_gmap'><h4>" + nom + "</h4><a style='display:block;float:right;' href='#' onclick=\"afficherDetailObjet('" +id+  "')\">+ d'infos</a></div>");
  				});
  				
  				GEvent.addListener(marker, "mouseout", function() {

  				marker.setImage(iconeOt.image);
  				});
  				

	}
	
	
function centerAddress(address) {
	  address = address + ", France";
   geocoder.getLatLng(
		address,
		function(point) {
		  if (!point) {

		  } else {
				map28_pnk0i_0.setCenter(point,11);
		  }
		}
	  );
	}
function centerPoint(id,lat,lon) {
  var point = new GLatLng(lat,lon);
	map28_pnk0i_0.setCenter(point,13);	
	
}

function openTb(elt,url,title) {
  var htmlelt = document.getElementById(elt); 
	var t = title
	var a = url
	var g = false;
	tb_show(t,a,g);
	$("#"+elt).blur();
	return false;
}


function pausecomp(millis)
{
  var date = new Date();
  var curDate = null;
  
  do { curDate = new Date(); }
  while(curDate-date < millis);
}
  
