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