//========================================================
// 	      File: p2_Octpous.js
//  Created by:	Clone New Zealand
// Created For: Flightcentre Ltd.
//     Authors:	B. Girimonti
//        Date:	28/03/2006
// plus update
//========================================================

function addOnLoad(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	}else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}

DOMHelper = {
				DGE:function(x){
					return document.getElementById(x);
				}
}
dh = DOMHelper;
dh.b = dh.DGE;
Date.prototype.isNorthAmerica = function(){
	return (this.getTimezoneOffset() < 660 && this.getTimezoneOffset() > 180);
	//return false;
}
Date.prototype.octopusDisplayFormat = function(){
	var mm = this.getMonth()+1;
	if(mm < 10) mm = "0" + mm;
	
	var dd = this.getDate();
	if(dd < 10) dd = "0" + dd;
	
	if(this.isNorthAmerica()){
		return mm + "/" + dd + "/" + this.getFullYear();
	}
	else{
		return dd + "/" + mm + "/" + this.getFullYear();
	}
}
// expDate = /^\d{1,2}\/\d{1,2}\/\d{2,4}$/
expDate =/(0[1-9]|[12][0-9]|3[01])[- \/.](0[1-9]|1[012])[- \/.](19|20)\d\d/;
today = new Date();
dFormat = today.isNorthAmerica()?"mm/dd/yyyy":"dd/mm/yyyy";
futureMonthLimit = 13;
//========================================================
// Function: makeEuroDate
// Purpose: Takes North American date format and converts it
// Inputs: string
// Outputs: date object
//--------------------------------------------------------
function makeEuroDate(str){
  	var vals = str.split("/");
  	var nDateString = vals[1] + "/" + vals[0] + "/" + vals[2];
  	return new Date(nDateString);
}
//========================================================
// Function: formatDateForURL
// Purpose: Prepends a zero to month and day portions to output 2 
// digits in each instance
// Input: Date object
// Output: string	
//--------------------------------------------------------
function formatDateForURL(d){
	var month = d.getMonth() + 1;
	if(month < 10) month = "0" + month;
	
	var date = d.getDate();
	if(date < 10) date = "0" + date;
	
	return d.getFullYear() + "-" + month + "-" + date;
}
//========================================================
// Function: getSelectedValue(id)
// Purpose: Returns the value of the chosen item in a drop-down list
// Inputs: string containing the name of the select object
// Output: string of the selected value
//--------------------------------------------------------
function getSelectedValue(id){
	try{
		var theSelect = DGE(id);
		return theSelect.options[theSelect.options.selectedIndex].value;
	}
	catch(Error){
	   return null;
	}
}
//========================================================
// Function: DGE
// Purpose: Returns element ID
// Input: string containing form field ID
// Output: integer referring to fields position in the  
// elements collection
//--------------------------------------------------------	
function DGE(x){
	return document.getElementById(x);
}
//========================================================
// Function: validateDate
// Purpose: Tests validity of a date
// Input: string representing a date
// Output: boolean representing whether or not the date
// string is valid
//--------------------------------------------------------
function validateDate(dateStr){
	if(!expDate.test(dateStr)) {return false;}
	var monthNumStr 	= today.isNorthAmerica() ? dateStr.split("/")[0]:dateStr.split("/")[1];
	var dateNumStr 		= today.isNorthAmerica()?dateStr.split("/")[1]:dateStr.split("/")[0];
	var yearNum 		= parseFloat(dateStr.split("/")[2]);
	var monthNum 		= parseFloat(monthNumStr);
	var dateNum 		= parseFloat(dateNumStr);
	var maxDate 		= 31;
	
	if(monthNum == 4 || monthNum == 5 || monthNum ==  6 || monthNum == 9 || monthNum == 11){
		maxDate = 30;
	}
	else if (monthNum == 2){
		if(yearNum %4 ==0) {maxDate = 29;}
	  	else{
		 	maxDate = 28;
	  	}
	}
	
	var bValid= (dateNum <= maxDate && dateNum > 0 && monthNum <= 12 && monthNum > 0);
	return bValid;
}
//========================================================
// Function: unselectRadios
// Purpose: Unchecks all radio buttons of a particular group
// Input: None
// Output: None
//--------------------------------------------------------
function unselectRadios(){
	var theRadio = null;
	var radios = document.getElementsByName("destinationRadio");
	
	for(var i=0;i<radios.length;i++){
		if(radios[i].checked==true) {
			theRadio = radios[i];
		}
	}
	if(theRadio != null) theRadio.checked=false;
}
//========================================================
// Function: resetDestination
// Purpose: Unselects drop-down list items from a 
// particuilar select
// Input: None
// Output: None
//--------------------------------------------------------
function resetDestination(){
	var d = dh.b("destination");
	d.options.selectedIndex=0;
}
//========================================================
// Function: DisplayCheckoutDate()
// Purpose: Calculates checkout date and displays it
// Input: None
// Output: None
//--------------------------------------------------------	
function DisplayCheckoutDate(){
	var numNights = parseInt(DGE("nights").value); //convert number of nights text to an integer
	var checkinDateVal = DGE("checkin").value; //grab text for checkin date
		
	if (checkinDateVal!="DD/MM/YY" && checkinDateVal!="") {
		var tDate = today.isNorthAmerica()?new Date(checkinDateVal):makeEuroDate(checkinDateVal);
		tDate.setDate(tDate.getDate() + numNights);
		if(tDate.octopusDisplayFormat()!="NaN/NaN/NaN")
			DGE("checkout").innerHTML = tDate.octopusDisplayFormat(); //Display Check-out date
	}
	return;
}
//========================================================
// Function: setCheckout
// Purpose: Unselects drop-down list items from a 
// particuilar select
// Input: None
// Output: None
//--------------------------------------------------------	
function setCheckout(){
	var numNights = parseInt(DGE("nights").value); //convert number of nights text to an integer
	var bError = false; //False implies all validation checks were successful
	var strValType;
	
	//Checks for a valid integer
	if(!isNaN(numNights)){
		var checkinDateVal = DGE("checkin").value; //grab text for checkin date
		
		if((numNights < 1 )||(numNights > 90)){
			alert("Date range between check-in and check-out must be between 1 and 90 days");
			//DGE("nights").focus();
			//DGE("nights").select();
			bError = true;
			//strValType = "nights";
		}
		
		/*
		if(!expDate.test(checkinDateVal)){
			alert("Check-in date format should be DD/MM/YYYY");
			//DGE("checkinSection").focus();
			//DGE("checkinSection").select();
			bError = true;
			//strValType = "checkinSection";
		}
		
		else if(!validateDate(checkinDateVal)){
		   alert("Check-in date is not valid");
		   //DGE("checkinSection").focus();
		   //DGE("checkinSection").select();
		   bError = true;
		   //strValType = "checkinSection";
		}

		else{
			//Generate check-out date
			var tDate = today.isNorthAmerica()?new Date(checkinDateVal):makeEuroDate(checkinDateVal);
			tDate.setDate(tDate.getDate() + numNights);
			DGE("checkout").innerHTML = tDate.octopusDisplayFormat(); //Display Check-out date
		
			//check to ensure the check-out date is within a year of today
			var datToday = new Date();
			var datYear = datToday.getFullYear();
			var datMonth = parseInt(datToday.getMonth() + 1);
			var datDay = parseInt(datToday.getDate() + 1);
			var datYFN = new Date();
					
			var endDate = new Date(datYFN.setFullYear(parseInt(datYear + 1)));
			var datEndYear = endDate.getFullYear();
			var datEndMonth = parseInt(endDate.getMonth() + 1);
			var datEndDay = parseInt(endDate.getDate());
			
			var fromDate = String(datDay + "/" + datMonth + "/" + datYear);
			var toDate = String(datEndDay + "/" + datEndMonth + "/" + datEndYear);
			
			var msg4 = "Please ensure valid dates in the range: Check-in: " + fromDate + " to Check-out: " + toDate;
			
			//Ensure no more than one year after check-in date
			if (tDate > endDate){
				alert(msg4);
				//DGE("checkinSection").focus();
				//DGE("checkinSection").select();
				bError = true;
				//strValType = "checkinSection";
			}
			//ensure check-in date is not before today
			if (tDate < datToday){
				alert(msg4);
				//DGE("checkin").focus();
				//DGE("checkin").select();
				bError = true;
				//strValType = "checkin";
			}
		}
		*/
	}
	else{
		alert("Number of nights must be a valid number between 1 and 90");
		//DGE("nights").select();
		//DGE("nights").focus();
		bError = true;
		strValType = "nights";
	}
		
	if (bError==true){
		return false;
	}
	else {
		return true;
	}		
}
//========================================================
// Function: makeURL
// Purpose: Builds URL string to post to. Also does some 
// general redundant validations
// Input: None
// Output: None
//--------------------------------------------------------	
function makeURL(){
	var destinationVal = getSelectedValue("scb_hotel_destination");
	var dradios = document.getElementsByName("destinationRadio");
	var dradioVal = "";
	
		
	for(var i=0;i<dradios.length;i++){
	   if(dradios[i].checked == true){
		 destinationVal= dradios[i].value;
	   }
	}
		
	var checkinVal 		= DGE("checkin").value;
	var nightsVal 		= DGE("nights").value;
	var roomtypeVal 	= getSelectedValue("roomtype");
	var roomsVal 		= getSelectedValue("rooms");
	var starratingVal 	= getSelectedValue("starrating");
	var languageVal 	= getSelectedValue("language");
	var currencyVal 	= getSelectedValue("currency");
	var bErrors 		= false;
	var errorMsg 		= "";
	var linebreak 		= "\n";
   	var bStatus 		= setCheckout(); 
	
	if(destinationVal == 0){
		errorMsg = "Please select a destination."  + linebreak;
		bErrors = true;
	}

/*	
	if(!expDate.test(checkinVal) ){
		errorMsg += "Please enter a checkin date in " + dFormat + " format."  + linebreak;
		bErrors = true;
	}
*/
	/*
	if(!validateDate(checkinVal)){
		errorMsg += "";
		bErrors = true;
	}
	*/
	
	if(isNaN(parseInt(nightsVal))){
		errorMsg += "Please enter the number of nights."  + linebreak;
		bErrors = true;
	}
	
	if (bErrors){
		alert(errorMsg);
		return;
	}
	
	if (!bStatus) {
		bErrors = true;
		return;
	}  
	
	var destinationArg = "&destination=" + destinationVal;
	var checkinArg = "";
	
	if(!expDate.test(checkinVal)){
		alert("The checkin date you entered must be in " + dFormat + " format");
	}
	else if(!validateDate(checkinVal)){
	   alert("Please enter a valid date");
	}
	else{
		var tDate = today.isNorthAmerica()?new Date(checkinVal):makeEuroDate(checkinVal);
		checkinArg = "&checkin=" + formatDateForURL(tDate);
	}
	
	var nightsArg= nightsVal == ""?"":"&nights=" + nightsVal;
	var roomtypeArg = "&roomtype=" + roomtypeVal;
	var roomsArg = "&rooms=" + roomsVal;
	var starratingArg = starratingVal == 0?"":"&starrating=" + starratingVal;
	var currencyArg = currencyVal == "0"?"":"&currency=" + currencyVal;
	var langArg= languageVal == "0"?"":"&language=" + languageVal;
	//var URLRoot = "http://www.octopustravel.com/HotelLink?country=AU&siteid=home";
	var URLRoot ="http://www.octopustravel.com/au/HotelLink?siteid=flightnz&country=NZ"
	//var URLRoot ="http://www.flightcentrehotels.co.nz/au/HotelLink?siteid=flightnz&country=NZ"
	var URL = URLRoot + destinationArg + checkinArg + nightsArg + roomtypeArg + roomsArg + starratingArg + currencyArg + langArg;
	
	var NewWidth = parseInt(screen.width * .75);
	var NewHeight = parseInt(screen.height * .75);
	
	//alert{"Height: " + NewHeight + "\nWidth: " + NewWidth);
	window.open(URL,"HotelSearch",'left=0,top=0,height=' + NewHeight + ',width=' + NewWidth + ',toolbar,titlebar,menubar,location,status,scrollbars,resizable');
}
//========================================================
// Function: init
// Purpose: Initialises and displays check-in and check-out 
// dates on load 
// Input: None
// Output: None
//--------------------------------------------------------		
function init(){
//   var co = DGE("checkout")
//   var ci = DGE("checkin");
//   var ciDate = new Date(today);
//   ciDate.setDate(ciDate.getDate() + 1)
//   ci.value = ciDate.octopusDisplayFormat();
 //  ciDate.setDate(ciDate.getDate() + 1);
//   co.innerHTML = ciDate.octopusDisplayFormat();
}
function goLink(URL){
	var NewWidth = parseInt(screen.width * .75);
	var NewHeight = parseInt(screen.height * .75);
	WinHotel = window.open('http://www.octopustravel.com/au/HotelLink?siteid=flightnz&country=NZ','HotelSearch','left=0,top=0,height=' + NewHeight + ',width=' + NewWidth + ',toolbar,titlebar,menubar,location,status,scrollbars,resizable');
	oTimeout = setTimeout('updateLink(\''+URL+'\')',2000);
}
function updateLink(URL){
	WinHotel.location.href=URL;
}
var WinHotel=null;
var oTimeout = null;
init();

