var isIE=document.all?true:false;
var isDOM=document.getElementById?true:false;
var isNS4=document.layers?true:false;
var XMLHTTP;

var center = new GLatLng(centreLat, centreLon);
var mapBounds=new GLatLngBounds(new GLatLng(latBottomRight,lngBottomRight),new GLatLng(latUpperLeft,lngUpperLeft));
var map = null;
var custommap = null;
var lays=new String();
var wmsLayers = null;
var gisServer='http://81.29.201.19/servlet/GisGateway?';

var beniculturali = new Array();
var etnografia = new Array();
var ambiente = new Array();

var pernottamenti = new Array();
var luoghi = new Array();
var sport = new Array();
var ristorazione = new Array();

var result = new Array();

var pointsRighello = new Array();
var path = null;
var start_marker = null;
var righello=false;

var mini_comuni	= new Array();
var mini = null;
var versanti 	= new GGroundOverlay("img/versanti.png", new GLatLngBounds(new GLatLng(44.54732,9.55091), new GLatLng(44.72812,10.09244)));

//wms layer parameters
var tileCountry = new GTileLayer(new GCopyrightCollection(""),9,maxZoom);
tileCountry.myLayers='';
tileCountry.myBaseURL=gisServer+'highlight=off&';
tileCountry.getTileUrl=CustomGetTileUrl;
tileCountry.myOpacity=0.75;
tileCountry.getOpacity=customOpacity;
//end wms

preload_image_object = new Image();
image_url = new Array();
image_url[0] = "img/lente_.gif";
image_url[1] = "img/righello_.gif";

for(var i=0;i<image_url.length;i++) 
	preload_image_object.src = image_url[i];

/*-----------------------------------------------*/

function load() {
	if (GBrowserIsCompatible()) {
		if(document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#SVG","1.1")){
		  _mSvgEnabled = true;
		  _mSvgForced  = true;
		}

		var tilelayers = [new GTileLayer(new GCopyrightCollection(''), 12, maxZoom)];
		tilelayers[0].getTileUrl = function(a,b) {
			return "../orchidea/Zoom"+map.getZoom()+"Maps/"+a.x+"_"+a.y+"_"+map.getZoom()+".jpg";
		}
		custommap = new GMapType(tilelayers, G_SATELLITE_MAP.getProjection(), "custommap", {errorMessage:""});
	
		map = new GMap2(document.getElementById("map"));

		var mt = map.getMapTypes();
		for (var i=0; i<mt.length; i++) {
			mt[i].getMaximumResolution = function() {return maxZoom;}
			mt[i].getMinimumResolution = function() {return minZoom;}
		}

		wmsLayers = new GTileLayerOverlay(tileCountry);
		
		map.addMapType(custommap);
		
		map.setCenter(center, startZoom);
		map.addControl(new GScaleControl());
		map.addControl(new GSmallMapControl(),new GControlPosition(G_ANCHOR_TOP_LEFT,new GSize(3,25)));
		map.addControl(new GZoomControl());	

		ovMap=new GOverviewMapControl(new GSize(120, 80));
		map.addControl(ovMap);

		//mini=ovMap.getOverviewMap();
                mini=GOverviewMapControl.prototype.getOverviewMap;
		//mini.disableDragging();
		
		GEvent.addListener(mini,"load",function(){
			GDownloadUrl("xml/mini_comuni.xml", function(data) {
			  var xml = GXml.parse(data);
			  var marks = xml.documentElement.getElementsByTagName("mark");
			  for (var i = 0; i < marks.length; i++)
			    mini.addOverlay(createLayer(marks[i],"mini_comuni","#000000",""));
			});
			mini.setCenter(center, (startZoom-2));
		});

		GEvent.addListener(mini, "maptypechanged", function() {
			if (map.getCurrentMapType().getName()=="custommap")
				mini.setCenter(center, (startZoom-2), G_SATELLITE_MAP);
		});

		GEvent.addListener(map, "click", mapClick);
		GEvent.addListener(map, "moveend", function() {
			checkBounds();
			mini.setCenter(center, (startZoom-2));
		});
		GEvent.addListener(map, "zoomend", function() {
			mini.setCenter(center, (startZoom-2));
			document.getElementById('zoomLevel').innerHTML="&nbsp;Zoom: "+map.getZoom()+"&nbsp;";
			for(var i=0;i<layers.length;i++) {
				if(!checkZoom(layers[i]) && eval("document.layer."+layers[i]+".checked==true;")) {
					eval("document.layer."+layers[i]+".checked=false;");
					for (var j = 0; j < eval(layers[i]).length; j++) {
						map.removeOverlay(eval(layers[i])[j]);
					}
				}
				if(map.getZoom()<9)
					map.removeOverlay(wmsLayers);
			}
		});
		
		map.getContainer().appendChild(document.getElementById("poweredby"));
		document.getElementById("poweredby").style.display = 'block';
		map.getContainer().appendChild(document.getElementById("zoomLevel"));
		document.getElementById("zoomLevel").style.display = 'block';
		map.getContainer().appendChild(document.getElementById("loading"));
	}
}

function help() {
	window.open('about:blank','info','width=400,height=200,scrollbars=yes');
}

function stampa() {
	window.print();
}

function popup(id,layer,start,key) {
	var url="GetInfoServlet?id="+id+"&layer="+layer+"&start="+start+"&key="+key;
	window.open(url,'info','width=400,height=200,scrollbars=yes');
}

function popupwms(lat,lng,layer) {
	var url="GetInfoServlet?layer="+layer+"&lat="+lat+"&lng="+lng+"&xmlsrc=true";
	window.open(url,'info','width=400,height=200,scrollbars=yes');
}

function changeUnit(field) {
	if(field.selectedIndex==0 && path!=null)
		document.getElementById("metri").innerHTML=(path.getLength()/1000).toFixed(3);
	else if(field.selectedIndex==1 && path!=null)
		document.getElementById("metri").innerHTML=(path.getLength()/1609.344).toFixed(3);
}

function mapClick(marker, point) {
    if (righello) {
        pointsRighello.push(point);
        if (pointsRighello.length == 1) {
            map.addOverlay(start_marker = new GMarker(point, {title:"start"}));
		}
		else {
			if(path!=null)
				map.removeOverlay(path);
			path = new GPolyline(pointsRighello, "#0000FF", 4, 0.8);
			map.addOverlay(path);
			if(document.getElementById("unita").selectedIndex==1)
				document.getElementById("metri").innerHTML=(path.getLength()/1609.344).toFixed(3);
			else
				document.getElementById("metri").innerHTML=(path.getLength()/1000).toFixed(3);
		}
    }
    if (point != null) {
	    var utm = ToUtm(point.lat(),point.lng());
	    var latClic=utm[0];
	    var lngClic=utm[1];
		GDownloadUrl("GetDataByIdServlet?lat="+latClic+"&lng="+lngClic+"&layer="+tileCountry.myLayers, function(data, responseCode) {
			if(data != "\r\n" && data != "\n" && data!=null && data!="" && responseCode==200) {
				map.openInfoWindowHtml(point,data);
			}
		});
	}

}

function enableRighello(field) {
	document.getElementById("metri").innerHTML="0.000"
	if (righello) {
		field.src="img/righello.gif";
		righello=false;
		if(path!=null) {
			map.removeOverlay(path);
			path=null;
		}
		if(start_marker!=null)
			map.removeOverlay(start_marker);
		pointsRighello.splice(0,pointsRighello.length);
	}
	else {
		field.src="img/righello_.gif";
		righello=true;
	}
}

function setType(type) {
	switch(type.value) {
		case "n":
			map.setMapType(G_NORMAL_MAP);
		break;
		case "s":
			map.setMapType(G_SATELLITE_MAP);
		break;
		case "h":
			map.setMapType(G_HYBRID_MAP);
		break;
		case "c":
			map.setMapType(custommap);
		break;
	}
}

function clearAll() {
	pointsRighello.splice(0,pointsRighello.length);
	result.splice(0,result.length);
	document.getElementById("risultati").innerHTML = "<div align=\"center\" class=\"testo\"><br><strong>Inserire una chiave di ricerca e selezionare un livello</strong></div>";
	map.clearOverlays();
	lays='';
	tileCountry.myLayers='';
	tileCountry.myBaseURL=gisServer+'highlight=off&';
	for(var i=0;i<layers.length;i++)
		eval("document.layer."+layers[i]+".checked=false;");
}

function hideSidebar() {
	if(document.getElementById('sidebar').style.display == "none") {
		if(document.getElementById('resultSearch').style.display == "none") {
			document.getElementById('map').style.width='780px';
		}
		else {
			document.getElementById('map').style.width='550px';
		}
		document.getElementById('imgside').src="img/hide-arrow.png";
	}
	else {
		if(document.getElementById('resultSearch').style.display == "none") {
			document.getElementById('map').style.width='962px';
		}
		else {
			document.getElementById('map').style.width='732px';
		}
		document.getElementById('imgside').src="img/show-arrow.png";
	}
	hideDiv('sidebar');
	map.checkResize();
}

function hideSearchBar() {
	if(document.getElementById('resultSearch').style.display == "none") {
		if(document.getElementById('sidebar').style.display == "none") {
			document.getElementById('map').style.width='732px';
		}
		else {
			document.getElementById('map').style.width='550px';
		}
		document.getElementById('imgsearch').src="img/show-arrow.png";
	}
	else {
		if(document.getElementById('sidebar').style.display == "none") {
			document.getElementById('map').style.width='962px';
		}
		else {
			document.getElementById('map').style.width='780px';
		}
		document.getElementById('imgsearch').src="img/hide-arrow.png";
	}
	hideDiv('resultSearch');
	map.checkResize();
}

function showSearchBar() {
	if(document.getElementById('resultSearch').style.display == "none") {
		if(document.getElementById('sidebar').style.display == "none") {
			document.getElementById('map').style.width='732px';
		}
		else {
			document.getElementById('map').style.width='550px';
		}
		document.getElementById('imgsearch').src="img/show-arrow.png";
		hideDiv('resultSearch');
		map.checkResize();
	}
}

function hideDiv(_w) {
	if (isDOM) {
		if (document.getElementById(_w).style.display=='none')
			document.getElementById(_w).style.display='block';
		else
			document.getElementById(_w).style.display='none';
	}
	else if (isIE) {
		if (_h=='s')
			eval("document.all."+_w+".style.display='block';");
		if (_h=='h')
			eval("document.all."+_w+".style.display='none';");
	}
	else if(isNS4) {
		if (_h=='s')
			eval("document.layers['"+_w+"'].display='block';");
		if (_h=='h')
			eval("document.layers['"+_w+"'].display='none';");
	}
}

function showWms(field,id,minZoom,maxZoom) {
	if(map.getZoom()>=minZoom && map.getZoom()<=maxZoom) {
		if(wmsLayers!=null)
			map.removeOverlay(wmsLayers);
	
		if(field.checked)
			lays=lays.concat(id+',');
		else
			lays=lays.replace(id+',','');
	
		tileCountry.myLayers=lays;
		if(lays!=null && lays!="")
			map.addOverlay(wmsLayers);
	}
	else {
		field.checked=false;
		window.alert("Layer visibile tra i livelli di zoom "+minZoom+" e "+maxZoom+"!");
	}
}

function show(field,color,img,minZoom,maxZoom) {
	if(map.getZoom()>=minZoom && map.getZoom()<=maxZoom) {
		if (field.checked) {
		  	document.getElementById("loading").style.display = 'block';
			if(eval(field.value).length!=0) {
			  for (var i = 0; i < eval(field.value).length; i++)
				  map.addOverlay(eval(field.value)[i]);
			  document.getElementById("loading").style.display = 'none';
			}
			else {
				GDownloadUrl("GetDataLayer?layer="+field.value, function(data) {
				  var xml = GXml.parse(data);
				  var marks = xml.documentElement.getElementsByTagName("mark");
				  if(color=="" || color==null)
				  	color = "#000000"
				  for (var i = 0; i < marks.length; i++)
					  map.addOverlay(createLayer(marks[i],field.value,color,img));
	  			  document.getElementById("loading").style.display = 'none';
				});
			}
		}
		else {
			for (var i = 0; i < eval(field.value).length; i++) {
				map.removeOverlay(eval(field.value)[i]);
			}
		}
	}
	else {
		field.checked=false;
		window.alert("Layer visibile tra i livelli di zoom "+minZoom+" e "+maxZoom+"!");
	}
}

function resetZoom() {
	map.setCenter(center, startZoom);	
}

function checkBounds() {
	if (mapBounds.contains(map.getCenter())) {
		return;
	}
	var C = map.getCenter();
	var X = C.lng();
	var Y = C.lat();
	
	var AmaxX = mapBounds.getNorthEast().lng();
	var AmaxY = mapBounds.getNorthEast().lat();
	var AminX = mapBounds.getSouthWest().lng();
	var AminY = mapBounds.getSouthWest().lat();
	
	if (X < AminX)
		X = AminX;
	if (X > AmaxX)
		X = AmaxX;
	if (Y < AminY)
		Y = AminY;
	if (Y > AmaxY)
		Y = AmaxY;
	map.setCenter(new GLatLng(Y,X));
}

function showImg(field) {
	if(field.checked)
		map.addOverlay(eval(field.value));
	else
		map.removeOverlay(eval(field.value));
}

function showIconResult(id,layer,icona,lat,lng,showInfo,idci) {
	point = new GLatLng(lat,lng);
	document.getElementById("loading").style.display = 'block';

	var icon = new GIcon();
	icon.image="img/"+icona;
	icon.shadow="img/shadow.png";
	icon.iconSize = new GSize(18, 18);
	icon.iconAnchor = new GPoint(7, 15);
	icon.infoWindowAnchor = new GPoint(7, 1);
	var tot=result.push(new GMarker(point,icon));
	GEvent.addListener(result[tot-1], "click", function() {
		GDownloadUrl("GetDataByIdServlet?layer="+layer+"&id="+id+"&idci="+idci, function(data, responseCode) {
			result[tot-1].openInfoWindowHtml(data);
		});
	});
	if(showInfo) {
		GDownloadUrl("GetDataByIdServlet?layer="+layer+"&id="+id+"&idci="+idci, function(data, responseCode) {
			result[tot-1].openInfoWindowHtml(data);
		});
	}
	map.addOverlay(result[tot-1]);
	document.getElementById("loading").style.display = 'none';
}

function createLayer(node, field, color, img) {
	var geom = node.getElementsByTagName("geo");
	var p = geom[0].getElementsByTagName("p");
	if(geom[0].getAttribute("type")=="point") {
		var icon = new GIcon();
		icon.image="img/"+img;
		icon.iconSize = new GSize(18, 18);
		icon.iconAnchor = new GPoint(7, 15);
		icon.infoWindowAnchor = new GPoint(10, 1);
		var tot=eval(field).push(new GMarker(new GLatLng(parseFloat(p[0].getAttribute("lat")),parseFloat(p[0].getAttribute("lng"))),icon));
		GEvent.addListener(eval(field)[tot-1], "click", function() {
			var id = geom[0].getAttribute("id");
			var idci = 0;
			if(field=="etnografia" || field=="beniculturali" || field=="ambiente")
				idci=geom[0].getAttribute("idci");
			GDownloadUrl("GetDataByIdServlet?layer="+field+"&id="+id+"&idci="+idci, function(data, responseCode) {
				eval(field)[tot-1].openInfoWindowHtml(data);
			});
		});
		return eval(field)[tot-1];
	}
	else if(geom[0].getAttribute("type")=="region") {
		var pts = new Array();
		for (var i = 0; i < p.length; i++)
			pts[i]=new GLatLng(parseFloat(p[i].getAttribute("lat")),parseFloat(p[i].getAttribute("lng")));
		eval(field).push(new GPolygon(pts,color,2,0.5,color,0.5));

		if(field!="mini_comuni") {
			GEvent.addListener(eval(field)[eval(field).length-1], "click", function(point) {
				var id = geom[0].getAttribute("id");
				var idci = 0;
				GDownloadUrl("GetDataByIdServlet?layer="+field+"&id="+id+"&idci="+idci, function(data, responseCode) {
					map.openInfoWindowHtml(point,data);
				});
			});
		}
		return eval(field)[eval(field).length-1];
	}
	else if(geom[0].getAttribute("type")=="multiline") {
		var pts = new Array();
		for (var i = 0; i < p.length; i++)
			pts[i]=new GLatLng(parseFloat(p[i].getAttribute("lat")),parseFloat(p[i].getAttribute("lng")));
		eval(field).push(new GPolyline(pts,color,2,0.5));
		return eval(field)[eval(field).length-1];
	}
}

function showWmsResult(wmsid,key,start) {
	tileCountry.myBaseURL=gisServer+'highlight='+wmsid+'&keyword='+key+'&records='+start+','+step+'&';
	tileCountry.myLayers=wmsid;
	lays=lays.concat(wmsid+',');
	map.addOverlay(wmsLayers);
}

function showIconWmsResult(id,wmsid,lat,lng,start,key) {
	GDownloadUrl("GetDataByIdServlet?layer="+wmsid+"&id="+id+"&start="+start+"&key="+key, function(data, responseCode) {
		map.openInfoWindowHtml(new GLatLng(lat,lng),data);
	});
}

function richiesta(layer,key,start) {
	if(checkZoom(layer)) {
		showSearchBar();
		if (key.length>0 && layer.length>0) {
			clearAll();
			document.getElementById("risultati").innerHTML = "<div align=\"center\"><strong><br /><br /><br />Caricamento in corso...</strong><br /><img src=\"img/loading.gif\" border=\"0\"></div>";
			var url="GetResultServlet?layer="+layer+"&key="+key+"&start="+start;
			XMLHTTP = RicavaBrowser(CambioStato);
	        XMLHTTP.open("GET", url, true);
	        XMLHTTP.send(null);
	    }
	    else {
		    document.getElementById("risultati").innerHTML = "<div align=\"center\" class=\"testo\"><br><strong>Inserire una chiave di ricerca e selezionare un livello</strong></div>";
		}
	}
	else {
		window.alert("Layer non visibile a questo livello di zoom!");
	}
}

function CambioStato() {
    if (XMLHTTP.readyState == 4) {
        var R = document.getElementById("risultati");
        R.innerHTML = XMLHTTP.responseText;
    }
}

function RicavaBrowser(QualeBrowser) {
    if (navigator.userAgent.indexOf("MSIE") != (-1)) {
        var Classe = "Msxml2.XMLHTTP";
        if (navigator.appVersion.indexOf("MSIE 5.5") != (-1)); {
            Classe = "Microsoft.XMLHTTP";
        } 
        try {
            OggettoXMLHTTP = new ActiveXObject(Classe);
            OggettoXMLHTTP.onreadystatechange = QualeBrowser;
            return OggettoXMLHTTP;
        }
        catch(e) {
            alert("Errore: l'ActiveX non verrą eseguito!");
        }
    }
    else if (navigator.userAgent.indexOf("Mozilla") != (-1)) {
        OggettoXMLHTTP = new XMLHttpRequest();
        OggettoXMLHTTP.onload = QualeBrowser;
        OggettoXMLHTTP.onerror = QualeBrowser;
        return OggettoXMLHTTP;
    }
    else {
        alert("L'esempio non funziona con altri browser!");
    }
}
