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;
125 var callbackIndex = 16;
127 var validate = new Array();
129 var requiredTxt = 'Missing Required Field:'
130 var invalidTxt = 'Invalid Value:'
131 var secondsSinceLoad = 0;
132 var inputsWithErrors = new Array();
133 var tabsWithErrors = new Array();
134 var lastSubmitTime = 0;
135 var alertList = new Array();
136 var oldStartsWith = '';
141 * As of Sugar version 6.2.3 (MSIE Version 9) this function is deprecated. The preferred method is to use the
142 * user agent check supplied by YUI to check for IE:
144 * for checking if a browser is IE in general : if(YAHOO.env.ua.ie) {...}
146 * or for checking specific versions: if (YAHOO.env.ua.ie >= 5.5 && YAHOO.env.ua.ie < 9) {...}
149 function isSupportedIE() {
150 var userAgent = navigator.userAgent.toLowerCase() ;
152 // IE Check supports ActiveX controls
153 if (userAgent.indexOf("msie") != -1 && userAgent.indexOf("mac") == -1 && userAgent.indexOf("opera") == -1) {
154 var version = navigator.appVersion.match(/MSIE (.\..)/)[1] ;
155 if(version >= 5.5 && version < 10) {
163 SUGAR.isIE = isSupportedIE();
164 var isSafari = (navigator.userAgent.toLowerCase().indexOf('safari')!=-1);
166 // escapes regular expression characters
167 RegExp.escape = function(text) { // http://simon.incutio.com/archive/2006/01/20/escape
168 if (!arguments.callee.sRE) {
169 var specials = ['/', '.', '*', '+', '?', '|','(', ')', '[', ']', '{', '}', '\\'];
170 arguments.callee.sRE = new RegExp('(\\' + specials.join('|\\') + ')', 'g');
172 return text.replace(arguments.callee.sRE, '\\$1');
175 function addAlert(type, name,subtitle, description,time, redirect) {
176 var addIndex = alertList.length;
177 alertList[addIndex]= new Array();
178 alertList[addIndex]['name'] = name;
179 alertList[addIndex]['type'] = type;
180 alertList[addIndex]['subtitle'] = subtitle;
181 alertList[addIndex]['description'] = description.replace(/<br>/gi, "\n").replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');
182 alertList[addIndex]['time'] = time;
183 alertList[addIndex]['done'] = 0;
184 alertList[addIndex]['redirect'] = redirect;
186 function checkAlerts() {
187 secondsSinceLoad += 1;
190 for(mj = 0 ; mj < alertList.length; mj++) {
191 if(alertList[mj]['done'] == 0) {
192 if(alertList[mj]['time'] < secondsSinceLoad && alertList[mj]['time'] > -1 ) {
193 alertmsg = alertList[mj]['type'] + ":" + alertList[mj]['name'] + "\n" +alertList[mj]['subtitle']+ "\n"+ alertList[mj]['description'] + "\n\n";
194 alertList[mj]['done'] = 1;
195 if(alertList[mj]['redirect'] == '') {
198 else if(confirm(alertmsg)) {
199 window.location = alertList[mj]['redirect'];
205 setTimeout("checkAlerts()", 1000);
208 function toggleDisplay(id) {
209 if(this.document.getElementById(id).style.display == 'none') {
210 this.document.getElementById(id).style.display = '';
211 if(this.document.getElementById(id+"link") != undefined) {
212 this.document.getElementById(id+"link").style.display = 'none';
214 if(this.document.getElementById(id+"_anchor") != undefined)
215 this.document.getElementById(id+"_anchor").innerHTML='[ - ]';
218 this.document.getElementById(id).style.display = 'none'
219 if(this.document.getElementById(id+"link") != undefined) {
220 this.document.getElementById(id+"link").style.display = '';
222 if(this.document.getElementById(id+"_anchor") != undefined)
223 this.document.getElementById(id+"_anchor").innerHTML='[+]';
227 function checkAll(form, field, value) {
228 for (i = 0; i < form.elements.length; i++) {
229 if(form.elements[i].name == field)
230 form.elements[i].checked = value;
234 function replaceAll(text, src, rep) {
235 offset = text.toLowerCase().indexOf(src.toLowerCase());
236 while(offset != -1) {
237 text = text.substring(0, offset) + rep + text.substring(offset + src.length ,text.length);
238 offset = text.indexOf( src, offset + rep.length + 1);
243 function addForm(formname) {
244 validate[formname] = new Array();
247 function addToValidate(formname, name, type, required, msg) {
248 if(typeof validate[formname] == 'undefined') {
251 validate[formname][validate[formname].length] = new Array(name, type,required, msg);
254 // Bug #47961 Callback validator definition
255 function addToValidateCallback(formname, name, type, required, msg, callback)
257 addToValidate(formname, name, type, required, msg);
258 var iIndex = validate[formname].length -1;
259 validate[formname][iIndex][jstypeIndex] = 'callback';
260 validate[formname][iIndex][callbackIndex] = callback;
263 function addToValidateRange(formname, name, type,required, msg,min,max) {
264 addToValidate(formname, name, type,required, msg);
265 validate[formname][validate[formname].length - 1][jstypeIndex] = 'range'
266 validate[formname][validate[formname].length - 1][minIndex] = min;
267 validate[formname][validate[formname].length - 1][maxIndex] = max;
270 function addToValidateIsValidDate(formname, name, type, required, msg) {
271 addToValidate(formname, name, type, required, msg);
272 validate[formname][validate[formname].length - 1][jstypeIndex] = 'date'
275 function addToValidateIsValidTime(formname, name, type, required, msg) {
276 addToValidate(formname, name, type, required, msg);
277 validate[formname][validate[formname].length - 1][jstypeIndex] = 'time'
280 function addToValidateDateBefore(formname, name, type, required, msg, compareTo) {
281 addToValidate(formname, name, type,required, msg);
282 validate[formname][validate[formname].length - 1][jstypeIndex] = 'isbefore'
283 validate[formname][validate[formname].length - 1][compareToIndex] = compareTo;
286 function addToValidateDateBeforeAllowBlank(formname, name, type, required, msg, compareTo, allowBlank) {
287 addToValidate(formname, name, type,required, msg);
288 validate[formname][validate[formname].length - 1][jstypeIndex] = 'isbefore'
289 validate[formname][validate[formname].length - 1][compareToIndex] = compareTo;
290 validate[formname][validate[formname].length - 1][allowblank] = allowBlank;
293 function addToValidateBinaryDependency(formname, name, type, required, msg, compareTo) {
294 addToValidate(formname, name, type, required, msg);
295 validate[formname][validate[formname].length - 1][jstypeIndex] = 'binarydep';
296 validate[formname][validate[formname].length - 1][compareToIndex] = compareTo;
299 function addToValidateComparison(formname, name, type, required, msg, compareTo) {
300 addToValidate(formname, name, type, required, msg);
301 validate[formname][validate[formname].length - 1][jstypeIndex] = 'comparison';
302 validate[formname][validate[formname].length - 1][compareToIndex] = compareTo;
305 function addToValidateIsInArray(formname, name, type, required, msg, arr, operator) {
306 addToValidate(formname, name, type, required, msg);
307 validate[formname][validate[formname].length - 1][jstypeIndex] = 'in_array';
308 validate[formname][validate[formname].length - 1][arrIndex] = arr;
309 validate[formname][validate[formname].length - 1][operatorIndex] = operator;
312 function addToValidateVerified(formname, name, type, required, msg, arr, operator) {
313 addToValidate(formname, name, type, required, msg);
314 validate[formname][validate[formname].length - 1][jstypeIndex] = 'verified';
317 function addToValidateLessThan(formname, name, type, required, msg, max, max_field_msg) {
318 addToValidate(formname, name, type, required, msg);
319 validate[formname][validate[formname].length - 1][jstypeIndex] = 'less';
320 validate[formname][validate[formname].length - 1][maxIndex] = max;
321 validate[formname][validate[formname].length - 1][altMsgIndex] = max_field_msg;
324 function addToValidateMoreThan(formname, name, type, required, msg, min) {
325 addToValidate(formname, name, type, required, msg);
326 validate[formname][validate[formname].length - 1][jstypeIndex] = 'more';
327 validate[formname][validate[formname].length - 1][minIndex] = min;
331 function removeFromValidate(formname, name) {
332 for(i = 0; i < validate[formname].length; i++)
334 if(validate[formname][i][nameIndex] == name)
336 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
340 function checkValidate(formname, name) {
341 if(validate[formname]){
342 for(i = 0; i < validate[formname].length; i++){
343 if(validate[formname][i][nameIndex] == name){
350 var formsWithFieldLogic=null;
351 var formWithPrecision =null;
352 function addToValidateFieldLogic(formId,minFieldId, maxFieldId, defaultFieldId, lenFieldId,type,msg){
353 this.formId = document.getElementById(formId);
354 this.min=document.getElementById(minFieldId);
355 this.max= document.getElementById(maxFieldId);
356 this._default= document.getElementById(defaultFieldId);
357 this.len = document.getElementById(lenFieldId);
361 //@params: formid- Dom id of the form containing the precision and float fields
362 // valudId- Dom id of the field containing a float whose precision is to be checked.
363 // precisionId- Dom id of the field containing precision value.
364 function addToValidatePrecision(formId, valueId, precisionId){
365 this.form = document.getElementById(formId);
366 this.float = document.getElementById(valueId);
367 this.precision = document.getElementById(precisionId);
370 //function checkLength(value, referenceValue){
374 function isValidPrecision(value, precision){
375 value = trim(value.toString());
381 if( (precision == "0") ){
382 if (value.indexOf(dec_sep)== -1){
389 if(value.charAt(value.length-precision-1) == num_grp_sep){
390 if(value.substr(value.indexOf(dec_sep), 1)==dec_sep){
395 var actualPrecision = value.substr(value.indexOf(dec_sep)+1, value.length).length;
396 return actualPrecision == precision;
398 function toDecimal(original, precision) {
399 precision = (precision == null) ? 2 : precision;
400 num = Math.pow(10, precision);
401 temp = Math.round(original*num)/num;
402 if((temp * 100) % 100 == 0)
404 if((temp * 10) % 10 == 0)
409 function isInteger(s) {
410 if(typeof num_grp_sep != 'undefined' && typeof dec_sep != 'undefined')
412 s = unformatNumberNoParse(s, num_grp_sep, dec_sep).toString();
414 return /^[+-]?[0-9]*$/.test(s) ;
417 function isDecimal(s) {
418 if (typeof s == "string" && s == "") // bug# 46530, this is required in order to
419 return true; // not check empty decimal fields
421 if(typeof num_grp_sep != 'undefined' && typeof dec_sep != 'undefined')
423 s = unformatNumberNoParse(s, num_grp_sep, dec_sep).toString();
425 return /^[+-]?[0-9]+\.?[0-9]*$/.test(s) ;
428 function isNumeric(s) {
432 var date_reg_positions = {'Y': 1,'m': 2,'d': 3};
433 var date_reg_format = '([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})'
434 function isDate(dtStr) {
436 if(dtStr.length== 0) {
440 // Check that we have numbers
441 myregexp = new RegExp(date_reg_format)
442 if(!myregexp.test(dtStr))
449 var dateParts = dtStr.match(date_reg_format);
450 for(key in date_reg_positions) {
451 index = date_reg_positions[key];
453 m = dateParts[index];
454 } else if(key == 'd') {
455 d = dateParts[index];
457 y = dateParts[index];
461 // Check that date is real
462 var dd = new Date(y,m,0);
463 // reject negative years
466 // reject month less than 1 and greater than 12
469 // reject days less than 1 or days not in month (e.g. February 30th)
470 if (d < 1 || d > dd.getDate())
475 function getDateObject(dtStr) {
476 if(dtStr.length== 0) {
480 myregexp = new RegExp(date_reg_format)
482 if(myregexp.exec(dtStr)) var dt = myregexp.exec(dtStr)
485 var yr = dt[date_reg_positions['Y']];
486 var mh = dt[date_reg_positions['m']];
487 var dy = dt[date_reg_positions['d']];
488 var dtar = dtStr.split(' ');
489 if(typeof(dtar[1])!='undefined' && isTime(dtar[1])) {//if it is a timedate, we should make date1 to have time value
490 var t1 = dtar[1].replace(/am/i,' AM');
491 var t1 = t1.replace(/pm/i,' PM');
492 //bug #37977: where time format 23.00 causes java script error
493 t1=t1.replace(/\./, ':');
494 date1 = new Date(Date.parse(mh+'/'+dy+ '/'+yr+' '+t1));
498 var date1 = new Date();
499 date1.setFullYear(yr); // xxxx 4 char year
500 date1.setMonth(mh-1); // 0-11 Bug 4048: javascript Date obj months are 0-index
501 date1.setDate(dy); // 1-31
506 function isBefore(value1, value2) {
507 var d1 = getDateObject(value1);
508 var d2 = getDateObject(value2);
509 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.
515 function isValidEmail(emailStr) {
517 if(emailStr.length== 0) {
520 // cn: bug 7128, a period at the end of the string mangles checks. (switched to accept spaces and delimiters)
521 var lastChar = emailStr.charAt(emailStr.length - 1);
522 if(!lastChar.match(/[^\.]/i)) {
525 //bug 40068, According to rules in page 6 of http://www.apps.ietf.org/rfc/rfc3696.html#sec-3,
526 //first character of local part of an email address
527 //should not be a period i.e. '.'
529 var firstLocalChar=emailStr.charAt(0);
530 if(firstLocalChar.match(/\./)){
534 //bug 40068, According to rules in page 6 of http://www.apps.ietf.org/rfc/rfc3696.html#sec-3,
535 //last character of local part of an email address
536 //should not be a period i.e. '.'
538 var pos=emailStr.lastIndexOf("@");
539 var localPart = emailStr.substr(0, pos);
540 var lastLocalChar=localPart.charAt(localPart.length - 1);
541 if(lastLocalChar.match(/\./)){
548 while ((results = reg.exec(emailStr)) != null) {
549 var original = results[0];
550 parsedResult = results[0].replace(';', '::;::');
551 emailStr = emailStr.replace (original, parsedResult);
555 while ((results = reg.exec(emailStr)) != null) {
556 var original = results[0];
557 //Check if we were using ; as a delimiter. If so, skip the commas
558 if(original.indexOf("::;::") == -1) {
559 var parsedResult = results[0].replace(',', '::;::');
560 emailStr = emailStr.replace (original, parsedResult);
564 // mfh: bug 15010 - more practical implementation of RFC 2822 from http://www.regular-expressions.info/email.html, modifed to accept CAPITAL LETTERS
565 //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))
568 //bug 40068, According to rules in page 6 of http://www.apps.ietf.org/rfc/rfc3696.html#sec-3,
569 //allowed special characters ! # $ % & ' * + - / = ? ^ _ ` . { | } ~ in local part
570 var emailArr = emailStr.split(/::;::/);
571 for (var i = 0; i < emailArr.length; i++) {
572 var emailAddress = emailArr[i];
573 if (trim(emailAddress) != '') {
574 if(!/^\s*[\w.%+\-&'#!\$\*=\?\^_`\{\}~\/]+@([A-Z0-9-]+\.)*[A-Z0-9-]+\.[\w-]{2,}\s*$/i.test(emailAddress) &&
575 !/^.*<[A-Z0-9._%+\-&'#!\$\*=\?\^_`\{\}~]+?@([A-Z0-9-]+\.)*[A-Z0-9-]+\.[\w-]{2,}>\s*$/i.test(emailAddress)) {
584 function isValidPhone(phoneStr) {
585 if(phoneStr.length== 0) {
588 if(!/^[0-9\-\(\)\s]+$/.test(phoneStr))
592 function isFloat(floatStr) {
593 if(floatStr.length== 0) {
596 if(!(typeof(num_grp_sep)=='undefined' || typeof(dec_sep)=='undefined')) {
597 floatStr = unformatNumberNoParse(floatStr, num_grp_sep, dec_sep).toString();
600 return /^(-)?[0-9\.]+$/.test(floatStr);
602 function isDBName(str) {
607 // must start with a letter
608 if(!/^[a-zA-Z][a-zA-Z\_0-9]*$/.test(str))
612 var time_reg_format = "[0-9]{1,2}\:[0-9]{2}";
613 function isTime(timeStr) {
614 var time_reg_format = "[0-9]{1,2}\:[0-9]{2}";
615 time_reg_format = time_reg_format.replace('([ap]m)', '');
616 time_reg_format = time_reg_format.replace('([AP]M)', '');
617 if(timeStr.length== 0){
620 //we now support multiple time formats
621 myregexp = new RegExp(time_reg_format)
622 if(!myregexp.test(timeStr))
628 function inRange(value, min, max) {
629 if (typeof num_grp_sep != 'undefined' && typeof dec_sep != 'undefined')
630 value = unformatNumberNoParse(value, num_grp_sep, dec_sep).toString();
631 return value >= min && value <= max;
634 function bothExist(item1, item2) {
635 if(typeof item1 == 'undefined') { return false; }
636 if(typeof item2 == 'undefined') { return false; }
637 if((item1 == '' && item2 != '') || (item1 != '' && item2 == '') ) { return false; }
641 trim = YAHOO.lang.trim;
644 function check_form(formname) {
645 if (typeof(siw) != 'undefined' && siw
646 && typeof(siw.selectingSomething) != 'undefined' && siw.selectingSomething)
648 return validate_form(formname, '');
651 function add_error_style(formname, input, txt, flash) {
652 var raiseFlag = false;
653 if (typeof flash == "undefined")
656 inputHandle = typeof input == "object" ? input : document.forms[formname][input];
657 style = get_current_bgcolor(inputHandle);
659 // strip off the colon at the end of the warning strings
660 if ( txt.substring(txt.length-1) == ':' )
661 txt = txt.substring(0,txt.length-1)
663 // Bug 28249 - To help avoid duplicate messages for an element, strip off extra messages and
664 // match on the field name itself
665 requiredTxt = SUGAR.language.get('app_strings', 'ERR_MISSING_REQUIRED_FIELDS');
666 invalidTxt = SUGAR.language.get('app_strings', 'ERR_INVALID_VALUE');
667 nomatchTxt = SUGAR.language.get('app_strings', 'ERR_SQS_NO_MATCH_FIELD');
668 matchTxt = txt.replace(requiredTxt,'').replace(invalidTxt,'').replace(nomatchTxt,'');
670 YUI().use('node', function (Y) {
671 Y.one(inputHandle).get('parentNode').get('children').each(function(node, index, nodeList){
672 if(node.hasClass('validation-message') && node.get('text').search(matchTxt)){
679 errorTextNode = document.createElement('div');
680 errorTextNode.className = 'required validation-message';
681 errorTextNode.innerHTML = txt;
682 if ( inputHandle.parentNode.className.indexOf('x-form-field-wrap') != -1 ) {
683 inputHandle.parentNode.parentNode.appendChild(errorTextNode);
686 inputHandle.parentNode.appendChild(errorTextNode);
689 inputHandle.style.backgroundColor = "#FF0000";
690 inputsWithErrors.push(inputHandle);
694 // We only need to setup the flashy-flashy on the first entry, it loops through all fields automatically
695 if ( inputsWithErrors.length == 1 ) {
696 for(wp = 1; wp <= 10; wp++) {
697 window.setTimeout('fade_error_style(style, '+wp*10+')',1000+(wp*50));
700 if(typeof (window[formname + "_tabs"]) != "undefined") {
701 var tabView = window[formname + "_tabs"];
702 var parentDiv = YAHOO.util.Dom.getAncestorByTagName(inputHandle, "div");
704 var tabs = tabView.get("tabs");
705 for (var i in tabs) {
706 if (tabs[i].get("contentEl") == parentDiv
707 || YAHOO.util.Dom.isAncestor(tabs[i].get("contentEl"), inputHandle))
709 tabs[i].get("labelEl").style.color = "red";
710 if ( inputsWithErrors.length == 1 )
711 tabView.selectTab(i);
716 window.setTimeout("inputsWithErrors[" + (inputsWithErrors.length - 1) + "].style.backgroundColor = '';", 2000);
720 // Catch errors here so we don't allow an incomplete record through the javascript validation
726 * removes all error messages for the current form
728 function clear_all_errors() {
729 for(var wp = 0; wp < inputsWithErrors.length; wp++) {
730 if(typeof(inputsWithErrors[wp]) !='undefined' && typeof inputsWithErrors[wp].parentNode != 'undefined' && inputsWithErrors[wp].parentNode != null) {
731 if ( inputsWithErrors[wp].parentNode.className.indexOf('x-form-field-wrap') != -1 )
733 inputsWithErrors[wp].parentNode.parentNode.removeChild(inputsWithErrors[wp].parentNode.parentNode.lastChild);
737 inputsWithErrors[wp].parentNode.removeChild(inputsWithErrors[wp].parentNode.lastChild);
741 if (inputsWithErrors.length == 0) return;
743 if ( YAHOO.util.Dom.getAncestorByTagName(inputsWithErrors[0], "form") ) {
744 var formname = YAHOO.util.Dom.getAncestorByTagName(inputsWithErrors[0], "form").getAttribute("name");
745 if(typeof (window[formname + "_tabs"]) != "undefined") {
746 var tabView = window[formname + "_tabs"];
748 var tabs = tabView.get("tabs");
749 for (var i in tabs) {
750 if (typeof tabs[i] == "object")
751 tabs[i].get("labelEl").style.color = "";
755 inputsWithErrors = new Array();
759 function get_current_bgcolor(input) {
760 if(input.currentStyle) {// ie
761 style = input.currentStyle.backgroundColor;
762 return style.substring(1,7);
766 styleRGB = document.defaultView.getComputedStyle(input, '').getPropertyValue("background-color");
767 comma = styleRGB.indexOf(',');
768 style += dec2hex(styleRGB.substring(4, comma));
769 commaPrevious = comma;
770 comma = styleRGB.indexOf(',', commaPrevious+1);
771 style += dec2hex(styleRGB.substring(commaPrevious+2, comma));
772 style += dec2hex(styleRGB.substring(comma+2, styleRGB.lastIndexOf(')')));
777 function hex2dec(hex){return(parseInt(hex,16));}
778 var hexDigit=new Array("0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F");
779 function dec2hex(dec){return(hexDigit[dec>>4]+hexDigit[dec&15]);}
781 function fade_error_style(normalStyle, percent) {
782 errorStyle = 'c60c30';
783 var r1 = hex2dec(errorStyle.slice(0,2));
784 var g1 = hex2dec(errorStyle.slice(2,4));
785 var b1 = hex2dec(errorStyle.slice(4,6));
787 var r2 = hex2dec(normalStyle.slice(0,2));
788 var g2 = hex2dec(normalStyle.slice(2,4));
789 var b2 = hex2dec(normalStyle.slice(4,6));
792 var pc = percent / 100;
794 r= Math.floor(r1+(pc*(r2-r1)) + .5);
795 g= Math.floor(g1+(pc*(g2-g1)) + .5);
796 b= Math.floor(b1+(pc*(b2-b1)) + .5);
798 for(var wp = 0; wp < inputsWithErrors.length; wp++) {
799 inputsWithErrors[wp].style.backgroundColor = "#" + dec2hex(r) + dec2hex(g) + dec2hex(b);
803 function isFieldTypeExceptFromEmptyCheck(fieldType)
806 var exemptList = ['bool','file'];
807 for(var i=0;i<exemptList.length;i++)
809 if(fieldType == exemptList[i])
814 function validate_form(formname, startsWith){
815 requiredTxt = SUGAR.language.get('app_strings', 'ERR_MISSING_REQUIRED_FIELDS');
816 invalidTxt = SUGAR.language.get('app_strings', 'ERR_INVALID_VALUE');
818 if ( typeof (formname) == 'undefined')
822 if ( typeof (validate[formname]) == 'undefined')
824 disableOnUnloadEditView(document.forms[formname]);
828 var form = document.forms[formname];
831 var _date = new Date();
832 if(_date.getTime() < (lastSubmitTime + 2000) && startsWith == oldStartsWith) { // ignore submits for the next 2 seconds
835 lastSubmitTime = _date.getTime();
836 oldStartsWith = startsWith;
838 clear_all_errors(); // remove previous error messages
840 inputsWithErrors = new Array();
841 for(var i = 0; i < validate[formname].length; i++){
842 if(validate[formname][i][nameIndex].indexOf(startsWith) == 0){
843 if(typeof form[validate[formname][i][nameIndex]] != 'undefined' && typeof form[validate[formname][i][nameIndex]].value != 'undefined'){
846 //If a field is not required and it is blank or is binarydependant, skip validation.
847 //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
848 if(!validate[formname][i][requiredIndex] && trim(form[validate[formname][i][nameIndex]].value) == '' && (typeof(validate[formname][i][jstypeIndex]) != 'undefined' && validate[formname][i][jstypeIndex] != 'binarydep'))
853 if(validate[formname][i][requiredIndex]
854 && !isFieldTypeExceptFromEmptyCheck(validate[formname][i][typeIndex])
856 if(typeof form[validate[formname][i][nameIndex]] == 'undefined' || trim(form[validate[formname][i][nameIndex]].value) == ""){
857 add_error_style(formname, validate[formname][i][nameIndex], requiredTxt +' ' + validate[formname][i][msgIndex]);
862 switch(validate[formname][i][typeIndex]){
864 if(!isValidEmail(trim(form[validate[formname][i][nameIndex]].value))){
866 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
870 if( !isTime(trim(form[validate[formname][i][nameIndex]].value))){
872 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
874 case 'date': if(!isDate(trim(form[validate[formname][i][nameIndex]].value))){
876 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
881 if(!isDBName(trim(form[validate[formname][i][nameIndex]].value))){
883 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
889 var file_input = form[validate[formname][i][nameIndex] + '_file'];
890 if( file_input && validate[formname][i][requiredIndex] && trim(file_input.value) == "" && !file_input.disabled ) {
892 add_error_style(formname, validate[formname][i][nameIndex], requiredTxt + " " + validate[formname][i][msgIndex]);
896 if(!isInteger(trim(form[validate[formname][i][nameIndex]].value))){
898 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
902 if(!isDecimal(trim(form[validate[formname][i][nameIndex]].value))){
904 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
909 if(!isFloat(trim(form[validate[formname][i][nameIndex]].value))){
911 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
915 var div_element_id = formname + '_' + form[validate[formname][i][nameIndex]].name + '_operation_div';
916 var input_elements = YAHOO.util.Selector.query('input', document.getElementById(div_element_id));
917 var primary_field_id = '';
918 var validation_passed = false;
919 var replace_selected = false;
921 //Loop through the option elements (replace or add currently)
922 for(t in input_elements) {
923 if(input_elements[t].type && input_elements[t].type == 'radio' && input_elements[t].checked == true && input_elements[t].value == 'replace') {
925 //Now find where the primary radio button is and if a value has been set
926 var radio_elements = YAHOO.util.Selector.query('input[type=radio]', document.getElementById(formname + '_team_name_table'));
928 for(var x = 0; x < radio_elements.length; x++) {
929 if(radio_elements[x].name != 'team_name_type') {
930 primary_field_id = 'team_name_collection_' + radio_elements[x].value;
931 if(radio_elements[x].checked) {
932 replace_selected = true;
933 if(trim(document.forms[formname].elements[primary_field_id].value) != '') {
934 validation_passed = true;
937 } else if(trim(document.forms[formname].elements[primary_field_id].value) != '') {
938 replace_selected = true;
945 if(replace_selected && !validation_passed) {
946 add_error_style(formname, primary_field_id, SUGAR.language.get('app_strings', 'ERR_NO_PRIMARY_TEAM_SPECIFIED'));
951 var table_element_id = formname + '_' + form[validate[formname][i][nameIndex]].name + '_table';
952 if(document.getElementById(table_element_id)) {
953 var input_elements = YAHOO.util.Selector.query('input[type=radio]', document.getElementById(table_element_id));
954 var has_primary = false;
955 var primary_field_id = form[validate[formname][i][nameIndex]].name + '_collection_0';
957 for(t in input_elements) {
958 primary_field_id = form[validate[formname][i][nameIndex]].name + '_collection_' + input_elements[t].value;
959 if(input_elements[t].type && input_elements[t].type == 'radio' && input_elements[t].checked == true) {
960 if(document.forms[formname].elements[primary_field_id].value != '') {
969 var field_id = form[validate[formname][i][nameIndex]].name + '_collection_' + input_elements[0].value;
970 add_error_style(formname, field_id, SUGAR.language.get('app_strings', 'ERR_NO_PRIMARY_TEAM_SPECIFIED'));
976 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex]);
980 if(typeof validate[formname][i][jstypeIndex] != 'undefined'/* && !isError*/){
982 switch(validate[formname][i][jstypeIndex]){
983 // Bug #47961 May be validation through callback is best way.
985 if (typeof validate[formname][i][callbackIndex] == 'function')
987 var result = validate[formname][i][callbackIndex](formname, validate[formname][i][nameIndex]);
991 add_error_style(formname, validate[formname][i][nameIndex], requiredTxt + " " + validate[formname][i][msgIndex]);
996 if(!inRange(trim(form[validate[formname][i][nameIndex]].value), validate[formname][i][minIndex], validate[formname][i][maxIndex])){
998 var lbl_validate_range = SUGAR.language.get('app_strings', 'LBL_VALIDATE_RANGE');
999 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] + ") ");
1003 compareTo = form[validate[formname][i][compareToIndex]];
1004 if( typeof compareTo != 'undefined'){
1005 if(trim(compareTo.value) != '' || (validate[formname][i][allowblank] != 'true') ) {
1006 date2 = trim(compareTo.value);
1007 date1 = trim(form[validate[formname][i][nameIndex]].value);
1009 if(trim(date1).length != 0 && !isBefore(date1,date2)){
1012 //jc:#12287 - adding translation for the is not before message
1013 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex] + "(" + date1 + ") " + SUGAR.language.get('app_strings', 'MSG_IS_NOT_BEFORE') + ' ' +date2);
1019 value=unformatNumber(trim(form[validate[formname][i][nameIndex]].value), num_grp_sep, dec_sep);
1020 maximum = parseFloat(validate[formname][i][maxIndex]);
1021 if( typeof maximum != 'undefined'){
1024 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]);
1029 value=unformatNumber(trim(form[validate[formname][i][nameIndex]].value), num_grp_sep, dec_sep);
1030 minimum = parseFloat(validate[formname][i][minIndex]);
1031 if( typeof minimum != 'undefined'){
1034 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'));
1039 compareTo = form[validate[formname][i][compareToIndex]];
1040 if( typeof compareTo != 'undefined') {
1041 item1 = trim(form[validate[formname][i][nameIndex]].value);
1042 item2 = trim(compareTo.value);
1043 if(!bothExist(item1, item2)) {
1045 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex]);
1050 compareTo = form[validate[formname][i][compareToIndex]];
1051 if( typeof compareTo != 'undefined') {
1052 item1 = trim(form[validate[formname][i][nameIndex]].value);
1053 item2 = trim(compareTo.value);
1054 if(!bothExist(item1, item2) || item1 != item2) {
1056 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex]);
1061 arr = eval(validate[formname][i][arrIndex]);
1062 operator = validate[formname][i][operatorIndex];
1063 item1 = trim(form[validate[formname][i][nameIndex]].value);
1064 if (operator.charAt(0) == 'u') {
1065 item1 = item1.toUpperCase();
1066 operator = operator.substring(1);
1067 } else if (operator.charAt(0) == 'l') {
1068 item1 = item1.toLowerCase();
1069 operator = operator.substring(1);
1071 for(j = 0; j < arr.length; j++){
1073 if((operator == "==" && val == item1) || (operator == "!=" && val != item1)){
1075 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
1080 if(trim(form[validate[formname][i][nameIndex]].value) == 'false'){
1081 //Fake an error so form does not submit
1091 /* nsingh: BUG#15102
1092 Check min max default field logic.
1093 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.*/
1094 if(formsWithFieldLogic){
1095 var invalidLogic=false;
1096 if(formsWithFieldLogic.min && formsWithFieldLogic.max && formsWithFieldLogic._default) {
1097 var showErrorsOn={min:{value:'min', show:false, obj:formsWithFieldLogic.min.value},
1098 max:{value:'max',show:false, obj:formsWithFieldLogic.max.value},
1099 _default:{value:'default',show:false, obj:formsWithFieldLogic._default.value},
1100 len:{value:'len', show:false, obj:parseInt(formsWithFieldLogic.len.value,10)}};
1102 var min = (formsWithFieldLogic.min.value !='') ? parseFloat(formsWithFieldLogic.min.value) : 'undef';
1103 var max = (formsWithFieldLogic.max.value !='') ? parseFloat(formsWithFieldLogic.max.value) : 'undef';
1104 var _default = (formsWithFieldLogic._default.value!='')? parseFloat(formsWithFieldLogic._default.value) : 'undef';
1106 /*Check all lengths are <= max size.*/
1107 for(var i in showErrorsOn){
1108 if(showErrorsOn[i].value!='len' && showErrorsOn[i].obj.length > showErrorsOn.len.obj){
1110 showErrorsOn[i].show=true;
1111 showErrorsOn.len.show=true;
1115 if(min!='undef' && max!='undef' && _default!='undef'){
1116 if(!inRange(_default,min,max)){
1118 showErrorsOn.min.show=true;
1119 showErrorsOn.max.show=true;
1120 showErrorsOn._default.show=true;
1123 if(min!='undef' && max!= 'undef' && min > max){
1124 invalidLogic = true;
1125 showErrorsOn.min.show=true;
1126 showErrorsOn.max.show=true;
1128 if(min!='undef' && _default!='undef' && _default < min){
1130 invalidLogic = true;
1131 showErrorsOn.min.show=true;
1132 showErrorsOn._default.show=true;
1134 if(max!='undef' && _default !='undef' && _default>max){
1136 invalidLogic = true;
1137 showErrorsOn.max.show=true;
1138 showErrorsOn._default.show=true;
1143 for(var error in showErrorsOn)
1144 if(showErrorsOn[error].show)
1145 add_error_style(formname,showErrorsOn[error].value, formsWithFieldLogic.msg);
1150 formsWithFieldLogic = null;
1153 if(formWithPrecision){
1154 if (!isValidPrecision(formWithPrecision.float.value, formWithPrecision.precision.value)){
1156 add_error_style(formname, 'default', SUGAR.language.get('app_strings', 'ERR_COMPATIBLE_PRECISION_VALUE'));
1164 if (isError == true) {
1166 if (self.pageYOffset) // all except Explorer
1168 nwX = self.pageXOffset;
1169 seX = self.innerWidth;
1170 nwY = self.pageYOffset;
1171 seY = self.innerHeight;
1173 else if (document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
1175 nwX = document.documentElement.scrollLeft;
1176 seX = document.documentElement.clientWidth;
1177 nwY = document.documentElement.scrollTop;
1178 seY = document.documentElement.clientHeight;
1180 else if (document.body) // all other Explorers
1182 nwX = document.body.scrollLeft;
1183 seX = document.body.clientWidth;
1184 nwY = document.body.scrollTop;
1185 seY = document.body.clientHeight;
1188 var inView = true; // is there an error within viewport of browser
1189 for(var wp = 0; wp < inputsWithErrors.length; wp++) {
1190 var elementCoor = findElementPos(inputsWithErrors[wp]);
1191 if(!(elementCoor.x >= nwX && elementCoor.y >= nwY &&
1192 elementCoor.x <= seX && elementCoor.y <= seY)) { // if input is not within viewport
1194 scrollToTop = elementCoor.y - 75;
1195 scrollToLeft = elementCoor.x - 75;
1197 else { // on first input within viewport, don't scroll
1203 if(!inView) window.scrollTo(scrollToLeft,scrollToTop);
1208 disableOnUnloadEditView(form);
1215 * This array is used to remember mark status of rows in browse mode
1217 var marked_row = new Array;
1221 * Sets/unsets the pointer and marker in browse mode
1223 * @param object the table row
1224 * @param interger the row number
1225 * @param string the action calling this script (over, out or click)
1226 * @param string the default background color
1227 * @param string the color to use for mouseover
1228 * @param string the color to use for marking a row
1230 * @return boolean whether pointer is set or not
1232 function setPointer(theRow, theRowNum, theAction, theDefaultColor, thePointerColor, theMarkColor) {
1233 var theCells = null;
1235 // 1. Pointer and mark feature are disabled or the browser can't get the
1237 if ((thePointerColor == '' && theMarkColor == '')
1238 || typeof(theRow.style) == 'undefined') {
1242 // 2. Gets the current row and exits if the browser can't get it
1243 if (typeof(document.getElementsByTagName) != 'undefined') {
1244 theCells = theRow.getElementsByTagName('td');
1246 else if (typeof(theRow.cells) != 'undefined') {
1247 theCells = theRow.cells;
1253 // 3. Gets the current color...
1254 var rowCellsCnt = theCells.length;
1255 var domDetect = null;
1256 var currentColor = null;
1257 var newColor = null;
1258 // 3.1 ... with DOM compatible browsers except Opera that does not return
1259 // valid values with "getAttribute"
1260 if (typeof(window.opera) == 'undefined'
1261 && typeof(theCells[0].getAttribute) != 'undefined') {
1262 currentColor = theCells[0].getAttribute('bgcolor');
1265 // 3.2 ... with other browsers
1267 currentColor = theCells[0].style.backgroundColor;
1271 // 4. Defines the new color
1272 // 4.1 Current color is the default one
1273 if (currentColor == ''
1274 || (currentColor!= null && (currentColor.toLowerCase() == theDefaultColor.toLowerCase()))) {
1275 if (theAction == 'over' && thePointerColor != '') {
1276 newColor = thePointerColor;
1278 else if (theAction == 'click' && theMarkColor != '') {
1279 newColor = theMarkColor;
1280 marked_row[theRowNum] = true;
1283 // 4.1.2 Current color is the pointer one
1284 else if (currentColor!= null && (currentColor.toLowerCase() == thePointerColor.toLowerCase())
1285 && (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])) {
1286 if (theAction == 'out') {
1287 newColor = theDefaultColor;
1289 else if (theAction == 'click' && theMarkColor != '') {
1290 newColor = theMarkColor;
1291 marked_row[theRowNum] = true;
1294 // 4.1.3 Current color is the marker one
1295 else if (currentColor!= null && (currentColor.toLowerCase() == theMarkColor.toLowerCase())) {
1296 if (theAction == 'click') {
1297 newColor = (thePointerColor != '')
1300 marked_row[theRowNum] = (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])
1306 // 5. Sets the new color...
1309 // 5.1 ... with DOM compatible browsers except Opera
1311 for (c = 0; c < rowCellsCnt; c++) {
1312 theCells[c].setAttribute('bgcolor', newColor, 0);
1315 // 5.2 ... with other browsers
1317 for (c = 0; c < rowCellsCnt; c++) {
1318 theCells[c].style.backgroundColor = newColor;
1324 } // end of the 'setPointer()' function
1328 * listbox redirection
1330 function goToUrl(selObj, goToLocation) {
1331 eval("document.location.href = '" + goToLocation + "pos=" + selObj.options[selObj.selectedIndex].value + "'");
1336 var json_objects = new Object();
1338 function getXMLHTTPinstance() {
1339 var xmlhttp = false;
1340 var userAgent = navigator.userAgent.toLowerCase() ;
1342 // IE Check supports ActiveX controls
1343 if (userAgent.indexOf("msie") != -1 && userAgent.indexOf("mac") == -1 && userAgent.indexOf("opera") == -1) {
1344 var version = navigator.appVersion.match(/MSIE (.\..)/)[1] ;
1345 if(version >= 5.5 ) {
1347 xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
1351 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
1360 if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
1361 xmlhttp = new XMLHttpRequest();
1366 // NOW LOAD THE OBJECT..
1367 var global_xmlhttp = getXMLHTTPinstance();
1369 function http_fetch_sync(url,post_data) {
1370 global_xmlhttp = getXMLHTTPinstance();
1373 if(typeof(post_data) != 'undefined') method = 'POST';
1375 global_xmlhttp.open(method, url,false);
1378 alert('message:'+e.message+":url:"+url);
1380 if(method == 'POST') {
1381 global_xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
1384 global_xmlhttp.send(post_data);
1386 if (SUGAR.util.isLoginPage(global_xmlhttp.responseText))
1389 var args = {"responseText" : global_xmlhttp.responseText,
1390 "responseXML" : global_xmlhttp.responseXML,
1391 "request_id" : typeof(request_id) != "undefined" ? request_id : 0};
1395 // this is a GET unless post_data is defined
1397 function http_fetch_async(url,callback,request_id,post_data) {
1399 if(typeof(post_data) != 'undefined') {
1404 global_xmlhttp.open(method, url,true);
1407 alert('message:'+e.message+":url:"+url);
1409 if(method == 'POST') {
1410 global_xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
1412 global_xmlhttp.onreadystatechange = function() {
1413 if(global_xmlhttp.readyState==4) {
1414 if(global_xmlhttp.status == 200) {
1415 if (SUGAR.util.isLoginPage(global_xmlhttp.responseText))
1417 var args = {"responseText" : global_xmlhttp.responseText,
1418 "responseXML" : global_xmlhttp.responseXML,
1419 "request_id" : request_id };
1420 callback.call(document,args);
1423 alert("There was a problem retrieving the XML data:\n" + global_xmlhttp.statusText);
1427 global_xmlhttp.send(post_data);
1430 function insert_at_cursor(field, value) {
1432 if (document.selection) {
1434 sel = document.selection.createRange();
1438 else if(field.selectionStart || field.selectionStart == '0') {
1439 var start_pos = field.selectionStart;
1440 var end_pos = field.selectionEnd;
1441 field.value = field.value.substring(0, start_pos) + value + field.value.substring(end_pos, field.value.length);
1444 field.value += value;
1448 function checkParentType(type,button) {
1449 if(button == null) {
1452 if(typeof disabledModules != 'undefined' && typeof(disabledModules[type]) != 'undefined') {
1453 button.disabled='disabled';
1456 button.disabled = false;
1460 function parseDate(input, format) {
1462 format = format.replace(/%/g, '');
1463 sep = format.charAt(1);
1464 yAt = format.indexOf('Y')
1465 // 1-1-06 or 1-12-06 or 1-1-2006 or 1-12-2006
1466 if(date.match(/^\d{1,2}[\/-]\d{1,2}[\/-]\d{2,4}$/) && yAt == 4) {
1467 if(date.match(/^\d{1}[\/-].*$/)) date = '0' + date;
1468 if(date.match(/^\d{2}[\/-]\d{1}[\/-].*$/)) date = date.substring(0,3) + '0' + date.substring(3,date.length);
1469 if(date.match(/^\d{2}[\/-]\d{2}[\/-]\d{2}$/)) date = date.substring(0,6) + '20' + date.substring(6,date.length);
1471 // 06-11-1 or 06-1-1
1472 else if(date.match(/^\d{2,4}[\/-]\d{1,2}[\/-]\d{1,2}$/)) {
1473 if(date.match(/^\d{2}[\/-].*$/)) date = '20' + date;
1474 if(date.match(/^\d{4}[\/-]\d{1}[\/-].*$/)) date = date.substring(0,5) + '0' + date.substring(5,date.length);
1475 if(date.match(/^\d{4}[\/-]\d{2}[\/-]\d{1}$/)) date = date.substring(0,8) + '0' + date.substring(8,date.length);
1477 else if(date.match(/^\d{4,8}$/)) { // digits only
1479 if(date.match(/^\d{8}$/)) digits = 8;// match for 8 digits
1480 else if(date.match(/\d{6}/)) digits = 6;// match for 5 digits
1481 else if(date.match(/\d{4}/)) digits = 4;// match for 5 digits
1482 else if(date.match(/\d{5}/)) digits = 5;// match for 5 digits
1487 case 4: date = '20' + date.substring(0,2) + sep + '0' + date.substring(2, 3) + sep + '0' + date.substring(3,4); break;
1488 case 5: date = '20' + date.substring(0,2) + sep + date.substring(2, 4) + sep + '0' + date.substring(4,5); break;
1489 case 6: date = '20' + date.substring(0,2) + sep + date.substring(2, 4) + sep + date.substring(4,6); break;
1490 case 8: date = date.substring(0,4) + sep + date.substring(4, 6) + sep + date.substring(6,8); break;
1495 case 4: date = '0' + date.substring(0,1) + sep + '20' + date.substring(1, 3) + sep + '0' + date.substring(3,4); break;
1496 case 5: date = date.substring(0,2) + sep + '20' + date.substring(2, 4) + sep + '0' + date.substring(4,5); break;
1497 case 6: date = date.substring(0,2) + sep + '20' + date.substring(2, 4) + sep + date.substring(4,6); break;
1498 case 8: date = date.substring(0,2) + sep + date.substring(2, 6) + sep + date.substring(6,8); break;
1502 case 4: date = '0' + date.substring(0,1) + sep + '0' + date.substring(1, 2) + sep + '20' + date.substring(2,4); break;
1503 case 5: date = '0' + date.substring(0,1) + sep + date.substring(1, 3) + sep + '20' + date.substring(3,5); break;
1504 case 6: date = date.substring(0,2) + sep + date.substring(2, 4) + sep + '20' + date.substring(4,6); break;
1505 case 8: date = date.substring(0,2) + sep + date.substring(2, 4) + sep + date.substring(4,8); break;
1510 date = date.replace(/[\/-]/g, sep);
1514 // find obj's position
1515 function findElementPos(obj) {
1518 if (obj.offsetParent) {
1519 while (obj.offsetParent) {
1520 x += obj.offsetLeft;
1522 obj = obj.offsetParent;
1524 }//if offsetParent exists
1525 else if (obj.x && obj.y) {
1529 return new coordinate(x, y);
1533 // get dimensions of the browser window
1534 function getClientDim() {
1535 var nwX, nwY, seX, seY;
1536 if (self.pageYOffset) // all except Explorer
1538 nwX = self.pageXOffset;
1539 seX = self.innerWidth + nwX;
1540 nwY = self.pageYOffset;
1541 seY = self.innerHeight + nwY;
1543 else if (document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
1545 nwX = document.documentElement.scrollLeft;
1546 seX = document.documentElement.clientWidth + nwX;
1547 nwY = document.documentElement.scrollTop;
1548 seY = document.documentElement.clientHeight + nwY;
1550 else if (document.body) // all other Explorers
1552 nwX = document.body.scrollLeft;
1553 seX = document.body.clientWidth + nwX;
1554 nwY = document.body.scrollTop;
1555 seY = document.body.clientHeight + nwY;
1557 return {'nw' : new coordinate(nwX, nwY), 'se' : new coordinate(seX, seY)};
1561 * stop propagation on events
1563 function freezeEvent(e) {
1565 if (e.preventDefault) e.preventDefault();
1566 e.returnValue = false;
1567 e.cancelBubble = true;
1568 if (e.stopPropagation) e.stopPropagation();
1577 function coordinate(_x, _y) {
1586 return new position(this.x + rh.x, this.y + rh.y);
1590 return new position(this.x + rh.x, this.y + rh.y);
1594 // sends theForm via AJAX and fills in the theDiv
1595 function sendAndRetrieve(theForm, theDiv, loadingStr) {
1596 function success(data) {
1597 document.getElementById(theDiv).innerHTML = data.responseText;
1598 ajaxStatus.hideStatus();
1600 if(typeof loadingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
1601 ajaxStatus.showStatus(loadingStr);
1602 YAHOO.util.Connect.setForm(theForm);
1603 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
1607 //save the form and redirect
1608 function sendAndRedirect(theForm, loadingStr, redirect_location) {
1609 function success(data) {
1610 if(redirect_location){
1611 location.href=redirect_location;
1613 ajaxStatus.hideStatus();
1615 if(typeof loadingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
1616 ajaxStatus.showStatus(loadingStr);
1617 YAHOO.util.Connect.setForm(theForm);
1618 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
1622 function saveForm(theForm, theDiv, loadingStr) {
1623 if(check_form(theForm)){
1624 for(i = 0; i < ajaxFormArray.length; i++){
1625 if(ajaxFormArray[i] == theForm){
1626 ajaxFormArray.splice(i, 1);
1629 return sendAndRetrieve(theForm, loadingStr, theDiv);
1635 // Builds a "snapshot" of the form, so we can use it to see if someone has changed it.
1636 function snapshotForm(theForm) {
1637 var snapshotTxt = '';
1638 var elemList = theForm.elements;
1642 for( var i = 0; i < elemList.length ; i++ ) {
1644 if ( typeof(elem.type) == 'undefined' ) {
1648 elemType = elem.type.toLowerCase();
1650 snapshotTxt = snapshotTxt + elem.name;
1652 if ( elemType == 'text' || elemType == 'textarea' || elemType == 'password' ) {
1653 snapshotTxt = snapshotTxt + elem.value;
1655 else if ( elemType == 'select' || elemType == 'select-one' || elemType == 'select-multiple' ) {
1656 var optionList = elem.options;
1657 for ( var ii = 0 ; ii < optionList.length ; ii++ ) {
1658 if ( optionList[ii].selected ) {
1659 snapshotTxt = snapshotTxt + optionList[ii].value;
1663 else if ( elemType == 'radio' || elemType == 'checkbox' ) {
1664 if ( elem.selected ) {
1665 snapshotTxt = snapshotTxt + 'checked';
1668 else if ( elemType == 'hidden' ) {
1669 snapshotTxt = snapshotTxt + elem.value;
1676 function initEditView(theForm) {
1677 if (SUGAR.util.ajaxCallInProgress()) {
1678 window.setTimeout(function(){initEditView(theForm);}, 100);
1682 if ( theForm == null || theForm.id == null ) {
1683 // Not much we can do here.
1687 // we don't need to check if the data is changed in the search popup
1688 if (theForm.id == 'popup_query_form' || theForm.id == 'MassUpdate') {
1691 if ( typeof editViewSnapshots == 'undefined' || editViewSnapshots == null ) {
1692 editViewSnapshots = new Object();
1694 if ( typeof SUGAR.loadedForms == 'undefined' || SUGAR.loadedForms == null) {
1695 SUGAR.loadedForms = new Object();
1698 editViewSnapshots[theForm.id] = snapshotForm(theForm);
1699 SUGAR.loadedForms[theForm.id] = true;
1702 function onUnloadEditView(theForm) {
1704 var dataHasChanged = false;
1706 if ( typeof editViewSnapshots == 'undefined' ) {
1707 // No snapshots, move along
1711 if ( typeof theForm == 'undefined' ) {
1712 // Need to check all editViewSnapshots
1713 for ( var idx in editViewSnapshots ) {
1715 theForm = document.getElementById(idx);
1716 // console.log('DEBUG: Checking all forms '+theForm.id);
1717 if ( theForm == null
1718 || typeof editViewSnapshots[theForm.id] == 'undefined'
1719 || editViewSnapshots[theForm.id] == null
1720 || !SUGAR.loadedForms[theForm.id]) {
1724 var snap = snapshotForm(theForm);
1725 if ( editViewSnapshots[theForm.id] != snap ) {
1726 dataHasChanged = true;
1730 // Just need to check a single form for changes
1731 if ( editViewSnapshots == null || typeof theForm.id == 'undefined' || typeof editViewSnapshots[theForm.id] == 'undefined' || editViewSnapshots[theForm.id] == null ) {
1735 // console.log('DEBUG: Checking one form '+theForm.id);
1736 if ( editViewSnapshots[theForm.id] != snapshotForm(theForm) ) {
1737 // Data has changed.
1738 dataHasChanged = true;
1742 if ( dataHasChanged == true ) {
1743 return SUGAR.language.get('app_strings','WARN_UNSAVED_CHANGES');
1750 function disableOnUnloadEditView(theForm) {
1751 // If you don't pass anything in, it disables all checking
1752 if ( typeof theForm == 'undefined' || typeof editViewSnapshots == 'undefined' || theForm == null || editViewSnapshots == null) {
1753 window.onbeforeunload = null;
1754 editViewSnapshots = null;
1756 // console.log('DEBUG: Disabling all edit view checks');
1759 // Otherwise, it just disables it for this form
1760 if ( typeof(theForm.id) != 'undefined' && typeof(editViewSnapshots[theForm.id]) != 'undefined' ) {
1761 editViewSnapshots[theForm.id] = null;
1764 // console.log('DEBUG : Disabling just checks for '+theForm.id);
1770 * save some forms using an ajax call
1771 * theForms - the ids of all of theh forms to save
1772 * savingStr - the string to display when saving the form
1773 * completeStr - the string to display when the form has been saved
1775 function saveForms( savingStr, completeStr) {
1777 theForms = ajaxFormArray;
1778 function success(data) {
1779 var theForm = document.getElementById(ajaxFormArray[0]);
1780 document.getElementById('multiedit_'+theForm.id).innerHTML = data.responseText;
1781 var saveAllButton = document.getElementById('ajaxsaveall');
1782 ajaxFormArray.splice(index, 1);
1783 if(saveAllButton && ajaxFormArray.length <= 1){
1784 saveAllButton.style.visibility = 'hidden';
1787 if(index == theForms.length){
1788 ajaxStatus.showStatus(completeStr);
1789 window.setTimeout('ajaxStatus.hideStatus();', 2000);
1791 saveAllButton.style.visibility = 'hidden';
1796 if(typeof savingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
1797 ajaxStatus.showStatus(savingStr);
1799 //loop through the forms saving each one
1800 for(i = 0; i < theForms.length; i++){
1801 var theForm = document.getElementById(theForms[i]);
1802 if(check_form(theForm.id)){
1803 theForm.action.value='AjaxFormSave';
1804 YAHOO.util.Connect.setForm(theForm);
1805 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
1807 ajaxStatus.hideStatus();
1809 lastSubmitTime = lastSubmitTime-2000;
1814 // -- start sugarListView class
1815 // js functions used for ListView
1816 function sugarListView() {
1820 sugarListView.prototype.confirm_action = function(del) {
1822 return confirm( SUGAR.language.get('app_strings', 'NTC_DELETE_CONFIRMATION_NUM') + sugarListView.get_num_selected() + SUGAR.language.get('app_strings', 'NTC_DELETE_SELECTED_RECORDS'));
1825 return confirm( SUGAR.language.get('app_strings', 'NTC_UPDATE_CONFIRMATION_NUM') + sugarListView.get_num_selected() + SUGAR.language.get('app_strings', 'NTC_DELETE_SELECTED_RECORDS'));
1829 sugarListView.get_num_selected = function () {
1830 if(typeof document.MassUpdate != 'undefined') {
1831 the_form = document.MassUpdate;
1832 for(wp = 0; wp < the_form.elements.length; wp++) {
1833 if(typeof the_form.elements[wp].name != 'undefined' && the_form.elements[wp].name == 'selectCount[]') {
1834 return the_form.elements[wp].value;
1841 sugarListView.update_count = function(count, add) {
1842 if(typeof document.MassUpdate != 'undefined') {
1843 the_form = document.MassUpdate;
1844 for(wp = 0; wp < the_form.elements.length; wp++) {
1845 if(typeof the_form.elements[wp].name != 'undefined' && the_form.elements[wp].name == 'selectCount[]') {
1847 the_form.elements[wp].value = parseInt(the_form.elements[wp].value,10) + count;
1848 if (the_form.select_entire_list.value == 1 && the_form.show_plus.value) {
1849 the_form.elements[wp].value += '+';
1852 if (the_form.select_entire_list.value == 1 && the_form.show_plus.value) {
1853 the_form.elements[wp].value = count + '+';
1855 the_form.elements[wp].value = count;
1862 sugarListView.prototype.use_external_mail_client = function(no_record_txt, module) {
1863 selected_records = sugarListView.get_checks_count();
1864 if(selected_records <1) {
1865 alert(no_record_txt);
1869 if (document.MassUpdate.select_entire_list.value == 1) {
1870 if (totalCount > 10) {
1871 alert(totalCountError);
1876 else if (document.MassUpdate.massall.checked == true)
1880 sugarListView.get_checks();
1882 if(select) { // use selected items
1883 ids = document.MassUpdate.uid.value;
1885 else { // use current page
1886 inputs = document.MassUpdate.elements;
1888 for(i = 0; i < inputs.length; i++) {
1889 if(inputs[i].name == 'mass[]' && inputs[i].checked && typeof(inputs[i].value) != 'function') {
1890 ar.push(inputs[i].value);
1895 YAHOO.util.Connect.asyncRequest("POST", "index.php?", {
1896 success: this.use_external_mail_client_callback
1897 }, SUGAR.util.paramsToUrl({
1900 listViewExternalClient: 1,
1901 action_module: module,
1909 sugarListView.prototype.use_external_mail_client_callback = function(o)
1912 location.href = 'mailto:' + o.responseText;
1915 sugarListView.prototype.send_form_for_emails = function(select, currentModule, action, no_record_txt,action_module,totalCount, totalCountError) {
1916 if ( typeof(SUGAR.config.email_sugarclient_listviewmaxselect) != 'undefined' ) {
1920 maxCount = SUGAR.config.email_sugarclient_listviewmaxselect;
1923 if (document.MassUpdate.select_entire_list.value == 1) {
1924 if (totalCount > maxCount) {
1925 alert(totalCountError);
1930 else if (document.MassUpdate.massall.checked == true)
1935 sugarListView.get_checks();
1936 // create new form to post (can't access action property of MassUpdate form due to action input)
1937 var newForm = document.createElement('form');
1938 newForm.method = 'post';
1939 newForm.action = action;
1940 newForm.name = 'newForm';
1941 newForm.id = 'newForm';
1942 var uidTa = document.createElement('textarea');
1944 uidTa.style.display = 'none';
1946 if(select) { // use selected items
1947 uidTa.value = document.MassUpdate.uid.value;
1949 else { // use current page
1950 inputs = document.MassUpdate.elements;
1952 for(i = 0; i < inputs.length; i++) {
1953 if(inputs[i].name == 'mass[]' && inputs[i].checked && typeof(inputs[i].value) != 'function') {
1954 ar.push(inputs[i].value);
1957 uidTa.value = ar.join(',');
1960 if(uidTa.value == '') {
1961 alert(no_record_txt);
1965 var selectedArray = uidTa.value.split(",");
1966 if(selectedArray.length > maxCount) {
1967 alert(totalCountError);
1970 newForm.appendChild(uidTa);
1972 var moduleInput = document.createElement('input');
1973 moduleInput.name = 'module';
1974 moduleInput.type = 'hidden';
1975 moduleInput.value = currentModule;
1976 newForm.appendChild(moduleInput);
1978 var actionInput = document.createElement('input');
1979 actionInput.name = 'action';
1980 actionInput.type = 'hidden';
1981 actionInput.value = 'Compose';
1982 newForm.appendChild(actionInput);
1984 if (typeof action_module != 'undefined' && action_module!= '') {
1985 var actionModule = document.createElement('input');
1986 actionModule.name = 'action_module';
1987 actionModule.type = 'hidden';
1988 actionModule.value = action_module;
1989 newForm.appendChild(actionModule);
1991 //return_info must follow this pattern."&return_module=Accounts&return_action=index"
1992 if (typeof return_info!= 'undefined' && return_info != '') {
1993 var params= return_info.split('&');
1994 if (params.length > 0) {
1995 for (var i=0;i< params.length;i++) {
1996 if (params[i].length > 0) {
1997 var param_nv=params[i].split('=');
1998 if (param_nv.length==2){
1999 returnModule = document.createElement('input');
2000 returnModule.name = param_nv[0];
2001 returnModule.type = 'hidden';
2002 returnModule.value = param_nv[1];
2003 newForm.appendChild(returnModule);
2010 var isAjaxCall = document.createElement('input');
2011 isAjaxCall.name = 'ajaxCall';
2012 isAjaxCall.type = 'hidden';
2013 isAjaxCall.value = true;
2014 newForm.appendChild(isAjaxCall);
2016 var isListView = document.createElement('input');
2017 isListView.name = 'ListView';
2018 isListView.type = 'hidden';
2019 isListView.value = true;
2020 newForm.appendChild(isListView);
2022 var toPdf = document.createElement('input');
2023 toPdf.name = 'to_pdf';
2024 toPdf.type = 'hidden';
2026 newForm.appendChild(toPdf);
2028 //Grab the Quick Compose package for the listview
2029 YAHOO.util.Connect.setForm(newForm);
2032 success: function(o) {
2033 var resp = YAHOO.lang.JSON.parse(o.responseText);
2034 var quickComposePackage = new Object();
2035 quickComposePackage.composePackage = resp;
2036 quickComposePackage.fullComposeUrl = 'index.php?module=Emails&action=Compose&ListView=true' +
2037 '&uid=' + uidTa.value + '&action_module=' + action_module;
2039 SUGAR.quickCompose.init(quickComposePackage);
2043 YAHOO.util.Connect.asyncRequest('POST','index.php', callback,null);
2045 // awu Bug 18624: Fixing issue where a canceled Export and unselect of row will persist the uid field, clear the field
2046 document.MassUpdate.uid.value = '';
2051 sugarListView.prototype.send_form = function(select, currentModule, action, no_record_txt,action_module,return_info) {
2052 if (document.MassUpdate.select_entire_list.value == 1) {
2054 if(sugarListView.get_checks_count() < 1) {
2055 alert(no_record_txt);
2060 if ( action.indexOf('?') != -1 )
2061 href += '&module=' + currentModule;
2063 href += '?module=' + currentModule;
2066 href += return_info;
2067 var newForm = document.createElement('form');
2068 newForm.method = 'post';
2069 newForm.action = href;
2070 newForm.name = 'newForm';
2071 newForm.id = 'newForm';
2072 var postTa = document.createElement('textarea');
2073 postTa.name = 'current_post';
2074 postTa.value = document.MassUpdate.current_query_by_page.value;
2075 postTa.style.display = 'none';
2076 newForm.appendChild(postTa);
2077 document.MassUpdate.parentNode.appendChild(newForm);
2081 else if (document.MassUpdate.massall.checked == true)
2086 sugarListView.get_checks();
2087 // create new form to post (can't access action property of MassUpdate form due to action input)
2088 var newForm = document.createElement('form');
2089 newForm.method = 'post';
2090 newForm.action = action;
2091 newForm.name = 'newForm';
2092 newForm.id = 'newForm';
2093 var uidTa = document.createElement('textarea');
2095 uidTa.style.display = 'none';
2096 uidTa.value = document.MassUpdate.uid.value;
2098 if(uidTa.value == '') {
2099 alert(no_record_txt);
2103 newForm.appendChild(uidTa);
2105 var moduleInput = document.createElement('input');
2106 moduleInput.name = 'module';
2107 moduleInput.type = 'hidden';
2108 moduleInput.value = currentModule;
2109 newForm.appendChild(moduleInput);
2111 var actionInput = document.createElement('input');
2112 actionInput.name = 'action';
2113 actionInput.type = 'hidden';
2114 actionInput.value = 'index';
2115 newForm.appendChild(actionInput);
2117 if (typeof action_module != 'undefined' && action_module!= '') {
2118 var actionModule = document.createElement('input');
2119 actionModule.name = 'action_module';
2120 actionModule.type = 'hidden';
2121 actionModule.value = action_module;
2122 newForm.appendChild(actionModule);
2124 //return_info must follow this pattern."&return_module=Accounts&return_action=index"
2125 if (typeof return_info!= 'undefined' && return_info != '') {
2126 var params= return_info.split('&');
2127 if (params.length > 0) {
2128 for (var i=0;i< params.length;i++) {
2129 if (params[i].length > 0) {
2130 var param_nv=params[i].split('=');
2131 if (param_nv.length==2){
2132 returnModule = document.createElement('input');
2133 returnModule.name = param_nv[0];
2134 returnModule.type = 'hidden';
2135 returnModule.value = param_nv[1];
2136 newForm.appendChild(returnModule);
2143 document.MassUpdate.parentNode.appendChild(newForm);
2146 // awu Bug 18624: Fixing issue where a canceled Export and unselect of row will persist the uid field, clear the field
2147 document.MassUpdate.uid.value = '';
2151 //return a count of checked row.
2152 sugarListView.get_checks_count = function() {
2155 if(document.MassUpdate.uid.value != '') {
2156 oldUids = document.MassUpdate.uid.value.split(',');
2157 for(uid in oldUids) {
2158 if(typeof(oldUids[uid]) != 'function') {
2159 ar[oldUids[uid]] = 1;
2163 // build associated array of uids, associated array ensures uniqueness
2164 inputs = document.MassUpdate.elements;
2165 for(i = 0; i < inputs.length; i++) {
2166 if(inputs[i].name == 'mass[]') {
2167 ar[inputs[i].value] = (inputs[i].checked) ? 1 : 0; // 0 of it is unchecked
2171 // build regular array of uids
2174 if((typeof(ar[i]) != 'function') && ar[i] == 1) {
2182 // saves the checks on the current page into the uid textarea
2183 sugarListView.get_checks = function() {
2185 if(typeof document.MassUpdate != 'undefined' ){
2186 if(document.MassUpdate.uid.value != '') {
2187 oldUids = document.MassUpdate.uid.value.split(',');
2188 for(uid in oldUids) {
2189 if(typeof(oldUids[uid]) != 'function') {
2190 ar[oldUids[uid]] = 1;
2195 // build associated array of uids, associated array ensures uniqueness
2196 inputs = document.MassUpdate.elements;
2197 for(i = 0; i < inputs.length; i++) {
2198 if(inputs[i].name == 'mass[]') {
2199 ar[inputs[i].value] = (inputs[i].checked) ? 1 : 0; // 0 of it is unchecked
2203 // build regular array of uids
2206 if(typeof(ar[i]) != 'function' && ar[i] == 1) {
2211 document.MassUpdate.uid.value = uids.join(',');
2213 if(uids.length == 0) return false; // return false if no checks to get
2214 return true; // there are saved checks
2219 sugarListView.prototype.order_checks = function(order,orderBy,moduleString){
2220 checks = sugarListView.get_checks();
2221 eval('document.MassUpdate.' + moduleString + '.value = orderBy');
2222 document.MassUpdate.lvso.value = order;
2223 if(typeof document.MassUpdate.massupdate != 'undefined') {
2224 document.MassUpdate.massupdate.value = 'false';
2227 //we must first clear the action of massupdate, change it to index
2228 document.MassUpdate.action.value = document.MassUpdate.return_action.value;
2229 document.MassUpdate.return_module.value='';
2230 document.MassUpdate.return_action.value='';
2231 document.MassUpdate.submit();
2235 sugarListView.prototype.save_checks = function(offset, moduleString) {
2236 checks = sugarListView.get_checks();
2237 if(typeof document.MassUpdate != 'undefined'){
2238 eval('document.MassUpdate.' + moduleString + '.value = offset');
2240 if(typeof document.MassUpdate.massupdate != 'undefined') {
2241 document.MassUpdate.massupdate.value = 'false';
2244 //we must first clear the action of massupdate, change it to index
2245 document.MassUpdate.action.value = document.MassUpdate.return_action.value;
2246 document.MassUpdate.return_module.value='';
2247 document.MassUpdate.return_action.value='';
2248 document.MassUpdate.submit();
2256 sugarListView.prototype.check_item = function(cb, form) {
2258 sugarListView.update_count(1, true);
2260 sugarListView.update_count(-1, true);
2261 if(typeof form != 'undefined' && form != null) {
2262 sugarListView.prototype.updateUid(cb, form);
2267 /**#28000, remove the unselect record id from MassUpdate.uid **/
2268 sugarListView.prototype.updateUid = function(cb , form){
2269 if(form.name == 'MassUpdate' && form.uid && form.uid.value && cb.value && form.uid.value.indexOf(cb.value) != -1){
2270 if(form.uid.value.indexOf(','+cb.value)!= -1){
2271 form.uid.value = form.uid.value.replace(','+cb.value , '');
2272 }else if(form.uid.value.indexOf(cb.value + ',')!= -1){
2273 form.uid.value = form.uid.value.replace(cb.value + ',' , '');
2274 }else if(form.uid.value.indexOf(cb.value)!= -1){
2275 form.uid.value = form.uid.value.replace(cb.value , '');
2280 sugarListView.prototype.check_entire_list = function(form, field, value, list_count) {
2281 // count number of items
2283 document.MassUpdate.massall.checked = true;
2284 document.MassUpdate.massall.disabled = true;
2286 for (i = 0; i < form.elements.length; i++) {
2287 if(form.elements[i].name == field && form.elements[i].disabled == false) {
2288 if(form.elements[i].checked != value) count++;
2289 form.elements[i].checked = value;
2290 form.elements[i].disabled = true;
2293 document.MassUpdate.select_entire_list.value = 1;
2295 sugarListView.update_count(list_count, false);
2296 //else sugarListView.update_count(-1 * count, true);
2299 sugarListView.prototype.check_all = function(form, field, value, pageTotal) {
2300 // count number of items
2302 document.MassUpdate.massall.checked = value;
2303 if (document.MassUpdate.select_entire_list &&
2304 document.MassUpdate.select_entire_list.value == 1)
2305 document.MassUpdate.massall.disabled = true;
2307 document.MassUpdate.massall.disabled = false;
2309 for (i = 0; i < form.elements.length; i++) {
2310 if(form.elements[i].name == field && !(form.elements[i].disabled == true && form.elements[i].checked == false)) {
2311 form.elements[i].disabled = false;
2313 if(form.elements[i].checked != value)
2315 form.elements[i].checked = value;
2317 sugarListView.prototype.updateUid(form.elements[i], form);
2322 sugarListView.update_count(pageTotal);
2324 sugarListView.update_count(count, true);
2326 sugarListView.update_count(-1 * count, true);
2328 sugarListView.check_all = sugarListView.prototype.check_all;
2329 sugarListView.confirm_action = sugarListView.prototype.confirm_action;
2331 sugarListView.prototype.check_boxes = function() {
2332 var inputsCount = 0;
2333 var checkedCount = 0;
2334 var existing_onload = window.onload;
2335 var theForm = document.MassUpdate;
2336 inputs_array = theForm.elements;
2338 if(typeof theForm.uid.value != 'undefined' && theForm.uid.value != "") {
2339 checked_items = theForm.uid.value.split(",");
2340 if (theForm.select_entire_list.value == 1)
2341 document.MassUpdate.massall.disabled = true;
2343 for(wp = 0 ; wp < inputs_array.length; wp++) {
2344 if(inputs_array[wp].name == "mass[]") {
2346 if (theForm.select_entire_list.value == 1) {
2347 inputs_array[wp].checked = true;
2348 inputs_array[wp].disabled = true;
2352 for(i in checked_items) {
2353 if(inputs_array[wp].value == checked_items[i]) {
2355 inputs_array[wp].checked = true;
2361 if (theForm.select_entire_list.value == 0)
2362 sugarListView.update_count(checked_items.length);
2364 sugarListView.update_count(0, true);
2368 for(wp = 0 ; wp < inputs_array.length; wp++) {
2369 if(inputs_array[wp].name == "mass[]") {
2370 inputs_array[wp].checked = false;
2371 inputs_array[wp].disabled = false;
2374 if (document.MassUpdate.massall) {
2375 document.MassUpdate.massall.checked = false;
2376 document.MassUpdate.massall.disabled = false;
2378 sugarListView.update_count(0)
2380 if(checkedCount > 0 && checkedCount == inputsCount)
2381 document.MassUpdate.massall.checked = true;
2387 * This function is used in Email Template Module's listview.
2388 * It will check whether the templates are used in Campaing->EmailMarketing.
2389 * If true, it will notify user.
2391 function check_used_email_templates() {
2392 var ids = document.MassUpdate.uid.value;
2394 success:function(r) {
2395 if(r.responseText != '') {
2396 if(!confirm(SUGAR.language.get('app_strings','NTC_TEMPLATES_IS_USED') + r.responseText)) {
2400 document.MassUpdate.submit();
2404 url = "index.php?module=EmailTemplates&action=CheckDeletable&from=ListView&to_pdf=1&records="+ids;
2405 YAHOO.util.Connect.asyncRequest('POST',url, call_back,null);
2409 sugarListView.prototype.send_mass_update = function(mode, no_record_txt, del) {
2410 formValid = check_form('MassUpdate');
2411 if(!formValid && !del) return false;
2414 if (document.MassUpdate.select_entire_list &&
2415 document.MassUpdate.select_entire_list.value == 1)
2420 var ar = new Array();
2424 for(wp = 0; wp < document.MassUpdate.elements.length; wp++) {
2425 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)+'$');
2426 //when the uid is already in document.MassUpdate.uid.value, we should not add it to ar.
2427 if(typeof document.MassUpdate.elements[wp].name != 'undefined'
2428 && document.MassUpdate.elements[wp].name == 'mass[]'
2429 && document.MassUpdate.elements[wp].checked
2430 && !reg_for_existing_uid.test(document.MassUpdate.uid.value)) {
2431 ar.push(document.MassUpdate.elements[wp].value);
2434 if(document.MassUpdate.uid.value != '') document.MassUpdate.uid.value += ',';
2435 document.MassUpdate.uid.value += ar.join(',');
2436 if(document.MassUpdate.uid.value == '') {
2437 alert(no_record_txt);
2440 if(typeof(current_admin_id)!='undefined' && document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'Users' && (document.MassUpdate.is_admin.value!='' || document.MassUpdate.status.value!='')) {
2441 var reg_for_current_admin_id = new RegExp('^'+current_admin_id+'[\s]*,|,[\s]*'+current_admin_id+'[\s]*,|,[\s]*'+current_admin_id+'$|^'+current_admin_id+'$');
2442 if(reg_for_current_admin_id.test(document.MassUpdate.uid.value)) {
2443 //if current user is admin, we should not allow massupdate the user_type and status of himself
2444 alert(SUGAR.language.get('Users','LBL_LAST_ADMIN_NOTICE'));
2450 var entireInput = document.createElement('input');
2451 entireInput.name = 'entire';
2452 entireInput.type = 'hidden';
2453 entireInput.value = 'index';
2454 document.MassUpdate.appendChild(entireInput);
2455 //confirm(no_record_txt);
2456 if(document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'Users' && (document.MassUpdate.is_admin.value!='' || document.MassUpdate.status.value!='')) {
2457 alert(SUGAR.language.get('Users','LBL_LAST_ADMIN_NOTICE'));
2463 if(!sugarListView.confirm_action(del))
2467 var deleteInput = document.createElement('input');
2468 deleteInput.name = 'Delete';
2469 deleteInput.type = 'hidden';
2470 deleteInput.value = true;
2471 document.MassUpdate.appendChild(deleteInput);
2472 if(document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'EmailTemplates') {
2473 check_used_email_templates();
2479 document.MassUpdate.submit();
2484 sugarListView.prototype.clear_all = function() {
2485 document.MassUpdate.uid.value = '';
2486 document.MassUpdate.select_entire_list.value = 0;
2487 sugarListView.check_all(document.MassUpdate, 'mass[]', false);
2488 document.MassUpdate.massall.checked = false;
2489 document.MassUpdate.massall.disabled = false;
2490 sugarListView.update_count(0);
2493 sListView = new sugarListView();
2494 // -- end sugarListView class
2496 // format and unformat numbers
2497 function unformatNumber(n, num_grp_sep, dec_sep) {
2498 var x=unformatNumberNoParse(n, num_grp_sep, dec_sep);
2501 return parseFloat(x);
2506 function unformatNumberNoParse(n, num_grp_sep, dec_sep) {
2507 if(typeof num_grp_sep == 'undefined' || typeof dec_sep == 'undefined') return n;
2508 n = n ? n.toString() : '';
2511 if(num_grp_sep != '')
2513 num_grp_sep_re = new RegExp('\\'+num_grp_sep, 'g');
2514 n = n.replace(num_grp_sep_re, '');
2517 n = n.replace(dec_sep, '.');
2519 if(typeof CurrencySymbols != 'undefined') {
2520 // Need to strip out the currency symbols from the start.
2521 for ( var idx in CurrencySymbols ) {
2522 n = n.replace(CurrencySymbols[idx], '');
2530 // round parameter can be negative for decimal, precision has to be postive
2531 function formatNumber(n, num_grp_sep, dec_sep, round, precision) {
2532 if(typeof num_grp_sep == 'undefined' || typeof dec_sep == 'undefined') return n;
2533 n = n ? n.toString() : '';
2534 if(n.split) n = n.split('.');
2537 if(n.length > 2) return n.join('.'); // that's not a num!
2539 if(typeof round != 'undefined') {
2540 if(round > 0 && n.length > 1) { // round to decimal
2541 n[1] = parseFloat('0.' + n[1]);
2542 n[1] = Math.round(n[1] * Math.pow(10, round)) / Math.pow(10, round);
2543 n[1] = n[1].toString().split('.')[1];
2545 if(round <= 0) { // round to whole number
2546 n[0] = Math.round(parseInt(n[0],10) * Math.pow(10, round)) / Math.pow(10, round);
2551 if(typeof precision != 'undefined' && precision >= 0) {
2552 if(n.length > 1 && typeof n[1] != 'undefined') n[1] = n[1].substring(0, precision); // cut off precision
2554 if(n[1].length < precision) {
2555 for(var wp = n[1].length; wp < precision; wp++) n[1] += '0';
2559 regex = /(\d+)(\d{3})/;
2560 while(num_grp_sep != '' && regex.test(n[0])) n[0] = n[0].toString().replace(regex, '$1' + num_grp_sep + '$2');
2561 return n[0] + (n.length > 1 && n[1] != '' ? dec_sep + n[1] : '');
2564 // --- begin ajax status class
2565 SUGAR.ajaxStatusClass = function() {};
2566 SUGAR.ajaxStatusClass.prototype.statusDiv = null;
2567 SUGAR.ajaxStatusClass.prototype.oldOnScroll = null;
2568 SUGAR.ajaxStatusClass.prototype.shown = false; // state of the status window
2570 // reposition the status div, top and centered
2571 SUGAR.ajaxStatusClass.prototype.positionStatus = function() {
2572 //this.statusDiv.style.top = document.body.scrollTop + 8 + 'px';
2573 statusDivRegion = YAHOO.util.Dom.getRegion(this.statusDiv);
2574 statusDivWidth = statusDivRegion.right - statusDivRegion.left;
2575 this.statusDiv.style.left = YAHOO.util.Dom.getViewportWidth() / 2 - statusDivWidth / 2 + 'px';
2578 // private func, create the status div
2579 SUGAR.ajaxStatusClass.prototype.createStatus = function(text) {
2580 statusDiv = document.createElement('div');
2581 statusDiv.className = 'dataLabel';
2582 statusDiv.id = 'ajaxStatusDiv';
2583 document.body.appendChild(statusDiv);
2584 this.statusDiv = document.getElementById('ajaxStatusDiv');
2587 // public - show the status div with text
2588 SUGAR.ajaxStatusClass.prototype.showStatus = function(text) {
2589 if(!this.statusDiv) {
2590 this.createStatus(text);
2593 this.statusDiv.style.display = '';
2595 this.statusDiv.innerHTML = ' <b>' + text + '</b> ';
2596 this.positionStatus();
2599 this.statusDiv.style.display = '';
2600 if(window.onscroll) this.oldOnScroll = window.onscroll; // save onScroll
2601 window.onscroll = this.positionStatus;
2606 SUGAR.ajaxStatusClass.prototype.hideStatus = function(text) {
2607 if(!this.shown) return;
2609 if(this.oldOnScroll) window.onscroll = this.oldOnScroll;
2610 else window.onscroll = '';
2611 this.statusDiv.style.display = 'none';
2614 SUGAR.ajaxStatusClass.prototype.flashStatus = function(text, time){
2615 this.showStatus(text);
2616 window.setTimeout('ajaxStatus.hideStatus();', time);
2620 var ajaxStatus = new SUGAR.ajaxStatusClass();
2621 // --- end ajax status class
2624 * Unified Search Advanced - for global search
2626 SUGAR.unifiedSearchAdvanced = function() {
2636 SUGAR.unifiedSearchAdvanced.usa_div = document.getElementById('unified_search_advanced_div');
2637 SUGAR.unifiedSearchAdvanced.usa_img = document.getElementById('unified_search_advanced_img');
2639 if(!SUGAR.unifiedSearchAdvanced.usa_div || !SUGAR.unifiedSearchAdvanced.usa_img) return;
2640 var attributes = { height: { to: 300 } };
2641 SUGAR.unifiedSearchAdvanced.anim_open = new YAHOO.util.Anim('unified_search_advanced_div', attributes );
2642 SUGAR.unifiedSearchAdvanced.anim_open.duration = 0.75;
2643 SUGAR.unifiedSearchAdvanced.anim_close = new YAHOO.util.Anim('unified_search_advanced_div', { height: {to: 0} } );
2644 SUGAR.unifiedSearchAdvanced.anim_close.duration = 0.75;
2645 //SUGAR.unifiedSearchAdvanced.anim_close.onComplete.subscribe(function() {SUGAR.unifiedSearchAdvanced.usa_div.style.display = 'none'});
2647 SUGAR.unifiedSearchAdvanced.usa_img._x = YAHOO.util.Dom.getX(SUGAR.unifiedSearchAdvanced.usa_img);
2648 SUGAR.unifiedSearchAdvanced.usa_img._y = YAHOO.util.Dom.getY(SUGAR.unifiedSearchAdvanced.usa_img);
2651 SUGAR.unifiedSearchAdvanced.usa_open = false;
2652 SUGAR.unifiedSearchAdvanced.usa_content = null;
2654 YAHOO.util.Event.addListener('unified_search_advanced_img', 'click', SUGAR.unifiedSearchAdvanced.get_content);
2657 get_content: function(e)
2659 query_string = trim(document.getElementById('query_string').value);
2660 if(query_string != '')
2662 window.location.href = 'index.php?module=Home&action=UnifiedSearch&query_string=' + query_string;
2664 window.location.href = 'index.php?module=Home&action=UnifiedSearch&form_only=true';
2668 animate: function(data) {
2669 ajaxStatus.hideStatus();
2672 SUGAR.unifiedSearchAdvanced.usa_content = data.responseText;
2673 SUGAR.unifiedSearchAdvanced.usa_div.innerHTML = SUGAR.unifiedSearchAdvanced.usa_content;
2675 if(SUGAR.unifiedSearchAdvanced.usa_open) {
2676 document.UnifiedSearch.advanced.value = 'false';
2677 SUGAR.unifiedSearchAdvanced.anim_close.animate();
2680 document.UnifiedSearch.advanced.value = 'true';
2681 SUGAR.unifiedSearchAdvanced.usa_div.style.display = '';
2682 YAHOO.util.Dom.setX(SUGAR.unifiedSearchAdvanced.usa_div, SUGAR.unifiedSearchAdvanced.usa_img._x - 90);
2683 YAHOO.util.Dom.setY(SUGAR.unifiedSearchAdvanced.usa_div, SUGAR.unifiedSearchAdvanced.usa_img._y + 15);
2684 SUGAR.unifiedSearchAdvanced.anim_open.animate();
2686 SUGAR.unifiedSearchAdvanced.usa_open = !SUGAR.unifiedSearchAdvanced.usa_open;
2691 checkUsaAdvanced: function() {
2692 if(document.UnifiedSearch.advanced.value == 'true') {
2693 document.UnifiedSearchAdvanced.query_string.value = document.UnifiedSearch.query_string.value;
2694 document.UnifiedSearchAdvanced.submit();
2701 if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.unifiedSearchAdvanced.init);
2706 * Toggles the header
2708 toggleHeader : function() {
2709 var h = document.getElementById('header');
2713 if(h.style.display == 'none') {
2714 h.style.display = '';
2716 h.style.display = 'none';
2720 alert(SUGAR.language.get("app_strings", "ERR_NO_HEADER_ID"));
2727 * General Sugar Utils
2729 SUGAR.util = function () {
2730 var additionalDetailsCache;
2731 var additionalDetailsCalls;
2732 var additionalDetailsRpcCall;
2735 getAndRemove : function (el) {
2736 if (YAHOO && YAHOO.util && YAHOO.util.Dom)
2737 el = YAHOO.util.Dom.get(el);
2738 else if (typeof (el) == "string")
2739 el = document.getElementById(el);
2740 if (el && el.parentNode)
2741 el.parentNode.removeChild(el);
2745 paramsToUrl : function (params) {
2748 url += i + "=" + params[i] + "&";
2752 evalScript:function(text){
2754 var waitUntilLoaded = function(){
2755 SUGAR.evalScript_waitCount--;
2756 if (SUGAR.evalScript_waitCount == 0) {
2757 var headElem = document.getElementsByTagName('head')[0];
2758 for ( var i = 0; i < SUGAR.evalScript_evalElem.length; i++) {
2759 var tmpElem = document.createElement('script');
2760 tmpElem.type = 'text/javascript';
2761 tmpElem.text = SUGAR.evalScript_evalElem[i];
2762 headElem.appendChild(tmpElem);
2767 var tmpElem = document.createElement('div');
2768 tmpElem.innerHTML = text;
2769 var results = tmpElem.getElementsByTagName('script');
2770 if (results == null) {
2771 // No scripts found, bail out
2775 var headElem = document.getElementsByTagName('head')[0];
2777 SUGAR.evalScript_waitCount = 0;
2778 SUGAR.evalScript_evalElem = new Array();
2779 for (var i = 0; i < results.length; i++) {
2780 if (typeof(results[i]) != 'object') {
2783 tmpElem = document.createElement('script');
2784 tmpElem.type = 'text/javascript';
2785 if (results[i].src != null && results[i].src != '') {
2786 tmpElem.src = results[i].src;
2788 // Need to defer execution of these scripts until the
2789 // required javascript files are fully loaded
2790 SUGAR.evalScript_evalElem[SUGAR.evalScript_evalElem.length] = results[i].text;
2793 tmpElem.addEventListener('load', waitUntilLoaded);
2794 SUGAR.evalScript_waitCount++;
2795 headElem.appendChild(tmpElem);
2797 // Add some code to handle pages without any external scripts
2798 SUGAR.evalScript_waitCount++;
2801 // Don't try and process things the IE way
2805 var objRegex = /<\s*script([^>]*)>((.|\s|\v|\0)*?)<\s*\/script\s*>/igm;
2807 var result = objRegex.exec(text);
2808 while(result && result.index > lastIndex){
2809 lastIndex = result.index
2811 var script = document.createElement('script');
2812 script.type= 'text/javascript';
2813 if(result[1].indexOf("src=") > -1){
2814 var srcRegex = /.*src=['"]([a-zA-Z0-9_\&\/\.\?=:-]*)['"].*/igm;
2815 var srcResult = result[1].replace(srcRegex, '$1');
2816 script.src = srcResult;
2818 script.text = result[2];
2820 document.body.appendChild(script);
2823 if(typeof(console) != "undefined" && typeof(console.log) == "function")
2825 console.log("error adding script");
2827 console.log(result);
2830 result = objRegex.exec(text);
2834 * Gets the sidebar object
2835 * @return object pointer to the sidebar element
2837 getLeftColObj: function() {
2838 leftColObj = document.getElementById('leftCol');
2839 while(leftColObj.nodeName != 'TABLE') {
2840 leftColObj = leftColObj.firstChild;
2842 leftColTable = leftColObj;
2843 leftColTd = leftColTable.getElementsByTagName('td')[0];
2844 leftColTdRegion = YAHOO.util.Dom.getRegion(leftColTd);
2845 leftColTd.style.width = (leftColTdRegion.right - leftColTdRegion.left) + 'px';
2850 * Fills the shortcut menu placeholders w/ actual content
2851 * Call this on load event
2853 * @param shortcutContent Array array of content to fill in
2855 fillShortcuts: function(e, shortcutContent) {
2858 // don't do this if leftCol isn't available
2859 if (document.getElementById('leftCol') == undefined) { return; }
2861 spans = document.getElementById('leftCol').getElementsByTagName('span');
2862 hideCol = document.getElementById('HideMenu').getElementsByTagName('span');
2863 w = spans.length + 1;
2865 spans[w] = hideCol[i];
2868 for(je in shortcutContent) {
2870 if(typeof spans[wp].innerHTML != 'undefined' && spans[wp].innerHTML == ('wp_shortcut_fill_' + je)) {
2871 if(typeof spans[wp].parentNode.parentNode == 'object') {
2872 if(typeof spans[wp].parentNode.parentNode.onclick != 'undefined') {
2873 spans[wp].parentNode.parentNode.onclick = null;
2875 // If the wp_shortcut span is contained by an A tag, replace the A with a DIV.
2876 if(spans[wp].parentNode.tagName == 'A' && !isIE) {
2877 var newDiv = document.createElement('DIV');
2878 var parentAnchor = spans[wp].parentNode;
2880 spans[wp].parentNode.parentNode.style.display = 'none';
2882 // Copy styles over to the new container div
2883 if(window.getComputedStyle) {
2884 var parentStyle = window.getComputedStyle(parentAnchor, '');
2885 for(var styleName in parentStyle) {
2886 if(typeof parentStyle[styleName] != 'function'
2887 && styleName != 'display'
2888 && styleName != 'borderWidth'
2889 && styleName != 'visibility') {
2891 newDiv.style[styleName] = parentStyle[styleName];
2893 // Catches .length and .parentRule, and others
2899 // Replace the A with the DIV
2900 newDiv.appendChild(spans[wp]);
2901 parentAnchor.parentNode.replaceChild(newDiv, parentAnchor);
2903 spans[wp].parentNode.parentNode.style.display = '';
2906 spans[wp].innerHTML = shortcutContent[je]; // fill w/ content
2907 if(spans[wp].style) spans[wp].style.display = '';
2913 * Make an AJAX request.
2915 * @param url string resource to load
2916 * @param theDiv string id of element to insert loaded data into
2917 * @param postForm string if set, a POST request will be made to resource specified by url using the form named by postForm
2918 * @param callback string name of function to invoke after HTTP response is recieved
2919 * @param callbackParam any parameter to pass to callback when invoked
2920 * @param appendMode bool if true, HTTP response will be appended to the contents of theDiv, or else contents will be overriten.
2922 retrieveAndFill: function(url, theDiv, postForm, callback, callbackParam, appendMode) {
2923 if(typeof theDiv == 'string') {
2925 theDiv = document.getElementById(theDiv);
2932 var success = function(data) {
2933 if (typeof theDiv != 'undefined' && theDiv != null)
2936 if (typeof appendMode != 'undefined' && appendMode)
2938 theDiv.innerHTML += data.responseText;
2942 theDiv.innerHTML = data.responseText;
2949 if (typeof callback != 'undefined' && callback != null) callback(callbackParam);
2952 if(typeof postForm == 'undefined' || postForm == null) {
2953 var cObj = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
2956 YAHOO.util.Connect.setForm(postForm);
2957 var cObj = YAHOO.util.Connect.asyncRequest('POST', url, {success: success, failure: success});
2960 checkMaxLength: function() { // modified from http://www.quirksmode.org/dom/maxlength.html
2961 var maxLength = this.getAttribute('maxlength');
2962 var currentLength = this.value.length;
2963 if (currentLength > maxLength) {
2964 this.value = this.value.substring(0, maxLength);
2969 * Adds maxlength attribute to textareas
2971 setMaxLength: function() { // modified from http://www.quirksmode.org/dom/maxlength.html
2972 var x = document.getElementsByTagName('textarea');
2973 for (var i=0;i<x.length;i++) {
2974 if (x[i].getAttribute('maxlength')) {
2975 x[i].onkeyup = x[i].onchange = SUGAR.util.checkMaxLength;
2982 * Retrieves additional details dynamically
2984 getAdditionalDetails: function(bean, id, spanId) {
2986 oReturn = function(body, caption, width, theme) {
2987 var _refx = 25-width;
2988 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);
2991 success = function(data) {
2992 eval(data.responseText);
2994 SUGAR.util.additionalDetailsCache[spanId] = new Array();
2995 SUGAR.util.additionalDetailsCache[spanId]['body'] = result['body'];
2996 SUGAR.util.additionalDetailsCache[spanId]['caption'] = result['caption'];
2997 SUGAR.util.additionalDetailsCache[spanId]['width'] = result['width'];
2998 SUGAR.util.additionalDetailsCache[spanId]['theme'] = result['theme'];
2999 ajaxStatus.hideStatus();
3000 return oReturn(SUGAR.util.additionalDetailsCache[spanId]['body'], SUGAR.util.additionalDetailsCache[spanId]['caption'], SUGAR.util.additionalDetailsCache[spanId]['width'], SUGAR.util.additionalDetailsCache[spanId]['theme']);
3003 if(typeof SUGAR.util.additionalDetailsCache[spanId] != 'undefined')
3004 return oReturn(SUGAR.util.additionalDetailsCache[spanId]['body'], SUGAR.util.additionalDetailsCache[spanId]['caption'], SUGAR.util.additionalDetailsCache[spanId]['width'], SUGAR.util.additionalDetailsCache[spanId]['theme']);
3006 if(typeof SUGAR.util.additionalDetailsCalls[spanId] != 'undefined') // call already in progress
3008 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_LOADING'));
3009 url = 'index.php?to_pdf=1&module=Home&action=AdditionalDetailsRetrieve&bean=' + bean + '&id=' + id;
3010 SUGAR.util.additionalDetailsCalls[spanId] = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
3014 SUGAR.util.additionalDetailsRpcCall = window.setTimeout('go()', 250);
3016 clearAdditionalDetailsCall: function() {
3017 if(typeof SUGAR.util.additionalDetailsRpcCall == 'number') window.clearTimeout(SUGAR.util.additionalDetailsRpcCall);
3020 * A function that extends functionality from parent to child.
3022 extend : function(subc, superc, overrides) {
3023 subc.prototype = new superc; // set the superclass
3026 for (var i in overrides) subc.prototype[i] = overrides[i];
3029 hrefURL : function(url) {
3031 // IE needs special treatment since otherwise it would not pass Referer
3032 var trampoline = document.createElement('a');
3033 trampoline.href = url;
3034 document.body.appendChild(trampoline);
3036 document.body.removeChild(trampoline);
3038 document.location.href = url;
3042 openWindow : function(URL, windowName, windowFeatures) {
3044 // IE needs special treatment since otherwise it would not pass Referer
3045 win = window.open('', windowName, windowFeatures);
3046 var trampoline = document.createElement('a');
3047 trampoline.href = URL;
3048 trampoline.target = windowName;
3049 document.body.appendChild(trampoline);
3051 document.body.removeChild(trampoline);
3053 win = window.open(URL, windowName, windowFeatures);
3057 //Reset the scroll on the window
3062 //Based on YUI onAvailible, but will use any boolean function instead of an ID
3063 doWhen : function(condition, fn, params, scope)
3065 this._doWhenStack.push({
3069 overrideContext: scope
3072 this._doWhenretryCount = 50;
3073 this._startDoWhenInterval();
3076 _startDoWhenInterval : function(){
3077 if (!this._doWhenInterval) {
3078 this._doWhenInterval = YAHOO.lang.later(50, this, this._doWhenCheck, null, true);
3082 _doWhenInterval : false,
3083 _doWhenCheck : function() {
3084 if (this._doWhenStack.length === 0) {
3085 this._doWhenretryCount = 0;
3086 if (this._doWhenInterval) {
3087 // clearInterval(this._interval);
3088 this._doWhenInterval.cancel();
3089 this._doWhenInterval = null;
3094 if (this._doWhenLocked) {
3099 // Hold off if DOMReady has not fired and check current
3100 // readyState to protect against the IE operation aborted
3102 if (!YAHOO.util.Event.DOMReady) {
3103 this._startDoWhenInterval();
3108 this._doWhenLocked = true;
3111 // keep trying until after the page is loaded. We need to
3112 // check the page load state prior to trying to bind the
3113 // elements so that we can be certain all elements have been
3114 // tested appropriately
3115 var tryAgain = YAHOO.util.Event.DOMReady;
3117 tryAgain = (this._doWhenretryCount > 0 && this._doWhenStack.length > 0);
3123 var executeItem = function (context, item) {
3124 if (item.overrideContext) {
3125 if (item.overrideContext === true) {
3128 context = item.overrideContext;
3131 item.fn.call(context, item.obj);
3134 var i, len, item, test;
3136 // onAvailable onContentReady
3137 for (i=0, len=this._doWhenStack.length; i<len; i=i+1) {
3138 item = this._doWhenStack[i];
3141 if ((typeof(test) == "string" && eval(test)) || (typeof(test) == "function" && test())) {
3142 executeItem(this, item);
3143 this._doWhenStack[i] = null;
3146 notAvail.push(item);
3151 this._doWhenretryCount--;
3154 for (i=this._doWhenStack.length-1; i>-1; i--) {
3155 item = this._doWhenStack[i];
3156 if (!item || !item.check) {
3157 this._doWhenStack.splice(i, 1);
3160 this._startDoWhenInterval();
3162 if (this._doWhenInterval) {
3163 // clearInterval(this._interval);
3164 this._doWhenInterval.cancel();
3165 this._doWhenInterval = null;
3168 this._doWhenLocked = false;
3172 SUGAR.util.additionalDetailsCache = new Array();
3173 SUGAR.util.additionalDetailsCalls = new Array();
3174 if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.util.setMaxLength); // allow textareas to obey maxlength attrib
3176 SUGAR.savedViews = function() {
3177 var selectedOrderBy;
3178 var selectedSortOrder;
3181 var columnsMeta; // meta data for the display columns
3184 setChooser: function() {
3186 var displayColumnsDef = new Array();
3187 var hideTabsDef = new Array();
3189 var left_td = document.getElementById('display_tabs_td');
3190 if(typeof left_td == 'undefined' || left_td == null) return; // abort!
3191 var right_td = document.getElementById('hide_tabs_td');
3193 var displayTabs = left_td.getElementsByTagName('select')[0];
3194 var hideTabs = right_td.getElementsByTagName('select')[0];
3196 for(i = 0; i < displayTabs.options.length; i++) {
3197 displayColumnsDef.push(displayTabs.options[i].value);
3200 if(typeof hideTabs != 'undefined') {
3201 for(i = 0; i < hideTabs.options.length; i++) {
3202 hideTabsDef.push(hideTabs.options[i].value);
3205 if (!SUGAR.savedViews.clearColumns)
3206 document.getElementById('displayColumnsDef').value = displayColumnsDef.join('|');
3207 document.getElementById('hideTabsDef').value = hideTabsDef.join('|');
3210 select: function(saved_search_select) {
3211 for(var wp = 0; wp < document.search_form.saved_search_select.options.length; wp++) {
3212 if(typeof document.search_form.saved_search_select.options[wp].value != 'undefined' &&
3213 document.search_form.saved_search_select.options[wp].value == saved_search_select) {
3214 document.search_form.saved_search_select.selectedIndex = wp;
3215 document.search_form.ss_delete.style.display = '';
3216 document.search_form.ss_update.style.display = '';
3220 saved_search_action: function(action, delete_lang) {
3221 if(action == 'delete') {
3222 if(!confirm(delete_lang)) return;
3224 if(action == 'save') {
3225 if(document.search_form.saved_search_name.value.replace(/^\s*|\s*$/g, '') == '') {
3226 alert(SUGAR.language.get('app_strings', 'LBL_SAVED_SEARCH_ERROR'));
3231 // This check is needed for the Activities module (Calls/Meetings/Tasks).
3232 if (document.search_form.saved_search_action)
3234 document.search_form.saved_search_action.value = action;
3235 document.search_form.search_module.value = document.search_form.module.value;
3236 document.search_form.module.value = 'SavedSearch';
3237 // Bug 31922 - Make sure to specify that we want to hit the index view here of
3238 // the SavedSearch module, since the ListView doesn't have the logic to save the
3239 // search and redirect back
3240 document.search_form.action.value = 'index';
3242 SUGAR.ajaxUI.submitForm(document.search_form);
3244 shortcut_select: function(selectBox, module) {
3246 selecturl = 'index.php?module=SavedSearch&search_module=' + module + '&action=index&saved_search_select=' + selectBox.options[selectBox.selectedIndex].value
3247 //add searchFormTab to url if it is available. This determines what tab to render
3248 if(typeof(document.getElementById('searchFormTab'))!='undefined'){
3249 selecturl = selecturl + '&searchFormTab=' + document.search_form.searchFormTab.value;
3251 //add showSSDIV to url if it is available. This determines whether saved search sub form should
3252 //be rendered open or not
3253 if(document.getElementById('showSSDIV') && typeof(document.getElementById('showSSDIV') !='undefined')){
3254 selecturl = selecturl + '&showSSDIV='+document.getElementById('showSSDIV').value;
3256 //use created url to navigate
3257 document.location.href = selecturl;
3259 handleForm: function() {
3260 SUGAR.tabChooser.movementCallback = function(left_side, right_side) {
3261 while(document.getElementById('orderBySelect').childNodes.length != 0) { // clear out order by options
3262 document.getElementById('orderBySelect').removeChild(document.getElementById('orderBySelect').lastChild);
3265 var selectedIndex = 0;
3266 var nodeCount = -1; // need this because the counter i also includes "undefined" nodes
3267 // which was breaking Calls and Meetings
3269 for(i in left_side.childNodes) { // fill in order by options
3270 if(typeof left_side.childNodes[i].nodeName != 'undefined' &&
3271 left_side.childNodes[i].nodeName.toLowerCase() == 'option' &&
3272 typeof SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value] != 'undefined' && // check if column is sortable
3273 typeof SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value]['sortable'] == 'undefined' &&
3274 SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value]['sortable'] != false) {
3276 optionNode = document.createElement('option');
3277 optionNode.value = left_side.childNodes[i].value;
3278 optionNode.innerHTML = left_side.childNodes[i].innerHTML;
3279 document.getElementById('orderBySelect').appendChild(optionNode);
3280 if(optionNode.value == SUGAR.savedViews.selectedOrderBy)
3281 selectedIndex = nodeCount;
3284 // Firefox needs this to be set after all the option nodes are created.
3285 document.getElementById('orderBySelect').selectedIndex = selectedIndex;
3287 SUGAR.tabChooser.movementCallback(document.getElementById('display_tabs_td').getElementsByTagName('select')[0]);
3289 // This check is needed for the Activities module (Calls/Meetings/Tasks).
3290 if (document.search_form.orderBy)
3291 document.search_form.orderBy.options.value = SUGAR.savedViews.selectedOrderBy;
3294 if(SUGAR.savedViews.selectedSortOrder == 'DESC') document.getElementById('sort_order_desc_radio').checked = true;
3295 else document.getElementById('sort_order_asc_radio').checked = true;
3300 SUGAR.searchForm = function() {
3303 // searchForm tab selector util
3304 searchFormSelect: function(view, previousView) {
3305 var module = view.split('|')[0];
3306 var theView = view.split('|')[1];
3308 var handleDisplay = function() { // hide other divs
3309 document.search_form.searchFormTab.value = theView;
3310 patt = module+"(.*)SearchForm$";
3311 divId=document.search_form.getElementsByTagName('div');
3312 // Hide all the search forms and retrive the name of the previous search tab (useful for the first load because previousView is empty)
3313 for (i=0;i<divId.length;i++){
3314 if(divId[i].id.match(module)==module){
3315 if(divId[i].id.match('SearchForm')=='SearchForm'){
3316 if(document.getElementById(divId[i].id).style.display == ''){
3317 previousTab=divId[i].id.match(patt)[1];
3319 document.getElementById(divId[i].id).style.display = 'none';
3323 // show the good search form.
3324 document.getElementById(module + theView + 'SearchForm').style.display = '';
3325 //if its not the first tab show there is a previous tab.
3327 thepreviousView=previousView.split('|')[1];
3330 thepreviousView=previousTab;
3332 thepreviousView=thepreviousView.replace(/_search/, "");
3333 // Process to retrieve the completed field from one tab to an other.
3334 for(num in document.search_form.elements) {
3335 if(document.search_form.elements[num]) {
3336 el = document.search_form.elements[num];
3337 pattern="^(.*)_"+thepreviousView+"$";
3338 if(typeof el.type != 'undefined' && typeof el.name != 'undefined' && el.name.match(pattern)) {
3339 advanced_input_name = el.name.match(pattern)[1]; // strip
3340 advanced_input_name = advanced_input_name+"_"+theView.replace(/_search/, "");
3341 if(typeof document.search_form[advanced_input_name] != 'undefined') // if advanced input of same name exists
3342 SUGAR.searchForm.copyElement(advanced_input_name, el);
3348 // if tab is not cached
3349 if(document.getElementById(module + theView + 'SearchForm').innerHTML == '') {
3350 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_LOADING'));
3351 var success = function(data) {
3352 document.getElementById(module + theView + 'SearchForm').innerHTML = data.responseText;
3354 SUGAR.util.evalScript(data.responseText);
3355 // pass script variables to global scope
3356 if(theView == 'saved_views') {
3357 if(typeof columnsMeta != 'undefined') SUGAR.savedViews.columnsMeta = columnsMeta;
3358 if(typeof selectedOrderBy != 'undefined') SUGAR.savedViews.selectedOrderBy = selectedOrderBy;
3359 if(typeof selectedSortOrder != 'undefined') SUGAR.savedViews.selectedSortOrder = selectedSortOrder;
3364 ajaxStatus.hideStatus();
3366 url = 'index.php?module=' + module + '&action=index&search_form_only=true&to_pdf=true&search_form_view=' + theView;
3368 //check to see if tpl has been specified. If so then pass location through url string
3370 if(document.getElementById('search_tpl') !=null && typeof(document.getElementById('search_tpl')) != 'undefined'){
3371 tpl = document.getElementById('search_tpl').value;
3372 if(tpl != ''){url += '&search_tpl='+tpl;}
3375 if(theView == 'saved_views') // handle the tab chooser
3376 url += '&displayColumns=' + SUGAR.savedViews.displayColumns + '&hideTabs=' + SUGAR.savedViews.hideTabs + '&orderBy=' + SUGAR.savedViews.selectedOrderBy + '&sortOrder=' + SUGAR.savedViews.selectedSortOrder;
3378 var cObj = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
3380 else { // that form already retrieved
3385 // copies one input to another
3386 copyElement: function(inputName, copyFromElement) {
3387 switch(copyFromElement.type) {
3390 document.search_form[inputName].value = copyFromElement.value;
3394 // This function is here to clear the form, instead of "resubmitting it
3395 clear_form: function(form, skipElementNames) {
3396 var elemList = form.elements;
3400 for( var i = 0; i < elemList.length ; i++ ) {
3402 if ( typeof(elem.type) == 'undefined' ) {
3406 if ( typeof(elem.type) != 'undefined' && typeof(skipElementNames) != 'undefined'
3407 && SUGAR.util.arrayIndexOf(skipElementNames, elem.name) != -1 )
3412 elemType = elem.type.toLowerCase();
3414 if ( elemType == 'text' || elemType == 'textarea' || elemType == 'password' ) {
3417 else if ( elemType == 'select' || elemType == 'select-one' || elemType == 'select-multiple' ) {
3418 // We have, what I hope, is a select box, time to unselect all options
3419 var optionList = elem.options;
3420 for ( var ii = 0 ; ii < optionList.length ; ii++ ) {
3421 optionList[ii].selected = false;
3424 else if ( elemType == 'radio' || elemType == 'checkbox' ) {
3425 elem.checked = false;
3426 elem.selected = false;
3428 else if ( elemType == 'hidden' ) {
3429 // We only want to reset the hidden values that link to the select boxes.
3430 if ( ( elem.name.length > 3 && elem.name.substring(elem.name.length-3) == '_id' )
3431 || ((elem.name.length > 9) && (elem.name.substring(elem.name.length - 9) == '_id_basic'))
3432 || ( elem.name.length > 12 && elem.name.substring(elem.name.length-12) == '_id_advanced' ) ) {
3437 SUGAR.savedViews.clearColumns = true;
3441 // Code for the column/tab chooser used on homepage and in admin section
3442 SUGAR.tabChooser = function () {
3443 var object_refs = new Array();
3445 /* Describe certain transfers as invalid */
3448 movementCallback: function(left_side, right_side) {},
3449 orderCallback: function(left_side, right_side) {},
3451 freezeOptions: function(left_name, right_name, target) {
3452 if(!SUGAR.tabChooser.frozenOptions) { SUGAR.tabChooser.frozenOptions = []; }
3453 if(!SUGAR.tabChooser.frozenOptions[left_name]) { SUGAR.tabChooser.frozenOptions[left_name] = []; }
3454 if(!SUGAR.tabChooser.frozenOptions[left_name][right_name]) { SUGAR.tabChooser.frozenOptions[left_name][right_name] = []; }
3455 if(typeof target == 'array') {
3456 for(var i in target) {
3457 SUGAR.tabChooser.frozenOptions[left_name][right_name][target[i]] = true;
3460 SUGAR.tabChooser.frozenOptions[left_name][right_name][target] = true;
3464 buildSelectHTML: function(info) {
3465 var text = "<select";
3467 if(typeof (info['select']['size']) != 'undefined') {
3468 text +=" size=\""+ info['select']['size'] +"\"";
3471 if(typeof (info['select']['name']) != 'undefined') {
3472 text +=" name=\""+ info['select']['name'] +"\"";
3475 if(typeof (info['select']['style']) != 'undefined') {
3476 text +=" style=\""+ info['select']['style'] +"\"";
3479 if(typeof (info['select']['onchange']) != 'undefined') {
3480 text +=" onChange=\""+ info['select']['onchange'] +"\"";
3483 if(typeof (info['select']['multiple']) != 'undefined') {
3488 for(i=0; i<info['options'].length;i++) {
3489 option = info['options'][i];
3490 text += "<option value=\""+option['value']+"\" ";
3491 if ( typeof (option['selected']) != 'undefined' && option['selected']== true) {
3494 text += ">"+option['text']+"</option>";
3496 text += "</select>";
3500 left_to_right: function(left_name, right_name, left_size, right_size) {
3501 SUGAR.savedViews.clearColumns = false;
3502 var left_td = document.getElementById(left_name+'_td');
3503 var right_td = document.getElementById(right_name+'_td');
3505 var display_columns_ref = left_td.getElementsByTagName('select')[0];
3506 var hidden_columns_ref = right_td.getElementsByTagName('select')[0];
3508 var selected_left = new Array();
3509 var notselected_left = new Array();
3510 var notselected_right = new Array();
3512 var left_array = new Array();
3514 var frozen_options = SUGAR.tabChooser.frozenOptions;
3515 frozen_options = frozen_options && frozen_options[left_name] && frozen_options[left_name][right_name]?frozen_options[left_name][right_name]:[];
3517 // determine which options are selected in left
3518 for (i=0; i < display_columns_ref.options.length; i++)
3520 if ( display_columns_ref.options[i].selected == true && !frozen_options[display_columns_ref.options[i].value])
3522 selected_left[selected_left.length] = {text: display_columns_ref.options[i].text, value: display_columns_ref.options[i].value};
3526 notselected_left[notselected_left.length] = {text: display_columns_ref.options[i].text, value: display_columns_ref.options[i].value};
3531 for (i=0; i < hidden_columns_ref.options.length; i++)
3533 notselected_right[notselected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
3537 var left_select_html_info = new Object();
3538 var left_options = new Array();
3539 var left_select = new Object();
3541 left_select['name'] = left_name+'[]';
3542 left_select['id'] = left_name;
3543 left_select['size'] = left_size;
3544 left_select['multiple'] = 'true';
3546 var right_select_html_info = new Object();
3547 var right_options = new Array();
3548 var right_select = new Object();
3550 right_select['name'] = right_name+'[]';
3551 right_select['id'] = right_name;
3552 right_select['size'] = right_size;
3553 right_select['multiple'] = 'true';
3555 for (i = 0; i < notselected_right.length; i++) {
3556 right_options[right_options.length] = notselected_right[i];
3559 for (i = 0; i < selected_left.length; i++) {
3560 right_options[right_options.length] = selected_left[i];
3562 for (i = 0; i < notselected_left.length; i++) {
3563 left_options[left_options.length] = notselected_left[i];
3565 left_select_html_info['options'] = left_options;
3566 left_select_html_info['select'] = left_select;
3567 right_select_html_info['options'] = right_options;
3568 right_select_html_info['select'] = right_select;
3569 right_select_html_info['style'] = 'background: lightgrey';
3571 var left_html = this.buildSelectHTML(left_select_html_info);
3572 var right_html = this.buildSelectHTML(right_select_html_info);
3574 left_td.innerHTML = left_html;
3575 right_td.innerHTML = right_html;
3577 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3578 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3580 this.movementCallback(object_refs[left_name], object_refs[right_name]);
3586 right_to_left: function(left_name, right_name, left_size, right_size, max_left) {
3587 SUGAR.savedViews.clearColumns = false;
3588 var left_td = document.getElementById(left_name+'_td');
3589 var right_td = document.getElementById(right_name+'_td');
3591 var display_columns_ref = left_td.getElementsByTagName('select')[0];
3592 var hidden_columns_ref = right_td.getElementsByTagName('select')[0];
3594 var selected_right = new Array();
3595 var notselected_right = new Array();
3596 var notselected_left = new Array();
3598 var frozen_options = SUGAR.tabChooser.frozenOptions;
3599 frozen_options = SUGAR.tabChooser.frozenOptions && SUGAR.tabChooser.frozenOptions[right_name] && SUGAR.tabChooser.frozenOptions[right_name][left_name]?SUGAR.tabChooser.frozenOptions[right_name][left_name]:[];
3601 for (i=0; i < hidden_columns_ref.options.length; i++)
3603 if (hidden_columns_ref.options[i].selected == true && !frozen_options[hidden_columns_ref.options[i].value])
3605 selected_right[selected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
3609 notselected_right[notselected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
3614 if(max_left != '' && (display_columns_ref.length + selected_right.length) > max_left) {
3615 alert('Maximum of ' + max_left + ' columns can be displayed.');
3619 for (i=0; i < display_columns_ref.options.length; i++)
3621 notselected_left[notselected_left.length] = {text:display_columns_ref.options[i].text, value:display_columns_ref.options[i].value};
3625 var left_select_html_info = new Object();
3626 var left_options = new Array();
3627 var left_select = new Object();
3629 left_select['name'] = left_name+'[]';
3630 left_select['id'] = left_name;
3631 left_select['multiple'] = 'true';
3632 left_select['size'] = left_size;
3634 var right_select_html_info = new Object();
3635 var right_options = new Array();
3636 var right_select = new Object();
3638 right_select['name'] = right_name+ '[]';
3639 right_select['id'] = right_name;
3640 right_select['multiple'] = 'true';
3641 right_select['size'] = right_size;
3643 for (i = 0; i < notselected_left.length; i++) {
3644 left_options[left_options.length] = notselected_left[i];
3647 for (i = 0; i < selected_right.length; i++) {
3648 left_options[left_options.length] = selected_right[i];
3650 for (i = 0; i < notselected_right.length; i++) {
3651 right_options[right_options.length] = notselected_right[i];
3653 left_select_html_info['options'] = left_options;
3654 left_select_html_info['select'] = left_select;
3655 right_select_html_info['options'] = right_options;
3656 right_select_html_info['select'] = right_select;
3657 right_select_html_info['style'] = 'background: lightgrey';
3659 var left_html = this.buildSelectHTML(left_select_html_info);
3660 var right_html = this.buildSelectHTML(right_select_html_info);
3662 left_td.innerHTML = left_html;
3663 right_td.innerHTML = right_html;
3665 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3666 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3668 this.movementCallback(object_refs[left_name], object_refs[right_name]);
3673 up: function(name, left_name, right_name) {
3674 SUGAR.savedViews.clearColumns = false;
3675 var left_td = document.getElementById(left_name+'_td');
3676 var right_td = document.getElementById(right_name+'_td');
3677 var td = document.getElementById(name+'_td');
3678 var obj = td.getElementsByTagName('select')[0];
3679 obj = (typeof obj == "string") ? document.getElementById(obj) : obj;
3680 if (obj.tagName.toLowerCase() != "select" && obj.length < 2)
3682 var sel = new Array();
3684 for (i=0; i<obj.length; i++) {
3685 if (obj[i].selected == true) {
3686 sel[sel.length] = i;
3689 for (i=0; i < sel.length; i++) {
3690 if (sel[i] != 0 && !obj[sel[i]-1].selected) {
3691 var tmp = new Array(obj[sel[i]-1].text, obj[sel[i]-1].value);
3692 obj[sel[i]-1].text = obj[sel[i]].text;
3693 obj[sel[i]-1].value = obj[sel[i]].value;
3694 obj[sel[i]].text = tmp[0];
3695 obj[sel[i]].value = tmp[1];
3696 obj[sel[i]-1].selected = true;
3697 obj[sel[i]].selected = false;
3701 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3702 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3704 this.orderCallback(object_refs[left_name], object_refs[right_name]);
3709 down: function(name, left_name, right_name) {
3710 SUGAR.savedViews.clearColumns = false;
3711 var left_td = document.getElementById(left_name+'_td');
3712 var right_td = document.getElementById(right_name+'_td');
3713 var td = document.getElementById(name+'_td');
3714 var obj = td.getElementsByTagName('select')[0];
3715 if (obj.tagName.toLowerCase() != "select" && obj.length < 2)
3717 var sel = new Array();
3718 for (i=obj.length-1; i>-1; i--) {
3719 if (obj[i].selected == true) {
3720 sel[sel.length] = i;
3723 for (i=0; i < sel.length; i++) {
3724 if (sel[i] != obj.length-1 && !obj[sel[i]+1].selected) {
3725 var tmp = new Array(obj[sel[i]+1].text, obj[sel[i]+1].value);
3726 obj[sel[i]+1].text = obj[sel[i]].text;
3727 obj[sel[i]+1].value = obj[sel[i]].value;
3728 obj[sel[i]].text = tmp[0];
3729 obj[sel[i]].value = tmp[1];
3730 obj[sel[i]+1].selected = true;
3731 obj[sel[i]].selected = false;
3735 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3736 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3738 this.orderCallback(object_refs[left_name], object_refs[right_name]);
3743 }(); // end tabChooser
3745 SUGAR.language = function() {
3747 languages : new Array(),
3749 setLanguage: function(module, data) {
3750 if (!SUGAR.language.languages) {
3753 SUGAR.language.languages[module] = data;
3756 get: function(module, str) {
3757 if(typeof SUGAR.language.languages[module] == 'undefined' || typeof SUGAR.language.languages[module][str] == 'undefined')
3761 return SUGAR.language.languages[module][str];
3764 translate: function(module, str)
3766 text = this.get(module, str);
3767 return text != 'undefined' ? text : this.get('app_strings', str);
3772 SUGAR.contextMenu = function() {
3774 objects: new Object(),
3775 objectTypes: new Object(),
3777 * Registers a new object for the context menu.
3778 * objectType - name of the type
3780 * metaData - metaData to pass to the action function
3782 registerObject: function(objectType, id, metaData) {
3783 SUGAR.contextMenu.objects[id] = new Object();
3784 SUGAR.contextMenu.objects[id] = {'objectType' : objectType, 'metaData' : metaData};
3787 * Registers a new object type
3788 * name - name of the type
3789 * menuItems - array of menu items
3791 registerObjectType: function(name, menuItems) {
3792 SUGAR.contextMenu.objectTypes[name] = new Object();
3793 SUGAR.contextMenu.objectTypes[name] = {'menuItems' : menuItems, 'objects' : new Array()};
3796 * Determines which menu item was clicked
3798 getListItemFromEventTarget: function(p_oNode) {
3800 if(p_oNode.tagName == "LI") {
3805 if(p_oNode.tagName == "LI") {
3810 } while((p_oNode = p_oNode.parentNode));
3815 * handles movement within context menu
3817 onContextMenuMove: function() {
3818 var oNode = this.contextEventTarget;
3819 var bDisabled = (oNode.tagName == "UL");
3820 var i = this.getItemGroups()[0].length - 1;
3822 this.getItem(i).cfg.setProperty("disabled", bDisabled);
3827 * handles clicks on a context menu ITEM
3829 onContextMenuItemClick: function(p_sType, p_aArguments, p_oItem) {
3830 var oLI = SUGAR.contextMenu.getListItemFromEventTarget(this.parent.contextEventTarget);
3831 id = this.parent.contextEventTarget.parentNode.id; // id of the target
3832 funct = eval(SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[id]['objectType']]['menuItems'][this.index]['action']);
3833 funct(this.parent.contextEventTarget, SUGAR.contextMenu.objects[id]['metaData']);
3836 * Initializes all context menus registered
3839 for(var i in SUGAR.contextMenu.objects) { // make a variable called objects in objectTypes containg references to all triggers
3840 if(typeof SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'] == 'undefined')
3841 SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'] = new Array();
3842 SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'].push(document.getElementById(i));
3844 // register the menus
3845 for(var i in SUGAR.contextMenu.objectTypes) {
3846 var oContextMenu = new YAHOO.widget.ContextMenu(i, {'trigger': SUGAR.contextMenu.objectTypes[i]['objects']});
3847 var aMainMenuItems = SUGAR.contextMenu.objectTypes[i]['menuItems'];
3848 var nMainMenuItems = aMainMenuItems.length;
3850 for(var j = 0; j < nMainMenuItems; j++) {
3851 oMenuItem = new YAHOO.widget.ContextMenuItem(aMainMenuItems[j].text, { helptext: aMainMenuItems[j].helptext });
3852 oMenuItem.clickEvent.subscribe(SUGAR.contextMenu.onContextMenuItemClick, oMenuItem, true);
3853 oContextMenu.addItem(oMenuItem);
3855 // Add a "move" event handler to the context menu
3856 oContextMenu.moveEvent.subscribe(SUGAR.contextMenu.onContextMenuMove, oContextMenu, true);
3857 // Add a "keydown" event handler to the context menu
3858 oContextMenu.keyDownEvent.subscribe(SUGAR.contextMenu.onContextMenuItemClick, oContextMenu, true);
3859 // Render the context menu
3860 oContextMenu.render(document.body);
3866 SUGAR.contextMenu.actions = function() {
3869 * redirects to a new note with the clicked on object as the target
3871 createNote: function(itemClicked, metaData) {
3872 loc = 'index.php?module=Notes&action=EditView';
3873 for(i in metaData) {
3874 if(i == 'notes_parent_type') loc += '&parent_type=' + metaData[i];
3875 else if(i != 'module' && i != 'parent_type') loc += '&' + i + '=' + metaData[i];
3877 document.location = loc;
3880 * redirects to a new note with the clicked on object as the target
3882 scheduleMeeting: function(itemClicked, metaData) {
3883 loc = 'index.php?module=Meetings&action=EditView';
3884 for(i in metaData) {
3885 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3887 document.location = loc;
3890 * redirects to a new note with the clicked on object as the target
3892 scheduleCall: function(itemClicked, metaData) {
3893 loc = 'index.php?module=Calls&action=EditView';
3894 for(i in metaData) {
3895 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3897 document.location = loc;
3900 * redirects to a new contact with the clicked on object as the target
3902 createContact: function(itemClicked, metaData) {
3903 loc = 'index.php?module=Contacts&action=EditView';
3904 for(i in metaData) {
3905 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3907 document.location = loc;
3910 * redirects to a new task with the clicked on object as the target
3912 createTask: function(itemClicked, metaData) {
3913 loc = 'index.php?module=Tasks&action=EditView';
3914 for(i in metaData) {
3915 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3917 document.location = loc;
3920 * redirects to a new opportunity with the clicked on object as the target
3922 createOpportunity: function(itemClicked, metaData) {
3923 loc = 'index.php?module=Opportunities&action=EditView';
3924 for(i in metaData) {
3925 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3927 document.location = loc;
3930 * redirects to a new opportunity with the clicked on object as the target
3932 createCase: function(itemClicked, metaData) {
3933 loc = 'index.php?module=Cases&action=EditView';
3934 for(i in metaData) {
3935 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3937 document.location = loc;
3940 * handles add to favorites menu selection
3942 addToFavorites: function(itemClicked, metaData) {
3943 success = function(data) {
3945 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});
3950 //if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.contextMenu.init);
3952 // initially from popup_parent_helper.js
3953 var popup_request_data;
3956 function get_popup_request_data()
3958 return YAHOO.lang.JSON.stringify(window.document.popup_request_data);
3961 function get_close_popup()
3963 return window.document.close_popup;
3966 function open_popup(module_name, width, height, initial_filter, close_popup, hide_clear_button, popup_request_data, popup_mode, create, metadata)
3968 if (typeof(popupCount) == "undefined" || popupCount == 0)
3971 // set the variables that the popup will pull from
3972 window.document.popup_request_data = popup_request_data;
3973 window.document.close_popup = close_popup;
3975 //globally changing width and height of standard pop up window from 600 x 400 to 800 x 800
3976 width = (width == 600) ? 800 : width;
3977 height = (height == 400) ? 800 : height;
3981 + 'module=' + module_name
3984 if (initial_filter != '') {
3985 URL += '&query=true' + initial_filter;
3986 // Bug 41891 - Popup Window Name
3987 popupName = initial_filter.replace(/[^a-z_0-9]+/ig, '_');
3988 windowName = module_name + '_popup_window' + popupName;
3990 windowName = module_name + '_popup_window' + popupCount;
3994 if (hide_clear_button) {
3995 URL += '&hide_clear_button=true';
3998 windowFeatures = 'width=' + width
3999 + ',height=' + height
4000 + ',resizable=1,scrollbars=1';
4002 if (popup_mode == '' && popup_mode == 'undefined') {
4003 popup_mode='single';
4005 URL+='&mode='+popup_mode;
4006 if (create == '' && create == 'undefined') {
4009 URL+='&create='+create;
4011 if (metadata != '' && metadata != 'undefined') {
4012 URL+='&metadata='+metadata;
4015 win = SUGAR.util.openWindow(URL, windowName, windowFeatures);
4019 // put the focus on the popup if the browser supports the focus() method
4023 win.popupCount = popupCount;
4029 * The reply data must be a JSON array structured with the following information:
4030 * 1) form name to populate
4031 * 2) associative array of input names to values for populating the form
4033 var from_popup_return = false;
4035 function set_return_basic(popup_reply_data,filter)
4037 var form_name = popup_reply_data.form_name;
4038 var name_to_value_array = popup_reply_data.name_to_value_array;
4039 for (var the_key in name_to_value_array)
4041 if(the_key == 'toJSON')
4045 else if(the_key.match(filter))
4047 var displayValue=name_to_value_array[the_key].replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');;
4048 // begin andopes change: support for enum fields (SELECT)
4049 if(window.document.forms[form_name] && window.document.forms[form_name].elements[the_key]) {
4050 if(window.document.forms[form_name].elements[the_key].tagName == 'SELECT') {
4051 var selectField = window.document.forms[form_name].elements[the_key];
4052 for(var i = 0; i < selectField.options.length; i++) {
4053 if(selectField.options[i].text == displayValue) {
4054 selectField.options[i].selected = true;
4055 SUGAR.util.callOnChangeListers(selectField);
4060 window.document.forms[form_name].elements[the_key].value = displayValue;
4061 SUGAR.util.callOnChangeListers(window.document.forms[form_name].elements[the_key]);
4064 // end andopes change: support for enum fields (SELECT)
4069 function set_return(popup_reply_data)
4071 from_popup_return = true;
4072 var form_name = popup_reply_data.form_name;
4073 var name_to_value_array = popup_reply_data.name_to_value_array;
4074 if(typeof name_to_value_array != 'undefined' && name_to_value_array['account_id'])
4077 var label_data_str = '';
4078 var current_label_data_str = '';
4079 for (var the_key in name_to_value_array)
4081 if(the_key == 'toJSON')
4087 var displayValue=name_to_value_array[the_key].replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');
4088 if(window.document.forms[form_name] && document.getElementById(the_key+'_label') && !the_key.match(/account/)) {
4089 var data_label = document.getElementById(the_key+'_label').innerHTML.replace(/\n/gi,'').replace(/<\/?[^>]+(>|$)/g, "");
4090 label_str += data_label + ' \n';
4091 label_data_str += data_label + ' ' + displayValue + '\n';
4092 if(window.document.forms[form_name].elements[the_key]) {
4093 current_label_data_str += data_label + ' ' + window.document.forms[form_name].elements[the_key].value +'\n';
4098 if(label_data_str != label_str && current_label_data_str != label_str){
4099 if(confirm(SUGAR.language.get('app_strings', 'NTC_OVERWRITE_ADDRESS_PHONE_CONFIRM') + '\n\n' + label_data_str))
4101 set_return_basic(popup_reply_data,/\S/);
4103 set_return_basic(popup_reply_data,/account/);
4105 }else if(label_data_str != label_str && current_label_data_str == label_str){
4106 set_return_basic(popup_reply_data,/\S/);
4107 }else if(label_data_str == label_str){
4108 set_return_basic(popup_reply_data,/account/);
4111 set_return_basic(popup_reply_data,/\S/);
4115 function set_return_lead_conv(popup_reply_data) {
4116 set_return(popup_reply_data);
4117 if (document.getElementById('lead_conv_ac_op_sel') && typeof onBlurKeyUpHandler=='function') {
4118 onBlurKeyUpHandler();
4122 function set_return_and_save(popup_reply_data)
4124 var form_name = popup_reply_data.form_name;
4125 var name_to_value_array = popup_reply_data.name_to_value_array;
4127 for (var the_key in name_to_value_array)
4129 if(the_key == 'toJSON')
4135 window.document.forms[form_name].elements[the_key].value = name_to_value_array[the_key];
4139 window.document.forms[form_name].return_module.value = window.document.forms[form_name].module.value;
4140 window.document.forms[form_name].return_action.value = 'DetailView';
4141 window.document.forms[form_name].return_id.value = window.document.forms[form_name].record.value;
4142 window.document.forms[form_name].action.value = 'Save';
4143 window.document.forms[form_name].submit();
4147 * This is a helper function to construct the initial filter that can be
4148 * passed into the open_popup() function. It assumes that there is an
4149 * account_id and account_name field in the given form_name to use to
4150 * construct the intial filter string.
4152 function get_initial_filter_by_account(form_name)
4154 var account_id = window.document.forms[form_name].account_id.value;
4155 var account_name = escape(window.document.forms[form_name].account_name.value);
4156 var initial_filter = "&account_id=" + account_id + "&account_name=" + account_name;
4158 return initial_filter;
4160 // end code from popup_parent_helper.js
4162 // begin code for address copy
4164 * This is a function used by the Address widget that will fill
4165 * in the given array fields using the fromKey and toKey as a
4166 * prefix into the form objects HTML elements.
4168 * @param form The HTML form object to parse
4169 * @param fromKey The prefix of elements to copy from
4170 * @param toKey The prefix of elements to copy into
4171 * @return boolean true if successful, false otherwise
4173 function copyAddress(form, fromKey, toKey) {
4175 var elems = new Array("address_street", "address_city", "address_state", "address_postalcode", "address_country");
4176 var checkbox = document.getElementById(toKey + "_checkbox");
4178 if(typeof checkbox != "undefined") {
4179 if(!checkbox.checked) {
4181 t = toKey + "_" + elems[x];
4182 document.getElementById(t).removeAttribute('readonly');
4186 f = fromKey + "_" + elems[x];
4187 t = toKey + "_" + elems[x];
4189 document.getElementById(t).value = document.getElementById(f).value;
4190 document.getElementById(t).setAttribute('readonly', true);
4196 // end code for address copy
4199 * This function is used in Email Template Module.
4200 * It will check whether the template is used in Campaing->EmailMarketing.
4201 * If true, it will notify user.
4204 function check_deletable_EmailTemplate() {
4205 id = document.getElementsByName('record')[0].value;
4206 currentForm = document.getElementById('form');
4208 success:function(r) {
4209 if(r.responseText == 'true') {
4210 if(!confirm(SUGAR.language.get('app_strings','NTC_TEMPLATE_IS_USED'))) {
4214 if(!confirm(SUGAR.language.get('app_strings','NTC_DELETE_CONFIRMATION'))) {
4218 currentForm.return_module.value='EmailTemplates';
4219 currentForm.return_action.value='ListView';
4220 currentForm.action.value='Delete';
4221 currentForm.submit();
4224 url = "index.php?module=EmailTemplates&action=CheckDeletable&from=DetailView&to_pdf=1&record="+id;
4225 YAHOO.util.Connect.asyncRequest('POST',url, call_back,null);
4229 remove_upload_imagefile : function(field_name) {
4230 var field=document.getElementById('remove_imagefile_' + field_name);
4233 //enable the file upload button.
4234 var field=document.getElementById( field_name);
4235 field.style.display="";
4237 //hide the image and remove button.
4238 var field=document.getElementById('img_' + field_name);
4239 field.style.display="none";
4240 var field=document.getElementById('bt_remove_' + field_name);
4241 field.style.display="none";
4243 if(document.getElementById(field_name + '_duplicate')) {
4244 var field = document.getElementById(field_name + '_duplicate');
4249 confirm_imagefile : function(field_name) {
4250 var field=document.getElementById(field_name);
4251 var filename=field.value;
4252 var fileExtension = filename.substring(filename.lastIndexOf(".")+1);
4253 fileExtension = fileExtension.toLowerCase();
4254 if (fileExtension == "jpg" || fileExtension == "jpeg"
4255 || fileExtension == "gif" || fileExtension == "png" || fileExtension == "bmp"){
4260 alert(SUGAR.language.get('app_strings', 'LBL_UPLOAD_IMAGE_FILE_INVALID'));
4264 lightbox : function(image)
4266 if (typeof(SUGAR.image.lighboxWindow) == "undefined")
4267 SUGAR.image.lighboxWindow = new YAHOO.widget.SimpleDialog('sugarImageViewer', {
4270 id:'sugarMsgWindow',
4273 msg: "<img src='" + image + "'> </img>",
4276 SUGAR.image.lighboxWindow.setBody("<img src='" + image + "'> </img>");
4277 SUGAR.image.lighboxWindow.render(document.body);
4278 SUGAR.image.lighboxWindow.show();
4279 SUGAR.image.lighboxWindow.center()
4283 SUGAR.append(SUGAR.util, {
4284 isTouchScreen: function() {
4285 // first check if we have forced use of the touch enhanced interface
4286 if (Get_Cookie("touchscreen") == '1') {
4290 // next check if we should use the touch interface with our device
4291 if ((navigator.userAgent.match(/iPad/i) != null)) {
4298 isLoginPage: function(content) {
4299 //skip if this is packageManager screen
4300 if(SUGAR.util.isPackageManager()) {return false;}
4301 var loginPageStart = "<!DOCTYPE";
4302 if (content.substr(0, loginPageStart.length) == loginPageStart && content.indexOf("<html>") != -1 && content.indexOf("login_module") != -1) {
4303 window.location.href = window.location.protocol + window.location.pathname;
4308 isPackageManager: function(){
4309 if(typeof(document.the_form) !='undefined' && typeof(document.the_form.language_pack_escaped) !='undefined'){
4311 }else{return false;}
4314 ajaxCallInProgress: function(){
4316 //First check if we are in a popup.
4317 if (typeof (send_back) != "function"){
4318 //If the page content is blank, it means we are probably still waiting on something
4319 var c = document.getElementById("content");
4320 if (!c) return true;
4321 t = YAHOO.lang.trim(SUGAR.util.innerText(c));
4323 return SUGAR_callsInProgress != 0 || t == "";
4325 //Firefox doesn't support innerText (textContent includes script content)
4326 innerText : function(el) {
4327 if (el.tagName == "SCRIPT")
4329 if(typeof(el.innerText) == "string")
4330 return el.innerText;
4332 for (var i in el.childNodes){
4333 var c = el.childNodes[i];
4334 if (typeof(c) != "object")
4336 if (typeof(c.nodeName) == "string" && c.nodeName == "#text")
4339 t += SUGAR.util.innerText(c);
4344 callOnChangeListers: function(field){
4345 var listeners = YAHOO.util.Event.getListeners(field, 'change');
4346 if (listeners != null) {
4347 for (var i = 0; i < listeners.length; i++) {
4348 var l = listeners[i];
4349 l.fn.call(l.scope ? l.scope : this, l.obj);
4354 closeActivityPanel: {
4355 show:function(module,id,new_status,viewType,parentContainerId){
4356 if (SUGAR.util.closeActivityPanel.panel)
4357 SUGAR.util.closeActivityPanel.panel.destroy();
4358 var singleModule = SUGAR.language.get("app_list_strings", "moduleListSingular")[module];
4359 singleModule = typeof(singleModule != 'undefined') ? singleModule.toLowerCase() : '';
4360 var closeText = SUGAR.language.get("app_strings", "LBL_CLOSE_ACTIVITY_CONFIRM").replace("#module#",singleModule);
4361 SUGAR.util.closeActivityPanel.panel =
4362 new YAHOO.widget.SimpleDialog("closeActivityDialog",
4369 constraintoviewport: true,
4370 buttons: [ { text:SUGAR.language.get("app_strings", "LBL_EMAIL_OK"), handler:function(){
4371 if (SUGAR.util.closeActivityPanel.panel)
4372 SUGAR.util.closeActivityPanel.panel.hide();
4374 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_SAVING'));
4375 var args = "action=save&id=" + id + "&record=" + id + "&status=" + new_status + "&module=" + module;
4376 // 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
4377 // TODO: Take id out and regression test. Left id in for now to not create any other unexpected problems
4378 //var args = "action=save&id=" + id + "&status=" + new_status + "&module=" + module;
4382 // 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.
4383 // So instead, we reload from a timeout
4384 window.setTimeout("window.location.reload(true);",0);
4386 argument:{'parentContainerId':parentContainerId}
4389 YAHOO.util.Connect.asyncRequest('POST', 'index.php', callback, args);
4391 }, isDefault:true },
4392 { text:SUGAR.language.get("app_strings", "LBL_EMAIL_CANCEL"), handler:function(){SUGAR.util.closeActivityPanel.panel.hide(); }} ]
4395 SUGAR.util.closeActivityPanel.panel.setHeader(SUGAR.language.get("app_strings", "LBL_CLOSE_ACTIVITY_HEADER"));
4396 SUGAR.util.closeActivityPanel.panel.render(document.body);
4397 SUGAR.util.closeActivityPanel.panel.show();
4401 setEmailPasswordDisplay: function(id, exists) {
4402 link = document.getElementById(id+'_link');
4403 pwd = document.getElementById(id);
4404 if(!pwd || !link) return;
4406 pwd.style.display = 'none';
4407 link.style.display = '';
4409 pwd.style.display = '';
4410 link.style.display = 'none';
4414 setEmailPasswordEdit: function(id) {
4415 link = document.getElementById(id+'_link');
4416 pwd = document.getElementById(id);
4417 if(!pwd || !link) return;
4418 pwd.style.display = '';
4419 link.style.display = 'none';
4423 * Compares a filename with a supplied array of allowed file extensions.
4424 * @param fileName string
4425 * @param allowedTypes array of allowed file extensions
4428 validateFileExt: function(fileName, allowedTypes) {
4429 var ext = fileName.split('.').pop().toLowerCase();
4431 for (var i = allowedTypes.length; i > 0; i--) {
4432 if (ext === allowedTypes[i]) {
4440 arrayIndexOf: function(arr, val, start) {
4441 if (typeof arr.indexOf == "function")
4442 return arr.indexOf(val, start);
4443 for (var i = (start || 0), j = arr.length; i < j; i++) {
4444 if (arr[i] === val) {
4452 SUGAR.clearRelateField = function(form, name, id)
4454 if (typeof form[name] == "object"){
4455 form[name].value = '';
4456 SUGAR.util.callOnChangeListers(form[name]);
4459 if (typeof form[id] == "object"){
4460 form[id].value = '';
4461 SUGAR.util.callOnChangeListers(form[id]);
4464 if(typeof(SUGAR.AutoComplete) == 'undefined') SUGAR.AutoComplete = {};
4466 SUGAR.AutoComplete.getOptionsArray = function(options_index){
4467 var return_arr = [];
4469 var opts = SUGAR.language.get('app_list_strings', options_index);
4470 if(typeof(opts) != 'undefined'){
4472 // Since we are using auto complete, we excluse blank dropdown entries since they can just leave it blank
4473 if(key != '' && opts[key] != ''){
4476 item['text'] = opts[key];
4477 return_arr.push(item);
4484 if(typeof(SUGAR.MultiEnumAutoComplete) == 'undefined') SUGAR.MultiEnumAutoComplete = {};
4486 SUGAR.MultiEnumAutoComplete.getMultiSelectKeysFromValues = function(options_index, val_string){
4487 var opts = SUGAR.language.get('app_list_strings', options_index);
4488 var selected_values = val_string.split(", ");
4489 // YUI AutoComplete adds a blank. We remove it automatically here
4490 if(selected_values.length > 0 && selected_values.indexOf('') == selected_values.length - 1){
4491 selected_values.pop();
4493 var final_arr = new Array();
4494 for(idx in selected_values){
4496 if(selected_values[idx] == opts[o_idx]){
4497 final_arr.push(o_idx);
4504 SUGAR.MultiEnumAutoComplete.getMultiSelectValuesFromKeys = function(options_index, val_string){
4505 var opts = SUGAR.language.get('app_list_strings', options_index);
4506 val_string=val_string.replace(/^\^/,'').replace(/\^$/,'') //fixes bug where string starts or ends with ^
4507 var selected_values = val_string.split("^,^");
4509 // YUI AutoComplete adds a blank. We remove it automatically here
4510 if(selected_values.length > 0 && selected_values.indexOf('') == selected_values.length - 1){
4511 selected_values.pop();
4514 var final_arr = new Array();
4515 for(idx in selected_values){
4517 if(selected_values[idx] == o_idx){
4518 final_arr.push(opts[o_idx]);