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.

2916 lines
101 KiB

2 years ago
  1. /*global $, alert, g_cus, g_de, g_api, g_db, g_ul, btoa, console, i18n */
  2. var i18next = ("undefined" === typeof i18next) ? parent.top.i18next : i18next,
  3. g_db = {
  4. /**
  5. * Check the capability
  6. * @private
  7. * @method SupportLocalStorage
  8. * @return {Object} description
  9. */
  10. SupportLocalStorage: function () {
  11. 'use strict';
  12. return typeof (localStorage) !== "undefined";
  13. },
  14. /**
  15. * Insert data
  16. * @private
  17. * @method SetItem
  18. * @param {Object} sKey
  19. * @param {Object} sValue
  20. * @return {Object} description
  21. */
  22. SetItem: function (sKey, sValue) {
  23. 'use strict';
  24. var bRes = false;
  25. if (this.SupportLocalStorage()) {
  26. localStorage.setItem(sKey, sValue);
  27. bRes = true;
  28. }
  29. return bRes;
  30. },
  31. /**
  32. * Fetch data
  33. * @private
  34. * @method GetItem
  35. * @param {Object} sKey
  36. * @return {Object} description
  37. */
  38. GetItem: function (sKey) {
  39. 'use strict';
  40. var sRes = null;
  41. if (this.SupportLocalStorage()) {
  42. sRes = localStorage.getItem(sKey);
  43. }
  44. return sRes;
  45. },
  46. /**
  47. * Remove data
  48. * @private
  49. * @method RemoveItem
  50. * @param {Object} sKey
  51. * @return {Object} description
  52. */
  53. RemoveItem: function (sKey) {
  54. 'use strict';
  55. var bRes = false;
  56. if (this.SupportLocalStorage()) {
  57. localStorage.removeItem(sKey);
  58. bRes = true;
  59. }
  60. return bRes;
  61. },
  62. /**
  63. * Description for GetDic
  64. * @private
  65. * @method GetDic
  66. * @return {Object} description
  67. */
  68. GetDic: function (sKey) {
  69. 'use strict';
  70. var dicRes = null,
  71. vTemp;
  72. if (this.SupportLocalStorage()) {
  73. vTemp = localStorage.getItem(sKey);
  74. if (null !== vTemp) {
  75. dicRes = JSON.parse(vTemp);
  76. }
  77. }
  78. return dicRes;
  79. },
  80. /**
  81. * Description for SetDic
  82. * @private
  83. * @method SetDic
  84. * @return {Object} description
  85. */
  86. SetDic: function (sKey, dicValue) {
  87. 'use strict';
  88. var bRes = false;
  89. if (this.SupportLocalStorage()) {
  90. localStorage.setItem(sKey, JSON.stringify(dicValue));
  91. bRes = true;
  92. }
  93. return bRes;
  94. }
  95. };
  96. var g_gd = {
  97. webapilonginurl: "/api/Service/GetLogin",
  98. webapiurl: "/api/Cmd/GetData",
  99. projectname: "Eurotran",
  100. projectver: "Origtek",
  101. relpath: "",
  102. debugmode: window.location.host === '192.168.1.105',
  103. debugcolor: "#732C6B",
  104. IsEDU: g_db.GetItem("isedu") === "true"
  105. };
  106. var g_ul = {
  107. /**
  108. * Get token from db
  109. * @returns {String} Token in localStorage
  110. */
  111. GetToken: function () {
  112. 'use strict';
  113. return g_db.GetItem("token");
  114. },
  115. /**
  116. * Set token to db
  117. * @param {String} sTokenValue api token
  118. */
  119. SetToken: function (sTokenValue) {
  120. 'use strict';
  121. g_db.SetItem("token", sTokenValue);
  122. },
  123. /**
  124. * Set signature to db
  125. * @param {String} sSignatureValue api signature
  126. */
  127. GetSignature: function () {
  128. 'use strict';
  129. return g_db.GetItem("signature");
  130. },
  131. /**
  132. * Set signature to db
  133. * @param {String} sSignatureValue api signature
  134. */
  135. SetSignature: function (sSignatureValue) {
  136. 'use strict';
  137. g_db.SetItem("signature", sSignatureValue);
  138. },
  139. /**
  140. * Set language
  141. * @param {String} language method
  142. */
  143. SetLang: function (sLang) {
  144. 'use strict';
  145. g_db.SetItem("lang", sLang);
  146. },
  147. /**
  148. * Get language
  149. * @returns {String} language in localStorage
  150. */
  151. GetLang: function () {
  152. 'use strict';
  153. return g_db.GetItem("lang");
  154. },
  155. /**
  156. * Set login method
  157. * @param {String} login method
  158. */
  159. SetLoginMethod: function (sLoginMethod) {
  160. 'use strict';
  161. g_db.SetItem("LoginMethod", sLoginMethod);
  162. },
  163. /**
  164. * Get login method
  165. * @returns {String} login method in localStorage
  166. */
  167. GetLoginMethod: function () {
  168. 'use strict';
  169. return g_db.GetItem("LoginMethod");
  170. },
  171. /**
  172. * Check is edu environment
  173. * @returns {String} login method in localStorage
  174. */
  175. IsEDU: function () {
  176. 'use strict';
  177. return g_db.GetItem("isedu");
  178. },
  179. /**
  180. * Get trace stack
  181. */
  182. TraceStackDump: function () {
  183. var dicTraceStackData = {},
  184. dicTraceStackDataLevel = {},
  185. ldicTraceStackDataList = [],
  186. curArguments = null,
  187. iLevel = 0,
  188. iIdx = 0,
  189. iLim = 0,
  190. oPara = null,
  191. bFindButtonEvent = false;
  192. curArguments = arguments;
  193. do {
  194. dicTraceStackDataLevel = {};
  195. dicTraceStackDataLevel.name = curArguments.callee.name;
  196. dicTraceStackDataLevel.parameters = [];
  197. iLim = curArguments.length;
  198. if (iLim > 0) {
  199. oPara = curArguments["0"];
  200. if (typeof (oPara) === "object" && oPara.hasOwnProperty("currentTarget")) {
  201. bFindButtonEvent = true;
  202. dicTraceStackDataLevel.buttonclick = oPara.currentTarget.id;
  203. }
  204. else {
  205. for (iIdx = 0; iIdx < iLim; iIdx++) {
  206. oPara = curArguments[iIdx.toString()];
  207. dicTraceStackDataLevel.parameters.push(curArguments[iIdx.toString()]);
  208. }
  209. }
  210. }
  211. if (iLevel > 0) {
  212. ldicTraceStackDataList.push($.extend({}, dicTraceStackDataLevel));
  213. }
  214. if (curArguments.callee.caller === null) {
  215. break;
  216. }
  217. curArguments = curArguments.callee.caller.arguments;
  218. iLevel = iLevel + 1;
  219. }
  220. while (bFindButtonEvent === false);
  221. dicTraceStackData.stack = ldicTraceStackDataList;
  222. return dicTraceStackData;
  223. }
  224. };
  225. var g_api = {
  226. ConnectLite: function (i_sModuleName, i_sFuncName, i_dicData, i_sSuccessFunc, i_FailFunc, i_bAsyn, i_sShwd) {
  227. window.IsWaiting = i_sShwd;
  228. return this.ConnectLiteWithoutToken(i_sModuleName, i_sFuncName, i_dicData, i_sSuccessFunc, i_FailFunc, i_bAsyn);
  229. },
  230. ConnectService: function (i_sModuleName, i_sFuncName, i_dicData, i_sSuccessFunc, i_FailFunc, i_bAsyn, i_sShwd) {
  231. window.IsWaiting = i_sShwd;
  232. return this.ConnectWebLiteWithoutToken(i_sModuleName, i_sFuncName, i_dicData, i_sSuccessFunc, i_FailFunc, i_bAsyn);
  233. },
  234. ConnectLiteWithoutToken: function (i_sModuleName, i_sFuncName, i_dicData, i_sSuccessFunc, i_FailFunc, i_bAsyn) {
  235. var dicData = {},
  236. dicParameters = {},
  237. token = g_ul.GetToken(),
  238. lang = g_ul.GetLang(),
  239. signature = g_ul.GetSignature();
  240. dicParameters.ORIGID = g_db.GetItem('orgid');
  241. dicParameters.USERID = g_db.GetItem('userid');
  242. dicParameters.MODULE = i_sModuleName;
  243. dicParameters.TYPE = i_sFuncName;
  244. dicParameters.PROJECT = g_gd.projectname;
  245. dicParameters.PROJECTVER = g_gd.projectver;
  246. dicParameters.TRACEDUMP = null; // g_ul.TraceStackDump();
  247. i_dicData = i_dicData || {};
  248. if (g_db.GetItem('dblockDict') !== null) {
  249. i_dicData.dblockDict = g_db.GetItem('dblockDict');
  250. }
  251. dicParameters.DATA = i_dicData;
  252. if (lang !== null) {
  253. dicParameters.LANG = lang;
  254. }
  255. if (token !== null) {
  256. dicParameters.TOKEN = token;
  257. }
  258. if (signature !== null) {
  259. dicParameters.SIGNATURE = signature;
  260. }
  261. dicParameters.CUSTOMDATA = {};
  262. if (window.sProgramId) {
  263. dicParameters.CUSTOMDATA.program_id = sProgramId;
  264. }
  265. dicParameters.CUSTOMDATA.module_id = "webapp";
  266. dicData.url = i_dicData.hasOwnProperty("url") ? i_dicData.url : g_gd.webapiurl;
  267. dicData.successfunc = i_sSuccessFunc;
  268. dicData.dicparameters = dicParameters;
  269. dicData.failfunc = ("function" === typeof (i_FailFunc)) ? i_FailFunc : function (jqXHR, textStatus, errorThrown) {
  270. alert("ConnectLite Fail jqXHR:" + jqXHR + " textStatus:" + textStatus + " errorThrown:" + errorThrown);
  271. };
  272. dicData.useasync = ("boolean" === typeof (i_bAsyn)) ? i_bAsyn : true;
  273. return this.AjaxPost(dicData);
  274. },
  275. //w.CallAjax = function (url, fnname, data, sucfn, failfn, wait, async, alwaysfn) {
  276. ConnectWebLiteWithoutToken: function (i_sUrl, i_sFuncName, i_dicData, i_sSuccessFunc, i_FailFunc, i_bAsyn) {
  277. var dicData = {},
  278. dicParameters = {},
  279. token = g_ul.GetToken(),
  280. lang = g_ul.GetLang(),
  281. signature = g_ul.GetSignature();
  282. dicParameters.ORIGID = g_db.GetItem('orgid');
  283. dicParameters.USERID = g_db.GetItem('userid');
  284. dicParameters.MODULE = '';
  285. dicParameters.TYPE = i_sFuncName;
  286. dicParameters.PROJECT = g_gd.projectname;
  287. dicParameters.PROJECTVER = g_gd.projectver;
  288. dicParameters.TRACEDUMP = null; // g_ul.TraceStackDump();
  289. if (g_db.GetItem('dblockDict') !== null) {
  290. i_dicData.dblockDict = g_db.GetItem('dblockDict');
  291. }
  292. dicParameters.DATA = i_dicData;
  293. if (lang !== null) {
  294. dicParameters.LANG = lang;
  295. }
  296. if (token !== null) {
  297. dicParameters.TOKEN = token;
  298. }
  299. if (signature !== null) {
  300. dicParameters.SIGNATURE = signature;
  301. }
  302. dicParameters.CUSTOMDATA = {};
  303. if (window.sProgramId) {
  304. dicParameters.CUSTOMDATA.program_id = sProgramId;
  305. }
  306. dicParameters.CUSTOMDATA.module_id = "webapp";
  307. dicData.url = getWebServiceUrl(i_sUrl, i_sFuncName);
  308. dicData.successfunc = i_sSuccessFunc;
  309. dicData.dicparameters = dicParameters;
  310. dicData.failfunc = ("function" === typeof (i_FailFunc)) ? i_FailFunc : function (jqXHR, textStatus, errorThrown) {
  311. alert("ConnectLite Fail jqXHR:" + jqXHR + " textStatus:" + textStatus + " errorThrown:" + errorThrown);
  312. };
  313. dicData.useasync = ("boolean" === typeof (i_bAsyn)) ? i_bAsyn : true;
  314. return this.AjaxPost(dicData);
  315. },
  316. AjaxPost: function (i_dicData) {
  317. 'use strict';
  318. var defaultOption = {
  319. useasync: true,
  320. successfunc: null,
  321. failfunc: null,
  322. alwaysfunc: null,
  323. url: null,
  324. dicparameters: null
  325. },
  326. runOption = $.extend(defaultOption, i_dicData),
  327. runSuccess = function (res) {
  328. if (res.RESULT === -1) { // ╠message.TokenVerifyFailed⇒您的身份認證已經過期,請重新登入╣ ╠common.Tips⇒提示╣
  329. layer.alert(i18next.t("message.TokenVerifyFailed"), { icon: 0, title: i18next.t("common.Tips") }, function (index) {
  330. window.top.location.href = '/Page/login.html';
  331. });
  332. }
  333. else {
  334. if (runOption.successfunc) {
  335. runOption.successfunc(res);
  336. }
  337. }
  338. };
  339. return $.ajax({
  340. type: 'POST',
  341. url: runOption.url,
  342. data: "=" + btoa2(encodeURIComponent(JSON.stringify(runOption.dicparameters))),
  343. success: runSuccess,
  344. error: runOption.failfunc,
  345. beforeSend: function (xhr) {
  346. var token = g_ul.GetToken(),
  347. timestamp = $.now(),
  348. nonce = rndnum();
  349. xhr.setRequestHeader("orgid", runOption.dicparameters.ORIGID);
  350. xhr.setRequestHeader("userid", runOption.dicparameters.USERID);
  351. xhr.setRequestHeader("token", token);
  352. xhr.setRequestHeader("timestamp", timestamp);
  353. xhr.setRequestHeader("nonce", nonce);
  354. },
  355. async: true !== runOption.useasync ? false : true
  356. }).always(runOption.alwaysfunc);
  357. }
  358. };
  359. (function ($, w, d) {
  360. /**
  361. * 取得host
  362. */
  363. w.gServerUrl = w.location.origin || gethost();
  364. /**
  365. * 定義系統所有HTML模版
  366. */
  367. w.ComTmp = {
  368. PageTitle: '/Page/Pop/PageTitle.html',
  369. };
  370. /**
  371. * 定義系統所有公用 Service.fnction
  372. */
  373. w.ComFn = {
  374. W_Com: 'comw',
  375. W_Web: 'web',
  376. GetUserList: 'GetUserList',
  377. GetArguments: 'GetArguments',
  378. GetSysSet: 'GetSysSet',
  379. GetSerial: 'GetSerialNumber',
  380. GetUpdateOrder: 'UpdateOrderByValue',
  381. SendMail: 'SendMail',
  382. GetExcel: 'CreateExcel',
  383. GetList: 'QueryList',
  384. GetOne: 'QueryOne',
  385. GetPage: 'QueryPage',
  386. GetPagePrc: 'QueryPageByPrc',
  387. GetAdd: 'Add',
  388. GetUpd: 'Update',
  389. GetDel: 'Delete',
  390. GetTran: 'UpdateTran',
  391. GetCount: 'QueryCount',
  392. CheckInvoiceNum: 'CheckInvoiceNumber'
  393. };
  394. /**
  395. * 定義系統所有公用 Service
  396. */
  397. w.Service = {
  398. cotrl: '/Controller.ashx',
  399. comw: 'ComWebService',
  400. web: 'WebService',
  401. com: 'Common',
  402. opm: 'OpmCom',
  403. eip: 'EipCom',
  404. sys: 'SysCom',
  405. auth: 'Authorize'
  406. };
  407. /**
  408. * 定義頁面離開是否需要儲存
  409. */
  410. w.bRequestStorage = false;
  411. w.bLeavePage = false;
  412. /**
  413. * 定義查詢頁面默認顯示第幾頁
  414. */
  415. w.QueryPageidx = 1;
  416. /**
  417. * Ajax是否等待
  418. */
  419. w.IsWaiting = null;
  420. /**
  421. * For display javascript exception on UI
  422. */
  423. w.onerror = function (message, source, lineno, colno, error) {
  424. console.log(source + " line:" + lineno + " colno:" + colno + " " + message);
  425. if (parent.top.SysSet && parent.top.SysSet.IsOpenMail === 'Y') {
  426. g_api.ConnectLite('Log', 'ErrorMessage', {
  427. ErrorSource: source,
  428. Errorlineno: lineno,
  429. Errorcolno: colno,
  430. ErrorMessage: message
  431. }, function (res) {
  432. });
  433. }
  434. };
  435. /**
  436. * 翻譯語系
  437. * @param {HTMLElement} dom 翻譯回調函數
  438. */
  439. w.transLang = function (dom) {
  440. i18next = ("undefined" === typeof i18next) ? parent.top.i18next : i18next;
  441. var oHandleData = dom === undefined ? $('[data-i18n]') : dom.find('[data-i18n]'),
  442. oHandlePlaceholder = dom === undefined ? $('[placeholderid]') : dom.find('[placeholderid]');
  443. oHandleData.each(function (idx, el) {
  444. var i18key = $(el).attr('data-i18n');
  445. if (i18key) {
  446. var sLan = i18next.t(i18key);
  447. if (el.nodeName == 'INPUT' && el.type == 'button') {
  448. $(el).val(sLan);
  449. }
  450. else {
  451. $(el).html(sLan);
  452. }
  453. }
  454. });
  455. oHandlePlaceholder.each(function (idx, el) {
  456. var i18key = $(el).attr("placeholderid");
  457. if (i18key) {
  458. var sLan = i18next.t(i18key);
  459. if (sLan !== i18key) {
  460. $(el).attr("placeholder", sLan);
  461. }
  462. }
  463. });
  464. };
  465. /**
  466. * 翻譯語系
  467. * @param {HTMLElement} dom 要翻譯的html標籤
  468. */
  469. w.refreshLang = function (dom) {
  470. if (dom && dom.length === 0) {
  471. return false;
  472. }
  473. transLang(dom);
  474. };
  475. /**
  476. * 設定多於系
  477. * @param {String} lng 語種
  478. * @param {String} dom 要翻譯的html標籤
  479. * @param {Function} callback 回調函數
  480. */
  481. w.setLang = function (lng, dom, callback) {
  482. if (!lng) return;
  483. g_ul.SetLang(lng);
  484. i18next = ("undefined" == typeof i18next) ? parent.top.i18next : i18next;
  485. $.getJSON(gServerUrl + "/Scripts/lang/" + (parent.top.OrgID || 'TE') + "/" + lng + ".json?v=20180801", function (json) {
  486. var oResources = {};
  487. oResources[lng] = {
  488. translation: json
  489. };
  490. i18next.init({
  491. lng: lng,
  492. resources: oResources,
  493. useLocalStorage: false, //是否将语言包存储在localstorage
  494. //ns: { namespaces: ['trans'], defaultNs: 'trans' }, //加载的语言包
  495. localStorageExpirationTime: 86400000 // 有效周期,单位ms。默认1
  496. }, function (err, t) {
  497. transLang(dom);
  498. if (typeof callback === 'function') {
  499. callback(t);
  500. }
  501. });
  502. });
  503. };
  504. /**
  505. * getLanguagePack
  506. */
  507. w.getLanguagePack = function (sMsgKey) {
  508. var sLang = g_ul.GetLang() || 'en';
  509. return i18next.getResourceBundle(sLang, 'translation').sMsgKey || sMsgKey;
  510. };
  511. /**
  512. * 獲取WebService路勁
  513. * @param {String} type Service類型
  514. * @param {String} fnname function 名稱
  515. */
  516. w.getWebServiceUrl = function (type, fnname) {
  517. var sUrl = '';
  518. switch (type) {
  519. case 'aspx':
  520. sUrl = fnname;
  521. break;
  522. case 'cotrl':
  523. sUrl = '/Controller.ashx?' + fnname;
  524. break;
  525. default:
  526. sUrl = '/WS/' + Service[type] + '.asmx/' + fnname;
  527. break;
  528. }
  529. return sUrl;
  530. };
  531. /**
  532. * 呼叫Ajax
  533. * @param {String} urlaspx 地址
  534. * @param {String} fnname 方法名稱
  535. * @param {Object} data 參數
  536. * @param {Function} callback 成功回調函數
  537. * @param {Function} failfn 失敗回調函數
  538. * @param {String} IsWait 是否waitting默認false
  539. * @param {Boolean} IsAsync 是否同步默認非同步
  540. * @return {Object} Ajax對象
  541. */
  542. w.CallAjax = function (url, fnname, data, sucfn, failfn, wait, async, alwaysfn) {
  543. w.IsWaiting = (wait === undefined || wait === true) ? true : (wait === false) ? null : wait;
  544. return $.ajax({
  545. type: 'POST',
  546. async: async == undefined ? true : false,
  547. url: getWebServiceUrl(url, fnname),
  548. data: JSON.stringify(data), //傳送區域參數
  549. contentType: 'application/json; charset=utf-8',
  550. dataType: 'json',
  551. success: function (res) {
  552. if (res.d === '-1' || res.d === -1) {// ╠message.TokenVerifyFailed⇒您的身份認證已經過期,請重新登入╣ ╠common.Tips⇒提示╣
  553. layer.alert(i18next.t("message.TokenVerifyFailed"), { icon: 0, title: i18next.t("common.Tips") }, function (index) {
  554. w.top.location.href = '/Page/login.html';
  555. });
  556. }
  557. else {
  558. if (sucfn) {
  559. sucfn(res);
  560. }
  561. }
  562. },
  563. beforeSend: function (xhr) {
  564. var orgid = g_db.GetItem('orgid'),
  565. userid = g_db.GetItem('userid'),
  566. token = g_ul.GetToken();
  567. xhr.setRequestHeader("orgid", orgid);
  568. xhr.setRequestHeader("userid", userid);
  569. xhr.setRequestHeader("token", token);
  570. },
  571. error: failfn || function (e1, e2, e3) { },
  572. global: wait === false ? false : true
  573. }).always(alwaysfn);
  574. };
  575. /**
  576. * 呼叫Ajax
  577. * @param {String} urlaspx 地址
  578. * @param {String} fnname 方法名稱
  579. * @param {Object} data 參數
  580. * @param {Function} callback 成功回調函數
  581. * @param {Function} failfn 失敗回調函數
  582. * @param {String} IsWait 是否waitting默認false
  583. * @param {Boolean} IsAsync 是否同步默認非同步
  584. * @return {Object} Ajax對象
  585. */
  586. w.CallAjaxCross = function (urlaspx, fnname, data, callback, failfn, IsWait, IsAsync) {
  587. if (IsWait) IsWaiting = IsWait; else IsWaiting = null;
  588. return $.ajax({
  589. type: 'POST',
  590. async: IsAsync == undefined ? true : false,
  591. jsonpCallback: "Callback",//callback的function名称
  592. url: getWebServiceUrl(urlaspx, fnname),
  593. data: data, //傳送區域參數
  594. dataType: 'jsonp',
  595. success: callback || function () { },
  596. beforeSend: function (xhr) {
  597. var orgid = g_db.GetItem('orgid'),
  598. userid = g_db.GetItem('userid'),
  599. token = g_ul.GetToken();
  600. xhr.setRequestHeader("orgid", orgid);
  601. xhr.setRequestHeader("userid", userid);
  602. xhr.setRequestHeader("token", token);
  603. },
  604. error: failfn || function (a, b, c) {
  605. console.log(c);
  606. },
  607. global: (IsWait == undefined || IsWait == null) ? false : true
  608. });
  609. };
  610. /**
  611. * 開啟Waiting視窗
  612. * @param {String} msg 提示文字
  613. */
  614. w.showWaiting = function (msg) {
  615. $.blockUI({
  616. message: $('<div id="Divshowwaiting"><img src="/images/ajax-loader.gif">' + (msg || 'Waiting...') + '</div>'),
  617. css: {
  618. 'font-size': '36px',
  619. border: '0px',
  620. 'border-radius': '10px',
  621. 'background-color': '#FFF',
  622. padding: '15px 15px',
  623. opacity: .5,
  624. color: 'orange',
  625. cursor: 'wait',
  626. 'z-index': 1000000001
  627. },
  628. baseZ: 1000000000
  629. });
  630. w.setTimeout($.unblockUI, 60000);//預設開啟60秒後關閉
  631. };
  632. /**
  633. * 關閉Waiting視窗
  634. * @param {Number} iSleep 延遲時間單位為毫秒
  635. */
  636. w.closeWaiting = function (iSleep) {
  637. $(function () {
  638. if (iSleep == undefined) {
  639. iSleep = 100;
  640. }
  641. setTimeout($.unblockUI, iSleep);
  642. });
  643. };
  644. /**
  645. * 從物件陣列中移除屬性為objPropery值為objValue元素的物件
  646. * @param {Array} arrPerson 陣列物件
  647. * @param {String} objPropery 物件的屬性
  648. * @param {String} objPropery 對象的值
  649. * @return {Array} 過濾後陣列
  650. */
  651. w.Jsonremove = function (arrPerson, objPropery, objValue) {
  652. return $.grep(arrPerson, function (cur, i) {
  653. return cur[objPropery] != objValue;
  654. });
  655. };
  656. /**
  657. * 從物件陣列中獲取屬性為objPropery值為objValue元素的物件
  658. * @param {Array} arrPerson 陣列物件
  659. * @param {String} objPropery 物件的屬性
  660. * @param {String} objPropery 對象的值
  661. * @return {Array} 過濾後陣列
  662. */
  663. w.Jsonget = function (arrPerson, objPropery, objValue) {
  664. return $.grep(arrPerson, function (cur, i) {
  665. return cur[objPropery] == objValue;
  666. });
  667. };
  668. /**
  669. * 將json轉換字串
  670. * @param {Object} json json物件
  671. * @return {String} json字串
  672. */
  673. w.Tostr = function (json) {
  674. return JSON.stringify(json);
  675. };
  676. /**
  677. * 下載文件
  678. * @param {String} path 文件路徑相對路勁
  679. */
  680. w.DownLoadFile = function (path, filename) {
  681. var sUrl = gServerUrl + "/Controller.ashx";
  682. sUrl += '?action=downfile&path=' + path;
  683. if (filename) {
  684. sUrl += '&filename=' + filename;
  685. }
  686. w.location.href = sUrl;
  687. closeWaiting();
  688. };
  689. /**
  690. * 修改文件
  691. * @param {Object} file 文件信息
  692. * @param {HTMLElement} el 文件對象
  693. */
  694. w.EditFile = function (file, el) {
  695. layer.open({
  696. type: 1,
  697. title: i18next.t("common.EditFile"),// ╠common.EditFile⇒編輯文件信息╣
  698. shade: 0.75,
  699. maxmin: true, //开启最大化最小化按钮
  700. area: ['500px', '350px'],
  701. content: '<div class="pop-box">\
  702. <div class="input-group input-append">\
  703. <input type="text" maxlength="30" id="FileName" name="FileName" class="form-control w100p">\
  704. <span class="input-group-addon add-on">\
  705. </span>\
  706. </div><br/>\
  707. <div class="input-group w100p">\
  708. <input type="text" maxlength="250" id="Link" name="Link" class="form-control w100p" placeholder="URL">\
  709. </div><br/>\
  710. <div class="input-group">\
  711. <textarea name="FileDescription" id="FileDescription" class="form-control w100p" rows="5" cols="500"></textarea>\
  712. </div>\
  713. </div>',
  714. btn: [i18next.t('common.Confirm'), i18next.t('common.Cancel')],//╠common.Confirm⇒確定╣╠common.Cancel⇒取消╣
  715. success: function (layero, index) {
  716. $('.pop-box .input-group-addon').text('.' + file.subname);
  717. $('#FileName').val(file.filename);
  718. $('#Link').val(file.link);
  719. uniformInit(layero);//表單美化
  720. },
  721. yes: function (index, layero) {
  722. var sFileName = $('#FileName').val(),
  723. data = {
  724. FileName: sFileName,
  725. Link: $('#Link').val(),
  726. Description: $('#FileDescription').val()
  727. };
  728. if (!data.FileName) {
  729. showMsg(i18next.t("message.FileName_Required")); // ╠common.message⇒文件名稱不能為空╣
  730. return false;
  731. }
  732. data.FileName += '.' + file.subname;
  733. CallAjax(ComFn.W_Com, ComFn.GetUpd, {
  734. Params: {
  735. files: {
  736. values: data,
  737. keys: { FileID: file.fileid }
  738. }
  739. }
  740. }, function (res) {
  741. if (res.d > 0) {
  742. file.filename = sFileName;
  743. file.link = data.Link;
  744. file.description = data.Description;
  745. var img_title = el.find('.jFiler-item-title>b'),
  746. img_name = el.find('.file-name li:first'),
  747. img_description = el.find('.jFiler-item-description span');
  748. if (img_title.length > 0) {
  749. img_title.attr('title', data.FileName).text(data.FileName);
  750. }
  751. if (img_name.length > 0) {
  752. img_name.text(data.FileName);
  753. }
  754. if (img_description.length > 0) {
  755. img_description.text(data.Description);
  756. }
  757. layer.close(index);
  758. showMsg(i18next.t("message.Modify_Success"), 'success'); //╠message.Modify_Success⇒修改成功╣
  759. }
  760. else {
  761. showMsg(i18next.t("message.Modify_Failed"), 'error'); //╠message.Modify_Failed⇒修改失敗╣
  762. }
  763. });
  764. }
  765. });
  766. };
  767. /**
  768. * 刪除文件
  769. * @param {String} fileid 文件id
  770. * @param {String} idtype id類型
  771. */
  772. w.DelFile = function (fileid, idtype, bAlert) {
  773. bAlert = (bAlert === undefined || bAlert === null) ? true : bAlert;
  774. if (fileid && $.trim(fileid)) {
  775. return g_api.ConnectLite(Service.com, 'DelFile',
  776. {
  777. FileID: fileid,
  778. IDType: idtype || ''
  779. },
  780. function (res) {
  781. if (res.RESULT) {
  782. if (bAlert) {
  783. if (res.DATA.rel) {
  784. showMsg(i18next.t("message.Delete_Success"), 'success'); // ╠message.Delete_Success⇒刪除成功╣
  785. }
  786. else {
  787. showMsg(i18next.t("message.Delete_Failed"), 'error'); // ╠message.Delete_Failed⇒刪除失敗╣
  788. }
  789. }
  790. }
  791. else {
  792. showMsg(i18next.t("message.Delete_Failed"), 'error'); // ╠message.Delete_Failed⇒刪除失敗╣
  793. }
  794. });
  795. }
  796. else {
  797. return $.Deferred().resolve().promise();
  798. }
  799. };
  800. /**
  801. * 刪除代辦
  802. * @param {String} sourseid 代辦id
  803. */
  804. w.DelTask = function (sourseid) {
  805. return CallAjax(ComFn.W_Com, ComFn.GetDel, {
  806. Params: {
  807. task: { SourceID: sourseid, OrgID: parent.top.OrgID }
  808. }
  809. });
  810. };
  811. /**
  812. * 用於表單序列化去除禁用欄位
  813. * @param {HTMLElement} dom 父層物件
  814. */
  815. w.reFreshInput = function (dom) {
  816. dom.find('[disabled]').each(function () {
  817. $(this).attr('hasdisable', 1).removeAttr('disabled');
  818. });
  819. };
  820. /**
  821. * 用於表單序列化恢復禁用欄位
  822. * @param {HTMLElement} dom 父層物件
  823. */
  824. w.reSetInput = function (dom) {
  825. dom.find('[hasdisable]').each(function () {
  826. $(this).removeAttr('hasdisable').prop('disabled', true);
  827. });
  828. };
  829. /**
  830. * 用於表單序列化恢復禁用欄位
  831. * @param {HTMLElement} dom 要禁用的物件標籤
  832. * @param {HTMLElement} notdom 不要禁用的物件標籤
  833. */
  834. w.disableInput = function (dom, notdom, bdisabled) {
  835. bdisabled = (bdisabled === undefined || bdisabled === null) ? true : bdisabled;
  836. dom = dom.find(':input,select-one,select,checkbox,radio,textarea');
  837. if (notdom) {
  838. dom = dom.not(notdom);
  839. }
  840. dom.each(function () {
  841. $(this).prop('disabled', bdisabled);
  842. });
  843. };
  844. /**
  845. * 序列化form表單
  846. * @param {HTMLElement} form 表單form物件
  847. * @param {String} type 傳回類型
  848. * @return {Object Or String} 表單資料
  849. */
  850. w.getFormSerialize = function (form, type) {
  851. var formdata = {};
  852. reFreshInput(form);
  853. if (type) {
  854. formdata = form.serializeJSON();
  855. }
  856. else {
  857. formdata = form.serializeObject();
  858. }
  859. reSetInput(form);
  860. return formdata;
  861. };
  862. /**
  863. * 參數添加修改人/時間創建人/時間
  864. * @param {Object} data 表單資料
  865. * @param {String} type 是否是修改
  866. * @return {Object} data 表單資料
  867. */
  868. w.packParams = function (data, type) {
  869. data.ModifyUser = parent.top.UserInfo.MemberID;
  870. data.ModifyDate = new Date().formate('yyyy/MM/dd HH:mm');
  871. if (!type) {
  872. data.CreateUser = data.ModifyUser;
  873. data.CreateDate = data.ModifyDate;
  874. }
  875. return data;
  876. };
  877. /**
  878. * 移除null項目
  879. * @param {Object} data 表單資料
  880. * @return {Object} data 表單資料
  881. */
  882. w.removeNull = function (data) {
  883. var dataNew = {};
  884. if (data instanceof (Object)) {
  885. for (var o in data) {
  886. if (data[o] !== null) {
  887. dataNew[o] = data[o];
  888. }
  889. }
  890. }
  891. return dataNew;
  892. };
  893. /**
  894. * 取得Url參數
  895. * @param {String} name 取得部分的名稱 例如輸入"Action"就能取到"Add"之類參數
  896. * @return {String}參數值
  897. */
  898. w.getUrlParam = function (name) {
  899. var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //構造一個含有目標參數的正則表達式對象
  900. var r = w.location.search.substr(1).match(reg); //匹配目標參數
  901. if (r != null) return unescape(r[2]); return null; //返回參數值
  902. };
  903. /**
  904. * 對網址路徑進行編碼
  905. * @param {String} url 要編碼的url或路徑
  906. * @return {String} 編碼後的url或路徑
  907. */
  908. w.encodeURL = function (url) {
  909. return encodeURIComponent(url).replace(/\'/g, "%27").replace(/\!/g, "%21").replace(/\(/g, "%28").replace(/\)/g, "%29");
  910. };
  911. /**
  912. * 對網址路徑進行解碼
  913. * @param {String} url 要解碼的url或路徑
  914. * @return {String} 解碼後的url或路徑
  915. */
  916. w.decodeURL = function (url) {
  917. return decodeURIComponent(url);
  918. };
  919. /**
  920. * 透過代號或名稱快速查詢人員
  921. * @param {String} set 要移出数据的jquery對象
  922. * @param {String} get 要移入数据的jquery對象
  923. */
  924. w.optionListMove = function (set, get) {
  925. var size = set.find("option").size();
  926. var selsize = set.find("option:selected").size();
  927. if (size > 0 && selsize > 0) {
  928. set.find("option:selected").each(function () {
  929. $(this).prependTo(get);
  930. });
  931. }
  932. };
  933. /**
  934. * select options 排序
  935. * @param {String} set 要排序的select
  936. * @param {String} ordertype 正序還是倒序
  937. */
  938. w.optionListOrder = function (set, ordertype) {
  939. var size = set.find("option").size(),
  940. select = set.find("option:selected"),
  941. selsize = select.size();
  942. if (size > 0 && selsize > 0) {
  943. var firstsel = set.find("option:selected:first"),
  944. lastsel = set.find("option:selected:last")
  945. if (ordertype) {
  946. if (firstsel.prev().length > 0) {
  947. firstsel.prev().before(select);
  948. }
  949. }
  950. else {
  951. if (lastsel.next().length > 0) {
  952. lastsel.next().after(select);
  953. }
  954. }
  955. }
  956. };
  957. /**
  958. * select options 排序
  959. * @param {String} set 要排序的select
  960. * @param {String} ordertype 正序還是倒序
  961. */
  962. w.optionListSearch = function (set, get, input) {
  963. //給左邊的每一項添加title效果
  964. $('option', set).attr('title', function () {
  965. return this.innerHTML;
  966. });
  967. //給右邊的每一項添加title效果
  968. $('option', get).attr('title', function () {
  969. return this.innerHTML;
  970. });
  971. var tempValue = set.html(), //儲存初始listbox值
  972. searchtxt = '';
  973. $.each(set.find('option'), function () {
  974. if ($(this).val() + $(this).text() != 'undefined') {
  975. searchtxt += $(this).val() + '|' + $(this).text() + ',';
  976. }
  977. });
  978. //給搜尋按鈕註冊事件
  979. input.off('keyup').on('keyup', function () {
  980. var sWord = this.value;
  981. set.empty();
  982. if (sWord != "") {
  983. $.each(searchtxt.split(','), function (key, val) {
  984. if (val.toLowerCase().indexOf(sWord.toLowerCase()) >= 0) {
  985. var setValue = val.split('|')[0];
  986. var setText = val.split('|')[1];
  987. set.append('<option value="' + setValue + '">' + setText + '</option>')
  988. }
  989. });
  990. }
  991. else {
  992. set.html(tempValue); //搜尋欄位為空返還初始值(全部人員)
  993. }
  994. //移除右邊存在的值
  995. if (get.html() != '') {
  996. $.each(get.find('option'), function () {
  997. set.find('option[value=' + $(this).val().replace(".", "\\.") + ']').remove();
  998. });
  999. }
  1000. });
  1001. };
  1002. /**
  1003. * 時間格式化處理
  1004. * @param {Date} date 日期時間
  1005. * @param {Boolean} type 格式日期 || 日期+時間
  1006. * @return {Boolean} 是否可傳回空
  1007. */
  1008. w.newDate = function (date, type, empty) {
  1009. var r = '';
  1010. if (date) {
  1011. if (typeof date == 'string') {
  1012. r = date.replace('T', ' ').replaceAll('-', '/');
  1013. if (r.indexOf(".") > -1) {
  1014. r = r.slice(0, r.indexOf("."));
  1015. }
  1016. }
  1017. else {
  1018. r = new Date(date);
  1019. }
  1020. r = new Date(r);
  1021. }
  1022. else {
  1023. if (!empty) {
  1024. r = new Date();
  1025. }
  1026. }
  1027. return r === '' ? '' : !type ? r.formate("yyyy/MM/dd HH:mm") : r.formate("yyyy/MM/dd");
  1028. };
  1029. /**
  1030. * 獲取html模版
  1031. * @param {String} sUrl 模版路徑
  1032. * @param {Boolean} bAsync 是否同步
  1033. */
  1034. w.getHtmlTmp = function (sUrl, bAsync) {
  1035. return $.ajax({
  1036. async: true,
  1037. url: sUrl,
  1038. success: function (html) {
  1039. if (typeof callback === 'function') {
  1040. callback(html);
  1041. }
  1042. }
  1043. });
  1044. };
  1045. /**
  1046. * 產生guid
  1047. * @param {Number} len 指定长度,比如guid(8, 16) // "098F4D35"
  1048. * @param {Number} radix 基数
  1049. * @return {String} guid
  1050. */
  1051. w.guid = function (len, radix) {
  1052. var buf = new Uint16Array(8),
  1053. cryptObj = w.crypto || w.msCrypto, // For IE11
  1054. s4 = function (num) {
  1055. var ret = num.toString(16);
  1056. while (ret.length < 4) {
  1057. ret = '0' + ret;
  1058. }
  1059. return ret;
  1060. };
  1061. cryptObj.getRandomValues(buf);
  1062. return s4(buf[0]) + s4(buf[1]) + '-' + s4(buf[2]) + '-' + s4(buf[3]) + '-' +
  1063. s4(buf[4]) + '-' + s4(buf[5]) + s4(buf[6]) + s4(buf[7]);
  1064. };
  1065. /**
  1066. * 產生隨機數
  1067. * @param {Number} len 指定长度,比如random(8)
  1068. * @return {String} rnd 亂數碼
  1069. */
  1070. rndnum = function (len) {
  1071. var rnd = "";
  1072. len = len || 10;
  1073. for (var i = 0; i < len; i++)
  1074. rnd += Math.floor(Math.random() * 10);
  1075. return rnd;
  1076. };
  1077. /**
  1078. * 添加提示Tips
  1079. * @param {HTMLElement} handle dom物件
  1080. */
  1081. w.addTips = function (handle) {
  1082. handle = (handle !== undefined) ? handle : $('[title]');
  1083. handle.each(function () {
  1084. var oTips = $(this);
  1085. if (oTips.attr('title') && oTips.attr('tooltips') !== 'Y') {
  1086. oTips.attr('tooltips', 'Y').jBox('Tooltip');
  1087. }
  1088. });
  1089. };
  1090. /**
  1091. * 停止冒泡行为时
  1092. * @param {HTMLElement} e 事件对象
  1093. */
  1094. w.stopBubble = function (e) {
  1095. //如果提供了事件对象,则这是一个非IE浏览器
  1096. if (e && e.stopPropagation)
  1097. //因此它支持W3C的stopPropagation()方法
  1098. e.stopPropagation();
  1099. else
  1100. //否则,我们需要使用IE的方式来取消事件冒泡
  1101. w.event.cancelBubble = true;
  1102. };
  1103. /**
  1104. * 阻止默认行为时
  1105. * @param {HTMLElement} e 事件对象
  1106. */
  1107. w.stopDefault = function (e) {
  1108. //阻止默认浏览器动作(W3C)
  1109. if (e && e.preventDefault)
  1110. e.preventDefault();
  1111. //IE中阻止函数器默认动作的方式
  1112. else
  1113. w.event.returnValue = false;
  1114. return false;
  1115. };
  1116. /**
  1117. * 獲取權限
  1118. * @param {String} programid 程式id
  1119. * @param {Function} 回調函數
  1120. * @return {Object} ajax 物件
  1121. */
  1122. w.getAuthority = function (programid, callback, cus, opt) {
  1123. var sTopMod = getTopMod(programid),
  1124. sAction = getUrlParam('Action') === null ? 'add' : getUrlParam('Action').toLowerCase();
  1125. return g_api.ConnectLite('Authorize', 'GetAuthorize',
  1126. {
  1127. ProgramID: programid,
  1128. TopModuleID: sTopMod
  1129. },
  1130. function (res) {
  1131. if (res.RESULT) {
  1132. var saAuthorize = res.DATA.rel,
  1133. saBtn = [],
  1134. oHasBtn = {},
  1135. oLastBtn = null,
  1136. initToolbar = function () {//等待 ToolBar(wedget)初始化ok后在執行,否則會報錯
  1137. $('#Toolbar').ToolBar({
  1138. btns: saBtn,
  1139. fncallback: callback || function () { }
  1140. });
  1141. transLang($('#Toolbar'));
  1142. },
  1143. delayInitToolbar = function () {
  1144. //initToolbar();
  1145. if ($.fn.ToolBar) {
  1146. initToolbar();
  1147. }
  1148. else {
  1149. delayInitToolbar();
  1150. }
  1151. };
  1152. $.each(saAuthorize, function (idx, roleright) {
  1153. if (roleright.AllowRight) {
  1154. var saRights = roleright.AllowRight.split('|');
  1155. $.each(saRights, function (e, btnright) {
  1156. var sBtn = $.trim(btnright);
  1157. if (oHasBtn[sBtn.toLowerCase()] === undefined) {
  1158. oHasBtn[sBtn.toLowerCase()] = sBtn;
  1159. }
  1160. });
  1161. }
  1162. });
  1163. if (!oHasBtn['upd']) {
  1164. delete oHasBtn.save;
  1165. delete oHasBtn.readd;
  1166. }
  1167. if (sAction === 'upd') {
  1168. delete oHasBtn.readd;
  1169. }
  1170. if (sAction === 'add') {
  1171. delete oHasBtn.del;
  1172. }
  1173. delete oHasBtn.upd;
  1174. delete oHasBtn.view;
  1175. for (var btnkey in oHasBtn) {
  1176. var oBtn = {};
  1177. oBtn.key = oHasBtn[btnkey];
  1178. if (btnkey === 'leave') {
  1179. oLastBtn = oBtn;
  1180. oLastBtn.hotkey = 'ctrl + l';
  1181. }
  1182. else {
  1183. switch (btnkey) {
  1184. case 'qry':
  1185. oBtn.hotkey = 'enter';
  1186. break;
  1187. case 'add':
  1188. oBtn.hotkey = 'ctrl + i';
  1189. break;
  1190. case 'readd':
  1191. oBtn.hotkey = 'ctrl + r';
  1192. break;
  1193. case 'save':
  1194. oBtn.hotkey = 'ctrl + s';
  1195. break;
  1196. case 'del':
  1197. oBtn.hotkey = 'ctrl + d';
  1198. break;
  1199. case 'clear':
  1200. oBtn.hotkey = 'ctrl + q';
  1201. break;
  1202. }
  1203. saBtn.push(oBtn);
  1204. }
  1205. }
  1206. if (cus) {
  1207. saBtn.push.apply(saBtn, cus);
  1208. }
  1209. if (oLastBtn) {
  1210. saBtn.push(oLastBtn);
  1211. }
  1212. delayInitToolbar();
  1213. let SpecialCse = 'InvoiceApplyForCustomer_View, InvoiceApplyForPersonal_View, BillChangeApply_View';
  1214. //button Ready 再執行
  1215. if (opt.PrgId.indexOf('_Upd') > -1 || SpecialCse.indexOf(opt.PrgId) > -1) {
  1216. if (sAction === 'Upd'.toLocaleLowerCase()) {//判斷當前頁面是否有人在操作
  1217. parent.top.msgs.server.checkEdit(opt.PrgId, sCheckId);
  1218. }
  1219. $('#form_main').find(':input,select').not('[data-type=select2]').change(function () {
  1220. if (!$(this).attr('data-trigger')) {
  1221. bRequestStorage = true;
  1222. }
  1223. });
  1224. setTimeout(function () {
  1225. $('#form_main').find('[data-type=select2]').change(function () {
  1226. if (!$(this).attr('data-trigger')) {
  1227. bRequestStorage = true;
  1228. }
  1229. });
  1230. }, 3000);
  1231. }
  1232. else {
  1233. if (opt.PrgId.indexOf('_Qry') > -1) {
  1234. parent.top.msgs.server.removeEditPrg(opt.PrgId.replace('_Qry', '_Upd'));//防止重複點擊首頁菜單導致之前編輯資料狀態無法移除
  1235. }
  1236. var oQueryBtn = $('#Toolbar_Qry');
  1237. if (oQueryBtn.length > 0) {
  1238. $('select').on('change', function (e, arg) {
  1239. //select2下拉單改變自動查詢
  1240. setTimeout(function () {
  1241. if (arg !== 'clear') {//清除動作(賦值)不查詢
  1242. $('#Toolbar_Qry').click();
  1243. }
  1244. }, 10);
  1245. });
  1246. $(':input[type="radio"],:input[type="checkbox"]').on('click', function (e, arg) {
  1247. //radio值改變自動查詢
  1248. if (arg !== 'clear') {//清除動作(賦值)不查詢
  1249. $('#Toolbar_Qry').click();
  1250. }
  1251. });
  1252. }
  1253. }
  1254. }
  1255. });
  1256. };
  1257. /**
  1258. * createPageTitle
  1259. * @param {String} programid 程式id
  1260. * @param {HTMLElement} handle 標有標籤
  1261. * @return {Object} ajax 物件
  1262. */
  1263. w.createPageTitle = function (programid, handle) {
  1264. if (!programid) { return; }
  1265. handle = handle || $('.page-title');
  1266. var saPrgList = g_db.GetItem('programList'),
  1267. sModTree = "",
  1268. saModTree = [],
  1269. setProgramPath = function (sModuleID) {
  1270. var oParent = getParentMod(sModuleID);
  1271. if (oParent.ModuleID) {
  1272. saModTree.unshift('<div class="ng-scope layout-row"> <a class="md-button" href="#"><span class="ng-binding ng-scope" data-i18n=common.' + oParent.ModuleID + '></span></a> <i class="fa fa-angle-right" aria-hidden="true"></i> </div>');
  1273. }
  1274. if (oParent.ParentID) {
  1275. setProgramPath(oParent.ParentID);
  1276. }
  1277. };
  1278. if (saPrgList == null || saPrgList === '') { return; }
  1279. var saProgramList = $.parseJSON(saPrgList);
  1280. var saProgram = $.grep(saProgramList, function (item) { return item.ModuleID === programid; });
  1281. if (saProgram.length === 0) { return; }
  1282. var oProgram = saProgram[0];
  1283. if (!oProgram.ParentID) { return; }
  1284. setProgramPath(oProgram.ParentID);
  1285. saModTree.push('<div class="ng-scope layout-row"> <a class="md-button" href="#"><span class="ng-binding ng-scope" data-i18n=common.' + oProgram.ModuleID + '></span></a> </div>');
  1286. sModTree = saModTree.join(''); //串起父層路徑名稱
  1287. return $.get(ComTmp.PageTitle).done(function (tmpl) {
  1288. $.templates({ tmpl: tmpl });
  1289. handle.html($.render.tmpl({ ProgramName: "common." + oProgram.ModuleID, showTable: parent.top.SysSet.TbShowOrHide, MainTableName: oProgram.MainTableName, ModTree: sModTree }));
  1290. transLang(handle);
  1291. if (navigator.userAgent.match(/mobile/i)) {
  1292. $('.ismobile').hide();
  1293. }
  1294. });
  1295. };
  1296. /**
  1297. * 產生下拉選單公用
  1298. * @param {Object} list datalist
  1299. * @param {String} id 顯示的id名稱
  1300. * @param {String} name 顯示的name名稱
  1301. * @param {Boolean} showid 是否顯示id
  1302. * @param {String} cusattr 客制化添加屬性
  1303. * @param {Boolean} isreapet 是否允許重複
  1304. * @return {String} option html
  1305. */
  1306. w.createOptions = function (list, id, name, showid, cusattr, isreapet) {
  1307. isreapet == isreapet || true;
  1308. list = list || [];
  1309. var Options = [],
  1310. originAry = [];
  1311. if (typeof list === 'number') {
  1312. var intNum = list;
  1313. while (list > 0) {
  1314. var svalue = intNum - list + 1;
  1315. svalue = $.trim(svalue);
  1316. Options.push($('<option />', {
  1317. value: svalue,
  1318. title: svalue,
  1319. html: svalue
  1320. }));
  1321. list--;
  1322. }
  1323. } else {
  1324. Options = [$('<option />', { value: '', html: '請選擇...' })];
  1325. var intCount = list.length;
  1326. if (intCount > 0) {
  1327. $.each(list, function (idx, obj) {
  1328. if (isreapet !== false || (originAry.indexOf($.trim(obj[id])) < 0 && isreapet === false)) {
  1329. var option = $('<option />', {
  1330. value: $.trim(obj[id]),
  1331. title: $.trim(obj[name]),
  1332. html: (showid ? $.trim(obj[id]) + '-' : '') + $.trim(obj[name])
  1333. });
  1334. if (cusattr) {
  1335. option.attr(cusattr, obj[cusattr]);
  1336. }
  1337. Options.push(option);
  1338. }
  1339. originAry.push($.trim(obj[id]));
  1340. });
  1341. }
  1342. }
  1343. return $('<div />').append(Options).html();
  1344. };
  1345. /**
  1346. * Radios公用
  1347. * @param {Object} list datalist
  1348. * @param {String} id 顯示的id名稱
  1349. * @param {String} name 顯示的name名稱
  1350. * @param {String} feilid 欄位ID
  1351. * @param {String} _id 客制化添加屬性
  1352. * @param {Boolean} showid 是否顯示id
  1353. * @param {Boolean} triggerattr 頁面加載後觸發change事件是否觸發提醒
  1354. * @return {String} sHtml Radios HTML
  1355. */
  1356. w.createRadios = function (list, id, name, feilid, _id, showid, triggerattr) {
  1357. list = list || [];
  1358. _id = _id || '';
  1359. triggerattr = triggerattr === false ? true : undefined;
  1360. var sHtml = '',
  1361. intCount = list.length;
  1362. if (intCount > 0) {
  1363. $.each(list, function (idx, obj) {
  1364. var sId = feilid + '_' + _id + '_' + idx,
  1365. inputradio = $('<input />', {
  1366. type: 'radio',
  1367. id: sId,
  1368. name: feilid,
  1369. 'data-trigger': triggerattr,
  1370. value: $.trim(obj[id])
  1371. }).attr('val', $.trim(obj[id]));
  1372. sHtml += '<label for="' + sId + '">' + inputradio[0].outerHTML + ((showid ? $.trim(obj[id]) + '-' : '') + $.trim(obj[name])) + "</label>";
  1373. });
  1374. }
  1375. return sHtml;
  1376. };
  1377. /**
  1378. * 產生CheckList公用
  1379. * @param {Object} list datalist
  1380. * @param {String} id 顯示的id名稱
  1381. * @param {String} name 顯示的name名稱
  1382. * @param {String} pmid 屬性id
  1383. * @param {String} _id id後邊擴展
  1384. * @return {String} sHtml CheckList HTML
  1385. */
  1386. w.createCheckList = function (list, id, name, pmid, _id) {
  1387. list = list || [];
  1388. var sHtml = '',
  1389. intCount = list.length;
  1390. if (intCount > 0) {
  1391. $.each(list, function (idx, obj) {
  1392. var inputradio = $('<input />', {
  1393. type: 'checkbox',
  1394. 'id': id + (_id === undefined ? '' : _id) + '_' + idx,
  1395. name: pmid + '[]',
  1396. value: $.trim(obj[id]),
  1397. 'class': 'input-mini'
  1398. });
  1399. sHtml += "<label for='" + id + (_id === undefined ? '' : _id) + '_' + idx + "' style='" + (intCount == idx + 1 ? '' : 'float:left;') + "padding-left: 10px'>" + inputradio[0].outerHTML + $.trim(obj[name]) + "</label>";
  1400. });
  1401. }
  1402. return sHtml;
  1403. };
  1404. /**
  1405. * 自適應
  1406. */
  1407. w.onresize = function () {
  1408. var sHeight = $('body').height();
  1409. if ($('#main-wrapper').length) {
  1410. $('#main-wrapper').css('min-height', (sHeight - 88) + 'px');
  1411. }
  1412. setContentHeight();
  1413. };
  1414. w.fnframesize = function (down) {
  1415. var pTar = null;
  1416. if (d.getElementById) {
  1417. pTar = d.getElementById(down);
  1418. }
  1419. else {
  1420. eval('pTar = ' + down + ';');
  1421. }
  1422. if (pTar && !w.opera) {
  1423. pTar.style.display = "block"
  1424. if (pTar.contentDocument && pTar.contentDocument.body.offsetHeight) {
  1425. //ns6 syntax
  1426. var iBody = $(d.body).outerHeight(true);
  1427. pTar.height = iBody - 125;
  1428. pTar.width = pTar.contentDocument.body.scrollWidth + 20;
  1429. }
  1430. else if (pTar.Document && pTar.Document.body.scrollHeight) {
  1431. pTar.height = pTar.Document.body.scrollHeight;
  1432. pTar.width = pTar.Document.body.scrollWidth;
  1433. }
  1434. }
  1435. };
  1436. w.setContentHeight = function () {
  1437. var fnIframeResize = function (h) {
  1438. var aryIframe = d.getElementsByTagName("iframe");
  1439. if (aryIframe == null) return;
  1440. for (var i = 0; i < aryIframe.length; i++) {
  1441. var Iframe = aryIframe[i];
  1442. if (Iframe.id.indexOf('ueditor_') === -1) {
  1443. Iframe.height = h;
  1444. }
  1445. }
  1446. },
  1447. content = $('.page-inner'),
  1448. pageContentHeight = $(d.body).outerHeight(true) - 110;
  1449. fnIframeResize(pageContentHeight);
  1450. };
  1451. /**
  1452. * 取得自定義json值
  1453. * @param {Object} json json對象
  1454. * @param {Object} name json鍵值
  1455. * @return {String} sLast 最終要獲取的對應的鍵值對的值
  1456. */
  1457. w.getJsonVal = function (json, name) {
  1458. var sLast = json,
  1459. saName = name.split('_');
  1460. for (var i = 0; i < saName.length; i++) {
  1461. if (!sLast[saName[i]]) {
  1462. sLast = '';
  1463. break;
  1464. }
  1465. sLast = sLast[saName[i]];
  1466. }
  1467. return sLast;
  1468. };
  1469. /**
  1470. * 緩存查詢條件
  1471. * @param {HTMLElement}form 表單物件
  1472. */
  1473. w.cacheQueryCondition = function (form) {
  1474. var oForm = form || $('#form_main'),
  1475. sPrgId = w.sProgramId || getProgramId() || '',
  1476. oPm = {};
  1477. w.bToFirstPage = false;
  1478. if (sPrgId) {
  1479. if (!parent[sPrgId + '_query']) {
  1480. parent[sPrgId + '_query'] = {};
  1481. }
  1482. if (typeof oForm === 'number') {
  1483. parent[sPrgId + '_query'].pageidx = oForm;
  1484. }
  1485. else {
  1486. var oQueryPm_Old = clone(parent[sPrgId + '_query']);
  1487. oPm = getFormSerialize(oForm);
  1488. for (var key in oPm) {
  1489. parent[sPrgId + '_query'][key] = oPm[key];
  1490. }
  1491. for (var key in oQueryPm_Old) {
  1492. if (key !== 'pageidx' && parent[sPrgId + '_query'][key] !== oQueryPm_Old[key]) {
  1493. w.bToFirstPage = true;
  1494. break;
  1495. }
  1496. }
  1497. }
  1498. }
  1499. };
  1500. /**
  1501. * 設定表單值
  1502. * @param {HTMLElement} form 表單
  1503. * @param {Object} json json對象
  1504. */
  1505. w.setFormVal = function (form, json) {
  1506. form.find('[name]').each(function () {
  1507. var sId = this.id,
  1508. sName = (this.name) ? this.name.replace('[]', '') : '',
  1509. sType = this.type,
  1510. sValue = json[sName] || getJsonVal(json, sId) || '';
  1511. if (sValue) {
  1512. switch (sType) {
  1513. case 'text':
  1514. case 'email':
  1515. case 'url':
  1516. case 'number':
  1517. case 'range':
  1518. case 'date':
  1519. case 'search':
  1520. case 'color':
  1521. case 'textarea':
  1522. case 'select-one':
  1523. case 'select':
  1524. case 'hidden':
  1525. var sDataType = $(this).attr("data-type");
  1526. if (sDataType && sDataType == 'pop') {
  1527. var sVal_Name = json[sName + 'Name'] || sValue;
  1528. $(this).attr("data-value", sValue);
  1529. if (sVal_Name) $(this).val(sVal_Name);
  1530. }
  1531. else {
  1532. if ($(this).hasClass('date-picker')) {
  1533. sValue = newDate(sValue, 'date');
  1534. }
  1535. else if ($(this).hasClass('date-picker') || $(this).hasClass('datetime-picker') || $(this).hasClass('date')) {
  1536. sValue = newDate(sValue);
  1537. }
  1538. if (sValue) $(this).val(sValue);
  1539. $(this).data('old', sValue);
  1540. if (sDataType && sDataType == 'int' && sValue) {
  1541. $(this).attr('data-value', sValue.toString().replace(/[^\d.]/g, ''));
  1542. }
  1543. }
  1544. if (sDataType === 'select2') {
  1545. $(this).trigger("change", 'setval');
  1546. }
  1547. break;
  1548. case 'checkbox':
  1549. if (typeof sValue == 'object') {
  1550. if (sValue.indexOf(this.value) > -1) {
  1551. this.checked = sValue;
  1552. }
  1553. }
  1554. else {
  1555. this.checked = typeof sValue == 'string' ? sValue == this.value : sValue;
  1556. }
  1557. $.uniform && $.uniform.update($(this).prop("checked", this.checked));
  1558. break;
  1559. case 'radio':
  1560. this.checked = this.value === sValue;
  1561. $.uniform && $.uniform.update($(this).prop("checked", this.checked));
  1562. break;
  1563. }
  1564. if ((sId == 'ModifyUser' || sId == 'CreateUser') && 'select-one'.indexOf(this.type) === -1) {
  1565. $(this).text(sValue);
  1566. }
  1567. if ((sId == 'ModifyUserName' || sId == 'CreateUserName') && 'select-one'.indexOf(this.type) === -1) {
  1568. $(this).text(sValue);
  1569. }
  1570. else if (sId == 'ModifyDate' || sId == 'CreateDate') {
  1571. $(this).text(newDate(sValue));
  1572. }
  1573. }
  1574. });
  1575. };
  1576. /**
  1577. * 去掉字符串中所有空格
  1578. * @param {String} str 要處理的字串
  1579. * @param {String} is_global (包括中间空格,需要设置第2个参数为:g)
  1580. * @return {String} result 處理後的字串
  1581. */
  1582. w.Trim = function (str, is_global) {
  1583. var result;
  1584. result = str.replace(/(^\s+)|(\s+$)/g, "");
  1585. if (is_global.toLowerCase() == "g") {
  1586. result = result.replace(/\s/g, "");
  1587. }
  1588. return result;
  1589. };
  1590. /**
  1591. * 通過id獲取name
  1592. * @return {Object} ajax 物件
  1593. */
  1594. w.setNameById = function () {
  1595. var saRequests = [];
  1596. $('[data-source]').each(function () {
  1597. var that = this,
  1598. sValue = $(that).attr('data-value') || $(that).data('value') || that.value || $(that).text(),
  1599. saSource = $(this).data('source').split('.'),
  1600. oParam = {},
  1601. oEnty = {};
  1602. if (saSource.length > 2) {
  1603. oEnty[saSource[1]] = sValue;
  1604. oParam[saSource[0]] = oEnty;
  1605. oParam.OrgID = parent.top.OrgID;
  1606. if (sValue) {
  1607. saRequests.push(CallAjax(ComFn.W_Com, ComFn.GetOne, {
  1608. Type: '',
  1609. Params: oParam
  1610. }, function (res) {
  1611. if (res.d) {
  1612. var oInfo = $.parseJSON(res.d);
  1613. if (that.type === 'text') {
  1614. $(that).val(oInfo[saSource[2]] || oInfo[saSource[3]]);
  1615. }
  1616. else {
  1617. $(that).text(oInfo[saSource[2]] || oInfo[saSource[3]]);
  1618. }
  1619. }
  1620. }));
  1621. }
  1622. }
  1623. });
  1624. return $.whenArray(saRequests);
  1625. };
  1626. /**
  1627. * 只能輸入數字
  1628. * @param {HTMLElement} $input 實例化物件
  1629. * @param {Number} decimal 幾位小數
  1630. * @param {Boolean} minus 是否支持負數
  1631. */
  1632. w.moneyInput = function ($input, decimal, minus) {
  1633. if ($input.length > 0) {
  1634. var oNum = new FormatNumber();
  1635. $input.each(function () {
  1636. var sValue = this.value,
  1637. sNewStr = '';
  1638. for (var i = 0; i < sValue.length; i++) {
  1639. if (!isNaN(sValue[i])) {
  1640. sNewStr += sValue[i];
  1641. }
  1642. }
  1643. this.value == sNewStr;
  1644. oNum.init({ trigger: $(this), decimal: decimal || 0, minus: minus || false });
  1645. });
  1646. }
  1647. };
  1648. //當前頁面所有Control的初始值
  1649. w.aryCurrentPageValueTmp = new Array();
  1650. /**
  1651. * 儲存當前頁面的值
  1652. * @param: {String} sMainId 要清除區塊的父層Id
  1653. */
  1654. w.getPageVal = function (sMainId) {
  1655. aryCurrentPageValueTmp = [];
  1656. //判斷傳入的樣式是否不存在或者等於空的情況
  1657. var oHandle = (sMainId !== undefined) ? $('#' + sMainId) : ($('#searchbar').length > 0 ? $('#searchbar') : $('.page-inner'));
  1658. //儲存畫面值
  1659. oHandle.find(':input', 'textarea', 'select').each(function () {
  1660. var ctl = {}; //實例化對象
  1661. ctl.ID = this.id;
  1662. ctl.Type = this.type;
  1663. switch (this.type) {
  1664. case 'text':
  1665. case 'email':
  1666. case 'url':
  1667. case 'number':
  1668. case 'range':
  1669. case 'date':
  1670. case 'search':
  1671. case 'color':
  1672. case 'password':
  1673. case 'hidden':
  1674. case 'textarea':
  1675. ctl.Value = $(this).val();
  1676. break;
  1677. case 'checkbox':
  1678. case 'radio':
  1679. ctl.Checked = this.checked;
  1680. break;
  1681. case 'select-multiple':
  1682. case 'select-one':
  1683. case 'select':
  1684. ctl.Value = $(this).val() || '';
  1685. ctl.Html = $(this).html();
  1686. break;
  1687. }
  1688. aryCurrentPageValueTmp.push(ctl);
  1689. });
  1690. };
  1691. /**
  1692. * 清除畫面值
  1693. * @param {String} flag 是否為查詢清空查詢頁面須全部清空不保留原值
  1694. */
  1695. w.clearPageVal = function () {
  1696. var oPageDataTmp = aryCurrentPageValueTmp,
  1697. oQueryBtn = $('#Toolbar_Qry');
  1698. for (var i = 0; i < oPageDataTmp.length; i++) {
  1699. var ctl = oPageDataTmp[i],
  1700. curInput = $("#" + ctl.ID),
  1701. ctlParent = curInput.parent();
  1702. try {
  1703. switch (ctl.Type) {
  1704. case 'text':
  1705. case 'email':
  1706. case 'url':
  1707. case 'number':
  1708. case 'range':
  1709. case 'date':
  1710. case 'search':
  1711. case 'color':
  1712. case 'password':
  1713. case 'hidden':
  1714. case 'textarea':
  1715. curInput.val(ctl.Value);
  1716. break;
  1717. case 'checkbox':
  1718. case 'radio':
  1719. curInput[0].checked = ctl.Checked;
  1720. $.uniform && $.uniform.update(curInput.prop("checked", curInput[0].checked));
  1721. break;
  1722. case 'select-multiple':
  1723. case 'select-one':
  1724. case 'select':
  1725. if (ctl.Html) {
  1726. curInput.html(ctl.Html)
  1727. }
  1728. curInput.val(ctl.Value);
  1729. if (curInput.attr('data-type') === 'select2') {
  1730. curInput.trigger('change', 'clear');
  1731. }
  1732. break;
  1733. }
  1734. } catch (e) {
  1735. alert(e);
  1736. }
  1737. }
  1738. if (oQueryBtn.length > 0) {
  1739. $('#Toolbar_Qry').click();
  1740. }
  1741. };
  1742. /**
  1743. * 監聽css文件是否加在完畢
  1744. * @param: {Function} fn 回調函數
  1745. * @param: {Object} link css標籤
  1746. */
  1747. w.cssReady = function (fn, link) {
  1748. var t = d.createStyleSheet,
  1749. r = t ? 'rules' : 'cssRules',
  1750. s = t ? 'styleSheet' : 'sheet',
  1751. l = d.getElementsByTagName('link');
  1752. // passed link or last link node
  1753. link || (link = l[l.length - 1]);
  1754. function check() {
  1755. try {
  1756. return link && link[s] && link[s][r] && link[s][r][0];
  1757. } catch (e) {
  1758. return false;
  1759. }
  1760. }
  1761. (function poll() {
  1762. check() && setTimeout(fn, 0) || setTimeout(poll, 100);
  1763. })();
  1764. };
  1765. /**
  1766. * 克隆对象
  1767. * @param: {Object} obj 被轉換對象
  1768. * @return{Object} o 新對象
  1769. */
  1770. w.clone = function (obj) {
  1771. var o, i, j, k;
  1772. if (typeof (obj) != "object" || obj === null) return obj;
  1773. if (obj instanceof (Array)) {
  1774. o = [];
  1775. i = 0; j = obj.length;
  1776. for (; i < j; i++) {
  1777. if (typeof (obj[i]) == "object" && obj[i] != null) {
  1778. o[i] = arguments.callee(obj[i]);
  1779. }
  1780. else {
  1781. o[i] = obj[i];
  1782. }
  1783. }
  1784. }
  1785. else {
  1786. o = {};
  1787. for (i in obj) {
  1788. if (typeof (obj[i]) == "object" && obj[i] != null) {
  1789. o[i] = arguments.callee(obj[i]);
  1790. }
  1791. else {
  1792. o[i] = obj[i];
  1793. }
  1794. }
  1795. }
  1796. return o;
  1797. };
  1798. /**
  1799. * 公用初始函數
  1800. * @param: {Object} opt 程式ID
  1801. * @return{Object} ajax 物件
  1802. */
  1803. w.commonInit = function (opt) {
  1804. if (navigator.userAgent.match(/mobile/i)) {
  1805. $('.ismobile').hide();
  1806. }
  1807. if ($("#tabs").length > 0) {
  1808. $("#tabs").tabs().find('li').on('click', function () {
  1809. var that = this;
  1810. $('#tabs>ul>li').removeClass('active');
  1811. $(this).addClass('active');
  1812. if (opt.tabClick) {
  1813. opt.tabClick(that);
  1814. }
  1815. });
  1816. }
  1817. setTimeout(function () {
  1818. if ($.datepicker !== undefined) {
  1819. $.datepicker.regional['zh-TW'] = {
  1820. dayNames: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
  1821. dayNamesMin: ["日", "一", "二", "三", "四", "五", "六"],
  1822. monthNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
  1823. monthNamesShort: ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"],
  1824. prevText: "上月",
  1825. nextText: "次月",
  1826. weekHeader: "週",
  1827. showMonthAfterYear: true, // True if the year select precedes month, false for month then year//設置是否在面板的头部年份后面显示月份
  1828. dateFormat: "yy/mm/dd"
  1829. };
  1830. $.datepicker.setDefaults($.datepicker.regional["zh-TW"]);
  1831. }
  1832. //註冊日曆控件(不含時間)
  1833. if ($('.date-picker').length > 0) {
  1834. $('.date-picker').datepicker({
  1835. changeYear: true,
  1836. changeMonth: true,
  1837. altFormat: 'yyyy/MM/dd',
  1838. onSelect: function (r, e) {
  1839. if (typeof opt.onSelect === 'function') {
  1840. opt.onSelect(r, e);
  1841. }
  1842. },
  1843. afterInject: function (r, e) { }
  1844. });
  1845. }
  1846. //註冊日曆控件(含時間)
  1847. if ($('.datetime-picker').length > 0) {
  1848. $('.datetime-picker').each(function () {
  1849. var iHour = ($(this).attr('hour') || 9) * 1,
  1850. iMinute = ($(this).attr('minute') || 0) * 1,
  1851. iStepMinute = ($(this).attr('stepminute') || 15) * 1;
  1852. $(this).datetimepicker({
  1853. changeYear: true,
  1854. changeMonth: true,
  1855. altFormat: 'yyyy/MM/dd',
  1856. timeFormat: 'HH:mm',
  1857. //minDateTime: new Date(),
  1858. //maxDateTime: new Date().dateAdd('d', 5),
  1859. //defaultValue: newDate(null, true) + ' 08:00',
  1860. hour: iHour,
  1861. minute: iMinute,
  1862. stepMinute: iStepMinute,
  1863. hourGrid: 6,
  1864. minuteGrid: 15,
  1865. onSelect: function (r, e) {
  1866. if (typeof opt.onSelect === 'function') {
  1867. opt.onSelect(r, e);
  1868. }
  1869. },
  1870. afterInject: function (r, e) { }
  1871. });
  1872. });
  1873. }
  1874. //註冊日曆控件(時間)
  1875. if ($('.time-picker').length > 0) {
  1876. $('.time-picker').each(function () {
  1877. var iHour = ($(this).attr('hour') || 9) * 1,
  1878. iMinute = ($(this).attr('minute') || 0) * 1;
  1879. $(this).timepicker({
  1880. timeFormat: 'HH:mm',
  1881. hour: iHour,
  1882. minute: iMinute,
  1883. minuteGrid: 30,
  1884. stepMinute: 30,
  1885. onSelect: function (r, e) {
  1886. if (typeof opt.onSelect == 'function') {
  1887. opt.onSelect(r, e);
  1888. }
  1889. }
  1890. });
  1891. });
  1892. }
  1893. }, 1000);
  1894. //註冊顏色控件
  1895. if ($('.color-picker').length > 0) {
  1896. $('.color-picker').each(function () {
  1897. var that = this;
  1898. $(that).spectrum({
  1899. color: "#000000",
  1900. //flat: true,
  1901. showInput: true,
  1902. className: "full-spectrum",
  1903. showInitial: true,
  1904. showPalette: true,
  1905. showSelectionPalette: true,
  1906. maxPaletteSize: 10,
  1907. preferredFormat: "hex",
  1908. hide: function (color) {
  1909. $(that).val(color.toHexString());
  1910. },
  1911. palette: [
  1912. ["rgb(0, 0, 0)", "rgb(67, 67, 67)", "rgb(102, 102, 102)",
  1913. "rgb(204, 204, 204)", "rgb(217, 217, 217)", "rgb(255, 255, 255)",
  1914. "rgb(152, 0, 0)", "rgb(255, 0, 0)", "rgb(255, 153, 0)", "rgb(255, 255, 0)", "rgb(0, 255, 0)"],
  1915. ["rgb(230, 184, 175)", "rgb(244, 204, 204)", "rgb(252, 229, 205)", "rgb(255, 242, 204)", "rgb(217, 234, 211)",
  1916. "rgb(208, 224, 227)", "rgb(201, 218, 248)", "rgb(207, 226, 243)", "rgb(217, 210, 233)", "rgb(234, 209, 220)",
  1917. "rgb(221, 126, 107)", "rgb(234, 153, 153)", "rgb(249, 203, 156)", "rgb(255, 229, 153)", "rgb(182, 215, 168)",
  1918. "rgb(162, 196, 201)", "rgb(164, 194, 244)", "rgb(159, 197, 232)", "rgb(180, 167, 214)", "rgb(213, 166, 189)",
  1919. "rgb(204, 65, 37)", "rgb(224, 102, 102)", "rgb(246, 178, 107)", "rgb(255, 217, 102)", "rgb(147, 196, 125)",
  1920. "rgb(118, 165, 175)", "rgb(109, 158, 235)", "rgb(111, 168, 220)", "rgb(142, 124, 195)", "rgb(194, 123, 160)",
  1921. "rgb(166, 28, 0)", "rgb(204, 0, 0)", "rgb(230, 145, 56)", "rgb(241, 194, 50)", "rgb(106, 168, 79)",
  1922. "rgb(69, 129, 142)", "rgb(60, 120, 216)", "rgb(61, 133, 198)", "rgb(103, 78, 167)", "rgb(166, 77, 121)",
  1923. "rgb(91, 15, 0)", "rgb(102, 0, 0)", "rgb(120, 63, 4)", "rgb(127, 96, 0)", "rgb(39, 78, 19)",
  1924. "rgb(12, 52, 61)", "rgb(28, 69, 135)", "rgb(7, 55, 99)", "rgb(32, 18, 77)", "rgb(76, 17, 48)",
  1925. "rgb(0, 255, 255)", "rgb(74, 134, 232)", "rgb(0, 0, 255)", "rgb(153, 0, 255)", "rgb(255, 0, 255)"]
  1926. ]
  1927. });
  1928. });
  1929. }
  1930. //if ($('textarea').length > 0) {
  1931. // $('textarea').each(function () {
  1932. // autoTextarea(this);//文本框textarea根据输入内容自适应高度
  1933. // });
  1934. //}
  1935. //keyTab(); //註冊按Tab鍵下移
  1936. keyInput(); //註冊欄位管控
  1937. select2Init();//初始化select2
  1938. uniformInit();//表單美化
  1939. if (opt.GoTop) {
  1940. goTop();
  1941. }
  1942. if (opt.PrgId) {
  1943. var sLang = g_ul.GetLang() || 'zh-TW';
  1944. setLang(sLang);//翻譯多語系
  1945. getPageVal(); //緩存頁面值,用於清除
  1946. createPageTitle(opt.PrgId).done(function () {//創建Header
  1947. if (opt.SearchBar) {
  1948. var iSearchBox_h = $('#searchbar').height(),
  1949. oSlideUpDown = $('<i>', {
  1950. class: 'fa fa-arrow-up slide-box',
  1951. click: function () {
  1952. if ($(this).hasClass('fa-arrow-up')) {
  1953. $(this).removeClass('fa-arrow-up').addClass('fa-arrow-down');
  1954. oSearchBox.slideUp();
  1955. oGrid.height = (oGrid.dfheight.replace('px', '') * 1 + iSearchBox_h) + 'px';
  1956. }
  1957. else {
  1958. $(this).removeClass('fa-arrow-down').addClass('fa-arrow-up');
  1959. oSearchBox.slideDown();
  1960. oGrid.height = oGrid.dfheight;
  1961. }
  1962. $("#jsGrid").jsGrid("refresh");
  1963. //調整Grid slimscrollDIV高度,保證和實際高度一致
  1964. var oGridBox = $('.jsgrid-grid-body.slimscroll');
  1965. oGridBox.parent().css('height', oGridBox.css('height'));
  1966. }
  1967. }),
  1968. oSlideDiv = $('<div>', { class: 'col-sm-12 up-down-go' }).append(oSlideUpDown),
  1969. oSearchBox = $('#searchbar').after(oSlideDiv);
  1970. }
  1971. });
  1972. reSetQueryPm(opt.PrgId); //恢復之前查詢條件
  1973. //加載按鈕權限
  1974. return getAuthority(opt.PrgId, opt.ButtonHandler, opt.Buttons, opt);
  1975. }
  1976. };
  1977. /**
  1978. * select2特殊化處理
  1979. * @param {Object} $d select2控制項
  1980. */
  1981. w.select2Init = function ($d) {
  1982. var select2 = $d === undefined ? $('select[data-type=select2]') : $d.find('select[data-type=select2]');
  1983. //註冊客制化選單
  1984. if (select2.length > 0) {
  1985. select2.each(function () {
  1986. if ($(this).find('option').length > 0 && !$(this).attr('data-hasselect2')) {
  1987. $(this).select2().attr('data-hasselect2', true);
  1988. $(this).next().after($(this));
  1989. }
  1990. });
  1991. }
  1992. };
  1993. /**
  1994. * select2特殊化處理
  1995. * @param {Object} $d 表單控制項
  1996. */
  1997. w.uniformInit = function ($d) {
  1998. //var checkBox = $("input[type=checkbox]:not(.switchery), input[type=radio]:not(.no-uniform)");
  1999. var checkBox = $("input[type=radio]:not(.no-uniform)");
  2000. if ($d) {
  2001. checkBox = $d.find("input[type=radio]:not(.no-uniform)");
  2002. }
  2003. if (checkBox.length > 0) {
  2004. checkBox.each(function () {
  2005. $(this).uniform();
  2006. });
  2007. };
  2008. };
  2009. /**
  2010. * 小數後n
  2011. * @param {HTMLElement} e
  2012. * @param {Object} that 控制項
  2013. * @param {Number} len 小數點後位數
  2014. */
  2015. w.keyIntp = function (e, that, len) {
  2016. if (e.keyCode != 8 && e.keyCode != 37 && e.keyCode != 39 && e.keyCode != 46) {
  2017. var reg = {
  2018. 1: /^(\-)*(\d+)\.(\d).*$/,
  2019. 2: /^(\-)*(\d+)\.(\d\d).*$/,
  2020. 3: /^(\-)*(\d+)\.(\d\d\d).*$/
  2021. };
  2022. that.value = that.value.replace(/[^\d.-]/g, ''); //清除“数字”和“.”以外的字符
  2023. that.value = that.value.replace(/\.{2,}/g, '.'); //只保留第一个. 清除多余的
  2024. that.value = that.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
  2025. that.value = that.value.replace(reg[len], '$1$2.$3');//只能输入n个小数
  2026. if (that.value.indexOf(".") < 0 && that.value !== "" && that.value !== "-") {//以上已经过滤,此处控制的是如果没有小数点,首位不能为类似于 01、02的金额&&不是“-”
  2027. if (that.value.indexOf("-") === 0) {//如果是負數
  2028. that.value = 0 - parseFloat(that.value.replace('-', ''));
  2029. }
  2030. else {
  2031. that.value = parseFloat(that.value);
  2032. }
  2033. //that.value = fMoney(that.value, 2);
  2034. }
  2035. }
  2036. };
  2037. /**
  2038. * 離開事件
  2039. */
  2040. w.pageLeave = function () {
  2041. var ToLeave = function () {
  2042. parent.top.openPageTab(sQueryPrgId);
  2043. parent.top.msgs.server.removeEditPrg(sProgramId);
  2044. };
  2045. //當被lock住,不儲存任何資料,直接離開。
  2046. if (parent.bLockDataForm0430 !== undefined)
  2047. ToLeave();
  2048. if (bRequestStorage) {
  2049. layer.confirm(i18next.t('message.HasDataTosave'), {//╠message.HasDataTosave⇒尚有資料未儲存,是否要儲存?╣
  2050. icon: 3,
  2051. title: i18next.t('common.Tips'),// ╠message.Tips⇒提示╣
  2052. btn: [i18next.t('common.Yes'), i18next.t('common.No')] // ╠message.Yes⇒是╣ ╠common.No⇒否╣
  2053. }, function (index) {
  2054. layer.close(index);
  2055. bLeavePage = true;
  2056. $('#Toolbar_Save').click();
  2057. }, function () {
  2058. ToLeave();
  2059. });
  2060. return false;
  2061. }
  2062. ToLeave();
  2063. };
  2064. /**
  2065. * 目的Html定位到某個位置
  2066. * @param {Object} goto 要定位的html jquery對象
  2067. * @param {Number} h 誤差值
  2068. */
  2069. w.goToJys = function (goto, h) {
  2070. $("html,body").animate({ scrollTop: goto.offset().top + (h || 0) }, 500);//定位到...
  2071. };
  2072. /**
  2073. * 目的設置滾動條
  2074. */
  2075. w.slimScroll = function (h, c) {
  2076. if ($.fn.slimScroll) {
  2077. var option = {
  2078. allowPageScroll: true,
  2079. color: '#ee7624',
  2080. opacity: 1
  2081. };
  2082. if (h) {
  2083. option.height = h;
  2084. }
  2085. if (c) {
  2086. option.reduce = c;
  2087. }
  2088. $('.slimscroll').slimscroll(option);
  2089. }
  2090. };
  2091. /**
  2092. * 目的回頂端
  2093. */
  2094. w.goTop = function () {
  2095. var oTop = $('<div>', {
  2096. class: 'gotop',
  2097. html: '<img src="../../images/gotop_1.png" />', click: function () {
  2098. return $("body,html").animate({ scrollTop: 0 }, 120), !1;
  2099. }
  2100. });
  2101. $('body').append(oTop.hide());//添加置頂控件
  2102. $(d).on('scroll', function () {
  2103. var h = ($(d).height(), $(this).scrollTop()),
  2104. toolbarH = -45,
  2105. toolbarCss = {};
  2106. h > 0 ? oTop.fadeIn() : oTop.fadeOut();
  2107. if (h > 35) {
  2108. toolbarH = h - 80;
  2109. $('#Toolbar').addClass('toolbar-float').removeClass('toolbar-fix');
  2110. }
  2111. else {
  2112. $('#Toolbar').removeClass('toolbar-float').addClass('toolbar-fix');
  2113. }
  2114. $('#Toolbar').css('margin-top', toolbarH + 'px');
  2115. });
  2116. };
  2117. /**
  2118. * 目的獲取當前瀏覽器
  2119. */
  2120. w.getExplorer = function () {
  2121. var sExplorerName = '',
  2122. explorer = w.navigator.userAgent;
  2123. //ie
  2124. if (explorer.indexOf("MSIE") >= 0) {
  2125. sExplorerName = 'ie';
  2126. }
  2127. //firefox
  2128. else if (explorer.indexOf("Firefox") >= 0) {
  2129. sExplorerName = 'firefox';
  2130. }
  2131. //Chrome
  2132. else if (explorer.indexOf("Chrome") >= 0) {
  2133. sExplorerName = 'chrome';
  2134. }
  2135. //Opera
  2136. else if (explorer.indexOf("Opera") >= 0) {
  2137. sExplorerName = 'opera';
  2138. }
  2139. //Safari
  2140. else if (explorer.indexOf("Safari") >= 0) {
  2141. sExplorerName = 'safari';
  2142. }
  2143. };
  2144. /**
  2145. * 目的異動模式點擊資料行彈出編輯按鈕
  2146. * @param {String} prgid 程式id
  2147. * @param {String} params 參數
  2148. */
  2149. w.goToEdit = function (prgid, params) {
  2150. parent.top.layer.open({
  2151. type: 1,
  2152. title: false,
  2153. area: ['100px', '70px'],//寬度
  2154. shade: 0.75,//遮罩
  2155. shadeClose: true,//╠common.Edit⇒編輯╣
  2156. content: '<div class="pop-box">\
  2157. <button type="button" data-i18n="common.Edit" id="RowEdit" class="btn-custom green">編輯</button>\
  2158. </div>',
  2159. success: function (layero, idx) {
  2160. layero.find('#RowEdit').click(function () {
  2161. parent.top.openPageTab(prgid, params);
  2162. parent.top.layer.close(idx);
  2163. });
  2164. }
  2165. });
  2166. };
  2167. /**
  2168. * 目的:回覆查詢條件
  2169. */
  2170. w.reSetQueryPm = function (programid) {
  2171. var oQueryPm = parent[programid + '_query'];
  2172. if (oQueryPm) {
  2173. setFormVal($('#form_main'), oQueryPm);
  2174. if (oQueryPm.pageidx) {
  2175. w.QueryPageidx = oQueryPm.pageidx;
  2176. }
  2177. }
  2178. };
  2179. /**
  2180. * 金額控件文本實例化
  2181. * @param {Number} s需要转换的金额;
  2182. * @param {Number} n 保留几位小数
  2183. * @param {String} istw 幣別
  2184. */
  2185. w.fMoney = function (s, n, istw) {
  2186. var p = n > 0 && n <= 20 ? n : 2;
  2187. if (istw && istw === 'NTD') {
  2188. s = Math.round(s);
  2189. }
  2190. s = parseFloat(((s || 0) + "").replace(/[^\d\.-]/g, "")).toFloat(p) + "";
  2191. var l = s.split(".")[0].split("").reverse(),
  2192. r = s.split(".")[1] || Array(n + 1).join(0),
  2193. t = "";
  2194. for (i = 0; i < l.length; i++) {
  2195. t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
  2196. }
  2197. return t.split("").reverse().join("") + (n === 0 ? '' : "." + r);
  2198. };
  2199. /**
  2200. * 金額控件
  2201. * @param {Number} s 需要转换的金额;
  2202. * @return {String} istw 浮動數字
  2203. */
  2204. w.fnRound = function (s, istw) {
  2205. let RoundingPoint = 0;
  2206. if (istw && istw === 'NTD') {
  2207. RoundingPoint = 0;
  2208. }
  2209. else {
  2210. RoundingPoint = 2;
  2211. }
  2212. let Result = parseFloat((s).toFixed(RoundingPoint));
  2213. return Result;
  2214. };
  2215. /**
  2216. * 目的:input文本處理
  2217. */
  2218. w.keyInput = function () {
  2219. //只能輸入數字
  2220. if ($('[data-keyint]').length > 0) {
  2221. $('[data-keyint]').on('keyup blur', function (e) {
  2222. this.value = this.value.replace(/\D/g, '');
  2223. });
  2224. }
  2225. //只能输入英文
  2226. if ($('[data-keyeng]').length > 0) {
  2227. $('[data-keyeng]').on('keyup blur', function (e) {
  2228. this.value = this.value.replace(/[^a-zA-Z]/g, '');
  2229. });
  2230. }
  2231. //只能输入中文
  2232. if ($('[data-keyeng]').length > 0) {
  2233. $('[data-keyeng]').on('keyup blur', function (e) {
  2234. this.value = this.value.replace(/[^\u4E00-\u9FA5]/g, '');
  2235. });
  2236. }
  2237. //只能輸入數字和“-”,(手機/電話)
  2238. if ($('[data-keytelno]').length > 0) {
  2239. $('[data-keytelno]').on('keyup blur', function (e) {
  2240. if (e.keyCode != 8 && e.keyCode != 37 && e.keyCode != 39 && e.keyCode != 46) {
  2241. this.value = this.value.replace(/[^0-9\-\+\#\ ]/g, '');
  2242. }
  2243. });
  2244. }
  2245. //只能輸入數字和“-,+,#”
  2246. if ($('[data-keyintg]').length > 0) {
  2247. $('[data-keyintg]').on('keyup blur', function (e) {
  2248. this.value = this.value.replace(/[^0-9\-\+\#]/g, '');
  2249. });
  2250. }
  2251. //只能輸入數字和“.”,小數點後保留一位有效數字
  2252. if ($('[data-keyintp1]').length > 0) {
  2253. $('[data-keyintp1]').on('keyup blur', function (e) {
  2254. keyIntp(e, this, 1);
  2255. });
  2256. }
  2257. //只能輸入數字和“.”,小數點後保留兩位有效數字
  2258. if ($('[data-keyintp2]').length > 0) {
  2259. $('[data-keyintp2]').on('keyup blur', function (e) {
  2260. keyIntp(e, this, 2);
  2261. });
  2262. }
  2263. //只能輸入數字和“.”,小數點後保留三位有效數字
  2264. if ($('[data-keyintp3]').length > 0) {
  2265. $('[data-keyintp3]').on('keyup blur', function (e) {
  2266. keyIntp(e, this, 3);
  2267. });
  2268. }
  2269. //只允许输入英文
  2270. if ($('[data-keyeng]').length > 0) {
  2271. $('[data-keyeng]').on('keyup blur', function (e) {
  2272. this.value = this.value.replace(/[^\a-\z\A-\Z]/g, '');
  2273. });
  2274. }
  2275. //只能输入英文字母和数字,不能输入中文
  2276. if ($('[data-keyinteng]').length > 0) {
  2277. $('[data-keyinteng]').on('keyup blur', function (e) {
  2278. this.value = this.value.replace(/[^0-9\a-\z\A-\Z\_]/g, '');
  2279. });
  2280. }
  2281. //只能输入字母和汉字
  2282. if ($('[data-keycneng]').length > 0) {
  2283. $('[data-keycneng]').on('keyup blur', function (e) {
  2284. this.value = this.value.replace(/[/d]/g, '');
  2285. });
  2286. }
  2287. //帳號輸入規則
  2288. if ($('[data-keymemberid]').length > 0) {
  2289. $('[data-keymemberid]').on('keyup blur', function (e) {
  2290. this.value = this.value.replace(/[^\w\.\/]/ig, '');
  2291. });
  2292. }
  2293. //限制inout輸入長度
  2294. if ($('[_maxlength]').length > 0) {
  2295. $('[_maxlength]').each(function () {
  2296. var iPromiseLen = $(this).attr('_maxlength');
  2297. if (iPromiseLen) {
  2298. $(this).on('input propertychange', function () {
  2299. var sVal = this.value,
  2300. sVal_New = '',
  2301. iLen = 0,
  2302. i = 0;
  2303. for (; i < sVal.length; i++) {
  2304. if ((sVal.charCodeAt(i) & 0xff00) != 0) {
  2305. iLen++;
  2306. }
  2307. iLen++;
  2308. if (iLen > iPromiseLen * 1) {
  2309. this.value = sVal_New;
  2310. break;
  2311. }
  2312. sVal_New += sVal[i];
  2313. }
  2314. });
  2315. }
  2316. });
  2317. }
  2318. };
  2319. /**
  2320. * 文本框根据输入内容自适应高度
  2321. * @param {HTMLElement} elem 输入框元素
  2322. * @param {Number} extra 设置光标与输入框保持的距离(默认0)
  2323. * @param {Number} maxHeight 设置最大高度(可选)
  2324. */
  2325. w.autoTextarea = function (elem, extra, maxHeight) {
  2326. extra = extra || 0;
  2327. var isFirefox = !!d.getBoxObjectFor || 'mozInnerScreenX' in w,
  2328. isOpera = !!w.opera && !!w.opera.toString().indexOf('Opera'),
  2329. addEvent = function (type, callback) {
  2330. elem.addEventListener ?
  2331. elem.addEventListener(type, callback, false) :
  2332. elem.attachEvent('on' + type, callback);
  2333. },
  2334. getStyle = elem.currentStyle ? function (name) {
  2335. var val = elem.currentStyle[name];
  2336. if (name === 'height' && val.search(/px/i) !== 1) {
  2337. var rect = elem.getBoundingClientRect();
  2338. return rect.bottom - rect.top -
  2339. parseFloat(getStyle('paddingTop')) -
  2340. parseFloat(getStyle('paddingBottom')) + 'px';
  2341. };
  2342. return val;
  2343. } : function (name) {
  2344. return getComputedStyle(elem, null)[name];
  2345. },
  2346. minHeight = parseFloat(getStyle('height'));
  2347. elem.style.resize = 'none';
  2348. var change = function () {
  2349. var scrollTop, height,
  2350. padding = 0,
  2351. style = elem.style;
  2352. if (elem._length === elem.value.length) return;
  2353. elem._length = elem.value.length;
  2354. if (!isFirefox && !isOpera) {
  2355. padding = parseInt(getStyle('paddingTop')) + parseInt(getStyle('paddingBottom'));
  2356. };
  2357. scrollTop = d.body.scrollTop || d.documentElement.scrollTop;
  2358. elem.style.height = minHeight + 'px';
  2359. if (elem.scrollHeight > minHeight) {
  2360. if (maxHeight && elem.scrollHeight > maxHeight) {
  2361. height = maxHeight - padding;
  2362. style.overflowY = 'auto';
  2363. } else {
  2364. height = elem.scrollHeight - padding;
  2365. style.overflowY = 'hidden';
  2366. };
  2367. style.height = height + extra + 'px';
  2368. scrollTop += parseInt(style.height) - elem.currHeight;
  2369. d.body.scrollTop = scrollTop;
  2370. d.documentElement.scrollTop = scrollTop;
  2371. elem.currHeight = parseInt(style.height);
  2372. };
  2373. };
  2374. addEvent('propertychange', change);
  2375. addEvent('input', change);
  2376. addEvent('focus', change);
  2377. change();
  2378. };
  2379. /**
  2380. * 驗證郵箱格式
  2381. * @param {String} email 输入的值
  2382. * @return{Boolean}
  2383. */
  2384. w.isEmail = function (email) {
  2385. 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)) {
  2386. return true;
  2387. }
  2388. else {
  2389. return false;
  2390. }
  2391. };
  2392. /**
  2393. * input改變後立即更新當前資料
  2394. * @param {HTMLElement} inputs 输入框元素
  2395. * @param {Object} data 當前資料
  2396. */
  2397. w.inputChange = function (inputs, data) {
  2398. inputs.on('change', function () {
  2399. var that = this,
  2400. sId = $(that).attr('data-id');
  2401. data[sId] = $(that).val();
  2402. });
  2403. };
  2404. if (!w.browser) {
  2405. var userAgent = navigator.userAgent.toLowerCase(), uaMatch;
  2406. w.browser = {}
  2407. /**
  2408. * 判断是否为ie
  2409. */
  2410. function isIE() {
  2411. return ("ActiveXObject" in w);
  2412. }
  2413. /**
  2414. * 判断是否为谷歌浏览器
  2415. */
  2416. if (!uaMatch) {
  2417. uaMatch = userAgent.match(/chrome\/([\d.]+)/);
  2418. if (uaMatch != null) {
  2419. w.browser['name'] = 'chrome';
  2420. w.browser['version'] = uaMatch[1];
  2421. }
  2422. }
  2423. /**
  2424. * 判断是否为火狐浏览器
  2425. */
  2426. if (!uaMatch) {
  2427. uaMatch = userAgent.match(/firefox\/([\d.]+)/);
  2428. if (uaMatch != null) {
  2429. w.browser['name'] = 'firefox';
  2430. w.browser['version'] = uaMatch[1];
  2431. }
  2432. }
  2433. /**
  2434. * 判断是否为opera浏览器
  2435. */
  2436. if (!uaMatch) {
  2437. uaMatch = userAgent.match(/opera.([\d.]+)/);
  2438. if (uaMatch != null) {
  2439. w.browser['name'] = 'opera';
  2440. w.browser['version'] = uaMatch[1];
  2441. }
  2442. }
  2443. /**
  2444. * 判断是否为Safari浏览器
  2445. */
  2446. if (!uaMatch) {
  2447. uaMatch = userAgent.match(/safari\/([\d.]+)/);
  2448. if (uaMatch != null) {
  2449. w.browser['name'] = 'safari';
  2450. w.browser['version'] = uaMatch[1];
  2451. }
  2452. }
  2453. /**
  2454. * 最后判断是否为IE
  2455. */
  2456. if (!uaMatch) {
  2457. if (userAgent.match(/msie ([\d.]+)/) != null) {
  2458. uaMatch = userAgent.match(/msie ([\d.]+)/);
  2459. w.browser['name'] = 'ie';
  2460. w.browser['version'] = uaMatch[1];
  2461. } else {
  2462. /**
  2463. * IE10
  2464. */
  2465. if (isIE() && !!d.attachEvent && (function () { "use strict"; return !this; }())) {
  2466. w.browser['name'] = 'ie';
  2467. w.browser['version'] = '10';
  2468. }
  2469. /**
  2470. * IE11
  2471. */
  2472. if (isIE() && !d.attachEvent) {
  2473. w.browser['name'] = 'ie';
  2474. w.browser['version'] = '11';
  2475. }
  2476. }
  2477. }
  2478. /**
  2479. * 注册判断方法
  2480. */
  2481. if (!$.isIE) {
  2482. $.extend({
  2483. isIE: function () {
  2484. return (w.browser.name == 'ie');
  2485. }
  2486. });
  2487. }
  2488. if (!$.isChrome) {
  2489. $.extend({
  2490. isChrome: function () {
  2491. return (w.browser.name == 'chrome');
  2492. }
  2493. });
  2494. }
  2495. if (!$.isFirefox) {
  2496. $.extend({
  2497. isFirefox: function () {
  2498. return (w.browser.name == 'firefox');
  2499. }
  2500. });
  2501. }
  2502. if (!$.isOpera) {
  2503. $.extend({
  2504. isOpera: function () {
  2505. return (w.browser.name == 'opera');
  2506. }
  2507. });
  2508. }
  2509. if (!$.isSafari) {
  2510. $.extend({
  2511. isSafari: function () {
  2512. return (w.browser.name == 'safari');
  2513. }
  2514. });
  2515. }
  2516. }
  2517. /**
  2518. * 取得host
  2519. * @return {String} host Url
  2520. */
  2521. function gethost() {
  2522. var g_ServerUrl = location.origin + '/';
  2523. if (!w.location.origin) {
  2524. g_ServerUrl = w.location.protocol + "//" + w.location.hostname + (w.location.port ? ':' + w.location.port : '');
  2525. }
  2526. return g_ServerUrl;
  2527. }
  2528. /**
  2529. * 取得頂層模組
  2530. * @param {String} programId 程式id
  2531. * @return {String} 頂層模組ID
  2532. */
  2533. function getTopMod(programId) {
  2534. var sTopMod = '',
  2535. saProgramList = g_db.GetDic('programList') || [],
  2536. oProgram = Enumerable.From(saProgramList).Where(function (item) { return item.ModuleID === programId; }).First(),
  2537. getParent = function (modid) {
  2538. var oMod = getParentMod(modid);
  2539. if (oMod.ParentID) {
  2540. getParent(oMod.ParentID);
  2541. }
  2542. else {
  2543. sTopMod = oMod.ModuleID
  2544. }
  2545. };
  2546. getParent(oProgram.ParentID);
  2547. return sTopMod;
  2548. }
  2549. /**
  2550. *取得程式所在模組的父層模組
  2551. * @param {String} modid 模組id
  2552. * @return {Object} oParent 模組對象
  2553. */
  2554. function getParentMod(modid) {
  2555. var saProgramList = g_db.GetDic('programList') || [];
  2556. var oParent = Enumerable.From(saProgramList).Where(function (item) { return (item.ModuleID == modid && item.FilePath == '#'); }).First();
  2557. return oParent;
  2558. }
  2559. /**
  2560. * 动态加载js文件的程序
  2561. * @param {String} filename css or js 路徑
  2562. * @param {String} filetype 類型js or css
  2563. */
  2564. function loadjscssfile(filename, filetype) {
  2565. if (filetype == "js") {
  2566. var script = d.createElement('script');
  2567. script.setAttribute("type", "text/javascript");
  2568. script.setAttribute("src", filename);
  2569. } else if (filetype == "css") {
  2570. var script = d.createElement('link');
  2571. script.setAttribute("rel", "stylesheet");
  2572. script.setAttribute("type", "text/css");
  2573. script.setAttribute("href", filename);
  2574. }
  2575. if (typeof script !== "undefined") {
  2576. $("head").append(script);
  2577. }
  2578. }
  2579. function onStart(e) {
  2580. showWaiting(typeof IsWaiting === 'string' ? IsWaiting : undefined);
  2581. }
  2582. function onStop(e) {
  2583. closeWaiting();
  2584. setTimeout(function () { IsWaiting = null; }, 3000);
  2585. }
  2586. $(d).ajaxStart(onStart).ajaxStop(onStop);//.ajaxSuccess(onSuccess);
  2587. })(jQuery, window, document);
  2588. /**
  2589. * 日期添加屬性
  2590. * @param {String} type y:;q:季度;m:;w:星期;d:;h:小時;n:;s:;ms:毫秒;
  2591. * @param {Number} filetype 添加的數值
  2592. * @return {Date} r 新的時間
  2593. */
  2594. Date.prototype.dateAdd = function (type, num) {
  2595. var r = this,
  2596. k = { y: 'FullYear', q: 'Month', m: 'Month', w: 'Date', d: 'Date', h: 'Hours', n: 'Minutes', s: 'Seconds', ms: 'MilliSeconds' },
  2597. n = { q: 3, w: 7 };
  2598. eval('r.set' + k[type] + '(r.get' + k[type] + '()+' + ((n[type] || 1) * num) + ')');
  2599. return r;
  2600. }
  2601. /**
  2602. * 計算兩個日期的天數
  2603. * @param {Object} date 第二個日期;
  2604. * @return {Number} 時間差
  2605. */
  2606. Date.prototype.diff = function (date) {
  2607. return (this.getTime() - date.getTime()) / (24 * 60 * 60 * 1000);
  2608. }
  2609. /**
  2610. * 对Date的扩展 Date 转化为指定格式的String
  2611. * (M)(d)12小时(h)24小时(H)(m)(s)(E)季度(q) 可以用 1-2 个占位符
  2612. * (y)可以用 1-4 个占位符毫秒(S)只能用 1 个占位符( 1-3 位的数字)
  2613. * eg:
  2614. * (new Date()).formate("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
  2615. * (new Date()).formate("yyyy-MM-dd E HH:mm:ss") ==> 2009-03-10 20:09:04
  2616. * (new Date()).formate("yyyy-MM-dd EE hh:mm:ss") ==> 2009-03-10 周二 08:09:04
  2617. * (new Date()).formate("yyyy-MM-dd EEE hh:mm:ss") ==> 2009-03-10 星期二 08:09:04
  2618. * (new Date()).formate("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
  2619. */
  2620. Date.prototype.formate = function (fmt) {
  2621. var o = {
  2622. "M+": this.getMonth() + 1, //月份
  2623. "d+": this.getDate(), //日
  2624. "h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, //小时
  2625. "H+": this.getHours(), //小时
  2626. "m+": this.getMinutes(), //分
  2627. "s+": this.getSeconds(), //秒
  2628. "q+": Math.floor((this.getMonth() + 3) / 3), //季度
  2629. "S": this.getMilliseconds() //毫秒
  2630. };
  2631. var week = {
  2632. "0": "\u65e5",
  2633. "1": "\u4e00",
  2634. "2": "\u4e8c",
  2635. "3": "\u4e09",
  2636. "4": "\u56db",
  2637. "5": "\u4e94",
  2638. "6": "\u516d"
  2639. };
  2640. if (/(y+)/.test(fmt)) {
  2641. fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  2642. }
  2643. if (/(E+)/.test(fmt)) {
  2644. fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "\u661f\u671f" : "\u5468") : "") + week[this.getDay() + ""]);
  2645. }
  2646. for (var k in o) {
  2647. if (new RegExp("(" + k + ")").test(fmt)) {
  2648. fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  2649. }
  2650. }
  2651. return fmt;
  2652. }
  2653. /**
  2654. * 註冊全替換
  2655. * @param {String} s1 字串1
  2656. * @param {String} s2 字串2
  2657. */
  2658. String.prototype.replaceAll = function (s1, s2) {
  2659. return this.replace(new RegExp(s1, "gm"), s2);
  2660. }
  2661. /**
  2662. * 註冊金額添加三位一撇
  2663. */
  2664. String.prototype.toMoney = Number.prototype.toMoney = function () {
  2665. return this.toString().replace(/\d+?(?=(?:\d{3})+$)/g, function (s) {
  2666. return s + ',';
  2667. });
  2668. }
  2669. /**
  2670. * 数字四舍五入保留n位小数
  2671. */
  2672. String.prototype.toFloat = Number.prototype.toFloat = function (n) {
  2673. n = n ? parseInt(n) : 0;
  2674. var number = this;
  2675. if (n <= 0) return Math.round(number);
  2676. number = Math.round(number * Math.pow(10, n)) / Math.pow(10, n);
  2677. return number;
  2678. }
  2679. /**
  2680. * 百分数转小数
  2681. */
  2682. String.prototype.toPoint = function () {
  2683. return this.replace("%", "") / 100;
  2684. }
  2685. /**
  2686. * 小数转化为分数
  2687. */
  2688. String.prototype.toPercent = Number.prototype.toPercent = function () {
  2689. var percent = Number(this * 100).toFixed(1);
  2690. percent += "%";
  2691. return percent;
  2692. }
  2693. /**
  2694. * 刪除陣列內包含(undefined, null, 0, false, NaN and '')的資料
  2695. */
  2696. Array.prototype.clear = function () {
  2697. var newArray = [];
  2698. for (var i = 0; i < this.length; i++) {
  2699. if (this[i]) {
  2700. newArray.push(this[i]);
  2701. }
  2702. }
  2703. return newArray;
  2704. }
  2705. /**
  2706. * 在數組指定位置添加元素
  2707. * @param {Number} index 位置
  2708. * @param {Object} item 要添加的元素
  2709. */
  2710. Array.prototype.insert = function (index, item) {
  2711. this.splice(index, 0, item);
  2712. };
  2713. /**
  2714. * 刪除陣列內指定元素
  2715. */
  2716. Array.prototype.remove = function (val) {
  2717. var index = this.indexOf(val);
  2718. if (index > -1) {
  2719. this.splice(index, 1);
  2720. }
  2721. };
  2722. /**
  2723. * 方法陣列內等待
  2724. */
  2725. jQuery.whenArray = function (array) {
  2726. return jQuery.when.apply(this, array);
  2727. };