You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1649 lines
54 KiB

2 years ago
  1. /*global $, alert, g_cus, g_de, g_api, g_db, g_ul, btoa, console, i18n */
  2. var g_db = {
  3. /**
  4. * Check the capability
  5. * @private
  6. * @method SupportLocalStorage
  7. * @return {Object} description
  8. */
  9. SupportLocalStorage: function () {
  10. 'use strict';
  11. return typeof (localStorage) !== "undefined";
  12. },
  13. /**
  14. * Insert data
  15. * @private
  16. * @method SetItem
  17. * @param {Object} sKey
  18. * @param {Object} sValue
  19. * @return {Object} description
  20. */
  21. SetItem: function (sKey, sValue) {
  22. 'use strict';
  23. var bRes = false;
  24. if (this.SupportLocalStorage()) {
  25. localStorage.setItem(sKey, sValue);
  26. bRes = true;
  27. }
  28. return bRes;
  29. },
  30. /**
  31. * Fetch data
  32. * @private
  33. * @method GetItem
  34. * @param {Object} sKey
  35. * @return {Object} description
  36. */
  37. GetItem: function (sKey) {
  38. 'use strict';
  39. var sRes = null;
  40. if (this.SupportLocalStorage()) {
  41. sRes = localStorage.getItem(sKey);
  42. }
  43. return sRes;
  44. },
  45. /**
  46. * Remove data
  47. * @private
  48. * @method RemoveItem
  49. * @param {Object} sKey
  50. * @return {Object} description
  51. */
  52. RemoveItem: function (sKey) {
  53. 'use strict';
  54. var bRes = false;
  55. if (this.SupportLocalStorage()) {
  56. localStorage.removeItem(sKey);
  57. bRes = true;
  58. }
  59. return bRes;
  60. },
  61. /**
  62. * Description for GetDic
  63. * @private
  64. * @method GetDic
  65. * @return {Object} description
  66. */
  67. GetDic: function (sKey) {
  68. 'use strict';
  69. var dicRes = null,
  70. vTemp;
  71. if (this.SupportLocalStorage()) {
  72. vTemp = localStorage.getItem(sKey);
  73. if (null !== vTemp) {
  74. dicRes = JSON.parse(vTemp);
  75. }
  76. }
  77. return dicRes;
  78. },
  79. /**
  80. * Description for SetDic
  81. * @private
  82. * @method SetDic
  83. * @return {Object} description
  84. */
  85. SetDic: function (sKey, dicValue) {
  86. 'use strict';
  87. var bRes = false;
  88. if (this.SupportLocalStorage()) {
  89. localStorage.setItem(sKey, JSON.stringify(dicValue));
  90. bRes = true;
  91. }
  92. return bRes;
  93. }
  94. };
  95. var g_gd = {
  96. webapilonginurl: "/api/Service/GetLogin",
  97. webapiurl: "/api/Cmd/GetData",
  98. projectname: "Eurotran",
  99. projectver: "Origtek",
  100. orgid: "TE",
  101. userid: "EUROTRAN",
  102. relpath: "",
  103. debugmode: window.location.host === '192.168.1.105',
  104. debugcolor: "#732C6B",
  105. IsEDU: g_db.GetItem("isedu") === "true"
  106. };
  107. var g_ul = {
  108. /**
  109. * Get token from db
  110. * @returns {String} Token in localStorage
  111. */
  112. GetToken: function () {
  113. 'use strict';
  114. return g_db.GetItem("token");
  115. },
  116. /**
  117. * Set token to db
  118. * @param {String} sTokenValue api token
  119. */
  120. SetToken: function (sTokenValue) {
  121. 'use strict';
  122. g_db.SetItem("token", sTokenValue);
  123. },
  124. /**
  125. * Set signature to db
  126. * @param {String} sSignatureValue api signature
  127. */
  128. GetSignature: function () {
  129. 'use strict';
  130. return g_db.GetItem("signature");
  131. },
  132. /**
  133. * Set signature to db
  134. * @param {String} sSignatureValue api signature
  135. */
  136. SetSignature: function (sSignatureValue) {
  137. 'use strict';
  138. g_db.SetItem("signature", sSignatureValue);
  139. },
  140. /**
  141. * Set language
  142. * @param {String} language method
  143. */
  144. SetLang: function (sLang) {
  145. 'use strict';
  146. g_db.SetItem("lang", sLang);
  147. },
  148. /**
  149. * Get language
  150. * @returns {String} language in localStorage
  151. */
  152. GetLang: function () {
  153. 'use strict';
  154. return g_db.GetItem("lang");
  155. },
  156. /**
  157. * Check is edu environment
  158. * @returns {String} login method in localStorage
  159. */
  160. IsEDU: function () {
  161. 'use strict';
  162. return g_db.GetItem("isedu");
  163. }
  164. };
  165. var g_api = {
  166. ConnectLite: function (i_sModuleName, i_sFuncName, i_dicData, i_sSuccessFunc, i_FailFunc, i_bAsyn, i_sShwd) {
  167. window.IsWaiting = i_sShwd;
  168. return this.ConnectLiteWithoutToken(i_sModuleName, i_sFuncName, i_dicData, i_sSuccessFunc, i_FailFunc, i_bAsyn);
  169. },
  170. ConnectService: function (i_sModuleName, i_sFuncName, i_dicData, i_sSuccessFunc, i_FailFunc, i_bAsyn, i_sShwd) {
  171. window.IsWaiting = i_sShwd;
  172. return this.ConnectWebLiteWithoutToken(i_sModuleName, i_sFuncName, i_dicData, i_sSuccessFunc, i_FailFunc, i_bAsyn);
  173. },
  174. ConnectLiteWithoutToken: function (i_sModuleName, i_sFuncName, i_dicData, i_sSuccessFunc, i_FailFunc, i_bAsyn) {
  175. var dicData = {},
  176. dicParameters = {},
  177. token = g_ul.GetToken(),
  178. lang = g_ul.GetLang(),
  179. signature = g_ul.GetSignature();
  180. dicParameters.ORIGID = g_gd.orgid;
  181. dicParameters.USERID = g_gd.userid;
  182. dicParameters.MODULE = i_sModuleName;
  183. dicParameters.TYPE = i_sFuncName;
  184. dicParameters.PROJECT = g_gd.projectname;
  185. dicParameters.PROJECTVER = g_gd.projectver;
  186. dicParameters.TRACEDUMP = null;
  187. i_dicData = i_dicData || {};
  188. if (g_db.GetItem('dblockDict') !== null) {
  189. i_dicData.dblockDict = g_db.GetItem('dblockDict');
  190. }
  191. dicParameters.DATA = i_dicData;
  192. if (lang !== null) {
  193. dicParameters.LANG = lang;
  194. }
  195. if (token !== null) {
  196. dicParameters.TOKEN = token;
  197. }
  198. if (signature !== null) {
  199. dicParameters.SIGNATURE = signature;
  200. }
  201. dicParameters.CUSTOMDATA = {};
  202. if (window.sProgramId) {
  203. dicParameters.CUSTOMDATA.program_id = sProgramId;
  204. }
  205. dicParameters.CUSTOMDATA.module_id = "WebSite";
  206. dicData.url = i_dicData.hasOwnProperty("url") ? i_dicData.url : g_gd.webapiurl;
  207. dicData.successfunc = i_sSuccessFunc;
  208. dicData.dicparameters = dicParameters;
  209. dicData.failfunc = ("function" === typeof (i_FailFunc)) ? i_FailFunc : function (jqXHR, textStatus, errorThrown) {
  210. alert("ConnectLite Fail jqXHR:" + jqXHR + " textStatus:" + textStatus + " errorThrown:" + errorThrown);
  211. };
  212. dicData.useasync = ("boolean" === typeof (i_bAsyn)) ? i_bAsyn : true;
  213. return this.AjaxPost(dicData);
  214. },
  215. //w.CallAjax = function (url, fnname, data, sucfn, failfn, wait, async, alwaysfn) {
  216. ConnectWebLiteWithoutToken: function (i_sUrl, i_sFuncName, i_dicData, i_sSuccessFunc, i_FailFunc, i_bAsyn) {
  217. var dicData = {},
  218. dicParameters = {},
  219. token = g_ul.GetToken(),
  220. lang = g_ul.GetLang(),
  221. signature = g_ul.GetSignature();
  222. dicParameters.ORIGID = g_gd.orgid;
  223. dicParameters.USERID = g_gd.userid;
  224. dicParameters.MODULE = '';
  225. dicParameters.TYPE = i_sFuncName;
  226. dicParameters.PROJECT = g_gd.projectname;
  227. dicParameters.PROJECTVER = g_gd.projectver;
  228. dicParameters.TRACEDUMP = null;
  229. if (g_db.GetItem('dblockDict') !== null) {
  230. i_dicData.dblockDict = g_db.GetItem('dblockDict');
  231. }
  232. dicParameters.DATA = i_dicData;
  233. if (lang !== null) {
  234. dicParameters.LANG = lang;
  235. }
  236. if (token !== null) {
  237. dicParameters.TOKEN = token;
  238. }
  239. if (signature !== null) {
  240. dicParameters.SIGNATURE = signature;
  241. }
  242. dicParameters.CUSTOMDATA = {};
  243. if (window.sProgramId) {
  244. dicParameters.CUSTOMDATA.program_id = sProgramId;
  245. }
  246. dicParameters.CUSTOMDATA.module_id = "WebSite";
  247. dicData.url = getWebServiceUrl(i_sUrl, i_sFuncName);
  248. dicData.successfunc = i_sSuccessFunc;
  249. dicData.dicparameters = dicParameters;
  250. dicData.failfunc = ("function" === typeof (i_FailFunc)) ? i_FailFunc : function (jqXHR, textStatus, errorThrown) {
  251. alert("ConnectLite Fail jqXHR:" + jqXHR + " textStatus:" + textStatus + " errorThrown:" + errorThrown);
  252. };
  253. dicData.useasync = ("boolean" === typeof (i_bAsyn)) ? i_bAsyn : true;
  254. return this.AjaxPost(dicData);
  255. },
  256. AjaxPost: function (i_dicData) {
  257. 'use strict';
  258. var defaultOption = {
  259. useasync: true,
  260. successfunc: null,
  261. failfunc: null,
  262. alwaysfunc: null,
  263. url: null,
  264. dicparameters: null
  265. },
  266. runOption = $.extend(defaultOption, i_dicData),
  267. runSuccess = function (res) {
  268. if (res.RESULT === -1) {
  269. //layer.alert(i18next.t("message.TokenVerifyFailed"), { icon: 0, title: i18next.t("common.Tips") }, function (index) {
  270. // window.top.location.href = '/Page/login.html';
  271. //});
  272. }
  273. else {
  274. if (runOption.successfunc) {
  275. runOption.successfunc(res);
  276. }
  277. }
  278. };
  279. return $.ajax({
  280. type: 'POST',
  281. url: runOption.url,
  282. data: "=" + btoa2(encodeURIComponent(JSON.stringify(runOption.dicparameters))),
  283. success: runSuccess,
  284. error: runOption.failfunc,
  285. beforeSend: function (xhr) {
  286. var token = g_ul.GetToken(),
  287. timestamp = $.now(),
  288. nonce = rndnum();
  289. xhr.setRequestHeader("orgid", runOption.dicparameters.ORIGID);
  290. xhr.setRequestHeader("userid", runOption.dicparameters.USERID);
  291. xhr.setRequestHeader("token", token);
  292. xhr.setRequestHeader("timestamp", timestamp);
  293. xhr.setRequestHeader("nonce", nonce);
  294. },
  295. async: true !== runOption.useasync ? false : true
  296. }).always(runOption.alwaysfunc);
  297. }
  298. };
  299. /**
  300. * 如果頁面js需要動態加載請在配置在這裡
  301. *
  302. *
  303. *
  304. *
  305. * window.UEDITOR_HOME_URL = "/xxxx/xxxx/";
  306. */
  307. (function ($, w, d) {
  308. /******************取得host***************************/
  309. w.gWebUrl = window.location.origin || gethost();
  310. //w.gServerUrl = 'https://www.eurotran.com:9001';
  311. //w.gServerUrl = 'https://www.origtek.com:8106';
  312. w.gServerUrl = 'http://localhost:3466';
  313. if ('www.eurotran.com.tw|www.g-yi.com.cn'.indexOf(window.location.hostname) > -1) {
  314. w.gServerUrl = 'https://www.eurotran.com:9001';
  315. }
  316. else if ('www.origtek.com'.indexOf(window.location.hostname) > -1) {
  317. w.gServerUrl = 'https://www.origtek.com:8106';
  318. }
  319. else if ('192.168.1.105'.indexOf(window.location.hostname) > -1) {
  320. w.gServerUrl = 'https://192.168.1.105:9001';
  321. }
  322. if (window.location.pathname.indexOf('/TG/') > -1) {
  323. g_gd.orgid = 'TG';
  324. }
  325. else if (window.location.pathname.indexOf('/SG/') > -1) {
  326. g_gd.orgid = 'SG';
  327. }
  328. /**
  329. * 定義系統所有公用 Service.fnction
  330. */
  331. w.ComFn = {
  332. GetOrgInfo: 'GetOrgInfo',
  333. GetSysSet: 'GetSysSet',
  334. GetArguments: 'GetArguments',
  335. GetNewsCount: 'GetNewsCount',
  336. GetNewsPage: 'GetNewsPage',
  337. GetExhibitionPage: 'GetExhibitionPage',
  338. GetNewsInfo: 'GetNewsInfo',
  339. GetFileList: 'GetUploadFiles'
  340. };
  341. /**
  342. * 定義系統所有公用 Service
  343. */
  344. w.Service = {
  345. apiappcom: 'Common',
  346. apite: 'TEAPI',
  347. apitg: 'TGAPI',
  348. apiwebcom: 'Com'
  349. };
  350. /**
  351. * For display javascript exception on UI
  352. */
  353. w.onerror = function (message, source, lineno, colno, error) {
  354. console.log(source + " line:" + lineno + " colno:" + colno + " " + message);
  355. if (parent.SysSet && parent.SysSet.IsOpenMail === 'Y') {
  356. g_api.ConnectLite('Log', 'ErrorMessage', {
  357. ErrorSource: source,
  358. Errorlineno: lineno,
  359. Errorcolno: colno,
  360. ErrorMessage: message
  361. }, function (res) {
  362. if (res.RESULT) { }
  363. });
  364. }
  365. };
  366. /**
  367. * 依據組織信息設定website
  368. * @param {Function} callback 回調函數
  369. * @param {Boolean} isreget 是否查詢DB
  370. */
  371. w.runByOrgInfo = function (callback, isreget) {
  372. isreget = isreget || false;
  373. var org = g_db.GetDic('OrgInfo');
  374. if (!org || isreget) {
  375. g_api.ConnectLite(Service.apiwebcom, ComFn.GetOrgInfo, {}, function (res) {
  376. if (res.RESULT) {
  377. org = res.DATA.rel;
  378. g_db.SetDic('OrgInfo', org);
  379. if (typeof callback === 'function') { callback(org); }
  380. }
  381. });
  382. }
  383. else {
  384. if (typeof callback === 'function') { callback(org); }
  385. }
  386. };
  387. /**
  388. * Ajax是否等待
  389. */
  390. w.IsWaiting = null;
  391. /**
  392. * 翻譯語系
  393. * @param {HTMLElement} dom 翻譯回調函數
  394. */
  395. w.transLang = function (dom) {
  396. i18next = ("undefined" == typeof i18next) ? parent.i18next : i18next;
  397. var oHandleData = dom === undefined ? $('[data-i18n]') : dom.find('[data-i18n]'),
  398. oHandlePlaceholder = dom === undefined ? $('[placeholderid]') : dom.find('[placeholderid]');
  399. oHandleData.each(function (idx, el) {
  400. var i18key = $(el).attr('data-i18n');
  401. if (i18key) {
  402. var sLan = i18next.t(i18key);
  403. if (el.nodeName == 'INPUT' && el.type == 'button') {
  404. $(el).val(sLan);
  405. }
  406. else {
  407. $(el).html(sLan);
  408. }
  409. }
  410. });
  411. oHandlePlaceholder.each(function (idx, el) {
  412. var i18key = $(el).attr("placeholderid");
  413. if (i18key) {
  414. var sLan = i18next.t(i18key);
  415. if (sLan !== i18key) {
  416. $(el).attr("placeholder", sLan);
  417. }
  418. }
  419. });
  420. };
  421. /**
  422. * 設定多於系
  423. * @param {String} lng 語種
  424. * @param {String} dom 要翻譯的html標籤
  425. * @param {Function} callback 回調函數
  426. */
  427. w.setLang = function (lng, dom, callback) {
  428. if (!lng) return;
  429. g_ul.SetLang(lng);
  430. i18next = ("undefined" == typeof i18next) ? parent.i18next : i18next;
  431. $.getJSON(gServerUrl + "/Scripts/lang/" + (g_gd.orgid || 'TE') + "/" + lng + ".json?v=" + new Date().getTime().toString(), function (json) {
  432. var oResources = {};
  433. oResources[lng] = {
  434. translation: json
  435. };
  436. i18next.init({
  437. lng: lng,
  438. resources: oResources,
  439. useLocalStorage: false, //是否将语言包存储在localstorage
  440. //ns: { namespaces: ['trans'], defaultNs: 'trans' }, //加载的语言包
  441. localStorageExpirationTime: 86400000 // 有效周期,单位ms。默认1
  442. }, function (err, t) {
  443. transLang(dom);
  444. if (typeof callback === 'function') {
  445. callback(t);
  446. }
  447. });
  448. }).error(function () {
  449. g_api.ConnectLite('Language', 'CreateLangJson', {}, function (res) {
  450. if (res.RESULT) {
  451. setLang(lng, dom, callback);
  452. }
  453. });
  454. });
  455. };
  456. /**
  457. * 開啟Waiting視窗
  458. * @param {String} msg 提示文字
  459. */
  460. w.showWaiting = function (msg) {
  461. $.blockUI({
  462. message: $('<div id="Divshowwaiting"><img src="/images/ajax_loading2.gif">' + (msg || 'Waiting...') + '</div>'),
  463. css: {
  464. 'font-size': (navigator.userAgent.match(/mobile/i) ? '20px' : '36px'),
  465. border: '0px',
  466. 'border-radius': '10px',
  467. 'background-color': '#FFF',
  468. padding: '15px 15px',
  469. opacity: .5,
  470. color: 'orange',
  471. cursor: 'wait',
  472. 'z-index': 1000000001
  473. },
  474. baseZ: 1000000000
  475. });
  476. w.setTimeout($.unblockUI, 60000);//預設開啟60秒後關閉
  477. };
  478. /**
  479. * 關閉Waiting視窗
  480. * @param {Number} iSleep 延遲時間單位為毫秒
  481. */
  482. w.closeWaiting = function (iSleep) {
  483. $(function () {
  484. if (iSleep == undefined) {
  485. iSleep = 100;
  486. }
  487. setTimeout($.unblockUI, iSleep);
  488. });
  489. };
  490. /**
  491. * 從物件陣列中移除屬性為objPropery值為objValue元素的物件
  492. * @param {Array} arrPerson 陣列物件
  493. * @param {String} objPropery 物件的屬性
  494. * @param {String} objPropery 對象的值
  495. * @return {Array} 過濾後陣列
  496. */
  497. w.Jsonremove = function (arrPerson, objPropery, objValue) {
  498. return $.grep(arrPerson, function (cur, i) {
  499. return cur[objPropery] != objValue;
  500. });
  501. };
  502. /**
  503. * 從物件陣列中獲取屬性為objPropery值為objValue元素的物件
  504. * @param {Array} arrPerson 陣列物件
  505. * @param {String} objPropery 物件的屬性
  506. * @param {String} objPropery 對象的值
  507. * @return {Array} 過濾後陣列
  508. */
  509. w.Jsonget = function (arrPerson, objPropery, objValue) {
  510. return $.grep(arrPerson, function (cur, i) {
  511. return cur[objPropery] == objValue;
  512. });
  513. };
  514. /**
  515. * 將json轉換字串
  516. * @param {Object} json json物件
  517. * @return {String} json字串
  518. */
  519. w.Tostr = function (json) {
  520. return JSON.stringify(json);
  521. };
  522. /**
  523. * 下載文件
  524. * @param {String} path 文件路徑相對路勁
  525. */
  526. w.DownLoadFile = function (path, filename) {
  527. var sUrl = gServerUrl + "/Controller.ashx";
  528. sUrl += '?action=downfile&path=' + path;
  529. if (filename) {
  530. sUrl += '&filename=' + filename;
  531. }
  532. window.location.href = sUrl;
  533. closeWaiting();
  534. };
  535. /**
  536. * 用於表單序列化去除禁用欄位
  537. * @param {HTMLElement} dom 父層物件
  538. */
  539. w.reFreshInput = function (dom) {
  540. dom.find('[disabled]').each(function () {
  541. $(this).attr('hasdisable', 1).removeAttr('disabled');
  542. });
  543. };
  544. /**
  545. * 用於表單序列化恢復禁用欄位
  546. * @param {HTMLElement} dom 父層物件
  547. */
  548. w.reSetInput = function (dom) {
  549. dom.find('[hasdisable]').each(function () {
  550. $(this).removeAttr('hasdisable').prop('disabled', true);
  551. });
  552. };
  553. /**
  554. * 序列化form表單
  555. * @param {HTMLElement} form 表單form物件
  556. * @param {String} type 傳回類型
  557. * @return {Object Or String} 表單資料
  558. */
  559. w.getFormSerialize = function (form, type) {
  560. var formdata = {};
  561. reFreshInput(form);
  562. if (type) {
  563. formdata = form.serializeJSON();
  564. }
  565. else {
  566. formdata = form.serializeObject();
  567. }
  568. reSetInput(form);
  569. return formdata;
  570. };
  571. /**
  572. * 取得Url參數
  573. * @param {String} name 取得部分的名稱 例如輸入"Action"就能取到"Add"之類參數
  574. * @return {String}參數值
  575. */
  576. w.getUrlParam = function (name) {
  577. var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //構造一個含有目標參數的正則表達式對象
  578. var r = window.location.search.substr(1).match(reg); //匹配目標參數
  579. if (r != null) return unescape(r[2]); return null; //返回參數值
  580. };
  581. /**
  582. * 對網址路徑進行編碼
  583. * @param {String} url 要編碼的url或路徑
  584. * @return {String} 編碼後的url或路徑
  585. */
  586. w.encodeURL = function (url) {
  587. return encodeURIComponent(url).replace(/\'/g, "%27").replace(/\!/g, "%21").replace(/\(/g, "%28").replace(/\)/g, "%29");
  588. };
  589. /**
  590. * 對網址路徑進行解碼
  591. * @param {String} url 要解碼的url或路徑
  592. * @return {String} 解碼後的url或路徑
  593. */
  594. w.decodeURL = function (url) {
  595. return decodeURIComponent(url);
  596. };
  597. /**
  598. * 時間格式化處理
  599. * @param {Date} date 日期時間
  600. * @param {Boolean} type 格式日期 || 日期+時間
  601. * @return {Boolean} 是否可傳回空
  602. */
  603. w.newDate = function (date, type, empty) {
  604. var r = '';
  605. if (date) {
  606. if (typeof date == 'string') {
  607. r = date.replace('T', ' ').replaceAll('-', '/');
  608. if (r.indexOf(".") > -1) {
  609. r = r.slice(0, r.indexOf("."));
  610. }
  611. }
  612. else {
  613. r = new Date(date);
  614. }
  615. r = new Date(r);
  616. }
  617. else {
  618. if (!empty) {
  619. r = new Date();
  620. }
  621. }
  622. return r === '' ? '' : !type ? r.formate("yyyy/MM/dd HH:mm") : r.formate("yyyy/MM/dd");
  623. };
  624. /**
  625. * 產生guid
  626. * @param {Number} len 指定长度,比如guid(8, 16) // "098F4D35"
  627. * @param {Number} radix 基数
  628. * @return {String} guid
  629. */
  630. w.guid = function (len, radix) {
  631. var buf = new Uint16Array(8),
  632. cryptObj = window.crypto || window.msCrypto, // For IE11
  633. s4 = function (num) {
  634. var ret = num.toString(16);
  635. while (ret.length < 4) {
  636. ret = '0' + ret;
  637. }
  638. return ret;
  639. };
  640. cryptObj.getRandomValues(buf);
  641. return s4(buf[0]) + s4(buf[1]) + '-' + s4(buf[2]) + '-' + s4(buf[3]) + '-' +
  642. s4(buf[4]) + '-' + s4(buf[5]) + s4(buf[6]) + s4(buf[7]);
  643. };
  644. /**
  645. * 產生隨機數
  646. * @param {Number} len 指定长度,比如random(8)
  647. * @return {String} rnd 亂數碼
  648. */
  649. rndnum = function (len) {
  650. var rnd = "";
  651. len = len || 10;
  652. for (var i = 0; i < len; i++)
  653. rnd += Math.floor(Math.random() * 10);
  654. return rnd;
  655. };
  656. /**
  657. * 停止冒泡行为时
  658. * @param {HTMLElement} e 事件对象
  659. */
  660. w.stopBubble = function (e) {
  661. //如果提供了事件对象,则这是一个非IE浏览器
  662. if (e && e.stopPropagation)
  663. //因此它支持W3C的stopPropagation()方法
  664. e.stopPropagation();
  665. else
  666. //否则,我们需要使用IE的方式来取消事件冒泡
  667. window.event.cancelBubble = true;
  668. };
  669. /**
  670. * 阻止默认行为时
  671. * @param {HTMLElement} e 事件对象
  672. */
  673. w.stopDefault = function (e) {
  674. //阻止默认浏览器动作(W3C)
  675. if (e && e.preventDefault)
  676. e.preventDefault();
  677. //IE中阻止函数器默认动作的方式
  678. else
  679. window.event.returnValue = false;
  680. return false;
  681. };
  682. /**
  683. * 產生下拉選單公用
  684. * @param {Object} list datalist
  685. * @param {String} id 顯示的id名稱
  686. * @param {String} name 顯示的name名稱
  687. * @param {Boolean} showid 是否顯示id
  688. * @param {String} cusattr 客制化添加屬性
  689. * @param {Boolean} isreapet 是否允許重複
  690. * @return {String} option html
  691. */
  692. w.createOptions = function (list, id, name, showid, cusattr, isreapet) {
  693. isreapet == isreapet || true;
  694. list = list || [];
  695. var Options = [],
  696. originAry = [];
  697. if (typeof list === 'number') {
  698. var intNum = list;
  699. while (list > 0) {
  700. var svalue = intNum - list + 1;
  701. svalue = $.trim(svalue);
  702. Options.push($('<option />', {
  703. value: svalue,
  704. title: svalue,
  705. html: svalue
  706. }));
  707. list--;
  708. }
  709. } else {
  710. Options = [$('<option />', { value: '', html: '請選擇...' })];
  711. var intCount = list.length;
  712. if (intCount > 0) {
  713. $.each(list, function (idx, obj) {
  714. if (isreapet !== false || (originAry.indexOf($.trim(obj[id])) < 0 && isreapet === false)) {
  715. var option = $('<option />', {
  716. value: $.trim(obj[id]),
  717. title: $.trim(obj[name]),
  718. html: (showid ? $.trim(obj[id]) + '-' : '') + $.trim(obj[name])
  719. });
  720. if (cusattr) {
  721. option.attr(cusattr, obj[cusattr]);
  722. }
  723. Options.push(option);
  724. }
  725. originAry.push($.trim(obj[id]));
  726. });
  727. }
  728. }
  729. return $('<div />').append(Options).html();
  730. };
  731. /**
  732. * Radios公用
  733. * @param {Object} list datalist
  734. * @param {String} id 顯示的id名稱
  735. * @param {String} name 顯示的name名稱
  736. * @param {String} feilid 欄位ID
  737. * @param {String} _id 客制化添加屬性
  738. * @param {Boolean} showid 是否顯示id
  739. * @param {Boolean} triggerattr 頁面加載後觸發change事件是否觸發提醒
  740. * @return {String} sHtml Radios HTML
  741. */
  742. w.createRadios = function (list, id, name, _id, showid) {
  743. list = list || [];
  744. var strHtml = '',
  745. intCount = list.length;
  746. if (intCount > 0) {
  747. $.each(list, function (idx, obj) {
  748. var inputradio = $('<input />', {
  749. type: 'radio',
  750. id: _id + '_' + idx,
  751. name: _id,
  752. value: $.trim(obj[id])
  753. }).attr('val', $.trim(obj[id]));
  754. strHtml += '<label for="' + _id + '_' + idx + '">' + inputradio[0].outerHTML + ((showid ? $.trim(obj[id]) + '-' : '') + $.trim(obj[name])) + "</label>";
  755. });
  756. }
  757. return strHtml;
  758. };
  759. /**
  760. * 產生CheckList公用
  761. * @param {Object} list datalist
  762. * @param {String} id 顯示的id名稱
  763. * @param {String} name 顯示的name名稱
  764. * @param {String} pmid 屬性id
  765. * @param {String} _id id後邊擴展
  766. * @return {String} sHtml CheckList HTML
  767. */
  768. w.createCheckList = function (list, id, name, pmid, _id) {
  769. list = list || [];
  770. var strHtml = '',
  771. intCount = list.length;
  772. if (intCount > 0) {
  773. $.each(list, function (idx, obj) {
  774. var inputradio = $('<input />', {
  775. type: 'checkbox',
  776. 'id': id + (_id === undefined ? '' : _id) + '_' + idx,
  777. name: pmid + '[]',
  778. value: $.trim(obj[id]),
  779. 'class': 'input-mini'
  780. });
  781. strHtml += "<label for='" + id + (_id === undefined ? '' : _id) + '_' + idx + "' style='" + (intCount == idx + 1 ? '' : 'float:left;') + "padding-left: 10px'>" + inputradio[0].outerHTML + $.trim(obj[name]) + "</label>";
  782. });
  783. }
  784. return strHtml;
  785. };
  786. /**
  787. * 取得自定義json值
  788. * @param {Object} json json對象
  789. * @param {Object} name json鍵值
  790. * @return {String} sLast 最終要獲取的對應的鍵值對的值
  791. */
  792. w.getJsonVal = function (json, name) {
  793. var oLast = json,
  794. saName = name.split('_');
  795. for (var i = 0; i < saName.length; i++) {
  796. if (!oLast[saName[i]]) {
  797. oLast = '';
  798. break;
  799. }
  800. oLast = oLast[saName[i]];
  801. }
  802. return oLast;
  803. };
  804. /**
  805. * 設定表單值
  806. * @param {HTMLElement} form 表單
  807. * @param {Object} json json對象
  808. */
  809. w.setFormVal = function (form, json) {
  810. form.find('[name]').each(function () {
  811. var sId = this.id,
  812. sName = (this.name) ? this.name.replace('[]', '') : '',
  813. sType = this.type,
  814. sValue = json[sName] || getJsonVal(json, sId) || '';
  815. if (sValue) {
  816. switch (sType) {
  817. case 'text':
  818. case 'email':
  819. case 'url':
  820. case 'number':
  821. case 'range':
  822. case 'date':
  823. case 'search':
  824. case 'color':
  825. case 'textarea':
  826. case 'select-one':
  827. case 'select':
  828. case 'hidden':
  829. var sDataType = $(this).attr("data-type");
  830. if (sDataType && sDataType == 'pop') {
  831. var sVal_Name = json[sName + 'Name'] || sValue;
  832. $(this).attr("data-value", sValue);
  833. if (sVal_Name) $(this).val(sVal_Name);
  834. }
  835. else {
  836. if ($(this).hasClass('date-picker')) {
  837. sValue = newDate(sValue, 'date');
  838. }
  839. else if ($(this).hasClass('date-picker') || $(this).hasClass('datetime-picker') || $(this).hasClass('date')) {
  840. sValue = newDate(sValue);
  841. }
  842. if (sValue) $(this).val(sValue);
  843. $(this).data('old', sValue);
  844. if (sDataType && sDataType == 'int' && sValue) {
  845. $(this).attr('data-value', sValue.toString().replace(/[^\d.]/g, ''));
  846. }
  847. }
  848. if (sDataType === 'select2') {
  849. $(this).trigger("change");
  850. }
  851. break;
  852. case 'checkbox':
  853. if (typeof sValue == 'object') {
  854. if (sValue.indexOf(this.value) > -1) {
  855. this.checked = sValue;
  856. }
  857. }
  858. else {
  859. this.checked = typeof sValue == 'string' ? sValue == this.value : sValue;
  860. }
  861. break;
  862. case 'radio':
  863. this.checked = this.value === sValue;
  864. break;
  865. }
  866. if ((sId == 'ModifyUser' || sId == 'CreateUser') && 'select-one'.indexOf(this.type) === -1) {
  867. $(this).text(sValue);
  868. }
  869. else if (sId == 'ModifyDate' || sId == 'CreateDate') {
  870. $(this).text(newDate(sValue));
  871. }
  872. }
  873. });
  874. };
  875. /**
  876. * 去掉字符串中所有空格
  877. * @param {String} str 要處理的字串
  878. * @param {String} is_global (包括中间空格,需要设置第2个参数为:g)
  879. * @return {String} result 處理後的字串
  880. */
  881. w.Trim = function (str, is_global) {
  882. var result;
  883. result = str.replace(/(^\s+)|(\s+$)/g, "");
  884. if (is_global.toLowerCase() == "g") {
  885. result = result.replace(/\s/g, "");
  886. }
  887. return result;
  888. };
  889. /**
  890. * 克隆对象
  891. * @param: {Object} obj 被轉換對象
  892. * @return{Object} o 新對象
  893. */
  894. w.clone = function (obj) {
  895. var o, i, j, k;
  896. if (typeof (obj) != "object" || obj === null) return obj;
  897. if (obj instanceof (Array)) {
  898. o = [];
  899. i = 0; j = obj.length;
  900. for (; i < j; i++) {
  901. if (typeof (obj[i]) == "object" && obj[i] != null) {
  902. o[i] = arguments.callee(obj[i]);
  903. }
  904. else {
  905. o[i] = obj[i];
  906. }
  907. }
  908. }
  909. else {
  910. o = {};
  911. for (i in obj) {
  912. if (typeof (obj[i]) == "object" && obj[i] != null) {
  913. o[i] = arguments.callee(obj[i]);
  914. }
  915. else {
  916. o[i] = obj[i];
  917. }
  918. }
  919. }
  920. return o;
  921. };
  922. /**
  923. * 只能輸入數字
  924. * @param {HTMLElement} $input 實例化物件
  925. * @param {Number} decimal 幾位小數
  926. * @param {Boolean} minus 是否支持負數
  927. */
  928. w.moneyInput = function ($input, decimal, minus) {
  929. if ($input.length > 0) {
  930. var oNum = new FormatNumber();
  931. $input.each(function () {
  932. var sValue = this.value,
  933. sNewStr = '';
  934. for (var i = 0; i < sValue.length; i++) {
  935. if (!isNaN(sValue[i])) {
  936. sNewStr += sValue[i];
  937. }
  938. }
  939. this.value == sNewStr;
  940. oNum.init({ trigger: $(this), decimal: decimal || 0, minus: minus || false });
  941. });
  942. }
  943. };
  944. /**
  945. * 小數後n
  946. * @param {HTMLElement} e
  947. * @param {Object} that 控制項
  948. * @param {Number} len 小數點後位數
  949. */
  950. w.keyIntp = function (e, that, len) {
  951. if (e.keyCode != 8 && e.keyCode != 37 && e.keyCode != 39 && e.keyCode != 46) {
  952. var reg = {
  953. 1: /^(\-)*(\d+)\.(\d).*$/,
  954. 2: /^(\-)*(\d+)\.(\d\d).*$/,
  955. 3: /^(\-)*(\d+)\.(\d\d\d).*$/
  956. };
  957. that.value = that.value.replace(/[^\d.-]/g, ''); //清除“数字”和“.”以外的字符
  958. that.value = that.value.replace(/\.{2,}/g, '.'); //只保留第一个. 清除多余的
  959. that.value = that.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
  960. that.value = that.value.replace(reg[len], '$1$2.$3');//只能输入n个小数
  961. if (that.value.indexOf(".") < 0 && that.value !== "" && that.value !== "-") {//以上已经过滤,此处控制的是如果没有小数点,首位不能为类似于 01、02的金额&&不是“-”
  962. if (that.value.indexOf("-") === 0) {//如果是負數
  963. that.value = 0 - parseFloat(that.value.replace('-', ''));
  964. }
  965. else {
  966. that.value = parseFloat(that.value);
  967. }
  968. }
  969. }
  970. };
  971. /**
  972. * 目的抓去網站設定
  973. * @param {Function} callback 回調函數
  974. * @param {Object} settype 設定類別
  975. * @param {String} lang 語系
  976. * @param {String} parentid 父層ID
  977. * @param {Boolean} haschild 是否只抓去父層
  978. * @param {Boolean} single 單筆
  979. */
  980. w.fnGetWebSiteSetting = function (callback, settype, lang, parentid, haschild, single) {
  981. var oQueryPm = { SetType: settype, LangId: lang };
  982. if (parentid) { oQueryPm.ParentId = parentid; }
  983. if (haschild) { oQueryPm.HasChild = haschild; }
  984. if (single) { oQueryPm.Single = single; }
  985. return g_api.ConnectLite(Service.apiwebcom, 'GetWebSiteSetting', oQueryPm, function (res) {
  986. if (res.RESULT) {
  987. if (typeof callback === 'function') {
  988. callback(res.DATA.rel);
  989. }
  990. }
  991. });
  992. };
  993. /**
  994. * 目的抓去網站設定分頁
  995. * @param {Object} args 參數
  996. */
  997. w.fnGetWebSiteSettingPage = function (args) {
  998. return g_api.ConnectLite(Service.apiwebcom, 'GetWebSiteSettingPage', args, function (res) {
  999. if (res.RESULT) {
  1000. if (typeof args.CallBack === 'function') {
  1001. args.CallBack(res.DATA.rel);
  1002. }
  1003. }
  1004. });
  1005. };
  1006. /**
  1007. * 目的Html定位到某個位置
  1008. * @param {Object} goto 要定位的html jquery對象
  1009. * @param {Number} h 誤差值
  1010. */
  1011. w.goToJys = function (goto, h) {
  1012. $("html,body").animate({ scrollTop: goto.offset().top + (h || 0) }, 500);//定位到...
  1013. };
  1014. /**
  1015. * 目的回頂端
  1016. */
  1017. w.goTop = function () {
  1018. var oTop = $('<div>', {
  1019. class: 'gotop',
  1020. html: '<img src="../images/gotop_1.png" />', click: function () {
  1021. return $("body,html").animate({ scrollTop: 0 }, 120), !1;
  1022. }
  1023. });
  1024. $('body').append(oTop.hide());//添加置頂控件
  1025. $(window).on('scroll', function () {
  1026. var h = ($(d).height(), $(this).scrollTop()),
  1027. toolbarH = -40,
  1028. toolbarCss = {};
  1029. h > 0 ? oTop.show() : oTop.hide();
  1030. if (h > 40) {
  1031. toolbarH = h - 80;
  1032. $('#Toolbar').addClass('toolbar-float').removeClass('toolbar-fix');
  1033. }
  1034. else {
  1035. $('#Toolbar').removeClass('toolbar-float').addClass('toolbar-fix');
  1036. }
  1037. $('#Toolbar').css('margin-top', toolbarH + 'px');
  1038. });
  1039. };
  1040. /**
  1041. * 目的獲取當前瀏覽器
  1042. */
  1043. w.getExplorer = function () {
  1044. var sExplorerName = '',
  1045. explorer = window.navigator.userAgent;
  1046. //ie
  1047. if (explorer.indexOf("MSIE") >= 0) {
  1048. sExplorerName = 'ie';
  1049. }
  1050. //firefox
  1051. else if (explorer.indexOf("Firefox") >= 0) {
  1052. sExplorerName = 'firefox';
  1053. }
  1054. //Chrome
  1055. else if (explorer.indexOf("Chrome") >= 0) {
  1056. sExplorerName = 'chrome';
  1057. }
  1058. //Opera
  1059. else if (explorer.indexOf("Opera") >= 0) {
  1060. sExplorerName = 'opera';
  1061. }
  1062. //Safari
  1063. else if (explorer.indexOf("Safari") >= 0) {
  1064. sExplorerName = 'safari';
  1065. }
  1066. };
  1067. /**
  1068. * 金額控件文本實例化
  1069. * @param {Number} s需要转换的金额;
  1070. * @param {Number} n 保留几位小数
  1071. * @param {String} istw 幣別
  1072. */
  1073. w.fMoney = function (s, n, istw) {
  1074. var p = n > 0 && n <= 20 ? n : 2;
  1075. if (istw && istw === 'NTD') {
  1076. s = Math.round(s);
  1077. }
  1078. s = parseFloat(((s || 0) + "").replace(/[^\d\.-]/g, "")).toFixed(p) + "";
  1079. var l = s.split(".")[0].split("").reverse(),
  1080. r = s.split(".")[1] || Array(n + 1).join(0),
  1081. t = "";
  1082. for (i = 0; i < l.length; i++) {
  1083. t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
  1084. }
  1085. return t.split("").reverse().join("") + (n === 0 ? '' : "." + r);
  1086. };
  1087. /**
  1088. * 目的:input文本處理
  1089. */
  1090. w.keyInput = function () {
  1091. //只能輸入數字
  1092. if ($('[data-keyint]').length > 0) {
  1093. $('[data-keyint]').on('keyup blur', function (e) {
  1094. this.value = this.value.replace(/\D/g, '');
  1095. });
  1096. }
  1097. //只能输入英文
  1098. if ($('[data-keyeng]').length > 0) {
  1099. $('[data-keyeng]').on('keyup blur', function (e) {
  1100. this.value = this.value.replace(/[^a-zA-Z]/g, '');
  1101. });
  1102. }
  1103. //只能输入中文
  1104. if ($('[data-keyeng]').length > 0) {
  1105. $('[data-keyeng]').on('keyup blur', function (e) {
  1106. this.value = this.value.replace(/[^\u4E00-\u9FA5]/g, '');
  1107. });
  1108. }
  1109. //只能輸入數字和“-”,(手機/電話)
  1110. if ($('[data-keytelno]').length > 0) {
  1111. $('[data-keytelno]').on('keyup blur', function (e) {
  1112. if (e.keyCode != 8 && e.keyCode != 37 && e.keyCode != 39 && e.keyCode != 46) {
  1113. this.value = this.value.replace(/[^0-9\-\+\#\ ]/g, '');
  1114. }
  1115. });
  1116. }
  1117. //只能輸入數字和“-,+,#”
  1118. if ($('[data-keyintg]').length > 0) {
  1119. $('[data-keyintg]').on('keyup blur', function (e) {
  1120. this.value = this.value.replace(/[^0-9\-\+\#]/g, '');
  1121. });
  1122. }
  1123. //只能輸入數字和“.”,小數點後保留一位有效數字
  1124. if ($('[data-keyintp1]').length > 0) {
  1125. $('[data-keyintp1]').on('keyup blur', function (e) {
  1126. keyIntp(e, this, 1);
  1127. });
  1128. }
  1129. //只能輸入數字和“.”,小數點後保留兩位有效數字
  1130. if ($('[data-keyintp2]').length > 0) {
  1131. $('[data-keyintp2]').on('keyup blur', function (e) {
  1132. keyIntp(e, this, 2);
  1133. });
  1134. }
  1135. //只能輸入數字和“.”,小數點後保留三位有效數字
  1136. if ($('[data-keyintp3]').length > 0) {
  1137. $('[data-keyintp3]').on('keyup blur', function (e) {
  1138. keyIntp(e, this, 3);
  1139. });
  1140. }
  1141. //只允许输入英文
  1142. if ($('[data-keyeng]').length > 0) {
  1143. $('[data-keyeng]').on('keyup blur', function (e) {
  1144. this.value = this.value.replace(/[^\a-\z\A-\Z]/g, '');
  1145. });
  1146. }
  1147. //只能输入英文字母和数字,不能输入中文
  1148. if ($('[data-keyinteng]').length > 0) {
  1149. $('[data-keyinteng]').on('keyup blur', function (e) {
  1150. this.value = this.value.replace(/[^0-9\a-\z\A-\Z\_]/g, '');
  1151. });
  1152. }
  1153. //只能输入字母和汉字
  1154. if ($('[data-keycneng]').length > 0) {
  1155. $('[data-keycneng]').on('keyup blur', function (e) {
  1156. this.value = this.value.replace(/[/d]/g, '');
  1157. });
  1158. }
  1159. //帳號輸入規則
  1160. if ($('[data-keymemberid]').length > 0) {
  1161. $('[data-keymemberid]').on('keyup blur', function (e) {
  1162. this.value = this.value.replace(/[^\w\.\/]/ig, '');
  1163. });
  1164. }
  1165. };
  1166. /**
  1167. * 驗證郵箱格式
  1168. * @param {String} email 输入的值
  1169. * @return{Boolean}
  1170. */
  1171. w.isEmail = function (email) {
  1172. if (/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(email)) {
  1173. return true;
  1174. }
  1175. else {
  1176. return false;
  1177. }
  1178. };
  1179. /********************************************
  1180. * 函數名稱showMsg
  1181. * 目的顯示提示訊息替代ALERT功能
  1182. * 作者John
  1183. * 時間2015/06/12
  1184. * 參數說明
  1185. *********************************************/
  1186. /**
  1187. * 消息提示
  1188. * @param {String} msg 提示文字
  1189. * @param {String} type 提示類型
  1190. */
  1191. w.showMsg = function (msg, type) {
  1192. var showDuration = "300",
  1193. hideDuration = "1000",
  1194. timeOut = "3000",
  1195. extendedTimeOut = "1000",
  1196. showEasing = "swing",
  1197. hideEasing = "linear",
  1198. showMethod = "fadeIn",
  1199. hideMethod = "fadeOut",
  1200. addClear = false,
  1201. debug = false,
  1202. newestOnTop = true,
  1203. progressBar = false,
  1204. positionClass = 'toast-edit-center',
  1205. preventDuplicates = true,
  1206. addBehaviorOnToastClick = true,
  1207. BehaviorFunc = null,
  1208. type = type || 'info';
  1209. getMsgBox(type, msg, showDuration, hideDuration, timeOut, extendedTimeOut, showEasing, hideEasing, showMethod, hideMethod, addClear, debug, newestOnTop, progressBar, positionClass, preventDuplicates, addBehaviorOnToastClick, BehaviorFunc);
  1210. };
  1211. /**
  1212. * 目的彈出帶一個按鈕的提示窗口並執行方法
  1213. * 參數說明
  1214. * msg 提示訊息
  1215. * title 提示窗口的標題success....
  1216. * Position提示窗口的位置
  1217. * type :提示方式success InfoWarningError四種
  1218. * msg :提示框中顯示的訊息
  1219. * title :提示框顯示的其他html內容
  1220. * showDuration :显示时间
  1221. * hideDuration :隐藏时间
  1222. * timeOut :超时
  1223. * extendedTimeOut :延长超时
  1224. * showEasing :
  1225. * hideEasing :
  1226. * showMethod :顯示的方式
  1227. * hideMethod :隱藏的方式
  1228. * addClear :是否添加清除
  1229. * debug :
  1230. * newestOnTop :
  1231. * progressBar :是否添加進度顯示
  1232. * positionClass :位置
  1233. * preventDuplicates:是否防止重复
  1234. * func :執行方法
  1235. *********************************************/
  1236. function getMsgBox(type, msg, showDuration, hideDuration, timeOut, extendedTimeOut, showEasing, hideEasing, showMethod, hideMethod, addClear, debug, newestOnTop, progressBar, positionClass, preventDuplicates, addBehaviorOnToastClick, BehaviorFunc) {
  1237. var title = i18next.t("message.Tips") || '<span data-i18n="message.Tips"></span>';
  1238. toastr.options = {
  1239. debug: debug,
  1240. newestOnTop: newestOnTop,
  1241. progressBar: progressBar,
  1242. positionClass: positionClass || 'toast-top-center',
  1243. preventDuplicates: preventDuplicates,
  1244. onclick: null
  1245. };
  1246. if (addBehaviorOnToastClick) {
  1247. toastr.options.onclick = BehaviorFunc;
  1248. }
  1249. if (showDuration) {
  1250. toastr.options.showDuration = showDuration;
  1251. }
  1252. if (hideDuration) {
  1253. toastr.options.hideDuration = hideDuration;
  1254. }
  1255. if (timeOut) {
  1256. toastr.options.timeOut = timeOut;
  1257. //setTimeout(BehaviorFunc, timeOut)
  1258. }
  1259. if (extendedTimeOut) {
  1260. toastr.options.extendedTimeOut = extendedTimeOut;
  1261. }
  1262. if (showEasing) {
  1263. toastr.options.showEasing = showEasing;
  1264. }
  1265. if (hideEasing) {
  1266. toastr.options.hideEasing = hideEasing;
  1267. }
  1268. if (showMethod) {
  1269. toastr.options.showMethod = showMethod;
  1270. }
  1271. if (hideMethod) {
  1272. toastr.options.hideMethod = hideMethod;
  1273. }
  1274. if (addClear) {//是否清空之前樣式
  1275. toastr.options.tapToDismiss = false;
  1276. }
  1277. var $toast = toastr[type](msg, title);
  1278. }
  1279. /**
  1280. * 取得host
  1281. * @return {String} host Url
  1282. */
  1283. function gethost() {
  1284. var g_ServerUrl = location.origin + '/';
  1285. if (!window.location.origin) {
  1286. gWebUrl = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port : '');
  1287. }
  1288. return g_ServerUrl;
  1289. }
  1290. if (!w.browser) {
  1291. var userAgent = navigator.userAgent.toLowerCase(), uaMatch;
  1292. window.browser = {}
  1293. /**
  1294. * 判断是否为ie
  1295. */
  1296. function isIE() {
  1297. return ("ActiveXObject" in window);
  1298. }
  1299. /**
  1300. * 判断是否为谷歌浏览器
  1301. */
  1302. if (!uaMatch) {
  1303. uaMatch = userAgent.match(/chrome\/([\d.]+)/);
  1304. if (uaMatch != null) {
  1305. window.browser['name'] = 'chrome';
  1306. window.browser['version'] = uaMatch[1];
  1307. }
  1308. }
  1309. /**
  1310. * 判断是否为火狐浏览器
  1311. */
  1312. if (!uaMatch) {
  1313. uaMatch = userAgent.match(/firefox\/([\d.]+)/);
  1314. if (uaMatch != null) {
  1315. window.browser['name'] = 'firefox';
  1316. window.browser['version'] = uaMatch[1];
  1317. }
  1318. }
  1319. /**
  1320. * 判断是否为opera浏览器
  1321. */
  1322. if (!uaMatch) {
  1323. uaMatch = userAgent.match(/opera.([\d.]+)/);
  1324. if (uaMatch != null) {
  1325. window.browser['name'] = 'opera';
  1326. window.browser['version'] = uaMatch[1];
  1327. }
  1328. }
  1329. /**
  1330. * 判断是否为Safari浏览器
  1331. */
  1332. if (!uaMatch) {
  1333. uaMatch = userAgent.match(/safari\/([\d.]+)/);
  1334. if (uaMatch != null) {
  1335. window.browser['name'] = 'safari';
  1336. window.browser['version'] = uaMatch[1];
  1337. }
  1338. }
  1339. /**
  1340. * 最后判断是否为IE
  1341. */
  1342. if (!uaMatch) {
  1343. if (userAgent.match(/msie ([\d.]+)/) != null) {
  1344. uaMatch = userAgent.match(/msie ([\d.]+)/);
  1345. window.browser['name'] = 'ie';
  1346. window.browser['version'] = uaMatch[1];
  1347. } else {
  1348. /**
  1349. * IE10
  1350. */
  1351. if (isIE() && !!d.attachEvent && (function () { "use strict"; return !this; }())) {
  1352. window.browser['name'] = 'ie';
  1353. window.browser['version'] = '10';
  1354. }
  1355. /**
  1356. * IE11
  1357. */
  1358. if (isIE() && !d.attachEvent) {
  1359. window.browser['name'] = 'ie';
  1360. window.browser['version'] = '11';
  1361. }
  1362. }
  1363. }
  1364. /**
  1365. * 注册判断方法
  1366. */
  1367. if (!$.isIE) {
  1368. $.extend({
  1369. isIE: function () {
  1370. return (window.browser.name == 'ie');
  1371. }
  1372. });
  1373. }
  1374. if (!$.isChrome) {
  1375. $.extend({
  1376. isChrome: function () {
  1377. return (window.browser.name == 'chrome');
  1378. }
  1379. });
  1380. }
  1381. if (!$.isFirefox) {
  1382. $.extend({
  1383. isFirefox: function () {
  1384. return (window.browser.name == 'firefox');
  1385. }
  1386. });
  1387. }
  1388. if (!$.isOpera) {
  1389. $.extend({
  1390. isOpera: function () {
  1391. return (window.browser.name == 'opera');
  1392. }
  1393. });
  1394. }
  1395. if (!$.isSafari) {
  1396. $.extend({
  1397. isSafari: function () {
  1398. return (window.browser.name == 'safari');
  1399. }
  1400. });
  1401. }
  1402. }
  1403. if ($.datepicker !== undefined) {
  1404. $.datepicker.regional['zh-TW'] = {
  1405. dayNames: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
  1406. dayNamesMin: ["日", "一", "二", "三", "四", "五", "六"],
  1407. monthNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
  1408. monthNamesShort: ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"],
  1409. prevText: "上月",
  1410. nextText: "次月",
  1411. weekHeader: "週",
  1412. showMonthAfterYear: true, // True if the year select precedes month, false for month then year//設置是否在面板的头部年份后面显示月份
  1413. dateFormat: "yy/mm/dd"
  1414. };
  1415. $.datepicker.setDefaults($.datepicker.regional["zh-TW"]);
  1416. }
  1417. function onStart(e) {
  1418. showWaiting(typeof IsWaiting === 'string' ? IsWaiting : undefined);
  1419. }
  1420. function onStop(e) {
  1421. closeWaiting();
  1422. setTimeout(function () { IsWaiting = null; }, 3000);
  1423. }
  1424. $(d).ajaxStart(onStart).ajaxStop(onStop);//.ajaxSuccess(onSuccess);
  1425. })(jQuery, window, document);
  1426. /**
  1427. * 日期添加屬性
  1428. * @param {String} type y:;q:季度;m:;w:星期;d:;h:小時;n:;s:;ms:毫秒;
  1429. * @param {Number} filetype 添加的數值
  1430. * @return {Date} r 新的時間
  1431. */
  1432. Date.prototype.dateAdd = function (type, num) {
  1433. var r = this,
  1434. k = { y: 'FullYear', q: 'Month', m: 'Month', w: 'Date', d: 'Date', h: 'Hours', n: 'Minutes', s: 'Seconds', ms: 'MilliSeconds' },
  1435. n = { q: 3, w: 7 };
  1436. eval('r.set' + k[type] + '(r.get' + k[type] + '()+' + ((n[type] || 1) * num) + ')');
  1437. return r;
  1438. }
  1439. /**
  1440. * 計算兩個日期的天數
  1441. * @param {Date} date 日期
  1442. */
  1443. Date.prototype.diff = function (date) {
  1444. return (this.getTime() - date.getTime()) / (24 * 60 * 60 * 1000);
  1445. }
  1446. /**
  1447. * 对Date的扩展 Date 转化为指定格式的String
  1448. * (M)(d)12小时(h)24小时(H)(m)(s)(E)季度(q) 可以用 1-2 个占位符
  1449. * (y)可以用 1-4 个占位符毫秒(S)只能用 1 个占位符( 1-3 位的数字)
  1450. * eg:
  1451. * (new Date()).formate("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
  1452. * (new Date()).formate("yyyy-MM-dd E HH:mm:ss") ==> 2009-03-10 20:09:04
  1453. * (new Date()).formate("yyyy-MM-dd EE hh:mm:ss") ==> 2009-03-10 周二 08:09:04
  1454. * (new Date()).formate("yyyy-MM-dd EEE hh:mm:ss") ==> 2009-03-10 星期二 08:09:04
  1455. * (new Date()).formate("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
  1456. */
  1457. Date.prototype.formate = function (fmt) {
  1458. var o = {
  1459. "M+": this.getMonth() + 1, //月份
  1460. "d+": this.getDate(), //日
  1461. "h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, //小时
  1462. "H+": this.getHours(), //小时
  1463. "m+": this.getMinutes(), //分
  1464. "s+": this.getSeconds(), //秒
  1465. "q+": Math.floor((this.getMonth() + 3) / 3), //季度
  1466. "S": this.getMilliseconds() //毫秒
  1467. };
  1468. var week = {
  1469. "0": "\u65e5",
  1470. "1": "\u4e00",
  1471. "2": "\u4e8c",
  1472. "3": "\u4e09",
  1473. "4": "\u56db",
  1474. "5": "\u4e94",
  1475. "6": "\u516d"
  1476. };
  1477. if (/(y+)/.test(fmt)) {
  1478. fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  1479. }
  1480. if (/(E+)/.test(fmt)) {
  1481. fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "\u661f\u671f" : "\u5468") : "") + week[this.getDay() + ""]);
  1482. }
  1483. for (var k in o) {
  1484. if (new RegExp("(" + k + ")").test(fmt)) {
  1485. fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  1486. }
  1487. }
  1488. return fmt;
  1489. }
  1490. /**
  1491. * 註冊全替換
  1492. * @param {String} s1 字串1
  1493. * @param {String} s2 字串2
  1494. */
  1495. String.prototype.replaceAll = function (s1, s2) {
  1496. return this.replace(new RegExp(s1, "gm"), s2);
  1497. }
  1498. /**
  1499. * 百分数转小数
  1500. */
  1501. String.prototype.toPoint = function () {
  1502. return this.replace("%", "") / 100;
  1503. }
  1504. /**
  1505. * 註冊金額添加三位一撇
  1506. */
  1507. String.prototype.toMoney = Number.prototype.toMoney = function () {
  1508. return this.toString().replace(/\d+?(?=(?:\d{3})+$)/g, function (s) {
  1509. return s + ',';
  1510. });
  1511. }
  1512. /**
  1513. * 数字四舍五入保留n位小数
  1514. */
  1515. String.prototype.toFloat = Number.prototype.toFloat = function (n) {
  1516. n = n ? parseInt(n) : 0;
  1517. var number = this;
  1518. if (n <= 0) return Math.round(number);
  1519. number = Math.round(number * Math.pow(10, n)) / Math.pow(10, n);
  1520. return number;
  1521. }
  1522. /**
  1523. * 刪除陣列內包含(undefined, null, 0, false, NaN and '')的資料
  1524. */
  1525. Array.prototype.clear = function () {
  1526. var newArray = [];
  1527. for (var i = 0; i < this.length; i++) {
  1528. if (this[i]) {
  1529. newArray.push(this[i]);
  1530. }
  1531. }
  1532. return newArray;
  1533. }
  1534. /**
  1535. * 在數組指定位置添加元素
  1536. * @param {Number} index 位置
  1537. * @param {Object} item 要添加的元素
  1538. */
  1539. Array.prototype.insert = function (index, item) {
  1540. this.splice(index, 0, item);
  1541. };
  1542. jQuery.whenArray = function (array) {
  1543. return jQuery.when.apply(this, array);
  1544. };