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 insert_at_cursor(field, value) {
1400 if (document.selection) {
1402 sel = document.selection.createRange();
1406 else if(field.selectionStart || field.selectionStart == '0') {
1407 var start_pos = field.selectionStart;
1408 var end_pos = field.selectionEnd;
1409 field.value = field.value.substring(0, start_pos) + value + field.value.substring(end_pos, field.value.length);
1412 field.value += value;
1416 function checkParentType(type,button) {
1417 if(button == null) {
1420 if(typeof disabledModules != 'undefined' && typeof(disabledModules[type]) != 'undefined') {
1421 button.disabled='disabled';
1424 button.disabled = false;
1428 function parseDate(input, format) {
1430 format = format.replace(/%/g, '');
1431 sep = format.charAt(1);
1432 yAt = format.indexOf('Y')
1433 // 1-1-06 or 1-12-06 or 1-1-2006 or 1-12-2006
1434 if(date.match(/^\d{1,2}[\/-]\d{1,2}[\/-]\d{2,4}$/) && yAt == 4) {
1435 if(date.match(/^\d{1}[\/-].*$/)) date = '0' + date;
1436 if(date.match(/^\d{2}[\/-]\d{1}[\/-].*$/)) date = date.substring(0,3) + '0' + date.substring(3,date.length);
1437 if(date.match(/^\d{2}[\/-]\d{2}[\/-]\d{2}$/)) date = date.substring(0,6) + '20' + date.substring(6,date.length);
1439 // 06-11-1 or 06-1-1
1440 else if(date.match(/^\d{2,4}[\/-]\d{1,2}[\/-]\d{1,2}$/)) {
1441 if(date.match(/^\d{2}[\/-].*$/)) date = '20' + date;
1442 if(date.match(/^\d{4}[\/-]\d{1}[\/-].*$/)) date = date.substring(0,5) + '0' + date.substring(5,date.length);
1443 if(date.match(/^\d{4}[\/-]\d{2}[\/-]\d{1}$/)) date = date.substring(0,8) + '0' + date.substring(8,date.length);
1445 else if(date.match(/^\d{4,8}$/)) { // digits only
1447 if(date.match(/^\d{8}$/)) digits = 8;// match for 8 digits
1448 else if(date.match(/\d{6}/)) digits = 6;// match for 5 digits
1449 else if(date.match(/\d{4}/)) digits = 4;// match for 5 digits
1450 else if(date.match(/\d{5}/)) digits = 5;// match for 5 digits
1455 case 4: date = '20' + date.substring(0,2) + sep + '0' + date.substring(2, 3) + sep + '0' + date.substring(3,4); break;
1456 case 5: date = '20' + date.substring(0,2) + sep + date.substring(2, 4) + sep + '0' + date.substring(4,5); break;
1457 case 6: date = '20' + date.substring(0,2) + sep + date.substring(2, 4) + sep + date.substring(4,6); break;
1458 case 8: date = date.substring(0,4) + sep + date.substring(4, 6) + sep + date.substring(6,8); break;
1463 case 4: date = '0' + date.substring(0,1) + sep + '20' + date.substring(1, 3) + sep + '0' + date.substring(3,4); break;
1464 case 5: date = date.substring(0,2) + sep + '20' + date.substring(2, 4) + sep + '0' + date.substring(4,5); break;
1465 case 6: date = date.substring(0,2) + sep + '20' + date.substring(2, 4) + sep + date.substring(4,6); break;
1466 case 8: date = date.substring(0,2) + sep + date.substring(2, 6) + sep + date.substring(6,8); break;
1470 case 4: date = '0' + date.substring(0,1) + sep + '0' + date.substring(1, 2) + sep + '20' + date.substring(2,4); break;
1471 case 5: date = '0' + date.substring(0,1) + sep + date.substring(1, 3) + sep + '20' + date.substring(3,5); break;
1472 case 6: date = date.substring(0,2) + sep + date.substring(2, 4) + sep + '20' + date.substring(4,6); break;
1473 case 8: date = date.substring(0,2) + sep + date.substring(2, 4) + sep + date.substring(4,8); break;
1478 date = date.replace(/[\/-]/g, sep);
1482 // find obj's position
1483 function findElementPos(obj) {
1486 if (obj.offsetParent) {
1487 while (obj.offsetParent) {
1488 x += obj.offsetLeft;
1490 obj = obj.offsetParent;
1492 }//if offsetParent exists
1493 else if (obj.x && obj.y) {
1497 return new coordinate(x, y);
1501 // get dimensions of the browser window
1502 function getClientDim() {
1503 var nwX, nwY, seX, seY;
1504 if (self.pageYOffset) // all except Explorer
1506 nwX = self.pageXOffset;
1507 seX = self.innerWidth + nwX;
1508 nwY = self.pageYOffset;
1509 seY = self.innerHeight + nwY;
1511 else if (document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
1513 nwX = document.documentElement.scrollLeft;
1514 seX = document.documentElement.clientWidth + nwX;
1515 nwY = document.documentElement.scrollTop;
1516 seY = document.documentElement.clientHeight + nwY;
1518 else if (document.body) // all other Explorers
1520 nwX = document.body.scrollLeft;
1521 seX = document.body.clientWidth + nwX;
1522 nwY = document.body.scrollTop;
1523 seY = document.body.clientHeight + nwY;
1525 return {'nw' : new coordinate(nwX, nwY), 'se' : new coordinate(seX, seY)};
1529 * stop propagation on events
1531 function freezeEvent(e) {
1533 if (e.preventDefault) e.preventDefault();
1534 e.returnValue = false;
1535 e.cancelBubble = true;
1536 if (e.stopPropagation) e.stopPropagation();
1545 function coordinate(_x, _y) {
1554 return new position(this.x + rh.x, this.y + rh.y);
1558 return new position(this.x + rh.x, this.y + rh.y);
1562 // sends theForm via AJAX and fills in the theDiv
1563 function sendAndRetrieve(theForm, theDiv, loadingStr) {
1564 function success(data) {
1565 document.getElementById(theDiv).innerHTML = data.responseText;
1566 ajaxStatus.hideStatus();
1568 if(typeof loadingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
1569 ajaxStatus.showStatus(loadingStr);
1570 YAHOO.util.Connect.setForm(theForm);
1571 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
1575 //save the form and redirect
1576 function sendAndRedirect(theForm, loadingStr, redirect_location) {
1577 function success(data) {
1578 if(redirect_location){
1579 location.href=redirect_location;
1581 ajaxStatus.hideStatus();
1583 if(typeof loadingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
1584 ajaxStatus.showStatus(loadingStr);
1585 YAHOO.util.Connect.setForm(theForm);
1586 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
1590 function saveForm(theForm, theDiv, loadingStr) {
1591 if(check_form(theForm)){
1592 for(i = 0; i < ajaxFormArray.length; i++){
1593 if(ajaxFormArray[i] == theForm){
1594 ajaxFormArray.splice(i, 1);
1597 return sendAndRetrieve(theForm, loadingStr, theDiv);
1603 // Builds a "snapshot" of the form, so we can use it to see if someone has changed it.
1604 function snapshotForm(theForm) {
1605 var snapshotTxt = '';
1606 var elemList = theForm.elements;
1610 for( var i = 0; i < elemList.length ; i++ ) {
1612 if ( typeof(elem.type) == 'undefined' ) {
1616 elemType = elem.type.toLowerCase();
1618 snapshotTxt = snapshotTxt + elem.name;
1620 if ( elemType == 'text' || elemType == 'textarea' || elemType == 'password' ) {
1621 snapshotTxt = snapshotTxt + elem.value;
1623 else if ( elemType == 'select' || elemType == 'select-one' || elemType == 'select-multiple' ) {
1624 var optionList = elem.options;
1625 for ( var ii = 0 ; ii < optionList.length ; ii++ ) {
1626 if ( optionList[ii].selected ) {
1627 snapshotTxt = snapshotTxt + optionList[ii].value;
1631 else if ( elemType == 'radio' || elemType == 'checkbox' ) {
1632 if ( elem.selected ) {
1633 snapshotTxt = snapshotTxt + 'checked';
1636 else if ( elemType == 'hidden' ) {
1637 snapshotTxt = snapshotTxt + elem.value;
1644 function initEditView(theForm) {
1645 if (SUGAR.util.ajaxCallInProgress()) {
1646 window.setTimeout(function(){initEditView(theForm);}, 100);
1650 if ( theForm == null || theForm.id == null ) {
1651 // Not much we can do here.
1655 // we don't need to check if the data is changed in the search popup
1656 if (theForm.id == 'popup_query_form' || theForm.id == 'MassUpdate') {
1659 if ( typeof editViewSnapshots == 'undefined' || editViewSnapshots == null ) {
1660 editViewSnapshots = new Object();
1662 if ( typeof SUGAR.loadedForms == 'undefined' || SUGAR.loadedForms == null) {
1663 SUGAR.loadedForms = new Object();
1666 editViewSnapshots[theForm.id] = snapshotForm(theForm);
1667 SUGAR.loadedForms[theForm.id] = true;
1670 function onUnloadEditView(theForm) {
1672 var dataHasChanged = false;
1674 if ( typeof editViewSnapshots == 'undefined' ) {
1675 // No snapshots, move along
1679 if ( typeof theForm == 'undefined' ) {
1680 // Need to check all editViewSnapshots
1681 for ( var idx in editViewSnapshots ) {
1683 theForm = document.getElementById(idx);
1684 // console.log('DEBUG: Checking all forms '+theForm.id);
1685 if ( theForm == null
1686 || typeof editViewSnapshots[theForm.id] == 'undefined'
1687 || editViewSnapshots[theForm.id] == null
1688 || !SUGAR.loadedForms[theForm.id]) {
1692 var snap = snapshotForm(theForm);
1693 if ( editViewSnapshots[theForm.id] != snap ) {
1694 dataHasChanged = true;
1698 // Just need to check a single form for changes
1699 if ( editViewSnapshots == null || typeof theForm.id == 'undefined' || typeof editViewSnapshots[theForm.id] == 'undefined' || editViewSnapshots[theForm.id] == null ) {
1703 // console.log('DEBUG: Checking one form '+theForm.id);
1704 if ( editViewSnapshots[theForm.id] != snapshotForm(theForm) ) {
1705 // Data has changed.
1706 dataHasChanged = true;
1710 if ( dataHasChanged == true ) {
1711 return SUGAR.language.get('app_strings','WARN_UNSAVED_CHANGES');
1718 function disableOnUnloadEditView(theForm) {
1719 // If you don't pass anything in, it disables all checking
1720 if ( typeof theForm == 'undefined' || typeof editViewSnapshots == 'undefined' || theForm == null || editViewSnapshots == null) {
1721 window.onbeforeunload = null;
1722 editViewSnapshots = null;
1724 // console.log('DEBUG: Disabling all edit view checks');
1727 // Otherwise, it just disables it for this form
1728 if ( typeof(theForm.id) != 'undefined' && typeof(editViewSnapshots[theForm.id]) != 'undefined' ) {
1729 editViewSnapshots[theForm.id] = null;
1732 // console.log('DEBUG : Disabling just checks for '+theForm.id);
1738 * save some forms using an ajax call
1739 * theForms - the ids of all of theh forms to save
1740 * savingStr - the string to display when saving the form
1741 * completeStr - the string to display when the form has been saved
1743 function saveForms( savingStr, completeStr) {
1745 theForms = ajaxFormArray;
1746 function success(data) {
1747 var theForm = document.getElementById(ajaxFormArray[0]);
1748 document.getElementById('multiedit_'+theForm.id).innerHTML = data.responseText;
1749 var saveAllButton = document.getElementById('ajaxsaveall');
1750 ajaxFormArray.splice(index, 1);
1751 if(saveAllButton && ajaxFormArray.length <= 1){
1752 saveAllButton.style.visibility = 'hidden';
1755 if(index == theForms.length){
1756 ajaxStatus.showStatus(completeStr);
1757 window.setTimeout('ajaxStatus.hideStatus();', 2000);
1759 saveAllButton.style.visibility = 'hidden';
1764 if(typeof savingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
1765 ajaxStatus.showStatus(savingStr);
1767 //loop through the forms saving each one
1768 for(i = 0; i < theForms.length; i++){
1769 var theForm = document.getElementById(theForms[i]);
1770 if(check_form(theForm.id)){
1771 theForm.action.value='AjaxFormSave';
1772 YAHOO.util.Connect.setForm(theForm);
1773 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
1775 ajaxStatus.hideStatus();
1777 lastSubmitTime = lastSubmitTime-2000;
1782 // -- start sugarListView class
1783 // js functions used for ListView
1784 function sugarListView() {
1788 sugarListView.prototype.confirm_action = function(del) {
1790 return confirm( SUGAR.language.get('app_strings', 'NTC_DELETE_CONFIRMATION_NUM') + sugarListView.get_num_selected() + SUGAR.language.get('app_strings', 'NTC_DELETE_SELECTED_RECORDS'));
1793 return confirm( SUGAR.language.get('app_strings', 'NTC_UPDATE_CONFIRMATION_NUM') + sugarListView.get_num_selected() + SUGAR.language.get('app_strings', 'NTC_DELETE_SELECTED_RECORDS'));
1797 sugarListView.get_num_selected = function () {
1798 if(typeof document.MassUpdate != 'undefined') {
1799 the_form = document.MassUpdate;
1800 for(wp = 0; wp < the_form.elements.length; wp++) {
1801 if(typeof the_form.elements[wp].name != 'undefined' && the_form.elements[wp].name == 'selectCount[]') {
1802 return the_form.elements[wp].value;
1809 sugarListView.update_count = function(count, add) {
1810 if(typeof document.MassUpdate != 'undefined') {
1811 the_form = document.MassUpdate;
1812 for(wp = 0; wp < the_form.elements.length; wp++) {
1813 if(typeof the_form.elements[wp].name != 'undefined' && the_form.elements[wp].name == 'selectCount[]') {
1815 the_form.elements[wp].value = parseInt(the_form.elements[wp].value,10) + count;
1816 if (the_form.select_entire_list.value == 1 && the_form.show_plus.value) {
1817 the_form.elements[wp].value += '+';
1820 if (the_form.select_entire_list.value == 1 && the_form.show_plus.value) {
1821 the_form.elements[wp].value = count + '+';
1823 the_form.elements[wp].value = count;
1830 sugarListView.prototype.use_external_mail_client = function(no_record_txt, module) {
1831 selected_records = sugarListView.get_checks_count();
1832 if(selected_records <1) {
1833 alert(no_record_txt);
1837 if (document.MassUpdate.select_entire_list.value == 1) {
1838 if (totalCount > 10) {
1839 alert(totalCountError);
1844 else if (document.MassUpdate.massall.checked == true)
1848 sugarListView.get_checks();
1850 if(select) { // use selected items
1851 ids = document.MassUpdate.uid.value;
1853 else { // use current page
1854 inputs = document.MassUpdate.elements;
1856 for(i = 0; i < inputs.length; i++) {
1857 if(inputs[i].name == 'mass[]' && inputs[i].checked && typeof(inputs[i].value) != 'function') {
1858 ar.push(inputs[i].value);
1863 YAHOO.util.Connect.asyncRequest("POST", "index.php?", {
1864 success: this.use_external_mail_client_callback
1865 }, SUGAR.util.paramsToUrl({
1868 listViewExternalClient: 1,
1869 action_module: module,
1877 sugarListView.prototype.use_external_mail_client_callback = function(o)
1880 location.href = 'mailto:' + o.responseText;
1883 sugarListView.prototype.send_form_for_emails = function(select, currentModule, action, no_record_txt,action_module,totalCount, totalCountError) {
1884 if ( typeof(SUGAR.config.email_sugarclient_listviewmaxselect) != 'undefined' ) {
1888 maxCount = SUGAR.config.email_sugarclient_listviewmaxselect;
1891 if (document.MassUpdate.select_entire_list.value == 1) {
1892 if (totalCount > maxCount) {
1893 alert(totalCountError);
1898 else if (document.MassUpdate.massall.checked == true)
1903 sugarListView.get_checks();
1904 // create new form to post (can't access action property of MassUpdate form due to action input)
1905 var newForm = document.createElement('form');
1906 newForm.method = 'post';
1907 newForm.action = action;
1908 newForm.name = 'newForm';
1909 newForm.id = 'newForm';
1910 var uidTa = document.createElement('textarea');
1912 uidTa.style.display = 'none';
1914 if(select) { // use selected items
1915 uidTa.value = document.MassUpdate.uid.value;
1917 else { // use current page
1918 inputs = document.MassUpdate.elements;
1920 for(i = 0; i < inputs.length; i++) {
1921 if(inputs[i].name == 'mass[]' && inputs[i].checked && typeof(inputs[i].value) != 'function') {
1922 ar.push(inputs[i].value);
1925 uidTa.value = ar.join(',');
1928 if(uidTa.value == '') {
1929 alert(no_record_txt);
1933 var selectedArray = uidTa.value.split(",");
1934 if(selectedArray.length > maxCount) {
1935 alert(totalCountError);
1938 newForm.appendChild(uidTa);
1940 var moduleInput = document.createElement('input');
1941 moduleInput.name = 'module';
1942 moduleInput.type = 'hidden';
1943 moduleInput.value = currentModule;
1944 newForm.appendChild(moduleInput);
1946 var actionInput = document.createElement('input');
1947 actionInput.name = 'action';
1948 actionInput.type = 'hidden';
1949 actionInput.value = 'Compose';
1950 newForm.appendChild(actionInput);
1952 if (typeof action_module != 'undefined' && action_module!= '') {
1953 var actionModule = document.createElement('input');
1954 actionModule.name = 'action_module';
1955 actionModule.type = 'hidden';
1956 actionModule.value = action_module;
1957 newForm.appendChild(actionModule);
1959 //return_info must follow this pattern."&return_module=Accounts&return_action=index"
1960 if (typeof return_info!= 'undefined' && return_info != '') {
1961 var params= return_info.split('&');
1962 if (params.length > 0) {
1963 for (var i=0;i< params.length;i++) {
1964 if (params[i].length > 0) {
1965 var param_nv=params[i].split('=');
1966 if (param_nv.length==2){
1967 returnModule = document.createElement('input');
1968 returnModule.name = param_nv[0];
1969 returnModule.type = 'hidden';
1970 returnModule.value = param_nv[1];
1971 newForm.appendChild(returnModule);
1978 var isAjaxCall = document.createElement('input');
1979 isAjaxCall.name = 'ajaxCall';
1980 isAjaxCall.type = 'hidden';
1981 isAjaxCall.value = true;
1982 newForm.appendChild(isAjaxCall);
1984 var isListView = document.createElement('input');
1985 isListView.name = 'ListView';
1986 isListView.type = 'hidden';
1987 isListView.value = true;
1988 newForm.appendChild(isListView);
1990 var toPdf = document.createElement('input');
1991 toPdf.name = 'to_pdf';
1992 toPdf.type = 'hidden';
1994 newForm.appendChild(toPdf);
1996 //Grab the Quick Compose package for the listview
1997 YAHOO.util.Connect.setForm(newForm);
2000 success: function(o) {
2001 var resp = YAHOO.lang.JSON.parse(o.responseText);
2002 var quickComposePackage = new Object();
2003 quickComposePackage.composePackage = resp;
2004 quickComposePackage.fullComposeUrl = 'index.php?module=Emails&action=Compose&ListView=true' +
2005 '&uid=' + uidTa.value + '&action_module=' + action_module;
2007 SUGAR.quickCompose.init(quickComposePackage);
2011 YAHOO.util.Connect.asyncRequest('POST','index.php', callback,null);
2013 // awu Bug 18624: Fixing issue where a canceled Export and unselect of row will persist the uid field, clear the field
2014 document.MassUpdate.uid.value = '';
2019 sugarListView.prototype.send_form = function(select, currentModule, action, no_record_txt,action_module,return_info) {
2020 if (document.MassUpdate.select_entire_list.value == 1) {
2022 if(sugarListView.get_checks_count() < 1) {
2023 alert(no_record_txt);
2028 if ( action.indexOf('?') != -1 )
2029 href += '&module=' + currentModule;
2031 href += '?module=' + currentModule;
2034 href += return_info;
2035 var newForm = document.createElement('form');
2036 newForm.method = 'post';
2037 newForm.action = href;
2038 newForm.name = 'newForm';
2039 newForm.id = 'newForm';
2040 var postTa = document.createElement('textarea');
2041 postTa.name = 'current_post';
2042 postTa.value = document.MassUpdate.current_query_by_page.value;
2043 postTa.style.display = 'none';
2044 newForm.appendChild(postTa);
2045 document.MassUpdate.parentNode.appendChild(newForm);
2049 else if (document.MassUpdate.massall.checked == true)
2054 sugarListView.get_checks();
2055 // create new form to post (can't access action property of MassUpdate form due to action input)
2056 var newForm = document.createElement('form');
2057 newForm.method = 'post';
2058 newForm.action = action;
2059 newForm.name = 'newForm';
2060 newForm.id = 'newForm';
2061 var uidTa = document.createElement('textarea');
2063 uidTa.style.display = 'none';
2064 uidTa.value = document.MassUpdate.uid.value;
2066 if(uidTa.value == '') {
2067 alert(no_record_txt);
2071 newForm.appendChild(uidTa);
2073 var moduleInput = document.createElement('input');
2074 moduleInput.name = 'module';
2075 moduleInput.type = 'hidden';
2076 moduleInput.value = currentModule;
2077 newForm.appendChild(moduleInput);
2079 var actionInput = document.createElement('input');
2080 actionInput.name = 'action';
2081 actionInput.type = 'hidden';
2082 actionInput.value = 'index';
2083 newForm.appendChild(actionInput);
2085 if (typeof action_module != 'undefined' && action_module!= '') {
2086 var actionModule = document.createElement('input');
2087 actionModule.name = 'action_module';
2088 actionModule.type = 'hidden';
2089 actionModule.value = action_module;
2090 newForm.appendChild(actionModule);
2092 //return_info must follow this pattern."&return_module=Accounts&return_action=index"
2093 if (typeof return_info!= 'undefined' && return_info != '') {
2094 var params= return_info.split('&');
2095 if (params.length > 0) {
2096 for (var i=0;i< params.length;i++) {
2097 if (params[i].length > 0) {
2098 var param_nv=params[i].split('=');
2099 if (param_nv.length==2){
2100 returnModule = document.createElement('input');
2101 returnModule.name = param_nv[0];
2102 returnModule.type = 'hidden';
2103 returnModule.value = param_nv[1];
2104 newForm.appendChild(returnModule);
2111 document.MassUpdate.parentNode.appendChild(newForm);
2114 // awu Bug 18624: Fixing issue where a canceled Export and unselect of row will persist the uid field, clear the field
2115 document.MassUpdate.uid.value = '';
2119 //return a count of checked row.
2120 sugarListView.get_checks_count = function() {
2123 if(document.MassUpdate.uid.value != '') {
2124 oldUids = document.MassUpdate.uid.value.split(',');
2125 for(uid in oldUids) {
2126 if(typeof(oldUids[uid]) != 'function') {
2127 ar[oldUids[uid]] = 1;
2131 // build associated array of uids, associated array ensures uniqueness
2132 inputs = document.MassUpdate.elements;
2133 for(i = 0; i < inputs.length; i++) {
2134 if(inputs[i].name == 'mass[]') {
2135 ar[inputs[i].value] = (inputs[i].checked) ? 1 : 0; // 0 of it is unchecked
2139 // build regular array of uids
2142 if((typeof(ar[i]) != 'function') && ar[i] == 1) {
2150 // saves the checks on the current page into the uid textarea
2151 sugarListView.get_checks = function() {
2154 if(document.MassUpdate.uid.value != '') {
2155 oldUids = document.MassUpdate.uid.value.split(',');
2156 for(uid in oldUids) {
2157 if(typeof(oldUids[uid]) != 'function') {
2158 ar[oldUids[uid]] = 1;
2163 // build associated array of uids, associated array ensures uniqueness
2164 inputs = document.MassUpdate.elements;
2165 for(i = 0; i < inputs.length; i++) {
2166 if(inputs[i].name == 'mass[]') {
2167 ar[inputs[i].value] = (inputs[i].checked) ? 1 : 0; // 0 of it is unchecked
2171 // build regular array of uids
2174 if(typeof(ar[i]) != 'function' && ar[i] == 1) {
2179 document.MassUpdate.uid.value = uids.join(',');
2181 if(uids.length == 0) return false; // return false if no checks to get
2182 return true; // there are saved checks
2185 sugarListView.prototype.order_checks = function(order,orderBy,moduleString){
2186 checks = sugarListView.get_checks();
2187 eval('document.MassUpdate.' + moduleString + '.value = orderBy');
2188 document.MassUpdate.lvso.value = order;
2189 if(typeof document.MassUpdate.massupdate != 'undefined') {
2190 document.MassUpdate.massupdate.value = 'false';
2193 //we must first clear the action of massupdate, change it to index
2194 document.MassUpdate.action.value = document.MassUpdate.return_action.value;
2195 document.MassUpdate.return_module.value='';
2196 document.MassUpdate.return_action.value='';
2197 document.MassUpdate.submit();
2201 sugarListView.prototype.save_checks = function(offset, moduleString) {
2202 checks = sugarListView.get_checks();
2203 eval('document.MassUpdate.' + moduleString + '.value = offset');
2205 if(typeof document.MassUpdate.massupdate != 'undefined') {
2206 document.MassUpdate.massupdate.value = 'false';
2209 //we must first clear the action of massupdate, change it to index
2210 document.MassUpdate.action.value = document.MassUpdate.return_action.value;
2211 document.MassUpdate.return_module.value='';
2212 document.MassUpdate.return_action.value='';
2213 document.MassUpdate.submit();
2219 sugarListView.prototype.check_item = function(cb, form) {
2221 sugarListView.update_count(1, true);
2223 sugarListView.update_count(-1, true);
2224 if(typeof form != 'undefined' && form != null) {
2225 sugarListView.prototype.updateUid(cb, form);
2230 /**#28000, remove the unselect record id from MassUpdate.uid **/
2231 sugarListView.prototype.updateUid = function(cb , form){
2232 if(form.name == 'MassUpdate' && form.uid && form.uid.value && cb.value && form.uid.value.indexOf(cb.value) != -1){
2233 if(form.uid.value.indexOf(','+cb.value)!= -1){
2234 form.uid.value = form.uid.value.replace(','+cb.value , '');
2235 }else if(form.uid.value.indexOf(cb.value + ',')!= -1){
2236 form.uid.value = form.uid.value.replace(cb.value + ',' , '');
2237 }else if(form.uid.value.indexOf(cb.value)!= -1){
2238 form.uid.value = form.uid.value.replace(cb.value , '');
2243 sugarListView.prototype.check_entire_list = function(form, field, value, list_count) {
2244 // count number of items
2246 document.MassUpdate.massall.checked = true;
2247 document.MassUpdate.massall.disabled = true;
2249 for (i = 0; i < form.elements.length; i++) {
2250 if(form.elements[i].name == field && form.elements[i].disabled == false) {
2251 if(form.elements[i].checked != value) count++;
2252 form.elements[i].checked = value;
2253 form.elements[i].disabled = true;
2256 document.MassUpdate.select_entire_list.value = 1;
2258 sugarListView.update_count(list_count, false);
2259 //else sugarListView.update_count(-1 * count, true);
2262 sugarListView.prototype.check_all = function(form, field, value, pageTotal) {
2263 // count number of items
2265 document.MassUpdate.massall.checked = value;
2266 if (document.MassUpdate.select_entire_list &&
2267 document.MassUpdate.select_entire_list.value == 1)
2268 document.MassUpdate.massall.disabled = true;
2270 document.MassUpdate.massall.disabled = false;
2272 for (i = 0; i < form.elements.length; i++) {
2273 if(form.elements[i].name == field && !(form.elements[i].disabled == true && form.elements[i].checked == false)) {
2274 form.elements[i].disabled = false;
2276 if(form.elements[i].checked != value)
2278 form.elements[i].checked = value;
2280 sugarListView.prototype.updateUid(form.elements[i], form);
2285 sugarListView.update_count(pageTotal);
2287 sugarListView.update_count(count, true);
2289 sugarListView.update_count(-1 * count, true);
2291 sugarListView.check_all = sugarListView.prototype.check_all;
2292 sugarListView.confirm_action = sugarListView.prototype.confirm_action;
2294 sugarListView.prototype.check_boxes = function() {
2295 var inputsCount = 0;
2296 var checkedCount = 0;
2297 var existing_onload = window.onload;
2298 var theForm = document.MassUpdate;
2299 inputs_array = theForm.elements;
2301 if(typeof theForm.uid.value != 'undefined' && theForm.uid.value != "") {
2302 checked_items = theForm.uid.value.split(",");
2303 if (theForm.select_entire_list.value == 1)
2304 document.MassUpdate.massall.disabled = true;
2306 for(wp = 0 ; wp < inputs_array.length; wp++) {
2307 if(inputs_array[wp].name == "mass[]") {
2309 if (theForm.select_entire_list.value == 1) {
2310 inputs_array[wp].checked = true;
2311 inputs_array[wp].disabled = true;
2315 for(i in checked_items) {
2316 if(inputs_array[wp].value == checked_items[i]) {
2318 inputs_array[wp].checked = true;
2324 if (theForm.select_entire_list.value == 0)
2325 sugarListView.update_count(checked_items.length);
2327 sugarListView.update_count(0, true);
2331 for(wp = 0 ; wp < inputs_array.length; wp++) {
2332 if(inputs_array[wp].name == "mass[]") {
2333 inputs_array[wp].checked = false;
2334 inputs_array[wp].disabled = false;
2337 if (document.MassUpdate.massall) {
2338 document.MassUpdate.massall.checked = false;
2339 document.MassUpdate.massall.disabled = false;
2341 sugarListView.update_count(0)
2343 if(checkedCount > 0 && checkedCount == inputsCount)
2344 document.MassUpdate.massall.checked = true;
2350 * This function is used in Email Template Module's listview.
2351 * It will check whether the templates are used in Campaing->EmailMarketing.
2352 * If true, it will notify user.
2354 function check_used_email_templates() {
2355 var ids = document.MassUpdate.uid.value;
2357 success:function(r) {
2358 if(r.responseText != '') {
2359 if(!confirm(SUGAR.language.get('app_strings','NTC_TEMPLATES_IS_USED') + r.responseText)) {
2363 document.MassUpdate.submit();
2367 url = "index.php?module=EmailTemplates&action=CheckDeletable&from=ListView&to_pdf=1&records="+ids;
2368 YAHOO.util.Connect.asyncRequest('POST',url, call_back,null);
2372 sugarListView.prototype.send_mass_update = function(mode, no_record_txt, del) {
2373 formValid = check_form('MassUpdate');
2374 if(!formValid && !del) return false;
2377 if (document.MassUpdate.select_entire_list &&
2378 document.MassUpdate.select_entire_list.value == 1)
2383 var ar = new Array();
2387 for(wp = 0; wp < document.MassUpdate.elements.length; wp++) {
2388 var reg_for_existing_uid = new RegExp('^'+RegExp.escape(document.MassUpdate.elements[wp].value)+'[\s]*,|,[\s]*'+RegExp.escape(document.MassUpdate.elements[wp].value)+'[\s]*,|,[\s]*'+RegExp.escape(document.MassUpdate.elements[wp].value)+'$|^'+RegExp.escape(document.MassUpdate.elements[wp].value)+'$');
2389 //when the uid is already in document.MassUpdate.uid.value, we should not add it to ar.
2390 if(typeof document.MassUpdate.elements[wp].name != 'undefined'
2391 && document.MassUpdate.elements[wp].name == 'mass[]'
2392 && document.MassUpdate.elements[wp].checked
2393 && !reg_for_existing_uid.test(document.MassUpdate.uid.value)) {
2394 ar.push(document.MassUpdate.elements[wp].value);
2397 if(document.MassUpdate.uid.value != '') document.MassUpdate.uid.value += ',';
2398 document.MassUpdate.uid.value += ar.join(',');
2399 if(document.MassUpdate.uid.value == '') {
2400 alert(no_record_txt);
2403 if(typeof(current_admin_id)!='undefined' && document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'Users' && (document.MassUpdate.is_admin.value!='' || document.MassUpdate.status.value!='')) {
2404 var reg_for_current_admin_id = new RegExp('^'+current_admin_id+'[\s]*,|,[\s]*'+current_admin_id+'[\s]*,|,[\s]*'+current_admin_id+'$|^'+current_admin_id+'$');
2405 if(reg_for_current_admin_id.test(document.MassUpdate.uid.value)) {
2406 //if current user is admin, we should not allow massupdate the user_type and status of himself
2407 alert(SUGAR.language.get('Users','LBL_LAST_ADMIN_NOTICE'));
2413 var entireInput = document.createElement('input');
2414 entireInput.name = 'entire';
2415 entireInput.type = 'hidden';
2416 entireInput.value = 'index';
2417 document.MassUpdate.appendChild(entireInput);
2418 //confirm(no_record_txt);
2419 if(document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'Users' && (document.MassUpdate.is_admin.value!='' || document.MassUpdate.status.value!='')) {
2420 alert(SUGAR.language.get('Users','LBL_LAST_ADMIN_NOTICE'));
2426 if(!sugarListView.confirm_action(del))
2430 var deleteInput = document.createElement('input');
2431 deleteInput.name = 'Delete';
2432 deleteInput.type = 'hidden';
2433 deleteInput.value = true;
2434 document.MassUpdate.appendChild(deleteInput);
2435 if(document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'EmailTemplates') {
2436 check_used_email_templates();
2442 document.MassUpdate.submit();
2447 sugarListView.prototype.clear_all = function() {
2448 document.MassUpdate.uid.value = '';
2449 document.MassUpdate.select_entire_list.value = 0;
2450 sugarListView.check_all(document.MassUpdate, 'mass[]', false);
2451 document.MassUpdate.massall.checked = false;
2452 document.MassUpdate.massall.disabled = false;
2453 sugarListView.update_count(0);
2456 sListView = new sugarListView();
2457 // -- end sugarListView class
2459 // format and unformat numbers
2460 function unformatNumber(n, num_grp_sep, dec_sep) {
2461 var x=unformatNumberNoParse(n, num_grp_sep, dec_sep);
2464 return parseFloat(x);
2469 function unformatNumberNoParse(n, num_grp_sep, dec_sep) {
2470 if(typeof num_grp_sep == 'undefined' || typeof dec_sep == 'undefined') return n;
2471 n = n ? n.toString() : '';
2474 if(num_grp_sep != '')
2476 num_grp_sep_re = new RegExp('\\'+num_grp_sep, 'g');
2477 n = n.replace(num_grp_sep_re, '');
2480 n = n.replace(dec_sep, '.');
2482 if(typeof CurrencySymbols != 'undefined') {
2483 // Need to strip out the currency symbols from the start.
2484 for ( var idx in CurrencySymbols ) {
2485 n = n.replace(CurrencySymbols[idx], '');
2493 // round parameter can be negative for decimal, precision has to be postive
2494 function formatNumber(n, num_grp_sep, dec_sep, round, precision) {
2495 if(typeof num_grp_sep == 'undefined' || typeof dec_sep == 'undefined') return n;
2496 n = n ? n.toString() : '';
2497 if(n.split) n = n.split('.');
2500 if(n.length > 2) return n.join('.'); // that's not a num!
2502 if(typeof round != 'undefined') {
2503 if(round > 0 && n.length > 1) { // round to decimal
2504 n[1] = parseFloat('0.' + n[1]);
2505 n[1] = Math.round(n[1] * Math.pow(10, round)) / Math.pow(10, round);
2506 n[1] = n[1].toString().split('.')[1];
2508 if(round <= 0) { // round to whole number
2509 n[0] = Math.round(parseInt(n[0],10) * Math.pow(10, round)) / Math.pow(10, round);
2514 if(typeof precision != 'undefined' && precision >= 0) {
2515 if(n.length > 1 && typeof n[1] != 'undefined') n[1] = n[1].substring(0, precision); // cut off precision
2517 if(n[1].length < precision) {
2518 for(var wp = n[1].length; wp < precision; wp++) n[1] += '0';
2522 regex = /(\d+)(\d{3})/;
2523 while(num_grp_sep != '' && regex.test(n[0])) n[0] = n[0].toString().replace(regex, '$1' + num_grp_sep + '$2');
2524 return n[0] + (n.length > 1 && n[1] != '' ? dec_sep + n[1] : '');
2527 // --- begin ajax status class
2528 SUGAR.ajaxStatusClass = function() {};
2529 SUGAR.ajaxStatusClass.prototype.statusDiv = null;
2530 SUGAR.ajaxStatusClass.prototype.oldOnScroll = null;
2531 SUGAR.ajaxStatusClass.prototype.shown = false; // state of the status window
2533 // reposition the status div, top and centered
2534 SUGAR.ajaxStatusClass.prototype.positionStatus = function() {
2535 //this.statusDiv.style.top = document.body.scrollTop + 8 + 'px';
2536 statusDivRegion = YAHOO.util.Dom.getRegion(this.statusDiv);
2537 statusDivWidth = statusDivRegion.right - statusDivRegion.left;
2538 this.statusDiv.style.left = YAHOO.util.Dom.getViewportWidth() / 2 - statusDivWidth / 2 + 'px';
2541 // private func, create the status div
2542 SUGAR.ajaxStatusClass.prototype.createStatus = function(text) {
2543 statusDiv = document.createElement('div');
2544 statusDiv.className = 'dataLabel';
2545 statusDiv.id = 'ajaxStatusDiv';
2546 document.body.appendChild(statusDiv);
2547 this.statusDiv = document.getElementById('ajaxStatusDiv');
2550 // public - show the status div with text
2551 SUGAR.ajaxStatusClass.prototype.showStatus = function(text) {
2552 if(!this.statusDiv) {
2553 this.createStatus(text);
2556 this.statusDiv.style.display = '';
2558 this.statusDiv.innerHTML = ' <b>' + text + '</b> ';
2559 this.positionStatus();
2562 this.statusDiv.style.display = '';
2563 if(window.onscroll) this.oldOnScroll = window.onscroll; // save onScroll
2564 window.onscroll = this.positionStatus;
2569 SUGAR.ajaxStatusClass.prototype.hideStatus = function(text) {
2570 if(!this.shown) return;
2572 if(this.oldOnScroll) window.onscroll = this.oldOnScroll;
2573 else window.onscroll = '';
2574 this.statusDiv.style.display = 'none';
2577 SUGAR.ajaxStatusClass.prototype.flashStatus = function(text, time){
2578 this.showStatus(text);
2579 window.setTimeout('ajaxStatus.hideStatus();', time);
2583 var ajaxStatus = new SUGAR.ajaxStatusClass();
2584 // --- end ajax status class
2587 * Unified Search Advanced - for global search
2589 SUGAR.unifiedSearchAdvanced = function() {
2599 SUGAR.unifiedSearchAdvanced.usa_div = document.getElementById('unified_search_advanced_div');
2600 SUGAR.unifiedSearchAdvanced.usa_img = document.getElementById('unified_search_advanced_img');
2602 if(!SUGAR.unifiedSearchAdvanced.usa_div || !SUGAR.unifiedSearchAdvanced.usa_img) return;
2603 var attributes = { height: { to: 300 } };
2604 SUGAR.unifiedSearchAdvanced.anim_open = new YAHOO.util.Anim('unified_search_advanced_div', attributes );
2605 SUGAR.unifiedSearchAdvanced.anim_open.duration = 0.75;
2606 SUGAR.unifiedSearchAdvanced.anim_close = new YAHOO.util.Anim('unified_search_advanced_div', { height: {to: 0} } );
2607 SUGAR.unifiedSearchAdvanced.anim_close.duration = 0.75;
2608 //SUGAR.unifiedSearchAdvanced.anim_close.onComplete.subscribe(function() {SUGAR.unifiedSearchAdvanced.usa_div.style.display = 'none'});
2610 SUGAR.unifiedSearchAdvanced.usa_img._x = YAHOO.util.Dom.getX(SUGAR.unifiedSearchAdvanced.usa_img);
2611 SUGAR.unifiedSearchAdvanced.usa_img._y = YAHOO.util.Dom.getY(SUGAR.unifiedSearchAdvanced.usa_img);
2614 SUGAR.unifiedSearchAdvanced.usa_open = false;
2615 SUGAR.unifiedSearchAdvanced.usa_content = null;
2617 YAHOO.util.Event.addListener('unified_search_advanced_img', 'click', SUGAR.unifiedSearchAdvanced.get_content);
2620 get_content: function(e)
2622 query_string = trim(document.getElementById('query_string').value);
2623 if(query_string != '')
2625 window.location.href = 'index.php?module=Home&action=UnifiedSearch&query_string=' + query_string;
2627 window.location.href = 'index.php?module=Home&action=UnifiedSearch&form_only=true';
2631 animate: function(data) {
2632 ajaxStatus.hideStatus();
2635 SUGAR.unifiedSearchAdvanced.usa_content = data.responseText;
2636 SUGAR.unifiedSearchAdvanced.usa_div.innerHTML = SUGAR.unifiedSearchAdvanced.usa_content;
2638 if(SUGAR.unifiedSearchAdvanced.usa_open) {
2639 document.UnifiedSearch.advanced.value = 'false';
2640 SUGAR.unifiedSearchAdvanced.anim_close.animate();
2643 document.UnifiedSearch.advanced.value = 'true';
2644 SUGAR.unifiedSearchAdvanced.usa_div.style.display = '';
2645 YAHOO.util.Dom.setX(SUGAR.unifiedSearchAdvanced.usa_div, SUGAR.unifiedSearchAdvanced.usa_img._x - 90);
2646 YAHOO.util.Dom.setY(SUGAR.unifiedSearchAdvanced.usa_div, SUGAR.unifiedSearchAdvanced.usa_img._y + 15);
2647 SUGAR.unifiedSearchAdvanced.anim_open.animate();
2649 SUGAR.unifiedSearchAdvanced.usa_open = !SUGAR.unifiedSearchAdvanced.usa_open;
2654 checkUsaAdvanced: function() {
2655 if(document.UnifiedSearch.advanced.value == 'true') {
2656 document.UnifiedSearchAdvanced.query_string.value = document.UnifiedSearch.query_string.value;
2657 document.UnifiedSearchAdvanced.submit();
2664 if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.unifiedSearchAdvanced.init);
2669 * Toggles the header
2671 toggleHeader : function() {
2672 var h = document.getElementById('header');
2676 if(h.style.display == 'none') {
2677 h.style.display = '';
2679 h.style.display = 'none';
2683 alert(SUGAR.language.get("app_strings", "ERR_NO_HEADER_ID"));
2690 * General Sugar Utils
2692 SUGAR.util = function () {
2693 var additionalDetailsCache;
2694 var additionalDetailsCalls;
2695 var additionalDetailsRpcCall;
2698 getAndRemove : function (el) {
2699 if (YAHOO && YAHOO.util && YAHOO.util.Dom)
2700 el = YAHOO.util.Dom.get(el);
2701 else if (typeof (el) == "string")
2702 el = document.getElementById(el);
2703 if (el && el.parentNode)
2704 el.parentNode.removeChild(el);
2708 paramsToUrl : function (params) {
2711 url += i + "=" + params[i] + "&";
2715 evalScript:function(text){
2717 var waitUntilLoaded = function(){
2718 SUGAR.evalScript_waitCount--;
2719 if (SUGAR.evalScript_waitCount == 0) {
2720 var headElem = document.getElementsByTagName('head')[0];
2721 for ( var i = 0; i < SUGAR.evalScript_evalElem.length; i++) {
2722 var tmpElem = document.createElement('script');
2723 tmpElem.type = 'text/javascript';
2724 tmpElem.text = SUGAR.evalScript_evalElem[i];
2725 headElem.appendChild(tmpElem);
2730 var tmpElem = document.createElement('div');
2731 tmpElem.innerHTML = text;
2732 var results = tmpElem.getElementsByTagName('script');
2733 if (results == null) {
2734 // No scripts found, bail out
2738 var headElem = document.getElementsByTagName('head')[0];
2740 SUGAR.evalScript_waitCount = 0;
2741 SUGAR.evalScript_evalElem = new Array();
2742 for (var i = 0; i < results.length; i++) {
2743 if (typeof(results[i]) != 'object') {
2746 tmpElem = document.createElement('script');
2747 tmpElem.type = 'text/javascript';
2748 if (results[i].src != null && results[i].src != '') {
2749 tmpElem.src = results[i].src;
2751 // Need to defer execution of these scripts until the
2752 // required javascript files are fully loaded
2753 SUGAR.evalScript_evalElem[SUGAR.evalScript_evalElem.length] = results[i].text;
2756 tmpElem.addEventListener('load', waitUntilLoaded);
2757 SUGAR.evalScript_waitCount++;
2758 headElem.appendChild(tmpElem);
2760 // Add some code to handle pages without any external scripts
2761 SUGAR.evalScript_waitCount++;
2764 // Don't try and process things the IE way
2768 var objRegex = /<\s*script([^>]*)>((.|\s|\v|\0)*?)<\s*\/script\s*>/igm;
2770 var result = objRegex.exec(text);
2771 while(result && result.index > lastIndex){
2772 lastIndex = result.index
2774 var script = document.createElement('script');
2775 script.type= 'text/javascript';
2776 if(result[1].indexOf("src=") > -1){
2777 var srcRegex = /.*src=['"]([a-zA-Z0-9_\&\/\.\?=:]*)['"].*/igm;
2778 var srcResult = result[1].replace(srcRegex, '$1');
2779 script.src = srcResult;
2781 script.text = result[2];
2783 document.body.appendChild(script);
2786 if(typeof(console) != "undefined" && typeof(console.log) == "function")
2788 console.log("error adding script");
2790 console.log(result);
2793 result = objRegex.exec(text);
2797 * Gets the sidebar object
2798 * @return object pointer to the sidebar element
2800 getLeftColObj: function() {
2801 leftColObj = document.getElementById('leftCol');
2802 while(leftColObj.nodeName != 'TABLE') {
2803 leftColObj = leftColObj.firstChild;
2805 leftColTable = leftColObj;
2806 leftColTd = leftColTable.getElementsByTagName('td')[0];
2807 leftColTdRegion = YAHOO.util.Dom.getRegion(leftColTd);
2808 leftColTd.style.width = (leftColTdRegion.right - leftColTdRegion.left) + 'px';
2813 * Fills the shortcut menu placeholders w/ actual content
2814 * Call this on load event
2816 * @param shortcutContent Array array of content to fill in
2818 fillShortcuts: function(e, shortcutContent) {
2821 // don't do this if leftCol isn't available
2822 if (document.getElementById('leftCol') == undefined) { return; }
2824 spans = document.getElementById('leftCol').getElementsByTagName('span');
2825 hideCol = document.getElementById('HideMenu').getElementsByTagName('span');
2826 w = spans.length + 1;
2828 spans[w] = hideCol[i];
2831 for(je in shortcutContent) {
2833 if(typeof spans[wp].innerHTML != 'undefined' && spans[wp].innerHTML == ('wp_shortcut_fill_' + je)) {
2834 if(typeof spans[wp].parentNode.parentNode == 'object') {
2835 if(typeof spans[wp].parentNode.parentNode.onclick != 'undefined') {
2836 spans[wp].parentNode.parentNode.onclick = null;
2838 // If the wp_shortcut span is contained by an A tag, replace the A with a DIV.
2839 if(spans[wp].parentNode.tagName == 'A' && !isIE) {
2840 var newDiv = document.createElement('DIV');
2841 var parentAnchor = spans[wp].parentNode;
2843 spans[wp].parentNode.parentNode.style.display = 'none';
2845 // Copy styles over to the new container div
2846 if(window.getComputedStyle) {
2847 var parentStyle = window.getComputedStyle(parentAnchor, '');
2848 for(var styleName in parentStyle) {
2849 if(typeof parentStyle[styleName] != 'function'
2850 && styleName != 'display'
2851 && styleName != 'borderWidth'
2852 && styleName != 'visibility') {
2854 newDiv.style[styleName] = parentStyle[styleName];
2856 // Catches .length and .parentRule, and others
2862 // Replace the A with the DIV
2863 newDiv.appendChild(spans[wp]);
2864 parentAnchor.parentNode.replaceChild(newDiv, parentAnchor);
2866 spans[wp].parentNode.parentNode.style.display = '';
2869 spans[wp].innerHTML = shortcutContent[je]; // fill w/ content
2870 if(spans[wp].style) spans[wp].style.display = '';
2876 * Make an AJAX request.
2878 * @param url string resource to load
2879 * @param theDiv string id of element to insert loaded data into
2880 * @param postForm string if set, a POST request will be made to resource specified by url using the form named by postForm
2881 * @param callback string name of function to invoke after HTTP response is recieved
2882 * @param callbackParam any parameter to pass to callback when invoked
2883 * @param appendMode bool if true, HTTP response will be appended to the contents of theDiv, or else contents will be overriten.
2885 retrieveAndFill: function(url, theDiv, postForm, callback, callbackParam, appendMode) {
2886 if(typeof theDiv == 'string') {
2888 theDiv = document.getElementById(theDiv);
2895 var success = function(data) {
2896 if (typeof theDiv != 'undefined' && theDiv != null)
2899 if (typeof appendMode != 'undefined' && appendMode)
2901 theDiv.innerHTML += data.responseText;
2905 theDiv.innerHTML = data.responseText;
2912 if (typeof callback != 'undefined' && callback != null) callback(callbackParam);
2915 if(typeof postForm == 'undefined' || postForm == null) {
2916 var cObj = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
2919 YAHOO.util.Connect.setForm(postForm);
2920 var cObj = YAHOO.util.Connect.asyncRequest('POST', url, {success: success, failure: success});
2923 checkMaxLength: function() { // modified from http://www.quirksmode.org/dom/maxlength.html
2924 var maxLength = this.getAttribute('maxlength');
2925 var currentLength = this.value.length;
2926 if (currentLength > maxLength) {
2927 this.value = this.value.substring(0, maxLength);
2932 * Adds maxlength attribute to textareas
2934 setMaxLength: function() { // modified from http://www.quirksmode.org/dom/maxlength.html
2935 var x = document.getElementsByTagName('textarea');
2936 for (var i=0;i<x.length;i++) {
2937 if (x[i].getAttribute('maxlength')) {
2938 x[i].onkeyup = x[i].onchange = SUGAR.util.checkMaxLength;
2945 * Retrieves additional details dynamically
2947 getAdditionalDetails: function(bean, id, spanId) {
2949 oReturn = function(body, caption, width, theme) {
2950 var _refx = 25-width;
2951 return overlib(body, CAPTION, caption, STICKY, MOUSEOFF, 1000, WIDTH, width, CLOSETEXT, ('<img border=0 style="margin-left:2px; margin-right: 2px;" src=index.php?entryPoint=getImage&themeName='+SUGAR.themes.theme_name+'&imageName=close.gif>'), CLOSETITLE, SUGAR.language.get('app_strings','LBL_ADDITIONAL_DETAILS_CLOSE_TITLE'), CLOSECLICK, FGCLASS, 'olFgClass', CGCLASS, 'olCgClass', BGCLASS, 'olBgClass', TEXTFONTCLASS, 'olFontClass', CAPTIONFONTCLASS, 'olCapFontClass', CLOSEFONTCLASS, 'olCloseFontClass', REF, spanId, REFC, 'LL', REFX, _refx);
2954 success = function(data) {
2955 eval(data.responseText);
2957 SUGAR.util.additionalDetailsCache[spanId] = new Array();
2958 SUGAR.util.additionalDetailsCache[spanId]['body'] = result['body'];
2959 SUGAR.util.additionalDetailsCache[spanId]['caption'] = result['caption'];
2960 SUGAR.util.additionalDetailsCache[spanId]['width'] = result['width'];
2961 SUGAR.util.additionalDetailsCache[spanId]['theme'] = result['theme'];
2962 ajaxStatus.hideStatus();
2963 return oReturn(SUGAR.util.additionalDetailsCache[spanId]['body'], SUGAR.util.additionalDetailsCache[spanId]['caption'], SUGAR.util.additionalDetailsCache[spanId]['width'], SUGAR.util.additionalDetailsCache[spanId]['theme']);
2966 if(typeof SUGAR.util.additionalDetailsCache[spanId] != 'undefined')
2967 return oReturn(SUGAR.util.additionalDetailsCache[spanId]['body'], SUGAR.util.additionalDetailsCache[spanId]['caption'], SUGAR.util.additionalDetailsCache[spanId]['width'], SUGAR.util.additionalDetailsCache[spanId]['theme']);
2969 if(typeof SUGAR.util.additionalDetailsCalls[spanId] != 'undefined') // call already in progress
2971 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_LOADING'));
2972 url = 'index.php?to_pdf=1&module=Home&action=AdditionalDetailsRetrieve&bean=' + bean + '&id=' + id;
2973 SUGAR.util.additionalDetailsCalls[spanId] = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
2977 SUGAR.util.additionalDetailsRpcCall = window.setTimeout('go()', 250);
2979 clearAdditionalDetailsCall: function() {
2980 if(typeof SUGAR.util.additionalDetailsRpcCall == 'number') window.clearTimeout(SUGAR.util.additionalDetailsRpcCall);
2983 * A function that extends functionality from parent to child.
2985 extend : function(subc, superc, overrides) {
2986 subc.prototype = new superc; // set the superclass
2989 for (var i in overrides) subc.prototype[i] = overrides[i];
2992 hrefURL : function(url) {
2994 // IE needs special treatment since otherwise it would not pass Referer
2995 var trampoline = document.createElement('a');
2996 trampoline.href = url;
2997 document.body.appendChild(trampoline);
2999 document.body.removeChild(trampoline);
3001 document.location.href = url;
3005 openWindow : function(URL, windowName, windowFeatures) {
3007 // IE needs special treatment since otherwise it would not pass Referer
3008 win = window.open('', windowName, windowFeatures);
3009 var trampoline = document.createElement('a');
3010 trampoline.href = URL;
3011 trampoline.target = windowName;
3012 document.body.appendChild(trampoline);
3014 document.body.removeChild(trampoline);
3016 win = window.open(URL, windowName, windowFeatures);
3020 //Reset the scroll on the window
3025 //Based on YUI onAvailible, but will use any boolean function instead of an ID
3026 doWhen : function(condition, fn, params, scope)
3028 this._doWhenStack.push({
3032 overrideContext: scope
3035 this._doWhenretryCount = 50;
3036 this._startDoWhenInterval();
3039 _startDoWhenInterval : function(){
3040 if (!this._doWhenInterval) {
3041 this._doWhenInterval = YAHOO.lang.later(50, this, this._doWhenCheck, null, true);
3045 _doWhenInterval : false,
3046 _doWhenCheck : function() {
3047 if (this._doWhenStack.length === 0) {
3048 this._doWhenretryCount = 0;
3049 if (this._doWhenInterval) {
3050 // clearInterval(this._interval);
3051 this._doWhenInterval.cancel();
3052 this._doWhenInterval = null;
3057 if (this._doWhenLocked) {
3062 // Hold off if DOMReady has not fired and check current
3063 // readyState to protect against the IE operation aborted
3065 if (!YAHOO.util.Event.DOMReady) {
3066 this._startDoWhenInterval();
3071 this._doWhenLocked = true;
3074 // keep trying until after the page is loaded. We need to
3075 // check the page load state prior to trying to bind the
3076 // elements so that we can be certain all elements have been
3077 // tested appropriately
3078 var tryAgain = YAHOO.util.Event.DOMReady;
3080 tryAgain = (this._doWhenretryCount > 0 && this._doWhenStack.length > 0);
3086 var executeItem = function (context, item) {
3087 if (item.overrideContext) {
3088 if (item.overrideContext === true) {
3091 context = item.overrideContext;
3094 item.fn.call(context, item.obj);
3097 var i, len, item, test;
3099 // onAvailable onContentReady
3100 for (i=0, len=this._doWhenStack.length; i<len; i=i+1) {
3101 item = this._doWhenStack[i];
3104 if ((typeof(test) == "string" && eval(test)) || (typeof(test) == "function" && test())) {
3105 executeItem(this, item);
3106 this._doWhenStack[i] = null;
3109 notAvail.push(item);
3114 this._doWhenretryCount--;
3117 for (i=this._doWhenStack.length-1; i>-1; i--) {
3118 item = this._doWhenStack[i];
3119 if (!item || !item.check) {
3120 this._doWhenStack.splice(i, 1);
3123 this._startDoWhenInterval();
3125 if (this._doWhenInterval) {
3126 // clearInterval(this._interval);
3127 this._doWhenInterval.cancel();
3128 this._doWhenInterval = null;
3131 this._doWhenLocked = false;
3135 SUGAR.util.additionalDetailsCache = new Array();
3136 SUGAR.util.additionalDetailsCalls = new Array();
3137 if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.util.setMaxLength); // allow textareas to obey maxlength attrib
3139 SUGAR.savedViews = function() {
3140 var selectedOrderBy;
3141 var selectedSortOrder;
3144 var columnsMeta; // meta data for the display columns
3147 setChooser: function() {
3149 var displayColumnsDef = new Array();
3150 var hideTabsDef = new Array();
3152 var left_td = document.getElementById('display_tabs_td');
3153 if(typeof left_td == 'undefined' || left_td == null) return; // abort!
3154 var right_td = document.getElementById('hide_tabs_td');
3156 var displayTabs = left_td.getElementsByTagName('select')[0];
3157 var hideTabs = right_td.getElementsByTagName('select')[0];
3159 for(i = 0; i < displayTabs.options.length; i++) {
3160 displayColumnsDef.push(displayTabs.options[i].value);
3163 if(typeof hideTabs != 'undefined') {
3164 for(i = 0; i < hideTabs.options.length; i++) {
3165 hideTabsDef.push(hideTabs.options[i].value);
3168 if (!SUGAR.savedViews.clearColumns)
3169 document.getElementById('displayColumnsDef').value = displayColumnsDef.join('|');
3170 document.getElementById('hideTabsDef').value = hideTabsDef.join('|');
3173 select: function(saved_search_select) {
3174 for(var wp = 0; wp < document.search_form.saved_search_select.options.length; wp++) {
3175 if(typeof document.search_form.saved_search_select.options[wp].value != 'undefined' &&
3176 document.search_form.saved_search_select.options[wp].value == saved_search_select) {
3177 document.search_form.saved_search_select.selectedIndex = wp;
3178 document.search_form.ss_delete.style.display = '';
3179 document.search_form.ss_update.style.display = '';
3183 saved_search_action: function(action, delete_lang) {
3184 if(action == 'delete') {
3185 if(!confirm(delete_lang)) return;
3187 if(action == 'save') {
3188 if(document.search_form.saved_search_name.value.replace(/^\s*|\s*$/g, '') == '') {
3189 alert(SUGAR.language.get('app_strings', 'LBL_SAVED_SEARCH_ERROR'));
3194 // This check is needed for the Activities module (Calls/Meetings/Tasks).
3195 if (document.search_form.saved_search_action)
3197 document.search_form.saved_search_action.value = action;
3198 document.search_form.search_module.value = document.search_form.module.value;
3199 document.search_form.module.value = 'SavedSearch';
3200 // Bug 31922 - Make sure to specify that we want to hit the index view here of
3201 // the SavedSearch module, since the ListView doesn't have the logic to save the
3202 // search and redirect back
3203 document.search_form.action.value = 'index';
3205 SUGAR.ajaxUI.submitForm(document.search_form);
3207 shortcut_select: function(selectBox, module) {
3209 selecturl = 'index.php?module=SavedSearch&search_module=' + module + '&action=index&saved_search_select=' + selectBox.options[selectBox.selectedIndex].value
3210 //add searchFormTab to url if it is available. This determines what tab to render
3211 if(typeof(document.getElementById('searchFormTab'))!='undefined'){
3212 selecturl = selecturl + '&searchFormTab=' + document.search_form.searchFormTab.value;
3214 //add showSSDIV to url if it is available. This determines whether saved search sub form should
3215 //be rendered open or not
3216 if(document.getElementById('showSSDIV') && typeof(document.getElementById('showSSDIV') !='undefined')){
3217 selecturl = selecturl + '&showSSDIV='+document.getElementById('showSSDIV').value;
3219 //use created url to navigate
3220 document.location.href = selecturl;
3222 handleForm: function() {
3223 SUGAR.tabChooser.movementCallback = function(left_side, right_side) {
3224 while(document.getElementById('orderBySelect').childNodes.length != 0) { // clear out order by options
3225 document.getElementById('orderBySelect').removeChild(document.getElementById('orderBySelect').lastChild);
3228 var selectedIndex = 0;
3229 var nodeCount = -1; // need this because the counter i also includes "undefined" nodes
3230 // which was breaking Calls and Meetings
3232 for(i in left_side.childNodes) { // fill in order by options
3233 if(typeof left_side.childNodes[i].nodeName != 'undefined' &&
3234 left_side.childNodes[i].nodeName.toLowerCase() == 'option' &&
3235 typeof SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value] != 'undefined' && // check if column is sortable
3236 typeof SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value]['sortable'] == 'undefined' &&
3237 SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value]['sortable'] != false) {
3239 optionNode = document.createElement('option');
3240 optionNode.value = left_side.childNodes[i].value;
3241 optionNode.innerHTML = left_side.childNodes[i].innerHTML;
3242 document.getElementById('orderBySelect').appendChild(optionNode);
3243 if(optionNode.value == SUGAR.savedViews.selectedOrderBy)
3244 selectedIndex = nodeCount;
3247 // Firefox needs this to be set after all the option nodes are created.
3248 document.getElementById('orderBySelect').selectedIndex = selectedIndex;
3250 SUGAR.tabChooser.movementCallback(document.getElementById('display_tabs_td').getElementsByTagName('select')[0]);
3252 // This check is needed for the Activities module (Calls/Meetings/Tasks).
3253 if (document.search_form.orderBy)
3254 document.search_form.orderBy.options.value = SUGAR.savedViews.selectedOrderBy;
3257 if(SUGAR.savedViews.selectedSortOrder == 'DESC') document.getElementById('sort_order_desc_radio').checked = true;
3258 else document.getElementById('sort_order_asc_radio').checked = true;
3263 SUGAR.searchForm = function() {
3266 // searchForm tab selector util
3267 searchFormSelect: function(view, previousView) {
3268 var module = view.split('|')[0];
3269 var theView = view.split('|')[1];
3271 var handleDisplay = function() { // hide other divs
3272 document.search_form.searchFormTab.value = theView;
3273 patt = module+"(.*)SearchForm$";
3274 divId=document.search_form.getElementsByTagName('div');
3275 // Hide all the search forms and retrive the name of the previous search tab (useful for the first load because previousView is empty)
3276 for (i=0;i<divId.length;i++){
3277 if(divId[i].id.match(module)==module){
3278 if(divId[i].id.match('SearchForm')=='SearchForm'){
3279 if(document.getElementById(divId[i].id).style.display == ''){
3280 previousTab=divId[i].id.match(patt)[1];
3282 document.getElementById(divId[i].id).style.display = 'none';
3286 // show the good search form.
3287 document.getElementById(module + theView + 'SearchForm').style.display = '';
3288 //if its not the first tab show there is a previous tab.
3290 thepreviousView=previousView.split('|')[1];
3293 thepreviousView=previousTab;
3295 thepreviousView=thepreviousView.replace(/_search/, "");
3296 // Process to retrieve the completed field from one tab to an other.
3297 for(num in document.search_form.elements) {
3298 if(document.search_form.elements[num]) {
3299 el = document.search_form.elements[num];
3300 pattern="^(.*)_"+thepreviousView+"$";
3301 if(typeof el.type != 'undefined' && typeof el.name != 'undefined' && el.name.match(pattern)) {
3302 advanced_input_name = el.name.match(pattern)[1]; // strip
3303 advanced_input_name = advanced_input_name+"_"+theView.replace(/_search/, "");
3304 if(typeof document.search_form[advanced_input_name] != 'undefined') // if advanced input of same name exists
3305 SUGAR.searchForm.copyElement(advanced_input_name, el);
3311 // if tab is not cached
3312 if(document.getElementById(module + theView + 'SearchForm').innerHTML == '') {
3313 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_LOADING'));
3314 var success = function(data) {
3315 document.getElementById(module + theView + 'SearchForm').innerHTML = data.responseText;
3317 SUGAR.util.evalScript(data.responseText);
3318 // pass script variables to global scope
3319 if(theView == 'saved_views') {
3320 if(typeof columnsMeta != 'undefined') SUGAR.savedViews.columnsMeta = columnsMeta;
3321 if(typeof selectedOrderBy != 'undefined') SUGAR.savedViews.selectedOrderBy = selectedOrderBy;
3322 if(typeof selectedSortOrder != 'undefined') SUGAR.savedViews.selectedSortOrder = selectedSortOrder;
3327 ajaxStatus.hideStatus();
3329 url = 'index.php?module=' + module + '&action=index&search_form_only=true&to_pdf=true&search_form_view=' + theView;
3331 //check to see if tpl has been specified. If so then pass location through url string
3333 if(document.getElementById('search_tpl') !=null && typeof(document.getElementById('search_tpl')) != 'undefined'){
3334 tpl = document.getElementById('search_tpl').value;
3335 if(tpl != ''){url += '&search_tpl='+tpl;}
3338 if(theView == 'saved_views') // handle the tab chooser
3339 url += '&displayColumns=' + SUGAR.savedViews.displayColumns + '&hideTabs=' + SUGAR.savedViews.hideTabs + '&orderBy=' + SUGAR.savedViews.selectedOrderBy + '&sortOrder=' + SUGAR.savedViews.selectedSortOrder;
3341 var cObj = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
3343 else { // that form already retrieved
3348 // copies one input to another
3349 copyElement: function(inputName, copyFromElement) {
3350 switch(copyFromElement.type) {
3353 document.search_form[inputName].value = copyFromElement.value;
3357 // This function is here to clear the form, instead of "resubmitting it
3358 clear_form: function(form, skipElementNames) {
3359 var elemList = form.elements;
3363 for( var i = 0; i < elemList.length ; i++ ) {
3365 if ( typeof(elem.type) == 'undefined' ) {
3369 if ( typeof(elem.type) != 'undefined' && typeof(skipElementNames) != 'undefined'
3370 && SUGAR.util.arrayIndexOf(skipElementNames, elem.name) != -1 )
3375 elemType = elem.type.toLowerCase();
3377 if ( elemType == 'text' || elemType == 'textarea' || elemType == 'password' ) {
3380 else if ( elemType == 'select' || elemType == 'select-one' || elemType == 'select-multiple' ) {
3381 // We have, what I hope, is a select box, time to unselect all options
3382 var optionList = elem.options;
3383 for ( var ii = 0 ; ii < optionList.length ; ii++ ) {
3384 optionList[ii].selected = false;
3387 else if ( elemType == 'radio' || elemType == 'checkbox' ) {
3388 elem.checked = false;
3389 elem.selected = false;
3391 else if ( elemType == 'hidden' ) {
3392 // We only want to reset the hidden values that link to the select boxes.
3393 if ( ( elem.name.length > 3 && elem.name.substring(elem.name.length-3) == '_id' )
3394 || ((elem.name.length > 9) && (elem.name.substring(elem.name.length - 9) == '_id_basic'))
3395 || ( elem.name.length > 12 && elem.name.substring(elem.name.length-12) == '_id_advanced' ) ) {
3400 SUGAR.savedViews.clearColumns = true;
3404 // Code for the column/tab chooser used on homepage and in admin section
3405 SUGAR.tabChooser = function () {
3406 var object_refs = new Array();
3408 /* Describe certain transfers as invalid */
3411 movementCallback: function(left_side, right_side) {},
3412 orderCallback: function(left_side, right_side) {},
3414 freezeOptions: function(left_name, right_name, target) {
3415 if(!SUGAR.tabChooser.frozenOptions) { SUGAR.tabChooser.frozenOptions = []; }
3416 if(!SUGAR.tabChooser.frozenOptions[left_name]) { SUGAR.tabChooser.frozenOptions[left_name] = []; }
3417 if(!SUGAR.tabChooser.frozenOptions[left_name][right_name]) { SUGAR.tabChooser.frozenOptions[left_name][right_name] = []; }
3418 if(typeof target == 'array') {
3419 for(var i in target) {
3420 SUGAR.tabChooser.frozenOptions[left_name][right_name][target[i]] = true;
3423 SUGAR.tabChooser.frozenOptions[left_name][right_name][target] = true;
3427 buildSelectHTML: function(info) {
3428 var text = "<select";
3430 if(typeof (info['select']['size']) != 'undefined') {
3431 text +=" size=\""+ info['select']['size'] +"\"";
3434 if(typeof (info['select']['name']) != 'undefined') {
3435 text +=" name=\""+ info['select']['name'] +"\"";
3438 if(typeof (info['select']['style']) != 'undefined') {
3439 text +=" style=\""+ info['select']['style'] +"\"";
3442 if(typeof (info['select']['onchange']) != 'undefined') {
3443 text +=" onChange=\""+ info['select']['onchange'] +"\"";
3446 if(typeof (info['select']['multiple']) != 'undefined') {
3451 for(i=0; i<info['options'].length;i++) {
3452 option = info['options'][i];
3453 text += "<option value=\""+option['value']+"\" ";
3454 if ( typeof (option['selected']) != 'undefined' && option['selected']== true) {
3457 text += ">"+option['text']+"</option>";
3459 text += "</select>";
3463 left_to_right: function(left_name, right_name, left_size, right_size) {
3464 SUGAR.savedViews.clearColumns = false;
3465 var left_td = document.getElementById(left_name+'_td');
3466 var right_td = document.getElementById(right_name+'_td');
3468 var display_columns_ref = left_td.getElementsByTagName('select')[0];
3469 var hidden_columns_ref = right_td.getElementsByTagName('select')[0];
3471 var selected_left = new Array();
3472 var notselected_left = new Array();
3473 var notselected_right = new Array();
3475 var left_array = new Array();
3477 var frozen_options = SUGAR.tabChooser.frozenOptions;
3478 frozen_options = frozen_options && frozen_options[left_name] && frozen_options[left_name][right_name]?frozen_options[left_name][right_name]:[];
3480 // determine which options are selected in left
3481 for (i=0; i < display_columns_ref.options.length; i++)
3483 if ( display_columns_ref.options[i].selected == true && !frozen_options[display_columns_ref.options[i].value])
3485 selected_left[selected_left.length] = {text: display_columns_ref.options[i].text, value: display_columns_ref.options[i].value};
3489 notselected_left[notselected_left.length] = {text: display_columns_ref.options[i].text, value: display_columns_ref.options[i].value};
3494 for (i=0; i < hidden_columns_ref.options.length; i++)
3496 notselected_right[notselected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
3500 var left_select_html_info = new Object();
3501 var left_options = new Array();
3502 var left_select = new Object();
3504 left_select['name'] = left_name+'[]';
3505 left_select['id'] = left_name;
3506 left_select['size'] = left_size;
3507 left_select['multiple'] = 'true';
3509 var right_select_html_info = new Object();
3510 var right_options = new Array();
3511 var right_select = new Object();
3513 right_select['name'] = right_name+'[]';
3514 right_select['id'] = right_name;
3515 right_select['size'] = right_size;
3516 right_select['multiple'] = 'true';
3518 for (i = 0; i < notselected_right.length; i++) {
3519 right_options[right_options.length] = notselected_right[i];
3522 for (i = 0; i < selected_left.length; i++) {
3523 right_options[right_options.length] = selected_left[i];
3525 for (i = 0; i < notselected_left.length; i++) {
3526 left_options[left_options.length] = notselected_left[i];
3528 left_select_html_info['options'] = left_options;
3529 left_select_html_info['select'] = left_select;
3530 right_select_html_info['options'] = right_options;
3531 right_select_html_info['select'] = right_select;
3532 right_select_html_info['style'] = 'background: lightgrey';
3534 var left_html = this.buildSelectHTML(left_select_html_info);
3535 var right_html = this.buildSelectHTML(right_select_html_info);
3537 left_td.innerHTML = left_html;
3538 right_td.innerHTML = right_html;
3540 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3541 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3543 this.movementCallback(object_refs[left_name], object_refs[right_name]);
3549 right_to_left: function(left_name, right_name, left_size, right_size, max_left) {
3550 SUGAR.savedViews.clearColumns = false;
3551 var left_td = document.getElementById(left_name+'_td');
3552 var right_td = document.getElementById(right_name+'_td');
3554 var display_columns_ref = left_td.getElementsByTagName('select')[0];
3555 var hidden_columns_ref = right_td.getElementsByTagName('select')[0];
3557 var selected_right = new Array();
3558 var notselected_right = new Array();
3559 var notselected_left = new Array();
3561 var frozen_options = SUGAR.tabChooser.frozenOptions;
3562 frozen_options = SUGAR.tabChooser.frozenOptions && SUGAR.tabChooser.frozenOptions[right_name] && SUGAR.tabChooser.frozenOptions[right_name][left_name]?SUGAR.tabChooser.frozenOptions[right_name][left_name]:[];
3564 for (i=0; i < hidden_columns_ref.options.length; i++)
3566 if (hidden_columns_ref.options[i].selected == true && !frozen_options[hidden_columns_ref.options[i].value])
3568 selected_right[selected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
3572 notselected_right[notselected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
3577 if(max_left != '' && (display_columns_ref.length + selected_right.length) > max_left) {
3578 alert('Maximum of ' + max_left + ' columns can be displayed.');
3582 for (i=0; i < display_columns_ref.options.length; i++)
3584 notselected_left[notselected_left.length] = {text:display_columns_ref.options[i].text, value:display_columns_ref.options[i].value};
3588 var left_select_html_info = new Object();
3589 var left_options = new Array();
3590 var left_select = new Object();
3592 left_select['name'] = left_name+'[]';
3593 left_select['id'] = left_name;
3594 left_select['multiple'] = 'true';
3595 left_select['size'] = left_size;
3597 var right_select_html_info = new Object();
3598 var right_options = new Array();
3599 var right_select = new Object();
3601 right_select['name'] = right_name+ '[]';
3602 right_select['id'] = right_name;
3603 right_select['multiple'] = 'true';
3604 right_select['size'] = right_size;
3606 for (i = 0; i < notselected_left.length; i++) {
3607 left_options[left_options.length] = notselected_left[i];
3610 for (i = 0; i < selected_right.length; i++) {
3611 left_options[left_options.length] = selected_right[i];
3613 for (i = 0; i < notselected_right.length; i++) {
3614 right_options[right_options.length] = notselected_right[i];
3616 left_select_html_info['options'] = left_options;
3617 left_select_html_info['select'] = left_select;
3618 right_select_html_info['options'] = right_options;
3619 right_select_html_info['select'] = right_select;
3620 right_select_html_info['style'] = 'background: lightgrey';
3622 var left_html = this.buildSelectHTML(left_select_html_info);
3623 var right_html = this.buildSelectHTML(right_select_html_info);
3625 left_td.innerHTML = left_html;
3626 right_td.innerHTML = right_html;
3628 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3629 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3631 this.movementCallback(object_refs[left_name], object_refs[right_name]);
3636 up: function(name, left_name, right_name) {
3637 SUGAR.savedViews.clearColumns = false;
3638 var left_td = document.getElementById(left_name+'_td');
3639 var right_td = document.getElementById(right_name+'_td');
3640 var td = document.getElementById(name+'_td');
3641 var obj = td.getElementsByTagName('select')[0];
3642 obj = (typeof obj == "string") ? document.getElementById(obj) : obj;
3643 if (obj.tagName.toLowerCase() != "select" && obj.length < 2)
3645 var sel = new Array();
3647 for (i=0; i<obj.length; i++) {
3648 if (obj[i].selected == true) {
3649 sel[sel.length] = i;
3652 for (i=0; i < sel.length; i++) {
3653 if (sel[i] != 0 && !obj[sel[i]-1].selected) {
3654 var tmp = new Array(obj[sel[i]-1].text, obj[sel[i]-1].value);
3655 obj[sel[i]-1].text = obj[sel[i]].text;
3656 obj[sel[i]-1].value = obj[sel[i]].value;
3657 obj[sel[i]].text = tmp[0];
3658 obj[sel[i]].value = tmp[1];
3659 obj[sel[i]-1].selected = true;
3660 obj[sel[i]].selected = false;
3664 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3665 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3667 this.orderCallback(object_refs[left_name], object_refs[right_name]);
3672 down: function(name, left_name, right_name) {
3673 SUGAR.savedViews.clearColumns = false;
3674 var left_td = document.getElementById(left_name+'_td');
3675 var right_td = document.getElementById(right_name+'_td');
3676 var td = document.getElementById(name+'_td');
3677 var obj = td.getElementsByTagName('select')[0];
3678 if (obj.tagName.toLowerCase() != "select" && obj.length < 2)
3680 var sel = new Array();
3681 for (i=obj.length-1; i>-1; i--) {
3682 if (obj[i].selected == true) {
3683 sel[sel.length] = i;
3686 for (i=0; i < sel.length; i++) {
3687 if (sel[i] != obj.length-1 && !obj[sel[i]+1].selected) {
3688 var tmp = new Array(obj[sel[i]+1].text, obj[sel[i]+1].value);
3689 obj[sel[i]+1].text = obj[sel[i]].text;
3690 obj[sel[i]+1].value = obj[sel[i]].value;
3691 obj[sel[i]].text = tmp[0];
3692 obj[sel[i]].value = tmp[1];
3693 obj[sel[i]+1].selected = true;
3694 obj[sel[i]].selected = false;
3698 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3699 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3701 this.orderCallback(object_refs[left_name], object_refs[right_name]);
3706 }(); // end tabChooser
3708 SUGAR.language = function() {
3710 languages : new Array(),
3712 setLanguage: function(module, data) {
3713 if (!SUGAR.language.languages) {
3716 SUGAR.language.languages[module] = data;
3719 get: function(module, str) {
3720 if(typeof SUGAR.language.languages[module] == 'undefined' || typeof SUGAR.language.languages[module][str] == 'undefined')
3724 return SUGAR.language.languages[module][str];
3727 translate: function(module, str)
3729 text = this.get(module, str);
3730 return text != 'undefined' ? text : this.get('app_strings', str);
3735 SUGAR.contextMenu = function() {
3737 objects: new Object(),
3738 objectTypes: new Object(),
3740 * Registers a new object for the context menu.
3741 * objectType - name of the type
3743 * metaData - metaData to pass to the action function
3745 registerObject: function(objectType, id, metaData) {
3746 SUGAR.contextMenu.objects[id] = new Object();
3747 SUGAR.contextMenu.objects[id] = {'objectType' : objectType, 'metaData' : metaData};
3750 * Registers a new object type
3751 * name - name of the type
3752 * menuItems - array of menu items
3754 registerObjectType: function(name, menuItems) {
3755 SUGAR.contextMenu.objectTypes[name] = new Object();
3756 SUGAR.contextMenu.objectTypes[name] = {'menuItems' : menuItems, 'objects' : new Array()};
3759 * Determines which menu item was clicked
3761 getListItemFromEventTarget: function(p_oNode) {
3763 if(p_oNode.tagName == "LI") {
3768 if(p_oNode.tagName == "LI") {
3773 } while((p_oNode = p_oNode.parentNode));
3778 * handles movement within context menu
3780 onContextMenuMove: function() {
3781 var oNode = this.contextEventTarget;
3782 var bDisabled = (oNode.tagName == "UL");
3783 var i = this.getItemGroups()[0].length - 1;
3785 this.getItem(i).cfg.setProperty("disabled", bDisabled);
3790 * handles clicks on a context menu ITEM
3792 onContextMenuItemClick: function(p_sType, p_aArguments, p_oItem) {
3793 var oLI = SUGAR.contextMenu.getListItemFromEventTarget(this.parent.contextEventTarget);
3794 id = this.parent.contextEventTarget.parentNode.id; // id of the target
3795 funct = eval(SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[id]['objectType']]['menuItems'][this.index]['action']);
3796 funct(this.parent.contextEventTarget, SUGAR.contextMenu.objects[id]['metaData']);
3799 * Initializes all context menus registered
3802 for(var i in SUGAR.contextMenu.objects) { // make a variable called objects in objectTypes containg references to all triggers
3803 if(typeof SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'] == 'undefined')
3804 SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'] = new Array();
3805 SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'].push(document.getElementById(i));
3807 // register the menus
3808 for(var i in SUGAR.contextMenu.objectTypes) {
3809 var oContextMenu = new YAHOO.widget.ContextMenu(i, {'trigger': SUGAR.contextMenu.objectTypes[i]['objects']});
3810 var aMainMenuItems = SUGAR.contextMenu.objectTypes[i]['menuItems'];
3811 var nMainMenuItems = aMainMenuItems.length;
3813 for(var j = 0; j < nMainMenuItems; j++) {
3814 oMenuItem = new YAHOO.widget.ContextMenuItem(aMainMenuItems[j].text, { helptext: aMainMenuItems[j].helptext });
3815 oMenuItem.clickEvent.subscribe(SUGAR.contextMenu.onContextMenuItemClick, oMenuItem, true);
3816 oContextMenu.addItem(oMenuItem);
3818 // Add a "move" event handler to the context menu
3819 oContextMenu.moveEvent.subscribe(SUGAR.contextMenu.onContextMenuMove, oContextMenu, true);
3820 // Add a "keydown" event handler to the context menu
3821 oContextMenu.keyDownEvent.subscribe(SUGAR.contextMenu.onContextMenuItemClick, oContextMenu, true);
3822 // Render the context menu
3823 oContextMenu.render(document.body);
3829 SUGAR.contextMenu.actions = function() {
3832 * redirects to a new note with the clicked on object as the target
3834 createNote: function(itemClicked, metaData) {
3835 loc = 'index.php?module=Notes&action=EditView';
3836 for(i in metaData) {
3837 if(i == 'notes_parent_type') loc += '&parent_type=' + metaData[i];
3838 else if(i != 'module' && i != 'parent_type') loc += '&' + i + '=' + metaData[i];
3840 document.location = loc;
3843 * redirects to a new note with the clicked on object as the target
3845 scheduleMeeting: function(itemClicked, metaData) {
3846 loc = 'index.php?module=Meetings&action=EditView';
3847 for(i in metaData) {
3848 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3850 document.location = loc;
3853 * redirects to a new note with the clicked on object as the target
3855 scheduleCall: function(itemClicked, metaData) {
3856 loc = 'index.php?module=Calls&action=EditView';
3857 for(i in metaData) {
3858 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3860 document.location = loc;
3863 * redirects to a new contact with the clicked on object as the target
3865 createContact: function(itemClicked, metaData) {
3866 loc = 'index.php?module=Contacts&action=EditView';
3867 for(i in metaData) {
3868 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3870 document.location = loc;
3873 * redirects to a new task with the clicked on object as the target
3875 createTask: function(itemClicked, metaData) {
3876 loc = 'index.php?module=Tasks&action=EditView';
3877 for(i in metaData) {
3878 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3880 document.location = loc;
3883 * redirects to a new opportunity with the clicked on object as the target
3885 createOpportunity: function(itemClicked, metaData) {
3886 loc = 'index.php?module=Opportunities&action=EditView';
3887 for(i in metaData) {
3888 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3890 document.location = loc;
3893 * redirects to a new opportunity with the clicked on object as the target
3895 createCase: function(itemClicked, metaData) {
3896 loc = 'index.php?module=Cases&action=EditView';
3897 for(i in metaData) {
3898 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3900 document.location = loc;
3903 * handles add to favorites menu selection
3905 addToFavorites: function(itemClicked, metaData) {
3906 success = function(data) {
3908 var cObj = YAHOO.util.Connect.asyncRequest('GET', 'index.php?to_pdf=true&module=Home&action=AddToFavorites&target_id=' + metaData['id'] + '&target_module=' + metaData['module'], {success: success, failure: success});
3913 //if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.contextMenu.init);
3915 // initially from popup_parent_helper.js
3916 var popup_request_data;
3919 function get_popup_request_data()
3921 return YAHOO.lang.JSON.stringify(window.document.popup_request_data);
3924 function get_close_popup()
3926 return window.document.close_popup;
3929 function open_popup(module_name, width, height, initial_filter, close_popup, hide_clear_button, popup_request_data, popup_mode, create, metadata)
3931 if (typeof(popupCount) == "undefined" || popupCount == 0)
3934 // set the variables that the popup will pull from
3935 window.document.popup_request_data = popup_request_data;
3936 window.document.close_popup = close_popup;
3938 //globally changing width and height of standard pop up window from 600 x 400 to 800 x 800
3939 width = (width == 600) ? 800 : width;
3940 height = (height == 400) ? 800 : height;
3944 + 'module=' + module_name
3947 if (initial_filter != '') {
3948 URL += '&query=true' + initial_filter;
3949 // Bug 41891 - Popup Window Name
3950 popupName = initial_filter.replace(/[^a-z_0-9]+/ig, '_');
3951 windowName = module_name + '_popup_window' + popupName;
3953 windowName = module_name + '_popup_window' + popupCount;
3957 if (hide_clear_button) {
3958 URL += '&hide_clear_button=true';
3961 windowFeatures = 'width=' + width
3962 + ',height=' + height
3963 + ',resizable=1,scrollbars=1';
3965 if (popup_mode == '' && popup_mode == 'undefined') {
3966 popup_mode='single';
3968 URL+='&mode='+popup_mode;
3969 if (create == '' && create == 'undefined') {
3972 URL+='&create='+create;
3974 if (metadata != '' && metadata != 'undefined') {
3975 URL+='&metadata='+metadata;
3978 win = SUGAR.util.openWindow(URL, windowName, windowFeatures);
3982 // put the focus on the popup if the browser supports the focus() method
3986 win.popupCount = popupCount;
3992 * The reply data must be a JSON array structured with the following information:
3993 * 1) form name to populate
3994 * 2) associative array of input names to values for populating the form
3996 var from_popup_return = false;
3998 function set_return_basic(popup_reply_data,filter)
4000 var form_name = popup_reply_data.form_name;
4001 var name_to_value_array = popup_reply_data.name_to_value_array;
4002 for (var the_key in name_to_value_array)
4004 if(the_key == 'toJSON')
4008 else if(the_key.match(filter))
4010 var displayValue=name_to_value_array[the_key].replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');;
4011 // begin andopes change: support for enum fields (SELECT)
4012 if(window.document.forms[form_name] && window.document.forms[form_name].elements[the_key]) {
4013 if(window.document.forms[form_name].elements[the_key].tagName == 'SELECT') {
4014 var selectField = window.document.forms[form_name].elements[the_key];
4015 for(var i = 0; i < selectField.options.length; i++) {
4016 if(selectField.options[i].text == displayValue) {
4017 selectField.options[i].selected = true;
4018 SUGAR.util.callOnChangeListers(selectField);
4023 window.document.forms[form_name].elements[the_key].value = displayValue;
4024 SUGAR.util.callOnChangeListers(window.document.forms[form_name].elements[the_key]);
4027 // end andopes change: support for enum fields (SELECT)
4032 function set_return(popup_reply_data)
4034 from_popup_return = true;
4035 var form_name = popup_reply_data.form_name;
4036 var name_to_value_array = popup_reply_data.name_to_value_array;
4037 if(typeof name_to_value_array != 'undefined' && name_to_value_array['account_id'])
4040 var label_data_str = '';
4041 var current_label_data_str = '';
4042 for (var the_key in name_to_value_array)
4044 if(the_key == 'toJSON')
4050 var displayValue=name_to_value_array[the_key].replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');
4051 if(window.document.forms[form_name] && document.getElementById(the_key+'_label') && !the_key.match(/account/)) {
4052 var data_label = document.getElementById(the_key+'_label').innerHTML.replace(/\n/gi,'');
4053 label_str += data_label + ' \n';
4054 label_data_str += data_label + ' ' + displayValue + '\n';
4055 if(window.document.forms[form_name].elements[the_key]) {
4056 current_label_data_str += data_label + ' ' + window.document.forms[form_name].elements[the_key].value +'\n';
4061 if(label_data_str != label_str && current_label_data_str != label_str){
4062 if(confirm(SUGAR.language.get('app_strings', 'NTC_OVERWRITE_ADDRESS_PHONE_CONFIRM') + '\n\n' + label_data_str))
4064 set_return_basic(popup_reply_data,/\S/);
4066 set_return_basic(popup_reply_data,/account/);
4068 }else if(label_data_str != label_str && current_label_data_str == label_str){
4069 set_return_basic(popup_reply_data,/\S/);
4070 }else if(label_data_str == label_str){
4071 set_return_basic(popup_reply_data,/account/);
4074 set_return_basic(popup_reply_data,/\S/);
4078 function set_return_lead_conv(popup_reply_data) {
4079 set_return(popup_reply_data);
4080 if (document.getElementById('lead_conv_ac_op_sel') && typeof onBlurKeyUpHandler=='function') {
4081 onBlurKeyUpHandler();
4085 function set_return_and_save(popup_reply_data)
4087 var form_name = popup_reply_data.form_name;
4088 var name_to_value_array = popup_reply_data.name_to_value_array;
4090 for (var the_key in name_to_value_array)
4092 if(the_key == 'toJSON')
4098 window.document.forms[form_name].elements[the_key].value = name_to_value_array[the_key];
4102 window.document.forms[form_name].return_module.value = window.document.forms[form_name].module.value;
4103 window.document.forms[form_name].return_action.value = 'DetailView';
4104 window.document.forms[form_name].return_id.value = window.document.forms[form_name].record.value;
4105 window.document.forms[form_name].action.value = 'Save';
4106 window.document.forms[form_name].submit();
4110 * This is a helper function to construct the initial filter that can be
4111 * passed into the open_popup() function. It assumes that there is an
4112 * account_id and account_name field in the given form_name to use to
4113 * construct the intial filter string.
4115 function get_initial_filter_by_account(form_name)
4117 var account_id = window.document.forms[form_name].account_id.value;
4118 var account_name = escape(window.document.forms[form_name].account_name.value);
4119 var initial_filter = "&account_id=" + account_id + "&account_name=" + account_name;
4121 return initial_filter;
4123 // end code from popup_parent_helper.js
4125 // begin code for address copy
4127 * This is a function used by the Address widget that will fill
4128 * in the given array fields using the fromKey and toKey as a
4129 * prefix into the form objects HTML elements.
4131 * @param form The HTML form object to parse
4132 * @param fromKey The prefix of elements to copy from
4133 * @param toKey The prefix of elements to copy into
4134 * @return boolean true if successful, false otherwise
4136 function copyAddress(form, fromKey, toKey) {
4138 var elems = new Array("address_street", "address_city", "address_state", "address_postalcode", "address_country");
4139 var checkbox = document.getElementById(toKey + "_checkbox");
4141 if(typeof checkbox != "undefined") {
4142 if(!checkbox.checked) {
4144 t = toKey + "_" + elems[x];
4145 document.getElementById(t).removeAttribute('readonly');
4149 f = fromKey + "_" + elems[x];
4150 t = toKey + "_" + elems[x];
4152 document.getElementById(t).value = document.getElementById(f).value;
4153 document.getElementById(t).setAttribute('readonly', true);
4159 // end code for address copy
4162 * This function is used in Email Template Module.
4163 * It will check whether the template is used in Campaing->EmailMarketing.
4164 * If true, it will notify user.
4167 function check_deletable_EmailTemplate() {
4168 id = document.getElementsByName('record')[0].value;
4169 currentForm = document.getElementById('form');
4171 success:function(r) {
4172 if(r.responseText == 'true') {
4173 if(!confirm(SUGAR.language.get('app_strings','NTC_TEMPLATE_IS_USED'))) {
4177 if(!confirm(SUGAR.language.get('app_strings','NTC_DELETE_CONFIRMATION'))) {
4181 currentForm.return_module.value='EmailTemplates';
4182 currentForm.return_action.value='ListView';
4183 currentForm.action.value='Delete';
4184 currentForm.submit();
4187 url = "index.php?module=EmailTemplates&action=CheckDeletable&from=DetailView&to_pdf=1&record="+id;
4188 YAHOO.util.Connect.asyncRequest('POST',url, call_back,null);
4192 remove_upload_imagefile : function(field_name) {
4193 var field=document.getElementById('remove_imagefile_' + field_name);
4196 //enable the file upload button.
4197 var field=document.getElementById( field_name);
4198 field.style.display="";
4200 //hide the image and remove button.
4201 var field=document.getElementById('img_' + field_name);
4202 field.style.display="none";
4203 var field=document.getElementById('bt_remove_' + field_name);
4204 field.style.display="none";
4206 if(document.getElementById(field_name + '_duplicate')) {
4207 var field = document.getElementById(field_name + '_duplicate');
4212 confirm_imagefile : function(field_name) {
4213 var field=document.getElementById(field_name);
4214 var filename=field.value;
4215 var fileExtension = filename.substring(filename.lastIndexOf(".")+1);
4216 fileExtension = fileExtension.toLowerCase();
4217 if (fileExtension == "jpg" || fileExtension == "jpeg"
4218 || fileExtension == "gif" || fileExtension == "png" || fileExtension == "bmp"){
4223 alert(SUGAR.language.get('app_strings', 'LBL_UPLOAD_IMAGE_FILE_INVALID'));
4227 lightbox : function(image)
4229 if (typeof(SUGAR.image.lighboxWindow) == "undefined")
4230 SUGAR.image.lighboxWindow = new YAHOO.widget.SimpleDialog('sugarImageViewer', {
4233 id:'sugarMsgWindow',
4236 msg: "<img src='" + image + "'> </img>",
4239 SUGAR.image.lighboxWindow.setBody("<img src='" + image + "'> </img>");
4240 SUGAR.image.lighboxWindow.render(document.body);
4241 SUGAR.image.lighboxWindow.show();
4242 SUGAR.image.lighboxWindow.center()
4246 SUGAR.append(SUGAR.util, {
4247 isTouchScreen: function() {
4248 // first check if we have forced use of the touch enhanced interface
4249 if (Get_Cookie("touchscreen") == '1') {
4253 // next check if we should use the touch interface with our device
4254 if ((navigator.userAgent.match(/iPad/i) != null)) {
4261 isLoginPage: function(content) {
4262 //skip if this is packageManager screen
4263 if(SUGAR.util.isPackageManager()) {return false;}
4264 var loginPageStart = "<!DOCTYPE";
4265 if (content.substr(0, loginPageStart.length) == loginPageStart && content.indexOf("<html>") != -1 && content.indexOf("login_module") != -1) {
4266 window.location.href = window.location.protocol + window.location.pathname;
4271 isPackageManager: function(){
4272 if(typeof(document.the_form) !='undefined' && typeof(document.the_form.language_pack_escaped) !='undefined'){
4274 }else{return false;}
4277 ajaxCallInProgress: function(){
4279 //First check if we are in a popup.
4280 if (typeof (send_back) != "function"){
4281 //If the page content is blank, it means we are probably still waiting on something
4282 var c = document.getElementById("content");
4283 if (!c) return true;
4284 t = YAHOO.lang.trim(SUGAR.util.innerText(c));
4286 return SUGAR_callsInProgress != 0 || t == "";
4288 //Firefox doesn't support innerText (textContent includes script content)
4289 innerText : function(el) {
4290 if (el.tagName == "SCRIPT")
4292 if(typeof(el.innerText) == "string")
4293 return el.innerText;
4295 for (var i in el.childNodes){
4296 var c = el.childNodes[i];
4297 if (typeof(c) != "object")
4299 if (typeof(c.nodeName) == "string" && c.nodeName == "#text")
4302 t += SUGAR.util.innerText(c);
4307 callOnChangeListers: function(field){
4308 var listeners = YAHOO.util.Event.getListeners(field, 'change');
4309 if (listeners != null) {
4310 for (var i = 0; i < listeners.length; i++) {
4311 var l = listeners[i];
4312 l.fn.call(l.scope ? l.scope : this, l.obj);
4317 closeActivityPanel: {
4318 show:function(module,id,new_status,viewType,parentContainerId){
4319 if (SUGAR.util.closeActivityPanel.panel)
4320 SUGAR.util.closeActivityPanel.panel.destroy();
4321 var singleModule = SUGAR.language.get("app_list_strings", "moduleListSingular")[module];
4322 singleModule = typeof(singleModule != 'undefined') ? singleModule.toLowerCase() : '';
4323 var closeText = SUGAR.language.get("app_strings", "LBL_CLOSE_ACTIVITY_CONFIRM").replace("#module#",singleModule);
4324 SUGAR.util.closeActivityPanel.panel =
4325 new YAHOO.widget.SimpleDialog("closeActivityDialog",
4332 constraintoviewport: true,
4333 buttons: [ { text:SUGAR.language.get("app_strings", "LBL_EMAIL_OK"), handler:function(){
4334 if (SUGAR.util.closeActivityPanel.panel)
4335 SUGAR.util.closeActivityPanel.panel.hide();
4337 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_SAVING'));
4338 var args = "action=save&id=" + id + "&record=" + id + "&status=" + new_status + "&module=" + module;
4339 // 20110307 Frank Steegmans: Fix for bug 42361, Any field with a default configured in any activity will be set to this default when closed using the close dialog
4340 // TODO: Take id out and regression test. Left id in for now to not create any other unexpected problems
4341 //var args = "action=save&id=" + id + "&status=" + new_status + "&module=" + module;
4345 // Bug 45792: Firefox seems to believe reloading a page after an ajax request means you are re-submitting a form and gives you the warning for it.
4346 // So instead, we reload from a timeout
4347 window.setTimeout("window.location.reload(true);",0);
4349 argument:{'parentContainerId':parentContainerId}
4352 YAHOO.util.Connect.asyncRequest('POST', 'index.php', callback, args);
4354 }, isDefault:true },
4355 { text:SUGAR.language.get("app_strings", "LBL_EMAIL_CANCEL"), handler:function(){SUGAR.util.closeActivityPanel.panel.hide(); }} ]
4358 SUGAR.util.closeActivityPanel.panel.setHeader(SUGAR.language.get("app_strings", "LBL_CLOSE_ACTIVITY_HEADER"));
4359 SUGAR.util.closeActivityPanel.panel.render(document.body);
4360 SUGAR.util.closeActivityPanel.panel.show();
4364 setEmailPasswordDisplay: function(id, exists) {
4365 link = document.getElementById(id+'_link');
4366 pwd = document.getElementById(id);
4367 if(!pwd || !link) return;
4369 pwd.style.display = 'none';
4370 link.style.display = '';
4372 pwd.style.display = '';
4373 link.style.display = 'none';
4377 setEmailPasswordEdit: function(id) {
4378 link = document.getElementById(id+'_link');
4379 pwd = document.getElementById(id);
4380 if(!pwd || !link) return;
4381 pwd.style.display = '';
4382 link.style.display = 'none';
4386 * Compares a filename with a supplied array of allowed file extensions.
4387 * @param fileName string
4388 * @param allowedTypes array of allowed file extensions
4391 validateFileExt: function(fileName, allowedTypes) {
4392 var ext = fileName.split('.').pop().toLowerCase();
4394 for (var i = allowedTypes.length; i > 0; i--) {
4395 if (ext === allowedTypes[i]) {
4403 arrayIndexOf: function(arr, val, start) {
4404 if (typeof arr.indexOf == "function")
4405 return arr.indexOf(val, start);
4406 for (var i = (start || 0), j = arr.length; i < j; i++) {
4407 if (arr[i] === val) {
4415 SUGAR.clearRelateField = function(form, name, id)
4417 if (typeof form[name] == "object"){
4418 form[name].value = '';
4419 SUGAR.util.callOnChangeListers(form[name]);
4422 if (typeof form[id] == "object"){
4423 form[id].value = '';
4424 SUGAR.util.callOnChangeListers(form[id]);
4427 if(typeof(SUGAR.AutoComplete) == 'undefined') SUGAR.AutoComplete = {};
4429 SUGAR.AutoComplete.getOptionsArray = function(options_index){
4430 var return_arr = [];
4432 var opts = SUGAR.language.get('app_list_strings', options_index);
4433 if(typeof(opts) != 'undefined'){
4435 // Since we are using auto complete, we excluse blank dropdown entries since they can just leave it blank
4436 if(key != '' && opts[key] != ''){
4439 item['text'] = opts[key];
4440 return_arr.push(item);
4447 if(typeof(SUGAR.MultiEnumAutoComplete) == 'undefined') SUGAR.MultiEnumAutoComplete = {};
4449 SUGAR.MultiEnumAutoComplete.getMultiSelectKeysFromValues = function(options_index, val_string){
4450 var opts = SUGAR.language.get('app_list_strings', options_index);
4451 var selected_values = val_string.split(", ");
4452 // YUI AutoComplete adds a blank. We remove it automatically here
4453 if(selected_values.length > 0 && selected_values.indexOf('') == selected_values.length - 1){
4454 selected_values.pop();
4456 var final_arr = new Array();
4457 for(idx in selected_values){
4459 if(selected_values[idx] == opts[o_idx]){
4460 final_arr.push(o_idx);
4467 SUGAR.MultiEnumAutoComplete.getMultiSelectValuesFromKeys = function(options_index, val_string){
4468 var opts = SUGAR.language.get('app_list_strings', options_index);
4469 val_string=val_string.replace(/^\^/,'').replace(/\^$/,'') //fixes bug where string starts or ends with ^
4470 var selected_values = val_string.split("^,^");
4472 // YUI AutoComplete adds a blank. We remove it automatically here
4473 if(selected_values.length > 0 && selected_values.indexOf('') == selected_values.length - 1){
4474 selected_values.pop();
4477 var final_arr = new Array();
4478 for(idx in selected_values){
4480 if(selected_values[idx] == o_idx){
4481 final_arr.push(opts[o_idx]);