/**
 * Booking Panel Class
 * 
 * 
 * @author Tim Stirrat <tim.stirrat@gmail.com>
 * @author Scott Mackenzie
 * @version SVN: $Revision: 12586 $
 * 
 * @class BookingPanel
 */
var BookingPanel = Class.create(
{
	/**
	 * Stores the error box objects
	 * 
	 * @type Array
	 */
	_error_box: [],
	
	/**
	 * The html form element
	 * 
	 * @type Element
	 */
	_form: null,


	/**
	 * Turns on encryption and request filtering (currently for VA only).  If turned off, the panel posts directly to amadeus
	 * 
	 * @type boolean
	 */
	_filter_search: false,

	
	/**
	 * The hidden form element
	 * 
	 * @type Element
	 */
	hiddenFormElem: null,
	

	/**
	 * Turns on the var dump page
	 * 
	 * @type boolean
	 */
	debugVars: false,
	
	
	/**
	 * The Vaustralia message panel
	 * 
	 * @type AjaxMessagePanel
	 */
	vaustMessagePanel: null,

	/**
	 * Initializes the Booking Panel
	 * 
	 * @constructor
	 */
	initialize: function (elem, options)
	{
		this.options = {
			show_countries:	false,
			countries: 			false,
			cities:					false,
			errors:					false,
			prefs: 					false,
			test_server: 		false,
			debug_vars:			false,
			filter_search:  false,
			default_engine:	'vb'
		};

		Object.extend(this.options, options || { });

		this._cities            = this.options.cities;
		this._countries         = this.options.countries;
		this._test_server       = this.options.test_server;
		this._default_engine    = this.options.default_engine;
		this.debugVars          = this.options.debug_vars;
		this._filter_search     = this.options.filter_search;

		// global variable
		bp_engine               = this._default_engine;
		
		// get first form
		this._form = elem.getElementsByTagName('form')[0];
		this._error_box = new ErrorBox();
		
		this.assignEvents();
		
		this.setOrigin(this.getOriginCookie());
	},

	/**
	 * Binds even listeners
	 */
	assignEvents: function ()
	{
		// trip type radios
		Event.observe($('bp-round'), 'click', this.setTripType.bind(this));
		Event.observe($('bp-oneway'), 'click', this.setTripType.bind(this));
		// city selects
		Event.observe($('bp-from'),	'change', this.originChangeListener.bind(this));
		Event.observe($('bp-to'),	'change', this.checkToCity.bind(this));
		// find flights
		Event.observe($('bp-submit'), 'click', this.validate.bindAsEventListener(this));
		//Event.observe($('btn-submit'), 'click', this.validate.bindAsEventListener(this));

	},

	/**
	 * Sets return or one way
	 */
	setTripType: function ()
	{
		if ($('bp-oneway').checked)
		{
			$('bp-day-return').disabled = 'disabled';
			$('bp-month-return').disabled = 'disabled';
			// disable the calendar date picker
			if (typeof(cal_objs) != 'undefined') {
				if (cal_objs.length >= 2)
					cal_objs[1].disable();
			}
		}
		else
		{
			$('bp-day-return').disabled = false;
			$('bp-month-return').disabled = false;
			// enable the calendar date picker
			if (typeof(cal_objs) != 'undefined') {
				if (cal_objs.length >= 2)
					cal_objs[1].enable();
			}
		}
	},

	/**
	 * Origin changed event handler
	 */
	originChangeListener: function ()
	{
		this.setDestinationCities($('bp-from').value);
	},

	/**
	 * Sorts contries
	 */
	sortCountries: function (countriesOrder)
	{
		var temp;
		for( var i=0 ; i<countriesOrder.length ; i++ )
		{
			for( var j=0 ; j<bp_show_only_countries.length ; j++)
			{
				if( bp_show_only_countries[j] == countriesOrder[i] )
				{
					temp = bp_show_only_countries[i];
					bp_show_only_countries[i] = bp_show_only_countries[j];
					bp_show_only_countries[j] = temp;
				}
			}
		}
	},

	/**
	 * Populates the destination list depending on the origin selection
	 */
	setDestinationCities: function (origin_city)
	{
		this.checkToCity();
		curr_city = origin_city;
		
		// if now show only list is set, fill out the array
		// with the default list
		if ( bp_show_only_countries.length <= 0 ) {
			for (var i in bp_countries) {
				bp_show_only_countries.push(i);
			}
		}

		if ( bp_site == 'va' && bp_country_of_residence == 'au' )
		{
			// Order the destination cities for AU facing VAustralia
			var countriesOrder = new Array('US', 'CA', 'ZA', 'TH' );
			this.sortCountries( countriesOrder );
		}

		// clear the to select list
		$('bp-to').length = 0;
		
		// clear the market warning panel
		el = $('bp-marketwarning');

		if (el) {
			el.style.display = 'none';
		}
		
		// create Destination default option
		this.createSelectOption($('bp-to'), '', 'Destination', false, '');
		
		last_country = '';
		
		for ( i = 0; i < bp_show_only_countries.length; i++ ) {
			if (curr_city) {
				for ( x = 0; x < bp_cities[curr_city].ports.length; x++ ) {
					
					country 	= bp_show_only_countries[i]
					iata 		= bp_cities[curr_city].ports[x];
					port_city 	= bp_cities[iata];
					
					if ( country == port_city.country ) {
						
						if (bp_remove_cities.indexOf(iata) == -1) {
							
							if (country != last_country && bp_show_countries) {
								
								 if (bp_show_only_cities.length > 0) {
									
									for ( y = 0; y < bp_show_only_cities.length; y++ ) {
										
										if (bp_cities[bp_show_only_cities[y]].country == country && country != last_country && bp_show_only_cities.indexOf(iata) != -1) {
											
											// this removes Thailand for PER->HKT from the VA bpanel (only) as its a VB flight (and all other HKT flights are VA)
                			// --stirratt
                			//if (bp_site == 'va' && $('bp-from').value == 'PER' && country == 'TH') {
												// do nothing
												// c o nsole.log('removed th');
											//} else {

											// We're not adding each port.
											// For now, don't add dest:Nadi if it's not orig:Sydney.
											if (bp_site == 'va' && country == 'FJ' && $('bp-from').value != 'SYD') {
												// Do nothing.
											} else {
												this.createSelectOption($('bp-to'), '', '----- ' + bp_countries[country].name.toUpperCase() + bp_countries[country].dash, true, 'bp-country');
											}
											//}
											last_country = country;
										}
									}
								 } else {
									this.createSelectOption($('bp-to'), '', '----- ' + bp_countries[country].name.toUpperCase() + bp_countries[country].dash, true, 'bp-country');
									last_country = country;
								 }
							}
							if (bp_show_only_cities.length <= 0) {
									
									this.createSelectOption($('bp-to'), iata, port_city.name, false);
							}
							if (bp_show_only_cities.length > 0 && bp_show_only_cities.indexOf(iata) != -1) {
								// this removes PER->HKT from the VA bpanel (only) as its a VB flight (and all other HKT flights are VA)
                // --stirratt
								//if (bp_site == 'va' && $('bp-from').value == 'PER' && iata == 'HKT') {
									// do nothing
									// c o nsole.log('d');
								//} else {
								
								// We're not adding each port.
								// For now, don't add dest:Nadi if it's not orig:Sydney.
								if (bp_site == 'va' && port_city.name == 'Nadi' && $('bp-from').value != 'SYD') {
									// Do nothing.
								} else {
									this.createSelectOption($('bp-to'), iata, port_city.name, false);
								}
							}
						}
					}
				}
			}
		}
		
		// set the selected value to the bp_default_dest if it exists
		if (typeof(bp_default_dest) != 'undefined') {
			if (bp_default_dest.length > 0) {
				for ( i = 0; i < $('bp-to').options.length; i++ ) {
					if ($('bp-to').options[i].value == bp_default_dest) {
						$('bp-to').options[i].setAttribute('selected', 'selected');
						$('bp-to').selectedIndex = i;
					}
				}
			}
		}
		
		// give message as to why destination drop down is empty
		if ($('bp-to').length == 1) {
			if (curr_city) {
				this.createSelectOption($('bp-to'), '', 'No results for ' + bp_cities[curr_city].name, false, '');
			} else {
				this.createSelectOption($('bp-to'), '', 'Please select an origin above', false, '');
			}
		}
	},

	/**
	 * Shows or hides the amadeus travel class fields
	 */
	checkToCity: function ()
	{
		// check if the city is part of the armadeus array and if so show the 
		// hidden row
		el = $('bp-travelclass-row');
		if (el) {
			if (bp_site != 'va') {
				if (this.checkAmadeusCities()) {
					el.style.display = 'block';
				} else {
					el.style.display = 'none';
				}
			}
		}

		// checks for a certain combination of city pairs and shows a warning
		el = $('bp-marketwarning');
		if (el) {
			if (this.checkCityPairForWarning()) {
					el.innerHTML = this.getCityPairWarningText();
					el.style.display = 'block';
			} else {
					el.innerHTML = '';
					el.style.display = 'none';
			}
		}
	},

	/**
	 * Is there likely to be a warning for certain city pairs?
	 */
	checkCityPairForWarning: function ()
	{
		return false;
	},

	/**
	 * Get the exact city pair warning message
	 */
	getCityPairWarningText: function ()
	{
		if ($('bp-from').value == 'PER')
		{
			return 'Please be aware that any direct flights from Perth to Phuket are operated by Virgin Blue. Flights to Phuket connecting via Melbourne or Brisbane are operated by V Australia.';
		}
		
		if ($('bp-from').value == 'SYD' || $('bp-from').value == 'MEL' || $('bp-from').value == 'BNE')
		{
			return 'Please be aware that any flights to Phuket connecting via Perth are operated by Virgin Blue. Flights to Phuket connecting via Melbourne or Brisbane are operated by V Australia.';
		}
	},

	/**
	 * Determines if the amadeus engine is to be used
	 */
	checkAmadeusCities: function ()
	{
		// exception for HKT: use amadeus if on va site
		if ( ($('bp-to').value == 'HKT' || $('bp-from').value == 'HKT') && bp_site == 'va' ) {
			return true;
		}
		// exception for HKT: use amadeus if departing from NZ
		if ( $('bp-to').value == 'HKT' && bp_cities[$('bp-from').value].country == 'NZ' ) {
			return true;
		}

		// exception for SYD -> NAN from 18 Dec 2009 onwards use VA, else use VB
		var depart_date = Number($('bp-month-depart').value) * 100 + Number($('bp-day-depart').value);
		if ( ($('bp-from').value == 'SYD' && $('bp-to').value == 'NAN') && depart_date >= 20091218 && bp_site != 'vb' ) {
			return true;
		}
		
		// otherwise detect as normal
		if (amedeus_cities.indexOf($('bp-to').value) != -1 || amedeus_cities.indexOf($('bp-from').value) != -1) {
			return true;
		}
	},

	/**
	 * Creates an <option> tag
	 */
	createSelectOption: function (select_elem, value, text, disabled, css_class)
	{
		o = document.createElement('option');
		o.value = value;
		if (disabled) o.disabled = 'disabled';
		if (css_class) o.className = css_class;
		o_text = document.createTextNode(text);
		o.appendChild(o_text);
		select_elem.appendChild(o);
	},

	/**
	 * Sets an origin manually
	 */
	setOrigin: function (iata)
	{
		
		found = false;
		option_els = Element.childElements($('bp-from'));
		
		for (i = 0; i < option_els.length; i++) {
			if (option_els[i].value == iata) {
				found = true;
			}
		}
		
		// set destinations cities
		if (typeof(bp_default_dest) != 'undefined') {
			this.setDestinationCities($('bp-from').value);
		} else if (iata.length == 3 && found) {
			$('bp-from').value = iata;
			this.setDestinationCities($('bp-from').value);
		} else {
			$('bp-from').selectedIndex = 0;
		}
	},

	/**
	 * Gets the cookied origin
	 */
	getOriginCookie: function ()
	{
		c_name 	= "vborigin";
		c		= ' ' + document.cookie + ';';
		c_start	= c.indexOf(c_name) + (c_name.length + 1);	
		c_end 	= c.indexOf(';', c_start);
		c_data 	= unescape(c.substring(c_start, c_end));
		return c_data;
	},

	/**
	 * Sets the origin cookie
	 */
	setOriginCookie: function ()
	{
		// before submitting, set a cookie for the selected origin
		d = new Date();
		d.setTime(d.getTime() + 2000*24*60*60*1000);
		d = d.toGMTString();
		cookie_name = "vborigin";
		document.cookie	= cookie_name + '='+ escape($('bp-from').value)+ '; expires=' + d + '; path = /'
	},

	/**
	 * Validates the corrent booking panel state
	 */
	validate: function (event)
	{
		if (event) {
			event.stop();
		}
		this.validateCities();
		this.validateDates();
		this.validatePax();
		
		if (this._error_box._errors.length > 0) {
			this._error_box._error_ref = eval(bp_engine+'_errors');
			this._error_box.show();
		} else {
			this.generateHiddenForm();
			
			// bp_site and bp_engine are globals
			if (bp_site == 'vb' && bp_engine == 'va') {
				var thisobj = this;
				var timeout = function () { thisobj.submit() };
    			window.setTimeout(timeout, 4000);
				this.showVaustMessage();
			} else {
				if (bp_engine == 'va')
				{
					this.submit();
				}
				else
				{
					FindFlights();
				}
			}
		}
	},
	
	/**
	 * Shows the vaustralia redirect warning message
	 */
	showVaustMessage: function ()
	{
		var path = '';
		
		if (typeof(bp_path) != 'undefined') {
			path = bp_path;
		}
	
		var mURL = path + 'vaustralia_message.php'
		
		this.vaustMessagePanel = new AjaxMessagePanel('vaust-message', mURL);
		this.vaustMessagePanel.show();
	},
	
	/**
	 * Shows the vaustralia redirect warning message
	 */
	closeVaustMessage: function ()
	{
		if (typeof(this.vaustMessagePanel) != 'undefined')
		{
			this.vaustMessagePanel.close();
		}
	},

	/**
	 * Validates the chosen city pairs
	 */
	validateCities: function ()
	{
		// always reset engine to default
		bp_engine = this._default_engine;
		
		// check a departing city has been selected
		tmp = ($('bp-from').value == '' || $('bp-from').value == -1);
		this._error_box.evalError(tmp, 'missingDepartCity');
		
		// check a return city has been selected

		tmp2 = ($('bp-to').value == '' || $('bp-to').value == -1);
		this._error_box.evalError(tmp2, 'missingArriveCity');

		// if no error check city against amadeus array
		if (!tmp && !tmp2) {
			// amedeus_cities is a global array :)
			if (this.checkAmadeusCities()) {
				bp_engine = 'va';
			}
		}

		var testNZHKTNoReturn = this.validateNZHKTNoReturn();
		this._error_box.evalError(testNZHKTNoReturn, 'HKTReturnOnly');

		var testLHRNoReturn = this.validateLHRNoReturn();
		this._error_box.evalError(testLHRNoReturn, 'HKTReturnOnly');
	},

	/**
	 * Validates the chosen dates
	 */
	validateDates: function ()
	{
		
		// check a return date is not before the departing date// if round trip
		today = new Date();
		
		// check if global start date variable exists
		if ( typeof(bp_start_date) != 'undefined' ) {
			today_date  = new Date(bp_start_date[2], bp_start_date[1]-1, bp_start_date[0]);
			va_start_date  = new Date(bp_start_date[2], bp_start_date[1]-1, bp_start_date[0]);
		} 
		// otherwise use todays date
		else {
			today_date  = new Date(today.getFullYear(), today.getMonth(),today.getDate());
			va_start_date  = new Date('1900', '12', '31');
		}
		
		depart_d = $('bp-day-depart').value;
		depart_m = $('bp-month-depart').value.substring(4,6);
		depart_y = $('bp-month-depart').value.substring(0,4);
		
		depart_date = new Date(depart_y, (depart_m - 1), depart_d);
		
		// days of the month validation
		tmp = this.validateDayMonth(Number(depart_d), Number(depart_m)) ? true : false;
		this._error_box.evalError(tmp, 'monthDaysDepart');
		
		// leap year for february validation
		if (Number(depart_m) == 2) {
			tmp = this.validateLeapYear(Number(depart_d), Number(depart_m), depart_y) ? true : false;
			this._error_box.evalError(tmp, 'monthDaysDepart');
		}

      // traveling dates validation - HKT/JNB date warnings

      // Phuket
			if ($('bp-from').value != 'PER') {
				tmp = this.validateHKTStartDate(Number(depart_d), Number(depart_m), depart_y);
            
      	this._error_box.evalError(tmp, 'badHKTDate');
			}

      // Johannesburg
			tmp = this.validateJNBStartDate(Number(depart_d), Number(depart_m), depart_y);
    		this._error_box.evalError(tmp, 'badJNBDate');	
		
		tmp = (today_date.getTime() > depart_date.getTime()) ? true : false;
		//this._error_box.evalError(tmp, 'departdateEarly');

		if (today_date.getTime() == va_start_date.getTime()){
			this._error_box.evalError(tmp, 'departdateEarlyb');
		}
		else {
			this._error_box.evalError(tmp, 'departdateEarly');
		}
		
		if ($('bp-round').checked) {
			
			return_d = $('bp-day-return').value;
			return_m = $('bp-month-return').value.substring(4,6);
			return_y = $('bp-month-return').value.substring(0,4);
			
			return_date = new Date(return_y, (return_m - 1), return_d);
			
			// days of the month validation
			tmp = this.validateDayMonth(Number(return_d), Number(return_m)) ? true : false;
			// this._error_box.evalError(tmp, 'monthDaysReturn');
			this._error_box.evalError(tmp, 'monthDaysDepart');
			
			// leap year for february validation
			if (Number(return_m) == 2) {
				tmp = this.validateLeapYear(Number(return_d), Number(return_m), return_y) ? true : false;
				// this._error_box.evalError(tmp, 'monthDaysReturn');
				this._error_box.evalError(tmp, 'monthDaysDepart');
			}
			
			// make sure departing date is before return date
			tmp = (depart_date > return_date) ? true : false;
			this._error_box.evalError(tmp, 'dateDiff');
			
			// make sure return date isn't before today
			tmp = (today_date.getTime() > return_date.getTime()) ? true : false;
			this._error_box.evalError(tmp, 'returndateEarly');
			
		}
	},

	/**
	 * Validates leap year dates
	 */
	validateLeapYear: function (d, m, y)
	{
		
		error = false;
		leap = 0;
		
		if ((y % 4 == 0) || (y % 100 == 0) || (y % 400 == 0)) {
		  leap = 1;
		}
		if ((m == 2) && (leap == 1) && (d > 29)) {
		  error = true;
		}
		if ((m == 2) && (leap != 1) && (d > 28)) {
		  error = true;
		}
		
		return error;
	},

	/**
	 * Validates the day of month is _not_ 31 on months which have 30 days
	 */
	validateDayMonth: function (d, m)
	{
		
		error = false;
		
		if ((d > 30) && ((m == 4) || (m == 6) || (m == 9) || (m == 11))) {
		  error = true;
		}
		
		return error;
	},

	/**
	 * Validates the PER-> HKT start dates
	 */
	validatePERHKTStartDate: function (d, m, y)
	{
		// not HKT? break early.
		if ($('bp-to').value != 'HKT' && $('bp-from').value != 'PER')
			return false;
	
		var testDate = new Date(2009, 11, 14);
		var suppliedDate = new Date(y, m, d);
	
		if (suppliedDate < testDate) {
			return true;
		}
	
		return false;
	},

	/**
	 * Validates HKT flight start dates
	 */
	validateHKTStartDate: function (d, m, y)
	{
		// not HKT? break early.
		if ($('bp-to').value != 'HKT')
				return false;
	
		var testDate = new Date(2009, 11, 22);
		var suppliedDate = new Date(y, m, d);
	
		if (suppliedDate < testDate) {
			return true;
		}
	
		return false;
	},

	/**
	 * Validates JNB flight start dates
	 */
	validateJNBStartDate: function (d, m, y)
	{
		// not JNB? break early.
		if ($('bp-to').value != 'JNB' && $('bp-from').value != 'JNB')
				return false;
	
		var testDate = new Date(2010, 3, 13);	
		var suppliedDate = new Date(y, m, d);
	
		if (suppliedDate < testDate) {
			return true;
		}
	
		return false;
	},

	/**
	 * Enforces one way from NZ to HKT
	 */
	validateNZHKTNoReturn: function ()
	{

		if ($('bp-to').value != 'HKT')
		{
				return false;
		}

		
		// if one way and:
		// NZ is the originating country
		if ($('bp-to').value == 'HKT' && bp_cities[$('bp-from').value].country == 'NZ' && !$('bp-round').checked)
		{
			return false;
		}
		
		return false;
  },

	/**
	 * Enforces one way from NZ to LHR
	 */
	validateLHRNoReturn: function ()
	{
		if ($('bp-to').value != 'LHR')
		{
			return false;
		}

		// if one way and:
		// LHR is the destination port
		if ($('bp-to').value == 'LHR' && !$('bp-round').checked)
		{
			return true;
		}

		return false;
	},

	/**
	 * Validates passenger numbers
	 */
	validatePax: function ()
	{
		a = Number($('bp-pax-adult').value);
		c = Number($('bp-pax-child').value);
		i = Number($('bp-pax-infant').value);
		
		// check the maximum amount of passengers
		pax_total = a + c + i;
		tmp = (pax_total > bp_prefs[bp_engine].maxPax) ? true : false;
		this._error_box.evalError(tmp, 'maxpax');
		
		// check there aren't more infants than adults
		tmp = (a < i) ? true : false;
		this._error_box.evalError(tmp, 'infants');
	},

	

	/**
	 * Amadeus specific forms fields creation
	 */
	createVAForm: function ()
	{
		engine 	 = 'va';

		var origin = $('bp-from').value;
		var destination = $('bp-to').value;

		if ( bp_cities[origin]['country'].match(/^(nz|us|za)$/i) ) {
			bp_country_of_residence = bp_cities[origin]['country'].toLowerCase();
		}
		else {
			// any other countries get no special treatment / variable settings
			bp_country_of_residence = "au";
		}

		// determine which URL to post to
		if (this._filter_search) {
			form_url = '/apps/vaustralia/flightsearch/find_flights.php';
		}
		else {
			form_url = 'http://book.vaustralia.com.au/pl/VAustralia/wds/Override.action';

			if (typeof(bp_country_of_residence) != 'undefined') {
				if ((bp_country_of_residence == 'us') || (bp_country_of_residence == 'za')) {
					form_url = 'http://book.vaustralia.com/pl/VAustralia/wds/Override.action';
				} else if (bp_country_of_residence == 'nz') {
					form_url = 'http://book.vaustralia.com/pl/VAustralia/wds/Override.action';
				}
			}
		}

		if ($('bp-hidden-'+engine)) {
			$('bp-hidden-'+engine).remove();
		}
		
		this.createHiddenForm('bp-hidden-'+engine, 'bp-hidden-'+engine, form_url, $('bp-hidden'));
	
		this.createHiddenField('B_DATE_1', 'bp-date-1-'+engine, $('bp-month-depart').value + $('bp-day-depart').value + '0000');
	
		this.createHiddenField('B_LOCATION_1', 'bp-to-'+engine, $('bp-from').value);
		this.createHiddenField('E_LOCATION_1', 'bp-from-'+engine, $('bp-to').value);
	
		if ($('bp-round').checked) {
			//this.createHiddenField('B_LOCATION_2', 'bp-to-round-'+engine, $('bp-to').value);
			//this.createHiddenField('E_LOCATION_2', 'bp-from-round-'+engine, $('bp-from').value);
			this.createHiddenField('B_DATE_2', 'bp-date-2-'+engine, $('bp-month-return').value + $('bp-day-return').value + '0000');
			this.createHiddenField('TRIP_TYPE', 'bp-triptype-'+engine, 'R');
		} else {
			this.createHiddenField('TRIP_TYPE', 'bp-triptype-'+engine, 'O');
		}
		if ($('bp-date-flex')) {
			if ($('bp-date-flex').checked) {
				this.createHiddenField('DATE_RANGE_QUALIFIER_1', 'bp-date-range-'+engine, 'C');
				this.createHiddenField('DATE_RANGE_VALUE_1', 'bp-date-range-value-'+engine, '3');
			}
		}
		// new fields rec'd from amadeus
		this.createHiddenField('EMBEDDED_TRANSACTION', 'bp-embedded-transaction-'+engine, 'FlexPricerAvailability');
		this.createHiddenField('DISPLAY_TYPE', 'bp-display-type-'+engine, '2');
		this.createHiddenField('PRICING_TYPE', 'bp-pricing-type-'+engine, 'O');
		this.createHiddenField('SITE', 'bp-site-'+engine, 'CBAVCBAV');
		//this.createHiddenField('COMMERCIAL_FARE_FAMILY_1', 'bp-commercial-ff-'+engine, 'CFFPREM');
		this.createHiddenField('WDS_ARRANGE_BY', 'bp-arrange-by-'+engine, 'E');
		this.createHiddenField('WDS_HBX_ID_E', 'bp-hbx-id-'+engine, 'DM5707176LZS03EN3');
		this.createHiddenField('DATE_RANGE_QUALIFIER_1', 'bp-dr-qualifier-'+engine, 'C');
		this.createHiddenField('DATE_RANGE_VALUE_1', 'bp-dr-value-'+engine, '3');
		this.createHiddenField('DATE_RANGE_QUALIFIER_2', 'bp-dr-qualifie2-'+engine, 'C');
		this.createHiddenField('DATE_RANGE_VALUE_2', 'bp-dr-value2-'+engine, '3');
	
		if (typeof(bp_country_of_residence) != 'undefined') {
			this.createHiddenField('SO_SITE_COUNTRY_OF_RESIDENCE_BIS', 'bp-country-residence-bis-'+engine, bp_country_of_residence);
			this.createHiddenField('SO_SITE_COUNTRY_OF_RESIDENCE', 'bp-country-residence-'+engine, bp_country_of_residence);
		} else {
			this.createHiddenField('SO_SITE_COUNTRY_OF_RESIDENCE_BIS', 'bp-country-residence-bis-'+engine, 'AU');
			this.createHiddenField('SO_SITE_COUNTRY_OF_RESIDENCE', 'bp-country-residence-'+engine, 'AU');
		}
	
		if (typeof(bp_country_of_residence) != 'undefined') {
			if (bp_country_of_residence == 'us') {
				this.createHiddenField('SO_SITE_OFFICE_ID', 'bp-site-office-id-'+engine, 'LAXVA08AA');
				this.createHiddenField('SO_SITE_QUEUE_OFFICE_ID', 'bp-site-queue-office-id-'+engine, 'LAXVA08AA');
			} else if (bp_country_of_residence == 'nz') {
				this.createHiddenField('SO_SITE_OFFICE_ID', 'bp-site-office-id-'+engine, 'AKLVA08AA');
				this.createHiddenField('SO_SITE_QUEUE_OFFICE_ID', 'bp-site-queue-office-id-'+engine, 'AKLVA08AA');
			} else if (bp_country_of_residence == 'za') {
				this.createHiddenField('SO_SITE_OFFICE_ID', 'bp-site-office-id-'+engine, 'JNBVA08AA');
				this.createHiddenField('SO_SITE_QUEUE_OFFICE_ID', 'bp-site-queue-office-id-'+engine, 'JNBVA08AA');
			} else {
				this.createHiddenField('SO_SITE_OFFICE_ID', 'bp-site-office-id-'+engine, 'BNEVA08AA');
				this.createHiddenField('SO_SITE_QUEUE_OFFICE_ID', 'bp-site-queue-office-id-'+engine, 'BNEVA08AA');
			}
		} else {
			this.createHiddenField('SO_SITE_OFFICE_ID', 'bp-site-office-id-'+engine, 'BNEVA08AA');
			this.createHiddenField('SO_SITE_QUEUE_OFFICE_ID', 'bp-site-queue-office-id-'+engine, 'BNEVA08AA');
		}
		this.createHiddenField('SKIN', 'bp-skin-'+engine, 'VA');
		//this.createHiddenField('WDS_VA_FRONTEND_URL', 'bp-wds-va-frontendurl-'+engine, 'nceyadam.nce.amadeus.net');
		this.createHiddenField('LANGUAGE', 'bp-language-'+engine, 'GB');
		this.createHiddenField('BOOKING_FLOW', 'bp-flow-'+engine, 'FLEX_PRICER_ITINERARY');
		//this.createHiddenField('IsWDS', 'bp-iswds-'+engine, 'TRUE');
		this.createHiddenField('SO_SITE_FP_NB_RECO', 'bp-reco-'+engine, '400');
					this.createHiddenField('WDS_BOOKING_FLOW', 'bp-wds-booking-flow', 'REVENUE');	
		// these are only test server paramters
		//if (this._test_server) {
			//this.createHiddenField('SERVER', 'bp-server-'+engine, 'SITE ACCEPTANCE');
			//this.createHiddenField('BACKEND', 'bp-backend-'+engine, 'PRODUCTION');
			//this.createHiddenField('OVERRIDE_CC_PARAMS', 'bp-override-'+engine, 'Y');
	
			this.createHiddenField('SO_SITE_APIV2_SERVER', 'bp-site-api-'+engine, '194.76.166.179');
			this.createHiddenField('SO_SITE_APIV2_SERVER_USER_ID', 'bp-site-api-id-'+engine, 'OCG');
			this.createHiddenField('SO_SITE_APIV2_SERVER_PWD', 'bp-site-api-pwd-'+engine, 'API2000');
			this.createHiddenField('SO_SITE_CORPORATE_ID', 'bp-site-corp-id-'+engine, 'OCG-MUCWW28AA');
	
			this.createHiddenField('SO_SITE_MAX_AIR_DATE_SPAN', 'bp-site-max-air-'+engine, 'M12');
			this.createHiddenField('SO_SITE_MAXIMAL_TIME', 'bp-site-maximal-air-'+engine, 'M12');
			this.createHiddenField('SO_SITE_MIN_AVAIL_DATE_SPAN', 'bp-site-minimal-avail-'+engine, 'H3');
			this.createHiddenField('SO_SITE_MINIMAL_TIME', 'bp-site-minimal-time-'+engine, 'H3');
			this.createHiddenField('SO_SITE_CMP_DATE_IN_GMT', 'bp-site-date-gmt-'+engine, 'TRUE');
			this.createHiddenField('BANNER', 'bp-banner-test-'+engine, 'TEST');
	
		//}
	
		var bp_temp_travel_class = $('bp-travelclass').value;
	
		if (typeof(bp_country_of_residence) != 'undefined') {
			if (bp_country_of_residence == 'nz') {
				bp_temp_travel_class = bp_temp_travel_class + 'NZ';
			}
			if (bp_country_of_residence == 'za') {
				bp_temp_travel_class = bp_temp_travel_class + 'ZA';
			}
		}
	
		switch ($('bp-travelclass').value) {
			case 'CFFLITE':
			case 'CFFECO':
			case 'CFFPREM':
			case 'CFFBUS':
				this.createHiddenField('COMMERCIAL_FARE_FAMILY_1', 'bp-commercial-ff-1-'+engine, bp_temp_travel_class);
				break;
			default:	// nothing is written if the value is invalid
				break;
		}
	
		//alert('country: '+bp_country_of_residence+' fare: '+bp_temp_travel_class);
	
		// get amount of pax
		a = Number($('bp-pax-adult').value);
		c = Number($('bp-pax-child').value);
		i = Number($('bp-pax-infant').value);
	
		for (x = 1; x <= a; x++) {	this.createHiddenField('TRAVELLER_TYPE_'+x, 'bp-travel-type-'+x+'-'+engine, 'ADT') }
		for (x = 1; x <= c; x++) {	this.createHiddenField('TRAVELLER_TYPE_'+(x+a), 'bp-travel-type-'+(x+a)+'-'+engine, 'CHD'); }
		if (i) {
			for (x = 1; x <= i; x++) { this.createHiddenField('HAS_INFANT_'+x, 'bp-has-infant-'+x+'-'+engine, 'TRUE'); }
		} else {
			this.createHiddenField('HAS_INFANT_1', 'bp-has-infant-'+engine, 'FALSE');
		}
	
		this.createHiddenField('SO_QUEUE_NUMBER', 'bp-site-queue-no-'+engine, '8');
		this.createHiddenField('SO_QUEUE_CATEGORY', 'bp-site-queue-cat-'+engine, '99');
	},
	
	/**
	 * Creates and appends a hidden form field
	 */
	createHiddenField: function (name, id, value)
	{
		append_elem = this.hiddenFormElem;
		
		if (!$(id)) {
			o = document.createElement('input');
			o.type = 'hidden';
			o.name = name;
			if (id)
				o.id = id;
	
			o.value = value;
			append_elem.appendChild(o);
		} else {
			$(id).value = value;
		}
	},
	
	
	/**
	 * Creates and appends a hidden form field
	 */
	createHiddenForm: function (name, id, action, append_elem)
	{
		if (!$(id))
		{
			f = document.createElement('form');
			f.method = 'post';
			f.id = id;
			f.name = name;
			f.action = action;
			append_elem.appendChild(f);
		}
		this.hiddenFormElem = $(id);
		return this.hiddenFormElem;
	},
	
	
	/**
	 * Executes the form creation function for the current bp engine
	 */
	generateHiddenForm: function ()
	{
		// depending on the engine run the correct form generator
		if (bp_engine == 'va')
		{
			this.createVAForm();
		}
	},

	/**
	 * Submits the form
	 */
	submit: function ()
	{
		this.setOriginCookie();
		var hasPopup = false;
		
		// find the current hidden form
		form = $('bp-hidden-'+bp_engine);
		//alert(form.COMMERCIAL_FARE_FAMILY_1.value);
		if (bp_engine == 'va') {
			if (typeof(Popup) != 'undefined') {
				this._popup = new Popup({ 
					url 		: '/apps/booking_panel/please_hold.php', 
					name 		: 'amadeus', 
					resizable 	: 1, 
					scrollbars 	: 1,
					width 		: '100%', 
					height 		: '100%' 
				});
				this._popup.launch();
				form.setAttribute('target', 'amadeus');
			}
		}
		else if (typeof(newskiesValidation) != 'undefined') {
			// new skies cutover - travel on the cutover day requires a popup informing of potential delays.
			var departDateString = '' + $('bp-month-depart').value + $('bp-day-depart').value;
			var arriveDateString = '' + $('bp-month-return').value + $('bp-day-return').value;

			var newskies = new newskiesValidation( Number(departDateString), Number(arriveDateString) );
			hasPopup = newskies.checkForPopup();
		}

		if (this.debugVars)
		{
			form.setAttribute('action', '/apps/booking_panel/print_post_vars.php');
		}

		// submit the flight panel form
		if (form)
		{
			// check if the guest has closed the popup without clicking the link to proceed.
			if (hasPopup) {
				var timeout = function () {
					if (newskies.newskiesMessagePanel.overlayDiv) {
						window.setTimeout(timeout, 2000);
					}
					else {
						form.submit();
					}
				};
				window.setTimeout(timeout, 4000);
			}
			else {
				form.submit();
			}
		}

		// close the amadeus message overlay
		// and redirect to Vaustralia website
		if (bp_site == 'vb' && bp_engine == 'va')
		{
			this.closeVaustMessage();
			window.location = "http://www.vaustralia.com.au/?from1="+$('bp-from').value+"&to1="+$('bp-to').value
		}
	}
});


/*Scripts for skysales*/

	/*
	Determines whether to send request to skylights or skysales, and
	then sends request.
	*/
function FindFlights() {

	// validate depart date
	var departDay1Index = $('bp-day-depart').selectedIndex;
	var departMonth1Index = $('bp-month-depart').selectedIndex;

	// validate return date
	var isOneWay = $("bp-oneway").checked;
	var departDay2Index = $('bp-day-return').selectedIndex;
	var departMonth2Index = $('bp-month-return').selectedIndex;

	// Set months in correct format for posting
	$('departMonth1').value = FixMonthYear($('bp-month-depart').value);
	$('departMonth2').value = FixMonthYear($('bp-month-return').value);
	
	// Fill the new skies variable here
	if (isOneWay) {
		var tripType = "OneWay";
	} else {
		var tripType = "RoundTrip";
	}


	var origin1 = $('bp-from').value;
	var day1 = $('bp-day-depart').value;
	
	var month1Raw = $('bp-month-depart').value;
	var month1 = month1Raw.substring(0, 4) + "-" + month1Raw.substring(4);
	
	var destination1 = $('bp-to').value;
	var origin2 = "";
	var day2 = $('bp-day-return').value;
	var month2Raw = $('bp-month-return').value;
	var month2 = month2Raw.substring(0, 4) + "-" + month2Raw.substring(4);
	var destination2 = "";
	var origin3 = "";
	var day3 = "";
	var month3 = "";
	var destination3 = "";
	var adultNum = $('bp-pax-adult').value;
	var childNum = $('bp-pax-child').value;
	var infantNum = $('bp-pax-infant').value;
	var currencyCode = $('currency').value;
	var fareTypes = "I";
	// var searchBy = "columnView";
	var date_picker = "";
	var urlInArray = document.URL.split("/");
	var cultureVal = "en-AU";

	// PB: added to cover combined Melbourne airport search
	var useMacOrigin1 = "";
	var useMacDestination1 = "";

	if ( typeof($("searchTypeFlexible")) != 'undefined' && $("searchTypeFlexible").checked ) {
		var searchType = $("searchTypeFlexible").value;
	}
	else if(typeof($("searchTypeMustTravel")) != 'undefined') {
		var searchType = $("searchTypeMustTravel").value;
	}
	else {
		var searchType = "columnView";
	}
	
	returnButton = document.getElementById("return");
	divNode = returnButton.parentNode.parentNode.parentNode;
	fieldNode = divNode.parentNode;
	formNode = fieldNode.parentNode;

	formNode.setAttribute("action", "http://book.virginblue.com.au/Search.aspx");

	addSkysalesInput("pageToken", "sLkmnwXwAsY=", formNode);
	addSkysalesInput("culture", cultureVal, formNode);
	addSkysalesInput("__VIEWSTATE", "/wEPDwUBMGQYAQUeX19Db250cm9sc1JlcXVpcmVQb3N0QmFja0tleV9fFgEFL1N0YXRpY0Rpc3BsYXlXZWxjb21lU2VhcmNoVmlldyRDaGVja0JveFByb21vT3B01vbgRxrRoI5cv2RyiNuBSO4wESc=", formNode);
	addSkysalesInput("ControlGroupSearchMainView$AvailabilitySearchInputSearchMainView$RadioButtonMarketStructure", tripType, formNode);
	addSkysalesInput("ControlGroupSearchMainView$AvailabilitySearchInputSearchMainView$TextBoxMarketOrigin1", origin1, formNode);
	addSkysalesInput("ControlGroupSearchMainView$AvailabilitySearchInputSearchMainView$DropDownListMarketDay1", day1, formNode);
	addSkysalesInput("ControlGroupSearchMainView$AvailabilitySearchInputSearchMainView$DropDownListMarketMonth1", month1, formNode);
	addSkysalesInput("ControlGroupSearchMainView$AvailabilitySearchInputSearchMainView$TextBoxMarketDestination1", destination1, formNode);
	addSkysalesInput("ControlGroupSearchMainView$AvailabilitySearchInputSearchMainView$TextBoxMarketOrigin2", origin2, formNode);
	addSkysalesInput("ControlGroupSearchMainView$AvailabilitySearchInputSearchMainView$DropDownListMarketDay2", day2, formNode);
	addSkysalesInput("ControlGroupSearchMainView$AvailabilitySearchInputSearchMainView$DropDownListMarketMonth2", month2, formNode);
	addSkysalesInput("ControlGroupSearchMainView$AvailabilitySearchInputSearchMainView$TextBoxMarketDestination2",destination2, formNode);
	addSkysalesInput("ControlGroupSearchMainView$AvailabilitySearchInputSearchMainView$DropDownListSearchBy", searchType, formNode);
	addSkysalesInput("ControlGroupSearchMainView$AvailabilitySearchInputSearchMainView$DropDownListPassengerType_ADT",adultNum, formNode);
	addSkysalesInput("ControlGroupSearchMainView$AvailabilitySearchInputSearchMainView$DropDownListPassengerType_CHD",childNum, formNode);
	addSkysalesInput("ControlGroupSearchMainView$AvailabilitySearchInputSearchMainView$DropDownListPassengerType_INFANT",infantNum, formNode);
	addSkysalesInput("ControlGroupSearchMainView$AvailabilitySearchInputSearchMainView$DropDownListCurrency",currencyCode, formNode);
	addSkysalesInput("ControlGroupSearchMainView$AvailabilitySearchInputSearchMainView$DropDownListFareTypes",fareTypes, formNode);
	addSkysalesInput("ControlGroupSearchMainView$ButtonSubmit", "", formNode);
	addSkysalesInput("date_picker", date_picker, formNode);
	addSkysalesInput("ControlGroupSearchMainView$AvailabilitySearchInputSearchMainView$fromCS", "yes", formNode);
		
	formNode.submit();
}

function addSkysalesInput(name, value, form)
{
	if(document.getElementsByName(name)[0]==undefined) {
		input = document.createElement('input');
		input.setAttribute("type", "hidden");
		input.name = name;
		input.value = value;
		form.appendChild(input);
	} else {
		document.getElementsByName(name)[0].value = value
	}
}

/*
Converts MMYYYY to YYYYMM for Skysales date format
*/
function FixMonthYear(str, carrier) {
	var m = str.substring(4);
	var y = str.substring(0, 4);
	return y + '-' + m;
}

/**
* days_in_month returns the number of days in the selected month, works for leap years
* @return days in month
* Date: 2010/06/28 Hau Le
*/
function days_in_month(iMonth, iYear)
{
	var d = new Date(iYear, iMonth - 1, 32).getDate();
    //alert(d + ' '+ iMonth + ' ' + (32-d));
	return (32 - d);
}	
/**
* get_num_days_in_month sets the departDayX (X is integer eg. 1, 2, ..) to the correct number of days in the selected month/year
* @param form_month_year_obj pass form object eg. departMonth1
* @param form_day_obj pass form object eg. departDay1
* @param bCalendar boolean 0, 1: load objects month/Year from function and not from form field
* @return nil
* Date: 2010/06/28 Hau Le
*/
function get_num_days_in_month(form_month_year_obj, form_day_obj, bCalendar)
{			
	if(bCalendar == 1)	// variables from skyframe calendar popup
	{
		var y = form_month_year_obj.substr(0,4);
		var m = form_month_year_obj.substr(4,2);
	}
	else    // objects from skyframe form fields and class_date_picker.js (main booking panel)
	{
		var y = form_month_year_obj.options[form_month_year_obj.selectedIndex].value.substr(0,4);
		var m = form_month_year_obj.options[form_month_year_obj.selectedIndex].value.substr(4,2);
	}
	
	var d_index = form_day_obj.options[form_day_obj.selectedIndex].value; // get value of selected form day
	var d_new = days_in_month(m, y);        // get number of days in current selected month	
	form_day_obj.options.length = d_new;	// set length of form day select to new days_in_month		
	var i_new="";
	var j=1;
    var d_selected="";
    //alert(y + ' ' + m + ' ' + form_day_obj.value + ' ' + d_new);
	for (var i=1; i <= d_new; i++) 
	{			
		i_new = (i < 10 ? "0"+j : j);
		form_day_obj.options[i-1]= new Option(i_new, i_new, false, false);	// create new Select Options list for new number of days in selected month
		j++;
	}
	d_selected = (d_index <= d_new ? d_index-1 : 0);	// set to 01 selected if user selects day 31 manually for eg. Jan 2010, then selects Feb 2010 	
	form_day_obj.selectedIndex=d_selected;
}
/**
* This function used to fix date bug when changing Depart date Jun 2011, select Return Feb 2011, numbers of days in Return date sets to 28, when it should be 30 same as Depart date
* @param form_month_year_obj pass form object eg. bp-month-return
* @param form_day_obj pass form object eg. bp-day-return
* @param bCalendar boolean 0, 1: load objects month/Year from function and not from form field
* @param form_depart_month_year_obj pass form object eg. bp-month-depart
* @param form_depart_day_obj pass form object eg. bp-day-depart
* @return nil
* Date: 2010/07/01 Hau Le
*/
function validate_against_depart_date(form_month_year_obj, form_day_obj, bCalendar, form_depart_month_year_obj, form_depart_day_obj)
{
	if(bCalendar == 1)	// variables from skyframe calendar popup
	{
		var y_return = form_month_year_obj.substr(0,4);
		var m_return = form_month_year_obj.substr(4,2);
		var y_depart = form_month_year_obj.substr(0,4);
		var m_depart = form_month_year_obj.substr(4,2);
	}
	else    // objects from skyframe form fields and class_date_picker.js (main booking panel)
	{
		var y_return = form_month_year_obj.options[form_month_year_obj.selectedIndex].value.substr(0,4);
		var m_return = form_month_year_obj.options[form_month_year_obj.selectedIndex].value.substr(4,2);
		var y_depart = form_depart_month_year_obj.options[form_depart_month_year_obj.selectedIndex].value.substr(0,4);
		var m_depart = form_depart_month_year_obj.options[form_depart_month_year_obj.selectedIndex].value.substr(4,2);
	}
	if(y_return == y_depart && m_return < m_depart || y_return < y_depart)  // eg. Depart Nov 10 > Return Jul 10, eg. Depart Feb 11 > Return Jun 11 > Return Jul 10
	{
		get_num_days_in_month(form_depart_month_year_obj, form_day_obj, bCalendar);
	}	
	else
	{		
		get_num_days_in_month(form_month_year_obj, form_day_obj, bCalendar);
	}
}