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

		// first main left grid head (clouded)
		do_corners("div#main.col-left div.grid:not(.grid-secondary, .grid-tertiary) div.head.ct:first",
				   "cnr-head-main-left-top", ['tl','tr'], 10);

		// first main right grid head (clouded)
		do_corners("div#main.col:not(.col-left) div.grid:not(.grid-secondary, .grid-tertiary) div.head.ct:first",
				"cnr-head-main-right-top", ['tl','tr'], 10);

		// first side left grid head (clouded) TOP CORNERS [eg: search panel on search results page]
		do_corners("div#side.col-left div.grid:not(.grid-secondary, .grid-tertiary) div.head.ct:first",
				"cnr-head-side-left-top", ['tl','tr'], 10);

		// first side left grid head (clouded) BOTTOM CORNERS [eg: search panel on search results page -- TODO: toggle this when opened]
		do_corners("div#side.col-left div.grid:not(.grid-secondary, .grid-tertiary) div.head-closed:first",
				"cnr-head-side-left-top", ['br','bl'], 10);

		// first side right grid head (clouded) TOP CORNERS [eg: search panel on search results page]
		do_corners("div#side.col:not(.col-left) div.grid:not(.grid-secondary, .grid-tertiary) div.head.ct:first",
				"cnr-head-side-right-top", ['tl','tr'], 10);

		// first side right grid head (clouded) BOTTOM CORNERS [eg: search panel on itinerary page -- TODO: toggle this when opened]
		do_corners("div#side.col:not(.col-left) div.grid:not(.grid-secondary, .grid-tertiary) div.head-closed:first",
				"cnr-head-side-right-top", ['br','bl'], 10);

		// all other main grid heads
		do_corners("div#main.col div.grid:not(.grid-secondary, .grid-tertiary) div.head.ct:not(:first)",
				"cnr-head", ['tl','tr'], 10);

		// all grid cell bottoms
		do_corners("div.grid:not(.grid-secondary, .grid-tertiary) div.cell.cb",	"cnr-cell", ['br', 'bl'], 10);

		// all grid cell bottoms
		do_corners("div.grid:not(.grid-secondary, .grid-tertiary) div.grid.cb",	"cnr-cell", ['br', 'bl'], 10);

		// all grid foots
		do_corners("div.grid:not(.grid-secondary, .grid-tertiary) div.foot.cb",	"cnr-foot", ['br', 'bl'], 10);

		// secondary grid heads
		do_corners("div.grid-secondary div.head.ct", "cnr-head-secondary", ['tl', 'tr'], 10);

		// secondary grid cells
		do_corners("div.grid-secondary div.cell.cb", "cnr-cell-secondary", ['br', 'bl'], 10);

		// tertiary grid heads
		do_corners("div.grid-tertiary div.head.ct", "cnr-head-tertiary", ['tl', 'tr'], 10);

		// tertiary grid heads
		do_corners("div.grid-tertiary div.head.ctnb", "cnr-head-tertiaryNB", ['tl', 'tr'], 10);

		// tertiary grid cells
		do_corners("div.grid-tertiary div.cell.cb", "cnr-cell-tertiary", ['br', 'bl'], 10);

		// tertiary grid cells
		do_corners("div.grid-tertiary div.cell.cbnb", "cnr-cell-tertiaryNB", ['br', 'bl'], 10);

		// tertiary grid foots
		do_corners("div.grid-tertiary div.foot.cb", "cnr-foot-tertiary", ['br', 'bl'], 10);


		// ---- SPECIFIC OBJECTS ----

		// warning box
		do_corners("div.warning.ca", "cnr-warn", ['tl','tr','br','bl'], 10, true);

		// deal accordion (DT)
		do_corners("ul#deal-list dt.casml", "cnr-deal", ['tl','tr','br','bl'], 6);

		// deal accordion (DD)
		do_corners("ul#deal-list dd.cbsml", "cnr-deal", ['br', 'bl'], 6);

		// value airlines bl
		do_corners("table.value th.cbl", "cnr-foot", ['bl'], 10);

		// value airlines br
		do_corners("table.value td.cbr", "cnr-foot", ['br'], 10);

		// agents area on itinerary
		do_corners("div#agents div.head.ca", "cnr-head", ['tl','tr', 'br', 'bl'], 10);

		// essential info block
		do_corners("div.infosection > ul > li", "cnr-infosection", ['tl','tr','br','bl'], 15);

		//volcano
		do_corners("div.volcanofaqlink > ul > li", "cnr-infosection", ['tl','tr','br','bl'], 15);

		// breadcrumb
		do_corners("div#breadcrumb-wrap", "cnr-breadcrumb", ['tl','tr','br','bl'], 10);

		// flight deals
		do_corners("div.deals ul li.ca", "cnr-foot", ['tl','tr','br','bl'], 10);

	});
}



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.flightExtraInfo();			// Flight Extra Info overlay
			Global.contact();					// Contact us hover
			Global.overlays();

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

			Global.ieTrans(commonTransparencies);

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

		});

	},

	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() {
	      this.getTip().animate({left: '+=5'}, 150).show();
	    },
	    // closing animation
	    function() {
	      this.getTip().animate({left: '+=15'}, 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;
				},
				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();
	},

	flightExtraInfo: function() {
		$('.extrasSuppsContentInfo div').hide();
		$('.extrasSuppsContentInfo a').show();
		$('.extrasSuppsContentInfo a').click(function() {
			var flightExtra = this.id;
			var flightExtraTitle = this.title;

			Global.flightExtraInfoDisplay(flightExtra,flightExtraTitle);
			
			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;
			},
			onBeforeLoad: function() {
				if (Global.ie6) $('select').css('visibility','hidden');
			},
			onClose:function() { if (Global.ie6)  $('select').css('visibility','visible');}
		});
	},

	flightExtraInfoDisplay: function(selector,title) {
		$('#overlay-holder h2').html(title).get(0).id = selector + 'flightExtra';
		$('#overlay-holder .content').html($('div#'+selector+'ExtraInfo').html());
		$('#overlay-holder .content div').css('display','block');
		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');
			}
		}));

	}

});

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')
						.find('span.bl6, span.br6')
							.show().end()
						.eq(n)
							.addClass('open')
							.find('span.bl6, span.br6')
							.hide();
				},
				onBeforeClick: function() {

				}
			});
			$('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').find('span.bl10,span.br10').toggle();
				$('#searchcontainer').toggle();
				return false;
			});

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

				var ok = Search.validate(form);

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

				return ok;
			});

			$('.select-btn').click(function() {
				var button = $(this);

				button.addClass('progress');

			});

			$('.continue-btn').click(function() {
				var button = $(this);
				if ($('#tandc').get(0).checked) {
					button.addClass('progress');
				}
			});


			Search.init();

			// open panel if MS search results
			if ($('body').hasClass('searchResults') && $('#searchTypeMultiStop').attr('checked'))
				$('#newsearch-link').click();
		});
	}
};

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

			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();
				$('div#return-mode').show();
				$('p#return-date').show();
				$('#search-tips ul').hide();
				$('#tips-return').show();
				$('div#flight-prefs fieldset:first').show();
				$('div#flight-prefs fieldset:first select').attr('disabled', '');
				Global.matchHeights();
			});
			$('input#searchTypeOneWay').bind('click', function() {
				$('div#multi-mode').hide();
				$('div#return-mode').show();
				$('p#return-date').hide();
				$('#search-tips ul').hide();
				$('#tips-oneway').show();
				$('div#flight-prefs fieldset:first').show();
				$('div#flight-prefs fieldset:first select').attr('disabled', '');
				Global.matchHeights();
			});
			$('input#searchTypeMultiStop').bind('click', function() {
				$('div#multi-mode').show();
				$('div#return-mode').hide();
				$('#search-tips ul').hide();
				$('#tips-multistop').show();
				$('div#flight-prefs fieldset:first').hide();
				$('div#flight-prefs fieldset:first select').attr('disabled', 'disabled');
				$('div#multi-mode > div.leg').hide().slice(0, parseInt($('input[name="noMultiStopLegs"]:first').val())).show();
				Global.matchHeights();
			});

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

				var ok = Search.validate(form);

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

			// 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 option links on next leg
				el.parents('div.leg').next('div.leg').find('a.option').show();

				// show the next leg
				el.parents('div.leg').next('div.leg').show();

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

				return false;
			});

			$('div#multi-mode > div.leg').each(function() {
				$(this).find('input.t:last').bind('result', function(){
					var el = $(this);
					var next = el.parents('div.leg').next('div.leg').find('input.t:first');
					if (next.val() == '')
						next.val(el.val());
				});
			});

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

			// Clear all button
			$('a#clear-all-btn').click(function() {
				if (confirm("Are you sure you want to start a new search?")) {
					$('input.t').val('');
					$('input.d').val('dd/mm/yyyy');

					$('#searchAirline').val(0);
					$('#searchCabin').val(0);

					$('#searchAdults').val(2);
					$('#searchChildren').val(0);
					$('#psg-under2').val(0);
					$('fieldset#psg-under2-options').hide();

					$('#searchTypeReturn').click();
				}
				return false;
			});

			transparencies = 'h1 a,'
										 + 'span.il,'
										 + 'input.t,'
										 + 'span.ir';
			Global.ieTrans(transparencies);

			if ($.browser.msie || $.browser.safari) {
				// preload image for IE and safari/chrome
				var img = new Image(92,31);
				img.src= Global.url + 'themes/' + Global.theme + '/images/buttons/search_progress.gif';

				var imgSelect = new Image(124,30);
				imgSelect.src= Global.url + 'themes/' + Global.theme + '/images/buttons/select.gif';

				var imgContinue = new Image(104,30);
				imgContinue.src= Global.url + 'themes/' + Global.theme + '/images/buttons/continue.gif';

				var interstitial = new Image(304,184);
				interstitial.src= Global.url + 'themes/' + Global.theme + '/images/progress/flexiWaitingAnim.gif';
			}


			$("input.airportList").autocomplete(SearchPanelAirportList, {
				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;
				}
			});

			// uk only airport list //
			$("input.airportListUK").autocomplete(SearchPanelAirportListUK, {
				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;
				}
			});
		});
	},

	datePickers: function() {

		var loadDates = function() {
			var today = new Date();
			Search.earliest = new Date(today.getFullYear(), today.getMonth(), today.getDate()+3);
			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.png',
			buttonImageOnly: true,
			showOn: 'both',
			minDate: Search.earliest,
			maxDate: Search.latest,
			onSelect: function(date, dp) {
				var search = $(this).parents('form>div').attr('id');

				var target = null;
				var val = null;
				var el = $(this);

				if (search == 'multi-mode'){
					target = el.parents('div.leg').next('div.leg').find('input.d');
				} else if (search == 'return-mode') {
					if ($(this).attr('id') == 'departdate')
						target = $('#returndate');
				}

				if (target && target.val() == 'dd/mm/yyyy') {
					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').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
		}));

		$('a.dpclose').live('click', function() { $('#ui-datepicker-div').hide(); });
	},

	validate: function(form) {
		var formObject = form.get(0);
		var errors = "";
		var searchType = form.find('input[name="searchType"]:checked').val();

		if (searchType == "MF") {

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

			for (var i = 0; i < noMultiStopLegs; i++) {
				if (i == 0) { blnUKOnly = true } else { blnUKOnly = false }
				errors += Search.validateAirport(formObject,"departureAirportCodes["+ i + "]","leg " + (i + 1) + " departure airport",blnUKOnly);
				errors += Search.validateAirport(formObject,"arrivalAirportCodes[" + i + "]","leg " + (i + 1) + " arrival airport",false);
				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 {
			errors += Search.validateAirport(formObject,'departurePoint','departure airport',true);
			errors += Search.validateAirport(formObject,'arrivalAirportCode','arrival airport',false);
			errors += Search.validateDate(formObject,'outboundDate','departure date','>',Search.earliest, "72 hours.\nFor reservations within the next 72 hours please call our Travel Centre on 0871 664968");

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

		// #5002 Flight only - Flexi- BKK restriction on 7 days
		var searchOutboundDateAry = Search.getValue(formObject,"outboundDate").split("/");
		var searchOutboundDate = new Date();
		searchOutboundDate.setFullYear(searchOutboundDateAry[2],searchOutboundDateAry[1] - 1,searchOutboundDateAry[0]);
		var today = new Date();
		var searchWithin7 = new Date(today.getFullYear(), today.getMonth(), today.getDate()+7);
		var restrictedAirport = $('input[name="arrivalAirportCode"]:first').val();
		if ((restrictedAirport == "Bangkok Suvarnabhumi Intl, Thailand (BKK)") && searchOutboundDate <= searchWithin7) {
			errors += "\nIf your desired departure date to Bangkok (BKK) is within 7 days from today's date you will be unable to book online. Please call our travel centre on freephone 0800 032 5492.";
		}
		// End of #5002

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

		$('#searchingfor').html(weAreSearchingFor);

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

		var airportCode;

		if (theAirport.length == 3)
			airportCode = theAirport.toUpperCase();
		else
			airportCode = theAirport.replace(/.*\(/,'').replace(/\).*/,'');

		for (var key in SearchPanelAirportList) {

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

		return false;
	},
	validUKAirport: function (theAirport) {

		var airportCode;

		if (theAirport.length == 3)
			airportCode = theAirport.toUpperCase();
		else
			airportCode = theAirport.replace(/.*\(/,'').replace(/\).*/,'');

		for (var key in SearchPanelAirportListUK) {

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

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

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

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

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

		if (blnUkOnly)
			if (!Search.validUKAirport(theAirport))
				return "\nDeparture is from a UK airport only.";

		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').find('span.bl10,span.br10').toggle();
				$('#agent-info').slideToggle(50);
				return false;
			});

			itnMsgHdr = 'Unable to continue because:\n';
			itnMsgTandC = '- You must agree to the Terms and Conditions to continue';
			itnMsgErrata = '- You must indicate that you have read the important information to continue\n';

			$('#holidaySummaryForm').bind('submit', function() {
				if ($('#tandc').attr('checked')) {
					submit = true;
				}
				else {
					alert(itnMsgHdr + itnMsgTandC);
					return false;
				}
				if ($('#acceptErrata').length != 0) {
					if ($('#acceptErrata').attr('checked')) {
						submit = true;
					}
					else {
						alert(itnMsgHdr + itnMsgErrata);
						return false;
					}
				}
			});

			$('a#continue-btn').click(function() {
				if ($('#tandc').attr('checked')) {
					submit = true;
				}
				else {
					alert(itnMsgHdr + itnMsgTandC);
					$.scrollTo('.smallprint');
					return false;
				}
				if ($('#acceptErrata').length != 0) {
					if ($('#acceptErrata').attr('checked')) {
						submit = true;
					}
					else {
						alert(itnMsgHdr + itnMsgErrata);
						$.scrollTo('.smallprint');
						return false;
					}
				}
				if (submit != false) {
					document.forms.holidaySummaryForm.submit();
				}
			});
						
			$('#flight-rules').appendTo('body');
			$('#multicom-rules').appendTo('body');
		});
	}
};

MultiStop = {
	init: function() {
		$(function(){
			$('ol#results.multi ul.options > li').addClass('bb').addClass('bt');
			$('ol#results.multi ul.options > li:first-child').addClass('first').removeClass('bt');
			$('ol#results.multi ul.options > li:last-child').removeClass('bb');
		});
	}
};
