var license = "72652e7265706c61742e636f6d-4d454e3457454220532e722e6c-1869f-132915f-7374616e64617264-0";
var key = "ABQIAAAAUFrppv2oMiwmfR8jhoAHFRQCecenUwhGiRVk6bsTp8zLS8a7BRQQ9NXNSf0cGXW3xhh7-hbVXQ6w9Q";

if (document.domain == "re.replat.com") {
  key = "ABQIAAAABC8SCe9lvkf858krcc4S7BSTs5ulkBctK4Mc8QwIgXsf9NhW4BRRXomzcDNmEkzNYeUJFc1mdXseVw";
}else if (document.domain == "re.replat-test.com") {
  key = "ABQIAAAABC8SCe9lvkf858krcc4S7BTZ3PfdOu3ajwZ3fRmOXxNECPDN1hT2PSyiMBeIuJhDPY2OJgVAbsTlxQ";
  license = "72652e7265706c61742d746573742e636f6d-4d454e3457454220532e722e6c-1869f-132915f-7374616e64617264-0";
}else if (document.domain == "my.frimmoney.com"){
  var key = "ABQIAAAABC8SCe9lvkf858krcc4S7BQ4VvFLGUqiVOgdtzmS8oWhTePSFxQOkAJKfBFILrANoZidwQb1M1BOAQ";
  var license = "6d792e6672696d6d6f6e65792e636f6d-4d454e3457454220532e722e6c-1869f-132b86f-7374616e64617264-0";
}else if (document.domain == "www.frimmoney-test.com") {
  key = "ABQIAAAABC8SCe9lvkf858krcc4S7BSi_F2MWRXMa0R2oBR_N7OQNpXN8RSwuEXppNNTgDfySZSwX5dwgVD86g";
  license = "6672696d6d6f6e65792d746573742e636f6d-4d454e3457454220532e722e6c-1869f-132b86f-7374616e64617264-0";
}else if (document.domain == "my.frimm.com") {
  key = "ABQIAAAABC8SCe9lvkf858krcc4S7BSuRnfO459tpC3Zxesvtk4KePaGWRRpROTCdfL0Y02pBEMiKT5BceEZ4Q";
  license = "6d792e6672696d6d2e636f6d-4d454e3457454220532e722e6c-1869f-132b86f-7374616e64617264-0";
}else if (document.domain == "my.replat.com") {
  key = "ABQIAAAABC8SCe9lvkf858krcc4S7BSUQZB-DWfmyRcafQunI8DOsmt9gBRXsJFb7OV7o488oOI9QZTZSxv4fA";
  license = "6d792e7265706c61742e636f6d-4d454e3457454220532e722e6c-1869f-132df7f-7374616e64617264-0";
}else if (document.domain == "www.frimm.com") {
  key = "ABQIAAAABC8SCe9lvkf858krcc4S7BRVZ3aY5ikUcUw-R44vt0HfBInYWhT-g9EX5TCcBe8rOSZm9yCsErTYKQ";
  license = "6672696d6d2e636f6d-4d454e3457454220532e722e6c-1869f-132df7f-7374616e64617264-0";
}else if (document.domain == "valucasa.frimm.com") {
  key = "ABQIAAAA8lfEQl_oy8Fqhi4aezRLrxSuRnfO459tpC3Zxesvtk4KePaGWRS9-V4OTqfRcs6nl8qVkb9NNcMcWg";
  license = "76616c75636173612e6672696d6d2e636f6d-4d454e3457454220532e722e6c-1869f-133068f-7374616e64617264-0";
}else if (document.domain == "www.valucasa.it") {
  key = "ABQIAAAA8lfEQl_oy8Fqhi4aezRLrxRGefOL5e1BHB6DvVuTVtULhwpC6RT81SyRmbQvKG_kUsoRYNt_g9GURQ";
  license = "76616c75636173612e6974-4d454e3457454220532e722e6c-1869f-1332953-7374616e64617264-0";
}else if (document.domain == "www.valucasa.com") {
  key = "ABQIAAAA8lfEQl_oy8Fqhi4aezRLrxRGoWYwedrBDwwjqNrvqavjRPnUXhQ2A_nnDMxDmaacAGOu68DG5f8hSw";
  license = "76616c75636173612e636f6d-4d454e3457454220532e722e6c-1869f-1332953-7374616e64617264-0";
}

document.write('<script src="http://maps.google.com/maps?file=api&v=2&key=' + key + '" type="text/javascript"></script>');

//creo l'array che contiene gli oggetti circle
array_circle = new Array();

// gestiore della mappa
var GCodeMap = null;    //vecchio _gcodemap

// semaforo per la gestione delle request multiple
var KeystrokeCount = 0;   //vecchio _keystrokeCount
// contiene l'ultimo indirizzo ricercato su mappa
var LastAddressSearch = "";   //vecchio _lastAddressSearch

// dettagli indirizzo al momento visibile su mappa
var GeoLocationOnMap = null;    //vecchio _geoLocationOnMap
// coordinate geografiche del punto su mappa
var PointOnMap = null;
// numero di cerchi disegnati su mappa
var NCircleOnMap = 0;

// form per effettuare la ricerca di un indirizzo 
//var FormStreet = null;
// form per disegnare un cerchio date le coordinate 
var FormCircle = null;
// form per assegnare il numero massimo di cerchi su mappa 
var FormLimitCircle = null;
 
// contenitore delle opzioni per interagire con la mappa
var HTMLOptions = null;
// contenitore della risposta della ricerca di un indirizzo
var HTMLSuggestionText = null;    //vecchio _suggest

// input per ricercare da un indirizzo
var geo_input = null;


function setMapLang(lang1) {
  maplang=lang1;
}


/**
 * caricamento pagina
 */
function loadPage(ac_type) {

  // creazione della mappa
	GCodeMap = new GeoCoderMap("map", license);

	// Enables double click to zoom in and out (disabled by default). 
	GCodeMap.enableDoubleClickZoom();
	// Enables zooming using a mouse's scroll wheel. Note: scroll wheel zoom is disabled by default.
	GCodeMap.enableScrollWheelZoom();

	// Creates a control with buttons to pan in four directions, and zoom in and zoom out.
	GCodeMap.addSmallMapControl();
	// Creates a control with buttons to pan in four directions, and zoom in and zoom out, and a zoom slider.
	// GCodeMap.addLargeMapControl();
	// Creates a control with buttons to zoom in and zoom out.
	// GCodeMap.addSmallZoomControl();
	// Creates a control that displays the map scale.
	// GCodeMap.addScaleControl();
	// Creates a standard map type control for selecting and switching between supported map types via buttons.
	// GCodeMap.addMapTypeControl();
	// Creates a drop-down map type control for switching between supported map types.
	 GCodeMap.addMenuMapTypeControl();
	// Creates a "nested" map type control for selecting and switching between supported map types via buttons and nested checkboxes.
	// GCodeMap.addHierarchicalMapTypeControl();
	// Creates a collapsible overview mini-map in the corner of the main map for reference location and navigation (through dragging).
	//GCodeMap.addOverviewMapControl();
	
	// gestione suggest
	HTMLSuggestionText = document.getElementById("suggestionText");
	//HTMLOptions = document.getElementById("options");
	//HTMLOptions = document.getElementById("map_range_1");
	//DA RIVEDERE//
	HTMLOptions = document.getElementById("geo_input");
	
	_suggestionDragging = document.getElementById("suggestionDragging");
	/*_suggestionDragging.style.display = "none";*/
	
	// gestione ricerca indirizzo
	geo_input = document.getElementById('geo_input');
	
	// eseguo la localizzazione ad ogni digitazione
  //q.onkeyup = q.onchange = function(event){updateAddress(event)};
  
  // eseguo la localizzazione solo alla fine
  //q.onblur = function(event){updateAddress(event)};

	// a questo punto la mappa e' visualizzata e
	// possiamo mostrare il form di inserimento indirizzo
	// geo_search e' l'id della tabella che lo racchiude
	
  //drawCircleScript

	//limitCircleScript

  //removeAllCircleScript
	
	//parseAddressDetailsScript

	//XmlDataScript

	//StreetScript

  //DelInfoMapScript
    if(ac_type!='search'){
   document.getElementById('geo_search').style.visibility='visible';
   document.getElementById('geo_search').style.display='inline';
     } 
  //bisogna trovare il modo per passargli rows_id come parametro (solo dei geo_input valorizzati)
	/*if (ac_type=='mod') {
	 //enableDragging();
    for (var rows_id = 1; rows_id <= 3; rows_id++) {
      if(document.getElementById('geo_input_'+rows_id).value!=''){
        drawCircleMod(rows_id);
      }else{
        document.getElementById('map_range_'+rows_id).value='---';
      }
      geo_input = document.getElementById('geo_input_'+rows_id).value;
    }
  }*/
	
}

function loadPageReq(ac_type) {

  // numero di cerchi disegnati su mappa
  //lo risetto ancora perche se non ricarico page_tfb la variabile non si resetta mai
  NCircleOnMap = 0;

  // creazione della mappa
	GCodeMap = new GeoCoderMap("map", license);

	// Enables double click to zoom in and out (disabled by default).
	GCodeMap.enableDoubleClickZoom();
	// Enables zooming using a mouse's scroll wheel. Note: scroll wheel zoom is disabled by default.
	GCodeMap.enableScrollWheelZoom();

	// Creates a control with buttons to pan in four directions, and zoom in and zoom out.
	GCodeMap.addSmallMapControl();
	// Creates a control with buttons to pan in four directions, and zoom in and zoom out, and a zoom slider.
	// GCodeMap.addLargeMapControl();
	// Creates a control with buttons to zoom in and zoom out.
	// GCodeMap.addSmallZoomControl();
	// Creates a control that displays the map scale.
	// GCodeMap.addScaleControl();
	// Creates a standard map type control for selecting and switching between supported map types via buttons.
	// GCodeMap.addMapTypeControl();
	// Creates a drop-down map type control for switching between supported map types.
	 GCodeMap.addMenuMapTypeControl();
	// Creates a "nested" map type control for selecting and switching between supported map types via buttons and nested checkboxes.
	// GCodeMap.addHierarchicalMapTypeControl();
	// Creates a collapsible overview mini-map in the corner of the main map for reference location and navigation (through dragging).
	//GCodeMap.addOverviewMapControl();

	// gestione suggest
	HTMLSuggestionText = document.getElementById("suggestionText");
	//HTMLOptions = document.getElementById("options");
	HTMLOptions = document.getElementById("map_range_1");

	_suggestionDragging = document.getElementById("suggestionDragging");
	/*_suggestionDragging.style.display = "none";*/

	// gestione ricerca indirizzo
	geo_input = document.getElementById('geo_input_1');

	// eseguo la localizzazione ad ogni digitazione
  //q.onkeyup = q.onchange = function(event){updateAddress(event)};

  // eseguo la localizzazione solo alla fine
  //q.onblur = function(event){updateAddress(event)};

	// a questo punto la mappa e' visualizzata e
	// possiamo mostrare il form di inserimento indirizzo
	// geo_search e' l'id della tabella che lo racchiude

  //drawCircleScript

	//limitCircleScript

  //removeAllCircleScript

	//parseAddressDetailsScript

	//XmlDataScript

	//StreetScript

  //DelInfoMapScript

   document.getElementById('geo_search').style.visibility='visible';
   document.getElementById('geo_search').style.display='inline';

  //bisogna trovare il modo per passargli rows_id come parametro (solo dei geo_input valorizzati)
	if (ac_type=='mod') {
	 //enableDragging();
    for (var rows_id = 1; rows_id <= 3; rows_id++) {
      if(document.getElementById('geo_input_'+rows_id).value!=''){
        drawCircleMod(rows_id);
      }else{
        document.getElementById('map_range_'+rows_id).value='---';
      }
      //geo_input = document.getElementById('geo_input_'+rows_id).value;
    }
  }

}

//funzione per visualizzare la mappa nella view
function loadPageView(div_name) {

  // creazione della mappa
  GCodeMap = new GeoCoderMap(div_name, license);

  // Enables double click to zoom in and out (disabled by default).
  GCodeMap.enableDoubleClickZoom();
  // Enables zooming using a mouse's scroll wheel. Note: scroll wheel zoom is disabled by default.
  GCodeMap.enableScrollWheelZoom();
  // Creates a control with buttons to pan in four directions, and zoom in and zoom out.
  GCodeMap.addSmallMapControl();
  // Creates a control with buttons to pan in four directions, and zoom in and zoom out, and a zoom slider.
  // _gcodemap.addLargeMapControl();
  // Creates a control with buttons to zoom in and zoom out.
  // _gcodemap.addSmallZoomControl();
  // Creates a control that displays the map scale.
  // _gcodemap.addScaleControl();
  // Creates a standard map type control for selecting and switching between supported map types via buttons.
  // _gcodemap.addMapTypeControl();
  // Creates a drop-down map type control for switching between supported map types.
   GCodeMap.addMenuMapTypeControl();
  // Creates a "nested" map type control for selecting and switching between supported map types via buttons and nested checkboxes.
  // _gcodemap.addHierarchicalMapTypeControl();
  // Creates a collapsible overview mini-map in the corner of the main map for reference location and navigation (through dragging).
  GCodeMap.addOverviewMapControl();

  var q_address=document.getElementById('complete_address').value;
  var q_lat=document.getElementById('map_lat').value;
  var q_lng=document.getElementById('map_lng').value;
  var show_pointer=document.getElementById('show_pointer').value;

  var point=new GeoPoint(q_lat,q_lng);

  if(show_pointer==1){
    viewAddress(q_lat,q_lng,q_address);
  }

  //setCenter(q_lat);
  GCodeMap.setCenter(point,14);
}

//funzione per visualizzare la mappa nella panoramica della view
function loadPageOverView(div_name) {
  // creazione della mappa
  GCodeMap = new GeoCoderMap(div_name, license);

  // Enables double click to zoom in and out (disabled by default).
  GCodeMap.enableDoubleClickZoom();
  // Enables zooming using a mouse's scroll wheel. Note: scroll wheel zoom is disabled by default.
  GCodeMap.enableScrollWheelZoom();
  // Creates a control with buttons to pan in four directions, and zoom in and zoom out.
  //_gcodemap.addSmallMapControl();
  // Creates a control with buttons to pan in four directions, and zoom in and zoom out, and a zoom slider.
  // _gcodemap.addLargeMapControl();
  // Creates a control with buttons to zoom in and zoom out.
  // _gcodemap.addSmallZoomControl();
  // Creates a control that displays the map scale.
  // _gcodemap.addScaleControl();
  // Creates a standard map type control for selecting and switching between supported map types via buttons.
  // _gcodemap.addMapTypeControl();
  // Creates a drop-down map type control for switching between supported map types.
  // _gcodemap.addMenuMapTypeControl();
  // Creates a "nested" map type control for selecting and switching between supported map types via buttons and nested checkboxes.
  // _gcodemap.addHierarchicalMapTypeControl();
  // Creates a collapsible overview mini-map in the corner of the main map for reference location and navigation (through dragging).
  //_gcodemap.addOverviewMapControl();

  // gestione suggest
  //_suggest = document.getElementById("suggest");

  var q_address=document.getElementById('complete_address').value;
  var q_lat=document.getElementById('map_lat').value;
  var q_lng=document.getElementById('map_lng').value;
  var show_pointer=document.getElementById('show_pointer').value;

  if(show_pointer==1){
    viewAddress(q_lat,q_lng,q_address);
  }else{
    var point=new GeoPoint(q_lat,q_lng);
    // ricerca indirizzo
    GCodeMap.setCenter(point,14);
  }

}


//funzione che disegna i cerchi nella modifica
function drawCircleMod(rows_id){
  updateAddressReq(null,null,rows_id);
  StreetScriptReq(rows_id);
}


function XmlDataScript(){
// gestione caricamento contenuti
	var xmldata = document.forms["xmldata"];
	document.forms["xmldata"].onsubmit = function(){
		// caricamento XML
		GCodeMap.loadXmlData(xmldata.text.value, xmldata.focus.checked);
		return false;
	};
}


function parseAddressDetailsScript(){
// gestione informazioni indirizzo
	document.forms["details"].onsubmit = function(){parseAddressDetails(0);return false;};
}
	

function limitCircleScript(){
// gestione limite cerchi su mappa
	FormLimitCircle = document.getElementById["limitcircle"];
}


function removeAllCircleScript(){
   // gestione eliminazione cerchi su mappa
	document.forms["clearcircle"].onsubmit = function(){GCodeMap.removeAllCircle();return false;};
}

function DelInfoMapScript(){
	// gestione eliminazione contenuti su mappa
	document.forms["reset"].onsubmit = function(){
		geo_input.value = "";
		HTMLSuggestionText.innerHTML = "";
		HTMLOptions.style.display = "none";
		
		// eliminiamo le infomrazioni caricate su mappa
		GCodeMap.clear();
		return false;
	};
}


function StreetScript(){
// gestione ricerca indirizzo
	geo_input = document.getElementById('geo_input').value;

	//geo_input.reset_google();
	//geo_input.onkeyup = geo_input.onchange = function(event){updateAddress(event)};
	//onsubmit = function(){updateAddressMap(KeystrokeCount);return false;};
	//dragging.onchange = function(){
	//	if (this.checked) {
			//_suggestionDragging.style.display = "";
			// abilitiamo il dragging del segnaposto
			
			//memorizzo il numero di riga in questa variabile,cosė evito il problema che rows_id venga decrementata
			//num=1;

			GCodeMap.enableDraggingAddress(function(point){
				// rispristino valori iniziali
				PointOnMap = point;
       
				// ricerca indirizzo
				GCodeMap.searchLatLng(point, function(name, response) {

					// numero di risultati prodotti dalla ricerca
					var nFound = response.length;
					
          // setto le coordinate
  				var lng = point.lng();
  				var lat = point.lat();
  				document.getElementById('map_lng').value=lng;
  				document.getElementById('map_lat').value=lat;
  				parseAddressDetails(0);
  				//reset_address();
		      //get_geo_id();
				  
					// mostriamo le opzioni
					HTMLOptions.style.display = (nFound > 0)?"":"none";

					// rispristino valori iniziali
					GeoLocationOnMap = null;

					if (nFound > 0) {
						// recupero l'indirizzo al momento visibile su mappa
						GeoLocationOnMap = response[0];

						// comunicazione messaggio utente
						var didyouHTML = "Sei in <b>" + response[0].getAddress() + "</b><br />" 
						+ "<i>Il punto su mappa dista <b>" + parseInt(point.distanceFrom( response[0].getPoint())) + " metri</b> da questo indirizzo</i><hr/>";
						
						//var didyouHTML = "Sei in <b>" + response[0].getAddress() + "</b><br />";
						
						// risultati multipli
						/*if (nFound > 1) {

							didyouHTML += "<h1>Forse cercavi:</h1>";
							
							// Loop through the results
							for (var i = 0; i < nFound; i++) {
								var location = response[i];
								didyouHTML += "<div class=\"ref\"><a href=\"javascript:placeAddress('" + encodeURIComponent(location.getAddress().replace("'", "\\'")) + "')\">" + location.getAddress() + "</a></div>";
							}
						}*/
						// comunicazione messaggio utente
						HTMLSuggestionText.innerHTML = didyouHTML;
					
					  //delCircleSingle(num);
            //document.getElementById('geo_input').value=response[0].getAddress();
            //updateAddress(null,null);
            
					}else{
						// rispristino valori iniziali
						PointOnMap = null;

						// comunicazione messaggio utente
						HTMLSuggestionText.innerHTML = "Impossibile riconoscere la localit&agrave; <b>" + name + "</b>";
					}
				});
  			
			})
			
	/*	} else {
			_suggestionDragging.style.display = "none";
			// disabilitiamo il dragging del segnaposto
			GCodeMap.disableDraggingAddress();
		}
	};*/
}

function StreetScriptReq(rows_id){
// gestione ricerca indirizzo
	geo_input = document.getElementById('geo_input_'+rows_id).value;

	//geo_input.reset_google();
	//geo_input.onkeyup = geo_input.onchange = function(event){updateAddress(event)};
	//onsubmit = function(){updateAddressMap(KeystrokeCount);return false;};
	//dragging.onchange = function(){
	//	if (this.checked) {
			//_suggestionDragging.style.display = "";
			// abilitiamo il dragging del segnaposto

			//memorizzo il numero di riga in questa variabile,cosė evito il problema che rows_id viene decrementata
			num=rows_id;

			GCodeMap.enableDraggingAddress(function(point){
				// rispristino valori iniziali
				PointOnMap = point;

				// ricerca indirizzo
				GCodeMap.searchLatLng(point, function(name, response) {

					// numero di risultati prodotti dalla ricerca
					var nFound = response.length;

					// mostriamo le opzioni
					HTMLOptions.style.display = (nFound > 0)?"":"none";

					// rispristino valori iniziali
					GeoLocationOnMap = null;

					if (nFound > 0) {
						// recupero l'indirizzo al momento visibile su mappa
						GeoLocationOnMap = response[0];

						// comunicazione messaggio utente
						//var didyouHTML = "Sei in <b>" + response[0].getAddress() + "</b><br />"
						//+ "<i>Il punto su mappa dista <b>" + parseInt(point.distanceFrom( response[0].getPoint())) + " metri</b> da questo indirizzo</i><hr/>";

						var didyouHTML = "Sei in <b>" + response[0].getAddress() + "</b><br />";

						// risultati multipli
						/*if (nFound > 1) {

							didyouHTML += "<h1>Forse cercavi:</h1>";

							// Loop through the results
							for (var i = 0; i < nFound; i++) {
								var location = response[i];
								didyouHTML += "<div class=\"ref\"><a href=\"javascript:placeAddress('" + encodeURIComponent(location.getAddress().replace("'", "\\'")) + "')\">" + location.getAddress() + "</a></div>";
							}
						}*/
						// comunicazione messaggio utente
						HTMLSuggestionText.innerHTML = didyouHTML;

					  delCircleSingle(num);
            document.getElementById('geo_input_'+num).value=response[0].getAddress();
            updateAddressReq(null,null,num);

					}else{
						// rispristino valori iniziali
						PointOnMap = null;

						// comunicazione messaggio utente
						HTMLSuggestionText.innerHTML = "Impossibile riconoscere la localit&agrave; <b>" + name + "</b>";
					}
				});

			})

	/*	} else {
			_suggestionDragging.style.display = "none";
			// disabilitiamo il dragging del segnaposto
			GCodeMap.disableDraggingAddress();
		}
	};*/
}

function disableDraggingAddress(){
  GCodeMap.disableDraggingAddress();
}

function removeAddress(){
  GCodeMap.removeAddress();
}
	

function drawCircleScript(){
	// gestione disegno cerchio
	FormCircle = document.forms["circle"];
	FormCircle.reset_google();
	FormCircle.lineColor.onkeyup = FormCircle.lineColor.onchange = function(event){document.getElementById("sample_" + this.name).style.backgroundColor = this.value};
	FormCircle.fillColor.onkeyup = FormCircle.fillColor.onchange = function(event){document.getElementById("sample_" + this.name).style.backgroundColor = this.value};
	FormCircle.onsubmit = function(){drawCircle();return false;};
}

//funzione che rimuove il cerchio desiderato
//il primo cerchio ha ID 0
/*function delCircleSingle(rows){
  circle_id=array_circle[rows];
  GCodeMap.removeCircleById(circle_id.ID);
  //document.getElementById('geo_input_'+rows).value='';
  //document.getElementById('map_range_'+rows).value='---';
  document.getElementById('map_lng_'+rows).value='';
  document.getElementById('map_lat_'+rows).value='';
  document.getElementById('geo_country_id_'+rows).value='';
  document.getElementById('geo_country_name_'+rows).value='';
  document.getElementById('geo_region_id_'+rows).value='';
  document.getElementById('geo_region_name_'+rows).value='';
  document.getElementById('geo_province_id_'+rows).value='';
  document.getElementById('geo_province_name_'+rows).value='';
  document.getElementById('geo_town_id_'+rows).value='';
  document.getElementById('geo_town_name_'+rows).value='';
  document.getElementById('cap_'+rows).value='';
  document.getElementById('geo_address_'+rows).value='';
  document.getElementById('complete_address_'+rows).value='';
  document.getElementById('geo_country_code_'+rows).value='';
  --NCircleOnMap;
}*/

//funzione che rimuove il cerchio desiderato
//il primo cerchio ha ID 0
function delCircleSingle(rows){
  circle_id=array_circle[rows];
  GCodeMap.removeCircleById(circle_id.ID);
  //document.getElementById('geo_input_'+rows).value='';
  //document.getElementById('map_range_'+rows).value='---';
  document.getElementById('map_lng_'+rows).value='';
  document.getElementById('map_lat_'+rows).value='';
  document.getElementById('geo_country_id_'+rows).value='';
  document.getElementById('geo_country_name_'+rows).value='';
  document.getElementById('geo_region_id_'+rows).value='';
  document.getElementById('geo_region_name_'+rows).value='';
  document.getElementById('geo_province_id_'+rows).value='';
  document.getElementById('geo_province_name_'+rows).value='';
  document.getElementById('geo_town_id_'+rows).value='';
  document.getElementById('geo_town_name_'+rows).value='';
  document.getElementById('cap_'+rows).value='';
  document.getElementById('geo_address_'+rows).value='';
  document.getElementById('complete_address_'+rows).value='';
  document.getElementById('geo_country_code_'+rows).value='';
  --NCircleOnMap;
}

function delCircleSingleNoClear(rows){

  if(NCircleOnMap>0){
    circle_id=array_circle[rows];
    GCodeMap.removeCircleById(circle_id.ID);
    --NCircleOnMap;
  }
}


// gestione eliminazione contenuti su mappa
function reset_google() {
  geo_input.value = "";
	HTMLSuggestionText.innerHTML = "";
	HTMLOptions.style.display = "none";
  //document.getElementById('counter_gg1').innerHTML="";
  //document.getElementById('counter_gg2').innerHTML="";
  GCodeMap.clear();
}

/**
 * richiamato durante la digitazione dell'indirizzo da parte dell'utente.
 * @param event gestore dell'evento che ha prodotto la richiesta.
 */ 
function updateAddress(event, breset) {
  
	// ignore tabs
	if (event && event.keyCode == 9) {
		return;
	}
	
	if (breset) {LastAddressSearch = null;}

    // wait two seconds, and if no more keys have been pressed, then update the address and map
	KeystrokeCount++;
	
	// gestione temporizzazione
	window.setTimeout(function(){updateAddressMap(KeystrokeCount)}, 500);

}

/**
 * ricerca l'indirizzo su mappa.
 * @param keyCount
 * @return
 */
function updateAddressMap(keyCount) {
	// only do the backend calls if it's been at least two seconds since the last key was pressed
 
	if (keyCount != KeystrokeCount) {
		return;
	}

	var geo_input = document.getElementById('geo_input').value;
  //var HTMLOptions = document.getElementById('map_range').value;

	// evitiamo di effettuare richieste multiple
  var addressNormalize = geo_input.replace(/[^A-Za-z0-9]/g,"");

  	if (addressNormalize.length > 0) {
  		LastAddressSearch = addressNormalize;
		
		// ricerca indirizzo
			GCodeMap.searchAddress(geo_input, function(name, response) {
			// numero di risultati prodotti dalla ricerca
			var nFound = response.length;
			
			// mostriamo le opzioni
			/*HTMLOptions.style.display = (nFound > 0)?"":"none";*/
	
			// rispristino valori iniziali
			GeoLocationOnMap = null;
			PointOnMap = null;

			if (nFound > 0) {

				// recupero l'indirizzo al momento visibile su mappa
				GeoLocationOnMap = response[0];
				PointOnMap = GeoLocationOnMap.getPoint();

        if (maplang!='es') {
          label_indirizzotrovato='indirizzo trovato';
        }else {
          label_indirizzotrovato='direccion encontrada';
        }

				// comunicazione messaggio utente
				var didyouHTML = "<br/><b>"+label_indirizzotrovato+"</b> '" + GeoLocationOnMap.getAddress() + "'<br/>";

				// risultati multipli
				/*if (nFound > 1) {
				  if (maplang!='es') {
            label_forse_cercavi='forse cercavi';
          }else {
            label_forse_cercavi='puede ser que buscaba';
          }

					didyouHTML += "<br/>"+label_forse_cercavi+":<br/>";
					
					//map_range_place=document.getElementById('map_range').value;
					// loop through the results
					for (var i = 0; i < nFound; i++) {
						var location = response[i];
						didyouHTML += "<div><a href=\"javascript:placeAddress('" + encodeURIComponent(location.getAddress().replace("'", "\\'")) + "');updateAddress(null,null);\">" + location.getAddress() + "</a></div>";
					}
					didyouHTML += "<br/>";
				}*/
				
				// comunicazione messaggio utente
				HTMLSuggestionText.innerHTML = didyouHTML;

				//GETCOORDS//
				var point = GeoLocationOnMap.getPoint();
					
				// setto le coordinate
				var lng = point.lng();
				var lat = point.lat();
				document.getElementById('map_lng').value=lng;
				document.getElementById('map_lat').value=lat;
				
				//richiamo funzione di recupero dettagli
				parseAddressDetails(0);
				//GETCOORDS//

				//la seguente funzione č presente in geo.xsl//
				get_geo_id();
				if(document.getElementById('map_lng').value!=''){
				  //control_unknown_locality(rows_id);
				}

				/*if (document.getElementById('map_range')) {
					drawCircleNew();
				}*/

			} else {
	       
	      if (maplang!='es') {
          label_impossibile_localita='impossibile riconoscere la localita';
        }else {
          label_impossibile_localita='imposible reconocer la localidad';
        }
				// comunicazione messaggio utente
				HTMLSuggestionText.innerHTML = "<br/><b>"+label_impossibile_localita+"</b> '" + name + "'<br/>";
				
			}
			
		});  //fine _gcodemap.searchAddress
	}  else {

		//GETCOORDS//
		var point = GeoLocationOnMap.getPoint();
		
		// setto le coordinate
		var lng = point.lng();
		var lat = point.lat();
		document.getElementById('map_lng').value=lng;
		document.getElementById('map_lat').value=lat;
	
		//richiamo funzione di recupero dettagli
		parseAddressDetails(0);
		//GETCOORDS//
	
		//la seguente funzione č presente in geo.xsl//
		get_geo_id();

		/*if (document.getElementById('map_range')) {
			drawCircleNew();
		}*/

	}  // fine else if lastaddress
	StreetScript();
}

/**
 * richiamato durante la digitazione dell'indirizzo da parte dell'utente.
 * @param event gestore dell'evento che ha prodotto la richiesta.
 */
function updateAddressReq(event, breset, rows_id) {

	// ignore tabs
	if (event && event.keyCode == 9) {
		return;
	}

	if (breset) {LastAddressSearch = null;}

    // wait two seconds, and if no more keys have been pressed, then update the address and map
	KeystrokeCount++;

	// gestione temporizzazione
	window.setTimeout(function(){updateAddressMapReq(KeystrokeCount,rows_id)}, 500);

}

/**
 * ricerca l'indirizzo su mappa.
 * @param keyCount
 * @return
 */
function updateAddressMapReq(keyCount,rows_id) {
	// only do the backend calls if it's been at least two seconds since the last key was pressed

	if (keyCount != KeystrokeCount) {
		return;
	}

	var geo_input = document.getElementById('geo_input_'+rows_id).value;
  var HTMLOptions = document.getElementById('map_range_'+rows_id).value;

	// evitiamo di effettuare richieste multiple
  var addressNormalize = geo_input.replace(/[^A-Za-z0-9]/g,"");

  	if (addressNormalize.length > 0) {
  		LastAddressSearch = addressNormalize;

		// ricerca indirizzo
			GCodeMap.searchAddress(geo_input, function(name, response) {
			// numero di risultati prodotti dalla ricerca
			var nFound = response.length;

			// mostriamo le opzioni
			/*HTMLOptions.style.display = (nFound > 0)?"":"none";*/

			// rispristino valori iniziali
			GeoLocationOnMap = null;
			PointOnMap = null;

			if (nFound > 0) {

				// recupero l'indirizzo al momento visibile su mappa
				GeoLocationOnMap = response[0];
				PointOnMap = GeoLocationOnMap.getPoint();

        if (maplang!='es') {
          label_indirizzotrovato='indirizzo trovato';
        }else {
          label_indirizzotrovato='direccion encontrada';
        }

				// comunicazione messaggio utente
				var didyouHTML = "<br/><b>"+label_indirizzotrovato+"</b> '" + GeoLocationOnMap.getAddress() + "'<br/>";

				// risultati multipli
				if (nFound > 1) {
				  if (maplang!='es') {
            label_forse_cercavi='forse cercavi';
          }else {
            label_forse_cercavi='puede ser que buscaba';
          }

					didyouHTML += "<br/>"+label_forse_cercavi+":<br/>";

					map_range_place=document.getElementById('map_range_'+rows_id).value;
					// loop through the results
					for (var i = 0; i < nFound; i++) {
						var location = response[i];
						didyouHTML += "<div><a href=\"javascript:delCircleSingle("+rows_id+");placeAddress('" + encodeURIComponent(location.getAddress().replace("'", "\\'")) + "',"+rows_id+","+map_range_place+");updateAddressReq(null,null,"+rows_id+");\">" + location.getAddress() + "</a></div>";
					}
					didyouHTML += "<br/>";
				}

				// comunicazione messaggio utente
				HTMLSuggestionText.innerHTML = didyouHTML;

				//GETCOORDS//
				var point = GeoLocationOnMap.getPoint();

				// setto le coordinate
				var lng = point.lng();
				var lat = point.lat();
				document.getElementById('map_lng_'+rows_id).value=lng;
				document.getElementById('map_lat_'+rows_id).value=lat;

				//richiamo funzione di recupero dettagli
				parseAddressDetails(rows_id);
				//GETCOORDS//

				//la seguente funzione č presente in geo.xsl//
				get_geo_id_req(rows_id);
				if(document.getElementById('map_lng_'+rows_id).value!=''){
				  control_unknown_locality(rows_id);
				}

				if (document.getElementById('map_range_'+rows_id).value!='') {
					drawCircleNew(rows_id,lng,lat);
				}

			} else {

	      if (maplang!='es') {
          label_impossibile_localita='impossibile riconoscere la localita';
        }else {
          label_impossibile_localita='imposible reconocer la localidad';
        }
				// comunicazione messaggio utente
				HTMLSuggestionText.innerHTML = "<br/><b>"+label_impossibile_localita+"</b> '" + name + "'<br/>";

			}

		});  //fine _gcodemap.searchAddress
	}  else {

		//GETCOORDS//
		var point = GeoLocationOnMap.getPoint();

		// setto le coordinate
		var lng = point.lng();
		var lat = point.lat();
		document.getElementById('map_lng_'+rows_id).value=lng;
		document.getElementById('map_lat_'+rows_id).value=lat;

		//richiamo funzione di recupero dettagli
		parseAddressDetails(rows_id);
		//GETCOORDS//

		//la seguente funzione č presente in geo.xsl//
		get_geo_id_req(rows_id);

		if (document.getElementById('map_range_'+rows_id)) {
			drawCircleNew(rows_id,lng,lat);
		}

	}  // fine else if lastaddress
}

/**
 * ricerca l'indirizzo specificato.
 */
function placeAddress(address,rows_id,map_range_place) {
  document.getElementById('geo_input_'+rows_id).value=decodeURIComponent(address);
  document.getElementById('map_range_'+rows_id).value=map_range_place;
}

/**
 * disegna un cerchio su mappa
 */
 function drawCircle() {
 
 var limitCircle='3';
 
 if (isNaN(limitCircle)) {
		alert("Attenzione!\nInserire nel campo \"Numero massimo di cerchi\" un numero valido.");
		return;
	}

	if (NCircleOnMap >= limitCircle) {
		alert("Attenzione!\nRaggiunto il numero massimo di cerchi su mappa\nEliminare almeno un cerchio prima di procedere.");
		return;
	}

	if (GeoLocationOnMap) {
		var point = GeoLocationOnMap.getPoint();
		
		// oppure
		// var point = new GeoPoint(-122.083739, 37.423021);
		if (document.getElementById("map_range").options[document.getElementById("map_range").selectedIndex].value!='---') {		
			var radius = document.getElementById("map_range").options[document.getElementById("map_range").selectedIndex].value;
			var fillOpacity = 0.3;
			var lineOpacity = 0.7;
		} else{
			var fillOpacity = 0.0;
			var lineOpacity = 0.0;
		}
		var quality = 40;
		var lineColor = "#555555";
		var lineWidth = 1;

		//var fillColor = "#ff9900";
		var fillColor = "#ffffff";
		// disegno cerchio
		GCodeMap.drawCircle(point, radius, quality, lineColor, lineWidth, lineOpacity, fillColor, fillOpacity);

		//re_counter();

	} else {
/////		alert('non e\' stato definito un punto sulla mappa; controllare l\'indirizzo e cliccare su \'conferma\'');
	}
}

function drawCircleNew(rows_id,lng,lat) {

	//var limitCircle = parseInt(FormLimitCircle.n.value);
	var limitCircle = '3';

	if (isNaN(limitCircle)) {
		alert("Attenzione!\nInserire nel campo \"Numero massimo di cerchi\" un numero valido.");
		return;
	}

	if (NCircleOnMap >= limitCircle) {
		alert("Attenzione!\nRaggiunto il numero massimo di cerchi su mappa\nEliminare almeno un cerchio prima di procedere.");
		return;
	}

	try {
		//var point = PointOnMap;

		var point = new GeoPoint(lat, lng);

		// oppure
		// var point = PointOnMap;
		// o
		// var point = new GeoPoint(-122.083739, 37.423021);
		// etc.

		/*var radius = parseFloat(FormCircle.radius.value) || 1;
		var quality = parseInt(FormCircle.quality.value) || 40;
		var lineColor = FormCircle.lineColor.value;
		var lineWidth = parseInt(FormCircle.lineWidth.value) || 1;
		var lineOpacity = parseFloat(FormCircle.lineOpacity.value) || 0.7;
		var fillColor = FormCircle.fillColor.value;
		var fillOpacity = parseFloat(FormCircle.fillOpacity.value) || 0.4;*/
		var radius= document.getElementById('map_range_'+rows_id).options[document.getElementById('map_range_'+rows_id).selectedIndex].value;
		var quality = 40;
		var lineColor = "#555555";
		var lineWidth = 1;
		var lineOpacity = 0.7;
		var fillColor = "#ff9900";
    var fillOpacity = 0.4;

		// disegno cerchio
		var myCircle = GCodeMap.drawCircle(point, radius, quality, lineColor, lineWidth, lineOpacity, fillColor, fillOpacity);

		//inizializzo l'array che contiene gli oggetti circle
    array_circle[rows_id]=myCircle;

		// gestione eventi
		addCircleEventListener(myCircle);
		// aggiornamento contatore
		++NCircleOnMap;

	} catch(e) {
		alert(e.message)
	}
}


function re_counter() {
    var point = GeoLocationOnMap.getPoint();
    radius= document.getElementById("map_range").options[document.getElementById("map_range").selectedIndex].value;
    var lng = point.lng();
    var lat = point.lat();
    
    //conto immobili
		document.getElementById('counter_gg1').innerHTML="";
		counter(lng,lat,radius,1);
}


/**
 * conta gli elementi presenti in un dato range
 */
function counter(map_lng,map_lat,map_range,gg) {

	try {
	  
	  var url = 'index.php?ac=geo_counter&gg='+gg+'&map_lng='+map_lng+'&map_lat='+map_lat+'&map_range='+map_range;
	  
    new Ajax.Updater('counter_gg'+gg, url,{asynchronous:true, evalScripts:true});
		
	} catch(e) {	
		alert(e.message);
	}

}

/**
 * Gestione eventi del cerchio
 * @param circle forma geometrica da gestire
 */
function addCircleEventListener(circle) {
	circle.addListener("mouseover", function(){
		/*circle.addListener("click", function(){
			if (confirm("Vuoi eliminare questo cerchio?")) {
				GCodeMap.removeCircleById(circle.ID);

				// aggiornamento contatore
				--NCircleOnMap;
			}
		})*/

		var strokeColor = "#555555";
		var strokeWeight = 3;
		var strokeOpacity = 1;
		var fillColor = "#ff9900";
		var fillOpacity = 0.4;
		// cambiamo gli stile del cerchio
		circle.setStrokeStyle({"color":strokeColor,"weight":strokeWeight,"opacity":strokeOpacity});
		circle.setFillStyle({"color":fillColor,"opacity":fillOpacity});

	
	})
	circle.addListener("mouseout", function() {
		circle.removeListener("click");

		var strokeColor = '#555555';
		var strokeWeight = 1;
		var strokeOpacity = 0.7;
		var fillColor = "#ff9900";
		var fillOpacity = 0.4;
		// cambiamo lo stile del cerchio
		circle.setStrokeStyle({"color":strokeColor,"weight":strokeWeight,"opacity":strokeOpacity});
		circle.setFillStyle({"color":fillColor,"opacity":fillOpacity});
	})
	
}



/**
 * recupera la localizzazione in formato JSON_xAL
 */
function parseAddressDetails(rows_id) {

  /*var addressDetails = window.open("", "addressDetails");
	addressDetails.document.write('<meta http-equiv="content-type" content="text/html; charset=utf-8"/>');
	addressDetails.document.write('<link rel="stylesheet" href="style/parse.css" type="text/css"/>');
	addressDetails.document.write('The address formatted as xAL, or <a href="http://www.oasis-open.org/committees/ciq/ciq.html#6">eXtensible Address Language</a>, an international standard for address formatting.<br/>');
  */
  var addressDetailsJSON_xAL = GeoLocationOnMap.getAddressDetails();
  
  var complete_address = GeoLocationOnMap.getAddress();
  
  if(rows_id>0){
    document.getElementById('complete_address_'+rows_id).value=complete_address;
  }else{
    document.getElementById('complete_address').value=complete_address;
  }
  
  var accuracy = addressDetailsJSON_xAL.Accuracy;

  if (addressDetailsJSON_xAL.Country){
    var country = addressDetailsJSON_xAL.Country.CountryName;
    var country_code = addressDetailsJSON_xAL.Country.CountryNameCode;
  }else {
    var country = "";
    var country_code = "";
  }
  
  if (addressDetailsJSON_xAL.Country.AdministrativeArea){

    var region = addressDetailsJSON_xAL.Country.AdministrativeArea.AdministrativeAreaName;
    //province
    if (addressDetailsJSON_xAL.Country.AdministrativeArea.SubAdministrativeArea){
      var province = addressDetailsJSON_xAL.Country.AdministrativeArea.SubAdministrativeArea.SubAdministrativeAreaName;
        //town
        if (addressDetailsJSON_xAL.Country.AdministrativeArea.SubAdministrativeArea.Locality){
          var town = addressDetailsJSON_xAL.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
          //address
          if (addressDetailsJSON_xAL.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare){
            var address = addressDetailsJSON_xAL.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName;
          }else if (addressDetailsJSON_xAL.Country.AdministrativeArea.SubAdministrativeArea.Locality.DependentLocality){
          	if(addressDetailsJSON_xAL.Country.AdministrativeArea.SubAdministrativeArea.Locality.DependentLocality.Thoroughfare){
          		var address = addressDetailsJSON_xAL.Country.AdministrativeArea.SubAdministrativeArea.Locality.DependentLocality.Thoroughfare.ThoroughfareName;
          	}else{
          	  var address = "";
          	}
          }else{
        	  var address = "";
          }
          //fine address
          //cap
          if (addressDetailsJSON_xAL.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode) {
            var cap = addressDetailsJSON_xAL.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber;
          }else if (addressDetailsJSON_xAL.Country.AdministrativeArea.SubAdministrativeArea.Locality.DependentLocality){
        	if(addressDetailsJSON_xAL.Country.AdministrativeArea.SubAdministrativeArea.Locality.DependentLocality.PostalCode){
        		var cap = addressDetailsJSON_xAL.Country.AdministrativeArea.SubAdministrativeArea.Locality.DependentLocality.PostalCode.PostalCodeNumber;
        	}else{
        		var cap = "";
        	}
          }else{
        	  var cap = "";
          }
          //fine cap
        }else{
          var town = "";
        }
        //fine town
    }else{
      var province = "";
      if(addressDetailsJSON_xAL.Country.AdministrativeArea.Locality){
        var town = addressDetailsJSON_xAL.Country.AdministrativeArea.Locality.LocalityName;
        //address
          if (addressDetailsJSON_xAL.Country.AdministrativeArea.Locality.Thoroughfare){
            var address = addressDetailsJSON_xAL.Country.AdministrativeArea.Locality.Thoroughfare.ThoroughfareName;
          }else if (addressDetailsJSON_xAL.Country.AdministrativeArea.Locality.DependentLocality){
          	if(addressDetailsJSON_xAL.Country.AdministrativeArea.Locality.DependentLocality.Thoroughfare){
          		var address = addressDetailsJSON_xAL.Country.AdministrativeArea.Locality.DependentLocality.Thoroughfare.ThoroughfareName;
          	}else{
          	  var address = "";
          	}
          }else{
        	  var address = "";
          }
          //fine address
          //cap
          if (addressDetailsJSON_xAL.Country.AdministrativeArea.Locality.PostalCode) {
            var cap = addressDetailsJSON_xAL.Country.AdministrativeArea.Locality.PostalCode.PostalCodeNumber;
          }else if (addressDetailsJSON_xAL.Country.AdministrativeArea.Locality.DependentLocality){
        	if(addressDetailsJSON_xAL.Country.AdministrativeArea.Locality.DependentLocality.PostalCode){
        		var cap = addressDetailsJSON_xAL.Country.AdministrativeArea.Locality.DependentLocality.PostalCode.PostalCodeNumber;
        	}else{
        		var cap = "";
        	}
          }else{
        	  var cap = "";
          }
          //fine cap
      }else{
        var town = "";
      }
    }
    //fine province
  }else{
    var region = "";
      if (addressDetailsJSON_xAL.Country.SubAdministrativeArea){
        var province = addressDetailsJSON_xAL.Country.SubAdministrativeArea.SubAdministrativeAreaName;
        //town
        if (addressDetailsJSON_xAL.Country.SubAdministrativeArea.Locality){
          var town = addressDetailsJSON_xAL.Country.SubAdministrativeArea.Locality.LocalityName;
          //address
          if (addressDetailsJSON_xAL.Country.SubAdministrativeArea.Locality.Thoroughfare){
            var address = addressDetailsJSON_xAL.Country.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName;
          }else if (addressDetailsJSON_xAL.Country.SubAdministrativeArea.Locality.DependentLocality){
          	if(addressDetailsJSON_xAL.Country.SubAdministrativeArea.Locality.DependentLocality.Thoroughfare){
          		var address = addressDetailsJSON_xAL.Country.SubAdministrativeArea.Locality.DependentLocality.Thoroughfare.ThoroughfareName;
          	}else{
          	  var address = "";
          	}
          }else{
        	  var address = "";
          }
          //fine address
          //cap
          if (addressDetailsJSON_xAL.Country.SubAdministrativeArea.Locality.PostalCode) {
            var cap = addressDetailsJSON_xAL.Country.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber;
          }else if (addressDetailsJSON_xAL.Country.SubAdministrativeArea.Locality.DependentLocality){
        	if(addressDetailsJSON_xAL.Country.SubAdministrativeArea.Locality.DependentLocality.PostalCode){
        		var cap = addressDetailsJSON_xAL.Country.SubAdministrativeArea.Locality.DependentLocality.PostalCode.PostalCodeNumber;
        	}else{
        		var cap = "";
        	}
          }else{
        	  var cap = "";
          }
          //fine cap
        }else{
          var town = "";
        }
        //fine town
      }else{
        var province = "";
          if (addressDetailsJSON_xAL.Country.Locality){
            var town = addressDetailsJSON_xAL.Country.Locality.LocalityName;
            //address
            if (addressDetailsJSON_xAL.Country.Locality.Thoroughfare){
              var address = addressDetailsJSON_xAL.Country.Locality.Thoroughfare.ThoroughfareName;
            }else if (addressDetailsJSON_xAL.Country.Locality.DependentLocality){
            	if(addressDetailsJSON_xAL.Country.Locality.DependentLocality.Thoroughfare){
            		var address = addressDetailsJSON_xAL.Country.Locality.DependentLocality.Thoroughfare.ThoroughfareName;
            	}else{
            	  var address = "";
            	}
            }else{
          	  var address = "";
            }
            //fine address
            //cap
            if (addressDetailsJSON_xAL.Country.Locality.PostalCode) {
              var cap = addressDetailsJSON_xAL.Country.Locality.PostalCode.PostalCodeNumber;
            }else if (addressDetailsJSON_xAL.Country.Locality.DependentLocality){
          	if(addressDetailsJSON_xAL.Country.Locality.DependentLocality.PostalCode){
          		var cap = addressDetailsJSON_xAL.Country.Locality.DependentLocality.PostalCode.PostalCodeNumber;
          	}else{
          		var cap = "";
          	}
            }else{
          	  var cap = "";
            }
            //fine cap
          }else{
            var town = "";
          }  //fine if locality
      }  // fine if subadministrativearea
    
  }   // fine id administrativearea

  if(rows_id>0){
    document.getElementById('geo_country_name_'+rows_id).value=country;
    document.getElementById('geo_country_code_'+rows_id).value=country_code;
    document.getElementById('geo_region_name_'+rows_id).value=region;
    document.getElementById('geo_province_name_'+rows_id).value=province;
    document.getElementById('geo_town_name_'+rows_id).value=town;
    document.getElementById('geo_address_'+rows_id).value=address;
    document.getElementById('cap_'+rows_id).value=cap;
  }else{
    document.getElementById('geo_country_name').value=country;
    document.getElementById('geo_country_code').value=country_code;
    document.getElementById('geo_region_name').value=region;
    document.getElementById('geo_province_name').value=province;
    document.getElementById('geo_town_name').value=town;
    document.getElementById('geo_address').value=address;
    document.getElementById('cap').value=cap;
  }
  
  /*addressDetails.document.write(parseJSON(eval(addressDetailsJSON_xAL)));
	addressDetails.document.close()*/
}


//usata per geocodificare i nostri immobili... temporanea con geolocate.php//
function searchAddressFromData(id) {
	geo_input.value=eval('document.getElementById(\'complete_address_'+id+'\')').value;
  
	GCodeMap.searchAddress(geo_input.value, function (name,response){
      
      // numero di risultati prodotti dalla ricerca
			var nFound = response.length;

			if (nFound > 0) {
			
				// recupero l'indirizzo al momento visibile su mappa
				GeoLocationOnMap = response[0];

				// comunicazione messaggio utente
				var geo = GeoLocationOnMap.getAddress();
				var point = GeoLocationOnMap.getPoint();
        
        eval('document.getElementById(\'new_complete_address_'+id+'\')').value=geo;
				eval('document.getElementById(\'lat_'+id+'\')').value=point.lat();
				eval('document.getElementById(\'lng_'+id+'\')').value=point.lng();

		document.getElementById('query').innerHTML=document.getElementById('query').innerHTML+
		'update re_re set map_lng='+point.lng()+',map_lat='+point.lat()+' where id='+id+';<br/>';
				
			}
			
  });
	
}


function searchAddressFromData_address_null(id) {
	geo_input.value=eval('document.getElementById(\'complete_address_'+id+'\')').value;
  	
	GCodeMap.searchAddress(geo_input.value, function (name,response){
      
      // numero di risultati prodotti dalla ricerca
			var nFound = response.length;

			if (nFound > 0) {
			
				// recupero l'indirizzo al momento visibile su mappa
				GeoLocationOnMap = response[0];

				// comunicazione messaggio utente
				var geo = GeoLocationOnMap.getAddress();
				var point = GeoLocationOnMap.getPoint();
        
        eval('document.getElementById(\'new_complete_address_'+id+'\')').value=geo;
				eval('document.getElementById(\'lat_'+id+'\')').value=point.lat();
				eval('document.getElementById(\'lng_'+id+'\')').value=point.lng();

		document.getElementById('query').innerHTML=document.getElementById('query').innerHTML+
		'update re_re set map_lng='+point.lng()+',map_lat='+point.lat()+' where (address is null or address=\'null\' or address =\'n/a\') and geo_town_id='+id+';<br/>';
				
			}
			
  });
	
}

// visualizzazione punto su mappa
function viewAddress(map_lat,map_lng,address) {

  // caricamento XML
	var xmlstring = '<?xml version="1.0"?>'+
    '<GeoCoderMap>'+
      '<Style id="orange">'+
    		'<Icon width="12" height="20">http:&#47;&#47;labs.google.com/ridefinder/images/mm_20_orange.png</Icon>'+
    		'<Shadow width="22" height="20">http:&#47;&#47;labs.google.com/ridefinder/images/mm_20_shadow.png</Shadow>'+
    	'</Style>'+
    	'<Point lat="'+map_lat+'" lng="'+map_lng+'">'+
    		'<Snippet>'+address+'</Snippet>'+
    		'<StyleRef>address</StyleRef>'+
    	'</Point>'+
    '</GeoCoderMap>';

  GCodeMap.loadXmlData(xmlstring,true);
}

function viewAddressFromXml() {
  
  // caricamento XML
  var xmlstring=document.getElementById('google_xml').value;

  GCodeMap.loadXmlData(xmlstring,true);
  
}

//funzione che visualizza il punto su mappa in modifica
function setCenter(rows_id) {

  var lng=document.getElementById('map_lng_'+rows_id).value;
  var lat=document.getElementById('map_lat_'+rows_id).value;
  var point=new GeoPoint(lat,lng);
  var zoom=setLevelZoom(rows_id);
  GCodeMap.setCenter(point,zoom);
}

function setLevelZoom(rows_id) {

  var map_range=document.getElementById('map_range_'+rows_id).value;

  if(map_range==0.25){
    var zoom=16;
  }else if(map_range==0.5){
    var zoom=15;
  }else if(map_range==1){
    var zoom=14;
  }else if(map_range==2){
    var zoom=13;
  }else if(map_range==3){
    var zoom=12;
  }else if(map_range==4){
    var zoom=12;
  }else if(map_range==5){
    var zoom=12;
  }else if(map_range==10){
    var zoom=11;
  }else if(map_range==15){
    var zoom=10;
  }else if(map_range==25){
    var zoom=9;
  }else if(map_range==40){
    var zoom=9;
  }else if(map_range==65){
    var zoom=8;
  }
  return zoom;
}

function enableDragging(){

  GCodeMap.enableDragging();
}
