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