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