1 /*********************************************************************************
2 * SugarCRM Community Edition is a customer relationship management program developed by
3 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
5 * This program is free software; you can redistribute it and/or modify it under
6 * the terms of the GNU Affero General Public License version 3 as published by the
7 * Free Software Foundation with the addition of the following permission added
8 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
10 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
12 * This program is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
17 * You should have received a copy of the GNU Affero General Public License along with
18 * this program; if not, see http://www.gnu.org/licenses or write to the Free
19 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
23 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
25 * The interactive user interfaces in modified source and object code versions
26 * of this program must display Appropriate Legal Notices, as required under
27 * Section 5 of the GNU Affero General Public License version 3.
29 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
30 * these Appropriate Legal Notices must retain the display of the "Powered by
31 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
32 * technical reasons, the Appropriate Legal Notices must display the words
33 * "Powered by SugarCRM".
34 ********************************************************************************/
40 * Namespace for Sugar Objects
42 if (typeof(SUGAR) == "undefined") {
46 * Creates a namespace if it doesn't exist and then returns it.
48 * Note: this implementation only creates a top-level namespace. Extend this function if
49 * multi-level namespaces are needed.
52 namespace: function(ns) {
53 SUGAR[ns] = SUGAR[ns] || {};
55 return ((typeof SUGAR[ns] === "object") && (SUGAR[ns] !== null)) ? SUGAR[ns] : false;
59 * Add properties of an object to target object.
63 append: function(target, obj) {
64 for (var prop in obj) {
65 if (obj[prop] !== void 0) target[prop] = obj[prop];
74 SUGAR.namespace("themes");
77 * Namespace for Homepage
79 SUGAR.namespace("sugarHome");
82 * Namespace for Subpanel Utils
84 SUGAR.namespace("subpanelUtils");
89 SUGAR.namespace("ajaxStatusClass");
94 SUGAR.namespace("tabChooser");
97 * General namespace for Sugar utils
99 SUGAR.namespace("utils");
100 SUGAR.namespace("savedViews");
105 SUGAR.namespace("dashlets");
106 SUGAR.namespace("unifiedSearchAdvanced");
108 SUGAR.namespace("searchForm");
109 SUGAR.namespace("language");
110 SUGAR.namespace("Studio");
111 SUGAR.namespace("contextMenu");
112 SUGAR.namespace("config");
116 var requiredIndex = 2;
121 var altMsgIndex = 15;
122 var compareToIndex = 7;
124 var operatorIndex = 13;
126 var validate = new Array();
128 var requiredTxt = 'Missing Required Field:'
129 var invalidTxt = 'Invalid Value:'
130 var secondsSinceLoad = 0;
131 var inputsWithErrors = new Array();
132 var tabsWithErrors = new Array();
133 var lastSubmitTime = 0;
134 var alertList = new Array();
135 var oldStartsWith = '';
140 * As of Sugar version 6.2.3 (MSIE Version 9) this function is deprecated. The preferred method is to use the
141 * user agent check supplied by YUI to check for IE:
143 * for checking if a browser is IE in general : if(YAHOO.env.ua.ie) {...}
145 * or for checking specific versions: if (YAHOO.env.ua.ie >= 5.5 && YAHOO.env.ua.ie < 9) {...}
148 function isSupportedIE() {
149 var userAgent = navigator.userAgent.toLowerCase() ;
151 // IE Check supports ActiveX controls
152 if (userAgent.indexOf("msie") != -1 && userAgent.indexOf("mac") == -1 && userAgent.indexOf("opera") == -1) {
153 var version = navigator.appVersion.match(/MSIE (.\..)/)[1] ;
154 if(version >= 5.5 && version < 10) {
162 SUGAR.isIE = isSupportedIE();
163 var isSafari = (navigator.userAgent.toLowerCase().indexOf('safari')!=-1);
165 // escapes regular expression characters
166 RegExp.escape = function(text) { // http://simon.incutio.com/archive/2006/01/20/escape
167 if (!arguments.callee.sRE) {
168 var specials = ['/', '.', '*', '+', '?', '|','(', ')', '[', ']', '{', '}', '\\'];
169 arguments.callee.sRE = new RegExp('(\\' + specials.join('|\\') + ')', 'g');
171 return text.replace(arguments.callee.sRE, '\\$1');
174 function addAlert(type, name,subtitle, description,time, redirect) {
175 var addIndex = alertList.length;
176 alertList[addIndex]= new Array();
177 alertList[addIndex]['name'] = name;
178 alertList[addIndex]['type'] = type;
179 alertList[addIndex]['subtitle'] = subtitle;
180 alertList[addIndex]['description'] = description.replace(/<br>/gi, "\n").replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');
181 alertList[addIndex]['time'] = time;
182 alertList[addIndex]['done'] = 0;
183 alertList[addIndex]['redirect'] = redirect;
185 function checkAlerts() {
186 secondsSinceLoad += 1;
189 for(mj = 0 ; mj < alertList.length; mj++) {
190 if(alertList[mj]['done'] == 0) {
191 if(alertList[mj]['time'] < secondsSinceLoad && alertList[mj]['time'] > -1 ) {
192 alertmsg = alertList[mj]['type'] + ":" + alertList[mj]['name'] + "\n" +alertList[mj]['subtitle']+ "\n"+ alertList[mj]['description'] + "\n\n";
193 alertList[mj]['done'] = 1;
194 if(alertList[mj]['redirect'] == '') {
197 else if(confirm(alertmsg)) {
198 window.location = alertList[mj]['redirect'];
204 setTimeout("checkAlerts()", 1000);
207 function toggleDisplay(id) {
208 if(this.document.getElementById(id).style.display == 'none') {
209 this.document.getElementById(id).style.display = '';
210 if(this.document.getElementById(id+"link") != undefined) {
211 this.document.getElementById(id+"link").style.display = 'none';
213 if(this.document.getElementById(id+"_anchor") != undefined)
214 this.document.getElementById(id+"_anchor").innerHTML='[ - ]';
217 this.document.getElementById(id).style.display = 'none'
218 if(this.document.getElementById(id+"link") != undefined) {
219 this.document.getElementById(id+"link").style.display = '';
221 if(this.document.getElementById(id+"_anchor") != undefined)
222 this.document.getElementById(id+"_anchor").innerHTML='[+]';
226 function checkAll(form, field, value) {
227 for (i = 0; i < form.elements.length; i++) {
228 if(form.elements[i].name == field)
229 form.elements[i].checked = value;
233 function replaceAll(text, src, rep) {
234 offset = text.toLowerCase().indexOf(src.toLowerCase());
235 while(offset != -1) {
236 text = text.substring(0, offset) + rep + text.substring(offset + src.length ,text.length);
237 offset = text.indexOf( src, offset + rep.length + 1);
242 function addForm(formname) {
243 validate[formname] = new Array();
246 function addToValidate(formname, name, type, required, msg) {
247 if(typeof validate[formname] == 'undefined') {
250 validate[formname][validate[formname].length] = new Array(name, type,required, msg);
253 function addToValidateRange(formname, name, type,required, msg,min,max) {
254 addToValidate(formname, name, type,required, msg);
255 validate[formname][validate[formname].length - 1][jstypeIndex] = 'range'
256 validate[formname][validate[formname].length - 1][minIndex] = min;
257 validate[formname][validate[formname].length - 1][maxIndex] = max;
260 function addToValidateIsValidDate(formname, name, type, required, msg) {
261 addToValidate(formname, name, type, required, msg);
262 validate[formname][validate[formname].length - 1][jstypeIndex] = 'date'
265 function addToValidateIsValidTime(formname, name, type, required, msg) {
266 addToValidate(formname, name, type, required, msg);
267 validate[formname][validate[formname].length - 1][jstypeIndex] = 'time'
270 function addToValidateDateBefore(formname, name, type, required, msg, compareTo) {
271 addToValidate(formname, name, type,required, msg);
272 validate[formname][validate[formname].length - 1][jstypeIndex] = 'isbefore'
273 validate[formname][validate[formname].length - 1][compareToIndex] = compareTo;
276 function addToValidateDateBeforeAllowBlank(formname, name, type, required, msg, compareTo, allowBlank) {
277 addToValidate(formname, name, type,required, msg);
278 validate[formname][validate[formname].length - 1][jstypeIndex] = 'isbefore'
279 validate[formname][validate[formname].length - 1][compareToIndex] = compareTo;
280 validate[formname][validate[formname].length - 1][allowblank] = allowBlank;
283 function addToValidateBinaryDependency(formname, name, type, required, msg, compareTo) {
284 addToValidate(formname, name, type, required, msg);
285 validate[formname][validate[formname].length - 1][jstypeIndex] = 'binarydep';
286 validate[formname][validate[formname].length - 1][compareToIndex] = compareTo;
289 function addToValidateComparison(formname, name, type, required, msg, compareTo) {
290 addToValidate(formname, name, type, required, msg);
291 validate[formname][validate[formname].length - 1][jstypeIndex] = 'comparison';
292 validate[formname][validate[formname].length - 1][compareToIndex] = compareTo;
295 function addToValidateIsInArray(formname, name, type, required, msg, arr, operator) {
296 addToValidate(formname, name, type, required, msg);
297 validate[formname][validate[formname].length - 1][jstypeIndex] = 'in_array';
298 validate[formname][validate[formname].length - 1][arrIndex] = arr;
299 validate[formname][validate[formname].length - 1][operatorIndex] = operator;
302 function addToValidateVerified(formname, name, type, required, msg, arr, operator) {
303 addToValidate(formname, name, type, required, msg);
304 validate[formname][validate[formname].length - 1][jstypeIndex] = 'verified';
307 function addToValidateLessThan(formname, name, type, required, msg, max, max_field_msg) {
308 addToValidate(formname, name, type, required, msg);
309 validate[formname][validate[formname].length - 1][jstypeIndex] = 'less';
310 validate[formname][validate[formname].length - 1][maxIndex] = max;
311 validate[formname][validate[formname].length - 1][altMsgIndex] = max_field_msg;
314 function addToValidateMoreThan(formname, name, type, required, msg, min) {
315 addToValidate(formname, name, type, required, msg);
316 validate[formname][validate[formname].length - 1][jstypeIndex] = 'more';
317 validate[formname][validate[formname].length - 1][minIndex] = min;
321 function removeFromValidate(formname, name) {
322 for(i = 0; i < validate[formname].length; i++)
324 if(validate[formname][i][nameIndex] == name)
326 validate[formname].splice(i--,1); // We subtract 1 from i since the slice removed an element, and we'll skip over the next item we scan
330 function checkValidate(formname, name) {
331 if(validate[formname]){
332 for(i = 0; i < validate[formname].length; i++){
333 if(validate[formname][i][nameIndex] == name){
340 var formsWithFieldLogic=null;
341 var formWithPrecision =null;
342 function addToValidateFieldLogic(formId,minFieldId, maxFieldId, defaultFieldId, lenFieldId,type,msg){
343 this.formId = document.getElementById(formId);
344 this.min=document.getElementById(minFieldId);
345 this.max= document.getElementById(maxFieldId);
346 this._default= document.getElementById(defaultFieldId);
347 this.len = document.getElementById(lenFieldId);
351 //@params: formid- Dom id of the form containing the precision and float fields
352 // valudId- Dom id of the field containing a float whose precision is to be checked.
353 // precisionId- Dom id of the field containing precision value.
354 function addToValidatePrecision(formId, valueId, precisionId){
355 this.form = document.getElementById(formId);
356 this.float = document.getElementById(valueId);
357 this.precision = document.getElementById(precisionId);
360 //function checkLength(value, referenceValue){
364 function isValidPrecision(value, precision){
365 value = trim(value.toString());
371 if( (precision == "0") ){
372 if (value.indexOf(dec_sep)== -1){
379 if(value.charAt(value.length-precision-1) == num_grp_sep){
380 if(value.substr(value.indexOf(dec_sep), 1)==dec_sep){
385 var actualPrecision = value.substr(value.indexOf(dec_sep)+1, value.length).length;
386 return actualPrecision == precision;
388 function toDecimal(original, precision) {
389 precision = (precision == null) ? 2 : precision;
390 num = Math.pow(10, precision);
391 temp = Math.round(original*num)/num;
392 if((temp * 100) % 100 == 0)
394 if((temp * 10) % 10 == 0)
399 function isInteger(s) {
400 if(typeof num_grp_sep != 'undefined' && typeof dec_sep != 'undefined')
402 s = unformatNumberNoParse(s, num_grp_sep, dec_sep).toString();
404 return /^[+-]?[0-9]*$/.test(s) ;
407 function isDecimal(s) {
408 if (typeof s == "string" && s == "") // bug# 46530, this is required in order to
409 return true; // not check empty decimal fields
411 if(typeof num_grp_sep != 'undefined' && typeof dec_sep != 'undefined')
413 s = unformatNumberNoParse(s, num_grp_sep, dec_sep).toString();
415 return /^[+-]?[0-9]+\.?[0-9]*$/.test(s) ;
418 function isNumeric(s) {
422 var date_reg_positions = {'Y': 1,'m': 2,'d': 3};
423 var date_reg_format = '([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})'
424 function isDate(dtStr) {
426 if(dtStr.length== 0) {
430 // Check that we have numbers
431 myregexp = new RegExp(date_reg_format)
432 if(!myregexp.test(dtStr))
439 var dateParts = dtStr.match(date_reg_format);
440 for(key in date_reg_positions) {
441 index = date_reg_positions[key];
443 m = dateParts[index];
444 } else if(key == 'd') {
445 d = dateParts[index];
447 y = dateParts[index];
451 // Check that date is real
452 var dd = new Date(y,m,0);
453 // reject negative years
456 // reject month less than 1 and greater than 12
459 // reject days less than 1 or days not in month (e.g. February 30th)
460 if (d < 1 || d > dd.getDate())
465 function getDateObject(dtStr) {
466 if(dtStr.length== 0) {
470 myregexp = new RegExp(date_reg_format)
472 if(myregexp.exec(dtStr)) var dt = myregexp.exec(dtStr)
475 var yr = dt[date_reg_positions['Y']];
476 var mh = dt[date_reg_positions['m']];
477 var dy = dt[date_reg_positions['d']];
478 var dtar = dtStr.split(' ');
479 if(typeof(dtar[1])!='undefined' && isTime(dtar[1])) {//if it is a timedate, we should make date1 to have time value
480 var t1 = dtar[1].replace(/am/i,' AM');
481 var t1 = t1.replace(/pm/i,' PM');
482 //bug #37977: where time format 23.00 causes java script error
483 t1=t1.replace(/\./, ':');
484 date1 = new Date(Date.parse(mh+'/'+dy+ '/'+yr+' '+t1));
488 var date1 = new Date();
489 date1.setFullYear(yr); // xxxx 4 char year
490 date1.setMonth(mh-1); // 0-11 Bug 4048: javascript Date obj months are 0-index
491 date1.setDate(dy); // 1-31
496 function isBefore(value1, value2) {
497 var d1 = getDateObject(value1);
498 var d2 = getDateObject(value2);
499 if(typeof(d2)=='boolean') {// if d2 is not set, we should let it pass, the d2 may not need to be set. the empty check should not be done here.
505 function isValidEmail(emailStr) {
507 if(emailStr.length== 0) {
510 // cn: bug 7128, a period at the end of the string mangles checks. (switched to accept spaces and delimiters)
511 var lastChar = emailStr.charAt(emailStr.length - 1);
512 if(!lastChar.match(/[^\.]/i)) {
515 //bug 40068, According to rules in page 6 of http://www.apps.ietf.org/rfc/rfc3696.html#sec-3,
516 //first character of local part of an email address
517 //should not be a period i.e. '.'
519 var firstLocalChar=emailStr.charAt(0);
520 if(firstLocalChar.match(/\./)){
524 //bug 40068, According to rules in page 6 of http://www.apps.ietf.org/rfc/rfc3696.html#sec-3,
525 //last character of local part of an email address
526 //should not be a period i.e. '.'
528 var pos=emailStr.lastIndexOf("@");
529 var localPart = emailStr.substr(0, pos);
530 var lastLocalChar=localPart.charAt(localPart.length - 1);
531 if(lastLocalChar.match(/\./)){
538 while ((results = reg.exec(emailStr)) != null) {
539 var original = results[0];
540 parsedResult = results[0].replace(';', '::;::');
541 emailStr = emailStr.replace (original, parsedResult);
545 while ((results = reg.exec(emailStr)) != null) {
546 var original = results[0];
547 //Check if we were using ; as a delimiter. If so, skip the commas
548 if(original.indexOf("::;::") == -1) {
549 var parsedResult = results[0].replace(',', '::;::');
550 emailStr = emailStr.replace (original, parsedResult);
554 // mfh: bug 15010 - more practical implementation of RFC 2822 from http://www.regular-expressions.info/email.html, modifed to accept CAPITAL LETTERS
555 //if(!/[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?/.test(emailStr))
558 //bug 40068, According to rules in page 6 of http://www.apps.ietf.org/rfc/rfc3696.html#sec-3,
559 //allowed special characters ! # $ % & ' * + - / = ? ^ _ ` . { | } ~ in local part
560 var emailArr = emailStr.split(/::;::/);
561 for (var i = 0; i < emailArr.length; i++) {
562 var emailAddress = emailArr[i];
563 if (trim(emailAddress) != '') {
564 if(!/^\s*[\w.%+\-&'#!\$\*=\?\^_`\{\}~\/]+@([A-Z0-9-]+\.)*[A-Z0-9-]+\.[\w-]{2,}\s*$/i.test(emailAddress) &&
565 !/^.*<[A-Z0-9._%+\-&'#!\$\*=\?\^_`\{\}~]+?@([A-Z0-9-]+\.)*[A-Z0-9-]+\.[\w-]{2,}>\s*$/i.test(emailAddress)) {
574 function isValidPhone(phoneStr) {
575 if(phoneStr.length== 0) {
578 if(!/^[0-9\-\(\)\s]+$/.test(phoneStr))
582 function isFloat(floatStr) {
583 if(floatStr.length== 0) {
586 if(!(typeof(num_grp_sep)=='undefined' || typeof(dec_sep)=='undefined')) {
587 floatStr = unformatNumberNoParse(floatStr, num_grp_sep, dec_sep).toString();
590 return /^(-)?[0-9\.]+$/.test(floatStr);
592 function isDBName(str) {
597 // must start with a letter
598 if(!/^[a-zA-Z][a-zA-Z\_0-9]*$/.test(str))
602 var time_reg_format = "[0-9]{1,2}\:[0-9]{2}";
603 function isTime(timeStr) {
604 var time_reg_format = "[0-9]{1,2}\:[0-9]{2}";
605 time_reg_format = time_reg_format.replace('([ap]m)', '');
606 time_reg_format = time_reg_format.replace('([AP]M)', '');
607 if(timeStr.length== 0){
610 //we now support multiple time formats
611 myregexp = new RegExp(time_reg_format)
612 if(!myregexp.test(timeStr))
618 function inRange(value, min, max) {
619 if (typeof num_grp_sep != 'undefined' && typeof dec_sep != 'undefined')
620 value = unformatNumberNoParse(value, num_grp_sep, dec_sep).toString();
621 return value >= min && value <= max;
624 function bothExist(item1, item2) {
625 if(typeof item1 == 'undefined') { return false; }
626 if(typeof item2 == 'undefined') { return false; }
627 if((item1 == '' && item2 != '') || (item1 != '' && item2 == '') ) { return false; }
631 trim = YAHOO.lang.trim;
634 function check_form(formname) {
635 if (typeof(siw) != 'undefined' && siw
636 && typeof(siw.selectingSomething) != 'undefined' && siw.selectingSomething)
638 return validate_form(formname, '');
641 function add_error_style(formname, input, txt, flash) {
642 var raiseFlag = false;
643 if (typeof flash == "undefined")
646 inputHandle = typeof input == "object" ? input : document.forms[formname][input];
647 style = get_current_bgcolor(inputHandle);
649 // strip off the colon at the end of the warning strings
650 if ( txt.substring(txt.length-1) == ':' )
651 txt = txt.substring(0,txt.length-1)
653 // Bug 28249 - To help avoid duplicate messages for an element, strip off extra messages and
654 // match on the field name itself
655 requiredTxt = SUGAR.language.get('app_strings', 'ERR_MISSING_REQUIRED_FIELDS');
656 invalidTxt = SUGAR.language.get('app_strings', 'ERR_INVALID_VALUE');
657 nomatchTxt = SUGAR.language.get('app_strings', 'ERR_SQS_NO_MATCH_FIELD');
658 matchTxt = txt.replace(requiredTxt,'').replace(invalidTxt,'').replace(nomatchTxt,'');
660 YUI().use('node', function (Y) {
661 Y.one(inputHandle).get('parentNode').get('children').each(function(node, index, nodeList){
662 if(node.hasClass('validation-message') && node.get('text').search(matchTxt)){
669 errorTextNode = document.createElement('div');
670 errorTextNode.className = 'required validation-message';
671 errorTextNode.innerHTML = txt;
672 if ( inputHandle.parentNode.className.indexOf('x-form-field-wrap') != -1 ) {
673 inputHandle.parentNode.parentNode.appendChild(errorTextNode);
676 inputHandle.parentNode.appendChild(errorTextNode);
679 inputHandle.style.backgroundColor = "#FF0000";
680 inputsWithErrors.push(inputHandle);
684 // We only need to setup the flashy-flashy on the first entry, it loops through all fields automatically
685 if ( inputsWithErrors.length == 1 ) {
686 for(wp = 1; wp <= 10; wp++) {
687 window.setTimeout('fade_error_style(style, '+wp*10+')',1000+(wp*50));
690 if(typeof (window[formname + "_tabs"]) != "undefined") {
691 var tabView = window[formname + "_tabs"];
692 var parentDiv = YAHOO.util.Dom.getAncestorByTagName(inputHandle, "div");
694 var tabs = tabView.get("tabs");
695 for (var i in tabs) {
696 if (tabs[i].get("contentEl") == parentDiv
697 || YAHOO.util.Dom.isAncestor(tabs[i].get("contentEl"), inputHandle))
699 tabs[i].get("labelEl").style.color = "red";
700 if ( inputsWithErrors.length == 1 )
701 tabView.selectTab(i);
706 window.setTimeout("inputsWithErrors[" + (inputsWithErrors.length - 1) + "].style.backgroundColor = '';", 2000);
710 // Catch errors here so we don't allow an incomplete record through the javascript validation
716 * removes all error messages for the current form
718 function clear_all_errors() {
719 for(var wp = 0; wp < inputsWithErrors.length; wp++) {
720 if(typeof(inputsWithErrors[wp]) !='undefined' && typeof inputsWithErrors[wp].parentNode != 'undefined' && inputsWithErrors[wp].parentNode != null) {
721 if ( inputsWithErrors[wp].parentNode.className.indexOf('x-form-field-wrap') != -1 )
723 inputsWithErrors[wp].parentNode.parentNode.removeChild(inputsWithErrors[wp].parentNode.parentNode.lastChild);
727 inputsWithErrors[wp].parentNode.removeChild(inputsWithErrors[wp].parentNode.lastChild);
731 if (inputsWithErrors.length == 0) return;
733 if ( YAHOO.util.Dom.getAncestorByTagName(inputsWithErrors[0], "form") ) {
734 var formname = YAHOO.util.Dom.getAncestorByTagName(inputsWithErrors[0], "form").getAttribute("name");
735 if(typeof (window[formname + "_tabs"]) != "undefined") {
736 var tabView = window[formname + "_tabs"];
738 var tabs = tabView.get("tabs");
739 for (var i in tabs) {
740 if (typeof tabs[i] == "object")
741 tabs[i].get("labelEl").style.color = "";
745 inputsWithErrors = new Array();
749 function get_current_bgcolor(input) {
750 if(input.currentStyle) {// ie
751 style = input.currentStyle.backgroundColor;
752 return style.substring(1,7);
756 styleRGB = document.defaultView.getComputedStyle(input, '').getPropertyValue("background-color");
757 comma = styleRGB.indexOf(',');
758 style += dec2hex(styleRGB.substring(4, comma));
759 commaPrevious = comma;
760 comma = styleRGB.indexOf(',', commaPrevious+1);
761 style += dec2hex(styleRGB.substring(commaPrevious+2, comma));
762 style += dec2hex(styleRGB.substring(comma+2, styleRGB.lastIndexOf(')')));
767 function hex2dec(hex){return(parseInt(hex,16));}
768 var hexDigit=new Array("0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F");
769 function dec2hex(dec){return(hexDigit[dec>>4]+hexDigit[dec&15]);}
771 function fade_error_style(normalStyle, percent) {
772 errorStyle = 'c60c30';
773 var r1 = hex2dec(errorStyle.slice(0,2));
774 var g1 = hex2dec(errorStyle.slice(2,4));
775 var b1 = hex2dec(errorStyle.slice(4,6));
777 var r2 = hex2dec(normalStyle.slice(0,2));
778 var g2 = hex2dec(normalStyle.slice(2,4));
779 var b2 = hex2dec(normalStyle.slice(4,6));
782 var pc = percent / 100;
784 r= Math.floor(r1+(pc*(r2-r1)) + .5);
785 g= Math.floor(g1+(pc*(g2-g1)) + .5);
786 b= Math.floor(b1+(pc*(b2-b1)) + .5);
788 for(var wp = 0; wp < inputsWithErrors.length; wp++) {
789 inputsWithErrors[wp].style.backgroundColor = "#" + dec2hex(r) + dec2hex(g) + dec2hex(b);
793 function isFieldTypeExceptFromEmptyCheck(fieldType)
796 var exemptList = ['bool','file'];
797 for(var i=0;i<exemptList.length;i++)
799 if(fieldType == exemptList[i])
804 function validate_form(formname, startsWith){
805 requiredTxt = SUGAR.language.get('app_strings', 'ERR_MISSING_REQUIRED_FIELDS');
806 invalidTxt = SUGAR.language.get('app_strings', 'ERR_INVALID_VALUE');
808 if ( typeof (formname) == 'undefined')
812 if ( typeof (validate[formname]) == 'undefined')
814 disableOnUnloadEditView(document.forms[formname]);
818 var form = document.forms[formname];
821 var _date = new Date();
822 if(_date.getTime() < (lastSubmitTime + 2000) && startsWith == oldStartsWith) { // ignore submits for the next 2 seconds
825 lastSubmitTime = _date.getTime();
826 oldStartsWith = startsWith;
828 clear_all_errors(); // remove previous error messages
830 inputsWithErrors = new Array();
831 for(var i = 0; i < validate[formname].length; i++){
832 if(validate[formname][i][nameIndex].indexOf(startsWith) == 0){
833 if(typeof form[validate[formname][i][nameIndex]] != 'undefined' && typeof form[validate[formname][i][nameIndex]].value != 'undefined'){
836 //If a field is not required and it is blank or is binarydependant, skip validation.
837 //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
838 if(!validate[formname][i][requiredIndex] && trim(form[validate[formname][i][nameIndex]].value) == '' && (typeof(validate[formname][i][jstypeIndex]) != 'undefined' && validate[formname][i][jstypeIndex] != 'binarydep'))
843 if(validate[formname][i][requiredIndex]
844 && !isFieldTypeExceptFromEmptyCheck(validate[formname][i][typeIndex])
846 if(typeof form[validate[formname][i][nameIndex]] == 'undefined' || trim(form[validate[formname][i][nameIndex]].value) == ""){
847 add_error_style(formname, validate[formname][i][nameIndex], requiredTxt +' ' + validate[formname][i][msgIndex]);
852 switch(validate[formname][i][typeIndex]){
854 if(!isValidEmail(trim(form[validate[formname][i][nameIndex]].value))){
856 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
860 if( !isTime(trim(form[validate[formname][i][nameIndex]].value))){
862 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
864 case 'date': if(!isDate(trim(form[validate[formname][i][nameIndex]].value))){
866 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
871 if(!isDBName(trim(form[validate[formname][i][nameIndex]].value))){
873 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
879 var file_input = form[validate[formname][i][nameIndex] + '_file'];
880 if( file_input && validate[formname][i][requiredIndex] && trim(file_input.value) == "" && !file_input.disabled ) {
882 add_error_style(formname, validate[formname][i][nameIndex], requiredTxt + " " + validate[formname][i][msgIndex]);
886 if(!isInteger(trim(form[validate[formname][i][nameIndex]].value))){
888 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
892 if(!isDecimal(trim(form[validate[formname][i][nameIndex]].value))){
894 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
899 if(!isFloat(trim(form[validate[formname][i][nameIndex]].value))){
901 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
905 var div_element_id = formname + '_' + form[validate[formname][i][nameIndex]].name + '_operation_div';
906 var input_elements = YAHOO.util.Selector.query('input', document.getElementById(div_element_id));
907 var primary_field_id = '';
908 var validation_passed = false;
909 var replace_selected = false;
911 //Loop through the option elements (replace or add currently)
912 for(t in input_elements) {
913 if(input_elements[t].type && input_elements[t].type == 'radio' && input_elements[t].checked == true && input_elements[t].value == 'replace') {
915 //Now find where the primary radio button is and if a value has been set
916 var radio_elements = YAHOO.util.Selector.query('input[type=radio]', document.getElementById(formname + '_team_name_table'));
918 for(var x = 0; x < radio_elements.length; x++) {
919 if(radio_elements[x].name != 'team_name_type') {
920 primary_field_id = 'team_name_collection_' + radio_elements[x].value;
921 if(radio_elements[x].checked) {
922 replace_selected = true;
923 if(trim(document.forms[formname].elements[primary_field_id].value) != '') {
924 validation_passed = true;
927 } else if(trim(document.forms[formname].elements[primary_field_id].value) != '') {
928 replace_selected = true;
935 if(replace_selected && !validation_passed) {
936 add_error_style(formname, primary_field_id, SUGAR.language.get('app_strings', 'ERR_NO_PRIMARY_TEAM_SPECIFIED'));
941 var table_element_id = formname + '_' + form[validate[formname][i][nameIndex]].name + '_table';
942 if(document.getElementById(table_element_id)) {
943 var input_elements = YAHOO.util.Selector.query('input[type=radio]', document.getElementById(table_element_id));
944 var has_primary = false;
945 var primary_field_id = form[validate[formname][i][nameIndex]].name + '_collection_0';
947 for(t in input_elements) {
948 primary_field_id = form[validate[formname][i][nameIndex]].name + '_collection_' + input_elements[t].value;
949 if(input_elements[t].type && input_elements[t].type == 'radio' && input_elements[t].checked == true) {
950 if(document.forms[formname].elements[primary_field_id].value != '') {
959 var field_id = form[validate[formname][i][nameIndex]].name + '_collection_' + input_elements[0].value;
960 add_error_style(formname, field_id, SUGAR.language.get('app_strings', 'ERR_NO_PRIMARY_TEAM_SPECIFIED'));
966 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex]);
970 if(typeof validate[formname][i][jstypeIndex] != 'undefined'/* && !isError*/){
972 switch(validate[formname][i][jstypeIndex]){
974 if(!inRange(trim(form[validate[formname][i][nameIndex]].value), validate[formname][i][minIndex], validate[formname][i][maxIndex])){
976 var lbl_validate_range = SUGAR.language.get('app_strings', 'LBL_VALIDATE_RANGE');
977 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] + ") ");
981 compareTo = form[validate[formname][i][compareToIndex]];
982 if( typeof compareTo != 'undefined'){
983 if(trim(compareTo.value) != '' || (validate[formname][i][allowblank] != 'true') ) {
984 date2 = trim(compareTo.value);
985 date1 = trim(form[validate[formname][i][nameIndex]].value);
987 if(trim(date1).length != 0 && !isBefore(date1,date2)){
990 //jc:#12287 - adding translation for the is not before message
991 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex] + "(" + date1 + ") " + SUGAR.language.get('app_strings', 'MSG_IS_NOT_BEFORE') + ' ' +date2);
997 value=unformatNumber(trim(form[validate[formname][i][nameIndex]].value), num_grp_sep, dec_sep);
998 maximum = parseFloat(validate[formname][i][maxIndex]);
999 if( typeof maximum != 'undefined'){
1002 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]);
1007 value=unformatNumber(trim(form[validate[formname][i][nameIndex]].value), num_grp_sep, dec_sep);
1008 minimum = parseFloat(validate[formname][i][minIndex]);
1009 if( typeof minimum != 'undefined'){
1012 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'));
1017 compareTo = form[validate[formname][i][compareToIndex]];
1018 if( typeof compareTo != 'undefined') {
1019 item1 = trim(form[validate[formname][i][nameIndex]].value);
1020 item2 = trim(compareTo.value);
1021 if(!bothExist(item1, item2)) {
1023 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex]);
1028 compareTo = form[validate[formname][i][compareToIndex]];
1029 if( typeof compareTo != 'undefined') {
1030 item1 = trim(form[validate[formname][i][nameIndex]].value);
1031 item2 = trim(compareTo.value);
1032 if(!bothExist(item1, item2) || item1 != item2) {
1034 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex]);
1039 arr = eval(validate[formname][i][arrIndex]);
1040 operator = validate[formname][i][operatorIndex];
1041 item1 = trim(form[validate[formname][i][nameIndex]].value);
1042 if (operator.charAt(0) == 'u') {
1043 item1 = item1.toUpperCase();
1044 operator = operator.substring(1);
1045 } else if (operator.charAt(0) == 'l') {
1046 item1 = item1.toLowerCase();
1047 operator = operator.substring(1);
1049 for(j = 0; j < arr.length; j++){
1051 if((operator == "==" && val == item1) || (operator == "!=" && val != item1)){
1053 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
1058 if(trim(form[validate[formname][i][nameIndex]].value) == 'false'){
1059 //Fake an error so form does not submit
1069 /* nsingh: BUG#15102
1070 Check min max default field logic.
1071 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.*/
1072 if(formsWithFieldLogic){
1073 var invalidLogic=false;
1074 if(formsWithFieldLogic.min && formsWithFieldLogic.max && formsWithFieldLogic._default) {
1075 var showErrorsOn={min:{value:'min', show:false, obj:formsWithFieldLogic.min.value},
1076 max:{value:'max',show:false, obj:formsWithFieldLogic.max.value},
1077 _default:{value:'default',show:false, obj:formsWithFieldLogic._default.value},
1078 len:{value:'len', show:false, obj:parseInt(formsWithFieldLogic.len.value,10)}};
1080 var min = (formsWithFieldLogic.min.value !='') ? parseFloat(formsWithFieldLogic.min.value) : 'undef';
1081 var max = (formsWithFieldLogic.max.value !='') ? parseFloat(formsWithFieldLogic.max.value) : 'undef';
1082 var _default = (formsWithFieldLogic._default.value!='')? parseFloat(formsWithFieldLogic._default.value) : 'undef';
1084 /*Check all lengths are <= max size.*/
1085 for(var i in showErrorsOn){
1086 if(showErrorsOn[i].value!='len' && showErrorsOn[i].obj.length > showErrorsOn.len.obj){
1088 showErrorsOn[i].show=true;
1089 showErrorsOn.len.show=true;
1093 if(min!='undef' && max!='undef' && _default!='undef'){
1094 if(!inRange(_default,min,max)){
1096 showErrorsOn.min.show=true;
1097 showErrorsOn.max.show=true;
1098 showErrorsOn._default.show=true;
1101 if(min!='undef' && max!= 'undef' && min > max){
1102 invalidLogic = true;
1103 showErrorsOn.min.show=true;
1104 showErrorsOn.max.show=true;
1106 if(min!='undef' && _default!='undef' && _default < min){
1108 invalidLogic = true;
1109 showErrorsOn.min.show=true;
1110 showErrorsOn._default.show=true;
1112 if(max!='undef' && _default !='undef' && _default>max){
1114 invalidLogic = true;
1115 showErrorsOn.max.show=true;
1116 showErrorsOn._default.show=true;
1121 for(var error in showErrorsOn)
1122 if(showErrorsOn[error].show)
1123 add_error_style(formname,showErrorsOn[error].value, formsWithFieldLogic.msg);
1128 formsWithFieldLogic = null;
1131 if(formWithPrecision){
1132 if (!isValidPrecision(formWithPrecision.float.value, formWithPrecision.precision.value)){
1134 add_error_style(formname, 'default', SUGAR.language.get('app_strings', 'ERR_COMPATIBLE_PRECISION_VALUE'));
1142 if (isError == true) {
1144 if (self.pageYOffset) // all except Explorer
1146 nwX = self.pageXOffset;
1147 seX = self.innerWidth;
1148 nwY = self.pageYOffset;
1149 seY = self.innerHeight;
1151 else if (document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
1153 nwX = document.documentElement.scrollLeft;
1154 seX = document.documentElement.clientWidth;
1155 nwY = document.documentElement.scrollTop;
1156 seY = document.documentElement.clientHeight;
1158 else if (document.body) // all other Explorers
1160 nwX = document.body.scrollLeft;
1161 seX = document.body.clientWidth;
1162 nwY = document.body.scrollTop;
1163 seY = document.body.clientHeight;
1166 var inView = true; // is there an error within viewport of browser
1167 for(var wp = 0; wp < inputsWithErrors.length; wp++) {
1168 var elementCoor = findElementPos(inputsWithErrors[wp]);
1169 if(!(elementCoor.x >= nwX && elementCoor.y >= nwY &&
1170 elementCoor.x <= seX && elementCoor.y <= seY)) { // if input is not within viewport
1172 scrollToTop = elementCoor.y - 75;
1173 scrollToLeft = elementCoor.x - 75;
1175 else { // on first input within viewport, don't scroll
1181 if(!inView) window.scrollTo(scrollToLeft,scrollToTop);
1186 disableOnUnloadEditView(form);
1193 * This array is used to remember mark status of rows in browse mode
1195 var marked_row = new Array;
1199 * Sets/unsets the pointer and marker in browse mode
1201 * @param object the table row
1202 * @param interger the row number
1203 * @param string the action calling this script (over, out or click)
1204 * @param string the default background color
1205 * @param string the color to use for mouseover
1206 * @param string the color to use for marking a row
1208 * @return boolean whether pointer is set or not
1210 function setPointer(theRow, theRowNum, theAction, theDefaultColor, thePointerColor, theMarkColor) {
1211 var theCells = null;
1213 // 1. Pointer and mark feature are disabled or the browser can't get the
1215 if ((thePointerColor == '' && theMarkColor == '')
1216 || typeof(theRow.style) == 'undefined') {
1220 // 2. Gets the current row and exits if the browser can't get it
1221 if (typeof(document.getElementsByTagName) != 'undefined') {
1222 theCells = theRow.getElementsByTagName('td');
1224 else if (typeof(theRow.cells) != 'undefined') {
1225 theCells = theRow.cells;
1231 // 3. Gets the current color...
1232 var rowCellsCnt = theCells.length;
1233 var domDetect = null;
1234 var currentColor = null;
1235 var newColor = null;
1236 // 3.1 ... with DOM compatible browsers except Opera that does not return
1237 // valid values with "getAttribute"
1238 if (typeof(window.opera) == 'undefined'
1239 && typeof(theCells[0].getAttribute) != 'undefined') {
1240 currentColor = theCells[0].getAttribute('bgcolor');
1243 // 3.2 ... with other browsers
1245 currentColor = theCells[0].style.backgroundColor;
1249 // 4. Defines the new color
1250 // 4.1 Current color is the default one
1251 if (currentColor == ''
1252 || (currentColor!= null && (currentColor.toLowerCase() == theDefaultColor.toLowerCase()))) {
1253 if (theAction == 'over' && thePointerColor != '') {
1254 newColor = thePointerColor;
1256 else if (theAction == 'click' && theMarkColor != '') {
1257 newColor = theMarkColor;
1258 marked_row[theRowNum] = true;
1261 // 4.1.2 Current color is the pointer one
1262 else if (currentColor!= null && (currentColor.toLowerCase() == thePointerColor.toLowerCase())
1263 && (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])) {
1264 if (theAction == 'out') {
1265 newColor = theDefaultColor;
1267 else if (theAction == 'click' && theMarkColor != '') {
1268 newColor = theMarkColor;
1269 marked_row[theRowNum] = true;
1272 // 4.1.3 Current color is the marker one
1273 else if (currentColor!= null && (currentColor.toLowerCase() == theMarkColor.toLowerCase())) {
1274 if (theAction == 'click') {
1275 newColor = (thePointerColor != '')
1278 marked_row[theRowNum] = (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])
1284 // 5. Sets the new color...
1287 // 5.1 ... with DOM compatible browsers except Opera
1289 for (c = 0; c < rowCellsCnt; c++) {
1290 theCells[c].setAttribute('bgcolor', newColor, 0);
1293 // 5.2 ... with other browsers
1295 for (c = 0; c < rowCellsCnt; c++) {
1296 theCells[c].style.backgroundColor = newColor;
1302 } // end of the 'setPointer()' function
1306 * listbox redirection
1308 function goToUrl(selObj, goToLocation) {
1309 eval("document.location.href = '" + goToLocation + "pos=" + selObj.options[selObj.selectedIndex].value + "'");
1314 var json_objects = new Object();
1316 function getXMLHTTPinstance() {
1317 var xmlhttp = false;
1318 var userAgent = navigator.userAgent.toLowerCase() ;
1320 // IE Check supports ActiveX controls
1321 if (userAgent.indexOf("msie") != -1 && userAgent.indexOf("mac") == -1 && userAgent.indexOf("opera") == -1) {
1322 var version = navigator.appVersion.match(/MSIE (.\..)/)[1] ;
1323 if(version >= 5.5 ) {
1325 xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
1329 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
1338 if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
1339 xmlhttp = new XMLHttpRequest();
1344 // NOW LOAD THE OBJECT..
1345 var global_xmlhttp = getXMLHTTPinstance();
1347 function http_fetch_sync(url,post_data) {
1348 global_xmlhttp = getXMLHTTPinstance();
1351 if(typeof(post_data) != 'undefined') method = 'POST';
1353 global_xmlhttp.open(method, url,false);
1356 alert('message:'+e.message+":url:"+url);
1358 if(method == 'POST') {
1359 global_xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
1362 global_xmlhttp.send(post_data);
1364 if (SUGAR.util.isLoginPage(global_xmlhttp.responseText))
1367 var args = {"responseText" : global_xmlhttp.responseText,
1368 "responseXML" : global_xmlhttp.responseXML,
1369 "request_id" : typeof(request_id) != "undefined" ? request_id : 0};
1373 // this is a GET unless post_data is defined
1375 function http_fetch_async(url,callback,request_id,post_data) {
1377 if(typeof(post_data) != 'undefined') {
1382 global_xmlhttp.open(method, url,true);
1385 alert('message:'+e.message+":url:"+url);
1387 if(method == 'POST') {
1388 global_xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
1390 global_xmlhttp.onreadystatechange = function() {
1391 if(global_xmlhttp.readyState==4) {
1392 if(global_xmlhttp.status == 200) {
1393 if (SUGAR.util.isLoginPage(global_xmlhttp.responseText))
1395 var args = {"responseText" : global_xmlhttp.responseText,
1396 "responseXML" : global_xmlhttp.responseXML,
1397 "request_id" : request_id };
1398 callback.call(document,args);
1401 alert("There was a problem retrieving the XML data:\n" + global_xmlhttp.statusText);
1405 global_xmlhttp.send(post_data);
1408 function insert_at_cursor(field, value) {
1410 if (document.selection) {
1412 sel = document.selection.createRange();
1416 else if(field.selectionStart || field.selectionStart == '0') {
1417 var start_pos = field.selectionStart;
1418 var end_pos = field.selectionEnd;
1419 field.value = field.value.substring(0, start_pos) + value + field.value.substring(end_pos, field.value.length);
1422 field.value += value;
1426 function checkParentType(type,button) {
1427 if(button == null) {
1430 if(typeof disabledModules != 'undefined' && typeof(disabledModules[type]) != 'undefined') {
1431 button.disabled='disabled';
1434 button.disabled = false;
1438 function parseDate(input, format) {
1440 format = format.replace(/%/g, '');
1441 sep = format.charAt(1);
1442 yAt = format.indexOf('Y')
1443 // 1-1-06 or 1-12-06 or 1-1-2006 or 1-12-2006
1444 if(date.match(/^\d{1,2}[\/-]\d{1,2}[\/-]\d{2,4}$/) && yAt == 4) {
1445 if(date.match(/^\d{1}[\/-].*$/)) date = '0' + date;
1446 if(date.match(/^\d{2}[\/-]\d{1}[\/-].*$/)) date = date.substring(0,3) + '0' + date.substring(3,date.length);
1447 if(date.match(/^\d{2}[\/-]\d{2}[\/-]\d{2}$/)) date = date.substring(0,6) + '20' + date.substring(6,date.length);
1449 // 06-11-1 or 06-1-1
1450 else if(date.match(/^\d{2,4}[\/-]\d{1,2}[\/-]\d{1,2}$/)) {
1451 if(date.match(/^\d{2}[\/-].*$/)) date = '20' + date;
1452 if(date.match(/^\d{4}[\/-]\d{1}[\/-].*$/)) date = date.substring(0,5) + '0' + date.substring(5,date.length);
1453 if(date.match(/^\d{4}[\/-]\d{2}[\/-]\d{1}$/)) date = date.substring(0,8) + '0' + date.substring(8,date.length);
1455 else if(date.match(/^\d{4,8}$/)) { // digits only
1457 if(date.match(/^\d{8}$/)) digits = 8;// match for 8 digits
1458 else if(date.match(/\d{6}/)) digits = 6;// match for 5 digits
1459 else if(date.match(/\d{4}/)) digits = 4;// match for 5 digits
1460 else if(date.match(/\d{5}/)) digits = 5;// match for 5 digits
1465 case 4: date = '20' + date.substring(0,2) + sep + '0' + date.substring(2, 3) + sep + '0' + date.substring(3,4); break;
1466 case 5: date = '20' + date.substring(0,2) + sep + date.substring(2, 4) + sep + '0' + date.substring(4,5); break;
1467 case 6: date = '20' + date.substring(0,2) + sep + date.substring(2, 4) + sep + date.substring(4,6); break;
1468 case 8: date = date.substring(0,4) + sep + date.substring(4, 6) + sep + date.substring(6,8); break;
1473 case 4: date = '0' + date.substring(0,1) + sep + '20' + date.substring(1, 3) + sep + '0' + date.substring(3,4); break;
1474 case 5: date = date.substring(0,2) + sep + '20' + date.substring(2, 4) + sep + '0' + date.substring(4,5); break;
1475 case 6: date = date.substring(0,2) + sep + '20' + date.substring(2, 4) + sep + date.substring(4,6); break;
1476 case 8: date = date.substring(0,2) + sep + date.substring(2, 6) + sep + date.substring(6,8); break;
1480 case 4: date = '0' + date.substring(0,1) + sep + '0' + date.substring(1, 2) + sep + '20' + date.substring(2,4); break;
1481 case 5: date = '0' + date.substring(0,1) + sep + date.substring(1, 3) + sep + '20' + date.substring(3,5); break;
1482 case 6: date = date.substring(0,2) + sep + date.substring(2, 4) + sep + '20' + date.substring(4,6); break;
1483 case 8: date = date.substring(0,2) + sep + date.substring(2, 4) + sep + date.substring(4,8); break;
1488 date = date.replace(/[\/-]/g, sep);
1492 // find obj's position
1493 function findElementPos(obj) {
1496 if (obj.offsetParent) {
1497 while (obj.offsetParent) {
1498 x += obj.offsetLeft;
1500 obj = obj.offsetParent;
1502 }//if offsetParent exists
1503 else if (obj.x && obj.y) {
1507 return new coordinate(x, y);
1511 // get dimensions of the browser window
1512 function getClientDim() {
1513 var nwX, nwY, seX, seY;
1514 if (self.pageYOffset) // all except Explorer
1516 nwX = self.pageXOffset;
1517 seX = self.innerWidth + nwX;
1518 nwY = self.pageYOffset;
1519 seY = self.innerHeight + nwY;
1521 else if (document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
1523 nwX = document.documentElement.scrollLeft;
1524 seX = document.documentElement.clientWidth + nwX;
1525 nwY = document.documentElement.scrollTop;
1526 seY = document.documentElement.clientHeight + nwY;
1528 else if (document.body) // all other Explorers
1530 nwX = document.body.scrollLeft;
1531 seX = document.body.clientWidth + nwX;
1532 nwY = document.body.scrollTop;
1533 seY = document.body.clientHeight + nwY;
1535 return {'nw' : new coordinate(nwX, nwY), 'se' : new coordinate(seX, seY)};
1539 * stop propagation on events
1541 function freezeEvent(e) {
1543 if (e.preventDefault) e.preventDefault();
1544 e.returnValue = false;
1545 e.cancelBubble = true;
1546 if (e.stopPropagation) e.stopPropagation();
1555 function coordinate(_x, _y) {
1564 return new position(this.x + rh.x, this.y + rh.y);
1568 return new position(this.x + rh.x, this.y + rh.y);
1572 // sends theForm via AJAX and fills in the theDiv
1573 function sendAndRetrieve(theForm, theDiv, loadingStr) {
1574 function success(data) {
1575 document.getElementById(theDiv).innerHTML = data.responseText;
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 //save the form and redirect
1586 function sendAndRedirect(theForm, loadingStr, redirect_location) {
1587 function success(data) {
1588 if(redirect_location){
1589 location.href=redirect_location;
1591 ajaxStatus.hideStatus();
1593 if(typeof loadingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
1594 ajaxStatus.showStatus(loadingStr);
1595 YAHOO.util.Connect.setForm(theForm);
1596 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
1600 function saveForm(theForm, theDiv, loadingStr) {
1601 if(check_form(theForm)){
1602 for(i = 0; i < ajaxFormArray.length; i++){
1603 if(ajaxFormArray[i] == theForm){
1604 ajaxFormArray.splice(i, 1);
1607 return sendAndRetrieve(theForm, loadingStr, theDiv);
1613 // Builds a "snapshot" of the form, so we can use it to see if someone has changed it.
1614 function snapshotForm(theForm) {
1615 var snapshotTxt = '';
1616 var elemList = theForm.elements;
1620 for( var i = 0; i < elemList.length ; i++ ) {
1622 if ( typeof(elem.type) == 'undefined' ) {
1626 elemType = elem.type.toLowerCase();
1628 snapshotTxt = snapshotTxt + elem.name;
1630 if ( elemType == 'text' || elemType == 'textarea' || elemType == 'password' ) {
1631 snapshotTxt = snapshotTxt + elem.value;
1633 else if ( elemType == 'select' || elemType == 'select-one' || elemType == 'select-multiple' ) {
1634 var optionList = elem.options;
1635 for ( var ii = 0 ; ii < optionList.length ; ii++ ) {
1636 if ( optionList[ii].selected ) {
1637 snapshotTxt = snapshotTxt + optionList[ii].value;
1641 else if ( elemType == 'radio' || elemType == 'checkbox' ) {
1642 if ( elem.selected ) {
1643 snapshotTxt = snapshotTxt + 'checked';
1646 else if ( elemType == 'hidden' ) {
1647 snapshotTxt = snapshotTxt + elem.value;
1654 function initEditView(theForm) {
1655 if (SUGAR.util.ajaxCallInProgress()) {
1656 window.setTimeout(function(){initEditView(theForm);}, 100);
1660 if ( theForm == null || theForm.id == null ) {
1661 // Not much we can do here.
1665 // we don't need to check if the data is changed in the search popup
1666 if (theForm.id == 'popup_query_form' || theForm.id == 'MassUpdate') {
1669 if ( typeof editViewSnapshots == 'undefined' || editViewSnapshots == null ) {
1670 editViewSnapshots = new Object();
1672 if ( typeof SUGAR.loadedForms == 'undefined' || SUGAR.loadedForms == null) {
1673 SUGAR.loadedForms = new Object();
1676 editViewSnapshots[theForm.id] = snapshotForm(theForm);
1677 SUGAR.loadedForms[theForm.id] = true;
1680 function onUnloadEditView(theForm) {
1682 var dataHasChanged = false;
1684 if ( typeof editViewSnapshots == 'undefined' ) {
1685 // No snapshots, move along
1689 if ( typeof theForm == 'undefined' ) {
1690 // Need to check all editViewSnapshots
1691 for ( var idx in editViewSnapshots ) {
1693 theForm = document.getElementById(idx);
1694 // console.log('DEBUG: Checking all forms '+theForm.id);
1695 if ( theForm == null
1696 || typeof editViewSnapshots[theForm.id] == 'undefined'
1697 || editViewSnapshots[theForm.id] == null
1698 || !SUGAR.loadedForms[theForm.id]) {
1702 var snap = snapshotForm(theForm);
1703 if ( editViewSnapshots[theForm.id] != snap ) {
1704 dataHasChanged = true;
1708 // Just need to check a single form for changes
1709 if ( editViewSnapshots == null || typeof theForm.id == 'undefined' || typeof editViewSnapshots[theForm.id] == 'undefined' || editViewSnapshots[theForm.id] == null ) {
1713 // console.log('DEBUG: Checking one form '+theForm.id);
1714 if ( editViewSnapshots[theForm.id] != snapshotForm(theForm) ) {
1715 // Data has changed.
1716 dataHasChanged = true;
1720 if ( dataHasChanged == true ) {
1721 return SUGAR.language.get('app_strings','WARN_UNSAVED_CHANGES');
1728 function disableOnUnloadEditView(theForm) {
1729 // If you don't pass anything in, it disables all checking
1730 if ( typeof theForm == 'undefined' || typeof editViewSnapshots == 'undefined' || theForm == null || editViewSnapshots == null) {
1731 window.onbeforeunload = null;
1732 editViewSnapshots = null;
1734 // console.log('DEBUG: Disabling all edit view checks');
1737 // Otherwise, it just disables it for this form
1738 if ( typeof(theForm.id) != 'undefined' && typeof(editViewSnapshots[theForm.id]) != 'undefined' ) {
1739 editViewSnapshots[theForm.id] = null;
1742 // console.log('DEBUG : Disabling just checks for '+theForm.id);
1748 * save some forms using an ajax call
1749 * theForms - the ids of all of theh forms to save
1750 * savingStr - the string to display when saving the form
1751 * completeStr - the string to display when the form has been saved
1753 function saveForms( savingStr, completeStr) {
1755 theForms = ajaxFormArray;
1756 function success(data) {
1757 var theForm = document.getElementById(ajaxFormArray[0]);
1758 document.getElementById('multiedit_'+theForm.id).innerHTML = data.responseText;
1759 var saveAllButton = document.getElementById('ajaxsaveall');
1760 ajaxFormArray.splice(index, 1);
1761 if(saveAllButton && ajaxFormArray.length <= 1){
1762 saveAllButton.style.visibility = 'hidden';
1765 if(index == theForms.length){
1766 ajaxStatus.showStatus(completeStr);
1767 window.setTimeout('ajaxStatus.hideStatus();', 2000);
1769 saveAllButton.style.visibility = 'hidden';
1774 if(typeof savingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
1775 ajaxStatus.showStatus(savingStr);
1777 //loop through the forms saving each one
1778 for(i = 0; i < theForms.length; i++){
1779 var theForm = document.getElementById(theForms[i]);
1780 if(check_form(theForm.id)){
1781 theForm.action.value='AjaxFormSave';
1782 YAHOO.util.Connect.setForm(theForm);
1783 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
1785 ajaxStatus.hideStatus();
1787 lastSubmitTime = lastSubmitTime-2000;
1792 // -- start sugarListView class
1793 // js functions used for ListView
1794 function sugarListView() {
1798 sugarListView.prototype.confirm_action = function(del) {
1800 return confirm( SUGAR.language.get('app_strings', 'NTC_DELETE_CONFIRMATION_NUM') + sugarListView.get_num_selected() + SUGAR.language.get('app_strings', 'NTC_DELETE_SELECTED_RECORDS'));
1803 return confirm( SUGAR.language.get('app_strings', 'NTC_UPDATE_CONFIRMATION_NUM') + sugarListView.get_num_selected() + SUGAR.language.get('app_strings', 'NTC_DELETE_SELECTED_RECORDS'));
1807 sugarListView.get_num_selected = function () {
1808 if(typeof document.MassUpdate != 'undefined') {
1809 the_form = document.MassUpdate;
1810 for(wp = 0; wp < the_form.elements.length; wp++) {
1811 if(typeof the_form.elements[wp].name != 'undefined' && the_form.elements[wp].name == 'selectCount[]') {
1812 return the_form.elements[wp].value;
1819 sugarListView.update_count = function(count, add) {
1820 if(typeof document.MassUpdate != 'undefined') {
1821 the_form = document.MassUpdate;
1822 for(wp = 0; wp < the_form.elements.length; wp++) {
1823 if(typeof the_form.elements[wp].name != 'undefined' && the_form.elements[wp].name == 'selectCount[]') {
1825 the_form.elements[wp].value = parseInt(the_form.elements[wp].value,10) + count;
1826 if (the_form.select_entire_list.value == 1 && the_form.show_plus.value) {
1827 the_form.elements[wp].value += '+';
1830 if (the_form.select_entire_list.value == 1 && the_form.show_plus.value) {
1831 the_form.elements[wp].value = count + '+';
1833 the_form.elements[wp].value = count;
1840 sugarListView.prototype.use_external_mail_client = function(no_record_txt, module) {
1841 selected_records = sugarListView.get_checks_count();
1842 if(selected_records <1) {
1843 alert(no_record_txt);
1847 if (document.MassUpdate.select_entire_list.value == 1) {
1848 if (totalCount > 10) {
1849 alert(totalCountError);
1854 else if (document.MassUpdate.massall.checked == true)
1858 sugarListView.get_checks();
1860 if(select) { // use selected items
1861 ids = document.MassUpdate.uid.value;
1863 else { // use current page
1864 inputs = document.MassUpdate.elements;
1866 for(i = 0; i < inputs.length; i++) {
1867 if(inputs[i].name == 'mass[]' && inputs[i].checked && typeof(inputs[i].value) != 'function') {
1868 ar.push(inputs[i].value);
1873 YAHOO.util.Connect.asyncRequest("POST", "index.php?", {
1874 success: this.use_external_mail_client_callback
1875 }, SUGAR.util.paramsToUrl({
1878 listViewExternalClient: 1,
1879 action_module: module,
1887 sugarListView.prototype.use_external_mail_client_callback = function(o)
1890 location.href = 'mailto:' + o.responseText;
1893 sugarListView.prototype.send_form_for_emails = function(select, currentModule, action, no_record_txt,action_module,totalCount, totalCountError) {
1894 if ( typeof(SUGAR.config.email_sugarclient_listviewmaxselect) != 'undefined' ) {
1898 maxCount = SUGAR.config.email_sugarclient_listviewmaxselect;
1901 if (document.MassUpdate.select_entire_list.value == 1) {
1902 if (totalCount > maxCount) {
1903 alert(totalCountError);
1908 else if (document.MassUpdate.massall.checked == true)
1913 sugarListView.get_checks();
1914 // create new form to post (can't access action property of MassUpdate form due to action input)
1915 var newForm = document.createElement('form');
1916 newForm.method = 'post';
1917 newForm.action = action;
1918 newForm.name = 'newForm';
1919 newForm.id = 'newForm';
1920 var uidTa = document.createElement('textarea');
1922 uidTa.style.display = 'none';
1924 if(select) { // use selected items
1925 uidTa.value = document.MassUpdate.uid.value;
1927 else { // use current page
1928 inputs = document.MassUpdate.elements;
1930 for(i = 0; i < inputs.length; i++) {
1931 if(inputs[i].name == 'mass[]' && inputs[i].checked && typeof(inputs[i].value) != 'function') {
1932 ar.push(inputs[i].value);
1935 uidTa.value = ar.join(',');
1938 if(uidTa.value == '') {
1939 alert(no_record_txt);
1943 var selectedArray = uidTa.value.split(",");
1944 if(selectedArray.length > maxCount) {
1945 alert(totalCountError);
1948 newForm.appendChild(uidTa);
1950 var moduleInput = document.createElement('input');
1951 moduleInput.name = 'module';
1952 moduleInput.type = 'hidden';
1953 moduleInput.value = currentModule;
1954 newForm.appendChild(moduleInput);
1956 var actionInput = document.createElement('input');
1957 actionInput.name = 'action';
1958 actionInput.type = 'hidden';
1959 actionInput.value = 'Compose';
1960 newForm.appendChild(actionInput);
1962 if (typeof action_module != 'undefined' && action_module!= '') {
1963 var actionModule = document.createElement('input');
1964 actionModule.name = 'action_module';
1965 actionModule.type = 'hidden';
1966 actionModule.value = action_module;
1967 newForm.appendChild(actionModule);
1969 //return_info must follow this pattern."&return_module=Accounts&return_action=index"
1970 if (typeof return_info!= 'undefined' && return_info != '') {
1971 var params= return_info.split('&');
1972 if (params.length > 0) {
1973 for (var i=0;i< params.length;i++) {
1974 if (params[i].length > 0) {
1975 var param_nv=params[i].split('=');
1976 if (param_nv.length==2){
1977 returnModule = document.createElement('input');
1978 returnModule.name = param_nv[0];
1979 returnModule.type = 'hidden';
1980 returnModule.value = param_nv[1];
1981 newForm.appendChild(returnModule);
1988 var isAjaxCall = document.createElement('input');
1989 isAjaxCall.name = 'ajaxCall';
1990 isAjaxCall.type = 'hidden';
1991 isAjaxCall.value = true;
1992 newForm.appendChild(isAjaxCall);
1994 var isListView = document.createElement('input');
1995 isListView.name = 'ListView';
1996 isListView.type = 'hidden';
1997 isListView.value = true;
1998 newForm.appendChild(isListView);
2000 var toPdf = document.createElement('input');
2001 toPdf.name = 'to_pdf';
2002 toPdf.type = 'hidden';
2004 newForm.appendChild(toPdf);
2006 //Grab the Quick Compose package for the listview
2007 YAHOO.util.Connect.setForm(newForm);
2010 success: function(o) {
2011 var resp = YAHOO.lang.JSON.parse(o.responseText);
2012 var quickComposePackage = new Object();
2013 quickComposePackage.composePackage = resp;
2014 quickComposePackage.fullComposeUrl = 'index.php?module=Emails&action=Compose&ListView=true' +
2015 '&uid=' + uidTa.value + '&action_module=' + action_module;
2017 SUGAR.quickCompose.init(quickComposePackage);
2021 YAHOO.util.Connect.asyncRequest('POST','index.php', callback,null);
2023 // awu Bug 18624: Fixing issue where a canceled Export and unselect of row will persist the uid field, clear the field
2024 document.MassUpdate.uid.value = '';
2029 sugarListView.prototype.send_form = function(select, currentModule, action, no_record_txt,action_module,return_info) {
2030 if (document.MassUpdate.select_entire_list.value == 1) {
2032 if(sugarListView.get_checks_count() < 1) {
2033 alert(no_record_txt);
2038 if ( action.indexOf('?') != -1 )
2039 href += '&module=' + currentModule;
2041 href += '?module=' + currentModule;
2044 href += return_info;
2045 var newForm = document.createElement('form');
2046 newForm.method = 'post';
2047 newForm.action = href;
2048 newForm.name = 'newForm';
2049 newForm.id = 'newForm';
2050 var postTa = document.createElement('textarea');
2051 postTa.name = 'current_post';
2052 postTa.value = document.MassUpdate.current_query_by_page.value;
2053 postTa.style.display = 'none';
2054 newForm.appendChild(postTa);
2055 document.MassUpdate.parentNode.appendChild(newForm);
2059 else if (document.MassUpdate.massall.checked == true)
2064 sugarListView.get_checks();
2065 // create new form to post (can't access action property of MassUpdate form due to action input)
2066 var newForm = document.createElement('form');
2067 newForm.method = 'post';
2068 newForm.action = action;
2069 newForm.name = 'newForm';
2070 newForm.id = 'newForm';
2071 var uidTa = document.createElement('textarea');
2073 uidTa.style.display = 'none';
2074 uidTa.value = document.MassUpdate.uid.value;
2076 if(uidTa.value == '') {
2077 alert(no_record_txt);
2081 newForm.appendChild(uidTa);
2083 var moduleInput = document.createElement('input');
2084 moduleInput.name = 'module';
2085 moduleInput.type = 'hidden';
2086 moduleInput.value = currentModule;
2087 newForm.appendChild(moduleInput);
2089 var actionInput = document.createElement('input');
2090 actionInput.name = 'action';
2091 actionInput.type = 'hidden';
2092 actionInput.value = 'index';
2093 newForm.appendChild(actionInput);
2095 if (typeof action_module != 'undefined' && action_module!= '') {
2096 var actionModule = document.createElement('input');
2097 actionModule.name = 'action_module';
2098 actionModule.type = 'hidden';
2099 actionModule.value = action_module;
2100 newForm.appendChild(actionModule);
2102 //return_info must follow this pattern."&return_module=Accounts&return_action=index"
2103 if (typeof return_info!= 'undefined' && return_info != '') {
2104 var params= return_info.split('&');
2105 if (params.length > 0) {
2106 for (var i=0;i< params.length;i++) {
2107 if (params[i].length > 0) {
2108 var param_nv=params[i].split('=');
2109 if (param_nv.length==2){
2110 returnModule = document.createElement('input');
2111 returnModule.name = param_nv[0];
2112 returnModule.type = 'hidden';
2113 returnModule.value = param_nv[1];
2114 newForm.appendChild(returnModule);
2121 document.MassUpdate.parentNode.appendChild(newForm);
2124 // awu Bug 18624: Fixing issue where a canceled Export and unselect of row will persist the uid field, clear the field
2125 document.MassUpdate.uid.value = '';
2129 //return a count of checked row.
2130 sugarListView.get_checks_count = function() {
2133 if(document.MassUpdate.uid.value != '') {
2134 oldUids = document.MassUpdate.uid.value.split(',');
2135 for(uid in oldUids) {
2136 if(typeof(oldUids[uid]) != 'function') {
2137 ar[oldUids[uid]] = 1;
2141 // build associated array of uids, associated array ensures uniqueness
2142 inputs = document.MassUpdate.elements;
2143 for(i = 0; i < inputs.length; i++) {
2144 if(inputs[i].name == 'mass[]') {
2145 ar[inputs[i].value] = (inputs[i].checked) ? 1 : 0; // 0 of it is unchecked
2149 // build regular array of uids
2152 if((typeof(ar[i]) != 'function') && ar[i] == 1) {
2160 // saves the checks on the current page into the uid textarea
2161 sugarListView.get_checks = function() {
2164 if(document.MassUpdate.uid.value != '') {
2165 oldUids = document.MassUpdate.uid.value.split(',');
2166 for(uid in oldUids) {
2167 if(typeof(oldUids[uid]) != 'function') {
2168 ar[oldUids[uid]] = 1;
2173 // build associated array of uids, associated array ensures uniqueness
2174 inputs = document.MassUpdate.elements;
2175 for(i = 0; i < inputs.length; i++) {
2176 if(inputs[i].name == 'mass[]') {
2177 ar[inputs[i].value] = (inputs[i].checked) ? 1 : 0; // 0 of it is unchecked
2181 // build regular array of uids
2184 if(typeof(ar[i]) != 'function' && ar[i] == 1) {
2189 document.MassUpdate.uid.value = uids.join(',');
2191 if(uids.length == 0) return false; // return false if no checks to get
2192 return true; // there are saved checks
2195 sugarListView.prototype.order_checks = function(order,orderBy,moduleString){
2196 checks = sugarListView.get_checks();
2197 eval('document.MassUpdate.' + moduleString + '.value = orderBy');
2198 document.MassUpdate.lvso.value = order;
2199 if(typeof document.MassUpdate.massupdate != 'undefined') {
2200 document.MassUpdate.massupdate.value = 'false';
2203 //we must first clear the action of massupdate, change it to index
2204 document.MassUpdate.action.value = document.MassUpdate.return_action.value;
2205 document.MassUpdate.return_module.value='';
2206 document.MassUpdate.return_action.value='';
2207 document.MassUpdate.submit();
2211 sugarListView.prototype.save_checks = function(offset, moduleString) {
2212 checks = sugarListView.get_checks();
2213 eval('document.MassUpdate.' + moduleString + '.value = offset');
2215 if(typeof document.MassUpdate.massupdate != 'undefined') {
2216 document.MassUpdate.massupdate.value = 'false';
2219 //we must first clear the action of massupdate, change it to index
2220 document.MassUpdate.action.value = document.MassUpdate.return_action.value;
2221 document.MassUpdate.return_module.value='';
2222 document.MassUpdate.return_action.value='';
2223 document.MassUpdate.submit();
2229 sugarListView.prototype.check_item = function(cb, form) {
2231 sugarListView.update_count(1, true);
2233 sugarListView.update_count(-1, true);
2234 if(typeof form != 'undefined' && form != null) {
2235 sugarListView.prototype.updateUid(cb, form);
2240 /**#28000, remove the unselect record id from MassUpdate.uid **/
2241 sugarListView.prototype.updateUid = function(cb , form){
2242 if(form.name == 'MassUpdate' && form.uid && form.uid.value && cb.value && form.uid.value.indexOf(cb.value) != -1){
2243 if(form.uid.value.indexOf(','+cb.value)!= -1){
2244 form.uid.value = form.uid.value.replace(','+cb.value , '');
2245 }else if(form.uid.value.indexOf(cb.value + ',')!= -1){
2246 form.uid.value = form.uid.value.replace(cb.value + ',' , '');
2247 }else if(form.uid.value.indexOf(cb.value)!= -1){
2248 form.uid.value = form.uid.value.replace(cb.value , '');
2253 sugarListView.prototype.check_entire_list = function(form, field, value, list_count) {
2254 // count number of items
2256 document.MassUpdate.massall.checked = true;
2257 document.MassUpdate.massall.disabled = true;
2259 for (i = 0; i < form.elements.length; i++) {
2260 if(form.elements[i].name == field && form.elements[i].disabled == false) {
2261 if(form.elements[i].checked != value) count++;
2262 form.elements[i].checked = value;
2263 form.elements[i].disabled = true;
2266 document.MassUpdate.select_entire_list.value = 1;
2268 sugarListView.update_count(list_count, false);
2269 //else sugarListView.update_count(-1 * count, true);
2272 sugarListView.prototype.check_all = function(form, field, value, pageTotal) {
2273 // count number of items
2275 document.MassUpdate.massall.checked = value;
2276 if (document.MassUpdate.select_entire_list &&
2277 document.MassUpdate.select_entire_list.value == 1)
2278 document.MassUpdate.massall.disabled = true;
2280 document.MassUpdate.massall.disabled = false;
2282 for (i = 0; i < form.elements.length; i++) {
2283 if(form.elements[i].name == field && !(form.elements[i].disabled == true && form.elements[i].checked == false)) {
2284 form.elements[i].disabled = false;
2286 if(form.elements[i].checked != value)
2288 form.elements[i].checked = value;
2290 sugarListView.prototype.updateUid(form.elements[i], form);
2295 sugarListView.update_count(pageTotal);
2297 sugarListView.update_count(count, true);
2299 sugarListView.update_count(-1 * count, true);
2301 sugarListView.check_all = sugarListView.prototype.check_all;
2302 sugarListView.confirm_action = sugarListView.prototype.confirm_action;
2304 sugarListView.prototype.check_boxes = function() {
2305 var inputsCount = 0;
2306 var checkedCount = 0;
2307 var existing_onload = window.onload;
2308 var theForm = document.MassUpdate;
2309 inputs_array = theForm.elements;
2311 if(typeof theForm.uid.value != 'undefined' && theForm.uid.value != "") {
2312 checked_items = theForm.uid.value.split(",");
2313 if (theForm.select_entire_list.value == 1)
2314 document.MassUpdate.massall.disabled = true;
2316 for(wp = 0 ; wp < inputs_array.length; wp++) {
2317 if(inputs_array[wp].name == "mass[]") {
2319 if (theForm.select_entire_list.value == 1) {
2320 inputs_array[wp].checked = true;
2321 inputs_array[wp].disabled = true;
2325 for(i in checked_items) {
2326 if(inputs_array[wp].value == checked_items[i]) {
2328 inputs_array[wp].checked = true;
2334 if (theForm.select_entire_list.value == 0)
2335 sugarListView.update_count(checked_items.length);
2337 sugarListView.update_count(0, true);
2341 for(wp = 0 ; wp < inputs_array.length; wp++) {
2342 if(inputs_array[wp].name == "mass[]") {
2343 inputs_array[wp].checked = false;
2344 inputs_array[wp].disabled = false;
2347 if (document.MassUpdate.massall) {
2348 document.MassUpdate.massall.checked = false;
2349 document.MassUpdate.massall.disabled = false;
2351 sugarListView.update_count(0)
2353 if(checkedCount > 0 && checkedCount == inputsCount)
2354 document.MassUpdate.massall.checked = true;
2360 * This function is used in Email Template Module's listview.
2361 * It will check whether the templates are used in Campaing->EmailMarketing.
2362 * If true, it will notify user.
2364 function check_used_email_templates() {
2365 var ids = document.MassUpdate.uid.value;
2367 success:function(r) {
2368 if(r.responseText != '') {
2369 if(!confirm(SUGAR.language.get('app_strings','NTC_TEMPLATES_IS_USED') + r.responseText)) {
2373 document.MassUpdate.submit();
2377 url = "index.php?module=EmailTemplates&action=CheckDeletable&from=ListView&to_pdf=1&records="+ids;
2378 YAHOO.util.Connect.asyncRequest('POST',url, call_back,null);
2382 sugarListView.prototype.send_mass_update = function(mode, no_record_txt, del) {
2383 formValid = check_form('MassUpdate');
2384 if(!formValid && !del) return false;
2387 if (document.MassUpdate.select_entire_list &&
2388 document.MassUpdate.select_entire_list.value == 1)
2393 var ar = new Array();
2397 for(wp = 0; wp < document.MassUpdate.elements.length; wp++) {
2398 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)+'$');
2399 //when the uid is already in document.MassUpdate.uid.value, we should not add it to ar.
2400 if(typeof document.MassUpdate.elements[wp].name != 'undefined'
2401 && document.MassUpdate.elements[wp].name == 'mass[]'
2402 && document.MassUpdate.elements[wp].checked
2403 && !reg_for_existing_uid.test(document.MassUpdate.uid.value)) {
2404 ar.push(document.MassUpdate.elements[wp].value);
2407 if(document.MassUpdate.uid.value != '') document.MassUpdate.uid.value += ',';
2408 document.MassUpdate.uid.value += ar.join(',');
2409 if(document.MassUpdate.uid.value == '') {
2410 alert(no_record_txt);
2413 if(typeof(current_admin_id)!='undefined' && document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'Users' && (document.MassUpdate.is_admin.value!='' || document.MassUpdate.status.value!='')) {
2414 var reg_for_current_admin_id = new RegExp('^'+current_admin_id+'[\s]*,|,[\s]*'+current_admin_id+'[\s]*,|,[\s]*'+current_admin_id+'$|^'+current_admin_id+'$');
2415 if(reg_for_current_admin_id.test(document.MassUpdate.uid.value)) {
2416 //if current user is admin, we should not allow massupdate the user_type and status of himself
2417 alert(SUGAR.language.get('Users','LBL_LAST_ADMIN_NOTICE'));
2423 var entireInput = document.createElement('input');
2424 entireInput.name = 'entire';
2425 entireInput.type = 'hidden';
2426 entireInput.value = 'index';
2427 document.MassUpdate.appendChild(entireInput);
2428 //confirm(no_record_txt);
2429 if(document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'Users' && (document.MassUpdate.is_admin.value!='' || document.MassUpdate.status.value!='')) {
2430 alert(SUGAR.language.get('Users','LBL_LAST_ADMIN_NOTICE'));
2436 if(!sugarListView.confirm_action(del))
2440 var deleteInput = document.createElement('input');
2441 deleteInput.name = 'Delete';
2442 deleteInput.type = 'hidden';
2443 deleteInput.value = true;
2444 document.MassUpdate.appendChild(deleteInput);
2445 if(document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'EmailTemplates') {
2446 check_used_email_templates();
2452 document.MassUpdate.submit();
2457 sugarListView.prototype.clear_all = function() {
2458 document.MassUpdate.uid.value = '';
2459 document.MassUpdate.select_entire_list.value = 0;
2460 sugarListView.check_all(document.MassUpdate, 'mass[]', false);
2461 document.MassUpdate.massall.checked = false;
2462 document.MassUpdate.massall.disabled = false;
2463 sugarListView.update_count(0);
2466 sListView = new sugarListView();
2467 // -- end sugarListView class
2469 // format and unformat numbers
2470 function unformatNumber(n, num_grp_sep, dec_sep) {
2471 var x=unformatNumberNoParse(n, num_grp_sep, dec_sep);
2474 return parseFloat(x);
2479 function unformatNumberNoParse(n, num_grp_sep, dec_sep) {
2480 if(typeof num_grp_sep == 'undefined' || typeof dec_sep == 'undefined') return n;
2481 n = n ? n.toString() : '';
2484 if(num_grp_sep != '')
2486 num_grp_sep_re = new RegExp('\\'+num_grp_sep, 'g');
2487 n = n.replace(num_grp_sep_re, '');
2490 n = n.replace(dec_sep, '.');
2492 if(typeof CurrencySymbols != 'undefined') {
2493 // Need to strip out the currency symbols from the start.
2494 for ( var idx in CurrencySymbols ) {
2495 n = n.replace(CurrencySymbols[idx], '');
2503 // round parameter can be negative for decimal, precision has to be postive
2504 function formatNumber(n, num_grp_sep, dec_sep, round, precision) {
2505 if(typeof num_grp_sep == 'undefined' || typeof dec_sep == 'undefined') return n;
2506 n = n ? n.toString() : '';
2507 if(n.split) n = n.split('.');
2510 if(n.length > 2) return n.join('.'); // that's not a num!
2512 if(typeof round != 'undefined') {
2513 if(round > 0 && n.length > 1) { // round to decimal
2514 n[1] = parseFloat('0.' + n[1]);
2515 n[1] = Math.round(n[1] * Math.pow(10, round)) / Math.pow(10, round);
2516 n[1] = n[1].toString().split('.')[1];
2518 if(round <= 0) { // round to whole number
2519 n[0] = Math.round(parseInt(n[0],10) * Math.pow(10, round)) / Math.pow(10, round);
2524 if(typeof precision != 'undefined' && precision >= 0) {
2525 if(n.length > 1 && typeof n[1] != 'undefined') n[1] = n[1].substring(0, precision); // cut off precision
2527 if(n[1].length < precision) {
2528 for(var wp = n[1].length; wp < precision; wp++) n[1] += '0';
2532 regex = /(\d+)(\d{3})/;
2533 while(num_grp_sep != '' && regex.test(n[0])) n[0] = n[0].toString().replace(regex, '$1' + num_grp_sep + '$2');
2534 return n[0] + (n.length > 1 && n[1] != '' ? dec_sep + n[1] : '');
2537 // --- begin ajax status class
2538 SUGAR.ajaxStatusClass = function() {};
2539 SUGAR.ajaxStatusClass.prototype.statusDiv = null;
2540 SUGAR.ajaxStatusClass.prototype.oldOnScroll = null;
2541 SUGAR.ajaxStatusClass.prototype.shown = false; // state of the status window
2543 // reposition the status div, top and centered
2544 SUGAR.ajaxStatusClass.prototype.positionStatus = function() {
2545 //this.statusDiv.style.top = document.body.scrollTop + 8 + 'px';
2546 statusDivRegion = YAHOO.util.Dom.getRegion(this.statusDiv);
2547 statusDivWidth = statusDivRegion.right - statusDivRegion.left;
2548 this.statusDiv.style.left = YAHOO.util.Dom.getViewportWidth() / 2 - statusDivWidth / 2 + 'px';
2551 // private func, create the status div
2552 SUGAR.ajaxStatusClass.prototype.createStatus = function(text) {
2553 statusDiv = document.createElement('div');
2554 statusDiv.className = 'dataLabel';
2555 statusDiv.id = 'ajaxStatusDiv';
2556 document.body.appendChild(statusDiv);
2557 this.statusDiv = document.getElementById('ajaxStatusDiv');
2560 // public - show the status div with text
2561 SUGAR.ajaxStatusClass.prototype.showStatus = function(text) {
2562 if(!this.statusDiv) {
2563 this.createStatus(text);
2566 this.statusDiv.style.display = '';
2568 this.statusDiv.innerHTML = ' <b>' + text + '</b> ';
2569 this.positionStatus();
2572 this.statusDiv.style.display = '';
2573 if(window.onscroll) this.oldOnScroll = window.onscroll; // save onScroll
2574 window.onscroll = this.positionStatus;
2579 SUGAR.ajaxStatusClass.prototype.hideStatus = function(text) {
2580 if(!this.shown) return;
2582 if(this.oldOnScroll) window.onscroll = this.oldOnScroll;
2583 else window.onscroll = '';
2584 this.statusDiv.style.display = 'none';
2587 SUGAR.ajaxStatusClass.prototype.flashStatus = function(text, time){
2588 this.showStatus(text);
2589 window.setTimeout('ajaxStatus.hideStatus();', time);
2593 var ajaxStatus = new SUGAR.ajaxStatusClass();
2594 // --- end ajax status class
2597 * Unified Search Advanced - for global search
2599 SUGAR.unifiedSearchAdvanced = function() {
2609 SUGAR.unifiedSearchAdvanced.usa_div = document.getElementById('unified_search_advanced_div');
2610 SUGAR.unifiedSearchAdvanced.usa_img = document.getElementById('unified_search_advanced_img');
2612 if(!SUGAR.unifiedSearchAdvanced.usa_div || !SUGAR.unifiedSearchAdvanced.usa_img) return;
2613 var attributes = { height: { to: 300 } };
2614 SUGAR.unifiedSearchAdvanced.anim_open = new YAHOO.util.Anim('unified_search_advanced_div', attributes );
2615 SUGAR.unifiedSearchAdvanced.anim_open.duration = 0.75;
2616 SUGAR.unifiedSearchAdvanced.anim_close = new YAHOO.util.Anim('unified_search_advanced_div', { height: {to: 0} } );
2617 SUGAR.unifiedSearchAdvanced.anim_close.duration = 0.75;
2618 //SUGAR.unifiedSearchAdvanced.anim_close.onComplete.subscribe(function() {SUGAR.unifiedSearchAdvanced.usa_div.style.display = 'none'});
2620 SUGAR.unifiedSearchAdvanced.usa_img._x = YAHOO.util.Dom.getX(SUGAR.unifiedSearchAdvanced.usa_img);
2621 SUGAR.unifiedSearchAdvanced.usa_img._y = YAHOO.util.Dom.getY(SUGAR.unifiedSearchAdvanced.usa_img);
2624 SUGAR.unifiedSearchAdvanced.usa_open = false;
2625 SUGAR.unifiedSearchAdvanced.usa_content = null;
2627 YAHOO.util.Event.addListener('unified_search_advanced_img', 'click', SUGAR.unifiedSearchAdvanced.get_content);
2630 get_content: function(e)
2632 query_string = trim(document.getElementById('query_string').value);
2633 if(query_string != '')
2635 window.location.href = 'index.php?module=Home&action=UnifiedSearch&query_string=' + query_string;
2637 window.location.href = 'index.php?module=Home&action=UnifiedSearch&form_only=true';
2641 animate: function(data) {
2642 ajaxStatus.hideStatus();
2645 SUGAR.unifiedSearchAdvanced.usa_content = data.responseText;
2646 SUGAR.unifiedSearchAdvanced.usa_div.innerHTML = SUGAR.unifiedSearchAdvanced.usa_content;
2648 if(SUGAR.unifiedSearchAdvanced.usa_open) {
2649 document.UnifiedSearch.advanced.value = 'false';
2650 SUGAR.unifiedSearchAdvanced.anim_close.animate();
2653 document.UnifiedSearch.advanced.value = 'true';
2654 SUGAR.unifiedSearchAdvanced.usa_div.style.display = '';
2655 YAHOO.util.Dom.setX(SUGAR.unifiedSearchAdvanced.usa_div, SUGAR.unifiedSearchAdvanced.usa_img._x - 90);
2656 YAHOO.util.Dom.setY(SUGAR.unifiedSearchAdvanced.usa_div, SUGAR.unifiedSearchAdvanced.usa_img._y + 15);
2657 SUGAR.unifiedSearchAdvanced.anim_open.animate();
2659 SUGAR.unifiedSearchAdvanced.usa_open = !SUGAR.unifiedSearchAdvanced.usa_open;
2664 checkUsaAdvanced: function() {
2665 if(document.UnifiedSearch.advanced.value == 'true') {
2666 document.UnifiedSearchAdvanced.query_string.value = document.UnifiedSearch.query_string.value;
2667 document.UnifiedSearchAdvanced.submit();
2674 if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.unifiedSearchAdvanced.init);
2679 * Toggles the header
2681 toggleHeader : function() {
2682 var h = document.getElementById('header');
2686 if(h.style.display == 'none') {
2687 h.style.display = '';
2689 h.style.display = 'none';
2693 alert(SUGAR.language.get("app_strings", "ERR_NO_HEADER_ID"));
2700 * General Sugar Utils
2702 SUGAR.util = function () {
2703 var additionalDetailsCache;
2704 var additionalDetailsCalls;
2705 var additionalDetailsRpcCall;
2708 getAndRemove : function (el) {
2709 if (YAHOO && YAHOO.util && YAHOO.util.Dom)
2710 el = YAHOO.util.Dom.get(el);
2711 else if (typeof (el) == "string")
2712 el = document.getElementById(el);
2713 if (el && el.parentNode)
2714 el.parentNode.removeChild(el);
2718 paramsToUrl : function (params) {
2721 url += i + "=" + params[i] + "&";
2725 evalScript:function(text){
2727 var waitUntilLoaded = function(){
2728 SUGAR.evalScript_waitCount--;
2729 if (SUGAR.evalScript_waitCount == 0) {
2730 var headElem = document.getElementsByTagName('head')[0];
2731 for ( var i = 0; i < SUGAR.evalScript_evalElem.length; i++) {
2732 var tmpElem = document.createElement('script');
2733 tmpElem.type = 'text/javascript';
2734 tmpElem.text = SUGAR.evalScript_evalElem[i];
2735 headElem.appendChild(tmpElem);
2740 var tmpElem = document.createElement('div');
2741 tmpElem.innerHTML = text;
2742 var results = tmpElem.getElementsByTagName('script');
2743 if (results == null) {
2744 // No scripts found, bail out
2748 var headElem = document.getElementsByTagName('head')[0];
2750 SUGAR.evalScript_waitCount = 0;
2751 SUGAR.evalScript_evalElem = new Array();
2752 for (var i = 0; i < results.length; i++) {
2753 if (typeof(results[i]) != 'object') {
2756 tmpElem = document.createElement('script');
2757 tmpElem.type = 'text/javascript';
2758 if (results[i].src != null && results[i].src != '') {
2759 tmpElem.src = results[i].src;
2761 // Need to defer execution of these scripts until the
2762 // required javascript files are fully loaded
2763 SUGAR.evalScript_evalElem[SUGAR.evalScript_evalElem.length] = results[i].text;
2766 tmpElem.addEventListener('load', waitUntilLoaded);
2767 SUGAR.evalScript_waitCount++;
2768 headElem.appendChild(tmpElem);
2770 // Add some code to handle pages without any external scripts
2771 SUGAR.evalScript_waitCount++;
2774 // Don't try and process things the IE way
2778 var objRegex = /<\s*script([^>]*)>((.|\s|\v|\0)*?)<\s*\/script\s*>/igm;
2780 var result = objRegex.exec(text);
2781 while(result && result.index > lastIndex){
2782 lastIndex = result.index
2784 var script = document.createElement('script');
2785 script.type= 'text/javascript';
2786 if(result[1].indexOf("src=") > -1){
2787 var srcRegex = /.*src=['"]([a-zA-Z0-9_\&\/\.\?=:]*)['"].*/igm;
2788 var srcResult = result[1].replace(srcRegex, '$1');
2789 script.src = srcResult;
2791 script.text = result[2];
2793 document.body.appendChild(script);
2796 if(typeof(console) != "undefined" && typeof(console.log) == "function")
2798 console.log("error adding script");
2800 console.log(result);
2803 result = objRegex.exec(text);
2807 * Gets the sidebar object
2808 * @return object pointer to the sidebar element
2810 getLeftColObj: function() {
2811 leftColObj = document.getElementById('leftCol');
2812 while(leftColObj.nodeName != 'TABLE') {
2813 leftColObj = leftColObj.firstChild;
2815 leftColTable = leftColObj;
2816 leftColTd = leftColTable.getElementsByTagName('td')[0];
2817 leftColTdRegion = YAHOO.util.Dom.getRegion(leftColTd);
2818 leftColTd.style.width = (leftColTdRegion.right - leftColTdRegion.left) + 'px';
2823 * Fills the shortcut menu placeholders w/ actual content
2824 * Call this on load event
2826 * @param shortcutContent Array array of content to fill in
2828 fillShortcuts: function(e, shortcutContent) {
2831 // don't do this if leftCol isn't available
2832 if (document.getElementById('leftCol') == undefined) { return; }
2834 spans = document.getElementById('leftCol').getElementsByTagName('span');
2835 hideCol = document.getElementById('HideMenu').getElementsByTagName('span');
2836 w = spans.length + 1;
2838 spans[w] = hideCol[i];
2841 for(je in shortcutContent) {
2843 if(typeof spans[wp].innerHTML != 'undefined' && spans[wp].innerHTML == ('wp_shortcut_fill_' + je)) {
2844 if(typeof spans[wp].parentNode.parentNode == 'object') {
2845 if(typeof spans[wp].parentNode.parentNode.onclick != 'undefined') {
2846 spans[wp].parentNode.parentNode.onclick = null;
2848 // If the wp_shortcut span is contained by an A tag, replace the A with a DIV.
2849 if(spans[wp].parentNode.tagName == 'A' && !isIE) {
2850 var newDiv = document.createElement('DIV');
2851 var parentAnchor = spans[wp].parentNode;
2853 spans[wp].parentNode.parentNode.style.display = 'none';
2855 // Copy styles over to the new container div
2856 if(window.getComputedStyle) {
2857 var parentStyle = window.getComputedStyle(parentAnchor, '');
2858 for(var styleName in parentStyle) {
2859 if(typeof parentStyle[styleName] != 'function'
2860 && styleName != 'display'
2861 && styleName != 'borderWidth'
2862 && styleName != 'visibility') {
2864 newDiv.style[styleName] = parentStyle[styleName];
2866 // Catches .length and .parentRule, and others
2872 // Replace the A with the DIV
2873 newDiv.appendChild(spans[wp]);
2874 parentAnchor.parentNode.replaceChild(newDiv, parentAnchor);
2876 spans[wp].parentNode.parentNode.style.display = '';
2879 spans[wp].innerHTML = shortcutContent[je]; // fill w/ content
2880 if(spans[wp].style) spans[wp].style.display = '';
2886 * Make an AJAX request.
2888 * @param url string resource to load
2889 * @param theDiv string id of element to insert loaded data into
2890 * @param postForm string if set, a POST request will be made to resource specified by url using the form named by postForm
2891 * @param callback string name of function to invoke after HTTP response is recieved
2892 * @param callbackParam any parameter to pass to callback when invoked
2893 * @param appendMode bool if true, HTTP response will be appended to the contents of theDiv, or else contents will be overriten.
2895 retrieveAndFill: function(url, theDiv, postForm, callback, callbackParam, appendMode) {
2896 if(typeof theDiv == 'string') {
2898 theDiv = document.getElementById(theDiv);
2905 var success = function(data) {
2906 if (typeof theDiv != 'undefined' && theDiv != null)
2909 if (typeof appendMode != 'undefined' && appendMode)
2911 theDiv.innerHTML += data.responseText;
2915 theDiv.innerHTML = data.responseText;
2922 if (typeof callback != 'undefined' && callback != null) callback(callbackParam);
2925 if(typeof postForm == 'undefined' || postForm == null) {
2926 var cObj = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
2929 YAHOO.util.Connect.setForm(postForm);
2930 var cObj = YAHOO.util.Connect.asyncRequest('POST', url, {success: success, failure: success});
2933 checkMaxLength: function() { // modified from http://www.quirksmode.org/dom/maxlength.html
2934 var maxLength = this.getAttribute('maxlength');
2935 var currentLength = this.value.length;
2936 if (currentLength > maxLength) {
2937 this.value = this.value.substring(0, maxLength);
2942 * Adds maxlength attribute to textareas
2944 setMaxLength: function() { // modified from http://www.quirksmode.org/dom/maxlength.html
2945 var x = document.getElementsByTagName('textarea');
2946 for (var i=0;i<x.length;i++) {
2947 if (x[i].getAttribute('maxlength')) {
2948 x[i].onkeyup = x[i].onchange = SUGAR.util.checkMaxLength;
2955 * Retrieves additional details dynamically
2957 getAdditionalDetails: function(bean, id, spanId) {
2959 oReturn = function(body, caption, width, theme) {
2960 var _refx = 25-width;
2961 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);
2964 success = function(data) {
2965 eval(data.responseText);
2967 SUGAR.util.additionalDetailsCache[spanId] = new Array();
2968 SUGAR.util.additionalDetailsCache[spanId]['body'] = result['body'];
2969 SUGAR.util.additionalDetailsCache[spanId]['caption'] = result['caption'];
2970 SUGAR.util.additionalDetailsCache[spanId]['width'] = result['width'];
2971 SUGAR.util.additionalDetailsCache[spanId]['theme'] = result['theme'];
2972 ajaxStatus.hideStatus();
2973 return oReturn(SUGAR.util.additionalDetailsCache[spanId]['body'], SUGAR.util.additionalDetailsCache[spanId]['caption'], SUGAR.util.additionalDetailsCache[spanId]['width'], SUGAR.util.additionalDetailsCache[spanId]['theme']);
2976 if(typeof SUGAR.util.additionalDetailsCache[spanId] != 'undefined')
2977 return oReturn(SUGAR.util.additionalDetailsCache[spanId]['body'], SUGAR.util.additionalDetailsCache[spanId]['caption'], SUGAR.util.additionalDetailsCache[spanId]['width'], SUGAR.util.additionalDetailsCache[spanId]['theme']);
2979 if(typeof SUGAR.util.additionalDetailsCalls[spanId] != 'undefined') // call already in progress
2981 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_LOADING'));
2982 url = 'index.php?to_pdf=1&module=Home&action=AdditionalDetailsRetrieve&bean=' + bean + '&id=' + id;
2983 SUGAR.util.additionalDetailsCalls[spanId] = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
2987 SUGAR.util.additionalDetailsRpcCall = window.setTimeout('go()', 250);
2989 clearAdditionalDetailsCall: function() {
2990 if(typeof SUGAR.util.additionalDetailsRpcCall == 'number') window.clearTimeout(SUGAR.util.additionalDetailsRpcCall);
2993 * A function that extends functionality from parent to child.
2995 extend : function(subc, superc, overrides) {
2996 subc.prototype = new superc; // set the superclass
2999 for (var i in overrides) subc.prototype[i] = overrides[i];
3002 hrefURL : function(url) {
3004 // IE needs special treatment since otherwise it would not pass Referer
3005 var trampoline = document.createElement('a');
3006 trampoline.href = url;
3007 document.body.appendChild(trampoline);
3009 document.body.removeChild(trampoline);
3011 document.location.href = url;
3015 openWindow : function(URL, windowName, windowFeatures) {
3017 // IE needs special treatment since otherwise it would not pass Referer
3018 win = window.open('', windowName, windowFeatures);
3019 var trampoline = document.createElement('a');
3020 trampoline.href = URL;
3021 trampoline.target = windowName;
3022 document.body.appendChild(trampoline);
3024 document.body.removeChild(trampoline);
3026 win = window.open(URL, windowName, windowFeatures);
3030 //Reset the scroll on the window
3035 //Based on YUI onAvailible, but will use any boolean function instead of an ID
3036 doWhen : function(condition, fn, params, scope)
3038 this._doWhenStack.push({
3042 overrideContext: scope
3045 this._doWhenretryCount = 50;
3046 this._startDoWhenInterval();
3049 _startDoWhenInterval : function(){
3050 if (!this._doWhenInterval) {
3051 this._doWhenInterval = YAHOO.lang.later(50, this, this._doWhenCheck, null, true);
3055 _doWhenInterval : false,
3056 _doWhenCheck : function() {
3057 if (this._doWhenStack.length === 0) {
3058 this._doWhenretryCount = 0;
3059 if (this._doWhenInterval) {
3060 // clearInterval(this._interval);
3061 this._doWhenInterval.cancel();
3062 this._doWhenInterval = null;
3067 if (this._doWhenLocked) {
3072 // Hold off if DOMReady has not fired and check current
3073 // readyState to protect against the IE operation aborted
3075 if (!YAHOO.util.Event.DOMReady) {
3076 this._startDoWhenInterval();
3081 this._doWhenLocked = true;
3084 // keep trying until after the page is loaded. We need to
3085 // check the page load state prior to trying to bind the
3086 // elements so that we can be certain all elements have been
3087 // tested appropriately
3088 var tryAgain = YAHOO.util.Event.DOMReady;
3090 tryAgain = (this._doWhenretryCount > 0 && this._doWhenStack.length > 0);
3096 var executeItem = function (context, item) {
3097 if (item.overrideContext) {
3098 if (item.overrideContext === true) {
3101 context = item.overrideContext;
3104 item.fn.call(context, item.obj);
3107 var i, len, item, test;
3109 // onAvailable onContentReady
3110 for (i=0, len=this._doWhenStack.length; i<len; i=i+1) {
3111 item = this._doWhenStack[i];
3114 if ((typeof(test) == "string" && eval(test)) || (typeof(test) == "function" && test())) {
3115 executeItem(this, item);
3116 this._doWhenStack[i] = null;
3119 notAvail.push(item);
3124 this._doWhenretryCount--;
3127 for (i=this._doWhenStack.length-1; i>-1; i--) {
3128 item = this._doWhenStack[i];
3129 if (!item || !item.check) {
3130 this._doWhenStack.splice(i, 1);
3133 this._startDoWhenInterval();
3135 if (this._doWhenInterval) {
3136 // clearInterval(this._interval);
3137 this._doWhenInterval.cancel();
3138 this._doWhenInterval = null;
3141 this._doWhenLocked = false;
3145 SUGAR.util.additionalDetailsCache = new Array();
3146 SUGAR.util.additionalDetailsCalls = new Array();
3147 if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.util.setMaxLength); // allow textareas to obey maxlength attrib
3149 SUGAR.savedViews = function() {
3150 var selectedOrderBy;
3151 var selectedSortOrder;
3154 var columnsMeta; // meta data for the display columns
3157 setChooser: function() {
3159 var displayColumnsDef = new Array();
3160 var hideTabsDef = new Array();
3162 var left_td = document.getElementById('display_tabs_td');
3163 if(typeof left_td == 'undefined' || left_td == null) return; // abort!
3164 var right_td = document.getElementById('hide_tabs_td');
3166 var displayTabs = left_td.getElementsByTagName('select')[0];
3167 var hideTabs = right_td.getElementsByTagName('select')[0];
3169 for(i = 0; i < displayTabs.options.length; i++) {
3170 displayColumnsDef.push(displayTabs.options[i].value);
3173 if(typeof hideTabs != 'undefined') {
3174 for(i = 0; i < hideTabs.options.length; i++) {
3175 hideTabsDef.push(hideTabs.options[i].value);
3178 if (!SUGAR.savedViews.clearColumns)
3179 document.getElementById('displayColumnsDef').value = displayColumnsDef.join('|');
3180 document.getElementById('hideTabsDef').value = hideTabsDef.join('|');
3183 select: function(saved_search_select) {
3184 for(var wp = 0; wp < document.search_form.saved_search_select.options.length; wp++) {
3185 if(typeof document.search_form.saved_search_select.options[wp].value != 'undefined' &&
3186 document.search_form.saved_search_select.options[wp].value == saved_search_select) {
3187 document.search_form.saved_search_select.selectedIndex = wp;
3188 document.search_form.ss_delete.style.display = '';
3189 document.search_form.ss_update.style.display = '';
3193 saved_search_action: function(action, delete_lang) {
3194 if(action == 'delete') {
3195 if(!confirm(delete_lang)) return;
3197 if(action == 'save') {
3198 if(document.search_form.saved_search_name.value.replace(/^\s*|\s*$/g, '') == '') {
3199 alert(SUGAR.language.get('app_strings', 'LBL_SAVED_SEARCH_ERROR'));
3204 // This check is needed for the Activities module (Calls/Meetings/Tasks).
3205 if (document.search_form.saved_search_action)
3207 document.search_form.saved_search_action.value = action;
3208 document.search_form.search_module.value = document.search_form.module.value;
3209 document.search_form.module.value = 'SavedSearch';
3210 // Bug 31922 - Make sure to specify that we want to hit the index view here of
3211 // the SavedSearch module, since the ListView doesn't have the logic to save the
3212 // search and redirect back
3213 document.search_form.action.value = 'index';
3215 SUGAR.ajaxUI.submitForm(document.search_form);
3217 shortcut_select: function(selectBox, module) {
3219 selecturl = 'index.php?module=SavedSearch&search_module=' + module + '&action=index&saved_search_select=' + selectBox.options[selectBox.selectedIndex].value
3220 //add searchFormTab to url if it is available. This determines what tab to render
3221 if(typeof(document.getElementById('searchFormTab'))!='undefined'){
3222 selecturl = selecturl + '&searchFormTab=' + document.search_form.searchFormTab.value;
3224 //add showSSDIV to url if it is available. This determines whether saved search sub form should
3225 //be rendered open or not
3226 if(document.getElementById('showSSDIV') && typeof(document.getElementById('showSSDIV') !='undefined')){
3227 selecturl = selecturl + '&showSSDIV='+document.getElementById('showSSDIV').value;
3229 //use created url to navigate
3230 document.location.href = selecturl;
3232 handleForm: function() {
3233 SUGAR.tabChooser.movementCallback = function(left_side, right_side) {
3234 while(document.getElementById('orderBySelect').childNodes.length != 0) { // clear out order by options
3235 document.getElementById('orderBySelect').removeChild(document.getElementById('orderBySelect').lastChild);
3238 var selectedIndex = 0;
3239 var nodeCount = -1; // need this because the counter i also includes "undefined" nodes
3240 // which was breaking Calls and Meetings
3242 for(i in left_side.childNodes) { // fill in order by options
3243 if(typeof left_side.childNodes[i].nodeName != 'undefined' &&
3244 left_side.childNodes[i].nodeName.toLowerCase() == 'option' &&
3245 typeof SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value] != 'undefined' && // check if column is sortable
3246 typeof SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value]['sortable'] == 'undefined' &&
3247 SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value]['sortable'] != false) {
3249 optionNode = document.createElement('option');
3250 optionNode.value = left_side.childNodes[i].value;
3251 optionNode.innerHTML = left_side.childNodes[i].innerHTML;
3252 document.getElementById('orderBySelect').appendChild(optionNode);
3253 if(optionNode.value == SUGAR.savedViews.selectedOrderBy)
3254 selectedIndex = nodeCount;
3257 // Firefox needs this to be set after all the option nodes are created.
3258 document.getElementById('orderBySelect').selectedIndex = selectedIndex;
3260 SUGAR.tabChooser.movementCallback(document.getElementById('display_tabs_td').getElementsByTagName('select')[0]);
3262 // This check is needed for the Activities module (Calls/Meetings/Tasks).
3263 if (document.search_form.orderBy)
3264 document.search_form.orderBy.options.value = SUGAR.savedViews.selectedOrderBy;
3267 if(SUGAR.savedViews.selectedSortOrder == 'DESC') document.getElementById('sort_order_desc_radio').checked = true;
3268 else document.getElementById('sort_order_asc_radio').checked = true;
3273 SUGAR.searchForm = function() {
3276 // searchForm tab selector util
3277 searchFormSelect: function(view, previousView) {
3278 var module = view.split('|')[0];
3279 var theView = view.split('|')[1];
3281 var handleDisplay = function() { // hide other divs
3282 document.search_form.searchFormTab.value = theView;
3283 patt = module+"(.*)SearchForm$";
3284 divId=document.search_form.getElementsByTagName('div');
3285 // Hide all the search forms and retrive the name of the previous search tab (useful for the first load because previousView is empty)
3286 for (i=0;i<divId.length;i++){
3287 if(divId[i].id.match(module)==module){
3288 if(divId[i].id.match('SearchForm')=='SearchForm'){
3289 if(document.getElementById(divId[i].id).style.display == ''){
3290 previousTab=divId[i].id.match(patt)[1];
3292 document.getElementById(divId[i].id).style.display = 'none';
3296 // show the good search form.
3297 document.getElementById(module + theView + 'SearchForm').style.display = '';
3298 //if its not the first tab show there is a previous tab.
3300 thepreviousView=previousView.split('|')[1];
3303 thepreviousView=previousTab;
3305 thepreviousView=thepreviousView.replace(/_search/, "");
3306 // Process to retrieve the completed field from one tab to an other.
3307 for(num in document.search_form.elements) {
3308 if(document.search_form.elements[num]) {
3309 el = document.search_form.elements[num];
3310 pattern="^(.*)_"+thepreviousView+"$";
3311 if(typeof el.type != 'undefined' && typeof el.name != 'undefined' && el.name.match(pattern)) {
3312 advanced_input_name = el.name.match(pattern)[1]; // strip
3313 advanced_input_name = advanced_input_name+"_"+theView.replace(/_search/, "");
3314 if(typeof document.search_form[advanced_input_name] != 'undefined') // if advanced input of same name exists
3315 SUGAR.searchForm.copyElement(advanced_input_name, el);
3321 // if tab is not cached
3322 if(document.getElementById(module + theView + 'SearchForm').innerHTML == '') {
3323 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_LOADING'));
3324 var success = function(data) {
3325 document.getElementById(module + theView + 'SearchForm').innerHTML = data.responseText;
3327 SUGAR.util.evalScript(data.responseText);
3328 // pass script variables to global scope
3329 if(theView == 'saved_views') {
3330 if(typeof columnsMeta != 'undefined') SUGAR.savedViews.columnsMeta = columnsMeta;
3331 if(typeof selectedOrderBy != 'undefined') SUGAR.savedViews.selectedOrderBy = selectedOrderBy;
3332 if(typeof selectedSortOrder != 'undefined') SUGAR.savedViews.selectedSortOrder = selectedSortOrder;
3337 ajaxStatus.hideStatus();
3339 url = 'index.php?module=' + module + '&action=index&search_form_only=true&to_pdf=true&search_form_view=' + theView;
3341 //check to see if tpl has been specified. If so then pass location through url string
3343 if(document.getElementById('search_tpl') !=null && typeof(document.getElementById('search_tpl')) != 'undefined'){
3344 tpl = document.getElementById('search_tpl').value;
3345 if(tpl != ''){url += '&search_tpl='+tpl;}
3348 if(theView == 'saved_views') // handle the tab chooser
3349 url += '&displayColumns=' + SUGAR.savedViews.displayColumns + '&hideTabs=' + SUGAR.savedViews.hideTabs + '&orderBy=' + SUGAR.savedViews.selectedOrderBy + '&sortOrder=' + SUGAR.savedViews.selectedSortOrder;
3351 var cObj = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
3353 else { // that form already retrieved
3358 // copies one input to another
3359 copyElement: function(inputName, copyFromElement) {
3360 switch(copyFromElement.type) {
3363 document.search_form[inputName].value = copyFromElement.value;
3367 // This function is here to clear the form, instead of "resubmitting it
3368 clear_form: function(form, skipElementNames) {
3369 var elemList = form.elements;
3373 for( var i = 0; i < elemList.length ; i++ ) {
3375 if ( typeof(elem.type) == 'undefined' ) {
3379 if ( typeof(elem.type) != 'undefined' && typeof(skipElementNames) != 'undefined'
3380 && SUGAR.util.arrayIndexOf(skipElementNames, elem.name) != -1 )
3385 elemType = elem.type.toLowerCase();
3387 if ( elemType == 'text' || elemType == 'textarea' || elemType == 'password' ) {
3390 else if ( elemType == 'select' || elemType == 'select-one' || elemType == 'select-multiple' ) {
3391 // We have, what I hope, is a select box, time to unselect all options
3392 var optionList = elem.options;
3393 for ( var ii = 0 ; ii < optionList.length ; ii++ ) {
3394 optionList[ii].selected = false;
3397 else if ( elemType == 'radio' || elemType == 'checkbox' ) {
3398 elem.checked = false;
3399 elem.selected = false;
3401 else if ( elemType == 'hidden' ) {
3402 // We only want to reset the hidden values that link to the select boxes.
3403 if ( ( elem.name.length > 3 && elem.name.substring(elem.name.length-3) == '_id' )
3404 || ((elem.name.length > 9) && (elem.name.substring(elem.name.length - 9) == '_id_basic'))
3405 || ( elem.name.length > 12 && elem.name.substring(elem.name.length-12) == '_id_advanced' ) ) {
3410 SUGAR.savedViews.clearColumns = true;
3414 // Code for the column/tab chooser used on homepage and in admin section
3415 SUGAR.tabChooser = function () {
3416 var object_refs = new Array();
3418 /* Describe certain transfers as invalid */
3421 movementCallback: function(left_side, right_side) {},
3422 orderCallback: function(left_side, right_side) {},
3424 freezeOptions: function(left_name, right_name, target) {
3425 if(!SUGAR.tabChooser.frozenOptions) { SUGAR.tabChooser.frozenOptions = []; }
3426 if(!SUGAR.tabChooser.frozenOptions[left_name]) { SUGAR.tabChooser.frozenOptions[left_name] = []; }
3427 if(!SUGAR.tabChooser.frozenOptions[left_name][right_name]) { SUGAR.tabChooser.frozenOptions[left_name][right_name] = []; }
3428 if(typeof target == 'array') {
3429 for(var i in target) {
3430 SUGAR.tabChooser.frozenOptions[left_name][right_name][target[i]] = true;
3433 SUGAR.tabChooser.frozenOptions[left_name][right_name][target] = true;
3437 buildSelectHTML: function(info) {
3438 var text = "<select";
3440 if(typeof (info['select']['size']) != 'undefined') {
3441 text +=" size=\""+ info['select']['size'] +"\"";
3444 if(typeof (info['select']['name']) != 'undefined') {
3445 text +=" name=\""+ info['select']['name'] +"\"";
3448 if(typeof (info['select']['style']) != 'undefined') {
3449 text +=" style=\""+ info['select']['style'] +"\"";
3452 if(typeof (info['select']['onchange']) != 'undefined') {
3453 text +=" onChange=\""+ info['select']['onchange'] +"\"";
3456 if(typeof (info['select']['multiple']) != 'undefined') {
3461 for(i=0; i<info['options'].length;i++) {
3462 option = info['options'][i];
3463 text += "<option value=\""+option['value']+"\" ";
3464 if ( typeof (option['selected']) != 'undefined' && option['selected']== true) {
3467 text += ">"+option['text']+"</option>";
3469 text += "</select>";
3473 left_to_right: function(left_name, right_name, left_size, right_size) {
3474 SUGAR.savedViews.clearColumns = false;
3475 var left_td = document.getElementById(left_name+'_td');
3476 var right_td = document.getElementById(right_name+'_td');
3478 var display_columns_ref = left_td.getElementsByTagName('select')[0];
3479 var hidden_columns_ref = right_td.getElementsByTagName('select')[0];
3481 var selected_left = new Array();
3482 var notselected_left = new Array();
3483 var notselected_right = new Array();
3485 var left_array = new Array();
3487 var frozen_options = SUGAR.tabChooser.frozenOptions;
3488 frozen_options = frozen_options && frozen_options[left_name] && frozen_options[left_name][right_name]?frozen_options[left_name][right_name]:[];
3490 // determine which options are selected in left
3491 for (i=0; i < display_columns_ref.options.length; i++)
3493 if ( display_columns_ref.options[i].selected == true && !frozen_options[display_columns_ref.options[i].value])
3495 selected_left[selected_left.length] = {text: display_columns_ref.options[i].text, value: display_columns_ref.options[i].value};
3499 notselected_left[notselected_left.length] = {text: display_columns_ref.options[i].text, value: display_columns_ref.options[i].value};
3504 for (i=0; i < hidden_columns_ref.options.length; i++)
3506 notselected_right[notselected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
3510 var left_select_html_info = new Object();
3511 var left_options = new Array();
3512 var left_select = new Object();
3514 left_select['name'] = left_name+'[]';
3515 left_select['id'] = left_name;
3516 left_select['size'] = left_size;
3517 left_select['multiple'] = 'true';
3519 var right_select_html_info = new Object();
3520 var right_options = new Array();
3521 var right_select = new Object();
3523 right_select['name'] = right_name+'[]';
3524 right_select['id'] = right_name;
3525 right_select['size'] = right_size;
3526 right_select['multiple'] = 'true';
3528 for (i = 0; i < notselected_right.length; i++) {
3529 right_options[right_options.length] = notselected_right[i];
3532 for (i = 0; i < selected_left.length; i++) {
3533 right_options[right_options.length] = selected_left[i];
3535 for (i = 0; i < notselected_left.length; i++) {
3536 left_options[left_options.length] = notselected_left[i];
3538 left_select_html_info['options'] = left_options;
3539 left_select_html_info['select'] = left_select;
3540 right_select_html_info['options'] = right_options;
3541 right_select_html_info['select'] = right_select;
3542 right_select_html_info['style'] = 'background: lightgrey';
3544 var left_html = this.buildSelectHTML(left_select_html_info);
3545 var right_html = this.buildSelectHTML(right_select_html_info);
3547 left_td.innerHTML = left_html;
3548 right_td.innerHTML = right_html;
3550 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3551 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3553 this.movementCallback(object_refs[left_name], object_refs[right_name]);
3559 right_to_left: function(left_name, right_name, left_size, right_size, max_left) {
3560 SUGAR.savedViews.clearColumns = false;
3561 var left_td = document.getElementById(left_name+'_td');
3562 var right_td = document.getElementById(right_name+'_td');
3564 var display_columns_ref = left_td.getElementsByTagName('select')[0];
3565 var hidden_columns_ref = right_td.getElementsByTagName('select')[0];
3567 var selected_right = new Array();
3568 var notselected_right = new Array();
3569 var notselected_left = new Array();
3571 var frozen_options = SUGAR.tabChooser.frozenOptions;
3572 frozen_options = SUGAR.tabChooser.frozenOptions && SUGAR.tabChooser.frozenOptions[right_name] && SUGAR.tabChooser.frozenOptions[right_name][left_name]?SUGAR.tabChooser.frozenOptions[right_name][left_name]:[];
3574 for (i=0; i < hidden_columns_ref.options.length; i++)
3576 if (hidden_columns_ref.options[i].selected == true && !frozen_options[hidden_columns_ref.options[i].value])
3578 selected_right[selected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
3582 notselected_right[notselected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
3587 if(max_left != '' && (display_columns_ref.length + selected_right.length) > max_left) {
3588 alert('Maximum of ' + max_left + ' columns can be displayed.');
3592 for (i=0; i < display_columns_ref.options.length; i++)
3594 notselected_left[notselected_left.length] = {text:display_columns_ref.options[i].text, value:display_columns_ref.options[i].value};
3598 var left_select_html_info = new Object();
3599 var left_options = new Array();
3600 var left_select = new Object();
3602 left_select['name'] = left_name+'[]';
3603 left_select['id'] = left_name;
3604 left_select['multiple'] = 'true';
3605 left_select['size'] = left_size;
3607 var right_select_html_info = new Object();
3608 var right_options = new Array();
3609 var right_select = new Object();
3611 right_select['name'] = right_name+ '[]';
3612 right_select['id'] = right_name;
3613 right_select['multiple'] = 'true';
3614 right_select['size'] = right_size;
3616 for (i = 0; i < notselected_left.length; i++) {
3617 left_options[left_options.length] = notselected_left[i];
3620 for (i = 0; i < selected_right.length; i++) {
3621 left_options[left_options.length] = selected_right[i];
3623 for (i = 0; i < notselected_right.length; i++) {
3624 right_options[right_options.length] = notselected_right[i];
3626 left_select_html_info['options'] = left_options;
3627 left_select_html_info['select'] = left_select;
3628 right_select_html_info['options'] = right_options;
3629 right_select_html_info['select'] = right_select;
3630 right_select_html_info['style'] = 'background: lightgrey';
3632 var left_html = this.buildSelectHTML(left_select_html_info);
3633 var right_html = this.buildSelectHTML(right_select_html_info);
3635 left_td.innerHTML = left_html;
3636 right_td.innerHTML = right_html;
3638 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3639 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3641 this.movementCallback(object_refs[left_name], object_refs[right_name]);
3646 up: function(name, left_name, right_name) {
3647 SUGAR.savedViews.clearColumns = false;
3648 var left_td = document.getElementById(left_name+'_td');
3649 var right_td = document.getElementById(right_name+'_td');
3650 var td = document.getElementById(name+'_td');
3651 var obj = td.getElementsByTagName('select')[0];
3652 obj = (typeof obj == "string") ? document.getElementById(obj) : obj;
3653 if (obj.tagName.toLowerCase() != "select" && obj.length < 2)
3655 var sel = new Array();
3657 for (i=0; i<obj.length; i++) {
3658 if (obj[i].selected == true) {
3659 sel[sel.length] = i;
3662 for (i=0; i < sel.length; i++) {
3663 if (sel[i] != 0 && !obj[sel[i]-1].selected) {
3664 var tmp = new Array(obj[sel[i]-1].text, obj[sel[i]-1].value);
3665 obj[sel[i]-1].text = obj[sel[i]].text;
3666 obj[sel[i]-1].value = obj[sel[i]].value;
3667 obj[sel[i]].text = tmp[0];
3668 obj[sel[i]].value = tmp[1];
3669 obj[sel[i]-1].selected = true;
3670 obj[sel[i]].selected = false;
3674 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3675 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3677 this.orderCallback(object_refs[left_name], object_refs[right_name]);
3682 down: function(name, left_name, right_name) {
3683 SUGAR.savedViews.clearColumns = false;
3684 var left_td = document.getElementById(left_name+'_td');
3685 var right_td = document.getElementById(right_name+'_td');
3686 var td = document.getElementById(name+'_td');
3687 var obj = td.getElementsByTagName('select')[0];
3688 if (obj.tagName.toLowerCase() != "select" && obj.length < 2)
3690 var sel = new Array();
3691 for (i=obj.length-1; i>-1; i--) {
3692 if (obj[i].selected == true) {
3693 sel[sel.length] = i;
3696 for (i=0; i < sel.length; i++) {
3697 if (sel[i] != obj.length-1 && !obj[sel[i]+1].selected) {
3698 var tmp = new Array(obj[sel[i]+1].text, obj[sel[i]+1].value);
3699 obj[sel[i]+1].text = obj[sel[i]].text;
3700 obj[sel[i]+1].value = obj[sel[i]].value;
3701 obj[sel[i]].text = tmp[0];
3702 obj[sel[i]].value = tmp[1];
3703 obj[sel[i]+1].selected = true;
3704 obj[sel[i]].selected = false;
3708 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3709 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3711 this.orderCallback(object_refs[left_name], object_refs[right_name]);
3716 }(); // end tabChooser
3718 SUGAR.language = function() {
3720 languages : new Array(),
3722 setLanguage: function(module, data) {
3723 if (!SUGAR.language.languages) {
3726 SUGAR.language.languages[module] = data;
3729 get: function(module, str) {
3730 if(typeof SUGAR.language.languages[module] == 'undefined' || typeof SUGAR.language.languages[module][str] == 'undefined')
3734 return SUGAR.language.languages[module][str];
3737 translate: function(module, str)
3739 text = this.get(module, str);
3740 return text != 'undefined' ? text : this.get('app_strings', str);
3745 SUGAR.contextMenu = function() {
3747 objects: new Object(),
3748 objectTypes: new Object(),
3750 * Registers a new object for the context menu.
3751 * objectType - name of the type
3753 * metaData - metaData to pass to the action function
3755 registerObject: function(objectType, id, metaData) {
3756 SUGAR.contextMenu.objects[id] = new Object();
3757 SUGAR.contextMenu.objects[id] = {'objectType' : objectType, 'metaData' : metaData};
3760 * Registers a new object type
3761 * name - name of the type
3762 * menuItems - array of menu items
3764 registerObjectType: function(name, menuItems) {
3765 SUGAR.contextMenu.objectTypes[name] = new Object();
3766 SUGAR.contextMenu.objectTypes[name] = {'menuItems' : menuItems, 'objects' : new Array()};
3769 * Determines which menu item was clicked
3771 getListItemFromEventTarget: function(p_oNode) {
3773 if(p_oNode.tagName == "LI") {
3778 if(p_oNode.tagName == "LI") {
3783 } while((p_oNode = p_oNode.parentNode));
3788 * handles movement within context menu
3790 onContextMenuMove: function() {
3791 var oNode = this.contextEventTarget;
3792 var bDisabled = (oNode.tagName == "UL");
3793 var i = this.getItemGroups()[0].length - 1;
3795 this.getItem(i).cfg.setProperty("disabled", bDisabled);
3800 * handles clicks on a context menu ITEM
3802 onContextMenuItemClick: function(p_sType, p_aArguments, p_oItem) {
3803 var oLI = SUGAR.contextMenu.getListItemFromEventTarget(this.parent.contextEventTarget);
3804 id = this.parent.contextEventTarget.parentNode.id; // id of the target
3805 funct = eval(SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[id]['objectType']]['menuItems'][this.index]['action']);
3806 funct(this.parent.contextEventTarget, SUGAR.contextMenu.objects[id]['metaData']);
3809 * Initializes all context menus registered
3812 for(var i in SUGAR.contextMenu.objects) { // make a variable called objects in objectTypes containg references to all triggers
3813 if(typeof SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'] == 'undefined')
3814 SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'] = new Array();
3815 SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'].push(document.getElementById(i));
3817 // register the menus
3818 for(var i in SUGAR.contextMenu.objectTypes) {
3819 var oContextMenu = new YAHOO.widget.ContextMenu(i, {'trigger': SUGAR.contextMenu.objectTypes[i]['objects']});
3820 var aMainMenuItems = SUGAR.contextMenu.objectTypes[i]['menuItems'];
3821 var nMainMenuItems = aMainMenuItems.length;
3823 for(var j = 0; j < nMainMenuItems; j++) {
3824 oMenuItem = new YAHOO.widget.ContextMenuItem(aMainMenuItems[j].text, { helptext: aMainMenuItems[j].helptext });
3825 oMenuItem.clickEvent.subscribe(SUGAR.contextMenu.onContextMenuItemClick, oMenuItem, true);
3826 oContextMenu.addItem(oMenuItem);
3828 // Add a "move" event handler to the context menu
3829 oContextMenu.moveEvent.subscribe(SUGAR.contextMenu.onContextMenuMove, oContextMenu, true);
3830 // Add a "keydown" event handler to the context menu
3831 oContextMenu.keyDownEvent.subscribe(SUGAR.contextMenu.onContextMenuItemClick, oContextMenu, true);
3832 // Render the context menu
3833 oContextMenu.render(document.body);
3839 SUGAR.contextMenu.actions = function() {
3842 * redirects to a new note with the clicked on object as the target
3844 createNote: function(itemClicked, metaData) {
3845 loc = 'index.php?module=Notes&action=EditView';
3846 for(i in metaData) {
3847 if(i == 'notes_parent_type') loc += '&parent_type=' + metaData[i];
3848 else if(i != 'module' && i != 'parent_type') loc += '&' + i + '=' + metaData[i];
3850 document.location = loc;
3853 * redirects to a new note with the clicked on object as the target
3855 scheduleMeeting: function(itemClicked, metaData) {
3856 loc = 'index.php?module=Meetings&action=EditView';
3857 for(i in metaData) {
3858 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3860 document.location = loc;
3863 * redirects to a new note with the clicked on object as the target
3865 scheduleCall: function(itemClicked, metaData) {
3866 loc = 'index.php?module=Calls&action=EditView';
3867 for(i in metaData) {
3868 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3870 document.location = loc;
3873 * redirects to a new contact with the clicked on object as the target
3875 createContact: function(itemClicked, metaData) {
3876 loc = 'index.php?module=Contacts&action=EditView';
3877 for(i in metaData) {
3878 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3880 document.location = loc;
3883 * redirects to a new task with the clicked on object as the target
3885 createTask: function(itemClicked, metaData) {
3886 loc = 'index.php?module=Tasks&action=EditView';
3887 for(i in metaData) {
3888 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3890 document.location = loc;
3893 * redirects to a new opportunity with the clicked on object as the target
3895 createOpportunity: function(itemClicked, metaData) {
3896 loc = 'index.php?module=Opportunities&action=EditView';
3897 for(i in metaData) {
3898 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3900 document.location = loc;
3903 * redirects to a new opportunity with the clicked on object as the target
3905 createCase: function(itemClicked, metaData) {
3906 loc = 'index.php?module=Cases&action=EditView';
3907 for(i in metaData) {
3908 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3910 document.location = loc;
3913 * handles add to favorites menu selection
3915 addToFavorites: function(itemClicked, metaData) {
3916 success = function(data) {
3918 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});
3923 //if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.contextMenu.init);
3925 // initially from popup_parent_helper.js
3926 var popup_request_data;
3929 function get_popup_request_data()
3931 return YAHOO.lang.JSON.stringify(window.document.popup_request_data);
3934 function get_close_popup()
3936 return window.document.close_popup;
3939 function open_popup(module_name, width, height, initial_filter, close_popup, hide_clear_button, popup_request_data, popup_mode, create, metadata)
3941 if (typeof(popupCount) == "undefined" || popupCount == 0)
3944 // set the variables that the popup will pull from
3945 window.document.popup_request_data = popup_request_data;
3946 window.document.close_popup = close_popup;
3948 //globally changing width and height of standard pop up window from 600 x 400 to 800 x 800
3949 width = (width == 600) ? 800 : width;
3950 height = (height == 400) ? 800 : height;
3954 + 'module=' + module_name
3957 if (initial_filter != '') {
3958 URL += '&query=true' + initial_filter;
3959 // Bug 41891 - Popup Window Name
3960 popupName = initial_filter.replace(/[^a-z_0-9]+/ig, '_');
3961 windowName = module_name + '_popup_window' + popupName;
3963 windowName = module_name + '_popup_window' + popupCount;
3967 if (hide_clear_button) {
3968 URL += '&hide_clear_button=true';
3971 windowFeatures = 'width=' + width
3972 + ',height=' + height
3973 + ',resizable=1,scrollbars=1';
3975 if (popup_mode == '' && popup_mode == 'undefined') {
3976 popup_mode='single';
3978 URL+='&mode='+popup_mode;
3979 if (create == '' && create == 'undefined') {
3982 URL+='&create='+create;
3984 if (metadata != '' && metadata != 'undefined') {
3985 URL+='&metadata='+metadata;
3988 win = SUGAR.util.openWindow(URL, windowName, windowFeatures);
3992 // put the focus on the popup if the browser supports the focus() method
3996 win.popupCount = popupCount;
4002 * The reply data must be a JSON array structured with the following information:
4003 * 1) form name to populate
4004 * 2) associative array of input names to values for populating the form
4006 var from_popup_return = false;
4008 function set_return_basic(popup_reply_data,filter)
4010 var form_name = popup_reply_data.form_name;
4011 var name_to_value_array = popup_reply_data.name_to_value_array;
4012 for (var the_key in name_to_value_array)
4014 if(the_key == 'toJSON')
4018 else if(the_key.match(filter))
4020 var displayValue=name_to_value_array[the_key].replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');;
4021 // begin andopes change: support for enum fields (SELECT)
4022 if(window.document.forms[form_name] && window.document.forms[form_name].elements[the_key]) {
4023 if(window.document.forms[form_name].elements[the_key].tagName == 'SELECT') {
4024 var selectField = window.document.forms[form_name].elements[the_key];
4025 for(var i = 0; i < selectField.options.length; i++) {
4026 if(selectField.options[i].text == displayValue) {
4027 selectField.options[i].selected = true;
4028 SUGAR.util.callOnChangeListers(selectField);
4033 window.document.forms[form_name].elements[the_key].value = displayValue;
4034 SUGAR.util.callOnChangeListers(window.document.forms[form_name].elements[the_key]);
4037 // end andopes change: support for enum fields (SELECT)
4042 function set_return(popup_reply_data)
4044 from_popup_return = true;
4045 var form_name = popup_reply_data.form_name;
4046 var name_to_value_array = popup_reply_data.name_to_value_array;
4047 if(typeof name_to_value_array != 'undefined' && name_to_value_array['account_id'])
4050 var label_data_str = '';
4051 var current_label_data_str = '';
4052 for (var the_key in name_to_value_array)
4054 if(the_key == 'toJSON')
4060 var displayValue=name_to_value_array[the_key].replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');
4061 if(window.document.forms[form_name] && document.getElementById(the_key+'_label') && !the_key.match(/account/)) {
4062 var data_label = document.getElementById(the_key+'_label').innerHTML.replace(/\n/gi,'');
4063 label_str += data_label + ' \n';
4064 label_data_str += data_label + ' ' + displayValue + '\n';
4065 if(window.document.forms[form_name].elements[the_key]) {
4066 current_label_data_str += data_label + ' ' + window.document.forms[form_name].elements[the_key].value +'\n';
4071 if(label_data_str != label_str && current_label_data_str != label_str){
4072 if(confirm(SUGAR.language.get('app_strings', 'NTC_OVERWRITE_ADDRESS_PHONE_CONFIRM') + '\n\n' + label_data_str))
4074 set_return_basic(popup_reply_data,/\S/);
4076 set_return_basic(popup_reply_data,/account/);
4078 }else if(label_data_str != label_str && current_label_data_str == label_str){
4079 set_return_basic(popup_reply_data,/\S/);
4080 }else if(label_data_str == label_str){
4081 set_return_basic(popup_reply_data,/account/);
4084 set_return_basic(popup_reply_data,/\S/);
4088 function set_return_lead_conv(popup_reply_data) {
4089 set_return(popup_reply_data);
4090 if (document.getElementById('lead_conv_ac_op_sel') && typeof onBlurKeyUpHandler=='function') {
4091 onBlurKeyUpHandler();
4095 function set_return_and_save(popup_reply_data)
4097 var form_name = popup_reply_data.form_name;
4098 var name_to_value_array = popup_reply_data.name_to_value_array;
4100 for (var the_key in name_to_value_array)
4102 if(the_key == 'toJSON')
4108 window.document.forms[form_name].elements[the_key].value = name_to_value_array[the_key];
4112 window.document.forms[form_name].return_module.value = window.document.forms[form_name].module.value;
4113 window.document.forms[form_name].return_action.value = 'DetailView';
4114 window.document.forms[form_name].return_id.value = window.document.forms[form_name].record.value;
4115 window.document.forms[form_name].action.value = 'Save';
4116 window.document.forms[form_name].submit();
4120 * This is a helper function to construct the initial filter that can be
4121 * passed into the open_popup() function. It assumes that there is an
4122 * account_id and account_name field in the given form_name to use to
4123 * construct the intial filter string.
4125 function get_initial_filter_by_account(form_name)
4127 var account_id = window.document.forms[form_name].account_id.value;
4128 var account_name = escape(window.document.forms[form_name].account_name.value);
4129 var initial_filter = "&account_id=" + account_id + "&account_name=" + account_name;
4131 return initial_filter;
4133 // end code from popup_parent_helper.js
4135 // begin code for address copy
4137 * This is a function used by the Address widget that will fill
4138 * in the given array fields using the fromKey and toKey as a
4139 * prefix into the form objects HTML elements.
4141 * @param form The HTML form object to parse
4142 * @param fromKey The prefix of elements to copy from
4143 * @param toKey The prefix of elements to copy into
4144 * @return boolean true if successful, false otherwise
4146 function copyAddress(form, fromKey, toKey) {
4148 var elems = new Array("address_street", "address_city", "address_state", "address_postalcode", "address_country");
4149 var checkbox = document.getElementById(toKey + "_checkbox");
4151 if(typeof checkbox != "undefined") {
4152 if(!checkbox.checked) {
4154 t = toKey + "_" + elems[x];
4155 document.getElementById(t).removeAttribute('readonly');
4159 f = fromKey + "_" + elems[x];
4160 t = toKey + "_" + elems[x];
4162 document.getElementById(t).value = document.getElementById(f).value;
4163 document.getElementById(t).setAttribute('readonly', true);
4169 // end code for address copy
4172 * This function is used in Email Template Module.
4173 * It will check whether the template is used in Campaing->EmailMarketing.
4174 * If true, it will notify user.
4177 function check_deletable_EmailTemplate() {
4178 id = document.getElementsByName('record')[0].value;
4179 currentForm = document.getElementById('form');
4181 success:function(r) {
4182 if(r.responseText == 'true') {
4183 if(!confirm(SUGAR.language.get('app_strings','NTC_TEMPLATE_IS_USED'))) {
4187 if(!confirm(SUGAR.language.get('app_strings','NTC_DELETE_CONFIRMATION'))) {
4191 currentForm.return_module.value='EmailTemplates';
4192 currentForm.return_action.value='ListView';
4193 currentForm.action.value='Delete';
4194 currentForm.submit();
4197 url = "index.php?module=EmailTemplates&action=CheckDeletable&from=DetailView&to_pdf=1&record="+id;
4198 YAHOO.util.Connect.asyncRequest('POST',url, call_back,null);
4202 remove_upload_imagefile : function(field_name) {
4203 var field=document.getElementById('remove_imagefile_' + field_name);
4206 //enable the file upload button.
4207 var field=document.getElementById( field_name);
4208 field.style.display="";
4210 //hide the image and remove button.
4211 var field=document.getElementById('img_' + field_name);
4212 field.style.display="none";
4213 var field=document.getElementById('bt_remove_' + field_name);
4214 field.style.display="none";
4216 if(document.getElementById(field_name + '_duplicate')) {
4217 var field = document.getElementById(field_name + '_duplicate');
4222 confirm_imagefile : function(field_name) {
4223 var field=document.getElementById(field_name);
4224 var filename=field.value;
4225 var fileExtension = filename.substring(filename.lastIndexOf(".")+1);
4226 fileExtension = fileExtension.toLowerCase();
4227 if (fileExtension == "jpg" || fileExtension == "jpeg"
4228 || fileExtension == "gif" || fileExtension == "png" || fileExtension == "bmp"){
4233 alert(SUGAR.language.get('app_strings', 'LBL_UPLOAD_IMAGE_FILE_INVALID'));
4237 lightbox : function(image)
4239 if (typeof(SUGAR.image.lighboxWindow) == "undefined")
4240 SUGAR.image.lighboxWindow = new YAHOO.widget.SimpleDialog('sugarImageViewer', {
4243 id:'sugarMsgWindow',
4246 msg: "<img src='" + image + "'> </img>",
4249 SUGAR.image.lighboxWindow.setBody("<img src='" + image + "'> </img>");
4250 SUGAR.image.lighboxWindow.render(document.body);
4251 SUGAR.image.lighboxWindow.show();
4252 SUGAR.image.lighboxWindow.center()
4256 SUGAR.append(SUGAR.util, {
4257 isTouchScreen: function() {
4258 // first check if we have forced use of the touch enhanced interface
4259 if (Get_Cookie("touchscreen") == '1') {
4263 // next check if we should use the touch interface with our device
4264 if ((navigator.userAgent.match(/iPad/i) != null)) {
4271 isLoginPage: function(content) {
4272 //skip if this is packageManager screen
4273 if(SUGAR.util.isPackageManager()) {return false;}
4274 var loginPageStart = "<!DOCTYPE";
4275 if (content.substr(0, loginPageStart.length) == loginPageStart && content.indexOf("<html>") != -1 && content.indexOf("login_module") != -1) {
4276 window.location.href = window.location.protocol + window.location.pathname;
4281 isPackageManager: function(){
4282 if(typeof(document.the_form) !='undefined' && typeof(document.the_form.language_pack_escaped) !='undefined'){
4284 }else{return false;}
4287 ajaxCallInProgress: function(){
4289 //First check if we are in a popup.
4290 if (typeof (send_back) != "function"){
4291 //If the page content is blank, it means we are probably still waiting on something
4292 var c = document.getElementById("content");
4293 if (!c) return true;
4294 t = YAHOO.lang.trim(SUGAR.util.innerText(c));
4296 return SUGAR_callsInProgress != 0 || t == "";
4298 //Firefox doesn't support innerText (textContent includes script content)
4299 innerText : function(el) {
4300 if (el.tagName == "SCRIPT")
4302 if(typeof(el.innerText) == "string")
4303 return el.innerText;
4305 for (var i in el.childNodes){
4306 var c = el.childNodes[i];
4307 if (typeof(c) != "object")
4309 if (typeof(c.nodeName) == "string" && c.nodeName == "#text")
4312 t += SUGAR.util.innerText(c);
4317 callOnChangeListers: function(field){
4318 var listeners = YAHOO.util.Event.getListeners(field, 'change');
4319 if (listeners != null) {
4320 for (var i = 0; i < listeners.length; i++) {
4321 var l = listeners[i];
4322 l.fn.call(l.scope ? l.scope : this, l.obj);
4327 closeActivityPanel: {
4328 show:function(module,id,new_status,viewType,parentContainerId){
4329 if (SUGAR.util.closeActivityPanel.panel)
4330 SUGAR.util.closeActivityPanel.panel.destroy();
4331 var singleModule = SUGAR.language.get("app_list_strings", "moduleListSingular")[module];
4332 singleModule = typeof(singleModule != 'undefined') ? singleModule.toLowerCase() : '';
4333 var closeText = SUGAR.language.get("app_strings", "LBL_CLOSE_ACTIVITY_CONFIRM").replace("#module#",singleModule);
4334 SUGAR.util.closeActivityPanel.panel =
4335 new YAHOO.widget.SimpleDialog("closeActivityDialog",
4342 constraintoviewport: true,
4343 buttons: [ { text:SUGAR.language.get("app_strings", "LBL_EMAIL_OK"), handler:function(){
4344 if (SUGAR.util.closeActivityPanel.panel)
4345 SUGAR.util.closeActivityPanel.panel.hide();
4347 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_SAVING'));
4348 var args = "action=save&id=" + id + "&record=" + id + "&status=" + new_status + "&module=" + module;
4349 // 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
4350 // TODO: Take id out and regression test. Left id in for now to not create any other unexpected problems
4351 //var args = "action=save&id=" + id + "&status=" + new_status + "&module=" + module;
4355 // Bug 45792: Firefox seems to believe reloading a page after an ajax request means you are re-submitting a form and gives you the warning for it.
4356 // So instead, we reload from a timeout
4357 window.setTimeout("window.location.reload(true);",0);
4359 argument:{'parentContainerId':parentContainerId}
4362 YAHOO.util.Connect.asyncRequest('POST', 'index.php', callback, args);
4364 }, isDefault:true },
4365 { text:SUGAR.language.get("app_strings", "LBL_EMAIL_CANCEL"), handler:function(){SUGAR.util.closeActivityPanel.panel.hide(); }} ]
4368 SUGAR.util.closeActivityPanel.panel.setHeader(SUGAR.language.get("app_strings", "LBL_CLOSE_ACTIVITY_HEADER"));
4369 SUGAR.util.closeActivityPanel.panel.render(document.body);
4370 SUGAR.util.closeActivityPanel.panel.show();
4374 setEmailPasswordDisplay: function(id, exists) {
4375 link = document.getElementById(id+'_link');
4376 pwd = document.getElementById(id);
4377 if(!pwd || !link) return;
4379 pwd.style.display = 'none';
4380 link.style.display = '';
4382 pwd.style.display = '';
4383 link.style.display = 'none';
4387 setEmailPasswordEdit: function(id) {
4388 link = document.getElementById(id+'_link');
4389 pwd = document.getElementById(id);
4390 if(!pwd || !link) return;
4391 pwd.style.display = '';
4392 link.style.display = 'none';
4396 * Compares a filename with a supplied array of allowed file extensions.
4397 * @param fileName string
4398 * @param allowedTypes array of allowed file extensions
4401 validateFileExt: function(fileName, allowedTypes) {
4402 var ext = fileName.split('.').pop().toLowerCase();
4404 for (var i = allowedTypes.length; i >= 0; i--) {
4405 if (ext === allowedTypes[i]) {
4413 arrayIndexOf: function(arr, val, start) {
4414 if (typeof arr.indexOf == "function")
4415 return arr.indexOf(val, start);
4416 for (var i = (start || 0), j = arr.length; i < j; i++) {
4417 if (arr[i] === val) {
4425 SUGAR.clearRelateField = function(form, name, id)
4427 if (typeof form[name] == "object"){
4428 form[name].value = '';
4429 SUGAR.util.callOnChangeListers(form[name]);
4432 if (typeof form[id] == "object"){
4433 form[id].value = '';
4434 SUGAR.util.callOnChangeListers(form[id]);
4437 if(typeof(SUGAR.AutoComplete) == 'undefined') SUGAR.AutoComplete = {};
4439 SUGAR.AutoComplete.getOptionsArray = function(options_index){
4440 var return_arr = [];
4442 var opts = SUGAR.language.get('app_list_strings', options_index);
4443 if(typeof(opts) != 'undefined'){
4445 // Since we are using auto complete, we excluse blank dropdown entries since they can just leave it blank
4446 if(key != '' && opts[key] != ''){
4449 item['text'] = opts[key];
4450 return_arr.push(item);
4457 if(typeof(SUGAR.MultiEnumAutoComplete) == 'undefined') SUGAR.MultiEnumAutoComplete = {};
4459 SUGAR.MultiEnumAutoComplete.getMultiSelectKeysFromValues = function(options_index, val_string){
4460 var opts = SUGAR.language.get('app_list_strings', options_index);
4461 var selected_values = val_string.split(", ");
4462 // YUI AutoComplete adds a blank. We remove it automatically here
4463 if(selected_values.length > 0 && selected_values.indexOf('') == selected_values.length - 1){
4464 selected_values.pop();
4466 var final_arr = new Array();
4467 for(idx in selected_values){
4469 if(selected_values[idx] == opts[o_idx]){
4470 final_arr.push(o_idx);
4477 SUGAR.MultiEnumAutoComplete.getMultiSelectValuesFromKeys = function(options_index, val_string){
4478 var opts = SUGAR.language.get('app_list_strings', options_index);
4479 val_string=val_string.replace(/^\^/,'').replace(/\^$/,'') //fixes bug where string starts or ends with ^
4480 var selected_values = val_string.split("^,^");
4482 // YUI AutoComplete adds a blank. We remove it automatically here
4483 if(selected_values.length > 0 && selected_values.indexOf('') == selected_values.length - 1){
4484 selected_values.pop();
4487 var final_arr = new Array();
4488 for(idx in selected_values){
4490 if(selected_values[idx] == o_idx){
4491 final_arr.push(opts[o_idx]);