]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - jssource/src_files/include/javascript/sugar_3.js
Release 6.5.6
[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                         SUGAR.util.globalEval(result[2]);
2953                         }
2954                       }
2955                       catch(e) {
2956                       if(typeof(console) != "undefined" && typeof(console.log) == "function")
2957                       {
2958                           console.log("error adding script");
2959                           console.log(e);
2960                           console.log(result);
2961                       }
2962                   }
2963                   result =  objRegex.exec(text);
2964                         }
2965             },
2966                 /**
2967                  * Gets the sidebar object
2968                  * @return object pointer to the sidebar element
2969                  */
2970                 getLeftColObj: function() {
2971                         leftColObj = document.getElementById('leftCol');
2972                         while(leftColObj.nodeName != 'TABLE') {
2973                                 leftColObj = leftColObj.firstChild;
2974                         }
2975                         leftColTable = leftColObj;
2976                         leftColTd = leftColTable.getElementsByTagName('td')[0];
2977                         leftColTdRegion = YAHOO.util.Dom.getRegion(leftColTd);
2978                         leftColTd.style.width = (leftColTdRegion.right - leftColTdRegion.left) + 'px';
2979
2980                         return leftColTd;
2981                 },
2982                 /**
2983                  * Fills the shortcut menu placeholders w/ actual content
2984                  * Call this on load event
2985                  *
2986                  * @param shortcutContent Array array of content to fill in
2987                  */
2988                 fillShortcuts: function(e, shortcutContent) {
2989                         return ;
2990 /*
2991             // don't do this if leftCol isn't available
2992             if (document.getElementById('leftCol') == undefined) { return; }
2993
2994                 spans = document.getElementById('leftCol').getElementsByTagName('span');
2995                         hideCol = document.getElementById('HideMenu').getElementsByTagName('span');
2996                         w = spans.length + 1;
2997                         for(i in hideCol) {
2998                                 spans[w] = hideCol[i];
2999                                 w++;
3000                         }
3001                     for(je in shortcutContent) {
3002                         for(wp in spans) {
3003                                 if(typeof spans[wp].innerHTML != 'undefined' && spans[wp].innerHTML == ('wp_shortcut_fill_' + je)) {
3004                                         if(typeof spans[wp].parentNode.parentNode == 'object') {
3005                                                 if(typeof spans[wp].parentNode.parentNode.onclick != 'undefined') {
3006                                                         spans[wp].parentNode.parentNode.onclick = null;
3007                                                 }
3008                                                 // If the wp_shortcut span is contained by an A tag, replace the A with a DIV.
3009                                                 if(spans[wp].parentNode.tagName == 'A' && !isIE) {
3010                                                         var newDiv = document.createElement('DIV');
3011                                                         var parentAnchor = spans[wp].parentNode;
3012
3013                                                         spans[wp].parentNode.parentNode.style.display = 'none';
3014
3015                                                         // Copy styles over to the new container div
3016                                                         if(window.getComputedStyle) {
3017                                                                 var parentStyle = window.getComputedStyle(parentAnchor, '');
3018                                                                 for(var styleName in parentStyle) {
3019                                                                         if(typeof parentStyle[styleName] != 'function'
3020                                                                     && styleName != 'display'
3021                                                                     && styleName != 'borderWidth'
3022                                                                     && styleName != 'visibility') {
3023                                                                         try {
3024                                                                                         newDiv.style[styleName] = parentStyle[styleName];
3025                                                                                 } catch(e) {
3026                                                                                         // Catches .length and .parentRule, and others
3027                                                                                 }
3028                                                                         }
3029                                                                 }
3030                                                         }
3031
3032                                                         // Replace the A with the DIV
3033                                                         newDiv.appendChild(spans[wp]);
3034                                                         parentAnchor.parentNode.replaceChild(newDiv, parentAnchor);
3035
3036                                                         spans[wp].parentNode.parentNode.style.display = '';
3037                                                 }
3038                                         }
3039                                     spans[wp].innerHTML = shortcutContent[je]; // fill w/ content
3040                                     if(spans[wp].style) spans[wp].style.display = '';
3041                                 }
3042                         }
3043                         }*/
3044                 },
3045                 /**
3046                  * Make an AJAX request.
3047                  *
3048                  * @param       url                             string  resource to load
3049                  * @param       theDiv                  string  id of element to insert loaded data into
3050                  * @param       postForm                string  if set, a POST request will be made to resource specified by url using the form named by postForm
3051                  * @param       callback                string  name of function to invoke after HTTP response is recieved
3052                  * @param       callbackParam   any             parameter to pass to callback when invoked
3053                  * @param       appendMode              bool    if true, HTTP response will be appended to the contents of theDiv, or else contents will be overriten.
3054                  */
3055             retrieveAndFill: function(url, theDiv, postForm, callback, callbackParam, appendMode) {
3056                         if(typeof theDiv == 'string') {
3057                                 try {
3058                                         theDiv = document.getElementById(theDiv);
3059                                 }
3060                         catch(e) {
3061                                         return;
3062                                 }
3063                         }
3064
3065                         var success = function(data) {
3066                                 if (typeof theDiv != 'undefined' && theDiv != null)
3067                                 {
3068                                         try {
3069                                                 if (typeof appendMode != 'undefined' && appendMode)
3070                                                 {
3071                                                         theDiv.innerHTML += data.responseText;
3072                                                 }
3073                                                 else
3074                                                 {
3075                                                         theDiv.innerHTML = data.responseText;
3076                                                 }
3077                                         }
3078                                         catch (e) {
3079                                                 return;
3080                                         }
3081                                 }
3082                                 if (typeof callback != 'undefined' && callback != null) callback(callbackParam);
3083                         }
3084
3085                         if(typeof postForm == 'undefined' || postForm == null) {
3086                                 var cObj = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
3087                         }
3088                         else {
3089                                 YAHOO.util.Connect.setForm(postForm);
3090                                 var cObj = YAHOO.util.Connect.asyncRequest('POST', url, {success: success, failure: success});
3091                         }
3092                 },
3093                 checkMaxLength: function() { // modified from http://www.quirksmode.org/dom/maxlength.html
3094                         var maxLength = this.getAttribute('maxlength');
3095                         var currentLength = this.value.length;
3096                         if (currentLength > maxLength) {
3097                                 this.value = this.value.substring(0, maxLength);
3098                         }
3099                         // not innerHTML
3100                 },
3101                 /**
3102                  * Adds maxlength attribute to textareas
3103                  */
3104                 setMaxLength: function() { // modified from http://www.quirksmode.org/dom/maxlength.html
3105                         var x = document.getElementsByTagName('textarea');
3106                         for (var i=0;i<x.length;i++) {
3107                                 if (x[i].getAttribute('maxlength')) {
3108                                         x[i].onkeyup = x[i].onchange = SUGAR.util.checkMaxLength;
3109                                         x[i].onkeyup();
3110                                 }
3111                         }
3112                 },
3113
3114                 /**
3115                  * Renders Query UI Help Dialog
3116                  */
3117                 showHelpTips: function(el,helpText,myPos,atPos,id) {
3118                                 if(myPos == undefined || myPos == "") {
3119                                         myPos = "left top";
3120                                 }
3121                                 if(atPos == undefined || atPos == "") {
3122                                         atPos = "right top";
3123                                 }
3124
3125                                 var pos = $(el).offset(),
3126                     ofWidth = $(el).width(),
3127                     elmId = id || 'helpTip' + pos.left + '_' + ofWidth,
3128                     $dialog = elmId ? ( $("#"+elmId).length > 0 ? $("#"+elmId) : $('<div></div>').attr("id", elmId) ) : $('<div></div>');
3129                 $dialog.html(helpText)
3130                                         .dialog({
3131                                                 autoOpen: false,
3132                                                 title: SUGAR.language.get('app_strings', 'LBL_HELP'),
3133                                                 position: {
3134                                                     my: myPos,
3135                                                     at: atPos,
3136                                                     of: $(el)
3137                                                 }
3138                                         });
3139
3140
3141                                         var width = $dialog.dialog( "option", "width" );
3142
3143                                         if((pos.left + ofWidth) - 40 < width) {
3144                                                 $dialog.dialog("option","position",{my: 'left top',at: 'right top',of: $(el)})  ;
3145                                         }
3146                                         $dialog.dialog('open');
3147                                         $(".ui-dialog").appendTo("#content");
3148
3149
3150                 },
3151                 getStaticAdditionalDetails: function(el, body, caption, show_buttons) {
3152                         if(typeof show_buttons == "undefined") {
3153                                 show_buttons = false;
3154                         }
3155
3156                         $(".ui-dialog").find(".open").dialog("close");
3157
3158                         var $dialog = $('<div class="open"></div>')
3159                         .html(body)
3160                         .dialog({
3161                                 autoOpen: false,
3162                                 title: caption,
3163                                 width: 300,
3164                                 position: {
3165                                     my: 'right top',
3166                                     at: 'left top',
3167                                     of: $(el)
3168                           }
3169                         });
3170
3171                         if(show_buttons) {
3172                                 $(".ui-dialog").find('.ui-dialog-titlebar-close').css("display","none");
3173                                 $(".ui-dialog").find('.ui-dialog-title').css("width","100%");
3174                         }
3175
3176
3177                         var width = $dialog.dialog( "option", "width" );
3178                         var pos = $(el).offset();
3179                         var ofWidth = $(el).width();
3180
3181                         if((pos.left + ofWidth) - 40 < width) {
3182                                 $dialog.dialog("option","position",{my: 'left top',at: 'right top',of: $(el)})  ;
3183                         }
3184
3185                         $dialog.dialog('open');
3186                         $(".ui-dialog").appendTo("#content");
3187
3188                 },
3189
3190                 closeStaticAdditionalDetails: function() {
3191                         $(".ui-dialog").find(".open").dialog("close");
3192                 },
3193                 /**
3194                  * Retrieves additional details dynamically
3195                  */
3196                 getAdditionalDetails: function(bean, id, spanId, show_buttons) {
3197                         if(typeof show_buttons == "undefined")
3198                                 show_buttons = false;
3199                                 var el = '#'+spanId;
3200                         go = function() {
3201                                 oReturn = function(body, caption, width, theme) {
3202
3203                                         $(".ui-dialog").find(".open").dialog("close");
3204
3205                                         var $dialog = $('<div class="open"></div>')
3206                                         .html(body)
3207                                         .dialog({
3208                                                 autoOpen: false,
3209                                                 title: caption,
3210                                                 width: 300,
3211                                                 position: {
3212                                                     my: 'right top',
3213                                                     at: 'left top',
3214                                                     of: $(el)
3215                                           }
3216                                         });
3217                                 if(show_buttons) {
3218                                         $(".ui-dialog").find('.ui-dialog-titlebar-close').css("display","none");
3219                                         $(".ui-dialog").find('.ui-dialog-title').css("width","100%");
3220                                 }
3221
3222                                         var width = $dialog.dialog( "option", "width" );
3223                                         var pos = $(el).offset();
3224                                         var ofWidth = $(el).width();
3225
3226                                         if((pos.left + ofWidth) - 40 < width) {
3227                                                 $dialog.dialog("option","position",{my: 'left top',at: 'right top',of: $(el)})  ;
3228                                         }
3229
3230                                         $dialog.dialog('open');
3231                                         $(".ui-dialog").appendTo("#content");
3232                                 }
3233
3234                                 success = function(data) {
3235                                         eval(data.responseText);
3236
3237                                         SUGAR.util.additionalDetailsCache[id] = new Array();
3238                                         SUGAR.util.additionalDetailsCache[id]['body'] = result['body'];
3239                                         SUGAR.util.additionalDetailsCache[id]['caption'] = result['caption'];
3240                                         SUGAR.util.additionalDetailsCache[id]['width'] = result['width'];
3241                                         SUGAR.util.additionalDetailsCache[id]['theme'] = result['theme'];
3242                                         ajaxStatus.hideStatus();
3243                                         return oReturn(SUGAR.util.additionalDetailsCache[id]['body'], SUGAR.util.additionalDetailsCache[id]['caption'], SUGAR.util.additionalDetailsCache[id]['width'], SUGAR.util.additionalDetailsCache[id]['theme']);
3244                                 }
3245
3246                                 if(typeof SUGAR.util.additionalDetailsCache[id] != 'undefined')
3247                                         return oReturn(SUGAR.util.additionalDetailsCache[id]['body'], SUGAR.util.additionalDetailsCache[id]['caption'], SUGAR.util.additionalDetailsCache[id]['width'], SUGAR.util.additionalDetailsCache[id]['theme']);
3248
3249                                 if(typeof SUGAR.util.additionalDetailsCalls[id] != 'undefined') // call already in progress
3250                                         return;
3251                                 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_LOADING'));
3252                                 url = 'index.php?to_pdf=1&module=Home&action=AdditionalDetailsRetrieve&bean=' + bean + '&id=' + id;
3253                                 if(show_buttons)
3254                                         url += '&show_buttons=true';
3255                                 SUGAR.util.additionalDetailsCalls[id] = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
3256
3257                                 return false;
3258                         }
3259                         SUGAR.util.additionalDetailsRpcCall = window.setTimeout('go()', 250);
3260                 },
3261                 clearAdditionalDetailsCall: function() {
3262                         if(typeof SUGAR.util.additionalDetailsRpcCall == 'number') window.clearTimeout(SUGAR.util.additionalDetailsRpcCall);
3263                 },
3264                 /**
3265                  * A function that extends functionality from parent to child.
3266                  */
3267                 extend : function(subc, superc, overrides) {
3268                         subc.prototype = new superc;    // set the superclass
3269                         // overrides
3270                         if (overrides) {
3271                             for (var i in overrides)    subc.prototype[i] = overrides[i];
3272                         }
3273                 },
3274                 hrefURL : function(url) {
3275                         if(SUGAR.isIE) {
3276                                 // IE needs special treatment since otherwise it would not pass Referer
3277                                 var trampoline = document.createElement('a');
3278                                 trampoline.href = url;
3279                                 document.body.appendChild(trampoline);
3280                                 trampoline.click();
3281                                 document.body.removeChild(trampoline);
3282                         } else {
3283                                 document.location.href = url;
3284                         }
3285                 },
3286
3287                 openWindow : function(URL, windowName, windowFeatures) {
3288                         if(SUGAR.isIE) {
3289                                 // IE needs special treatment since otherwise it would not pass Referer
3290                                 win = window.open('', windowName, windowFeatures);
3291                                 var trampoline = document.createElement('a');
3292                                 trampoline.href = URL;
3293                                 trampoline.target = windowName;
3294                                 document.body.appendChild(trampoline);
3295                                 trampoline.click();
3296                                 document.body.removeChild(trampoline);
3297                         } else {
3298                                 win = window.open(URL, windowName, windowFeatures);
3299                         }
3300                         return win;
3301                 },
3302         //Reset the scroll on the window
3303         top : function() {
3304                         window.scroll(0,0);
3305                 },
3306
3307         //Based on YUI onAvailible, but will use any boolean function instead of an ID
3308         doWhen : function(condition, fn, params, scope)
3309         {
3310             this._doWhenStack.push({
3311                 check:condition,
3312                 fn:         fn,
3313                 obj:        params,
3314                 overrideContext:   scope
3315             });
3316
3317             this._doWhenretryCount = 50;
3318             this._startDoWhenInterval();
3319         },
3320
3321         _startDoWhenInterval : function(){
3322             if (!this._doWhenInterval) {
3323                 this._doWhenInterval = YAHOO.lang.later(50, this, this._doWhenCheck, null, true);
3324             }
3325         },
3326         _doWhenStack : [],
3327         _doWhenInterval : false,
3328         _doWhenCheck : function() {
3329                 if (this._doWhenStack.length === 0) {
3330                     this._doWhenretryCount = 0;
3331                     if (this._doWhenInterval) {
3332                         // clearInterval(this._interval);
3333                         this._doWhenInterval.cancel();
3334                         this._doWhenInterval = null;
3335                     }
3336                     return;
3337                 }
3338
3339                 if (this._doWhenLocked) {
3340                     return;
3341                 }
3342
3343                 if (SUGAR.isIE) {
3344                     // Hold off if DOMReady has not fired and check current
3345                     // readyState to protect against the IE operation aborted
3346                     // issue.
3347                     if (!YAHOO.util.Event.DOMReady) {
3348                         this._startDoWhenInterval();
3349                         return;
3350                     }
3351                 }
3352
3353                 this._doWhenLocked = true;
3354
3355
3356                 // keep trying until after the page is loaded.  We need to
3357                 // check the page load state prior to trying to bind the
3358                 // elements so that we can be certain all elements have been
3359                 // tested appropriately
3360                 var tryAgain = YAHOO.util.Event.DOMReady;
3361                 if (!tryAgain) {
3362                     tryAgain = (this._doWhenretryCount > 0 && this._doWhenStack.length > 0);
3363                 }
3364
3365                 // onAvailable
3366                 var notAvail = [];
3367
3368                 var executeItem = function (context, item) {
3369                     if (item.overrideContext) {
3370                         if (item.overrideContext === true) {
3371                             context = item.obj;
3372                         } else {
3373                             context = item.overrideContext;
3374                         }
3375                     }
3376                     if(item.fn) {
3377                         item.fn.call(context, item.obj);
3378                     }
3379                 };
3380
3381                 var i, len, item, test;
3382
3383                 // onAvailable onContentReady
3384                 for (i=0, len=this._doWhenStack.length; i<len; i=i+1) {
3385                     item = this._doWhenStack[i];
3386                     if (item) {
3387                         test = item.check;
3388                         if ((typeof(test) == "string" && eval(test)) || (typeof(test) == "function" && test())) {
3389                             executeItem(this, item);
3390                             this._doWhenStack[i] = null;
3391                         }
3392                          else {
3393                             notAvail.push(item);
3394                         }
3395                     }
3396                 }
3397
3398                 this._doWhenretryCount--;
3399
3400                 if (tryAgain) {
3401                     for (i=this._doWhenStack.length-1; i>-1; i--) {
3402                         item = this._doWhenStack[i];
3403                         if (!item || !item.check) {
3404                             this._doWhenStack.splice(i, 1);
3405                         }
3406                     }
3407                     this._startDoWhenInterval();
3408                 } else {
3409                     if (this._doWhenInterval) {
3410                         // clearInterval(this._interval);
3411                         this._doWhenInterval.cancel();
3412                         this._doWhenInterval = null;
3413                     }
3414                 }
3415                 this._doWhenLocked = false;
3416             },
3417         buildAccessKeyLabels : function() {
3418             if (typeof(Y.env.ua) !== 'undefined'){
3419                 envStr = '';
3420                 browserOS = Y.env.ua['os'];
3421                 isIE = Y.env.ua['ie'];
3422                 isCR = Y.env.ua['chrome'];
3423                 isFF = Y.env.ua['gecko'];
3424                 isWK = Y.env.ua['webkit'];
3425                 isOP = Y.env.ua['opera'];
3426                 controlKey = '';
3427
3428                 //first determine the OS
3429                 if(browserOS=='macintosh'){
3430                     //we got a mac, lets use the mac specific commands while we check the browser
3431                     if(isIE){
3432                         //IE on a Mac? Not possible, but let's assign alt anyways for completions sake
3433                         controlKey = 'Alt+';
3434                     }else if(isWK){
3435                         //Chrome or safari on a mac
3436                         controlKey = 'Ctrl+Opt+';
3437                     }else if(isOP){
3438                         //Opera on a mac
3439                         controlKey = 'Shift+Esc: ';
3440                     }else{
3441                         //default FF and everything else on a mac
3442                         controlKey = 'Ctrl+';
3443                     }
3444                 }else{
3445                     //this is not a mac so let's use the windows/unix commands while we check the browser
3446                     if(isFF){
3447                         //FF on windows/unix
3448                         controlKey = 'Alt+Shift+';
3449                     }else if(isOP){
3450                         //Opera on windows/unix
3451                         controlKey = 'Shift+Esc: ';
3452                     }else {
3453                         //this is the default for safari, IE and Chrome
3454                         //if this is webkit and is NOT google, then we are most likely looking at Safari
3455                         controlKey = 'Alt+';
3456                     }
3457
3458                 }
3459
3460                 //now lets retrieve all elements of type input
3461                 allButtons = document.getElementsByTagName('input');
3462                 //iterate through list and modify title if the accesskey is not empty
3463                 for(i=0;i<allButtons.length;i++){
3464                     if(allButtons[i].getAttribute('accesskey') && allButtons[i].getAttribute('type') && allButtons[i].getAttribute('type')=='button'){
3465                         allButtons[i].setAttribute('title',allButtons[i].getAttribute('title')+' ['+controlKey+allButtons[i].getAttribute('accesskey')+']');
3466                     }
3467                 }
3468                 //now change the text in the help div
3469                 $("#shortcuts_dialog").html(function(i, text)  {
3470                     return text.replace(/Alt\+/g,controlKey);
3471                 });
3472             }// end if (typeof(Y.env.ua) !== 'undefined')
3473         }//end buildAccessKeyLabels()
3474         };
3475 }(); // end util
3476 SUGAR.util.additionalDetailsCache = new Array();
3477 SUGAR.util.additionalDetailsCalls = new Array();
3478 if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.util.setMaxLength); // allow textareas to obey maxlength attrib
3479
3480 SUGAR.savedViews = function() {
3481         var selectedOrderBy;
3482         var selectedSortOrder;
3483         var displayColumns;
3484         var hideTabs;
3485         var columnsMeta; // meta data for the display columns
3486
3487         return {
3488                 setChooser: function() {
3489
3490                         var displayColumnsDef = new Array();
3491                         var hideTabsDef = new Array();
3492
3493                     var left_td = document.getElementById('display_tabs_td');
3494                     if(typeof left_td == 'undefined' || left_td == null) return; // abort!
3495                     var right_td = document.getElementById('hide_tabs_td');
3496
3497                     var displayTabs = left_td.getElementsByTagName('select')[0];
3498                     var hideTabs = right_td.getElementsByTagName('select')[0];
3499
3500                         for(i = 0; i < displayTabs.options.length; i++) {
3501                                 displayColumnsDef.push(displayTabs.options[i].value);
3502                         }
3503
3504                         if(typeof hideTabs != 'undefined') {
3505                                 for(i = 0; i < hideTabs.options.length; i++) {
3506                                  hideTabsDef.push(hideTabs.options[i].value);
3507                                 }
3508                         }
3509                         if (!SUGAR.savedViews.clearColumns)
3510                                 document.getElementById('displayColumnsDef').value = displayColumnsDef.join('|');
3511                         document.getElementById('hideTabsDef').value = hideTabsDef.join('|');
3512                 },
3513
3514                 select: function(saved_search_select) {
3515                         for(var wp = 0; wp < document.search_form.saved_search_select.options.length; wp++) {
3516                                 if(typeof document.search_form.saved_search_select.options[wp].value != 'undefined' &&
3517                                         document.search_form.saved_search_select.options[wp].value == saved_search_select) {
3518                                                 document.search_form.saved_search_select.selectedIndex = wp;
3519                                                 document.search_form.ss_delete.style.display = '';
3520                                                 document.search_form.ss_update.style.display = '';
3521                                 }
3522                         }
3523                 },
3524                 saved_search_action: function(action, delete_lang) {
3525                         if(action == 'delete') {
3526                                 if(!confirm(delete_lang)) return;
3527                         }
3528                         if(action == 'save') {
3529                                 if(document.search_form.saved_search_name.value.replace(/^\s*|\s*$/g, '') == '') {
3530                                         alert(SUGAR.language.get('app_strings', 'LBL_SAVED_SEARCH_ERROR'));
3531                                         return;
3532                                 }
3533                         }
3534
3535                         // This check is needed for the Activities module (Calls/Meetings/Tasks).
3536                         if (document.search_form.saved_search_action)
3537                         {
3538                                 document.search_form.saved_search_action.value = action;
3539                                 document.search_form.search_module.value = document.search_form.module.value;
3540                                 document.search_form.module.value = 'SavedSearch';
3541                                 // Bug 31922 - Make sure to specify that we want to hit the index view here of
3542                                 // the SavedSearch module, since the ListView doesn't have the logic to save the
3543                                 // search and redirect back
3544                                 document.search_form.action.value = 'index';
3545                         }
3546                         SUGAR.ajaxUI.submitForm(document.search_form);
3547                 },
3548                 shortcut_select: function(selectBox, module) {
3549                         //build url
3550                         selecturl = 'index.php?module=SavedSearch&search_module=' + module + '&action=index&saved_search_select=' + selectBox.options[selectBox.selectedIndex].value
3551                         //add searchFormTab to url if it is available.  This determines what tab to render
3552                         if(typeof(document.getElementById('searchFormTab'))!='undefined'){
3553                                 selecturl = selecturl + '&searchFormTab=' + document.search_form.searchFormTab.value;
3554                         }
3555                         //add showSSDIV to url if it is available.  This determines whether saved search sub form should
3556                         //be rendered open or not
3557                         if(document.getElementById('showSSDIV') && typeof(document.getElementById('showSSDIV') !='undefined')){
3558                                 selecturl = selecturl + '&showSSDIV='+document.getElementById('showSSDIV').value;
3559                         }
3560                         //use created url to navigate
3561                         document.location.href = selecturl;
3562                 },
3563                 handleForm: function() {
3564                         SUGAR.tabChooser.movementCallback = function(left_side, right_side) {
3565                                 while(document.getElementById('orderBySelect').childNodes.length != 0) { // clear out order by options
3566                                         document.getElementById('orderBySelect').removeChild(document.getElementById('orderBySelect').lastChild);
3567                                 }
3568
3569                                 var selectedIndex = 0;
3570                                 var nodeCount = -1; // need this because the counter i also includes "undefined" nodes
3571                                                                         // which was breaking Calls and Meetings
3572
3573                                 for(i in left_side.childNodes) { // fill in order by options
3574                                         if(typeof left_side.childNodes[i].nodeName != 'undefined' &&
3575                                                 left_side.childNodes[i].nodeName.toLowerCase() == 'option' &&
3576                                                 typeof SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value] != 'undefined' && // check if column is sortable
3577                                                 typeof SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value]['sortable'] == 'undefined' &&
3578                                                 SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value]['sortable'] != false) {
3579                                                         nodeCount++;
3580                                                         optionNode = document.createElement('option');
3581                                                         optionNode.value = left_side.childNodes[i].value;
3582                                                         optionNode.innerHTML = left_side.childNodes[i].innerHTML;
3583                                                         document.getElementById('orderBySelect').appendChild(optionNode);
3584                                                         if(optionNode.value == SUGAR.savedViews.selectedOrderBy)
3585                                                                 selectedIndex = nodeCount;
3586                                         }
3587                                 }
3588                                 // Firefox needs this to be set after all the option nodes are created.
3589                                 document.getElementById('orderBySelect').selectedIndex = selectedIndex;
3590                         };
3591                         SUGAR.tabChooser.movementCallback(document.getElementById('display_tabs_td').getElementsByTagName('select')[0]);
3592
3593                         // This check is needed for the Activities module (Calls/Meetings/Tasks).
3594                         if (document.search_form.orderBy)
3595                                 document.search_form.orderBy.options.value = SUGAR.savedViews.selectedOrderBy;
3596
3597                         // handle direction
3598                         if(SUGAR.savedViews.selectedSortOrder == 'DESC') document.getElementById('sort_order_desc_radio').checked = true;
3599                         else document.getElementById('sort_order_asc_radio').checked = true;
3600                 }
3601         };
3602 }();
3603
3604 SUGAR.searchForm = function() {
3605         var url;
3606         return {
3607                 // searchForm tab selector util
3608                 searchFormSelect: function(view, previousView) {
3609                         var module = view.split('|')[0];
3610                         var theView = view.split('|')[1];
3611                         // retrieve form
3612                         var handleDisplay = function() { // hide other divs
3613                                 document.search_form.searchFormTab.value = theView;
3614                                 patt = module+"(.*)SearchForm$";
3615                                 divId=document.search_form.getElementsByTagName('div');
3616                                 // Hide all the search forms and retrive the name of the previous search tab (useful for the first load because previousView is empty)
3617                                 for (i=0;i<divId.length;i++){
3618                                         if(divId[i].id.match(module)==module){
3619                                                 if(divId[i].id.match('SearchForm')=='SearchForm'){
3620                                 if(document.getElementById(divId[i].id).style.display == ''){
3621                                    previousTab=divId[i].id.match(patt)[1];
3622                                 }
3623                                 document.getElementById(divId[i].id).style.display = 'none';
3624                             }
3625                                         }
3626                                 }
3627
3628                 //clear thesearch form accesekeys and reset them to the appropriate link
3629                 adv = document.getElementById('advanced_search_link');
3630                 bas = document.getElementById('basic_search_link');
3631                 adv.setAttribute('accesskey','');
3632                 bas.setAttribute('accesskey','');
3633                 a_key = SUGAR.language.get("app_strings", "LBL_ADV_SEARCH_LNK_KEY");
3634
3635                 //reset the ccesskey based on theview
3636                 if(theView === 'advanced_search'){
3637
3638                     bas.setAttribute('accesskey',a_key);
3639                 }else{
3640                     adv.setAttribute('accesskey',a_key);
3641                 }
3642                 
3643                                 // show the good search form.
3644                                 document.getElementById(module + theView + 'SearchForm').style.display = '';
3645                 //if its not the first tab show there is a previous tab.
3646                 if(previousView) {
3647                      thepreviousView=previousView.split('|')[1];
3648                  }
3649                  else{
3650                      thepreviousView=previousTab;
3651                  }
3652                  thepreviousView=thepreviousView.replace(/_search/, "");
3653                  // Process to retrieve the completed field from one tab to an other.
3654                  for(num in document.search_form.elements) {
3655                      if(document.search_form.elements[num]) {
3656                          el = document.search_form.elements[num];
3657                          pattern="^(.*)_"+thepreviousView+"$";
3658                          if(typeof el.type != 'undefined' && typeof el.name != 'undefined' && el.name.match(pattern)) {
3659                              advanced_input_name = el.name.match(pattern)[1]; // strip
3660                              advanced_input_name = advanced_input_name+"_"+theView.replace(/_search/, "");
3661                              if(typeof document.search_form[advanced_input_name] != 'undefined')  // if advanced input of same name exists
3662                                  SUGAR.searchForm.copyElement(advanced_input_name, el);
3663                          }
3664                      }
3665                  }
3666                         }
3667
3668                         // if tab is not cached
3669                         if(document.getElementById(module + theView + 'SearchForm').innerHTML == '') {
3670                                 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_LOADING'));
3671                                 var success = function(data) {
3672                                         document.getElementById(module + theView + 'SearchForm').innerHTML = data.responseText;
3673
3674                                         SUGAR.util.evalScript(data.responseText);
3675                                         // pass script variables to global scope
3676                                         if(theView == 'saved_views') {
3677                                                 if(typeof columnsMeta != 'undefined') SUGAR.savedViews.columnsMeta = columnsMeta;
3678                                                 if(typeof selectedOrderBy != 'undefined') SUGAR.savedViews.selectedOrderBy = selectedOrderBy;
3679                                                 if(typeof selectedSortOrder != 'undefined') SUGAR.savedViews.selectedSortOrder = selectedSortOrder;
3680                                         }
3681
3682                                         handleDisplay();
3683                                         enableQS(true);
3684                                         ajaxStatus.hideStatus();
3685                                 }
3686                                 url =   'index.php?module=' + module + '&action=index&search_form_only=true&to_pdf=true&search_form_view=' + theView;
3687
3688                                 //check to see if tpl has been specified.  If so then pass location through url string
3689                                 var tpl ='';
3690                                 if(document.getElementById('search_tpl') !=null && typeof(document.getElementById('search_tpl')) != 'undefined'){
3691                                         tpl = document.getElementById('search_tpl').value;
3692                                         if(tpl != ''){url += '&search_tpl='+tpl;}
3693                                 }
3694
3695                                 if(theView == 'saved_views') // handle the tab chooser
3696                                         url += '&displayColumns=' + SUGAR.savedViews.displayColumns + '&hideTabs=' + SUGAR.savedViews.hideTabs + '&orderBy=' + SUGAR.savedViews.selectedOrderBy + '&sortOrder=' + SUGAR.savedViews.selectedSortOrder;
3697
3698                                 var cObj = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
3699                         }
3700                         else { // that form already retrieved
3701                                 handleDisplay();
3702                         }
3703                 },
3704
3705                 // copies one input to another
3706                 copyElement: function(inputName, copyFromElement) {
3707                         switch(copyFromElement.type) {
3708                                 case 'select-one':
3709                                 case 'text':
3710                                         document.search_form[inputName].value = copyFromElement.value;
3711                                         break;
3712                         }
3713                 },
3714         // This function is here to clear the form, instead of "resubmitting it
3715                 clear_form: function(form, skipElementNames) {
3716             var elemList = form.elements;
3717             var elem;
3718             var elemType;
3719
3720             for( var i = 0; i < elemList.length ; i++ ) {
3721                 elem = elemList[i];
3722                 if ( typeof(elem.type) == 'undefined' ) {
3723                     continue;
3724                 }
3725
3726                 if ( typeof(elem.type) != 'undefined' && typeof(skipElementNames) != 'undefined'
3727                         && SUGAR.util.arrayIndexOf(skipElementNames, elem.name) != -1 )
3728                 {
3729                     continue;
3730                 }
3731
3732                 elemType = elem.type.toLowerCase();
3733
3734                 if ( elemType == 'text' || elemType == 'textarea' || elemType == 'password' ) {
3735                     elem.value = '';
3736                 }
3737                 else if ( elemType == 'select' || elemType == 'select-one' || elemType == 'select-multiple' ) {
3738                     // We have, what I hope, is a select box, time to unselect all options
3739                     var optionList = elem.options;
3740
3741                     if (optionList.length > 0) {
3742                         optionList[0].selected = "selected";
3743                     }
3744
3745                     for ( var ii = 0 ; ii < optionList.length ; ii++ ) {
3746                         optionList[ii].selected = false;
3747                     }
3748                 }
3749                 else if ( elemType == 'radio' || elemType == 'checkbox' ) {
3750                     elem.checked = false;
3751                     elem.selected = false;
3752                 }
3753                 else if ( elemType == 'hidden' ) {
3754                     // We only want to reset the hidden values that link to the select boxes.
3755                     // _c custom field kludge added to fix Bug 41384
3756                     if ( ( elem.name.length > 3 && elem.name.substring(elem.name.length-3) == '_id' )
3757                          || ((elem.name.length > 9) && (elem.name.substring(elem.name.length - 9) == '_id_basic'))
3758                          || ( elem.name.length > 12 && elem.name.substring(elem.name.length-12) == '_id_advanced' )
3759                          || ( elem.name.length > 2 && elem.name.substring(elem.name.length-2) == '_c' )
3760                          || ((elem.name.length > 8) && (elem.name.substring(elem.name.length - 8) == '_c_basic'))
3761                          || ( elem.name.length > 11 && elem.name.substring(elem.name.length-11) == '_c_advanced' ) )
3762                     {
3763                         elem.value = '';
3764                     }
3765                 }
3766             }
3767                         SUGAR.savedViews.clearColumns = true;
3768                 }
3769         };
3770 }();
3771 // Code for the column/tab chooser used on homepage and in admin section
3772 SUGAR.tabChooser = function () {
3773         var     object_refs = new Array();
3774         return {
3775                         /* Describe certain transfers as invalid */
3776                         frozenOptions: [],
3777
3778                         movementCallback: function(left_side, right_side) {},
3779                         orderCallback: function(left_side, right_side) {},
3780
3781                         freezeOptions: function(left_name, right_name, target) {
3782                                 if(!SUGAR.tabChooser.frozenOptions) { SUGAR.tabChooser.frozenOptions = []; }
3783                                 if(!SUGAR.tabChooser.frozenOptions[left_name]) { SUGAR.tabChooser.frozenOptions[left_name] = []; }
3784                                 if(!SUGAR.tabChooser.frozenOptions[left_name][right_name]) { SUGAR.tabChooser.frozenOptions[left_name][right_name] = []; }
3785                                 if(typeof target == 'array') {
3786                                         for(var i in target) {
3787                                                 SUGAR.tabChooser.frozenOptions[left_name][right_name][target[i]] = true;
3788                                         }
3789                                 } else {
3790                                         SUGAR.tabChooser.frozenOptions[left_name][right_name][target] = true;
3791                                 }
3792                         },
3793
3794                         buildSelectHTML: function(info) {
3795                                 var text = "<select";
3796
3797                         if(typeof (info['select']['size']) != 'undefined') {
3798                                 text +=" size=\""+ info['select']['size'] +"\"";
3799                         }
3800
3801                         if(typeof (info['select']['name']) != 'undefined') {
3802                                 text +=" name=\""+ info['select']['name'] +"\"";
3803                         }
3804
3805                         if(typeof (info['select']['style']) != 'undefined') {
3806                                 text +=" style=\""+ info['select']['style'] +"\"";
3807                         }
3808
3809                         if(typeof (info['select']['onchange']) != 'undefined') {
3810                                 text +=" onChange=\""+ info['select']['onchange'] +"\"";
3811                         }
3812
3813                         if(typeof (info['select']['multiple']) != 'undefined') {
3814                                 text +=" multiple";
3815                         }
3816                         text +=">";
3817
3818                         for(i=0; i<info['options'].length;i++) {
3819                                 option = info['options'][i];
3820                                 text += "<option value=\""+option['value']+"\" ";
3821                                 if ( typeof (option['selected']) != 'undefined' && option['selected']== true) {
3822                                         text += "SELECTED";
3823                                 }
3824                                 text += ">"+option['text']+"</option>";
3825                         }
3826                         text += "</select>";
3827                         return text;
3828                         },
3829
3830                         left_to_right: function(left_name, right_name, left_size, right_size) {
3831                                 SUGAR.savedViews.clearColumns = false;
3832                             var left_td = document.getElementById(left_name+'_td');
3833                             var right_td = document.getElementById(right_name+'_td');
3834
3835                             var display_columns_ref = left_td.getElementsByTagName('select')[0];
3836                             var hidden_columns_ref = right_td.getElementsByTagName('select')[0];
3837
3838                             var selected_left = new Array();
3839                             var notselected_left = new Array();
3840                             var notselected_right = new Array();
3841
3842                             var left_array = new Array();
3843
3844                             var frozen_options = SUGAR.tabChooser.frozenOptions;
3845                             frozen_options = frozen_options && frozen_options[left_name] && frozen_options[left_name][right_name]?frozen_options[left_name][right_name]:[];
3846
3847                                 // determine which options are selected in left
3848                             for (i=0; i < display_columns_ref.options.length; i++)
3849                             {
3850                                 if ( display_columns_ref.options[i].selected == true && !frozen_options[display_columns_ref.options[i].value])
3851                                 {
3852                                     selected_left[selected_left.length] = {text: display_columns_ref.options[i].text, value: display_columns_ref.options[i].value};
3853                                 }
3854                                 else
3855                                 {
3856                                     notselected_left[notselected_left.length] = {text: display_columns_ref.options[i].text, value: display_columns_ref.options[i].value};
3857                                 }
3858
3859                             }
3860
3861                             for (i=0; i < hidden_columns_ref.options.length; i++)
3862                             {
3863                                 notselected_right[notselected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
3864
3865                             }
3866
3867                             var left_select_html_info = new Object();
3868                             var left_options = new Array();
3869                             var left_select = new Object();
3870
3871                             left_select['name'] = left_name+'[]';
3872                             left_select['id'] = left_name;
3873                             left_select['size'] = left_size;
3874                             left_select['multiple'] = 'true';
3875
3876                             var right_select_html_info = new Object();
3877                             var right_options = new Array();
3878                             var right_select = new Object();
3879
3880                             right_select['name'] = right_name+'[]';
3881                             right_select['id'] = right_name;
3882                             right_select['size'] = right_size;
3883                             right_select['multiple'] = 'true';
3884
3885                             for (i = 0; i < notselected_right.length; i++) {
3886                                 right_options[right_options.length] = notselected_right[i];
3887                             }
3888
3889                             for (i = 0; i < selected_left.length; i++) {
3890                                 right_options[right_options.length] = selected_left[i];
3891                             }
3892                             for (i = 0; i < notselected_left.length; i++) {
3893                                 left_options[left_options.length] = notselected_left[i];
3894                             }
3895                             left_select_html_info['options'] = left_options;
3896                             left_select_html_info['select'] = left_select;
3897                             right_select_html_info['options'] = right_options;
3898                             right_select_html_info['select'] = right_select;
3899                             right_select_html_info['style'] = 'background: lightgrey';
3900
3901                             var left_html = this.buildSelectHTML(left_select_html_info);
3902                             var right_html = this.buildSelectHTML(right_select_html_info);
3903
3904                             left_td.innerHTML = left_html;
3905                             right_td.innerHTML = right_html;
3906
3907                                 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3908                                 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3909
3910                                 this.movementCallback(object_refs[left_name], object_refs[right_name]);
3911
3912                             return false;
3913                         },
3914
3915
3916                         right_to_left: function(left_name, right_name, left_size, right_size, max_left) {
3917                                 SUGAR.savedViews.clearColumns = false;
3918                             var left_td = document.getElementById(left_name+'_td');
3919                             var right_td = document.getElementById(right_name+'_td');
3920
3921                             var display_columns_ref = left_td.getElementsByTagName('select')[0];
3922                             var hidden_columns_ref = right_td.getElementsByTagName('select')[0];
3923
3924                             var selected_right = new Array();
3925                             var notselected_right = new Array();
3926                             var notselected_left = new Array();
3927
3928                             var frozen_options = SUGAR.tabChooser.frozenOptions;
3929                             frozen_options = SUGAR.tabChooser.frozenOptions && SUGAR.tabChooser.frozenOptions[right_name] && SUGAR.tabChooser.frozenOptions[right_name][left_name]?SUGAR.tabChooser.frozenOptions[right_name][left_name]:[];
3930
3931                             for (i=0; i < hidden_columns_ref.options.length; i++)
3932                             {
3933                                 if (hidden_columns_ref.options[i].selected == true && !frozen_options[hidden_columns_ref.options[i].value])
3934                                 {
3935                                     selected_right[selected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
3936                                 }
3937                                 else
3938                                 {
3939                                     notselected_right[notselected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
3940                                 }
3941
3942                             }
3943
3944                             if(max_left != '' && (display_columns_ref.length + selected_right.length) > max_left) {
3945                                 alert('Maximum of ' + max_left + ' columns can be displayed.');
3946                                         return;
3947                             }
3948
3949                             for (i=0; i < display_columns_ref.options.length; i++)
3950                             {
3951                                 notselected_left[notselected_left.length] = {text:display_columns_ref.options[i].text, value:display_columns_ref.options[i].value};
3952
3953                             }
3954
3955                             var left_select_html_info = new Object();
3956                             var left_options = new Array();
3957                             var left_select = new Object();
3958
3959                             left_select['name'] = left_name+'[]';
3960                             left_select['id'] = left_name;
3961                             left_select['multiple'] = 'true';
3962                             left_select['size'] = left_size;
3963
3964                             var right_select_html_info = new Object();
3965                             var right_options = new Array();
3966                             var right_select = new Object();
3967
3968                             right_select['name'] = right_name+ '[]';
3969                             right_select['id'] = right_name;
3970                             right_select['multiple'] = 'true';
3971                             right_select['size'] = right_size;
3972
3973                             for (i = 0; i < notselected_left.length; i++) {
3974                                 left_options[left_options.length] = notselected_left[i];
3975                             }
3976
3977                             for (i = 0; i < selected_right.length; i++) {
3978                                 left_options[left_options.length] = selected_right[i];
3979                             }
3980                             for (i = 0; i < notselected_right.length; i++) {
3981                                 right_options[right_options.length] = notselected_right[i];
3982                             }
3983                             left_select_html_info['options'] = left_options;
3984                             left_select_html_info['select'] = left_select;
3985                             right_select_html_info['options'] = right_options;
3986                             right_select_html_info['select'] = right_select;
3987                             right_select_html_info['style'] = 'background: lightgrey';
3988
3989                             var left_html = this.buildSelectHTML(left_select_html_info);
3990                             var right_html = this.buildSelectHTML(right_select_html_info);
3991
3992                             left_td.innerHTML = left_html;
3993                             right_td.innerHTML = right_html;
3994
3995                                 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3996                                 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3997
3998                                 this.movementCallback(object_refs[left_name], object_refs[right_name]);
3999
4000                             return false;
4001                         },
4002
4003                         up: function(name, left_name, right_name) {
4004                                 SUGAR.savedViews.clearColumns = false;
4005                             var left_td = document.getElementById(left_name+'_td');
4006                             var right_td = document.getElementById(right_name+'_td');
4007                             var td = document.getElementById(name+'_td');
4008                             var obj = td.getElementsByTagName('select')[0];
4009                             obj = (typeof obj == "string") ? document.getElementById(obj) : obj;
4010                             if (obj.tagName.toLowerCase() != "select" && obj.length < 2)
4011                                 return false;
4012                             var sel = new Array();
4013
4014                             for (i=0; i<obj.length; i++) {
4015                                 if (obj[i].selected == true) {
4016                                     sel[sel.length] = i;
4017                                 }
4018                             }
4019                             for (i=0; i < sel.length; i++) {
4020                                 if (sel[i] != 0 && !obj[sel[i]-1].selected) {
4021                                     var tmp = new Array(obj[sel[i]-1].text, obj[sel[i]-1].value);
4022                                     obj[sel[i]-1].text = obj[sel[i]].text;
4023                                     obj[sel[i]-1].value = obj[sel[i]].value;
4024                                     obj[sel[i]].text = tmp[0];
4025                                     obj[sel[i]].value = tmp[1];
4026                                     obj[sel[i]-1].selected = true;
4027                                     obj[sel[i]].selected = false;
4028                                 }
4029                             }
4030
4031                                 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
4032                                 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
4033
4034                                 this.orderCallback(object_refs[left_name], object_refs[right_name]);
4035
4036                             return false;
4037                         },
4038
4039                         down: function(name, left_name, right_name) {
4040                                 SUGAR.savedViews.clearColumns = false;
4041                                 var left_td = document.getElementById(left_name+'_td');
4042                             var right_td = document.getElementById(right_name+'_td');
4043                             var td = document.getElementById(name+'_td');
4044                             var obj = td.getElementsByTagName('select')[0];
4045                             if (obj.tagName.toLowerCase() != "select" && obj.length < 2)
4046                                 return false;
4047                             var sel = new Array();
4048                             for (i=obj.length-1; i>-1; i--) {
4049                                 if (obj[i].selected == true) {
4050                                     sel[sel.length] = i;
4051                                 }
4052                             }
4053                             for (i=0; i < sel.length; i++) {
4054                                 if (sel[i] != obj.length-1 && !obj[sel[i]+1].selected) {
4055                                     var tmp = new Array(obj[sel[i]+1].text, obj[sel[i]+1].value);
4056                                     obj[sel[i]+1].text = obj[sel[i]].text;
4057                                     obj[sel[i]+1].value = obj[sel[i]].value;
4058                                     obj[sel[i]].text = tmp[0];
4059                                     obj[sel[i]].value = tmp[1];
4060                                     obj[sel[i]+1].selected = true;
4061                                     obj[sel[i]].selected = false;
4062                                 }
4063                             }
4064
4065                                 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
4066                                 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
4067
4068                                 this.orderCallback(object_refs[left_name], object_refs[right_name]);
4069
4070                             return false;
4071                         }
4072                 };
4073 }(); // end tabChooser
4074
4075 SUGAR.language = function() {
4076     return {
4077         languages : new Array(),
4078
4079         setLanguage: function(module, data) {
4080            if (!SUGAR.language.languages) {
4081
4082            }
4083             SUGAR.language.languages[module] = data;
4084         },
4085
4086         get: function(module, str) {
4087             if(typeof SUGAR.language.languages[module] == 'undefined' || typeof SUGAR.language.languages[module][str] == 'undefined')
4088             {
4089                 return 'undefined';
4090             }
4091             return SUGAR.language.languages[module][str];
4092         },
4093
4094         translate: function(module, str)
4095         {
4096             text = this.get(module, str);
4097             return text != 'undefined' ? text : this.get('app_strings', str);
4098         }
4099     }
4100 }();
4101
4102 SUGAR.contextMenu = function() {
4103         return {
4104                 objects: new Object(),
4105                 objectTypes: new Object(),
4106                 /**
4107                  * Registers a new object for the context menu.
4108                  * objectType - name of the type
4109                  * id - element id
4110                  * metaData - metaData to pass to the action function
4111                  **/
4112                 registerObject: function(objectType, id, metaData) {
4113                         SUGAR.contextMenu.objects[id] = new Object();
4114             SUGAR.contextMenu.objects[id] = {'objectType' : objectType, 'metaData' : metaData};
4115                 },
4116                 /**
4117                  * Registers a new object type
4118                  * name - name of the type
4119                  * menuItems - array of menu items
4120                  **/
4121                 registerObjectType: function(name, menuItems) {
4122                         SUGAR.contextMenu.objectTypes[name] = new Object();
4123                         SUGAR.contextMenu.objectTypes[name] = {'menuItems' : menuItems, 'objects' : new Array()};
4124                 },
4125                 /**
4126                  * Determines which menu item was clicked
4127                  **/
4128                 getListItemFromEventTarget: function(p_oNode) {
4129             var oLI;
4130             if(p_oNode.tagName == "LI") {
4131                     oLI = p_oNode;
4132             }
4133             else {
4134                     do {
4135                         if(p_oNode.tagName == "LI") {
4136                             oLI = p_oNode;
4137                             break;
4138                         }
4139
4140                     } while((p_oNode = p_oNode.parentNode));
4141                 }
4142             return oLI;
4143          },
4144          /**
4145           * handles movement within context menu
4146           **/
4147          onContextMenuMove: function() {
4148             var oNode = this.contextEventTarget;
4149             var bDisabled = (oNode.tagName == "UL");
4150             var i = this.getItemGroups()[0].length - 1;
4151             do {
4152                 this.getItem(i).cfg.setProperty("disabled", bDisabled);
4153             }
4154             while(i--);
4155         },
4156         /**
4157          * handles clicks on a context menu ITEM
4158          **/
4159                 onContextMenuItemClick: function(p_sType, p_aArguments, p_oItem) {
4160             var oLI = SUGAR.contextMenu.getListItemFromEventTarget(this.parent.contextEventTarget);
4161             id = this.parent.contextEventTarget.parentNode.id; // id of the target
4162             funct = eval(SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[id]['objectType']]['menuItems'][this.index]['action']);
4163             funct(this.parent.contextEventTarget, SUGAR.contextMenu.objects[id]['metaData']);
4164                 },
4165                 /**
4166                  * Initializes all context menus registered
4167                  **/
4168                 init: function() {
4169                         for(var i in SUGAR.contextMenu.objects) { // make a variable called objects in objectTypes containg references to all triggers
4170                 if(typeof SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'] == 'undefined')
4171                     SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'] = new Array();
4172                                 SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'].push(document.getElementById(i));
4173                         }
4174             // register the menus
4175                         for(var i in SUGAR.contextMenu.objectTypes) {
4176                     var oContextMenu = new YAHOO.widget.ContextMenu(i, {'trigger': SUGAR.contextMenu.objectTypes[i]['objects']});
4177                                 var aMainMenuItems = SUGAR.contextMenu.objectTypes[i]['menuItems'];
4178                     var nMainMenuItems = aMainMenuItems.length;
4179                     var oMenuItem;
4180                     for(var j = 0; j < nMainMenuItems; j++) {
4181                         oMenuItem = new YAHOO.widget.ContextMenuItem(aMainMenuItems[j].text, { helptext: aMainMenuItems[j].helptext });
4182                         oMenuItem.clickEvent.subscribe(SUGAR.contextMenu.onContextMenuItemClick, oMenuItem, true);
4183                         oContextMenu.addItem(oMenuItem);
4184                     }
4185                     //  Add a "move" event handler to the context menu
4186                     oContextMenu.moveEvent.subscribe(SUGAR.contextMenu.onContextMenuMove, oContextMenu, true);
4187                     // Add a "keydown" event handler to the context menu
4188                     oContextMenu.keyDownEvent.subscribe(SUGAR.contextMenu.onContextMenuItemClick, oContextMenu, true);
4189                     // Render the context menu
4190                     oContextMenu.render(document.body);
4191                 }
4192                 }
4193         };
4194 }();
4195
4196 SUGAR.contextMenu.actions = function() {
4197         return {
4198                 /**
4199                  * redirects to a new note with the clicked on object as the target
4200                  **/
4201                 createNote: function(itemClicked, metaData) {
4202                         loc = 'index.php?module=Notes&action=EditView';
4203                         for(i in metaData) {
4204                                 if(i == 'notes_parent_type') loc += '&parent_type=' + metaData[i];
4205                                 else if(i != 'module' && i != 'parent_type') loc += '&' + i + '=' + metaData[i];
4206                         }
4207                         document.location = loc;
4208                 },
4209                 /**
4210                  * redirects to a new note with the clicked on object as the target
4211                  **/
4212                 scheduleMeeting: function(itemClicked, metaData) {
4213                         loc = 'index.php?module=Meetings&action=EditView';
4214                         for(i in metaData) {
4215                                 if(i != 'module') 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                 scheduleCall: function(itemClicked, metaData) {
4223                         loc = 'index.php?module=Calls&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 contact with the clicked on object as the target
4231                  **/
4232                 createContact: function(itemClicked, metaData) {
4233                         loc = 'index.php?module=Contacts&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 task with the clicked on object as the target
4241                  **/
4242                 createTask: function(itemClicked, metaData) {
4243                         loc = 'index.php?module=Tasks&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 opportunity with the clicked on object as the target
4251                  **/
4252                 createOpportunity: function(itemClicked, metaData) {
4253                         loc = 'index.php?module=Opportunities&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                 createCase: function(itemClicked, metaData) {
4263                         loc = 'index.php?module=Cases&action=EditView';
4264                         for(i in metaData) {
4265                                 if(i != 'module') loc += '&' + i + '=' + metaData[i];
4266                         }
4267                         document.location = loc;
4268                 },
4269                 /**
4270                  * handles add to favorites menu selection
4271                  **/
4272                 addToFavorites: function(itemClicked, metaData) {
4273                         success = function(data) {
4274                         }
4275                         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});
4276
4277                 }
4278         };
4279 }();
4280 //if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.contextMenu.init);
4281
4282 // initially from popup_parent_helper.js
4283 var popup_request_data;
4284 var close_popup;
4285
4286 function get_popup_request_data()
4287 {
4288         return YAHOO.lang.JSON.stringify(window.document.popup_request_data);
4289 }
4290
4291 function get_close_popup()
4292 {
4293         return window.document.close_popup;
4294 }
4295
4296 function open_popup(module_name, width, height, initial_filter, close_popup, hide_clear_button, popup_request_data, popup_mode, create, metadata)
4297 {
4298         if (typeof(popupCount) == "undefined" || popupCount == 0)
4299            popupCount = 1;
4300
4301         // set the variables that the popup will pull from
4302         window.document.popup_request_data = popup_request_data;
4303         window.document.close_popup = close_popup;
4304
4305         //globally changing width and height of standard pop up window from 600 x 400 to 800 x 800
4306         width = (width == 600) ? 800 : width;
4307         height = (height == 400) ? 800 : height;
4308
4309         // launch the popup
4310         URL = 'index.php?'
4311                 + 'module=' + module_name
4312                 + '&action=Popup';
4313
4314         if (initial_filter != '') {
4315                 URL += '&query=true' + initial_filter;
4316                 // Bug 41891 - Popup Window Name
4317                 popupName = initial_filter.replace(/[^a-z_0-9]+/ig, '_');
4318                 windowName = module_name + '_popup_window' + popupName;
4319         } else {
4320                 windowName = module_name + '_popup_window' + popupCount;
4321         }
4322         popupCount++;
4323
4324         if (hide_clear_button) {
4325                 URL += '&hide_clear_button=true';
4326         }
4327
4328         windowFeatures = 'width=' + width
4329                 + ',height=' + height
4330                 + ',resizable=1,scrollbars=1';
4331
4332         if (popup_mode == '' || popup_mode == undefined) {
4333                 popup_mode='single';
4334         }
4335         URL+='&mode='+popup_mode;
4336         if (create == '' || create == undefined) {
4337                 create = 'false';
4338         }
4339         URL+='&create='+create;
4340
4341         if (metadata != '' && metadata != undefined) {
4342                 URL+='&metadata='+metadata;
4343         }
4344
4345     // Bug #46842 : The relate field field_to_name_array fails to copy over custom fields
4346     // post fields that should be populated from popup form
4347         if(popup_request_data.jsonObject) {
4348                 var request_data = popup_request_data.jsonObject;
4349         } else {
4350                 var request_data = popup_request_data;
4351         }
4352     var field_to_name_array_url = '';
4353
4354     if (request_data && request_data.field_to_name_array != undefined) {
4355         for(var key in request_data.field_to_name_array) {
4356             if ( key.toLowerCase() != 'id' ) {
4357                 field_to_name_array_url += '&field_to_name[]='+encodeURIComponent(key.toLowerCase());
4358             }
4359         }
4360     }
4361     if ( field_to_name_array_url ) {
4362         URL+=field_to_name_array_url;
4363     }
4364
4365         win = SUGAR.util.openWindow(URL, windowName, windowFeatures);
4366
4367         if(window.focus)
4368         {
4369                 // put the focus on the popup if the browser supports the focus() method
4370                 win.focus();
4371         }
4372
4373         win.popupCount = popupCount;
4374
4375         return win;
4376 }
4377
4378 /**
4379  * The reply data must be a JSON array structured with the following information:
4380  *  1) form name to populate
4381  *  2) associative array of input names to values for populating the form
4382  */
4383 var from_popup_return  = false;
4384
4385 //Function replaces special HTML chars for usage in text boxes
4386 function replaceHTMLChars(value) {
4387         return value.replace(/&amp;/gi,'&').replace(/&lt;/gi,'<').replace(/&gt;/gi,'>').replace(/&#039;/gi,'\'').replace(/&quot;/gi,'"');
4388 }
4389
4390 function set_return_basic(popup_reply_data,filter)
4391 {
4392         var form_name = popup_reply_data.form_name;
4393         var name_to_value_array = popup_reply_data.name_to_value_array;
4394         for (var the_key in name_to_value_array)
4395         {
4396                 if(the_key == 'toJSON')
4397                 {
4398                         /* just ignore */
4399                 }
4400                 else if(the_key.match(filter))
4401                 {
4402                         var displayValue=replaceHTMLChars(name_to_value_array[the_key]);
4403                         // begin andopes change: support for enum fields (SELECT)
4404                         if(window.document.forms[form_name] && window.document.forms[form_name].elements[the_key]) {
4405                                 if(window.document.forms[form_name].elements[the_key].tagName == 'SELECT') {
4406                                         var selectField = window.document.forms[form_name].elements[the_key];
4407                                         for(var i = 0; i < selectField.options.length; i++) {
4408                                                 if(selectField.options[i].text == displayValue) {
4409                                                         selectField.options[i].selected = true;
4410                             SUGAR.util.callOnChangeListers(selectField);
4411                                                         break;
4412                                                 }
4413                                         }
4414                                 } else {
4415                                         window.document.forms[form_name].elements[the_key].value = displayValue;
4416                     SUGAR.util.callOnChangeListers(window.document.forms[form_name].elements[the_key]);
4417                                 }
4418                         }
4419                         // end andopes change: support for enum fields (SELECT)
4420                 }
4421         }
4422 }
4423
4424 function set_return(popup_reply_data)
4425 {
4426         from_popup_return = true;
4427         var form_name = popup_reply_data.form_name;
4428         var name_to_value_array = popup_reply_data.name_to_value_array;
4429         if(typeof name_to_value_array != 'undefined' && name_to_value_array['account_id'])
4430         {
4431                 var label_str = '';
4432                 var label_data_str = '';
4433                 var current_label_data_str = '';
4434                 var popupConfirm = popup_reply_data.popupConfirm;
4435                 for (var the_key in name_to_value_array)
4436                 {
4437                         if(the_key == 'toJSON')
4438                         {
4439                                 /* just ignore */
4440                         }
4441                         else
4442                         {
4443                                 var displayValue=replaceHTMLChars(name_to_value_array[the_key]);
4444                                 if(window.document.forms[form_name] && document.getElementById(the_key+'_label') && !the_key.match(/account/)) {
4445                     var data_label = document.getElementById(the_key+'_label').innerHTML.replace(/\n/gi,'').replace(/<\/?[^>]+(>|$)/g, "");
4446                                         label_str += data_label + ' \n';
4447                                         label_data_str += data_label  + ' ' + displayValue + '\n';
4448                                         if(window.document.forms[form_name].elements[the_key]) {
4449                                                 current_label_data_str += data_label + ' ' + window.document.forms[form_name].elements[the_key].value +'\n';
4450                                         }
4451                                 }
4452                         }
4453                 }
4454
4455         if(label_data_str != label_str && current_label_data_str != label_str){
4456                 // Bug 48726 Start
4457                 if (typeof popupConfirm != 'undefined')
4458                 {
4459                         if (popupConfirm > -1) {
4460                                 set_return_basic(popup_reply_data,/\S/);
4461                         } else {
4462                                 set_return_basic(popup_reply_data,/account/);
4463                         }
4464                 }
4465                 // Bug 48726 End
4466                 else if(confirm(SUGAR.language.get('app_strings', 'NTC_OVERWRITE_ADDRESS_PHONE_CONFIRM') + '\n\n' + label_data_str))
4467                         {
4468                         set_return_basic(popup_reply_data,/\S/);
4469                         }
4470                 else
4471                         {
4472                         set_return_basic(popup_reply_data,/account/);
4473                         }
4474                 }else if(label_data_str != label_str && current_label_data_str == label_str){
4475                         set_return_basic(popup_reply_data,/\S/);
4476                 }else if(label_data_str == label_str){
4477                         set_return_basic(popup_reply_data,/account/);
4478                 }
4479         }else{
4480                 set_return_basic(popup_reply_data,/\S/);
4481         }
4482 }
4483
4484 function set_return_lead_conv(popup_reply_data) {
4485     set_return(popup_reply_data);
4486     if (document.getElementById('lead_conv_ac_op_sel') && typeof onBlurKeyUpHandler=='function') {
4487         onBlurKeyUpHandler();
4488     }
4489 }
4490
4491 function set_return_and_save(popup_reply_data)
4492 {
4493         var form_name = popup_reply_data.form_name;
4494         var name_to_value_array = popup_reply_data.name_to_value_array;
4495
4496         for (var the_key in name_to_value_array)
4497         {
4498                 if(the_key == 'toJSON')
4499                 {
4500                         /* just ignore */
4501                 }
4502                 else
4503                 {
4504                         window.document.forms[form_name].elements[the_key].value = name_to_value_array[the_key];
4505                 }
4506         }
4507
4508         window.document.forms[form_name].return_module.value = window.document.forms[form_name].module.value;
4509         window.document.forms[form_name].return_action.value = 'DetailView';
4510         window.document.forms[form_name].return_id.value = window.document.forms[form_name].record.value;
4511         window.document.forms[form_name].action.value = 'Save';
4512         window.document.forms[form_name].submit();
4513 }
4514
4515 /**
4516  * This is a helper function to construct the initial filter that can be
4517  * passed into the open_popup() function.  It assumes that there is an
4518  * account_id and account_name field in the given form_name to use to
4519  * construct the intial filter string.
4520  */
4521 function get_initial_filter_by_account(form_name)
4522 {
4523         var account_id = window.document.forms[form_name].account_id.value;
4524         var account_name = escape(window.document.forms[form_name].account_name.value);
4525         var initial_filter = "&account_id=" + account_id + "&account_name=" + account_name;
4526
4527         return initial_filter;
4528 }
4529 // end code from popup_parent_helper.js
4530
4531 // begin code for address copy
4532 /**
4533  * This is a function used by the Address widget that will fill
4534  * in the given array fields using the fromKey and toKey as a
4535  * prefix into the form objects HTML elements.
4536  *
4537  * @param form The HTML form object to parse
4538  * @param fromKey The prefix of elements to copy from
4539  * @param toKey The prefix of elements to copy into
4540  * @return boolean true if successful, false otherwise
4541  */
4542 function copyAddress(form, fromKey, toKey) {
4543
4544     var elems = new Array("address_street", "address_city", "address_state", "address_postalcode", "address_country");
4545     var checkbox = document.getElementById(toKey + "_checkbox");
4546
4547     if(typeof checkbox != "undefined") {
4548         if(!checkbox.checked) {
4549                     for(x in elems) {
4550                         t = toKey + "_" + elems[x];
4551                             document.getElementById(t).removeAttribute('readonly');
4552                     }
4553         } else {
4554                     for(x in elems) {
4555                             f = fromKey + "_" + elems[x];
4556                             t = toKey + "_" + elems[x];
4557
4558                             document.getElementById(t).value = document.getElementById(f).value;
4559                             document.getElementById(t).setAttribute('readonly', true);
4560                     }
4561             }
4562     }
4563         return true;
4564 }
4565 // end code for address copy
4566
4567 /**
4568  * This function is used in Email Template Module.
4569  * It will check whether the template is used in Campaing->EmailMarketing.
4570  * If true, it will notify user.
4571  */
4572
4573 function check_deletable_EmailTemplate() {
4574         id = document.getElementsByName('record')[0].value;
4575         currentForm = document.getElementById('form');
4576         var call_back = {
4577                 success:function(r) {
4578                         if(r.responseText == 'true') {
4579                                 if(!confirm(SUGAR.language.get('app_strings','NTC_TEMPLATE_IS_USED'))) {
4580                                         return false;
4581                                 }
4582                         } else {
4583                                 if(!confirm(SUGAR.language.get('app_strings','NTC_DELETE_CONFIRMATION'))) {
4584                                         return false;
4585                                 }
4586                         }
4587                         currentForm.return_module.value='EmailTemplates';
4588                         currentForm.return_action.value='ListView';
4589                         currentForm.action.value='Delete';
4590                         currentForm.submit();
4591                 }
4592                 };
4593         url = "index.php?module=EmailTemplates&action=CheckDeletable&from=DetailView&to_pdf=1&record="+id;
4594         YAHOO.util.Connect.asyncRequest('POST',url, call_back,null);
4595 }
4596
4597 SUGAR.image = {
4598      remove_upload_imagefile : function(field_name) {
4599             var field=document.getElementById('remove_imagefile_' + field_name);
4600             field.value=1;
4601
4602             //enable the file upload button.
4603             var field=document.getElementById( field_name);
4604             field.style.display="";
4605
4606             //hide the image and remove button.
4607             var field=document.getElementById('img_' + field_name);
4608             field.style.display="none";
4609             var field=document.getElementById('bt_remove_' + field_name);
4610             field.style.display="none";
4611
4612             if(document.getElementById(field_name + '_duplicate')) {
4613                var field = document.getElementById(field_name + '_duplicate');
4614                field.value = "";
4615             }
4616     },
4617
4618     confirm_imagefile : function(field_name) {
4619             var field=document.getElementById(field_name);
4620             var filename=field.value;
4621             var fileExtension = filename.substring(filename.lastIndexOf(".")+1);
4622             fileExtension = fileExtension.toLowerCase();
4623             if (fileExtension == "jpg" || fileExtension == "jpeg"
4624                 || fileExtension == "gif" || fileExtension == "png" || fileExtension == "bmp"){
4625                     //image file
4626                 }
4627             else{
4628                 field.value=null;
4629                 alert(SUGAR.language.get('app_strings', 'LBL_UPLOAD_IMAGE_FILE_INVALID'));
4630             }
4631     },
4632
4633     lightbox : function(image)
4634         {
4635         if (typeof(SUGAR.image.lighboxWindow) == "undefined")
4636                         SUGAR.image.lighboxWindow = new YAHOO.widget.SimpleDialog('sugarImageViewer', {
4637                     type:'message',
4638                     modal:true,
4639                     id:'sugarMsgWindow',
4640                     close:true,
4641                     title:"Alert",
4642                     msg: "<img src='" + image + "'> </img>",
4643                     buttons: [ ]
4644                 });
4645                 SUGAR.image.lighboxWindow.setBody("<img src='" + image + "'> </img>");
4646                 SUGAR.image.lighboxWindow.render(document.body);
4647         SUGAR.image.lighboxWindow.show();
4648                 SUGAR.image.lighboxWindow.center()
4649     }
4650 }
4651
4652 SUGAR.append(SUGAR.util, {
4653     isTouchScreen: function() {
4654         // first check if we have forced use of the touch enhanced interface
4655         if (Get_Cookie("touchscreen") == '1') {
4656             return true;
4657         }
4658
4659         // next check if we should use the touch interface with our device
4660         if ((navigator.userAgent.match(/iPad/i) != null)) {
4661             return true;
4662         }
4663
4664         return false;
4665     },
4666
4667     isLoginPage: function(content) {
4668         //skip if this is packageManager screen
4669         if(SUGAR.util.isPackageManager()) {return false;}
4670         var loginPageStart = "<!DOCTYPE";
4671         if (content.substr(0, loginPageStart.length) == loginPageStart && content.indexOf("<html>") != -1  && content.indexOf("login_module") != -1) {
4672                 window.location.href = window.location.protocol + window.location.pathname;
4673                 return true;
4674         }
4675     },
4676
4677 isPackageManager: function(){
4678         if(typeof(document.the_form) !='undefined' && typeof(document.the_form.language_pack_escaped) !='undefined'){
4679                 return true;
4680         }else{return false;}
4681 },
4682
4683 ajaxCallInProgress: function(){
4684     var t = true;
4685     //First check if we are in a popup.
4686     if (typeof (send_back) != "function"){
4687         //If the page content is blank, it means we are probably still waiting on something
4688         var c = document.getElementById("content");
4689         if (!c) return true;
4690         t = YAHOO.lang.trim(SUGAR.util.innerText(c));
4691     }
4692     return SUGAR_callsInProgress != 0 || t == "";
4693 },
4694 //Firefox doesn't support innerText (textContent includes script content)
4695 innerText : function(el) {
4696     if (el.tagName == "SCRIPT")
4697         return "";
4698     if(typeof(el.innerText) == "string")
4699         return el.innerText;
4700     var t = "";
4701     for (var i in el.childNodes){
4702         var c = el.childNodes[i];
4703         if (typeof(c) != "object")
4704             continue;
4705         if (typeof(c.nodeName) == "string" && c.nodeName == "#text")
4706             t += c.nodeValue;
4707         else
4708             t += SUGAR.util.innerText(c);
4709     }
4710     return t;
4711 },
4712
4713 callOnChangeListers: function(field){
4714         var listeners = YAHOO.util.Event.getListeners(field, 'change');
4715         if (listeners != null) {
4716                 for (var i = 0; i < listeners.length; i++) {
4717                         var l = listeners[i];
4718                         l.fn.call(l.scope ? l.scope : this, l.obj);
4719                 }
4720         }
4721 },
4722
4723 closeActivityPanel: {
4724     show:function(module,id,new_status,viewType,parentContainerId){
4725         if (SUGAR.util.closeActivityPanel.panel)
4726                         SUGAR.util.closeActivityPanel.panel.destroy();
4727             var singleModule = SUGAR.language.get("app_list_strings", "moduleListSingular")[module];
4728             singleModule = typeof(singleModule != 'undefined') ? singleModule.toLowerCase() : '';
4729             var closeText =  SUGAR.language.get("app_strings", "LBL_CLOSE_ACTIVITY_CONFIRM").replace("#module#",singleModule);
4730         SUGAR.util.closeActivityPanel.panel =
4731             new YAHOO.widget.SimpleDialog("closeActivityDialog",
4732                      { width: "300px",
4733                        fixedcenter: true,
4734                        visible: false,
4735                        draggable: false,
4736                        close: true,
4737                        text: closeText,
4738                        constraintoviewport: true,
4739                        buttons: [ { text:SUGAR.language.get("app_strings", "LBL_EMAIL_OK"), handler:function(){
4740                            if (SUGAR.util.closeActivityPanel.panel)
4741                             SUGAR.util.closeActivityPanel.panel.hide();
4742
4743                         ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_SAVING'));
4744                         var args = "action=save&id=" + id + "&record=" + id + "&status=" + new_status + "&module=" + module;
4745                         // 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
4746                         // TODO: Take id out and regression test. Left id in for now to not create any other unexpected problems
4747                         //var args = "action=save&id=" + id + "&status=" + new_status + "&module=" + module;
4748                         var callback = {
4749                             success:function(o)
4750                             {
4751                                 // Bug 51984: We need to submit the form just incase we have a form already submitted
4752                                 // so we dont get a popup stating that the form needs to be resubmitted like it doesn,
4753                                 // when you do a reload/refresh
4754                                 window.setTimeout(function(){if(document.getElementById('search_form')) document.getElementById('search_form').submit(); else window.location.reload(true);}, 0);
4755                             },
4756                             argument:{'parentContainerId':parentContainerId}
4757                         };
4758
4759                         YAHOO.util.Connect.asyncRequest('POST', 'index.php', callback, args);
4760
4761                        }, isDefault:true },
4762                                   { text:SUGAR.language.get("app_strings", "LBL_EMAIL_CANCEL"),  handler:function(){SUGAR.util.closeActivityPanel.panel.hide(); }} ]
4763                      } );
4764
4765             SUGAR.util.closeActivityPanel.panel.setHeader(SUGAR.language.get("app_strings", "LBL_CLOSE_ACTIVITY_HEADER"));
4766         SUGAR.util.closeActivityPanel.panel.render(document.body);
4767         SUGAR.util.closeActivityPanel.panel.show();
4768     }
4769 },
4770
4771 setEmailPasswordDisplay: function(id, exists, formName) {
4772         link = document.getElementById(id+'_link');
4773         pwd = document.getElementById(id);
4774         if(!pwd || !link) return;
4775         if(exists) {
4776         pwd.style.display = 'none';
4777         link.style.display = '';
4778         if(typeof(formName) != 'undefined')
4779             removeFromValidate(formName, id);
4780         } else {
4781         pwd.style.display = '';
4782         link.style.display = 'none';
4783         }
4784 },
4785
4786 setEmailPasswordEdit: function(id) {
4787         link = document.getElementById(id+'_link');
4788         pwd = document.getElementById(id);
4789         if(!pwd || !link) return;
4790         pwd.style.display = '';
4791         link.style.display = 'none';
4792 },
4793
4794     /**
4795      * Compares a filename with a supplied array of allowed file extensions.
4796      * @param fileName string
4797      * @param allowedTypes array of allowed file extensions
4798      * @return bool
4799      */
4800     validateFileExt: function(fileName, allowedTypes) {
4801         var ext = fileName.split('.').pop().toLowerCase();
4802
4803         for (var i = allowedTypes.length; i >= 0; i--) {
4804             if (ext === allowedTypes[i]) {
4805                 return true;
4806             }
4807         }
4808
4809         return false;
4810     },
4811
4812     arrayIndexOf: function(arr, val, start) {
4813         if (typeof arr.indexOf == "function")
4814             return arr.indexOf(val, start);
4815         for (var i = (start || 0), j = arr.length; i < j; i++) {
4816             if (arr[i] === val) {
4817                 return i;
4818             }
4819         }
4820         return -1;
4821     }
4822 });
4823
4824 SUGAR.clearRelateField = function(form, name, id)
4825 {
4826     if (typeof form[name] == "object"){
4827         form[name].value = '';
4828         SUGAR.util.callOnChangeListers(form[name]);
4829     }
4830
4831     if (typeof form[id] == "object"){
4832         form[id].value = '';
4833         SUGAR.util.callOnChangeListers(form[id]);
4834     }
4835 };
4836 if(typeof(SUGAR.AutoComplete) == 'undefined') SUGAR.AutoComplete = {};
4837
4838 SUGAR.AutoComplete.getOptionsArray = function(options_index){
4839     var return_arr = [];
4840
4841     var opts = SUGAR.language.get('app_list_strings', options_index);
4842     if(typeof(opts) != 'undefined'){
4843         for(key in opts){
4844             // Since we are using auto complete, we excluse blank dropdown entries since they can just leave it blank
4845             if(key != '' && opts[key] != ''){
4846                 var item = [];
4847                 item['key'] = key;
4848                 item['text'] = opts[key];
4849                 return_arr.push(item);
4850             }
4851         }
4852     }
4853     return return_arr;
4854 }
4855
4856 if(typeof(SUGAR.MultiEnumAutoComplete) == 'undefined') SUGAR.MultiEnumAutoComplete = {};
4857
4858 SUGAR.MultiEnumAutoComplete.getMultiSelectKeysFromValues = function(options_index, val_string){
4859     var opts = SUGAR.language.get('app_list_strings', options_index);
4860     var selected_values = val_string.split(", ");
4861     // YUI AutoComplete adds a blank. We remove it automatically here
4862     if(selected_values.length > 0 && selected_values.indexOf('') == selected_values.length - 1){
4863         selected_values.pop();
4864     }
4865     var final_arr = new Array();
4866     for(idx in selected_values){
4867         for(o_idx in opts){
4868             if(selected_values[idx] == opts[o_idx]){
4869                 final_arr.push(o_idx);
4870             }
4871         }
4872     }
4873     return final_arr;
4874 }
4875
4876 SUGAR.MultiEnumAutoComplete.getMultiSelectValuesFromKeys = function(options_index, val_string){
4877     var opts = SUGAR.language.get('app_list_strings', options_index);
4878     val_string=val_string.replace(/^\^/,'').replace(/\^$/,'') //fixes bug where string starts or ends with ^
4879     var selected_values = val_string.split("^,^");
4880
4881     // YUI AutoComplete adds a blank. We remove it automatically here
4882     if(selected_values.length > 0 && selected_values.indexOf('') == selected_values.length - 1){
4883         selected_values.pop();
4884     }
4885
4886     var final_arr = new Array();
4887     for(idx in selected_values){
4888         for(o_idx in opts){
4889             if(selected_values[idx] == o_idx){
4890                 final_arr.push(opts[o_idx]);
4891             }
4892         }
4893     }
4894     return final_arr;
4895 }