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.

1650 lines
54 KiB

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