//////////////////////////////////////////////////////////////
// Global variables for form elements
// default values for flightInputForm set here
var FORM = "flightInputForm";
var DEPART_DAY = "selectedDay_1";
var DEPART_MONTH = "selectedMonth_1";
var RETURN_DAY = "selectedDay_2";
var RETURN_MONTH = "selectedMonth_2";
var FARE_CATEGORY = "selectedFareCategory";
var SEARCH_TYPE = "selectedSearchType";
var FLIGHT_TYPE = "selectedFlightType";
var ONE_WAY_FLAG = "oneWayFlag";
var LOC = "en";
var PROMOTIONAL_FARE = "promotionalFlights";

function disableFlexibleSearch(disable){
	if(disable == false){
		document[FORM][SEARCH_TYPE][0].disabled = false;
		document[FORM][SEARCH_TYPE][1].checked = false;
		document[FORM][SEARCH_TYPE][0].checked = true;
	}
	if(disable == true){
		document[FORM][SEARCH_TYPE][0].checked = false;
		document[FORM][SEARCH_TYPE][0].disabled = true;
		document[FORM][SEARCH_TYPE][1].checked = true;
	}
}

function initCorporateSearch(){
	document[FORM][PROMOTIONAL_FARE][0].checked=true;
	document[FORM][PROMOTIONAL_FARE][1].checked=false;
	document[FORM][SEARCH_TYPE][0].checked = false;
	document[FORM][SEARCH_TYPE][0].disabled = true;
	document[FORM][SEARCH_TYPE][1].checked = true;
}


//////////////////////////////////////////////////////////////
// This function populates the global variables for form elements
// This funciton should be called when values other than the default ones are needed.
function populateGlobalVars(newForm, newDepartDay, newDepartMonth, newReturnDay, newReturnMonth){
	FORM = newForm;
	DEPART_DAY = newDepartDay;
	DEPART_MONTH = newDepartMonth;
	RETURN_DAY = newReturnDay;
	RETURN_MONTH = newReturnMonth;
}

//////////////////////////////////////////////////////////////
//Update the global variables with new form values
//
function updateGlobalVars(newForm){

  DEPART_DAY = FORM+"."+DEPART_DAY;
  DEPART_MONTH = FORM+"."+DEPART_MONTH;
  RETURN_DAY = FORM+"."+RETURN_DAY;
  RETURN_MONTH = FORM+"."+RETURN_MONTH;
  FARE_CATEGORY = FORM+"."+FARE_CATEGORY;
  SEARCH_TYPE = FORM+"."+SEARCH_TYPE;
  FLIGHT_TYPE = FORM+"."+FLIGHT_TYPE;

  FORM = newForm;

}

function updateForm(newForm) {
	FORM = newForm;
}

//////////////////////////////////////////////////////////////
// This function disables the return date fields when oneway is selected
function disableRtnDate(disable){
	if (disable == true){
    document[FORM][RETURN_DAY].disabled=true;
		document[FORM][RETURN_MONTH].disabled=true;
		document[FORM][ONE_WAY_FLAG].value=true;
    document[FORM].selectedFlightType.value="ONEWAY";
	}else{
		document[FORM][RETURN_DAY].disabled=false;
		document[FORM][RETURN_MONTH].disabled=false;
    document[FORM][ONE_WAY_FLAG].value="false";
    document[FORM].selectedFlightType.value="RETURN";
	}
}

function checkRtnDate(){
  if( document[FORM][ONE_WAY_FLAG].value == "true" ) {
     disableRtnDate(true);
  }
}

//////////////////////////////////////////////////////////////
// This function disables / enables the fare category drop down
// based on the value of the boolean paramater passed in.
// If the value of "disable" is true then the element for
// "lowest" fare is selected before the list is disabled. This
// ensures that the fare category is set to lowest for flexible search.
function disableFareCategory(disable){
    if (disable == false){
		// enable the fare category drop down
    document[FORM][FARE_CATEGORY].disabled=false;
		var selectedFareCategory = document[FORM][FARE_CATEGORY];

	} else {
		// select the "lowest" option
		var len = document[FORM][FARE_CATEGORY].length;
		for (var i = 0; i < len; i++) {
			var fareCat = document[FORM][FARE_CATEGORY].options[i].value;
			if (fareCat == 0){
				document[FORM][FARE_CATEGORY].options[i].selected=true;
				break;
			}
		}
		// disable the fare category drop down
		//eval("var selectedFareCategory = document."+ FORM +"."+ FARE_CATEGORY +".disabled=true;");
    document[FORM][FARE_CATEGORY].disabled=true;
		var selectedFareCategory = document[FORM][FARE_CATEGORY];
	}

}

//////////////////////////////////////////////////////////////
// This function changes the selected day on the return day combo box
// to match the selected day on the depart day combo box
// if the months are the same and the selected return day is less than the depart day
function changeReturnDay(){

	// get days
	var selectedDepartDay = document[FORM][DEPART_DAY]["selectedIndex"];
	var selectedReturnDay = document[FORM][RETURN_DAY]["selectedIndex"];
	// get months
	var selectedDepartMonth = document[FORM][DEPART_MONTH]["value"];
	var selectedReturnMonth = document[FORM][RETURN_MONTH]["value"];

	if ((selectedDepartMonth == selectedReturnMonth) && (selectedReturnDay < selectedDepartDay) ){
		document[FORM][RETURN_DAY].options[selectedDepartDay].selected=true;
	}
}

//////////////////////////////////////////////////////////////
// This function gets the number of days for the selected month
// and populates the dayCombo with the appropriate number of days.
// If on the depart leg this function also sets the returning month
// to be the same month (if the return month is before the new selected month)
// and updates the return dayCombo accordingly.
function changeMonth(leg, formName){
	if (formName) {
		FORM = formName;
	}
	// decide if the depart leg or return leg month was changed
	var dayCombo, monthCombo;
	if (leg == "depart"){
		dayCombo = DEPART_DAY;
		monthCombo = DEPART_MONTH;
	}else if (leg == "return"){
		dayCombo = RETURN_DAY;
		monthCombo = RETURN_MONTH;
	}
	// get the month selected index and the month value
	var depMonthSelectedIndex = document[FORM][monthCombo]["selectedIndex"];
	var depMonthSelected = document[FORM][monthCombo]["options"][depMonthSelectedIndex]["value"];

	var intMonthSelected = parseInt(depMonthSelected,10);

	// check to see if the month is for this year or next year,
	// e.g if it's less than todays month it in next year so change the year to the following year
	var currDate = new Date();
	var currMonth = (currDate.getUTCMonth());
	var currYear = currDate.getYear();
	if (intMonthSelected < currMonth) {
		var numOfDays = getLenMonth(currYear + 1, intMonthSelected);
	} else {
		var numOfDays = getLenMonth(currYear, intMonthSelected);
	}

	// change the days in the corresponding day combo box
	// to equal the number of days for the selected month
	popDays(numOfDays, dayCombo, false);

	// if depart month was changed and if return month is less than selected depart month
	// change it to depart month and change the days in the returning day combo boxes
	// to equal the number of days for the selected month.
	if (leg == "depart"){
		var retMonthSelectedIndex = document[FORM][RETURN_MONTH]["selectedIndex"];
		if (retMonthSelectedIndex < depMonthSelectedIndex){
			document[FORM][RETURN_MONTH]["options"][depMonthSelectedIndex]["selected"]=true;
			popDays(numOfDays, RETURN_DAY, false);
		}
		// need to call changeReturnDay() to alter the return day if it is before the depart day
		changeReturnDay();
	}
}

//////////////////////////////////////////////////////////////
// This function gets the number of days for the selected month
// and populates the dayCombo with the appropriate number of days.
//
// It takes in as paramaters the index and the form element type
// (date of birth or passport expiry) and builds the form element names.
//
// From the form element names the users selected month and year
// can be retrieved and used to calculate the appropriate number of days.
function setDaysForMonthAndYear(index, type){

	// set up the form element names based on the type that is passed in.
	if (type=="dob"){
		var dayCombo = "passportInfoIndexed["+ index +"].dateOfBirthDay";
		var monthCombo = "passportInfoIndexed["+ index +"].dateOfBirthMonth";
		var yearCombo = "passportInfoIndexed["+ index +"].dateOfBirthYear";

	} else if (type=="expiry") {
		var dayCombo = "passportInfoIndexed["+ index +"].expiryDay";
		var monthCombo = "passportInfoIndexed["+ index +"].expiryMonth";
		var yearCombo = "passportInfoIndexed["+ index +"].expiryYear";
	}

	// get the month selected index and the month value
	var monthSelectedIndex = document[FORM][monthCombo]["selectedIndex"];
	var monthSelected = document[FORM][monthCombo]["options"][monthSelectedIndex]["value"];

	// get the year selected index and the year value
	var yearSelectedIndex = document[FORM][yearCombo]["selectedIndex"];
	var yearSelected = document[FORM][yearCombo]["options"][yearSelectedIndex]["value"];

	// only do check if both month and year have been selected
	if ( (monthSelected != "") && (yearSelected != "") ){
		var intMonthSelected = parseInt(monthSelected,10);
		var intYearSelected = parseInt(yearSelected,10);

		//get the number of days in a month
		var numOfDays = getLenMonth(yearSelected, intMonthSelected);

		// change the days in the corresponding day combo box
		// to equal the number of days for the selected month
		popDays(numOfDays, dayCombo, true);
	}

}

//////////////////////////////////////////////////////////////
// Helper function that gets the number of days in a month
function getLenMonth(year, month){
	month++;
	var days;
	if (month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12) {
		days=31;
	} else if (month==4 || month==6 || month==9 || month==11) {
		days=30;
	}	else if (month==2) {
		if (isLeapYear(year)) {
			days=29;
		}	else {
			days=28;
		}
	}
	return (days);
}

function isLeapYear(Year) {
	if (((Year % 4)==0) && ((Year % 100)!=0) || ((Year % 400)==0)) {
		return (true);
	} else {
		return (false);
	}
}

//////////////////////////////////////////////////////////////
// Helper function that populates the dayCombo box with
// the number of days in the selected month
function popDays(numOfDays, daySel, addBlankEntry) {

	var len = document[FORM][daySel]["length"];
	var selectedDay = document[FORM][daySel]["selectedIndex"] + 1;

	// clear the array
	for (var i = 0; i < len; i++) {
		document[FORM][daySel].options[i] = null;
	}

	// if a blank entry needs to be added, add it to the start
	if (addBlankEntry) {
		numOfDays = numOfDays + 1;
		document[FORM][daySel].length = numOfDays;
		document[FORM][daySel].options[0] = new Option("--");
		document[FORM][daySel].options[0].value = ("");
		// populate the array with the days
		for(var i = 1; i < numOfDays; i++) {
			document[FORM][daySel].options[i] = new Option(i);
			document[FORM][daySel].options[i].value = (i);
			if (i == (selectedDay - 1)) {
				document[FORM][daySel].options[i].selected = true
			}
		}

	// else just populate the array with the days
	} else {
		document[FORM][daySel].length = numOfDays;
		// populate the array with the days
		for(var i = 0; i < numOfDays; i++) {
			document[FORM][daySel].options[i] = new Option(i+1);
			document[FORM][daySel].options[i].value = (i+1);
			if (i == (selectedDay - 1)) {
				document[FORM][daySel].options[i].selected = true
			}
		}
	}
}

//////////////////////////////////////////////////////////////
// This function opens the calendar passing in the selected
// day, month and leg.
function openCalendar(strPath, leg, locale) {
	//set the global var form
	var width=255,height=240;
	var monthSel, daySel;
	if (leg == "depart") {
		monthSel = DEPART_MONTH;
		daySel = DEPART_DAY;
	} else   if (leg == "return") {
		monthSel = RETURN_MONTH;
		daySel = RETURN_DAY;
	}

	var daySelectedIndex = document[FORM][daySel]["selectedIndex"];
	var monthSelectedIndex = document[FORM][monthSel]["selectedIndex"];
	var daySelected = document[FORM][daySel]["options"][daySelectedIndex]["value"];
	var monthSelected = document[FORM][monthSel]["options"][monthSelectedIndex]["value"];

	if ((locale == null)||(locale == "")){
		locale = LOC;
	}
	if(strPath == ""){
		strPath = strPath +"calendar.do?daySelected="+ daySelected +"&monthSelected="+ monthSelected +"&leg="+ leg+"&bookingLocale="+locale;
	}else{
		strPath += "&daySelected="+ daySelected +"&monthSelected="+ monthSelected +"&leg="+ leg+"&bookingLocale="+locale;
	}

	window.open(strPath,'Calendar','width=' + width + ',height=' + height);
}

function openCalendarSingleLegOnTwoLegs(strPath, leg, locale, sessId, otherDay, otherMonth,otherYear) {
	var width=255,height=240;
	var monthSel, daySel, dayTwo, monthTwo;

	if (leg == "depart"){
		daySel= DEPART_DAY;
		monthSel= 	DEPART_MONTH;
		dayTwo = otherDay
		monthTwo =otherMonth
	}else{
		daySel= RETURN_DAY;
		monthSel= RETURN_MONTH;
		dayTwo = otherDay
		monthTwo =otherMonth
	}

	eval("var daySelectedIndex = document."+ FORM +"."+ daySel +".selectedIndex");
	eval("var monthSelectedIndex = document."+ FORM +"."+ monthSel +".selectedIndex");
	eval("var daySelected = document."+ FORM +"."+ daySel +".options[daySelectedIndex].value");
 	eval("var monthSelected = document."+ FORM +"."+ monthSel +".options[monthSelectedIndex].value");

	if ((locale == null)||(locale == "")){
		locale = LOC;
	}

	if (sessId == ""){
		strPath = strPath +"calendar.do?daySelected="+ daySelected +"&monthSelected="+ monthSelected +"&otherDay="+ otherDay +"&otherMonth="+ otherMonth +"&otherYear="+ otherYear +"&leg="+ leg+"&bookingLocale="+locale;
	}else{
		strPath = strPath +"calendar.do?"+sessId+"&daySelected="+ daySelected +"&monthSelected="+ monthSelected +"&otherDay="+ otherDay +"&otherMonth="+ otherMonth +"&otherYear="+ otherYear +"&leg="+ leg+"&bookingLocale="+locale;
	}
	window.open(strPath,'Calendar','width=' + width + ',height=' + height);
}

//////////////////////////////////////////////////////////////
// This function sets the dayCombo and monthCombo with the
// date that was selected in the calendar pop-up
function setDate(newDay, newMonth, leg) {
	var monthSel, daySel;
	var monthSelectedIndex = 0;
	if (leg == "depart") {
		monthSel = document[FORM][DEPART_MONTH];
		daySel = 	document[FORM][DEPART_DAY];
	} else if (leg == "return") {
		monthSel = document[FORM][RETURN_MONTH];
		daySel = 	document[FORM][RETURN_DAY];
	}

	// set the month to the newly selected month
	for (i = 0; i < 12; i++) {
		if(newMonth == (parseInt(monthSel.options[i].value,10))) {
			monthSelectedIndex = i;
		}
	}
	monthSel.options[monthSelectedIndex].selected = true;
	changeMonth(leg);

	// set the day to the newly selectd day
	var intNewDay = parseInt(newDay) - 1;
	daySel.options[intNewDay]["selected"] = true;

	// if setting the depart leg call changeDay to see if return leg needs to be changed
	if (leg == "depart") {
		changeReturnDay();
	}
}

//////////////////////////////////////////////////////////////
// this function updates the destination drop down with the
// list of airports that are destinations for the selected origin
//
// NOTE: because of different behaviour in different browsers
// it is necessary to use the sessDest var if it is not ""
// can talk to warrecl about this if you are curious.
function updateDestinations(origBox, destBox, fromOnload, sessDest) {

	// get destination value
	var destIndex = 0;
	var destValue = "";
	destIndex += eval(destBox.selectedIndex);
	if (destIndex == -1){
		destIndex = 0;
	} else{
		destValue = destBox.options[destIndex].value;
	}
	// sessDest overrides destValue if it is available
	if (sessDest != ""){
		destValue = sessDest;
	}

	var origIndex = eval(origBox.selectedIndex);

	if (origIndex!=-1){
		var orig = origBox.options[origBox.selectedIndex].value;

		if ((orig != "null") && (orig != "")) {
			orig = eval(orig);
			destBox.innerHTML = "";
			destBox.length = 0;
			for (var i = 0; i < orig.length - 1; i++) {
				var oOption = document.createElement("OPTION");
				oOption.innerHTML = orig[i].meaning;
				oOption.value = orig[i].code;
				oOption.title = orig[i].meaning;
				// set selected element in drop down
				if ((destValue != "") && (orig[i].code == destValue)){
					oOption.selected = true;
				}
				destBox.appendChild(oOption);
			}

		} else if(fromOnload == false){
			destBox.innerHTML = "";
			var oOption = document.createElement("OPTION");
			oOption.innerHTML = "Going To";
			oOption.value = "null";
			destBox.appendChild(oOption);
		}
	}
}

//get meaning of airport based on airport code
function getMeaning(masterList,code){
	for(var i=0;i<masterList.length-1;i++){
		if(masterList[i].code == code){
			return masterList[i].meaning;
			break;
		}
	}
}

//////////////////////////////////////////////////////////////
// this function stores the currently selected destination
// into a hidden form field
function updateDestinationOnChange(destBox, destHiddenField) {
	var detailIndex = eval(destBox.selectedIndex);
	if (detailIndex!=-1) {
		destHiddenField.value = destBox.options[detailIndex].value;
 	} else {
		destHiddenField.value = '';
	}
}

//////////////////////////////////////////////////////////////
// this function updates Return field in Change PNR screen
// and also updates a hidden form field if necessary
function updateReturnDestinationAirport(formname,destOut,destReturn,destReturnHidden){
	var frm = document.forms[formname];
	var dest = frm.elements[destOut];
	var outText = dest.options[dest.selectedIndex].text;
	var len = outText.indexOf("(");
	if (len > 0 ){
		outText = outText.substring(0,len);
	}
	var outValue = dest.options[dest.selectedIndex].value;

	frm.elements[destReturn].value = outText;
	if(destReturnHidden.length > 0){
		frm.elements[destReturnHidden].value = outValue;
	}
}

//////////////////////////////////////////////////////////////
//This function establishes an initial outbound destination airport
//on plan new pnr screen
function selectOutboundDestination(formName, optionsName, valueName){
	eval("var opts = document."+ formName +"."+ optionsName);
	var i;
	for(i=0;i!=opts.length;i++){
		if(opts[i].value == valueName){
			opts[i].selected = true;
		}
	}
}


//////////////////////////////////////////////////////////////
// this function updates the destination drop down with the
// list of airports that are destinations for the selected origin
// at load up time
//
// NOTE: because of different behaviour in different browsers
// it is necessary to use the sessDest var if it is not ""
// can talk to warrecl about this if you are curious.
function updateDestinationsOnLoad(formName, orig, destBoxName, fromOnload, sessDest) {

	// get destination value
	var destIndex = 0;
	var destValue = "";
	if (sessDest != ""){
		destValue = sessDest;
	}

	eval("var destBox = document."+ formName +"."+ destBoxName);

	if ((orig != "null") && (orig != "")) {
		orig = eval(orig);
		destBox.innerHTML = "";
		destBox.length = 0;

		for (var i = 0; i < orig.length - 1 && orig.length > 0; i++) {
			var oOption = document.createElement("OPTION");
			oOption.innerHTML = orig[i].meaning;
			oOption.value = orig[i].code;
			oOption.title = orig[i].meaning;
			// set selected element in drop down
			if ((destValue != "") && (orig[i].code == destValue)){
				oOption.selected = true;
			}
			destBox.appendChild(oOption);
		}

	} else {
		destBox.innerHTML = "";
		var oOption = document.createElement("OPTION");
		oOption.innerHTML = "--- none ---";
		oOption.value = "null";
		destBox.appendChild(oOption);
	}
}

//////////////////////////////////////////////////////////////
//Updates the code for multi-city stuff
function updateDestinationsCode(hiddenField, destBox) {
	// get destination value
	var destIndex = 0;
	var destValue = "";
	destIndex += eval(destBox.selectedIndex);
	if (destIndex == -1){
		destIndex = 0;
	} else{
		destValue = destBox.options[destIndex].value;
	}
  hiddenField.value = destValue;
}

//////////////////////////////////////////////////////////////
function disableBusiness(){
  var onlyBusinessRoutes = isBusinessRoute();
  disableFareCategory(!onlyBusinessRoutes);
}

//////////////////////////////////////////////////////////////
function getRouteCode(routeNum){
  var orig = null;
  eval("orig = document." + FORM + ".selectedSourceAirport_"+ routeNum );
  if (null == orig){
    var origCode = "XXX";
  }else{
    var origCode = orig.value;
  }
  var dest = null;
  eval("dest = document." + FORM + ".selectedDestinationAirport_"+ routeNum );
  if (null == dest){
    var destCode = "XXX";
  }else{
    var destCode = dest.value;
  }
  var routeCode = origCode + destCode;
  return routeCode;
}

//////////////////////////////////////////////////////////////
// Disables the fare category dropdown if the user has 
// selected flexible search
// Note: unlike disableFareCategory, this function will never 
// enable the fare category dropdown
function disableFareCatForFlexible(){
 if(!isBusinessRoute()){
      if (document[FORM][SEARCH_TYPE]) {
    	  if (document[FORM][SEARCH_TYPE][0]){
    		  if (document[FORM][SEARCH_TYPE][0].checked == true) {
    			  document[FORM][FARE_CATEGORY].disabled=true;
    		  }
    	  }
      }
  }
}

//////////////////////////////////////////////////////////////
function isBusinessRoute(){
	var routeCode_1 = getRouteCode("1");
	var routeCode_2 = getRouteCode("2");
	var len = businessRoutes.length;
	var routeIsBusiness_1 = false;
	var routeIsBusiness_2 = false;
	for (i = 0; i < len; i++) {
		if (businessRoutes[i]==routeCode_1) {
			routeIsBusiness_1 = true;
		} else if (businessRoutes[i]==routeCode_2) {
		routeIsBusiness_2 = true;
		}
	}
  return (routeIsBusiness_1 || routeIsBusiness_2);
}

//////////////////////////////////////////////////////////////
function isFixedSearchRoute(){
  var routeCode_1 = getRouteCode("1");
  var routeCode_2 = getRouteCode("2");
  
  var len = fixedSearchRoutes.length;
  var isFixedSearchRoute_1 = false;
  var isFixedSearchRoute_2 = false;
  for (i = 0; i < len; i++) {
    if (fixedSearchRoutes[i]==routeCode_1) {
      isFixedSearchRoute_1 = true;
    } else if (fixedSearchRoutes[i]==routeCode_2) {
      isFixedSearchRoute_2 = true;
    }
  }
  return (isFixedSearchRoute_1 || isFixedSearchRoute_2);
}

//////////////////////////////////////////////////////////////
function setDefaultSearchType(){
	if (document[FORM][SEARCH_TYPE]){
		if(isFixedSearchRoute()){
			document[FORM][SEARCH_TYPE][1].checked = true; 
		}else{
			// If we are in corporate flow then the 'flexible date' search option will be disabled 
			// when the 'Promotional rates are selected in this case don't want to select flexible date.
			if(document[FORM][SEARCH_TYPE][0] && document[FORM][SEARCH_TYPE][0].disabled == false)
				document[FORM][SEARCH_TYPE][0].checked = true;
			disableFareCategory(true);
		}
	}
}


//////////////////////////////////////////////////////////////
function updateSelectedSearchType(isCorporate){
	if(isCorporate == 'false'){
		if(document[FORM][SEARCH_TYPE].length > 1){
			if(document[FORM][FARE_CATEGORY].options[1].selected){
				document[FORM][SEARCH_TYPE][1].checked = true;
			}
		}
	}
}

//////////////////////////////////////////////////////////////
function checkRtnOnLoad(){
	if(document[FORM][FLIGHT_TYPE][1].checked){
		disableRtnDate(true);
	}
}

//////////////////////////////////////////////////////////////
function checkFlightType(){
	if (document[FORM][SEARCH_TYPE] == null){
		if (document[FORM]['selectedSearchTypeCorporate'] == null){
	  	if (document[FORM]['selectedSearchTypeTab'] == null){
	    	;
	  	}else{
    		document[FORM]['selectedSearchTypeTab'].checked = true;
	  	}
		}else{
			document[FORM]['selectedSearchTypeCorporate'].checked = true;
		}
  }else{
		document[FORM][SEARCH_TYPE].checked = true;
  }
}

