var dob_pop = "<a href=\"/booking/information/dob.html\" onclick=\"popup_win('/booking/information/dob.html'); this.blur(); return false;\">Date of birth</a>";

var ERR_NOT_ENTITLED_CHILDREN = 0;
var ERR_DOB                   = 1;
var ERR_DEPARTURE_DATE        = 2;
var ERR_EMPTY_ROOM            = 3;
var ERR_DEPARTURE_DATE_FAR    = 4;
var ERR_NOT_ENTITLED_INFANTS  = 5;
var ERR_FUTURE_CHILDREN       = 6;
var ERR_FUTURE_INFANTS        = 7;
var ERR_DEPARTURE_PAST        = 8;
var ERR_NO_DESTINATION        = 9;

var ERROR = Array (
	 dob_pop + " at time of departure is not valid for a child", // ERR_NOT_ENTITLED_CHILDREN
	 "The date of birth you have entered is either not within the age ranges specified or is not in the correct format - dd/mm/yyyy.", // ERR_DOB
	 "Your chosen departure date is not valid. The correct date format is dd/mm/yyyy.", // ERR_DEPARTURE_DATE
	 "Rooms must have at least one adult or child", // ERR_EMPTY_ROOM
	 "We cannot offer departures online for your chosen date. Please try an alternative date or call us on 01306 747002", // ERR_DEPARTURE_DATE_FAR
	 dob_pop + " at time of departure is not valid for an infant", // ERR_NOT_ENTITLED_INFANTS
	 dob_pop + " entered for a child is in the future", // ERR_FUTURE_CHILDREN
	 dob_pop + " entered for an infant is in the future", // ERR_FUTURE_INFANTS
	 "The departure date you have chosen is in the past.", // ERR_DEPARTURE_PAST
	 "Please select a destination" // ERR_NO_DESTINATION
);

var routes = new Array();
routes.push(new Array('1', 'UK_FEAST_OZ'));
routes.push(new Array('2', 'UK_INDIA_OZ'));
routes.push(new Array('3', 'UK_AFR_OZ'));
routes.push(new Array('4', 'UK_USA_OZ'));
routes.push(new Array('5', 'UK_MEAST_OZ'));
routes.push(new Array('6', 'UK_OZ'));

/**
 * Returns the absolute layer's coordinate Y
 * @param obj the object (layer)
 */
function findPosY(obj_name)
{
	obj = document.getElementById(obj_name);
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}

/**
 * Returns the absolute layer's coordinate X
 * @param obj the object (layer)
 */
function findPosX(obj_name)
{
	obj = document.getElementById(obj_name);
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curtop += obj.x;
	return curtop;
}

function showHideDiv(divName)
{
   if (document.getElementById(divName))
   {
      new_style = (document.getElementById(divName).style.display == "none") ? "block" : "none";
      document.getElementById(divName).style.display = new_style;
   }
}

function hideDiv(divName)
{
   if (document.getElementById(divName))
   {
      document.getElementById(divName).style.display = 'none';
   }
}

function showDiv(divName)
{
   if (document.getElementById(divName))
   {
      document.getElementById(divName).style.display = 'block';
   }
}

function showHideLayer(layerName, actionType, frameName)
{
	//if no action specified, this function will toggle the current state	
	if (actionType == 2)
	{
		if (frameName != null)
		{
   	   new_style = (top.frames[frameName].document.getElementById(layerName).style.display != "none") ? "none" : "block";		   
		}
		else
		{
   	   new_style = (document.getElementById(layerName).style.display != "none") ? "none" : "block";
   	}   
   }
   else
   {
   	new_style = (actionType == 1) ? "block" : "none";
   }
   if (frameName != null)
	{
	   top.frames[frameName].document.getElementById(layerName).style.display = new_style;
	}
	else
	{
	   document.getElementById(layerName).style.display = new_style;
	}   
}

function showHideRooms(no)
{
	if (no == 1)
	{
		hideDiv('div_room_label');
	}
		
	if (no > 1)
	{
		showDiv('div_room_label');
	}

	for (i = 1; i <= 9; i++)
	{
		if (i <= no)
		{
			showDiv('div_room_' + i);
		}
		else
		{
			hideDiv('div_room_' + i);

			// Clear for contents for hidden rooms
			document.getElementById('room_' + i + '_adults').selectedIndex = 0;
			document.getElementById('room_' + i + '_children').selectedIndex = 0;
			document.getElementById('room_' + i + '_infants').selectedIndex = 0;
			for (j = 1; j <= 9; j ++)
			{
				div_content = '';
				document.getElementById('div_room_' + i + '_dob_' + j).innerHTML = div_content;
			}
		}
	}
}

// type: 1=children, 2=infants
function showHideDob(room, no, type)
{
	var dob_type = "";
	
	if (type == 1) dob_type = "_dob";
	else dob_type = "_dobi";
	
	showDiv('div_room_' + room + dob_type);

	for (var i = 1; i <= 9; i ++)
	{
		if (i <= no)
		{
			if (!show_status('div_room_' + room + dob_type + '_' + i))
			{
				showDiv('div_room_' + room + dob_type + '_' + i);
				var div_content = '<label for="room_' + room + dob_type + '_' + i + '">';
				
				if (type == 1) div_content += "Child ";
				else div_content += "Infant ";

				div_content += i + '</label><input type="text" id="room_' +
									room + dob_type + '_' + i + '" name="PDOB" class="form-text-date" value="dd/mm/yyyy" onfocus="date_focus(this)" onblur="date_blur(this)" />';
				document.getElementById('div_room_' + room + dob_type + '_' + i).innerHTML = div_content;
			}
		}
		else
		{
			if (1 || show_status('div_room_' + room + dob_type + '_' + i))
			{
				hideDiv('div_room_' + room + dob_type + '_' + i);
				div_content = '';
				document.getElementById('div_room_' + room + dob_type + '_' + i).innerHTML = div_content;
			}
		}
	}

	if (document.getElementById('room_' + room + '_children').value == 0)
	{
		hideDiv('div_room_' + room + "_dob");
	}
	if (document.getElementById('room_' + room + '_infants').value == 0)
	{
		hideDiv('div_room_' + room + "_dobi");
	}

renameDOBs(dob_type);
}

function show_status(divId)
{
	if (document.getElementById(divId).style.display == 'block')
	{
		return true;
	}
	else
	{
		return false;
	}
}

function renameDOBs(dob_type)
{
	var passengers = 0;

	for (var i = 1; i <= 9; i ++)  // loop rounds rooms
	{
		var no = parseInt(document.getElementById('room_' + i + '_adults').value);
		if (!(isNaN(no)))
		{
			passengers += no;
		}
		no = 0;

		if (dob_type == '_dobi')
		{
			no = parseInt(document.getElementById('room_' + i + '_children').value);
		}

		if (!(isNaN(no)))
		{
			passengers += no;
		}
		
		for (var j = 1; j <= 4; j ++)
		{
			if (show_status('div_room_' + i + dob_type + '_' + j))
			{
				passengers += 1;
				document.getElementById('room_' + i + dob_type + '_' + j).name = 'PDOB' + passengers + 'D';
			}
		}

		if (dob_type == '_dob')
		{		
			for (var j = 1; j <= 4; j ++) //loop round infants
			{
				if (show_status('div_room_' + i + '_dobi_' + j))
				{
					passengers += 1;
					document.getElementById('room_' + i + '_dobi_' + j).name = 'PDOB' + passengers + 'D';
				}
			}
		}
	}
}

function checkFormStep1()
{
	// Calculates total number of passengers
	passengers = 0;
	for (i = 1; i <= parseInt(document.getElementById('total_room_no').value); i ++)
	{
		no = parseInt(document.getElementById('room_' + i + '_adults').value);
		if (!(isNaN(no)))
		{
			passengers += no;
		}
		no = parseInt(document.getElementById('room_' + i + '_children').value);
		if (!(isNaN(no)))
		{
			passengers += no;
		}
		no = parseInt(document.getElementById('room_' + i + '_infants').value);
		if (!(isNaN(no)))
		{
			passengers += no;
		}
	}

	if (passengers > 9)
	{
		alert('You selected ' + passengers + ' passengers. Maximum number of passengers is 9');
		return false;
	}

	res_validate_dest = validate_destination();
	res_validate_dob = validate_dob();
	
	//Code added by ted to update the submit button to an animating gif	
	if(res_validate_dest==true && res_validate_dob==true){
	var targ = document.getElementById("booknowsearch");
	var waitingI = document.createElement("img");

	waitingI.setAttribute("src","/booking/images/searching-button.gif");
	
	waitingI.setAttribute("alt","Searching...");
	waitingI.setAttribute("width","157");
	waitingI.setAttribute("height","20");
	targ.appendChild(waitingI);
	targ.removeChild(targ.firstChild);
	}
	//------------------------------------------------
	
	return (res_validate_dest && res_validate_dob);


	
	

}

function findObj(n, d) { //v4.01

	var p,i,x;  
	if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) 
	{
		d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);
	}
	
	if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
	for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
	if(!x && d.getElementById) x=d.getElementById(n); return x;
}



function validate_destination()
{
	x=findObj('dest_single', document);
	if (x==null)
	{
		return true;
	}

	//UPDATE BY TED TO USE NEW RADIO BUTTON ID'S
	//if (document.getElementById('loc_usa').checked || document.getElementById('loc_nz').checked || document.getElementById('loc_za').checked || document.getElementById('loc_fe').checked)
	if (document.getElementById('dest_single').checked || document.getElementById('dest_multiple').checked || document.getElementById('dest_america_australasia').checked)
	{
		return true;
	}
	else
	{
		var err_div = document.getElementById('error_req_dest');
		if (err_div)
		{
			err_div.innerHTML = ERROR[ERR_NO_DESTINATION];
			showDiv('error_req_dest');
			Fat.fade_element('error_req_dest', 30, 1000, '#ff7979', '#E6F7FF');
		}
		return false;
	}

}

function change_loc(location){
	//return true;
	document.getElementById('req_location').className = "req_loc_" + location;

	document.getElementById('loc_label_usa').className = "loc_unsel";
	document.getElementById('loc_label_nz').className = "loc_unsel";
	document.getElementById('loc_label_za').className = "loc_unsel";
	document.getElementById('loc_label_fe').className = "loc_unsel";

	document.getElementById('loc_label_' + location).className = "loc_sel";
	//if(location == 'usa') hideDiv('tempo');

	if (document.getElementById('div_air_preferences'))
	{
		if (location == 'usa')
		{
			showDiv('div_air_preferences');
		}
		else
		{
			hideDiv('div_air_preferences');
			if (document.getElementById('sel_air_preference'))
			{
				document.getElementById('sel_air_preference').selectedIndex = 0;
			}
		}
	}
}

// Change CSS class for a given Object ID
function change_css(id, css_class)
{
	document.getElementById(id).className = css_class;
}

function date_blur(obj)
{
	if (obj.value == '')
	{
		change_css(obj.id, 'form-text-date');
		obj.value = 'dd/mm/yyyy';
	}
}

function date_focus(obj)
{
	if (obj.value == 'dd/mm/yyyy')
	{
		change_css(obj.id, 'form-text-date-filled');
		obj.value = '';
	}
}


function makeCalVisible()
{


	document.getElementById('cal-holder').style.display = "block";
   	tmp = document.getElementById('iframe_cal');	
	 
   	tmp.style.visibility = 'visible';
   	tmp.style.display = 'block';
   	tmp.style.left = findPosX('departure1') + "px";
   	tmp.style.top = findPosY('departure1') + 20 + "px";
}//end function makeCalVisible()


function toggleRecommended()
{
	var ua = navigator.userAgent.toLowerCase();
	isIE = (ua.indexOf('msie') != -1 && !this.isOpera && (ua.indexOf('webtv') == -1));
	if (document.getElementById('kuo_recomm').style.display == 'block')
	{
		hideDiv('kuo_recomm');
		hideDiv('div_white_space');
		if (isIE)
		{
			showDiv('no_of_nights');
			showDiv('sel_alt_destinations');
		}

	}
	else
	{
		if (isIE)
		{
			x = 95; y = 40;	
		}
		else
		{
			x = 110; y = 39;
		}
		
		document.getElementById('kuo_recomm').style.left = findPosX('kuo_recomm_link') - x + "px";
		document.getElementById('kuo_recomm').style.top = (findPosY('kuo_recomm_link') - y) + "px";
		showDiv('div_white_space');
		showDiv('kuo_recomm');
		location.hash='#kuo_recomm';
		if (isIE)
		{
			hideDiv('no_of_nights');
			hideDiv('sel_alt_destinations');
		}
	}
}


function noMoreRecomm(label)
{
	var other=0;
	(label == 1)? other=2 : other=1;
	document.getElementById("no_more_recomm" + other).checked = document.getElementById("no_more_recomm" + label).checked;
	if (document.getElementById("no_more_recomm" + label).checked)
	{
		var expdate = new Date ();
		FixCookieDate (expdate); // Correct for Mac date bug - call only once for given Date object!
		expdate.setTime (expdate.getTime() + (24 * 60 * 60 * 1000)); // 24 hrs from now
		SetCookie ("noMoreRecomm", el, expdate);
	}
	else
	{
		el = GetCookie ("noMoreRecomm");
		if (el)
		{
			DeleteCookie("noMoreRecomm");
		}
	}
}

function showRecomm()
{
	d = document.getElementById("kuo_recomm");
	if (d)
	{
		el = GetCookie ("noMoreRecomm");
		if (el)
		{
			document.getElementById("no_more_recomm1").checked = true;
			document.getElementById("no_more_recomm2").checked = true;
		}
		else
		{
			toggleRecommended();
		}
	}
}



function toggleDriving()
{
	var ua = navigator.userAgent.toLowerCase();
	isIE = (ua.indexOf('msie') != -1 && !this.isOpera && (ua.indexOf('webtv') == -1));
	if (document.getElementById('kuo_driving').style.display == 'block')
	{
		hideDiv('kuo_driving');
		if (isIE)
		{
			showDiv('no_of_nights');
			showDiv('sel_alt_destinations');
		}

	}
	else
	{
		if (isIE)
		{
			x = 95; y = 75;
		}
		else
		{
			x = 110; y = 50;
		}
		
		document.getElementById('kuo_driving').style.left = findPosX('kuo_driving_link') - x + "px";
		document.getElementById('kuo_driving').style.top = (findPosY('kuo_driving_link') - y) + "px";
		showDiv('kuo_driving');
		if (isIE)
		{
			hideDiv('no_of_nights');
			hideDiv('sel_alt_destinations');
		}
	}
}


function noMoreDriving(label)
{
	var other=0;
	(label == 1)? other=2 : other=1;
	document.getElementById("no_more_driving" + other).checked = document.getElementById("no_more_driving" + label).checked;
	if (document.getElementById("no_more_driving" + label).checked)
	{
		var expdate = new Date ();
		FixCookieDate (expdate); // Correct for Mac date bug - call only once for given Date object!
		expdate.setTime (expdate.getTime() + (24 * 60 * 60 * 1000)); // 24 hrs from now
		SetCookie ("noMoreDriving", el, expdate);
	}
	else
	{
		el = GetCookie ("noMoreDriving");
		if (el)
		{
			DeleteCookie("noMoreDriving");
		}
	}
}

function showDriving()
{
	d = document.getElementById("kuo_driving");
	if (d)
	{
		el = GetCookie ("noMoreDriving");
		if (el)
		{
			document.getElementById("no_more_driving1").checked = true;
			document.getElementById("no_more_driving2").checked = true;
		}
		else
		{
			toggleDriving();
		}
	}
}


function view_route(sessionId, transactionId, pageRoot)
{
	// Google API for http://www.kuoni.co.uk/ob/
	// ABQIAAAA_ZAvRz9gb1Y9tI-IEKUlWRSLTlRuRwzF9lAJy8np0Am7r86chBSKg4RPJCFKwt16lg_0TWlnJPaymA

	// Google API for http://www.agents.kuoni.co.uk/ob/
	// ABQIAAAA_ZAvRz9gb1Y9tI-IEKUlWRRzPOmuMOfWtaARdZAPvYQWxyVEqBQmgp3LMKl2w_OA3YBdDs24Lqczpg

	// Google API for http://10.80.64.12
	// ABQIAAAACgdwNgb3JMnH0Z9jOiJjrxRjN1q1-xlCuZ49KeAQl2a6m-WbhhQIE5d-hSbxkfWohKWlmHNAyaV_Rg

	// Google API for https://212.162.213.91
	// ABQIAAAA_ZAvRz9gb1Y9tI-IEKUlWRRisxSiiJK7sCbbm1vBGQKZ-7DXtBRNNQWeKNn1FhTBSP1k8w-U2Eh4VQ

	var on_server = "";
	var server_name = '212.162.213.91/oblae/';
	
	if (location.href.indexOf("10.80.64.12") != -1)
	{
		on_server = "_local";
		server_name = '10.80.64.12/ob/';
	} 
	else if (location.href.indexOf("www.kuoni.co.uk") != -1)
	{
		on_server = "_kuoni";
		server_name = 'www.kuoni.co.uk/ob/';
	}
	else if (location.href.indexOf("agents.kuoni.co.uk") != -1)
	{
		on_server = "_agents";
		server_name = 'agents.kuoni.co.uk/ob/';
	}
	
	pageurl = 'XSLT/google_map' + on_server + '.html?'+sessionId+','+transactionId;
	//pageurl = 'http://' + server_name + 'Booking/XSLT/google_map' + on_server + '.html?'+sessionId+','+transactionId;
	newwindow = window.open(pageurl, 'name', 'height=400, width=600');
	if (window.focus) {newwindow.focus()}
	return false;		
}

function selectAltDestination()
{
	document.getElementById("destination").value = document.getElementById("sel_alt_destination").value;
}

function addCarDestination(resort)
{
	document.getElementById("destination").value = resort;
	document.getElementById("travel_by_car").checked = true;
	toggleDriving();
}

function urlencode(str)
{
	var result = "";
	
	for (i = 0; i < str.length; i++) {
		if (str.charAt(i) == " ") result += "+";
		else result += str.charAt(i);
	}
	
	return escape(result);
}
function finaliseItineraryUrl(base_url)
{
	// Mean of transportation
	mt_value = 0;
	if (document.getElementById("travel_by_air"))
	{
		if (document.getElementById("travel_by_air").checked == true)
		{
			mt_value = document.getElementById("travel_by_air").value;
		}
	}
	if (document.getElementById("travel_by_car"))
	{
		if (document.getElementById("travel_by_car").checked == true)
		{
			mt_value = document.getElementById("travel_by_car").value;
		}
	}
	if (document.getElementById("travel_by_motorhome"))
	{
		if (document.getElementById("travel_by_motorhome").checked == true)
		{
			mt_value = document.getElementById("travel_by_motorhome").value;
		}
	}
	if (document.getElementById("travel_by_own"))
	{
		if (document.getElementById("travel_by_own").checked == true)
		{
			mt_value = document.getElementById("travel_by_own").value;
		}
	}
	base_url += '&TPTTPD=' + mt_value;
	
	// Destination
	if (document.getElementById("destination"))
	{
		base_url += '&RSTDSD=' + urlencode(document.getElementById("destination").value);
	}

	// Alternative destination
	if (document.getElementById("sel_alt_destination"))
	{
		base_url += '&RSTALT=' + urlencode(document.getElementById("sel_alt_destination").value);
	}

	// Number of nights
	if (document.getElementById("no_of_nights"))
	{
		base_url += '&NRNTSD=' + urlencode(document.getElementById("no_of_nights").value);
	}

	// Position where to insert the new destination
	if (document.getElementById("req_add_after"))
	{
		base_url += '&RSTNRD=' + urlencode(document.getElementById("req_add_after").value);
	}

	return base_url;

}

function toggleChangeDestination(number, destination, nights, transportation)
{
	// Finds allowed transportations for previous location
	prev_id = -1;
	prev_found = false;
	for (i = 0; i < trans_opt.length; i ++)
	{
		if (trans_opt[i][0] == number)
		{
			prev_found = true;
		}
		else if (!prev_found)
		{
			prev_id = i;
		}
	}
	if (prev_id > -1)
	{
		// Toggle allowed means of transportation
		if (trans_opt[prev_id][1] == 1)
		{
			showDiv('div_ch_flight');
		}
		else
		{
			hideDiv('div_ch_flight');
		}
		if (trans_opt[prev_id][2] == 1)
		{
			showDiv('div_ch_car');
		}
		else
		{
			hideDiv('div_ch_car');
		}
		hideDiv('div_ch_motorhome');
		showDiv('div_ch_own');
	}
	else
	{
		showDiv('div_ch_flight');
		hideDiv('div_ch_car');
		hideDiv('div_ch_motorhome');
		hideDiv('div_ch_own');
	}


	// Complete change destination form with selected destination's details
	document.getElementById("iti_change_destination_title").innerHTML = 'Change Details';
	switch (transportation)
	{
		case 1:
		{
			document.getElementById("ch_travel_by_air").checked = true;
			break;
		}
		case 2:
		{
			document.getElementById("ch_travel_by_car").checked = true;
			break;
		}
		case 3:
		{
			document.getElementById("ch_travel_by_motorhome").checked = true;
			break;
		}
		case 4:
		{
			document.getElementById("ch_travel_by_own").checked = true;
			break;
		}
	
	} // switch (transportation)

	document.getElementById("ch_dest_number").value = number;
	document.getElementById("ch_destination").value = destination;
	document.getElementById("ch_no_of_nights").selectedIndex = nights - 1;

	// Hide all destinations after destination that needs be changed
	i = number + 1;
	while (document.getElementById('div_dest_' + i) && i <= first_stage + no_of_stages - 1)
	{
		hideDiv('div_dest_' + i);
		i ++;
	}

	// Highlight changing destination
	document.getElementById('div_dest_' + number).style.backgroundColor = "#c2d6ff";
	document.getElementById(last_destination_div).style.backgroundColor = "#c2d6ff";

	hideDiv('iti_new_destination_form_holder');
	showDiv('iti_change_destination_form_holder');
	location.hash='#iti_change_destination_form_holder';
}

function cancelChangeDestination()
{
	// Show all destinations
	i = first_stage;
	while (document.getElementById('div_dest_' + i))
	{
		document.getElementById('div_dest_' + i).style.backgroundColor = "#FFFFFF";
		showDiv('div_dest_' + i);
		i ++;
	}
	document.getElementById(last_destination_div).style.backgroundColor = "#FFFFFF";

	hideDiv('iti_change_destination_form_holder');
	showDiv('iti_new_destination_form_holder');
}

function submitChangeDestination(base_url)
{

	// Mean of transportation
	mt_value = 0;
	if (document.getElementById("ch_travel_by_air"))
	{
		if (document.getElementById("ch_travel_by_air").checked == true)
		{
			mt_value = document.getElementById("ch_travel_by_air").value;
		}
	}
	if (document.getElementById("ch_travel_by_car"))
	{
		if (document.getElementById("ch_travel_by_car").checked == true)
		{
			mt_value = document.getElementById("ch_travel_by_car").value;
		}
	}
	if (document.getElementById("ch_travel_by_motorhome"))
	{
		if (document.getElementById("ch_travel_by_motorhome").checked == true)
		{
			mt_value = document.getElementById("ch_travel_by_motorhome").value;
		}
	}
	if (document.getElementById("ch_travel_by_own"))
	{
		if (document.getElementById("ch_travel_by_own").checked == true)
		{
			mt_value = document.getElementById("ch_travel_by_own").value;
		}
	}
	base_url += '&TPTTPD=' + mt_value;
	
	// Destination
	if (document.getElementById("ch_destination"))
	{
		base_url += '&RSTDSD=' + urlencode(document.getElementById("ch_destination").value);
	}

	// Number of nights
	if (document.getElementById("ch_no_of_nights"))
	{
		base_url += '&NRNTSD=' + urlencode(document.getElementById("ch_no_of_nights").value);
	}

	// Position where to insert the new destination
	if (document.getElementById("ch_dest_number"))
	{
		base_url += '&RSTNRD=' + urlencode(document.getElementById("ch_dest_number").value);
	}

	return base_url;

}

function debugform()
{
	alert(document.forms['AddDest'].elements['SSNIDD'].value);
}

function selectOutRoute(div, region_code)
{
	if (div != '')
	{
		if (outbound_route != '')
		{
			change_css('div_out_' + outbound_route, 'aus_route_subitem');
		}
		change_css('div_out_' + div, 'aus_route_subitem_selected');
		document.getElementById('rad_out_' + div).checked = true;
		document.getElementById('hid_out_region').value = region_code;
		for (i = 0; i < routes.length; i ++)
		{
			if (routes[i][0] == region_code)
			{
				document.getElementById('img_out_route').src = 'XSLT/images/routing_' + routes[i][1] + '.gif';
			}
		}
		outbound_route = div;
	}
}

function selectInRoute(div, region_code)
{
	if (div != '')
	{
		if (inbound_route != '')
		{
			change_css('div_in_' + inbound_route, 'aus_route_subitem');
		}
		change_css('div_in_' + div, 'aus_route_subitem_selected');
		document.getElementById('rad_in_' + div).checked = true;
		document.getElementById('hid_in_region').value = region_code;
		for (i = 0; i < routes.length; i ++)
		{
			if (routes[i][0] == region_code)
			{
				document.getElementById('img_in_route').src = 'XSLT/images/routing_' + routes[i][1] + '.gif';
			}
		}
		inbound_route = div;
	}
}
function checkForError()
{
	if (block_finalise == 1)
	{
		//change_css('span_add_dest_or_holder', 'add_dest_or_holder_disabled');
		change_css('but_add_dest_finalise', 'req_finalise_disabled');
	}
}

function showHideRouteOptions(div_options_id, div_title_id)
{
	direction = ((div_options_id.substring(4,5) == 'i') ? 'in' : 'out');
	region_code = parseInt(div_options_id.substring(div_options_id.length - 1,div_options_id.length));
	for (i = 0; i < routes.length; i ++)
	{
		if (routes[i][0] == region_code)
		{
			document.getElementById('img_' + direction + '_route').src = 'XSLT/images/routing_' + routes[i][1] + '.gif';
		}
	}
	
	if (!((document.getElementById(div_options_id).style.display != "none" && div_options_id == 'div_out_'+no_out_stopover && document.getElementById('rad_out_'+no_out_stopover+'_1').checked != true) || (document.getElementById(div_options_id).style.display != "none" && div_options_id == 'div_in_'+no_in_stopover && document.getElementById('rad_in_'+no_in_stopover+'_1').checked != true)))
	{
		showHideDiv(div_options_id);
		if (document.getElementById(div_options_id).style.display == "none")
		{
			change_css(div_title_id, 'aus_route_option')
		}
		else
		{
			change_css(div_title_id, 'aus_route_option_opened')
		}
	}
}

function checkRouteSelection()
{
	out_selected = false;
	frm = document.getElementById('frm_stopovers');
	for (i = 0; i < frm.elements['OBRNRD'].length; i ++)
	{
		if (frm.elements['OBRNRD'][i].checked)
		{
			out_selected = true;
		}
	}
	in_selected = false;
	for (i = 0; i < frm.elements['IBRNRD'].length; i ++)
	{
		if (frm.elements['IBRNRD'][i].checked)
		{
			in_selected = true;
		}
	}
	routes_selected = out_selected && in_selected;
	if (!routes_selected)
	{
		alert('Please select outbound and inbound routes.');
	}
	return routes_selected;
}

function popup_win(url)
{
	window.open(url, 'kuo_pp', 'height=400,width=700,scrollbars=yes,status=no,toolbar=no,menubar=no,location=no');
}



	function getYear(d)
	{
		return (d < 1000) ? d + 1900 : d;
	}

	
	function isDate (year, month, day)
	{
		month = month - 1;
		var tempDate = new Date(year, month, day);
		if ( (getYear(tempDate.getYear()) == year) && (month == tempDate.getMonth()) && (day == tempDate.getDate()) )
			return true;
		else
			return false
	}
	

	function dateDiff(a, b, type)
	{
		var date_a = a.split("/");
		var date_b = b.split("/");
		
		if (date_a.length == 3 && date_b.length == 3 && isDate(date_a[2], date_a[1], date_a[0]) && isDate(date_b[2], date_b[1], date_b[0]))
		{
			var date_a_ = new Date(date_a[2], date_a[1] - 1, date_a[0]);
			var date_b_ = new Date(date_b[2], date_b[1] - 1, date_b[0]);
			var tmp = date_a_.getTime() - date_b_.getTime();

			switch (type)
			{
				case 'years':
					// average no. of days / year =  365.25 * 86400 (sec. / day) = 31 557 600 seconds 
					return tmp / 31557600000; 
					break;
				case 'months':
					return tmp / 2628000000;
					break;
				case 'days':
					return tmp / 86400000;
					break;
				default:
					return tmp;
			}
		}
		else
		{
			return false;
		}
	}


function validate_dob()
{
/*
	tmp = document.getElementById('loc_usa');
	if (tmp)
	{
		if (!tmp.checked)
		{
			showDiv('tempo');
			Fat.fade_element('tempo', 30, 1000, '#ff7979', '#ffffff');
			return false;
		}
	}
*/	
	clear_dob_css();
	
	var error_msg = "";
			
	//departure date
	dep_date = document.getElementById('departure1');
	var dep_date_ = dep_date.value.split("/");
	if (dep_date_.length == 3 && isDate(dep_date_[2], dep_date_[1], dep_date_[0]))
	{
		var dep_date_stop = document.getElementById('date_stop').value;

		var dep_date_limit = new Date(parseInt(dep_date_stop.substring(0, 4)), parseInt(dep_date_stop.substring(4, 6)) - 1, parseInt(dep_date_stop.substring(6, 8)));
		var dep_date_date = new Date(dep_date_[2], dep_date_[1] - 1, dep_date_[0]);
		var curr_date = new Date();

		// verify if departure date is in the past
		if (dep_date_date.getTime() < curr_date.getTime())
		{
			error_msg += "<p>" + ERROR[ERR_DEPARTURE_PAST] + "</p>";
		}
		else
		{	
			// verify if departure date is greater than top limit
			if(dep_date_limit.getTime() < dep_date_date.getTime())
			{
				error_msg += "<p>" + ERROR[ERR_DEPARTURE_DATE_FAR];
				//+ dep_date_stop.substring(6, 8) + '/' + dep_date_stop.substring(4, 6) + '/' + dep_date_stop.substring(0, 4)
				error_msg += "</p>";
			}
			else
			{
				// holder of rooms / dates of birth
				tmp = document.getElementById('req_rooms');
				var inputs = tmp.getElementsByTagName('input');
				
				// arrays containing the elements (inputs) triggering warnings / errors
				var warning_inputs = Array();
				var error_inputs = Array();
				var diff = 0, div_holder;	
				var div_holder, room_div, is_visible;
				var warning_children = false;
				var warning_infants = false;
				var warning_children_fut = false;
				var warning_infants_fut = false;
		
				// iterate trough all visible input elements
				for (var i = 0; i < inputs.length; i++)
				{
					is_visible = false;
					
					if (inputs[i].style.display != 'none')
					{
						// the div containing all dob's of a room
						div_holder = inputs[i].parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode;
						if (div_holder.id && div_holder.style.display != 'none')
						{
							// the 'room' div
							room_div = div_holder.parentNode;
							if (room_div.id && room_div.style.display != 'none')
								is_visible = true;
						}
					}
				
				
					if (is_visible && inputs[i].id && inputs[i].id.indexOf('_dob') != -1)
					{
						
						diff = dateDiff(dep_date.value, inputs[i].value, 'years');
						if (diff === false)
						{
							error_inputs.push(inputs[i].id);
						}
						else
						{
		
							if (inputs[i].id.indexOf('_dobi') != -1)
							{
								// infant ages must be < 2
								if (diff > 2 || diff < 0)
								{
									warning_inputs.push(inputs[i].id);
	
									if (diff < 0)
										warning_infants_fut = true;
									else
										warning_infants = true;
								}
							}
							else
							{
								// children ages must be < 18
								if (diff > 18 || diff < 0)
								{
									warning_inputs.push(inputs[i].id);
									if (diff < 0)
										warning_children_fut = true;
									else
										warning_children = true;
								}
							}
							
						} // if (diff != false)
					}
				}
				
				if (warning_inputs.length > 0)
				{
					for (i = 0; i < warning_inputs.length; i++)
						document.getElementById(warning_inputs[i]).style.backgroundColor = "#f8ece6";
					if 	(warning_children) error_msg += "<p>" + ERROR[ERR_NOT_ENTITLED_CHILDREN] + "</p>";
					if 	(warning_infants) error_msg += "<p>" + ERROR[ERR_NOT_ENTITLED_INFANTS] + "</p>";
					if 	(warning_children_fut) error_msg += "<p>" + ERROR[ERR_FUTURE_CHILDREN] + "</p>";
					if 	(warning_infants_fut) error_msg += "<p>" + ERROR[ERR_FUTURE_INFANTS] + "</p>";
				}
		
				if (error_inputs.length > 0)
				{
					for (i = 0; i < error_inputs.length; i++)
						document.getElementById(error_inputs[i]).style.backgroundColor = "#EDFAFF";
					error_msg += "<p>" + ERROR[ERR_DOB] + "</p>";
				}
				
				//alert(warning_inputs.join());
				//alert(error_inputs.join());
			}
		}
	}
	else
	{
		error_msg += "<p>" + ERROR[ERR_DEPARTURE_DATE] + "</p>";
	}



	// validate room inhabitance (at least one adult or child per room)
	for(var j = 0; j < 9; j++)
	{
		var tmp3 = document.getElementById('div_room_' + j);

		if (tmp3 && tmp3.style.display != 'none')
		{
			var tmp1 = document.getElementById('room_' + j + "_children");
			var tmp2 = document.getElementById('room_' + j + "_adults");
			if (parseInt(tmp1.options[tmp1.selectedIndex].value) + parseInt(tmp2.options[tmp2.selectedIndex].value) == 0)
			{
				error_msg += "<p>" + ERROR[ERR_EMPTY_ROOM] + "</p>";
				break;
			}
		}
	}


	// on any error found
	if (error_msg != "")
	{
		var err_div = document.getElementById('error_req');
		if (err_div)
		{
			document.location.hash = "#error_req";

			//hide previous displayed errors
			var errors=document.getElementsByTagName('div');
			for (var k = 0; k < errors.length; k++)
			{
				if (!errors[k].id && errors[k].className == 'error')
				{
					errors[k].style.display = 'none';
				}
			}
			
			err_div.innerHTML = error_msg;
			showDiv('errors_req');
			showDiv('error_req');	
			Fat.fade_element('errors_req', 30, 1000, '#ff7979', '#EDFAFF');
		}
		return false;
	}

	// if no error was found, return true
	return true;
}

function clear_dob_css()
{
	// holder of rooms / dates of birth
	tmp = document.getElementById('req_rooms');
	var inputs = tmp.getElementsByTagName('input');
	
	// iterate trhrough all input elements
	for (var i = 0; i < inputs.length; i++)
	{
		if (inputs[i].id && inputs[i].id.indexOf('_dob') != -1)
		{
			inputs[i].style.backgroundColor = "#ffffff";
		}
	}
	hideDiv('errors_req');
}

function jumpToAdd()
{
	if (document.getElementById('kuo_recomm'))
	{
		if (document.getElementById('kuo_recomm').style.display != 'block')
		{
			location.hash='#iti_new_destination_form_holder';
		}
	}
	else
	{
		location.hash='#iti_new_destination_form_holder';
	}
}

function openRecommPage(page)
{
	for (i = 0; i < pk_pages.length; i ++)
	{
		if (parseInt(pk_pages[i][0]) == parseInt(page))
		{
			showDiv('div_recomm_pack_' + pk_pages[i][1]);
		}
		else
		{
			hideDiv('div_recomm_pack_' + pk_pages[i][1]);
		}
	}
	writePages(parseInt(page));
}

function writePages(current_page)
{
	var visible_pages = 5;
	var number_of_pages = pk_pages[pk_pages.length - 1][0];

	var min_shown_page = current_page;
	var max_shown_page = current_page;
	var shown_pages = 1;
	var changed = true;

	while (shown_pages < visible_pages && shown_pages < number_of_pages && changed)
	{
		changed = false;
		if (min_shown_page > 1)
		{
			min_shown_page -= 1;
			shown_pages += 1;
			changed = true;
		}
		if (max_shown_page < number_of_pages)
		{
			max_shown_page += 1;
			shown_pages += 1;
			changed = true;
		}
	}

	var content = '';
	if (current_page > 1)
	{
		content += '<a href="#" onclick="openRecommPage(1); return false;"><strong>&lt;&lt;</strong></a>&nbsp;&nbsp;';
		previous_page = current_page - 1;
		content += '<a href="#" onclick="openRecommPage(' + previous_page + '); return false;"><strong>&lt;</strong></a>&nbsp;&nbsp;';
	}
	else
	{
		content += '<strong style="color: gray;">&lt;&lt;&nbsp;&nbsp;&lt;</strong>&nbsp;&nbsp;';
	}
	var last_page = 0;
	for (i = 0; i < pk_pages.length; i ++)
	{
		if (pk_pages[i][0] >= min_shown_page && pk_pages[i][0] <= max_shown_page)
		{
			if (pk_pages[i][0] != last_page)
			{
				last_page = pk_pages[i][0];
				if (last_page == current_page)
				{
					content += '<strong>' + last_page + '</strong>&nbsp;';
				}
				else
				{
					content += '<a href="#" onclick="openRecommPage(' + last_page + '); return false;"><b>' + last_page + '</b></a>&nbsp;';
				}
			}
		}
	}
	if (current_page < number_of_pages)
	{
		next_page = current_page + 1;
		content += '&nbsp;<a href="#" onclick="openRecommPage(' + next_page + '); return false;"><strong>&gt;</strong></a>&nbsp;&nbsp;';
		content += '<a href="#" onclick="openRecommPage(' + number_of_pages + '); return false;"><strong>&gt;&gt;</strong></a>';
	}
	else
	{
		content += '&nbsp;<strong style="color: gray;">&gt;&nbsp;&nbsp;&gt;&gt;</strong>';
	}
	document.getElementById('div_pg_links_top').innerHTML = content;
	document.getElementById('div_pg_links_bottom').innerHTML = content;
}

function __attachEvent(elem, eventName, handler)
 {
	if (elem.attachEvent) // IE
		return elem.attachEvent("on" + eventName, handler);	
	else if (elem.addEventListener)
	{
		elem.addEventListener(eventName, handler, false);
		return true;
	}
	return false;
}
function __detachEvent(elem, eventName, handler)
{
	if (elem.detachEvent) // IE
		return elem.detachEvent("on" + eventName, handler);	
	else if (elem.removeEventListener)
	{
		elem.removeEventListener(eventName, handler, false);
		return true;
	}
	return false;
}

function prepare_interstitial()
{
	var tmpImage1 = new Image();
	tmpImage1.src = 'XSLT/images/interstitial_logo.gif';
	var tmpImage2 = new Image();
	tmpImage2.src = 'XSLT/images/interstitial_wait.gif';
	var tmpImage3 = new Image();
	tmpImage3.src = 'XSLT/images/interstitial_checked.gif';
	
	__attachEvent(window, "unload", hide_interstitial);
}

function hide_interstitial()
{
	hideDiv('interstitial');
	showDiv('kuo_container');	
}

function show_interstitial()
{
	hideDiv('kuo_container');	
	hideDiv('container');
	hideDiv('wizard');
	showDiv('interstitial');
}

function finaliseItinerary(url)
{
	if (block_finalise != 1)
	{
		show_interstitial();
		document.location = url;
		setTimeout('document.getElementById("img_interstitial_wait").src = "XSLT/images/interstitial_wait.gif"', 200); 
	}
}

