1 /*********************************************************************************
2 * SugarCRM Community Edition is a customer relationship management program developed by
3 * SugarCRM, Inc. Copyright (C) 2004-2012 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");
75 SUGAR.namespace("tour");
78 * Namespace for Homepage
80 SUGAR.namespace("sugarHome");
83 * Namespace for Subpanel Utils
85 SUGAR.namespace("subpanelUtils");
90 SUGAR.namespace("ajaxStatusClass");
95 SUGAR.namespace("tabChooser");
98 * General namespace for Sugar utils
100 SUGAR.namespace("utils");
101 SUGAR.namespace("savedViews");
106 SUGAR.namespace("dashlets");
107 SUGAR.namespace("unifiedSearchAdvanced");
109 SUGAR.namespace("searchForm");
110 SUGAR.namespace("language");
111 SUGAR.namespace("Studio");
112 SUGAR.namespace("contextMenu");
113 SUGAR.namespace("config");
117 var requiredIndex = 2;
122 var altMsgIndex = 15;
123 var compareToIndex = 7;
125 var operatorIndex = 13;
126 var callbackIndex = 16;
128 var validate = new Array();
130 var requiredTxt = 'Missing Required Field:';
131 var invalidTxt = 'Invalid Value:';
132 var secondsSinceLoad = 0;
133 var inputsWithErrors = new Array();
134 var tabsWithErrors = new Array();
135 var lastSubmitTime = 0;
136 var alertList = new Array();
137 var oldStartsWith = '';
142 * As of Sugar version 6.2.3 (MSIE Version 9) this function is deprecated. The preferred method is to use the
143 * user agent check supplied by YUI to check for IE:
145 * for checking if a browser is IE in general : if(YAHOO.env.ua.ie) {...}
147 * or for checking specific versions: if (YAHOO.env.ua.ie >= 5.5 && YAHOO.env.ua.ie < 9) {...}
150 function isSupportedIE() {
151 var userAgent = navigator.userAgent.toLowerCase() ;
153 // IE Check supports ActiveX controls
154 if (userAgent.indexOf("msie") != -1 && userAgent.indexOf("mac") == -1 && userAgent.indexOf("opera") == -1) {
155 var version = navigator.appVersion.match(/MSIE (.\..)/)[1] ;
156 if(version >= 5.5 && version < 10) {
164 SUGAR.isIE = isSupportedIE();
165 var isSafari = (navigator.userAgent.toLowerCase().indexOf('safari')!=-1);
167 // escapes regular expression characters
168 RegExp.escape = function(text) { // http://simon.incutio.com/archive/2006/01/20/escape
169 if (!arguments.callee.sRE) {
170 var specials = ['/', '.', '*', '+', '?', '|','(', ')', '[', ']', '{', '}', '\\'];
171 arguments.callee.sRE = new RegExp('(\\' + specials.join('|\\') + ')', 'g');
173 return text.replace(arguments.callee.sRE, '\\$1');
176 function addAlert(type, name,subtitle, description,time, redirect) {
177 var addIndex = alertList.length;
178 alertList[addIndex]= new Array();
179 alertList[addIndex]['name'] = name;
180 alertList[addIndex]['type'] = type;
181 alertList[addIndex]['subtitle'] = subtitle;
182 alertList[addIndex]['description'] = replaceHTMLChars(description.replace(/<br>/gi, "\n"));
183 alertList[addIndex]['time'] = time;
184 alertList[addIndex]['done'] = 0;
185 alertList[addIndex]['redirect'] = redirect;
187 function checkAlerts() {
188 secondsSinceLoad += 1;
191 for(mj = 0 ; mj < alertList.length; mj++) {
192 if(alertList[mj]['done'] == 0) {
193 if(alertList[mj]['time'] < secondsSinceLoad && alertList[mj]['time'] > -1 ) {
194 alertmsg = alertList[mj]['type'] + ":" + alertList[mj]['name'] + "\n" +alertList[mj]['subtitle']+ "\n"+ alertList[mj]['description'] + "\n\n";
195 alertList[mj]['done'] = 1;
196 if(alertList[mj]['redirect'] == '') {
199 else if(confirm(alertmsg)) {
200 window.location = alertList[mj]['redirect'];
206 setTimeout("checkAlerts()", 1000);
209 function toggleDisplay(id) {
210 if(this.document.getElementById(id).style.display == 'none') {
211 this.document.getElementById(id).style.display = '';
212 if(this.document.getElementById(id+"link") != undefined) {
213 this.document.getElementById(id+"link").style.display = 'none';
215 if(this.document.getElementById(id+"_anchor") != undefined)
216 this.document.getElementById(id+"_anchor").innerHTML='[ - ]';
219 this.document.getElementById(id).style.display = 'none';
220 if(this.document.getElementById(id+"link") != undefined) {
221 this.document.getElementById(id+"link").style.display = '';
223 if(this.document.getElementById(id+"_anchor") != undefined)
224 this.document.getElementById(id+"_anchor").innerHTML='[+]';
228 function checkAll(form, field, value) {
229 for (i = 0; i < form.elements.length; i++) {
230 if(form.elements[i].name == field)
231 form.elements[i].checked = value;
235 function replaceAll(text, src, rep) {
236 offset = text.toLowerCase().indexOf(src.toLowerCase());
237 while(offset != -1) {
238 text = text.substring(0, offset) + rep + text.substring(offset + src.length ,text.length);
239 offset = text.indexOf( src, offset + rep.length + 1);
244 function addForm(formname) {
245 validate[formname] = new Array();
248 function addToValidate(formname, name, type, required, msg) {
249 if(typeof validate[formname] == 'undefined') {
252 validate[formname][validate[formname].length] = new Array(name, type,required, msg);
255 // Bug #47961 Callback validator definition
256 function addToValidateCallback(formname, name, type, required, msg, callback)
258 addToValidate(formname, name, type, required, msg);
259 var iIndex = validate[formname].length -1;
260 validate[formname][iIndex][jstypeIndex] = 'callback';
261 validate[formname][iIndex][callbackIndex] = callback;
264 function addToValidateRange(formname, name, type,required, msg,min,max) {
265 addToValidate(formname, name, type,required, msg);
266 validate[formname][validate[formname].length - 1][jstypeIndex] = 'range';
267 validate[formname][validate[formname].length - 1][minIndex] = min;
268 validate[formname][validate[formname].length - 1][maxIndex] = max;
271 function addToValidateIsValidDate(formname, name, type, required, msg) {
272 addToValidate(formname, name, type, required, msg);
273 validate[formname][validate[formname].length - 1][jstypeIndex] = 'date';
276 function addToValidateIsValidTime(formname, name, type, required, msg) {
277 addToValidate(formname, name, type, required, msg);
278 validate[formname][validate[formname].length - 1][jstypeIndex] = 'time';
281 function addToValidateDateBefore(formname, name, type, required, msg, compareTo) {
282 addToValidate(formname, name, type,required, msg);
283 validate[formname][validate[formname].length - 1][jstypeIndex] = 'isbefore';
284 validate[formname][validate[formname].length - 1][compareToIndex] = compareTo;
287 function addToValidateDateBeforeAllowBlank(formname, name, type, required, msg, compareTo, allowBlank) {
288 addToValidate(formname, name, type,required, msg);
289 validate[formname][validate[formname].length - 1][jstypeIndex] = 'isbefore';
290 validate[formname][validate[formname].length - 1][compareToIndex] = compareTo;
291 validate[formname][validate[formname].length - 1][allowblank] = allowBlank;
294 function addToValidateBinaryDependency(formname, name, type, required, msg, compareTo) {
295 addToValidate(formname, name, type, required, msg);
296 validate[formname][validate[formname].length - 1][jstypeIndex] = 'binarydep';
297 validate[formname][validate[formname].length - 1][compareToIndex] = compareTo;
300 function addToValidateComparison(formname, name, type, required, msg, compareTo) {
301 addToValidate(formname, name, type, required, msg);
302 validate[formname][validate[formname].length - 1][jstypeIndex] = 'comparison';
303 validate[formname][validate[formname].length - 1][compareToIndex] = compareTo;
306 function addToValidateIsInArray(formname, name, type, required, msg, arr, operator) {
307 addToValidate(formname, name, type, required, msg);
308 validate[formname][validate[formname].length - 1][jstypeIndex] = 'in_array';
309 validate[formname][validate[formname].length - 1][arrIndex] = arr;
310 validate[formname][validate[formname].length - 1][operatorIndex] = operator;
313 function addToValidateVerified(formname, name, type, required, msg, arr, operator) {
314 addToValidate(formname, name, type, required, msg);
315 validate[formname][validate[formname].length - 1][jstypeIndex] = 'verified';
318 function addToValidateLessThan(formname, name, type, required, msg, max, max_field_msg) {
319 addToValidate(formname, name, type, required, msg);
320 validate[formname][validate[formname].length - 1][jstypeIndex] = 'less';
321 validate[formname][validate[formname].length - 1][maxIndex] = max;
322 validate[formname][validate[formname].length - 1][altMsgIndex] = max_field_msg;
325 function addToValidateMoreThan(formname, name, type, required, msg, min) {
326 addToValidate(formname, name, type, required, msg);
327 validate[formname][validate[formname].length - 1][jstypeIndex] = 'more';
328 validate[formname][validate[formname].length - 1][minIndex] = min;
332 function removeFromValidate(formname, name) {
333 for(i = 0; i < validate[formname].length; i++)
335 if(validate[formname][i][nameIndex] == name)
337 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
341 function checkValidate(formname, name) {
342 if(validate[formname]){
343 for(i = 0; i < validate[formname].length; i++){
344 if(validate[formname][i][nameIndex] == name){
351 var formsWithFieldLogic=null;
352 var formWithPrecision =null;
353 function addToValidateFieldLogic(formId,minFieldId, maxFieldId, defaultFieldId, lenFieldId,type,msg){
354 this.formId = document.getElementById(formId);
355 this.min=document.getElementById(minFieldId);
356 this.max= document.getElementById(maxFieldId);
357 this._default= document.getElementById(defaultFieldId);
358 this.len = document.getElementById(lenFieldId);
362 //@params: formid- Dom id of the form containing the precision and float fields
363 // valudId- Dom id of the field containing a float whose precision is to be checked.
364 // precisionId- Dom id of the field containing precision value.
365 function addToValidatePrecision(formId, valueId, precisionId){
366 this.form = document.getElementById(formId);
367 this.float = document.getElementById(valueId);
368 this.precision = document.getElementById(precisionId);
371 //function checkLength(value, referenceValue){
375 function isValidPrecision(value, precision){
376 value = trim(value.toString());
382 if( (precision == "0") ){
383 if (value.indexOf(dec_sep)== -1){
390 if(value.charAt(value.length-precision-1) == num_grp_sep){
391 if(value.substr(value.indexOf(dec_sep), 1)==dec_sep){
396 var actualPrecision = value.substr(value.indexOf(dec_sep)+1, value.length).length;
397 return actualPrecision == precision;
399 function toDecimal(original, precision) {
400 precision = (precision == null) ? 2 : precision;
401 num = Math.pow(10, precision);
402 temp = Math.round(original*num)/num;
403 if((temp * 100) % 100 == 0)
405 if((temp * 10) % 10 == 0)
410 function isInteger(s) {
411 if(typeof num_grp_sep != 'undefined' && typeof dec_sep != 'undefined')
413 s = unformatNumberNoParse(s, num_grp_sep, dec_sep).toString();
415 return /^[+-]?[0-9]*$/.test(s) ;
418 function isDecimal(s) {
419 if (typeof s == "string" && s == "") // bug# 46530, this is required in order to
420 return true; // not check empty decimal fields
422 if(typeof num_grp_sep != 'undefined' && typeof dec_sep != 'undefined')
424 s = unformatNumberNoParse(s, num_grp_sep, dec_sep).toString();
426 return /^[+-]?[0-9]*\.?[0-9]*$/.test(s) ;
429 function isNumeric(s) {
433 if (typeof date_reg_positions != "object") var date_reg_positions = {'Y': 1,'m': 2,'d': 3};
434 if (typeof date_reg_format != "string") var date_reg_format = '([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})';
436 function isDate(dtStr) {
438 if(dtStr.length== 0) {
442 // Check that we have numbers
443 myregexp = new RegExp(date_reg_format)
444 if(!myregexp.test(dtStr))
451 var dateParts = dtStr.match(date_reg_format);
452 for(key in date_reg_positions) {
453 index = date_reg_positions[key];
455 m = dateParts[index];
456 } else if(key == 'd') {
457 d = dateParts[index];
459 y = dateParts[index];
463 // Check that date is real
464 var dd = new Date(y,m,0);
465 // reject negative years
468 // reject month less than 1 and greater than 12
471 // reject days less than 1 or days not in month (e.g. February 30th)
472 if (d < 1 || d > dd.getDate())
477 function getDateObject(dtStr) {
478 if(dtStr.length== 0) {
482 myregexp = new RegExp(date_reg_format)
484 if(myregexp.exec(dtStr)) var dt = myregexp.exec(dtStr)
487 var yr = dt[date_reg_positions['Y']];
488 var mh = dt[date_reg_positions['m']];
489 var dy = dt[date_reg_positions['d']];
490 var dtar = dtStr.split(' ');
491 if(typeof(dtar[1])!='undefined' && isTime(dtar[1])) {//if it is a timedate, we should make date1 to have time value
492 var t1 = dtar[1].replace(/am/i,' AM');
493 var t1 = t1.replace(/pm/i,' PM');
494 //bug #37977: where time format 23.00 causes java script error
495 t1=t1.replace(/\./, ':');
496 date1 = new Date(Date.parse(mh+'/'+dy+ '/'+yr+' '+t1));
500 var date1 = new Date();
501 date1.setFullYear(yr); // xxxx 4 char year
502 date1.setMonth(mh-1); // 0-11 Bug 4048: javascript Date obj months are 0-index
503 date1.setDate(dy); // 1-31
508 function isBefore(value1, value2) {
509 var d1 = getDateObject(value1);
510 var d2 = getDateObject(value2);
511 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.
517 function isValidEmail(emailStr) {
519 if(emailStr.length== 0) {
522 // cn: bug 7128, a period at the end of the string mangles checks. (switched to accept spaces and delimiters)
523 var lastChar = emailStr.charAt(emailStr.length - 1);
524 if(!lastChar.match(/[^\.]/i)) {
527 //bug 40068, According to rules in page 6 of http://www.apps.ietf.org/rfc/rfc3696.html#sec-3,
528 //first character of local part of an email address
529 //should not be a period i.e. '.'
531 var firstLocalChar=emailStr.charAt(0);
532 if(firstLocalChar.match(/\./)){
536 //bug 40068, According to rules in page 6 of http://www.apps.ietf.org/rfc/rfc3696.html#sec-3,
537 //last character of local part of an email address
538 //should not be a period i.e. '.'
540 var pos=emailStr.lastIndexOf("@");
541 var localPart = emailStr.substr(0, pos);
542 var lastLocalChar=localPart.charAt(localPart.length - 1);
543 if(lastLocalChar.match(/\./)){
550 while ((results = reg.exec(emailStr)) != null) {
551 var original = results[0];
552 parsedResult = results[0].replace(';', '::;::');
553 emailStr = emailStr.replace (original, parsedResult);
557 while ((results = reg.exec(emailStr)) != null) {
558 var original = results[0];
559 //Check if we were using ; as a delimiter. If so, skip the commas
560 if(original.indexOf("::;::") == -1) {
561 var parsedResult = results[0].replace(',', '::;::');
562 emailStr = emailStr.replace (original, parsedResult);
566 // mfh: bug 15010 - more practical implementation of RFC 2822 from http://www.regular-expressions.info/email.html, modifed to accept CAPITAL LETTERS
567 //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))
570 //bug 40068, According to rules in page 6 of http://www.apps.ietf.org/rfc/rfc3696.html#sec-3,
571 //allowed special characters ! # $ % & ' * + - / = ? ^ _ ` . { | } ~ in local part
572 var emailArr = emailStr.split(/::;::/);
573 for (var i = 0; i < emailArr.length; i++) {
574 var emailAddress = emailArr[i];
575 if (trim(emailAddress) != '') {
576 if(!/^\s*[\w.%+\-&'#!\$\*=\?\^_`\{\}~\/]+@([A-Z0-9-]+\.)*[A-Z0-9-]+\.[\w-]{2,}\s*$/i.test(emailAddress) &&
577 !/^.*<[A-Z0-9._%+\-&'#!\$\*=\?\^_`\{\}~]+?@([A-Z0-9-]+\.)*[A-Z0-9-]+\.[\w-]{2,}>\s*$/i.test(emailAddress)) {
586 function isValidPhone(phoneStr) {
587 if(phoneStr.length== 0) {
590 if(!/^[0-9\-\(\)\s]+$/.test(phoneStr))
594 function isFloat(floatStr) {
595 if(floatStr.length== 0) {
598 if(!(typeof(num_grp_sep)=='undefined' || typeof(dec_sep)=='undefined')) {
599 floatStr = unformatNumberNoParse(floatStr, num_grp_sep, dec_sep).toString();
602 return /^(-)?[0-9\.]+$/.test(floatStr);
604 function isDBName(str) {
609 // must start with a letter
610 if(!/^[a-zA-Z][a-zA-Z\_0-9]*$/.test(str))
614 var time_reg_format = "[0-9]{1,2}\:[0-9]{2}";
615 function isTime(timeStr) {
616 var time_reg_format = "[0-9]{1,2}\:[0-9]{2}";
617 time_reg_format = time_reg_format.replace('([ap]m)', '');
618 time_reg_format = time_reg_format.replace('([AP]M)', '');
619 if(timeStr.length== 0){
622 //we now support multiple time formats
623 myregexp = new RegExp(time_reg_format)
624 if(!myregexp.test(timeStr))
630 function inRange(value, min, max) {
631 if (typeof num_grp_sep != 'undefined' && typeof dec_sep != 'undefined')
632 value = unformatNumberNoParse(value, num_grp_sep, dec_sep).toString();
633 return value >= min && value <= max;
636 function bothExist(item1, item2) {
637 if(typeof item1 == 'undefined') { return false; }
638 if(typeof item2 == 'undefined') { return false; }
639 if((item1 == '' && item2 != '') || (item1 != '' && item2 == '') ) { return false; }
643 trim = YAHOO.lang.trim;
646 function check_form(formname) {
647 if (typeof(siw) != 'undefined' && siw
648 && typeof(siw.selectingSomething) != 'undefined' && siw.selectingSomething)
650 return validate_form(formname, '');
653 function add_error_style(formname, input, txt, flash) {
654 var raiseFlag = false;
655 if (typeof flash == "undefined")
658 inputHandle = typeof input == "object" ? input : document.forms[formname][input];
659 style = get_current_bgcolor(inputHandle);
661 // strip off the colon at the end of the warning strings
662 if ( txt.substring(txt.length-1) == ':' )
663 txt = txt.substring(0,txt.length-1)
665 // Bug 28249 - To help avoid duplicate messages for an element, strip off extra messages and
666 // match on the field name itself
667 requiredTxt = SUGAR.language.get('app_strings', 'ERR_MISSING_REQUIRED_FIELDS');
668 invalidTxt = SUGAR.language.get('app_strings', 'ERR_INVALID_VALUE');
669 nomatchTxt = SUGAR.language.get('app_strings', 'ERR_SQS_NO_MATCH_FIELD');
670 matchTxt = txt.replace(requiredTxt,'').replace(invalidTxt,'').replace(nomatchTxt,'');
672 YUI().use('node', function (Y) {
673 Y.one(inputHandle).get('parentNode').get('children').each(function(node, index, nodeList){
674 if(node.hasClass('validation-message') && node.get('text').search(matchTxt)){
681 errorTextNode = document.createElement('div');
682 errorTextNode.className = 'required validation-message';
683 errorTextNode.innerHTML = txt;
684 if ( inputHandle.parentNode.className.indexOf('x-form-field-wrap') != -1 ) {
685 inputHandle.parentNode.parentNode.appendChild(errorTextNode);
688 inputHandle.parentNode.appendChild(errorTextNode);
691 inputHandle.style.backgroundColor = "#FF0000";
692 inputsWithErrors.push(inputHandle);
696 // We only need to setup the flashy-flashy on the first entry, it loops through all fields automatically
697 if ( inputsWithErrors.length == 1 ) {
698 for(var wp = 1; wp <= 10; wp++) {
699 window.setTimeout('fade_error_style(style, '+wp*10+')',1000+(wp*50));
702 if(typeof (window[formname + "_tabs"]) != "undefined") {
703 var tabView = window[formname + "_tabs"];
704 var parentDiv = YAHOO.util.Dom.getAncestorByTagName(inputHandle, "div");
706 var tabs = tabView.get("tabs");
707 for (var i in tabs) {
708 if (tabs[i].get("contentEl") == parentDiv
709 || YAHOO.util.Dom.isAncestor(tabs[i].get("contentEl"), inputHandle))
711 tabs[i].get("labelEl").style.color = "red";
712 if ( inputsWithErrors.length == 1 )
713 tabView.selectTab(i);
718 window.setTimeout("inputsWithErrors[" + (inputsWithErrors.length - 1) + "].style.backgroundColor = '';", 2000);
722 // Catch errors here so we don't allow an incomplete record through the javascript validation
728 * removes all error messages for the current form
730 function clear_all_errors() {
731 for(var wp = 0; wp < inputsWithErrors.length; wp++) {
732 if(typeof(inputsWithErrors[wp]) !='undefined' && typeof inputsWithErrors[wp].parentNode != 'undefined' && inputsWithErrors[wp].parentNode != null) {
733 if ( inputsWithErrors[wp].parentNode.className.indexOf('x-form-field-wrap') != -1 )
735 inputsWithErrors[wp].parentNode.parentNode.removeChild(inputsWithErrors[wp].parentNode.parentNode.lastChild);
739 inputsWithErrors[wp].parentNode.removeChild(inputsWithErrors[wp].parentNode.lastChild);
743 if (inputsWithErrors.length == 0) return;
745 if ( YAHOO.util.Dom.getAncestorByTagName(inputsWithErrors[0], "form") ) {
746 var formname = YAHOO.util.Dom.getAncestorByTagName(inputsWithErrors[0], "form").getAttribute("name");
747 if(typeof (window[formname + "_tabs"]) != "undefined") {
748 var tabView = window[formname + "_tabs"];
750 var tabs = tabView.get("tabs");
751 for (var i in tabs) {
752 if (typeof tabs[i] == "object")
753 tabs[i].get("labelEl").style.color = "";
757 inputsWithErrors = new Array();
761 function get_current_bgcolor(input) {
762 if(input.currentStyle) {// ie
763 style = input.currentStyle.backgroundColor;
764 return style.substring(1,7);
768 styleRGB = document.defaultView.getComputedStyle(input, '').getPropertyValue("background-color");
769 comma = styleRGB.indexOf(',');
770 style += dec2hex(styleRGB.substring(4, comma));
771 commaPrevious = comma;
772 comma = styleRGB.indexOf(',', commaPrevious+1);
773 style += dec2hex(styleRGB.substring(commaPrevious+2, comma));
774 style += dec2hex(styleRGB.substring(comma+2, styleRGB.lastIndexOf(')')));
779 function hex2dec(hex){return(parseInt(hex,16));}
780 var hexDigit=new Array("0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F");
781 function dec2hex(dec){return(hexDigit[dec>>4]+hexDigit[dec&15]);}
783 function fade_error_style(normalStyle, percent) {
784 errorStyle = 'c60c30';
785 var r1 = hex2dec(errorStyle.slice(0,2));
786 var g1 = hex2dec(errorStyle.slice(2,4));
787 var b1 = hex2dec(errorStyle.slice(4,6));
789 var r2 = hex2dec(normalStyle.slice(0,2));
790 var g2 = hex2dec(normalStyle.slice(2,4));
791 var b2 = hex2dec(normalStyle.slice(4,6));
794 var pc = percent / 100;
796 r= Math.floor(r1+(pc*(r2-r1)) + .5);
797 g= Math.floor(g1+(pc*(g2-g1)) + .5);
798 b= Math.floor(b1+(pc*(b2-b1)) + .5);
800 for(var wp = 0; wp < inputsWithErrors.length; wp++) {
801 inputsWithErrors[wp].style.backgroundColor = "#" + dec2hex(r) + dec2hex(g) + dec2hex(b);
805 function isFieldTypeExceptFromEmptyCheck(fieldType)
808 var exemptList = ['bool','file'];
809 for(var i=0;i<exemptList.length;i++)
811 if(fieldType == exemptList[i])
816 function validate_form(formname, startsWith){
817 requiredTxt = SUGAR.language.get('app_strings', 'ERR_MISSING_REQUIRED_FIELDS');
818 invalidTxt = SUGAR.language.get('app_strings', 'ERR_INVALID_VALUE');
820 if ( typeof (formname) == 'undefined')
824 if ( typeof (validate[formname]) == 'undefined')
826 disableOnUnloadEditView(document.forms[formname]);
830 var form = document.forms[formname];
833 var _date = new Date();
834 if(_date.getTime() < (lastSubmitTime + 2000) && startsWith == oldStartsWith) { // ignore submits for the next 2 seconds
837 lastSubmitTime = _date.getTime();
838 oldStartsWith = startsWith;
840 clear_all_errors(); // remove previous error messages
842 inputsWithErrors = new Array();
843 for(var i = 0; i < validate[formname].length; i++){
844 if(validate[formname][i][nameIndex].indexOf(startsWith) == 0){
845 if(typeof form[validate[formname][i][nameIndex]] != 'undefined' && typeof form[validate[formname][i][nameIndex]].value != 'undefined'){
848 //If a field is not required and it is blank or is binarydependant, skip validation.
849 //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
850 if(!validate[formname][i][requiredIndex] && trim(form[validate[formname][i][nameIndex]].value) == '' && (typeof(validate[formname][i][jstypeIndex]) != 'undefined' && validate[formname][i][jstypeIndex] != 'binarydep'))
855 if(validate[formname][i][requiredIndex]
856 && !isFieldTypeExceptFromEmptyCheck(validate[formname][i][typeIndex])
858 if(typeof form[validate[formname][i][nameIndex]] == 'undefined' || trim(form[validate[formname][i][nameIndex]].value) == ""){
859 add_error_style(formname, validate[formname][i][nameIndex], requiredTxt +' ' + validate[formname][i][msgIndex]);
864 switch(validate[formname][i][typeIndex]){
866 if(!isValidEmail(trim(form[validate[formname][i][nameIndex]].value))){
868 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
872 if( !isTime(trim(form[validate[formname][i][nameIndex]].value))){
874 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
876 case 'date': if(!isDate(trim(form[validate[formname][i][nameIndex]].value))){
878 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
883 if(!isDBName(trim(form[validate[formname][i][nameIndex]].value))){
885 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
888 // Bug #49614 : Check value without trimming before
890 if(!isDBName(form[validate[formname][i][nameIndex]].value)){
892 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
898 var file_input = form[validate[formname][i][nameIndex] + '_file'];
899 if( file_input && validate[formname][i][requiredIndex] && trim(file_input.value) == "" && !file_input.disabled ) {
901 add_error_style(formname, validate[formname][i][nameIndex], requiredTxt + " " + validate[formname][i][msgIndex]);
905 if(!isInteger(trim(form[validate[formname][i][nameIndex]].value))){
907 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
911 if(!isDecimal(trim(form[validate[formname][i][nameIndex]].value))){
913 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
918 if(!isFloat(trim(form[validate[formname][i][nameIndex]].value))){
920 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
924 var div_element_id = formname + '_' + form[validate[formname][i][nameIndex]].name + '_operation_div';
925 var input_elements = YAHOO.util.Selector.query('input', document.getElementById(div_element_id));
926 var primary_field_id = '';
927 var validation_passed = false;
928 var replace_selected = false;
930 //Loop through the option elements (replace or add currently)
931 for(t in input_elements) {
932 if(input_elements[t].type && input_elements[t].type == 'radio' && input_elements[t].checked == true && input_elements[t].value == 'replace') {
934 //Now find where the primary radio button is and if a value has been set
935 var radio_elements = YAHOO.util.Selector.query('input[type=radio]', document.getElementById(formname + '_team_name_table'));
937 for(var x = 0; x < radio_elements.length; x++) {
938 if(radio_elements[x].name != 'team_name_type') {
939 primary_field_id = 'team_name_collection_' + radio_elements[x].value;
940 if(radio_elements[x].checked) {
941 replace_selected = true;
942 if(trim(document.forms[formname].elements[primary_field_id].value) != '') {
943 validation_passed = true;
946 } else if(trim(document.forms[formname].elements[primary_field_id].value) != '') {
947 replace_selected = true;
954 if(replace_selected && !validation_passed) {
955 add_error_style(formname, primary_field_id, SUGAR.language.get('app_strings', 'ERR_NO_PRIMARY_TEAM_SPECIFIED'));
960 var table_element_id = formname + '_' + form[validate[formname][i][nameIndex]].name + '_table';
961 if(document.getElementById(table_element_id)) {
962 var input_elements = YAHOO.util.Selector.query('input[type=radio]', document.getElementById(table_element_id));
963 var has_primary = false;
964 var primary_field_id = form[validate[formname][i][nameIndex]].name + '_collection_0';
966 for(t in input_elements) {
967 primary_field_id = form[validate[formname][i][nameIndex]].name + '_collection_' + input_elements[t].value;
968 if(input_elements[t].type && input_elements[t].type == 'radio' && input_elements[t].checked == true) {
969 if(document.forms[formname].elements[primary_field_id].value != '') {
978 var field_id = form[validate[formname][i][nameIndex]].name + '_collection_' + input_elements[0].value;
979 add_error_style(formname, field_id, SUGAR.language.get('app_strings', 'ERR_NO_PRIMARY_TEAM_SPECIFIED'));
985 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex]);
989 if(typeof validate[formname][i][jstypeIndex] != 'undefined'/* && !isError*/){
991 switch(validate[formname][i][jstypeIndex]){
992 // Bug #47961 May be validation through callback is best way.
994 if (typeof validate[formname][i][callbackIndex] == 'function')
996 var result = validate[formname][i][callbackIndex](formname, validate[formname][i][nameIndex]);
1000 add_error_style(formname, validate[formname][i][nameIndex], requiredTxt + " " + validate[formname][i][msgIndex]);
1005 if(!inRange(trim(form[validate[formname][i][nameIndex]].value), validate[formname][i][minIndex], validate[formname][i][maxIndex])){
1007 var lbl_validate_range = SUGAR.language.get('app_strings', 'LBL_VALIDATE_RANGE');
1008 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] + ") ");
1012 compareTo = form[validate[formname][i][compareToIndex]];
1013 if( typeof compareTo != 'undefined'){
1014 if(trim(compareTo.value) != '' || (validate[formname][i][allowblank] != 'true') ) {
1015 date2 = trim(compareTo.value);
1016 date1 = trim(form[validate[formname][i][nameIndex]].value);
1018 if(trim(date1).length != 0 && !isBefore(date1,date2)){
1021 //jc:#12287 - adding translation for the is not before message
1022 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex] + "(" + date1 + ") " + SUGAR.language.get('app_strings', 'MSG_IS_NOT_BEFORE') + ' ' +date2);
1028 value=unformatNumber(trim(form[validate[formname][i][nameIndex]].value), num_grp_sep, dec_sep);
1029 maximum = parseFloat(validate[formname][i][maxIndex]);
1030 if( typeof maximum != 'undefined'){
1033 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]);
1038 value=unformatNumber(trim(form[validate[formname][i][nameIndex]].value), num_grp_sep, dec_sep);
1039 minimum = parseFloat(validate[formname][i][minIndex]);
1040 if( typeof minimum != 'undefined'){
1043 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'));
1048 compareTo = form[validate[formname][i][compareToIndex]];
1049 if( typeof compareTo != 'undefined') {
1050 item1 = trim(form[validate[formname][i][nameIndex]].value);
1051 item2 = trim(compareTo.value);
1052 if(!bothExist(item1, item2)) {
1054 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex]);
1059 compareTo = form[validate[formname][i][compareToIndex]];
1060 if( typeof compareTo != 'undefined') {
1061 item1 = trim(form[validate[formname][i][nameIndex]].value);
1062 item2 = trim(compareTo.value);
1063 if(!bothExist(item1, item2) || item1 != item2) {
1065 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex]);
1070 arr = eval(validate[formname][i][arrIndex]);
1071 operator = validate[formname][i][operatorIndex];
1072 item1 = trim(form[validate[formname][i][nameIndex]].value);
1073 if (operator.charAt(0) == 'u') {
1074 item1 = item1.toUpperCase();
1075 operator = operator.substring(1);
1076 } else if (operator.charAt(0) == 'l') {
1077 item1 = item1.toLowerCase();
1078 operator = operator.substring(1);
1080 for(j = 0; j < arr.length; j++){
1082 if((operator == "==" && val == item1) || (operator == "!=" && val != item1)){
1084 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
1089 if(trim(form[validate[formname][i][nameIndex]].value) == 'false'){
1090 //Fake an error so form does not submit
1100 /* nsingh: BUG#15102
1101 Check min max default field logic.
1102 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.*/
1103 if(formsWithFieldLogic){
1104 var invalidLogic=false;
1105 if(formsWithFieldLogic.min && formsWithFieldLogic.max && formsWithFieldLogic._default) {
1106 var showErrorsOn={min:{value:'min', show:false, obj:formsWithFieldLogic.min.value},
1107 max:{value:'max',show:false, obj:formsWithFieldLogic.max.value},
1108 _default:{value:'default',show:false, obj:formsWithFieldLogic._default.value},
1109 len:{value:'len', show:false, obj:parseInt(formsWithFieldLogic.len.value,10)}};
1111 var min = (formsWithFieldLogic.min.value !='') ? parseFloat(formsWithFieldLogic.min.value) : 'undef';
1112 var max = (formsWithFieldLogic.max.value !='') ? parseFloat(formsWithFieldLogic.max.value) : 'undef';
1113 var _default = (formsWithFieldLogic._default.value!='')? parseFloat(formsWithFieldLogic._default.value) : 'undef';
1115 /*Check all lengths are <= max size.*/
1116 for(var i in showErrorsOn){
1117 if(showErrorsOn[i].value!='len' && showErrorsOn[i].obj.length > showErrorsOn.len.obj){
1119 showErrorsOn[i].show=true;
1120 showErrorsOn.len.show=true;
1124 if(min!='undef' && max!='undef' && _default!='undef'){
1125 if(!inRange(_default,min,max)){
1127 showErrorsOn.min.show=true;
1128 showErrorsOn.max.show=true;
1129 showErrorsOn._default.show=true;
1132 if(min!='undef' && max!= 'undef' && min > max){
1133 invalidLogic = true;
1134 showErrorsOn.min.show=true;
1135 showErrorsOn.max.show=true;
1137 if(min!='undef' && _default!='undef' && _default < min){
1139 invalidLogic = true;
1140 showErrorsOn.min.show=true;
1141 showErrorsOn._default.show=true;
1143 if(max!='undef' && _default !='undef' && _default>max){
1145 invalidLogic = true;
1146 showErrorsOn.max.show=true;
1147 showErrorsOn._default.show=true;
1152 for(var error in showErrorsOn)
1153 if(showErrorsOn[error].show)
1154 add_error_style(formname,showErrorsOn[error].value, formsWithFieldLogic.msg);
1159 formsWithFieldLogic = null;
1162 if(formWithPrecision){
1163 if (!isValidPrecision(formWithPrecision.float.value, formWithPrecision.precision.value)){
1165 add_error_style(formname, 'default', SUGAR.language.get('app_strings', 'ERR_COMPATIBLE_PRECISION_VALUE'));
1173 if (isError == true) {
1175 if (self.pageYOffset) // all except Explorer
1177 nwX = self.pageXOffset;
1178 seX = self.innerWidth;
1179 nwY = self.pageYOffset;
1180 seY = self.innerHeight;
1182 else if (document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
1184 nwX = document.documentElement.scrollLeft;
1185 seX = document.documentElement.clientWidth;
1186 nwY = document.documentElement.scrollTop;
1187 seY = document.documentElement.clientHeight;
1189 else if (document.body) // all other Explorers
1191 nwX = document.body.scrollLeft;
1192 seX = document.body.clientWidth;
1193 nwY = document.body.scrollTop;
1194 seY = document.body.clientHeight;
1197 var inView = true; // is there an error within viewport of browser
1198 for(var wp = 0; wp < inputsWithErrors.length; wp++) {
1199 var elementCoor = findElementPos(inputsWithErrors[wp]);
1200 if(!(elementCoor.x >= nwX && elementCoor.y >= nwY &&
1201 elementCoor.x <= seX+nwX && elementCoor.y <= seY+nwY)) { // if input is not within viewport, modify for SI bug 52497
1203 scrollToTop = elementCoor.y - 75;
1204 scrollToLeft = elementCoor.x - 75;
1206 else { // on first input within viewport, don't scroll
1212 if(!inView) window.scrollTo(scrollToLeft,scrollToTop);
1217 disableOnUnloadEditView(form);
1224 * This array is used to remember mark status of rows in browse mode
1226 var marked_row = new Array;
1230 * Sets/unsets the pointer and marker in browse mode
1232 * @param object the table row
1233 * @param interger the row number
1234 * @param string the action calling this script (over, out or click)
1235 * @param string the default background color
1236 * @param string the color to use for mouseover
1237 * @param string the color to use for marking a row
1239 * @return boolean whether pointer is set or not
1241 function setPointer(theRow, theRowNum, theAction, theDefaultColor, thePointerColor, theMarkColor) {
1242 var theCells = null;
1244 // 1. Pointer and mark feature are disabled or the browser can't get the
1246 if ((thePointerColor == '' && theMarkColor == '')
1247 || typeof(theRow.style) == 'undefined') {
1251 // 2. Gets the current row and exits if the browser can't get it
1252 if (typeof(document.getElementsByTagName) != 'undefined') {
1253 theCells = theRow.getElementsByTagName('td');
1255 else if (typeof(theRow.cells) != 'undefined') {
1256 theCells = theRow.cells;
1262 // 3. Gets the current color...
1263 var rowCellsCnt = theCells.length;
1264 var domDetect = null;
1265 var currentColor = null;
1266 var newColor = null;
1267 // 3.1 ... with DOM compatible browsers except Opera that does not return
1268 // valid values with "getAttribute"
1269 if (typeof(window.opera) == 'undefined'
1270 && typeof(theCells[0].getAttribute) != 'undefined') {
1271 currentColor = theCells[0].getAttribute('bgcolor');
1274 // 3.2 ... with other browsers
1276 currentColor = theCells[0].style.backgroundColor;
1280 // 4. Defines the new color
1281 // 4.1 Current color is the default one
1282 if (currentColor == ''
1283 || (currentColor!= null && (currentColor.toLowerCase() == theDefaultColor.toLowerCase()))) {
1284 if (theAction == 'over' && thePointerColor != '') {
1285 newColor = thePointerColor;
1287 else if (theAction == 'click' && theMarkColor != '') {
1288 newColor = theMarkColor;
1289 marked_row[theRowNum] = true;
1292 // 4.1.2 Current color is the pointer one
1293 else if (currentColor!= null && (currentColor.toLowerCase() == thePointerColor.toLowerCase())
1294 && (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])) {
1295 if (theAction == 'out') {
1296 newColor = theDefaultColor;
1298 else if (theAction == 'click' && theMarkColor != '') {
1299 newColor = theMarkColor;
1300 marked_row[theRowNum] = true;
1303 // 4.1.3 Current color is the marker one
1304 else if (currentColor!= null && (currentColor.toLowerCase() == theMarkColor.toLowerCase())) {
1305 if (theAction == 'click') {
1306 newColor = (thePointerColor != '')
1309 marked_row[theRowNum] = (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])
1315 // 5. Sets the new color...
1318 // 5.1 ... with DOM compatible browsers except Opera
1320 for (c = 0; c < rowCellsCnt; c++) {
1321 theCells[c].setAttribute('bgcolor', newColor, 0);
1324 // 5.2 ... with other browsers
1326 for (c = 0; c < rowCellsCnt; c++) {
1327 theCells[c].style.backgroundColor = newColor;
1333 } // end of the 'setPointer()' function
1337 * listbox redirection
1339 function goToUrl(selObj, goToLocation) {
1340 eval("document.location.href = '" + goToLocation + "pos=" + selObj.options[selObj.selectedIndex].value + "'");
1345 var json_objects = new Object();
1347 function getXMLHTTPinstance() {
1348 var xmlhttp = false;
1349 var userAgent = navigator.userAgent.toLowerCase() ;
1351 // IE Check supports ActiveX controls
1352 if (userAgent.indexOf("msie") != -1 && userAgent.indexOf("mac") == -1 && userAgent.indexOf("opera") == -1) {
1353 var version = navigator.appVersion.match(/MSIE (.\..)/)[1] ;
1354 if(version >= 5.5 ) {
1356 xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
1360 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
1369 if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
1370 xmlhttp = new XMLHttpRequest();
1375 // NOW LOAD THE OBJECT..
1376 var global_xmlhttp = getXMLHTTPinstance();
1378 function http_fetch_sync(url,post_data) {
1379 global_xmlhttp = getXMLHTTPinstance();
1382 if(typeof(post_data) != 'undefined') method = 'POST';
1384 global_xmlhttp.open(method, url,false);
1387 alert('message:'+e.message+":url:"+url);
1389 if(method == 'POST') {
1390 global_xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
1393 global_xmlhttp.send(post_data);
1395 if (SUGAR.util.isLoginPage(global_xmlhttp.responseText))
1398 var args = {"responseText" : global_xmlhttp.responseText,
1399 "responseXML" : global_xmlhttp.responseXML,
1400 "request_id" : typeof(request_id) != "undefined" ? request_id : 0};
1404 // this is a GET unless post_data is defined
1406 function http_fetch_async(url,callback,request_id,post_data) {
1408 if(typeof(post_data) != 'undefined') {
1413 global_xmlhttp.open(method, url,true);
1416 alert('message:'+e.message+":url:"+url);
1418 if(method == 'POST') {
1419 global_xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
1421 global_xmlhttp.onreadystatechange = function() {
1422 if(global_xmlhttp.readyState==4) {
1423 if(global_xmlhttp.status == 200) {
1424 if (SUGAR.util.isLoginPage(global_xmlhttp.responseText))
1426 var args = {"responseText" : global_xmlhttp.responseText,
1427 "responseXML" : global_xmlhttp.responseXML,
1428 "request_id" : request_id };
1429 callback.call(document,args);
1432 alert("There was a problem retrieving the XML data:\n" + global_xmlhttp.statusText);
1436 global_xmlhttp.send(post_data);
1439 function insert_at_cursor(field, value) {
1441 if (document.selection) {
1443 sel = document.selection.createRange();
1447 else if(field.selectionStart || field.selectionStart == '0') {
1448 var start_pos = field.selectionStart;
1449 var end_pos = field.selectionEnd;
1450 field.value = field.value.substring(0, start_pos) + value + field.value.substring(end_pos, field.value.length);
1453 field.value += value;
1457 function checkParentType(type,button) {
1458 if(button == null) {
1461 if(typeof disabledModules != 'undefined' && typeof(disabledModules[type]) != 'undefined') {
1462 button.disabled='disabled';
1465 button.disabled = false;
1469 function parseDate(input, format) {
1471 format = format.replace(/%/g, '');
1472 sep = format.charAt(1);
1473 yAt = format.indexOf('Y')
1474 // 1-1-06 or 1-12-06 or 1-1-2006 or 1-12-2006
1475 if(date.match(/^\d{1,2}[\/-]\d{1,2}[\/-]\d{2,4}$/) && yAt == 4) {
1476 if(date.match(/^\d{1}[\/-].*$/)) date = '0' + date;
1477 if(date.match(/^\d{2}[\/-]\d{1}[\/-].*$/)) date = date.substring(0,3) + '0' + date.substring(3,date.length);
1478 if(date.match(/^\d{2}[\/-]\d{2}[\/-]\d{2}$/)) date = date.substring(0,6) + '20' + date.substring(6,date.length);
1480 // 06-11-1 or 06-1-1
1481 else if(date.match(/^\d{2,4}[\/-]\d{1,2}[\/-]\d{1,2}$/)) {
1482 if(date.match(/^\d{2}[\/-].*$/)) date = '20' + date;
1483 if(date.match(/^\d{4}[\/-]\d{1}[\/-].*$/)) date = date.substring(0,5) + '0' + date.substring(5,date.length);
1484 if(date.match(/^\d{4}[\/-]\d{2}[\/-]\d{1}$/)) date = date.substring(0,8) + '0' + date.substring(8,date.length);
1486 else if(date.match(/^\d{4,8}$/)) { // digits only
1488 if(date.match(/^\d{8}$/)) digits = 8;// match for 8 digits
1489 else if(date.match(/\d{6}/)) digits = 6;// match for 5 digits
1490 else if(date.match(/\d{4}/)) digits = 4;// match for 5 digits
1491 else if(date.match(/\d{5}/)) digits = 5;// match for 5 digits
1496 case 4: date = '20' + date.substring(0,2) + sep + '0' + date.substring(2, 3) + sep + '0' + date.substring(3,4); break;
1497 case 5: date = '20' + date.substring(0,2) + sep + date.substring(2, 4) + sep + '0' + date.substring(4,5); break;
1498 case 6: date = '20' + date.substring(0,2) + sep + date.substring(2, 4) + sep + date.substring(4,6); break;
1499 case 8: date = date.substring(0,4) + sep + date.substring(4, 6) + sep + date.substring(6,8); break;
1504 case 4: date = '0' + date.substring(0,1) + sep + '20' + date.substring(1, 3) + sep + '0' + date.substring(3,4); break;
1505 case 5: date = date.substring(0,2) + sep + '20' + date.substring(2, 4) + sep + '0' + date.substring(4,5); break;
1506 case 6: date = date.substring(0,2) + sep + '20' + date.substring(2, 4) + sep + date.substring(4,6); break;
1507 case 8: date = date.substring(0,2) + sep + date.substring(2, 6) + sep + date.substring(6,8); break;
1511 case 4: date = '0' + date.substring(0,1) + sep + '0' + date.substring(1, 2) + sep + '20' + date.substring(2,4); break;
1512 case 5: date = '0' + date.substring(0,1) + sep + date.substring(1, 3) + sep + '20' + date.substring(3,5); break;
1513 case 6: date = date.substring(0,2) + sep + date.substring(2, 4) + sep + '20' + date.substring(4,6); break;
1514 case 8: date = date.substring(0,2) + sep + date.substring(2, 4) + sep + date.substring(4,8); break;
1519 date = date.replace(/[\/-]/g, sep);
1523 // find obj's position
1524 function findElementPos(obj) {
1527 if (obj.offsetParent) {
1528 while (obj.offsetParent) {
1529 x += obj.offsetLeft;
1531 obj = obj.offsetParent;
1533 }//if offsetParent exists
1534 else if (obj.x && obj.y) {
1538 return new coordinate(x, y);
1542 // get dimensions of the browser window
1543 function getClientDim() {
1544 var nwX, nwY, seX, seY;
1545 if (self.pageYOffset) // all except Explorer
1547 nwX = self.pageXOffset;
1548 seX = self.innerWidth + nwX;
1549 nwY = self.pageYOffset;
1550 seY = self.innerHeight + nwY;
1552 else if (document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
1554 nwX = document.documentElement.scrollLeft;
1555 seX = document.documentElement.clientWidth + nwX;
1556 nwY = document.documentElement.scrollTop;
1557 seY = document.documentElement.clientHeight + nwY;
1559 else if (document.body) // all other Explorers
1561 nwX = document.body.scrollLeft;
1562 seX = document.body.clientWidth + nwX;
1563 nwY = document.body.scrollTop;
1564 seY = document.body.clientHeight + nwY;
1566 return {'nw' : new coordinate(nwX, nwY), 'se' : new coordinate(seX, seY)};
1570 * stop propagation on events
1572 function freezeEvent(e) {
1574 if (e.preventDefault) e.preventDefault();
1575 e.returnValue = false;
1576 e.cancelBubble = true;
1577 if (e.stopPropagation) e.stopPropagation();
1586 function coordinate(_x, _y) {
1595 return new position(this.x + rh.x, this.y + rh.y);
1599 return new position(this.x + rh.x, this.y + rh.y);
1603 // sends theForm via AJAX and fills in the theDiv
1604 function sendAndRetrieve(theForm, theDiv, loadingStr) {
1605 function success(data) {
1606 document.getElementById(theDiv).innerHTML = data.responseText;
1607 ajaxStatus.hideStatus();
1609 if(typeof loadingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
1610 ajaxStatus.showStatus(loadingStr);
1611 oForm = new YAHOO.util.Element(theForm);
1612 if ( oForm.get('enctype') && oForm.get('enctype') == 'multipart/form-data' ) {
1613 // the second argument is true to indicate file upload.
1614 YAHOO.util.Connect.setForm(theForm, true);
1615 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {upload: success, failure: success});
1617 YAHOO.util.Connect.setForm(theForm);
1618 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
1623 //save the form and redirect
1624 function sendAndRedirect(theForm, loadingStr, redirect_location) {
1625 function success(data) {
1626 if(redirect_location){
1627 location.href=redirect_location;
1629 ajaxStatus.hideStatus();
1631 if(typeof loadingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
1632 ajaxStatus.showStatus(loadingStr);
1633 oForm = new YAHOO.util.Element(theForm);
1634 if ( oForm.get('enctype') && oForm.get('enctype') == 'multipart/form-data' ) {
1635 // the second argument is true to indicate file upload.
1636 YAHOO.util.Connect.setForm(theForm, true);
1637 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {upload: success, failure: success});
1639 YAHOO.util.Connect.setForm(theForm);
1640 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
1645 function saveForm(theForm, theDiv, loadingStr) {
1646 if(check_form(theForm)){
1647 for(i = 0; i < ajaxFormArray.length; i++){
1648 if(ajaxFormArray[i] == theForm){
1649 ajaxFormArray.splice(i, 1);
1652 return sendAndRetrieve(theForm, loadingStr, theDiv);
1658 // Builds a "snapshot" of the form, so we can use it to see if someone has changed it.
1659 function snapshotForm(theForm) {
1660 var snapshotTxt = '';
1661 var elemList = theForm.elements;
1665 for( var i = 0; i < elemList.length ; i++ ) {
1667 if ( typeof(elem.type) == 'undefined' ) {
1671 elemType = elem.type.toLowerCase();
1673 snapshotTxt = snapshotTxt + elem.name;
1675 if ( elemType == 'text' || elemType == 'textarea' || elemType == 'password' ) {
1676 snapshotTxt = snapshotTxt + elem.value;
1678 else if ( elemType == 'select' || elemType == 'select-one' || elemType == 'select-multiple' ) {
1679 var optionList = elem.options;
1680 for ( var ii = 0 ; ii < optionList.length ; ii++ ) {
1681 if ( optionList[ii].selected ) {
1682 snapshotTxt = snapshotTxt + optionList[ii].value;
1686 else if ( elemType == 'radio' || elemType == 'checkbox' ) {
1687 if ( elem.selected ) {
1688 snapshotTxt = snapshotTxt + 'checked';
1691 else if ( elemType == 'hidden' ) {
1692 snapshotTxt = snapshotTxt + elem.value;
1699 function initEditView(theForm) {
1700 if (SUGAR.util.ajaxCallInProgress()) {
1701 window.setTimeout(function(){initEditView(theForm);}, 100);
1705 if ( theForm == null || theForm.id == null ) {
1706 // Not much we can do here.
1710 // we don't need to check if the data is changed in the search popup
1711 if (theForm.id == 'popup_query_form' || theForm.id == 'MassUpdate') {
1714 if ( typeof editViewSnapshots == 'undefined' || editViewSnapshots == null ) {
1715 editViewSnapshots = new Object();
1717 if ( typeof SUGAR.loadedForms == 'undefined' || SUGAR.loadedForms == null) {
1718 SUGAR.loadedForms = new Object();
1721 editViewSnapshots[theForm.id] = snapshotForm(theForm);
1722 SUGAR.loadedForms[theForm.id] = true;
1725 function onUnloadEditView(theForm) {
1727 var dataHasChanged = false;
1728 if ( typeof editViewSnapshots == 'undefined' ) {
1729 // No snapshots, move along
1733 if ( typeof theForm == 'undefined' ) {
1734 // Need to check all editViewSnapshots
1735 for ( var idx in editViewSnapshots ) {
1737 theForm = document.getElementById(idx);
1738 // console.log('DEBUG: Checking all forms '+theForm.id);
1739 if ( theForm == null
1740 || typeof editViewSnapshots[theForm.id] == 'undefined'
1741 || editViewSnapshots[theForm.id] == null
1742 || !SUGAR.loadedForms[theForm.id]) {
1746 var snap = snapshotForm(theForm);
1747 if ( editViewSnapshots[theForm.id] != snap ) {
1748 dataHasChanged = true;
1752 // Just need to check a single form for changes
1753 if ( editViewSnapshots == null || typeof theForm.id == 'undefined' || typeof editViewSnapshots[theForm.id] == 'undefined' || editViewSnapshots[theForm.id] == null ) {
1757 // console.log('DEBUG: Checking one form '+theForm.id);
1758 if ( editViewSnapshots[theForm.id] != snapshotForm(theForm) ) {
1759 // Data has changed.
1760 dataHasChanged = true;
1764 if ( dataHasChanged == true ) {
1765 return SUGAR.language.get('app_strings','WARN_UNSAVED_CHANGES');
1772 function disableOnUnloadEditView(theForm) {
1773 // If you don't pass anything in, it disables all checking
1774 if ( typeof theForm == 'undefined' || typeof editViewSnapshots == 'undefined' || theForm == null || editViewSnapshots == null) {
1775 window.onbeforeunload = null;
1776 editViewSnapshots = null;
1778 // console.log('DEBUG: Disabling all edit view checks');
1781 // Otherwise, it just disables it for this form
1782 if ( typeof(theForm.id) != 'undefined' && typeof(editViewSnapshots[theForm.id]) != 'undefined' ) {
1783 editViewSnapshots[theForm.id] = null;
1786 // console.log('DEBUG : Disabling just checks for '+theForm.id);
1792 * save some forms using an ajax call
1793 * theForms - the ids of all of theh forms to save
1794 * savingStr - the string to display when saving the form
1795 * completeStr - the string to display when the form has been saved
1797 function saveForms( savingStr, completeStr) {
1799 theForms = ajaxFormArray;
1800 function success(data) {
1801 var theForm = document.getElementById(ajaxFormArray[0]);
1802 document.getElementById('multiedit_'+theForm.id).innerHTML = data.responseText;
1803 var saveAllButton = document.getElementById('ajaxsaveall');
1804 ajaxFormArray.splice(index, 1);
1805 if(saveAllButton && ajaxFormArray.length <= 1){
1806 saveAllButton.style.visibility = 'hidden';
1809 if(index == theForms.length){
1810 ajaxStatus.showStatus(completeStr);
1811 window.setTimeout('ajaxStatus.hideStatus();', 2000);
1813 saveAllButton.style.visibility = 'hidden';
1818 if(typeof savingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
1819 ajaxStatus.showStatus(savingStr);
1821 //loop through the forms saving each one
1822 for(i = 0; i < theForms.length; i++){
1823 var theForm = document.getElementById(theForms[i]);
1824 if(check_form(theForm.id)){
1825 theForm.action.value='AjaxFormSave';
1826 YAHOO.util.Connect.setForm(theForm);
1827 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
1829 ajaxStatus.hideStatus();
1831 lastSubmitTime = lastSubmitTime-2000;
1836 // -- start sugarListView class
1837 // js functions used for ListView
1838 function sugarListView() {
1842 sugarListView.prototype.confirm_action = function(del) {
1844 return confirm( SUGAR.language.get('app_strings', 'NTC_DELETE_CONFIRMATION_NUM') + sugarListView.get_num_selected() + SUGAR.language.get('app_strings', 'NTC_DELETE_SELECTED_RECORDS'));
1847 return confirm( SUGAR.language.get('app_strings', 'NTC_UPDATE_CONFIRMATION_NUM') + sugarListView.get_num_selected() + SUGAR.language.get('app_strings', 'NTC_DELETE_SELECTED_RECORDS'));
1851 sugarListView.get_num_selected = function () {
1852 var selectCount = $("input[name='selectCount[]']:first");
1853 if(selectCount.length > 0)
1854 return parseInt(selectCount.val().replace("+", ""));
1858 sugarListView.update_count = function(count, add) {
1859 if(typeof document.MassUpdate != 'undefined') {
1860 the_form = document.MassUpdate;
1861 for(var wp = 0; wp < the_form.elements.length; wp++) {
1862 if(typeof the_form.elements[wp].name != 'undefined' && the_form.elements[wp].name == 'selectCount[]') {
1864 the_form.elements[wp].value = parseInt(the_form.elements[wp].value,10) + count;
1865 if (the_form.select_entire_list.value == 1 && the_form.show_plus.value) {
1866 the_form.elements[wp].value += '+';
1869 if (the_form.select_entire_list.value == 1 && the_form.show_plus.value) {
1870 the_form.elements[wp].value = count + '+';
1872 the_form.elements[wp].value = count;
1879 sugarListView.prototype.use_external_mail_client = function(no_record_txt, module) {
1880 selected_records = sugarListView.get_checks_count();
1881 if(selected_records <1) {
1882 alert(no_record_txt);
1886 if (document.MassUpdate.select_entire_list.value == 1) {
1887 if (totalCount > 10) {
1888 alert(totalCountError);
1893 else if (document.MassUpdate.massall.checked == true)
1897 sugarListView.get_checks();
1899 if(select) { // use selected items
1900 ids = document.MassUpdate.uid.value;
1902 else { // use current page
1903 inputs = document.MassUpdate.elements;
1905 for(i = 0; i < inputs.length; i++) {
1906 if(inputs[i].name == 'mass[]' && inputs[i].checked && typeof(inputs[i].value) != 'function') {
1907 ar.push(inputs[i].value);
1912 YAHOO.util.Connect.asyncRequest("POST", "index.php?", {
1913 success: this.use_external_mail_client_callback
1914 }, SUGAR.util.paramsToUrl({
1917 listViewExternalClient: 1,
1918 action_module: module,
1926 sugarListView.prototype.use_external_mail_client_callback = function(o)
1929 location.href = 'mailto:' + o.responseText;
1932 sugarListView.prototype.send_form_for_emails = function(select, currentModule, action, no_record_txt,action_module,totalCount, totalCountError) {
1933 if ( typeof(SUGAR.config.email_sugarclient_listviewmaxselect) != 'undefined' ) {
1937 maxCount = SUGAR.config.email_sugarclient_listviewmaxselect;
1940 if (document.MassUpdate.select_entire_list.value == 1) {
1941 if (totalCount > maxCount) {
1942 alert(totalCountError);
1947 else if (document.MassUpdate.massall.checked == true)
1952 sugarListView.get_checks();
1953 // create new form to post (can't access action property of MassUpdate form due to action input)
1954 var newForm = document.createElement('form');
1955 newForm.method = 'post';
1956 newForm.action = action;
1957 newForm.name = 'newForm';
1958 newForm.id = 'newForm';
1959 var uidTa = document.createElement('textarea');
1961 uidTa.style.display = 'none';
1963 if(select) { // use selected items
1964 uidTa.value = document.MassUpdate.uid.value;
1966 else { // use current page
1967 inputs = document.MassUpdate.elements;
1969 for(i = 0; i < inputs.length; i++) {
1970 if(inputs[i].name == 'mass[]' && inputs[i].checked && typeof(inputs[i].value) != 'function') {
1971 ar.push(inputs[i].value);
1974 uidTa.value = ar.join(',');
1977 if(uidTa.value == '') {
1978 alert(no_record_txt);
1982 var selectedArray = uidTa.value.split(",");
1983 if(selectedArray.length > maxCount) {
1984 alert(totalCountError);
1987 newForm.appendChild(uidTa);
1989 var moduleInput = document.createElement('input');
1990 moduleInput.name = 'module';
1991 moduleInput.type = 'hidden';
1992 moduleInput.value = currentModule;
1993 newForm.appendChild(moduleInput);
1995 var actionInput = document.createElement('input');
1996 actionInput.name = 'action';
1997 actionInput.type = 'hidden';
1998 actionInput.value = 'Compose';
1999 newForm.appendChild(actionInput);
2001 if (typeof action_module != 'undefined' && action_module!= '') {
2002 var actionModule = document.createElement('input');
2003 actionModule.name = 'action_module';
2004 actionModule.type = 'hidden';
2005 actionModule.value = action_module;
2006 newForm.appendChild(actionModule);
2008 //return_info must follow this pattern."&return_module=Accounts&return_action=index"
2009 if (typeof return_info!= 'undefined' && return_info != '') {
2010 var params= return_info.split('&');
2011 if (params.length > 0) {
2012 for (var i=0;i< params.length;i++) {
2013 if (params[i].length > 0) {
2014 var param_nv=params[i].split('=');
2015 if (param_nv.length==2){
2016 returnModule = document.createElement('input');
2017 returnModule.name = param_nv[0];
2018 returnModule.type = 'hidden';
2019 returnModule.value = param_nv[1];
2020 newForm.appendChild(returnModule);
2027 var isAjaxCall = document.createElement('input');
2028 isAjaxCall.name = 'ajaxCall';
2029 isAjaxCall.type = 'hidden';
2030 isAjaxCall.value = true;
2031 newForm.appendChild(isAjaxCall);
2033 var isListView = document.createElement('input');
2034 isListView.name = 'ListView';
2035 isListView.type = 'hidden';
2036 isListView.value = true;
2037 newForm.appendChild(isListView);
2039 var toPdf = document.createElement('input');
2040 toPdf.name = 'to_pdf';
2041 toPdf.type = 'hidden';
2043 newForm.appendChild(toPdf);
2045 //Grab the Quick Compose package for the listview
2046 YAHOO.util.Connect.setForm(newForm);
2049 success: function(o) {
2050 var resp = YAHOO.lang.JSON.parse(o.responseText);
2051 var quickComposePackage = new Object();
2052 quickComposePackage.composePackage = resp;
2053 quickComposePackage.fullComposeUrl = 'index.php?module=Emails&action=Compose&ListView=true' +
2054 '&uid=' + uidTa.value + '&action_module=' + action_module;
2056 SUGAR.quickCompose.init(quickComposePackage);
2060 YAHOO.util.Connect.asyncRequest('POST','index.php', callback,null);
2062 // awu Bug 18624: Fixing issue where a canceled Export and unselect of row will persist the uid field, clear the field
2063 document.MassUpdate.uid.value = '';
2068 sugarListView.prototype.send_form = function(select, currentModule, action, no_record_txt,action_module,return_info) {
2069 if (document.MassUpdate.select_entire_list.value == 1) {
2071 if(sugarListView.get_checks_count() < 1) {
2072 alert(no_record_txt);
2077 if ( action.indexOf('?') != -1 )
2078 href += '&module=' + currentModule;
2080 href += '?module=' + currentModule;
2083 href += return_info;
2084 var newForm = document.createElement('form');
2085 newForm.method = 'post';
2086 newForm.action = href;
2087 newForm.name = 'newForm';
2088 newForm.id = 'newForm';
2089 var postTa = document.createElement('textarea');
2090 postTa.name = 'current_post';
2091 postTa.value = document.MassUpdate.current_query_by_page.value;
2092 postTa.style.display = 'none';
2093 newForm.appendChild(postTa);
2094 document.MassUpdate.parentNode.appendChild(newForm);
2098 else if (document.MassUpdate.massall.checked == true)
2103 sugarListView.get_checks();
2104 // create new form to post (can't access action property of MassUpdate form due to action input)
2105 var newForm = document.createElement('form');
2106 newForm.method = 'post';
2107 newForm.action = action;
2108 newForm.name = 'newForm';
2109 newForm.id = 'newForm';
2110 var uidTa = document.createElement('textarea');
2112 uidTa.style.display = 'none';
2113 uidTa.value = document.MassUpdate.uid.value;
2115 if(uidTa.value == '') {
2116 alert(no_record_txt);
2120 newForm.appendChild(uidTa);
2122 var moduleInput = document.createElement('input');
2123 moduleInput.name = 'module';
2124 moduleInput.type = 'hidden';
2125 moduleInput.value = currentModule;
2126 newForm.appendChild(moduleInput);
2128 var actionInput = document.createElement('input');
2129 actionInput.name = 'action';
2130 actionInput.type = 'hidden';
2131 actionInput.value = 'index';
2132 newForm.appendChild(actionInput);
2134 if (typeof action_module != 'undefined' && action_module!= '') {
2135 var actionModule = document.createElement('input');
2136 actionModule.name = 'action_module';
2137 actionModule.type = 'hidden';
2138 actionModule.value = action_module;
2139 newForm.appendChild(actionModule);
2141 //return_info must follow this pattern."&return_module=Accounts&return_action=index"
2142 if (typeof return_info!= 'undefined' && return_info != '') {
2143 var params= return_info.split('&');
2144 if (params.length > 0) {
2145 for (var i=0;i< params.length;i++) {
2146 if (params[i].length > 0) {
2147 var param_nv=params[i].split('=');
2148 if (param_nv.length==2){
2149 returnModule = document.createElement('input');
2150 returnModule.name = param_nv[0];
2151 returnModule.type = 'hidden';
2152 returnModule.value = param_nv[1];
2153 newForm.appendChild(returnModule);
2160 document.MassUpdate.parentNode.appendChild(newForm);
2163 // awu Bug 18624: Fixing issue where a canceled Export and unselect of row will persist the uid field, clear the field
2164 document.MassUpdate.uid.value = '';
2168 //return a count of checked row.
2169 sugarListView.get_checks_count = function() {
2172 if(document.MassUpdate.uid.value != '') {
2173 oldUids = document.MassUpdate.uid.value.split(',');
2174 for(uid in oldUids) {
2175 if(typeof(oldUids[uid]) != 'function') {
2176 ar[oldUids[uid]] = 1;
2180 // build associated array of uids, associated array ensures uniqueness
2181 inputs = document.MassUpdate.elements;
2182 for(i = 0; i < inputs.length; i++) {
2183 if(inputs[i].name == 'mass[]') {
2184 ar[inputs[i].value] = (inputs[i].checked) ? 1 : 0; // 0 of it is unchecked
2188 // build regular array of uids
2191 if((typeof(ar[i]) != 'function') && ar[i] == 1) {
2199 // saves the checks on the current page into the uid textarea
2200 sugarListView.get_checks = function() {
2202 if(typeof document.MassUpdate != 'undefined' ){
2203 if(document.MassUpdate.uid.value != '') {
2204 oldUids = document.MassUpdate.uid.value.split(',');
2205 for(uid in oldUids) {
2206 if(typeof(oldUids[uid]) != 'function') {
2207 ar[oldUids[uid]] = 1;
2212 // build associated array of uids, associated array ensures uniqueness
2213 inputs = document.MassUpdate.elements;
2214 for(i = 0; i < inputs.length; i++) {
2215 if(inputs[i].name == 'mass[]') {
2216 ar[inputs[i].value] = (inputs[i].checked) ? 1 : 0; // 0 of it is unchecked
2220 // build regular array of uids
2223 if(typeof(ar[i]) != 'function' && ar[i] == 1) {
2228 document.MassUpdate.uid.value = uids.join(',');
2230 if(uids.length == 0) return false; // return false if no checks to get
2231 return true; // there are saved checks
2236 sugarListView.prototype.order_checks = function(order,orderBy,moduleString){
2237 checks = sugarListView.get_checks();
2238 eval('document.MassUpdate.' + moduleString + '.value = orderBy');
2239 document.MassUpdate.lvso.value = order;
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();
2252 sugarListView.prototype.save_checks = function(offset, moduleString) {
2253 checks = sugarListView.get_checks();
2254 if(typeof document.MassUpdate != 'undefined'){
2255 eval('document.MassUpdate.' + moduleString + '.value = offset');
2257 if(typeof document.MassUpdate.massupdate != 'undefined') {
2258 document.MassUpdate.massupdate.value = 'false';
2261 //we must first clear the action of massupdate, change it to index
2262 document.MassUpdate.action.value = document.MassUpdate.return_action.value;
2263 document.MassUpdate.return_module.value='';
2264 document.MassUpdate.return_action.value='';
2265 document.MassUpdate.submit();
2273 sugarListView.prototype.check_item = function(cb, form) {
2275 sugarListView.update_count(1, true);
2278 sugarListView.update_count(-1, true);
2279 if(typeof form != 'undefined' && form != null) {
2280 sugarListView.prototype.updateUid(cb, form);
2283 sugarListView.prototype.toggleSelected();
2286 sugarListView.prototype.toggleSelected = function() {
2288 var numSelected = sugarListView.get_num_selected();
2289 var selectedRecords = document.getElementById("selectedRecordsTop");
2290 var selectActions = document.getElementById("selectActions");
2291 var selectActionsDisabled = document.getElementById("selectActionsDisabled");
2292 if(numSelected > 0) {
2293 $(selectedRecords).removeAttr("style").addClass("show");
2294 $(".selectActionsDisabled").hide();
2295 jQuery('ul[name=selectActions]').each(function () {
2296 jQuery(this).removeAttr("style").addClass("show");
2300 $(selectedRecords).hide();
2301 $(".selectActionsDisabled").removeAttr("style").addClass("show");
2302 jQuery('ul[name=selectActions]').each(function () {
2303 jQuery(this).hide();
2309 /**#28000, remove the unselect record id from MassUpdate.uid **/
2310 sugarListView.prototype.updateUid = function(cb , form){
2311 if(form.name == 'MassUpdate' && form.uid && form.uid.value && cb.value && form.uid.value.indexOf(cb.value) != -1){
2312 if(form.uid.value.indexOf(','+cb.value)!= -1){
2313 form.uid.value = form.uid.value.replace(','+cb.value , '');
2314 }else if(form.uid.value.indexOf(cb.value + ',')!= -1){
2315 form.uid.value = form.uid.value.replace(cb.value + ',' , '');
2316 }else if(form.uid.value.indexOf(cb.value)!= -1){
2317 form.uid.value = form.uid.value.replace(cb.value , '');
2322 sugarListView.prototype.check_entire_list = function(form, field, value, list_count) {
2323 // count number of items
2325 $(document.MassUpdate.massall).each(function(){
2326 $(this).attr('checked', true).attr('disabled', true);
2328 for (i = 0; i < form.elements.length; i++) {
2329 if(form.elements[i].name == field && form.elements[i].disabled == false) {
2330 if(form.elements[i].checked != value) count++;
2331 form.elements[i].checked = value;
2332 form.elements[i].disabled = true;
2335 document.MassUpdate.select_entire_list.value = 1;
2336 sugarListView.update_count(list_count, false);
2337 sugarListView.prototype.toggleSelected();
2340 sugarListView.prototype.check_all = function(form, field, value, pageTotal) {
2341 // count number of items
2343 $(document.MassUpdate.massall).each(function(){$(this).attr('checked', value);});
2344 if (document.MassUpdate.select_entire_list &&
2345 document.MassUpdate.select_entire_list.value == 1)
2347 sugarListView.prototype.toggleSelected();
2348 $(document.MassUpdate.massall).each(function(){$(this).attr('disabled', true);});
2352 $(document.MassUpdate.massall).each(function(){$(this).attr('disabled', false);});
2354 for (i = 0; i < form.elements.length; i++) {
2355 if(form.elements[i].name == field && !(form.elements[i].disabled == true && form.elements[i].checked == false)) {
2356 form.elements[i].disabled = false;
2358 if(form.elements[i].checked != value)
2360 form.elements[i].checked = value;
2362 sugarListView.prototype.updateUid(form.elements[i], form);
2367 sugarListView.update_count(pageTotal);
2369 sugarListView.update_count(count, true);
2371 sugarListView.update_count(-1 * count, true);
2373 sugarListView.prototype.toggleSelected();
2375 sugarListView.check_all = sugarListView.prototype.check_all;
2376 sugarListView.confirm_action = sugarListView.prototype.confirm_action;
2378 sugarListView.prototype.check_boxes = function() {
2379 var inputsCount = 0;
2380 var checkedCount = 0;
2381 var existing_onload = window.onload;
2382 var theForm = document.MassUpdate;
2383 inputs_array = theForm.elements;
2385 if(typeof theForm.uid.value != 'undefined' && theForm.uid.value != "") {
2386 checked_items = theForm.uid.value.split(",");
2387 if (theForm.select_entire_list.value == 1) {
2388 document.MassUpdate.massall.disabled = true;
2389 sugarListView.prototype.toggleSelected();
2390 $("a[name=selectall]:first").click();
2393 for(var wp = 0 ; wp < inputs_array.length; wp++) {
2394 if(inputs_array[wp].name == "mass[]") {
2396 if (theForm.select_entire_list.value == 1) {
2397 inputs_array[wp].checked = true;
2398 inputs_array[wp].disabled = true;
2402 for(i in checked_items) {
2403 if(inputs_array[wp].value == checked_items[i]) {
2405 inputs_array[wp].checked = true;
2406 //Bug#52748: Total # of checked items are calculated in back-end side
2407 //sugarListView.prototype.check_item(inputs_array[wp], document.MassUpdate);
2415 for(var wp = 0 ; wp < inputs_array.length; wp++) {
2416 if(inputs_array[wp].name == "mass[]") {
2417 inputs_array[wp].checked = false;
2418 inputs_array[wp].disabled = false;
2421 if (document.MassUpdate.massall) {
2422 document.MassUpdate.massall.checked = false;
2423 document.MassUpdate.massall.disabled = false;
2425 sugarListView.update_count(0)
2427 if(checkedCount > 0 && checkedCount == inputsCount)
2428 document.MassUpdate.massall.checked = true;
2433 * This function is used in Email Template Module's listview.
2434 * It will check whether the templates are used in Campaing->EmailMarketing.
2435 * If true, it will notify user.
2437 function check_used_email_templates() {
2438 var ids = document.MassUpdate.uid.value;
2440 success:function(r) {
2441 if(r.responseText != '') {
2442 if(!confirm(SUGAR.language.get('app_strings','NTC_TEMPLATES_IS_USED') + r.responseText)) {
2446 document.MassUpdate.submit();
2450 url = "index.php?module=EmailTemplates&action=CheckDeletable&from=ListView&to_pdf=1&records="+ids;
2451 YAHOO.util.Connect.asyncRequest('POST',url, call_back,null);
2455 sugarListView.prototype.send_mass_update = function(mode, no_record_txt, del) {
2456 formValid = check_form('MassUpdate');
2457 if(!formValid && !del) return false;
2460 if (document.MassUpdate.select_entire_list &&
2461 document.MassUpdate.select_entire_list.value == 1)
2466 var ar = new Array();
2470 for(var wp = 0; wp < document.MassUpdate.elements.length; wp++) {
2471 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)+'$');
2472 //when the uid is already in document.MassUpdate.uid.value, we should not add it to ar.
2473 if(typeof document.MassUpdate.elements[wp].name != 'undefined'
2474 && document.MassUpdate.elements[wp].name == 'mass[]'
2475 && document.MassUpdate.elements[wp].checked
2476 && !reg_for_existing_uid.test(document.MassUpdate.uid.value)) {
2477 ar.push(document.MassUpdate.elements[wp].value);
2480 if(document.MassUpdate.uid.value != '') document.MassUpdate.uid.value += ',';
2481 document.MassUpdate.uid.value += ar.join(',');
2482 if(document.MassUpdate.uid.value == '') {
2483 alert(no_record_txt);
2486 if(typeof(current_admin_id)!='undefined' && document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'Users' && (document.MassUpdate.is_admin.value!='' || document.MassUpdate.status.value!='')) {
2487 var reg_for_current_admin_id = new RegExp('^'+current_admin_id+'[\s]*,|,[\s]*'+current_admin_id+'[\s]*,|,[\s]*'+current_admin_id+'$|^'+current_admin_id+'$');
2488 if(reg_for_current_admin_id.test(document.MassUpdate.uid.value)) {
2489 //if current user is admin, we should not allow massupdate the user_type and status of himself
2490 alert(SUGAR.language.get('Users','LBL_LAST_ADMIN_NOTICE'));
2496 var entireInput = document.createElement('input');
2497 entireInput.name = 'entire';
2498 entireInput.type = 'hidden';
2499 entireInput.value = 'index';
2500 document.MassUpdate.appendChild(entireInput);
2501 //confirm(no_record_txt);
2502 if(document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'Users' && (document.MassUpdate.is_admin.value!='' || document.MassUpdate.status.value!='')) {
2503 alert(SUGAR.language.get('Users','LBL_LAST_ADMIN_NOTICE'));
2509 if(!sugarListView.confirm_action(del))
2513 var deleteInput = document.createElement('input');
2514 deleteInput.name = 'Delete';
2515 deleteInput.type = 'hidden';
2516 deleteInput.value = true;
2517 document.MassUpdate.appendChild(deleteInput);
2518 if(document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'EmailTemplates') {
2519 check_used_email_templates();
2525 document.MassUpdate.submit();
2530 sugarListView.prototype.clear_all = function() {
2531 document.MassUpdate.uid.value = '';
2532 document.MassUpdate.select_entire_list.value = 0;
2533 sugarListView.check_all(document.MassUpdate, 'mass[]', false);
2534 $(document.MassUpdate.massall).each(function(){
2535 $(this).attr('checked', false).attr('disabled', false);
2537 sugarListView.update_count(0);
2538 sugarListView.prototype.toggleSelected();
2541 sListView = new sugarListView();
2542 // -- end sugarListView class
2544 // format and unformat numbers
2545 function unformatNumber(n, num_grp_sep, dec_sep) {
2546 var x=unformatNumberNoParse(n, num_grp_sep, dec_sep);
2549 return parseFloat(x);
2554 function unformatNumberNoParse(n, num_grp_sep, dec_sep) {
2555 if(typeof num_grp_sep == 'undefined' || typeof dec_sep == 'undefined') return n;
2556 n = n ? n.toString() : '';
2559 if(num_grp_sep != '')
2561 num_grp_sep_re = new RegExp('\\'+num_grp_sep, 'g');
2562 n = n.replace(num_grp_sep_re, '');
2565 n = n.replace(dec_sep, '.');
2567 if(typeof CurrencySymbols != 'undefined') {
2568 // Need to strip out the currency symbols from the start.
2569 for ( var idx in CurrencySymbols ) {
2570 n = n.replace(CurrencySymbols[idx], '');
2578 // round parameter can be negative for decimal, precision has to be postive
2579 function formatNumber(n, num_grp_sep, dec_sep, round, precision) {
2580 if(typeof num_grp_sep == 'undefined' || typeof dec_sep == 'undefined') return n;
2581 n = n ? n.toString() : '';
2582 if(n.split) n = n.split('.');
2585 if(n.length > 2) return n.join('.'); // that's not a num!
2587 if(typeof round != 'undefined') {
2588 if(round > 0 && n.length > 1) { // round to decimal
2589 n[1] = parseFloat('0.' + n[1]);
2590 n[1] = Math.round(n[1] * Math.pow(10, round)) / Math.pow(10, round);
2591 n[1] = n[1].toString().split('.')[1];
2593 if(round <= 0) { // round to whole number
2594 n[0] = Math.round(parseInt(n[0],10) * Math.pow(10, round)) / Math.pow(10, round);
2599 if(typeof precision != 'undefined' && precision >= 0) {
2600 if(n.length > 1 && typeof n[1] != 'undefined') n[1] = n[1].substring(0, precision); // cut off precision
2602 if(n[1].length < precision) {
2603 for(var wp = n[1].length; wp < precision; wp++) n[1] += '0';
2607 regex = /(\d+)(\d{3})/;
2608 while(num_grp_sep != '' && regex.test(n[0])) n[0] = n[0].toString().replace(regex, '$1' + num_grp_sep + '$2');
2609 return n[0] + (n.length > 1 && n[1] != '' ? dec_sep + n[1] : '');
2612 // --- begin ajax status class
2613 SUGAR.ajaxStatusClass = function() {};
2614 SUGAR.ajaxStatusClass.prototype.statusDiv = null;
2615 SUGAR.ajaxStatusClass.prototype.oldOnScroll = null;
2616 SUGAR.ajaxStatusClass.prototype.shown = false; // state of the status window
2618 // reposition the status div, top and centered
2619 SUGAR.ajaxStatusClass.prototype.positionStatus = function() {
2620 //this.statusDiv.style.top = document.body.scrollTop + 8 + 'px';
2621 statusDivRegion = YAHOO.util.Dom.getRegion(this.statusDiv);
2622 statusDivWidth = statusDivRegion.right - statusDivRegion.left;
2623 this.statusDiv.style.left = YAHOO.util.Dom.getViewportWidth() / 2 - statusDivWidth / 2 + 'px';
2626 // private func, create the status div
2627 SUGAR.ajaxStatusClass.prototype.createStatus = function(text) {
2628 statusDiv = document.createElement('div');
2629 statusDiv.className = 'dataLabel';
2630 statusDiv.id = 'ajaxStatusDiv';
2631 document.body.appendChild(statusDiv);
2632 this.statusDiv = document.getElementById('ajaxStatusDiv');
2635 // public - show the status div with text
2636 SUGAR.ajaxStatusClass.prototype.showStatus = function(text) {
2637 if(!this.statusDiv) {
2638 this.createStatus(text);
2641 this.statusDiv.style.display = '';
2643 this.statusDiv.innerHTML = ' <b>' + text + '</b> ';
2644 this.positionStatus();
2647 this.statusDiv.style.display = '';
2648 if(window.onscroll) this.oldOnScroll = window.onscroll; // save onScroll
2649 window.onscroll = this.positionStatus;
2654 SUGAR.ajaxStatusClass.prototype.hideStatus = function(text) {
2655 if(!this.shown) return;
2657 if(this.oldOnScroll) window.onscroll = this.oldOnScroll;
2658 else window.onscroll = '';
2659 this.statusDiv.style.display = 'none';
2662 SUGAR.ajaxStatusClass.prototype.flashStatus = function(text, time){
2663 this.showStatus(text);
2664 window.setTimeout('ajaxStatus.hideStatus();', time);
2668 var ajaxStatus = new SUGAR.ajaxStatusClass();
2669 // --- end ajax status class
2672 * Unified Search Advanced - for global search
2674 SUGAR.unifiedSearchAdvanced = function() {
2684 SUGAR.unifiedSearchAdvanced.usa_div = document.getElementById('unified_search_advanced_div');
2685 SUGAR.unifiedSearchAdvanced.usa_img = document.getElementById('unified_search_advanced_img');
2687 if(!SUGAR.unifiedSearchAdvanced.usa_div || !SUGAR.unifiedSearchAdvanced.usa_img) return;
2688 var attributes = { height: { to: 300 } };
2689 SUGAR.unifiedSearchAdvanced.anim_open = new YAHOO.util.Anim('unified_search_advanced_div', attributes );
2690 SUGAR.unifiedSearchAdvanced.anim_open.duration = 0.75;
2691 SUGAR.unifiedSearchAdvanced.anim_close = new YAHOO.util.Anim('unified_search_advanced_div', { height: {to: 0} } );
2692 SUGAR.unifiedSearchAdvanced.anim_close.duration = 0.75;
2693 //SUGAR.unifiedSearchAdvanced.anim_close.onComplete.subscribe(function() {SUGAR.unifiedSearchAdvanced.usa_div.style.display = 'none'});
2695 SUGAR.unifiedSearchAdvanced.usa_img._x = YAHOO.util.Dom.getX(SUGAR.unifiedSearchAdvanced.usa_img);
2696 SUGAR.unifiedSearchAdvanced.usa_img._y = YAHOO.util.Dom.getY(SUGAR.unifiedSearchAdvanced.usa_img);
2699 SUGAR.unifiedSearchAdvanced.usa_open = false;
2700 SUGAR.unifiedSearchAdvanced.usa_content = null;
2702 YAHOO.util.Event.addListener('unified_search_advanced_img', 'click', SUGAR.unifiedSearchAdvanced.get_content);
2705 get_content: function(e)
2707 query_string = trim(document.getElementById('query_string').value);
2708 if(query_string != '')
2710 window.location.href = 'index.php?module=Home&action=UnifiedSearch&query_string=' + query_string;
2712 window.location.href = 'index.php?module=Home&action=UnifiedSearch&form_only=true';
2716 animate: function(data) {
2717 ajaxStatus.hideStatus();
2720 SUGAR.unifiedSearchAdvanced.usa_content = data.responseText;
2721 SUGAR.unifiedSearchAdvanced.usa_div.innerHTML = SUGAR.unifiedSearchAdvanced.usa_content;
2723 if(SUGAR.unifiedSearchAdvanced.usa_open) {
2724 document.UnifiedSearch.advanced.value = 'false';
2725 SUGAR.unifiedSearchAdvanced.anim_close.animate();
2728 document.UnifiedSearch.advanced.value = 'true';
2729 SUGAR.unifiedSearchAdvanced.usa_div.style.display = '';
2730 YAHOO.util.Dom.setX(SUGAR.unifiedSearchAdvanced.usa_div, SUGAR.unifiedSearchAdvanced.usa_img._x - 90);
2731 YAHOO.util.Dom.setY(SUGAR.unifiedSearchAdvanced.usa_div, SUGAR.unifiedSearchAdvanced.usa_img._y + 15);
2732 SUGAR.unifiedSearchAdvanced.anim_open.animate();
2734 SUGAR.unifiedSearchAdvanced.usa_open = !SUGAR.unifiedSearchAdvanced.usa_open;
2739 checkUsaAdvanced: function() {
2740 if(document.UnifiedSearch.advanced.value == 'true') {
2741 document.UnifiedSearchAdvanced.query_string.value = document.UnifiedSearch.query_string.value;
2742 document.UnifiedSearchAdvanced.submit();
2749 if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.unifiedSearchAdvanced.init);
2754 * Toggles the header
2756 toggleHeader : function() {
2757 var h = document.getElementById('header');
2761 if(h.style.display == 'none') {
2762 h.style.display = '';
2764 h.style.display = 'none';
2768 alert(SUGAR.language.get("app_strings", "ERR_NO_HEADER_ID"));
2775 * General Sugar Utils
2777 SUGAR.util = function () {
2778 var additionalDetailsCache;
2779 var additionalDetailsCalls;
2780 var additionalDetailsRpcCall;
2783 getAndRemove : function (el) {
2784 if (YAHOO && YAHOO.util && YAHOO.util.Dom)
2785 el = YAHOO.util.Dom.get(el);
2786 else if (typeof (el) == "string")
2787 el = document.getElementById(el);
2788 if (el && el.parentNode)
2789 el.parentNode.removeChild(el);
2793 paramsToUrl : function (params) {
2796 url += i + "=" + params[i] + "&";
2800 evalScript:function(text){
2802 var waitUntilLoaded = function(){
2803 SUGAR.evalScript_waitCount--;
2804 if (SUGAR.evalScript_waitCount == 0) {
2805 var headElem = document.getElementsByTagName('head')[0];
2806 for ( var i = 0; i < SUGAR.evalScript_evalElem.length; i++) {
2807 var tmpElem = document.createElement('script');
2808 tmpElem.type = 'text/javascript';
2809 tmpElem.text = SUGAR.evalScript_evalElem[i];
2810 headElem.appendChild(tmpElem);
2815 var tmpElem = document.createElement('div');
2816 tmpElem.innerHTML = text;
2817 var results = tmpElem.getElementsByTagName('script');
2818 if (results == null) {
2819 // No scripts found, bail out
2823 var headElem = document.getElementsByTagName('head')[0];
2825 SUGAR.evalScript_waitCount = 0;
2826 SUGAR.evalScript_evalElem = new Array();
2827 for (var i = 0; i < results.length; i++) {
2828 if (typeof(results[i]) != 'object') {
2831 tmpElem = document.createElement('script');
2832 tmpElem.type = 'text/javascript';
2833 if (results[i].src != null && results[i].src != '') {
2834 tmpElem.src = results[i].src;
2836 // Need to defer execution of these scripts until the
2837 // required javascript files are fully loaded
2838 SUGAR.evalScript_evalElem[SUGAR.evalScript_evalElem.length] = results[i].text;
2841 tmpElem.addEventListener('load', waitUntilLoaded);
2842 SUGAR.evalScript_waitCount++;
2843 headElem.appendChild(tmpElem);
2845 // Add some code to handle pages without any external scripts
2846 SUGAR.evalScript_waitCount++;
2849 // Don't try and process things the IE way
2853 var objRegex = /<\s*script([^>]*)>((.|\s|\v|\0)*?)<\s*\/script\s*>/igm;
2855 var result = objRegex.exec(text);
2856 while(result && result.index > lastIndex){
2857 lastIndex = result.index
2859 var script = document.createElement('script');
2860 script.type= 'text/javascript';
2861 if(result[1].indexOf("src=") > -1){
2862 var srcRegex = /.*src=['"]([a-zA-Z0-9_\-\&\/\.\?=:-]*)['"].*/igm;
2863 var srcResult = result[1].replace(srcRegex, '$1');
2864 script.src = srcResult;
2866 script.text = result[2];
2868 document.body.appendChild(script);
2871 if(typeof(console) != "undefined" && typeof(console.log) == "function")
2873 console.log("error adding script");
2875 console.log(result);
2878 result = objRegex.exec(text);
2882 * Gets the sidebar object
2883 * @return object pointer to the sidebar element
2885 getLeftColObj: function() {
2886 leftColObj = document.getElementById('leftCol');
2887 while(leftColObj.nodeName != 'TABLE') {
2888 leftColObj = leftColObj.firstChild;
2890 leftColTable = leftColObj;
2891 leftColTd = leftColTable.getElementsByTagName('td')[0];
2892 leftColTdRegion = YAHOO.util.Dom.getRegion(leftColTd);
2893 leftColTd.style.width = (leftColTdRegion.right - leftColTdRegion.left) + 'px';
2898 * Fills the shortcut menu placeholders w/ actual content
2899 * Call this on load event
2901 * @param shortcutContent Array array of content to fill in
2903 fillShortcuts: function(e, shortcutContent) {
2906 // don't do this if leftCol isn't available
2907 if (document.getElementById('leftCol') == undefined) { return; }
2909 spans = document.getElementById('leftCol').getElementsByTagName('span');
2910 hideCol = document.getElementById('HideMenu').getElementsByTagName('span');
2911 w = spans.length + 1;
2913 spans[w] = hideCol[i];
2916 for(je in shortcutContent) {
2918 if(typeof spans[wp].innerHTML != 'undefined' && spans[wp].innerHTML == ('wp_shortcut_fill_' + je)) {
2919 if(typeof spans[wp].parentNode.parentNode == 'object') {
2920 if(typeof spans[wp].parentNode.parentNode.onclick != 'undefined') {
2921 spans[wp].parentNode.parentNode.onclick = null;
2923 // If the wp_shortcut span is contained by an A tag, replace the A with a DIV.
2924 if(spans[wp].parentNode.tagName == 'A' && !isIE) {
2925 var newDiv = document.createElement('DIV');
2926 var parentAnchor = spans[wp].parentNode;
2928 spans[wp].parentNode.parentNode.style.display = 'none';
2930 // Copy styles over to the new container div
2931 if(window.getComputedStyle) {
2932 var parentStyle = window.getComputedStyle(parentAnchor, '');
2933 for(var styleName in parentStyle) {
2934 if(typeof parentStyle[styleName] != 'function'
2935 && styleName != 'display'
2936 && styleName != 'borderWidth'
2937 && styleName != 'visibility') {
2939 newDiv.style[styleName] = parentStyle[styleName];
2941 // Catches .length and .parentRule, and others
2947 // Replace the A with the DIV
2948 newDiv.appendChild(spans[wp]);
2949 parentAnchor.parentNode.replaceChild(newDiv, parentAnchor);
2951 spans[wp].parentNode.parentNode.style.display = '';
2954 spans[wp].innerHTML = shortcutContent[je]; // fill w/ content
2955 if(spans[wp].style) spans[wp].style.display = '';
2961 * Make an AJAX request.
2963 * @param url string resource to load
2964 * @param theDiv string id of element to insert loaded data into
2965 * @param postForm string if set, a POST request will be made to resource specified by url using the form named by postForm
2966 * @param callback string name of function to invoke after HTTP response is recieved
2967 * @param callbackParam any parameter to pass to callback when invoked
2968 * @param appendMode bool if true, HTTP response will be appended to the contents of theDiv, or else contents will be overriten.
2970 retrieveAndFill: function(url, theDiv, postForm, callback, callbackParam, appendMode) {
2971 if(typeof theDiv == 'string') {
2973 theDiv = document.getElementById(theDiv);
2980 var success = function(data) {
2981 if (typeof theDiv != 'undefined' && theDiv != null)
2984 if (typeof appendMode != 'undefined' && appendMode)
2986 theDiv.innerHTML += data.responseText;
2990 theDiv.innerHTML = data.responseText;
2997 if (typeof callback != 'undefined' && callback != null) callback(callbackParam);
3000 if(typeof postForm == 'undefined' || postForm == null) {
3001 var cObj = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
3004 YAHOO.util.Connect.setForm(postForm);
3005 var cObj = YAHOO.util.Connect.asyncRequest('POST', url, {success: success, failure: success});
3008 checkMaxLength: function() { // modified from http://www.quirksmode.org/dom/maxlength.html
3009 var maxLength = this.getAttribute('maxlength');
3010 var currentLength = this.value.length;
3011 if (currentLength > maxLength) {
3012 this.value = this.value.substring(0, maxLength);
3017 * Adds maxlength attribute to textareas
3019 setMaxLength: function() { // modified from http://www.quirksmode.org/dom/maxlength.html
3020 var x = document.getElementsByTagName('textarea');
3021 for (var i=0;i<x.length;i++) {
3022 if (x[i].getAttribute('maxlength')) {
3023 x[i].onkeyup = x[i].onchange = SUGAR.util.checkMaxLength;
3030 * Renders Query UI Help Dialog
3032 showHelpTips: function(el,helpText,myPos,atPos,id) {
3033 if(myPos == undefined || myPos == "") {
3036 if(atPos == undefined || atPos == "") {
3037 atPos = "right top";
3040 var pos = $(el).offset(),
3041 ofWidth = $(el).width(),
3042 elmId = id || 'helpTip' + pos.left + '_' + ofWidth,
3043 $dialog = elmId ? ( $("#"+elmId).length > 0 ? $("#"+elmId) : $('<div></div>').attr("id", elmId) ) : $('<div></div>');
3044 $dialog.html(helpText)
3047 title: SUGAR.language.get('app_strings', 'LBL_HELP'),
3056 var width = $dialog.dialog( "option", "width" );
3058 if((pos.left + ofWidth) - 40 < width) {
3059 $dialog.dialog("option","position",{my: 'left top',at: 'right top',of: $(el)}) ;
3061 $dialog.dialog('open');
3062 $(".ui-dialog").appendTo("#content");
3066 getStaticAdditionalDetails: function(el, body, caption, show_buttons) {
3067 if(typeof show_buttons == "undefined") {
3068 show_buttons = false;
3071 $(".ui-dialog").find(".open").dialog("close");
3073 var $dialog = $('<div class="open"></div>')
3087 $(".ui-dialog").find('.ui-dialog-titlebar-close').css("display","none");
3088 $(".ui-dialog").find('.ui-dialog-title').css("width","100%");
3092 var width = $dialog.dialog( "option", "width" );
3093 var pos = $(el).offset();
3094 var ofWidth = $(el).width();
3096 if((pos.left + ofWidth) - 40 < width) {
3097 $dialog.dialog("option","position",{my: 'left top',at: 'right top',of: $(el)}) ;
3100 $dialog.dialog('open');
3101 $(".ui-dialog").appendTo("#content");
3105 closeStaticAdditionalDetails: function() {
3106 $(".ui-dialog").find(".open").dialog("close");
3109 * Retrieves additional details dynamically
3111 getAdditionalDetails: function(bean, id, spanId, show_buttons) {
3112 if(typeof show_buttons == "undefined")
3113 show_buttons = false;
3114 var el = '#'+spanId;
3116 oReturn = function(body, caption, width, theme) {
3118 $(".ui-dialog").find(".open").dialog("close");
3120 var $dialog = $('<div class="open"></div>')
3133 $(".ui-dialog").find('.ui-dialog-titlebar-close').css("display","none");
3134 $(".ui-dialog").find('.ui-dialog-title').css("width","100%");
3137 var width = $dialog.dialog( "option", "width" );
3138 var pos = $(el).offset();
3139 var ofWidth = $(el).width();
3141 if((pos.left + ofWidth) - 40 < width) {
3142 $dialog.dialog("option","position",{my: 'left top',at: 'right top',of: $(el)}) ;
3145 $dialog.dialog('open');
3146 $(".ui-dialog").appendTo("#content");
3149 success = function(data) {
3150 eval(data.responseText);
3152 SUGAR.util.additionalDetailsCache[id] = new Array();
3153 SUGAR.util.additionalDetailsCache[id]['body'] = result['body'];
3154 SUGAR.util.additionalDetailsCache[id]['caption'] = result['caption'];
3155 SUGAR.util.additionalDetailsCache[id]['width'] = result['width'];
3156 SUGAR.util.additionalDetailsCache[id]['theme'] = result['theme'];
3157 ajaxStatus.hideStatus();
3158 return oReturn(SUGAR.util.additionalDetailsCache[id]['body'], SUGAR.util.additionalDetailsCache[id]['caption'], SUGAR.util.additionalDetailsCache[id]['width'], SUGAR.util.additionalDetailsCache[id]['theme']);
3161 if(typeof SUGAR.util.additionalDetailsCache[id] != 'undefined')
3162 return oReturn(SUGAR.util.additionalDetailsCache[id]['body'], SUGAR.util.additionalDetailsCache[id]['caption'], SUGAR.util.additionalDetailsCache[id]['width'], SUGAR.util.additionalDetailsCache[id]['theme']);
3164 if(typeof SUGAR.util.additionalDetailsCalls[id] != 'undefined') // call already in progress
3166 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_LOADING'));
3167 url = 'index.php?to_pdf=1&module=Home&action=AdditionalDetailsRetrieve&bean=' + bean + '&id=' + id;
3169 url += '&show_buttons=true';
3170 SUGAR.util.additionalDetailsCalls[id] = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
3174 SUGAR.util.additionalDetailsRpcCall = window.setTimeout('go()', 250);
3176 clearAdditionalDetailsCall: function() {
3177 if(typeof SUGAR.util.additionalDetailsRpcCall == 'number') window.clearTimeout(SUGAR.util.additionalDetailsRpcCall);
3180 * A function that extends functionality from parent to child.
3182 extend : function(subc, superc, overrides) {
3183 subc.prototype = new superc; // set the superclass
3186 for (var i in overrides) subc.prototype[i] = overrides[i];
3189 hrefURL : function(url) {
3191 // IE needs special treatment since otherwise it would not pass Referer
3192 var trampoline = document.createElement('a');
3193 trampoline.href = url;
3194 document.body.appendChild(trampoline);
3196 document.body.removeChild(trampoline);
3198 document.location.href = url;
3202 openWindow : function(URL, windowName, windowFeatures) {
3204 // IE needs special treatment since otherwise it would not pass Referer
3205 win = window.open('', windowName, windowFeatures);
3206 var trampoline = document.createElement('a');
3207 trampoline.href = URL;
3208 trampoline.target = windowName;
3209 document.body.appendChild(trampoline);
3211 document.body.removeChild(trampoline);
3213 win = window.open(URL, windowName, windowFeatures);
3217 //Reset the scroll on the window
3222 //Based on YUI onAvailible, but will use any boolean function instead of an ID
3223 doWhen : function(condition, fn, params, scope)
3225 this._doWhenStack.push({
3229 overrideContext: scope
3232 this._doWhenretryCount = 50;
3233 this._startDoWhenInterval();
3236 _startDoWhenInterval : function(){
3237 if (!this._doWhenInterval) {
3238 this._doWhenInterval = YAHOO.lang.later(50, this, this._doWhenCheck, null, true);
3242 _doWhenInterval : false,
3243 _doWhenCheck : function() {
3244 if (this._doWhenStack.length === 0) {
3245 this._doWhenretryCount = 0;
3246 if (this._doWhenInterval) {
3247 // clearInterval(this._interval);
3248 this._doWhenInterval.cancel();
3249 this._doWhenInterval = null;
3254 if (this._doWhenLocked) {
3259 // Hold off if DOMReady has not fired and check current
3260 // readyState to protect against the IE operation aborted
3262 if (!YAHOO.util.Event.DOMReady) {
3263 this._startDoWhenInterval();
3268 this._doWhenLocked = true;
3271 // keep trying until after the page is loaded. We need to
3272 // check the page load state prior to trying to bind the
3273 // elements so that we can be certain all elements have been
3274 // tested appropriately
3275 var tryAgain = YAHOO.util.Event.DOMReady;
3277 tryAgain = (this._doWhenretryCount > 0 && this._doWhenStack.length > 0);
3283 var executeItem = function (context, item) {
3284 if (item.overrideContext) {
3285 if (item.overrideContext === true) {
3288 context = item.overrideContext;
3292 item.fn.call(context, item.obj);
3296 var i, len, item, test;
3298 // onAvailable onContentReady
3299 for (i=0, len=this._doWhenStack.length; i<len; i=i+1) {
3300 item = this._doWhenStack[i];
3303 if ((typeof(test) == "string" && eval(test)) || (typeof(test) == "function" && test())) {
3304 executeItem(this, item);
3305 this._doWhenStack[i] = null;
3308 notAvail.push(item);
3313 this._doWhenretryCount--;
3316 for (i=this._doWhenStack.length-1; i>-1; i--) {
3317 item = this._doWhenStack[i];
3318 if (!item || !item.check) {
3319 this._doWhenStack.splice(i, 1);
3322 this._startDoWhenInterval();
3324 if (this._doWhenInterval) {
3325 // clearInterval(this._interval);
3326 this._doWhenInterval.cancel();
3327 this._doWhenInterval = null;
3330 this._doWhenLocked = false;
3332 buildAccessKeyLabels : function() {
3333 if (typeof(Y.env.ua) !== 'undefined'){
3335 browserOS = Y.env.ua['os'];
3336 isIE = Y.env.ua['ie'];
3337 isCR = Y.env.ua['chrome'];
3338 isFF = Y.env.ua['gecko'];
3339 isWK = Y.env.ua['webkit'];
3340 isOP = Y.env.ua['opera'];
3343 //first determine the OS
3344 if(browserOS=='macintosh'){
3345 //we got a mac, lets use the mac specific commands while we check the browser
3347 //IE on a Mac? Not possible, but let's assign alt anyways for completions sake
3348 controlKey = 'Alt+';
3350 //Chrome or safari on a mac
3351 controlKey = 'Ctrl+Opt+';
3354 controlKey = 'Shift+Esc: ';
3356 //default FF and everything else on a mac
3357 controlKey = 'Ctrl+';
3360 //this is not a mac so let's use the windows/unix commands while we check the browser
3362 //FF on windows/unix
3363 controlKey = 'Alt+Shift+';
3365 //Opera on windows/unix
3366 controlKey = 'Shift+Esc: ';
3368 //this is the default for safari, IE and Chrome
3369 //if this is webkit and is NOT google, then we are most likely looking at Safari
3370 controlKey = 'Alt+';
3375 //now lets retrieve all elements of type input
3376 allButtons = document.getElementsByTagName('input');
3377 //iterate through list and modify title if the accesskey is not empty
3378 for(i=0;i<allButtons.length;i++){
3379 if(allButtons[i].getAttribute('accesskey') && allButtons[i].getAttribute('type') && allButtons[i].getAttribute('type')=='button'){
3380 allButtons[i].setAttribute('title',allButtons[i].getAttribute('title')+' ['+controlKey+allButtons[i].getAttribute('accesskey')+']');
3383 //now change the text in the help div
3384 $("#shortcuts_dialog").html(function(i, text) {
3385 return text.replace(/Alt\+/g,controlKey);
3387 }// end if (typeof(Y.env.ua) !== 'undefined')
3388 }//end buildAccessKeyLabels()
3391 SUGAR.util.additionalDetailsCache = new Array();
3392 SUGAR.util.additionalDetailsCalls = new Array();
3393 if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.util.setMaxLength); // allow textareas to obey maxlength attrib
3395 SUGAR.savedViews = function() {
3396 var selectedOrderBy;
3397 var selectedSortOrder;
3400 var columnsMeta; // meta data for the display columns
3403 setChooser: function() {
3405 var displayColumnsDef = new Array();
3406 var hideTabsDef = new Array();
3408 var left_td = document.getElementById('display_tabs_td');
3409 if(typeof left_td == 'undefined' || left_td == null) return; // abort!
3410 var right_td = document.getElementById('hide_tabs_td');
3412 var displayTabs = left_td.getElementsByTagName('select')[0];
3413 var hideTabs = right_td.getElementsByTagName('select')[0];
3415 for(i = 0; i < displayTabs.options.length; i++) {
3416 displayColumnsDef.push(displayTabs.options[i].value);
3419 if(typeof hideTabs != 'undefined') {
3420 for(i = 0; i < hideTabs.options.length; i++) {
3421 hideTabsDef.push(hideTabs.options[i].value);
3424 if (!SUGAR.savedViews.clearColumns)
3425 document.getElementById('displayColumnsDef').value = displayColumnsDef.join('|');
3426 document.getElementById('hideTabsDef').value = hideTabsDef.join('|');
3429 select: function(saved_search_select) {
3430 for(var wp = 0; wp < document.search_form.saved_search_select.options.length; wp++) {
3431 if(typeof document.search_form.saved_search_select.options[wp].value != 'undefined' &&
3432 document.search_form.saved_search_select.options[wp].value == saved_search_select) {
3433 document.search_form.saved_search_select.selectedIndex = wp;
3434 document.search_form.ss_delete.style.display = '';
3435 document.search_form.ss_update.style.display = '';
3439 saved_search_action: function(action, delete_lang) {
3440 if(action == 'delete') {
3441 if(!confirm(delete_lang)) return;
3443 if(action == 'save') {
3444 if(document.search_form.saved_search_name.value.replace(/^\s*|\s*$/g, '') == '') {
3445 alert(SUGAR.language.get('app_strings', 'LBL_SAVED_SEARCH_ERROR'));
3450 // This check is needed for the Activities module (Calls/Meetings/Tasks).
3451 if (document.search_form.saved_search_action)
3453 document.search_form.saved_search_action.value = action;
3454 document.search_form.search_module.value = document.search_form.module.value;
3455 document.search_form.module.value = 'SavedSearch';
3456 // Bug 31922 - Make sure to specify that we want to hit the index view here of
3457 // the SavedSearch module, since the ListView doesn't have the logic to save the
3458 // search and redirect back
3459 document.search_form.action.value = 'index';
3461 SUGAR.ajaxUI.submitForm(document.search_form);
3463 shortcut_select: function(selectBox, module) {
3465 selecturl = 'index.php?module=SavedSearch&search_module=' + module + '&action=index&saved_search_select=' + selectBox.options[selectBox.selectedIndex].value
3466 //add searchFormTab to url if it is available. This determines what tab to render
3467 if(typeof(document.getElementById('searchFormTab'))!='undefined'){
3468 selecturl = selecturl + '&searchFormTab=' + document.search_form.searchFormTab.value;
3470 //add showSSDIV to url if it is available. This determines whether saved search sub form should
3471 //be rendered open or not
3472 if(document.getElementById('showSSDIV') && typeof(document.getElementById('showSSDIV') !='undefined')){
3473 selecturl = selecturl + '&showSSDIV='+document.getElementById('showSSDIV').value;
3475 //use created url to navigate
3476 document.location.href = selecturl;
3478 handleForm: function() {
3479 SUGAR.tabChooser.movementCallback = function(left_side, right_side) {
3480 while(document.getElementById('orderBySelect').childNodes.length != 0) { // clear out order by options
3481 document.getElementById('orderBySelect').removeChild(document.getElementById('orderBySelect').lastChild);
3484 var selectedIndex = 0;
3485 var nodeCount = -1; // need this because the counter i also includes "undefined" nodes
3486 // which was breaking Calls and Meetings
3488 for(i in left_side.childNodes) { // fill in order by options
3489 if(typeof left_side.childNodes[i].nodeName != 'undefined' &&
3490 left_side.childNodes[i].nodeName.toLowerCase() == 'option' &&
3491 typeof SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value] != 'undefined' && // check if column is sortable
3492 typeof SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value]['sortable'] == 'undefined' &&
3493 SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value]['sortable'] != false) {
3495 optionNode = document.createElement('option');
3496 optionNode.value = left_side.childNodes[i].value;
3497 optionNode.innerHTML = left_side.childNodes[i].innerHTML;
3498 document.getElementById('orderBySelect').appendChild(optionNode);
3499 if(optionNode.value == SUGAR.savedViews.selectedOrderBy)
3500 selectedIndex = nodeCount;
3503 // Firefox needs this to be set after all the option nodes are created.
3504 document.getElementById('orderBySelect').selectedIndex = selectedIndex;
3506 SUGAR.tabChooser.movementCallback(document.getElementById('display_tabs_td').getElementsByTagName('select')[0]);
3508 // This check is needed for the Activities module (Calls/Meetings/Tasks).
3509 if (document.search_form.orderBy)
3510 document.search_form.orderBy.options.value = SUGAR.savedViews.selectedOrderBy;
3513 if(SUGAR.savedViews.selectedSortOrder == 'DESC') document.getElementById('sort_order_desc_radio').checked = true;
3514 else document.getElementById('sort_order_asc_radio').checked = true;
3519 SUGAR.searchForm = function() {
3522 // searchForm tab selector util
3523 searchFormSelect: function(view, previousView) {
3524 var module = view.split('|')[0];
3525 var theView = view.split('|')[1];
3527 var handleDisplay = function() { // hide other divs
3528 document.search_form.searchFormTab.value = theView;
3529 patt = module+"(.*)SearchForm$";
3530 divId=document.search_form.getElementsByTagName('div');
3531 // Hide all the search forms and retrive the name of the previous search tab (useful for the first load because previousView is empty)
3532 for (i=0;i<divId.length;i++){
3533 if(divId[i].id.match(module)==module){
3534 if(divId[i].id.match('SearchForm')=='SearchForm'){
3535 if(document.getElementById(divId[i].id).style.display == ''){
3536 previousTab=divId[i].id.match(patt)[1];
3538 document.getElementById(divId[i].id).style.display = 'none';
3543 //clear thesearch form accesekeys and reset them to the appropriate link
3544 adv = document.getElementById('advanced_search_link');
3545 bas = document.getElementById('basic_search_link');
3546 adv.setAttribute('accesskey','');
3547 bas.setAttribute('accesskey','');
3548 a_key = SUGAR.language.get("app_strings", "LBL_ADV_SEARCH_LNK_KEY");
3550 //reset the ccesskey based on theview
3551 if(theView === 'advanced_search'){
3553 bas.setAttribute('accesskey',a_key);
3555 adv.setAttribute('accesskey',a_key);
3558 // show the good search form.
3559 document.getElementById(module + theView + 'SearchForm').style.display = '';
3560 //if its not the first tab show there is a previous tab.
3562 thepreviousView=previousView.split('|')[1];
3565 thepreviousView=previousTab;
3567 thepreviousView=thepreviousView.replace(/_search/, "");
3568 // Process to retrieve the completed field from one tab to an other.
3569 for(num in document.search_form.elements) {
3570 if(document.search_form.elements[num]) {
3571 el = document.search_form.elements[num];
3572 pattern="^(.*)_"+thepreviousView+"$";
3573 if(typeof el.type != 'undefined' && typeof el.name != 'undefined' && el.name.match(pattern)) {
3574 advanced_input_name = el.name.match(pattern)[1]; // strip
3575 advanced_input_name = advanced_input_name+"_"+theView.replace(/_search/, "");
3576 if(typeof document.search_form[advanced_input_name] != 'undefined') // if advanced input of same name exists
3577 SUGAR.searchForm.copyElement(advanced_input_name, el);
3583 // if tab is not cached
3584 if(document.getElementById(module + theView + 'SearchForm').innerHTML == '') {
3585 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_LOADING'));
3586 var success = function(data) {
3587 document.getElementById(module + theView + 'SearchForm').innerHTML = data.responseText;
3589 SUGAR.util.evalScript(data.responseText);
3590 // pass script variables to global scope
3591 if(theView == 'saved_views') {
3592 if(typeof columnsMeta != 'undefined') SUGAR.savedViews.columnsMeta = columnsMeta;
3593 if(typeof selectedOrderBy != 'undefined') SUGAR.savedViews.selectedOrderBy = selectedOrderBy;
3594 if(typeof selectedSortOrder != 'undefined') SUGAR.savedViews.selectedSortOrder = selectedSortOrder;
3599 ajaxStatus.hideStatus();
3601 url = 'index.php?module=' + module + '&action=index&search_form_only=true&to_pdf=true&search_form_view=' + theView;
3603 //check to see if tpl has been specified. If so then pass location through url string
3605 if(document.getElementById('search_tpl') !=null && typeof(document.getElementById('search_tpl')) != 'undefined'){
3606 tpl = document.getElementById('search_tpl').value;
3607 if(tpl != ''){url += '&search_tpl='+tpl;}
3610 if(theView == 'saved_views') // handle the tab chooser
3611 url += '&displayColumns=' + SUGAR.savedViews.displayColumns + '&hideTabs=' + SUGAR.savedViews.hideTabs + '&orderBy=' + SUGAR.savedViews.selectedOrderBy + '&sortOrder=' + SUGAR.savedViews.selectedSortOrder;
3613 var cObj = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
3615 else { // that form already retrieved
3620 // copies one input to another
3621 copyElement: function(inputName, copyFromElement) {
3622 switch(copyFromElement.type) {
3625 document.search_form[inputName].value = copyFromElement.value;
3629 // This function is here to clear the form, instead of "resubmitting it
3630 clear_form: function(form, skipElementNames) {
3631 var elemList = form.elements;
3635 for( var i = 0; i < elemList.length ; i++ ) {
3637 if ( typeof(elem.type) == 'undefined' ) {
3641 if ( typeof(elem.type) != 'undefined' && typeof(skipElementNames) != 'undefined'
3642 && SUGAR.util.arrayIndexOf(skipElementNames, elem.name) != -1 )
3647 elemType = elem.type.toLowerCase();
3649 if ( elemType == 'text' || elemType == 'textarea' || elemType == 'password' ) {
3652 else if ( elemType == 'select' || elemType == 'select-one' || elemType == 'select-multiple' ) {
3653 // We have, what I hope, is a select box, time to unselect all options
3654 var optionList = elem.options;
3656 if (optionList.length > 0) {
3657 optionList[0].selected = "selected";
3660 for ( var ii = 0 ; ii < optionList.length ; ii++ ) {
3661 optionList[ii].selected = false;
3664 else if ( elemType == 'radio' || elemType == 'checkbox' ) {
3665 elem.checked = false;
3666 elem.selected = false;
3668 else if ( elemType == 'hidden' ) {
3669 // We only want to reset the hidden values that link to the select boxes.
3670 // _c custom field kludge added to fix Bug 41384
3671 if ( ( elem.name.length > 3 && elem.name.substring(elem.name.length-3) == '_id' )
3672 || ((elem.name.length > 9) && (elem.name.substring(elem.name.length - 9) == '_id_basic'))
3673 || ( elem.name.length > 12 && elem.name.substring(elem.name.length-12) == '_id_advanced' )
3674 || ( elem.name.length > 2 && elem.name.substring(elem.name.length-2) == '_c' )
3675 || ((elem.name.length > 8) && (elem.name.substring(elem.name.length - 8) == '_c_basic'))
3676 || ( elem.name.length > 11 && elem.name.substring(elem.name.length-11) == '_c_advanced' ) )
3682 SUGAR.savedViews.clearColumns = true;
3686 // Code for the column/tab chooser used on homepage and in admin section
3687 SUGAR.tabChooser = function () {
3688 var object_refs = new Array();
3690 /* Describe certain transfers as invalid */
3693 movementCallback: function(left_side, right_side) {},
3694 orderCallback: function(left_side, right_side) {},
3696 freezeOptions: function(left_name, right_name, target) {
3697 if(!SUGAR.tabChooser.frozenOptions) { SUGAR.tabChooser.frozenOptions = []; }
3698 if(!SUGAR.tabChooser.frozenOptions[left_name]) { SUGAR.tabChooser.frozenOptions[left_name] = []; }
3699 if(!SUGAR.tabChooser.frozenOptions[left_name][right_name]) { SUGAR.tabChooser.frozenOptions[left_name][right_name] = []; }
3700 if(typeof target == 'array') {
3701 for(var i in target) {
3702 SUGAR.tabChooser.frozenOptions[left_name][right_name][target[i]] = true;
3705 SUGAR.tabChooser.frozenOptions[left_name][right_name][target] = true;
3709 buildSelectHTML: function(info) {
3710 var text = "<select";
3712 if(typeof (info['select']['size']) != 'undefined') {
3713 text +=" size=\""+ info['select']['size'] +"\"";
3716 if(typeof (info['select']['name']) != 'undefined') {
3717 text +=" name=\""+ info['select']['name'] +"\"";
3720 if(typeof (info['select']['style']) != 'undefined') {
3721 text +=" style=\""+ info['select']['style'] +"\"";
3724 if(typeof (info['select']['onchange']) != 'undefined') {
3725 text +=" onChange=\""+ info['select']['onchange'] +"\"";
3728 if(typeof (info['select']['multiple']) != 'undefined') {
3733 for(i=0; i<info['options'].length;i++) {
3734 option = info['options'][i];
3735 text += "<option value=\""+option['value']+"\" ";
3736 if ( typeof (option['selected']) != 'undefined' && option['selected']== true) {
3739 text += ">"+option['text']+"</option>";
3741 text += "</select>";
3745 left_to_right: function(left_name, right_name, left_size, right_size) {
3746 SUGAR.savedViews.clearColumns = false;
3747 var left_td = document.getElementById(left_name+'_td');
3748 var right_td = document.getElementById(right_name+'_td');
3750 var display_columns_ref = left_td.getElementsByTagName('select')[0];
3751 var hidden_columns_ref = right_td.getElementsByTagName('select')[0];
3753 var selected_left = new Array();
3754 var notselected_left = new Array();
3755 var notselected_right = new Array();
3757 var left_array = new Array();
3759 var frozen_options = SUGAR.tabChooser.frozenOptions;
3760 frozen_options = frozen_options && frozen_options[left_name] && frozen_options[left_name][right_name]?frozen_options[left_name][right_name]:[];
3762 // determine which options are selected in left
3763 for (i=0; i < display_columns_ref.options.length; i++)
3765 if ( display_columns_ref.options[i].selected == true && !frozen_options[display_columns_ref.options[i].value])
3767 selected_left[selected_left.length] = {text: display_columns_ref.options[i].text, value: display_columns_ref.options[i].value};
3771 notselected_left[notselected_left.length] = {text: display_columns_ref.options[i].text, value: display_columns_ref.options[i].value};
3776 for (i=0; i < hidden_columns_ref.options.length; i++)
3778 notselected_right[notselected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
3782 var left_select_html_info = new Object();
3783 var left_options = new Array();
3784 var left_select = new Object();
3786 left_select['name'] = left_name+'[]';
3787 left_select['id'] = left_name;
3788 left_select['size'] = left_size;
3789 left_select['multiple'] = 'true';
3791 var right_select_html_info = new Object();
3792 var right_options = new Array();
3793 var right_select = new Object();
3795 right_select['name'] = right_name+'[]';
3796 right_select['id'] = right_name;
3797 right_select['size'] = right_size;
3798 right_select['multiple'] = 'true';
3800 for (i = 0; i < notselected_right.length; i++) {
3801 right_options[right_options.length] = notselected_right[i];
3804 for (i = 0; i < selected_left.length; i++) {
3805 right_options[right_options.length] = selected_left[i];
3807 for (i = 0; i < notselected_left.length; i++) {
3808 left_options[left_options.length] = notselected_left[i];
3810 left_select_html_info['options'] = left_options;
3811 left_select_html_info['select'] = left_select;
3812 right_select_html_info['options'] = right_options;
3813 right_select_html_info['select'] = right_select;
3814 right_select_html_info['style'] = 'background: lightgrey';
3816 var left_html = this.buildSelectHTML(left_select_html_info);
3817 var right_html = this.buildSelectHTML(right_select_html_info);
3819 left_td.innerHTML = left_html;
3820 right_td.innerHTML = right_html;
3822 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3823 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3825 this.movementCallback(object_refs[left_name], object_refs[right_name]);
3831 right_to_left: function(left_name, right_name, left_size, right_size, max_left) {
3832 SUGAR.savedViews.clearColumns = false;
3833 var left_td = document.getElementById(left_name+'_td');
3834 var right_td = document.getElementById(right_name+'_td');
3836 var display_columns_ref = left_td.getElementsByTagName('select')[0];
3837 var hidden_columns_ref = right_td.getElementsByTagName('select')[0];
3839 var selected_right = new Array();
3840 var notselected_right = new Array();
3841 var notselected_left = new Array();
3843 var frozen_options = SUGAR.tabChooser.frozenOptions;
3844 frozen_options = SUGAR.tabChooser.frozenOptions && SUGAR.tabChooser.frozenOptions[right_name] && SUGAR.tabChooser.frozenOptions[right_name][left_name]?SUGAR.tabChooser.frozenOptions[right_name][left_name]:[];
3846 for (i=0; i < hidden_columns_ref.options.length; i++)
3848 if (hidden_columns_ref.options[i].selected == true && !frozen_options[hidden_columns_ref.options[i].value])
3850 selected_right[selected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
3854 notselected_right[notselected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
3859 if(max_left != '' && (display_columns_ref.length + selected_right.length) > max_left) {
3860 alert('Maximum of ' + max_left + ' columns can be displayed.');
3864 for (i=0; i < display_columns_ref.options.length; i++)
3866 notselected_left[notselected_left.length] = {text:display_columns_ref.options[i].text, value:display_columns_ref.options[i].value};
3870 var left_select_html_info = new Object();
3871 var left_options = new Array();
3872 var left_select = new Object();
3874 left_select['name'] = left_name+'[]';
3875 left_select['id'] = left_name;
3876 left_select['multiple'] = 'true';
3877 left_select['size'] = left_size;
3879 var right_select_html_info = new Object();
3880 var right_options = new Array();
3881 var right_select = new Object();
3883 right_select['name'] = right_name+ '[]';
3884 right_select['id'] = right_name;
3885 right_select['multiple'] = 'true';
3886 right_select['size'] = right_size;
3888 for (i = 0; i < notselected_left.length; i++) {
3889 left_options[left_options.length] = notselected_left[i];
3892 for (i = 0; i < selected_right.length; i++) {
3893 left_options[left_options.length] = selected_right[i];
3895 for (i = 0; i < notselected_right.length; i++) {
3896 right_options[right_options.length] = notselected_right[i];
3898 left_select_html_info['options'] = left_options;
3899 left_select_html_info['select'] = left_select;
3900 right_select_html_info['options'] = right_options;
3901 right_select_html_info['select'] = right_select;
3902 right_select_html_info['style'] = 'background: lightgrey';
3904 var left_html = this.buildSelectHTML(left_select_html_info);
3905 var right_html = this.buildSelectHTML(right_select_html_info);
3907 left_td.innerHTML = left_html;
3908 right_td.innerHTML = right_html;
3910 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3911 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3913 this.movementCallback(object_refs[left_name], object_refs[right_name]);
3918 up: function(name, left_name, right_name) {
3919 SUGAR.savedViews.clearColumns = false;
3920 var left_td = document.getElementById(left_name+'_td');
3921 var right_td = document.getElementById(right_name+'_td');
3922 var td = document.getElementById(name+'_td');
3923 var obj = td.getElementsByTagName('select')[0];
3924 obj = (typeof obj == "string") ? document.getElementById(obj) : obj;
3925 if (obj.tagName.toLowerCase() != "select" && obj.length < 2)
3927 var sel = new Array();
3929 for (i=0; i<obj.length; i++) {
3930 if (obj[i].selected == true) {
3931 sel[sel.length] = i;
3934 for (i=0; i < sel.length; i++) {
3935 if (sel[i] != 0 && !obj[sel[i]-1].selected) {
3936 var tmp = new Array(obj[sel[i]-1].text, obj[sel[i]-1].value);
3937 obj[sel[i]-1].text = obj[sel[i]].text;
3938 obj[sel[i]-1].value = obj[sel[i]].value;
3939 obj[sel[i]].text = tmp[0];
3940 obj[sel[i]].value = tmp[1];
3941 obj[sel[i]-1].selected = true;
3942 obj[sel[i]].selected = false;
3946 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3947 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3949 this.orderCallback(object_refs[left_name], object_refs[right_name]);
3954 down: function(name, left_name, right_name) {
3955 SUGAR.savedViews.clearColumns = false;
3956 var left_td = document.getElementById(left_name+'_td');
3957 var right_td = document.getElementById(right_name+'_td');
3958 var td = document.getElementById(name+'_td');
3959 var obj = td.getElementsByTagName('select')[0];
3960 if (obj.tagName.toLowerCase() != "select" && obj.length < 2)
3962 var sel = new Array();
3963 for (i=obj.length-1; i>-1; i--) {
3964 if (obj[i].selected == true) {
3965 sel[sel.length] = i;
3968 for (i=0; i < sel.length; i++) {
3969 if (sel[i] != obj.length-1 && !obj[sel[i]+1].selected) {
3970 var tmp = new Array(obj[sel[i]+1].text, obj[sel[i]+1].value);
3971 obj[sel[i]+1].text = obj[sel[i]].text;
3972 obj[sel[i]+1].value = obj[sel[i]].value;
3973 obj[sel[i]].text = tmp[0];
3974 obj[sel[i]].value = tmp[1];
3975 obj[sel[i]+1].selected = true;
3976 obj[sel[i]].selected = false;
3980 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3981 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3983 this.orderCallback(object_refs[left_name], object_refs[right_name]);
3988 }(); // end tabChooser
3990 SUGAR.language = function() {
3992 languages : new Array(),
3994 setLanguage: function(module, data) {
3995 if (!SUGAR.language.languages) {
3998 SUGAR.language.languages[module] = data;
4001 get: function(module, str) {
4002 if(typeof SUGAR.language.languages[module] == 'undefined' || typeof SUGAR.language.languages[module][str] == 'undefined')
4006 return SUGAR.language.languages[module][str];
4009 translate: function(module, str)
4011 text = this.get(module, str);
4012 return text != 'undefined' ? text : this.get('app_strings', str);
4017 SUGAR.contextMenu = function() {
4019 objects: new Object(),
4020 objectTypes: new Object(),
4022 * Registers a new object for the context menu.
4023 * objectType - name of the type
4025 * metaData - metaData to pass to the action function
4027 registerObject: function(objectType, id, metaData) {
4028 SUGAR.contextMenu.objects[id] = new Object();
4029 SUGAR.contextMenu.objects[id] = {'objectType' : objectType, 'metaData' : metaData};
4032 * Registers a new object type
4033 * name - name of the type
4034 * menuItems - array of menu items
4036 registerObjectType: function(name, menuItems) {
4037 SUGAR.contextMenu.objectTypes[name] = new Object();
4038 SUGAR.contextMenu.objectTypes[name] = {'menuItems' : menuItems, 'objects' : new Array()};
4041 * Determines which menu item was clicked
4043 getListItemFromEventTarget: function(p_oNode) {
4045 if(p_oNode.tagName == "LI") {
4050 if(p_oNode.tagName == "LI") {
4055 } while((p_oNode = p_oNode.parentNode));
4060 * handles movement within context menu
4062 onContextMenuMove: function() {
4063 var oNode = this.contextEventTarget;
4064 var bDisabled = (oNode.tagName == "UL");
4065 var i = this.getItemGroups()[0].length - 1;
4067 this.getItem(i).cfg.setProperty("disabled", bDisabled);
4072 * handles clicks on a context menu ITEM
4074 onContextMenuItemClick: function(p_sType, p_aArguments, p_oItem) {
4075 var oLI = SUGAR.contextMenu.getListItemFromEventTarget(this.parent.contextEventTarget);
4076 id = this.parent.contextEventTarget.parentNode.id; // id of the target
4077 funct = eval(SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[id]['objectType']]['menuItems'][this.index]['action']);
4078 funct(this.parent.contextEventTarget, SUGAR.contextMenu.objects[id]['metaData']);
4081 * Initializes all context menus registered
4084 for(var i in SUGAR.contextMenu.objects) { // make a variable called objects in objectTypes containg references to all triggers
4085 if(typeof SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'] == 'undefined')
4086 SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'] = new Array();
4087 SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'].push(document.getElementById(i));
4089 // register the menus
4090 for(var i in SUGAR.contextMenu.objectTypes) {
4091 var oContextMenu = new YAHOO.widget.ContextMenu(i, {'trigger': SUGAR.contextMenu.objectTypes[i]['objects']});
4092 var aMainMenuItems = SUGAR.contextMenu.objectTypes[i]['menuItems'];
4093 var nMainMenuItems = aMainMenuItems.length;
4095 for(var j = 0; j < nMainMenuItems; j++) {
4096 oMenuItem = new YAHOO.widget.ContextMenuItem(aMainMenuItems[j].text, { helptext: aMainMenuItems[j].helptext });
4097 oMenuItem.clickEvent.subscribe(SUGAR.contextMenu.onContextMenuItemClick, oMenuItem, true);
4098 oContextMenu.addItem(oMenuItem);
4100 // Add a "move" event handler to the context menu
4101 oContextMenu.moveEvent.subscribe(SUGAR.contextMenu.onContextMenuMove, oContextMenu, true);
4102 // Add a "keydown" event handler to the context menu
4103 oContextMenu.keyDownEvent.subscribe(SUGAR.contextMenu.onContextMenuItemClick, oContextMenu, true);
4104 // Render the context menu
4105 oContextMenu.render(document.body);
4111 SUGAR.contextMenu.actions = function() {
4114 * redirects to a new note with the clicked on object as the target
4116 createNote: function(itemClicked, metaData) {
4117 loc = 'index.php?module=Notes&action=EditView';
4118 for(i in metaData) {
4119 if(i == 'notes_parent_type') loc += '&parent_type=' + metaData[i];
4120 else if(i != 'module' && i != 'parent_type') loc += '&' + i + '=' + metaData[i];
4122 document.location = loc;
4125 * redirects to a new note with the clicked on object as the target
4127 scheduleMeeting: function(itemClicked, metaData) {
4128 loc = 'index.php?module=Meetings&action=EditView';
4129 for(i in metaData) {
4130 if(i != 'module') loc += '&' + i + '=' + metaData[i];
4132 document.location = loc;
4135 * redirects to a new note with the clicked on object as the target
4137 scheduleCall: function(itemClicked, metaData) {
4138 loc = 'index.php?module=Calls&action=EditView';
4139 for(i in metaData) {
4140 if(i != 'module') loc += '&' + i + '=' + metaData[i];
4142 document.location = loc;
4145 * redirects to a new contact with the clicked on object as the target
4147 createContact: function(itemClicked, metaData) {
4148 loc = 'index.php?module=Contacts&action=EditView';
4149 for(i in metaData) {
4150 if(i != 'module') loc += '&' + i + '=' + metaData[i];
4152 document.location = loc;
4155 * redirects to a new task with the clicked on object as the target
4157 createTask: function(itemClicked, metaData) {
4158 loc = 'index.php?module=Tasks&action=EditView';
4159 for(i in metaData) {
4160 if(i != 'module') loc += '&' + i + '=' + metaData[i];
4162 document.location = loc;
4165 * redirects to a new opportunity with the clicked on object as the target
4167 createOpportunity: function(itemClicked, metaData) {
4168 loc = 'index.php?module=Opportunities&action=EditView';
4169 for(i in metaData) {
4170 if(i != 'module') loc += '&' + i + '=' + metaData[i];
4172 document.location = loc;
4175 * redirects to a new opportunity with the clicked on object as the target
4177 createCase: function(itemClicked, metaData) {
4178 loc = 'index.php?module=Cases&action=EditView';
4179 for(i in metaData) {
4180 if(i != 'module') loc += '&' + i + '=' + metaData[i];
4182 document.location = loc;
4185 * handles add to favorites menu selection
4187 addToFavorites: function(itemClicked, metaData) {
4188 success = function(data) {
4190 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});
4195 //if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.contextMenu.init);
4197 // initially from popup_parent_helper.js
4198 var popup_request_data;
4201 function get_popup_request_data()
4203 return YAHOO.lang.JSON.stringify(window.document.popup_request_data);
4206 function get_close_popup()
4208 return window.document.close_popup;
4211 function open_popup(module_name, width, height, initial_filter, close_popup, hide_clear_button, popup_request_data, popup_mode, create, metadata)
4213 if (typeof(popupCount) == "undefined" || popupCount == 0)
4216 // set the variables that the popup will pull from
4217 window.document.popup_request_data = popup_request_data;
4218 window.document.close_popup = close_popup;
4220 //globally changing width and height of standard pop up window from 600 x 400 to 800 x 800
4221 width = (width == 600) ? 800 : width;
4222 height = (height == 400) ? 800 : height;
4226 + 'module=' + module_name
4229 if (initial_filter != '') {
4230 URL += '&query=true' + initial_filter;
4231 // Bug 41891 - Popup Window Name
4232 popupName = initial_filter.replace(/[^a-z_0-9]+/ig, '_');
4233 windowName = module_name + '_popup_window' + popupName;
4235 windowName = module_name + '_popup_window' + popupCount;
4239 if (hide_clear_button) {
4240 URL += '&hide_clear_button=true';
4243 windowFeatures = 'width=' + width
4244 + ',height=' + height
4245 + ',resizable=1,scrollbars=1';
4247 if (popup_mode == '' || popup_mode == undefined) {
4248 popup_mode='single';
4250 URL+='&mode='+popup_mode;
4251 if (create == '' || create == undefined) {
4254 URL+='&create='+create;
4256 if (metadata != '' && metadata != undefined) {
4257 URL+='&metadata='+metadata;
4260 // Bug #46842 : The relate field field_to_name_array fails to copy over custom fields
4261 // post fields that should be populated from popup form
4262 if(popup_request_data.jsonObject) {
4263 var request_data = popup_request_data.jsonObject;
4265 var request_data = popup_request_data;
4267 var field_to_name_array_url = '';
4269 if (request_data && request_data.field_to_name_array != undefined) {
4270 for(var key in request_data.field_to_name_array) {
4271 if ( key.toLowerCase() != 'id' ) {
4272 field_to_name_array_url += '&field_to_name[]='+encodeURIComponent(key.toLowerCase());
4276 if ( field_to_name_array_url ) {
4277 URL+=field_to_name_array_url;
4280 win = SUGAR.util.openWindow(URL, windowName, windowFeatures);
4284 // put the focus on the popup if the browser supports the focus() method
4288 win.popupCount = popupCount;
4294 * The reply data must be a JSON array structured with the following information:
4295 * 1) form name to populate
4296 * 2) associative array of input names to values for populating the form
4298 var from_popup_return = false;
4300 //Function replaces special HTML chars for usage in text boxes
4301 function replaceHTMLChars(value) {
4302 return value.replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');
4305 function set_return_basic(popup_reply_data,filter)
4307 var form_name = popup_reply_data.form_name;
4308 var name_to_value_array = popup_reply_data.name_to_value_array;
4309 for (var the_key in name_to_value_array)
4311 if(the_key == 'toJSON')
4315 else if(the_key.match(filter))
4317 var displayValue=replaceHTMLChars(name_to_value_array[the_key]);
4318 // begin andopes change: support for enum fields (SELECT)
4319 if(window.document.forms[form_name] && window.document.forms[form_name].elements[the_key]) {
4320 if(window.document.forms[form_name].elements[the_key].tagName == 'SELECT') {
4321 var selectField = window.document.forms[form_name].elements[the_key];
4322 for(var i = 0; i < selectField.options.length; i++) {
4323 if(selectField.options[i].text == displayValue) {
4324 selectField.options[i].selected = true;
4325 SUGAR.util.callOnChangeListers(selectField);
4330 window.document.forms[form_name].elements[the_key].value = displayValue;
4331 SUGAR.util.callOnChangeListers(window.document.forms[form_name].elements[the_key]);
4334 // end andopes change: support for enum fields (SELECT)
4339 function set_return(popup_reply_data)
4341 from_popup_return = true;
4342 var form_name = popup_reply_data.form_name;
4343 var name_to_value_array = popup_reply_data.name_to_value_array;
4344 if(typeof name_to_value_array != 'undefined' && name_to_value_array['account_id'])
4347 var label_data_str = '';
4348 var current_label_data_str = '';
4349 var popupConfirm = popup_reply_data.popupConfirm;
4350 for (var the_key in name_to_value_array)
4352 if(the_key == 'toJSON')
4358 var displayValue=replaceHTMLChars(name_to_value_array[the_key]);
4359 if(window.document.forms[form_name] && document.getElementById(the_key+'_label') && !the_key.match(/account/)) {
4360 var data_label = document.getElementById(the_key+'_label').innerHTML.replace(/\n/gi,'').replace(/<\/?[^>]+(>|$)/g, "");
4361 label_str += data_label + ' \n';
4362 label_data_str += data_label + ' ' + displayValue + '\n';
4363 if(window.document.forms[form_name].elements[the_key]) {
4364 current_label_data_str += data_label + ' ' + window.document.forms[form_name].elements[the_key].value +'\n';
4370 if(label_data_str != label_str && current_label_data_str != label_str){
4372 if (typeof popupConfirm != 'undefined')
4374 if (popupConfirm > -1) {
4375 set_return_basic(popup_reply_data,/\S/);
4377 set_return_basic(popup_reply_data,/account/);
4381 else if(confirm(SUGAR.language.get('app_strings', 'NTC_OVERWRITE_ADDRESS_PHONE_CONFIRM') + '\n\n' + label_data_str))
4383 set_return_basic(popup_reply_data,/\S/);
4387 set_return_basic(popup_reply_data,/account/);
4389 }else if(label_data_str != label_str && current_label_data_str == label_str){
4390 set_return_basic(popup_reply_data,/\S/);
4391 }else if(label_data_str == label_str){
4392 set_return_basic(popup_reply_data,/account/);
4395 set_return_basic(popup_reply_data,/\S/);
4399 function set_return_lead_conv(popup_reply_data) {
4400 set_return(popup_reply_data);
4401 if (document.getElementById('lead_conv_ac_op_sel') && typeof onBlurKeyUpHandler=='function') {
4402 onBlurKeyUpHandler();
4406 function set_return_and_save(popup_reply_data)
4408 var form_name = popup_reply_data.form_name;
4409 var name_to_value_array = popup_reply_data.name_to_value_array;
4411 for (var the_key in name_to_value_array)
4413 if(the_key == 'toJSON')
4419 window.document.forms[form_name].elements[the_key].value = name_to_value_array[the_key];
4423 window.document.forms[form_name].return_module.value = window.document.forms[form_name].module.value;
4424 window.document.forms[form_name].return_action.value = 'DetailView';
4425 window.document.forms[form_name].return_id.value = window.document.forms[form_name].record.value;
4426 window.document.forms[form_name].action.value = 'Save';
4427 window.document.forms[form_name].submit();
4431 * This is a helper function to construct the initial filter that can be
4432 * passed into the open_popup() function. It assumes that there is an
4433 * account_id and account_name field in the given form_name to use to
4434 * construct the intial filter string.
4436 function get_initial_filter_by_account(form_name)
4438 var account_id = window.document.forms[form_name].account_id.value;
4439 var account_name = escape(window.document.forms[form_name].account_name.value);
4440 var initial_filter = "&account_id=" + account_id + "&account_name=" + account_name;
4442 return initial_filter;
4444 // end code from popup_parent_helper.js
4446 // begin code for address copy
4448 * This is a function used by the Address widget that will fill
4449 * in the given array fields using the fromKey and toKey as a
4450 * prefix into the form objects HTML elements.
4452 * @param form The HTML form object to parse
4453 * @param fromKey The prefix of elements to copy from
4454 * @param toKey The prefix of elements to copy into
4455 * @return boolean true if successful, false otherwise
4457 function copyAddress(form, fromKey, toKey) {
4459 var elems = new Array("address_street", "address_city", "address_state", "address_postalcode", "address_country");
4460 var checkbox = document.getElementById(toKey + "_checkbox");
4462 if(typeof checkbox != "undefined") {
4463 if(!checkbox.checked) {
4465 t = toKey + "_" + elems[x];
4466 document.getElementById(t).removeAttribute('readonly');
4470 f = fromKey + "_" + elems[x];
4471 t = toKey + "_" + elems[x];
4473 document.getElementById(t).value = document.getElementById(f).value;
4474 document.getElementById(t).setAttribute('readonly', true);
4480 // end code for address copy
4483 * This function is used in Email Template Module.
4484 * It will check whether the template is used in Campaing->EmailMarketing.
4485 * If true, it will notify user.
4488 function check_deletable_EmailTemplate() {
4489 id = document.getElementsByName('record')[0].value;
4490 currentForm = document.getElementById('form');
4492 success:function(r) {
4493 if(r.responseText == 'true') {
4494 if(!confirm(SUGAR.language.get('app_strings','NTC_TEMPLATE_IS_USED'))) {
4498 if(!confirm(SUGAR.language.get('app_strings','NTC_DELETE_CONFIRMATION'))) {
4502 currentForm.return_module.value='EmailTemplates';
4503 currentForm.return_action.value='ListView';
4504 currentForm.action.value='Delete';
4505 currentForm.submit();
4508 url = "index.php?module=EmailTemplates&action=CheckDeletable&from=DetailView&to_pdf=1&record="+id;
4509 YAHOO.util.Connect.asyncRequest('POST',url, call_back,null);
4513 remove_upload_imagefile : function(field_name) {
4514 var field=document.getElementById('remove_imagefile_' + field_name);
4517 //enable the file upload button.
4518 var field=document.getElementById( field_name);
4519 field.style.display="";
4521 //hide the image and remove button.
4522 var field=document.getElementById('img_' + field_name);
4523 field.style.display="none";
4524 var field=document.getElementById('bt_remove_' + field_name);
4525 field.style.display="none";
4527 if(document.getElementById(field_name + '_duplicate')) {
4528 var field = document.getElementById(field_name + '_duplicate');
4533 confirm_imagefile : function(field_name) {
4534 var field=document.getElementById(field_name);
4535 var filename=field.value;
4536 var fileExtension = filename.substring(filename.lastIndexOf(".")+1);
4537 fileExtension = fileExtension.toLowerCase();
4538 if (fileExtension == "jpg" || fileExtension == "jpeg"
4539 || fileExtension == "gif" || fileExtension == "png" || fileExtension == "bmp"){
4544 alert(SUGAR.language.get('app_strings', 'LBL_UPLOAD_IMAGE_FILE_INVALID'));
4548 lightbox : function(image)
4550 if (typeof(SUGAR.image.lighboxWindow) == "undefined")
4551 SUGAR.image.lighboxWindow = new YAHOO.widget.SimpleDialog('sugarImageViewer', {
4554 id:'sugarMsgWindow',
4557 msg: "<img src='" + image + "'> </img>",
4560 SUGAR.image.lighboxWindow.setBody("<img src='" + image + "'> </img>");
4561 SUGAR.image.lighboxWindow.render(document.body);
4562 SUGAR.image.lighboxWindow.show();
4563 SUGAR.image.lighboxWindow.center()
4567 SUGAR.append(SUGAR.util, {
4568 isTouchScreen: function() {
4569 // first check if we have forced use of the touch enhanced interface
4570 if (Get_Cookie("touchscreen") == '1') {
4574 // next check if we should use the touch interface with our device
4575 if ((navigator.userAgent.match(/iPad/i) != null)) {
4582 isLoginPage: function(content) {
4583 //skip if this is packageManager screen
4584 if(SUGAR.util.isPackageManager()) {return false;}
4585 var loginPageStart = "<!DOCTYPE";
4586 if (content.substr(0, loginPageStart.length) == loginPageStart && content.indexOf("<html>") != -1 && content.indexOf("login_module") != -1) {
4587 window.location.href = window.location.protocol + window.location.pathname;
4592 isPackageManager: function(){
4593 if(typeof(document.the_form) !='undefined' && typeof(document.the_form.language_pack_escaped) !='undefined'){
4595 }else{return false;}
4598 ajaxCallInProgress: function(){
4600 //First check if we are in a popup.
4601 if (typeof (send_back) != "function"){
4602 //If the page content is blank, it means we are probably still waiting on something
4603 var c = document.getElementById("content");
4604 if (!c) return true;
4605 t = YAHOO.lang.trim(SUGAR.util.innerText(c));
4607 return SUGAR_callsInProgress != 0 || t == "";
4609 //Firefox doesn't support innerText (textContent includes script content)
4610 innerText : function(el) {
4611 if (el.tagName == "SCRIPT")
4613 if(typeof(el.innerText) == "string")
4614 return el.innerText;
4616 for (var i in el.childNodes){
4617 var c = el.childNodes[i];
4618 if (typeof(c) != "object")
4620 if (typeof(c.nodeName) == "string" && c.nodeName == "#text")
4623 t += SUGAR.util.innerText(c);
4628 callOnChangeListers: function(field){
4629 var listeners = YAHOO.util.Event.getListeners(field, 'change');
4630 if (listeners != null) {
4631 for (var i = 0; i < listeners.length; i++) {
4632 var l = listeners[i];
4633 l.fn.call(l.scope ? l.scope : this, l.obj);
4638 closeActivityPanel: {
4639 show:function(module,id,new_status,viewType,parentContainerId){
4640 if (SUGAR.util.closeActivityPanel.panel)
4641 SUGAR.util.closeActivityPanel.panel.destroy();
4642 var singleModule = SUGAR.language.get("app_list_strings", "moduleListSingular")[module];
4643 singleModule = typeof(singleModule != 'undefined') ? singleModule.toLowerCase() : '';
4644 var closeText = SUGAR.language.get("app_strings", "LBL_CLOSE_ACTIVITY_CONFIRM").replace("#module#",singleModule);
4645 SUGAR.util.closeActivityPanel.panel =
4646 new YAHOO.widget.SimpleDialog("closeActivityDialog",
4653 constraintoviewport: true,
4654 buttons: [ { text:SUGAR.language.get("app_strings", "LBL_EMAIL_OK"), handler:function(){
4655 if (SUGAR.util.closeActivityPanel.panel)
4656 SUGAR.util.closeActivityPanel.panel.hide();
4658 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_SAVING'));
4659 var args = "action=save&id=" + id + "&record=" + id + "&status=" + new_status + "&module=" + module;
4660 // 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
4661 // TODO: Take id out and regression test. Left id in for now to not create any other unexpected problems
4662 //var args = "action=save&id=" + id + "&status=" + new_status + "&module=" + module;
4666 // Bug 51984: We need to submit the form just incase we have a form already submitted
4667 // so we dont get a popup stating that the form needs to be resubmitted like it doesn,
4668 // when you do a reload/refresh
4669 window.setTimeout(function(){if(document.getElementById('search_form')) document.getElementById('search_form').submit(); else window.location.reload(true);}, 0);
4671 argument:{'parentContainerId':parentContainerId}
4674 YAHOO.util.Connect.asyncRequest('POST', 'index.php', callback, args);
4676 }, isDefault:true },
4677 { text:SUGAR.language.get("app_strings", "LBL_EMAIL_CANCEL"), handler:function(){SUGAR.util.closeActivityPanel.panel.hide(); }} ]
4680 SUGAR.util.closeActivityPanel.panel.setHeader(SUGAR.language.get("app_strings", "LBL_CLOSE_ACTIVITY_HEADER"));
4681 SUGAR.util.closeActivityPanel.panel.render(document.body);
4682 SUGAR.util.closeActivityPanel.panel.show();
4686 setEmailPasswordDisplay: function(id, exists, formName) {
4687 link = document.getElementById(id+'_link');
4688 pwd = document.getElementById(id);
4689 if(!pwd || !link) return;
4691 pwd.style.display = 'none';
4692 link.style.display = '';
4693 if(typeof(formName) != 'undefined')
4694 removeFromValidate(formName, id);
4696 pwd.style.display = '';
4697 link.style.display = 'none';
4701 setEmailPasswordEdit: function(id) {
4702 link = document.getElementById(id+'_link');
4703 pwd = document.getElementById(id);
4704 if(!pwd || !link) return;
4705 pwd.style.display = '';
4706 link.style.display = 'none';
4710 * Compares a filename with a supplied array of allowed file extensions.
4711 * @param fileName string
4712 * @param allowedTypes array of allowed file extensions
4715 validateFileExt: function(fileName, allowedTypes) {
4716 var ext = fileName.split('.').pop().toLowerCase();
4718 for (var i = allowedTypes.length; i >= 0; i--) {
4719 if (ext === allowedTypes[i]) {
4727 arrayIndexOf: function(arr, val, start) {
4728 if (typeof arr.indexOf == "function")
4729 return arr.indexOf(val, start);
4730 for (var i = (start || 0), j = arr.length; i < j; i++) {
4731 if (arr[i] === val) {
4739 SUGAR.clearRelateField = function(form, name, id)
4741 if (typeof form[name] == "object"){
4742 form[name].value = '';
4743 SUGAR.util.callOnChangeListers(form[name]);
4746 if (typeof form[id] == "object"){
4747 form[id].value = '';
4748 SUGAR.util.callOnChangeListers(form[id]);
4751 if(typeof(SUGAR.AutoComplete) == 'undefined') SUGAR.AutoComplete = {};
4753 SUGAR.AutoComplete.getOptionsArray = function(options_index){
4754 var return_arr = [];
4756 var opts = SUGAR.language.get('app_list_strings', options_index);
4757 if(typeof(opts) != 'undefined'){
4759 // Since we are using auto complete, we excluse blank dropdown entries since they can just leave it blank
4760 if(key != '' && opts[key] != ''){
4763 item['text'] = opts[key];
4764 return_arr.push(item);
4771 if(typeof(SUGAR.MultiEnumAutoComplete) == 'undefined') SUGAR.MultiEnumAutoComplete = {};
4773 SUGAR.MultiEnumAutoComplete.getMultiSelectKeysFromValues = function(options_index, val_string){
4774 var opts = SUGAR.language.get('app_list_strings', options_index);
4775 var selected_values = val_string.split(", ");
4776 // YUI AutoComplete adds a blank. We remove it automatically here
4777 if(selected_values.length > 0 && selected_values.indexOf('') == selected_values.length - 1){
4778 selected_values.pop();
4780 var final_arr = new Array();
4781 for(idx in selected_values){
4783 if(selected_values[idx] == opts[o_idx]){
4784 final_arr.push(o_idx);
4791 SUGAR.MultiEnumAutoComplete.getMultiSelectValuesFromKeys = function(options_index, val_string){
4792 var opts = SUGAR.language.get('app_list_strings', options_index);
4793 val_string=val_string.replace(/^\^/,'').replace(/\^$/,'') //fixes bug where string starts or ends with ^
4794 var selected_values = val_string.split("^,^");
4796 // YUI AutoComplete adds a blank. We remove it automatically here
4797 if(selected_values.length > 0 && selected_values.indexOf('') == selected_values.length - 1){
4798 selected_values.pop();
4801 var final_arr = new Array();
4802 for(idx in selected_values){
4804 if(selected_values[idx] == o_idx){
4805 final_arr.push(opts[o_idx]);