// JScript File
/*
 * Google MAP jQuery interface
 * Copyright (c) 2009  Oliver Astrologo
 * Dual licensed under MIT and GPL.
 * @author  Oliver Astrologo
 * @version 1.1
 */

var side_bar_html;
var map;
var counter = 0;
var gmarkers = [];
var htmls = [];
var geocoder = null;
var selmarker = false;
var responseLat = 41.895465;
var responseLng = 12.482324;
var defaultMapZoom = 10;
var mapIsInitialized = false;
var firstSearch = false;
var dataResponse;
var mapCenterPoint;


function showRequest(XMLHttpRequest) {
	//jQuery("#loading-indicator").show();
	jQuery('#form-via').addClass("ac_loading");
	  jQuery('body').addClass('wait');
	}

function showError(XMLHttpRequest, textStatus, errorThrown) {
	//console.log( textStatus);
	jQuery('#form-via').removeClass("ac_loading");
	 jQuery('body').removeClass('wait');
	
	jQuery("#search-string").html("Spiacenti ma il servizio non è al momento disponibile.").fadeIn();	
	}

function processFormData() {
	
	jQuery('#search-string').fadeOut();
	var key = jQuery('#form-via').val();
	var keyId = jQuery('#IdVia').val();
	var keyType = jQuery('#wizard-form input:radio:checked').val();
	//Query("#search-string").fadeOut();	
	
	
	if (key != '' && key != jQuery('#form-via-label').html()) {
		 jQuery.ajax({
			type: "GET",
			dataType: 'json',
			cache: false,
			beforeSend: showRequest,
			error: showError,
			url: dataSrc,
			data: {tipo:1,foto:'2:2000',q:key,azienda:keyType,id:keyId,limit:2,distance:50000},
			success: function(data){
				searchResponse(data,key);
				dataResponse = data;

				//Nasconde i punti mobili.
				hideMarkerGroup('11');
				hideMarkerGroup('12');
				hideMarkerGroup('13');
				hideMarkerGroup('14');
				hideMarkerGroup('15');
				hideMarkerGroup('16');
				}
			}); 
		}
	}


function showPuntiMobili() {
	showMarkerGroup(11);
	showMarkerGroup(12);
	showMarkerGroup(13);
	showMarkerGroup(14);
	showMarkerGroup(15);
	showMarkerGroup(16);
	centerAndZoom();
	jQuery('#legenda-puntimobili').show();
	}

function searchResponse (data,key) {
	jQuery('#form-via').removeClass("ac_loading");
	jQuery('body').removeClass('wait');
	jQuery("#materiali-informativi-btn").parent().removeClass("current");
	jQuery("#servizi-quartiere-modal").hide();
	jQuery("#map-container").show();
				
	
	//click(function(){jQuery("#servizi-quartiere-modal").toggle();jQuery(this).parent().toggleClass("current");});
	
	if (data){	
		var responseStatus = data.responseStatus;
		if (responseStatus == 'OK') {
	//	if (data.responseHtml) {
			firstSearch = true;
			jQuery('#search-value').html(key);
			
			jQuery('#legenda-mappa').html(data.legenda);
			jQuery('#legenda-puntimobili').html(data.legendapm);
			jQuery('#legenda-puntimobili').hide();
			//jQuery('#servizi-quartiere-result-container').slideDown();
			
			if (!mapIsInitialized) {
				initializeMap();
				}
			else {
				map.getInfoWindow().hide();
				map.clearOverlays();
				gmarkers = [];	
				htmls = [];
				counter = 0;
				//map = null;
				//initializeMap();
				}
			addMarkers (data,key);
			
			if (data.responseCenter) {
				addPosMarker (data.responseCenter,key);
				var subAddress = '';
				if (data.subAddress) subAddress = '<p class="subaddress">'+data.subAddress+'</p>';
				//subAddress = '<p class="subaddress">da Via Luchino dal Verme a Via del Pigneto</p>';
				
				var responseCenterHtml = '<img src="/images-new/gmaps-icons/marker_rosso.png" width="32" height="40" alt="'+data.address+'" class="png-fix" onclick="centerAndZoom();"/><h4>'+data.address+'</h4>'+subAddress+'<p class="municipio">'+data.municipio+'&deg; Municipio</p><div class="infotext">'+data.infotext+'</div>'
				jQuery('#servizi-quartiere-result-response').html(responseCenterHtml);
			
				}
			}
		else {
			//jQuery('#search-string').fadeIn();
			jQuery('#search-value').html();
			//jQuery('#servizi-quartiere-result-response').html();
			//jQuery('#servizi-quartiere-result-container').hide();
			}
		}
	else {
		jQuery("#search-string").html("Nessuna risposta").fadeIn();	
		}
	}
	//}


///
// Aggiungo il marker centrale
///
function addPosMarker (data,key) {
	var lat = parseFloat(data.lat);
	var lng = parseFloat(data.lng);
	var point = new GLatLng(lat, lng);
	mapCenterPoint = point;
	var html = '<h4>'+data.name+'</h4>' + (data.address ? '<strong>'+data.address+'</strong><br/>':'') + data.html;
	var icontype =  parseFloat(data.tipo);
	htmls[counter] = html;
	var marker = createMarker(point,icontype,counter,false);
	map.addOverlay(marker);
	//map.setCenter(point, 12);
	map.panTo(point);  
	counter++;
	}

///
// Aggiungo i marers
///
function addMarkers (data,key) {
	var bounds = new GLatLngBounds();
	var pmcounter = 0;
	jQuery.each(data.markers, function (i, item) {
		var tipo = parseFloat(item.tipo);
		var lat = parseFloat(item.lat);
		var lng = parseFloat(item.lng);
		var point = new GLatLng(lat, lng);
		if (item.pm == 1) {
			pmcounter++;
			if (pmcounter >= 10) {
				return true;
				}
			}
		var html = '<h4>'+item.name+'</h4>' + (item.address ? '<strong>'+item.address+'</strong><br/>':'') + item.html;
		htmls[counter] = html;
		var marker = createMarker(point, tipo,counter);
		map.addOverlay(marker);
		bounds.extend(point);
		counter++;
		});
	if (counter == 0) {
		map.setCenter(new GLatLng(responseLat,responseLng), 12);
		//console.log("DEF");
		}
	else {
		
		//
		//
		//map.panTo(bounds.getCenter());  
		map.setZoom(map.getBoundsZoomLevel(bounds)+2);
		
		//map.setCenter(bounds.getCenter(),map.getBoundsZoomLevel(bounds));
		
		//console.log(map.getBoundsZoomLevel(bounds));
		}
	}


function showAllPM () {
	var bounds = new GLatLngBounds();
	var pmcounter = 0;
	jQuery.each(dataResponse.markers, function (i, item) {
		var tipo = parseFloat(item.tipo);
		var lat = parseFloat(item.lat);
		var lng = parseFloat(item.lng);
		var point = new GLatLng(lat, lng);
		if (item.pm == 1) {
			pmcounter++;
			if (pmcounter >= 10) {
				var html = '<h4>'+item.name+'</h4>' + (item.address ? '<strong>'+item.address+'</strong><br/>':'') + item.html;
				htmls[counter] = html;
				var marker = createMarker(point, tipo,counter);
				map.addOverlay(marker);
				bounds.extend(point);
				counter++;
				}
			}
		});
	map.setZoom(map.getBoundsZoomLevel(bounds));
	}



///
// Se clicco su un marker
///
function myclick(i) {
	gmarkers[i].openInfoWindowHtml('<div class="baloon">' + htmls[i] + '</div>',{ maxWidth: 250});
	}

///
// Creo il marker
///
function createMarker(point, icontype,index,defaultOpen) {
	var marker = new GMarker(point, icons[icontype]);
      // === Store the category and name info as a marker properties ===
      marker.category = icontype;                                 
//    marker.name = name;
	if (jQuery('#map_canvas_add').length == 0) {
		GEvent.addListener(marker, "click", function () {
			marker.openInfoWindowHtml('<div class="baloon">' + htmls[index] + '</div>');
			});
		}
	if (defaultOpen){
		GEvent.trigger(marker, "click");
		}
	gmarkers[index] = marker;
	return marker;
	}




function centerAndZoom() {
	jQuery("#servizi-quartiere-modal").hide();
	jQuery("#map-container").show();
	map.setCenter(mapCenterPoint, 16);
	
	}
	


// == shows all markers of a particular category, and ensures the checkbox is checked ==
function showMarkerGroup(category) {
	jQuery("#servizi-quartiere-modal").hide();
	jQuery("#map-container").show();
				
	for (var i=0; i<gmarkers.length; i++) {
		if (gmarkers[i].category == category) {
			gmarkers[i].show();
			}
		}
	}

// == hides all markers of a particular category, and ensures the checkbox is cleared ==
function hideMarkerGroup(category) {
	for (var i=0; i<gmarkers.length; i++) {
		if (gmarkers[i].category == category) {
			gmarkers[i].hide();
			}
		}
	}

///
// Cancello i marers
///
/*function resetMap() {
	jQuery.each(data.markers, function (i, item) {
		gmarkers[i].closeInfoWindowHtml();
		});
	}*/


function initializeMap() {
	if (jQuery('#map_canvas').length > 0) {
		if (GBrowserIsCompatible()) {
			// this variable will collect the html which will eventualkly be placed in the side_bar
			// create the map
			map = new GMap2(document.getElementById("map_canvas"));
			map.enableDoubleClickZoom();
			map.setUIToDefault();
			map.setCenter(new GLatLng(responseLat,responseLng),defaultMapZoom);
			map.disableScrollWheelZoom();
			mapIsInitialized = true;
			}
		else {
			alert("Sorry, the Google Maps API is not compatible with this browser");
			}
		};
	}

jQuery(function(){	
		
	jQuery("#wizard-form").submit(function () {
	
	
	
	//jQuery("#servizi-quartiere-submit").click(function(){
	//	window.location="/servizi-quartiere/quartieri/?form-via="+jQuery('#form-via').val()+"&IdVia="+jQuery('#IdVia').val()+"#servizi-quartiere-result";
				
		if (jQuery('#IdVia').val()) {			
				if(firstSearch){			
					//window.location="/servizi-quartiere/quartieri/?form-via="+jQuery('#form-via').val()+"&IdVia="+jQuery('#IdVia').val()+"#servizi-quartiere-result";
					processFormData();
				}else{				
					processFormData();
				}
			
			}else{
			jQuery("#search-string").html("La via che hai inserito non è valida. Per effettuare la ricerca  scrivere il nome della strada, anche in parte,  selezionare un indirizzo dalla lista dei risultati e premere il pulsante Cerca.").fadeIn();		
				
			}
			
		
		return false;
		
		});
	
	
	jQuery("#form-via").keydown(function(e){
		if (e.keyCode != 13) {
			jQuery('#IdVia').val("");
			}
		});
	initializeMap();	
	processFormData();
	
	jQuery("#form-radio-domestiche,#form-radio-nondomestiche").change(function(){if (jQuery('#IdVia').val()) {processFormData();}});
	
	
	//jQuery("#materiali-informativi-btn").click(function(){jQuery("#servizi-quartiere-modal").toggle();jQuery(this).parent().toggleClass("current");});
	
	});
	
	
	function openModal(id){
 		if (id > 0) {
	 		jQuery("#servizi-quartiere-modal div.text-content").html('');
			//if (jQuery("#servizi-quartiere-modal:hidden").length > 0){
		
			jQuery.ajax({
				type: "GET",
				dataType: 'html',
				cache: false,
				beforeSend: showRequest,
				error: showError,
				url: dataSrc,
				data: {getPapContent:id},
				success: function(html){
					jQuery('#form-via').removeClass("ac_loading");
					jQuery('body').removeClass('wait');
					jQuery("#servizi-quartiere-modal div.text-content").html(html);
//					jQuery('html, body').animate({
//						scrollTop: jQuery("#servizi-quartiere-modal").offset().top
//					}, 1000);
					jQuery("#map-container").hide();
					jQuery("#servizi-quartiere-modal").show();
					
					} 		
				}); 
		//	}else{
		//		jQuery("#servizi-quartiere-modal").hide();
		//		jQuery("#map-container").show();
					
		//	}
		}
	}

	function closeModal(){
		jQuery("#servizi-quartiere-modal").hide();
		jQuery("#map-container").show();
		}
