function changeNumber(country)
{
	var value = country.value;
	$('div#Tollfree div.countrySelect div.countryNr').text(value);
}

$(document).ready(function()
{
	// Backoffice check -------------------------------------------------------------------------
	if ($('div.controlBorder').length > 0)
		var backoffice = true;
	else
		var backoffice = false;
	
	
	// Cufon --------------------------------------------------------------------------
	Cufon.now();
	
	Cufon('div#Menu ul li a');
	Cufon('.mittelschrift');
	Cufon('h1');
	Cufon('h2');
	Cufon('h3');
	
	
	// Selectbox --------------------------------------------------------------------------
	$('div.reservation div.childrenPerRoom div.activeRooms').css('display','block');
	$('select').selectbox();
	$('div.reservation div.childrenPerRoom div.activeRooms').css('display','none');
	
	
	// LanguageSelect-----------------------------------------------------------------
	$('div#Language ul li').each(function()
	{
		$(this).find('a').html('');
		$(this).find('span').html('');	
	});
	
	
	// Menu --------------------------------------------------------------------------
	var hoverout;
	var activeHover;
	
	$('div#Menu > div > ul > li').mouseenter(function()
	{
		if (hoverout != null)
			clearTimeout(hoverout);
			
		if (activeHover != null)
			closeHover();
			
		$(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');
	}
	
	$('div#Menu div ul li ul li').mouseenter(function()
	{
		$(this).addClass('hover');
	});
	
	$('div#Menu div ul li ul li').mouseleave(function()
	{
		$(this).removeClass('hover');
	});
	
	var menuWidth = $('div#Menu').width();
	var homeWidth = $('div#Menu ul.home').width();
	var linksWidth = $('div#Menu ul:eq(1)').width();
	$('div#Menu ul.language').css('width', (menuWidth - homeWidth - linksWidth));
	
	
	// Booking engine --------------------------------------------------------------------------
	$('div.reservation').each(function(index)
	{
		var startDate = $(this).find('div.minDate span').text();
		var endDate = $(this).find('div.maxDate span').text();
		var minDays = $(this).find('div.minDays span').text();
		var rateAccessCode = $(this).find('div.accountID span').text();
		var activeID = $(this).find('div.activeID span').text();
		
		var hideDays = $(this).find('div.hideDays span').text().split(',');
		var daysToDisable = new Array();
		
		for (i = 0; i < hideDays.length; i++)
		{
			daysToDisable.push(parseInt(hideDays[i]));
		}
		
		var hotels = $(this).find('div.hotel select option').length;
		if (hotels > 1)
		{
			$(this).addClass('showHotels');
			$(this).find('div.hotel select').selectbox();
		}
		
		if (backoffice == true)
		{
			$(this).addClass('backoffice');
		}
		
		var bookFrom = $(this).find('.bookFrom');
		var bookTo = $(this).find('.bookTo');
		
		if (isNaN(parseInt(minDays)))
		{
			minDays = 1;
		}
		
		if (startDate == "" && endDate == "")
		{
			bookFromDate = "today";
			bookToDate = parseInt(minDays);
		}
		else if (startDate != "" && endDate == "")
		{
			startDate = startDate.split('-');
			bookFromDate = new Date(startDate[2], startDate[1] - 1, startDate[0]);
			
			bookToDate = new Date(startDate[2], startDate[1] - 1, startDate[0]);
			bookToDate.setDate(bookToDate.getDate() + parseInt(minDays));
		}
		else if (startDate == "" && endDate != "")
		{
			bookFromDate = "today";
			
			endDate = endDate.split('-');
			bookToDate = new Date(endDate[2], endDate[1] - 1, endDate[0]);
		}
		else if (startDate != "" && endDate != "")
		{
			startDate = startDate.split('-');
			bookFromDate = new Date(startDate[2], startDate[1] - 1, startDate[0]);
			
			endDate = endDate.split('-');
			bookToDate = new Date(endDate[2], endDate[1] - 1, endDate[0]);
		}
		
		if (activeID == 1 && rateAccessCode == '')
		{
			$(this).find('div.rates').addClass('showRates');
		}
		
		if (rateAccessCode != '')
		{
			$(this).find('input.accessCode').val(rateAccessCode);
		}
		
		var dates = $(this).find( ".bookFrom, .bookTo" ).datepicker({
			showOn: 'both',
			buttonImage: '/content/images/Date_Picker.jpg',
			minDate: 0,
			beforeShowDay: function( selectedDate ) {
				var day = selectedDate.getDay();
				for (i = 0; i < daysToDisable.length; i++) 
				{
					if ($.inArray(day, daysToDisable) != -1) 
					{
						return [false];
					}
				}
				return [true];
			},
			onSelect: function( selectedDate ) {
				var option = $(this).attr('class').replace(/\ hasDatepicker/gi, ''),
					instance = $( this ).data( "datepicker" );
					date = $.datepicker.parseDate(
						instance.settings.dateFormat ||
						$.datepicker._defaults.dateFormat,
						selectedDate, instance.settings );
				dates.not( this ).datepicker( "option", option, date);
			},
			onClose: function( selectedDate ) {
				if ($(this).hasClass('bookFrom') == true)
				{
					var newDate = new Date();
					newDate = bookFrom.datepicker("getDate");
					newDate.setDate(newDate.getDate() + parseInt(minDays));
					bookTo.datepicker("option", "minDate", newDate);
					bookTo.datepicker("show");
				}
			}
		});
		
		// Set dates
		bookFrom.datepicker("setDate", bookFromDate);
		bookTo.datepicker("setDate", bookToDate);
		
		// Align the selectboxes vertically to top or bottom, depending on available space
		if ($(this).parents('div#Content').length > 0)
		{
			var topPos = $(this).parent().position().top;
			var containerHeight = $('div#Content').height();
			var resHeight = $(this).outerHeight();
			
			$(this).find('div.jquery-selectbox-list').each(function()
			{
				$(this).parents('div.childrenPerRoom').addClass('selectActive');
				var listHeight = $(this).height();
				$(this).parents('div.childrenPerRoom').removeClass('selectActive');
				
				if ((resHeight + listHeight + topPos) > containerHeight)
				{
					$(this).addClass('topAlign');
				}
			});
		}
	});
	
	$('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.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();
        }
    }
	
	
	// Watermarks --------------------------------------------------------------------------
	$('div.reservation div.rates input.accountID').watermark('Account ID');
	$('div.reservation div.rates input.accessCode').watermark('Access code');
	
	
	// Flash image slider variables --------------------------------------------------------------------
	var activeCat = $('div.flashVars div.activeCategory span').text();
	var flashName = $('div.flashVars div.activeHotel span').text();
	
	if (flashName == '' || flashName == '[Label not set]')
	{
		flashName = 'Saltanat';
	}
		
	if (backoffice == true)
		$('div.flashVars').css('display','block');
	
	loadFlash();
	
	function loadFlash()
	{
		var flashvars = {};
		//flashvars.xmlUrl="/content/flash/xml/pbsr.xml";
		flashvars.xmlUrl= subsiteUrl + "/Controls/Plugins/WorldHotels/GalleryImages.ashx?hotel=" + flashName;
		flashvars.cssUrl="/content/flash/flash.css";
		flashvars.baseUrl="/";
		flashvars.category=0;
		flashvars.activeCategoryName=activeCat;
		
		var params = {};
		params.wmode = "transparent";
		
		var attributes = {};
		attributes.id = "PhotoFlow";
		attributes.name = "PhotoFlow";
		swfobject.embedSWF("/content/flash/photoFlow.swf", "FlashContent", "501", "226", "9.0.0", false, flashvars, params, attributes);
	}
	
	// Reservation ------------------------------------------------------------------------
	$('div.reservation div.button').click(function()
	{
		if ($(this).parent().hasClass('myResContent'))
		{
			return;
		}
		
		var currentPage = location.pathname;
		//pageTracker._trackPageview(currentPage + '/reservation-click/search');
		//_gaq.push(['_trackPageview', currentPage + '/reservation-click/search']);
		
		build_url( $(this).parents('div.reservation') );
		
		return false;
	});
	
	// Final scripts to execute ------------------------------------------------------------------------
	if ($('div.homeBlocksRow').length > 0)
	{
		$('div.homeBlocksRow').each(function()
		{
			resizeBlocks($(this));
		});
	}
	
});

// 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')
		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');
	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();
}

var enlargeDirection = 1;
var enlargeActive = null;
var enlargeCounter = 1;

function loadEnlargement(url, id)
{
	if (enlargeActive == id) return false;
	
	var container = $('div.mainImage');
	var slides = container.find('div.slide');
	
	if (slides.length == 0)
	{
		container.html('');
	}
	else
	{
		slides.stop();
	}
	
	if (container.find('div#' + id).length == 0)
	{
		var image = '<div id="' + id + '" class="slide">' + '<img src="' + url + '" alt="image" />' + '</div>';
		container.append(image);
	}
	
	var slide = container.find('div#' + id);
	slide.css('z-index', enlargeCounter);
	
	/*
	slide.css('left', -100);
	slide.css('top', -30);
	
	slide.animate({
		left: -100  - (100 * enlargeDirection),
		top: -30  - (30 * enlargeDirection)
	}, 5000, 'linear');
	
	enlargeDirection = enlargeDirection * -1;
	*/
	slide.hide();
	slide.fadeTo('slow', 1);
	
	enlargeActive = id;
	enlargeCounter++;
}

/* Google Maps Snippet
-----------------------------------------------------------------------*/
var mapName;
var getAddress;
var getGeocode;
var geocode;
var address;

function displayMap(inMap, inAddress, inGeocode) 
{		 
	mapName = $("div#" + inMap);
	
	getAddress = $("span#" + inAddress);	
	getGeocode = $("span#" + inGeocode);	
		
	address = getAddress.text();
	address = $.trim(address);
	
	geocode = getGeocode.text();
	geocode = $.trim(geocode);
		
	if(geocode != "")
	{
		geocode = geocode.split(",");
		
		lat = geocode[0];
		lng = geocode[1];
				
		geocode = new google.maps.LatLng(lat, lng);
		
		createMap(geocode);
	}
	else
	{
		calculateGeocode(address);	
	}					
}    

function calculateGeocode(address) 
{	
	geocoder = new google.maps.Geocoder();	
	geocoder.geocode( { 'address': address}, function(results, status) 
	{
		if (status == google.maps.GeocoderStatus.OK) 
		{					
			var latlng = results[0].geometry.location;			
			createMap(latlng);
		} 
		else 
		{			
			alert("Geocode was not successful for the following reason: " + status);			
		}
	});
}

function createMap(latlng) 
{	
	var myOptions = 
	{    
		zoom: 13,
		center: latlng,      
		mapTypeId: google.maps.MapTypeId.ROADMAP     
	};     
	
	var map = new google.maps.Map(mapName.get(0), myOptions);  
	
	var marker = new google.maps.Marker({       
		position: latlng,     
		map: map   
	});   
	
	var contentString = '<span><strong>Address:</strong></span><br /><span>' + address.split(",", 1)[0] + "<br \>" + address.substr(address.split(",", 1)[0].length + 2, address.length) + '</span>';  
	
	var infowindow = new google.maps.InfoWindow({     
		content: contentString 
	});  
	
	infowindow.open(map,marker); 
}

function resizeBlocks(target)
{
	var newHeight = 0;
	
	target.find('div.contents').each(function()
	{
		if ($(this).height() > newHeight)
		{
			newHeight = $(this).height();
		}
	});
	
	target.find('div.contents').height(newHeight);
}
