// ==UserScript== // @name ChatGPT学习通作业考试助手 // @version 3.3.3 // @description 本脚本【采用ChatGPT,Claude,Gemini等世界顶尖AI生成答案】 【🥇操作简单】ChatGPT学习通助手,安装即可使用;推荐使用作业、考试自动答题【✨版本特性】版本特性:无题库,全采用AI回复答案,原作者:Ne-21 // @match *://*.chaoxing.com/* // @match *://*.xuexitong.com/* // @match *://*.edu.cn/* // @match *://*.org.cn/* // @match *://*.ac.cn/* // @match *://*.xueyinonline.com/* // @match *://*.sslibrary.com/* // @match *://*.neauce.com/* // @match *://*.nbdlib.cn/* // @match *://*.hnsyu.net/* // @match *://*.qutjxjy.cn/* // @match *://*.ynny.cn/* // @match *://*.hnvist.cn/* // @match *://*.fjlecb.cn/* // @match *://*.gdhkmooc.com/* // @match *://*.cugbonline.cn/* // @match *://*.zjelib.cn/* // @match *://*.cqrspx.cn/* // @match *://*.zhihui-yun.com/* // @match *://*.cqie.cn/* // @match *://*.ccqmxx.com/* // @match *://*.jxgmxy.com/* // @match *://*.jnzyjsxy.cn/* // @connect 911285.xyz // @connect gptjs.808860.xyz // @connect 127.0.0.1 // @run-at document-end // @grant unsafeWindow // @grant GM_xmlhttpRequest // @grant GM_setValue // @grant GM_getValue // @grant GM_deleteValue // @grant GM_addValueChangeListener // @grant GM_info // @icon data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDEiIGhlaWdodD0iNDEiIHZpZXdCb3g9IjAgMCA0MSA0MSIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiBzdHJva2Utd2lkdGg9IjEuNSIgY2xhc3M9ImgtNiB3LTYiIHJvbGU9ImltZyI+PHRpdGxlPkNoYXRHUFQ8L3RpdGxlPjx0ZXh0IHg9Ii05OTk5IiB5PSItOTk5OSI+Q2hhdEdQVDwvdGV4dD48cGF0aCBkPSJNMzcuNTMyNCAxNi44NzA3QzM3Ljk4MDggMTUuNTI0MSAzOC4xMzYzIDE0LjA5NzQgMzcuOTg4NiAxMi42ODU5QzM3Ljg0MDkgMTEuMjc0NCAzNy4zOTM0IDkuOTEwNzYgMzYuNjc2IDguNjg2MjJDMzUuNjEyNiA2LjgzNDA0IDMzLjk4ODIgNS4zNjc2IDMyLjAzNzMgNC40OTg1QzMwLjA4NjQgMy42Mjk0MSAyNy45MDk4IDMuNDAyNTkgMjUuODIxNSAzLjg1MDc4QzI0Ljg3OTYgMi43ODkzIDIzLjcyMTkgMS45NDEyNSAyMi40MjU3IDEuMzYzNDFDMjEuMTI5NSAwLjc4NTU3NSAxOS43MjQ5IDAuNDkxMjY5IDE4LjMwNTggMC41MDAxOTdDMTYuMTcwOCAwLjQ5NTA0NCAxNC4wODkzIDEuMTY4MDMgMTIuMzYxNCAyLjQyMjE0QzEwLjYzMzUgMy42NzYyNCA5LjM0ODUzIDUuNDQ2NjYgOC42OTE3IDcuNDc4MTVDNy4zMDA4NSA3Ljc2Mjg2IDUuOTg2ODYgOC4zNDE0IDQuODM3NyA5LjE3NTA1QzMuNjg4NTQgMTAuMDA4NyAyLjczMDczIDExLjA3ODIgMi4wMjgzOSAxMi4zMTJDMC45NTY0NjQgMTQuMTU5MSAwLjQ5ODkwNSAxNi4yOTg4IDAuNzIxNjk4IDE4LjQyMjhDMC45NDQ0OTIgMjAuNTQ2NyAxLjgzNjEyIDIyLjU0NDkgMy4yNjggMjQuMTI5M0MyLjgxOTY2IDI1LjQ3NTkgMi42NjQxMyAyNi45MDI2IDIuODExODIgMjguMzE0MUMyLjk1OTUxIDI5LjcyNTYgMy40MDcwMSAzMS4wODkyIDQuMTI0MzcgMzIuMzEzOEM1LjE4NzkxIDM0LjE2NTkgNi44MTIzIDM1LjYzMjIgOC43NjMyMSAzNi41MDEzQzEwLjcxNDEgMzcuMzcwNCAxMi44OTA3IDM3LjU5NzMgMTQuOTc4OSAzNy4xNDkyQzE1LjkyMDggMzguMjEwNyAxNy4wNzg2IDM5LjA1ODcgMTguMzc0NyAzOS42MzY2QzE5LjY3MDkgNDAuMjE0NCAyMS4wNzU1IDQwLjUwODcgMjIuNDk0NiA0MC40OTk4QzI0LjYzMDcgNDAuNTA1NCAyNi43MTMzIDM5LjgzMjEgMjguNDQxOCAzOC41NzcyQzMwLjE3MDQgMzcuMzIyMyAzMS40NTU2IDM1LjU1MDYgMzIuMTExOSAzMy41MTc5QzMzLjUwMjcgMzMuMjMzMiAzNC44MTY3IDMyLjY1NDcgMzUuOTY1OSAzMS44MjFDMzcuMTE1IDMwLjk4NzQgMzguMDcyOCAyOS45MTc4IDM4Ljc3NTIgMjguNjg0QzM5Ljg0NTggMjYuODM3MSA0MC4zMDIzIDI0LjY5NzkgNDAuMDc4OSAyMi41NzQ4QzM5Ljg1NTYgMjAuNDUxNyAzOC45NjM5IDE4LjQ1NDQgMzcuNTMyNCAxNi44NzA3Wk0yMi40OTc4IDM3Ljg4NDlDMjAuNzQ0MyAzNy44ODc0IDE5LjA0NTkgMzcuMjczMyAxNy42OTk0IDM2LjE1MDFDMTcuNzYwMSAzNi4xMTcgMTcuODY2NiAzNi4wNTg2IDE3LjkzNiAzNi4wMTYxTDI1LjkwMDQgMzEuNDE1NkMyNi4xMDAzIDMxLjMwMTkgMjYuMjY2MyAzMS4xMzcgMjYuMzgxMyAzMC45Mzc4QzI2LjQ5NjQgMzAuNzM4NiAyNi41NTYzIDMwLjUxMjQgMjYuNTU0OSAzMC4yODI1VjE5LjA1NDJMMjkuOTIxMyAyMC45OThDMjkuOTM4OSAyMS4wMDY4IDI5Ljk1NDEgMjEuMDE5OCAyOS45NjU2IDIxLjAzNTlDMjkuOTc3IDIxLjA1MiAyOS45ODQyIDIxLjA3MDcgMjkuOTg2NyAyMS4wOTAyVjMwLjM4ODlDMjkuOTg0MiAzMi4zNzUgMjkuMTk0NiAzNC4yNzkxIDI3Ljc5MDkgMzUuNjg0MUMyNi4zODcyIDM3LjA4OTIgMjQuNDgzOCAzNy44ODA2IDIyLjQ5NzggMzcuODg0OVpNNi4zOTIyNyAzMS4wMDY0QzUuNTEzOTcgMjkuNDg4OCA1LjE5NzQyIDI3LjcxMDcgNS40OTgwNCAyNS45ODMyQzUuNTU3MTggMjYuMDE4NyA1LjY2MDQ4IDI2LjA4MTggNS43MzQ2MSAyNi4xMjQ0TDEzLjY5OSAzMC43MjQ4QzEzLjg5NzUgMzAuODQwOCAxNC4xMjMzIDMwLjkwMiAxNC4zNTMyIDMwLjkwMkMxNC41ODMgMzAuOTAyIDE0LjgwODggMzAuODQwOCAxNS4wMDczIDMwLjcyNDhMMjQuNzMxIDI1LjExMDNWMjguOTk3OUMyNC43MzIxIDI5LjAxNzcgMjQuNzI4MyAyOS4wMzc2IDI0LjcxOTkgMjkuMDU1NkMyNC43MTE1IDI5LjA3MzYgMjQuNjk4OCAyOS4wODkzIDI0LjY4MjkgMjkuMTAxMkwxNi42MzE3IDMzLjc0OTdDMTQuOTA5NiAzNC43NDE2IDEyLjg2NDMgMzUuMDA5NyAxMC45NDQ3IDM0LjQ5NTRDOS4wMjUwNiAzMy45ODExIDcuMzg3ODUgMzIuNzI2MyA2LjM5MjI3IDMxLjAwNjRaTTQuMjk3MDcgMTMuNjE5NEM1LjE3MTU2IDEyLjA5OTggNi41NTI3OSAxMC45MzY0IDguMTk4ODUgMTAuMzMyN0M4LjE5ODg1IDEwLjQwMTMgOC4xOTQ5MSAxMC41MjI4IDguMTk0OTEgMTAuNjA3MVYxOS44MDhDOC4xOTM1MSAyMC4wMzc4IDguMjUzMzQgMjAuMjYzOCA4LjM2ODIzIDIwLjQ2MjlDOC40ODMxMiAyMC42NjE5IDguNjQ4OTMgMjAuODI2NyA4Ljg0ODYzIDIwLjk0MDRMMTguNTcyMyAyNi41NTQyTDE1LjIwNiAyOC40OTc5QzE1LjE4OTQgMjguNTA4OSAxNS4xNzAzIDI4LjUxNTUgMTUuMTUwNSAyOC41MTczQzE1LjEzMDcgMjguNTE5MSAxNS4xMTA3IDI4LjUxNiAxNS4wOTI0IDI4LjUwODJMNy4wNDA0NiAyMy44NTU3QzUuMzIxMzUgMjIuODYwMSA0LjA2NzE2IDIxLjIyMzUgMy41NTI4OSAxOS4zMDQ2QzMuMDM4NjIgMTcuMzg1OCAzLjMwNjI0IDE1LjM0MTMgNC4yOTcwNyAxMy42MTk0Wk0zMS45NTUgMjAuMDU1NkwyMi4yMzEyIDE0LjQ0MTFMMjUuNTk3NiAxMi40OTgxQzI1LjYxNDIgMTIuNDg3MiAyNS42MzMzIDEyLjQ4MDUgMjUuNjUzMSAxMi40Nzg3QzI1LjY3MjkgMTIuNDc2OSAyNS42OTI4IDEyLjQ4MDEgMjUuNzExMSAxMi40ODc5TDMzLjc2MzEgMTcuMTM2NEMzNC45OTY3IDE3Ljg0OSAzNi4wMDE3IDE4Ljg5ODIgMzYuNjYwNiAyMC4xNjEzQzM3LjMxOTQgMjEuNDI0NCAzNy42MDQ3IDIyLjg0OSAzNy40ODMyIDI0LjI2ODRDMzcuMzYxNyAyNS42ODc4IDM2LjgzODIgMjcuMDQzMiAzNS45NzQzIDI4LjE3NTlDMzUuMTEwMyAyOS4zMDg2IDMzLjk0MTUgMzAuMTcxNyAzMi42MDQ3IDMwLjY2NDFDMzIuNjA0NyAzMC41OTQ3IDMyLjYwNDcgMzAuNDczMyAzMi42MDQ3IDMwLjM4ODlWMjEuMTg4QzMyLjYwNjYgMjAuOTU4NiAzMi41NDc0IDIwLjczMjggMzIuNDMzMiAyMC41MzM4QzMyLjMxOSAyMC4zMzQ4IDMyLjE1NCAyMC4xNjk4IDMxLjk1NSAyMC4wNTU2Wk0zNS4zMDU1IDE1LjAxMjhDMzUuMjQ2NCAxNC45NzY1IDM1LjE0MzEgMTQuOTE0MiAzNS4wNjkgMTQuODcxN0wyNy4xMDQ1IDEwLjI3MTJDMjYuOTA2IDEwLjE1NTQgMjYuNjgwMyAxMC4wOTQzIDI2LjQ1MDQgMTAuMDk0M0MyNi4yMjA2IDEwLjA5NDMgMjUuOTk0OCAxMC4xNTU0IDI1Ljc5NjMgMTAuMjcxMkwxNi4wNzI2IDE1Ljg4NThWMTEuOTk4MkMxNi4wNzE1IDExLjk3ODMgMTYuMDc1MyAxMS45NTg1IDE2LjA4MzcgMTEuOTQwNUMxNi4wOTIxIDExLjkyMjUgMTYuMTA0OCAxMS45MDY4IDE2LjEyMDcgMTEuODk0OUwyNC4xNzE5IDcuMjUwMjVDMjUuNDA1MyA2LjUzOTAzIDI2LjgxNTggNi4xOTM3NiAyOC4yMzgzIDYuMjU0ODJDMjkuNjYwOCA2LjMxNTg5IDMxLjAzNjQgNi43ODA3NyAzMi4yMDQ0IDcuNTk1MDhDMzMuMzcyMyA4LjQwOTM5IDM0LjI4NDIgOS41Mzk0NSAzNC44MzM0IDEwLjg1MzFDMzUuMzgyNiAxMi4xNjY3IDM1LjU0NjQgMTMuNjA5NSAzNS4zMDU1IDE1LjAxMjhaTTE0LjI0MjQgMjEuOTQxOUwxMC44NzUyIDE5Ljk5ODFDMTAuODU3NiAxOS45ODkzIDEwLjg0MjMgMTkuOTc2MyAxMC44MzA5IDE5Ljk2MDJDMTAuODE5NSAxOS45NDQxIDEwLjgxMjIgMTkuOTI1NCAxMC44MDk4IDE5LjkwNThWMTAuNjA3MUMxMC44MTA3IDkuMTgyOTUgMTEuMjE3MyA3Ljc4ODQ4IDExLjk4MTkgNi41ODY5NkMxMi43NDY2IDUuMzg1NDQgMTMuODM3NyA0LjQyNjU5IDE1LjEyNzUgMy44MjI2NEMxNi40MTczIDMuMjE4NjkgMTcuODUyNCAyLjk5NDY0IDE5LjI2NDkgMy4xNzY3QzIwLjY3NzUgMy4zNTg3NiAyMi4wMDg5IDMuOTM5NDEgMjMuMTAzNCA0Ljg1MDY3QzIzLjA0MjcgNC44ODM3OSAyMi45MzcgNC45NDIxNSAyMi44NjY4IDQuOTg0NzNMMTQuOTAyNCA5LjU4NTE3QzE0LjcwMjUgOS42OTg3OCAxNC41MzY2IDkuODYzNTYgMTQuNDIxNSAxMC4wNjI2QzE0LjMwNjUgMTAuMjYxNiAxNC4yNDY2IDEwLjQ4NzcgMTQuMjQ3OSAxMC43MTc1TDE0LjI0MjQgMjEuOTQxOVpNMTYuMDcxIDE3Ljk5OTFMMjAuNDAxOCAxNS40OTc4TDI0LjczMjUgMTcuOTk3NVYyMi45OTg1TDIwLjQwMTggMjUuNDk4M0wxNi4wNzEgMjIuOTk4NVYxNy45OTkxWiIgZmlsbD0iY3VycmVudENvbG9yIj48L3BhdGg+PC9zdmc+ // @homepage https://scriptcat.org/script-show-page/1027 // @license 未经授权请勿二开 // ==/UserScript== var setting = { showBox: 1, task: 0, video: 1, audio: 1, rate: 1, review: 0, work: 1, time: 2500, sub: 1, force: 0, decrypt: 1, redo: 0, examTurn: 0, examTurnTime: 0, goodStudent: 0, alterTitle: 1, autoLogin: 0, phone: '', password: '' } var ANSWER_SEPARATOR = '¦'; __initBundledDeps(); var Typr = window.Typr, md5 = window.md5, jQuery = window.jQuery, GptRequestGuard = window.GptRequestGuard; try { var domainMatch = location.hostname.match(/(?:^|\.)(chaoxing\.com|xuexitong\.com)$/); if (domainMatch) document.domain = domainMatch[1]; } catch (e) { console.error('[GPTJs] 无法设置 document.domain', e); } try { Object.defineProperty(unsafeWindow, 'onblur', { get: function () { return function () { }; }, set: function () { } }); document.hasFocus = function () { return true; }; Object.defineProperty(document, 'visibilityState', { get: function () { return 'visible'; }, configurable: true }); Object.defineProperty(document, 'hidden', { get: function () { return false; }, configurable: true }); } catch (e) { console.error('[GPTJs] 无法劫持 window.onblur / document.hasFocus', e); } var localStorage = { _getPrefix: function () { try { var host = window.location.hostname; if (host === 'xuexitong.com' || host.endsWith('.xuexitong.com')) { host = 'chaoxing.com'; } var matches = host.match(/([^.]+\.(?:com|net|org|edu)\.cn|[^.]+\.[^.]+)$/i); return (matches ? matches[0] : host) + ':'; } catch (e) { return ''; } }, getItem: function (key) { var prefixedKey = this._getPrefix() + key; var val = undefined; try { val = GM_getValue(prefixedKey); } catch (e) { } if (val === undefined || val === null) { try { val = window.localStorage.getItem(key); if (val !== null) { GM_setValue(prefixedKey, val); } } catch (e) { } } return (val !== undefined && val !== null) ? val : null; }, setItem: function (key, value) { var prefixedKey = this._getPrefix() + key; try { GM_setValue(prefixedKey, String(value)); } catch (e) { } try { window.localStorage.setItem(key, String(value)); } catch (e) { } }, removeItem: function (key) { var prefixedKey = this._getPrefix() + key; try { GM_deleteValue(prefixedKey); } catch (e) { } try { window.localStorage.removeItem(key); } catch (e) { } } }; var _w = unsafeWindow, _l = location, _d = _w.document, $ = _w.jQuery || (function () { try { if (top.jQuery) return top.jQuery; } catch (_) {} return jQuery; })(), md5 = md5 || window.md5, UE = _w.UE; var HOST_CANDIDATES = [ "https://911285.xyz", "https://gptjs.808860.xyz" ]; var _cachedHost = localStorage.getItem('GPTJsSetting.hostSelected'); var _cachedAt = parseInt(localStorage.getItem('GPTJsSetting.hostSelectedAt') || '0'); var _host = _cachedHost || HOST_CANDIDATES[0]; function requestGuardClientId() { var saved = GM_getValue('GPTJsSetting.guardClientId', ''); if (!/^[a-f0-9]{32}$/.test(saved)) { saved = GptRequestGuard.clientId(); GM_setValue('GPTJsSetting.guardClientId', saved); } return saved; } var _guardClientId = requestGuardClientId(); function guardHttp(host, path, method, data, headers) { return new Promise(function (resolve, reject) { GM_xmlhttpRequest({ method: method, url: host + path, headers: Object.assign({ 'X-Client-Id': _guardClientId }, data ? { 'Content-Type': 'application/json' } : {}, headers || {}), data: data ? JSON.stringify(data) : undefined, timeout: 8000, onload: function (xhr) { var body = {}; try { var parsed = JSON.parse(xhr.responseText); if (parsed && typeof parsed === 'object') body = parsed; } catch (_) { } if (xhr.status >= 200 && xhr.status < 300) { resolve({ data: body, response: xhr.responseText }); } else { var error = new Error(body.message || body.msg || '服务器请求失败,请稍后重试。'); error.response = { status: xhr.status, data: body }; reject(error); } }, onerror: function () { reject(new Error('暂时无法连接服务器,请稍后重试。')); }, ontimeout: function () { reject(new Error('服务器响应超时,请稍后重试。')); } }); }); } function requestAuthRaw(host, headers) { var startAt = Date.now(); var learningAccountId = getLearningAccountId(); return guardHttp(host, '/api/v1/auth?uid=' + encodeURIComponent(learningAccountId || '') + '&v=' + encodeURIComponent(GM_info.script.version), 'GET', null, headers) .then(function (result) { return { host: host, ms: Date.now() - startAt, response: result.response, learningAccountId: learningAccountId }; }); } function requestAuth(host, initialError) { var pendingError = initialError; return GptRequestGuard.withCaptcha(function (headers) { if (pendingError) { var error = pendingError; pendingError = null; return Promise.reject(error); } return requestAuthRaw(host, headers); }, { clientId: _guardClientId, refresh: function (captchaId, headers) { return guardHttp(host, '/api/security/captcha/refresh', 'POST', { captchaId: captchaId }, headers); } }); } function rememberHost(result) { _host = result.host; localStorage.setItem('GPTJsSetting.hostSelected', _host); localStorage.setItem('GPTJsSetting.hostSelectedAt', String(Date.now())); return result; } function findFastest() { return new Promise(function (resolve, reject) { var finished = false; var failures = 0; var limitedHost; var firstError; HOST_CANDIDATES.forEach(function (host) { requestAuthRaw(host, { 'X-Client-Id': _guardClientId }).then(function (result) { if (!finished) { finished = true; resolve(rememberHost(result)); } }).catch(function (error) { firstError = firstError || error; if (error.response && error.response.status === 429 && !limitedHost) limitedHost = { host: host, error: error }; failures++; if (failures === HOST_CANDIDATES.length && !finished) { finished = true; if (limitedHost) requestAuth(limitedHost.host, limitedHost.error).then(function (result) { resolve(rememberHost(result)); }).catch(reject); else reject(firstError); } }); }); }); } function initFastestHost() { var twoHours = 2 * 60 * 60 * 1000; if (_cachedAt && Date.now() - _cachedAt < twoHours) { return requestAuthRaw(_host, { 'X-Client-Id': _guardClientId }).catch(function (error) { if (error.response && error.response.status === 429) return requestAuth(_host, error); return findFastest(); }); } return findFastest(); } var _authPromise = null; function ensureAuth() { if (!_authPromise) { _authPromise = initFastestHost(); _authPromise.catch(function () { }); } return _authPromise; } function getApiHost() { var stored = localStorage.getItem('GPTJsSetting.hostSelected'); return HOST_CANDIDATES.indexOf(stored) !== -1 ? stored : _host; } var _mlist, _defaults, _domList, $subBtn, $saveBtn, $frame_c; var _currentQuestionMeta = null; var _ne21AutoSubmitBlocked = false; function blockAutoSubmit() { _ne21AutoSubmitBlocked = true; } var _ne21NextAiAllowedAt = 0; $('.navshow').find('a:contains(体验新版)')[0] ? $('.navshow').find('a:contains(体验新版)')[0].click() : ''; var _ne21DecryptReady = Promise.resolve(); if (setting.decrypt) { _ne21DecryptReady = decryptFont().catch(function (e) { console.error('[GPTJs] 字体解密失败', e); }); } if (localStorage.getItem('GPTJsSetting.time') !== null) { var _savedTime = parseFloat(localStorage.getItem('GPTJsSetting.time')); if (isFinite(_savedTime) && _savedTime >= 0) { setting.time = _savedTime * 1000; } } function watchSetting(key, handler) { try { if (typeof GM_addValueChangeListener === 'function') { GM_addValueChangeListener(localStorage._getPrefix() + key, function (_name, _oldValue, newValue) { try { handler(newValue === undefined ? null : newValue); } catch (e) { console.error('[GPTJs] 同步设置失败', key, e); } }); } } catch (_) {} } function applyTimeSetting(value) { if (value === null || value === undefined) return; var changedTime = parseFloat(value); if (isFinite(changedTime) && changedTime >= 0) setting.time = changedTime * 1000; } watchSetting('GPTJsSetting.time', applyTimeSetting); window.addEventListener('storage', function (event) { if (event.key === 'GPTJsSetting.time') applyTimeSetting(event.newValue); if (event.key === 'GPTJsSetting.rate') applyLiveRate(); if (event.key === 'GPTJsSetting.isPaused') { try { updatePausedUI(getPanelDocument(), event.newValue === 'true'); } catch (_) {} } }); var _ne21LiveRateAppliers = []; function applyLiveRate() { _ne21LiveRateAppliers.slice().forEach(function (apply) { try { apply(); } catch (e) { console.error('[GPTJs] 应用倍速失败', e); } }); } watchSetting('GPTJsSetting.rate', applyLiveRate); function updateRateWarning(doc, rate) { if (!doc) return; var warning = doc.getElementById('ne21-rate-warning'); if (!warning) return; var n = parseFloat(rate); warning.hidden = !(isFinite(n) && n > 1); } function syncPanelControl(key, value) { var doc; try { doc = getPanelDocument(); } catch (_) { return; } if (value === null || value === undefined) return; if (key === 'GPTJsSetting.model') { var select = doc.getElementById('modelSelect'); if (!select || select.value === value) return; for (var i = 0; i < select.options.length; i++) { if (select.options[i].value === value) { select.value = value; break; } } return; } var control = doc.getElementById(key); if (!control) return; if (control.type === 'checkbox') control.checked = String(value) === 'true'; else if (doc.activeElement !== control) control.value = String(value); if (key === 'GPTJsSetting.rate') updateRateWarning(doc, value); } ['sub', 'force', 'examTurn', 'goodStudent', 'alterTitle', 'redo', 'fuzzyMatch', 'rate', 'time', 'model'].forEach(function (settingId) { watchSetting('GPTJsSetting.' + settingId, function (value) { syncPanelControl('GPTJsSetting.' + settingId, value); }); }); watchSetting('GPTJsSetting.panelShortcut', function () { try { refreshPanelShortcut(getPanelDocument()); } catch (_) {} }); watchSetting('GPTJsSetting.isPaused', function (value) { try { updatePausedUI(getPanelDocument(), String(value) === 'true'); } catch (_) {} }); function updatePausedUI(doc, isPaused) { if (!doc) return; var box = doc.getElementById('ne-21box'); if (box) box.classList.toggle('ne21-paused', !!isPaused); var pauseBtn = doc.getElementById('ne-21pause'); if (pauseBtn) { pauseBtn.innerHTML = isPaused ? '' : ''; pauseBtn.setAttribute('title', isPaused ? '已暂停,点击继续' : '运行中,点击暂停'); pauseBtn.setAttribute('aria-pressed', isPaused ? 'true' : 'false'); } var banner = doc.getElementById('ne-21paused-banner'); if (banner) banner.hidden = !isPaused; } function getPanelShortcut() { try { var shortcut = JSON.parse(localStorage.getItem('GPTJsSetting.panelShortcut')); if (shortcut && /^(F([1-9]|1[0-2])|Key[A-Z]|Digit[0-9])$/.test(shortcut.code) && (/^F\d+$/.test(shortcut.code) || shortcut.ctrlKey || shortcut.altKey || shortcut.metaKey)) { return shortcut; } } catch (_) {} return { code: 'F9' }; } function formatPanelShortcut(shortcut) { return [shortcut.ctrlKey && 'Ctrl', shortcut.altKey && 'Alt', shortcut.shiftKey && 'Shift', shortcut.metaKey && 'Meta', shortcut.code.replace(/^(Key|Digit)/, '')].filter(Boolean).join('+'); } function refreshPanelShortcut(doc) { var label = formatPanelShortcut(getPanelShortcut()); var badge = doc.querySelector('#ne-21box .ne21-kbd'); if (badge) { badge.textContent = label + ' 显隐'; badge.title = '按 ' + label + ' 显示/隐藏面板,可在设置中修改'; } var header = doc.querySelector('#ne-21box .ne21-header'); if (header) header.title = '按住标题栏可拖动 / 按 ' + label + ' 显示或隐藏面板 / 点击右侧按钮收起'; var input = doc.getElementById('GPTJsSetting.panelShortcut'); if (input) input.value = label; } function bindPanelShortcut(doc) { if (doc._ne21ShortcutHandler) return; doc._ne21ShortcutHandler = function (event) { if (event.defaultPrevented || event.isComposing || event.target && event.target.id === 'GPTJsSetting.panelShortcut') return; var shortcut = getPanelShortcut(); if (event.code !== shortcut.code || !!event.ctrlKey !== !!shortcut.ctrlKey || !!event.altKey !== !!shortcut.altKey || !!event.shiftKey !== !!shortcut.shiftKey || !!event.metaKey !== !!shortcut.metaKey) return; if (!/^F\d+$/.test(shortcut.code) && event.target && (event.target.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(event.target.tagName))) return; if (!getPanelDocument().getElementById('ne-21box')) return; event.preventDefault(); event.stopPropagation(); if (!event.repeat) toggleBoxVisibility(); }; doc.addEventListener('keydown', doc._ne21ShortcutHandler, true); } function toggleBoxVisibility() { var $box = $('#ne-21box', getPanelDocument()); if ($box.length === 0) return; if (localStorage.getItem('GPTJsSetting.showBox') === 'hide') { $box.css('display', ''); localStorage.setItem('GPTJsSetting.showBox', 'show'); } else { $box.css('display', 'none'); localStorage.setItem('GPTJsSetting.showBox', 'hide'); } } bindPanelShortcut(document); try { bindPanelShortcut(getPanelDocument()); } catch (_) {} function waitForJQueryElement(selector, timeout) { return new Promise(function (resolve) { var interval = setInterval(function () { if ($(selector).length > 0) { clearInterval(interval); if (timer) clearTimeout(timer); resolve(true); } }, 500); var timer = null; if (timeout && timeout > 0) { timer = setTimeout(function () { clearInterval(interval); resolve(false); }, timeout); } }); } if (window === top) { showBox(); } if (_l.hostname.startsWith('i.mooc.') || _l.hostname.startsWith('i.chaoxing.com') || (_l.hostname === 'i.xuexitong.com' && (_l.pathname === '/' || _l.pathname.startsWith('/space/')))) { if (window === top) { if (_l.pathname.includes('/space/out_link.shtml')) { logger('检测到外链嵌套页面,脚本将在 iframe 内自动运行考试/作业', 'green'); } else { logger('ChatGPT学习通助手已就绪,进入课程视频、作业或考试页面即可自动运行', 'green'); } } } else if (_l.pathname == '/login') { showBox() if (setting.autoLogin) waitForJQueryElement('#phone', 30000).then(function (found) { if (found) autoLogin(); else logger('登录页等待超时(30s),未找到手机号输入框', 'red'); }); } else if (_l.pathname.includes('/mycourse/studentstudy')) { showBox() clearLogEntries('初始化完毕!') setupAntiSleep() setupAutoRefresh() setInterval(function () { try { if (typeof _w.checkJob === 'function' && !_w._gptCheckJobHooked) { _w._gptCheckJobHooked = true; _w.checkJob = function () { return false; }; } } catch (_) {} try { if (_w.PCount && typeof _w.PCount.next === 'function' && !_w.PCount._gptHooked) { var _origPCountNext = _w.PCount.next; _w.PCount.next = function () { if (_w._gptJsJumpAllowed) { _w._gptJsJumpAllowed = false; return _origPCountNext.apply(this, arguments); } console.log('[GPTJs] 拦截 PCount.next 自动跳转'); return false; }; _w.PCount._gptHooked = true; } } catch (_) {} }, 1000); var _blankSectionChecks = 0; var _lastBlankSectionDoc = null; setInterval(function () { var cardsDoc = getStudyCardsDocument(_w); if (localStorage.getItem('GPTJsSetting.isPaused') === 'true' || !isEmptyStudyPage(cardsDoc)) { _blankSectionChecks = 0; _lastBlankSectionDoc = null; return; } if (cardsDoc !== _lastBlankSectionDoc) { _blankSectionChecks = 0; _lastBlankSectionDoc = cardsDoc; } _blankSectionChecks++; if (_blankSectionChecks >= 2) { _blankSectionChecks = 0; toNext(true); } }, 5000); } else if (_l.pathname.includes('/knowledge/cards')) { setupAntiSleep() var params = getTaskParams() var parsedParams = null; if (params && params !== '$mArg') { try { parsedParams = $.parseJSON(params); } catch (e) { parsedParams = null; } } if (!parsedParams || !parsedParams['attachments'] || parsedParams['attachments'].length <= 0) { logger('检测到无任务点(无任务参数),自动跳过', 'red') setTimeout(function () { toNext(true) }, 2000) } else { waitForJQueryElement('.wrap .ans-cc .ans-attach-ct', 8000).then(function (found) { if (!found) { var anyExists = document.querySelectorAll('.ans-attach-ct, .ans-job-ct, .chapter-item').length; if (anyExists > 0) { logger('章节任务均已完成,准备跳转', 'green') } else { logger('检测到无任务点(DOM 无任务节点),自动跳过', 'red') } setTimeout(function () { toNext(anyExists === 0) }, 2000) return; } try { if (typeof top.checkJob === 'function') top.checkJob = function () { return false; }; } catch (_) {} var _checkJobGuard = setInterval(function () { try { if (typeof top.checkJob === 'function') top.checkJob = function () { return false; }; } catch (_) {} }, 3000); _defaults = parsedParams['defaults'] var allDomNodes = [] $.each($('.wrap .ans-cc .ans-attach-ct'), function (i, t) { var iframeEl = $(t).find('iframe') var dataStr = '' try { dataStr = iframeEl.attr('data') || '' } catch (_) {} allDomNodes.push({ iframe: iframeEl, data: dataStr }) }) var rawList = parsedParams['attachments'] _mlist = [] _domList = [] var usedDomIndexes = {} for (var ai = 0; ai < rawList.length; ai++) { var att = rawList[ai] var attMid = (att['property'] && att['property']['mid']) || '' var attObjId = (att['property'] && att['property']['objectid']) || '' var matched = false for (var di = 0; di < allDomNodes.length; di++) { if (usedDomIndexes[di]) continue var dStr = allDomNodes[di].data if (dStr && ((attMid && dStr.indexOf(attMid) !== -1) || (attObjId && dStr.indexOf(attObjId) !== -1))) { _mlist.push(att) _domList.push(allDomNodes[di].iframe) usedDomIndexes[di] = true matched = true break } } if (!matched) { var skipType = att['type'] || (att['property'] && att['property']['module']) || 'unknown' var skipName = (att['property'] && att['property']['name']) || '' if (skipType === 'knowledgeGraph') { _mlist.push(att) _domList.push(null) console.log('[GPTJs] 保留 knowledgeGraph 任务点: ' + (skipName || '知识图谱')) } else { console.log('[GPTJs] 跳过无DOM对应的附件: type=' + skipType + (skipName ? ', name=' + skipName : '')) } } } if (_mlist.length === 0 && rawList.length > 0 && allDomNodes.length > 0) { console.log('[GPTJs] 精确匹配未命中,回退到索引对应模式') _mlist = rawList _domList = [] for (var fi = 0; fi < allDomNodes.length; fi++) { _domList.push(allDomNodes[fi].iframe) } } missonStart() }); } } else if (_l.pathname.includes('/exam/test/reVersionTestStartNew')) { showBox() waitForJQueryElement('.mark_table .whiteDiv', 30000).then(async function (found) { if (!found) { logger('考试页等待超时(30s),未找到题目容器', 'red'); return; } await _ne21DecryptReady; if (setting.decrypt) await decryptFont().catch(function (e) { console.error('[GPTJs] 字体解密失败', e); }); missonExam(); }); } else if (_l.pathname.includes('/mooc2/exam/preview')) { showBox() waitForJQueryElement('.mark_table .questionLi', 30000).then(async function (found) { if (!found) { logger('整卷预览页等待超时(30s),未找到题目列表', 'red'); return; } await _ne21DecryptReady; if (setting.decrypt) await decryptFont().catch(function (e) { console.error('[GPTJs] 字体解密失败', e); }); missonExamPreview(); }); } else if (_l.pathname.includes('/mooc2/work/dowork')) { showBox() waitForJQueryElement('.mark_table form', 30000).then(async function (found) { if (!found) { logger('作业页等待超时(30s),未找到作业表单', 'red'); return; } await _ne21DecryptReady; if (setting.decrypt) await decryptFont().catch(function (e) { console.error('[GPTJs] 字体解密失败', e); }); missonHomeWork(); }); } else if (_l.pathname.includes('/work/phone/doHomeWork')) { var _oldal = _w.alert _w.alert = function (msg) { if (msg == '保存成功') { return; } return _oldal(msg) } var _oldcf = _w.confirm _w.confirm = function (msg) { if (msg.includes('确认提交') || msg.includes('未做完')) { return true } return _oldcf(msg) } } else if (_l.pathname.includes('/page/quiz/stu/answerQuestion')) { showBox() waitForJQueryElement('.question-item', 30000).then(async function (found) { if (!found) { logger('随堂练习页等待超时(30s),未找到题目容器', 'red'); return; } await _ne21DecryptReady; if (setting.decrypt) await decryptFont().catch(function (e) { console.error('[GPTJs] 字体解密失败', e); }); missonQuizPractice(); }); } else if (_l.pathname.includes('/mooc2/exam/exam-list')) { } else if (_l.pathname == '/mycourse/stu') { checkBrowser() } else { if (window === top) { logger('ChatGPT学习通助手已就绪,进入课程视频、作业或考试页面即可自动运行', 'green'); } } function checkBrowser() { var userAgent = navigator.userAgent if (userAgent.indexOf('Chrome') == -1 || GM_info.scriptHandler != 'ScriptCat') { } } function parseUrlParams() { let query = window.location.search.substring(1); let vars = query.split("&"); let _p = {} for (let i = 0; i < vars.length; i++) { let pair = vars[i].split("="); _p[pair[0]] = pair[1] } return _p } function updateLocalStorage(event) { var checkbox = event.target; localStorage.setItem(checkbox.id, checkbox.checked); } function isRedoMode() { var stored = localStorage.getItem('GPTJsSetting.redo'); if (stored !== null) return stored === 'true'; return !!setting.redo; } function isFuzzyMatchEnabled() { return true; } function stringSimilarity(s1, s2) { if (!s1 && !s2) return 1; if (!s1 || !s2) return 0; s1 = s1.toLowerCase().trim(); s2 = s2.toLowerCase().trim(); if (s1 === s2) return 1; var len1 = s1.length, len2 = s2.length; if (len1 === 0 || len2 === 0) return 0; var prev = [], curr = []; for (let j = 0; j <= len2; j++) prev[j] = j; for (let i = 1; i <= len1; i++) { curr[0] = i; for (let j = 1; j <= len2; j++) { if (s1[i - 1] === s2[j - 1]) { curr[j] = prev[j - 1]; } else { curr[j] = 1 + Math.min(prev[j], curr[j - 1], prev[j - 1]); } } var tmp = prev; prev = curr; curr = tmp; } var maxLen = Math.max(len1, len2); return 1 - prev[len2] / maxLen; } function findBestFuzzyMatch(optionTexts, aiAnswer, threshold) { if (!isFuzzyMatchEnabled()) return -1; if (!aiAnswer || !optionTexts || optionTexts.length === 0) return -1; threshold = (threshold !== undefined) ? threshold : 0.5; var bestIndex = -1, bestScore = 0; for (var i = 0; i < optionTexts.length; i++) { var score = stringSimilarity(optionTexts[i], aiAnswer); if (score > bestScore) { bestScore = score; bestIndex = i; } } if (bestScore >= threshold) { logger('相似度匹配: 最佳匹配项[' + bestIndex + '] 相似度=' + (bestScore * 100).toFixed(1) + '%', 'blue'); return bestIndex; } logger('相似度匹配: 所有选项相似度均低于阈值(' + (threshold * 100) + '%),最高=' + (bestScore * 100).toFixed(1) + '%', 'orange'); return -1; } function findFuzzyMatchMultiple(optionTexts, aiAnswer, threshold) { if (!isFuzzyMatchEnabled()) return []; if (!aiAnswer || !optionTexts || optionTexts.length === 0) return []; threshold = (threshold !== undefined) ? threshold : 0.5; var parts = aiAnswer.split(ANSWER_SEPARATOR); var matched = []; for (var p = 0; p < parts.length; p++) { var part = parts[p].trim(); if (!part) continue; var bestIndex = -1, bestScore = 0; for (var i = 0; i < optionTexts.length; i++) { var score = stringSimilarity(optionTexts[i], part); if (score > bestScore) { bestScore = score; bestIndex = i; } } if (bestScore >= threshold && matched.indexOf(bestIndex) === -1) { matched.push(bestIndex); logger('相似度匹配(多选): "' + escapeLogText(part) + '" → 选项[' + bestIndex + '] 相似度=' + (bestScore * 100).toFixed(1) + '%', 'blue'); } } return matched; } function normalizeChoiceText(text) { return String(text == null ? '' : text) .replace(/^[A-Z]\s*[\.、.::)]\s*/i, '') .replace(/\s+/g, '') .trim(); } function getAnswerLetterIndexes(answer, optionCount) { var s = String(answer == null ? '' : answer).toUpperCase(); var result = []; var letterPattern = /(?:^|[^A-Z])([A-Z])(?=$|[^A-Z])/g; var m; while ((m = letterPattern.exec(s)) !== null) { var idx = m[1].charCodeAt(0) - 65; if (idx >= 0 && idx < optionCount && result.indexOf(idx) === -1) result.push(idx); } var compact = String(answer == null ? '' : answer).trim(); if (result.length === 0 && /^[A-Z]+$/.test(compact) && Array.from(compact).every(function (letter) { return letter.charCodeAt(0) - 65 < optionCount; })) { for (var i = 0; i < s.trim().length; i++) { var charIdx = s.trim().charCodeAt(i) - 65; if (charIdx >= 0 && charIdx < optionCount && result.indexOf(charIdx) === -1) result.push(charIdx); } } return result; } function splitAiAnswers(answer) { return String(answer == null ? '' : answer) .split(ANSWER_SEPARATOR) .map(function (s) { return s.trim(); }) .filter(Boolean); } var ANSWER_LEAD_IN = /^(?:正确答案|答案|正确)\s*[是为]?\s*[::]?\s*|^选择?\s*/; function getPartLetterIndexes(part, optionCount) { var text = String(part).trim().replace(ANSWER_LEAD_IN, ''); var list = text.match(/^[A-Z](?:\s*[,,、;;和与及]\s*[A-Z])*(?![A-Za-z0-9])/); if (!list) return []; var rest = text.slice(list[0].length); var indexes = list[0].replace(/[^A-Z]/g, '').split('').map(function (letter) { return letter.charCodeAt(0) - 65; }); if (indexes.length === 1 && !/^\s*(?:[.、.::)),,。;;]|$)/.test(rest)) return []; if (!indexes.every(function (idx) { return idx < optionCount; })) return []; var labeled = /(?:^|[^A-Za-z0-9((])([A-Z])(?=\s*[..、::))])/g; var last = indexes[indexes.length - 1]; var m; while ((m = labeled.exec(rest)) !== null) { var idx = m[1].charCodeAt(0) - 65; if (idx >= optionCount) continue; if (idx <= last) return []; indexes.push(idx); last = idx; } return indexes; } function getExplicitLetterIndexes(answer, parts, optionCount, isMultiple) { var inRange = function (idx) { return idx >= 0 && idx < optionCount; }; var tokens = String(answer == null ? '' : answer).trim().replace(ANSWER_LEAD_IN, '').split(ANSWER_SEPARATOR).join(' ') .split(/[\s,,、;;..。和与及]+/).filter(Boolean); var compact = tokens.join(''); var spelledOut = tokens.every(function (token) { return token.length === 1; }); if (/^[A-Za-z]+$/.test(compact) && (spelledOut || /^[A-Z]+$/.test(compact)) && (isMultiple || compact.length === 1)) { compact = compact.toUpperCase(); var pure = Array.from(new Set(compact.split('').map(function (letter) { return letter.charCodeAt(0) - 65; }))); if (pure.length === compact.length && pure.every(inRange)) return pure; } if (isMultiple) { var perPart = parts.map(function (part) { return getPartLetterIndexes(part, optionCount); }); if (perPart.length === 0 || perPart.some(function (found) { return found.length === 0; })) return []; return Array.from(new Set([].concat.apply([], perPart))); } var leading = parts.map(function (part) { var m = String(part).trim().match(/^(?:答案\s*[是为]?\s*[::]?\s*|选择?\s*)?([A-Z])\s*(?:[.、.::)),,。;;]|$)/); return m ? m[1].charCodeAt(0) - 65 : -1; }); if (leading.length > 0 && leading.every(inRange)) return leading.slice(0, 1); return []; } function findContainedOptionIndexes(options, answer) { var result = []; var remaining = String(answer == null ? '' : answer).replace(/\s+/g, ''); options.map(function (text, idx) { return { text: text, idx: idx }; }) .filter(function (option) { return option.text; }) .sort(function (a, b) { return b.text.length - a.text.length; }) .forEach(function (option) { if (remaining.indexOf(option.text) === -1) return; result.push(option.idx); remaining = remaining.split(option.text).join('\n'); }); return result; } function findVideoQuizMatchIndexes(optionTexts, aiAnswer, isMultiple) { var normalizedOptions = optionTexts.map(normalizeChoiceText); var parts = isMultiple ? splitAiAnswers(aiAnswer) : [String(aiAnswer == null ? '' : aiAnswer).trim()]; var exactIndexes = parts.map(function (part) { var text = normalizeChoiceText(part); return text ? normalizedOptions.indexOf(text) : -1; }); if (exactIndexes.length > 0 && exactIndexes.every(function (idx) { return idx >= 0; })) { return Array.from(new Set(exactIndexes)); } var result = getExplicitLetterIndexes(aiAnswer, parts, optionTexts.length, isMultiple); if (result.length > 0) return result; if (parts.length === 0 && aiAnswer) parts = [String(aiAnswer).trim()]; for (var p = 0; p < parts.length; p++) { var normalizedAnswer = normalizeChoiceText(parts[p]); if (!normalizedAnswer) continue; var contained = findContainedOptionIndexes(normalizedOptions, normalizedAnswer); if (!isMultiple) contained = contained.slice(0, 1); for (var i = 0; contained.length === 0 && i < normalizedOptions.length; i++) { if (result.indexOf(i) === -1 && normalizedOptions[i] && normalizedOptions[i].indexOf(normalizedAnswer) !== -1) contained = [i]; } contained.forEach(function (idx) { if (result.indexOf(idx) === -1) result.push(idx); }); } if (result.length === 0) { result = isMultiple ? findFuzzyMatchMultiple(normalizedOptions, aiAnswer, 0.45) : [findBestFuzzyMatch(normalizedOptions, aiAnswer, 0.45)]; result = result.filter(function (idx) { return idx >= 0; }); } if (result.length === 0) result = getAnswerLetterIndexes(aiAnswer, optionTexts.length); return isMultiple ? result : result.slice(0, 1); } function matchSingleOptionIndex(optionTexts, answer) { var exact = optionTexts.indexOf(answer); if (exact !== -1) return exact; var indexes = findVideoQuizMatchIndexes(optionTexts, answer, false); return indexes.length ? indexes[0] : -1; } function matchMultiOptionIndexes(optionTexts, answer) { var options = optionTexts.map(normalizeChoiceText); var parts = splitAiAnswers(answer); var exact = parts.map(function (part) { var text = normalizeChoiceText(part); return text ? options.indexOf(text) : -1; }); if (exact.length > 0 && exact.every(function (idx) { return idx >= 0; })) return Array.from(new Set(exact)); var result = getExplicitLetterIndexes(answer, parts, options.length, true); if (result.length > 0) return result; result = findContainedOptionIndexes(options, answer); if (result.length === 0) result = findFuzzyMatchMultiple(options, answer); return result.sort(function (a, b) { return a - b; }); } function getVideoQuizText(container, optionNodes) { var title = container.querySelector('.tkItem_title, .ans-videoquiz-title, .ans-videoquiz-subject, .ans-videoquiz-question, .videoquiz-title, .videoquiz-question'); if (title) return (title.innerText || title.textContent || '').replace(/\s+/g, ' ').trim(); var clone = container.cloneNode(true); try { Array.prototype.forEach.call(clone.querySelectorAll('.ans-videoquiz-opt, .tkTopic_numbar, .tkTopic_title, .tkTopic_oper, .tkParsing, .rightInfo, .spanNot, .spanNotBack, [id^="videoquiz-"], #knowledgeBack, #viewAnalysis, [id^="ascrail"], [hidden], [aria-hidden="true"], button, input, label'), function (node) { if (node.parentNode) node.parentNode.removeChild(node); }); } catch (_) {} var text = (clone.innerText || clone.textContent || '').trim(); (optionNodes || []).forEach(function (label) { var optText = (label.innerText || label.textContent || '').trim(); if (optText) text = text.replace(optText, ''); }); return text.replace(/\s+/g, ' ').trim(); } function isVideoQuizNodeVisible(node) { if (!node || !node.isConnected) return false; var view = node.ownerDocument.defaultView; for (var el = node; el && el.nodeType === 1; el = el.parentElement) { if (el.hidden || el.getAttribute('aria-hidden') === 'true') return false; var style = view.getComputedStyle(el); if (style.display === 'none' || style.visibility === 'hidden' || style.visibility === 'collapse') return false; } return true; } function getVisibleVideoQuizNode(container, selector) { return Array.prototype.slice.call(container.querySelectorAll(selector)).find(isVideoQuizNodeVisible); } function getVideoQuizResult(container) { if (getVisibleVideoQuizNode(container, '#videoquiz-submitting')) return 'pending'; var wrong = getVisibleVideoQuizNode(container, '#spanNot, #spanNotBack, #spanNotBackPoint, .spanNot, .spanNotBack'); if (wrong && /真遗憾|回答错误|答错/.test(wrong.textContent || '')) return 'wrong'; var right = getVisibleVideoQuizNode(container, '#spanHas, .rightInfo'); if (right && /答对|回答正确/.test(right.textContent || '')) return 'correct'; if (getVisibleVideoQuizNode(container, '#videoquiz-continue, .ans-videoquiz-continue')) return 'correct'; return 'pending'; } function getVideoQuizInput(label) { var option = label.closest('.ans-videoquiz-opt'); return label.control || label.querySelector('input') || (option && option.querySelector('input')); } function getVideoQuizFallbackIndexes(record, optionCount, isMultiple) { if (record.triedAnswers.length >= 16) return []; if (!isMultiple) { for (var i = 0; i < optionCount; i++) { if (record.triedAnswers.indexOf(String(i)) === -1) return [i]; } return []; } var selected = record.aiIndexes.slice(); var findCombination = function (start, remaining) { if (remaining === 0) { var indexes = selected.slice().sort(function (a, b) { return a - b; }); return indexes.length && record.triedAnswers.indexOf(indexes.join(',')) === -1 ? indexes : null; } for (var idx = start; idx <= optionCount - remaining; idx++) { var pos = selected.indexOf(idx); if (pos === -1) selected.push(idx); else selected.splice(pos, 1); var found = findCombination(idx + 1, remaining - 1); if (pos === -1) selected.splice(selected.indexOf(idx), 1); else selected.push(idx); if (found) return found; } return null; }; for (var distance = 1; distance <= optionCount; distance++) { var next = findCombination(0, distance); if (next) return next; } return []; } function handleVideoQuiz(doc, media, taskName) { if (!setting.work || localStorage.getItem('GPTJsSetting.isPaused') === 'true') return false; var container = getVisibleVideoQuizNode(doc, '.ans-videoquiz'); if (!container || !media) return false; var result = getVideoQuizResult(container); var optionNodes = Array.prototype.slice.call(container.querySelectorAll('.ans-videoquiz-opt label')); if (optionNodes.length === 0) optionNodes = Array.prototype.slice.call(container.querySelectorAll('label')); var optionTexts = optionNodes.map(function (label) { return (label.innerText || label.textContent || '').trim(); }); var inputs = optionNodes.map(getVideoQuizInput); var typeNode = container.querySelector('.tkTopic_title'); var typeText = typeNode ? typeNode.textContent : ''; var isMultiple = /多选|多项/.test(typeText) || inputs.some(function (input) { return input && input.type === 'checkbox'; }); var isJudge = !isMultiple && (/判断/.test(typeText) || (optionTexts.length === 2 && optionTexts.every(function (t) { return /^(正确|错误|对|错|是|否|true|false|√|×)$/i.test(normalizeChoiceText(t)); }))); var question = getVideoQuizText(container, optionNodes); var typeName = isMultiple ? '多选题' : (isJudge ? '判断题' : '单选题'); var quizKey = JSON.stringify([media.currentSrc || media.src || taskName, typeName, question, optionTexts]); media._ne21VideoQuizRecords = media._ne21VideoQuizRecords || Object.create(null); var record = media._ne21VideoQuizRecords[quizKey]; if (!record) record = media._ne21VideoQuizRecords[quizKey] = { phase: 'idle', triedAnswers: [], aiIndexes: [], pendingIndexes: [] }; if (result === 'correct') { record.phase = 'solved'; record.solvedIndexes = []; inputs.forEach(function (input, idx) { if (input && input.checked) record.solvedIndexes.push(idx); }); if (!record.solvedIndexes.length) record.solvedIndexes = record.pendingIndexes.slice(); if (container.getAttribute('data-ne21-status') === 'done') return true; container.setAttribute('data-ne21-status', 'done'); logger('弹题已答对,尝试点击“继续学习”并清理弹窗', 'green'); var completedQuestion = getVideoQuizText(container); var btn = getVisibleVideoQuizNode(container, '#videoquiz-continue, .ans-videoquiz-continue'); if (btn) try { btn.click(); } catch (_) {} setTimeout(function () { try { if (container.isConnected && getVideoQuizText(container) === completedQuestion && getVideoQuizResult(container) === 'correct') { container.remove(); } if (!getVisibleVideoQuizNode(doc, '.ans-videoquiz') && media.isConnected && media.paused && !media.ended && localStorage.getItem('GPTJsSetting.isPaused') !== 'true') { var play = media.play(); if (play && play.catch) play.catch(function () {}); } } catch (_) {} }, 800); return true; } if (optionNodes.length === 0) return false; try { media.pause(); } catch (_) {} var waitForManual = function (message) { record.phase = 'manual'; container.setAttribute('data-ne21-status', 'manual'); logger(message + ',已停止自动重试,请手动处理', 'orange'); }; if (record.phase === 'manual' || record.phase === 'requesting' || record.phase === 'selecting') return true; if (!question) { waitForManual('视频弹题未能提取题干'); return true; } var submitBtn = getVisibleVideoQuizNode(container, '#videoquiz-submit'); if (record.phase === 'submitted') { if (result === 'wrong') record.phase = 'retry'; else { if (Date.now() - record.submittedAt >= 15000) waitForManual('视频弹题提交结果未确认'); return true; } } if (record.phase === 'retry' && !getVideoQuizFallbackIndexes(record, optionTexts.length, isMultiple).length) { waitForManual('视频弹题已尝试可用答案或达到 16 次上限'); return true; } if (result === 'wrong' && !submitBtn) { if (!record.replayRequestedAt) { var back = getVisibleVideoQuizNode(container, '#knowledgeBack, .ans-videoquiz-back'); if (!back) { waitForManual('视频弹题答错后无法恢复答题'); return true; } record.replayRequestedAt = Date.now(); logger('视频弹题回答错误,先回看知识点再重试', 'orange'); try { back.click(); } catch (_) { waitForManual('视频弹题回看失败'); } } else if (Date.now() - record.replayRequestedAt >= 15000) { waitForManual('视频弹题未能恢复答题'); } return true; } if (!submitBtn || submitBtn.disabled) return true; record.replayRequestedAt = 0; var isCurrentQuiz = function () { return media.isConnected && isVideoQuizNodeVisible(container) && getVideoQuizText(container, optionNodes) === question && optionNodes.every(function (label) { return label.isConnected && container.contains(label); }); }; var doSubmit = function (indexes) { record.pendingIndexes = indexes.slice().sort(function (a, b) { return a - b; }); record.phase = 'ready'; if (localStorage.getItem('GPTJsSetting.isPaused') === 'true' || !isCurrentQuiz()) return; indexes.forEach(function (idx) { var label = optionNodes[idx]; if (!label) return; label.style.fontWeight = 'bold'; label.style.color = '#dc2626'; }); if (localStorage.getItem('GPTJsSetting.goodStudent') === 'true') { waitForManual('视频弹题答案已加粗,当前为好学生模式'); return; } try { optionNodes.forEach(function (label, idx) { var wanted = indexes.indexOf(idx) !== -1; var input = inputs[idx]; if (input ? input.checked !== wanted && (isMultiple || wanted) : wanted) label.click(); }); if (inputs.some(function (input, idx) { return input && input.checked !== (indexes.indexOf(idx) !== -1); })) { waitForManual('视频弹题选项未能正确勾选'); return; } } catch (_) { waitForManual('视频弹题选项点击失败'); return; } record.phase = 'selecting'; container.setAttribute('data-ne21-status', 'processing'); setTimeout(function () { record.phase = 'ready'; if (localStorage.getItem('GPTJsSetting.isPaused') === 'true' || !isCurrentQuiz()) return; if (localStorage.getItem('GPTJsSetting.goodStudent') === 'true') { waitForManual('当前为好学生模式'); return; } if (!isVideoQuizNodeVisible(submitBtn) || submitBtn.disabled) { waitForManual('视频弹题提交按钮不可用'); return; } if (inputs.some(function (input, idx) { return input && input.checked !== (record.pendingIndexes.indexOf(idx) !== -1); })) { waitForManual('视频弹题勾选状态已变化'); return; } record.phase = 'submitted'; record.submittedAt = Date.now(); record.triedAnswers.push(record.pendingIndexes.join(',')); try { submitBtn.click(); logger('视频弹题已提交,等待答题结果', 'green'); } catch (_) { waitForManual('视频弹题提交失败'); } }, 600); }; if (record.phase === 'solved') { if (!record.solvedIndexes.length || record.triedAnswers.length >= 16) { waitForManual('视频弹题重复出现次数过多或已验证答案不可用'); return true; } logger('视频弹题重复出现,沿用已验证答案', 'orange'); doSubmit(record.solvedIndexes); } else if (record.phase === 'ready') { doSubmit(record.pendingIndexes); } else if (record.phase === 'retry') { var nextIndexes = getVideoQuizFallbackIndexes(record, optionTexts.length, isMultiple); if (!nextIndexes.length) { waitForManual('视频弹题已尝试可用答案或达到 16 次上限'); return true; } logger('视频弹题上一答案错误,尝试未提交过的' + (isMultiple ? '组合: ' : '选项: ') + escapeLogText(nextIndexes.map(function (i) { return optionTexts[i]; }).join(',')), 'orange'); doSubmit(nextIndexes); } else { record.phase = 'requesting'; container.setAttribute('data-ne21-status', 'processing'); var prompt = buildPrompt({ type: typeName, question: question, options: optionTexts, answer_format: isMultiple ? "用'" + ANSWER_SEPARATOR + "'分割多个答案,或回答选项字母" : (isJudge ? '只回答正确或错误,或回答选项字母' : '只回答一个选项字母或选项内容') }); logger('检测到视频中题目,开始处理:' + (taskName || ''), 'purple'); getAnswer(isMultiple ? 1 : (isJudge ? 3 : 0), prompt).then(function (answer) { if (record.phase !== 'requesting') return; var indexes; if (isJudge) { var parsed = parseJudgeAnswer(answer); if (parsed) { indexes = []; optionTexts.forEach(function (text, idx) { var norm = normalizeChoiceText(text); if (parsed === 'true' && /正确|对|是|true|√/i.test(norm)) indexes.push(idx); if (parsed === 'false' && /错误|错|否|false|×/i.test(norm)) indexes.push(idx); }); } } if (!indexes || indexes.length === 0) { indexes = findVideoQuizMatchIndexes(optionTexts, answer, isMultiple); } if (indexes.length === 0) { waitForManual('视频弹题未能匹配到选项'); return; } record.aiIndexes = indexes.slice(); doSubmit(indexes); }).catch(function () { if (record.phase === 'requesting') waitForManual('视频弹题 AI 作答失败'); }); } return true; } function getRate() { var stored = localStorage.getItem('GPTJsSetting.rate'); var n = stored !== null ? parseFloat(stored) : (setting.rate || 1); if (!isFinite(n) || n <= 0) n = 1; if (n > 16) n = 16; return n; } function parseJudgeAnswer(agrs) { if (!agrs) return null; var raw = String(agrs).toLowerCase(); var s = raw.replace(/[。,.,!!\s]/g, ''); var trueWords = ['正确', '是', '对', '√', '✓', '✔', 't', 'true', 'ri', 'right', 'yes']; var falseWords = ['错误', '否', '错', '×', '✗', '✘', 'f', 'false', 'wr', 'wrong', 'no']; for (let i = 0; i < trueWords.length; i++) { if (s === trueWords[i]) return 'true'; } for (let i = 0; i < falseWords.length; i++) { if (s === falseWords[i]) return 'false'; } if (/没有?错|不错|无误/.test(s)) return 'true'; if (/不正确|不对|不是|错|否|×|✗|✘/.test(s) || /\b(?:false|wrong|incorrect|no|not\s+(?:true|correct|right))\b/.test(raw)) return 'false'; if (/正确|对|是|√|✓|✔/.test(s) || /\b(?:true|right|correct|yes)\b/.test(raw)) return 'true'; return null; } function findJudgeOptionIndex(optionTexts, isTrue) { var trueWords = ['正确', '是', '对', '√', 'T', 'ri']; var falseWords = ['错误', '否', '错', '×', 'F', 'wr']; var words = isTrue ? trueWords : falseWords; for (var i = 0; i < optionTexts.length; i++) { var t = optionTexts[i]; for (var j = 0; j < words.length; j++) { if (t.indexOf(words[j]) !== -1) return i; } } return -1; } function findAnswerTextareas($container) { if (!$container || $container.length === 0) return $(); var $eles = $container.find('textarea[name^="answerEditor"]'); if ($eles.length > 0) return $eles; $eles = $container.find('.subEditor textarea, .Answer .divText textarea, .stem_answer textarea, .edui-editor textarea'); if ($eles.length > 0) return $eles; return $container.find('textarea'); } function readQuestionTypeCode($item) { if (!$item || !$item.length) return Number.NaN; function parseCode(val) { if (val === undefined || val === null) return Number.NaN; var s = String(val).trim(); return /^\d+$/.test(s) ? Number.parseInt(s, 10) : Number.NaN; } var code = parseCode($item.attr('qtype') || $item.attr('data-qtype')); if (!Number.isNaN(code)) return code; if ($item.is('.readCompreHensionItem')) { code = parseCode($item.find('input[name="readCompreHension-childType"]').val()); if (!Number.isNaN(code)) return code; code = parseCode($item.find('ul[qtype]').first().attr('qtype')); if (!Number.isNaN(code)) return code; } var $answerTypes = $item.find('input[id^="answertype"], input[name^="answertype"]'); for (var i = 0; i < $answerTypes.length; i++) { code = parseCode($answerTypes.eq(i).val()); if (!Number.isNaN(code)) return code; } var qid = $item.attr('data') || $item.find('input[name="questionId"], input#questionId, input.questionId, .questionId').first().val(); if (!qid) { var idMatch = String($item.attr('id') || '').match(/(\d+)$/); if (idMatch) qid = idMatch[1]; } if (qid && /^\d+$/.test(String(qid).trim())) { var cleanQid = String(qid).trim(); var doc = $item[0] && $item[0].ownerDocument ? $item[0].ownerDocument : document; var $byQid = $(doc).find('input[name="answertype' + cleanQid + '"], input[id="answertype' + cleanQid + '"], input[name="type' + cleanQid + '"]'); for (var k = 0; k < $byQid.length; k++) { code = parseCode($byQid.eq(k).val()); if (!Number.isNaN(code)) return code; } } var $typeInputs = $item.find('input[name^="type"]'); for (var j = 0; j < $typeInputs.length; j++) { var inputName = String($typeInputs.eq(j).attr('name') || ''); if (!/^type\d+$/i.test(inputName)) continue; code = parseCode($typeInputs.eq(j).val()); if (!Number.isNaN(code)) return code; } var $optWithType = $item.find('.stem_answer [qtype], .stem_answer [data-qtype], .answerBg[qtype], .answerBg[data-qtype], .answerList[qtype]').first(); if ($optWithType.length) { code = parseCode($optWithType.attr('qtype') || $optWithType.attr('data-qtype')); if (!Number.isNaN(code) && ![14, 15, 19].includes(code)) return code; } if ($item.is('.TiMu')) { code = parseCode($item.attr('data')); if (!Number.isNaN(code) && code <= 30) return code; } return Number.NaN; } function hasMultipleChoiceDom($item) { if (!$item || !$item.length) return false; return $item.find( '.num_option_dx, [role="checkbox"], [onclick*="addMultipleChoice"], .saveMultipleSelect, .saveMultiSelect, .answerList.multiChoice li, input[type="checkbox"]' ).length > 0; } function detectStandardQuestionType($container, typeName) { var cleanName = String(typeName || '').replace(/\s+/g, ''); if (/^(写作|作文)题?$/.test(cleanName)) return { type: 5, source: 'name' }; if (/^翻译题?$/.test(cleanName)) return { type: 6, source: 'name' }; var code = readQuestionTypeCode($container); var baseMap = { 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 4, 6: 4, 7: 4, 8: 4, 9: 4, 10: 4 }; if (baseMap[code] !== undefined) { return { type: baseMap[code], source: 'code', code: code }; } if ($container && $container.length) { if (hasMultipleChoiceDom($container)) return { type: 1, source: 'dom' }; if ($container.find('.answerList.panduan li').length > 0) return { type: 3, source: 'dom' }; if ($container.find('.num_option, [role="radio"], [onclick*="addChoice("], .saveSingleSelect, .answerList.singleChoice li, input[type="radio"], .stem_answer .answer_p, .answerBg .answer_p').length > 0) { return { type: 0, source: 'dom' }; } if ($container.find('.blankList2 input, .blankInp, .filling_answer input').length > 0) return { type: 2, source: 'dom' }; if ($container.find('textarea[name^="answerEditor"], .subEditor textarea, .Answer .divText textarea, .edui-editor, textarea').length > 0) { return { type: 4, source: 'dom' }; } } if (/多[项选]*选|不定项/.test(cleanName)) return { type: 1, source: 'name' }; if (/单[项选]*选|选择题/.test(cleanName)) return { type: 0, source: 'name' }; if (/判断|是非/.test(cleanName)) return { type: 3, source: 'name' }; if (/填空|思政元素/.test(cleanName)) return { type: 2, source: 'name' }; if (/简答|问答|名词解释|论述|计算|分录|材料|资料|写作|作文|翻译|证明|分析|应用|其它|其他|阅读|完[型形]|综合/.test(cleanName)) { return { type: 4, source: 'name' }; } return { type: undefined, source: 'unknown' }; } function getQuestionTypeLabel(type) { return ({ 0: '单选题', 1: '多选题', 2: '填空题', 3: '判断题', 4: '简答题', 5: '写作题', 6: '翻译题' })[type] || '未知题型'; } function getWorkQuestionType($item, typeName) { var name = typeName || $item.attr('typename') || $item.find('.newZy_TItle, .Zy_TItle, .Py-m1-title, .colorShallow, .read_type, .grey-text').first().text(); name = String(name || '').replace(/\s+/g, ''); var prefix = name.match(/[【\[((]([^】\])),,]+)[】\])),,]/); if (prefix) name = prefix[1]; var code = readQuestionTypeCode($item); if ($item.find('.CodeMirror, .ace_editor, .monaco-editor').length) return { type: 17, typeName: name || '编程题' }; var codes = { 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 4, 6: 4, 7: 4, 8: 4, 9: 4, 10: 4, 11: 11, 13: 13, 14: 15, 15: 15, 17: 17, 19: 15, 20: 20, 24: 24 }; if (codes[code] !== undefined) { var defaultNames = { 0: '单选题', 1: '多选题', 2: '填空题', 3: '判断题', 11: '连线题', 13: '排序题', 15: '阅读理解', 17: '编程题', 20: '共用选项题', 24: '选词填空' }; return { type: codes[code], typeName: name || defaultNames[codes[code]] || '文字题' }; } if ($item.find('.fillBlanksChoose').length) return { type: 24, typeName: name || '选词填空' }; if ($item.find('.bTypeWrap').length) return { type: 20, typeName: name || '共用选项题' }; if (hasMultipleChoiceDom($item)) return { type: 1, typeName: name || '多选题' }; var rules = [ [/编程|程序|代码/, 17], [/选词填空/, 24], [/共用选项/, 20], [/连线|匹配/, 11], [/排序/, 13], [/完[型形]|阅读|听力|综合|组合/, 15], [/多[项选]*选|不定项/, 1], [/单[项选]*选|选择题/, 0], [/判断|是非/, 3], [/填空|思政元素/, 2], [/简答|问答|名词解释|论述|计算|分录|材料|资料|写作|作文|翻译|证明|分析|应用|其它|其他/, 4] ]; for (var i = 0; i < rules.length; i++) { if (rules[i][0].test(name)) return { type: rules[i][1], typeName: name }; } if ($item.find('.saveSingleSelect, [class*="before-after"], .answerBg, .stem_answer .hoverDiv, .answerList li, input[type="radio"], [role="radio"], [onclick*="addChoice"]').length) return { type: 0, typeName: name || '单选题' }; if ($item.find('.CodeMirror, .ace_editor, .monaco-editor').length) code = 17; return { type: code === 17 ? 17 : codes[code], typeName: name || '题型' + code }; } function getWorkSubQuestions($item) { var selector = '.reading_answer, .filling_answer, .reader_answer, .readCompreHensionItem, [class*="clozeTextItem"]'; var $subs = $item.find(selector); if (!$subs.length) { $subs = $item.find('[qtype], [data-qtype]').filter(function () { return !$(this).is('li, a, span, input') && $(this).find('.saveSingleSelect, .saveMultipleSelect, .answerBg, [role="radio"], input[type="radio"], textarea').length > 1; }); } return $subs.filter(function () { var node = this; return !$subs.toArray().some(function (parent) { return parent !== node && parent.contains(node); }); }); } function removeQuestionMarkControls($root) { var MARK_TEXT_RE = /^(?:标记|取消标记|已标记)$/; var INLINE_FORMAT_SELECTOR = 'b, strong, u, sub, sup, code, font, p'; var INTERACTIVE_CLASS_RE = /(?:mark|sign|flag|tag|btn|collect|star|biaoji)/i; var candidates = $root.find('*').filter(function () { var $el = $(this); if ($el.find('img').length) return false; return MARK_TEXT_RE.test(($el.text() || '').replace(/\s+/g, '')); }).get(); candidates = candidates.filter(function (el) { return !candidates.some(function (other) { return other !== el && other.contains(el); }); }); candidates.forEach(function (el) { var $el = $(el); if ($el.is(INLINE_FORMAT_SELECTOR)) return; var before = '', after = '', seen = false; (function walk(parent) { var nodes = parent.childNodes; for (var i = 0; i < nodes.length; i++) { var child = nodes[i]; if (child === el) { seen = true; continue; } if (child.nodeType === 3) { if (seen) after += child.nodeValue || ''; else before += child.nodeValue || ''; } else if (child.nodeType === 1) { if (child.tagName === 'IMG') { if (seen) after += '[img]'; else before += '[img]'; } else { walk(child); } } } })($root[0]); var beforeTrim = before.replace(/\s+/g, ''); var afterTrim = after.replace(/\s+/g, ''); var remaining = (beforeTrim + afterTrim).replace(/^(?:\d+[.、.]|[((]\d+[))])+/, ''); if (!remaining) return; var cls = String(el.getAttribute && el.getAttribute('class') || ''); var isInteractive = $el.is('a, button, [onclick], [role="button"]') || $el.find('a, button, [onclick], [role="button"]').length > 0 || INTERACTIVE_CLASS_RE.test(cls); var atStart = !beforeTrim || /^(?:\d+[.、.]|[((]\d+[))])+$/.test(beforeTrim); var atEnd = !afterTrim; if (isInteractive || atStart || atEnd) { $el.remove(); } }); } function extractQuestionFromTitle($title) { if (!$title || !$title.length) return ''; var $clone = $title.clone(); $clone.find('.colorShallow, .read_type, .ne21-ai-answer, script, style').remove(); removeQuestionMarkControls($clone); var html = $clone.html() || ''; var typeTagRe = /^[((](?:[^(())]{1,20}[,,]\s*\d+(?:\.\d+)?\s*分|(?:单选|单项选择|多选|多项选择|判断|是非|填空|简答|问答|论述|名词解释|计算|分录|资料|作图|阅读理解|完形填空|综合|写作|翻译|排序|连线|匹配|材料|选词填空|听力|口语|程序|编程|代码|操作|客观|主观|其他|其它)题?)[))]\s*/; var numPrefixRe = /^(?:\(\d+\)|(\d+)|\d+\s*[.、.](?!\d))\s*/; return (tidyQuestion(html.replace(/|<\/(?:p|div|pre|tr)>/gi, '\n')) || '') .replace(numPrefixRe, '') .replace(typeTagRe, '') .replace(numPrefixRe, '') .replace(/\r\n?/g, '\n') .replace(/[ \t]+\n/g, '\n') .replace(/\n[ \t]*\t+[ \t]*/g, '\n') .replace(/\t+/g, ' ') .replace(/\n{3,}/g, '\n\n') .trim(); } function getWorkQuestionText($item) { var $title = $item.is('.readCompreHensionItem') ? $item.children('.clear').children('div').first() : $(); if (!$title.length) $title = $item.find('.fontLabel, h3.mark_name, .Zy_TItle > div, .Py-m1-title, .reader_answer_tit').first(); return extractQuestionFromTitle($title); } function getWorkTextEditors($item, isCode) { var win = $item[0].ownerDocument.defaultView; var editors = []; $item.find('.CodeMirror, .ace_editor, .monaco-editor').each(function () { var node = this, editor; if (node.CodeMirror) { editor = node.CodeMirror; editors.push({ get: function () { return editor.getValue(); }, set: function (value) { editor.setValue(value); if (editor.save) editor.save(); return editor.getValue() === value; } }); } else if (node.classList.contains('ace_editor') && win.ace) { editor = win.ace.edit(node); editors.push({ get: function () { return editor.getValue(); }, set: function (value) { editor.setValue(value, -1); return editor.getValue() === value; } }); } else if (win.monaco && win.monaco.editor && win.monaco.editor.getEditors) { editor = win.monaco.editor.getEditors().find(function (e) { return e.getDomNode() === node; }); if (editor) editors.push({ get: function () { return editor.getValue(); }, set: function (value) { editor.setValue(value); return editor.getValue() === value; } }); } }); if (editors.length) return editors; findAnswerTextareas($item).filter(function () { return !$(this).closest('.CodeMirror, .ace_editor, .monaco-editor').length; }).each(function () { var textarea = this, ue; var ids = [textarea.name, textarea.id, 'ananas-editor-' + textarea.id]; if (win.UE) { for (var i = 0; i < ids.length && !ue; i++) { if (ids[i]) ue = win.UE.instants && win.UE.instants[ids[i]]; } if (!ue) ue = Object.values(win.UE.instants || {}).find(function (editor) { return editor.textarea === textarea || ids.includes(editor.key) || ids.includes(editor.id); }); if (!ue && /^answerEditor/.test(textarea.name || '')) { try { ue = win.UE.getEditor(textarea.name); } catch (_) {} } } editors.push({ get: function () { return ue && ue.getContentTxt ? ue.getContentTxt() : textarea.value; }, set: async function (value) { if (ue) { if (!ue.isReady && ue.ready) { await new Promise(function (resolve, reject) { var timer = setTimeout(function () { reject(new Error('编辑器加载超时')); }, 10000); ue.ready(function () { clearTimeout(timer); resolve(); }); }); } var html = $('
').text(value).html().replace(/\n/g, '
'); ue.setContent('

' + html + '

'); } setQuizPracticeValue($(textarea), value); return ue && ue.getContentTxt ? Boolean(ue.getContentTxt().trim()) : textarea.value === value; } }); }); if (!editors.length && !isCode) { $item.find('[contenteditable="true"]').each(function () { var node = this; editors.push({ get: function () { return node.textContent; }, set: function (value) { node.textContent = value; node.dispatchEvent(new win.Event('input', { bubbles: true })); return node.textContent === value; } }); }); } return editors; } function workOptionSelected(node) { var $node = $(node); return $node.attr('aria-checked') === 'true' || $node.attr('aria-label') && /未选|未选择/.test($node.attr('aria-label')) === false && /已选/.test($node.attr('aria-label')) || $node.is(':checked, .cur, .check_answer, .check_answer_dx') || $node.find('input:checked, .check_answer, .check_answer_dx').length > 0; } function parseWorkTextAnswer(answer, expectedCount, isFillBlank) { var text = String(answer || '').trim(); if (/^\[[\s\S]*\]$/.test(text)) { try { var parsed = JSON.parse(text); if (Array.isArray(parsed) && parsed.length > 0 && parsed.every(function (v) { return typeof v === 'string' || typeof v === 'number'; })) { var arr = parsed.map(function (v) { return String(v).trim(); }); if (arr.length === expectedCount) return arr; if (expectedCount === 1) return [arr.join('\n')]; } } catch (_) {} } if (expectedCount === 1) return [isFillBlank ? text.split(ANSWER_SEPARATOR).map(function (part) { return part.trim(); }).filter(Boolean).join('、') : text]; if (text.indexOf(ANSWER_SEPARATOR) !== -1) { return text.split(ANSWER_SEPARATOR).map(function (part) { return part.trim(); }); } if (isFillBlank) { return text.split(/\r?\n+/).map(function (part) { return part.trim(); }).filter(Boolean); } return [text]; } function splitSequenceAnswer(answer, expectedCount) { var text = String(answer || '').trim(); if (/^\[[\s\S]*\]$/.test(text)) { try { var parsed = JSON.parse(text); if (Array.isArray(parsed) && parsed.length === expectedCount) { return parsed.map(function (v) { return String(v).trim(); }); } } catch (_) {} } var parts = text.split(ANSWER_SEPARATOR).map(function (p) { return p.trim(); }).filter(Boolean); if (parts.length === expectedCount) return parts; if (expectedCount > 1) { var bySep = text.split(/[,,、;;\s\r\n]+/).map(function (p) { return p.trim(); }).filter(Boolean); if (bySep.length === expectedCount) return bySep; var compactLetters = text.replace(/[^A-Za-z]/g, ''); if (compactLetters.length === expectedCount && /^[A-Za-z\s,,、;;\-]+$/.test(text)) { return compactLetters.toUpperCase().split(''); } } return parts; } async function answerWorkQuestion($item, info, question) { var type = info.type; if (!question && type !== 24) throw new Error('未找到题干'); var $subs = getWorkSubQuestions($item); if ($subs.length) { return new Promise(function (resolve) { processSubQuestions(0, $subs, question, function () { return setting.time; }, resolve); }); } if (type === 15 && findAnswerTextareas($item).length) type = 4; if ([0, 1, 3].includes(type)) { var $options = $item.find('.saveSingleSelect, .saveMultipleSelect, .saveMultiSelect'); if (!$options.length) $options = $item.find('[class*="before-after"]'); if (!$options.length) $options = $item.find('.Zy_ulTop li, .answerBg, .stem_answer .hoverDiv, .answerList li, [role="radio"], [role="checkbox"], [onclick*="addChoice"], [onclick*="addMultipleChoice"]'); if (!$options.length) throw new Error('未找到选项'); if (!isRedoMode() && $options.toArray().some(workOptionSelected)) return true; var texts = $options.map(function () { var $text = $(this).find('.fl.after, .answer_p, .optiontext').first(); return ($text.length ? $text : $(this)).text().replace(/\s+/g, ' ').trim(); }).get(); var prompt = buildPrompt({ type: info.typeName, question: question, options: texts, answer_format: type === 3 ? '只回答正确或错误' : type === 1 ? "多个答案用'" + ANSWER_SEPARATOR + "'分隔,或回答选项字母" : '只回答一个选项字母或选项内容' }); var answer = await getAnswer(type, prompt); var indexes; if (type === 3) { var judge = parseJudgeAnswer(answer); var idx = judge === null ? -1 : findJudgeOptionIndex(texts, judge === 'true'); indexes = idx < 0 ? getAnswerLetterIndexes(answer, texts.length) : [idx]; } else { indexes = findVideoQuizMatchIndexes(texts, answer, type === 1); } if (!indexes.length || type !== 1 && indexes.length !== 1) throw new Error('未匹配到完整答案'); $options.each(function (i) { var selected = workOptionSelected(this), wanted = indexes.includes(i); if (wanted && !selected || type === 1 && selected && !wanted) this.click(); }); return true; } if (type === 20) { var $wrap = $item.find('.bTypeWrap').first(); var $subCts = $wrap.find('.B-answer-ct'); if (!$wrap.length || !$subCts.length) throw new Error('未找到共用选项题控件,请手动作答'); var allAnsweredB = $subCts.toArray().every(function (ct) { return $(ct).find('.B-answerCon span.check_answer').length > 0; }); if (!isRedoMode() && allAnsweredB) return true; var sharedOpts = $wrap.children('.stem_answer').children('.clearfix').map(function () { var key = $(this).find('span').first().text().replace(/[.、.\s]+/g, '').trim().toUpperCase(); var text = tidyQuestion($(this).find('div').first().html() || '') || $(this).find('div').first().text().trim(); return key ? { key: key, text: text } : null; }).get(); var subQuestionsText = $subCts.map(function (i) { var $clone = $(this).clone(); $clone.find('.B-answerCon').remove(); var t = tidyQuestion($clone.html() || '') || $clone.text().replace(/\s+/g, ' ').trim(); return '(' + (i + 1) + ') ' + t.replace(/^\(\d+\)\s*/, ''); }).get(); var bQuestion = question; if (sharedOpts.length) { bQuestion += '\n共用备选答案:\n' + sharedOpts.map(function (o) { return o.key + '. ' + o.text; }).join('\n'); } bQuestion += '\n小题:\n' + subQuestionsText.join('\n'); var bAnswer = await getAnswer(4, buildPrompt({ type: info.typeName, question: bQuestion, answer_format: '共' + $subCts.length + '个小题,按小题顺序返回对应选项字母,用' + ANSWER_SEPARATOR + '分隔(例如A' + ANSWER_SEPARATOR + 'B),不要返回小题编号,不要解释' })); var bParts = splitSequenceAnswer(bAnswer, $subCts.length); if (bParts.length !== $subCts.length) throw new Error('共用选项题答案数量不匹配'); var bTargets = $subCts.toArray().map(function (ct, i) { var part = bParts[i].trim(); var $spans = $(ct).find('.B-answerCon span[data]'); var upper = part.toUpperCase(); var $hit = $spans.filter(function () { return String($(this).attr('data') || '').toUpperCase() === upper; }).first(); if (!$hit.length) { var matchedOpt = sharedOpts.find(function (o) { return o.text === part; }); if (matchedOpt) { $hit = $spans.filter(function () { return String($(this).attr('data') || '').toUpperCase() === matchedOpt.key; }).first(); } } if (!$hit.length) { var letterMatch = upper.match(/^([A-Z])(?:[.、=::\s]|$)/); if (letterMatch) { $hit = $spans.filter(function () { return String($(this).attr('data') || '').toUpperCase() === letterMatch[1]; }).first(); } } return $hit[0]; }); if (bTargets.some(function (node) { return !node; })) throw new Error('共用选项题答案匹配失败'); bTargets.forEach(function (node) { if (!$(node).hasClass('check_answer')) node.click(); }); return true; } if (type === 24) { var $fillWrap = $item.find('.fillBlanksChoose').first(); var $targets = $fillWrap.find('.textTarget'); var $wordSpans = $fillWrap.find('.blanksBox span[data-choose-name]'); if (!$fillWrap.length || !$targets.length || !$wordSpans.length) throw new Error('未找到选词填空控件,请手动作答'); var allFilledW = $targets.toArray().every(function (el) { return Boolean(el.dataset && String(el.dataset.chooseName || '').trim()); }); if (!isRedoMode() && allFilledW) return true; var wordOpts = $wordSpans.toArray().map(function (el) { var key = String(el.dataset.chooseName || $(el).attr('data-choose-name') || '').trim().toUpperCase(); var rawText = el.childNodes[0] && el.childNodes[0].nodeType === 3 ? el.childNodes[0].nodeValue : $(el).clone().find('i').remove().end().text(); return { key: key, text: String(rawText || '').trim() }; }); var $textClone = $fillWrap.find('.textContent').first().clone(); $textClone.find('.textTarget').each(function (i) { $(this).replaceWith(' [空' + (i + 1) + '] '); }); var fillBody = tidyQuestion($textClone.html() || '') || $textClone.text().replace(/\s+/g, ' ').trim(); var wQuestion = (question ? question + '\n' : '') + fillBody + '\n备选词库:\n' + wordOpts.map(function (o) { return o.key + '. ' + o.text; }).join('\n'); var wAnswer = await getAnswer(4, buildPrompt({ type: info.typeName, question: wQuestion, answer_format: '共' + $targets.length + '空,按空位顺序返回备选词库对应的选项字母,用' + ANSWER_SEPARATOR + '分隔(例如A' + ANSWER_SEPARATOR + 'B),不要返回空位编号,不要解释' })); var wParts = splitSequenceAnswer(wAnswer, $targets.length); if (wParts.length !== $targets.length) throw new Error('选词填空答案数量不匹配'); var chosenWords = wParts.map(function (part) { var p = part.trim(); var upper = p.toUpperCase(); var byKey = wordOpts.find(function (o) { return o.key === upper; }); if (byKey) return byKey; var byText = wordOpts.find(function (o) { return o.text === p; }); if (byText) return byText; var letterMatch = upper.match(/^([A-Z])(?:[.、=::\s]|$)/); if (letterMatch) return wordOpts.find(function (o) { return o.key === letterMatch[1]; }); return undefined; }); if (chosenWords.some(function (o) { return !o; })) throw new Error('选词填空答案匹配失败'); $targets.each(function (i) { this.innerText = chosenWords[i].text; this.dataset.chooseName = chosenWords[i].key; this.setAttribute('draggable', 'true'); }); var fillQid = $fillWrap.attr('data') || $item.attr('data'); var fillWin = $item[0].ownerDocument.defaultView; if (fillQid && fillWin && typeof fillWin.getFillinBlanksDataForQuestion === 'function') { fillWin.getFillinBlanksDataForQuestion(fillQid); } return true; } if (type === 11 || type === 13) { var $boxes = $item.find('.line_answer_ct .selectBox, .orderSelect .selectBox, .order_box, .thirdUlList .dept_select, .line_answer select, .sort_answer select, .sortQuesSelect select'); if (!$boxes.length) throw new Error('未找到连线或排序控件,请手动作答'); var readBoxValue = function (box) { if ($(box).is('select')) return String(box.value || '').trim(); var v = String($(box).find('p span[value]').first().attr('value') || '').trim(); return v === '-' ? '' : v; }; var selectedValues = $boxes.toArray().map(readBoxValue); var $savedAnswer = $item.find('input[name^="answer"]').not('[name^="answertype"]').first(); if (!isRedoMode() && (!$savedAnswer.length || $savedAnswer.val()) && selectedValues.every(Boolean) && (type !== 13 || new Set(selectedValues).size === $boxes.length)) return true; if (type === 13) { var sortItems = $item.find('.stem_answer').first().children('.clearfix').map(function () { var key = $(this).children('span').first().text().replace(/[、..\s]+/g, ''); var text = tidyQuestion($(this).children('div').first().html() || '') || ''; return key && text ? key + '=' + text : null; }).get(); if (sortItems.length) { question += '\n排序项目:\n' + sortItems.join('\n'); } else { var $sortContent = $item.clone(); $sortContent.find('select, input, script, style, .chosen-container, .orderSelect, .selectBox, .team_tit, h3.mark_name').remove(); question += '\n排序项目:\n' + (tidyQuestion($sortContent.html().replace(/<\/(?:li|p|div)>/gi, '\n')) || '').replace(/\s*\n\s*/g, '\n'); } } var groups = ['.firstUlList', '.secondUlList'].map(function (selector) { return $item.find(selector + ' > li').not('.groupTitile').map(function () { return { key: $(this).find('i').first().text().replace(/[、..\s]+$/g, ''), text: tidyQuestion($(this).find('div').first().html() || '') || '' }; }).get(); }); if (!groups[0].length || !groups[1].length) { var $lineCols = $item.find('.line_wid_400'); if ($lineCols.length >= 2) { groups = [0, 1].map(function (colIdx) { return $lineCols.eq(colIdx).find('.lineCt').map(function () { return { key: $(this).find('span').first().text().replace(/[、..\s]+$/g, ''), text: tidyQuestion($(this).find('div').first().html() || '') || '' }; }).get(); }); } } if (groups[0].length && groups[1].length) { question += '\n第一组数据:\n' + groups[0].map(function (item) { return item.key + '=' + item.text; }).join('\n'); question += '\n第二组数据:\n' + groups[1].map(function (item) { return item.key + '=' + item.text; }).join('\n'); } var options = $boxes.map(function (i) { return (i + 1) + ': ' + $(this).find('li[data], option[value]').map(function () { var key = $(this).attr('data') || this.value; if (!key || this.disabled) return null; var item = groups[1].find(function (item) { return item.key === key; }); return key + '=' + (item ? item.text : $(this).text().trim()); }).get().join('; '); }).get(); var answer = await getAnswer(4, buildPrompt({ type: info.typeName, question: question, options: options, answer_format: '按第一组项目或排序位置依次返回对应的选项值,用' + ANSWER_SEPARATOR + '分隔(例如A' + ANSWER_SEPARATOR + 'B),不要返回项目编号,不要解释' })); var parts = splitSequenceAnswer(answer, $boxes.length); if (parts.length !== $boxes.length) throw new Error('连线或排序答案数量不匹配'); var targets = $boxes.toArray().map(function (box, i) { var part = parts[i].trim(); var upper = part.toUpperCase(); var candidates = $(box).find('li[data], option[value]').toArray().filter(function (node) { return !node.disabled && Boolean($(node).attr('data') || node.value); }); var exact = candidates.find(function (node) { return String($(node).attr('data') || node.value).toUpperCase() === upper; }); if (exact) return exact; var matched = candidates.filter(function (node) { var key = $(node).attr('data') || node.value; var item = groups[1].find(function (item) { return item.key === key; }); return item && item.text === part; }); if (matched.length === 1) return matched[0]; var letterMatch = upper.match(/^([A-Z])(?:[.、=::\s]|$)/); if (letterMatch) { return candidates.find(function (node) { return String($(node).attr('data') || node.value).toUpperCase() === letterMatch[1]; }); } return undefined; }); if (targets.some(function (node) { return !node; })) throw new Error('连线或排序答案不匹配'); if (type === 13 && new Set(targets.map(function (node) { return node.value || $(node).attr('data'); })).size !== targets.length) { throw new Error('排序答案存在重复选项,请手动检查'); } var usedNativeSelect = false; targets.forEach(function (node) { if (node.tagName === 'OPTION') { usedNativeSelect = true; setQuizPracticeValue($(node.parentElement), node.value); } else { ($(node).find('a')[0] || node).click(); } }); var win = $item[0].ownerDocument.defaultView; var qid = $item.attr('data') || $item.find('.line_answer, .orderSelect').first().attr('data'); if (usedNativeSelect) { if (type === 11 && typeof win.setConnLineAnswer === 'function') { win.setConnLineAnswer.length > 0 ? (qid && win.setConnLineAnswer(qid)) : win.setConnLineAnswer(); } if (type === 13) { if (typeof win.setSortQuesAnswer === 'function') win.setSortQuesAnswer(); else if (qid && typeof win.setSortAnswer === 'function') win.setSortAnswer(qid); } } return true; } if (![2, 4, 17].includes(type)) throw new Error('无法识别题型,请手动作答'); var editors = getWorkTextEditors($item, type === 17); if (!editors.length) throw new Error('未找到可写入的答案编辑器,请手动作答'); if (!isRedoMode() && editors.every(function (editor) { return String(editor.get() || '').trim(); })) return true; var format = type === 17 ? '只返回符合题目语言要求的完整代码,保留缩进换行,不要Markdown代码围栏或解释' : type === 2 ? (editors.length > 1 ? '共' + editors.length + "空,按顺序用'" + ANSWER_SEPARATOR + "'分隔,直接返回纯文本答案,不要使用JSON格式或中括号" : '只返回纯文本答案,不要解释,不要使用JSON格式或中括号') : (editors.length > 1 ? '共' + editors.length + "个答题区域,按顺序用'" + ANSWER_SEPARATOR + "'分隔,直接返回纯文本答案,不要使用JSON格式或中括号" : '按题目要求完整作答,保留必要的步骤,直接返回纯文本答案,不要使用JSON格式或中括号'); var answer = await getAnswer(4, buildPrompt({ type: info.typeName, question: question, answer_format: format, preserveWhitespace: type === 17 })); if (!answer || /^(暂无答案|无答案)$/.test(answer.trim())) throw new Error('暂无答案'); var parts; if (type === 17) { parts = [answer.replace(/^\s*\x60\x60\x60[^\n]*\r?\n/, '').replace(/\r?\n\x60\x60\x60\s*$/, '')]; } else { parts = parseWorkTextAnswer(answer, editors.length, type === 2); } if (!Array.isArray(parts) || parts.length !== editors.length || parts.some(function (part) { return typeof part !== 'string' || !part.trim(); })) throw new Error('答案数量与输入区域不匹配'); for (var i = 0; i < editors.length; i++) { if (!await editors[i].set(parts[i])) throw new Error('答案写入失败'); } return true; } function runWorkQuestion($item, info, question, next) { return answerWorkQuestion($item, info, question).catch(function (error) { blockAutoSubmit(); logger(error && error.message || '答题失败,请手动检查', 'red'); return false; }).then(function (success) { next(success); return success; }); } function handleExtraWorkQuestion($item, next, meta) { var info = getWorkQuestionType($item); if (![11, 13, 17, 20, 24].includes(info.type)) return false; if (meta) { _currentQuestionMeta = { index: meta.index, total: meta.total, typeName: info.typeName }; } runWorkQuestion($item, info, getWorkQuestionText($item), function () { setTimeout(next, setting.time); }); return true; } function getPanelDocument() { var current = window; try { while (true) { if (current.document.querySelector('#ne-21box')) return current.document; if (current === current.parent) break; current = current.parent; } } catch (_) {} return document; } function initSwitchDefaults() { ['sub', 'force', 'examTurn', 'goodStudent', 'alterTitle', 'redo'].forEach(function (settingId) { if (localStorage.getItem('GPTJsSetting.' + settingId) === null) { localStorage.setItem('GPTJsSetting.' + settingId, setting[settingId] ? 'true' : 'false'); } }); if (localStorage.getItem('GPTJsSetting.fuzzyMatch') === null) { localStorage.setItem('GPTJsSetting.fuzzyMatch', 'true'); } } function showBox() { if (!setting.showBox) { initSwitchDefaults(); ensureAuth(); return; } if (getPanelDocument().querySelector('#ne-21box')) return; if (setting.showBox && getPanelDocument().querySelector('#ne-21notice') == undefined) { if (!document.getElementById('ne-21style')) { var styleEl = document.createElement('style'); styleEl.id = 'ne-21style'; styleEl.textContent = ` /* === Liquid Glass UI (iOS 26 style, neutral light glass) === */ #ne-21box{position:fixed;top:5%;right:16%;width:340px;z-index:99999;font-family:-apple-system,BlinkMacSystemFont,"SF Pro Text","Segoe UI","PingFang SC","Microsoft YaHei",sans-serif;font-size:13px;color:rgba(15,23,42,.86);background:linear-gradient(180deg,rgba(255,255,255,.62) 0%,rgba(241,245,249,.55) 100%);backdrop-filter:blur(22px) saturate(180%) brightness(1.04);-webkit-backdrop-filter:blur(22px) saturate(180%) brightness(1.04);border:1px solid rgba(255,255,255,.65);border-radius:22px;box-shadow:0 0 0 1px rgba(15,23,42,.09),0 24px 48px -12px rgba(15,23,42,.45),0 10px 26px -8px rgba(15,23,42,.3),inset 0 1px 0 rgba(255,255,255,.9),inset 0 -1px 0 rgba(15,23,42,.06);overflow:hidden;transition:opacity .25s ease,transform .25s ease;animation:ne21-in .4s cubic-bezier(.2,.9,.3,1) both;} @keyframes ne21-in{from{opacity:0;transform:translateY(-8px) scale(.98)}to{opacity:1;transform:none}} #ne-21box .ne21-header{position:relative;display:flex;align-items:center;justify-content:space-between;padding:12px 16px;background:linear-gradient(180deg,rgba(255,255,255,.72) 0%,rgba(248,250,252,.35) 100%);color:rgba(15,23,42,.92);border-bottom:1px solid rgba(15,23,42,.07);cursor:move;user-select:none;} #ne-21box .ne21-header::after{content:'';position:absolute;left:14px;right:14px;bottom:-1px;height:1px;background:linear-gradient(90deg,transparent,rgba(255,255,255,.85),transparent);pointer-events:none;} #ne-21box.ne21-collapsed .ne21-body{display:none;} #ne-21box.ne21-collapsed .ne21-header{border-bottom:none;} #ne-21box.ne21-collapsed .ne21-header::after{display:none;} #ne-21box .ne21-title{display:flex;align-items:center;gap:9px;font-weight:600;font-size:14px;letter-spacing:.3px;margin:0;color:inherit;} #ne-21box .ne21-dot{width:9px;height:9px;border-radius:50%;background:radial-gradient(circle at 32% 28%,rgba(255,255,255,.98),rgba(255,255,255,.5) 55%,rgba(15,23,42,.18) 100%);box-shadow:0 0 0 0 rgba(255,255,255,.7),inset 0 1px 1px rgba(255,255,255,.95);animation:ne21-pulse 2s infinite;flex-shrink:0;} @keyframes ne21-pulse{0%{box-shadow:0 0 0 0 rgba(255,255,255,.7),inset 0 1px 1px rgba(255,255,255,.95)}70%{box-shadow:0 0 0 8px rgba(255,255,255,0),inset 0 1px 1px rgba(255,255,255,.95)}100%{box-shadow:0 0 0 0 rgba(255,255,255,0),inset 0 1px 1px rgba(255,255,255,.95)}} #ne-21box #ne-21close, #ne-21box #ne-21pause{margin:0;width:24px;height:24px;padding:0;display:inline-flex;align-items:center;justify-content:center;font-size:0;line-height:1;color:rgba(15,23,42,.7);cursor:pointer;border:1px solid rgba(255,255,255,.65);border-radius:50%;background:rgba(255,255,255,.55);box-shadow:0 0 0 1px rgba(15,23,42,.06),inset 0 1px 0 rgba(255,255,255,.8),0 1px 2px rgba(15,23,42,.08);transition:background .2s,color .2s,transform .15s;user-select:none;} #ne-21box #ne-21close:hover, #ne-21box #ne-21pause:hover{background:rgba(255,255,255,.78);color:rgba(15,23,42,.92);box-shadow:0 0 0 1px rgba(15,23,42,.08),inset 0 1px 0 rgba(255,255,255,.9),0 1px 2px rgba(15,23,42,.1);} #ne-21box #ne-21close:active, #ne-21box #ne-21pause:active{transform:scale(.92);} #ne-21box.ne21-paused .ne21-dot{background:#f59e0b;box-shadow:0 0 0 3px rgba(245,158,11,.24);animation:none;} #ne-21box.ne21-paused #ne-21pause{background:rgba(245,158,11,.18);border-color:rgba(245,158,11,.5);color:#b45309;} #ne-21box.ne21-paused #ne-21pause:hover{background:rgba(245,158,11,.28);color:#92400e;} #ne-21box #ne-21paused-banner{display:flex;align-items:center;justify-content:space-between;gap:8px;margin:10px 16px 0;padding:8px 10px;border-radius:12px;background:rgba(245,158,11,.14);border:1px solid rgba(245,158,11,.36);color:#b45309;font-size:12px;line-height:1.45;box-shadow:inset 0 1px 0 rgba(255,255,255,.55);} #ne-21box.ne21-collapsed #ne-21paused-banner{margin:10px 14px 12px;} #ne-21box #ne-21paused-banner[hidden]{display:none;} #ne-21box #ne-21paused-banner .ne21-paused-text{flex:1;min-width:0;font-weight:500;} #ne-21box #ne-21paused-resume{flex-shrink:0;padding:4px 9px;font-size:11px;font-weight:600;border-radius:10px;cursor:pointer;border:1px solid rgba(245,158,11,.45);background:rgba(255,255,255,.78);color:#b45309;transition:background .15s,transform .15s;} #ne-21box #ne-21paused-resume:hover{background:rgba(255,255,255,.95);color:#92400e;} #ne-21box #ne-21paused-resume:active{transform:scale(.96);} #ne-21box .ne21-actions{display:flex;align-items:center;gap:8px;flex-shrink:0;} #ne-21box .ne21-kbd{display:block;max-width:76px;overflow:hidden;text-overflow:ellipsis;padding:3px 8px;font-size:10.5px;font-weight:500;letter-spacing:.2px;color:rgba(15,23,42,.66);background:rgba(255,255,255,.55);border:1px solid rgba(255,255,255,.72);border-radius:8px;box-shadow:0 0 0 1px rgba(15,23,42,.06),inset 0 1px 0 rgba(255,255,255,.85),0 1px 2px rgba(15,23,42,.06);user-select:none;cursor:default;font-family:"SF Mono","Cascadia Code",Consolas,Menlo,monospace;line-height:1;white-space:nowrap;} #ne-21box .ne21-kbd b{font-family:-apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;font-weight:600;color:rgba(15,23,42,.78);} #ne-21box .ne21-body{padding:14px 16px 16px;} #ne-21box #ne-21notice{border-top:none!important;margin:0 0 6px!important;overflow:visible;} #ne-21box .ne21-uid{display:flex;align-items:center;gap:6px;color:rgba(15,23,42,.62);font-size:12px;margin-bottom:10px;padding:8px 12px;background:rgba(255,255,255,.5);border:1px solid rgba(255,255,255,.7);border-radius:12px;box-shadow:0 0 0 1px rgba(15,23,42,.05),inset 0 1px 0 rgba(255,255,255,.75),0 1px 2px rgba(15,23,42,.05);} #ne-21box .ne21-uid b{color:rgba(15,23,42,.92);font-weight:600;} #ne-21box .ne21-uid-missing{flex-direction:column;align-items:flex-start;gap:4px;line-height:1.6;} #ne-21box .ne21-row{display:flex;gap:8px;align-items:center;} #ne-21box .ne21-btn{display:inline-flex;align-items:center;justify-content:center;padding:7px 14px;font-size:12px;font-weight:500;border-radius:14px;cursor:pointer;border:1px solid rgba(255,255,255,.7);transition:transform .15s,box-shadow .2s,background .2s,color .2s;white-space:nowrap;} #ne-21box .ne21-btn-primary{color:rgba(15,23,42,.92);background:rgba(255,255,255,.72);box-shadow:0 0 0 1px rgba(15,23,42,.07),inset 0 1px 0 rgba(255,255,255,.95),inset 0 -6px 12px -6px rgba(15,23,42,.08),0 4px 10px -2px rgba(15,23,42,.22);} #ne-21box .ne21-btn-primary:hover{transform:translateY(-1px);background:rgba(255,255,255,.88);box-shadow:0 0 0 1px rgba(15,23,42,.09),inset 0 1px 0 rgba(255,255,255,1),inset 0 -6px 12px -6px rgba(15,23,42,.1),0 6px 14px -2px rgba(15,23,42,.28);} #ne-21box .ne21-btn-secondary{color:rgba(15,23,42,.78);background:rgba(255,255,255,.45);box-shadow:0 0 0 1px rgba(15,23,42,.06),inset 0 1px 0 rgba(255,255,255,.75),0 1px 2px rgba(15,23,42,.06);} #ne-21box .ne21-btn-secondary:hover{background:rgba(255,255,255,.65);color:rgba(15,23,42,.92);box-shadow:0 0 0 1px rgba(15,23,42,.08),inset 0 1px 0 rgba(255,255,255,.85),0 2px 4px rgba(15,23,42,.08);} #ne-21box .ne21-btn:active{transform:translateY(0) scale(.98);} #ne-21box .ne21-btn:disabled{opacity:.5;cursor:not-allowed;transform:none;} #ne-21box #modelSelect{flex:1;min-width:0;padding:7px 10px;font-size:12px;border-radius:14px;border:1px solid rgba(255,255,255,.7);background:rgba(255,255,255,.55);color:rgba(15,23,42,.86);cursor:pointer;outline:none;box-shadow:0 0 0 1px rgba(15,23,42,.06),inset 0 1px 0 rgba(255,255,255,.8);transition:background .2s,box-shadow .2s;} #ne-21box #modelSelect:hover{background:rgba(255,255,255,.7);} #ne-21box #modelSelect:focus{background:rgba(255,255,255,.75);box-shadow:0 0 0 1px rgba(15,23,42,.08),inset 0 1px 0 rgba(255,255,255,.85),0 0 0 4px rgba(15,23,42,.1);} #ne-21box .ne21-select{padding:5px 8px;font-size:12px;border-radius:10px;border:1px solid rgba(255,255,255,.65);background:rgba(255,255,255,.5);color:rgba(15,23,42,.86);cursor:pointer;outline:none;min-width:80px;flex-shrink:0;box-shadow:0 0 0 1px rgba(15,23,42,.05),inset 0 1px 0 rgba(255,255,255,.75);transition:background .2s,box-shadow .2s;} #ne-21box .ne21-select:hover{background:rgba(255,255,255,.7);} #ne-21box .ne21-select:focus{background:rgba(255,255,255,.72);box-shadow:0 0 0 1px rgba(15,23,42,.08),inset 0 1px 0 rgba(255,255,255,.82),0 0 0 3px rgba(15,23,42,.06);} #ne-21box #userInfo{margin:10px 0 0;padding:10px 12px;background:rgba(255,255,255,.5);border:1px solid rgba(255,255,255,.7);border-radius:12px;box-shadow:0 0 0 1px rgba(15,23,42,.05),inset 0 1px 0 rgba(255,255,255,.75);font-size:12px;color:rgba(15,23,42,.66);line-height:1.6;overflow:hidden;} #ne-21box #userInfo:empty{display:none;} #ne-21box #userInfo b{color:rgba(15,23,42,.9);font-weight:600;} #ne-21box #moreSettings{padding:4px 14px;background:rgba(255,255,255,.42);border:1px solid rgba(255,255,255,.65);border-radius:14px;box-shadow:0 0 0 1px rgba(15,23,42,.05),inset 0 1px 0 rgba(255,255,255,.7);margin:10px 0 0;} #ne-21box #moreSettings label{display:flex;flex-direction:row-reverse;align-items:center;justify-content:space-between;margin:0;padding:8px 2px;font-size:12px;color:rgba(15,23,42,.78);cursor:pointer;user-select:none;line-height:1.4;} #ne-21box #moreSettings label + label{border-top:1px dashed rgba(15,23,42,.1);} #ne-21box #moreSettings input[type=checkbox]{appearance:none;-webkit-appearance:none;width:34px;height:20px;border:1px solid rgba(15,23,42,.08);border-radius:20px;cursor:pointer;position:relative;transition:background .25s,box-shadow .25s;background:rgba(15,23,42,.16);box-shadow:inset 0 1px 2px rgba(15,23,42,.12);margin:0 0 0 10px;flex-shrink:0;} #ne-21box #moreSettings input[type=checkbox]::before{content:'';position:absolute;top:1px;left:1px;width:16px;height:16px;border-radius:50%;background:linear-gradient(180deg,rgba(255,255,255,1),rgba(255,255,255,.85));box-shadow:0 1px 3px rgba(15,23,42,.25),inset 0 1px 0 rgba(255,255,255,1);transition:transform .25s cubic-bezier(.2,.9,.3,1);} #ne-21box #moreSettings input[type=checkbox]:hover{background:rgba(15,23,42,.24);} #ne-21box #moreSettings input[type=checkbox]:checked{background:rgba(255,255,255,.78);border-color:rgba(15,23,42,.1);box-shadow:inset 0 1px 0 rgba(255,255,255,.95),inset 0 -2px 4px rgba(15,23,42,.08),0 0 0 1px rgba(15,23,42,.06);} #ne-21box #moreSettings input[type=checkbox]:checked:hover{background:rgba(255,255,255,.92);} #ne-21box #moreSettings input[type=checkbox]:checked::before{transform:translateX(14px);} #ne-21box #moreSettings p{display:none;} #ne-21box .ne21-shortcut-controls{display:flex;align-items:center;gap:6px;min-width:0;} #ne-21box .ne21-shortcut-controls input{width:112px;min-width:0;box-sizing:border-box;} #ne-21box .ne21-shortcut-controls button{padding:5px 7px;} #ne-21box #ne21-shortcut-hint{display:block;font-size:11px;line-height:1.5;color:#64748b;padding:0 2px 8px;} #ne-21box #ne21-rate-warning{display:block;font-size:11px;line-height:1.5;color:#c2410c;background:rgba(234,88,12,.1);border:1px solid rgba(234,88,12,.25);border-radius:8px;padding:6px 8px;margin:0 0 8px;} #ne-21box #ne21-rate-warning[hidden]{display:none;} #ne-21box #ne-21thinking{display:none!important;} @keyframes ne21-spin{to{transform:rotate(360deg)}} @keyframes ne21-dot{0%,80%,100%{transform:scale(.5);opacity:.4}40%{transform:scale(1);opacity:1}} #ne-21box #ne-21log .ne21-log-spinner{display:inline-block;width:9px;height:9px;margin-right:5px;border:1.5px solid rgba(15,23,42,.18);border-top-color:rgba(15,23,42,.7);border-radius:50%;vertical-align:-1px;animation:ne21-spin .8s linear infinite;} #ne-21box #ne-21log .ne21-log-dots{display:inline-flex;gap:2px;margin-left:3px;vertical-align:1px;} #ne-21box #ne-21log .ne21-log-dots i{width:3px;height:3px;border-radius:50%;background:currentColor;opacity:.65;animation:ne21-dot 1.2s infinite ease-in-out both;} #ne-21box #ne-21log .ne21-log-dots i:nth-child(2){animation-delay:.16s;} #ne-21box #ne-21log .ne21-log-dots i:nth-child(3){animation-delay:.32s;} #ne-21box #ne-21log{max-height:140px;overflow-y:auto;overflow-anchor:none;margin:12px 0 0;padding:10px 12px;background:rgba(15,23,42,.06);border:1px solid rgba(255,255,255,.55);border-radius:14px;box-shadow:0 0 0 1px rgba(15,23,42,.06),inset 0 1px 0 rgba(255,255,255,.6),inset 0 0 16px rgba(15,23,42,.06);font-family:"SF Mono","Cascadia Code",Consolas,Menlo,monospace;font-size:11px;line-height:1.6;color:rgba(15,23,42,.78);} #ne-21box #ne-21log:empty{display:none;} #ne-21box #ne-21log::-webkit-scrollbar{width:5px;} #ne-21box #ne-21log::-webkit-scrollbar-thumb{background:rgba(15,23,42,.2);border-radius:4px;} #ne-21box #ne-21log::-webkit-scrollbar-thumb:hover{background:rgba(15,23,42,.32);} #ne-21box #ne-21log p{margin:0;padding:2px 0;word-break:break-all;} #ne-21box #ne-21log hr{display:none;} #ne-21box #ne-21log .ne21-time{color:rgba(15,23,42,.4);margin-right:6px;} #ne-21box #ne-21log-latest{display:block;margin:6px 0 0 auto;padding:4px 10px;font-size:11px;} #ne-21box #ne-21log-latest[hidden]{display:none;} `; document.head.appendChild(styleEl); } var box_html = `

ChatGPT 学习通助手

F9 显隐
AI 思考中
`; $(box_html).appendTo('body'); refreshPanelShortcut(document); (function () { var $box = $('#ne-21box'); try { var savedPos = localStorage.getItem('GPTJsSetting.boxPosition'); if (savedPos) { var pos = JSON.parse(savedPos); if (pos && typeof pos.left === 'number' && typeof pos.top === 'number') { var vw = window.innerWidth, vh = window.innerHeight; var w = $box.outerWidth() || 340; var nx = Math.max(40 - w, Math.min(pos.left, vw - 40)); var ny = Math.max(0, Math.min(pos.top, vh - 40)); $box.css({ left: nx + 'px', top: ny + 'px', right: 'auto' }); } } } catch (_) {} if (localStorage.getItem('GPTJsSetting.boxCollapsed') === 'true') { $box.addClass('ne21-collapsed'); $('#ne-21close').html('').attr('aria-label', '展开'); } if (localStorage.getItem('GPTJsSetting.showBox') === 'hide') { $box.css('display', 'none'); } })(); function setScriptPaused(nextPaused) { localStorage.setItem('GPTJsSetting.isPaused', nextPaused ? 'true' : 'false'); updatePausedUI(document, nextPaused); if (nextPaused) { try { logger('脚本已暂停运行', 'orange'); } catch (_) { } } else { try { logger('脚本已恢复运行', 'green'); } catch (_) { } } } $('#ne-21box').on('mousedown', '#ne-21pause', function (e) { e.stopPropagation(); }).on('click', '#ne-21pause', function (e) { e.stopPropagation(); var isPaused = localStorage.getItem('GPTJsSetting.isPaused') === 'true'; setScriptPaused(!isPaused); }).on('click', '#ne-21paused-resume', function (e) { e.stopPropagation(); setScriptPaused(false); }); updatePausedUI(document, localStorage.getItem('GPTJsSetting.isPaused') === 'true'); $('#ne-21close').on('mousedown', function (e) { e.stopPropagation(); }).on('click', function (e) { e.stopPropagation(); var collapsed = $('#ne-21box').toggleClass('ne21-collapsed').hasClass('ne21-collapsed'); $(this).html(collapsed ? '' : ''); $(this).attr('aria-label', collapsed ? '展开' : '收起'); try { localStorage.setItem('GPTJsSetting.boxCollapsed', collapsed ? 'true' : 'false'); } catch (_) {} }); (function () { var $box = $('#ne-21box'); var $header = $box.find('.ne21-header'); var dragging = false, startX = 0, startY = 0, startLeft = 0, startTop = 0; $header.on('mousedown', function (e) { if (e.which !== 1) return; if ($(e.target).closest('#ne-21close, #ne-21pause').length) return; dragging = true; var rect = $box[0].getBoundingClientRect(); startX = e.clientX; startY = e.clientY; startLeft = rect.left; startTop = rect.top; $box.css({ left: startLeft + 'px', top: startTop + 'px', right: 'auto' }); $('body').css('user-select', 'none'); e.preventDefault(); }); $(document).on('mousemove.ne21drag', function (e) { if (!dragging) return; var nx = startLeft + (e.clientX - startX); var ny = startTop + (e.clientY - startY); var w = $box.outerWidth(); var vw = window.innerWidth; var vh = window.innerHeight; nx = Math.max(40 - w, Math.min(nx, vw - 40)); ny = Math.max(0, Math.min(ny, vh - 40)); $box.css({ left: nx + 'px', top: ny + 'px' }); }).on('mouseup.ne21drag', function () { if (!dragging) return; dragging = false; $('body').css('user-select', ''); try { var rect = $box[0].getBoundingClientRect(); localStorage.setItem('GPTJsSetting.boxPosition', JSON.stringify({ left: rect.left, top: rect.top })); } catch (_) {} }); })(); (function () { var moreSettings = document.getElementById('moreSettings'); var userInfo = document.getElementById('userInfo'); if (!moreSettings || !userInfo) return; var isSettingsVisible = false; $('#ne-21box').on('click', '#moreSettingsBtn', function () { userInfo.style.display = isSettingsVisible ? 'block' : 'none'; moreSettings.style.display = isSettingsVisible ? 'none' : 'block'; this.textContent = isSettingsVisible ? '设置' : '返回'; isSettingsVisible = !isSettingsVisible; }); var shortcutInput = document.getElementById('GPTJsSetting.panelShortcut'); var shortcutHint = document.getElementById('ne21-shortcut-hint'); shortcutInput.addEventListener('keydown', function (event) { if (event.key === 'Tab') return; event.preventDefault(); event.stopPropagation(); if (event.repeat || event.isComposing) return; if (event.key === 'Escape') { refreshPanelShortcut(document); shortcutInput.blur(); return; } if (/^(Control|Alt|Shift|Meta)$/.test(event.key)) return; if (!/^(F([1-9]|1[0-2])|Key[A-Z]|Digit[0-9])$/.test(event.code) || (!/^F\d+$/.test(event.code) && !event.ctrlKey && !event.altKey && !event.metaKey)) { shortcutHint.textContent = '请用 F1–F12 或 Ctrl/Alt/Meta + 字母/数字。'; return; } var shortcut = { code: event.code, ctrlKey: event.ctrlKey, altKey: event.altKey, shiftKey: event.shiftKey, metaKey: event.metaKey }; localStorage.setItem('GPTJsSetting.panelShortcut', JSON.stringify(shortcut)); refreshPanelShortcut(document); shortcutHint.textContent = '已保存:' + formatPanelShortcut(shortcut); }); document.getElementById('ne21-shortcut-reset').addEventListener('click', function () { localStorage.removeItem('GPTJsSetting.panelShortcut'); refreshPanelShortcut(document); shortcutHint.textContent = '已恢复 F9'; }); initSwitchDefaults(); ['sub', 'force', 'examTurn', 'goodStudent', 'alterTitle', 'redo', 'fuzzyMatch'].forEach(function (settingId) { var checkbox = document.getElementById('GPTJsSetting.' + settingId); if (!checkbox) return; checkbox.addEventListener('change', updateLocalStorage); checkbox.checked = localStorage.getItem('GPTJsSetting.' + settingId) === 'true'; }); var rateSelect = document.getElementById('GPTJsSetting.rate'); if (rateSelect) { var initialRate = getRate(); rateSelect.value = String(initialRate); updateRateWarning(document, initialRate); rateSelect.addEventListener('change', function () { var nextRate = parseFloat(rateSelect.value); localStorage.setItem('GPTJsSetting.rate', rateSelect.value); updateRateWarning(document, nextRate); if (isFinite(nextRate) && nextRate > 1) { logger('已切换为 ' + nextRate + '× 倍速:高倍速可能导致播放进度重置、无法完成任务点,建议使用 1×', 'orange'); } else { logger('已恢复默认 1× 倍速', 'green'); } applyLiveRate(); }); } var timeInput = document.getElementById('GPTJsSetting.time'); if (timeInput) { var savedTime = localStorage.getItem('GPTJsSetting.time'); timeInput.value = (savedTime !== null && isFinite(parseFloat(savedTime))) ? savedTime : String((setting.time || 2500) / 1000); timeInput.addEventListener('change', function () { var v = parseFloat(timeInput.value); if (!isFinite(v) || v < 0) v = 0; if (v > 60) v = 60; timeInput.value = String(v); localStorage.setItem('GPTJsSetting.time', String(v)); setting.time = v * 1000; }); } })(); } let _u = [getCk('_uid'), getCk('UID')].find(value => /^\d+$/.test(value || '') && Number(value) > 0 && Number(value) <= 2147483647) || ''; $('#ne-21notice').html(`
${_u ? '学习通账号 UID:' + _u + '' : '未获取到学习通 UID仍可点击充值前往充值页,页内有客服联系方式。'}
`); $('#ne21-recharge').on('click', function () { openRechargePage(_u); }); var CACHE_KEY_MODELS = 'GPTJsSetting.cachedModels'; var cachedModels = localStorage.getItem(CACHE_KEY_MODELS); if (cachedModels) { $('#modelSelect').html(cachedModels); } restoreSelectedModel(); $('#modelSelect').off('change.gptjsModel').on('change.gptjsModel', function () { localStorage.setItem('GPTJsSetting.model', $(this).val()); logger('已切换模型:' + $(this).find('option:selected').text() + ',下一题起生效', 'green'); }); updateAuthPanel(cachedModels); } function restoreSelectedModel() { var $select = $('#modelSelect', getPanelDocument()); if (!$select.length) return; var saved = localStorage.getItem('GPTJsSetting.model'); var hasSaved = !!saved && $select.find('option').filter(function () { return this.value === saved; }).length > 0; if (hasSaved) { $select.val(saved); return; } var first = $select.find('option').first().val(); if (!first) return; $select.val(first); if (saved !== first) localStorage.setItem('GPTJsSetting.model', first); } function getSelectedModel() { var saved = localStorage.getItem('GPTJsSetting.model'); if (saved) return saved; try { return $('#modelSelect', getPanelDocument()).val() || 'GPT-3.5'; } catch (_) { return 'GPT-3.5'; } } var LEARNING_ACCOUNT_STORAGE_KEY = 'GPTJsSetting.lastLearningAccount'; function getLearningAccountId() { return [getCk('_uid'), getCk('UID')].find(function (value) { return /^\d+$/.test(value || '') && Number(value) > 0 && Number(value) <= 2147483647; }) || ''; } function openRechargePage(learningAccountId) { var url = _host + (learningAccountId ? '?uid=' + encodeURIComponent(learningAccountId) : ''); window.open(url, '_blank', 'noopener,noreferrer'); } function showLearningAccountChangeNotice(learningAccountId) { var url = _host + (learningAccountId ? '?uid=' + encodeURIComponent(learningAccountId) : ''); logger('检测到您已更换学习通账号,积分按学习通账号同步。如有疑问请前往充值页联系售后。', 'orange'); } function checkLearningAccountChange(learningAccountId) { if (!learningAccountId) return; var previousLearningAccountId = String(GM_getValue(LEARNING_ACCOUNT_STORAGE_KEY, '') || ''); if (previousLearningAccountId === learningAccountId) return; GM_setValue(LEARNING_ACCOUNT_STORAGE_KEY, learningAccountId); if (previousLearningAccountId) showLearningAccountChangeNotice(learningAccountId); } function updateAuthPanel(cachedModels) { var CACHE_KEY_MODELS = 'GPTJsSetting.cachedModels'; if (ensureAuth()) { _authPromise.then(function (res) { var obj = {}; try { obj = $.parseJSON(res.response) || {}; } catch (e) {} var data = obj.data || {}; var notice = data.notice || ''; var score = (data.score !== undefined && data.score !== null) ? data.score : '-'; checkLearningAccountChange(res.learningAccountId); $('#userInfo').html(notice + "积分余额:" + score); if (data.models && data.models !== cachedModels) { localStorage.setItem(CACHE_KEY_MODELS, data.models); $('#modelSelect').html(data.models); restoreSelectedModel(); } }).catch(function (error) { var body = GptRequestGuard.errorBody(error); var message = body.message || error.message || '暂时无法获取账号信息,请稍后重试。'; var $retry = $('').css({ marginTop: '8px' }); $('#userInfo').empty().append($('
').text(message)).append($retry); $retry.on('click', function () { $retry.prop('disabled', true); _authPromise = requestAuth(_host); updateAuthPanel(cachedModels); }); }); } } var _ne21LogColorMap = { red: '#dc2626', green: '#059669', blue: '#2563eb', yellow: '#ca8a04', orange: '#ea580c', purple: '#7c3aed', pink: '#db2777', gray: '#64748b', grey: '#64748b' } function getLogScrollState(log) { if (log._ne21ScrollState) return log._ne21ScrollState var state = { follow: true, hasNew: false, lastTop: log.scrollTop, latest: null } log._ne21ScrollState = state function refreshButton() { var button = log.ownerDocument.getElementById('ne-21log-latest') if (!button) return button.hidden = state.follow button.textContent = state.hasNew ? '有新提示 · 回到最新日志' : '回到最新日志' } function pauseFollow() { if (!state.follow) return state.follow = false refreshButton() } state.refreshButton = refreshButton state.resume = function () { state.follow = true state.hasNew = false if (state.latest && state.latest.parentNode === log && state.latest !== log.lastChild) log.appendChild(state.latest) if (log.clientHeight > 0) log.scrollTop = log.scrollHeight state.lastTop = log.scrollTop refreshButton() } log.addEventListener('wheel', function (event) { if (event.deltaY < 0 && log.scrollHeight > log.clientHeight) { pauseFollow() } }, { passive: true }) log.addEventListener('scroll', function () { var curTop = log.scrollTop if (log.clientHeight === 0 || curTop === state.lastTop) return var prevTop = state.lastTop state.lastTop = curTop if (curTop < prevTop - 1) { pauseFollow() return } if (curTop > prevTop && log.scrollHeight - log.clientHeight - curTop <= 12) { if (!state.follow || state.hasNew) { state.follow = true state.hasNew = false refreshButton() } } }, { passive: true }) var button = log.ownerDocument.getElementById('ne-21log-latest') if (button) button.addEventListener('click', state.resume) var view = log.ownerDocument.defaultView if (view && view.ResizeObserver) { new view.ResizeObserver(function () { if (state.follow && log.clientHeight > 0) state.resume() }).observe(log) } return state } function followLatestLog(log, entry) { var state = getLogScrollState(log) state.latest = entry if (state.follow) state.resume() else { state.hasNew = true state.refreshButton() } } function clearLogEntries(message) { var log = getPanelDocument().getElementById('ne-21log') if (!log) return log.textContent = message || '' var state = getLogScrollState(log) state.latest = null state.resume() } function logger(str, color) { var _time = new Date().toLocaleTimeString() var c = (_ne21LogColorMap || {})[color] || color || '#334155' var $p = $('

[' + _time + ']' + str + '

') var log = getPanelDocument().getElementById('ne-21log') if (log) { getLogScrollState(log) $(log).append($p) followLatestLog(log, $p[0]) } return $p } function updateLogEntry($p, str, color) { if (!$p || !$p.length) return var log = $p[0].parentNode if (log && log.id === 'ne-21log') getLogScrollState(log) var c = _ne21LogColorMap[color] || color || '#334155' $p.find('.ne21-msg').css('color', c).html(str) if (log && log.id === 'ne-21log') followLatestLog(log, $p[0]) } function escapeLogText(text) { var escape = function (s) { return $('
').text(s).html().replace(/"/g, '"') } return String(text == null ? '' : text).split(/(]*>)/i).map(function (part, i) { if (i % 2 === 0) return escape(part) var m = part.match(/\bsrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i) var url = m ? (m[1] || m[2] || m[3] || '') : '' return url ? '' : '[图片]' }).join('') } function appendAnswerToTitle($title, answer) { if (!$title || !$title.length) return $title.append($('

').css('white-space', 'pre-wrap').text(answer == null ? '' : String(answer))) } function getStr(str, start, end) { let res = str.match(new RegExp(`${start}(.*?)${end}`)) return res ? res[1] : null } function getTaskParams(doc) { try { var _iframeScripts = (doc || _d).scripts, _p = null; for (let i = 0; i < _iframeScripts.length; i++) { if (_iframeScripts[i].innerHTML.indexOf('mArg = "";') != -1 && _iframeScripts[i].innerHTML.indexOf('==UserScript==') == -1) { _p = getStr(_iframeScripts[i].innerHTML.replace(/\s/g, ""), 'try{mArg=', ';}catch'); return _p } } return _p } catch (e) { return null } } function getCk(name) { return document.cookie.match(`(?:^|;\\s*)${name}=([^;]*)`)?.pop(); } function autoLogin() { logger('用户已设置自动登录', 'green') if (setting.phone.length <= 0 || setting.password.length <= 0) { logger('用户未设置登录信息', 'red') return } setTimeout(() => { $('#phone').val(setting.phone) $('#pwd').val(setting.password) $('#loginBtn').click() }, 3000) } function getStudyWindow() { var current = _w; try { while (current) { if (current.location.pathname.includes('/mycourse/studentstudy')) return current; if (current === current.parent) break; current = current.parent; } } catch (_) {} return _w.top; } function getStudyCardsDocument(studyWindow) { try { if (studyWindow.location.pathname.includes('/knowledge/cards')) return studyWindow.document; for (var i = 0; i < studyWindow.frames.length; i++) { var doc = getStudyCardsDocument(studyWindow.frames[i]); if (doc) return doc; } } catch (_) {} return null; } function isEmptyStudyPage(doc) { if (!doc || doc.readyState !== 'complete') return false; var params = getTaskParams(doc); try { var parsed = JSON.parse(params); if (parsed && Array.isArray(parsed.attachments)) { return parsed.attachments.length === 0; } } catch (_) {} return !!doc.querySelector('.ans-cc') && !doc.querySelector('.ans-attach-ct, .ans-job-ct, .chapter-item'); } function scheduleStudyNavigation(studyWindow, navigate) { var doc = studyWindow.document; var cardsDoc = getStudyCardsDocument(studyWindow); var chapterId = doc.querySelector('.posCatalog_active')?.id || ''; var tabSelector = '#prev_tab > li.active, .prev_ul > li.active, #prevTabBox > li.active, span.currents'; var activeTab = doc.querySelector(tabSelector); var pending = studyWindow._gptJsNextPagePending; if (pending && pending.cardsDoc === cardsDoc && pending.chapterId === chapterId && pending.activeTab === activeTab) return; pending = { cardsDoc: cardsDoc, chapterId: chapterId, activeTab: activeTab }; studyWindow._gptJsNextPagePending = pending; function release() { if (studyWindow._gptJsNextPagePending === pending) studyWindow._gptJsNextPagePending = null; } studyWindow.setTimeout(function run() { if (studyWindow.document !== doc || getStudyCardsDocument(studyWindow) !== cardsDoc || (doc.querySelector('.posCatalog_active')?.id || '') !== chapterId || doc.querySelector(tabSelector) !== activeTab) { release(); return; } if (localStorage.getItem('GPTJsSetting.isPaused') === 'true') { studyWindow.setTimeout(run, 1000); return; } try { if (!navigate()) release(); } catch (error) { release(); logger('自动切换失败:' + error.message, 'red'); } }, 2000); } function toNext(noTasks) { var studyWindow = getStudyWindow(); if (_l.pathname.includes('/knowledge/cards') && getStudyCardsDocument(studyWindow) !== _d) return; if (localStorage.getItem('GPTJsSetting.isPaused') === 'true') { setTimeout(function () { toNext(noTasks); }, 3000); return; } var courseList = noTasks === true || setting.review || !setting.work ? Promise.resolve(null) : refreshCourseList().catch(function (error) { logger(error.message + ',使用页面目录继续处理', 'orange'); return studyWindow.document.querySelector('#coursetree'); }); courseList.then((res) => { if (_l.pathname.includes('/knowledge/cards') && getStudyCardsDocument(studyWindow) !== _d) return; function detectSubTabPosition() { try { var selectors = ['#prev_tab > li', '.prev_ul > li', '#prevTabBox > li']; for (var i = 0; i < selectors.length; i++) { var nodes = studyWindow.document.querySelectorAll(selectors[i]); if (!nodes || nodes.length === 0) continue; var tabs = Array.prototype.slice.call(nodes); var activeIdx = -1; for (var j = 0; j < tabs.length; j++) { if (tabs[j].classList && tabs[j].classList.contains('active')) { activeIdx = j; break; } } if (activeIdx === -1) continue; return { activeIndex: activeIdx, total: tabs.length, hasNext: activeIdx < tabs.length - 1, tabs: tabs }; } var currents = studyWindow.document.querySelector('span.currents'); if (currents) { var nextSibs = []; var sib = currents.nextElementSibling; while (sib) { if (sib.tagName === 'SPAN') nextSibs.push(sib); sib = sib.nextElementSibling; } if (nextSibs.length > 0) { return { activeIndex: 0, total: nextSibs.length + 1, hasNext: true, tabs: [currents].concat(nextSibs) }; } } } catch (e) {} return null; } function clickNextPageBtn() { clearLogEntries() try { studyWindow._gptJsJumpAllowed = true; } catch (_) {} var nextBtn = studyWindow.document.querySelector('#mainid .prev_next.next') if (nextBtn) { nextBtn.click(); return true } var sub = detectSubTabPosition(); if (sub && sub.hasNext && sub.tabs) { sub.tabs[sub.activeIndex + 1].click(); return true; } logger('未找到本课时下一页入口,等待页面加载', 'orange'); return false } function clickNextChapterBtn() { clearLogEntries() try { studyWindow._gptJsJumpAllowed = true; } catch (_) {} var nextBtn = studyWindow.document.querySelector('#mainid .prev_next.next') if (nextBtn) { nextBtn.click(); return true } var focusBtn = studyWindow.document.querySelector('#prevNextFocusNext') if (focusBtn) { focusBtn.click(); return true } logger('未找到下一章节入口,本次不切换', 'orange'); return false } var sub = detectSubTabPosition() if (sub && sub.hasNext) { logger('当前课时存在未完成页面(' + (sub.activeIndex + 1) + '/' + sub.total + '),准备切换到下一页', 'blue') scheduleStudyNavigation(studyWindow, clickNextPageBtn) return } if (noTasks === true || setting.review || !setting.work) { logger(noTasks === true ? '当前页面无任务点,准备切换到下一章节' : '本课时已无未完成页面,准备切换到下一章节', 'blue') scheduleStudyNavigation(studyWindow, clickNextChapterBtn) return } let _t = [] $.each($(res).find('li'), (_, t) => { let curid = $(t).find('.posCatalog_select').attr('id'), status = $(t).find('.prevHoverTips').text(), name = $(t).find('.posCatalog_name').attr('title'); if (curid && curid.indexOf('cur') != -1) { _t.push({ 'curid': curid, 'status': status, 'name': name }) } }) let _curChaterId = $('#coursetree', studyWindow.document).find('.posCatalog_active').attr('id') let _curIndex = _t.findIndex((item) => item['curid'] == _curChaterId) if (_curIndex < 0) { logger('课程目录未能定位当前章节,尝试页面下一节入口', 'orange') scheduleStudyNavigation(studyWindow, clickNextChapterBtn) return } for (_curIndex; _curIndex < _t.length - 1; _curIndex++) { if (_t[_curIndex]['status'].indexOf('待完成') != -1) { var subAgain = detectSubTabPosition() if (subAgain && subAgain.hasNext) { logger('兜底检测到本课时仍有未完成页面(' + (subAgain.activeIndex + 1) + '/' + subAgain.total + '),切换到下一页', 'blue') scheduleStudyNavigation(studyWindow, clickNextPageBtn) return } } let t = _t[_curIndex + 1] if (t['status'].indexOf('待完成') != -1) { scheduleStudyNavigation(studyWindow, function () { var clicked = clickNextChapterBtn() showBox() return clicked }) return } else if (t['status'].indexOf('闯关') != -1) { logger('当前为闯关模式,存在未完成任务点,脚本已暂停运行,请手动完成并点击下一章节', 'red') return } else if (t['status'].indexOf('开放') != -1) { logger('章节未开放', 'red') return } else { } } logger('此课程处理完毕', 'green') return }).catch(function (error) { logger('自动切换失败:' + error.message, 'red'); }) } function missonStart() { if (localStorage.getItem('GPTJsSetting.isPaused') === 'true') { setTimeout(missonStart, 3000); return; } if (_mlist.length <= 0) { logger('此页面任务处理完毕,准备跳转页面', 'green') return toNext() } let _type = _mlist[0]['type'], _dom = _domList[0], _task = _mlist[0]; if (_type == undefined) { _type = _mlist[0]['property']["module"] } if (!_dom && (_type == 'video' || _type == 'workid')) { logger('未找到该任务点对应的页面节点,跳过。', 'red') switchMission() return } switch (_type) { case "video": if (_mlist[0]['property']['module'] == 'insertvideo') { logger('开始处理视频', 'purple') missonVideo(_dom, _task) break } else if (_mlist[0]['property']['module'] == 'insertaudio') { logger('开始处理音频', 'purple') missonVideo(_dom, _task) break } else { logger('未知类型任务,请联系作者,跳过', 'red') switchMission() break } case "workid": logger('开始处理测验', 'purple') missonWork(_dom, _task) break case "document": logger('开始处理文档', 'purple') missonDoucument(_dom, _task) break case "read": logger('开始处理阅读', 'purple') missonRead(_dom, _task) break case "insertbook": logger('开始处理读书', 'purple') missonBook(_dom, _task) break case "knowledgeGraph": logger('开始处理知识图谱', 'purple') missonKnowledgeGraph(_task) break default: { let GarbageTasks = ['insertimage', 'insertanswerquestion', 'insertshare', 'insertquestion', 'insertdiscuss', 'insertsubject'] if (GarbageTasks.indexOf(_type) != -1) { logger('发现无需处理任务(' + _type + '),跳过。', 'red') switchMission() } else { logger('暂不支持处理此类型:' + _type + ',跳过。', 'red') switchMission() } } } } async function playMedia(playFunction) { const tryPlayMedia = () => { return new Promise((resolve, reject) => { try { const playRes = playFunction(); if (playRes) { playRes.then(resolve).catch(reject); } else { resolve(); } } catch (err) { reject(err); } }); }; try { await tryPlayMedia(); return true; } catch (err) { console.error(err); if (String(err).includes("failed because the user didn't interact with the document first")) { return new Promise((resolve) => { logger("浏览器限制自动播放:请点击页面任意位置,脚本将自动继续播放音视频。", "orange"); const docs = [document]; try { const panelDoc = getPanelDocument(); if (panelDoc && panelDoc !== document) docs.push(panelDoc); } catch (_) { } let settled = false; const cleanup = () => { docs.forEach((d) => { try { d.removeEventListener('pointerdown', onInteract, true); d.removeEventListener('keydown', onInteract, true); } catch (_) { } }); }; const onInteract = async () => { if (settled) return; settled = true; cleanup(); try { await tryPlayMedia(); resolve(true); } catch (e) { console.error(e); resolve(false); } }; docs.forEach((d) => { try { d.addEventListener('pointerdown', onInteract, true); d.addEventListener('keydown', onInteract, true); } catch (_) { } }); }); } else if (String(err).includes("The element has no supported sources")) { logger("当前视频无法播放。", "red"); } else if (String(err).includes("background media was paused to save power") || String(err).includes("interrupted because video-only") || String(err).includes("interrupted by a call to pause")) { console.log("[GPTJs] 忽略浏览器播放中断:", err); } else { logger("播放视频时发生未知错误:" + String(err), "red"); } return false; } } function missonVideo(dom, obj) { const { isPassed, otherInfo, property } = obj; const { _jobid: jobId, name, objectid: objectId, module } = property; const isAudioTask = module === 'insertaudio'; const taskLabel = isAudioTask ? '音频' : '视频'; if (isAudioTask ? !setting.audio : !setting.video) { logger(`用户设置不处理${taskLabel}任务,准备开始下一个任务。`, 'red'); return setTimeout(switchMission, 3000); } if (!setting.review && isPassed === true) { logger(`${taskLabel}:${name} 检测已完成,准备处理下一个任务`, 'green'); return switchMission(); } let mediaType = isAudioTask ? 'audio' : 'video'; logger(`处理${taskLabel}:${name},正在解析`); let executed = false; let _parseDebugLogged = false; const PARSE_TIMEOUT_MS = 60 * 1000; const parseStartTime = Date.now(); function searchIframesForMedia(iframes) { for (var fi = 0; fi < iframes.length; fi++) { var frame = iframes[fi]; var frameDoc; try { frameDoc = frame.contentDocument || frame.contentWindow.document; } catch (_) { continue; } if (!frameDoc) continue; var m = frameDoc.querySelector('video') || frameDoc.querySelector('audio'); if (m) { if (m.tagName.toLowerCase() === 'audio') mediaType = 'audio'; return { media: m, doc: frameDoc }; } try { var nested = frameDoc.querySelectorAll('iframe'); for (var ni = 0; ni < nested.length; ni++) { var nDoc; try { nDoc = nested[ni].contentDocument || nested[ni].contentWindow.document; } catch (_) { continue; } if (!nDoc) continue; m = nDoc.querySelector('video') || nDoc.querySelector('audio'); if (m) { if (m.tagName.toLowerCase() === 'audio') mediaType = 'audio'; return { media: m, doc: nDoc }; } } } catch (_) {} } return null; } const intervalId = setInterval(() => { if (localStorage.getItem('GPTJsSetting.isPaused') === 'true') return; if (!executed && Date.now() - parseStartTime > PARSE_TIMEOUT_MS) { clearInterval(intervalId); logger(`${taskLabel}:${name} 解析超时(超过60秒未加载),即将刷新页面重试`, 'red'); setTimeout(() => { location.reload(); }, 2000); return; } var result = dom && dom.length > 0 ? searchIframesForMedia(dom) : null; if (!result) { try { var allIframes = _d.querySelectorAll('.ans-attach-ct iframe'); if (allIframes.length > 0) { result = searchIframesForMedia(allIframes); } } catch (_) {} } if (!_parseDebugLogged) { _parseDebugLogged = true; var domSrcs = []; if (dom && dom.length > 0) { for (var di = 0; di < dom.length; di++) domSrcs.push(dom[di].src || '(无src)'); } console.log('[GPTJs Debug] dom iframes:', domSrcs, '| 找到媒体:', !!result); } if (result && !executed) { executed = true; clearInterval(intervalId); var media = result.media; var doc = result.doc; const userRate = getRate(); const finalRate = userRate; let rateRestored = false; const liveRate = () => rateRestored ? 1 : getRate(); if (mediaType === 'video' && isPlaybackRateDisabled(doc) && userRate > 1) { logger(`${name} 超星倍速菜单不可用,已改用脚本强制倍速:${userRate}×(高倍速可能导致播放进度重置、无法完成任务点)`, 'orange'); } else if (userRate > 1) { logger(`已开启倍速:${userRate}×(高倍速可能导致播放进度重置、无法完成任务点)`, 'orange'); } logger(`${name} - ${mediaType} 播放成功,开始控制播放(${finalRate}×)`); const runPlayback = () => { return new Promise((resolve, reject) => { const reloadInterval = setInterval(() => { const errorDiv = doc.querySelector(".vjs-modal-dialog-content"); if (["视频文件损坏", "网络错误导致视频下载中途失败", "视频因格式不支持", "网络的问题无法加载"].some( (s) => errorDiv && errorDiv.innerText.includes(s) )) { logger("检测到视频/音频加载失败,即将跳过。", "red"); clearInterval(reloadInterval); setTimeout(() => { _doResolve('加载失败,已跳过'); }, 3000); } }, 3000); const quizIntervalId = mediaType === 'video' ? setInterval(function () { handleVideoQuiz(doc, media, name); }, 1500) : null; const playFunction = async () => { if (localStorage.getItem('GPTJsSetting.isPaused') === 'true') return; if (mediaType === 'video' && getVisibleVideoQuizNode(doc, '.ans-videoquiz')) return; if (media.ended === false) { await new Promise(r => setTimeout(r, 1000)); if (media.paused && media.ended === false) { media.muted = true; try { media.play().then(() => { hookMediaRate(media, liveRate()); }).catch(async (e) => { console.log('[GPTJs] 后台恢复播放失败,尝试静音并重新播放:', e); media.muted = true; await playMedia(() => media.play()); hookMediaRate(media, liveRate()); }); } catch (err) { console.error(err); } } } }; media.addEventListener("pause", playFunction); const onTimeUpdate = () => { if (!rateRestored && isFinite(media.duration) && media.duration - media.currentTime < 10) { rateRestored = true; if (media._ne21Rate !== undefined && media._ne21Rate !== 1) hookMediaRate(media, 1); media.removeEventListener('timeupdate', onTimeUpdate); } }; media.addEventListener('timeupdate', onTimeUpdate); let appliedRate = finalRate; const applyRateNow = () => { const nextRate = getRate(); if (rateRestored || nextRate === appliedRate) return; appliedRate = nextRate; hookMediaRate(media, nextRate); logger(`倍速已切换为 ${nextRate}×,已立即生效`, 'green'); }; _ne21LiveRateAppliers.push(applyRateNow); let _playbackResolved = false; const _doResolve = (reason) => { if (_playbackResolved) return; _playbackResolved = true; logger(`${name} - ${mediaType} ${reason || '已播放完成'}`); media.removeEventListener("pause", playFunction); media.removeEventListener('timeupdate', onTimeUpdate); var _applierIndex = _ne21LiveRateAppliers.indexOf(applyRateNow); if (_applierIndex !== -1) _ne21LiveRateAppliers.splice(_applierIndex, 1); if (quizIntervalId) clearInterval(quizIntervalId); clearInterval(reloadInterval); clearInterval(_stallCheckId); resolve(); }; media.addEventListener("ended", () => { _doResolve('已播放完成'); }); let _lastProgressTime = -1; let _stalledMs = 0; const _STALL_LIMIT_MS = 5 * 60 * 1000; const _stallCheckId = setInterval(() => { if (localStorage.getItem('GPTJsSetting.isPaused') === 'true') { _lastProgressTime = media.currentTime; _stalledMs = 0; return; } if (mediaType === 'video' && getVisibleVideoQuizNode(doc, '.ans-videoquiz')) { _lastProgressTime = media.currentTime; _stalledMs = 0; return; } if (Math.abs(media.currentTime - _lastProgressTime) > 0.5) { _lastProgressTime = media.currentTime; _stalledMs = 0; } else { _stalledMs += 30 * 1000; if (_stalledMs >= _STALL_LIMIT_MS) { _doResolve('播放长时间无进度(疑似卡死),自动跳过'); } } }, 30 * 1000); media.muted = true; media.currentTime = 0; setTimeout(() => { playMedia(() => media.play()).then(() => { hookMediaRate(media, liveRate()); }).catch(reject); }, 200); }); }; runPlayback().then(() => { setTimeout(switchMission, 1000); }).catch(err => { logger(`${name} - 播放异常: ${err},即将切换下一任务`, 'red'); setTimeout(switchMission, 1000); }); } }, 2500); } function hookMediaRate(media, rate) { media._ne21Rate = rate; try { delete media.playbackRate; } catch (_) {} try { media.playbackRate = rate; } catch (_) {} try { Object.defineProperty(media, 'playbackRate', { configurable: true, get: function () { return media._ne21Rate; }, set: function () {} }); } catch (_) { if (media._ne21RateGuard) return; media._ne21RateGuard = true; try { media.addEventListener('ratechange', function () { if (media.playbackRate !== media._ne21Rate) { try { media.playbackRate = media._ne21Rate; } catch (__) {} } }); } catch (___) {} } } function isPlaybackRateDisabled(iframeDocument) { try { var items = iframeDocument.querySelectorAll('.vjs-playback-rate .vjs-menu-content .vjs-menu-item'); return items.length === 0; } catch (_) { return false; } } function missonBook(dom, obj) { if (localStorage.getItem('GPTJsSetting.isPaused') === 'true') { setTimeout(() => { missonBook(dom, obj) }, 3000); return; } if (setting.task) { if (obj['jobid'] == undefined) { logger("当前只处理任务点任务,跳过", 'red') switchMission() return } } let jobId = obj['property']['jobid'], name = obj['property']['bookname'], jtoken = obj['jtoken'], knowledgeId = _defaults['knowledgeid'], courseId = _defaults['courseid'], clazzId = _defaults['clazzId']; if (obj['job'] == undefined) { logger('读书:' + name + '检测已完成,准备执行下一个任务。', 'green') switchMission() return } $.ajax({ url: _l.protocol + '//' + _l.host + '/ananas/job?jobid=' + jobId + '&knowledgeid=' + knowledgeId + '&courseid=' + courseId + '&clazzid=' + clazzId + '&jtoken=' + jtoken + '&_dc=' + String(Math.round(new Date())), method: 'GET', error: function () { logger((name || '任务') + ' 请求失败,跳过。', 'red') switchMission() }, success: function (res) { if (res.status) { logger('读书:' + name + res.msg + ',准备执行下一个任务。', 'green') } else { logger('读书:' + name + '处理异常,跳过。', 'red') } switchMission() return }, }) } function missonDoucument(dom, obj) { if (localStorage.getItem('GPTJsSetting.isPaused') === 'true') { setTimeout(() => { missonDoucument(dom, obj) }, 3000); return; } if (setting.task) { if (obj['jobid'] == undefined) { logger("当前只处理任务点任务,跳过", 'red') switchMission() return } } let jobId = obj['property']['jobid'], name = obj['property']['name'], jtoken = obj['jtoken'], knowledgeId = _defaults['knowledgeid'], courseId = _defaults['courseid'], clazzId = _defaults['clazzId']; if (obj['job'] == undefined) { logger('文档:' + name + '检测已完成,准备执行下一个任务。', 'green') switchMission() return } $.ajax({ url: _l.protocol + '//' + _l.host + '/ananas/job/document?jobid=' + jobId + '&knowledgeid=' + knowledgeId + '&courseid=' + courseId + '&clazzid=' + clazzId + '&jtoken=' + jtoken + '&_dc=' + String(Math.round(new Date())), method: 'GET', error: function () { logger((name || '任务') + ' 请求失败,跳过。', 'red') switchMission() }, success: function (res) { if (res.status) { logger('文档:' + name + res.msg + ',准备执行下一个任务。', 'green') } else { logger('文档:' + name + '处理异常,跳过。', 'red') } switchMission() return }, }) } function missonRead(dom, obj) { if (localStorage.getItem('GPTJsSetting.isPaused') === 'true') { setTimeout(() => { missonRead(dom, obj) }, 3000); return; } if (setting.task) { if (obj['jobid'] == undefined) { logger("当前只处理任务点任务,跳过", 'red') switchMission() return } } let jobId = obj['property']['jobid'], name = obj['property']['title'], jtoken = obj['jtoken'], knowledgeId = _defaults['knowledgeid'], courseId = _defaults['courseid'], clazzId = _defaults['clazzId']; if (obj['job'] == undefined) { logger('阅读:' + name + ',检测已完成,准备执行下一个任务。', 'green') switchMission() return } $.ajax({ url: _l.protocol + '//' + _l.host + '/ananas/job/readv2?jobid=' + jobId + '&knowledgeid=' + knowledgeId + '&courseid=' + courseId + '&clazzid=' + clazzId + '&jtoken=' + jtoken + '&_dc=' + String(Math.round(new Date())), method: 'GET', error: function () { logger((name || '任务') + ' 请求失败,跳过。', 'red') switchMission() }, success: function (res) { if (res.status) { logger('阅读:' + name + res.msg + ',准备执行下一个任务。', 'green') } else { logger('阅读:' + name + '处理异常,跳过。', 'red') } switchMission() return } }) } function missonKnowledgeGraph(obj) { if (localStorage.getItem('GPTJsSetting.isPaused') === 'true') { setTimeout(function () { missonKnowledgeGraph(obj) }, 3000); return; } var taskName = (obj['property'] && obj['property']['name']) || '知识图谱'; if (obj['job'] == undefined) { logger('知识图谱:' + taskName + ',检测已完成,准备执行下一个任务。', 'green') switchMission() return } var clicked = false; try { var iframes = document.querySelectorAll('iframe'); for (var i = 0; i < iframes.length; i++) { try { var iframeDoc = iframes[i].contentDocument || iframes[i].contentWindow.document; if (!iframeDoc) continue; var packBtn = iframeDoc.querySelector('#graphPackBtn'); if (packBtn) { if (!packBtn.classList.contains('active')) { packBtn.click(); logger('知识图谱:' + taskName + ',已点击展开按钮', 'green'); } else { logger('知识图谱:' + taskName + ',已是展开状态', 'green'); } clicked = true; break; } } catch (e) { } } } catch (e) { console.log('[GPTJs] 查找知识图谱 iframe 异常:', e); } if (!clicked) { logger('知识图谱:' + taskName + ',未找到展开按钮,可能已完成或不在当前页面,跳过', 'orange'); } setTimeout(function () { switchMission() }, 3000); } function missonWork(dom, obj) { if (!setting.work) { logger('用户设置不自动处理测验,准备处理下一个任务', 'green') switchMission() return } let isDo; if (setting.task) { logger("当前只处理任务点任务", 'red') if (obj['jobid'] == undefined ? false : true) { isDo = true } else { isDo = false } } else { logger("当前默认处理所有任务(包括非任务点任务)", 'red') isDo = true } if (isDo) { setTimeout(() => { startDoCyWork(0, dom) }, 3000) } else { logger('用户设置只处理属于任务点的任务,准备处理下一个任务', 'green') switchMission() return } } function getAccessibleFrameDocument(frame) { if (!frame) return null; try { return frame.contentDocument || (frame.contentWindow && frame.contentWindow.document) || null; } catch (_) { return null; } } function isCrossOriginAccessError(error) { return !!error && (error.name === 'SecurityError' || /Blocked a frame|cross-origin frame|Permission denied/i.test(error.message || '')); } function pollForElement(iframeDom, selector, interval, maxAttempts) { interval = interval || 2000; maxAttempts = (typeof maxAttempts === 'number' && maxAttempts > 0) ? maxAttempts : 60; return new Promise(function (resolve) { var attempts = 0; var check = function () { try { var doc = getAccessibleFrameDocument(iframeDom); if (doc) { var el = doc.querySelector(selector); if (el) return resolve(el); } } catch (e) {} attempts++; if (attempts >= maxAttempts) { logger('框架等待超时(' + Math.round(attempts * interval / 1000) + 's),上层将重试或跳过', 'red'); return resolve(null); } if (attempts % 15 === 0) { logger('框架仍在加载中,已等待' + (attempts * interval / 1000) + '秒...请耐心等待', 'orange'); } setTimeout(check, interval); }; check(); }); } var _ne21AntiSleepStarted = false; function setupAntiSleep() { if (_ne21AntiSleepStarted) return; var AC = window.AudioContext || window.webkitAudioContext; if (!AC) return; function tryStart() { if (_ne21AntiSleepStarted) return; try { var ac = new AC(); var osc = ac.createOscillator(); var gain = ac.createGain(); gain.gain.value = 0; osc.connect(gain); gain.connect(ac.destination); osc.start(); _ne21AntiSleepStarted = true; document.addEventListener('visibilitychange', function () { try { if (ac.state === 'suspended') ac.resume(); } catch (_) {} }); } catch (_) {} } tryStart(); if (!_ne21AntiSleepStarted) { var onUserGesture = function () { tryStart(); if (_ne21AntiSleepStarted) { document.removeEventListener('click', onUserGesture, true); document.removeEventListener('keydown', onUserGesture, true); document.removeEventListener('touchstart', onUserGesture, true); } }; document.addEventListener('click', onUserGesture, true); document.addEventListener('keydown', onUserGesture, true); document.addEventListener('touchstart', onUserGesture, true); } } function setupAutoRefresh() { var stored = localStorage.getItem('GPTJsSetting.autoRefresh'); var enabled = stored !== null ? (stored === 'true') : false; if (!enabled) return; var minutes = parseInt(localStorage.getItem('GPTJsSetting.autoRefreshMinutes'), 10); if (!isFinite(minutes) || minutes < 5) minutes = 30; setTimeout(function () { logger('已达到自动刷新时间(' + minutes + '分钟),3 秒后刷新页面...', 'orange'); setTimeout(function () { try { window.location.reload(); } catch (_) {} }, 3000); }, minutes * 60 * 1000); } function startDoCyWork(index, doms) { if (localStorage.getItem('GPTJsSetting.isPaused') === 'true') { setTimeout(() => { startDoCyWork(index, doms) }, 3000); return; } if (index >= doms.length) { setTimeout(missonStart, 2000); return; } var outerDoc = getAccessibleFrameDocument(doms[index]); if (!outerDoc || !outerDoc.querySelector('iframe')) logger('等待测验框架加载...', 'purple'); pollForElement(doms[index], 'iframe').then(async function (workIframe) { if (!workIframe) { logger('未找到测验框架,暂停处理,请刷新后重试', 'red'); return; } var ready = await pollForElement(workIframe, '.TiMu, .questionLi, .testTit_status', 1000, 60); if (!ready) return; var currentDoc = getAccessibleFrameDocument(workIframe); if (!currentDoc) { logger('测验框架正在跳转或受到跨域限制,请等待加载完成后重试', 'orange'); return; } var $doc = $(currentDoc); var status = $doc.find('.testTit_status').text().trim(); if (/待批阅|已完成/.test(status) && !(isRedoMode() && /已完成/.test(status))) { logger('测验:' + status + ',跳过', 'green'); _mlist.splice(0, 1); _domList.splice(0, 1); setTimeout(() => { startDoCyWork(index + 1, doms) }, 2000); } else { if (!$doc.find('.TiMu, .questionLi').length) { var question = await pollForElement(workIframe, '.TiMu, .questionLi', 1000, 60); if (!question) { logger('测验当前状态:' + (status || '未加载题目') + ',请手动进入作答页面', 'orange'); return; } } if (setting.decrypt) { await decryptFont(currentDoc).catch(function (e) { console.error('[GPTJs] 测验字体解密失败', e); }); } doWork(index, doms, workIframe); } }); } function getQuizPracticeType($item) { var typeText = ($item.find('.grey-text').first().text() || '').replace(/\s+/g, '') var className = String($item.attr('class') || '') if (typeText.indexOf('多选') !== -1 || className.indexOf('multiple-choice') !== -1) { return { type: 1, name: '多选题' } } if (typeText.indexOf('判断') !== -1) { return { type: 3, name: '判断题' } } if (typeText.indexOf('填空') !== -1 || $item.find('.option-fill-list').length > 0) { return { type: 2, name: '填空题' } } if (/(简答|问答|论述|名词解释|计算题|材料题|写作|翻译)/.test(typeText) || $item.find('.short-answer-textarea').length > 0) { return { type: 4, name: typeText.replace(/^\[|\]$/g, '') || '简答题' } } if (typeText.indexOf('单选') !== -1 || className.indexOf('single-choice') !== -1) { return { type: 0, name: '单选题' } } return { type: -1, name: typeText || '未知题型' } } function getQuizPracticeQuestionText($item) { var $name = $item.find('.question-name').first().clone() $name.find('.grey-text').remove() var text = ($name.text() || '').replace(/\s+/g, ' ').trim() return tidyQuestion($('
').text(text).html()) || '随堂练习题' } function getQuizPracticeOptions($item) { return $item.find('.option-list > li').map(function () { var $option = $(this) var $clone = $option.clone() $clone.find('.option-letter').remove() return tidyStr($('
').text($clone.text()).html()) || '' }).get() } function getQuizPracticeFillInputs($item) { return $item.find('input.ofl-ipt, .option-fill-list input, .option-fill-list textarea').filter(function () { return !this.disabled }) } function getQuizPracticeTextarea($item) { var $textarea = $item.find('.short-answer-textarea textarea').first() if ($textarea.length === 0) $textarea = $item.find('textarea').first() return $textarea } function isQuizPracticeAnswered($item, type) { if (type === 0 || type === 1 || type === 3) { return $item.find('.option-list > li.active, .option-list > li.selected, .option-list > li.checked').length > 0 } if (type === 2) { var $inputs = getQuizPracticeFillInputs($item) var hasFill = false $inputs.each(function () { if ($.trim($(this).val() || '')) hasFill = true }) return hasFill } if (type === 4) { return $.trim(getQuizPracticeTextarea($item).val() || '') !== '' } return false } function setQuizPracticeValue($element, value) { var element = $element.get(0) if (!element) return var text = value == null ? '' : String(value) try { var win = element.ownerDocument.defaultView var prototype = element.tagName === 'SELECT' ? win.HTMLSelectElement.prototype : element.tagName === 'TEXTAREA' ? win.HTMLTextAreaElement.prototype : win.HTMLInputElement.prototype var descriptor = Object.getOwnPropertyDescriptor(prototype, 'value') if (descriptor && descriptor.set) descriptor.set.call(element, text) else element.value = text } catch (_) { element.value = text } try { element.dispatchEvent(new Event('input', { bubbles: true })) element.dispatchEvent(new Event('change', { bubbles: true })) element.dispatchEvent(new Event('blur', { bubbles: true })) } catch (_) {} if (element.tagName === 'SELECT') { element.setAttribute('value', text) var pageJQuery = element.ownerDocument.defaultView.jQuery || element.ownerDocument.defaultView.$ if (pageJQuery) pageJQuery(element).trigger('chosen:updated').trigger('liszt:updated') } } function isQuizPracticeGoodStudent() { return localStorage.getItem('GPTJsSetting.goodStudent') === 'true' } function setQuizPracticeOptionState($options, selectedIndexes) { var selected = {} selectedIndexes.forEach(function (index) { selected[index] = true }) $options.each(function (index) { var $option = $(this) var shouldSelect = !!selected[index] if (isQuizPracticeGoodStudent()) { if (shouldSelect) $option.find('.option-letter, .option-result').css('font-weight', 'bold') return } var isSelected = $option.hasClass('active') || $option.hasClass('selected') || $option.hasClass('checked') if (shouldSelect !== isSelected) { try { this.click() } catch (_) { $option.trigger('click') } } }) } function appendQuizPracticeAnswer($item, answer) { var alterTitle = localStorage.getItem('GPTJsSetting.alterTitle') var shouldAlter = alterTitle === null ? !!setting.alterTitle : alterTitle === 'true' if (!shouldAlter || !answer || $item.attr('data-ne21-answer-appended') === 'true') return var $name = $item.find('.question-name').first() if ($name.length === 0) return $('

').css('font-weight', 'bold').text('答案:' + answer).appendTo($name) $item.attr('data-ne21-answer-appended', 'true') } function getQuizPracticeSubmitButton() { var candidates = $('button, input[type="button"], input[type="submit"], .van-button, .submit-btn, .submit, [role="button"]').filter(function () { if (this.disabled) return false if (!$(this).is(':visible')) return false var text = ($(this).text() || $(this).val() || '').replace(/\s+/g, '') var className = typeof this.className === 'string' ? this.className : '' if (text === '提交' || (text.indexOf('提交') !== -1 && text.length <= 8)) return true return /(?:^|[-_\s])submit(?:$|[-_\s])/i.test(' ' + className + ' ') }) return candidates.last() } function continueQuizPractice(index, questions, state) { var wait = Number(setting.time) if (!isFinite(wait) || wait < 300) wait = 2500 wait += Math.floor(Math.random() * 350) setTimeout(function () { doQuizPractice(index, questions, state) }, wait) } function finishQuizPractice(state) { if (localStorage.getItem('GPTJsSetting.isPaused') === 'true') { setTimeout(function () { finishQuizPractice(state) }, 3000) return } logger('随堂练习处理完成,共 ' + state.total + ' 题,已作答 ' + state.answered + ' 题,失败 ' + state.failed + ' 题', state.failed ? 'orange' : 'green') var storedSub = localStorage.getItem('GPTJsSetting.sub') var autoSubmit = storedSub === null ? !!setting.sub : storedSub === 'true' var storedForce = localStorage.getItem('GPTJsSetting.force') var forceSubmit = storedForce === null ? !!setting.force : storedForce === 'true' if (!autoSubmit && !forceSubmit) { logger('随堂练习未开启自动提交,已保留当前作答', 'blue') return } if (state.failed > 0 && !forceSubmit) { logger('存在未完成题目,已停止提交;如需强制提交请开启“测验强制提交”', 'orange') return } var $submit = getQuizPracticeSubmitButton() if ($submit.length === 0) { logger('未找到随堂练习提交按钮,请手动提交', 'red') return } try { $submit.get(0).click() logger('已提交随堂练习', 'green') } catch (_) { logger('随堂练习提交按钮点击失败,请手动提交', 'red') } } function doQuizPractice(index, questions, state) { if (localStorage.getItem('GPTJsSetting.isPaused') === 'true') { setTimeout(function () { doQuizPractice(index, questions, state) }, 3000) return } if (index >= questions.length) { setTimeout(function () { finishQuizPractice(state) }, 500) return } var $item = $(questions[index]) if ($item.length === 0) { state.failed++ continueQuizPractice(index + 1, questions, state) return } var typeInfo = getQuizPracticeType($item) _currentQuestionMeta = { index: index, total: questions.length, typeName: typeInfo.name } if (typeInfo.type < 0) { state.failed++ logger('第' + (index + 1) + '题题型未识别,已跳过', 'red') continueQuizPractice(index + 1, questions, state) return } if (!isRedoMode() && isQuizPracticeAnswered($item, typeInfo.type)) { state.answered++ logger('第' + (index + 1) + '题已作答,已跳过', 'blue') continueQuizPractice(index + 1, questions, state) return } var question = getQuizPracticeQuestionText($item) var options = getQuizPracticeOptions($item) var prompt if (typeInfo.type === 0) { if (options.length === 0) { state.failed++ logger('第' + (index + 1) + '题未找到选项,已跳过', 'red') continueQuizPractice(index + 1, questions, state) return } prompt = buildPrompt({ type: '单选题', question: question, options: options, answer_format: "只回答一个选项字母或选项内容" }) } else if (typeInfo.type === 1) { if (options.length === 0) { state.failed++ logger('第' + (index + 1) + '题未找到选项,已跳过', 'red') continueQuizPractice(index + 1, questions, state) return } prompt = buildPrompt({ type: '多选题', question: question, options: options, answer_format: "用'" + ANSWER_SEPARATOR + "'分割多个答案,或回答选项字母" }) } else if (typeInfo.type === 3) { if (options.length === 0) { state.failed++ logger('第' + (index + 1) + '题未找到选项,已跳过', 'red') continueQuizPractice(index + 1, questions, state) return } prompt = buildPrompt({ type: '判断题', question: question, options: options, answer_format: "只回答正确或错误,或回答选项字母" }) } else if (typeInfo.type === 2) { prompt = buildPrompt({ type: '填空题', question: question, answer_format: "多个填空内容用'" + ANSWER_SEPARATOR + "'分隔" }) } else { prompt = buildPrompt({ type: '简答题', question: question }) } getAnswer(typeInfo.type, prompt).then(function (answer) { appendQuizPracticeAnswer($item, answer) var applied = false if (typeInfo.type === 0 || typeInfo.type === 1 || typeInfo.type === 3) { var indexes = [] if (typeInfo.type === 3) { var judgeAnswer = parseJudgeAnswer(answer) var judgeIndex = judgeAnswer === null ? -1 : findJudgeOptionIndex(options, judgeAnswer === 'true') if (judgeIndex !== -1) indexes = [judgeIndex] } if (indexes.length === 0) { indexes = findVideoQuizMatchIndexes(options, answer, typeInfo.type === 1) } if (typeInfo.type !== 1) indexes = indexes.slice(0, 1) if (indexes.length === 0) { state.failed++ logger('第' + (index + 1) + '题未能匹配到选项,已跳过', 'red') } else { var $options = $item.find('.option-list > li') setQuizPracticeOptionState($options, indexes) applied = true state.answered++ } } else if (typeInfo.type === 2) { var $inputs = getQuizPracticeFillInputs($item) var parts = $inputs.length === 1 ? [String(answer || '').trim()] : splitAiAnswers(answer) if (parts.length === 0 && answer) parts = [String(answer).trim()] if ($inputs.length === 0) { state.failed++ logger('第' + (index + 1) + '题未找到填空输入框,已跳过', 'red') } else { $inputs.each(function (inputIndex) { var value = parts[inputIndex] != null ? parts[inputIndex] : (parts.length === 1 ? parts[0] : '') setQuizPracticeValue($(this), value) }) applied = true state.answered++ } } else { var $textarea = getQuizPracticeTextarea($item) if ($textarea.length === 0) { state.failed++ logger('第' + (index + 1) + '题未找到作答输入框,已跳过', 'red') } else { setQuizPracticeValue($textarea, answer) applied = true state.answered++ } } if (applied) logger('第' + (index + 1) + '题作答完成', 'green') continueQuizPractice(index + 1, questions, state) }).catch(function () { state.failed++ continueQuizPractice(index + 1, questions, state) }) } function missonQuizPractice() { if (document.documentElement.getAttribute('data-ne21-quiz-practice') === 'running') return var questions = $('.question-item').toArray() if (questions.length === 0) { logger('未找到随堂练习题目', 'red') return } document.documentElement.setAttribute('data-ne21-quiz-practice', 'running') var state = { total: questions.length, answered: 0, failed: 0 } logger('检测到随堂练习,共 ' + questions.length + ' 题,开始处理', 'green') doQuizPractice(0, questions, state) } function missonHomeWork() { logger('开始处理作业', 'green') let $_homeworktable = $('.mark_table').find('form') let TimuList = $_homeworktable.find('.questionLi') doHomeWork(0, TimuList) } function doHomeWork(index, TiMuList) { if (localStorage.getItem('GPTJsSetting.isPaused') === 'true') { setTimeout(() => { doHomeWork(index, TiMuList) }, 3000); return; } if (index == TiMuList.length) { logger('作业题目已全部完成', 'green') return } if (handleExtraWorkQuestion($(TiMuList[index]), () => { doHomeWork(index + 1, TiMuList); }, { index: index, total: TiMuList.length })) return; let $subQuestions = getWorkSubQuestions($(TiMuList[index])); if ($subQuestions && $subQuestions.length > 0) { logger('检测到复合大题(含有 ' + $subQuestions.length + ' 个子题),开始处理子题...', 'blue'); let parentQuestion = getWorkQuestionText($(TiMuList[index])); let currentTypeName = $(TiMuList[index]).attr('typename') || '阅读理解'; _currentQuestionMeta = { index: index, total: TiMuList.length, typeName: currentTypeName }; processSubQuestions(0, $subQuestions, parentQuestion, () => setting.time, () => { doHomeWork(index + 1, TiMuList) }); return; } function handleNormalTextarea(textareaList, jdt, index, TiMuList) { if (!textareaList || textareaList.length === 0) { setTimeout(() => { doHomeWork(index + 1, TiMuList) }, setting.time); return; } getAnswer(4, jdt).then((agrs) => { $.each(textareaList, (i, t) => { let _id = $(t).attr('id') || $(t).attr('name'); setTimeout(() => { try { UE.getEditor(_id).setContent(agrs) } catch (e) {} }, 300 + i * 200); }); logger('自动答题成功,准备切换下一题', 'green'); setTimeout(() => { doHomeWork(index + 1, TiMuList) }, setting.time + 200 * textareaList.length); }).catch((agrs) => { if (agrs && agrs['c'] == 0) { setTimeout(() => { doHomeWork(index + 1, TiMuList) }, setting.time); } }); } let typeName = $(TiMuList[index]).attr('typename'); let _type = ({ 单选题: 0, 单项选择题: 0, 单选: 0, 多选题: 1, 多项选择题: 1, 多选: 1, 填空题: 2, 填空: 2, 判断题: 3, 是非题: 3, 判断: 3, 简答题: 4, 简答: 4, 问答题: 4, 名词解释: 4, 论述题: 4, 论述: 4, 计算题: 4, 计算: 4, 分录题: 4, 资料题: 4, 作图题: 4, 其他: 4, 其它: 4, 阅读理解: 4, 阅读: 4, 阅读题: 4, 理解题: 4, 完形填空: 4, 完形: 4, 综合题: 4, 写作题: 5, 翻译题: 6 })[typeName] _currentQuestionMeta = { index: index, total: TiMuList.length, typeName: typeName } let _question = extractQuestionFromTitle($(TiMuList[index]).find('.mark_name').first()) let _a = [] let _answerTmpArr, _textareaList var check_answer_flag = 0; if (_type === undefined) { logger('未知题型: ' + typeName + ',尝试自动识别', 'blue'); let detected = detectStandardQuestionType($(TiMuList[index]), typeName); _type = detected.type; if (_type !== undefined) { logger((detected.source === 'code' ? '根据页面基础题型识别为' : '自动识别为') + getQuestionTypeLabel(_type), 'green'); } } switch (_type) { case 0: { _answerTmpArr = $(TiMuList[index]).find('.stem_answer').find('.answer_p') let mergedAnswers = []; _answerTmpArr.each(function () { var answerText = $(this).text().trim(); mergedAnswers.push(answerText); }); _question = buildPrompt({ type: '单选题', question: _question, options: mergedAnswers }) for (let i = 0; i < _answerTmpArr.length; i++) { if (($(_answerTmpArr[i]).parent().find('span').attr('class') || '').indexOf('check_answer') == -1) { } else { if (!isRedoMode()) { logger(index + 1 + '此题已作答,准备切换下一题', 'green') check_answer_flag = 1; setTimeout(() => { doHomeWork(index + 1, TiMuList) }, 30) } else { logger(index + 1 + '此题已作答,重做模式下重新作答', 'blue') $(_answerTmpArr[i]).parent().click() } break } } if (check_answer_flag == 0) { getAnswer(_type, _question).then((agrs) => { $.each(_answerTmpArr, (i, t) => { _a.push(tidyStr($(t).html())) }) if (localStorage.getItem('GPTJsSetting.alterTitle') === 'true') { let timuele = $(TiMuList[index]).find('.mark_name') appendAnswerToTitle(timuele, agrs) } let _i = matchSingleOptionIndex(_a, agrs) if (_i == -1) { logger('AI未能完美匹配正确答案,请尝试更换更高级模型或手动选择,跳过此题', 'red') setTimeout(() => { doHomeWork(index + 1, TiMuList) }, setting.time) } else { setTimeout(() => { let check = $(_answerTmpArr[_i]).parent().find('span').attr('class') || '' if (check.indexOf('check_answer') == -1) { $(_answerTmpArr[_i]).parent().click() } logger('自动答题成功,准备切换下一题', 'green') setTimeout(() => { doHomeWork(index + 1, TiMuList) }, setting.time) }, 300) } }).catch((agrs) => { if (agrs['c'] == 0) { setTimeout(() => { doHomeWork(index + 1, TiMuList) }, setting.time) } }) } } break case 1: { _answerTmpArr = $(TiMuList[index]).find('.stem_answer').find('.answer_p') let mergedAnswers = []; _answerTmpArr.each(function () { var answerText = $(this).text().trim(); mergedAnswers.push(answerText); }); _question = buildPrompt({ type: '多选题', question: _question, options: mergedAnswers, answer_format: "用'" + ANSWER_SEPARATOR + "'分割多个答案" }) for (let i = 0; i < _answerTmpArr.length; i++) { if (($(_answerTmpArr[i]).parent().find('span').attr('class') || '').indexOf('check_answer') == -1) { } else { if (!isRedoMode()) { logger(index + 1 + '此题已作答,准备切换下一题', 'green') check_answer_flag = 1; setTimeout(() => { doHomeWork(index + 1, TiMuList) }, 30) break } else { logger(index + 1 + '此题已作答,重做模式下取消旧答案', 'blue') $(_answerTmpArr[i]).parent().click() } } } if (check_answer_flag == 0) { getAnswer(_type, _question).then((agrs) => { if (localStorage.getItem('GPTJsSetting.alterTitle') === 'true') { let timuele = $(TiMuList[index]).find('.mark_name') appendAnswerToTitle(timuele, agrs) } let _multiOptions = [] $.each(_answerTmpArr, (i, t) => { _multiOptions.push(tidyStr($(t).html())) }) let matchedIndexes = matchMultiOptionIndexes(_multiOptions, agrs) if (matchedIndexes.length === 0) { logger('AI未能完美匹配正确答案,请尝试更换更高级模型或手动选择,跳过此题', 'red') setTimeout(() => { doHomeWork(index + 1, TiMuList) }, setting.time) return } matchedIndexes.forEach((idx) => { setTimeout(() => { let check = $(_answerTmpArr[idx]).parent().find('span').attr('class') || '' if (check.indexOf('check_answer_dx') == -1) { $(_answerTmpArr[idx]).parent().click() } }, 300) }) logger('自动答题成功,准备切换下一题', 'green') setTimeout(() => { doHomeWork(index + 1, TiMuList) }, setting.time) }).catch((agrs) => { if (agrs['c'] == 0) { setTimeout(() => { doHomeWork(index + 1, TiMuList) }, setting.time) } }) } } break case 2: { _question = buildPrompt({ type: '填空题', question: _question, answer_format: "用'" + ANSWER_SEPARATOR + "'分割多个答案" }); _textareaList = findAnswerTextareas($(TiMuList[index])); if (!_textareaList || _textareaList.length === 0) { logger('未找到填空题输入区域,跳过此题', 'red'); setTimeout(() => { doHomeWork(index + 1, TiMuList) }, setting.time); break } let _id = $(_textareaList[0]).attr('id') || $(_textareaList[0]).attr('name'); let firstAnswered = false; try { if (_id && UE.getEditor(_id) && UE.getEditor(_id).getContent && UE.getEditor(_id).getContent() !== '') firstAnswered = true; } catch (e) { firstAnswered = false; } if (firstAnswered && !isRedoMode()) { logger(index + 1 + '此题已作答,准备切换下一题', 'green'); setTimeout(() => { doHomeWork(index + 1, TiMuList) }, 30); } else { getAnswer(_type, _question).then((agrs) => { let _answerTmpArr = (agrs || '').split(ANSWER_SEPARATOR); $.each(_textareaList, (i, t) => { let _currentId = $(t).attr('id') || $(t).attr('name'); let val = _answerTmpArr[i] !== undefined ? _answerTmpArr[i] : (_answerTmpArr[0] || agrs); setTimeout(() => { try { UE.getEditor(_currentId).setContent(val) } catch (e) {} }, 300 + i * 200); }); setTimeout(() => { doHomeWork(index + 1, TiMuList) }, setting.time + 200 * _textareaList.length); logger('自动答题成功,准备切换下一题', 'green'); }).catch((agrs) => { if (agrs && agrs['c'] == 0) { setTimeout(() => { doHomeWork(index + 1, TiMuList) }, setting.time); } }); } break } case 3: { _answerTmpArr = $(TiMuList[index]).find('.stem_answer').find('.answer_p') $.each(_answerTmpArr, (i, t) => { _a.push($(t).text().trim()) }) for (let i = 0; i < _answerTmpArr.length; i++) { if (($(_answerTmpArr[i]).parent().find('span').attr('class') || '').indexOf('check_answer') == -1) { } else { if (!isRedoMode()) { logger(index + 1 + '此题已作答,准备切换下一题', 'green') check_answer_flag = 1; setTimeout(() => { doHomeWork(index + 1, TiMuList) }, 30) } else { logger(index + 1 + '此题已作答,重做模式下重新作答', 'blue') $(_answerTmpArr[i]).parent().click() } break } } if (check_answer_flag == 0) { _question = buildPrompt({ type: '判断题', question: _question, answer_format: "只回答正确或错误" }) getAnswer(_type, _question).then((agrs) => { if (localStorage.getItem('GPTJsSetting.alterTitle') === 'true') { let timuele = $(TiMuList[index]).find('.mark_name') appendAnswerToTitle(timuele, agrs) } let judgeResult = parseJudgeAnswer(agrs) if (judgeResult === null) { logger('答案匹配出错,准备切换下一题', 'red') setTimeout(() => { doHomeWork(index + 1, TiMuList) }, setting.time) return } let _i = findJudgeOptionIndex(_a, judgeResult === 'true') if (_i === -1) { logger('未匹配到正确选项,跳过', 'red') setTimeout(() => { doHomeWork(index + 1, TiMuList) }, setting.time) return } setTimeout(() => { let check = $(_answerTmpArr[_i]).parent().find('span').attr('class') || '' if (check.indexOf('check_answer') == -1) { $(_answerTmpArr[_i]).parent().click() } }, 300) logger('自动答题成功,准备切换下一题', 'green') setTimeout(() => { doHomeWork(index + 1, TiMuList) }, setting.time) }).catch((agrs) => { if (agrs['c'] == 0) { setTimeout(() => { doHomeWork(index + 1, TiMuList) }, setting.time) } }) } break } case 4: { let _answerEle = findAnswerTextareas($(TiMuList[index])) if (!_answerEle || _answerEle.length === 0) { logger((index + 1) + ' 未找到文本作答区域,跳过此题', 'red') setTimeout(() => { doHomeWork(index + 1, TiMuList) }, setting.time) break } let _isAnswered4 = false $.each(_answerEle, function (i, t) { let _eid = $(t).attr('id') || $(t).attr('name') try { if (_eid && UE.getEditor(_eid) && UE.getEditor(_eid).getContent && UE.getEditor(_eid).getContent() !== '') _isAnswered4 = true } catch (e) {} }) if (_isAnswered4 && !isRedoMode()) { logger((index + 1) + ' 此题已作答,准备切换下一题', 'green') setTimeout(() => { doHomeWork(index + 1, TiMuList) }, 30) break } let jdt = buildPrompt({ type: typeName || '简答题', question: _question, answer_format: "用50字简要回答" }) getAnswer(_type, jdt).then((agrs) => { if (localStorage.getItem('GPTJsSetting.alterTitle') === 'true') { let timuele = $(TiMuList[index]).find('.mark_name') appendAnswerToTitle(timuele, agrs) } $.each(_answerEle, (i, t) => { let _id = $(t).attr('id') || $(t).attr('name') setTimeout(() => { try { UE.getEditor(_id).setContent(agrs) } catch (e) {} }, 300 + i * 200); }); logger('自动答题成功,准备切换下一题', 'green') setTimeout(() => { doHomeWork(index + 1, TiMuList) }, setting.time + 200 * _answerEle.length); }).catch(() => { setTimeout(() => { doHomeWork(index + 1, TiMuList) }, setting.time) }); } break case 5: { let _answerEle5 = findAnswerTextareas($(TiMuList[index])) if (!_answerEle5 || _answerEle5.length === 0) { logger((index + 1) + ' 未找到写作题文本框,跳过此题', 'red') setTimeout(() => { doHomeWork(index + 1, TiMuList) }, setting.time) break } let _isAnswered5 = false $.each(_answerEle5, function (i, t) { let _eid = $(t).attr('id') || $(t).attr('name') try { if (_eid && UE.getEditor(_eid) && UE.getEditor(_eid).getContent && UE.getEditor(_eid).getContent() !== '') _isAnswered5 = true } catch (e) {} }) if (_isAnswered5 && !isRedoMode()) { logger((index + 1) + ' 此题已作答,准备切换下一题', 'green') setTimeout(() => { doHomeWork(index + 1, TiMuList) }, 30) break } let jdt5 = buildPrompt({ type: typeName || '写作题', question: _question, answer_format: "用英文根据题目进行写作" }) getAnswer(_type, jdt5).then((agrs) => { if (localStorage.getItem('GPTJsSetting.alterTitle') === 'true') { let timuele = $(TiMuList[index]).find('.mark_name') appendAnswerToTitle(timuele, agrs) } $.each(_answerEle5, (i, t) => { let _id = $(t).attr('id') || $(t).attr('name') setTimeout(() => { try { UE.getEditor(_id).setContent(agrs) } catch (e) {} }, 300 + i * 200); }); logger('自动答题成功,准备切换下一题', 'green') setTimeout(() => { doHomeWork(index + 1, TiMuList) }, setting.time + 200 * _answerEle5.length); }).catch(() => { setTimeout(() => { doHomeWork(index + 1, TiMuList) }, setting.time) }); } break case 6: { let _answerEle6 = findAnswerTextareas($(TiMuList[index])) if (!_answerEle6 || _answerEle6.length === 0) { logger((index + 1) + ' 未找到翻译题文本框,跳过此题', 'red') setTimeout(() => { doHomeWork(index + 1, TiMuList) }, setting.time) break } let _isAnswered6 = false $.each(_answerEle6, function (i, t) { let _eid = $(t).attr('id') || $(t).attr('name') try { if (_eid && UE.getEditor(_eid) && UE.getEditor(_eid).getContent && UE.getEditor(_eid).getContent() !== '') _isAnswered6 = true } catch (e) {} }) if (_isAnswered6 && !isRedoMode()) { logger((index + 1) + ' 此题已作答,准备切换下一题', 'green') setTimeout(() => { doHomeWork(index + 1, TiMuList) }, 30) break } let jdt6 = buildPrompt({ type: typeName || '翻译题', question: _question, answer_format: "中文英文互译" }) getAnswer(_type, jdt6).then((agrs) => { if (localStorage.getItem('GPTJsSetting.alterTitle') === 'true') { let timuele = $(TiMuList[index]).find('.mark_name') appendAnswerToTitle(timuele, agrs) } $.each(_answerEle6, (i, t) => { let _id = $(t).attr('id') || $(t).attr('name') setTimeout(() => { try { UE.getEditor(_id).setContent(agrs) } catch (e) {} }, 300 + i * 200); }); logger('自动答题成功,准备切换下一题', 'green') setTimeout(() => { doHomeWork(index + 1, TiMuList) }, setting.time + 200 * _answerEle6.length); }).catch(() => { setTimeout(() => { doHomeWork(index + 1, TiMuList) }, setting.time) }); } break default: { if (_type === undefined) { logger('无法识别题型:' + typeName + ',跳过此题', 'red') setTimeout(() => { doHomeWork(index + 1, TiMuList) }, setting.time) } else { _textareaList = $(TiMuList[index]).find('.stem_answer').find('textarea, .subEditor textarea, .divText textarea, .eidtDiv textarea, .divText .edui-editor, textarea[name^="answerEditor"]'); if (_textareaList && _textareaList.length > 0) { logger('检测到文本输入区域,尝试回答', 'green'); let jdt = buildPrompt({ type: typeName || '未知题型', question: _question, answer_format: "请根据题目作答" }) let editorTextareas = $(TiMuList[index]).find('.stem_answer textarea[name^="answerEditor"]'); if (editorTextareas && editorTextareas.length > 0) { let editorId = $(editorTextareas[0]).attr('id'); if (editorId) { getAnswer(_type || 4, jdt).then((agrs) => { setTimeout(() => { UE.getEditor(editorId).setContent(agrs) }, 300); logger('使用富文本编辑器ID回答成功,准备切换下一题', 'green'); setTimeout(() => { doHomeWork(index + 1, TiMuList) }, setting.time); }).catch((agrs) => { if (agrs['c'] == 0) { setTimeout(() => { doHomeWork(index + 1, TiMuList) }, setting.time); } }); } else { logger('找到富文本编辑器但无法获取ID,改用普通方法', 'yellow'); handleNormalTextarea(_textareaList, jdt, index, TiMuList); } } else { handleNormalTextarea(_textareaList, jdt, index, TiMuList); } } else { logger('无法处理此题型:' + typeName + ',跳过此题', 'red'); setTimeout(() => { doHomeWork(index + 1, TiMuList) }, setting.time); } } } } } function missonExam() { if (localStorage.getItem('GPTJsSetting.isPaused') === 'true') { setTimeout(missonExam, 3000); return; } let $_examtable = $('.mark_table').find('.whiteDiv') let _examCurIdx = null try { let $curLi = $('.mark_table .mark_li_list li.active, .mark_table .mark_li_list li.current') if ($curLi.length) _examCurIdx = parseInt($curLi.text().trim()) - 1 if (!Number.isFinite(_examCurIdx)) { let numMatch = ($_examtable.find('h3.mark_name').text() || '').trim().match(/^(\d+)\s*[.、.]/) if (numMatch) _examCurIdx = parseInt(numMatch[1], 10) - 1 } } catch (_) {} if (!Number.isFinite(_examCurIdx)) _examCurIdx = null if (handleExtraWorkQuestion($_examtable, toNextExam, { index: _examCurIdx, total: null })) return; let _questionFull = tidyStr(($_examtable.find('h3.mark_name').html() || '').trim(), true) || '' let typeName = _questionFull.match(/[(](.*?),.*?分[)]|$/)[1]; let _qType = ({ 单选题: 0, 单项选择题: 0, 单选: 0, 多选题: 1, 多项选择题: 1, 多选: 1, 填空题: 2, 填空: 2, 判断题: 3, 是非题: 3, 判断: 3, 简答题: 4, 简答: 4, 问答题: 4, 名词解释: 4, 论述题: 4, 论述: 4, 计算题: 4, 计算: 4, 分录题: 4, 资料题: 4, 作图题: 4, 其他: 4, 其它: 4, 阅读理解: 4, 阅读: 4, 阅读题: 4, 理解题: 4, 完形填空: 4, 完形: 4, 综合题: 4, 写作题: 5, 翻译题: 6 })[typeName] _currentQuestionMeta = { index: isFinite(_examCurIdx) ? _examCurIdx : null, total: null, typeName: typeName } let _question = extractQuestionFromTitle($_examtable.find('h3.mark_name').first()) let $_ansdom = $_examtable.find('#submitTest').find('.stem_answer') let $subQuestions = getWorkSubQuestions($_ansdom); if ($subQuestions && $subQuestions.length > 0) { logger('检测到复合大题(含有 ' + $subQuestions.length + ' 个子题),开始处理子题...', 'blue'); let parentQuestion = getWorkQuestionText($_examtable); _currentQuestionMeta = { index: _examCurIdx, total: null, typeName: typeName || '阅读理解' }; processSubQuestions(0, $subQuestions, parentQuestion, () => setting.time, () => { toNextExam() }); return; } let _answerTmpArr; let _a = [] function handleStandardExamTextarea(standardTextareas, _question) { logger('检测到标准文本输入区域,尝试回答', 'green'); let jdt = buildPrompt({ type: typeName || '未知题型', question: _question, answer_format: "请根据题目作答" }) getAnswer(4, jdt).then((agrs) => { $.each(standardTextareas, (i, t) => { let _id = $(t).attr('id') || $(t).attr('name') setTimeout(() => { UE.getEditor(_id).setContent(agrs) }, 300) }) logger('自动答题成功,准备切换下一题', 'green') toNextExam() }).catch((agrs) => { if (agrs['c'] == 0) { toNextExam() } }) } if (_qType === undefined) { logger('未知题型: ' + typeName + ',尝试自动识别', 'blue'); let detected = detectStandardQuestionType($_examtable, typeName); _qType = detected.type; if (_qType !== undefined) { logger((detected.source === 'code' ? '根据页面基础题型识别为' : '自动识别为') + getQuestionTypeLabel(_qType), 'green'); } } switch (_qType) { case 0: { _answerTmpArr = $_ansdom.find('.clearfix.answerBg .fl.answer_p') let _answeredIdxE0 = -1 for (let _ai = 0; _ai < _answerTmpArr.length; _ai++) { let _cls = $(_answerTmpArr[_ai]).parent().find('span').attr('class') || '' if (_cls.indexOf('check_answer') !== -1) { _answeredIdxE0 = _ai; break } } if (_answeredIdxE0 !== -1 && !isRedoMode()) { logger('此题已作答,准备切换下一题', 'green') toNextExam() break } if (_answeredIdxE0 !== -1 && isRedoMode()) { logger('此题已作答,重做模式下重新作答', 'blue') $(_answerTmpArr[_answeredIdxE0]).parent().click() } let mergedAnswers = []; _answerTmpArr.each(function () { var answerText = $(this).text().trim(); mergedAnswers.push(answerText); }); _question = buildPrompt({ type: '单选题', question: _question, options: mergedAnswers }) getAnswer(_qType, _question).then((agrs) => { $.each(_answerTmpArr, (i, t) => { _a.push(tidyStr($(t).html())) }) if (localStorage.getItem('GPTJsSetting.alterTitle') === 'true') { let timuele = $_examtable.find('h3.mark_name') appendAnswerToTitle(timuele, agrs) } let _i = matchSingleOptionIndex(_a, agrs) if (_i == -1) { logger('AI未能完美匹配正确答案,请尝试更换更高级模型或手动选择,跳过此题', 'red') setTimeout(toNextExam, 5000) } else { setTimeout(() => { if (($(_answerTmpArr[_i]).parent().find('span').attr('class') || '').indexOf('check_answer') == -1) { if (localStorage.getItem('GPTJsSetting.goodStudent') === 'true') { $(_answerTmpArr[_i]).parent().find('span').css('font-weight', 'bold'); } else { setTimeout(() => { $(_answerTmpArr[_i]).parent().click() }, 300) } logger('自动答题成功,准备切换下一题', 'green') toNextExam() } else { logger('此题已作答,准备切换下一题', 'green') toNextExam() } }, 300) } }).catch((agrs) => { if (agrs['c'] == 0) { toNextExam() } }) } break case 1: { _answerTmpArr = $_ansdom.find('.clearfix.answerBg .fl.answer_p') let _alreadyAnsweredE1 = $_ansdom.find('.clearfix.answerBg span.check_answer_dx, .clearfix.answerBg span.check_answer').length > 0 if (_alreadyAnsweredE1 && !isRedoMode()) { logger('此题已作答,准备切换下一题', 'green') toNextExam() break } if (_alreadyAnsweredE1 && isRedoMode()) { logger('此题已作答,重做模式下重新作答', 'blue') $.each(_answerTmpArr, function (_i2, _t2) { var _cls2 = $(_t2).parent().find('span').attr('class') || '' if (_cls2.indexOf('check_answer') !== -1) { $(_t2).parent().click() } }) } let mergedAnswers = []; _answerTmpArr.each(function () { var answerText = $(this).text().trim(); mergedAnswers.push(answerText); }); _question = buildPrompt({ type: '多选题', question: _question, options: mergedAnswers, answer_format: "用'" + ANSWER_SEPARATOR + "'分割多个答案" }) getAnswer(_qType, _question).then((agrs) => { if (localStorage.getItem('GPTJsSetting.alterTitle') === 'true') { let timuele = $_examtable.find('h3.mark_name') appendAnswerToTitle(timuele, agrs) } { let _multiOptions = [] $.each(_answerTmpArr, (i, t) => { _multiOptions.push(tidyStr($(t).html())) }) let matchedIndexes = matchMultiOptionIndexes(_multiOptions, agrs) if (matchedIndexes.length === 0) { logger('AI未能完美匹配正确答案,请尝试更换更高级模型或手动选择,跳过此题', 'red') setTimeout(toNextExam, 5000) return } matchedIndexes.forEach((idx) => { if (localStorage.getItem('GPTJsSetting.goodStudent') === 'true') { $(_answerTmpArr[idx]).parent().find('span').css('font-weight', 'bold'); } else { setTimeout(() => { $(_answerTmpArr[idx]).parent().click() }, 300) } }) logger('自动答题成功,准备切换下一题', 'green') toNextExam() } }).catch((agrs) => { if (agrs['c'] == 0) { toNextExam() } }) } break case 2: { let _textareaList = $_ansdom.find('.Answer .divText .subEditor textarea') if (!_textareaList || _textareaList.length === 0) { _textareaList = findAnswerTextareas($_ansdom) } let _alreadyAnsweredE2 = false $.each(_textareaList, function (_i2, _t2) { let _eid = $(_t2).attr('id') || $(_t2).attr('name') try { if (_eid && typeof UE !== 'undefined' && UE.getEditor(_eid) && UE.getEditor(_eid).getContent && UE.getEditor(_eid).getContent() !== '') { _alreadyAnsweredE2 = true } } catch (_e) {} }) if (_alreadyAnsweredE2 && !isRedoMode()) { logger('此题已作答,准备切换下一题', 'green') toNextExam() break } if (_alreadyAnsweredE2 && isRedoMode()) { logger('此题已作答,重做模式下重新作答', 'blue') $.each(_textareaList, function (_i2, _t2) { let _eid = $(_t2).attr('id') || $(_t2).attr('name') try { if (_eid && UE.getEditor(_eid)) UE.getEditor(_eid).setContent('') } catch (_e) {} }) } _question = buildPrompt({ type: '填空题', question: _question, answer_format: "用'" + ANSWER_SEPARATOR + "'分割多个答案" }); getAnswer(_qType, _question).then((agrs) => { let _answerTmpArr = parseWorkTextAnswer(agrs, _textareaList.length, true) $.each(_textareaList, (i, t) => { let _id = $(t).attr('id') || $(t).attr('name') setTimeout(() => { try { UE.getEditor(_id).setContent(_answerTmpArr[i] === undefined ? '' : _answerTmpArr[i]) } catch (e) {} }, 300) }) logger('自动答题成功,准备切换下一题', 'green') toNextExam() }).catch((agrs) => { if (agrs && agrs['c'] == 0) { toNextExam() } }) break } case 3: { _answerTmpArr = $_ansdom.find('.clearfix.answerBg .fl.answer_p') let _answeredIdxE3 = -1 for (let _ai = 0; _ai < _answerTmpArr.length; _ai++) { let _cls = $(_answerTmpArr[_ai]).parent().find('span').attr('class') || '' if (_cls.indexOf('check_answer') !== -1) { _answeredIdxE3 = _ai; break } } if (_answeredIdxE3 !== -1 && !isRedoMode()) { logger('此题已作答,准备切换下一题', 'green') toNextExam() break } if (_answeredIdxE3 !== -1 && isRedoMode()) { logger('此题已作答,重做模式下重新作答', 'blue') $(_answerTmpArr[_answeredIdxE3]).parent().click() } _question = buildPrompt({ type: '判断题', question: _question, answer_format: "只回答正确或错误" }); $.each(_answerTmpArr, (i, t) => { _a.push($(t).text().trim()) }) getAnswer(_qType, _question).then((agrs) => { if (localStorage.getItem('GPTJsSetting.alterTitle') === 'true') { let timuele = $_examtable.find('h3.mark_name') appendAnswerToTitle(timuele, agrs) } let judgeResult = parseJudgeAnswer(agrs) if (judgeResult === null) { logger('答案匹配出错,准备切换下一题', 'red') toNextExam() return } let _i = findJudgeOptionIndex(_a, judgeResult === 'true') if (_i === -1) { logger('未匹配到正确选项,跳过', 'red') toNextExam() return } if (($(_answerTmpArr[_i]).parent().find('span').attr('class') || '').indexOf('check_answer') == -1) { if (localStorage.getItem('GPTJsSetting.goodStudent') === 'true') { setTimeout(() => { $(_answerTmpArr[_i]).parent().find('span').css('font-weight', 'bold'); }, 300) } else { $(_answerTmpArr[_i]).parent().click() } logger('自动答题成功,准备切换下一题', 'green') toNextExam() } else { logger('此题已作答,准备切换下一题', 'green') toNextExam() } }).catch((agrs) => { if (agrs['c'] == 0) { toNextExam() } }) break } case 4: { let _answerEle = findAnswerTextareas($_ansdom) if (!_answerEle || _answerEle.length === 0) { toNextExam(); break } let _isAnsweredE4 = false $.each(_answerEle, function (i, t) { let _eid = $(t).attr('id') || $(t).attr('name') try { if (_eid && UE.getEditor(_eid) && UE.getEditor(_eid).getContent && UE.getEditor(_eid).getContent() !== '') _isAnsweredE4 = true } catch (e) {} }) if (_isAnsweredE4 && !isRedoMode()) { logger('此题已作答,准备切换下一题', 'green') toNextExam() break } let jdt = buildPrompt({ type: typeName || '简答题', question: _question, answer_format: "用50字简要回答" }) getAnswer(_qType, jdt).then((agrs) => { if (localStorage.getItem('GPTJsSetting.alterTitle') === 'true') { let timuele = $_examtable.find('h3.mark_name') appendAnswerToTitle(timuele, agrs) } $.each(_answerEle, (i, t) => { let _id = $(t).attr('id') || $(t).attr('name') setTimeout(() => { try { UE.getEditor(_id).setContent(agrs) } catch (e) {} }, 300 + i * 200); }); setTimeout(toNextExam, 300 + 200 * _answerEle.length); }).catch(() => { toNextExam(); }); } break case 5: { let _answerEle = findAnswerTextareas($_ansdom) if (!_answerEle || _answerEle.length === 0) { toNextExam(); break } let _isAnsweredE5 = false $.each(_answerEle, function (i, t) { let _eid = $(t).attr('id') || $(t).attr('name') try { if (_eid && UE.getEditor(_eid) && UE.getEditor(_eid).getContent && UE.getEditor(_eid).getContent() !== '') _isAnsweredE5 = true } catch (e) {} }) if (_isAnsweredE5 && !isRedoMode()) { logger('此题已作答,准备切换下一题', 'green') toNextExam() break } let jdt = buildPrompt({ type: typeName || '写作题', question: _question, answer_format: "用英文根据题目进行写作" }) getAnswer(_qType, jdt).then((agrs) => { if (localStorage.getItem('GPTJsSetting.alterTitle') === 'true') { let timuele = $_examtable.find('h3.mark_name') appendAnswerToTitle(timuele, agrs) } $.each(_answerEle, (i, t) => { let _id = $(t).attr('id') || $(t).attr('name') setTimeout(() => { try { UE.getEditor(_id).setContent(agrs) } catch (e) {} }, 300 + i * 200); }); setTimeout(toNextExam, 300 + 200 * _answerEle.length); }).catch(() => { toNextExam(); }); } break case 6: { let _answerEle = findAnswerTextareas($_ansdom) if (!_answerEle || _answerEle.length === 0) { toNextExam(); break } let _isAnsweredE6 = false $.each(_answerEle, function (i, t) { let _eid = $(t).attr('id') || $(t).attr('name') try { if (_eid && UE.getEditor(_eid) && UE.getEditor(_eid).getContent && UE.getEditor(_eid).getContent() !== '') _isAnsweredE6 = true } catch (e) {} }) if (_isAnsweredE6 && !isRedoMode()) { logger('此题已作答,准备切换下一题', 'green') toNextExam() break } let jdt = buildPrompt({ type: typeName || '翻译题', question: _question, answer_format: "中文英文互译" }) getAnswer(_qType, jdt).then((agrs) => { if (localStorage.getItem('GPTJsSetting.alterTitle') === 'true') { let timuele = $_examtable.find('h3.mark_name') appendAnswerToTitle(timuele, agrs) } $.each(_answerEle, (i, t) => { let _id = $(t).attr('id') || $(t).attr('name') setTimeout(() => { try { UE.getEditor(_id).setContent(agrs) } catch (e) {} }, 300 + i * 200); }); setTimeout(toNextExam, 300 + 200 * _answerEle.length); }).catch(() => { toNextExam(); }); } break default: { if (_qType === undefined) { logger('无法识别题型:' + typeName + ',跳过此题', 'red') toNextExam() } else { let standardTextareas = $_ansdom.find('.Answer .divText .subEditor textarea'); let richEditors = $_ansdom.find('.Answer .divText .edui-editor'); let editorTextareas = $_ansdom.find('textarea[name^="answerEditor"]'); if (editorTextareas && editorTextareas.length > 0) { logger('检测到材料题富文本编辑器,尝试回答', 'green'); let editorId = $(editorTextareas[0]).attr('id'); if (editorId) { let jdt = buildPrompt({ type: '材料题', question: _question, answer_format: "请根据材料详细回答" }) getAnswer(4, jdt).then((agrs) => { setTimeout(() => { UE.getEditor(editorId).setContent(agrs) }, 300); logger('材料题自动答题成功,准备切换下一题', 'green'); toNextExam(); }).catch((agrs) => { if (agrs['c'] == 0) { toNextExam(); } }); } else { logger('找到材料题编辑器但无法获取ID,尝试其他方法', 'yellow'); handleStandardExamTextarea(standardTextareas, _question); } } else if (standardTextareas && standardTextareas.length > 0) { handleStandardExamTextarea(standardTextareas, _question); } else if (richEditors && richEditors.length > 0) { logger('检测到富文本编辑器,尝试查找编辑器ID', 'green'); let editorScripts = $('script:contains("UE.getEditor")'); let editorIdMatch = null; if (editorScripts && editorScripts.length > 0) { let scriptContent = editorScripts.text(); let matches = scriptContent.match(/UE\.getEditor\(['"](.*?)['"]/); if (matches && matches.length > 1) { editorIdMatch = matches[1]; logger('从脚本中发现编辑器ID: ' + editorIdMatch, 'green'); } } if (editorIdMatch) { let jdt = buildPrompt({ type: '材料题', question: _question, answer_format: "请根据材料详细回答" }) getAnswer(4, jdt).then((agrs) => { setTimeout(() => { UE.getEditor(editorIdMatch).setContent(agrs) }, 300); logger('使用脚本找到的编辑器ID回答成功,准备切换下一题', 'green'); toNextExam(); }).catch((agrs) => { if (agrs['c'] == 0) { toNextExam(); } }); } else { logger('无法找到有效的编辑器ID,跳过此题', 'red'); toNextExam(); } } else { logger('无法处理此题型:' + typeName + ',跳过此题', 'red'); toNextExam(); } } } } } function toNextExam() { if (localStorage.getItem('GPTJsSetting.examTurn') === 'true') { let $_examtable = $('.mark_table').find('.whiteDiv') let $nextbtn = $_examtable.find('.nextDiv a.jb_btn') setTimeout(() => { $nextbtn.click() }, setting.examTurnTime ? 2000 + (Math.floor(Math.random() * 5 + 1) * 1000) : 2000) } else { logger('用户设置不自动跳转下一题,请手动点击', 'blue') } } function missonExamPreview() { logger('进入整卷预览页面,开始处理考试', 'green') let TiMuList = $('.mark_table').find('.questionLi') if (!TiMuList || TiMuList.length === 0) { logger('未解析到题目,请确认页面已渲染', 'red') return } logger('共解析到 ' + TiMuList.length + ' 道题', 'blue') doExamPreview(0, TiMuList) } function getExamPreviewDelay() { let base = (setting && setting.time) ? setting.time : 2500 return base + Math.floor(Math.random() * 1500) } function getExamPreviewType($timu) { let typeMap = { 单选题: 0, 单项选择题: 0, 单选: 0, 多选题: 1, 多项选择题: 1, 多选: 1, 填空题: 2, 填空: 2, 判断题: 3, 是非题: 3, 判断: 3, 简答题: 4, 简答: 4, 问答题: 4, 名词解释: 4, 论述题: 4, 论述: 4, 计算题: 4, 计算: 4, 分录题: 4, 资料题: 4, 作图题: 4, 其他: 4, 其它: 4, 阅读理解: 4, 阅读: 4, 阅读题: 4, 理解题: 4, 完形填空: 4, 完形: 4, 综合题: 4, 写作题: 5, 翻译题: 6 } let typeName = $timu.attr('typename') if (!typeName) { let prefixText = $timu.find('.colorShallow').text() || $timu.find('.mark_name').text() || '' let m = prefixText.match(/[((]([^)),,]+)[)),,]/) if (m) typeName = m[1].trim() } if (typeName && typeMap[typeName] !== undefined) { return { type: typeMap[typeName], typeName: typeName } } let detected = detectStandardQuestionType($timu, typeName) if (detected.type !== undefined) { return { type: detected.type, typeName: typeName || getQuestionTypeLabel(detected.type) } } return { type: undefined, typeName: typeName || '未知' } } function getExamPreviewPageWindow() { return typeof unsafeWindow !== 'undefined' ? unsafeWindow : window } function getExamPreviewQid($timu) { if (!$timu || !$timu.length) return '' let qid = $timu.attr('data') || $timu.find('input[name="questionId"], input.questionId, .questionId').first().val() if (!qid) { let m = String($timu.attr('id') || '').match(/(\d+)$/) if (m) qid = m[1] } return qid ? String(qid).trim() : '' } function isExamPreviewCardAnswered($timu) { let qid = getExamPreviewQid($timu) if (!qid) return true let $card = $('#answerSheet' + qid) return !$card.length || $card.hasClass('active') } function waitExamPreviewIdle(timeoutMs) { let limit = timeoutMs || 6000 let pageWin = getExamPreviewPageWindow() return new Promise(function (resolve) { let startAt = Date.now() function check() { if (!pageWin.submitOnce || Date.now() - startAt >= limit) { resolve() return } setTimeout(check, 100) } check() }) } function setExamPreviewEditors($editors, values) { let pageWin = getExamPreviewPageWindow() let tasks = [] $.each($editors, function (i, t) { let _id = $(t).attr('id') || $(t).attr('name') let val = Array.isArray(values) ? (values[i] !== undefined ? values[i] : (values[values.length - 1] || '')) : String(values == null ? '' : values) tasks.push(new Promise(function (resolve) { let done = false function finish() { if (done) return done = true resolve() } setTimeout(function () { try { let ue = _id && pageWin.UE && pageWin.UE.getEditor ? pageWin.UE.getEditor(_id) : null if (ue && typeof ue.setContent === 'function') { let writeAndSync = function () { try { ue.setContent(val) if (typeof ue.sync === 'function') ue.sync() } catch (_) {} $(t).val(val) finish() } if (ue.isReady || typeof ue.ready !== 'function') { writeAndSync() } else { let timer = setTimeout(writeAndSync, 4000) ue.ready(function () { clearTimeout(timer) writeAndSync() }) } return } } catch (_) {} $(t).val(val) finish() }, 150 + i * 120) })) }) return Promise.all(tasks) } function saveExamPreviewQuestion($timu) { let pageWin = getExamPreviewPageWindow() let qid = getExamPreviewQid($timu) return waitExamPreviewIdle(6000).then(function () { if ($('#answerMode').val() != '1' || typeof pageWin.submitForm !== 'function') return false return new Promise(function (resolve) { let finished = false let timer = setTimeout(function () { if (finished) return finished = true waitExamPreviewIdle(3000).then(function () { resolve(false) }) }, 8000) function done(ok) { if (finished) return finished = true clearTimeout(timer) resolve(ok) } try { let $targetDiv = (qid && $('#sigleQuestionDiv_' + qid).length) ? $('#sigleQuestionDiv_' + qid) : $timu pageWin.submitForm(true, $targetDiv, function () { try { $targetDiv.find('.saveButtonClass').hide() if (typeof pageWin.clearUnSaveBtn === 'function') pageWin.clearUnSaveBtn() if (qid && typeof pageWin.changeQuestionCardColor === 'function') pageWin.changeQuestionCardColor(qid) $('.sub_que_div').css('pointer-events', 'auto') } catch (_) {} done(true) }) setTimeout(function () { if (!finished && !pageWin.submitOnce) { if (qid && typeof pageWin.changeQuestionCardColor === 'function') { try { pageWin.changeQuestionCardColor(qid) } catch (_) {} } done(false) } }, 600) } catch (_) { done(false) } }) }) } function doExamPreview(index, TiMuList) { if (localStorage.getItem('GPTJsSetting.isPaused') === 'true') { setTimeout(() => { doExamPreview(index, TiMuList) }, 3000); return; } if (index >= TiMuList.length) { logger('整卷预览答题已完成,请人工核对后手动交卷', 'green') return } if (handleExtraWorkQuestion($(TiMuList[index]), () => { saveExamPreviewQuestion($(TiMuList[index])).then(() => { doExamPreview(index + 1, TiMuList) }) }, { index: index, total: TiMuList.length })) return; let $subQuestions = getWorkSubQuestions($(TiMuList[index])); if ($subQuestions && $subQuestions.length > 0) { logger('检测到复合大题(含有 ' + $subQuestions.length + ' 个子题),开始处理子题...', 'blue'); let parentQuestion = getWorkQuestionText($(TiMuList[index])); let currentTypeName = $(TiMuList[index]).attr('typename') || '阅读理解'; _currentQuestionMeta = { index: index, total: TiMuList.length, typeName: currentTypeName }; processSubQuestions(0, $subQuestions, parentQuestion, getExamPreviewDelay, () => { saveExamPreviewQuestion($(TiMuList[index])).then(() => { doExamPreview(index + 1, TiMuList) }) }); return; } let $timu = $(TiMuList[index]) let typeInfo = getExamPreviewType($timu) let _type = typeInfo.type let typeName = typeInfo.typeName let _question = extractQuestionFromTitle($timu.find('.mark_name').first()) let _a = [] let _answerTmpArr, _textareaList let alreadyAnswered = 0 let prefix = '第' + (index + 1) + '题: ' function nextSoon() { setTimeout(function () { doExamPreview(index + 1, TiMuList) }, getExamPreviewDelay()) } function nextFast() { setTimeout(function () { doExamPreview(index + 1, TiMuList) }, 30) } function skipAnsweredOrSync() { if (!isExamPreviewCardAnswered($timu)) { logger(prefix + '已有答案但未保存,正在补存...', 'blue') saveExamPreviewQuestion($timu).then(nextFast) } else { logger(prefix + '已作答,跳过', 'green') nextFast() } } _currentQuestionMeta = { index: index, total: TiMuList.length, typeName: typeName } if (_type === undefined) { logger(prefix + '无法识别题型(' + typeName + '),跳过此题', 'red') return nextSoon() } switch (_type) { case 0: { _answerTmpArr = $timu.find('.answerBg .answer_p') if (!_answerTmpArr || _answerTmpArr.length === 0) { logger(prefix + '未找到选项,跳过', 'red') return nextSoon() } let mergedAnswers = [] _answerTmpArr.each(function () { mergedAnswers.push($(this).text().trim()) }) let prompt = buildPrompt({ type: '单选题', question: _question, options: mergedAnswers }) for (let i = 0; i < _answerTmpArr.length; i++) { let cls = $(_answerTmpArr[i]).parent().find('span').attr('class') || '' if (cls.indexOf('check_answer') !== -1) { if (!isRedoMode()) { alreadyAnswered = 1 } else { logger(prefix + '已作答,重做模式下重新作答', 'blue') $(_answerTmpArr[i]).parent().click() } break } } if (alreadyAnswered) return skipAnsweredOrSync() getAnswer(_type, prompt).then(function (agrs) { $.each(_answerTmpArr, function (i, t) { _a.push(tidyStr($(t).html())) }) if (localStorage.getItem('GPTJsSetting.alterTitle') === 'true') { let timuele = $timu.find('.mark_name') appendAnswerToTitle(timuele, agrs) } let _i = matchSingleOptionIndex(_a, agrs) if (_i === -1) { logger(prefix + 'AI无法完美匹配正确答案,请手动选择', 'red') return nextSoon() } waitExamPreviewIdle(6000).then(function () { let cls = $(_answerTmpArr[_i]).parent().find('span').attr('class') || '' if (localStorage.getItem('GPTJsSetting.goodStudent') === 'true') { if (cls.indexOf('check_answer') === -1) { $(_answerTmpArr[_i]).parent().find('span').css('font-weight', 'bold') } logger(prefix + '自动答题成功', 'green') return nextSoon() } if (cls.indexOf('check_answer') === -1) { $(_answerTmpArr[_i]).parent().click() } setTimeout(function () { waitExamPreviewIdle(6000).then(function () { let ensureSaved = !isExamPreviewCardAnswered($timu) ? saveExamPreviewQuestion($timu) : Promise.resolve() ensureSaved.then(function () { logger(prefix + '自动答题成功', 'green') nextSoon() }) }) }, 200) }) }).catch(function () { nextSoon() }) break } case 1: { _answerTmpArr = $timu.find('.answerBg .answer_p') if (!_answerTmpArr || _answerTmpArr.length === 0) { logger(prefix + '未找到选项,跳过', 'red') return nextSoon() } let mergedAnswers = [] _answerTmpArr.each(function () { mergedAnswers.push($(this).text().trim()) }) let prompt = buildPrompt({ type: '多选题', question: _question, options: mergedAnswers, answer_format: "用'" + ANSWER_SEPARATOR + "'分割多个答案" }) for (let i = 0; i < _answerTmpArr.length; i++) { let cls = $(_answerTmpArr[i]).parent().find('span').attr('class') || '' if (cls.indexOf('check_answer') !== -1) { if (!isRedoMode()) { alreadyAnswered = 1 break } else { logger(prefix + '已作答,重做模式下取消旧答案', 'blue') $(_answerTmpArr[i]).parent().click() } } } if (alreadyAnswered) return skipAnsweredOrSync() getAnswer(_type, prompt).then(function (agrs) { if (localStorage.getItem('GPTJsSetting.alterTitle') === 'true') { let timuele = $timu.find('.mark_name') appendAnswerToTitle(timuele, agrs) } let _multiOptions = [] $.each(_answerTmpArr, function (i, t) { _multiOptions.push(tidyStr($(t).html())) }) let matchedIndexes = matchMultiOptionIndexes(_multiOptions, agrs) if (matchedIndexes.length === 0) { logger(prefix + 'AI无法完美匹配正确答案,请手动选择', 'red') return nextSoon() } waitExamPreviewIdle(6000).then(function () { let isGoodStudent = localStorage.getItem('GPTJsSetting.goodStudent') === 'true' matchedIndexes.forEach(function (idx) { if (isGoodStudent) { $(_answerTmpArr[idx]).parent().find('span').css('font-weight', 'bold') } else { let cls = $(_answerTmpArr[idx]).parent().find('span').attr('class') || '' if (cls.indexOf('check_answer_dx') === -1) { $(_answerTmpArr[idx]).parent().click() } } }) if (isGoodStudent) { logger(prefix + '自动答题成功', 'green') return nextSoon() } setTimeout(function () { waitExamPreviewIdle(6000).then(function () { let ensureSaved = !isExamPreviewCardAnswered($timu) ? saveExamPreviewQuestion($timu) : Promise.resolve() ensureSaved.then(function () { logger(prefix + '自动答题成功', 'green') nextSoon() }) }) }, 650) }) }).catch(function () { nextSoon() }) break } case 2: { _textareaList = $timu.find('textarea[name^="answerEditor"]') if (!_textareaList || _textareaList.length === 0) { _textareaList = $timu.find('.subEditor textarea') } if (!_textareaList || _textareaList.length === 0) { logger(prefix + '未找到填空文本框,跳过', 'red') return nextSoon() } let pageWin = getExamPreviewPageWindow() let isAnswered = false $.each(_textareaList, function (i, t) { let _id = $(t).attr('id') || $(t).attr('name') try { let ue = _id && pageWin.UE && pageWin.UE.getEditor ? pageWin.UE.getEditor(_id) : null if ((ue && ue.getContent && ue.getContent() !== '') || String($(t).val() || '').trim() !== '') { isAnswered = true } } catch (e) {} }) if (isAnswered && !isRedoMode()) return skipAnsweredOrSync() let prompt = buildPrompt({ type: '填空题', question: _question, answer_format: "用'" + ANSWER_SEPARATOR + "'分割多个答案" }) getAnswer(_type, prompt).then(function (agrs) { let parts = parseWorkTextAnswer(agrs, _textareaList.length, true) setExamPreviewEditors(_textareaList, parts).then(function () { return saveExamPreviewQuestion($timu) }).then(function () { logger(prefix + '自动答题成功', 'green') nextSoon() }) }).catch(function () { nextSoon() }) break } case 3: { _answerTmpArr = $timu.find('.answerBg .answer_p') if (!_answerTmpArr || _answerTmpArr.length === 0) { logger(prefix + '未找到判断选项,跳过', 'red') return nextSoon() } $.each(_answerTmpArr, function (i, t) { _a.push($(t).text().trim()) }) for (let i = 0; i < _answerTmpArr.length; i++) { let cls = $(_answerTmpArr[i]).parent().find('span').attr('class') || '' if (cls.indexOf('check_answer') !== -1) { if (!isRedoMode()) { alreadyAnswered = 1 } else { logger(prefix + '已作答,重做模式下重新作答', 'blue') $(_answerTmpArr[i]).parent().click() } break } } if (alreadyAnswered) return skipAnsweredOrSync() let prompt = buildPrompt({ type: '判断题', question: _question, answer_format: "只回答正确或错误" }) getAnswer(_type, prompt).then(function (agrs) { if (localStorage.getItem('GPTJsSetting.alterTitle') === 'true') { let timuele = $timu.find('.mark_name') appendAnswerToTitle(timuele, agrs) } let judgeResult = parseJudgeAnswer(agrs) let _i = judgeResult !== null ? findJudgeOptionIndex(_a, judgeResult === 'true') : -1 if (_i === -1) { logger(prefix + '答案匹配出错,跳过', 'red') return nextSoon() } waitExamPreviewIdle(6000).then(function () { let cls = $(_answerTmpArr[_i]).parent().find('span').attr('class') || '' if (localStorage.getItem('GPTJsSetting.goodStudent') === 'true') { if (cls.indexOf('check_answer') === -1) { $(_answerTmpArr[_i]).parent().find('span').css('font-weight', 'bold') } logger(prefix + '自动答题成功', 'green') return nextSoon() } if (cls.indexOf('check_answer') === -1) { $(_answerTmpArr[_i]).parent().click() } setTimeout(function () { waitExamPreviewIdle(6000).then(function () { let ensureSaved = !isExamPreviewCardAnswered($timu) ? saveExamPreviewQuestion($timu) : Promise.resolve() ensureSaved.then(function () { logger(prefix + '自动答题成功', 'green') nextSoon() }) }) }, 200) }) }).catch(function () { nextSoon() }) break } case 4: { let _answerEle = findAnswerTextareas($timu) if (!_answerEle || _answerEle.length === 0) { logger(prefix + '未找到答题文本框,跳过', 'red') return nextSoon() } let pageWin = getExamPreviewPageWindow() let isAnswered = false $.each(_answerEle, function (i, t) { let _id = $(t).attr('id') || $(t).attr('name') try { let ue = _id && pageWin.UE && pageWin.UE.getEditor ? pageWin.UE.getEditor(_id) : null if ((ue && ue.getContent && ue.getContent() !== '') || String($(t).val() || '').trim() !== '') { isAnswered = true } } catch (e) {} }) if (isAnswered && !isRedoMode()) return skipAnsweredOrSync() let prompt = buildPrompt({ type: typeName || '简答题', question: _question, answer_format: "用50字简要回答" }) getAnswer(_type, prompt).then(function (agrs) { let parts = parseWorkTextAnswer(agrs, _answerEle.length, false) setExamPreviewEditors(_answerEle, parts).then(function () { return saveExamPreviewQuestion($timu) }).then(function () { logger(prefix + '自动答题成功', 'green') nextSoon() }) }).catch(function () { nextSoon() }) break } case 5: { let _answerEle = findAnswerTextareas($timu) if (!_answerEle || _answerEle.length === 0) { logger(prefix + '未找到答题文本框,跳过', 'red') return nextSoon() } let pageWin = getExamPreviewPageWindow() let isAnswered5 = false $.each(_answerEle, function (i, t) { let _id = $(t).attr('id') || $(t).attr('name') try { let ue = _id && pageWin.UE && pageWin.UE.getEditor ? pageWin.UE.getEditor(_id) : null if ((ue && ue.getContent && ue.getContent() !== '') || String($(t).val() || '').trim() !== '') { isAnswered5 = true } } catch (e) {} }) if (isAnswered5 && !isRedoMode()) return skipAnsweredOrSync() let prompt = buildPrompt({ type: typeName || '写作题', question: _question, answer_format: "用英文根据题目进行写作" }) getAnswer(_type, prompt).then(function (agrs) { let parts = parseWorkTextAnswer(agrs, _answerEle.length, false) setExamPreviewEditors(_answerEle, parts).then(function () { return saveExamPreviewQuestion($timu) }).then(function () { logger(prefix + '自动答题成功', 'green') nextSoon() }) }).catch(function () { nextSoon() }) break } case 6: { let _answerEle = findAnswerTextareas($timu) if (!_answerEle || _answerEle.length === 0) { logger(prefix + '未找到答题文本框,跳过', 'red') return nextSoon() } let pageWin = getExamPreviewPageWindow() let isAnswered6 = false $.each(_answerEle, function (i, t) { let _id = $(t).attr('id') || $(t).attr('name') try { let ue = _id && pageWin.UE && pageWin.UE.getEditor ? pageWin.UE.getEditor(_id) : null if ((ue && ue.getContent && ue.getContent() !== '') || String($(t).val() || '').trim() !== '') { isAnswered6 = true } } catch (e) {} }) if (isAnswered6 && !isRedoMode()) return skipAnsweredOrSync() let prompt = buildPrompt({ type: typeName || '翻译题', question: _question, answer_format: "中文英文互译" }) getAnswer(_type, prompt).then(function (agrs) { let parts = parseWorkTextAnswer(agrs, _answerEle.length, false) setExamPreviewEditors(_answerEle, parts).then(function () { return saveExamPreviewQuestion($timu) }).then(function () { logger(prefix + '自动答题成功', 'green') nextSoon() }) }).catch(function () { nextSoon() }) break } default: { logger(prefix + '无法处理此题型: ' + typeName + ',跳过', 'red') nextSoon() } } } function refreshCourseList() { let _p = parseUrlParams() return new Promise((resolve, reject) => { $.ajax({ url: _l.protocol + '//' + _l.host + '/mycourse/studentstudycourselist?courseId=' + _p['courseid'] + '&chapterId=' + _p['knowledgeid'] + '&clazzid=' + _p['clazzid'] + '&mooc2=1', type: 'GET', dataType: 'html', timeout: 10000, success: function (res) { resolve(res) }, error: function (xhr, status) { reject(new Error(status === 'timeout' ? '课程目录请求超时(10秒)' : '课程目录请求失败(' + (xhr.status || status) + ')')) } }) }) } var _ne21ThinkingCount = 0; function showThinking() { _ne21ThinkingCount++; if (_ne21ThinkingCount === 1) { $('#ne-21thinking', getPanelDocument()).addClass('ne21-active'); } } function hideThinking() { if (_ne21ThinkingCount > 0) _ne21ThinkingCount--; if (_ne21ThinkingCount === 0) { $('#ne-21thinking', getPanelDocument()).removeClass('ne21-active'); } } function buildPrompt(opts) { opts = opts || {} let q = opts.question != null ? String(opts.question) : '' let payloadObj = {} if (opts.type) payloadObj.type = String(opts.type) if (opts.answer_format) payloadObj.answer_format = String(opts.answer_format) payloadObj.question = q if (Array.isArray(opts.options) && opts.options.length > 0) { payloadObj.options = opts.options.map(function (s) { return String(s == null ? '' : s).trim() }) } let payload = JSON.stringify(payloadObj, null, 2) let display = q if (payloadObj.options && payloadObj.options.length) { display += '\n' + payloadObj.options.join('\n') } return { payload: payload, display: display, preserveWhitespace: opts.preserveWhitespace === true } } function processSubQuestions(subIndex, $subQuestions, parentQuestion, getDelay, onComplete, allAnswered = true) { if (localStorage.getItem('GPTJsSetting.isPaused') === 'true') { setTimeout(() => { processSubQuestions(subIndex, $subQuestions, parentQuestion, getDelay, onComplete, allAnswered); }, 3000); return; } if (subIndex >= $subQuestions.length) return onComplete(allAnswered); var $sub = $($subQuestions[subIndex]); var info = getWorkQuestionType($sub); if (info.type === undefined) { var rawType = Number.parseInt($sub.attr('qtype'), 10); if ([0, 1, 2, 3].includes(rawType)) info.type = rawType; else if ([4, 5, 6, 7, 8, 9, 10].includes(rawType)) info.type = 4; else if ($sub.find('.saveSingleSelect').length) info.type = 0; } var question = '[大题背景]\n' + parentQuestion + '\n[小题' + (subIndex + 1) + ']\n' + getWorkQuestionText($sub); runWorkQuestion($sub, info, question, function (success) { var delay = typeof getDelay === 'function' ? getDelay() : setting.time; setTimeout(() => { processSubQuestions(subIndex + 1, $subQuestions, parentQuestion, getDelay, onComplete, allAnswered && success); }, delay); }); } function getAnswer(_t, _q, retryCount = 0) { var preserveWhitespace = Boolean(_q && _q.preserveWhitespace); let _payload, _display if (_q && typeof _q === 'object' && (_q.payload != null || _q.display != null)) { _payload = _q.payload != null ? String(_q.payload) : '' _display = _q.display != null ? String(_q.display) : _payload } else { _payload = _q == null ? '' : String(_q) _display = _payload } let _qPrefix = '' if (_currentQuestionMeta) { var _m = _currentQuestionMeta if (_m.index != null) _qPrefix = '第' + (_m.index + 1) + (_m.total ? '/' + _m.total : '') + '题 ' _qPrefix += '[' + escapeLogText(_m.typeName || '未知') + '] ' } logger(_qPrefix + '题目:' + escapeLogText(_display), 'pink') let _thinkingHtml = 'AI 思考中' + (retryCount > 0 ? '(第' + (retryCount + 1) + '次)' : '') let $thinkingLog = logger(_thinkingHtml, 'gray') return new Promise((resolve, reject) => { let _u = getLearningAccountId() let requestCompleted = false; let longWaitTimer = null; let _intervalMs = Math.min(60000, setting.time !== undefined ? setting.time : 2500) let _nowTs = Date.now() let _waitMs = Math.max(0, _ne21NextAiAllowedAt - _nowTs) _ne21NextAiAllowedAt = Math.max(_nowTs, _ne21NextAiAllowedAt) + _intervalMs if (_waitMs > 0) { updateLogEntry($thinkingLog, '搜题间隔限制,等待 ' + Math.round(_waitMs / 1000) + 's 后发起请求...', 'gray') } var _maxRetries = 3; longWaitTimer = setTimeout(() => { if (!requestCompleted) { requestCompleted = true; if (retryCount >= _maxRetries) { updateLogEntry($thinkingLog, '已重试' + _maxRetries + '次仍未响应,请刷新页面重试', 'red') reject({ 'c': 666 }) return; } updateLogEntry($thinkingLog, '请求超过2.5分钟未响应,正在重新发起请求...(第' + (retryCount + 1) + '次重试)', 'orange') getAnswer(_t, _q, retryCount + 1).then(resolve).catch(reject) } }, 150000 + _waitMs); setTimeout(function () { if (requestCompleted) return; if (_waitMs > 0) { let _resumeHtml = 'AI 思考中' + (retryCount > 0 ? '(第' + (retryCount + 1) + '次)' : '') updateLogEntry($thinkingLog, _resumeHtml, 'gray') } GM_xmlhttpRequest({ method: 'POST', url: getApiHost() + '/api/v1/cx?v=' + GM_info['script']['version'], headers: { 'Content-type': 'application/x-www-form-urlencoded', 'Authorization': '' }, data: 'question=' + encodeURIComponent(_payload) + (_u ? '&u=' + encodeURIComponent(_u) : '') + '&model=' + encodeURIComponent(getSelectedModel()), timeout: 135000, onload: function (xhr) { if (requestCompleted) { logger('收到已超时请求的响应,已忽略', 'gray') return; } requestCompleted = true; clearTimeout(longWaitTimer); if (xhr.status == 200) { let obj = {}; try { obj = $.parseJSON(xhr.responseText) || {}; } catch (_) {} if (!obj.data || typeof obj.data.answer !== 'string') { updateLogEntry($thinkingLog, obj.msg || '服务器返回数据异常', 'red') blockAutoSubmit(); reject({ 'c': 0 }) return; } let _answer = preserveWhitespace ? obj.data.answer : obj.data.answer.replace(/。$/, ''); if (obj.code == 200 && _answer) { updateLogEntry($thinkingLog, "答案:" + escapeLogText(_answer), 'purple') resolve(preserveWhitespace ? _answer : _answer.replace(/^[A-Z]\s*\n\s*/, '').trim()) } else if (obj.msg && _answer != '') { updateLogEntry($thinkingLog, obj.msg, 'red') blockAutoSubmit(); reject({ 'c': 0 }) } else { updateLogEntry($thinkingLog, '暂无答案', 'red') blockAutoSubmit(); reject({ 'c': 0 }) } } else if (xhr.status == 403) { updateLogEntry($thinkingLog, '请求过于频繁,请稍后再试', 'red') reject({ 'c': 403 }) } else if (xhr.status == 500) { updateLogEntry($thinkingLog, 'ChatGPT官方服务器压力过大,请先保存答案后刷新重试', 'red') reject({ 'c': 500 }) } else if (xhr.status == 444) { updateLogEntry($thinkingLog, 'IP异常,已被拉入服务器黑名单,请过几个小时再试', 'red') reject({ 'c': 444 }) } else if (xhr.status == 400) { let obj = {}; try { obj = $.parseJSON(xhr.responseText) || {}; } catch (_) {} updateLogEntry($thinkingLog, obj.msg || '请求参数异常,请稍后重试', 'red') reject({ 'c': 400 }) } else if (xhr.status == 222) { updateLogEntry($thinkingLog, "账户余额不足!", 'red') reject({ 'c': 222 }) } else { updateLogEntry($thinkingLog, '请求异常...,请先保存答案后刷新重试,仍然失败请尝试更换模型或联系售后', 'red') reject({ 'c': 555 }) } }, onerror: function () { if (requestCompleted) return; requestCompleted = true; clearTimeout(longWaitTimer); if (retryCount >= _maxRetries) { updateLogEntry($thinkingLog, '已重试' + _maxRetries + '次仍无法连接服务器,请检查网络后刷新页面重试', 'red') reject({ 'c': 666 }) return; } updateLogEntry($thinkingLog, '无法连接服务器,正在自动重试...(第' + (retryCount + 1) + '次重试)', 'orange') getAnswer(_t, _q, retryCount + 1).then(resolve).catch(reject) }, ontimeout: function () { if (requestCompleted) { return; } requestCompleted = true; clearTimeout(longWaitTimer); if (retryCount >= _maxRetries) { updateLogEntry($thinkingLog, '已重试' + _maxRetries + '次仍超时,请刷新页面重试', 'red') reject({ 'c': 666 }) return; } updateLogEntry($thinkingLog, '请求超时,正在自动重试...(第' + (retryCount + 1) + '次重试)', 'orange') getAnswer(_t, _q, retryCount + 1).then(resolve).catch(reject) } }); }, _waitMs); }) } function doWork(index, doms, dom) { var doc = getAccessibleFrameDocument(dom); if (!doc) { logger('测验框架暂不可访问,请等待加载完成后重试', 'orange'); return; } $frame_c = $(doc); var TiMuList = $frame_c.find('.TiMu, .questionLi').filter(function () { return !$(this).parents('.TiMu, .questionLi').length; }); if (!TiMuList.length) { logger('未找到测验题目,请检查页面是否加载完成', 'red'); return; } _ne21AutoSubmitBlocked = false; $subBtn = $frame_c.find('.ZY_sub .btnSubmit, .btnBlueSubmit, #btnBlueSubmit').first(); $saveBtn = $frame_c.find('.ZY_sub .btnSave, .btnGraySave, #btnGraySave').first(); startDoWork(index, doms, 0, TiMuList, dom); } function startDoWork(index, doms, c, TiMuList, workFrame) { if (localStorage.getItem('GPTJsSetting.isPaused') === 'true') { setTimeout(() => { startDoWork(index, doms, c, TiMuList, workFrame); }, 3000); return; } if (c >= TiMuList.length) { finishDesktopWork(index, doms, workFrame); return; } var $item = $(TiMuList[c]); var info = getWorkQuestionType($item); _currentQuestionMeta = { index: c, total: TiMuList.length, typeName: info.typeName }; runWorkQuestion($item, info, getWorkQuestionText($item), function () { setTimeout(() => { startDoWork(index, doms, c + 1, TiMuList, workFrame); }, setting.time); }); } function saveDesktopWork(doc, save) { return new Promise(function (resolve, reject) { var win = doc.defaultView, jq = win.jQuery || win.$; var $events = jq && jq(doc); var timer; function finish(error) { clearTimeout(timer); if ($events) $events.off('.ne21WorkSave'); if (error) reject(error); else resolve(); } if (!$events || !$events.on) return reject(new Error('无法监听暂存结果,请手动检查')); $events.on('ajaxSuccess.ne21WorkSave ajaxError.ne21WorkSave', function (event, xhr, settings, data) { if (!settings || !/\/work\/(?:addStudentWork|save|tempSave)/i.test(settings.url || '')) return; if (event.type === 'ajaxError') return finish(new Error('测验暂存请求失败,请手动检查')); try { var result = data || xhr.responseJSON || JSON.parse(xhr.responseText); if (result.status === true || result.status === 1) finish(); else finish(new Error(result.msg || '测验暂存失败,请手动检查')); } catch (error) { finish(error); } }); timer = setTimeout(function () { finish(new Error('暂存结果确认超时,请手动检查')); }, 20000); try { Promise.resolve(save()).catch(finish); } catch (error) { finish(error); } }); } function continueDesktopWork(index, doms) { _mlist.splice(0, 1); _domList.splice(0, 1); setTimeout(() => { startDoCyWork(index + 1, doms); }, 2000); } function getDesktopWorkConfirmPopups(doc) { var popups = [], current = doc && doc.defaultView while (current) { try { current.document.querySelectorAll('#workpop, #confirmSubWin').forEach(function (popup) { if (/确认提交/.test(popup.textContent || '')) popups.push(popup) }) if (current === current.parent) break current = current.parent } catch (_) { break } } return popups } function closeDesktopWorkConfirmPopups(doc, popups) { popups.concat(getDesktopWorkConfirmPopups(doc)).forEach(function (popup) { try { if (/确认提交/.test(popup.textContent || '')) popup.style.display = 'none' } catch (_) {} }) } async function finishDesktopWork(index, doms, workFrame) { var stage = '准备提交'; try { var doc = $frame_c[0], win = doc && doc.defaultView; if (!win) throw new Error('测验页面已被替换,请重新进入测验后重试'); var frame = workFrame || win.frameElement; var initialStatus = $frame_c.find('.testTit_status').text(); var initialDone = $(frame).parent().hasClass('ans-job-finished'); var submit = (localStorage.getItem('GPTJsSetting.sub') === 'true' && !_ne21AutoSubmitBlocked) || localStorage.getItem('GPTJsSetting.force') === 'true'; if (!submit) { stage = '暂存'; await saveDesktopWork(doc, function () { if (typeof win.noSubmit === 'function') return win.noSubmit(); if ($saveBtn.length) return $saveBtn[0].click(); throw new Error('未找到保存入口,请手动保存'); }); logger('暂存成功,继续处理下一项任务;此测验仍待提交', 'orange'); continueDesktopWork(index, doms); return; } stage = '打开提交确认窗口'; if (typeof win.btnBlueSubmit === 'function') await win.btnBlueSubmit(); else if ($subBtn.length) $subBtn[0].click(); else throw new Error('未找到提交入口,请手动提交'); await new Promise(resolve => { setTimeout(resolve, 1500); }); var confirmPopups = getDesktopWorkConfirmPopups(doc); var $confirm = $frame_c.find('#confirmSubWin a.bluebtn, #submitCheckTimes, .submitCheckTimes').first(); stage = '确认提交'; var confirmAccessError = false, inaccessibleResult = false; try { if (typeof win.submitCheckTimes === 'function') await win.submitCheckTimes(); else if ($confirm.length) $confirm[0].click(); else throw new Error('未找到确认提交入口,请手动检查提交状态'); } catch (error) { if (!isCrossOriginAccessError(error)) throw error; confirmAccessError = true; console.warn('[GPTJs] 确认提交入口发生跨域访问,继续检查提交结果', error); } stage = '检查提交结果'; for (var attempts = 0; attempts < 20; attempts++) { var currentDoc = frame ? getAccessibleFrameDocument(frame) : doc; if (!currentDoc) inaccessibleResult = true; var status = currentDoc ? $(currentDoc).find('.testTit_status').text() : ''; var frameDone = $(frame).parent().hasClass('ans-job-finished'); var changed = (currentDoc && currentDoc !== doc) || (currentDoc && status !== initialStatus) || frameDone !== initialDone; if (changed && (/已完成|待批阅/.test(status) || frameDone)) { closeDesktopWorkConfirmPopups(currentDoc, confirmPopups); logger('测验已提交:' + (status || '任务点已完成'), 'green'); continueDesktopWork(index, doms); return; } await new Promise(resolve => { setTimeout(resolve, 1000); }); } var reason = confirmAccessError ? '确认提交入口受到跨域限制,尚未确认提交结果' : inaccessibleResult ? '提交后测验框架暂不可访问,尚未确认提交结果' : '尚未确认提交结果'; logger(reason + ',请手动检查;脚本已暂停此测验,不会重复提交', 'orange'); } catch (error) { console.warn('[GPTJs] 测验' + stage + '失败', error); logger(isCrossOriginAccessError(error) ? '测验' + stage + '受到跨域限制,已暂停自动操作,请手动检查提交状态' : error.message || '测验保存或提交失败,请手动检查', 'red'); } } function switchMission() { _mlist.splice(0, 1) _domList.splice(0, 1) setTimeout(missonStart, 5000) } function decodeHtmlEntities(s) { return s.replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, '&') } function tidyStr(s, keepEntities) { if (s) { let str = s.replace(/<(?!img)[\s\S]*?>/g, "").replace(/^【.*?】\s*/, '').replace(/\s*(\d+\.\d+分)$/, '').trim().replace(/ /g, '').replace(new RegExp(" ", ("gm")), '').replace(/^\s+/, '').replace(/\s+$/, ''); return keepEntities ? str : decodeHtmlEntities(str) } else { return null } } function tidyQuestion(s) { if (s) { let str = s.replace(/<(?!img)[\s\S]*?>/g, "").replace(/^【.*?】\s*/, '').replace(/\s*(\d+\.\d+分)$/, '').replace(/^\d+(?:[..](?!\d)|、)/, '').trim().replace(/ /g, '').replace('javascript:void(0);', '').replace(new RegExp(" ", ("gm")), '').replace(/\r\n?/g, '\n').replace(/[ \t]+\n/g, '\n').replace(/\n[ \t]*\t+[ \t]*/g, '\n').replace(/\t+/g, ' ').replace(/^\s+/, '').replace(/\s+$/, ''); return decodeHtmlEntities(str) } else { return null } } var FONT_TABLE_CACHE_KEY = 'GPTJsSetting.fontTableJson'; var _ne21FontTableMem = null; var _ne21FontTablePromise = null; function isValidFontTable(table) { return !!(table && typeof table === 'object' && table['6e820cc1'] === 19968 && Object.keys(table).length >= 20000); } function fetchFontTableFromHost(host) { return new Promise(function (resolve, reject) { GM_xmlhttpRequest({ method: 'GET', url: host + '/libs/table.json', timeout: 15000, onload: function (xhr) { if (xhr.status < 200 || xhr.status >= 300) { reject(new Error('HTTP ' + xhr.status)); return; } try { var parsed = JSON.parse(xhr.responseText); if (!isValidFontTable(parsed)) { reject(new Error('字体表内容不完整')); return; } resolve({ parsed: parsed, raw: xhr.responseText }); } catch (e) { reject(e); } }, onerror: function () { reject(new Error('网络错误')); }, ontimeout: function () { reject(new Error('请求超时')); } }); }); } function loadDecryptTable() { if (_ne21FontTableMem) return Promise.resolve(_ne21FontTableMem); if (_ne21FontTablePromise) return _ne21FontTablePromise; try { var cachedRaw = GM_getValue(FONT_TABLE_CACHE_KEY, ''); if (cachedRaw) { var cached = JSON.parse(cachedRaw); if (isValidFontTable(cached)) { _ne21FontTableMem = cached; return Promise.resolve(_ne21FontTableMem); } GM_deleteValue(FONT_TABLE_CACHE_KEY); } } catch (_) { try { GM_deleteValue(FONT_TABLE_CACHE_KEY); } catch (_e) { } } var hosts = [getActiveHost()].concat(HOST_CANDIDATES).filter(function (h, idx, arr) { return h && arr.indexOf(h) === idx; }); _ne21FontTablePromise = (async function () { var lastError = null; for (var i = 0; i < hosts.length; i++) { try { var result = await fetchFontTableFromHost(hosts[i]); _ne21FontTableMem = result.parsed; try { GM_setValue(FONT_TABLE_CACHE_KEY, result.raw); } catch (_) { } return _ne21FontTableMem; } catch (e) { lastError = e; } } throw lastError || new Error('加载字体解密表失败'); })().catch(function (err) { _ne21FontTablePromise = null; throw err; }); return _ne21FontTablePromise; } async function decryptFont(targetDoc) { var doc = targetDoc || document; var $root = $(doc); if (!$root.find('.font-cxsecret').length) return; var $tip = $root.find('style:contains(font-cxsecret)'); if (!$tip.length) return; var matchFont = $tip.text().match(/base64,([\w\W]+?)'/); if (!matchFont || !matchFont[1]) return; var font = Typr.parse(base64ToUint8Array(matchFont[1]))[0]; var table = await loadDecryptTable(); var match = {}; for (var i = 19968; i < 40870; i++) { var gid = Typr.U.codeToGlyph(font, i); if (!gid) continue; var path = Typr.U.glyphToPath(font, gid); var hash = md5(JSON.stringify(path)).slice(24); if (table[hash]) match[i] = table[hash]; } $root.find('.font-cxsecret').html(function (index, html) { $.each(match, function (key, value) { key = String.fromCharCode(key); key = new RegExp(key, 'g'); value = String.fromCharCode(value); html = html.replace(key, value); }); return html; }).removeClass('font-cxsecret'); } function base64ToUint8Array(base64) { var data = window.atob(base64); var buffer = new Uint8Array(data.length); for (var i = 0; i < data.length; ++i) { buffer[i] = data.charCodeAt(i); } return buffer; } function __initBundledDeps() { /*! Typr.js + Typr.U.js (photopea/Typr.js) | MIT License */ var Typr = {}; Typr["parse"] = function(buff) { var readFont = function(data2, idx, offset2, tmap2) { var bin2 = Typr["B"]; var T = Typr["T"]; var prsr = { "cmap": T.cmap, "head": T.head, "hhea": T.hhea, "maxp": T.maxp, "hmtx": T.hmtx, "name": T.name, "OS/2": T.OS2, "post": T.post, "loca": T.loca, "kern": T.kern, "glyf": T.glyf, "CFF ": T.CFF, "SVG ": T.SVG }; var obj = { "_data": data2, "_index": idx, "_offset": offset2 }; for (var t in prsr) { var tab = Typr["findTable"](data2, t, offset2); if (tab) { var off = tab[0], tobj = tmap2[off]; if (tobj == null) tobj = prsr[t].parseTab(data2, off, tab[1], obj); obj[t] = tmap2[off] = tobj; } } return obj; }; var bin = Typr["B"]; var data = new Uint8Array(buff); var tmap = {}; var tag = bin.readASCII(data, 0, 4); if (tag == "ttcf") { var offset = 4; var majV = bin.readUshort(data, offset); offset += 2; var minV = bin.readUshort(data, offset); offset += 2; var numF = bin.readUint(data, offset); offset += 4; var fnts = []; for (var i = 0; i < numF; i++) { var foff = bin.readUint(data, offset); offset += 4; fnts.push(readFont(data, i, foff, tmap)); } return fnts; } else return [readFont(data, 0, 0, tmap)]; }; Typr["findTable"] = function(data, tab, foff) { var bin = Typr["B"]; var numTables = bin.readUshort(data, foff + 4); var offset = foff + 12; for (var i = 0; i < numTables; i++) { var tag = bin.readASCII(data, offset, 4); var checkSum = bin.readUint(data, offset + 4); var toffset = bin.readUint(data, offset + 8); var length = bin.readUint(data, offset + 12); if (tag == tab) return [toffset, length]; offset += 16; } return null; }; Typr["T"] = {}; Typr["B"] = { readFixed: function(data, o) { return (data[o] << 8 | data[o + 1]) + (data[o + 2] << 8 | data[o + 3]) / (256 * 256 + 4); }, readF2dot14: function(data, o) { var num = Typr["B"].readShort(data, o); return num / 16384; }, readInt: function(buff, p) { var a = Typr["B"].t.uint8; a[0] = buff[p + 3]; a[1] = buff[p + 2]; a[2] = buff[p + 1]; a[3] = buff[p]; return Typr["B"].t.int32[0]; }, readInt8: function(buff, p) { var a = Typr["B"].t.uint8; a[0] = buff[p]; return Typr["B"].t.int8[0]; }, readShort: function(buff, p) { var a = Typr["B"].t.uint8; a[1] = buff[p]; a[0] = buff[p + 1]; return Typr["B"].t.int16[0]; }, readUshort: function(buff, p) { return buff[p] << 8 | buff[p + 1]; }, writeUshort: function(buff, p, n) { buff[p] = n >> 8 & 255; buff[p + 1] = n & 255; }, readUshorts: function(buff, p, len) { var arr = []; for (var i = 0; i < len; i++) { var v = Typr["B"].readUshort(buff, p + i * 2); arr.push(v); } return arr; }, readUint: function(buff, p) { var a = Typr["B"].t.uint8; a[3] = buff[p]; a[2] = buff[p + 1]; a[1] = buff[p + 2]; a[0] = buff[p + 3]; return Typr["B"].t.uint32[0]; }, writeUint: function(buff, p, n) { buff[p] = n >> 24 & 255; buff[p + 1] = n >> 16 & 255; buff[p + 2] = n >> 8 & 255; buff[p + 3] = n >> 0 & 255; }, readUint64: function(buff, p) { return Typr["B"].readUint(buff, p) * (4294967295 + 1) + Typr["B"].readUint(buff, p + 4); }, readASCII: function(buff, p, l) { var s = ""; for (var i = 0; i < l; i++) s += String.fromCharCode(buff[p + i]); return s; }, writeASCII: function(buff, p, s) { for (var i = 0; i < s.length; i++) buff[p + i] = s.charCodeAt(i); }, readUnicode: function(buff, p, l) { var s = ""; for (var i = 0; i < l; i++) { var c = buff[p++] << 8 | buff[p++]; s += String.fromCharCode(c); } return s; }, _tdec: window["TextDecoder"] ? new window["TextDecoder"]() : null, readUTF8: function(buff, p, l) { var tdec = Typr["B"]._tdec; if (tdec && p == 0 && l == buff.length) return tdec["decode"](buff); return Typr["B"].readASCII(buff, p, l); }, readBytes: function(buff, p, l) { var arr = []; for (var i = 0; i < l; i++) arr.push(buff[p + i]); return arr; }, readASCIIArray: function(buff, p, l) { var s = []; for (var i = 0; i < l; i++) s.push(String.fromCharCode(buff[p + i])); return s; }, t: function() { var ab = new ArrayBuffer(8); return { buff: ab, int8: new Int8Array(ab), uint8: new Uint8Array(ab), int16: new Int16Array(ab), uint16: new Uint16Array(ab), int32: new Int32Array(ab), uint32: new Uint32Array(ab) }; }() }; Typr["T"].CFF = { parseTab: function(data, offset, length) { var bin = Typr["B"]; var CFF = Typr["T"].CFF; data = new Uint8Array(data.buffer, offset, length); offset = 0; var major = data[offset]; offset++; var minor = data[offset]; offset++; var hdrSize = data[offset]; offset++; var offsize = data[offset]; offset++; var ninds = []; offset = CFF.readIndex(data, offset, ninds); var names = []; for (var i = 0; i < ninds.length - 1; i++) names.push(bin.readASCII(data, offset + ninds[i], ninds[i + 1] - ninds[i])); offset += ninds[ninds.length - 1]; var tdinds = []; offset = CFF.readIndex(data, offset, tdinds); var topDicts = []; for (var i = 0; i < tdinds.length - 1; i++) topDicts.push(CFF.readDict(data, offset + tdinds[i], offset + tdinds[i + 1])); offset += tdinds[tdinds.length - 1]; var topdict = topDicts[0]; var sinds = []; offset = CFF.readIndex(data, offset, sinds); var strings = []; for (var i = 0; i < sinds.length - 1; i++) strings.push(bin.readASCII(data, offset + sinds[i], sinds[i + 1] - sinds[i])); offset += sinds[sinds.length - 1]; CFF.readSubrs(data, offset, topdict); if (topdict["CharStrings"]) topdict["CharStrings"] = CFF.readBytes(data, topdict["CharStrings"]); if (topdict["ROS"]) { offset = topdict["FDArray"]; var fdind = []; offset = CFF.readIndex(data, offset, fdind); topdict["FDArray"] = []; for (var i = 0; i < fdind.length - 1; i++) { var dict = CFF.readDict(data, offset + fdind[i], offset + fdind[i + 1]); CFF._readFDict(data, dict, strings); topdict["FDArray"].push(dict); } offset += fdind[fdind.length - 1]; offset = topdict["FDSelect"]; topdict["FDSelect"] = []; var fmt = data[offset]; offset++; if (fmt == 3) { var rns = bin.readUshort(data, offset); offset += 2; for (var i = 0; i < rns + 1; i++) { topdict["FDSelect"].push(bin.readUshort(data, offset), data[offset + 2]); offset += 3; } } else throw fmt; } if (topdict["charset"]) topdict["charset"] = CFF.readCharset(data, topdict["charset"], topdict["CharStrings"].length); CFF._readFDict(data, topdict, strings); return topdict; }, _readFDict: function(data, dict, ss) { var CFF = Typr["T"].CFF; var offset; if (dict["Private"]) { offset = dict["Private"][1]; dict["Private"] = CFF.readDict(data, offset, offset + dict["Private"][0]); if (dict["Private"]["Subrs"]) CFF.readSubrs(data, offset + dict["Private"]["Subrs"], dict["Private"]); } for (var p in dict) if (["FamilyName", "FontName", "FullName", "Notice", "version", "Copyright"].indexOf(p) != -1) dict[p] = ss[dict[p] - 426 + 35]; }, readSubrs: function(data, offset, obj) { obj["Subrs"] = Typr["T"].CFF.readBytes(data, offset); var bias, nSubrs = obj["Subrs"].length + 1; if (false) bias = 0; else if (nSubrs < 1240) bias = 107; else if (nSubrs < 33900) bias = 1131; else bias = 32768; obj["Bias"] = bias; }, readBytes: function(data, offset) { var bin = Typr["B"]; var arr = []; offset = Typr["T"].CFF.readIndex(data, offset, arr); var subrs = [], arl = arr.length - 1, no = data.byteOffset + offset; for (var i = 0; i < arl; i++) { var ari = arr[i]; subrs.push(new Uint8Array(data.buffer, no + ari, arr[i + 1] - ari)); } return subrs; }, tableSE: [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 0, 111, 112, 113, 114, 0, 115, 116, 117, 118, 119, 120, 121, 122, 0, 123, 0, 124, 125, 126, 127, 128, 129, 130, 131, 0, 132, 133, 0, 134, 135, 136, 137, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 138, 0, 139, 0, 0, 0, 0, 140, 141, 142, 143, 0, 0, 0, 0, 0, 144, 0, 0, 0, 145, 0, 0, 146, 147, 148, 149, 0, 0, 0, 0 ], glyphByUnicode: function(cff, code) { for (var i = 0; i < cff["charset"].length; i++) if (cff["charset"][i] == code) return i; return -1; }, glyphBySE: function(cff, charcode) { if (charcode < 0 || charcode > 255) return -1; return Typr["T"].CFF.glyphByUnicode(cff, Typr["T"].CFF.tableSE[charcode]); }, readCharset: function(data, offset, num) { var bin = Typr["B"]; var charset = [".notdef"]; var format = data[offset]; offset++; if (format == 0) { for (var i = 0; i < num; i++) { var first = bin.readUshort(data, offset); offset += 2; charset.push(first); } } else if (format == 1 || format == 2) { while (charset.length < num) { var first = bin.readUshort(data, offset); offset += 2; var nLeft = 0; if (format == 1) { nLeft = data[offset]; offset++; } else { nLeft = bin.readUshort(data, offset); offset += 2; } for (var i = 0; i <= nLeft; i++) { charset.push(first); first++; } } } else throw "error: format: " + format; return charset; }, readIndex: function(data, offset, inds) { var bin = Typr["B"]; var count = bin.readUshort(data, offset) + 1; offset += 2; var offsize = data[offset]; offset++; if (offsize == 1) for (var i = 0; i < count; i++) inds.push(data[offset + i]); else if (offsize == 2) for (var i = 0; i < count; i++) inds.push(bin.readUshort(data, offset + i * 2)); else if (offsize == 3) for (var i = 0; i < count; i++) inds.push(bin.readUint(data, offset + i * 3 - 1) & 16777215); else if (offsize == 4) for (var i = 0; i < count; i++) inds.push(bin.readUint(data, offset + i * 4)); else if (count != 1) throw "unsupported offset size: " + offsize + ", count: " + count; offset += count * offsize; return offset - 1; }, getCharString: function(data, offset, o) { var bin = Typr["B"]; var b0 = data[offset], b1 = data[offset + 1], b2 = data[offset + 2], b3 = data[offset + 3], b4 = data[offset + 4]; var vs = 1; var op = null, val = null; if (b0 <= 20) { op = b0; vs = 1; } if (b0 == 12) { op = b0 * 100 + b1; vs = 2; } if (21 <= b0 && b0 <= 27) { op = b0; vs = 1; } if (b0 == 28) { val = bin.readShort(data, offset + 1); vs = 3; } if (29 <= b0 && b0 <= 31) { op = b0; vs = 1; } if (32 <= b0 && b0 <= 246) { val = b0 - 139; vs = 1; } if (247 <= b0 && b0 <= 250) { val = (b0 - 247) * 256 + b1 + 108; vs = 2; } if (251 <= b0 && b0 <= 254) { val = -(b0 - 251) * 256 - b1 - 108; vs = 2; } if (b0 == 255) { val = bin.readInt(data, offset + 1) / 65535; vs = 5; } o.val = val != null ? val : "o" + op; o.size = vs; }, readCharString: function(data, offset, length) { var end = offset + length; var bin = Typr["B"]; var arr = []; while (offset < end) { var b0 = data[offset], b1 = data[offset + 1], b2 = data[offset + 2], b3 = data[offset + 3], b4 = data[offset + 4]; var vs = 1; var op = null, val = null; if (b0 <= 20) { op = b0; vs = 1; } if (b0 == 12) { op = b0 * 100 + b1; vs = 2; } if (b0 == 19 || b0 == 20) { op = b0; vs = 2; } if (21 <= b0 && b0 <= 27) { op = b0; vs = 1; } if (b0 == 28) { val = bin.readShort(data, offset + 1); vs = 3; } if (29 <= b0 && b0 <= 31) { op = b0; vs = 1; } if (32 <= b0 && b0 <= 246) { val = b0 - 139; vs = 1; } if (247 <= b0 && b0 <= 250) { val = (b0 - 247) * 256 + b1 + 108; vs = 2; } if (251 <= b0 && b0 <= 254) { val = -(b0 - 251) * 256 - b1 - 108; vs = 2; } if (b0 == 255) { val = bin.readInt(data, offset + 1) / 65535; vs = 5; } arr.push(val != null ? val : "o" + op); offset += vs; } return arr; }, readDict: function(data, offset, end) { var bin = Typr["B"]; var dict = {}; var carr = []; while (offset < end) { var b0 = data[offset], b1 = data[offset + 1], b2 = data[offset + 2], b3 = data[offset + 3], b4 = data[offset + 4]; var vs = 1; var key = null, val = null; if (b0 == 28) { val = bin.readShort(data, offset + 1); vs = 3; } if (b0 == 29) { val = bin.readInt(data, offset + 1); vs = 5; } if (32 <= b0 && b0 <= 246) { val = b0 - 139; vs = 1; } if (247 <= b0 && b0 <= 250) { val = (b0 - 247) * 256 + b1 + 108; vs = 2; } if (251 <= b0 && b0 <= 254) { val = -(b0 - 251) * 256 - b1 - 108; vs = 2; } if (b0 == 255) { val = bin.readInt(data, offset + 1) / 65535; vs = 5; throw "unknown number"; } if (b0 == 30) { var nibs = []; vs = 1; while (true) { var b = data[offset + vs]; vs++; var nib0 = b >> 4, nib1 = b & 15; if (nib0 != 15) nibs.push(nib0); if (nib1 != 15) nibs.push(nib1); if (nib1 == 15) break; } var s = ""; var chars = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ".", "e", "e-", "reserved", "-", "endOfNumber"]; for (var i = 0; i < nibs.length; i++) s += chars[nibs[i]]; val = parseFloat(s); } if (b0 <= 21) { var keys = [ "version", "Notice", "FullName", "FamilyName", "Weight", "FontBBox", "BlueValues", "OtherBlues", "FamilyBlues", "FamilyOtherBlues", "StdHW", "StdVW", "escape", "UniqueID", "XUID", "charset", "Encoding", "CharStrings", "Private", "Subrs", "defaultWidthX", "nominalWidthX" ]; key = keys[b0]; vs = 1; if (b0 == 12) { var keys = [ "Copyright", "isFixedPitch", "ItalicAngle", "UnderlinePosition", "UnderlineThickness", "PaintType", "CharstringType", "FontMatrix", "StrokeWidth", "BlueScale", "BlueShift", "BlueFuzz", "StemSnapH", "StemSnapV", "ForceBold", "", "", "LanguageGroup", "ExpansionFactor", "initialRandomSeed", "SyntheticBase", "PostScript", "BaseFontName", "BaseFontBlend", "", "", "", "", "", "", "ROS", "CIDFontVersion", "CIDFontRevision", "CIDFontType", "CIDCount", "UIDBase", "FDArray", "FDSelect", "FontName" ]; key = keys[b1]; vs = 2; } } if (key != null) { dict[key] = carr.length == 1 ? carr[0] : carr; carr = []; } else carr.push(val); offset += vs; } return dict; } }; Typr["T"].cmap = { parseTab: function(data, offset, length) { var obj = { tables: [], ids: {}, off: offset }; data = new Uint8Array(data.buffer, offset, length); offset = 0; var offset0 = offset; var bin = Typr["B"], rU = bin.readUshort, cmap = Typr["T"].cmap; var version = rU(data, offset); offset += 2; var numTables = rU(data, offset); offset += 2; var offs = []; for (var i = 0; i < numTables; i++) { var platformID = rU(data, offset); offset += 2; var encodingID = rU(data, offset); offset += 2; var noffset = bin.readUint(data, offset); offset += 4; var id = "p" + platformID + "e" + encodingID; var tind = offs.indexOf(noffset); if (tind == -1) { tind = obj.tables.length; var subt = {}; offs.push(noffset); var format = subt.format = rU(data, noffset); if (format == 0) subt = cmap.parse0(data, noffset, subt); else if (format == 4) subt = cmap.parse4(data, noffset, subt); else if (format == 6) subt = cmap.parse6(data, noffset, subt); else if (format == 12) subt = cmap.parse12(data, noffset, subt); obj.tables.push(subt); } if (obj.ids[id] != null) throw "multiple tables for one platform+encoding"; obj.ids[id] = tind; } return obj; }, parse0: function(data, offset, obj) { var bin = Typr["B"]; offset += 2; var len = bin.readUshort(data, offset); offset += 2; var lang = bin.readUshort(data, offset); offset += 2; obj.map = []; for (var i = 0; i < len - 6; i++) obj.map.push(data[offset + i]); return obj; }, parse4: function(data, offset, obj) { var bin = Typr["B"], rU = bin.readUshort, rUs = bin.readUshorts; var offset0 = offset; offset += 2; var length = rU(data, offset); offset += 2; var language = rU(data, offset); offset += 2; var segCountX2 = rU(data, offset); offset += 2; var segCount = segCountX2 >>> 1; obj.searchRange = rU(data, offset); offset += 2; obj.entrySelector = rU(data, offset); offset += 2; obj.rangeShift = rU(data, offset); offset += 2; obj.endCount = rUs(data, offset, segCount); offset += segCount * 2; offset += 2; obj.startCount = rUs(data, offset, segCount); offset += segCount * 2; obj.idDelta = []; for (var i = 0; i < segCount; i++) { obj.idDelta.push(bin.readShort(data, offset)); offset += 2; } obj.idRangeOffset = rUs(data, offset, segCount); offset += segCount * 2; obj.glyphIdArray = rUs(data, offset, offset0 + length - offset >>> 1); return obj; }, parse6: function(data, offset, obj) { var bin = Typr["B"]; var offset0 = offset; offset += 2; var length = bin.readUshort(data, offset); offset += 2; var language = bin.readUshort(data, offset); offset += 2; obj.firstCode = bin.readUshort(data, offset); offset += 2; var entryCount = bin.readUshort(data, offset); offset += 2; obj.glyphIdArray = []; for (var i = 0; i < entryCount; i++) { obj.glyphIdArray.push(bin.readUshort(data, offset)); offset += 2; } return obj; }, parse12: function(data, offset, obj) { var bin = Typr["B"], rU = bin.readUint; var offset0 = offset; offset += 4; var length = rU(data, offset); offset += 4; var lang = rU(data, offset); offset += 4; var nGroups = rU(data, offset) * 3; offset += 4; var gps = obj.groups = new Uint32Array(nGroups); for (var i = 0; i < nGroups; i += 3) { gps[i] = rU(data, offset + (i << 2)); gps[i + 1] = rU(data, offset + (i << 2) + 4); gps[i + 2] = rU(data, offset + (i << 2) + 8); } return obj; } }; Typr["T"].glyf = { parseTab: function(data, offset, length, font) { var obj = [], ng = font["maxp"]["numGlyphs"]; for (var g = 0; g < ng; g++) obj.push(null); return obj; }, _parseGlyf: function(font, g) { var bin = Typr["B"]; var data = font["_data"], loca = font["loca"]; if (loca[g] == loca[g + 1]) return null; var offset = Typr["findTable"](data, "glyf", font["_offset"])[0] + loca[g]; var gl = {}; gl.noc = bin.readShort(data, offset); offset += 2; gl.xMin = bin.readShort(data, offset); offset += 2; gl.yMin = bin.readShort(data, offset); offset += 2; gl.xMax = bin.readShort(data, offset); offset += 2; gl.yMax = bin.readShort(data, offset); offset += 2; if (gl.xMin >= gl.xMax || gl.yMin >= gl.yMax) return null; if (gl.noc > 0) { gl.endPts = []; for (var i = 0; i < gl.noc; i++) { gl.endPts.push(bin.readUshort(data, offset)); offset += 2; } var instructionLength = bin.readUshort(data, offset); offset += 2; if (data.length - offset < instructionLength) return null; gl.instructions = bin.readBytes(data, offset, instructionLength); offset += instructionLength; var crdnum = gl.endPts[gl.noc - 1] + 1; gl.flags = []; for (var i = 0; i < crdnum; i++) { var flag = data[offset]; offset++; gl.flags.push(flag); if ((flag & 8) != 0) { var rep = data[offset]; offset++; for (var j = 0; j < rep; j++) { gl.flags.push(flag); i++; } } } gl.xs = []; for (var i = 0; i < crdnum; i++) { var i8 = (gl.flags[i] & 2) != 0, same = (gl.flags[i] & 16) != 0; if (i8) { gl.xs.push(same ? data[offset] : -data[offset]); offset++; } else { if (same) gl.xs.push(0); else { gl.xs.push(bin.readShort(data, offset)); offset += 2; } } } gl.ys = []; for (var i = 0; i < crdnum; i++) { var i8 = (gl.flags[i] & 4) != 0, same = (gl.flags[i] & 32) != 0; if (i8) { gl.ys.push(same ? data[offset] : -data[offset]); offset++; } else { if (same) gl.ys.push(0); else { gl.ys.push(bin.readShort(data, offset)); offset += 2; } } } var x = 0, y = 0; for (var i = 0; i < crdnum; i++) { x += gl.xs[i]; y += gl.ys[i]; gl.xs[i] = x; gl.ys[i] = y; } } else { var ARG_1_AND_2_ARE_WORDS = 1 << 0; var ARGS_ARE_XY_VALUES = 1 << 1; var ROUND_XY_TO_GRID = 1 << 2; var WE_HAVE_A_SCALE = 1 << 3; var RESERVED = 1 << 4; var MORE_COMPONENTS = 1 << 5; var WE_HAVE_AN_X_AND_Y_SCALE = 1 << 6; var WE_HAVE_A_TWO_BY_TWO = 1 << 7; var WE_HAVE_INSTRUCTIONS = 1 << 8; var USE_MY_METRICS = 1 << 9; var OVERLAP_COMPOUND = 1 << 10; var SCALED_COMPONENT_OFFSET = 1 << 11; var UNSCALED_COMPONENT_OFFSET = 1 << 12; gl.parts = []; var flags; do { flags = bin.readUshort(data, offset); offset += 2; var part = { m: { a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0 }, p1: -1, p2: -1 }; gl.parts.push(part); part.glyphIndex = bin.readUshort(data, offset); offset += 2; if (flags & ARG_1_AND_2_ARE_WORDS) { var arg1 = bin.readShort(data, offset); offset += 2; var arg2 = bin.readShort(data, offset); offset += 2; } else { var arg1 = bin.readInt8(data, offset); offset++; var arg2 = bin.readInt8(data, offset); offset++; } if (flags & ARGS_ARE_XY_VALUES) { part.m.tx = arg1; part.m.ty = arg2; } else { part.p1 = arg1; part.p2 = arg2; } if (flags & WE_HAVE_A_SCALE) { part.m.a = part.m.d = bin.readF2dot14(data, offset); offset += 2; } else if (flags & WE_HAVE_AN_X_AND_Y_SCALE) { part.m.a = bin.readF2dot14(data, offset); offset += 2; part.m.d = bin.readF2dot14(data, offset); offset += 2; } else if (flags & WE_HAVE_A_TWO_BY_TWO) { part.m.a = bin.readF2dot14(data, offset); offset += 2; part.m.b = bin.readF2dot14(data, offset); offset += 2; part.m.c = bin.readF2dot14(data, offset); offset += 2; part.m.d = bin.readF2dot14(data, offset); offset += 2; } } while (flags & MORE_COMPONENTS); if (flags & WE_HAVE_INSTRUCTIONS) { var numInstr = bin.readUshort(data, offset); offset += 2; gl.instr = []; for (var i = 0; i < numInstr; i++) { gl.instr.push(data[offset]); offset++; } } } return gl; } }; Typr["T"].head = { parseTab: function(data, offset, length) { var bin = Typr["B"]; var obj = {}; var tableVersion = bin.readFixed(data, offset); offset += 4; obj["fontRevision"] = bin.readFixed(data, offset); offset += 4; var checkSumAdjustment = bin.readUint(data, offset); offset += 4; var magicNumber = bin.readUint(data, offset); offset += 4; obj["flags"] = bin.readUshort(data, offset); offset += 2; obj["unitsPerEm"] = bin.readUshort(data, offset); offset += 2; obj["created"] = bin.readUint64(data, offset); offset += 8; obj["modified"] = bin.readUint64(data, offset); offset += 8; obj["xMin"] = bin.readShort(data, offset); offset += 2; obj["yMin"] = bin.readShort(data, offset); offset += 2; obj["xMax"] = bin.readShort(data, offset); offset += 2; obj["yMax"] = bin.readShort(data, offset); offset += 2; obj["macStyle"] = bin.readUshort(data, offset); offset += 2; obj["lowestRecPPEM"] = bin.readUshort(data, offset); offset += 2; obj["fontDirectionHint"] = bin.readShort(data, offset); offset += 2; obj["indexToLocFormat"] = bin.readShort(data, offset); offset += 2; obj["glyphDataFormat"] = bin.readShort(data, offset); offset += 2; return obj; } }; Typr["T"].hhea = { parseTab: function(data, offset, length) { var bin = Typr["B"]; var obj = {}; var tableVersion = bin.readFixed(data, offset); offset += 4; var keys = [ "ascender", "descender", "lineGap", "advanceWidthMax", "minLeftSideBearing", "minRightSideBearing", "xMaxExtent", "caretSlopeRise", "caretSlopeRun", "caretOffset", "res0", "res1", "res2", "res3", "metricDataFormat", "numberOfHMetrics" ]; for (var i = 0; i < keys.length; i++) { var key = keys[i]; var func = key == "advanceWidthMax" || key == "numberOfHMetrics" ? bin.readUshort : bin.readShort; obj[key] = func(data, offset + i * 2); } return obj; } }; Typr["T"].hmtx = { parseTab: function(data, offset, length, font) { var bin = Typr["B"]; var aWidth = []; var lsBearing = []; var nG = font["maxp"]["numGlyphs"], nH = font["hhea"]["numberOfHMetrics"]; var aw = 0, lsb = 0, i = 0; while (i < nH) { aw = bin.readUshort(data, offset + (i << 2)); lsb = bin.readShort(data, offset + (i << 2) + 2); aWidth.push(aw); lsBearing.push(lsb); i++; } while (i < nG) { aWidth.push(aw); lsBearing.push(lsb); i++; } return { aWidth, lsBearing }; } }; Typr["T"].kern = { parseTab: function(data, offset, length, font) { var bin = Typr["B"], kern = Typr["T"].kern; var version = bin.readUshort(data, offset); if (version == 1) return kern.parseV1(data, offset, length, font); var nTables = bin.readUshort(data, offset + 2); offset += 4; var map = { glyph1: [], rval: [] }; for (var i = 0; i < nTables; i++) { offset += 2; var length = bin.readUshort(data, offset); offset += 2; var coverage = bin.readUshort(data, offset); offset += 2; var format = coverage >>> 8; format &= 15; if (format == 0) offset = kern.readFormat0(data, offset, map); } return map; }, parseV1: function(data, offset, length, font) { var bin = Typr["B"], kern = Typr["T"].kern; var version = bin.readFixed(data, offset); var nTables = bin.readUint(data, offset + 4); offset += 8; var map = { glyph1: [], rval: [] }; for (var i = 0; i < nTables; i++) { var length = bin.readUint(data, offset); offset += 4; var coverage = bin.readUshort(data, offset); offset += 2; var tupleIndex = bin.readUshort(data, offset); offset += 2; var format = coverage & 255; if (format == 0) offset = kern.readFormat0(data, offset, map); } return map; }, readFormat0: function(data, offset, map) { var bin = Typr["B"], rUs = bin.readUshort; var pleft = -1; var nPairs = rUs(data, offset); var searchRange = rUs(data, offset + 2); var entrySelector = rUs(data, offset + 4); var rangeShift = rUs(data, offset + 6); offset += 8; for (var j = 0; j < nPairs; j++) { var left = rUs(data, offset); offset += 2; var right = rUs(data, offset); offset += 2; var value = bin.readShort(data, offset); offset += 2; if (left != pleft) { map.glyph1.push(left); map.rval.push({ glyph2: [], vals: [] }); } var rval = map.rval[map.rval.length - 1]; rval.glyph2.push(right); rval.vals.push(value); pleft = left; } return offset; } }; Typr["T"].loca = { parseTab: function(data, offset, length, font) { var bin = Typr["B"]; var obj = []; var ver = font["head"]["indexToLocFormat"]; var len = font["maxp"]["numGlyphs"] + 1; if (ver == 0) for (var i = 0; i < len; i++) obj.push(bin.readUshort(data, offset + (i << 1)) << 1); if (ver == 1) for (var i = 0; i < len; i++) obj.push(bin.readUint(data, offset + (i << 2))); return obj; } }; Typr["T"].maxp = { parseTab: function(data, offset, length) { var bin = Typr["B"], rU = bin.readUshort; var obj = {}; var ver = bin.readUint(data, offset); offset += 4; obj["numGlyphs"] = rU(data, offset); offset += 2; return obj; } }; Typr["T"].name = { parseTab: function(data, offset, length) { var bin = Typr["B"]; var obj = {}; var format = bin.readUshort(data, offset); offset += 2; var count = bin.readUshort(data, offset); offset += 2; var stringOffset = bin.readUshort(data, offset); offset += 2; var names = [ "copyright", "fontFamily", "fontSubfamily", "ID", "fullName", "version", "postScriptName", "trademark", "manufacturer", "designer", "description", "urlVendor", "urlDesigner", "licence", "licenceURL", "---", "typoFamilyName", "typoSubfamilyName", "compatibleFull", "sampleText", "postScriptCID", "wwsFamilyName", "wwsSubfamilyName", "lightPalette", "darkPalette" ]; var offset0 = offset; var rU = bin.readUshort; for (var i = 0; i < count; i++) { var platformID = rU(data, offset); offset += 2; var encodingID = rU(data, offset); offset += 2; var languageID = rU(data, offset); offset += 2; var nameID = rU(data, offset); offset += 2; var slen = rU(data, offset); offset += 2; var noffset = rU(data, offset); offset += 2; var soff = offset0 + count * 12 + noffset; var str; if (false) { } else if (platformID == 0) str = bin.readUnicode(data, soff, slen / 2); else if (platformID == 3 && encodingID == 0) str = bin.readUnicode(data, soff, slen / 2); else if (encodingID == 0) str = bin.readASCII(data, soff, slen); else if (encodingID == 1) str = bin.readUnicode(data, soff, slen / 2); else if (encodingID == 3) str = bin.readUnicode(data, soff, slen / 2); else if (encodingID == 4) str = bin.readUnicode(data, soff, slen / 2); else if (encodingID == 10) str = bin.readUnicode(data, soff, slen / 2); else if (platformID == 1) { str = bin.readASCII(data, soff, slen); console.log("reading unknown MAC encoding " + encodingID + " as ASCII"); } else { console.log("unknown encoding " + encodingID + ", platformID: " + platformID); str = bin.readASCII(data, soff, slen); } var tid = "p" + platformID + "," + languageID.toString(16); if (obj[tid] == null) obj[tid] = {}; obj[tid][names[nameID]] = str; obj[tid]["_lang"] = languageID; } var psn = "postScriptName"; for (var p in obj) if (obj[p][psn] != null && obj[p]["_lang"] == 1033) return obj[p]; for (var p in obj) if (obj[p][psn] != null && obj[p]["_lang"] == 0) return obj[p]; for (var p in obj) if (obj[p][psn] != null && obj[p]["_lang"] == 3084) return obj[p]; for (var p in obj) if (obj[p][psn] != null) return obj[p]; var out; for (var p in obj) { out = obj[p]; break; } console.log("returning name table with languageID " + out._lang); if (out[psn] == null && out["ID"] != null) out[psn] = out["ID"]; return out; } }; Typr["T"].OS2 = { parseTab: function(data, offset, length) { var bin = Typr["B"]; var ver = bin.readUshort(data, offset); offset += 2; var OS2 = Typr["T"].OS2; var obj = {}; if (ver == 0) OS2.version0(data, offset, obj); else if (ver == 1) OS2.version1(data, offset, obj); else if (ver == 2 || ver == 3 || ver == 4) OS2.version2(data, offset, obj); else if (ver == 5) OS2.version5(data, offset, obj); else throw "unknown OS/2 table version: " + ver; return obj; }, version0: function(data, offset, obj) { var bin = Typr["B"]; obj["xAvgCharWidth"] = bin.readShort(data, offset); offset += 2; obj["usWeightClass"] = bin.readUshort(data, offset); offset += 2; obj["usWidthClass"] = bin.readUshort(data, offset); offset += 2; obj["fsType"] = bin.readUshort(data, offset); offset += 2; obj["ySubscriptXSize"] = bin.readShort(data, offset); offset += 2; obj["ySubscriptYSize"] = bin.readShort(data, offset); offset += 2; obj["ySubscriptXOffset"] = bin.readShort(data, offset); offset += 2; obj["ySubscriptYOffset"] = bin.readShort(data, offset); offset += 2; obj["ySuperscriptXSize"] = bin.readShort(data, offset); offset += 2; obj["ySuperscriptYSize"] = bin.readShort(data, offset); offset += 2; obj["ySuperscriptXOffset"] = bin.readShort(data, offset); offset += 2; obj["ySuperscriptYOffset"] = bin.readShort(data, offset); offset += 2; obj["yStrikeoutSize"] = bin.readShort(data, offset); offset += 2; obj["yStrikeoutPosition"] = bin.readShort(data, offset); offset += 2; obj["sFamilyClass"] = bin.readShort(data, offset); offset += 2; obj["panose"] = bin.readBytes(data, offset, 10); offset += 10; obj["ulUnicodeRange1"] = bin.readUint(data, offset); offset += 4; obj["ulUnicodeRange2"] = bin.readUint(data, offset); offset += 4; obj["ulUnicodeRange3"] = bin.readUint(data, offset); offset += 4; obj["ulUnicodeRange4"] = bin.readUint(data, offset); offset += 4; obj["achVendID"] = bin.readASCII(data, offset, 4); offset += 4; obj["fsSelection"] = bin.readUshort(data, offset); offset += 2; obj["usFirstCharIndex"] = bin.readUshort(data, offset); offset += 2; obj["usLastCharIndex"] = bin.readUshort(data, offset); offset += 2; obj["sTypoAscender"] = bin.readShort(data, offset); offset += 2; obj["sTypoDescender"] = bin.readShort(data, offset); offset += 2; obj["sTypoLineGap"] = bin.readShort(data, offset); offset += 2; obj["usWinAscent"] = bin.readUshort(data, offset); offset += 2; obj["usWinDescent"] = bin.readUshort(data, offset); offset += 2; return offset; }, version1: function(data, offset, obj) { var bin = Typr["B"]; offset = Typr["T"].OS2.version0(data, offset, obj); obj["ulCodePageRange1"] = bin.readUint(data, offset); offset += 4; obj["ulCodePageRange2"] = bin.readUint(data, offset); offset += 4; return offset; }, version2: function(data, offset, obj) { var bin = Typr["B"], rU = bin.readUshort; offset = Typr["T"].OS2.version1(data, offset, obj); obj["sxHeight"] = bin.readShort(data, offset); offset += 2; obj["sCapHeight"] = bin.readShort(data, offset); offset += 2; obj["usDefault"] = rU(data, offset); offset += 2; obj["usBreak"] = rU(data, offset); offset += 2; obj["usMaxContext"] = rU(data, offset); offset += 2; return offset; }, version5: function(data, offset, obj) { var rU = Typr["B"].readUshort; offset = Typr["T"].OS2.version2(data, offset, obj); obj["usLowerOpticalPointSize"] = rU(data, offset); offset += 2; obj["usUpperOpticalPointSize"] = rU(data, offset); offset += 2; return offset; } }; Typr["T"].post = { parseTab: function(data, offset, length) { var bin = Typr["B"]; var obj = {}; obj["version"] = bin.readFixed(data, offset); offset += 4; obj["italicAngle"] = bin.readFixed(data, offset); offset += 4; obj["underlinePosition"] = bin.readShort(data, offset); offset += 2; obj["underlineThickness"] = bin.readShort(data, offset); offset += 2; return obj; } }; Typr["T"].SVG = { parseTab: function(data, offset, length) { var bin = Typr["B"]; var obj = { entries: [] }; var offset0 = offset; var tableVersion = bin.readUshort(data, offset); offset += 2; var svgDocIndexOffset = bin.readUint(data, offset); offset += 4; var reserved = bin.readUint(data, offset); offset += 4; offset = svgDocIndexOffset + offset0; var numEntries = bin.readUshort(data, offset); offset += 2; for (var i = 0; i < numEntries; i++) { var startGlyphID = bin.readUshort(data, offset); offset += 2; var endGlyphID = bin.readUshort(data, offset); offset += 2; var svgDocOffset = bin.readUint(data, offset); offset += 4; var svgDocLength = bin.readUint(data, offset); offset += 4; var sbuf = new Uint8Array(data.buffer, offset0 + svgDocOffset + svgDocIndexOffset, svgDocLength); var svg = bin.readUTF8(sbuf, 0, sbuf.length); for (var f = startGlyphID; f <= endGlyphID; f++) { obj.entries[f] = svg; } } return obj; } }; Typr["U"] = { "shape": function(font, str, ltr) { var getGlyphPosition = function(font2, gls2, i1, ltr2) { var g1 = gls2[i1], g2 = gls2[i1 + 1], kern = font2["kern"]; if (kern) { var ind1 = kern.glyph1.indexOf(g1); if (ind1 != -1) { var ind2 = kern.rval[ind1].glyph2.indexOf(g2); if (ind2 != -1) return [0, 0, kern.rval[ind1].vals[ind2], 0]; } } return [0, 0, 0, 0]; }; var gls = []; for (var i = 0; i < str.length; i++) { var cc = str.codePointAt(i); if (cc > 65535) i++; gls.push(Typr["U"]["codeToGlyph"](font, cc)); } var shape = []; var x = 0, y = 0; for (var i = 0; i < gls.length; i++) { var padj = getGlyphPosition(font, gls, i, ltr); var gid = gls[i]; var ax = font["hmtx"].aWidth[gid] + padj[2]; shape.push({ "g": gid, "cl": i, "dx": 0, "dy": 0, "ax": ax, "ay": 0 }); x += ax; } return shape; }, "shapeToPath": function(font, shape, clr) { var tpath = { cmds: [], crds: [] }; var x = 0, y = 0; for (var i = 0; i < shape.length; i++) { var it = shape[i]; var path = Typr["U"]["glyphToPath"](font, it["g"]), crds = path["crds"]; for (var j = 0; j < crds.length; j += 2) { tpath.crds.push(crds[j] + x + it["dx"]); tpath.crds.push(crds[j + 1] + y + it["dy"]); } if (clr) tpath.cmds.push(clr); for (var j = 0; j < path["cmds"].length; j++) tpath.cmds.push(path["cmds"][j]); var clen = tpath.cmds.length; if (clr) { if (clen != 0 && tpath.cmds[clen - 1] != "X") tpath.cmds.push("X"); } x += it["ax"]; y += it["ay"]; } return { "cmds": tpath.cmds, "crds": tpath.crds }; }, "codeToGlyph": function(font, code) { var cmap = font["cmap"]; var tind = -1, pps = [ "p3e10", "p0e4", "p3e1", "p1e0", "p0e3", "p0e1" ]; for (var i = 0; i < pps.length; i++) if (cmap.ids[pps[i]] != null) { tind = cmap.ids[pps[i]]; break; } if (tind == -1) throw "no familiar platform and encoding!"; var arrSearch = function(arr2, k, v) { var l = 0, r = Math.floor(arr2.length / k); while (l + 1 != r) { var mid = l + (r - l >>> 1); if (arr2[mid * k] <= v) l = mid; else r = mid; } return l * k; }; var tab = cmap.tables[tind], fmt = tab.format, gid = -1; if (fmt == 0) { if (code >= tab.map.length) gid = 0; else gid = tab.map[code]; } else if (fmt == 4) { var sind = -1, ec = tab.endCount; if (code > ec[ec.length - 1]) sind = -1; else { sind = arrSearch(ec, 1, code); if (ec[sind] < code) sind++; } if (sind == -1) gid = 0; else if (code < tab.startCount[sind]) gid = 0; else { var gli = 0; if (tab.idRangeOffset[sind] != 0) gli = tab.glyphIdArray[code - tab.startCount[sind] + (tab.idRangeOffset[sind] >> 1) - (tab.idRangeOffset.length - sind)]; else gli = code + tab.idDelta[sind]; gid = gli & 65535; } } else if (fmt == 6) { var off = code - tab.firstCode, arr = tab.glyphIdArray; if (off < 0 || off >= arr.length) gid = 0; else gid = arr[off]; } else if (fmt == 12) { var grp = tab.groups; if (code > grp[grp.length - 2]) gid = 0; else { var i = arrSearch(grp, 3, code); if (grp[i] <= code && code <= grp[i + 1]) { gid = grp[i + 2] + (code - grp[i]); } if (gid == -1) gid = 0; } } else throw "unknown cmap table format " + tab.format; var SVG = font["SVG "], loca = font["loca"]; if (gid != 0 && font["CFF "] == null && (SVG == null || SVG.entries[gid] == null) && loca[gid] == loca[gid + 1] && [ 9, 10, 11, 12, 13, 32, 133, 160, 5760, 8232, 8233, 8239, 12288, 6158, 8203, 8204, 8205, 8288, 65279 ].indexOf(code) == -1 && !(8192 <= code && code <= 8202)) gid = 0; return gid; }, "glyphToPath": function(font, gid) { var path = { cmds: [], crds: [] }; var SVG = font["SVG "], CFF = font["CFF "]; var U = Typr["U"]; if (SVG && SVG.entries[gid]) { var p = SVG.entries[gid]; if (p != null) { if (typeof p == "string") { p = U["SVG"].toPath(p); SVG.entries[gid] = p; } path = p; } } else if (CFF) { var pdct = CFF["Private"]; var state = { x: 0, y: 0, stack: [], nStems: 0, haveWidth: false, width: pdct ? pdct["defaultWidthX"] : 0, open: false }; if (CFF["ROS"]) { var gi = 0; while (CFF["FDSelect"][gi + 2] <= gid) gi += 2; pdct = CFF["FDArray"][CFF["FDSelect"][gi + 1]]["Private"]; } U["_drawCFF"](CFF["CharStrings"][gid], state, CFF, pdct, path); } else if (font["glyf"]) { U["_drawGlyf"](gid, font, path); } return { "cmds": path.cmds, "crds": path.crds }; }, "_drawGlyf": function(gid, font, path) { var gl = font["glyf"][gid]; if (gl == null) gl = font["glyf"][gid] = Typr["T"].glyf._parseGlyf(font, gid); if (gl != null) { if (gl.noc > -1) Typr["U"]["_simpleGlyph"](gl, path); else Typr["U"]["_compoGlyph"](gl, font, path); } }, "_simpleGlyph": function(gl, p) { var P = Typr["U"]["P"]; for (var c = 0; c < gl.noc; c++) { var i0 = c == 0 ? 0 : gl.endPts[c - 1] + 1; var il = gl.endPts[c]; for (var i = i0; i <= il; i++) { var pr = i == i0 ? il : i - 1; var nx = i == il ? i0 : i + 1; var onCurve = gl.flags[i] & 1; var prOnCurve = gl.flags[pr] & 1; var nxOnCurve = gl.flags[nx] & 1; var x = gl.xs[i], y = gl.ys[i]; if (i == i0) { if (onCurve) { if (prOnCurve) P.MoveTo(p, gl.xs[pr], gl.ys[pr]); else { P.MoveTo(p, x, y); continue; } } else { if (prOnCurve) P.MoveTo(p, gl.xs[pr], gl.ys[pr]); else P.MoveTo(p, Math.floor((gl.xs[pr] + x) * 0.5), Math.floor((gl.ys[pr] + y) * 0.5)); } } if (onCurve) { if (prOnCurve) P.LineTo(p, x, y); } else { if (nxOnCurve) P.qCurveTo(p, x, y, gl.xs[nx], gl.ys[nx]); else P.qCurveTo(p, x, y, Math.floor((x + gl.xs[nx]) * 0.5), Math.floor((y + gl.ys[nx]) * 0.5)); } } P.ClosePath(p); } }, "_compoGlyph": function(gl, font, p) { for (var j = 0; j < gl.parts.length; j++) { var path = { cmds: [], crds: [] }; var prt = gl.parts[j]; Typr["U"]["_drawGlyf"](prt.glyphIndex, font, path); var m = prt.m; for (var i = 0; i < path.crds.length; i += 2) { var x = path.crds[i], y = path.crds[i + 1]; p.crds.push(x * m.a + y * m.b + m.tx); p.crds.push(x * m.c + y * m.d + m.ty); } for (var i = 0; i < path.cmds.length; i++) p.cmds.push(path.cmds[i]); } }, "pathToSVG": function(path, prec) { var cmds = path["cmds"], crds = path["crds"]; if (prec == null) prec = 5; var out = [], co = 0, lmap = { "M": 2, "L": 2, "Q": 4, "C": 6 }; for (var i = 0; i < cmds.length; i++) { var cmd = cmds[i], cn = co + (lmap[cmd] ? lmap[cmd] : 0); out.push(cmd); while (co < cn) { var c = crds[co++]; out.push(parseFloat(c.toFixed(prec)) + (co == cn ? "" : " ")); } } return out.join(""); }, "SVGToPath": function(d) { var pth = { cmds: [], crds: [] }; Typr["U"]["SVG"].svgToPath(d, pth); return { "cmds": pth.cmds, "crds": pth.crds }; }, "pathToContext": function(path, ctx) { var c = 0, cmds = path["cmds"], crds = path["crds"]; for (var j = 0; j < cmds.length; j++) { var cmd = cmds[j]; if (cmd == "M") { ctx.moveTo(crds[c], crds[c + 1]); c += 2; } else if (cmd == "L") { ctx.lineTo(crds[c], crds[c + 1]); c += 2; } else if (cmd == "C") { ctx.bezierCurveTo(crds[c], crds[c + 1], crds[c + 2], crds[c + 3], crds[c + 4], crds[c + 5]); c += 6; } else if (cmd == "Q") { ctx.quadraticCurveTo(crds[c], crds[c + 1], crds[c + 2], crds[c + 3]); c += 4; } else if (cmd.charAt(0) == "#") { ctx.beginPath(); ctx.fillStyle = cmd; } else if (cmd == "Z") { ctx.closePath(); } else if (cmd == "X") { ctx.fill(); } } }, "P": { MoveTo: function(p, x, y) { p.cmds.push("M"); p.crds.push(x, y); }, LineTo: function(p, x, y) { p.cmds.push("L"); p.crds.push(x, y); }, CurveTo: function(p, a, b, c, d, e, f) { p.cmds.push("C"); p.crds.push(a, b, c, d, e, f); }, qCurveTo: function(p, a, b, c, d) { p.cmds.push("Q"); p.crds.push(a, b, c, d); }, ClosePath: function(p) { p.cmds.push("Z"); } }, "_drawCFF": function(cmds, state, font, pdct, p) { var stack = state.stack; var nStems = state.nStems, haveWidth = state.haveWidth, width = state.width, open = state.open; var i = 0; var x = state.x, y = state.y, c1x = 0, c1y = 0, c2x = 0, c2y = 0, c3x = 0, c3y = 0, c4x = 0, c4y = 0, jpx = 0, jpy = 0; var CFF = Typr["T"].CFF, P = Typr["U"]["P"]; var nominalWidthX = pdct["nominalWidthX"]; var o = { val: 0, size: 0 }; while (i < cmds.length) { CFF.getCharString(cmds, i, o); var v = o.val; i += o.size; if (false) { } else if (v == "o1" || v == "o18") { var hasWidthArg; hasWidthArg = stack.length % 2 !== 0; if (hasWidthArg && !haveWidth) { width = stack.shift() + nominalWidthX; } nStems += stack.length >> 1; stack.length = 0; haveWidth = true; } else if (v == "o3" || v == "o23") { var hasWidthArg; hasWidthArg = stack.length % 2 !== 0; if (hasWidthArg && !haveWidth) { width = stack.shift() + nominalWidthX; } nStems += stack.length >> 1; stack.length = 0; haveWidth = true; } else if (v == "o4") { if (stack.length > 1 && !haveWidth) { width = stack.shift() + nominalWidthX; haveWidth = true; } if (open) P.ClosePath(p); y += stack.pop(); P.MoveTo(p, x, y); open = true; } else if (v == "o5") { while (stack.length > 0) { x += stack.shift(); y += stack.shift(); P.LineTo(p, x, y); } } else if (v == "o6" || v == "o7") { var count = stack.length; var isX = v == "o6"; for (var j = 0; j < count; j++) { var sval = stack.shift(); if (isX) x += sval; else y += sval; isX = !isX; P.LineTo(p, x, y); } } else if (v == "o8" || v == "o24") { var count = stack.length; var index = 0; while (index + 6 <= count) { c1x = x + stack.shift(); c1y = y + stack.shift(); c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); x = c2x + stack.shift(); y = c2y + stack.shift(); P.CurveTo(p, c1x, c1y, c2x, c2y, x, y); index += 6; } if (v == "o24") { x += stack.shift(); y += stack.shift(); P.LineTo(p, x, y); } } else if (v == "o11") break; else if (v == "o1234" || v == "o1235" || v == "o1236" || v == "o1237") { if (v == "o1234") { c1x = x + stack.shift(); c1y = y; c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); jpx = c2x + stack.shift(); jpy = c2y; c3x = jpx + stack.shift(); c3y = c2y; c4x = c3x + stack.shift(); c4y = y; x = c4x + stack.shift(); P.CurveTo(p, c1x, c1y, c2x, c2y, jpx, jpy); P.CurveTo(p, c3x, c3y, c4x, c4y, x, y); } if (v == "o1235") { c1x = x + stack.shift(); c1y = y + stack.shift(); c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); jpx = c2x + stack.shift(); jpy = c2y + stack.shift(); c3x = jpx + stack.shift(); c3y = jpy + stack.shift(); c4x = c3x + stack.shift(); c4y = c3y + stack.shift(); x = c4x + stack.shift(); y = c4y + stack.shift(); stack.shift(); P.CurveTo(p, c1x, c1y, c2x, c2y, jpx, jpy); P.CurveTo(p, c3x, c3y, c4x, c4y, x, y); } if (v == "o1236") { c1x = x + stack.shift(); c1y = y + stack.shift(); c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); jpx = c2x + stack.shift(); jpy = c2y; c3x = jpx + stack.shift(); c3y = c2y; c4x = c3x + stack.shift(); c4y = c3y + stack.shift(); x = c4x + stack.shift(); P.CurveTo(p, c1x, c1y, c2x, c2y, jpx, jpy); P.CurveTo(p, c3x, c3y, c4x, c4y, x, y); } if (v == "o1237") { c1x = x + stack.shift(); c1y = y + stack.shift(); c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); jpx = c2x + stack.shift(); jpy = c2y + stack.shift(); c3x = jpx + stack.shift(); c3y = jpy + stack.shift(); c4x = c3x + stack.shift(); c4y = c3y + stack.shift(); if (Math.abs(c4x - x) > Math.abs(c4y - y)) { x = c4x + stack.shift(); } else { y = c4y + stack.shift(); } P.CurveTo(p, c1x, c1y, c2x, c2y, jpx, jpy); P.CurveTo(p, c3x, c3y, c4x, c4y, x, y); } } else if (v == "o14") { if (stack.length > 0 && !haveWidth) { width = stack.shift() + font["nominalWidthX"]; haveWidth = true; } if (stack.length == 4) { var asb = 0; var adx = stack.shift(); var ady = stack.shift(); var bchar = stack.shift(); var achar = stack.shift(); var bind = CFF.glyphBySE(font, bchar); var aind = CFF.glyphBySE(font, achar); Typr["U"]["_drawCFF"](font["CharStrings"][bind], state, font, pdct, p); state.x = adx; state.y = ady; Typr["U"]["_drawCFF"](font["CharStrings"][aind], state, font, pdct, p); } if (open) { P.ClosePath(p); open = false; } } else if (v == "o19" || v == "o20") { var hasWidthArg; hasWidthArg = stack.length % 2 !== 0; if (hasWidthArg && !haveWidth) { width = stack.shift() + nominalWidthX; } nStems += stack.length >> 1; stack.length = 0; haveWidth = true; i += nStems + 7 >> 3; } else if (v == "o21") { if (stack.length > 2 && !haveWidth) { width = stack.shift() + nominalWidthX; haveWidth = true; } y += stack.pop(); x += stack.pop(); if (open) P.ClosePath(p); P.MoveTo(p, x, y); open = true; } else if (v == "o22") { if (stack.length > 1 && !haveWidth) { width = stack.shift() + nominalWidthX; haveWidth = true; } x += stack.pop(); if (open) P.ClosePath(p); P.MoveTo(p, x, y); open = true; } else if (v == "o25") { while (stack.length > 6) { x += stack.shift(); y += stack.shift(); P.LineTo(p, x, y); } c1x = x + stack.shift(); c1y = y + stack.shift(); c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); x = c2x + stack.shift(); y = c2y + stack.shift(); P.CurveTo(p, c1x, c1y, c2x, c2y, x, y); } else if (v == "o26") { if (stack.length % 2) { x += stack.shift(); } while (stack.length > 0) { c1x = x; c1y = y + stack.shift(); c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); x = c2x; y = c2y + stack.shift(); P.CurveTo(p, c1x, c1y, c2x, c2y, x, y); } } else if (v == "o27") { if (stack.length % 2) { y += stack.shift(); } while (stack.length > 0) { c1x = x + stack.shift(); c1y = y; c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); x = c2x + stack.shift(); y = c2y; P.CurveTo(p, c1x, c1y, c2x, c2y, x, y); } } else if (v == "o10" || v == "o29") { var obj = v == "o10" ? pdct : font; if (stack.length == 0) { console.log("error: empty stack"); } else { var ind = stack.pop(); var subr = obj["Subrs"][ind + obj["Bias"]]; state.x = x; state.y = y; state.nStems = nStems; state.haveWidth = haveWidth; state.width = width; state.open = open; Typr["U"]["_drawCFF"](subr, state, font, pdct, p); x = state.x; y = state.y; nStems = state.nStems; haveWidth = state.haveWidth; width = state.width; open = state.open; } } else if (v == "o30" || v == "o31") { var count, count1 = stack.length; var index = 0; var alternate = v == "o31"; count = count1 & ~2; index += count1 - count; while (index < count) { if (alternate) { c1x = x + stack.shift(); c1y = y; c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); y = c2y + stack.shift(); if (count - index == 5) { x = c2x + stack.shift(); index++; } else x = c2x; alternate = false; } else { c1x = x; c1y = y + stack.shift(); c2x = c1x + stack.shift(); c2y = c1y + stack.shift(); x = c2x + stack.shift(); if (count - index == 5) { y = c2y + stack.shift(); index++; } else y = c2y; alternate = true; } P.CurveTo(p, c1x, c1y, c2x, c2y, x, y); index += 4; } } else if ((v + "").charAt(0) == "o") { console.log("Unknown operation: " + v, cmds); throw v; } else stack.push(v); } state.x = x; state.y = y; state.nStems = nStems; state.haveWidth = haveWidth; state.width = width; state.open = open; }, "SVG": function() { var M = { getScale: function(m) { return Math.sqrt(Math.abs(m[0] * m[3] - m[1] * m[2])); }, translate: function(m, x, y) { M.concat(m, [1, 0, 0, 1, x, y]); }, rotate: function(m, a) { M.concat(m, [Math.cos(a), -Math.sin(a), Math.sin(a), Math.cos(a), 0, 0]); }, scale: function(m, x, y) { M.concat(m, [x, 0, 0, y, 0, 0]); }, concat: function(m, w) { var a = m[0], b = m[1], c = m[2], d = m[3], tx = m[4], ty = m[5]; m[0] = a * w[0] + b * w[2]; m[1] = a * w[1] + b * w[3]; m[2] = c * w[0] + d * w[2]; m[3] = c * w[1] + d * w[3]; m[4] = tx * w[0] + ty * w[2] + w[4]; m[5] = tx * w[1] + ty * w[3] + w[5]; }, invert: function(m) { var a = m[0], b = m[1], c = m[2], d = m[3], tx = m[4], ty = m[5], adbc = a * d - b * c; m[0] = d / adbc; m[1] = -b / adbc; m[2] = -c / adbc; m[3] = a / adbc; m[4] = (c * ty - d * tx) / adbc; m[5] = (b * tx - a * ty) / adbc; }, multPoint: function(m, p) { var x = p[0], y = p[1]; return [x * m[0] + y * m[2] + m[4], x * m[1] + y * m[3] + m[5]]; }, multArray: function(m, a) { for (var i = 0; i < a.length; i += 2) { var x = a[i], y = a[i + 1]; a[i] = x * m[0] + y * m[2] + m[4]; a[i + 1] = x * m[1] + y * m[3] + m[5]; } } }; function _bracketSplit(str, lbr, rbr) { var out = [], pos = 0, ci = 0, lvl = 0; while (true) { var li = str.indexOf(lbr, ci); var ri = str.indexOf(rbr, ci); if (li == -1 && ri == -1) break; if (ri == -1 || li != -1 && li < ri) { if (lvl == 0) { out.push(str.slice(pos, li).trim()); pos = li + 1; } lvl++; ci = li + 1; } else if (li == -1 || ri != -1 && ri < li) { lvl--; if (lvl == 0) { out.push(str.slice(pos, ri).trim()); pos = ri + 1; } ci = ri + 1; } } return out; } function cssMap(str) { var pts = _bracketSplit(str, "{", "}"); var css = {}; for (var i = 0; i < pts.length; i += 2) { var cn = pts[i].split(","); for (var j = 0; j < cn.length; j++) { var cnj = cn[j].trim(); if (css[cnj] == null) css[cnj] = ""; css[cnj] += pts[i + 1]; } } return css; } function readTrnf(trna) { var pts = _bracketSplit(trna, "(", ")"); var m = [1, 0, 0, 1, 0, 0]; for (var i = 0; i < pts.length; i += 2) { var om = m; m = _readTrnsAttr(pts[i], pts[i + 1]); M.concat(m, om); } return m; } function _readTrnsAttr(fnc, vls) { var m = [1, 0, 0, 1, 0, 0], gotSep = true; for (var i = 0; i < vls.length; i++) { var ch = vls.charAt(i); if (ch == "," || ch == " ") gotSep = true; else if (ch == ".") { if (!gotSep) { vls = vls.slice(0, i) + "," + vls.slice(i); i++; } gotSep = false; } else if (ch == "-" && i > 0 && vls[i - 1] != "e") { vls = vls.slice(0, i) + " " + vls.slice(i); i++; gotSep = true; } } vls = vls.split(/\s*[\s,]\s*/).map(parseFloat); if (false) { } else if (fnc == "translate") { if (vls.length == 1) M.translate(m, vls[0], 0); else M.translate(m, vls[0], vls[1]); } else if (fnc == "scale") { if (vls.length == 1) M.scale(m, vls[0], vls[0]); else M.scale(m, vls[0], vls[1]); } else if (fnc == "rotate") { var tx = 0, ty = 0; if (vls.length != 1) { tx = vls[1]; ty = vls[2]; } M.translate(m, -tx, -ty); M.rotate(m, -Math.PI * vls[0] / 180); M.translate(m, tx, ty); } else if (fnc == "matrix") m = vls; else console.log("unknown transform: ", fnc); return m; } function toPath(str) { var pth = { cmds: [], crds: [] }; if (str == null) return pth; var prsr = new DOMParser(); var doc = prsr["parseFromString"](str, "image/svg+xml"); var svg = doc.getElementsByTagName("svg")[0]; var vb = svg.getAttribute("viewBox"); if (vb) vb = vb.trim().split(" ").map(parseFloat); else vb = [0, 0, 1e3, 1e3]; _toPath(svg.children, pth); for (var i = 0; i < pth.crds.length; i += 2) { var x = pth.crds[i], y = pth.crds[i + 1]; x -= vb[0]; y -= vb[1]; y = -y; pth.crds[i] = x; pth.crds[i + 1] = y; } return pth; } function _toPath(nds, pth, fill) { for (var ni = 0; ni < nds.length; ni++) { var nd = nds[ni], tn = nd.tagName; var cfl = nd.getAttribute("fill"); if (cfl == null) cfl = fill; if (tn == "g") { var tp = { crds: [], cmds: [] }; _toPath(nd.children, tp, cfl); var trf = nd.getAttribute("transform"); if (trf) { var m = readTrnf(trf); M.multArray(m, tp.crds); } pth.crds = pth.crds.concat(tp.crds); pth.cmds = pth.cmds.concat(tp.cmds); } else if (tn == "path" || tn == "circle" || tn == "ellipse") { pth.cmds.push(cfl ? cfl : "#000000"); var d; if (tn == "path") d = nd.getAttribute("d"); if (tn == "circle" || tn == "ellipse") { var vls = [0, 0, 0, 0], nms = ["cx", "cy", "rx", "ry", "r"]; for (var i = 0; i < 5; i++) { var V = nd.getAttribute(nms[i]); if (V) { V = parseFloat(V); if (i < 4) vls[i] = V; else vls[2] = vls[3] = V; } } var cx = vls[0], cy = vls[1], rx = vls[2], ry = vls[3]; d = ["M", cx - rx, cy, "a", rx, ry, 0, 1, 0, rx * 2, 0, "a", rx, ry, 0, 1, 0, -rx * 2, 0].join(" "); } svgToPath(d, pth); pth.cmds.push("X"); } else if (tn == "defs") { } else console.log(tn, nd); } } function _tokens(d) { var ts = [], off = 0, rn = false, cn = "", pc = ""; while (off < d.length) { var cc = d.charCodeAt(off), ch = d.charAt(off); off++; var isNum = 48 <= cc && cc <= 57 || ch == "." || ch == "-" || ch == "e" || ch == "E"; if (rn) { if (ch == "-" && pc != "e" || ch == "." && cn.indexOf(".") != -1) { ts.push(parseFloat(cn)); cn = ch; } else if (isNum) cn += ch; else { ts.push(parseFloat(cn)); if (ch != "," && ch != " ") ts.push(ch); rn = false; } } else { if (isNum) { cn = ch; rn = true; } else if (ch != "," && ch != " ") ts.push(ch); } pc = ch; } if (rn) ts.push(parseFloat(cn)); return ts; } function _reps(ts, off, ps) { var i = off; while (i < ts.length) { if (typeof ts[i] == "string") break; i += ps; } return (i - off) / ps; } function svgToPath(d, pth) { var ts = _tokens(d); var i = 0, x = 0, y = 0, ox = 0, oy = 0, oldo = pth.crds.length; var pc = { "M": 2, "L": 2, "H": 1, "V": 1, "T": 2, "S": 4, "A": 7, "Q": 4, "C": 6 }; var cmds = pth.cmds, crds = pth.crds; while (i < ts.length) { var cmd = ts[i]; i++; var cmu = cmd.toUpperCase(); if (cmu == "Z") { cmds.push("Z"); x = ox; y = oy; } else { var ps = pc[cmu], reps = _reps(ts, i, ps); for (var j = 0; j < reps; j++) { if (j == 1 && cmu == "M") { cmd = cmd == cmu ? "L" : "l"; cmu = "L"; } var xi = 0, yi = 0; if (cmd != cmu) { xi = x; yi = y; } if (false) { } else if (cmu == "M") { x = xi + ts[i++]; y = yi + ts[i++]; cmds.push("M"); crds.push(x, y); ox = x; oy = y; } else if (cmu == "L") { x = xi + ts[i++]; y = yi + ts[i++]; cmds.push("L"); crds.push(x, y); } else if (cmu == "H") { x = xi + ts[i++]; cmds.push("L"); crds.push(x, y); } else if (cmu == "V") { y = yi + ts[i++]; cmds.push("L"); crds.push(x, y); } else if (cmu == "Q") { var x1 = xi + ts[i++], y1 = yi + ts[i++], x2 = xi + ts[i++], y2 = yi + ts[i++]; cmds.push("Q"); crds.push(x1, y1, x2, y2); x = x2; y = y2; } else if (cmu == "T") { var co = Math.max(crds.length - 2, oldo); var x1 = x + x - crds[co], y1 = y + y - crds[co + 1]; var x2 = xi + ts[i++], y2 = yi + ts[i++]; cmds.push("Q"); crds.push(x1, y1, x2, y2); x = x2; y = y2; } else if (cmu == "C") { var x1 = xi + ts[i++], y1 = yi + ts[i++], x2 = xi + ts[i++], y2 = yi + ts[i++], x3 = xi + ts[i++], y3 = yi + ts[i++]; cmds.push("C"); crds.push(x1, y1, x2, y2, x3, y3); x = x3; y = y3; } else if (cmu == "S") { var co = Math.max(crds.length - (cmds[cmds.length - 1] == "C" ? 4 : 2), oldo); var x1 = x + x - crds[co], y1 = y + y - crds[co + 1]; var x2 = xi + ts[i++], y2 = yi + ts[i++], x3 = xi + ts[i++], y3 = yi + ts[i++]; cmds.push("C"); crds.push(x1, y1, x2, y2, x3, y3); x = x3; y = y3; } else if (cmu == "A") { var x1 = x, y1 = y; var rx = ts[i++], ry = ts[i++]; var phi = ts[i++] * (Math.PI / 180), fA = ts[i++], fS = ts[i++]; var x2 = xi + ts[i++], y2 = yi + ts[i++]; if (x2 == x && y2 == y && rx == 0 && ry == 0) continue; var hdx = (x1 - x2) / 2, hdy = (y1 - y2) / 2; var cosP = Math.cos(phi), sinP = Math.sin(phi); var x1A = cosP * hdx + sinP * hdy; var y1A = -sinP * hdx + cosP * hdy; var rxS = rx * rx, ryS = ry * ry; var x1AS = x1A * x1A, y1AS = y1A * y1A; var frc = (rxS * ryS - rxS * y1AS - ryS * x1AS) / (rxS * y1AS + ryS * x1AS); var coef = (fA != fS ? 1 : -1) * Math.sqrt(Math.max(frc, 0)); var cxA = coef * (rx * y1A) / ry; var cyA = -coef * (ry * x1A) / rx; var cx = cosP * cxA - sinP * cyA + (x1 + x2) / 2; var cy = sinP * cxA + cosP * cyA + (y1 + y2) / 2; var angl = function(ux, uy, vx, vy) { var lU = Math.sqrt(ux * ux + uy * uy), lV = Math.sqrt(vx * vx + vy * vy); var num = (ux * vx + uy * vy) / (lU * lV); return (ux * vy - uy * vx >= 0 ? 1 : -1) * Math.acos(Math.max(-1, Math.min(1, num))); }; var vX = (x1A - cxA) / rx, vY = (y1A - cyA) / ry; var theta1 = angl(1, 0, vX, vY); var dtheta = angl(vX, vY, (-x1A - cxA) / rx, (-y1A - cyA) / ry); dtheta = dtheta % (2 * Math.PI); var arc = function(gst2, x4, y4, r, a0, a1, neg) { var rotate = function(m, a) { var si = Math.sin(a), co2 = Math.cos(a); var a = m[0], b = m[1], c = m[2], d2 = m[3]; m[0] = a * co2 + b * si; m[1] = -a * si + b * co2; m[2] = c * co2 + d2 * si; m[3] = -c * si + d2 * co2; }; var multArr = function(m, a) { for (var j3 = 0; j3 < a.length; j3 += 2) { var x5 = a[j3], y5 = a[j3 + 1]; a[j3] = m[0] * x5 + m[2] * y5 + m[4]; a[j3 + 1] = m[1] * x5 + m[3] * y5 + m[5]; } }; var concatA = function(a, b) { for (var j3 = 0; j3 < b.length; j3++) a.push(b[j3]); }; var concatP = function(p, r2) { concatA(p.cmds, r2.cmds); concatA(p.crds, r2.crds); }; if (neg) while (a1 > a0) a1 -= 2 * Math.PI; else while (a1 < a0) a1 += 2 * Math.PI; var th = (a1 - a0) / 4; var x0 = Math.cos(th / 2), y0 = -Math.sin(th / 2); var x12 = (4 - x0) / 3, y12 = y0 == 0 ? y0 : (1 - x0) * (3 - x0) / (3 * y0); var x22 = x12, y22 = -y12; var x32 = x0, y32 = -y0; var ps2 = [x12, y12, x22, y22, x32, y32]; var pth2 = { cmds: ["C", "C", "C", "C"], crds: ps2.slice(0) }; var rot = [1, 0, 0, 1, 0, 0]; rotate(rot, -th); for (var j2 = 0; j2 < 3; j2++) { multArr(rot, ps2); concatA(pth2.crds, ps2); } rotate(rot, -a0 + th / 2); rot[0] *= r; rot[1] *= r; rot[2] *= r; rot[3] *= r; rot[4] = x4; rot[5] = y4; multArr(rot, pth2.crds); multArr(gst2.ctm, pth2.crds); concatP(gst2.pth, pth2); }; var gst = { pth, ctm: [rx * cosP, rx * sinP, -ry * sinP, ry * cosP, cx, cy] }; arc(gst, 0, 0, 1, theta1, theta1 + dtheta, fS == 0); x = x2; y = y2; } else console.log("Unknown SVG command " + cmd); } } } } ; return { "cssMap": cssMap, "readTrnf": readTrnf, svgToPath, toPath }; }(), "initHB": function(hurl, resp) { var codeLength = function(code) { var len = 0; if ((code & 4294967295 - (1 << 7) + 1) == 0) { len = 1; } else if ((code & 4294967295 - (1 << 11) + 1) == 0) { len = 2; } else if ((code & 4294967295 - (1 << 16) + 1) == 0) { len = 3; } else if ((code & 4294967295 - (1 << 21) + 1) == 0) { len = 4; } return len; }; var te = new window["TextEncoder"]("utf8"); fetch(hurl).then(function(x) { return x["arrayBuffer"](); }).then(function(ab) { return WebAssembly["instantiate"](ab); }).then(function(res) { console.log("HB ready"); var exp = res["instance"]["exports"], mem = exp["memory"]; mem["grow"](700); var heapu8 = new Uint8Array(mem.buffer); var u32 = new Uint32Array(mem.buffer); var i32 = new Int32Array(mem.buffer); var __lastFnt, blob, blobPtr, face, font; Typr["U"]["shapeHB"] = function() { var toJson = function(ptr) { var length = exp["hb_buffer_get_length"](ptr); var result = []; var iPtr32 = exp["hb_buffer_get_glyph_infos"](ptr, 0) >>> 2; var pPtr32 = exp["hb_buffer_get_glyph_positions"](ptr, 0) >>> 2; for (var i = 0; i < length; ++i) { var a = iPtr32 + i * 5, b = pPtr32 + i * 5; result.push({ "g": u32[a + 0], "cl": u32[a + 2], "ax": i32[b + 0], "ay": i32[b + 1], "dx": i32[b + 2], "dy": i32[b + 3] }); } return result; }; return function(fnt, str, ltr) { var fdata = fnt["_data"], fn = fnt["name"]["postScriptName"]; if (__lastFnt != fn) { if (blob != null) { exp["hb_blob_destroy"](blob); exp["free"](blobPtr); exp["hb_face_destroy"](face); exp["hb_font_destroy"](font); } blobPtr = exp["malloc"](fdata.byteLength); heapu8.set(fdata, blobPtr); blob = exp["hb_blob_create"](blobPtr, fdata.byteLength, 2, 0, 0); face = exp["hb_face_create"](blob, 0); font = exp["hb_font_create"](face); __lastFnt = fn; } var buffer = exp["hb_buffer_create"](); var bytes = te["encode"](str); var len = bytes.length, strp = exp["malloc"](len); heapu8.set(bytes, strp); exp["hb_buffer_add_utf8"](buffer, strp, len, 0, len); exp["free"](strp); exp["hb_buffer_set_direction"](buffer, ltr ? 4 : 5); exp["hb_buffer_guess_segment_properties"](buffer); exp["hb_shape"](font, buffer, 0, 0); var json = toJson(buffer); exp["hb_buffer_destroy"](buffer); var arr = json.slice(0); if (!ltr) arr.reverse(); var ci = 0, bi = 0; for (var i = 1; i < arr.length; i++) { var gl = arr[i], cl = gl["cl"]; while (true) { var cpt = str.codePointAt(ci), cln = codeLength(cpt); if (bi + cln <= cl) { bi += cln; ci += cpt <= 65535 ? 1 : 2; } else break; } gl["cl"] = ci; } return json; }; }(); resp(); }); } }; window.Typr = Typr; /*! blueimp-md5 v2.19.0 | MIT License */ ; (function($) { "use strict"; function safeAdd(x, y) { var lsw = (x & 65535) + (y & 65535); var msw = (x >> 16) + (y >> 16) + (lsw >> 16); return msw << 16 | lsw & 65535; } function bitRotateLeft(num, cnt) { return num << cnt | num >>> 32 - cnt; } function md5cmn(q, a, b, x, s, t) { return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b); } function md5ff(a, b, c, d, x, s, t) { return md5cmn(b & c | ~b & d, a, b, x, s, t); } function md5gg(a, b, c, d, x, s, t) { return md5cmn(b & d | c & ~d, a, b, x, s, t); } function md5hh(a, b, c, d, x, s, t) { return md5cmn(b ^ c ^ d, a, b, x, s, t); } function md5ii(a, b, c, d, x, s, t) { return md5cmn(c ^ (b | ~d), a, b, x, s, t); } function binlMD5(x, len) { x[len >> 5] |= 128 << len % 32; x[(len + 64 >>> 9 << 4) + 14] = len; var i; var olda; var oldb; var oldc; var oldd; var a = 1732584193; var b = -271733879; var c = -1732584194; var d = 271733878; for (i = 0; i < x.length; i += 16) { olda = a; oldb = b; oldc = c; oldd = d; a = md5ff(a, b, c, d, x[i], 7, -680876936); d = md5ff(d, a, b, c, x[i + 1], 12, -389564586); c = md5ff(c, d, a, b, x[i + 2], 17, 606105819); b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330); a = md5ff(a, b, c, d, x[i + 4], 7, -176418897); d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426); c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341); b = md5ff(b, c, d, a, x[i + 7], 22, -45705983); a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416); d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417); c = md5ff(c, d, a, b, x[i + 10], 17, -42063); b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162); a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682); d = md5ff(d, a, b, c, x[i + 13], 12, -40341101); c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290); b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329); a = md5gg(a, b, c, d, x[i + 1], 5, -165796510); d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632); c = md5gg(c, d, a, b, x[i + 11], 14, 643717713); b = md5gg(b, c, d, a, x[i], 20, -373897302); a = md5gg(a, b, c, d, x[i + 5], 5, -701558691); d = md5gg(d, a, b, c, x[i + 10], 9, 38016083); c = md5gg(c, d, a, b, x[i + 15], 14, -660478335); b = md5gg(b, c, d, a, x[i + 4], 20, -405537848); a = md5gg(a, b, c, d, x[i + 9], 5, 568446438); d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690); c = md5gg(c, d, a, b, x[i + 3], 14, -187363961); b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501); a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467); d = md5gg(d, a, b, c, x[i + 2], 9, -51403784); c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473); b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734); a = md5hh(a, b, c, d, x[i + 5], 4, -378558); d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463); c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562); b = md5hh(b, c, d, a, x[i + 14], 23, -35309556); a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060); d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353); c = md5hh(c, d, a, b, x[i + 7], 16, -155497632); b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640); a = md5hh(a, b, c, d, x[i + 13], 4, 681279174); d = md5hh(d, a, b, c, x[i], 11, -358537222); c = md5hh(c, d, a, b, x[i + 3], 16, -722521979); b = md5hh(b, c, d, a, x[i + 6], 23, 76029189); a = md5hh(a, b, c, d, x[i + 9], 4, -640364487); d = md5hh(d, a, b, c, x[i + 12], 11, -421815835); c = md5hh(c, d, a, b, x[i + 15], 16, 530742520); b = md5hh(b, c, d, a, x[i + 2], 23, -995338651); a = md5ii(a, b, c, d, x[i], 6, -198630844); d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415); c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905); b = md5ii(b, c, d, a, x[i + 5], 21, -57434055); a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571); d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606); c = md5ii(c, d, a, b, x[i + 10], 15, -1051523); b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799); a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359); d = md5ii(d, a, b, c, x[i + 15], 10, -30611744); c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380); b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649); a = md5ii(a, b, c, d, x[i + 4], 6, -145523070); d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379); c = md5ii(c, d, a, b, x[i + 2], 15, 718787259); b = md5ii(b, c, d, a, x[i + 9], 21, -343485551); a = safeAdd(a, olda); b = safeAdd(b, oldb); c = safeAdd(c, oldc); d = safeAdd(d, oldd); } return [a, b, c, d]; } function binl2rstr(input) { var i; var output = ""; var length32 = input.length * 32; for (i = 0; i < length32; i += 8) { output += String.fromCharCode(input[i >> 5] >>> i % 32 & 255); } return output; } function rstr2binl(input) { var i; var output = []; output[(input.length >> 2) - 1] = void 0; for (i = 0; i < output.length; i += 1) { output[i] = 0; } var length8 = input.length * 8; for (i = 0; i < length8; i += 8) { output[i >> 5] |= (input.charCodeAt(i / 8) & 255) << i % 32; } return output; } function rstrMD5(s) { return binl2rstr(binlMD5(rstr2binl(s), s.length * 8)); } function rstrHMACMD5(key, data) { var i; var bkey = rstr2binl(key); var ipad = []; var opad = []; var hash; ipad[15] = opad[15] = void 0; if (bkey.length > 16) { bkey = binlMD5(bkey, key.length * 8); } for (i = 0; i < 16; i += 1) { ipad[i] = bkey[i] ^ 909522486; opad[i] = bkey[i] ^ 1549556828; } hash = binlMD5(ipad.concat(rstr2binl(data)), 512 + data.length * 8); return binl2rstr(binlMD5(opad.concat(hash), 512 + 128)); } function rstr2hex(input) { var hexTab = "0123456789abcdef"; var output = ""; var x; var i; for (i = 0; i < input.length; i += 1) { x = input.charCodeAt(i); output += hexTab.charAt(x >>> 4 & 15) + hexTab.charAt(x & 15); } return output; } function str2rstrUTF8(input) { return unescape(encodeURIComponent(input)); } function rawMD5(s) { return rstrMD5(str2rstrUTF8(s)); } function hexMD5(s) { return rstr2hex(rawMD5(s)); } function rawHMACMD5(k, d) { return rstrHMACMD5(str2rstrUTF8(k), str2rstrUTF8(d)); } function hexHMACMD5(k, d) { return rstr2hex(rawHMACMD5(k, d)); } function md5(string, key, raw) { if (!key) { if (!raw) { return hexMD5(string); } return rawMD5(string); } if (!raw) { return hexHMACMD5(key, string); } return rawHMACMD5(key, string); } if (typeof define === "function" && define.amd) { define(function() { return md5; }); } else if (typeof module === "object" && module.exports) { module.exports = md5; } else { $.md5 = md5; } })(typeof window !== "undefined" ? window : this); /*! jQuery v3.7.1 | MIT License | https://jquery.org/license */ (function(global, factory) { "use strict"; if (typeof module === "object" && typeof module.exports === "object") { module.exports = global.document ? factory(global, true) : function(w) { if (!w.document) { throw new Error("jQuery requires a window with a document"); } return factory(w); }; } else { factory(global); } })(typeof window !== "undefined" ? window : this, function(window2, noGlobal) { "use strict"; var arr = []; var getProto = Object.getPrototypeOf; var slice = arr.slice; var flat = arr.flat ? function(array) { return arr.flat.call(array); } : function(array) { return arr.concat.apply([], array); }; var push = arr.push; var indexOf = arr.indexOf; var class2type = {}; var toString = class2type.toString; var hasOwn = class2type.hasOwnProperty; var fnToString = hasOwn.toString; var ObjectFunctionString = fnToString.call(Object); var support = {}; var isFunction = function isFunction2(obj) { return typeof obj === "function" && typeof obj.nodeType !== "number" && typeof obj.item !== "function"; }; var isWindow = function isWindow2(obj) { return obj != null && obj === obj.window; }; var document = window2.document; var preservedScriptAttributes = { type: true, src: true, nonce: true, noModule: true }; function DOMEval(code, node, doc) { doc = doc || document; var i, val, script = doc.createElement("script"); script.text = code; if (node) { for (i in preservedScriptAttributes) { val = node[i] || node.getAttribute && node.getAttribute(i); if (val) { script.setAttribute(i, val); } } } doc.head.appendChild(script).parentNode.removeChild(script); } function toType(obj) { if (obj == null) { return obj + ""; } return typeof obj === "object" || typeof obj === "function" ? class2type[toString.call(obj)] || "object" : typeof obj; } var version = "3.7.1", rhtmlSuffix = /HTML$/i, jQuery = function(selector, context) { return new jQuery.fn.init(selector, context); }; jQuery.fn = jQuery.prototype = { jquery: version, constructor: jQuery, length: 0, toArray: function() { return slice.call(this); }, get: function(num) { if (num == null) { return slice.call(this); } return num < 0 ? this[num + this.length] : this[num]; }, pushStack: function(elems) { var ret = jQuery.merge(this.constructor(), elems); ret.prevObject = this; return ret; }, each: function(callback) { return jQuery.each(this, callback); }, map: function(callback) { return this.pushStack(jQuery.map(this, function(elem, i) { return callback.call(elem, i, elem); })); }, slice: function() { return this.pushStack(slice.apply(this, arguments)); }, first: function() { return this.eq(0); }, last: function() { return this.eq(-1); }, even: function() { return this.pushStack(jQuery.grep(this, function(_elem, i) { return (i + 1) % 2; })); }, odd: function() { return this.pushStack(jQuery.grep(this, function(_elem, i) { return i % 2; })); }, eq: function(i) { var len = this.length, j = +i + (i < 0 ? len : 0); return this.pushStack(j >= 0 && j < len ? [this[j]] : []); }, end: function() { return this.prevObject || this.constructor(); }, push, sort: arr.sort, splice: arr.splice }; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; if (typeof target === "boolean") { deep = target; target = arguments[i] || {}; i++; } if (typeof target !== "object" && !isFunction(target)) { target = {}; } if (i === length) { target = this; i--; } for (; i < length; i++) { if ((options = arguments[i]) != null) { for (name in options) { copy = options[name]; if (name === "__proto__" || target === copy) { continue; } if (deep && copy && (jQuery.isPlainObject(copy) || (copyIsArray = Array.isArray(copy)))) { src = target[name]; if (copyIsArray && !Array.isArray(src)) { clone = []; } else if (!copyIsArray && !jQuery.isPlainObject(src)) { clone = {}; } else { clone = src; } copyIsArray = false; target[name] = jQuery.extend(deep, clone, copy); } else if (copy !== void 0) { target[name] = copy; } } } } return target; }; jQuery.extend({ expando: "jQuery" + (version + Math.random()).replace(/\D/g, ""), isReady: true, error: function(msg) { throw new Error(msg); }, noop: function() { }, isPlainObject: function(obj) { var proto, Ctor; if (!obj || toString.call(obj) !== "[object Object]") { return false; } proto = getProto(obj); if (!proto) { return true; } Ctor = hasOwn.call(proto, "constructor") && proto.constructor; return typeof Ctor === "function" && fnToString.call(Ctor) === ObjectFunctionString; }, isEmptyObject: function(obj) { var name; for (name in obj) { return false; } return true; }, globalEval: function(code, options, doc) { DOMEval(code, { nonce: options && options.nonce }, doc); }, each: function(obj, callback) { var length, i = 0; if (isArrayLike(obj)) { length = obj.length; for (; i < length; i++) { if (callback.call(obj[i], i, obj[i]) === false) { break; } } } else { for (i in obj) { if (callback.call(obj[i], i, obj[i]) === false) { break; } } } return obj; }, text: function(elem) { var node, ret = "", i = 0, nodeType = elem.nodeType; if (!nodeType) { while (node = elem[i++]) { ret += jQuery.text(node); } } if (nodeType === 1 || nodeType === 11) { return elem.textContent; } if (nodeType === 9) { return elem.documentElement.textContent; } if (nodeType === 3 || nodeType === 4) { return elem.nodeValue; } return ret; }, makeArray: function(arr2, results) { var ret = results || []; if (arr2 != null) { if (isArrayLike(Object(arr2))) { jQuery.merge( ret, typeof arr2 === "string" ? [arr2] : arr2 ); } else { push.call(ret, arr2); } } return ret; }, inArray: function(elem, arr2, i) { return arr2 == null ? -1 : indexOf.call(arr2, elem, i); }, isXMLDoc: function(elem) { var namespace = elem && elem.namespaceURI, docElem = elem && (elem.ownerDocument || elem).documentElement; return !rhtmlSuffix.test(namespace || docElem && docElem.nodeName || "HTML"); }, merge: function(first, second) { var len = +second.length, j = 0, i = first.length; for (; j < len; j++) { first[i++] = second[j]; } first.length = i; return first; }, grep: function(elems, callback, invert) { var callbackInverse, matches = [], i = 0, length = elems.length, callbackExpect = !invert; for (; i < length; i++) { callbackInverse = !callback(elems[i], i); if (callbackInverse !== callbackExpect) { matches.push(elems[i]); } } return matches; }, map: function(elems, callback, arg) { var length, value, i = 0, ret = []; if (isArrayLike(elems)) { length = elems.length; for (; i < length; i++) { value = callback(elems[i], i, arg); if (value != null) { ret.push(value); } } } else { for (i in elems) { value = callback(elems[i], i, arg); if (value != null) { ret.push(value); } } } return flat(ret); }, guid: 1, support }); if (typeof Symbol === "function") { jQuery.fn[Symbol.iterator] = arr[Symbol.iterator]; } jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "), function(_i, name) { class2type["[object " + name + "]"] = name.toLowerCase(); } ); function isArrayLike(obj) { var length = !!obj && "length" in obj && obj.length, type = toType(obj); if (isFunction(obj) || isWindow(obj)) { return false; } return type === "array" || length === 0 || typeof length === "number" && length > 0 && length - 1 in obj; } function nodeName(elem, name) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); } var pop = arr.pop; var sort = arr.sort; var splice = arr.splice; var whitespace = "[\\x20\\t\\r\\n\\f]"; var rtrimCSS = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ); jQuery.contains = function(a, b) { var bup = b && b.parentNode; return a === bup || !!(bup && bup.nodeType === 1 && (a.contains ? a.contains(bup) : a.compareDocumentPosition && a.compareDocumentPosition(bup) & 16)); }; var rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\x80-\uFFFF\w-]/g; function fcssescape(ch, asCodePoint) { if (asCodePoint) { if (ch === "\0") { return "�"; } return ch.slice(0, -1) + "\\" + ch.charCodeAt(ch.length - 1).toString(16) + " "; } return "\\" + ch; } jQuery.escapeSelector = function(sel) { return (sel + "").replace(rcssescape, fcssescape); }; var preferredDoc = document, pushNative = push; (function() { var i, Expr, outermostContext, sortInput, hasDuplicate, push2 = pushNative, document2, documentElement2, documentIsHTML, rbuggyQSA, matches, expando = jQuery.expando, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), nonnativeSelectorCache = createCache(), sortOrder = function(a, b) { if (a === b) { hasDuplicate = true; } return 0; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", identifier = "(?:\\\\[\\da-fA-F]{1,6}" + whitespace + "?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+", attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + "*([*^$|!~]?=)" + whitespace + `*(?:'((?:\\\\.|[^\\\\'])*)'|"((?:\\\\.|[^\\\\"])*)"|(` + identifier + "))|)" + whitespace + "*\\]", pseudos = ":(" + identifier + `)(?:\\((('((?:\\\\.|[^\\\\'])*)'|"((?:\\\\.|[^\\\\"])*)")|((?:\\\\.|[^\\\\()[\\]]|` + attributes + ")*)|.*)\\)|)", rwhitespace = new RegExp(whitespace + "+", "g"), rcomma = new RegExp("^" + whitespace + "*," + whitespace + "*"), rleadingCombinator = new RegExp("^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*"), rdescend = new RegExp(whitespace + "|>"), rpseudo = new RegExp(pseudos), ridentifier = new RegExp("^" + identifier + "$"), matchExpr = { ID: new RegExp("^#(" + identifier + ")"), CLASS: new RegExp("^\\.(" + identifier + ")"), TAG: new RegExp("^(" + identifier + "|[*])"), ATTR: new RegExp("^" + attributes), PSEUDO: new RegExp("^" + pseudos), CHILD: new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), bool: new RegExp("^(?:" + booleans + ")$", "i"), needsContext: new RegExp("^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i") }, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rquickExpr2 = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, runescape = new RegExp("\\\\[\\da-fA-F]{1,6}" + whitespace + "?|\\\\([^\\r\\n\\f])", "g"), funescape = function(escape, nonHex) { var high = "0x" + escape.slice(1) - 65536; if (nonHex) { return nonHex; } return high < 0 ? String.fromCharCode(high + 65536) : String.fromCharCode(high >> 10 | 55296, high & 1023 | 56320); }, unloadHandler = function() { setDocument(); }, inDisabledFieldset = addCombinator( function(elem) { return elem.disabled === true && nodeName(elem, "fieldset"); }, { dir: "parentNode", next: "legend" } ); function safeActiveElement() { try { return document2.activeElement; } catch (err) { } } try { push2.apply( arr = slice.call(preferredDoc.childNodes), preferredDoc.childNodes ); arr[preferredDoc.childNodes.length].nodeType; } catch (e) { push2 = { apply: function(target, els) { pushNative.apply(target, slice.call(els)); }, call: function(target) { pushNative.apply(target, slice.call(arguments, 1)); } }; } function find(selector, context, results, seed) { var m, i2, elem, nid, match, groups, newSelector, newContext = context && context.ownerDocument, nodeType = context ? context.nodeType : 9; results = results || []; if (typeof selector !== "string" || !selector || nodeType !== 1 && nodeType !== 9 && nodeType !== 11) { return results; } if (!seed) { setDocument(context); context = context || document2; if (documentIsHTML) { if (nodeType !== 11 && (match = rquickExpr2.exec(selector))) { if (m = match[1]) { if (nodeType === 9) { if (elem = context.getElementById(m)) { if (elem.id === m) { push2.call(results, elem); return results; } } else { return results; } } else { if (newContext && (elem = newContext.getElementById(m)) && find.contains(context, elem) && elem.id === m) { push2.call(results, elem); return results; } } } else if (match[2]) { push2.apply(results, context.getElementsByTagName(selector)); return results; } else if ((m = match[3]) && context.getElementsByClassName) { push2.apply(results, context.getElementsByClassName(m)); return results; } } if (!nonnativeSelectorCache[selector + " "] && (!rbuggyQSA || !rbuggyQSA.test(selector))) { newSelector = selector; newContext = context; if (nodeType === 1 && (rdescend.test(selector) || rleadingCombinator.test(selector))) { newContext = rsibling.test(selector) && testContext(context.parentNode) || context; if (newContext != context || !support.scope) { if (nid = context.getAttribute("id")) { nid = jQuery.escapeSelector(nid); } else { context.setAttribute("id", nid = expando); } } groups = tokenize(selector); i2 = groups.length; while (i2--) { groups[i2] = (nid ? "#" + nid : ":scope") + " " + toSelector(groups[i2]); } newSelector = groups.join(","); } try { push2.apply( results, newContext.querySelectorAll(newSelector) ); return results; } catch (qsaError) { nonnativeSelectorCache(selector, true); } finally { if (nid === expando) { context.removeAttribute("id"); } } } } } return select(selector.replace(rtrimCSS, "$1"), context, results, seed); } function createCache() { var keys = []; function cache(key, value) { if (keys.push(key + " ") > Expr.cacheLength) { delete cache[keys.shift()]; } return cache[key + " "] = value; } return cache; } function markFunction(fn) { fn[expando] = true; return fn; } function assert(fn) { var el = document2.createElement("fieldset"); try { return !!fn(el); } catch (e) { return false; } finally { if (el.parentNode) { el.parentNode.removeChild(el); } el = null; } } function createInputPseudo(type) { return function(elem) { return nodeName(elem, "input") && elem.type === type; }; } function createButtonPseudo(type) { return function(elem) { return (nodeName(elem, "input") || nodeName(elem, "button")) && elem.type === type; }; } function createDisabledPseudo(disabled) { return function(elem) { if ("form" in elem) { if (elem.parentNode && elem.disabled === false) { if ("label" in elem) { if ("label" in elem.parentNode) { return elem.parentNode.disabled === disabled; } else { return elem.disabled === disabled; } } return elem.isDisabled === disabled || elem.isDisabled !== !disabled && inDisabledFieldset(elem) === disabled; } return elem.disabled === disabled; } else if ("label" in elem) { return elem.disabled === disabled; } return false; }; } function createPositionalPseudo(fn) { return markFunction(function(argument) { argument = +argument; return markFunction(function(seed, matches2) { var j, matchIndexes = fn([], seed.length, argument), i2 = matchIndexes.length; while (i2--) { if (seed[j = matchIndexes[i2]]) { seed[j] = !(matches2[j] = seed[j]); } } }); }); } function testContext(context) { return context && typeof context.getElementsByTagName !== "undefined" && context; } function setDocument(node) { var subWindow, doc = node ? node.ownerDocument || node : preferredDoc; if (doc == document2 || doc.nodeType !== 9 || !doc.documentElement) { return document2; } document2 = doc; documentElement2 = document2.documentElement; documentIsHTML = !jQuery.isXMLDoc(document2); matches = documentElement2.matches || documentElement2.webkitMatchesSelector || documentElement2.msMatchesSelector; if (documentElement2.msMatchesSelector && preferredDoc != document2 && (subWindow = document2.defaultView) && subWindow.top !== subWindow) { subWindow.addEventListener("unload", unloadHandler); } support.getById = assert(function(el) { documentElement2.appendChild(el).id = jQuery.expando; return !document2.getElementsByName || !document2.getElementsByName(jQuery.expando).length; }); support.disconnectedMatch = assert(function(el) { return matches.call(el, "*"); }); support.scope = assert(function() { return document2.querySelectorAll(":scope"); }); support.cssHas = assert(function() { try { document2.querySelector(":has(*,:jqfake)"); return false; } catch (e) { return true; } }); if (support.getById) { Expr.filter.ID = function(id) { var attrId = id.replace(runescape, funescape); return function(elem) { return elem.getAttribute("id") === attrId; }; }; Expr.find.ID = function(id, context) { if (typeof context.getElementById !== "undefined" && documentIsHTML) { var elem = context.getElementById(id); return elem ? [elem] : []; } }; } else { Expr.filter.ID = function(id) { var attrId = id.replace(runescape, funescape); return function(elem) { var node2 = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return node2 && node2.value === attrId; }; }; Expr.find.ID = function(id, context) { if (typeof context.getElementById !== "undefined" && documentIsHTML) { var node2, i2, elems, elem = context.getElementById(id); if (elem) { node2 = elem.getAttributeNode("id"); if (node2 && node2.value === id) { return [elem]; } elems = context.getElementsByName(id); i2 = 0; while (elem = elems[i2++]) { node2 = elem.getAttributeNode("id"); if (node2 && node2.value === id) { return [elem]; } } } return []; } }; } Expr.find.TAG = function(tag, context) { if (typeof context.getElementsByTagName !== "undefined") { return context.getElementsByTagName(tag); } else { return context.querySelectorAll(tag); } }; Expr.find.CLASS = function(className, context) { if (typeof context.getElementsByClassName !== "undefined" && documentIsHTML) { return context.getElementsByClassName(className); } }; rbuggyQSA = []; assert(function(el) { var input; documentElement2.appendChild(el).innerHTML = ""; if (!el.querySelectorAll("[selected]").length) { rbuggyQSA.push("\\[" + whitespace + "*(?:value|" + booleans + ")"); } if (!el.querySelectorAll("[id~=" + expando + "-]").length) { rbuggyQSA.push("~="); } if (!el.querySelectorAll("a#" + expando + "+*").length) { rbuggyQSA.push(".#.+[+~]"); } if (!el.querySelectorAll(":checked").length) { rbuggyQSA.push(":checked"); } input = document2.createElement("input"); input.setAttribute("type", "hidden"); el.appendChild(input).setAttribute("name", "D"); documentElement2.appendChild(el).disabled = true; if (el.querySelectorAll(":disabled").length !== 2) { rbuggyQSA.push(":enabled", ":disabled"); } input = document2.createElement("input"); input.setAttribute("name", ""); el.appendChild(input); if (!el.querySelectorAll("[name='']").length) { rbuggyQSA.push("\\[" + whitespace + "*name" + whitespace + "*=" + whitespace + `*(?:''|"")`); } }); if (!support.cssHas) { rbuggyQSA.push(":has"); } rbuggyQSA = rbuggyQSA.length && new RegExp(rbuggyQSA.join("|")); sortOrder = function(a, b) { if (a === b) { hasDuplicate = true; return 0; } var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; if (compare) { return compare; } compare = (a.ownerDocument || a) == (b.ownerDocument || b) ? a.compareDocumentPosition(b) : ( 1 ); if (compare & 1 || !support.sortDetached && b.compareDocumentPosition(a) === compare) { if (a === document2 || a.ownerDocument == preferredDoc && find.contains(preferredDoc, a)) { return -1; } if (b === document2 || b.ownerDocument == preferredDoc && find.contains(preferredDoc, b)) { return 1; } return sortInput ? indexOf.call(sortInput, a) - indexOf.call(sortInput, b) : 0; } return compare & 4 ? -1 : 1; }; return document2; } find.matches = function(expr, elements) { return find(expr, null, null, elements); }; find.matchesSelector = function(elem, expr) { setDocument(elem); if (documentIsHTML && !nonnativeSelectorCache[expr + " "] && (!rbuggyQSA || !rbuggyQSA.test(expr))) { try { var ret = matches.call(elem, expr); if (ret || support.disconnectedMatch || elem.document && elem.document.nodeType !== 11) { return ret; } } catch (e) { nonnativeSelectorCache(expr, true); } } return find(expr, document2, null, [elem]).length > 0; }; find.contains = function(context, elem) { if ((context.ownerDocument || context) != document2) { setDocument(context); } return jQuery.contains(context, elem); }; find.attr = function(elem, name) { if ((elem.ownerDocument || elem) != document2) { setDocument(elem); } var fn = Expr.attrHandle[name.toLowerCase()], val = fn && hasOwn.call(Expr.attrHandle, name.toLowerCase()) ? fn(elem, name, !documentIsHTML) : void 0; if (val !== void 0) { return val; } return elem.getAttribute(name); }; find.error = function(msg) { throw new Error("Syntax error, unrecognized expression: " + msg); }; jQuery.uniqueSort = function(results) { var elem, duplicates = [], j = 0, i2 = 0; hasDuplicate = !support.sortStable; sortInput = !support.sortStable && slice.call(results, 0); sort.call(results, sortOrder); if (hasDuplicate) { while (elem = results[i2++]) { if (elem === results[i2]) { j = duplicates.push(i2); } } while (j--) { splice.call(results, duplicates[j], 1); } } sortInput = null; return results; }; jQuery.fn.uniqueSort = function() { return this.pushStack(jQuery.uniqueSort(slice.apply(this))); }; Expr = jQuery.expr = { cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { ATTR: function(match) { match[1] = match[1].replace(runescape, funescape); match[3] = (match[3] || match[4] || match[5] || "").replace(runescape, funescape); if (match[2] === "~=") { match[3] = " " + match[3] + " "; } return match.slice(0, 4); }, CHILD: function(match) { match[1] = match[1].toLowerCase(); if (match[1].slice(0, 3) === "nth") { if (!match[3]) { find.error(match[0]); } match[4] = +(match[4] ? match[5] + (match[6] || 1) : 2 * (match[3] === "even" || match[3] === "odd")); match[5] = +(match[7] + match[8] || match[3] === "odd"); } else if (match[3]) { find.error(match[0]); } return match; }, PSEUDO: function(match) { var excess, unquoted = !match[6] && match[2]; if (matchExpr.CHILD.test(match[0])) { return null; } if (match[3]) { match[2] = match[4] || match[5] || ""; } else if (unquoted && rpseudo.test(unquoted) && (excess = tokenize(unquoted, true)) && (excess = unquoted.indexOf(")", unquoted.length - excess) - unquoted.length)) { match[0] = match[0].slice(0, excess); match[2] = unquoted.slice(0, excess); } return match.slice(0, 3); } }, filter: { TAG: function(nodeNameSelector) { var expectedNodeName = nodeNameSelector.replace(runescape, funescape).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function(elem) { return nodeName(elem, expectedNodeName); }; }, CLASS: function(className) { var pattern = classCache[className + " "]; return pattern || (pattern = new RegExp("(^|" + whitespace + ")" + className + "(" + whitespace + "|$)")) && classCache(className, function(elem) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" ); }); }, ATTR: function(name, operator, check) { return function(elem) { var result = find.attr(elem, name); if (result == null) { return operator === "!="; } if (!operator) { return true; } result += ""; if (operator === "=") { return result === check; } if (operator === "!=") { return result !== check; } if (operator === "^=") { return check && result.indexOf(check) === 0; } if (operator === "*=") { return check && result.indexOf(check) > -1; } if (operator === "$=") { return check && result.slice(-check.length) === check; } if (operator === "~=") { return (" " + result.replace(rwhitespace, " ") + " ").indexOf(check) > -1; } if (operator === "|=") { return result === check || result.slice(0, check.length + 1) === check + "-"; } return false; }; }, CHILD: function(type, what, _argument, first, last) { var simple = type.slice(0, 3) !== "nth", forward = type.slice(-4) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? ( function(elem) { return !!elem.parentNode; } ) : function(elem, _context, xml) { var cache, outerCache, node, nodeIndex, start, dir2 = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType, diff = false; if (parent) { if (simple) { while (dir2) { node = elem; while (node = node[dir2]) { if (ofType ? nodeName(node, name) : node.nodeType === 1) { return false; } } start = dir2 = type === "only" && !start && "nextSibling"; } return true; } start = [forward ? parent.firstChild : parent.lastChild]; if (forward && useCache) { outerCache = parent[expando] || (parent[expando] = {}); cache = outerCache[type] || []; nodeIndex = cache[0] === dirruns && cache[1]; diff = nodeIndex && cache[2]; node = nodeIndex && parent.childNodes[nodeIndex]; while (node = ++nodeIndex && node && node[dir2] || (diff = nodeIndex = 0) || start.pop()) { if (node.nodeType === 1 && ++diff && node === elem) { outerCache[type] = [dirruns, nodeIndex, diff]; break; } } } else { if (useCache) { outerCache = elem[expando] || (elem[expando] = {}); cache = outerCache[type] || []; nodeIndex = cache[0] === dirruns && cache[1]; diff = nodeIndex; } if (diff === false) { while (node = ++nodeIndex && node && node[dir2] || (diff = nodeIndex = 0) || start.pop()) { if ((ofType ? nodeName(node, name) : node.nodeType === 1) && ++diff) { if (useCache) { outerCache = node[expando] || (node[expando] = {}); outerCache[type] = [dirruns, diff]; } if (node === elem) { break; } } } } } diff -= last; return diff === first || diff % first === 0 && diff / first >= 0; } }; }, PSEUDO: function(pseudo, argument) { var args, fn = Expr.pseudos[pseudo] || Expr.setFilters[pseudo.toLowerCase()] || find.error("unsupported pseudo: " + pseudo); if (fn[expando]) { return fn(argument); } if (fn.length > 1) { args = [pseudo, pseudo, "", argument]; return Expr.setFilters.hasOwnProperty(pseudo.toLowerCase()) ? markFunction(function(seed, matches2) { var idx, matched = fn(seed, argument), i2 = matched.length; while (i2--) { idx = indexOf.call(seed, matched[i2]); seed[idx] = !(matches2[idx] = matched[i2]); } }) : function(elem) { return fn(elem, 0, args); }; } return fn; } }, pseudos: { not: markFunction(function(selector) { var input = [], results = [], matcher = compile(selector.replace(rtrimCSS, "$1")); return matcher[expando] ? markFunction(function(seed, matches2, _context, xml) { var elem, unmatched = matcher(seed, null, xml, []), i2 = seed.length; while (i2--) { if (elem = unmatched[i2]) { seed[i2] = !(matches2[i2] = elem); } } }) : function(elem, _context, xml) { input[0] = elem; matcher(input, null, xml, results); input[0] = null; return !results.pop(); }; }), has: markFunction(function(selector) { return function(elem) { return find(selector, elem).length > 0; }; }), contains: markFunction(function(text) { text = text.replace(runescape, funescape); return function(elem) { return (elem.textContent || jQuery.text(elem)).indexOf(text) > -1; }; }), lang: markFunction(function(lang) { if (!ridentifier.test(lang || "")) { find.error("unsupported lang: " + lang); } lang = lang.replace(runescape, funescape).toLowerCase(); return function(elem) { var elemLang; do { if (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf(lang + "-") === 0; } } while ((elem = elem.parentNode) && elem.nodeType === 1); return false; }; }), target: function(elem) { var hash = window2.location && window2.location.hash; return hash && hash.slice(1) === elem.id; }, root: function(elem) { return elem === documentElement2; }, focus: function(elem) { return elem === safeActiveElement() && document2.hasFocus() && !!(elem.type || elem.href || ~elem.tabIndex); }, enabled: createDisabledPseudo(false), disabled: createDisabledPseudo(true), checked: function(elem) { return nodeName(elem, "input") && !!elem.checked || nodeName(elem, "option") && !!elem.selected; }, selected: function(elem) { if (elem.parentNode) { elem.parentNode.selectedIndex; } return elem.selected === true; }, empty: function(elem) { for (elem = elem.firstChild; elem; elem = elem.nextSibling) { if (elem.nodeType < 6) { return false; } } return true; }, parent: function(elem) { return !Expr.pseudos.empty(elem); }, header: function(elem) { return rheader.test(elem.nodeName); }, input: function(elem) { return rinputs.test(elem.nodeName); }, button: function(elem) { return nodeName(elem, "input") && elem.type === "button" || nodeName(elem, "button"); }, text: function(elem) { var attr; return nodeName(elem, "input") && elem.type === "text" && ((attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text"); }, first: createPositionalPseudo(function() { return [0]; }), last: createPositionalPseudo(function(_matchIndexes, length) { return [length - 1]; }), eq: createPositionalPseudo(function(_matchIndexes, length, argument) { return [argument < 0 ? argument + length : argument]; }), even: createPositionalPseudo(function(matchIndexes, length) { var i2 = 0; for (; i2 < length; i2 += 2) { matchIndexes.push(i2); } return matchIndexes; }), odd: createPositionalPseudo(function(matchIndexes, length) { var i2 = 1; for (; i2 < length; i2 += 2) { matchIndexes.push(i2); } return matchIndexes; }), lt: createPositionalPseudo(function(matchIndexes, length, argument) { var i2; if (argument < 0) { i2 = argument + length; } else if (argument > length) { i2 = length; } else { i2 = argument; } for (; --i2 >= 0; ) { matchIndexes.push(i2); } return matchIndexes; }), gt: createPositionalPseudo(function(matchIndexes, length, argument) { var i2 = argument < 0 ? argument + length : argument; for (; ++i2 < length; ) { matchIndexes.push(i2); } return matchIndexes; }) } }; Expr.pseudos.nth = Expr.pseudos.eq; for (i in { radio: true, checkbox: true, file: true, password: true, image: true }) { Expr.pseudos[i] = createInputPseudo(i); } for (i in { submit: true, reset: true }) { Expr.pseudos[i] = createButtonPseudo(i); } function setFilters() { } setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); function tokenize(selector, parseOnly) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[selector + " "]; if (cached) { return parseOnly ? 0 : cached.slice(0); } soFar = selector; groups = []; preFilters = Expr.preFilter; while (soFar) { if (!matched || (match = rcomma.exec(soFar))) { if (match) { soFar = soFar.slice(match[0].length) || soFar; } groups.push(tokens = []); } matched = false; if (match = rleadingCombinator.exec(soFar)) { matched = match.shift(); tokens.push({ value: matched, type: match[0].replace(rtrimCSS, " ") }); soFar = soFar.slice(matched.length); } for (type in Expr.filter) { if ((match = matchExpr[type].exec(soFar)) && (!preFilters[type] || (match = preFilters[type](match)))) { matched = match.shift(); tokens.push({ value: matched, type, matches: match }); soFar = soFar.slice(matched.length); } } if (!matched) { break; } } if (parseOnly) { return soFar.length; } return soFar ? find.error(selector) : ( tokenCache(selector, groups).slice(0) ); } function toSelector(tokens) { var i2 = 0, len = tokens.length, selector = ""; for (; i2 < len; i2++) { selector += tokens[i2].value; } return selector; } function addCombinator(matcher, combinator, base) { var dir2 = combinator.dir, skip = combinator.next, key = skip || dir2, checkNonElements = base && key === "parentNode", doneName = done++; return combinator.first ? ( function(elem, context, xml) { while (elem = elem[dir2]) { if (elem.nodeType === 1 || checkNonElements) { return matcher(elem, context, xml); } } return false; } ) : ( function(elem, context, xml) { var oldCache, outerCache, newCache = [dirruns, doneName]; if (xml) { while (elem = elem[dir2]) { if (elem.nodeType === 1 || checkNonElements) { if (matcher(elem, context, xml)) { return true; } } } } else { while (elem = elem[dir2]) { if (elem.nodeType === 1 || checkNonElements) { outerCache = elem[expando] || (elem[expando] = {}); if (skip && nodeName(elem, skip)) { elem = elem[dir2] || elem; } else if ((oldCache = outerCache[key]) && oldCache[0] === dirruns && oldCache[1] === doneName) { return newCache[2] = oldCache[2]; } else { outerCache[key] = newCache; if (newCache[2] = matcher(elem, context, xml)) { return true; } } } } } return false; } ); } function elementMatcher(matchers) { return matchers.length > 1 ? function(elem, context, xml) { var i2 = matchers.length; while (i2--) { if (!matchers[i2](elem, context, xml)) { return false; } } return true; } : matchers[0]; } function multipleContexts(selector, contexts, results) { var i2 = 0, len = contexts.length; for (; i2 < len; i2++) { find(selector, contexts[i2], results); } return results; } function condense(unmatched, map, filter, context, xml) { var elem, newUnmatched = [], i2 = 0, len = unmatched.length, mapped = map != null; for (; i2 < len; i2++) { if (elem = unmatched[i2]) { if (!filter || filter(elem, context, xml)) { newUnmatched.push(elem); if (mapped) { map.push(i2); } } } } return newUnmatched; } function setMatcher(preFilter, selector, matcher, postFilter, postFinder, postSelector) { if (postFilter && !postFilter[expando]) { postFilter = setMatcher(postFilter); } if (postFinder && !postFinder[expando]) { postFinder = setMatcher(postFinder, postSelector); } return markFunction(function(seed, results, context, xml) { var temp, i2, elem, matcherOut, preMap = [], postMap = [], preexisting = results.length, elems = seed || multipleContexts( selector || "*", context.nodeType ? [context] : context, [] ), matcherIn = preFilter && (seed || !selector) ? condense(elems, preMap, preFilter, context, xml) : elems; if (matcher) { matcherOut = postFinder || (seed ? preFilter : preexisting || postFilter) ? ( [] ) : ( results ); matcher(matcherIn, matcherOut, context, xml); } else { matcherOut = matcherIn; } if (postFilter) { temp = condense(matcherOut, postMap); postFilter(temp, [], context, xml); i2 = temp.length; while (i2--) { if (elem = temp[i2]) { matcherOut[postMap[i2]] = !(matcherIn[postMap[i2]] = elem); } } } if (seed) { if (postFinder || preFilter) { if (postFinder) { temp = []; i2 = matcherOut.length; while (i2--) { if (elem = matcherOut[i2]) { temp.push(matcherIn[i2] = elem); } } postFinder(null, matcherOut = [], temp, xml); } i2 = matcherOut.length; while (i2--) { if ((elem = matcherOut[i2]) && (temp = postFinder ? indexOf.call(seed, elem) : preMap[i2]) > -1) { seed[temp] = !(results[temp] = elem); } } } } else { matcherOut = condense( matcherOut === results ? matcherOut.splice(preexisting, matcherOut.length) : matcherOut ); if (postFinder) { postFinder(null, results, matcherOut, xml); } else { push2.apply(results, matcherOut); } } }); } function matcherFromTokens(tokens) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[tokens[0].type], implicitRelative = leadingRelative || Expr.relative[" "], i2 = leadingRelative ? 1 : 0, matchContext = addCombinator(function(elem) { return elem === checkContext; }, implicitRelative, true), matchAnyContext = addCombinator(function(elem) { return indexOf.call(checkContext, elem) > -1; }, implicitRelative, true), matchers = [function(elem, context, xml) { var ret = !leadingRelative && (xml || context != outermostContext) || ((checkContext = context).nodeType ? matchContext(elem, context, xml) : matchAnyContext(elem, context, xml)); checkContext = null; return ret; }]; for (; i2 < len; i2++) { if (matcher = Expr.relative[tokens[i2].type]) { matchers = [addCombinator(elementMatcher(matchers), matcher)]; } else { matcher = Expr.filter[tokens[i2].type].apply(null, tokens[i2].matches); if (matcher[expando]) { j = ++i2; for (; j < len; j++) { if (Expr.relative[tokens[j].type]) { break; } } return setMatcher( i2 > 1 && elementMatcher(matchers), i2 > 1 && toSelector( tokens.slice(0, i2 - 1).concat({ value: tokens[i2 - 2].type === " " ? "*" : "" }) ).replace(rtrimCSS, "$1"), matcher, i2 < j && matcherFromTokens(tokens.slice(i2, j)), j < len && matcherFromTokens(tokens = tokens.slice(j)), j < len && toSelector(tokens) ); } matchers.push(matcher); } } return elementMatcher(matchers); } function matcherFromGroupMatchers(elementMatchers, setMatchers) { var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function(seed, context, xml, results, outermost) { var elem, j, matcher, matchedCount = 0, i2 = "0", unmatched = seed && [], setMatched = [], contextBackup = outermostContext, elems = seed || byElement && Expr.find.TAG("*", outermost), dirrunsUnique = dirruns += contextBackup == null ? 1 : Math.random() || 0.1, len = elems.length; if (outermost) { outermostContext = context == document2 || context || outermost; } for (; i2 !== len && (elem = elems[i2]) != null; i2++) { if (byElement && elem) { j = 0; if (!context && elem.ownerDocument != document2) { setDocument(elem); xml = !documentIsHTML; } while (matcher = elementMatchers[j++]) { if (matcher(elem, context || document2, xml)) { push2.call(results, elem); break; } } if (outermost) { dirruns = dirrunsUnique; } } if (bySet) { if (elem = !matcher && elem) { matchedCount--; } if (seed) { unmatched.push(elem); } } } matchedCount += i2; if (bySet && i2 !== matchedCount) { j = 0; while (matcher = setMatchers[j++]) { matcher(unmatched, setMatched, context, xml); } if (seed) { if (matchedCount > 0) { while (i2--) { if (!(unmatched[i2] || setMatched[i2])) { setMatched[i2] = pop.call(results); } } } setMatched = condense(setMatched); } push2.apply(results, setMatched); if (outermost && !seed && setMatched.length > 0 && matchedCount + setMatchers.length > 1) { jQuery.uniqueSort(results); } } if (outermost) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction(superMatcher) : superMatcher; } function compile(selector, match) { var i2, setMatchers = [], elementMatchers = [], cached = compilerCache[selector + " "]; if (!cached) { if (!match) { match = tokenize(selector); } i2 = match.length; while (i2--) { cached = matcherFromTokens(match[i2]); if (cached[expando]) { setMatchers.push(cached); } else { elementMatchers.push(cached); } } cached = compilerCache( selector, matcherFromGroupMatchers(elementMatchers, setMatchers) ); cached.selector = selector; } return cached; } function select(selector, context, results, seed) { var i2, tokens, token, type, find2, compiled = typeof selector === "function" && selector, match = !seed && tokenize(selector = compiled.selector || selector); results = results || []; if (match.length === 1) { tokens = match[0] = match[0].slice(0); if (tokens.length > 2 && (token = tokens[0]).type === "ID" && context.nodeType === 9 && documentIsHTML && Expr.relative[tokens[1].type]) { context = (Expr.find.ID( token.matches[0].replace(runescape, funescape), context ) || [])[0]; if (!context) { return results; } else if (compiled) { context = context.parentNode; } selector = selector.slice(tokens.shift().value.length); } i2 = matchExpr.needsContext.test(selector) ? 0 : tokens.length; while (i2--) { token = tokens[i2]; if (Expr.relative[type = token.type]) { break; } if (find2 = Expr.find[type]) { if (seed = find2( token.matches[0].replace(runescape, funescape), rsibling.test(tokens[0].type) && testContext(context.parentNode) || context )) { tokens.splice(i2, 1); selector = seed.length && toSelector(tokens); if (!selector) { push2.apply(results, seed); return results; } break; } } } } (compiled || compile(selector, match))( seed, context, !documentIsHTML, results, !context || rsibling.test(selector) && testContext(context.parentNode) || context ); return results; } support.sortStable = expando.split("").sort(sortOrder).join("") === expando; setDocument(); support.sortDetached = assert(function(el) { return el.compareDocumentPosition(document2.createElement("fieldset")) & 1; }); jQuery.find = find; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = jQuery.uniqueSort; find.compile = compile; find.select = select; find.setDocument = setDocument; find.tokenize = tokenize; find.escape = jQuery.escapeSelector; find.getText = jQuery.text; find.isXML = jQuery.isXMLDoc; find.selectors = jQuery.expr; find.support = jQuery.support; find.uniqueSort = jQuery.uniqueSort; })(); var dir = function(elem, dir2, until) { var matched = [], truncate = until !== void 0; while ((elem = elem[dir2]) && elem.nodeType !== 9) { if (elem.nodeType === 1) { if (truncate && jQuery(elem).is(until)) { break; } matched.push(elem); } } return matched; }; var siblings = function(n, elem) { var matched = []; for (; n; n = n.nextSibling) { if (n.nodeType === 1 && n !== elem) { matched.push(n); } } return matched; }; var rneedsContext = jQuery.expr.match.needsContext; var rsingleTag = /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i; function winnow(elements, qualifier, not) { if (isFunction(qualifier)) { return jQuery.grep(elements, function(elem, i) { return !!qualifier.call(elem, i, elem) !== not; }); } if (qualifier.nodeType) { return jQuery.grep(elements, function(elem) { return elem === qualifier !== not; }); } if (typeof qualifier !== "string") { return jQuery.grep(elements, function(elem) { return indexOf.call(qualifier, elem) > -1 !== not; }); } return jQuery.filter(qualifier, elements, not); } jQuery.filter = function(expr, elems, not) { var elem = elems[0]; if (not) { expr = ":not(" + expr + ")"; } if (elems.length === 1 && elem.nodeType === 1) { return jQuery.find.matchesSelector(elem, expr) ? [elem] : []; } return jQuery.find.matches(expr, jQuery.grep(elems, function(elem2) { return elem2.nodeType === 1; })); }; jQuery.fn.extend({ find: function(selector) { var i, ret, len = this.length, self = this; if (typeof selector !== "string") { return this.pushStack(jQuery(selector).filter(function() { for (i = 0; i < len; i++) { if (jQuery.contains(self[i], this)) { return true; } } })); } ret = this.pushStack([]); for (i = 0; i < len; i++) { jQuery.find(selector, self[i], ret); } return len > 1 ? jQuery.uniqueSort(ret) : ret; }, filter: function(selector) { return this.pushStack(winnow(this, selector || [], false)); }, not: function(selector) { return this.pushStack(winnow(this, selector || [], true)); }, is: function(selector) { return !!winnow( this, typeof selector === "string" && rneedsContext.test(selector) ? jQuery(selector) : selector || [], false ).length; } }); var rootjQuery, rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/, init = jQuery.fn.init = function(selector, context, root) { var match, elem; if (!selector) { return this; } root = root || rootjQuery; if (typeof selector === "string") { if (selector[0] === "<" && selector[selector.length - 1] === ">" && selector.length >= 3) { match = [null, selector, null]; } else { match = rquickExpr.exec(selector); } if (match && (match[1] || !context)) { if (match[1]) { context = context instanceof jQuery ? context[0] : context; jQuery.merge(this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true )); if (rsingleTag.test(match[1]) && jQuery.isPlainObject(context)) { for (match in context) { if (isFunction(this[match])) { this[match](context[match]); } else { this.attr(match, context[match]); } } } return this; } else { elem = document.getElementById(match[2]); if (elem) { this[0] = elem; this.length = 1; } return this; } } else if (!context || context.jquery) { return (context || root).find(selector); } else { return this.constructor(context).find(selector); } } else if (selector.nodeType) { this[0] = selector; this.length = 1; return this; } else if (isFunction(selector)) { return root.ready !== void 0 ? root.ready(selector) : ( selector(jQuery) ); } return jQuery.makeArray(selector, this); }; init.prototype = jQuery.fn; rootjQuery = jQuery(document); var rparentsprev = /^(?:parents|prev(?:Until|All))/, guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ has: function(target) { var targets = jQuery(target, this), l = targets.length; return this.filter(function() { var i = 0; for (; i < l; i++) { if (jQuery.contains(this, targets[i])) { return true; } } }); }, closest: function(selectors, context) { var cur, i = 0, l = this.length, matched = [], targets = typeof selectors !== "string" && jQuery(selectors); if (!rneedsContext.test(selectors)) { for (; i < l; i++) { for (cur = this[i]; cur && cur !== context; cur = cur.parentNode) { if (cur.nodeType < 11 && (targets ? targets.index(cur) > -1 : ( cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors) ))) { matched.push(cur); break; } } } } return this.pushStack(matched.length > 1 ? jQuery.uniqueSort(matched) : matched); }, index: function(elem) { if (!elem) { return this[0] && this[0].parentNode ? this.first().prevAll().length : -1; } if (typeof elem === "string") { return indexOf.call(jQuery(elem), this[0]); } return indexOf.call( this, elem.jquery ? elem[0] : elem ); }, add: function(selector, context) { return this.pushStack( jQuery.uniqueSort( jQuery.merge(this.get(), jQuery(selector, context)) ) ); }, addBack: function(selector) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); function sibling(cur, dir2) { while ((cur = cur[dir2]) && cur.nodeType !== 1) { } return cur; } jQuery.each({ parent: function(elem) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function(elem) { return dir(elem, "parentNode"); }, parentsUntil: function(elem, _i, until) { return dir(elem, "parentNode", until); }, next: function(elem) { return sibling(elem, "nextSibling"); }, prev: function(elem) { return sibling(elem, "previousSibling"); }, nextAll: function(elem) { return dir(elem, "nextSibling"); }, prevAll: function(elem) { return dir(elem, "previousSibling"); }, nextUntil: function(elem, _i, until) { return dir(elem, "nextSibling", until); }, prevUntil: function(elem, _i, until) { return dir(elem, "previousSibling", until); }, siblings: function(elem) { return siblings((elem.parentNode || {}).firstChild, elem); }, children: function(elem) { return siblings(elem.firstChild); }, contents: function(elem) { if (elem.contentDocument != null && getProto(elem.contentDocument)) { return elem.contentDocument; } if (nodeName(elem, "template")) { elem = elem.content || elem; } return jQuery.merge([], elem.childNodes); } }, function(name, fn) { jQuery.fn[name] = function(until, selector) { var matched = jQuery.map(this, fn, until); if (name.slice(-5) !== "Until") { selector = until; } if (selector && typeof selector === "string") { matched = jQuery.filter(selector, matched); } if (this.length > 1) { if (!guaranteedUnique[name]) { jQuery.uniqueSort(matched); } if (rparentsprev.test(name)) { matched.reverse(); } } return this.pushStack(matched); }; }); var rnothtmlwhite = /[^\x20\t\r\n\f]+/g; function createOptions(options) { var object = {}; jQuery.each(options.match(rnothtmlwhite) || [], function(_, flag) { object[flag] = true; }); return object; } jQuery.Callbacks = function(options) { options = typeof options === "string" ? createOptions(options) : jQuery.extend({}, options); var firing, memory, fired, locked, list = [], queue = [], firingIndex = -1, fire = function() { locked = locked || options.once; fired = firing = true; for (; queue.length; firingIndex = -1) { memory = queue.shift(); while (++firingIndex < list.length) { if (list[firingIndex].apply(memory[0], memory[1]) === false && options.stopOnFalse) { firingIndex = list.length; memory = false; } } } if (!options.memory) { memory = false; } firing = false; if (locked) { if (memory) { list = []; } else { list = ""; } } }, self = { add: function() { if (list) { if (memory && !firing) { firingIndex = list.length - 1; queue.push(memory); } (function add(args) { jQuery.each(args, function(_, arg) { if (isFunction(arg)) { if (!options.unique || !self.has(arg)) { list.push(arg); } } else if (arg && arg.length && toType(arg) !== "string") { add(arg); } }); })(arguments); if (memory && !firing) { fire(); } } return this; }, remove: function() { jQuery.each(arguments, function(_, arg) { var index; while ((index = jQuery.inArray(arg, list, index)) > -1) { list.splice(index, 1); if (index <= firingIndex) { firingIndex--; } } }); return this; }, has: function(fn) { return fn ? jQuery.inArray(fn, list) > -1 : list.length > 0; }, empty: function() { if (list) { list = []; } return this; }, disable: function() { locked = queue = []; list = memory = ""; return this; }, disabled: function() { return !list; }, lock: function() { locked = queue = []; if (!memory && !firing) { list = memory = ""; } return this; }, locked: function() { return !!locked; }, fireWith: function(context, args) { if (!locked) { args = args || []; args = [context, args.slice ? args.slice() : args]; queue.push(args); if (!firing) { fire(); } } return this; }, fire: function() { self.fireWith(this, arguments); return this; }, fired: function() { return !!fired; } }; return self; }; function Identity(v) { return v; } function Thrower(ex) { throw ex; } function adoptValue(value, resolve, reject, noValue) { var method; try { if (value && isFunction(method = value.promise)) { method.call(value).done(resolve).fail(reject); } else if (value && isFunction(method = value.then)) { method.call(value, resolve, reject); } else { resolve.apply(void 0, [value].slice(noValue)); } } catch (value2) { reject.apply(void 0, [value2]); } } jQuery.extend({ Deferred: function(func) { var tuples = [ [ "notify", "progress", jQuery.Callbacks("memory"), jQuery.Callbacks("memory"), 2 ], [ "resolve", "done", jQuery.Callbacks("once memory"), jQuery.Callbacks("once memory"), 0, "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), jQuery.Callbacks("once memory"), 1, "rejected" ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done(arguments).fail(arguments); return this; }, "catch": function(fn) { return promise.then(null, fn); }, pipe: function() { var fns = arguments; return jQuery.Deferred(function(newDefer) { jQuery.each(tuples, function(_i, tuple) { var fn = isFunction(fns[tuple[4]]) && fns[tuple[4]]; deferred[tuple[1]](function() { var returned = fn && fn.apply(this, arguments); if (returned && isFunction(returned.promise)) { returned.promise().progress(newDefer.notify).done(newDefer.resolve).fail(newDefer.reject); } else { newDefer[tuple[0] + "With"]( this, fn ? [returned] : arguments ); } }); }); fns = null; }).promise(); }, then: function(onFulfilled, onRejected, onProgress) { var maxDepth = 0; function resolve(depth, deferred2, handler, special) { return function() { var that = this, args = arguments, mightThrow = function() { var returned, then; if (depth < maxDepth) { return; } returned = handler.apply(that, args); if (returned === deferred2.promise()) { throw new TypeError("Thenable self-resolution"); } then = returned && (typeof returned === "object" || typeof returned === "function") && returned.then; if (isFunction(then)) { if (special) { then.call( returned, resolve(maxDepth, deferred2, Identity, special), resolve(maxDepth, deferred2, Thrower, special) ); } else { maxDepth++; then.call( returned, resolve(maxDepth, deferred2, Identity, special), resolve(maxDepth, deferred2, Thrower, special), resolve( maxDepth, deferred2, Identity, deferred2.notifyWith ) ); } } else { if (handler !== Identity) { that = void 0; args = [returned]; } (special || deferred2.resolveWith)(that, args); } }, process = special ? mightThrow : function() { try { mightThrow(); } catch (e) { if (jQuery.Deferred.exceptionHook) { jQuery.Deferred.exceptionHook( e, process.error ); } if (depth + 1 >= maxDepth) { if (handler !== Thrower) { that = void 0; args = [e]; } deferred2.rejectWith(that, args); } } }; if (depth) { process(); } else { if (jQuery.Deferred.getErrorHook) { process.error = jQuery.Deferred.getErrorHook(); } else if (jQuery.Deferred.getStackHook) { process.error = jQuery.Deferred.getStackHook(); } window2.setTimeout(process); } }; } return jQuery.Deferred(function(newDefer) { tuples[0][3].add( resolve( 0, newDefer, isFunction(onProgress) ? onProgress : Identity, newDefer.notifyWith ) ); tuples[1][3].add( resolve( 0, newDefer, isFunction(onFulfilled) ? onFulfilled : Identity ) ); tuples[2][3].add( resolve( 0, newDefer, isFunction(onRejected) ? onRejected : Thrower ) ); }).promise(); }, promise: function(obj) { return obj != null ? jQuery.extend(obj, promise) : promise; } }, deferred = {}; jQuery.each(tuples, function(i, tuple) { var list = tuple[2], stateString = tuple[5]; promise[tuple[1]] = list.add; if (stateString) { list.add( function() { state = stateString; }, tuples[3 - i][2].disable, tuples[3 - i][3].disable, tuples[0][2].lock, tuples[0][3].lock ); } list.add(tuple[3].fire); deferred[tuple[0]] = function() { deferred[tuple[0] + "With"](this === deferred ? void 0 : this, arguments); return this; }; deferred[tuple[0] + "With"] = list.fireWith; }); promise.promise(deferred); if (func) { func.call(deferred, deferred); } return deferred; }, when: function(singleValue) { var remaining = arguments.length, i = remaining, resolveContexts = Array(i), resolveValues = slice.call(arguments), primary = jQuery.Deferred(), updateFunc = function(i2) { return function(value) { resolveContexts[i2] = this; resolveValues[i2] = arguments.length > 1 ? slice.call(arguments) : value; if (!--remaining) { primary.resolveWith(resolveContexts, resolveValues); } }; }; if (remaining <= 1) { adoptValue( singleValue, primary.done(updateFunc(i)).resolve, primary.reject, !remaining ); if (primary.state() === "pending" || isFunction(resolveValues[i] && resolveValues[i].then)) { return primary.then(); } } while (i--) { adoptValue(resolveValues[i], updateFunc(i), primary.reject); } return primary.promise(); } }); var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/; jQuery.Deferred.exceptionHook = function(error, asyncError) { if (window2.console && window2.console.warn && error && rerrorNames.test(error.name)) { window2.console.warn( "jQuery.Deferred exception: " + error.message, error.stack, asyncError ); } }; jQuery.readyException = function(error) { window2.setTimeout(function() { throw error; }); }; var readyList = jQuery.Deferred(); jQuery.fn.ready = function(fn) { readyList.then(fn).catch(function(error) { jQuery.readyException(error); }); return this; }; jQuery.extend({ isReady: false, readyWait: 1, ready: function(wait) { if (wait === true ? --jQuery.readyWait : jQuery.isReady) { return; } jQuery.isReady = true; if (wait !== true && --jQuery.readyWait > 0) { return; } readyList.resolveWith(document, [jQuery]); } }); jQuery.ready.then = readyList.then; function completed() { document.removeEventListener("DOMContentLoaded", completed); window2.removeEventListener("load", completed); jQuery.ready(); } if (document.readyState === "complete" || document.readyState !== "loading" && !document.documentElement.doScroll) { window2.setTimeout(jQuery.ready); } else { document.addEventListener("DOMContentLoaded", completed); window2.addEventListener("load", completed); } var access = function(elems, fn, key, value, chainable, emptyGet, raw) { var i = 0, len = elems.length, bulk = key == null; if (toType(key) === "object") { chainable = true; for (i in key) { access(elems, fn, i, key[i], true, emptyGet, raw); } } else if (value !== void 0) { chainable = true; if (!isFunction(value)) { raw = true; } if (bulk) { if (raw) { fn.call(elems, value); fn = null; } else { bulk = fn; fn = function(elem, _key, value2) { return bulk.call(jQuery(elem), value2); }; } } if (fn) { for (; i < len; i++) { fn( elems[i], key, raw ? value : value.call(elems[i], i, fn(elems[i], key)) ); } } } if (chainable) { return elems; } if (bulk) { return fn.call(elems); } return len ? fn(elems[0], key) : emptyGet; }; var rmsPrefix = /^-ms-/, rdashAlpha = /-([a-z])/g; function fcamelCase(_all, letter) { return letter.toUpperCase(); } function camelCase(string) { return string.replace(rmsPrefix, "ms-").replace(rdashAlpha, fcamelCase); } var acceptData = function(owner) { return owner.nodeType === 1 || owner.nodeType === 9 || !+owner.nodeType; }; function Data() { this.expando = jQuery.expando + Data.uid++; } Data.uid = 1; Data.prototype = { cache: function(owner) { var value = owner[this.expando]; if (!value) { value = {}; if (acceptData(owner)) { if (owner.nodeType) { owner[this.expando] = value; } else { Object.defineProperty(owner, this.expando, { value, configurable: true }); } } } return value; }, set: function(owner, data, value) { var prop, cache = this.cache(owner); if (typeof data === "string") { cache[camelCase(data)] = value; } else { for (prop in data) { cache[camelCase(prop)] = data[prop]; } } return cache; }, get: function(owner, key) { return key === void 0 ? this.cache(owner) : ( owner[this.expando] && owner[this.expando][camelCase(key)] ); }, access: function(owner, key, value) { if (key === void 0 || key && typeof key === "string" && value === void 0) { return this.get(owner, key); } this.set(owner, key, value); return value !== void 0 ? value : key; }, remove: function(owner, key) { var i, cache = owner[this.expando]; if (cache === void 0) { return; } if (key !== void 0) { if (Array.isArray(key)) { key = key.map(camelCase); } else { key = camelCase(key); key = key in cache ? [key] : key.match(rnothtmlwhite) || []; } i = key.length; while (i--) { delete cache[key[i]]; } } if (key === void 0 || jQuery.isEmptyObject(cache)) { if (owner.nodeType) { owner[this.expando] = void 0; } else { delete owner[this.expando]; } } }, hasData: function(owner) { var cache = owner[this.expando]; return cache !== void 0 && !jQuery.isEmptyObject(cache); } }; var dataPriv = new Data(); var dataUser = new Data(); var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, rmultiDash = /[A-Z]/g; function getData(data) { if (data === "true") { return true; } if (data === "false") { return false; } if (data === "null") { return null; } if (data === +data + "") { return +data; } if (rbrace.test(data)) { return JSON.parse(data); } return data; } function dataAttr(elem, key, data) { var name; if (data === void 0 && elem.nodeType === 1) { name = "data-" + key.replace(rmultiDash, "-$&").toLowerCase(); data = elem.getAttribute(name); if (typeof data === "string") { try { data = getData(data); } catch (e) { } dataUser.set(elem, key, data); } else { data = void 0; } } return data; } jQuery.extend({ hasData: function(elem) { return dataUser.hasData(elem) || dataPriv.hasData(elem); }, data: function(elem, name, data) { return dataUser.access(elem, name, data); }, removeData: function(elem, name) { dataUser.remove(elem, name); }, _data: function(elem, name, data) { return dataPriv.access(elem, name, data); }, _removeData: function(elem, name) { dataPriv.remove(elem, name); } }); jQuery.fn.extend({ data: function(key, value) { var i, name, data, elem = this[0], attrs = elem && elem.attributes; if (key === void 0) { if (this.length) { data = dataUser.get(elem); if (elem.nodeType === 1 && !dataPriv.get(elem, "hasDataAttrs")) { i = attrs.length; while (i--) { if (attrs[i]) { name = attrs[i].name; if (name.indexOf("data-") === 0) { name = camelCase(name.slice(5)); dataAttr(elem, name, data[name]); } } } dataPriv.set(elem, "hasDataAttrs", true); } } return data; } if (typeof key === "object") { return this.each(function() { dataUser.set(this, key); }); } return access(this, function(value2) { var data2; if (elem && value2 === void 0) { data2 = dataUser.get(elem, key); if (data2 !== void 0) { return data2; } data2 = dataAttr(elem, key); if (data2 !== void 0) { return data2; } return; } this.each(function() { dataUser.set(this, key, value2); }); }, null, value, arguments.length > 1, null, true); }, removeData: function(key) { return this.each(function() { dataUser.remove(this, key); }); } }); jQuery.extend({ queue: function(elem, type, data) { var queue; if (elem) { type = (type || "fx") + "queue"; queue = dataPriv.get(elem, type); if (data) { if (!queue || Array.isArray(data)) { queue = dataPriv.access(elem, type, jQuery.makeArray(data)); } else { queue.push(data); } } return queue || []; } }, dequeue: function(elem, type) { type = type || "fx"; var queue = jQuery.queue(elem, type), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks(elem, type), next = function() { jQuery.dequeue(elem, type); }; if (fn === "inprogress") { fn = queue.shift(); startLength--; } if (fn) { if (type === "fx") { queue.unshift("inprogress"); } delete hooks.stop; fn.call(elem, next, hooks); } if (!startLength && hooks) { hooks.empty.fire(); } }, _queueHooks: function(elem, type) { var key = type + "queueHooks"; return dataPriv.get(elem, key) || dataPriv.access(elem, key, { empty: jQuery.Callbacks("once memory").add(function() { dataPriv.remove(elem, [type + "queue", key]); }) }); } }); jQuery.fn.extend({ queue: function(type, data) { var setter = 2; if (typeof type !== "string") { data = type; type = "fx"; setter--; } if (arguments.length < setter) { return jQuery.queue(this[0], type); } return data === void 0 ? this : this.each(function() { var queue = jQuery.queue(this, type, data); jQuery._queueHooks(this, type); if (type === "fx" && queue[0] !== "inprogress") { jQuery.dequeue(this, type); } }); }, dequeue: function(type) { return this.each(function() { jQuery.dequeue(this, type); }); }, clearQueue: function(type) { return this.queue(type || "fx", []); }, promise: function(type, obj) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if (!--count) { defer.resolveWith(elements, [elements]); } }; if (typeof type !== "string") { obj = type; type = void 0; } type = type || "fx"; while (i--) { tmp = dataPriv.get(elements[i], type + "queueHooks"); if (tmp && tmp.empty) { count++; tmp.empty.add(resolve); } } resolve(); return defer.promise(obj); } }); var pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source; var rcssNum = new RegExp("^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i"); var cssExpand = ["Top", "Right", "Bottom", "Left"]; var documentElement = document.documentElement; var isAttached = function(elem) { return jQuery.contains(elem.ownerDocument, elem); }, composed = { composed: true }; if (documentElement.getRootNode) { isAttached = function(elem) { return jQuery.contains(elem.ownerDocument, elem) || elem.getRootNode(composed) === elem.ownerDocument; }; } var isHiddenWithinTree = function(elem, el) { elem = el || elem; return elem.style.display === "none" || elem.style.display === "" && isAttached(elem) && jQuery.css(elem, "display") === "none"; }; function adjustCSS(elem, prop, valueParts, tween) { var adjusted, scale, maxIterations = 20, currentValue = tween ? function() { return tween.cur(); } : function() { return jQuery.css(elem, prop, ""); }, initial = currentValue(), unit = valueParts && valueParts[3] || (jQuery.cssNumber[prop] ? "" : "px"), initialInUnit = elem.nodeType && (jQuery.cssNumber[prop] || unit !== "px" && +initial) && rcssNum.exec(jQuery.css(elem, prop)); if (initialInUnit && initialInUnit[3] !== unit) { initial = initial / 2; unit = unit || initialInUnit[3]; initialInUnit = +initial || 1; while (maxIterations--) { jQuery.style(elem, prop, initialInUnit + unit); if ((1 - scale) * (1 - (scale = currentValue() / initial || 0.5)) <= 0) { maxIterations = 0; } initialInUnit = initialInUnit / scale; } initialInUnit = initialInUnit * 2; jQuery.style(elem, prop, initialInUnit + unit); valueParts = valueParts || []; } if (valueParts) { initialInUnit = +initialInUnit || +initial || 0; adjusted = valueParts[1] ? initialInUnit + (valueParts[1] + 1) * valueParts[2] : +valueParts[2]; if (tween) { tween.unit = unit; tween.start = initialInUnit; tween.end = adjusted; } } return adjusted; } var defaultDisplayMap = {}; function getDefaultDisplay(elem) { var temp, doc = elem.ownerDocument, nodeName2 = elem.nodeName, display = defaultDisplayMap[nodeName2]; if (display) { return display; } temp = doc.body.appendChild(doc.createElement(nodeName2)); display = jQuery.css(temp, "display"); temp.parentNode.removeChild(temp); if (display === "none") { display = "block"; } defaultDisplayMap[nodeName2] = display; return display; } function showHide(elements, show) { var display, elem, values = [], index = 0, length = elements.length; for (; index < length; index++) { elem = elements[index]; if (!elem.style) { continue; } display = elem.style.display; if (show) { if (display === "none") { values[index] = dataPriv.get(elem, "display") || null; if (!values[index]) { elem.style.display = ""; } } if (elem.style.display === "" && isHiddenWithinTree(elem)) { values[index] = getDefaultDisplay(elem); } } else { if (display !== "none") { values[index] = "none"; dataPriv.set(elem, "display", display); } } } for (index = 0; index < length; index++) { if (values[index] != null) { elements[index].style.display = values[index]; } } return elements; } jQuery.fn.extend({ show: function() { return showHide(this, true); }, hide: function() { return showHide(this); }, toggle: function(state) { if (typeof state === "boolean") { return state ? this.show() : this.hide(); } return this.each(function() { if (isHiddenWithinTree(this)) { jQuery(this).show(); } else { jQuery(this).hide(); } }); } }); var rcheckableType = /^(?:checkbox|radio)$/i; var rtagName = /<([a-z][^\/\0>\x20\t\r\n\f]*)/i; var rscriptType = /^$|^module$|\/(?:java|ecma)script/i; (function() { var fragment = document.createDocumentFragment(), div = fragment.appendChild(document.createElement("div")), input = document.createElement("input"); input.setAttribute("type", "radio"); input.setAttribute("checked", "checked"); input.setAttribute("name", "t"); div.appendChild(input); support.checkClone = div.cloneNode(true).cloneNode(true).lastChild.checked; div.innerHTML = ""; support.noCloneChecked = !!div.cloneNode(true).lastChild.defaultValue; div.innerHTML = ""; support.option = !!div.lastChild; })(); var wrapMap = { thead: [1, "", "
"], col: [2, "", "
"], tr: [2, "", "
"], td: [3, "", "
"], _default: [0, "", ""] }; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; if (!support.option) { wrapMap.optgroup = wrapMap.option = [1, ""]; } function getAll(context, tag) { var ret; if (typeof context.getElementsByTagName !== "undefined") { ret = context.getElementsByTagName(tag || "*"); } else if (typeof context.querySelectorAll !== "undefined") { ret = context.querySelectorAll(tag || "*"); } else { ret = []; } if (tag === void 0 || tag && nodeName(context, tag)) { return jQuery.merge([context], ret); } return ret; } function setGlobalEval(elems, refElements) { var i = 0, l = elems.length; for (; i < l; i++) { dataPriv.set( elems[i], "globalEval", !refElements || dataPriv.get(refElements[i], "globalEval") ); } } var rhtml = /<|&#?\w+;/; function buildFragment(elems, context, scripts, selection, ignored) { var elem, tmp, tag, wrap, attached, j, fragment = context.createDocumentFragment(), nodes = [], i = 0, l = elems.length; for (; i < l; i++) { elem = elems[i]; if (elem || elem === 0) { if (toType(elem) === "object") { jQuery.merge(nodes, elem.nodeType ? [elem] : elem); } else if (!rhtml.test(elem)) { nodes.push(context.createTextNode(elem)); } else { tmp = tmp || fragment.appendChild(context.createElement("div")); tag = (rtagName.exec(elem) || ["", ""])[1].toLowerCase(); wrap = wrapMap[tag] || wrapMap._default; tmp.innerHTML = wrap[1] + jQuery.htmlPrefilter(elem) + wrap[2]; j = wrap[0]; while (j--) { tmp = tmp.lastChild; } jQuery.merge(nodes, tmp.childNodes); tmp = fragment.firstChild; tmp.textContent = ""; } } } fragment.textContent = ""; i = 0; while (elem = nodes[i++]) { if (selection && jQuery.inArray(elem, selection) > -1) { if (ignored) { ignored.push(elem); } continue; } attached = isAttached(elem); tmp = getAll(fragment.appendChild(elem), "script"); if (attached) { setGlobalEval(tmp); } if (scripts) { j = 0; while (elem = tmp[j++]) { if (rscriptType.test(elem.type || "")) { scripts.push(elem); } } } } return fragment; } var rtypenamespace = /^([^.]*)(?:\.(.+)|)/; function returnTrue() { return true; } function returnFalse() { return false; } function on(elem, types, selector, data, fn, one) { var origFn, type; if (typeof types === "object") { if (typeof selector !== "string") { data = data || selector; selector = void 0; } for (type in types) { on(elem, type, selector, data, types[type], one); } return elem; } if (data == null && fn == null) { fn = selector; data = selector = void 0; } else if (fn == null) { if (typeof selector === "string") { fn = data; data = void 0; } else { fn = data; data = selector; selector = void 0; } } if (fn === false) { fn = returnFalse; } else if (!fn) { return elem; } if (one === 1) { origFn = fn; fn = function(event) { jQuery().off(event); return origFn.apply(this, arguments); }; fn.guid = origFn.guid || (origFn.guid = jQuery.guid++); } return elem.each(function() { jQuery.event.add(this, types, fn, data, selector); }); } jQuery.event = { global: {}, add: function(elem, types, handler, data, selector) { var handleObjIn, eventHandle, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = dataPriv.get(elem); if (!acceptData(elem)) { return; } if (handler.handler) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } if (selector) { jQuery.find.matchesSelector(documentElement, selector); } if (!handler.guid) { handler.guid = jQuery.guid++; } if (!(events = elemData.events)) { events = elemData.events =Object.create(null); } if (!(eventHandle = elemData.handle)) { eventHandle = elemData.handle = function(e) { return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ? jQuery.event.dispatch.apply(elem, arguments) : void 0; }; } types = (types || "").match(rnothtmlwhite) || [""]; t = types.length; while (t--) { tmp = rtypenamespace.exec(types[t]) || []; type = origType = tmp[1]; namespaces = (tmp[2] || "").split(".").sort(); if (!type) { continue; } special = jQuery.event.special[type] || {}; type = (selector ? special.delegateType : special.bindType) || type; special = jQuery.event.special[type] || {}; handleObj = jQuery.extend({ type, origType, data, handler, guid: handler.guid, selector, needsContext: selector && jQuery.expr.match.needsContext.test(selector), namespace: namespaces.join(".") }, handleObjIn); if (!(handlers = events[type])) { handlers = events[type] = []; handlers.delegateCount = 0; if (!special.setup || special.setup.call(elem, data, namespaces, eventHandle) === false) { if (elem.addEventListener) { elem.addEventListener(type, eventHandle); } } } if (special.add) { special.add.call(elem, handleObj); if (!handleObj.handler.guid) { handleObj.handler.guid = handler.guid; } } if (selector) { handlers.splice(handlers.delegateCount++, 0, handleObj); } else { handlers.push(handleObj); } jQuery.event.global[type] = true; } }, remove: function(elem, types, handler, selector, mappedTypes) { var j, origCount, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = dataPriv.hasData(elem) && dataPriv.get(elem); if (!elemData || !(events = elemData.events)) { return; } types = (types || "").match(rnothtmlwhite) || [""]; t = types.length; while (t--) { tmp = rtypenamespace.exec(types[t]) || []; type = origType = tmp[1]; namespaces = (tmp[2] || "").split(".").sort(); if (!type) { for (type in events) { jQuery.event.remove(elem, type + types[t], handler, selector, true); } continue; } special = jQuery.event.special[type] || {}; type = (selector ? special.delegateType : special.bindType) || type; handlers = events[type] || []; tmp = tmp[2] && new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)"); origCount = j = handlers.length; while (j--) { handleObj = handlers[j]; if ((mappedTypes || origType === handleObj.origType) && (!handler || handler.guid === handleObj.guid) && (!tmp || tmp.test(handleObj.namespace)) && (!selector || selector === handleObj.selector || selector === "**" && handleObj.selector)) { handlers.splice(j, 1); if (handleObj.selector) { handlers.delegateCount--; } if (special.remove) { special.remove.call(elem, handleObj); } } } if (origCount && !handlers.length) { if (!special.teardown || special.teardown.call(elem, namespaces, elemData.handle) === false) { jQuery.removeEvent(elem, type, elemData.handle); } delete events[type]; } } if (jQuery.isEmptyObject(events)) { dataPriv.remove(elem, "handle events"); } }, dispatch: function(nativeEvent) { var i, j, ret, matched, handleObj, handlerQueue, args = new Array(arguments.length), event = jQuery.event.fix(nativeEvent), handlers = (dataPriv.get(this, "events") ||Object.create(null))[event.type] || [], special = jQuery.event.special[event.type] || {}; args[0] = event; for (i = 1; i < arguments.length; i++) { args[i] = arguments[i]; } event.delegateTarget = this; if (special.preDispatch && special.preDispatch.call(this, event) === false) { return; } handlerQueue = jQuery.event.handlers.call(this, event, handlers); i = 0; while ((matched = handlerQueue[i++]) && !event.isPropagationStopped()) { event.currentTarget = matched.elem; j = 0; while ((handleObj = matched.handlers[j++]) && !event.isImmediatePropagationStopped()) { if (!event.rnamespace || handleObj.namespace === false || event.rnamespace.test(handleObj.namespace)) { event.handleObj = handleObj; event.data = handleObj.data; ret = ((jQuery.event.special[handleObj.origType] || {}).handle || handleObj.handler).apply(matched.elem, args); if (ret !== void 0) { if ((event.result = ret) === false) { event.preventDefault(); event.stopPropagation(); } } } } } if (special.postDispatch) { special.postDispatch.call(this, event); } return event.result; }, handlers: function(event, handlers) { var i, handleObj, sel, matchedHandlers, matchedSelectors, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; if (delegateCount && cur.nodeType && !(event.type === "click" && event.button >= 1)) { for (; cur !== this; cur = cur.parentNode || this) { if (cur.nodeType === 1 && !(event.type === "click" && cur.disabled === true)) { matchedHandlers = []; matchedSelectors = {}; for (i = 0; i < delegateCount; i++) { handleObj = handlers[i]; sel = handleObj.selector + " "; if (matchedSelectors[sel] === void 0) { matchedSelectors[sel] = handleObj.needsContext ? jQuery(sel, this).index(cur) > -1 : jQuery.find(sel, this, null, [cur]).length; } if (matchedSelectors[sel]) { matchedHandlers.push(handleObj); } } if (matchedHandlers.length) { handlerQueue.push({ elem: cur, handlers: matchedHandlers }); } } } } cur = this; if (delegateCount < handlers.length) { handlerQueue.push({ elem: cur, handlers: handlers.slice(delegateCount) }); } return handlerQueue; }, addProp: function(name, hook) { Object.defineProperty(jQuery.Event.prototype, name, { enumerable: true, configurable: true, get: isFunction(hook) ? function() { if (this.originalEvent) { return hook(this.originalEvent); } } : function() { if (this.originalEvent) { return this.originalEvent[name]; } }, set: function(value) { Object.defineProperty(this, name, { enumerable: true, configurable: true, writable: true, value }); } }); }, fix: function(originalEvent) { return originalEvent[jQuery.expando] ? originalEvent : new jQuery.Event(originalEvent); }, special: { load: { noBubble: true }, click: { setup: function(data) { var el = this || data; if (rcheckableType.test(el.type) && el.click && nodeName(el, "input")) { leverageNative(el, "click", true); } return false; }, trigger: function(data) { var el = this || data; if (rcheckableType.test(el.type) && el.click && nodeName(el, "input")) { leverageNative(el, "click"); } return true; }, _default: function(event) { var target = event.target; return rcheckableType.test(target.type) && target.click && nodeName(target, "input") && dataPriv.get(target, "click") || nodeName(target, "a"); } }, beforeunload: { postDispatch: function(event) { if (event.result !== void 0 && event.originalEvent) { event.originalEvent.returnValue = event.result; } } } } }; function leverageNative(el, type, isSetup) { if (!isSetup) { if (dataPriv.get(el, type) === void 0) { jQuery.event.add(el, type, returnTrue); } return; } dataPriv.set(el, type, false); jQuery.event.add(el, type, { namespace: false, handler: function(event) { var result, saved = dataPriv.get(this, type); if (event.isTrigger & 1 && this[type]) { if (!saved) { saved = slice.call(arguments); dataPriv.set(this, type, saved); this[type](); result = dataPriv.get(this, type); dataPriv.set(this, type, false); if (saved !== result) { event.stopImmediatePropagation(); event.preventDefault(); return result; } } else if ((jQuery.event.special[type] || {}).delegateType) { event.stopPropagation(); } } else if (saved) { dataPriv.set(this, type, jQuery.event.trigger( saved[0], saved.slice(1), this )); event.stopPropagation(); event.isImmediatePropagationStopped = returnTrue; } } }); } jQuery.removeEvent = function(elem, type, handle) { if (elem.removeEventListener) { elem.removeEventListener(type, handle); } }; jQuery.Event = function(src, props) { if (!(this instanceof jQuery.Event)) { return new jQuery.Event(src, props); } if (src && src.type) { this.originalEvent = src; this.type = src.type; this.isDefaultPrevented = src.defaultPrevented || src.defaultPrevented === void 0 && src.returnValue === false ? returnTrue : returnFalse; this.target = src.target && src.target.nodeType === 3 ? src.target.parentNode : src.target; this.currentTarget = src.currentTarget; this.relatedTarget = src.relatedTarget; } else { this.type = src; } if (props) { jQuery.extend(this, props); } this.timeStamp = src && src.timeStamp || Date.now(); this[jQuery.expando] = true; }; jQuery.Event.prototype = { constructor: jQuery.Event, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, isSimulated: false, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if (e && !this.isSimulated) { e.preventDefault(); } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if (e && !this.isSimulated) { e.stopPropagation(); } }, stopImmediatePropagation: function() { var e = this.originalEvent; this.isImmediatePropagationStopped = returnTrue; if (e && !this.isSimulated) { e.stopImmediatePropagation(); } this.stopPropagation(); } }; jQuery.each({ altKey: true, bubbles: true, cancelable: true, changedTouches: true, ctrlKey: true, detail: true, eventPhase: true, metaKey: true, pageX: true, pageY: true, shiftKey: true, view: true, "char": true, code: true, charCode: true, key: true, keyCode: true, button: true, buttons: true, clientX: true, clientY: true, offsetX: true, offsetY: true, pointerId: true, pointerType: true, screenX: true, screenY: true, targetTouches: true, toElement: true, touches: true, which: true }, jQuery.event.addProp); jQuery.each({ focus: "focusin", blur: "focusout" }, function(type, delegateType) { function focusMappedHandler(nativeEvent) { if (document.documentMode) { var handle = dataPriv.get(this, "handle"), event = jQuery.event.fix(nativeEvent); event.type = nativeEvent.type === "focusin" ? "focus" : "blur"; event.isSimulated = true; handle(nativeEvent); if (event.target === event.currentTarget) { handle(event); } } else { jQuery.event.simulate( delegateType, nativeEvent.target, jQuery.event.fix(nativeEvent) ); } } jQuery.event.special[type] = { setup: function() { var attaches; leverageNative(this, type, true); if (document.documentMode) { attaches = dataPriv.get(this, delegateType); if (!attaches) { this.addEventListener(delegateType, focusMappedHandler); } dataPriv.set(this, delegateType, (attaches || 0) + 1); } else { return false; } }, trigger: function() { leverageNative(this, type); return true; }, teardown: function() { var attaches; if (document.documentMode) { attaches = dataPriv.get(this, delegateType) - 1; if (!attaches) { this.removeEventListener(delegateType, focusMappedHandler); dataPriv.remove(this, delegateType); } else { dataPriv.set(this, delegateType, attaches); } } else { return false; } }, _default: function(event) { return dataPriv.get(event.target, type); }, delegateType }; jQuery.event.special[delegateType] = { setup: function() { var doc = this.ownerDocument || this.document || this, dataHolder = document.documentMode ? this : doc, attaches = dataPriv.get(dataHolder, delegateType); if (!attaches) { if (document.documentMode) { this.addEventListener(delegateType, focusMappedHandler); } else { doc.addEventListener(type, focusMappedHandler, true); } } dataPriv.set(dataHolder, delegateType, (attaches || 0) + 1); }, teardown: function() { var doc = this.ownerDocument || this.document || this, dataHolder = document.documentMode ? this : doc, attaches = dataPriv.get(dataHolder, delegateType) - 1; if (!attaches) { if (document.documentMode) { this.removeEventListener(delegateType, focusMappedHandler); } else { doc.removeEventListener(type, focusMappedHandler, true); } dataPriv.remove(dataHolder, delegateType); } else { dataPriv.set(dataHolder, delegateType, attaches); } } }; }); jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout", pointerenter: "pointerover", pointerleave: "pointerout" }, function(orig, fix) { jQuery.event.special[orig] = { delegateType: fix, bindType: fix, handle: function(event) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; if (!related || related !== target && !jQuery.contains(target, related)) { event.type = handleObj.origType; ret = handleObj.handler.apply(this, arguments); event.type = fix; } return ret; } }; }); jQuery.fn.extend({ on: function(types, selector, data, fn) { return on(this, types, selector, data, fn); }, one: function(types, selector, data, fn) { return on(this, types, selector, data, fn, 1); }, off: function(types, selector, fn) { var handleObj, type; if (types && types.preventDefault && types.handleObj) { handleObj = types.handleObj; jQuery(types.delegateTarget).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if (typeof types === "object") { for (type in types) { this.off(type, selector, types[type]); } return this; } if (selector === false || typeof selector === "function") { fn = selector; selector = void 0; } if (fn === false) { fn = returnFalse; } return this.each(function() { jQuery.event.remove(this, types, fn, selector); }); } }); var rnoInnerhtml = /\s*$/g; function manipulationTarget(elem, content) { if (nodeName(elem, "table") && nodeName(content.nodeType !== 11 ? content : content.firstChild, "tr")) { return jQuery(elem).children("tbody")[0] || elem; } return elem; } function disableScript(elem) { elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type; return elem; } function restoreScript(elem) { if ((elem.type || "").slice(0, 5) === "true/") { elem.type = elem.type.slice(5); } else { elem.removeAttribute("type"); } return elem; } function cloneCopyEvent(src, dest) { var i, l, type, pdataOld, udataOld, udataCur, events; if (dest.nodeType !== 1) { return; } if (dataPriv.hasData(src)) { pdataOld = dataPriv.get(src); events = pdataOld.events; if (events) { dataPriv.remove(dest, "handle events"); for (type in events) { for (i = 0, l = events[type].length; i < l; i++) { jQuery.event.add(dest, type, events[type][i]); } } } } if (dataUser.hasData(src)) { udataOld = dataUser.access(src); udataCur = jQuery.extend({}, udataOld); dataUser.set(dest, udataCur); } } function fixInput(src, dest) { var nodeName2 = dest.nodeName.toLowerCase(); if (nodeName2 === "input" && rcheckableType.test(src.type)) { dest.checked = src.checked; } else if (nodeName2 === "input" || nodeName2 === "textarea") { dest.defaultValue = src.defaultValue; } } function domManip(collection, args, callback, ignored) { args = flat(args); var fragment, first, scripts, hasScripts, node, doc, i = 0, l = collection.length, iNoClone = l - 1, value = args[0], valueIsFunction = isFunction(value); if (valueIsFunction || l > 1 && typeof value === "string" && !support.checkClone && rchecked.test(value)) { return collection.each(function(index) { var self = collection.eq(index); if (valueIsFunction) { args[0] = value.call(this, index, self.html()); } domManip(self, args, callback, ignored); }); } if (l) { fragment = buildFragment(args, collection[0].ownerDocument, false, collection, ignored); first = fragment.firstChild; if (fragment.childNodes.length === 1) { fragment = first; } if (first || ignored) { scripts = jQuery.map(getAll(fragment, "script"), disableScript); hasScripts = scripts.length; for (; i < l; i++) { node = fragment; if (i !== iNoClone) { node = jQuery.clone(node, true, true); if (hasScripts) { jQuery.merge(scripts, getAll(node, "script")); } } callback.call(collection[i], node, i); } if (hasScripts) { doc = scripts[scripts.length - 1].ownerDocument; jQuery.map(scripts, restoreScript); for (i = 0; i < hasScripts; i++) { node = scripts[i]; if (rscriptType.test(node.type || "") && !dataPriv.access(node, "globalEval") && jQuery.contains(doc, node)) { if (node.src && (node.type || "").toLowerCase() !== "module") { if (jQuery._evalUrl && !node.noModule) { jQuery._evalUrl(node.src, { nonce: node.nonce || node.getAttribute("nonce") }, doc); } } else { DOMEval(node.textContent.replace(rcleanScript, ""), node, doc); } } } } } } return collection; } function remove(elem, selector, keepData) { var node, nodes = selector ? jQuery.filter(selector, elem) : elem, i = 0; for (; (node = nodes[i]) != null; i++) { if (!keepData && node.nodeType === 1) { jQuery.cleanData(getAll(node)); } if (node.parentNode) { if (keepData && isAttached(node)) { setGlobalEval(getAll(node, "script")); } node.parentNode.removeChild(node); } } return elem; } jQuery.extend({ htmlPrefilter: function(html) { return html; }, clone: function(elem, dataAndEvents, deepDataAndEvents) { var i, l, srcElements, destElements, clone = elem.cloneNode(true), inPage = isAttached(elem); if (!support.noCloneChecked && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem)) { destElements = getAll(clone); srcElements = getAll(elem); for (i = 0, l = srcElements.length; i < l; i++) { fixInput(srcElements[i], destElements[i]); } } if (dataAndEvents) { if (deepDataAndEvents) { srcElements = srcElements || getAll(elem); destElements = destElements || getAll(clone); for (i = 0, l = srcElements.length; i < l; i++) { cloneCopyEvent(srcElements[i], destElements[i]); } } else { cloneCopyEvent(elem, clone); } } destElements = getAll(clone, "script"); if (destElements.length > 0) { setGlobalEval(destElements, !inPage && getAll(elem, "script")); } return clone; }, cleanData: function(elems) { var data, elem, type, special = jQuery.event.special, i = 0; for (; (elem = elems[i]) !== void 0; i++) { if (acceptData(elem)) { if (data = elem[dataPriv.expando]) { if (data.events) { for (type in data.events) { if (special[type]) { jQuery.event.remove(elem, type); } else { jQuery.removeEvent(elem, type, data.handle); } } } elem[dataPriv.expando] = void 0; } if (elem[dataUser.expando]) { elem[dataUser.expando] = void 0; } } } } }); jQuery.fn.extend({ detach: function(selector) { return remove(this, selector, true); }, remove: function(selector) { return remove(this, selector); }, text: function(value) { return access(this, function(value2) { return value2 === void 0 ? jQuery.text(this) : this.empty().each(function() { if (this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9) { this.textContent = value2; } }); }, null, value, arguments.length); }, append: function() { return domManip(this, arguments, function(elem) { if (this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9) { var target = manipulationTarget(this, elem); target.appendChild(elem); } }); }, prepend: function() { return domManip(this, arguments, function(elem) { if (this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9) { var target = manipulationTarget(this, elem); target.insertBefore(elem, target.firstChild); } }); }, before: function() { return domManip(this, arguments, function(elem) { if (this.parentNode) { this.parentNode.insertBefore(elem, this); } }); }, after: function() { return domManip(this, arguments, function(elem) { if (this.parentNode) { this.parentNode.insertBefore(elem, this.nextSibling); } }); }, empty: function() { var elem, i = 0; for (; (elem = this[i]) != null; i++) { if (elem.nodeType === 1) { jQuery.cleanData(getAll(elem, false)); elem.textContent = ""; } } return this; }, clone: function(dataAndEvents, deepDataAndEvents) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map(function() { return jQuery.clone(this, dataAndEvents, deepDataAndEvents); }); }, html: function(value) { return access(this, function(value2) { var elem = this[0] || {}, i = 0, l = this.length; if (value2 === void 0 && elem.nodeType === 1) { return elem.innerHTML; } if (typeof value2 === "string" && !rnoInnerhtml.test(value2) && !wrapMap[(rtagName.exec(value2) || ["", ""])[1].toLowerCase()]) { value2 = jQuery.htmlPrefilter(value2); try { for (; i < l; i++) { elem = this[i] || {}; if (elem.nodeType === 1) { jQuery.cleanData(getAll(elem, false)); elem.innerHTML = value2; } } elem = 0; } catch (e) { } } if (elem) { this.empty().append(value2); } }, null, value, arguments.length); }, replaceWith: function() { var ignored = []; return domManip(this, arguments, function(elem) { var parent = this.parentNode; if (jQuery.inArray(this, ignored) < 0) { jQuery.cleanData(getAll(this)); if (parent) { parent.replaceChild(elem, this); } } }, ignored); } }); jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function(name, original) { jQuery.fn[name] = function(selector) { var elems, ret = [], insert = jQuery(selector), last = insert.length - 1, i = 0; for (; i <= last; i++) { elems = i === last ? this : this.clone(true); jQuery(insert[i])[original](elems); push.apply(ret, elems.get()); } return this.pushStack(ret); }; }); var rnumnonpx = new RegExp("^(" + pnum + ")(?!px)[a-z%]+$", "i"); var rcustomProp = /^--/; var getStyles = function(elem) { var view = elem.ownerDocument.defaultView; if (!view || !view.opener) { view = window2; } return view.getComputedStyle(elem); }; var swap = function(elem, options, callback) { var ret, name, old = {}; for (name in options) { old[name] = elem.style[name]; elem.style[name] = options[name]; } ret = callback.call(elem); for (name in options) { elem.style[name] = old[name]; } return ret; }; var rboxStyle = new RegExp(cssExpand.join("|"), "i"); (function() { function computeStyleTests() { if (!div) { return; } container.style.cssText = "position:absolute;left:-11111px;width:60px;margin-top:1px;padding:0;border:0"; div.style.cssText = "position:relative;display:block;box-sizing:border-box;overflow:scroll;margin:auto;border:1px;padding:1px;width:60%;top:1%"; documentElement.appendChild(container).appendChild(div); var divStyle = window2.getComputedStyle(div); pixelPositionVal = divStyle.top !== "1%"; reliableMarginLeftVal = roundPixelMeasures(divStyle.marginLeft) === 12; div.style.right = "60%"; pixelBoxStylesVal = roundPixelMeasures(divStyle.right) === 36; boxSizingReliableVal = roundPixelMeasures(divStyle.width) === 36; div.style.position = "absolute"; scrollboxSizeVal = roundPixelMeasures(div.offsetWidth / 3) === 12; documentElement.removeChild(container); div = null; } function roundPixelMeasures(measure) { return Math.round(parseFloat(measure)); } var pixelPositionVal, boxSizingReliableVal, scrollboxSizeVal, pixelBoxStylesVal, reliableTrDimensionsVal, reliableMarginLeftVal, container = document.createElement("div"), div = document.createElement("div"); if (!div.style) { return; } div.style.backgroundClip = "content-box"; div.cloneNode(true).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; jQuery.extend(support, { boxSizingReliable: function() { computeStyleTests(); return boxSizingReliableVal; }, pixelBoxStyles: function() { computeStyleTests(); return pixelBoxStylesVal; }, pixelPosition: function() { computeStyleTests(); return pixelPositionVal; }, reliableMarginLeft: function() { computeStyleTests(); return reliableMarginLeftVal; }, scrollboxSize: function() { computeStyleTests(); return scrollboxSizeVal; }, reliableTrDimensions: function() { var table, tr, trChild, trStyle; if (reliableTrDimensionsVal == null) { table = document.createElement("table"); tr = document.createElement("tr"); trChild = document.createElement("div"); table.style.cssText = "position:absolute;left:-11111px;border-collapse:separate"; tr.style.cssText = "box-sizing:content-box;border:1px solid"; tr.style.height = "1px"; trChild.style.height = "9px"; trChild.style.display = "block"; documentElement.appendChild(table).appendChild(tr).appendChild(trChild); trStyle = window2.getComputedStyle(tr); reliableTrDimensionsVal = parseInt(trStyle.height, 10) + parseInt(trStyle.borderTopWidth, 10) + parseInt(trStyle.borderBottomWidth, 10) === tr.offsetHeight; documentElement.removeChild(table); } return reliableTrDimensionsVal; } }); })(); function curCSS(elem, name, computed) { var width, minWidth, maxWidth, ret, isCustomProp = rcustomProp.test(name), style = elem.style; computed = computed || getStyles(elem); if (computed) { ret = computed.getPropertyValue(name) || computed[name]; if (isCustomProp && ret) { ret = ret.replace(rtrimCSS, "$1") || void 0; } if (ret === "" && !isAttached(elem)) { ret = jQuery.style(elem, name); } if (!support.pixelBoxStyles() && rnumnonpx.test(ret) && rboxStyle.test(name)) { width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret !== void 0 ? ( ret + "" ) : ret; } function addGetHookIf(conditionFn, hookFn) { return { get: function() { if (conditionFn()) { delete this.get; return; } return (this.get = hookFn).apply(this, arguments); } }; } var cssPrefixes = ["Webkit", "Moz", "ms"], emptyStyle = document.createElement("div").style, vendorProps = {}; function vendorPropName(name) { var capName = name[0].toUpperCase() + name.slice(1), i = cssPrefixes.length; while (i--) { name = cssPrefixes[i] + capName; if (name in emptyStyle) { return name; } } } function finalPropName(name) { var final = jQuery.cssProps[name] || vendorProps[name]; if (final) { return final; } if (name in emptyStyle) { return name; } return vendorProps[name] = vendorPropName(name) || name; } var rdisplayswap = /^(none|table(?!-c[ea]).+)/, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: "0", fontWeight: "400" }; function setPositiveNumber(_elem, value, subtract) { var matches = rcssNum.exec(value); return matches ? ( Math.max(0, matches[2] - (subtract || 0)) + (matches[3] || "px") ) : value; } function boxModelAdjustment(elem, dimension, box, isBorderBox, styles, computedVal) { var i = dimension === "width" ? 1 : 0, extra = 0, delta = 0, marginDelta = 0; if (box === (isBorderBox ? "border" : "content")) { return 0; } for (; i < 4; i += 2) { if (box === "margin") { marginDelta += jQuery.css(elem, box + cssExpand[i], true, styles); } if (!isBorderBox) { delta += jQuery.css(elem, "padding" + cssExpand[i], true, styles); if (box !== "padding") { delta += jQuery.css(elem, "border" + cssExpand[i] + "Width", true, styles); } else { extra += jQuery.css(elem, "border" + cssExpand[i] + "Width", true, styles); } } else { if (box === "content") { delta -= jQuery.css(elem, "padding" + cssExpand[i], true, styles); } if (box !== "margin") { delta -= jQuery.css(elem, "border" + cssExpand[i] + "Width", true, styles); } } } if (!isBorderBox && computedVal >= 0) { delta += Math.max(0, Math.ceil( elem["offset" + dimension[0].toUpperCase() + dimension.slice(1)] - computedVal - delta - extra - 0.5 )) || 0; } return delta + marginDelta; } function getWidthOrHeight(elem, dimension, extra) { var styles = getStyles(elem), boxSizingNeeded = !support.boxSizingReliable() || extra, isBorderBox = boxSizingNeeded && jQuery.css(elem, "boxSizing", false, styles) === "border-box", valueIsBorderBox = isBorderBox, val = curCSS(elem, dimension, styles), offsetProp = "offset" + dimension[0].toUpperCase() + dimension.slice(1); if (rnumnonpx.test(val)) { if (!extra) { return val; } val = "auto"; } if ((!support.boxSizingReliable() && isBorderBox || !support.reliableTrDimensions() && nodeName(elem, "tr") || val === "auto" || !parseFloat(val) && jQuery.css(elem, "display", false, styles) === "inline") && elem.getClientRects().length) { isBorderBox = jQuery.css(elem, "boxSizing", false, styles) === "border-box"; valueIsBorderBox = offsetProp in elem; if (valueIsBorderBox) { val = elem[offsetProp]; } } val = parseFloat(val) || 0; return val + boxModelAdjustment( elem, dimension, extra || (isBorderBox ? "border" : "content"), valueIsBorderBox, styles, val ) + "px"; } jQuery.extend({ cssHooks: { opacity: { get: function(elem, computed) { if (computed) { var ret = curCSS(elem, "opacity"); return ret === "" ? "1" : ret; } } } }, cssNumber: { animationIterationCount: true, aspectRatio: true, borderImageSlice: true, columnCount: true, flexGrow: true, flexShrink: true, fontWeight: true, gridArea: true, gridColumn: true, gridColumnEnd: true, gridColumnStart: true, gridRow: true, gridRowEnd: true, gridRowStart: true, lineHeight: true, opacity: true, order: true, orphans: true, scale: true, widows: true, zIndex: true, zoom: true, fillOpacity: true, floodOpacity: true, stopOpacity: true, strokeMiterlimit: true, strokeOpacity: true }, cssProps: {}, style: function(elem, name, value, extra) { if (!elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style) { return; } var ret, type, hooks, origName = camelCase(name), isCustomProp = rcustomProp.test(name), style = elem.style; if (!isCustomProp) { name = finalPropName(origName); } hooks = jQuery.cssHooks[name] || jQuery.cssHooks[origName]; if (value !== void 0) { type = typeof value; if (type === "string" && (ret = rcssNum.exec(value)) && ret[1]) { value = adjustCSS(elem, name, ret); type = "number"; } if (value == null || value !== value) { return; } if (type === "number" && !isCustomProp) { value += ret && ret[3] || (jQuery.cssNumber[origName] ? "" : "px"); } if (!support.clearCloneStyle && value === "" && name.indexOf("background") === 0) { style[name] = "inherit"; } if (!hooks || !("set" in hooks) || (value = hooks.set(elem, value, extra)) !== void 0) { if (isCustomProp) { style.setProperty(name, value); } else { style[name] = value; } } } else { if (hooks && "get" in hooks && (ret = hooks.get(elem, false, extra)) !== void 0) { return ret; } return style[name]; } }, css: function(elem, name, extra, styles) { var val, num, hooks, origName = camelCase(name), isCustomProp = rcustomProp.test(name); if (!isCustomProp) { name = finalPropName(origName); } hooks = jQuery.cssHooks[name] || jQuery.cssHooks[origName]; if (hooks && "get" in hooks) { val = hooks.get(elem, true, extra); } if (val === void 0) { val = curCSS(elem, name, styles); } if (val === "normal" && name in cssNormalTransform) { val = cssNormalTransform[name]; } if (extra === "" || extra) { num = parseFloat(val); return extra === true || isFinite(num) ? num || 0 : val; } return val; } }); jQuery.each(["height", "width"], function(_i, dimension) { jQuery.cssHooks[dimension] = { get: function(elem, computed, extra) { if (computed) { return rdisplayswap.test(jQuery.css(elem, "display")) && (!elem.getClientRects().length || !elem.getBoundingClientRect().width) ? swap(elem, cssShow, function() { return getWidthOrHeight(elem, dimension, extra); }) : getWidthOrHeight(elem, dimension, extra); } }, set: function(elem, value, extra) { var matches, styles = getStyles(elem), scrollboxSizeBuggy = !support.scrollboxSize() && styles.position === "absolute", boxSizingNeeded = scrollboxSizeBuggy || extra, isBorderBox = boxSizingNeeded && jQuery.css(elem, "boxSizing", false, styles) === "border-box", subtract = extra ? boxModelAdjustment( elem, dimension, extra, isBorderBox, styles ) : 0; if (isBorderBox && scrollboxSizeBuggy) { subtract -= Math.ceil( elem["offset" + dimension[0].toUpperCase() + dimension.slice(1)] - parseFloat(styles[dimension]) - boxModelAdjustment(elem, dimension, "border", false, styles) - 0.5 ); } if (subtract && (matches = rcssNum.exec(value)) && (matches[3] || "px") !== "px") { elem.style[dimension] = value; value = jQuery.css(elem, dimension); } return setPositiveNumber(elem, value, subtract); } }; }); jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft, function(elem, computed) { if (computed) { return (parseFloat(curCSS(elem, "marginLeft")) || elem.getBoundingClientRect().left - swap(elem, { marginLeft: 0 }, function() { return elem.getBoundingClientRect().left; })) + "px"; } } ); jQuery.each({ margin: "", padding: "", border: "Width" }, function(prefix, suffix) { jQuery.cssHooks[prefix + suffix] = { expand: function(value) { var i = 0, expanded = {}, parts = typeof value === "string" ? value.split(" ") : [value]; for (; i < 4; i++) { expanded[prefix + cssExpand[i] + suffix] = parts[i] || parts[i - 2] || parts[0]; } return expanded; } }; if (prefix !== "margin") { jQuery.cssHooks[prefix + suffix].set = setPositiveNumber; } }); jQuery.fn.extend({ css: function(name, value) { return access(this, function(elem, name2, value2) { var styles, len, map = {}, i = 0; if (Array.isArray(name2)) { styles = getStyles(elem); len = name2.length; for (; i < len; i++) { map[name2[i]] = jQuery.css(elem, name2[i], false, styles); } return map; } return value2 !== void 0 ? jQuery.style(elem, name2, value2) : jQuery.css(elem, name2); }, name, value, arguments.length > 1); } }); function Tween(elem, options, prop, end, easing) { return new Tween.prototype.init(elem, options, prop, end, easing); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function(elem, options, prop, end, easing, unit) { this.elem = elem; this.prop = prop; this.easing = easing || jQuery.easing._default; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || (jQuery.cssNumber[prop] ? "" : "px"); }, cur: function() { var hooks = Tween.propHooks[this.prop]; return hooks && hooks.get ? hooks.get(this) : Tween.propHooks._default.get(this); }, run: function(percent) { var eased, hooks = Tween.propHooks[this.prop]; if (this.options.duration) { this.pos = eased = jQuery.easing[this.easing]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = (this.end - this.start) * eased + this.start; if (this.options.step) { this.options.step.call(this.elem, this.now, this); } if (hooks && hooks.set) { hooks.set(this); } else { Tween.propHooks._default.set(this); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function(tween) { var result; if (tween.elem.nodeType !== 1 || tween.elem[tween.prop] != null && tween.elem.style[tween.prop] == null) { return tween.elem[tween.prop]; } result = jQuery.css(tween.elem, tween.prop, ""); return !result || result === "auto" ? 0 : result; }, set: function(tween) { if (jQuery.fx.step[tween.prop]) { jQuery.fx.step[tween.prop](tween); } else if (tween.elem.nodeType === 1 && (jQuery.cssHooks[tween.prop] || tween.elem.style[finalPropName(tween.prop)] != null)) { jQuery.style(tween.elem, tween.prop, tween.now + tween.unit); } else { tween.elem[tween.prop] = tween.now; } } } }; Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function(tween) { if (tween.elem.nodeType && tween.elem.parentNode) { tween.elem[tween.prop] = tween.now; } } }; jQuery.easing = { linear: function(p) { return p; }, swing: function(p) { return 0.5 - Math.cos(p * Math.PI) / 2; }, _default: "swing" }; jQuery.fx = Tween.prototype.init; jQuery.fx.step = {}; var fxNow, inProgress, rfxtypes = /^(?:toggle|show|hide)$/, rrun = /queueHooks$/; function schedule() { if (inProgress) { if (document.hidden === false && window2.requestAnimationFrame) { window2.requestAnimationFrame(schedule); } else { window2.setTimeout(schedule, jQuery.fx.interval); } jQuery.fx.tick(); } } function createFxNow() { window2.setTimeout(function() { fxNow = void 0; }); return fxNow = Date.now(); } function genFx(type, includeWidth) { var which, i = 0, attrs = { height: type }; includeWidth = includeWidth ? 1 : 0; for (; i < 4; i += 2 - includeWidth) { which = cssExpand[i]; attrs["margin" + which] = attrs["padding" + which] = type; } if (includeWidth) { attrs.opacity = attrs.width = type; } return attrs; } function createTween(value, prop, animation) { var tween, collection = (Animation.tweeners[prop] || []).concat(Animation.tweeners["*"]), index = 0, length = collection.length; for (; index < length; index++) { if (tween = collection[index].call(animation, prop, value)) { return tween; } } } function defaultPrefilter(elem, props, opts) { var prop, value, toggle, hooks, oldfire, propTween, restoreDisplay, display, isBox = "width" in props || "height" in props, anim = this, orig = {}, style = elem.style, hidden = elem.nodeType && isHiddenWithinTree(elem), dataShow = dataPriv.get(elem, "fxshow"); if (!opts.queue) { hooks = jQuery._queueHooks(elem, "fx"); if (hooks.unqueued == null) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if (!hooks.unqueued) { oldfire(); } }; } hooks.unqueued++; anim.always(function() { anim.always(function() { hooks.unqueued--; if (!jQuery.queue(elem, "fx").length) { hooks.empty.fire(); } }); }); } for (prop in props) { value = props[prop]; if (rfxtypes.test(value)) { delete props[prop]; toggle = toggle || value === "toggle"; if (value === (hidden ? "hide" : "show")) { if (value === "show" && dataShow && dataShow[prop] !== void 0) { hidden = true; } else { continue; } } orig[prop] = dataShow && dataShow[prop] || jQuery.style(elem, prop); } } propTween = !jQuery.isEmptyObject(props); if (!propTween && jQuery.isEmptyObject(orig)) { return; } if (isBox && elem.nodeType === 1) { opts.overflow = [style.overflow, style.overflowX, style.overflowY]; restoreDisplay = dataShow && dataShow.display; if (restoreDisplay == null) { restoreDisplay = dataPriv.get(elem, "display"); } display = jQuery.css(elem, "display"); if (display === "none") { if (restoreDisplay) { display = restoreDisplay; } else { showHide([elem], true); restoreDisplay = elem.style.display || restoreDisplay; display = jQuery.css(elem, "display"); showHide([elem]); } } if (display === "inline" || display === "inline-block" && restoreDisplay != null) { if (jQuery.css(elem, "float") === "none") { if (!propTween) { anim.done(function() { style.display = restoreDisplay; }); if (restoreDisplay == null) { display = style.display; restoreDisplay = display === "none" ? "" : display; } } style.display = "inline-block"; } } } if (opts.overflow) { style.overflow = "hidden"; anim.always(function() { style.overflow = opts.overflow[0]; style.overflowX = opts.overflow[1]; style.overflowY = opts.overflow[2]; }); } propTween = false; for (prop in orig) { if (!propTween) { if (dataShow) { if ("hidden" in dataShow) { hidden = dataShow.hidden; } } else { dataShow = dataPriv.access(elem, "fxshow", { display: restoreDisplay }); } if (toggle) { dataShow.hidden = !hidden; } if (hidden) { showHide([elem], true); } anim.done(function() { if (!hidden) { showHide([elem]); } dataPriv.remove(elem, "fxshow"); for (prop in orig) { jQuery.style(elem, prop, orig[prop]); } }); } propTween = createTween(hidden ? dataShow[prop] : 0, prop, anim); if (!(prop in dataShow)) { dataShow[prop] = propTween.start; if (hidden) { propTween.end = propTween.start; propTween.start = 0; } } } } function propFilter(props, specialEasing) { var index, name, easing, value, hooks; for (index in props) { name = camelCase(index); easing = specialEasing[name]; value = props[index]; if (Array.isArray(value)) { easing = value[1]; value = props[index] = value[0]; } if (index !== name) { props[name] = value; delete props[index]; } hooks = jQuery.cssHooks[name]; if (hooks && "expand" in hooks) { value = hooks.expand(value); delete props[name]; for (index in value) { if (!(index in props)) { props[index] = value[index]; specialEasing[index] = easing; } } } else { specialEasing[name] = easing; } } } function Animation(elem, properties, options) { var result, stopped, index = 0, length = Animation.prefilters.length, deferred = jQuery.Deferred().always(function() { delete tick.elem; }), tick = function() { if (stopped) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max(0, animation.startTime + animation.duration - currentTime), temp = remaining / animation.duration || 0, percent = 1 - temp, index2 = 0, length2 = animation.tweens.length; for (; index2 < length2; index2++) { animation.tweens[index2].run(percent); } deferred.notifyWith(elem, [animation, percent, remaining]); if (percent < 1 && length2) { return remaining; } if (!length2) { deferred.notifyWith(elem, [animation, 1, 0]); } deferred.resolveWith(elem, [animation]); return false; }, animation = deferred.promise({ elem, props: jQuery.extend({}, properties), opts: jQuery.extend(true, { specialEasing: {}, easing: jQuery.easing._default }, options), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function(prop, end) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[prop] || animation.opts.easing ); animation.tweens.push(tween); return tween; }, stop: function(gotoEnd) { var index2 = 0, length2 = gotoEnd ? animation.tweens.length : 0; if (stopped) { return this; } stopped = true; for (; index2 < length2; index2++) { animation.tweens[index2].run(1); } if (gotoEnd) { deferred.notifyWith(elem, [animation, 1, 0]); deferred.resolveWith(elem, [animation, gotoEnd]); } else { deferred.rejectWith(elem, [animation, gotoEnd]); } return this; } }), props = animation.props; propFilter(props, animation.opts.specialEasing); for (; index < length; index++) { result = Animation.prefilters[index].call(animation, elem, props, animation.opts); if (result) { if (isFunction(result.stop)) { jQuery._queueHooks(animation.elem, animation.opts.queue).stop = result.stop.bind(result); } return result; } } jQuery.map(props, createTween, animation); if (isFunction(animation.opts.start)) { animation.opts.start.call(elem, animation); } animation.progress(animation.opts.progress).done(animation.opts.done, animation.opts.complete).fail(animation.opts.fail).always(animation.opts.always); jQuery.fx.timer( jQuery.extend(tick, { elem, anim: animation, queue: animation.opts.queue }) ); return animation; } jQuery.Animation = jQuery.extend(Animation, { tweeners: { "*": [function(prop, value) { var tween = this.createTween(prop, value); adjustCSS(tween.elem, prop, rcssNum.exec(value), tween); return tween; }] }, tweener: function(props, callback) { if (isFunction(props)) { callback = props; props = ["*"]; } else { props = props.match(rnothtmlwhite); } var prop, index = 0, length = props.length; for (; index < length; index++) { prop = props[index]; Animation.tweeners[prop] = Animation.tweeners[prop] || []; Animation.tweeners[prop].unshift(callback); } }, prefilters: [defaultPrefilter], prefilter: function(callback, prepend) { if (prepend) { Animation.prefilters.unshift(callback); } else { Animation.prefilters.push(callback); } } }); jQuery.speed = function(speed, easing, fn) { var opt = speed && typeof speed === "object" ? jQuery.extend({}, speed) : { complete: fn || !fn && easing || isFunction(speed) && speed, duration: speed, easing: fn && easing || easing && !isFunction(easing) && easing }; if (jQuery.fx.off) { opt.duration = 0; } else { if (typeof opt.duration !== "number") { if (opt.duration in jQuery.fx.speeds) { opt.duration = jQuery.fx.speeds[opt.duration]; } else { opt.duration = jQuery.fx.speeds._default; } } } if (opt.queue == null || opt.queue === true) { opt.queue = "fx"; } opt.old = opt.complete; opt.complete = function() { if (isFunction(opt.old)) { opt.old.call(this); } if (opt.queue) { jQuery.dequeue(this, opt.queue); } }; return opt; }; jQuery.fn.extend({ fadeTo: function(speed, to, easing, callback) { return this.filter(isHiddenWithinTree).css("opacity", 0).show().end().animate({ opacity: to }, speed, easing, callback); }, animate: function(prop, speed, easing, callback) { var empty = jQuery.isEmptyObject(prop), optall = jQuery.speed(speed, easing, callback), doAnimation = function() { var anim = Animation(this, jQuery.extend({}, prop), optall); if (empty || dataPriv.get(this, "finish")) { anim.stop(true); } }; doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each(doAnimation) : this.queue(optall.queue, doAnimation); }, stop: function(type, clearQueue, gotoEnd) { var stopQueue = function(hooks) { var stop = hooks.stop; delete hooks.stop; stop(gotoEnd); }; if (typeof type !== "string") { gotoEnd = clearQueue; clearQueue = type; type = void 0; } if (clearQueue) { this.queue(type || "fx", []); } return this.each(function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = dataPriv.get(this); if (index) { if (data[index] && data[index].stop) { stopQueue(data[index]); } } else { for (index in data) { if (data[index] && data[index].stop && rrun.test(index)) { stopQueue(data[index]); } } } for (index = timers.length; index--; ) { if (timers[index].elem === this && (type == null || timers[index].queue === type)) { timers[index].anim.stop(gotoEnd); dequeue = false; timers.splice(index, 1); } } if (dequeue || !gotoEnd) { jQuery.dequeue(this, type); } }); }, finish: function(type) { if (type !== false) { type = type || "fx"; } return this.each(function() { var index, data = dataPriv.get(this), queue = data[type + "queue"], hooks = data[type + "queueHooks"], timers = jQuery.timers, length = queue ? queue.length : 0; data.finish = true; jQuery.queue(this, type, []); if (hooks && hooks.stop) { hooks.stop.call(this, true); } for (index = timers.length; index--; ) { if (timers[index].elem === this && timers[index].queue === type) { timers[index].anim.stop(true); timers.splice(index, 1); } } for (index = 0; index < length; index++) { if (queue[index] && queue[index].finish) { queue[index].finish.call(this); } } delete data.finish; }); } }); jQuery.each(["toggle", "show", "hide"], function(_i, name) { var cssFn = jQuery.fn[name]; jQuery.fn[name] = function(speed, easing, callback) { return speed == null || typeof speed === "boolean" ? cssFn.apply(this, arguments) : this.animate(genFx(name, true), speed, easing, callback); }; }); jQuery.each({ slideDown: genFx("show"), slideUp: genFx("hide"), slideToggle: genFx("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function(name, props) { jQuery.fn[name] = function(speed, easing, callback) { return this.animate(props, speed, easing, callback); }; }); jQuery.timers = []; jQuery.fx.tick = function() { var timer, i = 0, timers = jQuery.timers; fxNow = Date.now(); for (; i < timers.length; i++) { timer = timers[i]; if (!timer() && timers[i] === timer) { timers.splice(i--, 1); } } if (!timers.length) { jQuery.fx.stop(); } fxNow = void 0; }; jQuery.fx.timer = function(timer) { jQuery.timers.push(timer); jQuery.fx.start(); }; jQuery.fx.interval = 13; jQuery.fx.start = function() { if (inProgress) { return; } inProgress = true; schedule(); }; jQuery.fx.stop = function() { inProgress = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, _default: 400 }; jQuery.fn.delay = function(time, type) { time = jQuery.fx ? jQuery.fx.speeds[time] || time : time; type = type || "fx"; return this.queue(type, function(next, hooks) { var timeout = window2.setTimeout(next, time); hooks.stop = function() { window2.clearTimeout(timeout); }; }); }; (function() { var input = document.createElement("input"), select = document.createElement("select"), opt = select.appendChild(document.createElement("option")); input.type = "checkbox"; support.checkOn = input.value !== ""; support.optSelected = opt.selected; input = document.createElement("input"); input.value = "t"; input.type = "radio"; support.radioValue = input.value === "t"; })(); var boolHook, attrHandle = jQuery.expr.attrHandle; jQuery.fn.extend({ attr: function(name, value) { return access(this, jQuery.attr, name, value, arguments.length > 1); }, removeAttr: function(name) { return this.each(function() { jQuery.removeAttr(this, name); }); } }); jQuery.extend({ attr: function(elem, name, value) { var ret, hooks, nType = elem.nodeType; if (nType === 3 || nType === 8 || nType === 2) { return; } if (typeof elem.getAttribute === "undefined") { return jQuery.prop(elem, name, value); } if (nType !== 1 || !jQuery.isXMLDoc(elem)) { hooks = jQuery.attrHooks[name.toLowerCase()] || (jQuery.expr.match.bool.test(name) ? boolHook : void 0); } if (value !== void 0) { if (value === null) { jQuery.removeAttr(elem, name); return; } if (hooks && "set" in hooks && (ret = hooks.set(elem, value, name)) !== void 0) { return ret; } elem.setAttribute(name, value + ""); return value; } if (hooks && "get" in hooks && (ret = hooks.get(elem, name)) !== null) { return ret; } ret = jQuery.find.attr(elem, name); return ret == null ? void 0 : ret; }, attrHooks: { type: { set: function(elem, value) { if (!support.radioValue && value === "radio" && nodeName(elem, "input")) { var val = elem.value; elem.setAttribute("type", value); if (val) { elem.value = val; } return value; } } } }, removeAttr: function(elem, value) { var name, i = 0, attrNames = value && value.match(rnothtmlwhite); if (attrNames && elem.nodeType === 1) { while (name = attrNames[i++]) { elem.removeAttribute(name); } } } }); boolHook = { set: function(elem, value, name) { if (value === false) { jQuery.removeAttr(elem, name); } else { elem.setAttribute(name, name); } return name; } }; jQuery.each(jQuery.expr.match.bool.source.match(/\w+/g), function(_i, name) { var getter = attrHandle[name] || jQuery.find.attr; attrHandle[name] = function(elem, name2, isXML) { var ret, handle, lowercaseName = name2.toLowerCase(); if (!isXML) { handle = attrHandle[lowercaseName]; attrHandle[lowercaseName] = ret; ret = getter(elem, name2, isXML) != null ? lowercaseName : null; attrHandle[lowercaseName] = handle; } return ret; }; }); var rfocusable = /^(?:input|select|textarea|button)$/i, rclickable = /^(?:a|area)$/i; jQuery.fn.extend({ prop: function(name, value) { return access(this, jQuery.prop, name, value, arguments.length > 1); }, removeProp: function(name) { return this.each(function() { delete this[jQuery.propFix[name] || name]; }); } }); jQuery.extend({ prop: function(elem, name, value) { var ret, hooks, nType = elem.nodeType; if (nType === 3 || nType === 8 || nType === 2) { return; } if (nType !== 1 || !jQuery.isXMLDoc(elem)) { name = jQuery.propFix[name] || name; hooks = jQuery.propHooks[name]; } if (value !== void 0) { if (hooks && "set" in hooks && (ret = hooks.set(elem, value, name)) !== void 0) { return ret; } return elem[name] = value; } if (hooks && "get" in hooks && (ret = hooks.get(elem, name)) !== null) { return ret; } return elem[name]; }, propHooks: { tabIndex: { get: function(elem) { var tabindex = jQuery.find.attr(elem, "tabindex"); if (tabindex) { return parseInt(tabindex, 10); } if (rfocusable.test(elem.nodeName) || rclickable.test(elem.nodeName) && elem.href) { return 0; } return -1; } } }, propFix: { "for": "htmlFor", "class": "className" } }); if (!support.optSelected) { jQuery.propHooks.selected = { get: function(elem) { var parent = elem.parentNode; if (parent && parent.parentNode) { parent.parentNode.selectedIndex; } return null; }, set: function(elem) { var parent = elem.parentNode; if (parent) { parent.selectedIndex; if (parent.parentNode) { parent.parentNode.selectedIndex; } } } }; } jQuery.each([ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[this.toLowerCase()] = this; }); function stripAndCollapse(value) { var tokens = value.match(rnothtmlwhite) || []; return tokens.join(" "); } function getClass(elem) { return elem.getAttribute && elem.getAttribute("class") || ""; } function classesToArray(value) { if (Array.isArray(value)) { return value; } if (typeof value === "string") { return value.match(rnothtmlwhite) || []; } return []; } jQuery.fn.extend({ addClass: function(value) { var classNames, cur, curValue, className, i, finalValue; if (isFunction(value)) { return this.each(function(j) { jQuery(this).addClass(value.call(this, j, getClass(this))); }); } classNames = classesToArray(value); if (classNames.length) { return this.each(function() { curValue = getClass(this); cur = this.nodeType === 1 && " " + stripAndCollapse(curValue) + " "; if (cur) { for (i = 0; i < classNames.length; i++) { className = classNames[i]; if (cur.indexOf(" " + className + " ") < 0) { cur += className + " "; } } finalValue = stripAndCollapse(cur); if (curValue !== finalValue) { this.setAttribute("class", finalValue); } } }); } return this; }, removeClass: function(value) { var classNames, cur, curValue, className, i, finalValue; if (isFunction(value)) { return this.each(function(j) { jQuery(this).removeClass(value.call(this, j, getClass(this))); }); } if (!arguments.length) { return this.attr("class", ""); } classNames = classesToArray(value); if (classNames.length) { return this.each(function() { curValue = getClass(this); cur = this.nodeType === 1 && " " + stripAndCollapse(curValue) + " "; if (cur) { for (i = 0; i < classNames.length; i++) { className = classNames[i]; while (cur.indexOf(" " + className + " ") > -1) { cur = cur.replace(" " + className + " ", " "); } } finalValue = stripAndCollapse(cur); if (curValue !== finalValue) { this.setAttribute("class", finalValue); } } }); } return this; }, toggleClass: function(value, stateVal) { var classNames, className, i, self, type = typeof value, isValidValue = type === "string" || Array.isArray(value); if (isFunction(value)) { return this.each(function(i2) { jQuery(this).toggleClass( value.call(this, i2, getClass(this), stateVal), stateVal ); }); } if (typeof stateVal === "boolean" && isValidValue) { return stateVal ? this.addClass(value) : this.removeClass(value); } classNames = classesToArray(value); return this.each(function() { if (isValidValue) { self = jQuery(this); for (i = 0; i < classNames.length; i++) { className = classNames[i]; if (self.hasClass(className)) { self.removeClass(className); } else { self.addClass(className); } } } else if (value === void 0 || type === "boolean") { className = getClass(this); if (className) { dataPriv.set(this, "__className__", className); } if (this.setAttribute) { this.setAttribute( "class", className || value === false ? "" : dataPriv.get(this, "__className__") || "" ); } } }); }, hasClass: function(selector) { var className, elem, i = 0; className = " " + selector + " "; while (elem = this[i++]) { if (elem.nodeType === 1 && (" " + stripAndCollapse(getClass(elem)) + " ").indexOf(className) > -1) { return true; } } return false; } }); var rreturn = /\r/g; jQuery.fn.extend({ val: function(value) { var hooks, ret, valueIsFunction, elem = this[0]; if (!arguments.length) { if (elem) { hooks = jQuery.valHooks[elem.type] || jQuery.valHooks[elem.nodeName.toLowerCase()]; if (hooks && "get" in hooks && (ret = hooks.get(elem, "value")) !== void 0) { return ret; } ret = elem.value; if (typeof ret === "string") { return ret.replace(rreturn, ""); } return ret == null ? "" : ret; } return; } valueIsFunction = isFunction(value); return this.each(function(i) { var val; if (this.nodeType !== 1) { return; } if (valueIsFunction) { val = value.call(this, i, jQuery(this).val()); } else { val = value; } if (val == null) { val = ""; } else if (typeof val === "number") { val += ""; } else if (Array.isArray(val)) { val = jQuery.map(val, function(value2) { return value2 == null ? "" : value2 + ""; }); } hooks = jQuery.valHooks[this.type] || jQuery.valHooks[this.nodeName.toLowerCase()]; if (!hooks || !("set" in hooks) || hooks.set(this, val, "value") === void 0) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function(elem) { var val = jQuery.find.attr(elem, "value"); return val != null ? val : ( stripAndCollapse(jQuery.text(elem)) ); } }, select: { get: function(elem) { var value, option, i, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one", values = one ? null : [], max = one ? index + 1 : options.length; if (index < 0) { i = max; } else { i = one ? index : 0; } for (; i < max; i++) { option = options[i]; if ((option.selected || i === index) && !option.disabled && (!option.parentNode.disabled || !nodeName(option.parentNode, "optgroup"))) { value = jQuery(option).val(); if (one) { return value; } values.push(value); } } return values; }, set: function(elem, value) { var optionSet, option, options = elem.options, values = jQuery.makeArray(value), i = options.length; while (i--) { option = options[i]; if (option.selected = jQuery.inArray(jQuery.valHooks.option.get(option), values) > -1) { optionSet = true; } } if (!optionSet) { elem.selectedIndex = -1; } return values; } } } }); jQuery.each(["radio", "checkbox"], function() { jQuery.valHooks[this] = { set: function(elem, value) { if (Array.isArray(value)) { return elem.checked = jQuery.inArray(jQuery(elem).val(), value) > -1; } } }; if (!support.checkOn) { jQuery.valHooks[this].get = function(elem) { return elem.getAttribute("value") === null ? "on" : elem.value; }; } }); var location = window2.location; var nonce = { guid: Date.now() }; var rquery = /\?/; jQuery.parseXML = function(data) { var xml, parserErrorElem; if (!data || typeof data !== "string") { return null; } try { xml = new window2.DOMParser().parseFromString(data, "text/xml"); } catch (e) { } parserErrorElem = xml && xml.getElementsByTagName("parsererror")[0]; if (!xml || parserErrorElem) { jQuery.error("Invalid XML: " + (parserErrorElem ? jQuery.map(parserErrorElem.childNodes, function(el) { return el.textContent; }).join("\n") : data)); } return xml; }; var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, stopPropagationCallback = function(e) { e.stopPropagation(); }; jQuery.extend(jQuery.event, { trigger: function(event, data, elem, onlyHandlers) { var i, cur, tmp, bubbleType, ontype, handle, special, lastElement, eventPath = [elem || document], type = hasOwn.call(event, "type") ? event.type : event, namespaces = hasOwn.call(event, "namespace") ? event.namespace.split(".") : []; cur = lastElement = tmp = elem = elem || document; if (elem.nodeType === 3 || elem.nodeType === 8) { return; } if (rfocusMorph.test(type + jQuery.event.triggered)) { return; } if (type.indexOf(".") > -1) { namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; event = event[jQuery.expando] ? event : new jQuery.Event(type, typeof event === "object" && event); event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join("."); event.rnamespace = event.namespace ? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)") : null; event.result = void 0; if (!event.target) { event.target = elem; } data = data == null ? [event] : jQuery.makeArray(data, [event]); special = jQuery.event.special[type] || {}; if (!onlyHandlers && special.trigger && special.trigger.apply(elem, data) === false) { return; } if (!onlyHandlers && !special.noBubble && !isWindow(elem)) { bubbleType = special.delegateType || type; if (!rfocusMorph.test(bubbleType + type)) { cur = cur.parentNode; } for (; cur; cur = cur.parentNode) { eventPath.push(cur); tmp = cur; } if (tmp === (elem.ownerDocument || document)) { eventPath.push(tmp.defaultView || tmp.parentWindow || window2); } } i = 0; while ((cur = eventPath[i++]) && !event.isPropagationStopped()) { lastElement = cur; event.type = i > 1 ? bubbleType : special.bindType || type; handle = (dataPriv.get(cur, "events") ||Object.create(null))[event.type] && dataPriv.get(cur, "handle"); if (handle) { handle.apply(cur, data); } handle = ontype && cur[ontype]; if (handle && handle.apply && acceptData(cur)) { event.result = handle.apply(cur, data); if (event.result === false) { event.preventDefault(); } } } event.type = type; if (!onlyHandlers && !event.isDefaultPrevented()) { if ((!special._default || special._default.apply(eventPath.pop(), data) === false) && acceptData(elem)) { if (ontype && isFunction(elem[type]) && !isWindow(elem)) { tmp = elem[ontype]; if (tmp) { elem[ontype] = null; } jQuery.event.triggered = type; if (event.isPropagationStopped()) { lastElement.addEventListener(type, stopPropagationCallback); } elem[type](); if (event.isPropagationStopped()) { lastElement.removeEventListener(type, stopPropagationCallback); } jQuery.event.triggered = void 0; if (tmp) { elem[ontype] = tmp; } } } } return event.result; }, simulate: function(type, elem, event) { var e = jQuery.extend( new jQuery.Event(), event, { type, isSimulated: true } ); jQuery.event.trigger(e, null, elem); } }); jQuery.fn.extend({ trigger: function(type, data) { return this.each(function() { jQuery.event.trigger(type, data, this); }); }, triggerHandler: function(type, data) { var elem = this[0]; if (elem) { return jQuery.event.trigger(type, data, elem, true); } } }); var rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; function buildParams(prefix, obj, traditional, add) { var name; if (Array.isArray(obj)) { jQuery.each(obj, function(i, v) { if (traditional || rbracket.test(prefix)) { add(prefix, v); } else { buildParams( prefix + "[" + (typeof v === "object" && v != null ? i : "") + "]", v, traditional, add ); } }); } else if (!traditional && toType(obj) === "object") { for (name in obj) { buildParams(prefix + "[" + name + "]", obj[name], traditional, add); } } else { add(prefix, obj); } } jQuery.param = function(a, traditional) { var prefix, s = [], add = function(key, valueOrFunction) { var value = isFunction(valueOrFunction) ? valueOrFunction() : valueOrFunction; s[s.length] = encodeURIComponent(key) + "=" + encodeURIComponent(value == null ? "" : value); }; if (a == null) { return ""; } if (Array.isArray(a) || a.jquery && !jQuery.isPlainObject(a)) { jQuery.each(a, function() { add(this.name, this.value); }); } else { for (prefix in a) { buildParams(prefix, a[prefix], traditional, add); } } return s.join("&"); }; jQuery.fn.extend({ serialize: function() { return jQuery.param(this.serializeArray()); }, serializeArray: function() { return this.map(function() { var elements = jQuery.prop(this, "elements"); return elements ? jQuery.makeArray(elements) : this; }).filter(function() { var type = this.type; return this.name && !jQuery(this).is(":disabled") && rsubmittable.test(this.nodeName) && !rsubmitterTypes.test(type) && (this.checked || !rcheckableType.test(type)); }).map(function(_i, elem) { var val = jQuery(this).val(); if (val == null) { return null; } if (Array.isArray(val)) { return jQuery.map(val, function(val2) { return { name: elem.name, value: val2.replace(rCRLF, "\r\n") }; }); } return { name: elem.name, value: val.replace(rCRLF, "\r\n") }; }).get(); } }); var r20 = /%20/g, rhash = /#.*$/, rantiCache = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, prefilters = {}, transports = {}, allTypes = "*/".concat("*"), originAnchor = document.createElement("a"); originAnchor.href = location.href; function addToPrefiltersOrTransports(structure) { return function(dataTypeExpression, func) { if (typeof dataTypeExpression !== "string") { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match(rnothtmlwhite) || []; if (isFunction(func)) { while (dataType = dataTypes[i++]) { if (dataType[0] === "+") { dataType = dataType.slice(1) || "*"; (structure[dataType] = structure[dataType] || []).unshift(func); } else { (structure[dataType] = structure[dataType] || []).push(func); } } } }; } function inspectPrefiltersOrTransports(structure, options, originalOptions, jqXHR) { var inspected = {}, seekingTransport = structure === transports; function inspect(dataType) { var selected; inspected[dataType] = true; jQuery.each(structure[dataType] || [], function(_, prefilterOrFactory) { var dataTypeOrTransport = prefilterOrFactory(options, originalOptions, jqXHR); if (typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[dataTypeOrTransport]) { options.dataTypes.unshift(dataTypeOrTransport); inspect(dataTypeOrTransport); return false; } else if (seekingTransport) { return !(selected = dataTypeOrTransport); } }); return selected; } return inspect(options.dataTypes[0]) || !inspected["*"] && inspect("*"); } function ajaxExtend(target, src) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for (key in src) { if (src[key] !== void 0) { (flatOptions[key] ? target : deep || (deep = {}))[key] = src[key]; } } if (deep) { jQuery.extend(true, target, deep); } return target; } function ajaxHandleResponses(s, jqXHR, responses) { var ct, type, finalDataType, firstDataType, contents = s.contents, dataTypes = s.dataTypes; while (dataTypes[0] === "*") { dataTypes.shift(); if (ct === void 0) { ct = s.mimeType || jqXHR.getResponseHeader("Content-Type"); } } if (ct) { for (type in contents) { if (contents[type] && contents[type].test(ct)) { dataTypes.unshift(type); break; } } } if (dataTypes[0] in responses) { finalDataType = dataTypes[0]; } else { for (type in responses) { if (!dataTypes[0] || s.converters[type + " " + dataTypes[0]]) { finalDataType = type; break; } if (!firstDataType) { firstDataType = type; } } finalDataType = finalDataType || firstDataType; } if (finalDataType) { if (finalDataType !== dataTypes[0]) { dataTypes.unshift(finalDataType); } return responses[finalDataType]; } } function ajaxConvert(s, response, jqXHR, isSuccess) { var conv2, current, conv, tmp, prev, converters = {}, dataTypes = s.dataTypes.slice(); if (dataTypes[1]) { for (conv in s.converters) { converters[conv.toLowerCase()] = s.converters[conv]; } } current = dataTypes.shift(); while (current) { if (s.responseFields[current]) { jqXHR[s.responseFields[current]] = response; } if (!prev && isSuccess && s.dataFilter) { response = s.dataFilter(response, s.dataType); } prev = current; current = dataTypes.shift(); if (current) { if (current === "*") { current = prev; } else if (prev !== "*" && prev !== current) { conv = converters[prev + " " + current] || converters["* " + current]; if (!conv) { for (conv2 in converters) { tmp = conv2.split(" "); if (tmp[1] === current) { conv = converters[prev + " " + tmp[0]] || converters["* " + tmp[0]]; if (conv) { if (conv === true) { conv = converters[conv2]; } else if (converters[conv2] !== true) { current = tmp[0]; dataTypes.unshift(tmp[1]); } break; } } } } if (conv !== true) { if (conv && s.throws) { response = conv(response); } else { try { response = conv(response); } catch (e) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } } } return { state: "success", data: response }; } jQuery.extend({ active: 0, lastModified: {}, etag: {}, ajaxSettings: { url: location.href, type: "GET", isLocal: rlocalProtocol.test(location.protocol), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", accepts: { "*": allTypes, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /\bxml\b/, html: /\bhtml/, json: /\bjson\b/ }, responseFields: { xml: "responseXML", text: "responseText", json: "responseJSON" }, converters: { "* text": String, "text html": true, "text json": JSON.parse, "text xml": jQuery.parseXML }, flatOptions: { url: true, context: true } }, ajaxSetup: function(target, settings) { return settings ? ( ajaxExtend(ajaxExtend(target, jQuery.ajaxSettings), settings) ) : ( ajaxExtend(jQuery.ajaxSettings, target) ); }, ajaxPrefilter: addToPrefiltersOrTransports(prefilters), ajaxTransport: addToPrefiltersOrTransports(transports), ajax: function(url, options) { if (typeof url === "object") { options = url; url = void 0; } options = options || {}; var transport, cacheURL, responseHeadersString, responseHeaders, timeoutTimer, urlAnchor, completed2, fireGlobals, i, uncached, s = jQuery.ajaxSetup({}, options), callbackContext = s.context || s, globalEventContext = s.context && (callbackContext.nodeType || callbackContext.jquery) ? jQuery(callbackContext) : jQuery.event, deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks("once memory"), statusCode = s.statusCode || {}, requestHeaders = {}, requestHeadersNames = {}, strAbort = "canceled", jqXHR = { readyState: 0, getResponseHeader: function(key) { var match; if (completed2) { if (!responseHeaders) { responseHeaders = {}; while (match = rheaders.exec(responseHeadersString)) { responseHeaders[match[1].toLowerCase() + " "] = (responseHeaders[match[1].toLowerCase() + " "] || []).concat(match[2]); } } match = responseHeaders[key.toLowerCase() + " "]; } return match == null ? null : match.join(", "); }, getAllResponseHeaders: function() { return completed2 ? responseHeadersString : null; }, setRequestHeader: function(name, value) { if (completed2 == null) { name = requestHeadersNames[name.toLowerCase()] = requestHeadersNames[name.toLowerCase()] || name; requestHeaders[name] = value; } return this; }, overrideMimeType: function(type) { if (completed2 == null) { s.mimeType = type; } return this; }, statusCode: function(map) { var code; if (map) { if (completed2) { jqXHR.always(map[jqXHR.status]); } else { for (code in map) { statusCode[code] = [statusCode[code], map[code]]; } } } return this; }, abort: function(statusText) { var finalText = statusText || strAbort; if (transport) { transport.abort(finalText); } done(0, finalText); return this; } }; deferred.promise(jqXHR); s.url = ((url || s.url || location.href) + "").replace(rprotocol, location.protocol + "//"); s.type = options.method || options.type || s.method || s.type; s.dataTypes = (s.dataType || "*").toLowerCase().match(rnothtmlwhite) || [""]; if (s.crossDomain == null) { urlAnchor = document.createElement("a"); try { urlAnchor.href = s.url; urlAnchor.href = urlAnchor.href; s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !== urlAnchor.protocol + "//" + urlAnchor.host; } catch (e) { s.crossDomain = true; } } if (s.data && s.processData && typeof s.data !== "string") { s.data = jQuery.param(s.data, s.traditional); } inspectPrefiltersOrTransports(prefilters, s, options, jqXHR); if (completed2) { return jqXHR; } fireGlobals = jQuery.event && s.global; if (fireGlobals && jQuery.active++ === 0) { jQuery.event.trigger("ajaxStart"); } s.type = s.type.toUpperCase(); s.hasContent = !rnoContent.test(s.type); cacheURL = s.url.replace(rhash, ""); if (!s.hasContent) { uncached = s.url.slice(cacheURL.length); if (s.data && (s.processData || typeof s.data === "string")) { cacheURL += (rquery.test(cacheURL) ? "&" : "?") + s.data; delete s.data; } if (s.cache === false) { cacheURL = cacheURL.replace(rantiCache, "$1"); uncached = (rquery.test(cacheURL) ? "&" : "?") + "_=" + nonce.guid++ + uncached; } s.url = cacheURL + uncached; } else if (s.data && s.processData && (s.contentType || "").indexOf("application/x-www-form-urlencoded") === 0) { s.data = s.data.replace(r20, "+"); } if (s.ifModified) { if (jQuery.lastModified[cacheURL]) { jqXHR.setRequestHeader("If-Modified-Since", jQuery.lastModified[cacheURL]); } if (jQuery.etag[cacheURL]) { jqXHR.setRequestHeader("If-None-Match", jQuery.etag[cacheURL]); } } if (s.data && s.hasContent && s.contentType !== false || options.contentType) { jqXHR.setRequestHeader("Content-Type", s.contentType); } jqXHR.setRequestHeader( "Accept", s.dataTypes[0] && s.accepts[s.dataTypes[0]] ? s.accepts[s.dataTypes[0]] + (s.dataTypes[0] !== "*" ? ", " + allTypes + "; q=0.01" : "") : s.accepts["*"] ); for (i in s.headers) { jqXHR.setRequestHeader(i, s.headers[i]); } if (s.beforeSend && (s.beforeSend.call(callbackContext, jqXHR, s) === false || completed2)) { return jqXHR.abort(); } strAbort = "abort"; completeDeferred.add(s.complete); jqXHR.done(s.success); jqXHR.fail(s.error); transport = inspectPrefiltersOrTransports(transports, s, options, jqXHR); if (!transport) { done(-1, "No Transport"); } else { jqXHR.readyState = 1; if (fireGlobals) { globalEventContext.trigger("ajaxSend", [jqXHR, s]); } if (completed2) { return jqXHR; } if (s.async && s.timeout > 0) { timeoutTimer = window2.setTimeout(function() { jqXHR.abort("timeout"); }, s.timeout); } try { completed2 = false; transport.send(requestHeaders, done); } catch (e) { if (completed2) { throw e; } done(-1, e); } } function done(status, nativeStatusText, responses, headers) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; if (completed2) { return; } completed2 = true; if (timeoutTimer) { window2.clearTimeout(timeoutTimer); } transport = void 0; responseHeadersString = headers || ""; jqXHR.readyState = status > 0 ? 4 : 0; isSuccess = status >= 200 && status < 300 || status === 304; if (responses) { response = ajaxHandleResponses(s, jqXHR, responses); } if (!isSuccess && jQuery.inArray("script", s.dataTypes) > -1 && jQuery.inArray("json", s.dataTypes) < 0) { s.converters["text script"] = function() { }; } response = ajaxConvert(s, response, jqXHR, isSuccess); if (isSuccess) { if (s.ifModified) { modified = jqXHR.getResponseHeader("Last-Modified"); if (modified) { jQuery.lastModified[cacheURL] = modified; } modified = jqXHR.getResponseHeader("etag"); if (modified) { jQuery.etag[cacheURL] = modified; } } if (status === 204 || s.type === "HEAD") { statusText = "nocontent"; } else if (status === 304) { statusText = "notmodified"; } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { error = statusText; if (status || !statusText) { statusText = "error"; if (status < 0) { status = 0; } } } jqXHR.status = status; jqXHR.statusText = (nativeStatusText || statusText) + ""; if (isSuccess) { deferred.resolveWith(callbackContext, [success, statusText, jqXHR]); } else { deferred.rejectWith(callbackContext, [jqXHR, statusText, error]); } jqXHR.statusCode(statusCode); statusCode = void 0; if (fireGlobals) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [jqXHR, s, isSuccess ? success : error] ); } completeDeferred.fireWith(callbackContext, [jqXHR, statusText]); if (fireGlobals) { globalEventContext.trigger("ajaxComplete", [jqXHR, s]); if (!--jQuery.active) { jQuery.event.trigger("ajaxStop"); } } } return jqXHR; }, getJSON: function(url, data, callback) { return jQuery.get(url, data, callback, "json"); }, getScript: function(url, callback) { return jQuery.get(url, void 0, callback, "script"); } }); jQuery.each(["get", "post"], function(_i, method) { jQuery[method] = function(url, data, callback, type) { if (isFunction(data)) { type = type || callback; callback = data; data = void 0; } return jQuery.ajax(jQuery.extend({ url, type: method, dataType: type, data, success: callback }, jQuery.isPlainObject(url) && url)); }; }); jQuery.ajaxPrefilter(function(s) { var i; for (i in s.headers) { if (i.toLowerCase() === "content-type") { s.contentType = s.headers[i] || ""; } } }); jQuery._evalUrl = function(url, options, doc) { return jQuery.ajax({ url, type: "GET", dataType: "script", cache: true, async: false, global: false, converters: { "text script": function() { } }, dataFilter: function(response) { jQuery.globalEval(response, options, doc); } }); }; jQuery.fn.extend({ wrapAll: function(html) { var wrap; if (this[0]) { if (isFunction(html)) { html = html.call(this[0]); } wrap = jQuery(html, this[0].ownerDocument).eq(0).clone(true); if (this[0].parentNode) { wrap.insertBefore(this[0]); } wrap.map(function() { var elem = this; while (elem.firstElementChild) { elem = elem.firstElementChild; } return elem; }).append(this); } return this; }, wrapInner: function(html) { if (isFunction(html)) { return this.each(function(i) { jQuery(this).wrapInner(html.call(this, i)); }); } return this.each(function() { var self = jQuery(this), contents = self.contents(); if (contents.length) { contents.wrapAll(html); } else { self.append(html); } }); }, wrap: function(html) { var htmlIsFunction = isFunction(html); return this.each(function(i) { jQuery(this).wrapAll(htmlIsFunction ? html.call(this, i) : html); }); }, unwrap: function(selector) { this.parent(selector).not("body").each(function() { jQuery(this).replaceWith(this.childNodes); }); return this; } }); jQuery.expr.pseudos.hidden = function(elem) { return !jQuery.expr.pseudos.visible(elem); }; jQuery.expr.pseudos.visible = function(elem) { return !!(elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length); }; jQuery.ajaxSettings.xhr = function() { try { return new window2.XMLHttpRequest(); } catch (e) { } }; var xhrSuccessStatus = { 0: 200, 1223: 204 }, xhrSupported = jQuery.ajaxSettings.xhr(); support.cors = !!xhrSupported && "withCredentials" in xhrSupported; support.ajax = xhrSupported = !!xhrSupported; jQuery.ajaxTransport(function(options) { var callback, errorCallback; if (support.cors || xhrSupported && !options.crossDomain) { return { send: function(headers, complete) { var i, xhr = options.xhr(); xhr.open( options.type, options.url, options.async, options.username, options.password ); if (options.xhrFields) { for (i in options.xhrFields) { xhr[i] = options.xhrFields[i]; } } if (options.mimeType && xhr.overrideMimeType) { xhr.overrideMimeType(options.mimeType); } if (!options.crossDomain && !headers["X-Requested-With"]) { headers["X-Requested-With"] = "XMLHttpRequest"; } for (i in headers) { xhr.setRequestHeader(i, headers[i]); } callback = function(type) { return function() { if (callback) { callback = errorCallback = xhr.onload = xhr.onerror = xhr.onabort = xhr.ontimeout = xhr.onreadystatechange = null; if (type === "abort") { xhr.abort(); } else if (type === "error") { if (typeof xhr.status !== "number") { complete(0, "error"); } else { complete( xhr.status, xhr.statusText ); } } else { complete( xhrSuccessStatus[xhr.status] || xhr.status, xhr.statusText, (xhr.responseType || "text") !== "text" || typeof xhr.responseText !== "string" ? { binary: xhr.response } : { text: xhr.responseText }, xhr.getAllResponseHeaders() ); } } }; }; xhr.onload = callback(); errorCallback = xhr.onerror = xhr.ontimeout = callback("error"); if (xhr.onabort !== void 0) { xhr.onabort = errorCallback; } else { xhr.onreadystatechange = function() { if (xhr.readyState === 4) { window2.setTimeout(function() { if (callback) { errorCallback(); } }); } }; } callback = callback("abort"); try { xhr.send(options.hasContent && options.data || null); } catch (e) { if (callback) { throw e; } } }, abort: function() { if (callback) { callback(); } } }; } }); jQuery.ajaxPrefilter(function(s) { if (s.crossDomain) { s.contents.script = false; } }); jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /\b(?:java|ecma)script\b/ }, converters: { "text script": function(text) { jQuery.globalEval(text); return text; } } }); jQuery.ajaxPrefilter("script", function(s) { if (s.cache === void 0) { s.cache = false; } if (s.crossDomain) { s.type = "GET"; } }); jQuery.ajaxTransport("script", function(s) { if (s.crossDomain || s.scriptAttrs) { var script, callback; return { send: function(_, complete) { script = jQuery("