// 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" />');
	    	}
	      
			if($('#indirizzo_ente').html()!=null){
			 $.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){
		
		for(i=0;i<ind.length;i++){
			
		  	get_geocode(ind[i]);
		  	
		  	/*if(isdefined('console')){
		  		console.log(i,ind[i]);
		  	}*/
	  	}
	  	
	  	window.loc_all['n']=ind.length;
	}
	
}


function get_geocode(addr){


	if(isdefined(addr) && addr.lat!=''){
	
		if(isdefined('console')){
		  	console.log(addr);
		}
		
		placeMarker({'b':addr.lat, 'c':addr.lng},  addr.url, addr.nome, addr.c);
	}
	
	else{
	
		if(isdefined('console')){
		  	console.log('geo');
		  	console.log(isdefined(addr.lat));
		  	console.log(addr.lat);
		}
		
		geocoder.geocode( {'address': addr.indirizzo}, function(results, status) {
		 
	 		
			
			if (status == google.maps.GeocoderStatus.OK) {
		
			
			
				window.loc_all[loc_all.length]= results[0].geometry.location;
			
				if(isdefined('console')){
			  		console.log(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();
    	
    	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(){
	
	var maxLat=loc_all[0].lat();
	var maxLng=loc_all[0].lng();
	
	var minLat=loc_all[0].lat();
	var minLng=loc_all[0].lng();
	
	for(i=1;i<m_counter;i++){
		
		maxLat = (loc_all[i].lat()>maxLat) ? loc_all[i].lat() : maxLat;
		maxLng = (loc_all[i].lng()>maxLng) ? loc_all[i].lng() : maxLng;
		
		minLat = (loc_all[i].lat()<minLat) ? loc_all[i].lat() : minLat;
		minLng = (loc_all[i].lng()<minLng) ? loc_all[i].lng() : minLng;
	}

	if(isdefined('console')){

		console.log(loc_all, maxLat,maxLng,minLat,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;
}


function test_form(){

	var msg='';

	if($.trim($('#comm_nome').val())==''){
	
		msg+='- Inserire un nome\n';
	}
	
	if($.trim($('#comm_email').val())==''){
	
		msg+='- Inserire una email\n';
	}
	else{
	
		resp=$.ajax({url:'/rubricapa/rpc/rpc.testemail.php?email='+$.trim($('#comm_email').val()),
					async: false
				  });
		
		if(resp.responseText!=1){
			msg+='- Inserire una email valida\n';
		}
	}
	
	
	if($.trim($('#comm_testo').val())==''){
	
		msg+='- Non \350 possibile inviare un commento vuoto\n';
	}
	
	
	if(msg!=''){
	
		alert('Non \350 possibile inviare il commento:\n'+msg);
		$('#cform input:submit').attr('disabled','');
		
		return false;
	}
	else{
	
		return 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');
  		}
  	});
  	
  	
  	$('#a_commento').click( function (){
  	
  		$('#commentonew').show();
  		return false;
  	});


	//$('#cform input:submit').click( function (){ $(this).attr('disabled','disabled'); test_form(); });
	$('#cform').submit(function (){return test_form();});
	
	


	// regole per il form

});



