$(function(){ 

	/* CAMPO RICERCA */
	$(".len").click(function(){
		$(this).hide();
		$(".query").show();
		$(".query").val("");
		$(".query").focus();
		$(".query").animate({
		width: "125px"
		}, 400 );
		$(".search").show();
	});
		
	$(document).keyup(function(event) {
		if ( event.which == 27 ) {
			$(".query").animate({
			width: "1px"
			}, 400,function(){
				$(this).hide();
				$(".search").hide();
				$(".len").show();
			});
		}
	});
	/* FINE CAMPO RICERCA */
	
	/*
	$("#homebanking").bind({
	    mouseover: function() {
	        $("#homebanking-content").show();
	    },
	    mouseout: function() {
	       	$("#homebanking-content").hide();
	    }
	})
	*/
	$("#homebanking").click(function () {
		$("#homebanking-content").toggle();
	});

	// SLIDER MACROSEZIONI
	$("#slides").slides({
		preload: true,
		preloadImage: img_dir+'/slides/loading.gif',
		play: 5000,
		pause: 5000,
		hoverPause: true
	});
	
	// MENU
	var posizione = $("#navigation").position().left + "px";
	$(".menu-wrapper").bind({
	  mouseover: function() {
	    var idmenu = $(this).attr("id");
		var menu = ".menu-" + idmenu;
		$(menu).css("left",posizione);
		$(menu).show();
		$(this).find("a").first().addClass("active");
	  },
	  mouseout: function() {
	    $(".menu-second").hide();
		$(this).find("a").removeClass("active");
	  }
	});

	/* ESIGENZE */
	$(".etichetta").click(function(){
		var idesigenza = $(this).attr("id");
		var esigenza = "#esigenza" + idesigenza;
		$(".esigenze-detail").slideUp();
		if( $(esigenza).is(":visible") == false ) {
			$(esigenza).slideDown();
		}
	});

	if(explode != '') {
		var scheda = ".scheda"+explode;
		if( $(scheda).is(":visible") == false ) {
			$(scheda).slideDown(function(){
				var ancora = $(scheda).position().top - 29;
				$('html, body').animate({scrollTop:ancora}, 'fast');
			});
		}
	}
	else {
		$(".scheda1").slideDown();
	}
	/* FINE ESIGENZE */

	/* SELEZIONE ANNO COMUNICATI */
	$(function(){ 	
		$('#select-categoria').change(function(){
			var url = $("#select-categoria").val();
			if(url) { window.location = url; }
		});
	});
	/* FINE ANNO */
	
	if( utility == 'accettazione' ) {
		overlay('.overlay-mandatory','','noclose');
	}
	
	$(".confirm").click(function(){
		$("#content").show();
		$(overlayWrapper).fadeOut('fast',function(){
			$(overlayObj).hide();
			$(overlayClose).remove();
		});
	});
	$(".notconfirm").click(function(){
		window.location = urlhomepage;
	});		

	/* COOKIE */
	var cookieval = $.cookie("BancaDiBologna");
	var documenturl = location.href;
	check = documenturl.indexOf('9080');
	
	if(check != '-1') {
		console.log("top cookieval: " + cookieval);
		console.log(idpage);
		
		if(cookieval) {
			console.log("step 3");
			if(cookieval != '1' && idpage == '3679'){
				console.log("redirect: " + cookieval);
				window.location = cookieval;
			}
		}
		else {
			console.log("step 1");
			cookieval = $.cookie("BancaDiBologna","1",{expires:365});
		}		
		if(cookieval == '1' && (idpage=='3680' || idpage=='3681' || idpage=='3683' || idpage=='3684')) {
			console.log("step 2");
			cookieval = $.cookie("BancaDiBologna",documenturl,{expires:365});
		}

		/* FINE COOKIE */
		console.log("bottom cookieval: " + cookieval);
	}
	
});

function overlay(obj,objmappa,obnoclose) {
	oggetto = $(obj);
	mappa = $(objmappa);
	var contenuto = oggetto.html();
	objClose = "<a href='javascript:void(0);' class='overlay-close'>&#160;</a>";

	screenWidth = $(window).width();
	screenHeight = $(window).height();
	documentHeight = $(document).height();
	scrolltop = $(window).scrollTop();
	
	$(overlayContent).html("");
	$(overlayContent).html(contenuto);
	if(!obnoclose) {
		$(overlayContent).after(objClose);
	}
	
	var sinistra = (screenWidth - $(overlayWrapper).width()) / 2 + "px";
	var alto = (screenHeight - $(overlayWrapper).height()) / 2;
	var difference = scrolltop + alto;

	$(overlayObj).css("height",documentHeight);
	$(overlayObj).fadeIn('fast',function(){
		$(overlayWrapper).css("left",sinistra);
		$(overlayWrapper).css("top",difference);
		$(overlayWrapper).show();
	});
	
	$(document).keyup(function(event) {
		if ( event.which == 27 ) {
			closeOverlay();
		}
	});
	
	$(overlayClose).click(function() {
		closeOverlay();
	});
	
	function closeOverlay() {
		mappa.css("top","-1000px"); //NASCONDO LA MAPPA
		$(overlayWrapper).fadeOut('fast',function(){
			$(overlayObj).hide();
			$(overlayClose).remove();
		});
	}
	
	_createMap();
}

function _createMapOLD(){

	//TIMESTAMP
	var fullDate = new Date()	
	var twoDigitMonth = (fullDate.getMonth().length === 1)? fullDate.getMonth() : '0' + fullDate.getMonth();	 
	var timestamp = fullDate.getDate() + twoDigitMonth + fullDate.getFullYear() + fullDate.getHours() + fullDate.getMinutes() + fullDate.getSeconds();

	var latlng = new google.maps.LatLng(44.498954,11.377029); //SETTO LA MAPPA SU BOLOGNA
	var myOptions = {
		zoom: 20,
		minZoom: 10,
		center: latlng ,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		mapTypeControl: true
	};
	map = new google.maps.Map(document.getElementById('filiali'), myOptions);
	var georssLayer = new google.maps.KmlLayer('http://maps.google.it/maps/ms?authuser=0&vps=3&hl=it&ie=UTF8&msa=0&output=kml&msid=217485575349643784076.0004a86cd8296a1f57897&date='+timestamp);
	georssLayer.setMap(map);

	google.maps.event.addListener(map,"tilesloaded",function(){
		// AL CARIMENTO DELLA MAPPA LA SPOSTO
		if( $(overlayObj).is(":visible") == false ){
			mappa.css("top","-5000px");
		}
		var mappaTop = scrolltop + (screenHeight - $(overlayWrapper).height()) / 2 + 40;
		var mappaLeft = (screenWidth - $(overlayWrapper).width()) / 2 + 400;
		mappa.css("top",mappaTop);
		mappa.css("left",mappaLeft);
	});		
}

function _createMap(){

	//TIMESTAMP
	var fullDate = new Date()	
	var twoDigitMonth = (fullDate.getMonth().length === 1)? fullDate.getMonth() : '0' + fullDate.getMonth();	 
	var timestamp = fullDate.getDate() + twoDigitMonth + fullDate.getFullYear() + fullDate.getHours() + fullDate.getMinutes() + fullDate.getSeconds();
	
	/* CREO LA MAPPA */
	var latlng = new google.maps.LatLng(44.4942,11.3465); //SETTO LA MAPPA SU BOLOGNA
	var myOptions = {
		zoom: 10,
		//minZoom: 10,
		center: latlng ,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		mapTypeControl: true
	};
	map = new google.maps.Map(document.getElementById('filiali'), myOptions);
	/* FINE MAPPA */
	
	marker = new Array();
	infoWindow = new google.maps.InfoWindow();
	
	google.maps.event.addListener(map,"tilesloaded",function(){
		// AL CARIMENTO DELLA MAPPA LA SPOSTO
		if( $(overlayObj).is(":visible") == false ){
			mappa.css("top","-5000px");
		}
		var mappaTop = scrolltop + (screenHeight - $(overlayWrapper).height()) / 2 + 40;
		var mappaLeft = (screenWidth - $(overlayWrapper).width()) / 2 + 400;
		mappa.css("top",mappaTop);
		mappa.css("left",mappaLeft);
	});

	// CHIAMO IL KML
	$.ajax({
		url: static_dir+"/Filiali.kml?t="+timestamp,
		dataType: 'xml',
		beforeSend: function() {
			//$('#loading').show();
		},
		success: function(data,textStatus) {
			var placemarks = jQuery(data).find('Document').find('Placemark');
			if(placemarks.size() > 0) {
				placemarks.each(
					function(index){
						var placemark = jQuery(this);
						var coordinate = placemark.find("coordinates").text().split(",");
						var titolo = placemark.find("name").text();
						var descrizione = placemark.find("description").text();
						if(descrizione == "") {descrizione = "&nbsp;";}
						var markerLng = new google.maps.LatLng(coordinate[1],coordinate[0]); //SETTO LA MAPPA SU BOLOGNA;
						marker[index] = new google.maps.Marker({
							position: markerLng,
							title: titolo,
							description: descrizione,
							icon: new google.maps.MarkerImage(img_dir+'/marker-logo.png'),
							map: map
						});

						google.maps.event.addListener(marker[index], "click", function(){
							infoWindow.setPosition(this.getPosition());
							infoWindow.setContent(
								"<div class='bold m-b-dieci'>"+this.title+"</div>"+
								"<div>"+this.description+"</div>"
							);
							infoWindow.open(map);
						});
						
						/* CARICO E INIETTO L'ELENCO DELLE FILIALI */
						var elencoFiliali = "";
						$.each(marker,function(index,item){
							elencoFiliali += "<div class='branch'><a href='javascript:void(_centerMap("+item.getPosition().lat()+","+item.getPosition().lng()+","+index+"));'>" + item.title + "</a></div>";
						});
						$(".branchcontent").html(elencoFiliali);
						/* FINE CARICAMENTO FILIALI */
					}
				);
			}

			google.maps.event.addListener(map, "dragstart", function(){				
				infoWindow.close();
			});
			google.maps.event.addListener(map, "click", function(){				
				infoWindow.close();
			});
		},
		error: function() {
			alert("errore");
		}
	});
}

function _centerMap(lat,lng,index){
	//var index = 0;
	var cd = new google.maps.LatLng(lat,lng);
	map.setCenter(cd);
	map.setZoom(17);
	infoWindow.setPosition(cd);
	infoWindow.setContent(
		"<div class='bold m-b-dieci'>"+marker[index].title+"</div>"+
		"<div>"+marker[index].description+"</div>"
	);
	infoWindow.open(map);
}

function distance(){
	var origin = new google.maps.LatLng(44.498954,11.377029);
	
	destinazioni = new Array();
	$.each(marker,function(index,item){
		destinazioni[index] = item.getPosition();
	});
	
	var service = new google.maps.DistanceMatrixService();
	service.getDistanceMatrix(
	  {
	    origins: [origin],
	    destinations: destinazioni,
	    travelMode: google.maps.TravelMode.DRIVING,
	    avoidHighways: false,
	    avoidTolls: false
	  }, callback);
	
	function callback(response, status) {
		alert(response);
		alert(status);
	}
}

function elencoFilialiQuestionario() {
	
	//TIMESTAMP
	var fullDate = new Date()	
	var twoDigitMonth = (fullDate.getMonth().length === 1)? fullDate.getMonth() : '0' + fullDate.getMonth();	 
	var timestamp = fullDate.getDate() + twoDigitMonth + fullDate.getFullYear() + fullDate.getHours() + fullDate.getMinutes() + fullDate.getSeconds();
	
	// CHIAMO IL KML
	$.ajax({
		url: static_dir+"/Filiali.kml?t="+timestamp,
		dataType: 'xml',
		beforeSend: function() {},
		success: function(data,textStatus) {
			
			var dropdown = jQuery(".select-elenco-filiali");
			var piazzatori = jQuery(data).find('Document').find('Placemark');
			
			titoloPiazzatore = new Array();
			var elencoFiliali = "";
			
			if(piazzatori.size() > 0) {
				piazzatori.each(function(index) {
					var piazzatore = jQuery(this);
					titolo = piazzatore.find("name").text();
					elencoFiliali += "<option class='option' value='"+titolo+"'>"+titolo+"</option>";
				});
				dropdown.append(elencoFiliali);
			}
		},
		error: function() {
			alert("errore");
		}
	});
}

function loadevidence() {
	ajaxurl = urlpath2;
	
	$("#evidenza").load(ajaxurl + " #evidence", function(response, status) {
		var contenuto = $("#evidenza").html();
		if(status == "success" ) {
			if(contenuto != ''){
				$("#evidenza").show();
			}
		}
	});
}
