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