// JavaScript Document
var backoffice = false;
var referenceOffset;

var initTabs = true;
var activeTabbed = false;

var fading;

var imageWidth;

var contentHeight = $('div#Content').height;

var init = true;

var prevIndex;

//WH Gallery item
var xmlGallery;
var whGallerySlide = 98;
var whGalleryOffset = 14;
var whGalleryItems = 4;

var tableCell;

$(document).ready(function()
{
	if ($('div.controlBorder').length > 0)
	{
		backoffice = true;
		$('html').addClass('backoffice');
	}
	if (navigator.userAgent.match(/iPad/i) != null)
	{
		$('html').addClass('iPad');
		$('html').width(1000);
		$('div#TopBar').width(1000);
	}
	
	$(window).resize(function(){ setHeight(); });
	
	
	// Room & Suites Tables --------------------------------------------------------------------------
	if ($('div.roomBlocks div.specialOffer'))
	{
		$('div.smallColumn').find('div.specialOffer:last').addClass('rightOffer');
	}
	
	// Accordeon hover color
	$('div#Accordeon h3').hover(function () {
		$(this).addClass('accHover');
		Cufon.refresh('div#Accordeon h3');
		}, 
	function () {
		$(this).removeClass('accHover');
		Cufon.refresh('div#Accordeon h3');
		}
	);

	
	// Selectbox --------------------------------------------------------------------------
	$('select').selectbox();
	
	// Special Offers --------------------------------------------------------------------------
	$('div.specialOffer').click(function()
	{
		if (backoffice = true)
		{
			return;
		}
		
		var href = $(this).find('a:first').attr('href');
		window.location = href;
		
		return false;
	});
	
	
	// Menu ------------------------------------------------------------------
	var hoverout;
	var activeHover;
	var dropoutWidth;
	var dropoutLeft;
	
	var musicWidth = $('div#Music').outerWidth();
	var fullWidth = $('div#SiteContainer').width();
	
	$('div#Menu > div > ul > li:first').addClass('noBorder');
	
	$('div#Menu > div > ul > li').mouseenter(function()
	{
		dropoutLeft = $(this).position().left;
		dropoutWidth = $(this).find('> ul').outerWidth();
		
		if (hoverout != null)
			clearTimeout(hoverout);
			
		if (activeHover != null)
			closeHover();
			
		if ((dropoutLeft + dropoutWidth) > (fullWidth))
		{
			$(this).find('ul').addClass('alignRight');
		}
		
		$(this).addClass('hover');
		
		activeHover = $(this).find('> ul');
	});
	$('div#Menu > div > ul > li').mouseleave(function()
	{
		hoverout = setTimeout(closeHover, 1000);
	});
	
	function closeHover()
	{
		$('div#Menu ul li.hover').removeClass('hover');
		
		hoverout = null;
		activeHover = null;
	}
	
	$('div#SubLinks li.language').mouseenter(function()
	{
		$(this).parent().addClass('hover');
	});
	$('div#SubLinks li.language').mouseleave(function()
	{
		$(this).parent().removeClass('hover');
	});
	
	
	// Accordeon --------------------------------------------------------------------------
	$('div#Accordeon h3').click(function()
	{
		var row = $(this).parents('div.row');
		
		if (row.hasClass('activeRow'))
		{
			return;
		}
		
		$('div#Accordeon div.activeRow div.accordeonContent').slideUp(300);
		$('div#Accordeon div.row').removeClass('activeRow');
		
		row.find('div.accordeonContent').slideDown(300, function() { setHeight() });
		row.addClass('activeRow');
		Cufon.refresh('div#Accordeon h3');

		setHeight();
	});
	
	$('div#Accordeon div.accordeonContent').each(function(index)
	{
		if ($(this).find('div.SurveyContainer').text().indexOf('Thank you for your subscription') >= 0)
		{
			$('div#Accordeon h3').eq(index).click();
		}
		
	});
	
	
	// Tabs --------------------------------------------------------------------------
	$('div#Background p img:first').addClass('activeImage');
	$('div#HomeBlocks div.block:first').addClass('activeBlock');
	
	$('div#Tabs ul li:odd').addClass('odd');
	
	//$('div#Tabs ul li a').click(function()
	$('div#Tabs ul li a').not('div#Tabs ul li div.editbutton a').click(function()
	{
		if (initTabs == false && $('body').hasClass('home') == false)
		{
			return true;
		}
		
		initTabs = false;
		
		if ($(this).parent().hasClass('activeTab') || fading == true)
		{
			return false;
		}
		
		fading = true;
		
		var index = $(this).parent().index();
		
		$('div#Tabs ul li').removeClass('activeTab');
		
		if (activeTabbed == true || $('body').hasClass('home') == true) {
			$(this).parent().addClass('activeTab');
		}

		if (activeTabbed == true && $('body').hasClass('home') == false) {
			index = 0;
		}
		
		if (backoffice != true)
		{
			changeBackground(index);
		}
		
		if ($('body').hasClass('home'))
		{
			//Change content
			changeHomeblock(index);
			//console.log('changeHomeblock');
		}

		//Change Phrase
		animatePhrase(index)

		var tabs = $('div#Tabs a').not('div#Tabs div.popupMenu a');
		Cufon.refresh(tabs);

		return false;
	});
	
	/*
	if ($('body').hasClass('home'))
	{
		$('div#Tabs ul li a:first').click();
	}
	*/
		//Works for Frontend, not backend
		if (backoffice == true)
		{
			changeHomeblock(0);
		}
		else
		{
			var activeTab = $('div#Tabs ul li a[href=' + window.location.pathname + ']');
			if (activeTab.length == 0)
			{
				$('div#Tabs ul li a:first').click();
			}
			else if (window.location.pathname.length >= 1) 
			{
				activeTabbed = true;
				activeTab.click();
			}
		}
	
	
	function changeBackground(tabIndex)
	{
		var largeImages = $('div#BackgroundSystem div#BackgroundImages');
		var backgroundLeft = $('div#BackgroundSystem div#BackgroundLeft');
		var backgroundRight = $('div#BackgroundSystem div#BackgroundRight');
		
		if (init == true)
		{
			$('div#BackgroundContent img').each(function(index)
			{
				$(this).attr('id', 'Tab' + index)
				
				var bgcolor1 = $(this).parents('table').find('tr:eq(1) td:eq(0)').attr('bgcolor');
				var bgcolor2 = $(this).parents('table').find('tr:eq(1) td:eq(1)').attr('bgcolor');
				
				if (!bgcolor1)
				{
					bgcolor1 = $(this).parents('table').find('tr:eq(1) td:eq(0)').css('background-color');
				}
				if (!bgcolor2)
				{
					bgcolor2 = $(this).parents('table').find('tr:eq(1) td:eq(1)').css('background-color');
				}

				$(this).attr('bgleft', bgcolor1);
				$(this).attr('bgright', bgcolor2);
				
				$(this).hide();
				largeImages.append($(this));
			});
			
			$('div#BackgroundContent').remove();
			init = false
		}
		
		var oldImage = largeImages.find('img.activeImage');
		var newImage = largeImages.find('img').eq(tabIndex);

		oldImage.fadeTo(1500, 0);
		oldImage.removeClass('activeImage');
		newImage.addClass('activeImage');
		newImage.fadeTo(1500, 1, function() { fading = false });
		
		//backgroundLeft.animate({ backgroundColor: newImage.attr('bgleft') }, 1750);
		//backgroundRight.animate({ backgroundColor: newImage.attr('bgright') }, 1750);
	}
	
	function changeHomeblock(index)
	{
		var homeBlocks = $('div#HomeBlocks');
		var activeBlock = $('div#HomeBlocks div.activeBlock');
		var newBlock = homeBlocks.find('div.block:eq(' + index + ')');
		
		activeBlock.animate({top: '-155px'}, 1500);
		newBlock.css('top', '155px');
		newBlock.animate({top: 0}, 1500, function(){ fading = false; });
		
		activeBlock.removeClass('activeBlock');
		newBlock.addClass('activeBlock').show();
	}
	
	
	// Image Slider --------------------------------------------------------------------------
	/*
	if ($('div#ImageSlider').length > 0 && backoffice == false)
	{
		var slider = $('div#ImageSlider');
		var sliderWidth = 0;
		
		slider.find('img').each(function()
		{
			sliderWidth += $(this).outerWidth();
		});
		
		slider.find('div.images').width(sliderWidth);
		imageWidth = sliderWidth / slider.find('img').length;
	}
	
	$('div#ImageSlider div.slideButton').mouseenter(function()
	{
		if ($(this).hasClass('slideLeft'))
		{
			imageSlide(1);
		}
		else if ($(this).hasClass('slideRight'))
		{
			imageSlide(-1);
		}
	});
	$('div#ImageSlider div.slideButton').mouseleave(function()
	{
		$('div#ImageSlider div.images').stop();
	});
	
	function imageSlide(direction)
	{
		$('div#ImageSlider div.images').animate({left: '+=' + (10 * direction) + 'px'}, 100, 'linear', function(){ imageSlide(direction); });
		
		var offset = $('div#ImageSlider div.images').position().left;
		offset = offset * -1;
		
		if (offset >= imageWidth)
		{
			var index = Math.floor(offset / imageWidth);
		}
	}
	*/
	
	//WH JS gallery
	var gallery = $('div.whGallery');
	
	if (gallery.length > 0)
	{
		$.get('/Controls/Plugins/WorldHotels/GalleryImages.ashx?hotel=Parkhotel', function(data)
		{
			//Parser
			if (window.DOMParser)
			{
				parser = new DOMParser();
				xmlGallery = parser.parseFromString(data, "text/xml");
			}
			else // Internet Explorer
			{
				xmlGallery = new ActiveXObject("Microsoft.XMLDOM");
				xmlGallery.async = "false";
				xmlGallery.loadXML(data);
			}
			
			loadGalleries();
		});
	}
	
	function loadGalleries()
	{
		var human = Array('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fiveteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen', 'twenty');
		
		//Iterate galleries
		gallery.each(function(index)
		{
			var myGallery = $(this);
			var galleryContent = myGallery.find('div.imageArea');
			var selectCategory = $.trim(myGallery.find('div.sliderConfig').text());
			
			var categories = Array();
			
			//Clear contents
			galleryContent.html('');

			//Categories
			$(xmlGallery).find('categories category').each(function()
			{
				
				//Current category from XML
				var categoryName = $(this).attr('name');
				categoryName = categoryName.split(' ').join('_');
				
				if (selectCategory && selectCategory != categoryName)
				{
					myGallery.find('div.categories').hide();
					return true;
				}
				
				categories.push(categoryName);
				//Add category div
				galleryContent.append('<div class="category" id="' + categoryName + '" />');
				//Select category
				thisCategory = galleryContent.find('div#' + categoryName);
				//Add to category selector
				myGallery.find('div.categories').append('<a href="#" class="mittelschrift">' + $(this).attr('name') + '</a> ');
				//Add images
				$(this).find('image').each(function()
				{
					//Get SRC's
					var url = '/' + $(this).text().toLowerCase();
					
					//var largeUrl = url.substr(0, url.lastIndexOf('.jpg')) + '_Large.jpg';
					//var largeUrl = url.split('.jpg').join('_Large.jpg');
					var largeUrl = url.split('.').join('_Large.');
					
					//Add to gallery
					var galleryName = categoryName + '_' + human[index];
					//Add slide
					thisCategory.append('<div class="slide"><a href="' + largeUrl + '" rel="'+ galleryName + '"><img src="' + url + '" /></a></div>');
				});

				thisCategory.find('div.slide').each(function()
				{
					$(this).mouseenter(function()
					{
						var img = $(this).find('img')
						img.stop();
						img.animate({opacity: 0.65}, 150);
					});
					$(this).mouseleave(function()
					{
						var img = $(this).find('img')
						img.stop();
						img.animate({opacity: 1}, 150);
					});
				});
				//Calculate width
				thisCategory.width($(this).find('image').length * whGallerySlide);
				
				thisCategory.append('<div class="clear">&nbsp;</div>');
			});

			changeGallery(0, myGallery);
			
			//Shadowbox.init();
			if (index == gallery.length - 1)
			{
				$('div.slide a').colorbox({ opacity: 0.65 });
			}
		});
		
		gallery.find('div.categories a').click(function()
		{				
			var thisGallery = $(this).parents('div.whGallery');
			
			changeGallery($(this).index(), thisGallery);
			
			return false;
		});
		
		gallery.find('div.leftScroll').click(function()
		{
			var thisGallery = $(this).parents('div.whGallery');
			var galleryContent = thisGallery.find('div.imageArea');
			
			if (galleryContent.attr('posX') >= 0) return;
			
			scrollGallery('left', thisGallery);
			
			return false;
		});
		gallery.find('div.rightScroll').click(function()
		{
			var thisGallery = $(this).parents('div.whGallery');
			var galleryContent = thisGallery.find('div.imageArea');
			
			var activeGallery = thisGallery.attr('active');
			
			var maxi = (galleryContent.find('div.category').eq(activeGallery).find('div.slide').length * -whGallerySlide) + (whGalleryItems * whGallerySlide) + whGalleryOffset;
			//console.log('Max: ' + maxi);
			
			if (galleryContent.attr('posX') <= maxi) return;
			
			scrollGallery('right', thisGallery);
			
			return false;
		});
		
	}

	function scrollGallery(dir, thisGallery)
	{
		var galleryContent = thisGallery.find('div.imageArea');
		
		var x = parseInt(galleryContent.attr('posX'));
		
		if (dir == 'right')
		{
			galleryContent.attr('posX', x - whGallerySlide);
		}
		else
		{
			galleryContent.attr('posX', x + whGallerySlide);
		}

		//console.log('Moving to: ' + galleryContent.attr('posX'));

		galleryContent.stop();
		galleryContent.animate({left: galleryContent.attr('posX') + 'px'}, 250);
	}
	
	function changeGallery(index, thisGallery)
	{
		var galleryContent = thisGallery.find('div.imageArea');
		var activeGallery = thisGallery.attr('active');
		var categories = galleryContent.find('div.category');
		
		categories.eq(activeGallery).hide();
		categories.eq(index).show();
		
		//Reset position
		galleryContent.attr('posX', whGalleryOffset);
		galleryContent.stop();
		galleryContent.animate({left: galleryContent.attr('posX') + 'px'}, 250);

		var names = thisGallery.find('div.categories a');
		names.removeClass('active');
		names.eq(index).addClass('active');

		thisGallery.attr('active', index);
	}
	//End WH JS gallery
	
	// 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',
			dateFormat: 'dd/mm/yy',
			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');
				}
			});
		}
	});
	
	$('div.reservation').mouseenter(function()
	{
		$(this).parents('div.innerContent').addClass('topIndex');
	});
	$('div.reservation').mouseleave(function()
	{
		$(this).parents('div.innerContent').removeClass('topIndex');
	});
	
	$('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;
		}
		
		//pageTracker._trackPageview(currentPage + '/reservation-click/search');
		
		_gaq.push(['_trackPageview', '/booking-search']);
		
		build_url( $(this).parents('div.reservation') );
		
		return false;
	});
	
	
	// Watermarks --------------------------------------------------------------------------
	$('div.reservation div.rates input.accountID').watermark('Account ID');
	$('div.reservation div.rates input.accessCode').watermark('Access code');
	
	// Animated Phrases
	$('div.animatedPhrase').not('div.homePhrases').each(function()
	{
		if ($(this).find('div.phrasePosition').text() != '')
		{
			var pos = $(this).find('div.phrasePosition').text()
			pos = $.trim(pos);
			pos = pos.split(',');
			
			$(this).parents('div#Phrase').css('right', 'auto');
			$(this).parents('div#Phrase').css('left', pos[0] + 'px');
			$(this).parents('div#Phrase').css('top', pos[1] + 'px');
		}

		if (backoffice == true)
		{
			return;
		}

		var phrase1 = $(this).find('div.phrase1');
		var phrase2 = $(this).find('div.phrase2');
		var phrase3 = $(this).find('div.phrase3');
		
		var movement = 175;
		var movementTime = 9000;
		
		$(this).show();
		
		phrase1.css('left', -movement);
		phrase1.animate({ left: 0 }, movementTime, 'easeOutCubic');
		
		phrase2.css('left', movement);
		phrase2.animate({ left: 0 }, movementTime, 'easeOutCubic');
		
		phrase3.css('left', -movement * 0.75);
		phrase3.animate({ left: 0 }, movementTime);
	});

	$('div.homePhrases').each(function()
	{
		$(this).find('div.tabPhrase').each(function(index)
		{
			//Set position
			var pos = $.trim($(this).find('div.phrasePosition').text());
			if (pos == '')
			{
				pos = '0,0';
			}
			
			pos = pos.split(',');
				
			//$(this).attr('init', pos[0] + ',' + pos[1]);
			$(this).css('left', pos[0] + 'px');
			$(this).css('top', pos[1] + 'px');
		});
		
		animatePhrase(0);
	});

	//Music
	$('div#Music div.status').click(function()
	{
		window.open('/music', 'Player', 'location=0,status=0,scrollbars=0,toolbar=0,directories=0,resizable=0,width=250,height=24');
	});

	// Cufon --------------------------------------------------------------------------------------
	Cufon.set('fontFamily', 'Avant Garde Book');
	Cufon.replace('.avantgarde-book');
	Cufon.replace('h2');
	Cufon.replace('div#HomeBlocks div.title');
	Cufon.replace('div.roomTypes a', { hover: { color: '#863ba2' } });


	Cufon.set('fontFamily', 'Avant Garde Demi');
	Cufon.replace('.avantgarde-demi');
	Cufon.replace('div#Menu > div > ul > li > a', { hover: { color: '#b432e4' } })('div#SubLinks a', { hover: { color: '#b432e4' } })('div#SubLinks span', { hover: { color: '#b432e4' } });

	//Cufon.set('fontFamily', 'Avant Garde Medium');
	Cufon.replace('.avantgarde-medium');
	Cufon.replace('div#Accordeon h3', { hover: { color: '#863ba2' } })('h3', { hover: { color: '#863ba2' } });
	Cufon.replace('div#HomeBlocks div.title strong');
	
	//Cufon.replace('h3'); Strange IE error

	Cufon.set('fontFamily', 'Futura Light');
	Cufon.replace('.futura-light p');

	Cufon.set('fontFamily', 'Futura Medium');
	Cufon.replace('.futura-medium p, .futura-medium a');
	
	var tabs = $('div#Tabs a').not('div#Tabs div.popupMenu a');
	//Cufon.replace('div#Tabs a', { hover: { color: '#ffffff' } });
	Cufon.replace(tabs, { hover: { color: '#ffffff' } });
	
	Cufon.replace('div#Phrase sub')('div#Phrase sup');
	Cufon.replace('table.roomBlock td.room');
	
	Cufon.set('fontFamily', 'Futura Bold');
	Cufon.replace('.futura-bold p');
	Cufon.replace('h1:not(h1.small)');
	Cufon.replace('div#Phrase strong');
	Cufon.replace('table.roomBlock td.room strong');
	
	//Cufon.set('fontFamily', 'Futura Book');
	//Cufon.replace('.futura-book');

	setHeight();
		
	// 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()
	{
		$('div.datequestion').each(function()
		{
			$(this).parent().css('z-index', '999');
		});
		
		$(this).parent().parent().css('z-index', '1000');	
	});
	
	
	$('div#Accordeon div.accordeonContent div.SurveyContainer').each(function()
	{	
		$(this).parent().find('p:first').css('padding', '0');
	});
	
	$('div.SurveyContainer div.singleselectquestion, div.SurveyContainer div.multipleselectquestion').each(function(){
		
		var rowArray = Array();
		var row = '';
		
		var tr = $(this).find('tr');
		
		//length td's
		var numTD = $(this).find('td').length;
		
    	$(this).find('td').each(function(index)
		{
			rowArray.push('<td>' + $(this).html() + '</td>');
			//alert(rowArray);			
			
			if(index % 4 == 3 || index == numTD - 1)
			{
				row += '<tr>' + rowArray.join('') + '</tr>';
			
				// clear Array
				rowArray.length = 0;
			}		
					
		});
		
		tr.remove();
		
		$(this).find('table').append(row);
									
	});
	
	//Shadowbox
	if (gallery.length == 0)
	{
		//Shadowbox.init();
	}
	
});

//Animate Home phrases
function animatePhrase(which)
{
	var tab = $('div.tabPhrase').eq(which);
	
	var phrase1 = tab.find('div.phrase1');
	var phrase2 = tab.find('div.phrase2');
	var phrase3 = tab.find('div.phrase3');
	
	var movement = 175;
	var movementTime = 9000;
	
	if (backoffice == true)
	{
		movementTime = 1500;
	}
	
	$('div.tabPhrase').not(tab).hide();
	tab.show();
	
	phrase1.css('left', -movement);
	phrase1.animate({ left: 0 }, movementTime, 'easeOutCubic');
	
	phrase2.css('left', movement);
	phrase2.animate({ left: 0 }, movementTime, 'easeOutCubic');
	
	phrase3.css('left', -movement * 0.75);
	phrase3.animate({ left: 0 }, movementTime);
}

// 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 adults = reservation.find('input[name=adults]').val();
	var rooms = reservation.find('select[name=rooms]').val();
	
	var parts = checkindate.split('/');
	var calArrivalDateField = parts[2] + '-' + parts[0] + '-' + parts[1];
	parts = checkoutdate.split('/');
	var calDepartureDateField = parts[2] + '-' + parts[0] + '-' + parts[1];
	*/
	
	var adults = reservation.find('select[name=adults]').val();
	var rooms = reservation.find('select[name=rooms]').val();
	
	var checkindate = reservation.find('input[name=checkindate]').val();
	checkinSplit = checkindate.split('/');

	var checkoutdate = reservation.find('input[name=checkoutdate]').val();
	checkoutSplit = checkoutdate.split('/');

	var checkinRealDate = new Date(checkinSplit[2], checkinSplit[1], checkinSplit[0]);
	var checkoutRealDate = new Date(checkoutSplit[2], checkoutSplit[1], checkoutSplit[0]);
	/*
	var checkinRealDate = new Date(checkinSplit[2], checkinSplit[0], checkinSplit[1]);
	var checkoutRealDate = new Date(checkoutSplit[2], checkoutSplit[0], checkoutSplit[1]);
	*/
	
	var stay = (checkoutRealDate - checkinRealDate) / 1000 / 60 / 60 / 24;
	
	var params = {
		'arrival': checkinSplit[2] + '-' + checkinSplit[1] + '-' + checkinSplit[0],
		'arrivald': checkinSplit[0],
		'arrivalm': checkinSplit[1],
		'arrivaly': checkinSplit[2],
		'adults': adults,
		'rooms': rooms,
		'nights': stay,
		'children': 0
	};
	/*
	var params = {
		'arrival': checkinSplit[2] + '-' + checkinSplit[0] + '-' + checkinSplit[1],
		'arrivald': checkinSplit[1],
		'arrivalm': checkinSplit[0],
		'arrivaly': checkinSplit[2],
		'adults': adults,
		'rooms': rooms,
		'nights': stay,
		'children': 0
	};
	*/

	post_to_url('https://www.myfidelio.net/webui/availabilitysearch.aspx?chain=GCH&property=DEAMS01&language=en', params, 'post');
	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");

	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();
}

function setHeight()
{
	if (backoffice == true)
	{
		$('html, body, div#Background').height($(window).height() - $('div#TopBar').height());
	}
	else
	{
		$('html, body, div#Background').height($('div#SiteContainer').height() + $('div#TopBar').height());
	}
	
	var container = $('html').height();
	
	var height = 0;
	height += $('div#TopBar').outerHeight();
	height += $('div#Header').outerHeight();
	height += parseInt($('div#Content').css('paddingTop'));
	height += parseInt($('div#Content').css('paddingBottom'));
	
	$('div#Content').height('auto');
	
	if ((height + $('div#Content').height()) < container)
	{
		$('div#Content').height(container - height);
	}
}
