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");
77 * Namespace for Homepage
79 SUGAR.namespace("sugarHome");
82 * Namespace for Subpanel Utils
84 SUGAR.namespace("subpanelUtils");
89 SUGAR.namespace("ajaxStatusClass");
94 SUGAR.namespace("tabChooser");
97 * General namespace for Sugar utils
99 SUGAR.namespace("utils");
100 SUGAR.namespace("savedViews");
105 SUGAR.namespace("dashlets");
106 SUGAR.namespace("unifiedSearchAdvanced");
108 SUGAR.namespace("searchForm");
109 SUGAR.namespace("language");
110 SUGAR.namespace("Studio");
111 SUGAR.namespace("contextMenu");
112 SUGAR.namespace("config");
116 var requiredIndex = 2;
121 var altMsgIndex = 15;
122 var compareToIndex = 7;
124 var operatorIndex = 13;
125 var callbackIndex = 16;
127 var validate = new Array();
129 var requiredTxt = 'Missing Required Field:';
130 var invalidTxt = 'Invalid Value:';
131 var secondsSinceLoad = 0;
132 var inputsWithErrors = new Array();
133 var tabsWithErrors = new Array();
134 var lastSubmitTime = 0;
135 var alertList = new Array();
136 var oldStartsWith = '';
141 * As of Sugar version 6.2.3 (MSIE Version 9) this function is deprecated. The preferred method is to use the
142 * user agent check supplied by YUI to check for IE:
144 * for checking if a browser is IE in general : if(YAHOO.env.ua.ie) {...}
146 * or for checking specific versions: if (YAHOO.env.ua.ie >= 5.5 && YAHOO.env.ua.ie < 9) {...}
149 function isSupportedIE() {
150 var userAgent = navigator.userAgent.toLowerCase() ;
152 // IE Check supports ActiveX controls
153 if (userAgent.indexOf("msie") != -1 && userAgent.indexOf("mac") == -1 && userAgent.indexOf("opera") == -1) {
154 var version = navigator.appVersion.match(/MSIE (.\..)/)[1] ;
155 if(version >= 5.5 && version < 10) {
163 SUGAR.isIE = isSupportedIE();
164 var isSafari = (navigator.userAgent.toLowerCase().indexOf('safari')!=-1);
166 // escapes regular expression characters
167 RegExp.escape = function(text) { // http://simon.incutio.com/archive/2006/01/20/escape
168 if (!arguments.callee.sRE) {
169 var specials = ['/', '.', '*', '+', '?', '|','(', ')', '[', ']', '{', '}', '\\'];
170 arguments.callee.sRE = new RegExp('(\\' + specials.join('|\\') + ')', 'g');
172 return text.replace(arguments.callee.sRE, '\\$1');
175 function addAlert(type, name,subtitle, description,time, redirect) {
176 var addIndex = alertList.length;
177 alertList[addIndex]= new Array();
178 alertList[addIndex]['name'] = name;
179 alertList[addIndex]['type'] = type;
180 alertList[addIndex]['subtitle'] = subtitle;
181 alertList[addIndex]['description'] = replaceHTMLChars(description.replace(/<br>/gi, "\n"));
182 alertList[addIndex]['time'] = time;
183 alertList[addIndex]['done'] = 0;
184 alertList[addIndex]['redirect'] = redirect;
186 function checkAlerts() {
187 secondsSinceLoad += 1;
190 for(mj = 0 ; mj < alertList.length; mj++) {
191 if(alertList[mj]['done'] == 0) {
192 if(alertList[mj]['time'] < secondsSinceLoad && alertList[mj]['time'] > -1 ) {
193 alertmsg = alertList[mj]['type'] + ":" + alertList[mj]['name'] + "\n" +alertList[mj]['subtitle']+ "\n"+ alertList[mj]['description'] + "\n\n";
194 alertList[mj]['done'] = 1;
195 if(alertList[mj]['redirect'] == '') {
198 else if(confirm(alertmsg)) {
199 window.location = alertList[mj]['redirect'];
205 setTimeout("checkAlerts()", 1000);
208 function toggleDisplay(id) {
209 if(this.document.getElementById(id).style.display == 'none') {
210 this.document.getElementById(id).style.display = '';
211 if(this.document.getElementById(id+"link") != undefined) {
212 this.document.getElementById(id+"link").style.display = 'none';
214 if(this.document.getElementById(id+"_anchor") != undefined)
215 this.document.getElementById(id+"_anchor").innerHTML='[ - ]';
218 this.document.getElementById(id).style.display = 'none';
219 if(this.document.getElementById(id+"link") != undefined) {
220 this.document.getElementById(id+"link").style.display = '';
222 if(this.document.getElementById(id+"_anchor") != undefined)
223 this.document.getElementById(id+"_anchor").innerHTML='[+]';
227 function checkAll(form, field, value) {
228 for (i = 0; i < form.elements.length; i++) {
229 if(form.elements[i].name == field)
230 form.elements[i].checked = value;
234 function replaceAll(text, src, rep) {
235 offset = text.toLowerCase().indexOf(src.toLowerCase());
236 while(offset != -1) {
237 text = text.substring(0, offset) + rep + text.substring(offset + src.length ,text.length);
238 offset = text.indexOf( src, offset + rep.length + 1);
243 function addForm(formname) {
244 validate[formname] = new Array();
247 function addToValidate(formname, name, type, required, msg) {
248 if(typeof validate[formname] == 'undefined') {
251 validate[formname][validate[formname].length] = new Array(name, type,required, msg);
254 // Bug #47961 Callback validator definition
255 function addToValidateCallback(formname, name, type, required, msg, callback)
257 addToValidate(formname, name, type, required, msg);
258 var iIndex = validate[formname].length -1;
259 validate[formname][iIndex][jstypeIndex] = 'callback';
260 validate[formname][iIndex][callbackIndex] = callback;
263 function addToValidateRange(formname, name, type,required, msg,min,max) {
264 addToValidate(formname, name, type,required, msg);
265 validate[formname][validate[formname].length - 1][jstypeIndex] = 'range';
266 validate[formname][validate[formname].length - 1][minIndex] = min;
267 validate[formname][validate[formname].length - 1][maxIndex] = max;
270 function addToValidateIsValidDate(formname, name, type, required, msg) {
271 addToValidate(formname, name, type, required, msg);
272 validate[formname][validate[formname].length - 1][jstypeIndex] = 'date';
275 function addToValidateIsValidTime(formname, name, type, required, msg) {
276 addToValidate(formname, name, type, required, msg);
277 validate[formname][validate[formname].length - 1][jstypeIndex] = 'time';
280 function addToValidateDateBefore(formname, name, type, required, msg, compareTo) {
281 addToValidate(formname, name, type,required, msg);
282 validate[formname][validate[formname].length - 1][jstypeIndex] = 'isbefore';
283 validate[formname][validate[formname].length - 1][compareToIndex] = compareTo;
286 function addToValidateDateBeforeAllowBlank(formname, name, type, required, msg, compareTo, allowBlank) {
287 addToValidate(formname, name, type,required, msg);
288 validate[formname][validate[formname].length - 1][jstypeIndex] = 'isbefore';
289 validate[formname][validate[formname].length - 1][compareToIndex] = compareTo;
290 validate[formname][validate[formname].length - 1][allowblank] = allowBlank;
293 function addToValidateBinaryDependency(formname, name, type, required, msg, compareTo) {
294 addToValidate(formname, name, type, required, msg);
295 validate[formname][validate[formname].length - 1][jstypeIndex] = 'binarydep';
296 validate[formname][validate[formname].length - 1][compareToIndex] = compareTo;
299 function addToValidateComparison(formname, name, type, required, msg, compareTo) {
300 addToValidate(formname, name, type, required, msg);
301 validate[formname][validate[formname].length - 1][jstypeIndex] = 'comparison';
302 validate[formname][validate[formname].length - 1][compareToIndex] = compareTo;
305 function addToValidateIsInArray(formname, name, type, required, msg, arr, operator) {
306 addToValidate(formname, name, type, required, msg);
307 validate[formname][validate[formname].length - 1][jstypeIndex] = 'in_array';
308 validate[formname][validate[formname].length - 1][arrIndex] = arr;
309 validate[formname][validate[formname].length - 1][operatorIndex] = operator;
312 function addToValidateVerified(formname, name, type, required, msg, arr, operator) {
313 addToValidate(formname, name, type, required, msg);
314 validate[formname][validate[formname].length - 1][jstypeIndex] = 'verified';
317 function addToValidateLessThan(formname, name, type, required, msg, max, max_field_msg) {
318 addToValidate(formname, name, type, required, msg);
319 validate[formname][validate[formname].length - 1][jstypeIndex] = 'less';
320 validate[formname][validate[formname].length - 1][maxIndex] = max;
321 validate[formname][validate[formname].length - 1][altMsgIndex] = max_field_msg;
324 function addToValidateMoreThan(formname, name, type, required, msg, min) {
325 addToValidate(formname, name, type, required, msg);
326 validate[formname][validate[formname].length - 1][jstypeIndex] = 'more';
327 validate[formname][validate[formname].length - 1][minIndex] = min;
331 function removeFromValidate(formname, name) {
332 for(i = 0; i < validate[formname].length; i++)
334 if(validate[formname][i][nameIndex] == name)
336 validate[formname].splice(i--,1); // We subtract 1 from i since the slice removed an element, and we'll skip over the next item we scan
340 function checkValidate(formname, name) {
341 if(validate[formname]){
342 for(i = 0; i < validate[formname].length; i++){
343 if(validate[formname][i][nameIndex] == name){
350 var formsWithFieldLogic=null;
351 var formWithPrecision =null;
352 function addToValidateFieldLogic(formId,minFieldId, maxFieldId, defaultFieldId, lenFieldId,type,msg){
353 this.formId = document.getElementById(formId);
354 this.min=document.getElementById(minFieldId);
355 this.max= document.getElementById(maxFieldId);
356 this._default= document.getElementById(defaultFieldId);
357 this.len = document.getElementById(lenFieldId);
361 //@params: formid- Dom id of the form containing the precision and float fields
362 // valudId- Dom id of the field containing a float whose precision is to be checked.
363 // precisionId- Dom id of the field containing precision value.
364 function addToValidatePrecision(formId, valueId, precisionId){
365 this.form = document.getElementById(formId);
366 this.float = document.getElementById(valueId);
367 this.precision = document.getElementById(precisionId);
370 //function checkLength(value, referenceValue){
374 function isValidPrecision(value, precision){
375 value = trim(value.toString());
381 if( (precision == "0") ){
382 if (value.indexOf(dec_sep)== -1){
389 if(value.charAt(value.length-precision-1) == num_grp_sep){
390 if(value.substr(value.indexOf(dec_sep), 1)==dec_sep){
395 var actualPrecision = value.substr(value.indexOf(dec_sep)+1, value.length).length;
396 return actualPrecision == precision;
398 function toDecimal(original, precision) {
399 precision = (precision == null) ? 2 : precision;
400 num = Math.pow(10, precision);
401 temp = Math.round(original*num)/num;
402 if((temp * 100) % 100 == 0)
404 if((temp * 10) % 10 == 0)
409 function isInteger(s) {
410 if(typeof num_grp_sep != 'undefined' && typeof dec_sep != 'undefined')
412 s = unformatNumberNoParse(s, num_grp_sep, dec_sep).toString();
414 return /^[+-]?[0-9]*$/.test(s) ;
417 function isDecimal(s) {
418 if (typeof s == "string" && s == "") // bug# 46530, this is required in order to
419 return true; // not check empty decimal fields
421 if(typeof num_grp_sep != 'undefined' && typeof dec_sep != 'undefined')
423 s = unformatNumberNoParse(s, num_grp_sep, dec_sep).toString();
425 return /^[+-]?[0-9]*\.?[0-9]*$/.test(s) ;
428 function isNumeric(s) {
432 if (typeof date_reg_positions != "object") var date_reg_positions = {'Y': 1,'m': 2,'d': 3};
433 if (typeof date_reg_format != "string") var date_reg_format = '([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})';
435 function isDate(dtStr) {
437 if(dtStr.length== 0) {
441 // Check that we have numbers
442 myregexp = new RegExp(date_reg_format)
443 if(!myregexp.test(dtStr))
450 var dateParts = dtStr.match(date_reg_format);
451 for(key in date_reg_positions) {
452 index = date_reg_positions[key];
454 m = dateParts[index];
455 } else if(key == 'd') {
456 d = dateParts[index];
458 y = dateParts[index];
462 // Check that date is real
463 var dd = new Date(y,m,0);
464 // reject negative years
467 // reject month less than 1 and greater than 12
470 // reject days less than 1 or days not in month (e.g. February 30th)
471 if (d < 1 || d > dd.getDate())
476 function getDateObject(dtStr) {
477 if(dtStr.length== 0) {
481 myregexp = new RegExp(date_reg_format)
483 if(myregexp.exec(dtStr)) var dt = myregexp.exec(dtStr)
486 var yr = dt[date_reg_positions['Y']];
487 var mh = dt[date_reg_positions['m']];
488 var dy = dt[date_reg_positions['d']];
489 var dtar = dtStr.split(' ');
490 if(typeof(dtar[1])!='undefined' && isTime(dtar[1])) {//if it is a timedate, we should make date1 to have time value
491 var t1 = dtar[1].replace(/am/i,' AM');
492 var t1 = t1.replace(/pm/i,' PM');
493 //bug #37977: where time format 23.00 causes java script error
494 t1=t1.replace(/\./, ':');
495 date1 = new Date(Date.parse(mh+'/'+dy+ '/'+yr+' '+t1));
499 var date1 = new Date();
500 date1.setFullYear(yr); // xxxx 4 char year
501 date1.setMonth(mh-1); // 0-11 Bug 4048: javascript Date obj months are 0-index
502 date1.setDate(dy); // 1-31
507 function isBefore(value1, value2) {
508 var d1 = getDateObject(value1);
509 var d2 = getDateObject(value2);
510 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.
516 function isValidEmail(emailStr) {
518 if(emailStr.length== 0) {
521 // cn: bug 7128, a period at the end of the string mangles checks. (switched to accept spaces and delimiters)
522 var lastChar = emailStr.charAt(emailStr.length - 1);
523 if(!lastChar.match(/[^\.]/i)) {
526 //bug 40068, According to rules in page 6 of http://www.apps.ietf.org/rfc/rfc3696.html#sec-3,
527 //first character of local part of an email address
528 //should not be a period i.e. '.'
530 var firstLocalChar=emailStr.charAt(0);
531 if(firstLocalChar.match(/\./)){
535 //bug 40068, According to rules in page 6 of http://www.apps.ietf.org/rfc/rfc3696.html#sec-3,
536 //last character of local part of an email address
537 //should not be a period i.e. '.'
539 var pos=emailStr.lastIndexOf("@");
540 var localPart = emailStr.substr(0, pos);
541 var lastLocalChar=localPart.charAt(localPart.length - 1);
542 if(lastLocalChar.match(/\./)){
549 while ((results = reg.exec(emailStr)) != null) {
550 var original = results[0];
551 parsedResult = results[0].replace(';', '::;::');
552 emailStr = emailStr.replace (original, parsedResult);
556 while ((results = reg.exec(emailStr)) != null) {
557 var original = results[0];
558 //Check if we were using ; as a delimiter. If so, skip the commas
559 if(original.indexOf("::;::") == -1) {
560 var parsedResult = results[0].replace(',', '::;::');
561 emailStr = emailStr.replace (original, parsedResult);
565 // mfh: bug 15010 - more practical implementation of RFC 2822 from http://www.regular-expressions.info/email.html, modifed to accept CAPITAL LETTERS
566 //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))
569 //bug 40068, According to rules in page 6 of http://www.apps.ietf.org/rfc/rfc3696.html#sec-3,
570 //allowed special characters ! # $ % & ' * + - / = ? ^ _ ` . { | } ~ in local part
571 var emailArr = emailStr.split(/::;::/);
572 for (var i = 0; i < emailArr.length; i++) {
573 var emailAddress = emailArr[i];
574 if (trim(emailAddress) != '') {
575 if(!/^\s*[\w.%+\-&'#!\$\*=\?\^_`\{\}~\/]+@([A-Z0-9-]+\.)*[A-Z0-9-]+\.[\w-]{2,}\s*$/i.test(emailAddress) &&
576 !/^.*<[A-Z0-9._%+\-&'#!\$\*=\?\^_`\{\}~]+?@([A-Z0-9-]+\.)*[A-Z0-9-]+\.[\w-]{2,}>\s*$/i.test(emailAddress)) {
585 function isValidPhone(phoneStr) {
586 if(phoneStr.length== 0) {
589 if(!/^[0-9\-\(\)\s]+$/.test(phoneStr))
593 function isFloat(floatStr) {
594 if(floatStr.length== 0) {
597 if(!(typeof(num_grp_sep)=='undefined' || typeof(dec_sep)=='undefined')) {
598 floatStr = unformatNumberNoParse(floatStr, num_grp_sep, dec_sep).toString();
601 return /^(-)?[0-9\.]+$/.test(floatStr);
603 function isDBName(str) {
608 // must start with a letter
609 if(!/^[a-zA-Z][a-zA-Z\_0-9]*$/.test(str))
613 var time_reg_format = "[0-9]{1,2}\:[0-9]{2}";
614 function isTime(timeStr) {
615 var time_reg_format = "[0-9]{1,2}\:[0-9]{2}";
616 time_reg_format = time_reg_format.replace('([ap]m)', '');
617 time_reg_format = time_reg_format.replace('([AP]M)', '');
618 if(timeStr.length== 0){
621 //we now support multiple time formats
622 myregexp = new RegExp(time_reg_format)
623 if(!myregexp.test(timeStr))
629 function inRange(value, min, max) {
630 if (typeof num_grp_sep != 'undefined' && typeof dec_sep != 'undefined')
631 value = unformatNumberNoParse(value, num_grp_sep, dec_sep).toString();
632 return value >= min && value <= max;
635 function bothExist(item1, item2) {
636 if(typeof item1 == 'undefined') { return false; }
637 if(typeof item2 == 'undefined') { return false; }
638 if((item1 == '' && item2 != '') || (item1 != '' && item2 == '') ) { return false; }
642 trim = YAHOO.lang.trim;
645 function check_form(formname) {
646 if (typeof(siw) != 'undefined' && siw
647 && typeof(siw.selectingSomething) != 'undefined' && siw.selectingSomething)
649 return validate_form(formname, '');
652 function add_error_style(formname, input, txt, flash) {
653 var raiseFlag = false;
654 if (typeof flash == "undefined")
657 inputHandle = typeof input == "object" ? input : document.forms[formname][input];
658 style = get_current_bgcolor(inputHandle);
660 // strip off the colon at the end of the warning strings
661 if ( txt.substring(txt.length-1) == ':' )
662 txt = txt.substring(0,txt.length-1)
664 // Bug 28249 - To help avoid duplicate messages for an element, strip off extra messages and
665 // match on the field name itself
666 requiredTxt = SUGAR.language.get('app_strings', 'ERR_MISSING_REQUIRED_FIELDS');
667 invalidTxt = SUGAR.language.get('app_strings', 'ERR_INVALID_VALUE');
668 nomatchTxt = SUGAR.language.get('app_strings', 'ERR_SQS_NO_MATCH_FIELD');
669 matchTxt = txt.replace(requiredTxt,'').replace(invalidTxt,'').replace(nomatchTxt,'');
671 YUI().use('node', function (Y) {
672 Y.one(inputHandle).get('parentNode').get('children').each(function(node, index, nodeList){
673 if(node.hasClass('validation-message') && node.get('text').search(matchTxt)){
680 errorTextNode = document.createElement('div');
681 errorTextNode.className = 'required validation-message';
682 errorTextNode.innerHTML = txt;
683 if ( inputHandle.parentNode.className.indexOf('x-form-field-wrap') != -1 ) {
684 inputHandle.parentNode.parentNode.appendChild(errorTextNode);
687 inputHandle.parentNode.appendChild(errorTextNode);
690 inputHandle.style.backgroundColor = "#FF0000";
691 inputsWithErrors.push(inputHandle);
695 // We only need to setup the flashy-flashy on the first entry, it loops through all fields automatically
696 if ( inputsWithErrors.length == 1 ) {
697 for(var wp = 1; wp <= 10; wp++) {
698 window.setTimeout('fade_error_style(style, '+wp*10+')',1000+(wp*50));
701 if(typeof (window[formname + "_tabs"]) != "undefined") {
702 var tabView = window[formname + "_tabs"];
703 var parentDiv = YAHOO.util.Dom.getAncestorByTagName(inputHandle, "div");
705 var tabs = tabView.get("tabs");
706 for (var i in tabs) {
707 if (tabs[i].get("contentEl") == parentDiv
708 || YAHOO.util.Dom.isAncestor(tabs[i].get("contentEl"), inputHandle))
710 tabs[i].get("labelEl").style.color = "red";
711 if ( inputsWithErrors.length == 1 )
712 tabView.selectTab(i);
717 window.setTimeout("inputsWithErrors[" + (inputsWithErrors.length - 1) + "].style.backgroundColor = '';", 2000);
721 // Catch errors here so we don't allow an incomplete record through the javascript validation
727 * removes all error messages for the current form
729 function clear_all_errors() {
730 for(var wp = 0; wp < inputsWithErrors.length; wp++) {
731 if(typeof(inputsWithErrors[wp]) !='undefined' && typeof inputsWithErrors[wp].parentNode != 'undefined' && inputsWithErrors[wp].parentNode != null) {
732 if ( inputsWithErrors[wp].parentNode.className.indexOf('x-form-field-wrap') != -1 )
734 inputsWithErrors[wp].parentNode.parentNode.removeChild(inputsWithErrors[wp].parentNode.parentNode.lastChild);
738 inputsWithErrors[wp].parentNode.removeChild(inputsWithErrors[wp].parentNode.lastChild);
742 if (inputsWithErrors.length == 0) return;
744 if ( YAHOO.util.Dom.getAncestorByTagName(inputsWithErrors[0], "form") ) {
745 var formname = YAHOO.util.Dom.getAncestorByTagName(inputsWithErrors[0], "form").getAttribute("name");
746 if(typeof (window[formname + "_tabs"]) != "undefined") {
747 var tabView = window[formname + "_tabs"];
749 var tabs = tabView.get("tabs");
750 for (var i in tabs) {
751 if (typeof tabs[i] == "object")
752 tabs[i].get("labelEl").style.color = "";
756 inputsWithErrors = new Array();
760 function get_current_bgcolor(input) {
761 if(input.currentStyle) {// ie
762 style = input.currentStyle.backgroundColor;
763 return style.substring(1,7);
767 styleRGB = document.defaultView.getComputedStyle(input, '').getPropertyValue("background-color");
768 comma = styleRGB.indexOf(',');
769 style += dec2hex(styleRGB.substring(4, comma));
770 commaPrevious = comma;
771 comma = styleRGB.indexOf(',', commaPrevious+1);
772 style += dec2hex(styleRGB.substring(commaPrevious+2, comma));
773 style += dec2hex(styleRGB.substring(comma+2, styleRGB.lastIndexOf(')')));
778 function hex2dec(hex){return(parseInt(hex,16));}
779 var hexDigit=new Array("0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F");
780 function dec2hex(dec){return(hexDigit[dec>>4]+hexDigit[dec&15]);}
782 function fade_error_style(normalStyle, percent) {
783 errorStyle = 'c60c30';
784 var r1 = hex2dec(errorStyle.slice(0,2));
785 var g1 = hex2dec(errorStyle.slice(2,4));
786 var b1 = hex2dec(errorStyle.slice(4,6));
788 var r2 = hex2dec(normalStyle.slice(0,2));
789 var g2 = hex2dec(normalStyle.slice(2,4));
790 var b2 = hex2dec(normalStyle.slice(4,6));
793 var pc = percent / 100;
795 r= Math.floor(r1+(pc*(r2-r1)) + .5);
796 g= Math.floor(g1+(pc*(g2-g1)) + .5);
797 b= Math.floor(b1+(pc*(b2-b1)) + .5);
799 for(var wp = 0; wp < inputsWithErrors.length; wp++) {
800 inputsWithErrors[wp].style.backgroundColor = "#" + dec2hex(r) + dec2hex(g) + dec2hex(b);
804 function isFieldTypeExceptFromEmptyCheck(fieldType)
807 var exemptList = ['bool','file'];
808 for(var i=0;i<exemptList.length;i++)
810 if(fieldType == exemptList[i])
815 function validate_form(formname, startsWith){
816 requiredTxt = SUGAR.language.get('app_strings', 'ERR_MISSING_REQUIRED_FIELDS');
817 invalidTxt = SUGAR.language.get('app_strings', 'ERR_INVALID_VALUE');
819 if ( typeof (formname) == 'undefined')
823 if ( typeof (validate[formname]) == 'undefined')
825 disableOnUnloadEditView(document.forms[formname]);
829 var form = document.forms[formname];
832 var _date = new Date();
833 if(_date.getTime() < (lastSubmitTime + 2000) && startsWith == oldStartsWith) { // ignore submits for the next 2 seconds
836 lastSubmitTime = _date.getTime();
837 oldStartsWith = startsWith;
839 clear_all_errors(); // remove previous error messages
841 inputsWithErrors = new Array();
842 for(var i = 0; i < validate[formname].length; i++){
843 if(validate[formname][i][nameIndex].indexOf(startsWith) == 0){
844 if(typeof form[validate[formname][i][nameIndex]] != 'undefined' && typeof form[validate[formname][i][nameIndex]].value != 'undefined'){
847 //If a field is not required and it is blank or is binarydependant, skip validation.
848 //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
849 if(!validate[formname][i][requiredIndex] && trim(form[validate[formname][i][nameIndex]].value) == '' && (typeof(validate[formname][i][jstypeIndex]) != 'undefined' && validate[formname][i][jstypeIndex] != 'binarydep'))
854 if(validate[formname][i][requiredIndex]
855 && !isFieldTypeExceptFromEmptyCheck(validate[formname][i][typeIndex])
857 if(typeof form[validate[formname][i][nameIndex]] == 'undefined' || trim(form[validate[formname][i][nameIndex]].value) == ""){
858 add_error_style(formname, validate[formname][i][nameIndex], requiredTxt +' ' + validate[formname][i][msgIndex]);
863 switch(validate[formname][i][typeIndex]){
865 if(!isValidEmail(trim(form[validate[formname][i][nameIndex]].value))){
867 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
871 if( !isTime(trim(form[validate[formname][i][nameIndex]].value))){
873 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
875 case 'date': if(!isDate(trim(form[validate[formname][i][nameIndex]].value))){
877 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
882 if(!isDBName(trim(form[validate[formname][i][nameIndex]].value))){
884 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
887 // Bug #49614 : Check value without trimming before
889 if(!isDBName(form[validate[formname][i][nameIndex]].value)){
891 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
897 var file_input = form[validate[formname][i][nameIndex] + '_file'];
898 if( file_input && validate[formname][i][requiredIndex] && trim(file_input.value) == "" && !file_input.disabled ) {
900 add_error_style(formname, validate[formname][i][nameIndex], requiredTxt + " " + validate[formname][i][msgIndex]);
904 if(!isInteger(trim(form[validate[formname][i][nameIndex]].value))){
906 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
910 if(!isDecimal(trim(form[validate[formname][i][nameIndex]].value))){
912 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
917 if(!isFloat(trim(form[validate[formname][i][nameIndex]].value))){
919 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
923 var div_element_id = formname + '_' + form[validate[formname][i][nameIndex]].name + '_operation_div';
924 var input_elements = YAHOO.util.Selector.query('input', document.getElementById(div_element_id));
925 var primary_field_id = '';
926 var validation_passed = false;
927 var replace_selected = false;
929 //Loop through the option elements (replace or add currently)
930 for(t in input_elements) {
931 if(input_elements[t].type && input_elements[t].type == 'radio' && input_elements[t].checked == true && input_elements[t].value == 'replace') {
933 //Now find where the primary radio button is and if a value has been set
934 var radio_elements = YAHOO.util.Selector.query('input[type=radio]', document.getElementById(formname + '_team_name_table'));
936 for(var x = 0; x < radio_elements.length; x++) {
937 if(radio_elements[x].name != 'team_name_type') {
938 primary_field_id = 'team_name_collection_' + radio_elements[x].value;
939 if(radio_elements[x].checked) {
940 replace_selected = true;
941 if(trim(document.forms[formname].elements[primary_field_id].value) != '') {
942 validation_passed = true;
945 } else if(trim(document.forms[formname].elements[primary_field_id].value) != '') {
946 replace_selected = true;
953 if(replace_selected && !validation_passed) {
954 add_error_style(formname, primary_field_id, SUGAR.language.get('app_strings', 'ERR_NO_PRIMARY_TEAM_SPECIFIED'));
959 var table_element_id = formname + '_' + form[validate[formname][i][nameIndex]].name + '_table';
960 if(document.getElementById(table_element_id)) {
961 var input_elements = YAHOO.util.Selector.query('input[type=radio]', document.getElementById(table_element_id));
962 var has_primary = false;
963 var primary_field_id = form[validate[formname][i][nameIndex]].name + '_collection_0';
965 for(t in input_elements) {
966 primary_field_id = form[validate[formname][i][nameIndex]].name + '_collection_' + input_elements[t].value;
967 if(input_elements[t].type && input_elements[t].type == 'radio' && input_elements[t].checked == true) {
968 if(document.forms[formname].elements[primary_field_id].value != '') {
977 var field_id = form[validate[formname][i][nameIndex]].name + '_collection_' + input_elements[0].value;
978 add_error_style(formname, field_id, SUGAR.language.get('app_strings', 'ERR_NO_PRIMARY_TEAM_SPECIFIED'));
984 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex]);
988 if(typeof validate[formname][i][jstypeIndex] != 'undefined'/* && !isError*/){
990 switch(validate[formname][i][jstypeIndex]){
991 // Bug #47961 May be validation through callback is best way.
993 if (typeof validate[formname][i][callbackIndex] == 'function')
995 var result = validate[formname][i][callbackIndex](formname, validate[formname][i][nameIndex]);
999 add_error_style(formname, validate[formname][i][nameIndex], requiredTxt + " " + validate[formname][i][msgIndex]);
1004 if(!inRange(trim(form[validate[formname][i][nameIndex]].value), validate[formname][i][minIndex], validate[formname][i][maxIndex])){
1006 var lbl_validate_range = SUGAR.language.get('app_strings', 'LBL_VALIDATE_RANGE');
1007 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] + ") ");
1011 compareTo = form[validate[formname][i][compareToIndex]];
1012 if( typeof compareTo != 'undefined'){
1013 if(trim(compareTo.value) != '' || (validate[formname][i][allowblank] != 'true') ) {
1014 date2 = trim(compareTo.value);
1015 date1 = trim(form[validate[formname][i][nameIndex]].value);
1017 if(trim(date1).length != 0 && !isBefore(date1,date2)){
1020 //jc:#12287 - adding translation for the is not before message
1021 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex] + "(" + date1 + ") " + SUGAR.language.get('app_strings', 'MSG_IS_NOT_BEFORE') + ' ' +date2);
1027 value=unformatNumber(trim(form[validate[formname][i][nameIndex]].value), num_grp_sep, dec_sep);
1028 maximum = parseFloat(validate[formname][i][maxIndex]);
1029 if( typeof maximum != 'undefined'){
1032 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]);
1037 value=unformatNumber(trim(form[validate[formname][i][nameIndex]].value), num_grp_sep, dec_sep);
1038 minimum = parseFloat(validate[formname][i][minIndex]);
1039 if( typeof minimum != 'undefined'){
1042 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'));
1047 compareTo = form[validate[formname][i][compareToIndex]];
1048 if( typeof compareTo != 'undefined') {
1049 item1 = trim(form[validate[formname][i][nameIndex]].value);
1050 item2 = trim(compareTo.value);
1051 if(!bothExist(item1, item2)) {
1053 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex]);
1058 compareTo = form[validate[formname][i][compareToIndex]];
1059 if( typeof compareTo != 'undefined') {
1060 item1 = trim(form[validate[formname][i][nameIndex]].value);
1061 item2 = trim(compareTo.value);
1062 if(!bothExist(item1, item2) || item1 != item2) {
1064 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex]);
1069 arr = eval(validate[formname][i][arrIndex]);
1070 operator = validate[formname][i][operatorIndex];
1071 item1 = trim(form[validate[formname][i][nameIndex]].value);
1072 if (operator.charAt(0) == 'u') {
1073 item1 = item1.toUpperCase();
1074 operator = operator.substring(1);
1075 } else if (operator.charAt(0) == 'l') {
1076 item1 = item1.toLowerCase();
1077 operator = operator.substring(1);
1079 for(j = 0; j < arr.length; j++){
1081 if((operator == "==" && val == item1) || (operator == "!=" && val != item1)){
1083 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
1088 if(trim(form[validate[formname][i][nameIndex]].value) == 'false'){
1089 //Fake an error so form does not submit
1099 /* nsingh: BUG#15102
1100 Check min max default field logic.
1101 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.*/
1102 if(formsWithFieldLogic){
1103 var invalidLogic=false;
1104 if(formsWithFieldLogic.min && formsWithFieldLogic.max && formsWithFieldLogic._default) {
1105 var showErrorsOn={min:{value:'min', show:false, obj:formsWithFieldLogic.min.value},
1106 max:{value:'max',show:false, obj:formsWithFieldLogic.max.value},
1107 _default:{value:'default',show:false, obj:formsWithFieldLogic._default.value},
1108 len:{value:'len', show:false, obj:parseInt(formsWithFieldLogic.len.value,10)}};
1110 var min = (formsWithFieldLogic.min.value !='') ? parseFloat(formsWithFieldLogic.min.value) : 'undef';
1111 var max = (formsWithFieldLogic.max.value !='') ? parseFloat(formsWithFieldLogic.max.value) : 'undef';
1112 var _default = (formsWithFieldLogic._default.value!='')? parseFloat(formsWithFieldLogic._default.value) : 'undef';
1114 /*Check all lengths are <= max size.*/
1115 for(var i in showErrorsOn){
1116 if(showErrorsOn[i].value!='len' && showErrorsOn[i].obj.length > showErrorsOn.len.obj){
1118 showErrorsOn[i].show=true;
1119 showErrorsOn.len.show=true;
1123 if(min!='undef' && max!='undef' && _default!='undef'){
1124 if(!inRange(_default,min,max)){
1126 showErrorsOn.min.show=true;
1127 showErrorsOn.max.show=true;
1128 showErrorsOn._default.show=true;
1131 if(min!='undef' && max!= 'undef' && min > max){
1132 invalidLogic = true;
1133 showErrorsOn.min.show=true;
1134 showErrorsOn.max.show=true;
1136 if(min!='undef' && _default!='undef' && _default < min){
1138 invalidLogic = true;
1139 showErrorsOn.min.show=true;
1140 showErrorsOn._default.show=true;
1142 if(max!='undef' && _default !='undef' && _default>max){
1144 invalidLogic = true;
1145 showErrorsOn.max.show=true;
1146 showErrorsOn._default.show=true;
1151 for(var error in showErrorsOn)
1152 if(showErrorsOn[error].show)
1153 add_error_style(formname,showErrorsOn[error].value, formsWithFieldLogic.msg);
1158 formsWithFieldLogic = null;
1161 if(formWithPrecision){
1162 if (!isValidPrecision(formWithPrecision.float.value, formWithPrecision.precision.value)){
1164 add_error_style(formname, 'default', SUGAR.language.get('app_strings', 'ERR_COMPATIBLE_PRECISION_VALUE'));
1172 if (isError == true) {
1174 if (self.pageYOffset) // all except Explorer
1176 nwX = self.pageXOffset;
1177 seX = self.innerWidth;
1178 nwY = self.pageYOffset;
1179 seY = self.innerHeight;
1181 else if (document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
1183 nwX = document.documentElement.scrollLeft;
1184 seX = document.documentElement.clientWidth;
1185 nwY = document.documentElement.scrollTop;
1186 seY = document.documentElement.clientHeight;
1188 else if (document.body) // all other Explorers
1190 nwX = document.body.scrollLeft;
1191 seX = document.body.clientWidth;
1192 nwY = document.body.scrollTop;
1193 seY = document.body.clientHeight;
1196 var inView = true; // is there an error within viewport of browser
1197 for(var wp = 0; wp < inputsWithErrors.length; wp++) {
1198 var elementCoor = findElementPos(inputsWithErrors[wp]);
1199 if(!(elementCoor.x >= nwX && elementCoor.y >= nwY &&
1200 elementCoor.x <= seX && elementCoor.y <= seY)) { // if input is not within viewport
1202 scrollToTop = elementCoor.y - 75;
1203 scrollToLeft = elementCoor.x - 75;
1205 else { // on first input within viewport, don't scroll
1211 if(!inView) window.scrollTo(scrollToLeft,scrollToTop);
1216 disableOnUnloadEditView(form);
1223 * This array is used to remember mark status of rows in browse mode
1225 var marked_row = new Array;
1229 * Sets/unsets the pointer and marker in browse mode
1231 * @param object the table row
1232 * @param interger the row number
1233 * @param string the action calling this script (over, out or click)
1234 * @param string the default background color
1235 * @param string the color to use for mouseover
1236 * @param string the color to use for marking a row
1238 * @return boolean whether pointer is set or not
1240 function setPointer(theRow, theRowNum, theAction, theDefaultColor, thePointerColor, theMarkColor) {
1241 var theCells = null;
1243 // 1. Pointer and mark feature are disabled or the browser can't get the
1245 if ((thePointerColor == '' && theMarkColor == '')
1246 || typeof(theRow.style) == 'undefined') {
1250 // 2. Gets the current row and exits if the browser can't get it
1251 if (typeof(document.getElementsByTagName) != 'undefined') {
1252 theCells = theRow.getElementsByTagName('td');
1254 else if (typeof(theRow.cells) != 'undefined') {
1255 theCells = theRow.cells;
1261 // 3. Gets the current color...
1262 var rowCellsCnt = theCells.length;
1263 var domDetect = null;
1264 var currentColor = null;
1265 var newColor = null;
1266 // 3.1 ... with DOM compatible browsers except Opera that does not return
1267 // valid values with "getAttribute"
1268 if (typeof(window.opera) == 'undefined'
1269 && typeof(theCells[0].getAttribute) != 'undefined') {
1270 currentColor = theCells[0].getAttribute('bgcolor');
1273 // 3.2 ... with other browsers
1275 currentColor = theCells[0].style.backgroundColor;
1279 // 4. Defines the new color
1280 // 4.1 Current color is the default one
1281 if (currentColor == ''
1282 || (currentColor!= null && (currentColor.toLowerCase() == theDefaultColor.toLowerCase()))) {
1283 if (theAction == 'over' && thePointerColor != '') {
1284 newColor = thePointerColor;
1286 else if (theAction == 'click' && theMarkColor != '') {
1287 newColor = theMarkColor;
1288 marked_row[theRowNum] = true;
1291 // 4.1.2 Current color is the pointer one
1292 else if (currentColor!= null && (currentColor.toLowerCase() == thePointerColor.toLowerCase())
1293 && (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])) {
1294 if (theAction == 'out') {
1295 newColor = theDefaultColor;
1297 else if (theAction == 'click' && theMarkColor != '') {
1298 newColor = theMarkColor;
1299 marked_row[theRowNum] = true;
1302 // 4.1.3 Current color is the marker one
1303 else if (currentColor!= null && (currentColor.toLowerCase() == theMarkColor.toLowerCase())) {
1304 if (theAction == 'click') {
1305 newColor = (thePointerColor != '')
1308 marked_row[theRowNum] = (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])
1314 // 5. Sets the new color...
1317 // 5.1 ... with DOM compatible browsers except Opera
1319 for (c = 0; c < rowCellsCnt; c++) {
1320 theCells[c].setAttribute('bgcolor', newColor, 0);
1323 // 5.2 ... with other browsers
1325 for (c = 0; c < rowCellsCnt; c++) {
1326 theCells[c].style.backgroundColor = newColor;
1332 } // end of the 'setPointer()' function
1336 * listbox redirection
1338 function goToUrl(selObj, goToLocation) {
1339 eval("document.location.href = '" + goToLocation + "pos=" + selObj.options[selObj.selectedIndex].value + "'");
1344 var json_objects = new Object();
1346 function getXMLHTTPinstance() {
1347 var xmlhttp = false;
1348 var userAgent = navigator.userAgent.toLowerCase() ;
1350 // IE Check supports ActiveX controls
1351 if (userAgent.indexOf("msie") != -1 && userAgent.indexOf("mac") == -1 && userAgent.indexOf("opera") == -1) {
1352 var version = navigator.appVersion.match(/MSIE (.\..)/)[1] ;
1353 if(version >= 5.5 ) {
1355 xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
1359 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
1368 if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
1369 xmlhttp = new XMLHttpRequest();
1374 // NOW LOAD THE OBJECT..
1375 var global_xmlhttp = getXMLHTTPinstance();
1377 function http_fetch_sync(url,post_data) {
1378 global_xmlhttp = getXMLHTTPinstance();
1381 if(typeof(post_data) != 'undefined') method = 'POST';
1383 global_xmlhttp.open(method, url,false);
1386 alert('message:'+e.message+":url:"+url);
1388 if(method == 'POST') {
1389 global_xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
1392 global_xmlhttp.send(post_data);
1394 if (SUGAR.util.isLoginPage(global_xmlhttp.responseText))
1397 var args = {"responseText" : global_xmlhttp.responseText,
1398 "responseXML" : global_xmlhttp.responseXML,
1399 "request_id" : typeof(request_id) != "undefined" ? request_id : 0};
1403 // this is a GET unless post_data is defined
1405 function http_fetch_async(url,callback,request_id,post_data) {
1407 if(typeof(post_data) != 'undefined') {
1412 global_xmlhttp.open(method, url,true);
1415 alert('message:'+e.message+":url:"+url);
1417 if(method == 'POST') {
1418 global_xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
1420 global_xmlhttp.onreadystatechange = function() {
1421 if(global_xmlhttp.readyState==4) {
1422 if(global_xmlhttp.status == 200) {
1423 if (SUGAR.util.isLoginPage(global_xmlhttp.responseText))
1425 var args = {"responseText" : global_xmlhttp.responseText,
1426 "responseXML" : global_xmlhttp.responseXML,
1427 "request_id" : request_id };
1428 callback.call(document,args);
1431 alert("There was a problem retrieving the XML data:\n" + global_xmlhttp.statusText);
1435 global_xmlhttp.send(post_data);
1438 function insert_at_cursor(field, value) {
1440 if (document.selection) {
1442 sel = document.selection.createRange();
1446 else if(field.selectionStart || field.selectionStart == '0') {
1447 var start_pos = field.selectionStart;
1448 var end_pos = field.selectionEnd;
1449 field.value = field.value.substring(0, start_pos) + value + field.value.substring(end_pos, field.value.length);
1452 field.value += value;
1456 function checkParentType(type,button) {
1457 if(button == null) {
1460 if(typeof disabledModules != 'undefined' && typeof(disabledModules[type]) != 'undefined') {
1461 button.disabled='disabled';
1464 button.disabled = false;
1468 function parseDate(input, format) {
1470 format = format.replace(/%/g, '');
1471 sep = format.charAt(1);
1472 yAt = format.indexOf('Y')
1473 // 1-1-06 or 1-12-06 or 1-1-2006 or 1-12-2006
1474 if(date.match(/^\d{1,2}[\/-]\d{1,2}[\/-]\d{2,4}$/) && yAt == 4) {
1475 if(date.match(/^\d{1}[\/-].*$/)) date = '0' + date;
1476 if(date.match(/^\d{2}[\/-]\d{1}[\/-].*$/)) date = date.substring(0,3) + '0' + date.substring(3,date.length);
1477 if(date.match(/^\d{2}[\/-]\d{2}[\/-]\d{2}$/)) date = date.substring(0,6) + '20' + date.substring(6,date.length);
1479 // 06-11-1 or 06-1-1
1480 else if(date.match(/^\d{2,4}[\/-]\d{1,2}[\/-]\d{1,2}$/)) {
1481 if(date.match(/^\d{2}[\/-].*$/)) date = '20' + date;
1482 if(date.match(/^\d{4}[\/-]\d{1}[\/-].*$/)) date = date.substring(0,5) + '0' + date.substring(5,date.length);
1483 if(date.match(/^\d{4}[\/-]\d{2}[\/-]\d{1}$/)) date = date.substring(0,8) + '0' + date.substring(8,date.length);
1485 else if(date.match(/^\d{4,8}$/)) { // digits only
1487 if(date.match(/^\d{8}$/)) digits = 8;// match for 8 digits
1488 else if(date.match(/\d{6}/)) digits = 6;// match for 5 digits
1489 else if(date.match(/\d{4}/)) digits = 4;// match for 5 digits
1490 else if(date.match(/\d{5}/)) digits = 5;// match for 5 digits
1495 case 4: date = '20' + date.substring(0,2) + sep + '0' + date.substring(2, 3) + sep + '0' + date.substring(3,4); break;
1496 case 5: date = '20' + date.substring(0,2) + sep + date.substring(2, 4) + sep + '0' + date.substring(4,5); break;
1497 case 6: date = '20' + date.substring(0,2) + sep + date.substring(2, 4) + sep + date.substring(4,6); break;
1498 case 8: date = date.substring(0,4) + sep + date.substring(4, 6) + sep + date.substring(6,8); break;
1503 case 4: date = '0' + date.substring(0,1) + sep + '20' + date.substring(1, 3) + sep + '0' + date.substring(3,4); break;
1504 case 5: date = date.substring(0,2) + sep + '20' + date.substring(2, 4) + sep + '0' + date.substring(4,5); break;
1505 case 6: date = date.substring(0,2) + sep + '20' + date.substring(2, 4) + sep + date.substring(4,6); break;
1506 case 8: date = date.substring(0,2) + sep + date.substring(2, 6) + sep + date.substring(6,8); break;
1510 case 4: date = '0' + date.substring(0,1) + sep + '0' + date.substring(1, 2) + sep + '20' + date.substring(2,4); break;
1511 case 5: date = '0' + date.substring(0,1) + sep + date.substring(1, 3) + sep + '20' + date.substring(3,5); break;
1512 case 6: date = date.substring(0,2) + sep + date.substring(2, 4) + sep + '20' + date.substring(4,6); break;
1513 case 8: date = date.substring(0,2) + sep + date.substring(2, 4) + sep + date.substring(4,8); break;
1518 date = date.replace(/[\/-]/g, sep);
1522 // find obj's position
1523 function findElementPos(obj) {
1526 if (obj.offsetParent) {
1527 while (obj.offsetParent) {
1528 x += obj.offsetLeft;
1530 obj = obj.offsetParent;
1532 }//if offsetParent exists
1533 else if (obj.x && obj.y) {
1537 return new coordinate(x, y);
1541 // get dimensions of the browser window
1542 function getClientDim() {
1543 var nwX, nwY, seX, seY;
1544 if (self.pageYOffset) // all except Explorer
1546 nwX = self.pageXOffset;
1547 seX = self.innerWidth + nwX;
1548 nwY = self.pageYOffset;
1549 seY = self.innerHeight + nwY;
1551 else if (document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
1553 nwX = document.documentElement.scrollLeft;
1554 seX = document.documentElement.clientWidth + nwX;
1555 nwY = document.documentElement.scrollTop;
1556 seY = document.documentElement.clientHeight + nwY;
1558 else if (document.body) // all other Explorers
1560 nwX = document.body.scrollLeft;
1561 seX = document.body.clientWidth + nwX;
1562 nwY = document.body.scrollTop;
1563 seY = document.body.clientHeight + nwY;
1565 return {'nw' : new coordinate(nwX, nwY), 'se' : new coordinate(seX, seY)};
1569 * stop propagation on events
1571 function freezeEvent(e) {
1573 if (e.preventDefault) e.preventDefault();
1574 e.returnValue = false;
1575 e.cancelBubble = true;
1576 if (e.stopPropagation) e.stopPropagation();
1585 function coordinate(_x, _y) {
1594 return new position(this.x + rh.x, this.y + rh.y);
1598 return new position(this.x + rh.x, this.y + rh.y);
1602 // sends theForm via AJAX and fills in the theDiv
1603 function sendAndRetrieve(theForm, theDiv, loadingStr) {
1604 function success(data) {
1605 document.getElementById(theDiv).innerHTML = data.responseText;
1606 ajaxStatus.hideStatus();
1608 if(typeof loadingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
1609 ajaxStatus.showStatus(loadingStr);
1610 oForm = new YAHOO.util.Element(theForm);
1611 if ( oForm.get('enctype') && oForm.get('enctype') == 'multipart/form-data' ) {
1612 // the second argument is true to indicate file upload.
1613 YAHOO.util.Connect.setForm(theForm, true);
1614 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {upload: success, failure: success});
1616 YAHOO.util.Connect.setForm(theForm);
1617 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
1622 //save the form and redirect
1623 function sendAndRedirect(theForm, loadingStr, redirect_location) {
1624 function success(data) {
1625 if(redirect_location){
1626 location.href=redirect_location;
1628 ajaxStatus.hideStatus();
1630 if(typeof loadingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
1631 ajaxStatus.showStatus(loadingStr);
1632 oForm = new YAHOO.util.Element(theForm);
1633 if ( oForm.get('enctype') && oForm.get('enctype') == 'multipart/form-data' ) {
1634 // the second argument is true to indicate file upload.
1635 YAHOO.util.Connect.setForm(theForm, true);
1636 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {upload: success, failure: success});
1638 YAHOO.util.Connect.setForm(theForm);
1639 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
1644 function saveForm(theForm, theDiv, loadingStr) {
1645 if(check_form(theForm)){
1646 for(i = 0; i < ajaxFormArray.length; i++){
1647 if(ajaxFormArray[i] == theForm){
1648 ajaxFormArray.splice(i, 1);
1651 return sendAndRetrieve(theForm, loadingStr, theDiv);
1657 // Builds a "snapshot" of the form, so we can use it to see if someone has changed it.
1658 function snapshotForm(theForm) {
1659 var snapshotTxt = '';
1660 var elemList = theForm.elements;
1664 for( var i = 0; i < elemList.length ; i++ ) {
1666 if ( typeof(elem.type) == 'undefined' ) {
1670 elemType = elem.type.toLowerCase();
1672 snapshotTxt = snapshotTxt + elem.name;
1674 if ( elemType == 'text' || elemType == 'textarea' || elemType == 'password' ) {
1675 snapshotTxt = snapshotTxt + elem.value;
1677 else if ( elemType == 'select' || elemType == 'select-one' || elemType == 'select-multiple' ) {
1678 var optionList = elem.options;
1679 for ( var ii = 0 ; ii < optionList.length ; ii++ ) {
1680 if ( optionList[ii].selected ) {
1681 snapshotTxt = snapshotTxt + optionList[ii].value;
1685 else if ( elemType == 'radio' || elemType == 'checkbox' ) {
1686 if ( elem.selected ) {
1687 snapshotTxt = snapshotTxt + 'checked';
1690 else if ( elemType == 'hidden' ) {
1691 snapshotTxt = snapshotTxt + elem.value;
1698 function initEditView(theForm) {
1699 if (SUGAR.util.ajaxCallInProgress()) {
1700 window.setTimeout(function(){initEditView(theForm);}, 100);
1704 if ( theForm == null || theForm.id == null ) {
1705 // Not much we can do here.
1709 // we don't need to check if the data is changed in the search popup
1710 if (theForm.id == 'popup_query_form' || theForm.id == 'MassUpdate') {
1713 if ( typeof editViewSnapshots == 'undefined' || editViewSnapshots == null ) {
1714 editViewSnapshots = new Object();
1716 if ( typeof SUGAR.loadedForms == 'undefined' || SUGAR.loadedForms == null) {
1717 SUGAR.loadedForms = new Object();
1720 editViewSnapshots[theForm.id] = snapshotForm(theForm);
1721 SUGAR.loadedForms[theForm.id] = true;
1724 function onUnloadEditView(theForm) {
1726 var dataHasChanged = false;
1727 if ( typeof editViewSnapshots == 'undefined' ) {
1728 // No snapshots, move along
1732 if ( typeof theForm == 'undefined' ) {
1733 // Need to check all editViewSnapshots
1734 for ( var idx in editViewSnapshots ) {
1736 theForm = document.getElementById(idx);
1737 // console.log('DEBUG: Checking all forms '+theForm.id);
1738 if ( theForm == null
1739 || typeof editViewSnapshots[theForm.id] == 'undefined'
1740 || editViewSnapshots[theForm.id] == null
1741 || !SUGAR.loadedForms[theForm.id]) {
1745 var snap = snapshotForm(theForm);
1746 if ( editViewSnapshots[theForm.id] != snap ) {
1747 dataHasChanged = true;
1751 // Just need to check a single form for changes
1752 if ( editViewSnapshots == null || typeof theForm.id == 'undefined' || typeof editViewSnapshots[theForm.id] == 'undefined' || editViewSnapshots[theForm.id] == null ) {
1756 // console.log('DEBUG: Checking one form '+theForm.id);
1757 if ( editViewSnapshots[theForm.id] != snapshotForm(theForm) ) {
1758 // Data has changed.
1759 dataHasChanged = true;
1763 if ( dataHasChanged == true ) {
1764 return SUGAR.language.get('app_strings','WARN_UNSAVED_CHANGES');
1771 function disableOnUnloadEditView(theForm) {
1772 // If you don't pass anything in, it disables all checking
1773 if ( typeof theForm == 'undefined' || typeof editViewSnapshots == 'undefined' || theForm == null || editViewSnapshots == null) {
1774 window.onbeforeunload = null;
1775 editViewSnapshots = null;
1777 // console.log('DEBUG: Disabling all edit view checks');
1780 // Otherwise, it just disables it for this form
1781 if ( typeof(theForm.id) != 'undefined' && typeof(editViewSnapshots[theForm.id]) != 'undefined' ) {
1782 editViewSnapshots[theForm.id] = null;
1785 // console.log('DEBUG : Disabling just checks for '+theForm.id);
1791 * save some forms using an ajax call
1792 * theForms - the ids of all of theh forms to save
1793 * savingStr - the string to display when saving the form
1794 * completeStr - the string to display when the form has been saved
1796 function saveForms( savingStr, completeStr) {
1798 theForms = ajaxFormArray;
1799 function success(data) {
1800 var theForm = document.getElementById(ajaxFormArray[0]);
1801 document.getElementById('multiedit_'+theForm.id).innerHTML = data.responseText;
1802 var saveAllButton = document.getElementById('ajaxsaveall');
1803 ajaxFormArray.splice(index, 1);
1804 if(saveAllButton && ajaxFormArray.length <= 1){
1805 saveAllButton.style.visibility = 'hidden';
1808 if(index == theForms.length){
1809 ajaxStatus.showStatus(completeStr);
1810 window.setTimeout('ajaxStatus.hideStatus();', 2000);
1812 saveAllButton.style.visibility = 'hidden';
1817 if(typeof savingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
1818 ajaxStatus.showStatus(savingStr);
1820 //loop through the forms saving each one
1821 for(i = 0; i < theForms.length; i++){
1822 var theForm = document.getElementById(theForms[i]);
1823 if(check_form(theForm.id)){
1824 theForm.action.value='AjaxFormSave';
1825 YAHOO.util.Connect.setForm(theForm);
1826 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
1828 ajaxStatus.hideStatus();
1830 lastSubmitTime = lastSubmitTime-2000;
1835 // -- start sugarListView class
1836 // js functions used for ListView
1837 function sugarListView() {
1841 sugarListView.prototype.confirm_action = function(del) {
1843 return confirm( SUGAR.language.get('app_strings', 'NTC_DELETE_CONFIRMATION_NUM') + sugarListView.get_num_selected() + SUGAR.language.get('app_strings', 'NTC_DELETE_SELECTED_RECORDS'));
1846 return confirm( SUGAR.language.get('app_strings', 'NTC_UPDATE_CONFIRMATION_NUM') + sugarListView.get_num_selected() + SUGAR.language.get('app_strings', 'NTC_DELETE_SELECTED_RECORDS'));
1850 sugarListView.get_num_selected = function () {
1851 var selectCount = $("input[name='selectCount[]']:first");
1852 if(selectCount.length > 0)
1853 return parseInt(selectCount.val().replace("+", ""));
1857 sugarListView.update_count = function(count, add) {
1858 if(typeof document.MassUpdate != 'undefined') {
1859 the_form = document.MassUpdate;
1860 for(var wp = 0; wp < the_form.elements.length; wp++) {
1861 if(typeof the_form.elements[wp].name != 'undefined' && the_form.elements[wp].name == 'selectCount[]') {
1863 the_form.elements[wp].value = parseInt(the_form.elements[wp].value,10) + count;
1864 if (the_form.select_entire_list.value == 1 && the_form.show_plus.value) {
1865 the_form.elements[wp].value += '+';
1868 if (the_form.select_entire_list.value == 1 && the_form.show_plus.value) {
1869 the_form.elements[wp].value = count + '+';
1871 the_form.elements[wp].value = count;
1878 sugarListView.prototype.use_external_mail_client = function(no_record_txt, module) {
1879 selected_records = sugarListView.get_checks_count();
1880 if(selected_records <1) {
1881 alert(no_record_txt);
1885 if (document.MassUpdate.select_entire_list.value == 1) {
1886 if (totalCount > 10) {
1887 alert(totalCountError);
1892 else if (document.MassUpdate.massall.checked == true)
1896 sugarListView.get_checks();
1898 if(select) { // use selected items
1899 ids = document.MassUpdate.uid.value;
1901 else { // use current page
1902 inputs = document.MassUpdate.elements;
1904 for(i = 0; i < inputs.length; i++) {
1905 if(inputs[i].name == 'mass[]' && inputs[i].checked && typeof(inputs[i].value) != 'function') {
1906 ar.push(inputs[i].value);
1911 YAHOO.util.Connect.asyncRequest("POST", "index.php?", {
1912 success: this.use_external_mail_client_callback
1913 }, SUGAR.util.paramsToUrl({
1916 listViewExternalClient: 1,
1917 action_module: module,
1925 sugarListView.prototype.use_external_mail_client_callback = function(o)
1928 location.href = 'mailto:' + o.responseText;
1931 sugarListView.prototype.send_form_for_emails = function(select, currentModule, action, no_record_txt,action_module,totalCount, totalCountError) {
1932 if ( typeof(SUGAR.config.email_sugarclient_listviewmaxselect) != 'undefined' ) {
1936 maxCount = SUGAR.config.email_sugarclient_listviewmaxselect;
1939 if (document.MassUpdate.select_entire_list.value == 1) {
1940 if (totalCount > maxCount) {
1941 alert(totalCountError);
1946 else if (document.MassUpdate.massall.checked == true)
1951 sugarListView.get_checks();
1952 // create new form to post (can't access action property of MassUpdate form due to action input)
1953 var newForm = document.createElement('form');
1954 newForm.method = 'post';
1955 newForm.action = action;
1956 newForm.name = 'newForm';
1957 newForm.id = 'newForm';
1958 var uidTa = document.createElement('textarea');
1960 uidTa.style.display = 'none';
1962 if(select) { // use selected items
1963 uidTa.value = document.MassUpdate.uid.value;
1965 else { // use current page
1966 inputs = document.MassUpdate.elements;
1968 for(i = 0; i < inputs.length; i++) {
1969 if(inputs[i].name == 'mass[]' && inputs[i].checked && typeof(inputs[i].value) != 'function') {
1970 ar.push(inputs[i].value);
1973 uidTa.value = ar.join(',');
1976 if(uidTa.value == '') {
1977 alert(no_record_txt);
1981 var selectedArray = uidTa.value.split(",");
1982 if(selectedArray.length > maxCount) {
1983 alert(totalCountError);
1986 newForm.appendChild(uidTa);
1988 var moduleInput = document.createElement('input');
1989 moduleInput.name = 'module';
1990 moduleInput.type = 'hidden';
1991 moduleInput.value = currentModule;
1992 newForm.appendChild(moduleInput);
1994 var actionInput = document.createElement('input');
1995 actionInput.name = 'action';
1996 actionInput.type = 'hidden';
1997 actionInput.value = 'Compose';
1998 newForm.appendChild(actionInput);
2000 if (typeof action_module != 'undefined' && action_module!= '') {
2001 var actionModule = document.createElement('input');
2002 actionModule.name = 'action_module';
2003 actionModule.type = 'hidden';
2004 actionModule.value = action_module;
2005 newForm.appendChild(actionModule);
2007 //return_info must follow this pattern."&return_module=Accounts&return_action=index"
2008 if (typeof return_info!= 'undefined' && return_info != '') {
2009 var params= return_info.split('&');
2010 if (params.length > 0) {
2011 for (var i=0;i< params.length;i++) {
2012 if (params[i].length > 0) {
2013 var param_nv=params[i].split('=');
2014 if (param_nv.length==2){
2015 returnModule = document.createElement('input');
2016 returnModule.name = param_nv[0];
2017 returnModule.type = 'hidden';
2018 returnModule.value = param_nv[1];
2019 newForm.appendChild(returnModule);
2026 var isAjaxCall = document.createElement('input');
2027 isAjaxCall.name = 'ajaxCall';
2028 isAjaxCall.type = 'hidden';
2029 isAjaxCall.value = true;
2030 newForm.appendChild(isAjaxCall);
2032 var isListView = document.createElement('input');
2033 isListView.name = 'ListView';
2034 isListView.type = 'hidden';
2035 isListView.value = true;
2036 newForm.appendChild(isListView);
2038 var toPdf = document.createElement('input');
2039 toPdf.name = 'to_pdf';
2040 toPdf.type = 'hidden';
2042 newForm.appendChild(toPdf);
2044 //Grab the Quick Compose package for the listview
2045 YAHOO.util.Connect.setForm(newForm);
2048 success: function(o) {
2049 var resp = YAHOO.lang.JSON.parse(o.responseText);
2050 var quickComposePackage = new Object();
2051 quickComposePackage.composePackage = resp;
2052 quickComposePackage.fullComposeUrl = 'index.php?module=Emails&action=Compose&ListView=true' +
2053 '&uid=' + uidTa.value + '&action_module=' + action_module;
2055 SUGAR.quickCompose.init(quickComposePackage);
2059 YAHOO.util.Connect.asyncRequest('POST','index.php', callback,null);
2061 // awu Bug 18624: Fixing issue where a canceled Export and unselect of row will persist the uid field, clear the field
2062 document.MassUpdate.uid.value = '';
2067 sugarListView.prototype.send_form = function(select, currentModule, action, no_record_txt,action_module,return_info) {
2068 if (document.MassUpdate.select_entire_list.value == 1) {
2070 if(sugarListView.get_checks_count() < 1) {
2071 alert(no_record_txt);
2076 if ( action.indexOf('?') != -1 )
2077 href += '&module=' + currentModule;
2079 href += '?module=' + currentModule;
2082 href += return_info;
2083 var newForm = document.createElement('form');
2084 newForm.method = 'post';
2085 newForm.action = href;
2086 newForm.name = 'newForm';
2087 newForm.id = 'newForm';
2088 var postTa = document.createElement('textarea');
2089 postTa.name = 'current_post';
2090 postTa.value = document.MassUpdate.current_query_by_page.value;
2091 postTa.style.display = 'none';
2092 newForm.appendChild(postTa);
2093 document.MassUpdate.parentNode.appendChild(newForm);
2097 else if (document.MassUpdate.massall.checked == true)
2102 sugarListView.get_checks();
2103 // create new form to post (can't access action property of MassUpdate form due to action input)
2104 var newForm = document.createElement('form');
2105 newForm.method = 'post';
2106 newForm.action = action;
2107 newForm.name = 'newForm';
2108 newForm.id = 'newForm';
2109 var uidTa = document.createElement('textarea');
2111 uidTa.style.display = 'none';
2112 uidTa.value = document.MassUpdate.uid.value;
2114 if(uidTa.value == '') {
2115 alert(no_record_txt);
2119 newForm.appendChild(uidTa);
2121 var moduleInput = document.createElement('input');
2122 moduleInput.name = 'module';
2123 moduleInput.type = 'hidden';
2124 moduleInput.value = currentModule;
2125 newForm.appendChild(moduleInput);
2127 var actionInput = document.createElement('input');
2128 actionInput.name = 'action';
2129 actionInput.type = 'hidden';
2130 actionInput.value = 'index';
2131 newForm.appendChild(actionInput);
2133 if (typeof action_module != 'undefined' && action_module!= '') {
2134 var actionModule = document.createElement('input');
2135 actionModule.name = 'action_module';
2136 actionModule.type = 'hidden';
2137 actionModule.value = action_module;
2138 newForm.appendChild(actionModule);
2140 //return_info must follow this pattern."&return_module=Accounts&return_action=index"
2141 if (typeof return_info!= 'undefined' && return_info != '') {
2142 var params= return_info.split('&');
2143 if (params.length > 0) {
2144 for (var i=0;i< params.length;i++) {
2145 if (params[i].length > 0) {
2146 var param_nv=params[i].split('=');
2147 if (param_nv.length==2){
2148 returnModule = document.createElement('input');
2149 returnModule.name = param_nv[0];
2150 returnModule.type = 'hidden';
2151 returnModule.value = param_nv[1];
2152 newForm.appendChild(returnModule);
2159 document.MassUpdate.parentNode.appendChild(newForm);
2162 // awu Bug 18624: Fixing issue where a canceled Export and unselect of row will persist the uid field, clear the field
2163 document.MassUpdate.uid.value = '';
2167 //return a count of checked row.
2168 sugarListView.get_checks_count = function() {
2171 if(document.MassUpdate.uid.value != '') {
2172 oldUids = document.MassUpdate.uid.value.split(',');
2173 for(uid in oldUids) {
2174 if(typeof(oldUids[uid]) != 'function') {
2175 ar[oldUids[uid]] = 1;
2179 // build associated array of uids, associated array ensures uniqueness
2180 inputs = document.MassUpdate.elements;
2181 for(i = 0; i < inputs.length; i++) {
2182 if(inputs[i].name == 'mass[]') {
2183 ar[inputs[i].value] = (inputs[i].checked) ? 1 : 0; // 0 of it is unchecked
2187 // build regular array of uids
2190 if((typeof(ar[i]) != 'function') && ar[i] == 1) {
2198 // saves the checks on the current page into the uid textarea
2199 sugarListView.get_checks = function() {
2201 if(typeof document.MassUpdate != 'undefined' ){
2202 if(document.MassUpdate.uid.value != '') {
2203 oldUids = document.MassUpdate.uid.value.split(',');
2204 for(uid in oldUids) {
2205 if(typeof(oldUids[uid]) != 'function') {
2206 ar[oldUids[uid]] = 1;
2211 // build associated array of uids, associated array ensures uniqueness
2212 inputs = document.MassUpdate.elements;
2213 for(i = 0; i < inputs.length; i++) {
2214 if(inputs[i].name == 'mass[]') {
2215 ar[inputs[i].value] = (inputs[i].checked) ? 1 : 0; // 0 of it is unchecked
2219 // build regular array of uids
2222 if(typeof(ar[i]) != 'function' && ar[i] == 1) {
2227 document.MassUpdate.uid.value = uids.join(',');
2229 if(uids.length == 0) return false; // return false if no checks to get
2230 return true; // there are saved checks
2235 sugarListView.prototype.order_checks = function(order,orderBy,moduleString){
2236 checks = sugarListView.get_checks();
2237 eval('document.MassUpdate.' + moduleString + '.value = orderBy');
2238 document.MassUpdate.lvso.value = order;
2239 if(typeof document.MassUpdate.massupdate != 'undefined') {
2240 document.MassUpdate.massupdate.value = 'false';
2243 //we must first clear the action of massupdate, change it to index
2244 document.MassUpdate.action.value = document.MassUpdate.return_action.value;
2245 document.MassUpdate.return_module.value='';
2246 document.MassUpdate.return_action.value='';
2247 document.MassUpdate.submit();
2251 sugarListView.prototype.save_checks = function(offset, moduleString) {
2252 checks = sugarListView.get_checks();
2253 if(typeof document.MassUpdate != 'undefined'){
2254 eval('document.MassUpdate.' + moduleString + '.value = offset');
2256 if(typeof document.MassUpdate.massupdate != 'undefined') {
2257 document.MassUpdate.massupdate.value = 'false';
2260 //we must first clear the action of massupdate, change it to index
2261 document.MassUpdate.action.value = document.MassUpdate.return_action.value;
2262 document.MassUpdate.return_module.value='';
2263 document.MassUpdate.return_action.value='';
2264 document.MassUpdate.submit();
2272 sugarListView.prototype.check_item = function(cb, form) {
2274 sugarListView.update_count(1, true);
2277 sugarListView.update_count(-1, true);
2278 if(typeof form != 'undefined' && form != null) {
2279 sugarListView.prototype.updateUid(cb, form);
2282 sugarListView.prototype.toggleSelected();
2285 sugarListView.prototype.toggleSelected = function() {
2287 var numSelected = sugarListView.get_num_selected();
2288 var selectedRecords = document.getElementById("selectedRecordsTop");
2289 var selectActions = document.getElementById("selectActions");
2290 var selectActionsDisabled = document.getElementById("selectActionsDisabled");
2291 if(numSelected > 0) {
2292 $(selectedRecords).removeAttr("style").addClass("show");
2293 $(".selectActionsDisabled").hide();
2294 jQuery('ul[name=selectActions]').each(function () {
2295 jQuery(this).removeAttr("style").addClass("show");
2299 $(selectedRecords).hide();
2300 $(".selectActionsDisabled").removeAttr("style").addClass("show");
2301 jQuery('ul[name=selectActions]').each(function () {
2302 jQuery(this).hide();
2308 /**#28000, remove the unselect record id from MassUpdate.uid **/
2309 sugarListView.prototype.updateUid = function(cb , form){
2310 if(form.name == 'MassUpdate' && form.uid && form.uid.value && cb.value && form.uid.value.indexOf(cb.value) != -1){
2311 if(form.uid.value.indexOf(','+cb.value)!= -1){
2312 form.uid.value = form.uid.value.replace(','+cb.value , '');
2313 }else if(form.uid.value.indexOf(cb.value + ',')!= -1){
2314 form.uid.value = form.uid.value.replace(cb.value + ',' , '');
2315 }else if(form.uid.value.indexOf(cb.value)!= -1){
2316 form.uid.value = form.uid.value.replace(cb.value , '');
2321 sugarListView.prototype.check_entire_list = function(form, field, value, list_count) {
2322 // count number of items
2324 $(document.MassUpdate.massall).each(function(){
2325 $(this).attr('checked', true).attr('disabled', true);
2327 for (i = 0; i < form.elements.length; i++) {
2328 if(form.elements[i].name == field && form.elements[i].disabled == false) {
2329 if(form.elements[i].checked != value) count++;
2330 form.elements[i].checked = value;
2331 form.elements[i].disabled = true;
2334 document.MassUpdate.select_entire_list.value = 1;
2335 sugarListView.update_count(list_count, false);
2336 sugarListView.prototype.toggleSelected();
2339 sugarListView.prototype.check_all = function(form, field, value, pageTotal) {
2340 // count number of items
2342 $(document.MassUpdate.massall).each(function(){$(this).attr('checked', value);});
2343 if (document.MassUpdate.select_entire_list &&
2344 document.MassUpdate.select_entire_list.value == 1)
2346 sugarListView.prototype.toggleSelected();
2347 $(document.MassUpdate.massall).each(function(){$(this).attr('disabled', true);});
2351 $(document.MassUpdate.massall).each(function(){$(this).attr('disabled', false);});
2353 for (i = 0; i < form.elements.length; i++) {
2354 if(form.elements[i].name == field && !(form.elements[i].disabled == true && form.elements[i].checked == false)) {
2355 form.elements[i].disabled = false;
2357 if(form.elements[i].checked != value)
2359 form.elements[i].checked = value;
2361 sugarListView.prototype.updateUid(form.elements[i], form);
2366 sugarListView.update_count(pageTotal);
2368 sugarListView.update_count(count, true);
2370 sugarListView.update_count(-1 * count, true);
2372 sugarListView.prototype.toggleSelected();
2374 sugarListView.check_all = sugarListView.prototype.check_all;
2375 sugarListView.confirm_action = sugarListView.prototype.confirm_action;
2377 sugarListView.prototype.check_boxes = function() {
2378 var inputsCount = 0;
2379 var checkedCount = 0;
2380 var existing_onload = window.onload;
2381 var theForm = document.MassUpdate;
2382 inputs_array = theForm.elements;
2384 if(typeof theForm.uid.value != 'undefined' && theForm.uid.value != "") {
2385 checked_items = theForm.uid.value.split(",");
2386 if (theForm.select_entire_list.value == 1) {
2387 document.MassUpdate.massall.disabled = true;
2388 sugarListView.prototype.toggleSelected();
2389 $("a[name=selectall]:first").click();
2392 for(var wp = 0 ; wp < inputs_array.length; wp++) {
2393 if(inputs_array[wp].name == "mass[]") {
2395 if (theForm.select_entire_list.value == 1) {
2396 inputs_array[wp].checked = true;
2397 inputs_array[wp].disabled = true;
2401 for(i in checked_items) {
2402 if(inputs_array[wp].value == checked_items[i]) {
2404 inputs_array[wp].checked = true;
2405 //Bug#52748: Total # of checked items are calculated in back-end side
2406 //sugarListView.prototype.check_item(inputs_array[wp], document.MassUpdate);
2414 for(var wp = 0 ; wp < inputs_array.length; wp++) {
2415 if(inputs_array[wp].name == "mass[]") {
2416 inputs_array[wp].checked = false;
2417 inputs_array[wp].disabled = false;
2420 if (document.MassUpdate.massall) {
2421 document.MassUpdate.massall.checked = false;
2422 document.MassUpdate.massall.disabled = false;
2424 sugarListView.update_count(0)
2426 if(checkedCount > 0 && checkedCount == inputsCount)
2427 document.MassUpdate.massall.checked = true;
2432 * This function is used in Email Template Module's listview.
2433 * It will check whether the templates are used in Campaing->EmailMarketing.
2434 * If true, it will notify user.
2436 function check_used_email_templates() {
2437 var ids = document.MassUpdate.uid.value;
2439 success:function(r) {
2440 if(r.responseText != '') {
2441 if(!confirm(SUGAR.language.get('app_strings','NTC_TEMPLATES_IS_USED') + r.responseText)) {
2445 document.MassUpdate.submit();
2449 url = "index.php?module=EmailTemplates&action=CheckDeletable&from=ListView&to_pdf=1&records="+ids;
2450 YAHOO.util.Connect.asyncRequest('POST',url, call_back,null);
2454 sugarListView.prototype.send_mass_update = function(mode, no_record_txt, del) {
2455 formValid = check_form('MassUpdate');
2456 if(!formValid && !del) return false;
2459 if (document.MassUpdate.select_entire_list &&
2460 document.MassUpdate.select_entire_list.value == 1)
2465 var ar = new Array();
2469 for(var wp = 0; wp < document.MassUpdate.elements.length; wp++) {
2470 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)+'$');
2471 //when the uid is already in document.MassUpdate.uid.value, we should not add it to ar.
2472 if(typeof document.MassUpdate.elements[wp].name != 'undefined'
2473 && document.MassUpdate.elements[wp].name == 'mass[]'
2474 && document.MassUpdate.elements[wp].checked
2475 && !reg_for_existing_uid.test(document.MassUpdate.uid.value)) {
2476 ar.push(document.MassUpdate.elements[wp].value);
2479 if(document.MassUpdate.uid.value != '') document.MassUpdate.uid.value += ',';
2480 document.MassUpdate.uid.value += ar.join(',');
2481 if(document.MassUpdate.uid.value == '') {
2482 alert(no_record_txt);
2485 if(typeof(current_admin_id)!='undefined' && document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'Users' && (document.MassUpdate.is_admin.value!='' || document.MassUpdate.status.value!='')) {
2486 var reg_for_current_admin_id = new RegExp('^'+current_admin_id+'[\s]*,|,[\s]*'+current_admin_id+'[\s]*,|,[\s]*'+current_admin_id+'$|^'+current_admin_id+'$');
2487 if(reg_for_current_admin_id.test(document.MassUpdate.uid.value)) {
2488 //if current user is admin, we should not allow massupdate the user_type and status of himself
2489 alert(SUGAR.language.get('Users','LBL_LAST_ADMIN_NOTICE'));
2495 var entireInput = document.createElement('input');
2496 entireInput.name = 'entire';
2497 entireInput.type = 'hidden';
2498 entireInput.value = 'index';
2499 document.MassUpdate.appendChild(entireInput);
2500 //confirm(no_record_txt);
2501 if(document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'Users' && (document.MassUpdate.is_admin.value!='' || document.MassUpdate.status.value!='')) {
2502 alert(SUGAR.language.get('Users','LBL_LAST_ADMIN_NOTICE'));
2508 if(!sugarListView.confirm_action(del))
2512 var deleteInput = document.createElement('input');
2513 deleteInput.name = 'Delete';
2514 deleteInput.type = 'hidden';
2515 deleteInput.value = true;
2516 document.MassUpdate.appendChild(deleteInput);
2517 if(document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'EmailTemplates') {
2518 check_used_email_templates();
2524 document.MassUpdate.submit();
2529 sugarListView.prototype.clear_all = function() {
2530 document.MassUpdate.uid.value = '';
2531 document.MassUpdate.select_entire_list.value = 0;
2532 sugarListView.check_all(document.MassUpdate, 'mass[]', false);
2533 $(document.MassUpdate.massall).each(function(){
2534 $(this).attr('checked', false).attr('disabled', false);
2536 sugarListView.update_count(0);
2537 sugarListView.prototype.toggleSelected();
2540 sListView = new sugarListView();
2541 // -- end sugarListView class
2543 // format and unformat numbers
2544 function unformatNumber(n, num_grp_sep, dec_sep) {
2545 var x=unformatNumberNoParse(n, num_grp_sep, dec_sep);
2548 return parseFloat(x);
2553 function unformatNumberNoParse(n, num_grp_sep, dec_sep) {
2554 if(typeof num_grp_sep == 'undefined' || typeof dec_sep == 'undefined') return n;
2555 n = n ? n.toString() : '';
2558 if(num_grp_sep != '')
2560 num_grp_sep_re = new RegExp('\\'+num_grp_sep, 'g');
2561 n = n.replace(num_grp_sep_re, '');
2564 n = n.replace(dec_sep, '.');
2566 if(typeof CurrencySymbols != 'undefined') {
2567 // Need to strip out the currency symbols from the start.
2568 for ( var idx in CurrencySymbols ) {
2569 n = n.replace(CurrencySymbols[idx], '');
2577 // round parameter can be negative for decimal, precision has to be postive
2578 function formatNumber(n, num_grp_sep, dec_sep, round, precision) {
2579 if(typeof num_grp_sep == 'undefined' || typeof dec_sep == 'undefined') return n;
2580 n = n ? n.toString() : '';
2581 if(n.split) n = n.split('.');
2584 if(n.length > 2) return n.join('.'); // that's not a num!
2586 if(typeof round != 'undefined') {
2587 if(round > 0 && n.length > 1) { // round to decimal
2588 n[1] = parseFloat('0.' + n[1]);
2589 n[1] = Math.round(n[1] * Math.pow(10, round)) / Math.pow(10, round);
2590 n[1] = n[1].toString().split('.')[1];
2592 if(round <= 0) { // round to whole number
2593 n[0] = Math.round(parseInt(n[0],10) * Math.pow(10, round)) / Math.pow(10, round);
2598 if(typeof precision != 'undefined' && precision >= 0) {
2599 if(n.length > 1 && typeof n[1] != 'undefined') n[1] = n[1].substring(0, precision); // cut off precision
2601 if(n[1].length < precision) {
2602 for(var wp = n[1].length; wp < precision; wp++) n[1] += '0';
2606 regex = /(\d+)(\d{3})/;
2607 while(num_grp_sep != '' && regex.test(n[0])) n[0] = n[0].toString().replace(regex, '$1' + num_grp_sep + '$2');
2608 return n[0] + (n.length > 1 && n[1] != '' ? dec_sep + n[1] : '');
2611 // --- begin ajax status class
2612 SUGAR.ajaxStatusClass = function() {};
2613 SUGAR.ajaxStatusClass.prototype.statusDiv = null;
2614 SUGAR.ajaxStatusClass.prototype.oldOnScroll = null;
2615 SUGAR.ajaxStatusClass.prototype.shown = false; // state of the status window
2617 // reposition the status div, top and centered
2618 SUGAR.ajaxStatusClass.prototype.positionStatus = function() {
2619 //this.statusDiv.style.top = document.body.scrollTop + 8 + 'px';
2620 statusDivRegion = YAHOO.util.Dom.getRegion(this.statusDiv);
2621 statusDivWidth = statusDivRegion.right - statusDivRegion.left;
2622 this.statusDiv.style.left = YAHOO.util.Dom.getViewportWidth() / 2 - statusDivWidth / 2 + 'px';
2625 // private func, create the status div
2626 SUGAR.ajaxStatusClass.prototype.createStatus = function(text) {
2627 statusDiv = document.createElement('div');
2628 statusDiv.className = 'dataLabel';
2629 statusDiv.id = 'ajaxStatusDiv';
2630 document.body.appendChild(statusDiv);
2631 this.statusDiv = document.getElementById('ajaxStatusDiv');
2634 // public - show the status div with text
2635 SUGAR.ajaxStatusClass.prototype.showStatus = function(text) {
2636 if(!this.statusDiv) {
2637 this.createStatus(text);
2640 this.statusDiv.style.display = '';
2642 this.statusDiv.innerHTML = ' <b>' + text + '</b> ';
2643 this.positionStatus();
2646 this.statusDiv.style.display = '';
2647 if(window.onscroll) this.oldOnScroll = window.onscroll; // save onScroll
2648 window.onscroll = this.positionStatus;
2653 SUGAR.ajaxStatusClass.prototype.hideStatus = function(text) {
2654 if(!this.shown) return;
2656 if(this.oldOnScroll) window.onscroll = this.oldOnScroll;
2657 else window.onscroll = '';
2658 this.statusDiv.style.display = 'none';
2661 SUGAR.ajaxStatusClass.prototype.flashStatus = function(text, time){
2662 this.showStatus(text);
2663 window.setTimeout('ajaxStatus.hideStatus();', time);
2667 var ajaxStatus = new SUGAR.ajaxStatusClass();
2668 // --- end ajax status class
2671 * Unified Search Advanced - for global search
2673 SUGAR.unifiedSearchAdvanced = function() {
2683 SUGAR.unifiedSearchAdvanced.usa_div = document.getElementById('unified_search_advanced_div');
2684 SUGAR.unifiedSearchAdvanced.usa_img = document.getElementById('unified_search_advanced_img');
2686 if(!SUGAR.unifiedSearchAdvanced.usa_div || !SUGAR.unifiedSearchAdvanced.usa_img) return;
2687 var attributes = { height: { to: 300 } };
2688 SUGAR.unifiedSearchAdvanced.anim_open = new YAHOO.util.Anim('unified_search_advanced_div', attributes );
2689 SUGAR.unifiedSearchAdvanced.anim_open.duration = 0.75;
2690 SUGAR.unifiedSearchAdvanced.anim_close = new YAHOO.util.Anim('unified_search_advanced_div', { height: {to: 0} } );
2691 SUGAR.unifiedSearchAdvanced.anim_close.duration = 0.75;
2692 //SUGAR.unifiedSearchAdvanced.anim_close.onComplete.subscribe(function() {SUGAR.unifiedSearchAdvanced.usa_div.style.display = 'none'});
2694 SUGAR.unifiedSearchAdvanced.usa_img._x = YAHOO.util.Dom.getX(SUGAR.unifiedSearchAdvanced.usa_img);
2695 SUGAR.unifiedSearchAdvanced.usa_img._y = YAHOO.util.Dom.getY(SUGAR.unifiedSearchAdvanced.usa_img);
2698 SUGAR.unifiedSearchAdvanced.usa_open = false;
2699 SUGAR.unifiedSearchAdvanced.usa_content = null;
2701 YAHOO.util.Event.addListener('unified_search_advanced_img', 'click', SUGAR.unifiedSearchAdvanced.get_content);
2704 get_content: function(e)
2706 query_string = trim(document.getElementById('query_string').value);
2707 if(query_string != '')
2709 window.location.href = 'index.php?module=Home&action=UnifiedSearch&query_string=' + query_string;
2711 window.location.href = 'index.php?module=Home&action=UnifiedSearch&form_only=true';
2715 animate: function(data) {
2716 ajaxStatus.hideStatus();
2719 SUGAR.unifiedSearchAdvanced.usa_content = data.responseText;
2720 SUGAR.unifiedSearchAdvanced.usa_div.innerHTML = SUGAR.unifiedSearchAdvanced.usa_content;
2722 if(SUGAR.unifiedSearchAdvanced.usa_open) {
2723 document.UnifiedSearch.advanced.value = 'false';
2724 SUGAR.unifiedSearchAdvanced.anim_close.animate();
2727 document.UnifiedSearch.advanced.value = 'true';
2728 SUGAR.unifiedSearchAdvanced.usa_div.style.display = '';
2729 YAHOO.util.Dom.setX(SUGAR.unifiedSearchAdvanced.usa_div, SUGAR.unifiedSearchAdvanced.usa_img._x - 90);
2730 YAHOO.util.Dom.setY(SUGAR.unifiedSearchAdvanced.usa_div, SUGAR.unifiedSearchAdvanced.usa_img._y + 15);
2731 SUGAR.unifiedSearchAdvanced.anim_open.animate();
2733 SUGAR.unifiedSearchAdvanced.usa_open = !SUGAR.unifiedSearchAdvanced.usa_open;
2738 checkUsaAdvanced: function() {
2739 if(document.UnifiedSearch.advanced.value == 'true') {
2740 document.UnifiedSearchAdvanced.query_string.value = document.UnifiedSearch.query_string.value;
2741 document.UnifiedSearchAdvanced.submit();
2748 if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.unifiedSearchAdvanced.init);
2753 * Toggles the header
2755 toggleHeader : function() {
2756 var h = document.getElementById('header');
2760 if(h.style.display == 'none') {
2761 h.style.display = '';
2763 h.style.display = 'none';
2767 alert(SUGAR.language.get("app_strings", "ERR_NO_HEADER_ID"));
2774 * General Sugar Utils
2776 SUGAR.util = function () {
2777 var additionalDetailsCache;
2778 var additionalDetailsCalls;
2779 var additionalDetailsRpcCall;
2782 getAndRemove : function (el) {
2783 if (YAHOO && YAHOO.util && YAHOO.util.Dom)
2784 el = YAHOO.util.Dom.get(el);
2785 else if (typeof (el) == "string")
2786 el = document.getElementById(el);
2787 if (el && el.parentNode)
2788 el.parentNode.removeChild(el);
2792 paramsToUrl : function (params) {
2795 url += i + "=" + params[i] + "&";
2799 evalScript:function(text){
2801 var waitUntilLoaded = function(){
2802 SUGAR.evalScript_waitCount--;
2803 if (SUGAR.evalScript_waitCount == 0) {
2804 var headElem = document.getElementsByTagName('head')[0];
2805 for ( var i = 0; i < SUGAR.evalScript_evalElem.length; i++) {
2806 var tmpElem = document.createElement('script');
2807 tmpElem.type = 'text/javascript';
2808 tmpElem.text = SUGAR.evalScript_evalElem[i];
2809 headElem.appendChild(tmpElem);
2814 var tmpElem = document.createElement('div');
2815 tmpElem.innerHTML = text;
2816 var results = tmpElem.getElementsByTagName('script');
2817 if (results == null) {
2818 // No scripts found, bail out
2822 var headElem = document.getElementsByTagName('head')[0];
2824 SUGAR.evalScript_waitCount = 0;
2825 SUGAR.evalScript_evalElem = new Array();
2826 for (var i = 0; i < results.length; i++) {
2827 if (typeof(results[i]) != 'object') {
2830 tmpElem = document.createElement('script');
2831 tmpElem.type = 'text/javascript';
2832 if (results[i].src != null && results[i].src != '') {
2833 tmpElem.src = results[i].src;
2835 // Need to defer execution of these scripts until the
2836 // required javascript files are fully loaded
2837 SUGAR.evalScript_evalElem[SUGAR.evalScript_evalElem.length] = results[i].text;
2840 tmpElem.addEventListener('load', waitUntilLoaded);
2841 SUGAR.evalScript_waitCount++;
2842 headElem.appendChild(tmpElem);
2844 // Add some code to handle pages without any external scripts
2845 SUGAR.evalScript_waitCount++;
2848 // Don't try and process things the IE way
2852 var objRegex = /<\s*script([^>]*)>((.|\s|\v|\0)*?)<\s*\/script\s*>/igm;
2854 var result = objRegex.exec(text);
2855 while(result && result.index > lastIndex){
2856 lastIndex = result.index
2858 var script = document.createElement('script');
2859 script.type= 'text/javascript';
2860 if(result[1].indexOf("src=") > -1){
2861 var srcRegex = /.*src=['"]([a-zA-Z0-9_\-\&\/\.\?=:-]*)['"].*/igm;
2862 var srcResult = result[1].replace(srcRegex, '$1');
2863 script.src = srcResult;
2865 script.text = result[2];
2867 document.body.appendChild(script);
2870 if(typeof(console) != "undefined" && typeof(console.log) == "function")
2872 console.log("error adding script");
2874 console.log(result);
2877 result = objRegex.exec(text);
2881 * Gets the sidebar object
2882 * @return object pointer to the sidebar element
2884 getLeftColObj: function() {
2885 leftColObj = document.getElementById('leftCol');
2886 while(leftColObj.nodeName != 'TABLE') {
2887 leftColObj = leftColObj.firstChild;
2889 leftColTable = leftColObj;
2890 leftColTd = leftColTable.getElementsByTagName('td')[0];
2891 leftColTdRegion = YAHOO.util.Dom.getRegion(leftColTd);
2892 leftColTd.style.width = (leftColTdRegion.right - leftColTdRegion.left) + 'px';
2897 * Fills the shortcut menu placeholders w/ actual content
2898 * Call this on load event
2900 * @param shortcutContent Array array of content to fill in
2902 fillShortcuts: function(e, shortcutContent) {
2905 // don't do this if leftCol isn't available
2906 if (document.getElementById('leftCol') == undefined) { return; }
2908 spans = document.getElementById('leftCol').getElementsByTagName('span');
2909 hideCol = document.getElementById('HideMenu').getElementsByTagName('span');
2910 w = spans.length + 1;
2912 spans[w] = hideCol[i];
2915 for(je in shortcutContent) {
2917 if(typeof spans[wp].innerHTML != 'undefined' && spans[wp].innerHTML == ('wp_shortcut_fill_' + je)) {
2918 if(typeof spans[wp].parentNode.parentNode == 'object') {
2919 if(typeof spans[wp].parentNode.parentNode.onclick != 'undefined') {
2920 spans[wp].parentNode.parentNode.onclick = null;
2922 // If the wp_shortcut span is contained by an A tag, replace the A with a DIV.
2923 if(spans[wp].parentNode.tagName == 'A' && !isIE) {
2924 var newDiv = document.createElement('DIV');
2925 var parentAnchor = spans[wp].parentNode;
2927 spans[wp].parentNode.parentNode.style.display = 'none';
2929 // Copy styles over to the new container div
2930 if(window.getComputedStyle) {
2931 var parentStyle = window.getComputedStyle(parentAnchor, '');
2932 for(var styleName in parentStyle) {
2933 if(typeof parentStyle[styleName] != 'function'
2934 && styleName != 'display'
2935 && styleName != 'borderWidth'
2936 && styleName != 'visibility') {
2938 newDiv.style[styleName] = parentStyle[styleName];
2940 // Catches .length and .parentRule, and others
2946 // Replace the A with the DIV
2947 newDiv.appendChild(spans[wp]);
2948 parentAnchor.parentNode.replaceChild(newDiv, parentAnchor);
2950 spans[wp].parentNode.parentNode.style.display = '';
2953 spans[wp].innerHTML = shortcutContent[je]; // fill w/ content
2954 if(spans[wp].style) spans[wp].style.display = '';
2960 * Make an AJAX request.
2962 * @param url string resource to load
2963 * @param theDiv string id of element to insert loaded data into
2964 * @param postForm string if set, a POST request will be made to resource specified by url using the form named by postForm
2965 * @param callback string name of function to invoke after HTTP response is recieved
2966 * @param callbackParam any parameter to pass to callback when invoked
2967 * @param appendMode bool if true, HTTP response will be appended to the contents of theDiv, or else contents will be overriten.
2969 retrieveAndFill: function(url, theDiv, postForm, callback, callbackParam, appendMode) {
2970 if(typeof theDiv == 'string') {
2972 theDiv = document.getElementById(theDiv);
2979 var success = function(data) {
2980 if (typeof theDiv != 'undefined' && theDiv != null)
2983 if (typeof appendMode != 'undefined' && appendMode)
2985 theDiv.innerHTML += data.responseText;
2989 theDiv.innerHTML = data.responseText;
2996 if (typeof callback != 'undefined' && callback != null) callback(callbackParam);
2999 if(typeof postForm == 'undefined' || postForm == null) {
3000 var cObj = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
3003 YAHOO.util.Connect.setForm(postForm);
3004 var cObj = YAHOO.util.Connect.asyncRequest('POST', url, {success: success, failure: success});
3007 checkMaxLength: function() { // modified from http://www.quirksmode.org/dom/maxlength.html
3008 var maxLength = this.getAttribute('maxlength');
3009 var currentLength = this.value.length;
3010 if (currentLength > maxLength) {
3011 this.value = this.value.substring(0, maxLength);
3016 * Adds maxlength attribute to textareas
3018 setMaxLength: function() { // modified from http://www.quirksmode.org/dom/maxlength.html
3019 var x = document.getElementsByTagName('textarea');
3020 for (var i=0;i<x.length;i++) {
3021 if (x[i].getAttribute('maxlength')) {
3022 x[i].onkeyup = x[i].onchange = SUGAR.util.checkMaxLength;
3029 * Renders Query UI Help Dialog
3031 showHelpTips: function(el,helpText,myPos,atPos,id) {
3032 if(myPos == undefined || myPos == "") {
3035 if(atPos == undefined || atPos == "") {
3036 atPos = "right top";
3039 var pos = $(el).offset(),
3040 ofWidth = $(el).width(),
3041 elmId = id || 'helpTip' + pos.left + '_' + ofWidth,
3042 $dialog = elmId ? ( $("#"+elmId).length > 0 ? $("#"+elmId) : $('<div></div>').attr("id", elmId) ) : $('<div></div>');
3043 $dialog.html(helpText)
3046 title: SUGAR.language.get('app_strings', 'LBL_HELP'),
3055 var width = $dialog.dialog( "option", "width" );
3057 if((pos.left + ofWidth) - 40 < width) {
3058 $dialog.dialog("option","position",{my: 'left top',at: 'right top',of: $(el)}) ;
3060 $dialog.dialog('open');
3061 $(".ui-dialog").appendTo("#content");
3065 getStaticAdditionalDetails: function(el, body, caption, show_buttons) {
3066 if(typeof show_buttons == "undefined") {
3067 show_buttons = false;
3070 $(".ui-dialog").find(".open").dialog("close");
3072 var $dialog = $('<div class="open"></div>')
3086 $(".ui-dialog").find('.ui-dialog-titlebar-close').css("display","none");
3087 $(".ui-dialog").find('.ui-dialog-title').css("width","100%");
3091 var width = $dialog.dialog( "option", "width" );
3092 var pos = $(el).offset();
3093 var ofWidth = $(el).width();
3095 if((pos.left + ofWidth) - 40 < width) {
3096 $dialog.dialog("option","position",{my: 'left top',at: 'right top',of: $(el)}) ;
3099 $dialog.dialog('open');
3100 $(".ui-dialog").appendTo("#content");
3104 closeStaticAdditionalDetails: function() {
3105 $(".ui-dialog").find(".open").dialog("close");
3108 * Retrieves additional details dynamically
3110 getAdditionalDetails: function(bean, id, spanId, show_buttons) {
3111 if(typeof show_buttons == "undefined")
3112 show_buttons = false;
3113 var el = '#'+spanId;
3115 oReturn = function(body, caption, width, theme) {
3117 $(".ui-dialog").find(".open").dialog("close");
3119 var $dialog = $('<div class="open"></div>')
3132 $(".ui-dialog").find('.ui-dialog-titlebar-close').css("display","none");
3133 $(".ui-dialog").find('.ui-dialog-title').css("width","100%");
3136 var width = $dialog.dialog( "option", "width" );
3137 var pos = $(el).offset();
3138 var ofWidth = $(el).width();
3140 if((pos.left + ofWidth) - 40 < width) {
3141 $dialog.dialog("option","position",{my: 'left top',at: 'right top',of: $(el)}) ;
3144 $dialog.dialog('open');
3145 $(".ui-dialog").appendTo("#content");
3148 success = function(data) {
3149 eval(data.responseText);
3151 SUGAR.util.additionalDetailsCache[id] = new Array();
3152 SUGAR.util.additionalDetailsCache[id]['body'] = result['body'];
3153 SUGAR.util.additionalDetailsCache[id]['caption'] = result['caption'];
3154 SUGAR.util.additionalDetailsCache[id]['width'] = result['width'];
3155 SUGAR.util.additionalDetailsCache[id]['theme'] = result['theme'];
3156 ajaxStatus.hideStatus();
3157 return oReturn(SUGAR.util.additionalDetailsCache[id]['body'], SUGAR.util.additionalDetailsCache[id]['caption'], SUGAR.util.additionalDetailsCache[id]['width'], SUGAR.util.additionalDetailsCache[id]['theme']);
3160 if(typeof SUGAR.util.additionalDetailsCache[id] != 'undefined')
3161 return oReturn(SUGAR.util.additionalDetailsCache[id]['body'], SUGAR.util.additionalDetailsCache[id]['caption'], SUGAR.util.additionalDetailsCache[id]['width'], SUGAR.util.additionalDetailsCache[id]['theme']);
3163 if(typeof SUGAR.util.additionalDetailsCalls[id] != 'undefined') // call already in progress
3165 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_LOADING'));
3166 url = 'index.php?to_pdf=1&module=Home&action=AdditionalDetailsRetrieve&bean=' + bean + '&id=' + id;
3168 url += '&show_buttons=true';
3169 SUGAR.util.additionalDetailsCalls[id] = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
3173 SUGAR.util.additionalDetailsRpcCall = window.setTimeout('go()', 250);
3175 clearAdditionalDetailsCall: function() {
3176 if(typeof SUGAR.util.additionalDetailsRpcCall == 'number') window.clearTimeout(SUGAR.util.additionalDetailsRpcCall);
3179 * A function that extends functionality from parent to child.
3181 extend : function(subc, superc, overrides) {
3182 subc.prototype = new superc; // set the superclass
3185 for (var i in overrides) subc.prototype[i] = overrides[i];
3188 hrefURL : function(url) {
3190 // IE needs special treatment since otherwise it would not pass Referer
3191 var trampoline = document.createElement('a');
3192 trampoline.href = url;
3193 document.body.appendChild(trampoline);
3195 document.body.removeChild(trampoline);
3197 document.location.href = url;
3201 openWindow : function(URL, windowName, windowFeatures) {
3203 // IE needs special treatment since otherwise it would not pass Referer
3204 win = window.open('', windowName, windowFeatures);
3205 var trampoline = document.createElement('a');
3206 trampoline.href = URL;
3207 trampoline.target = windowName;
3208 document.body.appendChild(trampoline);
3210 document.body.removeChild(trampoline);
3212 win = window.open(URL, windowName, windowFeatures);
3216 //Reset the scroll on the window
3221 //Based on YUI onAvailible, but will use any boolean function instead of an ID
3222 doWhen : function(condition, fn, params, scope)
3224 this._doWhenStack.push({
3228 overrideContext: scope
3231 this._doWhenretryCount = 50;
3232 this._startDoWhenInterval();
3235 _startDoWhenInterval : function(){
3236 if (!this._doWhenInterval) {
3237 this._doWhenInterval = YAHOO.lang.later(50, this, this._doWhenCheck, null, true);
3241 _doWhenInterval : false,
3242 _doWhenCheck : function() {
3243 if (this._doWhenStack.length === 0) {
3244 this._doWhenretryCount = 0;
3245 if (this._doWhenInterval) {
3246 // clearInterval(this._interval);
3247 this._doWhenInterval.cancel();
3248 this._doWhenInterval = null;
3253 if (this._doWhenLocked) {
3258 // Hold off if DOMReady has not fired and check current
3259 // readyState to protect against the IE operation aborted
3261 if (!YAHOO.util.Event.DOMReady) {
3262 this._startDoWhenInterval();
3267 this._doWhenLocked = true;
3270 // keep trying until after the page is loaded. We need to
3271 // check the page load state prior to trying to bind the
3272 // elements so that we can be certain all elements have been
3273 // tested appropriately
3274 var tryAgain = YAHOO.util.Event.DOMReady;
3276 tryAgain = (this._doWhenretryCount > 0 && this._doWhenStack.length > 0);
3282 var executeItem = function (context, item) {
3283 if (item.overrideContext) {
3284 if (item.overrideContext === true) {
3287 context = item.overrideContext;
3291 item.fn.call(context, item.obj);
3295 var i, len, item, test;
3297 // onAvailable onContentReady
3298 for (i=0, len=this._doWhenStack.length; i<len; i=i+1) {
3299 item = this._doWhenStack[i];
3302 if ((typeof(test) == "string" && eval(test)) || (typeof(test) == "function" && test())) {
3303 executeItem(this, item);
3304 this._doWhenStack[i] = null;
3307 notAvail.push(item);
3312 this._doWhenretryCount--;
3315 for (i=this._doWhenStack.length-1; i>-1; i--) {
3316 item = this._doWhenStack[i];
3317 if (!item || !item.check) {
3318 this._doWhenStack.splice(i, 1);
3321 this._startDoWhenInterval();
3323 if (this._doWhenInterval) {
3324 // clearInterval(this._interval);
3325 this._doWhenInterval.cancel();
3326 this._doWhenInterval = null;
3329 this._doWhenLocked = false;
3331 buildAccessKeyLabels : function() {
3332 if (typeof(Y.env.ua) !== 'undefined'){
3334 browserOS = Y.env.ua['os'];
3335 isIE = Y.env.ua['ie'];
3336 isCR = Y.env.ua['chrome'];
3337 isFF = Y.env.ua['gecko'];
3338 isWK = Y.env.ua['webkit'];
3339 isOP = Y.env.ua['opera'];
3342 //first determine the OS
3343 if(browserOS=='macintosh'){
3344 //we got a mac, lets use the mac specific commands while we check the browser
3346 //IE on a Mac? Not possible, but let's assign alt anyways for completions sake
3347 controlKey = 'Alt+';
3349 //Chrome or safari on a mac
3350 controlKey = 'Ctrl+Opt+';
3353 controlKey = 'Shift+Esc: ';
3355 //default FF and everything else on a mac
3356 controlKey = 'Ctrl+';
3359 //this is not a mac so let's use the windows/unix commands while we check the browser
3361 //FF on windows/unix
3362 controlKey = 'Alt+Shift+';
3364 //Opera on windows/unix
3365 controlKey = 'Shift+Esc: ';
3367 //this is the default for safari, IE and Chrome
3368 //if this is webkit and is NOT google, then we are most likely looking at Safari
3369 controlKey = 'Alt+';
3374 //now lets retrieve all elements of type input
3375 allButtons = document.getElementsByTagName('input');
3376 //iterate through list and modify title if the accesskey is not empty
3377 for(i=0;i<allButtons.length;i++){
3378 if(allButtons[i].getAttribute('accesskey') && allButtons[i].getAttribute('type') && allButtons[i].getAttribute('type')=='button'){
3379 allButtons[i].setAttribute('title',allButtons[i].getAttribute('title')+' ['+controlKey+allButtons[i].getAttribute('accesskey')+']');
3382 //now change the text in the help div
3383 $("#shortcuts_dialog").html(function(i, text) {
3384 return text.replace(/Alt\+/g,controlKey);
3386 }// end if (typeof(Y.env.ua) !== 'undefined')
3387 }//end buildAccessKeyLabels()
3390 SUGAR.util.additionalDetailsCache = new Array();
3391 SUGAR.util.additionalDetailsCalls = new Array();
3392 if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.util.setMaxLength); // allow textareas to obey maxlength attrib
3394 SUGAR.savedViews = function() {
3395 var selectedOrderBy;
3396 var selectedSortOrder;
3399 var columnsMeta; // meta data for the display columns
3402 setChooser: function() {
3404 var displayColumnsDef = new Array();
3405 var hideTabsDef = new Array();
3407 var left_td = document.getElementById('display_tabs_td');
3408 if(typeof left_td == 'undefined' || left_td == null) return; // abort!
3409 var right_td = document.getElementById('hide_tabs_td');
3411 var displayTabs = left_td.getElementsByTagName('select')[0];
3412 var hideTabs = right_td.getElementsByTagName('select')[0];
3414 for(i = 0; i < displayTabs.options.length; i++) {
3415 displayColumnsDef.push(displayTabs.options[i].value);
3418 if(typeof hideTabs != 'undefined') {
3419 for(i = 0; i < hideTabs.options.length; i++) {
3420 hideTabsDef.push(hideTabs.options[i].value);
3423 if (!SUGAR.savedViews.clearColumns)
3424 document.getElementById('displayColumnsDef').value = displayColumnsDef.join('|');
3425 document.getElementById('hideTabsDef').value = hideTabsDef.join('|');
3428 select: function(saved_search_select) {
3429 for(var wp = 0; wp < document.search_form.saved_search_select.options.length; wp++) {
3430 if(typeof document.search_form.saved_search_select.options[wp].value != 'undefined' &&
3431 document.search_form.saved_search_select.options[wp].value == saved_search_select) {
3432 document.search_form.saved_search_select.selectedIndex = wp;
3433 document.search_form.ss_delete.style.display = '';
3434 document.search_form.ss_update.style.display = '';
3438 saved_search_action: function(action, delete_lang) {
3439 if(action == 'delete') {
3440 if(!confirm(delete_lang)) return;
3442 if(action == 'save') {
3443 if(document.search_form.saved_search_name.value.replace(/^\s*|\s*$/g, '') == '') {
3444 alert(SUGAR.language.get('app_strings', 'LBL_SAVED_SEARCH_ERROR'));
3449 // This check is needed for the Activities module (Calls/Meetings/Tasks).
3450 if (document.search_form.saved_search_action)
3452 document.search_form.saved_search_action.value = action;
3453 document.search_form.search_module.value = document.search_form.module.value;
3454 document.search_form.module.value = 'SavedSearch';
3455 // Bug 31922 - Make sure to specify that we want to hit the index view here of
3456 // the SavedSearch module, since the ListView doesn't have the logic to save the
3457 // search and redirect back
3458 document.search_form.action.value = 'index';
3460 SUGAR.ajaxUI.submitForm(document.search_form);
3462 shortcut_select: function(selectBox, module) {
3464 selecturl = 'index.php?module=SavedSearch&search_module=' + module + '&action=index&saved_search_select=' + selectBox.options[selectBox.selectedIndex].value
3465 //add searchFormTab to url if it is available. This determines what tab to render
3466 if(typeof(document.getElementById('searchFormTab'))!='undefined'){
3467 selecturl = selecturl + '&searchFormTab=' + document.search_form.searchFormTab.value;
3469 //add showSSDIV to url if it is available. This determines whether saved search sub form should
3470 //be rendered open or not
3471 if(document.getElementById('showSSDIV') && typeof(document.getElementById('showSSDIV') !='undefined')){
3472 selecturl = selecturl + '&showSSDIV='+document.getElementById('showSSDIV').value;
3474 //use created url to navigate
3475 document.location.href = selecturl;
3477 handleForm: function() {
3478 SUGAR.tabChooser.movementCallback = function(left_side, right_side) {
3479 while(document.getElementById('orderBySelect').childNodes.length != 0) { // clear out order by options
3480 document.getElementById('orderBySelect').removeChild(document.getElementById('orderBySelect').lastChild);
3483 var selectedIndex = 0;
3484 var nodeCount = -1; // need this because the counter i also includes "undefined" nodes
3485 // which was breaking Calls and Meetings
3487 for(i in left_side.childNodes) { // fill in order by options
3488 if(typeof left_side.childNodes[i].nodeName != 'undefined' &&
3489 left_side.childNodes[i].nodeName.toLowerCase() == 'option' &&
3490 typeof SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value] != 'undefined' && // check if column is sortable
3491 typeof SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value]['sortable'] == 'undefined' &&
3492 SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value]['sortable'] != false) {
3494 optionNode = document.createElement('option');
3495 optionNode.value = left_side.childNodes[i].value;
3496 optionNode.innerHTML = left_side.childNodes[i].innerHTML;
3497 document.getElementById('orderBySelect').appendChild(optionNode);
3498 if(optionNode.value == SUGAR.savedViews.selectedOrderBy)
3499 selectedIndex = nodeCount;
3502 // Firefox needs this to be set after all the option nodes are created.
3503 document.getElementById('orderBySelect').selectedIndex = selectedIndex;
3505 SUGAR.tabChooser.movementCallback(document.getElementById('display_tabs_td').getElementsByTagName('select')[0]);
3507 // This check is needed for the Activities module (Calls/Meetings/Tasks).
3508 if (document.search_form.orderBy)
3509 document.search_form.orderBy.options.value = SUGAR.savedViews.selectedOrderBy;
3512 if(SUGAR.savedViews.selectedSortOrder == 'DESC') document.getElementById('sort_order_desc_radio').checked = true;
3513 else document.getElementById('sort_order_asc_radio').checked = true;
3518 SUGAR.searchForm = function() {
3521 // searchForm tab selector util
3522 searchFormSelect: function(view, previousView) {
3523 var module = view.split('|')[0];
3524 var theView = view.split('|')[1];
3526 var handleDisplay = function() { // hide other divs
3527 document.search_form.searchFormTab.value = theView;
3528 patt = module+"(.*)SearchForm$";
3529 divId=document.search_form.getElementsByTagName('div');
3530 // Hide all the search forms and retrive the name of the previous search tab (useful for the first load because previousView is empty)
3531 for (i=0;i<divId.length;i++){
3532 if(divId[i].id.match(module)==module){
3533 if(divId[i].id.match('SearchForm')=='SearchForm'){
3534 if(document.getElementById(divId[i].id).style.display == ''){
3535 previousTab=divId[i].id.match(patt)[1];
3537 document.getElementById(divId[i].id).style.display = 'none';
3541 // show the good search form.
3542 document.getElementById(module + theView + 'SearchForm').style.display = '';
3543 //if its not the first tab show there is a previous tab.
3545 thepreviousView=previousView.split('|')[1];
3548 thepreviousView=previousTab;
3550 thepreviousView=thepreviousView.replace(/_search/, "");
3551 // Process to retrieve the completed field from one tab to an other.
3552 for(num in document.search_form.elements) {
3553 if(document.search_form.elements[num]) {
3554 el = document.search_form.elements[num];
3555 pattern="^(.*)_"+thepreviousView+"$";
3556 if(typeof el.type != 'undefined' && typeof el.name != 'undefined' && el.name.match(pattern)) {
3557 advanced_input_name = el.name.match(pattern)[1]; // strip
3558 advanced_input_name = advanced_input_name+"_"+theView.replace(/_search/, "");
3559 if(typeof document.search_form[advanced_input_name] != 'undefined') // if advanced input of same name exists
3560 SUGAR.searchForm.copyElement(advanced_input_name, el);
3566 // if tab is not cached
3567 if(document.getElementById(module + theView + 'SearchForm').innerHTML == '') {
3568 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_LOADING'));
3569 var success = function(data) {
3570 document.getElementById(module + theView + 'SearchForm').innerHTML = data.responseText;
3572 SUGAR.util.evalScript(data.responseText);
3573 // pass script variables to global scope
3574 if(theView == 'saved_views') {
3575 if(typeof columnsMeta != 'undefined') SUGAR.savedViews.columnsMeta = columnsMeta;
3576 if(typeof selectedOrderBy != 'undefined') SUGAR.savedViews.selectedOrderBy = selectedOrderBy;
3577 if(typeof selectedSortOrder != 'undefined') SUGAR.savedViews.selectedSortOrder = selectedSortOrder;
3582 ajaxStatus.hideStatus();
3584 url = 'index.php?module=' + module + '&action=index&search_form_only=true&to_pdf=true&search_form_view=' + theView;
3586 //check to see if tpl has been specified. If so then pass location through url string
3588 if(document.getElementById('search_tpl') !=null && typeof(document.getElementById('search_tpl')) != 'undefined'){
3589 tpl = document.getElementById('search_tpl').value;
3590 if(tpl != ''){url += '&search_tpl='+tpl;}
3593 if(theView == 'saved_views') // handle the tab chooser
3594 url += '&displayColumns=' + SUGAR.savedViews.displayColumns + '&hideTabs=' + SUGAR.savedViews.hideTabs + '&orderBy=' + SUGAR.savedViews.selectedOrderBy + '&sortOrder=' + SUGAR.savedViews.selectedSortOrder;
3596 var cObj = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
3598 else { // that form already retrieved
3603 // copies one input to another
3604 copyElement: function(inputName, copyFromElement) {
3605 switch(copyFromElement.type) {
3608 document.search_form[inputName].value = copyFromElement.value;
3612 // This function is here to clear the form, instead of "resubmitting it
3613 clear_form: function(form, skipElementNames) {
3614 var elemList = form.elements;
3618 for( var i = 0; i < elemList.length ; i++ ) {
3620 if ( typeof(elem.type) == 'undefined' ) {
3624 if ( typeof(elem.type) != 'undefined' && typeof(skipElementNames) != 'undefined'
3625 && SUGAR.util.arrayIndexOf(skipElementNames, elem.name) != -1 )
3630 elemType = elem.type.toLowerCase();
3632 if ( elemType == 'text' || elemType == 'textarea' || elemType == 'password' ) {
3635 else if ( elemType == 'select' || elemType == 'select-one' || elemType == 'select-multiple' ) {
3636 // We have, what I hope, is a select box, time to unselect all options
3637 var optionList = elem.options;
3638 for ( var ii = 0 ; ii < optionList.length ; ii++ ) {
3639 optionList[ii].selected = false;
3642 else if ( elemType == 'radio' || elemType == 'checkbox' ) {
3643 elem.checked = false;
3644 elem.selected = false;
3646 else if ( elemType == 'hidden' ) {
3647 // We only want to reset the hidden values that link to the select boxes.
3648 // _c custom field kludge added to fix Bug 41384
3649 if ( ( elem.name.length > 3 && elem.name.substring(elem.name.length-3) == '_id' )
3650 || ((elem.name.length > 9) && (elem.name.substring(elem.name.length - 9) == '_id_basic'))
3651 || ( elem.name.length > 12 && elem.name.substring(elem.name.length-12) == '_id_advanced' )
3652 || ( elem.name.length > 2 && elem.name.substring(elem.name.length-2) == '_c' )
3653 || ((elem.name.length > 8) && (elem.name.substring(elem.name.length - 8) == '_c_basic'))
3654 || ( elem.name.length > 11 && elem.name.substring(elem.name.length-11) == '_c_advanced' ) )
3660 SUGAR.savedViews.clearColumns = true;
3664 // Code for the column/tab chooser used on homepage and in admin section
3665 SUGAR.tabChooser = function () {
3666 var object_refs = new Array();
3668 /* Describe certain transfers as invalid */
3671 movementCallback: function(left_side, right_side) {},
3672 orderCallback: function(left_side, right_side) {},
3674 freezeOptions: function(left_name, right_name, target) {
3675 if(!SUGAR.tabChooser.frozenOptions) { SUGAR.tabChooser.frozenOptions = []; }
3676 if(!SUGAR.tabChooser.frozenOptions[left_name]) { SUGAR.tabChooser.frozenOptions[left_name] = []; }
3677 if(!SUGAR.tabChooser.frozenOptions[left_name][right_name]) { SUGAR.tabChooser.frozenOptions[left_name][right_name] = []; }
3678 if(typeof target == 'array') {
3679 for(var i in target) {
3680 SUGAR.tabChooser.frozenOptions[left_name][right_name][target[i]] = true;
3683 SUGAR.tabChooser.frozenOptions[left_name][right_name][target] = true;
3687 buildSelectHTML: function(info) {
3688 var text = "<select";
3690 if(typeof (info['select']['size']) != 'undefined') {
3691 text +=" size=\""+ info['select']['size'] +"\"";
3694 if(typeof (info['select']['name']) != 'undefined') {
3695 text +=" name=\""+ info['select']['name'] +"\"";
3698 if(typeof (info['select']['style']) != 'undefined') {
3699 text +=" style=\""+ info['select']['style'] +"\"";
3702 if(typeof (info['select']['onchange']) != 'undefined') {
3703 text +=" onChange=\""+ info['select']['onchange'] +"\"";
3706 if(typeof (info['select']['multiple']) != 'undefined') {
3711 for(i=0; i<info['options'].length;i++) {
3712 option = info['options'][i];
3713 text += "<option value=\""+option['value']+"\" ";
3714 if ( typeof (option['selected']) != 'undefined' && option['selected']== true) {
3717 text += ">"+option['text']+"</option>";
3719 text += "</select>";
3723 left_to_right: function(left_name, right_name, left_size, right_size) {
3724 SUGAR.savedViews.clearColumns = false;
3725 var left_td = document.getElementById(left_name+'_td');
3726 var right_td = document.getElementById(right_name+'_td');
3728 var display_columns_ref = left_td.getElementsByTagName('select')[0];
3729 var hidden_columns_ref = right_td.getElementsByTagName('select')[0];
3731 var selected_left = new Array();
3732 var notselected_left = new Array();
3733 var notselected_right = new Array();
3735 var left_array = new Array();
3737 var frozen_options = SUGAR.tabChooser.frozenOptions;
3738 frozen_options = frozen_options && frozen_options[left_name] && frozen_options[left_name][right_name]?frozen_options[left_name][right_name]:[];
3740 // determine which options are selected in left
3741 for (i=0; i < display_columns_ref.options.length; i++)
3743 if ( display_columns_ref.options[i].selected == true && !frozen_options[display_columns_ref.options[i].value])
3745 selected_left[selected_left.length] = {text: display_columns_ref.options[i].text, value: display_columns_ref.options[i].value};
3749 notselected_left[notselected_left.length] = {text: display_columns_ref.options[i].text, value: display_columns_ref.options[i].value};
3754 for (i=0; i < hidden_columns_ref.options.length; i++)
3756 notselected_right[notselected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
3760 var left_select_html_info = new Object();
3761 var left_options = new Array();
3762 var left_select = new Object();
3764 left_select['name'] = left_name+'[]';
3765 left_select['id'] = left_name;
3766 left_select['size'] = left_size;
3767 left_select['multiple'] = 'true';
3769 var right_select_html_info = new Object();
3770 var right_options = new Array();
3771 var right_select = new Object();
3773 right_select['name'] = right_name+'[]';
3774 right_select['id'] = right_name;
3775 right_select['size'] = right_size;
3776 right_select['multiple'] = 'true';
3778 for (i = 0; i < notselected_right.length; i++) {
3779 right_options[right_options.length] = notselected_right[i];
3782 for (i = 0; i < selected_left.length; i++) {
3783 right_options[right_options.length] = selected_left[i];
3785 for (i = 0; i < notselected_left.length; i++) {
3786 left_options[left_options.length] = notselected_left[i];
3788 left_select_html_info['options'] = left_options;
3789 left_select_html_info['select'] = left_select;
3790 right_select_html_info['options'] = right_options;
3791 right_select_html_info['select'] = right_select;
3792 right_select_html_info['style'] = 'background: lightgrey';
3794 var left_html = this.buildSelectHTML(left_select_html_info);
3795 var right_html = this.buildSelectHTML(right_select_html_info);
3797 left_td.innerHTML = left_html;
3798 right_td.innerHTML = right_html;
3800 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3801 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3803 this.movementCallback(object_refs[left_name], object_refs[right_name]);
3809 right_to_left: function(left_name, right_name, left_size, right_size, max_left) {
3810 SUGAR.savedViews.clearColumns = false;
3811 var left_td = document.getElementById(left_name+'_td');
3812 var right_td = document.getElementById(right_name+'_td');
3814 var display_columns_ref = left_td.getElementsByTagName('select')[0];
3815 var hidden_columns_ref = right_td.getElementsByTagName('select')[0];
3817 var selected_right = new Array();
3818 var notselected_right = new Array();
3819 var notselected_left = new Array();
3821 var frozen_options = SUGAR.tabChooser.frozenOptions;
3822 frozen_options = SUGAR.tabChooser.frozenOptions && SUGAR.tabChooser.frozenOptions[right_name] && SUGAR.tabChooser.frozenOptions[right_name][left_name]?SUGAR.tabChooser.frozenOptions[right_name][left_name]:[];
3824 for (i=0; i < hidden_columns_ref.options.length; i++)
3826 if (hidden_columns_ref.options[i].selected == true && !frozen_options[hidden_columns_ref.options[i].value])
3828 selected_right[selected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
3832 notselected_right[notselected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
3837 if(max_left != '' && (display_columns_ref.length + selected_right.length) > max_left) {
3838 alert('Maximum of ' + max_left + ' columns can be displayed.');
3842 for (i=0; i < display_columns_ref.options.length; i++)
3844 notselected_left[notselected_left.length] = {text:display_columns_ref.options[i].text, value:display_columns_ref.options[i].value};
3848 var left_select_html_info = new Object();
3849 var left_options = new Array();
3850 var left_select = new Object();
3852 left_select['name'] = left_name+'[]';
3853 left_select['id'] = left_name;
3854 left_select['multiple'] = 'true';
3855 left_select['size'] = left_size;
3857 var right_select_html_info = new Object();
3858 var right_options = new Array();
3859 var right_select = new Object();
3861 right_select['name'] = right_name+ '[]';
3862 right_select['id'] = right_name;
3863 right_select['multiple'] = 'true';
3864 right_select['size'] = right_size;
3866 for (i = 0; i < notselected_left.length; i++) {
3867 left_options[left_options.length] = notselected_left[i];
3870 for (i = 0; i < selected_right.length; i++) {
3871 left_options[left_options.length] = selected_right[i];
3873 for (i = 0; i < notselected_right.length; i++) {
3874 right_options[right_options.length] = notselected_right[i];
3876 left_select_html_info['options'] = left_options;
3877 left_select_html_info['select'] = left_select;
3878 right_select_html_info['options'] = right_options;
3879 right_select_html_info['select'] = right_select;
3880 right_select_html_info['style'] = 'background: lightgrey';
3882 var left_html = this.buildSelectHTML(left_select_html_info);
3883 var right_html = this.buildSelectHTML(right_select_html_info);
3885 left_td.innerHTML = left_html;
3886 right_td.innerHTML = right_html;
3888 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3889 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3891 this.movementCallback(object_refs[left_name], object_refs[right_name]);
3896 up: function(name, left_name, right_name) {
3897 SUGAR.savedViews.clearColumns = false;
3898 var left_td = document.getElementById(left_name+'_td');
3899 var right_td = document.getElementById(right_name+'_td');
3900 var td = document.getElementById(name+'_td');
3901 var obj = td.getElementsByTagName('select')[0];
3902 obj = (typeof obj == "string") ? document.getElementById(obj) : obj;
3903 if (obj.tagName.toLowerCase() != "select" && obj.length < 2)
3905 var sel = new Array();
3907 for (i=0; i<obj.length; i++) {
3908 if (obj[i].selected == true) {
3909 sel[sel.length] = i;
3912 for (i=0; i < sel.length; i++) {
3913 if (sel[i] != 0 && !obj[sel[i]-1].selected) {
3914 var tmp = new Array(obj[sel[i]-1].text, obj[sel[i]-1].value);
3915 obj[sel[i]-1].text = obj[sel[i]].text;
3916 obj[sel[i]-1].value = obj[sel[i]].value;
3917 obj[sel[i]].text = tmp[0];
3918 obj[sel[i]].value = tmp[1];
3919 obj[sel[i]-1].selected = true;
3920 obj[sel[i]].selected = false;
3924 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3925 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3927 this.orderCallback(object_refs[left_name], object_refs[right_name]);
3932 down: function(name, left_name, right_name) {
3933 SUGAR.savedViews.clearColumns = false;
3934 var left_td = document.getElementById(left_name+'_td');
3935 var right_td = document.getElementById(right_name+'_td');
3936 var td = document.getElementById(name+'_td');
3937 var obj = td.getElementsByTagName('select')[0];
3938 if (obj.tagName.toLowerCase() != "select" && obj.length < 2)
3940 var sel = new Array();
3941 for (i=obj.length-1; i>-1; i--) {
3942 if (obj[i].selected == true) {
3943 sel[sel.length] = i;
3946 for (i=0; i < sel.length; i++) {
3947 if (sel[i] != obj.length-1 && !obj[sel[i]+1].selected) {
3948 var tmp = new Array(obj[sel[i]+1].text, obj[sel[i]+1].value);
3949 obj[sel[i]+1].text = obj[sel[i]].text;
3950 obj[sel[i]+1].value = obj[sel[i]].value;
3951 obj[sel[i]].text = tmp[0];
3952 obj[sel[i]].value = tmp[1];
3953 obj[sel[i]+1].selected = true;
3954 obj[sel[i]].selected = false;
3958 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3959 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3961 this.orderCallback(object_refs[left_name], object_refs[right_name]);
3966 }(); // end tabChooser
3968 SUGAR.language = function() {
3970 languages : new Array(),
3972 setLanguage: function(module, data) {
3973 if (!SUGAR.language.languages) {
3976 SUGAR.language.languages[module] = data;
3979 get: function(module, str) {
3980 if(typeof SUGAR.language.languages[module] == 'undefined' || typeof SUGAR.language.languages[module][str] == 'undefined')
3984 return SUGAR.language.languages[module][str];
3987 translate: function(module, str)
3989 text = this.get(module, str);
3990 return text != 'undefined' ? text : this.get('app_strings', str);
3995 SUGAR.contextMenu = function() {
3997 objects: new Object(),
3998 objectTypes: new Object(),
4000 * Registers a new object for the context menu.
4001 * objectType - name of the type
4003 * metaData - metaData to pass to the action function
4005 registerObject: function(objectType, id, metaData) {
4006 SUGAR.contextMenu.objects[id] = new Object();
4007 SUGAR.contextMenu.objects[id] = {'objectType' : objectType, 'metaData' : metaData};
4010 * Registers a new object type
4011 * name - name of the type
4012 * menuItems - array of menu items
4014 registerObjectType: function(name, menuItems) {
4015 SUGAR.contextMenu.objectTypes[name] = new Object();
4016 SUGAR.contextMenu.objectTypes[name] = {'menuItems' : menuItems, 'objects' : new Array()};
4019 * Determines which menu item was clicked
4021 getListItemFromEventTarget: function(p_oNode) {
4023 if(p_oNode.tagName == "LI") {
4028 if(p_oNode.tagName == "LI") {
4033 } while((p_oNode = p_oNode.parentNode));
4038 * handles movement within context menu
4040 onContextMenuMove: function() {
4041 var oNode = this.contextEventTarget;
4042 var bDisabled = (oNode.tagName == "UL");
4043 var i = this.getItemGroups()[0].length - 1;
4045 this.getItem(i).cfg.setProperty("disabled", bDisabled);
4050 * handles clicks on a context menu ITEM
4052 onContextMenuItemClick: function(p_sType, p_aArguments, p_oItem) {
4053 var oLI = SUGAR.contextMenu.getListItemFromEventTarget(this.parent.contextEventTarget);
4054 id = this.parent.contextEventTarget.parentNode.id; // id of the target
4055 funct = eval(SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[id]['objectType']]['menuItems'][this.index]['action']);
4056 funct(this.parent.contextEventTarget, SUGAR.contextMenu.objects[id]['metaData']);
4059 * Initializes all context menus registered
4062 for(var i in SUGAR.contextMenu.objects) { // make a variable called objects in objectTypes containg references to all triggers
4063 if(typeof SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'] == 'undefined')
4064 SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'] = new Array();
4065 SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'].push(document.getElementById(i));
4067 // register the menus
4068 for(var i in SUGAR.contextMenu.objectTypes) {
4069 var oContextMenu = new YAHOO.widget.ContextMenu(i, {'trigger': SUGAR.contextMenu.objectTypes[i]['objects']});
4070 var aMainMenuItems = SUGAR.contextMenu.objectTypes[i]['menuItems'];
4071 var nMainMenuItems = aMainMenuItems.length;
4073 for(var j = 0; j < nMainMenuItems; j++) {
4074 oMenuItem = new YAHOO.widget.ContextMenuItem(aMainMenuItems[j].text, { helptext: aMainMenuItems[j].helptext });
4075 oMenuItem.clickEvent.subscribe(SUGAR.contextMenu.onContextMenuItemClick, oMenuItem, true);
4076 oContextMenu.addItem(oMenuItem);
4078 // Add a "move" event handler to the context menu
4079 oContextMenu.moveEvent.subscribe(SUGAR.contextMenu.onContextMenuMove, oContextMenu, true);
4080 // Add a "keydown" event handler to the context menu
4081 oContextMenu.keyDownEvent.subscribe(SUGAR.contextMenu.onContextMenuItemClick, oContextMenu, true);
4082 // Render the context menu
4083 oContextMenu.render(document.body);
4089 SUGAR.contextMenu.actions = function() {
4092 * redirects to a new note with the clicked on object as the target
4094 createNote: function(itemClicked, metaData) {
4095 loc = 'index.php?module=Notes&action=EditView';
4096 for(i in metaData) {
4097 if(i == 'notes_parent_type') loc += '&parent_type=' + metaData[i];
4098 else if(i != 'module' && i != 'parent_type') loc += '&' + i + '=' + metaData[i];
4100 document.location = loc;
4103 * redirects to a new note with the clicked on object as the target
4105 scheduleMeeting: function(itemClicked, metaData) {
4106 loc = 'index.php?module=Meetings&action=EditView';
4107 for(i in metaData) {
4108 if(i != 'module') loc += '&' + i + '=' + metaData[i];
4110 document.location = loc;
4113 * redirects to a new note with the clicked on object as the target
4115 scheduleCall: function(itemClicked, metaData) {
4116 loc = 'index.php?module=Calls&action=EditView';
4117 for(i in metaData) {
4118 if(i != 'module') loc += '&' + i + '=' + metaData[i];
4120 document.location = loc;
4123 * redirects to a new contact with the clicked on object as the target
4125 createContact: function(itemClicked, metaData) {
4126 loc = 'index.php?module=Contacts&action=EditView';
4127 for(i in metaData) {
4128 if(i != 'module') loc += '&' + i + '=' + metaData[i];
4130 document.location = loc;
4133 * redirects to a new task with the clicked on object as the target
4135 createTask: function(itemClicked, metaData) {
4136 loc = 'index.php?module=Tasks&action=EditView';
4137 for(i in metaData) {
4138 if(i != 'module') loc += '&' + i + '=' + metaData[i];
4140 document.location = loc;
4143 * redirects to a new opportunity with the clicked on object as the target
4145 createOpportunity: function(itemClicked, metaData) {
4146 loc = 'index.php?module=Opportunities&action=EditView';
4147 for(i in metaData) {
4148 if(i != 'module') loc += '&' + i + '=' + metaData[i];
4150 document.location = loc;
4153 * redirects to a new opportunity with the clicked on object as the target
4155 createCase: function(itemClicked, metaData) {
4156 loc = 'index.php?module=Cases&action=EditView';
4157 for(i in metaData) {
4158 if(i != 'module') loc += '&' + i + '=' + metaData[i];
4160 document.location = loc;
4163 * handles add to favorites menu selection
4165 addToFavorites: function(itemClicked, metaData) {
4166 success = function(data) {
4168 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});
4173 //if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.contextMenu.init);
4175 // initially from popup_parent_helper.js
4176 var popup_request_data;
4179 function get_popup_request_data()
4181 return YAHOO.lang.JSON.stringify(window.document.popup_request_data);
4184 function get_close_popup()
4186 return window.document.close_popup;
4189 function open_popup(module_name, width, height, initial_filter, close_popup, hide_clear_button, popup_request_data, popup_mode, create, metadata)
4191 if (typeof(popupCount) == "undefined" || popupCount == 0)
4194 // set the variables that the popup will pull from
4195 window.document.popup_request_data = popup_request_data;
4196 window.document.close_popup = close_popup;
4198 //globally changing width and height of standard pop up window from 600 x 400 to 800 x 800
4199 width = (width == 600) ? 800 : width;
4200 height = (height == 400) ? 800 : height;
4204 + 'module=' + module_name
4207 if (initial_filter != '') {
4208 URL += '&query=true' + initial_filter;
4209 // Bug 41891 - Popup Window Name
4210 popupName = initial_filter.replace(/[^a-z_0-9]+/ig, '_');
4211 windowName = module_name + '_popup_window' + popupName;
4213 windowName = module_name + '_popup_window' + popupCount;
4217 if (hide_clear_button) {
4218 URL += '&hide_clear_button=true';
4221 windowFeatures = 'width=' + width
4222 + ',height=' + height
4223 + ',resizable=1,scrollbars=1';
4225 if (popup_mode == '' && popup_mode == 'undefined') {
4226 popup_mode='single';
4228 URL+='&mode='+popup_mode;
4229 if (create == '' && create == 'undefined') {
4232 URL+='&create='+create;
4234 if (metadata != '' && metadata != 'undefined') {
4235 URL+='&metadata='+metadata;
4238 // Bug #46842 : The relate field field_to_name_array fails to copy over custom fields
4239 // post fields that should be populated from popup form
4240 if(popup_request_data.jsonObject) {
4241 var request_data = popup_request_data.jsonObject;
4243 var request_data = popup_request_data;
4245 var field_to_name_array_url = '';
4246 if (request_data && request_data.field_to_name_array != 'undefined') {
4247 for(var key in request_data.field_to_name_array) {
4248 if ( key.toLowerCase() != 'id' ) {
4249 field_to_name_array_url += '&field_to_name[]='+encodeURIComponent(key.toLowerCase());
4253 if ( field_to_name_array_url ) {
4254 URL+=field_to_name_array_url;
4257 win = SUGAR.util.openWindow(URL, windowName, windowFeatures);
4261 // put the focus on the popup if the browser supports the focus() method
4265 win.popupCount = popupCount;
4271 * The reply data must be a JSON array structured with the following information:
4272 * 1) form name to populate
4273 * 2) associative array of input names to values for populating the form
4275 var from_popup_return = false;
4277 //Function replaces special HTML chars for usage in text boxes
4278 function replaceHTMLChars(value) {
4279 return value.replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');
4282 function set_return_basic(popup_reply_data,filter)
4284 var form_name = popup_reply_data.form_name;
4285 var name_to_value_array = popup_reply_data.name_to_value_array;
4286 for (var the_key in name_to_value_array)
4288 if(the_key == 'toJSON')
4292 else if(the_key.match(filter))
4294 var displayValue=replaceHTMLChars(name_to_value_array[the_key]);
4295 // begin andopes change: support for enum fields (SELECT)
4296 if(window.document.forms[form_name] && window.document.forms[form_name].elements[the_key]) {
4297 if(window.document.forms[form_name].elements[the_key].tagName == 'SELECT') {
4298 var selectField = window.document.forms[form_name].elements[the_key];
4299 for(var i = 0; i < selectField.options.length; i++) {
4300 if(selectField.options[i].text == displayValue) {
4301 selectField.options[i].selected = true;
4302 SUGAR.util.callOnChangeListers(selectField);
4307 window.document.forms[form_name].elements[the_key].value = displayValue;
4308 SUGAR.util.callOnChangeListers(window.document.forms[form_name].elements[the_key]);
4311 // end andopes change: support for enum fields (SELECT)
4316 function set_return(popup_reply_data)
4318 from_popup_return = true;
4319 var form_name = popup_reply_data.form_name;
4320 var name_to_value_array = popup_reply_data.name_to_value_array;
4321 if(typeof name_to_value_array != 'undefined' && name_to_value_array['account_id'])
4324 var label_data_str = '';
4325 var current_label_data_str = '';
4326 var popupConfirm = popup_reply_data.popupConfirm;
4327 for (var the_key in name_to_value_array)
4329 if(the_key == 'toJSON')
4335 var displayValue=replaceHTMLChars(name_to_value_array[the_key]);
4336 if(window.document.forms[form_name] && document.getElementById(the_key+'_label') && !the_key.match(/account/)) {
4337 var data_label = document.getElementById(the_key+'_label').innerHTML.replace(/\n/gi,'').replace(/<\/?[^>]+(>|$)/g, "");
4338 label_str += data_label + ' \n';
4339 label_data_str += data_label + ' ' + displayValue + '\n';
4340 if(window.document.forms[form_name].elements[the_key]) {
4341 current_label_data_str += data_label + ' ' + window.document.forms[form_name].elements[the_key].value +'\n';
4347 if(label_data_str != label_str && current_label_data_str != label_str){
4349 if (typeof popupConfirm != 'undefined')
4351 if (popupConfirm > -1) {
4352 set_return_basic(popup_reply_data,/\S/);
4354 set_return_basic(popup_reply_data,/account/);
4358 else if(confirm(SUGAR.language.get('app_strings', 'NTC_OVERWRITE_ADDRESS_PHONE_CONFIRM') + '\n\n' + label_data_str))
4360 set_return_basic(popup_reply_data,/\S/);
4364 set_return_basic(popup_reply_data,/account/);
4366 }else if(label_data_str != label_str && current_label_data_str == label_str){
4367 set_return_basic(popup_reply_data,/\S/);
4368 }else if(label_data_str == label_str){
4369 set_return_basic(popup_reply_data,/account/);
4372 set_return_basic(popup_reply_data,/\S/);
4376 function set_return_lead_conv(popup_reply_data) {
4377 set_return(popup_reply_data);
4378 if (document.getElementById('lead_conv_ac_op_sel') && typeof onBlurKeyUpHandler=='function') {
4379 onBlurKeyUpHandler();
4383 function set_return_and_save(popup_reply_data)
4385 var form_name = popup_reply_data.form_name;
4386 var name_to_value_array = popup_reply_data.name_to_value_array;
4388 for (var the_key in name_to_value_array)
4390 if(the_key == 'toJSON')
4396 window.document.forms[form_name].elements[the_key].value = name_to_value_array[the_key];
4400 window.document.forms[form_name].return_module.value = window.document.forms[form_name].module.value;
4401 window.document.forms[form_name].return_action.value = 'DetailView';
4402 window.document.forms[form_name].return_id.value = window.document.forms[form_name].record.value;
4403 window.document.forms[form_name].action.value = 'Save';
4404 window.document.forms[form_name].submit();
4408 * This is a helper function to construct the initial filter that can be
4409 * passed into the open_popup() function. It assumes that there is an
4410 * account_id and account_name field in the given form_name to use to
4411 * construct the intial filter string.
4413 function get_initial_filter_by_account(form_name)
4415 var account_id = window.document.forms[form_name].account_id.value;
4416 var account_name = escape(window.document.forms[form_name].account_name.value);
4417 var initial_filter = "&account_id=" + account_id + "&account_name=" + account_name;
4419 return initial_filter;
4421 // end code from popup_parent_helper.js
4423 // begin code for address copy
4425 * This is a function used by the Address widget that will fill
4426 * in the given array fields using the fromKey and toKey as a
4427 * prefix into the form objects HTML elements.
4429 * @param form The HTML form object to parse
4430 * @param fromKey The prefix of elements to copy from
4431 * @param toKey The prefix of elements to copy into
4432 * @return boolean true if successful, false otherwise
4434 function copyAddress(form, fromKey, toKey) {
4436 var elems = new Array("address_street", "address_city", "address_state", "address_postalcode", "address_country");
4437 var checkbox = document.getElementById(toKey + "_checkbox");
4439 if(typeof checkbox != "undefined") {
4440 if(!checkbox.checked) {
4442 t = toKey + "_" + elems[x];
4443 document.getElementById(t).removeAttribute('readonly');
4447 f = fromKey + "_" + elems[x];
4448 t = toKey + "_" + elems[x];
4450 document.getElementById(t).value = document.getElementById(f).value;
4451 document.getElementById(t).setAttribute('readonly', true);
4457 // end code for address copy
4460 * This function is used in Email Template Module.
4461 * It will check whether the template is used in Campaing->EmailMarketing.
4462 * If true, it will notify user.
4465 function check_deletable_EmailTemplate() {
4466 id = document.getElementsByName('record')[0].value;
4467 currentForm = document.getElementById('form');
4469 success:function(r) {
4470 if(r.responseText == 'true') {
4471 if(!confirm(SUGAR.language.get('app_strings','NTC_TEMPLATE_IS_USED'))) {
4475 if(!confirm(SUGAR.language.get('app_strings','NTC_DELETE_CONFIRMATION'))) {
4479 currentForm.return_module.value='EmailTemplates';
4480 currentForm.return_action.value='ListView';
4481 currentForm.action.value='Delete';
4482 currentForm.submit();
4485 url = "index.php?module=EmailTemplates&action=CheckDeletable&from=DetailView&to_pdf=1&record="+id;
4486 YAHOO.util.Connect.asyncRequest('POST',url, call_back,null);
4490 remove_upload_imagefile : function(field_name) {
4491 var field=document.getElementById('remove_imagefile_' + field_name);
4494 //enable the file upload button.
4495 var field=document.getElementById( field_name);
4496 field.style.display="";
4498 //hide the image and remove button.
4499 var field=document.getElementById('img_' + field_name);
4500 field.style.display="none";
4501 var field=document.getElementById('bt_remove_' + field_name);
4502 field.style.display="none";
4504 if(document.getElementById(field_name + '_duplicate')) {
4505 var field = document.getElementById(field_name + '_duplicate');
4510 confirm_imagefile : function(field_name) {
4511 var field=document.getElementById(field_name);
4512 var filename=field.value;
4513 var fileExtension = filename.substring(filename.lastIndexOf(".")+1);
4514 fileExtension = fileExtension.toLowerCase();
4515 if (fileExtension == "jpg" || fileExtension == "jpeg"
4516 || fileExtension == "gif" || fileExtension == "png" || fileExtension == "bmp"){
4521 alert(SUGAR.language.get('app_strings', 'LBL_UPLOAD_IMAGE_FILE_INVALID'));
4525 lightbox : function(image)
4527 if (typeof(SUGAR.image.lighboxWindow) == "undefined")
4528 SUGAR.image.lighboxWindow = new YAHOO.widget.SimpleDialog('sugarImageViewer', {
4531 id:'sugarMsgWindow',
4534 msg: "<img src='" + image + "'> </img>",
4537 SUGAR.image.lighboxWindow.setBody("<img src='" + image + "'> </img>");
4538 SUGAR.image.lighboxWindow.render(document.body);
4539 SUGAR.image.lighboxWindow.show();
4540 SUGAR.image.lighboxWindow.center()
4544 SUGAR.append(SUGAR.util, {
4545 isTouchScreen: function() {
4546 // first check if we have forced use of the touch enhanced interface
4547 if (Get_Cookie("touchscreen") == '1') {
4551 // next check if we should use the touch interface with our device
4552 if ((navigator.userAgent.match(/iPad/i) != null)) {
4559 isLoginPage: function(content) {
4560 //skip if this is packageManager screen
4561 if(SUGAR.util.isPackageManager()) {return false;}
4562 var loginPageStart = "<!DOCTYPE";
4563 if (content.substr(0, loginPageStart.length) == loginPageStart && content.indexOf("<html>") != -1 && content.indexOf("login_module") != -1) {
4564 window.location.href = window.location.protocol + window.location.pathname;
4569 isPackageManager: function(){
4570 if(typeof(document.the_form) !='undefined' && typeof(document.the_form.language_pack_escaped) !='undefined'){
4572 }else{return false;}
4575 ajaxCallInProgress: function(){
4577 //First check if we are in a popup.
4578 if (typeof (send_back) != "function"){
4579 //If the page content is blank, it means we are probably still waiting on something
4580 var c = document.getElementById("content");
4581 if (!c) return true;
4582 t = YAHOO.lang.trim(SUGAR.util.innerText(c));
4584 return SUGAR_callsInProgress != 0 || t == "";
4586 //Firefox doesn't support innerText (textContent includes script content)
4587 innerText : function(el) {
4588 if (el.tagName == "SCRIPT")
4590 if(typeof(el.innerText) == "string")
4591 return el.innerText;
4593 for (var i in el.childNodes){
4594 var c = el.childNodes[i];
4595 if (typeof(c) != "object")
4597 if (typeof(c.nodeName) == "string" && c.nodeName == "#text")
4600 t += SUGAR.util.innerText(c);
4605 callOnChangeListers: function(field){
4606 var listeners = YAHOO.util.Event.getListeners(field, 'change');
4607 if (listeners != null) {
4608 for (var i = 0; i < listeners.length; i++) {
4609 var l = listeners[i];
4610 l.fn.call(l.scope ? l.scope : this, l.obj);
4615 closeActivityPanel: {
4616 show:function(module,id,new_status,viewType,parentContainerId){
4617 if (SUGAR.util.closeActivityPanel.panel)
4618 SUGAR.util.closeActivityPanel.panel.destroy();
4619 var singleModule = SUGAR.language.get("app_list_strings", "moduleListSingular")[module];
4620 singleModule = typeof(singleModule != 'undefined') ? singleModule.toLowerCase() : '';
4621 var closeText = SUGAR.language.get("app_strings", "LBL_CLOSE_ACTIVITY_CONFIRM").replace("#module#",singleModule);
4622 SUGAR.util.closeActivityPanel.panel =
4623 new YAHOO.widget.SimpleDialog("closeActivityDialog",
4630 constraintoviewport: true,
4631 buttons: [ { text:SUGAR.language.get("app_strings", "LBL_EMAIL_OK"), handler:function(){
4632 if (SUGAR.util.closeActivityPanel.panel)
4633 SUGAR.util.closeActivityPanel.panel.hide();
4635 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_SAVING'));
4636 var args = "action=save&id=" + id + "&record=" + id + "&status=" + new_status + "&module=" + module;
4637 // 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
4638 // TODO: Take id out and regression test. Left id in for now to not create any other unexpected problems
4639 //var args = "action=save&id=" + id + "&status=" + new_status + "&module=" + module;
4643 // Bug 51984: We need to submit the form just incase we have a form already submitted
4644 // so we dont get a popup stating that the form needs to be resubmitted like it doesn,
4645 // when you do a reload/refresh
4646 window.setTimeout(function(){if(document.getElementById('search_form')) document.getElementById('search_form').submit(); else window.location.reload(true);}, 0);
4648 argument:{'parentContainerId':parentContainerId}
4651 YAHOO.util.Connect.asyncRequest('POST', 'index.php', callback, args);
4653 }, isDefault:true },
4654 { text:SUGAR.language.get("app_strings", "LBL_EMAIL_CANCEL"), handler:function(){SUGAR.util.closeActivityPanel.panel.hide(); }} ]
4657 SUGAR.util.closeActivityPanel.panel.setHeader(SUGAR.language.get("app_strings", "LBL_CLOSE_ACTIVITY_HEADER"));
4658 SUGAR.util.closeActivityPanel.panel.render(document.body);
4659 SUGAR.util.closeActivityPanel.panel.show();
4663 setEmailPasswordDisplay: function(id, exists, formName) {
4664 link = document.getElementById(id+'_link');
4665 pwd = document.getElementById(id);
4666 if(!pwd || !link) return;
4668 pwd.style.display = 'none';
4669 link.style.display = '';
4670 if(typeof(formName) != 'undefined')
4671 removeFromValidate(formName, id);
4673 pwd.style.display = '';
4674 link.style.display = 'none';
4678 setEmailPasswordEdit: function(id) {
4679 link = document.getElementById(id+'_link');
4680 pwd = document.getElementById(id);
4681 if(!pwd || !link) return;
4682 pwd.style.display = '';
4683 link.style.display = 'none';
4687 * Compares a filename with a supplied array of allowed file extensions.
4688 * @param fileName string
4689 * @param allowedTypes array of allowed file extensions
4692 validateFileExt: function(fileName, allowedTypes) {
4693 var ext = fileName.split('.').pop().toLowerCase();
4695 for (var i = allowedTypes.length; i >= 0; i--) {
4696 if (ext === allowedTypes[i]) {
4704 arrayIndexOf: function(arr, val, start) {
4705 if (typeof arr.indexOf == "function")
4706 return arr.indexOf(val, start);
4707 for (var i = (start || 0), j = arr.length; i < j; i++) {
4708 if (arr[i] === val) {
4716 SUGAR.clearRelateField = function(form, name, id)
4718 if (typeof form[name] == "object"){
4719 form[name].value = '';
4720 SUGAR.util.callOnChangeListers(form[name]);
4723 if (typeof form[id] == "object"){
4724 form[id].value = '';
4725 SUGAR.util.callOnChangeListers(form[id]);
4728 if(typeof(SUGAR.AutoComplete) == 'undefined') SUGAR.AutoComplete = {};
4730 SUGAR.AutoComplete.getOptionsArray = function(options_index){
4731 var return_arr = [];
4733 var opts = SUGAR.language.get('app_list_strings', options_index);
4734 if(typeof(opts) != 'undefined'){
4736 // Since we are using auto complete, we excluse blank dropdown entries since they can just leave it blank
4737 if(key != '' && opts[key] != ''){
4740 item['text'] = opts[key];
4741 return_arr.push(item);
4748 if(typeof(SUGAR.MultiEnumAutoComplete) == 'undefined') SUGAR.MultiEnumAutoComplete = {};
4750 SUGAR.MultiEnumAutoComplete.getMultiSelectKeysFromValues = function(options_index, val_string){
4751 var opts = SUGAR.language.get('app_list_strings', options_index);
4752 var selected_values = val_string.split(", ");
4753 // YUI AutoComplete adds a blank. We remove it automatically here
4754 if(selected_values.length > 0 && selected_values.indexOf('') == selected_values.length - 1){
4755 selected_values.pop();
4757 var final_arr = new Array();
4758 for(idx in selected_values){
4760 if(selected_values[idx] == opts[o_idx]){
4761 final_arr.push(o_idx);
4768 SUGAR.MultiEnumAutoComplete.getMultiSelectValuesFromKeys = function(options_index, val_string){
4769 var opts = SUGAR.language.get('app_list_strings', options_index);
4770 val_string=val_string.replace(/^\^/,'').replace(/\^$/,'') //fixes bug where string starts or ends with ^
4771 var selected_values = val_string.split("^,^");
4773 // YUI AutoComplete adds a blank. We remove it automatically here
4774 if(selected_values.length > 0 && selected_values.indexOf('') == selected_values.length - 1){
4775 selected_values.pop();
4778 var final_arr = new Array();
4779 for(idx in selected_values){
4781 if(selected_values[idx] == o_idx){
4782 final_arr.push(opts[o_idx]);