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