/*#############################################################################

FILE:	SB/ataGlanceSearch.js

	Copyright (c) 2005 Navitaire Inc. All rights reserved.

	This source code is (i) proprietary to and a trade secret of Navitaire Inc.
	and (ii) protected by copyright law and international treaties.
	Unauthorized disclosure, reproduction, distribution or alteration of this
	source code, or any portion of it, may result in severe civil and criminal
	penalties and will be prosecuted to the maximum extent possible under
	the law.

	www.navitaire.com

DESCRIPTION:

	Contains javascript for the search form.  Note that this file relies on
	javascript from the jAtaGlanceSearch.wld template and dateValidation.js.

#############################################################################*/

	var searchText 	= new Object();
	var searchPrefs	= new Object();
	captureSearchText(searchText);
	captureSearchPrefs(searchPrefs);
	/*##############################################
	#
	# Function: setDest()
	#
	# Parameter: 
	#		mkt : 1 - outbound
	#		      2 - Inbound
	#			
	#
	# Description: 
	#	       Captures the selected destination city for outbound or inbound
	#	       to be put in the skylights form.
	#*/
	function setDest( mkt )
	{
		var toList		= document.getElementById( "to" + mkt + "Select" );
		eval( "document.skylightsForm.toCity" + mkt + ".value = toList.value" );
	}
	/*##############################################
	#
	# Function: resetDest()
	#
	# Parameter: 
	#		mkt : 1 - outbound
	#		      2 - Inbound
	#			
	#
	# Description: 
	#	       Resets the city options for destination depending on the selected 
	#	       origin city.
	#*/
	function resetDest( mkt )
	{
		var fromList		= document.getElementById( "from" + mkt + "Select" );

		//one roundtrip, this is called for market2, but we have hidden the controls
		if (!fromList)
		{
			return;
		}

		var toList		= document.getElementById( "to" + mkt + "Select" );
		var orig		= fromList.options[ fromList.selectedIndex ].value;
		var dest		= eval( "document.skylightsForm.toCity" + mkt + ".value" );
		
		toList.length	= 1;
		toList.options[0]		= new Option("Destination");
		toList.options[0].value	= "???"

		if ( fromList.selectedIndex == 0 )
		{
			for (var i = 0; i < Airports.length; i++)
			{
				toList.length	+= 1;
				var l_ix		= toList.length - 1;
				var opt_str		= Airports[i].name;
				if ( searchPrefs.DISPLAY_AIRPORT_CITY_CODES == 'true' )
				{
					opt_str		+=  " (" + Airports[i].code + ")";
				}

				toList.options[l_ix]	= new Option( opt_str );
				toList.options[l_ix].value	= Airports[i].code;

				if (Airports[i].code.match('XXX'))
				{
					toList.options[l_ix].disabled = true;
					//FIX FOR COUNTRY COLORS
					toList.options[l_ix].className = "bp-country";
				}

				if ( dest == Airports[i].code )
				{
					toList.selectedIndex	= l_ix;
				}
			}
		}
		else
		{
			var air		= getAirport( orig );
			for (var i = 0; i < air.dests.length; i++)
			{
				dest_air		= getAirport( air.dests[i] );
				toList.length	+= 1;
				var l_ix		= toList.length - 1;
				var opt_str		= dest_air.name;
				if ( searchPrefs.DISPLAY_AIRPORT_CITY_CODES == 'true' )
				{
					opt_str		+=  " (" + dest_air.code + ")";
				}

				toList.options[l_ix]	= new Option( opt_str );
				toList.options[l_ix].value	= dest_air.code;

				if (dest_air.code.match('XXX'))
				{
					toList.options[l_ix].disabled = true;
					//FIX FOR COUNTRY COLORS
					toList.options[l_ix].className = "bp-country";
				}

				if ( dest == dest_air.code )
				{
					toList.selectedIndex	= l_ix;
				}
			}
		}
		
		setDest( mkt );
	}
	/*##############################################
	#
	# Function: resetDest()
	#
	# Parameter: 
	#		checkDates: flag if roundtrip flight is selected
	#		 
	#			
	#
	# Description: 
	#	       Validates and adjust the inbound date drop down boxes referring to the outbound date.
	#	       
	#*/
	function resetDates(checkDates)
	{
		var m1d_ix		= document.skylightsForm.departDay1.selectedIndex;
		var m1y_ix		= document.skylightsForm.departMonth1.selectedIndex;

		if ( checkDates ) {
			if ( m1y_ix > document.skylightsForm.departMonth2.selectedIndex ) {
				document.skylightsForm.departMonth2.selectedIndex	=  m1y_ix;
				document.skylightsForm.departDay2.selectedIndex	=  m1d_ix;
			}
			if ( ( (m1y_ix) == document.skylightsForm.departMonth2.selectedIndex )
			  && ( m1d_ix > document.skylightsForm.departDay2.selectedIndex ) ) {
				document.skylightsForm.departDay2.selectedIndex	=  m1d_ix;
			}
		}
	}
	/*##############################################
	#
	# Function: validCities()
	#
	# Parameter: 
	#			
	#
	# Description: 
	#	       Verifies if both origin and destination cities are filled-up.
	#
	# Return:	
	#		True: both origin and destination is not blank
	#		false: if otherwise
	#*/
	function validCities()
	{
		var is_valid	= true;
		if ( (document.skylightsForm.from1.selectedIndex == 0) || (document.skylightsForm.from1.value.match('XXX')) )
		{
			alert( searchText.missingDepartCity );
			is_valid	= false;
		}
		else if ( (document.skylightsForm.to1.selectedIndex == 0)  || (document.skylightsForm.to1.value.match('XXX')) )
		{
			alert( searchText.missingArriveCity );
			is_valid	= false;
		}
		else if ((searchPrefs.OFFER_OPEN_JAW_ROUTES == "true") && (document.skylightsForm.travel[2].checked))
		{
			is_valid = validateOpenJawConnections();
		}
		
		return is_valid;
	}

	/*##############################################
	#
	# Function: isVAus()
	#
	# Parameter: 
	#			
	#
	# Description: 
	#	       Determines if the booking should be made through VAustralia/Amadeus rather than Skylights.
	#
	# Return:	
	#		True: either origin or destination is a US city
	#		false: if otherwise
	#*/
	function isVAus()
	{
		var vamatch = /^(ATL|BOS|CVG|DTW|IAD|IND|JFK|LAS|LAX|MEM|MSP|MCO|PDX|SLC|SFO|SEA|TPA|YVR|HKT|JNB|LHR)$/; // I hate this.  We need a flag in the js cities...
		var from_city = document.skylightsForm.from1.value;
		var to_city = document.skylightsForm.to1.value;

		// PER <-> HKT and HKT -> BNE(one way) exception (all other HTK is VA) --stirratt
		if ( (from_city == 'PER' && to_city == 'HKT') || (from_city == 'HKT' && to_city == 'PER') || (from_city == 'HKT' && to_city == 'BNE') ) {
			return false;
		}
	
		if ( from_city.match(vamatch) || to_city.match(vamatch) )
		{
			return true;
		}

		var depart_date = Number(document.skylightsForm.departMonth1.value) * 100 + Number(document.skylightsForm.departDay1.value);
		var total_seats = Number(document.skylightsForm.ADULT.value) + Number(document.skylightsForm.CHILD.value);
		if ( (from_city == 'SYD' && to_city == 'NAN') && depart_date >= 20091218 && total_seats > 9) {
			return true;
		}

		return false;
	}

	// check if the city is part of the amadeus engine and if so show the 
	// hidden row
	function checkAmadeusHidden() {
		el = $('travelclass-row');
		if (el) {
			if (isVAus()) {
				el.style.display = 'block';
			} else {
				el.style.display = 'none';
			}
		}
	};

	/*##############################################
	#
	# Function: skylightsToAmadeus()
	#
	# Parameter: 
	#			
	#
	# Description: 
	#	       Populates hidden booking panel fields with values from skylights form, then
	#	       redirects to Amadeus booking panel to process the booking
	#
	# Return:	
	#		
	#		
	#*/
	function skylightsToAmadeus()
	{
		buildAmadeusData();

		var bpanel = new BookingPanel($('bp-amadeus'));
		bpanel.validate();
	}

	/*##############################################
	#
	# Function: buildAmadeusData()
	#
	# Parameter: 
	#			
	#
	# Description: 
	#	       Creates and populates hidden booking panel form with values from skylights form
	#
	# Return:	
	#		
	#		
	#*/
	function buildAmadeusData()
	{
		va_data = document.getElementById("bp-amadeus");
		va_data.innerHTML = "";	// make sure there is no previously posted data

		form        = document.createElement('form');
		form.id     = "bp-form";
		form.name   = "bp-form";
		form.action = "/";
		form.method = "post"

		id_map = Array
		(
			Array("bp-round",        "roundTripRadio"),
			Array("bp-oneway",       "oneWayRadio"),
			Array("bp-day-depart",   "departDay1Select"),
			Array("bp-month-depart", "departMonth1Select"),
			Array("bp-day-return",   "departDay2Select"),
			Array("bp-month-return", "departMonth2Select"),
			Array("bp-pax-adult",    "ADULTSelect"),
			Array("bp-pax-child",    "CHILDSelect"),
			Array("bp-pax-infant",   "INFANTSelect"),
			Array("bp-to",           "to1Select"),
			Array("bp-from",         "from1Select"),
			Array("bp-travelclass",  "travelclass")
		);
		id_map.each(function(field_name)
		{
			skyfield = document.getElementById(field_name[1]);
			bp       = document.createElement("input");
			bp.id    = field_name[0];
			bp.name  = field_name[0];
			if (field_name[1].match(/Radio/))
			{
				bp.type    = "radio";
				bp.value = Number(skyfield.value) - 1; // skylights values for the radio buttons were set to 1 extra than the booking panel values
				if (skyfield.checked)
				{
					bp.setAttribute("checked", "checked");
					bp.defaultChecked = "checked";	// ie bug hack, since .checked doesn't work in ie6
				}
			}
			else
			{
				bp.type  = "hidden";
				bp.value = skyfield.value;
			}
			form.appendChild(bp);
		});

		bp       = document.createElement("input");
		bp.id    = "bp-submit";
		bp.type  = "submit";
		bp.value = "submit";
		form.appendChild(bp);

		va_data.appendChild(form);
	}

	/*##############################################
	#
	# Function: validPax()
	#
	# Parameter: 
	#			
	#
	# Description: 
	#	       Verifies if the number of passengers are valid with this conditions:
	#		1. Does not exceed the Max allowable number of passengers (setting in PREF)
	#		2. There should be 1 or more passengers
	#		3. Number of adults should be greater or equal to number of infants 
	#
	# Return:	
	#		True: satisfies all conditions
	#		false: if otherwise
	#*/
	function validPax()
	{
		var adults = document.skylightsForm.ADULT.value;
		var infants = document.skylightsForm.INFANT.value;
		var paxTotal = 0;
		
		for (i = 0; i < searchPrefs.paxTypes.length; i++)
		{
			var paxType 	= searchPrefs.paxTypes[i];
			var paxSelect	= document.getElementById(paxType +"Select");
			paxTotal		= eval(paxTotal) + eval(paxSelect.options[paxSelect.selectedIndex].value);
		}

		if ((paxTotal > searchPrefs.MAX_PASSENGERS_ALLOWED) && ( searchPrefs.MAX_PASSENGERS_ALLOWED > 0 ))
		{
			alert("\n"	+ searchText.popup_max_passenger_amount_1
						+ searchPrefs.MAX_PASSENGERS_ALLOWED
						+ searchText.popup_max_passenger_amount_2 + "\n");
			return false;
		}

		if ( paxTotal < 1)
		{
			alert(searchText.popup_missing_passenger_amount);
			return false;
		}

		if ( (adults  / infants) < 1 )
		{
			alert(searchText.popup_too_many_infants);
			document.skylightsForm.INFANT.focus();
/*
			// If there is a default, reset it
			if( document.skylightsForm.defaultADULT.value > -1 )
			{
				var adultSelect = document.skylightsForm.ADULT;
				for(x1=0; x1 < adultSelect.length; x1++)
				{
					if( adultSelect[x1].value == document.skylightsForm.defaultADULT.value )
					{
						document.skylightsForm.ADULT.selectedIndex = x1;
						break;
					}
				}
			}
			
			var infantSelect = document.skylightsForm.INFANT;
			for(x2=0; x2 < infantSelect.length; x2++)
			{
				if( (document.skylightsForm.defaultINFANT.value == -1 && infantSelect[x2].value == 0) || 
				    (document.skylightsForm.defaultINFANT.value != -1 && infantSelect[x2].value == document.skylightsForm.defaultINFANT.value) )
				{
					document.skylightsForm.INFANT.selectedIndex = x2;
					break;
				}
			}
*/			
			return false;
		}

		return true;
	}
	/*##############################################
	#
	# Function: validDates()
	#
	# Parameter: 
	#		beginDate: valid start date (set in PREFs)
	#		endDate:  valid end date (set in PREFs)
	#
	# Description: 
	#	       Checks the selected dates against the beginDate and endDate parameter
	#	       
	#
	# Return:	
	#		True: valid date/s
	#		false: if otherwise
	#*/
	function validDates(beginDate, endDate)
	{
		var is_valid			= true;
		var beginDateString		= new String (beginDate);
		var endDateString		= new String (endDate);
		var departDateString	= captureDateString("departDay1", "departMonth1");
		var arriveDateString	= captureDateString("departDay2", "departMonth2");

		date_message = searchText.popup_pre_flight_date_1 +
						searchText.popup_initial_flight_date +
						searchText.popup_pre_flight_date_2;
						
		if ( departDateString < beginDateString )
		{
			alert( date_message );
			setDate( "departDay1", "departMonth1", beginDateString );
			if( isRoundTrip() && arriveDateString < beginDateString )
				setDate( "departDay2", "departMonth2", beginDateString );
			return false;
		}

		if ( searchPrefs.final_date_used )
		{
			if( departDateString > endDateString )
			{
				is_valid = false;
				setDate( "departDay1", "departMonth1", endDateString );
			}
			if( isRoundTrip() && ( arriveDateString > endDateString ) )
			{
				is_valid = false;
				setDate( "departDay2", "departMonth2", endDateString );
			}
			if( !is_valid )
			{
				alert( searchText.popup_post_live_flight_date_1 +
						searchText.popup_final_flight_date +
						searchText.popup_post_live_flight_date_2 );
				return false;
			}
		}

		// check that dates are valid calandar dates
		if(!validateCalendarDate("departDay1", "departMonth1", true, true))
		{
			if( isRoundTrip() || ( !isOneWay() && searchPrefs.OFFER_OPEN_JAW_ROUTES == 'true' ) )
			{
				validateCalendarDate("departDay2", "departMonth2", false, true);
			}
			return false;
		}
		if(	( isRoundTrip() || ( !isOneWay() && searchPrefs.OFFER_OPEN_JAW_ROUTES == 'true' ) ) && !validateCalendarDate("departDay2", "departMonth2", true, true) )
		{
			return false;
		}

		if ( isRoundTrip() || ( !isOneWay() && searchPrefs.OFFER_OPEN_JAW_ROUTES == 'true' ) )
		{
			if ( !validateDateOverlap("departDay1", "departMonth1", "departDay2", "departMonth2", true, true) )
			{
				return false;
			}
			else if ( searchText.sameDayWarning && arriveDateString == '' + departDateString )
			{
				is_valid		= confirm( searchText.sameDayWarning );
			}
		}

		// HKT/JNB checks - stirratt
		var tmpDest = document.skylightsForm.to1.value;
		var testJNBDateString = '20100313';
		var testHKTDateString = '20091114';

		if (tmpDest == 'JNB' && (departDateString < testJNBDateString)) {
			alert('Our flights to/from Johannesburg start operating on 13 March 2010. Please select a date for travel after this date.');
			return false;
		}

		/*
		// removed validation at request of PB (or whoever it was) --stirratt	
		if (tmpDest == 'HKT' && (departDateString < testHKTDateString)) {
      alert('Our flights to Phuket start operating on November 14th. Please select a date for travel after this date.');
      return false;
    }*/
		
		
		return is_valid;
	}
	/*##############################################
	#
	# Function: formatDates()
	#
	# Parameter: 
	#
	# Description: 
	#	       Arranged the captured day and month values selected for inbound and outbound flights	
	#	       
	#
	#*/
	function formatDates()
	{
		document.skylightsForm.departDate1.value		= 		captureDateString("departDay1", "departMonth1");
		if ( document.skylightsForm.numberMarkets.value > 1 )
		{
			document.skylightsForm.departDate2.value	= captureDateString("departDay2", "departMonth2");
		}
	}
	/*##############################################
	#
	# Function: validateOpenJawConnections()
	#
	# Parameter: 
	#
	# Description: 
	#	       Verifies if the selected cities are valid for open jaw routes.
	#	       
	#
	# Return:	
	#		True: valid open jaw routes
	#		false: if otherwise
	#*/	
	function validateOpenJawConnections()
	{
		if ( ( ( document.skylightsForm.from1.value == document.skylightsForm.to2.value ) ||
				( document.skylightsForm.to1.value == document.skylightsForm.from2.value ) ) 
				&& ( document.skylightsForm.from2.value != '???') && ( document.skylightsForm.to2.value != '???'))
		{
			return true;
		}
		else
		{
			alert(searchText.popup_illogical_open_jaw);
			return false;
		}
	}


// Begin Oneway/Roundtrip javascript
	/*##############################################
	#
	# Function: isOneWay()
	#
	# Parameter: 
	#
	# Description: 
	#	       Returns true if one way radio button is selected, else.
	#	       false
	#
	#*/
	function isOneWay()
	{
		return ( document.skylightsForm.travel[1].checked );
	}
	/*##############################################
	#
	# Function: isRoundTrip()
	#
	# Parameter: 
	#
	# Description: 
	#	       Returns true if round trip radio button is selected, else.
	#	       false
	#
	#*/	
	function isRoundTrip()
	{
		return ( document.skylightsForm.travel[0].checked );
	}
	/*##############################################
	#
	# Function: swapTravel()
	#
	# Parameter: 
	#
	# Description: 
	#	       Dynamically changes the display in the search display
	#	       depending on the selected travel option( round trip, one way or open jaw)
	#
	#*/
	function swapTravel()
	{
		// switched to round trip
		if ( document.skylightsForm.travel[0].checked )
		{
			document.skylightsForm.numberMarkets.value			= 2;
			showDiv(true, 'dateSel2');
			if (searchPrefs.OFFER_OPEN_JAW_ROUTES == 'true')
			{
				showDiv(false, 'fromToSel2');
			}
		}
		// switched to one way
		else if ( document.skylightsForm.travel[1].checked )
		{
			document.skylightsForm.numberMarkets.value			= 1;
			showDiv(false, 'dateSel2');
			if (searchPrefs.OFFER_OPEN_JAW_ROUTES == 'true')
			{
				showDiv(false, 'fromToSel2');
			}
		}
		//switched to open jaw
		else
		{
			document.skylightsForm.numberMarkets.value			= 2;
			showDiv(true, 'dateSel2');
			showDiv(true, 'fromToSel2');
		}
		/*// FIX FOR EXTRA COMBO BOX
		if (eval(document.skylightsForm.farePriority))
		{
			showDateFlex();
		}
		*/
		//balanceHeight('wrapper', 'right', 'left');
	}
	
	/*##############################################
	#
	# Function: showDateFlex()
	#
	# Parameter: 
	#
	# Description: 
	#	       Dynamically changes the display in the search display
	#	       depending on the selected fare priority option( Standard Search or LFS)
	#
	#*/
	function showDateFlex()
	{
		/*var option_val = document.skylightsForm.farePriority[document.skylightsForm.farePriority.selectedIndex].value;*/
		var option_val = document.skylightsForm.farePriority.value;
		var elem_id;
		for (i = 1; i <= document.skylightsForm.numberMarkets.value; i++)
		{
			elem_id = "depart" + i + "FlexBySelect";

			if (option_val == 1) // selected Stardard search mode
			{
			      showDiv(true, elem_id,'inline');
			}
			else  // selected LFS search mode
			{
			      showDiv(false, elem_id );
			}
		}
	}
// Begin Search Submit Form javascript
	/*##############################################
	#
	# Function: submitSearch()
	#
	# Parameter: 
	#		beginDate: valid start date (set in PREFs)
	#		endDate:  valid end date (set in PREFs) 
	#
	# Description: 
	#	       Verifies all fields are in proper values, then
	#	       submits the form to start the flight availability search.
	#
	#*/
	function submitSearch(beginDate, endDate)
	{
		if (isVAus() && document.getElementById("bp-amadeus"))
		{
			skylightsToAmadeus();
			stop;
		}
		else if ( validCities() && validDates(beginDate, endDate) && validPax())
		{
			
			finalDate();
			
			/*
			# Removing this line as the templates will concatenate 
			# the month year and day values.
			#
			#formatDates();
			*/
			document.skylightsForm.page.value 	= 'SEARCH';
			document.skylightsForm.module.value	= 'SB';			
			document.skylightsForm.event.value 	= 'search';
			document.skylightsForm.submit();

		}
	}
	/*##############################################
	#
	# Function: onLoadAtaGlance()
	#
	# Parameter: 
	#
	# Description: 
	#	       initializes the display and field values for 
	#	       search page.
	#
	#*/
	function onLoadAtaGlance()
	{
		swapTravel();
		for (i = 1; i <= document.skylightsForm.numberMarkets.value; i++)
		{
			resetDest(i);
		}

		checkAmadeusHidden();
	}
