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