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") {
46 * Creates a namespace if it doesn't exist and then returns it.
48 * Note: this implementation only creates a top-level namespace. Extend this function if
49 * multi-level namespaces are needed.
52 namespace: function(ns) {
53 SUGAR[ns] = SUGAR[ns] || {};
55 return ((typeof SUGAR[ns] === "object") && (SUGAR[ns] !== null)) ? SUGAR[ns] : false;
59 * Add properties of an object to target object.
63 append: function(target, obj) {
64 for (var prop in obj) {
65 if (obj[prop] !== void 0) target[prop] = obj[prop];
74 SUGAR.namespace("themes");
77 * Namespace for Homepage
79 SUGAR.namespace("sugarHome");
82 * Namespace for Subpanel Utils
84 SUGAR.namespace("subpanelUtils");
89 SUGAR.namespace("ajaxStatusClass");
94 SUGAR.namespace("tabChooser");
97 * General namespace for Sugar utils
99 SUGAR.namespace("utils");
100 SUGAR.namespace("savedViews");
105 SUGAR.namespace("dashlets");
106 SUGAR.namespace("unifiedSearchAdvanced");
108 SUGAR.namespace("searchForm");
109 SUGAR.namespace("language");
110 SUGAR.namespace("Studio");
111 SUGAR.namespace("contextMenu");
112 SUGAR.namespace("config");
116 var requiredIndex = 2;
121 var altMsgIndex = 15;
122 var compareToIndex = 7;
124 var operatorIndex = 13;
126 var validate = new Array();
128 var requiredTxt = 'Missing Required Field:'
129 var invalidTxt = 'Invalid Value:'
130 var secondsSinceLoad = 0;
131 var inputsWithErrors = new Array();
132 var tabsWithErrors = new Array();
133 var lastSubmitTime = 0;
134 var alertList = new Array();
135 var oldStartsWith = '';
140 * As of Sugar version 6.2.3 (MSIE Version 9) this function is deprecated. The preferred method is to use the
141 * user agent check supplied by YUI to check for IE:
143 * for checking if a browser is IE in general : if(YAHOO.env.ua.ie) {...}
145 * or for checking specific versions: if (YAHOO.env.ua.ie >= 5.5 && YAHOO.env.ua.ie < 9) {...}
148 function isSupportedIE() {
149 var userAgent = navigator.userAgent.toLowerCase() ;
151 // IE Check supports ActiveX controls
152 if (userAgent.indexOf("msie") != -1 && userAgent.indexOf("mac") == -1 && userAgent.indexOf("opera") == -1) {
153 var version = navigator.appVersion.match(/MSIE (.\..)/)[1] ;
154 if(version >= 5.5 && version < 10) {
162 SUGAR.isIE = isSupportedIE();
163 var isSafari = (navigator.userAgent.toLowerCase().indexOf('safari')!=-1);
165 // escapes regular expression characters
166 RegExp.escape = function(text) { // http://simon.incutio.com/archive/2006/01/20/escape
167 if (!arguments.callee.sRE) {
168 var specials = ['/', '.', '*', '+', '?', '|','(', ')', '[', ']', '{', '}', '\\'];
169 arguments.callee.sRE = new RegExp('(\\' + specials.join('|\\') + ')', 'g');
171 return text.replace(arguments.callee.sRE, '\\$1');
174 function addAlert(type, name,subtitle, description,time, redirect) {
175 var addIndex = alertList.length;
176 alertList[addIndex]= new Array();
177 alertList[addIndex]['name'] = name;
178 alertList[addIndex]['type'] = type;
179 alertList[addIndex]['subtitle'] = subtitle;
180 alertList[addIndex]['description'] = description.replace(/<br>/gi, "\n").replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');
181 alertList[addIndex]['time'] = time;
182 alertList[addIndex]['done'] = 0;
183 alertList[addIndex]['redirect'] = redirect;
185 function checkAlerts() {
186 secondsSinceLoad += 1;
189 for(mj = 0 ; mj < alertList.length; mj++) {
190 if(alertList[mj]['done'] == 0) {
191 if(alertList[mj]['time'] < secondsSinceLoad && alertList[mj]['time'] > -1 ) {
192 alertmsg = alertList[mj]['type'] + ":" + alertList[mj]['name'] + "\n" +alertList[mj]['subtitle']+ "\n"+ alertList[mj]['description'] + "\n\n";
193 alertList[mj]['done'] = 1;
194 if(alertList[mj]['redirect'] == '') {
197 else if(confirm(alertmsg)) {
198 window.location = alertList[mj]['redirect'];
204 setTimeout("checkAlerts()", 1000);
207 function toggleDisplay(id) {
208 if(this.document.getElementById(id).style.display == 'none') {
209 this.document.getElementById(id).style.display = '';
210 if(this.document.getElementById(id+"link") != undefined) {
211 this.document.getElementById(id+"link").style.display = 'none';
213 if(this.document.getElementById(id+"_anchor") != undefined)
214 this.document.getElementById(id+"_anchor").innerHTML='[ - ]';
217 this.document.getElementById(id).style.display = 'none'
218 if(this.document.getElementById(id+"link") != undefined) {
219 this.document.getElementById(id+"link").style.display = '';
221 if(this.document.getElementById(id+"_anchor") != undefined)
222 this.document.getElementById(id+"_anchor").innerHTML='[+]';
226 function checkAll(form, field, value) {
227 for (i = 0; i < form.elements.length; i++) {
228 if(form.elements[i].name == field)
229 form.elements[i].checked = value;
233 function replaceAll(text, src, rep) {
234 offset = text.toLowerCase().indexOf(src.toLowerCase());
235 while(offset != -1) {
236 text = text.substring(0, offset) + rep + text.substring(offset + src.length ,text.length);
237 offset = text.indexOf( src, offset + rep.length + 1);
242 function addForm(formname) {
243 validate[formname] = new Array();
246 function addToValidate(formname, name, type, required, msg) {
247 if(typeof validate[formname] == 'undefined') {
250 validate[formname][validate[formname].length] = new Array(name, type,required, msg);
253 function addToValidateRange(formname, name, type,required, msg,min,max) {
254 addToValidate(formname, name, type,required, msg);
255 validate[formname][validate[formname].length - 1][jstypeIndex] = 'range'
256 validate[formname][validate[formname].length - 1][minIndex] = min;
257 validate[formname][validate[formname].length - 1][maxIndex] = max;
260 function addToValidateIsValidDate(formname, name, type, required, msg) {
261 addToValidate(formname, name, type, required, msg);
262 validate[formname][validate[formname].length - 1][jstypeIndex] = 'date'
265 function addToValidateIsValidTime(formname, name, type, required, msg) {
266 addToValidate(formname, name, type, required, msg);
267 validate[formname][validate[formname].length - 1][jstypeIndex] = 'time'
270 function addToValidateDateBefore(formname, name, type, required, msg, compareTo) {
271 addToValidate(formname, name, type,required, msg);
272 validate[formname][validate[formname].length - 1][jstypeIndex] = 'isbefore'
273 validate[formname][validate[formname].length - 1][compareToIndex] = compareTo;
276 function addToValidateDateBeforeAllowBlank(formname, name, type, required, msg, compareTo, allowBlank) {
277 addToValidate(formname, name, type,required, msg);
278 validate[formname][validate[formname].length - 1][jstypeIndex] = 'isbefore'
279 validate[formname][validate[formname].length - 1][compareToIndex] = compareTo;
280 validate[formname][validate[formname].length - 1][allowblank] = allowBlank;
283 function addToValidateBinaryDependency(formname, name, type, required, msg, compareTo) {
284 addToValidate(formname, name, type, required, msg);
285 validate[formname][validate[formname].length - 1][jstypeIndex] = 'binarydep';
286 validate[formname][validate[formname].length - 1][compareToIndex] = compareTo;
289 function addToValidateComparison(formname, name, type, required, msg, compareTo) {
290 addToValidate(formname, name, type, required, msg);
291 validate[formname][validate[formname].length - 1][jstypeIndex] = 'comparison';
292 validate[formname][validate[formname].length - 1][compareToIndex] = compareTo;
295 function addToValidateIsInArray(formname, name, type, required, msg, arr, operator) {
296 addToValidate(formname, name, type, required, msg);
297 validate[formname][validate[formname].length - 1][jstypeIndex] = 'in_array';
298 validate[formname][validate[formname].length - 1][arrIndex] = arr;
299 validate[formname][validate[formname].length - 1][operatorIndex] = operator;
302 function addToValidateVerified(formname, name, type, required, msg, arr, operator) {
303 addToValidate(formname, name, type, required, msg);
304 validate[formname][validate[formname].length - 1][jstypeIndex] = 'verified';
307 function addToValidateLessThan(formname, name, type, required, msg, max, max_field_msg) {
308 addToValidate(formname, name, type, required, msg);
309 validate[formname][validate[formname].length - 1][jstypeIndex] = 'less';
310 validate[formname][validate[formname].length - 1][maxIndex] = max;
311 validate[formname][validate[formname].length - 1][altMsgIndex] = max_field_msg;
314 function addToValidateMoreThan(formname, name, type, required, msg, min) {
315 addToValidate(formname, name, type, required, msg);
316 validate[formname][validate[formname].length - 1][jstypeIndex] = 'more';
317 validate[formname][validate[formname].length - 1][minIndex] = min;
321 function removeFromValidate(formname, name) {
322 for(i = 0; i < validate[formname].length; i++)
324 if(validate[formname][i][nameIndex] == name)
326 validate[formname].splice(i--,1); // We subtract 1 from i since the slice removed an element, and we'll skip over the next item we scan
330 function checkValidate(formname, name) {
331 if(validate[formname]){
332 for(i = 0; i < validate[formname].length; i++){
333 if(validate[formname][i][nameIndex] == name){
340 var formsWithFieldLogic=null;
341 var formWithPrecision =null;
342 function addToValidateFieldLogic(formId,minFieldId, maxFieldId, defaultFieldId, lenFieldId,type,msg){
343 this.formId = document.getElementById(formId);
344 this.min=document.getElementById(minFieldId);
345 this.max= document.getElementById(maxFieldId);
346 this._default= document.getElementById(defaultFieldId);
347 this.len = document.getElementById(lenFieldId);
351 //@params: formid- Dom id of the form containing the precision and float fields
352 // valudId- Dom id of the field containing a float whose precision is to be checked.
353 // precisionId- Dom id of the field containing precision value.
354 function addToValidatePrecision(formId, valueId, precisionId){
355 this.form = document.getElementById(formId);
356 this.float = document.getElementById(valueId);
357 this.precision = document.getElementById(precisionId);
360 //function checkLength(value, referenceValue){
364 function isValidPrecision(value, precision){
365 value = trim(value.toString());
371 if( (precision == "0") ){
372 if (value.indexOf(dec_sep)== -1){
379 if(value.charAt(value.length-precision-1) == num_grp_sep){
380 if(value.substr(value.indexOf(dec_sep), 1)==dec_sep){
385 var actualPrecision = value.substr(value.indexOf(dec_sep)+1, value.length).length;
386 return actualPrecision == precision;
388 function toDecimal(original, precision) {
389 precision = (precision == null) ? 2 : precision;
390 num = Math.pow(10, precision);
391 temp = Math.round(original*num)/num;
392 if((temp * 100) % 100 == 0)
394 if((temp * 10) % 10 == 0)
399 function isInteger(s) {
400 if(typeof num_grp_sep != 'undefined' && typeof dec_sep != 'undefined')
402 s = unformatNumberNoParse(s, num_grp_sep, dec_sep).toString();
404 return /^[+-]?[0-9]*$/.test(s) ;
407 function isDecimal(s) {
408 if (typeof s == "string" && s == "") // bug# 46530, this is required in order to
409 return true; // not check empty decimal fields
411 if(typeof num_grp_sep != 'undefined' && typeof dec_sep != 'undefined')
413 s = unformatNumberNoParse(s, num_grp_sep, dec_sep).toString();
415 return /^[+-]?[0-9]+\.?[0-9]*$/.test(s) ;
418 function isNumeric(s) {
422 var date_reg_positions = {'Y': 1,'m': 2,'d': 3};
423 var date_reg_format = '([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})'
424 function isDate(dtStr) {
426 if(dtStr.length== 0) {
430 // Check that we have numbers
431 myregexp = new RegExp(date_reg_format)
432 if(!myregexp.test(dtStr))
439 var dateParts = dtStr.match(date_reg_format);
440 for(key in date_reg_positions) {
441 index = date_reg_positions[key];
443 m = dateParts[index];
444 } else if(key == 'd') {
445 d = dateParts[index];
447 y = dateParts[index];
451 // Check that date is real
452 var dd = new Date(y,m,0);
453 // reject negative years
456 // reject month less than 1 and greater than 12
459 // reject days less than 1 or days not in month (e.g. February 30th)
460 if (d < 1 || d > dd.getDate())
465 function getDateObject(dtStr) {
466 if(dtStr.length== 0) {
470 myregexp = new RegExp(date_reg_format)
472 if(myregexp.exec(dtStr)) var dt = myregexp.exec(dtStr)
475 var yr = dt[date_reg_positions['Y']];
476 var mh = dt[date_reg_positions['m']];
477 var dy = dt[date_reg_positions['d']];
478 var dtar = dtStr.split(' ');
479 if(typeof(dtar[1])!='undefined' && isTime(dtar[1])) {//if it is a timedate, we should make date1 to have time value
480 var t1 = dtar[1].replace(/am/i,' AM');
481 var t1 = t1.replace(/pm/i,' PM');
482 //bug #37977: where time format 23.00 causes java script error
483 t1=t1.replace(/\./, ':');
484 date1 = new Date(Date.parse(mh+'/'+dy+ '/'+yr+' '+t1));
488 var date1 = new Date();
489 date1.setFullYear(yr); // xxxx 4 char year
490 date1.setMonth(mh-1); // 0-11 Bug 4048: javascript Date obj months are 0-index
491 date1.setDate(dy); // 1-31
496 function isBefore(value1, value2) {
497 var d1 = getDateObject(value1);
498 var d2 = getDateObject(value2);
499 if(typeof(d2)=='boolean') {// if d2 is not set, we should let it pass, the d2 may not need to be set. the empty check should not be done here.
505 function isValidEmail(emailStr) {
507 if(emailStr.length== 0) {
510 // cn: bug 7128, a period at the end of the string mangles checks. (switched to accept spaces and delimiters)
511 var lastChar = emailStr.charAt(emailStr.length - 1);
512 if(!lastChar.match(/[^\.]/i)) {
515 //bug 40068, According to rules in page 6 of http://www.apps.ietf.org/rfc/rfc3696.html#sec-3,
516 //first character of local part of an email address
517 //should not be a period i.e. '.'
519 var firstLocalChar=emailStr.charAt(0);
520 if(firstLocalChar.match(/\./)){
524 //bug 40068, According to rules in page 6 of http://www.apps.ietf.org/rfc/rfc3696.html#sec-3,
525 //last character of local part of an email address
526 //should not be a period i.e. '.'
528 var pos=emailStr.lastIndexOf("@");
529 var localPart = emailStr.substr(0, pos);
530 var lastLocalChar=localPart.charAt(localPart.length - 1);
531 if(lastLocalChar.match(/\./)){
538 while ((results = reg.exec(emailStr)) != null) {
539 var original = results[0];
540 parsedResult = results[0].replace(';', '::;::');
541 emailStr = emailStr.replace (original, parsedResult);
545 while ((results = reg.exec(emailStr)) != null) {
546 var original = results[0];
547 //Check if we were using ; as a delimiter. If so, skip the commas
548 if(original.indexOf("::;::") == -1) {
549 var parsedResult = results[0].replace(',', '::;::');
550 emailStr = emailStr.replace (original, parsedResult);
554 // mfh: bug 15010 - more practical implementation of RFC 2822 from http://www.regular-expressions.info/email.html, modifed to accept CAPITAL LETTERS
555 //if(!/[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?/.test(emailStr))
558 //bug 40068, According to rules in page 6 of http://www.apps.ietf.org/rfc/rfc3696.html#sec-3,
559 //allowed special characters ! # $ % & ' * + - / = ? ^ _ ` . { | } ~ in local part
560 var emailArr = emailStr.split(/::;::/);
561 for (var i = 0; i < emailArr.length; i++) {
562 var emailAddress = emailArr[i];
563 if (trim(emailAddress) != '') {
564 if(!/^\s*[\w.%+\-&'#!\$\*=\?\^_`\{\}~\/]+@([A-Z0-9-]+\.)*[A-Z0-9-]+\.[\w-]{2,}\s*$/i.test(emailAddress) &&
565 !/^.*<[A-Z0-9._%+\-&'#!\$\*=\?\^_`\{\}~]+?@([A-Z0-9-]+\.)*[A-Z0-9-]+\.[\w-]{2,}>\s*$/i.test(emailAddress)) {
574 function isValidPhone(phoneStr) {
575 if(phoneStr.length== 0) {
578 if(!/^[0-9\-\(\)\s]+$/.test(phoneStr))
582 function isFloat(floatStr) {
583 if(floatStr.length== 0) {
586 if(!(typeof(num_grp_sep)=='undefined' || typeof(dec_sep)=='undefined')) {
587 floatStr = unformatNumberNoParse(floatStr, num_grp_sep, dec_sep).toString();
590 return /^(-)?[0-9\.]+$/.test(floatStr);
592 function isDBName(str) {
597 // must start with a letter
598 if(!/^[a-zA-Z][a-zA-Z\_0-9]*$/.test(str))
602 var time_reg_format = "[0-9]{1,2}\:[0-9]{2}";
603 function isTime(timeStr) {
604 var time_reg_format = "[0-9]{1,2}\:[0-9]{2}";
605 time_reg_format = time_reg_format.replace('([ap]m)', '');
606 time_reg_format = time_reg_format.replace('([AP]M)', '');
607 if(timeStr.length== 0){
610 //we now support multiple time formats
611 myregexp = new RegExp(time_reg_format)
612 if(!myregexp.test(timeStr))
618 function inRange(value, min, max) {
619 if (typeof num_grp_sep != 'undefined' && typeof dec_sep != 'undefined')
620 value = unformatNumberNoParse(value, num_grp_sep, dec_sep).toString();
621 return value >= min && value <= max;
624 function bothExist(item1, item2) {
625 if(typeof item1 == 'undefined') { return false; }
626 if(typeof item2 == 'undefined') { return false; }
627 if((item1 == '' && item2 != '') || (item1 != '' && item2 == '') ) { return false; }
631 trim = YAHOO.lang.trim;
634 function check_form(formname) {
635 if (typeof(siw) != 'undefined' && siw
636 && typeof(siw.selectingSomething) != 'undefined' && siw.selectingSomething)
638 return validate_form(formname, '');
641 function add_error_style(formname, input, txt, flash) {
642 if (typeof flash == "undefined")
645 inputHandle = typeof input == "object" ? input : document.forms[formname][input];
646 style = get_current_bgcolor(inputHandle);
648 // strip off the colon at the end of the warning strings
649 if ( txt.substring(txt.length-1) == ':' )
650 txt = txt.substring(0,txt.length-1)
652 // Bug 28249 - To help avoid duplicate messages for an element, strip off extra messages and
653 // match on the field name itself
654 requiredTxt = SUGAR.language.get('app_strings', 'ERR_MISSING_REQUIRED_FIELDS');
655 invalidTxt = SUGAR.language.get('app_strings', 'ERR_INVALID_VALUE');
656 nomatchTxt = SUGAR.language.get('app_strings', 'ERR_SQS_NO_MATCH_FIELD');
657 matchTxt = txt.replace(requiredTxt,'').replace(invalidTxt,'').replace(nomatchTxt,'');
659 if(inputHandle.parentNode.innerHTML.search(matchTxt) == -1) {
660 errorTextNode = document.createElement('div');
661 errorTextNode.className = 'required';
662 errorTextNode.innerHTML = txt;
663 if ( inputHandle.parentNode.className.indexOf('x-form-field-wrap') != -1 ) {
664 inputHandle.parentNode.parentNode.appendChild(errorTextNode);
667 inputHandle.parentNode.appendChild(errorTextNode);
670 inputHandle.style.backgroundColor = "#FF0000";
671 inputsWithErrors.push(inputHandle);
675 // We only need to setup the flashy-flashy on the first entry, it loops through all fields automatically
676 if ( inputsWithErrors.length == 1 ) {
677 for(wp = 1; wp <= 10; wp++) {
678 window.setTimeout('fade_error_style(style, '+wp*10+')',1000+(wp*50));
681 if(typeof (window[formname + "_tabs"]) != "undefined") {
682 var tabView = window[formname + "_tabs"];
683 var parentDiv = YAHOO.util.Dom.getAncestorByTagName(inputHandle, "div");
685 var tabs = tabView.get("tabs");
686 for (var i in tabs) {
687 if (tabs[i].get("contentEl") == parentDiv
688 || YAHOO.util.Dom.isAncestor(tabs[i].get("contentEl"), inputHandle))
690 tabs[i].get("labelEl").style.color = "red";
691 if ( inputsWithErrors.length == 1 )
692 tabView.selectTab(i);
697 window.setTimeout("inputsWithErrors[" + (inputsWithErrors.length - 1) + "].style.backgroundColor = '';", 2000);
701 // Catch errors here so we don't allow an incomplete record through the javascript validation
706 * removes all error messages for the current form
708 function clear_all_errors() {
709 for(var wp = 0; wp < inputsWithErrors.length; wp++) {
710 if(typeof(inputsWithErrors[wp]) !='undefined' && typeof inputsWithErrors[wp].parentNode != 'undefined' && inputsWithErrors[wp].parentNode != null) {
711 if ( inputsWithErrors[wp].parentNode.className.indexOf('x-form-field-wrap') != -1 )
713 inputsWithErrors[wp].parentNode.parentNode.removeChild(inputsWithErrors[wp].parentNode.parentNode.lastChild);
717 inputsWithErrors[wp].parentNode.removeChild(inputsWithErrors[wp].parentNode.lastChild);
721 if (inputsWithErrors.length == 0) return;
723 if ( YAHOO.util.Dom.getAncestorByTagName(inputsWithErrors[0], "form") ) {
724 var formname = YAHOO.util.Dom.getAncestorByTagName(inputsWithErrors[0], "form").getAttribute("name");
725 if(typeof (window[formname + "_tabs"]) != "undefined") {
726 var tabView = window[formname + "_tabs"];
728 var tabs = tabView.get("tabs");
729 for (var i in tabs) {
730 if (typeof tabs[i] == "object")
731 tabs[i].get("labelEl").style.color = "";
735 inputsWithErrors = new Array();
739 function get_current_bgcolor(input) {
740 if(input.currentStyle) {// ie
741 style = input.currentStyle.backgroundColor;
742 return style.substring(1,7);
746 styleRGB = document.defaultView.getComputedStyle(input, '').getPropertyValue("background-color");
747 comma = styleRGB.indexOf(',');
748 style += dec2hex(styleRGB.substring(4, comma));
749 commaPrevious = comma;
750 comma = styleRGB.indexOf(',', commaPrevious+1);
751 style += dec2hex(styleRGB.substring(commaPrevious+2, comma));
752 style += dec2hex(styleRGB.substring(comma+2, styleRGB.lastIndexOf(')')));
757 function hex2dec(hex){return(parseInt(hex,16));}
758 var hexDigit=new Array("0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F");
759 function dec2hex(dec){return(hexDigit[dec>>4]+hexDigit[dec&15]);}
761 function fade_error_style(normalStyle, percent) {
762 errorStyle = 'c60c30';
763 var r1 = hex2dec(errorStyle.slice(0,2));
764 var g1 = hex2dec(errorStyle.slice(2,4));
765 var b1 = hex2dec(errorStyle.slice(4,6));
767 var r2 = hex2dec(normalStyle.slice(0,2));
768 var g2 = hex2dec(normalStyle.slice(2,4));
769 var b2 = hex2dec(normalStyle.slice(4,6));
772 var pc = percent / 100;
774 r= Math.floor(r1+(pc*(r2-r1)) + .5);
775 g= Math.floor(g1+(pc*(g2-g1)) + .5);
776 b= Math.floor(b1+(pc*(b2-b1)) + .5);
778 for(var wp = 0; wp < inputsWithErrors.length; wp++) {
779 inputsWithErrors[wp].style.backgroundColor = "#" + dec2hex(r) + dec2hex(g) + dec2hex(b);
783 function isFieldTypeExceptFromEmptyCheck(fieldType)
786 var exemptList = ['bool','file'];
787 for(var i=0;i<exemptList.length;i++)
789 if(fieldType == exemptList[i])
794 function validate_form(formname, startsWith){
795 requiredTxt = SUGAR.language.get('app_strings', 'ERR_MISSING_REQUIRED_FIELDS');
796 invalidTxt = SUGAR.language.get('app_strings', 'ERR_INVALID_VALUE');
798 if ( typeof (formname) == 'undefined')
802 if ( typeof (validate[formname]) == 'undefined')
804 disableOnUnloadEditView(document.forms[formname]);
808 var form = document.forms[formname];
811 var _date = new Date();
812 if(_date.getTime() < (lastSubmitTime + 2000) && startsWith == oldStartsWith) { // ignore submits for the next 2 seconds
815 lastSubmitTime = _date.getTime();
816 oldStartsWith = startsWith;
818 clear_all_errors(); // remove previous error messages
820 inputsWithErrors = new Array();
821 for(var i = 0; i < validate[formname].length; i++){
822 if(validate[formname][i][nameIndex].indexOf(startsWith) == 0){
823 if(typeof form[validate[formname][i][nameIndex]] != 'undefined' && typeof form[validate[formname][i][nameIndex]].value != 'undefined'){
826 //If a field is not required and it is blank or is binarydependant, skip validation.
827 //Example of binary dependant fields would be the hour/min/meridian dropdowns in a date time combo widget, which require further processing than a blank check
828 if(!validate[formname][i][requiredIndex] && trim(form[validate[formname][i][nameIndex]].value) == '' && (typeof(validate[formname][i][jstypeIndex]) != 'undefined' && validate[formname][i][jstypeIndex] != 'binarydep'))
833 if(validate[formname][i][requiredIndex]
834 && !isFieldTypeExceptFromEmptyCheck(validate[formname][i][typeIndex])
836 if(typeof form[validate[formname][i][nameIndex]] == 'undefined' || trim(form[validate[formname][i][nameIndex]].value) == ""){
837 add_error_style(formname, validate[formname][i][nameIndex], requiredTxt +' ' + validate[formname][i][msgIndex]);
842 switch(validate[formname][i][typeIndex]){
844 if(!isValidEmail(trim(form[validate[formname][i][nameIndex]].value))){
846 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
850 if( !isTime(trim(form[validate[formname][i][nameIndex]].value))){
852 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
854 case 'date': if(!isDate(trim(form[validate[formname][i][nameIndex]].value))){
856 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
861 if(!isDBName(trim(form[validate[formname][i][nameIndex]].value))){
863 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
869 var file_input = form[validate[formname][i][nameIndex] + '_file'];
870 if( file_input && validate[formname][i][requiredIndex] && trim(file_input.value) == "" && !file_input.disabled ) {
872 add_error_style(formname, validate[formname][i][nameIndex], requiredTxt + " " + validate[formname][i][msgIndex]);
876 if(!isInteger(trim(form[validate[formname][i][nameIndex]].value))){
878 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
882 if(!isDecimal(trim(form[validate[formname][i][nameIndex]].value))){
884 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
889 if(!isFloat(trim(form[validate[formname][i][nameIndex]].value))){
891 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
895 var div_element_id = formname + '_' + form[validate[formname][i][nameIndex]].name + '_operation_div';
896 var input_elements = YAHOO.util.Selector.query('input', document.getElementById(div_element_id));
897 var primary_field_id = '';
898 var validation_passed = false;
899 var replace_selected = false;
901 //Loop through the option elements (replace or add currently)
902 for(t in input_elements) {
903 if(input_elements[t].type && input_elements[t].type == 'radio' && input_elements[t].checked == true && input_elements[t].value == 'replace') {
905 //Now find where the primary radio button is and if a value has been set
906 var radio_elements = YAHOO.util.Selector.query('input[type=radio]', document.getElementById(formname + '_team_name_table'));
908 for(var x = 0; x < radio_elements.length; x++) {
909 if(radio_elements[x].name != 'team_name_type') {
910 primary_field_id = 'team_name_collection_' + radio_elements[x].value;
911 if(radio_elements[x].checked) {
912 replace_selected = true;
913 if(trim(document.forms[formname].elements[primary_field_id].value) != '') {
914 validation_passed = true;
917 } else if(trim(document.forms[formname].elements[primary_field_id].value) != '') {
918 replace_selected = true;
925 if(replace_selected && !validation_passed) {
926 add_error_style(formname, primary_field_id, SUGAR.language.get('app_strings', 'ERR_NO_PRIMARY_TEAM_SPECIFIED'));
931 var table_element_id = formname + '_' + form[validate[formname][i][nameIndex]].name + '_table';
932 if(document.getElementById(table_element_id)) {
933 var input_elements = YAHOO.util.Selector.query('input[type=radio]', document.getElementById(table_element_id));
934 var has_primary = false;
935 var primary_field_id = form[validate[formname][i][nameIndex]].name + '_collection_0';
937 for(t in input_elements) {
938 primary_field_id = form[validate[formname][i][nameIndex]].name + '_collection_' + input_elements[t].value;
939 if(input_elements[t].type && input_elements[t].type == 'radio' && input_elements[t].checked == true) {
940 if(document.forms[formname].elements[primary_field_id].value != '') {
949 var field_id = form[validate[formname][i][nameIndex]].name + '_collection_' + input_elements[0].value;
950 add_error_style(formname, field_id, SUGAR.language.get('app_strings', 'ERR_NO_PRIMARY_TEAM_SPECIFIED'));
956 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex]);
960 if(typeof validate[formname][i][jstypeIndex] != 'undefined'/* && !isError*/){
962 switch(validate[formname][i][jstypeIndex]){
964 if(!inRange(trim(form[validate[formname][i][nameIndex]].value), validate[formname][i][minIndex], validate[formname][i][maxIndex])){
966 var lbl_validate_range = SUGAR.language.get('app_strings', 'LBL_VALIDATE_RANGE');
967 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex] + " value " + form[validate[formname][i][nameIndex]].value + " " + lbl_validate_range + " (" +validate[formname][i][minIndex] + " - " + validate[formname][i][maxIndex] + ") ");
971 compareTo = form[validate[formname][i][compareToIndex]];
972 if( typeof compareTo != 'undefined'){
973 if(trim(compareTo.value) != '' || (validate[formname][i][allowblank] != 'true') ) {
974 date2 = trim(compareTo.value);
975 date1 = trim(form[validate[formname][i][nameIndex]].value);
977 if(trim(date1).length != 0 && !isBefore(date1,date2)){
980 //jc:#12287 - adding translation for the is not before message
981 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex] + "(" + date1 + ") " + SUGAR.language.get('app_strings', 'MSG_IS_NOT_BEFORE') + ' ' +date2);
987 value=unformatNumber(trim(form[validate[formname][i][nameIndex]].value), num_grp_sep, dec_sep);
988 maximum = parseFloat(validate[formname][i][maxIndex]);
989 if( typeof maximum != 'undefined'){
992 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex] +" " +SUGAR.language.get('app_strings', 'MSG_IS_MORE_THAN')+ ' ' + validate[formname][i][altMsgIndex]);
997 value=unformatNumber(trim(form[validate[formname][i][nameIndex]].value), num_grp_sep, dec_sep);
998 minimum = parseFloat(validate[formname][i][minIndex]);
999 if( typeof minimum != 'undefined'){
1002 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex] +" " +SUGAR.language.get('app_strings', 'MSG_SHOULD_BE')+ ' ' + minimum + ' ' + SUGAR.language.get('app_strings', 'MSG_OR_GREATER'));
1007 compareTo = form[validate[formname][i][compareToIndex]];
1008 if( typeof compareTo != 'undefined') {
1009 item1 = trim(form[validate[formname][i][nameIndex]].value);
1010 item2 = trim(compareTo.value);
1011 if(!bothExist(item1, item2)) {
1013 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex]);
1018 compareTo = form[validate[formname][i][compareToIndex]];
1019 if( typeof compareTo != 'undefined') {
1020 item1 = trim(form[validate[formname][i][nameIndex]].value);
1021 item2 = trim(compareTo.value);
1022 if(!bothExist(item1, item2) || item1 != item2) {
1024 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex]);
1029 arr = eval(validate[formname][i][arrIndex]);
1030 operator = validate[formname][i][operatorIndex];
1031 item1 = trim(form[validate[formname][i][nameIndex]].value);
1032 if (operator.charAt(0) == 'u') {
1033 item1 = item1.toUpperCase();
1034 operator = operator.substring(1);
1035 } else if (operator.charAt(0) == 'l') {
1036 item1 = item1.toLowerCase();
1037 operator = operator.substring(1);
1039 for(j = 0; j < arr.length; j++){
1041 if((operator == "==" && val == item1) || (operator == "!=" && val != item1)){
1043 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
1048 if(trim(form[validate[formname][i][nameIndex]].value) == 'false'){
1049 //Fake an error so form does not submit
1059 /* nsingh: BUG#15102
1060 Check min max default field logic.
1061 Can work with float values as well, but as of 10/8/07 decimal values in MB and studio don't have min and max value constraints.*/
1062 if(formsWithFieldLogic){
1063 var invalidLogic=false;
1064 if(formsWithFieldLogic.min && formsWithFieldLogic.max && formsWithFieldLogic._default) {
1065 var showErrorsOn={min:{value:'min', show:false, obj:formsWithFieldLogic.min.value},
1066 max:{value:'max',show:false, obj:formsWithFieldLogic.max.value},
1067 _default:{value:'default',show:false, obj:formsWithFieldLogic._default.value},
1068 len:{value:'len', show:false, obj:parseInt(formsWithFieldLogic.len.value,10)}};
1070 var min = (formsWithFieldLogic.min.value !='') ? parseFloat(formsWithFieldLogic.min.value) : 'undef';
1071 var max = (formsWithFieldLogic.max.value !='') ? parseFloat(formsWithFieldLogic.max.value) : 'undef';
1072 var _default = (formsWithFieldLogic._default.value!='')? parseFloat(formsWithFieldLogic._default.value) : 'undef';
1074 /*Check all lengths are <= max size.*/
1075 for(var i in showErrorsOn){
1076 if(showErrorsOn[i].value!='len' && showErrorsOn[i].obj.length > showErrorsOn.len.obj){
1078 showErrorsOn[i].show=true;
1079 showErrorsOn.len.show=true;
1083 if(min!='undef' && max!='undef' && _default!='undef'){
1084 if(!inRange(_default,min,max)){
1086 showErrorsOn.min.show=true;
1087 showErrorsOn.max.show=true;
1088 showErrorsOn._default.show=true;
1091 if(min!='undef' && max!= 'undef' && min > max){
1092 invalidLogic = true;
1093 showErrorsOn.min.show=true;
1094 showErrorsOn.max.show=true;
1096 if(min!='undef' && _default!='undef' && _default < min){
1098 invalidLogic = true;
1099 showErrorsOn.min.show=true;
1100 showErrorsOn._default.show=true;
1102 if(max!='undef' && _default !='undef' && _default>max){
1104 invalidLogic = true;
1105 showErrorsOn.max.show=true;
1106 showErrorsOn._default.show=true;
1111 for(var error in showErrorsOn)
1112 if(showErrorsOn[error].show)
1113 add_error_style(formname,showErrorsOn[error].value, formsWithFieldLogic.msg);
1118 formsWithFieldLogic = null;
1121 if(formWithPrecision){
1122 if (!isValidPrecision(formWithPrecision.float.value, formWithPrecision.precision.value)){
1124 add_error_style(formname, 'default', SUGAR.language.get('app_strings', 'ERR_COMPATIBLE_PRECISION_VALUE'));
1132 if (isError == true) {
1134 if (self.pageYOffset) // all except Explorer
1136 nwX = self.pageXOffset;
1137 seX = self.innerWidth;
1138 nwY = self.pageYOffset;
1139 seY = self.innerHeight;
1141 else if (document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
1143 nwX = document.documentElement.scrollLeft;
1144 seX = document.documentElement.clientWidth;
1145 nwY = document.documentElement.scrollTop;
1146 seY = document.documentElement.clientHeight;
1148 else if (document.body) // all other Explorers
1150 nwX = document.body.scrollLeft;
1151 seX = document.body.clientWidth;
1152 nwY = document.body.scrollTop;
1153 seY = document.body.clientHeight;
1156 var inView = true; // is there an error within viewport of browser
1157 for(var wp = 0; wp < inputsWithErrors.length; wp++) {
1158 var elementCoor = findElementPos(inputsWithErrors[wp]);
1159 if(!(elementCoor.x >= nwX && elementCoor.y >= nwY &&
1160 elementCoor.x <= seX && elementCoor.y <= seY)) { // if input is not within viewport
1162 scrollToTop = elementCoor.y - 75;
1163 scrollToLeft = elementCoor.x - 75;
1165 else { // on first input within viewport, don't scroll
1171 if(!inView) window.scrollTo(scrollToLeft,scrollToTop);
1176 disableOnUnloadEditView(form);
1183 * This array is used to remember mark status of rows in browse mode
1185 var marked_row = new Array;
1189 * Sets/unsets the pointer and marker in browse mode
1191 * @param object the table row
1192 * @param interger the row number
1193 * @param string the action calling this script (over, out or click)
1194 * @param string the default background color
1195 * @param string the color to use for mouseover
1196 * @param string the color to use for marking a row
1198 * @return boolean whether pointer is set or not
1200 function setPointer(theRow, theRowNum, theAction, theDefaultColor, thePointerColor, theMarkColor) {
1201 var theCells = null;
1203 // 1. Pointer and mark feature are disabled or the browser can't get the
1205 if ((thePointerColor == '' && theMarkColor == '')
1206 || typeof(theRow.style) == 'undefined') {
1210 // 2. Gets the current row and exits if the browser can't get it
1211 if (typeof(document.getElementsByTagName) != 'undefined') {
1212 theCells = theRow.getElementsByTagName('td');
1214 else if (typeof(theRow.cells) != 'undefined') {
1215 theCells = theRow.cells;
1221 // 3. Gets the current color...
1222 var rowCellsCnt = theCells.length;
1223 var domDetect = null;
1224 var currentColor = null;
1225 var newColor = null;
1226 // 3.1 ... with DOM compatible browsers except Opera that does not return
1227 // valid values with "getAttribute"
1228 if (typeof(window.opera) == 'undefined'
1229 && typeof(theCells[0].getAttribute) != 'undefined') {
1230 currentColor = theCells[0].getAttribute('bgcolor');
1233 // 3.2 ... with other browsers
1235 currentColor = theCells[0].style.backgroundColor;
1239 // 4. Defines the new color
1240 // 4.1 Current color is the default one
1241 if (currentColor == ''
1242 || (currentColor!= null && (currentColor.toLowerCase() == theDefaultColor.toLowerCase()))) {
1243 if (theAction == 'over' && thePointerColor != '') {
1244 newColor = thePointerColor;
1246 else if (theAction == 'click' && theMarkColor != '') {
1247 newColor = theMarkColor;
1248 marked_row[theRowNum] = true;
1251 // 4.1.2 Current color is the pointer one
1252 else if (currentColor!= null && (currentColor.toLowerCase() == thePointerColor.toLowerCase())
1253 && (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])) {
1254 if (theAction == 'out') {
1255 newColor = theDefaultColor;
1257 else if (theAction == 'click' && theMarkColor != '') {
1258 newColor = theMarkColor;
1259 marked_row[theRowNum] = true;
1262 // 4.1.3 Current color is the marker one
1263 else if (currentColor!= null && (currentColor.toLowerCase() == theMarkColor.toLowerCase())) {
1264 if (theAction == 'click') {
1265 newColor = (thePointerColor != '')
1268 marked_row[theRowNum] = (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])
1274 // 5. Sets the new color...
1277 // 5.1 ... with DOM compatible browsers except Opera
1279 for (c = 0; c < rowCellsCnt; c++) {
1280 theCells[c].setAttribute('bgcolor', newColor, 0);
1283 // 5.2 ... with other browsers
1285 for (c = 0; c < rowCellsCnt; c++) {
1286 theCells[c].style.backgroundColor = newColor;
1292 } // end of the 'setPointer()' function
1296 * listbox redirection
1298 function goToUrl(selObj, goToLocation) {
1299 eval("document.location.href = '" + goToLocation + "pos=" + selObj.options[selObj.selectedIndex].value + "'");
1304 var json_objects = new Object();
1306 function getXMLHTTPinstance() {
1307 var xmlhttp = false;
1308 var userAgent = navigator.userAgent.toLowerCase() ;
1310 // IE Check supports ActiveX controls
1311 if (userAgent.indexOf("msie") != -1 && userAgent.indexOf("mac") == -1 && userAgent.indexOf("opera") == -1) {
1312 var version = navigator.appVersion.match(/MSIE (.\..)/)[1] ;
1313 if(version >= 5.5 ) {
1315 xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
1319 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
1328 if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
1329 xmlhttp = new XMLHttpRequest();
1334 // NOW LOAD THE OBJECT..
1335 var global_xmlhttp = getXMLHTTPinstance();
1337 function http_fetch_sync(url,post_data) {
1338 global_xmlhttp = getXMLHTTPinstance();
1341 if(typeof(post_data) != 'undefined') method = 'POST';
1343 global_xmlhttp.open(method, url,false);
1346 alert('message:'+e.message+":url:"+url);
1348 if(method == 'POST') {
1349 global_xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
1352 global_xmlhttp.send(post_data);
1354 if (SUGAR.util.isLoginPage(global_xmlhttp.responseText))
1357 var args = {"responseText" : global_xmlhttp.responseText,
1358 "responseXML" : global_xmlhttp.responseXML,
1359 "request_id" : typeof(request_id) != "undefined" ? request_id : 0};
1363 // this is a GET unless post_data is defined
1365 function http_fetch_async(url,callback,request_id,post_data) {
1367 if(typeof(post_data) != 'undefined') {
1372 global_xmlhttp.open(method, url,true);
1375 alert('message:'+e.message+":url:"+url);
1377 if(method == 'POST') {
1378 global_xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
1380 global_xmlhttp.onreadystatechange = function() {
1381 if(global_xmlhttp.readyState==4) {
1382 if(global_xmlhttp.status == 200) {
1383 if (SUGAR.util.isLoginPage(global_xmlhttp.responseText))
1385 var args = {"responseText" : global_xmlhttp.responseText,
1386 "responseXML" : global_xmlhttp.responseXML,
1387 "request_id" : request_id };
1388 callback.call(document,args);
1391 alert("There was a problem retrieving the XML data:\n" + global_xmlhttp.statusText);
1395 global_xmlhttp.send(post_data);
1398 function call_json_method(module,action,vars,variable_name,callback) {
1399 global_xmlhttp.open("GET", "index.php?entryPoint=json&module="+module+"&action="+action+"&"+vars,true);
1400 global_xmlhttp.onreadystatechange=
1402 if(global_xmlhttp.readyState==4) {
1403 if(global_xmlhttp.status == 200) {
1404 // cn: bug 12274 - pass through JSON.parse() to remove security envelope
1405 json_objects[variable_name] = JSON.parse(global_xmlhttp.responseText);
1407 // cn: bug 12274 - safe from CSRF, render response as expected
1408 var respText = YAHOO.lang.JSON.stringify(global_xmlhttp.responseText);
1409 var args = {responseText:respText, responseXML:global_xmlhttp.responseXML};
1410 callback.call(document, args);
1413 alert("There was a problem retrieving the XML data:\n" + global_xmlhttp.statusText);
1417 global_xmlhttp.send(null);
1420 function insert_at_cursor(field, value) {
1422 if (document.selection) {
1424 sel = document.selection.createRange();
1428 else if(field.selectionStart || field.selectionStart == '0') {
1429 var start_pos = field.selectionStart;
1430 var end_pos = field.selectionEnd;
1431 field.value = field.value.substring(0, start_pos) + value + field.value.substring(end_pos, field.value.length);
1434 field.value += value;
1438 function checkParentType(type,button) {
1439 if(button == null) {
1442 if(typeof disabledModules != 'undefined' && typeof(disabledModules[type]) != 'undefined') {
1443 button.disabled='disabled';
1446 button.disabled = false;
1450 function parseDate(input, format) {
1452 format = format.replace(/%/g, '');
1453 sep = format.charAt(1);
1454 yAt = format.indexOf('Y')
1455 // 1-1-06 or 1-12-06 or 1-1-2006 or 1-12-2006
1456 if(date.match(/^\d{1,2}[\/-]\d{1,2}[\/-]\d{2,4}$/) && yAt == 4) {
1457 if(date.match(/^\d{1}[\/-].*$/)) date = '0' + date;
1458 if(date.match(/^\d{2}[\/-]\d{1}[\/-].*$/)) date = date.substring(0,3) + '0' + date.substring(3,date.length);
1459 if(date.match(/^\d{2}[\/-]\d{2}[\/-]\d{2}$/)) date = date.substring(0,6) + '20' + date.substring(6,date.length);
1461 // 06-11-1 or 06-1-1
1462 else if(date.match(/^\d{2,4}[\/-]\d{1,2}[\/-]\d{1,2}$/)) {
1463 if(date.match(/^\d{2}[\/-].*$/)) date = '20' + date;
1464 if(date.match(/^\d{4}[\/-]\d{1}[\/-].*$/)) date = date.substring(0,5) + '0' + date.substring(5,date.length);
1465 if(date.match(/^\d{4}[\/-]\d{2}[\/-]\d{1}$/)) date = date.substring(0,8) + '0' + date.substring(8,date.length);
1467 else if(date.match(/^\d{4,8}$/)) { // digits only
1469 if(date.match(/^\d{8}$/)) digits = 8;// match for 8 digits
1470 else if(date.match(/\d{6}/)) digits = 6;// match for 5 digits
1471 else if(date.match(/\d{4}/)) digits = 4;// match for 5 digits
1472 else if(date.match(/\d{5}/)) digits = 5;// match for 5 digits
1477 case 4: date = '20' + date.substring(0,2) + sep + '0' + date.substring(2, 3) + sep + '0' + date.substring(3,4); break;
1478 case 5: date = '20' + date.substring(0,2) + sep + date.substring(2, 4) + sep + '0' + date.substring(4,5); break;
1479 case 6: date = '20' + date.substring(0,2) + sep + date.substring(2, 4) + sep + date.substring(4,6); break;
1480 case 8: date = date.substring(0,4) + sep + date.substring(4, 6) + sep + date.substring(6,8); break;
1485 case 4: date = '0' + date.substring(0,1) + sep + '20' + date.substring(1, 3) + sep + '0' + date.substring(3,4); break;
1486 case 5: date = date.substring(0,2) + sep + '20' + date.substring(2, 4) + sep + '0' + date.substring(4,5); break;
1487 case 6: date = date.substring(0,2) + sep + '20' + date.substring(2, 4) + sep + date.substring(4,6); break;
1488 case 8: date = date.substring(0,2) + sep + date.substring(2, 6) + sep + date.substring(6,8); break;
1492 case 4: date = '0' + date.substring(0,1) + sep + '0' + date.substring(1, 2) + sep + '20' + date.substring(2,4); break;
1493 case 5: date = '0' + date.substring(0,1) + sep + date.substring(1, 3) + sep + '20' + date.substring(3,5); break;
1494 case 6: date = date.substring(0,2) + sep + date.substring(2, 4) + sep + '20' + date.substring(4,6); break;
1495 case 8: date = date.substring(0,2) + sep + date.substring(2, 4) + sep + date.substring(4,8); break;
1500 date = date.replace(/[\/-]/g, sep);
1504 // find obj's position
1505 function findElementPos(obj) {
1508 if (obj.offsetParent) {
1509 while (obj.offsetParent) {
1510 x += obj.offsetLeft;
1512 obj = obj.offsetParent;
1514 }//if offsetParent exists
1515 else if (obj.x && obj.y) {
1519 return new coordinate(x, y);
1523 // get dimensions of the browser window
1524 function getClientDim() {
1525 var nwX, nwY, seX, seY;
1526 if (self.pageYOffset) // all except Explorer
1528 nwX = self.pageXOffset;
1529 seX = self.innerWidth + nwX;
1530 nwY = self.pageYOffset;
1531 seY = self.innerHeight + nwY;
1533 else if (document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
1535 nwX = document.documentElement.scrollLeft;
1536 seX = document.documentElement.clientWidth + nwX;
1537 nwY = document.documentElement.scrollTop;
1538 seY = document.documentElement.clientHeight + nwY;
1540 else if (document.body) // all other Explorers
1542 nwX = document.body.scrollLeft;
1543 seX = document.body.clientWidth + nwX;
1544 nwY = document.body.scrollTop;
1545 seY = document.body.clientHeight + nwY;
1547 return {'nw' : new coordinate(nwX, nwY), 'se' : new coordinate(seX, seY)};
1551 * stop propagation on events
1553 function freezeEvent(e) {
1555 if (e.preventDefault) e.preventDefault();
1556 e.returnValue = false;
1557 e.cancelBubble = true;
1558 if (e.stopPropagation) e.stopPropagation();
1567 function coordinate(_x, _y) {
1576 return new position(this.x + rh.x, this.y + rh.y);
1580 return new position(this.x + rh.x, this.y + rh.y);
1584 // sends theForm via AJAX and fills in the theDiv
1585 function sendAndRetrieve(theForm, theDiv, loadingStr) {
1586 function success(data) {
1587 document.getElementById(theDiv).innerHTML = data.responseText;
1588 ajaxStatus.hideStatus();
1590 if(typeof loadingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
1591 ajaxStatus.showStatus(loadingStr);
1592 YAHOO.util.Connect.setForm(theForm);
1593 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
1597 //save the form and redirect
1598 function sendAndRedirect(theForm, loadingStr, redirect_location) {
1599 function success(data) {
1600 if(redirect_location){
1601 location.href=redirect_location;
1603 ajaxStatus.hideStatus();
1605 if(typeof loadingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
1606 ajaxStatus.showStatus(loadingStr);
1607 YAHOO.util.Connect.setForm(theForm);
1608 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
1612 function saveForm(theForm, theDiv, loadingStr) {
1613 if(check_form(theForm)){
1614 for(i = 0; i < ajaxFormArray.length; i++){
1615 if(ajaxFormArray[i] == theForm){
1616 ajaxFormArray.splice(i, 1);
1619 return sendAndRetrieve(theForm, loadingStr, theDiv);
1625 // Builds a "snapshot" of the form, so we can use it to see if someone has changed it.
1626 function snapshotForm(theForm) {
1627 var snapshotTxt = '';
1628 var elemList = theForm.elements;
1632 for( var i = 0; i < elemList.length ; i++ ) {
1634 if ( typeof(elem.type) == 'undefined' ) {
1638 elemType = elem.type.toLowerCase();
1640 snapshotTxt = snapshotTxt + elem.name;
1642 if ( elemType == 'text' || elemType == 'textarea' || elemType == 'password' ) {
1643 snapshotTxt = snapshotTxt + elem.value;
1645 else if ( elemType == 'select' || elemType == 'select-one' || elemType == 'select-multiple' ) {
1646 var optionList = elem.options;
1647 for ( var ii = 0 ; ii < optionList.length ; ii++ ) {
1648 if ( optionList[ii].selected ) {
1649 snapshotTxt = snapshotTxt + optionList[ii].value;
1653 else if ( elemType == 'radio' || elemType == 'checkbox' ) {
1654 if ( elem.selected ) {
1655 snapshotTxt = snapshotTxt + 'checked';
1658 else if ( elemType == 'hidden' ) {
1659 snapshotTxt = snapshotTxt + elem.value;
1666 function initEditView(theForm) {
1667 if (SUGAR.util.ajaxCallInProgress()) {
1668 window.setTimeout(function(){initEditView(theForm);}, 100);
1672 if ( theForm == null || theForm.id == null ) {
1673 // Not much we can do here.
1677 // we don't need to check if the data is changed in the search popup
1678 if (theForm.id == 'popup_query_form' || theForm.id == 'MassUpdate') {
1681 if ( typeof editViewSnapshots == 'undefined' || editViewSnapshots == null ) {
1682 editViewSnapshots = new Object();
1684 if ( typeof SUGAR.loadedForms == 'undefined' || SUGAR.loadedForms == null) {
1685 SUGAR.loadedForms = new Object();
1688 editViewSnapshots[theForm.id] = snapshotForm(theForm);
1689 SUGAR.loadedForms[theForm.id] = true;
1692 function onUnloadEditView(theForm) {
1694 var dataHasChanged = false;
1696 if ( typeof editViewSnapshots == 'undefined' ) {
1697 // No snapshots, move along
1701 if ( typeof theForm == 'undefined' ) {
1702 // Need to check all editViewSnapshots
1703 for ( var idx in editViewSnapshots ) {
1705 theForm = document.getElementById(idx);
1706 // console.log('DEBUG: Checking all forms '+theForm.id);
1707 if ( theForm == null
1708 || typeof editViewSnapshots[theForm.id] == 'undefined'
1709 || editViewSnapshots[theForm.id] == null
1710 || !SUGAR.loadedForms[theForm.id]) {
1714 var snap = snapshotForm(theForm);
1715 if ( editViewSnapshots[theForm.id] != snap ) {
1716 dataHasChanged = true;
1720 // Just need to check a single form for changes
1721 if ( editViewSnapshots == null || typeof theForm.id == 'undefined' || typeof editViewSnapshots[theForm.id] == 'undefined' || editViewSnapshots[theForm.id] == null ) {
1725 // console.log('DEBUG: Checking one form '+theForm.id);
1726 if ( editViewSnapshots[theForm.id] != snapshotForm(theForm) ) {
1727 // Data has changed.
1728 dataHasChanged = true;
1732 if ( dataHasChanged == true ) {
1733 return SUGAR.language.get('app_strings','WARN_UNSAVED_CHANGES');
1740 function disableOnUnloadEditView(theForm) {
1741 // If you don't pass anything in, it disables all checking
1742 if ( typeof theForm == 'undefined' || typeof editViewSnapshots == 'undefined' || theForm == null || editViewSnapshots == null) {
1743 window.onbeforeunload = null;
1744 editViewSnapshots = null;
1746 // console.log('DEBUG: Disabling all edit view checks');
1749 // Otherwise, it just disables it for this form
1750 if ( typeof(theForm.id) != 'undefined' && typeof(editViewSnapshots[theForm.id]) != 'undefined' ) {
1751 editViewSnapshots[theForm.id] = null;
1754 // console.log('DEBUG : Disabling just checks for '+theForm.id);
1760 * save some forms using an ajax call
1761 * theForms - the ids of all of theh forms to save
1762 * savingStr - the string to display when saving the form
1763 * completeStr - the string to display when the form has been saved
1765 function saveForms( savingStr, completeStr) {
1767 theForms = ajaxFormArray;
1768 function success(data) {
1769 var theForm = document.getElementById(ajaxFormArray[0]);
1770 document.getElementById('multiedit_'+theForm.id).innerHTML = data.responseText;
1771 var saveAllButton = document.getElementById('ajaxsaveall');
1772 ajaxFormArray.splice(index, 1);
1773 if(saveAllButton && ajaxFormArray.length <= 1){
1774 saveAllButton.style.visibility = 'hidden';
1777 if(index == theForms.length){
1778 ajaxStatus.showStatus(completeStr);
1779 window.setTimeout('ajaxStatus.hideStatus();', 2000);
1781 saveAllButton.style.visibility = 'hidden';
1786 if(typeof savingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
1787 ajaxStatus.showStatus(savingStr);
1789 //loop through the forms saving each one
1790 for(i = 0; i < theForms.length; i++){
1791 var theForm = document.getElementById(theForms[i]);
1792 if(check_form(theForm.id)){
1793 theForm.action.value='AjaxFormSave';
1794 YAHOO.util.Connect.setForm(theForm);
1795 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
1797 ajaxStatus.hideStatus();
1799 lastSubmitTime = lastSubmitTime-2000;
1804 // -- start sugarListView class
1805 // js functions used for ListView
1806 function sugarListView() {
1810 sugarListView.prototype.confirm_action = function(del) {
1812 return confirm( SUGAR.language.get('app_strings', 'NTC_DELETE_CONFIRMATION_NUM') + sugarListView.get_num_selected() + SUGAR.language.get('app_strings', 'NTC_DELETE_SELECTED_RECORDS'));
1815 return confirm( SUGAR.language.get('app_strings', 'NTC_UPDATE_CONFIRMATION_NUM') + sugarListView.get_num_selected() + SUGAR.language.get('app_strings', 'NTC_DELETE_SELECTED_RECORDS'));
1819 sugarListView.get_num_selected = function () {
1820 if(typeof document.MassUpdate != 'undefined') {
1821 the_form = document.MassUpdate;
1822 for(wp = 0; wp < the_form.elements.length; wp++) {
1823 if(typeof the_form.elements[wp].name != 'undefined' && the_form.elements[wp].name == 'selectCount[]') {
1824 return the_form.elements[wp].value;
1831 sugarListView.update_count = function(count, add) {
1832 if(typeof document.MassUpdate != 'undefined') {
1833 the_form = document.MassUpdate;
1834 for(wp = 0; wp < the_form.elements.length; wp++) {
1835 if(typeof the_form.elements[wp].name != 'undefined' && the_form.elements[wp].name == 'selectCount[]') {
1837 the_form.elements[wp].value = parseInt(the_form.elements[wp].value,10) + count;
1838 if (the_form.select_entire_list.value == 1 && the_form.show_plus.value) {
1839 the_form.elements[wp].value += '+';
1842 if (the_form.select_entire_list.value == 1 && the_form.show_plus.value) {
1843 the_form.elements[wp].value = count + '+';
1845 the_form.elements[wp].value = count;
1852 sugarListView.prototype.use_external_mail_client = function(no_record_txt, module) {
1853 selected_records = sugarListView.get_checks_count();
1854 if(selected_records <1) {
1855 alert(no_record_txt);
1859 if (document.MassUpdate.select_entire_list.value == 1) {
1860 if (totalCount > 10) {
1861 alert(totalCountError);
1866 else if (document.MassUpdate.massall.checked == true)
1870 sugarListView.get_checks();
1872 if(select) { // use selected items
1873 ids = document.MassUpdate.uid.value;
1875 else { // use current page
1876 inputs = document.MassUpdate.elements;
1878 for(i = 0; i < inputs.length; i++) {
1879 if(inputs[i].name == 'mass[]' && inputs[i].checked && typeof(inputs[i].value) != 'function') {
1880 ar.push(inputs[i].value);
1885 YAHOO.util.Connect.asyncRequest("POST", "index.php?", {
1886 success: this.use_external_mail_client_callback
1887 }, SUGAR.util.paramsToUrl({
1890 listViewExternalClient: 1,
1891 action_module: module,
1899 sugarListView.prototype.use_external_mail_client_callback = function(o)
1902 location.href = 'mailto:' + o.responseText;
1905 sugarListView.prototype.send_form_for_emails = function(select, currentModule, action, no_record_txt,action_module,totalCount, totalCountError) {
1906 if ( typeof(SUGAR.config.email_sugarclient_listviewmaxselect) != 'undefined' ) {
1910 maxCount = SUGAR.config.email_sugarclient_listviewmaxselect;
1913 if (document.MassUpdate.select_entire_list.value == 1) {
1914 if (totalCount > maxCount) {
1915 alert(totalCountError);
1920 else if (document.MassUpdate.massall.checked == true)
1925 sugarListView.get_checks();
1926 // create new form to post (can't access action property of MassUpdate form due to action input)
1927 var newForm = document.createElement('form');
1928 newForm.method = 'post';
1929 newForm.action = action;
1930 newForm.name = 'newForm';
1931 newForm.id = 'newForm';
1932 var uidTa = document.createElement('textarea');
1934 uidTa.style.display = 'none';
1936 if(select) { // use selected items
1937 uidTa.value = document.MassUpdate.uid.value;
1939 else { // use current page
1940 inputs = document.MassUpdate.elements;
1942 for(i = 0; i < inputs.length; i++) {
1943 if(inputs[i].name == 'mass[]' && inputs[i].checked && typeof(inputs[i].value) != 'function') {
1944 ar.push(inputs[i].value);
1947 uidTa.value = ar.join(',');
1950 if(uidTa.value == '') {
1951 alert(no_record_txt);
1955 var selectedArray = uidTa.value.split(",");
1956 if(selectedArray.length > maxCount) {
1957 alert(totalCountError);
1960 newForm.appendChild(uidTa);
1962 var moduleInput = document.createElement('input');
1963 moduleInput.name = 'module';
1964 moduleInput.type = 'hidden';
1965 moduleInput.value = currentModule;
1966 newForm.appendChild(moduleInput);
1968 var actionInput = document.createElement('input');
1969 actionInput.name = 'action';
1970 actionInput.type = 'hidden';
1971 actionInput.value = 'Compose';
1972 newForm.appendChild(actionInput);
1974 if (typeof action_module != 'undefined' && action_module!= '') {
1975 var actionModule = document.createElement('input');
1976 actionModule.name = 'action_module';
1977 actionModule.type = 'hidden';
1978 actionModule.value = action_module;
1979 newForm.appendChild(actionModule);
1981 //return_info must follow this pattern."&return_module=Accounts&return_action=index"
1982 if (typeof return_info!= 'undefined' && return_info != '') {
1983 var params= return_info.split('&');
1984 if (params.length > 0) {
1985 for (var i=0;i< params.length;i++) {
1986 if (params[i].length > 0) {
1987 var param_nv=params[i].split('=');
1988 if (param_nv.length==2){
1989 returnModule = document.createElement('input');
1990 returnModule.name = param_nv[0];
1991 returnModule.type = 'hidden';
1992 returnModule.value = param_nv[1];
1993 newForm.appendChild(returnModule);
2000 var isAjaxCall = document.createElement('input');
2001 isAjaxCall.name = 'ajaxCall';
2002 isAjaxCall.type = 'hidden';
2003 isAjaxCall.value = true;
2004 newForm.appendChild(isAjaxCall);
2006 var isListView = document.createElement('input');
2007 isListView.name = 'ListView';
2008 isListView.type = 'hidden';
2009 isListView.value = true;
2010 newForm.appendChild(isListView);
2012 var toPdf = document.createElement('input');
2013 toPdf.name = 'to_pdf';
2014 toPdf.type = 'hidden';
2016 newForm.appendChild(toPdf);
2018 //Grab the Quick Compose package for the listview
2019 YAHOO.util.Connect.setForm(newForm);
2022 success: function(o) {
2023 var resp = YAHOO.lang.JSON.parse(o.responseText);
2024 var quickComposePackage = new Object();
2025 quickComposePackage.composePackage = resp;
2026 quickComposePackage.fullComposeUrl = 'index.php?module=Emails&action=Compose&ListView=true' +
2027 '&uid=' + uidTa.value + '&action_module=' + action_module;
2029 SUGAR.quickCompose.init(quickComposePackage);
2033 YAHOO.util.Connect.asyncRequest('POST','index.php', callback,null);
2035 // awu Bug 18624: Fixing issue where a canceled Export and unselect of row will persist the uid field, clear the field
2036 document.MassUpdate.uid.value = '';
2041 sugarListView.prototype.send_form = function(select, currentModule, action, no_record_txt,action_module,return_info) {
2042 if (document.MassUpdate.select_entire_list.value == 1) {
2044 if(sugarListView.get_checks_count() < 1) {
2045 alert(no_record_txt);
2050 if ( action.indexOf('?') != -1 )
2051 href += '&module=' + currentModule;
2053 href += '?module=' + currentModule;
2056 href += return_info;
2057 var newForm = document.createElement('form');
2058 newForm.method = 'post';
2059 newForm.action = href;
2060 newForm.name = 'newForm';
2061 newForm.id = 'newForm';
2062 var postTa = document.createElement('textarea');
2063 postTa.name = 'current_post';
2064 postTa.value = document.MassUpdate.current_query_by_page.value;
2065 postTa.style.display = 'none';
2066 newForm.appendChild(postTa);
2067 document.MassUpdate.parentNode.appendChild(newForm);
2071 else if (document.MassUpdate.massall.checked == true)
2076 sugarListView.get_checks();
2077 // create new form to post (can't access action property of MassUpdate form due to action input)
2078 var newForm = document.createElement('form');
2079 newForm.method = 'post';
2080 newForm.action = action;
2081 newForm.name = 'newForm';
2082 newForm.id = 'newForm';
2083 var uidTa = document.createElement('textarea');
2085 uidTa.style.display = 'none';
2086 uidTa.value = document.MassUpdate.uid.value;
2088 if(uidTa.value == '') {
2089 alert(no_record_txt);
2093 newForm.appendChild(uidTa);
2095 var moduleInput = document.createElement('input');
2096 moduleInput.name = 'module';
2097 moduleInput.type = 'hidden';
2098 moduleInput.value = currentModule;
2099 newForm.appendChild(moduleInput);
2101 var actionInput = document.createElement('input');
2102 actionInput.name = 'action';
2103 actionInput.type = 'hidden';
2104 actionInput.value = 'index';
2105 newForm.appendChild(actionInput);
2107 if (typeof action_module != 'undefined' && action_module!= '') {
2108 var actionModule = document.createElement('input');
2109 actionModule.name = 'action_module';
2110 actionModule.type = 'hidden';
2111 actionModule.value = action_module;
2112 newForm.appendChild(actionModule);
2114 //return_info must follow this pattern."&return_module=Accounts&return_action=index"
2115 if (typeof return_info!= 'undefined' && return_info != '') {
2116 var params= return_info.split('&');
2117 if (params.length > 0) {
2118 for (var i=0;i< params.length;i++) {
2119 if (params[i].length > 0) {
2120 var param_nv=params[i].split('=');
2121 if (param_nv.length==2){
2122 returnModule = document.createElement('input');
2123 returnModule.name = param_nv[0];
2124 returnModule.type = 'hidden';
2125 returnModule.value = param_nv[1];
2126 newForm.appendChild(returnModule);
2133 document.MassUpdate.parentNode.appendChild(newForm);
2136 // awu Bug 18624: Fixing issue where a canceled Export and unselect of row will persist the uid field, clear the field
2137 document.MassUpdate.uid.value = '';
2141 //return a count of checked row.
2142 sugarListView.get_checks_count = function() {
2145 if(document.MassUpdate.uid.value != '') {
2146 oldUids = document.MassUpdate.uid.value.split(',');
2147 for(uid in oldUids) {
2148 if(typeof(oldUids[uid]) != 'function') {
2149 ar[oldUids[uid]] = 1;
2153 // build associated array of uids, associated array ensures uniqueness
2154 inputs = document.MassUpdate.elements;
2155 for(i = 0; i < inputs.length; i++) {
2156 if(inputs[i].name == 'mass[]') {
2157 ar[inputs[i].value] = (inputs[i].checked) ? 1 : 0; // 0 of it is unchecked
2161 // build regular array of uids
2164 if((typeof(ar[i]) != 'function') && ar[i] == 1) {
2172 // saves the checks on the current page into the uid textarea
2173 sugarListView.get_checks = function() {
2176 if(document.MassUpdate.uid.value != '') {
2177 oldUids = document.MassUpdate.uid.value.split(',');
2178 for(uid in oldUids) {
2179 if(typeof(oldUids[uid]) != 'function') {
2180 ar[oldUids[uid]] = 1;
2185 // build associated array of uids, associated array ensures uniqueness
2186 inputs = document.MassUpdate.elements;
2187 for(i = 0; i < inputs.length; i++) {
2188 if(inputs[i].name == 'mass[]') {
2189 ar[inputs[i].value] = (inputs[i].checked) ? 1 : 0; // 0 of it is unchecked
2193 // build regular array of uids
2196 if(typeof(ar[i]) != 'function' && ar[i] == 1) {
2201 document.MassUpdate.uid.value = uids.join(',');
2203 if(uids.length == 0) return false; // return false if no checks to get
2204 return true; // there are saved checks
2207 sugarListView.prototype.order_checks = function(order,orderBy,moduleString){
2208 checks = sugarListView.get_checks();
2209 eval('document.MassUpdate.' + moduleString + '.value = orderBy');
2210 document.MassUpdate.lvso.value = order;
2211 if(typeof document.MassUpdate.massupdate != 'undefined') {
2212 document.MassUpdate.massupdate.value = 'false';
2215 //we must first clear the action of massupdate, change it to index
2216 document.MassUpdate.action.value = document.MassUpdate.return_action.value;
2217 document.MassUpdate.return_module.value='';
2218 document.MassUpdate.return_action.value='';
2219 document.MassUpdate.submit();
2223 sugarListView.prototype.save_checks = function(offset, moduleString) {
2224 checks = sugarListView.get_checks();
2225 eval('document.MassUpdate.' + moduleString + '.value = offset');
2227 if(typeof document.MassUpdate.massupdate != 'undefined') {
2228 document.MassUpdate.massupdate.value = 'false';
2231 //we must first clear the action of massupdate, change it to index
2232 document.MassUpdate.action.value = document.MassUpdate.return_action.value;
2233 document.MassUpdate.return_module.value='';
2234 document.MassUpdate.return_action.value='';
2235 document.MassUpdate.submit();
2241 sugarListView.prototype.check_item = function(cb, form) {
2243 sugarListView.update_count(1, true);
2245 sugarListView.update_count(-1, true);
2246 if(typeof form != 'undefined' && form != null) {
2247 sugarListView.prototype.updateUid(cb, form);
2252 /**#28000, remove the unselect record id from MassUpdate.uid **/
2253 sugarListView.prototype.updateUid = function(cb , form){
2254 if(form.name == 'MassUpdate' && form.uid && form.uid.value && cb.value && form.uid.value.indexOf(cb.value) != -1){
2255 if(form.uid.value.indexOf(','+cb.value)!= -1){
2256 form.uid.value = form.uid.value.replace(','+cb.value , '');
2257 }else if(form.uid.value.indexOf(cb.value + ',')!= -1){
2258 form.uid.value = form.uid.value.replace(cb.value + ',' , '');
2259 }else if(form.uid.value.indexOf(cb.value)!= -1){
2260 form.uid.value = form.uid.value.replace(cb.value , '');
2265 sugarListView.prototype.check_entire_list = function(form, field, value, list_count) {
2266 // count number of items
2268 document.MassUpdate.massall.checked = true;
2269 document.MassUpdate.massall.disabled = true;
2271 for (i = 0; i < form.elements.length; i++) {
2272 if(form.elements[i].name == field && form.elements[i].disabled == false) {
2273 if(form.elements[i].checked != value) count++;
2274 form.elements[i].checked = value;
2275 form.elements[i].disabled = true;
2278 document.MassUpdate.select_entire_list.value = 1;
2280 sugarListView.update_count(list_count, false);
2281 //else sugarListView.update_count(-1 * count, true);
2284 sugarListView.prototype.check_all = function(form, field, value, pageTotal) {
2285 // count number of items
2287 document.MassUpdate.massall.checked = value;
2288 if (document.MassUpdate.select_entire_list &&
2289 document.MassUpdate.select_entire_list.value == 1)
2290 document.MassUpdate.massall.disabled = true;
2292 document.MassUpdate.massall.disabled = false;
2294 for (i = 0; i < form.elements.length; i++) {
2295 if(form.elements[i].name == field && !(form.elements[i].disabled == true && form.elements[i].checked == false)) {
2296 form.elements[i].disabled = false;
2298 if(form.elements[i].checked != value)
2300 form.elements[i].checked = value;
2302 sugarListView.prototype.updateUid(form.elements[i], form);
2307 sugarListView.update_count(pageTotal);
2309 sugarListView.update_count(count, true);
2311 sugarListView.update_count(-1 * count, true);
2313 sugarListView.check_all = sugarListView.prototype.check_all;
2314 sugarListView.confirm_action = sugarListView.prototype.confirm_action;
2316 sugarListView.prototype.check_boxes = function() {
2317 var inputsCount = 0;
2318 var checkedCount = 0;
2319 var existing_onload = window.onload;
2320 var theForm = document.MassUpdate;
2321 inputs_array = theForm.elements;
2323 if(typeof theForm.uid.value != 'undefined' && theForm.uid.value != "") {
2324 checked_items = theForm.uid.value.split(",");
2325 if (theForm.select_entire_list.value == 1)
2326 document.MassUpdate.massall.disabled = true;
2328 for(wp = 0 ; wp < inputs_array.length; wp++) {
2329 if(inputs_array[wp].name == "mass[]") {
2331 if (theForm.select_entire_list.value == 1) {
2332 inputs_array[wp].checked = true;
2333 inputs_array[wp].disabled = true;
2337 for(i in checked_items) {
2338 if(inputs_array[wp].value == checked_items[i]) {
2340 inputs_array[wp].checked = true;
2346 if (theForm.select_entire_list.value == 0)
2347 sugarListView.update_count(checked_items.length);
2349 sugarListView.update_count(0, true);
2353 for(wp = 0 ; wp < inputs_array.length; wp++) {
2354 if(inputs_array[wp].name == "mass[]") {
2355 inputs_array[wp].checked = false;
2356 inputs_array[wp].disabled = false;
2359 if (document.MassUpdate.massall) {
2360 document.MassUpdate.massall.checked = false;
2361 document.MassUpdate.massall.disabled = false;
2363 sugarListView.update_count(0)
2365 if(checkedCount > 0 && checkedCount == inputsCount)
2366 document.MassUpdate.massall.checked = true;
2372 * This function is used in Email Template Module's listview.
2373 * It will check whether the templates are used in Campaing->EmailMarketing.
2374 * If true, it will notify user.
2376 function check_used_email_templates() {
2377 var ids = document.MassUpdate.uid.value;
2379 success:function(r) {
2380 if(r.responseText != '') {
2381 if(!confirm(SUGAR.language.get('app_strings','NTC_TEMPLATES_IS_USED') + r.responseText)) {
2385 document.MassUpdate.submit();
2389 url = "index.php?module=EmailTemplates&action=CheckDeletable&from=ListView&to_pdf=1&records="+ids;
2390 YAHOO.util.Connect.asyncRequest('POST',url, call_back,null);
2394 sugarListView.prototype.send_mass_update = function(mode, no_record_txt, del) {
2395 formValid = check_form('MassUpdate');
2396 if(!formValid && !del) return false;
2399 if (document.MassUpdate.select_entire_list &&
2400 document.MassUpdate.select_entire_list.value == 1)
2405 var ar = new Array();
2409 for(wp = 0; wp < document.MassUpdate.elements.length; wp++) {
2410 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)+'$');
2411 //when the uid is already in document.MassUpdate.uid.value, we should not add it to ar.
2412 if(typeof document.MassUpdate.elements[wp].name != 'undefined'
2413 && document.MassUpdate.elements[wp].name == 'mass[]'
2414 && document.MassUpdate.elements[wp].checked
2415 && !reg_for_existing_uid.test(document.MassUpdate.uid.value)) {
2416 ar.push(document.MassUpdate.elements[wp].value);
2419 if(document.MassUpdate.uid.value != '') document.MassUpdate.uid.value += ',';
2420 document.MassUpdate.uid.value += ar.join(',');
2421 if(document.MassUpdate.uid.value == '') {
2422 alert(no_record_txt);
2425 if(typeof(current_admin_id)!='undefined' && document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'Users' && (document.MassUpdate.is_admin.value!='' || document.MassUpdate.status.value!='')) {
2426 var reg_for_current_admin_id = new RegExp('^'+current_admin_id+'[\s]*,|,[\s]*'+current_admin_id+'[\s]*,|,[\s]*'+current_admin_id+'$|^'+current_admin_id+'$');
2427 if(reg_for_current_admin_id.test(document.MassUpdate.uid.value)) {
2428 //if current user is admin, we should not allow massupdate the user_type and status of himself
2429 alert(SUGAR.language.get('Users','LBL_LAST_ADMIN_NOTICE'));
2435 var entireInput = document.createElement('input');
2436 entireInput.name = 'entire';
2437 entireInput.type = 'hidden';
2438 entireInput.value = 'index';
2439 document.MassUpdate.appendChild(entireInput);
2440 //confirm(no_record_txt);
2441 if(document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'Users' && (document.MassUpdate.is_admin.value!='' || document.MassUpdate.status.value!='')) {
2442 alert(SUGAR.language.get('Users','LBL_LAST_ADMIN_NOTICE'));
2448 if(!sugarListView.confirm_action(del))
2452 var deleteInput = document.createElement('input');
2453 deleteInput.name = 'Delete';
2454 deleteInput.type = 'hidden';
2455 deleteInput.value = true;
2456 document.MassUpdate.appendChild(deleteInput);
2457 if(document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'EmailTemplates') {
2458 check_used_email_templates();
2464 document.MassUpdate.submit();
2469 sugarListView.prototype.clear_all = function() {
2470 document.MassUpdate.uid.value = '';
2471 document.MassUpdate.select_entire_list.value = 0;
2472 sugarListView.check_all(document.MassUpdate, 'mass[]', false);
2473 document.MassUpdate.massall.checked = false;
2474 document.MassUpdate.massall.disabled = false;
2475 sugarListView.update_count(0);
2478 sListView = new sugarListView();
2479 // -- end sugarListView class
2481 // format and unformat numbers
2482 function unformatNumber(n, num_grp_sep, dec_sep) {
2483 var x=unformatNumberNoParse(n, num_grp_sep, dec_sep);
2486 return parseFloat(x);
2491 function unformatNumberNoParse(n, num_grp_sep, dec_sep) {
2492 if(typeof num_grp_sep == 'undefined' || typeof dec_sep == 'undefined') return n;
2493 n = n ? n.toString() : '';
2496 if(num_grp_sep != '')
2498 num_grp_sep_re = new RegExp('\\'+num_grp_sep, 'g');
2499 n = n.replace(num_grp_sep_re, '');
2502 n = n.replace(dec_sep, '.');
2504 if(typeof CurrencySymbols != 'undefined') {
2505 // Need to strip out the currency symbols from the start.
2506 for ( var idx in CurrencySymbols ) {
2507 n = n.replace(CurrencySymbols[idx], '');
2515 // round parameter can be negative for decimal, precision has to be postive
2516 function formatNumber(n, num_grp_sep, dec_sep, round, precision) {
2517 if(typeof num_grp_sep == 'undefined' || typeof dec_sep == 'undefined') return n;
2518 n = n ? n.toString() : '';
2519 if(n.split) n = n.split('.');
2522 if(n.length > 2) return n.join('.'); // that's not a num!
2524 if(typeof round != 'undefined') {
2525 if(round > 0 && n.length > 1) { // round to decimal
2526 n[1] = parseFloat('0.' + n[1]);
2527 n[1] = Math.round(n[1] * Math.pow(10, round)) / Math.pow(10, round);
2528 n[1] = n[1].toString().split('.')[1];
2530 if(round <= 0) { // round to whole number
2531 n[0] = Math.round(parseInt(n[0],10) * Math.pow(10, round)) / Math.pow(10, round);
2536 if(typeof precision != 'undefined' && precision >= 0) {
2537 if(n.length > 1 && typeof n[1] != 'undefined') n[1] = n[1].substring(0, precision); // cut off precision
2539 if(n[1].length < precision) {
2540 for(var wp = n[1].length; wp < precision; wp++) n[1] += '0';
2544 regex = /(\d+)(\d{3})/;
2545 while(num_grp_sep != '' && regex.test(n[0])) n[0] = n[0].toString().replace(regex, '$1' + num_grp_sep + '$2');
2546 return n[0] + (n.length > 1 && n[1] != '' ? dec_sep + n[1] : '');
2549 // --- begin ajax status class
2550 SUGAR.ajaxStatusClass = function() {};
2551 SUGAR.ajaxStatusClass.prototype.statusDiv = null;
2552 SUGAR.ajaxStatusClass.prototype.oldOnScroll = null;
2553 SUGAR.ajaxStatusClass.prototype.shown = false; // state of the status window
2555 // reposition the status div, top and centered
2556 SUGAR.ajaxStatusClass.prototype.positionStatus = function() {
2557 //this.statusDiv.style.top = document.body.scrollTop + 8 + 'px';
2558 statusDivRegion = YAHOO.util.Dom.getRegion(this.statusDiv);
2559 statusDivWidth = statusDivRegion.right - statusDivRegion.left;
2560 this.statusDiv.style.left = YAHOO.util.Dom.getViewportWidth() / 2 - statusDivWidth / 2 + 'px';
2563 // private func, create the status div
2564 SUGAR.ajaxStatusClass.prototype.createStatus = function(text) {
2565 statusDiv = document.createElement('div');
2566 statusDiv.className = 'dataLabel';
2567 statusDiv.id = 'ajaxStatusDiv';
2568 document.body.appendChild(statusDiv);
2569 this.statusDiv = document.getElementById('ajaxStatusDiv');
2572 // public - show the status div with text
2573 SUGAR.ajaxStatusClass.prototype.showStatus = function(text) {
2574 if(!this.statusDiv) {
2575 this.createStatus(text);
2578 this.statusDiv.style.display = '';
2580 this.statusDiv.innerHTML = ' <b>' + text + '</b> ';
2581 this.positionStatus();
2584 this.statusDiv.style.display = '';
2585 if(window.onscroll) this.oldOnScroll = window.onscroll; // save onScroll
2586 window.onscroll = this.positionStatus;
2591 SUGAR.ajaxStatusClass.prototype.hideStatus = function(text) {
2592 if(!this.shown) return;
2594 if(this.oldOnScroll) window.onscroll = this.oldOnScroll;
2595 else window.onscroll = '';
2596 this.statusDiv.style.display = 'none';
2599 SUGAR.ajaxStatusClass.prototype.flashStatus = function(text, time){
2600 this.showStatus(text);
2601 window.setTimeout('ajaxStatus.hideStatus();', time);
2605 var ajaxStatus = new SUGAR.ajaxStatusClass();
2606 // --- end ajax status class
2609 * Unified Search Advanced - for global search
2611 SUGAR.unifiedSearchAdvanced = function() {
2621 SUGAR.unifiedSearchAdvanced.usa_div = document.getElementById('unified_search_advanced_div');
2622 SUGAR.unifiedSearchAdvanced.usa_img = document.getElementById('unified_search_advanced_img');
2624 if(!SUGAR.unifiedSearchAdvanced.usa_div || !SUGAR.unifiedSearchAdvanced.usa_img) return;
2625 var attributes = { height: { to: 300 } };
2626 SUGAR.unifiedSearchAdvanced.anim_open = new YAHOO.util.Anim('unified_search_advanced_div', attributes );
2627 SUGAR.unifiedSearchAdvanced.anim_open.duration = 0.75;
2628 SUGAR.unifiedSearchAdvanced.anim_close = new YAHOO.util.Anim('unified_search_advanced_div', { height: {to: 0} } );
2629 SUGAR.unifiedSearchAdvanced.anim_close.duration = 0.75;
2630 //SUGAR.unifiedSearchAdvanced.anim_close.onComplete.subscribe(function() {SUGAR.unifiedSearchAdvanced.usa_div.style.display = 'none'});
2632 SUGAR.unifiedSearchAdvanced.usa_img._x = YAHOO.util.Dom.getX(SUGAR.unifiedSearchAdvanced.usa_img);
2633 SUGAR.unifiedSearchAdvanced.usa_img._y = YAHOO.util.Dom.getY(SUGAR.unifiedSearchAdvanced.usa_img);
2636 SUGAR.unifiedSearchAdvanced.usa_open = false;
2637 SUGAR.unifiedSearchAdvanced.usa_content = null;
2639 YAHOO.util.Event.addListener('unified_search_advanced_img', 'click', SUGAR.unifiedSearchAdvanced.get_content);
2642 get_content: function(e)
2644 query_string = trim(document.getElementById('query_string').value);
2645 if(query_string != '')
2647 window.location.href = 'index.php?module=Home&action=UnifiedSearch&query_string=' + query_string;
2649 window.location.href = 'index.php?module=Home&action=UnifiedSearch&form_only=true';
2653 animate: function(data) {
2654 ajaxStatus.hideStatus();
2657 SUGAR.unifiedSearchAdvanced.usa_content = data.responseText;
2658 SUGAR.unifiedSearchAdvanced.usa_div.innerHTML = SUGAR.unifiedSearchAdvanced.usa_content;
2660 if(SUGAR.unifiedSearchAdvanced.usa_open) {
2661 document.UnifiedSearch.advanced.value = 'false';
2662 SUGAR.unifiedSearchAdvanced.anim_close.animate();
2665 document.UnifiedSearch.advanced.value = 'true';
2666 SUGAR.unifiedSearchAdvanced.usa_div.style.display = '';
2667 YAHOO.util.Dom.setX(SUGAR.unifiedSearchAdvanced.usa_div, SUGAR.unifiedSearchAdvanced.usa_img._x - 90);
2668 YAHOO.util.Dom.setY(SUGAR.unifiedSearchAdvanced.usa_div, SUGAR.unifiedSearchAdvanced.usa_img._y + 15);
2669 SUGAR.unifiedSearchAdvanced.anim_open.animate();
2671 SUGAR.unifiedSearchAdvanced.usa_open = !SUGAR.unifiedSearchAdvanced.usa_open;
2676 checkUsaAdvanced: function() {
2677 if(document.UnifiedSearch.advanced.value == 'true') {
2678 document.UnifiedSearchAdvanced.query_string.value = document.UnifiedSearch.query_string.value;
2679 document.UnifiedSearchAdvanced.submit();
2686 if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.unifiedSearchAdvanced.init);
2691 * Toggles the header
2693 toggleHeader : function() {
2694 var h = document.getElementById('header');
2698 if(h.style.display == 'none') {
2699 h.style.display = '';
2701 h.style.display = 'none';
2705 alert(SUGAR.language.get("app_strings", "ERR_NO_HEADER_ID"));
2712 * General Sugar Utils
2714 SUGAR.util = function () {
2715 var additionalDetailsCache;
2716 var additionalDetailsCalls;
2717 var additionalDetailsRpcCall;
2720 getAndRemove : function (el) {
2721 if (YAHOO && YAHOO.util && YAHOO.util.Dom)
2722 el = YAHOO.util.Dom.get(el);
2723 else if (typeof (el) == "string")
2724 el = document.getElementById(el);
2725 if (el && el.parentNode)
2726 el.parentNode.removeChild(el);
2730 paramsToUrl : function (params) {
2733 url += i + "=" + params[i] + "&";
2737 evalScript:function(text){
2739 var waitUntilLoaded = function(){
2740 SUGAR.evalScript_waitCount--;
2741 if (SUGAR.evalScript_waitCount == 0) {
2742 var headElem = document.getElementsByTagName('head')[0];
2743 for ( var i = 0; i < SUGAR.evalScript_evalElem.length; i++) {
2744 var tmpElem = document.createElement('script');
2745 tmpElem.type = 'text/javascript';
2746 tmpElem.text = SUGAR.evalScript_evalElem[i];
2747 headElem.appendChild(tmpElem);
2752 var tmpElem = document.createElement('div');
2753 tmpElem.innerHTML = text;
2754 var results = tmpElem.getElementsByTagName('script');
2755 if (results == null) {
2756 // No scripts found, bail out
2760 var headElem = document.getElementsByTagName('head')[0];
2762 SUGAR.evalScript_waitCount = 0;
2763 SUGAR.evalScript_evalElem = new Array();
2764 for (var i = 0; i < results.length; i++) {
2765 if (typeof(results[i]) != 'object') {
2768 tmpElem = document.createElement('script');
2769 tmpElem.type = 'text/javascript';
2770 if (results[i].src != null && results[i].src != '') {
2771 tmpElem.src = results[i].src;
2773 // Need to defer execution of these scripts until the
2774 // required javascript files are fully loaded
2775 SUGAR.evalScript_evalElem[SUGAR.evalScript_evalElem.length] = results[i].text;
2778 tmpElem.addEventListener('load', waitUntilLoaded);
2779 SUGAR.evalScript_waitCount++;
2780 headElem.appendChild(tmpElem);
2782 // Add some code to handle pages without any external scripts
2783 SUGAR.evalScript_waitCount++;
2786 // Don't try and process things the IE way
2790 var objRegex = /<\s*script([^>]*)>((.|\s|\v|\0)*?)<\s*\/script\s*>/igm;
2792 var result = objRegex.exec(text);
2793 while(result && result.index > lastIndex){
2794 lastIndex = result.index
2796 var script = document.createElement('script');
2797 script.type= 'text/javascript';
2798 if(result[1].indexOf("src=") > -1){
2799 var srcRegex = /.*src=['"]([a-zA-Z0-9_\&\/\.\?=:]*)['"].*/igm;
2800 var srcResult = result[1].replace(srcRegex, '$1');
2801 script.src = srcResult;
2803 script.text = result[2];
2805 document.body.appendChild(script);
2808 if(typeof(console) != "undefined" && typeof(console.log) == "function")
2810 console.log("error adding script");
2812 console.log(result);
2815 result = objRegex.exec(text);
2819 * Gets the sidebar object
2820 * @return object pointer to the sidebar element
2822 getLeftColObj: function() {
2823 leftColObj = document.getElementById('leftCol');
2824 while(leftColObj.nodeName != 'TABLE') {
2825 leftColObj = leftColObj.firstChild;
2827 leftColTable = leftColObj;
2828 leftColTd = leftColTable.getElementsByTagName('td')[0];
2829 leftColTdRegion = YAHOO.util.Dom.getRegion(leftColTd);
2830 leftColTd.style.width = (leftColTdRegion.right - leftColTdRegion.left) + 'px';
2835 * Fills the shortcut menu placeholders w/ actual content
2836 * Call this on load event
2838 * @param shortcutContent Array array of content to fill in
2840 fillShortcuts: function(e, shortcutContent) {
2843 // don't do this if leftCol isn't available
2844 if (document.getElementById('leftCol') == undefined) { return; }
2846 spans = document.getElementById('leftCol').getElementsByTagName('span');
2847 hideCol = document.getElementById('HideMenu').getElementsByTagName('span');
2848 w = spans.length + 1;
2850 spans[w] = hideCol[i];
2853 for(je in shortcutContent) {
2855 if(typeof spans[wp].innerHTML != 'undefined' && spans[wp].innerHTML == ('wp_shortcut_fill_' + je)) {
2856 if(typeof spans[wp].parentNode.parentNode == 'object') {
2857 if(typeof spans[wp].parentNode.parentNode.onclick != 'undefined') {
2858 spans[wp].parentNode.parentNode.onclick = null;
2860 // If the wp_shortcut span is contained by an A tag, replace the A with a DIV.
2861 if(spans[wp].parentNode.tagName == 'A' && !isIE) {
2862 var newDiv = document.createElement('DIV');
2863 var parentAnchor = spans[wp].parentNode;
2865 spans[wp].parentNode.parentNode.style.display = 'none';
2867 // Copy styles over to the new container div
2868 if(window.getComputedStyle) {
2869 var parentStyle = window.getComputedStyle(parentAnchor, '');
2870 for(var styleName in parentStyle) {
2871 if(typeof parentStyle[styleName] != 'function'
2872 && styleName != 'display'
2873 && styleName != 'borderWidth'
2874 && styleName != 'visibility') {
2876 newDiv.style[styleName] = parentStyle[styleName];
2878 // Catches .length and .parentRule, and others
2884 // Replace the A with the DIV
2885 newDiv.appendChild(spans[wp]);
2886 parentAnchor.parentNode.replaceChild(newDiv, parentAnchor);
2888 spans[wp].parentNode.parentNode.style.display = '';
2891 spans[wp].innerHTML = shortcutContent[je]; // fill w/ content
2892 if(spans[wp].style) spans[wp].style.display = '';
2898 * Make an AJAX request.
2900 * @param url string resource to load
2901 * @param theDiv string id of element to insert loaded data into
2902 * @param postForm string if set, a POST request will be made to resource specified by url using the form named by postForm
2903 * @param callback string name of function to invoke after HTTP response is recieved
2904 * @param callbackParam any parameter to pass to callback when invoked
2905 * @param appendMode bool if true, HTTP response will be appended to the contents of theDiv, or else contents will be overriten.
2907 retrieveAndFill: function(url, theDiv, postForm, callback, callbackParam, appendMode) {
2908 if(typeof theDiv == 'string') {
2910 theDiv = document.getElementById(theDiv);
2917 var success = function(data) {
2918 if (typeof theDiv != 'undefined' && theDiv != null)
2921 if (typeof appendMode != 'undefined' && appendMode)
2923 theDiv.innerHTML += data.responseText;
2927 theDiv.innerHTML = data.responseText;
2934 if (typeof callback != 'undefined' && callback != null) callback(callbackParam);
2937 if(typeof postForm == 'undefined' || postForm == null) {
2938 var cObj = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
2941 YAHOO.util.Connect.setForm(postForm);
2942 var cObj = YAHOO.util.Connect.asyncRequest('POST', url, {success: success, failure: success});
2945 checkMaxLength: function() { // modified from http://www.quirksmode.org/dom/maxlength.html
2946 var maxLength = this.getAttribute('maxlength');
2947 var currentLength = this.value.length;
2948 if (currentLength > maxLength) {
2949 this.value = this.value.substring(0, maxLength);
2954 * Adds maxlength attribute to textareas
2956 setMaxLength: function() { // modified from http://www.quirksmode.org/dom/maxlength.html
2957 var x = document.getElementsByTagName('textarea');
2958 for (var i=0;i<x.length;i++) {
2959 if (x[i].getAttribute('maxlength')) {
2960 x[i].onkeyup = x[i].onchange = SUGAR.util.checkMaxLength;
2967 * Retrieves additional details dynamically
2969 getAdditionalDetails: function(bean, id, spanId) {
2971 oReturn = function(body, caption, width, theme) {
2972 var _refx = 25-width;
2973 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);
2976 success = function(data) {
2977 eval(data.responseText);
2979 SUGAR.util.additionalDetailsCache[spanId] = new Array();
2980 SUGAR.util.additionalDetailsCache[spanId]['body'] = result['body'];
2981 SUGAR.util.additionalDetailsCache[spanId]['caption'] = result['caption'];
2982 SUGAR.util.additionalDetailsCache[spanId]['width'] = result['width'];
2983 SUGAR.util.additionalDetailsCache[spanId]['theme'] = result['theme'];
2984 ajaxStatus.hideStatus();
2985 return oReturn(SUGAR.util.additionalDetailsCache[spanId]['body'], SUGAR.util.additionalDetailsCache[spanId]['caption'], SUGAR.util.additionalDetailsCache[spanId]['width'], SUGAR.util.additionalDetailsCache[spanId]['theme']);
2988 if(typeof SUGAR.util.additionalDetailsCache[spanId] != 'undefined')
2989 return oReturn(SUGAR.util.additionalDetailsCache[spanId]['body'], SUGAR.util.additionalDetailsCache[spanId]['caption'], SUGAR.util.additionalDetailsCache[spanId]['width'], SUGAR.util.additionalDetailsCache[spanId]['theme']);
2991 if(typeof SUGAR.util.additionalDetailsCalls[spanId] != 'undefined') // call already in progress
2993 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_LOADING'));
2994 url = 'index.php?to_pdf=1&module=Home&action=AdditionalDetailsRetrieve&bean=' + bean + '&id=' + id;
2995 SUGAR.util.additionalDetailsCalls[spanId] = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
2999 SUGAR.util.additionalDetailsRpcCall = window.setTimeout('go()', 250);
3001 clearAdditionalDetailsCall: function() {
3002 if(typeof SUGAR.util.additionalDetailsRpcCall == 'number') window.clearTimeout(SUGAR.util.additionalDetailsRpcCall);
3005 * A function that extends functionality from parent to child.
3007 extend : function(subc, superc, overrides) {
3008 subc.prototype = new superc; // set the superclass
3011 for (var i in overrides) subc.prototype[i] = overrides[i];
3014 hrefURL : function(url) {
3016 // IE needs special treatment since otherwise it would not pass Referer
3017 var trampoline = document.createElement('a');
3018 trampoline.href = url;
3019 document.body.appendChild(trampoline);
3021 document.body.removeChild(trampoline);
3023 document.location.href = url;
3027 openWindow : function(URL, windowName, windowFeatures) {
3029 // IE needs special treatment since otherwise it would not pass Referer
3030 win = window.open('', windowName, windowFeatures);
3031 var trampoline = document.createElement('a');
3032 trampoline.href = URL;
3033 trampoline.target = windowName;
3034 document.body.appendChild(trampoline);
3036 document.body.removeChild(trampoline);
3038 win = window.open(URL, windowName, windowFeatures);
3042 //Reset the scroll on the window
3047 //Based on YUI onAvailible, but will use any boolean function instead of an ID
3048 doWhen : function(condition, fn, params, scope)
3050 this._doWhenStack.push({
3054 overrideContext: scope
3057 this._doWhenretryCount = 50;
3058 this._startDoWhenInterval();
3061 _startDoWhenInterval : function(){
3062 if (!this._doWhenInterval) {
3063 this._doWhenInterval = YAHOO.lang.later(50, this, this._doWhenCheck, null, true);
3067 _doWhenInterval : false,
3068 _doWhenCheck : function() {
3069 if (this._doWhenStack.length === 0) {
3070 this._doWhenretryCount = 0;
3071 if (this._doWhenInterval) {
3072 // clearInterval(this._interval);
3073 this._doWhenInterval.cancel();
3074 this._doWhenInterval = null;
3079 if (this._doWhenLocked) {
3084 // Hold off if DOMReady has not fired and check current
3085 // readyState to protect against the IE operation aborted
3087 if (!YAHOO.util.Event.DOMReady) {
3088 this._startDoWhenInterval();
3093 this._doWhenLocked = true;
3096 // keep trying until after the page is loaded. We need to
3097 // check the page load state prior to trying to bind the
3098 // elements so that we can be certain all elements have been
3099 // tested appropriately
3100 var tryAgain = YAHOO.util.Event.DOMReady;
3102 tryAgain = (this._doWhenretryCount > 0 && this._doWhenStack.length > 0);
3108 var executeItem = function (context, item) {
3109 if (item.overrideContext) {
3110 if (item.overrideContext === true) {
3113 context = item.overrideContext;
3116 item.fn.call(context, item.obj);
3119 var i, len, item, test;
3121 // onAvailable onContentReady
3122 for (i=0, len=this._doWhenStack.length; i<len; i=i+1) {
3123 item = this._doWhenStack[i];
3126 if ((typeof(test) == "string" && eval(test)) || (typeof(test) == "function" && test())) {
3127 executeItem(this, item);
3128 this._doWhenStack[i] = null;
3131 notAvail.push(item);
3136 this._doWhenretryCount--;
3139 for (i=this._doWhenStack.length-1; i>-1; i--) {
3140 item = this._doWhenStack[i];
3141 if (!item || !item.check) {
3142 this._doWhenStack.splice(i, 1);
3145 this._startDoWhenInterval();
3147 if (this._doWhenInterval) {
3148 // clearInterval(this._interval);
3149 this._doWhenInterval.cancel();
3150 this._doWhenInterval = null;
3153 this._doWhenLocked = false;
3157 SUGAR.util.additionalDetailsCache = new Array();
3158 SUGAR.util.additionalDetailsCalls = new Array();
3159 if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.util.setMaxLength); // allow textareas to obey maxlength attrib
3161 SUGAR.savedViews = function() {
3162 var selectedOrderBy;
3163 var selectedSortOrder;
3166 var columnsMeta; // meta data for the display columns
3169 setChooser: function() {
3171 var displayColumnsDef = new Array();
3172 var hideTabsDef = new Array();
3174 var left_td = document.getElementById('display_tabs_td');
3175 if(typeof left_td == 'undefined' || left_td == null) return; // abort!
3176 var right_td = document.getElementById('hide_tabs_td');
3178 var displayTabs = left_td.getElementsByTagName('select')[0];
3179 var hideTabs = right_td.getElementsByTagName('select')[0];
3181 for(i = 0; i < displayTabs.options.length; i++) {
3182 displayColumnsDef.push(displayTabs.options[i].value);
3185 if(typeof hideTabs != 'undefined') {
3186 for(i = 0; i < hideTabs.options.length; i++) {
3187 hideTabsDef.push(hideTabs.options[i].value);
3190 if (!SUGAR.savedViews.clearColumns)
3191 document.getElementById('displayColumnsDef').value = displayColumnsDef.join('|');
3192 document.getElementById('hideTabsDef').value = hideTabsDef.join('|');
3195 select: function(saved_search_select) {
3196 for(var wp = 0; wp < document.search_form.saved_search_select.options.length; wp++) {
3197 if(typeof document.search_form.saved_search_select.options[wp].value != 'undefined' &&
3198 document.search_form.saved_search_select.options[wp].value == saved_search_select) {
3199 document.search_form.saved_search_select.selectedIndex = wp;
3200 document.search_form.ss_delete.style.display = '';
3201 document.search_form.ss_update.style.display = '';
3205 saved_search_action: function(action, delete_lang) {
3206 if(action == 'delete') {
3207 if(!confirm(delete_lang)) return;
3209 if(action == 'save') {
3210 if(document.search_form.saved_search_name.value.replace(/^\s*|\s*$/g, '') == '') {
3211 alert(SUGAR.language.get('app_strings', 'LBL_SAVED_SEARCH_ERROR'));
3216 // This check is needed for the Activities module (Calls/Meetings/Tasks).
3217 if (document.search_form.saved_search_action)
3219 document.search_form.saved_search_action.value = action;
3220 document.search_form.search_module.value = document.search_form.module.value;
3221 document.search_form.module.value = 'SavedSearch';
3222 // Bug 31922 - Make sure to specify that we want to hit the index view here of
3223 // the SavedSearch module, since the ListView doesn't have the logic to save the
3224 // search and redirect back
3225 document.search_form.action.value = 'index';
3227 SUGAR.ajaxUI.submitForm(document.search_form);
3229 shortcut_select: function(selectBox, module) {
3231 selecturl = 'index.php?module=SavedSearch&search_module=' + module + '&action=index&saved_search_select=' + selectBox.options[selectBox.selectedIndex].value
3232 //add searchFormTab to url if it is available. This determines what tab to render
3233 if(typeof(document.getElementById('searchFormTab'))!='undefined'){
3234 selecturl = selecturl + '&searchFormTab=' + document.search_form.searchFormTab.value;
3236 //add showSSDIV to url if it is available. This determines whether saved search sub form should
3237 //be rendered open or not
3238 if(document.getElementById('showSSDIV') && typeof(document.getElementById('showSSDIV') !='undefined')){
3239 selecturl = selecturl + '&showSSDIV='+document.getElementById('showSSDIV').value;
3241 //use created url to navigate
3242 document.location.href = selecturl;
3244 handleForm: function() {
3245 SUGAR.tabChooser.movementCallback = function(left_side, right_side) {
3246 while(document.getElementById('orderBySelect').childNodes.length != 0) { // clear out order by options
3247 document.getElementById('orderBySelect').removeChild(document.getElementById('orderBySelect').lastChild);
3250 var selectedIndex = 0;
3251 var nodeCount = -1; // need this because the counter i also includes "undefined" nodes
3252 // which was breaking Calls and Meetings
3254 for(i in left_side.childNodes) { // fill in order by options
3255 if(typeof left_side.childNodes[i].nodeName != 'undefined' &&
3256 left_side.childNodes[i].nodeName.toLowerCase() == 'option' &&
3257 typeof SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value] != 'undefined' && // check if column is sortable
3258 typeof SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value]['sortable'] == 'undefined' &&
3259 SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value]['sortable'] != false) {
3261 optionNode = document.createElement('option');
3262 optionNode.value = left_side.childNodes[i].value;
3263 optionNode.innerHTML = left_side.childNodes[i].innerHTML;
3264 document.getElementById('orderBySelect').appendChild(optionNode);
3265 if(optionNode.value == SUGAR.savedViews.selectedOrderBy)
3266 selectedIndex = nodeCount;
3269 // Firefox needs this to be set after all the option nodes are created.
3270 document.getElementById('orderBySelect').selectedIndex = selectedIndex;
3272 SUGAR.tabChooser.movementCallback(document.getElementById('display_tabs_td').getElementsByTagName('select')[0]);
3274 // This check is needed for the Activities module (Calls/Meetings/Tasks).
3275 if (document.search_form.orderBy)
3276 document.search_form.orderBy.options.value = SUGAR.savedViews.selectedOrderBy;
3279 if(SUGAR.savedViews.selectedSortOrder == 'DESC') document.getElementById('sort_order_desc_radio').checked = true;
3280 else document.getElementById('sort_order_asc_radio').checked = true;
3285 SUGAR.searchForm = function() {
3288 // searchForm tab selector util
3289 searchFormSelect: function(view, previousView) {
3290 var module = view.split('|')[0];
3291 var theView = view.split('|')[1];
3293 var handleDisplay = function() { // hide other divs
3294 document.search_form.searchFormTab.value = theView;
3295 patt = module+"(.*)SearchForm$";
3296 divId=document.search_form.getElementsByTagName('div');
3297 // Hide all the search forms and retrive the name of the previous search tab (useful for the first load because previousView is empty)
3298 for (i=0;i<divId.length;i++){
3299 if(divId[i].id.match(module)==module){
3300 if(divId[i].id.match('SearchForm')=='SearchForm'){
3301 if(document.getElementById(divId[i].id).style.display == ''){
3302 previousTab=divId[i].id.match(patt)[1];
3304 document.getElementById(divId[i].id).style.display = 'none';
3308 // show the good search form.
3309 document.getElementById(module + theView + 'SearchForm').style.display = '';
3310 //if its not the first tab show there is a previous tab.
3312 thepreviousView=previousView.split('|')[1];
3315 thepreviousView=previousTab;
3317 thepreviousView=thepreviousView.replace(/_search/, "");
3318 // Process to retrieve the completed field from one tab to an other.
3319 for(num in document.search_form.elements) {
3320 if(document.search_form.elements[num]) {
3321 el = document.search_form.elements[num];
3322 pattern="^(.*)_"+thepreviousView+"$";
3323 if(typeof el.type != 'undefined' && typeof el.name != 'undefined' && el.name.match(pattern)) {
3324 advanced_input_name = el.name.match(pattern)[1]; // strip
3325 advanced_input_name = advanced_input_name+"_"+theView.replace(/_search/, "");
3326 if(typeof document.search_form[advanced_input_name] != 'undefined') // if advanced input of same name exists
3327 SUGAR.searchForm.copyElement(advanced_input_name, el);
3333 // if tab is not cached
3334 if(document.getElementById(module + theView + 'SearchForm').innerHTML == '') {
3335 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_LOADING'));
3336 var success = function(data) {
3337 document.getElementById(module + theView + 'SearchForm').innerHTML = data.responseText;
3339 SUGAR.util.evalScript(data.responseText);
3340 // pass script variables to global scope
3341 if(theView == 'saved_views') {
3342 if(typeof columnsMeta != 'undefined') SUGAR.savedViews.columnsMeta = columnsMeta;
3343 if(typeof selectedOrderBy != 'undefined') SUGAR.savedViews.selectedOrderBy = selectedOrderBy;
3344 if(typeof selectedSortOrder != 'undefined') SUGAR.savedViews.selectedSortOrder = selectedSortOrder;
3349 ajaxStatus.hideStatus();
3351 url = 'index.php?module=' + module + '&action=index&search_form_only=true&to_pdf=true&search_form_view=' + theView;
3353 //check to see if tpl has been specified. If so then pass location through url string
3355 if(document.getElementById('search_tpl') !=null && typeof(document.getElementById('search_tpl')) != 'undefined'){
3356 tpl = document.getElementById('search_tpl').value;
3357 if(tpl != ''){url += '&search_tpl='+tpl;}
3360 if(theView == 'saved_views') // handle the tab chooser
3361 url += '&displayColumns=' + SUGAR.savedViews.displayColumns + '&hideTabs=' + SUGAR.savedViews.hideTabs + '&orderBy=' + SUGAR.savedViews.selectedOrderBy + '&sortOrder=' + SUGAR.savedViews.selectedSortOrder;
3363 var cObj = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
3365 else { // that form already retrieved
3370 // copies one input to another
3371 copyElement: function(inputName, copyFromElement) {
3372 switch(copyFromElement.type) {
3375 document.search_form[inputName].value = copyFromElement.value;
3379 // This function is here to clear the form, instead of "resubmitting it
3380 clear_form: function(form, skipElementNames) {
3381 var elemList = form.elements;
3385 for( var i = 0; i < elemList.length ; i++ ) {
3387 if ( typeof(elem.type) == 'undefined' ) {
3391 if ( typeof(elem.type) != 'undefined' && typeof(skipElementNames) != 'undefined'
3392 && SUGAR.util.arrayIndexOf(skipElementNames, elem.name) != -1 )
3397 elemType = elem.type.toLowerCase();
3399 if ( elemType == 'text' || elemType == 'textarea' || elemType == 'password' ) {
3402 else if ( elemType == 'select' || elemType == 'select-one' || elemType == 'select-multiple' ) {
3403 // We have, what I hope, is a select box, time to unselect all options
3404 var optionList = elem.options;
3405 for ( var ii = 0 ; ii < optionList.length ; ii++ ) {
3406 optionList[ii].selected = false;
3409 else if ( elemType == 'radio' || elemType == 'checkbox' ) {
3410 elem.checked = false;
3411 elem.selected = false;
3413 else if ( elemType == 'hidden' ) {
3414 // We only want to reset the hidden values that link to the select boxes.
3415 if ( ( elem.name.length > 3 && elem.name.substring(elem.name.length-3) == '_id' )
3416 || ((elem.name.length > 9) && (elem.name.substring(elem.name.length - 9) == '_id_basic'))
3417 || ( elem.name.length > 12 && elem.name.substring(elem.name.length-12) == '_id_advanced' ) ) {
3422 SUGAR.savedViews.clearColumns = true;
3426 // Code for the column/tab chooser used on homepage and in admin section
3427 SUGAR.tabChooser = function () {
3428 var object_refs = new Array();
3430 /* Describe certain transfers as invalid */
3433 movementCallback: function(left_side, right_side) {},
3434 orderCallback: function(left_side, right_side) {},
3436 freezeOptions: function(left_name, right_name, target) {
3437 if(!SUGAR.tabChooser.frozenOptions) { SUGAR.tabChooser.frozenOptions = []; }
3438 if(!SUGAR.tabChooser.frozenOptions[left_name]) { SUGAR.tabChooser.frozenOptions[left_name] = []; }
3439 if(!SUGAR.tabChooser.frozenOptions[left_name][right_name]) { SUGAR.tabChooser.frozenOptions[left_name][right_name] = []; }
3440 if(typeof target == 'array') {
3441 for(var i in target) {
3442 SUGAR.tabChooser.frozenOptions[left_name][right_name][target[i]] = true;
3445 SUGAR.tabChooser.frozenOptions[left_name][right_name][target] = true;
3449 buildSelectHTML: function(info) {
3450 var text = "<select";
3452 if(typeof (info['select']['size']) != 'undefined') {
3453 text +=" size=\""+ info['select']['size'] +"\"";
3456 if(typeof (info['select']['name']) != 'undefined') {
3457 text +=" name=\""+ info['select']['name'] +"\"";
3460 if(typeof (info['select']['style']) != 'undefined') {
3461 text +=" style=\""+ info['select']['style'] +"\"";
3464 if(typeof (info['select']['onchange']) != 'undefined') {
3465 text +=" onChange=\""+ info['select']['onchange'] +"\"";
3468 if(typeof (info['select']['multiple']) != 'undefined') {
3473 for(i=0; i<info['options'].length;i++) {
3474 option = info['options'][i];
3475 text += "<option value=\""+option['value']+"\" ";
3476 if ( typeof (option['selected']) != 'undefined' && option['selected']== true) {
3479 text += ">"+option['text']+"</option>";
3481 text += "</select>";
3485 left_to_right: function(left_name, right_name, left_size, right_size) {
3486 SUGAR.savedViews.clearColumns = false;
3487 var left_td = document.getElementById(left_name+'_td');
3488 var right_td = document.getElementById(right_name+'_td');
3490 var display_columns_ref = left_td.getElementsByTagName('select')[0];
3491 var hidden_columns_ref = right_td.getElementsByTagName('select')[0];
3493 var selected_left = new Array();
3494 var notselected_left = new Array();
3495 var notselected_right = new Array();
3497 var left_array = new Array();
3499 var frozen_options = SUGAR.tabChooser.frozenOptions;
3500 frozen_options = frozen_options && frozen_options[left_name] && frozen_options[left_name][right_name]?frozen_options[left_name][right_name]:[];
3502 // determine which options are selected in left
3503 for (i=0; i < display_columns_ref.options.length; i++)
3505 if ( display_columns_ref.options[i].selected == true && !frozen_options[display_columns_ref.options[i].value])
3507 selected_left[selected_left.length] = {text: display_columns_ref.options[i].text, value: display_columns_ref.options[i].value};
3511 notselected_left[notselected_left.length] = {text: display_columns_ref.options[i].text, value: display_columns_ref.options[i].value};
3516 for (i=0; i < hidden_columns_ref.options.length; i++)
3518 notselected_right[notselected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
3522 var left_select_html_info = new Object();
3523 var left_options = new Array();
3524 var left_select = new Object();
3526 left_select['name'] = left_name+'[]';
3527 left_select['id'] = left_name;
3528 left_select['size'] = left_size;
3529 left_select['multiple'] = 'true';
3531 var right_select_html_info = new Object();
3532 var right_options = new Array();
3533 var right_select = new Object();
3535 right_select['name'] = right_name+'[]';
3536 right_select['id'] = right_name;
3537 right_select['size'] = right_size;
3538 right_select['multiple'] = 'true';
3540 for (i = 0; i < notselected_right.length; i++) {
3541 right_options[right_options.length] = notselected_right[i];
3544 for (i = 0; i < selected_left.length; i++) {
3545 right_options[right_options.length] = selected_left[i];
3547 for (i = 0; i < notselected_left.length; i++) {
3548 left_options[left_options.length] = notselected_left[i];
3550 left_select_html_info['options'] = left_options;
3551 left_select_html_info['select'] = left_select;
3552 right_select_html_info['options'] = right_options;
3553 right_select_html_info['select'] = right_select;
3554 right_select_html_info['style'] = 'background: lightgrey';
3556 var left_html = this.buildSelectHTML(left_select_html_info);
3557 var right_html = this.buildSelectHTML(right_select_html_info);
3559 left_td.innerHTML = left_html;
3560 right_td.innerHTML = right_html;
3562 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3563 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3565 this.movementCallback(object_refs[left_name], object_refs[right_name]);
3571 right_to_left: function(left_name, right_name, left_size, right_size, max_left) {
3572 SUGAR.savedViews.clearColumns = false;
3573 var left_td = document.getElementById(left_name+'_td');
3574 var right_td = document.getElementById(right_name+'_td');
3576 var display_columns_ref = left_td.getElementsByTagName('select')[0];
3577 var hidden_columns_ref = right_td.getElementsByTagName('select')[0];
3579 var selected_right = new Array();
3580 var notselected_right = new Array();
3581 var notselected_left = new Array();
3583 var frozen_options = SUGAR.tabChooser.frozenOptions;
3584 frozen_options = SUGAR.tabChooser.frozenOptions && SUGAR.tabChooser.frozenOptions[right_name] && SUGAR.tabChooser.frozenOptions[right_name][left_name]?SUGAR.tabChooser.frozenOptions[right_name][left_name]:[];
3586 for (i=0; i < hidden_columns_ref.options.length; i++)
3588 if (hidden_columns_ref.options[i].selected == true && !frozen_options[hidden_columns_ref.options[i].value])
3590 selected_right[selected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
3594 notselected_right[notselected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
3599 if(max_left != '' && (display_columns_ref.length + selected_right.length) > max_left) {
3600 alert('Maximum of ' + max_left + ' columns can be displayed.');
3604 for (i=0; i < display_columns_ref.options.length; i++)
3606 notselected_left[notselected_left.length] = {text:display_columns_ref.options[i].text, value:display_columns_ref.options[i].value};
3610 var left_select_html_info = new Object();
3611 var left_options = new Array();
3612 var left_select = new Object();
3614 left_select['name'] = left_name+'[]';
3615 left_select['id'] = left_name;
3616 left_select['multiple'] = 'true';
3617 left_select['size'] = left_size;
3619 var right_select_html_info = new Object();
3620 var right_options = new Array();
3621 var right_select = new Object();
3623 right_select['name'] = right_name+ '[]';
3624 right_select['id'] = right_name;
3625 right_select['multiple'] = 'true';
3626 right_select['size'] = right_size;
3628 for (i = 0; i < notselected_left.length; i++) {
3629 left_options[left_options.length] = notselected_left[i];
3632 for (i = 0; i < selected_right.length; i++) {
3633 left_options[left_options.length] = selected_right[i];
3635 for (i = 0; i < notselected_right.length; i++) {
3636 right_options[right_options.length] = notselected_right[i];
3638 left_select_html_info['options'] = left_options;
3639 left_select_html_info['select'] = left_select;
3640 right_select_html_info['options'] = right_options;
3641 right_select_html_info['select'] = right_select;
3642 right_select_html_info['style'] = 'background: lightgrey';
3644 var left_html = this.buildSelectHTML(left_select_html_info);
3645 var right_html = this.buildSelectHTML(right_select_html_info);
3647 left_td.innerHTML = left_html;
3648 right_td.innerHTML = right_html;
3650 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3651 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3653 this.movementCallback(object_refs[left_name], object_refs[right_name]);
3658 up: function(name, left_name, right_name) {
3659 SUGAR.savedViews.clearColumns = false;
3660 var left_td = document.getElementById(left_name+'_td');
3661 var right_td = document.getElementById(right_name+'_td');
3662 var td = document.getElementById(name+'_td');
3663 var obj = td.getElementsByTagName('select')[0];
3664 obj = (typeof obj == "string") ? document.getElementById(obj) : obj;
3665 if (obj.tagName.toLowerCase() != "select" && obj.length < 2)
3667 var sel = new Array();
3669 for (i=0; i<obj.length; i++) {
3670 if (obj[i].selected == true) {
3671 sel[sel.length] = i;
3674 for (i=0; i < sel.length; i++) {
3675 if (sel[i] != 0 && !obj[sel[i]-1].selected) {
3676 var tmp = new Array(obj[sel[i]-1].text, obj[sel[i]-1].value);
3677 obj[sel[i]-1].text = obj[sel[i]].text;
3678 obj[sel[i]-1].value = obj[sel[i]].value;
3679 obj[sel[i]].text = tmp[0];
3680 obj[sel[i]].value = tmp[1];
3681 obj[sel[i]-1].selected = true;
3682 obj[sel[i]].selected = false;
3686 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3687 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3689 this.orderCallback(object_refs[left_name], object_refs[right_name]);
3694 down: function(name, left_name, right_name) {
3695 SUGAR.savedViews.clearColumns = false;
3696 var left_td = document.getElementById(left_name+'_td');
3697 var right_td = document.getElementById(right_name+'_td');
3698 var td = document.getElementById(name+'_td');
3699 var obj = td.getElementsByTagName('select')[0];
3700 if (obj.tagName.toLowerCase() != "select" && obj.length < 2)
3702 var sel = new Array();
3703 for (i=obj.length-1; i>-1; i--) {
3704 if (obj[i].selected == true) {
3705 sel[sel.length] = i;
3708 for (i=0; i < sel.length; i++) {
3709 if (sel[i] != obj.length-1 && !obj[sel[i]+1].selected) {
3710 var tmp = new Array(obj[sel[i]+1].text, obj[sel[i]+1].value);
3711 obj[sel[i]+1].text = obj[sel[i]].text;
3712 obj[sel[i]+1].value = obj[sel[i]].value;
3713 obj[sel[i]].text = tmp[0];
3714 obj[sel[i]].value = tmp[1];
3715 obj[sel[i]+1].selected = true;
3716 obj[sel[i]].selected = false;
3720 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3721 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3723 this.orderCallback(object_refs[left_name], object_refs[right_name]);
3728 }(); // end tabChooser
3730 SUGAR.language = function() {
3732 languages : new Array(),
3734 setLanguage: function(module, data) {
3735 if (!SUGAR.language.languages) {
3738 SUGAR.language.languages[module] = data;
3741 get: function(module, str) {
3742 if(typeof SUGAR.language.languages[module] == 'undefined' || typeof SUGAR.language.languages[module][str] == 'undefined')
3746 return SUGAR.language.languages[module][str];
3749 translate: function(module, str)
3751 text = this.get(module, str);
3752 return text != 'undefined' ? text : this.get('app_strings', str);
3757 SUGAR.contextMenu = function() {
3759 objects: new Object(),
3760 objectTypes: new Object(),
3762 * Registers a new object for the context menu.
3763 * objectType - name of the type
3765 * metaData - metaData to pass to the action function
3767 registerObject: function(objectType, id, metaData) {
3768 SUGAR.contextMenu.objects[id] = new Object();
3769 SUGAR.contextMenu.objects[id] = {'objectType' : objectType, 'metaData' : metaData};
3772 * Registers a new object type
3773 * name - name of the type
3774 * menuItems - array of menu items
3776 registerObjectType: function(name, menuItems) {
3777 SUGAR.contextMenu.objectTypes[name] = new Object();
3778 SUGAR.contextMenu.objectTypes[name] = {'menuItems' : menuItems, 'objects' : new Array()};
3781 * Determines which menu item was clicked
3783 getListItemFromEventTarget: function(p_oNode) {
3785 if(p_oNode.tagName == "LI") {
3790 if(p_oNode.tagName == "LI") {
3795 } while((p_oNode = p_oNode.parentNode));
3800 * handles movement within context menu
3802 onContextMenuMove: function() {
3803 var oNode = this.contextEventTarget;
3804 var bDisabled = (oNode.tagName == "UL");
3805 var i = this.getItemGroups()[0].length - 1;
3807 this.getItem(i).cfg.setProperty("disabled", bDisabled);
3812 * handles clicks on a context menu ITEM
3814 onContextMenuItemClick: function(p_sType, p_aArguments, p_oItem) {
3815 var oLI = SUGAR.contextMenu.getListItemFromEventTarget(this.parent.contextEventTarget);
3816 id = this.parent.contextEventTarget.parentNode.id; // id of the target
3817 funct = eval(SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[id]['objectType']]['menuItems'][this.index]['action']);
3818 funct(this.parent.contextEventTarget, SUGAR.contextMenu.objects[id]['metaData']);
3821 * Initializes all context menus registered
3824 for(var i in SUGAR.contextMenu.objects) { // make a variable called objects in objectTypes containg references to all triggers
3825 if(typeof SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'] == 'undefined')
3826 SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'] = new Array();
3827 SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'].push(document.getElementById(i));
3829 // register the menus
3830 for(var i in SUGAR.contextMenu.objectTypes) {
3831 var oContextMenu = new YAHOO.widget.ContextMenu(i, {'trigger': SUGAR.contextMenu.objectTypes[i]['objects']});
3832 var aMainMenuItems = SUGAR.contextMenu.objectTypes[i]['menuItems'];
3833 var nMainMenuItems = aMainMenuItems.length;
3835 for(var j = 0; j < nMainMenuItems; j++) {
3836 oMenuItem = new YAHOO.widget.ContextMenuItem(aMainMenuItems[j].text, { helptext: aMainMenuItems[j].helptext });
3837 oMenuItem.clickEvent.subscribe(SUGAR.contextMenu.onContextMenuItemClick, oMenuItem, true);
3838 oContextMenu.addItem(oMenuItem);
3840 // Add a "move" event handler to the context menu
3841 oContextMenu.moveEvent.subscribe(SUGAR.contextMenu.onContextMenuMove, oContextMenu, true);
3842 // Add a "keydown" event handler to the context menu
3843 oContextMenu.keyDownEvent.subscribe(SUGAR.contextMenu.onContextMenuItemClick, oContextMenu, true);
3844 // Render the context menu
3845 oContextMenu.render(document.body);
3851 SUGAR.contextMenu.actions = function() {
3854 * redirects to a new note with the clicked on object as the target
3856 createNote: function(itemClicked, metaData) {
3857 loc = 'index.php?module=Notes&action=EditView';
3858 for(i in metaData) {
3859 if(i == 'notes_parent_type') loc += '&parent_type=' + metaData[i];
3860 else if(i != 'module' && i != 'parent_type') loc += '&' + i + '=' + metaData[i];
3862 document.location = loc;
3865 * redirects to a new note with the clicked on object as the target
3867 scheduleMeeting: function(itemClicked, metaData) {
3868 loc = 'index.php?module=Meetings&action=EditView';
3869 for(i in metaData) {
3870 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3872 document.location = loc;
3875 * redirects to a new note with the clicked on object as the target
3877 scheduleCall: function(itemClicked, metaData) {
3878 loc = 'index.php?module=Calls&action=EditView';
3879 for(i in metaData) {
3880 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3882 document.location = loc;
3885 * redirects to a new contact with the clicked on object as the target
3887 createContact: function(itemClicked, metaData) {
3888 loc = 'index.php?module=Contacts&action=EditView';
3889 for(i in metaData) {
3890 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3892 document.location = loc;
3895 * redirects to a new task with the clicked on object as the target
3897 createTask: function(itemClicked, metaData) {
3898 loc = 'index.php?module=Tasks&action=EditView';
3899 for(i in metaData) {
3900 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3902 document.location = loc;
3905 * redirects to a new opportunity with the clicked on object as the target
3907 createOpportunity: function(itemClicked, metaData) {
3908 loc = 'index.php?module=Opportunities&action=EditView';
3909 for(i in metaData) {
3910 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3912 document.location = loc;
3915 * redirects to a new opportunity with the clicked on object as the target
3917 createCase: function(itemClicked, metaData) {
3918 loc = 'index.php?module=Cases&action=EditView';
3919 for(i in metaData) {
3920 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3922 document.location = loc;
3925 * handles add to favorites menu selection
3927 addToFavorites: function(itemClicked, metaData) {
3928 success = function(data) {
3930 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});
3935 //if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.contextMenu.init);
3937 // initially from popup_parent_helper.js
3938 var popup_request_data;
3941 function get_popup_request_data()
3943 return YAHOO.lang.JSON.stringify(window.document.popup_request_data);
3946 function get_close_popup()
3948 return window.document.close_popup;
3951 function open_popup(module_name, width, height, initial_filter, close_popup, hide_clear_button, popup_request_data, popup_mode, create, metadata)
3953 if (typeof(popupCount) == "undefined" || popupCount == 0)
3956 // set the variables that the popup will pull from
3957 window.document.popup_request_data = popup_request_data;
3958 window.document.close_popup = close_popup;
3960 //globally changing width and height of standard pop up window from 600 x 400 to 800 x 800
3961 width = (width == 600) ? 800 : width;
3962 height = (height == 400) ? 800 : height;
3966 + 'module=' + module_name
3969 if (initial_filter != '') {
3970 URL += '&query=true' + initial_filter;
3971 // Bug 41891 - Popup Window Name
3972 popupName = initial_filter.replace(/[^a-z_0-9]+/ig, '_');
3973 windowName = module_name + '_popup_window' + popupName;
3975 windowName = module_name + '_popup_window' + popupCount;
3979 if (hide_clear_button) {
3980 URL += '&hide_clear_button=true';
3983 windowFeatures = 'width=' + width
3984 + ',height=' + height
3985 + ',resizable=1,scrollbars=1';
3987 if (popup_mode == '' && popup_mode == 'undefined') {
3988 popup_mode='single';
3990 URL+='&mode='+popup_mode;
3991 if (create == '' && create == 'undefined') {
3994 URL+='&create='+create;
3996 if (metadata != '' && metadata != 'undefined') {
3997 URL+='&metadata='+metadata;
4000 win = SUGAR.util.openWindow(URL, windowName, windowFeatures);
4004 // put the focus on the popup if the browser supports the focus() method
4008 win.popupCount = popupCount;
4014 * The reply data must be a JSON array structured with the following information:
4015 * 1) form name to populate
4016 * 2) associative array of input names to values for populating the form
4018 var from_popup_return = false;
4020 function set_return_basic(popup_reply_data,filter)
4022 var form_name = popup_reply_data.form_name;
4023 var name_to_value_array = popup_reply_data.name_to_value_array;
4024 for (var the_key in name_to_value_array)
4026 if(the_key == 'toJSON')
4030 else if(the_key.match(filter))
4032 var displayValue=name_to_value_array[the_key].replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');;
4033 // begin andopes change: support for enum fields (SELECT)
4034 if(window.document.forms[form_name] && window.document.forms[form_name].elements[the_key]) {
4035 if(window.document.forms[form_name].elements[the_key].tagName == 'SELECT') {
4036 var selectField = window.document.forms[form_name].elements[the_key];
4037 for(var i = 0; i < selectField.options.length; i++) {
4038 if(selectField.options[i].text == displayValue) {
4039 selectField.options[i].selected = true;
4040 SUGAR.util.callOnChangeListers(selectField);
4045 window.document.forms[form_name].elements[the_key].value = displayValue;
4046 SUGAR.util.callOnChangeListers(window.document.forms[form_name].elements[the_key]);
4049 // end andopes change: support for enum fields (SELECT)
4054 function set_return(popup_reply_data)
4056 from_popup_return = true;
4057 var form_name = popup_reply_data.form_name;
4058 var name_to_value_array = popup_reply_data.name_to_value_array;
4059 if(typeof name_to_value_array != 'undefined' && name_to_value_array['account_id'])
4062 var label_data_str = '';
4063 var current_label_data_str = '';
4064 for (var the_key in name_to_value_array)
4066 if(the_key == 'toJSON')
4072 var displayValue=name_to_value_array[the_key].replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');
4073 if(window.document.forms[form_name] && document.getElementById(the_key+'_label') && !the_key.match(/account/)) {
4074 var data_label = document.getElementById(the_key+'_label').innerHTML.replace(/\n/gi,'');
4075 label_str += data_label + ' \n';
4076 label_data_str += data_label + ' ' + displayValue + '\n';
4077 if(window.document.forms[form_name].elements[the_key]) {
4078 current_label_data_str += data_label + ' ' + window.document.forms[form_name].elements[the_key].value +'\n';
4083 if(label_data_str != label_str && current_label_data_str != label_str){
4084 if(confirm(SUGAR.language.get('app_strings', 'NTC_OVERWRITE_ADDRESS_PHONE_CONFIRM') + '\n\n' + label_data_str))
4086 set_return_basic(popup_reply_data,/\S/);
4088 set_return_basic(popup_reply_data,/account/);
4090 }else if(label_data_str != label_str && current_label_data_str == label_str){
4091 set_return_basic(popup_reply_data,/\S/);
4092 }else if(label_data_str == label_str){
4093 set_return_basic(popup_reply_data,/account/);
4096 set_return_basic(popup_reply_data,/\S/);
4100 function set_return_lead_conv(popup_reply_data) {
4101 set_return(popup_reply_data);
4102 if (document.getElementById('lead_conv_ac_op_sel') && typeof onBlurKeyUpHandler=='function') {
4103 onBlurKeyUpHandler();
4107 function set_return_and_save(popup_reply_data)
4109 var form_name = popup_reply_data.form_name;
4110 var name_to_value_array = popup_reply_data.name_to_value_array;
4112 for (var the_key in name_to_value_array)
4114 if(the_key == 'toJSON')
4120 window.document.forms[form_name].elements[the_key].value = name_to_value_array[the_key];
4124 window.document.forms[form_name].return_module.value = window.document.forms[form_name].module.value;
4125 window.document.forms[form_name].return_action.value = 'DetailView';
4126 window.document.forms[form_name].return_id.value = window.document.forms[form_name].record.value;
4127 window.document.forms[form_name].action.value = 'Save';
4128 window.document.forms[form_name].submit();
4132 * This is a helper function to construct the initial filter that can be
4133 * passed into the open_popup() function. It assumes that there is an
4134 * account_id and account_name field in the given form_name to use to
4135 * construct the intial filter string.
4137 function get_initial_filter_by_account(form_name)
4139 var account_id = window.document.forms[form_name].account_id.value;
4140 var account_name = escape(window.document.forms[form_name].account_name.value);
4141 var initial_filter = "&account_id=" + account_id + "&account_name=" + account_name;
4143 return initial_filter;
4145 // end code from popup_parent_helper.js
4147 // begin code for address copy
4149 * This is a function used by the Address widget that will fill
4150 * in the given array fields using the fromKey and toKey as a
4151 * prefix into the form objects HTML elements.
4153 * @param form The HTML form object to parse
4154 * @param fromKey The prefix of elements to copy from
4155 * @param toKey The prefix of elements to copy into
4156 * @return boolean true if successful, false otherwise
4158 function copyAddress(form, fromKey, toKey) {
4160 var elems = new Array("address_street", "address_city", "address_state", "address_postalcode", "address_country");
4161 var checkbox = document.getElementById(toKey + "_checkbox");
4163 if(typeof checkbox != "undefined") {
4164 if(!checkbox.checked) {
4166 t = toKey + "_" + elems[x];
4167 document.getElementById(t).removeAttribute('readonly');
4171 f = fromKey + "_" + elems[x];
4172 t = toKey + "_" + elems[x];
4174 document.getElementById(t).value = document.getElementById(f).value;
4175 document.getElementById(t).setAttribute('readonly', true);
4181 // end code for address copy
4184 * This function is used in Email Template Module.
4185 * It will check whether the template is used in Campaing->EmailMarketing.
4186 * If true, it will notify user.
4189 function check_deletable_EmailTemplate() {
4190 id = document.getElementsByName('record')[0].value;
4191 currentForm = document.getElementById('form');
4193 success:function(r) {
4194 if(r.responseText == 'true') {
4195 if(!confirm(SUGAR.language.get('app_strings','NTC_TEMPLATE_IS_USED'))) {
4199 if(!confirm(SUGAR.language.get('app_strings','NTC_DELETE_CONFIRMATION'))) {
4203 currentForm.return_module.value='EmailTemplates';
4204 currentForm.return_action.value='ListView';
4205 currentForm.action.value='Delete';
4206 currentForm.submit();
4209 url = "index.php?module=EmailTemplates&action=CheckDeletable&from=DetailView&to_pdf=1&record="+id;
4210 YAHOO.util.Connect.asyncRequest('POST',url, call_back,null);
4214 remove_upload_imagefile : function(field_name) {
4215 var field=document.getElementById('remove_imagefile_' + field_name);
4218 //enable the file upload button.
4219 var field=document.getElementById( field_name);
4220 field.style.display="";
4222 //hide the image and remove button.
4223 var field=document.getElementById('img_' + field_name);
4224 field.style.display="none";
4225 var field=document.getElementById('bt_remove_' + field_name);
4226 field.style.display="none";
4228 if(document.getElementById(field_name + '_duplicate')) {
4229 var field = document.getElementById(field_name + '_duplicate');
4234 confirm_imagefile : function(field_name) {
4235 var field=document.getElementById(field_name);
4236 var filename=field.value;
4237 var fileExtension = filename.substring(filename.lastIndexOf(".")+1);
4238 fileExtension = fileExtension.toLowerCase();
4239 if (fileExtension == "jpg" || fileExtension == "jpeg"
4240 || fileExtension == "gif" || fileExtension == "png" || fileExtension == "bmp"){
4245 alert(SUGAR.language.get('app_strings', 'LBL_UPLOAD_IMAGE_FILE_INVALID'));
4249 lightbox : function(image)
4251 if (typeof(SUGAR.image.lighboxWindow) == "undefined")
4252 SUGAR.image.lighboxWindow = new YAHOO.widget.SimpleDialog('sugarImageViewer', {
4255 id:'sugarMsgWindow',
4258 msg: "<img src='" + image + "'> </img>",
4261 SUGAR.image.lighboxWindow.setBody("<img src='" + image + "'> </img>");
4262 SUGAR.image.lighboxWindow.render(document.body);
4263 SUGAR.image.lighboxWindow.show();
4264 SUGAR.image.lighboxWindow.center()
4268 SUGAR.append(SUGAR.util, {
4269 isTouchScreen: function() {
4270 // first check if we have forced use of the touch enhanced interface
4271 if (Get_Cookie("touchscreen") == '1') {
4275 // next check if we should use the touch interface with our device
4276 if ((navigator.userAgent.match(/iPad/i) != null)) {
4283 isLoginPage: function(content) {
4284 //skip if this is packageManager screen
4285 if(SUGAR.util.isPackageManager()) {return false;}
4286 var loginPageStart = "<!DOCTYPE";
4287 if (content.substr(0, loginPageStart.length) == loginPageStart && content.indexOf("<html>") != -1 && content.indexOf("login_module") != -1) {
4288 window.location.href = window.location.protocol + window.location.pathname;
4293 isPackageManager: function(){
4294 if(typeof(document.the_form) !='undefined' && typeof(document.the_form.language_pack_escaped) !='undefined'){
4296 }else{return false;}
4299 ajaxCallInProgress: function(){
4300 //If the page content is blank, it means we are probably still waiting on something
4301 var c = document.getElementById("content");
4302 if (!c) return true;
4303 var t = YAHOO.lang.trim(SUGAR.util.innerText(c));
4304 return SUGAR_callsInProgress != 0 || t == "";
4306 //Firefox doesn't support innerText (textContent includes script content)
4307 innerText : function(el) {
4308 if (el.tagName == "SCRIPT")
4310 if(typeof(el.innerText) == "string")
4311 return el.innerText;
4313 for (var i in el.childNodes){
4314 var c = el.childNodes[i];
4315 if (typeof(c) != "object")
4317 if (typeof(c.nodeName) == "string" && c.nodeName == "#text")
4320 t += SUGAR.util.innerText(c);
4325 callOnChangeListers: function(field){
4326 var listeners = YAHOO.util.Event.getListeners(field, 'change');
4327 if (listeners != null) {
4328 for (var i = 0; i < listeners.length; i++) {
4329 var l = listeners[i];
4330 l.fn.call(l.scope ? l.scope : this, l.obj);
4335 closeActivityPanel: {
4336 show:function(module,id,new_status,viewType,parentContainerId){
4337 if (SUGAR.util.closeActivityPanel.panel)
4338 SUGAR.util.closeActivityPanel.panel.destroy();
4339 var singleModule = SUGAR.language.get("app_list_strings", "moduleListSingular")[module];
4340 singleModule = typeof(singleModule != 'undefined') ? singleModule.toLowerCase() : '';
4341 var closeText = SUGAR.language.get("app_strings", "LBL_CLOSE_ACTIVITY_CONFIRM").replace("#module#",singleModule);
4342 SUGAR.util.closeActivityPanel.panel =
4343 new YAHOO.widget.SimpleDialog("closeActivityDialog",
4350 constraintoviewport: true,
4351 buttons: [ { text:SUGAR.language.get("app_strings", "LBL_EMAIL_OK"), handler:function(){
4352 if (SUGAR.util.closeActivityPanel.panel)
4353 SUGAR.util.closeActivityPanel.panel.hide();
4355 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_SAVING'));
4356 var args = "action=save&id=" + id + "&record=" + id + "&status=" + new_status + "&module=" + module;
4357 // 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
4358 // TODO: Take id out and regression test. Left id in for now to not create any other unexpected problems
4359 //var args = "action=save&id=" + id + "&status=" + new_status + "&module=" + module;
4363 // 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.
4364 // So instead, we reload from a timeout
4365 window.setTimeout("window.location.reload(true);",0);
4367 argument:{'parentContainerId':parentContainerId}
4370 YAHOO.util.Connect.asyncRequest('POST', 'index.php', callback, args);
4372 }, isDefault:true },
4373 { text:SUGAR.language.get("app_strings", "LBL_EMAIL_CANCEL"), handler:function(){SUGAR.util.closeActivityPanel.panel.hide(); }} ]
4376 SUGAR.util.closeActivityPanel.panel.setHeader(SUGAR.language.get("app_strings", "LBL_CLOSE_ACTIVITY_HEADER"));
4377 SUGAR.util.closeActivityPanel.panel.render(document.body);
4378 SUGAR.util.closeActivityPanel.panel.show();
4382 setEmailPasswordDisplay: function(id, exists) {
4383 link = document.getElementById(id+'_link');
4384 pwd = document.getElementById(id);
4385 if(!pwd || !link) return;
4387 pwd.style.display = 'none';
4388 link.style.display = '';
4390 pwd.style.display = '';
4391 link.style.display = 'none';
4395 setEmailPasswordEdit: function(id) {
4396 link = document.getElementById(id+'_link');
4397 pwd = document.getElementById(id);
4398 if(!pwd || !link) return;
4399 pwd.style.display = '';
4400 link.style.display = 'none';
4404 * Compares a filename with a supplied array of allowed file extensions.
4405 * @param fileName string
4406 * @param allowedTypes array of allowed file extensions
4409 validateFileExt: function(fileName, allowedTypes) {
4410 var ext = fileName.split('.').pop();
4412 for (var i = allowedTypes.length; i > 0; i--) {
4413 if (ext === allowedTypes[i]) {
4421 arrayIndexOf: function(arr, val, start) {
4422 if (typeof arr.indexOf == "function")
4423 return arr.indexOf(val, start);
4424 for (var i = (start || 0), j = arr.length; i < j; i++) {
4425 if (arr[i] === val) {
4433 SUGAR.clearRelateField = function(form, name, id)
4435 if (typeof form[name] == "object"){
4436 form[name].value = '';
4437 SUGAR.util.callOnChangeListers(form[name]);
4440 if (typeof form[id] == "object"){
4441 form[id].value = '';
4442 SUGAR.util.callOnChangeListers(form[id]);
4445 if(typeof(SUGAR.AutoComplete) == 'undefined') SUGAR.AutoComplete = {};
4447 SUGAR.AutoComplete.getOptionsArray = function(options_index){
4448 var return_arr = [];
4450 var opts = SUGAR.language.get('app_list_strings', options_index);
4451 if(typeof(opts) != 'undefined'){
4453 // Since we are using auto complete, we excluse blank dropdown entries since they can just leave it blank
4454 if(key != '' && opts[key] != ''){
4457 item['text'] = opts[key];
4458 return_arr.push(item);
4465 if(typeof(SUGAR.MultiEnumAutoComplete) == 'undefined') SUGAR.MultiEnumAutoComplete = {};
4467 SUGAR.MultiEnumAutoComplete.getMultiSelectKeysFromValues = function(options_index, val_string){
4468 var opts = SUGAR.language.get('app_list_strings', options_index);
4469 var selected_values = val_string.split(", ");
4470 // YUI AutoComplete adds a blank. We remove it automatically here
4471 if(selected_values.length > 0 && selected_values.indexOf('') == selected_values.length - 1){
4472 selected_values.pop();
4474 var final_arr = new Array();
4475 for(idx in selected_values){
4477 if(selected_values[idx] == opts[o_idx]){
4478 final_arr.push(o_idx);
4485 SUGAR.MultiEnumAutoComplete.getMultiSelectValuesFromKeys = function(options_index, val_string){
4486 var opts = SUGAR.language.get('app_list_strings', options_index);
4487 val_string=val_string.replace(/^\^/,'').replace(/\^$/,'') //fixes bug where string starts or ends with ^
4488 var selected_values = val_string.split("^,^");
4490 // YUI AutoComplete adds a blank. We remove it automatically here
4491 if(selected_values.length > 0 && selected_values.indexOf('') == selected_values.length - 1){
4492 selected_values.pop();
4495 var final_arr = new Array();
4496 for(idx in selected_values){
4498 if(selected_values[idx] == o_idx){
4499 final_arr.push(opts[o_idx]);