1 /*********************************************************************************
2 * SugarCRM Community Edition is a customer relationship management program developed by
3 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
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.
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
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
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.
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.
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 ********************************************************************************/
40 * Namespace for Sugar Objects
42 if ( typeof(SUGAR) == "undefined" ) SUGAR = {};
43 if ( typeof(SUGAR.themes) == "undefined" ) SUGAR.themes = {};
47 * Namespace for Homepage
51 * Namespace for Subpanel Utils
53 SUGAR.subpanelUtils= {};
57 SUGAR.ajaxStatusClass= {};
63 * General namespace for Sugar utils
71 SUGAR.unifiedSearchAdvanced= {};
76 SUGAR.contextMenu= {};
82 var requiredIndex = 2;
88 var compareToIndex = 7;
90 var operatorIndex = 13;
92 var validate = new Array();
94 var requiredTxt = 'Missing Required Field:'
95 var invalidTxt = 'Invalid Value:'
96 var secondsSinceLoad = 0;
97 var inputsWithErrors = new Array();
98 var tabsWithErrors = new Array();
99 var lastSubmitTime = 0;
100 var alertList = new Array();
101 var oldStartsWith = '';
106 * As of Sugar version 6.2.3 (MSIE Version 9) this function is deprecated. The preferred method is to use the
107 * user agent check supplied by YUI to check for IE:
109 * for checking if a browser is IE in general : if(YAHOO.env.ua.ie) {...}
111 * or for checking specific versions: if (YAHOO.env.ua.ie >= 5.5 && YAHOO.env.ua.ie < 9) {...}
114 function isSupportedIE() {
115 var userAgent = navigator.userAgent.toLowerCase() ;
117 // IE Check supports ActiveX controls
118 if (userAgent.indexOf("msie") != -1 && userAgent.indexOf("mac") == -1 && userAgent.indexOf("opera") == -1) {
119 var version = navigator.appVersion.match(/MSIE (.\..)/)[1] ;
121 if(version >= 5.5 && version < 9) {
129 SUGAR.isIE = isSupportedIE();
130 SUGAR.isIE7 = (navigator.userAgent.toLowerCase().indexOf('msie 7')!=-1);
131 var isSafari = (navigator.userAgent.toLowerCase().indexOf('safari')!=-1);
133 // escapes regular expression characters
134 RegExp.escape = function(text) { // http://simon.incutio.com/archive/2006/01/20/escape
135 if (!arguments.callee.sRE) {
136 var specials = ['/', '.', '*', '+', '?', '|','(', ')', '[', ']', '{', '}', '\\'];
137 arguments.callee.sRE = new RegExp('(\\' + specials.join('|\\') + ')', 'g');
139 return text.replace(arguments.callee.sRE, '\\$1');
142 function addAlert(type, name,subtitle, description,time, redirect) {
143 var addIndex = alertList.length;
144 alertList[addIndex]= new Array();
145 alertList[addIndex]['name'] = name;
146 alertList[addIndex]['type'] = type;
147 alertList[addIndex]['subtitle'] = subtitle;
148 alertList[addIndex]['description'] = description.replace(/<br>/gi, "\n").replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');
149 alertList[addIndex]['time'] = time;
150 alertList[addIndex]['done'] = 0;
151 alertList[addIndex]['redirect'] = redirect;
153 function checkAlerts() {
154 secondsSinceLoad += 1;
157 for(mj = 0 ; mj < alertList.length; mj++) {
158 if(alertList[mj]['done'] == 0) {
159 if(alertList[mj]['time'] < secondsSinceLoad && alertList[mj]['time'] > -1 ) {
160 alertmsg = alertList[mj]['type'] + ":" + alertList[mj]['name'] + "\n" +alertList[mj]['subtitle']+ "\n"+ alertList[mj]['description'] + "\n\n";
161 alertList[mj]['done'] = 1;
162 if(alertList[mj]['redirect'] == '') {
165 else if(confirm(alertmsg)) {
166 window.location = alertList[mj]['redirect'];
172 setTimeout("checkAlerts()", 1000);
175 function toggleDisplay(id) {
176 if(this.document.getElementById(id).style.display == 'none') {
177 this.document.getElementById(id).style.display = '';
178 if(this.document.getElementById(id+"link") != undefined) {
179 this.document.getElementById(id+"link").style.display = 'none';
181 if(this.document.getElementById(id+"_anchor") != undefined)
182 this.document.getElementById(id+"_anchor").innerHTML='[ - ]';
185 this.document.getElementById(id).style.display = 'none'
186 if(this.document.getElementById(id+"link") != undefined) {
187 this.document.getElementById(id+"link").style.display = '';
189 if(this.document.getElementById(id+"_anchor") != undefined)
190 this.document.getElementById(id+"_anchor").innerHTML='[+]';
194 function checkAll(form, field, value) {
195 for (i = 0; i < form.elements.length; i++) {
196 if(form.elements[i].name == field)
197 form.elements[i].checked = value;
201 function replaceAll(text, src, rep) {
202 offset = text.toLowerCase().indexOf(src.toLowerCase());
203 while(offset != -1) {
204 text = text.substring(0, offset) + rep + text.substring(offset + src.length ,text.length);
205 offset = text.indexOf( src, offset + rep.length + 1);
210 function addForm(formname) {
211 validate[formname] = new Array();
214 function addToValidate(formname, name, type, required, msg) {
215 if(typeof validate[formname] == 'undefined') {
218 validate[formname][validate[formname].length] = new Array(name, type,required, msg);
221 function addToValidateRange(formname, name, type,required, msg,min,max) {
222 addToValidate(formname, name, type,required, msg);
223 validate[formname][validate[formname].length - 1][jstypeIndex] = 'range'
224 validate[formname][validate[formname].length - 1][minIndex] = min;
225 validate[formname][validate[formname].length - 1][maxIndex] = max;
228 function addToValidateIsValidDate(formname, name, type, required, msg) {
229 addToValidate(formname, name, type, required, msg);
230 validate[formname][validate[formname].length - 1][jstypeIndex] = 'date'
233 function addToValidateIsValidTime(formname, name, type, required, msg) {
234 addToValidate(formname, name, type, required, msg);
235 validate[formname][validate[formname].length - 1][jstypeIndex] = 'time'
238 function addToValidateDateBefore(formname, name, type, required, msg, compareTo) {
239 addToValidate(formname, name, type,required, msg);
240 validate[formname][validate[formname].length - 1][jstypeIndex] = 'isbefore'
241 validate[formname][validate[formname].length - 1][compareToIndex] = compareTo;
244 function addToValidateDateBeforeAllowBlank(formname, name, type, required, msg, compareTo, allowBlank) {
245 addToValidate(formname, name, type,required, msg);
246 validate[formname][validate[formname].length - 1][jstypeIndex] = 'isbefore'
247 validate[formname][validate[formname].length - 1][compareToIndex] = compareTo;
248 validate[formname][validate[formname].length - 1][allowblank] = allowBlank;
251 function addToValidateBinaryDependency(formname, name, type, required, msg, compareTo) {
252 addToValidate(formname, name, type, required, msg);
253 validate[formname][validate[formname].length - 1][jstypeIndex] = 'binarydep';
254 validate[formname][validate[formname].length - 1][compareToIndex] = compareTo;
257 function addToValidateComparison(formname, name, type, required, msg, compareTo) {
258 addToValidate(formname, name, type, required, msg);
259 validate[formname][validate[formname].length - 1][jstypeIndex] = 'comparison';
260 validate[formname][validate[formname].length - 1][compareToIndex] = compareTo;
263 function addToValidateIsInArray(formname, name, type, required, msg, arr, operator) {
264 addToValidate(formname, name, type, required, msg);
265 validate[formname][validate[formname].length - 1][jstypeIndex] = 'in_array';
266 validate[formname][validate[formname].length - 1][arrIndex] = arr;
267 validate[formname][validate[formname].length - 1][operatorIndex] = operator;
270 function addToValidateVerified(formname, name, type, required, msg, arr, operator) {
271 addToValidate(formname, name, type, required, msg);
272 validate[formname][validate[formname].length - 1][jstypeIndex] = 'verified';
275 function addToValidateLessThan(formname, name, type, required, msg, max, max_field_msg) {
276 addToValidate(formname, name, type, required, msg);
277 validate[formname][validate[formname].length - 1][jstypeIndex] = 'less';
278 validate[formname][validate[formname].length - 1][maxIndex] = max;
279 validate[formname][validate[formname].length - 1][altMsgIndex] = max_field_msg;
282 function addToValidateMoreThan(formname, name, type, required, msg, min) {
283 addToValidate(formname, name, type, required, msg);
284 validate[formname][validate[formname].length - 1][jstypeIndex] = 'more';
285 validate[formname][validate[formname].length - 1][minIndex] = min;
289 function removeFromValidate(formname, name) {
290 for(i = 0; i < validate[formname].length; i++)
292 if(validate[formname][i][nameIndex] == name)
294 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
298 function checkValidate(formname, name) {
299 if(validate[formname]){
300 for(i = 0; i < validate[formname].length; i++){
301 if(validate[formname][i][nameIndex] == name){
308 var formsWithFieldLogic=null;
309 var formWithPrecision =null;
310 function addToValidateFieldLogic(formId,minFieldId, maxFieldId, defaultFieldId, lenFieldId,type,msg){
311 this.formId = document.getElementById(formId);
312 this.min=document.getElementById(minFieldId);
313 this.max= document.getElementById(maxFieldId);
314 this._default= document.getElementById(defaultFieldId);
315 this.len = document.getElementById(lenFieldId);
319 //@params: formid- Dom id of the form containing the precision and float fields
320 // valudId- Dom id of the field containing a float whose precision is to be checked.
321 // precisionId- Dom id of the field containing precision value.
322 function addToValidatePrecision(formId, valueId, precisionId){
323 this.form = document.getElementById(formId);
324 this.float = document.getElementById(valueId);
325 this.precision = document.getElementById(precisionId);
328 //function checkLength(value, referenceValue){
332 function isValidPrecision(value, precision){
333 value = trim(value.toString());
339 if( (precision == "0") ){
340 if (value.indexOf(dec_sep)== -1){
347 if(value.charAt(value.length-precision-1) == num_grp_sep){
348 if(value.substr(value.indexOf(dec_sep), 1)==dec_sep){
353 var actualPrecision = value.substr(value.indexOf(dec_sep)+1, value.length).length;
354 return actualPrecision == precision;
356 function toDecimal(original, precision) {
357 precision = (precision == null) ? 2 : precision;
358 num = Math.pow(10, precision);
359 temp = Math.round(original*num)/num;
360 if((temp * 100) % 100 == 0)
362 if((temp * 10) % 10 == 0)
367 function isInteger(s) {
368 if(typeof num_grp_sep != 'undefined' && typeof dec_sep != 'undefined')
370 s = unformatNumberNoParse(s, num_grp_sep, dec_sep).toString();
372 return /^[+-]?[0-9]*$/.test(s) ;
375 function isDecimal(s) {
376 if (typeof s == "string" && s == "") // bug# 46530, this is required in order to
377 return true; // not check empty decimal fields
378 if(typeof num_grp_sep != 'undefined' && typeof dec_sep != 'undefined')
380 s = unformatNumberNoParse(s, num_grp_sep, dec_sep).toString();
382 return /^[+-]?[0-9]+\.?[0-9]*$/.test(s) ;
385 function isNumeric(s) {
389 var date_reg_positions = {'Y': 1,'m': 2,'d': 3};
390 var date_reg_format = '([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})'
391 function isDate(dtStr) {
393 if(dtStr.length== 0) {
397 // Check that we have numbers
398 myregexp = new RegExp(date_reg_format)
399 if(!myregexp.test(dtStr))
406 var dateParts = dtStr.match(date_reg_format);
407 for(key in date_reg_positions) {
408 index = date_reg_positions[key];
410 m = dateParts[index];
411 } else if(key == 'd') {
412 d = dateParts[index];
414 y = dateParts[index];
418 // Check that date is real
419 var dd = new Date(y,m,0);
420 // reject negative years
423 // reject month less than 1 and greater than 12
426 // reject days less than 1 or days not in month (e.g. February 30th)
427 if (d < 1 || d > dd.getDate())
432 function getDateObject(dtStr) {
433 if(dtStr.length== 0) {
437 myregexp = new RegExp(date_reg_format)
439 if(myregexp.exec(dtStr)) var dt = myregexp.exec(dtStr)
442 var yr = dt[date_reg_positions['Y']];
443 var mh = dt[date_reg_positions['m']];
444 var dy = dt[date_reg_positions['d']];
445 var dtar = dtStr.split(' ');
446 if(typeof(dtar[1])!='undefined' && isTime(dtar[1])) {//if it is a timedate, we should make date1 to have time value
447 var t1 = dtar[1].replace(/am/i,' AM');
448 var t1 = t1.replace(/pm/i,' PM');
449 //bug #37977: where time format 23.00 causes java script error
450 t1=t1.replace(/\./, ':');
451 date1 = new Date(Date.parse(mh+'/'+dy+ '/'+yr+' '+t1));
455 var date1 = new Date();
456 date1.setFullYear(yr); // xxxx 4 char year
457 date1.setMonth(mh-1); // 0-11 Bug 4048: javascript Date obj months are 0-index
458 date1.setDate(dy); // 1-31
463 function isBefore(value1, value2) {
464 var d1 = getDateObject(value1);
465 var d2 = getDateObject(value2);
466 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.
472 function isValidEmail(emailStr) {
474 if(emailStr.length== 0) {
477 // cn: bug 7128, a period at the end of the string mangles checks. (switched to accept spaces and delimiters)
478 var lastChar = emailStr.charAt(emailStr.length - 1);
479 if(!lastChar.match(/[^\.]/i)) {
482 //bug 40068, According to rules in page 6 of http://www.apps.ietf.org/rfc/rfc3696.html#sec-3,
483 //first character of local part of an email address
484 //should not be a period i.e. '.'
486 var firstLocalChar=emailStr.charAt(0);
487 if(firstLocalChar.match(/\./)){
491 //bug 40068, According to rules in page 6 of http://www.apps.ietf.org/rfc/rfc3696.html#sec-3,
492 //last character of local part of an email address
493 //should not be a period i.e. '.'
495 var pos=emailStr.lastIndexOf("@");
496 var localPart = emailStr.substr(0, pos);
497 var lastLocalChar=localPart.charAt(localPart.length - 1);
498 if(lastLocalChar.match(/\./)){
505 while ((results = reg.exec(emailStr)) != null) {
506 var original = results[0];
507 parsedResult = results[0].replace(';', '::;::');
508 emailStr = emailStr.replace (original, parsedResult);
512 while ((results = reg.exec(emailStr)) != null) {
513 var original = results[0];
514 //Check if we were using ; as a delimiter. If so, skip the commas
515 if(original.indexOf("::;::") == -1) {
516 var parsedResult = results[0].replace(',', '::;::');
517 emailStr = emailStr.replace (original, parsedResult);
521 // mfh: bug 15010 - more practical implementation of RFC 2822 from http://www.regular-expressions.info/email.html, modifed to accept CAPITAL LETTERS
522 //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))
525 //bug 40068, According to rules in page 6 of http://www.apps.ietf.org/rfc/rfc3696.html#sec-3,
526 //allowed special characters ! # $ % & ' * + - / = ? ^ _ ` . { | } ~ in local part
527 var emailArr = emailStr.split(/::;::/);
528 for (var i = 0; i < emailArr.length; i++) {
529 var emailAddress = emailArr[i];
530 if (trim(emailAddress) != '') {
531 if(!/^\s*[\w.%+\-&'#!\$\*=\?\^_`\{\}~\/]+@([A-Z0-9-]+\.)*[A-Z0-9-]+\.[\w-]{2,}\s*$/i.test(emailAddress) &&
532 !/^.*<[A-Z0-9._%+\-&'#!\$\*=\?\^_`\{\}~]+?@([A-Z0-9-]+\.)*[A-Z0-9-]+\.[\w-]{2,}>\s*$/i.test(emailAddress)) {
541 function isValidPhone(phoneStr) {
542 if(phoneStr.length== 0) {
545 if(!/^[0-9\-\(\)\s]+$/.test(phoneStr))
549 function isFloat(floatStr) {
550 if(floatStr.length== 0) {
553 if(!(typeof(num_grp_sep)=='undefined' || typeof(dec_sep)=='undefined')) {
554 floatStr = unformatNumberNoParse(floatStr, num_grp_sep, dec_sep).toString();
557 return /^(-)?[0-9\.]+$/.test(floatStr);
559 function isDBName(str) {
564 // must start with a letter
565 if(!/^[a-zA-Z][a-zA-Z\_0-9]*$/.test(str))
569 var time_reg_format = "[0-9]{1,2}\:[0-9]{2}";
570 function isTime(timeStr) {
571 var time_reg_format = "[0-9]{1,2}\:[0-9]{2}";
572 time_reg_format = time_reg_format.replace('([ap]m)', '');
573 time_reg_format = time_reg_format.replace('([AP]M)', '');
574 if(timeStr.length== 0){
577 //we now support multiple time formats
578 myregexp = new RegExp(time_reg_format)
579 if(!myregexp.test(timeStr))
585 function inRange(value, min, max) {
586 if (typeof num_grp_sep != 'undefined' && typeof dec_sep != 'undefined')
587 value = unformatNumberNoParse(value, num_grp_sep, dec_sep).toString();
588 return value >= min && value <= max;
591 function bothExist(item1, item2) {
592 if(typeof item1 == 'undefined') { return false; }
593 if(typeof item2 == 'undefined') { return false; }
594 if((item1 == '' && item2 != '') || (item1 != '' && item2 == '') ) { return false; }
598 trim = YAHOO.lang.trim;
601 function check_form(formname) {
602 if (typeof(siw) != 'undefined' && siw
603 && typeof(siw.selectingSomething) != 'undefined' && siw.selectingSomething)
605 return validate_form(formname, '');
608 function add_error_style(formname, input, txt, flash) {
609 if (typeof flash == "undefined")
612 inputHandle = typeof input == "object" ? input : document.forms[formname][input];
613 style = get_current_bgcolor(inputHandle);
615 // strip off the colon at the end of the warning strings
616 if ( txt.substring(txt.length-1) == ':' )
617 txt = txt.substring(0,txt.length-1)
619 // Bug 28249 - To help avoid duplicate messages for an element, strip off extra messages and
620 // match on the field name itself
621 requiredTxt = SUGAR.language.get('app_strings', 'ERR_MISSING_REQUIRED_FIELDS');
622 invalidTxt = SUGAR.language.get('app_strings', 'ERR_INVALID_VALUE');
623 nomatchTxt = SUGAR.language.get('app_strings', 'ERR_SQS_NO_MATCH_FIELD');
624 matchTxt = txt.replace(requiredTxt,'').replace(invalidTxt,'').replace(nomatchTxt,'');
626 if(inputHandle.parentNode.innerHTML.search(matchTxt) == -1) {
627 errorTextNode = document.createElement('div');
628 errorTextNode.className = 'required';
629 errorTextNode.innerHTML = txt;
630 if ( inputHandle.parentNode.className.indexOf('x-form-field-wrap') != -1 ) {
631 inputHandle.parentNode.parentNode.appendChild(errorTextNode);
634 inputHandle.parentNode.appendChild(errorTextNode);
637 inputHandle.style.backgroundColor = "#FF0000";
638 inputsWithErrors.push(inputHandle);
642 // We only need to setup the flashy-flashy on the first entry, it loops through all fields automatically
643 if ( inputsWithErrors.length == 1 ) {
644 for(wp = 1; wp <= 10; wp++) {
645 window.setTimeout('fade_error_style(style, '+wp*10+')',1000+(wp*50));
648 if(typeof (window[formname + "_tabs"]) != "undefined") {
649 var tabView = window[formname + "_tabs"];
650 var parentDiv = YAHOO.util.Dom.getAncestorByTagName(inputHandle, "div");
652 var tabs = tabView.get("tabs");
653 for (var i in tabs) {
654 if (tabs[i].get("contentEl") == parentDiv
655 || YAHOO.util.Dom.isAncestor(tabs[i].get("contentEl"), inputHandle))
657 tabs[i].get("labelEl").style.color = "red";
658 if ( inputsWithErrors.length == 1 )
659 tabView.selectTab(i);
664 window.setTimeout("inputsWithErrors[" + (inputsWithErrors.length - 1) + "].style.backgroundColor = '';", 2000);
668 // Catch errors here so we don't allow an incomplete record through the javascript validation
673 * removes all error messages for the current form
675 function clear_all_errors() {
676 for(var wp = 0; wp < inputsWithErrors.length; wp++) {
677 if(typeof(inputsWithErrors[wp]) !='undefined' && typeof inputsWithErrors[wp].parentNode != 'undefined' && inputsWithErrors[wp].parentNode != null) {
678 if ( inputsWithErrors[wp].parentNode.className.indexOf('x-form-field-wrap') != -1 )
680 inputsWithErrors[wp].parentNode.parentNode.removeChild(inputsWithErrors[wp].parentNode.parentNode.lastChild);
684 inputsWithErrors[wp].parentNode.removeChild(inputsWithErrors[wp].parentNode.lastChild);
688 if (inputsWithErrors.length == 0) return;
690 if ( YAHOO.util.Dom.getAncestorByTagName(inputsWithErrors[0], "form") ) {
691 var formname = YAHOO.util.Dom.getAncestorByTagName(inputsWithErrors[0], "form").getAttribute("name");
692 if(typeof (window[formname + "_tabs"]) != "undefined") {
693 var tabView = window[formname + "_tabs"];
695 var tabs = tabView.get("tabs");
696 for (var i in tabs) {
697 tabs[i].get("labelEl").style.color = "";
701 inputsWithErrors = new Array();
705 function get_current_bgcolor(input) {
706 if(input.currentStyle) {// ie
707 style = input.currentStyle.backgroundColor;
708 return style.substring(1,7);
712 styleRGB = document.defaultView.getComputedStyle(input, '').getPropertyValue("background-color");
713 comma = styleRGB.indexOf(',');
714 style += dec2hex(styleRGB.substring(4, comma));
715 commaPrevious = comma;
716 comma = styleRGB.indexOf(',', commaPrevious+1);
717 style += dec2hex(styleRGB.substring(commaPrevious+2, comma));
718 style += dec2hex(styleRGB.substring(comma+2, styleRGB.lastIndexOf(')')));
723 function hex2dec(hex){return(parseInt(hex,16));}
724 var hexDigit=new Array("0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F");
725 function dec2hex(dec){return(hexDigit[dec>>4]+hexDigit[dec&15]);}
727 function fade_error_style(normalStyle, percent) {
728 errorStyle = 'c60c30';
729 var r1 = hex2dec(errorStyle.slice(0,2));
730 var g1 = hex2dec(errorStyle.slice(2,4));
731 var b1 = hex2dec(errorStyle.slice(4,6));
733 var r2 = hex2dec(normalStyle.slice(0,2));
734 var g2 = hex2dec(normalStyle.slice(2,4));
735 var b2 = hex2dec(normalStyle.slice(4,6));
738 var pc = percent / 100;
740 r= Math.floor(r1+(pc*(r2-r1)) + .5);
741 g= Math.floor(g1+(pc*(g2-g1)) + .5);
742 b= Math.floor(b1+(pc*(b2-b1)) + .5);
744 for(var wp = 0; wp < inputsWithErrors.length; wp++) {
745 inputsWithErrors[wp].style.backgroundColor = "#" + dec2hex(r) + dec2hex(g) + dec2hex(b);
749 function isFieldTypeExceptFromEmptyCheck(fieldType)
752 var exemptList = ['bool','file'];
753 for(var i=0;i<exemptList.length;i++)
755 if(fieldType == exemptList[i])
760 function validate_form(formname, startsWith){
761 requiredTxt = SUGAR.language.get('app_strings', 'ERR_MISSING_REQUIRED_FIELDS');
762 invalidTxt = SUGAR.language.get('app_strings', 'ERR_INVALID_VALUE');
764 if ( typeof (formname) == 'undefined')
768 if ( typeof (validate[formname]) == 'undefined')
770 disableOnUnloadEditView(document.forms[formname]);
774 var form = document.forms[formname];
777 var _date = new Date();
778 if(_date.getTime() < (lastSubmitTime + 2000) && startsWith == oldStartsWith) { // ignore submits for the next 2 seconds
781 lastSubmitTime = _date.getTime();
782 oldStartsWith = startsWith;
784 clear_all_errors(); // remove previous error messages
786 inputsWithErrors = new Array();
787 for(var i = 0; i < validate[formname].length; i++){
788 if(validate[formname][i][nameIndex].indexOf(startsWith) == 0){
789 if(typeof form[validate[formname][i][nameIndex]] != 'undefined'){
792 //If a field is not required and it is blank or is binarydependant, skip validation.
793 //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
794 if(!validate[formname][i][requiredIndex] && trim(form[validate[formname][i][nameIndex]].value) == '' && (typeof(validate[formname][i][jstypeIndex]) != 'undefined' && validate[formname][i][jstypeIndex] != 'binarydep'))
799 if(validate[formname][i][requiredIndex]
800 && !isFieldTypeExceptFromEmptyCheck(validate[formname][i][typeIndex])
802 if(typeof form[validate[formname][i][nameIndex]] == 'undefined' || trim(form[validate[formname][i][nameIndex]].value) == ""){
803 add_error_style(formname, validate[formname][i][nameIndex], requiredTxt +' ' + validate[formname][i][msgIndex]);
808 switch(validate[formname][i][typeIndex]){
810 if(!isValidEmail(trim(form[validate[formname][i][nameIndex]].value))){
812 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
816 if( !isTime(trim(form[validate[formname][i][nameIndex]].value))){
818 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
820 case 'date': if(!isDate(trim(form[validate[formname][i][nameIndex]].value))){
822 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
827 if(!isDBName(trim(form[validate[formname][i][nameIndex]].value))){
829 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
835 if( validate[formname][i][requiredIndex] && typeof( form[validate[formname][i][nameIndex] + '_file'] ) != 'undefined' && trim( form[validate[formname][i][nameIndex] + '_file'].value) == "" && !form[validate[formname][i][nameIndex] + '_file'].disabled ) {
837 add_error_style(formname, validate[formname][i][nameIndex], requiredTxt + " " + validate[formname][i][msgIndex]);
841 if(!isInteger(trim(form[validate[formname][i][nameIndex]].value))){
843 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
847 if(!isDecimal(trim(form[validate[formname][i][nameIndex]].value))){
849 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
854 if(!isFloat(trim(form[validate[formname][i][nameIndex]].value))){
856 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
860 div_element_id = formname + '_' + form[validate[formname][i][nameIndex]].name + '_operation_div';
861 input_elements = YAHOO.util.Selector.query('input', document.getElementById(div_element_id));
862 primary_field_id = '';
863 validation_passed = false;
864 replace_selected = false;
866 //Loop through the option elements (replace or add currently)
867 for(t in input_elements) {
868 if(input_elements[t].type && input_elements[t].type == 'radio' && input_elements[t].checked == true && input_elements[t].value == 'replace') {
870 //Now find where the primary radio button is and if a value has been set
871 radio_elements = YAHOO.util.Selector.query('input[type=radio]', document.getElementById(formname + '_team_name_table'));
873 for(x in radio_elements) {
874 if(radio_elements[x].name != 'team_name_type') {
875 primary_field_id = 'team_name_collection_' + radio_elements[x].value;
876 if(radio_elements[x].checked) {
877 replace_selected = true;
878 if(trim(document.forms[formname].elements[primary_field_id].value) != '') {
879 validation_passed = true;
882 } else if(trim(document.forms[formname].elements[primary_field_id].value) != '') {
883 replace_selected = true;
890 if(replace_selected && !validation_passed) {
891 add_error_style(formname, primary_field_id, SUGAR.language.get('app_strings', 'ERR_NO_PRIMARY_TEAM_SPECIFIED'));
896 table_element_id = formname + '_' + form[validate[formname][i][nameIndex]].name + '_table';
897 if(document.getElementById(table_element_id)) {
898 input_elements = YAHOO.util.Selector.query('input[type=radio]', document.getElementById(table_element_id));
900 primary_field_id = form[validate[formname][i][nameIndex]].name + '_collection_0';
902 for(t in input_elements) {
903 primary_field_id = form[validate[formname][i][nameIndex]].name + '_collection_' + input_elements[t].value;
904 if(input_elements[t].type && input_elements[t].type == 'radio' && input_elements[t].checked == true) {
905 if(document.forms[formname].elements[primary_field_id].value != '') {
914 field_id = form[validate[formname][i][nameIndex]].name + '_collection_' + input_elements[0].value;
915 add_error_style(formname, field_id, SUGAR.language.get('app_strings', 'ERR_NO_PRIMARY_TEAM_SPECIFIED'));
921 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex]);
925 if(typeof validate[formname][i][jstypeIndex] != 'undefined'/* && !isError*/){
927 switch(validate[formname][i][jstypeIndex]){
929 if(!inRange(trim(form[validate[formname][i][nameIndex]].value), validate[formname][i][minIndex], validate[formname][i][maxIndex])){
931 var lbl_validate_range = SUGAR.language.get('app_strings', 'LBL_VALIDATE_RANGE');
932 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] + ") ");
936 compareTo = form[validate[formname][i][compareToIndex]];
937 if( typeof compareTo != 'undefined'){
938 if(trim(compareTo.value) != '' || (validate[formname][i][allowblank] != 'true') ) {
939 date2 = trim(compareTo.value);
940 date1 = trim(form[validate[formname][i][nameIndex]].value);
942 if(trim(date1).length != 0 && !isBefore(date1,date2)){
945 //jc:#12287 - adding translation for the is not before message
946 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex] + "(" + date1 + ") " + SUGAR.language.get('app_strings', 'MSG_IS_NOT_BEFORE') + ' ' +date2);
952 value=unformatNumber(trim(form[validate[formname][i][nameIndex]].value), num_grp_sep, dec_sep);
953 maximum = parseFloat(validate[formname][i][maxIndex]);
954 if( typeof maximum != 'undefined'){
957 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]);
962 value=unformatNumber(trim(form[validate[formname][i][nameIndex]].value), num_grp_sep, dec_sep);
963 minimum = parseFloat(validate[formname][i][minIndex]);
964 if( typeof minimum != 'undefined'){
967 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'));
972 compareTo = form[validate[formname][i][compareToIndex]];
973 if( typeof compareTo != 'undefined') {
974 item1 = trim(form[validate[formname][i][nameIndex]].value);
975 item2 = trim(compareTo.value);
976 if(!bothExist(item1, item2)) {
978 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex]);
983 compareTo = form[validate[formname][i][compareToIndex]];
984 if( typeof compareTo != 'undefined') {
985 item1 = trim(form[validate[formname][i][nameIndex]].value);
986 item2 = trim(compareTo.value);
987 if(!bothExist(item1, item2) || item1 != item2) {
989 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex]);
994 arr = eval(validate[formname][i][arrIndex]);
995 operator = validate[formname][i][operatorIndex];
996 item1 = trim(form[validate[formname][i][nameIndex]].value);
997 if (operator.charAt(0) == 'u') {
998 item1 = item1.toUpperCase();
999 operator = operator.substring(1);
1000 } else if (operator.charAt(0) == 'l') {
1001 item1 = item1.toLowerCase();
1002 operator = operator.substring(1);
1004 for(j = 0; j < arr.length; j++){
1006 if((operator == "==" && val == item1) || (operator == "!=" && val != item1)){
1008 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
1013 if(trim(form[validate[formname][i][nameIndex]].value) == 'false'){
1014 //Fake an error so form does not submit
1024 /* nsingh: BUG#15102
1025 Check min max default field logic.
1026 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.*/
1027 if(formsWithFieldLogic){
1028 var invalidLogic=false;
1029 if(formsWithFieldLogic.min && formsWithFieldLogic.max && formsWithFieldLogic._default) {
1030 var showErrorsOn={min:{value:'min', show:false, obj:formsWithFieldLogic.min.value},
1031 max:{value:'max',show:false, obj:formsWithFieldLogic.max.value},
1032 _default:{value:'default',show:false, obj:formsWithFieldLogic._default.value},
1033 len:{value:'len', show:false, obj:parseInt(formsWithFieldLogic.len.value,10)}};
1035 var min = (formsWithFieldLogic.min.value !='') ? parseFloat(formsWithFieldLogic.min.value) : 'undef';
1036 var max = (formsWithFieldLogic.max.value !='') ? parseFloat(formsWithFieldLogic.max.value) : 'undef';
1037 var _default = (formsWithFieldLogic._default.value!='')? parseFloat(formsWithFieldLogic._default.value) : 'undef';
1039 /*Check all lengths are <= max size.*/
1040 for(var i in showErrorsOn){
1041 if(showErrorsOn[i].value!='len' && showErrorsOn[i].obj.length > showErrorsOn.len.obj){
1043 showErrorsOn[i].show=true;
1044 showErrorsOn.len.show=true;
1048 if(min!='undef' && max!='undef' && _default!='undef'){
1049 if(!inRange(_default,min,max)){
1051 showErrorsOn.min.show=true;
1052 showErrorsOn.max.show=true;
1053 showErrorsOn._default.show=true;
1056 if(min!='undef' && max!= 'undef' && min > max){
1057 invalidLogic = true;
1058 showErrorsOn.min.show=true;
1059 showErrorsOn.max.show=true;
1061 if(min!='undef' && _default!='undef' && _default < min){
1063 invalidLogic = true;
1064 showErrorsOn.min.show=true;
1065 showErrorsOn._default.show=true;
1067 if(max!='undef' && _default !='undef' && _default>max){
1069 invalidLogic = true;
1070 showErrorsOn.max.show=true;
1071 showErrorsOn._default.show=true;
1076 for(var error in showErrorsOn)
1077 if(showErrorsOn[error].show)
1078 add_error_style(formname,showErrorsOn[error].value, formsWithFieldLogic.msg);
1083 formsWithFieldLogic = null;
1086 if(formWithPrecision){
1087 if (!isValidPrecision(formWithPrecision.float.value, formWithPrecision.precision.value)){
1089 add_error_style(formname, 'default', SUGAR.language.get('app_strings', 'ERR_COMPATIBLE_PRECISION_VALUE'));
1097 if (isError == true) {
1099 if (self.pageYOffset) // all except Explorer
1101 nwX = self.pageXOffset;
1102 seX = self.innerWidth;
1103 nwY = self.pageYOffset;
1104 seY = self.innerHeight;
1106 else if (document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
1108 nwX = document.documentElement.scrollLeft;
1109 seX = document.documentElement.clientWidth;
1110 nwY = document.documentElement.scrollTop;
1111 seY = document.documentElement.clientHeight;
1113 else if (document.body) // all other Explorers
1115 nwX = document.body.scrollLeft;
1116 seX = document.body.clientWidth;
1117 nwY = document.body.scrollTop;
1118 seY = document.body.clientHeight;
1121 var inView = true; // is there an error within viewport of browser
1122 for(var wp = 0; wp < inputsWithErrors.length; wp++) {
1123 var elementCoor = findElementPos(inputsWithErrors[wp]);
1124 if(!(elementCoor.x >= nwX && elementCoor.y >= nwY &&
1125 elementCoor.x <= seX && elementCoor.y <= seY)) { // if input is not within viewport
1127 scrollToTop = elementCoor.y - 75;
1128 scrollToLeft = elementCoor.x - 75;
1130 else { // on first input within viewport, don't scroll
1136 if(!inView) window.scrollTo(scrollToLeft,scrollToTop);
1141 disableOnUnloadEditView(form);
1148 * This array is used to remember mark status of rows in browse mode
1150 var marked_row = new Array;
1154 * Sets/unsets the pointer and marker in browse mode
1156 * @param object the table row
1157 * @param interger the row number
1158 * @param string the action calling this script (over, out or click)
1159 * @param string the default background color
1160 * @param string the color to use for mouseover
1161 * @param string the color to use for marking a row
1163 * @return boolean whether pointer is set or not
1165 function setPointer(theRow, theRowNum, theAction, theDefaultColor, thePointerColor, theMarkColor) {
1166 var theCells = null;
1168 // 1. Pointer and mark feature are disabled or the browser can't get the
1170 if ((thePointerColor == '' && theMarkColor == '')
1171 || typeof(theRow.style) == 'undefined') {
1175 // 2. Gets the current row and exits if the browser can't get it
1176 if (typeof(document.getElementsByTagName) != 'undefined') {
1177 theCells = theRow.getElementsByTagName('td');
1179 else if (typeof(theRow.cells) != 'undefined') {
1180 theCells = theRow.cells;
1186 // 3. Gets the current color...
1187 var rowCellsCnt = theCells.length;
1188 var domDetect = null;
1189 var currentColor = null;
1190 var newColor = null;
1191 // 3.1 ... with DOM compatible browsers except Opera that does not return
1192 // valid values with "getAttribute"
1193 if (typeof(window.opera) == 'undefined'
1194 && typeof(theCells[0].getAttribute) != 'undefined') {
1195 currentColor = theCells[0].getAttribute('bgcolor');
1198 // 3.2 ... with other browsers
1200 currentColor = theCells[0].style.backgroundColor;
1204 // 4. Defines the new color
1205 // 4.1 Current color is the default one
1206 if (currentColor == ''
1207 || (currentColor!= null && (currentColor.toLowerCase() == theDefaultColor.toLowerCase()))) {
1208 if (theAction == 'over' && thePointerColor != '') {
1209 newColor = thePointerColor;
1211 else if (theAction == 'click' && theMarkColor != '') {
1212 newColor = theMarkColor;
1213 marked_row[theRowNum] = true;
1216 // 4.1.2 Current color is the pointer one
1217 else if (currentColor!= null && (currentColor.toLowerCase() == thePointerColor.toLowerCase())
1218 && (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])) {
1219 if (theAction == 'out') {
1220 newColor = theDefaultColor;
1222 else if (theAction == 'click' && theMarkColor != '') {
1223 newColor = theMarkColor;
1224 marked_row[theRowNum] = true;
1227 // 4.1.3 Current color is the marker one
1228 else if (currentColor!= null && (currentColor.toLowerCase() == theMarkColor.toLowerCase())) {
1229 if (theAction == 'click') {
1230 newColor = (thePointerColor != '')
1233 marked_row[theRowNum] = (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])
1239 // 5. Sets the new color...
1242 // 5.1 ... with DOM compatible browsers except Opera
1244 for (c = 0; c < rowCellsCnt; c++) {
1245 theCells[c].setAttribute('bgcolor', newColor, 0);
1248 // 5.2 ... with other browsers
1250 for (c = 0; c < rowCellsCnt; c++) {
1251 theCells[c].style.backgroundColor = newColor;
1257 } // end of the 'setPointer()' function
1261 * listbox redirection
1263 function goToUrl(selObj, goToLocation) {
1264 eval("document.location.href = '" + goToLocation + "pos=" + selObj.options[selObj.selectedIndex].value + "'");
1269 var json_objects = new Object();
1271 function getXMLHTTPinstance() {
1272 var xmlhttp = false;
1273 var userAgent = navigator.userAgent.toLowerCase() ;
1275 // IE Check supports ActiveX controls
1276 if (userAgent.indexOf("msie") != -1 && userAgent.indexOf("mac") == -1 && userAgent.indexOf("opera") == -1) {
1277 var version = navigator.appVersion.match(/MSIE (.\..)/)[1] ;
1278 if(version >= 5.5 ) {
1280 xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
1284 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
1293 if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
1294 xmlhttp = new XMLHttpRequest();
1299 // NOW LOAD THE OBJECT..
1300 var global_xmlhttp = getXMLHTTPinstance();
1302 function http_fetch_sync(url,post_data) {
1303 global_xmlhttp = getXMLHTTPinstance();
1304 var method = (typeof(post_data) != 'undefined') ? 'POST' : 'GET';
1307 global_xmlhttp.open(method, url, false);
1310 alert('message:'+e.message+":url:"+url);
1312 if(method == 'POST') {
1313 global_xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
1316 global_xmlhttp.send(post_data);
1318 if (SUGAR.util.isLoginPage(global_xmlhttp.responseText))
1321 var args = {"responseText" : global_xmlhttp.responseText,
1322 "responseXML" : global_xmlhttp.responseXML,
1323 "request_id" : typeof(request_id) != "undefined" ? request_id : 0};
1327 // this is a GET unless post_data is defined
1329 function http_fetch_async(url,callback,request_id,post_data) {
1331 if(typeof(post_data) != 'undefined') {
1336 global_xmlhttp.open(method, url,true);
1339 alert('message:'+e.message+":url:"+url);
1341 if(method == 'POST') {
1342 global_xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
1344 global_xmlhttp.onreadystatechange = function() {
1345 if(global_xmlhttp.readyState==4) {
1346 if(global_xmlhttp.status == 200) {
1347 if (SUGAR.util.isLoginPage(global_xmlhttp.responseText))
1349 var args = {"responseText" : global_xmlhttp.responseText,
1350 "responseXML" : global_xmlhttp.responseXML,
1351 "request_id" : request_id };
1352 callback.call(document,args);
1355 alert("There was a problem retrieving the XML data:\n" + global_xmlhttp.statusText);
1359 global_xmlhttp.send(post_data);
1362 function call_json_method(module,action,vars,variable_name,callback) {
1363 global_xmlhttp.open("GET", "index.php?entryPoint=json&module="+module+"&action="+action+"&"+vars,true);
1364 global_xmlhttp.onreadystatechange=
1366 if(global_xmlhttp.readyState==4) {
1367 if(global_xmlhttp.status == 200) {
1368 // cn: bug 12274 - pass through JSON.parse() to remove security envelope
1369 json_objects[variable_name] = YAHOO.lang.JSON.parse(global_xmlhttp.responseText);
1371 // cn: bug 12274 - safe from CSRF, render response as expected
1372 var respText = YAHOO.lang.JSON.parse(global_xmlhttp.responseText);
1373 var args = {responseText:respText, responseXML:global_xmlhttp.responseXML};
1374 callback.call(document, args);
1377 alert("There was a problem retrieving the XML data:\n" + global_xmlhttp.statusText);
1381 global_xmlhttp.send(null);
1384 function insert_at_cursor(field, value) {
1386 if (document.selection) {
1388 sel = document.selection.createRange();
1392 else if(field.selectionStart || field.selectionStart == '0') {
1393 var start_pos = field.selectionStart;
1394 var end_pos = field.selectionEnd;
1395 field.value = field.value.substring(0, start_pos) + value + field.value.substring(end_pos, field.value.length);
1398 field.value += value;
1402 function checkParentType(type,button) {
1403 if(button == null) {
1406 if(typeof disabledModules != 'undefined' && typeof(disabledModules[type]) != 'undefined') {
1407 button.disabled='disabled';
1410 button.disabled = false;
1414 function parseDate(input, format) {
1416 format = format.replace(/%/g, '');
1417 sep = format.charAt(1);
1418 yAt = format.indexOf('Y')
1419 // 1-1-06 or 1-12-06 or 1-1-2006 or 1-12-2006
1420 if(date.match(/^\d{1,2}[\/-]\d{1,2}[\/-]\d{2,4}$/) && yAt == 4) {
1421 if(date.match(/^\d{1}[\/-].*$/)) date = '0' + date;
1422 if(date.match(/^\d{2}[\/-]\d{1}[\/-].*$/)) date = date.substring(0,3) + '0' + date.substring(3,date.length);
1423 if(date.match(/^\d{2}[\/-]\d{2}[\/-]\d{2}$/)) date = date.substring(0,6) + '20' + date.substring(6,date.length);
1425 // 06-11-1 or 06-1-1
1426 else if(date.match(/^\d{2,4}[\/-]\d{1,2}[\/-]\d{1,2}$/)) {
1427 if(date.match(/^\d{2}[\/-].*$/)) date = '20' + date;
1428 if(date.match(/^\d{4}[\/-]\d{1}[\/-].*$/)) date = date.substring(0,5) + '0' + date.substring(5,date.length);
1429 if(date.match(/^\d{4}[\/-]\d{2}[\/-]\d{1}$/)) date = date.substring(0,8) + '0' + date.substring(8,date.length);
1431 else if(date.match(/^\d{4,8}$/)) { // digits only
1433 if(date.match(/^\d{8}$/)) digits = 8;// match for 8 digits
1434 else if(date.match(/\d{6}/)) digits = 6;// match for 5 digits
1435 else if(date.match(/\d{4}/)) digits = 4;// match for 5 digits
1436 else if(date.match(/\d{5}/)) digits = 5;// match for 5 digits
1441 case 4: date = '20' + date.substring(0,2) + sep + '0' + date.substring(2, 3) + sep + '0' + date.substring(3,4); break;
1442 case 5: date = '20' + date.substring(0,2) + sep + date.substring(2, 4) + sep + '0' + date.substring(4,5); break;
1443 case 6: date = '20' + date.substring(0,2) + sep + date.substring(2, 4) + sep + date.substring(4,6); break;
1444 case 8: date = date.substring(0,4) + sep + date.substring(4, 6) + sep + date.substring(6,8); break;
1449 case 4: date = '0' + date.substring(0,1) + sep + '20' + date.substring(1, 3) + sep + '0' + date.substring(3,4); break;
1450 case 5: date = date.substring(0,2) + sep + '20' + date.substring(2, 4) + sep + '0' + date.substring(4,5); break;
1451 case 6: date = date.substring(0,2) + sep + '20' + date.substring(2, 4) + sep + date.substring(4,6); break;
1452 case 8: date = date.substring(0,2) + sep + date.substring(2, 6) + sep + date.substring(6,8); break;
1456 case 4: date = '0' + date.substring(0,1) + sep + '0' + date.substring(1, 2) + sep + '20' + date.substring(2,4); break;
1457 case 5: date = '0' + date.substring(0,1) + sep + date.substring(1, 3) + sep + '20' + date.substring(3,5); break;
1458 case 6: date = date.substring(0,2) + sep + date.substring(2, 4) + sep + '20' + date.substring(4,6); break;
1459 case 8: date = date.substring(0,2) + sep + date.substring(2, 4) + sep + date.substring(4,8); break;
1464 date = date.replace(/[\/-]/g, sep);
1468 // find obj's position
1469 function findElementPos(obj) {
1472 if (obj.offsetParent) {
1473 while (obj.offsetParent) {
1474 x += obj.offsetLeft;
1476 obj = obj.offsetParent;
1478 }//if offsetParent exists
1479 else if (obj.x && obj.y) {
1483 return new coordinate(x, y);
1487 // get dimensions of the browser window
1488 function getClientDim() {
1489 var nwX, nwY, seX, seY;
1490 if (self.pageYOffset) // all except Explorer
1492 nwX = self.pageXOffset;
1493 seX = self.innerWidth + nwX;
1494 nwY = self.pageYOffset;
1495 seY = self.innerHeight + nwY;
1497 else if (document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
1499 nwX = document.documentElement.scrollLeft;
1500 seX = document.documentElement.clientWidth + nwX;
1501 nwY = document.documentElement.scrollTop;
1502 seY = document.documentElement.clientHeight + nwY;
1504 else if (document.body) // all other Explorers
1506 nwX = document.body.scrollLeft;
1507 seX = document.body.clientWidth + nwX;
1508 nwY = document.body.scrollTop;
1509 seY = document.body.clientHeight + nwY;
1511 return {'nw' : new coordinate(nwX, nwY), 'se' : new coordinate(seX, seY)};
1515 * stop propagation on events
1517 function freezeEvent(e) {
1519 if (e.preventDefault) e.preventDefault();
1520 e.returnValue = false;
1521 e.cancelBubble = true;
1522 if (e.stopPropagation) e.stopPropagation();
1531 function coordinate(_x, _y) {
1540 return new position(this.x + rh.x, this.y + rh.y);
1544 return new position(this.x + rh.x, this.y + rh.y);
1548 // sends theForm via AJAX and fills in the theDiv
1549 function sendAndRetrieve(theForm, theDiv, loadingStr) {
1550 function success(data) {
1551 document.getElementById(theDiv).innerHTML = data.responseText;
1552 ajaxStatus.hideStatus();
1554 if(typeof loadingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
1555 ajaxStatus.showStatus(loadingStr);
1556 YAHOO.util.Connect.setForm(theForm);
1557 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
1561 //save the form and redirect
1562 function sendAndRedirect(theForm, loadingStr, redirect_location) {
1563 function success(data) {
1564 if(redirect_location){
1565 location.href=redirect_location;
1567 ajaxStatus.hideStatus();
1569 if(typeof loadingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
1570 ajaxStatus.showStatus(loadingStr);
1571 YAHOO.util.Connect.setForm(theForm);
1572 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
1576 function saveForm(theForm, theDiv, loadingStr) {
1577 if(check_form(theForm)){
1578 for(i = 0; i < ajaxFormArray.length; i++){
1579 if(ajaxFormArray[i] == theForm){
1580 ajaxFormArray.splice(i, 1);
1583 return sendAndRetrieve(theForm, loadingStr, theDiv);
1589 // Builds a "snapshot" of the form, so we can use it to see if someone has changed it.
1590 function snapshotForm(theForm) {
1591 var snapshotTxt = '';
1592 var elemList = theForm.elements;
1596 for( var i = 0; i < elemList.length ; i++ ) {
1598 if ( typeof(elem.type) == 'undefined' ) {
1602 elemType = elem.type.toLowerCase();
1604 snapshotTxt = snapshotTxt + elem.name;
1606 if ( elemType == 'text' || elemType == 'textarea' || elemType == 'password' ) {
1607 snapshotTxt = snapshotTxt + elem.value;
1609 else if ( elemType == 'select' || elemType == 'select-one' || elemType == 'select-multiple' ) {
1610 var optionList = elem.options;
1611 for ( var ii = 0 ; ii < optionList.length ; ii++ ) {
1612 if ( optionList[ii].selected ) {
1613 snapshotTxt = snapshotTxt + optionList[ii].value;
1617 else if ( elemType == 'radio' || elemType == 'checkbox' ) {
1618 if ( elem.selected ) {
1619 snapshotTxt = snapshotTxt + 'checked';
1622 else if ( elemType == 'hidden' ) {
1623 snapshotTxt = snapshotTxt + elem.value;
1630 function initEditView(theForm) {
1631 if (SUGAR.util.ajaxCallInProgress()) {
1632 window.setTimeout(function(){initEditView(theForm);}, 100);
1635 if ( theForm == null || theForm.id == null ) {
1636 // Not much we can do here.
1639 // we don't need to check if the data is changed in the search popup
1640 if (theForm.id == 'popup_query_form' || theForm.id == 'MassUpdate') {
1643 if ( typeof editViewSnapshots == 'undefined' ) {
1644 editViewSnapshots = new Object();
1646 if ( typeof SUGAR.loadedForms == 'undefined' ) {
1647 SUGAR.loadedForms = new Object();
1649 editViewSnapshots[theForm.id] = snapshotForm(theForm);
1650 SUGAR.loadedForms[theForm.id] = true;
1653 function onUnloadEditView(theForm) {
1655 var dataHasChanged = false;
1657 if ( typeof editViewSnapshots == 'undefined' ) {
1658 // No snapshots, move along
1662 if ( typeof theForm == 'undefined' ) {
1663 // Need to check all editViewSnapshots
1664 for ( var idx in editViewSnapshots ) {
1666 theForm = document.getElementById(idx);
1667 // console.log('DEBUG: Checking all forms '+theForm.id);
1668 if ( theForm == null
1669 || typeof editViewSnapshots[theForm.id] == 'undefined'
1670 || editViewSnapshots[theForm.id] == null
1671 || !SUGAR.loadedForms[theForm.id]) {
1675 var snap = snapshotForm(theForm);
1676 if ( editViewSnapshots[theForm.id] != snap ) {
1677 dataHasChanged = true;
1681 // Just need to check a single form for changes
1682 if ( editViewSnapshots == null || typeof theForm.id == 'undefined' || typeof editViewSnapshots[theForm.id] == 'undefined' || editViewSnapshots[theForm.id] == null ) {
1686 // console.log('DEBUG: Checking one form '+theForm.id);
1687 if ( editViewSnapshots[theForm.id] != snapshotForm(theForm) ) {
1688 // Data has changed.
1689 dataHasChanged = true;
1693 if ( dataHasChanged == true ) {
1694 return SUGAR.language.get('app_strings','WARN_UNSAVED_CHANGES');
1701 function disableOnUnloadEditView(theForm) {
1702 // If you don't pass anything in, it disables all checking
1703 if ( typeof theForm == 'undefined' || typeof editViewSnapshots == 'undefined' || theForm == null || editViewSnapshots == null) {
1704 window.onbeforeunload = null;
1705 editViewSnapshots = null;
1707 // console.log('DEBUG: Disabling all edit view checks');
1710 // Otherwise, it just disables it for this form
1711 if ( typeof(theForm.id) != 'undefined' && typeof(editViewSnapshots[theForm.id]) != 'undefined' ) {
1712 editViewSnapshots[theForm.id] = null;
1715 // console.log('DEBUG : Disabling just checks for '+theForm.id);
1721 * save some forms using an ajax call
1722 * theForms - the ids of all of theh forms to save
1723 * savingStr - the string to display when saving the form
1724 * completeStr - the string to display when the form has been saved
1726 function saveForms( savingStr, completeStr) {
1728 theForms = ajaxFormArray;
1729 function success(data) {
1730 var theForm = document.getElementById(ajaxFormArray[0]);
1731 document.getElementById('multiedit_'+theForm.id).innerHTML = data.responseText;
1732 var saveAllButton = document.getElementById('ajaxsaveall');
1733 ajaxFormArray.splice(index, 1);
1734 if(saveAllButton && ajaxFormArray.length <= 1){
1735 saveAllButton.style.visibility = 'hidden';
1738 if(index == theForms.length){
1739 ajaxStatus.showStatus(completeStr);
1740 window.setTimeout('ajaxStatus.hideStatus();', 2000);
1742 saveAllButton.style.visibility = 'hidden';
1747 if(typeof savingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
1748 ajaxStatus.showStatus(savingStr);
1750 //loop through the forms saving each one
1751 for(i = 0; i < theForms.length; i++){
1752 var theForm = document.getElementById(theForms[i]);
1753 if(check_form(theForm.id)){
1754 theForm.action.value='AjaxFormSave';
1755 YAHOO.util.Connect.setForm(theForm);
1756 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
1758 ajaxStatus.hideStatus();
1760 lastSubmitTime = lastSubmitTime-2000;
1765 // -- start sugarListView class
1766 // js functions used for ListView
1767 function sugarListView() {
1771 sugarListView.prototype.confirm_action = function(del) {
1773 return confirm( SUGAR.language.get('app_strings', 'NTC_DELETE_CONFIRMATION_NUM') + sugarListView.get_num_selected() + SUGAR.language.get('app_strings', 'NTC_DELETE_SELECTED_RECORDS'));
1776 return confirm( SUGAR.language.get('app_strings', 'NTC_UPDATE_CONFIRMATION_NUM') + sugarListView.get_num_selected() + SUGAR.language.get('app_strings', 'NTC_DELETE_SELECTED_RECORDS'));
1780 sugarListView.get_num_selected = function () {
1781 if(typeof document.MassUpdate != 'undefined') {
1782 the_form = document.MassUpdate;
1783 for(wp = 0; wp < the_form.elements.length; wp++) {
1784 if(typeof the_form.elements[wp].name != 'undefined' && the_form.elements[wp].name == 'selectCount[]') {
1785 return the_form.elements[wp].value;
1792 sugarListView.update_count = function(count, add) {
1793 if(typeof document.MassUpdate != 'undefined') {
1794 the_form = document.MassUpdate;
1795 for(wp = 0; wp < the_form.elements.length; wp++) {
1796 if(typeof the_form.elements[wp].name != 'undefined' && the_form.elements[wp].name == 'selectCount[]') {
1798 the_form.elements[wp].value = parseInt(the_form.elements[wp].value,10) + count;
1799 if (the_form.select_entire_list.value == 1 && the_form.show_plus.value) {
1800 the_form.elements[wp].value += '+';
1803 if (the_form.select_entire_list.value == 1 && the_form.show_plus.value) {
1804 the_form.elements[wp].value = count + '+';
1806 the_form.elements[wp].value = count;
1813 sugarListView.prototype.use_external_mail_client = function(no_record_txt, module) {
1814 selected_records = sugarListView.get_checks_count();
1815 if(selected_records <1) {
1816 alert(no_record_txt);
1820 if (document.MassUpdate.select_entire_list.value == 1) {
1821 if (totalCount > 10) {
1822 alert(totalCountError);
1827 else if (document.MassUpdate.massall.checked == true)
1831 sugarListView.get_checks();
1833 if(select) { // use selected items
1834 ids = document.MassUpdate.uid.value;
1836 else { // use current page
1837 inputs = document.MassUpdate.elements;
1839 for(i = 0; i < inputs.length; i++) {
1840 if(inputs[i].name == 'mass[]' && inputs[i].checked && typeof(inputs[i].value) != 'function') {
1841 ar.push(inputs[i].value);
1846 YAHOO.util.Connect.asyncRequest("POST", "index.php?", {
1847 success: this.use_external_mail_client_callback
1848 }, SUGAR.util.paramsToUrl({
1851 listViewExternalClient: 1,
1852 action_module: module,
1860 sugarListView.prototype.use_external_mail_client_callback = function(o)
1863 location.href = 'mailto:' + o.responseText;
1866 sugarListView.prototype.send_form_for_emails = function(select, currentModule, action, no_record_txt,action_module,totalCount, totalCountError) {
1867 if ( typeof(SUGAR.config.email_sugarclient_listviewmaxselect) != 'undefined' ) {
1871 maxCount = SUGAR.config.email_sugarclient_listviewmaxselect;
1874 if (document.MassUpdate.select_entire_list.value == 1) {
1875 if (totalCount > maxCount) {
1876 alert(totalCountError);
1881 else if (document.MassUpdate.massall.checked == true)
1886 sugarListView.get_checks();
1887 // create new form to post (can't access action property of MassUpdate form due to action input)
1888 var newForm = document.createElement('form');
1889 newForm.method = 'post';
1890 newForm.action = action;
1891 newForm.name = 'newForm';
1892 newForm.id = 'newForm';
1893 var uidTa = document.createElement('textarea');
1895 uidTa.style.display = 'none';
1897 if(select) { // use selected items
1898 uidTa.value = document.MassUpdate.uid.value;
1900 else { // use current page
1901 inputs = document.MassUpdate.elements;
1903 for(i = 0; i < inputs.length; i++) {
1904 if(inputs[i].name == 'mass[]' && inputs[i].checked && typeof(inputs[i].value) != 'function') {
1905 ar.push(inputs[i].value);
1908 uidTa.value = ar.join(',');
1911 if(uidTa.value == '') {
1912 alert(no_record_txt);
1916 var selectedArray = uidTa.value.split(",");
1917 if(selectedArray.length > maxCount) {
1918 alert(totalCountError);
1921 newForm.appendChild(uidTa);
1923 var moduleInput = document.createElement('input');
1924 moduleInput.name = 'module';
1925 moduleInput.type = 'hidden';
1926 moduleInput.value = currentModule;
1927 newForm.appendChild(moduleInput);
1929 var actionInput = document.createElement('input');
1930 actionInput.name = 'action';
1931 actionInput.type = 'hidden';
1932 actionInput.value = 'Compose';
1933 newForm.appendChild(actionInput);
1935 if (typeof action_module != 'undefined' && action_module!= '') {
1936 var actionModule = document.createElement('input');
1937 actionModule.name = 'action_module';
1938 actionModule.type = 'hidden';
1939 actionModule.value = action_module;
1940 newForm.appendChild(actionModule);
1942 //return_info must follow this pattern."&return_module=Accounts&return_action=index"
1943 if (typeof return_info!= 'undefined' && return_info != '') {
1944 var params= return_info.split('&');
1945 if (params.length > 0) {
1946 for (var i=0;i< params.length;i++) {
1947 if (params[i].length > 0) {
1948 var param_nv=params[i].split('=');
1949 if (param_nv.length==2){
1950 returnModule = document.createElement('input');
1951 returnModule.name = param_nv[0];
1952 returnModule.type = 'hidden';
1953 returnModule.value = param_nv[1];
1954 newForm.appendChild(returnModule);
1961 var isAjaxCall = document.createElement('input');
1962 isAjaxCall.name = 'ajaxCall';
1963 isAjaxCall.type = 'hidden';
1964 isAjaxCall.value = true;
1965 newForm.appendChild(isAjaxCall);
1967 var isListView = document.createElement('input');
1968 isListView.name = 'ListView';
1969 isListView.type = 'hidden';
1970 isListView.value = true;
1971 newForm.appendChild(isListView);
1973 var toPdf = document.createElement('input');
1974 toPdf.name = 'to_pdf';
1975 toPdf.type = 'hidden';
1977 newForm.appendChild(toPdf);
1979 //Grab the Quick Compose package for the listview
1980 YAHOO.util.Connect.setForm(newForm);
1983 success: function(o) {
1984 var resp = YAHOO.lang.JSON.parse(o.responseText);
1985 var quickComposePackage = new Object();
1986 quickComposePackage.composePackage = resp;
1987 quickComposePackage.fullComposeUrl = 'index.php?module=Emails&action=Compose&ListView=true' +
1988 '&uid=' + uidTa.value + '&action_module=' + action_module;
1990 SUGAR.quickCompose.init(quickComposePackage);
1994 YAHOO.util.Connect.asyncRequest('POST','index.php', callback,null);
1996 // awu Bug 18624: Fixing issue where a canceled Export and unselect of row will persist the uid field, clear the field
1997 document.MassUpdate.uid.value = '';
2002 sugarListView.prototype.send_form = function(select, currentModule, action, no_record_txt,action_module,return_info) {
2003 if (document.MassUpdate.select_entire_list.value == 1) {
2005 if(sugarListView.get_checks_count() < 1) {
2006 alert(no_record_txt);
2011 if ( action.indexOf('?') != -1 )
2012 href += '&module=' + currentModule;
2014 href += '?module=' + currentModule;
2017 href += return_info;
2018 var newForm = document.createElement('form');
2019 newForm.method = 'post';
2020 newForm.action = href;
2021 newForm.name = 'newForm';
2022 newForm.id = 'newForm';
2023 var postTa = document.createElement('textarea');
2024 postTa.name = 'current_post';
2025 postTa.value = document.MassUpdate.current_query_by_page.value;
2026 postTa.style.display = 'none';
2027 newForm.appendChild(postTa);
2028 document.MassUpdate.parentNode.appendChild(newForm);
2032 else if (document.MassUpdate.massall.checked == true)
2037 sugarListView.get_checks();
2038 // create new form to post (can't access action property of MassUpdate form due to action input)
2039 var newForm = document.createElement('form');
2040 newForm.method = 'post';
2041 newForm.action = action;
2042 newForm.name = 'newForm';
2043 newForm.id = 'newForm';
2044 var uidTa = document.createElement('textarea');
2046 uidTa.style.display = 'none';
2047 uidTa.value = document.MassUpdate.uid.value;
2049 if(uidTa.value == '') {
2050 alert(no_record_txt);
2054 newForm.appendChild(uidTa);
2056 var moduleInput = document.createElement('input');
2057 moduleInput.name = 'module';
2058 moduleInput.type = 'hidden';
2059 moduleInput.value = currentModule;
2060 newForm.appendChild(moduleInput);
2062 var actionInput = document.createElement('input');
2063 actionInput.name = 'action';
2064 actionInput.type = 'hidden';
2065 actionInput.value = 'index';
2066 newForm.appendChild(actionInput);
2068 if (typeof action_module != 'undefined' && action_module!= '') {
2069 var actionModule = document.createElement('input');
2070 actionModule.name = 'action_module';
2071 actionModule.type = 'hidden';
2072 actionModule.value = action_module;
2073 newForm.appendChild(actionModule);
2075 //return_info must follow this pattern."&return_module=Accounts&return_action=index"
2076 if (typeof return_info!= 'undefined' && return_info != '') {
2077 var params= return_info.split('&');
2078 if (params.length > 0) {
2079 for (var i=0;i< params.length;i++) {
2080 if (params[i].length > 0) {
2081 var param_nv=params[i].split('=');
2082 if (param_nv.length==2){
2083 returnModule = document.createElement('input');
2084 returnModule.name = param_nv[0];
2085 returnModule.type = 'hidden';
2086 returnModule.value = param_nv[1];
2087 newForm.appendChild(returnModule);
2094 document.MassUpdate.parentNode.appendChild(newForm);
2097 // awu Bug 18624: Fixing issue where a canceled Export and unselect of row will persist the uid field, clear the field
2098 document.MassUpdate.uid.value = '';
2102 //return a count of checked row.
2103 sugarListView.get_checks_count = function() {
2106 if(document.MassUpdate.uid.value != '') {
2107 oldUids = document.MassUpdate.uid.value.split(',');
2108 for(uid in oldUids) {
2109 if(typeof(oldUids[uid]) != 'function') {
2110 ar[oldUids[uid]] = 1;
2114 // build associated array of uids, associated array ensures uniqueness
2115 inputs = document.MassUpdate.elements;
2116 for(i = 0; i < inputs.length; i++) {
2117 if(inputs[i].name == 'mass[]') {
2118 ar[inputs[i].value] = (inputs[i].checked) ? 1 : 0; // 0 of it is unchecked
2122 // build regular array of uids
2125 if((typeof(ar[i]) != 'function') && ar[i] == 1) {
2133 // saves the checks on the current page into the uid textarea
2134 sugarListView.get_checks = function() {
2137 if(document.MassUpdate.uid.value != '') {
2138 oldUids = document.MassUpdate.uid.value.split(',');
2139 for(uid in oldUids) {
2140 if(typeof(oldUids[uid]) != 'function') {
2141 ar[oldUids[uid]] = 1;
2146 // build associated array of uids, associated array ensures uniqueness
2147 inputs = document.MassUpdate.elements;
2148 for(i = 0; i < inputs.length; i++) {
2149 if(inputs[i].name == 'mass[]') {
2150 ar[inputs[i].value] = (inputs[i].checked) ? 1 : 0; // 0 of it is unchecked
2154 // build regular array of uids
2157 if(typeof(ar[i]) != 'function' && ar[i] == 1) {
2162 document.MassUpdate.uid.value = uids.join(',');
2164 if(uids.length == 0) return false; // return false if no checks to get
2165 return true; // there are saved checks
2168 sugarListView.prototype.order_checks = function(order,orderBy,moduleString){
2169 checks = sugarListView.get_checks();
2170 eval('document.MassUpdate.' + moduleString + '.value = orderBy');
2171 document.MassUpdate.lvso.value = order;
2172 if(typeof document.MassUpdate.massupdate != 'undefined') {
2173 document.MassUpdate.massupdate.value = 'false';
2176 //we must first clear the action of massupdate, change it to index
2177 document.MassUpdate.action.value = document.MassUpdate.return_action.value;
2178 document.MassUpdate.return_module.value='';
2179 document.MassUpdate.return_action.value='';
2180 document.MassUpdate.submit();
2184 sugarListView.prototype.save_checks = function(offset, moduleString) {
2185 checks = sugarListView.get_checks();
2186 eval('document.MassUpdate.' + moduleString + '.value = offset');
2188 if(typeof document.MassUpdate.massupdate != 'undefined') {
2189 document.MassUpdate.massupdate.value = 'false';
2192 //we must first clear the action of massupdate, change it to index
2193 document.MassUpdate.action.value = document.MassUpdate.return_action.value;
2194 document.MassUpdate.return_module.value='';
2195 document.MassUpdate.return_action.value='';
2196 document.MassUpdate.submit();
2202 sugarListView.prototype.check_item = function(cb, form) {
2204 sugarListView.update_count(1, true);
2206 sugarListView.update_count(-1, true);
2207 if(typeof form != 'undefined' && form != null) {
2208 sugarListView.prototype.updateUid(cb, form);
2213 /**#28000, remove the unselect record id from MassUpdate.uid **/
2214 sugarListView.prototype.updateUid = function(cb , form){
2215 if(form.name == 'MassUpdate' && form.uid && form.uid.value && cb.value && form.uid.value.indexOf(cb.value) != -1){
2216 if(form.uid.value.indexOf(','+cb.value)!= -1){
2217 form.uid.value = form.uid.value.replace(','+cb.value , '');
2218 }else if(form.uid.value.indexOf(cb.value + ',')!= -1){
2219 form.uid.value = form.uid.value.replace(cb.value + ',' , '');
2220 }else if(form.uid.value.indexOf(cb.value)!= -1){
2221 form.uid.value = form.uid.value.replace(cb.value , '');
2226 sugarListView.prototype.check_entire_list = function(form, field, value, list_count) {
2227 // count number of items
2229 document.MassUpdate.massall.checked = true;
2230 document.MassUpdate.massall.disabled = true;
2232 for (i = 0; i < form.elements.length; i++) {
2233 if(form.elements[i].name == field && form.elements[i].disabled == false) {
2234 if(form.elements[i].checked != value) count++;
2235 form.elements[i].checked = value;
2236 form.elements[i].disabled = true;
2239 document.MassUpdate.select_entire_list.value = 1;
2241 sugarListView.update_count(list_count, false);
2242 //else sugarListView.update_count(-1 * count, true);
2245 sugarListView.prototype.check_all = function(form, field, value, pageTotal) {
2246 // count number of items
2248 document.MassUpdate.massall.checked = value;
2249 if (document.MassUpdate.select_entire_list &&
2250 document.MassUpdate.select_entire_list.value == 1)
2251 document.MassUpdate.massall.disabled = true;
2253 document.MassUpdate.massall.disabled = false;
2255 for (i = 0; i < form.elements.length; i++) {
2256 if(form.elements[i].name == field && !(form.elements[i].disabled == true && form.elements[i].checked == false)) {
2257 form.elements[i].disabled = false;
2259 if(form.elements[i].checked != value)
2261 form.elements[i].checked = value;
2263 sugarListView.prototype.updateUid(form.elements[i], form);
2268 sugarListView.update_count(pageTotal);
2270 sugarListView.update_count(count, true);
2272 sugarListView.update_count(-1 * count, true);
2274 sugarListView.check_all = sugarListView.prototype.check_all;
2275 sugarListView.confirm_action = sugarListView.prototype.confirm_action;
2277 sugarListView.prototype.check_boxes = function() {
2278 var inputsCount = 0;
2279 var checkedCount = 0;
2280 var existing_onload = window.onload;
2281 var theForm = document.MassUpdate;
2282 inputs_array = theForm.elements;
2284 if(typeof theForm.uid.value != 'undefined' && theForm.uid.value != "") {
2285 checked_items = theForm.uid.value.split(",");
2286 if (theForm.select_entire_list.value == 1)
2287 document.MassUpdate.massall.disabled = true;
2289 for(wp = 0 ; wp < inputs_array.length; wp++) {
2290 if(inputs_array[wp].name == "mass[]") {
2292 if (theForm.select_entire_list.value == 1) {
2293 inputs_array[wp].checked = true;
2294 inputs_array[wp].disabled = true;
2298 for(i in checked_items) {
2299 if(inputs_array[wp].value == checked_items[i]) {
2301 inputs_array[wp].checked = true;
2307 if (theForm.select_entire_list.value == 0)
2308 sugarListView.update_count(checked_items.length);
2310 sugarListView.update_count(0, true);
2314 for(wp = 0 ; wp < inputs_array.length; wp++) {
2315 if(inputs_array[wp].name == "mass[]") {
2316 inputs_array[wp].checked = false;
2317 inputs_array[wp].disabled = false;
2320 if (document.MassUpdate.massall) {
2321 document.MassUpdate.massall.checked = false;
2322 document.MassUpdate.massall.disabled = false;
2324 sugarListView.update_count(0)
2326 if(checkedCount > 0 && checkedCount == inputsCount)
2327 document.MassUpdate.massall.checked = true;
2333 * This function is used in Email Template Module's listview.
2334 * It will check whether the templates are used in Campaing->EmailMarketing.
2335 * If true, it will notify user.
2337 function check_used_email_templates() {
2338 var ids = document.MassUpdate.uid.value;
2340 success:function(r) {
2341 if(r.responseText != '') {
2342 if(!confirm(SUGAR.language.get('app_strings','NTC_TEMPLATES_IS_USED') + r.responseText)) {
2346 document.MassUpdate.submit();
2350 url = "index.php?module=EmailTemplates&action=CheckDeletable&from=ListView&to_pdf=1&records="+ids;
2351 YAHOO.util.Connect.asyncRequest('POST',url, call_back,null);
2355 sugarListView.prototype.send_mass_update = function(mode, no_record_txt, del) {
2356 formValid = check_form('MassUpdate');
2357 if(!formValid && !del) return false;
2360 if (document.MassUpdate.select_entire_list &&
2361 document.MassUpdate.select_entire_list.value == 1)
2366 var ar = new Array();
2370 for(wp = 0; wp < document.MassUpdate.elements.length; wp++) {
2371 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)+'$');
2372 //when the uid is already in document.MassUpdate.uid.value, we should not add it to ar.
2373 if(typeof document.MassUpdate.elements[wp].name != 'undefined'
2374 && document.MassUpdate.elements[wp].name == 'mass[]'
2375 && document.MassUpdate.elements[wp].checked
2376 && !reg_for_existing_uid.test(document.MassUpdate.uid.value)) {
2377 ar.push(document.MassUpdate.elements[wp].value);
2380 if(document.MassUpdate.uid.value != '') document.MassUpdate.uid.value += ',';
2381 document.MassUpdate.uid.value += ar.join(',');
2382 if(document.MassUpdate.uid.value == '') {
2383 alert(no_record_txt);
2386 if(typeof(current_admin_id)!='undefined' && document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'Users' && (document.MassUpdate.is_admin.value!='' || document.MassUpdate.status.value!='')) {
2387 var reg_for_current_admin_id = new RegExp('^'+current_admin_id+'[\s]*,|,[\s]*'+current_admin_id+'[\s]*,|,[\s]*'+current_admin_id+'$|^'+current_admin_id+'$');
2388 if(reg_for_current_admin_id.test(document.MassUpdate.uid.value)) {
2389 //if current user is admin, we should not allow massupdate the user_type and status of himself
2390 alert(SUGAR.language.get('Users','LBL_LAST_ADMIN_NOTICE'));
2396 var entireInput = document.createElement('input');
2397 entireInput.name = 'entire';
2398 entireInput.type = 'hidden';
2399 entireInput.value = 'index';
2400 document.MassUpdate.appendChild(entireInput);
2401 //confirm(no_record_txt);
2402 if(document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'Users' && (document.MassUpdate.is_admin.value!='' || document.MassUpdate.status.value!='')) {
2403 alert(SUGAR.language.get('Users','LBL_LAST_ADMIN_NOTICE'));
2409 if(!sugarListView.confirm_action(del))
2413 var deleteInput = document.createElement('input');
2414 deleteInput.name = 'Delete';
2415 deleteInput.type = 'hidden';
2416 deleteInput.value = true;
2417 document.MassUpdate.appendChild(deleteInput);
2418 if(document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'EmailTemplates') {
2419 check_used_email_templates();
2425 document.MassUpdate.submit();
2430 sugarListView.prototype.clear_all = function() {
2431 document.MassUpdate.uid.value = '';
2432 document.MassUpdate.select_entire_list.value = 0;
2433 sugarListView.check_all(document.MassUpdate, 'mass[]', false);
2434 document.MassUpdate.massall.checked = false;
2435 document.MassUpdate.massall.disabled = false;
2436 sugarListView.update_count(0);
2439 sListView = new sugarListView();
2440 // -- end sugarListView class
2442 // format and unformat numbers
2443 function unformatNumber(n, num_grp_sep, dec_sep) {
2444 var x=unformatNumberNoParse(n, num_grp_sep, dec_sep);
2447 return parseFloat(x);
2452 function unformatNumberNoParse(n, num_grp_sep, dec_sep) {
2453 if(typeof num_grp_sep == 'undefined' || typeof dec_sep == 'undefined') return n;
2454 n = n ? n.toString() : '';
2457 if(num_grp_sep != '')
2459 num_grp_sep_re = new RegExp('\\'+num_grp_sep, 'g');
2460 n = n.replace(num_grp_sep_re, '');
2463 n = n.replace(dec_sep, '.');
2465 if(typeof CurrencySymbols != 'undefined') {
2466 // Need to strip out the currency symbols from the start.
2467 for ( var idx in CurrencySymbols ) {
2468 n = n.replace(CurrencySymbols[idx], '');
2476 // round parameter can be negative for decimal, precision has to be postive
2477 function formatNumber(n, num_grp_sep, dec_sep, round, precision) {
2478 if(typeof num_grp_sep == 'undefined' || typeof dec_sep == 'undefined') return n;
2479 n = n ? n.toString() : '';
2480 if(n.split) n = n.split('.');
2483 if(n.length > 2) return n.join('.'); // that's not a num!
2485 if(typeof round != 'undefined') {
2486 if(round > 0 && n.length > 1) { // round to decimal
2487 n[1] = parseFloat('0.' + n[1]);
2488 n[1] = Math.round(n[1] * Math.pow(10, round)) / Math.pow(10, round);
2489 n[1] = n[1].toString().split('.')[1];
2491 if(round <= 0) { // round to whole number
2492 n[0] = Math.round(parseInt(n[0],10) * Math.pow(10, round)) / Math.pow(10, round);
2497 if(typeof precision != 'undefined' && precision >= 0) {
2498 if(n.length > 1 && typeof n[1] != 'undefined') n[1] = n[1].substring(0, precision); // cut off precision
2500 if(n[1].length < precision) {
2501 for(var wp = n[1].length; wp < precision; wp++) n[1] += '0';
2505 regex = /(\d+)(\d{3})/;
2506 while(num_grp_sep != '' && regex.test(n[0])) n[0] = n[0].toString().replace(regex, '$1' + num_grp_sep + '$2');
2507 return n[0] + (n.length > 1 && n[1] != '' ? dec_sep + n[1] : '');
2510 // --- begin ajax status class
2511 SUGAR.ajaxStatusClass = function() {};
2512 SUGAR.ajaxStatusClass.prototype.statusDiv = null;
2513 SUGAR.ajaxStatusClass.prototype.oldOnScroll = null;
2514 SUGAR.ajaxStatusClass.prototype.shown = false; // state of the status window
2516 // reposition the status div, top and centered
2517 SUGAR.ajaxStatusClass.prototype.positionStatus = function() {
2518 this.statusDiv.style.top = document.body.scrollTop + 8 + 'px';
2519 statusDivRegion = YAHOO.util.Dom.getRegion(this.statusDiv);
2520 statusDivWidth = statusDivRegion.right - statusDivRegion.left;
2521 this.statusDiv.style.left = YAHOO.util.Dom.getViewportWidth() / 2 - statusDivWidth / 2 + 'px';
2524 // private func, create the status div
2525 SUGAR.ajaxStatusClass.prototype.createStatus = function(text) {
2526 statusDiv = document.createElement('div');
2527 statusDiv.className = 'dataLabel';
2528 statusDiv.id = 'ajaxStatusDiv';
2529 document.body.appendChild(statusDiv);
2530 this.statusDiv = document.getElementById('ajaxStatusDiv');
2533 // public - show the status div with text
2534 SUGAR.ajaxStatusClass.prototype.showStatus = function(text) {
2535 if(!this.statusDiv) {
2536 this.createStatus(text);
2539 this.statusDiv.style.display = '';
2541 this.statusDiv.style.zIndex = 20;
2542 this.statusDiv.innerHTML = ' <b>' + text + '</b> ';
2543 this.positionStatus();
2546 this.statusDiv.style.display = '';
2547 if(window.onscroll) this.oldOnScroll = window.onscroll; // save onScroll
2548 window.onscroll = this.positionStatus;
2553 SUGAR.ajaxStatusClass.prototype.hideStatus = function(text) {
2554 if(!this.shown) return;
2556 if(this.oldOnScroll) window.onscroll = this.oldOnScroll;
2557 else window.onscroll = '';
2558 this.statusDiv.style.display = 'none';
2561 SUGAR.ajaxStatusClass.prototype.flashStatus = function(text, time){
2562 this.showStatus(text);
2563 window.setTimeout('ajaxStatus.hideStatus();', time);
2567 var ajaxStatus = new SUGAR.ajaxStatusClass();
2568 // --- end ajax status class
2571 * Unified Search Advanced - for global search
2573 SUGAR.unifiedSearchAdvanced = function() {
2583 SUGAR.unifiedSearchAdvanced.usa_div = document.getElementById('unified_search_advanced_div');
2584 SUGAR.unifiedSearchAdvanced.usa_img = document.getElementById('unified_search_advanced_img');
2586 if(!SUGAR.unifiedSearchAdvanced.usa_div || !SUGAR.unifiedSearchAdvanced.usa_img) return;
2587 var attributes = { height: { to: 300 } };
2588 SUGAR.unifiedSearchAdvanced.anim_open = new YAHOO.util.Anim('unified_search_advanced_div', attributes );
2589 SUGAR.unifiedSearchAdvanced.anim_open.duration = 0.75;
2590 SUGAR.unifiedSearchAdvanced.anim_close = new YAHOO.util.Anim('unified_search_advanced_div', { height: {to: 0} } );
2591 SUGAR.unifiedSearchAdvanced.anim_close.duration = 0.75;
2592 //SUGAR.unifiedSearchAdvanced.anim_close.onComplete.subscribe(function() {SUGAR.unifiedSearchAdvanced.usa_div.style.display = 'none'});
2594 SUGAR.unifiedSearchAdvanced.usa_img._x = YAHOO.util.Dom.getX(SUGAR.unifiedSearchAdvanced.usa_img);
2595 SUGAR.unifiedSearchAdvanced.usa_img._y = YAHOO.util.Dom.getY(SUGAR.unifiedSearchAdvanced.usa_img);
2598 SUGAR.unifiedSearchAdvanced.usa_open = false;
2599 SUGAR.unifiedSearchAdvanced.usa_content = null;
2601 YAHOO.util.Event.addListener('unified_search_advanced_img', 'click', SUGAR.unifiedSearchAdvanced.get_content);
2604 get_content: function(e)
2606 query_string = trim(document.getElementById('query_string').value);
2607 if(query_string != '')
2609 window.location.href = 'index.php?module=Home&action=UnifiedSearch&query_string=' + query_string;
2611 window.location.href = 'index.php?module=Home&action=UnifiedSearch&form_only=true';
2615 animate: function(data) {
2616 ajaxStatus.hideStatus();
2619 SUGAR.unifiedSearchAdvanced.usa_content = data.responseText;
2620 SUGAR.unifiedSearchAdvanced.usa_div.innerHTML = SUGAR.unifiedSearchAdvanced.usa_content;
2622 if(SUGAR.unifiedSearchAdvanced.usa_open) {
2623 document.UnifiedSearch.advanced.value = 'false';
2624 SUGAR.unifiedSearchAdvanced.anim_close.animate();
2627 document.UnifiedSearch.advanced.value = 'true';
2628 SUGAR.unifiedSearchAdvanced.usa_div.style.display = '';
2629 YAHOO.util.Dom.setX(SUGAR.unifiedSearchAdvanced.usa_div, SUGAR.unifiedSearchAdvanced.usa_img._x - 90);
2630 YAHOO.util.Dom.setY(SUGAR.unifiedSearchAdvanced.usa_div, SUGAR.unifiedSearchAdvanced.usa_img._y + 15);
2631 SUGAR.unifiedSearchAdvanced.anim_open.animate();
2633 SUGAR.unifiedSearchAdvanced.usa_open = !SUGAR.unifiedSearchAdvanced.usa_open;
2638 checkUsaAdvanced: function() {
2639 if(document.UnifiedSearch.advanced.value == 'true') {
2640 document.UnifiedSearchAdvanced.query_string.value = document.UnifiedSearch.query_string.value;
2641 document.UnifiedSearchAdvanced.submit();
2648 if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.unifiedSearchAdvanced.init);
2653 * Toggles the header
2655 toggleHeader : function() {
2656 var h = document.getElementById('header');
2660 if(h.style.display == 'none') {
2661 h.style.display = '';
2663 h.style.display = 'none';
2667 alert(SUGAR.language.get("app_strings", "ERR_NO_HEADER_ID"));
2674 * General Sugar Utils
2676 SUGAR.util = function () {
2677 var additionalDetailsCache;
2678 var additionalDetailsCalls;
2679 var additionalDetailsRpcCall;
2682 getAndRemove : function (el) {
2683 if (YAHOO && YAHOO.util && YAHOO.util.Dom)
2684 el = YAHOO.util.Dom.get(el);
2685 else if (typeof (el) == "string")
2686 el = document.getElementById(el);
2687 if (el && el.parentNode)
2688 el.parentNode.removeChild(el);
2692 paramsToUrl : function (params) {
2695 url += i + "=" + params[i] + "&";
2699 evalScript:function(text){
2701 var waitUntilLoaded = function(){
2702 SUGAR.evalScript_waitCount--;
2703 if (SUGAR.evalScript_waitCount == 0) {
2704 var headElem = document.getElementsByTagName('head')[0];
2705 for ( var i = 0; i < SUGAR.evalScript_evalElem.length; i++) {
2706 var tmpElem = document.createElement('script');
2707 tmpElem.type = 'text/javascript';
2708 tmpElem.text = SUGAR.evalScript_evalElem[i];
2709 headElem.appendChild(tmpElem);
2714 var tmpElem = document.createElement('div');
2715 tmpElem.innerHTML = text;
2716 var results = tmpElem.getElementsByTagName('script');
2717 if (results == null) {
2718 // No scripts found, bail out
2722 var headElem = document.getElementsByTagName('head')[0];
2724 SUGAR.evalScript_waitCount = 0;
2725 SUGAR.evalScript_evalElem = new Array();
2726 for (var i = 0; i < results.length; i++) {
2727 if (typeof(results[i]) != 'object') {
2730 tmpElem = document.createElement('script');
2731 tmpElem.type = 'text/javascript';
2732 if (results[i].src != null && results[i].src != '') {
2733 tmpElem.src = results[i].src;
2735 // Need to defer execution of these scripts until the
2736 // required javascript files are fully loaded
2737 SUGAR.evalScript_evalElem[SUGAR.evalScript_evalElem.length] = results[i].text;
2740 tmpElem.addEventListener('load', waitUntilLoaded);
2741 SUGAR.evalScript_waitCount++;
2742 headElem.appendChild(tmpElem);
2744 // Add some code to handle pages without any external scripts
2745 SUGAR.evalScript_waitCount++;
2748 // Don't try and process things the IE way
2752 var objRegex = /<\s*script([^>]*)>((.|\s|\v|\0)*?)<\s*\/script\s*>/igm;
2754 var result = objRegex.exec(text);
2755 while(result && result.index > lastIndex){
2756 lastIndex = result.index
2758 var script = document.createElement('script');
2759 script.type= 'text/javascript';
2760 if(result[1].indexOf("src=") > -1){
2761 var srcRegex = /.*src=['"]([a-zA-Z0-9_\&\/\.\?=:]*)['"].*/igm;
2762 var srcResult = result[1].replace(srcRegex, '$1');
2763 script.src = srcResult;
2765 script.text = result[2];
2767 document.body.appendChild(script)
2772 result = objRegex.exec(text);
2776 * Gets the sidebar object
2777 * @return object pointer to the sidebar element
2779 getLeftColObj: function() {
2780 leftColObj = document.getElementById('leftCol');
2781 while(leftColObj.nodeName != 'TABLE') {
2782 leftColObj = leftColObj.firstChild;
2784 leftColTable = leftColObj;
2785 leftColTd = leftColTable.getElementsByTagName('td')[0];
2786 leftColTdRegion = YAHOO.util.Dom.getRegion(leftColTd);
2787 leftColTd.style.width = (leftColTdRegion.right - leftColTdRegion.left) + 'px';
2792 * Fills the shortcut menu placeholders w/ actual content
2793 * Call this on load event
2795 * @param shortcutContent Array array of content to fill in
2797 fillShortcuts: function(e, shortcutContent) {
2800 // don't do this if leftCol isn't available
2801 if (document.getElementById('leftCol') == undefined) { return; }
2803 spans = document.getElementById('leftCol').getElementsByTagName('span');
2804 hideCol = document.getElementById('HideMenu').getElementsByTagName('span');
2805 w = spans.length + 1;
2807 spans[w] = hideCol[i];
2810 for(je in shortcutContent) {
2812 if(typeof spans[wp].innerHTML != 'undefined' && spans[wp].innerHTML == ('wp_shortcut_fill_' + je)) {
2813 if(typeof spans[wp].parentNode.parentNode == 'object') {
2814 if(typeof spans[wp].parentNode.parentNode.onclick != 'undefined') {
2815 spans[wp].parentNode.parentNode.onclick = null;
2817 // If the wp_shortcut span is contained by an A tag, replace the A with a DIV.
2818 if(spans[wp].parentNode.tagName == 'A' && !isIE) {
2819 var newDiv = document.createElement('DIV');
2820 var parentAnchor = spans[wp].parentNode;
2822 spans[wp].parentNode.parentNode.style.display = 'none';
2824 // Copy styles over to the new container div
2825 if(window.getComputedStyle) {
2826 var parentStyle = window.getComputedStyle(parentAnchor, '');
2827 for(var styleName in parentStyle) {
2828 if(typeof parentStyle[styleName] != 'function'
2829 && styleName != 'display'
2830 && styleName != 'borderWidth'
2831 && styleName != 'visibility') {
2833 newDiv.style[styleName] = parentStyle[styleName];
2835 // Catches .length and .parentRule, and others
2841 // Replace the A with the DIV
2842 newDiv.appendChild(spans[wp]);
2843 parentAnchor.parentNode.replaceChild(newDiv, parentAnchor);
2845 spans[wp].parentNode.parentNode.style.display = '';
2848 spans[wp].innerHTML = shortcutContent[je]; // fill w/ content
2849 if(spans[wp].style) spans[wp].style.display = '';
2855 * Make an AJAX request.
2857 * @param url string resource to load
2858 * @param theDiv string id of element to insert loaded data into
2859 * @param postForm string if set, a POST request will be made to resource specified by url using the form named by postForm
2860 * @param callback string name of function to invoke after HTTP response is recieved
2861 * @param callbackParam any parameter to pass to callback when invoked
2862 * @param appendMode bool if true, HTTP response will be appended to the contents of theDiv, or else contents will be overriten.
2864 retrieveAndFill: function(url, theDiv, postForm, callback, callbackParam, appendMode) {
2865 if(typeof theDiv == 'string') {
2867 theDiv = document.getElementById(theDiv);
2874 var success = function(data) {
2875 if (typeof theDiv != 'undefined' && theDiv != null)
2878 if (typeof appendMode != 'undefined' && appendMode)
2880 theDiv.innerHTML += data.responseText;
2884 theDiv.innerHTML = data.responseText;
2891 if (typeof callback != 'undefined' && callback != null) callback(callbackParam);
2894 if(typeof postForm == 'undefined' || postForm == null) {
2895 var cObj = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
2898 YAHOO.util.Connect.setForm(postForm);
2899 var cObj = YAHOO.util.Connect.asyncRequest('POST', url, {success: success, failure: success});
2902 checkMaxLength: function() { // modified from http://www.quirksmode.org/dom/maxlength.html
2903 var maxLength = this.getAttribute('maxlength');
2904 var currentLength = this.value.length;
2905 if (currentLength > maxLength) {
2906 this.value = this.value.substring(0, maxLength);
2911 * Adds maxlength attribute to textareas
2913 setMaxLength: function() { // modified from http://www.quirksmode.org/dom/maxlength.html
2914 var x = document.getElementsByTagName('textarea');
2915 for (var i=0;i<x.length;i++) {
2916 if (x[i].getAttribute('maxlength')) {
2917 x[i].onkeyup = x[i].onchange = SUGAR.util.checkMaxLength;
2924 * Retrieves additional details dynamically
2926 getAdditionalDetails: function(bean, id, spanId) {
2928 oReturn = function(body, caption, width, theme) {
2929 var _refx = 25-width;
2930 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);
2933 success = function(data) {
2934 eval(data.responseText);
2936 SUGAR.util.additionalDetailsCache[spanId] = new Array();
2937 SUGAR.util.additionalDetailsCache[spanId]['body'] = result['body'];
2938 SUGAR.util.additionalDetailsCache[spanId]['caption'] = result['caption'];
2939 SUGAR.util.additionalDetailsCache[spanId]['width'] = result['width'];
2940 SUGAR.util.additionalDetailsCache[spanId]['theme'] = result['theme'];
2941 ajaxStatus.hideStatus();
2942 return oReturn(SUGAR.util.additionalDetailsCache[spanId]['body'], SUGAR.util.additionalDetailsCache[spanId]['caption'], SUGAR.util.additionalDetailsCache[spanId]['width'], SUGAR.util.additionalDetailsCache[spanId]['theme']);
2945 if(typeof SUGAR.util.additionalDetailsCache[spanId] != 'undefined')
2946 return oReturn(SUGAR.util.additionalDetailsCache[spanId]['body'], SUGAR.util.additionalDetailsCache[spanId]['caption'], SUGAR.util.additionalDetailsCache[spanId]['width'], SUGAR.util.additionalDetailsCache[spanId]['theme']);
2948 if(typeof SUGAR.util.additionalDetailsCalls[spanId] != 'undefined') // call already in progress
2950 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_LOADING'));
2951 url = 'index.php?to_pdf=1&module=Home&action=AdditionalDetailsRetrieve&bean=' + bean + '&id=' + id;
2952 SUGAR.util.additionalDetailsCalls[spanId] = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
2956 SUGAR.util.additionalDetailsRpcCall = window.setTimeout('go()', 250);
2958 clearAdditionalDetailsCall: function() {
2959 if(typeof SUGAR.util.additionalDetailsRpcCall == 'number') window.clearTimeout(SUGAR.util.additionalDetailsRpcCall);
2962 * A function that extends functionality from parent to child.
2964 extend : function(subc, superc, overrides) {
2965 subc.prototype = new superc; // set the superclass
2968 for (var i in overrides) subc.prototype[i] = overrides[i];
2971 hrefURL : function(url) {
2973 // IE needs special treatment since otherwise it would not pass Referer
2974 var trampoline = document.createElement('a');
2975 trampoline.href = url;
2976 document.body.appendChild(trampoline);
2978 document.body.removeChild(trampoline);
2980 document.location.href = url;
2984 openWindow : function(URL, windowName, windowFeatures) {
2986 // IE needs special treatment since otherwise it would not pass Referer
2987 win = window.open('', windowName, windowFeatures);
2988 var trampoline = document.createElement('a');
2989 trampoline.href = URL;
2990 trampoline.target = windowName;
2991 document.body.appendChild(trampoline);
2993 document.body.removeChild(trampoline);
2995 win = window.open(URL, windowName, windowFeatures);
3001 SUGAR.util.additionalDetailsCache = new Array();
3002 SUGAR.util.additionalDetailsCalls = new Array();
3003 if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.util.setMaxLength); // allow textareas to obey maxlength attrib
3005 SUGAR.savedViews = function() {
3006 var selectedOrderBy;
3007 var selectedSortOrder;
3010 var columnsMeta; // meta data for the display columns
3013 setChooser: function() {
3015 var displayColumnsDef = new Array();
3016 var hideTabsDef = new Array();
3018 var left_td = document.getElementById('display_tabs_td');
3019 if(typeof left_td == 'undefined' || left_td == null) return; // abort!
3020 var right_td = document.getElementById('hide_tabs_td');
3022 var displayTabs = left_td.getElementsByTagName('select')[0];
3023 var hideTabs = right_td.getElementsByTagName('select')[0];
3025 for(i = 0; i < displayTabs.options.length; i++) {
3026 displayColumnsDef.push(displayTabs.options[i].value);
3029 if(typeof hideTabs != 'undefined') {
3030 for(i = 0; i < hideTabs.options.length; i++) {
3031 hideTabsDef.push(hideTabs.options[i].value);
3034 if (!SUGAR.savedViews.clearColumns)
3035 document.getElementById('displayColumnsDef').value = displayColumnsDef.join('|');
3036 document.getElementById('hideTabsDef').value = hideTabsDef.join('|');
3039 select: function(saved_search_select) {
3040 for(var wp = 0; wp < document.search_form.saved_search_select.options.length; wp++) {
3041 if(typeof document.search_form.saved_search_select.options[wp].value != 'undefined' &&
3042 document.search_form.saved_search_select.options[wp].value == saved_search_select) {
3043 document.search_form.saved_search_select.selectedIndex = wp;
3044 document.search_form.ss_delete.style.display = '';
3045 document.search_form.ss_update.style.display = '';
3049 saved_search_action: function(action, delete_lang) {
3050 if(action == 'delete') {
3051 if(!confirm(delete_lang)) return;
3053 if(action == 'save') {
3054 if(document.search_form.saved_search_name.value.replace(/^\s*|\s*$/g, '') == '') {
3055 alert(SUGAR.language.get('app_strings', 'LBL_SAVED_SEARCH_ERROR'));
3060 // This check is needed for the Activities module (Calls/Meetings/Tasks).
3061 if (document.search_form.saved_search_action)
3063 document.search_form.saved_search_action.value = action;
3064 document.search_form.search_module.value = document.search_form.module.value;
3065 document.search_form.module.value = 'SavedSearch';
3066 // Bug 31922 - Make sure to specify that we want to hit the index view here of
3067 // the SavedSearch module, since the ListView doesn't have the logic to save the
3068 // search and redirect back
3069 document.search_form.action.value = 'index';
3071 document.search_form.submit();
3073 shortcut_select: function(selectBox, module) {
3075 selecturl = 'index.php?module=SavedSearch&search_module=' + module + '&action=index&saved_search_select=' + selectBox.options[selectBox.selectedIndex].value
3076 //add searchFormTab to url if it is available. This determines what tab to render
3077 if(typeof(document.getElementById('searchFormTab'))!='undefined'){
3078 selecturl = selecturl + '&searchFormTab=' + document.search_form.searchFormTab.value;
3080 //add showSSDIV to url if it is available. This determines whether saved search sub form should
3081 //be rendered open or not
3082 if(document.getElementById('showSSDIV') && typeof(document.getElementById('showSSDIV') !='undefined')){
3083 selecturl = selecturl + '&showSSDIV='+document.getElementById('showSSDIV').value;
3085 //use created url to navigate
3086 document.location.href = selecturl;
3088 handleForm: function() {
3089 SUGAR.tabChooser.movementCallback = function(left_side, right_side) {
3090 while(document.getElementById('orderBySelect').childNodes.length != 0) { // clear out order by options
3091 document.getElementById('orderBySelect').removeChild(document.getElementById('orderBySelect').lastChild);
3094 var selectedIndex = 0;
3095 var nodeCount = -1; // need this because the counter i also includes "undefined" nodes
3096 // which was breaking Calls and Meetings
3098 for(i in left_side.childNodes) { // fill in order by options
3099 if(typeof left_side.childNodes[i].nodeName != 'undefined' &&
3100 left_side.childNodes[i].nodeName.toLowerCase() == 'option' &&
3101 typeof SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value] != 'undefined' && // check if column is sortable
3102 typeof SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value]['sortable'] == 'undefined' &&
3103 SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value]['sortable'] != false) {
3105 optionNode = document.createElement('option');
3106 optionNode.value = left_side.childNodes[i].value;
3107 optionNode.innerHTML = left_side.childNodes[i].innerHTML;
3108 document.getElementById('orderBySelect').appendChild(optionNode);
3109 if(optionNode.value == SUGAR.savedViews.selectedOrderBy)
3110 selectedIndex = nodeCount;
3113 // Firefox needs this to be set after all the option nodes are created.
3114 document.getElementById('orderBySelect').selectedIndex = selectedIndex;
3116 SUGAR.tabChooser.movementCallback(document.getElementById('display_tabs_td').getElementsByTagName('select')[0]);
3118 // This check is needed for the Activities module (Calls/Meetings/Tasks).
3119 if (document.search_form.orderBy)
3120 document.search_form.orderBy.options.value = SUGAR.savedViews.selectedOrderBy;
3123 if(SUGAR.savedViews.selectedSortOrder == 'DESC') document.getElementById('sort_order_desc_radio').checked = true;
3124 else document.getElementById('sort_order_asc_radio').checked = true;
3129 SUGAR.searchForm = function() {
3132 // searchForm tab selector util
3133 searchFormSelect: function(view, previousView) {
3134 var module = view.split('|')[0];
3135 var theView = view.split('|')[1];
3137 var handleDisplay = function() { // hide other divs
3138 document.search_form.searchFormTab.value = theView;
3139 patt = module+"(.*)SearchForm$";
3140 divId=document.search_form.getElementsByTagName('div');
3141 // Hide all the search forms and retrive the name of the previous search tab (useful for the first load because previousView is empty)
3142 for (i=0;i<divId.length;i++){
3143 if(divId[i].id.match(module)==module){
3144 if(divId[i].id.match('SearchForm')=='SearchForm'){
3145 if(document.getElementById(divId[i].id).style.display == ''){
3146 previousTab=divId[i].id.match(patt)[1];
3148 document.getElementById(divId[i].id).style.display = 'none';
3152 // show the good search form.
3153 document.getElementById(module + theView + 'SearchForm').style.display = '';
3154 //if its not the first tab show there is a previous tab.
3156 thepreviousView=previousView.split('|')[1];
3159 thepreviousView=previousTab;
3161 thepreviousView=thepreviousView.replace(/_search/, "");
3162 // Process to retrieve the completed field from one tab to an other.
3163 for(num in document.search_form.elements) {
3164 if(document.search_form.elements[num]) {
3165 el = document.search_form.elements[num];
3166 pattern="^(.*)_"+thepreviousView+"$";
3167 if(typeof el.type != 'undefined' && typeof el.name != 'undefined' && el.name.match(pattern)) {
3168 advanced_input_name = el.name.match(pattern)[1]; // strip
3169 advanced_input_name = advanced_input_name+"_"+theView.replace(/_search/, "");
3170 if(typeof document.search_form[advanced_input_name] != 'undefined') // if advanced input of same name exists
3171 SUGAR.searchForm.copyElement(advanced_input_name, el);
3177 // if tab is not cached
3178 if(document.getElementById(module + theView + 'SearchForm').innerHTML == '') {
3179 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_LOADING'));
3180 var success = function(data) {
3181 document.getElementById(module + theView + 'SearchForm').innerHTML = data.responseText;
3183 SUGAR.util.evalScript(data.responseText);
3184 // pass script variables to global scope
3185 if(theView == 'saved_views') {
3186 if(typeof columnsMeta != 'undefined') SUGAR.savedViews.columnsMeta = columnsMeta;
3187 if(typeof selectedOrderBy != 'undefined') SUGAR.savedViews.selectedOrderBy = selectedOrderBy;
3188 if(typeof selectedSortOrder != 'undefined') SUGAR.savedViews.selectedSortOrder = selectedSortOrder;
3193 ajaxStatus.hideStatus();
3195 url = 'index.php?module=' + module + '&action=index&search_form_only=true&to_pdf=true&search_form_view=' + theView;
3197 //check to see if tpl has been specified. If so then pass location through url string
3199 if(document.getElementById('search_tpl') !=null && typeof(document.getElementById('search_tpl')) != 'undefined'){
3200 tpl = document.getElementById('search_tpl').value;
3201 if(tpl != ''){url += '&search_tpl='+tpl;}
3204 if(theView == 'saved_views') // handle the tab chooser
3205 url += '&displayColumns=' + SUGAR.savedViews.displayColumns + '&hideTabs=' + SUGAR.savedViews.hideTabs + '&orderBy=' + SUGAR.savedViews.selectedOrderBy + '&sortOrder=' + SUGAR.savedViews.selectedSortOrder;
3207 var cObj = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
3209 else { // that form already retrieved
3214 // copies one input to another
3215 copyElement: function(inputName, copyFromElement) {
3216 switch(copyFromElement.type) {
3219 document.search_form[inputName].value = copyFromElement.value;
3223 // This function is here to clear the form, instead of "resubmitting it
3224 clear_form: function(form) {
3225 var elemList = form.elements;
3229 for( var i = 0; i < elemList.length ; i++ ) {
3231 if ( typeof(elem.type) == 'undefined' ) {
3235 elemType = elem.type.toLowerCase();
3237 if ( elemType == 'text' || elemType == 'textarea' || elemType == 'password' ) {
3240 else if ( elemType == 'select' || elemType == 'select-one' || elemType == 'select-multiple' ) {
3241 // We have, what I hope, is a select box, time to unselect all options
3242 var optionList = elem.options;
3243 for ( var ii = 0 ; ii < optionList.length ; ii++ ) {
3244 optionList[ii].selected = false;
3247 else if ( elemType == 'radio' || elemType == 'checkbox' ) {
3248 elem.checked = false;
3249 elem.selected = false;
3251 else if ( elemType == 'hidden' ) {
3252 // We only want to reset the hidden values that link to the select boxes.
3253 if ( ( elem.name.length > 3 && elem.name.substring(elem.name.length-3) == '_id' )
3254 || ((elem.name.length > 9) && (elem.name.substring(elem.name.length - 9) == '_id_basic'))
3255 || ( elem.name.length > 12 && elem.name.substring(elem.name.length-12) == '_id_advanced' ) ) {
3260 SUGAR.savedViews.clearColumns = true;
3264 // Code for the column/tab chooser used on homepage and in admin section
3265 SUGAR.tabChooser = function () {
3266 var object_refs = new Array();
3268 /* Describe certain transfers as invalid */
3271 movementCallback: function(left_side, right_side) {},
3272 orderCallback: function(left_side, right_side) {},
3274 freezeOptions: function(left_name, right_name, target) {
3275 if(!SUGAR.tabChooser.frozenOptions) { SUGAR.tabChooser.frozenOptions = []; }
3276 if(!SUGAR.tabChooser.frozenOptions[left_name]) { SUGAR.tabChooser.frozenOptions[left_name] = []; }
3277 if(!SUGAR.tabChooser.frozenOptions[left_name][right_name]) { SUGAR.tabChooser.frozenOptions[left_name][right_name] = []; }
3278 if(typeof target == 'array') {
3279 for(var i in target) {
3280 SUGAR.tabChooser.frozenOptions[left_name][right_name][target[i]] = true;
3283 SUGAR.tabChooser.frozenOptions[left_name][right_name][target] = true;
3287 buildSelectHTML: function(info) {
3288 var text = "<select";
3290 if(typeof (info['select']['size']) != 'undefined') {
3291 text +=" size=\""+ info['select']['size'] +"\"";
3294 if(typeof (info['select']['name']) != 'undefined') {
3295 text +=" name=\""+ info['select']['name'] +"\"";
3298 if(typeof (info['select']['style']) != 'undefined') {
3299 text +=" style=\""+ info['select']['style'] +"\"";
3302 if(typeof (info['select']['onchange']) != 'undefined') {
3303 text +=" onChange=\""+ info['select']['onchange'] +"\"";
3306 if(typeof (info['select']['multiple']) != 'undefined') {
3311 for(i=0; i<info['options'].length;i++) {
3312 option = info['options'][i];
3313 text += "<option value=\""+option['value']+"\" ";
3314 if ( typeof (option['selected']) != 'undefined' && option['selected']== true) {
3317 text += ">"+option['text']+"</option>";
3319 text += "</select>";
3323 left_to_right: function(left_name, right_name, left_size, right_size) {
3324 SUGAR.savedViews.clearColumns = false;
3325 var left_td = document.getElementById(left_name+'_td');
3326 var right_td = document.getElementById(right_name+'_td');
3328 var display_columns_ref = left_td.getElementsByTagName('select')[0];
3329 var hidden_columns_ref = right_td.getElementsByTagName('select')[0];
3331 var selected_left = new Array();
3332 var notselected_left = new Array();
3333 var notselected_right = new Array();
3335 var left_array = new Array();
3337 var frozen_options = SUGAR.tabChooser.frozenOptions;
3338 frozen_options = frozen_options && frozen_options[left_name] && frozen_options[left_name][right_name]?frozen_options[left_name][right_name]:[];
3340 // determine which options are selected in left
3341 for (i=0; i < display_columns_ref.options.length; i++)
3343 if ( display_columns_ref.options[i].selected == true && !frozen_options[display_columns_ref.options[i].value])
3345 selected_left[selected_left.length] = {text: display_columns_ref.options[i].text, value: display_columns_ref.options[i].value};
3349 notselected_left[notselected_left.length] = {text: display_columns_ref.options[i].text, value: display_columns_ref.options[i].value};
3354 for (i=0; i < hidden_columns_ref.options.length; i++)
3356 notselected_right[notselected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
3360 var left_select_html_info = new Object();
3361 var left_options = new Array();
3362 var left_select = new Object();
3364 left_select['name'] = left_name+'[]';
3365 left_select['id'] = left_name;
3366 left_select['size'] = left_size;
3367 left_select['multiple'] = 'true';
3369 var right_select_html_info = new Object();
3370 var right_options = new Array();
3371 var right_select = new Object();
3373 right_select['name'] = right_name+'[]';
3374 right_select['id'] = right_name;
3375 right_select['size'] = right_size;
3376 right_select['multiple'] = 'true';
3378 for (i = 0; i < notselected_right.length; i++) {
3379 right_options[right_options.length] = notselected_right[i];
3382 for (i = 0; i < selected_left.length; i++) {
3383 right_options[right_options.length] = selected_left[i];
3385 for (i = 0; i < notselected_left.length; i++) {
3386 left_options[left_options.length] = notselected_left[i];
3388 left_select_html_info['options'] = left_options;
3389 left_select_html_info['select'] = left_select;
3390 right_select_html_info['options'] = right_options;
3391 right_select_html_info['select'] = right_select;
3392 right_select_html_info['style'] = 'background: lightgrey';
3394 var left_html = this.buildSelectHTML(left_select_html_info);
3395 var right_html = this.buildSelectHTML(right_select_html_info);
3397 left_td.innerHTML = left_html;
3398 right_td.innerHTML = right_html;
3400 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3401 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3403 this.movementCallback(object_refs[left_name], object_refs[right_name]);
3409 right_to_left: function(left_name, right_name, left_size, right_size, max_left) {
3410 SUGAR.savedViews.clearColumns = false;
3411 var left_td = document.getElementById(left_name+'_td');
3412 var right_td = document.getElementById(right_name+'_td');
3414 var display_columns_ref = left_td.getElementsByTagName('select')[0];
3415 var hidden_columns_ref = right_td.getElementsByTagName('select')[0];
3417 var selected_right = new Array();
3418 var notselected_right = new Array();
3419 var notselected_left = new Array();
3421 var frozen_options = SUGAR.tabChooser.frozenOptions;
3422 frozen_options = SUGAR.tabChooser.frozenOptions && SUGAR.tabChooser.frozenOptions[right_name] && SUGAR.tabChooser.frozenOptions[right_name][left_name]?SUGAR.tabChooser.frozenOptions[right_name][left_name]:[];
3424 for (i=0; i < hidden_columns_ref.options.length; i++)
3426 if (hidden_columns_ref.options[i].selected == true && !frozen_options[hidden_columns_ref.options[i].value])
3428 selected_right[selected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
3432 notselected_right[notselected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
3437 if(max_left != '' && (display_columns_ref.length + selected_right.length) > max_left) {
3438 alert('Maximum of ' + max_left + ' columns can be displayed.');
3442 for (i=0; i < display_columns_ref.options.length; i++)
3444 notselected_left[notselected_left.length] = {text:display_columns_ref.options[i].text, value:display_columns_ref.options[i].value};
3448 var left_select_html_info = new Object();
3449 var left_options = new Array();
3450 var left_select = new Object();
3452 left_select['name'] = left_name+'[]';
3453 left_select['id'] = left_name;
3454 left_select['multiple'] = 'true';
3455 left_select['size'] = left_size;
3457 var right_select_html_info = new Object();
3458 var right_options = new Array();
3459 var right_select = new Object();
3461 right_select['name'] = right_name+ '[]';
3462 right_select['id'] = right_name;
3463 right_select['multiple'] = 'true';
3464 right_select['size'] = right_size;
3466 for (i = 0; i < notselected_left.length; i++) {
3467 left_options[left_options.length] = notselected_left[i];
3470 for (i = 0; i < selected_right.length; i++) {
3471 left_options[left_options.length] = selected_right[i];
3473 for (i = 0; i < notselected_right.length; i++) {
3474 right_options[right_options.length] = notselected_right[i];
3476 left_select_html_info['options'] = left_options;
3477 left_select_html_info['select'] = left_select;
3478 right_select_html_info['options'] = right_options;
3479 right_select_html_info['select'] = right_select;
3480 right_select_html_info['style'] = 'background: lightgrey';
3482 var left_html = this.buildSelectHTML(left_select_html_info);
3483 var right_html = this.buildSelectHTML(right_select_html_info);
3485 left_td.innerHTML = left_html;
3486 right_td.innerHTML = right_html;
3488 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3489 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3491 this.movementCallback(object_refs[left_name], object_refs[right_name]);
3496 up: function(name, left_name, right_name) {
3497 SUGAR.savedViews.clearColumns = false;
3498 var left_td = document.getElementById(left_name+'_td');
3499 var right_td = document.getElementById(right_name+'_td');
3500 var td = document.getElementById(name+'_td');
3501 var obj = td.getElementsByTagName('select')[0];
3502 obj = (typeof obj == "string") ? document.getElementById(obj) : obj;
3503 if (obj.tagName.toLowerCase() != "select" && obj.length < 2)
3505 var sel = new Array();
3507 for (i=0; i<obj.length; i++) {
3508 if (obj[i].selected == true) {
3509 sel[sel.length] = i;
3512 for (i=0; i < sel.length; i++) {
3513 if (sel[i] != 0 && !obj[sel[i]-1].selected) {
3514 var tmp = new Array(obj[sel[i]-1].text, obj[sel[i]-1].value);
3515 obj[sel[i]-1].text = obj[sel[i]].text;
3516 obj[sel[i]-1].value = obj[sel[i]].value;
3517 obj[sel[i]].text = tmp[0];
3518 obj[sel[i]].value = tmp[1];
3519 obj[sel[i]-1].selected = true;
3520 obj[sel[i]].selected = false;
3524 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3525 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3527 this.orderCallback(object_refs[left_name], object_refs[right_name]);
3532 down: function(name, left_name, right_name) {
3533 SUGAR.savedViews.clearColumns = false;
3534 var left_td = document.getElementById(left_name+'_td');
3535 var right_td = document.getElementById(right_name+'_td');
3536 var td = document.getElementById(name+'_td');
3537 var obj = td.getElementsByTagName('select')[0];
3538 if (obj.tagName.toLowerCase() != "select" && obj.length < 2)
3540 var sel = new Array();
3541 for (i=obj.length-1; i>-1; i--) {
3542 if (obj[i].selected == true) {
3543 sel[sel.length] = i;
3546 for (i=0; i < sel.length; i++) {
3547 if (sel[i] != obj.length-1 && !obj[sel[i]+1].selected) {
3548 var tmp = new Array(obj[sel[i]+1].text, obj[sel[i]+1].value);
3549 obj[sel[i]+1].text = obj[sel[i]].text;
3550 obj[sel[i]+1].value = obj[sel[i]].value;
3551 obj[sel[i]].text = tmp[0];
3552 obj[sel[i]].value = tmp[1];
3553 obj[sel[i]+1].selected = true;
3554 obj[sel[i]].selected = false;
3558 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3559 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3561 this.orderCallback(object_refs[left_name], object_refs[right_name]);
3566 }(); // end tabChooser
3568 SUGAR.language = function() {
3570 languages : new Array(),
3572 setLanguage: function(module, data) {
3573 if (!SUGAR.language.languages) {
3576 SUGAR.language.languages[module] = data;
3579 get: function(module, str) {
3580 if(typeof SUGAR.language.languages[module] == 'undefined' || typeof SUGAR.language.languages[module][str] == 'undefined')
3584 return SUGAR.language.languages[module][str];
3587 translate: function(module, str)
3589 text = this.get(module, str);
3590 return text != 'undefined' ? text : this.get('app_strings', str);
3595 SUGAR.contextMenu = function() {
3597 objects: new Object(),
3598 objectTypes: new Object(),
3600 * Registers a new object for the context menu.
3601 * objectType - name of the type
3603 * metaData - metaData to pass to the action function
3605 registerObject: function(objectType, id, metaData) {
3606 SUGAR.contextMenu.objects[id] = new Object();
3607 SUGAR.contextMenu.objects[id] = {'objectType' : objectType, 'metaData' : metaData};
3610 * Registers a new object type
3611 * name - name of the type
3612 * menuItems - array of menu items
3614 registerObjectType: function(name, menuItems) {
3615 SUGAR.contextMenu.objectTypes[name] = new Object();
3616 SUGAR.contextMenu.objectTypes[name] = {'menuItems' : menuItems, 'objects' : new Array()};
3619 * Determines which menu item was clicked
3621 getListItemFromEventTarget: function(p_oNode) {
3623 if(p_oNode.tagName == "LI") {
3628 if(p_oNode.tagName == "LI") {
3633 } while((p_oNode = p_oNode.parentNode));
3638 * handles movement within context menu
3640 onContextMenuMove: function() {
3641 var oNode = this.contextEventTarget;
3642 var bDisabled = (oNode.tagName == "UL");
3643 var i = this.getItemGroups()[0].length - 1;
3645 this.getItem(i).cfg.setProperty("disabled", bDisabled);
3650 * handles clicks on a context menu ITEM
3652 onContextMenuItemClick: function(p_sType, p_aArguments, p_oItem) {
3653 var oLI = SUGAR.contextMenu.getListItemFromEventTarget(this.parent.contextEventTarget);
3654 id = this.parent.contextEventTarget.parentNode.id; // id of the target
3655 funct = eval(SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[id]['objectType']]['menuItems'][this.index]['action']);
3656 funct(this.parent.contextEventTarget, SUGAR.contextMenu.objects[id]['metaData']);
3659 * Initializes all context menus registered
3662 for(var i in SUGAR.contextMenu.objects) { // make a variable called objects in objectTypes containg references to all triggers
3663 if(typeof SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'] == 'undefined')
3664 SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'] = new Array();
3665 SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'].push(document.getElementById(i));
3667 // register the menus
3668 for(var i in SUGAR.contextMenu.objectTypes) {
3669 var oContextMenu = new YAHOO.widget.ContextMenu(i, {'trigger': SUGAR.contextMenu.objectTypes[i]['objects']});
3670 var aMainMenuItems = SUGAR.contextMenu.objectTypes[i]['menuItems'];
3671 var nMainMenuItems = aMainMenuItems.length;
3673 for(var j = 0; j < nMainMenuItems; j++) {
3674 oMenuItem = new YAHOO.widget.ContextMenuItem(aMainMenuItems[j].text, { helptext: aMainMenuItems[j].helptext });
3675 oMenuItem.clickEvent.subscribe(SUGAR.contextMenu.onContextMenuItemClick, oMenuItem, true);
3676 oContextMenu.addItem(oMenuItem);
3678 // Add a "move" event handler to the context menu
3679 oContextMenu.moveEvent.subscribe(SUGAR.contextMenu.onContextMenuMove, oContextMenu, true);
3680 // Add a "keydown" event handler to the context menu
3681 oContextMenu.keyDownEvent.subscribe(SUGAR.contextMenu.onContextMenuItemClick, oContextMenu, true);
3682 // Render the context menu
3683 oContextMenu.render(document.body);
3689 SUGAR.contextMenu.actions = function() {
3692 * redirects to a new note with the clicked on object as the target
3694 createNote: function(itemClicked, metaData) {
3695 loc = 'index.php?module=Notes&action=EditView';
3696 for(i in metaData) {
3697 if(i == 'notes_parent_type') loc += '&parent_type=' + metaData[i];
3698 else if(i != 'module' && i != 'parent_type') loc += '&' + i + '=' + metaData[i];
3700 document.location = loc;
3703 * redirects to a new note with the clicked on object as the target
3705 scheduleMeeting: function(itemClicked, metaData) {
3706 loc = 'index.php?module=Meetings&action=EditView';
3707 for(i in metaData) {
3708 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3710 document.location = loc;
3713 * redirects to a new note with the clicked on object as the target
3715 scheduleCall: function(itemClicked, metaData) {
3716 loc = 'index.php?module=Calls&action=EditView';
3717 for(i in metaData) {
3718 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3720 document.location = loc;
3723 * redirects to a new contact with the clicked on object as the target
3725 createContact: function(itemClicked, metaData) {
3726 loc = 'index.php?module=Contacts&action=EditView';
3727 for(i in metaData) {
3728 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3730 document.location = loc;
3733 * redirects to a new task with the clicked on object as the target
3735 createTask: function(itemClicked, metaData) {
3736 loc = 'index.php?module=Tasks&action=EditView';
3737 for(i in metaData) {
3738 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3740 document.location = loc;
3743 * redirects to a new opportunity with the clicked on object as the target
3745 createOpportunity: function(itemClicked, metaData) {
3746 loc = 'index.php?module=Opportunities&action=EditView';
3747 for(i in metaData) {
3748 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3750 document.location = loc;
3753 * redirects to a new opportunity with the clicked on object as the target
3755 createCase: function(itemClicked, metaData) {
3756 loc = 'index.php?module=Cases&action=EditView';
3757 for(i in metaData) {
3758 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3760 document.location = loc;
3763 * handles add to favorites menu selection
3765 addToFavorites: function(itemClicked, metaData) {
3766 success = function(data) {
3768 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});
3773 //if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.contextMenu.init);
3775 // initially from popup_parent_helper.js
3776 var popup_request_data;
3779 function get_popup_request_data()
3781 return window.document.popup_request_data;
3784 function get_close_popup()
3786 return window.document.close_popup;
3789 function open_popup(module_name, width, height, initial_filter, close_popup, hide_clear_button, popup_request_data, popup_mode, create, metadata)
3791 if (typeof(popupCount) == "undefined" || popupCount == 0)
3794 // set the variables that the popup will pull from
3795 window.document.popup_request_data = popup_request_data;
3796 window.document.close_popup = close_popup;
3798 //globally changing width and height of standard pop up window from 600 x 400 to 800 x 800
3799 width = (width == 600) ? 800 : width;
3800 height = (height == 400) ? 800 : height;
3804 + 'module=' + module_name
3807 if (initial_filter != '') {
3808 URL += '&query=true' + initial_filter;
3809 // Bug 41891 - Popup Window Name
3810 popupName = initial_filter.replace(/[^a-z_0-9]+/ig, '_');
3811 windowName = module_name + '_popup_window' + popupName;
3813 windowName = module_name + '_popup_window' + popupCount;
3817 if (hide_clear_button) {
3818 URL += '&hide_clear_button=true';
3821 windowFeatures = 'width=' + width
3822 + ',height=' + height
3823 + ',resizable=1,scrollbars=1';
3825 if (popup_mode == '' && popup_mode == 'undefined') {
3826 popup_mode='single';
3828 URL+='&mode='+popup_mode;
3829 if (create == '' && create == 'undefined') {
3832 URL+='&create='+create;
3834 if (metadata != '' && metadata != 'undefined') {
3835 URL+='&metadata='+metadata;
3838 win = SUGAR.util.openWindow(URL, windowName, windowFeatures);
3842 // put the focus on the popup if the browser supports the focus() method
3846 win.popupCount = popupCount;
3852 * The reply data must be a JSON array structured with the following information:
3853 * 1) form name to populate
3854 * 2) associative array of input names to values for populating the form
3856 var from_popup_return = false;
3858 function set_return_basic(popup_reply_data,filter)
3860 var form_name = popup_reply_data.form_name;
3861 var name_to_value_array = popup_reply_data.name_to_value_array;
3862 for (var the_key in name_to_value_array)
3864 if(the_key == 'toJSON')
3868 else if(the_key.match(filter))
3870 var displayValue=name_to_value_array[the_key].replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');;
3871 // begin andopes change: support for enum fields (SELECT)
3872 if(window.document.forms[form_name] && window.document.forms[form_name].elements[the_key]) {
3873 if(window.document.forms[form_name].elements[the_key].tagName == 'SELECT') {
3874 var selectField = window.document.forms[form_name].elements[the_key];
3875 for(var i = 0; i < selectField.options.length; i++) {
3876 if(selectField.options[i].text == displayValue) {
3877 selectField.options[i].selected = true;
3882 window.document.forms[form_name].elements[the_key].value = displayValue;
3885 // end andopes change: support for enum fields (SELECT)
3890 function set_return(popup_reply_data)
3892 from_popup_return = true;
3893 var form_name = popup_reply_data.form_name;
3894 var name_to_value_array = popup_reply_data.name_to_value_array;
3895 if(typeof name_to_value_array != 'undefined' && name_to_value_array['account_id'])
3898 var label_data_str = '';
3899 var current_label_data_str = '';
3900 for (var the_key in name_to_value_array)
3902 if(the_key == 'toJSON')
3908 var displayValue=name_to_value_array[the_key].replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');
3909 if(window.document.forms[form_name] && document.getElementById(the_key+'_label') && !the_key.match(/account/)) {
3910 var data_label = document.getElementById(the_key+'_label').innerHTML.replace(/\n/gi,'');
3911 label_str += data_label + ' \n';
3912 label_data_str += data_label + ' ' + displayValue + '\n';
3913 if(window.document.forms[form_name].elements[the_key]) {
3914 current_label_data_str += data_label + ' ' + window.document.forms[form_name].elements[the_key].value +'\n';
3919 if(label_data_str != label_str && current_label_data_str != label_str){
3920 if(confirm(SUGAR.language.get('app_strings', 'NTC_OVERWRITE_ADDRESS_PHONE_CONFIRM') + '\n\n' + label_data_str))
3922 set_return_basic(popup_reply_data,/\S/);
3924 set_return_basic(popup_reply_data,/account/);
3926 }else if(label_data_str != label_str && current_label_data_str == label_str){
3927 set_return_basic(popup_reply_data,/\S/);
3928 }else if(label_data_str == label_str){
3929 set_return_basic(popup_reply_data,/account/);
3932 set_return_basic(popup_reply_data,/\S/);
3936 function set_return_and_save(popup_reply_data)
3938 var form_name = popup_reply_data.form_name;
3939 var name_to_value_array = popup_reply_data.name_to_value_array;
3941 for (var the_key in name_to_value_array)
3943 if(the_key == 'toJSON')
3949 window.document.forms[form_name].elements[the_key].value = name_to_value_array[the_key];
3953 window.document.forms[form_name].return_module.value = window.document.forms[form_name].module.value;
3954 window.document.forms[form_name].return_action.value = 'DetailView';
3955 window.document.forms[form_name].return_id.value = window.document.forms[form_name].record.value;
3956 window.document.forms[form_name].action.value = 'Save';
3957 window.document.forms[form_name].submit();
3961 * This is a helper function to construct the initial filter that can be
3962 * passed into the open_popup() function. It assumes that there is an
3963 * account_id and account_name field in the given form_name to use to
3964 * construct the intial filter string.
3966 function get_initial_filter_by_account(form_name)
3968 var account_id = window.document.forms[form_name].account_id.value;
3969 var account_name = escape(window.document.forms[form_name].account_name.value);
3970 var initial_filter = "&account_id=" + account_id + "&account_name=" + account_name;
3972 return initial_filter;
3974 // end code from popup_parent_helper.js
3976 // begin code for address copy
3978 * This is a function used by the Address widget that will fill
3979 * in the given array fields using the fromKey and toKey as a
3980 * prefix into the form objects HTML elements.
3982 * @param form The HTML form object to parse
3983 * @param fromKey The prefix of elements to copy from
3984 * @param toKey The prefix of elements to copy into
3985 * @return boolean true if successful, false otherwise
3987 function copyAddress(form, fromKey, toKey) {
3989 var elems = new Array("address_street", "address_city", "address_state", "address_postalcode", "address_country");
3990 var checkbox = document.getElementById(toKey + "_checkbox");
3992 if(typeof checkbox != "undefined") {
3993 if(!checkbox.checked) {
3995 t = toKey + "_" + elems[x];
3996 document.getElementById(t).removeAttribute('readonly');
4000 f = fromKey + "_" + elems[x];
4001 t = toKey + "_" + elems[x];
4003 document.getElementById(t).value = document.getElementById(f).value;
4004 document.getElementById(t).setAttribute('readonly', true);
4010 // end code for address copy
4013 * This function is used in Email Template Module.
4014 * It will check whether the template is used in Campaing->EmailMarketing.
4015 * If true, it will notify user.
4018 function check_deletable_EmailTemplate() {
4019 id = document.getElementsByName('record')[0].value;
4020 currentForm = document.getElementById('form');
4022 success:function(r) {
4023 if(r.responseText == 'true') {
4024 if(!confirm(SUGAR.language.get('app_strings','NTC_TEMPLATE_IS_USED'))) {
4028 if(!confirm(SUGAR.language.get('app_strings','NTC_DELETE_CONFIRMATION'))) {
4032 currentForm.return_module.value='EmailTemplates';
4033 currentForm.return_action.value='ListView';
4034 currentForm.action.value='Delete';
4035 currentForm.submit();
4038 url = "index.php?module=EmailTemplates&action=CheckDeletable&from=DetailView&to_pdf=1&record="+id;
4039 YAHOO.util.Connect.asyncRequest('POST',url, call_back,null);
4043 remove_upload_imagefile : function(field_name) {
4044 var field=document.getElementById('remove_imagefile_' + field_name);
4047 //enable the file upload button.
4048 var field=document.getElementById( field_name);
4049 field.style.display="";
4051 //hide the image and remove button.
4052 var field=document.getElementById('img_' + field_name);
4053 field.style.display="none";
4054 var field=document.getElementById('bt_remove_' + field_name);
4055 field.style.display="none";
4057 if(document.getElementById(field_name + '_duplicate')) {
4058 var field = document.getElementById(field_name + '_duplicate');
4063 confirm_imagefile : function(field_name) {
4064 var field=document.getElementById(field_name);
4065 var filename=field.value;
4066 var fileExtension = filename.substring(filename.lastIndexOf(".")+1);
4067 fileExtension = fileExtension.toLowerCase();
4068 if (fileExtension == "jpg" || fileExtension == "jpeg"
4069 || fileExtension == "gif" || fileExtension == "png" || fileExtension == "bmp"){
4074 alert(SUGAR.language.get('app_strings', 'LBL_UPLOAD_IMAGE_FILE_INVALID'));
4078 lightbox : function(image)
4080 if (typeof(SUGAR.image.lighboxWindow) == "undefined")
4081 SUGAR.image.lighboxWindow = new YAHOO.widget.SimpleDialog('sugarImageViewer', {
4084 id:'sugarMsgWindow',
4087 msg: "<img src='" + image + "'> </img>",
4090 SUGAR.image.lighboxWindow.setBody("<img src='" + image + "'> </img>");
4091 SUGAR.image.lighboxWindow.render(document.body);
4092 SUGAR.image.lighboxWindow.show();
4093 SUGAR.image.lighboxWindow.center()
4097 SUGAR.util.isTouchScreen = function()
4099 // first check if we have forced use of the touch enhanced interface
4100 if ( Get_Cookie("touchscreen") == '1' ) {
4104 // next check if we should use the touch interface with our device
4105 if ( (navigator.userAgent.match(/iPad/i) != null) ) {
4112 SUGAR.util.isLoginPage = function(content)
4114 //skip if this is packageManager screen
4115 if(SUGAR.util.isPackageManager()) {return false;}
4116 var loginPageStart = "<!DOCTYPE";
4117 if (content.substr(0, loginPageStart.length) == loginPageStart && content.indexOf("<html>") != -1 && content.indexOf("login_module") != -1) {
4118 window.location.href = window.location.protocol + window.location.pathname;
4123 SUGAR.util.isPackageManager=function(){
4124 if(typeof(document.the_form) !='undefined' && typeof(document.the_form.language_pack_escaped) !='undefined'){
4126 }else{return false;}
4129 SUGAR.util.ajaxCallInProgress = function(){
4130 return SUGAR_callsInProgress != 0;
4133 SUGAR.util.callOnChangeListers = function(field){
4134 var listeners = YAHOO.util.Event.getListeners(field, 'change');
4135 if (listeners != null) {
4136 for (var i = 0; i < listeners.length; i++) {
4137 var l = listeners[i];
4138 l.fn.call(l.scope ? l.scope : this, l.obj);
4143 SUGAR.util.closeActivityPanel = {
4144 show:function(module,id,new_status,viewType,parentContainerId){
4145 if (SUGAR.util.closeActivityPanel.panel)
4146 SUGAR.util.closeActivityPanel.panel.destroy();
4147 var singleModule = SUGAR.language.get("app_list_strings", "moduleListSingular")[module];
4148 singleModule = typeof(singleModule != 'undefined') ? singleModule.toLowerCase() : '';
4149 var closeText = SUGAR.language.get("app_strings", "LBL_CLOSE_ACTIVITY_CONFIRM").replace("#module#",singleModule);
4150 SUGAR.util.closeActivityPanel.panel =
4151 new YAHOO.widget.SimpleDialog("closeActivityDialog",
4158 constraintoviewport: true,
4159 buttons: [ { text:SUGAR.language.get("app_strings", "LBL_EMAIL_OK"), handler:function(){
4160 if (SUGAR.util.closeActivityPanel.panel)
4161 SUGAR.util.closeActivityPanel.panel.hide();
4163 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_SAVING'));
4164 var args = "action=save&id=" + id + "&record=" + id + "&status=" + new_status + "&module=" + module;
4165 // 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
4166 // TODO: Take id out and regression test. Left id in for now to not create any other unexpected problems
4167 //var args = "action=save&id=" + id + "&status=" + new_status + "&module=" + module;
4171 // 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.
4172 // So instead, we reload from a timeout
4173 window.setTimeout("window.location.reload(true);",0);
4175 argument:{'parentContainerId':parentContainerId}
4178 YAHOO.util.Connect.asyncRequest('POST', 'index.php', callback, args);
4180 }, isDefault:true },
4181 { text:SUGAR.language.get("app_strings", "LBL_EMAIL_CANCEL"), handler:function(){SUGAR.util.closeActivityPanel.panel.hide(); }} ]
4184 SUGAR.util.closeActivityPanel.panel.setHeader(SUGAR.language.get("app_strings", "LBL_CLOSE_ACTIVITY_HEADER"));
4185 SUGAR.util.closeActivityPanel.panel.render(document.body);
4186 SUGAR.util.closeActivityPanel.panel.show();
4190 SUGAR.util.setEmailPasswordDisplay = function(id, exists) {
4191 link = document.getElementById(id+'_link');
4192 pwd = document.getElementById(id);
4193 if(!pwd || !link) return;
4195 pwd.style.display = 'none';
4196 link.style.display = '';
4198 pwd.style.display = '';
4199 link.style.display = 'none';
4203 SUGAR.util.setEmailPasswordEdit = function(id) {
4204 link = document.getElementById(id+'_link');
4205 pwd = document.getElementById(id);
4206 if(!pwd || !link) return;
4207 pwd.style.display = '';
4208 link.style.display = 'none';
4212 * Compares a filename with a supplied array of allowed file extensions.
4213 * @param fileName string
4214 * @param allowedTypes array of allowed file extensions
4217 SUGAR.util.validateFileExt = function(fileName, allowedTypes) {
4218 var ext = fileName.split('.').pop();
4220 for (var i = allowedTypes.length; i > 0; i--) {
4221 if (ext === allowedTypes[i]) {