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