PageRenderTime 55ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 2ms

/jssource/src_files/include/javascript/sugar_3.js

https://github.com/BarnetikKoop/SuiteCRM
JavaScript | 5060 lines | 4047 code | 498 blank | 515 comment | 1317 complexity | 69577f9e441f2729ec6387e2843ecb88 MD5 | raw file
Possible License(s): AGPL-3.0, LGPL-2.1, MPL-2.0-no-copyleft-exception
  1. /*********************************************************************************
  2. * SugarCRM Community Edition is a customer relationship management program developed by
  3. * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
  4. * SuiteCRM is an extension to SugarCRM Community Edition developed by Salesagility Ltd.
  5. * Copyright (C) 2011 - 2014 Salesagility Ltd.
  6. *
  7. * This program is free software; you can redistribute it and/or modify it under
  8. * the terms of the GNU Affero General Public License version 3 as published by the
  9. * Free Software Foundation with the addition of the following permission added
  10. * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
  11. * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
  12. * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
  13. *
  14. * This program is distributed in the hope that it will be useful, but WITHOUT
  15. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  16. * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
  17. * details.
  18. *
  19. * You should have received a copy of the GNU Affero General Public License along with
  20. * this program; if not, see http://www.gnu.org/licenses or write to the Free
  21. * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  22. * 02110-1301 USA.
  23. *
  24. * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
  25. * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
  26. *
  27. * The interactive user interfaces in modified source and object code versions
  28. * of this program must display Appropriate Legal Notices, as required under
  29. * Section 5 of the GNU Affero General Public License version 3.
  30. *
  31. * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
  32. * these Appropriate Legal Notices must retain the display of the "Powered by
  33. * SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not
  34. * reasonably feasible for technical reasons, the Appropriate Legal Notices must
  35. * display the words "Powered by SugarCRM" and "Supercharged by SuiteCRM".
  36. ********************************************************************************/
  37. /**
  38. * Namespace for Sugar Objects
  39. */
  40. if (typeof(SUGAR) == "undefined") {
  41. SUGAR = {
  42. /**
  43. * Creates a namespace if it doesn't exist and then returns it.
  44. *
  45. * Note: this implementation only creates a top-level namespace. Extend this function if
  46. * multi-level namespaces are needed.
  47. * @param ns
  48. */
  49. namespace: function(ns) {
  50. SUGAR[ns] = SUGAR[ns] || {};
  51. return ((typeof SUGAR[ns] === "object") && (SUGAR[ns] !== null)) ? SUGAR[ns] : false;
  52. },
  53. /**
  54. * Add properties of an object to target object.
  55. * @param target
  56. * @param obj
  57. */
  58. append: function(target, obj) {
  59. for (var prop in obj) {
  60. if (obj[prop] !== void 0) target[prop] = obj[prop];
  61. }
  62. return target;
  63. }
  64. };
  65. }
  66. // Namespaces
  67. SUGAR.namespace("themes");
  68. SUGAR.namespace("tour");
  69. /**
  70. * Namespace for Homepage
  71. */
  72. SUGAR.namespace("sugarHome");
  73. /**
  74. * Namespace for Subpanel Utils
  75. */
  76. SUGAR.namespace("subpanelUtils");
  77. /**
  78. * AJAX status class
  79. */
  80. SUGAR.namespace("ajaxStatusClass");
  81. /**
  82. * Tab selector utils
  83. */
  84. SUGAR.namespace("tabChooser");
  85. /**
  86. * General namespace for Sugar utils
  87. */
  88. SUGAR.namespace("utils");
  89. SUGAR.namespace("savedViews");
  90. /**
  91. * Dashlet utils
  92. */
  93. SUGAR.namespace("dashlets");
  94. SUGAR.namespace("unifiedSearchAdvanced");
  95. SUGAR.namespace("searchForm");
  96. SUGAR.namespace("language");
  97. SUGAR.namespace("Studio");
  98. SUGAR.namespace("contextMenu");
  99. SUGAR.namespace("config");
  100. var nameIndex = 0;
  101. var typeIndex = 1;
  102. var requiredIndex = 2;
  103. var msgIndex = 3;
  104. var jstypeIndex = 5;
  105. var minIndex = 10;
  106. var maxIndex = 11;
  107. var altMsgIndex = 15;
  108. var compareToIndex = 7;
  109. var arrIndex = 12;
  110. var operatorIndex = 13;
  111. var callbackIndex = 16;
  112. var allowblank = 8;
  113. var validate = new Array();
  114. var maxHours = 24;
  115. var requiredTxt = 'Missing Required Field:';
  116. var invalidTxt = 'Invalid Value:';
  117. var secondsSinceLoad = 0;
  118. var alertsTimeoutId;
  119. var inputsWithErrors = new Array();
  120. var tabsWithErrors = new Array();
  121. var lastSubmitTime = 0;
  122. var alertList = new Array();
  123. var oldStartsWith = '';
  124. /**
  125. * @deprecated
  126. *
  127. * As of Sugar version 6.2.3 (MSIE Version 9) this function is deprecated. The preferred method is to use the
  128. * user agent check supplied by YUI to check for IE:
  129. *
  130. * for checking if a browser is IE in general : if(YAHOO.env.ua.ie) {...}
  131. *
  132. * or for checking specific versions: if (YAHOO.env.ua.ie >= 5.5 && YAHOO.env.ua.ie < 9) {...}
  133. *
  134. */
  135. function isSupportedIE() {
  136. var userAgent = navigator.userAgent.toLowerCase() ;
  137. // IE Check supports ActiveX controls
  138. if (userAgent.indexOf("msie") != -1 && userAgent.indexOf("mac") == -1 && userAgent.indexOf("opera") == -1) {
  139. var version = navigator.appVersion.match(/MSIE (\d+\.\d+)/)[1] ;
  140. if(version >= 5.5 && version < 10) {
  141. return true;
  142. } else {
  143. return false;
  144. }
  145. }
  146. }
  147. function checkMinSupported(c, s) {
  148. var current = c.split(".");
  149. var supported = s.split(".");
  150. for (var i in supported) {
  151. if (current[i] && parseInt(current[i]) > parseInt(supported[i])) return true;
  152. else if (current[i] && parseInt(current[i]) < parseInt(supported[i])) return false;
  153. }
  154. return true;
  155. }
  156. function checkMaxSupported(c, s) {
  157. var current = c.split(".");
  158. var supported = s.split(".");
  159. for (var i in supported) {
  160. if (current[i] && parseInt(current[i]) > parseInt(supported[i])) return false;
  161. else if (current[i] && parseInt(current[i]) < parseInt(supported[i])) return true;
  162. }
  163. return true;
  164. }
  165. SUGAR.isSupportedBrowser = function(){
  166. var supportedBrowsers = {
  167. msie : {min:9, max:11}, // IE 9, 11
  168. safari : {min:534}, // Safari 5.1
  169. mozilla : {min:23.0}, // Firefox 23.0
  170. chrome : {min:29} // Chrome 29
  171. };
  172. var current = String($.browser.version);
  173. var supported;
  174. if ($.browser.msie || (!(window.ActiveXObject) && "ActiveXObject" in window)){ // Internet Explorer
  175. supported = supportedBrowsers['msie'];
  176. }
  177. else if ($.browser.mozilla) { // Firefox
  178. supported = supportedBrowsers['mozilla'];
  179. }
  180. else {
  181. $.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase());
  182. if($.browser.chrome){ // Chrome
  183. current = navigator.userAgent.match(/Chrome\/(.*?) /)[1];
  184. supported = supportedBrowsers['chrome'];
  185. }
  186. else if($.browser.safari){ // Safari
  187. supported = supportedBrowsers['safari'];
  188. }
  189. }
  190. if (current && supported)
  191. return checkMinSupported(current, String(supported.min)) && (!supported.max || checkMaxSupported(current, String(supported.max)));
  192. else
  193. return false;
  194. }
  195. SUGAR.isIECompatibilityMode = function(){
  196. var agentStr = navigator.userAgent;
  197. var mode = false;
  198. if (agentStr.indexOf("MSIE 7.0") > -1 &&
  199. (agentStr.indexOf("Trident/5.0") > -1 || // IE9 Compatibility View
  200. agentStr.indexOf("Trident/4.0") > -1 // IE8 Compatibility View
  201. )
  202. )
  203. {
  204. mode = true;
  205. }
  206. return mode;
  207. }
  208. SUGAR.isIE = isSupportedIE();
  209. var isSafari = (navigator.userAgent.toLowerCase().indexOf('safari')!=-1);
  210. // escapes regular expression characters
  211. RegExp.escape = function(text) { // http://simon.incutio.com/archive/2006/01/20/escape
  212. if (!arguments.callee.sRE) {
  213. var specials = ['/', '.', '*', '+', '?', '|','(', ')', '[', ']', '{', '}', '\\'];
  214. arguments.callee.sRE = new RegExp('(\\' + specials.join('|\\') + ')', 'g');
  215. }
  216. return text.replace(arguments.callee.sRE, '\\$1');
  217. }
  218. function addAlert(type, name,subtitle, description,time, redirect) {
  219. var addIndex = alertList.length;
  220. alertList[addIndex]= new Array();
  221. alertList[addIndex]['name'] = name;
  222. alertList[addIndex]['type'] = type;
  223. alertList[addIndex]['subtitle'] = subtitle;
  224. alertList[addIndex]['description'] = replaceHTMLChars(description.replace(/<br>/gi, "\n"));
  225. alertList[addIndex]['time'] = time;
  226. alertList[addIndex]['done'] = 0;
  227. alertList[addIndex]['redirect'] = redirect;
  228. }
  229. function checkAlerts() {
  230. secondsSinceLoad += 1;
  231. var mj = 0;
  232. var alertmsg = '';
  233. for(mj = 0 ; mj < alertList.length; mj++) {
  234. if(alertList[mj]['done'] == 0) {
  235. if(alertList[mj]['time'] < secondsSinceLoad && alertList[mj]['time'] > -1 ) {
  236. alertmsg = alertList[mj]['type'] + ":" + alertList[mj]['name'] + "\n" +alertList[mj]['subtitle']+ "\n"+ alertList[mj]['description'] + "\n\n";
  237. alertList[mj]['done'] = 1;
  238. if(alertList[mj]['redirect'] == '') {
  239. alert(alertmsg);
  240. }
  241. else if(confirm(alertmsg)) {
  242. window.location = alertList[mj]['redirect'];
  243. }
  244. }
  245. }
  246. }
  247. alertsTimeoutId = setTimeout("checkAlerts()", 1000);
  248. }
  249. function toggleDisplay(id) {
  250. if(this.document.getElementById(id).style.display == 'none') {
  251. this.document.getElementById(id).style.display = '';
  252. if(this.document.getElementById(id+"link") != undefined) {
  253. this.document.getElementById(id+"link").style.display = 'none';
  254. }
  255. if(this.document.getElementById(id+"_anchor") != undefined)
  256. this.document.getElementById(id+"_anchor").innerHTML='[ - ]';
  257. }
  258. else {
  259. this.document.getElementById(id).style.display = 'none';
  260. if(this.document.getElementById(id+"link") != undefined) {
  261. this.document.getElementById(id+"link").style.display = '';
  262. }
  263. if(this.document.getElementById(id+"_anchor") != undefined)
  264. this.document.getElementById(id+"_anchor").innerHTML='[+]';
  265. }
  266. }
  267. function checkAll(form, field, value) {
  268. for (i = 0; i < form.elements.length; i++) {
  269. if(form.elements[i].name == field)
  270. form.elements[i].checked = value;
  271. }
  272. }
  273. function replaceAll(text, src, rep) {
  274. offset = text.toLowerCase().indexOf(src.toLowerCase());
  275. while(offset != -1) {
  276. text = text.substring(0, offset) + rep + text.substring(offset + src.length ,text.length);
  277. offset = text.indexOf( src, offset + rep.length + 1);
  278. }
  279. return text;
  280. }
  281. function addForm(formname) {
  282. validate[formname] = new Array();
  283. }
  284. function addToValidate(formname, name, type, required, msg) {
  285. if(typeof validate[formname] == 'undefined') {
  286. addForm(formname);
  287. }
  288. validate[formname][validate[formname].length] = new Array(name, type,required, msg);
  289. }
  290. // Bug #47961 Callback validator definition
  291. function addToValidateCallback(formname, name, type, required, msg, callback)
  292. {
  293. addToValidate(formname, name, type, required, msg);
  294. var iIndex = validate[formname].length -1;
  295. validate[formname][iIndex][jstypeIndex] = 'callback';
  296. validate[formname][iIndex][callbackIndex] = callback;
  297. }
  298. function addToValidateRange(formname, name, type,required, msg,min,max) {
  299. addToValidate(formname, name, type,required, msg);
  300. validate[formname][validate[formname].length - 1][jstypeIndex] = 'range';
  301. validate[formname][validate[formname].length - 1][minIndex] = min;
  302. validate[formname][validate[formname].length - 1][maxIndex] = max;
  303. }
  304. function addToValidateIsValidDate(formname, name, type, required, msg) {
  305. addToValidate(formname, name, type, required, msg);
  306. validate[formname][validate[formname].length - 1][jstypeIndex] = 'date';
  307. }
  308. function addToValidateIsValidTime(formname, name, type, required, msg) {
  309. addToValidate(formname, name, type, required, msg);
  310. validate[formname][validate[formname].length - 1][jstypeIndex] = 'time';
  311. }
  312. function addToValidateDateBefore(formname, name, type, required, msg, compareTo) {
  313. addToValidate(formname, name, type,required, msg);
  314. validate[formname][validate[formname].length - 1][jstypeIndex] = 'isbefore';
  315. validate[formname][validate[formname].length - 1][compareToIndex] = compareTo;
  316. }
  317. function addToValidateDateBeforeAllowBlank(formname, name, type, required, msg, compareTo, allowBlank) {
  318. addToValidate(formname, name, type,required, msg);
  319. validate[formname][validate[formname].length - 1][jstypeIndex] = 'isbefore';
  320. validate[formname][validate[formname].length - 1][compareToIndex] = compareTo;
  321. validate[formname][validate[formname].length - 1][allowblank] = allowBlank;
  322. }
  323. function addToValidateBinaryDependency(formname, name, type, required, msg, compareTo) {
  324. addToValidate(formname, name, type, required, msg);
  325. validate[formname][validate[formname].length - 1][jstypeIndex] = 'binarydep';
  326. validate[formname][validate[formname].length - 1][compareToIndex] = compareTo;
  327. }
  328. function addToValidateComparison(formname, name, type, required, msg, compareTo) {
  329. addToValidate(formname, name, type, required, msg);
  330. validate[formname][validate[formname].length - 1][jstypeIndex] = 'comparison';
  331. validate[formname][validate[formname].length - 1][compareToIndex] = compareTo;
  332. }
  333. function addToValidateIsInArray(formname, name, type, required, msg, arr, operator) {
  334. addToValidate(formname, name, type, required, msg);
  335. validate[formname][validate[formname].length - 1][jstypeIndex] = 'in_array';
  336. validate[formname][validate[formname].length - 1][arrIndex] = arr;
  337. validate[formname][validate[formname].length - 1][operatorIndex] = operator;
  338. }
  339. function addToValidateVerified(formname, name, type, required, msg, arr, operator) {
  340. addToValidate(formname, name, type, required, msg);
  341. validate[formname][validate[formname].length - 1][jstypeIndex] = 'verified';
  342. }
  343. function addToValidateLessThan(formname, name, type, required, msg, max, max_field_msg) {
  344. addToValidate(formname, name, type, required, msg);
  345. validate[formname][validate[formname].length - 1][jstypeIndex] = 'less';
  346. validate[formname][validate[formname].length - 1][maxIndex] = max;
  347. validate[formname][validate[formname].length - 1][altMsgIndex] = max_field_msg;
  348. }
  349. function addToValidateMoreThan(formname, name, type, required, msg, min) {
  350. addToValidate(formname, name, type, required, msg);
  351. validate[formname][validate[formname].length - 1][jstypeIndex] = 'more';
  352. validate[formname][validate[formname].length - 1][minIndex] = min;
  353. }
  354. function removeFromValidate(formname, name) {
  355. for(i = 0; i < validate[formname].length; i++)
  356. {
  357. if(validate[formname][i][nameIndex] == name)
  358. {
  359. validate[formname].splice(i--,1); // We subtract 1 from i since the slice removed an element, and we'll skip over the next item we scan
  360. }
  361. }
  362. }
  363. function checkValidate(formname, name) {
  364. if(validate[formname]){
  365. for(i = 0; i < validate[formname].length; i++){
  366. if(validate[formname][i][nameIndex] == name){
  367. return true;
  368. }
  369. }
  370. }
  371. return false;
  372. }
  373. var formsWithFieldLogic=null;
  374. var formWithPrecision =null;
  375. function addToValidateFieldLogic(formId,minFieldId, maxFieldId, defaultFieldId, lenFieldId,type,msg){
  376. this.formId = document.getElementById(formId);
  377. this.min=document.getElementById(minFieldId);
  378. this.max= document.getElementById(maxFieldId);
  379. this._default= document.getElementById(defaultFieldId);
  380. this.len = document.getElementById(lenFieldId);
  381. this.msg = msg;
  382. this.type= type;
  383. }
  384. //@params: formid- Dom id of the form containing the precision and float fields
  385. // valudId- Dom id of the field containing a float whose precision is to be checked.
  386. // precisionId- Dom id of the field containing precision value.
  387. function addToValidatePrecision(formId, valueId, precisionId){
  388. this.form = document.getElementById(formId);
  389. this.float = document.getElementById(valueId);
  390. this.precision = document.getElementById(precisionId);
  391. }
  392. //function checkLength(value, referenceValue){
  393. // return value
  394. //}
  395. function isValidPrecision(value, precision){
  396. value = trim(value.toString());
  397. if(precision == '')
  398. return true;
  399. if(value == '')
  400. return true;
  401. //#27021
  402. if( (precision == "0") ){
  403. if (value.indexOf(dec_sep)== -1){
  404. return true;
  405. }else{
  406. return false;
  407. }
  408. }
  409. //#27021 end
  410. if(value.charAt(value.length-precision-1) == num_grp_sep){
  411. if(value.substr(value.indexOf(dec_sep), 1)==dec_sep){
  412. return false;
  413. }
  414. return true;
  415. }
  416. var actualPrecision = value.substr(value.indexOf(dec_sep)+1, value.length).length;
  417. return actualPrecision == precision;
  418. }
  419. function toDecimal(original, precision) {
  420. precision = (precision == null) ? 2 : precision;
  421. num = Math.pow(10, precision);
  422. temp = Math.round(original*num)/num;
  423. if((temp * 100) % 100 == 0)
  424. return temp + '.00';
  425. if((temp * 10) % 10 == 0)
  426. return temp + '0';
  427. return temp
  428. }
  429. function isInteger(s) {
  430. if(typeof num_grp_sep != 'undefined' && typeof dec_sep != 'undefined')
  431. {
  432. s = unformatNumberNoParse(s, num_grp_sep, dec_sep).toString();
  433. }
  434. return /^[+-]?[0-9]*$/.test(s) ;
  435. }
  436. function isDecimal(s) {
  437. if (typeof s == "string" && s == "") // bug# 46530, this is required in order to
  438. return true; // not check empty decimal fields
  439. if(typeof num_grp_sep != 'undefined' && typeof dec_sep != 'undefined')
  440. {
  441. s = unformatNumberNoParse(s, num_grp_sep, dec_sep).toString();
  442. }
  443. return /^[+-]?[0-9]*\.?[0-9]*$/.test(s) ;
  444. }
  445. function isNumeric(s) {
  446. return isDecimal(s);
  447. }
  448. if (typeof date_reg_positions != "object") var date_reg_positions = {'Y': 1,'m': 2,'d': 3};
  449. if (typeof date_reg_format != "string") var date_reg_format = '([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})';
  450. function isDate(dtStr) {
  451. if(dtStr.length== 0) {
  452. return true;
  453. }
  454. // Check that we have numbers
  455. myregexp = new RegExp(date_reg_format)
  456. if(!myregexp.test(dtStr))
  457. return false
  458. m = '';
  459. d = '';
  460. y = '';
  461. var dateParts = dtStr.match(date_reg_format);
  462. for(key in date_reg_positions) {
  463. index = date_reg_positions[key];
  464. if(key == 'm') {
  465. m = dateParts[index];
  466. } else if(key == 'd') {
  467. d = dateParts[index];
  468. } else {
  469. y = dateParts[index];
  470. }
  471. }
  472. // Check that date is real
  473. var dd = new Date(y,m,0);
  474. // reject negative years
  475. if (y < 1)
  476. return false;
  477. // reject month less than 1 and greater than 12
  478. if (m > 12 || m < 1)
  479. return false;
  480. // reject days less than 1 or days not in month (e.g. February 30th)
  481. if (d < 1 || d > dd.getDate())
  482. return false;
  483. return true;
  484. }
  485. function getDateObject(dtStr) {
  486. if(dtStr.length== 0) {
  487. return true;
  488. }
  489. myregexp = new RegExp(date_reg_format)
  490. if(myregexp.exec(dtStr)) var dt = myregexp.exec(dtStr)
  491. else return false;
  492. var yr = dt[date_reg_positions['Y']];
  493. var mh = dt[date_reg_positions['m']];
  494. var dy = dt[date_reg_positions['d']];
  495. var dtar = dtStr.split(' ');
  496. var date1;
  497. if(typeof(dtar[1])!='undefined' && isTime(dtar[1])) {//if it is a timedate, we should make date1 to have time value
  498. var t1 = dtar[1].replace(/am/i,' AM');
  499. var t1 = t1.replace(/pm/i,' PM');
  500. //bug #37977: where time format 23.00 causes java script error
  501. t1=t1.replace(/\./, ':');
  502. date1 = new Date(mh+'/'+dy+'/'+yr+' '+t1);
  503. }
  504. else
  505. {
  506. date1 = new Date(mh+'/'+dy+'/'+yr);
  507. }
  508. if (isNaN(date1.valueOf())) {
  509. return null;
  510. }
  511. return date1;
  512. }
  513. function isBefore(value1, value2) {
  514. var d1 = getDateObject(value1);
  515. var d2 = getDateObject(value2);
  516. if(typeof(d2)=='boolean') {// if d2 is not set, we should let it pass, the d2 may not need to be set. the empty check should not be done here.
  517. return true;
  518. }
  519. return d2 >= d1;
  520. }
  521. function isValidEmail(emailStr) {
  522. if(emailStr.length== 0) {
  523. return true;
  524. }
  525. // cn: bug 7128, a period at the end of the string mangles checks. (switched to accept spaces and delimiters)
  526. var lastChar = emailStr.charAt(emailStr.length - 1);
  527. if(!lastChar.match(/[^\.]/i)) {
  528. return false;
  529. }
  530. //bug 40068, According to rules in page 6 of http://www.apps.ietf.org/rfc/rfc3696.html#sec-3,
  531. //first character of local part of an email address
  532. //should not be a period i.e. '.'
  533. var firstLocalChar=emailStr.charAt(0);
  534. if(firstLocalChar.match(/\./)){
  535. return false;
  536. }
  537. //bug 40068, According to rules in page 6 of http://www.apps.ietf.org/rfc/rfc3696.html#sec-3,
  538. //last character of local part of an email address
  539. //should not be a period i.e. '.'
  540. var pos=emailStr.lastIndexOf("@");
  541. var localPart = emailStr.substr(0, pos);
  542. var lastLocalChar=localPart.charAt(localPart.length - 1);
  543. if(lastLocalChar.match(/\./)){
  544. return false;
  545. }
  546. var reg = /@.*?;/g;
  547. var results;
  548. while ((results = reg.exec(emailStr)) != null) {
  549. var original = results[0];
  550. parsedResult = results[0].replace(';', '::;::');
  551. emailStr = emailStr.replace (original, parsedResult);
  552. }
  553. reg = /.@.*?,/g;
  554. while ((results = reg.exec(emailStr)) != null) {
  555. var original = results[0];
  556. //Check if we were using ; as a delimiter. If so, skip the commas
  557. if(original.indexOf("::;::") == -1) {
  558. var parsedResult = results[0].replace(',', '::;::');
  559. emailStr = emailStr.replace (original, parsedResult);
  560. }
  561. }
  562. // mfh: bug 15010 - more practical implementation of RFC 2822 from http://www.regular-expressions.info/email.html, modifed to accept CAPITAL LETTERS
  563. //if(!/[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?/.test(emailStr))
  564. // return false
  565. //bug 40068, According to rules in page 6 of http://www.apps.ietf.org/rfc/rfc3696.html#sec-3,
  566. //allowed special characters ! # $ % & ' * + - / = ? ^ _ ` . { | } ~ in local part
  567. var emailArr = emailStr.split(/::;::/);
  568. for (var i = 0; i < emailArr.length; i++) {
  569. var emailAddress = emailArr[i];
  570. if (trim(emailAddress) != '') {
  571. if(!/^\s*[\w.%+\-&'#!\$\*=\?\^_`\{\}~\/]+@([A-Z0-9-]+\.)*[A-Z0-9-]+\.[\w-]{2,}\s*$/i.test(emailAddress) &&
  572. !/^.*<[A-Z0-9._%+\-&'#!\$\*=\?\^_`\{\}~]+?@([A-Z0-9-]+\.)*[A-Z0-9-]+\.[\w-]{2,}>\s*$/i.test(emailAddress)) {
  573. return false;
  574. } // if
  575. }
  576. } // for
  577. return true;
  578. }
  579. function isValidPhone(phoneStr) {
  580. if(phoneStr.length== 0) {
  581. return true;
  582. }
  583. if(!/^[0-9\-\(\)\s]+$/.test(phoneStr))
  584. return false
  585. return true
  586. }
  587. function isFloat(floatStr) {
  588. if(floatStr.length== 0) {
  589. return true;
  590. }
  591. if(!(typeof(num_grp_sep)=='undefined' || typeof(dec_sep)=='undefined')) {
  592. floatStr = unformatNumberNoParse(floatStr, num_grp_sep, dec_sep).toString();
  593. }
  594. return /^(-)?[0-9\.]+$/.test(floatStr);
  595. }
  596. function isDBName(str) {
  597. if(str.length== 0) {
  598. return true;
  599. }
  600. // must start with a letter
  601. if(!/^[a-zA-Z][a-zA-Z\_0-9]*$/.test(str))
  602. return false
  603. return true
  604. }
  605. var time_reg_format = "[0-9]{1,2}\:[0-9]{2}";
  606. function isTime(timeStr) {
  607. var timeRegex = time_reg_format;
  608. // eliminate the am/pm from the external time_reg_format
  609. timeRegex = timeRegex.replace(/[ ]*\([^)]*m\)/i, '');
  610. if(timeStr.length== 0){
  611. return true;
  612. }
  613. //we now support multiple time formats
  614. myregexp = new RegExp(timeRegex);
  615. if(!myregexp.test(timeStr)) {
  616. return false;
  617. }
  618. return true;
  619. }
  620. function inRange(value, min, max) {
  621. if (typeof num_grp_sep != 'undefined' && typeof dec_sep != 'undefined')
  622. value = unformatNumberNoParse(value, num_grp_sep, dec_sep).toString();
  623. var result = true;
  624. if (typeof min == 'number' && value < min)
  625. {
  626. result = false;
  627. }
  628. if (typeof max == 'number' && value > max)
  629. {
  630. result = false;
  631. }
  632. return result;
  633. }
  634. function bothExist(item1, item2) {
  635. if(typeof item1 == 'undefined') { return false; }
  636. if(typeof item2 == 'undefined') { return false; }
  637. if((item1 == '' && item2 != '') || (item1 != '' && item2 == '') ) { return false; }
  638. return true;
  639. }
  640. trim = YAHOO.lang.trim;
  641. function check_form(formname) {
  642. if (typeof(siw) != 'undefined' && siw
  643. && typeof(siw.selectingSomething) != 'undefined' && siw.selectingSomething)
  644. return false;
  645. return validate_form(formname, '');
  646. }
  647. function add_error_style(formname, input, txt, flash) {
  648. var raiseFlag = false;
  649. if (typeof flash == "undefined")
  650. flash = true;
  651. try {
  652. inputHandle = typeof input == "object" ? input : document.forms[formname][input];
  653. style = get_current_bgcolor(inputHandle);
  654. // strip off the colon at the end of the warning strings
  655. if ( txt.substring(txt.length-1) == ':' )
  656. txt = txt.substring(0,txt.length-1)
  657. // Bug 28249 - To help avoid duplicate messages for an element, strip off extra messages and
  658. // match on the field name itself
  659. requiredTxt = SUGAR.language.get('app_strings', 'ERR_MISSING_REQUIRED_FIELDS');
  660. invalidTxt = SUGAR.language.get('app_strings', 'ERR_INVALID_VALUE');
  661. nomatchTxt = SUGAR.language.get('app_strings', 'ERR_SQS_NO_MATCH_FIELD');
  662. matchTxt = txt.replace(requiredTxt,'').replace(invalidTxt,'').replace(nomatchTxt,'');
  663. YUI().use('node', function (Y) {
  664. Y.one(inputHandle).get('parentNode').get('children').each(function(node, index, nodeList){
  665. if(node.hasClass('validation-message') && node.get('text').search(matchTxt)){
  666. raiseFlag = true;
  667. }
  668. });
  669. });
  670. if(!raiseFlag) {
  671. errorTextNode = document.createElement('div');
  672. errorTextNode.className = 'required validation-message';
  673. errorTextNode.innerHTML = txt;
  674. if ( inputHandle.parentNode.className.indexOf('x-form-field-wrap') != -1 ) {
  675. inputHandle.parentNode.parentNode.appendChild(errorTextNode);
  676. }
  677. else {
  678. inputHandle.parentNode.appendChild(errorTextNode);
  679. }
  680. if (flash)
  681. inputHandle.style.backgroundColor = "#FF0000";
  682. inputsWithErrors.push(inputHandle);
  683. }
  684. if (flash)
  685. {
  686. // We only need to setup the flashy-flashy on the first entry, it loops through all fields automatically
  687. if ( inputsWithErrors.length == 1 ) {
  688. for(var wp = 1; wp <= 10; wp++) {
  689. window.setTimeout('fade_error_style(style, '+wp*10+')',1000+(wp*50));
  690. }
  691. }
  692. if(typeof (window[formname + "_tabs"]) != "undefined") {
  693. var tabView = window[formname + "_tabs"];
  694. var parentDiv = YAHOO.util.Dom.getAncestorByTagName(inputHandle, "div");
  695. if ( tabView.get ) {
  696. var tabs = tabView.get("tabs");
  697. for (var i in tabs) {
  698. if (tabs[i].get("contentEl") == parentDiv
  699. || YAHOO.util.Dom.isAncestor(tabs[i].get("contentEl"), inputHandle))
  700. {
  701. tabs[i].get("labelEl").style.color = "red";
  702. if ( inputsWithErrors.length == 1 )
  703. tabView.selectTab(i);
  704. }
  705. }
  706. }
  707. }
  708. window.setTimeout("inputsWithErrors[" + (inputsWithErrors.length - 1) + "].style.backgroundColor = '';", 2000);
  709. }
  710. } catch ( e ) {
  711. // Catch errors here so we don't allow an incomplete record through the javascript validation
  712. }
  713. }
  714. /**
  715. * removes all error messages for the current form
  716. */
  717. function clear_all_errors() {
  718. for(var wp = 0; wp < inputsWithErrors.length; wp++) {
  719. if(typeof(inputsWithErrors[wp]) !='undefined' && typeof inputsWithErrors[wp].parentNode != 'undefined' && inputsWithErrors[wp].parentNode != null) {
  720. if ( inputsWithErrors[wp].parentNode.className.indexOf('x-form-field-wrap') != -1 )
  721. {
  722. inputsWithErrors[wp].parentNode.parentNode.removeChild(inputsWithErrors[wp].parentNode.parentNode.lastChild);
  723. }
  724. else
  725. {
  726. inputsWithErrors[wp].parentNode.removeChild(inputsWithErrors[wp].parentNode.lastChild);
  727. }
  728. }
  729. }
  730. if (inputsWithErrors.length == 0) return;
  731. if ( YAHOO.util.Dom.getAncestorByTagName(inputsWithErrors[0], "form") ) {
  732. var formname = YAHOO.util.Dom.getAncestorByTagName(inputsWithErrors[0], "form").getAttribute("name");
  733. if(typeof (window[formname + "_tabs"]) != "undefined") {
  734. var tabView = window[formname + "_tabs"];
  735. if ( tabView.get ) {
  736. var tabs = tabView.get("tabs");
  737. for (var i in tabs) {
  738. if (typeof tabs[i] == "object")
  739. tabs[i].get("labelEl").style.color = "";
  740. }
  741. }
  742. }
  743. inputsWithErrors = new Array();
  744. }
  745. }
  746. function get_current_bgcolor(input) {
  747. if(input.currentStyle) {// ie
  748. style = input.currentStyle.backgroundColor;
  749. return style.substring(1,7);
  750. }
  751. else {// moz
  752. style = '';
  753. styleRGB = document.defaultView.getComputedStyle(input, '').getPropertyValue("background-color");
  754. comma = styleRGB.indexOf(',');
  755. style += dec2hex(styleRGB.substring(4, comma));
  756. commaPrevious = comma;
  757. comma = styleRGB.indexOf(',', commaPrevious+1);
  758. style += dec2hex(styleRGB.substring(commaPrevious+2, comma));
  759. style += dec2hex(styleRGB.substring(comma+2, styleRGB.lastIndexOf(')')));
  760. return style;
  761. }
  762. }
  763. function hex2dec(hex){return(parseInt(hex,16));}
  764. var hexDigit=new Array("0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F");
  765. function dec2hex(dec){return(hexDigit[dec>>4]+hexDigit[dec&15]);}
  766. function fade_error_style(normalStyle, percent) {
  767. errorStyle = 'f10202';
  768. var r1 = hex2dec(errorStyle.slice(0,2));
  769. var g1 = hex2dec(errorStyle.slice(2,4));
  770. var b1 = hex2dec(errorStyle.slice(4,6));
  771. var r2 = hex2dec(normalStyle.slice(0,2));
  772. var g2 = hex2dec(normalStyle.slice(2,4));
  773. var b2 = hex2dec(normalStyle.slice(4,6));
  774. var pc = percent / 100;
  775. r= Math.floor(r1+(pc*(r2-r1)) + .5);
  776. g= Math.floor(g1+(pc*(g2-g1)) + .5);
  777. b= Math.floor(b1+(pc*(b2-b1)) + .5);
  778. for(var wp = 0; wp < inputsWithErrors.length; wp++) {
  779. inputsWithErrors[wp].style.backgroundColor = "#" + dec2hex(r) + dec2hex(g) + dec2hex(b);
  780. }
  781. }
  782. function isFieldTypeExceptFromEmptyCheck(fieldType)
  783. {
  784. var results = false;
  785. var exemptList = ['bool','file'];
  786. for(var i=0;i<exemptList.length;i++)
  787. {
  788. if(fieldType == exemptList[i])
  789. return true;
  790. }
  791. return results;
  792. }
  793. function validate_form(formname, startsWith){
  794. requiredTxt = SUGAR.language.get('app_strings', 'ERR_MISSING_REQUIRED_FIELDS');
  795. invalidTxt = SUGAR.language.get('app_strings', 'ERR_INVALID_VALUE');
  796. if ( typeof (formname) == 'undefined')
  797. {
  798. return false;
  799. }
  800. if ( typeof (validate[formname]) == 'undefined')
  801. {
  802. disableOnUnloadEditView(document.forms[formname]);
  803. return true;
  804. }
  805. var form = document.forms[formname];
  806. var isError = false;
  807. var errorMsg = "";
  808. var _date = new Date();
  809. if(_date.getTime() < (lastSubmitTime + 2000) && startsWith == oldStartsWith) { // ignore submits for the next 2 seconds
  810. return false;
  811. }
  812. lastSubmitTime = _date.getTime();
  813. oldStartsWith = startsWith;
  814. clear_all_errors(); // remove previous error messages
  815. inputsWithErrors = new Array();
  816. for(var i = 0; i < validate[formname].length; i++){
  817. if(validate[formname][i][nameIndex].indexOf(startsWith) == 0){
  818. if(typeof form[validate[formname][i][nameIndex]] != 'undefined' && typeof form[validate[formname][i][nameIndex]].value != 'undefined'){
  819. var bail = false;
  820. //If a field is not required and it is blank or is binarydependant, skip validation.
  821. //Example of binary dependant fields would be the hour/min/meridian dropdowns in a date time combo widget, which require further processing than a blank check
  822. if(!validate[formname][i][requiredIndex] && trim(form[validate[formname][i][nameIndex]].value) == '' && (typeof(validate[formname][i][jstypeIndex]) != 'undefined' && validate[formname][i][jstypeIndex] != 'binarydep'))
  823. {
  824. continue;
  825. }
  826. if(validate[formname][i][requiredIndex]
  827. && !isFieldTypeExceptFromEmptyCheck(validate[formname][i][typeIndex])
  828. ){
  829. if(typeof form[validate[formname][i][nameIndex]] == 'undefined' || trim(form[validate[formname][i][nameIndex]].value) == ""){
  830. add_error_style(formname, validate[formname][i][nameIndex], requiredTxt +' ' + validate[formname][i][msgIndex]);
  831. isError = true;
  832. }
  833. }
  834. if(!bail){
  835. switch(validate[formname][i][typeIndex]){
  836. case 'email':
  837. if(!isValidEmail(trim(form[validate[formname][i][nameIndex]].value))){
  838. isError = true;
  839. add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
  840. }
  841. break;
  842. case 'time':
  843. if( !isTime(trim(form[validate[formname][i][nameIndex]].value))){
  844. isError = true;
  845. add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
  846. } break;
  847. case 'date': if(!isDate(trim(form[validate[formname][i][nameIndex]].value))){
  848. isError = true;
  849. add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
  850. } break;
  851. case 'alpha':
  852. break;
  853. case 'DBName':
  854. if(!isDBName(trim(form[validate[formname][i][nameIndex]].value))){
  855. isError = true;
  856. add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
  857. }
  858. break;
  859. // Bug #49614 : Check value without trimming before
  860. case 'DBNameRaw':
  861. if(!isDBName(form[validate[formname][i][nameIndex]].value)){
  862. isError = true;
  863. add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
  864. }
  865. break;
  866. case 'alphanumeric':
  867. break;
  868. case 'file':
  869. var file_input = form[validate[formname][i][nameIndex] + '_file'];
  870. if( file_input && validate[formname][i][requiredIndex] && trim(file_input.value) == "" && !file_input.disabled ) {
  871. isError = true;
  872. add_error_style(formname, validate[formname][i][nameIndex], requiredTxt + " " + validate[formname][i][msgIndex]);
  873. }
  874. break;
  875. case 'int':
  876. if(!isInteger(trim(form[validate[formname][i][nameIndex]].value))){
  877. isError = true;
  878. add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
  879. }
  880. break;
  881. case 'decimal':
  882. if(!isDecimal(trim(form[validate[formname][i][nameIndex]].value))){
  883. isError = true;
  884. add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
  885. }
  886. break;
  887. case 'currency':
  888. case 'float':
  889. if(!isFloat(trim(form[validate[formname][i][nameIndex]].value))){
  890. isError = true;
  891. add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
  892. }
  893. break;
  894. case 'teamset_mass':
  895. var div_element_id = formname + '_' + form[validate[formname][i][nameIndex]].name + '_operation_div';
  896. var input_elements = YAHOO.util.Selector.query('input', document.getElementById(div_element_id));
  897. var primary_field_id = '';
  898. var validation_passed = false;
  899. var replace_selected = false;
  900. //Loop through the option elements (replace or add currently)
  901. for(t in input_elements) {
  902. if(input_elements[t].type && input_elements[t].type == 'radio' && input_elements[t].checked == true && input_elements[t].value == 'replace') {
  903. //Now find where the primary radio button is and if a value has been set
  904. var radio_elements = YAHOO.util.Selector.query('input[type=radio]', document.getElementById(formname + '_team_name_table'));
  905. for(var x = 0; x < radio_elements.length; x++) {
  906. if(radio_elements[x].name != 'team_name_type') {
  907. primary_field_id = 'team_name_collection_' + radio_elements[x].value;
  908. if(radio_elements[x].checked) {
  909. replace_selected = true;
  910. if(trim(document.forms[formname].elements[primary_field_id].value) != '') {
  911. validation_passed = true;
  912. break;
  913. }
  914. } else if(trim(document.forms[formname].elements[primary_field_id].value) != '') {
  915. replace_selected = true;
  916. }
  917. }
  918. }
  919. }
  920. }
  921. if(replace_selected && !validation_passed) {
  922. add_error_style(formname, primary_field_id, SUGAR.language.get('app_strings', 'ERR_NO_PRIMARY_TEAM_SPECIFIED'));
  923. isError = true;
  924. }
  925. break;
  926. case 'teamset':
  927. var table_element_id = formname + '_' + form[validate[formname][i][nameIndex]].name + '_table';
  928. if(document.getElementById(table_element_id)) {
  929. var input_elements = YAHOO.util.Selector.query('input[type=radio]', document.getElementById(table_element_id));
  930. var has_primary = false;
  931. var primary_field_id = form[validate[formname][i][nameIndex]].name + '_collection_0';
  932. for(t in input_elements) {
  933. primary_field_id = form[validate[formname][i][nameIndex]].name + '_collection_' + input_elements[t].value;
  934. if(input_elements[t].type && input_elements[t].type == 'radio' && input_elements[t].checked == true) {
  935. if(document.forms[formname].elements[primary_field_id].value != '') {
  936. has_primary = true;
  937. }
  938. break;
  939. }
  940. }
  941. if(!has_primary) {
  942. isError = true;
  943. var field_id = form[validate[formname][i][nameIndex]].name + '_collection_' + input_elements[0].value;
  944. add_error_style(formname, field_id, SUGAR.language.get('app_strings', 'ERR_NO_PRIMARY_TEAM_SPECIFIED'));
  945. }
  946. }
  947. break;
  948. case 'error':
  949. isError = true;
  950. add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex]);
  951. break;
  952. }
  953. if(typeof validate[formname][i][jstypeIndex] != 'undefined'/* && !isError*/){
  954. switch(validate[formname][i][jstypeIndex]){
  955. // Bug #47961 May be validation through callback is best way.
  956. case 'callback' :
  957. if (typeof validate[formname][i][callbackIndex] == 'function')
  958. {
  959. var result = validate[formname][i][callbackIndex](formname, validate[formname][i][nameIndex]);
  960. if (result == false)
  961. {
  962. isError = true;
  963. add_error_style(formname, validate[formname][i][nameIndex], requiredTxt + " " + validate[formname][i][msgIndex]);
  964. }
  965. }
  966. break;
  967. case 'range':
  968. if(!inRange(trim(form[validate[formname][i][nameIndex]].value), validate[formname][i][minIndex], validate[formname][i][maxIndex])){
  969. isError = true;
  970. var lbl_validate_range = SUGAR.language.get('app_strings', 'LBL_VALIDATE_RANGE');
  971. if (typeof validate[formname][i][minIndex] == 'number' && typeof validate[formname][i][maxIndex] == 'number')
  972. {
  973. add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex] + " value " + form[validate[formname][i][nameIndex]].value + " " + lbl_validate_range + " (" +validate[formname][i][minIndex] + " - " + validate[formname][i][maxIndex] + ")");
  974. }
  975. else if (typeof validate[formname][i][minIndex] == 'number')
  976. {
  977. add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex] + " " + SUGAR.language.get('app_strings', 'MSG_SHOULD_BE') + ' ' + validate[formname][i][minIndex] + ' ' + SUGAR.language.get('app_strings', 'MSG_OR_GREATER'));
  978. }
  979. else if (typeof validate[formname][i][maxIndex] == 'number')
  980. {
  981. add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex] + " " + SUGAR.language.get('app_strings', 'MSG_IS_MORE_THAN') + ' ' + validate[formname][i][maxIndex]);
  982. }
  983. }
  984. break;
  985. case 'isbefore':
  986. compareTo = form[validate[formname][i][compareToIndex]];
  987. if( typeof compareTo != 'undefined'){
  988. if(trim(compareTo.value) != '' || (validate[formname][i][allowblank] != 'true') ) {
  989. date2 = trim(compareTo.value);
  990. date1 = trim(form[validate[formname][i][nameIndex]].value);
  991. if(trim(date1).length != 0 && !isBefore(date1,date2)){
  992. isError = true;
  993. //jc:#12287 - adding translation for the is not before message
  994. add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex] + "(" + date1 + ") " + SUGAR.language.get('app_strings', 'MSG_IS_NOT_BEFORE') + ' ' +date2);
  995. }
  996. }
  997. }
  998. break;
  999. case 'less':
  1000. value=unformatNumber(trim(form[validate[formname][i][nameIndex]].value), num_grp_sep, dec_sep);
  1001. maximum = parseFloat(validate[formname][i][maxIndex]);
  1002. if( typeof maximum != 'undefined'){
  1003. if(value>maximum) {
  1004. isError = true;
  1005. add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex] +" " +SUGAR.language.get('app_strings', 'MSG_IS_MORE_THAN')+ ' ' + validate[formname][i][altMsgIndex]);
  1006. }
  1007. }
  1008. break;
  1009. case 'more':
  1010. value=unformatNumber(trim(form[validate[formname][i][nameIndex]].value), num_grp_sep, dec_sep);
  1011. minimum = parseFloat(validate[formname][i][minIndex]);
  1012. if( typeof minimum != 'undefined'){
  1013. if(value<minimum) {
  1014. isError = true;
  1015. add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex] +" " +SUGAR.language.get('app_strings', 'MSG_SHOULD_BE')+ ' ' + minimum + ' ' + SUGAR.language.get('app_strings', 'MSG_OR_GREATER'));
  1016. }
  1017. }
  1018. break;
  1019. case 'binarydep':
  1020. compareTo = form[validate[formname][i][compareToIndex]];
  1021. if( typeof compareTo != 'undefined') {
  1022. item1 = trim(form[validate[formname][i][nameIndex]].value);
  1023. item2 = trim(compareTo.value);
  1024. if(!bothExist(item1, item2)) {
  1025. isError = true;
  1026. add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex]);
  1027. }
  1028. }
  1029. break;
  1030. case 'comparison':
  1031. compareTo = form[validate[formname][i][compareToIndex]];
  1032. if( typeof compareTo != 'undefined') {
  1033. item1 = trim(form[validate[formname][i][nameIndex]].value);
  1034. item2 = trim(compareTo.value);
  1035. if(!bothExist(item1, item2) || item1 != item2) {
  1036. isError = true;
  1037. add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex]);
  1038. }
  1039. }
  1040. break;
  1041. case 'in_array':
  1042. arr = eval(validate[formname][i][arrIndex]);
  1043. operator = validate[formname][i][operatorIndex];
  1044. item1 = trim(form[validate[formname][i][nameIndex]].value);
  1045. if (operator.charAt(0) == 'u') {
  1046. item1 = item1.toUpperCase();
  1047. operator = operator.substring(1);
  1048. } else if (operator.charAt(0) == 'l') {
  1049. item1 = item1.toLowerCase();
  1050. operator = operator.substring(1);
  1051. }
  1052. for(j = 0; j < arr.length; j++){
  1053. val = arr[j];
  1054. if((operator == "==" && val == item1) || (operator == "!=" && val != item1)){
  1055. isError = true;
  1056. add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
  1057. }
  1058. }
  1059. break;
  1060. case 'verified':
  1061. if(trim(form[validate[formname][i][nameIndex]].value) == 'false'){
  1062. //Fake an error so form does not submit
  1063. isError = true;
  1064. }
  1065. break;
  1066. }
  1067. }
  1068. }
  1069. }
  1070. }
  1071. }
  1072. /* nsingh: BUG#15102
  1073. Check min max default field logic.
  1074. Can work with float values as well, but as of 10/8/07 decimal values in MB and studio don't have min and max value constraints.*/
  1075. if(formsWithFieldLogic){
  1076. var invalidLogic=false;
  1077. if(formsWithFieldLogic.min && formsWithFieldLogic.max && formsWithFieldLogic._default) {
  1078. var showErrorsOn={min:{value:'min', show:false, obj:formsWithFieldLogic.min.value},
  1079. max:{value:'max',show:false, obj:formsWithFieldLogic.max.value},
  1080. _default:{value:'default',show:false, obj:formsWithFieldLogic._default.value},
  1081. len:{value:'len', show:false, obj:parseInt(formsWithFieldLogic.len.value,10)}};
  1082. var min = (formsWithFieldLogic.min.value !='') ? parseFloat(formsWithFieldLogic.min.value) : 'undef';
  1083. var max = (formsWithFieldLogic.max.value !='') ? parseFloat(formsWithFieldLogic.max.value) : 'undef';
  1084. var _default = (formsWithFieldLogic._default.value!='')? parseFloat(formsWithFieldLogic._default.value) : 'undef';
  1085. /*Check all lengths are <= max size.*/
  1086. for(var i in showErrorsOn){
  1087. if(showErrorsOn[i].value!='len' && showErrorsOn[i].obj.length > showErrorsOn.len.obj){
  1088. invalidLogic=true;
  1089. showErrorsOn[i].show=true;
  1090. showErrorsOn.len.show=true;
  1091. }
  1092. }
  1093. if(min!='undef' && max!='undef' && _default!='undef'){
  1094. if(!inRange(_default,min,max)){
  1095. invalidLogic=true;
  1096. showErrorsOn.min.show=true;
  1097. showErrorsOn.max.show=true;
  1098. showErrorsOn._default.show=true;
  1099. }
  1100. }
  1101. if(min!='undef' && max!= 'undef' && min > max){
  1102. invalidLogic = true;
  1103. showErrorsOn.min.show=true;
  1104. showErrorsOn.max.show=true;
  1105. }
  1106. if(min!='undef' && _default!='undef' && _default < min){
  1107. invalidLogic = true;
  1108. showErrorsOn.min.show=true;
  1109. showErrorsOn._default.show=true;
  1110. }
  1111. if(max!='undef' && _default !='undef' && _default>max){
  1112. invalidLogic = true;
  1113. showErrorsOn.max.show=true;
  1114. showErrorsOn._default.show=true;
  1115. }
  1116. if(invalidLogic){
  1117. isError=true;
  1118. for(var error in showErrorsOn)
  1119. if(showErrorsOn[error].show)
  1120. add_error_style(formname,showErrorsOn[error].value, formsWithFieldLogic.msg);
  1121. }
  1122. else if (!isError)
  1123. formsWithFieldLogic = null;
  1124. }
  1125. }
  1126. if(formWithPrecision){
  1127. if (!isValidPrecision(formWithPrecision.float.value, formWithPrecision.precision.value)){
  1128. isError = true;
  1129. add_error_style(formname, 'default', SUGAR.language.get('app_strings', 'ERR_COMPATIBLE_PRECISION_VALUE'));
  1130. }else if(!isError){
  1131. isError = false;
  1132. }
  1133. }
  1134. //END BUG# 15102
  1135. if (isError == true) {
  1136. var nw, ne, sw, se;
  1137. if (self.pageYOffset) // all except Explorer
  1138. {
  1139. nwX = self.pageXOffset;
  1140. seX = self.innerWidth;
  1141. nwY = self.pageYOffset;
  1142. seY = self.innerHeight;
  1143. }
  1144. else if (document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
  1145. {
  1146. nwX = document.documentElement.scrollLeft;
  1147. seX = document.documentElement.clientWidth;
  1148. nwY = document.documentElement.scrollTop;
  1149. seY = document.documentElement.clientHeight;
  1150. }
  1151. else if (document.body) // all other Explorers
  1152. {
  1153. nwX = document.body.scrollLeft;
  1154. seX = document.body.clientWidth;
  1155. nwY = document.body.scrollTop;
  1156. seY = document.body.clientHeight;
  1157. }
  1158. var inView = true; // is there an error within viewport of browser
  1159. for(var wp = 0; wp < inputsWithErrors.length; wp++) {
  1160. var elementCoor = findElementPos(inputsWithErrors[wp]);
  1161. if(!(elementCoor.x >= nwX && elementCoor.y >= nwY &&
  1162. elementCoor.x <= seX+nwX && elementCoor.y <= seY+nwY)) { // if input is not within viewport, modify for SI bug 52497
  1163. inView = false;
  1164. scrollToTop = elementCoor.y - 75;
  1165. scrollToLeft = elementCoor.x - 75;
  1166. }
  1167. else { // on first input within viewport, don't scroll
  1168. break;
  1169. }
  1170. }
  1171. if(!inView) window.scrollTo(scrollToLeft,scrollToTop);
  1172. return false;
  1173. }
  1174. disableOnUnloadEditView(form);
  1175. return true;
  1176. }
  1177. /**
  1178. * This array is used to remember mark status of rows in browse mode
  1179. */
  1180. var marked_row = new Array;
  1181. /**
  1182. * Sets/unsets the pointer and marker in browse mode
  1183. *
  1184. * @param object the table row
  1185. * @param interger the row number
  1186. * @param string the action calling this script (over, out or click)
  1187. * @param string the default background color
  1188. * @param string the color to use for mouseover
  1189. * @param string the color to use for marking a row
  1190. *
  1191. * @return boolean whether pointer is set or not
  1192. */
  1193. function setPointer(theRow, theRowNum, theAction, theDefaultColor, thePointerColor, theMarkColor) {
  1194. var theCells = null;
  1195. // 1. Pointer and mark feature are disabled or the browser can't get the
  1196. // row -> exits
  1197. if ((thePointerColor == '' && theMarkColor == '')
  1198. || typeof(theRow.style) == 'undefined') {
  1199. return false;
  1200. }
  1201. // 2. Gets the current row and exits if the browser can't get it
  1202. if (typeof(document.getElementsByTagName) != 'undefined') {
  1203. theCells = theRow.getElementsByTagName('td');
  1204. }
  1205. else if (typeof(theRow.cells) != 'undefined') {
  1206. theCells = theRow.cells;
  1207. }
  1208. else {
  1209. return false;
  1210. }
  1211. // 3. Gets the current color...
  1212. var rowCellsCnt = theCells.length;
  1213. var domDetect = null;
  1214. var currentColor = null;
  1215. var newColor = null;
  1216. // 3.1 ... with DOM compatible browsers except Opera that does not return
  1217. // valid values with "getAttribute"
  1218. if (typeof(window.opera) == 'undefined'
  1219. && typeof(theCells[0].getAttribute) != 'undefined') {
  1220. currentColor = theCells[0].getAttribute('bgcolor');
  1221. domDetect = true;
  1222. }
  1223. // 3.2 ... with other browsers
  1224. else {
  1225. currentColor = theCells[0].style.backgroundColor;
  1226. domDetect = false;
  1227. } // end 3
  1228. // 4. Defines the new color
  1229. // 4.1 Current color is the default one
  1230. if (currentColor == ''
  1231. || (currentColor!= null && (currentColor.toLowerCase() == theDefaultColor.toLowerCase()))) {
  1232. if (theAction == 'over' && thePointerColor != '') {
  1233. newColor = thePointerColor;
  1234. }
  1235. else if (theAction == 'click' && theMarkColor != '') {
  1236. newColor = theMarkColor;
  1237. marked_row[theRowNum] = true;
  1238. }
  1239. }
  1240. // 4.1.2 Current color is the pointer one
  1241. else if (currentColor!= null && (currentColor.toLowerCase() == thePointerColor.toLowerCase())
  1242. && (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])) {
  1243. if (theAction == 'out') {
  1244. newColor = theDefaultColor;
  1245. }
  1246. else if (theAction == 'click' && theMarkColor != '') {
  1247. newColor = theMarkColor;
  1248. marked_row[theRowNum] = true;
  1249. }
  1250. }
  1251. // 4.1.3 Current color is the marker one
  1252. else if (currentColor!= null && (currentColor.toLowerCase() == theMarkColor.toLowerCase())) {
  1253. if (theAction == 'click') {
  1254. newColor = (thePointerColor != '')
  1255. ? thePointerColor
  1256. : theDefaultColor;
  1257. marked_row[theRowNum] = (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])
  1258. ? true
  1259. : null;
  1260. }
  1261. } // end 4
  1262. // 5. Sets the new color...
  1263. if (newColor) {
  1264. var c = null;
  1265. // 5.1 ... with DOM compatible browsers except Opera
  1266. if (domDetect) {
  1267. for (c = 0; c < rowCellsCnt; c++) {
  1268. theCells[c].setAttribute('bgcolor', newColor, 0);
  1269. } // end for
  1270. }
  1271. // 5.2 ... with other browsers
  1272. else {
  1273. for (c = 0; c < rowCellsCnt; c++) {
  1274. theCells[c].style.backgroundColor = newColor;
  1275. }
  1276. }
  1277. } // end 5
  1278. return true;
  1279. } // end of the 'setPointer()' function
  1280. /**
  1281. * listbox redirection
  1282. */
  1283. function goToUrl(selObj, goToLocation) {
  1284. eval("document.location.href = '" + goToLocation + "pos=" + selObj.options[selObj.selectedIndex].value + "'");
  1285. }
  1286. var json_objects = new Object();
  1287. function getXMLHTTPinstance() {
  1288. var xmlhttp = false;
  1289. var userAgent = navigator.userAgent.toLowerCase() ;
  1290. // IE Check supports ActiveX controls
  1291. if (userAgent.indexOf("msie") != -1 && userAgent.indexOf("mac") == -1 && userAgent.indexOf("opera") == -1) {
  1292. var version = navigator.appVersion.match(/MSIE (\d+\.\d+)/)[1] ;
  1293. if(version >= 5.5 ) {
  1294. try {
  1295. xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
  1296. }
  1297. catch (e) {
  1298. try {
  1299. xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  1300. }
  1301. catch (E) {
  1302. xmlhttp = false;
  1303. }
  1304. }
  1305. }
  1306. }
  1307. if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
  1308. xmlhttp = new XMLHttpRequest();
  1309. }
  1310. return xmlhttp;
  1311. }
  1312. // NOW LOAD THE OBJECT..
  1313. var global_xmlhttp = getXMLHTTPinstance();
  1314. function http_fetch_sync(url,post_data) {
  1315. global_xmlhttp = getXMLHTTPinstance();
  1316. var method = 'GET';
  1317. if(typeof(post_data) != 'undefined') method = 'POST';
  1318. try {
  1319. global_xmlhttp.open(method, url,false);
  1320. }
  1321. catch(e) {
  1322. alert('message:'+e.message+":url:"+url);
  1323. }
  1324. if(method == 'POST') {
  1325. global_xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  1326. }
  1327. global_xmlhttp.send(post_data);
  1328. if (SUGAR.util.isLoginPage(global_xmlhttp.responseText))
  1329. return false;
  1330. var args = {"responseText" : global_xmlhttp.responseText,
  1331. "responseXML" : global_xmlhttp.responseXML,
  1332. "request_id" : typeof(request_id) != "undefined" ? request_id : 0};
  1333. return args;
  1334. }
  1335. // this is a GET unless post_data is defined
  1336. function http_fetch_async(url,callback,request_id,post_data) {
  1337. var method = 'GET';
  1338. if(typeof(post_data) != 'undefined') {
  1339. method = 'POST';
  1340. }
  1341. try {
  1342. global_xmlhttp.open(method, url,true);
  1343. }
  1344. catch(e) {
  1345. alert('message:'+e.message+":url:"+url);
  1346. }
  1347. if(method == 'POST') {
  1348. global_xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  1349. }
  1350. global_xmlhttp.onreadystatechange = function() {
  1351. if(global_xmlhttp.readyState==4) {
  1352. if(global_xmlhttp.status == 200) {
  1353. if (SUGAR.util.isLoginPage(global_xmlhttp.responseText))
  1354. return false;
  1355. var args = {"responseText" : global_xmlhttp.responseText,
  1356. "responseXML" : global_xmlhttp.responseXML,
  1357. "request_id" : request_id };
  1358. callback.call(document,args);
  1359. }
  1360. else {
  1361. alert("There was a problem retrieving the XML data:\n" + global_xmlhttp.statusText);
  1362. }
  1363. }
  1364. }
  1365. global_xmlhttp.send(post_data);
  1366. }
  1367. function insert_at_cursor(field, value) {
  1368. //ie:
  1369. if (document.selection) {
  1370. field.focus();
  1371. sel = document.selection.createRange();
  1372. sel.text = value;
  1373. }
  1374. //mozilla:
  1375. else if(field.selectionStart || field.selectionStart == '0') {
  1376. var start_pos = field.selectionStart;
  1377. var end_pos = field.selectionEnd;
  1378. field.value = field.value.substring(0, start_pos) + value + field.value.substring(end_pos, field.value.length);
  1379. }
  1380. else {
  1381. field.value += value;
  1382. }
  1383. }
  1384. function checkParentType(type,button) {
  1385. if(button == null) {
  1386. return;
  1387. }
  1388. if(typeof disabledModules != 'undefined' && typeof(disabledModules[type]) != 'undefined') {
  1389. button.disabled='disabled';
  1390. }
  1391. else {
  1392. button.disabled = false;
  1393. }
  1394. }
  1395. function parseDate(input, format) {
  1396. date = input.value;
  1397. format = format.replace(/%/g, '');
  1398. sep = format.charAt(1);
  1399. yAt = format.indexOf('Y')
  1400. // 1-1-06 or 1-12-06 or 1-1-2006 or 1-12-2006
  1401. if(date.match(/^\d{1,2}[\/-]\d{1,2}[\/-]\d{2,4}$/) && yAt == 4) {
  1402. if(date.match(/^\d{1}[\/-].*$/)) date = '0' + date;
  1403. if(date.match(/^\d{2}[\/-]\d{1}[\/-].*$/)) date = date.substring(0,3) + '0' + date.substring(3,date.length);
  1404. if(date.match(/^\d{2}[\/-]\d{2}[\/-]\d{2}$/)) date = date.substring(0,6) + '20' + date.substring(6,date.length);
  1405. }
  1406. // 06-11-1 or 06-1-1
  1407. else if(date.match(/^\d{2,4}[\/-]\d{1,2}[\/-]\d{1,2}$/)) {
  1408. if(date.match(/^\d{2}[\/-].*$/)) date = '20' + date;
  1409. if(date.match(/^\d{4}[\/-]\d{1}[\/-].*$/)) date = date.substring(0,5) + '0' + date.substring(5,date.length);
  1410. if(date.match(/^\d{4}[\/-]\d{2}[\/-]\d{1}$/)) date = date.substring(0,8) + '0' + date.substring(8,date.length);
  1411. }
  1412. else if(date.match(/^\d{4,8}$/)) { // digits only
  1413. digits = 0;
  1414. if(date.match(/^\d{8}$/)) digits = 8;// match for 8 digits
  1415. else if(date.match(/\d{6}/)) digits = 6;// match for 5 digits
  1416. else if(date.match(/\d{4}/)) digits = 4;// match for 5 digits
  1417. else if(date.match(/\d{5}/)) digits = 5;// match for 5 digits
  1418. switch(yAt) {
  1419. case 0:
  1420. switch(digits) {
  1421. case 4: date = '20' + date.substring(0,2) + sep + '0' + date.substring(2, 3) + sep + '0' + date.substring(3,4); break;
  1422. case 5: date = '20' + date.substring(0,2) + sep + date.substring(2, 4) + sep + '0' + date.substring(4,5); break;
  1423. case 6: date = '20' + date.substring(0,2) + sep + date.substring(2, 4) + sep + date.substring(4,6); break;
  1424. case 8: date = date.substring(0,4) + sep + date.substring(4, 6) + sep + date.substring(6,8); break;
  1425. }
  1426. break;
  1427. case 2:
  1428. switch(digits) {
  1429. case 4: date = '0' + date.substring(0,1) + sep + '20' + date.substring(1, 3) + sep + '0' + date.substring(3,4); break;
  1430. case 5: date = date.substring(0,2) + sep + '20' + date.substring(2, 4) + sep + '0' + date.substring(4,5); break;
  1431. case 6: date = date.substring(0,2) + sep + '20' + date.substring(2, 4) + sep + date.substring(4,6); break;
  1432. case 8: date = date.substring(0,2) + sep + date.substring(2, 6) + sep + date.substring(6,8); break;
  1433. }
  1434. case 4:
  1435. switch(digits) {
  1436. case 4: date = '0' + date.substring(0,1) + sep + '0' + date.substring(1, 2) + sep + '20' + date.substring(2,4); break;
  1437. case 5: date = '0' + date.substring(0,1) + sep + date.substring(1, 3) + sep + '20' + date.substring(3,5); break;
  1438. case 6: date = date.substring(0,2) + sep + date.substring(2, 4) + sep + '20' + date.substring(4,6); break;
  1439. case 8: date = date.substring(0,2) + sep + date.substring(2, 4) + sep + date.substring(4,8); break;
  1440. }
  1441. break;
  1442. }
  1443. }
  1444. date = date.replace(/[\/-]/g, sep);
  1445. input.value = date;
  1446. }
  1447. // find obj's position
  1448. function findElementPos(obj) {
  1449. var x = 0;
  1450. var y = 0;
  1451. if (obj.offsetParent) {
  1452. while (obj.offsetParent) {
  1453. x += obj.offsetLeft;
  1454. y += obj.offsetTop;
  1455. obj = obj.offsetParent;
  1456. }
  1457. }//if offsetParent exists
  1458. else if (obj.x && obj.y) {
  1459. y += obj.y
  1460. x += obj.x
  1461. }
  1462. return new coordinate(x, y);
  1463. }//findElementPos
  1464. // get dimensions of the browser window
  1465. function getClientDim() {
  1466. var nwX, nwY, seX, seY;
  1467. if (self.pageYOffset) // all except Explorer
  1468. {
  1469. nwX = self.pageXOffset;
  1470. seX = self.innerWidth + nwX;
  1471. nwY = self.pageYOffset;
  1472. seY = self.innerHeight + nwY;
  1473. }
  1474. else if (document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
  1475. {
  1476. nwX = document.documentElement.scrollLeft;
  1477. seX = document.documentElement.clientWidth + nwX;
  1478. nwY = document.documentElement.scrollTop;
  1479. seY = document.documentElement.clientHeight + nwY;
  1480. }
  1481. else if (document.body) // all other Explorers
  1482. {
  1483. nwX = document.body.scrollLeft;
  1484. seX = document.body.clientWidth + nwX;
  1485. nwY = document.body.scrollTop;
  1486. seY = document.body.clientHeight + nwY;
  1487. }
  1488. return {'nw' : new coordinate(nwX, nwY), 'se' : new coordinate(seX, seY)};
  1489. }
  1490. /**
  1491. * stop propagation on events
  1492. **/
  1493. function freezeEvent(e) {
  1494. if(e) {
  1495. if (e.preventDefault) e.preventDefault();
  1496. e.returnValue = false;
  1497. e.cancelBubble = true;
  1498. if (e.stopPropagation) e.stopPropagation();
  1499. return false;
  1500. }
  1501. }
  1502. /**
  1503. * coordinate class
  1504. **/
  1505. function coordinate(_x, _y) {
  1506. var x = _x;
  1507. var y = _y;
  1508. this.add = add;
  1509. this.sub = sub;
  1510. this.x = x;
  1511. this.y = y;
  1512. function add(rh) {
  1513. return new position(this.x + rh.x, this.y + rh.y);
  1514. }
  1515. function sub(rh) {
  1516. return new position(this.x + rh.x, this.y + rh.y);
  1517. }
  1518. }
  1519. // sends theForm via AJAX and fills in the theDiv
  1520. function sendAndRetrieve(theForm, theDiv, loadingStr) {
  1521. function success(data) {
  1522. document.getElementById(theDiv).innerHTML = data.responseText;
  1523. ajaxStatus.hideStatus();
  1524. }
  1525. if(typeof loadingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
  1526. ajaxStatus.showStatus(loadingStr);
  1527. oForm = new YAHOO.util.Element(theForm);
  1528. if ( oForm.get('enctype') && oForm.get('enctype') == 'multipart/form-data' ) {
  1529. // the second argument is true to indicate file upload.
  1530. YAHOO.util.Connect.setForm(theForm, true);
  1531. var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {upload: success, failure: success});
  1532. } else {
  1533. YAHOO.util.Connect.setForm(theForm);
  1534. var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
  1535. }
  1536. return false;
  1537. }
  1538. //save the form and redirect
  1539. function sendAndRedirect(theForm, loadingStr, redirect_location) {
  1540. function success(data) {
  1541. if(redirect_location){
  1542. location.href=redirect_location;
  1543. }
  1544. ajaxStatus.hideStatus();
  1545. }
  1546. if(typeof loadingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
  1547. ajaxStatus.showStatus(loadingStr);
  1548. oForm = new YAHOO.util.Element(theForm);
  1549. if ( oForm.get('enctype') && oForm.get('enctype') == 'multipart/form-data' ) {
  1550. // the second argument is true to indicate file upload.
  1551. YAHOO.util.Connect.setForm(theForm, true);
  1552. var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {upload: success, failure: success});
  1553. } else {
  1554. YAHOO.util.Connect.setForm(theForm);
  1555. var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
  1556. }
  1557. return false;
  1558. }
  1559. function saveForm(theForm, theDiv, loadingStr) {
  1560. if(check_form(theForm)){
  1561. for(i = 0; i < ajaxFormArray.length; i++){
  1562. if(ajaxFormArray[i] == theForm){
  1563. ajaxFormArray.splice(i, 1);
  1564. }
  1565. }
  1566. return sendAndRetrieve(theForm, loadingStr, theDiv);
  1567. }
  1568. else
  1569. return false;
  1570. }
  1571. // Builds a "snapshot" of the form, so we can use it to see if someone has changed it.
  1572. function snapshotForm(theForm) {
  1573. var snapshotTxt = '';
  1574. var elemList = theForm.elements;
  1575. var elem;
  1576. var elemType;
  1577. for( var i = 0; i < elemList.length ; i++ ) {
  1578. elem = elemList[i];
  1579. if ( typeof(elem.type) == 'undefined' ) {
  1580. continue;
  1581. }
  1582. elemType = elem.type.toLowerCase();
  1583. snapshotTxt = snapshotTxt + elem.name;
  1584. if ( elemType == 'text' || elemType == 'textarea' || elemType == 'password' ) {
  1585. snapshotTxt = snapshotTxt + elem.value;
  1586. }
  1587. else if ( elemType == 'select' || elemType == 'select-one' || elemType == 'select-multiple' ) {
  1588. var optionList = elem.options;
  1589. for ( var ii = 0 ; ii < optionList.length ; ii++ ) {
  1590. if ( optionList[ii].selected ) {
  1591. snapshotTxt = snapshotTxt + optionList[ii].value;
  1592. }
  1593. }
  1594. }
  1595. else if ( elemType == 'radio' || elemType == 'checkbox' ) {
  1596. if ( elem.selected ) {
  1597. snapshotTxt = snapshotTxt + 'checked';
  1598. }
  1599. }
  1600. else if ( elemType == 'hidden' ) {
  1601. snapshotTxt = snapshotTxt + elem.value;
  1602. }
  1603. }
  1604. return snapshotTxt;
  1605. }
  1606. function initEditView(theForm) {
  1607. if (SUGAR.util.ajaxCallInProgress()) {
  1608. window.setTimeout(function(){initEditView(theForm);}, 100);
  1609. return;
  1610. }
  1611. if ( theForm == null || theForm.id == null ) {
  1612. // Not much we can do here.
  1613. return;
  1614. }
  1615. // we don't need to check if the data is changed in the search popup
  1616. if (theForm.id == 'popup_query_form' || theForm.id == 'MassUpdate') {
  1617. return;
  1618. }
  1619. if ( typeof editViewSnapshots == 'undefined' || editViewSnapshots == null ) {
  1620. editViewSnapshots = new Object();
  1621. }
  1622. if ( typeof SUGAR.loadedForms == 'undefined' || SUGAR.loadedForms == null) {
  1623. SUGAR.loadedForms = new Object();
  1624. }
  1625. editViewSnapshots[theForm.id] = snapshotForm(theForm);
  1626. SUGAR.loadedForms[theForm.id] = true;
  1627. }
  1628. function onUnloadEditView(theForm) {
  1629. var dataHasChanged = false;
  1630. if ( typeof editViewSnapshots == 'undefined' ) {
  1631. // No snapshots, move along
  1632. return;
  1633. }
  1634. if ( typeof theForm == 'undefined' ) {
  1635. // Need to check all editViewSnapshots
  1636. for ( var idx in editViewSnapshots ) {
  1637. theForm = document.getElementById(idx);
  1638. // console.log('DEBUG: Checking all forms '+theForm.id);
  1639. if ( theForm == null
  1640. || typeof editViewSnapshots[theForm.id] == 'undefined'
  1641. || editViewSnapshots[theForm.id] == null
  1642. || !SUGAR.loadedForms[theForm.id]) {
  1643. continue;
  1644. }
  1645. var snap = snapshotForm(theForm);
  1646. if ( editViewSnapshots[theForm.id] != snap ) {
  1647. dataHasChanged = true;
  1648. }
  1649. }
  1650. } else {
  1651. // Just need to check a single form for changes
  1652. if ( editViewSnapshots == null || typeof theForm.id == 'undefined' || typeof editViewSnapshots[theForm.id] == 'undefined' || editViewSnapshots[theForm.id] == null ) {
  1653. return;
  1654. }
  1655. // console.log('DEBUG: Checking one form '+theForm.id);
  1656. if ( editViewSnapshots[theForm.id] != snapshotForm(theForm) ) {
  1657. // Data has changed.
  1658. dataHasChanged = true;
  1659. }
  1660. }
  1661. if ( dataHasChanged == true ) {
  1662. return SUGAR.language.get('app_strings','WARN_UNSAVED_CHANGES');
  1663. } else {
  1664. return;
  1665. }
  1666. }
  1667. function disableOnUnloadEditView(theForm) {
  1668. // If you don't pass anything in, it disables all checking
  1669. if ( typeof theForm == 'undefined' || typeof editViewSnapshots == 'undefined' || theForm == null || editViewSnapshots == null) {
  1670. window.onbeforeunload = null;
  1671. editViewSnapshots = null;
  1672. // console.log('DEBUG: Disabling all edit view checks');
  1673. } else {
  1674. // Otherwise, it just disables it for this form
  1675. if ( typeof(theForm.id) != 'undefined' && typeof(editViewSnapshots[theForm.id]) != 'undefined' ) {
  1676. editViewSnapshots[theForm.id] = null;
  1677. }
  1678. // console.log('DEBUG : Disabling just checks for '+theForm.id);
  1679. }
  1680. }
  1681. /*
  1682. * save some forms using an ajax call
  1683. * theForms - the ids of all of theh forms to save
  1684. * savingStr - the string to display when saving the form
  1685. * completeStr - the string to display when the form has been saved
  1686. */
  1687. function saveForms( savingStr, completeStr) {
  1688. index = 0;
  1689. theForms = ajaxFormArray;
  1690. function success(data) {
  1691. var theForm = document.getElementById(ajaxFormArray[0]);
  1692. document.getElementById('multiedit_'+theForm.id).innerHTML = data.responseText;
  1693. var saveAllButton = document.getElementById('ajaxsaveall');
  1694. ajaxFormArray.splice(index, 1);
  1695. if(saveAllButton && ajaxFormArray.length <= 1){
  1696. saveAllButton.style.visibility = 'hidden';
  1697. }
  1698. index++;
  1699. if(index == theForms.length){
  1700. ajaxStatus.showStatus(completeStr);
  1701. window.setTimeout('ajaxStatus.hideStatus();', 2000);
  1702. if(saveAllButton)
  1703. saveAllButton.style.visibility = 'hidden';
  1704. }
  1705. }
  1706. if(typeof savingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
  1707. ajaxStatus.showStatus(savingStr);
  1708. //loop through the forms saving each one
  1709. for(i = 0; i < theForms.length; i++){
  1710. var theForm = document.getElementById(theForms[i]);
  1711. if(check_form(theForm.id)){
  1712. theForm.action.value='AjaxFormSave';
  1713. YAHOO.util.Connect.setForm(theForm);
  1714. var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
  1715. }else{
  1716. ajaxStatus.hideStatus();
  1717. }
  1718. lastSubmitTime = lastSubmitTime-2000;
  1719. }
  1720. return false;
  1721. }
  1722. // -- start sugarListView class
  1723. // js functions used for ListView
  1724. function sugarListView() {
  1725. }
  1726. sugarListView.prototype.confirm_action = function(del) {
  1727. if (del == 1) {
  1728. return confirm( SUGAR.language.get('app_strings', 'NTC_DELETE_CONFIRMATION_NUM') + sugarListView.get_num_selected() + SUGAR.language.get('app_strings', 'NTC_DELETE_SELECTED_RECORDS'));
  1729. }
  1730. else {
  1731. return confirm( SUGAR.language.get('app_strings', 'NTC_UPDATE_CONFIRMATION_NUM') + sugarListView.get_num_selected() + SUGAR.language.get('app_strings', 'NTC_DELETE_SELECTED_RECORDS'));
  1732. }
  1733. }
  1734. sugarListView.get_num_selected = function () {
  1735. var selectCount = $("input[name='selectCount[]']:first");
  1736. if(selectCount.length > 0)
  1737. return parseInt(selectCount.val().replace("+", ""));
  1738. return 0;
  1739. }
  1740. sugarListView.update_count = function(count, add) {
  1741. if(typeof document.MassUpdate != 'undefined') {
  1742. the_form = document.MassUpdate;
  1743. for(var wp = 0; wp < the_form.elements.length; wp++) {
  1744. if(typeof the_form.elements[wp].name != 'undefined' && the_form.elements[wp].name == 'selectCount[]') {
  1745. if(add) {
  1746. the_form.elements[wp].value = parseInt(the_form.elements[wp].value,10) + count;
  1747. if (the_form.select_entire_list.value == 1 && the_form.show_plus.value) {
  1748. the_form.elements[wp].value += '+';
  1749. }
  1750. } else {
  1751. if (the_form.select_entire_list.value == 1 && the_form.show_plus.value) {
  1752. the_form.elements[wp].value = count + '+';
  1753. } else {
  1754. the_form.elements[wp].value = count;
  1755. }
  1756. }
  1757. }
  1758. }
  1759. }
  1760. }
  1761. sugarListView.prototype.use_external_mail_client = function(no_record_txt, module) {
  1762. selected_records = sugarListView.get_checks_count();
  1763. if(selected_records <1) {
  1764. alert(no_record_txt);
  1765. return false;
  1766. }
  1767. if (document.MassUpdate.select_entire_list.value == 1) {
  1768. if (totalCount > 10) {
  1769. alert(totalCountError);
  1770. return;
  1771. } // if
  1772. select = false;
  1773. }
  1774. else if (document.MassUpdate.massall.checked == true)
  1775. select = false;
  1776. else
  1777. select = true;
  1778. sugarListView.get_checks();
  1779. var ids = "";
  1780. if(select) { // use selected items
  1781. ids = document.MassUpdate.uid.value;
  1782. }
  1783. else { // use current page
  1784. inputs = document.MassUpdate.elements;
  1785. ar = new Array();
  1786. for(i = 0; i < inputs.length; i++) {
  1787. if(inputs[i].name == 'mass[]' && inputs[i].checked && typeof(inputs[i].value) != 'function') {
  1788. ar.push(inputs[i].value);
  1789. }
  1790. }
  1791. ids = ar.join(',');
  1792. }
  1793. YAHOO.util.Connect.asyncRequest("POST", "index.php?", {
  1794. success: this.use_external_mail_client_callback
  1795. }, SUGAR.util.paramsToUrl({
  1796. module: "Emails",
  1797. action: "Compose",
  1798. listViewExternalClient: 1,
  1799. action_module: module,
  1800. uid: ids,
  1801. to_pdf:1
  1802. }));
  1803. return false;
  1804. }
  1805. sugarListView.prototype.use_external_mail_client_callback = function(o)
  1806. {
  1807. if (o.responseText)
  1808. location.href = 'mailto:' + o.responseText;
  1809. }
  1810. sugarListView.prototype.send_form_for_emails = function(select, currentModule, action, no_record_txt,action_module,totalCount, totalCountError) {
  1811. if ( typeof(SUGAR.config.email_sugarclient_listviewmaxselect) != 'undefined' ) {
  1812. maxCount = 10;
  1813. }
  1814. else {
  1815. maxCount = SUGAR.config.email_sugarclient_listviewmaxselect;
  1816. }
  1817. if (document.MassUpdate.select_entire_list.value == 1) {
  1818. if (totalCount > maxCount) {
  1819. alert(totalCountError);
  1820. return;
  1821. } // if
  1822. select = false;
  1823. }
  1824. else if (document.MassUpdate.massall.checked == true)
  1825. select = false;
  1826. else
  1827. select = true;
  1828. sugarListView.get_checks();
  1829. // create new form to post (can't access action property of MassUpdate form due to action input)
  1830. var newForm = document.createElement('form');
  1831. newForm.method = 'post';
  1832. newForm.action = action;
  1833. newForm.name = 'newForm';
  1834. newForm.id = 'newForm';
  1835. var uidTa = document.createElement('textarea');
  1836. uidTa.name = 'uid';
  1837. uidTa.style.display = 'none';
  1838. if(select) { // use selected items
  1839. uidTa.value = document.MassUpdate.uid.value;
  1840. }
  1841. else { // use current page
  1842. inputs = document.MassUpdate.elements;
  1843. ar = new Array();
  1844. for(i = 0; i < inputs.length; i++) {
  1845. if(inputs[i].name == 'mass[]' && inputs[i].checked && typeof(inputs[i].value) != 'function') {
  1846. ar.push(inputs[i].value);
  1847. }
  1848. }
  1849. uidTa.value = ar.join(',');
  1850. }
  1851. if(uidTa.value == '') {
  1852. alert(no_record_txt);
  1853. return false;
  1854. }
  1855. var selectedArray = uidTa.value.split(",");
  1856. if(selectedArray.length > maxCount) {
  1857. alert(totalCountError);
  1858. return;
  1859. } // if
  1860. newForm.appendChild(uidTa);
  1861. var moduleInput = document.createElement('input');
  1862. moduleInput.name = 'module';
  1863. moduleInput.type = 'hidden';
  1864. moduleInput.value = currentModule;
  1865. newForm.appendChild(moduleInput);
  1866. var actionInput = document.createElement('input');
  1867. actionInput.name = 'action';
  1868. actionInput.type = 'hidden';
  1869. actionInput.value = 'Compose';
  1870. newForm.appendChild(actionInput);
  1871. if (typeof action_module != 'undefined' && action_module!= '') {
  1872. var actionModule = document.createElement('input');
  1873. actionModule.name = 'action_module';
  1874. actionModule.type = 'hidden';
  1875. actionModule.value = action_module;
  1876. newForm.appendChild(actionModule);
  1877. }
  1878. //return_info must follow this pattern."&return_module=Accounts&return_action=index"
  1879. if (typeof return_info!= 'undefined' && return_info != '') {
  1880. var params= return_info.split('&');
  1881. if (params.length > 0) {
  1882. for (var i=0;i< params.length;i++) {
  1883. if (params[i].length > 0) {
  1884. var param_nv=params[i].split('=');
  1885. if (param_nv.length==2){
  1886. returnModule = document.createElement('input');
  1887. returnModule.name = param_nv[0];
  1888. returnModule.type = 'hidden';
  1889. returnModule.value = param_nv[1];
  1890. newForm.appendChild(returnModule);
  1891. }
  1892. }
  1893. }
  1894. }
  1895. }
  1896. var isAjaxCall = document.createElement('input');
  1897. isAjaxCall.name = 'ajaxCall';
  1898. isAjaxCall.type = 'hidden';
  1899. isAjaxCall.value = true;
  1900. newForm.appendChild(isAjaxCall);
  1901. var isListView = document.createElement('input');
  1902. isListView.name = 'ListView';
  1903. isListView.type = 'hidden';
  1904. isListView.value = true;
  1905. newForm.appendChild(isListView);
  1906. var toPdf = document.createElement('input');
  1907. toPdf.name = 'to_pdf';
  1908. toPdf.type = 'hidden';
  1909. toPdf.value = true;
  1910. newForm.appendChild(toPdf);
  1911. //Grab the Quick Compose package for the listview
  1912. YAHOO.util.Connect.setForm(newForm);
  1913. var callback =
  1914. {
  1915. success: function(o) {
  1916. var resp = YAHOO.lang.JSON.parse(o.responseText);
  1917. var quickComposePackage = new Object();
  1918. quickComposePackage.composePackage = resp;
  1919. quickComposePackage.fullComposeUrl = 'index.php?module=Emails&action=Compose&ListView=true' +
  1920. '&uid=' + uidTa.value + '&action_module=' + action_module;
  1921. SUGAR.quickCompose.init(quickComposePackage);
  1922. }
  1923. }
  1924. YAHOO.util.Connect.asyncRequest('POST','index.php', callback,null);
  1925. // awu Bug 18624: Fixing issue where a canceled Export and unselect of row will persist the uid field, clear the field
  1926. document.MassUpdate.uid.value = '';
  1927. return false;
  1928. }
  1929. sugarListView.prototype.send_form = function(select, currentModule, action, no_record_txt,action_module,return_info) {
  1930. if (document.MassUpdate.select_entire_list.value == 1) {
  1931. if(sugarListView.get_checks_count() < 1) {
  1932. alert(no_record_txt);
  1933. return false;
  1934. }
  1935. var href = action;
  1936. if ( action.indexOf('?') != -1 )
  1937. href += '&module=' + currentModule;
  1938. else
  1939. href += '?module=' + currentModule;
  1940. if (return_info)
  1941. href += return_info;
  1942. var newForm = document.createElement('form');
  1943. newForm.method = 'post';
  1944. newForm.action = href;
  1945. newForm.name = 'newForm';
  1946. newForm.id = 'newForm';
  1947. var postTa = document.createElement('textarea');
  1948. postTa.name = 'current_post';
  1949. postTa.value = document.MassUpdate.current_query_by_page.value;
  1950. postTa.style.display = 'none';
  1951. newForm.appendChild(postTa);
  1952. document.MassUpdate.parentNode.appendChild(newForm);
  1953. newForm.submit();
  1954. return;
  1955. }
  1956. else if (document.MassUpdate.massall.checked == true)
  1957. select = false;
  1958. else
  1959. select = true;
  1960. sugarListView.get_checks();
  1961. // create new form to post (can't access action property of MassUpdate form due to action input)
  1962. var newForm = document.createElement('form');
  1963. newForm.method = 'post';
  1964. newForm.action = action;
  1965. newForm.name = 'newForm';
  1966. newForm.id = 'newForm';
  1967. var uidTa = document.createElement('textarea');
  1968. uidTa.name = 'uid';
  1969. uidTa.style.display = 'none';
  1970. uidTa.value = document.MassUpdate.uid.value;
  1971. if(uidTa.value == '') {
  1972. alert(no_record_txt);
  1973. return false;
  1974. }
  1975. newForm.appendChild(uidTa);
  1976. var moduleInput = document.createElement('input');
  1977. moduleInput.name = 'module';
  1978. moduleInput.type = 'hidden';
  1979. moduleInput.value = currentModule;
  1980. newForm.appendChild(moduleInput);
  1981. var actionInput = document.createElement('input');
  1982. actionInput.name = 'action';
  1983. actionInput.type = 'hidden';
  1984. actionInput.value = 'index';
  1985. newForm.appendChild(actionInput);
  1986. if (typeof action_module != 'undefined' && action_module!= '') {
  1987. var actionModule = document.createElement('input');
  1988. actionModule.name = 'action_module';
  1989. actionModule.type = 'hidden';
  1990. actionModule.value = action_module;
  1991. newForm.appendChild(actionModule);
  1992. }
  1993. //return_info must follow this pattern."&return_module=Accounts&return_action=index"
  1994. if (typeof return_info!= 'undefined' && return_info != '') {
  1995. var params= return_info.split('&');
  1996. if (params.length > 0) {
  1997. for (var i=0;i< params.length;i++) {
  1998. if (params[i].length > 0) {
  1999. var param_nv=params[i].split('=');
  2000. if (param_nv.length==2){
  2001. returnModule = document.createElement('input');
  2002. returnModule.name = param_nv[0];
  2003. returnModule.type = 'hidden';
  2004. returnModule.value = param_nv[1];
  2005. newForm.appendChild(returnModule);
  2006. }
  2007. }
  2008. }
  2009. }
  2010. }
  2011. document.MassUpdate.parentNode.appendChild(newForm);
  2012. newForm.submit();
  2013. // awu Bug 18624: Fixing issue where a canceled Export and unselect of row will persist the uid field, clear the field
  2014. document.MassUpdate.uid.value = '';
  2015. return false;
  2016. }
  2017. //return a count of checked row.
  2018. sugarListView.get_checks_count = function() {
  2019. ar = new Array();
  2020. if(document.MassUpdate.uid.value != '') {
  2021. oldUids = document.MassUpdate.uid.value.split(',');
  2022. for(uid in oldUids) {
  2023. if(typeof(oldUids[uid]) != 'function') {
  2024. ar[oldUids[uid]] = 1;
  2025. }
  2026. }
  2027. }
  2028. // build associated array of uids, associated array ensures uniqueness
  2029. inputs = document.MassUpdate.elements;
  2030. for(i = 0; i < inputs.length; i++) {
  2031. if(inputs[i].name == 'mass[]') {
  2032. ar[inputs[i].value] = (inputs[i].checked) ? 1 : 0; // 0 of it is unchecked
  2033. }
  2034. }
  2035. // build regular array of uids
  2036. uids = new Array();
  2037. for(i in ar) {
  2038. if((typeof(ar[i]) != 'function') && ar[i] == 1) {
  2039. uids.push(i);
  2040. }
  2041. }
  2042. return uids.length;
  2043. }
  2044. // saves the checks on the current page into the uid textarea
  2045. sugarListView.get_checks = function() {
  2046. ar = new Array();
  2047. if(typeof document.MassUpdate != 'undefined' ){
  2048. if(document.MassUpdate.uid.value != '') {
  2049. oldUids = document.MassUpdate.uid.value.split(',');
  2050. for(uid in oldUids) {
  2051. if(typeof(oldUids[uid]) != 'function') {
  2052. ar[oldUids[uid]] = 1;
  2053. }
  2054. }
  2055. }
  2056. // build associated array of uids, associated array ensures uniqueness
  2057. inputs = document.MassUpdate.elements;
  2058. for(i = 0; i < inputs.length; i++) {
  2059. if(inputs[i].name == 'mass[]') {
  2060. ar[inputs[i].value] = (inputs[i].checked) ? 1 : 0; // 0 of it is unchecked
  2061. }
  2062. }
  2063. // build regular array of uids
  2064. uids = new Array();
  2065. for(i in ar) {
  2066. if(typeof(ar[i]) != 'function' && ar[i] == 1) {
  2067. uids.push(i);
  2068. }
  2069. }
  2070. document.MassUpdate.uid.value = uids.join(',');
  2071. if(uids.length == 0) return false; // return false if no checks to get
  2072. return true; // there are saved checks
  2073. }
  2074. else return false;
  2075. }
  2076. sugarListView.prototype.order_checks = function(order,orderBy,moduleString){
  2077. checks = sugarListView.get_checks();
  2078. eval('document.MassUpdate.' + moduleString + '.value = orderBy');
  2079. document.MassUpdate.lvso.value = order;
  2080. if(typeof document.MassUpdate.massupdate != 'undefined') {
  2081. document.MassUpdate.massupdate.value = 'false';
  2082. }
  2083. //we must first clear the action of massupdate, change it to index
  2084. document.MassUpdate.action.value = document.MassUpdate.return_action.value;
  2085. document.MassUpdate.return_module.value='';
  2086. document.MassUpdate.return_action.value='';
  2087. document.MassUpdate.submit();
  2088. return !checks;
  2089. }
  2090. sugarListView.prototype.save_checks = function(offset, moduleString) {
  2091. checks = sugarListView.get_checks();
  2092. if(typeof document.MassUpdate != 'undefined'){
  2093. eval('document.MassUpdate.' + moduleString + '.value = offset');
  2094. if(typeof document.MassUpdate.massupdate != 'undefined') {
  2095. document.MassUpdate.massupdate.value = 'false';
  2096. }
  2097. //we must first clear the action of massupdate, change it to index
  2098. document.MassUpdate.action.value = document.MassUpdate.return_action.value;
  2099. document.MassUpdate.return_module.value='';
  2100. document.MassUpdate.return_action.value='';
  2101. document.MassUpdate.submit();
  2102. return !checks;
  2103. }
  2104. else return false;
  2105. }
  2106. sugarListView.prototype.check_item = function(cb, form) {
  2107. if(cb.checked) {
  2108. sugarListView.update_count(1, true);
  2109. }else{
  2110. sugarListView.update_count(-1, true);
  2111. if(typeof form != 'undefined' && form != null) {
  2112. sugarListView.prototype.updateUid(cb, form);
  2113. }
  2114. }
  2115. sugarListView.prototype.toggleSelected();
  2116. }
  2117. sugarListView.prototype.toggleSelected = function() {
  2118. var numSelected = sugarListView.get_num_selected();
  2119. var selectedRecords = document.getElementById("selectedRecordsTop");
  2120. var selectActions = document.getElementById("selectActions");
  2121. var selectActionsDisabled = document.getElementById("selectActionsDisabled");
  2122. if(numSelected > 0) {
  2123. $(selectedRecords).removeAttr("style").addClass("show");
  2124. $(".selectActionsDisabled").hide();
  2125. jQuery('ul[name=selectActions]').each(function () {
  2126. jQuery(this).removeAttr("style").addClass("show");
  2127. });
  2128. } else {
  2129. $(selectedRecords).hide();
  2130. $(".selectActionsDisabled").removeAttr("style").addClass("show");
  2131. jQuery('ul[name=selectActions]').each(function () {
  2132. jQuery(this).hide();
  2133. });
  2134. }
  2135. }
  2136. /**#28000, remove the unselect record id from MassUpdate.uid **/
  2137. sugarListView.prototype.updateUid = function(cb , form){
  2138. if(form.name == 'MassUpdate' && form.uid && form.uid.value && cb.value && form.uid.value.indexOf(cb.value) != -1){
  2139. if(form.uid.value.indexOf(','+cb.value)!= -1){
  2140. form.uid.value = form.uid.value.replace(','+cb.value , '');
  2141. }else if(form.uid.value.indexOf(cb.value + ',')!= -1){
  2142. form.uid.value = form.uid.value.replace(cb.value + ',' , '');
  2143. }else if(form.uid.value.indexOf(cb.value)!= -1){
  2144. form.uid.value = form.uid.value.replace(cb.value , '');
  2145. }
  2146. }
  2147. }
  2148. sugarListView.prototype.check_entire_list = function(form, field, value, list_count) {
  2149. // count number of items
  2150. count = 0;
  2151. $(document.MassUpdate.massall).each(function(){
  2152. $(this).attr('checked', true).attr('disabled', true);
  2153. });
  2154. for (i = 0; i < form.elements.length; i++) {
  2155. if(form.elements[i].name == field && form.elements[i].disabled == false) {
  2156. if(form.elements[i].checked != value) count++;
  2157. form.elements[i].checked = value;
  2158. form.elements[i].disabled = true;
  2159. }
  2160. }
  2161. document.MassUpdate.select_entire_list.value = 1;
  2162. sugarListView.update_count(list_count, false);
  2163. sugarListView.prototype.toggleSelected();
  2164. }
  2165. sugarListView.prototype.check_all = function(form, field, value, pageTotal) {
  2166. // count number of items
  2167. count = 0;
  2168. $(document.MassUpdate.massall).each(function(){$(this).attr('checked', value);});
  2169. if (document.MassUpdate.select_entire_list &&
  2170. document.MassUpdate.select_entire_list.value == 1)
  2171. {
  2172. sugarListView.prototype.toggleSelected();
  2173. $(document.MassUpdate.massall).each(function(){$(this).attr('disabled', true);});
  2174. }
  2175. else
  2176. {
  2177. $(document.MassUpdate.massall).each(function(){$(this).attr('disabled', false);});
  2178. }
  2179. for (i = 0; i < form.elements.length; i++) {
  2180. if(form.elements[i].name == field && !(form.elements[i].disabled == true && form.elements[i].checked == false)) {
  2181. form.elements[i].disabled = false;
  2182. if(form.elements[i].checked != value)
  2183. count++;
  2184. form.elements[i].checked = value;
  2185. if(!value){
  2186. sugarListView.prototype.updateUid(form.elements[i], form);
  2187. }
  2188. }
  2189. }
  2190. if (pageTotal >= 0)
  2191. sugarListView.update_count(pageTotal);
  2192. else if(value)
  2193. sugarListView.update_count(count, true);
  2194. else
  2195. sugarListView.update_count(-1 * count, true);
  2196. sugarListView.prototype.toggleSelected();
  2197. }
  2198. sugarListView.check_all = sugarListView.prototype.check_all;
  2199. sugarListView.confirm_action = sugarListView.prototype.confirm_action;
  2200. sugarListView.prototype.check_boxes = function() {
  2201. var inputsCount = 0;
  2202. var checkedCount = 0;
  2203. var existing_onload = window.onload;
  2204. var theForm = document.MassUpdate;
  2205. inputs_array = theForm.elements;
  2206. if(typeof theForm.uid.value != 'undefined' && theForm.uid.value != "") {
  2207. checked_items = theForm.uid.value.split(",");
  2208. if (theForm.select_entire_list.value == 1) {
  2209. document.MassUpdate.massall.disabled = true;
  2210. sugarListView.prototype.toggleSelected();
  2211. $("a[name=selectall]:first").click();
  2212. }
  2213. for(var wp = 0 ; wp < inputs_array.length; wp++) {
  2214. if(inputs_array[wp].name == "mass[]") {
  2215. inputsCount++;
  2216. if (theForm.select_entire_list.value == 1) {
  2217. inputs_array[wp].checked = true;
  2218. inputs_array[wp].disabled = true;
  2219. checkedCount++;
  2220. }
  2221. else {
  2222. for(i in checked_items) {
  2223. if(inputs_array[wp].value == checked_items[i]) {
  2224. checkedCount++;
  2225. inputs_array[wp].checked = true;
  2226. //Bug#52748: Total # of checked items are calculated in back-end side
  2227. //sugarListView.prototype.check_item(inputs_array[wp], document.MassUpdate);
  2228. }
  2229. }
  2230. }
  2231. }
  2232. }
  2233. }
  2234. else {
  2235. for(var wp = 0 ; wp < inputs_array.length; wp++) {
  2236. if(inputs_array[wp].name == "mass[]") {
  2237. inputs_array[wp].checked = false;
  2238. inputs_array[wp].disabled = false;
  2239. }
  2240. }
  2241. if (document.MassUpdate.massall) {
  2242. document.MassUpdate.massall.checked = false;
  2243. document.MassUpdate.massall.disabled = false;
  2244. }
  2245. sugarListView.update_count(0)
  2246. }
  2247. if(checkedCount > 0 && checkedCount == inputsCount)
  2248. document.MassUpdate.massall.checked = true;
  2249. }
  2250. /**
  2251. * This function is used in Email Template Module's listview.
  2252. * It will check whether the templates are used in Campaing->EmailMarketing.
  2253. * If true, it will notify user.
  2254. */
  2255. function check_used_email_templates() {
  2256. var ids = document.MassUpdate.uid.value;
  2257. var call_back = {
  2258. success:function(r) {
  2259. if(r.responseText != '') {
  2260. if(!confirm(SUGAR.language.get('app_strings','NTC_TEMPLATES_IS_USED') + r.responseText)) {
  2261. return false;
  2262. }
  2263. }
  2264. document.MassUpdate.submit();
  2265. return false;
  2266. }
  2267. };
  2268. url = "index.php?module=EmailTemplates&action=CheckDeletable&from=ListView&to_pdf=1&records="+ids;
  2269. YAHOO.util.Connect.asyncRequest('POST',url, call_back,null);
  2270. }
  2271. sugarListView.prototype.send_mass_update = function(mode, no_record_txt, del) {
  2272. formValid = check_form('MassUpdate');
  2273. if(!formValid && !del) return false;
  2274. if (document.MassUpdate.select_entire_list &&
  2275. document.MassUpdate.select_entire_list.value == 1)
  2276. mode = 'entire';
  2277. else
  2278. mode = 'selected';
  2279. var ar = new Array();
  2280. switch(mode) {
  2281. case 'selected':
  2282. for(var wp = 0; wp < document.MassUpdate.elements.length; wp++) {
  2283. var reg_for_existing_uid = new RegExp('^'+RegExp.escape(document.MassUpdate.elements[wp].value)+'[\s]*,|,[\s]*'+RegExp.escape(document.MassUpdate.elements[wp].value)+'[\s]*,|,[\s]*'+RegExp.escape(document.MassUpdate.elements[wp].value)+'$|^'+RegExp.escape(document.MassUpdate.elements[wp].value)+'$');
  2284. //when the uid is already in document.MassUpdate.uid.value, we should not add it to ar.
  2285. if(typeof document.MassUpdate.elements[wp].name != 'undefined'
  2286. && document.MassUpdate.elements[wp].name == 'mass[]'
  2287. && document.MassUpdate.elements[wp].checked
  2288. && !reg_for_existing_uid.test(document.MassUpdate.uid.value)) {
  2289. ar.push(document.MassUpdate.elements[wp].value);
  2290. }
  2291. }
  2292. if(document.MassUpdate.uid.value != '') document.MassUpdate.uid.value += ',';
  2293. document.MassUpdate.uid.value += ar.join(',');
  2294. if(document.MassUpdate.uid.value == '') {
  2295. alert(no_record_txt);
  2296. return false;
  2297. }
  2298. if(typeof(current_admin_id)!='undefined' && document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'Users' && (document.MassUpdate.is_admin.value!='' || document.MassUpdate.status.value!='')) {
  2299. var reg_for_current_admin_id = new RegExp('^'+current_admin_id+'[\s]*,|,[\s]*'+current_admin_id+'[\s]*,|,[\s]*'+current_admin_id+'$|^'+current_admin_id+'$');
  2300. if(reg_for_current_admin_id.test(document.MassUpdate.uid.value)) {
  2301. //if current user is admin, we should not allow massupdate the user_type and status of himself
  2302. alert(SUGAR.language.get('Users','LBL_LAST_ADMIN_NOTICE'));
  2303. return false;
  2304. }
  2305. }
  2306. break;
  2307. case 'entire':
  2308. var entireInput = document.createElement('input');
  2309. entireInput.name = 'entire';
  2310. entireInput.type = 'hidden';
  2311. entireInput.value = 'index';
  2312. document.MassUpdate.appendChild(entireInput);
  2313. //confirm(no_record_txt);
  2314. if(document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'Users' && (document.MassUpdate.is_admin.value!='' || document.MassUpdate.status.value!='')) {
  2315. alert(SUGAR.language.get('Users','LBL_LAST_ADMIN_NOTICE'));
  2316. return false;
  2317. }
  2318. break;
  2319. }
  2320. if(!sugarListView.confirm_action(del))
  2321. return false;
  2322. if(del == 1) {
  2323. var deleteInput = document.createElement('input');
  2324. deleteInput.name = 'Delete';
  2325. deleteInput.type = 'hidden';
  2326. deleteInput.value = true;
  2327. document.MassUpdate.appendChild(deleteInput);
  2328. if(document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'EmailTemplates') {
  2329. check_used_email_templates();
  2330. return false;
  2331. }
  2332. }
  2333. document.MassUpdate.submit();
  2334. return false;
  2335. }
  2336. sugarListView.prototype.clear_all = function() {
  2337. document.MassUpdate.uid.value = '';
  2338. document.MassUpdate.select_entire_list.value = 0;
  2339. sugarListView.check_all(document.MassUpdate, 'mass[]', false);
  2340. $(document.MassUpdate.massall).each(function(){
  2341. $(this).attr('checked', false).attr('disabled', false);
  2342. });
  2343. sugarListView.update_count(0);
  2344. sugarListView.prototype.toggleSelected();
  2345. }
  2346. sListView = new sugarListView();
  2347. // -- end sugarListView class
  2348. // format and unformat numbers
  2349. function unformatNumber(n, num_grp_sep, dec_sep) {
  2350. var x=unformatNumberNoParse(n, num_grp_sep, dec_sep);
  2351. x=x.toString();
  2352. if(x.length > 0) {
  2353. return parseFloat(x);
  2354. }
  2355. return '';
  2356. }
  2357. function unformatNumberNoParse(n, num_grp_sep, dec_sep) {
  2358. if(typeof num_grp_sep == 'undefined' || typeof dec_sep == 'undefined') return n;
  2359. n = n ? n.toString() : '';
  2360. if(n.length > 0) {
  2361. if(num_grp_sep != '')
  2362. {
  2363. num_grp_sep_re = new RegExp('\\'+num_grp_sep, 'g');
  2364. n = n.replace(num_grp_sep_re, '');
  2365. }
  2366. n = n.replace(dec_sep, '.');
  2367. if(typeof CurrencySymbols != 'undefined') {
  2368. // Need to strip out the currency symbols from the start.
  2369. for ( var idx in CurrencySymbols ) {
  2370. n = n.replace(CurrencySymbols[idx], '');
  2371. }
  2372. }
  2373. return n;
  2374. }
  2375. return '';
  2376. }
  2377. // round parameter can be negative for decimal, precision has to be postive
  2378. function formatNumber(n, num_grp_sep, dec_sep, round, precision) {
  2379. if(typeof num_grp_sep == 'undefined' || typeof dec_sep == 'undefined') return n;
  2380. n = n ? n.toString() : '';
  2381. if(n.split) n = n.split('.');
  2382. else return n;
  2383. if(n.length > 2) return n.join('.'); // that's not a num!
  2384. // round
  2385. if(typeof round != 'undefined') {
  2386. if(round > 0 && n.length > 1) { // round to decimal
  2387. n[1] = parseFloat('0.' + n[1]);
  2388. n[1] = Math.round(n[1] * Math.pow(10, round)) / Math.pow(10, round);
  2389. n[1] = n[1].toString().split('.')[1];
  2390. }
  2391. if(round <= 0) { // round to whole number
  2392. n[0] = Math.round(parseInt(n[0],10) * Math.pow(10, round)) / Math.pow(10, round);
  2393. n[1] = '';
  2394. }
  2395. }
  2396. if(typeof precision != 'undefined' && precision >= 0) {
  2397. if(n.length > 1 && typeof n[1] != 'undefined') n[1] = n[1].substring(0, precision); // cut off precision
  2398. else n[1] = '';
  2399. if(n[1].length < precision) {
  2400. for(var wp = n[1].length; wp < precision; wp++) n[1] += '0';
  2401. }
  2402. }
  2403. regex = /(\d+)(\d{3})/;
  2404. while(num_grp_sep != '' && regex.test(n[0])) n[0] = n[0].toString().replace(regex, '$1' + num_grp_sep + '$2');
  2405. return n[0] + (n.length > 1 && n[1] != '' ? dec_sep + n[1] : '');
  2406. }
  2407. // --- begin ajax status class
  2408. SUGAR.ajaxStatusClass = function() {};
  2409. SUGAR.ajaxStatusClass.prototype.statusDiv = null;
  2410. SUGAR.ajaxStatusClass.prototype.oldOnScroll = null;
  2411. SUGAR.ajaxStatusClass.prototype.shown = false; // state of the status window
  2412. // reposition the status div, top and centered
  2413. SUGAR.ajaxStatusClass.prototype.positionStatus = function() {
  2414. //this.statusDiv.style.top = document.body.scrollTop + 8 + 'px';
  2415. statusDivRegion = YAHOO.util.Dom.getRegion(this.statusDiv);
  2416. statusDivWidth = statusDivRegion.right - statusDivRegion.left;
  2417. this.statusDiv.style.left = YAHOO.util.Dom.getViewportWidth() / 2 - statusDivWidth / 2 + 'px';
  2418. }
  2419. // private func, create the status div
  2420. SUGAR.ajaxStatusClass.prototype.createStatus = function(text) {
  2421. statusDiv = document.createElement('div');
  2422. statusDiv.className = 'dataLabel';
  2423. statusDiv.id = 'ajaxStatusDiv';
  2424. document.body.appendChild(statusDiv);
  2425. this.statusDiv = document.getElementById('ajaxStatusDiv');
  2426. }
  2427. // public - show the status div with text
  2428. SUGAR.ajaxStatusClass.prototype.showStatus = function(text) {
  2429. if(!this.statusDiv) {
  2430. this.createStatus(text);
  2431. }
  2432. else {
  2433. this.statusDiv.style.display = '';
  2434. }
  2435. this.statusDiv.innerHTML = '&nbsp;<b>' + text + '</b>&nbsp;';
  2436. this.positionStatus();
  2437. if(!this.shown) {
  2438. this.shown = true;
  2439. this.statusDiv.style.display = '';
  2440. if(window.onscroll) this.oldOnScroll = window.onscroll; // save onScroll
  2441. window.onscroll = this.positionStatus;
  2442. }
  2443. }
  2444. // public - hide it
  2445. SUGAR.ajaxStatusClass.prototype.hideStatus = function(text) {
  2446. if(!this.shown) return;
  2447. this.shown = false;
  2448. if(this.oldOnScroll) window.onscroll = this.oldOnScroll;
  2449. else window.onscroll = '';
  2450. this.statusDiv.style.display = 'none';
  2451. }
  2452. SUGAR.ajaxStatusClass.prototype.flashStatus = function(text, time){
  2453. this.showStatus(text);
  2454. window.setTimeout('ajaxStatus.hideStatus();', time);
  2455. }
  2456. var ajaxStatus = new SUGAR.ajaxStatusClass();
  2457. // --- end ajax status class
  2458. /**
  2459. * Unified Search Advanced - for global search
  2460. */
  2461. SUGAR.unifiedSearchAdvanced = function() {
  2462. var usa_div;
  2463. var usa_img;
  2464. var usa_open;
  2465. var usa_content;
  2466. var anim_open;
  2467. var anim_close;
  2468. return {
  2469. init: function() {
  2470. SUGAR.unifiedSearchAdvanced.usa_div = document.getElementById('unified_search_advanced_div');
  2471. SUGAR.unifiedSearchAdvanced.usa_img = document.getElementById('unified_search_advanced_img');
  2472. if(!SUGAR.unifiedSearchAdvanced.usa_div || !SUGAR.unifiedSearchAdvanced.usa_img) return;
  2473. var attributes = { height: { to: 300 } };
  2474. SUGAR.unifiedSearchAdvanced.anim_open = new YAHOO.util.Anim('unified_search_advanced_div', attributes );
  2475. SUGAR.unifiedSearchAdvanced.anim_open.duration = 0.75;
  2476. SUGAR.unifiedSearchAdvanced.anim_close = new YAHOO.util.Anim('unified_search_advanced_div', { height: {to: 0} } );
  2477. SUGAR.unifiedSearchAdvanced.anim_close.duration = 0.75;
  2478. //SUGAR.unifiedSearchAdvanced.anim_close.onComplete.subscribe(function() {SUGAR.unifiedSearchAdvanced.usa_div.style.display = 'none'});
  2479. SUGAR.unifiedSearchAdvanced.usa_img._x = YAHOO.util.Dom.getX(SUGAR.unifiedSearchAdvanced.usa_img);
  2480. SUGAR.unifiedSearchAdvanced.usa_img._y = YAHOO.util.Dom.getY(SUGAR.unifiedSearchAdvanced.usa_img);
  2481. SUGAR.unifiedSearchAdvanced.usa_open = false;
  2482. SUGAR.unifiedSearchAdvanced.usa_content = null;
  2483. YAHOO.util.Event.addListener('unified_search_advanced_img', 'click', SUGAR.unifiedSearchAdvanced.get_content);
  2484. },
  2485. get_content: function(e)
  2486. {
  2487. query_string = trim(document.getElementById('query_string').value);
  2488. if(query_string != '')
  2489. {
  2490. window.location.href = 'index.php?module=Home&action=UnifiedSearch&query_string=' + query_string;
  2491. } else {
  2492. window.location.href = 'index.php?module=Home&action=UnifiedSearch&form_only=true';
  2493. }
  2494. },
  2495. animate: function(data) {
  2496. ajaxStatus.hideStatus();
  2497. if(data) {
  2498. SUGAR.unifiedSearchAdvanced.usa_content = data.responseText;
  2499. SUGAR.unifiedSearchAdvanced.usa_div.innerHTML = SUGAR.unifiedSearchAdvanced.usa_content;
  2500. }
  2501. if(SUGAR.unifiedSearchAdvanced.usa_open) {
  2502. document.UnifiedSearch.advanced.value = 'false';
  2503. SUGAR.unifiedSearchAdvanced.anim_close.animate();
  2504. }
  2505. else {
  2506. document.UnifiedSearch.advanced.value = 'true';
  2507. SUGAR.unifiedSearchAdvanced.usa_div.style.display = '';
  2508. YAHOO.util.Dom.setX(SUGAR.unifiedSearchAdvanced.usa_div, SUGAR.unifiedSearchAdvanced.usa_img._x - 90);
  2509. YAHOO.util.Dom.setY(SUGAR.unifiedSearchAdvanced.usa_div, SUGAR.unifiedSearchAdvanced.usa_img._y + 15);
  2510. SUGAR.unifiedSearchAdvanced.anim_open.animate();
  2511. }
  2512. SUGAR.unifiedSearchAdvanced.usa_open = !SUGAR.unifiedSearchAdvanced.usa_open;
  2513. return false;
  2514. },
  2515. checkUsaAdvanced: function() {
  2516. if(document.UnifiedSearch.advanced.value == 'true') {
  2517. document.UnifiedSearchAdvanced.query_string.value = document.UnifiedSearch.query_string.value;
  2518. document.UnifiedSearchAdvanced.submit();
  2519. return false;
  2520. }
  2521. return true;
  2522. }
  2523. };
  2524. }();
  2525. if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.unifiedSearchAdvanced.init);
  2526. SUGAR.ui = {
  2527. /**
  2528. * Toggles the header
  2529. */
  2530. toggleHeader : function() {
  2531. var h = document.getElementById('header');
  2532. if(h != null) {
  2533. if(h != null) {
  2534. if(h.style.display == 'none') {
  2535. h.style.display = '';
  2536. } else {
  2537. h.style.display = 'none';
  2538. }
  2539. }
  2540. } else {
  2541. alert(SUGAR.language.get("app_strings", "ERR_NO_HEADER_ID"));
  2542. }
  2543. }
  2544. };
  2545. /**
  2546. * General Sugar Utils
  2547. */
  2548. SUGAR.util = function () {
  2549. var additionalDetailsCache;
  2550. var additionalDetailsCalls;
  2551. var additionalDetailsRpcCall;
  2552. return {
  2553. getAndRemove : function (el) {
  2554. if (YAHOO && YAHOO.util && YAHOO.util.Dom)
  2555. el = YAHOO.util.Dom.get(el);
  2556. else if (typeof (el) == "string")
  2557. el = document.getElementById(el);
  2558. if (el && el.parentNode)
  2559. el.parentNode.removeChild(el);
  2560. return el;
  2561. },
  2562. paramsToUrl : function (params) {
  2563. var parts = [];
  2564. for (var i in params)
  2565. {
  2566. if (params.hasOwnProperty(i))
  2567. {
  2568. parts.push(encodeURIComponent(i) + '=' + encodeURIComponent(params[i]));
  2569. }
  2570. }
  2571. return parts.join("&")+"&";
  2572. },
  2573. // Evaluates a script in a global context
  2574. // Workarounds based on findings by Jim Driscoll
  2575. // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
  2576. globalEval: function( data ) {
  2577. var rnotwhite = /\S/;
  2578. if ( data && rnotwhite.test( data ) ) {
  2579. // We use execScript on Internet Explorer
  2580. // We use an anonymous function so that context is window
  2581. // rather than jQuery in Firefox
  2582. ( window.execScript || function( data ) {
  2583. window[ "eval" ].call( window, data );
  2584. } )( data );
  2585. }
  2586. },
  2587. evalScript:function(text){
  2588. if (isSafari) {
  2589. var waitUntilLoaded = function(){
  2590. SUGAR.evalScript_waitCount--;
  2591. if (SUGAR.evalScript_waitCount == 0) {
  2592. var headElem = document.getElementsByTagName('head')[0];
  2593. for ( var i = 0; i < SUGAR.evalScript_evalElem.length; i++) {
  2594. var tmpElem = document.createElement('script');
  2595. tmpElem.type = 'text/javascript';
  2596. tmpElem.text = SUGAR.evalScript_evalElem[i];
  2597. headElem.appendChild(tmpElem);
  2598. }
  2599. }
  2600. };
  2601. var tmpElem = document.createElement('div');
  2602. tmpElem.innerHTML = text;
  2603. var results = tmpElem.getElementsByTagName('script');
  2604. if (results == null) {
  2605. // No scripts found, bail out
  2606. return;
  2607. }
  2608. var headElem = document.getElementsByTagName('head')[0];
  2609. var tmpElem = null;
  2610. SUGAR.evalScript_waitCount = 0;
  2611. SUGAR.evalScript_evalElem = new Array();
  2612. for (var i = 0; i < results.length; i++) {
  2613. if (typeof(results[i]) != 'object') {
  2614. continue;
  2615. };
  2616. tmpElem = document.createElement('script');
  2617. tmpElem.type = 'text/javascript';
  2618. if (results[i].src != null && results[i].src != '') {
  2619. tmpElem.src = results[i].src;
  2620. } else {
  2621. // Need to defer execution of these scripts until the
  2622. // required javascript files are fully loaded
  2623. SUGAR.evalScript_evalElem[SUGAR.evalScript_evalElem.length] = results[i].text;
  2624. continue;
  2625. }
  2626. tmpElem.addEventListener('load', waitUntilLoaded);
  2627. SUGAR.evalScript_waitCount++;
  2628. headElem.appendChild(tmpElem);
  2629. }
  2630. // Add some code to handle pages without any external scripts
  2631. SUGAR.evalScript_waitCount++;
  2632. waitUntilLoaded();
  2633. // Don't try and process things the IE way
  2634. return;
  2635. }
  2636. var objRegex = /<\s*script([^>]*)>((.|\s|\v|\0)*?)<\s*\/script\s*>/igm;
  2637. var lastIndex = -1;
  2638. var result = objRegex.exec(text);
  2639. while(result && result.index > lastIndex){
  2640. lastIndex = result.index
  2641. try{
  2642. // Bug #49205 : Subpanels fail to load when selecting subpanel tab
  2643. // Change approach to handle javascripts included to body of ajax response.
  2644. // To load & run javascripts and inline javascript in correct order load them as synchronous requests
  2645. // JQuery library uses this approach to eval scripts
  2646. if(result[1].indexOf("src=") > -1){
  2647. var srcRegex = /.*src=['"]([a-zA-Z0-9_\-\&\/\.\?=:-]*)['"].*/igm;
  2648. var srcResult = result[1].replace(srcRegex, '$1');
  2649. // Check is ulr cross domain or not
  2650. var r1 = /:\/\//igm;
  2651. if ( r1.test(srcResult) && srcResult.indexOf(window.location.hostname) == -1 )
  2652. {
  2653. // if script is cross domain it cannot be loaded via ajax request
  2654. // try load script asynchronous by creating script element in the body
  2655. // YUI 3.3 doesn't allow load scrips synchronously
  2656. // YUI 3.5 do it
  2657. YUI().use('get', function (Y)
  2658. {
  2659. var url = srcResult;
  2660. Y.Get.script(srcResult,
  2661. {
  2662. autopurge: false,
  2663. onSuccess : function(o) { },
  2664. onFailure: function(o) { },
  2665. onTimeout: function(o) { }
  2666. });
  2667. });
  2668. // TODO: for YUI 3.5 - load scripts as script object synchronous
  2669. /*
  2670. YUI().use('get', function (Y) {
  2671. var url = srcResult;
  2672. Y.Get.js([{url: url, async: false}], function (err) {});
  2673. });
  2674. */
  2675. }
  2676. else
  2677. {
  2678. // Bug #49205 : Subpanels fail to load when selecting subpanel tab
  2679. // Create a YUI instance using the io-base module.
  2680. (function (srcResult) {
  2681. YUI().use("io-base",function(Y)
  2682. {
  2683. var cfg,response;
  2684. cfg={
  2685. method:'GET',
  2686. sync:true,
  2687. on:{
  2688. success:function(transactionid,response,arguments)
  2689. {
  2690. SUGAR.util.globalEval(response.responseText);
  2691. }
  2692. }
  2693. };
  2694. // Call synchronous request to load javascript content
  2695. // restonse will be processed in success function
  2696. response=Y.io(srcResult,cfg);
  2697. });
  2698. })(srcResult);
  2699. }
  2700. }else{
  2701. // Bug #49205 : Subpanels fail to load when selecting subpanel tab
  2702. // execute script in global context
  2703. // Bug #57288 : don't eval with html comment-out script; that causes syntax error in IE
  2704. var srcRegex = /<!--([\s\S]*?)-->/;
  2705. var srcResult = srcRegex.exec(result[2]);
  2706. if (srcResult && srcResult.index > -1)
  2707. {
  2708. SUGAR.util.globalEval(srcResult[1]);
  2709. }
  2710. else
  2711. {
  2712. SUGAR.util.globalEval(result[2]);
  2713. }
  2714. }
  2715. }
  2716. catch(e) {
  2717. if(typeof(console) != "undefined" && typeof(console.log) == "function")
  2718. {
  2719. console.log("error adding script");
  2720. console.log(e);
  2721. console.log(result);
  2722. }
  2723. }
  2724. result = objRegex.exec(text);
  2725. }
  2726. },
  2727. /**
  2728. * Gets the sidebar object
  2729. * @return object pointer to the sidebar element
  2730. */
  2731. getLeftColObj: function() {
  2732. leftColObj = document.getElementById('leftCol');
  2733. while(leftColObj.nodeName != 'TABLE') {
  2734. leftColObj = leftColObj.firstChild;
  2735. }
  2736. leftColTable = leftColObj;
  2737. leftColTd = leftColTable.getElementsByTagName('td')[0];
  2738. leftColTdRegion = YAHOO.util.Dom.getRegion(leftColTd);
  2739. leftColTd.style.width = (leftColTdRegion.right - leftColTdRegion.left) + 'px';
  2740. return leftColTd;
  2741. },
  2742. /**
  2743. * Fills the shortcut menu placeholders w/ actual content
  2744. * Call this on load event
  2745. *
  2746. * @param shortcutContent Array array of content to fill in
  2747. */
  2748. fillShortcuts: function(e, shortcutContent) {
  2749. return ;
  2750. /*
  2751. // don't do this if leftCol isn't available
  2752. if (document.getElementById('leftCol') == undefined) { return; }
  2753. spans = document.getElementById('leftCol').getElementsByTagName('span');
  2754. hideCol = document.getElementById('HideMenu').getElementsByTagName('span');
  2755. w = spans.length + 1;
  2756. for(i in hideCol) {
  2757. spans[w] = hideCol[i];
  2758. w++;
  2759. }
  2760. for(je in shortcutContent) {
  2761. for(wp in spans) {
  2762. if(typeof spans[wp].innerHTML != 'undefined' && spans[wp].innerHTML == ('wp_shortcut_fill_' + je)) {
  2763. if(typeof spans[wp].parentNode.parentNode == 'object') {
  2764. if(typeof spans[wp].parentNode.parentNode.onclick != 'undefined') {
  2765. spans[wp].parentNode.parentNode.onclick = null;
  2766. }
  2767. // If the wp_shortcut span is contained by an A tag, replace the A with a DIV.
  2768. if(spans[wp].parentNode.tagName == 'A' && !isIE) {
  2769. var newDiv = document.createElement('DIV');
  2770. var parentAnchor = spans[wp].parentNode;
  2771. spans[wp].parentNode.parentNode.style.display = 'none';
  2772. // Copy styles over to the new container div
  2773. if(window.getComputedStyle) {
  2774. var parentStyle = window.getComputedStyle(parentAnchor, '');
  2775. for(var styleName in parentStyle) {
  2776. if(typeof parentStyle[styleName] != 'function'
  2777. && styleName != 'display'
  2778. && styleName != 'borderWidth'
  2779. && styleName != 'visibility') {
  2780. try {
  2781. newDiv.style[styleName] = parentStyle[styleName];
  2782. } catch(e) {
  2783. // Catches .length and .parentRule, and others
  2784. }
  2785. }
  2786. }
  2787. }
  2788. // Replace the A with the DIV
  2789. newDiv.appendChild(spans[wp]);
  2790. parentAnchor.parentNode.replaceChild(newDiv, parentAnchor);
  2791. spans[wp].parentNode.parentNode.style.display = '';
  2792. }
  2793. }
  2794. spans[wp].innerHTML = shortcutContent[je]; // fill w/ content
  2795. if(spans[wp].style) spans[wp].style.display = '';
  2796. }
  2797. }
  2798. }*/
  2799. },
  2800. /**
  2801. * Make an AJAX request.
  2802. *
  2803. * @param url string resource to load
  2804. * @param theDiv string id of element to insert loaded data into
  2805. * @param postForm string if set, a POST request will be made to resource specified by url using the form named by postForm
  2806. * @param callback string name of function to invoke after HTTP response is recieved
  2807. * @param callbackParam any parameter to pass to callback when invoked
  2808. * @param appendMode bool if true, HTTP response will be appended to the contents of theDiv, or else contents will be overriten.
  2809. */
  2810. retrieveAndFill: function(url, theDiv, postForm, callback, callbackParam, appendMode) {
  2811. if(typeof theDiv == 'string') {
  2812. try {
  2813. theDiv = document.getElementById(theDiv);
  2814. }
  2815. catch(e) {
  2816. return;
  2817. }
  2818. }
  2819. var success = function(data) {
  2820. if (typeof theDiv != 'undefined' && theDiv != null)
  2821. {
  2822. try {
  2823. if (typeof appendMode != 'undefined' && appendMode)
  2824. {
  2825. theDiv.insertAdjacentHTML('beforeend', data.responseText);
  2826. }
  2827. else
  2828. {
  2829. theDiv.innerHTML = data.responseText;
  2830. }
  2831. }
  2832. catch (e) {
  2833. return;
  2834. }
  2835. }
  2836. if (typeof callback != 'undefined' && callback != null) callback(callbackParam);
  2837. }
  2838. if(typeof postForm == 'undefined' || postForm == null) {
  2839. var cObj = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
  2840. }
  2841. else {
  2842. YAHOO.util.Connect.setForm(postForm);
  2843. var cObj = YAHOO.util.Connect.asyncRequest('POST', url, {success: success, failure: success});
  2844. }
  2845. },
  2846. checkMaxLength: function() { // modified from http://www.quirksmode.org/dom/maxlength.html
  2847. var maxLength = this.getAttribute('maxlength');
  2848. var currentLength = this.value.length;
  2849. if (currentLength > maxLength) {
  2850. this.value = this.value.substring(0, maxLength);
  2851. }
  2852. // not innerHTML
  2853. },
  2854. /**
  2855. * Adds maxlength attribute to textareas
  2856. */
  2857. setMaxLength: function() { // modified from http://www.quirksmode.org/dom/maxlength.html
  2858. var x = document.getElementsByTagName('textarea');
  2859. for (var i=0;i<x.length;i++) {
  2860. if (x[i].getAttribute('maxlength')) {
  2861. x[i].onkeyup = x[i].onchange = SUGAR.util.checkMaxLength;
  2862. x[i].onkeyup();
  2863. }
  2864. }
  2865. },
  2866. /**
  2867. * Renders Query UI Help Dialog
  2868. */
  2869. showHelpTips: function(el,helpText,myPos,atPos,id) {
  2870. if(myPos == undefined || myPos == "") {
  2871. myPos = "left top";
  2872. }
  2873. if(atPos == undefined || atPos == "") {
  2874. atPos = "right top";
  2875. }
  2876. var pos = $(el).offset(),
  2877. ofWidth = $(el).width(),
  2878. elmId = id || 'helpTip' + pos.left + '_' + ofWidth,
  2879. $dialog = elmId ? ( $("#"+elmId).length > 0 ? $("#"+elmId) : $('<div></div>').attr("id", elmId) ) : $('<div></div>');
  2880. $dialog.html(helpText)
  2881. .dialog({
  2882. autoOpen: false,
  2883. title: SUGAR.language.get('app_strings', 'LBL_HELP'),
  2884. position: {
  2885. my: myPos,
  2886. at: atPos,
  2887. of: $(el)
  2888. }
  2889. });
  2890. var width = $dialog.dialog( "option", "width" );
  2891. if((pos.left + ofWidth) - 40 < width) {
  2892. $dialog.dialog("option","position",{my: 'left top',at: 'right top',of: $(el)}) ;
  2893. }
  2894. $dialog.dialog('open');
  2895. $(".ui-dialog").appendTo("#content");
  2896. },
  2897. getStaticAdditionalDetails: function(el, body, caption, show_buttons) {
  2898. if(typeof show_buttons == "undefined") {
  2899. show_buttons = false;
  2900. }
  2901. $(".ui-dialog").find(".open").dialog("close");
  2902. var $dialog = $('<div class="open"></div>')
  2903. .html(body)
  2904. .dialog({
  2905. autoOpen: false,
  2906. title: caption,
  2907. width: 300,
  2908. position: {
  2909. my: 'right top',
  2910. at: 'left top',
  2911. of: $(el)
  2912. }
  2913. });
  2914. if(show_buttons) {
  2915. $(".ui-dialog").find('.ui-dialog-titlebar-close').css("display","none");
  2916. $(".ui-dialog").find('.ui-dialog-title').css("width","100%");
  2917. }
  2918. var width = $dialog.dialog( "option", "width" );
  2919. var pos = $(el).offset();
  2920. var ofWidth = $(el).width();
  2921. if((pos.left + ofWidth) - 40 < width) {
  2922. $dialog.dialog("option","position",{my: 'left top',at: 'right top',of: $(el)}) ;
  2923. }
  2924. $dialog.dialog('open');
  2925. $(".ui-dialog").appendTo("#content");
  2926. },
  2927. closeStaticAdditionalDetails: function() {
  2928. $(".ui-dialog").find(".open").dialog("close");
  2929. },
  2930. /**
  2931. * Retrieves additional details dynamically
  2932. */
  2933. getAdditionalDetails: function(bean, id, spanId, show_buttons) {
  2934. if(typeof show_buttons == "undefined")
  2935. show_buttons = false;
  2936. var el = '#'+spanId;
  2937. go = function() {
  2938. oReturn = function(body, caption, width, theme) {
  2939. $(".ui-dialog").find(".open").dialog("close");
  2940. var $dialog = $('<div class="open"></div>')
  2941. .html(body)
  2942. .dialog({
  2943. autoOpen: false,
  2944. title: caption,
  2945. width: 300,
  2946. position: {
  2947. my: 'right top',
  2948. at: 'left top',
  2949. of: $(el)
  2950. }
  2951. });
  2952. if(show_buttons) {
  2953. $(".ui-dialog").find('.ui-dialog-titlebar-close').css("display","none");
  2954. $(".ui-dialog").find('.ui-dialog-title').css("width","100%");
  2955. }
  2956. var width = $dialog.dialog( "option", "width" );
  2957. var pos = $(el).offset();
  2958. var ofWidth = $(el).width();
  2959. if((pos.left + ofWidth) - 40 < width) {
  2960. $dialog.dialog("option","position",{my: 'left top',at: 'right top',of: $(el)}) ;
  2961. }
  2962. $dialog.dialog('open');
  2963. $(".ui-dialog").appendTo("#content");
  2964. }
  2965. success = function(data) {
  2966. eval(data.responseText);
  2967. SUGAR.util.additionalDetailsCache[id] = new Array();
  2968. SUGAR.util.additionalDetailsCache[id]['body'] = result['body'];
  2969. SUGAR.util.additionalDetailsCache[id]['caption'] = result['caption'];
  2970. SUGAR.util.additionalDetailsCache[id]['width'] = result['width'];
  2971. SUGAR.util.additionalDetailsCache[id]['theme'] = result['theme'];
  2972. ajaxStatus.hideStatus();
  2973. return oReturn(SUGAR.util.additionalDetailsCache[id]['body'], SUGAR.util.additionalDetailsCache[id]['caption'], SUGAR.util.additionalDetailsCache[id]['width'], SUGAR.util.additionalDetailsCache[id]['theme']);
  2974. }
  2975. if(typeof SUGAR.util.additionalDetailsCache[id] != 'undefined')
  2976. return oReturn(SUGAR.util.additionalDetailsCache[id]['body'], SUGAR.util.additionalDetailsCache[id]['caption'], SUGAR.util.additionalDetailsCache[id]['width'], SUGAR.util.additionalDetailsCache[id]['theme']);
  2977. if(typeof SUGAR.util.additionalDetailsCalls[id] != 'undefined') // call already in progress
  2978. return;
  2979. ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_LOADING'));
  2980. url = 'index.php?to_pdf=1&module=Home&action=AdditionalDetailsRetrieve&bean=' + bean + '&id=' + id;
  2981. if(show_buttons)
  2982. url += '&show_buttons=true';
  2983. SUGAR.util.additionalDetailsCalls[id] = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
  2984. return false;
  2985. }
  2986. SUGAR.util.additionalDetailsRpcCall = window.setTimeout('go()', 250);
  2987. },
  2988. clearAdditionalDetailsCall: function() {
  2989. if(typeof SUGAR.util.additionalDetailsRpcCall == 'number') window.clearTimeout(SUGAR.util.additionalDetailsRpcCall);
  2990. },
  2991. /**
  2992. * A function that extends functionality from parent to child.
  2993. */
  2994. extend : function(subc, superc, overrides) {
  2995. subc.prototype = new superc; // set the superclass
  2996. // overrides
  2997. if (overrides) {
  2998. for (var i in overrides) subc.prototype[i] = overrides[i];
  2999. }
  3000. },
  3001. hrefURL : function(url) {
  3002. if(SUGAR.isIE) {
  3003. // IE needs special treatment since otherwise it would not pass Referer
  3004. var trampoline = document.createElement('a');
  3005. trampoline.href = url;
  3006. document.body.appendChild(trampoline);
  3007. trampoline.click();
  3008. document.body.removeChild(trampoline);
  3009. } else {
  3010. document.location.href = url;
  3011. }
  3012. },
  3013. openWindow : function(URL, windowName, windowFeatures) {
  3014. if(SUGAR.isIE) {
  3015. // IE needs special treatment since otherwise it would not pass Referer
  3016. win = window.open('', windowName, windowFeatures);
  3017. var trampoline = document.createElement('a');
  3018. trampoline.href = URL;
  3019. trampoline.target = windowName;
  3020. document.body.appendChild(trampoline);
  3021. trampoline.click();
  3022. document.body.removeChild(trampoline);
  3023. } else {
  3024. win = window.open(URL, windowName, windowFeatures);
  3025. }
  3026. return win;
  3027. },
  3028. //Reset the scroll on the window
  3029. top : function() {
  3030. window.scroll(0,0);
  3031. },
  3032. //Based on YUI onAvailible, but will use any boolean function instead of an ID
  3033. doWhen : function(condition, fn, params, scope)
  3034. {
  3035. this._doWhenStack.push({
  3036. check:condition,
  3037. fn: fn,
  3038. obj: params,
  3039. overrideContext: scope
  3040. });
  3041. this._doWhenretryCount = 50;
  3042. this._startDoWhenInterval();
  3043. },
  3044. _startDoWhenInterval : function(){
  3045. if (!this._doWhenInterval) {
  3046. this._doWhenInterval = YAHOO.lang.later(50, this, this._doWhenCheck, null, true);
  3047. }
  3048. },
  3049. _doWhenStack : [],
  3050. _doWhenInterval : false,
  3051. _doWhenCheck : function() {
  3052. if (this._doWhenStack.length === 0) {
  3053. this._doWhenretryCount = 0;
  3054. if (this._doWhenInterval) {
  3055. // clearInterval(this._interval);
  3056. this._doWhenInterval.cancel();
  3057. this._doWhenInterval = null;
  3058. }
  3059. return;
  3060. }
  3061. if (this._doWhenLocked) {
  3062. return;
  3063. }
  3064. if (SUGAR.isIE) {
  3065. // Hold off if DOMReady has not fired and check current
  3066. // readyState to protect against the IE operation aborted
  3067. // issue.
  3068. if (!YAHOO.util.Event.DOMReady) {
  3069. this._startDoWhenInterval();
  3070. return;
  3071. }
  3072. }
  3073. this._doWhenLocked = true;
  3074. // keep trying until after the page is loaded. We need to
  3075. // check the page load state prior to trying to bind the
  3076. // elements so that we can be certain all elements have been
  3077. // tested appropriately
  3078. var tryAgain = YAHOO.util.Event.DOMReady;
  3079. if (!tryAgain) {
  3080. tryAgain = (this._doWhenretryCount > 0 && this._doWhenStack.length > 0);
  3081. }
  3082. // onAvailable
  3083. var notAvail = [];
  3084. var executeItem = function (context, item) {
  3085. if (item.overrideContext) {
  3086. if (item.overrideContext === true) {
  3087. context = item.obj;
  3088. } else {
  3089. context = item.overrideContext;
  3090. }
  3091. }
  3092. if(item.fn) {
  3093. item.fn.call(context, item.obj);
  3094. }
  3095. };
  3096. var i, len, item, test;
  3097. // onAvailable onContentReady
  3098. for (i=0, len=this._doWhenStack.length; i<len; i=i+1) {
  3099. item = this._doWhenStack[i];
  3100. if (item) {
  3101. test = item.check;
  3102. if ((typeof(test) == "string" && eval(test)) || (typeof(test) == "function" && test())) {
  3103. executeItem(this, item);
  3104. this._doWhenStack[i] = null;
  3105. }
  3106. else {
  3107. notAvail.push(item);
  3108. }
  3109. }
  3110. }
  3111. this._doWhenretryCount--;
  3112. if (tryAgain) {
  3113. for (i=this._doWhenStack.length-1; i>-1; i--) {
  3114. item = this._doWhenStack[i];
  3115. if (!item || !item.check) {
  3116. this._doWhenStack.splice(i, 1);
  3117. }
  3118. }
  3119. this._startDoWhenInterval();
  3120. } else {
  3121. if (this._doWhenInterval) {
  3122. // clearInterval(this._interval);
  3123. this._doWhenInterval.cancel();
  3124. this._doWhenInterval = null;
  3125. }
  3126. }
  3127. this._doWhenLocked = false;
  3128. },
  3129. buildAccessKeyLabels : function() {
  3130. if (typeof(Y.env.ua) !== 'undefined'){
  3131. envStr = '';
  3132. browserOS = Y.env.ua['os'];
  3133. isIE = Y.env.ua['ie'];
  3134. isCR = Y.env.ua['chrome'];
  3135. isFF = Y.env.ua['gecko'];
  3136. isWK = Y.env.ua['webkit'];
  3137. isOP = Y.env.ua['opera'];
  3138. controlKey = '';
  3139. //first determine the OS
  3140. if(browserOS=='macintosh'){
  3141. //we got a mac, lets use the mac specific commands while we check the browser
  3142. if(isIE){
  3143. //IE on a Mac? Not possible, but let's assign alt anyways for completions sake
  3144. controlKey = 'Alt+';
  3145. }else if(isWK || isFF){
  3146. //Chrome or safari on a mac
  3147. //firefox moved to webkit standard starting with FF14
  3148. controlKey = 'Ctrl+Opt+';
  3149. }else if(isOP){
  3150. //Opera on a mac
  3151. controlKey = 'Shift+Esc: ';
  3152. }else{
  3153. //default for everything else on a mac
  3154. controlKey = 'Ctrl+';
  3155. }
  3156. }else{
  3157. //this is not a mac so let's use the windows/unix commands while we check the browser
  3158. if(isFF){
  3159. //FF on windows/unix
  3160. controlKey = 'Alt+Shift+';
  3161. }else if(isOP){
  3162. //Opera on windows/unix
  3163. controlKey = 'Shift+Esc: ';
  3164. }else {
  3165. //this is the default for safari, IE and Chrome
  3166. //if this is webkit and is NOT google, then we are most likely looking at Safari
  3167. controlKey = 'Alt+';
  3168. }
  3169. }
  3170. //now lets retrieve all elements of type input
  3171. allButtons = document.getElementsByTagName('input');
  3172. //iterate through list and modify title if the accesskey is not empty
  3173. for(i=0;i<allButtons.length;i++){
  3174. if(allButtons[i].getAttribute('accesskey') && allButtons[i].getAttribute('type') && allButtons[i].getAttribute('type')=='button'){
  3175. allButtons[i].setAttribute('title',allButtons[i].getAttribute('title')+' ['+controlKey+allButtons[i].getAttribute('accesskey')+']');
  3176. }
  3177. }
  3178. //now change the text in the help div
  3179. $("#shortcuts_dialog").html(function(i, text) {
  3180. return text.replace(/Alt\+/g,controlKey);
  3181. });
  3182. }// end if (typeof(Y.env.ua) !== 'undefined')
  3183. }//end buildAccessKeyLabels()
  3184. };
  3185. }(); // end util
  3186. SUGAR.util.additionalDetailsCache = new Array();
  3187. SUGAR.util.additionalDetailsCalls = new Array();
  3188. if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.util.setMaxLength); // allow textareas to obey maxlength attrib
  3189. SUGAR.savedViews = function() {
  3190. var selectedOrderBy;
  3191. var selectedSortOrder;
  3192. var displayColumns;
  3193. var hideTabs;
  3194. var columnsMeta; // meta data for the display columns
  3195. return {
  3196. setChooser: function() {
  3197. var displayColumnsDef = new Array();
  3198. var hideTabsDef = new Array();
  3199. var left_td = document.getElementById('display_tabs_td');
  3200. if(typeof left_td == 'undefined' || left_td == null) return; // abort!
  3201. var right_td = document.getElementById('hide_tabs_td');
  3202. var displayTabs = left_td.getElementsByTagName('select')[0];
  3203. var hideTabs = right_td.getElementsByTagName('select')[0];
  3204. for(i = 0; i < displayTabs.options.length; i++) {
  3205. displayColumnsDef.push(displayTabs.options[i].value);
  3206. }
  3207. if(typeof hideTabs != 'undefined') {
  3208. for(i = 0; i < hideTabs.options.length; i++) {
  3209. hideTabsDef.push(hideTabs.options[i].value);
  3210. }
  3211. }
  3212. if (!SUGAR.savedViews.clearColumns)
  3213. document.getElementById('displayColumnsDef').value = displayColumnsDef.join('|');
  3214. document.getElementById('hideTabsDef').value = hideTabsDef.join('|');
  3215. },
  3216. select: function(saved_search_select) {
  3217. for(var wp = 0; wp < document.search_form.saved_search_select.options.length; wp++) {
  3218. if(typeof document.search_form.saved_search_select.options[wp].value != 'undefined' &&
  3219. document.search_form.saved_search_select.options[wp].value == saved_search_select) {
  3220. document.search_form.saved_search_select.selectedIndex = wp;
  3221. document.search_form.ss_delete.style.display = '';
  3222. document.search_form.ss_update.style.display = '';
  3223. }
  3224. }
  3225. },
  3226. saved_search_action: function(action, delete_lang) {
  3227. if(action == 'delete') {
  3228. if(!confirm(delete_lang)) return;
  3229. }
  3230. if(action == 'save') {
  3231. if(document.search_form.saved_search_name.value.replace(/^\s*|\s*$/g, '') == '') {
  3232. alert(SUGAR.language.get('app_strings', 'LBL_SAVED_SEARCH_ERROR'));
  3233. return;
  3234. }
  3235. }
  3236. // This check is needed for the Activities module (Calls/Meetings/Tasks).
  3237. if (document.search_form.saved_search_action)
  3238. {
  3239. document.search_form.saved_search_action.value = action;
  3240. document.search_form.search_module.value = document.search_form.module.value;
  3241. document.search_form.module.value = 'SavedSearch';
  3242. // Bug 31922 - Make sure to specify that we want to hit the index view here of
  3243. // the SavedSearch module, since the ListView doesn't have the logic to save the
  3244. // search and redirect back
  3245. document.search_form.action.value = 'index';
  3246. }
  3247. SUGAR.ajaxUI.submitForm(document.search_form);
  3248. },
  3249. shortcut_select: function(selectBox, module) {
  3250. //build url
  3251. selecturl = 'index.php?module=SavedSearch&search_module=' + module + '&action=index&saved_search_select=' + selectBox.options[selectBox.selectedIndex].value
  3252. //add searchFormTab to url if it is available. This determines what tab to render
  3253. if(typeof(document.getElementById('searchFormTab'))!='undefined'){
  3254. selecturl = selecturl + '&searchFormTab=' + document.search_form.searchFormTab.value;
  3255. }
  3256. //add showSSDIV to url if it is available. This determines whether saved search sub form should
  3257. //be rendered open or not
  3258. if(document.getElementById('showSSDIV') && typeof(document.getElementById('showSSDIV') !='undefined')){
  3259. selecturl = selecturl + '&showSSDIV='+document.getElementById('showSSDIV').value;
  3260. }
  3261. //use created url to navigate
  3262. document.location.href = selecturl;
  3263. },
  3264. handleForm: function() {
  3265. SUGAR.tabChooser.movementCallback = function(left_side, right_side) {
  3266. while(document.getElementById('orderBySelect').childNodes.length != 0) { // clear out order by options
  3267. document.getElementById('orderBySelect').removeChild(document.getElementById('orderBySelect').lastChild);
  3268. }
  3269. var selectedIndex = 0;
  3270. var nodeCount = -1; // need this because the counter i also includes "undefined" nodes
  3271. // which was breaking Calls and Meetings
  3272. for(i in left_side.childNodes) { // fill in order by options
  3273. if(typeof left_side.childNodes[i].nodeName != 'undefined' &&
  3274. left_side.childNodes[i].nodeName.toLowerCase() == 'option' &&
  3275. typeof SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value] != 'undefined' && // check if column is sortable
  3276. typeof SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value]['sortable'] == 'undefined' &&
  3277. SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value]['sortable'] != false) {
  3278. nodeCount++;
  3279. optionNode = document.createElement('option');
  3280. optionNode.value = left_side.childNodes[i].value;
  3281. optionNode.innerHTML = left_side.childNodes[i].innerHTML;
  3282. document.getElementById('orderBySelect').appendChild(optionNode);
  3283. if(optionNode.value == SUGAR.savedViews.selectedOrderBy)
  3284. selectedIndex = nodeCount;
  3285. }
  3286. }
  3287. // Firefox needs this to be set after all the option nodes are created.
  3288. document.getElementById('orderBySelect').selectedIndex = selectedIndex;
  3289. };
  3290. SUGAR.tabChooser.movementCallback(document.getElementById('display_tabs_td').getElementsByTagName('select')[0]);
  3291. // This check is needed for the Activities module (Calls/Meetings/Tasks).
  3292. if (document.search_form.orderBy)
  3293. {
  3294. if (document.search_form.orderBy.length > 1 && document.search_form.orderBy[1].type == 'select-one')
  3295. {
  3296. document.search_form.orderBy[1].options.value = SUGAR.savedViews.selectedOrderBy;
  3297. }
  3298. else
  3299. {
  3300. document.search_form.orderBy.options.value = SUGAR.savedViews.selectedOrderBy;
  3301. }
  3302. }
  3303. // handle direction
  3304. if(SUGAR.savedViews.selectedSortOrder == 'DESC') document.getElementById('sort_order_desc_radio').checked = true;
  3305. else document.getElementById('sort_order_asc_radio').checked = true;
  3306. }
  3307. };
  3308. }();
  3309. SUGAR.searchForm = function() {
  3310. var url;
  3311. return {
  3312. // searchForm tab selector util
  3313. searchFormSelect: function(view, previousView) {
  3314. var module = view.split('|')[0];
  3315. var theView = view.split('|')[1];
  3316. // retrieve form
  3317. var handleDisplay = function() { // hide other divs
  3318. document.search_form.searchFormTab.value = theView;
  3319. patt = module+"(.*)SearchForm$";
  3320. divId=document.search_form.getElementsByTagName('div');
  3321. // Hide all the search forms and retrive the name of the previous search tab (useful for the first load because previousView is empty)
  3322. for (i=0;i<divId.length;i++){
  3323. if(divId[i].id.match(module)==module){
  3324. if(divId[i].id.match('SearchForm')=='SearchForm'){
  3325. if(document.getElementById(divId[i].id).style.display == ''){
  3326. previousTab=divId[i].id.match(patt)[1];
  3327. }
  3328. document.getElementById(divId[i].id).style.display = 'none';
  3329. }
  3330. }
  3331. }
  3332. //clear thesearch form accesekeys and reset them to the appropriate link
  3333. adv = document.getElementById('advanced_search_link');
  3334. bas = document.getElementById('basic_search_link');
  3335. adv.setAttribute('accesskey','');
  3336. bas.setAttribute('accesskey','');
  3337. a_key = SUGAR.language.get("app_strings", "LBL_ADV_SEARCH_LNK_KEY");
  3338. //reset the ccesskey based on theview
  3339. if(theView === 'advanced_search'){
  3340. bas.setAttribute('accesskey',a_key);
  3341. }else{
  3342. adv.setAttribute('accesskey',a_key);
  3343. }
  3344. // show the good search form.
  3345. document.getElementById(module + theView + 'SearchForm').style.display = '';
  3346. //if its not the first tab show there is a previous tab.
  3347. if(previousView) {
  3348. thepreviousView=previousView.split('|')[1];
  3349. }
  3350. else{
  3351. thepreviousView=previousTab;
  3352. }
  3353. thepreviousView=thepreviousView.replace(/_search/, "");
  3354. // Process to retrieve the completed field from one tab to an other.
  3355. for(num in document.search_form.elements) {
  3356. if(document.search_form.elements[num]) {
  3357. el = document.search_form.elements[num];
  3358. pattern="^(.*)_"+thepreviousView+"$";
  3359. if(typeof el.type != 'undefined' && typeof el.name != 'undefined' && el.name.match(pattern)) {
  3360. advanced_input_name = el.name.match(pattern)[1]; // strip
  3361. advanced_input_name = advanced_input_name+"_"+theView.replace(/_search/, "");
  3362. if(typeof document.search_form[advanced_input_name] != 'undefined') // if advanced input of same name exists
  3363. SUGAR.searchForm.copyElement(advanced_input_name, el);
  3364. }
  3365. }
  3366. }
  3367. // Remove the previously selected div, so that only data from current div to be sent as form data to the server-side
  3368. if (document.getElementById(module + thepreviousView + '_search' + 'SearchForm'))
  3369. {
  3370. document.getElementById(module + thepreviousView + '_search' + 'SearchForm').innerHTML = '';
  3371. }
  3372. }
  3373. // if tab is not cached
  3374. if(document.getElementById(module + theView + 'SearchForm').innerHTML == '') {
  3375. ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_LOADING'));
  3376. var success = function(data) {
  3377. document.getElementById(module + theView + 'SearchForm').innerHTML = data.responseText;
  3378. SUGAR.util.evalScript(data.responseText);
  3379. // pass script variables to global scope
  3380. if(theView == 'saved_views') {
  3381. if(typeof columnsMeta != 'undefined') SUGAR.savedViews.columnsMeta = columnsMeta;
  3382. if(typeof selectedOrderBy != 'undefined') SUGAR.savedViews.selectedOrderBy = selectedOrderBy;
  3383. if(typeof selectedSortOrder != 'undefined') SUGAR.savedViews.selectedSortOrder = selectedSortOrder;
  3384. }
  3385. handleDisplay();
  3386. enableQS(true);
  3387. ajaxStatus.hideStatus();
  3388. }
  3389. url = 'index.php?module=' + module + '&action=index&search_form_only=true&to_pdf=true&search_form_view=' + theView;
  3390. //check to see if tpl has been specified. If so then pass location through url string
  3391. var tpl ='';
  3392. if(document.getElementById('search_tpl') !=null && typeof(document.getElementById('search_tpl')) != 'undefined'){
  3393. tpl = document.getElementById('search_tpl').value;
  3394. if(tpl != ''){url += '&search_tpl='+tpl;}
  3395. }
  3396. if(theView == 'saved_views') // handle the tab chooser
  3397. url += '&displayColumns=' + SUGAR.savedViews.displayColumns + '&hideTabs=' + SUGAR.savedViews.hideTabs + '&orderBy=' + SUGAR.savedViews.selectedOrderBy + '&sortOrder=' + SUGAR.savedViews.selectedSortOrder;
  3398. var cObj = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
  3399. }
  3400. else { // that form already retrieved
  3401. handleDisplay();
  3402. }
  3403. },
  3404. // copies one input to another
  3405. copyElement: function(inputName, copyFromElement) {
  3406. switch(copyFromElement.type) {
  3407. case 'select-one':
  3408. case 'text':
  3409. document.search_form[inputName].value = copyFromElement.value;
  3410. break;
  3411. }
  3412. },
  3413. // This function is here to clear the form, instead of "resubmitting it
  3414. clear_form: function(form, skipElementNames) {
  3415. var elemList = form.elements;
  3416. var elem;
  3417. var elemType;
  3418. for( var i = 0; i < elemList.length ; i++ ) {
  3419. elem = elemList[i];
  3420. if ( typeof(elem.type) == 'undefined' ) {
  3421. continue;
  3422. }
  3423. if ( typeof(elem.type) != 'undefined' && typeof(skipElementNames) != 'undefined'
  3424. && SUGAR.util.arrayIndexOf(skipElementNames, elem.name) != -1 )
  3425. {
  3426. continue;
  3427. }
  3428. elemType = elem.type.toLowerCase();
  3429. if ( elemType == 'text' || elemType == 'textarea' || elemType == 'password' ) {
  3430. elem.value = '';
  3431. } else if (elemType == 'select-one') {
  3432. // We have, what I hope, is a select box, time to unselect all options
  3433. var optionList = elem.options,
  3434. selectedIndex = 0;
  3435. for (var ii = 0; ii < optionList.length; ii++) {
  3436. if (optionList[ii].value == '') {
  3437. selectedIndex = ii;
  3438. break;
  3439. }
  3440. }
  3441. if (optionList.length > 0) {
  3442. optionList[selectedIndex].selected = "selected";
  3443. }
  3444. } else if (elemType == 'select-multiple') {
  3445. var optionList = elem.options;
  3446. for ( var ii = 0 ; ii < optionList.length ; ii++ ) {
  3447. optionList[ii].selected = false;
  3448. }
  3449. }
  3450. else if ( elemType == 'radio' || elemType == 'checkbox' ) {
  3451. elem.checked = false;
  3452. elem.selected = false;
  3453. }
  3454. else if ( elemType == 'hidden' ) {
  3455. if (
  3456. // For bean selection
  3457. elem.name.indexOf("_id") != -1
  3458. // For custom fields
  3459. || elem.name.indexOf("_c") != -1
  3460. // For advanced fields, like team collection, or datetime fields
  3461. || elem.name.indexOf("_advanced") != -1
  3462. )
  3463. {
  3464. elem.value = '';
  3465. }
  3466. }
  3467. }
  3468. // If there are any collections
  3469. if (typeof(collection) !== 'undefined')
  3470. {
  3471. // Loop through all the collections on the page and run clean_up()
  3472. for (key in collection)
  3473. {
  3474. // Clean up only removes blank fields, if any
  3475. collection[key].clean_up();
  3476. }
  3477. }
  3478. SUGAR.searchForm.clearBasicSearchOrderToDefault(form);
  3479. SUGAR.savedViews.clearColumns = true;
  3480. },
  3481. // This function sets sorting to default Sugar values after BasicSearch Clear button is pressed
  3482. clearBasicSearchOrderToDefault: function(form)
  3483. {
  3484. if(form.elements['searchFormTab']){
  3485. var formType = form.elements['searchFormTab'].value;
  3486. if (formType == 'basic_search')
  3487. {
  3488. form.elements['orderBy'].value = 'DATE_ENTERED';
  3489. form.elements['sortOrder'].value = 'DESC';
  3490. }
  3491. }
  3492. }
  3493. };
  3494. }();
  3495. // Code for the column/tab chooser used on homepage and in admin section
  3496. SUGAR.tabChooser = function () {
  3497. var object_refs = new Array();
  3498. return {
  3499. /* Describe certain transfers as invalid */
  3500. frozenOptions: [],
  3501. movementCallback: function(left_side, right_side) {},
  3502. orderCallback: function(left_side, right_side) {},
  3503. freezeOptions: function(left_name, right_name, target) {
  3504. if(!SUGAR.tabChooser.frozenOptions) { SUGAR.tabChooser.frozenOptions = []; }
  3505. if(!SUGAR.tabChooser.frozenOptions[left_name]) { SUGAR.tabChooser.frozenOptions[left_name] = []; }
  3506. if(!SUGAR.tabChooser.frozenOptions[left_name][right_name]) { SUGAR.tabChooser.frozenOptions[left_name][right_name] = []; }
  3507. if(typeof target == 'array') {
  3508. for(var i in target) {
  3509. SUGAR.tabChooser.frozenOptions[left_name][right_name][target[i]] = true;
  3510. }
  3511. } else {
  3512. SUGAR.tabChooser.frozenOptions[left_name][right_name][target] = true;
  3513. }
  3514. },
  3515. buildSelectHTML: function(info) {
  3516. var text = "<select";
  3517. if(typeof (info['select']['size']) != 'undefined') {
  3518. text +=" size=\""+ info['select']['size'] +"\"";
  3519. }
  3520. if(typeof (info['select']['name']) != 'undefined') {
  3521. text +=" name=\""+ info['select']['name'] +"\"";
  3522. }
  3523. if(typeof (info['select']['style']) != 'undefined') {
  3524. text +=" style=\""+ info['select']['style'] +"\"";
  3525. }
  3526. if(typeof (info['select']['onchange']) != 'undefined') {
  3527. text +=" onChange=\""+ info['select']['onchange'] +"\"";
  3528. }
  3529. if(typeof (info['select']['multiple']) != 'undefined') {
  3530. text +=" multiple";
  3531. }
  3532. text +=">";
  3533. for(i=0; i<info['options'].length;i++) {
  3534. option = info['options'][i];
  3535. text += "<option value=\""+option['value']+"\" ";
  3536. if ( typeof (option['selected']) != 'undefined' && option['selected']== true) {
  3537. text += "SELECTED";
  3538. }
  3539. text += ">"+option['text']+"</option>";
  3540. }
  3541. text += "</select>";
  3542. return text;
  3543. },
  3544. left_to_right: function(left_name, right_name, left_size, right_size) {
  3545. SUGAR.savedViews.clearColumns = false;
  3546. var left_td = document.getElementById(left_name+'_td');
  3547. var right_td = document.getElementById(right_name+'_td');
  3548. var display_columns_ref = left_td.getElementsByTagName('select')[0];
  3549. var hidden_columns_ref = right_td.getElementsByTagName('select')[0];
  3550. var selected_left = new Array();
  3551. var notselected_left = new Array();
  3552. var notselected_right = new Array();
  3553. var left_array = new Array();
  3554. var frozen_options = SUGAR.tabChooser.frozenOptions;
  3555. frozen_options = frozen_options && frozen_options[left_name] && frozen_options[left_name][right_name]?frozen_options[left_name][right_name]:[];
  3556. // determine which options are selected in left
  3557. for (i=0; i < display_columns_ref.options.length; i++)
  3558. {
  3559. if ( display_columns_ref.options[i].selected == true && !frozen_options[display_columns_ref.options[i].value])
  3560. {
  3561. selected_left[selected_left.length] = {text: display_columns_ref.options[i].text, value: display_columns_ref.options[i].value};
  3562. }
  3563. else
  3564. {
  3565. notselected_left[notselected_left.length] = {text: display_columns_ref.options[i].text, value: display_columns_ref.options[i].value};
  3566. }
  3567. }
  3568. for (i=0; i < hidden_columns_ref.options.length; i++)
  3569. {
  3570. notselected_right[notselected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
  3571. }
  3572. var left_select_html_info = new Object();
  3573. var left_options = new Array();
  3574. var left_select = new Object();
  3575. left_select['name'] = left_name+'[]';
  3576. left_select['id'] = left_name;
  3577. left_select['size'] = left_size;
  3578. left_select['multiple'] = 'true';
  3579. var right_select_html_info = new Object();
  3580. var right_options = new Array();
  3581. var right_select = new Object();
  3582. right_select['name'] = right_name+'[]';
  3583. right_select['id'] = right_name;
  3584. right_select['size'] = right_size;
  3585. right_select['multiple'] = 'true';
  3586. for (i = 0; i < notselected_right.length; i++) {
  3587. right_options[right_options.length] = notselected_right[i];
  3588. }
  3589. for (i = 0; i < selected_left.length; i++) {
  3590. right_options[right_options.length] = selected_left[i];
  3591. }
  3592. for (i = 0; i < notselected_left.length; i++) {
  3593. left_options[left_options.length] = notselected_left[i];
  3594. }
  3595. left_select_html_info['options'] = left_options;
  3596. left_select_html_info['select'] = left_select;
  3597. right_select_html_info['options'] = right_options;
  3598. right_select_html_info['select'] = right_select;
  3599. right_select_html_info['style'] = 'background: lightgrey';
  3600. var left_html = this.buildSelectHTML(left_select_html_info);
  3601. var right_html = this.buildSelectHTML(right_select_html_info);
  3602. left_td.innerHTML = left_html;
  3603. right_td.innerHTML = right_html;
  3604. object_refs[left_name] = left_td.getElementsByTagName('select')[0];
  3605. object_refs[right_name] = right_td.getElementsByTagName('select')[0];
  3606. this.movementCallback(object_refs[left_name], object_refs[right_name]);
  3607. return false;
  3608. },
  3609. right_to_left: function(left_name, right_name, left_size, right_size, max_left) {
  3610. SUGAR.savedViews.clearColumns = false;
  3611. var left_td = document.getElementById(left_name+'_td');
  3612. var right_td = document.getElementById(right_name+'_td');
  3613. var display_columns_ref = left_td.getElementsByTagName('select')[0];
  3614. var hidden_columns_ref = right_td.getElementsByTagName('select')[0];
  3615. var selected_right = new Array();
  3616. var notselected_right = new Array();
  3617. var notselected_left = new Array();
  3618. var frozen_options = SUGAR.tabChooser.frozenOptions;
  3619. frozen_options = SUGAR.tabChooser.frozenOptions && SUGAR.tabChooser.frozenOptions[right_name] && SUGAR.tabChooser.frozenOptions[right_name][left_name]?SUGAR.tabChooser.frozenOptions[right_name][left_name]:[];
  3620. for (i=0; i < hidden_columns_ref.options.length; i++)
  3621. {
  3622. if (hidden_columns_ref.options[i].selected == true && !frozen_options[hidden_columns_ref.options[i].value])
  3623. {
  3624. selected_right[selected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
  3625. }
  3626. else
  3627. {
  3628. notselected_right[notselected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
  3629. }
  3630. }
  3631. if(max_left != '' && (display_columns_ref.length + selected_right.length) > max_left) {
  3632. alert('Maximum of ' + max_left + ' columns can be displayed.');
  3633. return;
  3634. }
  3635. for (i=0; i < display_columns_ref.options.length; i++)
  3636. {
  3637. notselected_left[notselected_left.length] = {text:display_columns_ref.options[i].text, value:display_columns_ref.options[i].value};
  3638. }
  3639. var left_select_html_info = new Object();
  3640. var left_options = new Array();
  3641. var left_select = new Object();
  3642. left_select['name'] = left_name+'[]';
  3643. left_select['id'] = left_name;
  3644. left_select['multiple'] = 'true';
  3645. left_select['size'] = left_size;
  3646. var right_select_html_info = new Object();
  3647. var right_options = new Array();
  3648. var right_select = new Object();
  3649. right_select['name'] = right_name+ '[]';
  3650. right_select['id'] = right_name;
  3651. right_select['multiple'] = 'true';
  3652. right_select['size'] = right_size;
  3653. for (i = 0; i < notselected_left.length; i++) {
  3654. left_options[left_options.length] = notselected_left[i];
  3655. }
  3656. for (i = 0; i < selected_right.length; i++) {
  3657. left_options[left_options.length] = selected_right[i];
  3658. }
  3659. for (i = 0; i < notselected_right.length; i++) {
  3660. right_options[right_options.length] = notselected_right[i];
  3661. }
  3662. left_select_html_info['options'] = left_options;
  3663. left_select_html_info['select'] = left_select;
  3664. right_select_html_info['options'] = right_options;
  3665. right_select_html_info['select'] = right_select;
  3666. right_select_html_info['style'] = 'background: lightgrey';
  3667. var left_html = this.buildSelectHTML(left_select_html_info);
  3668. var right_html = this.buildSelectHTML(right_select_html_info);
  3669. left_td.innerHTML = left_html;
  3670. right_td.innerHTML = right_html;
  3671. object_refs[left_name] = left_td.getElementsByTagName('select')[0];
  3672. object_refs[right_name] = right_td.getElementsByTagName('select')[0];
  3673. this.movementCallback(object_refs[left_name], object_refs[right_name]);
  3674. return false;
  3675. },
  3676. up: function(name, left_name, right_name) {
  3677. SUGAR.savedViews.clearColumns = false;
  3678. var left_td = document.getElementById(left_name+'_td');
  3679. var right_td = document.getElementById(right_name+'_td');
  3680. var td = document.getElementById(name+'_td');
  3681. var obj = td.getElementsByTagName('select')[0];
  3682. obj = (typeof obj == "string") ? document.getElementById(obj) : obj;
  3683. if (obj.tagName.toLowerCase() != "select" && obj.length < 2)
  3684. return false;
  3685. var sel = new Array();
  3686. for (i=0; i<obj.length; i++) {
  3687. if (obj[i].selected == true) {
  3688. sel[sel.length] = i;
  3689. }
  3690. }
  3691. for (i=0; i < sel.length; i++) {
  3692. if (sel[i] != 0 && !obj[sel[i]-1].selected) {
  3693. var tmp = new Array(obj[sel[i]-1].text, obj[sel[i]-1].value);
  3694. obj[sel[i]-1].text = obj[sel[i]].text;
  3695. obj[sel[i]-1].value = obj[sel[i]].value;
  3696. obj[sel[i]].text = tmp[0];
  3697. obj[sel[i]].value = tmp[1];
  3698. obj[sel[i]-1].selected = true;
  3699. obj[sel[i]].selected = false;
  3700. }
  3701. }
  3702. object_refs[left_name] = left_td.getElementsByTagName('select')[0];
  3703. object_refs[right_name] = right_td.getElementsByTagName('select')[0];
  3704. this.orderCallback(object_refs[left_name], object_refs[right_name]);
  3705. return false;
  3706. },
  3707. down: function(name, left_name, right_name) {
  3708. SUGAR.savedViews.clearColumns = false;
  3709. var left_td = document.getElementById(left_name+'_td');
  3710. var right_td = document.getElementById(right_name+'_td');
  3711. var td = document.getElementById(name+'_td');
  3712. var obj = td.getElementsByTagName('select')[0];
  3713. if (obj.tagName.toLowerCase() != "select" && obj.length < 2)
  3714. return false;
  3715. var sel = new Array();
  3716. for (i=obj.length-1; i>-1; i--) {
  3717. if (obj[i].selected == true) {
  3718. sel[sel.length] = i;
  3719. }
  3720. }
  3721. for (i=0; i < sel.length; i++) {
  3722. if (sel[i] != obj.length-1 && !obj[sel[i]+1].selected) {
  3723. var tmp = new Array(obj[sel[i]+1].text, obj[sel[i]+1].value);
  3724. obj[sel[i]+1].text = obj[sel[i]].text;
  3725. obj[sel[i]+1].value = obj[sel[i]].value;
  3726. obj[sel[i]].text = tmp[0];
  3727. obj[sel[i]].value = tmp[1];
  3728. obj[sel[i]+1].selected = true;
  3729. obj[sel[i]].selected = false;
  3730. }
  3731. }
  3732. object_refs[left_name] = left_td.getElementsByTagName('select')[0];
  3733. object_refs[right_name] = right_td.getElementsByTagName('select')[0];
  3734. this.orderCallback(object_refs[left_name], object_refs[right_name]);
  3735. return false;
  3736. }
  3737. };
  3738. }(); // end tabChooser
  3739. SUGAR.language = function() {
  3740. return {
  3741. languages : new Array(),
  3742. setLanguage: function(module, data) {
  3743. if (!SUGAR.language.languages) {
  3744. }
  3745. SUGAR.language.languages[module] = data;
  3746. },
  3747. get: function(module, str) {
  3748. if(typeof SUGAR.language.languages[module] == 'undefined' || typeof SUGAR.language.languages[module][str] == 'undefined')
  3749. {
  3750. return 'undefined';
  3751. }
  3752. return SUGAR.language.languages[module][str];
  3753. },
  3754. translate: function(module, str)
  3755. {
  3756. text = this.get(module, str);
  3757. return text != 'undefined' ? text : this.get('app_strings', str);
  3758. }
  3759. }
  3760. }();
  3761. SUGAR.contextMenu = function() {
  3762. return {
  3763. objects: new Object(),
  3764. objectTypes: new Object(),
  3765. /**
  3766. * Registers a new object for the context menu.
  3767. * objectType - name of the type
  3768. * id - element id
  3769. * metaData - metaData to pass to the action function
  3770. **/
  3771. registerObject: function(objectType, id, metaData) {
  3772. SUGAR.contextMenu.objects[id] = new Object();
  3773. SUGAR.contextMenu.objects[id] = {'objectType' : objectType, 'metaData' : metaData};
  3774. },
  3775. /**
  3776. * Registers a new object type
  3777. * name - name of the type
  3778. * menuItems - array of menu items
  3779. **/
  3780. registerObjectType: function(name, menuItems) {
  3781. SUGAR.contextMenu.objectTypes[name] = new Object();
  3782. SUGAR.contextMenu.objectTypes[name] = {'menuItems' : menuItems, 'objects' : new Array()};
  3783. },
  3784. /**
  3785. * Determines which menu item was clicked
  3786. **/
  3787. getListItemFromEventTarget: function(p_oNode) {
  3788. var oLI;
  3789. if(p_oNode.tagName == "LI") {
  3790. oLI = p_oNode;
  3791. }
  3792. else {
  3793. do {
  3794. if(p_oNode.tagName == "LI") {
  3795. oLI = p_oNode;
  3796. break;
  3797. }
  3798. } while((p_oNode = p_oNode.parentNode));
  3799. }
  3800. return oLI;
  3801. },
  3802. /**
  3803. * handles movement within context menu
  3804. **/
  3805. onContextMenuMove: function() {
  3806. var oNode = this.contextEventTarget;
  3807. var bDisabled = (oNode.tagName == "UL");
  3808. var i = this.getItemGroups()[0].length - 1;
  3809. do {
  3810. this.getItem(i).cfg.setProperty("disabled", bDisabled);
  3811. }
  3812. while(i--);
  3813. },
  3814. /**
  3815. * handles clicks on a context menu ITEM
  3816. **/
  3817. onContextMenuItemClick: function(p_sType, p_aArguments, p_oItem) {
  3818. var oLI = SUGAR.contextMenu.getListItemFromEventTarget(this.parent.contextEventTarget);
  3819. id = this.parent.contextEventTarget.parentNode.id; // id of the target
  3820. funct = eval(SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[id]['objectType']]['menuItems'][this.index]['action']);
  3821. funct(this.parent.contextEventTarget, SUGAR.contextMenu.objects[id]['metaData']);
  3822. },
  3823. /**
  3824. * Initializes all context menus registered
  3825. **/
  3826. init: function() {
  3827. for(var i in SUGAR.contextMenu.objects) { // make a variable called objects in objectTypes containg references to all triggers
  3828. if(typeof SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'] == 'undefined')
  3829. SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'] = new Array();
  3830. SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'].push(document.getElementById(i));
  3831. }
  3832. // register the menus
  3833. for(var i in SUGAR.contextMenu.objectTypes) {
  3834. var oContextMenu = new YAHOO.widget.ContextMenu(i, {'trigger': SUGAR.contextMenu.objectTypes[i]['objects']});
  3835. var aMainMenuItems = SUGAR.contextMenu.objectTypes[i]['menuItems'];
  3836. var nMainMenuItems = aMainMenuItems.length;
  3837. var oMenuItem;
  3838. for(var j = 0; j < nMainMenuItems; j++) {
  3839. oMenuItem = new YAHOO.widget.ContextMenuItem(aMainMenuItems[j].text, { helptext: aMainMenuItems[j].helptext });
  3840. oMenuItem.clickEvent.subscribe(SUGAR.contextMenu.onContextMenuItemClick, oMenuItem, true);
  3841. oContextMenu.addItem(oMenuItem);
  3842. }
  3843. // Add a "move" event handler to the context menu
  3844. oContextMenu.moveEvent.subscribe(SUGAR.contextMenu.onContextMenuMove, oContextMenu, true);
  3845. // Add a "keydown" event handler to the context menu
  3846. oContextMenu.keyDownEvent.subscribe(SUGAR.contextMenu.onContextMenuItemClick, oContextMenu, true);
  3847. // Render the context menu
  3848. oContextMenu.render(document.body);
  3849. }
  3850. }
  3851. };
  3852. }();
  3853. SUGAR.contextMenu.actions = function() {
  3854. return {
  3855. /**
  3856. * redirects to a new note with the clicked on object as the target
  3857. **/
  3858. createNote: function(itemClicked, metaData) {
  3859. loc = 'index.php?module=Notes&action=EditView';
  3860. for(i in metaData) {
  3861. if(i == 'notes_parent_type') loc += '&parent_type=' + metaData[i];
  3862. else if(i != 'module' && i != 'parent_type') loc += '&' + i + '=' + metaData[i];
  3863. }
  3864. document.location = loc;
  3865. },
  3866. /**
  3867. * redirects to a new note with the clicked on object as the target
  3868. **/
  3869. scheduleMeeting: function(itemClicked, metaData) {
  3870. loc = 'index.php?module=Meetings&action=EditView';
  3871. for(i in metaData) {
  3872. if(i != 'module') loc += '&' + i + '=' + metaData[i];
  3873. }
  3874. document.location = loc;
  3875. },
  3876. /**
  3877. * redirects to a new note with the clicked on object as the target
  3878. **/
  3879. scheduleCall: function(itemClicked, metaData) {
  3880. loc = 'index.php?module=Calls&action=EditView';
  3881. for(i in metaData) {
  3882. if(i != 'module') loc += '&' + i + '=' + metaData[i];
  3883. }
  3884. document.location = loc;
  3885. },
  3886. /**
  3887. * redirects to a new contact with the clicked on object as the target
  3888. **/
  3889. createContact: function(itemClicked, metaData) {
  3890. loc = 'index.php?module=Contacts&action=EditView';
  3891. for(i in metaData) {
  3892. if(i != 'module') loc += '&' + i + '=' + metaData[i];
  3893. }
  3894. document.location = loc;
  3895. },
  3896. /**
  3897. * redirects to a new task with the clicked on object as the target
  3898. **/
  3899. createTask: function(itemClicked, metaData) {
  3900. loc = 'index.php?module=Tasks&action=EditView';
  3901. for(i in metaData) {
  3902. if(i != 'module') loc += '&' + i + '=' + metaData[i];
  3903. }
  3904. document.location = loc;
  3905. },
  3906. /**
  3907. * redirects to a new opportunity with the clicked on object as the target
  3908. **/
  3909. createOpportunity: function(itemClicked, metaData) {
  3910. loc = 'index.php?module=Opportunities&action=EditView';
  3911. for(i in metaData) {
  3912. if(i != 'module') loc += '&' + i + '=' + metaData[i];
  3913. }
  3914. document.location = loc;
  3915. },
  3916. /**
  3917. * redirects to a new opportunity with the clicked on object as the target
  3918. **/
  3919. createCase: function(itemClicked, metaData) {
  3920. loc = 'index.php?module=Cases&action=EditView';
  3921. for(i in metaData) {
  3922. if(i != 'module') loc += '&' + i + '=' + metaData[i];
  3923. }
  3924. document.location = loc;
  3925. },
  3926. /**
  3927. * handles add to favorites menu selection
  3928. **/
  3929. addToFavorites: function(itemClicked, metaData) {
  3930. success = function(data) {
  3931. }
  3932. var cObj = YAHOO.util.Connect.asyncRequest('GET', 'index.php?to_pdf=true&module=Home&action=AddToFavorites&target_id=' + metaData['id'] + '&target_module=' + metaData['module'], {success: success, failure: success});
  3933. }
  3934. };
  3935. }();
  3936. //if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.contextMenu.init);
  3937. // initially from popup_parent_helper.js
  3938. var popup_request_data;
  3939. var close_popup;
  3940. function get_popup_request_data()
  3941. {
  3942. return YAHOO.lang.JSON.stringify(window.document.popup_request_data);
  3943. }
  3944. function get_close_popup()
  3945. {
  3946. return window.document.close_popup;
  3947. }
  3948. function open_popup(module_name, width, height, initial_filter, close_popup, hide_clear_button, popup_request_data, popup_mode, create, metadata)
  3949. {
  3950. if (typeof(popupCount) == "undefined" || popupCount == 0)
  3951. popupCount = 1;
  3952. // set the variables that the popup will pull from
  3953. window.document.popup_request_data = popup_request_data;
  3954. window.document.close_popup = close_popup;
  3955. //globally changing width and height of standard pop up window from 600 x 400 to 800 x 800
  3956. width = (width == 600) ? 800 : width;
  3957. height = (height == 400) ? 800 : height;
  3958. // launch the popup
  3959. URL = 'index.php?'
  3960. + 'module=' + module_name
  3961. + '&action=Popup';
  3962. if (initial_filter != '') {
  3963. URL += '&query=true' + initial_filter;
  3964. // Bug 41891 - Popup Window Name
  3965. popupName = initial_filter.replace(/[^a-z_0-9]+/ig, '_');
  3966. windowName = module_name + '_popup_window' + popupName;
  3967. } else {
  3968. windowName = module_name + '_popup_window' + popupCount;
  3969. }
  3970. popupCount++;
  3971. if (hide_clear_button) {
  3972. URL += '&hide_clear_button=true';
  3973. }
  3974. windowFeatures = 'width=' + width
  3975. + ',height=' + height
  3976. + ',resizable=1,scrollbars=1';
  3977. if (popup_mode == '' || popup_mode == undefined) {
  3978. popup_mode='single';
  3979. }
  3980. URL+='&mode='+popup_mode;
  3981. if (create == '' || create == undefined) {
  3982. create = 'false';
  3983. }
  3984. URL+='&create='+create;
  3985. if (metadata != '' && metadata != undefined) {
  3986. URL+='&metadata='+metadata;
  3987. }
  3988. // Bug #46842 : The relate field field_to_name_array fails to copy over custom fields
  3989. // post fields that should be populated from popup form
  3990. if(popup_request_data.jsonObject) {
  3991. var request_data = popup_request_data.jsonObject;
  3992. } else {
  3993. var request_data = popup_request_data;
  3994. }
  3995. var field_to_name_array_url = '';
  3996. if (request_data && request_data.field_to_name_array != undefined) {
  3997. for(var key in request_data.field_to_name_array) {
  3998. if ( key.toLowerCase() != 'id' ) {
  3999. field_to_name_array_url += '&field_to_name[]='+encodeURIComponent(key.toLowerCase());
  4000. }
  4001. }
  4002. }
  4003. if ( field_to_name_array_url ) {
  4004. URL+=field_to_name_array_url;
  4005. }
  4006. win = SUGAR.util.openWindow(URL, windowName, windowFeatures);
  4007. if(window.focus)
  4008. {
  4009. // put the focus on the popup if the browser supports the focus() method
  4010. win.focus();
  4011. }
  4012. win.popupCount = popupCount;
  4013. return win;
  4014. }
  4015. /**
  4016. * The reply data must be a JSON array structured with the following information:
  4017. * 1) form name to populate
  4018. * 2) associative array of input names to values for populating the form
  4019. */
  4020. var from_popup_return = false;
  4021. //Function replaces special HTML chars for usage in text boxes
  4022. function replaceHTMLChars(value) {
  4023. return value.replace(/&amp;/gi,'&').replace(/&lt;/gi,'<').replace(/&gt;/gi,'>').replace(/&#039;/gi,'\'').replace(/&quot;/gi,'"');
  4024. }
  4025. function set_return_basic(popup_reply_data,filter)
  4026. {
  4027. var form_name = popup_reply_data.form_name;
  4028. var name_to_value_array = popup_reply_data.name_to_value_array;
  4029. for (var the_key in name_to_value_array)
  4030. {
  4031. if(the_key == 'toJSON')
  4032. {
  4033. /* just ignore */
  4034. }
  4035. else if(the_key.match(filter))
  4036. {
  4037. var displayValue=replaceHTMLChars(name_to_value_array[the_key]);
  4038. // begin andopes change: support for enum fields (SELECT)
  4039. if(window.document.forms[form_name] && window.document.forms[form_name].elements[the_key]) {
  4040. if(window.document.forms[form_name].elements[the_key].tagName == 'SELECT') {
  4041. var selectField = window.document.forms[form_name].elements[the_key];
  4042. for(var i = 0; i < selectField.options.length; i++) {
  4043. if(selectField.options[i].text == displayValue) {
  4044. selectField.options[i].selected = true;
  4045. SUGAR.util.callOnChangeListers(selectField);
  4046. break;
  4047. }
  4048. }
  4049. } else {
  4050. window.document.forms[form_name].elements[the_key].value = displayValue;
  4051. SUGAR.util.callOnChangeListers(window.document.forms[form_name].elements[the_key]);
  4052. }
  4053. }
  4054. // end andopes change: support for enum fields (SELECT)
  4055. }
  4056. }
  4057. }
  4058. function set_return(popup_reply_data)
  4059. {
  4060. from_popup_return = true;
  4061. var form_name = popup_reply_data.form_name;
  4062. var name_to_value_array = popup_reply_data.name_to_value_array;
  4063. if(typeof name_to_value_array != 'undefined' && name_to_value_array['account_id'])
  4064. {
  4065. var label_str = '';
  4066. var label_data_str = '';
  4067. var current_label_data_str = '';
  4068. var popupConfirm = popup_reply_data.popupConfirm;
  4069. for (var the_key in name_to_value_array)
  4070. {
  4071. if(the_key == 'toJSON')
  4072. {
  4073. /* just ignore */
  4074. }
  4075. else
  4076. {
  4077. var displayValue=replaceHTMLChars(name_to_value_array[the_key]);
  4078. if(window.document.forms[form_name] && document.getElementById(the_key+'_label') && !the_key.match(/account/)) {
  4079. var data_label = document.getElementById(the_key+'_label').innerHTML.replace(/\n/gi,'').replace(/<\/?[^>]+(>|$)/g, "");
  4080. label_str += data_label + ' \n';
  4081. label_data_str += data_label + ' ' + displayValue + '\n';
  4082. if(window.document.forms[form_name].elements[the_key]) {
  4083. current_label_data_str += data_label + ' ' + window.document.forms[form_name].elements[the_key].value +'\n';
  4084. }
  4085. }
  4086. }
  4087. }
  4088. if(label_data_str != label_str && current_label_data_str != label_str){
  4089. // Bug 48726 Start
  4090. if (typeof popupConfirm != 'undefined')
  4091. {
  4092. if (popupConfirm > -1) {
  4093. set_return_basic(popup_reply_data,/\S/);
  4094. } else {
  4095. set_return_basic(popup_reply_data,/account/);
  4096. }
  4097. }
  4098. // Bug 48726 End
  4099. else if(confirm(SUGAR.language.get('app_strings', 'NTC_OVERWRITE_ADDRESS_PHONE_CONFIRM') + '\n\n' + label_data_str))
  4100. {
  4101. set_return_basic(popup_reply_data,/\S/);
  4102. }
  4103. else
  4104. {
  4105. set_return_basic(popup_reply_data,/account/);
  4106. }
  4107. }else if(label_data_str != label_str && current_label_data_str == label_str){
  4108. set_return_basic(popup_reply_data,/\S/);
  4109. }else if(label_data_str == label_str){
  4110. set_return_basic(popup_reply_data,/account/);
  4111. }
  4112. }else{
  4113. set_return_basic(popup_reply_data,/\S/);
  4114. }
  4115. }
  4116. function set_return_lead_conv(popup_reply_data) {
  4117. set_return(popup_reply_data);
  4118. if (document.getElementById('lead_conv_ac_op_sel') && typeof onBlurKeyUpHandler=='function') {
  4119. onBlurKeyUpHandler();
  4120. }
  4121. }
  4122. function set_return_and_save(popup_reply_data)
  4123. {
  4124. var form_name = popup_reply_data.form_name;
  4125. var name_to_value_array = popup_reply_data.name_to_value_array;
  4126. for (var the_key in name_to_value_array)
  4127. {
  4128. if(the_key == 'toJSON')
  4129. {
  4130. /* just ignore */
  4131. }
  4132. else
  4133. {
  4134. window.document.forms[form_name].elements[the_key].value = name_to_value_array[the_key];
  4135. }
  4136. }
  4137. window.document.forms[form_name].return_module.value = window.document.forms[form_name].module.value;
  4138. window.document.forms[form_name].return_action.value = 'DetailView';
  4139. window.document.forms[form_name].return_id.value = window.document.forms[form_name].record.value;
  4140. window.document.forms[form_name].action.value = 'Save';
  4141. window.document.forms[form_name].submit();
  4142. }
  4143. /**
  4144. * This is a helper function to construct the initial filter that can be
  4145. * passed into the open_popup() function. It assumes that there is an
  4146. * account_id and account_name field in the given form_name to use to
  4147. * construct the intial filter string.
  4148. */
  4149. function get_initial_filter_by_account(form_name)
  4150. {
  4151. var account_id = window.document.forms[form_name].account_id.value;
  4152. var account_name = escape(window.document.forms[form_name].account_name.value);
  4153. var initial_filter = "&account_id=" + account_id + "&account_name=" + account_name;
  4154. return initial_filter;
  4155. }
  4156. // end code from popup_parent_helper.js
  4157. // begin code for address copy
  4158. /**
  4159. * This is a function used by the Address widget that will fill
  4160. * in the given array fields using the fromKey and toKey as a
  4161. * prefix into the form objects HTML elements.
  4162. *
  4163. * @param form The HTML form object to parse
  4164. * @param fromKey The prefix of elements to copy from
  4165. * @param toKey The prefix of elements to copy into
  4166. * @return boolean true if successful, false otherwise
  4167. */
  4168. function copyAddress(form, fromKey, toKey) {
  4169. var elems = new Array("address_street", "address_city", "address_state", "address_postalcode", "address_country");
  4170. var checkbox = document.getElementById(toKey + "_checkbox");
  4171. if(typeof checkbox != "undefined") {
  4172. if(!checkbox.checked) {
  4173. for(x in elems) {
  4174. t = toKey + "_" + elems[x];
  4175. document.getElementById(t).removeAttribute('readonly');
  4176. }
  4177. } else {
  4178. for(x in elems) {
  4179. f = fromKey + "_" + elems[x];
  4180. t = toKey + "_" + elems[x];
  4181. document.getElementById(t).value = document.getElementById(f).value;
  4182. document.getElementById(t).setAttribute('readonly', true);
  4183. }
  4184. }
  4185. }
  4186. return true;
  4187. }
  4188. // end code for address copy
  4189. /**
  4190. * This function is used in Email Template Module.
  4191. * It will check whether the template is used in Campaing->EmailMarketing.
  4192. * If true, it will notify user.
  4193. */
  4194. function check_deletable_EmailTemplate() {
  4195. id = document.getElementsByName('record')[0].value;
  4196. currentForm = document.getElementById('form');
  4197. var call_back = {
  4198. success:function(r) {
  4199. if(r.responseText == 'true') {
  4200. if(!confirm(SUGAR.language.get('app_strings','NTC_TEMPLATE_IS_USED'))) {
  4201. return false;
  4202. }
  4203. } else {
  4204. if(!confirm(SUGAR.language.get('app_strings','NTC_DELETE_CONFIRMATION'))) {
  4205. return false;
  4206. }
  4207. }
  4208. currentForm.return_module.value='EmailTemplates';
  4209. currentForm.return_action.value='ListView';
  4210. currentForm.action.value='Delete';
  4211. currentForm.submit();
  4212. }
  4213. };
  4214. url = "index.php?module=EmailTemplates&action=CheckDeletable&from=DetailView&to_pdf=1&record="+id;
  4215. YAHOO.util.Connect.asyncRequest('POST',url, call_back,null);
  4216. }
  4217. SUGAR.image = {
  4218. remove_upload_imagefile : function(field_name) {
  4219. var field=document.getElementById('remove_imagefile_' + field_name);
  4220. field.value=1;
  4221. //enable the file upload button.
  4222. var field=document.getElementById( field_name);
  4223. field.style.display="";
  4224. //hide the image and remove button.
  4225. var field=document.getElementById('img_' + field_name);
  4226. field.style.display="none";
  4227. var field=document.getElementById('bt_remove_' + field_name);
  4228. field.style.display="none";
  4229. if(document.getElementById(field_name + '_duplicate')) {
  4230. var field = document.getElementById(field_name + '_duplicate');
  4231. field.value = "";
  4232. }
  4233. },
  4234. confirm_imagefile : function(field_name) {
  4235. var field=document.getElementById(field_name);
  4236. var filename=field.value;
  4237. var fileExtension = filename.substring(filename.lastIndexOf(".")+1);
  4238. fileExtension = fileExtension.toLowerCase();
  4239. if (fileExtension == "jpg" || fileExtension == "jpeg"
  4240. || fileExtension == "gif" || fileExtension == "png" || fileExtension == "bmp"){
  4241. //image file
  4242. }
  4243. else{
  4244. field.value=null;
  4245. alert(SUGAR.language.get('app_strings', 'LBL_UPLOAD_IMAGE_FILE_INVALID'));
  4246. }
  4247. },
  4248. lightbox : function(image)
  4249. {
  4250. if (typeof(SUGAR.image.lighboxWindow) == "undefined")
  4251. SUGAR.image.lighboxWindow = new YAHOO.widget.SimpleDialog('sugarImageViewer', {
  4252. type:'message',
  4253. modal:true,
  4254. id:'sugarMsgWindow',
  4255. close:true,
  4256. title:"Alert",
  4257. msg: "<img src='" + image + "'> </img>",
  4258. buttons: [ ]
  4259. });
  4260. SUGAR.image.lighboxWindow.setBody("<img src='" + image + "'> </img>");
  4261. SUGAR.image.lighboxWindow.render(document.body);
  4262. SUGAR.image.lighboxWindow.show();
  4263. SUGAR.image.lighboxWindow.center()
  4264. }
  4265. }
  4266. SUGAR.append(SUGAR.util, {
  4267. isTouchScreen: function() {
  4268. // first check if we have forced use of the touch enhanced interface
  4269. if (Get_Cookie("touchscreen") == '1') {
  4270. return true;
  4271. }
  4272. // next check if we should use the touch interface with our device
  4273. if ((navigator.userAgent.match(/iPad/i) != null)) {
  4274. return true;
  4275. }
  4276. return false;
  4277. },
  4278. isLoginPage: function(content) {
  4279. //skip if this is packageManager screen
  4280. if(SUGAR.util.isPackageManager()) {return false;}
  4281. var loginPageStart = "<!DOCTYPE";
  4282. if (content.substr(0, loginPageStart.length) == loginPageStart && content.indexOf("<html>") != -1 && content.indexOf("login_module") != -1) {
  4283. window.location.href = window.location.protocol + window.location.pathname;
  4284. return true;
  4285. }
  4286. },
  4287. isPackageManager: function(){
  4288. if(typeof(document.the_form) !='undefined' && typeof(document.the_form.language_pack_escaped) !='undefined'){
  4289. return true;
  4290. }else{return false;}
  4291. },
  4292. ajaxCallInProgress: function(){
  4293. var t = true;
  4294. //First check if we are in a popup.
  4295. if (typeof (send_back) != "function"){
  4296. //If the page content is blank, it means we are probably still waiting on something
  4297. var c = document.getElementById("content");
  4298. if (!c) return true;
  4299. t = YAHOO.lang.trim(SUGAR.util.innerText(c));
  4300. }
  4301. return SUGAR_callsInProgress != 0 || t == "";
  4302. },
  4303. //Firefox doesn't support innerText (textContent includes script content)
  4304. innerText : function(el) {
  4305. if (el.tagName == "SCRIPT")
  4306. return "";
  4307. if(typeof(el.innerText) == "string")
  4308. return el.innerText;
  4309. var t = "";
  4310. for (var i in el.childNodes){
  4311. var c = el.childNodes[i];
  4312. if (typeof(c) != "object")
  4313. continue;
  4314. if (typeof(c.nodeName) == "string" && c.nodeName == "#text")
  4315. t += c.nodeValue;
  4316. else
  4317. t += SUGAR.util.innerText(c);
  4318. }
  4319. return t;
  4320. },
  4321. callOnChangeListers: function(field){
  4322. var listeners = YAHOO.util.Event.getListeners(field, 'change');
  4323. if (listeners != null) {
  4324. for (var i = 0; i < listeners.length; i++) {
  4325. var l = listeners[i];
  4326. l.fn.call(l.scope ? l.scope : this, l.obj);
  4327. }
  4328. }
  4329. },
  4330. closeActivityPanel: {
  4331. show:function(module,id,new_status,viewType,parentContainerId){
  4332. if (SUGAR.util.closeActivityPanel.panel)
  4333. SUGAR.util.closeActivityPanel.panel.destroy();
  4334. var singleModule = SUGAR.language.get("app_list_strings", "moduleListSingular")[module];
  4335. singleModule = typeof(singleModule != 'undefined') ? singleModule.toLowerCase() : '';
  4336. var closeText = SUGAR.language.get("app_strings", "LBL_CLOSE_ACTIVITY_CONFIRM").replace("#module#",singleModule);
  4337. SUGAR.util.closeActivityPanel.panel =
  4338. new YAHOO.widget.SimpleDialog("closeActivityDialog",
  4339. { width: "300px",
  4340. fixedcenter: true,
  4341. visible: false,
  4342. draggable: false,
  4343. close: true,
  4344. text: closeText,
  4345. constraintoviewport: true,
  4346. buttons: [ { text:SUGAR.language.get("app_strings", "LBL_EMAIL_OK"), handler:function(){
  4347. if (SUGAR.util.closeActivityPanel.panel)
  4348. SUGAR.util.closeActivityPanel.panel.hide();
  4349. ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_SAVING'));
  4350. var args = "action=save&id=" + id + "&record=" + id + "&status=" + new_status + "&module=" + module;
  4351. // 20110307 Frank Steegmans: Fix for bug 42361, Any field with a default configured in any activity will be set to this default when closed using the close dialog
  4352. // TODO: Take id out and regression test. Left id in for now to not create any other unexpected problems
  4353. //var args = "action=save&id=" + id + "&status=" + new_status + "&module=" + module;
  4354. var callback = {
  4355. success:function(o)
  4356. {
  4357. // Bug 51984: We need to submit the form just incase we have a form already submitted
  4358. // so we dont get a popup stating that the form needs to be resubmitted like it doesn,
  4359. // when you do a reload/refresh
  4360. window.setTimeout(function(){if(document.getElementById('search_form')) document.getElementById('search_form').submit(); else window.location.reload(true);}, 0);
  4361. },
  4362. argument:{'parentContainerId':parentContainerId}
  4363. };
  4364. YAHOO.util.Connect.asyncRequest('POST', 'index.php', callback, args);
  4365. }, isDefault:true },
  4366. { text:SUGAR.language.get("app_strings", "LBL_EMAIL_CANCEL"), handler:function(){SUGAR.util.closeActivityPanel.panel.hide(); }} ]
  4367. } );
  4368. SUGAR.util.closeActivityPanel.panel.setHeader(SUGAR.language.get("app_strings", "LBL_CLOSE_ACTIVITY_HEADER"));
  4369. SUGAR.util.closeActivityPanel.panel.render(document.body);
  4370. SUGAR.util.closeActivityPanel.panel.show();
  4371. }
  4372. },
  4373. setEmailPasswordDisplay: function(id, exists, formName) {
  4374. link = document.getElementById(id+'_link');
  4375. pwd = document.getElementById(id);
  4376. if(!pwd || !link) return;
  4377. if(exists) {
  4378. pwd.disabled = true;
  4379. pwd.style.display = 'none';
  4380. link.style.display = '';
  4381. if(typeof(formName) != 'undefined')
  4382. removeFromValidate(formName, id);
  4383. } else {
  4384. pwd.disabled = false;
  4385. pwd.style.display = '';
  4386. link.style.display = 'none';
  4387. }
  4388. },
  4389. setEmailPasswordEdit: function(id) {
  4390. link = document.getElementById(id+'_link');
  4391. pwd = document.getElementById(id);
  4392. if(!pwd || !link) return;
  4393. pwd.disabled = false;
  4394. pwd.style.display = '';
  4395. link.style.display = 'none';
  4396. },
  4397. /**
  4398. * Compares a filename with a supplied array of allowed file extensions.
  4399. * @param fileName string
  4400. * @param allowedTypes array of allowed file extensions
  4401. * @return bool
  4402. */
  4403. validateFileExt: function(fileName, allowedTypes) {
  4404. var ext = fileName.split('.').pop().toLowerCase();
  4405. for (var i = allowedTypes.length; i >= 0; i--) {
  4406. if (ext === allowedTypes[i]) {
  4407. return true;
  4408. }
  4409. }
  4410. return false;
  4411. },
  4412. arrayIndexOf: function(arr, val, start) {
  4413. if (typeof arr.indexOf == "function")
  4414. return arr.indexOf(val, start);
  4415. for (var i = (start || 0), j = arr.length; i < j; i++) {
  4416. if (arr[i] === val) {
  4417. return i;
  4418. }
  4419. }
  4420. return -1;
  4421. }
  4422. });
  4423. SUGAR.clearRelateField = function(form, name, id)
  4424. {
  4425. if (typeof form[name] == "object"){
  4426. form[name].value = '';
  4427. SUGAR.util.callOnChangeListers(form[name]);
  4428. }
  4429. if (typeof form[id] == "object"){
  4430. form[id].value = '';
  4431. SUGAR.util.callOnChangeListers(form[id]);
  4432. }
  4433. };
  4434. if(typeof(SUGAR.AutoComplete) == 'undefined') SUGAR.AutoComplete = {};
  4435. SUGAR.AutoComplete.getOptionsArray = function(options_index){
  4436. var return_arr = [];
  4437. var opts = SUGAR.language.get('app_list_strings', options_index);
  4438. if(typeof(opts) != 'undefined'){
  4439. for(key in opts){
  4440. // Since we are using auto complete, we excluse blank dropdown entries since they can just leave it blank
  4441. if(key != '' && opts[key] != ''){
  4442. var item = [];
  4443. item['key'] = key;
  4444. item['text'] = opts[key];
  4445. return_arr.push(item);
  4446. }
  4447. }
  4448. }
  4449. return return_arr;
  4450. }
  4451. if(typeof(SUGAR.MultiEnumAutoComplete) == 'undefined') SUGAR.MultiEnumAutoComplete = {};
  4452. SUGAR.MultiEnumAutoComplete.getMultiSelectKeysFromValues = function(options_index, val_string){
  4453. var opts = SUGAR.language.get('app_list_strings', options_index);
  4454. var selected_values = val_string.split(", ");
  4455. // YUI AutoComplete adds a blank. We remove it automatically here
  4456. if(selected_values.length > 0 && selected_values.indexOf('') == selected_values.length - 1){
  4457. selected_values.pop();
  4458. }
  4459. var final_arr = new Array();
  4460. for(idx in selected_values){
  4461. for(o_idx in opts){
  4462. if(selected_values[idx] == opts[o_idx]){
  4463. final_arr.push(o_idx);
  4464. }
  4465. }
  4466. }
  4467. return final_arr;
  4468. }
  4469. SUGAR.MultiEnumAutoComplete.getMultiSelectValuesFromKeys = function(options_index, val_string){
  4470. var opts = SUGAR.language.get('app_list_strings', options_index);
  4471. val_string=val_string.replace(/^\^/,'').replace(/\^$/,'') //fixes bug where string starts or ends with ^
  4472. var selected_values = val_string.split("^,^");
  4473. // YUI AutoComplete adds a blank. We remove it automatically here
  4474. if(selected_values.length > 0 && selected_values.indexOf('') == selected_values.length - 1){
  4475. selected_values.pop();
  4476. }
  4477. var final_arr = new Array();
  4478. for(idx in selected_values){
  4479. for(o_idx in opts){
  4480. if(selected_values[idx] == o_idx){
  4481. final_arr.push(opts[o_idx]);
  4482. }
  4483. }
  4484. }
  4485. return final_arr;
  4486. }
  4487. function convertReportDateTimeToDB(dateValue, timeValue)
  4488. {
  4489. var date_match = dateValue.match(date_reg_format);
  4490. var time_match = timeValue.match(/([0-9]{1,2})\:([0-9]{1,2})([ap]m)/);
  4491. if ( date_match != null && time_match != null) {
  4492. time_match[1] = parseInt(time_match[1]);
  4493. if (time_match[3] == 'pm') {
  4494. time_match[1] = time_match[1] + 12;
  4495. if (time_match[1] >= 24) {
  4496. time_match[1] = time_match[1] - 24;
  4497. }
  4498. } else if (time_match[3] == 'am' && time_match[1] == 12) {
  4499. time_match[1] = 0;
  4500. }
  4501. if (time_match[1] < 10) {
  4502. time_match[1] = '0' + time_match[1];
  4503. }
  4504. return date_match[date_reg_positions['Y']] + "-"+date_match[date_reg_positions['m']] + "-"+date_match[date_reg_positions['d']] + ' '+ time_match[1] + ':' + time_match[2] + ':00';
  4505. }
  4506. return '';
  4507. }