/*
	
	Booking Panel Class
	
*/
var BookingPanel = Class.create({
	_error_box		: [],
	_form			: null,
	/*
		Initializes the Booking Panel.
	*/
	initialize : function(elem, options) {
		
		this.options = {
			show_countries	:	false,
			countries		: 	false,
			cities			:	false,
			errors			:	false,
			prefs			: 	false,
			test_server		: 	false,
			default_engine	: 	'ap'
		};
		
		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;
		bp_engine = 'ap';
		
		this._form = elem.getElementsByTagName('form')[0];
		this._error_box = new ErrorBox();
		
		if($('form-flights')) {
		this.assignEvents();
		
		this.setOrigin(this.getOriginCookie());
		}
  	},
	/*
		Create event observers
	*/
	assignEvents : function() {
		// trip type radios
		//Event.observe($('bp-round'), 'click', this.setTripType.bindAsEventListener(this));
		//Event.observe($('bp-oneway'), 'click', this.setTripType.bindAsEventListener(this));
		// city selects
		Event.observe($('bp-from'),	'change', this.originChangeListener.bindAsEventListener(this, 'bp-from'));
		Event.observe($('bp-to'),	'change', this.checkToCity.bindAsEventListener(this));
		Event.observe($('bp-from2'),	'change', this.originChangeListener.bindAsEventListener(this, 'bp-from2'));
		Event.observe($('bp-to2'),	'change', this.checkToCity.bindAsEventListener(this));
		Event.observe($('bp-from3'),	'change', this.originChangeListener.bindAsEventListener(this, 'bp-from3'));
		Event.observe($('bp-to3'),	'change', this.checkToCity.bindAsEventListener(this));
		// find flights
		Event.observe($('bp-submit'), 'click', this.validate.bindAsEventListener(this));
		Event.observe($('bp-findflights'), 'click', this.validateFindFlights.bindAsEventListener(this));
	},
	/*
		Set one way or round
	*/
	setTripType : function () {
	},
	/*
		Listener for origin select element change events
	*/
	originChangeListener : function (event, originListID) {
		var destListID = 'bp-to';
		
		switch (originListID) {
			case 'bp-from':
					destListID = 'bp-to';
				break;
			case 'bp-from2':
					destListID = 'bp-to2';
				break;
			case 'bp-from3':
					destListID = 'bp-to3';
				break;
			default:
				break;
		}
		
		this.setDestinationCities($F(originListID), destListID);
	},
	/*
		Sets destination cities based on your origin selection
			- simply uses the 'from' element value
	*/
	setDestinationCities : function ( origin_city, destListID ) {
		
		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);
			}
		}
		// clear the to select list
		$(destListID).length = 0;
		
		// create Destination default option
		this.createSelectOption($(destListID), '', '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.createSelectOption($(destListID), '', '----- ' + bp_countries[country].name.toUpperCase() + bp_countries[country].dash, true, 'bp-country');
											last_country = country;
										}
									}
								 } else {
									this.createSelectOption($(destListID), '', '----- ' + bp_countries[country].name.toUpperCase() + bp_countries[country].dash, true, 'bp-country');
									last_country = country;
								 }
							}
							if (bp_show_only_cities.length <= 0) {
								this.createSelectOption($(destListID), iata, port_city.name, false);
							}
							if (bp_show_only_cities.length > 0 && bp_show_only_cities.indexOf(iata) != -1) {
								this.createSelectOption($(destListID), 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 < $(destListID).options.length; i++ ) {
					if ($(destListID).options[i].value == bp_default_dest) {
						$(destListID).options[i].setAttribute('selected', 'selected');
						$(destListID).selectedIndex = i;
					}
				}
			}
		}
		
		// give message as to why destination drop down is empty
		if ($(destListID).length == 1) {
			if (curr_city) {
				this.createSelectOption($(destListID), '', 'No results for ' + bp_cities[curr_city].name, false, '');
			} else {
				this.createSelectOption($(destListID), '', 'Please select an origin above', false, '');
			}
		}
	},
	/*
		Checks the to city for armadeus
	*/
	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 (amedeus_cities.indexOf($('bp-to').value) != -1 || amedeus_cities.indexOf($('bp-from').value) != -1) {
					el.style.display = 'block';
				} else {
					el.style.display = 'none';
				}
			}
		}
	},
	/*
		Creates and appends an option to passed select
	*/
	createSelectOption : function (select_elem, value, text, disabled, css_class) {
		var 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 the the origin
	*/
	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, 'bp-to');
		} else if (iata.length == 3 && found) {
			$('bp-from').value = iata;
			this.setDestinationCities($('bp-from').value, 'bp-to');
		} else {
			$('bp-from').selectedIndex = 0;
		}
	},
	/*
		Get cookie for chosen 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;
	},
	/*
		Set cookie for chosen origin
	*/
	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 = /'
	},
	/*
		Checks the booking panel for errors
	*/
	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.createHiddenForm();
			this.submit();
		}
	},
	/*
		Checks the booking panel for errors
	*/
	validateFindFlights : function (event) {
		if (event) {
			event.stop();
		}
		
		format_findflights_form();
		this.submit();
	},
	/*
		Validates cities
	*/
	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
		tmp = ($('bp-to').value == '' || $('bp-to').value == -1);
		this._error_box.evalError(tmp, 'missingArriveCity');

	},
	/*
		Validates 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]);
		} 
		// otherwise use todays date
		else {
			today_date  = new Date(today.getFullYear(), today.getMonth(),today.getDate())
		}
		depart_d = $('bp-day-depart').value;
		depart_m = $('bp-month-depart').value.substring(5,7);
		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');
		}
		
		tmp = (today_date.getTime() > depart_date.getTime()) ? true : false;

		this._error_box.evalError(tmp, 'departdateEarly');

	},
	/*
		Makes sure the day chosen for February is ok
	*/
	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 date numbers in relation to their month / year
	*/
	validateDayMonth : function (d, m) {
		
		error = false;
		
		if ((d > 30) && ((m == 4) || (m == 6) || (m == 9) || (m == 11))) {
		  error = true;
		}
		
		return error;
	},
	/*
		Validates passengers
	*/
	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');
	},
	/*
		Formats the hidden fields as per certain booking systems requirements
	*/
	createHiddenForm : function () {
		// depending on the engine run the correct 
		// hidden field formatting function and set the active form
		field_function = 'format_'+bp_engine+'_form()';
		eval(field_function);
	},
	/*
		Submits the booking form and sets a cookie for chosen origin
	*/
	submit : function () {
		this.setOriginCookie();
		var hasPopup = false;
		// find the current hidden form
		form = $('bp-hidden-'+bp_engine);

		if (typeof(newskiesValidation) != 'undefined') {
			// new skies cutover - travel on the cutover day requires a popup informing of potential delays.
			var month_hack = $('bp-month-depart').value.replace(" ", "");
			month_hack = month_hack.substring(0,6);
			var departDateString = '' + month_hack + $('bp-day-depart').value;

			month_hack = $('bp-month-depart2').value.replace(" ", "");
			month_hack = month_hack.substring(0,6);
			var arriveDateString = '' + month_hack + $('bp-day-depart2').value;

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

		// 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();
			}
		}
	}
});