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