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