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 var raiseFlag = false;
610 if (typeof flash == "undefined")
613 inputHandle = typeof input == "object" ? input : document.forms[formname][input];
614 style = get_current_bgcolor(inputHandle);
616 // strip off the colon at the end of the warning strings
617 if ( txt.substring(txt.length-1) == ':' )
618 txt = txt.substring(0,txt.length-1)
620 // Bug 28249 - To help avoid duplicate messages for an element, strip off extra messages and
621 // match on the field name itself
622 requiredTxt = SUGAR.language.get('app_strings', 'ERR_MISSING_REQUIRED_FIELDS');
623 invalidTxt = SUGAR.language.get('app_strings', 'ERR_INVALID_VALUE');
624 nomatchTxt = SUGAR.language.get('app_strings', 'ERR_SQS_NO_MATCH_FIELD');
625 matchTxt = txt.replace(requiredTxt,'').replace(invalidTxt,'').replace(nomatchTxt,'');
627 YUI().use('node', function (Y) {
628 Y.one(inputHandle).get('parentNode').get('children').each(function(node, index, nodeList){
629 if(node.hasClass('validation-message') && node.get('text').search(matchTxt)){
636 errorTextNode = document.createElement('div');
637 errorTextNode.className = 'required validation-message';
638 errorTextNode.innerHTML = txt;
639 if ( inputHandle.parentNode.className.indexOf('x-form-field-wrap') != -1 ) {
640 inputHandle.parentNode.parentNode.appendChild(errorTextNode);
643 inputHandle.parentNode.appendChild(errorTextNode);
646 inputHandle.style.backgroundColor = "#FF0000";
647 inputsWithErrors.push(inputHandle);
651 // We only need to setup the flashy-flashy on the first entry, it loops through all fields automatically
652 if ( inputsWithErrors.length == 1 ) {
653 for(wp = 1; wp <= 10; wp++) {
654 window.setTimeout('fade_error_style(style, '+wp*10+')',1000+(wp*50));
657 if(typeof (window[formname + "_tabs"]) != "undefined") {
658 var tabView = window[formname + "_tabs"];
659 var parentDiv = YAHOO.util.Dom.getAncestorByTagName(inputHandle, "div");
661 var tabs = tabView.get("tabs");
662 for (var i in tabs) {
663 if (tabs[i].get("contentEl") == parentDiv
664 || YAHOO.util.Dom.isAncestor(tabs[i].get("contentEl"), inputHandle))
666 tabs[i].get("labelEl").style.color = "red";
667 if ( inputsWithErrors.length == 1 )
668 tabView.selectTab(i);
673 window.setTimeout("inputsWithErrors[" + (inputsWithErrors.length - 1) + "].style.backgroundColor = '';", 2000);
677 // Catch errors here so we don't allow an incomplete record through the javascript validation
683 * removes all error messages for the current form
685 function clear_all_errors() {
686 for(var wp = 0; wp < inputsWithErrors.length; wp++) {
687 if(typeof(inputsWithErrors[wp]) !='undefined' && typeof inputsWithErrors[wp].parentNode != 'undefined' && inputsWithErrors[wp].parentNode != null) {
688 if ( inputsWithErrors[wp].parentNode.className.indexOf('x-form-field-wrap') != -1 )
690 inputsWithErrors[wp].parentNode.parentNode.removeChild(inputsWithErrors[wp].parentNode.parentNode.lastChild);
694 inputsWithErrors[wp].parentNode.removeChild(inputsWithErrors[wp].parentNode.lastChild);
698 if (inputsWithErrors.length == 0) return;
700 if ( YAHOO.util.Dom.getAncestorByTagName(inputsWithErrors[0], "form") ) {
701 var formname = YAHOO.util.Dom.getAncestorByTagName(inputsWithErrors[0], "form").getAttribute("name");
702 if(typeof (window[formname + "_tabs"]) != "undefined") {
703 var tabView = window[formname + "_tabs"];
705 var tabs = tabView.get("tabs");
706 for (var i in tabs) {
707 tabs[i].get("labelEl").style.color = "";
711 inputsWithErrors = new Array();
715 function get_current_bgcolor(input) {
716 if(input.currentStyle) {// ie
717 style = input.currentStyle.backgroundColor;
718 return style.substring(1,7);
722 styleRGB = document.defaultView.getComputedStyle(input, '').getPropertyValue("background-color");
723 comma = styleRGB.indexOf(',');
724 style += dec2hex(styleRGB.substring(4, comma));
725 commaPrevious = comma;
726 comma = styleRGB.indexOf(',', commaPrevious+1);
727 style += dec2hex(styleRGB.substring(commaPrevious+2, comma));
728 style += dec2hex(styleRGB.substring(comma+2, styleRGB.lastIndexOf(')')));
733 function hex2dec(hex){return(parseInt(hex,16));}
734 var hexDigit=new Array("0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F");
735 function dec2hex(dec){return(hexDigit[dec>>4]+hexDigit[dec&15]);}
737 function fade_error_style(normalStyle, percent) {
738 errorStyle = 'c60c30';
739 var r1 = hex2dec(errorStyle.slice(0,2));
740 var g1 = hex2dec(errorStyle.slice(2,4));
741 var b1 = hex2dec(errorStyle.slice(4,6));
743 var r2 = hex2dec(normalStyle.slice(0,2));
744 var g2 = hex2dec(normalStyle.slice(2,4));
745 var b2 = hex2dec(normalStyle.slice(4,6));
748 var pc = percent / 100;
750 r= Math.floor(r1+(pc*(r2-r1)) + .5);
751 g= Math.floor(g1+(pc*(g2-g1)) + .5);
752 b= Math.floor(b1+(pc*(b2-b1)) + .5);
754 for(var wp = 0; wp < inputsWithErrors.length; wp++) {
755 inputsWithErrors[wp].style.backgroundColor = "#" + dec2hex(r) + dec2hex(g) + dec2hex(b);
759 function isFieldTypeExceptFromEmptyCheck(fieldType)
762 var exemptList = ['bool','file'];
763 for(var i=0;i<exemptList.length;i++)
765 if(fieldType == exemptList[i])
770 function validate_form(formname, startsWith){
771 requiredTxt = SUGAR.language.get('app_strings', 'ERR_MISSING_REQUIRED_FIELDS');
772 invalidTxt = SUGAR.language.get('app_strings', 'ERR_INVALID_VALUE');
774 if ( typeof (formname) == 'undefined')
778 if ( typeof (validate[formname]) == 'undefined')
780 disableOnUnloadEditView(document.forms[formname]);
784 var form = document.forms[formname];
787 var _date = new Date();
788 if(_date.getTime() < (lastSubmitTime + 2000) && startsWith == oldStartsWith) { // ignore submits for the next 2 seconds
791 lastSubmitTime = _date.getTime();
792 oldStartsWith = startsWith;
794 clear_all_errors(); // remove previous error messages
796 inputsWithErrors = new Array();
797 for(var i = 0; i < validate[formname].length; i++){
798 if(validate[formname][i][nameIndex].indexOf(startsWith) == 0){
799 if(typeof form[validate[formname][i][nameIndex]] != 'undefined'){
802 //If a field is not required and it is blank or is binarydependant, skip validation.
803 //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
804 if(!validate[formname][i][requiredIndex] && trim(form[validate[formname][i][nameIndex]].value) == '' && (typeof(validate[formname][i][jstypeIndex]) != 'undefined' && validate[formname][i][jstypeIndex] != 'binarydep'))
809 if(validate[formname][i][requiredIndex]
810 && !isFieldTypeExceptFromEmptyCheck(validate[formname][i][typeIndex])
812 if(typeof form[validate[formname][i][nameIndex]] == 'undefined' || trim(form[validate[formname][i][nameIndex]].value) == ""){
813 add_error_style(formname, validate[formname][i][nameIndex], requiredTxt +' ' + validate[formname][i][msgIndex]);
818 switch(validate[formname][i][typeIndex]){
820 if(!isValidEmail(trim(form[validate[formname][i][nameIndex]].value))){
822 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
826 if( !isTime(trim(form[validate[formname][i][nameIndex]].value))){
828 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
830 case 'date': if(!isDate(trim(form[validate[formname][i][nameIndex]].value))){
832 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
837 if(!isDBName(trim(form[validate[formname][i][nameIndex]].value))){
839 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
845 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 ) {
847 add_error_style(formname, validate[formname][i][nameIndex], requiredTxt + " " + validate[formname][i][msgIndex]);
851 if(!isInteger(trim(form[validate[formname][i][nameIndex]].value))){
853 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
857 if(!isDecimal(trim(form[validate[formname][i][nameIndex]].value))){
859 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
864 if(!isFloat(trim(form[validate[formname][i][nameIndex]].value))){
866 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
870 div_element_id = formname + '_' + form[validate[formname][i][nameIndex]].name + '_operation_div';
871 input_elements = YAHOO.util.Selector.query('input', document.getElementById(div_element_id));
872 primary_field_id = '';
873 validation_passed = false;
874 replace_selected = false;
876 //Loop through the option elements (replace or add currently)
877 for(t in input_elements) {
878 if(input_elements[t].type && input_elements[t].type == 'radio' && input_elements[t].checked == true && input_elements[t].value == 'replace') {
880 //Now find where the primary radio button is and if a value has been set
881 radio_elements = YAHOO.util.Selector.query('input[type=radio]', document.getElementById(formname + '_team_name_table'));
883 for(x in radio_elements) {
884 if(radio_elements[x].name != 'team_name_type') {
885 primary_field_id = 'team_name_collection_' + radio_elements[x].value;
886 if(radio_elements[x].checked) {
887 replace_selected = true;
888 if(trim(document.forms[formname].elements[primary_field_id].value) != '') {
889 validation_passed = true;
892 } else if(trim(document.forms[formname].elements[primary_field_id].value) != '') {
893 replace_selected = true;
900 if(replace_selected && !validation_passed) {
901 add_error_style(formname, primary_field_id, SUGAR.language.get('app_strings', 'ERR_NO_PRIMARY_TEAM_SPECIFIED'));
906 table_element_id = formname + '_' + form[validate[formname][i][nameIndex]].name + '_table';
907 if(document.getElementById(table_element_id)) {
908 input_elements = YAHOO.util.Selector.query('input[type=radio]', document.getElementById(table_element_id));
910 primary_field_id = form[validate[formname][i][nameIndex]].name + '_collection_0';
912 for(t in input_elements) {
913 primary_field_id = form[validate[formname][i][nameIndex]].name + '_collection_' + input_elements[t].value;
914 if(input_elements[t].type && input_elements[t].type == 'radio' && input_elements[t].checked == true) {
915 if(document.forms[formname].elements[primary_field_id].value != '') {
924 field_id = form[validate[formname][i][nameIndex]].name + '_collection_' + input_elements[0].value;
925 add_error_style(formname, field_id, SUGAR.language.get('app_strings', 'ERR_NO_PRIMARY_TEAM_SPECIFIED'));
931 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex]);
935 if(typeof validate[formname][i][jstypeIndex] != 'undefined'/* && !isError*/){
937 switch(validate[formname][i][jstypeIndex]){
939 if(!inRange(trim(form[validate[formname][i][nameIndex]].value), validate[formname][i][minIndex], validate[formname][i][maxIndex])){
941 var lbl_validate_range = SUGAR.language.get('app_strings', 'LBL_VALIDATE_RANGE');
942 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] + ") ");
946 compareTo = form[validate[formname][i][compareToIndex]];
947 if( typeof compareTo != 'undefined'){
948 if(trim(compareTo.value) != '' || (validate[formname][i][allowblank] != 'true') ) {
949 date2 = trim(compareTo.value);
950 date1 = trim(form[validate[formname][i][nameIndex]].value);
952 if(trim(date1).length != 0 && !isBefore(date1,date2)){
955 //jc:#12287 - adding translation for the is not before message
956 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex] + "(" + date1 + ") " + SUGAR.language.get('app_strings', 'MSG_IS_NOT_BEFORE') + ' ' +date2);
962 value=unformatNumber(trim(form[validate[formname][i][nameIndex]].value), num_grp_sep, dec_sep);
963 maximum = parseFloat(validate[formname][i][maxIndex]);
964 if( typeof maximum != 'undefined'){
967 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]);
972 value=unformatNumber(trim(form[validate[formname][i][nameIndex]].value), num_grp_sep, dec_sep);
973 minimum = parseFloat(validate[formname][i][minIndex]);
974 if( typeof minimum != 'undefined'){
977 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'));
982 compareTo = form[validate[formname][i][compareToIndex]];
983 if( typeof compareTo != 'undefined') {
984 item1 = trim(form[validate[formname][i][nameIndex]].value);
985 item2 = trim(compareTo.value);
986 if(!bothExist(item1, item2)) {
988 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex]);
993 compareTo = form[validate[formname][i][compareToIndex]];
994 if( typeof compareTo != 'undefined') {
995 item1 = trim(form[validate[formname][i][nameIndex]].value);
996 item2 = trim(compareTo.value);
997 if(!bothExist(item1, item2) || item1 != item2) {
999 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex]);
1004 arr = eval(validate[formname][i][arrIndex]);
1005 operator = validate[formname][i][operatorIndex];
1006 item1 = trim(form[validate[formname][i][nameIndex]].value);
1007 if (operator.charAt(0) == 'u') {
1008 item1 = item1.toUpperCase();
1009 operator = operator.substring(1);
1010 } else if (operator.charAt(0) == 'l') {
1011 item1 = item1.toLowerCase();
1012 operator = operator.substring(1);
1014 for(j = 0; j < arr.length; j++){
1016 if((operator == "==" && val == item1) || (operator == "!=" && val != item1)){
1018 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
1023 if(trim(form[validate[formname][i][nameIndex]].value) == 'false'){
1024 //Fake an error so form does not submit
1034 /* nsingh: BUG#15102
1035 Check min max default field logic.
1036 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.*/
1037 if(formsWithFieldLogic){
1038 var invalidLogic=false;
1039 if(formsWithFieldLogic.min && formsWithFieldLogic.max && formsWithFieldLogic._default) {
1040 var showErrorsOn={min:{value:'min', show:false, obj:formsWithFieldLogic.min.value},
1041 max:{value:'max',show:false, obj:formsWithFieldLogic.max.value},
1042 _default:{value:'default',show:false, obj:formsWithFieldLogic._default.value},
1043 len:{value:'len', show:false, obj:parseInt(formsWithFieldLogic.len.value,10)}};
1045 var min = (formsWithFieldLogic.min.value !='') ? parseFloat(formsWithFieldLogic.min.value) : 'undef';
1046 var max = (formsWithFieldLogic.max.value !='') ? parseFloat(formsWithFieldLogic.max.value) : 'undef';
1047 var _default = (formsWithFieldLogic._default.value!='')? parseFloat(formsWithFieldLogic._default.value) : 'undef';
1049 /*Check all lengths are <= max size.*/
1050 for(var i in showErrorsOn){
1051 if(showErrorsOn[i].value!='len' && showErrorsOn[i].obj.length > showErrorsOn.len.obj){
1053 showErrorsOn[i].show=true;
1054 showErrorsOn.len.show=true;
1058 if(min!='undef' && max!='undef' && _default!='undef'){
1059 if(!inRange(_default,min,max)){
1061 showErrorsOn.min.show=true;
1062 showErrorsOn.max.show=true;
1063 showErrorsOn._default.show=true;
1066 if(min!='undef' && max!= 'undef' && min > max){
1067 invalidLogic = true;
1068 showErrorsOn.min.show=true;
1069 showErrorsOn.max.show=true;
1071 if(min!='undef' && _default!='undef' && _default < min){
1073 invalidLogic = true;
1074 showErrorsOn.min.show=true;
1075 showErrorsOn._default.show=true;
1077 if(max!='undef' && _default !='undef' && _default>max){
1079 invalidLogic = true;
1080 showErrorsOn.max.show=true;
1081 showErrorsOn._default.show=true;
1086 for(var error in showErrorsOn)
1087 if(showErrorsOn[error].show)
1088 add_error_style(formname,showErrorsOn[error].value, formsWithFieldLogic.msg);
1093 formsWithFieldLogic = null;
1096 if(formWithPrecision){
1097 if (!isValidPrecision(formWithPrecision.float.value, formWithPrecision.precision.value)){
1099 add_error_style(formname, 'default', SUGAR.language.get('app_strings', 'ERR_COMPATIBLE_PRECISION_VALUE'));
1107 if (isError == true) {
1109 if (self.pageYOffset) // all except Explorer
1111 nwX = self.pageXOffset;
1112 seX = self.innerWidth;
1113 nwY = self.pageYOffset;
1114 seY = self.innerHeight;
1116 else if (document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
1118 nwX = document.documentElement.scrollLeft;
1119 seX = document.documentElement.clientWidth;
1120 nwY = document.documentElement.scrollTop;
1121 seY = document.documentElement.clientHeight;
1123 else if (document.body) // all other Explorers
1125 nwX = document.body.scrollLeft;
1126 seX = document.body.clientWidth;
1127 nwY = document.body.scrollTop;
1128 seY = document.body.clientHeight;
1131 var inView = true; // is there an error within viewport of browser
1132 for(var wp = 0; wp < inputsWithErrors.length; wp++) {
1133 var elementCoor = findElementPos(inputsWithErrors[wp]);
1134 if(!(elementCoor.x >= nwX && elementCoor.y >= nwY &&
1135 elementCoor.x <= seX && elementCoor.y <= seY)) { // if input is not within viewport
1137 scrollToTop = elementCoor.y - 75;
1138 scrollToLeft = elementCoor.x - 75;
1140 else { // on first input within viewport, don't scroll
1146 if(!inView) window.scrollTo(scrollToLeft,scrollToTop);
1151 disableOnUnloadEditView(form);
1158 * This array is used to remember mark status of rows in browse mode
1160 var marked_row = new Array;
1164 * Sets/unsets the pointer and marker in browse mode
1166 * @param object the table row
1167 * @param interger the row number
1168 * @param string the action calling this script (over, out or click)
1169 * @param string the default background color
1170 * @param string the color to use for mouseover
1171 * @param string the color to use for marking a row
1173 * @return boolean whether pointer is set or not
1175 function setPointer(theRow, theRowNum, theAction, theDefaultColor, thePointerColor, theMarkColor) {
1176 var theCells = null;
1178 // 1. Pointer and mark feature are disabled or the browser can't get the
1180 if ((thePointerColor == '' && theMarkColor == '')
1181 || typeof(theRow.style) == 'undefined') {
1185 // 2. Gets the current row and exits if the browser can't get it
1186 if (typeof(document.getElementsByTagName) != 'undefined') {
1187 theCells = theRow.getElementsByTagName('td');
1189 else if (typeof(theRow.cells) != 'undefined') {
1190 theCells = theRow.cells;
1196 // 3. Gets the current color...
1197 var rowCellsCnt = theCells.length;
1198 var domDetect = null;
1199 var currentColor = null;
1200 var newColor = null;
1201 // 3.1 ... with DOM compatible browsers except Opera that does not return
1202 // valid values with "getAttribute"
1203 if (typeof(window.opera) == 'undefined'
1204 && typeof(theCells[0].getAttribute) != 'undefined') {
1205 currentColor = theCells[0].getAttribute('bgcolor');
1208 // 3.2 ... with other browsers
1210 currentColor = theCells[0].style.backgroundColor;
1214 // 4. Defines the new color
1215 // 4.1 Current color is the default one
1216 if (currentColor == ''
1217 || (currentColor!= null && (currentColor.toLowerCase() == theDefaultColor.toLowerCase()))) {
1218 if (theAction == 'over' && thePointerColor != '') {
1219 newColor = thePointerColor;
1221 else if (theAction == 'click' && theMarkColor != '') {
1222 newColor = theMarkColor;
1223 marked_row[theRowNum] = true;
1226 // 4.1.2 Current color is the pointer one
1227 else if (currentColor!= null && (currentColor.toLowerCase() == thePointerColor.toLowerCase())
1228 && (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])) {
1229 if (theAction == 'out') {
1230 newColor = theDefaultColor;
1232 else if (theAction == 'click' && theMarkColor != '') {
1233 newColor = theMarkColor;
1234 marked_row[theRowNum] = true;
1237 // 4.1.3 Current color is the marker one
1238 else if (currentColor!= null && (currentColor.toLowerCase() == theMarkColor.toLowerCase())) {
1239 if (theAction == 'click') {
1240 newColor = (thePointerColor != '')
1243 marked_row[theRowNum] = (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])
1249 // 5. Sets the new color...
1252 // 5.1 ... with DOM compatible browsers except Opera
1254 for (c = 0; c < rowCellsCnt; c++) {
1255 theCells[c].setAttribute('bgcolor', newColor, 0);
1258 // 5.2 ... with other browsers
1260 for (c = 0; c < rowCellsCnt; c++) {
1261 theCells[c].style.backgroundColor = newColor;
1267 } // end of the 'setPointer()' function
1271 * listbox redirection
1273 function goToUrl(selObj, goToLocation) {
1274 eval("document.location.href = '" + goToLocation + "pos=" + selObj.options[selObj.selectedIndex].value + "'");
1279 var json_objects = new Object();
1281 function getXMLHTTPinstance() {
1282 var xmlhttp = false;
1283 var userAgent = navigator.userAgent.toLowerCase() ;
1285 // IE Check supports ActiveX controls
1286 if (userAgent.indexOf("msie") != -1 && userAgent.indexOf("mac") == -1 && userAgent.indexOf("opera") == -1) {
1287 var version = navigator.appVersion.match(/MSIE (.\..)/)[1] ;
1288 if(version >= 5.5 ) {
1290 xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
1294 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
1303 if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
1304 xmlhttp = new XMLHttpRequest();
1309 // NOW LOAD THE OBJECT..
1310 var global_xmlhttp = getXMLHTTPinstance();
1312 function http_fetch_sync(url,post_data) {
1313 global_xmlhttp = getXMLHTTPinstance();
1314 var method = (typeof(post_data) != 'undefined') ? 'POST' : 'GET';
1317 global_xmlhttp.open(method, url, false);
1320 alert('message:'+e.message+":url:"+url);
1322 if(method == 'POST') {
1323 global_xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
1326 global_xmlhttp.send(post_data);
1328 if (SUGAR.util.isLoginPage(global_xmlhttp.responseText))
1331 var args = {"responseText" : global_xmlhttp.responseText,
1332 "responseXML" : global_xmlhttp.responseXML,
1333 "request_id" : typeof(request_id) != "undefined" ? request_id : 0};
1337 // this is a GET unless post_data is defined
1339 function http_fetch_async(url,callback,request_id,post_data) {
1341 if(typeof(post_data) != 'undefined') {
1346 global_xmlhttp.open(method, url,true);
1349 alert('message:'+e.message+":url:"+url);
1351 if(method == 'POST') {
1352 global_xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
1354 global_xmlhttp.onreadystatechange = function() {
1355 if(global_xmlhttp.readyState==4) {
1356 if(global_xmlhttp.status == 200) {
1357 if (SUGAR.util.isLoginPage(global_xmlhttp.responseText))
1359 var args = {"responseText" : global_xmlhttp.responseText,
1360 "responseXML" : global_xmlhttp.responseXML,
1361 "request_id" : request_id };
1362 callback.call(document,args);
1365 alert("There was a problem retrieving the XML data:\n" + global_xmlhttp.statusText);
1369 global_xmlhttp.send(post_data);
1372 function insert_at_cursor(field, value) {
1374 if (document.selection) {
1376 sel = document.selection.createRange();
1380 else if(field.selectionStart || field.selectionStart == '0') {
1381 var start_pos = field.selectionStart;
1382 var end_pos = field.selectionEnd;
1383 field.value = field.value.substring(0, start_pos) + value + field.value.substring(end_pos, field.value.length);
1386 field.value += value;
1390 function checkParentType(type,button) {
1391 if(button == null) {
1394 if(typeof disabledModules != 'undefined' && typeof(disabledModules[type]) != 'undefined') {
1395 button.disabled='disabled';
1398 button.disabled = false;
1402 function parseDate(input, format) {
1404 format = format.replace(/%/g, '');
1405 sep = format.charAt(1);
1406 yAt = format.indexOf('Y')
1407 // 1-1-06 or 1-12-06 or 1-1-2006 or 1-12-2006
1408 if(date.match(/^\d{1,2}[\/-]\d{1,2}[\/-]\d{2,4}$/) && yAt == 4) {
1409 if(date.match(/^\d{1}[\/-].*$/)) date = '0' + date;
1410 if(date.match(/^\d{2}[\/-]\d{1}[\/-].*$/)) date = date.substring(0,3) + '0' + date.substring(3,date.length);
1411 if(date.match(/^\d{2}[\/-]\d{2}[\/-]\d{2}$/)) date = date.substring(0,6) + '20' + date.substring(6,date.length);
1413 // 06-11-1 or 06-1-1
1414 else if(date.match(/^\d{2,4}[\/-]\d{1,2}[\/-]\d{1,2}$/)) {
1415 if(date.match(/^\d{2}[\/-].*$/)) date = '20' + date;
1416 if(date.match(/^\d{4}[\/-]\d{1}[\/-].*$/)) date = date.substring(0,5) + '0' + date.substring(5,date.length);
1417 if(date.match(/^\d{4}[\/-]\d{2}[\/-]\d{1}$/)) date = date.substring(0,8) + '0' + date.substring(8,date.length);
1419 else if(date.match(/^\d{4,8}$/)) { // digits only
1421 if(date.match(/^\d{8}$/)) digits = 8;// match for 8 digits
1422 else if(date.match(/\d{6}/)) digits = 6;// match for 5 digits
1423 else if(date.match(/\d{4}/)) digits = 4;// match for 5 digits
1424 else if(date.match(/\d{5}/)) digits = 5;// match for 5 digits
1429 case 4: date = '20' + date.substring(0,2) + sep + '0' + date.substring(2, 3) + sep + '0' + date.substring(3,4); break;
1430 case 5: date = '20' + date.substring(0,2) + sep + date.substring(2, 4) + sep + '0' + date.substring(4,5); break;
1431 case 6: date = '20' + date.substring(0,2) + sep + date.substring(2, 4) + sep + date.substring(4,6); break;
1432 case 8: date = date.substring(0,4) + sep + date.substring(4, 6) + sep + date.substring(6,8); break;
1437 case 4: date = '0' + date.substring(0,1) + sep + '20' + date.substring(1, 3) + sep + '0' + date.substring(3,4); break;
1438 case 5: date = date.substring(0,2) + sep + '20' + date.substring(2, 4) + sep + '0' + date.substring(4,5); break;
1439 case 6: date = date.substring(0,2) + sep + '20' + date.substring(2, 4) + sep + date.substring(4,6); break;
1440 case 8: date = date.substring(0,2) + sep + date.substring(2, 6) + sep + date.substring(6,8); break;
1444 case 4: date = '0' + date.substring(0,1) + sep + '0' + date.substring(1, 2) + sep + '20' + date.substring(2,4); break;
1445 case 5: date = '0' + date.substring(0,1) + sep + date.substring(1, 3) + sep + '20' + date.substring(3,5); break;
1446 case 6: date = date.substring(0,2) + sep + date.substring(2, 4) + sep + '20' + date.substring(4,6); break;
1447 case 8: date = date.substring(0,2) + sep + date.substring(2, 4) + sep + date.substring(4,8); break;
1452 date = date.replace(/[\/-]/g, sep);
1456 // find obj's position
1457 function findElementPos(obj) {
1460 if (obj.offsetParent) {
1461 while (obj.offsetParent) {
1462 x += obj.offsetLeft;
1464 obj = obj.offsetParent;
1466 }//if offsetParent exists
1467 else if (obj.x && obj.y) {
1471 return new coordinate(x, y);
1475 // get dimensions of the browser window
1476 function getClientDim() {
1477 var nwX, nwY, seX, seY;
1478 if (self.pageYOffset) // all except Explorer
1480 nwX = self.pageXOffset;
1481 seX = self.innerWidth + nwX;
1482 nwY = self.pageYOffset;
1483 seY = self.innerHeight + nwY;
1485 else if (document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
1487 nwX = document.documentElement.scrollLeft;
1488 seX = document.documentElement.clientWidth + nwX;
1489 nwY = document.documentElement.scrollTop;
1490 seY = document.documentElement.clientHeight + nwY;
1492 else if (document.body) // all other Explorers
1494 nwX = document.body.scrollLeft;
1495 seX = document.body.clientWidth + nwX;
1496 nwY = document.body.scrollTop;
1497 seY = document.body.clientHeight + nwY;
1499 return {'nw' : new coordinate(nwX, nwY), 'se' : new coordinate(seX, seY)};
1503 * stop propagation on events
1505 function freezeEvent(e) {
1507 if (e.preventDefault) e.preventDefault();
1508 e.returnValue = false;
1509 e.cancelBubble = true;
1510 if (e.stopPropagation) e.stopPropagation();
1519 function coordinate(_x, _y) {
1528 return new position(this.x + rh.x, this.y + rh.y);
1532 return new position(this.x + rh.x, this.y + rh.y);
1536 // sends theForm via AJAX and fills in the theDiv
1537 function sendAndRetrieve(theForm, theDiv, loadingStr) {
1538 function success(data) {
1539 document.getElementById(theDiv).innerHTML = data.responseText;
1540 ajaxStatus.hideStatus();
1542 if(typeof loadingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
1543 ajaxStatus.showStatus(loadingStr);
1544 YAHOO.util.Connect.setForm(theForm);
1545 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
1549 //save the form and redirect
1550 function sendAndRedirect(theForm, loadingStr, redirect_location) {
1551 function success(data) {
1552 if(redirect_location){
1553 location.href=redirect_location;
1555 ajaxStatus.hideStatus();
1557 if(typeof loadingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
1558 ajaxStatus.showStatus(loadingStr);
1559 YAHOO.util.Connect.setForm(theForm);
1560 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
1564 function saveForm(theForm, theDiv, loadingStr) {
1565 if(check_form(theForm)){
1566 for(i = 0; i < ajaxFormArray.length; i++){
1567 if(ajaxFormArray[i] == theForm){
1568 ajaxFormArray.splice(i, 1);
1571 return sendAndRetrieve(theForm, loadingStr, theDiv);
1577 // Builds a "snapshot" of the form, so we can use it to see if someone has changed it.
1578 function snapshotForm(theForm) {
1579 var snapshotTxt = '';
1580 var elemList = theForm.elements;
1584 for( var i = 0; i < elemList.length ; i++ ) {
1586 if ( typeof(elem.type) == 'undefined' ) {
1590 elemType = elem.type.toLowerCase();
1592 snapshotTxt = snapshotTxt + elem.name;
1594 if ( elemType == 'text' || elemType == 'textarea' || elemType == 'password' ) {
1595 snapshotTxt = snapshotTxt + elem.value;
1597 else if ( elemType == 'select' || elemType == 'select-one' || elemType == 'select-multiple' ) {
1598 var optionList = elem.options;
1599 for ( var ii = 0 ; ii < optionList.length ; ii++ ) {
1600 if ( optionList[ii].selected ) {
1601 snapshotTxt = snapshotTxt + optionList[ii].value;
1605 else if ( elemType == 'radio' || elemType == 'checkbox' ) {
1606 if ( elem.selected ) {
1607 snapshotTxt = snapshotTxt + 'checked';
1610 else if ( elemType == 'hidden' ) {
1611 snapshotTxt = snapshotTxt + elem.value;
1618 function initEditView(theForm) {
1619 if (SUGAR.util.ajaxCallInProgress()) {
1620 window.setTimeout(function(){initEditView(theForm);}, 100);
1623 if ( theForm == null || theForm.id == null ) {
1624 // Not much we can do here.
1627 // we don't need to check if the data is changed in the search popup
1628 if (theForm.id == 'popup_query_form' || theForm.id == 'MassUpdate') {
1631 if ( typeof editViewSnapshots == 'undefined' ) {
1632 editViewSnapshots = new Object();
1634 if ( typeof SUGAR.loadedForms == 'undefined' ) {
1635 SUGAR.loadedForms = new Object();
1637 editViewSnapshots[theForm.id] = snapshotForm(theForm);
1638 SUGAR.loadedForms[theForm.id] = true;
1641 function onUnloadEditView(theForm) {
1643 var dataHasChanged = false;
1645 if ( typeof editViewSnapshots == 'undefined' ) {
1646 // No snapshots, move along
1650 if ( typeof theForm == 'undefined' ) {
1651 // Need to check all editViewSnapshots
1652 for ( var idx in editViewSnapshots ) {
1654 theForm = document.getElementById(idx);
1655 // console.log('DEBUG: Checking all forms '+theForm.id);
1656 if ( theForm == null
1657 || typeof editViewSnapshots[theForm.id] == 'undefined'
1658 || editViewSnapshots[theForm.id] == null
1659 || !SUGAR.loadedForms[theForm.id]) {
1663 var snap = snapshotForm(theForm);
1664 if ( editViewSnapshots[theForm.id] != snap ) {
1665 dataHasChanged = true;
1669 // Just need to check a single form for changes
1670 if ( editViewSnapshots == null || typeof theForm.id == 'undefined' || typeof editViewSnapshots[theForm.id] == 'undefined' || editViewSnapshots[theForm.id] == null ) {
1674 // console.log('DEBUG: Checking one form '+theForm.id);
1675 if ( editViewSnapshots[theForm.id] != snapshotForm(theForm) ) {
1676 // Data has changed.
1677 dataHasChanged = true;
1681 if ( dataHasChanged == true ) {
1682 return SUGAR.language.get('app_strings','WARN_UNSAVED_CHANGES');
1689 function disableOnUnloadEditView(theForm) {
1690 // If you don't pass anything in, it disables all checking
1691 if ( typeof theForm == 'undefined' || typeof editViewSnapshots == 'undefined' || theForm == null || editViewSnapshots == null) {
1692 window.onbeforeunload = null;
1693 editViewSnapshots = null;
1695 // console.log('DEBUG: Disabling all edit view checks');
1698 // Otherwise, it just disables it for this form
1699 if ( typeof(theForm.id) != 'undefined' && typeof(editViewSnapshots[theForm.id]) != 'undefined' ) {
1700 editViewSnapshots[theForm.id] = null;
1703 // console.log('DEBUG : Disabling just checks for '+theForm.id);
1709 * save some forms using an ajax call
1710 * theForms - the ids of all of theh forms to save
1711 * savingStr - the string to display when saving the form
1712 * completeStr - the string to display when the form has been saved
1714 function saveForms( savingStr, completeStr) {
1716 theForms = ajaxFormArray;
1717 function success(data) {
1718 var theForm = document.getElementById(ajaxFormArray[0]);
1719 document.getElementById('multiedit_'+theForm.id).innerHTML = data.responseText;
1720 var saveAllButton = document.getElementById('ajaxsaveall');
1721 ajaxFormArray.splice(index, 1);
1722 if(saveAllButton && ajaxFormArray.length <= 1){
1723 saveAllButton.style.visibility = 'hidden';
1726 if(index == theForms.length){
1727 ajaxStatus.showStatus(completeStr);
1728 window.setTimeout('ajaxStatus.hideStatus();', 2000);
1730 saveAllButton.style.visibility = 'hidden';
1735 if(typeof savingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
1736 ajaxStatus.showStatus(savingStr);
1738 //loop through the forms saving each one
1739 for(i = 0; i < theForms.length; i++){
1740 var theForm = document.getElementById(theForms[i]);
1741 if(check_form(theForm.id)){
1742 theForm.action.value='AjaxFormSave';
1743 YAHOO.util.Connect.setForm(theForm);
1744 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
1746 ajaxStatus.hideStatus();
1748 lastSubmitTime = lastSubmitTime-2000;
1753 // -- start sugarListView class
1754 // js functions used for ListView
1755 function sugarListView() {
1759 sugarListView.prototype.confirm_action = function(del) {
1761 return confirm( SUGAR.language.get('app_strings', 'NTC_DELETE_CONFIRMATION_NUM') + sugarListView.get_num_selected() + SUGAR.language.get('app_strings', 'NTC_DELETE_SELECTED_RECORDS'));
1764 return confirm( SUGAR.language.get('app_strings', 'NTC_UPDATE_CONFIRMATION_NUM') + sugarListView.get_num_selected() + SUGAR.language.get('app_strings', 'NTC_DELETE_SELECTED_RECORDS'));
1768 sugarListView.get_num_selected = function () {
1769 if(typeof document.MassUpdate != 'undefined') {
1770 the_form = document.MassUpdate;
1771 for(wp = 0; wp < the_form.elements.length; wp++) {
1772 if(typeof the_form.elements[wp].name != 'undefined' && the_form.elements[wp].name == 'selectCount[]') {
1773 return the_form.elements[wp].value;
1780 sugarListView.update_count = function(count, add) {
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[]') {
1786 the_form.elements[wp].value = parseInt(the_form.elements[wp].value,10) + count;
1787 if (the_form.select_entire_list.value == 1 && the_form.show_plus.value) {
1788 the_form.elements[wp].value += '+';
1791 if (the_form.select_entire_list.value == 1 && the_form.show_plus.value) {
1792 the_form.elements[wp].value = count + '+';
1794 the_form.elements[wp].value = count;
1801 sugarListView.prototype.use_external_mail_client = function(no_record_txt, module) {
1802 selected_records = sugarListView.get_checks_count();
1803 if(selected_records <1) {
1804 alert(no_record_txt);
1808 if (document.MassUpdate.select_entire_list.value == 1) {
1809 if (totalCount > 10) {
1810 alert(totalCountError);
1815 else if (document.MassUpdate.massall.checked == true)
1819 sugarListView.get_checks();
1821 if(select) { // use selected items
1822 ids = document.MassUpdate.uid.value;
1824 else { // use current page
1825 inputs = document.MassUpdate.elements;
1827 for(i = 0; i < inputs.length; i++) {
1828 if(inputs[i].name == 'mass[]' && inputs[i].checked && typeof(inputs[i].value) != 'function') {
1829 ar.push(inputs[i].value);
1834 YAHOO.util.Connect.asyncRequest("POST", "index.php?", {
1835 success: this.use_external_mail_client_callback
1836 }, SUGAR.util.paramsToUrl({
1839 listViewExternalClient: 1,
1840 action_module: module,
1848 sugarListView.prototype.use_external_mail_client_callback = function(o)
1851 location.href = 'mailto:' + o.responseText;
1854 sugarListView.prototype.send_form_for_emails = function(select, currentModule, action, no_record_txt,action_module,totalCount, totalCountError) {
1855 if ( typeof(SUGAR.config.email_sugarclient_listviewmaxselect) != 'undefined' ) {
1859 maxCount = SUGAR.config.email_sugarclient_listviewmaxselect;
1862 if (document.MassUpdate.select_entire_list.value == 1) {
1863 if (totalCount > maxCount) {
1864 alert(totalCountError);
1869 else if (document.MassUpdate.massall.checked == true)
1874 sugarListView.get_checks();
1875 // create new form to post (can't access action property of MassUpdate form due to action input)
1876 var newForm = document.createElement('form');
1877 newForm.method = 'post';
1878 newForm.action = action;
1879 newForm.name = 'newForm';
1880 newForm.id = 'newForm';
1881 var uidTa = document.createElement('textarea');
1883 uidTa.style.display = 'none';
1885 if(select) { // use selected items
1886 uidTa.value = document.MassUpdate.uid.value;
1888 else { // use current page
1889 inputs = document.MassUpdate.elements;
1891 for(i = 0; i < inputs.length; i++) {
1892 if(inputs[i].name == 'mass[]' && inputs[i].checked && typeof(inputs[i].value) != 'function') {
1893 ar.push(inputs[i].value);
1896 uidTa.value = ar.join(',');
1899 if(uidTa.value == '') {
1900 alert(no_record_txt);
1904 var selectedArray = uidTa.value.split(",");
1905 if(selectedArray.length > maxCount) {
1906 alert(totalCountError);
1909 newForm.appendChild(uidTa);
1911 var moduleInput = document.createElement('input');
1912 moduleInput.name = 'module';
1913 moduleInput.type = 'hidden';
1914 moduleInput.value = currentModule;
1915 newForm.appendChild(moduleInput);
1917 var actionInput = document.createElement('input');
1918 actionInput.name = 'action';
1919 actionInput.type = 'hidden';
1920 actionInput.value = 'Compose';
1921 newForm.appendChild(actionInput);
1923 if (typeof action_module != 'undefined' && action_module!= '') {
1924 var actionModule = document.createElement('input');
1925 actionModule.name = 'action_module';
1926 actionModule.type = 'hidden';
1927 actionModule.value = action_module;
1928 newForm.appendChild(actionModule);
1930 //return_info must follow this pattern."&return_module=Accounts&return_action=index"
1931 if (typeof return_info!= 'undefined' && return_info != '') {
1932 var params= return_info.split('&');
1933 if (params.length > 0) {
1934 for (var i=0;i< params.length;i++) {
1935 if (params[i].length > 0) {
1936 var param_nv=params[i].split('=');
1937 if (param_nv.length==2){
1938 returnModule = document.createElement('input');
1939 returnModule.name = param_nv[0];
1940 returnModule.type = 'hidden';
1941 returnModule.value = param_nv[1];
1942 newForm.appendChild(returnModule);
1949 var isAjaxCall = document.createElement('input');
1950 isAjaxCall.name = 'ajaxCall';
1951 isAjaxCall.type = 'hidden';
1952 isAjaxCall.value = true;
1953 newForm.appendChild(isAjaxCall);
1955 var isListView = document.createElement('input');
1956 isListView.name = 'ListView';
1957 isListView.type = 'hidden';
1958 isListView.value = true;
1959 newForm.appendChild(isListView);
1961 var toPdf = document.createElement('input');
1962 toPdf.name = 'to_pdf';
1963 toPdf.type = 'hidden';
1965 newForm.appendChild(toPdf);
1967 //Grab the Quick Compose package for the listview
1968 YAHOO.util.Connect.setForm(newForm);
1971 success: function(o) {
1972 var resp = YAHOO.lang.JSON.parse(o.responseText);
1973 var quickComposePackage = new Object();
1974 quickComposePackage.composePackage = resp;
1975 quickComposePackage.fullComposeUrl = 'index.php?module=Emails&action=Compose&ListView=true' +
1976 '&uid=' + uidTa.value + '&action_module=' + action_module;
1978 SUGAR.quickCompose.init(quickComposePackage);
1982 YAHOO.util.Connect.asyncRequest('POST','index.php', callback,null);
1984 // awu Bug 18624: Fixing issue where a canceled Export and unselect of row will persist the uid field, clear the field
1985 document.MassUpdate.uid.value = '';
1990 sugarListView.prototype.send_form = function(select, currentModule, action, no_record_txt,action_module,return_info) {
1991 if (document.MassUpdate.select_entire_list.value == 1) {
1993 if(sugarListView.get_checks_count() < 1) {
1994 alert(no_record_txt);
1999 if ( action.indexOf('?') != -1 )
2000 href += '&module=' + currentModule;
2002 href += '?module=' + currentModule;
2005 href += return_info;
2006 var newForm = document.createElement('form');
2007 newForm.method = 'post';
2008 newForm.action = href;
2009 newForm.name = 'newForm';
2010 newForm.id = 'newForm';
2011 var postTa = document.createElement('textarea');
2012 postTa.name = 'current_post';
2013 postTa.value = document.MassUpdate.current_query_by_page.value;
2014 postTa.style.display = 'none';
2015 newForm.appendChild(postTa);
2016 document.MassUpdate.parentNode.appendChild(newForm);
2020 else if (document.MassUpdate.massall.checked == true)
2025 sugarListView.get_checks();
2026 // create new form to post (can't access action property of MassUpdate form due to action input)
2027 var newForm = document.createElement('form');
2028 newForm.method = 'post';
2029 newForm.action = action;
2030 newForm.name = 'newForm';
2031 newForm.id = 'newForm';
2032 var uidTa = document.createElement('textarea');
2034 uidTa.style.display = 'none';
2035 uidTa.value = document.MassUpdate.uid.value;
2037 if(uidTa.value == '') {
2038 alert(no_record_txt);
2042 newForm.appendChild(uidTa);
2044 var moduleInput = document.createElement('input');
2045 moduleInput.name = 'module';
2046 moduleInput.type = 'hidden';
2047 moduleInput.value = currentModule;
2048 newForm.appendChild(moduleInput);
2050 var actionInput = document.createElement('input');
2051 actionInput.name = 'action';
2052 actionInput.type = 'hidden';
2053 actionInput.value = 'index';
2054 newForm.appendChild(actionInput);
2056 if (typeof action_module != 'undefined' && action_module!= '') {
2057 var actionModule = document.createElement('input');
2058 actionModule.name = 'action_module';
2059 actionModule.type = 'hidden';
2060 actionModule.value = action_module;
2061 newForm.appendChild(actionModule);
2063 //return_info must follow this pattern."&return_module=Accounts&return_action=index"
2064 if (typeof return_info!= 'undefined' && return_info != '') {
2065 var params= return_info.split('&');
2066 if (params.length > 0) {
2067 for (var i=0;i< params.length;i++) {
2068 if (params[i].length > 0) {
2069 var param_nv=params[i].split('=');
2070 if (param_nv.length==2){
2071 returnModule = document.createElement('input');
2072 returnModule.name = param_nv[0];
2073 returnModule.type = 'hidden';
2074 returnModule.value = param_nv[1];
2075 newForm.appendChild(returnModule);
2082 document.MassUpdate.parentNode.appendChild(newForm);
2085 // awu Bug 18624: Fixing issue where a canceled Export and unselect of row will persist the uid field, clear the field
2086 document.MassUpdate.uid.value = '';
2090 //return a count of checked row.
2091 sugarListView.get_checks_count = function() {
2094 if(document.MassUpdate.uid.value != '') {
2095 oldUids = document.MassUpdate.uid.value.split(',');
2096 for(uid in oldUids) {
2097 if(typeof(oldUids[uid]) != 'function') {
2098 ar[oldUids[uid]] = 1;
2102 // build associated array of uids, associated array ensures uniqueness
2103 inputs = document.MassUpdate.elements;
2104 for(i = 0; i < inputs.length; i++) {
2105 if(inputs[i].name == 'mass[]') {
2106 ar[inputs[i].value] = (inputs[i].checked) ? 1 : 0; // 0 of it is unchecked
2110 // build regular array of uids
2113 if((typeof(ar[i]) != 'function') && ar[i] == 1) {
2121 // saves the checks on the current page into the uid textarea
2122 sugarListView.get_checks = function() {
2125 if(document.MassUpdate.uid.value != '') {
2126 oldUids = document.MassUpdate.uid.value.split(',');
2127 for(uid in oldUids) {
2128 if(typeof(oldUids[uid]) != 'function') {
2129 ar[oldUids[uid]] = 1;
2134 // build associated array of uids, associated array ensures uniqueness
2135 inputs = document.MassUpdate.elements;
2136 for(i = 0; i < inputs.length; i++) {
2137 if(inputs[i].name == 'mass[]') {
2138 ar[inputs[i].value] = (inputs[i].checked) ? 1 : 0; // 0 of it is unchecked
2142 // build regular array of uids
2145 if(typeof(ar[i]) != 'function' && ar[i] == 1) {
2150 document.MassUpdate.uid.value = uids.join(',');
2152 if(uids.length == 0) return false; // return false if no checks to get
2153 return true; // there are saved checks
2156 sugarListView.prototype.order_checks = function(order,orderBy,moduleString){
2157 checks = sugarListView.get_checks();
2158 eval('document.MassUpdate.' + moduleString + '.value = orderBy');
2159 document.MassUpdate.lvso.value = order;
2160 if(typeof document.MassUpdate.massupdate != 'undefined') {
2161 document.MassUpdate.massupdate.value = 'false';
2164 //we must first clear the action of massupdate, change it to index
2165 document.MassUpdate.action.value = document.MassUpdate.return_action.value;
2166 document.MassUpdate.return_module.value='';
2167 document.MassUpdate.return_action.value='';
2168 document.MassUpdate.submit();
2172 sugarListView.prototype.save_checks = function(offset, moduleString) {
2173 checks = sugarListView.get_checks();
2174 eval('document.MassUpdate.' + moduleString + '.value = offset');
2176 if(typeof document.MassUpdate.massupdate != 'undefined') {
2177 document.MassUpdate.massupdate.value = 'false';
2180 //we must first clear the action of massupdate, change it to index
2181 document.MassUpdate.action.value = document.MassUpdate.return_action.value;
2182 document.MassUpdate.return_module.value='';
2183 document.MassUpdate.return_action.value='';
2184 document.MassUpdate.submit();
2190 sugarListView.prototype.check_item = function(cb, form) {
2192 sugarListView.update_count(1, true);
2194 sugarListView.update_count(-1, true);
2195 if(typeof form != 'undefined' && form != null) {
2196 sugarListView.prototype.updateUid(cb, form);
2201 /**#28000, remove the unselect record id from MassUpdate.uid **/
2202 sugarListView.prototype.updateUid = function(cb , form){
2203 if(form.name == 'MassUpdate' && form.uid && form.uid.value && cb.value && form.uid.value.indexOf(cb.value) != -1){
2204 if(form.uid.value.indexOf(','+cb.value)!= -1){
2205 form.uid.value = form.uid.value.replace(','+cb.value , '');
2206 }else if(form.uid.value.indexOf(cb.value + ',')!= -1){
2207 form.uid.value = form.uid.value.replace(cb.value + ',' , '');
2208 }else if(form.uid.value.indexOf(cb.value)!= -1){
2209 form.uid.value = form.uid.value.replace(cb.value , '');
2214 sugarListView.prototype.check_entire_list = function(form, field, value, list_count) {
2215 // count number of items
2217 document.MassUpdate.massall.checked = true;
2218 document.MassUpdate.massall.disabled = true;
2220 for (i = 0; i < form.elements.length; i++) {
2221 if(form.elements[i].name == field && form.elements[i].disabled == false) {
2222 if(form.elements[i].checked != value) count++;
2223 form.elements[i].checked = value;
2224 form.elements[i].disabled = true;
2227 document.MassUpdate.select_entire_list.value = 1;
2229 sugarListView.update_count(list_count, false);
2230 //else sugarListView.update_count(-1 * count, true);
2233 sugarListView.prototype.check_all = function(form, field, value, pageTotal) {
2234 // count number of items
2236 document.MassUpdate.massall.checked = value;
2237 if (document.MassUpdate.select_entire_list &&
2238 document.MassUpdate.select_entire_list.value == 1)
2239 document.MassUpdate.massall.disabled = true;
2241 document.MassUpdate.massall.disabled = false;
2243 for (i = 0; i < form.elements.length; i++) {
2244 if(form.elements[i].name == field && !(form.elements[i].disabled == true && form.elements[i].checked == false)) {
2245 form.elements[i].disabled = false;
2247 if(form.elements[i].checked != value)
2249 form.elements[i].checked = value;
2251 sugarListView.prototype.updateUid(form.elements[i], form);
2256 sugarListView.update_count(pageTotal);
2258 sugarListView.update_count(count, true);
2260 sugarListView.update_count(-1 * count, true);
2262 sugarListView.check_all = sugarListView.prototype.check_all;
2263 sugarListView.confirm_action = sugarListView.prototype.confirm_action;
2265 sugarListView.prototype.check_boxes = function() {
2266 var inputsCount = 0;
2267 var checkedCount = 0;
2268 var existing_onload = window.onload;
2269 var theForm = document.MassUpdate;
2270 inputs_array = theForm.elements;
2272 if(typeof theForm.uid.value != 'undefined' && theForm.uid.value != "") {
2273 checked_items = theForm.uid.value.split(",");
2274 if (theForm.select_entire_list.value == 1)
2275 document.MassUpdate.massall.disabled = true;
2277 for(wp = 0 ; wp < inputs_array.length; wp++) {
2278 if(inputs_array[wp].name == "mass[]") {
2280 if (theForm.select_entire_list.value == 1) {
2281 inputs_array[wp].checked = true;
2282 inputs_array[wp].disabled = true;
2286 for(i in checked_items) {
2287 if(inputs_array[wp].value == checked_items[i]) {
2289 inputs_array[wp].checked = true;
2295 if (theForm.select_entire_list.value == 0)
2296 sugarListView.update_count(checked_items.length);
2298 sugarListView.update_count(0, true);
2302 for(wp = 0 ; wp < inputs_array.length; wp++) {
2303 if(inputs_array[wp].name == "mass[]") {
2304 inputs_array[wp].checked = false;
2305 inputs_array[wp].disabled = false;
2308 if (document.MassUpdate.massall) {
2309 document.MassUpdate.massall.checked = false;
2310 document.MassUpdate.massall.disabled = false;
2312 sugarListView.update_count(0)
2314 if(checkedCount > 0 && checkedCount == inputsCount)
2315 document.MassUpdate.massall.checked = true;
2321 * This function is used in Email Template Module's listview.
2322 * It will check whether the templates are used in Campaing->EmailMarketing.
2323 * If true, it will notify user.
2325 function check_used_email_templates() {
2326 var ids = document.MassUpdate.uid.value;
2328 success:function(r) {
2329 if(r.responseText != '') {
2330 if(!confirm(SUGAR.language.get('app_strings','NTC_TEMPLATES_IS_USED') + r.responseText)) {
2334 document.MassUpdate.submit();
2338 url = "index.php?module=EmailTemplates&action=CheckDeletable&from=ListView&to_pdf=1&records="+ids;
2339 YAHOO.util.Connect.asyncRequest('POST',url, call_back,null);
2343 sugarListView.prototype.send_mass_update = function(mode, no_record_txt, del) {
2344 formValid = check_form('MassUpdate');
2345 if(!formValid && !del) return false;
2348 if (document.MassUpdate.select_entire_list &&
2349 document.MassUpdate.select_entire_list.value == 1)
2354 var ar = new Array();
2358 for(wp = 0; wp < document.MassUpdate.elements.length; wp++) {
2359 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)+'$');
2360 //when the uid is already in document.MassUpdate.uid.value, we should not add it to ar.
2361 if(typeof document.MassUpdate.elements[wp].name != 'undefined'
2362 && document.MassUpdate.elements[wp].name == 'mass[]'
2363 && document.MassUpdate.elements[wp].checked
2364 && !reg_for_existing_uid.test(document.MassUpdate.uid.value)) {
2365 ar.push(document.MassUpdate.elements[wp].value);
2368 if(document.MassUpdate.uid.value != '') document.MassUpdate.uid.value += ',';
2369 document.MassUpdate.uid.value += ar.join(',');
2370 if(document.MassUpdate.uid.value == '') {
2371 alert(no_record_txt);
2374 if(typeof(current_admin_id)!='undefined' && document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'Users' && (document.MassUpdate.is_admin.value!='' || document.MassUpdate.status.value!='')) {
2375 var reg_for_current_admin_id = new RegExp('^'+current_admin_id+'[\s]*,|,[\s]*'+current_admin_id+'[\s]*,|,[\s]*'+current_admin_id+'$|^'+current_admin_id+'$');
2376 if(reg_for_current_admin_id.test(document.MassUpdate.uid.value)) {
2377 //if current user is admin, we should not allow massupdate the user_type and status of himself
2378 alert(SUGAR.language.get('Users','LBL_LAST_ADMIN_NOTICE'));
2384 var entireInput = document.createElement('input');
2385 entireInput.name = 'entire';
2386 entireInput.type = 'hidden';
2387 entireInput.value = 'index';
2388 document.MassUpdate.appendChild(entireInput);
2389 //confirm(no_record_txt);
2390 if(document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'Users' && (document.MassUpdate.is_admin.value!='' || document.MassUpdate.status.value!='')) {
2391 alert(SUGAR.language.get('Users','LBL_LAST_ADMIN_NOTICE'));
2397 if(!sugarListView.confirm_action(del))
2401 var deleteInput = document.createElement('input');
2402 deleteInput.name = 'Delete';
2403 deleteInput.type = 'hidden';
2404 deleteInput.value = true;
2405 document.MassUpdate.appendChild(deleteInput);
2406 if(document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'EmailTemplates') {
2407 check_used_email_templates();
2413 document.MassUpdate.submit();
2418 sugarListView.prototype.clear_all = function() {
2419 document.MassUpdate.uid.value = '';
2420 document.MassUpdate.select_entire_list.value = 0;
2421 sugarListView.check_all(document.MassUpdate, 'mass[]', false);
2422 document.MassUpdate.massall.checked = false;
2423 document.MassUpdate.massall.disabled = false;
2424 sugarListView.update_count(0);
2427 sListView = new sugarListView();
2428 // -- end sugarListView class
2430 // format and unformat numbers
2431 function unformatNumber(n, num_grp_sep, dec_sep) {
2432 var x=unformatNumberNoParse(n, num_grp_sep, dec_sep);
2435 return parseFloat(x);
2440 function unformatNumberNoParse(n, num_grp_sep, dec_sep) {
2441 if(typeof num_grp_sep == 'undefined' || typeof dec_sep == 'undefined') return n;
2442 n = n ? n.toString() : '';
2445 if(num_grp_sep != '')
2447 num_grp_sep_re = new RegExp('\\'+num_grp_sep, 'g');
2448 n = n.replace(num_grp_sep_re, '');
2451 n = n.replace(dec_sep, '.');
2453 if(typeof CurrencySymbols != 'undefined') {
2454 // Need to strip out the currency symbols from the start.
2455 for ( var idx in CurrencySymbols ) {
2456 n = n.replace(CurrencySymbols[idx], '');
2464 // round parameter can be negative for decimal, precision has to be postive
2465 function formatNumber(n, num_grp_sep, dec_sep, round, precision) {
2466 if(typeof num_grp_sep == 'undefined' || typeof dec_sep == 'undefined') return n;
2467 n = n ? n.toString() : '';
2468 if(n.split) n = n.split('.');
2471 if(n.length > 2) return n.join('.'); // that's not a num!
2473 if(typeof round != 'undefined') {
2474 if(round > 0 && n.length > 1) { // round to decimal
2475 n[1] = parseFloat('0.' + n[1]);
2476 n[1] = Math.round(n[1] * Math.pow(10, round)) / Math.pow(10, round);
2477 n[1] = n[1].toString().split('.')[1];
2479 if(round <= 0) { // round to whole number
2480 n[0] = Math.round(parseInt(n[0],10) * Math.pow(10, round)) / Math.pow(10, round);
2485 if(typeof precision != 'undefined' && precision >= 0) {
2486 if(n.length > 1 && typeof n[1] != 'undefined') n[1] = n[1].substring(0, precision); // cut off precision
2488 if(n[1].length < precision) {
2489 for(var wp = n[1].length; wp < precision; wp++) n[1] += '0';
2493 regex = /(\d+)(\d{3})/;
2494 while(num_grp_sep != '' && regex.test(n[0])) n[0] = n[0].toString().replace(regex, '$1' + num_grp_sep + '$2');
2495 return n[0] + (n.length > 1 && n[1] != '' ? dec_sep + n[1] : '');
2498 // --- begin ajax status class
2499 SUGAR.ajaxStatusClass = function() {};
2500 SUGAR.ajaxStatusClass.prototype.statusDiv = null;
2501 SUGAR.ajaxStatusClass.prototype.oldOnScroll = null;
2502 SUGAR.ajaxStatusClass.prototype.shown = false; // state of the status window
2504 // reposition the status div, top and centered
2505 SUGAR.ajaxStatusClass.prototype.positionStatus = function() {
2506 this.statusDiv.style.top = document.body.scrollTop + 8 + 'px';
2507 statusDivRegion = YAHOO.util.Dom.getRegion(this.statusDiv);
2508 statusDivWidth = statusDivRegion.right - statusDivRegion.left;
2509 this.statusDiv.style.left = YAHOO.util.Dom.getViewportWidth() / 2 - statusDivWidth / 2 + 'px';
2512 // private func, create the status div
2513 SUGAR.ajaxStatusClass.prototype.createStatus = function(text) {
2514 statusDiv = document.createElement('div');
2515 statusDiv.className = 'dataLabel';
2516 statusDiv.id = 'ajaxStatusDiv';
2517 document.body.appendChild(statusDiv);
2518 this.statusDiv = document.getElementById('ajaxStatusDiv');
2521 // public - show the status div with text
2522 SUGAR.ajaxStatusClass.prototype.showStatus = function(text) {
2523 if(!this.statusDiv) {
2524 this.createStatus(text);
2527 this.statusDiv.style.display = '';
2529 this.statusDiv.style.zIndex = 20;
2530 this.statusDiv.innerHTML = ' <b>' + text + '</b> ';
2531 this.positionStatus();
2534 this.statusDiv.style.display = '';
2535 if(window.onscroll) this.oldOnScroll = window.onscroll; // save onScroll
2536 window.onscroll = this.positionStatus;
2541 SUGAR.ajaxStatusClass.prototype.hideStatus = function(text) {
2542 if(!this.shown) return;
2544 if(this.oldOnScroll) window.onscroll = this.oldOnScroll;
2545 else window.onscroll = '';
2546 this.statusDiv.style.display = 'none';
2549 SUGAR.ajaxStatusClass.prototype.flashStatus = function(text, time){
2550 this.showStatus(text);
2551 window.setTimeout('ajaxStatus.hideStatus();', time);
2555 var ajaxStatus = new SUGAR.ajaxStatusClass();
2556 // --- end ajax status class
2559 * Unified Search Advanced - for global search
2561 SUGAR.unifiedSearchAdvanced = function() {
2571 SUGAR.unifiedSearchAdvanced.usa_div = document.getElementById('unified_search_advanced_div');
2572 SUGAR.unifiedSearchAdvanced.usa_img = document.getElementById('unified_search_advanced_img');
2574 if(!SUGAR.unifiedSearchAdvanced.usa_div || !SUGAR.unifiedSearchAdvanced.usa_img) return;
2575 var attributes = { height: { to: 300 } };
2576 SUGAR.unifiedSearchAdvanced.anim_open = new YAHOO.util.Anim('unified_search_advanced_div', attributes );
2577 SUGAR.unifiedSearchAdvanced.anim_open.duration = 0.75;
2578 SUGAR.unifiedSearchAdvanced.anim_close = new YAHOO.util.Anim('unified_search_advanced_div', { height: {to: 0} } );
2579 SUGAR.unifiedSearchAdvanced.anim_close.duration = 0.75;
2580 //SUGAR.unifiedSearchAdvanced.anim_close.onComplete.subscribe(function() {SUGAR.unifiedSearchAdvanced.usa_div.style.display = 'none'});
2582 SUGAR.unifiedSearchAdvanced.usa_img._x = YAHOO.util.Dom.getX(SUGAR.unifiedSearchAdvanced.usa_img);
2583 SUGAR.unifiedSearchAdvanced.usa_img._y = YAHOO.util.Dom.getY(SUGAR.unifiedSearchAdvanced.usa_img);
2586 SUGAR.unifiedSearchAdvanced.usa_open = false;
2587 SUGAR.unifiedSearchAdvanced.usa_content = null;
2589 YAHOO.util.Event.addListener('unified_search_advanced_img', 'click', SUGAR.unifiedSearchAdvanced.get_content);
2592 get_content: function(e)
2594 query_string = trim(document.getElementById('query_string').value);
2595 if(query_string != '')
2597 window.location.href = 'index.php?module=Home&action=UnifiedSearch&query_string=' + query_string;
2599 window.location.href = 'index.php?module=Home&action=UnifiedSearch&form_only=true';
2603 animate: function(data) {
2604 ajaxStatus.hideStatus();
2607 SUGAR.unifiedSearchAdvanced.usa_content = data.responseText;
2608 SUGAR.unifiedSearchAdvanced.usa_div.innerHTML = SUGAR.unifiedSearchAdvanced.usa_content;
2610 if(SUGAR.unifiedSearchAdvanced.usa_open) {
2611 document.UnifiedSearch.advanced.value = 'false';
2612 SUGAR.unifiedSearchAdvanced.anim_close.animate();
2615 document.UnifiedSearch.advanced.value = 'true';
2616 SUGAR.unifiedSearchAdvanced.usa_div.style.display = '';
2617 YAHOO.util.Dom.setX(SUGAR.unifiedSearchAdvanced.usa_div, SUGAR.unifiedSearchAdvanced.usa_img._x - 90);
2618 YAHOO.util.Dom.setY(SUGAR.unifiedSearchAdvanced.usa_div, SUGAR.unifiedSearchAdvanced.usa_img._y + 15);
2619 SUGAR.unifiedSearchAdvanced.anim_open.animate();
2621 SUGAR.unifiedSearchAdvanced.usa_open = !SUGAR.unifiedSearchAdvanced.usa_open;
2626 checkUsaAdvanced: function() {
2627 if(document.UnifiedSearch.advanced.value == 'true') {
2628 document.UnifiedSearchAdvanced.query_string.value = document.UnifiedSearch.query_string.value;
2629 document.UnifiedSearchAdvanced.submit();
2636 if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.unifiedSearchAdvanced.init);
2641 * Toggles the header
2643 toggleHeader : function() {
2644 var h = document.getElementById('header');
2648 if(h.style.display == 'none') {
2649 h.style.display = '';
2651 h.style.display = 'none';
2655 alert(SUGAR.language.get("app_strings", "ERR_NO_HEADER_ID"));
2662 * General Sugar Utils
2664 SUGAR.util = function () {
2665 var additionalDetailsCache;
2666 var additionalDetailsCalls;
2667 var additionalDetailsRpcCall;
2670 getAndRemove : function (el) {
2671 if (YAHOO && YAHOO.util && YAHOO.util.Dom)
2672 el = YAHOO.util.Dom.get(el);
2673 else if (typeof (el) == "string")
2674 el = document.getElementById(el);
2675 if (el && el.parentNode)
2676 el.parentNode.removeChild(el);
2680 paramsToUrl : function (params) {
2683 url += i + "=" + params[i] + "&";
2687 evalScript:function(text){
2689 var waitUntilLoaded = function(){
2690 SUGAR.evalScript_waitCount--;
2691 if (SUGAR.evalScript_waitCount == 0) {
2692 var headElem = document.getElementsByTagName('head')[0];
2693 for ( var i = 0; i < SUGAR.evalScript_evalElem.length; i++) {
2694 var tmpElem = document.createElement('script');
2695 tmpElem.type = 'text/javascript';
2696 tmpElem.text = SUGAR.evalScript_evalElem[i];
2697 headElem.appendChild(tmpElem);
2702 var tmpElem = document.createElement('div');
2703 tmpElem.innerHTML = text;
2704 var results = tmpElem.getElementsByTagName('script');
2705 if (results == null) {
2706 // No scripts found, bail out
2710 var headElem = document.getElementsByTagName('head')[0];
2712 SUGAR.evalScript_waitCount = 0;
2713 SUGAR.evalScript_evalElem = new Array();
2714 for (var i = 0; i < results.length; i++) {
2715 if (typeof(results[i]) != 'object') {
2718 tmpElem = document.createElement('script');
2719 tmpElem.type = 'text/javascript';
2720 if (results[i].src != null && results[i].src != '') {
2721 tmpElem.src = results[i].src;
2723 // Need to defer execution of these scripts until the
2724 // required javascript files are fully loaded
2725 SUGAR.evalScript_evalElem[SUGAR.evalScript_evalElem.length] = results[i].text;
2728 tmpElem.addEventListener('load', waitUntilLoaded);
2729 SUGAR.evalScript_waitCount++;
2730 headElem.appendChild(tmpElem);
2732 // Add some code to handle pages without any external scripts
2733 SUGAR.evalScript_waitCount++;
2736 // Don't try and process things the IE way
2740 var objRegex = /<\s*script([^>]*)>((.|\s|\v|\0)*?)<\s*\/script\s*>/igm;
2742 var result = objRegex.exec(text);
2743 while(result && result.index > lastIndex){
2744 lastIndex = result.index
2746 var script = document.createElement('script');
2747 script.type= 'text/javascript';
2748 if(result[1].indexOf("src=") > -1){
2749 var srcRegex = /.*src=['"]([a-zA-Z0-9_\&\/\.\?=:]*)['"].*/igm;
2750 var srcResult = result[1].replace(srcRegex, '$1');
2751 script.src = srcResult;
2753 script.text = result[2];
2755 document.body.appendChild(script)
2760 result = objRegex.exec(text);
2764 * Gets the sidebar object
2765 * @return object pointer to the sidebar element
2767 getLeftColObj: function() {
2768 leftColObj = document.getElementById('leftCol');
2769 while(leftColObj.nodeName != 'TABLE') {
2770 leftColObj = leftColObj.firstChild;
2772 leftColTable = leftColObj;
2773 leftColTd = leftColTable.getElementsByTagName('td')[0];
2774 leftColTdRegion = YAHOO.util.Dom.getRegion(leftColTd);
2775 leftColTd.style.width = (leftColTdRegion.right - leftColTdRegion.left) + 'px';
2780 * Fills the shortcut menu placeholders w/ actual content
2781 * Call this on load event
2783 * @param shortcutContent Array array of content to fill in
2785 fillShortcuts: function(e, shortcutContent) {
2788 // don't do this if leftCol isn't available
2789 if (document.getElementById('leftCol') == undefined) { return; }
2791 spans = document.getElementById('leftCol').getElementsByTagName('span');
2792 hideCol = document.getElementById('HideMenu').getElementsByTagName('span');
2793 w = spans.length + 1;
2795 spans[w] = hideCol[i];
2798 for(je in shortcutContent) {
2800 if(typeof spans[wp].innerHTML != 'undefined' && spans[wp].innerHTML == ('wp_shortcut_fill_' + je)) {
2801 if(typeof spans[wp].parentNode.parentNode == 'object') {
2802 if(typeof spans[wp].parentNode.parentNode.onclick != 'undefined') {
2803 spans[wp].parentNode.parentNode.onclick = null;
2805 // If the wp_shortcut span is contained by an A tag, replace the A with a DIV.
2806 if(spans[wp].parentNode.tagName == 'A' && !isIE) {
2807 var newDiv = document.createElement('DIV');
2808 var parentAnchor = spans[wp].parentNode;
2810 spans[wp].parentNode.parentNode.style.display = 'none';
2812 // Copy styles over to the new container div
2813 if(window.getComputedStyle) {
2814 var parentStyle = window.getComputedStyle(parentAnchor, '');
2815 for(var styleName in parentStyle) {
2816 if(typeof parentStyle[styleName] != 'function'
2817 && styleName != 'display'
2818 && styleName != 'borderWidth'
2819 && styleName != 'visibility') {
2821 newDiv.style[styleName] = parentStyle[styleName];
2823 // Catches .length and .parentRule, and others
2829 // Replace the A with the DIV
2830 newDiv.appendChild(spans[wp]);
2831 parentAnchor.parentNode.replaceChild(newDiv, parentAnchor);
2833 spans[wp].parentNode.parentNode.style.display = '';
2836 spans[wp].innerHTML = shortcutContent[je]; // fill w/ content
2837 if(spans[wp].style) spans[wp].style.display = '';
2843 * Make an AJAX request.
2845 * @param url string resource to load
2846 * @param theDiv string id of element to insert loaded data into
2847 * @param postForm string if set, a POST request will be made to resource specified by url using the form named by postForm
2848 * @param callback string name of function to invoke after HTTP response is recieved
2849 * @param callbackParam any parameter to pass to callback when invoked
2850 * @param appendMode bool if true, HTTP response will be appended to the contents of theDiv, or else contents will be overriten.
2852 retrieveAndFill: function(url, theDiv, postForm, callback, callbackParam, appendMode) {
2853 if(typeof theDiv == 'string') {
2855 theDiv = document.getElementById(theDiv);
2862 var success = function(data) {
2863 if (typeof theDiv != 'undefined' && theDiv != null)
2866 if (typeof appendMode != 'undefined' && appendMode)
2868 theDiv.innerHTML += data.responseText;
2872 theDiv.innerHTML = data.responseText;
2879 if (typeof callback != 'undefined' && callback != null) callback(callbackParam);
2882 if(typeof postForm == 'undefined' || postForm == null) {
2883 var cObj = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
2886 YAHOO.util.Connect.setForm(postForm);
2887 var cObj = YAHOO.util.Connect.asyncRequest('POST', url, {success: success, failure: success});
2890 checkMaxLength: function() { // modified from http://www.quirksmode.org/dom/maxlength.html
2891 var maxLength = this.getAttribute('maxlength');
2892 var currentLength = this.value.length;
2893 if (currentLength > maxLength) {
2894 this.value = this.value.substring(0, maxLength);
2899 * Adds maxlength attribute to textareas
2901 setMaxLength: function() { // modified from http://www.quirksmode.org/dom/maxlength.html
2902 var x = document.getElementsByTagName('textarea');
2903 for (var i=0;i<x.length;i++) {
2904 if (x[i].getAttribute('maxlength')) {
2905 x[i].onkeyup = x[i].onchange = SUGAR.util.checkMaxLength;
2912 * Retrieves additional details dynamically
2914 getAdditionalDetails: function(bean, id, spanId) {
2916 oReturn = function(body, caption, width, theme) {
2917 var _refx = 25-width;
2918 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);
2921 success = function(data) {
2922 eval(data.responseText);
2924 SUGAR.util.additionalDetailsCache[spanId] = new Array();
2925 SUGAR.util.additionalDetailsCache[spanId]['body'] = result['body'];
2926 SUGAR.util.additionalDetailsCache[spanId]['caption'] = result['caption'];
2927 SUGAR.util.additionalDetailsCache[spanId]['width'] = result['width'];
2928 SUGAR.util.additionalDetailsCache[spanId]['theme'] = result['theme'];
2929 ajaxStatus.hideStatus();
2930 return oReturn(SUGAR.util.additionalDetailsCache[spanId]['body'], SUGAR.util.additionalDetailsCache[spanId]['caption'], SUGAR.util.additionalDetailsCache[spanId]['width'], SUGAR.util.additionalDetailsCache[spanId]['theme']);
2933 if(typeof SUGAR.util.additionalDetailsCache[spanId] != 'undefined')
2934 return oReturn(SUGAR.util.additionalDetailsCache[spanId]['body'], SUGAR.util.additionalDetailsCache[spanId]['caption'], SUGAR.util.additionalDetailsCache[spanId]['width'], SUGAR.util.additionalDetailsCache[spanId]['theme']);
2936 if(typeof SUGAR.util.additionalDetailsCalls[spanId] != 'undefined') // call already in progress
2938 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_LOADING'));
2939 url = 'index.php?to_pdf=1&module=Home&action=AdditionalDetailsRetrieve&bean=' + bean + '&id=' + id;
2940 SUGAR.util.additionalDetailsCalls[spanId] = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
2944 SUGAR.util.additionalDetailsRpcCall = window.setTimeout('go()', 250);
2946 clearAdditionalDetailsCall: function() {
2947 if(typeof SUGAR.util.additionalDetailsRpcCall == 'number') window.clearTimeout(SUGAR.util.additionalDetailsRpcCall);
2950 * A function that extends functionality from parent to child.
2952 extend : function(subc, superc, overrides) {
2953 subc.prototype = new superc; // set the superclass
2956 for (var i in overrides) subc.prototype[i] = overrides[i];
2959 hrefURL : function(url) {
2961 // IE needs special treatment since otherwise it would not pass Referer
2962 var trampoline = document.createElement('a');
2963 trampoline.href = url;
2964 document.body.appendChild(trampoline);
2966 document.body.removeChild(trampoline);
2968 document.location.href = url;
2972 openWindow : function(URL, windowName, windowFeatures) {
2974 // IE needs special treatment since otherwise it would not pass Referer
2975 win = window.open('', windowName, windowFeatures);
2976 var trampoline = document.createElement('a');
2977 trampoline.href = URL;
2978 trampoline.target = windowName;
2979 document.body.appendChild(trampoline);
2981 document.body.removeChild(trampoline);
2983 win = window.open(URL, windowName, windowFeatures);
2989 SUGAR.util.additionalDetailsCache = new Array();
2990 SUGAR.util.additionalDetailsCalls = new Array();
2991 if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.util.setMaxLength); // allow textareas to obey maxlength attrib
2993 SUGAR.savedViews = function() {
2994 var selectedOrderBy;
2995 var selectedSortOrder;
2998 var columnsMeta; // meta data for the display columns
3001 setChooser: function() {
3003 var displayColumnsDef = new Array();
3004 var hideTabsDef = new Array();
3006 var left_td = document.getElementById('display_tabs_td');
3007 if(typeof left_td == 'undefined' || left_td == null) return; // abort!
3008 var right_td = document.getElementById('hide_tabs_td');
3010 var displayTabs = left_td.getElementsByTagName('select')[0];
3011 var hideTabs = right_td.getElementsByTagName('select')[0];
3013 for(i = 0; i < displayTabs.options.length; i++) {
3014 displayColumnsDef.push(displayTabs.options[i].value);
3017 if(typeof hideTabs != 'undefined') {
3018 for(i = 0; i < hideTabs.options.length; i++) {
3019 hideTabsDef.push(hideTabs.options[i].value);
3022 if (!SUGAR.savedViews.clearColumns)
3023 document.getElementById('displayColumnsDef').value = displayColumnsDef.join('|');
3024 document.getElementById('hideTabsDef').value = hideTabsDef.join('|');
3027 select: function(saved_search_select) {
3028 for(var wp = 0; wp < document.search_form.saved_search_select.options.length; wp++) {
3029 if(typeof document.search_form.saved_search_select.options[wp].value != 'undefined' &&
3030 document.search_form.saved_search_select.options[wp].value == saved_search_select) {
3031 document.search_form.saved_search_select.selectedIndex = wp;
3032 document.search_form.ss_delete.style.display = '';
3033 document.search_form.ss_update.style.display = '';
3037 saved_search_action: function(action, delete_lang) {
3038 if(action == 'delete') {
3039 if(!confirm(delete_lang)) return;
3041 if(action == 'save') {
3042 if(document.search_form.saved_search_name.value.replace(/^\s*|\s*$/g, '') == '') {
3043 alert(SUGAR.language.get('app_strings', 'LBL_SAVED_SEARCH_ERROR'));
3048 // This check is needed for the Activities module (Calls/Meetings/Tasks).
3049 if (document.search_form.saved_search_action)
3051 document.search_form.saved_search_action.value = action;
3052 document.search_form.search_module.value = document.search_form.module.value;
3053 document.search_form.module.value = 'SavedSearch';
3054 // Bug 31922 - Make sure to specify that we want to hit the index view here of
3055 // the SavedSearch module, since the ListView doesn't have the logic to save the
3056 // search and redirect back
3057 document.search_form.action.value = 'index';
3059 document.search_form.submit();
3061 shortcut_select: function(selectBox, module) {
3063 selecturl = 'index.php?module=SavedSearch&search_module=' + module + '&action=index&saved_search_select=' + selectBox.options[selectBox.selectedIndex].value
3064 //add searchFormTab to url if it is available. This determines what tab to render
3065 if(typeof(document.getElementById('searchFormTab'))!='undefined'){
3066 selecturl = selecturl + '&searchFormTab=' + document.search_form.searchFormTab.value;
3068 //add showSSDIV to url if it is available. This determines whether saved search sub form should
3069 //be rendered open or not
3070 if(document.getElementById('showSSDIV') && typeof(document.getElementById('showSSDIV') !='undefined')){
3071 selecturl = selecturl + '&showSSDIV='+document.getElementById('showSSDIV').value;
3073 //use created url to navigate
3074 document.location.href = selecturl;
3076 handleForm: function() {
3077 SUGAR.tabChooser.movementCallback = function(left_side, right_side) {
3078 while(document.getElementById('orderBySelect').childNodes.length != 0) { // clear out order by options
3079 document.getElementById('orderBySelect').removeChild(document.getElementById('orderBySelect').lastChild);
3082 var selectedIndex = 0;
3083 var nodeCount = -1; // need this because the counter i also includes "undefined" nodes
3084 // which was breaking Calls and Meetings
3086 for(i in left_side.childNodes) { // fill in order by options
3087 if(typeof left_side.childNodes[i].nodeName != 'undefined' &&
3088 left_side.childNodes[i].nodeName.toLowerCase() == 'option' &&
3089 typeof SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value] != 'undefined' && // check if column is sortable
3090 typeof SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value]['sortable'] == 'undefined' &&
3091 SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value]['sortable'] != false) {
3093 optionNode = document.createElement('option');
3094 optionNode.value = left_side.childNodes[i].value;
3095 optionNode.innerHTML = left_side.childNodes[i].innerHTML;
3096 document.getElementById('orderBySelect').appendChild(optionNode);
3097 if(optionNode.value == SUGAR.savedViews.selectedOrderBy)
3098 selectedIndex = nodeCount;
3101 // Firefox needs this to be set after all the option nodes are created.
3102 document.getElementById('orderBySelect').selectedIndex = selectedIndex;
3104 SUGAR.tabChooser.movementCallback(document.getElementById('display_tabs_td').getElementsByTagName('select')[0]);
3106 // This check is needed for the Activities module (Calls/Meetings/Tasks).
3107 if (document.search_form.orderBy)
3108 document.search_form.orderBy.options.value = SUGAR.savedViews.selectedOrderBy;
3111 if(SUGAR.savedViews.selectedSortOrder == 'DESC') document.getElementById('sort_order_desc_radio').checked = true;
3112 else document.getElementById('sort_order_asc_radio').checked = true;
3117 SUGAR.searchForm = function() {
3120 // searchForm tab selector util
3121 searchFormSelect: function(view, previousView) {
3122 var module = view.split('|')[0];
3123 var theView = view.split('|')[1];
3125 var handleDisplay = function() { // hide other divs
3126 document.search_form.searchFormTab.value = theView;
3127 patt = module+"(.*)SearchForm$";
3128 divId=document.search_form.getElementsByTagName('div');
3129 // Hide all the search forms and retrive the name of the previous search tab (useful for the first load because previousView is empty)
3130 for (i=0;i<divId.length;i++){
3131 if(divId[i].id.match(module)==module){
3132 if(divId[i].id.match('SearchForm')=='SearchForm'){
3133 if(document.getElementById(divId[i].id).style.display == ''){
3134 previousTab=divId[i].id.match(patt)[1];
3136 document.getElementById(divId[i].id).style.display = 'none';
3140 // show the good search form.
3141 document.getElementById(module + theView + 'SearchForm').style.display = '';
3142 //if its not the first tab show there is a previous tab.
3144 thepreviousView=previousView.split('|')[1];
3147 thepreviousView=previousTab;
3149 thepreviousView=thepreviousView.replace(/_search/, "");
3150 // Process to retrieve the completed field from one tab to an other.
3151 for(num in document.search_form.elements) {
3152 if(document.search_form.elements[num]) {
3153 el = document.search_form.elements[num];
3154 pattern="^(.*)_"+thepreviousView+"$";
3155 if(typeof el.type != 'undefined' && typeof el.name != 'undefined' && el.name.match(pattern)) {
3156 advanced_input_name = el.name.match(pattern)[1]; // strip
3157 advanced_input_name = advanced_input_name+"_"+theView.replace(/_search/, "");
3158 if(typeof document.search_form[advanced_input_name] != 'undefined') // if advanced input of same name exists
3159 SUGAR.searchForm.copyElement(advanced_input_name, el);
3165 // if tab is not cached
3166 if(document.getElementById(module + theView + 'SearchForm').innerHTML == '') {
3167 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_LOADING'));
3168 var success = function(data) {
3169 document.getElementById(module + theView + 'SearchForm').innerHTML = data.responseText;
3171 SUGAR.util.evalScript(data.responseText);
3172 // pass script variables to global scope
3173 if(theView == 'saved_views') {
3174 if(typeof columnsMeta != 'undefined') SUGAR.savedViews.columnsMeta = columnsMeta;
3175 if(typeof selectedOrderBy != 'undefined') SUGAR.savedViews.selectedOrderBy = selectedOrderBy;
3176 if(typeof selectedSortOrder != 'undefined') SUGAR.savedViews.selectedSortOrder = selectedSortOrder;
3181 ajaxStatus.hideStatus();
3183 url = 'index.php?module=' + module + '&action=index&search_form_only=true&to_pdf=true&search_form_view=' + theView;
3185 //check to see if tpl has been specified. If so then pass location through url string
3187 if(document.getElementById('search_tpl') !=null && typeof(document.getElementById('search_tpl')) != 'undefined'){
3188 tpl = document.getElementById('search_tpl').value;
3189 if(tpl != ''){url += '&search_tpl='+tpl;}
3192 if(theView == 'saved_views') // handle the tab chooser
3193 url += '&displayColumns=' + SUGAR.savedViews.displayColumns + '&hideTabs=' + SUGAR.savedViews.hideTabs + '&orderBy=' + SUGAR.savedViews.selectedOrderBy + '&sortOrder=' + SUGAR.savedViews.selectedSortOrder;
3195 var cObj = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
3197 else { // that form already retrieved
3202 // copies one input to another
3203 copyElement: function(inputName, copyFromElement) {
3204 switch(copyFromElement.type) {
3207 document.search_form[inputName].value = copyFromElement.value;
3211 // This function is here to clear the form, instead of "resubmitting it
3212 clear_form: function(form) {
3213 var elemList = form.elements;
3217 for( var i = 0; i < elemList.length ; i++ ) {
3219 if ( typeof(elem.type) == 'undefined' ) {
3223 elemType = elem.type.toLowerCase();
3225 if ( elemType == 'text' || elemType == 'textarea' || elemType == 'password' ) {
3228 else if ( elemType == 'select' || elemType == 'select-one' || elemType == 'select-multiple' ) {
3229 // We have, what I hope, is a select box, time to unselect all options
3230 var optionList = elem.options;
3231 for ( var ii = 0 ; ii < optionList.length ; ii++ ) {
3232 optionList[ii].selected = false;
3235 else if ( elemType == 'radio' || elemType == 'checkbox' ) {
3236 elem.checked = false;
3237 elem.selected = false;
3239 else if ( elemType == 'hidden' ) {
3240 // We only want to reset the hidden values that link to the select boxes.
3241 if ( ( elem.name.length > 3 && elem.name.substring(elem.name.length-3) == '_id' )
3242 || ((elem.name.length > 9) && (elem.name.substring(elem.name.length - 9) == '_id_basic'))
3243 || ( elem.name.length > 12 && elem.name.substring(elem.name.length-12) == '_id_advanced' ) ) {
3248 SUGAR.savedViews.clearColumns = true;
3252 // Code for the column/tab chooser used on homepage and in admin section
3253 SUGAR.tabChooser = function () {
3254 var object_refs = new Array();
3256 /* Describe certain transfers as invalid */
3259 movementCallback: function(left_side, right_side) {},
3260 orderCallback: function(left_side, right_side) {},
3262 freezeOptions: function(left_name, right_name, target) {
3263 if(!SUGAR.tabChooser.frozenOptions) { SUGAR.tabChooser.frozenOptions = []; }
3264 if(!SUGAR.tabChooser.frozenOptions[left_name]) { SUGAR.tabChooser.frozenOptions[left_name] = []; }
3265 if(!SUGAR.tabChooser.frozenOptions[left_name][right_name]) { SUGAR.tabChooser.frozenOptions[left_name][right_name] = []; }
3266 if(typeof target == 'array') {
3267 for(var i in target) {
3268 SUGAR.tabChooser.frozenOptions[left_name][right_name][target[i]] = true;
3271 SUGAR.tabChooser.frozenOptions[left_name][right_name][target] = true;
3275 buildSelectHTML: function(info) {
3276 var text = "<select";
3278 if(typeof (info['select']['size']) != 'undefined') {
3279 text +=" size=\""+ info['select']['size'] +"\"";
3282 if(typeof (info['select']['name']) != 'undefined') {
3283 text +=" name=\""+ info['select']['name'] +"\"";
3286 if(typeof (info['select']['style']) != 'undefined') {
3287 text +=" style=\""+ info['select']['style'] +"\"";
3290 if(typeof (info['select']['onchange']) != 'undefined') {
3291 text +=" onChange=\""+ info['select']['onchange'] +"\"";
3294 if(typeof (info['select']['multiple']) != 'undefined') {
3299 for(i=0; i<info['options'].length;i++) {
3300 option = info['options'][i];
3301 text += "<option value=\""+option['value']+"\" ";
3302 if ( typeof (option['selected']) != 'undefined' && option['selected']== true) {
3305 text += ">"+option['text']+"</option>";
3307 text += "</select>";
3311 left_to_right: function(left_name, right_name, left_size, right_size) {
3312 SUGAR.savedViews.clearColumns = false;
3313 var left_td = document.getElementById(left_name+'_td');
3314 var right_td = document.getElementById(right_name+'_td');
3316 var display_columns_ref = left_td.getElementsByTagName('select')[0];
3317 var hidden_columns_ref = right_td.getElementsByTagName('select')[0];
3319 var selected_left = new Array();
3320 var notselected_left = new Array();
3321 var notselected_right = new Array();
3323 var left_array = new Array();
3325 var frozen_options = SUGAR.tabChooser.frozenOptions;
3326 frozen_options = frozen_options && frozen_options[left_name] && frozen_options[left_name][right_name]?frozen_options[left_name][right_name]:[];
3328 // determine which options are selected in left
3329 for (i=0; i < display_columns_ref.options.length; i++)
3331 if ( display_columns_ref.options[i].selected == true && !frozen_options[display_columns_ref.options[i].value])
3333 selected_left[selected_left.length] = {text: display_columns_ref.options[i].text, value: display_columns_ref.options[i].value};
3337 notselected_left[notselected_left.length] = {text: display_columns_ref.options[i].text, value: display_columns_ref.options[i].value};
3342 for (i=0; i < hidden_columns_ref.options.length; i++)
3344 notselected_right[notselected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
3348 var left_select_html_info = new Object();
3349 var left_options = new Array();
3350 var left_select = new Object();
3352 left_select['name'] = left_name+'[]';
3353 left_select['id'] = left_name;
3354 left_select['size'] = left_size;
3355 left_select['multiple'] = 'true';
3357 var right_select_html_info = new Object();
3358 var right_options = new Array();
3359 var right_select = new Object();
3361 right_select['name'] = right_name+'[]';
3362 right_select['id'] = right_name;
3363 right_select['size'] = right_size;
3364 right_select['multiple'] = 'true';
3366 for (i = 0; i < notselected_right.length; i++) {
3367 right_options[right_options.length] = notselected_right[i];
3370 for (i = 0; i < selected_left.length; i++) {
3371 right_options[right_options.length] = selected_left[i];
3373 for (i = 0; i < notselected_left.length; i++) {
3374 left_options[left_options.length] = notselected_left[i];
3376 left_select_html_info['options'] = left_options;
3377 left_select_html_info['select'] = left_select;
3378 right_select_html_info['options'] = right_options;
3379 right_select_html_info['select'] = right_select;
3380 right_select_html_info['style'] = 'background: lightgrey';
3382 var left_html = this.buildSelectHTML(left_select_html_info);
3383 var right_html = this.buildSelectHTML(right_select_html_info);
3385 left_td.innerHTML = left_html;
3386 right_td.innerHTML = right_html;
3388 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3389 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3391 this.movementCallback(object_refs[left_name], object_refs[right_name]);
3397 right_to_left: function(left_name, right_name, left_size, right_size, max_left) {
3398 SUGAR.savedViews.clearColumns = false;
3399 var left_td = document.getElementById(left_name+'_td');
3400 var right_td = document.getElementById(right_name+'_td');
3402 var display_columns_ref = left_td.getElementsByTagName('select')[0];
3403 var hidden_columns_ref = right_td.getElementsByTagName('select')[0];
3405 var selected_right = new Array();
3406 var notselected_right = new Array();
3407 var notselected_left = new Array();
3409 var frozen_options = SUGAR.tabChooser.frozenOptions;
3410 frozen_options = SUGAR.tabChooser.frozenOptions && SUGAR.tabChooser.frozenOptions[right_name] && SUGAR.tabChooser.frozenOptions[right_name][left_name]?SUGAR.tabChooser.frozenOptions[right_name][left_name]:[];
3412 for (i=0; i < hidden_columns_ref.options.length; i++)
3414 if (hidden_columns_ref.options[i].selected == true && !frozen_options[hidden_columns_ref.options[i].value])
3416 selected_right[selected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
3420 notselected_right[notselected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
3425 if(max_left != '' && (display_columns_ref.length + selected_right.length) > max_left) {
3426 alert('Maximum of ' + max_left + ' columns can be displayed.');
3430 for (i=0; i < display_columns_ref.options.length; i++)
3432 notselected_left[notselected_left.length] = {text:display_columns_ref.options[i].text, value:display_columns_ref.options[i].value};
3436 var left_select_html_info = new Object();
3437 var left_options = new Array();
3438 var left_select = new Object();
3440 left_select['name'] = left_name+'[]';
3441 left_select['id'] = left_name;
3442 left_select['multiple'] = 'true';
3443 left_select['size'] = left_size;
3445 var right_select_html_info = new Object();
3446 var right_options = new Array();
3447 var right_select = new Object();
3449 right_select['name'] = right_name+ '[]';
3450 right_select['id'] = right_name;
3451 right_select['multiple'] = 'true';
3452 right_select['size'] = right_size;
3454 for (i = 0; i < notselected_left.length; i++) {
3455 left_options[left_options.length] = notselected_left[i];
3458 for (i = 0; i < selected_right.length; i++) {
3459 left_options[left_options.length] = selected_right[i];
3461 for (i = 0; i < notselected_right.length; i++) {
3462 right_options[right_options.length] = notselected_right[i];
3464 left_select_html_info['options'] = left_options;
3465 left_select_html_info['select'] = left_select;
3466 right_select_html_info['options'] = right_options;
3467 right_select_html_info['select'] = right_select;
3468 right_select_html_info['style'] = 'background: lightgrey';
3470 var left_html = this.buildSelectHTML(left_select_html_info);
3471 var right_html = this.buildSelectHTML(right_select_html_info);
3473 left_td.innerHTML = left_html;
3474 right_td.innerHTML = right_html;
3476 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3477 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3479 this.movementCallback(object_refs[left_name], object_refs[right_name]);
3484 up: function(name, left_name, right_name) {
3485 SUGAR.savedViews.clearColumns = false;
3486 var left_td = document.getElementById(left_name+'_td');
3487 var right_td = document.getElementById(right_name+'_td');
3488 var td = document.getElementById(name+'_td');
3489 var obj = td.getElementsByTagName('select')[0];
3490 obj = (typeof obj == "string") ? document.getElementById(obj) : obj;
3491 if (obj.tagName.toLowerCase() != "select" && obj.length < 2)
3493 var sel = new Array();
3495 for (i=0; i<obj.length; i++) {
3496 if (obj[i].selected == true) {
3497 sel[sel.length] = i;
3500 for (i=0; i < sel.length; i++) {
3501 if (sel[i] != 0 && !obj[sel[i]-1].selected) {
3502 var tmp = new Array(obj[sel[i]-1].text, obj[sel[i]-1].value);
3503 obj[sel[i]-1].text = obj[sel[i]].text;
3504 obj[sel[i]-1].value = obj[sel[i]].value;
3505 obj[sel[i]].text = tmp[0];
3506 obj[sel[i]].value = tmp[1];
3507 obj[sel[i]-1].selected = true;
3508 obj[sel[i]].selected = false;
3512 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3513 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3515 this.orderCallback(object_refs[left_name], object_refs[right_name]);
3520 down: function(name, left_name, right_name) {
3521 SUGAR.savedViews.clearColumns = false;
3522 var left_td = document.getElementById(left_name+'_td');
3523 var right_td = document.getElementById(right_name+'_td');
3524 var td = document.getElementById(name+'_td');
3525 var obj = td.getElementsByTagName('select')[0];
3526 if (obj.tagName.toLowerCase() != "select" && obj.length < 2)
3528 var sel = new Array();
3529 for (i=obj.length-1; i>-1; i--) {
3530 if (obj[i].selected == true) {
3531 sel[sel.length] = i;
3534 for (i=0; i < sel.length; i++) {
3535 if (sel[i] != obj.length-1 && !obj[sel[i]+1].selected) {
3536 var tmp = new Array(obj[sel[i]+1].text, obj[sel[i]+1].value);
3537 obj[sel[i]+1].text = obj[sel[i]].text;
3538 obj[sel[i]+1].value = obj[sel[i]].value;
3539 obj[sel[i]].text = tmp[0];
3540 obj[sel[i]].value = tmp[1];
3541 obj[sel[i]+1].selected = true;
3542 obj[sel[i]].selected = false;
3546 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3547 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3549 this.orderCallback(object_refs[left_name], object_refs[right_name]);
3554 }(); // end tabChooser
3556 SUGAR.language = function() {
3558 languages : new Array(),
3560 setLanguage: function(module, data) {
3561 if (!SUGAR.language.languages) {
3564 SUGAR.language.languages[module] = data;
3567 get: function(module, str) {
3568 if(typeof SUGAR.language.languages[module] == 'undefined' || typeof SUGAR.language.languages[module][str] == 'undefined')
3572 return SUGAR.language.languages[module][str];
3575 translate: function(module, str)
3577 text = this.get(module, str);
3578 return text != 'undefined' ? text : this.get('app_strings', str);
3583 SUGAR.contextMenu = function() {
3585 objects: new Object(),
3586 objectTypes: new Object(),
3588 * Registers a new object for the context menu.
3589 * objectType - name of the type
3591 * metaData - metaData to pass to the action function
3593 registerObject: function(objectType, id, metaData) {
3594 SUGAR.contextMenu.objects[id] = new Object();
3595 SUGAR.contextMenu.objects[id] = {'objectType' : objectType, 'metaData' : metaData};
3598 * Registers a new object type
3599 * name - name of the type
3600 * menuItems - array of menu items
3602 registerObjectType: function(name, menuItems) {
3603 SUGAR.contextMenu.objectTypes[name] = new Object();
3604 SUGAR.contextMenu.objectTypes[name] = {'menuItems' : menuItems, 'objects' : new Array()};
3607 * Determines which menu item was clicked
3609 getListItemFromEventTarget: function(p_oNode) {
3611 if(p_oNode.tagName == "LI") {
3616 if(p_oNode.tagName == "LI") {
3621 } while((p_oNode = p_oNode.parentNode));
3626 * handles movement within context menu
3628 onContextMenuMove: function() {
3629 var oNode = this.contextEventTarget;
3630 var bDisabled = (oNode.tagName == "UL");
3631 var i = this.getItemGroups()[0].length - 1;
3633 this.getItem(i).cfg.setProperty("disabled", bDisabled);
3638 * handles clicks on a context menu ITEM
3640 onContextMenuItemClick: function(p_sType, p_aArguments, p_oItem) {
3641 var oLI = SUGAR.contextMenu.getListItemFromEventTarget(this.parent.contextEventTarget);
3642 id = this.parent.contextEventTarget.parentNode.id; // id of the target
3643 funct = eval(SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[id]['objectType']]['menuItems'][this.index]['action']);
3644 funct(this.parent.contextEventTarget, SUGAR.contextMenu.objects[id]['metaData']);
3647 * Initializes all context menus registered
3650 for(var i in SUGAR.contextMenu.objects) { // make a variable called objects in objectTypes containg references to all triggers
3651 if(typeof SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'] == 'undefined')
3652 SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'] = new Array();
3653 SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'].push(document.getElementById(i));
3655 // register the menus
3656 for(var i in SUGAR.contextMenu.objectTypes) {
3657 var oContextMenu = new YAHOO.widget.ContextMenu(i, {'trigger': SUGAR.contextMenu.objectTypes[i]['objects']});
3658 var aMainMenuItems = SUGAR.contextMenu.objectTypes[i]['menuItems'];
3659 var nMainMenuItems = aMainMenuItems.length;
3661 for(var j = 0; j < nMainMenuItems; j++) {
3662 oMenuItem = new YAHOO.widget.ContextMenuItem(aMainMenuItems[j].text, { helptext: aMainMenuItems[j].helptext });
3663 oMenuItem.clickEvent.subscribe(SUGAR.contextMenu.onContextMenuItemClick, oMenuItem, true);
3664 oContextMenu.addItem(oMenuItem);
3666 // Add a "move" event handler to the context menu
3667 oContextMenu.moveEvent.subscribe(SUGAR.contextMenu.onContextMenuMove, oContextMenu, true);
3668 // Add a "keydown" event handler to the context menu
3669 oContextMenu.keyDownEvent.subscribe(SUGAR.contextMenu.onContextMenuItemClick, oContextMenu, true);
3670 // Render the context menu
3671 oContextMenu.render(document.body);
3677 SUGAR.contextMenu.actions = function() {
3680 * redirects to a new note with the clicked on object as the target
3682 createNote: function(itemClicked, metaData) {
3683 loc = 'index.php?module=Notes&action=EditView';
3684 for(i in metaData) {
3685 if(i == 'notes_parent_type') loc += '&parent_type=' + metaData[i];
3686 else if(i != 'module' && i != 'parent_type') loc += '&' + i + '=' + metaData[i];
3688 document.location = loc;
3691 * redirects to a new note with the clicked on object as the target
3693 scheduleMeeting: function(itemClicked, metaData) {
3694 loc = 'index.php?module=Meetings&action=EditView';
3695 for(i in metaData) {
3696 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3698 document.location = loc;
3701 * redirects to a new note with the clicked on object as the target
3703 scheduleCall: function(itemClicked, metaData) {
3704 loc = 'index.php?module=Calls&action=EditView';
3705 for(i in metaData) {
3706 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3708 document.location = loc;
3711 * redirects to a new contact with the clicked on object as the target
3713 createContact: function(itemClicked, metaData) {
3714 loc = 'index.php?module=Contacts&action=EditView';
3715 for(i in metaData) {
3716 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3718 document.location = loc;
3721 * redirects to a new task with the clicked on object as the target
3723 createTask: function(itemClicked, metaData) {
3724 loc = 'index.php?module=Tasks&action=EditView';
3725 for(i in metaData) {
3726 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3728 document.location = loc;
3731 * redirects to a new opportunity with the clicked on object as the target
3733 createOpportunity: function(itemClicked, metaData) {
3734 loc = 'index.php?module=Opportunities&action=EditView';
3735 for(i in metaData) {
3736 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3738 document.location = loc;
3741 * redirects to a new opportunity with the clicked on object as the target
3743 createCase: function(itemClicked, metaData) {
3744 loc = 'index.php?module=Cases&action=EditView';
3745 for(i in metaData) {
3746 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3748 document.location = loc;
3751 * handles add to favorites menu selection
3753 addToFavorites: function(itemClicked, metaData) {
3754 success = function(data) {
3756 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});
3761 //if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.contextMenu.init);
3763 // initially from popup_parent_helper.js
3764 var popup_request_data;
3767 function get_popup_request_data()
3769 return window.document.popup_request_data;
3772 function get_close_popup()
3774 return window.document.close_popup;
3777 function open_popup(module_name, width, height, initial_filter, close_popup, hide_clear_button, popup_request_data, popup_mode, create, metadata)
3779 if (typeof(popupCount) == "undefined" || popupCount == 0)
3782 // set the variables that the popup will pull from
3783 window.document.popup_request_data = popup_request_data;
3784 window.document.close_popup = close_popup;
3786 //globally changing width and height of standard pop up window from 600 x 400 to 800 x 800
3787 width = (width == 600) ? 800 : width;
3788 height = (height == 400) ? 800 : height;
3792 + 'module=' + module_name
3795 if (initial_filter != '') {
3796 URL += '&query=true' + initial_filter;
3797 // Bug 41891 - Popup Window Name
3798 popupName = initial_filter.replace(/[^a-z_0-9]+/ig, '_');
3799 windowName = module_name + '_popup_window' + popupName;
3801 windowName = module_name + '_popup_window' + popupCount;
3805 if (hide_clear_button) {
3806 URL += '&hide_clear_button=true';
3809 windowFeatures = 'width=' + width
3810 + ',height=' + height
3811 + ',resizable=1,scrollbars=1';
3813 if (popup_mode == '' && popup_mode == 'undefined') {
3814 popup_mode='single';
3816 URL+='&mode='+popup_mode;
3817 if (create == '' && create == 'undefined') {
3820 URL+='&create='+create;
3822 if (metadata != '' && metadata != 'undefined') {
3823 URL+='&metadata='+metadata;
3826 win = SUGAR.util.openWindow(URL, windowName, windowFeatures);
3830 // put the focus on the popup if the browser supports the focus() method
3834 win.popupCount = popupCount;
3840 * The reply data must be a JSON array structured with the following information:
3841 * 1) form name to populate
3842 * 2) associative array of input names to values for populating the form
3844 var from_popup_return = false;
3846 function set_return_basic(popup_reply_data,filter)
3848 var form_name = popup_reply_data.form_name;
3849 var name_to_value_array = popup_reply_data.name_to_value_array;
3850 for (var the_key in name_to_value_array)
3852 if(the_key == 'toJSON')
3856 else if(the_key.match(filter))
3858 var displayValue=name_to_value_array[the_key].replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');;
3859 // begin andopes change: support for enum fields (SELECT)
3860 if(window.document.forms[form_name] && window.document.forms[form_name].elements[the_key]) {
3861 if(window.document.forms[form_name].elements[the_key].tagName == 'SELECT') {
3862 var selectField = window.document.forms[form_name].elements[the_key];
3863 for(var i = 0; i < selectField.options.length; i++) {
3864 if(selectField.options[i].text == displayValue) {
3865 selectField.options[i].selected = true;
3870 window.document.forms[form_name].elements[the_key].value = displayValue;
3873 // end andopes change: support for enum fields (SELECT)
3878 function set_return(popup_reply_data)
3880 from_popup_return = true;
3881 var form_name = popup_reply_data.form_name;
3882 var name_to_value_array = popup_reply_data.name_to_value_array;
3883 if(typeof name_to_value_array != 'undefined' && name_to_value_array['account_id'])
3886 var label_data_str = '';
3887 var current_label_data_str = '';
3888 for (var the_key in name_to_value_array)
3890 if(the_key == 'toJSON')
3896 var displayValue=name_to_value_array[the_key].replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');
3897 if(window.document.forms[form_name] && document.getElementById(the_key+'_label') && !the_key.match(/account/)) {
3898 var data_label = document.getElementById(the_key+'_label').innerHTML.replace(/\n/gi,'');
3899 label_str += data_label + ' \n';
3900 label_data_str += data_label + ' ' + displayValue + '\n';
3901 if(window.document.forms[form_name].elements[the_key]) {
3902 current_label_data_str += data_label + ' ' + window.document.forms[form_name].elements[the_key].value +'\n';
3907 if(label_data_str != label_str && current_label_data_str != label_str){
3908 if(confirm(SUGAR.language.get('app_strings', 'NTC_OVERWRITE_ADDRESS_PHONE_CONFIRM') + '\n\n' + label_data_str))
3910 set_return_basic(popup_reply_data,/\S/);
3912 set_return_basic(popup_reply_data,/account/);
3914 }else if(label_data_str != label_str && current_label_data_str == label_str){
3915 set_return_basic(popup_reply_data,/\S/);
3916 }else if(label_data_str == label_str){
3917 set_return_basic(popup_reply_data,/account/);
3920 set_return_basic(popup_reply_data,/\S/);
3924 function set_return_and_save(popup_reply_data)
3926 var form_name = popup_reply_data.form_name;
3927 var name_to_value_array = popup_reply_data.name_to_value_array;
3929 for (var the_key in name_to_value_array)
3931 if(the_key == 'toJSON')
3937 window.document.forms[form_name].elements[the_key].value = name_to_value_array[the_key];
3941 window.document.forms[form_name].return_module.value = window.document.forms[form_name].module.value;
3942 window.document.forms[form_name].return_action.value = 'DetailView';
3943 window.document.forms[form_name].return_id.value = window.document.forms[form_name].record.value;
3944 window.document.forms[form_name].action.value = 'Save';
3945 window.document.forms[form_name].submit();
3949 * This is a helper function to construct the initial filter that can be
3950 * passed into the open_popup() function. It assumes that there is an
3951 * account_id and account_name field in the given form_name to use to
3952 * construct the intial filter string.
3954 function get_initial_filter_by_account(form_name)
3956 var account_id = window.document.forms[form_name].account_id.value;
3957 var account_name = escape(window.document.forms[form_name].account_name.value);
3958 var initial_filter = "&account_id=" + account_id + "&account_name=" + account_name;
3960 return initial_filter;
3962 // end code from popup_parent_helper.js
3964 // begin code for address copy
3966 * This is a function used by the Address widget that will fill
3967 * in the given array fields using the fromKey and toKey as a
3968 * prefix into the form objects HTML elements.
3970 * @param form The HTML form object to parse
3971 * @param fromKey The prefix of elements to copy from
3972 * @param toKey The prefix of elements to copy into
3973 * @return boolean true if successful, false otherwise
3975 function copyAddress(form, fromKey, toKey) {
3977 var elems = new Array("address_street", "address_city", "address_state", "address_postalcode", "address_country");
3978 var checkbox = document.getElementById(toKey + "_checkbox");
3980 if(typeof checkbox != "undefined") {
3981 if(!checkbox.checked) {
3983 t = toKey + "_" + elems[x];
3984 document.getElementById(t).removeAttribute('readonly');
3988 f = fromKey + "_" + elems[x];
3989 t = toKey + "_" + elems[x];
3991 document.getElementById(t).value = document.getElementById(f).value;
3992 document.getElementById(t).setAttribute('readonly', true);
3998 // end code for address copy
4001 * This function is used in Email Template Module.
4002 * It will check whether the template is used in Campaing->EmailMarketing.
4003 * If true, it will notify user.
4006 function check_deletable_EmailTemplate() {
4007 id = document.getElementsByName('record')[0].value;
4008 currentForm = document.getElementById('form');
4010 success:function(r) {
4011 if(r.responseText == 'true') {
4012 if(!confirm(SUGAR.language.get('app_strings','NTC_TEMPLATE_IS_USED'))) {
4016 if(!confirm(SUGAR.language.get('app_strings','NTC_DELETE_CONFIRMATION'))) {
4020 currentForm.return_module.value='EmailTemplates';
4021 currentForm.return_action.value='ListView';
4022 currentForm.action.value='Delete';
4023 currentForm.submit();
4026 url = "index.php?module=EmailTemplates&action=CheckDeletable&from=DetailView&to_pdf=1&record="+id;
4027 YAHOO.util.Connect.asyncRequest('POST',url, call_back,null);
4031 remove_upload_imagefile : function(field_name) {
4032 var field=document.getElementById('remove_imagefile_' + field_name);
4035 //enable the file upload button.
4036 var field=document.getElementById( field_name);
4037 field.style.display="";
4039 //hide the image and remove button.
4040 var field=document.getElementById('img_' + field_name);
4041 field.style.display="none";
4042 var field=document.getElementById('bt_remove_' + field_name);
4043 field.style.display="none";
4045 if(document.getElementById(field_name + '_duplicate')) {
4046 var field = document.getElementById(field_name + '_duplicate');
4051 confirm_imagefile : function(field_name) {
4052 var field=document.getElementById(field_name);
4053 var filename=field.value;
4054 var fileExtension = filename.substring(filename.lastIndexOf(".")+1);
4055 fileExtension = fileExtension.toLowerCase();
4056 if (fileExtension == "jpg" || fileExtension == "jpeg"
4057 || fileExtension == "gif" || fileExtension == "png" || fileExtension == "bmp"){
4062 alert(SUGAR.language.get('app_strings', 'LBL_UPLOAD_IMAGE_FILE_INVALID'));
4066 lightbox : function(image)
4068 if (typeof(SUGAR.image.lighboxWindow) == "undefined")
4069 SUGAR.image.lighboxWindow = new YAHOO.widget.SimpleDialog('sugarImageViewer', {
4072 id:'sugarMsgWindow',
4075 msg: "<img src='" + image + "'> </img>",
4078 SUGAR.image.lighboxWindow.setBody("<img src='" + image + "'> </img>");
4079 SUGAR.image.lighboxWindow.render(document.body);
4080 SUGAR.image.lighboxWindow.show();
4081 SUGAR.image.lighboxWindow.center()
4085 SUGAR.util.isTouchScreen = function()
4087 // first check if we have forced use of the touch enhanced interface
4088 if ( Get_Cookie("touchscreen") == '1' ) {
4092 // next check if we should use the touch interface with our device
4093 if ( (navigator.userAgent.match(/iPad/i) != null) ) {
4100 SUGAR.util.isLoginPage = function(content)
4102 //skip if this is packageManager screen
4103 if(SUGAR.util.isPackageManager()) {return false;}
4104 var loginPageStart = "<!DOCTYPE";
4105 if (content.substr(0, loginPageStart.length) == loginPageStart && content.indexOf("<html>") != -1 && content.indexOf("login_module") != -1) {
4106 window.location.href = window.location.protocol + window.location.pathname;
4111 SUGAR.util.isPackageManager=function(){
4112 if(typeof(document.the_form) !='undefined' && typeof(document.the_form.language_pack_escaped) !='undefined'){
4114 }else{return false;}
4117 SUGAR.util.ajaxCallInProgress = function(){
4118 return SUGAR_callsInProgress != 0;
4121 SUGAR.util.callOnChangeListers = function(field){
4122 var listeners = YAHOO.util.Event.getListeners(field, 'change');
4123 if (listeners != null) {
4124 for (var i = 0; i < listeners.length; i++) {
4125 var l = listeners[i];
4126 l.fn.call(l.scope ? l.scope : this, l.obj);
4131 SUGAR.util.closeActivityPanel = {
4132 show:function(module,id,new_status,viewType,parentContainerId){
4133 if (SUGAR.util.closeActivityPanel.panel)
4134 SUGAR.util.closeActivityPanel.panel.destroy();
4135 var singleModule = SUGAR.language.get("app_list_strings", "moduleListSingular")[module];
4136 singleModule = typeof(singleModule != 'undefined') ? singleModule.toLowerCase() : '';
4137 var closeText = SUGAR.language.get("app_strings", "LBL_CLOSE_ACTIVITY_CONFIRM").replace("#module#",singleModule);
4138 SUGAR.util.closeActivityPanel.panel =
4139 new YAHOO.widget.SimpleDialog("closeActivityDialog",
4146 constraintoviewport: true,
4147 buttons: [ { text:SUGAR.language.get("app_strings", "LBL_EMAIL_OK"), handler:function(){
4148 if (SUGAR.util.closeActivityPanel.panel)
4149 SUGAR.util.closeActivityPanel.panel.hide();
4151 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_SAVING'));
4152 var args = "action=save&id=" + id + "&record=" + id + "&status=" + new_status + "&module=" + module;
4153 // 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
4154 // TODO: Take id out and regression test. Left id in for now to not create any other unexpected problems
4155 //var args = "action=save&id=" + id + "&status=" + new_status + "&module=" + module;
4159 // 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.
4160 // So instead, we reload from a timeout
4161 window.setTimeout("window.location.reload(true);",0);
4163 argument:{'parentContainerId':parentContainerId}
4166 YAHOO.util.Connect.asyncRequest('POST', 'index.php', callback, args);
4168 }, isDefault:true },
4169 { text:SUGAR.language.get("app_strings", "LBL_EMAIL_CANCEL"), handler:function(){SUGAR.util.closeActivityPanel.panel.hide(); }} ]
4172 SUGAR.util.closeActivityPanel.panel.setHeader(SUGAR.language.get("app_strings", "LBL_CLOSE_ACTIVITY_HEADER"));
4173 SUGAR.util.closeActivityPanel.panel.render(document.body);
4174 SUGAR.util.closeActivityPanel.panel.show();
4178 SUGAR.util.setEmailPasswordDisplay = function(id, exists) {
4179 link = document.getElementById(id+'_link');
4180 pwd = document.getElementById(id);
4181 if(!pwd || !link) return;
4183 pwd.style.display = 'none';
4184 link.style.display = '';
4186 pwd.style.display = '';
4187 link.style.display = 'none';
4191 SUGAR.util.setEmailPasswordEdit = function(id) {
4192 link = document.getElementById(id+'_link');
4193 pwd = document.getElementById(id);
4194 if(!pwd || !link) return;
4195 pwd.style.display = '';
4196 link.style.display = 'none';
4200 * Compares a filename with a supplied array of allowed file extensions.
4201 * @param fileName string
4202 * @param allowedTypes array of allowed file extensions
4205 SUGAR.util.validateFileExt = function(fileName, allowedTypes) {
4206 var ext = fileName.split('.').pop();
4207 for (var i = allowedTypes.length; i >= 0; i--) {
4208 if (ext === allowedTypes[i]) {