/**
 * 机票查询专用
 * 
 * @author Jacky
 * @param {}
 *            optionValue
 */

$(function() {
	// 宝库温馨提示,到5点自动进行提醒，5点后每20分钟提醒一次
	// showMessage('宝库提醒您', '18：00至18：10系统数据备份，届时请重新登录！');

	// 宝库温馨提示

	// 单程autocomplete
	eventAC("#from_id", "#from_id_code", "#from_suggest");
	eventAC("#to_id", "#to_id_code", "#to_suggest");
	// 航空公司下拉列表
	createCarrierOption("#airline_id");

	// 选择单程，往返，联程
	$("input[type='radio']").click(function() {
		var searchType = "single";
		$("input[type='radio']").each(function() {
			if ($(this).attr("checked")) {
				searchType = $(this).val();
			}
		});

		if (searchType == "single") {
			$("#querycontent").show();
			$(".goback_date_id").hide();
			$("#morejourneycontainer").hide();
		}
		// 往返
			else if (searchType == "goback") {
				$("#querycontent").show();
				$(".goback_date_id").show();
				$("#morejourneycontainer").hide();
			}
			// 联程
			else if (searchType == "more") {
				$("#querycontent").hide();
				$("#morejourneycontainer").show();
				// 第一段
				eventAC("#from_id_0", "#from_id_code0", "#from_suggest_0");
				eventAC("#to_id_0", "#to_id_code0", "#to_suggest_0");
				// 第二段
				eventAC("#from_id_1", "#from_id_code1", "#from_suggest_1");
				eventAC("#to_id_1", "#to_id_code1", "#to_suggest_1");
				// 第三段
				eventAC("#from_id_2", "#from_id_code2", "#from_suggest_2");
				eventAC("#to_id_2", "#to_id_code2", "#to_suggest_2");
				// 航空公司下拉列表
				createCarrierOption("#carrier_id_0");
				createCarrierOption("#carrier_id_1");
				createCarrierOption("#carrier_id_2");
			}
		});

	var inputTxt = '中文/拼音/三字码';
	// 点击机票查询按钮
	$("#search_id").click(
			function() {
				if (checkForm()) {
					$("#queryForm").attr("action",
							getURL() + "frontplatform/loading.jsp");
					$("#queryForm").submit();
				} else
					return false;
			});

});

/**
 * 宝库温馨提示
 * 
 * @param eventId
 */
function showMessage(title, content) {
	$.messager.lays(243, 185);
	$.messager.show(title, content, 0);
}

/**
 * 监听Autocomplete
 * 
 * @param eventId
 * @param resultId
 * @param divId
 */
function eventAC(eventId, resultId, divId) {
	$(eventId).suggest(citys, {
		hot_list : commoncitys,
		dataContainer : resultId,
		attachObject : divId
	});
}

/**
 * 设置下拉列表的航空公司
 */
function createCarrierOption(id) {
	// 设置航空公司
	var carrierHTML = "<option value='ALL'>"
			+ (language == 'zh' ? '所有' : 'ALL') + "</option>";
	if (carriersArray.length == 0) {
		$.ajax( {
			type : "post",
			url : getURL() + "air/domair.do?method=loadJsonCarrieres",
			dataType : "json",
			cache : false,
			success : function(data) {
				$.each(eval(data.carrieres), function(entryIndex, entry) {
					// alert(entryIndex + " ==" +
						// entry['name']);
						carriersArray[entryIndex] = new Array('-',
								entry['carrierCode'], entry['name'],
								entry['nameEn']);
					});
				carriersArray = carriersArray.sort();
				for ( var i = 0; i < carriersArray.length; i++) {
					carrierHTML += "<option value='"
							+ carriersArray[i][1]
							+ "'>"
							+ carriersArray[i][1]
							+ " "
							+ (language == 'zh' ? carriersArray[i][2]
									: carriersArray[i][3]) + "</option>";
				}
				$(id).html(carrierHTML);
			},
			error : function() {
				alert("对不起，网络繁忙，稍后重试...");
			}
		});
	} else {
		for ( var i = 0; i < carriersArray.length; i++) {
			carrierHTML += "<option value='"
					+ carriersArray[i][1]
					+ "'>"
					+ carriersArray[i][1]
					+ " "
					+ (language == 'zh' ? carriersArray[i][2]
							: carriersArray[i][3]) + "</option>";
		}
		$(id).html(carrierHTML);

	}
}

/**
 * 根据选择的类型，显示，隐藏
 * 
 * @param {}
 *            showId
 * @param {}
 *            hideId
 */
function showOrhideDivByBool(bool, showId, hideId) {
	if (showId instanceof Array) {
		for ( var id in showId) {
			bool == true ? $(id).show() : $(id).hide();
		}
	} else {
		bool == true ? $(showId).show() : $(showId).hide();
	}
	if (hideId instanceof Array) {
		for ( var id in hideId) {
			bool == true ? $(id).hide() : $(id).show();
		}
	} else {
		bool == true ? $(showId).hide() : $(showId).show();
	}
}
/**
 * 表单验证
 */
var error_ow_rt_ZH = [];
error_ow_rt_ZH[0] = new Array("请选择出发城市.");
error_ow_rt_ZH[1] = new Array("请选择到达城市.");
error_ow_rt_ZH[2] = new Array("对不起，出发/到达城市不能相同，请重新选择.");
error_ow_rt_ZH[3] = new Array("请选择出发日期.");
error_ow_rt_ZH[4] = new Array("对不起，出发日期不能早于当前日期，请修改后，重新查询！");
error_ow_rt_ZH[5] = new Array("请选择返回日期.");
error_ow_rt_ZH[6] = new Array("返回日期不能小于出发日期.");

var error_ow_rt_EN = [];
error_ow_rt_EN[0] = new Array("Please select departure city.");
error_ow_rt_EN[1] = new Array("Please Select Arrival City.");
error_ow_rt_EN[2] = new Array(
		"Sorry, departure/arrival cities can not be the same, please re-select.");
error_ow_rt_EN[3] = new Array("Please select the departure date.");
error_ow_rt_EN[4] = new Array(
		"The starting date of your choice may be inconsistent with common sense, choose the next date today, thank cooperation!");
error_ow_rt_EN[5] = new Array("Please Select Return Date.");
error_ow_rt_EN[6] = new Array(
		"Return Date can not be less than the departure date.");

function checkForm() {
	nowDate = new Date().format("yyyy-MM-dd");
	var searchType = $("input[type='radio']").val();
	$("input[type='radio']").each(function() {
		if ($(this).attr("checked")) {
			searchType = $(this).val();
		}
	});
	var startCity = $("#from_id_code").val();
	var arrivalCity = $("#to_id_code").val();
	var startdate = $("#godate").val();
	if (language == "en") {
		error_ow_rt_ZH = error_ow_rt_EN;
	}
	// 单程
	if (searchType == "single" || searchType == "goback") {
		if ($.trim(startCity) == '') {
			alert(error_ow_rt_ZH[0]);
			$("#from_id").focus();
			return false;
		}
		if ($.trim(arrivalCity) == '') {
			alert(error_ow_rt_ZH[1]);
			$("#to_id").focus();
			return false;
		}
		if ($.trim(startCity) == $.trim(arrivalCity)) {
			alert(error_ow_rt_ZH[2]);
			$("#to_id").val("");
			$("#to_id").focus();
			return false;
		}
		if ($.trim(startdate) == '') {
			alert(error_ow_rt_ZH[3]);
			$("#godate").focus();
			return false;
		}
		if (nowDate > $.trim(startdate)) {
			alert(error_ow_rt_ZH[4]);
			$("#godate").focus();
			return false;
		}
	}
	// 往返
	if (searchType == "goback") {
		var backdate = $("#backdate").val();
		if ($.trim(backdate) == '') {
			alert(error_ow_rt_ZH[5]);
			$("#backdate").focus();
			return false;
		}
		if (!(backdate >= startdate)) {
			alert(error_ow_rt_ZH[6]);
			$("#backdate").focus();
			return false;
		}
	}
	// 联程
	else if (searchType == "more") {
		var from0 = $("#from_id_code0").val();
		var to0 = $("#to_id_code0").val();
		var startdate0 = $("#startdate_0").val();
		try {
			$("input[name='startdate']")
					.each(
							function(j) {
								var startdateVal = $(this);
								if (startdateVal.val() == "") {
									alert("第" + (j + 1) + "段出发日期不可为空");
									startdateVal.focus();
									throw errorText;
								} else if (j != 0) {
									if (startdateVal.val() <= $(
											"input[name='startdate']")
											.eq(j - 1).val()) {
										alert("第" + (j + 1)
												+ "段航程出发日期不可早于或等于上面的出发日期");
										startdateVal.focus();
										throw errorText;
									}
								}
								;

							});
		} catch (e) {
			return false;
		}
		;

		try {
			$(".startcode").each(function(i) {
				if ($(this).val == "" || $(this).val() == "中文/拼音") {
					alert("第" + (i + 1) + "段出发城市不可为空");
					$(this).foucs();
					throw errorText;
				}
			});
		} catch (f) {
			return false;
		}
		;

		try {
			$(".arrivalcode").each(function(i) {
				if ($(this).val == "" || $(this).val() == "中文/拼音") {
					alert("第" + (i + 1) + "段到达城市不可为空");
					$(this).foucs();
					throw errorText;
				}
			});
		} catch (f) {
			return false;
		}
	}

	return true;
	// $("#airMain").hide();
	// $("#waiting").show();
	// $("#queryForm").submit();

}

/*
 * 多程添加删除
 * 
 */
var journey = 2;
function addjourney() {
	var jForm = '<div id="morejourney_id'
			+ journey
			+ '"  title="morejourney_id'
			+ journey
			+ '">'
			+ '<table class="td_h20">'
			+ '<tr>'
			+ '<th colspan="2"><span> 请选择&nbsp;&nbsp;第<span class="journeyNo">'
			+ (journey + 1)
			+ '</span>段行程</span><a href="javascript:deletejourney('
			+ journey
			+ ')" class="deleteJourney">移除</a></th>'
			+ '</tr>'
			+ '<tr>'
			+ '<td height="30">'
			+ '<span class="ared">*</span> 出发城市：'
			+ ' <input type="text" name="startcode1" id="from_id_'
			+ journey
			+ '"'
			+ ' class="startcode queryInput" data="'
			+ journey
			+ '"/>'
			+ '</td>'
			+ '<div id="from_suggest_'
			+ journey
			+ '" class="width180 cityDiv"></div>'
			+ '<td height="30"> '
			+ '<span class="ared">*</span> 到达城市：'
			+ ' <input type="text" name="arrivalcode1" id="to_id_'
			+ journey
			+ '" class="arrivalcode queryInput" data="'
			+ journey
			+ '"/>'
			+ '</td>'
			+ '<div id="to_suggest_'
			+ journey
			+ '" class="width180 cityDiv"></div>'
			+ '</tr>'
			+ '<tr>'
			+ '<td height="30">'
			+ '<span class="ared">*</span> 出发日期：'
			+ ' <input type="text" name="startdate" onfocus="WdatePicker()" value="" class="Wdate queryInput" id="startdate_'
			+ journey + '" />' + '</td>' + '<td height="30">'
			+ '&nbsp;&nbsp;&nbsp;航空公司：'
			+ ' <select class="queryInput"  name="aircompany"  id="carrier_id_'
			+ journey + '">' + '</select>' + '</td></tr>' + '</table>'
			+ '<input type="hidden" name="aircompany" value="CA">'
			+ '<input type="hidden" name="startcode" id="from_id_code'
			+ journey + '">'
			+ '<input type="hidden" name="arrivalcode" id="to_id_code'
			+ journey + '">' + '</div>';
	$(jForm).appendTo("#morejourney");
	eventAC('#from_id_' + journey, '#from_id_code' + journey,
			'#from_suggest_' + journey);
	eventAC('#to_id_' + journey, '#to_id_code' + journey,
			'#to_suggest_' + journey);
	createCarrierOption('#carrier_id_' + journey);
	journey++;
}

function deletejourney(journeyNo) {
	$("#morejourney_id" + (journeyNo)).remove();
	$(".journeyNo").each(function(no) {
		$(this).text(no + 1);
		journey = no + 2;

	})
}

/**
 * 
 * @param {}
 *            index
 * @param {}
 *            first
 * @param {}
 *            second
 * @return {}
 */
function getError_uw(index, first, second) {
	var error_uw_ZH = [];
	var error_uw_EN = [];

	var course_ZH = new Array("一", "二", "三");
	var course_EN = new Array("first", "secend", "third");

	if (language == "en") {
		course_ZH = course_EN;
	}
	course1 = course_ZH[first == null ? "" : first];
	course2 = course_ZH[second == null ? "" : second];

	error_uw_ZH[0] = new Array("请选择第" + course1 + "段行程的出发城市");
	error_uw_ZH[1] = new Array("请选择第" + course1 + "段行程的到达城市");
	error_uw_ZH[2] = new Array("第" + course1 + "段行程的出发/到达城市不能相同，请重新选择");
	error_uw_ZH[3] = new Array("请选择第" + course1 + "段行程的出发日期");
	error_uw_ZH[4] = new Array("对不起，出发日期不能早于当前日期，请修改后，重新查询！");
	error_uw_ZH[5] = new Array("第" + course2 + "段行程的出发日期不能小于第" + course1
			+ "段行程的出发日期，请重新选择");

	error_uw_EN[0] = new Array("Please select the " + course1
			+ " paragraph of the trip departure city");
	error_uw_EN[1] = new Array("Please select the arrival of the " + course1
			+ " leg Cities");
	error_uw_EN[2] = new Array(
			"The "
					+ course1
					+ " paragraph of the trip departure / arrival cities can not be the same, please re-select");
	error_uw_EN[3] = new Array("Please select the " + course1
			+ " paragraph of the trip departure date");
	error_uw_EN[4] = new Array(
			"The starting date of your choice may be inconsistent with common sense, choose the next date today, thank cooperation!");
	error_uw_EN[5] = new Array("The starting date of the" + course2
			+ " leg of the trip can not be less than the " + course1
			+ " paragraph of the departure date, please re-select");

	if (language == "en") {
		error_uw_ZH = error_uw_EN;
	}

	return error_uw_ZH[index];
}

function checkedLianCheng(id, value, i, txt) {
	var GG = new Array("一", "二", "三");
	if ($.trim(value) == '中文/拼音/三字码' || $.trim(value) == '') {
		alert("#" + id + i);
		$("#" + id + i).focus();
		alert("请选择第" + GG[i] + txt);
		return false;
	}
	return true;
}

jQuery.cookie = function(name, value, options) {
	if (typeof value != 'undefined') {
		options = options || {};
		if (value === null) {
			value = '';
			options = $.extend( {}, options);
			options.expires = -1;
		}
		var expires = '';
		if (options.expires
				&& (typeof options.expires == 'number' || options.expires.toUTCString)) {
			var date;
			if (typeof options.expires == 'number') {
				date = new Date();
				date.setTime(date.getTime()
						+ (options.expires * 24 * 60 * 60 * 1000));
			} else {
				date = options.expires;
			}
			expires = '; expires=' + date.toUTCString();
		}
		var path = options.path ? '; path=' + (options.path) : '';
		var domain = options.domain ? '; domain=' + (options.domain) : '';
		var secure = options.secure ? '; secure' : '';
		document.cookie = [ name, '=', encodeURIComponent(value), expires,
				path, domain, secure ].join('');
	} else {
		var cookieValue = null;
		if (document.cookie && document.cookie != '') {
			var cookies = document.cookie.split(';');
			for ( var i = 0; i < cookies.length; i++) {
				var cookie = jQuery.trim(cookies[i]);
				if (cookie.substring(0, name.length + 1) == (name + '=')) {
					cookieValue = decodeURIComponent(cookie
							.substring(name.length + 1));
					break;
				}
			}
		}
		return cookieValue;
	}
};

Date.prototype.format = function(format) {
	var o = {
		"M+" : this.getMonth() + 1, // month
		"d+" : this.getDate(), // day
		"h+" : this.getHours(), // hour
		"m+" : this.getMinutes(), // minute
		"s+" : this.getSeconds(), // second
		"q+" : Math.floor((this.getMonth() + 3) / 3), // quarter
		"S" : this.getMilliseconds()
	// millisecond
	}
	if (/(y+)/.test(format))
		format = format.replace(RegExp.$1, (this.getFullYear() + "")
				.substr(4 - RegExp.$1.length));
	for ( var k in o)
		if (new RegExp("(" + k + ")").test(format))
			format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k]
					: ("00" + o[k]).substr(("" + o[k]).length));
	return format;
}

