USGSOverlay.prototype = new google.maps.OverlayView();

//NUOVA FUNZIONE GEOCODIFICA GOOGLE
function newGeoIp(){
	// Try W3C Geolocation method (Preferred)
	  if (geo) {
	  setTimeout("callNoGeolocalizedMap()",2000);
	  geo.getCurrentPosition(function(position) {
	  latLngGeolocalized = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
	  latGeolocalized=position.coords.latitude;
	  lngGeolocalized=position.coords.longitude;
	  accurancyGeolocalized=position.coords.accuracy;
	  reverseGeocoding(latLngGeolocalized,latGeolocalized,lngGeolocalized,accurancyGeolocalized);
	  firstCall=1;
	  //	  country=position.gearsAddress.country;
  }, mapError ,{
      timeout: 10000

  });  
} else {
  // Browser doesn't support Geolocation
	 callNoGeolocalizedMap();
 // alert("Browser doesn't support Geolocation");
  
  }
}

function callNoGeolocalizedMap(){
	clearParamForCountryCodeFromSelect($("#gridCountry"+idTabMap));
	//questo controllo serve ad evitare che la mappa venga ricaricata se è il setTimeout di newGeoIp che entra in azione , dopo che l'utente 
	//ha gia geolocalizzato.
	
	if(firstCall==0) {
		var xmlEmpty="";
		setInitMap(xmlEmpty);
		isGeolocalized=false;
		showLocation();
	}
	
}

// questa funzione serve per i casi in cui nel tab dealer locator c'è la tendina con piu' nazioni.
//al change della nazione bisogna ripulire alcune variabili e ricreare la mappa come una non geolocalizzata
function cleanAndCallNoGeolocalizedMap(){
	    flagInitZoomArray=false;
		lat="";
		lng="";
		var xmlEmpty="";
		setInitMap(xmlEmpty);
		isGeolocalized=false;
		var noGeoLatLng = new google.maps.LatLng(label_gmap_center_lat, label_gmap_center_lng);
	    map[actuallyMap].map = createDynamicMap(noGeoLatLng);
	    flagCall=0;
	    flagDropDown=true;
	    eventsMap();
}

//ERRORE MAPPA IN FASE DI GEOLOCALIZZAZIONE
function mapError(e){
	//alert("mapError");
	 var xmlEmpty="";
	 setInitMap(xmlEmpty);
	 showLocation();
	 
    var error;
    switch (e.code) {
        case 1:
            error = "Permission Denied.\n\n Please turn on Geo Location by going to Settings ";
            break;
        case 2:
            error = "Network or Satellites Down";
            break;
        case 3:
            error = "GeoLocation timed out";
            break;
        case 0:
            error = "Other Error";
            break;
    }
    alert(error);
   
    //overlay = new USGSOverlay(map[actuallyMap].getBounds(), error, map[actuallyMap]);
}

//CERCO L'INDIRIZZO DALLA LAT&LNG e SETTO IL COUNTRY CON LA CAMPAIGNID 
function reverseGeocoding(latlng_position,lat_position,lng_position,accuracy_position){
	 //alert("reverse"+latlng_position+" "+lat_position+" "+lng_position+" "+accuracy_position+" "+idTabMap+" lastDealers"+lastDealers[actuallyMap]);
	var geocoder= new google.maps.Geocoder();
	 geocoder.geocode({'latLng': latlng_position}, function(results, status) {
	        
		 if (status == google.maps.GeocoderStatus.OK) {
			  //Prendo il country dalla result. Mi servira' per confrontarla con il country del dialogo    
		       var countryFromRevGeo="";
		       for (i=0;i<results[0].address_components.length;i++){
				   for (j=0;j<results[0].address_components[i].types.length;j++){
			           if(results[0].address_components[i].types[j]=="country"){
			        	   countryFromRevGeo = results[0].address_components[i].short_name;
			             break;
			        }
				   }
		       }
		      
		       // serve per dare la possibilità di prendere la country da una grid contenente un gruppo di paesi.
		       for (j=0;arrayNationsCountry!=null && arrayNationsCountry!="" && j<arrayNationsCountry.length && $("#gridCountry"+idTabMap).val()!=undefined;j++){
		    	   var country=arrayNationsCountry[j].split("-");
		    	   if(country[0].trim()==countryFromRevGeo.trim()){
		    		   campaignIdArray[idTabMap]=country[1].trim();
		    		   countryCode=countryFromRevGeo;
		    		   $("#gridCountry"+idTabMap).val(countryCode+"-"+campaignIdArray[idTabMap]);
		    		   break;
		    	   }
		       }
			
		      //verifico che stiamo parlando dello stesso paese.Se e' diverso fingo che sia come se non fosse correttamente geolocalizzato
		       if(countryFromRevGeo!=countryCode){
		       var xmlEmpty="";
		       setInitMap(xmlEmpty);
		       //firstCall=1;
		       showLocation();
		       }else{   
		           campaignId=campaignIdArray[idTabMap];
                    $('#search'+idTabMap).val(results[0].formatted_address);
		       		setDefaultCountryValue();
			        initZoomArray();
			        label_gmap_map_zoom=getZoomLevel(accuracy_position);
			       // alert("lat_position"+lat_position+"lng_position"+lng_position+"label_gmap_map_zoom"+label_gmap_map_zoom);
					prepareService(lat_position, lng_position, label_gmap_map_zoom);   
		       }
			
		 } else {
	         // alert("Geocoder failed due to: " + status);
	          errorGeocoder(status);
	        }
	  });
}

function changeSelectCountry (formForClean){
       	setCountryCodeFromSelect($("#gridCountry"+idTabMap));
		formForClean.reset();
		cleanAndCallNoGeolocalizedMap();
	}



function setInitMap(xmldoc1){
	
	try { //Internet Explorer
		xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async=false;
		xmlDoc.loadXML(xmldoc1);
	} catch(e) {
		try { //Firefox, Mozilla, Opera, etc.
			parser=new DOMParser();
			xmlDoc=parser.parseFromString(xmldoc1,"text/xml");
		} catch(e) {
			alert(e);
			return;
		}
	}
	
	if(xmldoc1!='') {

		var ipInfo = xmlDoc.documentElement.getElementsByTagName("info");	
		if (ipInfo) {
			var i = 0;
			var ip_localized = ipInfo[i].getElementsByTagName("ip_localized")[0].firstChild.nodeValue;
			var ip_address = ipInfo[i].getElementsByTagName("ip_address")[0].firstChild.nodeValue;
			var country_code = ipInfo[i].getElementsByTagName("country_code")[0].firstChild.nodeValue;
			var country_name = ipInfo[i].getElementsByTagName("country_name")[0].firstChild.nodeValue;
			var region_code = ipInfo[i].getElementsByTagName("region_code")[0].firstChild.nodeValue;
			var region_name = ipInfo[i].getElementsByTagName("region_name")[0].firstChild.nodeValue;
			var city_name = ipInfo[i].getElementsByTagName("city_name")[0].firstChild.nodeValue;
			var postal_code = ipInfo[i].getElementsByTagName("postal_code")[0].firstChild.nodeValue;	
			var lat = parseFloat(ipInfo[i].getElementsByTagName("lat")[0].firstChild.nodeValue);
			var lng = parseFloat(ipInfo[i].getElementsByTagName("lng")[0].firstChild.nodeValue);
			var metro_code = ipInfo[i].getElementsByTagName("metro_code")[0].firstChild.nodeValue;
			var area_code = ipInfo[i].getElementsByTagName("area_code")[0].firstChild.nodeValue;
			var time_zone = ipInfo[i].getElementsByTagName("time_zone")[0].firstChild.nodeValue;
		}
		else {
			var ip_localized = '';
			var country_code = '';
		}
		
	}	
	else {
		var ip_localized = '';
		var country_code = '';
	}
	
	setDefaultCountryValue();

	geo = new google.maps.Geocoder();
	lat=label_gmap_center_lat;
	lng=label_gmap_center_lng;
	label_gmap_map_zoom=label_gmap_center_zoom;
	label_gmap_map_minresolution=label_gmap_map_zoom;
					
}	

//INIZIALIZZAZIONE LIVELLI DI ZOOM
//------------------------------------
function initZoomArray() {
	   type = 'accZoomLevel';
	   var zoomArrayXML = $.ajax( {
        url : call_ws,
	        data : {
	       countryCode : countryCode,
		   type : type
	        },
	        dataType: "xml",
	        async: false,
	        success : function(data) {
	        	flagInitZoomArray=true;
	        },
	        error: function(xhr, ajaxOptions, thrownError){
	        	// alert("xhr: " + xhr.status);
	        	// alert("thrownError: " + thrownError);
	        }   
	      }).responseText;	
	   
	   setZoomArray(zoomArrayXML);	
}

function setZoomArray(xmldoc1){
	try { //Internet Explorer
		xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async=false;
		xmlDoc.loadXML(xmldoc1);
	} catch(e) {
		try { //Firefox, Mozilla, Opera, etc.
			parser=new DOMParser();
			xmlDoc=parser.parseFromString(xmldoc1,"text/xml");
		} catch(e) {
			alert(e.message);
			return;
		}
	}

	if(xmldoc1!='') {
		var ipInfo = xmlDoc.documentElement.getElementsByTagName("info");	
		if (ipInfo) {
			var i = 0;
	
	        zoom_array = new Array(ipInfo.length);
	        for (i=0;i < ipInfo.length; i++) {
		        zoom_array [i] = new Array(2);
		        zoom_array [i][0] = ipInfo[i].getElementsByTagName("accurancy")[0].firstChild.nodeValue;
		        zoom_array [i][1] = ipInfo[i].getElementsByTagName("zoom")[0].firstChild.nodeValue;
	      }
      }
	}
}


function getZoomLevel(accurancy) {
	var zoom_level = label_gmap_map_zoom;
	for(var dim=0; dim < 10; dim++) {
		if(zoom_array[dim][0] == accurancy){
			zoom_level = zoom_array[dim][1];	 
			return zoom_level;
		}
	}
	return zoom_level;
}

//---------------------------------------------------

//SETTA LA MAPPA CON IL PAESE DI DEFAULT ED IMPOSTA LE COORDINATE ED i LIVELLI DI ZOOM BASE
//---------------------------------------------------
function setDefaultCountryValue(){
       type = 'defaultGmaps';
	   var countryXML = $.ajax( {
	       url : call_ws,
	       data : {
	       countryCode : countryCode,
		   type : type
	        },
	        dataType: "xml",
	        async: false,
	        success : function(data) {
	        	//alert("success: " + data);
	        },
	        error: function(xhr, ajaxOptions, thrownError){
	        	// alert("xhr: " + xhr.status);
	        	// alert("thrownError: " + thrownError);
	        }   
	      }).responseText;	
		   
	   	setCountryMap(countryXML);
	}



function setCountryMap(xmldoc1){
	try { //Internet Explorer
		xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async=false;
		xmlDoc.loadXML(xmldoc1);
	} catch(e) {
		try { //Firefox, Mozilla, Opera, etc.
			parser=new DOMParser();
			xmlDoc=parser.parseFromString(xmldoc1,"text/xml");
		} catch(e) {
			alert(e.message);
			return;
		}
	}

	if(xmldoc1!='') {
		var ipInfo = xmlDoc.documentElement.getElementsByTagName("info");	
		if (ipInfo) {
			
			var i = 0;
			label_gmap_center_lat = parseFloat(ipInfo[i].getElementsByTagName("center_lat_fe")[0].firstChild.nodeValue);
			label_gmap_center_lng = parseFloat(ipInfo[i].getElementsByTagName("center_lon_fe")[0].firstChild.nodeValue);
			label_gmap_center_zoom = parseFloat(ipInfo[i].getElementsByTagName("center_zoom_fe")[0].firstChild.nodeValue);
			label_gmap_map_zoom = parseFloat(ipInfo[i].getElementsByTagName("map_zoom_fe")[0].firstChild.nodeValue);
			label_gmap_map_minresolution = parseFloat(ipInfo[i].getElementsByTagName("map_minres_fe")[0].firstChild.nodeValue);	
			label_gmap_map_maxresolution = parseFloat(ipInfo[i].getElementsByTagName("map_maxres_fe")[0].firstChild.nodeValue);
			
		}
	}
}

//---------------------------------------------------
// PRENDE DAL LINK LAT, LNG E ZOOM, MOSTRA LA MAPPA E CHIAMA IL SERVIZIO CHE CERCA I DEALER
function prepareService(latPas,lngPas,set_zoomPas){
	    lat=latPas;
		lng=lngPas;
		label_gmap_map_zoom=set_zoomPas;
		//label_gmap_map_zoom=11;
		//alert(idTabMap);
		showLocation();
		
		
	}

//FUNZIONE CHIAMATA DA showLocation - CREA LA MAPPA
function createDynamicMap(latlng){
    //alert("createDynamicMap"+countryCode+idTabMap+document.getElementById('maps'+idTabMap));
	//alert("createDynamicMap"+latlng+"zoom"+label_gmap_map_zoom+"min"+label_gmap_map_minresolution+"max"+label_gmap_map_maxresolution);
   
     var options = {
         zoom: label_gmap_map_zoom,
         minZoom: label_gmap_map_minresolution ,
         maxZoom: label_gmap_map_maxresolution ,
         center: latlng,
         mapTypeId: google.maps.MapTypeId.ROADMAP,
         mapTypeControlOptions: {
             mapTypeIds: []
           }
     };
       return new google.maps.Map(document.getElementById('maps'+idTabMap), options);
 }


// CREA LA MAPPA ED ASSOCIA I LISTENER PRENDENDO LAT E LNG DALLE VARIABILI GLOBALI
//----------------------------------------------------
function showLocation(){
	//alert("showLocation");
    if (lat=="")
        lat=label_gmap_center_lat;
    if (lng=="")
        lng=label_gmap_center_lng;
     latlng = new google.maps.LatLng(lat, lng);
    //alert("latlng"+latlng);
    
     loadArrayMap();
    
     //overlay = new USGSOverlay(bounds1, label_gmap_nodealer, map[actuallyMap]);
     flagCall=0;
     eventsLoadMap();
     //eventsMap();
     //showAddress();
     // return 1;
 }

function loadArrayMap(){
	var mapInfo={
   	   mapKey:'',
       map:'',
      geocoder : new google.maps.Geocoder() 
    }
	mapInfo.map=createDynamicMap(latlng);
    mapInfo.mapKey=idTabMap;
    map.push(mapInfo);
}
//---------------------------------------------------

// CARICA LA MAPPA CORRETTA PER IL TAB SELEZIONATO (SERVE PER I TAB MULTIPLI)
function getMap(mapKey) {
   // alert(map.length);
    for (var i = 0 ; i < map.length ; i++) {
        if (map[i].mapKey == mapKey) {
            return i;
        }
    }
    return false;
}

//CARICA l'EVENTO CHE SEGNALA IL CARICAMENTO COMPLETO DELLA MAPPA E LANCIA GLI ALTRI EVENTI
function eventsLoadMap(){
	 //EVENTO LOAD MAP
	//alert("eventsLoadMap before search actuallyMap"+actuallyMap);
	actuallyMap=""+getMap(idTabMap);
	//alert("idTab."+idTabMap+"actuallyMap:"+actuallyMap+"map[actuallyMap]"+map[actuallyMap].map);
	 if(lastDealers[actuallyMap]== undefined ){
       lastDealers[actuallyMap]=new Array();
     }
    indexLastDealers=lastDealers[actuallyMap].length;
    //alert("initialize_map"+indexLastDealers);
   eventsMap();
   showAddress();
	//	google.maps.event.addListener(map[actuallyMap].map, 'projection_changed', function() {
	//		//alert('projection_changed');
	//		
	//		  //  var zoomLevelMap = map[actuallyMap].getZoom();
	//   	      eventsMap();
	//   	      showAddress();
	//		  });
}


//CARICA GLI EVENTI
function eventsMap(){
	 //EVENTO ZOOM
	     google.maps.event.addListener(map[actuallyMap].map, 'zoom_changed', function() {
    	 zoomChangeBoundsListener = google.maps.event.addListener(map[actuallyMap].map, 'bounds_changed', function() {
   	    	//rimuovo il div contenente l'errore se c'e'. c'e' un for poiche' possono partire 2 richieste che restituiscono NO dealer found e lo scrivono 2 volte
         	//es: clicco su find 1° richiesta ... puo' scattare nel caso cambi il livello di zoom una 2° richiesta. Inserito for max 5 richieste.
            for (var i=0;i<5 && $("#overlayError"+idTabMap)!=null;i++){
         	  $("#overlayError"+idTabMap).remove();
             }
            if((firstCall==0 && flagChangeBoundFalse[actuallyMap]==undefined) || flagDropDown ){
        	   firstCallNoGeolocalizedMap(levelZoomNoGeolocalized);
        	   google.maps.event.removeListener(zoomChangeBoundsListener);
            }else if(flagChangeBoundFalse[actuallyMap]){
	   	    	   //  var zoomLevelMap = map[actuallyMap].getZoom();
			       bounds1 = map[actuallyMap].map.getBounds();
			       //alert("change zoom"+bounds1);
			       southWest = bounds1.getSouthWest();
			       northEast = bounds1.getNorthEast();
			       
			       // Cancello i markers se ,quelli in mappa, superano il livello massimo impostato da dialogo.
			       if(lastDealers.length!=0 && lastDealers[actuallyMap]!=undefined && lastDealers[actuallyMap][indexLastDealers-1]!=undefined && lastDealers[actuallyMap].length>numberCleanMarker){
			       //   alert("before deleteOverlaysMarkers di selectService"+lastDealers[actuallyMap].length);
					deleteOverlaysMarkers();
					}
			       selectService(southWest.lat(),southWest.lng(),northEast.lat(),northEast.lng());
			       google.maps.event.removeListener(zoomChangeBoundsListener);
	    	 } 

});
   	     
	});
    //EVENTO CHE ALLA FINE DEL DRAG RICARICA I MARKER
            google.maps.event.addListener(map[actuallyMap].map, 'dragend', function() {
	      	//rimuovo il div contenente l'errore se c'e'. c'e' un for poiche' possono partire 2 richieste che restituiscono NO dealer found e lo scrivono 2 volte
	        //es: clicco su find 1° richiesta ... puo' scattare nel caso cambi il livello di zoom una 2° richiesta. Inserito for max 5 richieste.
	        for (var i=0;i<5 && $("#overlayError"+idTabMap)!=null;i++){
	        	  $("#overlayError"+idTabMap).remove();
	        }
	         if((firstCall==0 && flagChangeBoundFalse[actuallyMap]==undefined) || flagDropDown){
	        	firstCallNoGeolocalizedMap(levelZoomNoGeolocalized);
	          }else if(flagChangeBoundFalse[actuallyMap]){
			  bounds1 =  map[actuallyMap].map.getBounds();
		      southWest = bounds1.getSouthWest();
		      northEast = bounds1.getNorthEast();
		      // Cancello i markers se ,quelli in mappa, superano il livello massimo impostato da dialogo.
	       	  if(lastDealers.length!=0 && lastDealers[actuallyMap]!=undefined && lastDealers[actuallyMap][indexLastDealers-1]!=undefined && lastDealers[actuallyMap].length>numberCleanMarker){
		      // alert("before deleteOverlaysMarkers di selectService"+lastDealers[actuallyMap].length);
				deleteOverlaysMarkers();
	       	  }
		      selectService(southWest.lat(),southWest.lng(),northEast.lat(),northEast.lng());
	    	  }
	  });
	 
}
//FUNZIONE CHE NON CHIAMA LA FUNZIONE CHE GENERA I MARKER,
//ALLA PRIMA CHIAMATA NON GEOLOCALIZZATA SE AL DI SOTTO DEL LIVELLO IMPOSTATO DA DIALOGO
function firstCallNoGeolocalizedMap(controlLevel){
   	if (map[actuallyMap].map.getZoom()<controlLevel){
       	//alert(map[actuallyMap].map.getZoom()+"is less"+controlLevel);
       	  overlay = new USGSOverlay(map[actuallyMap].map.getBounds(), label_gmap_message_many_dealer, map[actuallyMap].map,"");  
      	  deleteOverlaysMarkers();
       	}
       	else{
    	   bounds1 = map[actuallyMap].map.getBounds();
	       //alert("change zoom"+bounds1);
	       southWest = bounds1.getSouthWest();
	       northEast = bounds1.getNorthEast();
	       // Cancello i markers se ,quelli in mappa, superano il livello massimo impostato da dialogo.
	       	  if(lastDealers.length!=0 && lastDealers[actuallyMap]!=undefined && lastDealers[actuallyMap][indexLastDealers-1]!=undefined && lastDealers[actuallyMap].length>numberCleanMarker){
		      // alert("before deleteOverlaysMarkers di selectService"+lastDealers[actuallyMap].length);
				deleteOverlaysMarkers();
	        }
	       selectService(southWest.lat(),southWest.lng(),northEast.lat(),northEast.lng());
	       
       	}
}


//FUNZIONE RICERCA INDIRIZZO
function showAddress() { 
	   flagDropDown=false;
	   setCountryCodeFromSelect($("#gridCountry"+idTabMap));
	   var search = document.getElementById("search"+idTabMap).value +" "+countryCode;
	  // ====== Perform the Geocoding ======        
	  map[actuallyMap].geocoder.geocode( { 'address': search}, function(resultsAddr, statusAddr) {
	      if (statusAddr == google.maps.GeocoderStatus.OK) {
	       //Prendo il country dalla result. Mi servira' per confrontarla con il country del dialogo    
	       var countryFromGeo="";
	       for (i=0;i<resultsAddr[0].address_components.length;i++){
			   for (j=0;j<resultsAddr[0].address_components[i].types.length;j++){
		           if(resultsAddr[0].address_components[i].types[j]=="country"){
		             countryFromGeo = resultsAddr[0].address_components[i].short_name;
		             break;
		        }
			   }
	       }
	       //Se non ho il flagInitZoomArray a true significa che è la prima ricerca dopo aver visualizzato la mappa della nazione non geolocalizzata.
	       //Quindi devo settare il country di default con l'inizializzazione dei livelli di zoom
	     
	      if(!flagInitZoomArray)
	       {
	    	setDefaultCountryValue();
	        initZoomArray();
	       }
	      
	       
		    //  document.getElementById("messageTitle").innerHTML = label_gmap_list_title;
	        // ===== If there was more than one result, "ask did you mean" on them all =====
	       if (firstCall==1 || isGeolocalized==true){
	    	  if (resultsAddr.length > 1) {
	    		  $('#mapContainer').attr('style', 'display: none');
	    		  $('#addressResult').attr('style', 'display: block');
	    		   document.getElementById('search-results'+idTabMap).innerHTML="";

    		        for(var i=0; i<resultsAddr.length; i++){
    		        	var bounds_viewportSearch=resultsAddr[i].geometry.viewport;
    		        	var local=resultsAddr[i].geometry.location;
		    			var latElem = local.lat();
		    			var lngElem =local.lng();
		    		    var southWestElem = bounds_viewportSearch.getSouthWest();
		    		    var northEastElem = bounds_viewportSearch.getNorthEast();
		    		    if(countryFromGeo!="" && countryFromGeo==countryCode)
	    		         document.getElementById('search-results'+idTabMap).innerHTML+="<li><a href='javascript:callSearchAddress("+latElem+","+lngElem+","+southWestElem.lat()+","+southWestElem.lng()+","+northEastElem.lat()+","+northEastElem.lng()+")'><span>"+i+"-</span>"+resultsAddr[i].formatted_address+"</a></li>";
		    		    else
	    		         document.getElementById("search-results"+idTabMap).innerHTML = label_gmap_message_not_addr_country;
		    		    
    		        }
	        }
	      
	        // ===== If there was a single marker =====
	        else {
	        	//alert("sono in else"+resultsAddr[0].formatted_address);
	        	document.getElementById('search-results'+idTabMap).innerHTML="";
	        	 if(countryFromGeo!="" && countryFromGeo==countryCode){
	        		 var bounds_viewport=resultsAddr[0].geometry.viewport;
	 	             showSearchLocation(resultsAddr[0].geometry.location,bounds_viewport);
	 	         }
	        	 else{
    		         document.getElementById("search-results"+idTabMap).innerHTML = label_gmap_message_not_addr_country;
	        	 }
	        	
	        	
	        }
	      }
	    	else{firstCall=1;}
	      }
	      // ====== Decode the error status ======
	      else {
	    	  // se e' la prima chiamata significa che non ho geolocalizzato e quindi non devo mostrare l'overlay di errore
	    		  if(firstCall>0){
	    		    errorGeocoder(statusAddr);
	    		  }
	    		 /* else{
	    			  overlay = new USGSOverlay(map[actuallyMap].map.getBounds(), label_gmap_message_many_dealer, map[actuallyMap].map,"");  
	    		  }*/
	    	  
	      }
	    });
	}

//FUNZIONE CHE CHIAMA DAI LINK MULTIPLI DEGLI INDIRIZZI LA showSearchLocation CREANDO LATLNG E BOUNDS
function callSearchAddress(addrlat,addrlng,swlat,swlng,nelat,nwlng){
	 var sALatLng = new google.maps.LatLng(addrlat, addrlng);
	 var sAsouthWest = new google.maps.LatLng(swlat,swlng);
	 var sAnorthEast = new google.maps.LatLng(nelat,nwlng);
	 var sAbounds = new google.maps.LatLngBounds(sAsouthWest,sAnorthEast);
	 showSearchLocation(sALatLng,sAbounds);
	 //lert("test"+boundsn+" separati"+swlat+","+swlng+","+nelat+","+nwlng);
	
}

// CREA LA MAPPA ED ASSOCIA I LISTENER PRENDENDO LAT E LNG DALLA VARIABILE PASSATA e CHIAMA LA SELECTSERVICE 
function showSearchLocation(latlngSearch,boundsSearch){
	
	 //pulisco un eventuale percorso precedente
	 $("#streetDirection"+idTabMap).html('');
	 //abilito l'evento zoom e drag che poteva essere stato disabilitato da una ricerca percorso
	 flagChangeBoundFalse[actuallyMap]=true;
	 lat="";
	 lng="";
	 latlng="";
     map[actuallyMap].map = createDynamicMap(latlngSearch);

     flagCall=0;
     eventsMap();
     bounds1=boundsSearch;
     if(map[actuallyMap].map.getBounds()!=undefined){
     	map[actuallyMap].map.fitBounds(boundsSearch);
        bounds1 =  map[actuallyMap].map.getBounds();
     }
		  southWest = bounds1.getSouthWest();
		  northEast = bounds1.getNorthEast();
	       // CANCELLO I MARKERS POICHE' LA MAPPA SI RICARICA AZZERANDO GRAFICAMENTE I MARKER,LA SELECTSERVICE ELIMINERA' EVENTUALI OVERLAY D'ERRORE
		  deleteOverlaysMarkers();
		  selectService(southWest.lat(),southWest.lng(),northEast.lat(),northEast.lng());
 }

function selectService(llat,llng,rlat,rlong){

	type = 'dealerlist';
	flagCall++;
	var codeCountry=countryCode;
	if (codeCountryMap!="")
		codeCountry=codeCountryMap;
    //	alert("llat: " + llat + " llng: " + llng + " rlat: " + rlat + " rlong: " + rlong);
	//alert("selectService:"+homeStateLocale+campaignId+codeCountry+"lastDealers[]"+lastDealers[actuallyMap]); 
	
   $.ajax( {
        url : call_ws,
        data : {
          countryCode : codeCountry,
 	      type : type,          
          leftLat: llat,
          leftLong: llng,
          rightLat: rlat,
          rightLong: rlong,
          campaignId: campaignId,
          locale: homeStateLocale,
          context: typeSection,
          requestId: flagCall
        },
        dataType: "xml",
        async: true,
        success : function(data) {
           	//rimuovo il div contenente l'errore se c'e'. c'e' un for poiche' possono partire 2 richieste che restituiscono NO dealer found e lo scrivono 2 volte
        	//es: clicco su find 1° richiesta ... puo' scattare nel caso cambi il livello di zoom una 2° richiesta. Inserito for max 5 richieste.
        for (var i=0;i<5 && $("#overlayError"+idTabMap)!=null;i++){
        	  $("#overlayError"+idTabMap).remove();
        }
       	//alert(call_ws+"flag"+flagCall);
        	 createMarkers(data,flagCall);
        },
        error: function(xhr, ajaxOptions, thrownError){
       	 createMarkers(null,flagCall);
        }   
      });	
   	
}
//FUNZIONE CHE CREA I MARKER RICHIAMATA DA createMarkers
function createMarker(latlng, imgMarker){
	 return new google.maps.Marker({
        position: latlng,
        map:  map[actuallyMap].map,
        icon:imgMarker
    });
	
}

//ERRORI NELLA GEOCODIFICA
function errorGeocoder(statusPas){
	 // status=google.maps.GeocoderStatus.INVALID_REQUEST;
	  var labelGeocoderError="";
		 switch(statusPas){
		 case google.maps.GeocoderStatus.ZERO_RESULTS: labelGeocoderError=google.maps.GeocoderStatus.ZERO_RESULTS; break;
		 case google.maps.GeocoderStatus.OVER_QUERY_LIMIT: labelGeocoderError=google.maps.GeocoderStatus.OVER_QUERY_LIMIT; break;
		 case google.maps.GeocoderStatus.REQUEST_DENIED: labelGeocoderError=google.maps.GeocoderStatus.REQUEST_DENIED; break;
		 case google.maps.GeocoderStatus.INVALID_REQUEST: labelGeocoderError=google.maps.GeocoderStatus.INVALID_REQUEST;
		 }
    //rimuovo il div contenente l'errore se c'e'. c'e' un for poiche' possono partire 2 richieste che restituiscono NO dealer found e lo scrivono 2 volte
    //es: clicco su find 1° richiesta ... puo' scattare nel caso cambi il livello di zoom una 2° richiesta. Inserito for max 5 richieste.
     for (var i=0;i<5 && $("#overlayError"+idTabMap)!=null;i++){
     	  $("#overlayError"+idTabMap).remove();
     }
	  overlay = new USGSOverlay(map[actuallyMap].map.getBounds(), labelGeocoderError, map[actuallyMap].map,"");
}
    


function createMarkers(xmldoc1,requestId){
		var dealer;
		var response;
		var responseId=0;
		
		if (xmldoc1 != null) {
			
			xmlDoc = xmldoc1;
			response=xmlDoc.documentElement.getElementsByTagName("flag");
			for( var x = 0; response && response.length>0 && x < response[0].attributes.length; x++ ) {
				if(response[0].attributes[x].nodeName== 'responseId') responseId = response[0].attributes[x].nodeValue;
			}
			dealer = xmlDoc.documentElement.getElementsByTagName("dealer");
		}	
		//alert(map[actuallyMap].map.getZoom()+"livello zoom");
		 if (dealer && dealer.length>0 ) {
			//alert(dealer.length);
    		if(responseId==requestId){
     		var ginfo=[];
     		for (var i = 0; i < dealer.length; i++){
    	    
    	    var name = dealer[i].getElementsByTagName("name")[0].firstChild.nodeValue;	
     	    var lat_marker = parseFloat(dealer[i].getElementsByTagName("lat")[0].firstChild.nodeValue);
    	    var lng_marker = parseFloat(dealer[i].getElementsByTagName("lng")[0].firstChild.nodeValue);
    	    
    	    
    	    //CERCO NELL'ARRAY DEI DEALER  IL DEALER 'i'. SE E' PRESENTE SIGNIFICA CHE IL MARKER E' NELLA MAPPA E QUINDI NON LO AGGIUNGO E 
    	    // SALTO AL PROSSIMO ELEMENTO DEL FOR
     	    if (findMarker(name,lat_marker,lng_marker)){
    	     	//alert("salto:"+i);
    	    	continue;
    	    }
    	    
    	    //alert("non salto:"+i);
			var address=getNodeValue(dealer[i].getElementsByTagName("address")[0]);			
			var city=getNodeValue(dealer[i].getElementsByTagName("city")[0]);
			var cap=getNodeValue(dealer[i].getElementsByTagName("postal_code")[0]);
			var tel1=getNodeValue(dealer[i].getElementsByTagName("tel1")[0]);		
			
			var tel2=getNodeValue(dealer[i].getElementsByTagName("tel2")[0]);
			var email=getNodeValue(dealer[i].getElementsByTagName("email")[0]);
			var url=getNodeValue(dealer[i].getElementsByTagName("url")[0]);
			var fax=getNodeValue(dealer[i].getElementsByTagName("fax")[0]);
			var id=getNodeValue(dealer[i].getElementsByTagName("id")[0]);
			
			//Aggiunti ora//
			 var img1="";
			 var img2="";
			 var img3="";
			 var img4="";
			 if(dealer[i].getElementsByTagName("image1")[0].firstChild!=null)
			  img1=dealer[i].getElementsByTagName("image1")[0].firstChild.nodeValue;
			 if(dealer[i].getElementsByTagName("image2")[0].firstChild!=null)
			  img2=dealer[i].getElementsByTagName("image2")[0].firstChild.nodeValue;
			 if(dealer[i].getElementsByTagName("image3")[0].firstChild!=null)
			  img3=dealer[i].getElementsByTagName("image3")[0].firstChild.nodeValue;
			 if(dealer[i].getElementsByTagName("image4")[0].firstChild!=null)
			  img4=dealer[i].getElementsByTagName("image4")[0].firstChild.nodeValue;
			 var markerNode=dealer[i].getElementsByTagName("marker")[0];
			 
			 var loc_imagePath1 = "";
			 var loc_imagePath2 = "";
			 var loc_printImage = "";
			 var loc_mozPrintImage = "";
			 var loc_shadow = "";
			 var loc_imageMap = "";
			 var loc_iconSize = "";
			 var log_shadowSize = "";
			 var loc_iconAnchor = "";
			 var loc_infoWindowAnchor = "";
			
	
			 /*read the attributes of the marker node*/
			 for( var x = 0; x < markerNode.attributes.length; x++ ) {
			 if(markerNode.attributes[x].nodeName == 'imagePath1') loc_imagePath1 = markerNode.attributes[x].nodeValue;
			 imagePath1 = loc_imagePath1;
			 if(markerNode.attributes[x].nodeName == 'imagePath2') loc_imagePath2 = markerNode.attributes[x].nodeValue;
			 imagePath2 = loc_imagePath2;
			 if(markerNode.attributes[x].nodeName == 'printImagePath') loc_printImage = markerNode.attributes[x].nodeValue;
			 if(markerNode.attributes[x].nodeName == 'mozPrintImagePath') loc_mozPrintImage = markerNode.attributes[x].nodeValue;
			 if(markerNode.attributes[x].nodeName == 'shadowImagePath') loc_shadow = markerNode.attributes[x].nodeValue;
			 if(markerNode.attributes[x].nodeName == 'imageMap') loc_imageMap = markerNode.attributes[x].nodeValue;
			 if(markerNode.attributes[x].nodeName == 'imageSize') loc_iconSize = markerNode.attributes[x].nodeValue;
			 if(markerNode.attributes[x].nodeName == 'shadowImageSize') log_shadowSize = markerNode.attributes[x].nodeValue;
			 if(markerNode.attributes[x].nodeName == 'iconAnchor') loc_iconAnchor = markerNode.attributes[x].nodeValue;
			 if(markerNode.attributes[x].nodeName == 'windowAnchor') loc_infoWindowAnchor = markerNode.attributes[x].nodeValue;
			 }
			 if(infowindow[actuallyMap]==undefined){
		   		     infowindow[actuallyMap]=new Array();
		   	 }

			 var idDivTab=infowindow[actuallyMap].length;
			
			 ginfo[i]="";
			 if (img1!='' || img2!='' || img3!='' || img4!=''){
			    ginfo[i]+="<div id='contenitore"+actuallyMap+""+idDivTab+"' class='map-info-window' style='width:400px;height:118px;clear:both;'>";
			 }
			 else{
				 ginfo[i]+="<div   id='contenitore"+actuallyMap+""+idDivTab+"'  style='width:320px;height:118px;clear:both;'>";
			 }
			//ginfo[i]+="<ul style = 'list-style: none; float: left; padding-bottom : 15px;'><li><strong>"+name+"</strong></li></ul>
			 ginfo[i]+="<div id='content"+actuallyMap+""+idDivTab+"' style ='display:block;clear:both;'><ul style = 'list-style: none; float: left; padding-bottom : 20px;'><li style='display : inline; float: left;  padding-right : 10px;'>";
						
				ginfo[i]+="<strong>"+name+"</strong><br/>";
				if (url==''){
					ginfo[i]+="<br/>";
				}
				ginfo[i]+=address; //+"<div style='float: right;'>"+ html1Img+html2Img+"</div>";
				ginfo[i]+="<br/>"+cap+" "+city;
				if (tel1!=''){
					ginfo[i]+="<br/>"+label_dealers_phoneNumber + " " + tel1;
				}
				if (tel2!=''){
					ginfo[i]+=" - "+tel2;
				}
				if (fax!=''){
					ginfo[i]+="<br/>"+label_dealers_faxNumber+ " " +fax;			
				}
				if (email!=''){
					ginfo[i]+="<br/>"+label_dealers_email+" <a class ='linkGrigio10' href='mailto:"+email+"'>"+email+"</a>";	
				}
				if (url!=''){
					ginfo[i]+="<br/>"+label_dealers_url+" <a class ='linkGrigio10' href='http://"+url+"' target='_blank'>"+url+"</a>";	
				}
				ginfo[i]+="<br/><br/><a class ='linkGrigio10' href='javascript:void(0);' onclick='hideDivBaloon("+idDivTab+");return false;'>"+label_gmap_direction+"</a>";	
				ginfo[i]+="</li>"; 
				/*
				 * questo pezzo serve per caricare le immagini che identificano il tipo di dealer
				*/
				var imgCostruito="/docroot/tyre/"+homeSiteLocale+"/img/dealer/";
				var pdTop=10;
				
				if (img1!='' || img2!='' || img3!='' || img4!=''){
					
					if (url==''){
					
						pdTop=30;
					}
					 if (img2!='' || img3!='' || img4!=''){
						 if (img3!='' || img4!=''){
							 if (img4!=''){
								 ginfo[i]+="<li style='display : inline; float: left;  padding-top :"+pdTop+"px;'><ul><li><img border='0' src='"+imgCostruito+img3+"'/></li><li><img border='0' src='"+imgCostruito+img4+"'/></li></ul></li>";
							 } else {
								 ginfo[i]+="<li style='display : inline; float: left;  padding-top :"+pdTop+"px;'><img border='0' src='"+imgCostruito+img3+"' /></li>";
							 }
							 ginfo[i]+="<li style='display : inline; float: left;   padding-top :"+pdTop+"px;'><ul><li><img border='0' src='"+imgCostruito+img1+"'/></li><li><img border='0' src='"+imgCostruito+img2+"'/></li></ul></li>";
						  }else{
							
						 	ginfo[i]+="<li style='display : inline; float: left;   padding-top :"+pdTop+"px;'><ul><li><img border='0' src='"+imgCostruito+img1+"'/></li><li><img border='0' src='"+imgCostruito+img2+"'/></li></ul></li>";
						  }
						  
					 } else {
						 
						 //var imgCostruito="/docroot/tyre/"+homeSiteLocale+"/img/dealer/"+img1;
						 ginfo[i]+="<li style='display : inline; float: left;   padding-top :"+pdTop+"px;'><ul><li><img border='0' src='"+imgCostruito+img1+"' /></li><li><img width='1px' height='1px' border='0' src='/docroot/tyre/common/gfx/1x1.gif'/></li></ul></li>";
					 }
				 } 

					 ginfo[i]+="&nbsp;";
					 ginfo[i]+="</ul>";
					 ginfo[i]+="</div>";
				 
					 ginfo[i]+="<div id='direction"+actuallyMap+""+idDivTab+"' style='display:none;clear:both;'>";
					 ginfo[i]+=createDirectionTab(label_gmap_address_from,label_gmap_calculate,"'" + lat_marker + "'","'" + lng_marker + "'");
					 ginfo[i]+="</div>";	 

				
				 ginfo[i]+="</div>";
				 ginfo[i]+="&nbsp;";
				 ginfo[i]+="&nbsp;";
				
			//alert("sto per creare un marker");
			latlng_marker = new google.maps.LatLng(lat_marker, lng_marker);
			var markerImage = new google.maps.MarkerImage(pathimages+loc_imagePath1);
			var markerNew=createMarker(latlng_marker,markerImage);

			attachHtml(markerNew,ginfo[i],infowindow[actuallyMap].length,actuallyMap,idDivTab);
			//INSERISCO NELL'ARRAY DEI DEALER IL NOME,LATITUDINE,LONGITUDINE E MARKER ED INCREMENTO UNA VARIABILE INDICE
			 //alert("indexLastDealers:"+indexLastDealers);
			 lastDealers[actuallyMap][indexLastDealers]=new Array(name,lat_marker,lng_marker,markerNew);
			 indexLastDealers++;
					
		}// end for
	
	}
		 }
	else {
		  overlay = new USGSOverlay(map[actuallyMap].map.getBounds(), label_gmap_nodealer, map[actuallyMap].map,"");
		}

	
}

//INSERISCE L'HTML DENTRO IL BALOON
function attachHtml(marker, html,nEl,mapIdNow,idDivTabNow) {
	     var cnHide="#contenitore"+mapIdNow+""+idDivTabNow;
	     infowindow[actuallyMap][nEl] = new google.maps.InfoWindow({ content: html});
    	 google.maps.event.addListener(marker, 'click', function() {
		 if(lastMapMarkerOpen[actuallyMap]){
		      lastMapMarkerOpen[actuallyMap].close();
		}
	    infowindow[actuallyMap][nEl].open(map[actuallyMap].map,marker);
//	    alert("test2"+cnHide+"scont"+$(cnHide).parent().attr("style"));
//	    alert("test3"+cnHide+"scont"+$(cnHide).parent().parent().attr("style"));
//	    $(cnHide).parent().parent().css('overflow','hidden');
	  
	    setTimeout("msg('"+cnHide+"')",150);
	    lastMapMarkerOpen[actuallyMap]=infowindow[actuallyMap][nEl];
	  });
}
// FUNCTION CHE GESTISCE NEL BALOON LA COMPARSA DELLE INFO O DELLA DIRECTION
function hideDivBaloon(id) {
	id=actuallyMap+""+id;
	var cHide="#content"+id;
	var dHide="#direction"+id;
	var cnHide="#contenitore"+id;
	$(cnHide).parent().css('overflow','hidden');
    $(cHide).attr('style','display:none;clear:both;');
    $(dHide).attr('style','display:block;clear:both;');
}

function msg(cnHideP){
	$(cnHideP).parent().css('overflow','hidden');
	$(cnHideP).parent().parent().css('overflow','hidden');
}



//ESTRAPOLA DALL'XML GLI ATTRIBUTI DEL DEALER
function getNodeValue(element) {
	var value = "";
	if ((element != null) && (element.firstChild != null)) {
		value = element.firstChild.nodeValue;
	}
	return value;
} 


//CONTROLLA SE IL MARKER DEL DEALER E' GIA' SULLA MAPPA E RESITUISCE TRUE O FALSE
function findMarker(passName,passLat_marker,passLng_marker){
	varParamReturn=false;
//	alert("findMarkerlastDealers[actuallyMap]"+lastDealers[actuallyMap]);
	for (var j = 0; lastDealers.length!=0 && lastDealers[actuallyMap]!=undefined && j < lastDealers[actuallyMap].length; j++){
	
		if(lastDealers[actuallyMap][j][0] == passName)	{
		if(lastDealers[actuallyMap][j][1] == passLat_marker){	
			if(lastDealers[actuallyMap][j][2] == passLng_marker){
				//alert("find dealer already present:"+passName);
				varParamReturn=true;
				break;
			}
	    }
		}
	
	}
	return varParamReturn;	
}

// Deletes all markers in the array by removing references to them
function deleteOverlaysMarkers() {
	if(lastDealers[actuallyMap]!=undefined){
	
  if (lastDealers[actuallyMap]) {
	for (indexM in lastDealers[actuallyMap]) {
        	lastDealers[actuallyMap][indexM][3].setMap(null);
    }
    lastDealers[actuallyMap].length = 0;
    // AZZERO LA VARIABILE INDICE DELL'ARRAY DI DEALER
    indexLastDealers=0;
	//alert("elementi dopo nell'array:"+lastDealers[actuallyMap].length);
  }
	}
}
// DISEGNA L'HTML PER INSERIRE L'INDIRIZZO DI PARTENZA
function createDirectionTab(addressString, bottonString, latitudine, longitudine) {
     var htmlText = "<table cellpadding=\"2\" cellspacing=\"2\" border=\"0\" >";
	 var fromAddr = getCookie('_gmap_dl_fromAddr');
	 //row 1
	 htmlText += "<tr>";
	 htmlText += "<td>" + addressString + "</td>";
	 htmlText += "</tr>";
	 //row 2
	 htmlText += "<tr>";
	 htmlText += "<td><input type=\"text\" value=\""+fromAddr+"\" class=\"input-tab-direction\" size=\"60\" id=\"address_from\" name=\"address_from\"></td>";
	 htmlText += "</tr>";
	 //row 3
	 htmlText += "<tr>";
	 htmlText += "<td align=\"right\"><a href='#' onclick=\"javascript:getDirection(" + latitudine + "," + longitudine + ");return false;\">" + bottonString + "&gt;</a></td>";
	 htmlText += "</tr>";
	 htmlText += "</table>";
	 return htmlText;
	
	} 
// restituisce il valore del cookie sNome
 function getCookie(sNome) {
 // genera un array di coppie "Nome = Valore"
 // NOTA: i cookies sono separati da ';'
 var asCookies = document.cookie.split("; ");
 // ciclo su tutti i cookies
 for (var iCnt = 0; iCnt < asCookies.length; iCnt++)
 {
 // leggo singolo cookie "Nome = Valore"
 var asCookie = asCookies[iCnt].split("=");
 if (sNome == asCookie[0]) {
 return (unescape(asCookie[1]));
 }
 }

 // SE non esiste il cookie richiesto
 return("");
 }

 // SETTA IL COOKIE PER MANTENERE LA DIREZIONE
 function setCookie(sNome, sValore, iGiorni) {
	 if(iGiorni!='') {
	 var dtOggi = new Date()
	 var dtExpires = new Date()
	 dtExpires.setTime
	 (dtOggi.getTime() + 24 * iGiorni * 3600000)
	 document.cookie = sNome + "=" + escape(sValore) +
	 "; expires=" + dtExpires.toGMTString();
	 }
	 else {
	 document.cookie = sNome + "=" + escape(sValore);
	 }
	 
} 
 
 
 // rimuove un cookie
 function delCookie(sNome) {
 setCookie(sNome, "","");
 } 
 
 function setGeolocalizedFlag(flag){
	
	 isGeolocalized=flag;
 }
 function getDirection(latitudine, longitudine) {
	  var startGeopoint = arrayFormDirection[idTabMap].address_from.value;
	  arrayFormDirection[idTabMap].myAddressFrom.value = startGeopoint;
	  if(startGeopoint==null||startGeopoint=='') {
	  return;
	  }
	  //Reimposto il livello min di zoom nel caso in cui il percorso sia troppo lungo
	  //e la mappa non riesca a visualizzare tutta la strada.
	  var minZoomSetted=label_gmap_map_minresolution;
	  label_gmap_map_minresolution=label_gmap_map_minresolution_default;
	  map[actuallyMap].map = createDynamicMap(new google.maps.LatLng(latitudine, longitudine));
	  label_gmap_map_minresolution=minZoomSetted;
	 
	  directionsRendererArray[actuallyMap]=new google.maps.DirectionsRenderer({ map: map[actuallyMap].map }); 
	  // Convert the distance to box around the route from miles to km
      //distance = parseFloat(document.getElementById("distance").value) * 1.609344;
	  
      var directionLatLng = new google.maps.LatLng(latitudine, longitudine);
     
     var request = {
       origin: startGeopoint,
       destination: directionLatLng,
       travelMode: google.maps.DirectionsTravelMode.DRIVING
     }
      directionsRendererArray[actuallyMap].setPanel(document.getElementById("streetDirection"+idTabMap));
     // Make the directions request
      directionService.route(request, function(result, status) {
       if (status == google.maps.DirectionsStatus.OK) {
     	   flagChangeBoundFalse[actuallyMap]=false;  
    	   if(lastMapMarkerOpen[actuallyMap]){
          	
  		      lastMapMarkerOpen[actuallyMap].close();
  		 }
         
           deleteOverlaysMarkers();
    	   directionsRendererArray[actuallyMap].setDirections(result);
        } else {
         alert(msg_direction_failed + status);
       }
     });
	  setCookie('_gmap_dl_fromAddr',startGeopoint,'');
	 } 
 
 //Queste due funzioni servono nel caso in cui ci sia la tendina con le nazioni.
 //setCountryCodeFromSelect setta la countryCode con la country selezionata nella tendina e prende la lista dei campaignId inseriti da dialogo in ordine
 // di tab e separati da |
 function setCountryCodeFromSelect(param){
	 if(param.val()!=undefined){
		var campaignGridIndex=0;
		var paramSplitted=param.val().split("-");
		countryCode=paramSplitted[0];
		var  campaignSplitted=paramSplitted[1].split("|");
		//alert("idTabMap"+idTabMap);
		if(idTabMap>0)
		   campaignGridIndex=idTabMap-1;
		campaignId=campaignSplitted[campaignGridIndex];
		//alert(campaignGridIndex+"cmapagna"+campaignId);
	 }
 }
 //clearParamForCountryCodeFromSelect chiama setCountryCodeFromSelect ed in piu' pulisce le variabili latitudine e longitudine
 function clearParamForCountryCodeFromSelect(parameter){
	 setCountryCodeFromSelect(parameter);
	 if(parameter.val()!=undefined){
	 lat="";
	 lng="";
	 }
 }

 
  function USGSOverlay(boundsPassato, labelPassata, mapPassata,background) {
				      // Now initialize all properties.
					    this.bounds_ = boundsPassato;
					    this.label = labelPassata;
					    this.map_ = mapPassata;
				        this.background_=background;
					    // We define a property to hold the image's div. We'll 
					    // actually create this div upon receipt of the onAdd() 
					    // method so we'll leave it null for now.
					    this.div_ = null;
				        // alert("this.setMap(map);");
					    // Explicitly call setMap on this overlay
					    this.setMap(mapPassata);
					    //alert("fine");
	  }


	  
	 USGSOverlay.prototype.onAdd = function() {
	   		            
 	   		    	    // Note: an overlay's receipt of onAdd() indicates that
	   		    	    // the map's panes are now available for attaching
	   		    	    // the overlay to the map via the DOM.

	   		    	    // Create the DIV and set some basic attributes.
	   		    	    var div = document.createElement('DIV');
	   		    	    div.style.borderStyle = "none";
	   		    	    div.style.borderWidth = "0px";
	   		    	    div.style.paddingLeft = "150px";
	   		    	    div.style.paddingTop = "15px";
	   		    	    div.style.position = "absolute";
	   		    	    div.id = "overlayError"+idTabMap;

	   		    	    var htmlNoDealers = document.createElement("P"); 
	   		    	    htmlNoDealers.align="center";
	   		    	    
	   		    	    htmlNoDealers.style.fontSize="20px";
	   		    	    
	   		    	    var text = document.createTextNode(this.label);
	   		    	    htmlNoDealers.appendChild(text);
						//var img = document.createElement("img");
						//img.src = "http://gmaps-samples.googlecode.com/svn/trunk/markers/circular/bluecirclemarker.png";
						//img.style.width = "100%";
						//img.style.height = "100%";
						//div.appendChild(img);
	   		              div.appendChild(htmlNoDealers);
	   		    	    // Set the overlay's div_ property to this DIV
       	   		    	 this.div_ = div;
	   		    	
	   		    	    // We add an overlay to a map via one of the map's panes.
	   		    	    // We'll add this overlay to the overlayImage pane.
	   		    	    var panes = this.getPanes();
	   		    	    panes.overlayLayer.appendChild(div);
	   		    	    
	   		    	  }
	   	
	  USGSOverlay.prototype.draw = function() {

	    	    // Size and position the overlay. We use a southwest and northeast
	    	    // position of the overlay to peg it to the correct position and size.
	    	    // We need to retrieve the projection from this overlay to do this.
	    	    var overlayProjection = this.getProjection();

	    	    // Retrieve the southwest and northeast coordinates of this overlay
	    	    // in latlngs and convert them to pixels coordinates.
	    	    // We'll use these coordinates to resize the DIV.
	    	    var sw = overlayProjection.fromLatLngToDivPixel(this.bounds_.getSouthWest());
	    	    var ne = overlayProjection.fromLatLngToDivPixel(this.bounds_.getNorthEast());

	    	    // Resize the image's DIV to fit the indicated dimensions.
	    	    var div = this.div_;
	    	    div.style.left = sw.x + 'px';
	    	    div.style.top = ne.y + 'px';
	    	    div.style.width = (ne.x - sw.x) + 'px';
	    	    div.style.height = (sw.y - ne.y) + 'px';
	    	    if(this.background_!="")
	    	      div.style.background = this.background_;
	    	  }


	  USGSOverlay.prototype.onRemove = function() {
	    this.div_.parentNode.removeChild(this.div_);
	    this.div_ = null;
	  }

