// JavaScript Document
var backoffice;
var referenceOffset;

var headerSlider;
var slideLength;
var slideTimeout;
var headerIndex;

var siteWidth;

$(document).ready(function()
{
	siteWidth = $('div#Header div.leftColumn').outerWidth() + $('div#HeaderSlider').outerWidth();
	
	// LanguageSelector
	$('div#SubLinks li.language').mouseenter(function()
	{
		$(this).parent().addClass('hover');
	});
	$('div#SubLinks li.language').mouseleave(function()
	{
		$(this).parent().removeClass('hover');
	});
	
	//Add flag
	var flag = $('div#SubLinks li.language ul span').parent(); // gets li for span element
	$('div#SubLinks li.language > a').after('<span class="flag ' + flag.attr('class') + '">&nbsp;</span>');
	
	// Header Slider --------------------------------------------------------------------------
	if ($('div#HeaderImage img:not(div#HeaderImage div.editbutton img)').length > 0)
	{
		slideLength = $('div#HeaderImage img:not(div#HeaderImage div.editbutton img)').length;
		headerSlider = $('div#HeaderSlider');
		
		for (i = 0; i < slideLength; i++)
		{
			headerSlider.find('div#HeaderNav').append('<div class="nav">' + 0 + (i + 1) + '</div>');
		}
		
		headerSlider.find('img:first').addClass('activeImage').show();
		
		//Navigation
		headerSlider.find('div.nav').each(function()
		{
			$(this).click(function()
			{
				clearTimeout(slideTimeout);
				headerSlide($(this).index() - 1)
			});
		});
		
		headerSlider.find('div.nav:first').addClass('activeNav');
		
		if (backoffice != true && slideLength > 1)
		{
			slideTimeout = setTimeout(function(){ headerSlide(1); }, 5000);
		}
	}
	
	function headerSlide(index)
	{
		headerSlider.find('img.activeImage').fadeOut(500, function(){ $(this).removeClass('activeImage'); });
		headerSlider.find('img:eq(' + index + ')').fadeIn(500, function(){ $(this).addClass('activeImage'); });
		
		headerSlider.find('div.activeNav').removeClass('activeNav');
		headerSlider.find('div.nav:eq(' + index + ')').addClass('activeNav');
		
		index += 1;
		
		if (index == slideLength)
		{
			index = 0;
		}
		
		slideTimeout = setTimeout(function(){ headerSlide(index); }, 5000);
	}
	
	
	// Menu --------------------------------------------------------------------------
	$('div#Menu a').each(function(e)
	{
		var text = $(this).text();
		$(this).text($.trim(text));
	});
	
	$('div#Menu li').each(function()
	{
		$(this).mouseenter(function()
		{
			$(this).addClass('expand');
		});
		$(this).mouseleave(function()
		{
			$(this).removeClass('expand');
		});
	});
	
	// Cufon --------------------------------------------------------------------------------------
	Cufon.now();
	
	Cufon.set('fontFamily', 'Flama Light');
	Cufon.replace('.customFont.light');
	Cufon.replace('div#HeaderTitle');
	Cufon.replace('div#HeaderNav div.nav');
	Cufon.replace('div#ContentTitle h1');
	
	Cufon.set('fontFamily', 'Flama Medium');
	Cufon.replace('.customFont.medium');
	Cufon.replace('div#HeaderTitle strong');
	
	Cufon.set('fontFamily', 'Flama Book');
	Cufon.replace('.customFont.book');
	Cufon.replace('h1:not(div#ContentTitle h1)')('h2')('h3');
	Cufon.replace('div#Menu > div > ul > li a', {hover: {'color': '#A97026'}});
	Cufon.replace('div.reservation div.tabs div.tab');
	
	Cufon.replace('div#SubLinks li.language > a');
	
	// Selectbox --------------------------------------------------------------------------
	$('div.reservation select').selectbox();
	
	
	// ImageBlock --------------------------------------------------------------------------
	$('div.imageColumns div.column').click(function()
	{
		var href = $(this).find('a:first').attr('href');
		if (backoffice != true)
		{
			window.location = href;
		}
	})	
	
	// Selectbox --------------------------------------------------------------------------
	$('div.reservation div.childrenPerRoom div.activeRooms').css('display','none');
	
	// Language --------------------------------------------------------------------------
	$('div#Language div.activeLanguage').toggle(function()
	{
		var language = $(this).parent();
		language.find('ul').slideDown(300);
	}, function()
	{
		var language = $(this).parent();
		language.find('ul').slideUp(300);
	});
	$('div#Language ul li').hover(function()
	{
		$(this).addClass('hover');
	}, function()
	{
		$(this).removeClass('hover');
	});
	
	
	// Booking engine --------------------------------------------------------------------------
	$('div.reservation').each(function(index)
	{
		var startDate = $(this).find('div.minDate span').text();
		var endDate = $(this).find('div.maxDate span').text();
		var minDays = $(this).find('div.minDays span').text();
		var rateAccessCode = $(this).find('div.accountID span').text();
		var activeID = $(this).find('div.activeID span').text();
		
		var hideDays = $(this).find('div.hideDays span').text().split(',');
		var daysToDisable = new Array();
		
		for (i = 0; i < hideDays.length; i++)
		{
			daysToDisable.push(parseInt(hideDays[i]));
		}
		
		var hotels = $(this).find('div.hotel select option').length;
		if (hotels > 1)
		{
			$(this).addClass('showHotels');
			$(this).find('div.hotel select').selectbox();
		}
		
		if (backoffice == true)
		{
			$(this).addClass('backoffice');
		}
		
		var bookFrom = $(this).find('.bookFrom');
		var bookTo = $(this).find('.bookTo');
		
		if (isNaN(parseInt(minDays)))
		{
			minDays = 1;
		}
		
		if (startDate == "" && endDate == "")
		{
			bookFromDate = "today";
			bookToDate = parseInt(minDays);
		}
		else if (startDate != "" && endDate == "")
		{
			startDate = startDate.split('-');
			bookFromDate = new Date(startDate[2], startDate[1] - 1, startDate[0]);
			
			bookToDate = new Date(startDate[2], startDate[1] - 1, startDate[0]);
			bookToDate.setDate(bookToDate.getDate() + parseInt(minDays));
		}
		else if (startDate == "" && endDate != "")
		{
			bookFromDate = "today";
			
			endDate = endDate.split('-');
			bookToDate = new Date(endDate[2], endDate[1] - 1, endDate[0]);
		}
		else if (startDate != "" && endDate != "")
		{
			startDate = startDate.split('-');
			bookFromDate = new Date(startDate[2], startDate[1] - 1, startDate[0]);
			
			endDate = endDate.split('-');
			bookToDate = new Date(endDate[2], endDate[1] - 1, endDate[0]);
		}
		
		if (activeID == 1 && rateAccessCode == '')
		{
			$(this).find('div.rates').addClass('showRates');
		}
		
		if (rateAccessCode != '')
		{
			$(this).find('input.accessCode').val(rateAccessCode);
		}
		
		var dates = $(this).find( ".bookFrom, .bookTo" ).datepicker({
			showOn: 'both',
			buttonImage: '/content/images/Date_Picker.jpg',
			minDate: 0,
			beforeShowDay: function( selectedDate ) {
				var day = selectedDate.getDay();
				for (i = 0; i < daysToDisable.length; i++) 
				{
					if ($.inArray(day, daysToDisable) != -1) 
					{
						return [false];
					}
				}
				return [true];
			},
			onSelect: function( selectedDate ) {
				var option = $(this).attr('class').replace(/\ hasDatepicker/gi, ''),
					instance = $( this ).data( "datepicker" );
					date = $.datepicker.parseDate(
						instance.settings.dateFormat ||
						$.datepicker._defaults.dateFormat,
						selectedDate, instance.settings );
				dates.not( this ).datepicker( "option", option, date);
			},
			onClose: function( selectedDate ) {
				if ($(this).hasClass('bookFrom') == true)
				{
					var newDate = new Date();
					newDate = bookFrom.datepicker("getDate");
					newDate.setDate(newDate.getDate() + parseInt(minDays));
					bookTo.datepicker("option", "minDate", newDate);
					bookTo.datepicker("show");
				}
			}
		});
		
		// Set dates
		bookFrom.datepicker("setDate", bookFromDate);
		bookTo.datepicker("setDate", bookToDate);
		
		// Align the selectboxes vertically to top or bottom, depending on available space
		if ($(this).parents('div#Content').length > 0)
		{
			var topPos = $(this).parent().position().top;
			var containerHeight = $('div#Content').height();
			var resHeight = $(this).outerHeight();
			
			$(this).find('div.jquery-selectbox-list').each(function()
			{
				$(this).parents('div.childrenPerRoom').addClass('selectActive');
				var listHeight = $(this).height();
				$(this).parents('div.childrenPerRoom').removeClass('selectActive');
				
				if ((resHeight + listHeight + topPos) > containerHeight)
				{
					$(this).addClass('topAlign');
				}
			});
		}
		
		// Align the selectboxes vertically to top or bottom, depending on available space
		if ($(this).parents('div.rightColumn').length > 0)
		{
			var topPos = $(this).parent().position().top;
			var containerHeight = $('div.rightColumn').height();
			var resHeight = $(this).outerHeight();
			
			$(this).find('div.jquery-selectbox-list').each(function()
			{
				$(this).parents('div.childrenPerRoom').addClass('selectActive');
				var listHeight = $(this).height();
				$(this).parents('div.childrenPerRoom').removeClass('selectActive');
				
				if ((resHeight + listHeight + topPos) > containerHeight)
				{
					$(this).addClass('topAlign');
				}
			});
		}		
	});
	
	$('div.reservation').mouseenter(function()
	{
		$(this).parents('div.innerContent').addClass('topIndex');
	});
	$('div.reservation').mouseleave(function()
	{
		$(this).parents('div.innerContent').removeClass('topIndex');
	});
	
	$('div.reservation div.tab').click(function()
	{
		$('div.reservation div.active').removeClass('active');
		$(this).addClass('active');
		
		var tabClass = $(this).attr('id');
		$('div.reservation div.' + tabClass + '').addClass('active');
		
		Cufon.refresh('div.reservation div.tabs div.tab');
	});
	
	$('div.reservation div.childrenPerRoom a').click(function()
	{
		var childrenPerRoom = $(this).parents('div.childrenPerRoom');
		childrenPerRoom.addClass('selectActive');
		
		var selectedRooms = $(this).parents('div.reservation').find('select.rooms');
		roomsChanges(selectedRooms);
		
		return false;
	});
	
	$('div.reservation div.rates a').click(function()
	{
		var rates = $(this).parents('div.rates');
		rates.addClass('selectActive');
		
		return false;
	});
	
	$('div.reservation select.rooms').change(function()
	{
		var selectedRooms = $(this);
		roomsChanges(selectedRooms);
	});
	
	function roomsChanges(elem)
	{
        if (elem && elem.val()) {
            var count = elem.val();
            if (count >= 1)
                $('div.childrenPerRoom div.room1').show();
            else
                $('div.childrenPerRoom div.room1').hide();
            if (count >= 2)
                $('div.childrenPerRoom div.room2').show();
            else
                $('div.childrenPerRoom div.room2').hide();
            if (count >= 3)
                $('div.childrenPerRoom div.room3').show();
            else
                $('div.childrenPerRoom div.room3').hide();
        }
        else {
            $('div.childrenPerRoom div.room1').hide();
            $('div.childrenPerRoom div.room2').hide();
            $('div.childrenPerRoom div.room3').hide();
        }
    }
	
	$('div.reservation div.button').click(function()
	{
		if ($(this).parent().hasClass('myResContent'))
		{
			return;
		}
		
		var currentPage = location.pathname;
		//pageTracker._trackPageview(currentPage + '/reservation-click/search');
		//_gaq.push(['_trackPageview', currentPage + '/reservation-click/search']);
		
		build_url( $(this).parents('div.reservation') );
		
		return false;
	});
	
	
	// Watermarks --------------------------------------------------------------------------
	$('div.reservation div.rates input.accountID').watermark('Promo rate');
	

	// Newsletter --------------------------------------------------------------------------
	$('div#Newsletter a#Send').click(function()
	{
		var newsletter = $(this).parent('div#Newsletter');
		
		var params = {
			email: newsletter.find('input#Email').val(),
			IDstato: newsletter.find('select#Country').val(),
			IDcliente: 102,
			IDcategoria: 1691
		};
		
		post_to_url('http://www.newsletterplus.it/contatti/codice/iscrizione.asp', params);
		
		return false;
	});

	resizeWindow();
	$(window).resize(function(){ resizeWindow(); });
	
	// Forms -------------------------------------------------------------------------------
	/*if ($('div.datequestion').length > 0)
	{		
		$('div.datequestion input:first').addClass('text');
	}	*/
	
	$('div.datequestion').each(function()
	{
		$(this).find('input:first').addClass('text');
		$(this).find('input:eq(1)').addClass('image');
		
		$(this).parent().css('z-index','999');					
	});
	
	$('div.datequestion input.image').click(function()
	{
		$(this).parent().parent().css('z-index', '1000');	
	})
});


// Booking engine script -----------------------------------------------------------------------------------------
function build_url( reservation ) {
	var selectedHotel = reservation.find('select[name=hotel]').val();
	selectedHotel = selectedHotel.split('|');
	
	var checkindate = reservation.find('input[name=checkindate]').val();
	var checkoutdate = reservation.find('input[name=checkoutdate]').val();
	var ccpSelectCity = selectedHotel[1];
	var ccpSelectHotel = selectedHotel[2];
	var ccpSelectCountry = selectedHotel[3];
	var language = selectedHotel[4];
	var rateAccessCode = reservation.find('input[name=rateAccessCode]').val();
	var accountID = reservation.find('input[name=accountID]').val();
	var adults = reservation.find('select[name=adults]').val();
	var rooms = reservation.find('select[name=rooms]').val();
	
	//Children
	var child1 = reservation.find('select[name=child1]').val();
	var child2 = reservation.find('select[name=child2]').val();
	var child3 = reservation.find('select[name=child3]').val();
	var child4 = reservation.find('select[name=child4]').val();
	var child5 = reservation.find('select[name=child5]').val();
	var child6 = reservation.find('select[name=child6]').val();
	var children = reservation.find('select[name=children]').val();
	
	var IBFname = selectedHotel[0];
	
	var parts = checkindate.split('/');
	var calArrivalDateField = parts[2] + '-' + parts[0] + '-' + parts[1];
	parts = checkoutdate.split('/');
	var calDepartureDateField = parts[2] + '-' + parts[0] + '-' + parts[1];

	var params = {
		'calArrivalDateField': calArrivalDateField,
		'calDepartureDateField': calDepartureDateField,
		'quick': 'quick',
		'ccpSelectCity': ccpSelectCity,
		'ccpSelectHotel': ccpSelectHotel,
		'ccpSelectCountry': ccpSelectCountry,
		'language': language
	};
	if (rateAccessCode != 'Access code' && rateAccessCode)
		params["rateAccessCode"] = rateAccessCode;
	if (accountID != 'Account ID' && accountID != 'Promo rate')
		params["accountId"] = accountID;
	params["adults1"] = adults;
	if (rooms > 1)
		params["adults2"] = adults;
	if (rooms > 2)
		params["adults3"] = adults;
		
	//Children
	if (child1 != '' && child1)
		params["childrenAges1"] = child1;
	if (child2 != '' && child2)
		params["childrenAges1"] += ',' + child2;
	if (child3 != '' && child3)
		params["childrenAges2"] = child3;
	if (child4 != '' && child4)
		params["childrenAges2"] += ',' + child4;
	if (child5 != '' && child5)
		params["childrenAges3"] = child5;
	if (child6 != '' && child6)
		params["childrenAges3"] += ',' + child6;
		
	if (children > 0)
	{
		var childrenPerRoom = Math.floor(rooms / children);
		
		var many = new Array();
		
		for (var iFill = 0; iFill < children; iFill++)
		{
			var fillRoom = childrenPerRoom;
			
			many.push(1);
		}

		for (var iFill = 0; iFill < rooms; iFill++)
		{
			eval('params["childrenAges' + (iFill + 1) + '"] = "' + many.join(',') + '"');
		}

	}

	post_to_url('https://www.yourreservation.net/ibe/' + IBFname + '/main.html', params, 'get');
	//post_to_url('http://www.yourreservation.net/tb3/index.cfm', params, 'get');
	
	return false;
}
function post_to_url(path, params, method) {
	method = method || "post"; // Set method to post by default, if not specified.

	// The rest of this code assumes you are not using a library.
	// It can be made less wordy if you use one.
	var form = document.createElement("form");
	form.setAttribute("method", method);
	form.setAttribute("action", path);
	form.setAttribute("target", "_blank");
	form.setAttribute("onsubmit", "_gaq.push(['_linkByPost', this]);");

	var urlParams = '?';

	for (var key in params)
	{
		var hiddenField = document.createElement("input");
		hiddenField.setAttribute("type", "hidden");
		hiddenField.setAttribute("name", key);
		hiddenField.setAttribute("value", params[key]);
		
		urlParams += key + '=' + params[key] + '&';
		
		form.appendChild(hiddenField);
	}
		
	if (_gaq)
	{
		_gaq.push(function()
		{
			var pageTracker = _gat._getTrackerByName();
			window.open(pageTracker._getLinkerUrl(path + urlParams));
		});
	}
	else
	{
		document.body.appendChild(form);
		form.submit();
	}
}

function resizeWindow()
{
	var width = $(window).width();
	
	if (width < 1000)
	{
		$('html').addClass('overflow');
	}
	else
	{
		$('html').attr('class', '');
	}
}

/*function post_to_url(path, params, method) {
	method = method || "post"; // Set method to post by default, if not specified.

	// The rest of this code assumes you are not using a library.
	// It can be made less wordy if you use one.
	var form = document.createElement("form");
	form.setAttribute("method", method);
	form.setAttribute("action", path);
	form.setAttribute("target", "_blank");

	for (var key in params) {
		var hiddenField = document.createElement("input");
		hiddenField.setAttribute("type", "hidden");
		hiddenField.setAttribute("name", key);
		hiddenField.setAttribute("value", params[key]);

		form.appendChild(hiddenField);
	}

	document.body.appendChild(form);    // Not entirely sure if this is necessary
	form.submit();
}*/

