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