// JavaScript Document
var points = []; 
var markers = []; 
var counter = 0; 
var sidebar_html = ""; 
var marker_html = []; 
var map = null; 
var nbsites = 0
var nbresults=0;
var exml;
var controlZoom;
function onLoad() { if (GBrowserIsCompatible()) { 
var mapObj = document.getElementById("map"); 
if (mapObj != "undefined" && mapObj != null) { map = new GMap2(document.getElementById("map"));
        /* first set of options is for the visual overlay.*/
        var boxStyleOpts = {
          opacity: .2,
          border: "2px solid #4DA1A3"
        }

        /* second set of options is for everything else */
        var otherOpts = {
          buttonHTML: "<img src='/themes/tooristic/images/searchInteractive.jpg' />",
          buttonZoomingHTML: "<img src='/themes/tooristic/images/searchInteractive.jpg' />",
          buttonStartingStyle: {width: '48px', height: '48px'}
        };

        /* third set of options specifies callbacks */
        var callbacks = {
          buttonclick: function(){GLog.write("Looks like you activated DragZoom!")},
          dragstart: function(){GLog.write("Started to Drag . . .")},
          dragging: function(x1,y1,x2,y2){GLog.write("Dragging, currently x="+x2+",y="+y2)},
          dragend: function(nw,ne,se,sw,nwpx,nepx,sepx,swpx){GLog.write("Zoom! NE="+ne+";SW="+sw)}
        };
  		controlZoom=new DragZoomControl(boxStyleOpts, otherOpts, {});
         map.addControl(controlZoom,
                new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(32,40)));


map.enableScrollWheelZoom();
map.enableScrollWheelZoom();

GEvent.addListener(map, "dragend", function() {
  var bl=map.getBounds().getSouthWest();var tr=map.getBounds().getNorthEast();map_minx=bl.lat();map_miny=bl.lng();map_maxx=tr.lat();map_maxy=tr.lng();
changeCoord(map_minx, map_maxx, map_miny, map_maxy);
  if(map.getZoom()>8)
  {
  	  document.getElementById('sidebar_map').innerHTML="";
	  deleteAllMarker();
	  listeCategorie=getCategories();
	  getLink(map_minx, map_maxx, map_miny, map_maxy, listeCategorie);
	}
	else
	{
	  deleteAllMarker();
	}
}
	
);

GEvent.addListener(map, "zoomend", function() {
  var bl=map.getBounds().getSouthWest();var tr=map.getBounds().getNorthEast();map_minx=bl.lat();map_miny=bl.lng();map_maxx=tr.lat();map_maxy=tr.lng();
  var zoomEnCours=map.getZoom();
  //document.getElementById('divZoom').innerHTML="Zoom en cours : "+zoomEnCours;
  document.getElementById('level').innerHTML=zoomEnCours;
msgResultNotActive="<i>Résultats inactifs - Zoom insuffisant ( Minimum 9 )</i>";
msgResultActive="<i>Résultats actifs</i> ";	
changeCoord(map_minx, map_maxx, map_miny, map_maxy);
  if(zoomEnCours>8)
  {
  	  document.getElementById('sidebar_map').innerHTML="";
	  deleteAllMarker();
	  listeCategorie=getCategories();
	  getLink(map_minx, map_maxx, map_miny, map_maxy, listeCategorie);
	}
	else
	{
	//document.getElementById('divZoom').innerHTML+=msgResultNotActive;
	showMessage(msgResultNotActive);
	document.getElementById('moveResults1').innerHTML="Résultats";
	deleteAllMarker();
	}
	
}
);

 var adsManager = new GAdsManager(map, "ca-pub-8850220189803030");adsManager.enable(); map.setCenter(new GLatLng(46.227638, 2.213749), 5, G_NORMAL_MAP); map.addControl(new GScaleControl()); 
document.getElementById("sidebar_map").innerHTML = "<ul class=\"gmapSidebar\">"+ sidebar_html +"<\/ul>"; } } else { alert("Sorry, the Google Maps API is not compatible with this browser."); } } 


function createMarker(point, title, html, n, tooltip) {
if(n >= 0) { n = -1; }
var marker = new GMarker(point,{'title': tooltip});
if(isArray(html)) { GEvent.addListener(marker, "click", function() { marker.openInfoWindowTabsHtml(html); }); }
else { GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml(html); }); }
points[counter] = point;
markers[counter] = marker;
marker_html[counter] = html;
sidebar_html += '<li class="gmapSidebarItem" id="gmapSidebarItem_'+ counter +'"><a href="javascript:click_sidebar(' + counter + ')">' + title + '<\/a><\/li>';
counter++;
return marker;
}
var geoCallback = function()
{
while(GGeoXml.hasLoaded()!=true)
{
}
alert('pret');
/*geoXml.show()
geoXml.gotoDefaultViewport(map);*/
}
function getCategories()
{
	 // Attention on va prendre en compte les catégories sélectionnées
	 tailleTableau=document.categ.elements["tabCheckbox[]"].length;
	 liste="0";
	for(i=0;i<tailleTableau;i++)
	{
		if (document.categ.elements["tabCheckbox[]"][i].checked==true)
		{
			liste+="-"+document.categ.elements["tabCheckbox[]"][i].value;
		}
	}
	return liste;
}
function getLink(latmin, latmax, lngmin, lngmax,listeCategorie)
{
			document.getElementById('light2').style.display='block';
	changePanoramio('panoramio2');
	  nbresults=0;
	  // === create the base icon ===
     exml = new EGeoXml("exml", map, "/placemark.php?latmin="+latmin+"&latmax="+latmax+"&lngmin="+lngmin+"&lngmax="+lngmax+"&categ="+listeCategorie,{sidebarid:"sidebar_map",sortbyname:true,iwwidth:380,iwheight:350,directions:false,sidebarfn:side,nozoom:true});
     exml.parse();
	 if ( !exml.gmarkers.length)
	 {
								
	 }
}

function side(myvar,name,type,i,graphic) {
      if (type == "marker") {
		  	if(nbsites%2==0){classe="pair";}
			else{classe="impair";}
			nbresults=nbresults+1;
			if(exml.gmarkers[i])
			{
				    // Switch icon on marker mouseover and mouseout
					GEvent.addListener(exml.gmarkers[i], "mouseover", function() {
					  exml.gmarkers[i].setImage("/themes/tooristic/images/markerOver.png");
					  document.getElementById('liste-'+i+'').className='listeOver';
					});
					
					GEvent.addListener(exml.gmarkers[i], "mouseout", function() {
					  exml.gmarkers[i].setImage("/themes/tooristic/images/marker.png");
					  document.getElementById('liste-'+i+'').className='';
					});

					  eval(myvar+'.gmarkers['+i+'].setImage(\'/themes/tooristic/images/marker.png\');');nbsites++;
				return '<div id="liste-'+i+'"><a onmouseout="'
				  + myvar+ '.gmarkers['+i+'].setImage(\'/themes/tooristic/images/marker.png\');" onmouseover="'
				  + myvar+ '.gmarkers['+i+'].setImage(\'/themes/tooristic/images/markerOver.png\');" href="javascript:GEvent.trigger('
				  + myvar+ '.gmarkers['+i+'],\'click\')" class='+classe+'>' + name.replace("tOOristic.net : ","") + '</a></div>';
			}
		  
      }
	  //document.getElementById('zoom').innerHTML=i+" Résultats";
      return "";
    }
function deleteAllMarker()
{
	if(exml)
	{
	var tab=exml.gmarkers;
	for( var i=0;i < exml.gmarkers.length ; i++)
	{
	map.removeOverlay(exml.gmarkers[i]);
	}
	}
	removePanoramioPicture();
	nbsites=0;
	document.getElementById('sidebar_map').innerHTML="";
}
function actualiser()
{var bl=map.getBounds().getSouthWest();var tr=map.getBounds().getNorthEast();map_minx=bl.lat();map_miny=bl.lng();map_maxx=tr.lat();map_maxy=tr.lng();
  if(map.getZoom()>8)
  {
  	  document.getElementById('sidebar_map').innerHTML="";
	  deleteAllMarker();
	  listeCategorie=getCategories();
	  getLink(map_minx, map_maxx, map_miny, map_maxy, listeCategorie);
	}
}
function changeCoord(map_minx, map_maxx, map_miny, map_maxy)
{
document.getElementById('divPosition').innerHTML = "<b>Coordonnées</b> <br>coin haut-gauche (lat:"+map_minx+" - lon:"+map_miny+" )<br> coin bas-droite (lat:"+parseFloat(map_maxx)+" - lon:"+parseFloat(map_maxy)+" )";
}
function showMessage(msg)
{
		document.getElementById("divInfo").style.display="";
		document.getElementById('divLoad').innerHTML=msg;
		setTimeout('document.getElementById("divInfo").style.display="none"',4000);
}

function changeClass(idObject,classObject)
{
	divChosen=document.getElementById(idObject);
	if(divChosen.lang=="open")
	{
	   divChosen.className=classObject;
	   divChosen.lang="close";
	}
	 else{
	 	divChosen.className="";
		divChosen.lang="open";
	 }
}

function interactiveAddPanoramioPicturesOnMap(panoramio)
{
panoramioPhotos=panoramio.photos;
addPanoramioPicturesOnMap();
}

function removePanoramioPicture()
{
	if(panoramioPhotos)
	{
		for(var i=0;i<panoramioPhotos.length;i++)
		{
			map.removeOverlay(tabMarkerPhoto[i]);
		}
	}
}

function gestionPanoramio(idObject)
{
	maDiv=document.getElementById(idObject);
		if (document.getElementById(idObject).lang=="0")
		{
			document.getElementById(idObject).lang="1";
		}else{
			document.getElementById(idObject).lang="0";
		}
	
	if (document.getElementById(idObject).lang=="0")
	{
		if(map.getZoom()>8)
		{
			getPanoramioPictures('interactiveAddPanoramioPicturesOnMap','40');
			maDiv.className="photosOk";}
		
	}else
	{
		removePanoramioPicture();
		maDiv.className="photos";
	}
}
function changePanoramio(idObject)
{
	maDiv=document.getElementById(idObject);
	if (maDiv.lang=="0")
	{
		if(map.getZoom()>8)
		{
			getPanoramioPictures('interactiveAddPanoramioPicturesOnMap','40');
			maDiv.className="photosOk";
		
		}
		
	}else
	{
		maDiv.className="photos";
		removePanoramioPicture();
	}
}

  function showAddress(address)
  {
	   geocoder = new GClientGeocoder();
       if (geocoder) 
	   {
          geocoder.getLatLng(address,
          function(point) 
		  {
            if (!point) 
			{
              alert(address + " non trouvée");
			  
			 // document.getElementById("lat").value=""
			 // document.getElementById("lng").value=""
			  return false
            } else 
			{
			  //document.getElementById("lat").value = point.lat().toFixed(5);
		     // document.getElementById("lng").value = point.lng().toFixed(5);
			 document.getElementById('light').style.display='none';document.getElementById('fade').style.display='none'
			  map.clearOverlays()
			  map.setCenter(point, 14);
   			   var marker = new GMarker(point, {draggable: true});  
			  
				 map.addOverlay(marker);
            }
          });
      }
    }
	function changeChecked(idCategorie)
	{
	if(document.getElementById(idCategorie).checked==true)
	document.getElementById(idCategorie).checked=false;
	else
	document.getElementById(idCategorie).checked=true;
	}
