//by Great Han
var MSG = {
	depart_city: 'Please provide departure city.',
	dest_city: 'Please provide arrival city.',
	depart_date: 'Please provide departure date.',
	depart_err: 'Please check departure date.',
	depart_date1: 'Please provide flight 2 departure date.',
	return_date: 'Please check arrival date.',
	return_err: 'Return date cannot be earlier than departure date.',
	same_city: 'Departure city and arrival city cannot be the same.',
	final_city: 'Please provide flight 2 arrival city.',
	date_err: 'Departure date cannot precede current date.',
	date_err1: 'Flight 2 departure date cannot be earlier than Flight 1 departure date.',
	both_intl: 'Either departure city or arrival city must be within Mainland China.',
	both_dmt: 'Either departure city or arrival city must be outside Mainland China.',
	five_hour: 'This flight is too close to departure time to be booked online. Please call 400 619 9999 for more information.',
	HMT: 'Hong Kong, Macau and Tapei require international bookings.<br />Select the international flights tab to book international flights or connections.'
};

var $m = function(){
	var args = arguments,
		l = args.length,
		rlt = [];
	for (var i = 0; i < l; i++) rlt.push($(args[i], true));
	return rlt;
};

function starttime(obj,str){
	var str = str.split(' '),
		d = str[0].split('-'),
		time = str[1].split(':'),
		bd = new Date(d[0], d[1]-1, d[2], time[0], time[1]);
		//cd = new Date();
	if($('NSTime')) {
		var NSTime = $('NSTime').value,
		cd = new Date(NSTime),	//The NSTime is like "2009/06/16 20:30:20"
		nd = NSTime.split(' '),
		nd1 = nd[0].split('/'),
		nd2 = nd[1].split(':'),
		isTimeout = false;
	}
	if (time[0] - 0 <= 10) {	//If the fly time is before 10:00
		if (nd1[2] == d[2]) {	//If the same date
			if(nd2[0] - 0 < 8) {
				isTimeout = true;
			}
		}
		else {
			if(nd2[0] - 0 > 20) {
				isTimeout = true;
			}
			else if(nd2[0] - 0 == 20) {
				if(nd2[1] - 0 >= 30) {
					isTimeout = true;
				}
			}
		}
	}
	if (isTimeout || bd - cd <= 18000000) {
		$alert(obj,MSG.five_hour,false,"tr","rb");
		return false;
	}
	return true;
}

$r('domready', function(){
	window.fm = document.forms[0];
	//interFlightTips
	var tips=$('internationalTips');
	var html = $$.module.interFlightQuery?$$.module.interFlightQuery.TipsHTML:'';
		if(tips&&html)tips.innerHTML=html;
	var	isQueryPage = /SearchFlights|query\.aspx?/i.test(location.href),
		qtb = $m('fltDomestic', 'fltInternational'),
		FlightWay = $m('flightway1', 'flightway2'),
		qtb_classes = [
			['oneway', 'roundtrip', 'destination'],
			['oneway', 'roundtrip', 'openround']
		],
		passenger_type = $m('passenger_type', 'passenger_type1'),
		child_tip = $m('child_tip', 'child_tip1');

	if (!isQueryPage) {
		$('flights_list').$('tr').$each(function(el, i){
			if (i != 0) {
			el.$r('mouseover', function(){
				this.className = 'prilist_select_hover';
			});
			el.$r('mouseout', function(){this.className = ''});
			}
		});
	}
	

	(function(){
		var _ = this;
		_.v = function(){
			var a = arguments,
				l = a.length;
			if(l == 1) {
				if (typeof a[0] == 'string') return _[a[0]] ? _[a[0]].value : null;
				else for (var p in a[0]) if(_[p]) _[p].value = a[0][p];
			} else if (l == 2) if (_[a[0]]) _[a[0]].value = a[1];
			return _;
		};
		_.post = function(){
			var fltWay = _.v('flightway1');
			_.action = _.v('domesticAction');
			function isHMT(cityID){
				return new RegExp("\\|" + cityID + "\\|", 'i').test('|HKG|MFM|TPE|')
			}
			if (fltWay == 'M') {
				if (isHMT(_.v('flight11Code'))) {
					$alert(_.depart_city1, MSG.HMT);
					return false;
				}
				if (isHMT(_.v('flight12Code'))) {
					$alert(_.dest_city1, MSG.HMT);
					return false;
				}
				if (isHMT(_.v('flight04Code'))) {
					$alert(_.dest_city2, MSG.HMT);
					return false;
				}
			}
			if (isHMT(_.v('flight01Code')) || isHMT(_.v('flight02Code'))) {
				_.action = _.v('intlAction');
				var psgr_type = _.v('passenger_type');
				if (psgr_type == 'BAB') psgr_type = 'CHI';
				_.v({
					'intlDCityCode': _.v('flight01Code'),
					'intlACityCode': _.v('flight02Code'),
					'flt_type': 'international',
					'depart1_city': _.v('depart_city'),
					'dest1_city': _.v('dest_city'),
					'depart1_date': _.v('depart_date'),
					'depart1_time': _.v('depart_time'),
					'return_date1': _.v('return_date'),
					'return_time1': _.v('return_time'),
					'passenger_type1': psgr_type,
					'passenger_num1': _.v('QuantitySelect'),
					'flightway2': fltWay=='M'?'S':fltWay,
					'class2': _.v('DSeatSelect')
				});
				return;
			}
			_.v('FlightWay', fltWay);
			switch (fltWay) {
				case 'D':
					_.v({
						'ADatePeriod1': _.v('return_date').parseStdDate(),
						'startPeriod2': _.v('return_time')
					});
				case 'S':
					_.v({
						'HomeCity': _.v('depart_city'),
						'DestCity1': _.v('dest_city'),
						'TicketAgency_List': _.v('depart_city')
					});
					break;
				case 'M':
					_.v({
						'flight01Code': _.v('flight11Code'),
						'flight02Code': _.v('flight12Code'),
						'HomeCity': _.v('depart_city1'),
						'DestCity1': _.v('dest_city1'),
						'DestCity2': _.v('dest_city2'),
						'ADatePeriod1': _.v('depart_date1').parseStdDate(),
						'startPeriod2': _.v('depart_time1'),
						'TicketAgency_List': _.v('depart_city1')
					});
			}
			_.v({
				'DDatePeriod1': _.v('depart_date').parseStdDate(),
				'startPeriod': _.v('depart_time'),
				'DSeatClass': _.v('DSeatSelect'),
				'ChildType': _.v('passenger_type'),
				'Quantity': _.v('QuantitySelect'),
				'airlineChoice': _.v('airline')
			});
			return true;
		};
	}).apply(fm);
	
	window.checkInternational = function(){ return chkFn[FlightWay[1].selectedIndex + 3]();};
	
	window.intlSubmit = function(){
		if (chkFn[FlightWay[1].selectedIndex + 3]()) {
			fm.action = fm.v('intlAction');
			fm.submit();
		}
	};
	function removePostBack(){
		function removeExt(objId){
			var obj = $(objId);
			if (obj) obj.parentNode.removeChild(obj);
		}
		removeExt("__VIEWSTATE");
		removeExt("__EVENTARGUMENT");
		removeExt("__EVENTTARGET");
	}
	window.domesticSubmit = function(){
		if (chkFn[FlightWay[0].selectedIndex]()) {
			if (!isQueryPage) removePostBack();
			fm.submit();
		}
	};
	if (fm.v('flt_type')=='international') {
		$(isQueryPage?'prifltinternational_querybar':'pubglobal_tab01').module.tab.select(2);
		if(tips){
			if(!tips.$isDisplay())	{
				tips.style.display="";
				tips.style.zIndex=100;
				tips.$setIframe();
			}
		}
	}


	qtb.each(function(el, i){
		el.className = 'prifltinternational_query_table priflt_' +
						qtb_classes[i][FlightWay[i].selectedIndex];
	});

	function chTitle(){
		var t = $('fltQ_title', true),
			tab_cn = $('tab_cn', true),
			tab_en = $('tab_en', true),
			flt_type = $('flt_type', true);		
		if (t) t.innerHTML = (FlightWay[0].selectedIndex == 2) ? 'Find 2 flights' : 'Find a flight';
		if (tab_en) tab_en.onclick = function(){
			if (isQueryPage) t.innerHTML = 'Find a flight';
			flt_type.value = 'international';
			if(!tips)	return;
			if(!tips.$isDisplay())	{
				tips.style.display="";
				tips.style.zIndex=100;
				tips.$setIframe();
			}			
		};
		if (tab_cn) tab_cn.onclick = function(){
			if (isQueryPage) chTitle();
			flt_type.value = 'domestic';
			if(!tips)	return;
			if(tips.$isDisplay()){
				tips.style.display="none";
				tips.$clearIframe();
			}
			
		}
	};

	chTitle();	
	(function (){
		if(!tips)	return;
		var closeBtn=tips.$("a")[0];
		if(closeBtn){
			closeBtn.onclick=function(){
				tips.style.display="none";
				tips.$clearIframe();
			}
		}
	})();
	FlightWay.each(function(el, i){
		el.$r(['change', 'keyup'], function(){
			qtb[i].className = 'prifltinternational_query_table priflt_' +
								qtb_classes[i][this.selectedIndex];
			if (el == FlightWay[0]) chTitle();
		});
	});
	
	passenger_type.each(function(el, i){
		child_tip[i].style.display = (el.selectedIndex == 0) ? 'none' : 'block';
		el.$r(['change', 'keyup'], function(){
			child_tip[i].style.display = (this.selectedIndex == 0) ? 'none' : 'block';
		});
	});

	$('dest_city1', true).$r(['keyup', 'blur'], function(){$('depart_city2', true).value = this.value});
	

});

(function(){
//make $alert return false
var $alt = function(o, msg){
	$alert(o, msg);
	return false;
};

String.prototype.toStdDate = function(){
	var arr = this.split('-');
	return new Date(arr[0], arr[1] - 1, arr[2]);
};
/*
 date = [a1, a2]  
 a1： 第一个日期input的ID
 a2：第二个日期input的ID
 如果只有一个日期则和当天比较
 msg = [m1, m2, m3] MSG属性名
 m1：第一个日期提示信息
 m2：第二个日期提示信息
 m3：第二个日期小于第一个日期的提示信息
*/
function checkDate(date, msg){
	if($('NSTime')) {
		var NSTime = $('NSTime').value;
	}
	var isSingleDate = !date[1];
		dt1 = $(date[0], true),
		dt2 = isSingleDate ? dt1 : $(date[1], true),
		v1 = 
			isSingleDate ?
			new Date(NSTime).toStdString().toStdDate() :
			//new Date().toStdString().toStdDate() :
			dt1.value.parseStdDate().toStdDate(),
		v2 = dt2.value.parseStdDate();
	v2 = v2 ? v2.toStdDate() : false;
	return dt1.isNull() ?
			$alt(dt1, MSG[msg[0]]) :
			!v1 ? $alt(dt1, MSG[msg[1]]) :
			dt2.isNull() ?
			$alt(dt2, MSG[msg[2]]) :
			!v2 ? $alt(dt2, MSG[msg[3]]) :
			v1 > v2 ? $alt(dt2, MSG[msg[4]]) : 1;
}

/*
 city = [c1, c2]
 c1：出发城市input的ID
 c2：目的城市input的ID
 date = [d1, d2]参考checkDate
*/
function checkOneway(city, date, intl){
	var cc1 = function(){return checkCity(city[0], 'depart_city')},
		cc2 = function(){return checkCity(city[1], 'dest_city')},
		ccs = function(){
			return ($(city[0], true).value.replace(/\(.*?\)/,'') == $(city[1], true).value.replace(/\(.*?\)/,'')) ?
					$alt($(city[1]), MSG.same_city) : 1;
		},
		cc3 = intl ? function(){
			var c1 = $(intl[0], true).value,
				c2 = $(intl[1], true).value,
				isDmt = new RegExp("\\|\\|" + c2 + "@").test($$.module.address.source.fltInternational_cn),
				isHMT = new RegExp("\\|" + c1 + "\\|").test('|58|59|617|');
			return isHMT?1:isDmt?$alt(city[1],MSG['both_dmt']):1;
		} : function(){return true},
		cd = function(){
			return checkDate(date, 
				['depart_date', 'depart_err', 'depart_date', 'depart_err', 'date_err']
			)
		};
	return cc1() ? cc2() ? ccs() ? cc3() ? cd() ? 1 : cd() : cc3() : ccs() : cc2() : cc1();
}

/*
 city与checkOneway中的city一样
*/
function checkRoundtrip(city, date, intl){
	var co = function(){return checkOneway(city, [date[0]], intl)},
		cd = function(){
			return checkDate(date,
				['depart_date', 'depart_err', '', 'return_date', 'return_err'])};
	if ($(date[1], true).isNull() && co()) {
		var fltp = fm.v('flt_type'),
			fltWay = {
			'domestic': 'flightway1',
			'international': 'flightway2'
		}[fltp];
		$(fltWay, true).value= 'S';
		if (fltp == 'domestic') fm.v('FlightWay', 'S');
		return true;
	}
	return co() ? cd() ? 1 : cd() : co();
}

/*
 check single city
 cityID：一个地址input的ID
 msg：提示信息
*/
function checkCity(cityID, msg){
	var city = $(cityID, true);
	return city.isNull() ? $alt(city, MSG[msg]) : 1;
}

/*
 city1 = [c1, c2]
 city2 = [c1, c2]
 city1 city2与checkOneway中的city一样
 date = [d1, d2]
 date与checkDate中的date一样
*/
function checkMulti(city1, city2, date){
	var co1 = function(){return checkOneway(city1, ['depart_date'])},
		co2 = function(){return  checkCity(city2[1], 'final_city')},
		ccs = function(){
			return ($(city2[0], true).value.replace(/\(.*?\)/,'') == $(city2[1], true).value.replace(/\(.*?\)/,'')) ?
					$alt($(city2[1]), MSG.same_city) : 1;
		},
		cd = function(){
			return checkDate(date,
				['depart_date', 'depart_err', 'depart_date1', 'depart_err1', 'date_err1']
			)
		};
	return co1() ? co2() ? ccs() ? cd() ? 1 : cd() : ccs() : co2() : co1();
}

window.chkFn = [
	function(){fm.post();return checkOneway(['depart_city', 'dest_city'], ['depart_date'])},
	function(){fm.post();return checkRoundtrip(['depart_city', 'dest_city'], ['depart_date', 'return_date'])},
	function(){return fm.post() && checkMulti(['depart_city1', 'dest_city1'], ['depart_city2', 'dest_city2'], ['depart_date', 'depart_date1'])},
	function(){return checkOneway(['depart1_city', 'dest1_city'], ['depart1_date'], ['txtDCityCode', 'txtACityCode'])},
	function(){return checkRoundtrip(['depart1_city', 'dest1_city'], ['depart1_date', 'return_date1'], ['txtDCityCode', 'txtACityCode'])},
	function(){return checkOneway(['depart1_city', 'dest1_city'], ['depart1_date'], ['txtDCityCode', 'txtACityCode'])}
];
})();