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