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