jQuery.fn.fadeToggle = function(speed, easing, callback) {
	return this.animate({opacity: 'toggle'}, speed, easing, callback);
};

// ignore any firebug log calls in non firebug browsers
if (typeof console === 'undefined') console = {log: function(){}};

function OpenWin(u,n,w,h,s)
{
	var l = (screen.width)  ? (screen.width  - w)/2 : 0;
	var t = (screen.height) ? (screen.height - h)/2 : 0;
	var p = window.open(u,n,'width='+w+',height='+h+',scrollbars='+s+',left='+l+',top='+t+',resizable');
	p.focus();
}

FancyLabels = {
	labels: {},
	selector: '.fancylabel[title]',
	init: function() {
		$(FancyLabels.selector).each(function(){
			FancyLabels.labels[this.id] = this.title;
			this.title = '';
		}).bind('blur', FancyLabels.trigger).bind('focus', FancyLabels.trigger).trigger('blur');

		$('button[type=submit],input[type=submit]').bind('click',FancyLabels.clear);
	},

	triggerAll: function() {
		for (var id in FancyLabels.labels) {
			$('#'+id).trigger('blur');
		}
	},

	trigger: function(e) {
		if (this.value == '' && (e.type == 'blur' || e.type != 'focus')) { // deal with initial load of fancylabels, as well as blur events
			this.value = FancyLabels.labels[this.id];
			$(this).addClass('inputlabel');
		} else if (this.value == FancyLabels.labels[this.id] && e.type == 'focus') {
			this.value = '';
			$(this).removeClass('inputlabel');
		}
	},

	clear: function() {
		for (var id in FancyLabels.labels) {
			if ($('#'+id).val() == FancyLabels.labels[id])
				$('#'+id).val('');
		}
	}
};

Global = $.extend(Global, {

	fancyLabels: [],
	ie6: false,

	init: function() {

		$(document).ready(function() {

			FancyLabels.init();

			$('a.print-btn').click(function() { window.print(); });

			// Travelmood Booking Path Progress Indicator
			Global.progressIndicator();

			$('#accom-flights-add-dest button').bind('click', function() {
				$('#accom-flights-add-dest').hide();
				$('#acomm-flights-single').hide();
				$('#acomm-flights-twin').show();
			});

			// fire off other init methods as required
			if ($('#searchPanel').length == 1) SearchPanel.init();


			//init funtions
			Global.overlays();
			HomePage.init();


			// payment page logic
			$('a.securityNumber').click(function(){ $('#hiddenSecurityNumber').toggle(); return false;});

			
			if ($('a.via-cluetip').length > 0)
				$('a.via-cluetip').cluetip({splitTitle: '|', onShow: function(ct, c){ $(ct).css('width', 'auto'); $(ct).slice(0,5).children().css('width', $(ct).width() ); return true;}});
		});
	},
	progressIndicator: function(){
		$('ul#progressTracker li:last-child').css('width', '128px');
		$('ul#progressTracker li:last-child span').css({
			'background-image': 'none',
			'padding-right': '10px'
		});
		$('ul#progressTracker li.booking_tab_selected').prev().find('span:first-child').eq(0).css({
			'background-image': "url('" + Global.url + '/themes/' + Global.theme + "/images/backgrounds/progress/chevron_back.gif')"
		});
	},
	overlays: function() {
		var common = {
				expose: {color: '#000', opacity: 0.5},
				close: 'a.overlay-close',
				onBeforeLoad: function() { if (Global.ie6) $('select').css('visibility','hidden');},
				onClose:function() { if (Global.ie6) $('select').css('visibility','visible');}
		}
		$("a.overlay").overlay(common);
		$('a[target=#overlay-holder], a[rel=#overlay-holder]').overlay($.extend(common,{
			onBeforeLoad: function(){
				// empty the h2 in there
				$('#overlay-holder h2').html(this.getTrigger().text()).get(0).id = '';
		        // grab wrapper element inside content
		        var wrap = this.getContent().find("div.content");
		        var load = this.getTrigger().attr("href") + ' div#wrapper';
		        wrap.load(load);
		        if (Global.ie6) $('select').css('visibility','hidden');
			}
		}));

	}
});


SearchPanel = {
	init: function() {

		// hook in to 'new search' button if present
		var newsearch = $("#newsearch-link");
		var toggleFn = function(){
			$("#newsearch-link").parent().toggle();
			$("#searchcontainer").toggle();
		}

		if (newsearch.length == 1) {
			$('#searchPanel h2:first').wrapInner('<a href="#"></a>').find('a').click(toggleFn);
			newsearch.click(toggleFn);
		}

		var searchType = Global.requiredSearchType || $("#searchPanelSearchType").val();
		var searchTypeIndex = 0;
		if (searchType != '') {
			switch (searchType) {
				case 'RF':
				case 'OF':
				case 'MF':
					searchTypeIndex = 1;
					break;
				case 'AO':
					searchTypeIndex = 2;
					break;
			}
		}

		//$("#searchPanel .accordion").tabs("#searchPanel .accordion div.pane", {
		//	tabs: 'h4',
		//	effect: 'slide',
		//	current: 'open',
		//	initialIndex: searchTypeIndex
		//});

		// Form Submission and Validation
		$('#searchPanel form').bind('submit', function() {
			
			var formSearchType = $(this).attr('id');

			if(formSearchType != 'searchFlight'){
			//	Validate Hotels
				if( Search.validateHotel(this) ) {
					SearchPanel.formWaiting();
					return true;
				}
			}
			else{
			//  Validate Flights
				if( Search.validateFlight(this) ) {
					SearchPanel.formWaiting();
					return true;
				}
			}
			return false;
		});

		SearchPanel.inits.singleCenter();
		SearchPanel.inits.accomOnly();
		SearchPanel.inits.flightOnly();

	},
	// Waiting animation
	formWaiting: function(){
		console.log('waiting');
		$('#page div.main.col').animate({	opacity: 0 }, 250, function() {
			$(this).empty().append("<div id='loading'></div>");
			$('#page div.main.col').animate({ opacity: 1 }, 250);
		});

	},
	inits: {
		singleCenter: function () {
			$('#SCdestinationRegionList').bind('change', SearchPanel.onChangeDestinationRegion).trigger('change');

			$('#SCdestinationRegionResortList').bind('change', SearchPanel.onChangeDestinationRegionResort);

			$('#SCdeparturePointList').bind('change', SearchPanelAirportList);
			
			$('#SCrooms').bind('change', function() {
				var el = $(this);
				var n = parseInt(el.val());
				el.closest('form').find('table.passengers tbody tr').show().slice(n).hide()
			}).trigger('change');

			$('form#searchSC .psg-under2').bind('change', function() {
				var count = 0;
				var form = $(this).closest('form');

				form.find('select[name^=noInfantsRoomList]').slice(0, $('#SCrooms').val()).each(function(){
					count += parseInt($(this).val());
				});

				SearchPanel.hide_show_infants.call(form, count);
			});
		},

		accomOnly: function () {
			$('#AOdestinationRegionList').bind('change', SearchPanel.onChangeDestinationRegion).trigger('change');

			$('#AOrooms').bind('change', function() {
				var el = $(this);
				var n = parseInt(el.val());
				el.closest('form').find('table.passengers tbody tr').show().slice(n).hide()
			}).trigger('change');
		},

		flightOnly: function() {

			var populate_date = function() {

				var target = null;
				var el = $(this);
				var search = el.closest('form>div').attr('id');

				if (search == 'flight-only-multistop'){
					target = el.closest('div.leg').next('div.leg').find('input.datepicker');
				} else if (search == 'flight-only-singlestop') {
					if ($(this).attr('id') == 'departdate')
						target = $('#returndate');
				}

				if (target && target.val() == 'dd/mm/yyyy') {
					var date = $.datepicker.parseDate('dd/mm/yy', el.val());
					date = new Date(date.getFullYear(), date.getMonth(), date.getDate()+1);
					target.val($.datepicker.formatDate('dd/mm/yy', date)).removeClass('inputlabel');
				}

			};

			var loadDates = function() {
				var today = new Date();
				Search.earliest = new Date(today.getFullYear(), today.getMonth(), today.getDate()+Global.searchDays);
				Search.latest = new Date(today.getFullYear(), today.getMonth()+11, today.getDate());
				Search.departDate = null;
				try {
					Search.departDate = $.datepicker.parseDate('dd/mm/yy', $('#departdate').val());
				}
				catch(e) {}
				Search.returnDate = null;
				try {
					Search.returnDate = $.datepicker.parseDate('dd/mm/yy', $('#returndate').val());
				}
				catch(e) {}
			};

			loadDates();

			var common = {
				numberOfMonths: 2,
				dateFormat: 'dd/mm/yy',
				dayNamesMin: ['S','M','T','W','T','F','S'],
				firstDay: 1,
				showAnim: 'fadeIn',
				showOptions: {speed: 'fast'},
				buttonImage: Global.url + 'themes/' + Global.theme + '/images/calendar_icon.gif',
				buttonImageOnly: true,
				showOn: 'both',
				minDate: Search.earliest,
				maxDate: Search.latest,
				onSelect: populate_date
			}

			$('#departdate').datepicker($.extend(common, {
				beforeShow: function() {
					SearchPanel.today = new Date();
				},
				beforeShowDay: function(date) {
					return [(date > SearchPanel.today), ''];
				}
			})).bind('change', SearchPanel.yy_to_yyyy).bind('change', populate_date);

			$('#returndate').datepicker($.extend(common, {
				beforeShow: function() {
					SearchPanel.departDate = new Date();
					try {
						SearchPanel.departDate = $.datepicker.parseDate('dd/mm/yyyy', $('#departdate').val());
					}
					catch(e) {}
				},
				beforeShowDay: function(date) {
					return [(date > SearchPanel.departDate), (date.valueOf() == SearchPanel.departDate.valueOf() ? 'depart' : '')];
				}
			})).bind('change', SearchPanel.yy_to_yyyy).bind('change', populate_date);

			$('#flight-only-multistop input.datepicker').datepicker(common).bind('change', SearchPanel.yy_to_yyyy).bind('change', populate_date);

			$('#flight-only-multistop > div.leg').each(function() {
				$(this).find('input.airportList:last').bind('result', function(){
					var el = $(this);
					var next = el.closest('div.leg').next('div.leg').find('input.airportList:first');
					if (next.val() == '' || next.val() == 'From')
						next.val(el.val()).removeClass('inputlabel');
				});
			});

			Search.autoComplete("input.airportList",SearchPanelAirportList);

			// search modes

			$('input#searchTypeReturn').bind('click', function() {
				$('div#flight-only-multistop').hide();
				$('div#flight-only-singlestop').show();
				$('p#flight-only-return-date').show();
				$('p.flight-only-prefs').show();
			});
			$('input#searchTypeOneWay').bind('click', function() {
				$('div#flight-only-multistop').hide();
				$('div#flight-only-singlestop').show();
				$('p#flight-only-return-date').hide();
				$('p.flight-only-prefs').show();
			});
			$('input#searchTypeMultiStop').bind('click', function() {
				$('div#flight-only-multistop').show();
				$('div#flight-only-singlestop').hide();
				$('p.flight-only-prefs').hide();
			});

			var showLegs = function(n) { $('#flight-only-multistop .leg').hide().slice(0, n).show(); };
			var showRemoves = function(n) { $('.flight-only-multi-remove').hide().eq(n).show(); };
			var maxLegs = 4;

			$('#flight-only-multi-add').bind('click', function() {

				var stepsInput = $('input[name="noMultiStopLegs"]:first')
				var curSteps = parseInt(stepsInput.val());

				if (curSteps <= maxLegs) {
					curSteps++;
					stepsInput.val(curSteps);
					showLegs(curSteps);

					// update date on next leg if poss

					// TODO check/fix this
					var date = null;
					try {
						date = $.datepicker.parseDate('dd/mm/yy', el.parents('div.leg').find('input.d').val());
					} catch(e) {}

					if (date != null) {
						date = new Date(date.getFullYear(), date.getMonth(), date.getDate()+1);
						el.parents('div.leg').next('div.leg').find('input.d').val($.datepicker.formatDate('dd/mm/yy', date));
					}

					// update 'from' based on previous 'to'

					// TODO

					// hide/show 'remove' links
					showRemoves(curSteps-3);

					if (curSteps == maxLegs)
						$('#flight-only-multi-add').parent().parent().hide();

				}

				return false;
			});

			$('.flight-only-multi-remove').bind('click', function() {
				var stepsInput = $('input[name="noMultiStopLegs"]:first')
				var curSteps = parseInt(stepsInput.val());

				if (curSteps > 2) {
					curSteps--;
					stepsInput.val(curSteps);
					showLegs(curSteps);

					showRemoves(curSteps-3);
					$('#flight-only-multi-add').parent().parent().show();
				}

				return false;
			});

			$('form#searchFlight .psg-under2').bind('change', function() {
				SearchPanel.hide_show_infants.call($(this).closest('form'), $(this).val());
			});
		}
	},

	hide_show_infants: function (infant_count) {

		if (infant_count==0)
			this.find('.psg-under2-options').hide();
		else {
			this.find('.psg-under2-options').show();
			this.find('.infant-seats p').hide().slice(0, infant_count).show();
		}

	},

	yy_to_yyyy: function() {
		var d = $(this);
		if (d.val().match(/\d\d\/\d\d\/\d\d$/))
			d.val(d.val().replace(/(\d\d\/\d\d)\/(\d\d)/, '$1/20$2'));
	},

	onChangeDestinationRegion: function () {

		var selectElement = this;
		var el = $(this);

		if (selectElement == null) {
			alert("selectElement == null");
		    return;
		}

		var destinationRegionResortList = el.closest('fieldset').find('select[name=destinationResort]').get(0);

		if (destinationRegionResortList == null) {
			console.log("destinationRegionResortList == null");
		    return;
		}

		if (destinationRegionResortList.selectedIndex < 0) {
			console.log("destinationRegionResortList.selectedIndex < 0");
		    return;
		}

		if (selectElement.selectedIndex < 0) {
			console.log("selectElement.selectedIndex < 0");
		    return;
		}

		var currentSelection = destinationRegionResortList.options[destinationRegionResortList.selectedIndex].value;
		var newOptions 	     = qDestinationRegionList[selectElement.options[selectElement.selectedIndex].value];

//		alert(selectElement.options[selectElement.selectedIndex].value);
//
//		if (newOptions == null && selectElement.options[selectElement.selectedIndex].value.match(/:/)) {
//			currentSelection = selectElement.options[selectElement.selectedIndex].value;
//
////			newOptions = new Array();
////			newOptions.push(new Option('All', currentSelection));
//			
//			newOptions       = qDestinationRegionList["Spain"];
////	    	$("#AOdestinationRegionResortList").parent().hide();
////	    	$("#SCdestinationRegionResortList").parent().hide();
//		}
////		else {
//////	    	$("#AOdestinationRegionResortList").parent().show();
//////	    	$("#SCdestinationRegionResortList").parent().show();
////		}

		if (newOptions == null || newOptions.length <= 0) {
			console.log("newOptions == null || newOptions.length <= 0");
		    return;
		}

		var i;
		var selectedIndex = 0;

		for (i = 0; i < newOptions.length; i++)
		{
			destinationRegionResortList.options[i] = new Option(newOptions[i].text, newOptions[i].value); //newOptions[i];

			if (newOptions[i].value == currentSelection)
				selectedIndex = i;
		}

		destinationRegionResortList.options.length = i;
		destinationRegionResortList.selectedIndex  = selectedIndex;

		SearchPanel.onChangeDestinationRegionResort.call(destinationRegionResortList);

		if (Global.accommodationOnlyCountries && Global.accommodationOnlyCountries.indexOf(selectElement.options[selectElement.selectedIndex].value) >=0) {
			
			if ($("#catAccommodationFlight:checked").length > 0) {
				$("#catAccommodationFlight").attr("checked", false);
				$("#catAccommodationOnly").attr("checked", true);
				$('#AOdestinationRegionList').val('Italy');
				$('#AOdestinationRegionList').change();
				$('#SCdestinationRegionList').val('');
				$('#SCdestinationRegionList').change('');
		    	$("#searchSC").hide();
		        $("#searchForm").show();
	  		}
		}

	},

	onChangeDestinationRegionResort: function() {

		var selectElement = this;
		var el = $(this);

		var departurePointList = el.closest('fieldset').find('select[name=departurePoint]');

		if (departurePointList.length == 0) {
			if (el.val() && el.val() != '')
				console.log("departurePointList is null (" + el.val() + ")");
			return;
		} else {
			departurePointList = departurePointList.get(0);
		}

		if (selectElement.selectedIndex < 0) {
			console.log("selectElement.selectedIndex < 0");
			return;
		}

		var currentSelection;

		if (departurePointList.selectedIndex < 0)
			currentSelection = "";
		else
			currentSelection = departurePointList.options[departurePointList.selectedIndex].value;

		var routeListKey     = selectElement.options[selectElement.selectedIndex].value;


		var newOptions 	     = qRouteList[routeListKey];
		if (!newOptions){
			for (rar in qRouteList){
				if (rar.indexOf(routeListKey)>=0){
					newOptions = qRouteList[rar];
					if (newOptions)
						break;
				}
			}
		}

		if (newOptions == null || newOptions.length <= 0) {
			if (selectElement.options[selectElement.selectedIndex].value)
				console.log("no routes defined for (" + routeListKey + ")");
			return;
		}

		var i;
		var selectedIndex = 0;

		for (i = 0; i < newOptions.length; i++)
		{
			departurePointList.options[i] = newOptions[i];

			if (newOptions[i].value == currentSelection)
				selectedIndex = i;
		}

		departurePointList.options.length = i;
		departurePointList.selectedIndex  = selectedIndex;

	}


};

Search = {
	init: function() {
		$(function() {

			$('#search form').submit(function() {
				var form = $(this);

				var ok = Search.validate(form);

				if (ok) {
					console.log('ok');
					$('div#main').fadeOut(250);
				}

				return ok;
			});

			// Infant seat preferences
			$('select#psg-under2').bind('change', function() {
				var c = $(this).val();

				if (c==0)
					$('fieldset#psg-under2-options').hide();
				else {
					$('fieldset#psg-under2-options').show();
					$('#infant-seats p').hide().slice(0, c).show();
				}

				Global.matchHeights();
			});

		});
	},
	autoComplete: function(elementName,airportList) {
		$(elementName).autocomplete(airportList, {
			max: 15,
			minChars: 3,
			matchContains: true,
			width: 556,
			scrollHeight: 240,
			sortList: function(list,term) {
				if (term.length != 3)
					return list;
				var newList = new Array();
				var length = list.length;
				var termUpper = term.toUpperCase();
				// look for an exact code match and put that at the top of the list
				for (var i = 0; i < length; i++) {
					if (!list[i])
						continue;
					if (list[i].data.code == termUpper)
						newList.push(list[i]);
				}
				// add the rest
				for (var i = 0; i < length; i++) {
					if (!list[i])
						continue;
					if (list[i].data.code != termUpper)
						newList.push(list[i]);
				}
				return newList;
			},
			formatItem: function(row, i, max) {
				return '<span class="airport">' + row.name.substring(0,row.name.lastIndexOf(',')) + '</span><span class="code">' + row.code + '</span><span class="country">' + row.country + '</span>';
			},
			formatMatch: function(row, i, max) {
				if (SearchPanelAirportCountryList[row.country] && new Number(SearchPanelAirportCountryList[row.country]) > 4) {
					// prevent matches on country if there are more than 4 airports in the country
					return row.name.replace(", " + row.country,"");
				}
				return row.name;
			},
			formatResult: function(row) {
				return row.name;
			}
		});
	},

	validate: function(formSearchType, form) {
		//deprecated with the inclusion of Flight only validation
		// alert is warning in developerment only - comment out for live purpose
		alert("This is line 625 or applications js - need to check where this was called from.\n this should not be used any more.");
		return true;
	},
	//Hotel Validation
	validateHotel: function(form) {

		hotelSearchType = $("#searchPanelSearchType").val();

		var errors = "";

		if( form.destinationCountry.options[form.destinationCountry.options.selectedIndex].text == 'Please choose' ) {
			errors += "Please select a destination airport.\n";
		}

		if( form.destinationResort.options[form.destinationResort.options.selectedIndex].text == 'Please choose' ) {
			errors += "Please select a resort.\n";
		}		
		if($(form).attr('id') == "searchSC"){
			if( form.departurePoint.options[form.departurePoint.options.selectedIndex].text == 'Please choose' ) {
				errors += "Please select a departure airport.\n";				
			}
		}
		if($(form).attr('id') == "searchForm"){
			if( form.destinationCountry.options[form.destinationCountry.options.selectedIndex].text == 'Maldives' ) {
				errors += "We are sorry but the destination you have selected is not available for accommodation only bookings.\n\nPlease search for either Accommodation & Flights to the Maldives or another destination as Accommodation Only.";
			}
		}
		if (errors != "") {
			alert("Please check the following:\n\n" + errors)
			return false;
		}

		return true;
	},
	// Flight Validation...
	validateFlight: function(form) {
		var formObject = form;
		var errors = "";

		var searchType = $('input[name="searchType"]:checked').val();

		if (searchType == "MF") {

			var noMultiStopLegs = new Number($('input[name="noMultiStopLegs"]:first').val());

			for (var i = 0; i < noMultiStopLegs; i++) {
				errors += Search.validateAirport(formObject,"departureAirportCodes["+ i + "]","leg " + (i + 1) + " departure airport");
				errors += Search.validateAirport(formObject,"arrivalAirportCodes[" + i + "]","leg " + (i + 1) + " arrival airport");
				errors += Search.validateDate(formObject,"departureDates[" + i + "]","leg " + (i + 1) + " departure date",'>', Search.earliest, "72 hours.\nFor reservations within the next 72 hours please call our Travel Centre on 0871 664968");

				if (i > 0) {
					if (Search.validateDate(formObject,"departureDates[" + i + "]") == "" && Search.validateDate(formObject,"departureDates[" + (i - 1) + "]") == "") {
						errors += Search.validateDate(formObject,"departureDates[" + i + "]","leg " + (i + 1) + " departure date",'>=',
								Search.validateDate(formObject,"departureDates[" + (i - 1) + "]","leg " + (i - 1) + " departure date"),
								"the leg " + i + " departure date");

					}
				}
			}
		}
		else {
			var airportError = Search.validateAirport(formObject,'departurePoint','departure airport',SearchPanelAirportListIE);
			if(airportError != ""){
				errors += airportError + " Please note your journey must begin from a Republic of Ireland airport.";
			}
			airportError = Search.validateAirport(formObject,'arrivalAirportCode','arrival airport',SearchPanelAirportList);
			if(airportError != ""){
				errors += airportError ;
			}

			errors += Search.validateDate(formObject,'outboundDate','departure date','>today');

			if (searchType == "RF") {
				errors += Search.validateDate(formObject,'returnDate','return date','>=',
						Search.validateDate(formObject,'outboundDate','departure date'),
						"the departure date");
			}
		}

		var noAdults   = new Number(Search.getValue(formObject,'noAdultsRoomList[0]'));
		var noChildren = new Number(Search.getValue(formObject,'noChildrenRoomList[0]'));
		var noInfants  = new Number(Search.getValue(formObject,'noInfantsRoomList[0]'));

		if (noAdults + noChildren + noInfants > 9) {
			errors += "\nFor groups of more than 9 passengers, please call our group sales team on " + Global.groupSalesTelephone + ".";
		}

		if (noAdults < noInfants) {
			errors += "\nDue to airline restrictions, each infant must be accompanied by an adult.";
		}

		if (errors != "") {
			alert("Please check the following:\n" + errors)
			return false;
		}

		return true;
	},
	validAirport: function (theAirport,validAirportList) {


		var airportCode;

		if (theAirport.length == 3)
			airportCode = theAirport.toUpperCase();
		else
			airportCode = theAirport.replace(/.*\(/,'').replace(/\).*/,'');
		for (var key in validAirportList) {

			if (validAirportList[key].code == airportCode)
				return true;
		}

		return false;
	},
	validateAirport: function(formObject,elementName,elementDescription,validAirportList) {

		var theAirport = Search.getValue(formObject,elementName);

		if (theAirport == "")
			return "\nPlease select a " + elementDescription + ".";

		if (!Search.validAirport(theAirport,validAirportList))
			return "\nThe " + elementDescription + " - " + theAirport + " - is not a valid airport.";

		return "";
	},
	getValue: function(formObject,elementName) {

		if (formObject && formObject.elements && formObject.elements[elementName] && formObject.elements[elementName].value)
			return $.trim(formObject.elements[elementName].value)

		return "";
	},
	invalidDate: function(theDate,elementDescription) {
		return "\nThe " + elementDescription + " - " + theDate + " - is not a valid date.";
	},
	compareDateError: function(theDate,elementDescription,theCondition,theOtherDate,theOtherPieceOfText) {

		var messageBase = "\nThe " + elementDescription + " - " + theDate + " - " + theCondition;

		if (theOtherPieceOfText)
			return messageBase + " " + theOtherPieceOfText;

		if (theOtherDate)
			return messageBase + " " + $.datepicker.formatDate('dd/mm/yy',theOtherDate);

		return messageBase;
	},
	validateDate: function(formObject,elementName,elementDescription,compareWith,anotherDate,anotherPieceOfText) {

		var theDate = Search.getValue(formObject,elementName);

		if (theDate == "")
			return "\nPlease enter a " + elementDescription + ".";

		var datePat    = /^(\d{1,2})[-\/.](\d{1,2})[-\/.]((\d{2}|\d{4}))$/;
		var matchArray = theDate.match(datePat); // is the format ok?

		if (matchArray == null) {
			return Search.invalidDate(theDate,elementDescription);
		}

		var day   = Number(matchArray[1]);
		var month = Number(matchArray[2]);
		var year  = Number(matchArray[3]);

		if (year < 100) //2 digit year
			year += 2000;

		if (month < 1 || month > 12) { // check month range
			return Search.invalidDate(theDate,elementDescription);
		}

		if (day < 1 || day > 31) {
			return Search.invalidDate(theDate,elementDescription);
		}

		if (day == 31 && (month == 4 || month == 6 || month == 9 || month == 11)) {
			return Search.invalidDate(theDate,elementDescription);
		}

		if (month == 2 && (day > 29 || (day==29 && !(year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))))) {
			return Search.invalidDate(theDate,elementDescription);
		}

		var date = new Date();

		date.setFullYear(year,month - 1,day);

		if (!compareWith)
			return date;  // date is valid

		if (compareWith == ">today") {

			var today = new Date();

			if (date <= today)
				return Search.compareDateError(theDate,elementDescription,"must be after today");

			return "";
		}

		if (compareWith == ">") {
			if (date <= anotherDate)
				return Search.compareDateError(theDate,elementDescription,"must be after",anotherDate,anotherPieceOfText);
			return "";
		}

		if (compareWith == ">=") {
			if (date < anotherDate)
				return Search.compareDateError(theDate,elementDescription,"cannot be before",anotherDate,anotherPieceOfText);
			return "";
		}

		if (compareWith == "<") {
			if (date >= anotherDate)
				return Search.compareDateError(theDate,elementDescription,"must be before",anotherDate,anotherPieceOfText);
			return "";
		}

		if (compareWith == "<=") {
			if (date > anotherDate)
				return Search.compareDateError(theDate,elementDescription,"cannot be after",anotherDate,anotherPieceOfText);
			return "";
		}

		return "";
	}
};

EssentialInfo = {
	init: function() {
		$(function() {
		    $('#info-wrap').tabs('div.infosection>ul>li>div', {
				tabs: 'div.infosection>ul>li>a',
		    	event: 'click',
		    	initialIndex: -1
		    });

		    $('a.expandall').click(function(){
				$(this).parent().parent().find('ul>li>div').show();
				return false;
			});

		    $('a#print-info-btn').click(function() {
		    	$('div#top-wrap a.expandall').click();
		    	window.print();
		    	return false;
		    });

		});
	}
};

HomePage = {
		init: function() {
			$(function() {

				$("div.tabs ul").tabs("div.images div.pane", {

					// enable "cross-fading" effect
					effect: 'fade',
					fadeOutSpeed: 'slow',

					// start from the beginning after the last tab
					rotate: true,

					onBeforeClick: function(event, tabIndex) {
					    $('.pane a').click(function () {
					    	location.href = $("div.images div.pane:nth-child(" + (tabIndex+1) + ") a").attr("href");
					    	return false;
					    });
			    	}
				// use the slideshow plugin. It accepts its own configuration
				}).slideshow({clickable: false, interval: 5000, autoplay: true, autopause: true});

			});

		}
	};

Maps = {
	init: function() {
		$(function() {

			$('a.tag').bind('mouseenter mouseleave', function() {
				country = $(this).attr('id').substring(2);
				$('img#h_' + country).toggle();
			});
			
		});

	}
};

Tours = (function() {
	var obj = {};

	function initRegionPicker() {
		$('#regionSelect select').change(function() {
			window.location.href = $(this).val();
		});
	}

	function initFilter() {
		$('.checkAll,.clearAll').click(function(){
			$(this).closest('div').find('input[type=checkbox]').attr('checked',$(this).hasClass('checkAll'));
			return false;
		});
	}

	obj.init = function() {
		if ($('#filtering').length > 0)
			initFilter();

		if ($('#regionSelect').length > 0)
			initRegionPicker();
	};

	return obj;
})();

$(Tours.init);

Multicentre = (function(){
	var obj = {};

	function initDescriptions() {
		$('body.multicentres #description p.more a').click(function() {
			if ($(this).text() == 'More')
				$(this).text('Less').closest('div').find('p.extra').show();
			else
				$(this).text('More').closest('div').find('p.extra').hide();
			return false;
		});
	}

	obj.init = function() {
		if ($('body.multicentres #description').length > 0)
			initDescriptions();
	};

	return obj;
})();

$(Multicentre.init);


