/*
	
	Globals
	
*/
var bp_path = '/apps/airpass/booking_panel/';

/*
	bp_site
	- defines which site the user is one
*/
var bp_site = 'ap';

/*
	bp_engine
	- defines which engine the booking panel is using. We need this as a separate
	variable because you could be on the Virgin Blue site, but because you've selected a V Australia destination
	the booking panel will be using the V Australia engine and rules
*/

var bp_engine = 'ap';

/*
	
	Preferences
	
*/
var bp_prefs = {
	'ap'  : {
		'maxPax': 9
	},
	'va'  : {
		'maxPax': 9
	}
};
/*
	
	Errors
	
*/
var bp_errors_val;
var ap_errors = {
	'missingDepartCity'	: 'Please select the city you will be departing from',
	'missingArriveCity'	: 'Please choose your destination.',
	'maxpax'			: 'You are allowed a maximum of '+bp_prefs.va.maxPax+' passengers per booking.',
	'infants'			: 'You are unable to book a greater number of Infants than Adults',
	'dateDiff'			: 'Your return date is earlier than your departing date',
	'departdateEarly'	: 'Your departing date is earlier than today',
	'returndateEarly'	: 'Your return date is earlier than today',
	'departdateEarlyb'	: 'Flights commence 15 December. Please select a departing date on or after this date',
	'returndateEarlyb'	: 'Flights commence 15 December. Please select a return date date on or after this date',
	'monthDaysDepart'	: 'You have selected an invalid date.',
	'monthDaysReturn'	: 'You have selected an invalid date.'
};
/*
	
	Dom Ready Instructions
	
*/
//Event.observe(window, 'load',  function() {   
document.observe('dom:loaded', function() {

	// new booking engine instance
	if($('form-flights')) {
		ap_bp = new BookingPanel($('booking-panel'), 
			{ 
				show_countries 	: true, 
				test_server		: true,
				countries 		: bp_countries, 
				cities 			: bp_cities
			}
		);
		// create date pickers for booking panel
		cal_objs = new Array();
		
		init_DatePickers(cal_objs);
		
		// in case one way is checked
		ap_bp.setTripType();
	}
	if (typeof(bp_site) != 'undefined') {
		if (bp_site == 'vb' && $('bp-tabs')) {
			bp_tabs = new CompactTabs();
		}
	}
//});
}); 
/*

	Date Pickers aren't bound to the booking panel class
	they're merely helpers to pick dates and are therefore
	separate
	
*/
function init_DatePickers (cal_objs) {
	$$('.calendar').each(function(elem) {
		cal_obj	= new DatePicker( elem );
		cal_objs.push(cal_obj);
	});


	cal_objs[0].pair(cal_objs[1]);
	cal_objs[0].pair(cal_objs[2]);
	cal_objs[1].pair(cal_objs[0]);
	cal_objs[1].pair(cal_objs[2]);
	cal_objs[2].pair(cal_objs[0]);
	cal_objs[2].pair(cal_objs[1]);

}

function format_findflights_form () {
	//DODGY, move into a funciton or something
	var str = window.location + '';
	if (str.substring(0, 12) == 'http://apdev') {
		form_url = 'https://test.airpass.com.au/airpass/Booking.action?begin';
	} else {
		split_string = str.split('/');
		form_url = 'https://' + split_string[2] + '/airpass/Booking.action?begin';
		//form_url = str.replace('http://', 'https://') + (str.substring(str.length-1)!='/'?'/':'') + 'airpass/Booking.action?begin';
	}
	format_ap_form(form_url);

	// trip 4
	createHiddenField('flightComponents[3].origin', 'bp-from4-'+engine, '', form);
	createHiddenField('flightComponents[3].destination', 'bp-to4-'+engine, '', form);
	createHiddenField('flightComponents[3].departureDate.dayOfMonth', 'bp-day-depart4-'+engine, $('bp-day-depart3').value, form);
	createHiddenField('flightComponents[3].departureDate.monthYear', 'bp-month-depart4-'+engine, $('bp-month-depart3').value, form);

}

/*

	Skylights specific forms fields creation

*/
function format_ap_form (form_url) {
	
	engine = 'ap';
	var str = window.location + '';
	
	if (form_url == null) {
		if( str.substring(0, 12) == 'http://apdev'){
			form_url = 'https://test.airpass.com.au/airpass/Booking.action?gotoSelectStep';
		} else {
			split_string = str.split('/');
			form_url = 'https://' + split_string[2] + '/airpass/Booking.action?gotoSelectStep';
			//form_url = str.replace('http://', 'https://') + (str.substring(str.length-1)!='/'?'/':'') + 'airpass/Booking.action';
		}
	}
	if ($('bp-hidden-'+engine)) {
		$('bp-hidden-'+engine).remove();
	}
	form 	= createForm('bp-hidden-'+engine, 'bp-hidden-'+engine, form_url, $('bp-hidden'));
	
	// hidden static fields
	// NONE
	
	// hidden variable fields
	
	// IATAs
	createHiddenField('flightComponents[0].origin', 'bp-from1-'+engine, $('bp-from').value, form);
	createHiddenField('flightComponents[0].destination', 'bp-to1-'+engine, $('bp-to').value, form);
	
	// PAX
	createHiddenField('airpass.adultCount', 'bp-adult-'+engine, $('bp-pax-adult').value, form);
	createHiddenField('airpass.childCount', 'bp-child-'+engine, $('bp-pax-child').value, form);
	createHiddenField('airpass.infantCount', 'bp-infant-'+engine, $('bp-pax-infant').value, form);
	
	// dates 
	createHiddenField('flightComponents[0].departureDate.dayOfMonth', 'bp-day-depart1-'+engine, $('bp-day-depart').value, form);
	createHiddenField('flightComponents[0].departureDate.monthYear', 'bp-month-depart1-'+engine, $('bp-month-depart').value, form);
	
	// trip 2
	createHiddenField('flightComponents[1].origin', 'bp-from2-'+engine, $('bp-from2').value, form);
	createHiddenField('flightComponents[1].destination', 'bp-to2-'+engine, $('bp-to2').value, form);
	createHiddenField('flightComponents[1].departureDate.dayOfMonth', 'bp-day-depart2-'+engine, $('bp-day-depart2').value, form);
	createHiddenField('flightComponents[1].departureDate.monthYear', 'bp-month-depart2-'+engine, $('bp-month-depart2').value, form);
	
	// trip 3
	createHiddenField('flightComponents[2].origin', 'bp-from3-'+engine, $('bp-from3').value, form);
	createHiddenField('flightComponents[2].destination', 'bp-to3-'+engine, $('bp-to3').value, form);
	createHiddenField('flightComponents[2].departureDate.dayOfMonth', 'bp-day-depart3-'+engine, $('bp-day-depart3').value, form);
	createHiddenField('flightComponents[2].departureDate.monthYear', 'bp-month-depart3-'+engine, $('bp-month-depart3').value, form);
	
}
/*

	Creates and appends a hidden form field
	
*/
function createHiddenField (name, id, value, append_elem) {
	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
	
*/
function createForm (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);
	}
	return $(id);
}
/*

	Tab Switching for Virgin Blue
	
*/
/* booking tabs
----------------------------------------------------------------------------------------------- */
var CompactTabs = Class.create();
CompactTabs.prototype = {

_flightTab 		: "",
_checkTab 		: "",
_changeTab 		: "",
_currentTab		: "flights",
_currentHover 	: "",
_tabsElem 		: "",

	initialize: function( ) {

		this._tabsElem 		= $('bp-tabs');
		this._flightsTab 	= 'tab-flights';
		//this._checkTab 		= 'tab-webcheck';
		this._changeTab 	= 'tab-change';
		this._outer_div 	= 'booking-panel';
		this._preload		= 'bp-tab-preloader';
	  
		flightsTab = $(this._flightsTab);
		//checkTab = $(this._checkTab);
		changeTab = $(this._changeTab);
		
		this.attachLoader();
		
		//for (i = 0; i < class.length; i++) {
			if (this._tabsElem.className.indexOf('tab') != -1) {
				tab = this._tabsElem.className.split('-')[1];
				// load the tab
				this.load_tab( tab );
				// set the new current tab
				this._currentTab = tab;
			}
		//}
	  
		Event.observe(flightsTab, 'click', this.swap.bindAsEventListener(this));
		//Event.observe(checkTab, 'click', this.swap.bindAsEventListener(this));
		Event.observe(changeTab, 'click', this.swap.bindAsEventListener(this));
		
		flightsTab.onclick = function(){ this.blur(); return false; };
		//checkTab.onclick = function(){ this.blur(); return false; };
		changeTab.onclick = function(){ this.blur(); return false; };
},
	swap : function ( event ) {
  		nextTab = Event.element(event).id.split("-")[1];

		this.load_tab(nextTab);
		
  		if ( nextTab != this._currentTab ) {
			Element.removeClassName(this._tabsElem, this._flightTab+"-on");
			Element.removeClassName(this._tabsElem, this._checkTab+"-on");
			Element.removeClassName(this._tabsElem, this._changeTab+"-on");

			switch (Event.element(event).id) {
				case this._flightTab:
					Element.addClassName(this._tabsElem, this._flightTab+"-on");
			  	break;
			  	case this._checkTab:
					Element.addClassName(this._tabsElem, this._checkTab+"-on");
			  	break;
				case this._changeTab:
					Element.addClassName(this._tabsElem, this._changeTab+"-on");
			 	break;
			}
			//Element.removeClassName( $('booking-'+nextTab), "no-display" );
			this._currentTab = nextTab;
  		}
  		return false;
	},
	load_tab : function ( tab ) {
		
		h = parseFloat($('bp-'+this._currentTab).getStyle('height'));
		$('bp-'+this._currentTab).hide();
		
		empty = false;
		// if the div exists but there are no childnodes (meaning the ajax wasn't loaded previously)
		if ($('bp-'+tab)) {
			if ($('bp-'+tab).childNodes.length <= 0) {
				empty = true;
			}
		}
		if (!$('bp-'+tab) || empty) {
			
			$(this._preload).show();
			
			$(this._preload+'-img').setStyle( { marginTop: ((h/2)-40)+'px' } );
			$(this._preload).setStyle( { height: h+'px' } );
			$(this._preload+'-inner').setStyle( { height: (h-65)+'px' } ); 
			
			// create the empty div and attach it to 'booking-panel'
			tmp = document.createElement('div');
			tmp.id = 'bp-'+tab;
			
			$(this._outer_div).appendChild(tmp);
			
			path = '';
			if (typeof(bp_path) != 'undefined') {
				path = bp_path;
			}
			
			//if ('tab-'+tab == this._changeTab) {
				//import_javascript(path+'js/change_validation.js');
			//}
			// web checkin javascripts
			if ('tab-'+tab == this._checkTab) {
				import_javascript(path+'js/webcheck_validation.js');
				import_stylesheet(path+'css/webcheck.css');
			}
			
			rand = new Date().getTime();
			
			url = path+'tab_'+tab+'.php?site='+bp_site+'&rand='+rand;
			
			new Ajax.Request(url, {
			  method		: 'get',
			  evalScripts 	: true,
			  onSuccess 	: function(transport) { $('bp-'+tab).update(transport.responseText); },
			  onComplete 	: $(this._preload).hide()
			});
			// ajax load
			// new Ajax.Updater( tmp.id, 'tab_'+tab+'.php?site='+bp_site, { evalScripts : true, onComplete : $(this._preload).hide() } );
			
		} else {
			// just in case the preloader is still open
			$(this._preload).hide();
			Element.show( $('bp-'+tab) );
		}
	},
	attachLoader : function () {
		tmp = document.createElement('div');
		tmp.id = this._preload;
		
		tmp_b = document.createElement('div');
		tmp_b.className = 'clearfix bp-inner';
		tmp_b.id = this._preload+'-inner';
		
		tmp_c = document.createElement('div');
		tmp_c.className = 'submit-outer';
		tmp_c.id = this._preload+'-submit';
		
		// bp_site GLOBAL
		img = document.createElement('img');
		img.id = this._preload+'-img';
		img.src = '/apps/booking_panel/' + bp_site+'/images/preload.gif';
		
		tmp_b.appendChild(img);
		tmp.appendChild(tmp_b);
		tmp.appendChild(tmp_c);
		$(this._outer_div).appendChild(tmp);
		
		$(this._preload).hide();
	}
}

function getPageScroll(){
	var yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}

	arrayPageScroll = new Array('',yScroll) 
	return arrayPageScroll;
}
function getPageSize () {
		
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

function message_resize_old () {
	arrayPageSize = getPageSize();
	$('vaust-message-overlay').style.height 	= (arrayPageSize[3] + 'px');
	$('vaust-message-wrap').style.height 	= (arrayPageSize[3] + 'px');
	margin = (arrayPageSize[3] / 2) - (Element.getHeight('vaust-message') / 2) - 50;
	$('vaust-message').style.marginTop = margin + 'px';
}

function message_resize () {
	arrayPageSize = getPageSize();
	arrayPageScroll = getPageScroll();
	
	$('vaust-message-overlay').style.height = (arrayPageSize[1] + 'px');
	$('vaust-message-wrap').style.height 	= (arrayPageSize[1] + 'px');
	
	var messageTop = arrayPageScroll[1] + ((arrayPageSize[3] - 35 - Element.getHeight('vaust-message')) / 2);
	$('vaust-message').style.top = (messageTop < 0) ? "0px" : messageTop + "px";
}

function hideSelects (action) {
	if ( action != 'visible' ){ action='hidden'; }
	if ( navigator.appName.indexOf("Microsoft") >= 0 || navigator.appName.indexOf("MSIE") >= 0 ) {
		selects = document.body.getElementsByTagName('SELECT');
			
		for (var i = 0; i < selects.length; i++){
			selects[i].style.visibility = action;
		}
	}
}

function import_javascript(file)
{
    try {
        script = document.createElement("script");
        script.type = "text/javascript";
        script.src = file;
        head = document.getElementsByTagName("head");
        head[0].appendChild(script);
    } catch(e) {
		rand = new Date().getTime();
        document.write('<script type="text/javascript" src="' + file + '?rand=' + rand + '"></script>');
    }
}

function import_stylesheet(file)
{
    try {
        el = document.createElement("link");
        el.type = "text/css";
		el.rel = "stylesheet";
		el.media = "screen";
        el.href = file;
        head = document.getElementsByTagName("head");
        head[0].appendChild(el);
    } catch(e) {
		rand = new Date().getTime();
        document.write('<link type="text/css" rel="stylesheet" href="' + file + '?rand=' + rand + '" media="screen" />');
    }
}