//WH Gallery item
//var activeGallery;
var backoffice;
var whGallerySlide = 315;
var whGalleryHeight = 165;

var whGallerySlideLarge = 501;
var whGalleryHeightLarge = 381;

var whGalleryOffset = 0;
var whGalleryItems = 1;

var contentExpanded = false;

var musicFrame = false;
var systemLink = false;

var musicMutedByUser = false;

$(document).ready(function()
{
	// Selectbox --------------------------------------------------------------------------
	//$('div.reservation select').selectbox();
	$('div.reservationWidget select').selectbox();	
	
	$('div.reservationWidget div.childrenPerRoom div.expand').hide();
	$('div.reservationWidget div.rates div.expand').hide();

	//Language fix
	$('div.language ul li span, div.language ul li a').html('&nbsp;')
	
	//Homepage SlideShow init. Hide all images show first
	$('div#BackgroundSystem div.image img').hide();
	$('div#BackgroundSystem div.image img:eq(0)').show().addClass('activeImg');
	
	//Homepage movie
	$('body.home a#sb-nav-close').live("click", function(){
		var music = window.parent.document.getElementById('MusicFrame');
		var player = $('div#Switches div.music a');
		var text = '';
		//('MusicFrame').contentWindow.pausePlayer();
		if (player.hasClass('mute') == true && !musicMutedByUser){
			player.removeClass('mute');
			music.contentWindow.playPlayer();
			player.text('music on');
		} 
	});
	
	//Music
	$('div#Switches div.music a').click(function()
	{
		var music = window.parent.document.getElementById('MusicFrame');
		var text = '';
		
		$(this).toggleClass('mute');
		
		if ($(this).hasClass('mute') == true)
		{
			music.contentWindow.pausePlayer();
			musicMutedByUser = true;
			text = 'off';
		}
		else
		{
			music.contentWindow.playPlayer();
			musicMutedByUser = false;
			text = 'on';
		}
		
		$(this).text('music ' + text);
		
		return false;
	});
	
	$('a#playMovie').live("click", function(){
		var music = window.parent.document.getElementById('MusicFrame');
		var player = $('div#Switches div.music a');
		var text = '';
		if (player.hasClass('mute') == true){
			// do nothing music is muted
		} else {
			player.addClass('mute');
			music.contentWindow.pausePlayer();
			player.text('music off');
		}
	});
	
	//Content
	if ($('div#ContentGrid').length > 0)
	{
		$('body').addClass('content');
	}
	
	$(window).resize(function()
	{
		backgroundSystem();
	});
	
	$('ul').each(function()
	{
		$(this).find('li:first').addClass('first');
		$(this).find('li:last').addClass('last');
	});
	
	//WH Gallery
	if ($('div.whGallery').length > 0)
	{
		loadGalleries();
	}
	
	//Expand system
	$('div#Content a.more').click(function()
	{
		expandArea();
		
		return false;
	});
	
	$('div#Content div.closeExpand a').click(function()
	{
		setTimeout('window.location = "/"',100);
		$('div#ContentGrid').fadeOut('1000');
		collapseArea();		
		return false;
	});
	
	//Booking
	$('div#Booking div.bookButton').click(function()
	{
		build_url($(this).parents('div#Booking'));
		
		return false;
	});

	//Date Picker
	var pickers = $('div#Header div.datePicker input').datepicker({
		minDate: new Date(),
		onSelect: function(selectedDate)
		{
			if ($(this).parents('div.datePicker').hasClass('checkindate') == true)
			{
				var setStart = new Date(selectedDate);
				setStart.setDate(setStart.getDate() + 1);
				
				$(pickers[1]).datepicker('option', 'minDate', selectedDate);
				$(pickers[1]).datepicker('setDate', setStart);
			}
		}
	});

	//Adults Picker
	$('div#Header div.amountPicker select').selectbox();
	$('div#Header div.amountPicker span.jquery-selectbox-currentItem').click(function()
	{
		$('div#Header div.amountPicker div.jquery-selectbox-moreButton').click();
	});
	$('div#Header div.amountPicker div.jquery-custom-selectboxes-replaced-list span:first').hide();
	
	// ReservationWidget selectboxes
	//$('div.reservationWidget select').selectbox();
	
	// Login box float fix
	if($('div#pressLogin').length > 0){
		var rowWidth = parseInt($('div#pressLogin div.customForm_Row').css('width'));
		$('div#pressLogin div.customForm_Row').eq(1).css('width',(rowWidth+60)+'px');
	}	
	
	$('div.reservationWidget').each(function()
	{
		var config = $(this).find('div.reservationConfig');
		var fields = $(this).find('div.reservationForm');
		
		//Config option
		var startDate = $.trim(config.find('div.minDate span').text());
		var endDate = $.trim(config.find('div.maxDate span').text());
		var minDays = $.trim(config.find('div.minDays span').text());
		var rateAccessCode = $.trim(config.find('div.accountID span').text());
		var activeID = $.trim(config.find('div.activeID span').text());
		var hideDays = $.trim($(this).find('div.hideDays span').text()).split(',');
		
		//Hotel
		var hotel = fields.find('div.hotel');
		if (hotel.find('select option').length <= 1)
		{
			hotel.hide();
		}
		
		//Checkin
		var checkin = fields.find('div.checkIn');
		if (startDate)
		{
			checkin.find('input').val(startDate);
		}
	
		//Checkout
		var checkout = fields.find('div.checkOut');
		if (endDate)
		{
			checkout.find('input').val(endDate);
		}
		
		/*
		//Toggle link
		fields.find('div.toggleLink a').click(function()
		{
			var nextDiv = $(this).parent().parent().next('div.expand');
			nextDiv.toggle()
			
			return false;
		});
		*/
		
		//Toggle link ChildrenPerRoom
		$('div.childrenPerRoom div.toggleLink a').click(function()
		{
			var nextDiv = $(this).parents('div.childrenPerRoom').find('div.expand');
			nextDiv.toggle()
			
			return false;
		});
		
		//Toggle link Rates
		$('div.rates div.toggleLink a').click(function()
		{
			var nextDiv = $(this).parents('div.rates').find('div.expand');
			nextDiv.toggle()
			
			return false;
		});
				
		//Dates
		var dates = fields.find("div.checkIn input, div.checkOut input" ).datepicker({
			minDate: new Date(),
			beforeShowDay: function(selectedDate)
			{
				var day = selectedDate.getDay();
	
				if ($.inArray(day, hideDays) != -1) 
				{
					return [false];
				}
				else
				{
					return [true];
				}
				
			},
			onSelect: function(selectedDate)
			{
				if ($(this).parents('div.formRow').hasClass('checkIn') == true)
				{
					//Set minimal stay
					if (minDays)
					{
						selectedDate.setDate(selectedDate.getDate() + minDays)
					}
					
					$(dates[1]).datepicker('option', 'minDate', selectedDate);
				}
			}
		});
		
		//Book button
		$(this).find('div.button a').click(function()
		{
			handleReservation($(this).parent().prev('div.reservationForm'));

			return false;
		});
		
	});	
	

	//Background edit
	$('.backoffice div#BackgroundSystem div.editbutton img').click(function(event)
	{
		event.stopPropagation();
	});
	$('.backoffice div#BackgroundSystem img').click(function()
	{
		var system = $('div#BackgroundSystem');
		
		var newHeight = 0;
		
		if (system.height() > 50)
		{
			newHeight = 50;
		}
		else
		{
			newHeight = system.find('div.image').height();
		}
		
		system.stop(true, true);
		system.animate({ height: newHeight + 'px' }, 1000);
		
	});
	
	
	//Home gallery
	if (backoffice == true)
	{
		//nothing
	}
	else {
		if ($('ul#SlideShowNavigation').length > 0 ) {
			//start slideShow on page load 
			var slideTimeout = setTimeout(slideGoRight, 8000);	
		}
	}
		
	$('ul#SlideShowNavigation li.prev').click(function(event) {
		if (!event.detail || event.detail==1) 
		{//activate on first click only to avoid hiding again on double clicks	
			slideGoLeft();	
		}		
	});
	$('ul#SlideShowNavigation li.next').click(function(event) {
		if (!event.detail || event.detail==1) 
		{//activate on first click only to avoid hiding again on double clicks	
			slideGoRight();		
		}		
	});
	

	function slideGoLeft() 
	{
			clearTimeout(slideTimeout);
			slideTimeout = setTimeout(slideGoRight, 8000);
			
			var activeImg = $('div#BackgroundSystem div.image img.activeImg');
			activeImg.fadeOut(1000, function() {
				// Animation complete callback
				activeImg.removeClass('activeImg');
			});  
		  
			var hasPrevSibling = activeImg.prev('img');
			
			if (hasPrevSibling.length > 0) {
				hasPrevSibling.fadeIn(1000, function() {
				// Animation complete callback
					hasPrevSibling.addClass('activeImg');
				});  
			}
			else {
				//er is geen prev, vind :last
				$('div#BackgroundSystem div.image img:last').fadeIn(1000, function() {
				// Animation complete callback
					$(this).addClass('activeImg');
				});  
			}	
	}
	
	function slideGoRight() 
	{
			clearTimeout(slideTimeout);
			slideTimeout = setTimeout(slideGoRight, 8000);
			
			var activeImg = $('div#BackgroundSystem div.image img.activeImg');
			activeImg.fadeOut(1000, function() {
				// Animation complete callback
				activeImg.removeClass('activeImg');
			});  
		  
			var hasNextSibling = activeImg.next('img');
			
			if (hasNextSibling.length > 0) {
				hasNextSibling.fadeIn(1000, function() {
					// Animation complete claaback
					hasNextSibling.addClass('activeImg');
				});  
			}
			else {
				//er is geen next, vind :first
				$('div#BackgroundSystem div.image img:first').fadeIn(1000, function() {
				// Animation complete callback
					$(this).addClass('activeImg');
				});  
			}	
	}
		
	$('ul#SlideShowNavigation li.next').click(function() {
		var activeImg = $('div#BackgroundSystem div.image div.activeImg');
		activeImg.fadeOut().removeClass('activeImg');	
	});
	
	(function(){
		//set email field.
		var a = $('.subscribe a:first');
		a.data('orig-href', a.attr('href'));

		$('.subscribe input[type=text]')
			.watermark('  email', {className: 'init'})
			.bind('keyup', function(){
				a.attr('href', a.data('orig-href') + $(this).val());
			}).bind('keydown', function(event){
				if(event.which == 13){
					post_to_url(a.data('orig-href').replace(/\?email=.+/i,''), { email: $(this).val() }, 'get');
				}
			});
		
	})();
	
	
	
	backgroundSystem();
	
});

function backgroundSystem()
{
	var container = $(window);
	
	var windowWidth = container.width();
	var windowHeight = container.height();
	
	var container;
	
	if (backoffice == true)
	{
		container = $('div#SiteContainer');
	}
	else
	{
		container = $('div#BackgroundSystem, div#SiteContainer');
	}
	
	container.width(windowWidth);
	
	if (backoffice == true)
	{
		container.height(windowHeight - 60);
	}
	else
	{
		container.height(windowHeight);
	}
	
	//Description
	var label = $('div#BackgroundSystem div.label');
	var position = $.trim(label.find('div.position span').text());
	
	if (position != '')
	{
		position = position.split(',');
		label.css('right', parseInt(position[0]) + 'px');
		label.css('top', parseInt(position[1]) + 'px');
	}
	
	//Expanded area
	var expand = $('div#ContentGrid div.textArea div.expandArea');
	var textHeight = expand.find('div.collection').height();
	expand.height(textHeight);
	
	if ($('body').hasClass('content') == false)
	{
		$('div#Content').height(windowHeight - $('div#Header').outerHeight() - $('div#Footer').outerHeight());
	}
	
	//Menu
	if (container.length > 0)
	{
		var maxHeight = 800;
		var minHeight = 550;
		
		var maxWidth = 1250;
		var minWidth = 1000;
		
		var minFont = 0.5;
		
		var totalHeight = container.outerHeight();
		var totalWidth = container.outerWidth();
		
		var newSize = 0;
		
		if (totalHeight < maxHeight || totalWidth < maxWidth)
		{
			var newSizeH = (totalHeight - minHeight) / (maxHeight - minHeight);
			var newSizeW = (totalWidth - minWidth) / (maxWidth - minWidth);
			
			if (newSizeH < newSizeW)
			{
				newSize = newSizeH;
			}
			else
			{
				newSize = newSizeW;
			}
			
			if (newSize < minFont)
			{
				newSize = minFont;
			}
		}
		else
		{
			newSize = 1;
		}
		
		$('div#SiteContainer div#Menu').css('font-size', newSize + 'em');
		
	}
	
}

function expandArea()
{
	contentExpanded = true;
	
	var container = $('div#Content');
	container.addClass('expanded');
	
	var expand = container.find('div#ContentGrid div.textArea div.expandArea');
	
	//remove other Close X
	if($('div.closeContent').length > 0 ){ $('div.closeContent').css('display','none');}
	
	if (expand.length > 0)
	{
		expand.show();
	}
	else
	{
		container.find('div#ContentGrid div.textArea').append('<div class="expandArea"><div class="collection">&nbsp;</div><div class="closeExpand"><a href="#">close<span>X</span></a></div></div>');
		$('div#Content div.closeExpand a').click(function()
		{
			setTimeout('window.location = "/"',100);
			$('div#ContentGrid').fadeOut('1000');
			collapseArea();		
			return false;
		});
		container.find('div#ContentGrid div.textArea div.expandArea').show();
	}
		
	var textHeight = expand.find('div.collection').height();
	
	var thisGallery = container.find('div.whGallery');
	var activeGallery = thisGallery.attr('active');
	var galleryContent = thisGallery.find('div.imageArea div.category').eq(activeGallery);

	expand.stop(true, true);
	expand.animate({ height: textHeight + 'px' }, 500);
	
	thisGallery.find('div.imageArea').stop(true, true);
	thisGallery.find('div.imageArea').animate({
		width: whGallerySlideLarge + 'px',
		height: whGalleryHeightLarge + 'px'
	}, 500);
	
	thisGallery.find('div.scroller').stop(true, true);
	thisGallery.find('div.scroller').animate({ top: '135px' }, 500);
	
	//All categories
	thisGallery.find('div.imageArea div.category').each(function()
	{
		$(this).width($(this).find('div.slide').length * whGallerySlideLarge);
	});
	//galleryContent.width(galleryContent.find('div.slide').length * whGallerySlideLarge);
	
	galleryContent.css('left', galleryContent.attr('posXLarge') + 'px');
}
function collapseArea()
{
	contentExpanded = false;
	
	var container = $('div#Content');
	container.removeClass('expanded');
	
	var expand = container.find('div#ContentGrid div.textArea div.expandArea');
	
	var thisGallery = container.find('div.whGallery');
	var activeGallery = thisGallery.attr('active');
	var galleryContent = thisGallery.find('div.imageArea div.category').eq(activeGallery);

	expand.stop(true, true);
	expand.animate({ height: 0 }, 500, null, function() { $(this).hide() } );

	thisGallery.find('div.imageArea').stop(true, true);
	thisGallery.find('div.imageArea').animate({
		width: whGallerySlide + 'px',
		height: whGalleryHeight + 'px'
	}, 500);
	
	thisGallery.find('div.scroller').stop(true, true);
	thisGallery.find('div.scroller').animate({ top: '75px' }, 500);
	
	//All categories
	thisGallery.find('div.imageArea div.category').each(function()
	{
		$(this).width($(this).find('div.slide').length * whGallerySlide);
	});
	//galleryContent.width(galleryContent.find('div.slide').length * whGallerySlide);

	galleryContent.css('left', galleryContent.attr('posX') + 'px');
}

function loadGalleries()
{
	//WH JS gallery
	var gallery = $('div.whGallery');
	
	var human = Array('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen');
	
	gallery.each(function(index)
	{
		var myGallery = $(this);
		
		var selectHotel = $.trim(myGallery.find('div.sliderConfig span').eq(0).text());
		if (selectHotel == '')
		{
			selectHotel = 'Weinmeister';
		}
		
		var selectCategory = $.trim(myGallery.find('div.sliderConfig span').eq(1).text());
		selectCategory = selectCategory.toLowerCase();
		
		//$.get('/content/gallery.txt', function(data)
		//$.get('gallery.txt', function(data)
		//$.get('/Controls/Plugins/WorldHotels/GalleryImages.ashx?hotel=' + selectHotel, function(data)
		$.get('/Handlers/GalleryImages.ashx?GalleryName=' + selectHotel, function(data)
		{
			var galleryContent = myGallery.find('div.imageArea');
		
			var categories = Array();
			
			//Parser
			if (window.DOMParser)
			{
				parser=new DOMParser();
				xmlDoc=parser.parseFromString(data,"text/xml");
			}
			else // Internet Explorer
			{
				xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
				xmlDoc.async="false";
				xmlDoc.loadXML(data);
			} 

			galleryContent.html('');

			$(xmlDoc).find('categories category').each(function()
			{
				var categoryName = $(this).attr('name');
				categoryName = categoryName.split(' ').join('_');
				categoryName = categoryName.toLowerCase();

				if (selectCategory && selectCategory != categoryName)
				{
					//return true;
					return;
				}
				
				categories.push(categoryName);
				
				galleryContent.append('<div class="category" id="' + categoryName + '" />');
				
				thisCategory = galleryContent.find('div#' + categoryName);
				
				myGallery.find('div.categories').append('<a href="#" class="mittelschrift">' + $(this).attr('name') + '</a> ');
				
				$(this).find('image').each(function()
				{
					var url = '/' + $(this).text();
					//var url = 'http://www.worldhotelsaltanat.com/' + $(this).text();
					url = url.toLowerCase();
					
					//var largeUrl = url.split('.jpg').join('_Large.jpg');
					var largeUrl = url.substr(0, url.lastIndexOf('.jpg')) + '_Large.jpg';
					
					var galleryName = categoryName + '_' + human[index];
					
					//thisCategory.append('<div class="slide"><a href="' + largeUrl + '" rel="shadowbox['+ galleryName + ']"><img src="' + url + '" /></a></div>');
					thisCategory.append('<div class="slide"><a href="' + largeUrl + '" rel="shadowbox['+ galleryName + ']"><img src="' + largeUrl + '" /></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);
					});
					
					$(this).click(function()
					{
						expandArea();
						
						return false;
					});
					
				});
				
				thisCategory.width($(this).find('image').length * whGallerySlide);
				
				thisCategory.append('<div class="clear">&nbsp;</div>');
			});
			
			if (selectCategory)
			{
				myGallery.find('div.categories').hide();
			}

			if (index == gallery.length - 1)
			{
				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 activeGallery = thisGallery.attr('active');
					//var galleryContent = thisGallery.find('div.imageArea');
					var galleryContent = thisGallery.find('div.imageArea div.category').eq(activeGallery);
					
					//if (galleryContent.attr('posX') >= 0) return;
					if (contentExpanded == true)
					{
						if (galleryContent.attr('posXLarge') >= 0) return;
					}
					else
					{
						if (galleryContent.attr('posX') >= 0) return;
					}
					
					scrollGallery('left', thisGallery);
					
					return false;
				});
				gallery.find('div.rightScroll').click(function()
				{
					var thisGallery = $(this).parents('div.whGallery');
					var activeGallery = thisGallery.attr('active');
					//var galleryContent = thisGallery.find('div.imageArea');
					var galleryContent = thisGallery.find('div.imageArea div.category').eq(activeGallery);
					
					//var maxi = (galleryContent.find('div.category').eq(activeGallery).find('div.slide').length * -whGallerySlide) + (whGalleryItems * whGallerySlide) + whGalleryOffset;
					var maxi = 0;
					if (contentExpanded == true)
					{
						maxi = (galleryContent.find('div.slide').length * -whGallerySlideLarge) + (whGalleryItems * whGallerySlideLarge) + whGalleryOffset;
						if (galleryContent.attr('posXLarge') <= maxi) return;
					}
					else
					{
						maxi = (galleryContent.find('div.slide').length * -whGallerySlide) + (whGalleryItems * whGallerySlide) + whGalleryOffset;
						if (galleryContent.attr('posX') <= maxi) return;
					}
					
					scrollGallery('right', thisGallery);
					
					return false;
				});
				
				//Has to be set to mark active for all galleries, not only first
				changeGallery(0, $('div.whGallery:first'));
				//Shadowbox.init();
			}

		});

	});

	function scrollGallery(dir, thisGallery)
	{
		//var galleryContent = thisGallery.find('div.imageArea');
		var activeGallery = thisGallery.attr('active');
		var galleryContent = thisGallery.find('div.imageArea div.category').eq(activeGallery);
		
		var x = parseInt(galleryContent.attr('posX'));
		var xLarge = parseInt(galleryContent.attr('posXLarge'));

		if (dir == 'right')
		{
			galleryContent.attr('posX', x - whGallerySlide);
			galleryContent.attr('posXLarge', xLarge - whGallerySlideLarge);
		}
		else
		{
			galleryContent.attr('posX', x + whGallerySlide);
			galleryContent.attr('posXLarge', xLarge + whGallerySlideLarge);
		}
		
		galleryContent.stop();
		
		var newPosX = 0;
		if (contentExpanded == true)
		{
			newPosX = galleryContent.attr('posXLarge');
		}
		else
		{
			newPosX = galleryContent.attr('posX');
		}
		
		galleryContent.animate({left: newPosX + 'px'}, 250);
	}
	
	function changeGallery(index, thisGallery)
	{
		var galleryContent = thisGallery.find('div.imageArea');
		var activeGallery = thisGallery.attr('active');
		
		if (index == activeGallery) return;
		
		var categories = galleryContent.find('div.category');
		
		categories.eq(activeGallery).hide();
		categories.eq(index).show();
		
		//galleryContent.attr('posX', whGalleryOffset);
		//galleryContent.stop();
		//galleryContent.animate({left: galleryContent.attr('posX') + 'px'}, 250);
		categories.attr('posX', whGalleryOffset);
		categories.attr('posXLarge', whGalleryOffset);
		
		categories.stop();
		categories.animate({left: categories.attr('posX') + 'px'}, 250);

		var names = gallery.find('div.categories a');
		names.removeClass('active');
		names.eq(index).addClass('active');

		thisGallery.attr('active', index)
	}

	//End WH JS gallery
}

//Music system
function useMusic()
{
	if (navigator.userAgent.match(/MSIE 6.0/i) != null)
	{
		return;
	}
	
	if ($('div.controlBorder'.length) > 0) return;
	
	var History;
	var pageURL = window.location.href;
	
	if (pageURL.lastIndexOf('?') == pageURL.length - 1)
	{
		pageURL = pageURL.substring(0, pageURL.lastIndexOf('?'));
	}
	
	if (window.name == 'contentFrame')
	{
		musicFrame = true;
		
		window.parent.systemLink = true;
		
		History = window.parent.History;
		History.pushState(null, null, pageURL);
		
		//IE Delay
		setTimeout(function() { window.parent.systemLink = false }, 500);
	}
	else
	{
		History = window.History;

		History.Adapter.bind(window, 'statechange', function()
		{
			var State = History.getState();
			
			//History.log(State.data, State.title, State.url);
			//console.log(systemLink);
			
			if (systemLink == false)
			{
				document.getElementById('ContentFrame').src = State.url + '?'; // + '?' + (Math.random() * 1000);
			}
			
		});

		if (pageURL.indexOf('#') >= 0)
		{
			var pageSplit = pageURL.split('#');
			
			window.location = 'http://' + document.domain + '/' + pageSplit[1];
		}
		
		$('body').html('');
		$('body').css('line-height', 0);
		$('body').css('font-size', 0);
		
		$('html').css('overflow', 'visible');
		
		var frameHTML = '';
		frameHTML += '<iframe src="' + pageURL + '?" id="ContentFrame" name="contentFrame" width="100%" scrolling="auto" frameborder="0"></iframe>';
		frameHTML += '<iframe src="/music" id="MusicFrame" name="musicFrame" width="100%" scrolling="no" frameborder="0"></iframe>';
		
		$('body').html(frameHTML);
		
		$(window).resize(useMusicResize);
		
		useMusicResize();
	}
	
}

function useMusicResize()
{
	var content = $('iframe#ContentFrame');
	var music = $('iframe#MusicFrame');
	
	content.height($(window).height() - 1);
	music.height(1);
}


// Booking engine script -----------------------------------------------------------------------------------------
function build_url(reservation)
{
	var selectedHotel = reservation.find('input[name=hotel]').val();
	selectedHotel = selectedHotel.split('|');
	
	var checkindate = reservation.find('div.checkindate input').val();
	var checkoutdate = reservation.find('div.checkoutdate input').val();
	
	var IBFname = selectedHotel[0];
	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();
	var rooms = 1;
	
	//var child1 = reservation.find('select[name=child1]').val();
	var child1 = 0;
	//var child2 = reservation.find('select[name=child2]').val();
	var child2 = 0;
	//var child3 = reservation.find('select[name=child3]').val();
	var child3 = 0;
	//var child4 = reservation.find('select[name=child4]').val();
	var child4 = 0;
	//var child5 = reservation.find('select[name=child5]').val();
	var child5 = 0;
	//var child6 = reservation.find('select[name=child6]').val();
	var child6 = 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 = {
		'bf':IBFname,
		'arrivalDate': calArrivalDateField,
		'departureDate':calDepartureDateField,
		'adults': adults,
		'lng': language
	};
	
	
	if (rateAccessCode != 'Access code')
		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;
	if (child1 != '')
		params["childrenAges1"] = child1;
	if (child2 != '')
		params["childrenAges1"] += ',' + child2;
	if (child3 != '')
		params["childrenAges2"] = child3;
	if (child4 != '')
		params["childrenAges2"] += ',' + child4;
	if (child5 != '')
		params["childrenAges3"] = child5;
	if (child6 != '')
		params["childrenAges3"] += ',' + child6;

	
		
	//Children fields here...
	//post_to_url('https://www.yourreservation.net/ibe/' + IBFname + '/main.html', params, 'get');
	//post_to_url('http://www.yourreservation.net/tb3/index.cfm?bf=' + IBFname + '', params, 'get');
	
	// MOBILE FIX FOR BOOKING
	// REMOVE AFTER MOBILE SITES GO LIVE
	if(devicIseMobile()){
		window.open('https://www.trustinternational.com/mb/WH/2B?LANGUAGE=en&i=HABERWEI&property=TXL-WW-HABERWEI');
	} else {
		post_to_url('http://www.yourreservation.net/tb3/index.cfm', params, 'get');
	}
	// UNCOMMENT THIS
	// post_to_url('http://www.yourreservation.net/tb3/index.cfm', params, 'get');
	// END FIX
	
	
	//post_to_url('https://www.yourreservation.net/ibe/' + IBFname + '/main.html', params, 'get');
	
	//_gaq.push(['_link', 'https://www.yourreservation.net/ibe/' + IBFname + '/main.html']);
	
	return false;
}

function post_to_url(path, params, method) {
	method = method || "post"; // Set method to post by default, if not specified.
	
	$('form#GeneratedForm').remove();

	// 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 + '?' + (Math.random() * 1000));
	form.setAttribute("target", "_blank");
	form.setAttribute("id", 'GeneratedForm');
	
	//Google Analytics post
	//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 handleReservation(myreservation)
{
	//Hotel
	var hotel = myreservation.find('div.hotel select').val();
	hotel = hotel.split('|');
	
	var IBFname = hotel[0];
	var ccpSelectCity = hotel[1];
	var ccpSelectHotel = hotel[2];
	var ccpSelectCountry = hotel[3];
	var language = hotel[4];
	
	//Check-in
	var checkIn = myreservation.find('div.checkIn input').val();
	//Check-out
	var checkOut = myreservation.find('div.checkOut input').val();

	//Rooms
	var rooms = myreservation.find('div.rooms input').val();

	//Adults
	var adults = myreservation.find('div.adults select').val();

	//Child code here...
	
	//Promo rate
	var rateAccessCode = myreservation.find('div.rates input.accessCode').val();
	
	//Account ID
	var accountID = myreservation.find('div.rates input.accessCode').val();
	
	//Date fields
	var parts = checkIn.split('/');
	var calArrivalDateField = parts[2] + '-' + parts[0] + '-' + parts[1];
	
	parts = checkOut.split('/');
	var calDepartureDateField = parts[2] + '-' + parts[0] + '-' + parts[1];

	var params = {
		'bf':IBFname,
		'arrivalDate': calArrivalDateField,
		'adults': adults,
		'rooms': rooms,
		'lng': language
	};
	
	if (checkOut && checkOut != 'Check-out')
	{
		params["departureDate"] = calDepartureDateField;
	}
	
	if (rateAccessCode && rateAccessCode != 'Code')
	{
		params["rateAccessCode"] = rateAccessCode;
	}
	
	if (accountID && accountID != 'ID')
	{
		params["iataNumber"] = accountID;
	}
	
	post_to_url('http://www.yourreservation.net/tb3/index.cfm', params, 'get');
	
	//_gaq.push(['_link', 'https://www.yourreservation.net/ibe/' + IBFname + '/main.html']);
	
	return false;	
}

function devicIseMobile(){
	var ua = navigator.userAgent;
	// supported mobile devices
    var checker = {
      iphone: ua.match(/(iPhone|iPod|iPad)/),
      blackberry: ua.match(/BlackBerry/),
      android: ua.match(/Android/)
    };
    if (checker.android){
        return true;
    }
    else if (checker.iphone){
       return true;
    }
    else if (checker.blackberry){
        return true;
    }
    else {
        return false;
    }
}

/*
function makeReservationWidget()
{
	$('div.reservationWidget').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();
		
		//Disable days
		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]));
		}
		
		//Hotels
		var hotels = $(this).find('div.hotel select option').length;
		if (hotels > 1)
		{
			$(this).addClass('showHotels');
			$(this).find('div.hotel select').selectbox();
		}
		
		//Fields
		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');
				}
			});
		}
		
		
		
	});
	
	$('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();
        }
    }
	
} */
