// IE specific
if (jQuery.browser.msie && parseInt(jQuery.browser.version) > 6) {
	// add round corners
	$(function(){
		var corners = [];

		var do_corners = function(selector, id, corners, size, border) {
			if (border == null) border = false;
			var el = $(selector).css('position','relative');
			for(var i in corners) {
				var corner = corners[i];
				el.append('<span class="cnr ' + id + ' ' + corner + size + ' ' + (border ? 'b ' : '') + 'c' + size + '"></span>');
			}
		}

		do_corners("div.ca:not(.foot.ca, .subhead.ca, li.callToAction div.ca)",  "cnr-cell", ['tl','tr','br','bl'], 5)

		do_corners("ul.offerList li.ca",  "cnr-cell", ['tl','tr','br','bl'], 5)

		//register home page
		do_corners("div#callToAction div",  "cnr-cell", ['tl','tr','br','bl'], 5)

		do_corners("div#promoPage div",  "cnr-cell", ['tl','tr','br','bl'], 5)

		//booking path
		do_corners("div#wideSide div#holidaySuitcase.ca",  "cnr-cell", ['tl','tr','br','bl'], 5)
		do_corners("body.passengerAndPaymentDetails h3:not(#itinerary-summary div h3)",  "cnr-cell", ['tl','tr','br','bl'], 5)
		do_corners("ol#results div.grid div.foot.ca", "cnr-cell-secondary", ['tl','tr','br','bl'], 5)
		do_corners("div#filter .subhead", "cnr-cell-tertiary", ['tl','tr','br','bl'], 5)

		//agent Login
		do_corners("div#session .loggedin.ca", "cnr-cell-loggedin", ['tl','tr','br','bl'], 5)

		//Offers
		do_corners("li.callToAction div.ca", "cnr-cell-callToBook", ['tl','tr','br','bl'], 5)

	});
}



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

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();
}

Global = $.extend(Global, {

	fancyLabels: [],
	ie6: false,

	init: function() {

		$(document).ready(function() {

			Global.ie6 = jQuery.browser.msie && parseInt(jQuery.browser.version) < 7 && parseInt(jQuery.browser.version) > 4;

			// Prepare fancy labels
			var fancylabels = $('.fancylabel[title]');
				fancylabels.each(function(){
					Global.fancyLabels[this.id] = this.title;
					this.title = '';
				});
			fancylabels.each(Global.doFancyLabel);
			fancylabels.bind('blur', Global.doFancyLabel);
			fancylabels.bind('focus', Global.doFancyLabel);
			$('button[type=submit],input[type=submit]').bind('click',Global.clearFancyLabel);

			Global.progress();					// Progress tracker
			Global.matchHeights();				// Element height matching
			Global.selectFix();					// Select iframe shim IE6
			Global.toolTips();					// Tooltip info on search page
			Global.essentialInfo();				// Essential info ajax helper
			Global.contact();					// Contact us hover
			Global.overlays();
			Global.showSearchPanel();
			Search.init();

			// common transparent elements
			commonTransparencies = 'p.logo a,'
								 + 'input.t,'
								 + 'ol#progress,'
								 + 'ol#progress li,'
								 + 'ol#progress li a:link,'
								 + 'ol#progress li a:visited,'
								 + 'img.airline-logo,'
								 + 'div.mapBox img,'
								 + 'img.UIRoundedImage_CornersSprite,'
								 + 'div.overlay a.overlay-close';

			Global.ieTrans(commonTransparencies);

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

			$("form.signup input.email").focus(function() {
				$input = $("form.signup input.email").val();
				if ($input == "Enter your email address") {
						this.value='';
					}

			});
			$("form.signup input.email").blur(function() {
				if (this.value == '') {
					this.value="Enter your email address";
				}
			});

		});

	},

	matchHeights: function() {
		$('div.heightmatch').each(function() {
			var maxHeight = 0;
			$(this).children('div.cell').each(function() {
				$(this).css('height', 'auto');
				if ($(this).height() > maxHeight)
					maxHeight = $(this).height();
			});
			$(this).children('div.cell').css('height', maxHeight);
		});

	},

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

	clearFancyLabel: function() {
		for (var id in Global.fancyLabels) {
			if ($('#'+id).val() == Global.fancyLabels[id])
				$('#'+id).val('');
		}
	},

	contact: function() {
		$('ul#toplinks li.contact').bind('mouseenter', function() {
			$(this).addClass('hover');
			$('div#contact-overlay-holder').show();
		});
		$('div#contact-overlay-holder').bind('mouseleave', function() {
			$(this).removeClass('hover');
			$('div#contact-overlay-holder').hide();
		});
	},

	toolTips: function() {
		// Custom effect
		$.tools.addTipEffect("slidedown",
	    // opening animation
	    function() {
	      var opacity = this.getConf().opacity;
	      this.getTip().css({opacity:0}).animate({left: '+=5', opacity:opacity}, 150).show();
	    },
	    // closing animation
	    function() {
	      this.getTip().animate({left: '+=15', opacity:0}, 150, function() {
	        $(this).hide().animate({left: '+=20'}, 0);
	      });
	    }
		);
		// Generate
		var n = 1;
		$('.tip-trigger').each(function(){
			var el = $(this);
			el.next().attr('id', 'tip'+n);
			el.tooltip({
				position: ['center', 'right'],
				effect: 'slidedown',
				tip: '#tip'+n
			});
			n++;
		});
	},

	progress: function() {
		$('ol#progress li.future a, ol#progress li.current a').bind('click', function() { return false; });
	},

	ieTrans: function(selectors) {
		if (typeof(DD_belatedPNG) != 'undefined')
			DD_belatedPNG.fix(selectors);
	},

	essentialInfo: function() {

		var holder = $('#full-info-holder');

		if (holder.length == 1) {
			$('#essential-info-links a').click(function() {
				var item = this.hash.substring(1);

				if (holder.html().length == 0)
				{
					// do ajax load
					holder.load(Global.url + 'viewPage.vm?viewName=essentialInformation .infosection>ul', {}, function(){ Global.essentialInfoDisplay(item); });
				} else {
					Global.essentialInfoDisplay(item)
				}

				return false;
			});

			Global.overlay = $('#overlay-holder').overlay({
				expose: {color: '#000', opacity: 0.5},
				api: true,
				close: 'a.overlay-close',
				onLoad: function() {
					$('#overlay-holder .content').get(0).scrollTop = 0;
					//
					Cufon.refresh();
				},
				onBeforeLoad: function() {
					if (Global.ie6) $('select').css('visibility','hidden');
				},
				onClose:function() { if (Global.ie6)  $('select').css('visibility','visible');}
			});
		}
	},

	essentialInfoDisplay: function(selector) {
		$('#overlay-holder h2').html('Essential Information').get(0).id = 'essential-info';

		$('#overlay-holder .content').html($('#full-info-holder div#'+selector).html());
		Global.overlay.load();
	},

	selectFix: function() {
		if (Global.ie6) {
			//SelectFix.repairFloatingElement('select');
			//$('div.tip-holder div.tip').bgiframe({ src: "BLOCKED SCRIPT'&lt;html&gt;&lt;/html&gt;';" });
		}
	},

	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[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');
			}
		}));

	},
	searchPanelCollapsed: function() {
		$(function() {
			$("div.searchAgainLink").css('display','block');
			$("#searchContainer").hide();
		});
	},
	showSearchPanel: function(){
		$('a[name=search]').click(function(e) {
			//Cancel the link behavior
			e.preventDefault();

		//	alert("searchPanel");
			$("#searchContainer").slideToggle("slow");
			//need to toggle css here....
			$(".searchAgainLink a span.srchAgainBtn").toggleClass("srchHideBtn");
		});

	}
});
Index = {
		init: function() {
			Cufon.replace('h3');

		    $(function() {
				 $('#offerFeatures').tabs({
					 fx: { opacity: 'toggle' } }).tabs('rotate', 5000); // rotating tabs
		    });
	}
};
Deals = {
	init: function() {

		$.tools.addTabEffect("switch", function(i) {
			this.getCurrentPane().slideUp('normal');
			this.getPanes().eq(i).slideDown('normal');
		});

		$(function(){

			// Deal accordions
			Deals.tabs = $('ul#deal-list').tabs('ul#deal-list dd', {
				tabs: 'dt',
				event: 'click',
				effect: 'switch',
				initialIndex: -1,
				delay: 1000,
				api:true,
				onClick: function(n) { $('ul#deal-list dt').removeClass('open').eq(n).addClass('open'); }
			});
			$('ul#deal-list dt').bind('mouseenter', function(){
				var index = $('ul#deal-list dt').index(this);
				Deals.timeout = setTimeout(function(){
					Deals.tabs.click(index);
				}, 1000);
			});
			$('ul#deal-list dt').bind('mouseleave', function(){
				clearTimeout(Deals.timeout);
			});

		});
	}
};

SideSearch = {
	init: function() {
		$(function(){
			$('#newsearch-link').click(function(){
				$('#newsearch .head').toggleClass('head-closed');
				$('#searchcontainer').toggle();
				return false;
			});

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

				var ok = Search.validate(form);

				if (ok)
					form.find('input[type=submit]').addClass('progress');

				return ok;
			});

			Search.init();
		});
	}
};

Search = {
	init: function() {
		$(function() {
			$('#searchPanelTabs').tabs({
				   show: function(event, ui) {
							var $tabs = $('#searchPanelTabs').tabs();
							var selected = $tabs.tabs('option', 'selected');
							switch (selected){
								case 0: //Accommodation and flights
									$('div#searchPanelSingleCentre').show();
									$('div#searchPanelFlightOnly').hide();
									$('fieldset#departurePointDiv').show();
									$('form#searchForm input[name=searchType]').val("SC");
									break;
								case 1: //Accommodation Only
									$('div#searchPanelSingleCentre').show();
									$('div#searchPanelFlightOnly').hide();
									$('fieldset#departurePointDiv').hide();
									$('form#searchForm input[name=searchType]').val("AO");
									break;
								case 2: //Flight Only
									$('div#searchPanelFlightOnly').show();
									$('div#searchPanelSingleCentre').hide();
								default:
									break;
							}
					}

			});
			// set Current Search Tab
			Search.currentTab();
			$('.searchAgainLink a').click(function() { // bind click event to link
				Search.currentTab();
			    return false;
			});

			//Deals.init();

			// Dates
			Search.datePickers();
			$('input.d').bind('change', 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'));
			});

			// text
			$('input.t').bind('focus', function() { this.select(); });

			// Search modes
			$('input#searchTypeReturn').bind('click', function() {
				$('div#multi-mode').hide();
				$('fieldset#return-mode').show();
				$('fieldset#whenLeaving').show();
				$('.return-date').show();
				$('#search-tips ul').hide();
				$('#tips-return').show();
				$('fieldset#flight-prefs').show();
				$('#searchPanelFlightOnly ul.search').removeClass("jqMulti");
				Global.matchHeights();
			});
			$('input#searchTypeOneWay').bind('click', function() {
				$('div#multi-mode').hide();
				$('fieldset#return-mode').show();
				$('fieldset#whenLeaving').show();
				$('.return-date').hide();
				$('#search-tips ul').hide();
				$('#tips-oneway').show();
				$('fieldset#flight-prefs').show();
				$('#searchPanelFlightOnly ul.search').removeClass("jqMulti");
				Global.matchHeights();
			});
			$('input#searchTypeMultiStop').bind('click', function() {
				$('div#multi-mode').show();
				$('fieldset#return-mode').hide();
				$('fieldset#whenLeaving').hide();
				$('#search-tips ul').hide();
				$('#tips-multistop').show();
				$('fieldset#flight-prefs').hide();
				$('fieldset#multi-mode > div.leg').hide().slice(0, parseInt($('input[name="noMultiStopLegs"]:first').val())).show();
				$('#searchPanelFlightOnly ul.search').addClass("jqMulti");
				Global.matchHeights();
			});

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

				var ok = Search.validate(form);

				if (ok)
					form.find('input[type=submit]').addClass('progress');

				return ok;
			});
			$('#results form').submit(function() {
				// Show interstitial on Flight only search results
				Global.interstitial("austrv");
			});

			// Add / Remove Multi Destinations
			$('a.option-add').bind('click', function() {

				var el = $(this);
				// hide this link
				el.hide();

				// remove the remove link from this leg (if applicable)
				el.siblings('a.option-remove').hide();

				// show the next leg
				el.parents('div.leg').next('div.leg').show().find('input.t:first').val(el.parents('div.leg').find('input.t:last').val());

				// update date on next leg if poss
				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 noMultiStopLegs
				$('input[name="noMultiStopLegs"]:first').val(1 + parseInt(el.parents('div.leg').get(0).id.substring(3)));

				return false;
			});

			$('a.option-remove').bind('click', function() {

				var el = $(this);
				// hide this leg
				el.parents('div.leg').hide();

				// restore the options in the previous leg
				el.parents().prev('div.leg').find('a.option').show();

				// update noMultiStopLegs
				$('input[name="noMultiStopLegs"]:first').val(parseInt(el.parents('div.leg').get(0).id.substring(3)) - 1);

				return false;

			});

			// 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();
			});


			transparencies = 'h1 a,'
										 + 'span.il,'
										 + 'input.t,'
										 + 'span.ir,'
										 + 'div#header p.atol,'
										 + '#footer #footer-inside,'
										 + 'dl.nav dt';
			Global.ieTrans(transparencies);


			Search.autoComplete("input.airportList",SearchPanelAirportList);
			Search.autoComplete("input.airportListUK",SearchPanelAirportListUK);
			Search.autoComplete("input.airportListNonUK",SearchPanelAirportListNonUK);
			Search.autoComplete("input.airportListTurnAround",SearchPanelAirportListTurnAround);


//Radio Button Actions

			$('input#searchPackageRadio').bind('click', function() {
				$('div#searchPanelSingleCentre').show();
				$('div#searchPanelFlightOnly').hide();
				$('fieldset#departurePointDiv').show();
				$('form#searchForm input[name=searchType]').val("SC");
			});
			$('input#searchAccommodationOnlyRadio').bind('click', function() {
				$('div#searchPanelSingleCentre').show();
				$('div#searchPanelFlightOnly').hide();
				$('fieldset#departurePointDiv').hide();
				$('form#searchForm input[name=searchType]').val("AO");
			});
			$('input#searchFlightOnlyRadio').bind('click', function() {
				$('div#searchPanelFlightOnly').show();
				$('div#searchPanelSingleCentre').hide();
				$('input#searchTypeReturn').val(['RF']);
			});
		});
	},
	currentTab: function() {
		var $tabs = $('#searchPanelTabs').tabs();
		// What tab to display....
		$tabState = $('#searchPanelTabState').val();
		if($tabState == "SC"){
			$tabs.tabs('select', 0);
		}
		else if($tabState == "AO"){
			$tabs.tabs('select', 1);
		}
		else{
			$tabs.tabs('select', 2);
		};
	},
	selectFlightTab: function() {
		$(document).ready(function() {
			var $tabs = $('#searchPanelTabs').tabs();
			$tabs.tabs('select', 2);
		});
	},
	datePickers: function() {

		var loadDates = function() {
			var today = new Date();
			Search.earliest = new Date(today.getFullYear(), today.getMonth(), today.getDate()+2);
			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/pageElements/icons/calendar_icon.png',
			buttonImageOnly: true,
			showOn: 'both',
			minDate: Search.earliest,
			maxDate: Search.latest,
			onSelect: function(date, dp) {
				var search = $("form#flightOnlySrch").find('input[name="searchType"]:checked').val();
				var target = null;
				var val = null;
				var el = $(this);

				if (search == 'MF'){
					target = el.parents('div.leg').next('div.leg').find('input.d');
				} else if (search == 'RF') {
					target = $('#returndate');
				}
				
				if (target) {					
					date = $.datepicker.parseDate('dd/mm/yy', date);
					date = new Date(date.getFullYear(), date.getMonth(), date.getDate()+1);
					target.val($.datepicker.formatDate('dd/mm/yy', date));
				}
			},
			beforeShow: loadDates
		}

		$('#departdate input').datepicker($.extend(common, {
			dateType: 'departure ',
			beforeShowDay: function(date) {
				var cls = '';
				if (Search.departDate && date.valueOf() == Search.departDate.valueOf())
					cls = 'depart';
				if (Search.returnDate && date.valueOf() == Search.returnDate.valueOf())
					cls = 'return';
				return [(date >= Search.earliest), cls];
			}
		}));

		$('#returndate').datepicker($.extend(common, {
			dateType: 'return ',
			beforeShowDay: function(date) {
				var cls = '';
				if (Search.departDate && date.valueOf() == Search.departDate.valueOf())
					cls = 'depart';
				if (Search.returnDate && date.valueOf() == Search.returnDate.valueOf())
					cls = 'return';
				return [(date >= (Search.departDate || Search.earliest)), cls];
			}
		}));

		$('#multi-mode input.d').datepicker($.extend(common, {
			dateType: 'flight ',
			beforeShowDay: null
		}));
		// Close Date Pickers
		$('a.dpclose').live('click', function() { $('#ui-datepicker-div').hide(); });
	},
	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(form) {
		var formObject = form.get(0);
		var errors = "";
		var searchType = form.find('input[name="searchType"]:checked').val();
		if (searchType == "MF") {
			var hasTurnAroundAirport = false;

			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",i==0?SearchPanelAirportListUK:SearchPanelAirportList);
				errors += Search.validateAirport(formObject,"arrivalAirportCodes[" + i + "]","leg " + (i + 1) + " arrival airport",SearchPanelAirportList);
				errors += Search.validateDate(formObject,"departureDates[" + i + "]","leg " + (i + 1) + " departure date",'>today');

				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");
					}
				}
				//check if at least one airport code is a valid turn around airport
				if (Search.validateAirport(formObject,"departureAirportCodes["+ i + "]","",SearchPanelAirportListTurnAround) == ""){
					hasTurnAroundAirport = true;
				}
				if (Search.validateAirport(formObject,"arrivalAirportCodes[" + i + "]","",SearchPanelAirportListTurnAround) == ""){
					hasTurnAroundAirport = true;
				}
			}
			if(!hasTurnAroundAirport){
				errors += "\nAt least one leg of your jorney needs to include Australia, New Zealand or the Pacific Islands";
			}
		}
		else {
			var airportError = Search.validateAirport(formObject,'departurePoint','departure airport',SearchPanelAirportListUK);
			if(airportError != ""){
				errors += airportError + " Please note your journey must begin from a UK airport.";
			}
			airportError = Search.validateAirport(formObject,'arrivalAirportCode','arrival airport',SearchPanelAirportListTurnAround);
			if(airportError != ""){
				errors += airportError + " Please note your destination must be in Australia, New Zealand or a Pacific Island.";
			}

			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;
		}

		var weAreSearchingFor = "We are searching for ";

		if (searchType == "OF") {

			weAreSearchingFor += "flights from " +
				"<em>" +
				$('input[name="departurePoint"]:first').val() +
				"</em> to <em>" +
				$('input[name="arrivalAirportCode"]:first').val() +
				"</em> departing on <em>" +
				$.datepicker.formatDate('d MM', $.datepicker.parseDate('dd/mm/yy', form.find('input[name="outboundDate"]:first').val())) +
				"</em>";
		}
		else {
			if (searchType == "MF") {
				weAreSearchingFor += "your multistop flights";
			}
			else {

				weAreSearchingFor += "flights from " +
					"<em>" +
					$('input[name="departurePoint"]:first').val() +
					"</em> to <em>" +
					$('input[name="arrivalAirportCode"]:first').val() +
					"</em> departing on <em>" +
					$.datepicker.formatDate('d MM', $.datepicker.parseDate('dd/mm/yy', form.find('input[name="outboundDate"]:first').val())) +
					"</em> returning <em>" +
					$.datepicker.formatDate('d MM', $.datepicker.parseDate('dd/mm/yy', form.find('input[name="returnDate"]:first').val())) +
					"</em>";
			}
		}

		$("#waiting p").html(weAreSearchingFor);
		Global.interstitial("austrv");

		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;
		    });

		});
	}
};

AgentLogin = {
    init: function() {
		$(function(){
	        $('#more-airlines-btn').click(function () {
	            $('div#more-airlines').slideDown();
	            $.scrollTo('870px', {axis: 'y', duration: 500, easing: 'easeInQuad'});
	            $(this).fadeOut();
	            return false;
	        });
		});
    }
};

Itinerary = {
	init: function() {
		$(function(){
			$('a#agent-toggle').click(function(){
				$(this).toggleClass('hide').toggleClass('show');
				$('div#agents div.head').toggleClass('bb').toggleClass('open');
				$('#agent-info').slideToggle(50);
				return false;
			});

			$('#holidaySummaryForm').bind('submit', function() {
				if (!$('#tandc').get(0).checked) {
					alert('You must agree to the Terms and Conditions to continue');
					return false;
				}
			});

			$('#flight-rules').appendTo('body');
		});
	}
}
Payment = {
	    init: function() {
			$(function(){
				 $('a.securityNumber').cluetip({
					 	activation: 'click',
					 	local:true,
						cursor: 'pointer',
						width: 350,
						 closePosition:    'title',
						sticky: true
						});
				 Cufon.replace('h3');

			});
	    }
	};

specialOffers = {
	    init: function() {
			$(function(){
				var maxHeight = 0;
				$('div.cell').each(function() {
					$(this).css('height', 'auto');
					if ($(this).height() > maxHeight)
						maxHeight = $(this).height();
				});
				$('div.cell').css('height', maxHeight);

			});
	    }
	};
Destinations = {
		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;
			    });

			});
		}
	};

Tours = (function() {
	var obj = {};
	
	var mapLoaded = true;
	
	function initFilter() {
		$('.checkAll,.clearAll').click(function(){
			$(this).closest('div').find('input[type=checkbox]').attr('checked',$(this).hasClass('checkAll'));
			return false;
		});
	}
	
	function initMap(){
		$('#showMap').click(function(){
			if ($('#tourMap:visible').length == 1) {
				$(this).removeClass('open');
				$('#tourMap').slideUp();
			} else {
				$(this).addClass('open');
				$('#tourMap').slideDown();
				if (!mapLoaded) {
					// TODO: instantiate the google map here
				}
			}
			return false;
		});
	}
	
	obj.init = function() {	
		if ($('#filterPanel').length > 0)
			initFilter();
		
		if ($('#tourMap').length == 1)
			initMap();
	};
	
	return obj;
})();

$(Tours.init);


// Older functions that are still required by various parts of the sites

function MM_reloadPage(init) {  //reloads the window if Nav4 resized
	  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
		document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
	  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
	}

	MM_reloadPage(true);

	function MM_findObj(n, d) { //v4.01
	  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
		d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
	  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
	  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
	  if(!x && d.getElementById) x=d.getElementById(n); return x;
	}

	function MM_showHideLayers() { //v6.0
	  var i,p,v,obj,args=MM_showHideLayers.arguments;

	  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
	  	if (obj.style) { obj=obj.style; v=(v=='show')?'block':(v=='hide')?'none':v; }
		obj.display=v; }
	}

	function MM_jumpMenu(targ,selObj,restore){ //v3.0
	  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
	  if (restore) selObj.selectedIndex=0;
	}

	function MM_jumpMenuGo(selName,targ,restore){ //v3.0
	  var selObj = MM_findObj(selName); if (selObj) MM_jumpMenu(targ,selObj,restore);
	}

	var d = document;


	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();
	}

	function checkCheckBox(f){
	if (f.acceptErrata.checked == false )
	{
	alert('Please confirm that you have read and agree\n to the information shown.');
	return false;
	}else
	return true;
	}

	function doSubmit(formName,nextPage) {

		var formObject = MM_findObj(formName);

		if (formObject != null)
		{
			if (formObject.nextPage != null)
				formObject.nextPage.value = nextPage;

			formObject.submit();

			return false;
		}

		return true;
	}

	function MM_preloadImages() { //v3.0
	  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
		var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
		if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
	}

	function MM_swapImgRestore() { //v3.0
	  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
	}

	function MM_findObj(n, d) { //v4.01
	  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
		d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
	  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
	  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
	  if(!x && d.getElementById) x=d.getElementById(n); return x;
	}

	function MM_swapImage() { //v3.0
	  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
	   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
	}
	function hoteDetails() {
		//alert ("This is hoteDetails")
		//window.location = "#top";
		window.scrollTo(0,0);
		MM_showHideLayers('waiting','','show');
		MM_showHideLayers('content','','hide','bookingFooter','','hide','holiday_summary_div','','show');
	}

	function hotelToOptions(){
		window.scrollTo(0,0);
		MM_showHideLayers('holiday_summary_div','','show');
		MM_showHideLayers('container-content','','hide');
	}

	function qGetElementById(id)
	{
		var elements = document.getElementsByName(id);

		for (var i = 0; i < elements.length; i++)
		{
			if (elements[i].name == elements[i].id)
			    return elements[i];
		}

		return MM_findObj(id);
	}

	function qDumpObject(object)
	{
		var debugWindow = window.open('','debug','scrollbars,status,resizable,location,width=900,height=500');

		debugWindow.document.writeln("<html><head><title>Quatro Debug</title></head>");
		debugWindow.document.writeln("<body><pre>");

		debugWindow.document.writeln(object);

		for (var property in object)
			debugWindow.document.writeln(property + " = " + object[property]);

		debugWindow.document.writeln("</pre></body></html>");
		debugWindow.document.close();
		debugWindow.focus();
	}