var logging = false;
var MAXIMUM_DRIVER_AGE = 75;
var MINIMUM_DRIVER_AGE = 21;

// emergency change prompted by ad tags stomping all over the global namespace
var DCPosition = Position;

// -------------------------------------------------------------------
//  Event extensions for observing sets of elements with a given name
// -------------------------------------------------------------------
Object.extend(Event, {

  observeElements: function(elementsName, name, observer, useCapture) {
  	var elements = document.getElementsByName(elementsName);
	if (elements) {
		for(var i = 0; i < elements.length; i++) {
			Event.observe(elements[i], name, observer, useCapture);
		}
	}
  },

  stopObservingElements: function(elementsName, name, observer, useCapture) {
  	var elements = document.getElementsByName(elementsName);
	if (elements) {
		for(var i = 0; i < elements.length; i++) {
			Event.stopObserving(elements[i], name, observer, useCapture);
		}
	}
  }
});

/*--------------------------------------------------------------------------
	DWR Error Handling
--------------------------------------------------------------------------*/
DWREngine.setWarningHandler(handleDWRError);
DWREngine.setErrorHandler(handleDWRError);
function handleDWRError() {};

/*--------------------------------------------------------------------------
	Shortcuts
--------------------------------------------------------------------------*/

setRB = function(elem,value) {
	setBoxValue(elem,value);
}

setSB = function(elem,value) {
	setSelectBoxValue(elem,value);
}

getRB = function(elem) {
	return getBoxValue(elem);
}


set = function(elem, value) {
	$(elem).value = value;
}

log = function(message) {
	if (logging) {
		new Insertion.Top('logger', message + "<br />");
		$('logger').style.display='block';
	}
}

/*--------------------------------------------------------------------------
	Functions
--------------------------------------------------------------------------*/

/* Dates */
disableDatesBeforeYesterday = function(date, y, m, d) {
	var today = new Date();
	if (date<today) {
		return "disabled";
	} else {
		return false;
	}
}

getHoursAgo = function(date)
{
	var now = new Date();
	var d = now.getTime() - date.getTime();
	//Get 1 hour in milliseconds
	var one_hour=1000*60*60;
	return Math.floor(d / one_hour);
}


onSelectEndDate = function(date) {
	if ($F('endDate') != $('endDate').origDate) {
		$('endDate').dirty = true;
	}
	$('endDate').value = date;
}

onSelectEndDateWhereErrors = function(date) {
	if ($F('endDate') != $('endDate').origDate) {
		$('endDate').dirty = true;
	}
	$('endDate').value = date;
}

onSelectStartDate = function(date) {
	var dCheck = DateValidator.checkDate(date);
	if (dCheck.valid) {
		$('startDate').value = date;
		if ($('endDate'))
		{
			var endDate = parseDate($('endDate').value);
			var startDate = parseDate(date);
			if ((!$('endDate').dirty) || (endDate<=startDate)) {
				$('endDate').value = formatDate(addDaysToDate(startDate,7));
			}
		}
	}
}

//////////////////////////////////////////////////////////////////////
// FIX - the following two functions are to fix the problem where
// two forms on the same page i.e. refineSearch and changeDates have
// the same name fileds the date pop up code we use does not like it.
// Please feel free to fix with nicely engineered solution!!
///////////////////////////////////////////////////////////////////////
onSelectStartDateFix = function(date) {
	var dCheck = DateValidator.checkDate(date);
	if (dCheck.valid) {
		document.search.startDate.value = date;
		if (document.search.endDate.value)
		{
			var endDate = parseDate(document.search.endDate.value);
			var startDate = parseDate(date);
			if ((!document.search.endDate.dirty) || (endDate<=startDate)) {
				document.search.endDate.value = formatDate(addDaysToDate(startDate,7));
			}
		}
	}
}

onSelectEndDateFix = function(date) {
	var dCheck = DateValidator.checkDate(date);
	if (dCheck.valid) {
		document.search.endDate.value = date;
	}
}

// End of fix

onSelectHolidayStartDate = function(date) {
    onSelectStartDate(date);
    updateNightsDuration('startDate', 'endDate', 'holidayNights');
}

onSelectHolidayDealStartDate = function(date) {
    onSelectStartDate(date);
    updateNightsDuration('startDate', 'endDate', 'holidayNights');
}

onSelectHolidayEndDate = function(date) {
    onSelectEndDate(date);
    updateNightsDuration('startDate', 'endDate', 'holidayNights');
}

updateNightsDuration = function(start, end, nights) {
    var days = getDiffInDays(parseDate($(start).value), parseDate($(end).value));
    if ($(nights)) {
    	Element.update(nights, (days > 0 ? days + " night" + (days > 1 ? "s" : "") : ""));
    }
}

disableDatesBeforeStartDate = function(date, y, m, d) {
	var startDate = parseDate($('startDate').value);
	if (date<=startDate) {
		return "disabled";
	} else {
		return false;
	}
}

addDaysToDate = function(date, d) {
	var futureDate = date.getTime();
	futureDate += (86400000 * d);
	date.setTime(futureDate);
	return date;
}

getDiffInDays = function(start, end) {
    return Math.round((end.getTime() - start.getTime()) / (1000*60*60*24));
}

parseDate = function(date) {
	var day = date.split("/")[0];
	var month = date.split("/")[1];
	var year = date.split("/")[2];
	return new Date(year, month-1, day);
}

validateDate = function(dateRep) {
	return DateValidator.checkDate(dateRep).valid;
//	try {
//		var d = parseDate(dateRep);
//		var t = d.getDay();
//		var ok = !isNaN(t);
//	}
//	catch (e) { }
//	return false;
	}

formatDate = function(date) {
	var m = addZero(date.getMonth()+1);
	return addZero(date.getDate()) + "/" + m + "/" + date.getFullYear();
}

formatDateVerbose = function(date) {
	var m = date.getMonth() + 1;
	var months = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];
	return months[date.getMonth()] + " " + addZero(date.getDate()) + ", " + date.getFullYear();
}

addZero = function(d) {
	d = parseInt(d);
	if (d<10) {
		d = ("0" + d);
	}
	return d;
}

escapeQuotes = function(value) {
	return (new String(value)).replace("'", "\\'");
}

/* General */
setBoxValue = function(elem, value) {
	var rb = document.getElementsByName(elem);
	for (i=0;i<rb.length;i++) {
		if (rb[i].value == value) {
			rb[i].checked = true;
		}
	}
}

setSelectBoxValue = function(elem, value) {
	var sb = $(elem);
	for (i=0;i<sb.options.length;i++) {
		if (sb[i].value == value) {
			sb[i].selected = true;
		}
	}
}

getBoxValue = function (elem) {
	var boxes = document.getElementsByName(elem);
	for (i=0;i<boxes.length;i++) {
		if (boxes[i].checked == true) {
			return boxes[i].value;
		}
	}
}

highlight = function(oDiv, colour) {
	oDiv.style.backgroundColor = colour;
}

hi = function(elem, state, colour) {
	elem.style.backgroundColor=color;
}

function bookmarkIt(url,title){
	if (document.all) {
		window.external.AddFavorite(url, title);
	}
	else {
		window.sidebar.addPanel(url, title, "");
	}
}



/* Login Register */
doDeal = function(realDealId) {
	logClick("DEAL"+realDealId);
	ajax.isSubscribed(realDealId,{callback:doPostIsSubscribed,errorHandler:doNothing});
}

doSubscribe = function(email, name, postcode,realdealid, position, response) {
	if (realdealid!=null && realdealid.length>0) {
		position = position + "-" + realdealid;
	}
	var postSubscribe = function(results)  {
		var status = results[0];
		if (status == 'ERROR') {
			doShowRegistrationErrors(results, response);
		} else if (status == 'SUCCESS') {
			if (results[1] != -1)
			{
				$('floatingSubscribeForm').style.display = 'none';
				set('float-name', '');
				set('float-postcode','');
				set('float-email','');
				showDealDescription(results[1]);
			}
		} else if (status == 'SUBSCRIBED') {
			var tracking = $('tracking-code-' + results[2]) ? $('tracking-code-' + results[2]).value : '';
			doShowMailMessage('<li>' + results[1] + tracking + '</li>', response);
		}
	}
	ajax.subscribe(email,name,postcode,realdealid,position,{callback:postSubscribe,errorHandler:doNothing});
}

showRegistration = function(location) {
	var result = {errorCode:location};
	doSubscriberError(result);
}


doSubscriberLogin = function(email, realdealid) {
	ajax.subscriberLogin(email,realdealid,{callback:doPostSubscribe,errorHandler:doNothing});
}

doPostSubscribe = function(results) {
	var status = results[0];
	if (status == 'ERROR') {
		doShowRegistrationErrors(results, 'mailMessage');
	} else if (status == 'SUCCESS') {
		if (results[1] != -1)
		{
			$('floatingSubscribeForm').style.display = 'none';
			set('float-name', '');
			set('float-postcode','');
			set('float-email','');
			showDealDescription(results[1]);
		}
	} else if (status == 'SUBSCRIBED') {
		doShowMailMessage('<li>' + results[1] + '</li>','mailMessage');
	}
}

doPostIsSubscribed = function(result) {
	var subscribed = result[0];
	if (subscribed == 'SUBSCRIBED') {
		//doForward(result[1]);
		showDealDescription(result[1]);
	} else {
		//ajax.getDeal(result[1],{callback:doShowRegisterForm,errorHandler:doNothing});
		//log("errors length: " + result[1]);
		doSubscriberError(result[1]);
	}
}

doSubscriberError = function(error) {
	$('float-realDealId').value = error.errorCode;
	if (error) {
		$('floatingSubscribeForm').style.display='block';
		$('float-name').focus();
	}
}

doShowRegistrationErrors = function(errors, elem) {
	var errorContent = '';
	for (var i=1;i<errors.length;i++)  {
		errorContent+='<li>' + errors[i].errorMessage + '</li>';
	}
	//log(errorContent);
	doShowMailMessage(errorContent,elem);
},

doShowMailMessage = function(message, elem) {
	//log(message);
	var msg = '<ul>';
	msg+=message;
	msg+='</ul>';

	$(elem).innerHTML = msg;
	new Effect.BlindDown(elem);
},

doForward = function(url) {
	document.location = url;
}

doShowRegisterForm = function(realdeal) {
	$('registerLoginHeader').innerHTML = realdeal.title;
	$('realDealId').value = realdeal.dealId;
	$('registerLogin').style.display='block';
}

doHide = function(elem) {
	$(elem).style.display = 'none';
	$(elem+'Errors').style.display = 'none';
}

showDealDescription = function(dealId) {
	ajax.getDeal(dealId,{callback:doPostShowDealDescription,errorHandler:doNothing});
}

doPostShowDealDescription = function(deal) {
	if (deal) {
		/* fill the bits and pieces */
		$('deal-info-title').innerHTML = deal.title;
		$('deal-info-shortDesc').innerHTML = deal.shortDescription;
        var price = '';
        if (deal.formattedPrice > 0) {
            price = '&pound;' + deal.formattedPrice;
        }
        $('deal-info-price').innerHTML = price;
		$('deal-info-book-top').href = deal.url;
		$('deal-info-book-bottom').href = deal.url;
		$('layerContentBot').innerHTML = deal.description //+ '<p><a href="javascript://nop" onclick="javascript:$(\'packageDealsLayer\').style.display=\'none\';">Close</a></p>';

		/* now show the div */
		$('packageDealsLayer').style.display = 'block';
	}
}

/* World66 */
doShowGuide = function(world66Id) {
	ajax.getWorld66Guide(world66Id, {callback:doPostShowGuide, errorHandler:doNothing});
}

doContentGuide = function(contentId) {
	ajax.getFullContent(contentId, {callback:doPostShowGuide, errorHandler:doNothing});
}

doPostShowGuide = function(result) {
	if (result!='-1') {
		//log(result);
		$('w66Guide').innerHTML = result;
	}
}

/*--------------------------------------------------------------------------
	Ajax Calls
--------------------------------------------------------------------------*/

doError = function(message) {
	//log("Error occurred: " + message);
	ajax.logError(message,{callback:doNothing,errorHandler:doNothing});
	doLoading(false);
}

/* XML Handler */
handleUrl = function(xml) {
	var root = xml.documentElement;
	//log("root: " + xml);

	var respNode = root.getElementsByTagName("response")[0];
	var itemNodes = respNode.getElementsByTagName("item");
	if (itemNodes.length > 0) {
		//log("items: " + itemNodes[0]);
		var url = getValueForNode(respNode, "static_url");
		var supplierId = getValueForNode(respNode, "supplier_id");
		$('url' + supplierId).value = url;
		log($('url' + supplierId).value);
	}
}

function getPropertyByName(node, nodeName) {
	var arr = new Array();
	var items = node.getElementsByTagName("name");
	for (var i=0; i<items.length; i++) {
		if (nodeName == items[i].firstChild.nodeValue) {
			arr[0] = items[i].firstChild.nodeValue;
			arr[1] = items[i].parentNode.getElementsByTagName("value")[0].firstChild.nodeValue;
			return arr;
		}
	}
	return null;
}

function getValueForNode(node, nodeName) {
	var arr = getPropertyByName(node, nodeName);
	return arr != null ? arr[1] : null;
}

/* Skinny Flight Search Form */
doValidateSkinny = function(elem, supplierId, type, desc, dest, supplierName, sessionId, searchbox) {
	submission = new searchForm.Validation();
	//log("doValidateSkinny " + type);
	var ret = submission.submitSkinny(type,elem,searchbox,'left', 'skinny');
	//var pars = Form.serialize('search');
	if (ret) {
		//log("loading skinny partner");
		loadPartner(supplierId, 'skinny', type);
	}
	//pars = pars + "&supplierId=" + supplierId + "&supplierName=" + supplierName;
	//var url = "/flights/validateSkinny.html";
	//var result = new Ajax.Request(url, {onComplete: onPostValidateSkinny, method: 'get', parameters: pars, asynchronous: true});
}

onPostValidateSkinny = function	(result) {
	if (result != null && result.status == 200) {
		handleUrl(result.responseXML);
	}
}


updateFlightSupplierUrl = function (supplierIndex, supplierName) {
	flightSearch = { destination:null, departure:null, ticketType:null, cabinClass:null, startDate:null, endDate:null, noAdults:null, noChildren:null, noInfants:null};
	DWRUtil.getValues(flightSearch);
	var tt = getRB('ticketType');
	flightSearch.ticketType = tt;
	var urlInput = $('url' + supplierIndex);
	//log("updating url");
	if (urlInput) {
		flights.generateFlightUrlWithSupplier(flightSearch,parseInt(supplierIndex),supplierName,{callback:doPostUpdateFlightSupplier,errorHandler:doNothing});
	}
}

doPostUpdateFlightSupplier = function(result) {
	//log('url' + result.supplierId + ' value: ' + result.staticURL);
	$('url' + result.supplierId).value = result.staticURL;
}

/* Flight Search Form */
isOneWay = function(state) {
	$('endDate').disabled=state;
	if ($('launchEndDate')) {
		$('launchEndDate').style.visibility = (state) ? 'hidden' : '';
	}
}

var searchForm = new Object();
searchForm.Base = function(){};
searchForm.Base.prototype = {};

searchForm.Validation = Class.create();
searchForm.Validation.prototype = {

	destination: 'destination',
	departure: 'departure',
	error: 'err',
	messages: 'messages',
	objectName: 'submission',
	searchName: 'search',
	output: 'destination', //prefix for destination field

	initialize: function(options) {
	},

	submit: function(type, elem,searchbox,whichway, searchType, searchName, err, departure, output){
		//log("type: " + type);
		this.searchType = searchType;
		this.searchbox = searchbox;
		this.type = type;
		this.elem = elem;
		this.whichway = whichway;
		if (output!=null) {
			this.output = output;
		}
		this.destination = this.output;
		if (searchName!=null) {
			this.searchName = searchName;
		}
		if (departure!=null) {
			this.departure = departure;
		}
		if (err) {
			this.error = err;
		}
        if (this.elem) {
            doLoading(true, this.elem, this.whichway);
        }

        if (this.type=='FLIGHTS') {
	        log("submit()" + this.type);
			var errors = this.validateFlightSearch($F(this.destination), $(this.departure).value,
			                                       $F('startDate'), $F('endDate'),
			                                       $('ticketTypeR').checked == true);
			return this.validateDestination(errors);
		} else if (this.type == 'HOTELS') {
			var errors = this.validateHotelSearch($F(this.destination), $F('startDate'), $F('endDate'));
			return this.validateDestination(errors);
		} else if (this.type == 'HOLIDAYS') {
            var errors = this.validateHolidaySearch($('destination').value, $('departure').value, $F('startDate'), $F('endDate'));
            return this.validateDestination(errors);
		} else if (this.type == 'HDYOFFER') {
            var errors = this.validateHolidaySearch($('destination').value, $('departure').value, $F('startDate'), $F('endDate'));
            return this.validateDestination(errors);
         } else if (this.type == 'CRUISE') {
            var errors = "";
            return this.validateDestination(errors);
		} else if (this.type == 'CARS') {
            var errors = this.validateCarSearch($F('driverAge'), $F('startDate'), $F('endDate'));
			return this.validateDestination(errors);
		} else if (this.type == 'LOWCOST') {
			var errors = this.validateLowCostSearch($F('dept'), $F('dest'), $F('startDate'), $F('endDate'));
			return this.validateDestination(errors);
		} else if (this.type == 'FLT-INS') {
			return this.validateFlightInspiration($F('dept'));
		}
		return false;
	},

	submitSkinny: function(type, elem, searchbox, whichway, searchType) {
		this.searchType = searchType;
		this.searchbox = searchbox;
		this.type = type;
		this.elem = elem;
		this.whichway = whichway;
		doLoading(true,this.elem, this.whichway);
		this.effect = new fx.FadeFromHidden('err', '1.0',{duration:400});
		if (this.type.indexOf('FLIGHTS')>=0) {
			//log("submitSkinny - type: " + this.type);
			//ajax.validateFlightSearch($F('startDate'),$F('endDate'),$F(this.destination),getRB('ticketType'), $(this.departure).value,{callback:doValidateDestination,errorHandler:doNothing});
			var errors = this.validateFlightSearch($F(this.output + 'Id'), $(this.departure).value);
			if (errors.length>0) {				setTimeout("doLoading(false);","500");
				this.displayErrors(errors);
			} else {
				return true;
			}
		} else if (this.type.indexOf('HOTELS')>=0) {
			ajax.validateHotelSearch({callback:this.postSubmit,errorHandler:doNothing});
		}
	},

	validateFlightSearch: function(destination, departure, startDate, endDate, validateBoth) {
		log("validateFlightSearch");
		var errors = [];
		var i=0;
		//log("validateFlightSearch" + destination);
		if (departure.length == 0) {
			errors[i] = "Please select a departure.";
			i++;
		}
		if (destination.length ==0) {
			errors[i] = "Please enter a destination.";
			i++;
		} else {
			this.validateDestinationId();
		}

		var vdf = this.validateDateFields(startDate, endDate, validateBoth, "Departure date", "return date");
		for (var j = 0; j < vdf.length; j++)
		{
			errors[i] = vdf[j];
			i++;
		}

		log ("dept" + departure + destination);
		if (destination.length>0 && (departure == destination)) {
			errors[i] = "Destination and departure airports can't be the same.";
			i++;
		} else if (departure == 'LGW' || departure == 'LHR' || departure=='LTN' || departure == 'STN' || departure == 'LCY') {
			if (destination == 'LON') {
				errors[i] = "Destination and departure airports can't be the same.";
				i++;
			}
		}
		return errors;
	},

	validateFlightInspiration: function(departure) {
		var errors = [];
		var i=0;
		if (departure.length == 0) {
			errors[i] = "Please select a departure.";
			i++;
		}
		if (errors.length > 0) {
			setTimeout("doLoading(false);","500");
			this.displayErrors(errors);
			return false;
		} else {
			this.handleSubmit();
		}
	},

	validateHotelSearch: function(destination, startDate, endDate) {
		var errors = [];
		var i=0;
		//log("validateHotelSearch" + destination);
		if (destination.length ==0) {
			errors[i] = "Please enter a destination.";
			i++;
		} else {
			this.validateDestinationId();
		}
		var vdf = this.validateDateFields(startDate, endDate, true, "check in date", "check out date");
		for (var j = 0; j < vdf.length; j++)
		{
			errors[i] = vdf[j];
			i++;
		}

		return errors;
	},

	validateHotelDetailsSearch: function(startDate, endDate) {
		var errors = [];
		var i=0;
		//log("validateHotelSearch" + destination);
		var vdf = this.validateDateFields(startDate, endDate, true, "check in date", "check out date");
		for (var j = 0; j < vdf.length; j++)
		{
			errors[i] = vdf[j];
			i++;
		}

		return errors;
	},

	validateCarSearch: function(age, startDate, endDate) {
		var errors = [];
		var i=0;
		if ($(this.departure) && $(this.destination)) {
			var pickup = $F(this.departure);
			var dropOff = $F(this.destination);
			if (pickup == null || pickup.length == 0) {
				errors[i] = "Please enter a pickup point.";
				i++;
			} else {
				this.validateDepartureId();
			}
			if (dropOff == null || dropOff.length ==0) {
				errors[i] = "Please enter a drop off point.";
				i++;
			} else {
				this.validateDestinationId();
			}
		} else {
			var pickupId = $F(this.departure + 'Id');
			var dropOffId = $F(this.destination + 'Id');
			if (pickupId == null || pickupId.length == 0) {
				errors[i] = "Please select a pickup point.";
				i++;
			}
			if (dropOffId == null || dropOffId.length == 0) {
				errors[i] = "Please select a drop off point.";
				i++;
			}
		}
		if (age == null || age.length == 0) {
			errors[i] = "Please enter the driver's age.";
			i++;
		} else if (age < MINIMUM_DRIVER_AGE || age > MAXIMUM_DRIVER_AGE) {
			errors[i] = "The driver's age must be between " + MINIMUM_DRIVER_AGE + " and " + MAXIMUM_DRIVER_AGE;
			i++;
		}
		var vdf = this.validateDateFields(startDate, endDate, true, "Pickup date", "dropoff date");
		for (var j = 0; j < vdf.length; j++)
		{
			errors[i] = vdf[j];
			i++;
		}
		return errors;
	},

	validateHolidaySearch: function(destination, departure, startDate, endDate) {
		var errors = [];
		var i=0;
		//log("validateHolidaySearch" + destination);
		if (departure.length == 0) {
			errors[i] = "Please select a departure.";
			i++;
		}
		if (destination.length ==0) {
			errors[i] = "Please enter a destination.";
			i++;
		}
		var vdf = this.validateDateFields(startDate, endDate, true, "Departure date", "return date");
		for (var j = 0; j < vdf.length; j++)
		{
			errors[i] = vdf[j];
			i++;
		}
		return errors;
	},


	validateLowCostSearch: function(departure, destination, startDate, endDate) {
		var errors = [];
		if (departure.length == 0) {
			errors[errors.length] = "Please select a departure.";
		}
		if (destination.length == 0) {
			errors[errors.length] = "Please select a destination.";
		}
		var dateFieldErrors = this.validateDateFields(startDate, endDate, true, "Departure date", "return date");
		for (var i = 0; i < dateFieldErrors.length; i++) {
			errors[errors.length] = dateFieldErrors[i];
		}
		return errors;
	},

	validateDestinationId: function() {
		if($F(this.output + 'Id')!=null && $F(this.output + 'Id').length>0) {
			if ($F(this.output + 'Current') != $F(this.destination)) {
				$(this.output + 'Id').value = '';
			}
		}
	},

	validateDepartureId: function() {
		if($F(this.departure + 'Id')!=null && $F(this.departure + 'Id').length>0) {
			if ($F(this.departure + 'Current') != $F(this.departure)) {
				$(this.departure + 'Id').value = '';
			}
		}
	},

	validateDateFields: function(start, end, validateBoth,
								startDateName, endDateName)
	{
		var sd = null, ed = null;
		var errors = [];
		var i = 0;
		var dCheck = DateValidator.checkDate(start);
		if (!dCheck.valid) {
			for (var j = 0; j < dCheck.errors.length; j++)
			{
				errors[i]= dCheck.errors[j];//"Please enter a valid start date (dd/mm/yyyy)";
			i++;
		}
		}
		else sd = parseDate(start);

		if (validateBoth) {
			dCheck = DateValidator.checkDate(end);
			if (!dCheck.valid) {
				for (var j = 0; j < dCheck.errors.length; j++)
				{
					errors[i]= dCheck.errors[j];//"Please enter a valid start date (dd/mm/yyyy)";
				i++;
			}
			}
			else ed = parseDate(end);
		}

		if (ed != null && sd != null && !(ed.getTime() > sd.getTime()))
		{
			errors[i] = endDateName + " should be after " + startDateName;
			i++;
		}

		return errors;
	},

	validateDestination: function(errors) {
		//log(errors.length);
		if (errors.length > 0) {
			setTimeout("doLoading(false);","500");
			this.displayErrors(errors);
			return false;
		}

		if (this.type == 'CARS') {
			if ($(this.departure) && $(this.destination)) {
				var pickupAccepted = this.isAutoSuggestAccepted(this.departure);
				var dropOffAccepted = this.isAutoSuggestAccepted(this.destination);
				if (pickupAccepted && dropOffAccepted) {
					return this.handleSubmit();
				} else {
					var _pi = pickupAccepted ? $F(this.departure + 'Id') : $F(this.departure);
					var _do = dropOffAccepted ? $F(this.destination + 'Id') : $F(this.destination);
					ajax.validateCarHireDestination(_pi, _do, {callback:this.postValidateDestination.bind(this),errorHandler:doNothing});
					return false;
				}
			} else {
				return this.handleSubmit();
			}
		} else {
            if (this.isAutoSuggestAccepted(this.destination)) {
	        	setTimeout("doLoading(false);","3000");
            	openPopUp(this.type);
				return this.handleSubmit();
			} else {
				if(this.type == 'FLIGHTS') {
					log("validateFlightDestination");
					ajax.validateFlightDestination($F(this.destination),{callback:this.postValidateDestination.bind(this),errorHandler:doNothing});
					return false;
				} else if (this.type == 'HOTELS') {
					ajax.validateHotelDestination($F(this.destination),{callback:this.postValidateDestination.bind(this),errorHandler:doNothing});
					return false;
				} else if (this.type == 'HOLIDAYS') {
                    ajax.validateHolidayDestination($F('departure'), $F('destination'),{callback:doPostValidateDestination,errorHandler:doNothing});
                    return false;
				} else if (this.type == 'HDYOFFER') {
                    ajax.validateHolidayOfferDestination($F('departure'), $F('destination'),{callback:doPostValidateDestination,errorHandler:doNothing});
                    return false;
				} else if (this.type == 'LOWCOST') {
					ajax.checkLowCostRouting($F('dept'), $F('dest'), $('ticketTypeR').checked, $F('startDate'), $F('endDate'), {callback:doPostValidateDestination,errorHandler:doNothing});
					return false;
				}
			}
			return true;
		}
	},

	isAutoSuggestAccepted: function(prefix) {
		return $(prefix + 'Id') && $F(prefix + 'Id') != null && $F(prefix + 'Id').length > 0
				&& $F(prefix + 'Current') == $F(prefix);
	},

	postValidation: function(errors) {
		if (errors.length>0) {
			setTimeout("doLoading(false);","500");
			this.displayErrors(errors);
		} else {
			return this.handleSubmit();
		}
	},

	postValidateDestination: function(errorBean) {
		//log("postValidateFlightDestination" + errorBean.errorCode);
        if (!errorBean.errorCode) {
            return this.handleSubmit();
        } else if (errorBean.errorCode=='DESTINATIONFOUND') {
			var airport = errorBean.data[0];
			$(this.output + 'Id').value = airport.airportCode;
			return this.handleSubmit();
		} else if (errorBean.errorCode=='TOOMANYAIRPORTS' || errorBean.errorCode=='TOOMANYAIRPORTNOSUPERCODE') {
			this.displayAirports(errorBean.data);
			setTimeout("doLoading(false);","500");
		} else if (errorBean.errorCode=='NOCITIES' || errorBean.errorCode=='NOAIRPORTS') {
			var ourErrors = [ 'Sorry, we couldn\'t find any matching destinations. Please enter a new destination.' ];
			this.displayErrors(ourErrors);
			setTimeout("doLoading(false);","500");
        } else if (errorBean.errorCode=='NO_ROUTES') {
            var ourErrors = [ 'Sorry, no holidays match your chosen departure and destination. Please try another depature airport.' ];
            this.displayErrors(ourErrors);
            setTimeout("doLoading(false);","500");
        } else if (errorBean.errorCode=='CARHIRE_DESTINATIONS') {
			var errors = new Array();
			var pickup = errorBean.data[0];
        	if (pickup != null) {
				if (pickup != $F(this.departure + 'Id')) {
		        	$(this.departure + 'Id').value = pickup;
		        	$(this.departure + 'Current').value = pickup;
	        	}
	        } else {
	        	errors[errors.length] = 'Sorry, we couldn\'t find any matching pickup locations.';
	        }
           	var dropOff = errorBean.data[1];
           	if (dropOff != null) {
				if (dropOff != $F(this.destination + 'Id')) {
		        	$(this.destination + 'Id').value = dropOff;
		        	$(this.destination + 'Current').value = dropOff;
	        	}
        	} else {
        		errors[errors.length] = 'Sorry, we couldn\'t find any matching drop-off locations.';
        	}

        	if (errors.length == 2) {
        		errors = [ 'Sorry, we couldn\'t find any matching pickup or drop-off locations.' ];
        	}

        	if (errors.length == 0) {
	        	return this.handleSubmit();
	        } else {
				this.displayErrors(errors);
				setTimeout("doLoading(false);","500");
	        }
        } else if (errorBean.errorCode == 'LOWCOST_ROUTINGS') {
        	this.displayErrors(errorBean.data);
        	setTimeout("doLoading(false);","500");
        }
	},

	handleSubmit: function() {
		//log("handleSubmit:" + this.searchName);
		if (this.searchType=='normal') {
			//log("submitting");
			$(this.searchName).submit();
		}
	},

	displayAirports: function(airports) {
		$(this.error).innerHTML = '';
		var airportContent = '<div style="margin-left:300px">[<a href=\"javascript://nop\" onclick=\"' + this.objectName +  '.hideDisplayAirports();\">cancel</a>]</div>' + '<h1>\"' + $(this.destination).value + '\" has more than one airport.</h1>Please select one from the list below:<br/>' + '<ul class="errorlist">';
		for (var i=0;i<airports.length;i++)  {
			airportContent+='<li><a href=\'javascript://nop\' class="airport" onclick=\'' + this.objectName +  '.setAirport(\"' + airports[i].cityName +  ' [' + airports[i].airportCode + ']' + '\");\'>' + airports[i].airportName + ', <b>' + airports[i].cityName +  '</b> [' + airports[i].airportCode + ']' + '</a></li>';
		}
		airportContent+='</ul>';
		$(this.messages + "Content").innerHTML = airportContent;
		var posXY = DCPosition.cumulativeOffset($(this.searchbox));
		var eBox = $(this.messages);
		eBox.style.top = (posXY[1]) + 80 + "px";
		eBox.style.left = (posXY[0]) + 10 + "px";
		this.createIframe(this.messages, 160, 365, eBox.style.top, eBox.style.left);
		Element.show($(this.messages));
		this.showIframe(this.messages);
		//eBox.style.width = $(this.searchbox).offsetWidth + "px";
	},

	createIframe: function(elem, height, width, top , left) {
		var posXY = DCPosition.cumulativeOffset($(this.searchbox));
		var i = document.createElement("IFRAME");
		i.setAttribute("id", $(elem).id + 'tmp');
		i.frameborder = 0;
		i.zIndex = $(elem).style.zIndex-1;
		i.style.top = top;
		i.style.left = left;
		i.style.width = width + "px";
		i.style.height = height + "px";
		i.style.position='absolute';
		i.style.visibility='hidden';
		//i.style.display='';
		document.body.appendChild(i);
	},

	hideDisplayAirports: function() {
		this.hideIframe(this.messages);
		Element.hide($(this.messages));
	},

	hideIframe: function(elem) {
		$(elem + 'tmp').style.visibility='hidden';
	},

	showIframe: function(elem) {
		$(elem + 'tmp').style.visibility='visible';
	},

	setAirport: function(airport) {
		$(this.destination).value = airport;
		this.hideDisplayAirports();
		//new Effect.Fade(this.messages);
		//this.handleSubmit();
	},

	displayErrors: function(errors) {
		var errorContent = '<ul>';
		for (var i=0;i<errors.length;i++)  {
			errorContent+='<li>' + errors[i] + '</li>';
		}
		errorContent+='</ul>';
		$(this.error).innerHTML = errorContent;
		new Effect.BlindDown(this.error);
	},

	hideErrors: function() {
		this.effect.hide();
	}
}

showErrors = function(errors, errorDiv) {
	var errorContent = '<ul>';
	for (var i=0;i<errors.length;i++)  {
		errorContent+='<li>' + errors[i].errorMessage + '</li>';
	}
	errorContent+='</ul>';
	$(errorDiv).innerHTML = errorContent;
	new Effect.BlindDown(errorDiv);
}

//
// consumes the enter keypress and performs a form submit if necessary. used in conjunction with submission.Validation.
consumeEnter = function(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8)
{
	var pK = document.all ? window.event.keyCode: -1;
	if (pK == 13) {
		return doSubmit(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8);
	}
}


z = function(elem){
	doLoading(true,elem, null);
	//$('search').submit();
}

function closeDivsByName(name) {
	var divs = document.getElementsByName(name);
	if (divs != null && divs.length > 0) {
		for (var i = 0; i < divs.length; i++) {
			divs[i].style.display = 'none';
		}
	} else  {
		divs = document.getElementsByTagName('div');
		for (var i = 0; i < divs.length; i++) {
			if (divs[i].name == name) {
				divs[i].style.display = 'none';
			}
		}
	}
}

doNothing = function(message) {
	log(message);
}

lightboxIt = function() {
	//log("startLightBox");
	getScroll();
	$('lightbox').style.width=window.outerWidth + "px";
	$('lightbox').style.height=window.outerHeight + 100 + "px";
	$('lightbox').style.display='block';
}

getScroll = function(){
	if (self.pageYOffset) {
		return self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){
		return document.documentElement.scrollTop;
	} else if (document.body) {
		return document.body.scrollTop;
	}
}

doSubmit = function(type,elem,searchbox,whichway, searchName, err, departure, object) {
	submission = new searchForm.Validation();
	submission.submit(type,elem,searchbox,whichway, 'normal', searchName, err, departure, object);
	return false;
}
// used only for HOTEL-DETAIL

var INVALID_SEARCH = -1;
var VALID_SEARCH = 1;
doValidationOnly = function(type,elem,searchbox,whichway, searchName, err, departure, object) {
	submission = new searchForm.Validation();
	var errors = submission.validateHotelDetailsSearch($F('startDate'), $F('endDate'));
	if (errors.length > 0) {
		submission.displayErrors(errors);
		return INVALID_SEARCH
	}
	return VALID_SEARCH;
}

processHotelDetailUrl = function(form, anchor, supplier, hotelId) {
	var result = doValidationOnly('HOTEL-DETAILS', form, 'search-box-content', 'right');
	if (result == VALID_SEARCH) {
		anchor.href = "/track.html?supplierId=" + supplier + "&t=hoteld&hotelId=" + hotelId + "&startDate=" + form.startDate.value + "&endDate=" + form.endDate.value + "&noAdults=" + form.noAdults.value + "&noChildren=" + form.noChildren.value + "&noRooms=" + form.noRooms.value + "&validSearch=true";
		anchor.target = "results_" + supplier;
		return true;
	} else {
		// invalid search details
		return false;
	}
}

handleHotelDetailCallBack = function(searchId, supplier) {
	var url = document.location.href.replace(/hotels.*$/, "/track.html?supplierId=" + supplier + "&t=hoteld&d=&s=" + searchId);
	alert(url);
	window.location = url;
	window.open();
	//document.location.href = url;
}

doValidateDestination = function(errors) {
	submission.validateDestination(errors);
}

doPostValidateDestination = function(errorBean){
	submission.postValidateDestination(errorBean);
}

doPostGetError = function(errors){
	submission.displayErrors(errors);
}

doDisplayErrors = function(errors) {
	elem = 'search-box-content';
	var posXY = DCPosition.cumulativeOffset($(elem));
	$('errors').style.top = posXY[1] + "px";
	$('errors').style.left = posXY[0] + $('search-box-content').offsetWidth + "px";
	error.show();
}

searchAgain = function(elem, errorDiv, startDate, endDate, startDateName, endDateName){
	var sfv = new searchForm.Validation();
	sfv.error = $(errorDiv);
	var errors = sfv.validateDateFields(startDate, endDate, true, startDateName, endDateName);
	if (errors.length > 0) {
		sfv.displayErrors(errors);
	}
	else
	{
		new Effect.BlindUp($(errorDiv));
		doLoading(true,elem, null);
		$('search').submit();
	}
}

doHideErrors = function() {
	error.hide();
}

doLoading = function(state, elem, whichway) {
	var eBox = $('loader');
	if(state) {
		var posXY = DCPosition.cumulativeOffset($(elem));
		//log("ebox" + posXY);
		if (whichway == 'right') {
			eBox.style.top = (posXY[1] + 10) + "px";
			eBox.style.left = (posXY[0] + 20) + "px";
		} else {
			eBox.style.top = (posXY[1] + 10) + "px";
			eBox.style.left = (posXY[0] + 20) + "px";
		}
		if (eBox.offsetLeft < 0) {
			eBox.style.left = 0;
		}
		if (eBox.offsetTop < 0) {
			eBox.style.top = 0;
		}
		eBox.style.display = 'block';
	} else {
		eBox.style.display = 'none';
	}
}

hideNanoTerms = function() {
	new Effect.Fade($('termsShadow'), {queue: 'front'});
	new Effect.Fade($('terms'), {queue: 'end'});
}

logClick = function(location) {
	ajax.logClick(location);
}

logClickWithDesc = function(location, description) {
	ajax.logClickWithDesc(location, description);
}

onDeal = function() {
	ajax.updateFlightSearchType('FLT-DEALS');
	Element.show('dealSearch');
	Element.hide('flightSearch');
}

onExact = function() {
	ajax.updateFlightSearchType('FLT-SEARCH');
	Element.show('flightSearch');
	Element.hide('dealSearch');
}

/*--------------------------------------------------------------------------*/

/**
	Helper method to capitalise the first letter of some text
*/
function capitaliseFirstLetter(word)
{
    var firstLetter = word.substring(0,1).toUpperCase();
    var restOfWord = word.substring(1, word.length);

    return (firstLetter + restOfWord);
}

// DC feedback window

showDialog = function(elem, dialog) {
	//$(dialog + 'Frm').reset();
	$(dialog + 'Response').innerHTML='';
	var posXY = DCPosition.cumulativeOffset($(elem));
	$(dialog).style.top = (posXY[1]) + 22 + "px";
	$(dialog).style.left = (posXY[0]) + "px";
	$(dialog + 'Shadow').style.top = (posXY[1]) + 22 + "px";
	$(dialog + 'Shadow').style.left = (posXY[0]) + "px";
	new Effect.Appear($(dialog + 'Shadow'));
	new Effect.BlindDown($(dialog));
}

showFeedback = function(elem) {
	$('feedbackFrm').reset();
	$('feedbackResponse').innerHTML='';
	var posXY = DCPosition.cumulativeOffset($(elem));
	$('feedback').style.top = (posXY[1]) + 22 + "px";
	$('feedback').style.left = (posXY[0]) + "px";
	$('feedbackShadow').style.top = (posXY[1]) + 22 + "px";
	$('feedbackShadow').style.left = (posXY[0]) + "px";
	new Effect.Appear($('feedbackShadow'));
	new Effect.BlindDown($('feedback'));
}

showContent = function(elem, point, left) {
	var posXY = DCPosition.cumulativeOffset($(point));
	$(elem).style.top = (posXY[1]) + 20 + "px";
	$(elem).style.left = (posXY[0]) + left + "px";
	$('shadow').style.top = (posXY[1]) + 20 + "px";
	$('shadow').style.left = (posXY[0]) + left + "px";
	new Effect.Appear($('shadow'));
	new Effect.BlindDown($(elem));
}

showNanoTerms = function() {
	var posXY = DCPosition.cumulativeOffset('nano');
	var terms = $('terms');
	terms.style.top = parseInt(posXY[1] + 120) + "px";
	terms.style.left = parseInt(posXY[0] + 60) + "px";
	$('termsShadow').style.top = parseInt(posXY[1] + 120) + "px";
	$('termsShadow').style.left = parseInt(posXY[0] + 60) + "px";
	new Effect.Appear($('terms'),{queue: 'front'});
	new Effect.Appear($('termsShadow'),{queue: 'end'});
}

hideContent = function(elem) {
	new Effect.Fade($('shadow'));
	new Effect.BlindUp($(elem));
}

hideFeedback = function() {
	new Effect.Fade($('feedbackShadow'));
	new Effect.BlindUp($('feedback'));
}

handleFeedback = function() {
	var v = function(errors) {
		if (errors.length==0) {
			var proxyFeedback = function(result) {
				$('feedbackResponse').innerHTML = "<b>Thanks!</b>";
				setTimeout("hideFeedback()","1500");
			}
			ajax.handleFeedback(getRB('rate'),getRB('friend'),$('feedbackComments').value,$('feedbackEmail').value, {callback:proxyFeedback});
		} else {
			var errorContent = '<ul>';
			for (var i=0;i<errors.length;i++)  {
				errorContent+='<li>' + errors[i].errorMessage + '</li>';
			}
			errorContent+='</ul>';
			$('feedbackResponse').innerHTML = errorContent;
			return false;
		}
	}
	ajax.validateFeedbackForm($('feedbackEmail').value, {callback:v});

}

validateFeedback = function() {
}

function doAttachCalendar() {
	attachCalendar("hdstartDate", "hdlaunchStartDate", onSelectHolidayDealStaticStartDate, disableDatesBeforeYesterday);
}

// **** calendar attach function ******************************
//
// Attaches a calendar to a given textfield.
//
// elementId : id of the input element to attach the calendar to.
// launchButton : id of the button that will be used to launch the calendar. optional.
// selectedFunc : function to run when something's been selected. optional.
// dateStatusFunc : function to help calendar to know which dates should be selectable
//                  at any given point in time.  optional.
//
function attachCalendar(elementId, launchButton, selectedFunc, dateStatusFunc)
{
	var params = {
		inputField     :    elementId,
        ifFormat       :    "%d/%m/%Y",
        daFormat       :    "%d/%m/%Y",
        align          :    "Br",
        weekNumbers    :    false,
        range          :    DateValidator.VALID_CALENDAR_YEARS,
        firstDay	   :    1,
        singleClick    :    true,
		electric	   :    false
	};

	if (launchButton != null) {
		params.button = launchButton;
	}

	if (selectedFunc != null) {
		var selectedBlurProxy = function() {
   			selectedFunc($F(elementId));
  		};
	    Event.observe($(elementId),"blur", selectedBlurProxy);
		var selectProxy = function(calendar, date) {
			selectedFunc(date);
            if (calendar.dateClicked) {
				calendar.callCloseHandler();
			}
		};
		params.onSelect = selectProxy;
	}
	if (dateStatusFunc != null) {
		var dateStatusProxy = function(date, y, m, d) {
			return dateStatusFunc(date, y, m, d, elementId)
		};
		params.dateStatusFunc = dateStatusProxy;
	}

    Calendar.setup(params);
}

launchBeenThere = function(direction) {
	logClick("LAUNCHBT");
	var bt = $('enterBeenThere');
	var btShadow = $('enterBeenThereShadow');
	bt.style.top = parseInt(130) + "px";
	bt.style.left = parseInt(30 + 10) + "px";
	new Effect.Appear('enterBeenThere');
	btShadow.style.top = parseInt(130) + "px";
	btShadow.style.left = parseInt(30 + 10) + "px";
	new Effect.Appear($('enterBeenThereShadow'));
}

sendBeenThere = function() {
	logClick("SENDBT");
	doLoading(true, 'btSend');
	var beenThere = {what: null, where: null, howToFind: null, tags: null};
	DWRUtil.getValues(beenThere);
	beenThere.email = $F('btEmail');
	var proxy = function(response) {
		var rh = new ResponseHandler('btErr','btErr');
		rh.handle(response);
		setTimeout("doLoading(false);","500");
	}
	ajax.sendTravelTip(beenThere,{callback:proxy});
}

hideBeenThere = function() {
	logClick("CLOSEBT");
	new Effect.Fade('enterBeenThere');
	new Effect.Fade('enterBeenThereShadow');
}

searchAgainSkinny = function(linkId, elem) {
	var state;
	if ($(elem).state=='up' || $(elem).state == 'down') {
		state=$(elem).state;
	} else {
		state = 'down';
	}
	if (state == 'down') {
		new Effect.BlindDown(elem);
		$(elem).state = 'up';
		$('searchAgainIcon').src="http://cdn-dev.dealchecker.co.uk:8080/images/common/minus.gif";
	} else {
		new Effect.BlindUp(elem);
		$(elem).state = 'down';
		$('searchAgainIcon').src="http://cdn-dev.dealchecker.co.uk:8080/images/common/plus.gif";
	}
}

validateLowCost1 = function() {
	//if (getRB('outbound').length==0 && getRB('inbound').length==0) {
	//	$('error').innerHTML = 'Please select an outgoing and return flights';
	//	new Effect.Highlight('error');
	//} else {
	//}
}

function getCookies() {
	var raw = document.cookie.split(';');
	var cookies = new Array();
	for (var i = 0; i < raw.length; i++) {
		var trimmed = raw[i].replace(/^\s*/, '').replace(/\s*$/, '');
		var split = trimmed.split('=');
		cookies.push({ key: split[0], value: split[1] });
	}
	return cookies;
}
// checks the dropoff fields for car hire and populates from the pickup fields
// if they are empty.  this is called from onblur listener on dropoff input
function checkCarHireDropoffFields()
{
	var curDo = $F('fs_do');
	if (curDo == null || curDo.length == 0) {
		$('fs_do').value = $('fs_pi').value;
		$('fs_doId').value = $('fs_piId').value;
		$('fs_doCurrent').value = $('fs_piCurrent').value;
	}
}

var Dialog = Class.create();
Dialog.prototype = {
	dialogId : null,
	contentId : null,

	getResponse: function(dialogId, contentId) {
		this.dialogId = dialogId;
		this.contentId = contentId;
		var result = TrimPath.processDOMTemplate('dialogbox', getContent());
	},

	getContent: function() {
		var content = {
			dialog : { main: this.dialogId, shadow: "shadow_" + this.dialogId, content :  $(contentId).innerHTML}
		};
	}
}


getSnippet = function(snippet, elem, type) {
	new Ajax.Updater(elem, '/snippet.html?snippet=' + snippet + '&type=' + type.value + '&' + Form.serialize($('search')), { method: "get",evalScripts: true});
}

getInsuranceSnippet = function(type, elem){
	var snippet= 'travel-insurance/'+type;

	new Ajax.Updater(elem, '/snippet.html?snippet=' + snippet, { method: "get",evalScripts: true});
}

getSnippetForRealBox = function(snippet, elem, type) {
	if ((type == "HTL" || type == "FLT-HTL") && $('destination') != null){
		$('destination').value = "";
	}

	$('flt-button').src = $('flt-button').src.replace("-hi", "-lo");
	$('htl-button').src = $('htl-button').src.replace("-hi", "-lo");
	$('hdy-button').src = $('hdy-button').src.replace("-hi", "-lo");
	$('car-button').src = $('car-button').src.replace("-hi", "-lo");

	if(type == "FLT"){
		$('flt-button').src = $('flt-button').src.replace("-lo", "-hi");
	}

	if(type == "HTL"){
		$('htl-button').src = $('htl-button').src.replace("-lo", "-hi");

	}
	if(type == "HDY"){
		$('hdy-button').src = $('hdy-button').src.replace("-lo", "-hi");
	}

	if(type == "FLT-HTL"){
		$('car-button').src = $('car-button').src.replace("-lo", "-hi");
	}

	new Ajax.Updater(elem, '/snippet.html?snippet=' + snippet + '&type=' + type + '&' + Form.serialize($('search')), { method: "get",evalScripts: true});




}

getStaBoxSnippet = function(snippet, elem, type) {
	new Ajax.Updater(elem, '/snippet.html?snippet=' + snippet + '&type=' + type + '&' + Form.serialize($('search')), { method: "get",evalScripts: true});
}


toggleSearch = function(state) {
	if (state=='on') {
		new Effect.BlindDown($('searchAgain'));
	} else if (state='off') {
		new Effect.BlindUp($('searchAgain'));

	}
}

submitCarHire = function() {
	ajax.logClick('CARCROSS');
	$('carHireCrossForm').submit();
}

submitHotelHire = function() {
	ajax.logClick('HOTELCROSS');
	$('hotelHireCrossForm').submit();
}

submitInsuranceCross = function() {
	ajax.logClick('INSCROSS');
	$('insuranceCrossForm').submit();
}


attachStaTravelForm = function(){

	if ($('staTravelFormBox').style.display == "block"){
		$('staTravelFormBox').style.display = "none";
		$('cross-sell-button-title-car').style.display = "block";
		$('cross-sell-button-title-hotel').style.display = "block";
		$('cross-sell-button-title-ins').style.display = "block";
		$('rightColMargNar').style.display = "block";
	}
	else{
		$('staTravelFormBox').style.display = "block";
		$('cross-sell-button-title-car').style.display = "none";
		$('cross-sell-button-title-hotel').style.display = "none";
		$('cross-sell-button-title-ins').style.display = "none";
		$('rightColMargNar').style.display = "none";
	}

}

 checkStaTravelDate = function(input){
 	if (input.value.length == 0 || input.value.length < 10){
 		$(input.id).value = "01/01/1970";
 	}
 	else {
 		if (input.value.match(/^[0-3]\d\/[0-1]\d\/[1-2]\d\d\d$/)){
 			var today = new Date();
 			var d = parseInt(input.value.substring(0,2));
 			var m = parseInt(input.value.substring(3,5));
 			var y = parseInt(input.value.substring(6,10));

 			if(d <= 31 && m <= 12 && y < parseInt(today.getYear())+1900 && y > 1930 && isValidMonth(m,d)){

 			}
 			else {
 				$(input.id).value = "01/01/1970";
 			}
 		}
 		else{
 			$(input.id).value = "01/01/1970";
 		}
 	}
 }

function isValidMonth(month, day){
 	switch(month){
 		case 4:
 		case 6:
 		case 9:
 		case 11:
 			return (day <= 30) ? true : false;
 		case 2:
 			return (day <= 28) ? true : false;
 	}
 	return true;
 }

 function getCruiseStartMonth(element, startMonth, startYear){
 	var month = new Array("January", "February", "March", "April", "May", "June",
 	"July", "August", "September", "October", "November", "December");

 	for(var i = 0; i < 12; i++){
 		if (startMonth == 12){
 			startMonth = 0;
 			startYear++;
 		}
 		var option = document.createElement("option");
 		var zero = "";
 		if ((startMonth+1) < 10)
 			zero = "0";
 		option.value= "01/"+zero+(startMonth+1)+"/"+startYear;
 		option.innerHTML = month[startMonth]+" "+startYear;
 		element.appendChild(option);
 		startMonth++;
 	}
 }


function handleInsuranceType(multi) {
	handleMultiTrip(multi);
	if (getRB('insuranceType')=='INS-65A' || getRB('insuranceType')=='INS-65S') {
		Element.show('family');
		Element.hide('policyType');
	} else {
		Element.show('policyType');
		Element.hide('family');

	}
}

resetInsurance = function() {
	for (var i=1;i<=6;i++) {
		$('age'+i).value ='';
		Element.hide('trav'+i);
	}
	Element.show('trav1');
	setSelectBoxValue('insurancePartySize', 1);
}


function updateNoAges() {
	resetInsurance();
	for (var i=1;i<=6;i++) {
		$('age'+i).value ='';
		Element.hide('trav'+i);
	}
	if ($F('policyType') == 'IND') {
		Element.hide('family');
		Element.show('trav1');
		setSelectBoxValue('insurancePartySize', 1);
		//alert($F('insurancePartySize'));
	} else if ($F('policyType') == 'COUPLE') {
		Element.hide('family');
		Element.show('trav1');
		Element.show('trav2');
		setSelectBoxValue('insurancePartySize', 2);
		//alert($F('insurancePartySize'));
	} else if ($F('policyType') == 'FAMILY') {
		setSelectBoxValue('insurancePartySize', 3);
		Element.show('trav1');
		Element.show('trav2');
		Element.show('trav3');
		Element.hide('opt1');
		Element.hide('opt2');
		Element.show('family');
	} else if ($F('policyType') == 'SGEPARENT') {
		setSelectBoxValue('insurancePartySize', 2);
		Element.show('trav1');
		Element.show('trav2');
		Element.hide('opt1');
		Element.hide('opt2');
		Element.show('family');
	}
}

function updateNoTravellers() {
	for (var i=1;i<=6;i++) {
		Element.hide('trav'+i);
	}
	for (var i=1;i<=$F('insurancePartySize');i++) {
		Element.show('trav'+i);
	}
}

function validateInsurance(form) {
	doLoading(true,'search-button-insurance', this.whichway);

	var postValidateInsurance = function (errors) {
		setTimeout("doLoading(false);","500");
		if (errors.length==0) {
			$('search').submit();
		} else {
			showErrors(errors, "err");
		}
	}
	var m = Form.serializeToMap($('search'));
	// hack to remove all access baggage that comes with $H - see prototype.js
	var formValues = new Object();
	m.each(function(pair) {
		formValues[pair.key] = pair.value;
	});
	ajax.validateInsurance(formValues,{callback:postValidateInsurance,errorHandler:doNothing});
}

String.prototype.addPossessive = function() {
	if (this.match(/ss$/) || this.match(/[^s]$/)) {
		return this + "'s";
	} else if (this.match(/s$/)) {
		return this + "'";
	} else {
		return this;
	}
}

function openProblemFeedbackForm(supplierId, imageName, supplierDisplayName) {
	var div = $('problemFeedbackContainer');
	var closeLink = $('problemFeedbackCloseLink');
	var messageDiv = $('problemFeedbackMessage');
	var form = $('problemFeedbackForm');
	var submitButton = form.elements['submit'];
	var radioButtons = form.elements['whatHappened'];
	var textArea = form.elements['additional'];

	logClick('PF-' + supplierId);


	// insert supplier-specific data
	form.elements['supplierId'].value = supplierId;
	$('problemFeedbackHeaderSupplierImage').innerHTML =
		'<img src="/images/suppliers/' + imageName + '" alt="' + supplierDisplayName + '" />';
	var supplierNameSpans = document.getElementsByClassName('problemFeedbackErrorPageOptionSupplierName');
	for (var i = 0; i < supplierNameSpans.length; i++) {
		supplierNameSpans[i].innerHTML = supplierDisplayName.addPossessive();
	}

	// attach event handler to the 'Close' link
	if (! closeLink.onclick) {
		closeLink.onclick = function() { div.style.display = 'none'; };
	}

	// disable form submit button
	submitButton.disabled = true;

	// initialise each radio button and its enclosing paragraph
	for (var i = 0; i < radioButtons.length; i++) {
		radioButtons[i].checked = false;

		// set up events on the paragraph
		var enclosingParagraph = $('whatHappened' + radioButtons[i].value);
		var firstAnchor = enclosingParagraph.getElementsByTagName('A')[0];
		Element.removeClassName(firstAnchor, 'selected');
		if (! enclosingParagraph.onclick) {
			// add 'selected' class and check radio button on click
			enclosingParagraph.onclick = (function() {
				var firstAnchor = this.getElementsByTagName('A')[0];
				Element.addClassName(firstAnchor, 'selected');
				for (var j = 0; j < radioButtons.length; j++) {
					var otherParagraph = $('whatHappened' + radioButtons[j].value);
					if (otherParagraph.id != this.id) {
						firstAnchor = otherParagraph.getElementsByTagName('A')[0];
						Element.removeClassName(firstAnchor, 'selected');
					} else {
						radioButtons[j].checked = true;
						submitButton.disabled = false;
					}
				}
			}).bindAsEventListener(enclosingParagraph);
		}
	}

	// clear out text area
	textArea.value = '';
	// set up event handler on the text area
	// (enables the submit button when text is present)
	if (! textArea.onkeyup) {
		textArea.onkeyup = function(e) {
			var radioButtonSelected = false;
			for (var i = 0; i < radioButtons.length; i++) {
				if (radioButtons[i].checked) {
					radioButtonSelected = true;
					break;
				}
			}
			submitButton.disabled = ! radioButtonSelected
				&& textArea.value.replace(/^\s+/, '').replace(/\s+$/, '').length == 0;
		};
	}

	// set up event handler on the submit button
	if (! submitButton.onclick) {
		submitButton.onclick = function() {
			new Ajax.Updater(messageDiv, '/problem-feedback.html', {
				postBody: Form.serialize(form),
				onComplete: function() {
					form.style.display = 'none';
					messageDiv.style.display = 'block';
					new Effect.BlindUp(div, {duration: 2});
				}
			});
			return false;
		};
	}

	// show div and form, hide message
	div.style.display = 'block';
	form.style.display = 'block';
	messageDiv.style.display = 'none';
}

//seo travel tips more and less buttons
function hideShowBlock(name ,id) {
  	var textId = name + "FullText" + id;
  	var buttonId = "button" + id;
  	var joinerId = name + "Joiner" + id;
  	if (document.getElementById(textId).style.display == '') {
  		document.getElementById(textId).style.display = 'none';
  		document.getElementById(joinerId).innerHTML = "... ";
  		document.getElementById(buttonId).innerHTML = "more";
  	} else if (document.getElementById(textId).style.display == 'none') {
  		document.getElementById(textId).style.display = '';
  		document.getElementById(joinerId).innerHTML = "";
  		document.getElementById(buttonId).innerHTML = "less";
  	}
}

/**
*
*  Javascript trim, ltrim, rtrim
*  http://www.webtoolkit.info/
*
*
**/

function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function checkRefineSearch(form, destinationParamName) {
	var dept1 = form.originalDeparture.value;
	var dept2 = form.departure.value;
	var dest1 = form.originalDestination.value;
	var dest2 = form[destinationParamName].value;
	var valid = ! (dept1 == dept2 && dest1 == dest2);
	if (! valid) {
		Effect.BlindDown('refineSearchError');
	}
	return valid;
}

function openPopUp(type) {
	var cookieValue = 'true';
	if (type == 'FLIGHTS' && cookieValue!='true' && $F('ticketTypeR')) {
		var popUpUrl = "/hotels/results-pop.html?crossSell=true&noAdults=1&nochildren=0&starRating=0&noRooms=1&startDate=" + $F('startDate') + "&endDate=" + $F('endDate') + "&destinationId=" + $F('fsId');
		var w = window.open(popUpUrl, "_blank", "width=381,height=345,resizable=1,scrollbars=1,status=0,toolbar=0,menubar=0,location=0,directories=0");
		w.blur();
	}
}

function doHolidayDealsSearch(searchId, elementId, partners) {
  new Ajax.Updater(elementId, '/holiday-deals-ajaxsearch/' + searchId + '.html?p=' + partners, { method: "get", evalScripts: true,
  	onComplete: function(transport) {
  	}
  });
}

function clearIfStartsWith(field, startsWith) {
	if (field.value.substring(0, startsWith.length) == startsWith) {
		field.value = "";
	}
}