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 = '';
138 function isSupportedIE() {
139 var userAgent = navigator.userAgent.toLowerCase() ;
141 // IE Check supports ActiveX controls
142 if (userAgent.indexOf("msie") != -1 && userAgent.indexOf("mac") == -1 && userAgent.indexOf("opera") == -1) {
143 var version = navigator.appVersion.match(/MSIE (.\..)/)[1] ;
144 if(version >= 5.5 && version < 9) {
152 SUGAR.isIE = isSupportedIE();
153 var isSafari = (navigator.userAgent.toLowerCase().indexOf('safari')!=-1);
155 // escapes regular expression characters
156 RegExp.escape = function(text) { // http://simon.incutio.com/archive/2006/01/20/escape
157 if (!arguments.callee.sRE) {
158 var specials = ['/', '.', '*', '+', '?', '|','(', ')', '[', ']', '{', '}', '\\'];
159 arguments.callee.sRE = new RegExp('(\\' + specials.join('|\\') + ')', 'g');
161 return text.replace(arguments.callee.sRE, '\\$1');
164 function addAlert(type, name,subtitle, description,time, redirect) {
165 var addIndex = alertList.length;
166 alertList[addIndex]= new Array();
167 alertList[addIndex]['name'] = name;
168 alertList[addIndex]['type'] = type;
169 alertList[addIndex]['subtitle'] = subtitle;
170 alertList[addIndex]['description'] = description.replace(/<br>/gi, "\n").replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');
171 alertList[addIndex]['time'] = time;
172 alertList[addIndex]['done'] = 0;
173 alertList[addIndex]['redirect'] = redirect;
175 function checkAlerts() {
176 secondsSinceLoad += 1;
179 for(mj = 0 ; mj < alertList.length; mj++) {
180 if(alertList[mj]['done'] == 0) {
181 if(alertList[mj]['time'] < secondsSinceLoad && alertList[mj]['time'] > -1 ) {
182 alertmsg = alertList[mj]['type'] + ":" + alertList[mj]['name'] + "\n" +alertList[mj]['subtitle']+ "\n"+ alertList[mj]['description'] + "\n\n";
183 alertList[mj]['done'] = 1;
184 if(alertList[mj]['redirect'] == '') {
187 else if(confirm(alertmsg)) {
188 window.location = alertList[mj]['redirect'];
194 setTimeout("checkAlerts()", 1000);
197 function toggleDisplay(id) {
198 if(this.document.getElementById(id).style.display == 'none') {
199 this.document.getElementById(id).style.display = '';
200 if(this.document.getElementById(id+"link") != undefined) {
201 this.document.getElementById(id+"link").style.display = 'none';
203 if(this.document.getElementById(id+"_anchor") != undefined)
204 this.document.getElementById(id+"_anchor").innerHTML='[ - ]';
207 this.document.getElementById(id).style.display = 'none'
208 if(this.document.getElementById(id+"link") != undefined) {
209 this.document.getElementById(id+"link").style.display = '';
211 if(this.document.getElementById(id+"_anchor") != undefined)
212 this.document.getElementById(id+"_anchor").innerHTML='[+]';
216 function checkAll(form, field, value) {
217 for (i = 0; i < form.elements.length; i++) {
218 if(form.elements[i].name == field)
219 form.elements[i].checked = value;
223 function replaceAll(text, src, rep) {
224 offset = text.toLowerCase().indexOf(src.toLowerCase());
225 while(offset != -1) {
226 text = text.substring(0, offset) + rep + text.substring(offset + src.length ,text.length);
227 offset = text.indexOf( src, offset + rep.length + 1);
232 function addForm(formname) {
233 validate[formname] = new Array();
236 function addToValidate(formname, name, type, required, msg) {
237 if(typeof validate[formname] == 'undefined') {
240 validate[formname][validate[formname].length] = new Array(name, type,required, msg);
243 function addToValidateRange(formname, name, type,required, msg,min,max) {
244 addToValidate(formname, name, type,required, msg);
245 validate[formname][validate[formname].length - 1][jstypeIndex] = 'range'
246 validate[formname][validate[formname].length - 1][minIndex] = min;
247 validate[formname][validate[formname].length - 1][maxIndex] = max;
250 function addToValidateIsValidDate(formname, name, type, required, msg) {
251 addToValidate(formname, name, type, required, msg);
252 validate[formname][validate[formname].length - 1][jstypeIndex] = 'date'
255 function addToValidateIsValidTime(formname, name, type, required, msg) {
256 addToValidate(formname, name, type, required, msg);
257 validate[formname][validate[formname].length - 1][jstypeIndex] = 'time'
260 function addToValidateDateBefore(formname, name, type, required, msg, compareTo) {
261 addToValidate(formname, name, type,required, msg);
262 validate[formname][validate[formname].length - 1][jstypeIndex] = 'isbefore'
263 validate[formname][validate[formname].length - 1][compareToIndex] = compareTo;
266 function addToValidateDateBeforeAllowBlank(formname, name, type, required, msg, compareTo, allowBlank) {
267 addToValidate(formname, name, type,required, msg);
268 validate[formname][validate[formname].length - 1][jstypeIndex] = 'isbefore'
269 validate[formname][validate[formname].length - 1][compareToIndex] = compareTo;
270 validate[formname][validate[formname].length - 1][allowblank] = allowBlank;
273 function addToValidateBinaryDependency(formname, name, type, required, msg, compareTo) {
274 addToValidate(formname, name, type, required, msg);
275 validate[formname][validate[formname].length - 1][jstypeIndex] = 'binarydep';
276 validate[formname][validate[formname].length - 1][compareToIndex] = compareTo;
279 function addToValidateComparison(formname, name, type, required, msg, compareTo) {
280 addToValidate(formname, name, type, required, msg);
281 validate[formname][validate[formname].length - 1][jstypeIndex] = 'comparison';
282 validate[formname][validate[formname].length - 1][compareToIndex] = compareTo;
285 function addToValidateIsInArray(formname, name, type, required, msg, arr, operator) {
286 addToValidate(formname, name, type, required, msg);
287 validate[formname][validate[formname].length - 1][jstypeIndex] = 'in_array';
288 validate[formname][validate[formname].length - 1][arrIndex] = arr;
289 validate[formname][validate[formname].length - 1][operatorIndex] = operator;
292 function addToValidateVerified(formname, name, type, required, msg, arr, operator) {
293 addToValidate(formname, name, type, required, msg);
294 validate[formname][validate[formname].length - 1][jstypeIndex] = 'verified';
297 function addToValidateLessThan(formname, name, type, required, msg, max, max_field_msg) {
298 addToValidate(formname, name, type, required, msg);
299 validate[formname][validate[formname].length - 1][jstypeIndex] = 'less';
300 validate[formname][validate[formname].length - 1][maxIndex] = max;
301 validate[formname][validate[formname].length - 1][altMsgIndex] = max_field_msg;
304 function addToValidateMoreThan(formname, name, type, required, msg, min) {
305 addToValidate(formname, name, type, required, msg);
306 validate[formname][validate[formname].length - 1][jstypeIndex] = 'more';
307 validate[formname][validate[formname].length - 1][minIndex] = min;
311 function removeFromValidate(formname, name) {
312 for(i = 0; i < validate[formname].length; i++)
314 if(validate[formname][i][nameIndex] == name)
316 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
320 function checkValidate(formname, name) {
321 if(validate[formname]){
322 for(i = 0; i < validate[formname].length; i++){
323 if(validate[formname][i][nameIndex] == name){
330 var formsWithFieldLogic=null;
331 var formWithPrecision =null;
332 function addToValidateFieldLogic(formId,minFieldId, maxFieldId, defaultFieldId, lenFieldId,type,msg){
333 this.formId = document.getElementById(formId);
334 this.min=document.getElementById(minFieldId);
335 this.max= document.getElementById(maxFieldId);
336 this._default= document.getElementById(defaultFieldId);
337 this.len = document.getElementById(lenFieldId);
341 //@params: formid- Dom id of the form containing the precision and float fields
342 // valudId- Dom id of the field containing a float whose precision is to be checked.
343 // precisionId- Dom id of the field containing precision value.
344 function addToValidatePrecision(formId, valueId, precisionId){
345 this.form = document.getElementById(formId);
346 this.float = document.getElementById(valueId);
347 this.precision = document.getElementById(precisionId);
350 //function checkLength(value, referenceValue){
354 function isValidPrecision(value, precision){
355 value = trim(value.toString());
361 if( (precision == "0") ){
362 if (value.indexOf(".")== -1){
369 var actualPrecision = value.substr(value.indexOf(".")+1, value.length).length;
370 return actualPrecision == precision;
372 function toDecimal(original, precision) {
373 precision = (precision == null) ? 2 : precision;
374 num = Math.pow(10, precision);
375 temp = Math.round(original*num)/num;
376 if((temp * 100) % 100 == 0)
378 if((temp * 10) % 10 == 0)
383 function isInteger(s) {
384 if (typeof s == "string" && s == "")
386 if(typeof num_grp_sep != 'undefined' && typeof dec_sep != 'undefined')
388 s = unformatNumberNoParse(s, num_grp_sep, dec_sep).toString();
390 return parseFloat(s) == parseInt(s) && !isNaN(s);
393 function isNumeric(s) {
394 if(!/^-*[0-9\.]+$/.test(s)) {
402 var date_reg_positions = {'Y': 1,'m': 2,'d': 3};
403 var date_reg_format = '([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})'
404 function isDate(dtStr) {
406 if(dtStr.length== 0) {
410 // Check that we have numbers
411 myregexp = new RegExp(date_reg_format)
412 if(!myregexp.test(dtStr))
419 var dateParts = dtStr.match(date_reg_format);
420 for(key in date_reg_positions) {
421 index = date_reg_positions[key];
423 m = dateParts[index];
424 } else if(key == 'd') {
425 d = dateParts[index];
427 y = dateParts[index];
431 // Check that date is real
432 var dd = new Date(y,m,0);
433 // reject negative years
436 // reject month less than 1 and greater than 12
439 // reject days less than 1 or days not in month (e.g. February 30th)
440 if (d < 1 || d > dd.getDate())
445 function getDateObject(dtStr) {
446 if(dtStr.length== 0) {
450 myregexp = new RegExp(date_reg_format)
452 if(myregexp.exec(dtStr)) var dt = myregexp.exec(dtStr)
455 var yr = dt[date_reg_positions['Y']];
456 var mh = dt[date_reg_positions['m']];
457 var dy = dt[date_reg_positions['d']];
458 var dtar = dtStr.split(' ');
459 if(typeof(dtar[1])!='undefined' && isTime(dtar[1])) {//if it is a timedate, we should make date1 to have time value
460 var t1 = dtar[1].replace(/am/i,' AM');
461 var t1 = t1.replace(/pm/i,' PM');
462 //bug #37977: where time format 23.00 causes java script error
463 t1=t1.replace(/\./, ':');
464 date1 = new Date(Date.parse(mh+'/'+dy+ '/'+yr+' '+t1));
468 var date1 = new Date();
469 date1.setFullYear(yr); // xxxx 4 char year
470 date1.setMonth(mh-1); // 0-11 Bug 4048: javascript Date obj months are 0-index
471 date1.setDate(dy); // 1-31
476 function isBefore(value1, value2) {
477 var d1 = getDateObject(value1);
478 var d2 = getDateObject(value2);
479 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.
485 function isValidEmail(emailStr) {
487 if(emailStr.length== 0) {
490 // cn: bug 7128, a period at the end of the string mangles checks. (switched to accept spaces and delimiters)
491 var lastChar = emailStr.charAt(emailStr.length - 1);
492 if(!lastChar.match(/[^\.]/i)) {
495 //bug 40068, According to rules in page 6 of http://www.apps.ietf.org/rfc/rfc3696.html#sec-3,
496 //first character of local part of an email address
497 //should not be a period i.e. '.'
499 var firstLocalChar=emailStr.charAt(0);
500 if(firstLocalChar.match(/\./)){
504 //bug 40068, According to rules in page 6 of http://www.apps.ietf.org/rfc/rfc3696.html#sec-3,
505 //last character of local part of an email address
506 //should not be a period i.e. '.'
508 var pos=emailStr.lastIndexOf("@");
509 var localPart = emailStr.substr(0, pos);
510 var lastLocalChar=localPart.charAt(localPart.length - 1);
511 if(lastLocalChar.match(/\./)){
518 while ((results = reg.exec(emailStr)) != null) {
519 var original = results[0];
520 parsedResult = results[0].replace(';', '::;::');
521 emailStr = emailStr.replace (original, parsedResult);
525 while ((results = reg.exec(emailStr)) != null) {
526 var original = results[0];
527 //Check if we were using ; as a delimiter. If so, skip the commas
528 if(original.indexOf("::;::") == -1) {
529 var parsedResult = results[0].replace(',', '::;::');
530 emailStr = emailStr.replace (original, parsedResult);
534 // mfh: bug 15010 - more practical implementation of RFC 2822 from http://www.regular-expressions.info/email.html, modifed to accept CAPITAL LETTERS
535 //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))
538 //bug 40068, According to rules in page 6 of http://www.apps.ietf.org/rfc/rfc3696.html#sec-3,
539 //allowed special characters ! # $ % & ' * + - / = ? ^ _ ` . { | } ~ in local part
540 var emailArr = emailStr.split(/::;::/);
541 for (var i = 0; i < emailArr.length; i++) {
542 var emailAddress = emailArr[i];
543 if (trim(emailAddress) != '') {
544 if(!/^\s*[\w.%+\-&'#!\$\*=\?\^_`\{\}~\/]+@([A-Z0-9-]+\.)*[A-Z0-9-]+\.[\w-]{2,}\s*$/i.test(emailAddress) &&
545 !/^.*<[A-Z0-9._%+\-&'#!\$\*=\?\^_`\{\}~]+?@([A-Z0-9-]+\.)*[A-Z0-9-]+\.[\w-]{2,}>\s*$/i.test(emailAddress)) {
554 function isValidPhone(phoneStr) {
555 if(phoneStr.length== 0) {
558 if(!/^[0-9\-\(\)\s]+$/.test(phoneStr))
562 function isFloat(floatStr) {
563 if(floatStr.length== 0) {
566 if(!(typeof(num_grp_sep)=='undefined' || typeof(dec_sep)=='undefined')) {
567 floatStr = unformatNumberNoParse(floatStr, num_grp_sep, dec_sep).toString();
570 return /^(-)?[0-9\.]+$/.test(floatStr);
572 function isDBName(str) {
577 // must start with a letter
578 if(!/^[a-zA-Z][a-zA-Z\_0-9]*$/.test(str))
582 var time_reg_format = "[0-9]{1,2}\:[0-9]{2}";
583 function isTime(timeStr) {
584 var time_reg_format = "[0-9]{1,2}\:[0-9]{2}";
585 time_reg_format = time_reg_format.replace('([ap]m)', '');
586 time_reg_format = time_reg_format.replace('([AP]M)', '');
587 if(timeStr.length== 0){
590 //we now support multiple time formats
591 myregexp = new RegExp(time_reg_format)
592 if(!myregexp.test(timeStr))
598 function inRange(value, min, max) {
599 if (typeof num_grp_sep != 'undefined' && typeof dec_sep != 'undefined')
600 value = unformatNumberNoParse(value, num_grp_sep, dec_sep).toString();
601 return value >= min && value <= max;
604 function bothExist(item1, item2) {
605 if(typeof item1 == 'undefined') { return false; }
606 if(typeof item2 == 'undefined') { return false; }
607 if((item1 == '' && item2 != '') || (item1 != '' && item2 == '') ) { return false; }
611 trim = YAHOO.lang.trim;
614 function check_form(formname) {
615 if (typeof(siw) != 'undefined' && siw
616 && typeof(siw.selectingSomething) != 'undefined' && siw.selectingSomething)
618 return validate_form(formname, '');
621 function add_error_style(formname, input, txt, flash) {
622 if (typeof flash == "undefined")
625 inputHandle = typeof input == "object" ? input : document.forms[formname][input];
626 style = get_current_bgcolor(inputHandle);
628 // strip off the colon at the end of the warning strings
629 if ( txt.substring(txt.length-1) == ':' )
630 txt = txt.substring(0,txt.length-1)
632 // Bug 28249 - To help avoid duplicate messages for an element, strip off extra messages and
633 // match on the field name itself
634 requiredTxt = SUGAR.language.get('app_strings', 'ERR_MISSING_REQUIRED_FIELDS');
635 invalidTxt = SUGAR.language.get('app_strings', 'ERR_INVALID_VALUE');
636 nomatchTxt = SUGAR.language.get('app_strings', 'ERR_SQS_NO_MATCH_FIELD');
637 matchTxt = txt.replace(requiredTxt,'').replace(invalidTxt,'').replace(nomatchTxt,'');
639 if(inputHandle.parentNode.innerHTML.search(matchTxt) == -1) {
640 errorTextNode = document.createElement('span');
641 errorTextNode.className = 'required';
642 errorTextNode.innerHTML = '<br />' + txt;
643 if ( inputHandle.parentNode.className.indexOf('x-form-field-wrap') != -1 ) {
644 inputHandle.parentNode.parentNode.appendChild(errorTextNode);
647 inputHandle.parentNode.appendChild(errorTextNode);
650 inputHandle.style.backgroundColor = "#FF0000";
651 inputsWithErrors.push(inputHandle);
655 // We only need to setup the flashy-flashy on the first entry, it loops through all fields automatically
656 if ( inputsWithErrors.length == 1 ) {
657 for(wp = 1; wp <= 10; wp++) {
658 window.setTimeout('fade_error_style(style, '+wp*10+')',1000+(wp*50));
661 if(typeof (window[formname + "_tabs"]) != "undefined") {
662 var tabView = window[formname + "_tabs"];
663 var parentDiv = YAHOO.util.Dom.getAncestorByTagName(inputHandle, "div");
665 var tabs = tabView.get("tabs");
666 for (var i in tabs) {
667 if (tabs[i].get("contentEl") == parentDiv
668 || YAHOO.util.Dom.isAncestor(tabs[i].get("contentEl"), inputHandle))
670 tabs[i].get("labelEl").style.color = "red";
671 if ( inputsWithErrors.length == 1 )
672 tabView.selectTab(i);
677 window.setTimeout("if (inputsWithErrors[" + (inputsWithErrors.length - 1) + "]) inputsWithErrors[" + (inputsWithErrors.length - 1) + "].style.backgroundColor = null;", 2000);
681 // Catch errors here so we don't allow an incomplete record through the javascript validation
686 * removes all error messages for the current form
688 function clear_all_errors() {
689 for(var wp = 0; wp < inputsWithErrors.length; wp++) {
690 if(typeof(inputsWithErrors[wp]) !='undefined' && typeof inputsWithErrors[wp].parentNode != 'undefined' && inputsWithErrors[wp].parentNode != null) {
691 if ( inputsWithErrors[wp].parentNode.className.indexOf('x-form-field-wrap') != -1 )
693 inputsWithErrors[wp].parentNode.parentNode.removeChild(inputsWithErrors[wp].parentNode.parentNode.lastChild);
697 inputsWithErrors[wp].parentNode.removeChild(inputsWithErrors[wp].parentNode.lastChild);
701 if (inputsWithErrors.length == 0) return;
703 if ( YAHOO.util.Dom.getAncestorByTagName(inputsWithErrors[0], "form") ) {
704 var formname = YAHOO.util.Dom.getAncestorByTagName(inputsWithErrors[0], "form").getAttribute("name");
705 if(typeof (window[formname + "_tabs"]) != "undefined") {
706 var tabView = window[formname + "_tabs"];
708 var tabs = tabView.get("tabs");
709 for (var i in tabs) {
710 tabs[i].get("labelEl").style.color = "";
714 inputsWithErrors = new Array();
718 function get_current_bgcolor(input) {
719 if(input.currentStyle) {// ie
720 style = input.currentStyle.backgroundColor;
721 return style.substring(1,7);
725 styleRGB = document.defaultView.getComputedStyle(input, '').getPropertyValue("background-color");
726 comma = styleRGB.indexOf(',');
727 style += dec2hex(styleRGB.substring(4, comma));
728 commaPrevious = comma;
729 comma = styleRGB.indexOf(',', commaPrevious+1);
730 style += dec2hex(styleRGB.substring(commaPrevious+2, comma));
731 style += dec2hex(styleRGB.substring(comma+2, styleRGB.lastIndexOf(')')));
736 function hex2dec(hex){return(parseInt(hex,16));}
737 var hexDigit=new Array("0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F");
738 function dec2hex(dec){return(hexDigit[dec>>4]+hexDigit[dec&15]);}
740 function fade_error_style(normalStyle, percent) {
741 errorStyle = 'c60c30';
742 var r1 = hex2dec(errorStyle.slice(0,2));
743 var g1 = hex2dec(errorStyle.slice(2,4));
744 var b1 = hex2dec(errorStyle.slice(4,6));
746 var r2 = hex2dec(normalStyle.slice(0,2));
747 var g2 = hex2dec(normalStyle.slice(2,4));
748 var b2 = hex2dec(normalStyle.slice(4,6));
751 var pc = percent / 100;
753 r= Math.floor(r1+(pc*(r2-r1)) + .5);
754 g= Math.floor(g1+(pc*(g2-g1)) + .5);
755 b= Math.floor(b1+(pc*(b2-b1)) + .5);
757 for(var wp = 0; wp < inputsWithErrors.length; wp++) {
758 inputsWithErrors[wp].style.backgroundColor = "#" + dec2hex(r) + dec2hex(g) + dec2hex(b);
762 function isFieldTypeExceptFromEmptyCheck(fieldType)
765 var exemptList = ['bool','file'];
766 for(var i=0;i<exemptList.length;i++)
768 if(fieldType == exemptList[i])
773 function validate_form(formname, startsWith){
774 requiredTxt = SUGAR.language.get('app_strings', 'ERR_MISSING_REQUIRED_FIELDS');
775 invalidTxt = SUGAR.language.get('app_strings', 'ERR_INVALID_VALUE');
777 if ( typeof (formname) == 'undefined')
781 if ( typeof (validate[formname]) == 'undefined')
783 disableOnUnloadEditView(document.forms[formname]);
787 var form = document.forms[formname];
790 var _date = new Date();
791 if(_date.getTime() < (lastSubmitTime + 2000) && startsWith == oldStartsWith) { // ignore submits for the next 2 seconds
794 lastSubmitTime = _date.getTime();
795 oldStartsWith = startsWith;
797 clear_all_errors(); // remove previous error messages
799 inputsWithErrors = new Array();
800 for(var i = 0; i < validate[formname].length; i++){
801 if(validate[formname][i][nameIndex].indexOf(startsWith) == 0){
802 if(typeof form[validate[formname][i][nameIndex]] != 'undefined' && typeof form[validate[formname][i][nameIndex]].value != 'undefined'){
805 //If a field is not required and it is blank or is binarydependant, skip validation.
806 //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
807 if(!validate[formname][i][requiredIndex] && trim(form[validate[formname][i][nameIndex]].value) == '' && (typeof(validate[formname][i][jstypeIndex]) != 'undefined' && validate[formname][i][jstypeIndex] != 'binarydep'))
812 if(validate[formname][i][requiredIndex]
813 && !isFieldTypeExceptFromEmptyCheck(validate[formname][i][typeIndex])
815 if(typeof form[validate[formname][i][nameIndex]] == 'undefined' || trim(form[validate[formname][i][nameIndex]].value) == ""){
816 add_error_style(formname, validate[formname][i][nameIndex], requiredTxt +' ' + validate[formname][i][msgIndex]);
821 switch(validate[formname][i][typeIndex]){
823 if(!isValidEmail(trim(form[validate[formname][i][nameIndex]].value))){
825 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
829 if( !isTime(trim(form[validate[formname][i][nameIndex]].value))){
831 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
833 case 'date': if(!isDate(trim(form[validate[formname][i][nameIndex]].value))){
835 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
840 if(!isDBName(trim(form[validate[formname][i][nameIndex]].value))){
842 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
848 var file_input = form[validate[formname][i][nameIndex] + '_file'];
849 if( file_input && validate[formname][i][requiredIndex] && trim(file_input.value) == "" && !file_input.disabled ) {
851 add_error_style(formname, validate[formname][i][nameIndex], requiredTxt + " " + validate[formname][i][msgIndex]);
855 if(!isInteger(trim(form[validate[formname][i][nameIndex]].value))){
857 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
862 if(!isFloat(trim(form[validate[formname][i][nameIndex]].value))){
864 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
868 var div_element_id = formname + '_' + form[validate[formname][i][nameIndex]].name + '_operation_div';
869 var input_elements = YAHOO.util.Selector.query('input', document.getElementById(div_element_id));
870 var primary_field_id = '';
871 var validation_passed = false;
872 var replace_selected = false;
874 //Loop through the option elements (replace or add currently)
875 for(t in input_elements) {
876 if(input_elements[t].type && input_elements[t].type == 'radio' && input_elements[t].checked == true && input_elements[t].value == 'replace') {
878 //Now find where the primary radio button is and if a value has been set
879 var radio_elements = YAHOO.util.Selector.query('input[type=radio]', document.getElementById(formname + '_team_name_table'));
881 for(var x = 0; x < radio_elements.length; x++) {
882 if(radio_elements[x].name != 'team_name_type') {
883 primary_field_id = 'team_name_collection_' + radio_elements[x].value;
884 if(radio_elements[x].checked) {
885 replace_selected = true;
886 if(trim(document.forms[formname].elements[primary_field_id].value) != '') {
887 validation_passed = true;
890 } else if(trim(document.forms[formname].elements[primary_field_id].value) != '') {
891 replace_selected = true;
898 if(replace_selected && !validation_passed) {
899 add_error_style(formname, primary_field_id, SUGAR.language.get('app_strings', 'ERR_NO_PRIMARY_TEAM_SPECIFIED'));
904 var table_element_id = formname + '_' + form[validate[formname][i][nameIndex]].name + '_table';
905 if(document.getElementById(table_element_id)) {
906 var input_elements = YAHOO.util.Selector.query('input[type=radio]', document.getElementById(table_element_id));
907 var has_primary = false;
908 var primary_field_id = form[validate[formname][i][nameIndex]].name + '_collection_0';
910 for(t in input_elements) {
911 primary_field_id = form[validate[formname][i][nameIndex]].name + '_collection_' + input_elements[t].value;
912 if(input_elements[t].type && input_elements[t].type == 'radio' && input_elements[t].checked == true) {
913 if(document.forms[formname].elements[primary_field_id].value != '') {
922 var field_id = form[validate[formname][i][nameIndex]].name + '_collection_' + input_elements[0].value;
923 add_error_style(formname, field_id, SUGAR.language.get('app_strings', 'ERR_NO_PRIMARY_TEAM_SPECIFIED'));
929 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex]);
933 if(typeof validate[formname][i][jstypeIndex] != 'undefined'/* && !isError*/){
935 switch(validate[formname][i][jstypeIndex]){
937 if(!inRange(trim(form[validate[formname][i][nameIndex]].value), validate[formname][i][minIndex], validate[formname][i][maxIndex])){
939 var lbl_validate_range = SUGAR.language.get('app_strings', 'LBL_VALIDATE_RANGE');
940 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] + ") ");
944 compareTo = form[validate[formname][i][compareToIndex]];
945 if( typeof compareTo != 'undefined'){
946 if(trim(compareTo.value) != '' || (validate[formname][i][allowblank] != 'true') ) {
947 date2 = trim(compareTo.value);
948 date1 = trim(form[validate[formname][i][nameIndex]].value);
950 if(trim(date1).length != 0 && !isBefore(date1,date2)){
953 //jc:#12287 - adding translation for the is not before message
954 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex] + "(" + date1 + ") " + SUGAR.language.get('app_strings', 'MSG_IS_NOT_BEFORE') + ' ' +date2);
960 value=unformatNumber(trim(form[validate[formname][i][nameIndex]].value), num_grp_sep, dec_sep);
961 maximum = parseFloat(validate[formname][i][maxIndex]);
962 if( typeof maximum != 'undefined'){
965 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]);
970 value=unformatNumber(trim(form[validate[formname][i][nameIndex]].value), num_grp_sep, dec_sep);
971 minimum = parseFloat(validate[formname][i][minIndex]);
972 if( typeof minimum != 'undefined'){
975 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'));
980 compareTo = form[validate[formname][i][compareToIndex]];
981 if( typeof compareTo != 'undefined') {
982 item1 = trim(form[validate[formname][i][nameIndex]].value);
983 item2 = trim(compareTo.value);
984 if(!bothExist(item1, item2)) {
986 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex]);
991 compareTo = form[validate[formname][i][compareToIndex]];
992 if( typeof compareTo != 'undefined') {
993 item1 = trim(form[validate[formname][i][nameIndex]].value);
994 item2 = trim(compareTo.value);
995 if(!bothExist(item1, item2) || item1 != item2) {
997 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex]);
1002 arr = eval(validate[formname][i][arrIndex]);
1003 operator = validate[formname][i][operatorIndex];
1004 item1 = trim(form[validate[formname][i][nameIndex]].value);
1005 if (operator.charAt(0) == 'u') {
1006 item1 = item1.toUpperCase();
1007 operator = operator.substring(1);
1008 } else if (operator.charAt(0) == 'l') {
1009 item1 = item1.toLowerCase();
1010 operator = operator.substring(1);
1012 for(j = 0; j < arr.length; j++){
1014 if((operator == "==" && val == item1) || (operator == "!=" && val != item1)){
1016 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
1021 if(trim(form[validate[formname][i][nameIndex]].value) == 'false'){
1022 //Fake an error so form does not submit
1032 /* nsingh: BUG#15102
1033 Check min max default field logic.
1034 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.*/
1035 if(formsWithFieldLogic){
1036 var invalidLogic=false;
1037 if(formsWithFieldLogic.min && formsWithFieldLogic.max && formsWithFieldLogic._default) {
1038 var showErrorsOn={min:{value:'min', show:false, obj:formsWithFieldLogic.min.value},
1039 max:{value:'max',show:false, obj:formsWithFieldLogic.max.value},
1040 _default:{value:'default',show:false, obj:formsWithFieldLogic._default.value},
1041 len:{value:'len', show:false, obj:parseInt(formsWithFieldLogic.len.value,10)}};
1043 var min = (formsWithFieldLogic.min.value !='') ? parseFloat(formsWithFieldLogic.min.value) : 'undef';
1044 var max = (formsWithFieldLogic.max.value !='') ? parseFloat(formsWithFieldLogic.max.value) : 'undef';
1045 var _default = (formsWithFieldLogic._default.value!='')? parseFloat(formsWithFieldLogic._default.value) : 'undef';
1047 /*Check all lengths are <= max size.*/
1048 for(var i in showErrorsOn){
1049 if(showErrorsOn[i].value!='len' && showErrorsOn[i].obj.length > showErrorsOn.len.obj){
1051 showErrorsOn[i].show=true;
1052 showErrorsOn.len.show=true;
1056 if(min!='undef' && max!='undef' && _default!='undef'){
1057 if(!inRange(_default,min,max)){
1059 showErrorsOn.min.show=true;
1060 showErrorsOn.max.show=true;
1061 showErrorsOn._default.show=true;
1064 if(min!='undef' && max!= 'undef' && min > max){
1065 invalidLogic = true;
1066 showErrorsOn.min.show=true;
1067 showErrorsOn.max.show=true;
1069 if(min!='undef' && _default!='undef' && _default < min){
1071 invalidLogic = true;
1072 showErrorsOn.min.show=true;
1073 showErrorsOn._default.show=true;
1075 if(max!='undef' && _default !='undef' && _default>max){
1077 invalidLogic = true;
1078 showErrorsOn.max.show=true;
1079 showErrorsOn._default.show=true;
1084 for(var error in showErrorsOn)
1085 if(showErrorsOn[error].show)
1086 add_error_style(formname,showErrorsOn[error].value, formsWithFieldLogic.msg);
1091 formsWithFieldLogic = null;
1094 if(formWithPrecision){
1095 if (!isValidPrecision(formWithPrecision.float.value, formWithPrecision.precision.value)){
1097 add_error_style(formname, 'default', SUGAR.language.get('app_strings', 'ERR_COMPATIBLE_PRECISION_VALUE'));
1105 if (isError == true) {
1107 if (self.pageYOffset) // all except Explorer
1109 nwX = self.pageXOffset;
1110 seX = self.innerWidth;
1111 nwY = self.pageYOffset;
1112 seY = self.innerHeight;
1114 else if (document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
1116 nwX = document.documentElement.scrollLeft;
1117 seX = document.documentElement.clientWidth;
1118 nwY = document.documentElement.scrollTop;
1119 seY = document.documentElement.clientHeight;
1121 else if (document.body) // all other Explorers
1123 nwX = document.body.scrollLeft;
1124 seX = document.body.clientWidth;
1125 nwY = document.body.scrollTop;
1126 seY = document.body.clientHeight;
1129 var inView = true; // is there an error within viewport of browser
1130 for(var wp = 0; wp < inputsWithErrors.length; wp++) {
1131 var elementCoor = findElementPos(inputsWithErrors[wp]);
1132 if(!(elementCoor.x >= nwX && elementCoor.y >= nwY &&
1133 elementCoor.x <= seX && elementCoor.y <= seY)) { // if input is not within viewport
1135 scrollToTop = elementCoor.y - 75;
1136 scrollToLeft = elementCoor.x - 75;
1138 else { // on first input within viewport, don't scroll
1144 if(!inView) window.scrollTo(scrollToLeft,scrollToTop);
1149 disableOnUnloadEditView(form);
1156 * This array is used to remember mark status of rows in browse mode
1158 var marked_row = new Array;
1162 * Sets/unsets the pointer and marker in browse mode
1164 * @param object the table row
1165 * @param interger the row number
1166 * @param string the action calling this script (over, out or click)
1167 * @param string the default background color
1168 * @param string the color to use for mouseover
1169 * @param string the color to use for marking a row
1171 * @return boolean whether pointer is set or not
1173 function setPointer(theRow, theRowNum, theAction, theDefaultColor, thePointerColor, theMarkColor) {
1174 var theCells = null;
1176 // 1. Pointer and mark feature are disabled or the browser can't get the
1178 if ((thePointerColor == '' && theMarkColor == '')
1179 || typeof(theRow.style) == 'undefined') {
1183 // 2. Gets the current row and exits if the browser can't get it
1184 if (typeof(document.getElementsByTagName) != 'undefined') {
1185 theCells = theRow.getElementsByTagName('td');
1187 else if (typeof(theRow.cells) != 'undefined') {
1188 theCells = theRow.cells;
1194 // 3. Gets the current color...
1195 var rowCellsCnt = theCells.length;
1196 var domDetect = null;
1197 var currentColor = null;
1198 var newColor = null;
1199 // 3.1 ... with DOM compatible browsers except Opera that does not return
1200 // valid values with "getAttribute"
1201 if (typeof(window.opera) == 'undefined'
1202 && typeof(theCells[0].getAttribute) != 'undefined') {
1203 currentColor = theCells[0].getAttribute('bgcolor');
1206 // 3.2 ... with other browsers
1208 currentColor = theCells[0].style.backgroundColor;
1212 // 4. Defines the new color
1213 // 4.1 Current color is the default one
1214 if (currentColor == ''
1215 || (currentColor!= null && (currentColor.toLowerCase() == theDefaultColor.toLowerCase()))) {
1216 if (theAction == 'over' && thePointerColor != '') {
1217 newColor = thePointerColor;
1219 else if (theAction == 'click' && theMarkColor != '') {
1220 newColor = theMarkColor;
1221 marked_row[theRowNum] = true;
1224 // 4.1.2 Current color is the pointer one
1225 else if (currentColor!= null && (currentColor.toLowerCase() == thePointerColor.toLowerCase())
1226 && (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])) {
1227 if (theAction == 'out') {
1228 newColor = theDefaultColor;
1230 else if (theAction == 'click' && theMarkColor != '') {
1231 newColor = theMarkColor;
1232 marked_row[theRowNum] = true;
1235 // 4.1.3 Current color is the marker one
1236 else if (currentColor!= null && (currentColor.toLowerCase() == theMarkColor.toLowerCase())) {
1237 if (theAction == 'click') {
1238 newColor = (thePointerColor != '')
1241 marked_row[theRowNum] = (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])
1247 // 5. Sets the new color...
1250 // 5.1 ... with DOM compatible browsers except Opera
1252 for (c = 0; c < rowCellsCnt; c++) {
1253 theCells[c].setAttribute('bgcolor', newColor, 0);
1256 // 5.2 ... with other browsers
1258 for (c = 0; c < rowCellsCnt; c++) {
1259 theCells[c].style.backgroundColor = newColor;
1265 } // end of the 'setPointer()' function
1269 * listbox redirection
1271 function goToUrl(selObj, goToLocation) {
1272 eval("document.location.href = '" + goToLocation + "pos=" + selObj.options[selObj.selectedIndex].value + "'");
1277 var json_objects = new Object();
1279 function getXMLHTTPinstance() {
1280 var xmlhttp = false;
1281 var userAgent = navigator.userAgent.toLowerCase() ;
1283 // IE Check supports ActiveX controls
1284 if (userAgent.indexOf("msie") != -1 && userAgent.indexOf("mac") == -1 && userAgent.indexOf("opera") == -1) {
1285 var version = navigator.appVersion.match(/MSIE (.\..)/)[1] ;
1286 if(version >= 5.5 ) {
1288 xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
1292 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
1301 if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
1302 xmlhttp = new XMLHttpRequest();
1307 // NOW LOAD THE OBJECT..
1308 var global_xmlhttp = getXMLHTTPinstance();
1310 function http_fetch_sync(url,post_data) {
1311 global_xmlhttp = getXMLHTTPinstance();
1314 if(typeof(post_data) != 'undefined') method = 'POST';
1316 global_xmlhttp.open(method, url,false);
1319 alert('message:'+e.message+":url:"+url);
1321 if(method == 'POST') {
1322 global_xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
1325 global_xmlhttp.send(post_data);
1327 if (SUGAR.util.isLoginPage(global_xmlhttp.responseText))
1330 var args = {"responseText" : global_xmlhttp.responseText,
1331 "responseXML" : global_xmlhttp.responseXML,
1332 "request_id" : typeof(request_id) != "undefined" ? request_id : 0};
1336 // this is a GET unless post_data is defined
1338 function http_fetch_async(url,callback,request_id,post_data) {
1340 if(typeof(post_data) != 'undefined') {
1345 global_xmlhttp.open(method, url,true);
1348 alert('message:'+e.message+":url:"+url);
1350 if(method == 'POST') {
1351 global_xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
1353 global_xmlhttp.onreadystatechange = function() {
1354 if(global_xmlhttp.readyState==4) {
1355 if(global_xmlhttp.status == 200) {
1356 if (SUGAR.util.isLoginPage(global_xmlhttp.responseText))
1358 var args = {"responseText" : global_xmlhttp.responseText,
1359 "responseXML" : global_xmlhttp.responseXML,
1360 "request_id" : request_id };
1361 callback.call(document,args);
1364 alert("There was a problem retrieving the XML data:\n" + global_xmlhttp.statusText);
1368 global_xmlhttp.send(post_data);
1371 function call_json_method(module,action,vars,variable_name,callback) {
1372 global_xmlhttp.open("GET", "index.php?entryPoint=json&module="+module+"&action="+action+"&"+vars,true);
1373 global_xmlhttp.onreadystatechange=
1375 if(global_xmlhttp.readyState==4) {
1376 if(global_xmlhttp.status == 200) {
1377 // cn: bug 12274 - pass through JSON.parse() to remove security envelope
1378 json_objects[variable_name] = JSON.parse(global_xmlhttp.responseText);
1380 // cn: bug 12274 - safe from CSRF, render response as expected
1381 var respText = YAHOO.lang.JSON.stringify(global_xmlhttp.responseText);
1382 var args = {responseText:respText, responseXML:global_xmlhttp.responseXML};
1383 callback.call(document, args);
1386 alert("There was a problem retrieving the XML data:\n" + global_xmlhttp.statusText);
1390 global_xmlhttp.send(null);
1393 function insert_at_cursor(field, value) {
1395 if (document.selection) {
1397 sel = document.selection.createRange();
1401 else if(field.selectionStart || field.selectionStart == '0') {
1402 var start_pos = field.selectionStart;
1403 var end_pos = field.selectionEnd;
1404 field.value = field.value.substring(0, start_pos) + value + field.value.substring(end_pos, field.value.length);
1407 field.value += value;
1411 function checkParentType(type,button) {
1412 if(button == null) {
1415 if(typeof disabledModules != 'undefined' && typeof(disabledModules[type]) != 'undefined') {
1416 button.disabled='disabled';
1419 button.disabled = false;
1423 function parseDate(input, format) {
1425 format = format.replace(/%/g, '');
1426 sep = format.charAt(1);
1427 yAt = format.indexOf('Y')
1428 // 1-1-06 or 1-12-06 or 1-1-2006 or 1-12-2006
1429 if(date.match(/^\d{1,2}[\/-]\d{1,2}[\/-]\d{2,4}$/) && yAt == 4) {
1430 if(date.match(/^\d{1}[\/-].*$/)) date = '0' + date;
1431 if(date.match(/^\d{2}[\/-]\d{1}[\/-].*$/)) date = date.substring(0,3) + '0' + date.substring(3,date.length);
1432 if(date.match(/^\d{2}[\/-]\d{2}[\/-]\d{2}$/)) date = date.substring(0,6) + '20' + date.substring(6,date.length);
1434 // 06-11-1 or 06-1-1
1435 else if(date.match(/^\d{2,4}[\/-]\d{1,2}[\/-]\d{1,2}$/)) {
1436 if(date.match(/^\d{2}[\/-].*$/)) date = '20' + date;
1437 if(date.match(/^\d{4}[\/-]\d{1}[\/-].*$/)) date = date.substring(0,5) + '0' + date.substring(5,date.length);
1438 if(date.match(/^\d{4}[\/-]\d{2}[\/-]\d{1}$/)) date = date.substring(0,8) + '0' + date.substring(8,date.length);
1440 else if(date.match(/^\d{4,8}$/)) { // digits only
1442 if(date.match(/^\d{8}$/)) digits = 8;// match for 8 digits
1443 else if(date.match(/\d{6}/)) digits = 6;// match for 5 digits
1444 else if(date.match(/\d{4}/)) digits = 4;// match for 5 digits
1445 else if(date.match(/\d{5}/)) digits = 5;// match for 5 digits
1450 case 4: date = '20' + date.substring(0,2) + sep + '0' + date.substring(2, 3) + sep + '0' + date.substring(3,4); break;
1451 case 5: date = '20' + date.substring(0,2) + sep + date.substring(2, 4) + sep + '0' + date.substring(4,5); break;
1452 case 6: date = '20' + date.substring(0,2) + sep + date.substring(2, 4) + sep + date.substring(4,6); break;
1453 case 8: date = date.substring(0,4) + sep + date.substring(4, 6) + sep + date.substring(6,8); break;
1458 case 4: date = '0' + date.substring(0,1) + sep + '20' + date.substring(1, 3) + sep + '0' + date.substring(3,4); break;
1459 case 5: date = date.substring(0,2) + sep + '20' + date.substring(2, 4) + sep + '0' + date.substring(4,5); break;
1460 case 6: date = date.substring(0,2) + sep + '20' + date.substring(2, 4) + sep + date.substring(4,6); break;
1461 case 8: date = date.substring(0,2) + sep + date.substring(2, 6) + sep + date.substring(6,8); break;
1465 case 4: date = '0' + date.substring(0,1) + sep + '0' + date.substring(1, 2) + sep + '20' + date.substring(2,4); break;
1466 case 5: date = '0' + date.substring(0,1) + sep + date.substring(1, 3) + sep + '20' + date.substring(3,5); break;
1467 case 6: date = date.substring(0,2) + sep + date.substring(2, 4) + sep + '20' + date.substring(4,6); break;
1468 case 8: date = date.substring(0,2) + sep + date.substring(2, 4) + sep + date.substring(4,8); break;
1473 date = date.replace(/[\/-]/g, sep);
1477 // find obj's position
1478 function findElementPos(obj) {
1481 if (obj.offsetParent) {
1482 while (obj.offsetParent) {
1483 x += obj.offsetLeft;
1485 obj = obj.offsetParent;
1487 }//if offsetParent exists
1488 else if (obj.x && obj.y) {
1492 return new coordinate(x, y);
1496 // get dimensions of the browser window
1497 function getClientDim() {
1498 var nwX, nwY, seX, seY;
1499 if (self.pageYOffset) // all except Explorer
1501 nwX = self.pageXOffset;
1502 seX = self.innerWidth + nwX;
1503 nwY = self.pageYOffset;
1504 seY = self.innerHeight + nwY;
1506 else if (document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
1508 nwX = document.documentElement.scrollLeft;
1509 seX = document.documentElement.clientWidth + nwX;
1510 nwY = document.documentElement.scrollTop;
1511 seY = document.documentElement.clientHeight + nwY;
1513 else if (document.body) // all other Explorers
1515 nwX = document.body.scrollLeft;
1516 seX = document.body.clientWidth + nwX;
1517 nwY = document.body.scrollTop;
1518 seY = document.body.clientHeight + nwY;
1520 return {'nw' : new coordinate(nwX, nwY), 'se' : new coordinate(seX, seY)};
1524 * stop propagation on events
1526 function freezeEvent(e) {
1528 if (e.preventDefault) e.preventDefault();
1529 e.returnValue = false;
1530 e.cancelBubble = true;
1531 if (e.stopPropagation) e.stopPropagation();
1540 function coordinate(_x, _y) {
1549 return new position(this.x + rh.x, this.y + rh.y);
1553 return new position(this.x + rh.x, this.y + rh.y);
1557 // sends theForm via AJAX and fills in the theDiv
1558 function sendAndRetrieve(theForm, theDiv, loadingStr) {
1559 function success(data) {
1560 document.getElementById(theDiv).innerHTML = data.responseText;
1561 ajaxStatus.hideStatus();
1563 if(typeof loadingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
1564 ajaxStatus.showStatus(loadingStr);
1565 YAHOO.util.Connect.setForm(theForm);
1566 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
1570 //save the form and redirect
1571 function sendAndRedirect(theForm, loadingStr, redirect_location) {
1572 function success(data) {
1573 if(redirect_location){
1574 location.href=redirect_location;
1576 ajaxStatus.hideStatus();
1578 if(typeof loadingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
1579 ajaxStatus.showStatus(loadingStr);
1580 YAHOO.util.Connect.setForm(theForm);
1581 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
1585 function saveForm(theForm, theDiv, loadingStr) {
1586 if(check_form(theForm)){
1587 for(i = 0; i < ajaxFormArray.length; i++){
1588 if(ajaxFormArray[i] == theForm){
1589 ajaxFormArray.splice(i, 1);
1592 return sendAndRetrieve(theForm, loadingStr, theDiv);
1598 // Builds a "snapshot" of the form, so we can use it to see if someone has changed it.
1599 function snapshotForm(theForm) {
1600 var snapshotTxt = '';
1601 var elemList = theForm.elements;
1605 for( var i = 0; i < elemList.length ; i++ ) {
1607 if ( typeof(elem.type) == 'undefined' ) {
1611 elemType = elem.type.toLowerCase();
1613 snapshotTxt = snapshotTxt + elem.name;
1615 if ( elemType == 'text' || elemType == 'textarea' || elemType == 'password' ) {
1616 snapshotTxt = snapshotTxt + elem.value;
1618 else if ( elemType == 'select' || elemType == 'select-one' || elemType == 'select-multiple' ) {
1619 var optionList = elem.options;
1620 for ( var ii = 0 ; ii < optionList.length ; ii++ ) {
1621 if ( optionList[ii].selected ) {
1622 snapshotTxt = snapshotTxt + optionList[ii].value;
1626 else if ( elemType == 'radio' || elemType == 'checkbox' ) {
1627 if ( elem.selected ) {
1628 snapshotTxt = snapshotTxt + 'checked';
1631 else if ( elemType == 'hidden' ) {
1632 snapshotTxt = snapshotTxt + elem.value;
1639 function initEditView(theForm) {
1640 if (SUGAR.util.ajaxCallInProgress()) {
1641 window.setTimeout(function(){initEditView(theForm);}, 100);
1645 if ( theForm == null || theForm.id == null ) {
1646 // Not much we can do here.
1650 // we don't need to check if the data is changed in the search popup
1651 if (theForm.id == 'popup_query_form') {
1654 if ( typeof editViewSnapshots == 'undefined' || editViewSnapshots == null ) {
1655 editViewSnapshots = new Object();
1657 if ( typeof SUGAR.loadedForms == 'undefined' || SUGAR.loadedForms == null) {
1658 SUGAR.loadedForms = new Object();
1661 editViewSnapshots[theForm.id] = snapshotForm(theForm);
1662 SUGAR.loadedForms[theForm.id] = true;
1666 function onUnloadEditView(theForm) {
1668 var dataHasChanged = false;
1670 if ( typeof editViewSnapshots == 'undefined' ) {
1671 // No snapshots, move along
1675 if ( typeof theForm == 'undefined' ) {
1676 // Need to check all editViewSnapshots
1677 for ( var idx in editViewSnapshots ) {
1679 theForm = document.getElementById(idx);
1680 // console.log('DEBUG: Checking all forms '+theForm.id);
1681 if ( theForm == null
1682 || typeof editViewSnapshots[theForm.id] == 'undefined'
1683 || editViewSnapshots[theForm.id] == null
1684 || !SUGAR.loadedForms[theForm.id]) {
1688 var snap = snapshotForm(theForm);
1689 if ( editViewSnapshots[theForm.id] != snap ) {
1690 dataHasChanged = true;
1694 // Just need to check a single form for changes
1695 if ( editViewSnapshots == null || typeof theForm.id == 'undefined' || typeof editViewSnapshots[theForm.id] == 'undefined' || editViewSnapshots[theForm.id] == null ) {
1699 // console.log('DEBUG: Checking one form '+theForm.id);
1700 if ( editViewSnapshots[theForm.id] != snapshotForm(theForm) ) {
1701 // Data has changed.
1702 dataHasChanged = true;
1706 if ( dataHasChanged == true ) {
1707 return SUGAR.language.get('app_strings','WARN_UNSAVED_CHANGES');
1714 function disableOnUnloadEditView(theForm) {
1715 // If you don't pass anything in, it disables all checking
1716 if ( typeof theForm == 'undefined' || typeof editViewSnapshots == 'undefined' || theForm == null || editViewSnapshots == null) {
1717 window.onbeforeunload = null;
1718 editViewSnapshots = null;
1720 // console.log('DEBUG: Disabling all edit view checks');
1723 // Otherwise, it just disables it for this form
1724 if ( typeof(theForm.id) != 'undefined' && typeof(editViewSnapshots[theForm.id]) != 'undefined' ) {
1725 editViewSnapshots[theForm.id] = null;
1728 // console.log('DEBUG : Disabling just checks for '+theForm.id);
1734 * save some forms using an ajax call
1735 * theForms - the ids of all of theh forms to save
1736 * savingStr - the string to display when saving the form
1737 * completeStr - the string to display when the form has been saved
1739 function saveForms( savingStr, completeStr) {
1741 theForms = ajaxFormArray;
1742 function success(data) {
1743 var theForm = document.getElementById(ajaxFormArray[0]);
1744 document.getElementById('multiedit_'+theForm.id).innerHTML = data.responseText;
1745 var saveAllButton = document.getElementById('ajaxsaveall');
1746 ajaxFormArray.splice(index, 1);
1747 if(saveAllButton && ajaxFormArray.length <= 1){
1748 saveAllButton.style.visibility = 'hidden';
1751 if(index == theForms.length){
1752 ajaxStatus.showStatus(completeStr);
1753 window.setTimeout('ajaxStatus.hideStatus();', 2000);
1755 saveAllButton.style.visibility = 'hidden';
1760 if(typeof savingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
1761 ajaxStatus.showStatus(savingStr);
1763 //loop through the forms saving each one
1764 for(i = 0; i < theForms.length; i++){
1765 var theForm = document.getElementById(theForms[i]);
1766 if(check_form(theForm.id)){
1767 theForm.action.value='AjaxFormSave';
1768 YAHOO.util.Connect.setForm(theForm);
1769 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
1771 ajaxStatus.hideStatus();
1773 lastSubmitTime = lastSubmitTime-2000;
1778 // -- start sugarListView class
1779 // js functions used for ListView
1780 function sugarListView() {
1784 sugarListView.prototype.confirm_action = function(del) {
1786 return confirm( SUGAR.language.get('app_strings', 'NTC_DELETE_CONFIRMATION_NUM') + sugarListView.get_num_selected() + SUGAR.language.get('app_strings', 'NTC_DELETE_SELECTED_RECORDS'));
1789 return confirm( SUGAR.language.get('app_strings', 'NTC_UPDATE_CONFIRMATION_NUM') + sugarListView.get_num_selected() + SUGAR.language.get('app_strings', 'NTC_DELETE_SELECTED_RECORDS'));
1793 sugarListView.get_num_selected = function () {
1794 if(typeof document.MassUpdate != 'undefined') {
1795 the_form = document.MassUpdate;
1796 for(wp = 0; wp < the_form.elements.length; wp++) {
1797 if(typeof the_form.elements[wp].name != 'undefined' && the_form.elements[wp].name == 'selectCount[]') {
1798 return the_form.elements[wp].value;
1805 sugarListView.update_count = function(count, add) {
1806 if(typeof document.MassUpdate != 'undefined') {
1807 the_form = document.MassUpdate;
1808 for(wp = 0; wp < the_form.elements.length; wp++) {
1809 if(typeof the_form.elements[wp].name != 'undefined' && the_form.elements[wp].name == 'selectCount[]') {
1811 the_form.elements[wp].value = parseInt(the_form.elements[wp].value,10) + count;
1812 if (the_form.select_entire_list.value == 1 && the_form.show_plus.value) {
1813 the_form.elements[wp].value += '+';
1816 if (the_form.select_entire_list.value == 1 && the_form.show_plus.value) {
1817 the_form.elements[wp].value = count + '+';
1819 the_form.elements[wp].value = count;
1826 sugarListView.prototype.use_external_mail_client = function(no_record_txt, module) {
1827 selected_records = sugarListView.get_checks_count();
1828 if(selected_records <1) {
1829 alert(no_record_txt);
1833 if (document.MassUpdate.select_entire_list.value == 1) {
1834 if (totalCount > 10) {
1835 alert(totalCountError);
1840 else if (document.MassUpdate.massall.checked == true)
1844 sugarListView.get_checks();
1846 if(select) { // use selected items
1847 ids = document.MassUpdate.uid.value;
1849 else { // use current page
1850 inputs = document.MassUpdate.elements;
1852 for(i = 0; i < inputs.length; i++) {
1853 if(inputs[i].name == 'mass[]' && inputs[i].checked && typeof(inputs[i].value) != 'function') {
1854 ar.push(inputs[i].value);
1859 YAHOO.util.Connect.asyncRequest("POST", "index.php?", {
1860 success: this.use_external_mail_client_callback
1861 }, SUGAR.util.paramsToUrl({
1864 listViewExternalClient: 1,
1865 action_module: module,
1873 sugarListView.prototype.use_external_mail_client_callback = function(o)
1876 location.href = 'mailto:' + o.responseText;
1879 sugarListView.prototype.send_form_for_emails = function(select, currentModule, action, no_record_txt,action_module,totalCount, totalCountError) {
1880 if (document.MassUpdate.select_entire_list.value == 1) {
1881 if (totalCount > 10) {
1882 alert(totalCountError);
1887 else if (document.MassUpdate.massall.checked == true)
1892 sugarListView.get_checks();
1893 // create new form to post (can't access action property of MassUpdate form due to action input)
1894 var newForm = document.createElement('form');
1895 newForm.method = 'post';
1896 newForm.action = action;
1897 newForm.name = 'newForm';
1898 newForm.id = 'newForm';
1899 var uidTa = document.createElement('textarea');
1901 uidTa.style.display = 'none';
1903 if(select) { // use selected items
1904 uidTa.value = document.MassUpdate.uid.value;
1906 else { // use current page
1907 inputs = document.MassUpdate.elements;
1909 for(i = 0; i < inputs.length; i++) {
1910 if(inputs[i].name == 'mass[]' && inputs[i].checked && typeof(inputs[i].value) != 'function') {
1911 ar.push(inputs[i].value);
1914 uidTa.value = ar.join(',');
1917 if(uidTa.value == '') {
1918 alert(no_record_txt);
1922 var selectedArray = uidTa.value.split(",");
1923 if(selectedArray.length > 10) {
1924 alert(totalCountError);
1927 newForm.appendChild(uidTa);
1929 var moduleInput = document.createElement('input');
1930 moduleInput.name = 'module';
1931 moduleInput.type = 'hidden';
1932 moduleInput.value = currentModule;
1933 newForm.appendChild(moduleInput);
1935 var actionInput = document.createElement('input');
1936 actionInput.name = 'action';
1937 actionInput.type = 'hidden';
1938 actionInput.value = 'Compose';
1939 newForm.appendChild(actionInput);
1941 if (typeof action_module != 'undefined' && action_module!= '') {
1942 var actionModule = document.createElement('input');
1943 actionModule.name = 'action_module';
1944 actionModule.type = 'hidden';
1945 actionModule.value = action_module;
1946 newForm.appendChild(actionModule);
1948 //return_info must follow this pattern."&return_module=Accounts&return_action=index"
1949 if (typeof return_info!= 'undefined' && return_info != '') {
1950 var params= return_info.split('&');
1951 if (params.length > 0) {
1952 for (var i=0;i< params.length;i++) {
1953 if (params[i].length > 0) {
1954 var param_nv=params[i].split('=');
1955 if (param_nv.length==2){
1956 returnModule = document.createElement('input');
1957 returnModule.name = param_nv[0];
1958 returnModule.type = 'hidden';
1959 returnModule.value = param_nv[1];
1960 newForm.appendChild(returnModule);
1967 var isAjaxCall = document.createElement('input');
1968 isAjaxCall.name = 'ajaxCall';
1969 isAjaxCall.type = 'hidden';
1970 isAjaxCall.value = true;
1971 newForm.appendChild(isAjaxCall);
1973 var isListView = document.createElement('input');
1974 isListView.name = 'ListView';
1975 isListView.type = 'hidden';
1976 isListView.value = true;
1977 newForm.appendChild(isListView);
1979 var toPdf = document.createElement('input');
1980 toPdf.name = 'to_pdf';
1981 toPdf.type = 'hidden';
1983 newForm.appendChild(toPdf);
1985 //Grab the Quick Compose package for the listview
1986 YAHOO.util.Connect.setForm(newForm);
1989 success: function(o) {
1990 var resp = YAHOO.lang.JSON.parse(o.responseText);
1991 var quickComposePackage = new Object();
1992 quickComposePackage.composePackage = resp;
1993 quickComposePackage.fullComposeUrl = 'index.php?module=Emails&action=Compose&ListView=true' +
1994 '&uid=' + uidTa.value + '&action_module=' + action_module;
1996 SUGAR.quickCompose.init(quickComposePackage);
2000 YAHOO.util.Connect.asyncRequest('POST','index.php', callback,null);
2002 // awu Bug 18624: Fixing issue where a canceled Export and unselect of row will persist the uid field, clear the field
2003 document.MassUpdate.uid.value = '';
2008 sugarListView.prototype.send_form = function(select, currentModule, action, no_record_txt,action_module,return_info) {
2009 if (document.MassUpdate.select_entire_list.value == 1) {
2011 if(sugarListView.get_checks_count() < 1) {
2012 alert(no_record_txt);
2017 if ( action.indexOf('?') != -1 )
2018 href += '&module=' + currentModule;
2020 href += '?module=' + currentModule;
2023 href += return_info;
2024 var newForm = document.createElement('form');
2025 newForm.method = 'post';
2026 newForm.action = href;
2027 newForm.name = 'newForm';
2028 newForm.id = 'newForm';
2029 var postTa = document.createElement('textarea');
2030 postTa.name = 'current_post';
2031 postTa.value = document.MassUpdate.current_query_by_page.value;
2032 postTa.style.display = 'none';
2033 newForm.appendChild(postTa);
2034 document.MassUpdate.parentNode.appendChild(newForm);
2038 else if (document.MassUpdate.massall.checked == true)
2043 sugarListView.get_checks();
2044 // create new form to post (can't access action property of MassUpdate form due to action input)
2045 var newForm = document.createElement('form');
2046 newForm.method = 'post';
2047 newForm.action = action;
2048 newForm.name = 'newForm';
2049 newForm.id = 'newForm';
2050 var uidTa = document.createElement('textarea');
2052 uidTa.style.display = 'none';
2053 uidTa.value = document.MassUpdate.uid.value;
2055 if(uidTa.value == '') {
2056 alert(no_record_txt);
2060 newForm.appendChild(uidTa);
2062 var moduleInput = document.createElement('input');
2063 moduleInput.name = 'module';
2064 moduleInput.type = 'hidden';
2065 moduleInput.value = currentModule;
2066 newForm.appendChild(moduleInput);
2068 var actionInput = document.createElement('input');
2069 actionInput.name = 'action';
2070 actionInput.type = 'hidden';
2071 actionInput.value = 'index';
2072 newForm.appendChild(actionInput);
2074 if (typeof action_module != 'undefined' && action_module!= '') {
2075 var actionModule = document.createElement('input');
2076 actionModule.name = 'action_module';
2077 actionModule.type = 'hidden';
2078 actionModule.value = action_module;
2079 newForm.appendChild(actionModule);
2081 //return_info must follow this pattern."&return_module=Accounts&return_action=index"
2082 if (typeof return_info!= 'undefined' && return_info != '') {
2083 var params= return_info.split('&');
2084 if (params.length > 0) {
2085 for (var i=0;i< params.length;i++) {
2086 if (params[i].length > 0) {
2087 var param_nv=params[i].split('=');
2088 if (param_nv.length==2){
2089 returnModule = document.createElement('input');
2090 returnModule.name = param_nv[0];
2091 returnModule.type = 'hidden';
2092 returnModule.value = param_nv[1];
2093 newForm.appendChild(returnModule);
2100 document.MassUpdate.parentNode.appendChild(newForm);
2103 // awu Bug 18624: Fixing issue where a canceled Export and unselect of row will persist the uid field, clear the field
2104 document.MassUpdate.uid.value = '';
2108 //return a count of checked row.
2109 sugarListView.get_checks_count = function() {
2112 if(document.MassUpdate.uid.value != '') {
2113 oldUids = document.MassUpdate.uid.value.split(',');
2114 for(uid in oldUids) {
2115 if(typeof(oldUids[uid]) != 'function') {
2116 ar[oldUids[uid]] = 1;
2120 // build associated array of uids, associated array ensures uniqueness
2121 inputs = document.MassUpdate.elements;
2122 for(i = 0; i < inputs.length; i++) {
2123 if(inputs[i].name == 'mass[]') {
2124 ar[inputs[i].value] = (inputs[i].checked) ? 1 : 0; // 0 of it is unchecked
2128 // build regular array of uids
2131 if((typeof(ar[i]) != 'function') && ar[i] == 1) {
2139 // saves the checks on the current page into the uid textarea
2140 sugarListView.get_checks = function() {
2143 if(document.MassUpdate.uid.value != '') {
2144 oldUids = document.MassUpdate.uid.value.split(',');
2145 for(uid in oldUids) {
2146 if(typeof(oldUids[uid]) != 'function') {
2147 ar[oldUids[uid]] = 1;
2152 // build associated array of uids, associated array ensures uniqueness
2153 inputs = document.MassUpdate.elements;
2154 for(i = 0; i < inputs.length; i++) {
2155 if(inputs[i].name == 'mass[]') {
2156 ar[inputs[i].value] = (inputs[i].checked) ? 1 : 0; // 0 of it is unchecked
2160 // build regular array of uids
2163 if(typeof(ar[i]) != 'function' && ar[i] == 1) {
2168 document.MassUpdate.uid.value = uids.join(',');
2170 if(uids.length == 0) return false; // return false if no checks to get
2171 return true; // there are saved checks
2174 sugarListView.prototype.order_checks = function(order,orderBy,moduleString){
2175 checks = sugarListView.get_checks();
2176 eval('document.MassUpdate.' + moduleString + '.value = orderBy');
2177 document.MassUpdate.lvso.value = order;
2178 if(typeof document.MassUpdate.massupdate != 'undefined') {
2179 document.MassUpdate.massupdate.value = 'false';
2182 //we must first clear the action of massupdate, change it to index
2183 document.MassUpdate.action.value = document.MassUpdate.return_action.value;
2184 document.MassUpdate.return_module.value='';
2185 document.MassUpdate.return_action.value='';
2186 document.MassUpdate.submit();
2190 sugarListView.prototype.save_checks = function(offset, moduleString) {
2191 checks = sugarListView.get_checks();
2192 eval('document.MassUpdate.' + moduleString + '.value = offset');
2194 if(typeof document.MassUpdate.massupdate != 'undefined') {
2195 document.MassUpdate.massupdate.value = 'false';
2198 //we must first clear the action of massupdate, change it to index
2199 document.MassUpdate.action.value = document.MassUpdate.return_action.value;
2200 document.MassUpdate.return_module.value='';
2201 document.MassUpdate.return_action.value='';
2202 document.MassUpdate.submit();
2208 sugarListView.prototype.check_item = function(cb, form) {
2210 sugarListView.update_count(1, true);
2212 sugarListView.update_count(-1, true);
2213 if(typeof form != 'undefined' && form != null) {
2214 sugarListView.prototype.updateUid(cb, form);
2219 /**#28000, remove the unselect record id from MassUpdate.uid **/
2220 sugarListView.prototype.updateUid = function(cb , form){
2221 if(form.name == 'MassUpdate' && form.uid && form.uid.value && cb.value && form.uid.value.indexOf(cb.value) != -1){
2222 if(form.uid.value.indexOf(','+cb.value)!= -1){
2223 form.uid.value = form.uid.value.replace(','+cb.value , '');
2224 }else if(form.uid.value.indexOf(cb.value + ',')!= -1){
2225 form.uid.value = form.uid.value.replace(cb.value + ',' , '');
2226 }else if(form.uid.value.indexOf(cb.value)!= -1){
2227 form.uid.value = form.uid.value.replace(cb.value , '');
2232 sugarListView.prototype.check_entire_list = function(form, field, value, list_count) {
2233 // count number of items
2235 document.MassUpdate.massall.checked = true;
2236 document.MassUpdate.massall.disabled = true;
2238 for (i = 0; i < form.elements.length; i++) {
2239 if(form.elements[i].name == field && form.elements[i].disabled == false) {
2240 if(form.elements[i].checked != value) count++;
2241 form.elements[i].checked = value;
2242 form.elements[i].disabled = true;
2245 document.MassUpdate.select_entire_list.value = 1;
2247 sugarListView.update_count(list_count, false);
2248 //else sugarListView.update_count(-1 * count, true);
2251 sugarListView.prototype.check_all = function(form, field, value, pageTotal) {
2252 // count number of items
2254 document.MassUpdate.massall.checked = value;
2255 if (document.MassUpdate.select_entire_list &&
2256 document.MassUpdate.select_entire_list.value == 1)
2257 document.MassUpdate.massall.disabled = true;
2259 document.MassUpdate.massall.disabled = false;
2261 for (i = 0; i < form.elements.length; i++) {
2262 if(form.elements[i].name == field && !(form.elements[i].disabled == true && form.elements[i].checked == false)) {
2263 form.elements[i].disabled = false;
2265 if(form.elements[i].checked != value)
2267 form.elements[i].checked = value;
2269 sugarListView.prototype.updateUid(form.elements[i], form);
2274 sugarListView.update_count(pageTotal);
2276 sugarListView.update_count(count, true);
2278 sugarListView.update_count(-1 * count, true);
2280 sugarListView.check_all = sugarListView.prototype.check_all;
2281 sugarListView.confirm_action = sugarListView.prototype.confirm_action;
2283 sugarListView.prototype.check_boxes = function() {
2284 var inputsCount = 0;
2285 var checkedCount = 0;
2286 var existing_onload = window.onload;
2287 var theForm = document.MassUpdate;
2288 inputs_array = theForm.elements;
2290 if(typeof theForm.uid.value != 'undefined' && theForm.uid.value != "") {
2291 checked_items = theForm.uid.value.split(",");
2292 if (theForm.select_entire_list.value == 1)
2293 document.MassUpdate.massall.disabled = true;
2295 for(wp = 0 ; wp < inputs_array.length; wp++) {
2296 if(inputs_array[wp].name == "mass[]") {
2298 if (theForm.select_entire_list.value == 1) {
2299 inputs_array[wp].checked = true;
2300 inputs_array[wp].disabled = true;
2304 for(i in checked_items) {
2305 if(inputs_array[wp].value == checked_items[i]) {
2307 inputs_array[wp].checked = true;
2313 if (theForm.select_entire_list.value == 0)
2314 sugarListView.update_count(checked_items.length);
2316 sugarListView.update_count(0, true);
2320 for(wp = 0 ; wp < inputs_array.length; wp++) {
2321 if(inputs_array[wp].name == "mass[]") {
2322 inputs_array[wp].checked = false;
2323 inputs_array[wp].disabled = false;
2326 if (document.MassUpdate.massall) {
2327 document.MassUpdate.massall.checked = false;
2328 document.MassUpdate.massall.disabled = false;
2330 sugarListView.update_count(0)
2332 if(checkedCount > 0 && checkedCount == inputsCount)
2333 document.MassUpdate.massall.checked = true;
2339 * This function is used in Email Template Module's listview.
2340 * It will check whether the templates are used in Campaing->EmailMarketing.
2341 * If true, it will notify user.
2343 function check_used_email_templates() {
2344 var ids = document.MassUpdate.uid.value;
2346 success:function(r) {
2347 if(r.responseText != '') {
2348 if(!confirm(SUGAR.language.get('app_strings','NTC_TEMPLATES_IS_USED') + r.responseText)) {
2352 document.MassUpdate.submit();
2356 url = "index.php?module=EmailTemplates&action=CheckDeletable&from=ListView&to_pdf=1&records="+ids;
2357 YAHOO.util.Connect.asyncRequest('POST',url, call_back,null);
2361 sugarListView.prototype.send_mass_update = function(mode, no_record_txt, del) {
2362 formValid = check_form('MassUpdate');
2363 if(!formValid && !del) return false;
2366 if (document.MassUpdate.select_entire_list &&
2367 document.MassUpdate.select_entire_list.value == 1)
2372 var ar = new Array();
2376 for(wp = 0; wp < document.MassUpdate.elements.length; wp++) {
2377 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)+'$');
2378 //when the uid is already in document.MassUpdate.uid.value, we should not add it to ar.
2379 if(typeof document.MassUpdate.elements[wp].name != 'undefined'
2380 && document.MassUpdate.elements[wp].name == 'mass[]'
2381 && document.MassUpdate.elements[wp].checked
2382 && !reg_for_existing_uid.test(document.MassUpdate.uid.value)) {
2383 ar.push(document.MassUpdate.elements[wp].value);
2386 if(document.MassUpdate.uid.value != '') document.MassUpdate.uid.value += ',';
2387 document.MassUpdate.uid.value += ar.join(',');
2388 if(document.MassUpdate.uid.value == '') {
2389 alert(no_record_txt);
2392 if(typeof(current_admin_id)!='undefined' && document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'Users' && (document.MassUpdate.is_admin.value!='' || document.MassUpdate.status.value!='')) {
2393 var reg_for_current_admin_id = new RegExp('^'+current_admin_id+'[\s]*,|,[\s]*'+current_admin_id+'[\s]*,|,[\s]*'+current_admin_id+'$|^'+current_admin_id+'$');
2394 if(reg_for_current_admin_id.test(document.MassUpdate.uid.value)) {
2395 //if current user is admin, we should not allow massupdate the user_type and status of himself
2396 alert(SUGAR.language.get('Users','LBL_LAST_ADMIN_NOTICE'));
2402 var entireInput = document.createElement('input');
2403 entireInput.name = 'entire';
2404 entireInput.type = 'hidden';
2405 entireInput.value = 'index';
2406 document.MassUpdate.appendChild(entireInput);
2407 //confirm(no_record_txt);
2408 if(document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'Users' && (document.MassUpdate.is_admin.value!='' || document.MassUpdate.status.value!='')) {
2409 alert(SUGAR.language.get('Users','LBL_LAST_ADMIN_NOTICE'));
2415 if(!sugarListView.confirm_action(del))
2419 var deleteInput = document.createElement('input');
2420 deleteInput.name = 'Delete';
2421 deleteInput.type = 'hidden';
2422 deleteInput.value = true;
2423 document.MassUpdate.appendChild(deleteInput);
2424 if(document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'EmailTemplates') {
2425 check_used_email_templates();
2431 document.MassUpdate.submit();
2436 sugarListView.prototype.clear_all = function() {
2437 document.MassUpdate.uid.value = '';
2438 document.MassUpdate.select_entire_list.value = 0;
2439 sugarListView.check_all(document.MassUpdate, 'mass[]', false);
2440 document.MassUpdate.massall.checked = false;
2441 document.MassUpdate.massall.disabled = false;
2442 sugarListView.update_count(0);
2445 sListView = new sugarListView();
2446 // -- end sugarListView class
2448 // format and unformat numbers
2449 function unformatNumber(n, num_grp_sep, dec_sep) {
2450 var x=unformatNumberNoParse(n, num_grp_sep, dec_sep);
2453 return parseFloat(x);
2458 function unformatNumberNoParse(n, num_grp_sep, dec_sep) {
2459 if(typeof num_grp_sep == 'undefined' || typeof dec_sep == 'undefined') return n;
2460 n = n ? n.toString() : '';
2463 if(num_grp_sep != '')
2465 num_grp_sep_re = new RegExp('\\'+num_grp_sep, 'g');
2466 n = n.replace(num_grp_sep_re, '');
2469 n = n.replace(dec_sep, '.');
2471 if(typeof CurrencySymbols != 'undefined') {
2472 // Need to strip out the currency symbols from the start.
2473 for ( var idx in CurrencySymbols ) {
2474 n = n.replace(CurrencySymbols[idx], '');
2482 // round parameter can be negative for decimal, precision has to be postive
2483 function formatNumber(n, num_grp_sep, dec_sep, round, precision) {
2484 if(typeof num_grp_sep == 'undefined' || typeof dec_sep == 'undefined') return n;
2485 n = n ? n.toString() : '';
2486 if(n.split) n = n.split('.');
2489 if(n.length > 2) return n.join('.'); // that's not a num!
2491 if(typeof round != 'undefined') {
2492 if(round > 0 && n.length > 1) { // round to decimal
2493 n[1] = parseFloat('0.' + n[1]);
2494 n[1] = Math.round(n[1] * Math.pow(10, round)) / Math.pow(10, round);
2495 n[1] = n[1].toString().split('.')[1];
2497 if(round <= 0) { // round to whole number
2498 n[0] = Math.round(parseInt(n[0],10) * Math.pow(10, round)) / Math.pow(10, round);
2503 if(typeof precision != 'undefined' && precision >= 0) {
2504 if(n.length > 1 && typeof n[1] != 'undefined') n[1] = n[1].substring(0, precision); // cut off precision
2506 if(n[1].length < precision) {
2507 for(var wp = n[1].length; wp < precision; wp++) n[1] += '0';
2511 regex = /(\d+)(\d{3})/;
2512 while(num_grp_sep != '' && regex.test(n[0])) n[0] = n[0].toString().replace(regex, '$1' + num_grp_sep + '$2');
2513 return n[0] + (n.length > 1 && n[1] != '' ? dec_sep + n[1] : '');
2516 // --- begin ajax status class
2517 SUGAR.ajaxStatusClass = function() {};
2518 SUGAR.ajaxStatusClass.prototype.statusDiv = null;
2519 SUGAR.ajaxStatusClass.prototype.oldOnScroll = null;
2520 SUGAR.ajaxStatusClass.prototype.shown = false; // state of the status window
2522 // reposition the status div, top and centered
2523 SUGAR.ajaxStatusClass.prototype.positionStatus = function() {
2524 this.statusDiv.style.top = document.body.scrollTop + 8 + 'px';
2525 statusDivRegion = YAHOO.util.Dom.getRegion(this.statusDiv);
2526 statusDivWidth = statusDivRegion.right - statusDivRegion.left;
2527 this.statusDiv.style.left = YAHOO.util.Dom.getViewportWidth() / 2 - statusDivWidth / 2 + 'px';
2530 // private func, create the status div
2531 SUGAR.ajaxStatusClass.prototype.createStatus = function(text) {
2532 statusDiv = document.createElement('div');
2533 statusDiv.className = 'dataLabel';
2534 statusDiv.style.background = '#ffffff';
2535 statusDiv.style.color = '#c60c30';
2536 statusDiv.style.position = 'absolute';
2537 statusDiv.style.opacity = .8;
2538 statusDiv.style.filter = 'alpha(opacity=80)';
2539 statusDiv.id = 'ajaxStatusDiv';
2540 document.body.appendChild(statusDiv);
2541 this.statusDiv = document.getElementById('ajaxStatusDiv');
2544 // public - show the status div with text
2545 SUGAR.ajaxStatusClass.prototype.showStatus = function(text) {
2546 if(!this.statusDiv) {
2547 this.createStatus(text);
2550 this.statusDiv.style.display = '';
2552 this.statusDiv.style.zIndex = 20;
2553 this.statusDiv.innerHTML = ' <b>' + text + '</b> ';
2554 this.positionStatus();
2557 this.statusDiv.style.display = '';
2558 if(window.onscroll) this.oldOnScroll = window.onscroll; // save onScroll
2559 window.onscroll = this.positionStatus;
2564 SUGAR.ajaxStatusClass.prototype.hideStatus = function(text) {
2565 if(!this.shown) return;
2567 if(this.oldOnScroll) window.onscroll = this.oldOnScroll;
2568 else window.onscroll = '';
2569 this.statusDiv.style.display = 'none';
2572 SUGAR.ajaxStatusClass.prototype.flashStatus = function(text, time){
2573 this.showStatus(text);
2574 window.setTimeout('ajaxStatus.hideStatus();', time);
2578 var ajaxStatus = new SUGAR.ajaxStatusClass();
2579 // --- end ajax status class
2582 * Unified Search Advanced - for global search
2584 SUGAR.unifiedSearchAdvanced = function() {
2594 SUGAR.unifiedSearchAdvanced.usa_div = document.getElementById('unified_search_advanced_div');
2595 SUGAR.unifiedSearchAdvanced.usa_img = document.getElementById('unified_search_advanced_img');
2597 if(!SUGAR.unifiedSearchAdvanced.usa_div || !SUGAR.unifiedSearchAdvanced.usa_img) return;
2598 var attributes = { height: { to: 300 } };
2599 SUGAR.unifiedSearchAdvanced.anim_open = new YAHOO.util.Anim('unified_search_advanced_div', attributes );
2600 SUGAR.unifiedSearchAdvanced.anim_open.duration = 0.75;
2601 SUGAR.unifiedSearchAdvanced.anim_close = new YAHOO.util.Anim('unified_search_advanced_div', { height: {to: 0} } );
2602 SUGAR.unifiedSearchAdvanced.anim_close.duration = 0.75;
2603 //SUGAR.unifiedSearchAdvanced.anim_close.onComplete.subscribe(function() {SUGAR.unifiedSearchAdvanced.usa_div.style.display = 'none'});
2605 SUGAR.unifiedSearchAdvanced.usa_img._x = YAHOO.util.Dom.getX(SUGAR.unifiedSearchAdvanced.usa_img);
2606 SUGAR.unifiedSearchAdvanced.usa_img._y = YAHOO.util.Dom.getY(SUGAR.unifiedSearchAdvanced.usa_img);
2609 SUGAR.unifiedSearchAdvanced.usa_open = false;
2610 SUGAR.unifiedSearchAdvanced.usa_content = null;
2612 YAHOO.util.Event.addListener('unified_search_advanced_img', 'click', SUGAR.unifiedSearchAdvanced.get_content);
2615 get_content: function(e)
2617 query_string = trim(document.getElementById('query_string').value);
2618 if(query_string != '')
2620 window.location.href = 'index.php?module=Home&action=UnifiedSearch&query_string=' + query_string;
2622 window.location.href = 'index.php?module=Home&action=UnifiedSearch&form_only=true';
2626 animate: function(data) {
2627 ajaxStatus.hideStatus();
2630 SUGAR.unifiedSearchAdvanced.usa_content = data.responseText;
2631 SUGAR.unifiedSearchAdvanced.usa_div.innerHTML = SUGAR.unifiedSearchAdvanced.usa_content;
2633 if(SUGAR.unifiedSearchAdvanced.usa_open) {
2634 document.UnifiedSearch.advanced.value = 'false';
2635 SUGAR.unifiedSearchAdvanced.anim_close.animate();
2638 document.UnifiedSearch.advanced.value = 'true';
2639 SUGAR.unifiedSearchAdvanced.usa_div.style.display = '';
2640 YAHOO.util.Dom.setX(SUGAR.unifiedSearchAdvanced.usa_div, SUGAR.unifiedSearchAdvanced.usa_img._x - 90);
2641 YAHOO.util.Dom.setY(SUGAR.unifiedSearchAdvanced.usa_div, SUGAR.unifiedSearchAdvanced.usa_img._y + 15);
2642 SUGAR.unifiedSearchAdvanced.anim_open.animate();
2644 SUGAR.unifiedSearchAdvanced.usa_open = !SUGAR.unifiedSearchAdvanced.usa_open;
2649 checkUsaAdvanced: function() {
2650 if(document.UnifiedSearch.advanced.value == 'true') {
2651 document.UnifiedSearchAdvanced.query_string.value = document.UnifiedSearch.query_string.value;
2652 document.UnifiedSearchAdvanced.submit();
2659 if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.unifiedSearchAdvanced.init);
2664 * Toggles the header
2666 toggleHeader : function() {
2667 var h = document.getElementById('header');
2671 if(h.style.display == 'none') {
2672 h.style.display = '';
2674 h.style.display = 'none';
2678 alert(SUGAR.language.get("app_strings", "ERR_NO_HEADER_ID"));
2685 * General Sugar Utils
2687 SUGAR.util = function () {
2688 var additionalDetailsCache;
2689 var additionalDetailsCalls;
2690 var additionalDetailsRpcCall;
2693 getAndRemove : function (el) {
2694 if (YAHOO && YAHOO.util && YAHOO.util.Dom)
2695 el = YAHOO.util.Dom.get(el);
2696 else if (typeof (el) == "string")
2697 el = document.getElementById(el);
2698 if (el && el.parentNode)
2699 el.parentNode.removeChild(el);
2703 paramsToUrl : function (params) {
2706 url += i + "=" + params[i] + "&";
2710 evalScript:function(text){
2712 var waitUntilLoaded = function(){
2713 SUGAR.evalScript_waitCount--;
2714 if (SUGAR.evalScript_waitCount == 0) {
2715 var headElem = document.getElementsByTagName('head')[0];
2716 for ( var i = 0; i < SUGAR.evalScript_evalElem.length; i++) {
2717 var tmpElem = document.createElement('script');
2718 tmpElem.type = 'text/javascript';
2719 tmpElem.text = SUGAR.evalScript_evalElem[i];
2720 headElem.appendChild(tmpElem);
2725 var tmpElem = document.createElement('div');
2726 tmpElem.innerHTML = text;
2727 var results = tmpElem.getElementsByTagName('script');
2728 if (results == null) {
2729 // No scripts found, bail out
2733 var headElem = document.getElementsByTagName('head')[0];
2735 SUGAR.evalScript_waitCount = 0;
2736 SUGAR.evalScript_evalElem = new Array();
2737 for (var i = 0; i < results.length; i++) {
2738 if (typeof(results[i]) != 'object') {
2741 tmpElem = document.createElement('script');
2742 tmpElem.type = 'text/javascript';
2743 if (results[i].src != null && results[i].src != '') {
2744 tmpElem.src = results[i].src;
2746 // Need to defer execution of these scripts until the
2747 // required javascript files are fully loaded
2748 SUGAR.evalScript_evalElem[SUGAR.evalScript_evalElem.length] = results[i].text;
2751 tmpElem.addEventListener('load', waitUntilLoaded);
2752 SUGAR.evalScript_waitCount++;
2753 headElem.appendChild(tmpElem);
2755 // Add some code to handle pages without any external scripts
2756 SUGAR.evalScript_waitCount++;
2759 // Don't try and process things the IE way
2763 var objRegex = /<\s*script([^>]*)>((.|\s|\v|\0)*?)<\s*\/script\s*>/igm;
2765 var result = objRegex.exec(text);
2766 while(result && result.index > lastIndex){
2767 lastIndex = result.index
2769 var script = document.createElement('script');
2770 script.type= 'text/javascript';
2771 if(result[1].indexOf("src=") > -1){
2772 var srcRegex = /.*src=['"]([a-zA-Z0-9_\&\/\.\?=:]*)['"].*/igm;
2773 var srcResult = result[1].replace(srcRegex, '$1');
2774 script.src = srcResult;
2776 script.text = result[2];
2778 document.body.appendChild(script);
2781 if(typeof(console) != "undefined" && typeof(console.log) == "function")
2783 console.log("error adding script");
2785 console.log(result);
2788 result = objRegex.exec(text);
2792 * Gets the sidebar object
2793 * @return object pointer to the sidebar element
2795 getLeftColObj: function() {
2796 leftColObj = document.getElementById('leftCol');
2797 while(leftColObj.nodeName != 'TABLE') {
2798 leftColObj = leftColObj.firstChild;
2800 leftColTable = leftColObj;
2801 leftColTd = leftColTable.getElementsByTagName('td')[0];
2802 leftColTdRegion = YAHOO.util.Dom.getRegion(leftColTd);
2803 leftColTd.style.width = (leftColTdRegion.right - leftColTdRegion.left) + 'px';
2808 * Fills the shortcut menu placeholders w/ actual content
2809 * Call this on load event
2811 * @param shortcutContent Array array of content to fill in
2813 fillShortcuts: function(e, shortcutContent) {
2816 // don't do this if leftCol isn't available
2817 if (document.getElementById('leftCol') == undefined) { return; }
2819 spans = document.getElementById('leftCol').getElementsByTagName('span');
2820 hideCol = document.getElementById('HideMenu').getElementsByTagName('span');
2821 w = spans.length + 1;
2823 spans[w] = hideCol[i];
2826 for(je in shortcutContent) {
2828 if(typeof spans[wp].innerHTML != 'undefined' && spans[wp].innerHTML == ('wp_shortcut_fill_' + je)) {
2829 if(typeof spans[wp].parentNode.parentNode == 'object') {
2830 if(typeof spans[wp].parentNode.parentNode.onclick != 'undefined') {
2831 spans[wp].parentNode.parentNode.onclick = null;
2833 // If the wp_shortcut span is contained by an A tag, replace the A with a DIV.
2834 if(spans[wp].parentNode.tagName == 'A' && !isIE) {
2835 var newDiv = document.createElement('DIV');
2836 var parentAnchor = spans[wp].parentNode;
2838 spans[wp].parentNode.parentNode.style.display = 'none';
2840 // Copy styles over to the new container div
2841 if(window.getComputedStyle) {
2842 var parentStyle = window.getComputedStyle(parentAnchor, '');
2843 for(var styleName in parentStyle) {
2844 if(typeof parentStyle[styleName] != 'function'
2845 && styleName != 'display'
2846 && styleName != 'borderWidth'
2847 && styleName != 'visibility') {
2849 newDiv.style[styleName] = parentStyle[styleName];
2851 // Catches .length and .parentRule, and others
2857 // Replace the A with the DIV
2858 newDiv.appendChild(spans[wp]);
2859 parentAnchor.parentNode.replaceChild(newDiv, parentAnchor);
2861 spans[wp].parentNode.parentNode.style.display = '';
2864 spans[wp].innerHTML = shortcutContent[je]; // fill w/ content
2865 if(spans[wp].style) spans[wp].style.display = '';
2871 * Make an AJAX request.
2873 * @param url string resource to load
2874 * @param theDiv string id of element to insert loaded data into
2875 * @param postForm string if set, a POST request will be made to resource specified by url using the form named by postForm
2876 * @param callback string name of function to invoke after HTTP response is recieved
2877 * @param callbackParam any parameter to pass to callback when invoked
2878 * @param appendMode bool if true, HTTP response will be appended to the contents of theDiv, or else contents will be overriten.
2880 retrieveAndFill: function(url, theDiv, postForm, callback, callbackParam, appendMode) {
2881 if(typeof theDiv == 'string') {
2883 theDiv = document.getElementById(theDiv);
2890 var success = function(data) {
2891 if (typeof theDiv != 'undefined' && theDiv != null)
2894 if (typeof appendMode != 'undefined' && appendMode)
2896 theDiv.innerHTML += data.responseText;
2900 theDiv.innerHTML = data.responseText;
2907 if (typeof callback != 'undefined' && callback != null) callback(callbackParam);
2910 if(typeof postForm == 'undefined' || postForm == null) {
2911 var cObj = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
2914 YAHOO.util.Connect.setForm(postForm);
2915 var cObj = YAHOO.util.Connect.asyncRequest('POST', url, {success: success, failure: success});
2918 checkMaxLength: function() { // modified from http://www.quirksmode.org/dom/maxlength.html
2919 var maxLength = this.getAttribute('maxlength');
2920 var currentLength = this.value.length;
2921 if (currentLength > maxLength) {
2922 this.value = this.value.substring(0, maxLength);
2927 * Adds maxlength attribute to textareas
2929 setMaxLength: function() { // modified from http://www.quirksmode.org/dom/maxlength.html
2930 var x = document.getElementsByTagName('textarea');
2931 for (var i=0;i<x.length;i++) {
2932 if (x[i].getAttribute('maxlength')) {
2933 x[i].onkeyup = x[i].onchange = SUGAR.util.checkMaxLength;
2940 * Retrieves additional details dynamically
2942 getAdditionalDetails: function(bean, id, spanId) {
2944 oReturn = function(body, caption, width, theme) {
2945 var _refx = 25-width;
2946 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);
2949 success = function(data) {
2950 eval(data.responseText);
2952 SUGAR.util.additionalDetailsCache[spanId] = new Array();
2953 SUGAR.util.additionalDetailsCache[spanId]['body'] = result['body'];
2954 SUGAR.util.additionalDetailsCache[spanId]['caption'] = result['caption'];
2955 SUGAR.util.additionalDetailsCache[spanId]['width'] = result['width'];
2956 SUGAR.util.additionalDetailsCache[spanId]['theme'] = result['theme'];
2957 ajaxStatus.hideStatus();
2958 return oReturn(SUGAR.util.additionalDetailsCache[spanId]['body'], SUGAR.util.additionalDetailsCache[spanId]['caption'], SUGAR.util.additionalDetailsCache[spanId]['width'], SUGAR.util.additionalDetailsCache[spanId]['theme']);
2961 if(typeof SUGAR.util.additionalDetailsCache[spanId] != 'undefined')
2962 return oReturn(SUGAR.util.additionalDetailsCache[spanId]['body'], SUGAR.util.additionalDetailsCache[spanId]['caption'], SUGAR.util.additionalDetailsCache[spanId]['width'], SUGAR.util.additionalDetailsCache[spanId]['theme']);
2964 if(typeof SUGAR.util.additionalDetailsCalls[spanId] != 'undefined') // call already in progress
2966 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_LOADING'));
2967 url = 'index.php?to_pdf=1&module=Home&action=AdditionalDetailsRetrieve&bean=' + bean + '&id=' + id;
2968 SUGAR.util.additionalDetailsCalls[spanId] = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
2972 SUGAR.util.additionalDetailsRpcCall = window.setTimeout('go()', 250);
2974 clearAdditionalDetailsCall: function() {
2975 if(typeof SUGAR.util.additionalDetailsRpcCall == 'number') window.clearTimeout(SUGAR.util.additionalDetailsRpcCall);
2978 * A function that extends functionality from parent to child.
2980 extend : function(subc, superc, overrides) {
2981 subc.prototype = new superc; // set the superclass
2984 for (var i in overrides) subc.prototype[i] = overrides[i];
2987 hrefURL : function(url) {
2989 // IE needs special treatment since otherwise it would not pass Referer
2990 var trampoline = document.createElement('a');
2991 trampoline.href = url;
2992 document.body.appendChild(trampoline);
2994 document.body.removeChild(trampoline);
2996 document.location.href = url;
3000 openWindow : function(URL, windowName, windowFeatures) {
3002 // IE needs special treatment since otherwise it would not pass Referer
3003 win = window.open('', windowName, windowFeatures);
3004 var trampoline = document.createElement('a');
3005 trampoline.href = URL;
3006 trampoline.target = windowName;
3007 document.body.appendChild(trampoline);
3009 document.body.removeChild(trampoline);
3011 win = window.open(URL, windowName, windowFeatures);
3015 //Reset the scroll on the window
3020 //Based on YUI onAvailible, but will use any boolean function instead of an ID
3021 doWhen : function(condition, fn, params, scope)
3023 this._doWhenStack.push({
3027 overrideContext: scope
3030 this._doWhenretryCount = 50;
3031 this._startDoWhenInterval();
3034 _startDoWhenInterval : function(){
3035 if (!this._doWhenInterval) {
3036 this._doWhenInterval = YAHOO.lang.later(50, this, this._doWhenCheck, null, true);
3040 _doWhenInterval : false,
3041 _doWhenCheck : function() {
3042 if (this._doWhenStack.length === 0) {
3043 this._doWhenretryCount = 0;
3044 if (this._doWhenInterval) {
3045 // clearInterval(this._interval);
3046 this._doWhenInterval.cancel();
3047 this._doWhenInterval = null;
3052 if (this._doWhenLocked) {
3057 // Hold off if DOMReady has not fired and check current
3058 // readyState to protect against the IE operation aborted
3060 if (!YAHOO.util.Event.DOMReady) {
3061 this._startDoWhenInterval();
3066 this._doWhenLocked = true;
3069 // keep trying until after the page is loaded. We need to
3070 // check the page load state prior to trying to bind the
3071 // elements so that we can be certain all elements have been
3072 // tested appropriately
3073 var tryAgain = YAHOO.util.Event.DOMReady;
3075 tryAgain = (this._doWhenretryCount > 0 && this._doWhenStack.length > 0);
3081 var executeItem = function (context, item) {
3082 if (item.overrideContext) {
3083 if (item.overrideContext === true) {
3086 context = item.overrideContext;
3089 item.fn.call(context, item.obj);
3092 var i, len, item, test;
3094 // onAvailable onContentReady
3095 for (i=0, len=this._doWhenStack.length; i<len; i=i+1) {
3096 item = this._doWhenStack[i];
3099 if ((typeof(test) == "string" && eval(test)) || (typeof(test) == "function" && test())) {
3100 executeItem(this, item);
3101 this._doWhenStack[i] = null;
3104 notAvail.push(item);
3109 this._doWhenretryCount--;
3112 for (i=this._doWhenStack.length-1; i>-1; i--) {
3113 item = this._doWhenStack[i];
3114 if (!item || !item.check) {
3115 this._doWhenStack.splice(i, 1);
3118 this._startDoWhenInterval();
3120 if (this._doWhenInterval) {
3121 // clearInterval(this._interval);
3122 this._doWhenInterval.cancel();
3123 this._doWhenInterval = null;
3126 this._doWhenLocked = false;
3130 SUGAR.util.additionalDetailsCache = new Array();
3131 SUGAR.util.additionalDetailsCalls = new Array();
3132 if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.util.setMaxLength); // allow textareas to obey maxlength attrib
3134 SUGAR.savedViews = function() {
3135 var selectedOrderBy;
3136 var selectedSortOrder;
3139 var columnsMeta; // meta data for the display columns
3142 setChooser: function() {
3144 var displayColumnsDef = new Array();
3145 var hideTabsDef = new Array();
3147 var left_td = document.getElementById('display_tabs_td');
3148 if(typeof left_td == 'undefined' || left_td == null) return; // abort!
3149 var right_td = document.getElementById('hide_tabs_td');
3151 var displayTabs = left_td.getElementsByTagName('select')[0];
3152 var hideTabs = right_td.getElementsByTagName('select')[0];
3154 for(i = 0; i < displayTabs.options.length; i++) {
3155 displayColumnsDef.push(displayTabs.options[i].value);
3158 if(typeof hideTabs != 'undefined') {
3159 for(i = 0; i < hideTabs.options.length; i++) {
3160 hideTabsDef.push(hideTabs.options[i].value);
3163 if (!SUGAR.savedViews.clearColumns)
3164 document.getElementById('displayColumnsDef').value = displayColumnsDef.join('|');
3165 document.getElementById('hideTabsDef').value = hideTabsDef.join('|');
3168 select: function(saved_search_select) {
3169 for(var wp = 0; wp < document.search_form.saved_search_select.options.length; wp++) {
3170 if(typeof document.search_form.saved_search_select.options[wp].value != 'undefined' &&
3171 document.search_form.saved_search_select.options[wp].value == saved_search_select) {
3172 document.search_form.saved_search_select.selectedIndex = wp;
3173 document.search_form.ss_delete.style.display = '';
3174 document.search_form.ss_update.style.display = '';
3178 saved_search_action: function(action, delete_lang) {
3179 if(action == 'delete') {
3180 if(!confirm(delete_lang)) return;
3182 if(action == 'save') {
3183 if(document.search_form.saved_search_name.value.replace(/^\s*|\s*$/g, '') == '') {
3184 alert(SUGAR.language.get('app_strings', 'LBL_SAVED_SEARCH_ERROR'));
3189 // This check is needed for the Activities module (Calls/Meetings/Tasks).
3190 if (document.search_form.saved_search_action)
3192 document.search_form.saved_search_action.value = action;
3193 document.search_form.search_module.value = document.search_form.module.value;
3194 document.search_form.module.value = 'SavedSearch';
3195 // Bug 31922 - Make sure to specify that we want to hit the index view here of
3196 // the SavedSearch module, since the ListView doesn't have the logic to save the
3197 // search and redirect back
3198 document.search_form.action.value = 'index';
3200 SUGAR.ajaxUI.submitForm(document.search_form);
3202 shortcut_select: function(selectBox, module) {
3204 selecturl = 'index.php?module=SavedSearch&search_module=' + module + '&action=index&saved_search_select=' + selectBox.options[selectBox.selectedIndex].value
3205 //add searchFormTab to url if it is available. This determines what tab to render
3206 if(typeof(document.getElementById('searchFormTab'))!='undefined'){
3207 selecturl = selecturl + '&searchFormTab=' + document.search_form.searchFormTab.value;
3209 //add showSSDIV to url if it is available. This determines whether saved search sub form should
3210 //be rendered open or not
3211 if(document.getElementById('showSSDIV') && typeof(document.getElementById('showSSDIV') !='undefined')){
3212 selecturl = selecturl + '&showSSDIV='+document.getElementById('showSSDIV').value;
3214 //use created url to navigate
3215 document.location.href = selecturl;
3217 handleForm: function() {
3218 SUGAR.tabChooser.movementCallback = function(left_side, right_side) {
3219 while(document.getElementById('orderBySelect').childNodes.length != 0) { // clear out order by options
3220 document.getElementById('orderBySelect').removeChild(document.getElementById('orderBySelect').lastChild);
3223 var selectedIndex = 0;
3224 var nodeCount = -1; // need this because the counter i also includes "undefined" nodes
3225 // which was breaking Calls and Meetings
3227 for(i in left_side.childNodes) { // fill in order by options
3228 if(typeof left_side.childNodes[i].nodeName != 'undefined' &&
3229 left_side.childNodes[i].nodeName.toLowerCase() == 'option' &&
3230 typeof SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value] != 'undefined' && // check if column is sortable
3231 typeof SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value]['sortable'] == 'undefined' &&
3232 SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value]['sortable'] != false) {
3234 optionNode = document.createElement('option');
3235 optionNode.value = left_side.childNodes[i].value;
3236 optionNode.innerHTML = left_side.childNodes[i].innerHTML;
3237 document.getElementById('orderBySelect').appendChild(optionNode);
3238 if(optionNode.value == SUGAR.savedViews.selectedOrderBy)
3239 selectedIndex = nodeCount;
3242 // Firefox needs this to be set after all the option nodes are created.
3243 document.getElementById('orderBySelect').selectedIndex = selectedIndex;
3245 SUGAR.tabChooser.movementCallback(document.getElementById('display_tabs_td').getElementsByTagName('select')[0]);
3247 // This check is needed for the Activities module (Calls/Meetings/Tasks).
3248 if (document.search_form.orderBy)
3249 document.search_form.orderBy.options.value = SUGAR.savedViews.selectedOrderBy;
3252 if(SUGAR.savedViews.selectedSortOrder == 'DESC') document.getElementById('sort_order_desc_radio').checked = true;
3253 else document.getElementById('sort_order_asc_radio').checked = true;
3258 SUGAR.searchForm = function() {
3261 // searchForm tab selector util
3262 searchFormSelect: function(view, previousView) {
3263 var module = view.split('|')[0];
3264 var theView = view.split('|')[1];
3266 var handleDisplay = function() { // hide other divs
3267 document.search_form.searchFormTab.value = theView;
3268 patt = module+"(.*)SearchForm$";
3269 divId=document.search_form.getElementsByTagName('div');
3270 // Hide all the search forms and retrive the name of the previous search tab (useful for the first load because previousView is empty)
3271 for (i=0;i<divId.length;i++){
3272 if(divId[i].id.match(module)==module){
3273 if(divId[i].id.match('SearchForm')=='SearchForm'){
3274 if(document.getElementById(divId[i].id).style.display == ''){
3275 previousTab=divId[i].id.match(patt)[1];
3277 document.getElementById(divId[i].id).style.display = 'none';
3281 // show the good search form.
3282 document.getElementById(module + theView + 'SearchForm').style.display = '';
3283 //if its not the first tab show there is a previous tab.
3285 thepreviousView=previousView.split('|')[1];
3288 thepreviousView=previousTab;
3290 thepreviousView=thepreviousView.replace(/_search/, "");
3291 // Process to retrieve the completed field from one tab to an other.
3292 for(num in document.search_form.elements) {
3293 if(document.search_form.elements[num]) {
3294 el = document.search_form.elements[num];
3295 pattern="^(.*)_"+thepreviousView+"$";
3296 if(typeof el.type != 'undefined' && typeof el.name != 'undefined' && el.name.match(pattern)) {
3297 advanced_input_name = el.name.match(pattern)[1]; // strip
3298 advanced_input_name = advanced_input_name+"_"+theView.replace(/_search/, "");
3299 if(typeof document.search_form[advanced_input_name] != 'undefined') // if advanced input of same name exists
3300 SUGAR.searchForm.copyElement(advanced_input_name, el);
3306 // if tab is not cached
3307 if(document.getElementById(module + theView + 'SearchForm').innerHTML == '') {
3308 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_LOADING'));
3309 var success = function(data) {
3310 document.getElementById(module + theView + 'SearchForm').innerHTML = data.responseText;
3312 SUGAR.util.evalScript(data.responseText);
3313 // pass script variables to global scope
3314 if(theView == 'saved_views') {
3315 if(typeof columnsMeta != 'undefined') SUGAR.savedViews.columnsMeta = columnsMeta;
3316 if(typeof selectedOrderBy != 'undefined') SUGAR.savedViews.selectedOrderBy = selectedOrderBy;
3317 if(typeof selectedSortOrder != 'undefined') SUGAR.savedViews.selectedSortOrder = selectedSortOrder;
3322 ajaxStatus.hideStatus();
3324 url = 'index.php?module=' + module + '&action=index&search_form_only=true&to_pdf=true&search_form_view=' + theView;
3326 //check to see if tpl has been specified. If so then pass location through url string
3328 if(document.getElementById('search_tpl') !=null && typeof(document.getElementById('search_tpl')) != 'undefined'){
3329 tpl = document.getElementById('search_tpl').value;
3330 if(tpl != ''){url += '&search_tpl='+tpl;}
3333 if(theView == 'saved_views') // handle the tab chooser
3334 url += '&displayColumns=' + SUGAR.savedViews.displayColumns + '&hideTabs=' + SUGAR.savedViews.hideTabs + '&orderBy=' + SUGAR.savedViews.selectedOrderBy + '&sortOrder=' + SUGAR.savedViews.selectedSortOrder;
3336 var cObj = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
3338 else { // that form already retrieved
3343 // copies one input to another
3344 copyElement: function(inputName, copyFromElement) {
3345 switch(copyFromElement.type) {
3348 document.search_form[inputName].value = copyFromElement.value;
3352 // This function is here to clear the form, instead of "resubmitting it
3353 clear_form: function(form, skipElementNames) {
3354 var elemList = form.elements;
3358 for( var i = 0; i < elemList.length ; i++ ) {
3360 if ( typeof(elem.type) == 'undefined' ) {
3364 if ( typeof(elem.type) != 'undefined' && typeof(skipElementNames) != 'undefined'
3365 && SUGAR.util.arrayIndexOf(skipElementNames, elem.name) != -1 )
3370 elemType = elem.type.toLowerCase();
3372 if ( elemType == 'text' || elemType == 'textarea' || elemType == 'password' ) {
3375 else if ( elemType == 'select' || elemType == 'select-one' || elemType == 'select-multiple' ) {
3376 // We have, what I hope, is a select box, time to unselect all options
3377 var optionList = elem.options;
3378 for ( var ii = 0 ; ii < optionList.length ; ii++ ) {
3379 optionList[ii].selected = false;
3382 else if ( elemType == 'radio' || elemType == 'checkbox' ) {
3383 elem.checked = false;
3384 elem.selected = false;
3386 else if ( elemType == 'hidden' ) {
3387 // We only want to reset the hidden values that link to the select boxes.
3388 if ( ( elem.name.length > 3 && elem.name.substring(elem.name.length-3) == '_id' )
3389 || ((elem.name.length > 9) && (elem.name.substring(elem.name.length - 9) == '_id_basic'))
3390 || ( elem.name.length > 12 && elem.name.substring(elem.name.length-12) == '_id_advanced' ) ) {
3395 SUGAR.savedViews.clearColumns = true;
3399 // Code for the column/tab chooser used on homepage and in admin section
3400 SUGAR.tabChooser = function () {
3401 var object_refs = new Array();
3403 /* Describe certain transfers as invalid */
3406 movementCallback: function(left_side, right_side) {},
3407 orderCallback: function(left_side, right_side) {},
3409 freezeOptions: function(left_name, right_name, target) {
3410 if(!SUGAR.tabChooser.frozenOptions) { SUGAR.tabChooser.frozenOptions = []; }
3411 if(!SUGAR.tabChooser.frozenOptions[left_name]) { SUGAR.tabChooser.frozenOptions[left_name] = []; }
3412 if(!SUGAR.tabChooser.frozenOptions[left_name][right_name]) { SUGAR.tabChooser.frozenOptions[left_name][right_name] = []; }
3413 if(typeof target == 'array') {
3414 for(var i in target) {
3415 SUGAR.tabChooser.frozenOptions[left_name][right_name][target[i]] = true;
3418 SUGAR.tabChooser.frozenOptions[left_name][right_name][target] = true;
3422 buildSelectHTML: function(info) {
3423 var text = "<select";
3425 if(typeof (info['select']['size']) != 'undefined') {
3426 text +=" size=\""+ info['select']['size'] +"\"";
3429 if(typeof (info['select']['name']) != 'undefined') {
3430 text +=" name=\""+ info['select']['name'] +"\"";
3433 if(typeof (info['select']['style']) != 'undefined') {
3434 text +=" style=\""+ info['select']['style'] +"\"";
3437 if(typeof (info['select']['onchange']) != 'undefined') {
3438 text +=" onChange=\""+ info['select']['onchange'] +"\"";
3441 if(typeof (info['select']['multiple']) != 'undefined') {
3446 for(i=0; i<info['options'].length;i++) {
3447 option = info['options'][i];
3448 text += "<option value=\""+option['value']+"\" ";
3449 if ( typeof (option['selected']) != 'undefined' && option['selected']== true) {
3452 text += ">"+option['text']+"</option>";
3454 text += "</select>";
3458 left_to_right: function(left_name, right_name, left_size, right_size) {
3459 SUGAR.savedViews.clearColumns = false;
3460 var left_td = document.getElementById(left_name+'_td');
3461 var right_td = document.getElementById(right_name+'_td');
3463 var display_columns_ref = left_td.getElementsByTagName('select')[0];
3464 var hidden_columns_ref = right_td.getElementsByTagName('select')[0];
3466 var selected_left = new Array();
3467 var notselected_left = new Array();
3468 var notselected_right = new Array();
3470 var left_array = new Array();
3472 var frozen_options = SUGAR.tabChooser.frozenOptions;
3473 frozen_options = frozen_options && frozen_options[left_name] && frozen_options[left_name][right_name]?frozen_options[left_name][right_name]:[];
3475 // determine which options are selected in left
3476 for (i=0; i < display_columns_ref.options.length; i++)
3478 if ( display_columns_ref.options[i].selected == true && !frozen_options[display_columns_ref.options[i].value])
3480 selected_left[selected_left.length] = {text: display_columns_ref.options[i].text, value: display_columns_ref.options[i].value};
3484 notselected_left[notselected_left.length] = {text: display_columns_ref.options[i].text, value: display_columns_ref.options[i].value};
3489 for (i=0; i < hidden_columns_ref.options.length; i++)
3491 notselected_right[notselected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
3495 var left_select_html_info = new Object();
3496 var left_options = new Array();
3497 var left_select = new Object();
3499 left_select['name'] = left_name+'[]';
3500 left_select['id'] = left_name;
3501 left_select['size'] = left_size;
3502 left_select['multiple'] = 'true';
3504 var right_select_html_info = new Object();
3505 var right_options = new Array();
3506 var right_select = new Object();
3508 right_select['name'] = right_name+'[]';
3509 right_select['id'] = right_name;
3510 right_select['size'] = right_size;
3511 right_select['multiple'] = 'true';
3513 for (i = 0; i < notselected_right.length; i++) {
3514 right_options[right_options.length] = notselected_right[i];
3517 for (i = 0; i < selected_left.length; i++) {
3518 right_options[right_options.length] = selected_left[i];
3520 for (i = 0; i < notselected_left.length; i++) {
3521 left_options[left_options.length] = notselected_left[i];
3523 left_select_html_info['options'] = left_options;
3524 left_select_html_info['select'] = left_select;
3525 right_select_html_info['options'] = right_options;
3526 right_select_html_info['select'] = right_select;
3527 right_select_html_info['style'] = 'background: lightgrey';
3529 var left_html = this.buildSelectHTML(left_select_html_info);
3530 var right_html = this.buildSelectHTML(right_select_html_info);
3532 left_td.innerHTML = left_html;
3533 right_td.innerHTML = right_html;
3535 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3536 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3538 this.movementCallback(object_refs[left_name], object_refs[right_name]);
3544 right_to_left: function(left_name, right_name, left_size, right_size, max_left) {
3545 SUGAR.savedViews.clearColumns = false;
3546 var left_td = document.getElementById(left_name+'_td');
3547 var right_td = document.getElementById(right_name+'_td');
3549 var display_columns_ref = left_td.getElementsByTagName('select')[0];
3550 var hidden_columns_ref = right_td.getElementsByTagName('select')[0];
3552 var selected_right = new Array();
3553 var notselected_right = new Array();
3554 var notselected_left = new Array();
3556 var frozen_options = SUGAR.tabChooser.frozenOptions;
3557 frozen_options = SUGAR.tabChooser.frozenOptions && SUGAR.tabChooser.frozenOptions[right_name] && SUGAR.tabChooser.frozenOptions[right_name][left_name]?SUGAR.tabChooser.frozenOptions[right_name][left_name]:[];
3559 for (i=0; i < hidden_columns_ref.options.length; i++)
3561 if (hidden_columns_ref.options[i].selected == true && !frozen_options[hidden_columns_ref.options[i].value])
3563 selected_right[selected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
3567 notselected_right[notselected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
3572 if(max_left != '' && (display_columns_ref.length + selected_right.length) > max_left) {
3573 alert('Maximum of ' + max_left + ' columns can be displayed.');
3577 for (i=0; i < display_columns_ref.options.length; i++)
3579 notselected_left[notselected_left.length] = {text:display_columns_ref.options[i].text, value:display_columns_ref.options[i].value};
3583 var left_select_html_info = new Object();
3584 var left_options = new Array();
3585 var left_select = new Object();
3587 left_select['name'] = left_name+'[]';
3588 left_select['id'] = left_name;
3589 left_select['multiple'] = 'true';
3590 left_select['size'] = left_size;
3592 var right_select_html_info = new Object();
3593 var right_options = new Array();
3594 var right_select = new Object();
3596 right_select['name'] = right_name+ '[]';
3597 right_select['id'] = right_name;
3598 right_select['multiple'] = 'true';
3599 right_select['size'] = right_size;
3601 for (i = 0; i < notselected_left.length; i++) {
3602 left_options[left_options.length] = notselected_left[i];
3605 for (i = 0; i < selected_right.length; i++) {
3606 left_options[left_options.length] = selected_right[i];
3608 for (i = 0; i < notselected_right.length; i++) {
3609 right_options[right_options.length] = notselected_right[i];
3611 left_select_html_info['options'] = left_options;
3612 left_select_html_info['select'] = left_select;
3613 right_select_html_info['options'] = right_options;
3614 right_select_html_info['select'] = right_select;
3615 right_select_html_info['style'] = 'background: lightgrey';
3617 var left_html = this.buildSelectHTML(left_select_html_info);
3618 var right_html = this.buildSelectHTML(right_select_html_info);
3620 left_td.innerHTML = left_html;
3621 right_td.innerHTML = right_html;
3623 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3624 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3626 this.movementCallback(object_refs[left_name], object_refs[right_name]);
3631 up: function(name, left_name, right_name) {
3632 SUGAR.savedViews.clearColumns = false;
3633 var left_td = document.getElementById(left_name+'_td');
3634 var right_td = document.getElementById(right_name+'_td');
3635 var td = document.getElementById(name+'_td');
3636 var obj = td.getElementsByTagName('select')[0];
3637 obj = (typeof obj == "string") ? document.getElementById(obj) : obj;
3638 if (obj.tagName.toLowerCase() != "select" && obj.length < 2)
3640 var sel = new Array();
3642 for (i=0; i<obj.length; i++) {
3643 if (obj[i].selected == true) {
3644 sel[sel.length] = i;
3647 for (i=0; i < sel.length; i++) {
3648 if (sel[i] != 0 && !obj[sel[i]-1].selected) {
3649 var tmp = new Array(obj[sel[i]-1].text, obj[sel[i]-1].value);
3650 obj[sel[i]-1].text = obj[sel[i]].text;
3651 obj[sel[i]-1].value = obj[sel[i]].value;
3652 obj[sel[i]].text = tmp[0];
3653 obj[sel[i]].value = tmp[1];
3654 obj[sel[i]-1].selected = true;
3655 obj[sel[i]].selected = false;
3659 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3660 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3662 this.orderCallback(object_refs[left_name], object_refs[right_name]);
3667 down: function(name, left_name, right_name) {
3668 SUGAR.savedViews.clearColumns = false;
3669 var left_td = document.getElementById(left_name+'_td');
3670 var right_td = document.getElementById(right_name+'_td');
3671 var td = document.getElementById(name+'_td');
3672 var obj = td.getElementsByTagName('select')[0];
3673 if (obj.tagName.toLowerCase() != "select" && obj.length < 2)
3675 var sel = new Array();
3676 for (i=obj.length-1; i>-1; i--) {
3677 if (obj[i].selected == true) {
3678 sel[sel.length] = i;
3681 for (i=0; i < sel.length; i++) {
3682 if (sel[i] != obj.length-1 && !obj[sel[i]+1].selected) {
3683 var tmp = new Array(obj[sel[i]+1].text, obj[sel[i]+1].value);
3684 obj[sel[i]+1].text = obj[sel[i]].text;
3685 obj[sel[i]+1].value = obj[sel[i]].value;
3686 obj[sel[i]].text = tmp[0];
3687 obj[sel[i]].value = tmp[1];
3688 obj[sel[i]+1].selected = true;
3689 obj[sel[i]].selected = false;
3693 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3694 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3696 this.orderCallback(object_refs[left_name], object_refs[right_name]);
3701 }(); // end tabChooser
3703 SUGAR.language = function() {
3705 languages : new Array(),
3707 setLanguage: function(module, data) {
3708 if (!SUGAR.language.languages) {
3711 SUGAR.language.languages[module] = data;
3714 get: function(module, str) {
3715 if(typeof SUGAR.language.languages[module] == 'undefined' || typeof SUGAR.language.languages[module][str] == 'undefined')
3719 return SUGAR.language.languages[module][str];
3722 translate: function(module, str)
3724 text = this.get(module, str);
3725 return text != 'undefined' ? text : this.get('app_strings', str);
3730 SUGAR.contextMenu = function() {
3732 objects: new Object(),
3733 objectTypes: new Object(),
3735 * Registers a new object for the context menu.
3736 * objectType - name of the type
3738 * metaData - metaData to pass to the action function
3740 registerObject: function(objectType, id, metaData) {
3741 SUGAR.contextMenu.objects[id] = new Object();
3742 SUGAR.contextMenu.objects[id] = {'objectType' : objectType, 'metaData' : metaData};
3745 * Registers a new object type
3746 * name - name of the type
3747 * menuItems - array of menu items
3749 registerObjectType: function(name, menuItems) {
3750 SUGAR.contextMenu.objectTypes[name] = new Object();
3751 SUGAR.contextMenu.objectTypes[name] = {'menuItems' : menuItems, 'objects' : new Array()};
3754 * Determines which menu item was clicked
3756 getListItemFromEventTarget: function(p_oNode) {
3758 if(p_oNode.tagName == "LI") {
3763 if(p_oNode.tagName == "LI") {
3768 } while((p_oNode = p_oNode.parentNode));
3773 * handles movement within context menu
3775 onContextMenuMove: function() {
3776 var oNode = this.contextEventTarget;
3777 var bDisabled = (oNode.tagName == "UL");
3778 var i = this.getItemGroups()[0].length - 1;
3780 this.getItem(i).cfg.setProperty("disabled", bDisabled);
3785 * handles clicks on a context menu ITEM
3787 onContextMenuItemClick: function(p_sType, p_aArguments, p_oItem) {
3788 var oLI = SUGAR.contextMenu.getListItemFromEventTarget(this.parent.contextEventTarget);
3789 id = this.parent.contextEventTarget.parentNode.id; // id of the target
3790 funct = eval(SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[id]['objectType']]['menuItems'][this.index]['action']);
3791 funct(this.parent.contextEventTarget, SUGAR.contextMenu.objects[id]['metaData']);
3794 * Initializes all context menus registered
3797 for(var i in SUGAR.contextMenu.objects) { // make a variable called objects in objectTypes containg references to all triggers
3798 if(typeof SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'] == 'undefined')
3799 SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'] = new Array();
3800 SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'].push(document.getElementById(i));
3802 // register the menus
3803 for(var i in SUGAR.contextMenu.objectTypes) {
3804 var oContextMenu = new YAHOO.widget.ContextMenu(i, {'trigger': SUGAR.contextMenu.objectTypes[i]['objects']});
3805 var aMainMenuItems = SUGAR.contextMenu.objectTypes[i]['menuItems'];
3806 var nMainMenuItems = aMainMenuItems.length;
3808 for(var j = 0; j < nMainMenuItems; j++) {
3809 oMenuItem = new YAHOO.widget.ContextMenuItem(aMainMenuItems[j].text, { helptext: aMainMenuItems[j].helptext });
3810 oMenuItem.clickEvent.subscribe(SUGAR.contextMenu.onContextMenuItemClick, oMenuItem, true);
3811 oContextMenu.addItem(oMenuItem);
3813 // Add a "move" event handler to the context menu
3814 oContextMenu.moveEvent.subscribe(SUGAR.contextMenu.onContextMenuMove, oContextMenu, true);
3815 // Add a "keydown" event handler to the context menu
3816 oContextMenu.keyDownEvent.subscribe(SUGAR.contextMenu.onContextMenuItemClick, oContextMenu, true);
3817 // Render the context menu
3818 oContextMenu.render(document.body);
3824 SUGAR.contextMenu.actions = function() {
3827 * redirects to a new note with the clicked on object as the target
3829 createNote: function(itemClicked, metaData) {
3830 loc = 'index.php?module=Notes&action=EditView';
3831 for(i in metaData) {
3832 if(i == 'notes_parent_type') loc += '&parent_type=' + metaData[i];
3833 else if(i != 'module' && i != 'parent_type') loc += '&' + i + '=' + metaData[i];
3835 document.location = loc;
3838 * redirects to a new note with the clicked on object as the target
3840 scheduleMeeting: function(itemClicked, metaData) {
3841 loc = 'index.php?module=Meetings&action=EditView';
3842 for(i in metaData) {
3843 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3845 document.location = loc;
3848 * redirects to a new note with the clicked on object as the target
3850 scheduleCall: function(itemClicked, metaData) {
3851 loc = 'index.php?module=Calls&action=EditView';
3852 for(i in metaData) {
3853 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3855 document.location = loc;
3858 * redirects to a new contact with the clicked on object as the target
3860 createContact: function(itemClicked, metaData) {
3861 loc = 'index.php?module=Contacts&action=EditView';
3862 for(i in metaData) {
3863 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3865 document.location = loc;
3868 * redirects to a new task with the clicked on object as the target
3870 createTask: function(itemClicked, metaData) {
3871 loc = 'index.php?module=Tasks&action=EditView';
3872 for(i in metaData) {
3873 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3875 document.location = loc;
3878 * redirects to a new opportunity with the clicked on object as the target
3880 createOpportunity: function(itemClicked, metaData) {
3881 loc = 'index.php?module=Opportunities&action=EditView';
3882 for(i in metaData) {
3883 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3885 document.location = loc;
3888 * redirects to a new opportunity with the clicked on object as the target
3890 createCase: function(itemClicked, metaData) {
3891 loc = 'index.php?module=Cases&action=EditView';
3892 for(i in metaData) {
3893 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3895 document.location = loc;
3898 * handles add to favorites menu selection
3900 addToFavorites: function(itemClicked, metaData) {
3901 success = function(data) {
3903 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});
3908 //if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.contextMenu.init);
3910 // initially from popup_parent_helper.js
3911 var popup_request_data;
3914 function get_popup_request_data()
3916 return YAHOO.lang.JSON.stringify(window.document.popup_request_data);
3919 function get_close_popup()
3921 return window.document.close_popup;
3924 function open_popup(module_name, width, height, initial_filter, close_popup, hide_clear_button, popup_request_data, popup_mode, create, metadata)
3926 if (typeof(popupCount) == "undefined" || popupCount == 0)
3929 // set the variables that the popup will pull from
3930 window.document.popup_request_data = popup_request_data;
3931 window.document.close_popup = close_popup;
3933 //globally changing width and height of standard pop up window from 600 x 400 to 800 x 800
3934 width = (width == 600) ? 800 : width;
3935 height = (height == 400) ? 800 : height;
3939 + 'module=' + module_name
3942 if (initial_filter != '') {
3943 URL += '&query=true' + initial_filter;
3944 // Bug 41891 - Popup Window Name
3945 popupName = initial_filter.replace(/[^a-z_0-9]+/ig, '_');
3946 windowName = module_name + '_popup_window' + popupName;
3948 windowName = module_name + '_popup_window' + popupCount;
3952 if (hide_clear_button) {
3953 URL += '&hide_clear_button=true';
3956 windowFeatures = 'width=' + width
3957 + ',height=' + height
3958 + ',resizable=1,scrollbars=1';
3960 if (popup_mode == '' && popup_mode == 'undefined') {
3961 popup_mode='single';
3963 URL+='&mode='+popup_mode;
3964 if (create == '' && create == 'undefined') {
3967 URL+='&create='+create;
3969 if (metadata != '' && metadata != 'undefined') {
3970 URL+='&metadata='+metadata;
3973 win = SUGAR.util.openWindow(URL, windowName, windowFeatures);
3977 // put the focus on the popup if the browser supports the focus() method
3981 win.popupCount = popupCount;
3987 * The reply data must be a JSON array structured with the following information:
3988 * 1) form name to populate
3989 * 2) associative array of input names to values for populating the form
3991 var from_popup_return = false;
3993 function set_return_basic(popup_reply_data,filter)
3995 var form_name = popup_reply_data.form_name;
3996 var name_to_value_array = popup_reply_data.name_to_value_array;
3997 for (var the_key in name_to_value_array)
3999 if(the_key == 'toJSON')
4003 else if(the_key.match(filter))
4005 var displayValue=name_to_value_array[the_key].replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');;
4006 // begin andopes change: support for enum fields (SELECT)
4007 if(window.document.forms[form_name] && window.document.forms[form_name].elements[the_key]) {
4008 if(window.document.forms[form_name].elements[the_key].tagName == 'SELECT') {
4009 var selectField = window.document.forms[form_name].elements[the_key];
4010 for(var i = 0; i < selectField.options.length; i++) {
4011 if(selectField.options[i].text == displayValue) {
4012 selectField.options[i].selected = true;
4013 SUGAR.util.callOnChangeListers(selectField);
4018 window.document.forms[form_name].elements[the_key].value = displayValue;
4019 SUGAR.util.callOnChangeListers(window.document.forms[form_name].elements[the_key]);
4022 // end andopes change: support for enum fields (SELECT)
4027 function set_return(popup_reply_data)
4029 from_popup_return = true;
4030 var form_name = popup_reply_data.form_name;
4031 var name_to_value_array = popup_reply_data.name_to_value_array;
4032 if(typeof name_to_value_array != 'undefined' && name_to_value_array['account_id'])
4035 var label_data_str = '';
4036 var current_label_data_str = '';
4037 for (var the_key in name_to_value_array)
4039 if(the_key == 'toJSON')
4045 var displayValue=name_to_value_array[the_key].replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');
4046 if(window.document.forms[form_name] && document.getElementById(the_key+'_label') && !the_key.match(/account/)) {
4047 var data_label = document.getElementById(the_key+'_label').innerHTML.replace(/\n/gi,'');
4048 label_str += data_label + ' \n';
4049 label_data_str += data_label + ' ' + displayValue + '\n';
4050 if(window.document.forms[form_name].elements[the_key]) {
4051 current_label_data_str += data_label + ' ' + window.document.forms[form_name].elements[the_key].value +'\n';
4056 if(label_data_str != label_str && current_label_data_str != label_str){
4057 if(confirm(SUGAR.language.get('app_strings', 'NTC_OVERWRITE_ADDRESS_PHONE_CONFIRM') + '\n\n' + label_data_str))
4059 set_return_basic(popup_reply_data,/\S/);
4061 set_return_basic(popup_reply_data,/account/);
4063 }else if(label_data_str != label_str && current_label_data_str == label_str){
4064 set_return_basic(popup_reply_data,/\S/);
4065 }else if(label_data_str == label_str){
4066 set_return_basic(popup_reply_data,/account/);
4069 set_return_basic(popup_reply_data,/\S/);
4073 function set_return_lead_conv(popup_reply_data) {
4074 set_return(popup_reply_data);
4075 if (document.getElementById('lead_conv_ac_op_sel') && typeof onBlurKeyUpHandler=='function') {
4076 onBlurKeyUpHandler();
4080 function set_return_and_save(popup_reply_data)
4082 var form_name = popup_reply_data.form_name;
4083 var name_to_value_array = popup_reply_data.name_to_value_array;
4085 for (var the_key in name_to_value_array)
4087 if(the_key == 'toJSON')
4093 window.document.forms[form_name].elements[the_key].value = name_to_value_array[the_key];
4097 window.document.forms[form_name].return_module.value = window.document.forms[form_name].module.value;
4098 window.document.forms[form_name].return_action.value = 'DetailView';
4099 window.document.forms[form_name].return_id.value = window.document.forms[form_name].record.value;
4100 window.document.forms[form_name].action.value = 'Save';
4101 window.document.forms[form_name].submit();
4105 * This is a helper function to construct the initial filter that can be
4106 * passed into the open_popup() function. It assumes that there is an
4107 * account_id and account_name field in the given form_name to use to
4108 * construct the intial filter string.
4110 function get_initial_filter_by_account(form_name)
4112 var account_id = window.document.forms[form_name].account_id.value;
4113 var account_name = escape(window.document.forms[form_name].account_name.value);
4114 var initial_filter = "&account_id=" + account_id + "&account_name=" + account_name;
4116 return initial_filter;
4118 // end code from popup_parent_helper.js
4120 // begin code for address copy
4122 * This is a function used by the Address widget that will fill
4123 * in the given array fields using the fromKey and toKey as a
4124 * prefix into the form objects HTML elements.
4126 * @param form The HTML form object to parse
4127 * @param fromKey The prefix of elements to copy from
4128 * @param toKey The prefix of elements to copy into
4129 * @return boolean true if successful, false otherwise
4131 function copyAddress(form, fromKey, toKey) {
4133 var elems = new Array("address_street", "address_city", "address_state", "address_postalcode", "address_country");
4134 var checkbox = document.getElementById(toKey + "_checkbox");
4136 if(typeof checkbox != "undefined") {
4137 if(!checkbox.checked) {
4139 t = toKey + "_" + elems[x];
4140 document.getElementById(t).removeAttribute('readonly');
4144 f = fromKey + "_" + elems[x];
4145 t = toKey + "_" + elems[x];
4147 document.getElementById(t).value = document.getElementById(f).value;
4148 document.getElementById(t).setAttribute('readonly', true);
4154 // end code for address copy
4157 * This function is used in Email Template Module.
4158 * It will check whether the template is used in Campaing->EmailMarketing.
4159 * If true, it will notify user.
4162 function check_deletable_EmailTemplate() {
4163 id = document.getElementsByName('record')[0].value;
4164 currentForm = document.getElementById('form');
4166 success:function(r) {
4167 if(r.responseText == 'true') {
4168 if(!confirm(SUGAR.language.get('app_strings','NTC_TEMPLATE_IS_USED'))) {
4172 if(!confirm(SUGAR.language.get('app_strings','NTC_DELETE_CONFIRMATION'))) {
4176 currentForm.return_module.value='EmailTemplates';
4177 currentForm.return_action.value='ListView';
4178 currentForm.action.value='Delete';
4179 currentForm.submit();
4182 url = "index.php?module=EmailTemplates&action=CheckDeletable&from=DetailView&to_pdf=1&record="+id;
4183 YAHOO.util.Connect.asyncRequest('POST',url, call_back,null);
4187 remove_upload_imagefile : function(field_name) {
4188 var field=document.getElementById('remove_imagefile_' + field_name);
4191 //enable the file upload button.
4192 var field=document.getElementById( field_name);
4193 field.style.display="";
4195 //hide the image and remove button.
4196 var field=document.getElementById('img_' + field_name);
4197 field.style.display="none";
4198 var field=document.getElementById('bt_remove_' + field_name);
4199 field.style.display="none";
4201 if(document.getElementById(field_name + '_duplicate')) {
4202 var field = document.getElementById(field_name + '_duplicate');
4207 confirm_imagefile : function(field_name) {
4208 var field=document.getElementById(field_name);
4209 var filename=field.value;
4210 var fileExtension = filename.substring(filename.lastIndexOf(".")+1);
4211 fileExtension = fileExtension.toLowerCase();
4212 if (fileExtension == "jpg" || fileExtension == "jpeg"
4213 || fileExtension == "gif" || fileExtension == "png" || fileExtension == "bmp"){
4218 alert(SUGAR.language.get('app_strings', 'LBL_UPLOAD_IMAGE_FILE_INVALID'));
4222 lightbox : function(image)
4224 if (typeof(SUGAR.image.lighboxWindow) == "undefined")
4225 SUGAR.image.lighboxWindow = new YAHOO.widget.SimpleDialog('sugarImageViewer', {
4228 id:'sugarMsgWindow',
4231 msg: "<img src='" + image + "'> </img>",
4234 SUGAR.image.lighboxWindow.setBody("<img src='" + image + "'> </img>");
4235 SUGAR.image.lighboxWindow.render(document.body);
4236 SUGAR.image.lighboxWindow.show();
4237 SUGAR.image.lighboxWindow.center()
4241 SUGAR.append(SUGAR.util, {
4242 isTouchScreen: function() {
4243 // first check if we have forced use of the touch enhanced interface
4244 if (Get_Cookie("touchscreen") == '1') {
4248 // next check if we should use the touch interface with our device
4249 if ((navigator.userAgent.match(/iPad/i) != null)) {
4256 isLoginPage: function(content) {
4257 //skip if this is packageManager screen
4258 if(SUGAR.util.isPackageManager()) {return false;}
4259 var loginPageStart = "<!DOCTYPE";
4260 if (content.substr(0, loginPageStart.length) == loginPageStart && content.indexOf("<html>") != -1 && content.indexOf("login_module") != -1) {
4261 window.location.href = window.location.protocol + window.location.pathname;
4266 isPackageManager: function(){
4267 if(typeof(document.the_form) !='undefined' && typeof(document.the_form.language_pack_escaped) !='undefined'){
4269 }else{return false;}
4272 ajaxCallInProgress: function(){
4273 return SUGAR_callsInProgress != 0;
4276 callOnChangeListers: function(field){
4277 var listeners = YAHOO.util.Event.getListeners(field, 'change');
4278 if (listeners != null) {
4279 for (var i = 0; i < listeners.length; i++) {
4280 var l = listeners[i];
4281 l.fn.call(l.scope ? l.scope : this, l.obj);
4286 closeActivityPanel: {
4287 show:function(module,id,new_status,viewType,parentContainerId){
4288 if (SUGAR.util.closeActivityPanel.panel)
4289 SUGAR.util.closeActivityPanel.panel.destroy();
4290 var singleModule = SUGAR.language.get("app_list_strings", "moduleListSingular")[module];
4291 singleModule = typeof(singleModule != 'undefined') ? singleModule.toLowerCase() : '';
4292 var closeText = SUGAR.language.get("app_strings", "LBL_CLOSE_ACTIVITY_CONFIRM").replace("#module#",singleModule);
4293 SUGAR.util.closeActivityPanel.panel =
4294 new YAHOO.widget.SimpleDialog("closeActivityDialog",
4301 constraintoviewport: true,
4302 buttons: [ { text:SUGAR.language.get("app_strings", "LBL_EMAIL_OK"), handler:function(){
4303 if (SUGAR.util.closeActivityPanel.panel)
4304 SUGAR.util.closeActivityPanel.panel.hide();
4306 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_SAVING'));
4307 var args = "action=save&id=" + id + "&record=" + id + "&status=" + new_status + "&module=" + module;
4308 // 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
4309 // TODO: Take id out and regression test. Left id in for now to not create any other unexpected problems
4310 //var args = "action=save&id=" + id + "&status=" + new_status + "&module=" + module;
4313 { //refresh window to show updated changes
4314 window.location.reload(true);
4316 if(viewType == 'dashlet')
4318 SUGAR.mySugar.retrieveDashlet(o.argument['parentContainerId']);
4319 ajaxStatus.hideStatus();
4321 else if(viewType == 'subpanel'){
4322 showSubPanel(o.argument['parentContainerId'],null,true);
4323 if(o.argument['parentContainerId'] == 'activities'){
4324 showSubPanel('history',null,true);
4326 ajaxStatus.hideStatus();
4328 }else if(viewType == 'listview'){
4329 document.location = 'index.php?module=' + module +'&action=index';
4333 argument:{'parentContainerId':parentContainerId}
4336 YAHOO.util.Connect.asyncRequest('POST', 'index.php', callback, args);
4338 }, isDefault:true },
4339 { text:SUGAR.language.get("app_strings", "LBL_EMAIL_CANCEL"), handler:function(){SUGAR.util.closeActivityPanel.panel.hide(); }} ]
4342 SUGAR.util.closeActivityPanel.panel.setHeader(SUGAR.language.get("app_strings", "LBL_CLOSE_ACTIVITY_HEADER"));
4343 SUGAR.util.closeActivityPanel.panel.render(document.body);
4344 SUGAR.util.closeActivityPanel.panel.show();
4348 setEmailPasswordDisplay: function(id, exists) {
4349 link = document.getElementById(id+'_link');
4350 pwd = document.getElementById(id);
4351 if(!pwd || !link) return;
4353 pwd.style.display = 'none';
4354 link.style.display = '';
4356 pwd.style.display = '';
4357 link.style.display = 'none';
4361 setEmailPasswordEdit: function(id) {
4362 link = document.getElementById(id+'_link');
4363 pwd = document.getElementById(id);
4364 if(!pwd || !link) return;
4365 pwd.style.display = '';
4366 link.style.display = 'none';
4370 * Compares a filename with a supplied array of allowed file extensions.
4371 * @param fileName string
4372 * @param allowedTypes array of allowed file extensions
4375 validateFileExt: function(fileName, allowedTypes) {
4376 var ext = fileName.split('.').pop();
4378 for (var i = allowedTypes.length; i > 0; i--) {
4379 if (ext === allowedTypes[i]) {
4387 arrayIndexOf: function(arr, val, start) {
4388 if (typeof arr.indexOf == "function")
4389 return arr.indexOf(val, start);
4390 for (var i = (start || 0), j = arr.length; i < j; i++) {
4391 if (arr[i] === val) {
4399 SUGAR.clearRelateField = function(form, name, id)
4401 if (typeof form[name] == "object"){
4402 form[name].value = '';
4403 SUGAR.util.callOnChangeListers(form[name]);
4406 if (typeof form[id] == "object"){
4407 form[id].value = '';
4408 SUGAR.util.callOnChangeListers(form[id]);
4411 if(typeof(SUGAR.AutoComplete) == 'undefined') SUGAR.AutoComplete = {};
4413 SUGAR.AutoComplete.getOptionsArray = function(options_index){
4414 var return_arr = [];
4416 var opts = SUGAR.language.get('app_list_strings', options_index);
4417 if(typeof(opts) != 'undefined'){
4419 // Since we are using auto complete, we excluse blank dropdown entries since they can just leave it blank
4420 if(key != '' && opts[key] != ''){
4423 item['text'] = opts[key];
4424 return_arr.push(item);
4431 if(typeof(SUGAR.MultiEnumAutoComplete) == 'undefined') SUGAR.MultiEnumAutoComplete = {};
4433 SUGAR.MultiEnumAutoComplete.getMultiSelectKeysFromValues = function(options_index, val_string){
4434 var opts = SUGAR.language.get('app_list_strings', options_index);
4435 var selected_values = val_string.split(", ");
4436 // YUI AutoComplete adds a blank. We remove it automatically here
4437 if(selected_values.length > 0 && selected_values.indexOf('') == selected_values.length - 1){
4438 selected_values.pop();
4440 var final_arr = new Array();
4441 for(idx in selected_values){
4443 if(selected_values[idx] == opts[o_idx]){
4444 final_arr.push(o_idx);
4451 SUGAR.MultiEnumAutoComplete.getMultiSelectValuesFromKeys = function(options_index, val_string){
4452 var opts = SUGAR.language.get('app_list_strings', options_index);
4453 val_string=val_string.replace(/^\^/,'').replace(/\^$/,'') //fixes bug where string starts or ends with ^
4454 var selected_values = val_string.split("^,^");
4456 // YUI AutoComplete adds a blank. We remove it automatically here
4457 if(selected_values.length > 0 && selected_values.indexOf('') == selected_values.length - 1){
4458 selected_values.pop();
4461 var final_arr = new Array();
4462 for(idx in selected_values){
4464 if(selected_values[idx] == o_idx){
4465 final_arr.push(opts[o_idx]);