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