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