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