if( !jQuery.browser.mobile )
{
	Cufon.replace('.cufon');
	Cufon.replace('#nav_section', { hover: true });
	Cufon.replace('h1,h2,h5,h6');
}

$(function () {
	$("#booking .panes").tabs();
	$(".aContent p").css('visibility', 'hidden');
});

jQuery(document).ready(function () {
	$(document).pngFix();
	$('#slideshow').cycle();

	// Pagina offerte, eventi
	$('#lista_foto_offerta, #lista_foto_evento, #lista_foto_articolo').cycle();
	$("#lista_foto_offerta a, #lista_foto_evento a, #lista_foto_articolo a").fancybox();

	$(".accordion").accordion({ header: "h4", autoHeight:false , active: 0 });
	$('#olListaOfferteGruppo li a').css('opacity', '0');
	// end

	$('#olListaOfferteGruppoHP li a').css('opacity', '0');
	if ($('#list_offerte_HP ol li ').length <= 1) {
		$('#list_offerte_HP .prev, #list_offerte_HP .next').hide();
	}

	$('.olListaOfferteGruppoHP').cycle({
		fx: 'scrollHorz',
		prev: '.prev',
		next: '.next',
		timeout: 0
	});

	/*
	$('.btnNwslIscriviti').fancybox({
		'hideOnContentClick': false,
		'zoomSpeedIn': 0,
		'zoomSpeedOut': 0,
		'frameWidth': 263,
		'frameHeight': 319,
		'callbackOnStart': function () {
		if (document.createStyleSheet)
		document.createStyleSheet("/_js/jQuery/plugin/fancybox/css/fancy-nwsl.css");
		else
		$("head").append('<link type="text/css" rel="stylesheet" href="_js/jQuery/plugin/fancybox/css/fancy-nwsl.css" />');
		},
		'callbackOnClose': function () {
		$("head link:last").remove();
		if ($('#success').val() == 'True')
		document.location = "/ita/newsletter/OK/"
		}
	});*/

	$('.bckgTd:first').width(16);
	var titleContent = ($('.tdTitleContent span').width() + 14);
	$('.tdTitleContent').width(titleContent);
	$('.bckgTd:last').width(482 - titleContent);


	// start_Footer Tips
	$('#tips ul li').each(function () {

		var time = 500;
		var hideDelay = 250;

		var hideDelayTimer = null;
		var beingShown = false;
		var shown = false;
		var nera = $('.bandaNera', this)
		var p = $('.bandaNera p', this)

		$(this)
		.mouseover(function () {

		if (hideDelayTimer) clearTimeout(hideDelayTimer);
		if (beingShown || shown)
		// don't trigger the animation again
		return;
		else {
			beingShown = true;
			p.show();

			nera.animate({ paddingTop: '13px', height: '24px'}, 400, function() {
				// Animation complete.
				beingShown = false;
				shown = true;
			});

			/*
			nera.animate({ height: '24px', paddingTop: '13px' }, { duration: 400, queue: 'false', complete: function () {
				beingShown = false; shown = true;
				}
			});*/
		}

		return false;
		})
		.mouseout(function () {

			if (hideDelayTimer) clearTimeout(hideDelayTimer);
			hideDelayTimer = setTimeout(function () {
				hideDelayTimer = null;
				p.hide();

				nera.animate({ paddingTop: '15px', height: '0px'}, 250, function() {
					// Animation complete.
					shown = false;
				});
				/*
				nera.animate({ height: '0px', paddingTop: '15px' }, { duration: 250, queue: 'false', complete: function () {
						shown = false;
					}
				});*/
			}, hideDelay);

			return false;
		});
	});
	// end_Footer Tips

	// start_Fancybox
	$('.fancy_bg,#fancy_close').each(function () {
		var filter = $(this).css('filter');
		$(this).css('filter', filter.replace('images', 'images-nwsl'));
	});

	if ('False' == 'True') {
		parent.top.$('#fancy_close').trigger('click');
		parent.top.$('#success').val('False');
	}
	// end_Fancybox

	$('.btnBooking').click(function () {
		var Error = true;

		//CalcolaPreventivi.cfm?IdHotel=7
		$('#myform').attr('action', 'http://www.iperbooking.net/CalcolaPreventivi.cfm?IdHotel=7&Lingua=it');

		if (($("#preventivo .arrivo").hasClass('error')) || ($("#preventivo .partenza").hasClass('error')))
			Error = false;

		// SE NON SETTATA LA DATA DAL NON FA NIENTE
		if (($("#preventivo .arrivo").val() == '') || ($("#preventivo .partenza").val() == ''))
			Error = false;

		// SE LA LINGUA E' INGLESE
		if ('ita' == 'ing') {
			$("#myform #Arrivo").val($("#preventivo .arrivo").val().substring(3, 6) + $("#preventivo .arrivo").val().substring(0, 3) + $("#preventivo .arrivo").val().substring(6, 10));
			$("#myform #Partenza").val($("#preventivo .partenza").val().substring(3, 6) + $("#preventivo .partenza").val().substring(0, 3) + $("#preventivo .partenza").val().substring(6, 10));
		}
		else {
			$("#myform #Arrivo").val($("#preventivo .arrivo").val());
			$("#myform #Partenza").val($("#preventivo .partenza").val());
		}

		// CLICK DEL SUBMIT
		if (Error)
			$("#myform").submit();

		return false;
	});

	// Menu/Sottomenu
	menuInit();

	// Booking ABS
	absInit();

	// Prenotazioni
	prenotaInit();

	// Contatti
	contattiInit();

	// Gallery
	GalleryInit();

	jQueryValidateAddons();

	// Controllo dati obbligatori nei form
	formCheckInit();
});

function absInit(){

	// start_Datepicker
	var openDate = new Date( 2012, 0, 1, 0, 0, 0 );
	var closeDate = new Date( 2012, 10, 2, 0, 0, 0 );

	jQuery("#abs_form #checkin, #abs_form #checkout").datepicker('option',jQuery.datepicker.regional['it']);
	jQuery("#abs_form #checkin, #abs_form #checkout").datepicker({option:"it", dateFormat: "dd-mm-yy", numberOfMonths: 3});

	jQuery( "#abs_form #checkin, #abs_form #checkout" ).datepicker( "option", "minDate", new Date(openDate.getFullYear(), openDate.getMonth(), openDate.getDate()) );
	jQuery( "#abs_form #checkin, #abs_form #checkout" ).datepicker( "option", "maxDate", new Date(closeDate.getFullYear(), closeDate.getMonth(), closeDate.getDate()) );

	// controllo su data di arrivo e di partenza
   	date1 = jQuery("#abs_form #checkin").datepicker( 'getDate' );
   	date1 = new Date(date1);
	date1.setDate(date1.getDate() + 1);

	jQuery("#abs_form #checkout").datepicker('option', 'minDate',date1);

	jQuery("#abs_form #checkin").change(
		function(){
			date1 = jQuery("#abs_form #checkin").datepicker( 'getDate' );
			date2 = new Date(date1);
			date2.setDate(date1.getDate() + 1);
			jQuery("#abs_form #checkout").datepicker('option', 'minDate',date2);
		}
	);
	// end_Datepicker

	// start_Booking
	var maxAdults = 7;
	var maxChild = 4;
	var maxChildAge = 17;
	var labelRoom = "Camera";
	var labelAdults = "Adulti";
	var labelChildren = "Bambini";
	var labelChildAge = "Eta' Bambini";

	jQuery("#abs_form #numRooms").change( function(){
		var nRooms = jQuery(this).val();
		var roomsOptions = jQuery("#contOption table:first");
		var roomRow = "";

		roomsOptions.find("tr:gt(0)").remove();

		for( var i=1; i<=nRooms; i++ )
		{
			// Per la 1a camera non stampo l'etichetta "Camera 1"
			if( i > 1 ) roomRow = roomRow + "<tr><td><strong>" + labelRoom+" "+i+"</strong></td></tr>";

			// Adulti
			roomRow = roomRow + "<tr><td><select name='bform[reqRooms]["+i+"][adults]'>";

			for( var x=1; x<=maxAdults; x++ )
			{
				roomRow = roomRow + "<option value='"+x+"'>"+x+"</option>";
			}

			// Bambini
			roomRow = roomRow + "</select>";
			if( i > 1 ) roomRow = roomRow +labelAdults;
			roomRow = roomRow + "</td><td><select name='bform[reqRooms]["+i+"][child]' class='absChildren' data-roomnumber='"+i+"'>";

			for( var x=0; x<=maxChild; x++ )
			{
				roomRow = roomRow + "<option value='"+x+"'>"+x+"</option>";
			}

			// Etā Bambini (creo la colonna)
			roomRow = roomRow + "</select> ";
			if( i > 1 ) roomRow = roomRow +labelChildren;
			roomRow = roomRow + "</td><td></td></tr>";
		}

		roomsOptions.append( roomRow );
	});

	// Cambio numero bambini
	jQuery("#abs_form .absChildren").live( "change", function(){
		var tdAgeChildren = jQuery(this).parent().next("td");
		var roomNumber = jQuery(this).data("roomnumber");
		var nChildren = jQuery(this).val();
		var childAgeRow = "";

		if( nChildren > 0 ){
			//jQuery("#contOption table:first tr:first td:last").html("Eta bambini");
		}
		else{
			jQuery("#abs_form #contOption table:first tr:first td:last").html("");
		}

		tdAgeChildren.html("");

		for( var x=1; x<=nChildren; x++ )
		{
			childAgeRow = childAgeRow + '<select name="bform[reqRooms]['+roomNumber+'][childAge]['+x+']">';
			for( var y=0; y<=maxChildAge; y++ )
			{
				if( y === 0 ){
					childAgeRow = childAgeRow + '<option value="'+y+'">&lsaquo; 1</option>';
				}
				else{
					childAgeRow = childAgeRow + '<option value="'+y+'">'+y+'</option>';
				}
			}

			childAgeRow = childAgeRow + "</select>";
		}

		childAgeRow = childAgeRow + " " + labelChildAge;

		tdAgeChildren.append( childAgeRow );
	});

	// ABS Submit
	jQuery("#abs_form #abs_form_invia").click( function(){

		if( jQuery("#abs_form #checkin").val() != "" && jQuery("#abs_form #checkout").val() != "" ){
			console.log( "invio form" );
			jQuery("#abs_form").submit();
		}
	});
	// end_Booking
}

function prenotaInit(){

	// start_Datepicker
	var openDate = new Date( 2012, 3, 5, 0, 0, 0 );
	var closeDate = new Date( 2012, 10, 2, 0, 0, 0 );

	jQuery("#form_prenota #form_prenota_dal, #form_prenota #form_prenota_al").datepicker('option',jQuery.datepicker.regional['it']);
	jQuery("#form_prenota #form_prenota_dal, #form_prenota #form_prenota_al").datepicker({option:"it", dateFormat: "dd-mm-yy", numberOfMonths: 3});

	jQuery( "#form_prenota #form_prenota_dal, #form_prenota #form_prenota_al" ).datepicker( "option", "minDate", new Date(openDate.getFullYear(), openDate.getMonth(), openDate.getDate()) );
	jQuery( "#form_prenota #form_prenota_dal, #form_prenota #form_prenota_al" ).datepicker( "option", "maxDate", new Date(closeDate.getFullYear(), closeDate.getMonth(), closeDate.getDate()) );

	// controllo su data di arrivo e di partenza
   	date1 = jQuery("#form_prenota #form_prenota_dal").datepicker( 'getDate' );
   	date1 = new Date(date1);
	date1.setDate(date1.getDate() + 1);

	jQuery("#form_prenota #form_prenota_al").datepicker('option', 'minDate',date1);

	jQuery("#form_prenota #form_prenota_dal").change(
		function(){
			date1 = jQuery("#form_prenota #form_prenota_dal").datepicker( 'getDate' );
			date2 = new Date(date1);
			date2.setDate(date1.getDate() + 1);
			jQuery("#form_prenota #form_prenota_al").datepicker('option', 'minDate',date2);
		}
	);
	// end_Datepicker

	// start_Booking
	var maxAdults = 7;
	var maxChild = 4;
	var maxChildAge = 12;
	var labelRoom = "Camera";
	var labelAdults = "Adulti";
	var labelChildren = "Bambini";
	var labelChildAge = "Eta' Bambini";

	jQuery("#form_prenota #numRooms").change( function(){
		console.log( "cambiato numero camere" );
		var nRooms = jQuery(this).val();
		var roomsOptions = jQuery("#form_prenota #contOption table:first");
		var roomRow = "";

		roomsOptions.find("tr:gt(0)").remove();

		for( var i=1; i<=nRooms; i++ )
		{
			// Per la 1a camera non stampo l'etichetta "Camera 1 nč i campi (ci sono giā)"
			if( i > 1 )
			{
				roomRow = roomRow + "<tr><td class='sx'>" + labelRoom+" "+i+"</td>";

				// Adulti
				roomRow = roomRow + "<tr><td class='prenota_dx1'>"+labelAdults+"</td><td><select name='bform[reqRooms]["+i+"][adults]' class='ddlGeneral ddlMin'>";

				for( var x=1; x<=maxAdults; x++ )
				{
					roomRow = roomRow + "<option value='"+x+"'>"+x+"</option>";
				}

				// Bambini
				roomRow = roomRow + "</select>";
				roomRow = roomRow + "</td><td class='prenota_dx2'>"+labelChildren+"</td><td><select name='bform[reqRooms]["+i+"][child]' class='absChildren ddlGeneral ddlMin' data-roomnumber='"+i+"'>";

				for( var x=0; x<=maxChild; x++ )
				{
					roomRow = roomRow + "<option value='"+x+"'>"+x+"</option>";
				}

				// Etā Bambini (creo la colonna)
				roomRow = roomRow + "</select> ";
				roomRow = roomRow + "</td><td></td></tr>";
			}
		}

		roomsOptions.append( roomRow );
	});

	// Cambio numero bambini
	jQuery("#form_prenota .absChildren").live( "change", function(){
		var tdAgeChildren = jQuery(this).parent().next("td");
		var roomNumber = jQuery(this).data("roomnumber");
		var nChildren = jQuery(this).val();
		var childAgeRow = "";

		if( nChildren > 0 ){
			//jQuery("#contOption table:first tr:first td:last").html("Eta bambini");
		}
		else{
			jQuery("#form_prenota #contOption table:first tr:first td:last").html("");
		}

		tdAgeChildren.html("");

		childAgeRow = childAgeRow + " " + labelChildAge;

		for( var x=1; x<=nChildren; x++ )
		{
			childAgeRow = childAgeRow + '<select name="bform[reqRooms]['+roomNumber+'][childAge]['+x+']" class="ddlGeneral ddlMin">';
			for( var y=0; y<=maxChildAge; y++ )
			{
				if( y === 0 ){
					childAgeRow = childAgeRow + '<option value="'+y+'">&lsaquo; 1</option>';
				}
				else{
					childAgeRow = childAgeRow + '<option value="'+y+'">'+y+'</option>';
				}
			}

			childAgeRow = childAgeRow + "</select>";
		}

		tdAgeChildren.append( childAgeRow );
	});

	// ABS Submit
	jQuery("#form_prenota .abs_form_invia").click( function(){

		if( jQuery("#form_prenota #form_prenota_dal").val() != "" && jQuery("#form_prenota #form_prenota_al").val() != "" ){
			console.log( "invio form" );
			jQuery("#form_prenota").submit();
		}
	});
	// end_Booking
}

function contattiInit(){

	// start_Datepicker
	var openDate = new Date( 2012, 3, 5, 0, 0, 0 );
	var closeDate = new Date( 2012, 10, 2, 0, 0, 0 );

	jQuery("#f_contatti_checkin, #f_contatti_checkout").datepicker('option',jQuery.datepicker.regional['it']);
	jQuery("#f_contatti_checkin, #f_contatti_checkout").datepicker({option:"it", dateFormat: "dd-mm-yy", numberOfMonths: 3});

	jQuery( "#f_contatti_checkin, #f_contatti_checkout" ).datepicker( "option", "minDate", new Date(openDate.getFullYear(), openDate.getMonth(), openDate.getDate()) );
	jQuery( "#f_contatti_checkin, #f_contatti_checkout" ).datepicker( "option", "maxDate", new Date(closeDate.getFullYear(), closeDate.getMonth(), closeDate.getDate()) );

	// controllo su data di arrivo e di partenza
   	date1 = jQuery("#f_contatti_checkin").datepicker( 'getDate' );
   	date1 = new Date(date1);
	date1.setDate(date1.getDate() + 1);

	jQuery("#f_contatti_checkout").datepicker('option', 'minDate',date1);

	jQuery("#f_contatti_checkin").change(
		function(){
			date1 = jQuery("#f_contatti_checkin").datepicker( 'getDate' );
			date2 = new Date(date1);
			date2.setDate(date1.getDate() + 1);
			jQuery("#f_contatti_checkout").datepicker('option', 'minDate',date2);
		}
	);
	// end_Datepicker
}

//Cufon.now();

function GalleryInit(){
	jQuery("a.group").fancybox({
		'speedIn':		300,
		'speedOut':	300,
		'overlayColor':	'#000',
		'overlayOpacity':	0.7
	});

	// Nella versione mobile l'immagine sarebbe troppo grande per visualizzarla, lasciamo il link normale alla foto
	if( !jQuery.browser.mobile ) jQuery("#divPhotogallery .aFancyBox").fancybox();
}

function formCheckInit()
{
	// Iscrizione Newsletter
	$("#newsletter_signup").validate({
		rules: {
			newsletter_nome: "required",
			newsletter_cognome: "required",
			newsletter_email: {
				required: true,
				email: true
			},
			newsletter_privacy: "required"
		},
		messages: {
			newsletter_nome: "",
			newsletter_cognome: "",
			newsletter_email: "",
			newsletter_privacy: "E' necessario prendere visione delle normative della privacy"
		}
	});

	// Form Contatti
	$("#f_contatti").validate({
		rules: {
			nome: "required",
			cognome: "required",
			email: {
				required: true,
				email: true
			},
			f_contatti_checkin: "dateITA",
			f_contatti_checkout: "dateITA",
			f_contatti_privacy: "required"
		},
		messages: {
			nome: "",
			cognome: "",
			email: "",
			f_contatti_checkin: "",
			f_contatti_checkout: "",
			f_contatti_privacy: "E' necessario prendere visione delle normative della privacy"
		}
	});

	// Form Prenotazioni
	$("#form_prenota").validate({
		rules: {
			form_prenota_nome: "required",
			form_prenota_cognome: "required",
			form_prenota_email: {
				required: true,
				email: true
			},
			form_prenota_dal: "dateITA",
			form_prenota_al: "dateITA",
			form_prenota_privacy: "required"
		},
		messages: {
			form_prenota_nome: "",
			form_prenota_cognome: "",
			form_prenota_email: "",
			form_prenota_dal: "",
			form_prenota_al: "",
			form_prenota_privacy: "La preghiamo di autorizzare l'uso dei suoi dati secondo la legge sulla Privacy.(art. 13 L. 675/03)"
		}
	});

}

// Gestione Menu e sottomenu
function menuInit(){

	$('.liHome a').each(function (){
		var time = 500;
		var hideDelay = 250;

		var hideDelayTimer = null;
		var beingShown = false;
		var shown = false;
		var info = $(this).siblings(".sottomenu-parent");

		$([$(this).get(0), info.get(0)])
			.mouseover(function () {
			  if (hideDelayTimer) clearTimeout(hideDelayTimer);
			  if (beingShown || shown)
			  // don't trigger the animation again
				return;
			  else {
				var thisW = jQuery(this).width();

				jQuery(this).next().next().find(".aContent").css({'width': thisW});

				beingShown = true;
				info.fadeIn(time, function () {
					beingShown = false;
					shown = true;
				});
			  }

			  return false;
			})
			.mouseout(function () {
			  if (hideDelayTimer) clearTimeout(hideDelayTimer);
			  hideDelayTimer = setTimeout(function () {
				hideDelayTimer = null;
				info.fadeOut(time, function () { shown = false; });
			  }, hideDelay);

			  return false;
			});
	});
}


function jQueryValidateAddons(){

	//jQuery Validator - Funzioni addizionali
	jQuery.validator.addMethod(
		"dateITA",
		function(value, element) {
			// put your own logic here, this is just a (crappy) example
			return value.match(/^\d{1,2}-\d{1,2}-\d{4}$/);
		},
		"Please enter a date in the format dd/mm/yyyy"
	);
}

function tabsInit(){


	if( !jQuery.browser.mobile ) Cufon.replace('.cufon');

	jQuery("#list_pagina_foto ol li a").fancybox();
	//$("#list_pagina_foto ol li a:first").css("margin-right", "7px");
	jQuery("#list_pagina_foto ol").cycle();

	/*
	$('.aCamere').each(function () {
		var href = $(this).attr('title');
		$(this).attr('href', href);
		var title = $(this).attr('text');
		$(this).attr('title', title);
	});*/

	var tabSpace = 0;
	$('.tabLink li').each(function (i) {
		if (i > 1) {
			if ($(this).width() > 0) {
				$(this).css('padding', '0 4px')
				tabSpace += $(this).width() + 8;
			}
		}
	});

	var titleContent = ($('.liTitleContent span').width() + 12);
	$('.liTitleContent').width(titleContent);
	$('.bckgTd').width(472 - (tabSpace + titleContent));

	jQuery(".content-tabs").tabs({
		select: function (event, ui) {
			var index = ui.index;
			jQuery('.plhFotoCamere').hide();
			jQuery('.plhFotoCamere:eq(' + index + ')').show();
		},
		show: function (event, ui) {
			var index = ui.index;
			jQuery('.plhFotoCamere').hide();
			jQuery('.plhFotoCamere:eq(' + index + ')').show();
		}
	});
}

