var delay 		= 10;
var isIntro     = true;
var isKeepZoom  = false;
var isControls  = true;
var isBalloon   = true;
var currentMapType = null;
var geocoder 	= new GClientGeocoder();
var listMarkers = new Array();
var lastIdCountry = "";
var listPhotos  = new Array();
var valuesOptions = new Array();
/*var reasons=[];
reasons[G_GEO_SUCCESS]            = "Success";
reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
reasons[403]                      = "Error 403: Probably an incorrect error caused by a bug in the handling of invalid JSON.";
*/
//***********************************************************************************
function showGoogleMap(isDraggable, listInfo, map){
	var ind = 0;
	var address = "";
	var bounds = new GLatLngBounds();

    // Add markers to the map at locations

    if ((!isIntro) && (listInfo.length > 0)){
       	map.setCenter(new GLatLng(listInfo[0].latitude,listInfo[0].longitude), currentZoom);
        for (var i = 0; i < listInfo.length; i++) {
          if (listInfo[i].address != ""){//With geocoder
    		  ind = i;         
    		  address = listInfo[i].address;
          	  reachAddress(address);
          } else {//With coordonates
			  var marker = manageMarker(new GLatLng(listInfo[i].latitude,listInfo[i].longitude), i,listInfo.length);
              //alert(map.getCenter().toUrlValue()); 
              var point = new GLatLng(listInfo[i].latitude,listInfo[i].longitude);
              bounds.extend(point);
                
          }
        }
        if (listInfo.length > 1){
        	map.setZoom(map.getBoundsZoomLevel(bounds));
        	map.setCenter(bounds.getCenter());
        	map.closeInfoWindow();
        } else if (isBalloon) {
        	map.openInfoWindow(map.getCenter(),listInfo[0].info);
        }
    } else { //Intro
         map.setCenter(new GLatLng(5.0,0.0), 2);
	     isIntro = false;
	     if (dragMarker == null){
		     dragMarker = createMenuMarker(dragMarker,new GLatLng(-10.0,0.0));
		     //dragMarker.setImage("/images/backmenu1.jpg");
		     map.addOverlay(dragMarker);
	     }
	     dragMarker.openInfoWindowHtml("<div class='balloonIntro'>"+welcomeMsg+"</div>");
    }
       
	//Select the map
    if (currentMapType == null){
       	map.setMapType(G_PHYSICAL_MAP);
       	currentMapType = G_PHYSICAL_MAP;
    } else {
       	map.setMapType(currentMapType);
    }
	
	GEvent.addListener(map, "maptypechanged", function() {  
		currentMapType = map.getCurrentMapType();
	});
	
	GEvent.addDomListener(map.getContainer(), "DOMMouseScroll", wheelevent);
	map.getContainer().onmousewheel = wheelevent; 

	//Create Markers fix 
	////////////////////////////////
     function createMarker(point, index,max,marker) {
       var type = listInfo[index].type;
       var baseIcon = new GIcon();
	   var makerIcon = null;
       if (listInfo[index].type == "photo") {
		   baseIcon.iconSize = new GSize(43, 38);
		   baseIcon.shadowSize = new GSize(43, 38);
		   baseIcon.iconAnchor = new GPoint(9, 9);
		   baseIcon.infoWindowAnchor = new GPoint(9, 0);
	       makerIcon = new GIcon(baseIcon);
	       makerIcon.image = listInfo[index].styleUrl;
       } else {
	       if (listInfo[index].type == "country") {
		       baseIcon.iconSize = new GSize(25, 16);
	       	   baseIcon.iconAnchor = new GPoint(10, 10);
		   } else if (listInfo[index].type == "wiki") {
		       baseIcon.iconSize = new GSize(25, 25);
	       	   baseIcon.iconAnchor = new GPoint(10, 10);
		   } else {
		       baseIcon.iconSize = new GSize(30, 34);
	       	   baseIcon.iconAnchor = new GPoint(9, 34);
		   }
		       
	       baseIcon.shadowSize = new GSize(45, 34);
	       baseIcon.infoWindowAnchor = new GPoint(9, 2);
	       baseIcon.infoShadowAnchor = new GPoint(18, 25);
	       baseIcon.shadow = listInfo[index].styleUrl+".shadow.png";
	
	       makerIcon = new GIcon(baseIcon);
	       makerIcon.image = listInfo[index].styleUrl+ ".png";
       }


       // Set up our GMarkerOptions object
       markerOptions = { icon:makerIcon };
       marker = new GMarker(point, markerOptions);

       GEvent.addListener(marker, "click", function() {
	       var html = listInfo[index].info;
	       marker.openInfoWindowHtml(html);
	         
	       //if (document.getElementById(listInfo[index].nodeCountry) == "")   alert("("+listInfo[index].nodeCountry+")");
	       if (listInfo[index].nodeCountry != "") {
	        	if (continentNode.selectedIndex != 0)getContinents();
	         	document.getElementById(listInfo[index].nodeCountry).selected=true;
	         	getStates(listInfo[index].nodeState,listInfo[index].nodeCity,listInfo[index].nodeIcao);
	       }  
       });

       return marker;
     }

	//Show Marker draggable when doubbleclick on map
	GEvent.addListener(map, "dblclick", function(overlay,latlng) { 
          //dragMarker.setLatLng(latlng);
          dragMarker.show();
	});
	         
	function wheelevent(e)
	{
		if (!e){
		e = window.event
		}
		if (e.preventDefault){
		e.preventDefault()
		}
		e.returnValue = false;
	}
       
	 function getAddress(address,i,max,reach,map) {
	   	 geocoder.getLocations(address, function (result)
	     { 
	       // If that was successful
	       if (result.Status.code == G_GEO_SUCCESS) {
	         var p = result.Placemark[0].Point.coordinates;
	         var point = new GLatLng(p[1],p[0]);
	         map.setCenter(point,currentZoom);
	         var marker = manageMarker(point, i,max);

	         var html = listInfo[i].info;
	         html += "<a href='#' onClick='javascript:getMeteo("+marker.getPoint().toUrlValue()+")'>[Meteo]</a></div>";
	         if (isBalloon) map.openInfoWindowHtml(point,html);
	       }
	       // ====== Decode the error status ======
	       else {
	         // === if we were sending the requests to fast, try this one again and increase the delay
	         if (result.Status.code == G_GEO_TOO_MANY_QUERIES) {
	           delay++;
	       	   reach(address);
	         } else {
	           var reason="Code "+result.Status.code;
	           if (result.Status.code == G_GEO_UNKNOWN_ADDRESS) {

	               //alert(reasons[result.Status.code]);
	               if (address.indexOf(" ") != -1) {
	                  address = address.substring(0,address.lastIndexOf(" "));
	                  reach(address);
	               }
	               //reason = reasons[result.Status.code];

               }  
	         }   
	       }
	     }
	   );
	   //return map;
	 }

	function reachAddress(address){
         getAddress(address,ind,listInfo.length,reachAddress,map);
     	 //var dummy = setTimeout(func,delay);
	}
	
	function valideBalloon(index,info,point){
        //alert(listInfo[index].latitude);
 /*       if (listInfo[index].latitude == 0) {*
        	info = replaceGotoGEarth(info, point);
        }
 */       return info;
	}

 	function replaceGotoGEarth(info, point){
 		var getCityKml    = "<a href='#' onClick='javascript:getCityKml(document.forms[0]);'>";
 		var getStateKml   = "<a href='#' onClick='javascript:getStateKml(document.forms[0]);'>";
 		var getCountryKml = "<a href='#' onClick='javascript:getCountryKml(document.forms[0]);'>";
 		var newGetter     = "";
 		var countryStr    = ", "+countryNode.options[countryNode.selectedIndex].text.replace("'","&#39;");
 	    if (info.indexOf(getCityKml) != -1) {
 	        message = cityNode.options[cityNode.selectedIndex].text+countryStr;
 			newGetter     = "<a href='#' onClick='javascript:gotoPos("+point.toUrlValue()+",\""+message+"\")'>"
 	        info = info.replace(getCityKml,newGetter);
 	    } else if (info.indexOf(getStateKml) != -1) {
 	        message = stateNode.options[stateNode.selectedIndex].text+countryStr;
 			newGetter     = "<a href='#' onClick='javascript:gotoPos("+point.toUrlValue()+",\""+message+"\")'>"
 	        info = info.replace(getStateKml,newGetter);
 	    } else if (info.indexOf(getCountryKml) != -1) {
 	        message = countryStr;
 			newGetter     = "<a href='#' onClick='javascript:gotoPos("+point.toUrlValue()+",\""+message+"\")'>"
 	        info = info.replace(getCountryKml,newGetter);
 	    }
 	    return info;
 	}
	
	function manageMarker(point, i,max){
	     //var lookingMarker = listMarkerInfo[keyId(listInfo[i])].listMarkerInfo[keyId(listInfo[i])];
	     var marker = null;
	     var key = keyId(listInfo[i]);

		 // alert(listMarkerInfo.length+" - "+key);
	     if ((listMarkers[key] == null) && (listMarkers[key] != "")){
	 		marker = createMarker(point, i,max,marker);
	  	  	map.addOverlay(marker);
	   	  	
	        listMarkers[key] = marker;
	        goobleIcon = marker.getIcon();
	        var icon = goobleIcon.image;

	        var coord  = marker.getPoint().toUrlValue();
	        var coords = coord.split(",");

     		jsonrpc.dicoExplore.addMarkerinfo(listMarkerInfo[key].title, listMarkerInfo[key].type, listMarkerInfo[key].info, String(coords[0]), String(coords[1]), key, icon);
	        
	        //listMarkerInfo[key].longitude = coords[1];
	   	  	nodeMarkers.options[nodeMarkers.options.length] = new Option(listInfo[i].title,key, false, false);
	   	 } else {
	   	    marker = listMarkers[key];
	   	 }
	   	 return marker;
	}
   	return map;      

}

	//Create Markers draggable
	////////////////////////////////
      function createMenuMarker(dragMarker,point) {
	     var tinyIcon = new GIcon();
	     tinyIcon.image = "http://maps.google.com/mapfiles/ms/icons/yellow-dot.png";
         tinyIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
	     //tinyIcon.image = "http://maps.google.com/mapfiles/ms/micons/question.png";
         //tinyIcon.shadow = "http://maps.google.com/mapfiles/ms/micons/question_shadow.png";
         
         tinyIcon.iconSize = new GSize(32, 34);
         tinyIcon.shadowSize = new GSize(56, 34);
         tinyIcon.iconAnchor = new GPoint(16,32); 
         tinyIcon.infoWindowAnchor = new GPoint(16,0); 
         tinyIcon.infoShadowAnchor = new GPoint(18, 25);
         
         dragMarker = new GMarker(point,  {icon:tinyIcon,draggable: true});
         
         GEvent.addListener(dragMarker, "dragstart", function() {
         	map.closeInfoWindow();
         });

         GEvent.addListener(dragMarker, "click", function() {
			if (continentNode.selectedIndex != 0)getContinents();	
            html = getMenuMagic(dragMarker);
            dragMarker.openInfoWindowHtml(html);
         });
         
		/*
         GEvent.addListener(dragMarker, "dragend", function() {
           //var html = "<a href='#' onClick='javascript:gotoPos("+dragMarker.getPoint().toUrlValue()+")'>Click here to open on Google Earth <br/>or Drag the marker at a new location.</a>";
           //dragMarker.openInfoWindowHtml(html);
      	 });

         GEvent.addListener(dragMarker, "mouseover", function() {
           var html = "<div class='balloonIntro'>"+"Click <a href='#' onClick='javascript:gotoPos("+dragMarker.getPoint().toUrlValue()+")'>here</a> to view this location on Google Earth or Drag the marker at a new location."+"</div>";
           dragMarker.openInfoWindowHtml(html);
         });
	    */
         return dragMarker;
       }

/////////////////////////////////////////////////////////////////////
function setUpMap(gmapNode){
    map = new GMap2(gmapNode);
    map.addMapType(G_PHYSICAL_MAP);
    //map.addMapType(G_STATELLITE_3D_MAP);
    map.addControl(new GScaleControl(200));
	//map.addControl(new GHieriarchicalMapTypeControl());
	//map.addControl(new GHierarchicalMapTypeControl(),new GControlPosition(G_ANCHOR_TOP_RIGHT,new GSize(7,7)));
	
	map.enableDoubleClickZoom();
	map.enableScrollWheelZoom();
	map.enableContinuousZoom();
	map.getContainer().style.overflow="visible";
    var mapControl = new GMapTypeControl();
    map.addControl(new GLargeMapControl());
	map.addControl(new GScaleControl(200));
    
  	//map.addControl(new MapSizeControl());
	map.addControl(mapControl);
//  ======== Add a map overview ==========
   // map.addControl(new GOverviewMapControl(new GSize(180,120)));
    

    //  ======== A function to adjust the positioning of the overview ========
    /*
    function positionOverview(x,y) {
      var omap=document.getElementById("map_overview");
      omap.style.left = x+"px";
      omap.style.top = y+"px";
      
      // == restyling ==
      omap.firstChild.style.border = "1px solid gray";

      omap.firstChild.firstChild.style.left="4px";
      omap.firstChild.firstChild.style.top="4px";
      omap.firstChild.firstChild.style.width="190px";
      omap.firstChild.firstChild.style.height="190px";
    }

    //  ======== Cause the overview to be positioned AFTER IE sets its initial position ======== 
    setTimeout("positionOverview(558,254)",1);
    */
}

function getCSS(line){
	return ((line.indexOf('Airport') != -1)?'balloonAirport':'balloon');	
}

function callCountryInfoByCoord(dragMarker){
        var timeout = setTimeout('eval("jsonrpc.dicoExplore.gotCountryInfoByCoord("+dragMarker.getPoint().toUrlValue()+")")', 6000);
}

//--------------------------------------- Magic menu  ----------------------------------------------
function getMenuMagic(dragMarker) {   
	 var searchResult = null;
	 var title = "Map2Explore";
	 valuesOptions = testOptionsValue();

     if (lastUrlValue != dragMarker.getPoint().toUrlValue()){
     	searchResult = eval("jsonrpc.dicoExplore.gotNearestGeonames("+dragMarker.getPoint().toUrlValue()+")");
	 	 if (searchResult != null){
		 	 title = searchResult.nameCountry;
		   	 document.getElementById(searchResult.idCountry).selected=true;
        	 if (!isInitSelectInfo)initSelectInfo();        
			 getStates(searchResult.idState,searchResult.idCity,"");
		 } else {
		  	return  "<div class='balloonTitleMenu'><br/>Nothing is found at this location...<br/></div>";
		  	lastUrlValue = "xxx";
		 }
        lastUrlValue = dragMarker.getPoint().toUrlValue();
     }

//     	searchResult = eval("jsonrpc.dicoExplore.gotNearestGeonames("+dragMarker.getPoint().toUrlValue()+")");

     var country = countryNode.options[countryNode.selectedIndex].text.replace(/'/g,"&#39;");
     var state   = ((stateNode.options.length > 0)?stateNode.options[stateNode.selectedIndex].text:"");
     var city    = ((cityNode.options.length > 0)?cityNode.options[cityNode.selectedIndex].text:"");
     state   	 = state.replace(/'/g,"&#39;")
     city 		 = city.replace(/'/g,"&#39;");

	 var coordinates = eval("jsonrpc.dicoExplore.getCoordonates("+dragMarker.getPoint().toUrlValue()+")");	     
	 jsonrpc.dicoExplore.setKmlDescrition(coordinates);
	 var info = "<div class='balloonTitleMenu'>Magic Menu ("+title+")";
	 info += "<div class='balloonMenuMagic'>"
	
	 info += "Nearest places found: <br/>";
	 info += "<a href='#' class='menu' onClick='javascript:getCountryInfo()'>-"+country+" </a><br/>";
	 if (stateNode.options.length > 0) info += "<a href='#' class='menu' onClick='javascript:getStateInfo()'>-"+state+" </a><br/>";
	 if (cityNode.options.length > 0) info += "<a href='#' class='menu' onClick='javascript:getCityInfo()'>-"+city+" </a><br/>";
	 for (var key in listURL) {    
		if ((key == "Google")||(key == "Yahoo")){
		   	info += createHREFmenu(listURL[key]+((cityNode.options.length > 0)?city:state)+" "+country,"["+key+"] ");
		 }
	 }
 	 info += "<a href='#' class='menu' onClick='javascript:gotoPos("+dragMarker.getPoint().toUrlValue()+",\"Near "+((cityNode.options.length > 0)?city:state)+"\",\"place\")'>[Google&nbsp;Earth]</a>";
	 info += "<br/>Nearest informations on the Web: <br/>";
	
	 for (var key in listURL) {    
		 if (key == "Wikipedia"){
 	   		info += "<a href='#' class='menu' onClick='javascript:getNearestWikiArticles("+dragMarker.getPoint().toUrlValue()+")'>-Wikipedia (articles)</a><br/>";
		 	info += "<a href='#' class='menu' onClick='javascript:getNearestAirports("+dragMarker.getPoint().toUrlValue()+")'>-Airports </a><br/>";
   		 } else if (key == "Panoramio"){
		 	//info += "<a href='#' class='menu' onClick='javascript:getPanoramio(dragMarker,this)'>-Panoramio (photos)</a>";
		 	info += "<a href='#' class='menu' onClick='javascript:getNearestPhotos("+dragMarker.getPoint().toUrlValue()+",\"menuPhotos\")'>-Panoramio (photos)</a>";
		 }
	 }
 	 //info += "<a href='#' class='menu' onClick='javascript:getMeteo("+dragMarker.getPoint().toUrlValue()+")'>[Weather]</a>";
	 info += "<br/>More nearest places:<br/>";
	 var listNearest = jsonrpc.dicoExplore.getListNearestPlaces();
	 for(var i=0; i < listNearest.list.length; i++){
	   Nearestplace = listNearest.list[i];
	   var name = Nearestplace.name.replace(/'/g,"&#39;");
	   var description = Nearestplace.description.replace(/'/g,"&#39;");
	   info += "<a href='#' class='menu' onClick='javascript:getNearestplace(\""+name+"\",\""+Nearestplace.key+"\",\""+description+"\",dragMarker)'>-"+listNearest.list[i].name+" ("+listNearest.list[i].number+")</a><br/>";
	 }
		 
     return info+= "</div><div>Select one for more info...</div></div>";
}

//--------------------------------------- NearestPhotos  ----------------------------------------------
	function menuPhotos(panoramio) { 
		listPhotos = panoramio['photos']
		if (listPhotos != null){
			 var info = "<div class='balloonTitleMenu'>Nearest photos";
			 info += "<div class='balloonMenuMagic'>";
			 info += "Select a photo or GMaps/GEarth to see all.<br/>";
			 for(var i=0; i < listPhotos.length; i++){
			    var p = listPhotos[i];
				var title = formatTitle(p['photo_title'],p['owner_name']);
				var distance = eval("jsonrpc.dicoExplore.calculDistance("+dragMarker.getPoint().toUrlValue()+","+p["latitude"]+","+p["longitude"]+")");
			    info += "<a href='#' class='menu' onClick='getNearestPhotoInfo("+i+")'>-"+title+" ("+distance+" km)</a><br/>";
			 }
		 }
		 if ((listPhotos == null) || (listPhotos.length == 0)){
		    alert("No photos found near this location!");
		 } else {
			info+= "</div><div class='menuNearest'>"+getMenuNearest("photos","","")+"</div></div>";
			dragMarker.openInfoWindowHtml(info);
		 }
	}
 
	function getNearestPhotos(lat, lng,callback){
	    var minx = lng - 0.6;
	    var maxx = lng + 0.6;
	    var miny = lat - 0.3;
	    var maxy = lat + 0.3;
        var url = "http://www.panoramio.com/map/get_panoramas.php?order=popularity&set=public&from=0&to=20&minx="+minx+"&miny="+miny+"&maxx="+maxx+"&maxy="+maxy+"&size=small&callback="+callback;
        var jstag=document.createElement("script");
        jstag.setAttribute("type", "text/javascript");
        jstag.setAttribute("src", url);
        document.getElementsByTagName("head")[0].appendChild(jstag);
	}
	

	function perfNearestPhoto2Map(){
		var listInfo=Array();
		
		for (var i=0; i < listPhotos.length; i++){
		    var photo = listPhotos[i];
		    var balloonPlace = formatPhoto(false,i);
		    var title = formatTitle(photo['photo_title'],photo['owner_name']);
	    	info = new MarkerInfo(title,"photo",photo['photo_file_url'],"",balloonPlace,photo['latitude'],photo['longitude'],countryNode.options[countryNode.selectedIndex].id,valuesOptions["idstate"],valuesOptions["idcity"],"");
	     	listMarkerInfo[keyId(info)] = info;
	    	listInfo[i] = info;
	   	}
	    if (!isKeepZoom) currentZoom = 13;
		map = showGoogleMap(false,listInfo,map);
	}
	
	function perfNearestPhoto(panoramio){
		listPhotos = panoramio['photos'];
		var listInfo=Array();
		for (var i=0; i < listPhotos.length; i++){
		    var photo = listPhotos[i];
		    var balloonPlace = formatPhoto(false,i);
		    var title = formatTitle(photo['photo_title'],photo['owner_name']);
	    	info = new MarkerInfo(title,"photo",photo['photo_file_url'],"",balloonPlace,photo['latitude'],photo['longitude'],countryNode.options[countryNode.selectedIndex].id,valuesOptions["idstate"],valuesOptions["idcity"],"");
	     	listMarkerInfo[keyId(info)] = info;
	    	listInfo[i] = info;
	   	}
	    if (!isKeepZoom) currentZoom = 13;
		map = showGoogleMap(false,listInfo,map);
	}

	function perfNearestPhoto2Earth(){
		jsonrpc.dicoExplore.initListNearestMarkerinfo();
		
	   	for (var i=0; i < listPhotos.length; i++){
		    var photo = listPhotos[i];
		    var balloonPlace = formatPhoto(true,i);
		    var title = formatTitle(photo['photo_title'],photo['owner_name']);
			jsonrpc.dicoExplore.addNearestMarkerinfo(title, "photo", balloonPlace, String(photo['latitude']), String(photo['longitude']), "", photo['photo_file_url']);
	   	}
		document.forms[0].action = "ActionSendfile.do?method=kmlFromNearest"
		document.forms[0].filename.value  = "Map2Explore";
		document.forms[0].label.value     = photo['owner_name'];
		document.forms[0].submit();
		
	}

//-------------------------------- util magic menu ---------------------------------	
	function formatTitle(title,ownerName){
	 	var maxlength = 25;
	    if (title != ""){
			if (title.length > maxlength) {
				title = title.substring(0, maxlength) + "&#8230;";
			}
			//title = removeAccents(title);
	    } else {
	    	title = ownerName;
		} 

		return title.replace(/\"/g,"&#39;");
	}
	
	function testOptionsValue(){
		var values = new Array();
	    if (cityNode.options.length == 0){
	    	values["idcity"] = "";
	    } else {
	    	values["idcity"] = cityNode.options[cityNode.selectedIndex].id;
	    }
	    if (stateNode.options.length == 0){
	    	values["idstate"] = "";
	    } else {
	    	values["idstate"] = stateNode.options[stateNode.selectedIndex].id;
	    }
	    
	    return values;
	}

//--------------------------------------- NearestPlace  ----------------------------------------------
function getNearestplace(name,key,description,dragMarker){
	var listGeonames = jsonrpc.dicoExplore.gotListGeonames(key);
	 var info = "<div class='balloonTitleMenu'>Magic Menu ("+name+")";
	 info += "<div class='balloonMenuMagic'>";
	 info += description+"<br/>";
	 if (listGeonames.list != null){
		 for(var i=0; i < listGeonames.list.length; i++){
		   geonames = jsonrpc.dicoExplore.selectGeonames(i,key);
		   var title = formatTitle(geonames.ansiname,geonames.ansiname);
		   info += "<a href='#' class='menu' onClick='javascript:getPlaceInfo("+i+",\""+key+"\",dragMarker)'>"+"-"+title+" ("+geonames.distance+" km)</a><br/>";
		 }
		 info+= "</div><div class='menuNearest'>"+getMenuNearest("place",key,name)+"</div></div>"
	
		 dragMarker.openInfoWindowHtml(info);
	 }
}


function perfNearestPlace2Map(key){
	var listGeonames = jsonrpc.dicoExplore.gotListGeonames(key);
	var listInfo=Array();
   	for (var i = 0; i < listGeonames.list.length; i++) {
   	    var geonames = listGeonames.list[i];
   	    var markerInf = selectNearestMarker(false,i,key,geonames);
	    var balloonPlace = "";
	    var namePlace = "";
		for (var place in markerInf) {    
		    namePlace = place;
	    	balloonPlace = markerInf[place];
		}
    	info = new MarkerInfo(geonames.ansiname,namePlace,markerImg[namePlace],"",balloonPlace,geonames.latitude,geonames.longitude,countryNode.options[countryNode.selectedIndex].id,valuesOptions["idstate"],valuesOptions["idcity"],"");
     	listMarkerInfo[keyId(info)] = info;
    	listInfo[i]=info;
   	}
    if (!isKeepZoom) currentZoom = 13;
	map = showGoogleMap(false,listInfo,map);
}

function perfNearestPlace2Earth(key,name){
	var listGeonames = jsonrpc.dicoExplore.gotListGeonames(key);
	jsonrpc.dicoExplore.initListNearestMarkerinfo();
	
   	for (var i = 0; i < listGeonames.list.length; i++) {
   	    var geonames = listGeonames.list[i];
   	    var markerInf = selectNearestMarker(true,i,key,geonames);
	    var balloonPlace = "";
	    var namePlace = "";
		for (var place in markerInf) {    
		    namePlace = place;
	    	balloonPlace = markerInf[place];
		}
		jsonrpc.dicoExplore.addNearestMarkerinfo(geonames.ansiname, namePlace, balloonPlace, String(geonames.latitude), String(geonames.longitude), "", "");
   	}
	document.forms[0].action = "ActionSendfile.do?method=kmlFromNearest"
	document.forms[0].filename.value  = "Map2Explore";
	document.forms[0].label.value     = name;
	document.forms[0].submit();
	
}

//--------------------------------------- Wikipedia ----------------------------------------------
function getNearestWikiArticles(lat, lng){
	var listWikiArticle = jsonrpc.dicoExplore.gotNearestWikiArticles(lat, lng);
	if (listWikiArticle != null){
		 var info = "<div class='balloonTitleMenu'>Wikipedia articles";
		 info += "<div class='balloonMenuMagic'>";
		 info += "Select a title to see the article or GMaps/GEarth to see all.<br/>";
		 for(var i=0; i < listWikiArticle.list.length; i++){
		   WikiArticle = listWikiArticle.list[i];
		   var title = formatTitle(WikiArticle.title,WikiArticle.title);
		   //info += WikiArticle.title+"<br/>";
		   info += "<a href='#' class='menu' onClick='getWikipediaInfo("+i+")'>-"+title+" ("+WikiArticle.distance+" km)</a><br/>";
		 }
	 }
	 if ((listWikiArticle == null) || (listWikiArticle.list.length == 0)){
	    alert("No Wikipedia articles found at this location...");
	 } else {
		info+= "</div><div class='menuNearest'>"+getMenuNearest("wiki","","")+"</div></div>";
		dragMarker.openInfoWindowHtml(info);
	 }
}

function perfNearestWiki2Map(){
	var listWikiArticle = jsonrpc.dicoExplore.gotNearestWikiArticles();
	var listInfo=Array();

   	for (var i = 0; i < listWikiArticle.list.length; i++) {
   	    var wikipediaArticle = listWikiArticle.list[i];
	    var balloonPlace = formatWikipedia(false,i,wikipediaArticle);
	    var namePlace = "wiki";
	    var title = removeAccents(wikipediaArticle.title);
    	info = new MarkerInfo(title,namePlace,markerImg[namePlace],"",balloonPlace,wikipediaArticle.latitude,wikipediaArticle.longitude,countryNode.options[countryNode.selectedIndex].id,valuesOptions["idstate"],valuesOptions["idcity"],"");
     	listMarkerInfo[keyId(info)] = info;
    	listInfo[i] = info;
   	}
    if (!isKeepZoom) currentZoom = 13;
	map = showGoogleMap(false,listInfo,map);
}

function perfNearestWiki2Earth(){
	var listWikiArticle = jsonrpc.dicoExplore.gotNearestWikiArticles();
	jsonrpc.dicoExplore.initListNearestMarkerinfo();
	
   	for (var i = 0; i < listWikiArticle.list.length; i++) {
   	    var wikipediaArticle = listWikiArticle.list[i];
	    var balloonPlace = formatWikipedia(true,i,wikipediaArticle);
	    var namePlace = "wiki";
	    var title = removeAccents(wikipediaArticle.title);
		jsonrpc.dicoExplore.addNearestMarkerinfo(title, namePlace, balloonPlace, String(wikipediaArticle.latitude), String(wikipediaArticle.longitude), "", "");
   	}
	document.forms[0].action = "ActionSendfile.do?method=kmlFromNearest"
	document.forms[0].filename.value  = "Map2Explore";
	document.forms[0].label.value     = name;
	document.forms[0].submit();
	
}

//--------------------------------------- NearestAirport ----------------------------------------------
function getNearestAirports(lat, lng){
	var listNearestAirports = jsonrpc.dicoExplore.gotNearestAirports(lat, lng);
	if (listNearestAirports != null){
		 var info = "<div class='balloonTitleMenu'>Nearest Airports";
		 info += "<div class='balloonMenuMagic'>";
		 info += "Select an airport or GMaps/GEarth to see all.<br/>";
		 for(var i=0; i < listNearestAirports.list.length; i++){
		   NearestAirport = listNearestAirports.list[i];
		   var title = formatTitle(NearestAirport.name+" "+NearestAirport.icao,NearestAirport.name+" "+NearestAirport.icao);
		   //info += NearestAirport.name+"<br/>";
		   info += "<a href='#' class='menu' onClick='getNearestAirportInfo("+i+")'>-"+title+" ("+NearestAirport.distance+" km)</a><br/>";
		 }
	 }
	 if ((listNearestAirports == null) || (listNearestAirports.list.length == 0)){
	    alert("No airport found near this location!");
	 } else {
		info+= "</div><div class='menuNearest'>"+getMenuNearest("icao","","")+"</div></div>";
		dragMarker.openInfoWindowHtml(info);
	 }
}

function perfNearestAirport2Map(){
	var listNearestAirports = jsonrpc.dicoExplore.getListNearestAirports();
	var listInfo=Array();
   	for (var i = 0; i < listNearestAirports.list.length; i++) {
	    var airport = jsonrpc.dicoExplore.getNearestAirport(i);
	    var balloonPlace = formatAirport(false,airport);
	    var namePlace = "icao";
    	info = new MarkerInfo(airport.icao,namePlace,markerImg[namePlace],"",balloonPlace,airport.latitude,airport.longitude,countryNode.options[countryNode.selectedIndex].id,valuesOptions["idstate"],valuesOptions["idcity"],"");
     	listMarkerInfo[keyId(info)] = info;
    	listInfo[i] = info;
   	}
    //if (!isKeepZoom) currentZoom = 13;
	map = showGoogleMap(false,listInfo,map);
}

function perfNearestAirport2Earth(){
	var listNearestAirports = jsonrpc.dicoExplore.getListNearestAirports();
	jsonrpc.dicoExplore.initListNearestMarkerinfo();
	
   	for (var i = 0; i < listNearestAirports.list.length; i++) {
   	    var airport = jsonrpc.dicoExplore.getNearestAirport(i);
	    var balloonPlace = formatAirport(true,airport);
	    var namePlace = "icao";
		jsonrpc.dicoExplore.addNearestMarkerinfo(airport.name, namePlace, balloonPlace, String(airport.latitude), String(airport.longitude), "", "");
   	}
	document.forms[0].action = "ActionSendfile.do?method=kmlFromNearest"
	document.forms[0].filename.value  = "Map2Explore";
	document.forms[0].label.value     = name;
	document.forms[0].submit();
	
}

//***************************************** MenuNearest ***************************************
function getMenuNearest(menu,key,name){
  var nearest2Map = "";
  var nearest2Earth = "";
	
  if (menu == "place"){
	  nearest2Map = "<a href='#' class='menuNearest' onClick='javascript:perfNearestPlace2Map(\""+key+"\")'>[GMaps]</a>";
	  nearest2Earth = "<a href='#' class='menuNearest' onClick='javascript:perfNearestPlace2Earth(\""+key+"\",\""+name+"\")'>[GEarth]</a>";
  } else if (menu == "wiki"){
	  nearest2Map   = "<a href='#' class='menuNearest' onClick='javascript:perfNearestWiki2Map()'>[GMaps]</a>";
	  nearest2Earth = "<a href='#' class='menuNearest' onClick='javascript:perfNearestWiki2Earth()'>[GEarth]</a>";
  } else if (menu == "icao"){
	  nearest2Map   = "<a href='#' class='menuNearest' onClick='javascript:perfNearestAirport2Map()'>[GMaps]</a>";
	  nearest2Earth = "<a href='#' class='menuNearest' onClick='javascript:perfNearestAirport2Earth()'>[GEarth]</a>";
  } else if (menu == "photos"){
	  nearest2Map   = "<a href='#' class='menuNearest' onClick='javascript:perfNearestPhoto2Map()'>[GMaps]</a>";
	  nearest2Earth = "<a href='#' class='menuNearest' onClick='javascript:perfNearestPhoto2Earth()'>[GEarth]</a>";
  }
  return "<div style='display:inline;margin:0px;'>"+nearest2Map+"</div>"+
  "<div style='display:inline;margin:26px;'>"+nearest2Earth+"</div>"+
  "<div style='display:inline;margin:0px;'><a href='#' class='menuNearest' onClick='javascript:returnMagicMenu()'>[Return]</a></div>";
}

function returnMagicMenu(){
    dragMarker.openInfoWindowHtml(getMenuMagic(dragMarker)); 
}


//--------------------------------------- Weather Meteo ----------------------------------------------

function getMeteo(lat,lng){
  	eval("jsonrpc.dicoExplore.gotMeteo("+lat+","+lng+")");
   	var html    = "";
   	var balloon = "";
   	//alert(wikiArticle);
   	var meteo = jsonrpc.dicoExplore.getMeteo();
   	if (meteo != null){
		html = meteo;
		balloon = "'balloonMeteo'"
     } else {
        balloon = "'balloon'";
        html = "<b>Sorry!</b><br/>No meteo is available at this location<br/>\n  or the service is down presently...<br/>";
   	 }
   	 dragMarker.setLatLng(new GLatLng(lat,lng));
     html = "<div class="+balloon+">"+html+"</div>";
	 dragMarker.openInfoWindowHtml(html);
}



function getPanoramio(dragMarker,obj){
	var coords = dragMarker.getPoint().toUrlValue().split(",");
    var zoom = 0;
   	zoom = (17-map.getZoom())
   	if (zoom > 6) zoom = 6;
	var urlpanoramio = "lt="+coords[0]+"&ln="+coords[1]+"&z="+zoom+"&k=2&a=1&tab=1";
	obj.target="_blank";
	obj.href="http://www.panoramio.com/map/#"+urlpanoramio;
}


//***************************** Functions KML **************************************
function askClearMarkers(){
    if ( confirm("Do you want to clear all markers?")){
    	clearMarkers();
    }
}

function clearMarkers(){
	map.clearOverlays();
    map.addOverlay(dragMarker);
    dragMarker.setLatLng(map.getCenter());
	nodeMarkers.options.length=0;
    listMarkerInfo = new Array();
    listMarkers = new Array();
    listInfo.length = 0;
    jsonrpc.dicoExplore.initListMarkerinfo();
}

function bringMarker(){
	map.removeOverlay(dragMarker);
    dragMarker = createMenuMarker(dragMarker,map.getCenter());
    map.addOverlay(dragMarker);
	dragMarker.openInfoWindowHtml("<div class='balloonIntro'>Click me for more info<br/>or Drag me at a new location.</div>");
}


function openMagicMenu(lat,lng){
   map.removeOverlay(dragMarker);
   dragMarker = createMenuMarker(dragMarker,new GLatLng(lat,lng));
   map.addOverlay(dragMarker);
   dragMarker.openInfoWindowHtml(getMenuMagic(dragMarker));
}

function doGeocoderSearch(address) {
   if (geocoder) {
     geocoder.getLatLng(
       address,
       function(point) {
         if (!point) {
           alert(address + " not found");
         } else {
            currentZoom = 10;
            map.setCenter(point,currentZoom);
			map.removeOverlay(dragMarker);
		    dragMarker = createMenuMarker(dragMarker,point);
		    map.addOverlay(dragMarker);
			dragMarker.openInfoWindowHtml("<div class='balloonIntro'><b><i>\""+address+"\" found!</b></i><br/><br/>Click me to explore this location<br/>or Drag me at a new one...</div>");
         }
       }
     );
   }

}

function selectMarker(markerSelected){
    listMarkers[markerSelected.value].openInfoWindowHtml(listMarkerInfo[markerSelected.value].info);
   	if (continentNode.selectedIndex != 0)getContinents();
	var values = markerSelected.value.split(",");
	var countryId = values[0];
	if (countryId != ""){
	   	document.getElementById(countryId).selected=true;
	    getStates(values[1],values[2],values[3]);
	}
}
