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();
634 if (typeof min == 'number' && value < min)
638 if (typeof max == 'number' && value > max)
645 function bothExist(item1, item2) {
646 if(typeof item1 == 'undefined') { return false; }
647 if(typeof item2 == 'undefined') { return false; }
648 if((item1 == '' && item2 != '') || (item1 != '' && item2 == '') ) { return false; }
652 trim = YAHOO.lang.trim;
655 function check_form(formname) {
656 if (typeof(siw) != 'undefined' && siw
657 && typeof(siw.selectingSomething) != 'undefined' && siw.selectingSomething)
659 return validate_form(formname, '');
662 function add_error_style(formname, input, txt, flash) {
663 var raiseFlag = false;
664 if (typeof flash == "undefined")
667 inputHandle = typeof input == "object" ? input : document.forms[formname][input];
668 style = get_current_bgcolor(inputHandle);
670 // strip off the colon at the end of the warning strings
671 if ( txt.substring(txt.length-1) == ':' )
672 txt = txt.substring(0,txt.length-1)
674 // Bug 28249 - To help avoid duplicate messages for an element, strip off extra messages and
675 // match on the field name itself
676 requiredTxt = SUGAR.language.get('app_strings', 'ERR_MISSING_REQUIRED_FIELDS');
677 invalidTxt = SUGAR.language.get('app_strings', 'ERR_INVALID_VALUE');
678 nomatchTxt = SUGAR.language.get('app_strings', 'ERR_SQS_NO_MATCH_FIELD');
679 matchTxt = txt.replace(requiredTxt,'').replace(invalidTxt,'').replace(nomatchTxt,'');
681 YUI().use('node', function (Y) {
682 Y.one(inputHandle).get('parentNode').get('children').each(function(node, index, nodeList){
683 if(node.hasClass('validation-message') && node.get('text').search(matchTxt)){
690 errorTextNode = document.createElement('div');
691 errorTextNode.className = 'required validation-message';
692 errorTextNode.innerHTML = txt;
693 if ( inputHandle.parentNode.className.indexOf('x-form-field-wrap') != -1 ) {
694 inputHandle.parentNode.parentNode.appendChild(errorTextNode);
697 inputHandle.parentNode.appendChild(errorTextNode);
700 inputHandle.style.backgroundColor = "#FF0000";
701 inputsWithErrors.push(inputHandle);
705 // We only need to setup the flashy-flashy on the first entry, it loops through all fields automatically
706 if ( inputsWithErrors.length == 1 ) {
707 for(var wp = 1; wp <= 10; wp++) {
708 window.setTimeout('fade_error_style(style, '+wp*10+')',1000+(wp*50));
711 if(typeof (window[formname + "_tabs"]) != "undefined") {
712 var tabView = window[formname + "_tabs"];
713 var parentDiv = YAHOO.util.Dom.getAncestorByTagName(inputHandle, "div");
715 var tabs = tabView.get("tabs");
716 for (var i in tabs) {
717 if (tabs[i].get("contentEl") == parentDiv
718 || YAHOO.util.Dom.isAncestor(tabs[i].get("contentEl"), inputHandle))
720 tabs[i].get("labelEl").style.color = "red";
721 if ( inputsWithErrors.length == 1 )
722 tabView.selectTab(i);
727 window.setTimeout("inputsWithErrors[" + (inputsWithErrors.length - 1) + "].style.backgroundColor = '';", 2000);
731 // Catch errors here so we don't allow an incomplete record through the javascript validation
737 * removes all error messages for the current form
739 function clear_all_errors() {
740 for(var wp = 0; wp < inputsWithErrors.length; wp++) {
741 if(typeof(inputsWithErrors[wp]) !='undefined' && typeof inputsWithErrors[wp].parentNode != 'undefined' && inputsWithErrors[wp].parentNode != null) {
742 if ( inputsWithErrors[wp].parentNode.className.indexOf('x-form-field-wrap') != -1 )
744 inputsWithErrors[wp].parentNode.parentNode.removeChild(inputsWithErrors[wp].parentNode.parentNode.lastChild);
748 inputsWithErrors[wp].parentNode.removeChild(inputsWithErrors[wp].parentNode.lastChild);
752 if (inputsWithErrors.length == 0) return;
754 if ( YAHOO.util.Dom.getAncestorByTagName(inputsWithErrors[0], "form") ) {
755 var formname = YAHOO.util.Dom.getAncestorByTagName(inputsWithErrors[0], "form").getAttribute("name");
756 if(typeof (window[formname + "_tabs"]) != "undefined") {
757 var tabView = window[formname + "_tabs"];
759 var tabs = tabView.get("tabs");
760 for (var i in tabs) {
761 if (typeof tabs[i] == "object")
762 tabs[i].get("labelEl").style.color = "";
766 inputsWithErrors = new Array();
770 function get_current_bgcolor(input) {
771 if(input.currentStyle) {// ie
772 style = input.currentStyle.backgroundColor;
773 return style.substring(1,7);
777 styleRGB = document.defaultView.getComputedStyle(input, '').getPropertyValue("background-color");
778 comma = styleRGB.indexOf(',');
779 style += dec2hex(styleRGB.substring(4, comma));
780 commaPrevious = comma;
781 comma = styleRGB.indexOf(',', commaPrevious+1);
782 style += dec2hex(styleRGB.substring(commaPrevious+2, comma));
783 style += dec2hex(styleRGB.substring(comma+2, styleRGB.lastIndexOf(')')));
788 function hex2dec(hex){return(parseInt(hex,16));}
789 var hexDigit=new Array("0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F");
790 function dec2hex(dec){return(hexDigit[dec>>4]+hexDigit[dec&15]);}
792 function fade_error_style(normalStyle, percent) {
793 errorStyle = 'c60c30';
794 var r1 = hex2dec(errorStyle.slice(0,2));
795 var g1 = hex2dec(errorStyle.slice(2,4));
796 var b1 = hex2dec(errorStyle.slice(4,6));
798 var r2 = hex2dec(normalStyle.slice(0,2));
799 var g2 = hex2dec(normalStyle.slice(2,4));
800 var b2 = hex2dec(normalStyle.slice(4,6));
803 var pc = percent / 100;
805 r= Math.floor(r1+(pc*(r2-r1)) + .5);
806 g= Math.floor(g1+(pc*(g2-g1)) + .5);
807 b= Math.floor(b1+(pc*(b2-b1)) + .5);
809 for(var wp = 0; wp < inputsWithErrors.length; wp++) {
810 inputsWithErrors[wp].style.backgroundColor = "#" + dec2hex(r) + dec2hex(g) + dec2hex(b);
814 function isFieldTypeExceptFromEmptyCheck(fieldType)
817 var exemptList = ['bool','file'];
818 for(var i=0;i<exemptList.length;i++)
820 if(fieldType == exemptList[i])
825 function validate_form(formname, startsWith){
826 requiredTxt = SUGAR.language.get('app_strings', 'ERR_MISSING_REQUIRED_FIELDS');
827 invalidTxt = SUGAR.language.get('app_strings', 'ERR_INVALID_VALUE');
829 if ( typeof (formname) == 'undefined')
833 if ( typeof (validate[formname]) == 'undefined')
835 disableOnUnloadEditView(document.forms[formname]);
839 var form = document.forms[formname];
842 var _date = new Date();
843 if(_date.getTime() < (lastSubmitTime + 2000) && startsWith == oldStartsWith) { // ignore submits for the next 2 seconds
846 lastSubmitTime = _date.getTime();
847 oldStartsWith = startsWith;
849 clear_all_errors(); // remove previous error messages
851 inputsWithErrors = new Array();
852 for(var i = 0; i < validate[formname].length; i++){
853 if(validate[formname][i][nameIndex].indexOf(startsWith) == 0){
854 if(typeof form[validate[formname][i][nameIndex]] != 'undefined' && typeof form[validate[formname][i][nameIndex]].value != 'undefined'){
857 //If a field is not required and it is blank or is binarydependant, skip validation.
858 //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
859 if(!validate[formname][i][requiredIndex] && trim(form[validate[formname][i][nameIndex]].value) == '' && (typeof(validate[formname][i][jstypeIndex]) != 'undefined' && validate[formname][i][jstypeIndex] != 'binarydep'))
864 if(validate[formname][i][requiredIndex]
865 && !isFieldTypeExceptFromEmptyCheck(validate[formname][i][typeIndex])
867 if(typeof form[validate[formname][i][nameIndex]] == 'undefined' || trim(form[validate[formname][i][nameIndex]].value) == ""){
868 add_error_style(formname, validate[formname][i][nameIndex], requiredTxt +' ' + validate[formname][i][msgIndex]);
873 switch(validate[formname][i][typeIndex]){
875 if(!isValidEmail(trim(form[validate[formname][i][nameIndex]].value))){
877 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
881 if( !isTime(trim(form[validate[formname][i][nameIndex]].value))){
883 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
885 case 'date': if(!isDate(trim(form[validate[formname][i][nameIndex]].value))){
887 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
892 if(!isDBName(trim(form[validate[formname][i][nameIndex]].value))){
894 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
897 // Bug #49614 : Check value without trimming before
899 if(!isDBName(form[validate[formname][i][nameIndex]].value)){
901 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
907 var file_input = form[validate[formname][i][nameIndex] + '_file'];
908 if( file_input && validate[formname][i][requiredIndex] && trim(file_input.value) == "" && !file_input.disabled ) {
910 add_error_style(formname, validate[formname][i][nameIndex], requiredTxt + " " + validate[formname][i][msgIndex]);
914 if(!isInteger(trim(form[validate[formname][i][nameIndex]].value))){
916 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
920 if(!isDecimal(trim(form[validate[formname][i][nameIndex]].value))){
922 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
927 if(!isFloat(trim(form[validate[formname][i][nameIndex]].value))){
929 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
933 var div_element_id = formname + '_' + form[validate[formname][i][nameIndex]].name + '_operation_div';
934 var input_elements = YAHOO.util.Selector.query('input', document.getElementById(div_element_id));
935 var primary_field_id = '';
936 var validation_passed = false;
937 var replace_selected = false;
939 //Loop through the option elements (replace or add currently)
940 for(t in input_elements) {
941 if(input_elements[t].type && input_elements[t].type == 'radio' && input_elements[t].checked == true && input_elements[t].value == 'replace') {
943 //Now find where the primary radio button is and if a value has been set
944 var radio_elements = YAHOO.util.Selector.query('input[type=radio]', document.getElementById(formname + '_team_name_table'));
946 for(var x = 0; x < radio_elements.length; x++) {
947 if(radio_elements[x].name != 'team_name_type') {
948 primary_field_id = 'team_name_collection_' + radio_elements[x].value;
949 if(radio_elements[x].checked) {
950 replace_selected = true;
951 if(trim(document.forms[formname].elements[primary_field_id].value) != '') {
952 validation_passed = true;
955 } else if(trim(document.forms[formname].elements[primary_field_id].value) != '') {
956 replace_selected = true;
963 if(replace_selected && !validation_passed) {
964 add_error_style(formname, primary_field_id, SUGAR.language.get('app_strings', 'ERR_NO_PRIMARY_TEAM_SPECIFIED'));
969 var table_element_id = formname + '_' + form[validate[formname][i][nameIndex]].name + '_table';
970 if(document.getElementById(table_element_id)) {
971 var input_elements = YAHOO.util.Selector.query('input[type=radio]', document.getElementById(table_element_id));
972 var has_primary = false;
973 var primary_field_id = form[validate[formname][i][nameIndex]].name + '_collection_0';
975 for(t in input_elements) {
976 primary_field_id = form[validate[formname][i][nameIndex]].name + '_collection_' + input_elements[t].value;
977 if(input_elements[t].type && input_elements[t].type == 'radio' && input_elements[t].checked == true) {
978 if(document.forms[formname].elements[primary_field_id].value != '') {
987 var field_id = form[validate[formname][i][nameIndex]].name + '_collection_' + input_elements[0].value;
988 add_error_style(formname, field_id, SUGAR.language.get('app_strings', 'ERR_NO_PRIMARY_TEAM_SPECIFIED'));
994 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex]);
998 if(typeof validate[formname][i][jstypeIndex] != 'undefined'/* && !isError*/){
1000 switch(validate[formname][i][jstypeIndex]){
1001 // Bug #47961 May be validation through callback is best way.
1003 if (typeof validate[formname][i][callbackIndex] == 'function')
1005 var result = validate[formname][i][callbackIndex](formname, validate[formname][i][nameIndex]);
1006 if (result == false)
1009 add_error_style(formname, validate[formname][i][nameIndex], requiredTxt + " " + validate[formname][i][msgIndex]);
1014 if(!inRange(trim(form[validate[formname][i][nameIndex]].value), validate[formname][i][minIndex], validate[formname][i][maxIndex])){
1016 var lbl_validate_range = SUGAR.language.get('app_strings', 'LBL_VALIDATE_RANGE');
1017 if (typeof validate[formname][i][minIndex] == 'number' && typeof validate[formname][i][maxIndex] == 'number')
1019 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] + ")");
1021 else if (typeof validate[formname][i][minIndex] == 'number')
1023 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex] + " " + SUGAR.language.get('app_strings', 'MSG_SHOULD_BE') + ' ' + validate[formname][i][minIndex] + ' ' + SUGAR.language.get('app_strings', 'MSG_OR_GREATER'));
1025 else if (typeof validate[formname][i][maxIndex] == 'number')
1027 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex] + " " + SUGAR.language.get('app_strings', 'MSG_IS_MORE_THAN') + ' ' + validate[formname][i][maxIndex]);
1032 compareTo = form[validate[formname][i][compareToIndex]];
1033 if( typeof compareTo != 'undefined'){
1034 if(trim(compareTo.value) != '' || (validate[formname][i][allowblank] != 'true') ) {
1035 date2 = trim(compareTo.value);
1036 date1 = trim(form[validate[formname][i][nameIndex]].value);
1038 if(trim(date1).length != 0 && !isBefore(date1,date2)){
1041 //jc:#12287 - adding translation for the is not before message
1042 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex] + "(" + date1 + ") " + SUGAR.language.get('app_strings', 'MSG_IS_NOT_BEFORE') + ' ' +date2);
1048 value=unformatNumber(trim(form[validate[formname][i][nameIndex]].value), num_grp_sep, dec_sep);
1049 maximum = parseFloat(validate[formname][i][maxIndex]);
1050 if( typeof maximum != 'undefined'){
1053 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]);
1058 value=unformatNumber(trim(form[validate[formname][i][nameIndex]].value), num_grp_sep, dec_sep);
1059 minimum = parseFloat(validate[formname][i][minIndex]);
1060 if( typeof minimum != 'undefined'){
1063 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'));
1068 compareTo = form[validate[formname][i][compareToIndex]];
1069 if( typeof compareTo != 'undefined') {
1070 item1 = trim(form[validate[formname][i][nameIndex]].value);
1071 item2 = trim(compareTo.value);
1072 if(!bothExist(item1, item2)) {
1074 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex]);
1079 compareTo = form[validate[formname][i][compareToIndex]];
1080 if( typeof compareTo != 'undefined') {
1081 item1 = trim(form[validate[formname][i][nameIndex]].value);
1082 item2 = trim(compareTo.value);
1083 if(!bothExist(item1, item2) || item1 != item2) {
1085 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex]);
1090 arr = eval(validate[formname][i][arrIndex]);
1091 operator = validate[formname][i][operatorIndex];
1092 item1 = trim(form[validate[formname][i][nameIndex]].value);
1093 if (operator.charAt(0) == 'u') {
1094 item1 = item1.toUpperCase();
1095 operator = operator.substring(1);
1096 } else if (operator.charAt(0) == 'l') {
1097 item1 = item1.toLowerCase();
1098 operator = operator.substring(1);
1100 for(j = 0; j < arr.length; j++){
1102 if((operator == "==" && val == item1) || (operator == "!=" && val != item1)){
1104 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
1109 if(trim(form[validate[formname][i][nameIndex]].value) == 'false'){
1110 //Fake an error so form does not submit
1120 /* nsingh: BUG#15102
1121 Check min max default field logic.
1122 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.*/
1123 if(formsWithFieldLogic){
1124 var invalidLogic=false;
1125 if(formsWithFieldLogic.min && formsWithFieldLogic.max && formsWithFieldLogic._default) {
1126 var showErrorsOn={min:{value:'min', show:false, obj:formsWithFieldLogic.min.value},
1127 max:{value:'max',show:false, obj:formsWithFieldLogic.max.value},
1128 _default:{value:'default',show:false, obj:formsWithFieldLogic._default.value},
1129 len:{value:'len', show:false, obj:parseInt(formsWithFieldLogic.len.value,10)}};
1131 var min = (formsWithFieldLogic.min.value !='') ? parseFloat(formsWithFieldLogic.min.value) : 'undef';
1132 var max = (formsWithFieldLogic.max.value !='') ? parseFloat(formsWithFieldLogic.max.value) : 'undef';
1133 var _default = (formsWithFieldLogic._default.value!='')? parseFloat(formsWithFieldLogic._default.value) : 'undef';
1135 /*Check all lengths are <= max size.*/
1136 for(var i in showErrorsOn){
1137 if(showErrorsOn[i].value!='len' && showErrorsOn[i].obj.length > showErrorsOn.len.obj){
1139 showErrorsOn[i].show=true;
1140 showErrorsOn.len.show=true;
1144 if(min!='undef' && max!='undef' && _default!='undef'){
1145 if(!inRange(_default,min,max)){
1147 showErrorsOn.min.show=true;
1148 showErrorsOn.max.show=true;
1149 showErrorsOn._default.show=true;
1152 if(min!='undef' && max!= 'undef' && min > max){
1153 invalidLogic = true;
1154 showErrorsOn.min.show=true;
1155 showErrorsOn.max.show=true;
1157 if(min!='undef' && _default!='undef' && _default < min){
1159 invalidLogic = true;
1160 showErrorsOn.min.show=true;
1161 showErrorsOn._default.show=true;
1163 if(max!='undef' && _default !='undef' && _default>max){
1165 invalidLogic = true;
1166 showErrorsOn.max.show=true;
1167 showErrorsOn._default.show=true;
1172 for(var error in showErrorsOn)
1173 if(showErrorsOn[error].show)
1174 add_error_style(formname,showErrorsOn[error].value, formsWithFieldLogic.msg);
1179 formsWithFieldLogic = null;
1182 if(formWithPrecision){
1183 if (!isValidPrecision(formWithPrecision.float.value, formWithPrecision.precision.value)){
1185 add_error_style(formname, 'default', SUGAR.language.get('app_strings', 'ERR_COMPATIBLE_PRECISION_VALUE'));
1193 if (isError == true) {
1195 if (self.pageYOffset) // all except Explorer
1197 nwX = self.pageXOffset;
1198 seX = self.innerWidth;
1199 nwY = self.pageYOffset;
1200 seY = self.innerHeight;
1202 else if (document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
1204 nwX = document.documentElement.scrollLeft;
1205 seX = document.documentElement.clientWidth;
1206 nwY = document.documentElement.scrollTop;
1207 seY = document.documentElement.clientHeight;
1209 else if (document.body) // all other Explorers
1211 nwX = document.body.scrollLeft;
1212 seX = document.body.clientWidth;
1213 nwY = document.body.scrollTop;
1214 seY = document.body.clientHeight;
1217 var inView = true; // is there an error within viewport of browser
1218 for(var wp = 0; wp < inputsWithErrors.length; wp++) {
1219 var elementCoor = findElementPos(inputsWithErrors[wp]);
1220 if(!(elementCoor.x >= nwX && elementCoor.y >= nwY &&
1221 elementCoor.x <= seX+nwX && elementCoor.y <= seY+nwY)) { // if input is not within viewport, modify for SI bug 52497
1223 scrollToTop = elementCoor.y - 75;
1224 scrollToLeft = elementCoor.x - 75;
1226 else { // on first input within viewport, don't scroll
1232 if(!inView) window.scrollTo(scrollToLeft,scrollToTop);
1237 disableOnUnloadEditView(form);
1244 * This array is used to remember mark status of rows in browse mode
1246 var marked_row = new Array;
1250 * Sets/unsets the pointer and marker in browse mode
1252 * @param object the table row
1253 * @param interger the row number
1254 * @param string the action calling this script (over, out or click)
1255 * @param string the default background color
1256 * @param string the color to use for mouseover
1257 * @param string the color to use for marking a row
1259 * @return boolean whether pointer is set or not
1261 function setPointer(theRow, theRowNum, theAction, theDefaultColor, thePointerColor, theMarkColor) {
1262 var theCells = null;
1264 // 1. Pointer and mark feature are disabled or the browser can't get the
1266 if ((thePointerColor == '' && theMarkColor == '')
1267 || typeof(theRow.style) == 'undefined') {
1271 // 2. Gets the current row and exits if the browser can't get it
1272 if (typeof(document.getElementsByTagName) != 'undefined') {
1273 theCells = theRow.getElementsByTagName('td');
1275 else if (typeof(theRow.cells) != 'undefined') {
1276 theCells = theRow.cells;
1282 // 3. Gets the current color...
1283 var rowCellsCnt = theCells.length;
1284 var domDetect = null;
1285 var currentColor = null;
1286 var newColor = null;
1287 // 3.1 ... with DOM compatible browsers except Opera that does not return
1288 // valid values with "getAttribute"
1289 if (typeof(window.opera) == 'undefined'
1290 && typeof(theCells[0].getAttribute) != 'undefined') {
1291 currentColor = theCells[0].getAttribute('bgcolor');
1294 // 3.2 ... with other browsers
1296 currentColor = theCells[0].style.backgroundColor;
1300 // 4. Defines the new color
1301 // 4.1 Current color is the default one
1302 if (currentColor == ''
1303 || (currentColor!= null && (currentColor.toLowerCase() == theDefaultColor.toLowerCase()))) {
1304 if (theAction == 'over' && thePointerColor != '') {
1305 newColor = thePointerColor;
1307 else if (theAction == 'click' && theMarkColor != '') {
1308 newColor = theMarkColor;
1309 marked_row[theRowNum] = true;
1312 // 4.1.2 Current color is the pointer one
1313 else if (currentColor!= null && (currentColor.toLowerCase() == thePointerColor.toLowerCase())
1314 && (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])) {
1315 if (theAction == 'out') {
1316 newColor = theDefaultColor;
1318 else if (theAction == 'click' && theMarkColor != '') {
1319 newColor = theMarkColor;
1320 marked_row[theRowNum] = true;
1323 // 4.1.3 Current color is the marker one
1324 else if (currentColor!= null && (currentColor.toLowerCase() == theMarkColor.toLowerCase())) {
1325 if (theAction == 'click') {
1326 newColor = (thePointerColor != '')
1329 marked_row[theRowNum] = (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])
1335 // 5. Sets the new color...
1338 // 5.1 ... with DOM compatible browsers except Opera
1340 for (c = 0; c < rowCellsCnt; c++) {
1341 theCells[c].setAttribute('bgcolor', newColor, 0);
1344 // 5.2 ... with other browsers
1346 for (c = 0; c < rowCellsCnt; c++) {
1347 theCells[c].style.backgroundColor = newColor;
1353 } // end of the 'setPointer()' function
1357 * listbox redirection
1359 function goToUrl(selObj, goToLocation) {
1360 eval("document.location.href = '" + goToLocation + "pos=" + selObj.options[selObj.selectedIndex].value + "'");
1365 var json_objects = new Object();
1367 function getXMLHTTPinstance() {
1368 var xmlhttp = false;
1369 var userAgent = navigator.userAgent.toLowerCase() ;
1371 // IE Check supports ActiveX controls
1372 if (userAgent.indexOf("msie") != -1 && userAgent.indexOf("mac") == -1 && userAgent.indexOf("opera") == -1) {
1373 var version = navigator.appVersion.match(/MSIE (.\..)/)[1] ;
1374 if(version >= 5.5 ) {
1376 xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
1380 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
1389 if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
1390 xmlhttp = new XMLHttpRequest();
1395 // NOW LOAD THE OBJECT..
1396 var global_xmlhttp = getXMLHTTPinstance();
1398 function http_fetch_sync(url,post_data) {
1399 global_xmlhttp = getXMLHTTPinstance();
1402 if(typeof(post_data) != 'undefined') method = 'POST';
1404 global_xmlhttp.open(method, url,false);
1407 alert('message:'+e.message+":url:"+url);
1409 if(method == 'POST') {
1410 global_xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
1413 global_xmlhttp.send(post_data);
1415 if (SUGAR.util.isLoginPage(global_xmlhttp.responseText))
1418 var args = {"responseText" : global_xmlhttp.responseText,
1419 "responseXML" : global_xmlhttp.responseXML,
1420 "request_id" : typeof(request_id) != "undefined" ? request_id : 0};
1424 // this is a GET unless post_data is defined
1426 function http_fetch_async(url,callback,request_id,post_data) {
1428 if(typeof(post_data) != 'undefined') {
1433 global_xmlhttp.open(method, url,true);
1436 alert('message:'+e.message+":url:"+url);
1438 if(method == 'POST') {
1439 global_xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
1441 global_xmlhttp.onreadystatechange = function() {
1442 if(global_xmlhttp.readyState==4) {
1443 if(global_xmlhttp.status == 200) {
1444 if (SUGAR.util.isLoginPage(global_xmlhttp.responseText))
1446 var args = {"responseText" : global_xmlhttp.responseText,
1447 "responseXML" : global_xmlhttp.responseXML,
1448 "request_id" : request_id };
1449 callback.call(document,args);
1452 alert("There was a problem retrieving the XML data:\n" + global_xmlhttp.statusText);
1456 global_xmlhttp.send(post_data);
1459 function insert_at_cursor(field, value) {
1461 if (document.selection) {
1463 sel = document.selection.createRange();
1467 else if(field.selectionStart || field.selectionStart == '0') {
1468 var start_pos = field.selectionStart;
1469 var end_pos = field.selectionEnd;
1470 field.value = field.value.substring(0, start_pos) + value + field.value.substring(end_pos, field.value.length);
1473 field.value += value;
1477 function checkParentType(type,button) {
1478 if(button == null) {
1481 if(typeof disabledModules != 'undefined' && typeof(disabledModules[type]) != 'undefined') {
1482 button.disabled='disabled';
1485 button.disabled = false;
1489 function parseDate(input, format) {
1491 format = format.replace(/%/g, '');
1492 sep = format.charAt(1);
1493 yAt = format.indexOf('Y')
1494 // 1-1-06 or 1-12-06 or 1-1-2006 or 1-12-2006
1495 if(date.match(/^\d{1,2}[\/-]\d{1,2}[\/-]\d{2,4}$/) && yAt == 4) {
1496 if(date.match(/^\d{1}[\/-].*$/)) date = '0' + date;
1497 if(date.match(/^\d{2}[\/-]\d{1}[\/-].*$/)) date = date.substring(0,3) + '0' + date.substring(3,date.length);
1498 if(date.match(/^\d{2}[\/-]\d{2}[\/-]\d{2}$/)) date = date.substring(0,6) + '20' + date.substring(6,date.length);
1500 // 06-11-1 or 06-1-1
1501 else if(date.match(/^\d{2,4}[\/-]\d{1,2}[\/-]\d{1,2}$/)) {
1502 if(date.match(/^\d{2}[\/-].*$/)) date = '20' + date;
1503 if(date.match(/^\d{4}[\/-]\d{1}[\/-].*$/)) date = date.substring(0,5) + '0' + date.substring(5,date.length);
1504 if(date.match(/^\d{4}[\/-]\d{2}[\/-]\d{1}$/)) date = date.substring(0,8) + '0' + date.substring(8,date.length);
1506 else if(date.match(/^\d{4,8}$/)) { // digits only
1508 if(date.match(/^\d{8}$/)) digits = 8;// match for 8 digits
1509 else if(date.match(/\d{6}/)) digits = 6;// match for 5 digits
1510 else if(date.match(/\d{4}/)) digits = 4;// match for 5 digits
1511 else if(date.match(/\d{5}/)) digits = 5;// match for 5 digits
1516 case 4: date = '20' + date.substring(0,2) + sep + '0' + date.substring(2, 3) + sep + '0' + date.substring(3,4); break;
1517 case 5: date = '20' + date.substring(0,2) + sep + date.substring(2, 4) + sep + '0' + date.substring(4,5); break;
1518 case 6: date = '20' + date.substring(0,2) + sep + date.substring(2, 4) + sep + date.substring(4,6); break;
1519 case 8: date = date.substring(0,4) + sep + date.substring(4, 6) + sep + date.substring(6,8); break;
1524 case 4: date = '0' + date.substring(0,1) + sep + '20' + date.substring(1, 3) + sep + '0' + date.substring(3,4); break;
1525 case 5: date = date.substring(0,2) + sep + '20' + date.substring(2, 4) + sep + '0' + date.substring(4,5); break;
1526 case 6: date = date.substring(0,2) + sep + '20' + date.substring(2, 4) + sep + date.substring(4,6); break;
1527 case 8: date = date.substring(0,2) + sep + date.substring(2, 6) + sep + date.substring(6,8); break;
1531 case 4: date = '0' + date.substring(0,1) + sep + '0' + date.substring(1, 2) + sep + '20' + date.substring(2,4); break;
1532 case 5: date = '0' + date.substring(0,1) + sep + date.substring(1, 3) + sep + '20' + date.substring(3,5); break;
1533 case 6: date = date.substring(0,2) + sep + date.substring(2, 4) + sep + '20' + date.substring(4,6); break;
1534 case 8: date = date.substring(0,2) + sep + date.substring(2, 4) + sep + date.substring(4,8); break;
1539 date = date.replace(/[\/-]/g, sep);
1543 // find obj's position
1544 function findElementPos(obj) {
1547 if (obj.offsetParent) {
1548 while (obj.offsetParent) {
1549 x += obj.offsetLeft;
1551 obj = obj.offsetParent;
1553 }//if offsetParent exists
1554 else if (obj.x && obj.y) {
1558 return new coordinate(x, y);
1562 // get dimensions of the browser window
1563 function getClientDim() {
1564 var nwX, nwY, seX, seY;
1565 if (self.pageYOffset) // all except Explorer
1567 nwX = self.pageXOffset;
1568 seX = self.innerWidth + nwX;
1569 nwY = self.pageYOffset;
1570 seY = self.innerHeight + nwY;
1572 else if (document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
1574 nwX = document.documentElement.scrollLeft;
1575 seX = document.documentElement.clientWidth + nwX;
1576 nwY = document.documentElement.scrollTop;
1577 seY = document.documentElement.clientHeight + nwY;
1579 else if (document.body) // all other Explorers
1581 nwX = document.body.scrollLeft;
1582 seX = document.body.clientWidth + nwX;
1583 nwY = document.body.scrollTop;
1584 seY = document.body.clientHeight + nwY;
1586 return {'nw' : new coordinate(nwX, nwY), 'se' : new coordinate(seX, seY)};
1590 * stop propagation on events
1592 function freezeEvent(e) {
1594 if (e.preventDefault) e.preventDefault();
1595 e.returnValue = false;
1596 e.cancelBubble = true;
1597 if (e.stopPropagation) e.stopPropagation();
1606 function coordinate(_x, _y) {
1615 return new position(this.x + rh.x, this.y + rh.y);
1619 return new position(this.x + rh.x, this.y + rh.y);
1623 // sends theForm via AJAX and fills in the theDiv
1624 function sendAndRetrieve(theForm, theDiv, loadingStr) {
1625 function success(data) {
1626 document.getElementById(theDiv).innerHTML = data.responseText;
1627 ajaxStatus.hideStatus();
1629 if(typeof loadingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
1630 ajaxStatus.showStatus(loadingStr);
1631 oForm = new YAHOO.util.Element(theForm);
1632 if ( oForm.get('enctype') && oForm.get('enctype') == 'multipart/form-data' ) {
1633 // the second argument is true to indicate file upload.
1634 YAHOO.util.Connect.setForm(theForm, true);
1635 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {upload: success, failure: success});
1637 YAHOO.util.Connect.setForm(theForm);
1638 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
1643 //save the form and redirect
1644 function sendAndRedirect(theForm, loadingStr, redirect_location) {
1645 function success(data) {
1646 if(redirect_location){
1647 location.href=redirect_location;
1649 ajaxStatus.hideStatus();
1651 if(typeof loadingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
1652 ajaxStatus.showStatus(loadingStr);
1653 oForm = new YAHOO.util.Element(theForm);
1654 if ( oForm.get('enctype') && oForm.get('enctype') == 'multipart/form-data' ) {
1655 // the second argument is true to indicate file upload.
1656 YAHOO.util.Connect.setForm(theForm, true);
1657 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {upload: success, failure: success});
1659 YAHOO.util.Connect.setForm(theForm);
1660 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
1665 function saveForm(theForm, theDiv, loadingStr) {
1666 if(check_form(theForm)){
1667 for(i = 0; i < ajaxFormArray.length; i++){
1668 if(ajaxFormArray[i] == theForm){
1669 ajaxFormArray.splice(i, 1);
1672 return sendAndRetrieve(theForm, loadingStr, theDiv);
1678 // Builds a "snapshot" of the form, so we can use it to see if someone has changed it.
1679 function snapshotForm(theForm) {
1680 var snapshotTxt = '';
1681 var elemList = theForm.elements;
1685 for( var i = 0; i < elemList.length ; i++ ) {
1687 if ( typeof(elem.type) == 'undefined' ) {
1691 elemType = elem.type.toLowerCase();
1693 snapshotTxt = snapshotTxt + elem.name;
1695 if ( elemType == 'text' || elemType == 'textarea' || elemType == 'password' ) {
1696 snapshotTxt = snapshotTxt + elem.value;
1698 else if ( elemType == 'select' || elemType == 'select-one' || elemType == 'select-multiple' ) {
1699 var optionList = elem.options;
1700 for ( var ii = 0 ; ii < optionList.length ; ii++ ) {
1701 if ( optionList[ii].selected ) {
1702 snapshotTxt = snapshotTxt + optionList[ii].value;
1706 else if ( elemType == 'radio' || elemType == 'checkbox' ) {
1707 if ( elem.selected ) {
1708 snapshotTxt = snapshotTxt + 'checked';
1711 else if ( elemType == 'hidden' ) {
1712 snapshotTxt = snapshotTxt + elem.value;
1719 function initEditView(theForm) {
1720 if (SUGAR.util.ajaxCallInProgress()) {
1721 window.setTimeout(function(){initEditView(theForm);}, 100);
1725 if ( theForm == null || theForm.id == null ) {
1726 // Not much we can do here.
1730 // we don't need to check if the data is changed in the search popup
1731 if (theForm.id == 'popup_query_form' || theForm.id == 'MassUpdate') {
1734 if ( typeof editViewSnapshots == 'undefined' || editViewSnapshots == null ) {
1735 editViewSnapshots = new Object();
1737 if ( typeof SUGAR.loadedForms == 'undefined' || SUGAR.loadedForms == null) {
1738 SUGAR.loadedForms = new Object();
1741 editViewSnapshots[theForm.id] = snapshotForm(theForm);
1742 SUGAR.loadedForms[theForm.id] = true;
1745 function onUnloadEditView(theForm) {
1747 var dataHasChanged = false;
1748 if ( typeof editViewSnapshots == 'undefined' ) {
1749 // No snapshots, move along
1753 if ( typeof theForm == 'undefined' ) {
1754 // Need to check all editViewSnapshots
1755 for ( var idx in editViewSnapshots ) {
1757 theForm = document.getElementById(idx);
1758 // console.log('DEBUG: Checking all forms '+theForm.id);
1759 if ( theForm == null
1760 || typeof editViewSnapshots[theForm.id] == 'undefined'
1761 || editViewSnapshots[theForm.id] == null
1762 || !SUGAR.loadedForms[theForm.id]) {
1766 var snap = snapshotForm(theForm);
1767 if ( editViewSnapshots[theForm.id] != snap ) {
1768 dataHasChanged = true;
1772 // Just need to check a single form for changes
1773 if ( editViewSnapshots == null || typeof theForm.id == 'undefined' || typeof editViewSnapshots[theForm.id] == 'undefined' || editViewSnapshots[theForm.id] == null ) {
1777 // console.log('DEBUG: Checking one form '+theForm.id);
1778 if ( editViewSnapshots[theForm.id] != snapshotForm(theForm) ) {
1779 // Data has changed.
1780 dataHasChanged = true;
1784 if ( dataHasChanged == true ) {
1785 return SUGAR.language.get('app_strings','WARN_UNSAVED_CHANGES');
1792 function disableOnUnloadEditView(theForm) {
1793 // If you don't pass anything in, it disables all checking
1794 if ( typeof theForm == 'undefined' || typeof editViewSnapshots == 'undefined' || theForm == null || editViewSnapshots == null) {
1795 window.onbeforeunload = null;
1796 editViewSnapshots = null;
1798 // console.log('DEBUG: Disabling all edit view checks');
1801 // Otherwise, it just disables it for this form
1802 if ( typeof(theForm.id) != 'undefined' && typeof(editViewSnapshots[theForm.id]) != 'undefined' ) {
1803 editViewSnapshots[theForm.id] = null;
1806 // console.log('DEBUG : Disabling just checks for '+theForm.id);
1812 * save some forms using an ajax call
1813 * theForms - the ids of all of theh forms to save
1814 * savingStr - the string to display when saving the form
1815 * completeStr - the string to display when the form has been saved
1817 function saveForms( savingStr, completeStr) {
1819 theForms = ajaxFormArray;
1820 function success(data) {
1821 var theForm = document.getElementById(ajaxFormArray[0]);
1822 document.getElementById('multiedit_'+theForm.id).innerHTML = data.responseText;
1823 var saveAllButton = document.getElementById('ajaxsaveall');
1824 ajaxFormArray.splice(index, 1);
1825 if(saveAllButton && ajaxFormArray.length <= 1){
1826 saveAllButton.style.visibility = 'hidden';
1829 if(index == theForms.length){
1830 ajaxStatus.showStatus(completeStr);
1831 window.setTimeout('ajaxStatus.hideStatus();', 2000);
1833 saveAllButton.style.visibility = 'hidden';
1838 if(typeof savingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
1839 ajaxStatus.showStatus(savingStr);
1841 //loop through the forms saving each one
1842 for(i = 0; i < theForms.length; i++){
1843 var theForm = document.getElementById(theForms[i]);
1844 if(check_form(theForm.id)){
1845 theForm.action.value='AjaxFormSave';
1846 YAHOO.util.Connect.setForm(theForm);
1847 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
1849 ajaxStatus.hideStatus();
1851 lastSubmitTime = lastSubmitTime-2000;
1856 // -- start sugarListView class
1857 // js functions used for ListView
1858 function sugarListView() {
1862 sugarListView.prototype.confirm_action = function(del) {
1864 return confirm( SUGAR.language.get('app_strings', 'NTC_DELETE_CONFIRMATION_NUM') + sugarListView.get_num_selected() + SUGAR.language.get('app_strings', 'NTC_DELETE_SELECTED_RECORDS'));
1867 return confirm( SUGAR.language.get('app_strings', 'NTC_UPDATE_CONFIRMATION_NUM') + sugarListView.get_num_selected() + SUGAR.language.get('app_strings', 'NTC_DELETE_SELECTED_RECORDS'));
1871 sugarListView.get_num_selected = function () {
1872 var selectCount = $("input[name='selectCount[]']:first");
1873 if(selectCount.length > 0)
1874 return parseInt(selectCount.val().replace("+", ""));
1878 sugarListView.update_count = function(count, add) {
1879 if(typeof document.MassUpdate != 'undefined') {
1880 the_form = document.MassUpdate;
1881 for(var wp = 0; wp < the_form.elements.length; wp++) {
1882 if(typeof the_form.elements[wp].name != 'undefined' && the_form.elements[wp].name == 'selectCount[]') {
1884 the_form.elements[wp].value = parseInt(the_form.elements[wp].value,10) + count;
1885 if (the_form.select_entire_list.value == 1 && the_form.show_plus.value) {
1886 the_form.elements[wp].value += '+';
1889 if (the_form.select_entire_list.value == 1 && the_form.show_plus.value) {
1890 the_form.elements[wp].value = count + '+';
1892 the_form.elements[wp].value = count;
1899 sugarListView.prototype.use_external_mail_client = function(no_record_txt, module) {
1900 selected_records = sugarListView.get_checks_count();
1901 if(selected_records <1) {
1902 alert(no_record_txt);
1906 if (document.MassUpdate.select_entire_list.value == 1) {
1907 if (totalCount > 10) {
1908 alert(totalCountError);
1913 else if (document.MassUpdate.massall.checked == true)
1917 sugarListView.get_checks();
1919 if(select) { // use selected items
1920 ids = document.MassUpdate.uid.value;
1922 else { // use current page
1923 inputs = document.MassUpdate.elements;
1925 for(i = 0; i < inputs.length; i++) {
1926 if(inputs[i].name == 'mass[]' && inputs[i].checked && typeof(inputs[i].value) != 'function') {
1927 ar.push(inputs[i].value);
1932 YAHOO.util.Connect.asyncRequest("POST", "index.php?", {
1933 success: this.use_external_mail_client_callback
1934 }, SUGAR.util.paramsToUrl({
1937 listViewExternalClient: 1,
1938 action_module: module,
1946 sugarListView.prototype.use_external_mail_client_callback = function(o)
1949 location.href = 'mailto:' + o.responseText;
1952 sugarListView.prototype.send_form_for_emails = function(select, currentModule, action, no_record_txt,action_module,totalCount, totalCountError) {
1953 if ( typeof(SUGAR.config.email_sugarclient_listviewmaxselect) != 'undefined' ) {
1957 maxCount = SUGAR.config.email_sugarclient_listviewmaxselect;
1960 if (document.MassUpdate.select_entire_list.value == 1) {
1961 if (totalCount > maxCount) {
1962 alert(totalCountError);
1967 else if (document.MassUpdate.massall.checked == true)
1972 sugarListView.get_checks();
1973 // create new form to post (can't access action property of MassUpdate form due to action input)
1974 var newForm = document.createElement('form');
1975 newForm.method = 'post';
1976 newForm.action = action;
1977 newForm.name = 'newForm';
1978 newForm.id = 'newForm';
1979 var uidTa = document.createElement('textarea');
1981 uidTa.style.display = 'none';
1983 if(select) { // use selected items
1984 uidTa.value = document.MassUpdate.uid.value;
1986 else { // use current page
1987 inputs = document.MassUpdate.elements;
1989 for(i = 0; i < inputs.length; i++) {
1990 if(inputs[i].name == 'mass[]' && inputs[i].checked && typeof(inputs[i].value) != 'function') {
1991 ar.push(inputs[i].value);
1994 uidTa.value = ar.join(',');
1997 if(uidTa.value == '') {
1998 alert(no_record_txt);
2002 var selectedArray = uidTa.value.split(",");
2003 if(selectedArray.length > maxCount) {
2004 alert(totalCountError);
2007 newForm.appendChild(uidTa);
2009 var moduleInput = document.createElement('input');
2010 moduleInput.name = 'module';
2011 moduleInput.type = 'hidden';
2012 moduleInput.value = currentModule;
2013 newForm.appendChild(moduleInput);
2015 var actionInput = document.createElement('input');
2016 actionInput.name = 'action';
2017 actionInput.type = 'hidden';
2018 actionInput.value = 'Compose';
2019 newForm.appendChild(actionInput);
2021 if (typeof action_module != 'undefined' && action_module!= '') {
2022 var actionModule = document.createElement('input');
2023 actionModule.name = 'action_module';
2024 actionModule.type = 'hidden';
2025 actionModule.value = action_module;
2026 newForm.appendChild(actionModule);
2028 //return_info must follow this pattern."&return_module=Accounts&return_action=index"
2029 if (typeof return_info!= 'undefined' && return_info != '') {
2030 var params= return_info.split('&');
2031 if (params.length > 0) {
2032 for (var i=0;i< params.length;i++) {
2033 if (params[i].length > 0) {
2034 var param_nv=params[i].split('=');
2035 if (param_nv.length==2){
2036 returnModule = document.createElement('input');
2037 returnModule.name = param_nv[0];
2038 returnModule.type = 'hidden';
2039 returnModule.value = param_nv[1];
2040 newForm.appendChild(returnModule);
2047 var isAjaxCall = document.createElement('input');
2048 isAjaxCall.name = 'ajaxCall';
2049 isAjaxCall.type = 'hidden';
2050 isAjaxCall.value = true;
2051 newForm.appendChild(isAjaxCall);
2053 var isListView = document.createElement('input');
2054 isListView.name = 'ListView';
2055 isListView.type = 'hidden';
2056 isListView.value = true;
2057 newForm.appendChild(isListView);
2059 var toPdf = document.createElement('input');
2060 toPdf.name = 'to_pdf';
2061 toPdf.type = 'hidden';
2063 newForm.appendChild(toPdf);
2065 //Grab the Quick Compose package for the listview
2066 YAHOO.util.Connect.setForm(newForm);
2069 success: function(o) {
2070 var resp = YAHOO.lang.JSON.parse(o.responseText);
2071 var quickComposePackage = new Object();
2072 quickComposePackage.composePackage = resp;
2073 quickComposePackage.fullComposeUrl = 'index.php?module=Emails&action=Compose&ListView=true' +
2074 '&uid=' + uidTa.value + '&action_module=' + action_module;
2076 SUGAR.quickCompose.init(quickComposePackage);
2080 YAHOO.util.Connect.asyncRequest('POST','index.php', callback,null);
2082 // awu Bug 18624: Fixing issue where a canceled Export and unselect of row will persist the uid field, clear the field
2083 document.MassUpdate.uid.value = '';
2088 sugarListView.prototype.send_form = function(select, currentModule, action, no_record_txt,action_module,return_info) {
2089 if (document.MassUpdate.select_entire_list.value == 1) {
2091 if(sugarListView.get_checks_count() < 1) {
2092 alert(no_record_txt);
2097 if ( action.indexOf('?') != -1 )
2098 href += '&module=' + currentModule;
2100 href += '?module=' + currentModule;
2103 href += return_info;
2104 var newForm = document.createElement('form');
2105 newForm.method = 'post';
2106 newForm.action = href;
2107 newForm.name = 'newForm';
2108 newForm.id = 'newForm';
2109 var postTa = document.createElement('textarea');
2110 postTa.name = 'current_post';
2111 postTa.value = document.MassUpdate.current_query_by_page.value;
2112 postTa.style.display = 'none';
2113 newForm.appendChild(postTa);
2114 document.MassUpdate.parentNode.appendChild(newForm);
2118 else if (document.MassUpdate.massall.checked == true)
2123 sugarListView.get_checks();
2124 // create new form to post (can't access action property of MassUpdate form due to action input)
2125 var newForm = document.createElement('form');
2126 newForm.method = 'post';
2127 newForm.action = action;
2128 newForm.name = 'newForm';
2129 newForm.id = 'newForm';
2130 var uidTa = document.createElement('textarea');
2132 uidTa.style.display = 'none';
2133 uidTa.value = document.MassUpdate.uid.value;
2135 if(uidTa.value == '') {
2136 alert(no_record_txt);
2140 newForm.appendChild(uidTa);
2142 var moduleInput = document.createElement('input');
2143 moduleInput.name = 'module';
2144 moduleInput.type = 'hidden';
2145 moduleInput.value = currentModule;
2146 newForm.appendChild(moduleInput);
2148 var actionInput = document.createElement('input');
2149 actionInput.name = 'action';
2150 actionInput.type = 'hidden';
2151 actionInput.value = 'index';
2152 newForm.appendChild(actionInput);
2154 if (typeof action_module != 'undefined' && action_module!= '') {
2155 var actionModule = document.createElement('input');
2156 actionModule.name = 'action_module';
2157 actionModule.type = 'hidden';
2158 actionModule.value = action_module;
2159 newForm.appendChild(actionModule);
2161 //return_info must follow this pattern."&return_module=Accounts&return_action=index"
2162 if (typeof return_info!= 'undefined' && return_info != '') {
2163 var params= return_info.split('&');
2164 if (params.length > 0) {
2165 for (var i=0;i< params.length;i++) {
2166 if (params[i].length > 0) {
2167 var param_nv=params[i].split('=');
2168 if (param_nv.length==2){
2169 returnModule = document.createElement('input');
2170 returnModule.name = param_nv[0];
2171 returnModule.type = 'hidden';
2172 returnModule.value = param_nv[1];
2173 newForm.appendChild(returnModule);
2180 document.MassUpdate.parentNode.appendChild(newForm);
2183 // awu Bug 18624: Fixing issue where a canceled Export and unselect of row will persist the uid field, clear the field
2184 document.MassUpdate.uid.value = '';
2188 //return a count of checked row.
2189 sugarListView.get_checks_count = function() {
2192 if(document.MassUpdate.uid.value != '') {
2193 oldUids = document.MassUpdate.uid.value.split(',');
2194 for(uid in oldUids) {
2195 if(typeof(oldUids[uid]) != 'function') {
2196 ar[oldUids[uid]] = 1;
2200 // build associated array of uids, associated array ensures uniqueness
2201 inputs = document.MassUpdate.elements;
2202 for(i = 0; i < inputs.length; i++) {
2203 if(inputs[i].name == 'mass[]') {
2204 ar[inputs[i].value] = (inputs[i].checked) ? 1 : 0; // 0 of it is unchecked
2208 // build regular array of uids
2211 if((typeof(ar[i]) != 'function') && ar[i] == 1) {
2219 // saves the checks on the current page into the uid textarea
2220 sugarListView.get_checks = function() {
2222 if(typeof document.MassUpdate != 'undefined' ){
2223 if(document.MassUpdate.uid.value != '') {
2224 oldUids = document.MassUpdate.uid.value.split(',');
2225 for(uid in oldUids) {
2226 if(typeof(oldUids[uid]) != 'function') {
2227 ar[oldUids[uid]] = 1;
2232 // build associated array of uids, associated array ensures uniqueness
2233 inputs = document.MassUpdate.elements;
2234 for(i = 0; i < inputs.length; i++) {
2235 if(inputs[i].name == 'mass[]') {
2236 ar[inputs[i].value] = (inputs[i].checked) ? 1 : 0; // 0 of it is unchecked
2240 // build regular array of uids
2243 if(typeof(ar[i]) != 'function' && ar[i] == 1) {
2248 document.MassUpdate.uid.value = uids.join(',');
2250 if(uids.length == 0) return false; // return false if no checks to get
2251 return true; // there are saved checks
2256 sugarListView.prototype.order_checks = function(order,orderBy,moduleString){
2257 checks = sugarListView.get_checks();
2258 eval('document.MassUpdate.' + moduleString + '.value = orderBy');
2259 document.MassUpdate.lvso.value = order;
2260 if(typeof document.MassUpdate.massupdate != 'undefined') {
2261 document.MassUpdate.massupdate.value = 'false';
2264 //we must first clear the action of massupdate, change it to index
2265 document.MassUpdate.action.value = document.MassUpdate.return_action.value;
2266 document.MassUpdate.return_module.value='';
2267 document.MassUpdate.return_action.value='';
2268 document.MassUpdate.submit();
2272 sugarListView.prototype.save_checks = function(offset, moduleString) {
2273 checks = sugarListView.get_checks();
2274 if(typeof document.MassUpdate != 'undefined'){
2275 eval('document.MassUpdate.' + moduleString + '.value = offset');
2277 if(typeof document.MassUpdate.massupdate != 'undefined') {
2278 document.MassUpdate.massupdate.value = 'false';
2281 //we must first clear the action of massupdate, change it to index
2282 document.MassUpdate.action.value = document.MassUpdate.return_action.value;
2283 document.MassUpdate.return_module.value='';
2284 document.MassUpdate.return_action.value='';
2285 document.MassUpdate.submit();
2293 sugarListView.prototype.check_item = function(cb, form) {
2295 sugarListView.update_count(1, true);
2298 sugarListView.update_count(-1, true);
2299 if(typeof form != 'undefined' && form != null) {
2300 sugarListView.prototype.updateUid(cb, form);
2303 sugarListView.prototype.toggleSelected();
2306 sugarListView.prototype.toggleSelected = function() {
2308 var numSelected = sugarListView.get_num_selected();
2309 var selectedRecords = document.getElementById("selectedRecordsTop");
2310 var selectActions = document.getElementById("selectActions");
2311 var selectActionsDisabled = document.getElementById("selectActionsDisabled");
2312 if(numSelected > 0) {
2313 $(selectedRecords).removeAttr("style").addClass("show");
2314 $(".selectActionsDisabled").hide();
2315 jQuery('ul[name=selectActions]').each(function () {
2316 jQuery(this).removeAttr("style").addClass("show");
2320 $(selectedRecords).hide();
2321 $(".selectActionsDisabled").removeAttr("style").addClass("show");
2322 jQuery('ul[name=selectActions]').each(function () {
2323 jQuery(this).hide();
2329 /**#28000, remove the unselect record id from MassUpdate.uid **/
2330 sugarListView.prototype.updateUid = function(cb , form){
2331 if(form.name == 'MassUpdate' && form.uid && form.uid.value && cb.value && form.uid.value.indexOf(cb.value) != -1){
2332 if(form.uid.value.indexOf(','+cb.value)!= -1){
2333 form.uid.value = form.uid.value.replace(','+cb.value , '');
2334 }else if(form.uid.value.indexOf(cb.value + ',')!= -1){
2335 form.uid.value = form.uid.value.replace(cb.value + ',' , '');
2336 }else if(form.uid.value.indexOf(cb.value)!= -1){
2337 form.uid.value = form.uid.value.replace(cb.value , '');
2342 sugarListView.prototype.check_entire_list = function(form, field, value, list_count) {
2343 // count number of items
2345 $(document.MassUpdate.massall).each(function(){
2346 $(this).attr('checked', true).attr('disabled', true);
2348 for (i = 0; i < form.elements.length; i++) {
2349 if(form.elements[i].name == field && form.elements[i].disabled == false) {
2350 if(form.elements[i].checked != value) count++;
2351 form.elements[i].checked = value;
2352 form.elements[i].disabled = true;
2355 document.MassUpdate.select_entire_list.value = 1;
2356 sugarListView.update_count(list_count, false);
2357 sugarListView.prototype.toggleSelected();
2360 sugarListView.prototype.check_all = function(form, field, value, pageTotal) {
2361 // count number of items
2363 $(document.MassUpdate.massall).each(function(){$(this).attr('checked', value);});
2364 if (document.MassUpdate.select_entire_list &&
2365 document.MassUpdate.select_entire_list.value == 1)
2367 sugarListView.prototype.toggleSelected();
2368 $(document.MassUpdate.massall).each(function(){$(this).attr('disabled', true);});
2372 $(document.MassUpdate.massall).each(function(){$(this).attr('disabled', false);});
2374 for (i = 0; i < form.elements.length; i++) {
2375 if(form.elements[i].name == field && !(form.elements[i].disabled == true && form.elements[i].checked == false)) {
2376 form.elements[i].disabled = false;
2378 if(form.elements[i].checked != value)
2380 form.elements[i].checked = value;
2382 sugarListView.prototype.updateUid(form.elements[i], form);
2387 sugarListView.update_count(pageTotal);
2389 sugarListView.update_count(count, true);
2391 sugarListView.update_count(-1 * count, true);
2393 sugarListView.prototype.toggleSelected();
2395 sugarListView.check_all = sugarListView.prototype.check_all;
2396 sugarListView.confirm_action = sugarListView.prototype.confirm_action;
2398 sugarListView.prototype.check_boxes = function() {
2399 var inputsCount = 0;
2400 var checkedCount = 0;
2401 var existing_onload = window.onload;
2402 var theForm = document.MassUpdate;
2403 inputs_array = theForm.elements;
2405 if(typeof theForm.uid.value != 'undefined' && theForm.uid.value != "") {
2406 checked_items = theForm.uid.value.split(",");
2407 if (theForm.select_entire_list.value == 1) {
2408 document.MassUpdate.massall.disabled = true;
2409 sugarListView.prototype.toggleSelected();
2410 $("a[name=selectall]:first").click();
2413 for(var wp = 0 ; wp < inputs_array.length; wp++) {
2414 if(inputs_array[wp].name == "mass[]") {
2416 if (theForm.select_entire_list.value == 1) {
2417 inputs_array[wp].checked = true;
2418 inputs_array[wp].disabled = true;
2422 for(i in checked_items) {
2423 if(inputs_array[wp].value == checked_items[i]) {
2425 inputs_array[wp].checked = true;
2426 //Bug#52748: Total # of checked items are calculated in back-end side
2427 //sugarListView.prototype.check_item(inputs_array[wp], document.MassUpdate);
2435 for(var wp = 0 ; wp < inputs_array.length; wp++) {
2436 if(inputs_array[wp].name == "mass[]") {
2437 inputs_array[wp].checked = false;
2438 inputs_array[wp].disabled = false;
2441 if (document.MassUpdate.massall) {
2442 document.MassUpdate.massall.checked = false;
2443 document.MassUpdate.massall.disabled = false;
2445 sugarListView.update_count(0)
2447 if(checkedCount > 0 && checkedCount == inputsCount)
2448 document.MassUpdate.massall.checked = true;
2453 * This function is used in Email Template Module's listview.
2454 * It will check whether the templates are used in Campaing->EmailMarketing.
2455 * If true, it will notify user.
2457 function check_used_email_templates() {
2458 var ids = document.MassUpdate.uid.value;
2460 success:function(r) {
2461 if(r.responseText != '') {
2462 if(!confirm(SUGAR.language.get('app_strings','NTC_TEMPLATES_IS_USED') + r.responseText)) {
2466 document.MassUpdate.submit();
2470 url = "index.php?module=EmailTemplates&action=CheckDeletable&from=ListView&to_pdf=1&records="+ids;
2471 YAHOO.util.Connect.asyncRequest('POST',url, call_back,null);
2475 sugarListView.prototype.send_mass_update = function(mode, no_record_txt, del) {
2476 formValid = check_form('MassUpdate');
2477 if(!formValid && !del) return false;
2480 if (document.MassUpdate.select_entire_list &&
2481 document.MassUpdate.select_entire_list.value == 1)
2486 var ar = new Array();
2490 for(var wp = 0; wp < document.MassUpdate.elements.length; wp++) {
2491 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)+'$');
2492 //when the uid is already in document.MassUpdate.uid.value, we should not add it to ar.
2493 if(typeof document.MassUpdate.elements[wp].name != 'undefined'
2494 && document.MassUpdate.elements[wp].name == 'mass[]'
2495 && document.MassUpdate.elements[wp].checked
2496 && !reg_for_existing_uid.test(document.MassUpdate.uid.value)) {
2497 ar.push(document.MassUpdate.elements[wp].value);
2500 if(document.MassUpdate.uid.value != '') document.MassUpdate.uid.value += ',';
2501 document.MassUpdate.uid.value += ar.join(',');
2502 if(document.MassUpdate.uid.value == '') {
2503 alert(no_record_txt);
2506 if(typeof(current_admin_id)!='undefined' && document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'Users' && (document.MassUpdate.is_admin.value!='' || document.MassUpdate.status.value!='')) {
2507 var reg_for_current_admin_id = new RegExp('^'+current_admin_id+'[\s]*,|,[\s]*'+current_admin_id+'[\s]*,|,[\s]*'+current_admin_id+'$|^'+current_admin_id+'$');
2508 if(reg_for_current_admin_id.test(document.MassUpdate.uid.value)) {
2509 //if current user is admin, we should not allow massupdate the user_type and status of himself
2510 alert(SUGAR.language.get('Users','LBL_LAST_ADMIN_NOTICE'));
2516 var entireInput = document.createElement('input');
2517 entireInput.name = 'entire';
2518 entireInput.type = 'hidden';
2519 entireInput.value = 'index';
2520 document.MassUpdate.appendChild(entireInput);
2521 //confirm(no_record_txt);
2522 if(document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'Users' && (document.MassUpdate.is_admin.value!='' || document.MassUpdate.status.value!='')) {
2523 alert(SUGAR.language.get('Users','LBL_LAST_ADMIN_NOTICE'));
2529 if(!sugarListView.confirm_action(del))
2533 var deleteInput = document.createElement('input');
2534 deleteInput.name = 'Delete';
2535 deleteInput.type = 'hidden';
2536 deleteInput.value = true;
2537 document.MassUpdate.appendChild(deleteInput);
2538 if(document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'EmailTemplates') {
2539 check_used_email_templates();
2545 document.MassUpdate.submit();
2550 sugarListView.prototype.clear_all = function() {
2551 document.MassUpdate.uid.value = '';
2552 document.MassUpdate.select_entire_list.value = 0;
2553 sugarListView.check_all(document.MassUpdate, 'mass[]', false);
2554 $(document.MassUpdate.massall).each(function(){
2555 $(this).attr('checked', false).attr('disabled', false);
2557 sugarListView.update_count(0);
2558 sugarListView.prototype.toggleSelected();
2561 sListView = new sugarListView();
2562 // -- end sugarListView class
2564 // format and unformat numbers
2565 function unformatNumber(n, num_grp_sep, dec_sep) {
2566 var x=unformatNumberNoParse(n, num_grp_sep, dec_sep);
2569 return parseFloat(x);
2574 function unformatNumberNoParse(n, num_grp_sep, dec_sep) {
2575 if(typeof num_grp_sep == 'undefined' || typeof dec_sep == 'undefined') return n;
2576 n = n ? n.toString() : '';
2579 if(num_grp_sep != '')
2581 num_grp_sep_re = new RegExp('\\'+num_grp_sep, 'g');
2582 n = n.replace(num_grp_sep_re, '');
2585 n = n.replace(dec_sep, '.');
2587 if(typeof CurrencySymbols != 'undefined') {
2588 // Need to strip out the currency symbols from the start.
2589 for ( var idx in CurrencySymbols ) {
2590 n = n.replace(CurrencySymbols[idx], '');
2598 // round parameter can be negative for decimal, precision has to be postive
2599 function formatNumber(n, num_grp_sep, dec_sep, round, precision) {
2600 if(typeof num_grp_sep == 'undefined' || typeof dec_sep == 'undefined') return n;
2601 n = n ? n.toString() : '';
2602 if(n.split) n = n.split('.');
2605 if(n.length > 2) return n.join('.'); // that's not a num!
2607 if(typeof round != 'undefined') {
2608 if(round > 0 && n.length > 1) { // round to decimal
2609 n[1] = parseFloat('0.' + n[1]);
2610 n[1] = Math.round(n[1] * Math.pow(10, round)) / Math.pow(10, round);
2611 n[1] = n[1].toString().split('.')[1];
2613 if(round <= 0) { // round to whole number
2614 n[0] = Math.round(parseInt(n[0],10) * Math.pow(10, round)) / Math.pow(10, round);
2619 if(typeof precision != 'undefined' && precision >= 0) {
2620 if(n.length > 1 && typeof n[1] != 'undefined') n[1] = n[1].substring(0, precision); // cut off precision
2622 if(n[1].length < precision) {
2623 for(var wp = n[1].length; wp < precision; wp++) n[1] += '0';
2627 regex = /(\d+)(\d{3})/;
2628 while(num_grp_sep != '' && regex.test(n[0])) n[0] = n[0].toString().replace(regex, '$1' + num_grp_sep + '$2');
2629 return n[0] + (n.length > 1 && n[1] != '' ? dec_sep + n[1] : '');
2632 // --- begin ajax status class
2633 SUGAR.ajaxStatusClass = function() {};
2634 SUGAR.ajaxStatusClass.prototype.statusDiv = null;
2635 SUGAR.ajaxStatusClass.prototype.oldOnScroll = null;
2636 SUGAR.ajaxStatusClass.prototype.shown = false; // state of the status window
2638 // reposition the status div, top and centered
2639 SUGAR.ajaxStatusClass.prototype.positionStatus = function() {
2640 //this.statusDiv.style.top = document.body.scrollTop + 8 + 'px';
2641 statusDivRegion = YAHOO.util.Dom.getRegion(this.statusDiv);
2642 statusDivWidth = statusDivRegion.right - statusDivRegion.left;
2643 this.statusDiv.style.left = YAHOO.util.Dom.getViewportWidth() / 2 - statusDivWidth / 2 + 'px';
2646 // private func, create the status div
2647 SUGAR.ajaxStatusClass.prototype.createStatus = function(text) {
2648 statusDiv = document.createElement('div');
2649 statusDiv.className = 'dataLabel';
2650 statusDiv.id = 'ajaxStatusDiv';
2651 document.body.appendChild(statusDiv);
2652 this.statusDiv = document.getElementById('ajaxStatusDiv');
2655 // public - show the status div with text
2656 SUGAR.ajaxStatusClass.prototype.showStatus = function(text) {
2657 if(!this.statusDiv) {
2658 this.createStatus(text);
2661 this.statusDiv.style.display = '';
2663 this.statusDiv.innerHTML = ' <b>' + text + '</b> ';
2664 this.positionStatus();
2667 this.statusDiv.style.display = '';
2668 if(window.onscroll) this.oldOnScroll = window.onscroll; // save onScroll
2669 window.onscroll = this.positionStatus;
2674 SUGAR.ajaxStatusClass.prototype.hideStatus = function(text) {
2675 if(!this.shown) return;
2677 if(this.oldOnScroll) window.onscroll = this.oldOnScroll;
2678 else window.onscroll = '';
2679 this.statusDiv.style.display = 'none';
2682 SUGAR.ajaxStatusClass.prototype.flashStatus = function(text, time){
2683 this.showStatus(text);
2684 window.setTimeout('ajaxStatus.hideStatus();', time);
2688 var ajaxStatus = new SUGAR.ajaxStatusClass();
2689 // --- end ajax status class
2692 * Unified Search Advanced - for global search
2694 SUGAR.unifiedSearchAdvanced = function() {
2704 SUGAR.unifiedSearchAdvanced.usa_div = document.getElementById('unified_search_advanced_div');
2705 SUGAR.unifiedSearchAdvanced.usa_img = document.getElementById('unified_search_advanced_img');
2707 if(!SUGAR.unifiedSearchAdvanced.usa_div || !SUGAR.unifiedSearchAdvanced.usa_img) return;
2708 var attributes = { height: { to: 300 } };
2709 SUGAR.unifiedSearchAdvanced.anim_open = new YAHOO.util.Anim('unified_search_advanced_div', attributes );
2710 SUGAR.unifiedSearchAdvanced.anim_open.duration = 0.75;
2711 SUGAR.unifiedSearchAdvanced.anim_close = new YAHOO.util.Anim('unified_search_advanced_div', { height: {to: 0} } );
2712 SUGAR.unifiedSearchAdvanced.anim_close.duration = 0.75;
2713 //SUGAR.unifiedSearchAdvanced.anim_close.onComplete.subscribe(function() {SUGAR.unifiedSearchAdvanced.usa_div.style.display = 'none'});
2715 SUGAR.unifiedSearchAdvanced.usa_img._x = YAHOO.util.Dom.getX(SUGAR.unifiedSearchAdvanced.usa_img);
2716 SUGAR.unifiedSearchAdvanced.usa_img._y = YAHOO.util.Dom.getY(SUGAR.unifiedSearchAdvanced.usa_img);
2719 SUGAR.unifiedSearchAdvanced.usa_open = false;
2720 SUGAR.unifiedSearchAdvanced.usa_content = null;
2722 YAHOO.util.Event.addListener('unified_search_advanced_img', 'click', SUGAR.unifiedSearchAdvanced.get_content);
2725 get_content: function(e)
2727 query_string = trim(document.getElementById('query_string').value);
2728 if(query_string != '')
2730 window.location.href = 'index.php?module=Home&action=UnifiedSearch&query_string=' + query_string;
2732 window.location.href = 'index.php?module=Home&action=UnifiedSearch&form_only=true';
2736 animate: function(data) {
2737 ajaxStatus.hideStatus();
2740 SUGAR.unifiedSearchAdvanced.usa_content = data.responseText;
2741 SUGAR.unifiedSearchAdvanced.usa_div.innerHTML = SUGAR.unifiedSearchAdvanced.usa_content;
2743 if(SUGAR.unifiedSearchAdvanced.usa_open) {
2744 document.UnifiedSearch.advanced.value = 'false';
2745 SUGAR.unifiedSearchAdvanced.anim_close.animate();
2748 document.UnifiedSearch.advanced.value = 'true';
2749 SUGAR.unifiedSearchAdvanced.usa_div.style.display = '';
2750 YAHOO.util.Dom.setX(SUGAR.unifiedSearchAdvanced.usa_div, SUGAR.unifiedSearchAdvanced.usa_img._x - 90);
2751 YAHOO.util.Dom.setY(SUGAR.unifiedSearchAdvanced.usa_div, SUGAR.unifiedSearchAdvanced.usa_img._y + 15);
2752 SUGAR.unifiedSearchAdvanced.anim_open.animate();
2754 SUGAR.unifiedSearchAdvanced.usa_open = !SUGAR.unifiedSearchAdvanced.usa_open;
2759 checkUsaAdvanced: function() {
2760 if(document.UnifiedSearch.advanced.value == 'true') {
2761 document.UnifiedSearchAdvanced.query_string.value = document.UnifiedSearch.query_string.value;
2762 document.UnifiedSearchAdvanced.submit();
2769 if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.unifiedSearchAdvanced.init);
2774 * Toggles the header
2776 toggleHeader : function() {
2777 var h = document.getElementById('header');
2781 if(h.style.display == 'none') {
2782 h.style.display = '';
2784 h.style.display = 'none';
2788 alert(SUGAR.language.get("app_strings", "ERR_NO_HEADER_ID"));
2795 * General Sugar Utils
2797 SUGAR.util = function () {
2798 var additionalDetailsCache;
2799 var additionalDetailsCalls;
2800 var additionalDetailsRpcCall;
2803 getAndRemove : function (el) {
2804 if (YAHOO && YAHOO.util && YAHOO.util.Dom)
2805 el = YAHOO.util.Dom.get(el);
2806 else if (typeof (el) == "string")
2807 el = document.getElementById(el);
2808 if (el && el.parentNode)
2809 el.parentNode.removeChild(el);
2813 paramsToUrl : function (params) {
2816 url += i + "=" + params[i] + "&";
2820 // Evaluates a script in a global context
2821 // Workarounds based on findings by Jim Driscoll
2822 // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
2823 globalEval: function( data ) {
2824 var rnotwhite = /\S/;
2825 if ( data && rnotwhite.test( data ) ) {
2826 // We use execScript on Internet Explorer
2827 // We use an anonymous function so that context is window
2828 // rather than jQuery in Firefox
2829 ( window.execScript || function( data ) {
2830 window[ "eval" ].call( window, data );
2834 evalScript:function(text){
2836 var waitUntilLoaded = function(){
2837 SUGAR.evalScript_waitCount--;
2838 if (SUGAR.evalScript_waitCount == 0) {
2839 var headElem = document.getElementsByTagName('head')[0];
2840 for ( var i = 0; i < SUGAR.evalScript_evalElem.length; i++) {
2841 var tmpElem = document.createElement('script');
2842 tmpElem.type = 'text/javascript';
2843 tmpElem.text = SUGAR.evalScript_evalElem[i];
2844 headElem.appendChild(tmpElem);
2849 var tmpElem = document.createElement('div');
2850 tmpElem.innerHTML = text;
2851 var results = tmpElem.getElementsByTagName('script');
2852 if (results == null) {
2853 // No scripts found, bail out
2857 var headElem = document.getElementsByTagName('head')[0];
2859 SUGAR.evalScript_waitCount = 0;
2860 SUGAR.evalScript_evalElem = new Array();
2861 for (var i = 0; i < results.length; i++) {
2862 if (typeof(results[i]) != 'object') {
2865 tmpElem = document.createElement('script');
2866 tmpElem.type = 'text/javascript';
2867 if (results[i].src != null && results[i].src != '') {
2868 tmpElem.src = results[i].src;
2870 // Need to defer execution of these scripts until the
2871 // required javascript files are fully loaded
2872 SUGAR.evalScript_evalElem[SUGAR.evalScript_evalElem.length] = results[i].text;
2875 tmpElem.addEventListener('load', waitUntilLoaded);
2876 SUGAR.evalScript_waitCount++;
2877 headElem.appendChild(tmpElem);
2879 // Add some code to handle pages without any external scripts
2880 SUGAR.evalScript_waitCount++;
2883 // Don't try and process things the IE way
2887 var objRegex = /<\s*script([^>]*)>((.|\s|\v|\0)*?)<\s*\/script\s*>/igm;
2889 var result = objRegex.exec(text);
2890 while(result && result.index > lastIndex){
2891 lastIndex = result.index
2893 // Bug #49205 : Subpanels fail to load when selecting subpanel tab
2894 // Change approach to handle javascripts included to body of ajax response.
2895 // To load & run javascripts and inline javascript in correct order load them as synchronous requests
2896 // JQuery library uses this approach to eval scripts
2897 if(result[1].indexOf("src=") > -1){
2898 var srcRegex = /.*src=['"]([a-zA-Z0-9_\-\&\/\.\?=:-]*)['"].*/igm;
2899 var srcResult = result[1].replace(srcRegex, '$1');
2901 // Check is ulr cross domain or not
2902 var r1 = /:\/\//igm;
2903 if ( r1.test(srcResult) && srcResult.indexOf(window.location.hostname) == -1 )
2905 // if script is cross domain it cannot be loaded via ajax request
2906 // try load script asynchronous by creating script element in the body
2907 // YUI 3.3 doesn't allow load scrips synchronously
2909 YUI().use('get', function (Y)
2911 var url = srcResult;
2912 Y.Get.script(srcResult,
2915 onSuccess : function(o) { },
2916 onFailure: function(o) { },
2917 onTimeout: function(o) { }
2920 // TODO: for YUI 3.5 - load scripts as script object synchronous
2922 YUI().use('get', function (Y) {
2923 var url = srcResult;
2924 Y.Get.js([{url: url, async: false}], function (err) {});
2930 // Bug #49205 : Subpanels fail to load when selecting subpanel tab
2931 // Create a YUI instance using the io-base module.
2932 YUI().use("io-base", function(Y) {
2938 success: function(transactionid, response, arguments)
2940 SUGAR.util.globalEval(response.responseText);
2944 // Call synchronous request to load javascript content
2945 // restonse will be processed in success function
2946 response = Y.io(srcResult, cfg);
2950 // Bug #49205 : Subpanels fail to load when selecting subpanel tab
2951 // execute script in global context
2952 SUGAR.util.globalEval(result[2]);
2956 if(typeof(console) != "undefined" && typeof(console.log) == "function")
2958 console.log("error adding script");
2960 console.log(result);
2963 result = objRegex.exec(text);
2967 * Gets the sidebar object
2968 * @return object pointer to the sidebar element
2970 getLeftColObj: function() {
2971 leftColObj = document.getElementById('leftCol');
2972 while(leftColObj.nodeName != 'TABLE') {
2973 leftColObj = leftColObj.firstChild;
2975 leftColTable = leftColObj;
2976 leftColTd = leftColTable.getElementsByTagName('td')[0];
2977 leftColTdRegion = YAHOO.util.Dom.getRegion(leftColTd);
2978 leftColTd.style.width = (leftColTdRegion.right - leftColTdRegion.left) + 'px';
2983 * Fills the shortcut menu placeholders w/ actual content
2984 * Call this on load event
2986 * @param shortcutContent Array array of content to fill in
2988 fillShortcuts: function(e, shortcutContent) {
2991 // don't do this if leftCol isn't available
2992 if (document.getElementById('leftCol') == undefined) { return; }
2994 spans = document.getElementById('leftCol').getElementsByTagName('span');
2995 hideCol = document.getElementById('HideMenu').getElementsByTagName('span');
2996 w = spans.length + 1;
2998 spans[w] = hideCol[i];
3001 for(je in shortcutContent) {
3003 if(typeof spans[wp].innerHTML != 'undefined' && spans[wp].innerHTML == ('wp_shortcut_fill_' + je)) {
3004 if(typeof spans[wp].parentNode.parentNode == 'object') {
3005 if(typeof spans[wp].parentNode.parentNode.onclick != 'undefined') {
3006 spans[wp].parentNode.parentNode.onclick = null;
3008 // If the wp_shortcut span is contained by an A tag, replace the A with a DIV.
3009 if(spans[wp].parentNode.tagName == 'A' && !isIE) {
3010 var newDiv = document.createElement('DIV');
3011 var parentAnchor = spans[wp].parentNode;
3013 spans[wp].parentNode.parentNode.style.display = 'none';
3015 // Copy styles over to the new container div
3016 if(window.getComputedStyle) {
3017 var parentStyle = window.getComputedStyle(parentAnchor, '');
3018 for(var styleName in parentStyle) {
3019 if(typeof parentStyle[styleName] != 'function'
3020 && styleName != 'display'
3021 && styleName != 'borderWidth'
3022 && styleName != 'visibility') {
3024 newDiv.style[styleName] = parentStyle[styleName];
3026 // Catches .length and .parentRule, and others
3032 // Replace the A with the DIV
3033 newDiv.appendChild(spans[wp]);
3034 parentAnchor.parentNode.replaceChild(newDiv, parentAnchor);
3036 spans[wp].parentNode.parentNode.style.display = '';
3039 spans[wp].innerHTML = shortcutContent[je]; // fill w/ content
3040 if(spans[wp].style) spans[wp].style.display = '';
3046 * Make an AJAX request.
3048 * @param url string resource to load
3049 * @param theDiv string id of element to insert loaded data into
3050 * @param postForm string if set, a POST request will be made to resource specified by url using the form named by postForm
3051 * @param callback string name of function to invoke after HTTP response is recieved
3052 * @param callbackParam any parameter to pass to callback when invoked
3053 * @param appendMode bool if true, HTTP response will be appended to the contents of theDiv, or else contents will be overriten.
3055 retrieveAndFill: function(url, theDiv, postForm, callback, callbackParam, appendMode) {
3056 if(typeof theDiv == 'string') {
3058 theDiv = document.getElementById(theDiv);
3065 var success = function(data) {
3066 if (typeof theDiv != 'undefined' && theDiv != null)
3069 if (typeof appendMode != 'undefined' && appendMode)
3071 theDiv.innerHTML += data.responseText;
3075 theDiv.innerHTML = data.responseText;
3082 if (typeof callback != 'undefined' && callback != null) callback(callbackParam);
3085 if(typeof postForm == 'undefined' || postForm == null) {
3086 var cObj = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
3089 YAHOO.util.Connect.setForm(postForm);
3090 var cObj = YAHOO.util.Connect.asyncRequest('POST', url, {success: success, failure: success});
3093 checkMaxLength: function() { // modified from http://www.quirksmode.org/dom/maxlength.html
3094 var maxLength = this.getAttribute('maxlength');
3095 var currentLength = this.value.length;
3096 if (currentLength > maxLength) {
3097 this.value = this.value.substring(0, maxLength);
3102 * Adds maxlength attribute to textareas
3104 setMaxLength: function() { // modified from http://www.quirksmode.org/dom/maxlength.html
3105 var x = document.getElementsByTagName('textarea');
3106 for (var i=0;i<x.length;i++) {
3107 if (x[i].getAttribute('maxlength')) {
3108 x[i].onkeyup = x[i].onchange = SUGAR.util.checkMaxLength;
3115 * Renders Query UI Help Dialog
3117 showHelpTips: function(el,helpText,myPos,atPos,id) {
3118 if(myPos == undefined || myPos == "") {
3121 if(atPos == undefined || atPos == "") {
3122 atPos = "right top";
3125 var pos = $(el).offset(),
3126 ofWidth = $(el).width(),
3127 elmId = id || 'helpTip' + pos.left + '_' + ofWidth,
3128 $dialog = elmId ? ( $("#"+elmId).length > 0 ? $("#"+elmId) : $('<div></div>').attr("id", elmId) ) : $('<div></div>');
3129 $dialog.html(helpText)
3132 title: SUGAR.language.get('app_strings', 'LBL_HELP'),
3141 var width = $dialog.dialog( "option", "width" );
3143 if((pos.left + ofWidth) - 40 < width) {
3144 $dialog.dialog("option","position",{my: 'left top',at: 'right top',of: $(el)}) ;
3146 $dialog.dialog('open');
3147 $(".ui-dialog").appendTo("#content");
3151 getStaticAdditionalDetails: function(el, body, caption, show_buttons) {
3152 if(typeof show_buttons == "undefined") {
3153 show_buttons = false;
3156 $(".ui-dialog").find(".open").dialog("close");
3158 var $dialog = $('<div class="open"></div>')
3172 $(".ui-dialog").find('.ui-dialog-titlebar-close').css("display","none");
3173 $(".ui-dialog").find('.ui-dialog-title').css("width","100%");
3177 var width = $dialog.dialog( "option", "width" );
3178 var pos = $(el).offset();
3179 var ofWidth = $(el).width();
3181 if((pos.left + ofWidth) - 40 < width) {
3182 $dialog.dialog("option","position",{my: 'left top',at: 'right top',of: $(el)}) ;
3185 $dialog.dialog('open');
3186 $(".ui-dialog").appendTo("#content");
3190 closeStaticAdditionalDetails: function() {
3191 $(".ui-dialog").find(".open").dialog("close");
3194 * Retrieves additional details dynamically
3196 getAdditionalDetails: function(bean, id, spanId, show_buttons) {
3197 if(typeof show_buttons == "undefined")
3198 show_buttons = false;
3199 var el = '#'+spanId;
3201 oReturn = function(body, caption, width, theme) {
3203 $(".ui-dialog").find(".open").dialog("close");
3205 var $dialog = $('<div class="open"></div>')
3218 $(".ui-dialog").find('.ui-dialog-titlebar-close').css("display","none");
3219 $(".ui-dialog").find('.ui-dialog-title').css("width","100%");
3222 var width = $dialog.dialog( "option", "width" );
3223 var pos = $(el).offset();
3224 var ofWidth = $(el).width();
3226 if((pos.left + ofWidth) - 40 < width) {
3227 $dialog.dialog("option","position",{my: 'left top',at: 'right top',of: $(el)}) ;
3230 $dialog.dialog('open');
3231 $(".ui-dialog").appendTo("#content");
3234 success = function(data) {
3235 eval(data.responseText);
3237 SUGAR.util.additionalDetailsCache[id] = new Array();
3238 SUGAR.util.additionalDetailsCache[id]['body'] = result['body'];
3239 SUGAR.util.additionalDetailsCache[id]['caption'] = result['caption'];
3240 SUGAR.util.additionalDetailsCache[id]['width'] = result['width'];
3241 SUGAR.util.additionalDetailsCache[id]['theme'] = result['theme'];
3242 ajaxStatus.hideStatus();
3243 return oReturn(SUGAR.util.additionalDetailsCache[id]['body'], SUGAR.util.additionalDetailsCache[id]['caption'], SUGAR.util.additionalDetailsCache[id]['width'], SUGAR.util.additionalDetailsCache[id]['theme']);
3246 if(typeof SUGAR.util.additionalDetailsCache[id] != 'undefined')
3247 return oReturn(SUGAR.util.additionalDetailsCache[id]['body'], SUGAR.util.additionalDetailsCache[id]['caption'], SUGAR.util.additionalDetailsCache[id]['width'], SUGAR.util.additionalDetailsCache[id]['theme']);
3249 if(typeof SUGAR.util.additionalDetailsCalls[id] != 'undefined') // call already in progress
3251 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_LOADING'));
3252 url = 'index.php?to_pdf=1&module=Home&action=AdditionalDetailsRetrieve&bean=' + bean + '&id=' + id;
3254 url += '&show_buttons=true';
3255 SUGAR.util.additionalDetailsCalls[id] = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
3259 SUGAR.util.additionalDetailsRpcCall = window.setTimeout('go()', 250);
3261 clearAdditionalDetailsCall: function() {
3262 if(typeof SUGAR.util.additionalDetailsRpcCall == 'number') window.clearTimeout(SUGAR.util.additionalDetailsRpcCall);
3265 * A function that extends functionality from parent to child.
3267 extend : function(subc, superc, overrides) {
3268 subc.prototype = new superc; // set the superclass
3271 for (var i in overrides) subc.prototype[i] = overrides[i];
3274 hrefURL : function(url) {
3276 // IE needs special treatment since otherwise it would not pass Referer
3277 var trampoline = document.createElement('a');
3278 trampoline.href = url;
3279 document.body.appendChild(trampoline);
3281 document.body.removeChild(trampoline);
3283 document.location.href = url;
3287 openWindow : function(URL, windowName, windowFeatures) {
3289 // IE needs special treatment since otherwise it would not pass Referer
3290 win = window.open('', windowName, windowFeatures);
3291 var trampoline = document.createElement('a');
3292 trampoline.href = URL;
3293 trampoline.target = windowName;
3294 document.body.appendChild(trampoline);
3296 document.body.removeChild(trampoline);
3298 win = window.open(URL, windowName, windowFeatures);
3302 //Reset the scroll on the window
3307 //Based on YUI onAvailible, but will use any boolean function instead of an ID
3308 doWhen : function(condition, fn, params, scope)
3310 this._doWhenStack.push({
3314 overrideContext: scope
3317 this._doWhenretryCount = 50;
3318 this._startDoWhenInterval();
3321 _startDoWhenInterval : function(){
3322 if (!this._doWhenInterval) {
3323 this._doWhenInterval = YAHOO.lang.later(50, this, this._doWhenCheck, null, true);
3327 _doWhenInterval : false,
3328 _doWhenCheck : function() {
3329 if (this._doWhenStack.length === 0) {
3330 this._doWhenretryCount = 0;
3331 if (this._doWhenInterval) {
3332 // clearInterval(this._interval);
3333 this._doWhenInterval.cancel();
3334 this._doWhenInterval = null;
3339 if (this._doWhenLocked) {
3344 // Hold off if DOMReady has not fired and check current
3345 // readyState to protect against the IE operation aborted
3347 if (!YAHOO.util.Event.DOMReady) {
3348 this._startDoWhenInterval();
3353 this._doWhenLocked = true;
3356 // keep trying until after the page is loaded. We need to
3357 // check the page load state prior to trying to bind the
3358 // elements so that we can be certain all elements have been
3359 // tested appropriately
3360 var tryAgain = YAHOO.util.Event.DOMReady;
3362 tryAgain = (this._doWhenretryCount > 0 && this._doWhenStack.length > 0);
3368 var executeItem = function (context, item) {
3369 if (item.overrideContext) {
3370 if (item.overrideContext === true) {
3373 context = item.overrideContext;
3377 item.fn.call(context, item.obj);
3381 var i, len, item, test;
3383 // onAvailable onContentReady
3384 for (i=0, len=this._doWhenStack.length; i<len; i=i+1) {
3385 item = this._doWhenStack[i];
3388 if ((typeof(test) == "string" && eval(test)) || (typeof(test) == "function" && test())) {
3389 executeItem(this, item);
3390 this._doWhenStack[i] = null;
3393 notAvail.push(item);
3398 this._doWhenretryCount--;
3401 for (i=this._doWhenStack.length-1; i>-1; i--) {
3402 item = this._doWhenStack[i];
3403 if (!item || !item.check) {
3404 this._doWhenStack.splice(i, 1);
3407 this._startDoWhenInterval();
3409 if (this._doWhenInterval) {
3410 // clearInterval(this._interval);
3411 this._doWhenInterval.cancel();
3412 this._doWhenInterval = null;
3415 this._doWhenLocked = false;
3417 buildAccessKeyLabels : function() {
3418 if (typeof(Y.env.ua) !== 'undefined'){
3420 browserOS = Y.env.ua['os'];
3421 isIE = Y.env.ua['ie'];
3422 isCR = Y.env.ua['chrome'];
3423 isFF = Y.env.ua['gecko'];
3424 isWK = Y.env.ua['webkit'];
3425 isOP = Y.env.ua['opera'];
3428 //first determine the OS
3429 if(browserOS=='macintosh'){
3430 //we got a mac, lets use the mac specific commands while we check the browser
3432 //IE on a Mac? Not possible, but let's assign alt anyways for completions sake
3433 controlKey = 'Alt+';
3435 //Chrome or safari on a mac
3436 controlKey = 'Ctrl+Opt+';
3439 controlKey = 'Shift+Esc: ';
3441 //default FF and everything else on a mac
3442 controlKey = 'Ctrl+';
3445 //this is not a mac so let's use the windows/unix commands while we check the browser
3447 //FF on windows/unix
3448 controlKey = 'Alt+Shift+';
3450 //Opera on windows/unix
3451 controlKey = 'Shift+Esc: ';
3453 //this is the default for safari, IE and Chrome
3454 //if this is webkit and is NOT google, then we are most likely looking at Safari
3455 controlKey = 'Alt+';
3460 //now lets retrieve all elements of type input
3461 allButtons = document.getElementsByTagName('input');
3462 //iterate through list and modify title if the accesskey is not empty
3463 for(i=0;i<allButtons.length;i++){
3464 if(allButtons[i].getAttribute('accesskey') && allButtons[i].getAttribute('type') && allButtons[i].getAttribute('type')=='button'){
3465 allButtons[i].setAttribute('title',allButtons[i].getAttribute('title')+' ['+controlKey+allButtons[i].getAttribute('accesskey')+']');
3468 //now change the text in the help div
3469 $("#shortcuts_dialog").html(function(i, text) {
3470 return text.replace(/Alt\+/g,controlKey);
3472 }// end if (typeof(Y.env.ua) !== 'undefined')
3473 }//end buildAccessKeyLabels()
3476 SUGAR.util.additionalDetailsCache = new Array();
3477 SUGAR.util.additionalDetailsCalls = new Array();
3478 if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.util.setMaxLength); // allow textareas to obey maxlength attrib
3480 SUGAR.savedViews = function() {
3481 var selectedOrderBy;
3482 var selectedSortOrder;
3485 var columnsMeta; // meta data for the display columns
3488 setChooser: function() {
3490 var displayColumnsDef = new Array();
3491 var hideTabsDef = new Array();
3493 var left_td = document.getElementById('display_tabs_td');
3494 if(typeof left_td == 'undefined' || left_td == null) return; // abort!
3495 var right_td = document.getElementById('hide_tabs_td');
3497 var displayTabs = left_td.getElementsByTagName('select')[0];
3498 var hideTabs = right_td.getElementsByTagName('select')[0];
3500 for(i = 0; i < displayTabs.options.length; i++) {
3501 displayColumnsDef.push(displayTabs.options[i].value);
3504 if(typeof hideTabs != 'undefined') {
3505 for(i = 0; i < hideTabs.options.length; i++) {
3506 hideTabsDef.push(hideTabs.options[i].value);
3509 if (!SUGAR.savedViews.clearColumns)
3510 document.getElementById('displayColumnsDef').value = displayColumnsDef.join('|');
3511 document.getElementById('hideTabsDef').value = hideTabsDef.join('|');
3514 select: function(saved_search_select) {
3515 for(var wp = 0; wp < document.search_form.saved_search_select.options.length; wp++) {
3516 if(typeof document.search_form.saved_search_select.options[wp].value != 'undefined' &&
3517 document.search_form.saved_search_select.options[wp].value == saved_search_select) {
3518 document.search_form.saved_search_select.selectedIndex = wp;
3519 document.search_form.ss_delete.style.display = '';
3520 document.search_form.ss_update.style.display = '';
3524 saved_search_action: function(action, delete_lang) {
3525 if(action == 'delete') {
3526 if(!confirm(delete_lang)) return;
3528 if(action == 'save') {
3529 if(document.search_form.saved_search_name.value.replace(/^\s*|\s*$/g, '') == '') {
3530 alert(SUGAR.language.get('app_strings', 'LBL_SAVED_SEARCH_ERROR'));
3535 // This check is needed for the Activities module (Calls/Meetings/Tasks).
3536 if (document.search_form.saved_search_action)
3538 document.search_form.saved_search_action.value = action;
3539 document.search_form.search_module.value = document.search_form.module.value;
3540 document.search_form.module.value = 'SavedSearch';
3541 // Bug 31922 - Make sure to specify that we want to hit the index view here of
3542 // the SavedSearch module, since the ListView doesn't have the logic to save the
3543 // search and redirect back
3544 document.search_form.action.value = 'index';
3546 SUGAR.ajaxUI.submitForm(document.search_form);
3548 shortcut_select: function(selectBox, module) {
3550 selecturl = 'index.php?module=SavedSearch&search_module=' + module + '&action=index&saved_search_select=' + selectBox.options[selectBox.selectedIndex].value
3551 //add searchFormTab to url if it is available. This determines what tab to render
3552 if(typeof(document.getElementById('searchFormTab'))!='undefined'){
3553 selecturl = selecturl + '&searchFormTab=' + document.search_form.searchFormTab.value;
3555 //add showSSDIV to url if it is available. This determines whether saved search sub form should
3556 //be rendered open or not
3557 if(document.getElementById('showSSDIV') && typeof(document.getElementById('showSSDIV') !='undefined')){
3558 selecturl = selecturl + '&showSSDIV='+document.getElementById('showSSDIV').value;
3560 //use created url to navigate
3561 document.location.href = selecturl;
3563 handleForm: function() {
3564 SUGAR.tabChooser.movementCallback = function(left_side, right_side) {
3565 while(document.getElementById('orderBySelect').childNodes.length != 0) { // clear out order by options
3566 document.getElementById('orderBySelect').removeChild(document.getElementById('orderBySelect').lastChild);
3569 var selectedIndex = 0;
3570 var nodeCount = -1; // need this because the counter i also includes "undefined" nodes
3571 // which was breaking Calls and Meetings
3573 for(i in left_side.childNodes) { // fill in order by options
3574 if(typeof left_side.childNodes[i].nodeName != 'undefined' &&
3575 left_side.childNodes[i].nodeName.toLowerCase() == 'option' &&
3576 typeof SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value] != 'undefined' && // check if column is sortable
3577 typeof SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value]['sortable'] == 'undefined' &&
3578 SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value]['sortable'] != false) {
3580 optionNode = document.createElement('option');
3581 optionNode.value = left_side.childNodes[i].value;
3582 optionNode.innerHTML = left_side.childNodes[i].innerHTML;
3583 document.getElementById('orderBySelect').appendChild(optionNode);
3584 if(optionNode.value == SUGAR.savedViews.selectedOrderBy)
3585 selectedIndex = nodeCount;
3588 // Firefox needs this to be set after all the option nodes are created.
3589 document.getElementById('orderBySelect').selectedIndex = selectedIndex;
3591 SUGAR.tabChooser.movementCallback(document.getElementById('display_tabs_td').getElementsByTagName('select')[0]);
3593 // This check is needed for the Activities module (Calls/Meetings/Tasks).
3594 if (document.search_form.orderBy)
3595 document.search_form.orderBy.options.value = SUGAR.savedViews.selectedOrderBy;
3598 if(SUGAR.savedViews.selectedSortOrder == 'DESC') document.getElementById('sort_order_desc_radio').checked = true;
3599 else document.getElementById('sort_order_asc_radio').checked = true;
3604 SUGAR.searchForm = function() {
3607 // searchForm tab selector util
3608 searchFormSelect: function(view, previousView) {
3609 var module = view.split('|')[0];
3610 var theView = view.split('|')[1];
3612 var handleDisplay = function() { // hide other divs
3613 document.search_form.searchFormTab.value = theView;
3614 patt = module+"(.*)SearchForm$";
3615 divId=document.search_form.getElementsByTagName('div');
3616 // Hide all the search forms and retrive the name of the previous search tab (useful for the first load because previousView is empty)
3617 for (i=0;i<divId.length;i++){
3618 if(divId[i].id.match(module)==module){
3619 if(divId[i].id.match('SearchForm')=='SearchForm'){
3620 if(document.getElementById(divId[i].id).style.display == ''){
3621 previousTab=divId[i].id.match(patt)[1];
3623 document.getElementById(divId[i].id).style.display = 'none';
3628 //clear thesearch form accesekeys and reset them to the appropriate link
3629 adv = document.getElementById('advanced_search_link');
3630 bas = document.getElementById('basic_search_link');
3631 adv.setAttribute('accesskey','');
3632 bas.setAttribute('accesskey','');
3633 a_key = SUGAR.language.get("app_strings", "LBL_ADV_SEARCH_LNK_KEY");
3635 //reset the ccesskey based on theview
3636 if(theView === 'advanced_search'){
3638 bas.setAttribute('accesskey',a_key);
3640 adv.setAttribute('accesskey',a_key);
3643 // show the good search form.
3644 document.getElementById(module + theView + 'SearchForm').style.display = '';
3645 //if its not the first tab show there is a previous tab.
3647 thepreviousView=previousView.split('|')[1];
3650 thepreviousView=previousTab;
3652 thepreviousView=thepreviousView.replace(/_search/, "");
3653 // Process to retrieve the completed field from one tab to an other.
3654 for(num in document.search_form.elements) {
3655 if(document.search_form.elements[num]) {
3656 el = document.search_form.elements[num];
3657 pattern="^(.*)_"+thepreviousView+"$";
3658 if(typeof el.type != 'undefined' && typeof el.name != 'undefined' && el.name.match(pattern)) {
3659 advanced_input_name = el.name.match(pattern)[1]; // strip
3660 advanced_input_name = advanced_input_name+"_"+theView.replace(/_search/, "");
3661 if(typeof document.search_form[advanced_input_name] != 'undefined') // if advanced input of same name exists
3662 SUGAR.searchForm.copyElement(advanced_input_name, el);
3668 // if tab is not cached
3669 if(document.getElementById(module + theView + 'SearchForm').innerHTML == '') {
3670 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_LOADING'));
3671 var success = function(data) {
3672 document.getElementById(module + theView + 'SearchForm').innerHTML = data.responseText;
3674 SUGAR.util.evalScript(data.responseText);
3675 // pass script variables to global scope
3676 if(theView == 'saved_views') {
3677 if(typeof columnsMeta != 'undefined') SUGAR.savedViews.columnsMeta = columnsMeta;
3678 if(typeof selectedOrderBy != 'undefined') SUGAR.savedViews.selectedOrderBy = selectedOrderBy;
3679 if(typeof selectedSortOrder != 'undefined') SUGAR.savedViews.selectedSortOrder = selectedSortOrder;
3684 ajaxStatus.hideStatus();
3686 url = 'index.php?module=' + module + '&action=index&search_form_only=true&to_pdf=true&search_form_view=' + theView;
3688 //check to see if tpl has been specified. If so then pass location through url string
3690 if(document.getElementById('search_tpl') !=null && typeof(document.getElementById('search_tpl')) != 'undefined'){
3691 tpl = document.getElementById('search_tpl').value;
3692 if(tpl != ''){url += '&search_tpl='+tpl;}
3695 if(theView == 'saved_views') // handle the tab chooser
3696 url += '&displayColumns=' + SUGAR.savedViews.displayColumns + '&hideTabs=' + SUGAR.savedViews.hideTabs + '&orderBy=' + SUGAR.savedViews.selectedOrderBy + '&sortOrder=' + SUGAR.savedViews.selectedSortOrder;
3698 var cObj = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
3700 else { // that form already retrieved
3705 // copies one input to another
3706 copyElement: function(inputName, copyFromElement) {
3707 switch(copyFromElement.type) {
3710 document.search_form[inputName].value = copyFromElement.value;
3714 // This function is here to clear the form, instead of "resubmitting it
3715 clear_form: function(form, skipElementNames) {
3716 var elemList = form.elements;
3720 for( var i = 0; i < elemList.length ; i++ ) {
3722 if ( typeof(elem.type) == 'undefined' ) {
3726 if ( typeof(elem.type) != 'undefined' && typeof(skipElementNames) != 'undefined'
3727 && SUGAR.util.arrayIndexOf(skipElementNames, elem.name) != -1 )
3732 elemType = elem.type.toLowerCase();
3734 if ( elemType == 'text' || elemType == 'textarea' || elemType == 'password' ) {
3737 else if ( elemType == 'select' || elemType == 'select-one' || elemType == 'select-multiple' ) {
3738 // We have, what I hope, is a select box, time to unselect all options
3739 var optionList = elem.options;
3741 if (optionList.length > 0) {
3742 optionList[0].selected = "selected";
3745 for ( var ii = 0 ; ii < optionList.length ; ii++ ) {
3746 optionList[ii].selected = false;
3749 else if ( elemType == 'radio' || elemType == 'checkbox' ) {
3750 elem.checked = false;
3751 elem.selected = false;
3753 else if ( elemType == 'hidden' ) {
3754 // We only want to reset the hidden values that link to the select boxes.
3755 // _c custom field kludge added to fix Bug 41384
3756 if ( ( elem.name.length > 3 && elem.name.substring(elem.name.length-3) == '_id' )
3757 || ((elem.name.length > 9) && (elem.name.substring(elem.name.length - 9) == '_id_basic'))
3758 || ( elem.name.length > 12 && elem.name.substring(elem.name.length-12) == '_id_advanced' )
3759 || ( elem.name.length > 2 && elem.name.substring(elem.name.length-2) == '_c' )
3760 || ((elem.name.length > 8) && (elem.name.substring(elem.name.length - 8) == '_c_basic'))
3761 || ( elem.name.length > 11 && elem.name.substring(elem.name.length-11) == '_c_advanced' ) )
3767 SUGAR.savedViews.clearColumns = true;
3771 // Code for the column/tab chooser used on homepage and in admin section
3772 SUGAR.tabChooser = function () {
3773 var object_refs = new Array();
3775 /* Describe certain transfers as invalid */
3778 movementCallback: function(left_side, right_side) {},
3779 orderCallback: function(left_side, right_side) {},
3781 freezeOptions: function(left_name, right_name, target) {
3782 if(!SUGAR.tabChooser.frozenOptions) { SUGAR.tabChooser.frozenOptions = []; }
3783 if(!SUGAR.tabChooser.frozenOptions[left_name]) { SUGAR.tabChooser.frozenOptions[left_name] = []; }
3784 if(!SUGAR.tabChooser.frozenOptions[left_name][right_name]) { SUGAR.tabChooser.frozenOptions[left_name][right_name] = []; }
3785 if(typeof target == 'array') {
3786 for(var i in target) {
3787 SUGAR.tabChooser.frozenOptions[left_name][right_name][target[i]] = true;
3790 SUGAR.tabChooser.frozenOptions[left_name][right_name][target] = true;
3794 buildSelectHTML: function(info) {
3795 var text = "<select";
3797 if(typeof (info['select']['size']) != 'undefined') {
3798 text +=" size=\""+ info['select']['size'] +"\"";
3801 if(typeof (info['select']['name']) != 'undefined') {
3802 text +=" name=\""+ info['select']['name'] +"\"";
3805 if(typeof (info['select']['style']) != 'undefined') {
3806 text +=" style=\""+ info['select']['style'] +"\"";
3809 if(typeof (info['select']['onchange']) != 'undefined') {
3810 text +=" onChange=\""+ info['select']['onchange'] +"\"";
3813 if(typeof (info['select']['multiple']) != 'undefined') {
3818 for(i=0; i<info['options'].length;i++) {
3819 option = info['options'][i];
3820 text += "<option value=\""+option['value']+"\" ";
3821 if ( typeof (option['selected']) != 'undefined' && option['selected']== true) {
3824 text += ">"+option['text']+"</option>";
3826 text += "</select>";
3830 left_to_right: function(left_name, right_name, left_size, right_size) {
3831 SUGAR.savedViews.clearColumns = false;
3832 var left_td = document.getElementById(left_name+'_td');
3833 var right_td = document.getElementById(right_name+'_td');
3835 var display_columns_ref = left_td.getElementsByTagName('select')[0];
3836 var hidden_columns_ref = right_td.getElementsByTagName('select')[0];
3838 var selected_left = new Array();
3839 var notselected_left = new Array();
3840 var notselected_right = new Array();
3842 var left_array = new Array();
3844 var frozen_options = SUGAR.tabChooser.frozenOptions;
3845 frozen_options = frozen_options && frozen_options[left_name] && frozen_options[left_name][right_name]?frozen_options[left_name][right_name]:[];
3847 // determine which options are selected in left
3848 for (i=0; i < display_columns_ref.options.length; i++)
3850 if ( display_columns_ref.options[i].selected == true && !frozen_options[display_columns_ref.options[i].value])
3852 selected_left[selected_left.length] = {text: display_columns_ref.options[i].text, value: display_columns_ref.options[i].value};
3856 notselected_left[notselected_left.length] = {text: display_columns_ref.options[i].text, value: display_columns_ref.options[i].value};
3861 for (i=0; i < hidden_columns_ref.options.length; i++)
3863 notselected_right[notselected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
3867 var left_select_html_info = new Object();
3868 var left_options = new Array();
3869 var left_select = new Object();
3871 left_select['name'] = left_name+'[]';
3872 left_select['id'] = left_name;
3873 left_select['size'] = left_size;
3874 left_select['multiple'] = 'true';
3876 var right_select_html_info = new Object();
3877 var right_options = new Array();
3878 var right_select = new Object();
3880 right_select['name'] = right_name+'[]';
3881 right_select['id'] = right_name;
3882 right_select['size'] = right_size;
3883 right_select['multiple'] = 'true';
3885 for (i = 0; i < notselected_right.length; i++) {
3886 right_options[right_options.length] = notselected_right[i];
3889 for (i = 0; i < selected_left.length; i++) {
3890 right_options[right_options.length] = selected_left[i];
3892 for (i = 0; i < notselected_left.length; i++) {
3893 left_options[left_options.length] = notselected_left[i];
3895 left_select_html_info['options'] = left_options;
3896 left_select_html_info['select'] = left_select;
3897 right_select_html_info['options'] = right_options;
3898 right_select_html_info['select'] = right_select;
3899 right_select_html_info['style'] = 'background: lightgrey';
3901 var left_html = this.buildSelectHTML(left_select_html_info);
3902 var right_html = this.buildSelectHTML(right_select_html_info);
3904 left_td.innerHTML = left_html;
3905 right_td.innerHTML = right_html;
3907 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3908 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3910 this.movementCallback(object_refs[left_name], object_refs[right_name]);
3916 right_to_left: function(left_name, right_name, left_size, right_size, max_left) {
3917 SUGAR.savedViews.clearColumns = false;
3918 var left_td = document.getElementById(left_name+'_td');
3919 var right_td = document.getElementById(right_name+'_td');
3921 var display_columns_ref = left_td.getElementsByTagName('select')[0];
3922 var hidden_columns_ref = right_td.getElementsByTagName('select')[0];
3924 var selected_right = new Array();
3925 var notselected_right = new Array();
3926 var notselected_left = new Array();
3928 var frozen_options = SUGAR.tabChooser.frozenOptions;
3929 frozen_options = SUGAR.tabChooser.frozenOptions && SUGAR.tabChooser.frozenOptions[right_name] && SUGAR.tabChooser.frozenOptions[right_name][left_name]?SUGAR.tabChooser.frozenOptions[right_name][left_name]:[];
3931 for (i=0; i < hidden_columns_ref.options.length; i++)
3933 if (hidden_columns_ref.options[i].selected == true && !frozen_options[hidden_columns_ref.options[i].value])
3935 selected_right[selected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
3939 notselected_right[notselected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
3944 if(max_left != '' && (display_columns_ref.length + selected_right.length) > max_left) {
3945 alert('Maximum of ' + max_left + ' columns can be displayed.');
3949 for (i=0; i < display_columns_ref.options.length; i++)
3951 notselected_left[notselected_left.length] = {text:display_columns_ref.options[i].text, value:display_columns_ref.options[i].value};
3955 var left_select_html_info = new Object();
3956 var left_options = new Array();
3957 var left_select = new Object();
3959 left_select['name'] = left_name+'[]';
3960 left_select['id'] = left_name;
3961 left_select['multiple'] = 'true';
3962 left_select['size'] = left_size;
3964 var right_select_html_info = new Object();
3965 var right_options = new Array();
3966 var right_select = new Object();
3968 right_select['name'] = right_name+ '[]';
3969 right_select['id'] = right_name;
3970 right_select['multiple'] = 'true';
3971 right_select['size'] = right_size;
3973 for (i = 0; i < notselected_left.length; i++) {
3974 left_options[left_options.length] = notselected_left[i];
3977 for (i = 0; i < selected_right.length; i++) {
3978 left_options[left_options.length] = selected_right[i];
3980 for (i = 0; i < notselected_right.length; i++) {
3981 right_options[right_options.length] = notselected_right[i];
3983 left_select_html_info['options'] = left_options;
3984 left_select_html_info['select'] = left_select;
3985 right_select_html_info['options'] = right_options;
3986 right_select_html_info['select'] = right_select;
3987 right_select_html_info['style'] = 'background: lightgrey';
3989 var left_html = this.buildSelectHTML(left_select_html_info);
3990 var right_html = this.buildSelectHTML(right_select_html_info);
3992 left_td.innerHTML = left_html;
3993 right_td.innerHTML = right_html;
3995 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3996 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3998 this.movementCallback(object_refs[left_name], object_refs[right_name]);
4003 up: function(name, left_name, right_name) {
4004 SUGAR.savedViews.clearColumns = false;
4005 var left_td = document.getElementById(left_name+'_td');
4006 var right_td = document.getElementById(right_name+'_td');
4007 var td = document.getElementById(name+'_td');
4008 var obj = td.getElementsByTagName('select')[0];
4009 obj = (typeof obj == "string") ? document.getElementById(obj) : obj;
4010 if (obj.tagName.toLowerCase() != "select" && obj.length < 2)
4012 var sel = new Array();
4014 for (i=0; i<obj.length; i++) {
4015 if (obj[i].selected == true) {
4016 sel[sel.length] = i;
4019 for (i=0; i < sel.length; i++) {
4020 if (sel[i] != 0 && !obj[sel[i]-1].selected) {
4021 var tmp = new Array(obj[sel[i]-1].text, obj[sel[i]-1].value);
4022 obj[sel[i]-1].text = obj[sel[i]].text;
4023 obj[sel[i]-1].value = obj[sel[i]].value;
4024 obj[sel[i]].text = tmp[0];
4025 obj[sel[i]].value = tmp[1];
4026 obj[sel[i]-1].selected = true;
4027 obj[sel[i]].selected = false;
4031 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
4032 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
4034 this.orderCallback(object_refs[left_name], object_refs[right_name]);
4039 down: function(name, left_name, right_name) {
4040 SUGAR.savedViews.clearColumns = false;
4041 var left_td = document.getElementById(left_name+'_td');
4042 var right_td = document.getElementById(right_name+'_td');
4043 var td = document.getElementById(name+'_td');
4044 var obj = td.getElementsByTagName('select')[0];
4045 if (obj.tagName.toLowerCase() != "select" && obj.length < 2)
4047 var sel = new Array();
4048 for (i=obj.length-1; i>-1; i--) {
4049 if (obj[i].selected == true) {
4050 sel[sel.length] = i;
4053 for (i=0; i < sel.length; i++) {
4054 if (sel[i] != obj.length-1 && !obj[sel[i]+1].selected) {
4055 var tmp = new Array(obj[sel[i]+1].text, obj[sel[i]+1].value);
4056 obj[sel[i]+1].text = obj[sel[i]].text;
4057 obj[sel[i]+1].value = obj[sel[i]].value;
4058 obj[sel[i]].text = tmp[0];
4059 obj[sel[i]].value = tmp[1];
4060 obj[sel[i]+1].selected = true;
4061 obj[sel[i]].selected = false;
4065 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
4066 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
4068 this.orderCallback(object_refs[left_name], object_refs[right_name]);
4073 }(); // end tabChooser
4075 SUGAR.language = function() {
4077 languages : new Array(),
4079 setLanguage: function(module, data) {
4080 if (!SUGAR.language.languages) {
4083 SUGAR.language.languages[module] = data;
4086 get: function(module, str) {
4087 if(typeof SUGAR.language.languages[module] == 'undefined' || typeof SUGAR.language.languages[module][str] == 'undefined')
4091 return SUGAR.language.languages[module][str];
4094 translate: function(module, str)
4096 text = this.get(module, str);
4097 return text != 'undefined' ? text : this.get('app_strings', str);
4102 SUGAR.contextMenu = function() {
4104 objects: new Object(),
4105 objectTypes: new Object(),
4107 * Registers a new object for the context menu.
4108 * objectType - name of the type
4110 * metaData - metaData to pass to the action function
4112 registerObject: function(objectType, id, metaData) {
4113 SUGAR.contextMenu.objects[id] = new Object();
4114 SUGAR.contextMenu.objects[id] = {'objectType' : objectType, 'metaData' : metaData};
4117 * Registers a new object type
4118 * name - name of the type
4119 * menuItems - array of menu items
4121 registerObjectType: function(name, menuItems) {
4122 SUGAR.contextMenu.objectTypes[name] = new Object();
4123 SUGAR.contextMenu.objectTypes[name] = {'menuItems' : menuItems, 'objects' : new Array()};
4126 * Determines which menu item was clicked
4128 getListItemFromEventTarget: function(p_oNode) {
4130 if(p_oNode.tagName == "LI") {
4135 if(p_oNode.tagName == "LI") {
4140 } while((p_oNode = p_oNode.parentNode));
4145 * handles movement within context menu
4147 onContextMenuMove: function() {
4148 var oNode = this.contextEventTarget;
4149 var bDisabled = (oNode.tagName == "UL");
4150 var i = this.getItemGroups()[0].length - 1;
4152 this.getItem(i).cfg.setProperty("disabled", bDisabled);
4157 * handles clicks on a context menu ITEM
4159 onContextMenuItemClick: function(p_sType, p_aArguments, p_oItem) {
4160 var oLI = SUGAR.contextMenu.getListItemFromEventTarget(this.parent.contextEventTarget);
4161 id = this.parent.contextEventTarget.parentNode.id; // id of the target
4162 funct = eval(SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[id]['objectType']]['menuItems'][this.index]['action']);
4163 funct(this.parent.contextEventTarget, SUGAR.contextMenu.objects[id]['metaData']);
4166 * Initializes all context menus registered
4169 for(var i in SUGAR.contextMenu.objects) { // make a variable called objects in objectTypes containg references to all triggers
4170 if(typeof SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'] == 'undefined')
4171 SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'] = new Array();
4172 SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'].push(document.getElementById(i));
4174 // register the menus
4175 for(var i in SUGAR.contextMenu.objectTypes) {
4176 var oContextMenu = new YAHOO.widget.ContextMenu(i, {'trigger': SUGAR.contextMenu.objectTypes[i]['objects']});
4177 var aMainMenuItems = SUGAR.contextMenu.objectTypes[i]['menuItems'];
4178 var nMainMenuItems = aMainMenuItems.length;
4180 for(var j = 0; j < nMainMenuItems; j++) {
4181 oMenuItem = new YAHOO.widget.ContextMenuItem(aMainMenuItems[j].text, { helptext: aMainMenuItems[j].helptext });
4182 oMenuItem.clickEvent.subscribe(SUGAR.contextMenu.onContextMenuItemClick, oMenuItem, true);
4183 oContextMenu.addItem(oMenuItem);
4185 // Add a "move" event handler to the context menu
4186 oContextMenu.moveEvent.subscribe(SUGAR.contextMenu.onContextMenuMove, oContextMenu, true);
4187 // Add a "keydown" event handler to the context menu
4188 oContextMenu.keyDownEvent.subscribe(SUGAR.contextMenu.onContextMenuItemClick, oContextMenu, true);
4189 // Render the context menu
4190 oContextMenu.render(document.body);
4196 SUGAR.contextMenu.actions = function() {
4199 * redirects to a new note with the clicked on object as the target
4201 createNote: function(itemClicked, metaData) {
4202 loc = 'index.php?module=Notes&action=EditView';
4203 for(i in metaData) {
4204 if(i == 'notes_parent_type') loc += '&parent_type=' + metaData[i];
4205 else if(i != 'module' && i != 'parent_type') loc += '&' + i + '=' + metaData[i];
4207 document.location = loc;
4210 * redirects to a new note with the clicked on object as the target
4212 scheduleMeeting: function(itemClicked, metaData) {
4213 loc = 'index.php?module=Meetings&action=EditView';
4214 for(i in metaData) {
4215 if(i != 'module') loc += '&' + i + '=' + metaData[i];
4217 document.location = loc;
4220 * redirects to a new note with the clicked on object as the target
4222 scheduleCall: function(itemClicked, metaData) {
4223 loc = 'index.php?module=Calls&action=EditView';
4224 for(i in metaData) {
4225 if(i != 'module') loc += '&' + i + '=' + metaData[i];
4227 document.location = loc;
4230 * redirects to a new contact with the clicked on object as the target
4232 createContact: function(itemClicked, metaData) {
4233 loc = 'index.php?module=Contacts&action=EditView';
4234 for(i in metaData) {
4235 if(i != 'module') loc += '&' + i + '=' + metaData[i];
4237 document.location = loc;
4240 * redirects to a new task with the clicked on object as the target
4242 createTask: function(itemClicked, metaData) {
4243 loc = 'index.php?module=Tasks&action=EditView';
4244 for(i in metaData) {
4245 if(i != 'module') loc += '&' + i + '=' + metaData[i];
4247 document.location = loc;
4250 * redirects to a new opportunity with the clicked on object as the target
4252 createOpportunity: function(itemClicked, metaData) {
4253 loc = 'index.php?module=Opportunities&action=EditView';
4254 for(i in metaData) {
4255 if(i != 'module') loc += '&' + i + '=' + metaData[i];
4257 document.location = loc;
4260 * redirects to a new opportunity with the clicked on object as the target
4262 createCase: function(itemClicked, metaData) {
4263 loc = 'index.php?module=Cases&action=EditView';
4264 for(i in metaData) {
4265 if(i != 'module') loc += '&' + i + '=' + metaData[i];
4267 document.location = loc;
4270 * handles add to favorites menu selection
4272 addToFavorites: function(itemClicked, metaData) {
4273 success = function(data) {
4275 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});
4280 //if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.contextMenu.init);
4282 // initially from popup_parent_helper.js
4283 var popup_request_data;
4286 function get_popup_request_data()
4288 return YAHOO.lang.JSON.stringify(window.document.popup_request_data);
4291 function get_close_popup()
4293 return window.document.close_popup;
4296 function open_popup(module_name, width, height, initial_filter, close_popup, hide_clear_button, popup_request_data, popup_mode, create, metadata)
4298 if (typeof(popupCount) == "undefined" || popupCount == 0)
4301 // set the variables that the popup will pull from
4302 window.document.popup_request_data = popup_request_data;
4303 window.document.close_popup = close_popup;
4305 //globally changing width and height of standard pop up window from 600 x 400 to 800 x 800
4306 width = (width == 600) ? 800 : width;
4307 height = (height == 400) ? 800 : height;
4311 + 'module=' + module_name
4314 if (initial_filter != '') {
4315 URL += '&query=true' + initial_filter;
4316 // Bug 41891 - Popup Window Name
4317 popupName = initial_filter.replace(/[^a-z_0-9]+/ig, '_');
4318 windowName = module_name + '_popup_window' + popupName;
4320 windowName = module_name + '_popup_window' + popupCount;
4324 if (hide_clear_button) {
4325 URL += '&hide_clear_button=true';
4328 windowFeatures = 'width=' + width
4329 + ',height=' + height
4330 + ',resizable=1,scrollbars=1';
4332 if (popup_mode == '' || popup_mode == undefined) {
4333 popup_mode='single';
4335 URL+='&mode='+popup_mode;
4336 if (create == '' || create == undefined) {
4339 URL+='&create='+create;
4341 if (metadata != '' && metadata != undefined) {
4342 URL+='&metadata='+metadata;
4345 // Bug #46842 : The relate field field_to_name_array fails to copy over custom fields
4346 // post fields that should be populated from popup form
4347 if(popup_request_data.jsonObject) {
4348 var request_data = popup_request_data.jsonObject;
4350 var request_data = popup_request_data;
4352 var field_to_name_array_url = '';
4354 if (request_data && request_data.field_to_name_array != undefined) {
4355 for(var key in request_data.field_to_name_array) {
4356 if ( key.toLowerCase() != 'id' ) {
4357 field_to_name_array_url += '&field_to_name[]='+encodeURIComponent(key.toLowerCase());
4361 if ( field_to_name_array_url ) {
4362 URL+=field_to_name_array_url;
4365 win = SUGAR.util.openWindow(URL, windowName, windowFeatures);
4369 // put the focus on the popup if the browser supports the focus() method
4373 win.popupCount = popupCount;
4379 * The reply data must be a JSON array structured with the following information:
4380 * 1) form name to populate
4381 * 2) associative array of input names to values for populating the form
4383 var from_popup_return = false;
4385 //Function replaces special HTML chars for usage in text boxes
4386 function replaceHTMLChars(value) {
4387 return value.replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');
4390 function set_return_basic(popup_reply_data,filter)
4392 var form_name = popup_reply_data.form_name;
4393 var name_to_value_array = popup_reply_data.name_to_value_array;
4394 for (var the_key in name_to_value_array)
4396 if(the_key == 'toJSON')
4400 else if(the_key.match(filter))
4402 var displayValue=replaceHTMLChars(name_to_value_array[the_key]);
4403 // begin andopes change: support for enum fields (SELECT)
4404 if(window.document.forms[form_name] && window.document.forms[form_name].elements[the_key]) {
4405 if(window.document.forms[form_name].elements[the_key].tagName == 'SELECT') {
4406 var selectField = window.document.forms[form_name].elements[the_key];
4407 for(var i = 0; i < selectField.options.length; i++) {
4408 if(selectField.options[i].text == displayValue) {
4409 selectField.options[i].selected = true;
4410 SUGAR.util.callOnChangeListers(selectField);
4415 window.document.forms[form_name].elements[the_key].value = displayValue;
4416 SUGAR.util.callOnChangeListers(window.document.forms[form_name].elements[the_key]);
4419 // end andopes change: support for enum fields (SELECT)
4424 function set_return(popup_reply_data)
4426 from_popup_return = true;
4427 var form_name = popup_reply_data.form_name;
4428 var name_to_value_array = popup_reply_data.name_to_value_array;
4429 if(typeof name_to_value_array != 'undefined' && name_to_value_array['account_id'])
4432 var label_data_str = '';
4433 var current_label_data_str = '';
4434 var popupConfirm = popup_reply_data.popupConfirm;
4435 for (var the_key in name_to_value_array)
4437 if(the_key == 'toJSON')
4443 var displayValue=replaceHTMLChars(name_to_value_array[the_key]);
4444 if(window.document.forms[form_name] && document.getElementById(the_key+'_label') && !the_key.match(/account/)) {
4445 var data_label = document.getElementById(the_key+'_label').innerHTML.replace(/\n/gi,'').replace(/<\/?[^>]+(>|$)/g, "");
4446 label_str += data_label + ' \n';
4447 label_data_str += data_label + ' ' + displayValue + '\n';
4448 if(window.document.forms[form_name].elements[the_key]) {
4449 current_label_data_str += data_label + ' ' + window.document.forms[form_name].elements[the_key].value +'\n';
4455 if(label_data_str != label_str && current_label_data_str != label_str){
4457 if (typeof popupConfirm != 'undefined')
4459 if (popupConfirm > -1) {
4460 set_return_basic(popup_reply_data,/\S/);
4462 set_return_basic(popup_reply_data,/account/);
4466 else if(confirm(SUGAR.language.get('app_strings', 'NTC_OVERWRITE_ADDRESS_PHONE_CONFIRM') + '\n\n' + label_data_str))
4468 set_return_basic(popup_reply_data,/\S/);
4472 set_return_basic(popup_reply_data,/account/);
4474 }else if(label_data_str != label_str && current_label_data_str == label_str){
4475 set_return_basic(popup_reply_data,/\S/);
4476 }else if(label_data_str == label_str){
4477 set_return_basic(popup_reply_data,/account/);
4480 set_return_basic(popup_reply_data,/\S/);
4484 function set_return_lead_conv(popup_reply_data) {
4485 set_return(popup_reply_data);
4486 if (document.getElementById('lead_conv_ac_op_sel') && typeof onBlurKeyUpHandler=='function') {
4487 onBlurKeyUpHandler();
4491 function set_return_and_save(popup_reply_data)
4493 var form_name = popup_reply_data.form_name;
4494 var name_to_value_array = popup_reply_data.name_to_value_array;
4496 for (var the_key in name_to_value_array)
4498 if(the_key == 'toJSON')
4504 window.document.forms[form_name].elements[the_key].value = name_to_value_array[the_key];
4508 window.document.forms[form_name].return_module.value = window.document.forms[form_name].module.value;
4509 window.document.forms[form_name].return_action.value = 'DetailView';
4510 window.document.forms[form_name].return_id.value = window.document.forms[form_name].record.value;
4511 window.document.forms[form_name].action.value = 'Save';
4512 window.document.forms[form_name].submit();
4516 * This is a helper function to construct the initial filter that can be
4517 * passed into the open_popup() function. It assumes that there is an
4518 * account_id and account_name field in the given form_name to use to
4519 * construct the intial filter string.
4521 function get_initial_filter_by_account(form_name)
4523 var account_id = window.document.forms[form_name].account_id.value;
4524 var account_name = escape(window.document.forms[form_name].account_name.value);
4525 var initial_filter = "&account_id=" + account_id + "&account_name=" + account_name;
4527 return initial_filter;
4529 // end code from popup_parent_helper.js
4531 // begin code for address copy
4533 * This is a function used by the Address widget that will fill
4534 * in the given array fields using the fromKey and toKey as a
4535 * prefix into the form objects HTML elements.
4537 * @param form The HTML form object to parse
4538 * @param fromKey The prefix of elements to copy from
4539 * @param toKey The prefix of elements to copy into
4540 * @return boolean true if successful, false otherwise
4542 function copyAddress(form, fromKey, toKey) {
4544 var elems = new Array("address_street", "address_city", "address_state", "address_postalcode", "address_country");
4545 var checkbox = document.getElementById(toKey + "_checkbox");
4547 if(typeof checkbox != "undefined") {
4548 if(!checkbox.checked) {
4550 t = toKey + "_" + elems[x];
4551 document.getElementById(t).removeAttribute('readonly');
4555 f = fromKey + "_" + elems[x];
4556 t = toKey + "_" + elems[x];
4558 document.getElementById(t).value = document.getElementById(f).value;
4559 document.getElementById(t).setAttribute('readonly', true);
4565 // end code for address copy
4568 * This function is used in Email Template Module.
4569 * It will check whether the template is used in Campaing->EmailMarketing.
4570 * If true, it will notify user.
4573 function check_deletable_EmailTemplate() {
4574 id = document.getElementsByName('record')[0].value;
4575 currentForm = document.getElementById('form');
4577 success:function(r) {
4578 if(r.responseText == 'true') {
4579 if(!confirm(SUGAR.language.get('app_strings','NTC_TEMPLATE_IS_USED'))) {
4583 if(!confirm(SUGAR.language.get('app_strings','NTC_DELETE_CONFIRMATION'))) {
4587 currentForm.return_module.value='EmailTemplates';
4588 currentForm.return_action.value='ListView';
4589 currentForm.action.value='Delete';
4590 currentForm.submit();
4593 url = "index.php?module=EmailTemplates&action=CheckDeletable&from=DetailView&to_pdf=1&record="+id;
4594 YAHOO.util.Connect.asyncRequest('POST',url, call_back,null);
4598 remove_upload_imagefile : function(field_name) {
4599 var field=document.getElementById('remove_imagefile_' + field_name);
4602 //enable the file upload button.
4603 var field=document.getElementById( field_name);
4604 field.style.display="";
4606 //hide the image and remove button.
4607 var field=document.getElementById('img_' + field_name);
4608 field.style.display="none";
4609 var field=document.getElementById('bt_remove_' + field_name);
4610 field.style.display="none";
4612 if(document.getElementById(field_name + '_duplicate')) {
4613 var field = document.getElementById(field_name + '_duplicate');
4618 confirm_imagefile : function(field_name) {
4619 var field=document.getElementById(field_name);
4620 var filename=field.value;
4621 var fileExtension = filename.substring(filename.lastIndexOf(".")+1);
4622 fileExtension = fileExtension.toLowerCase();
4623 if (fileExtension == "jpg" || fileExtension == "jpeg"
4624 || fileExtension == "gif" || fileExtension == "png" || fileExtension == "bmp"){
4629 alert(SUGAR.language.get('app_strings', 'LBL_UPLOAD_IMAGE_FILE_INVALID'));
4633 lightbox : function(image)
4635 if (typeof(SUGAR.image.lighboxWindow) == "undefined")
4636 SUGAR.image.lighboxWindow = new YAHOO.widget.SimpleDialog('sugarImageViewer', {
4639 id:'sugarMsgWindow',
4642 msg: "<img src='" + image + "'> </img>",
4645 SUGAR.image.lighboxWindow.setBody("<img src='" + image + "'> </img>");
4646 SUGAR.image.lighboxWindow.render(document.body);
4647 SUGAR.image.lighboxWindow.show();
4648 SUGAR.image.lighboxWindow.center()
4652 SUGAR.append(SUGAR.util, {
4653 isTouchScreen: function() {
4654 // first check if we have forced use of the touch enhanced interface
4655 if (Get_Cookie("touchscreen") == '1') {
4659 // next check if we should use the touch interface with our device
4660 if ((navigator.userAgent.match(/iPad/i) != null)) {
4667 isLoginPage: function(content) {
4668 //skip if this is packageManager screen
4669 if(SUGAR.util.isPackageManager()) {return false;}
4670 var loginPageStart = "<!DOCTYPE";
4671 if (content.substr(0, loginPageStart.length) == loginPageStart && content.indexOf("<html>") != -1 && content.indexOf("login_module") != -1) {
4672 window.location.href = window.location.protocol + window.location.pathname;
4677 isPackageManager: function(){
4678 if(typeof(document.the_form) !='undefined' && typeof(document.the_form.language_pack_escaped) !='undefined'){
4680 }else{return false;}
4683 ajaxCallInProgress: function(){
4685 //First check if we are in a popup.
4686 if (typeof (send_back) != "function"){
4687 //If the page content is blank, it means we are probably still waiting on something
4688 var c = document.getElementById("content");
4689 if (!c) return true;
4690 t = YAHOO.lang.trim(SUGAR.util.innerText(c));
4692 return SUGAR_callsInProgress != 0 || t == "";
4694 //Firefox doesn't support innerText (textContent includes script content)
4695 innerText : function(el) {
4696 if (el.tagName == "SCRIPT")
4698 if(typeof(el.innerText) == "string")
4699 return el.innerText;
4701 for (var i in el.childNodes){
4702 var c = el.childNodes[i];
4703 if (typeof(c) != "object")
4705 if (typeof(c.nodeName) == "string" && c.nodeName == "#text")
4708 t += SUGAR.util.innerText(c);
4713 callOnChangeListers: function(field){
4714 var listeners = YAHOO.util.Event.getListeners(field, 'change');
4715 if (listeners != null) {
4716 for (var i = 0; i < listeners.length; i++) {
4717 var l = listeners[i];
4718 l.fn.call(l.scope ? l.scope : this, l.obj);
4723 closeActivityPanel: {
4724 show:function(module,id,new_status,viewType,parentContainerId){
4725 if (SUGAR.util.closeActivityPanel.panel)
4726 SUGAR.util.closeActivityPanel.panel.destroy();
4727 var singleModule = SUGAR.language.get("app_list_strings", "moduleListSingular")[module];
4728 singleModule = typeof(singleModule != 'undefined') ? singleModule.toLowerCase() : '';
4729 var closeText = SUGAR.language.get("app_strings", "LBL_CLOSE_ACTIVITY_CONFIRM").replace("#module#",singleModule);
4730 SUGAR.util.closeActivityPanel.panel =
4731 new YAHOO.widget.SimpleDialog("closeActivityDialog",
4738 constraintoviewport: true,
4739 buttons: [ { text:SUGAR.language.get("app_strings", "LBL_EMAIL_OK"), handler:function(){
4740 if (SUGAR.util.closeActivityPanel.panel)
4741 SUGAR.util.closeActivityPanel.panel.hide();
4743 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_SAVING'));
4744 var args = "action=save&id=" + id + "&record=" + id + "&status=" + new_status + "&module=" + module;
4745 // 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
4746 // TODO: Take id out and regression test. Left id in for now to not create any other unexpected problems
4747 //var args = "action=save&id=" + id + "&status=" + new_status + "&module=" + module;
4751 // Bug 51984: We need to submit the form just incase we have a form already submitted
4752 // so we dont get a popup stating that the form needs to be resubmitted like it doesn,
4753 // when you do a reload/refresh
4754 window.setTimeout(function(){if(document.getElementById('search_form')) document.getElementById('search_form').submit(); else window.location.reload(true);}, 0);
4756 argument:{'parentContainerId':parentContainerId}
4759 YAHOO.util.Connect.asyncRequest('POST', 'index.php', callback, args);
4761 }, isDefault:true },
4762 { text:SUGAR.language.get("app_strings", "LBL_EMAIL_CANCEL"), handler:function(){SUGAR.util.closeActivityPanel.panel.hide(); }} ]
4765 SUGAR.util.closeActivityPanel.panel.setHeader(SUGAR.language.get("app_strings", "LBL_CLOSE_ACTIVITY_HEADER"));
4766 SUGAR.util.closeActivityPanel.panel.render(document.body);
4767 SUGAR.util.closeActivityPanel.panel.show();
4771 setEmailPasswordDisplay: function(id, exists, formName) {
4772 link = document.getElementById(id+'_link');
4773 pwd = document.getElementById(id);
4774 if(!pwd || !link) return;
4776 pwd.style.display = 'none';
4777 link.style.display = '';
4778 if(typeof(formName) != 'undefined')
4779 removeFromValidate(formName, id);
4781 pwd.style.display = '';
4782 link.style.display = 'none';
4786 setEmailPasswordEdit: function(id) {
4787 link = document.getElementById(id+'_link');
4788 pwd = document.getElementById(id);
4789 if(!pwd || !link) return;
4790 pwd.style.display = '';
4791 link.style.display = 'none';
4795 * Compares a filename with a supplied array of allowed file extensions.
4796 * @param fileName string
4797 * @param allowedTypes array of allowed file extensions
4800 validateFileExt: function(fileName, allowedTypes) {
4801 var ext = fileName.split('.').pop().toLowerCase();
4803 for (var i = allowedTypes.length; i >= 0; i--) {
4804 if (ext === allowedTypes[i]) {
4812 arrayIndexOf: function(arr, val, start) {
4813 if (typeof arr.indexOf == "function")
4814 return arr.indexOf(val, start);
4815 for (var i = (start || 0), j = arr.length; i < j; i++) {
4816 if (arr[i] === val) {
4824 SUGAR.clearRelateField = function(form, name, id)
4826 if (typeof form[name] == "object"){
4827 form[name].value = '';
4828 SUGAR.util.callOnChangeListers(form[name]);
4831 if (typeof form[id] == "object"){
4832 form[id].value = '';
4833 SUGAR.util.callOnChangeListers(form[id]);
4836 if(typeof(SUGAR.AutoComplete) == 'undefined') SUGAR.AutoComplete = {};
4838 SUGAR.AutoComplete.getOptionsArray = function(options_index){
4839 var return_arr = [];
4841 var opts = SUGAR.language.get('app_list_strings', options_index);
4842 if(typeof(opts) != 'undefined'){
4844 // Since we are using auto complete, we excluse blank dropdown entries since they can just leave it blank
4845 if(key != '' && opts[key] != ''){
4848 item['text'] = opts[key];
4849 return_arr.push(item);
4856 if(typeof(SUGAR.MultiEnumAutoComplete) == 'undefined') SUGAR.MultiEnumAutoComplete = {};
4858 SUGAR.MultiEnumAutoComplete.getMultiSelectKeysFromValues = function(options_index, val_string){
4859 var opts = SUGAR.language.get('app_list_strings', options_index);
4860 var selected_values = val_string.split(", ");
4861 // YUI AutoComplete adds a blank. We remove it automatically here
4862 if(selected_values.length > 0 && selected_values.indexOf('') == selected_values.length - 1){
4863 selected_values.pop();
4865 var final_arr = new Array();
4866 for(idx in selected_values){
4868 if(selected_values[idx] == opts[o_idx]){
4869 final_arr.push(o_idx);
4876 SUGAR.MultiEnumAutoComplete.getMultiSelectValuesFromKeys = function(options_index, val_string){
4877 var opts = SUGAR.language.get('app_list_strings', options_index);
4878 val_string=val_string.replace(/^\^/,'').replace(/\^$/,'') //fixes bug where string starts or ends with ^
4879 var selected_values = val_string.split("^,^");
4881 // YUI AutoComplete adds a blank. We remove it automatically here
4882 if(selected_values.length > 0 && selected_values.indexOf('') == selected_values.length - 1){
4883 selected_values.pop();
4886 var final_arr = new Array();
4887 for(idx in selected_values){
4889 if(selected_values[idx] == o_idx){
4890 final_arr.push(opts[o_idx]);