var map;
var geocoder;
var center =  new GLatLng(48.84494888284024, -67.53321647644043);
var geoXml; 
var toggleState = 0;
var inizoom=15;
var Kaleidossarray=new Array();
var defautMap=null;
var defaultPoint=null;
var out=null;
var nocache=randomNumber();
var DivArray= new Array("bandeau","bandeauflash","boutonsbandeau", "pied","oursins","menubas","categories");
var printmode=false;
var heightPage;
    function loadMap() {
      if (GBrowserIsCompatible()) {
       // geocoder = new GClientGeocoder();
        map = new GMap2(document.getElementById('map'));
        map.addControl(new GSmallMapControl());
       map.addControl(new GMapTypeControl());
		//map.enableScrollWheelZoom(); 
        map.setCenter(center, inizoom);
		//map.setMapType(G_HYBRID_MAP);
		if (defautMap) trouverlesattraits();
		var out=setTimeout('kmlLoading(false)', 600);
	setTimeout('document.getElementById("champ_Attraits").disabled=false', 600);
    setTimeout('document.getElementById("champ_Hebergement").disabled=false', 600);
    setTimeout('document.getElementById("champ_Restauration").disabled=false', 600);
    setTimeout('document.getElementById("champ_Services").disabled=false', 600);
		
      }
    }

   function searchLocations() {
     var address = document.getElementById('addressInput').value;
     geocoder.getLatLng(address, function(latlng) {
       if (!latlng) {
         alert(address + ' not found');
       } else {
         searchLocationsNear(latlng);
       }
     });
   }

   function searchLocationsNear(center) {
     var radius = document.getElementById('radiusSelect').value;
     var searchUrl = 'phpsqlsearch_genxml.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;
     GDownloadUrl(searchUrl, function(data) {
       var xml = GXml.parse(data);
       var markers = xml.documentElement.getElementsByTagName('marker');
       map.clearOverlays();

       var sidebar = document.getElementById('sidebar');
       sidebar.innerHTML = '';
       if (markers.length == 0) {
         sidebar.innerHTML = 'Aucun résultat.';
         map.setCenter(center, inizoom);
         return;
       }

       var bounds = new GLatLngBounds();
       for (var i = 0; i < markers.length; i++) {
         var name = markers[i].getAttribute('name');
         var address = markers[i].getAttribute('address');
         var distance = parseFloat(markers[i].getAttribute('distance'));
         var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')),
                                 parseFloat(markers[i].getAttribute('lng')));
         
         var marker = createMarker(point, name, address);
         map.addOverlay(marker);
         var sidebarEntry = createSidebarEntry(marker, name, address, distance);
         sidebar.appendChild(sidebarEntry);
         bounds.extend(point);
       }
       map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
     });
   }
   
   function trouverlesattraits(myNum) {
	//clearTimeout();
	kmlLoading(true);
	clearTimeout(out);
	var out=setTimeout('kmlLoading(false)', 500);
   	var numeroKaleidos=myNum;
	map.closeExtInfoWindow();
	map.clearOverlays();
	var sidebar = document.getElementById('sidebar');
	var numeroCat="";//document.getElementById("markerCat").value;
	if (document.getElementById("champ_Attraits").checked) numeroCat=document.getElementById("champ_Attraits").value+",";
    if (document.getElementById("champ_Hebergement").checked) numeroCat+=document.getElementById("champ_Hebergement").value+",";
    if (document.getElementById("champ_Restauration").checked) numeroCat+=document.getElementById("champ_Restauration").value+",";
    if (document.getElementById("champ_Services").checked) numeroCat+=document.getElementById("champ_Services").value+",";
   
	if (numeroCat!=""){
	MM_showHideLayers('points','','show');
     var searchUrl = 'carte/xmlPoints.php?categorie=' + numeroCat;
	 //alert(searchUrl);
     GDownloadUrl(searchUrl, function(data) {
       var xml = GXml.parse(data);
       var markers = xml.documentElement.getElementsByTagName('marker');
       sidebar.innerHTML = '';
       if (markers.length == 0) {
         sidebar.innerHTML = 'Aucun résultat';
		 clearTimeout(out);
		 var out=setTimeout('kmlLoading(false)', 500);
         return;
       }

       var bounds = new GLatLngBounds();
       for (var i = 0; i < markers.length; i++) {
		 clearTimeout(out);
		  var out=setTimeout('kmlLoading(false)', 500);
         var name = markers[i].getAttribute('name');
         var address = markers[i].getAttribute('address');
		 var icone = markers[i].getAttribute('icone');
		 var idMarker = markers[i].getAttribute('numero');
		 var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')),
                                 parseFloat(markers[i].getAttribute('lng')));
         
        // var marker = createMarker(point, name, address,icone, idMarker);
		var tmpName=name;
		if (printmode){
			var marker = createMarker(point, i+1);
		 	map.addOverlay(marker);
			tmpName= "("+(i+1).toString()+") " + name; 
		 } else{
		 var marker = createMarkerKaleidos(point, name, address,icone, idMarker,i);
         map.addOverlay(marker);
		 
		 if (defautMap==idMarker) defaultPoint=marker;
		 }
		 
         var sidebarEntry = createSidebarEntry(marker, tmpName, address,icone);
		 //getExtInfoWindow
         sidebar.appendChild(sidebarEntry);
         bounds.extend(point);
		
       }
	   //if (defautMap) GEvent.trigger(defautMap, 'click');
     });
	}else{
	
		map.clearOverlays();
		sidebar.innerHTML ="";
		MM_showHideLayers('points','','hide');
	}
	//chargementOut=setTimeout("kmlLoading(false)", 500);

   }
   
 function createMarker(point, index) { 

        var baseIcon = new GIcon(); 
		baseIcon.image = 'images/Upload/pictos/categories/print.png';//'http://gmaps-samples.googlecode.com/svn/trunk/markers/circular/greencirclemarker.png';
        baseIcon.iconSize = new GSize(30, 30);
        baseIcon.iconAnchor = new GPoint(15, 15);
        baseIcon.infoWindowAnchor = new GPoint(25, 7);
        opts = { 
          "icon": baseIcon,
          "clickable": false,
		  "labelClass":'markerNumber',
          "labelText": index.toString(),
		  "labelOffset": new GSize(-5, -10)
        };
        var marker = new LabeledMarker(point, opts); 
        return marker; 
 } 



function createMarkerKaleidos(point, name, address, icone, idMarker,numero) {

	if (icone!=""){
	var monicon = new GIcon();
	monicon.iconSize = new GSize(20, 20);
    monicon.image = icone;
	monicon.iconAnchor = new GPoint(0, 0);
    monicon.infoWindowAnchor = new GPoint(7, 0);
	 markerOptions = { icon:monicon };
	  var marker = new GMarker(point,markerOptions);
	}else{
	 var monicon = new GIcon();//G_DEFAULT_ICON
	 monicon.iconSize = new GSize(20, 20);
      monicon.iconAnchor = new GPoint(0, 0);
      monicon.infoWindowAnchor = new GPoint(7, 0);
      var marker = new GMarker(point, monicon);
	}

		  GEvent.addListener(marker, 'click', function(){ 
				if (checkCurrentState(idMarker+"tab1_content")) {
				//show(document.getElementById(idMarker+"tab1_content"));
				//hide(document.getElementById(idMarker+"tab0_content"));
				//hide(document.getElementById(idMarker+"tab2_content"));
				nexshow(idMarker);
				//map.getExtInfoWindow().resize();
				}else{
				//kmlLoading(true);
				marker.openExtInfoWindow(map,"custom_info_window_tourisme","<div class=\"title\">"+name+"</div>",{beakOffset: 2, ajaxUrl: idMarker}); 
				map.getExtInfoWindow().resize();
				//marker.openExtInfoWindow(map,"custom_info_window_tourisme","<div class=\"title\">"+name+"</div>",{beakOffset: 2, ajaxUrl: 'marker/'+idMarker+"/?rn="+nocache}); 	
				//chargementOut=setTimeout("kmlLoading(false)", 500);
				}
			}
          );
		 GEvent.addListener(marker, 'mouseover',function(){
			if (!checkCurrentState(idMarker+"tab1_content")) {
             marker.openExtInfoWindow(map,"custom_info_window_tourisme","<div class=\"title\">Chargement... "+name+"</div>",{beakOffset: 2, ajaxUrl: idMarker} );//
			map.getExtInfoWindow().resize();
			}
				
			}
          );
		 /*
          GEvent.addDomListener(map, 'extinfowindowupdate',function(){
			kmlLoading(true);														
            var windowContent = document.getElementById("custom_info_window_tourisme_contents");
            var tabs = new Array(document.getElementById("tab0"),document.getElementById("tab1"),document.getElementById("tab2"));
            if( tabs.length > 0 ){
              var tabContentsArray = new Array(tabs.length);
              for( i=0; i < tabs.length; i++){
                tabContentsArray[i] = document.getElementById("tab"+i+"_content");
                if( i > 0) hide(tabContentsArray[i]);
                tabs[i].setAttribute("name", i.toString());  
                GEvent.addDomListener(tabs[i],"click",function(){
				//kmlLoading(true);
                  var tabIndex = this.getAttribute("name");
                  for(tabContentIndex=0; tabContentIndex < tabs.length; tabContentIndex++){
                    if( tabContentIndex == tabIndex ){
					//	alert("a");
                      show(tabContentsArray[tabContentIndex]);
                    }else{
						//alert(tabContentIndex+" - "+tabs.length);
                      hide(tabContentsArray[tabContentIndex]);
                    }
                  }
                  map.getExtInfoWindow().resize();
				  chargementOut=setTimeout("kmlLoading(false)", 600);
                });
				var closetab2=document.getElementById("close3");
				GEvent.addDomListener(closetab2,"click",function(){
					//kmlLoading(true);
					hide(tabContentsArray[1]);
					hide(tabContentsArray[2]);
					show(tabContentsArray[0]);
                  	map.getExtInfoWindow().resize();
					//chargementOut=setTimeout("kmlLoading(false)", 600);
                });
              }
            }
			chargementOut=setTimeout("kmlLoading(false)", 500);
          });
		  */
		  return marker;
        }
		
	function ftab1(num){
	hide(document.getElementById(num+"tab0_content"));
	hide(document.getElementById(num+"tab2_content"));
	show(document.getElementById(num+"tab1_content"));
    map.getExtInfoWindow().resize();		
	}
   	function ftab2(num){
	hide(document.getElementById(num+"tab0_content"));
	hide(document.getElementById(num+"tab1_content"));
	show(document.getElementById(num+"tab2_content"));
    map.getExtInfoWindow().resize();		
	}
	function ftab0(num){
	hide(document.getElementById(num+"tab1_content"));
	hide(document.getElementById(num+"tab2_content"));
	show(document.getElementById(num+"tab0_content"));
    map.getExtInfoWindow().resize();
	}
      /**
       * Helper function to hide the given DOM element
       * @param {Object} element The DOM element that should be hidden
       */
      function hide(element){
        element.style.display = "none";
        element.style.position = "absolute";
      }
      /**
       * Helper function to show the given DOM element
       * @param {Object} element The DOM element that should be displayed
       */
      function show(element){
        element.style.display = "block";
        element.style.position = "relative";
      }
	  function nexshow(idMarker){
		  var a=document.getElementById(idMarker+"tab0_content");
		  var b=document.getElementById(idMarker+"tab1_content");
		  var c=document.getElementById(idMarker+"tab2_content");
		if (a.style.display != "none"){
		show(b);
		hide(a);
		if (c) hide(c); 
		}else if (b.style.display != "none"){
		hide(a);
		hide(b);
		if (c) {
			show(c);
			var imgWindow = c.getElementsByTagName('div');
			//alert(imgWindow.length);
			for (i=0; i<imgWindow.length; i++) {
			//imgWindow[i].style.display = "block";
			//myImage = new Image() ;
			//myImage.src = imgWindow[i].src;
			//alert(imgWindow[i].src
			}
		}else{
			show(a);
		}
		}else if (c.style.display != "none"){
			show(a);
			hide(b);
			if (c) hide(c); 
		}
		map.getExtInfoWindow().resize();
		 
	  }
	//********************
    function createSidebarEntry(marker, name, address, icone) {
      var div = document.createElement('div');
		// image stuff
		var myImage=document.createElement("img");
		myImage.setAttribute('src', icone);
		myImage.setAttribute('alt', name);
		myImage.setAttribute('height', '20px');
		myImage.setAttribute('width', '20px');
		div.appendChild(myImage);
      var html=div.innerHTML+' <b>' + name + '</b><br/>' + address;
	  //var html=document.createTextNode(name);
	  
	  div.innerHTML = html;
	  //div.appendChild(html);
	  div.className='siteRow';
      div.style.cursor = 'pointer';
      div.style.marginBottom = '5px'; 
	  
      GEvent.addDomListener(div, 'click', function() {
        GEvent.trigger(marker, 'click');
      });
    
	GEvent.addDomListener(div, 'mouseover', function() {
		div.className='siteRowOver';
      });
      GEvent.addDomListener(div, 'mouseout', function() {
      div.className='siteRow';
	  });

      return div;
    }

	
	
function randomNumber(limit){
  tmp=Math.floor(Math.random()*limit);
return tmp.toString();
}


function kmlLoading(etape) {
  this.thediv = document.getElementById('loading');
  this.WaitBarDiv = document.getElementById('WaitBarDiv');
  etat=this.thediv.style.visibility;
  if (etat!="visible" && etape==true){ 
  MM_showHideLayers('loading','','show');
  }else if(etape==false){
  MM_showHideLayers('loading','','hide');
  gotoKaleidos();
  }
 //gotoKaleidos();
}
function gotoKaleidos(){
	
	if (defaultPoint){
		//alert(defaultPoint);
		GEvent.trigger(defaultPoint, 'click');
		defaultPoint=null;
	}
}
function checkCurrentState(searchName){
var windowContent = document.getElementById("custom_info_window_tourisme_contents");
if (!windowContent) return false;
var tempDiv = windowContent.getElementsByTagName('DIV');
		for (i=0; i<tempDiv.length; i++) {
		if (tempDiv[i].getAttribute("id") == searchName) return true;
		}
return false;
}


function printMap(){
if (printmode){
	UnprintMap();
	return;
}
printmode=true;
heightPage=document.getElementById("page").offsetHeight;
trouverlesattraits();
for (i=0; i<DivArray.length; i++) {
	var tempDiv = document.getElementById(DivArray[i]);	
	tempDiv.style.display = "none";
}


var MapContent = document.getElementById("corps");
MapContent.style.width='880px';
MapContent.style.position='absolute';
MapContent.style.top = 10 + 'px';
MapContent.className='resetStyle';

var MapFrame = document.getElementById("map");
MapFrame.style.height='600px';
MapFrame.style.width='880px';
MapFrame.className='resetStyle';

var BarFrame = document.getElementById("sidebar");
BarFrame.style.height="auto";//(IFheight-10)+'px';
BarFrame.style.width='880px';

var pageDiv=document.getElementById("page");
pageDiv.style.height=(740+BarFrame.offsetHeight)+"px";
//setTimeout("window.print()", 2000);
document.getElementById('categoriesPrint').style.display = "block";
}

function UnprintMap(){
printmode=false;
trouverlesattraits();
for (i=0; i<DivArray.length; i++) {
	var tempDiv = document.getElementById(DivArray[i]);	
	tempDiv.style.display = "block";
}
document.getElementById('categoriesPrint').style.display = "none";
var MapContent = document.getElementById("corps");
MapContent.style.position='relative';

var MapFrame = document.getElementById("map");
MapFrame.style.height='525px';
MapFrame.style.width='665px';
MapFrame.className='cmap';

var BarFrame = document.getElementById("sidebar");
BarFrame.className='csidebar';
BarFrame.style.height='525px';
BarFrame.style.width='200px';

var pageDiv=document.getElementById("page");
pageDiv.style.height=heightPage+"px";
}