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