/*
	
	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	: 	'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;
		bp_engine = this._default_engine;
		
		this._form = elem.getElementsByTagName('form')[0];
		this._error_box = new ErrorBox();
		
		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));
		Event.observe($('bp-to'),	'change', this.checkToCity.bindAsEventListener(this));
		// find flights
		Event.observe($('bp-submit'), 'click', this.validate.bindAsEventListener(this));
	},
	/*
		Set one way or round
	*/
	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();
			}
		}
	},
	/*
		Listener for origin select element change events
	*/
	originChangeListener : function (event) {
		this.setDestinationCities($('bp-from').value);
	},
	/*
		Sets destination cities based on your origin selection
			- simply uses the 'from' element value
	*/
	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);
			}
		}
		// clear the to select list
		$('bp-to').length = 0;
		
		// 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.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.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, '');
			}
		}
	},
	/*
		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) {
		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);
		} else if (iata.length == 3 && found) {
			$('bp-from').value = iata;
			this.setDestinationCities($('bp-from').value);
		} 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();
			
			// 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);
				showVaustMessage();
			} else {
				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');
		
		// if no error check city against va array
		if (!tmp) {
			// amedeus_cities is a global array :)
			if (amedeus_cities.indexOf($('bp-from').value) != -1) {
				bp_engine = 'va';
			}
		}
		// check a return city has been selected
		tmp = ($('bp-to').value == '' || $('bp-to').value == -1);
		this._error_box.evalError(tmp, 'missingArriveCity');
		
		// if no error check city against amadeus array
		if (!tmp) {
			// amedeus_cities is a global array :)
			if (amedeus_cities.indexOf($('bp-to').value) != -1) {
				bp_engine = 'va';
			}
		}
	},
	/*
		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]);
			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');
		}
		
		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');
			
			// 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');
			}			
			
			// 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');
			
		}
	},
	/*
		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();
		
		// find the current hidden form
		form = $('bp-hidden-'+bp_engine);
		
		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');
			}
		}
		//form.setAttribute('action', 'print_post_vars.php');
		
		// submit the flight panel form
		if (form) {
			form.submit();
		}
		
		// close the amadeus message overlay
		// and redirect to Vaustralia website
		if (bp_site == 'vb' && bp_engine == 'va') {
			closeVaustMessage();
			window.location = "http://www.vaustralia.com.au/?from1="+$('bp-from').value+"&to1="+$('bp-to').value
		}
	}
});
