//刷票页面 $(function () { var $doc = $(document); var initialized = false; var currentUser = null; //UI初始化 $("#seatTypeList label").each(function (i, e) { e.dataset["index"] = i; }); //联系人搜索 $("#addp_search_key") .searchDelay() .bind("search.fish.searchdelay", function (e, key) { if (!key) { $("#contactList button").show(); $("#addp_search_clear").prop("disabled", true); } else { $("#contactList button").hide().filter("[data-key*=" + key + "], [data-fl*=" + key.toUpperCase() + "]").show(); $("#addp_search_clear").prop("disabled", !key); } }); $("#addp_search_clear").click(function () { $("#addp_search_key").val("").searchDelay("search"); }); //日期选择 (function () { var dateLoopContainer = $("#dateLoopBox"); var date = new Date().trimToDay(); var html = []; for (var j = 0; j < 25; j++) { var nd = date.addDays(j); html.push(""); } dateLoopContainer.html(html.join("")); $doc.on("click", "#dateLoopContainer button", function () { //点击删除 var btn = $(this); var dt = this.dataset.fulldate; currentUser.currentProfile.dateloop = _.without(currentUser.currentProfile.dateloop, dt, null); currentUser.save(); btn.remove(); $("#dateLoop .modal-body button[data-fulldate='" + dt + "']").prop("disabled", false); $("#dateLoopBtn").prop("disabled", false); message.sendToTab({ action: "removeDateLoop", detail: dt }); }); $doc.on("click", "#dateLoopBox button", function () { var btn = $(this); currentUser.currentProfile.dateloop.push(this.dataset.fulldate); $("#dateLoopContainer").append(btn.clone().removeClass("btn-primary").addClass("btn-default")); this.disabled = true; currentUser.save(); $("#dateLoopBtn").prop("disabled", currentUser.currentProfile.dateloop.length >= 5); if (currentUser.currentProfile.dateloop.length >= 5) { $("#dateLoop").modal("hide"); } message.sendToTab({ action: "addDateLoop", detail: this.dataset.fulldate }); }); message.addAction("addDateLoop", function () { $("#dateLoop .modal-body button[data-fulldate='" + this + "']:enabled").click(); }); message.addAction("removeDateLoop", function () { $("#dateLoopContainer button[data-fulldate='" + this + "']").click(); }); })(); var applyProfile = function (p) { if (!p) return; //处理席别 var seatContainer = $("#seatTypeList"); var bakst = p.selectedSeatType; seatContainer.find(":checkbox:checked").each(function () { this.checked = false; $(this).change(); }); $.each(bakst, function () { seatContainer.find(":checkbox[value=" + this + "]:not(:checked)").prop("checked", true).change(); }); p.selectedSeatType = bakst; $("#trains").val(p.selectedTrain.join(',')).change(); trains.importTags(p.selectedTrain.join(',')); //联系人 $("#passengers").html($.map(currentUser.currentProfile.passengers, function (e) { return e.toHtml(true); }).join("")); $("#btnAddPassengerD, #btnAddPassengerM").prop("disabled", currentUser.currentProfile.passengers.length >= 5); //日期轮查 (function () { var dateloop = $("#dateLoopContainer"); var cd = new Date().trimToDay(); dateloop.empty(); $("#dateLoop button").prop("disabled", false); var loopFiltered = []; $.each(currentUser.currentProfile.dateloop, function () { var dd = new Date(this + ''); if (dd >= cd) { dateloop.append(""); loopFiltered.push(this + ''); } currentUser.currentProfile.dateloop = loopFiltered; $("#dateLoop button[data-fulldate='" + this + "']").prop("disabled", true); }); $("#dateLoopBtn").prop("disabled", currentUser.currentProfile.dateloop.length >= 5); })(); //各种选项 $("input[data-profile-key], select[data-profile-key]").each(function () { var ele = this; var $ele = $(this); var type = ele.type; var key = ele.dataset.profileKey; var profile = currentUser.currentProfile; var propertyvalue = profile[key]; if (typeof propertyvalue == 'boolean') { if (type == "radio") { $("input[name=" + ele.name + "][value=" + (propertyvalue ? 1 : 0) + "]")[0].checked = true; } else if (type == "checkbox") { ele.checked = propertyvalue; } else { $ele.val(propertyvalue ? "1" : "0"); } } else { $ele.val(propertyvalue); } }); message.sendToTab({ action: "profileChanged", detail: JSON.parse(JSON.stringify(p)) }); }; var applyPassengers = function () { if (!currentUser) return; $("#contactList").empty(); if (!currentUser.passengers || !currentUser.passengers.length) { $("#addp_refresh").bsButton("loading"); currentUser.reloadPassengers(); return; } var list = $.map(currentUser.passengers, function (e) { return e.toHtml(); }); $("#contactList").html(list.join("")).find(); $("#addp_refresh").bsButton("reset"); $("#addPassenger").trigger("show.bs.modal"); }; //席别 $("input:checkbox[name=seat]").change(function () { if (!currentUser) return; var $cb = $(this); var $parent = $cb.parent(); var $container = $parent.parent(); if (this.checked) { //已选中? $parent.addClass("highlight"); //将其移动到队列末端 var $p = $parent.prevAll().find(":checkbox:checked").parent().last(); $p.length ? $p.after($parent) : $container.prepend($parent); if (currentUser && initialized) currentUser.currentProfile.selectedSeatType.push(this.value); if (initialized) message.sendActionToTab("addSeat", this.value); } else { //取消选择,则放回原来的位置 var index = $parent[0].dataset.index; var notChecked = $parent.nextAll().find(":checkbox:not(:checked)").parent(); $parent.removeClass("highlight"); if (!notChecked.length) $container.append($parent); else { if (index > notChecked.last()[0].dataset.index) { notChecked.last().after($parent); } else if (index < notChecked.first()[0].dataset.index) { notChecked.first().before($parent); } else { for (var j = 1; j < notChecked.length; j++) { if (notChecked[j - 1].dataset.index < index && notChecked[j].dataset.index > index) { notChecked.eq(j - 1).after($parent); break; } } } } if (currentUser && initialized) currentUser.currentProfile.selectedSeatType = _.without(currentUser.currentProfile.selectedSeatType, this.value); if (initialized) message.sendActionToTab("removeSeat", this.value); } if (currentUser && initialized) currentUser.save(); }); $doc.on("click", ".seatCheckLink", function () { var codes = this.dataset.target; $("input:checkbox[name=seat]:checked").each(function () { this.checked = false; $(this).change(); }); for (var j = 0; j < codes.length; j++) { $("input:checkbox[name=seat][value=" + codes[j] + "]").prop("checked", true).change(); } message.sendActionToTab("seatReset", currentUser.currentProfile.selectedSeatType); }); message.addAction("addSeat", function () { $("input:checkbox[name=seat][value=" + this + "]:not(:checked)").prop("checked", true).change(); }); message.addAction("removeSeat", function () { $("input:checkbox[name=seat][value=" + this + "]:checked").prop("checked", false).change(); }); //车次 var trains = $("#trains").tagsInput({ height: "20px", defaultText: "输入车次", removeWithBackspace: true, spacer: ",. |\n", width: "100%", onChange: function () { if (!currentUser || !initialized) return; currentUser.currentProfile.selectedTrain = _.filter($("#trains").val().split(','), function (e) { return e; }); currentUser.save(); }, onAddTag: function (id) { if (!initialized) return; message.sendActionToTab("addTrain", id); }, onRemoveTag: function (id) { if (!initialized) return; message.sendActionToTab("removeTrain", id); }, autosize: false, onBeforeAdd: function (v) { return v ? v.toUpperCase() : ""; } }); $("#addtrain_ok").click(function () { var val = $.trim($("#addtrain_code").val()); if (!val) return; //自动转换成正则表达式 val = val.replace(/[\s,,.。-]/g, "|").replace(/[\^\$]/g, "").toUpperCase(); if (trains.tagExist(val)) return; try { new RegExp("^" + val + "$"); } catch (e) { alert("表达式不正确..."); return; } trains.addTag(val); $("#addTrain").modal("hide"); }); $doc.on("click", ".cmd-addtrain", function () { if (!trains.tagExist(this.dataset.code)) trains.addTag(this.dataset.code); }); message.addAction("addTrain", function () { var code = this + ''; if (!trains.tagExist(code)) trains.addTag(code); }); message.addAction("removeTrain", function () { var code = this + ''; if (trains.tagExist(code)) trains.removeTag(code); }); //联系人 (function () { $doc.on("show.bs.modal", "#addPassenger", function () { var container = $("#addPassenger"); var buttons = container.find("[data-key]"); buttons.prop("disabled", false); buttons.find("i").remove(); $.each(currentUser.currentProfile.passengers, function () { buttons.filter("[data-key='" + this.key + "']").prop("disabled", true).prepend(''); }); }); var addPassenger = function (p) { if (_.findWhere(currentUser.currentProfile.passengers, { key: p.key })) return; currentUser.currentProfile.passengers.push(p); $("#passengers").append(p.toHtml(true)); $("#btnAddPassengerD, #btnAddPassengerM").prop("disabled", currentUser.currentProfile.passengers.length >= 5); currentUser.save(); message.sendActionToTab("addPassenger", p); }; var removePassenger = function (p) { if (!_.findWhere(currentUser.currentProfile.passengers, { key: p.key })) return; currentUser.currentProfile.passengers = _.without(currentUser.currentProfile.passengers, p); $("#btnAddPassengerD, #btnAddPassengerM").prop("disabled", false); currentUser.save(); message.sendActionToTab("removePassenger", p); }; $doc.on("click", "#addPassenger button[data-key]", function () { if (currentUser.currentProfile.passengers.length >= 5) { alert("亲,联系人最多只能选择五个哦。"); $("#addPassenger").modal("hide"); return; } this.disabled = true; $(this).prepend(''); var key = this.dataset.key; var p = _.findWhere(currentUser.passengers, { key: key }); addPassenger(p); if (currentUser.currentProfile.passengers.length >= 5) { $("#addPassenger").modal("hide"); } }); $doc.on("click", "#passengers button[data-key]", function () { var key = this.dataset.key; var $btn = $(this); $btn.remove(); removePassenger(_.findWhere(currentUser.currentProfile.passengers, { key: key })); }); $("#addmp_ok").click(function () { if (currentUser.currentProfile.passengers.length >= 5) { alert("亲,联系人最多只能选择五个哦。"); $("#enterPassenger").modal("hide"); return; } var idtype = $("#addmp_idtype").val(); var id = $("#addmp_id").val(); var name = $("#addmp_name").val(); var type = $("#addmp_tickettype").val(); if (!name || !id) { alert("咦,名字或证件号没写...."); return; } var p = _.findWhere(currentUser.currentProfile.passengers, { name: name, idtype: idtype, id: id }); if (p) { alert("这位客官,同名同证件号的乘客已经添加过了哦。。"); return; } var pm = new Passenger(name, type, passengerTypeCode[type], idtype, idTypeCode[idtype], id, ""); pm.save = false; addPassenger(pm); $("#enterPassenger").modal("hide"); }); message.addAction("addPassenger", function () { //查找联系人 var p = _.findWhere(currentUser.passengers, { name: this.name, typename: this.typename, id: this.id }); if (p) addPassenger(p); }); message.addAction("removePassenger", function () { //查找联系人 var p = _.findWhere(currentUser.passengers, { name: this.name, typename: this.typename, id: this.id }); if (p) { $("#passengers button[data-key='" + p.key + "']").click(); } }); })(); //时间选择初始化 var ranges = $("#timerangeContainer select"); for (var i = 0; i < 24; i++) { var number = (i < 10 ? "0" : "") + i; ranges.each(function () { this.options[i] = new Option(number + ":" + (this.dataset.isend ? "59" : "00"), i); }); } //各种杂项以及通过 data-profile-key 进行绑定的元素 (function () { $doc.on("change", "[data-profile-key]", function () { if (!currentUser) return; var ele = this; var $ele = $(this); var type = ele.type; var key = ele.dataset.profileKey; var profile = currentUser.currentProfile; var propertyvalue = profile[key]; if (typeof propertyvalue == 'boolean') { if (type == "radio") { profile[key] = $("input[name=" + ele.name + "]:checked")[0].value == "1"; } else if (type == "checkbox") { profile[key] = ele.checked; } else { profile[key] = $ele.val() == "1"; } } else if (typeof propertyvalue == 'number') { profile[key] = parseInt($ele.val() + ''); } else { profile[key] = $.trim($ele.val()); } profile.save(); if (initialized) { message.sendActionToTab("miscChanged", { key: key, value: profile[key] }); } }); $doc.on("change", "[data-sysconfigkey]", function () { if (!sysConfig) return; var ele = this; var $ele = $(this); var type = ele.type; var key = ele.dataset.sysconfigkey; var profile = {}; if (type == "radio") { profile[key] = $("input[name=" + ele.name + "]:checked")[0].value == "1"; } else if (type == "checkbox") { profile[key] = ele.checked; } else { profile[key] = $.trim($ele.val()); } message.sendAction("setUserConfig", profile); }); message.addAction("miscChanged", function () { var obj = $("[data-profile-key='" + this.key + "']"); var dom; if (!obj.length) return; var type = obj.attr("type"); if (typeof this.value === 'boolean') { if (type === "radio") { dom = $("input[name=" + obj[0].name + "][value=" + (this.value ? 1 : 0) + "]")[0]; if (dom.checked === this.value) return; dom.checked = this.value; } else if (type === "checkbox") { if (obj[0].checked === this.value) return; obj[0].checked = this.value; } else { if (obj.val() == this.value) return; obj.val(this.value ? "1" : "0"); } } else { if (obj.val() == this.value) return; obj.val(this.value); } obj.change(); }); })(); //出行计划保存 $("#cmdSaveTravelMethod").click(function () { message.sendToTab({ action: "getStationInfo" }, function (response) { var info = response.detail; if (!info || !info.fromCode || !info.toCode) { alert("您还木有选择出发地目标地和出发时间呢。。。"); return; } $.extend(currentUser.currentProfile, info); var name = prompt("请输入新的出行计划的名称(如果名称已经存在,则会被覆盖):", info.fromText + "--" + info.toText); if (!name) return; //移除老的 $("#historyList button").each(function () { if ($(this).text() == name) { var buttonGroup = $(this).closest(".btn-group"); currentUser.savedProfile.remove(buttonGroup.data("travel")); buttonGroup.removeData("travel"); buttonGroup.remove(); return false; } }); var pro = new Profile(currentUser.currentProfile); pro.name = name; currentUser.savedProfile.add(pro); var html = $('
'); html.data("travel", pro); $("#historyList").append(html); notification.create({ iconUrl: LARGEICON, message: "出行计划已保存~", title: "订票助手" }); }); }); $doc.on("click", "button[data-cmd=deleteTravelWay]", function () { var buttonGroup = $(this).closest(".btn-group"); var name = buttonGroup.find("button:first").text(); if (!confirm("确定要删除出行计划【" + name + "】吗?")) return; currentUser.savedProfile.remove(buttonGroup.data("travel")); buttonGroup.removeData("travel"); buttonGroup.remove(); }); $doc.on("click", "#historyList button.btn-info", function () { var btn = $(this); var name = $.trim(btn.text()); var profile = _.findWhere(currentUser.savedProfile.list, { name: name }); currentUser.resetCurrentProfile(profile); applyProfile(currentUser.currentProfile); message.sendActionToTab("profileReload", profile); $("#travelHistory").modal("hide"); }); //重置请求 $("#btnResetProfile").click(function () { if (!currentUser) return; currentUser.currentProfile.reset(); applyProfile(currentUser.currentProfile); currentUser.save(); }); //刷新联系人 $("#addp_refresh").click(function () { if (!currentUser || this.disabled) return; currentUser.passengers = []; applyPassengers(); }); if (currentUser) { applyProfile(currentUser.currentProfile); applyPassengers(); } //还原状态 var applyUser = function (user) { initialized = false; if (!user) return; currentUser = user; applyProfile(user.currentProfile); applyPassengers(); //出行计划 var travelContainer = $("#historyList"); travelContainer.empty(); $.each(currentUser.savedProfile.list, function () { var t = this; var html = $('
'); html.data("travel", this); travelContainer.append(html); }); //绑定事件 currentUser.on("passengerLoaded", function () { applyPassengers(); }); currentUser.on("userSaved", function () { message.sendToTab({ action: "profileChanged", detail: JSON.parse(JSON.stringify(currentUser.currentProfile)) }); }); initialized = true; }; //处理消息 (function () { message.addAction("stationInfoUpdate", function () { if (currentUser) { $.extend(currentUser.currentProfile, this); currentUser.save(); } }); message.addAction("getCurrentProfile", function (response) { if (!currentUser) return; response({ detail: JSON.parse(JSON.stringify(currentUser.currentProfile)) }); }); message.addAction("getCurrentUser", function (response) { if (!currentUser) return; response({ detail: JSON.parse(JSON.stringify(currentUser)) }); }); message.addAction("passengerUpdated", function () { currentUser.reloadPassengers(this); }); message.addAction("userOptionChanged", function () { currentUser.options = $.extend(currentUser.options, this); currentUser.save(); }); message.addAction("setResignMode", function() { var p = this; if (p.profile) { currentUser.currentProfile = $.extend(currentUser.currentProfile, p.profile); //禁用学生票的选择 $("input:checkbox[name=optStudent]").prop("disabled", true); } else { $("input:checkbox[name=optStudent]").prop("disabled", false); } }); })(); (function () { //刷新统计 var counters = $("#queryStat"); var refreshCount = 0; var statData = null; var lastCity = null; var enableBus = new Date() < new Date("2014-01-25 00:00:00"); var enableSfc = new Date() < new Date("2014-02-15 00:00:00"); var manuallyHide = false; var checkIsBus = function (fromText, toText) { if (!enableBus || manuallyHide) return false; if (fromText.indexOf("北京") === -1) return false; var target = ["呼和浩特", "太原", "菏泽", "大连", "合肥", "南京", "武汉"]; var valid = _.some(target, function (e) { return toText.indexOf(e) !== -1; }); return valid; }; var checkSfc = function(formText, toText) { if (!enableSfc || manuallyHide) return false; return true; }; message.addAction("queryStatisticsReport", function () { statData = this; var stat = this.stat; var profile = currentUser.currentProfile; if (lastCity !== profile.fromCode + profile.toCode) { refreshCount = 0; lastCity = profile.fromCode + profile.toCode; } refreshCount++; counters.css("visibility", "visible"); counters.find("span:eq(0)").html("第 " + refreshCount + " 次查票"); if (this.failed) { counters.find("span:eq(1)").html("查询失败"); counters.find("span:eq(2)").html("查询失败"); } else { counters.find("span:eq(1)").html("" + stat.original.length + " 趟车"); counters.find("span:eq(2)").html(stat.filtered.length + " 趟车过滤"); } if ($("#btnRefresh.btn-success, #btnRefresh.btn-info").length) { chrome.extension.sendMessage({ ticketEvent: 'refresh', times: refreshCount }); } //$("#bus").hide(); //if (refreshCount >= 30) { // var a = $("#bus"); // if (checkIsBus(profile.fromText, profile.toText)) { // //可以橙色大巴 // a.find("span").html("免费橙色大巴送您顺利回家"); // a.find("a:eq(0)").attr("href", "http://www.ijinshan.com/bus/"); // a.show(); // } else if (checkSfc(profile.fromText, profile.toText)) { // //显示顺风车 // a.find("span").html("免费顺风车助您顺利回家"); // a.find("a:eq(0)").attr("href", "http://www.shunfengche.org/NewYearAction.aspx"); // a.show(); // } //} }); $("#bus a:last").click(function() { manuallyHide = true; $(this).parent().hide(); }); $(document).on("show.bs.modal", "#queryResult", function () { var div = $("#queryResult .modal-body"); var html = []; var showGroup = function (reason, title) { var list = _.where(statData.stat.filtered, { reason: reason }); if (!list.length) return; html.push("" + title + ":" + _.map(list, function (e) { return e.code; }).join("; ")); }; showGroup(1, " 因无票被过滤"); showGroup(2, "因发站不同过滤"); showGroup(3, "因到站不同过滤"); showGroup(4, "时间不对被过滤"); showGroup(5, "非预定车次过滤"); if (!html.length) { html.push("没有车次被过滤"); } div.html(html.join("
")); }); })(); //刷票 (function () { var btn = $("#btnRefresh"); var btnIcon = btn.find("i"); var btnText = btn.find("span"); var timer = null; var nextTime; var stat; localStorage.removeItem("lastStatics"); message.addAction("pageInitCall", function () { if (!btn.hasClass("btn-primary")) { btn.click(); } }); var formatNumber = function (n) { n = (n / 10) + ''; return n.indexOf(".") == -1 ? n + ".0" : n; }; var countDown = function () { nextTime--; if (nextTime <= 0) { doQuery(); } else { $("#stopTimer").text(formatNumber(nextTime) + "秒后重查"); } }; var isInQuery = false; //var messageTimeoutTimer = null; //var doQueryTimeout = function () { // if (btn.hasClass("btn-success")) // btn.click(); // clearTimeout(messageTimeoutTimer); // messageTimeoutTimer = null; //}; var doQuery = function () { isInQuery = true; resetTimer(); var queryDate, byAuto = btn.hasClass("btn-success"); if (byAuto && currentUser.currentProfile.dateloop && currentUser.currentProfile.dateloop.length) { //如果是自动查询的,那就看看是否需要轮换日期 var currentDateLoop = $("#dateLoopContainer button.btn-primary"); if (!currentDateLoop.length) { //没有轮查 currentDateLoop = $("#dateLoopContainer button:first"); queryDate = currentDateLoop[0].dataset.fulldate; currentDateLoop.addClass("btn-primary"); } else { var nextLoop = currentDateLoop.next(); currentDateLoop.removeClass("btn-primary"); if (!nextLoop.length) { //最后一个了,那就木有了。改查第一天 queryDate = currentUser.currentProfile.depDate; } else { queryDate = nextLoop[0].dataset.fulldate; nextLoop.addClass("btn-primary"); } } } else { //获得当前信息 message.sendToTab({ action: "getStationInfo" }, function (response) { var info = response.detail; $.extend(currentUser.currentProfile, info); btn.removeClass("btn-primary").addClass("btn-success"); queryDate = currentUser.currentProfile.depDate; }); } btnText.text("正在查询"); btnIcon.removeClass().addClass("glyphicon glyphicon-flash"); $("#stopTimer").hide(); message.sendToTab({ action: "startQuery", detail: { date: queryDate, byAuto: byAuto } }, function (resp) { if (!resp.canquery) btn.click(); if (resp.sysAuto) { btnText.text("系统刷新中"); btn.removeClass("btn-success").addClass("btn-info"); btnIcon.removeClass().addClass("glyphicon glyphicon-dashboard"); } }); //messageTimeoutTimer = setTimeout(doQueryTimeout, 2000); }; var reset = function () { resetTimer(); btn.removeClass("btn-success btn-info").addClass("btn-primary"); $("#dateLoopContainer button").removeClass("btn-primary"); btnText.text("开始刷票"); $("#stopTimer").hide(); btnIcon.removeClass().addClass("glyphicon glyphicon-refresh"); message.sendToTab({ action: "profileChanged", detail: JSON.parse(JSON.stringify(currentUser.currentProfile)) }); }; var resetTimer = function () { if (timer !== null) { clearInterval(timer); timer = null; } }; btn.click(function () { $(".btnMute").click(); if (btn.hasClass("btn-success")) { reset(); } else if (btn.hasClass("btn-info")) { reset(); message.sendActionToTab("stopQuery"); } else { var profile = currentUser.currentProfile; message.sendAction("track", { type: 95, values: [ profile.fromCode, profile.fromText, profile.toCode, profile.toText, profile.depDate ] }); doQuery(); } }); if (!btn.hasClass("btn-primary")) btn.click(); message.addAction("autoSubmitOrder", function() { message.sendAction("track", { type: 96 }); }); message.addAction("queryStatisticsReport", function () { if (!isInQuery && (this.failed !== true)) return; //clearTimeout(messageTimeoutTimer); isInQuery = false; stat = this; localStorage['lastStatics'] = JSON.stringify(this); if (stat.auto) { //找到了! btn.click(); $(document).trigger("ticketAvailable", stat.auto); return; } //倒计时5秒 if (stat.nextTime > 0 && (!btn.hasClass("btn-info") || stat.failed)) { nextTime = Math.round(stat.nextTime * 10); $("#stopTimer").text(formatNumber(nextTime) + "秒后重查"); $("#stopTimer").show(); btnText.text("停止查询"); btn.removeClass().addClass("btn btn-success"); btnIcon.removeClass().addClass("glyphicon glyphicon-time"); if (timer) clearInterval(timer); timer = setInterval(countDown, 100); } }); message.addAction("checkAutoRefreshEnabled", function (response) { response({ enabled: btn.hasClass("btn-success") }); }); message.addAction("getLastAutoData", function (response) { if (stat) response(stat); else { var json = localStorage["lastStatics"]; if (json) response(JSON.parse(json)); else { response(null); } } }); message.addAction("queryStop", function () { $.extend(currentUser.currentProfile, this); reset(); }); })(); $doc.on("currentUserChange", function (e, u) { if (!u) { if (currentUser && currentUser.username === sessionStorage["12306_sessionuser"]) return; if (sessionStorage["12306_sessionuser"]) { u = new LoginUser(sessionStorage["12306_sessionuser"]); } else return; } applyUser(u); }); }); $(function promptUser() { var audio = new Audio("http://static.liebao.cn/resources/audio/music2.ogg"); $(document).on("ticketAvailable", function (e, auto) { if (sysConfig.enableSoundPrompt) { $(".btnMute").show(); audio.loop = true; audio.play(); } if (sysConfig.enablePopupPrompt) { notification.create({ iconUrl: "/icons/icon_128.png", title: "订票助手", message: "主公,查到车次:" + auto.train + " " + (seatTypeFull[auto.seat]) + ",快灰来订票啊!" }); } message.sendAction("attention", { tabid: message.tab.id, windowid: message.tab.windowId }); }); $(".btnMute").click(function () { audio.pause(); $(".btnMute").hide(); }); }); //提交页面 $(function () { //倒计时 (function () { var current = 0; var span = null; var timer = null; message.addAction("pageInitCall", function () { if (timer) { clearInterval(timer); timer = null; } if (this.page != 'onSubmitPage') return; current = (ISOTN ? sysConfig.otnAutoSubmitOrderDelay : sysConfig.dynamicAutoSubmitOrderDelay) / 100; span = $("#countDown").removeClass("label-success").addClass("label-warning").html("请等待 " + (current / 100) + " 秒再提交订单").find("em"); if (current > 0) { timer = setInterval(function () { current -= 1; if (current > 0) { var str = (current / 10) + ""; span.html(str + (str.length < 2 ? ".0" : "")); } else { span.parent().removeClass("label-warning").addClass("label-success").html("可以提交订单了哦"); clearInterval(timer); timer = null; message.sendToTab({ action: "enableSubmitOrder" }); } }, 100); } else { span.parent().removeClass("label-warning").addClass("label-success").html("可以提交订单了哦"); message.sendToTab({ action: "enableSubmitOrder" }); } }); })(); //实时余票 (function () { var timer = null; var stat = null; message.addAction("reportSubmitInfo", function () { resetTimer(); stat = this; message.sendAction("track", { type: 96, values: [ stat.from, stat.to, stat.date, stat.td, stat.tcode, stat.code || "" ] }); startRtp(); }); message.addAction("sysConfigUpdate", function () { if ($(".rtp:visible").length) startRtp(); }); message.addAction("pageInitCall", function () { resetTimer(); }); var resetTimer = function () { if (timer) { clearInterval(timer); timer = null; } }; var startRtp = function () { resetTimer(); if (!sysConfig.enableRealTimeTicketQuery) { $(".rtp").find("span").remove().append("实时余票查询已被自动关闭"); return; } if (!stat) return; timer = setInterval(queryTicket, 10000); queryTicket(); }; var queryTicket = function () { otsweb.queryTicket(stat.from, stat.to, stat.date, stat.td, stat.code, function (data) { if (!data) { $(".rtp").find("span").remove().end().append('警告:车次已无票'); } else { var html = []; $.each(data, function (i, d) { if (i[0] == "_" || d === -2 || !seatType[i]) return; //没有席别 html.push(""); html.push(seatType[i]); html.push(" "); if (d == -1) { html.push("未售"); } else if (d == 9999) { html.push("大量"); } else if (d > 0) { html.push(d + "张"); } else { html.push("无"); } html.push(" "); }); $(".rtp").find("span").remove().end().append(html.join("")); } }); }; })(); }); //登录页面 $(function () { var tempUser = null; if (localStorage["tempuser"]) tempUser = JSON.parse(localStorage["tempuser"]); message.addAction("logTempUser", function () { tempUser = this; localStorage["tempuser"] = JSON.stringify(this); }); message.addAction("logTempUserSuccess", function () { if (!tempUser) return; message.sendAction("track", { type: 93 }); var name = this.name; var user = new LoginUser(tempUser.tempUser); sessionStorage["12306_sessionuser"] = tempUser.tempUser; user.dispname = name; user.save(); //记录到列表 USERS.add(tempUser.tempUser, name, sysConfig.rememberLoginPwd ? tempUser.tempPwd : ""); //记录最后用户 localStorage.setItem("12306_lastUser", JSON.stringify({ name: tempUser.tempUser, pwd: sysConfig.rememberLoginPwd ? tempUser.tempPwd : "" })); sessionStorage.setItem("12306_sessionuser", tempUser.tempUser); //刷新列表 refreshList(); $(document).trigger("currentUserChange", user); }); message.addAction("getLastUser", function (r) { if (localStorage["12306_lastUser"]) { var info = JSON.parse(localStorage["12306_lastUser"]); r({ name: info.name, pwd: info.pwd }); } }); var refreshList = function () { $("#userSelect option").remove(); var dom = document.getElementById("userSelect"); if (_.size(USERS.list) > 0) { dom.options[dom.options.length] = new Option('请选择', ''); $.each(USERS.list, function (e) { dom.options[dom.options.length] = new Option(this.dispname, e); }); } else { dom.options[dom.options.length] = new Option('还没有记录...', ''); } }; refreshList(); $("#userSelect").change(function () { var value = $(this).val(); if (!value) return; var item = USERS.find(value); if (!item) return; message.sendToTab({ action: "fillUserInfo", detail: { name: value, pwd: item.password } }); }); $("#deleteUser").click(function () { var user = $("#userSelect").val(); if (!user) return; var u = USERS.find(user); if (confirm("确定要删除已经记录的用户【" + u.dispname + "】吗?所有的相关设置(如出行计划等)都将会被删除。")) { USERS.remove(user); refreshList(); } }); //日期 (function () { var from = new Date().trimToDay(); var today = from.addDays(19); $("#presellTip").html(from.format("MM月dd日") + " ~ " + today.format("MM月dd日")); })(); }); //页面切换 (function () { var switchPage = function (page) { //所有页面 var pages = $(".containerWraper > div"); var currentPage = pages.filter(".current"); var toPage = pages.filter("#" + page); if (currentPage.attr("id") == page || !toPage.length) return; currentPage.addClass("slideOut").removeClass("current"); toPage.removeClass("slideOut").addClass("current"); if (toPage[0].dataset.hidelogo) { $("#mainWrapper").addClass("nologo"); } else { $("#mainWrapper").removeClass("nologo"); } }; message.addAction("pageInitCall", function () { var page = this.page; if (page == "onMainPage") return; message.sendAction("track", { type: 94, values: [page] }); if (this.username) { sessionStorage["12306_sessionuser"] = this.username; } $(".special").hide(); if (page === "onLoginPage") { $(".btnMute").click(); $(".loginPageOnly, .preSellTip").show(); if (localStorage["12306_lastUser"]) { $("#userSelect").val(JSON.parse(localStorage["12306_lastUser"]).name); } switchPage("loginPage"); return; } if (ISOTN && !this.logined) { //未登录,无法使用 $(".btnMute").click(); $(".notLoginTip").show(); switchPage("loginPage"); return; } if (page === "onQueryPage") { if (!localStorage["query_usageTip"]) { localStorage["query_usageTip"] = "1"; notification.create({ iconUrl: "/icons/icon_128.png", title: "欢迎使用~", message: "订票助手增强并扩展了系统的刷票功能。不出意外的话,您可以完全用不到系统的更多选项区域了,助手会帮你直接设置好的,只需要在最上方的助手工具区设置即可。" }); } $(".btnMute").click(); $("#queryStat").css("visibility", "hidden"); $(document).trigger("currentUserChange"); switchPage("queryPage"); } else if (page === "onSubmitPage") { $(document).trigger("currentUserChange"); switchPage("loginPage"); $(".submitPageOnly").show(); } else if (page === "onMainPage") { } }); message.addAction("onUnvalidPage", function () { $(".special").hide(); $(".preSellTip").show(); $(".unvalid").show(); switchPage("loginPage"); }); })(); (function () { var servervalidTimer = setTimeout(function () { notification.create({ iconUrl: "/icons/icon_128.png", title: "订票助手好像没有正常启动", message: "看起来好像订票助手没有启动。建议您重新打开浏览器。" }); }, 3000); message.sendAction("servervalid", null, function (resp) { clearTimeout(servervalidTimer); if (resp.valid <= 0) { $("#chkEnableSmartDns").parent().hide(); $("#curServerSpeed").parent().remove(); } else { //显示服务器速度 var refreshSpeed = function () { chrome.runtime.sendMessage({ action: "getCurrentServer" }, function (m) { var data = ISOTN ? m["kyfw.12306.cn"] : m["dynamic.12306.cn"]; var speed = data.speed; var cls = speed === 0 ? "label-default" : speed < 0 ? "label-danger" : speed < 100 ? "label-success" : speed < 400 ? "label-warning" : "label-danger"; $("#curServerSpeed").removeClass().addClass("label label-normal " + cls).html(speed > 0 ? speed + " 毫秒" + (data.rate ? " (加速" + data.rate + "%)" : "") : speed < 0 ? "无法连接" : "正在帮你测速..."); }); }; refreshSpeed(); setInterval(refreshSpeed, 3000); } }); var refreshSysConfig = function () { $("#chkEnableSmartDns")[0].checked = sysConfig.enableServerAutoChange; //$("#chkEnableAutoCaptcha")[0].checked = sysConfig.enableAutoCaptcha; if (sysConfig.enableServerAutoChange) { $("#curServerSpeed").parent().show(); } else { $("#curServerSpeed").parent().hide(); } $("input[data-sysconfigkey], select[data-sysconfigkey]").each(function () { var ele = this; var $ele = $(this); var type = ele.type; var key = ele.dataset.sysconfigkey; var profile = sysConfig; var propertyvalue = profile[key]; if (typeof propertyvalue == 'boolean') { if (type == "radio") { $("input[name=" + ele.name + "][value=" + (propertyvalue ? 1 : 0) + "]")[0].checked = true; } else if (type == "checkbox") { ele.checked = propertyvalue; } else { $ele.val(propertyvalue ? "1" : "0"); } } else { $ele.val(propertyvalue); } }); }; $(document).on("sysConfigUpdated", function () { refreshSysConfig(); //message.sendAction("getBaseSysConfig", null, function (response) { // if (response.detail.enableAutoCaptcha && ISOTN) { // $("#chkEnableAutoCaptcha").parent().show(); // } else { // $("#chkEnableAutoCaptcha").parent().hide(); // } //}); }); if (sysConfig) refreshSysConfig(); $("#chkEnableSmartDns").change(function () { message.sendAction("setUserConfig", { enableServerAutoChange: this.checked }); if (this.checked) { $("#curServerSpeed").parent().show(); } else { $("#curServerSpeed").parent().hide(); } }); //$("#chkEnableAutoCaptcha").change(function () { // message.sendAction("setUserConfig", { enableAutoCaptcha: this.checked }); //}); })(); $(function () { //更新信息 var info, updateTipIsShown = false; var checkUpdateInfo = function () { if (!info.hasUpdate) $("#updateAvailable").hide(); else { log.print("nv-" + info.version); var a = $("#updateAvailable").show().find("a"); a.attr("title", "最新版:" + info.version); if (info.url) a.attr("href", info.url); if (!updateTipIsShown) { updateTipIsShown = true; notification.create({ title: "很高兴地告诉你有新版咯", message: "订票助手新版本发布:" + info.version + ",建议立刻收到碗里去哦。切记多手准备不要全靠哪个渠道买票哦。难道你忘记了大明湖畔的电话订票了吗~~", buttons: [ { title: "点击这里立刻更新", iconUrl: "/infobar/theme/plus_16.png", onClick: function () { chrome.tabs.create({ url: info.url }); } } ] }); } } $("#systemNotification").html(info.notify || "暂无通知"); }; message.sendAction("getUpdateInfo", null, function (data) { info = data; checkUpdateInfo(); }); message.addAction("updateInfoRefreshed", function () { info = this; checkUpdateInfo(); }); message.sendAction("triggerUpdate"); message.addAction("isAlive", function (r) { r(true); }); }); //infobar模式兼容 if (NONINFOBARMODE) { $("body").addClass("iframemode"); var url = "https://kyfw.12306.cn/otn/leftTicket/init"; document.write('
'); }; $(function () { message.addAction("isReady", function (r) { r({ ready: true }); }); //var vt = $("div.compatibleIntro").show(); //if (ISOTN) { // vt.find("a").html("老版
12306").attr("href", NONINFOBARMODE ? chrome.extension.getURL("/infobar/main.html") : "http://dynamic.12306.cn/otsweb/"); //} else { // vt.find("a").html("新版
12306").attr("href", NONINFOBARMODE ? chrome.extension.getURL("/infobar/main.html?new") : "http://kyfw.12306.cn/otn/"); //} message.sendAction("track", { type: 98 }); });