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