﻿//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.',
	depart_err1: 'Please check 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.',
	hotel_city: 'Please provide city.',
	checkIn: 'Please provide check-in date.',
	checkOut: 'Please provide check-out date.',
	checkIn_err: 'Please check check-in date.',
	checkOut_err: 'Please check check-out date.',
	htlDate_err1: 'Check-in date cannot precede current date.',
	htlDate_err2: 'Check-out date cannot be earlier than check-in 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.',
	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 fillDistrict(){
	var cityID = $('city').value;
	if (!cityID) return;
	var zones = ZoneList[cityID],
		district = $('zone');
	district.length = 1;
	if (zones) {
		zones.split('@').each(function(el){
			var opt = $c('option'),
				zone = el.split('|');
			district.options.add(new Option(zone[1], zone[0]));
		});
	}
}

$r('domready', function(){
	var qtb = $m('fltDomestic', 'fltInternational'),
		qtb_classes = [['oneway', 'roundtrip', 'destination'], ['oneway', 'roundtrip', 'openround']],
		fwValue = [['S', 'D', 'M'], ['S', 'D', 'O']],
		fnIndex = 0,tmp,
		passenger_type = $m('passenger_type', 'passenger_type1'),
		child_tip = $m('child_tip', 'child_tip1');
	window.checkForm = chkFn[0];
	fm = document.forms[0];
	fillDistrict();
	fm.zone.selectedIndex = fm.zoneIndex.value;
	
	var fltActions = {
		test: 'http://flights.english.test.sh.ctriptravel.com',
		uat: 'http://flights.english.uat.sh.ctriptravel.com',
		online: 'http://flights.english.ctrip.com'
	};
	
	(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 _;
		};
		_.dmtPost = function(){
			_.action = fltActions[fm.v('server')] + '/Domestic/Showfarefirst.aspx';
			var fltWay = _.v('FlightWay');
			function isHMT(cityID){
				return new RegExp("\\|" + cityID + "\\|", 'i').test('|HKG|MFM|TPE|')
			}
			if (fltWay == 'M') {
				if (isHMT(_.v('flight01Code'))) {
					$alert(_.depart_city, MSG.HMT);
					return false;
				}
				if (isHMT(_.v('flight02Code'))) {
					$alert(_.dest_city, MSG.HMT);
					return false;
				}
				if (isHMT(_.v('flight04Code'))) {
					$alert(_.dest_city2, MSG.HMT);
					return false;
				}
			}
			if (isHMT(_.v('flight01Code')) || isHMT(_.v('flight02Code'))) {
				_.action = fltActions[fm.v('server')] + '/International/Showfarefirst.aspx';
				_.v({
					'intlDCityCode': _.v('flight01Code'),
					'intlACityCode': _.v('flight02Code'),
					'depart1_city': _.v('depart_city').trim(),
					'dest1_city': _.v('dest_city').trim(),
					'depart1_date': _.v('depart_date'),
					'depart1_time': _.v('depart_time'),
					'return_date1': _.v('return_date'),
					'return_time1': _.v('return_time'),
					'passenger_type1': _.v('passenger_type'),
					'passenger_num1': _.v('passenger_num'),
					'flightway2': (function(){
						var fltWay = _.v('FlightWay');
						if (fltWay == 'M') fltWay = 'S';
						return fltWay;
					})()
				});
				var c1List = _.class1,
					c2List = _.class2;
				for (var i = 0; i < 3; i++)
					c2List[i].checked = c1List[i].checked;
				return;
			}
			switch (fltWay) {
				case 'S':
				case 'D':
					_.v({
						'ADatePeriod1': _.v('return_date').parseStdDate(),
						'startPeriod2': _.v('return_time')
					});
					break;
				case 'M':
					_.v({
						'DestCity2': _.v('dest_city2'),
						'ADatePeriod1': _.v('depart_date1').parseStdDate(),
						'startPeriod2': _.v('depart_time1')
					});
			}
			_.v({
				'HomeCity': _.v('depart_city'),
				'DestCity1': _.v('dest_city'),
				'TicketAgency_List': _.v('depart_city'),
				'DDatePeriod1': _.v('depart_date').parseStdDate(),
				'startPeriod': _.v('depart_time'),
				'DSeatClass': (function(){
					var list = _.class1;
					for (var i = 0; i < list.length; i++) {
						if (list[i].checked) return list[i].value; 
					}
				})(),
				'ChildType': _.v('passenger_type'),
				'Quantity': _.v('passenger_num'),
				'airlineChoice': _.v('airline')
			});
			return true;
		},
		_.intlPost = function(){
			_.action = fltActions[fm.v('server')] + '/International/Showfarefirst.aspx';
		},
		_.htlPost = function(){
			_.action = {
				test: 'http://hotels.english.test.sh.ctriptravel.com',
				uat: 'http://hotels.engish.uat.sh.ctriptravel.com',
				online: 'http://hotels.english.ctrip.com'
			}[fm.v('server')] + '/Domestic/ShowHotelList.aspx';
			_.v({
				'starttime': _.v('checkin_date').parseStdDate(),
				'deptime': _.v('checkout_date').parseStdDate(),
				'zoneIndex': _.zone.selectedIndex
			});
		};
	}).apply(fm);
	
	//fltType = Domestic, International
	//Domestic = 0,1,2
	//International = 3,4,5
	var fltTb = $m('fltDomestic', 'fltInternational'),
		tabIndex = parseInt(fm.v('tabIndex'), 10),
		tab_fltBtn = $('tab_fltBtn'),
		tab_flt = $('tab_flt'),
		ft = fm.v('fltType'),
		isDmt = ft == 'Domestic',
		tab_fltIndex = isDmt?1:2,
		fw = $m('fw_DmtBtn', 'fw_IntlBtn'),
		funcIndex = ['Domestic', 'International'];
	checkForm = chkFn[tabIndex==0?fm.v(ft):6];
	$('searchBox').module.tab.select(tabIndex + 1);
	(function(){
		tab_fltBtn.module.tab.select(tab_fltIndex);
		tab_flt.className = 'priindex_flightsearchhead0' + {'1':2,'2':1}[tab_fltIndex];
	})();
	
	$('tab_btn').$('li').$each(function(el,i){
		if (i < 2){
			el.onclick = function(){
				fm.v('tabIndex', i);
				checkForm = chkFn[i?6:fm.v(fm.v('fltType'))];
			}
		}
	
	});
	tab_fltBtn.$('li').$each(function(el,i){
		el.onclick = function(){
			fm.v('fltType', i?'International':'Domestic');
			checkForm = chkFn[i?fm.v('International'):fm.v('Domestic')];
			tab_flt.className = 'priindex_flightsearchhead0' + (i?1:2);
			fltTb[0].style.display = i ? 'none' : 'block';
			fltTb[1].style.display = i ? 'block' : 'none';
		};
	});
	fw.each(function(btn, i){
		(function(){
			var inx = parseInt(fm.v(funcIndex[i]),10) + (i?-2:1);
			btn.module.tab.select(inx);
			qtb[i].className = 'priindex_flt_' + qtb_classes[i][inx-1];

			//switch class
			fltTb[0].style.display = isDmt ? 'block' : 'none';
			fltTb[1].style.display = isDmt ? 'none' : 'block';
		})();
		btn.$('li').$each(function(el, j){
			el.onclick = function(){
				qtb[i].className = 'priindex_flt_' + qtb_classes[i][j];
				fnIndex = i ? j + 3 : j;
				checkForm = (function(k){return chkFn[k]})(fnIndex);
				i ? fm.v({'International': fnIndex, 'flightway2': fwValue[i][j]}) :
				fm.v({'Domestic': fnIndex, 'FlightWay': fwValue[i][j]});
			};
		});
	});
	
	//children tip
	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_city', true).$r(['keyup', 'blur'], function(){$('depart_city2', true).value = this.value});
	
	var liList = $("newsList").$('li');
	liList.$each(function(el, i){
		el.onclick = function(){
			liList.$each(function(el,j){
				el.className = i==j?'prindex_gridcenter_display':'';
			});
		};
	});
	
});

(function(){
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]);
};

function checkDate(date, msg){
	var isSingleDate = !date[1];
		dt1 = $(date[0], true),
		dt2 = isSingleDate ? dt1 : $(date[1], true),
		v1 = 
			isSingleDate ?
			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;
}

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]).value.replace(/\(.*?\)/,'') == $(city[1]).value.replace(/\(.*?\)/,'')) ?
					$alt($(city[1]), MSG.same_city) : 1;
		},
		cc3 = intl ? function(){
			var c1 = $(intl[0]).value,
				c2 = $(intl[1]).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();
}
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]).isNull() && co()) {
		var fltp = fm.v('fltType'),
			isDmt = fltp == 'Domestic',
			fltWay = {
			'Domestic': 'FlightWay',
			'International': 'flightway2'
		}[fltp];
		fm[fltWay].value = 'S';
		fm[fltp].value = isDmt?0:3; 
		return true;
	}
	return co() ? cd() ? 1 : cd() : co();
}
function checkCity(cityID, msg){
	var city = $(cityID, true);
	return city.isNull() ? $alt(city, MSG[msg]) : 1;
}
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]).value.replace(/\(.*?\)/,'') == $(city2[1]).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();
}
function checkHotel(city, date){
	var cc = function(){return checkCity(city, 'hotel_city')},
		cd1 = function(){
			return checkDate([date[0]],
				['checkIn', 'checkIn_err', 'checkIn', 'checkIn_err', 'htlDate_err1']
			)
		},
		cd2 = function(){
			return checkDate(date,
				['checkIn', 'checkIn_err', 'checkOut', 'checkOut_err', 'htlDate_err2']
			)
		};
	return cc() ? cd1() ? cd2() ? 1 : cd2() : cd1() : cc();
}

this.chkFn = [
	function(){
		fm.dmtPost();
		return checkOneway(
			['depart_city', 'dest_city'],
			['depart_date']
		)
	},
	function(){
		fm.dmtPost();
		return checkRoundtrip(
			['depart_city', 'dest_city'],
			['depart_date', 'return_date']
		)
	},
	function(){
		return fm.dmtPost() && checkMulti(
			['depart_city', 'dest_city'],
			['depart_city2', 'dest_city2'],
			['depart_date', 'depart_date1']
		)
	},
	function(){
		fm.intlPost();
		return checkOneway(
			['depart1_city', 'dest1_city'],
			['depart1_date'],
			['intlDCityCode', 'intlACityCode']
		)
	},
	function(){
		fm.intlPost();
		return checkRoundtrip(
			['depart1_city', 'dest1_city'],
			['depart1_date', 'return_date1'],
			['intlDCityCode', 'intlACityCode']
		)
	},
	function(){
		fm.intlPost();
		return checkOneway(
			['depart1_city', 'dest1_city'],
			['depart1_date'],
			['intlDCityCode', 'intlACityCode']
		)
	},
	function(){
		fm.htlPost();
		return checkHotel('hotel_city', ['checkin_date', 'checkout_date'])
	}
];
})();