var map_div;
var map;
var gdir;
var geocoder=null;
var loadingMessage;

var loading_div_width=590;
var loading_div_height=415;

var small_loading_div_width=360;
var small_loading_div_height=270;


var clean_url_to_fill;
var url_filled_with_alphaid;
var geoArray=new Array();
var toggleArray=new Array();
var location_suffix_to_append;
var found_areas_from_code='';


function initialize(map_div_id,latitudine,longitudine,zoom,risultato_percorso_div_id,absolute_clean_url_to_fill,location_suffix,eventual_alpha_id) {
	map_div=document.getElementById(map_div_id);
	if (GBrowserIsCompatible()) {
		map=new GMap2(map_div);
		map.setCenter(new GLatLng(latitudine,longitudine),zoom);
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		
		// hack to open kml description links in the current window ("a" target substitution)
		GEvent.addListener(map,"infowindowopen",function() {
				var i=map.getInfoWindow();
				var nodes=i.getContentContainers();
				for (var node in nodes) {
						var anchors=nodes[node].getElementsByTagName('a');
						for (var a in anchors) {
								if (anchors[a].tagName) anchors[a].setAttribute("target","_top");
						}
				}
		});
		
		
		geocoder=new GClientGeocoder();
		
		gdir=new GDirections(map,document.getElementById(risultato_percorso_div_id));
		GEvent.addListener(gdir,"error",handleErrors);
	}
	clean_url_to_fill=absolute_clean_url_to_fill;
	
	location_suffix_to_append=location_suffix;
	if (eventual_alpha_id!='') findAreaFromCode(eventual_alpha_id);
} 


function toggleKml(geotype,start) {
	
	//alert(clean_url_to_fill+geotype+'&start='+start);
	//document.write(clean_url_to_fill+geotype+'&start='+start);

	if (toggleArray[geotype]==undefined) {
		toggleArray[geotype]=new Array();
		geoArray[geotype]=new Array();
	}
	
	if (toggleArray[geotype][start]==undefined || toggleArray[geotype][start]==0) {

		performLoading();
		
		geoArray[geotype][start]=new GGeoXml(clean_url_to_fill+geotype+'&start='+start,loaded_callback);
		map.addOverlay(geoArray[geotype][start]);
		toggleArray[geotype][start]=1;
	} else {
		map.removeOverlay(geoArray[geotype][start]);
		toggleArray[geotype][start]=0;
	}
}


function showAddress(address) {
	address=address+location_suffix_to_append;
	if (geocoder) {
		geocoder.getLatLng(address,function(point) {
			if (!point) {
				alert(address+" not found");
			} else {
				map.setCenter(point, 13);
				var marker=new GMarker(point);
				map.addOverlay(marker);
				marker.openInfoWindowHtml(address);
			}
		});
	}
}


function setDirections(fromAddress,toAddress,locale) {
	gdir.load("from: "+fromAddress+location_suffix_to_append+" to: "+toAddress+location_suffix_to_append,{"locale": locale});
}


function changeAbleCheckboxes(not_able) {
	inputs=document.getElementsByTagName('input');
	for (var i=0;i<inputs.length;i++) {
		if(inputs[i].getAttribute('type')=='checkbox') inputs[i].disabled=not_able;
	}
}


function loaded_callback() {
	map.removeControl(loadingMessage);
	
	changeAbleCheckboxes(false);
	
	$.unblockUI();
}


function performLoading() {
	
	changeAbleCheckboxes(true);
	
	var html='<div style="width:'+loading_div_width+'px;height:'+loading_div_height+'px;background:transparent url(googlemap/resources/loading_grande.gif) no-repeat center;"></div>';
	loadingMessage=new HtmlControl(html);
	map.addControl(loadingMessage,new GControlPosition(G_ANCHOR_TOP_LEFT));
}


////////////////////////////////////////////////////////////////////////////
// funzioni prefatta per la gestione degli errori di GDirections
////////////////////////////////////////////////////////////////////////////

function handleErrors() {
	if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
		alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
		alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
		alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
	//else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
		//alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_BAD_KEY)
		alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
		alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
	else
		alert("An unknown error occurred.");
}


////////////////////////////////////////////////////////////////////////////
// funzioni per le pagine georeferenziate
////////////////////////////////////////////////////////////////////////////

function small_initialize(map_div_id,latitudine,longitudine,zoom,absolute_url_filled_with_alphaid) {
	map_div=document.getElementById(map_div_id);
	if (GBrowserIsCompatible()) {
		map=new GMap2(map_div);
		map.setCenter(new GLatLng(latitudine,longitudine),zoom);
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
	}
	url_filled_with_alphaid=absolute_url_filled_with_alphaid;
	
	//performSmallLoading();
	
	var single_area=new GGeoXml(url_filled_with_alphaid,loaded_callback);
	map.addOverlay(single_area);
} 


function displaySmallLoadingGif() {
	var html='<div style="width:'+small_loading_div_width+'px;height:'+small_loading_div_height+'px;background:transparent url(googlemap/resources/loading_grande.gif) no-repeat center;"></div>';
	loadingMessage=new HtmlControl(html);
	map.addControl(loadingMessage,new GControlPosition(G_ANCHOR_TOP_LEFT));
}


////////////////////////////////////////////////////////////////////////////
// ricerca area dal codice
////////////////////////////////////////////////////////////////////////////

function findAreaFromCode(code) {
	if (found_areas_from_code!='') map.removeOverlay(found_areas_from_code);

	performLoading();
    
	found_areas_from_code=new GGeoXml(clean_url_to_fill+'&alpha_id='+code,loaded_callback);
	map.addOverlay(found_areas_from_code);
}

function AreaToggleKml(code) {
	current_value='D20100730B';
	$.blockUI({ message: null });
	$('.'+radios_class).attr('disabled',false);
	$('#'+radios_class+'_'+id_index).attr('disabled',true);

	map.clearOverlays();
	geoOverlay=new GGeoXml(clean_url_to_fill+current_value+'&id_luogo='+code);
	var clean_url_to_fill_area = 'http://www.livornoeffettovenezia.it/index.php?page=google_generateKML&geotype=D20100730B&start=0'
	
	geoOverlay=new GGeoXml(clean_url_to_fill_area);
	map.addOverlay(geoOverlay);
}

////////////////////////////////////////////////////////////////////////////
// visualizza un solo kml statico
////////////////////////////////////////////////////////////////////////////

function displayKml(kml_url) {
		
	if (kml_url!='') {

		performLoading();
		toggleArray[0]=new GGeoXml(kml_url,loaded_callback);
		map.addOverlay(toggleArray[0]);
	}
}

function radioToggleKml(current_value,radios_class,id_index) {
	
	/*$.blockUI({ message: null });
	$('.'+radios_class).attr('disabled',false);
	$('#'+radios_class+'_'+id_index).attr('disabled',true);
	*/
	//map.clearOverlays();
	
	url_kml=clean_url_to_fill+current_value+'&start=0';
	geoOverlay=new GGeoXml(url_kml);
	map.addOverlay(geoOverlay);
}
