1 /*********************************************************************************
2 * SugarCRM Community Edition is a customer relationship management program developed by
3 * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
5 * This program is free software; you can redistribute it and/or modify it under
6 * the terms of the GNU Affero General Public License version 3 as published by the
7 * Free Software Foundation with the addition of the following permission added
8 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
9 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
10 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
12 * This program is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
17 * You should have received a copy of the GNU Affero General Public License along with
18 * this program; if not, see http://www.gnu.org/licenses or write to the Free
19 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
23 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
25 * The interactive user interfaces in modified source and object code versions
26 * of this program must display Appropriate Legal Notices, as required under
27 * Section 5 of the GNU Affero General Public License version 3.
29 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
30 * these Appropriate Legal Notices must retain the display of the "Powered by
31 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
32 * technical reasons, the Appropriate Legal Notices must display the words
33 * "Powered by SugarCRM".
34 ********************************************************************************/
40 * Namespace for Sugar Objects
42 if (typeof(SUGAR) == "undefined") {
46 * Creates a namespace if it doesn't exist and then returns it.
48 * Note: this implementation only creates a top-level namespace. Extend this function if
49 * multi-level namespaces are needed.
52 namespace: function(ns) {
53 SUGAR[ns] = SUGAR[ns] || {};
55 return ((typeof SUGAR[ns] === "object") && (SUGAR[ns] !== null)) ? SUGAR[ns] : false;
59 * Add properties of an object to target object.
63 append: function(target, obj) {
64 for (var prop in obj) {
65 if (obj[prop] !== void 0) target[prop] = obj[prop];
74 SUGAR.namespace("themes");
75 SUGAR.namespace("tour");
78 * Namespace for Homepage
80 SUGAR.namespace("sugarHome");
83 * Namespace for Subpanel Utils
85 SUGAR.namespace("subpanelUtils");
90 SUGAR.namespace("ajaxStatusClass");
95 SUGAR.namespace("tabChooser");
98 * General namespace for Sugar utils
100 SUGAR.namespace("utils");
101 SUGAR.namespace("savedViews");
106 SUGAR.namespace("dashlets");
107 SUGAR.namespace("unifiedSearchAdvanced");
109 SUGAR.namespace("searchForm");
110 SUGAR.namespace("language");
111 SUGAR.namespace("Studio");
112 SUGAR.namespace("contextMenu");
113 SUGAR.namespace("config");
117 var requiredIndex = 2;
122 var altMsgIndex = 15;
123 var compareToIndex = 7;
125 var operatorIndex = 13;
126 var callbackIndex = 16;
128 var validate = new Array();
130 var requiredTxt = 'Missing Required Field:';
131 var invalidTxt = 'Invalid Value:';
132 var secondsSinceLoad = 0;
134 var inputsWithErrors = new Array();
135 var tabsWithErrors = new Array();
136 var lastSubmitTime = 0;
137 var alertList = new Array();
138 var oldStartsWith = '';
143 * As of Sugar version 6.2.3 (MSIE Version 9) this function is deprecated. The preferred method is to use the
144 * user agent check supplied by YUI to check for IE:
146 * for checking if a browser is IE in general : if(YAHOO.env.ua.ie) {...}
148 * or for checking specific versions: if (YAHOO.env.ua.ie >= 5.5 && YAHOO.env.ua.ie < 9) {...}
151 function isSupportedIE() {
152 var userAgent = navigator.userAgent.toLowerCase() ;
154 // IE Check supports ActiveX controls
155 if (userAgent.indexOf("msie") != -1 && userAgent.indexOf("mac") == -1 && userAgent.indexOf("opera") == -1) {
156 var version = navigator.appVersion.match(/MSIE (.\..)/)[1] ;
157 if(version >= 5.5 && version < 10) {
165 function checkMinSupported(c, s) {
166 var current = c.split(".");
167 var supported = s.split(".");
168 for (var i in supported) {
169 if (current[i] && parseInt(current[i]) > parseInt(supported[i])) return true;
170 else if (current[i] && parseInt(current[i]) < parseInt(supported[i])) return false;
175 function checkMaxSupported(c, s) {
176 var current = c.split(".");
177 var supported = s.split(".");
178 for (var i in supported) {
179 if (current[i] && parseInt(current[i]) > parseInt(supported[i])) return false;
180 else if (current[i] && parseInt(current[i]) < parseInt(supported[i])) return true;
185 SUGAR.isSupportedBrowser = function(){
186 var supportedBrowsers = {
187 msie : {min:8, max:10}, // IE 8, 9, 10
188 safari : {min:534}, // Safari 5.1
189 mozilla : {min:20.0}, // Firefox 20.0
190 chrome : {min:537.31} // Chrome 26
192 var current = String($.browser.version);
194 if ($.browser.msie){ // Internet Explorer
195 supported = supportedBrowsers['msie'];
197 else if ($.browser.mozilla) { // Firefox
198 supported = supportedBrowsers['mozilla'];
201 $.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase());
202 if($.browser.chrome){ // Chrome
203 supported = supportedBrowsers['chrome'];
205 else if($.browser.safari){ // Safari
206 supported = supportedBrowsers['safari'];
209 if (current && supported)
210 return checkMinSupported(current, String(supported.min)) && (!supported.max || checkMaxSupported(current, String(supported.max)));
215 SUGAR.isIECompatibilityMode = function(){
216 var agentStr = navigator.userAgent;
218 if (agentStr.indexOf("MSIE 7.0") > -1 &&
219 (agentStr.indexOf("Trident/5.0") > -1 || // IE9 Compatibility View
220 agentStr.indexOf("Trident/4.0") > -1 // IE8 Compatibility View
229 SUGAR.isIE = isSupportedIE();
230 var isSafari = (navigator.userAgent.toLowerCase().indexOf('safari')!=-1);
232 // escapes regular expression characters
233 RegExp.escape = function(text) { // http://simon.incutio.com/archive/2006/01/20/escape
234 if (!arguments.callee.sRE) {
235 var specials = ['/', '.', '*', '+', '?', '|','(', ')', '[', ']', '{', '}', '\\'];
236 arguments.callee.sRE = new RegExp('(\\' + specials.join('|\\') + ')', 'g');
238 return text.replace(arguments.callee.sRE, '\\$1');
241 function addAlert(type, name,subtitle, description,time, redirect) {
242 var addIndex = alertList.length;
243 alertList[addIndex]= new Array();
244 alertList[addIndex]['name'] = name;
245 alertList[addIndex]['type'] = type;
246 alertList[addIndex]['subtitle'] = subtitle;
247 alertList[addIndex]['description'] = replaceHTMLChars(description.replace(/<br>/gi, "\n"));
248 alertList[addIndex]['time'] = time;
249 alertList[addIndex]['done'] = 0;
250 alertList[addIndex]['redirect'] = redirect;
252 function checkAlerts() {
253 secondsSinceLoad += 1;
256 for(mj = 0 ; mj < alertList.length; mj++) {
257 if(alertList[mj]['done'] == 0) {
258 if(alertList[mj]['time'] < secondsSinceLoad && alertList[mj]['time'] > -1 ) {
259 alertmsg = alertList[mj]['type'] + ":" + alertList[mj]['name'] + "\n" +alertList[mj]['subtitle']+ "\n"+ alertList[mj]['description'] + "\n\n";
260 alertList[mj]['done'] = 1;
261 if(alertList[mj]['redirect'] == '') {
264 else if(confirm(alertmsg)) {
265 window.location = alertList[mj]['redirect'];
271 alertsTimeoutId = setTimeout("checkAlerts()", 1000);
274 function toggleDisplay(id) {
275 if(this.document.getElementById(id).style.display == 'none') {
276 this.document.getElementById(id).style.display = '';
277 if(this.document.getElementById(id+"link") != undefined) {
278 this.document.getElementById(id+"link").style.display = 'none';
280 if(this.document.getElementById(id+"_anchor") != undefined)
281 this.document.getElementById(id+"_anchor").innerHTML='[ - ]';
284 this.document.getElementById(id).style.display = 'none';
285 if(this.document.getElementById(id+"link") != undefined) {
286 this.document.getElementById(id+"link").style.display = '';
288 if(this.document.getElementById(id+"_anchor") != undefined)
289 this.document.getElementById(id+"_anchor").innerHTML='[+]';
293 function checkAll(form, field, value) {
294 for (i = 0; i < form.elements.length; i++) {
295 if(form.elements[i].name == field)
296 form.elements[i].checked = value;
300 function replaceAll(text, src, rep) {
301 offset = text.toLowerCase().indexOf(src.toLowerCase());
302 while(offset != -1) {
303 text = text.substring(0, offset) + rep + text.substring(offset + src.length ,text.length);
304 offset = text.indexOf( src, offset + rep.length + 1);
309 function addForm(formname) {
310 validate[formname] = new Array();
313 function addToValidate(formname, name, type, required, msg) {
314 if(typeof validate[formname] == 'undefined') {
317 validate[formname][validate[formname].length] = new Array(name, type,required, msg);
320 // Bug #47961 Callback validator definition
321 function addToValidateCallback(formname, name, type, required, msg, callback)
323 addToValidate(formname, name, type, required, msg);
324 var iIndex = validate[formname].length -1;
325 validate[formname][iIndex][jstypeIndex] = 'callback';
326 validate[formname][iIndex][callbackIndex] = callback;
329 function addToValidateRange(formname, name, type,required, msg,min,max) {
330 addToValidate(formname, name, type,required, msg);
331 validate[formname][validate[formname].length - 1][jstypeIndex] = 'range';
332 validate[formname][validate[formname].length - 1][minIndex] = min;
333 validate[formname][validate[formname].length - 1][maxIndex] = max;
336 function addToValidateIsValidDate(formname, name, type, required, msg) {
337 addToValidate(formname, name, type, required, msg);
338 validate[formname][validate[formname].length - 1][jstypeIndex] = 'date';
341 function addToValidateIsValidTime(formname, name, type, required, msg) {
342 addToValidate(formname, name, type, required, msg);
343 validate[formname][validate[formname].length - 1][jstypeIndex] = 'time';
346 function addToValidateDateBefore(formname, name, type, required, msg, compareTo) {
347 addToValidate(formname, name, type,required, msg);
348 validate[formname][validate[formname].length - 1][jstypeIndex] = 'isbefore';
349 validate[formname][validate[formname].length - 1][compareToIndex] = compareTo;
352 function addToValidateDateBeforeAllowBlank(formname, name, type, required, msg, compareTo, allowBlank) {
353 addToValidate(formname, name, type,required, msg);
354 validate[formname][validate[formname].length - 1][jstypeIndex] = 'isbefore';
355 validate[formname][validate[formname].length - 1][compareToIndex] = compareTo;
356 validate[formname][validate[formname].length - 1][allowblank] = allowBlank;
359 function addToValidateBinaryDependency(formname, name, type, required, msg, compareTo) {
360 addToValidate(formname, name, type, required, msg);
361 validate[formname][validate[formname].length - 1][jstypeIndex] = 'binarydep';
362 validate[formname][validate[formname].length - 1][compareToIndex] = compareTo;
365 function addToValidateComparison(formname, name, type, required, msg, compareTo) {
366 addToValidate(formname, name, type, required, msg);
367 validate[formname][validate[formname].length - 1][jstypeIndex] = 'comparison';
368 validate[formname][validate[formname].length - 1][compareToIndex] = compareTo;
371 function addToValidateIsInArray(formname, name, type, required, msg, arr, operator) {
372 addToValidate(formname, name, type, required, msg);
373 validate[formname][validate[formname].length - 1][jstypeIndex] = 'in_array';
374 validate[formname][validate[formname].length - 1][arrIndex] = arr;
375 validate[formname][validate[formname].length - 1][operatorIndex] = operator;
378 function addToValidateVerified(formname, name, type, required, msg, arr, operator) {
379 addToValidate(formname, name, type, required, msg);
380 validate[formname][validate[formname].length - 1][jstypeIndex] = 'verified';
383 function addToValidateLessThan(formname, name, type, required, msg, max, max_field_msg) {
384 addToValidate(formname, name, type, required, msg);
385 validate[formname][validate[formname].length - 1][jstypeIndex] = 'less';
386 validate[formname][validate[formname].length - 1][maxIndex] = max;
387 validate[formname][validate[formname].length - 1][altMsgIndex] = max_field_msg;
390 function addToValidateMoreThan(formname, name, type, required, msg, min) {
391 addToValidate(formname, name, type, required, msg);
392 validate[formname][validate[formname].length - 1][jstypeIndex] = 'more';
393 validate[formname][validate[formname].length - 1][minIndex] = min;
397 function removeFromValidate(formname, name) {
398 for(i = 0; i < validate[formname].length; i++)
400 if(validate[formname][i][nameIndex] == name)
402 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
406 function checkValidate(formname, name) {
407 if(validate[formname]){
408 for(i = 0; i < validate[formname].length; i++){
409 if(validate[formname][i][nameIndex] == name){
416 var formsWithFieldLogic=null;
417 var formWithPrecision =null;
418 function addToValidateFieldLogic(formId,minFieldId, maxFieldId, defaultFieldId, lenFieldId,type,msg){
419 this.formId = document.getElementById(formId);
420 this.min=document.getElementById(minFieldId);
421 this.max= document.getElementById(maxFieldId);
422 this._default= document.getElementById(defaultFieldId);
423 this.len = document.getElementById(lenFieldId);
427 //@params: formid- Dom id of the form containing the precision and float fields
428 // valudId- Dom id of the field containing a float whose precision is to be checked.
429 // precisionId- Dom id of the field containing precision value.
430 function addToValidatePrecision(formId, valueId, precisionId){
431 this.form = document.getElementById(formId);
432 this.float = document.getElementById(valueId);
433 this.precision = document.getElementById(precisionId);
436 //function checkLength(value, referenceValue){
440 function isValidPrecision(value, precision){
441 value = trim(value.toString());
447 if( (precision == "0") ){
448 if (value.indexOf(dec_sep)== -1){
455 if(value.charAt(value.length-precision-1) == num_grp_sep){
456 if(value.substr(value.indexOf(dec_sep), 1)==dec_sep){
461 var actualPrecision = value.substr(value.indexOf(dec_sep)+1, value.length).length;
462 return actualPrecision == precision;
464 function toDecimal(original, precision) {
465 precision = (precision == null) ? 2 : precision;
466 num = Math.pow(10, precision);
467 temp = Math.round(original*num)/num;
468 if((temp * 100) % 100 == 0)
470 if((temp * 10) % 10 == 0)
475 function isInteger(s) {
476 if(typeof num_grp_sep != 'undefined' && typeof dec_sep != 'undefined')
478 s = unformatNumberNoParse(s, num_grp_sep, dec_sep).toString();
480 return /^[+-]?[0-9]*$/.test(s) ;
483 function isDecimal(s) {
484 if (typeof s == "string" && s == "") // bug# 46530, this is required in order to
485 return true; // not check empty decimal fields
487 if(typeof num_grp_sep != 'undefined' && typeof dec_sep != 'undefined')
489 s = unformatNumberNoParse(s, num_grp_sep, dec_sep).toString();
491 return /^[+-]?[0-9]*\.?[0-9]*$/.test(s) ;
494 function isNumeric(s) {
498 if (typeof date_reg_positions != "object") var date_reg_positions = {'Y': 1,'m': 2,'d': 3};
499 if (typeof date_reg_format != "string") var date_reg_format = '([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})';
501 function isDate(dtStr) {
503 if(dtStr.length== 0) {
507 // Check that we have numbers
508 myregexp = new RegExp(date_reg_format)
509 if(!myregexp.test(dtStr))
516 var dateParts = dtStr.match(date_reg_format);
517 for(key in date_reg_positions) {
518 index = date_reg_positions[key];
520 m = dateParts[index];
521 } else if(key == 'd') {
522 d = dateParts[index];
524 y = dateParts[index];
528 // Check that date is real
529 var dd = new Date(y,m,0);
530 // reject negative years
533 // reject month less than 1 and greater than 12
536 // reject days less than 1 or days not in month (e.g. February 30th)
537 if (d < 1 || d > dd.getDate())
542 function getDateObject(dtStr) {
543 if(dtStr.length== 0) {
547 myregexp = new RegExp(date_reg_format)
549 if(myregexp.exec(dtStr)) var dt = myregexp.exec(dtStr)
552 var yr = dt[date_reg_positions['Y']];
553 var mh = dt[date_reg_positions['m']];
554 var dy = dt[date_reg_positions['d']];
555 var dtar = dtStr.split(' ');
556 if(typeof(dtar[1])!='undefined' && isTime(dtar[1])) {//if it is a timedate, we should make date1 to have time value
557 var t1 = dtar[1].replace(/am/i,' AM');
558 var t1 = t1.replace(/pm/i,' PM');
559 //bug #37977: where time format 23.00 causes java script error
560 t1=t1.replace(/\./, ':');
561 date1 = new Date(Date.parse(mh+'/'+dy+ '/'+yr+' '+t1));
565 var date1 = new Date();
566 date1.setFullYear(yr); // xxxx 4 char year
567 date1.setMonth(mh-1); // 0-11 Bug 4048: javascript Date obj months are 0-index
568 date1.setDate(dy); // 1-31
573 function isBefore(value1, value2) {
574 var d1 = getDateObject(value1);
575 var d2 = getDateObject(value2);
576 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.
582 function isValidEmail(emailStr) {
584 if(emailStr.length== 0) {
587 // cn: bug 7128, a period at the end of the string mangles checks. (switched to accept spaces and delimiters)
588 var lastChar = emailStr.charAt(emailStr.length - 1);
589 if(!lastChar.match(/[^\.]/i)) {
592 //bug 40068, According to rules in page 6 of http://www.apps.ietf.org/rfc/rfc3696.html#sec-3,
593 //first character of local part of an email address
594 //should not be a period i.e. '.'
596 var firstLocalChar=emailStr.charAt(0);
597 if(firstLocalChar.match(/\./)){
601 //bug 40068, According to rules in page 6 of http://www.apps.ietf.org/rfc/rfc3696.html#sec-3,
602 //last character of local part of an email address
603 //should not be a period i.e. '.'
605 var pos=emailStr.lastIndexOf("@");
606 var localPart = emailStr.substr(0, pos);
607 var lastLocalChar=localPart.charAt(localPart.length - 1);
608 if(lastLocalChar.match(/\./)){
615 while ((results = reg.exec(emailStr)) != null) {
616 var original = results[0];
617 parsedResult = results[0].replace(';', '::;::');
618 emailStr = emailStr.replace (original, parsedResult);
622 while ((results = reg.exec(emailStr)) != null) {
623 var original = results[0];
624 //Check if we were using ; as a delimiter. If so, skip the commas
625 if(original.indexOf("::;::") == -1) {
626 var parsedResult = results[0].replace(',', '::;::');
627 emailStr = emailStr.replace (original, parsedResult);
631 // mfh: bug 15010 - more practical implementation of RFC 2822 from http://www.regular-expressions.info/email.html, modifed to accept CAPITAL LETTERS
632 //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))
635 //bug 40068, According to rules in page 6 of http://www.apps.ietf.org/rfc/rfc3696.html#sec-3,
636 //allowed special characters ! # $ % & ' * + - / = ? ^ _ ` . { | } ~ in local part
637 var emailArr = emailStr.split(/::;::/);
638 for (var i = 0; i < emailArr.length; i++) {
639 var emailAddress = emailArr[i];
640 if (trim(emailAddress) != '') {
641 if(!/^\s*[\w.%+\-&'#!\$\*=\?\^_`\{\}~\/]+@([A-Z0-9-]+\.)*[A-Z0-9-]+\.[\w-]{2,}\s*$/i.test(emailAddress) &&
642 !/^.*<[A-Z0-9._%+\-&'#!\$\*=\?\^_`\{\}~]+?@([A-Z0-9-]+\.)*[A-Z0-9-]+\.[\w-]{2,}>\s*$/i.test(emailAddress)) {
651 function isValidPhone(phoneStr) {
652 if(phoneStr.length== 0) {
655 if(!/^[0-9\-\(\)\s]+$/.test(phoneStr))
659 function isFloat(floatStr) {
660 if(floatStr.length== 0) {
663 if(!(typeof(num_grp_sep)=='undefined' || typeof(dec_sep)=='undefined')) {
664 floatStr = unformatNumberNoParse(floatStr, num_grp_sep, dec_sep).toString();
667 return /^(-)?[0-9\.]+$/.test(floatStr);
669 function isDBName(str) {
674 // must start with a letter
675 if(!/^[a-zA-Z][a-zA-Z\_0-9]*$/.test(str))
679 var time_reg_format = "[0-9]{1,2}\:[0-9]{2}";
680 function isTime(timeStr) {
681 var timeRegex = time_reg_format;
682 // eliminate the am/pm from the external time_reg_format
683 timeRegex = timeRegex.replace(/[ ]*\([^)]*m\)/i, '');
684 if(timeStr.length== 0){
687 //we now support multiple time formats
688 myregexp = new RegExp(timeRegex);
689 if(!myregexp.test(timeStr)) {
696 function inRange(value, min, max) {
697 if (typeof num_grp_sep != 'undefined' && typeof dec_sep != 'undefined')
698 value = unformatNumberNoParse(value, num_grp_sep, dec_sep).toString();
700 if (typeof min == 'number' && value < min)
704 if (typeof max == 'number' && value > max)
711 function bothExist(item1, item2) {
712 if(typeof item1 == 'undefined') { return false; }
713 if(typeof item2 == 'undefined') { return false; }
714 if((item1 == '' && item2 != '') || (item1 != '' && item2 == '') ) { return false; }
718 trim = YAHOO.lang.trim;
721 function check_form(formname) {
722 if (typeof(siw) != 'undefined' && siw
723 && typeof(siw.selectingSomething) != 'undefined' && siw.selectingSomething)
725 return validate_form(formname, '');
728 function add_error_style(formname, input, txt, flash) {
729 var raiseFlag = false;
730 if (typeof flash == "undefined")
733 inputHandle = typeof input == "object" ? input : document.forms[formname][input];
734 style = get_current_bgcolor(inputHandle);
736 // strip off the colon at the end of the warning strings
737 if ( txt.substring(txt.length-1) == ':' )
738 txt = txt.substring(0,txt.length-1)
740 // Bug 28249 - To help avoid duplicate messages for an element, strip off extra messages and
741 // match on the field name itself
742 requiredTxt = SUGAR.language.get('app_strings', 'ERR_MISSING_REQUIRED_FIELDS');
743 invalidTxt = SUGAR.language.get('app_strings', 'ERR_INVALID_VALUE');
744 nomatchTxt = SUGAR.language.get('app_strings', 'ERR_SQS_NO_MATCH_FIELD');
745 matchTxt = txt.replace(requiredTxt,'').replace(invalidTxt,'').replace(nomatchTxt,'');
747 YUI().use('node', function (Y) {
748 Y.one(inputHandle).get('parentNode').get('children').each(function(node, index, nodeList){
749 if(node.hasClass('validation-message') && node.get('text').search(matchTxt)){
756 errorTextNode = document.createElement('div');
757 errorTextNode.className = 'required validation-message';
758 errorTextNode.innerHTML = txt;
759 if ( inputHandle.parentNode.className.indexOf('x-form-field-wrap') != -1 ) {
760 inputHandle.parentNode.parentNode.appendChild(errorTextNode);
763 inputHandle.parentNode.appendChild(errorTextNode);
766 inputHandle.style.backgroundColor = "#FF0000";
767 inputsWithErrors.push(inputHandle);
771 // We only need to setup the flashy-flashy on the first entry, it loops through all fields automatically
772 if ( inputsWithErrors.length == 1 ) {
773 for(var wp = 1; wp <= 10; wp++) {
774 window.setTimeout('fade_error_style(style, '+wp*10+')',1000+(wp*50));
777 if(typeof (window[formname + "_tabs"]) != "undefined") {
778 var tabView = window[formname + "_tabs"];
779 var parentDiv = YAHOO.util.Dom.getAncestorByTagName(inputHandle, "div");
781 var tabs = tabView.get("tabs");
782 for (var i in tabs) {
783 if (tabs[i].get("contentEl") == parentDiv
784 || YAHOO.util.Dom.isAncestor(tabs[i].get("contentEl"), inputHandle))
786 tabs[i].get("labelEl").style.color = "red";
787 if ( inputsWithErrors.length == 1 )
788 tabView.selectTab(i);
793 window.setTimeout("inputsWithErrors[" + (inputsWithErrors.length - 1) + "].style.backgroundColor = '';", 2000);
797 // Catch errors here so we don't allow an incomplete record through the javascript validation
803 * removes all error messages for the current form
805 function clear_all_errors() {
806 for(var wp = 0; wp < inputsWithErrors.length; wp++) {
807 if(typeof(inputsWithErrors[wp]) !='undefined' && typeof inputsWithErrors[wp].parentNode != 'undefined' && inputsWithErrors[wp].parentNode != null) {
808 if ( inputsWithErrors[wp].parentNode.className.indexOf('x-form-field-wrap') != -1 )
810 inputsWithErrors[wp].parentNode.parentNode.removeChild(inputsWithErrors[wp].parentNode.parentNode.lastChild);
814 inputsWithErrors[wp].parentNode.removeChild(inputsWithErrors[wp].parentNode.lastChild);
818 if (inputsWithErrors.length == 0) return;
820 if ( YAHOO.util.Dom.getAncestorByTagName(inputsWithErrors[0], "form") ) {
821 var formname = YAHOO.util.Dom.getAncestorByTagName(inputsWithErrors[0], "form").getAttribute("name");
822 if(typeof (window[formname + "_tabs"]) != "undefined") {
823 var tabView = window[formname + "_tabs"];
825 var tabs = tabView.get("tabs");
826 for (var i in tabs) {
827 if (typeof tabs[i] == "object")
828 tabs[i].get("labelEl").style.color = "";
832 inputsWithErrors = new Array();
836 function get_current_bgcolor(input) {
837 if(input.currentStyle) {// ie
838 style = input.currentStyle.backgroundColor;
839 return style.substring(1,7);
843 styleRGB = document.defaultView.getComputedStyle(input, '').getPropertyValue("background-color");
844 comma = styleRGB.indexOf(',');
845 style += dec2hex(styleRGB.substring(4, comma));
846 commaPrevious = comma;
847 comma = styleRGB.indexOf(',', commaPrevious+1);
848 style += dec2hex(styleRGB.substring(commaPrevious+2, comma));
849 style += dec2hex(styleRGB.substring(comma+2, styleRGB.lastIndexOf(')')));
854 function hex2dec(hex){return(parseInt(hex,16));}
855 var hexDigit=new Array("0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F");
856 function dec2hex(dec){return(hexDigit[dec>>4]+hexDigit[dec&15]);}
858 function fade_error_style(normalStyle, percent) {
859 errorStyle = 'c60c30';
860 var r1 = hex2dec(errorStyle.slice(0,2));
861 var g1 = hex2dec(errorStyle.slice(2,4));
862 var b1 = hex2dec(errorStyle.slice(4,6));
864 var r2 = hex2dec(normalStyle.slice(0,2));
865 var g2 = hex2dec(normalStyle.slice(2,4));
866 var b2 = hex2dec(normalStyle.slice(4,6));
869 var pc = percent / 100;
871 r= Math.floor(r1+(pc*(r2-r1)) + .5);
872 g= Math.floor(g1+(pc*(g2-g1)) + .5);
873 b= Math.floor(b1+(pc*(b2-b1)) + .5);
875 for(var wp = 0; wp < inputsWithErrors.length; wp++) {
876 inputsWithErrors[wp].style.backgroundColor = "#" + dec2hex(r) + dec2hex(g) + dec2hex(b);
880 function isFieldTypeExceptFromEmptyCheck(fieldType)
883 var exemptList = ['bool','file'];
884 for(var i=0;i<exemptList.length;i++)
886 if(fieldType == exemptList[i])
891 function validate_form(formname, startsWith){
892 requiredTxt = SUGAR.language.get('app_strings', 'ERR_MISSING_REQUIRED_FIELDS');
893 invalidTxt = SUGAR.language.get('app_strings', 'ERR_INVALID_VALUE');
895 if ( typeof (formname) == 'undefined')
899 if ( typeof (validate[formname]) == 'undefined')
901 disableOnUnloadEditView(document.forms[formname]);
905 var form = document.forms[formname];
908 var _date = new Date();
909 if(_date.getTime() < (lastSubmitTime + 2000) && startsWith == oldStartsWith) { // ignore submits for the next 2 seconds
912 lastSubmitTime = _date.getTime();
913 oldStartsWith = startsWith;
915 clear_all_errors(); // remove previous error messages
917 inputsWithErrors = new Array();
918 for(var i = 0; i < validate[formname].length; i++){
919 if(validate[formname][i][nameIndex].indexOf(startsWith) == 0){
920 if(typeof form[validate[formname][i][nameIndex]] != 'undefined' && typeof form[validate[formname][i][nameIndex]].value != 'undefined'){
923 //If a field is not required and it is blank or is binarydependant, skip validation.
924 //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
925 if(!validate[formname][i][requiredIndex] && trim(form[validate[formname][i][nameIndex]].value) == '' && (typeof(validate[formname][i][jstypeIndex]) != 'undefined' && validate[formname][i][jstypeIndex] != 'binarydep'))
930 if(validate[formname][i][requiredIndex]
931 && !isFieldTypeExceptFromEmptyCheck(validate[formname][i][typeIndex])
933 if(typeof form[validate[formname][i][nameIndex]] == 'undefined' || trim(form[validate[formname][i][nameIndex]].value) == ""){
934 add_error_style(formname, validate[formname][i][nameIndex], requiredTxt +' ' + validate[formname][i][msgIndex]);
939 switch(validate[formname][i][typeIndex]){
941 if(!isValidEmail(trim(form[validate[formname][i][nameIndex]].value))){
943 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
947 if( !isTime(trim(form[validate[formname][i][nameIndex]].value))){
949 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
951 case 'date': if(!isDate(trim(form[validate[formname][i][nameIndex]].value))){
953 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
958 if(!isDBName(trim(form[validate[formname][i][nameIndex]].value))){
960 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
963 // Bug #49614 : Check value without trimming before
965 if(!isDBName(form[validate[formname][i][nameIndex]].value)){
967 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
973 var file_input = form[validate[formname][i][nameIndex] + '_file'];
974 if( file_input && validate[formname][i][requiredIndex] && trim(file_input.value) == "" && !file_input.disabled ) {
976 add_error_style(formname, validate[formname][i][nameIndex], requiredTxt + " " + validate[formname][i][msgIndex]);
980 if(!isInteger(trim(form[validate[formname][i][nameIndex]].value))){
982 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
986 if(!isDecimal(trim(form[validate[formname][i][nameIndex]].value))){
988 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
993 if(!isFloat(trim(form[validate[formname][i][nameIndex]].value))){
995 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
999 var div_element_id = formname + '_' + form[validate[formname][i][nameIndex]].name + '_operation_div';
1000 var input_elements = YAHOO.util.Selector.query('input', document.getElementById(div_element_id));
1001 var primary_field_id = '';
1002 var validation_passed = false;
1003 var replace_selected = false;
1005 //Loop through the option elements (replace or add currently)
1006 for(t in input_elements) {
1007 if(input_elements[t].type && input_elements[t].type == 'radio' && input_elements[t].checked == true && input_elements[t].value == 'replace') {
1009 //Now find where the primary radio button is and if a value has been set
1010 var radio_elements = YAHOO.util.Selector.query('input[type=radio]', document.getElementById(formname + '_team_name_table'));
1012 for(var x = 0; x < radio_elements.length; x++) {
1013 if(radio_elements[x].name != 'team_name_type') {
1014 primary_field_id = 'team_name_collection_' + radio_elements[x].value;
1015 if(radio_elements[x].checked) {
1016 replace_selected = true;
1017 if(trim(document.forms[formname].elements[primary_field_id].value) != '') {
1018 validation_passed = true;
1021 } else if(trim(document.forms[formname].elements[primary_field_id].value) != '') {
1022 replace_selected = true;
1029 if(replace_selected && !validation_passed) {
1030 add_error_style(formname, primary_field_id, SUGAR.language.get('app_strings', 'ERR_NO_PRIMARY_TEAM_SPECIFIED'));
1035 var table_element_id = formname + '_' + form[validate[formname][i][nameIndex]].name + '_table';
1036 if(document.getElementById(table_element_id)) {
1037 var input_elements = YAHOO.util.Selector.query('input[type=radio]', document.getElementById(table_element_id));
1038 var has_primary = false;
1039 var primary_field_id = form[validate[formname][i][nameIndex]].name + '_collection_0';
1041 for(t in input_elements) {
1042 primary_field_id = form[validate[formname][i][nameIndex]].name + '_collection_' + input_elements[t].value;
1043 if(input_elements[t].type && input_elements[t].type == 'radio' && input_elements[t].checked == true) {
1044 if(document.forms[formname].elements[primary_field_id].value != '') {
1053 var field_id = form[validate[formname][i][nameIndex]].name + '_collection_' + input_elements[0].value;
1054 add_error_style(formname, field_id, SUGAR.language.get('app_strings', 'ERR_NO_PRIMARY_TEAM_SPECIFIED'));
1060 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex]);
1064 if(typeof validate[formname][i][jstypeIndex] != 'undefined'/* && !isError*/){
1066 switch(validate[formname][i][jstypeIndex]){
1067 // Bug #47961 May be validation through callback is best way.
1069 if (typeof validate[formname][i][callbackIndex] == 'function')
1071 var result = validate[formname][i][callbackIndex](formname, validate[formname][i][nameIndex]);
1072 if (result == false)
1075 add_error_style(formname, validate[formname][i][nameIndex], requiredTxt + " " + validate[formname][i][msgIndex]);
1080 if(!inRange(trim(form[validate[formname][i][nameIndex]].value), validate[formname][i][minIndex], validate[formname][i][maxIndex])){
1082 var lbl_validate_range = SUGAR.language.get('app_strings', 'LBL_VALIDATE_RANGE');
1083 if (typeof validate[formname][i][minIndex] == 'number' && typeof validate[formname][i][maxIndex] == 'number')
1085 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] + ")");
1087 else if (typeof validate[formname][i][minIndex] == 'number')
1089 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex] + " " + SUGAR.language.get('app_strings', 'MSG_SHOULD_BE') + ' ' + validate[formname][i][minIndex] + ' ' + SUGAR.language.get('app_strings', 'MSG_OR_GREATER'));
1091 else if (typeof validate[formname][i][maxIndex] == 'number')
1093 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex] + " " + SUGAR.language.get('app_strings', 'MSG_IS_MORE_THAN') + ' ' + validate[formname][i][maxIndex]);
1098 compareTo = form[validate[formname][i][compareToIndex]];
1099 if( typeof compareTo != 'undefined'){
1100 if(trim(compareTo.value) != '' || (validate[formname][i][allowblank] != 'true') ) {
1101 date2 = trim(compareTo.value);
1102 date1 = trim(form[validate[formname][i][nameIndex]].value);
1104 if(trim(date1).length != 0 && !isBefore(date1,date2)){
1107 //jc:#12287 - adding translation for the is not before message
1108 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex] + "(" + date1 + ") " + SUGAR.language.get('app_strings', 'MSG_IS_NOT_BEFORE') + ' ' +date2);
1114 value=unformatNumber(trim(form[validate[formname][i][nameIndex]].value), num_grp_sep, dec_sep);
1115 maximum = parseFloat(validate[formname][i][maxIndex]);
1116 if( typeof maximum != 'undefined'){
1119 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]);
1124 value=unformatNumber(trim(form[validate[formname][i][nameIndex]].value), num_grp_sep, dec_sep);
1125 minimum = parseFloat(validate[formname][i][minIndex]);
1126 if( typeof minimum != 'undefined'){
1129 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'));
1134 compareTo = form[validate[formname][i][compareToIndex]];
1135 if( typeof compareTo != 'undefined') {
1136 item1 = trim(form[validate[formname][i][nameIndex]].value);
1137 item2 = trim(compareTo.value);
1138 if(!bothExist(item1, item2)) {
1140 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex]);
1145 compareTo = form[validate[formname][i][compareToIndex]];
1146 if( typeof compareTo != 'undefined') {
1147 item1 = trim(form[validate[formname][i][nameIndex]].value);
1148 item2 = trim(compareTo.value);
1149 if(!bothExist(item1, item2) || item1 != item2) {
1151 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex]);
1156 arr = eval(validate[formname][i][arrIndex]);
1157 operator = validate[formname][i][operatorIndex];
1158 item1 = trim(form[validate[formname][i][nameIndex]].value);
1159 if (operator.charAt(0) == 'u') {
1160 item1 = item1.toUpperCase();
1161 operator = operator.substring(1);
1162 } else if (operator.charAt(0) == 'l') {
1163 item1 = item1.toLowerCase();
1164 operator = operator.substring(1);
1166 for(j = 0; j < arr.length; j++){
1168 if((operator == "==" && val == item1) || (operator == "!=" && val != item1)){
1170 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
1175 if(trim(form[validate[formname][i][nameIndex]].value) == 'false'){
1176 //Fake an error so form does not submit
1186 /* nsingh: BUG#15102
1187 Check min max default field logic.
1188 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.*/
1189 if(formsWithFieldLogic){
1190 var invalidLogic=false;
1191 if(formsWithFieldLogic.min && formsWithFieldLogic.max && formsWithFieldLogic._default) {
1192 var showErrorsOn={min:{value:'min', show:false, obj:formsWithFieldLogic.min.value},
1193 max:{value:'max',show:false, obj:formsWithFieldLogic.max.value},
1194 _default:{value:'default',show:false, obj:formsWithFieldLogic._default.value},
1195 len:{value:'len', show:false, obj:parseInt(formsWithFieldLogic.len.value,10)}};
1197 var min = (formsWithFieldLogic.min.value !='') ? parseFloat(formsWithFieldLogic.min.value) : 'undef';
1198 var max = (formsWithFieldLogic.max.value !='') ? parseFloat(formsWithFieldLogic.max.value) : 'undef';
1199 var _default = (formsWithFieldLogic._default.value!='')? parseFloat(formsWithFieldLogic._default.value) : 'undef';
1201 /*Check all lengths are <= max size.*/
1202 for(var i in showErrorsOn){
1203 if(showErrorsOn[i].value!='len' && showErrorsOn[i].obj.length > showErrorsOn.len.obj){
1205 showErrorsOn[i].show=true;
1206 showErrorsOn.len.show=true;
1210 if(min!='undef' && max!='undef' && _default!='undef'){
1211 if(!inRange(_default,min,max)){
1213 showErrorsOn.min.show=true;
1214 showErrorsOn.max.show=true;
1215 showErrorsOn._default.show=true;
1218 if(min!='undef' && max!= 'undef' && min > max){
1219 invalidLogic = true;
1220 showErrorsOn.min.show=true;
1221 showErrorsOn.max.show=true;
1223 if(min!='undef' && _default!='undef' && _default < min){
1225 invalidLogic = true;
1226 showErrorsOn.min.show=true;
1227 showErrorsOn._default.show=true;
1229 if(max!='undef' && _default !='undef' && _default>max){
1231 invalidLogic = true;
1232 showErrorsOn.max.show=true;
1233 showErrorsOn._default.show=true;
1238 for(var error in showErrorsOn)
1239 if(showErrorsOn[error].show)
1240 add_error_style(formname,showErrorsOn[error].value, formsWithFieldLogic.msg);
1245 formsWithFieldLogic = null;
1248 if(formWithPrecision){
1249 if (!isValidPrecision(formWithPrecision.float.value, formWithPrecision.precision.value)){
1251 add_error_style(formname, 'default', SUGAR.language.get('app_strings', 'ERR_COMPATIBLE_PRECISION_VALUE'));
1259 if (isError == true) {
1261 if (self.pageYOffset) // all except Explorer
1263 nwX = self.pageXOffset;
1264 seX = self.innerWidth;
1265 nwY = self.pageYOffset;
1266 seY = self.innerHeight;
1268 else if (document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
1270 nwX = document.documentElement.scrollLeft;
1271 seX = document.documentElement.clientWidth;
1272 nwY = document.documentElement.scrollTop;
1273 seY = document.documentElement.clientHeight;
1275 else if (document.body) // all other Explorers
1277 nwX = document.body.scrollLeft;
1278 seX = document.body.clientWidth;
1279 nwY = document.body.scrollTop;
1280 seY = document.body.clientHeight;
1283 var inView = true; // is there an error within viewport of browser
1284 for(var wp = 0; wp < inputsWithErrors.length; wp++) {
1285 var elementCoor = findElementPos(inputsWithErrors[wp]);
1286 if(!(elementCoor.x >= nwX && elementCoor.y >= nwY &&
1287 elementCoor.x <= seX+nwX && elementCoor.y <= seY+nwY)) { // if input is not within viewport, modify for SI bug 52497
1289 scrollToTop = elementCoor.y - 75;
1290 scrollToLeft = elementCoor.x - 75;
1292 else { // on first input within viewport, don't scroll
1298 if(!inView) window.scrollTo(scrollToLeft,scrollToTop);
1303 disableOnUnloadEditView(form);
1310 * This array is used to remember mark status of rows in browse mode
1312 var marked_row = new Array;
1316 * Sets/unsets the pointer and marker in browse mode
1318 * @param object the table row
1319 * @param interger the row number
1320 * @param string the action calling this script (over, out or click)
1321 * @param string the default background color
1322 * @param string the color to use for mouseover
1323 * @param string the color to use for marking a row
1325 * @return boolean whether pointer is set or not
1327 function setPointer(theRow, theRowNum, theAction, theDefaultColor, thePointerColor, theMarkColor) {
1328 var theCells = null;
1330 // 1. Pointer and mark feature are disabled or the browser can't get the
1332 if ((thePointerColor == '' && theMarkColor == '')
1333 || typeof(theRow.style) == 'undefined') {
1337 // 2. Gets the current row and exits if the browser can't get it
1338 if (typeof(document.getElementsByTagName) != 'undefined') {
1339 theCells = theRow.getElementsByTagName('td');
1341 else if (typeof(theRow.cells) != 'undefined') {
1342 theCells = theRow.cells;
1348 // 3. Gets the current color...
1349 var rowCellsCnt = theCells.length;
1350 var domDetect = null;
1351 var currentColor = null;
1352 var newColor = null;
1353 // 3.1 ... with DOM compatible browsers except Opera that does not return
1354 // valid values with "getAttribute"
1355 if (typeof(window.opera) == 'undefined'
1356 && typeof(theCells[0].getAttribute) != 'undefined') {
1357 currentColor = theCells[0].getAttribute('bgcolor');
1360 // 3.2 ... with other browsers
1362 currentColor = theCells[0].style.backgroundColor;
1366 // 4. Defines the new color
1367 // 4.1 Current color is the default one
1368 if (currentColor == ''
1369 || (currentColor!= null && (currentColor.toLowerCase() == theDefaultColor.toLowerCase()))) {
1370 if (theAction == 'over' && thePointerColor != '') {
1371 newColor = thePointerColor;
1373 else if (theAction == 'click' && theMarkColor != '') {
1374 newColor = theMarkColor;
1375 marked_row[theRowNum] = true;
1378 // 4.1.2 Current color is the pointer one
1379 else if (currentColor!= null && (currentColor.toLowerCase() == thePointerColor.toLowerCase())
1380 && (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])) {
1381 if (theAction == 'out') {
1382 newColor = theDefaultColor;
1384 else if (theAction == 'click' && theMarkColor != '') {
1385 newColor = theMarkColor;
1386 marked_row[theRowNum] = true;
1389 // 4.1.3 Current color is the marker one
1390 else if (currentColor!= null && (currentColor.toLowerCase() == theMarkColor.toLowerCase())) {
1391 if (theAction == 'click') {
1392 newColor = (thePointerColor != '')
1395 marked_row[theRowNum] = (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])
1401 // 5. Sets the new color...
1404 // 5.1 ... with DOM compatible browsers except Opera
1406 for (c = 0; c < rowCellsCnt; c++) {
1407 theCells[c].setAttribute('bgcolor', newColor, 0);
1410 // 5.2 ... with other browsers
1412 for (c = 0; c < rowCellsCnt; c++) {
1413 theCells[c].style.backgroundColor = newColor;
1419 } // end of the 'setPointer()' function
1423 * listbox redirection
1425 function goToUrl(selObj, goToLocation) {
1426 eval("document.location.href = '" + goToLocation + "pos=" + selObj.options[selObj.selectedIndex].value + "'");
1431 var json_objects = new Object();
1433 function getXMLHTTPinstance() {
1434 var xmlhttp = false;
1435 var userAgent = navigator.userAgent.toLowerCase() ;
1437 // IE Check supports ActiveX controls
1438 if (userAgent.indexOf("msie") != -1 && userAgent.indexOf("mac") == -1 && userAgent.indexOf("opera") == -1) {
1439 var version = navigator.appVersion.match(/MSIE (.\..)/)[1] ;
1440 if(version >= 5.5 ) {
1442 xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
1446 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
1455 if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
1456 xmlhttp = new XMLHttpRequest();
1461 // NOW LOAD THE OBJECT..
1462 var global_xmlhttp = getXMLHTTPinstance();
1464 function http_fetch_sync(url,post_data) {
1465 global_xmlhttp = getXMLHTTPinstance();
1468 if(typeof(post_data) != 'undefined') method = 'POST';
1470 global_xmlhttp.open(method, url,false);
1473 alert('message:'+e.message+":url:"+url);
1475 if(method == 'POST') {
1476 global_xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
1479 global_xmlhttp.send(post_data);
1481 if (SUGAR.util.isLoginPage(global_xmlhttp.responseText))
1484 var args = {"responseText" : global_xmlhttp.responseText,
1485 "responseXML" : global_xmlhttp.responseXML,
1486 "request_id" : typeof(request_id) != "undefined" ? request_id : 0};
1490 // this is a GET unless post_data is defined
1492 function http_fetch_async(url,callback,request_id,post_data) {
1494 if(typeof(post_data) != 'undefined') {
1499 global_xmlhttp.open(method, url,true);
1502 alert('message:'+e.message+":url:"+url);
1504 if(method == 'POST') {
1505 global_xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
1507 global_xmlhttp.onreadystatechange = function() {
1508 if(global_xmlhttp.readyState==4) {
1509 if(global_xmlhttp.status == 200) {
1510 if (SUGAR.util.isLoginPage(global_xmlhttp.responseText))
1512 var args = {"responseText" : global_xmlhttp.responseText,
1513 "responseXML" : global_xmlhttp.responseXML,
1514 "request_id" : request_id };
1515 callback.call(document,args);
1518 alert("There was a problem retrieving the XML data:\n" + global_xmlhttp.statusText);
1522 global_xmlhttp.send(post_data);
1525 function insert_at_cursor(field, value) {
1527 if (document.selection) {
1529 sel = document.selection.createRange();
1533 else if(field.selectionStart || field.selectionStart == '0') {
1534 var start_pos = field.selectionStart;
1535 var end_pos = field.selectionEnd;
1536 field.value = field.value.substring(0, start_pos) + value + field.value.substring(end_pos, field.value.length);
1539 field.value += value;
1543 function checkParentType(type,button) {
1544 if(button == null) {
1547 if(typeof disabledModules != 'undefined' && typeof(disabledModules[type]) != 'undefined') {
1548 button.disabled='disabled';
1551 button.disabled = false;
1555 function parseDate(input, format) {
1557 format = format.replace(/%/g, '');
1558 sep = format.charAt(1);
1559 yAt = format.indexOf('Y')
1560 // 1-1-06 or 1-12-06 or 1-1-2006 or 1-12-2006
1561 if(date.match(/^\d{1,2}[\/-]\d{1,2}[\/-]\d{2,4}$/) && yAt == 4) {
1562 if(date.match(/^\d{1}[\/-].*$/)) date = '0' + date;
1563 if(date.match(/^\d{2}[\/-]\d{1}[\/-].*$/)) date = date.substring(0,3) + '0' + date.substring(3,date.length);
1564 if(date.match(/^\d{2}[\/-]\d{2}[\/-]\d{2}$/)) date = date.substring(0,6) + '20' + date.substring(6,date.length);
1566 // 06-11-1 or 06-1-1
1567 else if(date.match(/^\d{2,4}[\/-]\d{1,2}[\/-]\d{1,2}$/)) {
1568 if(date.match(/^\d{2}[\/-].*$/)) date = '20' + date;
1569 if(date.match(/^\d{4}[\/-]\d{1}[\/-].*$/)) date = date.substring(0,5) + '0' + date.substring(5,date.length);
1570 if(date.match(/^\d{4}[\/-]\d{2}[\/-]\d{1}$/)) date = date.substring(0,8) + '0' + date.substring(8,date.length);
1572 else if(date.match(/^\d{4,8}$/)) { // digits only
1574 if(date.match(/^\d{8}$/)) digits = 8;// match for 8 digits
1575 else if(date.match(/\d{6}/)) digits = 6;// match for 5 digits
1576 else if(date.match(/\d{4}/)) digits = 4;// match for 5 digits
1577 else if(date.match(/\d{5}/)) digits = 5;// match for 5 digits
1582 case 4: date = '20' + date.substring(0,2) + sep + '0' + date.substring(2, 3) + sep + '0' + date.substring(3,4); break;
1583 case 5: date = '20' + date.substring(0,2) + sep + date.substring(2, 4) + sep + '0' + date.substring(4,5); break;
1584 case 6: date = '20' + date.substring(0,2) + sep + date.substring(2, 4) + sep + date.substring(4,6); break;
1585 case 8: date = date.substring(0,4) + sep + date.substring(4, 6) + sep + date.substring(6,8); break;
1590 case 4: date = '0' + date.substring(0,1) + sep + '20' + date.substring(1, 3) + sep + '0' + date.substring(3,4); break;
1591 case 5: date = date.substring(0,2) + sep + '20' + date.substring(2, 4) + sep + '0' + date.substring(4,5); break;
1592 case 6: date = date.substring(0,2) + sep + '20' + date.substring(2, 4) + sep + date.substring(4,6); break;
1593 case 8: date = date.substring(0,2) + sep + date.substring(2, 6) + sep + date.substring(6,8); break;
1597 case 4: date = '0' + date.substring(0,1) + sep + '0' + date.substring(1, 2) + sep + '20' + date.substring(2,4); break;
1598 case 5: date = '0' + date.substring(0,1) + sep + date.substring(1, 3) + sep + '20' + date.substring(3,5); break;
1599 case 6: date = date.substring(0,2) + sep + date.substring(2, 4) + sep + '20' + date.substring(4,6); break;
1600 case 8: date = date.substring(0,2) + sep + date.substring(2, 4) + sep + date.substring(4,8); break;
1605 date = date.replace(/[\/-]/g, sep);
1609 // find obj's position
1610 function findElementPos(obj) {
1613 if (obj.offsetParent) {
1614 while (obj.offsetParent) {
1615 x += obj.offsetLeft;
1617 obj = obj.offsetParent;
1619 }//if offsetParent exists
1620 else if (obj.x && obj.y) {
1624 return new coordinate(x, y);
1628 // get dimensions of the browser window
1629 function getClientDim() {
1630 var nwX, nwY, seX, seY;
1631 if (self.pageYOffset) // all except Explorer
1633 nwX = self.pageXOffset;
1634 seX = self.innerWidth + nwX;
1635 nwY = self.pageYOffset;
1636 seY = self.innerHeight + nwY;
1638 else if (document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
1640 nwX = document.documentElement.scrollLeft;
1641 seX = document.documentElement.clientWidth + nwX;
1642 nwY = document.documentElement.scrollTop;
1643 seY = document.documentElement.clientHeight + nwY;
1645 else if (document.body) // all other Explorers
1647 nwX = document.body.scrollLeft;
1648 seX = document.body.clientWidth + nwX;
1649 nwY = document.body.scrollTop;
1650 seY = document.body.clientHeight + nwY;
1652 return {'nw' : new coordinate(nwX, nwY), 'se' : new coordinate(seX, seY)};
1656 * stop propagation on events
1658 function freezeEvent(e) {
1660 if (e.preventDefault) e.preventDefault();
1661 e.returnValue = false;
1662 e.cancelBubble = true;
1663 if (e.stopPropagation) e.stopPropagation();
1672 function coordinate(_x, _y) {
1681 return new position(this.x + rh.x, this.y + rh.y);
1685 return new position(this.x + rh.x, this.y + rh.y);
1689 // sends theForm via AJAX and fills in the theDiv
1690 function sendAndRetrieve(theForm, theDiv, loadingStr) {
1691 function success(data) {
1692 document.getElementById(theDiv).innerHTML = data.responseText;
1693 ajaxStatus.hideStatus();
1695 if(typeof loadingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
1696 ajaxStatus.showStatus(loadingStr);
1697 oForm = new YAHOO.util.Element(theForm);
1698 if ( oForm.get('enctype') && oForm.get('enctype') == 'multipart/form-data' ) {
1699 // the second argument is true to indicate file upload.
1700 YAHOO.util.Connect.setForm(theForm, true);
1701 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {upload: success, failure: success});
1703 YAHOO.util.Connect.setForm(theForm);
1704 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
1709 //save the form and redirect
1710 function sendAndRedirect(theForm, loadingStr, redirect_location) {
1711 function success(data) {
1712 if(redirect_location){
1713 location.href=redirect_location;
1715 ajaxStatus.hideStatus();
1717 if(typeof loadingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
1718 ajaxStatus.showStatus(loadingStr);
1719 oForm = new YAHOO.util.Element(theForm);
1720 if ( oForm.get('enctype') && oForm.get('enctype') == 'multipart/form-data' ) {
1721 // the second argument is true to indicate file upload.
1722 YAHOO.util.Connect.setForm(theForm, true);
1723 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {upload: success, failure: success});
1725 YAHOO.util.Connect.setForm(theForm);
1726 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
1731 function saveForm(theForm, theDiv, loadingStr) {
1732 if(check_form(theForm)){
1733 for(i = 0; i < ajaxFormArray.length; i++){
1734 if(ajaxFormArray[i] == theForm){
1735 ajaxFormArray.splice(i, 1);
1738 return sendAndRetrieve(theForm, loadingStr, theDiv);
1744 // Builds a "snapshot" of the form, so we can use it to see if someone has changed it.
1745 function snapshotForm(theForm) {
1746 var snapshotTxt = '';
1747 var elemList = theForm.elements;
1751 for( var i = 0; i < elemList.length ; i++ ) {
1753 if ( typeof(elem.type) == 'undefined' ) {
1757 elemType = elem.type.toLowerCase();
1759 snapshotTxt = snapshotTxt + elem.name;
1761 if ( elemType == 'text' || elemType == 'textarea' || elemType == 'password' ) {
1762 snapshotTxt = snapshotTxt + elem.value;
1764 else if ( elemType == 'select' || elemType == 'select-one' || elemType == 'select-multiple' ) {
1765 var optionList = elem.options;
1766 for ( var ii = 0 ; ii < optionList.length ; ii++ ) {
1767 if ( optionList[ii].selected ) {
1768 snapshotTxt = snapshotTxt + optionList[ii].value;
1772 else if ( elemType == 'radio' || elemType == 'checkbox' ) {
1773 if ( elem.selected ) {
1774 snapshotTxt = snapshotTxt + 'checked';
1777 else if ( elemType == 'hidden' ) {
1778 snapshotTxt = snapshotTxt + elem.value;
1785 function initEditView(theForm) {
1786 if (SUGAR.util.ajaxCallInProgress()) {
1787 window.setTimeout(function(){initEditView(theForm);}, 100);
1791 if ( theForm == null || theForm.id == null ) {
1792 // Not much we can do here.
1796 // we don't need to check if the data is changed in the search popup
1797 if (theForm.id == 'popup_query_form' || theForm.id == 'MassUpdate') {
1800 if ( typeof editViewSnapshots == 'undefined' || editViewSnapshots == null ) {
1801 editViewSnapshots = new Object();
1803 if ( typeof SUGAR.loadedForms == 'undefined' || SUGAR.loadedForms == null) {
1804 SUGAR.loadedForms = new Object();
1807 editViewSnapshots[theForm.id] = snapshotForm(theForm);
1808 SUGAR.loadedForms[theForm.id] = true;
1811 function onUnloadEditView(theForm) {
1813 var dataHasChanged = false;
1814 if ( typeof editViewSnapshots == 'undefined' ) {
1815 // No snapshots, move along
1819 if ( typeof theForm == 'undefined' ) {
1820 // Need to check all editViewSnapshots
1821 for ( var idx in editViewSnapshots ) {
1823 theForm = document.getElementById(idx);
1824 // console.log('DEBUG: Checking all forms '+theForm.id);
1825 if ( theForm == null
1826 || typeof editViewSnapshots[theForm.id] == 'undefined'
1827 || editViewSnapshots[theForm.id] == null
1828 || !SUGAR.loadedForms[theForm.id]) {
1832 var snap = snapshotForm(theForm);
1833 if ( editViewSnapshots[theForm.id] != snap ) {
1834 dataHasChanged = true;
1838 // Just need to check a single form for changes
1839 if ( editViewSnapshots == null || typeof theForm.id == 'undefined' || typeof editViewSnapshots[theForm.id] == 'undefined' || editViewSnapshots[theForm.id] == null ) {
1843 // console.log('DEBUG: Checking one form '+theForm.id);
1844 if ( editViewSnapshots[theForm.id] != snapshotForm(theForm) ) {
1845 // Data has changed.
1846 dataHasChanged = true;
1850 if ( dataHasChanged == true ) {
1851 return SUGAR.language.get('app_strings','WARN_UNSAVED_CHANGES');
1858 function disableOnUnloadEditView(theForm) {
1859 // If you don't pass anything in, it disables all checking
1860 if ( typeof theForm == 'undefined' || typeof editViewSnapshots == 'undefined' || theForm == null || editViewSnapshots == null) {
1861 window.onbeforeunload = null;
1862 editViewSnapshots = null;
1864 // console.log('DEBUG: Disabling all edit view checks');
1867 // Otherwise, it just disables it for this form
1868 if ( typeof(theForm.id) != 'undefined' && typeof(editViewSnapshots[theForm.id]) != 'undefined' ) {
1869 editViewSnapshots[theForm.id] = null;
1872 // console.log('DEBUG : Disabling just checks for '+theForm.id);
1878 * save some forms using an ajax call
1879 * theForms - the ids of all of theh forms to save
1880 * savingStr - the string to display when saving the form
1881 * completeStr - the string to display when the form has been saved
1883 function saveForms( savingStr, completeStr) {
1885 theForms = ajaxFormArray;
1886 function success(data) {
1887 var theForm = document.getElementById(ajaxFormArray[0]);
1888 document.getElementById('multiedit_'+theForm.id).innerHTML = data.responseText;
1889 var saveAllButton = document.getElementById('ajaxsaveall');
1890 ajaxFormArray.splice(index, 1);
1891 if(saveAllButton && ajaxFormArray.length <= 1){
1892 saveAllButton.style.visibility = 'hidden';
1895 if(index == theForms.length){
1896 ajaxStatus.showStatus(completeStr);
1897 window.setTimeout('ajaxStatus.hideStatus();', 2000);
1899 saveAllButton.style.visibility = 'hidden';
1904 if(typeof savingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
1905 ajaxStatus.showStatus(savingStr);
1907 //loop through the forms saving each one
1908 for(i = 0; i < theForms.length; i++){
1909 var theForm = document.getElementById(theForms[i]);
1910 if(check_form(theForm.id)){
1911 theForm.action.value='AjaxFormSave';
1912 YAHOO.util.Connect.setForm(theForm);
1913 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
1915 ajaxStatus.hideStatus();
1917 lastSubmitTime = lastSubmitTime-2000;
1922 // -- start sugarListView class
1923 // js functions used for ListView
1924 function sugarListView() {
1928 sugarListView.prototype.confirm_action = function(del) {
1930 return confirm( SUGAR.language.get('app_strings', 'NTC_DELETE_CONFIRMATION_NUM') + sugarListView.get_num_selected() + SUGAR.language.get('app_strings', 'NTC_DELETE_SELECTED_RECORDS'));
1933 return confirm( SUGAR.language.get('app_strings', 'NTC_UPDATE_CONFIRMATION_NUM') + sugarListView.get_num_selected() + SUGAR.language.get('app_strings', 'NTC_DELETE_SELECTED_RECORDS'));
1937 sugarListView.get_num_selected = function () {
1938 var selectCount = $("input[name='selectCount[]']:first");
1939 if(selectCount.length > 0)
1940 return parseInt(selectCount.val().replace("+", ""));
1944 sugarListView.update_count = function(count, add) {
1945 if(typeof document.MassUpdate != 'undefined') {
1946 the_form = document.MassUpdate;
1947 for(var wp = 0; wp < the_form.elements.length; wp++) {
1948 if(typeof the_form.elements[wp].name != 'undefined' && the_form.elements[wp].name == 'selectCount[]') {
1950 the_form.elements[wp].value = parseInt(the_form.elements[wp].value,10) + count;
1951 if (the_form.select_entire_list.value == 1 && the_form.show_plus.value) {
1952 the_form.elements[wp].value += '+';
1955 if (the_form.select_entire_list.value == 1 && the_form.show_plus.value) {
1956 the_form.elements[wp].value = count + '+';
1958 the_form.elements[wp].value = count;
1965 sugarListView.prototype.use_external_mail_client = function(no_record_txt, module) {
1966 selected_records = sugarListView.get_checks_count();
1967 if(selected_records <1) {
1968 alert(no_record_txt);
1972 if (document.MassUpdate.select_entire_list.value == 1) {
1973 if (totalCount > 10) {
1974 alert(totalCountError);
1979 else if (document.MassUpdate.massall.checked == true)
1983 sugarListView.get_checks();
1985 if(select) { // use selected items
1986 ids = document.MassUpdate.uid.value;
1988 else { // use current page
1989 inputs = document.MassUpdate.elements;
1991 for(i = 0; i < inputs.length; i++) {
1992 if(inputs[i].name == 'mass[]' && inputs[i].checked && typeof(inputs[i].value) != 'function') {
1993 ar.push(inputs[i].value);
1998 YAHOO.util.Connect.asyncRequest("POST", "index.php?", {
1999 success: this.use_external_mail_client_callback
2000 }, SUGAR.util.paramsToUrl({
2003 listViewExternalClient: 1,
2004 action_module: module,
2012 sugarListView.prototype.use_external_mail_client_callback = function(o)
2015 location.href = 'mailto:' + o.responseText;
2018 sugarListView.prototype.send_form_for_emails = function(select, currentModule, action, no_record_txt,action_module,totalCount, totalCountError) {
2019 if ( typeof(SUGAR.config.email_sugarclient_listviewmaxselect) != 'undefined' ) {
2023 maxCount = SUGAR.config.email_sugarclient_listviewmaxselect;
2026 if (document.MassUpdate.select_entire_list.value == 1) {
2027 if (totalCount > maxCount) {
2028 alert(totalCountError);
2033 else if (document.MassUpdate.massall.checked == true)
2038 sugarListView.get_checks();
2039 // create new form to post (can't access action property of MassUpdate form due to action input)
2040 var newForm = document.createElement('form');
2041 newForm.method = 'post';
2042 newForm.action = action;
2043 newForm.name = 'newForm';
2044 newForm.id = 'newForm';
2045 var uidTa = document.createElement('textarea');
2047 uidTa.style.display = 'none';
2049 if(select) { // use selected items
2050 uidTa.value = document.MassUpdate.uid.value;
2052 else { // use current page
2053 inputs = document.MassUpdate.elements;
2055 for(i = 0; i < inputs.length; i++) {
2056 if(inputs[i].name == 'mass[]' && inputs[i].checked && typeof(inputs[i].value) != 'function') {
2057 ar.push(inputs[i].value);
2060 uidTa.value = ar.join(',');
2063 if(uidTa.value == '') {
2064 alert(no_record_txt);
2068 var selectedArray = uidTa.value.split(",");
2069 if(selectedArray.length > maxCount) {
2070 alert(totalCountError);
2073 newForm.appendChild(uidTa);
2075 var moduleInput = document.createElement('input');
2076 moduleInput.name = 'module';
2077 moduleInput.type = 'hidden';
2078 moduleInput.value = currentModule;
2079 newForm.appendChild(moduleInput);
2081 var actionInput = document.createElement('input');
2082 actionInput.name = 'action';
2083 actionInput.type = 'hidden';
2084 actionInput.value = 'Compose';
2085 newForm.appendChild(actionInput);
2087 if (typeof action_module != 'undefined' && action_module!= '') {
2088 var actionModule = document.createElement('input');
2089 actionModule.name = 'action_module';
2090 actionModule.type = 'hidden';
2091 actionModule.value = action_module;
2092 newForm.appendChild(actionModule);
2094 //return_info must follow this pattern."&return_module=Accounts&return_action=index"
2095 if (typeof return_info!= 'undefined' && return_info != '') {
2096 var params= return_info.split('&');
2097 if (params.length > 0) {
2098 for (var i=0;i< params.length;i++) {
2099 if (params[i].length > 0) {
2100 var param_nv=params[i].split('=');
2101 if (param_nv.length==2){
2102 returnModule = document.createElement('input');
2103 returnModule.name = param_nv[0];
2104 returnModule.type = 'hidden';
2105 returnModule.value = param_nv[1];
2106 newForm.appendChild(returnModule);
2113 var isAjaxCall = document.createElement('input');
2114 isAjaxCall.name = 'ajaxCall';
2115 isAjaxCall.type = 'hidden';
2116 isAjaxCall.value = true;
2117 newForm.appendChild(isAjaxCall);
2119 var isListView = document.createElement('input');
2120 isListView.name = 'ListView';
2121 isListView.type = 'hidden';
2122 isListView.value = true;
2123 newForm.appendChild(isListView);
2125 var toPdf = document.createElement('input');
2126 toPdf.name = 'to_pdf';
2127 toPdf.type = 'hidden';
2129 newForm.appendChild(toPdf);
2131 //Grab the Quick Compose package for the listview
2132 YAHOO.util.Connect.setForm(newForm);
2135 success: function(o) {
2136 var resp = YAHOO.lang.JSON.parse(o.responseText);
2137 var quickComposePackage = new Object();
2138 quickComposePackage.composePackage = resp;
2139 quickComposePackage.fullComposeUrl = 'index.php?module=Emails&action=Compose&ListView=true' +
2140 '&uid=' + uidTa.value + '&action_module=' + action_module;
2142 SUGAR.quickCompose.init(quickComposePackage);
2146 YAHOO.util.Connect.asyncRequest('POST','index.php', callback,null);
2148 // awu Bug 18624: Fixing issue where a canceled Export and unselect of row will persist the uid field, clear the field
2149 document.MassUpdate.uid.value = '';
2154 sugarListView.prototype.send_form = function(select, currentModule, action, no_record_txt,action_module,return_info) {
2155 if (document.MassUpdate.select_entire_list.value == 1) {
2157 if(sugarListView.get_checks_count() < 1) {
2158 alert(no_record_txt);
2163 if ( action.indexOf('?') != -1 )
2164 href += '&module=' + currentModule;
2166 href += '?module=' + currentModule;
2169 href += return_info;
2170 var newForm = document.createElement('form');
2171 newForm.method = 'post';
2172 newForm.action = href;
2173 newForm.name = 'newForm';
2174 newForm.id = 'newForm';
2175 var postTa = document.createElement('textarea');
2176 postTa.name = 'current_post';
2177 postTa.value = document.MassUpdate.current_query_by_page.value;
2178 postTa.style.display = 'none';
2179 newForm.appendChild(postTa);
2180 document.MassUpdate.parentNode.appendChild(newForm);
2184 else if (document.MassUpdate.massall.checked == true)
2189 sugarListView.get_checks();
2190 // create new form to post (can't access action property of MassUpdate form due to action input)
2191 var newForm = document.createElement('form');
2192 newForm.method = 'post';
2193 newForm.action = action;
2194 newForm.name = 'newForm';
2195 newForm.id = 'newForm';
2196 var uidTa = document.createElement('textarea');
2198 uidTa.style.display = 'none';
2199 uidTa.value = document.MassUpdate.uid.value;
2201 if(uidTa.value == '') {
2202 alert(no_record_txt);
2206 newForm.appendChild(uidTa);
2208 var moduleInput = document.createElement('input');
2209 moduleInput.name = 'module';
2210 moduleInput.type = 'hidden';
2211 moduleInput.value = currentModule;
2212 newForm.appendChild(moduleInput);
2214 var actionInput = document.createElement('input');
2215 actionInput.name = 'action';
2216 actionInput.type = 'hidden';
2217 actionInput.value = 'index';
2218 newForm.appendChild(actionInput);
2220 if (typeof action_module != 'undefined' && action_module!= '') {
2221 var actionModule = document.createElement('input');
2222 actionModule.name = 'action_module';
2223 actionModule.type = 'hidden';
2224 actionModule.value = action_module;
2225 newForm.appendChild(actionModule);
2227 //return_info must follow this pattern."&return_module=Accounts&return_action=index"
2228 if (typeof return_info!= 'undefined' && return_info != '') {
2229 var params= return_info.split('&');
2230 if (params.length > 0) {
2231 for (var i=0;i< params.length;i++) {
2232 if (params[i].length > 0) {
2233 var param_nv=params[i].split('=');
2234 if (param_nv.length==2){
2235 returnModule = document.createElement('input');
2236 returnModule.name = param_nv[0];
2237 returnModule.type = 'hidden';
2238 returnModule.value = param_nv[1];
2239 newForm.appendChild(returnModule);
2246 document.MassUpdate.parentNode.appendChild(newForm);
2249 // awu Bug 18624: Fixing issue where a canceled Export and unselect of row will persist the uid field, clear the field
2250 document.MassUpdate.uid.value = '';
2254 //return a count of checked row.
2255 sugarListView.get_checks_count = function() {
2258 if(document.MassUpdate.uid.value != '') {
2259 oldUids = document.MassUpdate.uid.value.split(',');
2260 for(uid in oldUids) {
2261 if(typeof(oldUids[uid]) != 'function') {
2262 ar[oldUids[uid]] = 1;
2266 // build associated array of uids, associated array ensures uniqueness
2267 inputs = document.MassUpdate.elements;
2268 for(i = 0; i < inputs.length; i++) {
2269 if(inputs[i].name == 'mass[]') {
2270 ar[inputs[i].value] = (inputs[i].checked) ? 1 : 0; // 0 of it is unchecked
2274 // build regular array of uids
2277 if((typeof(ar[i]) != 'function') && ar[i] == 1) {
2285 // saves the checks on the current page into the uid textarea
2286 sugarListView.get_checks = function() {
2288 if(typeof document.MassUpdate != 'undefined' ){
2289 if(document.MassUpdate.uid.value != '') {
2290 oldUids = document.MassUpdate.uid.value.split(',');
2291 for(uid in oldUids) {
2292 if(typeof(oldUids[uid]) != 'function') {
2293 ar[oldUids[uid]] = 1;
2298 // build associated array of uids, associated array ensures uniqueness
2299 inputs = document.MassUpdate.elements;
2300 for(i = 0; i < inputs.length; i++) {
2301 if(inputs[i].name == 'mass[]') {
2302 ar[inputs[i].value] = (inputs[i].checked) ? 1 : 0; // 0 of it is unchecked
2306 // build regular array of uids
2309 if(typeof(ar[i]) != 'function' && ar[i] == 1) {
2314 document.MassUpdate.uid.value = uids.join(',');
2316 if(uids.length == 0) return false; // return false if no checks to get
2317 return true; // there are saved checks
2322 sugarListView.prototype.order_checks = function(order,orderBy,moduleString){
2323 checks = sugarListView.get_checks();
2324 eval('document.MassUpdate.' + moduleString + '.value = orderBy');
2325 document.MassUpdate.lvso.value = order;
2326 if(typeof document.MassUpdate.massupdate != 'undefined') {
2327 document.MassUpdate.massupdate.value = 'false';
2330 //we must first clear the action of massupdate, change it to index
2331 document.MassUpdate.action.value = document.MassUpdate.return_action.value;
2332 document.MassUpdate.return_module.value='';
2333 document.MassUpdate.return_action.value='';
2334 document.MassUpdate.submit();
2338 sugarListView.prototype.save_checks = function(offset, moduleString) {
2339 checks = sugarListView.get_checks();
2340 if(typeof document.MassUpdate != 'undefined'){
2341 eval('document.MassUpdate.' + moduleString + '.value = offset');
2343 if(typeof document.MassUpdate.massupdate != 'undefined') {
2344 document.MassUpdate.massupdate.value = 'false';
2347 //we must first clear the action of massupdate, change it to index
2348 document.MassUpdate.action.value = document.MassUpdate.return_action.value;
2349 document.MassUpdate.return_module.value='';
2350 document.MassUpdate.return_action.value='';
2351 document.MassUpdate.submit();
2359 sugarListView.prototype.check_item = function(cb, form) {
2361 sugarListView.update_count(1, true);
2364 sugarListView.update_count(-1, true);
2365 if(typeof form != 'undefined' && form != null) {
2366 sugarListView.prototype.updateUid(cb, form);
2369 sugarListView.prototype.toggleSelected();
2372 sugarListView.prototype.toggleSelected = function() {
2374 var numSelected = sugarListView.get_num_selected();
2375 var selectedRecords = document.getElementById("selectedRecordsTop");
2376 var selectActions = document.getElementById("selectActions");
2377 var selectActionsDisabled = document.getElementById("selectActionsDisabled");
2378 if(numSelected > 0) {
2379 $(selectedRecords).removeAttr("style").addClass("show");
2380 $(".selectActionsDisabled").hide();
2381 jQuery('ul[name=selectActions]').each(function () {
2382 jQuery(this).removeAttr("style").addClass("show");
2386 $(selectedRecords).hide();
2387 $(".selectActionsDisabled").removeAttr("style").addClass("show");
2388 jQuery('ul[name=selectActions]').each(function () {
2389 jQuery(this).hide();
2395 /**#28000, remove the unselect record id from MassUpdate.uid **/
2396 sugarListView.prototype.updateUid = function(cb , form){
2397 if(form.name == 'MassUpdate' && form.uid && form.uid.value && cb.value && form.uid.value.indexOf(cb.value) != -1){
2398 if(form.uid.value.indexOf(','+cb.value)!= -1){
2399 form.uid.value = form.uid.value.replace(','+cb.value , '');
2400 }else if(form.uid.value.indexOf(cb.value + ',')!= -1){
2401 form.uid.value = form.uid.value.replace(cb.value + ',' , '');
2402 }else if(form.uid.value.indexOf(cb.value)!= -1){
2403 form.uid.value = form.uid.value.replace(cb.value , '');
2408 sugarListView.prototype.check_entire_list = function(form, field, value, list_count) {
2409 // count number of items
2411 $(document.MassUpdate.massall).each(function(){
2412 $(this).attr('checked', true).attr('disabled', true);
2414 for (i = 0; i < form.elements.length; i++) {
2415 if(form.elements[i].name == field && form.elements[i].disabled == false) {
2416 if(form.elements[i].checked != value) count++;
2417 form.elements[i].checked = value;
2418 form.elements[i].disabled = true;
2421 document.MassUpdate.select_entire_list.value = 1;
2422 sugarListView.update_count(list_count, false);
2423 sugarListView.prototype.toggleSelected();
2426 sugarListView.prototype.check_all = function(form, field, value, pageTotal) {
2427 // count number of items
2429 $(document.MassUpdate.massall).each(function(){$(this).attr('checked', value);});
2430 if (document.MassUpdate.select_entire_list &&
2431 document.MassUpdate.select_entire_list.value == 1)
2433 sugarListView.prototype.toggleSelected();
2434 $(document.MassUpdate.massall).each(function(){$(this).attr('disabled', true);});
2438 $(document.MassUpdate.massall).each(function(){$(this).attr('disabled', false);});
2440 for (i = 0; i < form.elements.length; i++) {
2441 if(form.elements[i].name == field && !(form.elements[i].disabled == true && form.elements[i].checked == false)) {
2442 form.elements[i].disabled = false;
2444 if(form.elements[i].checked != value)
2446 form.elements[i].checked = value;
2448 sugarListView.prototype.updateUid(form.elements[i], form);
2453 sugarListView.update_count(pageTotal);
2455 sugarListView.update_count(count, true);
2457 sugarListView.update_count(-1 * count, true);
2459 sugarListView.prototype.toggleSelected();
2461 sugarListView.check_all = sugarListView.prototype.check_all;
2462 sugarListView.confirm_action = sugarListView.prototype.confirm_action;
2464 sugarListView.prototype.check_boxes = function() {
2465 var inputsCount = 0;
2466 var checkedCount = 0;
2467 var existing_onload = window.onload;
2468 var theForm = document.MassUpdate;
2469 inputs_array = theForm.elements;
2471 if(typeof theForm.uid.value != 'undefined' && theForm.uid.value != "") {
2472 checked_items = theForm.uid.value.split(",");
2473 if (theForm.select_entire_list.value == 1) {
2474 document.MassUpdate.massall.disabled = true;
2475 sugarListView.prototype.toggleSelected();
2476 $("a[name=selectall]:first").click();
2479 for(var wp = 0 ; wp < inputs_array.length; wp++) {
2480 if(inputs_array[wp].name == "mass[]") {
2482 if (theForm.select_entire_list.value == 1) {
2483 inputs_array[wp].checked = true;
2484 inputs_array[wp].disabled = true;
2488 for(i in checked_items) {
2489 if(inputs_array[wp].value == checked_items[i]) {
2491 inputs_array[wp].checked = true;
2492 //Bug#52748: Total # of checked items are calculated in back-end side
2493 //sugarListView.prototype.check_item(inputs_array[wp], document.MassUpdate);
2501 for(var wp = 0 ; wp < inputs_array.length; wp++) {
2502 if(inputs_array[wp].name == "mass[]") {
2503 inputs_array[wp].checked = false;
2504 inputs_array[wp].disabled = false;
2507 if (document.MassUpdate.massall) {
2508 document.MassUpdate.massall.checked = false;
2509 document.MassUpdate.massall.disabled = false;
2511 sugarListView.update_count(0)
2513 if(checkedCount > 0 && checkedCount == inputsCount)
2514 document.MassUpdate.massall.checked = true;
2519 * This function is used in Email Template Module's listview.
2520 * It will check whether the templates are used in Campaing->EmailMarketing.
2521 * If true, it will notify user.
2523 function check_used_email_templates() {
2524 var ids = document.MassUpdate.uid.value;
2526 success:function(r) {
2527 if(r.responseText != '') {
2528 if(!confirm(SUGAR.language.get('app_strings','NTC_TEMPLATES_IS_USED') + r.responseText)) {
2532 document.MassUpdate.submit();
2536 url = "index.php?module=EmailTemplates&action=CheckDeletable&from=ListView&to_pdf=1&records="+ids;
2537 YAHOO.util.Connect.asyncRequest('POST',url, call_back,null);
2541 sugarListView.prototype.send_mass_update = function(mode, no_record_txt, del) {
2542 formValid = check_form('MassUpdate');
2543 if(!formValid && !del) return false;
2546 if (document.MassUpdate.select_entire_list &&
2547 document.MassUpdate.select_entire_list.value == 1)
2552 var ar = new Array();
2556 for(var wp = 0; wp < document.MassUpdate.elements.length; wp++) {
2557 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)+'$');
2558 //when the uid is already in document.MassUpdate.uid.value, we should not add it to ar.
2559 if(typeof document.MassUpdate.elements[wp].name != 'undefined'
2560 && document.MassUpdate.elements[wp].name == 'mass[]'
2561 && document.MassUpdate.elements[wp].checked
2562 && !reg_for_existing_uid.test(document.MassUpdate.uid.value)) {
2563 ar.push(document.MassUpdate.elements[wp].value);
2566 if(document.MassUpdate.uid.value != '') document.MassUpdate.uid.value += ',';
2567 document.MassUpdate.uid.value += ar.join(',');
2568 if(document.MassUpdate.uid.value == '') {
2569 alert(no_record_txt);
2572 if(typeof(current_admin_id)!='undefined' && document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'Users' && (document.MassUpdate.is_admin.value!='' || document.MassUpdate.status.value!='')) {
2573 var reg_for_current_admin_id = new RegExp('^'+current_admin_id+'[\s]*,|,[\s]*'+current_admin_id+'[\s]*,|,[\s]*'+current_admin_id+'$|^'+current_admin_id+'$');
2574 if(reg_for_current_admin_id.test(document.MassUpdate.uid.value)) {
2575 //if current user is admin, we should not allow massupdate the user_type and status of himself
2576 alert(SUGAR.language.get('Users','LBL_LAST_ADMIN_NOTICE'));
2582 var entireInput = document.createElement('input');
2583 entireInput.name = 'entire';
2584 entireInput.type = 'hidden';
2585 entireInput.value = 'index';
2586 document.MassUpdate.appendChild(entireInput);
2587 //confirm(no_record_txt);
2588 if(document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'Users' && (document.MassUpdate.is_admin.value!='' || document.MassUpdate.status.value!='')) {
2589 alert(SUGAR.language.get('Users','LBL_LAST_ADMIN_NOTICE'));
2595 if(!sugarListView.confirm_action(del))
2599 var deleteInput = document.createElement('input');
2600 deleteInput.name = 'Delete';
2601 deleteInput.type = 'hidden';
2602 deleteInput.value = true;
2603 document.MassUpdate.appendChild(deleteInput);
2604 if(document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'EmailTemplates') {
2605 check_used_email_templates();
2611 document.MassUpdate.submit();
2616 sugarListView.prototype.clear_all = function() {
2617 document.MassUpdate.uid.value = '';
2618 document.MassUpdate.select_entire_list.value = 0;
2619 sugarListView.check_all(document.MassUpdate, 'mass[]', false);
2620 $(document.MassUpdate.massall).each(function(){
2621 $(this).attr('checked', false).attr('disabled', false);
2623 sugarListView.update_count(0);
2624 sugarListView.prototype.toggleSelected();
2627 sListView = new sugarListView();
2628 // -- end sugarListView class
2630 // format and unformat numbers
2631 function unformatNumber(n, num_grp_sep, dec_sep) {
2632 var x=unformatNumberNoParse(n, num_grp_sep, dec_sep);
2635 return parseFloat(x);
2640 function unformatNumberNoParse(n, num_grp_sep, dec_sep) {
2641 if(typeof num_grp_sep == 'undefined' || typeof dec_sep == 'undefined') return n;
2642 n = n ? n.toString() : '';
2645 if(num_grp_sep != '')
2647 num_grp_sep_re = new RegExp('\\'+num_grp_sep, 'g');
2648 n = n.replace(num_grp_sep_re, '');
2651 n = n.replace(dec_sep, '.');
2653 if(typeof CurrencySymbols != 'undefined') {
2654 // Need to strip out the currency symbols from the start.
2655 for ( var idx in CurrencySymbols ) {
2656 n = n.replace(CurrencySymbols[idx], '');
2664 // round parameter can be negative for decimal, precision has to be postive
2665 function formatNumber(n, num_grp_sep, dec_sep, round, precision) {
2666 if(typeof num_grp_sep == 'undefined' || typeof dec_sep == 'undefined') return n;
2667 n = n ? n.toString() : '';
2668 if(n.split) n = n.split('.');
2671 if(n.length > 2) return n.join('.'); // that's not a num!
2673 if(typeof round != 'undefined') {
2674 if(round > 0 && n.length > 1) { // round to decimal
2675 n[1] = parseFloat('0.' + n[1]);
2676 n[1] = Math.round(n[1] * Math.pow(10, round)) / Math.pow(10, round);
2677 n[1] = n[1].toString().split('.')[1];
2679 if(round <= 0) { // round to whole number
2680 n[0] = Math.round(parseInt(n[0],10) * Math.pow(10, round)) / Math.pow(10, round);
2685 if(typeof precision != 'undefined' && precision >= 0) {
2686 if(n.length > 1 && typeof n[1] != 'undefined') n[1] = n[1].substring(0, precision); // cut off precision
2688 if(n[1].length < precision) {
2689 for(var wp = n[1].length; wp < precision; wp++) n[1] += '0';
2693 regex = /(\d+)(\d{3})/;
2694 while(num_grp_sep != '' && regex.test(n[0])) n[0] = n[0].toString().replace(regex, '$1' + num_grp_sep + '$2');
2695 return n[0] + (n.length > 1 && n[1] != '' ? dec_sep + n[1] : '');
2698 // --- begin ajax status class
2699 SUGAR.ajaxStatusClass = function() {};
2700 SUGAR.ajaxStatusClass.prototype.statusDiv = null;
2701 SUGAR.ajaxStatusClass.prototype.oldOnScroll = null;
2702 SUGAR.ajaxStatusClass.prototype.shown = false; // state of the status window
2704 // reposition the status div, top and centered
2705 SUGAR.ajaxStatusClass.prototype.positionStatus = function() {
2706 //this.statusDiv.style.top = document.body.scrollTop + 8 + 'px';
2707 statusDivRegion = YAHOO.util.Dom.getRegion(this.statusDiv);
2708 statusDivWidth = statusDivRegion.right - statusDivRegion.left;
2709 this.statusDiv.style.left = YAHOO.util.Dom.getViewportWidth() / 2 - statusDivWidth / 2 + 'px';
2712 // private func, create the status div
2713 SUGAR.ajaxStatusClass.prototype.createStatus = function(text) {
2714 statusDiv = document.createElement('div');
2715 statusDiv.className = 'dataLabel';
2716 statusDiv.id = 'ajaxStatusDiv';
2717 document.body.appendChild(statusDiv);
2718 this.statusDiv = document.getElementById('ajaxStatusDiv');
2721 // public - show the status div with text
2722 SUGAR.ajaxStatusClass.prototype.showStatus = function(text) {
2723 if(!this.statusDiv) {
2724 this.createStatus(text);
2727 this.statusDiv.style.display = '';
2729 this.statusDiv.innerHTML = ' <b>' + text + '</b> ';
2730 this.positionStatus();
2733 this.statusDiv.style.display = '';
2734 if(window.onscroll) this.oldOnScroll = window.onscroll; // save onScroll
2735 window.onscroll = this.positionStatus;
2740 SUGAR.ajaxStatusClass.prototype.hideStatus = function(text) {
2741 if(!this.shown) return;
2743 if(this.oldOnScroll) window.onscroll = this.oldOnScroll;
2744 else window.onscroll = '';
2745 this.statusDiv.style.display = 'none';
2748 SUGAR.ajaxStatusClass.prototype.flashStatus = function(text, time){
2749 this.showStatus(text);
2750 window.setTimeout('ajaxStatus.hideStatus();', time);
2754 var ajaxStatus = new SUGAR.ajaxStatusClass();
2755 // --- end ajax status class
2758 * Unified Search Advanced - for global search
2760 SUGAR.unifiedSearchAdvanced = function() {
2770 SUGAR.unifiedSearchAdvanced.usa_div = document.getElementById('unified_search_advanced_div');
2771 SUGAR.unifiedSearchAdvanced.usa_img = document.getElementById('unified_search_advanced_img');
2773 if(!SUGAR.unifiedSearchAdvanced.usa_div || !SUGAR.unifiedSearchAdvanced.usa_img) return;
2774 var attributes = { height: { to: 300 } };
2775 SUGAR.unifiedSearchAdvanced.anim_open = new YAHOO.util.Anim('unified_search_advanced_div', attributes );
2776 SUGAR.unifiedSearchAdvanced.anim_open.duration = 0.75;
2777 SUGAR.unifiedSearchAdvanced.anim_close = new YAHOO.util.Anim('unified_search_advanced_div', { height: {to: 0} } );
2778 SUGAR.unifiedSearchAdvanced.anim_close.duration = 0.75;
2779 //SUGAR.unifiedSearchAdvanced.anim_close.onComplete.subscribe(function() {SUGAR.unifiedSearchAdvanced.usa_div.style.display = 'none'});
2781 SUGAR.unifiedSearchAdvanced.usa_img._x = YAHOO.util.Dom.getX(SUGAR.unifiedSearchAdvanced.usa_img);
2782 SUGAR.unifiedSearchAdvanced.usa_img._y = YAHOO.util.Dom.getY(SUGAR.unifiedSearchAdvanced.usa_img);
2785 SUGAR.unifiedSearchAdvanced.usa_open = false;
2786 SUGAR.unifiedSearchAdvanced.usa_content = null;
2788 YAHOO.util.Event.addListener('unified_search_advanced_img', 'click', SUGAR.unifiedSearchAdvanced.get_content);
2791 get_content: function(e)
2793 query_string = trim(document.getElementById('query_string').value);
2794 if(query_string != '')
2796 window.location.href = 'index.php?module=Home&action=UnifiedSearch&query_string=' + query_string;
2798 window.location.href = 'index.php?module=Home&action=UnifiedSearch&form_only=true';
2802 animate: function(data) {
2803 ajaxStatus.hideStatus();
2806 SUGAR.unifiedSearchAdvanced.usa_content = data.responseText;
2807 SUGAR.unifiedSearchAdvanced.usa_div.innerHTML = SUGAR.unifiedSearchAdvanced.usa_content;
2809 if(SUGAR.unifiedSearchAdvanced.usa_open) {
2810 document.UnifiedSearch.advanced.value = 'false';
2811 SUGAR.unifiedSearchAdvanced.anim_close.animate();
2814 document.UnifiedSearch.advanced.value = 'true';
2815 SUGAR.unifiedSearchAdvanced.usa_div.style.display = '';
2816 YAHOO.util.Dom.setX(SUGAR.unifiedSearchAdvanced.usa_div, SUGAR.unifiedSearchAdvanced.usa_img._x - 90);
2817 YAHOO.util.Dom.setY(SUGAR.unifiedSearchAdvanced.usa_div, SUGAR.unifiedSearchAdvanced.usa_img._y + 15);
2818 SUGAR.unifiedSearchAdvanced.anim_open.animate();
2820 SUGAR.unifiedSearchAdvanced.usa_open = !SUGAR.unifiedSearchAdvanced.usa_open;
2825 checkUsaAdvanced: function() {
2826 if(document.UnifiedSearch.advanced.value == 'true') {
2827 document.UnifiedSearchAdvanced.query_string.value = document.UnifiedSearch.query_string.value;
2828 document.UnifiedSearchAdvanced.submit();
2835 if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.unifiedSearchAdvanced.init);
2840 * Toggles the header
2842 toggleHeader : function() {
2843 var h = document.getElementById('header');
2847 if(h.style.display == 'none') {
2848 h.style.display = '';
2850 h.style.display = 'none';
2854 alert(SUGAR.language.get("app_strings", "ERR_NO_HEADER_ID"));
2861 * General Sugar Utils
2863 SUGAR.util = function () {
2864 var additionalDetailsCache;
2865 var additionalDetailsCalls;
2866 var additionalDetailsRpcCall;
2869 getAndRemove : function (el) {
2870 if (YAHOO && YAHOO.util && YAHOO.util.Dom)
2871 el = YAHOO.util.Dom.get(el);
2872 else if (typeof (el) == "string")
2873 el = document.getElementById(el);
2874 if (el && el.parentNode)
2875 el.parentNode.removeChild(el);
2879 paramsToUrl : function (params) {
2881 for (var i in params)
2883 if (params.hasOwnProperty(i))
2885 parts.push(encodeURIComponent(i) + '=' + encodeURIComponent(params[i]));
2888 return parts.join("&")+"&";
2890 // Evaluates a script in a global context
2891 // Workarounds based on findings by Jim Driscoll
2892 // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
2893 globalEval: function( data ) {
2894 var rnotwhite = /\S/;
2895 if ( data && rnotwhite.test( data ) ) {
2896 // We use execScript on Internet Explorer
2897 // We use an anonymous function so that context is window
2898 // rather than jQuery in Firefox
2899 ( window.execScript || function( data ) {
2900 window[ "eval" ].call( window, data );
2904 evalScript:function(text){
2906 var waitUntilLoaded = function(){
2907 SUGAR.evalScript_waitCount--;
2908 if (SUGAR.evalScript_waitCount == 0) {
2909 var headElem = document.getElementsByTagName('head')[0];
2910 for ( var i = 0; i < SUGAR.evalScript_evalElem.length; i++) {
2911 var tmpElem = document.createElement('script');
2912 tmpElem.type = 'text/javascript';
2913 tmpElem.text = SUGAR.evalScript_evalElem[i];
2914 headElem.appendChild(tmpElem);
2919 var tmpElem = document.createElement('div');
2920 tmpElem.innerHTML = text;
2921 var results = tmpElem.getElementsByTagName('script');
2922 if (results == null) {
2923 // No scripts found, bail out
2927 var headElem = document.getElementsByTagName('head')[0];
2929 SUGAR.evalScript_waitCount = 0;
2930 SUGAR.evalScript_evalElem = new Array();
2931 for (var i = 0; i < results.length; i++) {
2932 if (typeof(results[i]) != 'object') {
2935 tmpElem = document.createElement('script');
2936 tmpElem.type = 'text/javascript';
2937 if (results[i].src != null && results[i].src != '') {
2938 tmpElem.src = results[i].src;
2940 // Need to defer execution of these scripts until the
2941 // required javascript files are fully loaded
2942 SUGAR.evalScript_evalElem[SUGAR.evalScript_evalElem.length] = results[i].text;
2945 tmpElem.addEventListener('load', waitUntilLoaded);
2946 SUGAR.evalScript_waitCount++;
2947 headElem.appendChild(tmpElem);
2949 // Add some code to handle pages without any external scripts
2950 SUGAR.evalScript_waitCount++;
2953 // Don't try and process things the IE way
2957 var objRegex = /<\s*script([^>]*)>((.|\s|\v|\0)*?)<\s*\/script\s*>/igm;
2959 var result = objRegex.exec(text);
2960 while(result && result.index > lastIndex){
2961 lastIndex = result.index
2963 // Bug #49205 : Subpanels fail to load when selecting subpanel tab
2964 // Change approach to handle javascripts included to body of ajax response.
2965 // To load & run javascripts and inline javascript in correct order load them as synchronous requests
2966 // JQuery library uses this approach to eval scripts
2967 if(result[1].indexOf("src=") > -1){
2968 var srcRegex = /.*src=['"]([a-zA-Z0-9_\-\&\/\.\?=:-]*)['"].*/igm;
2969 var srcResult = result[1].replace(srcRegex, '$1');
2971 // Check is ulr cross domain or not
2972 var r1 = /:\/\//igm;
2973 if ( r1.test(srcResult) && srcResult.indexOf(window.location.hostname) == -1 )
2975 // if script is cross domain it cannot be loaded via ajax request
2976 // try load script asynchronous by creating script element in the body
2977 // YUI 3.3 doesn't allow load scrips synchronously
2979 YUI().use('get', function (Y)
2981 var url = srcResult;
2982 Y.Get.script(srcResult,
2985 onSuccess : function(o) { },
2986 onFailure: function(o) { },
2987 onTimeout: function(o) { }
2990 // TODO: for YUI 3.5 - load scripts as script object synchronous
2992 YUI().use('get', function (Y) {
2993 var url = srcResult;
2994 Y.Get.js([{url: url, async: false}], function (err) {});
3000 // Bug #49205 : Subpanels fail to load when selecting subpanel tab
3001 // Create a YUI instance using the io-base module.
3002 (function (srcResult) {
3003 YUI().use("io-base",function(Y)
3010 success:function(transactionid,response,arguments)
3012 SUGAR.util.globalEval(response.responseText);
3016 // Call synchronous request to load javascript content
3017 // restonse will be processed in success function
3018 response=Y.io(srcResult,cfg);
3023 // Bug #49205 : Subpanels fail to load when selecting subpanel tab
3024 // execute script in global context
3025 // Bug #57288 : don't eval with html comment-out script; that causes syntax error in IE
3026 var srcRegex = /<!--([\s\S]*?)-->/;
3027 var srcResult = srcRegex.exec(result[2]);
3028 if (srcResult && srcResult.index > -1)
3030 SUGAR.util.globalEval(srcResult[1]);
3034 SUGAR.util.globalEval(result[2]);
3039 if(typeof(console) != "undefined" && typeof(console.log) == "function")
3041 console.log("error adding script");
3043 console.log(result);
3046 result = objRegex.exec(text);
3050 * Gets the sidebar object
3051 * @return object pointer to the sidebar element
3053 getLeftColObj: function() {
3054 leftColObj = document.getElementById('leftCol');
3055 while(leftColObj.nodeName != 'TABLE') {
3056 leftColObj = leftColObj.firstChild;
3058 leftColTable = leftColObj;
3059 leftColTd = leftColTable.getElementsByTagName('td')[0];
3060 leftColTdRegion = YAHOO.util.Dom.getRegion(leftColTd);
3061 leftColTd.style.width = (leftColTdRegion.right - leftColTdRegion.left) + 'px';
3066 * Fills the shortcut menu placeholders w/ actual content
3067 * Call this on load event
3069 * @param shortcutContent Array array of content to fill in
3071 fillShortcuts: function(e, shortcutContent) {
3074 // don't do this if leftCol isn't available
3075 if (document.getElementById('leftCol') == undefined) { return; }
3077 spans = document.getElementById('leftCol').getElementsByTagName('span');
3078 hideCol = document.getElementById('HideMenu').getElementsByTagName('span');
3079 w = spans.length + 1;
3081 spans[w] = hideCol[i];
3084 for(je in shortcutContent) {
3086 if(typeof spans[wp].innerHTML != 'undefined' && spans[wp].innerHTML == ('wp_shortcut_fill_' + je)) {
3087 if(typeof spans[wp].parentNode.parentNode == 'object') {
3088 if(typeof spans[wp].parentNode.parentNode.onclick != 'undefined') {
3089 spans[wp].parentNode.parentNode.onclick = null;
3091 // If the wp_shortcut span is contained by an A tag, replace the A with a DIV.
3092 if(spans[wp].parentNode.tagName == 'A' && !isIE) {
3093 var newDiv = document.createElement('DIV');
3094 var parentAnchor = spans[wp].parentNode;
3096 spans[wp].parentNode.parentNode.style.display = 'none';
3098 // Copy styles over to the new container div
3099 if(window.getComputedStyle) {
3100 var parentStyle = window.getComputedStyle(parentAnchor, '');
3101 for(var styleName in parentStyle) {
3102 if(typeof parentStyle[styleName] != 'function'
3103 && styleName != 'display'
3104 && styleName != 'borderWidth'
3105 && styleName != 'visibility') {
3107 newDiv.style[styleName] = parentStyle[styleName];
3109 // Catches .length and .parentRule, and others
3115 // Replace the A with the DIV
3116 newDiv.appendChild(spans[wp]);
3117 parentAnchor.parentNode.replaceChild(newDiv, parentAnchor);
3119 spans[wp].parentNode.parentNode.style.display = '';
3122 spans[wp].innerHTML = shortcutContent[je]; // fill w/ content
3123 if(spans[wp].style) spans[wp].style.display = '';
3129 * Make an AJAX request.
3131 * @param url string resource to load
3132 * @param theDiv string id of element to insert loaded data into
3133 * @param postForm string if set, a POST request will be made to resource specified by url using the form named by postForm
3134 * @param callback string name of function to invoke after HTTP response is recieved
3135 * @param callbackParam any parameter to pass to callback when invoked
3136 * @param appendMode bool if true, HTTP response will be appended to the contents of theDiv, or else contents will be overriten.
3138 retrieveAndFill: function(url, theDiv, postForm, callback, callbackParam, appendMode) {
3139 if(typeof theDiv == 'string') {
3141 theDiv = document.getElementById(theDiv);
3148 var success = function(data) {
3149 if (typeof theDiv != 'undefined' && theDiv != null)
3152 if (typeof appendMode != 'undefined' && appendMode)
3154 theDiv.insertAdjacentHTML('beforeend', data.responseText);
3158 theDiv.innerHTML = data.responseText;
3165 if (typeof callback != 'undefined' && callback != null) callback(callbackParam);
3168 if(typeof postForm == 'undefined' || postForm == null) {
3169 var cObj = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
3172 YAHOO.util.Connect.setForm(postForm);
3173 var cObj = YAHOO.util.Connect.asyncRequest('POST', url, {success: success, failure: success});
3176 checkMaxLength: function() { // modified from http://www.quirksmode.org/dom/maxlength.html
3177 var maxLength = this.getAttribute('maxlength');
3178 var currentLength = this.value.length;
3179 if (currentLength > maxLength) {
3180 this.value = this.value.substring(0, maxLength);
3185 * Adds maxlength attribute to textareas
3187 setMaxLength: function() { // modified from http://www.quirksmode.org/dom/maxlength.html
3188 var x = document.getElementsByTagName('textarea');
3189 for (var i=0;i<x.length;i++) {
3190 if (x[i].getAttribute('maxlength')) {
3191 x[i].onkeyup = x[i].onchange = SUGAR.util.checkMaxLength;
3198 * Renders Query UI Help Dialog
3200 showHelpTips: function(el,helpText,myPos,atPos,id) {
3201 if(myPos == undefined || myPos == "") {
3204 if(atPos == undefined || atPos == "") {
3205 atPos = "right top";
3208 var pos = $(el).offset(),
3209 ofWidth = $(el).width(),
3210 elmId = id || 'helpTip' + pos.left + '_' + ofWidth,
3211 $dialog = elmId ? ( $("#"+elmId).length > 0 ? $("#"+elmId) : $('<div></div>').attr("id", elmId) ) : $('<div></div>');
3212 $dialog.html(helpText)
3215 title: SUGAR.language.get('app_strings', 'LBL_HELP'),
3224 var width = $dialog.dialog( "option", "width" );
3226 if((pos.left + ofWidth) - 40 < width) {
3227 $dialog.dialog("option","position",{my: 'left top',at: 'right top',of: $(el)}) ;
3229 $dialog.dialog('open');
3230 $(".ui-dialog").appendTo("#content");
3234 getStaticAdditionalDetails: function(el, body, caption, show_buttons) {
3235 if(typeof show_buttons == "undefined") {
3236 show_buttons = false;
3239 $(".ui-dialog").find(".open").dialog("close");
3241 var $dialog = $('<div class="open"></div>')
3255 $(".ui-dialog").find('.ui-dialog-titlebar-close').css("display","none");
3256 $(".ui-dialog").find('.ui-dialog-title').css("width","100%");
3260 var width = $dialog.dialog( "option", "width" );
3261 var pos = $(el).offset();
3262 var ofWidth = $(el).width();
3264 if((pos.left + ofWidth) - 40 < width) {
3265 $dialog.dialog("option","position",{my: 'left top',at: 'right top',of: $(el)}) ;
3268 $dialog.dialog('open');
3269 $(".ui-dialog").appendTo("#content");
3273 closeStaticAdditionalDetails: function() {
3274 $(".ui-dialog").find(".open").dialog("close");
3277 * Retrieves additional details dynamically
3279 getAdditionalDetails: function(bean, id, spanId, show_buttons) {
3280 if(typeof show_buttons == "undefined")
3281 show_buttons = false;
3282 var el = '#'+spanId;
3284 oReturn = function(body, caption, width, theme) {
3286 $(".ui-dialog").find(".open").dialog("close");
3288 var $dialog = $('<div class="open"></div>')
3301 $(".ui-dialog").find('.ui-dialog-titlebar-close').css("display","none");
3302 $(".ui-dialog").find('.ui-dialog-title').css("width","100%");
3305 var width = $dialog.dialog( "option", "width" );
3306 var pos = $(el).offset();
3307 var ofWidth = $(el).width();
3309 if((pos.left + ofWidth) - 40 < width) {
3310 $dialog.dialog("option","position",{my: 'left top',at: 'right top',of: $(el)}) ;
3313 $dialog.dialog('open');
3314 $(".ui-dialog").appendTo("#content");
3317 success = function(data) {
3318 eval(data.responseText);
3320 SUGAR.util.additionalDetailsCache[id] = new Array();
3321 SUGAR.util.additionalDetailsCache[id]['body'] = result['body'];
3322 SUGAR.util.additionalDetailsCache[id]['caption'] = result['caption'];
3323 SUGAR.util.additionalDetailsCache[id]['width'] = result['width'];
3324 SUGAR.util.additionalDetailsCache[id]['theme'] = result['theme'];
3325 ajaxStatus.hideStatus();
3326 return oReturn(SUGAR.util.additionalDetailsCache[id]['body'], SUGAR.util.additionalDetailsCache[id]['caption'], SUGAR.util.additionalDetailsCache[id]['width'], SUGAR.util.additionalDetailsCache[id]['theme']);
3329 if(typeof SUGAR.util.additionalDetailsCache[id] != 'undefined')
3330 return oReturn(SUGAR.util.additionalDetailsCache[id]['body'], SUGAR.util.additionalDetailsCache[id]['caption'], SUGAR.util.additionalDetailsCache[id]['width'], SUGAR.util.additionalDetailsCache[id]['theme']);
3332 if(typeof SUGAR.util.additionalDetailsCalls[id] != 'undefined') // call already in progress
3334 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_LOADING'));
3335 url = 'index.php?to_pdf=1&module=Home&action=AdditionalDetailsRetrieve&bean=' + bean + '&id=' + id;
3337 url += '&show_buttons=true';
3338 SUGAR.util.additionalDetailsCalls[id] = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
3342 SUGAR.util.additionalDetailsRpcCall = window.setTimeout('go()', 250);
3344 clearAdditionalDetailsCall: function() {
3345 if(typeof SUGAR.util.additionalDetailsRpcCall == 'number') window.clearTimeout(SUGAR.util.additionalDetailsRpcCall);
3348 * A function that extends functionality from parent to child.
3350 extend : function(subc, superc, overrides) {
3351 subc.prototype = new superc; // set the superclass
3354 for (var i in overrides) subc.prototype[i] = overrides[i];
3357 hrefURL : function(url) {
3359 // IE needs special treatment since otherwise it would not pass Referer
3360 var trampoline = document.createElement('a');
3361 trampoline.href = url;
3362 document.body.appendChild(trampoline);
3364 document.body.removeChild(trampoline);
3366 document.location.href = url;
3370 openWindow : function(URL, windowName, windowFeatures) {
3372 // IE needs special treatment since otherwise it would not pass Referer
3373 win = window.open('', windowName, windowFeatures);
3374 var trampoline = document.createElement('a');
3375 trampoline.href = URL;
3376 trampoline.target = windowName;
3377 document.body.appendChild(trampoline);
3379 document.body.removeChild(trampoline);
3381 win = window.open(URL, windowName, windowFeatures);
3385 //Reset the scroll on the window
3390 //Based on YUI onAvailible, but will use any boolean function instead of an ID
3391 doWhen : function(condition, fn, params, scope)
3393 this._doWhenStack.push({
3397 overrideContext: scope
3400 this._doWhenretryCount = 50;
3401 this._startDoWhenInterval();
3404 _startDoWhenInterval : function(){
3405 if (!this._doWhenInterval) {
3406 this._doWhenInterval = YAHOO.lang.later(50, this, this._doWhenCheck, null, true);
3410 _doWhenInterval : false,
3411 _doWhenCheck : function() {
3412 if (this._doWhenStack.length === 0) {
3413 this._doWhenretryCount = 0;
3414 if (this._doWhenInterval) {
3415 // clearInterval(this._interval);
3416 this._doWhenInterval.cancel();
3417 this._doWhenInterval = null;
3422 if (this._doWhenLocked) {
3427 // Hold off if DOMReady has not fired and check current
3428 // readyState to protect against the IE operation aborted
3430 if (!YAHOO.util.Event.DOMReady) {
3431 this._startDoWhenInterval();
3436 this._doWhenLocked = true;
3439 // keep trying until after the page is loaded. We need to
3440 // check the page load state prior to trying to bind the
3441 // elements so that we can be certain all elements have been
3442 // tested appropriately
3443 var tryAgain = YAHOO.util.Event.DOMReady;
3445 tryAgain = (this._doWhenretryCount > 0 && this._doWhenStack.length > 0);
3451 var executeItem = function (context, item) {
3452 if (item.overrideContext) {
3453 if (item.overrideContext === true) {
3456 context = item.overrideContext;
3460 item.fn.call(context, item.obj);
3464 var i, len, item, test;
3466 // onAvailable onContentReady
3467 for (i=0, len=this._doWhenStack.length; i<len; i=i+1) {
3468 item = this._doWhenStack[i];
3471 if ((typeof(test) == "string" && eval(test)) || (typeof(test) == "function" && test())) {
3472 executeItem(this, item);
3473 this._doWhenStack[i] = null;
3476 notAvail.push(item);
3481 this._doWhenretryCount--;
3484 for (i=this._doWhenStack.length-1; i>-1; i--) {
3485 item = this._doWhenStack[i];
3486 if (!item || !item.check) {
3487 this._doWhenStack.splice(i, 1);
3490 this._startDoWhenInterval();
3492 if (this._doWhenInterval) {
3493 // clearInterval(this._interval);
3494 this._doWhenInterval.cancel();
3495 this._doWhenInterval = null;
3498 this._doWhenLocked = false;
3500 buildAccessKeyLabels : function() {
3501 if (typeof(Y.env.ua) !== 'undefined'){
3503 browserOS = Y.env.ua['os'];
3504 isIE = Y.env.ua['ie'];
3505 isCR = Y.env.ua['chrome'];
3506 isFF = Y.env.ua['gecko'];
3507 isWK = Y.env.ua['webkit'];
3508 isOP = Y.env.ua['opera'];
3511 //first determine the OS
3512 if(browserOS=='macintosh'){
3513 //we got a mac, lets use the mac specific commands while we check the browser
3515 //IE on a Mac? Not possible, but let's assign alt anyways for completions sake
3516 controlKey = 'Alt+';
3517 }else if(isWK || isFF){
3518 //Chrome or safari on a mac
3519 //firefox moved to webkit standard starting with FF14
3520 controlKey = 'Ctrl+Opt+';
3523 controlKey = 'Shift+Esc: ';
3525 //default for everything else on a mac
3526 controlKey = 'Ctrl+';
3529 //this is not a mac so let's use the windows/unix commands while we check the browser
3531 //FF on windows/unix
3532 controlKey = 'Alt+Shift+';
3534 //Opera on windows/unix
3535 controlKey = 'Shift+Esc: ';
3537 //this is the default for safari, IE and Chrome
3538 //if this is webkit and is NOT google, then we are most likely looking at Safari
3539 controlKey = 'Alt+';
3544 //now lets retrieve all elements of type input
3545 allButtons = document.getElementsByTagName('input');
3546 //iterate through list and modify title if the accesskey is not empty
3547 for(i=0;i<allButtons.length;i++){
3548 if(allButtons[i].getAttribute('accesskey') && allButtons[i].getAttribute('type') && allButtons[i].getAttribute('type')=='button'){
3549 allButtons[i].setAttribute('title',allButtons[i].getAttribute('title')+' ['+controlKey+allButtons[i].getAttribute('accesskey')+']');
3552 //now change the text in the help div
3553 $("#shortcuts_dialog").html(function(i, text) {
3554 return text.replace(/Alt\+/g,controlKey);
3556 }// end if (typeof(Y.env.ua) !== 'undefined')
3557 }//end buildAccessKeyLabels()
3560 SUGAR.util.additionalDetailsCache = new Array();
3561 SUGAR.util.additionalDetailsCalls = new Array();
3562 if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.util.setMaxLength); // allow textareas to obey maxlength attrib
3564 SUGAR.savedViews = function() {
3565 var selectedOrderBy;
3566 var selectedSortOrder;
3569 var columnsMeta; // meta data for the display columns
3572 setChooser: function() {
3574 var displayColumnsDef = new Array();
3575 var hideTabsDef = new Array();
3577 var left_td = document.getElementById('display_tabs_td');
3578 if(typeof left_td == 'undefined' || left_td == null) return; // abort!
3579 var right_td = document.getElementById('hide_tabs_td');
3581 var displayTabs = left_td.getElementsByTagName('select')[0];
3582 var hideTabs = right_td.getElementsByTagName('select')[0];
3584 for(i = 0; i < displayTabs.options.length; i++) {
3585 displayColumnsDef.push(displayTabs.options[i].value);
3588 if(typeof hideTabs != 'undefined') {
3589 for(i = 0; i < hideTabs.options.length; i++) {
3590 hideTabsDef.push(hideTabs.options[i].value);
3593 if (!SUGAR.savedViews.clearColumns)
3594 document.getElementById('displayColumnsDef').value = displayColumnsDef.join('|');
3595 document.getElementById('hideTabsDef').value = hideTabsDef.join('|');
3598 select: function(saved_search_select) {
3599 for(var wp = 0; wp < document.search_form.saved_search_select.options.length; wp++) {
3600 if(typeof document.search_form.saved_search_select.options[wp].value != 'undefined' &&
3601 document.search_form.saved_search_select.options[wp].value == saved_search_select) {
3602 document.search_form.saved_search_select.selectedIndex = wp;
3603 document.search_form.ss_delete.style.display = '';
3604 document.search_form.ss_update.style.display = '';
3608 saved_search_action: function(action, delete_lang) {
3609 if(action == 'delete') {
3610 if(!confirm(delete_lang)) return;
3612 if(action == 'save') {
3613 if(document.search_form.saved_search_name.value.replace(/^\s*|\s*$/g, '') == '') {
3614 alert(SUGAR.language.get('app_strings', 'LBL_SAVED_SEARCH_ERROR'));
3619 // This check is needed for the Activities module (Calls/Meetings/Tasks).
3620 if (document.search_form.saved_search_action)
3622 document.search_form.saved_search_action.value = action;
3623 document.search_form.search_module.value = document.search_form.module.value;
3624 document.search_form.module.value = 'SavedSearch';
3625 // Bug 31922 - Make sure to specify that we want to hit the index view here of
3626 // the SavedSearch module, since the ListView doesn't have the logic to save the
3627 // search and redirect back
3628 document.search_form.action.value = 'index';
3630 SUGAR.ajaxUI.submitForm(document.search_form);
3632 shortcut_select: function(selectBox, module) {
3634 selecturl = 'index.php?module=SavedSearch&search_module=' + module + '&action=index&saved_search_select=' + selectBox.options[selectBox.selectedIndex].value
3635 //add searchFormTab to url if it is available. This determines what tab to render
3636 if(typeof(document.getElementById('searchFormTab'))!='undefined'){
3637 selecturl = selecturl + '&searchFormTab=' + document.search_form.searchFormTab.value;
3639 //add showSSDIV to url if it is available. This determines whether saved search sub form should
3640 //be rendered open or not
3641 if(document.getElementById('showSSDIV') && typeof(document.getElementById('showSSDIV') !='undefined')){
3642 selecturl = selecturl + '&showSSDIV='+document.getElementById('showSSDIV').value;
3644 //use created url to navigate
3645 document.location.href = selecturl;
3647 handleForm: function() {
3648 SUGAR.tabChooser.movementCallback = function(left_side, right_side) {
3649 while(document.getElementById('orderBySelect').childNodes.length != 0) { // clear out order by options
3650 document.getElementById('orderBySelect').removeChild(document.getElementById('orderBySelect').lastChild);
3653 var selectedIndex = 0;
3654 var nodeCount = -1; // need this because the counter i also includes "undefined" nodes
3655 // which was breaking Calls and Meetings
3657 for(i in left_side.childNodes) { // fill in order by options
3658 if(typeof left_side.childNodes[i].nodeName != 'undefined' &&
3659 left_side.childNodes[i].nodeName.toLowerCase() == 'option' &&
3660 typeof SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value] != 'undefined' && // check if column is sortable
3661 typeof SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value]['sortable'] == 'undefined' &&
3662 SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value]['sortable'] != false) {
3664 optionNode = document.createElement('option');
3665 optionNode.value = left_side.childNodes[i].value;
3666 optionNode.innerHTML = left_side.childNodes[i].innerHTML;
3667 document.getElementById('orderBySelect').appendChild(optionNode);
3668 if(optionNode.value == SUGAR.savedViews.selectedOrderBy)
3669 selectedIndex = nodeCount;
3672 // Firefox needs this to be set after all the option nodes are created.
3673 document.getElementById('orderBySelect').selectedIndex = selectedIndex;
3675 SUGAR.tabChooser.movementCallback(document.getElementById('display_tabs_td').getElementsByTagName('select')[0]);
3677 // This check is needed for the Activities module (Calls/Meetings/Tasks).
3678 if (document.search_form.orderBy)
3679 document.search_form.orderBy.options.value = SUGAR.savedViews.selectedOrderBy;
3682 if(SUGAR.savedViews.selectedSortOrder == 'DESC') document.getElementById('sort_order_desc_radio').checked = true;
3683 else document.getElementById('sort_order_asc_radio').checked = true;
3688 SUGAR.searchForm = function() {
3691 // searchForm tab selector util
3692 searchFormSelect: function(view, previousView) {
3693 var module = view.split('|')[0];
3694 var theView = view.split('|')[1];
3696 var handleDisplay = function() { // hide other divs
3697 document.search_form.searchFormTab.value = theView;
3698 patt = module+"(.*)SearchForm$";
3699 divId=document.search_form.getElementsByTagName('div');
3700 // Hide all the search forms and retrive the name of the previous search tab (useful for the first load because previousView is empty)
3701 for (i=0;i<divId.length;i++){
3702 if(divId[i].id.match(module)==module){
3703 if(divId[i].id.match('SearchForm')=='SearchForm'){
3704 if(document.getElementById(divId[i].id).style.display == ''){
3705 previousTab=divId[i].id.match(patt)[1];
3707 document.getElementById(divId[i].id).style.display = 'none';
3712 //clear thesearch form accesekeys and reset them to the appropriate link
3713 adv = document.getElementById('advanced_search_link');
3714 bas = document.getElementById('basic_search_link');
3715 adv.setAttribute('accesskey','');
3716 bas.setAttribute('accesskey','');
3717 a_key = SUGAR.language.get("app_strings", "LBL_ADV_SEARCH_LNK_KEY");
3719 //reset the ccesskey based on theview
3720 if(theView === 'advanced_search'){
3722 bas.setAttribute('accesskey',a_key);
3724 adv.setAttribute('accesskey',a_key);
3727 // show the good search form.
3728 document.getElementById(module + theView + 'SearchForm').style.display = '';
3729 //if its not the first tab show there is a previous tab.
3731 thepreviousView=previousView.split('|')[1];
3734 thepreviousView=previousTab;
3736 thepreviousView=thepreviousView.replace(/_search/, "");
3737 // Process to retrieve the completed field from one tab to an other.
3738 for(num in document.search_form.elements) {
3739 if(document.search_form.elements[num]) {
3740 el = document.search_form.elements[num];
3741 pattern="^(.*)_"+thepreviousView+"$";
3742 if(typeof el.type != 'undefined' && typeof el.name != 'undefined' && el.name.match(pattern)) {
3743 advanced_input_name = el.name.match(pattern)[1]; // strip
3744 advanced_input_name = advanced_input_name+"_"+theView.replace(/_search/, "");
3745 if(typeof document.search_form[advanced_input_name] != 'undefined') // if advanced input of same name exists
3746 SUGAR.searchForm.copyElement(advanced_input_name, el);
3752 // if tab is not cached
3753 if(document.getElementById(module + theView + 'SearchForm').innerHTML == '') {
3754 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_LOADING'));
3755 var success = function(data) {
3756 document.getElementById(module + theView + 'SearchForm').innerHTML = data.responseText;
3758 SUGAR.util.evalScript(data.responseText);
3759 // pass script variables to global scope
3760 if(theView == 'saved_views') {
3761 if(typeof columnsMeta != 'undefined') SUGAR.savedViews.columnsMeta = columnsMeta;
3762 if(typeof selectedOrderBy != 'undefined') SUGAR.savedViews.selectedOrderBy = selectedOrderBy;
3763 if(typeof selectedSortOrder != 'undefined') SUGAR.savedViews.selectedSortOrder = selectedSortOrder;
3768 ajaxStatus.hideStatus();
3770 url = 'index.php?module=' + module + '&action=index&search_form_only=true&to_pdf=true&search_form_view=' + theView;
3772 //check to see if tpl has been specified. If so then pass location through url string
3774 if(document.getElementById('search_tpl') !=null && typeof(document.getElementById('search_tpl')) != 'undefined'){
3775 tpl = document.getElementById('search_tpl').value;
3776 if(tpl != ''){url += '&search_tpl='+tpl;}
3779 if(theView == 'saved_views') // handle the tab chooser
3780 url += '&displayColumns=' + SUGAR.savedViews.displayColumns + '&hideTabs=' + SUGAR.savedViews.hideTabs + '&orderBy=' + SUGAR.savedViews.selectedOrderBy + '&sortOrder=' + SUGAR.savedViews.selectedSortOrder;
3782 var cObj = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
3784 else { // that form already retrieved
3789 // copies one input to another
3790 copyElement: function(inputName, copyFromElement) {
3791 switch(copyFromElement.type) {
3794 document.search_form[inputName].value = copyFromElement.value;
3798 // This function is here to clear the form, instead of "resubmitting it
3799 clear_form: function(form, skipElementNames) {
3800 var elemList = form.elements;
3804 for( var i = 0; i < elemList.length ; i++ ) {
3806 if ( typeof(elem.type) == 'undefined' ) {
3810 if ( typeof(elem.type) != 'undefined' && typeof(skipElementNames) != 'undefined'
3811 && SUGAR.util.arrayIndexOf(skipElementNames, elem.name) != -1 )
3816 elemType = elem.type.toLowerCase();
3818 if ( elemType == 'text' || elemType == 'textarea' || elemType == 'password' ) {
3820 } else if (elemType == 'select-one') {
3821 // We have, what I hope, is a select box, time to unselect all options
3822 var optionList = elem.options,
3824 for (var ii = 0; ii < optionList.length; ii++) {
3825 if (optionList[ii].value == '') {
3830 if (optionList.length > 0) {
3831 optionList[selectedIndex].selected = "selected";
3833 } else if (elemType == 'select-multiple') {
3834 var optionList = elem.options;
3835 for ( var ii = 0 ; ii < optionList.length ; ii++ ) {
3836 optionList[ii].selected = false;
3839 else if ( elemType == 'radio' || elemType == 'checkbox' ) {
3840 elem.checked = false;
3841 elem.selected = false;
3843 else if ( elemType == 'hidden' ) {
3845 // For bean selection
3846 elem.name.indexOf("_id") != -1
3847 // For custom fields
3848 || elem.name.indexOf("_c") != -1
3849 // For advanced fields, like team collection, or datetime fields
3850 || elem.name.indexOf("_advanced") != -1
3858 // If there are any collections
3859 if (typeof(collection) !== 'undefined')
3861 // Loop through all the collections on the page and run clean_up()
3862 for (key in collection)
3864 // Clean up only removes blank fields, if any
3865 collection[key].clean_up();
3869 SUGAR.savedViews.clearColumns = true;
3873 // Code for the column/tab chooser used on homepage and in admin section
3874 SUGAR.tabChooser = function () {
3875 var object_refs = new Array();
3877 /* Describe certain transfers as invalid */
3880 movementCallback: function(left_side, right_side) {},
3881 orderCallback: function(left_side, right_side) {},
3883 freezeOptions: function(left_name, right_name, target) {
3884 if(!SUGAR.tabChooser.frozenOptions) { SUGAR.tabChooser.frozenOptions = []; }
3885 if(!SUGAR.tabChooser.frozenOptions[left_name]) { SUGAR.tabChooser.frozenOptions[left_name] = []; }
3886 if(!SUGAR.tabChooser.frozenOptions[left_name][right_name]) { SUGAR.tabChooser.frozenOptions[left_name][right_name] = []; }
3887 if(typeof target == 'array') {
3888 for(var i in target) {
3889 SUGAR.tabChooser.frozenOptions[left_name][right_name][target[i]] = true;
3892 SUGAR.tabChooser.frozenOptions[left_name][right_name][target] = true;
3896 buildSelectHTML: function(info) {
3897 var text = "<select";
3899 if(typeof (info['select']['size']) != 'undefined') {
3900 text +=" size=\""+ info['select']['size'] +"\"";
3903 if(typeof (info['select']['name']) != 'undefined') {
3904 text +=" name=\""+ info['select']['name'] +"\"";
3907 if(typeof (info['select']['style']) != 'undefined') {
3908 text +=" style=\""+ info['select']['style'] +"\"";
3911 if(typeof (info['select']['onchange']) != 'undefined') {
3912 text +=" onChange=\""+ info['select']['onchange'] +"\"";
3915 if(typeof (info['select']['multiple']) != 'undefined') {
3920 for(i=0; i<info['options'].length;i++) {
3921 option = info['options'][i];
3922 text += "<option value=\""+option['value']+"\" ";
3923 if ( typeof (option['selected']) != 'undefined' && option['selected']== true) {
3926 text += ">"+option['text']+"</option>";
3928 text += "</select>";
3932 left_to_right: function(left_name, right_name, left_size, right_size) {
3933 SUGAR.savedViews.clearColumns = false;
3934 var left_td = document.getElementById(left_name+'_td');
3935 var right_td = document.getElementById(right_name+'_td');
3937 var display_columns_ref = left_td.getElementsByTagName('select')[0];
3938 var hidden_columns_ref = right_td.getElementsByTagName('select')[0];
3940 var selected_left = new Array();
3941 var notselected_left = new Array();
3942 var notselected_right = new Array();
3944 var left_array = new Array();
3946 var frozen_options = SUGAR.tabChooser.frozenOptions;
3947 frozen_options = frozen_options && frozen_options[left_name] && frozen_options[left_name][right_name]?frozen_options[left_name][right_name]:[];
3949 // determine which options are selected in left
3950 for (i=0; i < display_columns_ref.options.length; i++)
3952 if ( display_columns_ref.options[i].selected == true && !frozen_options[display_columns_ref.options[i].value])
3954 selected_left[selected_left.length] = {text: display_columns_ref.options[i].text, value: display_columns_ref.options[i].value};
3958 notselected_left[notselected_left.length] = {text: display_columns_ref.options[i].text, value: display_columns_ref.options[i].value};
3963 for (i=0; i < hidden_columns_ref.options.length; i++)
3965 notselected_right[notselected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
3969 var left_select_html_info = new Object();
3970 var left_options = new Array();
3971 var left_select = new Object();
3973 left_select['name'] = left_name+'[]';
3974 left_select['id'] = left_name;
3975 left_select['size'] = left_size;
3976 left_select['multiple'] = 'true';
3978 var right_select_html_info = new Object();
3979 var right_options = new Array();
3980 var right_select = new Object();
3982 right_select['name'] = right_name+'[]';
3983 right_select['id'] = right_name;
3984 right_select['size'] = right_size;
3985 right_select['multiple'] = 'true';
3987 for (i = 0; i < notselected_right.length; i++) {
3988 right_options[right_options.length] = notselected_right[i];
3991 for (i = 0; i < selected_left.length; i++) {
3992 right_options[right_options.length] = selected_left[i];
3994 for (i = 0; i < notselected_left.length; i++) {
3995 left_options[left_options.length] = notselected_left[i];
3997 left_select_html_info['options'] = left_options;
3998 left_select_html_info['select'] = left_select;
3999 right_select_html_info['options'] = right_options;
4000 right_select_html_info['select'] = right_select;
4001 right_select_html_info['style'] = 'background: lightgrey';
4003 var left_html = this.buildSelectHTML(left_select_html_info);
4004 var right_html = this.buildSelectHTML(right_select_html_info);
4006 left_td.innerHTML = left_html;
4007 right_td.innerHTML = right_html;
4009 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
4010 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
4012 this.movementCallback(object_refs[left_name], object_refs[right_name]);
4018 right_to_left: function(left_name, right_name, left_size, right_size, max_left) {
4019 SUGAR.savedViews.clearColumns = false;
4020 var left_td = document.getElementById(left_name+'_td');
4021 var right_td = document.getElementById(right_name+'_td');
4023 var display_columns_ref = left_td.getElementsByTagName('select')[0];
4024 var hidden_columns_ref = right_td.getElementsByTagName('select')[0];
4026 var selected_right = new Array();
4027 var notselected_right = new Array();
4028 var notselected_left = new Array();
4030 var frozen_options = SUGAR.tabChooser.frozenOptions;
4031 frozen_options = SUGAR.tabChooser.frozenOptions && SUGAR.tabChooser.frozenOptions[right_name] && SUGAR.tabChooser.frozenOptions[right_name][left_name]?SUGAR.tabChooser.frozenOptions[right_name][left_name]:[];
4033 for (i=0; i < hidden_columns_ref.options.length; i++)
4035 if (hidden_columns_ref.options[i].selected == true && !frozen_options[hidden_columns_ref.options[i].value])
4037 selected_right[selected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
4041 notselected_right[notselected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
4046 if(max_left != '' && (display_columns_ref.length + selected_right.length) > max_left) {
4047 alert('Maximum of ' + max_left + ' columns can be displayed.');
4051 for (i=0; i < display_columns_ref.options.length; i++)
4053 notselected_left[notselected_left.length] = {text:display_columns_ref.options[i].text, value:display_columns_ref.options[i].value};
4057 var left_select_html_info = new Object();
4058 var left_options = new Array();
4059 var left_select = new Object();
4061 left_select['name'] = left_name+'[]';
4062 left_select['id'] = left_name;
4063 left_select['multiple'] = 'true';
4064 left_select['size'] = left_size;
4066 var right_select_html_info = new Object();
4067 var right_options = new Array();
4068 var right_select = new Object();
4070 right_select['name'] = right_name+ '[]';
4071 right_select['id'] = right_name;
4072 right_select['multiple'] = 'true';
4073 right_select['size'] = right_size;
4075 for (i = 0; i < notselected_left.length; i++) {
4076 left_options[left_options.length] = notselected_left[i];
4079 for (i = 0; i < selected_right.length; i++) {
4080 left_options[left_options.length] = selected_right[i];
4082 for (i = 0; i < notselected_right.length; i++) {
4083 right_options[right_options.length] = notselected_right[i];
4085 left_select_html_info['options'] = left_options;
4086 left_select_html_info['select'] = left_select;
4087 right_select_html_info['options'] = right_options;
4088 right_select_html_info['select'] = right_select;
4089 right_select_html_info['style'] = 'background: lightgrey';
4091 var left_html = this.buildSelectHTML(left_select_html_info);
4092 var right_html = this.buildSelectHTML(right_select_html_info);
4094 left_td.innerHTML = left_html;
4095 right_td.innerHTML = right_html;
4097 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
4098 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
4100 this.movementCallback(object_refs[left_name], object_refs[right_name]);
4105 up: function(name, left_name, right_name) {
4106 SUGAR.savedViews.clearColumns = false;
4107 var left_td = document.getElementById(left_name+'_td');
4108 var right_td = document.getElementById(right_name+'_td');
4109 var td = document.getElementById(name+'_td');
4110 var obj = td.getElementsByTagName('select')[0];
4111 obj = (typeof obj == "string") ? document.getElementById(obj) : obj;
4112 if (obj.tagName.toLowerCase() != "select" && obj.length < 2)
4114 var sel = new Array();
4116 for (i=0; i<obj.length; i++) {
4117 if (obj[i].selected == true) {
4118 sel[sel.length] = i;
4121 for (i=0; i < sel.length; i++) {
4122 if (sel[i] != 0 && !obj[sel[i]-1].selected) {
4123 var tmp = new Array(obj[sel[i]-1].text, obj[sel[i]-1].value);
4124 obj[sel[i]-1].text = obj[sel[i]].text;
4125 obj[sel[i]-1].value = obj[sel[i]].value;
4126 obj[sel[i]].text = tmp[0];
4127 obj[sel[i]].value = tmp[1];
4128 obj[sel[i]-1].selected = true;
4129 obj[sel[i]].selected = false;
4133 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
4134 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
4136 this.orderCallback(object_refs[left_name], object_refs[right_name]);
4141 down: function(name, left_name, right_name) {
4142 SUGAR.savedViews.clearColumns = false;
4143 var left_td = document.getElementById(left_name+'_td');
4144 var right_td = document.getElementById(right_name+'_td');
4145 var td = document.getElementById(name+'_td');
4146 var obj = td.getElementsByTagName('select')[0];
4147 if (obj.tagName.toLowerCase() != "select" && obj.length < 2)
4149 var sel = new Array();
4150 for (i=obj.length-1; i>-1; i--) {
4151 if (obj[i].selected == true) {
4152 sel[sel.length] = i;
4155 for (i=0; i < sel.length; i++) {
4156 if (sel[i] != obj.length-1 && !obj[sel[i]+1].selected) {
4157 var tmp = new Array(obj[sel[i]+1].text, obj[sel[i]+1].value);
4158 obj[sel[i]+1].text = obj[sel[i]].text;
4159 obj[sel[i]+1].value = obj[sel[i]].value;
4160 obj[sel[i]].text = tmp[0];
4161 obj[sel[i]].value = tmp[1];
4162 obj[sel[i]+1].selected = true;
4163 obj[sel[i]].selected = false;
4167 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
4168 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
4170 this.orderCallback(object_refs[left_name], object_refs[right_name]);
4175 }(); // end tabChooser
4177 SUGAR.language = function() {
4179 languages : new Array(),
4181 setLanguage: function(module, data) {
4182 if (!SUGAR.language.languages) {
4185 SUGAR.language.languages[module] = data;
4188 get: function(module, str) {
4189 if(typeof SUGAR.language.languages[module] == 'undefined' || typeof SUGAR.language.languages[module][str] == 'undefined')
4193 return SUGAR.language.languages[module][str];
4196 translate: function(module, str)
4198 text = this.get(module, str);
4199 return text != 'undefined' ? text : this.get('app_strings', str);
4204 SUGAR.contextMenu = function() {
4206 objects: new Object(),
4207 objectTypes: new Object(),
4209 * Registers a new object for the context menu.
4210 * objectType - name of the type
4212 * metaData - metaData to pass to the action function
4214 registerObject: function(objectType, id, metaData) {
4215 SUGAR.contextMenu.objects[id] = new Object();
4216 SUGAR.contextMenu.objects[id] = {'objectType' : objectType, 'metaData' : metaData};
4219 * Registers a new object type
4220 * name - name of the type
4221 * menuItems - array of menu items
4223 registerObjectType: function(name, menuItems) {
4224 SUGAR.contextMenu.objectTypes[name] = new Object();
4225 SUGAR.contextMenu.objectTypes[name] = {'menuItems' : menuItems, 'objects' : new Array()};
4228 * Determines which menu item was clicked
4230 getListItemFromEventTarget: function(p_oNode) {
4232 if(p_oNode.tagName == "LI") {
4237 if(p_oNode.tagName == "LI") {
4242 } while((p_oNode = p_oNode.parentNode));
4247 * handles movement within context menu
4249 onContextMenuMove: function() {
4250 var oNode = this.contextEventTarget;
4251 var bDisabled = (oNode.tagName == "UL");
4252 var i = this.getItemGroups()[0].length - 1;
4254 this.getItem(i).cfg.setProperty("disabled", bDisabled);
4259 * handles clicks on a context menu ITEM
4261 onContextMenuItemClick: function(p_sType, p_aArguments, p_oItem) {
4262 var oLI = SUGAR.contextMenu.getListItemFromEventTarget(this.parent.contextEventTarget);
4263 id = this.parent.contextEventTarget.parentNode.id; // id of the target
4264 funct = eval(SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[id]['objectType']]['menuItems'][this.index]['action']);
4265 funct(this.parent.contextEventTarget, SUGAR.contextMenu.objects[id]['metaData']);
4268 * Initializes all context menus registered
4271 for(var i in SUGAR.contextMenu.objects) { // make a variable called objects in objectTypes containg references to all triggers
4272 if(typeof SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'] == 'undefined')
4273 SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'] = new Array();
4274 SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'].push(document.getElementById(i));
4276 // register the menus
4277 for(var i in SUGAR.contextMenu.objectTypes) {
4278 var oContextMenu = new YAHOO.widget.ContextMenu(i, {'trigger': SUGAR.contextMenu.objectTypes[i]['objects']});
4279 var aMainMenuItems = SUGAR.contextMenu.objectTypes[i]['menuItems'];
4280 var nMainMenuItems = aMainMenuItems.length;
4282 for(var j = 0; j < nMainMenuItems; j++) {
4283 oMenuItem = new YAHOO.widget.ContextMenuItem(aMainMenuItems[j].text, { helptext: aMainMenuItems[j].helptext });
4284 oMenuItem.clickEvent.subscribe(SUGAR.contextMenu.onContextMenuItemClick, oMenuItem, true);
4285 oContextMenu.addItem(oMenuItem);
4287 // Add a "move" event handler to the context menu
4288 oContextMenu.moveEvent.subscribe(SUGAR.contextMenu.onContextMenuMove, oContextMenu, true);
4289 // Add a "keydown" event handler to the context menu
4290 oContextMenu.keyDownEvent.subscribe(SUGAR.contextMenu.onContextMenuItemClick, oContextMenu, true);
4291 // Render the context menu
4292 oContextMenu.render(document.body);
4298 SUGAR.contextMenu.actions = function() {
4301 * redirects to a new note with the clicked on object as the target
4303 createNote: function(itemClicked, metaData) {
4304 loc = 'index.php?module=Notes&action=EditView';
4305 for(i in metaData) {
4306 if(i == 'notes_parent_type') loc += '&parent_type=' + metaData[i];
4307 else if(i != 'module' && i != 'parent_type') loc += '&' + i + '=' + metaData[i];
4309 document.location = loc;
4312 * redirects to a new note with the clicked on object as the target
4314 scheduleMeeting: function(itemClicked, metaData) {
4315 loc = 'index.php?module=Meetings&action=EditView';
4316 for(i in metaData) {
4317 if(i != 'module') loc += '&' + i + '=' + metaData[i];
4319 document.location = loc;
4322 * redirects to a new note with the clicked on object as the target
4324 scheduleCall: function(itemClicked, metaData) {
4325 loc = 'index.php?module=Calls&action=EditView';
4326 for(i in metaData) {
4327 if(i != 'module') loc += '&' + i + '=' + metaData[i];
4329 document.location = loc;
4332 * redirects to a new contact with the clicked on object as the target
4334 createContact: function(itemClicked, metaData) {
4335 loc = 'index.php?module=Contacts&action=EditView';
4336 for(i in metaData) {
4337 if(i != 'module') loc += '&' + i + '=' + metaData[i];
4339 document.location = loc;
4342 * redirects to a new task with the clicked on object as the target
4344 createTask: function(itemClicked, metaData) {
4345 loc = 'index.php?module=Tasks&action=EditView';
4346 for(i in metaData) {
4347 if(i != 'module') loc += '&' + i + '=' + metaData[i];
4349 document.location = loc;
4352 * redirects to a new opportunity with the clicked on object as the target
4354 createOpportunity: function(itemClicked, metaData) {
4355 loc = 'index.php?module=Opportunities&action=EditView';
4356 for(i in metaData) {
4357 if(i != 'module') loc += '&' + i + '=' + metaData[i];
4359 document.location = loc;
4362 * redirects to a new opportunity with the clicked on object as the target
4364 createCase: function(itemClicked, metaData) {
4365 loc = 'index.php?module=Cases&action=EditView';
4366 for(i in metaData) {
4367 if(i != 'module') loc += '&' + i + '=' + metaData[i];
4369 document.location = loc;
4372 * handles add to favorites menu selection
4374 addToFavorites: function(itemClicked, metaData) {
4375 success = function(data) {
4377 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});
4382 //if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.contextMenu.init);
4384 // initially from popup_parent_helper.js
4385 var popup_request_data;
4388 function get_popup_request_data()
4390 return YAHOO.lang.JSON.stringify(window.document.popup_request_data);
4393 function get_close_popup()
4395 return window.document.close_popup;
4398 function open_popup(module_name, width, height, initial_filter, close_popup, hide_clear_button, popup_request_data, popup_mode, create, metadata)
4400 if (typeof(popupCount) == "undefined" || popupCount == 0)
4403 // set the variables that the popup will pull from
4404 window.document.popup_request_data = popup_request_data;
4405 window.document.close_popup = close_popup;
4407 //globally changing width and height of standard pop up window from 600 x 400 to 800 x 800
4408 width = (width == 600) ? 800 : width;
4409 height = (height == 400) ? 800 : height;
4413 + 'module=' + module_name
4416 if (initial_filter != '') {
4417 URL += '&query=true' + initial_filter;
4418 // Bug 41891 - Popup Window Name
4419 popupName = initial_filter.replace(/[^a-z_0-9]+/ig, '_');
4420 windowName = module_name + '_popup_window' + popupName;
4422 windowName = module_name + '_popup_window' + popupCount;
4426 if (hide_clear_button) {
4427 URL += '&hide_clear_button=true';
4430 windowFeatures = 'width=' + width
4431 + ',height=' + height
4432 + ',resizable=1,scrollbars=1';
4434 if (popup_mode == '' || popup_mode == undefined) {
4435 popup_mode='single';
4437 URL+='&mode='+popup_mode;
4438 if (create == '' || create == undefined) {
4441 URL+='&create='+create;
4443 if (metadata != '' && metadata != undefined) {
4444 URL+='&metadata='+metadata;
4447 // Bug #46842 : The relate field field_to_name_array fails to copy over custom fields
4448 // post fields that should be populated from popup form
4449 if(popup_request_data.jsonObject) {
4450 var request_data = popup_request_data.jsonObject;
4452 var request_data = popup_request_data;
4454 var field_to_name_array_url = '';
4456 if (request_data && request_data.field_to_name_array != undefined) {
4457 for(var key in request_data.field_to_name_array) {
4458 if ( key.toLowerCase() != 'id' ) {
4459 field_to_name_array_url += '&field_to_name[]='+encodeURIComponent(key.toLowerCase());
4463 if ( field_to_name_array_url ) {
4464 URL+=field_to_name_array_url;
4467 win = SUGAR.util.openWindow(URL, windowName, windowFeatures);
4471 // put the focus on the popup if the browser supports the focus() method
4475 win.popupCount = popupCount;
4481 * The reply data must be a JSON array structured with the following information:
4482 * 1) form name to populate
4483 * 2) associative array of input names to values for populating the form
4485 var from_popup_return = false;
4487 //Function replaces special HTML chars for usage in text boxes
4488 function replaceHTMLChars(value) {
4489 return value.replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');
4492 function set_return_basic(popup_reply_data,filter)
4494 var form_name = popup_reply_data.form_name;
4495 var name_to_value_array = popup_reply_data.name_to_value_array;
4496 for (var the_key in name_to_value_array)
4498 if(the_key == 'toJSON')
4502 else if(the_key.match(filter))
4504 var displayValue=replaceHTMLChars(name_to_value_array[the_key]);
4505 // begin andopes change: support for enum fields (SELECT)
4506 if(window.document.forms[form_name] && window.document.forms[form_name].elements[the_key]) {
4507 if(window.document.forms[form_name].elements[the_key].tagName == 'SELECT') {
4508 var selectField = window.document.forms[form_name].elements[the_key];
4509 for(var i = 0; i < selectField.options.length; i++) {
4510 if(selectField.options[i].text == displayValue) {
4511 selectField.options[i].selected = true;
4512 SUGAR.util.callOnChangeListers(selectField);
4517 window.document.forms[form_name].elements[the_key].value = displayValue;
4518 SUGAR.util.callOnChangeListers(window.document.forms[form_name].elements[the_key]);
4521 // end andopes change: support for enum fields (SELECT)
4526 function set_return(popup_reply_data)
4528 from_popup_return = true;
4529 var form_name = popup_reply_data.form_name;
4530 var name_to_value_array = popup_reply_data.name_to_value_array;
4531 if(typeof name_to_value_array != 'undefined' && name_to_value_array['account_id'])
4534 var label_data_str = '';
4535 var current_label_data_str = '';
4536 var popupConfirm = popup_reply_data.popupConfirm;
4537 for (var the_key in name_to_value_array)
4539 if(the_key == 'toJSON')
4545 var displayValue=replaceHTMLChars(name_to_value_array[the_key]);
4546 if(window.document.forms[form_name] && document.getElementById(the_key+'_label') && !the_key.match(/account/)) {
4547 var data_label = document.getElementById(the_key+'_label').innerHTML.replace(/\n/gi,'').replace(/<\/?[^>]+(>|$)/g, "");
4548 label_str += data_label + ' \n';
4549 label_data_str += data_label + ' ' + displayValue + '\n';
4550 if(window.document.forms[form_name].elements[the_key]) {
4551 current_label_data_str += data_label + ' ' + window.document.forms[form_name].elements[the_key].value +'\n';
4557 if(label_data_str != label_str && current_label_data_str != label_str){
4559 if (typeof popupConfirm != 'undefined')
4561 if (popupConfirm > -1) {
4562 set_return_basic(popup_reply_data,/\S/);
4564 set_return_basic(popup_reply_data,/account/);
4568 else if(confirm(SUGAR.language.get('app_strings', 'NTC_OVERWRITE_ADDRESS_PHONE_CONFIRM') + '\n\n' + label_data_str))
4570 set_return_basic(popup_reply_data,/\S/);
4574 set_return_basic(popup_reply_data,/account/);
4576 }else if(label_data_str != label_str && current_label_data_str == label_str){
4577 set_return_basic(popup_reply_data,/\S/);
4578 }else if(label_data_str == label_str){
4579 set_return_basic(popup_reply_data,/account/);
4582 set_return_basic(popup_reply_data,/\S/);
4586 function set_return_lead_conv(popup_reply_data) {
4587 set_return(popup_reply_data);
4588 if (document.getElementById('lead_conv_ac_op_sel') && typeof onBlurKeyUpHandler=='function') {
4589 onBlurKeyUpHandler();
4593 function set_return_and_save(popup_reply_data)
4595 var form_name = popup_reply_data.form_name;
4596 var name_to_value_array = popup_reply_data.name_to_value_array;
4598 for (var the_key in name_to_value_array)
4600 if(the_key == 'toJSON')
4606 window.document.forms[form_name].elements[the_key].value = name_to_value_array[the_key];
4610 window.document.forms[form_name].return_module.value = window.document.forms[form_name].module.value;
4611 window.document.forms[form_name].return_action.value = 'DetailView';
4612 window.document.forms[form_name].return_id.value = window.document.forms[form_name].record.value;
4613 window.document.forms[form_name].action.value = 'Save';
4614 window.document.forms[form_name].submit();
4618 * This is a helper function to construct the initial filter that can be
4619 * passed into the open_popup() function. It assumes that there is an
4620 * account_id and account_name field in the given form_name to use to
4621 * construct the intial filter string.
4623 function get_initial_filter_by_account(form_name)
4625 var account_id = window.document.forms[form_name].account_id.value;
4626 var account_name = escape(window.document.forms[form_name].account_name.value);
4627 var initial_filter = "&account_id=" + account_id + "&account_name=" + account_name;
4629 return initial_filter;
4631 // end code from popup_parent_helper.js
4633 // begin code for address copy
4635 * This is a function used by the Address widget that will fill
4636 * in the given array fields using the fromKey and toKey as a
4637 * prefix into the form objects HTML elements.
4639 * @param form The HTML form object to parse
4640 * @param fromKey The prefix of elements to copy from
4641 * @param toKey The prefix of elements to copy into
4642 * @return boolean true if successful, false otherwise
4644 function copyAddress(form, fromKey, toKey) {
4646 var elems = new Array("address_street", "address_city", "address_state", "address_postalcode", "address_country");
4647 var checkbox = document.getElementById(toKey + "_checkbox");
4649 if(typeof checkbox != "undefined") {
4650 if(!checkbox.checked) {
4652 t = toKey + "_" + elems[x];
4653 document.getElementById(t).removeAttribute('readonly');
4657 f = fromKey + "_" + elems[x];
4658 t = toKey + "_" + elems[x];
4660 document.getElementById(t).value = document.getElementById(f).value;
4661 document.getElementById(t).setAttribute('readonly', true);
4667 // end code for address copy
4670 * This function is used in Email Template Module.
4671 * It will check whether the template is used in Campaing->EmailMarketing.
4672 * If true, it will notify user.
4675 function check_deletable_EmailTemplate() {
4676 id = document.getElementsByName('record')[0].value;
4677 currentForm = document.getElementById('form');
4679 success:function(r) {
4680 if(r.responseText == 'true') {
4681 if(!confirm(SUGAR.language.get('app_strings','NTC_TEMPLATE_IS_USED'))) {
4685 if(!confirm(SUGAR.language.get('app_strings','NTC_DELETE_CONFIRMATION'))) {
4689 currentForm.return_module.value='EmailTemplates';
4690 currentForm.return_action.value='ListView';
4691 currentForm.action.value='Delete';
4692 currentForm.submit();
4695 url = "index.php?module=EmailTemplates&action=CheckDeletable&from=DetailView&to_pdf=1&record="+id;
4696 YAHOO.util.Connect.asyncRequest('POST',url, call_back,null);
4700 remove_upload_imagefile : function(field_name) {
4701 var field=document.getElementById('remove_imagefile_' + field_name);
4704 //enable the file upload button.
4705 var field=document.getElementById( field_name);
4706 field.style.display="";
4708 //hide the image and remove button.
4709 var field=document.getElementById('img_' + field_name);
4710 field.style.display="none";
4711 var field=document.getElementById('bt_remove_' + field_name);
4712 field.style.display="none";
4714 if(document.getElementById(field_name + '_duplicate')) {
4715 var field = document.getElementById(field_name + '_duplicate');
4720 confirm_imagefile : function(field_name) {
4721 var field=document.getElementById(field_name);
4722 var filename=field.value;
4723 var fileExtension = filename.substring(filename.lastIndexOf(".")+1);
4724 fileExtension = fileExtension.toLowerCase();
4725 if (fileExtension == "jpg" || fileExtension == "jpeg"
4726 || fileExtension == "gif" || fileExtension == "png" || fileExtension == "bmp"){
4731 alert(SUGAR.language.get('app_strings', 'LBL_UPLOAD_IMAGE_FILE_INVALID'));
4735 lightbox : function(image)
4737 if (typeof(SUGAR.image.lighboxWindow) == "undefined")
4738 SUGAR.image.lighboxWindow = new YAHOO.widget.SimpleDialog('sugarImageViewer', {
4741 id:'sugarMsgWindow',
4744 msg: "<img src='" + image + "'> </img>",
4747 SUGAR.image.lighboxWindow.setBody("<img src='" + image + "'> </img>");
4748 SUGAR.image.lighboxWindow.render(document.body);
4749 SUGAR.image.lighboxWindow.show();
4750 SUGAR.image.lighboxWindow.center()
4754 SUGAR.append(SUGAR.util, {
4755 isTouchScreen: function() {
4756 // first check if we have forced use of the touch enhanced interface
4757 if (Get_Cookie("touchscreen") == '1') {
4761 // next check if we should use the touch interface with our device
4762 if ((navigator.userAgent.match(/iPad/i) != null)) {
4769 isLoginPage: function(content) {
4770 //skip if this is packageManager screen
4771 if(SUGAR.util.isPackageManager()) {return false;}
4772 var loginPageStart = "<!DOCTYPE";
4773 if (content.substr(0, loginPageStart.length) == loginPageStart && content.indexOf("<html>") != -1 && content.indexOf("login_module") != -1) {
4774 window.location.href = window.location.protocol + window.location.pathname;
4779 isPackageManager: function(){
4780 if(typeof(document.the_form) !='undefined' && typeof(document.the_form.language_pack_escaped) !='undefined'){
4782 }else{return false;}
4785 ajaxCallInProgress: function(){
4787 //First check if we are in a popup.
4788 if (typeof (send_back) != "function"){
4789 //If the page content is blank, it means we are probably still waiting on something
4790 var c = document.getElementById("content");
4791 if (!c) return true;
4792 t = YAHOO.lang.trim(SUGAR.util.innerText(c));
4794 return SUGAR_callsInProgress != 0 || t == "";
4796 //Firefox doesn't support innerText (textContent includes script content)
4797 innerText : function(el) {
4798 if (el.tagName == "SCRIPT")
4800 if(typeof(el.innerText) == "string")
4801 return el.innerText;
4803 for (var i in el.childNodes){
4804 var c = el.childNodes[i];
4805 if (typeof(c) != "object")
4807 if (typeof(c.nodeName) == "string" && c.nodeName == "#text")
4810 t += SUGAR.util.innerText(c);
4815 callOnChangeListers: function(field){
4816 var listeners = YAHOO.util.Event.getListeners(field, 'change');
4817 if (listeners != null) {
4818 for (var i = 0; i < listeners.length; i++) {
4819 var l = listeners[i];
4820 l.fn.call(l.scope ? l.scope : this, l.obj);
4825 closeActivityPanel: {
4826 show:function(module,id,new_status,viewType,parentContainerId){
4827 if (SUGAR.util.closeActivityPanel.panel)
4828 SUGAR.util.closeActivityPanel.panel.destroy();
4829 var singleModule = SUGAR.language.get("app_list_strings", "moduleListSingular")[module];
4830 singleModule = typeof(singleModule != 'undefined') ? singleModule.toLowerCase() : '';
4831 var closeText = SUGAR.language.get("app_strings", "LBL_CLOSE_ACTIVITY_CONFIRM").replace("#module#",singleModule);
4832 SUGAR.util.closeActivityPanel.panel =
4833 new YAHOO.widget.SimpleDialog("closeActivityDialog",
4840 constraintoviewport: true,
4841 buttons: [ { text:SUGAR.language.get("app_strings", "LBL_EMAIL_OK"), handler:function(){
4842 if (SUGAR.util.closeActivityPanel.panel)
4843 SUGAR.util.closeActivityPanel.panel.hide();
4845 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_SAVING'));
4846 var args = "action=save&id=" + id + "&record=" + id + "&status=" + new_status + "&module=" + module;
4847 // 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
4848 // TODO: Take id out and regression test. Left id in for now to not create any other unexpected problems
4849 //var args = "action=save&id=" + id + "&status=" + new_status + "&module=" + module;
4853 // Bug 51984: We need to submit the form just incase we have a form already submitted
4854 // so we dont get a popup stating that the form needs to be resubmitted like it doesn,
4855 // when you do a reload/refresh
4856 window.setTimeout(function(){if(document.getElementById('search_form')) document.getElementById('search_form').submit(); else window.location.reload(true);}, 0);
4858 argument:{'parentContainerId':parentContainerId}
4861 YAHOO.util.Connect.asyncRequest('POST', 'index.php', callback, args);
4863 }, isDefault:true },
4864 { text:SUGAR.language.get("app_strings", "LBL_EMAIL_CANCEL"), handler:function(){SUGAR.util.closeActivityPanel.panel.hide(); }} ]
4867 SUGAR.util.closeActivityPanel.panel.setHeader(SUGAR.language.get("app_strings", "LBL_CLOSE_ACTIVITY_HEADER"));
4868 SUGAR.util.closeActivityPanel.panel.render(document.body);
4869 SUGAR.util.closeActivityPanel.panel.show();
4873 setEmailPasswordDisplay: function(id, exists, formName) {
4874 link = document.getElementById(id+'_link');
4875 pwd = document.getElementById(id);
4876 if(!pwd || !link) return;
4878 pwd.style.display = 'none';
4879 link.style.display = '';
4880 if(typeof(formName) != 'undefined')
4881 removeFromValidate(formName, id);
4883 pwd.style.display = '';
4884 link.style.display = 'none';
4888 setEmailPasswordEdit: function(id) {
4889 link = document.getElementById(id+'_link');
4890 pwd = document.getElementById(id);
4891 if(!pwd || !link) return;
4892 pwd.style.display = '';
4893 link.style.display = 'none';
4897 * Compares a filename with a supplied array of allowed file extensions.
4898 * @param fileName string
4899 * @param allowedTypes array of allowed file extensions
4902 validateFileExt: function(fileName, allowedTypes) {
4903 var ext = fileName.split('.').pop().toLowerCase();
4905 for (var i = allowedTypes.length; i >= 0; i--) {
4906 if (ext === allowedTypes[i]) {
4914 arrayIndexOf: function(arr, val, start) {
4915 if (typeof arr.indexOf == "function")
4916 return arr.indexOf(val, start);
4917 for (var i = (start || 0), j = arr.length; i < j; i++) {
4918 if (arr[i] === val) {
4926 SUGAR.clearRelateField = function(form, name, id)
4928 if (typeof form[name] == "object"){
4929 form[name].value = '';
4930 SUGAR.util.callOnChangeListers(form[name]);
4933 if (typeof form[id] == "object"){
4934 form[id].value = '';
4935 SUGAR.util.callOnChangeListers(form[id]);
4938 if(typeof(SUGAR.AutoComplete) == 'undefined') SUGAR.AutoComplete = {};
4940 SUGAR.AutoComplete.getOptionsArray = function(options_index){
4941 var return_arr = [];
4943 var opts = SUGAR.language.get('app_list_strings', options_index);
4944 if(typeof(opts) != 'undefined'){
4946 // Since we are using auto complete, we excluse blank dropdown entries since they can just leave it blank
4947 if(key != '' && opts[key] != ''){
4950 item['text'] = opts[key];
4951 return_arr.push(item);
4958 if(typeof(SUGAR.MultiEnumAutoComplete) == 'undefined') SUGAR.MultiEnumAutoComplete = {};
4960 SUGAR.MultiEnumAutoComplete.getMultiSelectKeysFromValues = function(options_index, val_string){
4961 var opts = SUGAR.language.get('app_list_strings', options_index);
4962 var selected_values = val_string.split(", ");
4963 // YUI AutoComplete adds a blank. We remove it automatically here
4964 if(selected_values.length > 0 && selected_values.indexOf('') == selected_values.length - 1){
4965 selected_values.pop();
4967 var final_arr = new Array();
4968 for(idx in selected_values){
4970 if(selected_values[idx] == opts[o_idx]){
4971 final_arr.push(o_idx);
4978 SUGAR.MultiEnumAutoComplete.getMultiSelectValuesFromKeys = function(options_index, val_string){
4979 var opts = SUGAR.language.get('app_list_strings', options_index);
4980 val_string=val_string.replace(/^\^/,'').replace(/\^$/,'') //fixes bug where string starts or ends with ^
4981 var selected_values = val_string.split("^,^");
4983 // YUI AutoComplete adds a blank. We remove it automatically here
4984 if(selected_values.length > 0 && selected_values.indexOf('') == selected_values.length - 1){
4985 selected_values.pop();
4988 var final_arr = new Array();
4989 for(idx in selected_values){
4991 if(selected_values[idx] == o_idx){
4992 final_arr.push(opts[o_idx]);
4999 function convertReportDateTimeToDB(dateValue, timeValue)
5001 var date_match = dateValue.match(date_reg_format);
5002 var time_match = timeValue.match(/([0-9]{1,2})\:([0-9]{1,2})([ap]m)/);
5003 if ( date_match != null && time_match != null) {
5004 time_match[1] = parseInt(time_match[1]);
5005 if (time_match[3] == 'pm') {
5006 time_match[1] = time_match[1] + 12;
5007 if (time_match[1] >= 24) {
5008 time_match[1] = time_match[1] - 24;
5010 } else if (time_match[3] == 'am' && time_match[1] == 12) {
5013 if (time_match[1] < 10) {
5014 time_match[1] = '0' + time_match[1];
5016 return date_match[date_reg_positions['Y']] + "-"+date_match[date_reg_positions['m']] + "-"+date_match[date_reg_positions['d']] + ' '+ time_match[1] + ':' + time_match[2] + ':00';