// js

var loc_all = new Array();
var m_counter=0;
var geocoder;
var map;
function initialize(tipo) {
	geocoder = new google.maps.Geocoder();
	
	if(isdefined('centro_reg')){
		var latlng = new google.maps.LatLng(centro_reg.lat, centro_reg.lng);
	}
	else{
		var latlng = new google.maps.LatLng(42.0047,12.6123);
	}
	
	
	var base_latlng=latlng;
	var myOptions = {
	  zoom: 16,
	  center: latlng,
	  mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
	  mapTypeId: google.maps.MapTypeId.ROADMAP
	}
	
	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	
	if(tipo=='multimap'){
		multiCodeAddress();
		
		if(isdefined('centro_reg')){
			map.setZoom(7);
		}
		else{
			map.setZoom(5);
		}
		
		
	}
	else if(tipo=='singlemap'){
		codeAddress();
	}
	else if(tipo=='homemap'){
		
		map.setZoom(5);
		mapHome();
	}
}

function codeAddress() {
	var address = document.getElementById("address").value;
	if (geocoder) {
	  geocoder.geocode( { 'address': address}, function(results, status) {
	    if (status == google.maps.GeocoderStatus.OK) {

	    	// se è approssimato al centro città non lo mostra
	    	if(results[0].geometry.location_type!='APPROXIMATE'){
	    	
		    	map.setCenter(results[0].geometry.location);
			    var marker = new google.maps.Marker({
			        map: map, 
			        position: results[0].geometry.location
			    });
		    
	    	}
	    	else{
	    		$('#map_canvas').html('<img src="/rubricapa/img/gmap_noaddress.png" alt="Mappa non disponibile" />');
	    	}
	      
	      $.ajax({
			  type: 'POST',
			  url: "/rubricapa/rpc/store_cache_gdata.php",
			  data: "lat=" + results[0].geometry.location + "&approx=" + results[0].geometry.location_type+"&loc="+window.location
			});

	      
	    } else {
	      alert("Geocode was not successful for the following reason: " + status);
	    }
	  });
	}
}

function multiCodeAddress(){
	
	if(isdefined('ind') && geocoder){
		
		window.loc_all['n']=ind.length;
		
		for(i=0;i<ind.length;i++){
			
		  	get_geocode(ind[i]);
	  	}
	}
	
}


function get_geocode(addr){
	
	 geocoder.geocode( { 'address': addr.indirizzo}, function(results, status) {
			
		if (status == google.maps.GeocoderStatus.OK) {
			
			window.loc_all[loc_all.length]= results[0].geometry.location;

	 		placeMarker(results[0].geometry.location,  addr.url, addr.nome, addr.c);
		}
	});
	
}


function placeMarker(location, url, nome, c) {
	
	window.m_counter++;
	
	if(c<100){
		myIcon= new google.maps.MarkerImage('/rubricapa/img/markers/marker'+c+'.png');
	}
	else{
		myIcon= new google.maps.MarkerImage('/rubricapa/img/markers/marker.png');
	}
	
	var clickedLocation = new google.maps.LatLng(location);
	var marker = new google.maps.Marker({
		position: location, 
		map: map,
		title: nome,
		icon: myIcon
	});
	
	var listner = google.maps.event.addListener(marker, 'click', function() {
    	window.location=url;
    });
    
    /*
    Se è l'ultima chiamata ad un marker calcola i bounds 
    */
    if(m_counter==loc_all['n']){
    	
    	Max=max_latlng(loc_all);
    	
    	var SW = new google.maps.LatLng(Max.minLat,Max.minLng);
    	var NE = new google.maps.LatLng(Max.maxLat,Max.maxLng);
    	
    	var cLat = (Max.maxLat + Max.minLat) / 2;
    	var cLng = (Max.maxLng + Max.minLng) / 2;
    	
    	var CENTER = new google.maps.LatLng(cLat,cLng);
		
		var newbounds = new google.maps.LatLngBounds(SW, NE);
		
		if(m_counter>1){
			map.fitBounds(newbounds);
		}
		else{
			map.setZoom(11);
		}
		map.panTo(CENTER);
    }
    
}

function max_latlng(obj){
	
	var maxLat=loc_all[0].b;
	var maxLng=loc_all[0].c;
	
	var minLat=loc_all[0].b;
	var minLng=loc_all[0].c;
	
	for(i=1;i<m_counter;i++){
		
		maxLat = (loc_all[i].b>maxLat) ? loc_all[i].b : maxLat;
		maxLng = (loc_all[i].c>maxLng) ? loc_all[i].c : maxLng;
		
		minLat = (loc_all[i].b<minLat) ? loc_all[i].b : minLat;
		minLng = (loc_all[i].c<minLng) ? loc_all[i].c : minLng;
	}
	
	var maxmin={'maxLat':maxLat, 'maxLng':maxLng, 'minLat':minLat, 'minLng':minLng};
	
	return maxmin;
}


function mapHome(){
	
	for(i=0;i<latlng_reg.length;i++){
		
		latlng=new google.maps.LatLng(latlng_reg[i].lat_regione, latlng_reg[i].lng_regione);
		
		placeMarker(latlng, 'regione/'+ latlng_reg[i]['nome_regione'].replace(' ','+') +"/", latlng_reg[i]['nome_regione']+' '+latlng_reg[i].n);
	}
}


function isdefined(variable){
  return (typeof(window[variable]) == "undefined") ? false : true;
}

$(document).ready( function (){
	
	$('.folder_sx h3.closed').next().hide();
	
	$('label[for="i-cerca"]').hide();
	
	$('.folder_sx h3 a').click(function(){ return false;});
	
	$('.folder_sx h3 a').click( function (){ 
		
		if($(this).parent().next().is(':visible')){
			$(this).css('background-position','0 2px');
		}
		else{
			$(this).css('background-position','0 -15px');
		}
		
		$(this).parent().next().slideToggle('fast'); 
	});
	
		
  	if($('#map_canvas').length>0){
  		if($('#address').length>0){
  			
  			initialize('singlemap');
  		}
  		else if(isdefined('ind') || ($('#multi_address').length>0 && $('#multi_address').val()!='')){
  			
  			initialize('multimap');
  		}
  		else if($('.map-home').length>0){
  			
  			initialize('homemap');
  		}
  		else{
  			
  			$('#map_canvas').html('<img src="/rubricapa/img/gmap_noaddress.png" alt="Mappa non disponibile" />');
  		}
  	}
  	
  	
  	
  	
  	if($('#i-cerca').val()==''){
  		
  		$('#i-cerca').addClass('grigio').val('Cerca nella rubrica');
  	}
  	
  	$('#i-cerca').focus( function(){
  		
  		if($(this).val()=='Cerca nella rubrica'){
  			
  			$(this).removeClass('grigio').val('');
  		}
  	});
  	
  	$('#i-cerca').blur( function(){
  		
  		if($(this).val()==''){
  			
  			$(this).addClass('grigio').val('Cerca nella rubrica');
  		}
  	});

});

  
