// CLEAR TEXT FROM FORM FIELDS

function addFormClear(id, defaultText) {	
	var el = document.getElementById(id);
	if (!el) {
		return;
	}
	if (el.value == '' || el.value == defaultText) {	
		el.value = defaultText;
		el.onfocus = function() {
			if (el.value == defaultText) {
				el.value = '';
			}
		}
		el.onblur = function() {
			if (el.value == '') {			
				el.value = defaultText;
			}
		}
	}
	var parent = el.parentNode
	while (parent != null) {
		if (parent.tagName == 'FORM') {
			parent.onsubmit = function() {
				if (el.value == defaultText) {
					el.value = '';
				}
			}
			break;
		}
		parent = parent.parentNode;
	}
}

// =================================================================

// SEARCH FORM CLEAR

function searchFormClear(){
	if (!document.getElementById('search')) return;
	addFormClear('search', $('#headerSearch label').text());
}

// =================================================================

// NEWSLETTER SIDEBAR FORM

function newsletterForm(){
	
	if (!$('#newsletterSidebar')) return;
	
	var newsletterSidebar = $('#newsletterSidebar');
	
	// validate
	newsletterSidebar.onsubmit = function() {
	
		var email = $('#newsletterEmail').val();
		var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		
		if (!email || email == 'Your Email Address') {
    		alert($.i18n._('Your email address is required'));
    		return false;
	    } else if (!filter.test(email)) {
	    	alert($.i18n._('Your email address is not valid'));
	    	return false;
	    }
	}
}

// =================================================================

// DATE PICKER
function datePicker() {
	if (!$('#bookArrival')) return;
	if (!$('#bookDeparture')) return;

	// Main Booking Form
	if(document.getElementById('bookForm')){
		$('#bookArrival').datepicker(
			{
				showOn: "both", 
	   			buttonImage: "/images/icons/calendar.gif", 
				buttonImageOnly: true,
				minDate: new Date(),
				maxDate: '+3y',
				dateFormat: $.i18n.dateFormat
			}
		);
		
		$('#bookDeparture').datepicker(
			{
				showOn: "both", 
	   			buttonImage: "/images/icons/calendar.gif", 
				buttonImageOnly: true,
				minDate: '+1d',
				maxDate: '+3y',
				dateFormat: $.i18n.dateFormat
			}
		);
	// Homepage booking form
	} else if(document.getElementById('bookSidebar') && document.getElementById('wrapperHome')) {
		$('#bookArrival').datepicker(
			{
				showOn: "both", 
	   			buttonImage: "/images/icons/calendar.gif", 
				buttonImageOnly: true,
				minDate: new Date(),
				maxDate: '+3y',
				dateFormat: $.i18n.dateFormat
			}
		);
		
		$('#bookDeparture').datepicker(
			{
				showOn: "both", 
	   			buttonImage: "/images/icons/calendar.gif", 
				buttonImageOnly: true,
				minDate: '+1d',
				maxDate: '+3y',
				dateFormat: $.i18n.dateFormat
			}
		);
	// Sidebar booking form
	} else if(document.getElementById('bookSidebar')) {
		$('#bookArrival').datepicker(
			{
				showOn: "both", 
	   			buttonImage: "/images/icons/calendar-small.gif", 
				buttonImageOnly: true,
				minDate: new Date(),
				maxDate: '+3y',
				dateFormat: $.i18n.dateFormat
			}
		);
		
		$('#bookDeparture').datepicker(
			{
				showOn: "both", 
	   			buttonImage: "/images/icons/calendar-small.gif", 
				buttonImageOnly: true,
				minDate: '+1d',
				maxDate: '+3y',
				dateFormat: $.i18n.dateFormat
			}
		);
	}
}

// =================================================================

// BOOKING FORM
function bookingForm() {
	if (!$('bookHotel')) return;
	if (!$('bookArrival')) return;
	if (!$('bookDeparture')) return;
	if (!$('bookNights')) return;
	
	function updateNights() {
		var arrivalDate = $('#bookArrival').datepicker('getDate');
		var departureDate = $('#bookDeparture').datepicker('getDate');
		var nights = $('#bookNights').val();
		var dateDifference = Math.round((departureDate - arrivalDate) / 86400000);
		
		if(dateDifference <= 20){
			$("p.error").remove();
			$('#bookDeparture').parent().removeClass('error');
			$('#bookNights').attr('value', dateDifference);
		} else {
			$('<p class="error">' + $.i18n._('For a stay of more than 20 days, please contact us on %s.', ['+44 (0)844 824 6171']) + '</p>').insertBefore('#bookHotelLabel');
			$('#bookDeparture').parent().addClass('error');
			var newDate = new Date(arrivalDate);
			newDate.setDate(newDate.getDate() + 20);
			$('#bookDeparture').datepicker("disable");
			$('#bookDeparture').datepicker('setDate', newDate);
			$('#bookDeparture').datepicker("enable");
			$('#bookNights').attr('value', 20);
		}
	}

	$('#bookArrival').change(function() {
		// make sure dept is after this date
		var arrivalDate = $('#bookArrival').datepicker('getDate');
		var departureDate = $('#bookDeparture').datepicker('getDate');
		if (departureDate.getTime() <= arrivalDate.getTime()) {
			var newDate = new Date(arrivalDate);
			newDate.setDate(newDate.getDate() + 1);
			$('#bookDeparture').datepicker("disable");
			$('#bookDeparture').datepicker('setDate', newDate);
			$('#bookDeparture').datepicker("enable");
		}
		
		// update nights
		updateNights();
	});
	$('#bookDeparture').change(function() {
		// make sure arrival is before this date
		var arrivalDate = $('#bookArrival').datepicker('getDate');
		var departureDate = $('#bookDeparture').datepicker('getDate');
		if (arrivalDate >= departureDate) {
			var newDate = new Date(departureDate);
			newDate.setDate(newDate.getDate() - 1);
			$('#bookArrival').datepicker("disable");
			$('#bookArrival').datepicker('setDate', newDate);
			$('#bookArrival').datepicker("enable");
		}
		
		// update nights
		updateNights();
	});
	$('#bookNights').change(function() {
		// update dept
		var arrivalDate = $('#bookArrival').datepicker('getDate');
		var departureDate = $('#bookDeparture').datepicker('getDate');
		var newDate = new Date(arrivalDate);
		var days = parseInt($(this).val());
		newDate.setDate(newDate.getDate() + days);
		$('#bookDeparture').datepicker("disable");
		$('#bookDeparture').datepicker('setDate', newDate);
		$('#bookDeparture').datepicker("enable");
	});
		
	
	// booking validation
	$('#bookSidebar, #bookForm').submit(function(event){
		$('#mainContent .section p.required').before('<p id="bookFormError"></p>');
		if($('#bookHotel').val() == ''){
			$('#bookSidebar *, #bookForm *').removeClass('error');
			$('#bookSidebar p:eq(0), #bookFormError').text($.i18n._('Please select a hotel.'));
			$('#bookHotelLabel, #bookHotel, #bookSidebar p:eq(0), #bookFormError, #bookForm div:eq(0)').addClass('error');
			event.preventDefault();
			return false;
		}
		if($('#bookArrival').val() == ''){
			$('#bookSidebar *, #bookForm *').removeClass('error');
			$('#bookSidebar p:eq(0), #bookFormError').text($.i18n._('Please select an arrival date.'));
			$('#bookSidebar div.col50:eq(0), #bookForm div.alt:eq(0), #bookSidebar p, #bookFormError').addClass('error');
			event.preventDefault();
			return false;
		}
		if($('#bookDeparture').val() == ''){
			$('#bookSidebar *, #bookForm *').removeClass('error');
			$('#bookSidebar p:eq(0), #bookFormError').text($.i18n._('Please select a departure date.'));
			$('#bookSidebar div.col50:eq(0), #bookForm div:eq(2), #bookSidebar p:eq(0), #bookFormError').addClass('error');
			event.preventDefault();
			return false;
		}
		
		// add Oakley Court room validation - not more than 4
		if($('#bookHotel').val() == '18263' && $('#bookRooms').val() > '4'){
			$('#bookSidebar *, #bookForm *').removeClass('error');
			$('#bookSidebar p:eq(0), #bookFormError').text($.i18n._('To book more than 4 rooms please contact the hotel directly on +44 (0) 1753 609 988.'));
			$('#bookSidebar div.col33:eq(1),  #bookSidebar p:eq(0), #bookFormError').addClass('error');
			event.preventDefault();
			return false;
		}
	
		// track link
		pageTracker._linkByPost(this);
	});
}


// =================================================================

// VENUES - HOTELS OVERLAY
function venuesHotelsOverlay() {
	
	if (!$('#hotelFinder')) return;
	if (!$('#mainNav')) return;
		
	var hotelFinderMap = $('#hotelFinderMap');
	var hotelFinderList = $('#hotelFinderList');
	
	var isHotel = false;

	var CLOSE_DELAY = 500; // ms before closing	
	
	hotelFinderMap.hide();
	
	var closeInterval;
	
	// get x pos from nav item
	$.fn.x = function(n) {
		var result = null;
		this.each(function() {
			var o = this;
			if (n === undefined) {
				var x = 0;
				if (o.offsetParent) {
					while (o.offsetParent) {
						x += o.offsetLeft;
						o = o.offsetParent;
					}
				}
				if (result === null) {
					result = x;
				} else {
					result = Math.min(result, x);
				}
			} else {
				o.style.left = n + 'px';
			}
		});
	return result;
	};
	
	// IE6 sniffing - http://www.thefutureoftheweb.com/blog/detect-ie6-in-javascript
	var ie6 = false /*@cc_on || @_jscript_version < 5.7 @*/;
	
	// IE6 insert/remove iframe
	var insertIframe = function() {
		if(document.getElementById('hotelFinder')) {
			var iframe = document.createElement('iframe');
			iframe.src = '';
			iframe.width = '550';
			iframe.height = '400';
			iframe.frameborder = false;
			iframe.id = 'ieHotelFinder';
			iframe.name = 'ieHotelFinder';
			document.body.appendChild(iframe);
			//if($('#mainNav li.last').x() != null) {
				$('#ieHotelFinder').x($('#mainNav li.last').x() - 550 + $('#mainNav li.last').outerWidth());
			//} else {
				//$('#ieHotelFinder').x(411);
			//}
		}
	}
	
	$(window).resize(function() {
	  $('#ieHotelFinder').x($('#mainNav li.last').x() - 550 + $('#mainNav li.last').outerWidth());
	});
	
	var hideIframe = function() {
		$("#ieHotelFinder").css("display", "none");
	}
	var showIframe = function() {
		$("#ieHotelFinder").css("display", "block");
	}
	
	if(ie6 == true){
		insertIframe();
		hideIframe();
	}

	
	var closeOverlay = function() {
		clearInterval(closeInterval);
		$('#hotelFinder').fadeOut("slow");
		$('#mainNav li.last').removeClass("hoverFinder");
		if(ie6 == true){hideIframe();}
	}
	
	// show/hide hotelFinder all non-hotel pages
	$('#mainNav li.last a').hover(
		function() {
			clearInterval(closeInterval);
			// add class if it's meant to be active, i.e. non-hotel pages
			if($('#mainNav li.last').hasClass("active")) {
				isHotel = true;
			} else {
				isHotel = false;
			}			
			$('#hotelFinder').x($('#mainNav li.last').x() - 550 + $('#mainNav li.last').outerWidth());
			$('#hotelFinder').fadeIn("slow");
			if(ie6 == true){
				showIframe();
				//$('#hotelFinder').x($('#mainNav li.last').x() +1);
				//$('#ieHotelFinder').x($('#mainNav li.last').x() +1);
			}
		},
		function() {
			closeInterval = setInterval(closeOverlay, CLOSE_DELAY);
		}
	);
	
	$('#hotelFinder').hover(
		function() {
			clearInterval(closeInterval);
			$('#mainNav li.last').addClass("hoverFinder");
		},
		function() {
			closeInterval = setInterval(closeOverlay, CLOSE_DELAY);
		}
	);	
	
	$('#hotelFinderClose a').click(function(event){
		$('#hotelFinder').fadeOut("slow");	
		$('#mainNav li.last').removeClass("active");
		closeInterval = setInterval(closeOverlay, CLOSE_DELAY);
 		event.preventDefault();
	});
	
	// show/hide content
	$('#hotelFinderMapView a').click(function(event){
		hotelFinderList.fadeOut("slow");
		hotelFinderMap.fadeIn("slow");
 		event.preventDefault();
	});
	$('#hotelFinderListView a').click(function(event){
		hotelFinderMap.fadeOut("slow");
		hotelFinderList.fadeIn("slow");
 		event.preventDefault();
	});
}


// =================================================================

// FLASH MAP - HOTELLIST SWITCH
function flashMapSwitch() {
	if (!document.getElementById('mapView')) return;
	if (!document.getElementById('listView')) return;
	if (!document.getElementById('tabsMapList')) return;
	

	// not needed anymore as list view is one page now
	if(window.location.search.substring(1).indexOf('pageNo') != -1){
		$('#mapView').hide();
		$('#tabsMapList li:eq(1)').addClass("ui-tabs-active");
		$('#tabsMapList li:eq(0)').removeClass("ui-tabs-active");
	} else {
		$('#listView').hide();
		$('#tabsMapList li:eq(0)').addClass("ui-tabs-active");
		$('#tabsMapList li:eq(1)').removeClass("ui-tabs-active");
	}
	
	// show/hide content
	$('#tabsMapList a:eq(0)').click(function(event){
		$('#listView').hide();
		$('#mapView').fadeIn("slow");
		$('#tabsMapList li:eq(0)').addClass("ui-tabs-active");
		$('#tabsMapList li:eq(1)').removeClass("ui-tabs-active");
 		event.preventDefault();
	});
	$('#tabsMapList a:eq(1)').click(function(event){
		$('#mapView').hide();
		$('#listView').fadeIn("slow");
		$('#tabsMapList li:eq(1)').addClass("ui-tabs-active");
		$('#tabsMapList li:eq(0)').removeClass("ui-tabs-active");
 		event.preventDefault();
	});
}


// =================================================================

// TABBED SECTIONS - TAB SWITCH
function featuredTabSwitch() {
	if (!$('.featuredSection')) return;
	if (!$('#featuredNav')) return;
	if (!$('#tab1')) return;
	
	if ($('#tab2')){
		$('#tab2').hide();
	}
	
	if ($('#tab3')){
		$('#tab3').hide();
	}
	
	$('#featuredNav li:eq(0)').addClass("active");
	
	// show/hide content
	
	$('#featuredNav a:eq(0)').click(function(event){
		if ($('#tab2')){$('#tab2').hide();}
		if ($('#tab3')){$('#tab3').hide();}
		$('#tab1').fadeIn("fast");
		$('#featuredNav li:eq(0)').addClass("active");
		if ($('#featuredNav li:eq(1)')){$('#featuredNav li:eq(1)').removeClass("active");}
		if ($('#featuredNav li:eq(2)')){$('#featuredNav li:eq(2)').removeClass("active");}
 		event.preventDefault();
	});
	
	if($('#featuredNav li:eq(1)')){
		$('#featuredNav a:eq(1)').click(function(event){
			if ($('#tab1')){$('#tab1').hide();}
			if ($('#tab3')){$('#tab3').hide();}
			$('#tab2').fadeIn("fast");
			$('#featuredNav li:eq(1)').addClass("active");
			if ($('#featuredNav li:eq(0)')){$('#featuredNav li:eq(0)').removeClass("active");}
			if ($('#featuredNav li:eq(2)')){$('#featuredNav li:eq(2)').removeClass("active");}
	 		event.preventDefault();
		});
	}
	
	if($('#featuredNav li:eq(2)')){
		$('#featuredNav a:eq(2)').click(function(event){
			if ($('#tab1')){$('#tab1').hide();}
			if ($('#tab2')){$('#tab2').hide();}
			$('#tab3').fadeIn("fast");
			$('#featuredNav li:eq(2)').addClass("active");
			if ($('#featuredNav li:eq(0)')){$('#featuredNav li:eq(0)').removeClass("active");}
			if ($('#featuredNav li:eq(1)')){$('#featuredNav li:eq(1)').removeClass("active");}
	 		event.preventDefault();
		});
	}
}


// MAPS FILTER TABS
function mapsFilterSwitch() {
	if (!$('#section-1')) return;
	
	if ($('#section-2')){
		$('#section-2').hide();
	}
	
	if ($('#section-3')){
		$('#section-3').hide();
	}
	
	$('#tabsMapFilters a:eq(0)').addClass("active");
	
	// show/hide content
	
	$('#tabsMapFilters a:eq(0)').click(function(event){
		if ($('#section-2')){$('#section-2').hide();}
		if ($('#section-3')){$('#section-3').hide();}
		$('#section-1').fadeIn("fast");
		$('#tabsMapFilters a:eq(0)').addClass("active");
		if ($('#tabsMapFilters a:eq(1)')){$('#tabsMapFilters a:eq(1)').removeClass("active");}
		if ($('#tabsMapFilters a:eq(2)')){$('#tabsMapFilters a:eq(2)').removeClass("active");}
 		event.preventDefault();
	});
	
	if($('#tabsMapFilters li:eq(1)')){
		$('#tabsMapFilters a:eq(1)').click(function(event){
			if ($('#section-1')){$('#section-1').hide();}
			if ($('#section-3')){$('#section-3').hide();}
			$('#section-2').fadeIn("fast");
			$('#tabsMapFilters a:eq(1)').addClass("active");
			if ($('#tabsMapFilters a:eq(0)')){$('#tabsMapFilters a:eq(0)').removeClass("active");}
			if ($('#tabsMapFilters a:eq(2)')){$('#tabsMapFilters a:eq(2)').removeClass("active");}
	 		event.preventDefault();
		});
	}
	
	if($('#tabsMapFilters li:eq(2)')){
		$('#tabsMapFilters a:eq(2)').click(function(event){
			if ($('#section-1')){$('#section-1').hide();}
			if ($('#section-2')){$('#section-2').hide();}
			$('#section-3').fadeIn("fast");
			$('#tabsMapFilters a:eq(2)').addClass("active");
			if ($('#tabsMapFilters a:eq(0)')){$('#tabsMapFilters a:eq(0)').removeClass("active");}
			if ($('#tabsMapFilters a:eq(1)')){$('#tabsMapFilters a:eq(1)').removeClass("active");}
	 		event.preventDefault();
		});
	}
}

// =================================================================

// REGISTER FORM - SHOW/HIDE "How did you hear... - Other" FIELD
function showHideHowAboutOther() {
	// used on various forms so just checking for fields themselves
	if(!document.getElementById('hearAbout')) return;
	if(!document.getElementById('hearAboutOtherContainer')) return;
	
	$('#hearAboutOtherContainer').hide();
	
	$('#hearAbout').change(function(){
		if($('#hearAbout option:selected').attr('value') == 'Other'){
			$('#hearAboutOtherContainer').show();
		} else {
			$('#hearAboutOtherContainer').hide();
		}
	});
}

function updateOccupancy() {
	var roomCount = $('#bookRooms').val();
	var adultCount = roomCount * 2;
	var optionsAdults = '';
	var optionsChildren = '';
	for (var i=0; i<adultCount; i++) {
		var val = i + 1;
		optionsAdults += '<option value="' + (i + 1) + '">' + (i + 1) + '</option>';
		optionsChildren += '<option value="' + i + '">' + i + '</option>';
	}
	// add extra number to children since that dropdown starts at 0
	optionsChildren += '<option value="' + adultCount + '">' + adultCount + '</option>';
	
	var currentAdults = $('#bookAdults').val();
	var currentChildren = $('#bookChildren').val();
	$('#bookAdults').html(optionsAdults);
	$('#bookAdults').val(currentAdults);
	$('#bookChildren').html(optionsChildren);
	$('#bookChildren').val(currentChildren);
}

// add load events
$(searchFormClear);
$(venuesHotelsOverlay);
$(datePicker);
$(bookingForm);
$(newsletterForm);
$(flashMapSwitch);
$(featuredTabSwitch);
$(showHideHowAboutOther);
$(function() {
    updateOccupancy();
    $('#bookRooms').change(updateOccupancy);
});


// EXTERNAL LINKS
function externalLinks() {  
 if (!document.getElementsByTagName) return;  
 var anchors = document.getElementsByTagName("a");  
 for (var i=0; i<anchors.length; i++) {  
   var anchor = anchors[i];  
   if (anchor.getAttribute("href") &&  
       anchor.getAttribute("rel") == "external")  
     anchor.target = "_blank";  
 }  
}  
window.onload = externalLinks;

// REMOVE LINKS FOCUS

$(document).ready(function(){
	$('a').click(function(){
		$(this).blur();
	});
});