/// /// /// //#region 登录页面 $(document).bind(EVT_ONLOGINPAGE, function () { //登录页面,自动填充用户名和密码 msg.on("fillUserInfo", function () { if (this.name) $("input[name='loginUser.user_name']").val(this.name); if (this.pwd) { $("input[name='user.password']").val(this.pwd); document.getElementById("randCode").focus(); } else { $("input[name='user.password']")[0].focus(); } }); chrome.runtime.sendMessage({ action: "getLastUser" }, function (m) { if (m.name) $("input[name='loginUser.user_name']").val(m.name); if (m.pwd) { $("input[name='user.password']").val(m.pwd); $("#randCode")[0].focus(); } else { $("input[name='user.password']")[0].focus(); } }); $("#randCode").keyup(function () { if (sysConfig.autoLoginAfterVerifyCode && this.value.length >= 4) { $("#subLink")[0].click(); } }); $(window).on("unload", function () { var data = { tempUser: $("input[name='loginUser.user_name']").val(), tempPwd: $("input[name='user.password']").val() }; if (!data.tempUser || !data.tempPwd) return; chrome.runtime.sendMessage({ action: "logTempUser", detail: data }); }); }); //#endregion //#region 刷票页面 function getCurrentStationInfo() { if (!document.getElementById("fromStationText")) return null; return { fromText: $("#fromStationText").val(), fromCode: $("#fromStation").val(), toText: $("#toStationText").val(), toCode: $("#toStation").val(), depDate: $("#startdatepicker").val() }; } $(document).bind(EVT_ONQUERYPAGE, function () { var lastValid = null; var processProfile = function () { currentProfile.selectedTrain = _.map(currentProfile.selectedTrain, function (e, k) { return tagMap[e] || e; }); }; var applyProfile = function () { processProfile(); if (currentProfile.fromText) $("#fromStationText").val(currentProfile.fromText); if (currentProfile.fromCode) $("#fromStation").val(currentProfile.fromCode); if (currentProfile.toText) $("#toStationText").val(currentProfile.toText); if (currentProfile.toCode) $("#toStation").val(currentProfile.toCode); if (new Date() < new Date(currentProfile.depDate)) $("#startdatepicker").val(currentProfile.depDate); }; //注册响应消息 msg.on("getStationInfo", function (response) { response({ detail: getCurrentStationInfo() }); }); //当配置发生变化时发送消息通知。 $doc.on("change", "#fromStationText, #fromStation, #toStationText, #toStation, #startdatepicker", function () { chrome.runtime.sendMessage({ action: "stationInfoUpdate", detail: getCurrentStationInfo() }); }); $doc.on("click", "#submitQuery, #submitQuery_stu", function () { chrome.runtime.sendMessage({ action: "stationInfoUpdate", detail: getCurrentStationInfo() }); }); //回填状态 chrome.runtime.sendMessage({ action: "getCurrentProfile" }, function (message) { currentProfile = message.detail; applyProfile(); }); msg.on("profileChanged", function () { log.print("queryprofile updated."); currentProfile = this; processProfile(); applyProfile(); $(document).trigger("profileChanged"); }); msg.on("startQuery", function (r) { if (this.date) { $("#startdatepicker").val(this.date); } currentProfile.byAuto = this.byAuto; if (!this.byAuto) chrome.runtime.sendMessage({ action: "stationInfoUpdate", detail: getCurrentStationInfo() }); var e = new CustomEvent("requestQueryTicket", { detail: { config: { isStudent: currentProfile.studentTicket } } }); document.dispatchEvent(e); r({ canquery: lastValid }); }); //连接点,嵌入加载事件 unsafeInvoke(function () { if (window.removeLoadMsg) { var old = window.removeLoadMsg; window.removeLoadMsg = function () { old.apply(this, arguments); document.dispatchEvent(new CustomEvent("query" + "Complete")); }; } else if (window.mygrid.parse) { var op = window.mygrid.parse; window.mygrid.parse = function () { op.apply(this, arguments); document.dispatchEvent(new CustomEvent("query" + "Complete")); }; } document.addEventListener("request" + "Query" + "Ticket", function (e) { window.clickBuyStudentTicket = e.detail.config.isStudent ? "Y" : "N"; var valid = canquery(); document.dispatchEvent(new CustomEvent("canquery", { detail: valid })); if (!valid) { return; } var opt = e.detail.config; sendQueryFunc.call(opt.isStudent ? document.getElementById("stu_submitQuery") : document.getElementById("submitQuery")); }); $("body").ajaxError(function (e, r, s) { if (s.url.indexOf("queryLeftTicket") === -1) return; document.dispatchEvent(new CustomEvent("qe")); }); }); document.addEventListener("canquery", function (e) { lastValid = e.detail; }); document.addEventListener("queryComplete", function () { log.print("queryticket completed."); $(document).trigger("preprocessQueryResult").trigger("processQueryResult").trigger("processedQueryResult"); }); }); $(document).bind(EVT_ONQUERYPAGE, function () { $(document).on("preprocessQueryResult", function () { log.print("show real tickets."); //显示实际票数 var trs = $("#gridbox table table tr:gt(0)"); trs.each(function () { var tr = $(this); var tds = tr.find("td"); var submitBtn = tr.find(".btn130_2"); if (!submitBtn.length) return; var ticketInfo = getTicketInfo(submitBtn.attr("onclick")); tr.data("ticketdata", ticketInfo); if (sysConfig.showRealSeatCount) { tds.each(function (i, d) { if (!seatOrder[i]) return; var td = $(this); var txt = $.trim(td.text()); if (txt == '有' && ticketInfo[seatOrder[i]] > 0) { if (ticketInfo["_" + seatOrder[i]] && sysConfig.showTicketPrice) { td.html("" + ticketInfo[seatOrder[i]] + "
" + (sysConfig.appendPriceUnit ? "¥" : "") + (ticketInfo["_" + seatOrder[i]] / 10) + ""); } else { td.text(ticketInfo[seatOrder[i]]).css({ fontWeight: "bold", color: "#008800" }); } } else { if (ticketInfo["_" + seatOrder[i]] && sysConfig.showTicketPrice) { td.html("" + txt + "
" + (sysConfig.appendPriceUnit ? "¥" : "") + (ticketInfo["_" + seatOrder[i]] / 10) + ""); } else { td.text(txt).css({ fontWeight: "bold", color: "#008800" }); } } }); } }); }); }); $(document).bind(EVT_ONQUERYPAGE, function () { var result; $(document).on("processQueryResult", function () { //过滤车次,并按规则查找车次 var trs = $("#gridbox table.obj tr:gt(0)"); result = { raw: null, rawTrainMap: {}, trainMap: {}, auto: null, nextTime: null, rowInfo: {} }; trs.each(function () { var row = $(this); var item = { row: this, $row: row }; var train = {}; //车次信息 var ts = row.find("td:eq(0) span.base_txtdiv"); var m = /onStopHover\(['"](.*?)#(.*?)#(.*?)['"]\)/i.exec(ts.attr("onmouseover")); train.code = $.trim(ts.text()); train.from = { code: m[2] || "" }; train.to = { code: m[3] || "" }; train.id = m[1] || ""; //记录 //发站信息? var temp = $.trim(row.find("td:eq(1)").text()).split(/\s+/); train.from.endpoint = row.find("td:eq(1) img").length; train.from.name = temp[0]; train.from.time = temp[1]; temp = $.trim(row.find("td:eq(2)").text()).split(/\s+/); train.to.endpoint = row.find("td:eq(1) img").length; train.to.name = temp[0]; train.to.time = temp[1]; train.elapsedTime = { total: $.trim(row.find("td:eq(3)").text()) }; //ticket info var offset = 4; train.tickets = {}; train.price = {}; row.find("td:gt(3):lt(11)").each(function (i, e) { var code = seatOrder[offset + i]; var td = $(this); var span = td.find("span"); var txt, ptxt; if (span.length) { txt = span.text(); ptxt = $.trim(td.find("small").text()); } else { txt = $.trim(td.text()); ptxt = ""; } train.tickets[code] = txt.indexOf("有") != -1 ? 9999 : txt == '*' ? -1 : txt == '--' ? -2 : txt == '无' ? 0 : parseInt(txt); if (ptxt) train.price[code] = parseInt(ptxt.replace(/\./g, ""), 10); }); if (row.data("ticketdata")) { var tdkp = _.pairs(row.data("ticketdata")); train.price = $.extend(train.price, _.object(_.filter(tdkp, function (p) { return p[0][0] === '_'; }))); train.tickets = $.extend(train.tickets, _.object(_.filter(tdkp, function (p) { return p[0][0] !== '_'; }))); } //sell info. //先判断是不是可以订票 if (row.find(".btn130_2").length) { train.available = 1; //回填票价 } else { var btntxt = $.trim(row.find("td:eq(15) a").text()); var selltimem = /(0*(\d+)月0*(\d+)日)?(\d+)\s*点起售/i.exec(btntxt); if (selltimem === null) train.available = 0; else { train.available = -1; train.selltime = new Date(); train.selltime.setHours(parseInt(selltimem[4])); train.selltime.setMinutes(0); train.selltime.setSeconds(0); if (selltimem[1]) { //带日期 train.selltime.setMonth(parseInt(selltimem[2]) - 1); train.selltime.setDate(parseInt(selltimem[3])); if (train.selltime.getMonth() < new Date().getMonth()) { train.selltime.setFullYear(train.selltime.getFullYear() + 1); } } } } result.trainMap[train.id] = train; result.rowInfo[train.id] = item; }); result.original = _.values(result.trainMap); result.available = result.original; result.trainCodes = _.pluck(result.original, "code"); result.filtered = []; result.include = result.available; //过滤什么的 $(document).trigger("filterTrains", result); //处理车次 $(document).trigger("processTrains", result); }); (function () { $(document).bind("performAutoSubmit", function (e, ex) { result.rowInfo[result.auto.data.id].$row.find("a")[0].click(); }); })(); }); //#endregion //#region 提交页面 $(document).bind(EVT_ONSUBMITPAGE, function () { var stat = null; var enableSubmitOrder = false; var selected = false; unsafeInvoke(function up() { $.fn.query_passenger = (function (o) { return function () { o.apply(this, $.makeArray(arguments)); document.dispatchEvent(new CustomEvent("query_passenger")); return this; }; })($.fn.query_passenger); document.addEventListener("addp", function () { if (!selected) return; $("a.add_ticket_passenger").click(); selected = true; }); document.addEventListener("sf", function () { $("div.tj_btn button:last")[0].click(); }); $(document).ajaxComplete(function (e, xhr, s) { var x = new CustomEvent("ajax", { detail: { url: s.url, status: xhr.status, resp: xhr.responseText, data: s.data, type: s.type } }); document.dispatchEvent(x); }); }); var selectPassenger = function () { if (!stat) return; log.print(stat); if (!$("#showPassengerFilter :checkbox").length) { //还没有添加成功 document.addEventListener("query_passenger", function () { selectPassenger(); }); } else { //选择 var pas = stat.auto.passengers; $.each(pas, function () { var ck = $("#" + this.name + this.idtype + this.id + " :checkbox"); if (!ck.length) { //手动加的 document.dispatchEvent(new CustomEvent("addp")); var tr = $("table.table_qr tr:visible:not(:last):last"); tr.find("td:eq(3) select").val(this.type); tr.find("td:eq(4) input").val(this.name); tr.find("td:eq(5) select").val(this.idtype); tr.find("td:eq(6) input").val(this.id); tr.find("td:last :checkbox").prop("checked", this.save); } else { ck.click(); } }); //选择席别 $("select[name$=_seat]").val(stat.auto.seat === '0' ? "1" : stat.auto.seat); if (pas && pas.length) document.getElementById("rand").focus(); } }; //自动提交? msg.on("enableSubmitOrder", function () { enableSubmitOrder = true; $("#rand").keyup(); }); $("#rand").keyup(function () { if (!enableSubmitOrder) return; if (sysConfig.autoSubmitAfterVerifyCode && this.value.length >= 4) { document.dispatchEvent(new CustomEvent("sf")); } }); document.addEventListener("ajax", function (e) { var i = e.detail; if (i.url.indexOf("method=getQueueCount") === -1 || sysConfig.dynamicAutoConfirmOrderDelay < 0) return; setTimeout(function () { var btns = parent.$("#queue_note").closest(".ui-dialog").find("button"); for (var j = 0; j < btns.length; j++) { if ($.trim(btns.eq(j).text()).replace(/\s/g, "") === "确定") { btns[j].click(); } } }, sysConfig.dynamicAutoConfirmOrderDelay); }); //报告车次参数 (function () { var data = { date: $("#start_date").val(), from: $("#from_station_telecode").val(), to: $("#to_station_telecode").val(), td: $("#train_no").val(), tcode: $("#station_train_code").val(), code: "" }; chrome.runtime.sendMessage({ action: "reportSubmitInfo", detail: data }); })(); chrome.runtime.sendMessage({ action: "getLastAutoData" }, function (m) { stat = m; selectPassenger(); }); }); //#endregion //#region 主页面 $(document).bind(EVT_ONMAINPAGE, function () { //自动转向 var hash = location.hash; if (hash) { setTimeout(function () { document.getElementById("main").src = hash.substr(1); }, 1000); } (function () { var timer = null; $doc.on("sysConfigUpdated", function () { //保持在线 if (!sysConfig.keepOnline) { if (timer) { clearInterval(timer); timer = null; } return; } else { log.print("init keep-online timer."); timer = setInterval(function () { $.get("/otsweb/"); }, 10 * 60 * 1000); } }).trigger("sysConfigUpdated"); })(); }); //#endregion //#region 路由函数 $(document).bind("routePage", function () { var path = location.pathname.slice(8); var search = location.search.slice(1); var onValidPage = false; var dispatchEvent = function (evt) { onValidPage = true; chrome.runtime.sendMessage({ action: "pageInitCall", detail: { page: evt } }); $(document).trigger(evt); }; if (((path == "loginAction.do" && location.search != 'method=initForMy12306') || path == "login.jsp")) { if ($("#loginForm").length) dispatchEvent(EVT_ONLOGINPAGE); else if ($("div.left_m").length) { //登录成功 var name = $.trim($("div.left_m").text()); chrome.runtime.sendMessage({ action: "logTempUserSuccess", detail: { name: name } }); } } if (path == 'order/querySingleAction.do') { if (search == "method=init" && document.getElementById("submitQuery")) { dispatchEvent(EVT_ONQUERYPAGE); } else if (search == "method=submutOrderRequest") { //点击预定后的页面,按理说这里是不应该出现的,出现的原因基本上是因为服务器太忙导致出错的。 } } if (path == '' || path == 'main.jsp') { dispatchEvent(EVT_ONMAINPAGE); } if (path == 'passengerAction.do') { if (search == 'method=initUsualPassenger12306') { dispatchEvent(EVT_ONPASSENGERPAGE); } } if (path == "order/confirmPassengerAction.do" || path == "order/confirmPassengerResignAction.do") { //订单页 if (search == 'method=init') { //提交订单 dispatchEvent(EVT_ONSUBMITPAGE); } } if (path == "order/orderAction.do") { if (location.search.indexOf("method=cancelMyOrderNotComplete") != -1 && document.getElementById("submitQuery")) { dispatchEvent(EVT_ONQUERYPAGE); } } if (path == "order/payConfirmOnlineSingleAction.do") { if (location.search.indexOf("method=cancelOrder") != -1 && document.getElementById("submitQuery")) { dispatchEvent(EVT_ONQUERYPAGE); } } if (path == "order/myOrderAction.do") { if (search.indexOf("method=resign") != -1 && document.getElementById("submitQuery")) { dispatchEvent(EVT_ONQUERYPAGE); } } //没有操作? if (!onValidPage) { chrome.runtime.sendMessage({ action: "onUnvalidPage" }); } }); //#endregion