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