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