window.___gcfg = {lang: 'it'};
//var abs_url = "/";
var abs_url = "/";
$(document).ready(function(){
	gallerySlider();
	doColorBox();
});


function gallerySlider(name) {
	if(!name)
	  name = ".gallery_slider";
	  
	var numeroLiPoint = $(name + " ul.slides li").size();
	var largLi = $(name + " li").width(); 
	var largLiTot = numeroLiPoint*largLi;
	var termina = largLiTot-largLi;
	
	
	//larghezza dinamica dell'ul
	var boxUl = $(name + " ul.slides");
	boxUl.css("width",largLiTot);
	
	$(name + '-right').bind('click', moveBox1);
	function moveBox1(e1) {
	e1.preventDefault();
		$(name + '-right').unbind();
		if(boxUl.css("left")!=-termina+"px"){
			boxUl.stop().animate({left:"-="+largLi+"px"}, {
			duration: 500,
			complete: function() {
				$(name + '-right').bind('click', moveBox1);
				palliniInversa();
			}
			
		  });
		}
		else {
			$(name + '-right').bind('click', moveBox1);
		}
	}
	
	$(name + '-left').bind('click', moveBox2);
	function moveBox2(e2) {
	e2.preventDefault();
		$(name + '-left').unbind();
		if(boxUl.css("left")!="0px"){
			boxUl.stop().animate({left:"+="+largLi+"px"}, {
			duration: 500,
			complete: function() {
				$(name + '-left').bind('click', moveBox2);
				palliniInversa();
			}
		  });
		}
		else {
			$(name + '-left').bind('click', moveBox2);
			}
	}
	
	
	//creazione pallini
	for(i=0; i<numeroLiPoint; i++){
		$(name + "-spots").append("<li></li>");
	}
	//calcolo dinamico larghezza contenitore pallini
	var largPallini = $(name + "-spots li").width();
	$(name + "-spots").width(largPallini*numeroLiPoint);
	
	$(name + "-spots li:eq(0)").addClass("active");
	
	//spostamento dello slider al click sul pallino
	$(name + "-spots li").click(function(){
		$(name + "-spots li").removeClass("active");
		$(this).addClass("active");
		var indicePallini = $(name + "-spots li").index(this);
		boxUl.stop().animate({left:0-(indicePallini*largLi)}, {duration: 500});
		
		//sicurezza
		$(name + '-left').bind('click', moveBox2);
		$(name + '-right').bind('click', moveBox1);
	});
	
	function palliniInversa() {
		var boxLeft = parseInt(boxUl.css("left"));
		var indexPal = parseInt(-boxLeft/largLi);
		$(name + "-spots li").removeClass("active");
		$(name + "-spots li").eq(indexPal).addClass("active");
	}
}
$(document).ready(function(){
  $("a.landing_page").each(function(){
    $(this).click(function(event){
      event.preventDefault();
      $("div.landing_page").hide();
      $($(this).attr("href")).show();
    });
  });
});$(document).ready(function(){
	gallerySlider();
	doColorBox();
});


function gallerySlider(name) {
	if(!name)
	  name = ".gallery_slider";
	  
	var numeroLiPoint = $(name + " ul.slides li").size();
	var largLi = $(name + " li").width(); 
	var largLiTot = numeroLiPoint*largLi;
	var termina = largLiTot-largLi;
	
	
	//larghezza dinamica dell'ul
	var boxUl = $(name + " ul.slides");
	boxUl.css("width",largLiTot);
	
	$(name + '-right').bind('click', moveBox1);
	function moveBox1(e1) {
	e1.preventDefault();
		$(name + '-right').unbind();
		if(boxUl.css("left")!=-termina+"px"){
			boxUl.stop().animate({left:"-="+largLi+"px"}, {
			duration: 500,
			complete: function() {
				$(name + '-right').bind('click', moveBox1);
				palliniInversa();
			}
			
		  });
		}
		else {
			$(name + '-right').bind('click', moveBox1);
		}
	}
	
	$(name + '-left').bind('click', moveBox2);
	function moveBox2(e2) {
	e2.preventDefault();
		$(name + '-left').unbind();
		if(boxUl.css("left")!="0px"){
			boxUl.stop().animate({left:"+="+largLi+"px"}, {
			duration: 500,
			complete: function() {
				$(name + '-left').bind('click', moveBox2);
				palliniInversa();
			}
		  });
		}
		else {
			$(name + '-left').bind('click', moveBox2);
			}
	}
	
	
	//creazione pallini
	for(i=0; i<numeroLiPoint; i++){
		$(name + "-spots").append("<li></li>");
	}
	//calcolo dinamico larghezza contenitore pallini
	var largPallini = $(name + "-spots li").width();
	$(name + "-spots").width(largPallini*numeroLiPoint);
	
	$(name + "-spots li:eq(0)").addClass("active");
	
	//spostamento dello slider al click sul pallino
	$(name + "-spots li").click(function(){
		$(name + "-spots li").removeClass("active");
		$(this).addClass("active");
		var indicePallini = $(name + "-spots li").index(this);
		boxUl.stop().animate({left:0-(indicePallini*largLi)}, {duration: 500});
		
		//sicurezza
		$(name + '-left').bind('click', moveBox2);
		$(name + '-right').bind('click', moveBox1);
	});
	
	function palliniInversa() {
		var boxLeft = parseInt(boxUl.css("left"));
		var indexPal = parseInt(-boxLeft/largLi);
		$(name + "-spots li").removeClass("active");
		$(name + "-spots li").eq(indexPal).addClass("active");
	}
}

$(document).ready(function(){
	for(var id in slider_data)
		loadContent(id);
});

function loadContent(id)
{
	var e = slider_data[id];
	var tbl = e.table;
	var where = e.where;
	var order_by = e.order_by;
	var text = e.text;
	var link = e.link;
	
	//carico il contenuto
	var cnt = jsonSyncRequest("getNextSlider", {"p1":tbl, "p2":where, "p3":order_by, "p4":id, "p5":text, "p6":link});
	var size = $("#" + id).find("li:first-child").width();
	
	var li = isEmpty(cnt.link) ? cnt.text : "<a href='"+cnt.link+".html'>"+cnt.text+"</a>";
	
	$("#" + id).css("opacity", "0").append("<li>" + li + "</li>");
	$("#" + id).animate({
			left: "-=" + size,
			opacity: 1
		}, 
		1500, 
		'easeOutCirc', 
		function(){
			$($("#" + id).children("li")[0]).remove();
			$("#" + id).css("left", "0px");
			setTimeout("loadContent('"+id+"')",5000);
		} 
	);

	
}
var latlng;
var infowindow;
var marker;
var map;
var icons;
var directionsService;
var directionsRenderer;
/*
$(document).ready(function(){
	//Importo le librerie di google maps
	$.getScript("http://maps.googleapis.com/maps/api/js?sensor=false&language="+id_lingua+"&region=IT&async=2", function(){
		//Importo la libreria per effettuare le ricerche
		//La funzione _mapScriptLoaed viene richiamata dal parametro callback nella chiamata alle librerie di google maps
		$.getScript("http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false&language="+id_lingua+"&region=IT&async=2&callback=_mapScriptLoaed", function(data, textStatus){});
	});
});
*/
function _mapScriptLoaed()
{
	$("#map_search_button").click(function(){fetchDirection()});
	
	latlng = new google.maps.LatLng(icbm[0], icbm[1]); 
	
    var mapOptions = {
      zoom: 11,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    
    map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
	
	directionsService = new google.maps.DirectionsService();
	
	directionsRenderer = new google.maps.DirectionsRenderer();
	directionsRenderer.setMap(map);
	directionsRenderer.setOptions({
		suppressMarkers: true
	});
    	
      
    // Imposto il marker di STR
	icons = {
		start: new google.maps.MarkerImage(
			// URL
			abs_url + '/graph/map_start.png',
			// (width,height)
			new google.maps.Size( 32, 37 ),
			// The origin point (x,y)
			new google.maps.Point( 0, 0 ),
			// The anchor point (x,y)
			new google.maps.Point( 16, 37 )
		),
		end: new google.maps.MarkerImage(
			// URL
			abs_url + '/graph/map_destination.png',
			// (width,height)
			new google.maps.Size( 32, 37 ),
			// The origin point (x,y)
			new google.maps.Point( 0, 0 ),
			// The anchor point (x,y)
			new google.maps.Point( 16, 37 )
		)
	};
	
    markers = {
    	destination: new google.maps.Marker({
	          position: latlng,
	          map: map,
	          draggable: false,
	          animation: google.maps.Animation.DROP,
	          clickable: true,
	          icon: icons.end
	        }),
        from:null
    };
        
    google.maps.event.addListener(markers.destination, 'click', function() {
	    infowindow.open(map, markers.destination);
    });
    // ----------------------

    // Fumettino con info su STR
    infowindow = new google.maps.InfoWindow({
      content: document.getElementById("str_marker_content").innerHTML,
      position:latlng
    });
    // --------------------------

    // Imposto l'autocomplete
    var autocomplete = new google.maps.places.Autocomplete(document.getElementById('map_search_from'));
    autocomplete.bindTo('bounds', map);

    google.maps.event.addListener(autocomplete, 'place_changed', function() {
      infowindow.close();
      fetchDirection(autocomplete.getPlace().geometry.location);
    });
    // ---------
}

function fetchDirection(start_position){
	var from = (start_position ? start_position : $("#map_search_from").val());
	if(markers.from)
		markers.from.setMap(null);
	var request = {
    	origin:from,
    	destination:latlng,
    	travelMode: google.maps.TravelMode.DRIVING
  	};
	directionsService.route(request, function(result, status) {
	    if (status == google.maps.DirectionsStatus.OK) {
			directionsRenderer.setDirections(result);
			console.log(result);
			var leg = result.routes[ 0 ].legs[ 0 ];
			makeMarker( leg.start_location, icons.start);
	    }
  	});
}

function makeMarker( location, icon )
{
	markers.from = new google.maps.Marker({
	          position: location,
	          map: map,
	          draggable: false,
	          animation: google.maps.Animation.DROP,
	          clickable: true,
	          icon: icon
	});
}
$(document).ready(function(){
	$("a.captcha").click(function(){reload_captcha(); $(this).blur()});

	//Imposto il controllo per il captcha
	$("input.captcha").change(function(){
		$("input.captcha").attr("valid", "n");
		$("input.captcha").removeClass("valid invalid");
		if($("input.captcha").val() == "")
		  return false;
		  
		jsonRequest("checkCaptcha",  {"p1": $("input.captcha").val()}, function(data){
				$("input.captcha").addClass((data == "n" ? "in" : "") + "valid");
				$("input.captcha").attr("valid", data);
		});
	});

})

function reload_captcha()
{
	$("input.captcha").attr("valid", "n");
	$("input.captcha").removeClass("valid invalid");
	$("input.captcha").val("");
	$('img.captcha').attr('src', abs_url + 'lib/si_captcha/securimage_show.php?sid=' + Math.random()); 
	return false
}

function check_captcha()
{
	return $("input.captcha").attr("valid") == "y";
}

$(document).ready( function() {
	$("div.item_preview div.img img").each(function(){
		var parent_h = $(this).parent().height();
		var this_h = $(this).attr("height");
		var top = this_h/2 - parent_h/2;
		$(this).css("margin-top", "-" +  top + "px");
	});
});

function check_contatti()
{
	//check_captcha
	var nome = document.frmContatti.nome.value;
	var cognome = document.frmContatti.cognome.value;
	var email = document.frmContatti.email.value;
	var telefono = document.frmContatti.telefono.value;
	var messaggio = document.frmContatti.messaggio.value;
	
	if (nome != "" && nome != "nome" && cognome != "" && cognome != "cognome" &&  email != "" && email != "e-mail" &&  messaggio != "")
	{
		if (email.indexOf("@")==-1)
			alert("Email non valida");
		else
			return true;
	}
	else
		alert("Riempire i campi nome, cognome, email e messaggio");

	
	return false;	
}
var class_skype = "offline";
var current_url = abs_url + ".html";
/* Italian initialisation for the jQuery UI date picker plugin. */
/* Written by Antonello Pasella (antonello.pasella@gmail.com). */
jQuery(function($){
	$.datepicker.regional['it'] = {
		closeText: 'Chiudi',
		prevText: '&#x3c;Prec',
		nextText: 'Succ&#x3e;',
		currentText: 'Oggi',
		monthNames: ['Gennaio','Febbraio','Marzo','Aprile','Maggio','Giugno',
			'Luglio','Agosto','Settembre','Ottobre','Novembre','Dicembre'],
		monthNamesShort: ['Gen','Feb','Mar','Apr','Mag','Giu',
			'Lug','Ago','Set','Ott','Nov','Dic'],
		dayNames: ['Domenica','Luned&#236','Marted&#236','Mercoled&#236','Gioved&#236','Venerd&#236','Sabato'],
		dayNamesShort: ['Dom','Lun','Mar','Mer','Gio','Ven','Sab'],
		dayNamesMin: ['Do','Lu','Ma','Me','Gi','Ve','Sa'],
		weekHeader: 'Sm',
		dateFormat: 'dd/mm/yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['it']);
});

/* 
	############################################################
				PLUGIN JQUERY USATI NEL FRAMEWORK
	############################################################
*/

// ColorBox v1.3.17.2 - a full featured, light-weight, customizable lightbox based on jQuery 1.3+
// Copyright (c) 2011 Jack Moore - jack@colorpowered.com
// Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php

(function ($, document, window) {
	var
	// ColorBox Default Settings.	
	// See http://colorpowered.com/colorbox for details.
	defaults = {
	  iframeName: "", // Aggiunta possibilità di specificare il nome dell'iframe
		transition: "elastic",
		speed: 300,
		width: false,
		initialWidth: "600",
		innerWidth: false,
		maxWidth: false,
		height: false,
		initialHeight: "450",
		innerHeight: false,
		maxHeight: false,
		scalePhotos: true,
		scrolling: true,
		inline: false,
		html: false,
		iframe: false,
		fastIframe: true,
		photo: false,
		href: false,
		title: false,
		rel: false,
		opacity: 0.9,
		preloading: true,
		//current: "image {current} of {total}",
		current: "{current} / {total}",
		previous: "previous",
		next: "next",
		close: "close",
		open: false,
		returnFocus: true,
		loop: true,
		slideshow: false,
		slideshowAuto: true,
		slideshowSpeed: 2500,
		slideshowStart: "start slideshow",
		slideshowStop: "stop slideshow",
		onOpen: false,
		onLoad: false,
		onComplete: false,
		onCleanup: false,
		onClosed: false,
		overlayClose: true,		
		escKey: true,
		arrowKey: true,
        top: false,
        bottom: false,
        left: false,
        right: false,
        fixed: false,
        data: false
	},
	
	// Abstracting the HTML and event identifiers for easy rebranding
	colorbox = 'colorbox',
	prefix = 'cbox',
    boxElement = prefix + 'Element',
	
	// Events	
	event_open = prefix + '_open',
	event_load = prefix + '_load',
	event_complete = prefix + '_complete',
	event_cleanup = prefix + '_cleanup',
	event_closed = prefix + '_closed',
	event_purge = prefix + '_purge',
	
	// Special Handling for IE
	isIE = $.browser.msie && !$.support.opacity, // Detects IE6,7,8.  IE9 supports opacity.  Feature detection alone gave a false positive on at least one phone browser and on some development versions of Chrome, hence the user-agent test.
	isIE6 = isIE && $.browser.version < 7,
	event_ie6 = prefix + '_IE6',

	// Cached jQuery Object Variables
	$overlay,
	$box,
	$wrap,
	$content,
	$topBorder,
	$leftBorder,
	$rightBorder,
	$bottomBorder,
	$related,
	$window,
	$loaded,
	$loadingBay,
	$loadingOverlay,
	$title,
	$current,
	$slideshow,
	$next,
	$prev,
	$close,
	$groupControls,

	// Variables for cached values or use across multiple functions
	settings,
	interfaceHeight,
	interfaceWidth,
	loadedHeight,
	loadedWidth,
	element,
	index,
	photo,
	open,
	active,
	closing,
    handler,
    loadingTimer,
    publicMethod;
	
	// ****************
	// HELPER FUNCTIONS
	// ****************

	// jQuery object generator to reduce code size
	function $div(id, cssText, div) { 
		div = document.createElement('div');
		if (id) {
            div.id = prefix + id;
        }
		div.style.cssText = cssText || '';
		return $(div);
	}

	// Convert '%' and 'px' values to integers
	function setSize(size, dimension) {
		return Math.round((/%/.test(size) ? ((dimension === 'x' ? $window.width() : $window.height()) / 100) : 1) * parseInt(size, 10));
	}
	
	// Checks an href to see if it is a photo.
	// There is a force photo option (photo: true) for hrefs that cannot be matched by this regex.
	function isImage(url) {
		return settings.photo || /\.(gif|png|jpg|jpeg|bmp)(?:\?([^#]*))?(?:#(\.*))?$/i.test(url);
	}
	
	// Assigns function results to their respective settings.  This allows functions to be used as values.
	function makeSettings(i) {
        settings = $.extend({}, $.data(element, colorbox));
        
		for (i in settings) {
			if ($.isFunction(settings[i]) && i.substring(0, 2) !== 'on') { // checks to make sure the function isn't one of the callbacks, they will be handled at the appropriate time.
			    settings[i] = settings[i].call(element);
			}
		}
        
		settings.rel = settings.rel || element.rel || 'nofollow';
		settings.href = settings.href || $(element).attr('href');
		settings.title = settings.title || element.title;
        
        if (typeof settings.href === "string") {
            settings.href = $.trim(settings.href);
        }
	}

	function trigger(event, callback) {
		if (callback) {
			callback.call(element);
		}
		$.event.trigger(event);
	}

	// Slideshow functionality
	function slideshow() {
		var
		timeOut,
		className = prefix + "Slideshow_",
		click = "click." + prefix,
		start,
		stop,
		clear;
		
		if (settings.slideshow && $related[1]) {
			start = function () {
				$slideshow
					.text(settings.slideshowStop)
					.unbind(click)
					.bind(event_complete, function () {
						if (index < $related.length - 1 || settings.loop) {
							timeOut = setTimeout(publicMethod.next, settings.slideshowSpeed);
						}
					})
					.bind(event_load, function () {
						clearTimeout(timeOut);
					})
					.one(click + ' ' + event_cleanup, stop);
				$box.removeClass(className + "off").addClass(className + "on");
				timeOut = setTimeout(publicMethod.next, settings.slideshowSpeed);
			};
			
			stop = function () {
				clearTimeout(timeOut);
				$slideshow
					.text(settings.slideshowStart)
					.unbind([event_complete, event_load, event_cleanup, click].join(' '))
					.one(click, start);
				$box.removeClass(className + "on").addClass(className + "off");
			};
			
			if (settings.slideshowAuto) {
				start();
			} else {
				stop();
			}
		} else {
            $box.removeClass(className + "off " + className + "on");
        }
	}

	function launch(target) {
		if (!closing) {
			
			element = target;
			
			makeSettings();
			
			$related = $(element);
			
			index = 0;
			
			if (settings.rel !== 'nofollow') {
				$related = $('.' + boxElement).filter(function () {
					var relRelated = $.data(this, colorbox).rel || this.rel;
					return (relRelated === settings.rel);
				});
				index = $related.index(element);
				
				// Check direct calls to ColorBox.
				if (index === -1) {
					$related = $related.add(element);
					index = $related.length - 1;
				}
			}
			
			if (!open) {
				open = active = true; // Prevents the page-change action from queuing up if the visitor holds down the left or right keys.
				
				$box.show();
				
				if (settings.returnFocus) {
					try {
						element.blur();
						$(element).one(event_closed, function () {
							try {
								this.focus();
							} catch (e) {
								// do nothing
							}
						});
					} catch (e) {
						// do nothing
					}
				}
				
				// +settings.opacity avoids a problem in IE when using non-zero-prefixed-string-values, like '.5'
				$overlay.css({"opacity": +settings.opacity, "cursor": settings.overlayClose ? "pointer" : "auto"}).show();
				
				// Opens inital empty ColorBox prior to content being loaded.
				settings.w = setSize(settings.initialWidth, 'x');
				settings.h = setSize(settings.initialHeight, 'y');
				publicMethod.position();
				
				if (isIE6) {
					$window.bind('resize.' + event_ie6 + ' scroll.' + event_ie6, function () {
						$overlay.css({width: $window.width(), height: $window.height(), top: $window.scrollTop(), left: $window.scrollLeft()});
					}).trigger('resize.' + event_ie6);
				}
				
				trigger(event_open, settings.onOpen);
				
				$groupControls.add($title).hide();
				
				$close.html(settings.close).show();
			}
			
			publicMethod.load(true);
		}
	}

	// ****************
	// PUBLIC FUNCTIONS
	// Usage format: $.fn.colorbox.close();
	// Usage from within an iframe: parent.$.fn.colorbox.close();
	// ****************
	
	publicMethod = $.fn[colorbox] = $[colorbox] = function (options, callback) {
		var $this = this;
		
        options = options || {};
        
		if (!$this[0]) {
			if ($this.selector) { // if a selector was given and it didn't match any elements, go ahead and exit.
                return $this;
            }
            // if no selector was given (ie. $.colorbox()), create a temporary element to work with
			$this = $('<a/>');
			options.open = true; // assume an immediate open
		}
		
		if (callback) {
			options.onComplete = callback;
		}
		
		$this.each(function () {
			$.data(this, colorbox, $.extend({}, $.data(this, colorbox) || defaults, options));
			$(this).addClass(boxElement);
		});
		
        if (($.isFunction(options.open) && options.open.call($this)) || options.open) {
			launch($this[0]);
		}
        
		return $this;
	};

	// Initialize ColorBox: store common calculations, preload the interface graphics, append the html.
	// This preps ColorBox for a speedy open when clicked, and minimizes the burdon on the browser by only
	// having to run once, instead of each time colorbox is opened.
	publicMethod.init = function () {
		// Create & Append jQuery Objects
		$window = $(window);
		$box = $div().attr({id: colorbox, 'class': isIE ? prefix + (isIE6 ? 'IE6' : 'IE') : ''});
		$overlay = $div("Overlay", isIE6 ? 'position:absolute' : '').hide();
		
		$wrap = $div("Wrapper");
		$content = $div("Content").append(
			$loaded = $div("LoadedContent", 'width:0; height:0; overflow:hidden'),
			$loadingOverlay = $div("LoadingOverlay").add($div("LoadingGraphic")),
			$title = $div("Title"),
			$current = $div("Current"),
			$next = $div("Next"),
			$prev = $div("Previous"),
			$slideshow = $div("Slideshow").bind(event_open, slideshow),
			$close = $div("Close")
		);
		$wrap.append( // The 3x3 Grid that makes up ColorBox
			$div().append(
				$div("TopLeft"),
				$topBorder = $div("TopCenter"),
				$div("TopRight")
			),
			$div(false, 'clear:left').append(
				$leftBorder = $div("MiddleLeft"),
				$content,
				$rightBorder = $div("MiddleRight")
			),
			$div(false, 'clear:left').append(
				$div("BottomLeft"),
				$bottomBorder = $div("BottomCenter"),
				$div("BottomRight")
			)
		).children().children().css({'float': 'left'});
		
		$loadingBay = $div(false, 'position:absolute; width:9999px; visibility:hidden; display:none');
		
		$('body').prepend($overlay, $box.append($wrap, $loadingBay));
		
		$content.children()
		.hover(function () {
			$(this).addClass('hover');
		}, function () {
			$(this).removeClass('hover');
		}).addClass('hover');
		
		// Cache values needed for size calculations
		interfaceHeight = $topBorder.height() + $bottomBorder.height() + $content.outerHeight(true) - $content.height();//Subtraction needed for IE6
		interfaceWidth = $leftBorder.width() + $rightBorder.width() + $content.outerWidth(true) - $content.width();
		loadedHeight = $loaded.outerHeight(true);
		loadedWidth = $loaded.outerWidth(true);
		
		// Setting padding to remove the need to do size conversions during the animation step.
		$box.css({"padding-bottom": interfaceHeight, "padding-right": interfaceWidth}).hide();
		
        // Setup button events.
        // Anonymous functions here keep the public method from being cached, thereby allowing them to be redefined on the fly.
        $next.click(function () {
            publicMethod.next();
        });
        $prev.click(function () {
            publicMethod.prev();
        });
        $close.click(function () {
            publicMethod.close();
        });
		
		$groupControls = $next.add($prev).add($current).add($slideshow);
		
		// Adding the 'hover' class allowed the browser to load the hover-state
		// background graphics in case the images were not part of a sprite.  The class can now can be removed.
		$content.children().removeClass('hover');
		
		$overlay.click(function () {
			if (settings.overlayClose) {
				publicMethod.close();
			}
		});
		
		// Set Navigation Key Bindings
		$(document).bind('keydown.' + prefix, function (e) {
            var key = e.keyCode;
			if (open && settings.escKey && key === 27) {
				e.preventDefault();
				publicMethod.close();
			}
			if (open && settings.arrowKey && $related[1]) {
				if (key === 37) {
					e.preventDefault();
					$prev.click();
				} else if (key === 39) {
					e.preventDefault();
					$next.click();
				}
			}
		});
	};
	
	publicMethod.remove = function () {
		$box.add($overlay).remove();
		$('.' + boxElement).removeData(colorbox).removeClass(boxElement);
	};

	publicMethod.position = function (speed, loadedCallback) {
        var top = 0, left = 0;
        
        $window.unbind('resize.' + prefix);
        
        // remove the modal so that it doesn't influence the document width/height        
        $box.hide();
        
        if (settings.fixed && !isIE6) {
            $box.css({position: 'fixed'});
        } else {
            top = $window.scrollTop();
            left = $window.scrollLeft();
            $box.css({position: 'absolute'});
        }
        
		// keeps the top and left positions within the browser's viewport.
        if (settings.right !== false) {
            left += Math.max($window.width() - settings.w - loadedWidth - interfaceWidth - setSize(settings.right, 'x'), 0);
        } else if (settings.left !== false) {
            left += setSize(settings.left, 'x');
        } else {
            left += Math.round(Math.max($window.width() - settings.w - loadedWidth - interfaceWidth, 0) / 2);
        }
        
        if (settings.bottom !== false) {
            top += Math.max(document.documentElement.clientHeight - settings.h - loadedHeight - interfaceHeight - setSize(settings.bottom, 'y'), 0);
        } else if (settings.top !== false) {
            top += setSize(settings.top, 'y');
        } else {
            top += Math.round(Math.max(document.documentElement.clientHeight - settings.h - loadedHeight - interfaceHeight, 0) / 2);
        }
        
        $box.show();
        
		// setting the speed to 0 to reduce the delay between same-sized content.
		speed = ($box.width() === settings.w + loadedWidth && $box.height() === settings.h + loadedHeight) ? 0 : speed || 0;
        
		// this gives the wrapper plenty of breathing room so it's floated contents can move around smoothly,
		// but it has to be shrank down around the size of div#colorbox when it's done.  If not,
		// it can invoke an obscure IE bug when using iframes.
		$wrap[0].style.width = $wrap[0].style.height = "9999px";
		
		function modalDimensions(that) {
			// loading overlay height has to be explicitly set for IE6.
			$topBorder[0].style.width = $bottomBorder[0].style.width = $content[0].style.width = that.style.width;
			$loadingOverlay[0].style.height = $loadingOverlay[1].style.height = $content[0].style.height = $leftBorder[0].style.height = $rightBorder[0].style.height = that.style.height;
		}
		
		$box.dequeue().animate({width: settings.w + loadedWidth, height: settings.h + loadedHeight, top: top, left: left}, {
			duration: speed,
			complete: function () {
				modalDimensions(this);
				
				active = false;
				
				// shrink the wrapper down to exactly the size of colorbox to avoid a bug in IE's iframe implementation.
				$wrap[0].style.width = (settings.w + loadedWidth + interfaceWidth) + "px";
				$wrap[0].style.height = (settings.h + loadedHeight + interfaceHeight) + "px";
				
				if (loadedCallback) {
					loadedCallback();
				}
                
                setTimeout(function(){  // small delay before binding onresize due to an IE8 bug.
                    $window.bind('resize.' + prefix, publicMethod.position);
                }, 1);
			},
			step: function () {
				modalDimensions(this);
			}
		});
	};

	publicMethod.resize = function (options) {
		if (open) {
			options = options || {};
			
			if (options.width) {
				settings.w = setSize(options.width, 'x') - loadedWidth - interfaceWidth;
			}
			if (options.innerWidth) {
				settings.w = setSize(options.innerWidth, 'x');
			}
			$loaded.css({width: settings.w});
			
			if (options.height) {
				settings.h = setSize(options.height, 'y') - loadedHeight - interfaceHeight;
			}
			if (options.innerHeight) {
				settings.h = setSize(options.innerHeight, 'y');
			}
			if (!options.innerHeight && !options.height) {				
				var $child = $loaded.wrapInner("<div style='overflow:auto'></div>").children(); // temporary wrapper to get an accurate estimate of just how high the total content should be.
				settings.h = $child.height();
				$child.replaceWith($child.children()); // ditch the temporary wrapper div used in height calculation
			}
			$loaded.css({height: settings.h});
			
			publicMethod.position(settings.transition === "none" ? 0 : settings.speed);
		}
	};

	publicMethod.prep = function (object) {
		if (!open) {
			return;
		}
		
		var callback, speed = settings.transition === "none" ? 0 : settings.speed;
		
		$loaded.remove();
		$loaded = $div('LoadedContent').append(object);
		
		function getWidth() {
			settings.w = settings.w || $loaded.width();
			settings.w = settings.mw && settings.mw < settings.w ? settings.mw : settings.w;
			return settings.w;
		}
		function getHeight() {
			settings.h = settings.h || $loaded.height();
			settings.h = settings.mh && settings.mh < settings.h ? settings.mh : settings.h;
			return settings.h;
		}
		
		$loaded.hide()
		.appendTo($loadingBay.show())// content has to be appended to the DOM for accurate size calculations.
		.css({width: getWidth(), overflow: settings.scrolling ? 'auto' : 'hidden'})
		.css({height: getHeight()})// sets the height independently from the width in case the new width influences the value of height.
		.prependTo($content);
		
		$loadingBay.hide();
		
		// floating the IMG removes the bottom line-height and fixed a problem where IE miscalculates the width of the parent element as 100% of the document width.
		//$(photo).css({'float': 'none', marginLeft: 'auto', marginRight: 'auto'});
		
        $(photo).css({'float': 'none'});
        
		// Hides SELECT elements in IE6 because they would otherwise sit on top of the overlay.
		if (isIE6) {
			$('select').not($box.find('select')).filter(function () {
				return this.style.visibility !== 'hidden';
			}).css({'visibility': 'hidden'}).one(event_cleanup, function () {
				this.style.visibility = 'inherit';
			});
		}
		
		callback = function () {
            var prev, prevSrc, next, nextSrc, total = $related.length, iframe, complete;
            
            if (!open) {
                return;
            }
            
            function removeFilter() {
                if (isIE) {
                    $box[0].style.removeAttribute('filter');
                }
            }
            
            complete = function () {
                clearTimeout(loadingTimer);
                $loadingOverlay.hide();
                trigger(event_complete, settings.onComplete);
            };
            
            if (isIE) {
                //This fadeIn helps the bicubic resampling to kick-in.
                if (photo) {
                    $loaded.fadeIn(100);
                }
            }
            
            $title.html(settings.title).add($loaded).show();
            
            if (total > 1) { // handle grouping
                if (typeof settings.current === "string") {
                    $current.html(settings.current.replace('{current}', index + 1).replace('{total}', total)).show();
                }
                
                $next[(settings.loop || index < total - 1) ? "show" : "hide"]().html(settings.next);
                $prev[(settings.loop || index) ? "show" : "hide"]().html(settings.previous);
                
                prev = index ? $related[index - 1] : $related[total - 1];
                next = index < total - 1 ? $related[index + 1] : $related[0];
                
                if (settings.slideshow) {
                    $slideshow.show();
                }
                
                // Preloads images within a rel group
                if (settings.preloading) {
                    nextSrc = $.data(next, colorbox).href || next.href;
                    prevSrc = $.data(prev, colorbox).href || prev.href;
                    
                    nextSrc = $.isFunction(nextSrc) ? nextSrc.call(next) : nextSrc;
                    prevSrc = $.isFunction(prevSrc) ? prevSrc.call(prev) : prevSrc;
                    
                    if (isImage(nextSrc)) {
                        $('<img/>')[0].src = nextSrc;
                    }
                    
                    if (isImage(prevSrc)) {
                        $('<img/>')[0].src = prevSrc;
                    }
                }
            } else {
                $groupControls.hide();
            }
            
            if (settings.iframe) {
                iframe = $('<iframe/>').addClass(prefix + 'Iframe')[0];
                
                if (settings.fastIframe) {
                    complete();
                } else {
                    $(iframe).one('load', complete);
                }
                iframe.name = (settings.iframeName != ""  ? settings.iframeName : prefix + (+new Date()));
                iframe.src = settings.href;
                
                if (!settings.scrolling) {
                    iframe.scrolling = "no";
                }
                
                if (isIE) {
                    iframe.frameBorder = 0;
                    iframe.allowTransparency = "true";
                }
                
                $(iframe).appendTo($loaded).one(event_purge, function () {
                    iframe.src = "//about:blank";
                });
            } else {
                complete();
            }
            
            if (settings.transition === 'fade') {
                $box.fadeTo(speed, 1, removeFilter);
            } else {
                removeFilter();
            }
		};
		
		if (settings.transition === 'fade') {
			$box.fadeTo(speed, 0, function () {
				publicMethod.position(0, callback);
			});
		} else {
			publicMethod.position(speed, callback);
		}
	};

	publicMethod.load = function (launched) {
		var href, setResize, prep = publicMethod.prep;
		
		active = true;
		
		photo = false;
		
		element = $related[index];
		
		if (!launched) {
			makeSettings();
		}
		
		trigger(event_purge);
		
		trigger(event_load, settings.onLoad);
		
		settings.h = settings.height ?
				setSize(settings.height, 'y') - loadedHeight - interfaceHeight :
				settings.innerHeight && setSize(settings.innerHeight, 'y');
		
		settings.w = settings.width ?
				setSize(settings.width, 'x') - loadedWidth - interfaceWidth :
				settings.innerWidth && setSize(settings.innerWidth, 'x');
		
		// Sets the minimum dimensions for use in image scaling
		settings.mw = settings.w;
		settings.mh = settings.h;
		
		// Re-evaluate the minimum width and height based on maxWidth and maxHeight values.
		// If the width or height exceed the maxWidth or maxHeight, use the maximum values instead.
		if (settings.maxWidth) {
			settings.mw = setSize(settings.maxWidth, 'x') - loadedWidth - interfaceWidth;
			settings.mw = settings.w && settings.w < settings.mw ? settings.w : settings.mw;
		}
		if (settings.maxHeight) {
			settings.mh = setSize(settings.maxHeight, 'y') - loadedHeight - interfaceHeight;
			settings.mh = settings.h && settings.h < settings.mh ? settings.h : settings.mh;
		}
		
		href = settings.href;
		
        loadingTimer = setTimeout(function () {
            $loadingOverlay.show();
        }, 100);
        
		if (settings.inline) {
			// Inserts an empty placeholder where inline content is being pulled from.
			// An event is bound to put inline content back when ColorBox closes or loads new content.
			$div().hide().insertBefore($(href)[0]).one(event_purge, function () {
				$(this).replaceWith($loaded.children());
			});
			prep($(href));
		} else if (settings.iframe) {
			// IFrame element won't be added to the DOM until it is ready to be displayed,
			// to avoid problems with DOM-ready JS that might be trying to run in that iframe.
			prep(" ");
		} else if (settings.html) {
			prep(settings.html);
		} else if (isImage(href)) {
			$(photo = new Image())
			.addClass(prefix + 'Photo')
			.error(function () {
				settings.title = false;
				prep($div('Error').text('This image could not be loaded'));
			})
			.load(function () {
				var percent;
				photo.onload = null; //stops animated gifs from firing the onload repeatedly.
				
				if (settings.scalePhotos) {
					setResize = function () {
						photo.height -= photo.height * percent;
						photo.width -= photo.width * percent;	
					};
					if (settings.mw && photo.width > settings.mw) {
						percent = (photo.width - settings.mw) / photo.width;
						setResize();
					}
					if (settings.mh && photo.height > settings.mh) {
						percent = (photo.height - settings.mh) / photo.height;
						setResize();
					}
				}
				
				if (settings.h) {
					photo.style.marginTop = Math.max(settings.h - photo.height, 0) / 2 + 'px';
				}
				
				if ($related[1] && (index < $related.length - 1 || settings.loop)) {
					photo.style.cursor = 'pointer';
					photo.onclick = function () {
                        publicMethod.next();
                    };
				}
				
				if (isIE) {
					photo.style.msInterpolationMode = 'bicubic';
				}
				
				setTimeout(function () { // A pause because Chrome will sometimes report a 0 by 0 size otherwise.
					prep(photo);
				}, 1);
			});
			
			setTimeout(function () { // A pause because Opera 10.6+ will sometimes not run the onload function otherwise.
				photo.src = href;
			}, 1);
		} else if (href) {
			$loadingBay.load(href, settings.data, function (data, status, xhr) {
				prep(status === 'error' ? $div('Error').text('Request unsuccessful: ' + xhr.statusText) : $(this).contents());
			});
		}
	};
        
	// Navigates to the next page/image in a set.
	publicMethod.next = function () {
		if (!active && $related[1] && (index < $related.length - 1 || settings.loop)) {
			index = index < $related.length - 1 ? index + 1 : 0;
			publicMethod.load();
		}
	};
	
	publicMethod.prev = function () {
		if (!active && $related[1] && (index || settings.loop)) {
			index = index ? index - 1 : $related.length - 1;
			publicMethod.load();
		}
	};

	// Note: to use this within an iframe use the following format: parent.$.fn.colorbox.close();
	publicMethod.close = function () {
		if (open && !closing) {
			
			closing = true;
			
			open = false;
			
			trigger(event_cleanup, settings.onCleanup);
			
			$window.unbind('.' + prefix + ' .' + event_ie6);
			
			$overlay.fadeTo(200, 0);
			
			$box.stop().fadeTo(300, 0, function () {
                 
				$box.add($overlay).css({'opacity': 1, cursor: 'auto'}).hide();
				
				trigger(event_purge);
				
				$loaded.remove();
				
				setTimeout(function () {
					closing = false;
					trigger(event_closed, settings.onClosed);
				}, 1);
			});
		}
	};

	// A method for fetching the current element ColorBox is referencing.
	// returns a jQuery object.
	publicMethod.element = function () {
		return $(element);
	};

	publicMethod.settings = defaults;
    
	// Bind the live event before DOM-ready for maximum performance in IE6 & 7.
    handler = function (e) {
        // checks to see if it was a non-left mouse-click and for clicks modified with ctrl, shift, or alt.
        if (!((e.button !== 0 && typeof e.button !== 'undefined') || e.ctrlKey || e.shiftKey || e.altKey)) {
            e.preventDefault();
            launch(this);
        }
    };
    
    if ($.fn.delegate) {
        $(document).delegate('.' + boxElement, 'click', handler);
    } else {
        $('.' + boxElement).live('click', handler);
    }
    
	// Initializes ColorBox when the DOM has loaded
	$(publicMethod.init);

}(jQuery, document, this));




/*
 * jQuery Backstretch
 * Version 1.1.2
 * http://srobbin.com/jquery-plugins/jquery-backstretch/
 *
 * Add a dynamically-resized background image to the page
 *
 * Copyright (c) 2010 Scott Robbin (srobbin.com)
 * Dual licensed under the MIT and GPL licenses.
*/

(function($) {

    $.backstretch = function(src, options, callback) {
        var settings = {
            centeredX: true,         // Should we center the image on the X axis?
            centeredY: true,         // Should we center the image on the Y axis?
            speed: 0,                // fadeIn speed for background after image loads (e.g. "fast" or 500)
            id: "backstretch",       // id di default
            fixed: true,
            height: false,
            className: "backstretch",// classe css del div
            marginTop:0,
            marginBottom:0,
            marginLeft:0,
            marginRight:0
        },
        rootElement = ("onorientationchange" in window) ? $(document) : $(window), // hack to acccount for iOS position:fixed shortcomings
        imgRatio, bgImg, bgWidth, bgHeight, bgOffset, bgCSS;
        
        // Extend the settings with those the user has provided
        if(options && typeof options == "object") $.extend(settings, options);
    
        // Initialize
        $(document).ready(_init);
  
        // For chaining
        return this;
    
        function _init() {
            // Prepend image, wrapped in a DIV, with some positioning and zIndex voodoo
            if(src) {
                var container = $("<div />").attr("id", settings.id).addClass(settings.className)
                                            .css({left: 0, top: 0, position: options.fixed ? "fixed" : "absolute", overflow: "hidden", zIndex: -9999}),
                img = $("<img />").css({position: "relative", display: "none"})
                                      .bind("load", function(e) {                                          
                                          var self = $(this);
                                          imgRatio = $(e.target).width() / $(e.target).height();//( options.height==false ? $(e.target).height() : options.height);
    
                                          _adjustBG(function() {
                                              self.fadeIn(settings.speed, function(){
                                                  if(typeof callback == "function") callback();
                                              });
                                          });
                                      })
                                      .appendTo(container);
                  
				
                $("body").prepend(container);
                img.attr("src", src); // Hack for IE img onload event

                // Adjust the background size when the window is resized or orientation has changed (iOS)
                $(window).resize(_adjustBG);
            }
        }
            
        function _adjustBG(fn) {
            try {
                bgCSS = {left: 0, top: 0}
                bgWidth = rootElement.width();
                bgHeight = bgWidth / imgRatio;

				var max_height = (settings.height == false ? rootElement.height() : options.height) - settings.marginTop - settings.marginBottom;
				
				var div_height = max_height;
				var div_width = rootElement.width() - settings.marginLeft - settings.marginRight;
				
                // Make adjustments based on image ratio
                // Note: Offset code provided by Peter Baker (http://ptrbkr.com/). Thanks, Peter!
                if(bgHeight >= max_height) {
                	
                    bgOffset = (bgHeight - max_height) /2;
                    if(settings.centeredY) $.extend(bgCSS, {top: "-" + bgOffset + "px"});
                    $("#"+settings.id+"").width( div_width ).height( div_height );
                } else {
                    bgHeight = max_height;
                    bgWidth = bgHeight * imgRatio;
                    bgOffset = (bgWidth - rootElement.width()) / 2;
                    if(settings.centeredX) $.extend(bgCSS, {left: "-" + bgOffset + "px"});
                    $("#"+settings.id+"").width( div_width ).height( div_height );
                }
                
                $("#"+settings.id).css({top: settings.marginTop + "px", left: settings.marginLeft + "px"});
                $("#"+settings.id+" img").width( bgWidth ).height( bgHeight ).css(bgCSS);
                //$("#"+settings.id).height( div_height ).css(bgCSS);
            } catch(err) {
                // IE7 seems to trigger _adjustBG before the image is loaded.
                // This try/catch block is a hack to let it fail gracefully.
            }
      
            // Executed the passed in function, if necessary
            if (typeof fn == "function") fn();
        }
    };
  
})(jQuery);

/*
	##### Funzioni x Colorbox
*/
function doColorBox()
{
	if($('a.cb').colorbox)
	{
		$('a.cb').each(function(){
			var params = {
				maxHeight:"90%", 
				maxWidth:"90%",
				iframe: $(this).attr("iframe")=="true",
        inline: $(this).attr("inline")=="true",
        scrolling: true
			};

			if($(this).attr("cb_width")!="")
			  params["width"] = $(this).attr("cb_width");
			if($(this).attr("cb_height")!="")
			  params["height"] = $(this).attr("cb_height");

			/*
			if($(this).attr("ajaxFunction") && $(this).attr("ajaxFunction")!="")
				params["href"] = abs_url + "ajax_controller.php?func=" + $(this).attr("ajaxFunction") + "&p1=" + $(this).attr("href");
			*/
			$(this).colorbox(params);	
		});
	}
}



function getCbParam(params, name, fallbackValue)
{
	if(!params)
	  return eval(fallbackValue) + 20;

	var arr = params.split(",");
	for(var i = 0; i<arr.length; i++)
	{
  	  var s = arr[i];
	  if(s.indexOf(name+"=") == 0)
		  return eval(s.replace(name+"=", "")) + 20;
	}
	
	return "";
}
// ##########################################################
/**
  Funzioni di libreria
*/

function cleanJson(data)
{
	return data.substring(data.indexOf("{"));
}

function jsonRequest(func, params, callback)
{
	$.ajax({
		url: abs_url + "ajax_controller.php",
		data:$.extend({func:func}, params),
		success: function(data){
			if(callback)
				callback(jQuery.parseJSON(cleanJson(data)).result);
		}
	});
}

function jsonSyncRequest(func, params)
{
	var rv = "";
	$.ajax({
		url: abs_url + "ajax_controller.php",
		async: false,
		data:$.extend({func:func}, params),
		success: function(data){
			rv = jQuery.parseJSON(cleanJson(data)).result;
		}
	});
	
	return rv;
}

function myAlert(msg, return_value, callback)
{
	alert(msg);
	if(callback)
	  callback();
	return return_value;
}

function liClick(elem)
{
	/*try
	{
		var a = $(elem).find("a")[0];
	  if(a.href=="#" || a.href=="")
		return;
		
	  if(a.href.indexOf("javascript:") == 0)
	  {
		  eval(a.href);
		  return;
	  }
	  
	  if(a.target == "_blank")
		window.open(a.href);
	  else
		document.location = a.href;
	}
	catch(e){};*/
}


function isMobile(){
  return (/iphone|ipod|ipad|android|blackberry|mini|windows\sce|palm/i.test(navigator.userAgent.toLowerCase()));  
}

function isEmpty(s)
{
	return !(s != null && s != "" && s != "null");
}

function notEmpty()
{
	for(var i=0; i<arguments.length; i++)
		if(arguments[i] != null && arguments[i] != "" && arguments[i] != "null")
			return arguments[i];
}



function get_html_translation_table (table, quote_style) {
    // Returns the internal translation table used by htmlspecialchars and htmlentities  
    // 
    // version: 1107.2516
    // discuss at: http://phpjs.org/functions/get_html_translation_table
    // +   original by: Philip Peterson
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: noname
    // +   bugfixed by: Alex
    // +   bugfixed by: Marco
    // +   bugfixed by: madipta
    // +   improved by: KELAN
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Frank Forte
    // +   bugfixed by: T.Wild
    // +      input by: Ratheous
    // %          note: It has been decided that we're not going to add global
    // %          note: dependencies to php.js, meaning the constants are not
    // %          note: real constants, but strings instead. Integers are also supported if someone
    // %          note: chooses to create the constants themselves.
    // *     example 1: get_html_translation_table('HTML_SPECIALCHARS');
    // *     returns 1: {'"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;'}
    var entities = {},
        hash_map = {},
        decimal = 0,
        symbol = '';
    var constMappingTable = {},
        constMappingQuoteStyle = {};
    var useTable = {},
        useQuoteStyle = {};
 
    // Translate arguments
    constMappingTable[0] = 'HTML_SPECIALCHARS';
    constMappingTable[1] = 'HTML_ENTITIES';
    constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
    constMappingQuoteStyle[2] = 'ENT_COMPAT';
    constMappingQuoteStyle[3] = 'ENT_QUOTES';
 
    useTable = !isNaN(table) ? constMappingTable[table] : table ? table.toUpperCase() : 'HTML_SPECIALCHARS';
    useQuoteStyle = !isNaN(quote_style) ? constMappingQuoteStyle[quote_style] : quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT';
 
    if (useTable !== 'HTML_SPECIALCHARS' && useTable !== 'HTML_ENTITIES') {
        throw new Error("Table: " + useTable + ' not supported');
        // return false;
    }
 
    entities['38'] = '&amp;';
    if (useTable === 'HTML_ENTITIES') {
        entities['160'] = '&nbsp;';
        entities['161'] = '&iexcl;';
        entities['162'] = '&cent;';
        entities['163'] = '&pound;';
        entities['164'] = '&curren;';
        entities['165'] = '&yen;';
        entities['166'] = '&brvbar;';
        entities['167'] = '&sect;';
        entities['168'] = '&uml;';
        entities['169'] = '&copy;';
        entities['170'] = '&ordf;';
        entities['171'] = '&laquo;';
        entities['172'] = '&not;';
        entities['173'] = '&shy;';
        entities['174'] = '&reg;';
        entities['175'] = '&macr;';
        entities['176'] = '&deg;';
        entities['177'] = '&plusmn;';
        entities['178'] = '&sup2;';
        entities['179'] = '&sup3;';
        entities['180'] = '&acute;';
        entities['181'] = '&micro;';
        entities['182'] = '&para;';
        entities['183'] = '&middot;';
        entities['184'] = '&cedil;';
        entities['185'] = '&sup1;';
        entities['186'] = '&ordm;';
        entities['187'] = '&raquo;';
        entities['188'] = '&frac14;';
        entities['189'] = '&frac12;';
        entities['190'] = '&frac34;';
        entities['191'] = '&iquest;';
        entities['192'] = '&Agrave;';
        entities['193'] = '&Aacute;';
        entities['194'] = '&Acirc;';
        entities['195'] = '&Atilde;';
        entities['196'] = '&Auml;';
        entities['197'] = '&Aring;';
        entities['198'] = '&AElig;';
        entities['199'] = '&Ccedil;';
        entities['200'] = '&Egrave;';
        entities['201'] = '&Eacute;';
        entities['202'] = '&Ecirc;';
        entities['203'] = '&Euml;';
        entities['204'] = '&Igrave;';
        entities['205'] = '&Iacute;';
        entities['206'] = '&Icirc;';
        entities['207'] = '&Iuml;';
        entities['208'] = '&ETH;';
        entities['209'] = '&Ntilde;';
        entities['210'] = '&Ograve;';
        entities['211'] = '&Oacute;';
        entities['212'] = '&Ocirc;';
        entities['213'] = '&Otilde;';
        entities['214'] = '&Ouml;';
        entities['215'] = '&times;';
        entities['216'] = '&Oslash;';
        entities['217'] = '&Ugrave;';
        entities['218'] = '&Uacute;';
        entities['219'] = '&Ucirc;';
        entities['220'] = '&Uuml;';
        entities['221'] = '&Yacute;';
        entities['222'] = '&THORN;';
        entities['223'] = '&szlig;';
        entities['224'] = '&agrave;';
        entities['225'] = '&aacute;';
        entities['226'] = '&acirc;';
        entities['227'] = '&atilde;';
        entities['228'] = '&auml;';
        entities['229'] = '&aring;';
        entities['230'] = '&aelig;';
        entities['231'] = '&ccedil;';
        entities['232'] = '&egrave;';
        entities['233'] = '&eacute;';
        entities['234'] = '&ecirc;';
        entities['235'] = '&euml;';
        entities['236'] = '&igrave;';
        entities['237'] = '&iacute;';
        entities['238'] = '&icirc;';
        entities['239'] = '&iuml;';
        entities['240'] = '&eth;';
        entities['241'] = '&ntilde;';
        entities['242'] = '&ograve;';
        entities['243'] = '&oacute;';
        entities['244'] = '&ocirc;';
        entities['245'] = '&otilde;';
        entities['246'] = '&ouml;';
        entities['247'] = '&divide;';
        entities['248'] = '&oslash;';
        entities['249'] = '&ugrave;';
        entities['250'] = '&uacute;';
        entities['251'] = '&ucirc;';
        entities['252'] = '&uuml;';
        entities['253'] = '&yacute;';
        entities['254'] = '&thorn;';
        entities['255'] = '&yuml;';
    }
 
    if (useQuoteStyle !== 'ENT_NOQUOTES') {
        entities['34'] = '&quot;';
    }
    if (useQuoteStyle === 'ENT_QUOTES') {
        entities['39'] = '&#39;';
    }
    entities['60'] = '&lt;';
    entities['62'] = '&gt;';
 
 
    // ascii decimals to real symbols
    for (decimal in entities) {
        symbol = String.fromCharCode(decimal);
        hash_map[symbol] = entities[decimal];
    }
 
    return hash_map;
}

function htmlentities (string, quote_style, charset, double_encode) {
    // Convert all applicable characters to HTML entities  
    // 
    // version: 1107.2516
    // discuss at: http://phpjs.org/functions/htmlentities
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: nobbler
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Ratheous
    // +   improved by: Rafał Kukawski (http://blog.kukawski.pl)
    // -    depends on: get_html_translation_table
    // *     example 1: htmlentities('Kevin & van Zonneveld');
    // *     returns 1: 'Kevin &amp; van Zonneveld'
    // *     example 2: htmlentities("foo'bar","ENT_QUOTES");
    // *     returns 2: 'foo&#039;bar'
    var hash_map = {},
        symbol = '',
        entity = '',
        self = this;
    string += '';
    double_encode = !!double_encode || double_encode == null;
 
    if (false === (hash_map = this.get_html_translation_table('HTML_ENTITIES', quote_style))) {
        return false;
    }
    hash_map["'"] = '&#039;';
    
    if (double_encode) {
        for (symbol in hash_map) {
            entity = hash_map[symbol];
            string = string.split(symbol).join(entity);
        }
    } else {
        string = string.replace(/([\s\S]*?)(&(?:#\d+|#x[\da-f]+|[a-z][\da-z]*);|$)/g, function (ignore, text, entity) {
            return self.htmlentities(text, quote_style, charset) + entity;
        });
    }
 
    return string;
}


function setCalendar(selector, id_lingua){
	$(selector).datepicker();
	
	var dateformat = "mm/dd/yy";
	try{dateformat = $.datepicker.regional[id_lingua].dateFormat}catch(e){}
	var the_form = $(selector).parentsUntil("form").parent();
	dateformat = dateformat.replace("mm", "m").replace("dd", "d").replace("yy", "Y");
	the_form.append("<input type='hidden' class='dateformat' name='dateformat' value='"+dateformat+"'>");
}

var current_sfondo = 0;
var last_sfondo = 0;

var sfondo_timeout;

var gallery = new Array();

$(document).ready(function(){
	/*$("ul.main_menu>li>ul").hide();*/
	$("ul.main_menu > li").hover(
		function(evt){ //Hover :: visualizzo menu
			$(this).find("ul").fadeToggle("fast");
		}/*,
		function(evt){ //Out :: nascondo menu
			$(this).find("ul").fadeOut();
		}*/
	);
	
	//Riposiziono i tasti per la paginazione
	var w = $("div.content_center").width();
	$("div.pager").each(function(){
		var marginLeft = ($(this).hasClass("prev_page") ? -12 : w - $(this).width() -22);
		
		$(this).css({
			top: $("div.content_center").position().top + 15,
			marginLeft: marginLeft
		});

	});
	
	if(!$("body").hasClass("index"))
	{
    var max_h = 0;
    $("div.item_slider div.item_preview").each(function(){
      max_h = Math.max(max_h, $(this).height());
      $(this).data("height", $(this).height());
    });
    $("div.item_slider div.item_preview").height(max_h);
    $("div.item_links").each(function(){
      if($(this).html().trim() == "||")
        $(this).hide();
    });
    
    //Altezza del menu di destra
    var menu_h = $("div.content_left").height();
    
    //Altezza del contenuto
    var cnt_h = $("div.content_center").height();
    
    max_h = Math.max(menu_h, cnt_h);
    
    $("div.content_left").height(max_h + (
      $("body").hasClass("spa_cosmesi")
      ? -16  : 8 ));
      
      $("div.content_center>div:first-child").height(max_h + (
      $("body").hasClass("chatta") || $("body").hasClass("contatti") || $("body").hasClass("item_pacchetti") || $("body").hasClass("sitemap") || $("body").hasClass("press")
      ? ( $("body").hasClass("item_pacchetti") ? -10 : 10) : ($("body").hasClass("item") ? -26 : -16 )
      ));
    
    /*
    // il div content_center deve essere alto li massimo tra se stesso ed il primo div al suo interno
    $("div.content_center").height(
      Math.max($("div.content_center").height(), $("div.content_left").height())
    );

    // il div main_content deve essere alto quanto li massimo tra il div content_left ed il content_center
    $("div.main_content").height(
      Math.max($("div.content_center").height(), $("div.content_left").height()) + 30
    );
    
    if($("div.content_center").children().length == 1)
    {
      // il div contenuto dentro content_center (quando cen'è solo uno) deve essere alto li massimo tra se stesso ed div content_center
      $("div.content_center>div").height(
        Math.max($("div.content_center").height(), $("div.content_center>div").height()) - 20
      );
    }*/
  }
  
  //controllo lo stato di skype sulla home
  $("ul.menu_home li.chatta a").append("<div class='"+class_skype+"' />");
  
	doColorBox();
	
  //english section under construction
  $("div.lingua").hover(
    function(evt){ //Hover :: visualizzo under construction
      $("div.under_construction").fadeIn("fast");
      $(this).animate({borderTopLeftRadius: 0}, "fast");
    },
    function(evt){
      $("div.under_construction").fadeOut("fast");
      $(this).animate({borderTopLeftRadius: 10}, "fast");
    }
  );	
	
	//Recupero il link corrente
	var sel = $($("div.content_left, div.contenuto").find("a[href='"+document.location.pathname+"']")[0]);
	sel.addClass("selected");
	var freccia = $("<div class='freccia_voce_selezionata' />");
	//sel.prepend(freccia);
	
	//Date picker
	//$("input.datepicker").datepicker();
	setCalendar("input.datepicker", "it");
	
	//Zoom in e zoom out
  $("span.zoomIn").click(zoomIn);
  $("span.zoomOut").click(zoomOut);
  
  var gal_elems = $("div.gallery div.gallery_box img");
  for(var i=0; i<gal_elems.length; i++)
     gallery.push($(gal_elems[i]).attr("src"));

  
});

$(window).load(function(){
  try{
    _mapScriptLoaed();
  }catch(e){}

	//Controllo gli eventuali sfondi della pagina
	if(sfondi != null)
	{
		last_sfondo = sfondi.length;
		//In questo modo la pagina finisce di caricare e poi carica lo sfondo
		setTimeout("nextSfondo()",100);
	}
});

function slideShow()
{
  
}

function nextSfondo()
{
	var sfondo = abs_url + "content/sfondi/" + pagina + "/" + sfondi[current_sfondo].path;
	$.backstretch(sfondo, {
		speed:500,
		id:"full_bg_" + current_sfondo,
		fixed: true
	});
	
	if(sfondi.length == 1)
	  return;
	
	var last = (current_sfondo == 0 ? last_sfondo - 1 : current_sfondo - 1);
	
	$("#full_bg_" + (last)).fadeOut(2000, function(){
		$("#full_bg_" + (last)).remove()
	});
	
	current_sfondo++;
	if(current_sfondo == sfondi.length)
		current_sfondo = 0;
	
	sfondo_timeout = setTimeout("nextSfondo()",10000);
}

function loadModule(elem, url, new_id, post_function)
{
	
	dest = $("#" + elem).clone();//$("<div />");
	if(isEmpty(new_id))
	  dest.removeAttr("id");
	else
	  dest.attr("id", new_id);
	dest.hide();
	
	//console.log(url);
	
	dest.load(url, function(){
		$("#" + elem).parent().append(dest);
		$("#" + elem).fadeOut("fast", function(){
			dest.fadeIn("fast", function(){
				$(window).resize();
				$("#" + elem).remove();
				if(!isEmpty(post_function))
				{
					if(post_function.indexOf("(")==-1)
					  post_function+="();";
					try{ eval(post_function); } catch(e) { try{console.log(e);}catch(ee){} }
				}
			});
		});
	});
}

function loadTimelapse()
{
  var swf = abs_url + "graph/swf/timelap.swf";
  $("body").prepend('<div class="timelapse_container"><div class="timelapse">'
+'<object width="1920" height="640" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"> '
+' <param value="'+swf+'" name="movie"> '
+' <param value="high" name="quality"> '
+' <param name="wmode" value="transparent" />'
+' <embed width="1920" wmode="transparent" height="640" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" quality="high" src="'+swf+'" /> '
+'</object></div></div>');
  
}

function zoomIn(){
		var currentFontSize = $("div.contenuto").css('font-size');
    var currentFontSizeNum = parseFloat(currentFontSize, 10);
    var newFontSize = currentFontSizeNum*1.2;
    $("div.contenuto").css('font-size', newFontSize);
	
	/*$("div.content_center").children().each(function(){
	  if($(this).hasClass("pager"))
	    return;
		var currentFontSize = $(this).css('font-size');
	    var currentFontSizeNum = parseFloat(currentFontSize, 10);
	    var newFontSize = currentFontSizeNum*1.2;
	    $(this).css('font-size', newFontSize);
	});
	$('div.dialog').dialog('option', 'position', [((full_width -copertura_w) / 2  - dialog_w / 2), full_height/2 - 200]);*/
}
function zoomOut(){
		var currentFontSize = $("div.contenuto").css('font-size');
    var currentFontSizeNum = parseFloat(currentFontSize, 10);
    var newFontSize = currentFontSizeNum/1.2;
    $("div.contenuto").css('font-size', newFontSize);

	/*$("div.content_center").children().each(function(){
	  if($(this).hasClass("pager"))
	    return;
		var currentFontSize = $(this).css('font-size');
	    var currentFontSizeNum = parseFloat(currentFontSize, 10);
	    var newFontSize = currentFontSizeNum/1.2;
	    $(this).css('font-size', newFontSize);
	});*/
}

/*
function checkSubmit(form)
{
  var f = $(form);
  var rv = true;
      
//  if(f.attr("checkFunction") != "")
//    rv = eval(f.attr("checkFunction") + "(form)");
  if(rv)
  {
    //Controllo se tante le volte devo aprire l'iframe con il colorbox
    if(f.attr("target") == "__colorbox")
    {
      $.post(abs_url + "do_post.php",        // PERFORM AJAX POST
        f.serialize() + "&action=" + f.attr("action"),      // WITH SERIALIZED DATA OF MYFORM
        function(data){                // DATA NEXT SENT TO COLORBOX
          $.fn.colorbox({
            html:   data,
            open:   true,
            iframe: false,            // NO FRAME, JUST DIV CONTAINER?
            width:  "320px",
            height: "320px"
          });
        },
        "html");
        
      
      return false;
    }
  }
  
  return rv;
}
*/
function checkForm(form)
{
  if(!check_captcha())
    return myAlert("Controllo antispam non valido!", false);
    
  
  if($("#privacy").length > 0 && $("#privacy").attr("checked") != "checked")
    return myAlert("Accettare la privacy per continuare.", false);
    
  for(var f=0; f<form.length; f++)
  {
    if(form[f].hasAttribute("obbl") && $(form[f]).attr("obbl") == "y" && $(form[f]).val() == "")
      return myAlert("Campi obbligatori non compilati.", false);
  }

  return true;
}

function showHideLandings()
{
  $("#keyboxtext").toggle();
}
