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