//WH Gallery item
//var activeGallery;
var whGallerySlide = 830; //image is 800 plus 30 margin (15 left + 15 right)
var whGalleryHeight = 406;
var whGallerySlideLarge = 455;
var whGalleryHeightLarge = 300;
var whGalleryOffset = 0;
var whGalleryItems = 1;

var contentExpanded = false;

var backoffice = false;
		
var baseTopFloor1 = 54; // Floor 1: bottom floor is 5th in html flow
var baseTopFloor2 = 137; // Floor 2: bottom floor is 4th in html flow
var baseTopFloor3 = 220; // Floor 3: bottom floor is 3rd in html flow
var baseTopFloor4 = 303; // Floor 4: bottom floor is 2nd in html flow
var baseTopFloor5 = 385; // Floor 5: bottom floor is 1st in html flow

var baseStar1Pos = [70, 5];
var baseStar2Pos = [163, 140];
var baseStar3Pos = [360, 140];
var baseStar4Pos = [600, 75];
var baseStar5Pos = [730, 127];
var baseStar6Pos = [805, 188];
var baseStar7Pos = [63, 340];
var baseStar8Pos = [200, 340];
var baseStar9Pos = [445, 340];
var baseStar10Pos = [660, 340];
var baseStar11Pos = [810, 340];
var baseStar12Pos = [500, 180];

var musicFrame = false;
var systemLink = false;

var resizeTimeout;

$(document).ready(function()
{
	if (navigator.userAgent.match(/iPad/i) != null)
	{
		$('html').addClass('iPad');
		$('html').width(1000);
	}
	//Cufon init
		//GothamBook
		//Cufon('div.star a', { fontFamily: 'GothamBook' });		
		//GothamBold
		//GothamLight
		Cufon('div#IntroTitle span', { fontFamily: 'GothamLight', hover: 'true' });
		Cufon('H1 span', { fontFamily: 'GothamLight', hover: 'true' });
		//GothamMedium
		Cufon('div.reservation div.book a, div.bookButton a', { fontFamily: 'GothamMedium', hover: 'true' });
		Cufon('div#Menu ul li a', { fontFamily: 'GothamMedium', hover: 'true' });


		// Selectbox --------------------------------------------------------------------------
	$('div.reservation select').selectbox();
	$('div.reservationWidget select').selectbox();	
	
	$('div.reservationWidget div.childrenPerRoom div.expand').hide();
	$('div.reservationWidget div.rates div.expand').hide();

	$('div#StarGrid div.starWrap div.star').addClass('starHidden');
	
	//Content
	if ($('div#ContentGrid').length > 0)
	{
		$('body').addClass('content');
	}
	
	$(window).resize(function()
	{
		clearTimeout(resizeTimeout);
		backgroundSystem();
		resizeTimeout = setTimeout(backgroundSystem, 100);
	});
	
	$('ul').each(function()
	{
		$(this).find('li:first').addClass('first');
		$(this).find('li:last').addClass('last');
	});
	
	$('div#RoomLinks').each(function()
	{
		$(this).find('div.room:first').addClass('first');
		$(this).find('div.room:last').addClass('last');
	});
	
	//Music
	$('div#Music div.status').click(function()
	{
		var music = window.parent.document.getElementById('MusicFrame');
		var text = '';
		
		$(this).toggleClass('mute');
		
		if ($(this).hasClass('mute') == true)
		{
			music.contentWindow.pausePlayer();
			text = 'off';
		}
		else
		{
			music.contentWindow.playPlayer();
			text = 'on';
		}
		
		$(this).text('music ' + text);
		
		return false;
	});
	
		
	//WH Gallery
	if ($('div.whGallery').length > 0)
	{
		loadGalleries();
		//console.log('load galleries');
	}
	
	
	// SB Mini Gallery - Room page
	$('div#RoomGallery div#RoomMap div.view').each(function()
	{
		$(this).click(function()
		{
			index = $(this).index();
			//index = index - 1;
			$('div#RoomGallery div#RoomView img.active').removeClass('active');
			$('div#RoomGallery div#RoomView img').eq(index).addClass('active');
		});		
	});	
	
	// SB FloorNav links 
	$('div#FloorLinks ul.roomsList li').each(function()
	{
		$(this).mouseenter(function()
		{
			index = $(this).index();
			index = index + 1;
			//console.log(index);
			$(this).parents('div.floorRoomsMenu').find('div.active').removeClass('active');
			$(this).parents('div.floorRoomsMenu').find('div.floorRoomsPlan').eq(index).addClass('active');
		});
		$(this).mouseleave(function()
			{
				index = $(this).index();
				index = index + 1;
				//console.log(index);
				$(this).parents('div.floorRoomsMenu').find('div.active').removeClass('active');				
				$(this).parents('div.floorRoomsMenu').find('div.floorRoomsPlan').eq(0).addClass('active');
			});
	});	
	
	//Expand system
	$('div#Content a.more').click(function()
	{
		expandArea();
		
		return false;
	});
	$('div#Content div.closeExpand a').click(function()
	{
		collapseArea();
		
		return false;
	});
	
	//Date Picker
	$('div#Header div.datePicker input').datepicker();

	//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();

	
	// Pressbuton 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');
	}	
	
	
	//Background edit
	$('.backoffice div#BackgroundSystem div.editbutton img').click(function(event)
	{
		event.stopPropagation();
	});

	$('div#SubLinks li.language').mouseenter(function()
		{
			$(this).parent().addClass('hover');
		});
		$('div#SubLinks li.language').mouseleave(function()
		{
			$(this).parent().removeClass('hover');
		});
		
	$('div#SubLinks li.language').addClass($('div#SubLinks li.language ul li span').parent().attr('class'));
	
	
	var menuTimeout;
	var menuOpen; 
	
	$('div#Menu div.AspNet-TreeView ul li.AspNet-TreeView-Root').mouseenter(function()
		{
			clearTimeout(menuTimeout); 
			
			if(menuOpen != null) {
				menuOpen.removeClass('hover');
			} 
			
			$(this).addClass('hover');
			
			menuOpen = $(this);
		});
		$('div#Menu div.AspNet-TreeView ul li.AspNet-TreeView-Root').mouseleave(function()
		{
			menuTimeout = setTimeout(closeMenu, 800);
			//$(this).parent().removeClass('hover');
		});
		
		function closeMenu() {
			menuOpen.removeClass('hover');
		} 
	
	
	if (backoffice != true)
	{
		$('div#FloorLinks div.floor').mouseenter(function()
		{	
			$(this).addClass('hover');
			$(this).stop().animate({
			width:360
			}, 350, function() {
			// Animation complete.
			});
		
		});
		$('div#FloorLinks div.floor').mouseleave(function()
		{
			$(this).stop().animate({
			width:30
			}, 350, function() {
			// Animation complete.
			$(this).removeClass('hover');
			});
		});
	}
	
	$('div#RoomLinks div.room').mouseenter(function()
	{
		$(this).addClass('hover');
	});
	$('div#RoomLinks div.room').mouseleave(function()
	{
		$(this).removeClass('hover');
	});
	
	$('div#StarGrid div.starWrap').mouseenter(function()
	{
		$(this).addClass('hover');
	});
	$('div#StarGrid div.starWrap').mouseleave(function()
	{
		$(this).removeClass('hover');
	});

	if (backoffice != true)
	{
			$('div#BackgroundSystem div.image img').load(function()
			{
				homepageMenuHint();
				
				setTimeout(backgroundSystem, 100);
			});
	}	

	/*
	$('div#BackgroundSystem div.image img').load(function()
	{
		console.log($('div#BackgroundSystem div.image img').height());
		
		//Fix for loading images Chrome Mac
		$(this).css('visibility', 'visible');
		setTimeout(backgroundSystem, 100);
		
	});
	*/

	// Booking engine --------------------------------------------------------------------------
	$('div.reservationWidget, div.reservation').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().next('div.expand');
			$(this).hide();
			nextDiv.toggle()			
			return false;
		});
		
		//Dates
		var dates = fields.find("div.checkIn input, div.checkOut input" ).datepicker({
			buttonImage: '/content/Lux11/images/sprite.gif',
			buttonImageOnly: true,
			showOn: 'both',
			minDate: new Date(),
			beforeShowDay: function(selectedDate)
			{
				var day = selectedDate.getDay();
	
				if ($.inArray(day, hideDays) != -1) 
				{
					return [false];
				}
				else
				{
					return [true];
				}
				
			},
			onSelect: function(selectedDate)
			{
				selectedDate = new Date(selectedDate);
				
				if ($(this).parents('div.formRow').hasClass('checkIn') == true)
				{
					//Set minimal stay
					if (minDays)
					{
						selectedDate.setDate(selectedDate.getDate() + minDays)
					}
					else
					{
						selectedDate.setDate(selectedDate.getDate() + 1)
					}
					
					$(dates[1]).datepicker('option', 'minDate', selectedDate);
					$(dates[1]).datepicker('option', 'setDate', selectedDate);
					$(dates[1]).val((selectedDate.getMonth() + 1) + '/' + selectedDate.getDate() + '/' + selectedDate.getFullYear())
				}
			}
		});
		
		var checkItIn = new Date();
		checkItIn.setDate(checkItIn.getDate() + 1);
		
		$(dates[0]).datepicker('option', 'setDate', checkItIn);
		$(dates[0]).val((checkItIn.getMonth() + 1) + '/' + checkItIn.getDate() + '/' + checkItIn.getFullYear())

		var checkItOut = new Date();
		checkItOut.setDate(checkItIn.getDate() + 1);
		
		$(dates[1]).datepicker('option', 'setDate', checkItOut);
		$(dates[1]).val((checkItOut.getMonth() + 1) + '/' + checkItOut.getDate() + '/' + checkItOut.getFullYear())


		//Tabs
		$(this).find('div.reservationTabs li.reservation a').click(function()
		{
			//Hotel
			var thishotel = hotel.find('select').val();
			thishotel = thishotel.split('|');
			
			window.open('https://www.yourreservation.net/tb3/index.cfm?bf=' + thishotel[0] + '&lng=' + thishotel[4] + '&modification');
			
			return false;
		});

		//Book button
		$(this).find('div.book').click(function()
		{
			handleReservation($(this).prev('div.reservationForm'));
			return false;
		});
		
	});

	//Bind subscribe button
	(function(){
		//set email field.
		var a = $('.subscribe a:first');
		a.data('orig-href', a.attr('href'));

		$('.subscribe input[type=text]')
			.watermark('Subscribe to newsletter', {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');
				}
			});
		
	})();
	
	
	//Always do resize
	backgroundSystem();
		
});


function homepageMenuHint() 
	{	
	
		$('div#FloorLinks div.floor').each(function() 
			{
				$(this).addClass('hover');
			});
		$('div#StarGrid').css('z-index','10');
		$('div#FloorLinks div.floor').eq(0).stop().animate({width:360}, 300, 'easeInQuad', function() {/*Animation complete.*/});		
		$('div#FloorLinks div.floor').eq(0).delay(700).animate({width:30}, 300, 'easeOutQuad', function() {/*Animation complete.*/});
		
		$('div#FloorLinks div.floor').eq(1).delay(150).animate({width:360}, 300, 'easeInQuad', function() {/*Animation complete.*/});		
		$('div#FloorLinks div.floor').eq(1).delay(800).animate({width:30}, 300, 'easeOutQuad', function() {/*Animation complete.*/});	
		
		$('div#FloorLinks div.floor').eq(2).delay(300).animate({width:360}, 300, 'easeInQuad', function() {/*Animation complete.*/});		
		$('div#FloorLinks div.floor').eq(2).delay(900).animate({width:30}, 300, 'easeOutQuad', function() {/*Animation complete.*/});	
		
		$('div#FloorLinks div.floor').eq(3).delay(450).animate({width:360}, 300, 'easeInQuad', function() {/*Animation complete.*/});		
		$('div#FloorLinks div.floor').eq(3).delay(1000).animate({width:30}, 300, 'easeOutQuad', function() {/*Animation complete.*/});	
		
		$('div#FloorLinks div.floor').eq(4).delay(600).animate({width:360}, 300, 'easeInQuad', function() {/*Animation complete.*/});		
		$('div#FloorLinks div.floor').eq(4).delay(1100).animate({width:30}, 300, 'easeOutQuad', 
		function() 
		//callback function off last .animate
		{ 
			$('div#StarGrid').delay(300).css('z-index','0');
			
			$('div#FloorLinks div.floor').each(function() 
			{
				$(this).removeClass('hover');
			});
		});	
	}

	//Music
	$('div#Music div.status').click(function()
	{
		alert('clicked');
		window.open('/music', 'Player', 'location=0,status=0,scrollbars=0,toolbar=0,directories=0,resizable=0,width=250,height=24');
	});
	
// Background
function backgroundSystem()
{
	var minHeight = 560;
	var maxHeight = 664;
	var refHeight = 500;
	
	var docHeight = $(document).height() - $('div#Header').outerHeight(true) - $('div#Footer').outerHeight(true) - 10;
	
	if (docHeight < minHeight)
	{
		docHeight = minHeight;
	}
	if (docHeight > maxHeight)
	{
		docHeight = maxHeight;
	}

	$('div#Content').height(docHeight);
	
	//Correction
	var correctionFactor = docHeight / refHeight;
	correctionFactor = correctionFactor * 1.1;
	
	$('div#StarGrid div.starWrap').each(function(index)
	{
		eval('var starPos = baseStar' + (index + 1) + 'Pos');
		
		$(this).css('left', (parseInt(starPos[0]) * correctionFactor) + 'px');
		$(this).css('top', (parseInt(starPos[1]) * correctionFactor) + 'px');
	});

	$('div#FloorLinks div.floor').each(function(index) 
	{		
		eval('var floorPos = baseTopFloor' + (index + 1));
		
		$(this).css('top', (parseInt(floorPos) * correctionFactor) + 'px');
	});
	
	var imgWidth = $('div#BackgroundSystem div.image img').width();
	var bgWidth = $('div#BackgroundSystem').width();
	
	var offsetWidth = 0;
	var collection = $('div#Content div#BackgroundSystem, div#Content div#StarGrid, div#Content div#FloorLinks');
	
	if (imgWidth < bgWidth)
	{
		offsetWidth = ((bgWidth - imgWidth) / 2);
	}

	$('div#Header, div#Footer').css({ paddingLeft: offsetWidth + 'px', paddingRight: offsetWidth + 'px' });
	collection.css('left', offsetWidth + 'px');

	$('div#Introduction').each(function()
	{
		$(this).css('left', (($('div#BackgroundSystem div.image img').width() / 2) - ($(this).width() / 2)) + offsetWidth + 'px');
	});


	/*
	var baseHeight = 492;
	var baseWidth = 1000;
	
	var container = $(window);	
	var windowWidth = container.width();
	var imageWidth = $('div#BackgroundSystem div.image img').width();
	var imageHeight = $('div#BackgroundSystem div.image img').height();
	//var windowHeight = container.height() - 146 - 40;
	//var windowWidth = $('div#BackgroundSystem div.image img').width();
	
	//var windowHeight = $('div#BackgroundSystem div.image img').height();
	//C Hiralal 23-11-2011
	var windowHeight = $('div#BackgroundSystem div.image img').height();
	var docHeight = $(document).height() - $('div#Header').outerHeight() - $('div#Footer').outerHeight() - 10;
	
	if (docHeight < windowHeight)
	{
		windowHeight = docHeight;
	}
	
	//console.log('windowHeight: ' + windowHeight);
	//console.log('windowWidth: ' + windowWidth);	
	var container;

	if (backoffice == true)
	{
		//container = $('div#SiteContainer');
		container = $('div#BackgroundSystem');
	}
	else
	{
		container = $('div#BackgroundSystem');
	}
	//console.log('windowHeight: ' + windowHeight);
	//console.log('windowWidth: ' + windowWidth);	
	
	container.width(windowWidth);
	container.height(windowHeight);
	
	//$('div#Content').height((windowHeight + 40)); // Plus 40 for Footer
	
	//C Hiralal 23-11-2011
	//var docHeight = $(document).height() - $('div#Header').outerHeight() - $('div#Footer').outerHeight() - 10;
	
	//if (windowHeight < docHeight)
	//{
	//	docHeight = windowHeight;
	//}
	
	//$('div#Content').height(docHeight);

	$('div#Content').height(windowHeight);
	//End C Hiralal 23-11-2011
	
	//console.log('windowHeight updated');
	

		// Update Floorlinks top position. S Bonardt 25-10-2011 + C Hiralal 23-11-2011
		//var posAdjust = windowHeight / baseHeight;
		var posAdjust = docHeight / baseHeight;
		
		$('div#FloorLinks div.floor').each(function() 
		{		
			// Get current floor index
			var index = $(this).index();
					//console.log('index of current floor: ' + index);
			index = index + 1; //adjust to start at 1 iso 0
			index = index.toString();
					//console.log('index of current floor string: ' + index);
					//console.log('windowHeight in each:' + windowHeight);
					//console.log('baseHeight in each:' + baseHeight);	
			//var posAdjust = windowHeight / baseHeight;
					//console.log('posAdjust:' + posAdjust);
			
			var baseTopReference = 'baseTopFloor' + index;
					//console.log('baseTopReference + index :' + baseTopReference);
			var baseTopReferred = window[baseTopReference];
			
			var updateHeight = baseTopReferred * posAdjust;
					//console.log(updateHeight);
			$(this).css('top',updateHeight);
		});	

	$('div#StarGrid div.starWrap').each(function(index)
	{	
		var xPosAdjust = (imageWidth / baseWidth);
		var yPosAdjust = (imageHeight / baseHeight);
			// define reference variable upon array index pos.
			var baseStarPos = 'baseStar'+(index + 1 )+'Pos';
			var baseStarReferred = window[baseStarPos];
		// Set x and y coords from ref array
		var baseStarXReferred = baseStarReferred[0];
		var baseStarYReferred = baseStarReferred[1];
		//calculate new x and y pos.
		var addXPosition = (baseStarXReferred * xPosAdjust);
		var addYPosition = (baseStarYReferred * yPosAdjust);
		// Add to current item
		$(this).css('left', addXPosition);
		$(this).css('top', addYPosition);
	});
	

	
	//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());
		//console.log('contentheight');
	}
	*/
}

function expandArea()
{
	contentExpanded = true;
	
	var container = $('div#Content');
	container.addClass('expanded');
	
	var expand = container.find('div#ContentGrid div.textArea div.expandArea');
	
	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()
		{
			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);
		
		//$.get('../content/gallery.txt', function(data)
		//$.get('gallery.txt', function(data)
		//$.get('/Controls/Plugins/WorldHotels/GalleryImages.ashx?hotel=Lux11', function(data)
		$.get('/Handlers/GalleryImages.ashx?GalleryName=Lux11', function(data)		
		
		{
			var galleryContent = myGallery.find('div.imageArea');
			var selectCategory = $.trim(myGallery.find('div.sliderConfig').text());
			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('_');
				
				
				if (selectCategory && selectCategory != categoryName)
				{
					return true;
				}
				
				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> ');
				thisCategory.after('<div id="GalleryNav"><div id="NavWrap"></div><div class="clear">&nbsp;</div></div>');

				
				$(this).find('image').each(function()
				{
					var url = '/' + $(this).text();
					//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"><img src="' + largeUrl + '" /></div>');
					//thisCategory.append('<div class="slide"><a href="' + largeUrl + '" rel="shadowbox['+ galleryName + ']"><img src="' + largeUrl + '" /></a></div>');
					
					var imgAr = thisCategory.parent().find('div#GalleryNav div#NavWrap');
					imgAr.append('<div class="galleryNavItem">&nbsp;</div>');
					//console.log(imgAr);					
				});
				
				
				/*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;
					});
					
				});*/
				var imgAreaWidth = thisCategory.parent().width();
				var addedOffset = (imgAreaWidth - whGallerySlide) / 2;
				
				
				if($('div.slide').length > 1){
				// Move last divs to front
				$('div.slide:first', thisCategory).before($('div.slide:last', thisCategory));
				$('div.slide:first', thisCategory).before($('div.slide:last', thisCategory));
				//console.log('moved last to front');
				
				//thisCategory.width(9999);
				thisCategory.width($(this).find('image').length * whGallerySlide );
				thisCategory.append('<div class="clear">&nbsp;</div>');
								//var navItemCount = thisCategory.find('div#GalleryNav div.galleryNavItem').length();
				//var navItemWidth = thisCategory.find('div#GalleryNav div.galleryNavItem').outerWidth(true);
				thisCategory.parent().find('div#GalleryNav div#NavWrap').width($(this).find('image').length * 16);
				
				
				var number = $(this).find('image').length;
				var even = number%2;
				if (even == 0) 
				{
									//console.log('its even'); 	
					whGalleryOffset = (-(thisCategory.width() / 2)) + addedOffset;
				}
				else
				{
									//console.log('its uneven'); 
					whGalleryOffset = (-(thisCategory.width() / 2)) + addedOffset + (whGallerySlide / 2 );
				}
				

				//console.log(addedOffset);
				//imgAreaWidth = ((imgAreaWidth - 200) / 2) / 2;
				//console.log(imgAreaWidth);
				//whGalleryOffset = (-(thisCategory.width() / 2)) + addedOffset;
				
				centerImgIndex = ($(this).find('image').length / 2);
					if((parseFloat(centerImgIndex) == parseInt(centerImgIndex)) && !isNaN(centerImgIndex)){
						 //console.log('is integer');
					  } else { 
						 //console.log('not integer, convert');
						  centerImgIndex = parseInt(centerImgIndex);
						  centerImgIndex = centerImgIndex;
					  }
				//console.log(centerImgIndex);
				
				var currentNavItem = thisCategory.parent().find('div.galleryNavItem:eq('+ centerImgIndex +')');		
				//console.log(currentNavItem);
				currentNavItem.addClass('active');
				} else if($('div.slide').length == 1) {
					$('div.scroller').hide();
					$('div.slide').css('margin-left',addedOffset);
				}
			});
			
			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').hover(
					function() {
						$(this).addClass('leftScrollHover');
					}
					, 
					function() {
						$(this).removeClass('leftScrollHover');
					}
				);
				
				gallery.find('div.rightScroll').hover(
					function() {
						$(this).addClass('rightScrollHover');
					}
					, 
					function() {
						$(this).removeClass('rightScrollHover');
					}
				);
								
				gallery.find('div.leftScroll').click(function(event)
				{
					if (!event.detail || event.detail==1) 
						{//activate on first click only; prevent double clickers	
							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(event)
				{
					if (!event.detail || event.detail==1) 
						{//activate on first click only; prevent double clickers	
							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'));
		var activeGallItem = thisGallery.find('div#GalleryNav div.active');
		var firstGallItem = thisGallery.find('div#GalleryNav div.galleryNavItem:first');
		var lastGallItem = thisGallery.find('div#GalleryNav div.galleryNavItem:last');
		//console.log(activeGallItem);
		activeGallItem.removeClass('active');
		

		if (dir == 'right')
		{
			galleryContent.attr('posX', x - whGallerySlide);
			galleryContent.attr('posXLarge', xLarge - whGallerySlideLarge);
			if (activeGallItem.next('div.galleryNavItem').length > 0)
				{
					activeGallItem.next().addClass('active');
				}
				else
				{
					firstGallItem.addClass('active');
				}
		}
		else
		{
			galleryContent.attr('posX', x + whGallerySlide);
			galleryContent.attr('posXLarge', xLarge + whGallerySlideLarge);
			if (activeGallItem.prev('div.galleryNavItem').length > 0)
				{
					activeGallItem.prev().addClass('active');
				}
				else
				{
					lastGallItem.addClass('active');
				}
		}
		
		galleryContent.stop();
		
		var newPosX = 0;
		if (contentExpanded == true)
		{
			newPosX = galleryContent.attr('posXLarge');
		}
		else
		{
			newPosX = galleryContent.attr('posX');
		}
		
		galleryContent.animate({left: newPosX + 'px'}, 250,
		            // Added callback function in animation. Take (upon direction) last slide and put first or vice versa in div.slide order; set offset back
					function()
					{	
						if (dir == 'right')	
							{
								$('div.slide:last', thisCategory).after($('div.slide:first', thisCategory));
								thisCategory.css({'left' : whGalleryOffset});
								thisCategory.attr('posX', whGalleryOffset);
								thisCategory.attr('posXLarge', whGalleryOffset);
							}
						else 
							{
								$('div.slide:first', thisCategory).before($('div.slide:last', thisCategory));
								thisCategory.css({'left' : whGalleryOffset});
								thisCategory.attr('posX', whGalleryOffset);
								thisCategory.attr('posXLarge', whGalleryOffset);
							}
					}
				);
	}
	
	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.css('left', categories.attr('posX'));
		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
}

// 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();
	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 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')
		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;

	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#Generated').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("id", 'Generated');
	form.setAttribute("method", method);
	form.setAttribute("action", path);
	form.setAttribute("target", "_blank");

	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);
	}
	
	_gaq.push(function()
	{
		var pageTracker = _gat._getTrackerByName();
		window.open(pageTracker._getLinkerUrl(path + urlParams));
	});
}

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();

	//Children
	var children = parseInt(myreservation.find('div.children 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.accountID').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,
		'lng': language
	};
	
	if (checkOut && checkOut != 'Check-out')
	{
		params["departureDate"] = calDepartureDateField;
	}
	if (rateAccessCode && rateAccessCode != 'Code')
	{
		params["rateAccessCode"] = rateAccessCode;
	}
	if (accountID && accountID != 'ID')
	{
		params["iataNumber"] = accountID;
	}
	if (children > 0)
	{
		params["children"] = children;
	}
	
	//Children fields here...
	
	// MOBILE FIX FOR BOOKING
	// REMOVE AFTER MOBILE SITES GO LIVE
	if(devicIseMobile()){
		window.open('https://www.trustinternational.com/mb/WH/2B?LANGUAGE=en&i=HABERLUX&property=TXL-WW-HABERLUX');
	} 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
	
	//_gaq.push(['_link', 'https://www.yourreservation.net/ibe/' + IBFname + '/main.html']);
	
	return false;	
}

//Music system
function useMusic()
{

	//if (navigator.userAgent.match(/MSIE 6.0/i) != null || navigator.userAgent.match(/MSIE 7.0/i) != null || navigator.userAgent.match(/MSIE 8.0/i) != null)
	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);
			
			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');

	var frameSize = 1;

	content.height($(window).height() - frameSize);
	music.height(frameSize);
}

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;
    }
}
