//<![CDATA[
// Title: Tigra Form Validator
// URL: http://www.softcomplex.com/products/tigra_form_validator_pro/
// Version: 1.1
// Date: 09/14/2004 (mm/dd/yyyy)
// Notes: Registration needed to use this script legally. Visit official site for details.

// regular expressions or function to validate the format
var re_dt = /^(\d{1,2})\-(\d{1,2})\-(\d{4})$/,
re_tm = /^(\d{1,2})\:(\d{1,2})\:(\d{1,2})$/,

//alternativeEmailRegexp = /^[\w-\.]+\@[\w\.-]+\.[a-z]{2,4}$/,

a_formats = {
	'alpha'   : /^[-a-zA-Z\.]*$/,
	'alphapos'   : /^[-a-zA-Z\.\']*$/,
	'alphanum': /^\w+$/,
	'unsigned': /^\d+$/,
	'integer' : /^[\+\-]?\d*$/,
	'real'    : /^[\+\-]?\d*\.?\d*$/,
	'email'   : /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/,
	'phone'   : /^[\d\.\s\-]+$/,
	'date'    : function (s_date) {
		//reformat for regExp test
		s_date = ""+s_date.charAt(0)+s_date.charAt(1)+"-"+s_date.charAt(2)+s_date.charAt(3)+"-"+s_date.charAt(4)+s_date.charAt(5)+s_date.charAt(6)+s_date.charAt(7);
		
		
		// test for basic format
		if (!re_dt.test(s_date)){
			return false;
		}
		// test for value ranges
		if (RegExp.$1 > 31 || RegExp.$2 > 12){
			return false;
		}
		// test for invalid number of days in month
		//	MONTH IS ZERO-BASED IN JS DATE CONSTRUCTOR!!!
		var dt_test = new Date(Number(RegExp.$3), Number(RegExp.$2-1), Number(RegExp.$1));
		if (dt_test.getMonth() != Number(RegExp.$2-1)){
			//alert("month")
			return false;
		}
		// test for May -> October
		if ((dt_test.getMonth()>3)&&(dt_test.getMonth()<10)){
			//alert("May-Oct")
			return false;
		}
		// test for expired dates
		var dt_today = new Date();
		if (dt_today>dt_test){
			//alert("expired")
			return false;
		}
		return true;
	},
	'time'    : function validate_time(s_time) {
		// check format
		if (!re_tm.test(s_time))
			return false;
		// check allowed ranges	
		if (RegExp.$1 > 23 || RegExp.$2 > 59 || RegExp.$3 > 59)
			return false;
		return true;
	}
},
a_messages = [
	'No form name passed to validator construction routine',
	'No array of "%form%" form fields passed to validator construction routine',
	'Form "%form%" can not be found in this document',
	'Incomplete "%n%" form field descriptor entry. "l" attribute is missing',
	'Cannot find form field "%n%" in the form "%form%"',
	'Cannot find label tag (id="%t%")',
	'Cannot verify match. Field "%m%" was not found',
	'"%l%" is a required field',
	'Value for "%l%" must be %mn% characters or more',
	'Value for "%l%" must be no longer than %mx% characters',
	'"%v%" is not valid value for "%l%"',
	'"%l%" must match "%ml%"'
]

// validator counstruction routine
function validator(s_form, a_fields, o_cfg) {
	this.f_error = validator_error;
	this.f_alert = o_cfg && o_cfg.alert
		? function(s_msg) { alert(s_msg); return false }
		: function() { return false };
		
	// check required parameters
	if (!s_form)	
		return this.f_alert(this.f_error(0));
	this.s_form = s_form;
	
	if (!a_fields || typeof(a_fields) != 'object')
		return this.f_alert(this.f_error(1));
	this.a_fields = a_fields;

	this.a_2disable = o_cfg && o_cfg['to_disable'] && typeof(o_cfg['to_disable']) == 'object'
		? o_cfg['to_disable']
		: [];
		
	this.exec = validator_exec;
	this.additionalExec = validator_additionalExec;
	this.send = validator_submit;
}

function passenger_validator(s_form, a_fields, o_cfg) {
	this.f_error = validator_error;
	this.f_alert = o_cfg && o_cfg.alert
		? function(s_msg) { alert(s_msg); return false }
		: function() { return false };
		
	// check required parameters
	if (!s_form)	
		return this.f_alert(this.f_error(0));
	this.s_form = s_form;
	
	if (!a_fields || typeof(a_fields) != 'object')
		return this.f_alert(this.f_error(1));
	this.a_fields = a_fields;

	this.a_2disable = o_cfg && o_cfg['to_disable'] && typeof(o_cfg['to_disable']) == 'object'
		? o_cfg['to_disable']
		: [];
		
	this.exec = validator_exec;
	this.additionalExec = validator_additionalExec;
}


function validator_submit() {

	var o_form = document.forms[this.s_form];
	o_form.submit();
}

function validator_additionalExec() {

}

// validator execution method
function validator_exec() {
	var o_form = document.forms[this.s_form];
	if (!o_form)	
		return this.f_alert(this.f_error(2));
		
	b_dom = document.body && document.body.innerHTML;
	
	// check integrity of the form fields description structure
	for (var n_key in this.a_fields) {
		// check input description entry
		this.a_fields[n_key]['n'] = n_key;
		if (!this.a_fields[n_key]['l'])
			return this.f_alert(this.f_error(3, this.a_fields[n_key]));
		o_input = o_form.elements[n_key];
		if (!o_input)
			return this.f_alert(this.f_error(4, this.a_fields[n_key]));
		this.a_fields[n_key].o_input = o_input;
	}

	// reset labels highlight
	if (b_dom)
		for (var n_key in this.a_fields) 
			if (this.a_fields[n_key]['t']) {
				var s_labeltag = this.a_fields[n_key]['t'], e_labeltag = get_element(s_labeltag);
				if (!e_labeltag)
					return this.f_alert(this.f_error(5, this.a_fields[n_key]));
				this.a_fields[n_key].o_tag = e_labeltag;
				
				// normal state parameters assigned here
				e_labeltag.className = 'searchFormTitles';
			}

	// collect values depending on the type of the input
	for (var n_key in this.a_fields) {
		o_input = this.a_fields[n_key].o_input;
		if (o_input.type == 'text' || o_input.type == 'password' || o_input.type == 'hidden')
			this.a_fields[n_key]['v'] = stripSpace(o_input.value);
		else if (o_input.type == 'checkbox' && o_input.checked) {
			this.a_fields[n_key]['v'] = o_input.value;
			}
		else if (o_input.options) // select
			this.a_fields[n_key]['v'] = o_input.selectedIndex > -1
				? o_input.options[o_input.selectedIndex].value
				: null;
		else if (o_input.length > 0) // radiobutton
			for (var n_index = 0; n_index < o_input.length; n_index++)
				if (o_input[n_index].checked) {
					this.a_fields[n_key]['v'] = o_input[n_index].value;
					break;
				}
	}
	
	// check for errors
	var n_errors_count = 0,
		n_another, o_format_check;
	for (var n_key in this.a_fields) {
	
		o_format_check = this.a_fields[n_key]['f'] && a_formats[this.a_fields[n_key]['f']]
			? a_formats[this.a_fields[n_key]['f']]
			: null;

		// reset previous error if any
		this.a_fields[n_key].n_error = null;

		// check reqired fields
		if (this.a_fields[n_key]['r'] && !this.a_fields[n_key]['v']) {
			this.a_fields[n_key].n_error = 1;
			n_errors_count++;
		}
		// check length
		else if (this.a_fields[n_key]['mn'] && String(this.a_fields[n_key]['v']).length < this.a_fields[n_key]['mn']) {
			this.a_fields[n_key].n_error = 2;
			n_errors_count++;
		}
		else if (this.a_fields[n_key]['mx'] && String(this.a_fields[n_key]['v']).length > this.a_fields[n_key]['mx']) {
			this.a_fields[n_key].n_error = 3;
			n_errors_count++;
		}
		// check format
		else if (this.a_fields[n_key]['v'] && this.a_fields[n_key]['f'] && (
			(typeof(o_format_check) == 'function'
			&& !o_format_check(this.a_fields[n_key]['v']))
			|| (typeof(o_format_check) != 'function'
			&& !o_format_check.test(this.a_fields[n_key]['v'])))
			) {
			this.a_fields[n_key].n_error = 4;
			n_errors_count++;
		}
		// check match	
		else if (this.a_fields[n_key]['m']) {
			for (var n_key2 in this.a_fields)
				if (n_key2 == this.a_fields[n_key]['m']) {
					n_another = n_key2;
					break;
				}
			if (n_another == null)
				return this.f_alert(this.f_error(6, this.a_fields[n_key]));
			if (this.a_fields[n_another]['v'] != this.a_fields[n_key]['v']) {
				this.a_fields[n_key]['ml'] = this.a_fields[n_another]['l'];
				this.a_fields[n_key].n_error = 5;
				n_errors_count++;
			}
		}

	//add conditional on some other value - what other value? what condition?

	}

	// collect error messages and highlight captions for errorneous fields
	var s_alert_message = '',
		e_first_error;

	if (n_errors_count) {
		for (var n_key in this.a_fields) {
			var n_error_type = this.a_fields[n_key].n_error,
				s_message = '';
				
			if (n_error_type)
				s_message = this.f_error(n_error_type + 6, this.a_fields[n_key]);

			if (s_message) {
				if (!e_first_error)
					e_first_error = o_form.elements[n_key];
				s_alert_message += s_message + "\n";
				// highlighted state parameters assigned here
				if (b_dom && this.a_fields[n_key].o_tag)
					this.a_fields[n_key].o_tag.className = 'errorHighlight';
			}
		}
		alert(s_alert_message);
		// set focus to first errorneous field. As long as we can.
		if(e_first_error.type!="hidden"){
			if (e_first_error.focus){
				e_first_error.focus();
			}
		}
		// cancel form submission if errors detected
		return false;
	}
	
	for (n_key in this.a_2disable)
		if (o_form.elements[this.a_2disable[n_key]])
			o_form.elements[this.a_2disable[n_key]].disabled = true;

	if (additionalValidation!="") {
	
		var alertString = "";
		var fieldString = "";
		arSpans = new Array();
	
		for (i=0;i<additionalValidation.length;i=i+4) {
		

			ff = additionalValidation[i+1]; //form field name
			ffv = additionalValidation[i+2]; //form field value
			alt = additionalValidation[i+3]; //alert message

			if (additionalValidation[i].indexOf('|')!=-1) {
				
				dfa = additionalValidation[i].split('|'); //go through these - pull out the fieldname

				for (j=0;j<dfa.length;j=j+2) {
					if ((o_form.elements[dfa[j]].value == null || o_form.elements[dfa[j]].value == '') && (o_form.elements[ff].value == ffv)) {
						alertString += dfa[j+1] + "\n";
						arSpans[arSpans.length] = dfa[j+1];
					}
				}
			}

			else {
				df = additionalValidation[i]; //dependent field name
				if ((o_form.elements[df].value == null || o_form.elements[df].value == '') && (o_form.elements[ff].value == ffv)) {
					alertString += (alt + "\n");
					arSpans[arSpans.length] = df;
				}

			}
			
		}
		
		if (alertString!="") {
			alert(alertString);
			for (k=0;k<arSpans.length;k++) {
				z = document.getElementById(arSpans[k]).className = 'errorHighlight';
			}
			fieldString = "";
			alertString = "";
			return false;
		}
	}
	
	if (checkBoxConcat!="") {
	
	 for (l=0;l<checkBoxConcat.length;l=l+2) {
	 	
	 	var cbC = o_form.elements[checkBoxConcat[l]]; //checkboxes to concat
	 	var cbD = o_form.elements[checkBoxConcat[l+1]]; // field to insert values into
	 	var arBoxes = new Array();
	 	
	 	for (m=0;m<cbC.length;m++) {
	 		if (cbC[m].checked) {
	 			arBoxes[arBoxes.length] = cbC[m];
	 		}
	 	}
	 	if (arBoxes.length) {
	 		for (n=0;n<arBoxes.length;n++) {
	 			cbD.value+=arBoxes[n].value;
	 			if (n<(arBoxes.length-1)) cbD.value+='|';
	 			}
	 		arBoxes[arBoxes.length] = 0;
	 	}
	 	//alert(cbD.value);
	 }
	}
   
	if (submitByHref=='true') {
		o_form.submit();
	}
	if (submitByHrefRoomSel=='true') {
		return true;
	}
}

function validator_error(n_index) {
	var myDateFormat = /^(\d{8})$/
	var s_ = a_messages[n_index], n_i = 1, s_key;
	for (; n_i < arguments.length; n_i ++){
		for (s_key in arguments[n_i]){
			if (myDateFormat.test(arguments[n_i][s_key])){
				var myDateString = arguments[n_i][s_key];
				myDateString = ""+myDateString.charAt(0)+myDateString.charAt(1)+"-"+myDateString.charAt(2)+myDateString.charAt(3)+"-"+myDateString.charAt(4)+myDateString.charAt(5)+myDateString.charAt(6)+myDateString.charAt(7);
				s_ = s_.replace('%' + s_key + '%', myDateString);
			}else{
				s_ = s_.replace('%' + s_key + '%', arguments[n_i][s_key]);
			}
		}
		s_ = s_.replace('%form%', this.s_form);
	}
	return s_
}

function get_element (s_id) {
	return (document.all ? document.all[s_id] : (document.getElementById ? document.getElementById(s_id) : null));
}

//booking process room selection validation

function roomTypeValidator(theForm,theElement,theOtherElement) {

	var countRooms = 0;
	var countRoomCapacity = 0;
	var countRoomMinOcc = 0;
	var correspondingRoomIds = 0;
	var correspondingPassengerRoomIds = 0;
	var roomIds = new Array();
	var selectedRoomIds = new Array();
	var nSel = document.getElementsByTagName("select");

	for (i=0;i<nSel.length;i++) {
		if (nSel[i].className=='numberRooms') {
		countRooms += ((nSel[i].options[nSel[i].selectedIndex].value)-0);
		countRoomCapacity += (((nSel[i].getAttribute("maxCapacity")-0))*((nSel[i].options[nSel[i].selectedIndex].value)-0));
			if (nSel[i].options[nSel[i].selectedIndex].value!=0) {
				roomIds[roomIds.length] = nSel[i].getAttribute('associatedRoomId');
				roomIds[roomIds.length] = (((nSel[i].getAttribute("maxCapacity")-0))*((nSel[i].options[nSel[i].selectedIndex].value)-0));
				roomIds[roomIds.length] = (((nSel[i].getAttribute("minCapacity")-0))*((nSel[i].options[nSel[i].selectedIndex].value)-0));
			}
		}
	}

	for (j=0;j<radioGroups.length;j++) {
		rGp = theForm.elements[radioGroups[j]];
		if(rGp.length) {
			for (k=0;k<rGp.length;k++) {
				if (rGp[k].checked) {
					selectedRoomIds[selectedRoomIds.length] = rGp[k].value;
				}
			}
		}
		else {
			if (rGp.checked) {
				selectedRoomIds[selectedRoomIds.length] = rGp.value;
			}
		}
	}

	for(y=0;y<roomIds.length;y=y+3) {

		var temp = roomIds[y];
		var tempMin = roomIds[y+2];
		var tempCount = 0;

			for(z=0;z<selectedRoomIds.length;z++) {
				if(selectedRoomIds[z]==temp) {
					tempCount ++;
				}
			}
			if (tempCount>=tempMin); else countRoomMinOcc += 1;
		}

	var roomsOK = (countRooms>0) ? true : false;
	var roomsCapacityOK = (countRoomCapacity>=travellingPartySize) ? true : false;
	var roomsIdsOK = (selectedRoomIds.length == radioGroups.length) ? true : false;
	var minOccOK = (countRoomMinOcc==0) ? true : false;

	for(l=0;l<roomIds.length;l=l+3) {
		if (roomIds[l+1] > 0) { //only choose room ids for which we have selected capacity
			var temp = roomIds[l];
			for (m=0;m<selectedRoomIds.length;m++) {
				if (selectedRoomIds[m] == temp) {
					var b = selectedRoomIds.splice(m,1);
					m = m -1; //everything in the array moves back one place after splice....
					roomIds[l+1] = (roomIds[l+1]-1); //subtract one from the value of the selected max capacity
				}
			}
		}
	}

	var roomsAllocatedOK = (selectedRoomIds.length == 0) ? true : false;

	switch(roomsOK) {
		case true :
			switch(roomsCapacityOK) {
				case true:
					switch(roomsIdsOK) {
						case true :
								switch(roomsAllocatedOK) {
									case true :
											switch(minOccOK) {
												case true :
													theForm.submit();
												break
												case false :
														theRoomOccupancyAlert(theOtherElement)
												break
											}
									break
									case false :
										theRoomAllocationAlert(theOtherElement);
									break
								}
						break
						case false :
							theRoomAllocationAlert(theOtherElement);
						break
					}
				break
				case false:
					theRoomCapacityAlert(theElement);
				break
			}
		break
		case false :
			theRoomAlert(theElement);
		break
	}
}


function theRoomAlert(theElement) {
	document.getElementById(theElement).className = 'errorHighlight';
	alert('please select at least one room');
	return false;
}

function theRoomCapacityAlert(theElement) {
	document.getElementById(theElement).className = 'errorHighlight';
	alert('please choose enough room capacity for' + '\n' + 'the size of your party');
	return false;
}

function theRoomOccupancyAlert(theElement) {
	document.getElementById(theElement).className = 'errorHighlight';
	alert('please ensure you have met minimum occupancy' + '\n' + 'requirements for the type of your room');
	return false;
}

function theRoomAllocationAlert(theElement) {
	document.getElementById(theElement).className = 'errorHighlight';
	alert('please make sure that you choose a valid  room' + '\n' + 'for each member of your party -' + '\n' + 'you can change this later if you need');
	return false;
}

//options and extras validation

/*** Functions to validate person allocation to options and extras ***/

var timerId;
var ob = null;

function extraCode(codeSrc) {
	if(codeSrc.value=='' || codeSrc.value == null) codeSrc.value = 0;
	if((codeSrc.value-0)>=0) {
		fieldAlloc(codeSrc);
	}
}

//gets rid of this too - 

function winAlert() {
	alert("we can only accept whole numbers");
	setTimeout('extraCode(ob)',500);
}

function checkAlloc(obCheck) {

	//a checkbox calls this function
	//process flow is read from the onclick event of the checkbox

	var obField = obCheck.parentNode.parentNode;
	var costField = document.getElementById('cost' + obField.getAttribute('relatedId'));
	var idRef = obField.id.substring(3,obField.id.length);

	var allocationRow = document.getElementById('people' + obField.getAttribute('relatedId'));
	var ao = new allocationObject(document.getElementById(idRef),costField,allocationRow);
	ao.checkFromCb();
	
}

function fieldAlloc(obField) {

	//a text field containing a numeric entry calls this function
	//process flow is read from the onchange event of the field
	
	//changes to a select field making this call
	
	var costField = document.getElementById('cost' + obField.getAttribute('relatedId'));
	var allocationRow = document.getElementById('people' + obField.getAttribute('relatedId'));
	var ao = new allocationObject(obField,costField,allocationRow);
	if (allocationRow.getAttribute('fromLoad') != null) {
		ao.checkFromLoad();
	}
	else {
		ao.checkFromTf();
	}

}

function allocationObject(oField,oCostField,oAllocationRow) {
	
	this.obj = this;
	this.oField = oField;
	this.oCostField = oCostField;
	this.allocationRow = oAllocationRow;
	this.cBoxes = this.allocationRow.getElementsByTagName("input");
	this.alertDiv = this.allocationRow.getElementsByTagName("div")[0];
	this.checkSelectedBoxes = ao_checkSelectedBoxes;
	this.uncheckSelectedBoxes = ao_uncheckSelectedBoxes;
	this.showCalc = ao_showCalc;
	this.showDivCalc = ao_showDivCalc;
	this.checkRow = ao_checkRow;
	this.checkRowContents = ao_checkRowContents;
	this.destroy = ao_destroy;
	
	//this is like 'main' for text field - it does the things this needs to do from perspective of the text field onchange
	this.checkFromTf = ao_checkFromTf;

	//pre-populate calculation field on page load
	this.checkFromLoad = ao_checkFromLoad;

	//this is like 'main' for checkbox - it does the things this needs to do from perspective of the text field onchange
	this.checkFromCb = ao_checkFromCb;

}

function ao_uncheckSelectedBoxes() {

	for(i=0;i<this.cBoxes.length;i++) {
		this.cBoxes[i].checked = false;
	}

}

function ao_checkSelectedBoxes() {
//	for(i=0;i<this.oField.options[this.oField.selectedIndex].value;i++) {
	for(i=0;i<this.oField.value;i++) {
		this.cBoxes[i].checked = true;
	}

}

function ao_checkFromTf() {

	this.showCalc();
	this.checkRow();
	this.checkRowContents();
	this.destroy();

}

function ao_checkFromLoad() {

	this.showDivCalc();
	this.destroy();

}

function ao_checkFromCb() {

	var count = 0;

//other factor here - value - if value is greater than the num checkboxes

	if (this.oField.options[this.oField.selectedIndex].value > this.cBoxes.length) {
		this.checkRowContents(); //send the other alert
	}

	else {
		for(i=0;i<this.cBoxes.length;i++) {
			if(this.cBoxes[i].checked) count++;
		}
		if (count > this.oField.value) {
			this.alertDiv.innerHTML = "The Quantity of Extras you have chosen does not correspond to the number of Passengers that you have ticked. Please alter the Quantity correspondingly.";
			this.alertDiv.style.display = "";
			this.uncheckSelectedBoxes();
			this.oField.style.backgroundColor = "#FFCC33";
		}
		else {
			this.alertDiv.style.display = "none";
			this.oField.style.backgroundColor = "";		
		}
	}
}

function ao_showCalc() {
	//var amountSelected = this.oField.options[this.oField.selectedIndex].value;
	var amountSelected = this.oField.value;
	if (amountSelected==""){
		this.oCostField.innerHTML = '';
	}else{
		vl = (this.oField.getAttribute('extraPrice')-0)*(amountSelected);
		if (Math.round(vl*100)/100 < 0) {
			vl = '-&pound;'+ (Math.round(vl*100)/100) * (-1);
		} 
		else {
			vl = '&pound;'+Math.round(vl*100)/100;
		}
		if(vl!=""){
			if(vl.indexOf(".")>0){
				aPoundsAndPence = vl.split(".");
				sPence = aPoundsAndPence[1];
				if(sPence.length=1){
					vl = vl + "0";
				}
			}else{
				vl = vl + ".00"; 
			}
		}
		this.oCostField.innerHTML = vl;
	}
}

function ao_showDivCalc() {
	vl = (this.oField.getAttribute('extraPrice')-0)*(this.oField.getAttribute('multiple')-0);
	
	if (vl < 0) {
		vl = '-&pound;'+ vl * (-1);
	} 
	else {
		vl = '&pound;'+ vl;
	}
	if(vl!=""){
		if(vl.indexOf(".")>0){
			aPoundsAndPence = vl.split(".");
			sPence = aPoundsAndPence[1];
			if(sPence.length=1){
				vl = vl + "0";
			}
		}else{
			vl = vl + ".00"; 
		}
	}
	this.oCostField.innerHTML = vl;
}

function ao_checkRow() {

	//if((this.oField.options[this.oField.selectedIndex].value-0)>0){
	if((this.oField.value-0)>0){
		this.allocationRow.style.display = "";
	}else{
		this.allocationRow.style.display = "none";
	}

}

function ao_checkRowContents() {

	//if (this.oField.options[this.oField.selectedIndex].value > this.cBoxes.length) {
	if (this.oField.value > this.cBoxes.length) {
		this.alertDiv.innerHTML = "This is not a valid quantity for the number of people you have chosen to be in your party (infants are not included in extras)";
		this.alertDiv.style.display = "";
		this.uncheckSelectedBoxes();
		this.oField.style.backgroundColor = "#FFCC33";
	}
	else {
		this.alertDiv.style.display = "none";
		this.uncheckSelectedBoxes();
		this.checkSelectedBoxes();
		this.oField.style.backgroundColor = "";		
	}
}

function ao_destroy() {
	this.obj = null;
}

function extrasFormCheckAlloc(theForm) {

//confirm that the number in the text field matches the number allocated


	var stageOneValid = true;
	var selects = document.getElementsByTagName("select");

	for (z=0;z<selects.length;z++) {

		var c = 0;
			var tableRow = document.getElementById("people" + selects[z].getAttribute("relatedId"));
			var tableRowChecks = tableRow.getElementsByTagName("input");
				for (j=0;j<tableRowChecks.length;j++) {
					if(tableRowChecks[j].checked) {
					 c++;
					}
				}
			//if (selects[z].options[selects[z].selectedIndex].value==c) {
			if (selects[z].value==c) {
			}
			else {
				selects[z].style.backgroundColor='#FFCC33';
				selects[z].focus();
				alert("Please check the allocation of this item");
				stageOneValid = false;
				break;
			}

	}
	/*** all OK - because the number of checked checkboxes in the following row 
	equals the quantity entered in the quantity box selector ***/
	
	if (stageOneValid == true) {
		if (theForm.insuranceTerms.checked) {
				var ourInsurance = 0;
				var ownInsurance = 0;

						for (k=0;k<selects.length;k++) {
							//if (selects[k].name.substring(0,11)=='Option|INSR' && ((selects[k].options[selects[k].selectedIndex].value - 0) > 0) ) {
							if (selects[k].name.substring(0,11)=='Option|INSR' && ((selects[k].value - 0) > 0) ) {
								if (selects[k].name.substring(12,15)!='MOT') {
										ourInsurance = ourInsurance+(selects[k].value-0);	
								}
							}
						}

				if (theForm.ownInsurance.checked) {
					var regExpAlphaNum = /^[-a-zA-Z0-9\.\s\-\']*$/;
     				if (regExpAlphaNum.test(theForm.insuranceProviderName.value)){
						ownInsurance = 1;
					}else{
						alert('Please enter valid insurance provider details');
					}
				}
				if (((ownInsurance+ourInsurance)-0) > 0) {
					if (ownInsurance > 0 && ourInsurance > 0) {
								alert('Please choose only your own insurance or one of our range');
								window.scrollTo(0,0);
					}
					else {
						theForm.submit();
					}
				}
				else {
					alert('Please confirm that you have indeed arranged insurance');									
				}

		}
		else {
			alert("Please affirm you have read the insurance Terms and Conditions");
			theForm.insuranceTerms.focus();
		}
	}
	
}

function cWin(url,theWidth,theHeight){
	var theTop=(screen.height/2)-(theHeight/2);
	var theLeft=(screen.width/2)-(theWidth/2);
	var features=
	'height='+theHeight+',width='+theWidth+',top='+theTop+',left='+theLeft+",toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes";
	theWin=window.open(url,'t',features);
}
function showFormLayer(lyId) {
	document.getElementById(lyId).style.display = '';
}

	function stripSpace(inString) {
	  var spaces = inString.length;
	  for(var x = 1; x<spaces; x++){
	   inString = inString.replace(" ", "");
	 }
	 return inString;
	}


function date2string(yy,mm,dd) {
//alert(yy + ',' + mm + ',' + dd);
var returnstr;
returnstr = yy;
if (mm < 10) { returnstr += '0' } 
returnstr += mm;
if (dd < 10) { returnstr += '0' } 
returnstr += dd;
return returnstr;
}

/* Age-related validation */

var days = new Array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31);
var months = new Array("0","Jan","31","31","1","Feb","28","29","2","Mar","31","31","3","Apr","30","30","4","May","31","31","5","Jun","30","30","6","Jul","31","31","7","Aug","31","31","8","Sep","30","30","9","Oct","31","31","10","Nov","30","30","11","Dec","31","31");

function dobSelector(ptype,frm,dob) {

	this.form = document.forms[frm];

	this.ddField = this.form.elements[ptype+'DobDD'];
	this.mmField = this.form.elements[ptype+'DobMM'];
	this.yyField = this.form.elements[ptype+'DobYYYY'];

	this.dd;
	this.mm;
	this.yy;

 if (dob != null) {
  	this.dd = parseInt(dob.substr(6,2),10);
		this.mm = parseInt(dob.substr(4,2),10) -1
  	this.yy = parseInt(dob.substr(0,4),10);
	}
	
	this.depDate;
	this.depDateDay;
	this.depDateMonth;
	this.depDateYear;

	this.setBasics = ds_setBasics;
	this.setDepDate = ds_setDepDate;
	this.setDays = ds_setDays;
	this.setMonths = ds_setMonths;
	this.setYears = ds_setYears;
	this.putValues = ds_putValues;

	this.setBasics();
	this.setDepDate();
	this.setDays();
	this.setMonths();
	this.setYears();
	this.putValues();
	
	this.setValues = ds_setValues;

	this.check = ds_check;
	this.checkDate = ds_checkDate;

}

function addOption(txt,val,field) {
	g = new Option(txt,val);
	field.options[field.options.length] = g;
}

function y2k(number) { return (number < 1000) ? number + 1900 : number; }

function ds_setBasics() {
	addOption('...','',this.ddField);
	addOption('...','',this.mmField);
	addOption('...','',this.yyField);
}
function ds_setDepDate() {
	this.depDate = new Date(departureDate.substring(6,10),departureDate.substring(3,5)-1,departureDate.substring(0,2));
	this.depDateDay = this.depDate.getDate();
	this.depDateMonth = this.depDate.getMonth();
	this.depDateYear = y2k(this.depDate.getYear());
}

function ds_setDays() {
	for(i=0;i<days.length;i++) {
		addOption(days[i],days[i],this.ddField);
	}
}

function ds_setMonths() {
	for(i=0;i<months.length;i=i+4) {
		addOption(months[i+1],months[i],this.mmField);
	}
}

function ds_setYears() {
	var myDate = new Date();
	var thisYear = myDate.getFullYear();
	var validStartYear = this.depDateYear-(((this.ddField.getAttribute('maxAge')-0)+1)); //allow one less than dep date minus maxAge for possible yob
	var validEndYear = this.depDateYear-(((this.ddField.getAttribute('minAge')-0))); // New add for minAge 
	
	for(i=validEndYear;i>=validStartYear;i--) {
		addOption(y2k(i),y2k(i),this.yyField);
	}
}

function ds_setValues() {
	 this.dd = this.ddField.options[this.ddField.selectedIndex].value;
	 this.mm = this.mmField.options[this.mmField.selectedIndex].value;
	 this.yy = this.yyField.options[this.yyField.selectedIndex].value;
}

function ds_putValues() {
  for (i=0;i<this.ddField.options.length;i++) {
	  if (this.ddField.options[i].value == this.dd) { this.ddField.selectedIndex = i }
	 }
  for (i=0;i<this.mmField.options.length;i++) {
	  if (this.mmField.options[i].value == this.mm) { this.mmField.selectedIndex = i }
	 }
  for (i=0;i<this.yyField.options.length;i++) {
	  if (this.yyField.options[i].value == this.yy) { this.yyField.selectedIndex = i }
	 }
}

function ds_check() {
	this.setDepDate();
	this.setValues();
	if (this.yy > 0 && this.mm >= 0 && this.dd > 0) {
		this.checkDate(this.ddField.getAttribute('minAge')-0,this.ddField.getAttribute('maxAge')-0);
	}
	else {
		// do nothing at all.....
	}
}


function getMonthLength(month,year,julianFlag)
{
   var ml;
   if(month==1 || month==3 || month==5 || month==7 || month==8 || month==10||month==12)
      {ml = 31;}
   else {
       if(month==2) {
          ml = 28;
          if(!(year%4) && (julianFlag==1 || year%100 || !(year%400)))
             ml++;
       }
       else
          {ml = 30;}
   }
   return ml;
}


function ds_checkDate(minAge,maxAge)
{   
 var alertnum = 0;
	// the below check is to alert of any future dates
	var selectedDate = new Date(this.yy,this.mm,this.dd);	
	var today = new Date; // this needs to be set from server's to-date
	if (selectedDate > today) {
		alert(" You have selected a future date. Please correct. ");
		this.yyField.selectedIndex = 0;
		this.setDepDate;
		alertnum = alertnum + 1;
	}
	if (selectedDate.getMonth() != Number(this.mm)){
		alert(" The date you have entered is invalid. Please correct. ");
		this.yyField.selectedIndex = 0;
		this.setDepDate;
		alertnum = alertnum + 1;
	}
	
   // Month length 0->use calendar length
   var mLength = 0;
   // 0 if Gregorian, 1 is Julian
   var isJulian = 1;

   var ma=0;
   var ya=0;

   var da = this.depDateDay-this.dd;
   // This is the all-important day borrowing code.
   if(da<0)
   {
      this.depDateMonth--;
      // Borrow months from the year if necesssary.
      if(this.depDateMonth<1)
      {
	 this.depDateYear--;
	 // Determine no. of months in year
	 if(mLength)
	    {this.depDateMonth=this.depDateMonth+parseInt(365/mLength);}
	 else
	    {this.depDateMonth=this.depDateMonth+12;}
      }
      if(mLength==0) // Use real month length if no fixed
      {              // length is indicated - note that we add a leap day if necessary.
        ml=getMonthLength(this.depDateMonth,this.depDateYear,isJulian);
	 	da=da+ml;
      }
      // For this case, everything works like it did in elementary school.
      else
	 {da+=mLength;} // Use fixed month length
   }

   ma = this.depDateMonth - this.mm;
   // Month borrowing code - borrows months from years.
   if(ma<0)
   {
      this.depDateYear--;
      if(mLength!=0)
	 {ma=ma+parseInt(365/mLength);}
      else
	 {ma=ma+12;}
   }
   
   ya = this.depDateYear - this.yy;
   if ((ma/12) >= 1) { ya = ya + 1; }
  
   if(ya>=minAge && ya<=maxAge)  { }
   else if(this.mm != '' & alertnum < 1)
   {
      alert("The date of birth does not correspond with their age on date of return. Please re-enter your search criteria, ensuring that their age is correct on the date that you return to the UK");
      this.yyField.selectedIndex = 0;
      this.setDepDate;
   }

 }

function checkForCountry(selectedCountryValue, searchForm){
      var cname;
       if(selectedCountryValue=="CHL"){
       cname = "Chile";
      } else if (selectedCountryValue=="JPN"){
      cname = "Japan";
      }else if (selectedCountryValue=="LBN"){
	   cname = "Lebanon";
	  }else if (selectedCountryValue=="SWE"){
	   cname = "Sweden";
	  }else if (selectedCountryValue=="NOR"){
	   cname = "Norway";
	  }
      
	if(selectedCountryValue=="CHL" || selectedCountryValue=="JPN" || selectedCountryValue=="LBN" || selectedCountryValue=="SWE" || selectedCountryValue=="NOR"){
		alert("To book your holiday to " + cname +", please call our Custom Made reservations team on 0870 160 4090.");
		searchForm.countryList.selectedIndex = 0;	
       return false;
	}
return true;
 }
 
  function checkTotal(searchForm){
   
  var tadult = parseInt(searchForm.adults.options[searchForm.adults.selectedIndex].value);
  var tchild = parseInt(searchForm.children.options[searchForm.children.selectedIndex].value);
  var tinfant = parseInt(searchForm.infants.options[searchForm.infants.selectedIndex].value);
 	if((tadult + tchild) > 9){
		alert("It is not possible to book more than 9 passengers (adult & child) online. For group bookings please contact reservations on 0870 405 5047.");
		searchForm.children.selectedIndex = 0;
 	}
 	else if (tinfant > tadult) {
 		alert("Sorry, each infant must be accompanied by an individual adult." + tadult + " adults can carry maximum " + tadult + " infants only. ");
 		searchForm.infants.selectedIndex = 0;	 	
 	
	}
 
  }
 
 // function to close popup windows on body unload  
 var calWin;
 var mapWindow;
 function closePopup() {
   	if (calWin && calWin.open && !calWin.closed) calWin.close("cal"); //close calender
	if (mapWindow && mapWindow.open && !(mapWindow.closed)) mapWindow.close("Map"); // close piste map
 
}


 function checkMinThemeSelections(searchForm,max)
 {
	var ckCnt = 0;
	var ThemeName = searchForm.ThemeName
	ThemeName[0].value = ""
	ThemeName[1].value = ""
	ThemeName[2].value = ""
	for(i=0;i<searchForm.length;i++)
	{
		if (searchForm.elements[i].type == 'checkbox')
		{
		  if (searchForm.elements[i].checked)
		  {
			  ckCnt++;
			  if(ckCnt<=max)
			  {
				  ThemeName[ckCnt-1].value=searchForm.elements[i].name;
			  }
		  }
		}
	}

	if(ckCnt > max) {
		alert("Sorry, you can only select up to 3 themes.");
		return false;
	} 
	else if (ckCnt == 0) {
		alert("Please select between 1 and 3 themes.");
		return false;
	} 
 }
 
 function getSingleTheme(searchForm,checkThemeName)
 {
    var ThemeName = searchForm.ThemeName
    ThemeName[0].value = ""
    ThemeName[0].value=checkThemeName
    searchForm.submit()
 }

	function expandcollapse(objid) {
obj = document.getElementById(objid + 'desc')
objbutton = document.getElementById(objid + 'button')
  if (obj.style.display == 'none') {
  	obj.style.display = '';
  	objbutton.innerHTML = '-';
  } else {
  	obj.style.display = 'none';
  	objbutton.innerHTML = '+';
  }
}
//]]>
