// variabili per posizione altre informazioni
var locationhost = location.host;

var currentTime = new Date();

var mgr
var infowindow;

/* Definisco l'icona di default */

	var baseIcon = new google.maps.MarkerImage('/images/googlemaps/baseIcon.png',
	  // This marker is 37 pixels wide by 52 pixels tall.
		  new google.maps.Size(37, 52),
	  // The origin for this image is 0,0.
		  new google.maps.Point(0, 0),
	  // The anchor for this image is the base of the flagpole at 0,32.
		  new google.maps.Point(0, 52));
	//  var shadowIcon = new google.maps.MarkerImage('images/beachflag_shadow.png',
	//  // The shadow image is larger in the horizontal dimension
	//  // while the position and offset are the same as for the main image.
	//      new google.maps.Size(37, 32),
	//      new google.maps.Point(0, 0),
	//      new google.maps.Point(0, 32));
	//  // Shapes define the clickable region of the icon.
	  // The type defines an HTML <area> element 'poly' which
	  // traces out a polygon as a series of X,Y points. The final
	  // coordinate closes the poly by connecting to the first
	  // coordinate.
	  var shapeIcon = {
		  coord: [18,18,16],
		  type: 'circle'
	  };
		 var simpleIcon = new google.maps.MarkerImage('/images/googlemaps/simpleIcon.png',
		 // This marker is 37 pixels wide by 52 pixels tall.
		  new google.maps.Size(10,10),
		 // The origin for this image is 0,0.
		  new google.maps.Point(0, 0),
		 // The anchor for this image is the base of the flagpole at 0,32.
		  new google.maps.Point(5, 5));

/* Definisco le icone delle risorse e dei merchant */
	  var gicons = [];
	  gicons["unit"] = "http://maps.google.com/mapfiles/kml/pal2/icon28.png";
	  gicons["merchant"] = "http://maps.google.com/mapfiles/kml/pal2/icon10.png";
	  gicons["type1"] = "http://maps.google.com/mapfiles/kml/pal5/icon55.png";// HOTEL 1
	  gicons["type2"] = "http://maps.google.com/mapfiles/kml/pal5/icon48.png";// AGENZIA
	  gicons["type3"] = "http://maps.google.com/mapfiles/kml/pal5/icon58.png";// CAMPING
	  gicons["type4"] = "http://maps.google.com/mapfiles/kml/pal2/icon40.png";// RISTORANTI
	  gicons["foto"] = "http://maps.google.com/mapfiles/kml/pal4/icon46.png"; //foto
	  gicons["video"] = "http://maps.google.com/mapfiles/kml/pal2/icon30.png"; //video


// recupera tutte le informazioni da un url
function getUrlMarker(url,tMap) {

	mgr = new MarkerManager(tMap);
	google.maps.event.addListener(mgr, 'loaded', function(){
		jQuery.get(url, function (data) {
			var batch = [];
			jQuery(data).find("marker").each(function () {
				var xmlMarker = jQuery(this);
				var latlng = new google.maps.LatLng(
										parseFloat(xmlMarker.attr("lat")),
										parseFloat(xmlMarker.attr("lng"))
							 );
				var urlhtml = xmlMarker.attr("url");
				var icon = xmlMarker.attr("icon");
				var marker = createMarkerURL(latlng, urlhtml, gicons[icon], tMap);
				// icona letto
							if (icon==="merchant")
							{
							  mgr.addMarker(marker, 1,16);
							}
				batch.push(marker);
			});
			mgr.addMarkers(batch, 12);
			mgr.refresh();
		});
	});	
}
function getUrlMarkerMap3D(url, tMap, hidepoint) {

//	mgr = new MarkerManager(tMap);
//	google.maps.event.addListener(mgr, 'loaded', function () {
	jQuery.get(url, function (data) {
		//var batch = [];
		jQuery($(data)).find("marker").each(function () {
			var xmlMarker = jQuery(this);
			var point = new google.maps.LatLng(parseFloat(xmlMarker.attr("lat")), parseFloat(xmlMarker.attr("lng")));
			var point2 = new google.maps.LatLng(parseFloat(xmlMarker.attr("lat3d")), parseFloat(xmlMarker.attr("lng3d")));
			//				var point2 = new google.maps.LatLng(parseFloat(tGeneralMarker[i].lat3d), parseFloat(tGeneralMarker[i].lng3d));
			var category = xmlMarker.attr("category");
			var urlhtml = xmlMarker.attr("url");
			var icon = xmlMarker.attr("icon");
			if (icon === "simpleIcon") {
				icon = simpleIcon
			}
			//var marker = createMarkerURL(latlng, urlhtml, simpleIcon, tMap);
			if (point.lat() + '' !== '0' && point.lat() + '' !== 'NaN') {

				var marker = createMarkerURL3D(point, urlhtml, icon, tMap);
				marker.mycategory = category;
				marker.mytitle = xmlMarker.attr("title");
				marker.point = point;
				marker.point2 = point2;
				marker.divMarker = '';
				if (hidepoint) 	{			
					marker.setMap(null)
				}else{	
					marker.setMap(tMap)
				}
				gmarkers.push(marker);
			}
			// icona letto
			//				if (icon === "merchant") {
			//					mgr.addMarker(marker, 1, 16);
			//				}
			//				batch.push(marker);
		});
		//onMapTypeChange();
		//			mgr.addMarkers(batch, 12);
		//			mgr.refresh();
		//		});
	});
}

function removeAllMarkerMap3D(allMarker) {
	if (infowindow) infowindow.close();
	currentState.infoWindowOpen = null;
	currentState.infoWindowIsOpen = false;

	var tmTodlete = []
	$(gmarkers).each(function (i, marker) {
		if (allMarker) {
			tmTodlete.push(gmarkers[i])
			gmarkers[i].setMap(null)
		} else { 
			if (gmarkers[i].typeMarker === '3D') {
				tmTodlete.push(gmarkers[i])
				gmarkers[i].setMap(null)
				//delete gmarkers[i];

				//gmarkers.slice(i, 1);
			};
		}
	});
	$(tmTodlete).each(function (i) {
		RemoveElement(gmarkers, tmTodlete[i])
	});
}

function removeAllGeneratedMarkerMap3D() {
	removeAllMarkerMap3D(false)
}

function RemoveElement(arr, elem) {
	var idx;
	for (idx = 0; idx < arr.length; ++idx) {
		if (arr[idx] != elem)
			continue;
		break;
	}

	if (idx < arr.length) // the element was found
		arr.splice(idx, 1);
}
function getAllGeneratedMarkerMap3D(tMap,tGeneralMarker) {
	 for (var i = 0; i < tGeneralMarker.length; i++) {    
		 var point = new google.maps.LatLng(parseFloat(tGeneralMarker[i].lat),parseFloat(tGeneralMarker[i].lng));
		 var point2 = new google.maps.LatLng(parseFloat(tGeneralMarker[i].lat3d),parseFloat(tGeneralMarker[i].lng3d));
		 var urlhtml = tGeneralMarker[i].url;
		 var category = tGeneralMarker[i].category;
		 var letterIcon = tGeneralMarker[i].iconImage;
		 
		 var marker = createMarkerURLComplex(point, urlhtml, letterIcon, tMap);
		 //var marker = createMarkerURLComplex(point, urlhtml, baseIcon, tMap);
		 
		 marker.mycategory = category;
		 marker.mytitle = tGeneralMarker[i].title;
		 marker.point = point;
		 marker.point2 = point2;
		 marker.divMarker = tGeneralMarker[i].divMarker;
		 marker.typeMarker = '3D';
		 marker.setMap(tMap)
		 //tMap.addOverlay(marker);
		 gmarkers.push(marker);
		}
		$(gmarkers).each(function (i, marker) {
			if (gmarkers[i].divMarker !== '') { 
				/*--------------
				Aggiungo gli eventi per il click....
				----------------*/
				var tDiv = document.getElementById(gmarkers[i].divMarker)
				$(tDiv).find(".imgGMark").click(function () {
					window.scrollTo(0, 0);
					google.maps.event.trigger(marker, 'click');
				});
			}
		});

	// richiamo la funzione di controllo visualizzazione dei marker 
	onMapTypeChange();
}


// recupera tutti i merchants di un determinato tipo
var gmarkers = [];







function sortCategoryHandler(thisObject,thatObject) {	
	if (thisObject.mycategory > thatObject.mycategory)
	{
		return 1;
	}
	else if (thisObject.mycategory < thatObject.mycategory)
	{
		return -1;
	}
	return 0;
  }


jQuery.extend(jQuery.expr[':'], {
  containsIgnoreCase: "(a.textContent||a.innerText||jQuery(a).text()||'').toLowerCase().indexOf((m[3]||'').toLowerCase())>=0"
});

function deleteSearch(){
	$("#txbSearch").val("");
	$("#list li").each(function(){
				this.style.display ="";
			});
}

function getSearch(obj){
	if(obj.value!==''){
		$("#list li").each(function(){
					this.style.display ="none";
				});
		$("#list li:containsIgnoreCase("+obj.value+")").each(function(){
					this.style.display ="";
				});
	}else{
		$("#list li").each(function(){
					this.style.display ="";
				});
	}
}
/*------lista marker ------*/

function displayPoint(marker, index){
					GEvent.trigger(marker,'click');
					currentState.infoWindowOpen=marker;
//					map.panTo(marker.getLatLng());
					marker.show();
				}

function createMarkerURL(latlng, urlhtml, icon, currentMap) {
	var marker = new google.maps.Marker({
		position: latlng,
		icon:icon,
		map: currentMap,
		zIndex: 1
		});
		google.maps.event.addListener(marker, "click", function () {
			if (infowindow) infowindow.close();
			jQuery.get(urlhtml, function (data) {
				var contentString = '<div style="margin-right:10px;height:300px;width:220px;overflow:auto;">' + data + '</div>';
				infowindow = new google.maps.InfoWindow({ content: contentString });
				infowindow.open(currentMap, marker);
			});
		});
	return marker;
}
function createMarkerURL3D(latlng, urlhtml, icon, currentMap) {
	var marker = new google.maps.Marker({
		position: latlng,
		icon: icon,
		map: currentMap,
		zIndex: 1
	});
	if (urlhtml !== '') {
		google.maps.event.addListener(marker, "click", function () {
			if (infowindow) infowindow.close();
			jQuery.get(urlhtml, function (data) {
				var infoDiv = document.createElement('div');
				infoDiv.innerHTML = '<div style="margin-right:10px;height:300px;width:500px;">' + data + '</div>';
				makeTabFromDiv($(infoDiv));
				makeGalleryFromDiv($(infoDiv));
				infowindow = new google.maps.InfoWindow({ content: infoDiv });
				infowindow.open(currentMap, marker);
				currentState.infoWindowIsOpen = true;
			});
			currentState.infoWindowOpen = marker;
		});
	}
	return marker;
}

function createMarkerURLComplex(latlng, urlhtml, icon, currentMap) {
	var marker = new google.maps.Marker({
		position: latlng,
		icon:icon,
		map: currentMap,
		zIndex: 80
		});
		if (urlhtml !== '') {
			google.maps.event.addListener(marker, "click", function () {
				if (infowindow) infowindow.close();
				currentState.infoWindowOpen = null;
				if (marker.getMap() != null) {
					marker.setMap(null)
					marker.setMap(currentMap)
					jQuery.get(urlhtml, function (data) {
						var infoDiv = document.createElement('div');
						infoDiv.innerHTML = '<div style="margin-right:10px;height:300px;width:500px;">' + data + '</div>';
						makeTabFromDiv($(infoDiv));
						makeGalleryFromDiv($(infoDiv));
						infowindow = new google.maps.InfoWindow({ content: infoDiv });
						infowindow.open(currentMap, marker);
						currentState.infoWindowIsOpen = true;
					});
					currentState.infoWindowOpen = marker;
				} else {
					csscody.alert("No position")
					//alert("No position")
				}
			});
		}
//	google.maps.event.addListener(marker, "infowindowopen", function() {
//		if (marker.getLatLng().lat()==0)
//		{
//				marker.closeInfoWindow();
//		}
//	});
//	google.maps.event.addListener(marker, "infowindowclose", function() {
//		currentState.infoWindowIsOpen = false;
//	});
	return marker;
}

function makeTabFromDiv(tDiv) {
	$(tDiv).find(".tab_content").hide(); //Hide all content
	$(tDiv).find("ul.tabs li:first").addClass("active").show();
	$(tDiv).find(".tab_content:first").show();
//
//	//On Click Event
	$(tDiv).find("ul.tabs li").click(function() {
		$(tDiv).find("ul.tabs li").removeClass("active"); //Remove any "active" class
		$(this).addClass("active"); //Add "active" class to selected tab
		$(tDiv).find(".tab_content").hide(); //Hide all tab content
		var activeTab = $(this).find("a").attr("href").split("#")[1]; //Find the href attribute value to identify the active tab content
		$("#" + activeTab).fadeIn();
////		if ($.browser.msie)
////			{$(activeTab).show();}
////		else
////			{$(activeTab).fadeIn();}
		return false;
	});
}

function makeGalleryFromDiv(tDiv) {
//alert($(tDiv).find(".jCarouselLite").html())
////		$(tDiv).find(".jCarouselLite").jCarouselLite({
////			speed: 800,
////			visible: 2
////		});

		$(tDiv).find(".photogallerypopup img").click(function() {
			$(tDiv).find("img.imgGalleryBigpopup").attr("src", $(this).attr("srcbig"));
		});
}

function showotherdetails() {
}

/*------------------------------------------*/

/*---------------------------------*/
// recupera tutte le informazioni georeferenziate di un merchant
function getGeolocationMarker(tMap) {
	mgr = new MarkerManager(tMap);
	downloadUrl("/searchmapgeolocazionegoogle.aspx", function(data, responseCode) {  
	 var xml = GXml.parse(data);  
	 var markers = xml.documentElement.getElementsByTagName("marker");  
	 var batch = [];
	 for (var i = 0; i < markers.length; i++) {    
		var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),parseFloat(markers[i].getAttribute("lng")));
		var urlhtml = markers[i].getAttribute("url");
		var icon = markers[i].getAttribute("icon");
			if (icon == "type1") {
				var marker = createMarkerURLGeolocazione(point, urlhtml, gicons["foto"], startGallery, 0);
			}else{
				var marker = createMarkerURLGeolocazione(point, urlhtml, gicons["video"]);
			}
//		var marker = createMarkerURL(point,urlhtml,gicons[icon]);
		batch.push(marker);
		}
	mgr.addMarkers(batch, 12);
	mgr.refresh();
	});
}

function createMarkerURLGeolocazione(point,urlhtml,icon, callbackfunction, args) {
	var marker = new GMarker(point,icon);
	GEvent.addListener(marker, "click", function() {
		var request = GXmlHttp.create();
		request.open("GET", urlhtml.replace("%26","&"), true);
		request.onreadystatechange = function() {  
			if (request.readyState == 4) {
				marker.openInfoWindowHtml('<div style="height:310px;width:330px;overflow:auto;">' + request.responseText + '</div>'); 
				if (callbackfunction) {
					setTimeout(callbackfunction,1000);
				}
			}
		}
		request.send(null);
	});
	return marker;
}

var georssLayer,georssLayer2
var georssLayerVisible,georssLayer2Visible

function OtherInfoControl(controlDiv, tmap) {  
	// Set CSS styles for the DIV containing the control  
	// Setting padding to 5 px will offset the control  
	// from the edge of the map  controlDiv.style.padding = '5px';  
	 controlDiv.style.padding = '5px';
	// Set CSS for the control border  
	var controlUI = document.createElement('DIV');
	
//	controlUI.setAttribute("class","menugoogle");
	controlUI.title = 'Info';
	$(controlUI).attr('class','menugoogle');

	controlDiv.appendChild(controlUI);
	// Set CSS for the control interior  
	var controlText = document.createElement('DIV');
	controlText.style.fontFamily = 'Arial,sans-serif';
	controlText.style.fontSize = '12px';
	controlText.style.paddingTop = '4px';
	controlText.style.paddingBottom = '4px';
	controlText.style.paddingLeft = '4px';
	controlText.style.paddingRight = '4px';
	controlText.innerHTML = 'Info';
	controlUI.appendChild(controlText);
	// Setup the click event listeners: simply set the map to Chicago  
	google.maps.event.addDomListener(controlText, 'click', function() {    
		if (georssLayerVisible)
		{
			georssLayer.setMap(null);
		}else{
			georssLayer.setMap(currentMap);
		}
		georssLayerVisible = !georssLayerVisible;
		if (georssLayer2Visible)
		{
			georssLayer2.setMap(null);
		}else{
			georssLayer2.setMap(currentMap);
		}
		georssLayer2Visible = !georssLayer2Visible;
	});

}
function addOtherInfo(tMap){
	georssLayer = new google.maps.KmlLayer("http://" + location.host + "/include/xml/mapsgoogle/Piste_ciclabili.kml");
	georssLayer.setMap(tMap);
	georssLayerVisible =true
	
	georssLayer2 = new google.maps.KmlLayer("http://" + location.host + "/include/xml/mapsgoogle/informations.kml");
	georssLayer2.setMap(tMap);
	georssLayer2Visible =true

	var otherInfoControlDiv = document.createElement('DIV');  
	var otherInfoControl = new OtherInfoControl(otherInfoControlDiv, tMap);  
	otherInfoControlDiv.index = 1;  
	tMap.controls[google.maps.ControlPosition.TOP_CENTER].push(otherInfoControlDiv);
}


// == shows all markers of a particular category, and ensures the checkbox is checked ==
function showhide(category) {
	if (infowindow) infowindow.close();
	for (var i=0; i<gmarkers.length; i++) {
	  if (gmarkers[i].mycategory == category.value) {
		if (category.checked)
		{
			gmarkers[i].setMap(currentMap)
		} else {
			gmarkers[i].setMap(null)
			// == close the info window, in case its open on a marker that we just hid
		}
	  }
	}
}
// == shows all markers of a particular category, and ensures the checkbox is checked ==
function hideall() {
	georssLayer.setMap(null);
	georssLayer2.setMap(null);
	georssLayerVisible = false;
	georssLayer2Visible = false;
	onMapTypeChange()
	if (infowindow) infowindow.close();
	for (var i=0; i<gmarkers.length; i++) {
			gmarkers[i].setMap(null)
	}
	$('.otherinfo').find(':checkbox').each(function() {
		showhide(this)
	});
}

