// funzione di georeferenzazione indirizzo
function geo(mode,point,id_stabilimento,utente) {
	
	var _point = point || '';
	var _id_stabilimento = id_stabilimento || '';
	var _utente = utente || '';
	
	var _zoom = 15;
	var _regione	 = $('#reg_desc').val();
	var _provincia 	 = $('#prov_desc').val();
	var _comune 	 = $('#com_desc').val();
	var _address 	 = $('#addressInput').val();
	if ((_regione) && (!_comune) && (!_provincia)) {
		_zoom = 9;
	}

	switch (mode){
		case 0:		// partendo da click -> setto l'evemto myEventListener solo nel caso parta da click mappa
			var myEventListener = GEvent.addListener(map, "click", function(overlay, _point) {
				if (counter==0) {
					if (_point) {
						var _point_lat = _point.lat();
						var _point_lng = _point.lng();
						var new_address = _point_lat.toFixed(5)+','+ _point_lng.toFixed(5);
											
						jQuery.ajax({
				        	type: "POST",
				        	dataType: "json",
				        	url: "/mappe/luoghi_produzione/index.php/geo",
				        	data: ({
				            	q: new_address
				        	}),
				        	success: function(json){
					 		if (json.status) {
				        		var sta = json.status.substring(1,json.status.length-1);
								if (sta==200) {
							 		var	lng = json.longitude;
									var	lat = json.latitude;
									var	adr = json.address.substring(1,json.address.length-1);
						
									var address = adr.replace(',','|');
									
									searchLocations(_utente,_id_stabilimento,lat,lng,sta,address,_zoom,'inserisci_stabilimento_conferma','Inserisci stabilimento');
									} else {
										alert('Indirizzo non trovato!');
										$.unblockUI(); 
										return '';
									}
						 		} else {
						 			alert('Indirizzo non trovato!');
									$.unblockUI(); 
									return '';
						 		}
							}
						});		
					counter = 1;
					}
				} else {
					counter = 1;
					GEvent.removeListener(myEventListener);
				}
			});
		break;
	
		case 1:		// partendo dalla ricerca
			var new_address =  _address+', '+_comune+', '+_provincia+','+_regione +', Italia';
	
			jQuery.ajax({
	        	type: "POST",
	        	dataType: "json",
	        	url: "/mappe/luoghi_produzione/index.php/geo",
	        	data: ({
	            	q: new_address
	       		 }),
				 success: function(json){
			 		if (json.status) {
						var sta = json.status.substring(1,json.status.length-1);
						if (sta == 200) {
					 		var	lng = json.longitude;
							var	lat = json.latitude;
							var	adr = json.address.substring(1,json.address.length-1);
				
							var address = adr.replace(',','|');
							
							searchLocations(_utente,_id_stabilimento,lat,lng,sta,address,_zoom,'inserisci_stabilimento_conferma','Inserisci stabilimento');
						} else {
							alert('Indirizzo non trovato!');
							$.unblockUI(); 
							return '';
						}
			 		} else {
			 			alert('Indirizzo non trovato!');
						$.unblockUI(); 
						return '';
			 		}
				}
			});		
		break;
			
		case 2:		// partendo da click
			if (_point) {
				var _point_lat = _point.lat();
				var _point_lng = _point.lng();
				var new_address = _point_lat.toFixed(5)+','+ _point_lng.toFixed(5);
				jQuery.ajax({
		        	type: "POST",
		        	dataType: "json",
		        	url: "/mappe/luoghi_produzione/index.php/geo",
		        	data: ({
		            q: new_address
		        	}),
				 	success: function(json){
				 		if (json.status) {
				 			var sta = json.status.substring(1,json.status.length-1);
							if (sta==200) {
						 		var	lng = json.longitude;
								var	lat = json.latitude;
								var	adr = json.address.substring(1,json.address.length-1);
					
								var address = adr.replace(',','|');
		
								searchLocations(_utente,_id_stabilimento,lat,lng,sta,address,_zoom,'sposta_stabilimento_conferma','Sposta stabilimento');
							} else {
								alert('Indirizzo non trovato!');
								$.unblockUI(); 
								return '';
							}
				 		} else {
				 			alert('Indirizzo non trovato!');
							$.unblockUI(); 
							return '';
				 		}
					}
				});		
		}
		break;
	}		
}

// date incerte
function certa_dal_click() {

	var _form = $('#frm_modifica');
	
	var certa_dal = $('#certa_dal',_form).val();
	if (certa_dal == 1) {
		 $('#certa_dal').val(0);

	} else {
		$('#certa_dal',_form).val(1);
	}
}


function certa_al_click() {

	var _form = $('#frm_modifica');
	
	var certa_al = $('#certa_al',_form).val();
	if (certa_al == 1) {
		 $('#certa_al').val(0);
	} else {
		$('#certa_al',_form).val(1);
	}
}


// apri un link in un altra finestra
function jq_apri(){
	$("a.apri").each(
		function(){
			if(($(this).attr("target") !== "_blank") ||  ($(this).attr("target") !== "_top")) {
				$(this).attr("title", $(this).text() + " [link in una nuova finestra]");
				$(this).attr("target", "_blank");	
			}
		}
	);
	
	$("a.mydialog").each(
		function(){
			if($(this).attr("target") === "_top") {
				$(this).removeAttr("target");	
			}
		}
	);
	
	$("a.apri_full").each(
		function(){
			if($(this).attr("rel") != 'external'){
				var prop_apri='fullscreen=yes,scrollbars=yes,menubar=no,resizable=no,status=no,directories=no,location=no,width='+screen.availWidth+',height='+screen.availHeight; 
				var mhref = $(this).attr("href");
				$(this).attr("title", $(this).text() + " [link in una nuova finestra a tutto schermo]");
				$(this).attr("rel", "external");
				$(this).click(function () {window.open(mhref, '_new', prop_apri);return false;});
			}
		}
	);
	
	top.parent.focus();
} 

// Nasconde timeline con unblock
function hideTimeline() {
	$.unblockUI(); 
	nascondiTimeline();
}
// Nasconde timeline
function nascondiTimeline(){
	$('.ui-slider-handle').hide();
	$('.ui-slider-range').hide();
	$('#txt_breve').hide();
	$('#txt_lungo').hide();
	$('#timeline fieldset').addClass('opaco');
}
// Mostra timeline
function mostraTimeline(){
	$('.ui-slider-handle').show();
	$('.ui-slider-range').show();
	$('#txt_lungo').hide();
	$('#txt_breve').show();
	$('#timeline fieldset').removeClass('opaco');
}

// Pulisci i risultati dalla sidebar e ripagina
function clearResult(markerNum) {
	var newRes = Number($("input[name='resultCnt']").getValue())-1;
	$("input[name='resultCnt']").setValue(newRes);
	if (newRes<0) {
    	$("input[name='resultCnt']").setValue(0);	
    	$('#result_esp_a').parent().hide();
    }
	$("#"+markerNum).remove();
}


// attivo paginazione
function paginate(n) {
	$('#risultati_elenco').jpaging({
		record : '.items',
		per_pagina : n,
        lbl_page   : 'Pagina',
        lbl_next   : 'Successivo',
        lbl_prev   : 'Precedente',
		finestra   : 5
	});
}

// funzione che aggiorna l'input what e result cont contenuti in cercasx_form 
function setInput(what, cnt){
    $("input[name='what']").setValue(4);
    $("input[name='resultCnt']").setValue(Number(cnt));
    var newRes = $("input[name='resultCnt']").getValue();
    if (newRes<0) {
    	$("input[name='resultCnt']").setValue(0);
		$('#result_esp_a').parent().hide();
    }
}

//SOVRASCRIVO UNBLOCK
(function($){
	var _slider = false;
	var _unblock = $.unblockUI;
	$.unblockUI = function(opts) { _unblock(opts); $(document).trigger("unblock"); };
	
	$(document).bind("unblock", function(){
		var _c = $("#resultCnt").val();
		if(_c > 0 ){
			$('#result_esp_a').parent().show();
			mostraTimeline(); 
		}else{
			$('#result_esp_a').parent().hide();
			nascondiTimeline();
			clearMarker();
		}
	});

	
})(jQuery);


function fullScreen(_hash) {
	
	_hash = document.location.href+_hash.replace('#fullscreen?active=1#fullscreen?active=1','');
	_hash = _hash.replace('#Tod1_Overview#Tod1_Overview','');
	_hash = _hash.replace('###','#');
	
	//nascondere barre e dimensionare finestra
	window.opener=self;
	window.close(); 
	
	var options = '"fullscreen=yes,scrollbars=yes,menubar=no,resizable=no,status=no,directories=no,location=no,width='+screen.availWidth+',height='+screen.availHeight+'"' ; 
	var xOpen = window.open(_hash,'', options);
	return false;
}




$(window).load(function(){ 

	// pagina a tutto schermo + visualizzazione stabilimento
	var _hash = location.hash.replace("#","");
	var _fullscreen = _hash.substr(0,20) 

	if (_fullscreen!="#fullscreen?active=1")
	{
		var _hash = location.hash+'#fullscreen?active=1';
	}
	
	var _params = _hash.substr((_hash.indexOf("?")+1));
	_params = _params.split("&");
	
	for(var x in _params){
		var _arr = _params[x].split("=");
		switch(_arr[0]){
			
		case 'active' :
			counter = 1;
			//if (!_fullscreen) fullScreen(_hash);
			$("#tab_ricercastab").trigger("click");
		break ;
			
		case 'id' : 
			var id = _arr[1];
			if(parseInt(id) >0) {
				viewMarker(id);
			}
		break;

		case 'action' : 
			counter = 1;
			$("#tab_aggiungistab").trigger("click");
		break;

		};
	}
	
	//_f11();
	
});

/***** operazioni eseguite una volta che la pagina e'pronta *****/

$(document).ready(function() {
	if (typeof document.body.style.maxHeight === "undefined") {
		_messaggio = '<div id="msgie6"><p>'
		_messaggio += 'Hai una versione di Explorer non compatibile con questa applicazione.<br/>';
		_messaggio += 'Ti consigliamo di scaricare una ';
		_messaggio += '<a href="http://www.microsoft.com/italy/windows/internet-explorer/download-ie.aspx">versione pił aggiornata</a>  ';
		_messaggio += 'o di utilizzare un altro browser.<br/>';
		_messaggio += '<input type="button" class="puls" value="chiudi" onclick="window.close();">'
		_messaggio+= '</p></div>';
		$.blockUI({ message: _messaggio }); 
	}
	// inizializzazione timeline		
	var selects = $('select#valueA, select#valueB');

	//salvo il valore massimo e minimo delle due select
	var _A = $("select#valueA option:first").val();
	var _B = $("select#valueB option:last").val();
	
	var _slide_timer = null;
	var _slide_interval = 1000;
	//array of all option elements in select element (ignores optgroups)
	var selectOptions = (function(){
		var opts = [];
		selects.eq(0).find('option').each(function(){
			opts.push({
				value: $(this).attr('value'),
				text: $(this).text()
			});
		});
		return opts;
	})();

	var _on_slide = function _main(e, ui){
		var thisHandle = $(ui.handle);
		var textval = selectOptions[ui.value].text
		thisHandle
			.attr('aria-valuetext', textval)
			.attr('aria-valuenow', ui.value)
			.find('.ui-slider-tooltip')
				.text( textval );

		var currSelect = $('#' + thisHandle.attr('id').split('handle_')[1]);
		currSelect.find('option').eq(ui.value).attr('selected', 'selected');
		
		if ($("select#valueA").val() != $("select#valueB").val()) {
			filterMarkers();
		} else {
			var data = new Date();
			var anno =  data.getFullYear();

			if (($("select#valueA").val()==anno) && ($("select#valueB").val()==anno)) {
				_A = 2000;
				_B = $("select#valueB").val();
				$('select#valueA').val((_A)).trigger("change");
			} else if (($("select#valueA").val()=="1850") && ($("select#valueB").val()=="1850")) {
				_A = $("select#valueA").val();
				_B = 1860;
				$('select#valueB').val((_B)).trigger("change");
			} else 	if ($("select#valueA").val()==$("select#valueB").val()) {
				_A = $("select#valueA").val();
				_B = (parseFloat($("select#valueB").val())+10);
				$('select#valueB').val((_B)).trigger("change");
			}
				
			// ricalcolo toltip	
			var thisHandle = $('#handle_valueB');
			var textval = _B;
			thisHandle
				.attr('aria-valuetext', textval)
				.attr('aria-valuenow', textval)
				.find('.ui-slider-tooltip')
				.text( textval );

			var thisHandle = $('#handle_valueA');
			var textval = _A;
			thisHandle
				.attr('aria-valuetext', textval)
				.attr('aria-valuenow', textval)
				.find('.ui-slider-tooltip')
				.text( textval );

		// applico filtri		
		filterMarkers();

		}
	}
	
	selects.selectToUISlider({
		width: 650,
		labels: 10,
		sliderOptions : {
			slide : function(e, ui) {
				if (_slide_timer) clearTimeout(_slide_timer);
				_slide_timer = setTimeout(function(){
					_on_slide(e, ui);
				}, _slide_interval);
			}
		}
	});    
	$('.ui-slider-handle').show();
	$('.ui-slider-range').show();
	$('#timeline').addClass('timeline_ridotta');
	nascondiTimeline();
	$('#txt_breve').hide();
	$('#txt_lungo').show();
	$('#timeline fieldset').addClass('opaco');
	// fine iniziaizzazione time line

	
	// avvio ricerca stabilimenti
	$("#id_submit").click(function(){
		
		$('select#valueA').val((_A)).trigger("change");
		$('select#valueB').val(_B).trigger("change");			
		
		var _n = $("#settori").find("input:checkbox:checked").length > 0;
	/*	if (($("#indirizzo").val() == "Indirizzo (senza via, corso...)") && ($("#localita").val() == "Cittą")) {
			var _tutti = 0;
			$("#localita").val("");
			$("#indirizzo").val("");
		}
	*/	
	/*	var _text = $("#indirizzo, #nome_stab, #localita");

		var _flag = false;
		_text.each(function(){
			if(!_flag && $(this).val().length > 0){
				_flag = true;
			}
		});
	*/	
	//	if(!(_n || _flag))
		if(!(_n ))
			$("#ck_select_all").trigger("click");
		
	/*	if (_tutti == 0) {
			$("#localita").val("Cittą");
			$("#indirizzo").val("Indirizzo (senza via, corso...)");
		}
	*/	
		$.blockUI({ message: "<h1>Ricerca in corso...</h1>" }); 
		$("#result").show();
        $('ul#lista').replaceWith("");
        $('#risultati_elenco').empty();
        var arrSettori = $("input[name='ckb_settore']").getValue();
        var myRegExp = new RegExp(",", "g");
        var s = arrSettori.replace(myRegExp, "|");
        var w = $("input[name='what']").getValue();
        $("input[name='resultCnt']").setValue(0);
        searchLocationsSet(w, s);
		
        location.hash = "anchor";    
	});
	
	$('#frm_settori').submit(function(){
		//$("#id_submit").trigger("click");
		return false;
	});
	// avvia ricerca indirizzo
	$('#frm_ricerca').find("select").change(function(){
        $(this).trigger("blur");    
    });
	
    
	$("#frm_ricerca").submit(function(){
		var _validate = $(this).is(".validate");
		if(_validate && !$(this).validate().form())
			return false;
		
		$.blockUI({ message: "<h1>Ricerca indirizzo in corso...</h1>" }); 
		nascondiTimeline();

		// richiamo funzione di georeferenzazione
		geo(1);
		
	});
	
/*	// inizializzo il suggest
	var q = $("#indirizzo").val();
	q = q.replace("Indirizzo (senza via, corso...)","");
	
	$("#indirizzo").autocomplete("/mappe/luoghi_produzione/index.php/suggest/suggest_address/#", {
					inputClass:"input_small",
					resultClass:"input_small",
					minChars: 3,
					selectFirst: false
				});
				
	var digit = 0;
	$("#indirizzo").keydown(function () {
		var q = $("#indirizzo").val();
			q = q.replace("Indirizzo (senza via, corso...)","");

		digit++; 
		if (digit>3) {
			jQuery.ajax({
			   	type: "POST",
			   	url: "/mappe/luoghi_produzione/index.php/suggest/suggest_address",
			   	data: ({
			       	indirizzo: q
			   		}), 
			   		success: function(msg) {
			   			data = msg.split("|");
			   			$("#indirizzo").autocomplete(data,{
							inputClass:"input_small",
							resultClass:"input_small",
							minChars: 3,
							selectFirst: false
			   			});
			   	}
			});
		}
	});
*/	
	// estrazione province data una regione
	$("#regione").change(function(){
		
		$("#reg_desc").val("");
		$("#prov_desc").val("");
		$("#com_desc").val("");
		
		var id = $("#regione").val();
		var str = "";

		$("select#regione option:selected").each(function () {
	     	str += $(this).text() + " ";
              });

		$("#reg_desc").val(str);
		
		
		$.ajax({
            type: "POST",
            url: "/mappe/luoghi_produzione/index.php/cercadx/province",
            data: ({
                id: id
             }),
            success: function(html){
           		$("#lista_province").empty().append(html);
            	$("#comuni").empty();
            }
		});
	});		
	
	// estrazione province data una regione
	$("#lista_province").change(function(){
		
		var id = $("#lista_province").val();
		var str = "";
		
	    $("select#lista_province option:selected").each(function () {
	     	str += $(this).text() + " ";
              });

		$("#prov_desc").val(str);
		
		$.ajax({
            type: "POST",
            url: "/mappe/luoghi_produzione/index.php/cercadx/comuni",
            data: ({
                id: id
             }),
            success: function(html){
            	$("#comuni").empty().append(html);
            }
		});
	});		

	// estrazione comune data una provincia
	$("#comuni").change(function(){
		var str="";
	    $("select#comuni option:selected").each(function () {
	     	str += $(this).text() + " ";
              });

		$("#com_desc").val(str);
		
	});		
	
	
	// selezione settori - selettori multipli con autoceck
    $('#settori li input').hide();
    $('#elenco_settori li a').settori();
    $('#ck_deselect_all').hide();

	 // cancello cookie
	var _esci = $('#esci').text();
	if(_esci == 'esci'){ 
		$('#esci').click(function() {
			$.cookie('stin_auth','',{ path: "/", expires : -1, domain : window.location.host});//???
			document.location.href="/mappe/luoghi_produzione/";
			return false;
		});
	}

	$("#reset").click(function(){
        v.resetForm();
    });
    
    //
    // blocco per la visualizzazione dei due tab
    //
    $('#tabs').tabs();
    // tab dx
    $('#tab_aggiungistab').click(function(){
    	clearMarker();
		nascondiTimeline();
	   	$("#tabs").find("#datistab").hide();
    	$("#tabs").find("#daticommento").hide();
    	$("#tabs").find("#gestiscistab").hide();
    	$("#tabs").find("#inseriscistab").show();
    	// richiamo funzione di georeferenzazione
		counter = 0;
    	geo(0);
    });
    
    // tab sx
    $('#tab_ricercastab').click(function(){
    	clearMarker();
		nascondiTimeline();
    	$("#tabs").find("#result").hide();
    	$("#tabs").find("#risultati").hide();
    	$("#tabs").find("#inseriscistab").hide();
    	$("#tabs").find("#inseriscistab").hide();
    	$("#tabs").find("#settori").show();
    	$('#txt_lungo').show();
    	counter = 1;
     });
    
    // inizializzo autentificazione
    $("#accedi").unbind('click').click(function(){
        var metadata = $(this).metadata();
        document.location.href = metadata.link;
        return false;
    });
    
    //
    // blocco per il richiamo ad un nuovo inserimento
    //
    
    $('a#inserici_strabilimento').click(function(){
		$("#tab_aggiungistab").trigger("click");
    });

	//
    // blocco per la espansione/contrazione dei due tab
    //
    $('#map_contr_a').hide();
    
    // espandi mappa
    $('#map_esp_a').click(function(){
        $('#map_esp_a').hide();
        $('#map_contr_a').show();
        $('#tabs').hide();
       	$('#timeline').removeClass('timeline_ridotta').addClass('timeline_estesa');
        
    });
    
    // nascondi mappa
    $('#map_contr_a').click(function(){
        $('#map_esp_a').show();
    	$('#map_contr_a').hide();
        $('#tabs').show();
        $('#timeline').removeClass('timeline_estesa').addClass('timeline_ridotta');
    });
    
    
    //
    // blocco per la espansione/contrazione dei risultati della ricerca (tab sx)
    //
    $("#risultati").hide();
    $("#result").hide();
    
    
    // visualizza risultati
    $('#result_esp_a').click(function(){
        $("#risultati").show();
        $('#settori').hide();
    });
    
    // nascondi risultati
    $('a#result_contr_a').click(function(){
        $('#risultati').hide();
        $('#settori').show();
    });
    
    //
    // arrotondamenti angoli
    //
    if ($.browser.msie==false) {
	    $('.rounded').corners();
	    $('.rounded-n').corners("top 10px");
	    $('.rounded-w').corners("left 10px");
	    $('.rounded-nw').corners("top-left");
	    $('.rounded-ne').corners("top-right");
	    $('.rounded-s').corners("bottom 10px");
	    $('.rounded-se').corners("bottom-left");
	    $('.rounded-sw').corners("bottom-right");
	    $('.rounded-ne-s').corners("top-right bottom");
    }
    
    $('.absoluteIframeDOMWindow').openDOMWindow({ 
		height:screen.availHeight, 
		width:screen.availWidth, 
		positionType:'fixed', 
		positionTop:0, 
		eventType:'click', 
		positionLeft:0, 
		windowSource:'iframe', 
		windowPadding:10, 
		loader:1, 
		loaderImagePath:'animationProcessing.gif', 
		loaderHeight:16, 
		loaderWidth:17,
		modal:0 
	});    
    
	//$('.absoluteIframeDOMWindow').trigger("click");
	
	// carico mappa
    load();

    /*
     * SOLUZIONE DIMENSIONE MAPPA
     */

	var iw = map.getInfoWindow();
	GEvent.addListener(iw, "maximizeclick", function() {
		$("#map_esp_a").trigger("click");
	});
	GEvent.addListener(iw, "restoreclick", function() {
		$("#map_contr_a").trigger("click");
	});
	GEvent.addListener(iw, "closeclick", function() {
		$("#map_contr_a").trigger("click");
	});
	
	GEvent.addListener(iw, "maximizeend", function() {
		jq_apri();
	});
	
	$("#stampapagina > a").click(function(){
		$("#pr_stampa").attr("rel", "stylesheet");
		$("#pr_risultati").attr("rel", "alternate stylesheet");
		window.print();
		return false;
	});
	$(".stamparisultati").click(function(){
		$("#pr_stampa").attr("rel", "alternate stylesheet");
		$("#pr_risultati").attr("rel", "stylesheet");
		window.print();
		return false;
	});
	
	$("#id_reset").click(function(){
		$("#corpo").find("input:text").val("");
		$("#settori").find("input:checkbox").attr("checked","");
		$("#settori").find(".attivo").removeClass("attivo");
		$("#result").hide();
		nascondiTimeline();
		$('#txt_lungo').show();
		clearMarker();
	});

//	$(document).trigger("keydown",[122]);

});

$.fn.attrList = function(strAttribute, strDelimiter){
    // Start out with an empty value list. This list
    // will eventually contain a delimited list of
    // each attribute value.
    var strValueList = "";
    
    // Check to see if we were given a delimiter.
    // By default, we will use the comma.
    strDelimiter = (strDelimiter ? strDelimiter : ",");
    
    // Loop over each element in the $ stack and
    // add the given attribute value to the list.
    this.each(function(intI){
        // Get a $ version of the current
        // stack element.
        var jNode = $(this);
        
        // Add the attribute to the list. When
        // adding the value, check to see if
        // we need to add the leading delimiter.
        strValueList += ((strValueList.length ? strDelimiter : "") +
        jNode.attr(strAttribute));
    });
    
    // Return the value list.
    return (strValueList);
}

