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:21.0}, // Firefox 21.0
190 chrome : {min:537.36} // Chrome 27
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'){
924 //If a field is not required and it is blank or is binarydependant, skip validation.
925 //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
926 if(!validate[formname][i][requiredIndex] && trim(form[validate[formname][i][nameIndex]].value) == '' && (typeof(validate[formname][i][jstypeIndex]) != 'undefined' && validate[formname][i][jstypeIndex] != 'binarydep'))
931 if(validate[formname][i][requiredIndex]
932 && !isFieldTypeExceptFromEmptyCheck(validate[formname][i][typeIndex])
934 if(typeof form[validate[formname][i][nameIndex]] == 'undefined' || trim(form[validate[formname][i][nameIndex]].value) == ""){
935 add_error_style(formname, validate[formname][i][nameIndex], requiredTxt +' ' + validate[formname][i][msgIndex]);
940 switch(validate[formname][i][typeIndex]){
942 if(!isValidEmail(trim(form[validate[formname][i][nameIndex]].value))){
944 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
948 if( !isTime(trim(form[validate[formname][i][nameIndex]].value))){
950 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
952 case 'date': if(!isDate(trim(form[validate[formname][i][nameIndex]].value))){
954 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
959 if(!isDBName(trim(form[validate[formname][i][nameIndex]].value))){
961 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
964 // Bug #49614 : Check value without trimming before
966 if(!isDBName(form[validate[formname][i][nameIndex]].value)){
968 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
974 var file_input = form[validate[formname][i][nameIndex] + '_file'];
975 if( file_input && validate[formname][i][requiredIndex] && trim(file_input.value) == "" && !file_input.disabled ) {
977 add_error_style(formname, validate[formname][i][nameIndex], requiredTxt + " " + validate[formname][i][msgIndex]);
981 if(!isInteger(trim(form[validate[formname][i][nameIndex]].value))){
983 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
987 if(!isDecimal(trim(form[validate[formname][i][nameIndex]].value))){
989 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
994 if(!isFloat(trim(form[validate[formname][i][nameIndex]].value))){
996 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
1000 var div_element_id = formname + '_' + form[validate[formname][i][nameIndex]].name + '_operation_div';
1001 var input_elements = YAHOO.util.Selector.query('input', document.getElementById(div_element_id));
1002 var primary_field_id = '';
1003 var validation_passed = false;
1004 var replace_selected = false;
1006 //Loop through the option elements (replace or add currently)
1007 for(t in input_elements) {
1008 if(input_elements[t].type && input_elements[t].type == 'radio' && input_elements[t].checked == true && input_elements[t].value == 'replace') {
1010 //Now find where the primary radio button is and if a value has been set
1011 var radio_elements = YAHOO.util.Selector.query('input[type=radio]', document.getElementById(formname + '_team_name_table'));
1013 for(var x = 0; x < radio_elements.length; x++) {
1014 if(radio_elements[x].name != 'team_name_type') {
1015 primary_field_id = 'team_name_collection_' + radio_elements[x].value;
1016 if(radio_elements[x].checked) {
1017 replace_selected = true;
1018 if(trim(document.forms[formname].elements[primary_field_id].value) != '') {
1019 validation_passed = true;
1022 } else if(trim(document.forms[formname].elements[primary_field_id].value) != '') {
1023 replace_selected = true;
1030 if(replace_selected && !validation_passed) {
1031 add_error_style(formname, primary_field_id, SUGAR.language.get('app_strings', 'ERR_NO_PRIMARY_TEAM_SPECIFIED'));
1036 var table_element_id = formname + '_' + form[validate[formname][i][nameIndex]].name + '_table';
1037 if(document.getElementById(table_element_id)) {
1038 var input_elements = YAHOO.util.Selector.query('input[type=radio]', document.getElementById(table_element_id));
1039 var has_primary = false;
1040 var primary_field_id = form[validate[formname][i][nameIndex]].name + '_collection_0';
1042 for(t in input_elements) {
1043 primary_field_id = form[validate[formname][i][nameIndex]].name + '_collection_' + input_elements[t].value;
1044 if(input_elements[t].type && input_elements[t].type == 'radio' && input_elements[t].checked == true) {
1045 if(document.forms[formname].elements[primary_field_id].value != '') {
1054 var field_id = form[validate[formname][i][nameIndex]].name + '_collection_' + input_elements[0].value;
1055 add_error_style(formname, field_id, SUGAR.language.get('app_strings', 'ERR_NO_PRIMARY_TEAM_SPECIFIED'));
1061 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex]);
1065 if(typeof validate[formname][i][jstypeIndex] != 'undefined'/* && !isError*/){
1067 switch(validate[formname][i][jstypeIndex]){
1068 // Bug #47961 May be validation through callback is best way.
1070 if (typeof validate[formname][i][callbackIndex] == 'function')
1072 var result = validate[formname][i][callbackIndex](formname, validate[formname][i][nameIndex]);
1073 if (result == false)
1076 add_error_style(formname, validate[formname][i][nameIndex], requiredTxt + " " + validate[formname][i][msgIndex]);
1081 if(!inRange(trim(form[validate[formname][i][nameIndex]].value), validate[formname][i][minIndex], validate[formname][i][maxIndex])){
1083 var lbl_validate_range = SUGAR.language.get('app_strings', 'LBL_VALIDATE_RANGE');
1084 if (typeof validate[formname][i][minIndex] == 'number' && typeof validate[formname][i][maxIndex] == 'number')
1086 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] + ")");
1088 else if (typeof validate[formname][i][minIndex] == 'number')
1090 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'));
1092 else if (typeof validate[formname][i][maxIndex] == 'number')
1094 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]);
1099 compareTo = form[validate[formname][i][compareToIndex]];
1100 if( typeof compareTo != 'undefined'){
1101 if(trim(compareTo.value) != '' || (validate[formname][i][allowblank] != 'true') ) {
1102 date2 = trim(compareTo.value);
1103 date1 = trim(form[validate[formname][i][nameIndex]].value);
1105 if(trim(date1).length != 0 && !isBefore(date1,date2)){
1108 //jc:#12287 - adding translation for the is not before message
1109 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex] + "(" + date1 + ") " + SUGAR.language.get('app_strings', 'MSG_IS_NOT_BEFORE') + ' ' +date2);
1115 value=unformatNumber(trim(form[validate[formname][i][nameIndex]].value), num_grp_sep, dec_sep);
1116 maximum = parseFloat(validate[formname][i][maxIndex]);
1117 if( typeof maximum != 'undefined'){
1120 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]);
1125 value=unformatNumber(trim(form[validate[formname][i][nameIndex]].value), num_grp_sep, dec_sep);
1126 minimum = parseFloat(validate[formname][i][minIndex]);
1127 if( typeof minimum != 'undefined'){
1130 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'));
1135 compareTo = form[validate[formname][i][compareToIndex]];
1136 if( typeof compareTo != 'undefined') {
1137 item1 = trim(form[validate[formname][i][nameIndex]].value);
1138 item2 = trim(compareTo.value);
1139 if(!bothExist(item1, item2)) {
1141 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex]);
1146 compareTo = form[validate[formname][i][compareToIndex]];
1147 if( typeof compareTo != 'undefined') {
1148 item1 = trim(form[validate[formname][i][nameIndex]].value);
1149 item2 = trim(compareTo.value);
1150 if(!bothExist(item1, item2) || item1 != item2) {
1152 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex]);
1157 arr = eval(validate[formname][i][arrIndex]);
1158 operator = validate[formname][i][operatorIndex];
1159 item1 = trim(form[validate[formname][i][nameIndex]].value);
1160 if (operator.charAt(0) == 'u') {
1161 item1 = item1.toUpperCase();
1162 operator = operator.substring(1);
1163 } else if (operator.charAt(0) == 'l') {
1164 item1 = item1.toLowerCase();
1165 operator = operator.substring(1);
1167 for(j = 0; j < arr.length; j++){
1169 if((operator == "==" && val == item1) || (operator == "!=" && val != item1)){
1171 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
1176 if(trim(form[validate[formname][i][nameIndex]].value) == 'false'){
1177 //Fake an error so form does not submit
1187 /* nsingh: BUG#15102
1188 Check min max default field logic.
1189 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.*/
1190 if(formsWithFieldLogic){
1191 var invalidLogic=false;
1192 if(formsWithFieldLogic.min && formsWithFieldLogic.max && formsWithFieldLogic._default) {
1193 var showErrorsOn={min:{value:'min', show:false, obj:formsWithFieldLogic.min.value},
1194 max:{value:'max',show:false, obj:formsWithFieldLogic.max.value},
1195 _default:{value:'default',show:false, obj:formsWithFieldLogic._default.value},
1196 len:{value:'len', show:false, obj:parseInt(formsWithFieldLogic.len.value,10)}};
1198 var min = (formsWithFieldLogic.min.value !='') ? parseFloat(formsWithFieldLogic.min.value) : 'undef';
1199 var max = (formsWithFieldLogic.max.value !='') ? parseFloat(formsWithFieldLogic.max.value) : 'undef';
1200 var _default = (formsWithFieldLogic._default.value!='')? parseFloat(formsWithFieldLogic._default.value) : 'undef';
1202 /*Check all lengths are <= max size.*/
1203 for(var i in showErrorsOn){
1204 if(showErrorsOn[i].value!='len' && showErrorsOn[i].obj.length > showErrorsOn.len.obj){
1206 showErrorsOn[i].show=true;
1207 showErrorsOn.len.show=true;
1211 if(min!='undef' && max!='undef' && _default!='undef'){
1212 if(!inRange(_default,min,max)){
1214 showErrorsOn.min.show=true;
1215 showErrorsOn.max.show=true;
1216 showErrorsOn._default.show=true;
1219 if(min!='undef' && max!= 'undef' && min > max){
1220 invalidLogic = true;
1221 showErrorsOn.min.show=true;
1222 showErrorsOn.max.show=true;
1224 if(min!='undef' && _default!='undef' && _default < min){
1226 invalidLogic = true;
1227 showErrorsOn.min.show=true;
1228 showErrorsOn._default.show=true;
1230 if(max!='undef' && _default !='undef' && _default>max){
1232 invalidLogic = true;
1233 showErrorsOn.max.show=true;
1234 showErrorsOn._default.show=true;
1239 for(var error in showErrorsOn)
1240 if(showErrorsOn[error].show)
1241 add_error_style(formname,showErrorsOn[error].value, formsWithFieldLogic.msg);
1246 formsWithFieldLogic = null;
1249 if(formWithPrecision){
1250 if (!isValidPrecision(formWithPrecision.float.value, formWithPrecision.precision.value)){
1252 add_error_style(formname, 'default', SUGAR.language.get('app_strings', 'ERR_COMPATIBLE_PRECISION_VALUE'));
1260 if (isError == true) {
1262 if (self.pageYOffset) // all except Explorer
1264 nwX = self.pageXOffset;
1265 seX = self.innerWidth;
1266 nwY = self.pageYOffset;
1267 seY = self.innerHeight;
1269 else if (document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
1271 nwX = document.documentElement.scrollLeft;
1272 seX = document.documentElement.clientWidth;
1273 nwY = document.documentElement.scrollTop;
1274 seY = document.documentElement.clientHeight;
1276 else if (document.body) // all other Explorers
1278 nwX = document.body.scrollLeft;
1279 seX = document.body.clientWidth;
1280 nwY = document.body.scrollTop;
1281 seY = document.body.clientHeight;
1284 var inView = true; // is there an error within viewport of browser
1285 for(var wp = 0; wp < inputsWithErrors.length; wp++) {
1286 var elementCoor = findElementPos(inputsWithErrors[wp]);
1287 if(!(elementCoor.x >= nwX && elementCoor.y >= nwY &&
1288 elementCoor.x <= seX+nwX && elementCoor.y <= seY+nwY)) { // if input is not within viewport, modify for SI bug 52497
1290 scrollToTop = elementCoor.y - 75;
1291 scrollToLeft = elementCoor.x - 75;
1293 else { // on first input within viewport, don't scroll
1299 if(!inView) window.scrollTo(scrollToLeft,scrollToTop);
1304 disableOnUnloadEditView(form);
1311 * This array is used to remember mark status of rows in browse mode
1313 var marked_row = new Array;
1317 * Sets/unsets the pointer and marker in browse mode
1319 * @param object the table row
1320 * @param interger the row number
1321 * @param string the action calling this script (over, out or click)
1322 * @param string the default background color
1323 * @param string the color to use for mouseover
1324 * @param string the color to use for marking a row
1326 * @return boolean whether pointer is set or not
1328 function setPointer(theRow, theRowNum, theAction, theDefaultColor, thePointerColor, theMarkColor) {
1329 var theCells = null;
1331 // 1. Pointer and mark feature are disabled or the browser can't get the
1333 if ((thePointerColor == '' && theMarkColor == '')
1334 || typeof(theRow.style) == 'undefined') {
1338 // 2. Gets the current row and exits if the browser can't get it
1339 if (typeof(document.getElementsByTagName) != 'undefined') {
1340 theCells = theRow.getElementsByTagName('td');
1342 else if (typeof(theRow.cells) != 'undefined') {
1343 theCells = theRow.cells;
1349 // 3. Gets the current color...
1350 var rowCellsCnt = theCells.length;
1351 var domDetect = null;
1352 var currentColor = null;
1353 var newColor = null;
1354 // 3.1 ... with DOM compatible browsers except Opera that does not return
1355 // valid values with "getAttribute"
1356 if (typeof(window.opera) == 'undefined'
1357 && typeof(theCells[0].getAttribute) != 'undefined') {
1358 currentColor = theCells[0].getAttribute('bgcolor');
1361 // 3.2 ... with other browsers
1363 currentColor = theCells[0].style.backgroundColor;
1367 // 4. Defines the new color
1368 // 4.1 Current color is the default one
1369 if (currentColor == ''
1370 || (currentColor!= null && (currentColor.toLowerCase() == theDefaultColor.toLowerCase()))) {
1371 if (theAction == 'over' && thePointerColor != '') {
1372 newColor = thePointerColor;
1374 else if (theAction == 'click' && theMarkColor != '') {
1375 newColor = theMarkColor;
1376 marked_row[theRowNum] = true;
1379 // 4.1.2 Current color is the pointer one
1380 else if (currentColor!= null && (currentColor.toLowerCase() == thePointerColor.toLowerCase())
1381 && (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])) {
1382 if (theAction == 'out') {
1383 newColor = theDefaultColor;
1385 else if (theAction == 'click' && theMarkColor != '') {
1386 newColor = theMarkColor;
1387 marked_row[theRowNum] = true;
1390 // 4.1.3 Current color is the marker one
1391 else if (currentColor!= null && (currentColor.toLowerCase() == theMarkColor.toLowerCase())) {
1392 if (theAction == 'click') {
1393 newColor = (thePointerColor != '')
1396 marked_row[theRowNum] = (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])
1402 // 5. Sets the new color...
1405 // 5.1 ... with DOM compatible browsers except Opera
1407 for (c = 0; c < rowCellsCnt; c++) {
1408 theCells[c].setAttribute('bgcolor', newColor, 0);
1411 // 5.2 ... with other browsers
1413 for (c = 0; c < rowCellsCnt; c++) {
1414 theCells[c].style.backgroundColor = newColor;
1420 } // end of the 'setPointer()' function
1424 * listbox redirection
1426 function goToUrl(selObj, goToLocation) {
1427 eval("document.location.href = '" + goToLocation + "pos=" + selObj.options[selObj.selectedIndex].value + "'");
1432 var json_objects = new Object();
1434 function getXMLHTTPinstance() {
1435 var xmlhttp = false;
1436 var userAgent = navigator.userAgent.toLowerCase() ;
1438 // IE Check supports ActiveX controls
1439 if (userAgent.indexOf("msie") != -1 && userAgent.indexOf("mac") == -1 && userAgent.indexOf("opera") == -1) {
1440 var version = navigator.appVersion.match(/MSIE (.\..)/)[1] ;
1441 if(version >= 5.5 ) {
1443 xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
1447 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
1456 if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
1457 xmlhttp = new XMLHttpRequest();
1462 // NOW LOAD THE OBJECT..
1463 var global_xmlhttp = getXMLHTTPinstance();
1465 function http_fetch_sync(url,post_data) {
1466 global_xmlhttp = getXMLHTTPinstance();
1469 if(typeof(post_data) != 'undefined') method = 'POST';
1471 global_xmlhttp.open(method, url,false);
1474 alert('message:'+e.message+":url:"+url);
1476 if(method == 'POST') {
1477 global_xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
1480 global_xmlhttp.send(post_data);
1482 if (SUGAR.util.isLoginPage(global_xmlhttp.responseText))
1485 var args = {"responseText" : global_xmlhttp.responseText,
1486 "responseXML" : global_xmlhttp.responseXML,
1487 "request_id" : typeof(request_id) != "undefined" ? request_id : 0};
1491 // this is a GET unless post_data is defined
1493 function http_fetch_async(url,callback,request_id,post_data) {
1495 if(typeof(post_data) != 'undefined') {
1500 global_xmlhttp.open(method, url,true);
1503 alert('message:'+e.message+":url:"+url);
1505 if(method == 'POST') {
1506 global_xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
1508 global_xmlhttp.onreadystatechange = function() {
1509 if(global_xmlhttp.readyState==4) {
1510 if(global_xmlhttp.status == 200) {
1511 if (SUGAR.util.isLoginPage(global_xmlhttp.responseText))
1513 var args = {"responseText" : global_xmlhttp.responseText,
1514 "responseXML" : global_xmlhttp.responseXML,
1515 "request_id" : request_id };
1516 callback.call(document,args);
1519 alert("There was a problem retrieving the XML data:\n" + global_xmlhttp.statusText);
1523 global_xmlhttp.send(post_data);
1526 function insert_at_cursor(field, value) {
1528 if (document.selection) {
1530 sel = document.selection.createRange();
1534 else if(field.selectionStart || field.selectionStart == '0') {
1535 var start_pos = field.selectionStart;
1536 var end_pos = field.selectionEnd;
1537 field.value = field.value.substring(0, start_pos) + value + field.value.substring(end_pos, field.value.length);
1540 field.value += value;
1544 function checkParentType(type,button) {
1545 if(button == null) {
1548 if(typeof disabledModules != 'undefined' && typeof(disabledModules[type]) != 'undefined') {
1549 button.disabled='disabled';
1552 button.disabled = false;
1556 function parseDate(input, format) {
1558 format = format.replace(/%/g, '');
1559 sep = format.charAt(1);
1560 yAt = format.indexOf('Y')
1561 // 1-1-06 or 1-12-06 or 1-1-2006 or 1-12-2006
1562 if(date.match(/^\d{1,2}[\/-]\d{1,2}[\/-]\d{2,4}$/) && yAt == 4) {
1563 if(date.match(/^\d{1}[\/-].*$/)) date = '0' + date;
1564 if(date.match(/^\d{2}[\/-]\d{1}[\/-].*$/)) date = date.substring(0,3) + '0' + date.substring(3,date.length);
1565 if(date.match(/^\d{2}[\/-]\d{2}[\/-]\d{2}$/)) date = date.substring(0,6) + '20' + date.substring(6,date.length);
1567 // 06-11-1 or 06-1-1
1568 else if(date.match(/^\d{2,4}[\/-]\d{1,2}[\/-]\d{1,2}$/)) {
1569 if(date.match(/^\d{2}[\/-].*$/)) date = '20' + date;
1570 if(date.match(/^\d{4}[\/-]\d{1}[\/-].*$/)) date = date.substring(0,5) + '0' + date.substring(5,date.length);
1571 if(date.match(/^\d{4}[\/-]\d{2}[\/-]\d{1}$/)) date = date.substring(0,8) + '0' + date.substring(8,date.length);
1573 else if(date.match(/^\d{4,8}$/)) { // digits only
1575 if(date.match(/^\d{8}$/)) digits = 8;// match for 8 digits
1576 else if(date.match(/\d{6}/)) digits = 6;// match for 5 digits
1577 else if(date.match(/\d{4}/)) digits = 4;// match for 5 digits
1578 else if(date.match(/\d{5}/)) digits = 5;// match for 5 digits
1583 case 4: date = '20' + date.substring(0,2) + sep + '0' + date.substring(2, 3) + sep + '0' + date.substring(3,4); break;
1584 case 5: date = '20' + date.substring(0,2) + sep + date.substring(2, 4) + sep + '0' + date.substring(4,5); break;
1585 case 6: date = '20' + date.substring(0,2) + sep + date.substring(2, 4) + sep + date.substring(4,6); break;
1586 case 8: date = date.substring(0,4) + sep + date.substring(4, 6) + sep + date.substring(6,8); break;
1591 case 4: date = '0' + date.substring(0,1) + sep + '20' + date.substring(1, 3) + sep + '0' + date.substring(3,4); break;
1592 case 5: date = date.substring(0,2) + sep + '20' + date.substring(2, 4) + sep + '0' + date.substring(4,5); break;
1593 case 6: date = date.substring(0,2) + sep + '20' + date.substring(2, 4) + sep + date.substring(4,6); break;
1594 case 8: date = date.substring(0,2) + sep + date.substring(2, 6) + sep + date.substring(6,8); break;
1598 case 4: date = '0' + date.substring(0,1) + sep + '0' + date.substring(1, 2) + sep + '20' + date.substring(2,4); break;
1599 case 5: date = '0' + date.substring(0,1) + sep + date.substring(1, 3) + sep + '20' + date.substring(3,5); break;
1600 case 6: date = date.substring(0,2) + sep + date.substring(2, 4) + sep + '20' + date.substring(4,6); break;
1601 case 8: date = date.substring(0,2) + sep + date.substring(2, 4) + sep + date.substring(4,8); break;
1606 date = date.replace(/[\/-]/g, sep);
1610 // find obj's position
1611 function findElementPos(obj) {
1614 if (obj.offsetParent) {
1615 while (obj.offsetParent) {
1616 x += obj.offsetLeft;
1618 obj = obj.offsetParent;
1620 }//if offsetParent exists
1621 else if (obj.x && obj.y) {
1625 return new coordinate(x, y);
1629 // get dimensions of the browser window
1630 function getClientDim() {
1631 var nwX, nwY, seX, seY;
1632 if (self.pageYOffset) // all except Explorer
1634 nwX = self.pageXOffset;
1635 seX = self.innerWidth + nwX;
1636 nwY = self.pageYOffset;
1637 seY = self.innerHeight + nwY;
1639 else if (document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
1641 nwX = document.documentElement.scrollLeft;
1642 seX = document.documentElement.clientWidth + nwX;
1643 nwY = document.documentElement.scrollTop;
1644 seY = document.documentElement.clientHeight + nwY;
1646 else if (document.body) // all other Explorers
1648 nwX = document.body.scrollLeft;
1649 seX = document.body.clientWidth + nwX;
1650 nwY = document.body.scrollTop;
1651 seY = document.body.clientHeight + nwY;
1653 return {'nw' : new coordinate(nwX, nwY), 'se' : new coordinate(seX, seY)};
1657 * stop propagation on events
1659 function freezeEvent(e) {
1661 if (e.preventDefault) e.preventDefault();
1662 e.returnValue = false;
1663 e.cancelBubble = true;
1664 if (e.stopPropagation) e.stopPropagation();
1673 function coordinate(_x, _y) {
1682 return new position(this.x + rh.x, this.y + rh.y);
1686 return new position(this.x + rh.x, this.y + rh.y);
1690 // sends theForm via AJAX and fills in the theDiv
1691 function sendAndRetrieve(theForm, theDiv, loadingStr) {
1692 function success(data) {
1693 document.getElementById(theDiv).innerHTML = data.responseText;
1694 ajaxStatus.hideStatus();
1696 if(typeof loadingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
1697 ajaxStatus.showStatus(loadingStr);
1698 oForm = new YAHOO.util.Element(theForm);
1699 if ( oForm.get('enctype') && oForm.get('enctype') == 'multipart/form-data' ) {
1700 // the second argument is true to indicate file upload.
1701 YAHOO.util.Connect.setForm(theForm, true);
1702 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {upload: success, failure: success});
1704 YAHOO.util.Connect.setForm(theForm);
1705 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
1710 //save the form and redirect
1711 function sendAndRedirect(theForm, loadingStr, redirect_location) {
1712 function success(data) {
1713 if(redirect_location){
1714 location.href=redirect_location;
1716 ajaxStatus.hideStatus();
1718 if(typeof loadingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
1719 ajaxStatus.showStatus(loadingStr);
1720 oForm = new YAHOO.util.Element(theForm);
1721 if ( oForm.get('enctype') && oForm.get('enctype') == 'multipart/form-data' ) {
1722 // the second argument is true to indicate file upload.
1723 YAHOO.util.Connect.setForm(theForm, true);
1724 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {upload: success, failure: success});
1726 YAHOO.util.Connect.setForm(theForm);
1727 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
1732 function saveForm(theForm, theDiv, loadingStr) {
1733 if(check_form(theForm)){
1734 for(i = 0; i < ajaxFormArray.length; i++){
1735 if(ajaxFormArray[i] == theForm){
1736 ajaxFormArray.splice(i, 1);
1739 return sendAndRetrieve(theForm, loadingStr, theDiv);
1745 // Builds a "snapshot" of the form, so we can use it to see if someone has changed it.
1746 function snapshotForm(theForm) {
1747 var snapshotTxt = '';
1748 var elemList = theForm.elements;
1752 for( var i = 0; i < elemList.length ; i++ ) {
1754 if ( typeof(elem.type) == 'undefined' ) {
1758 elemType = elem.type.toLowerCase();
1760 snapshotTxt = snapshotTxt + elem.name;
1762 if ( elemType == 'text' || elemType == 'textarea' || elemType == 'password' ) {
1763 snapshotTxt = snapshotTxt + elem.value;
1765 else if ( elemType == 'select' || elemType == 'select-one' || elemType == 'select-multiple' ) {
1766 var optionList = elem.options;
1767 for ( var ii = 0 ; ii < optionList.length ; ii++ ) {
1768 if ( optionList[ii].selected ) {
1769 snapshotTxt = snapshotTxt + optionList[ii].value;
1773 else if ( elemType == 'radio' || elemType == 'checkbox' ) {
1774 if ( elem.selected ) {
1775 snapshotTxt = snapshotTxt + 'checked';
1778 else if ( elemType == 'hidden' ) {
1779 snapshotTxt = snapshotTxt + elem.value;
1786 function initEditView(theForm) {
1787 if (SUGAR.util.ajaxCallInProgress()) {
1788 window.setTimeout(function(){initEditView(theForm);}, 100);
1792 if ( theForm == null || theForm.id == null ) {
1793 // Not much we can do here.
1797 // we don't need to check if the data is changed in the search popup
1798 if (theForm.id == 'popup_query_form' || theForm.id == 'MassUpdate') {
1801 if ( typeof editViewSnapshots == 'undefined' || editViewSnapshots == null ) {
1802 editViewSnapshots = new Object();
1804 if ( typeof SUGAR.loadedForms == 'undefined' || SUGAR.loadedForms == null) {
1805 SUGAR.loadedForms = new Object();
1808 editViewSnapshots[theForm.id] = snapshotForm(theForm);
1809 SUGAR.loadedForms[theForm.id] = true;
1812 function onUnloadEditView(theForm) {
1814 var dataHasChanged = false;
1815 if ( typeof editViewSnapshots == 'undefined' ) {
1816 // No snapshots, move along
1820 if ( typeof theForm == 'undefined' ) {
1821 // Need to check all editViewSnapshots
1822 for ( var idx in editViewSnapshots ) {
1824 theForm = document.getElementById(idx);
1825 // console.log('DEBUG: Checking all forms '+theForm.id);
1826 if ( theForm == null
1827 || typeof editViewSnapshots[theForm.id] == 'undefined'
1828 || editViewSnapshots[theForm.id] == null
1829 || !SUGAR.loadedForms[theForm.id]) {
1833 var snap = snapshotForm(theForm);
1834 if ( editViewSnapshots[theForm.id] != snap ) {
1835 dataHasChanged = true;
1839 // Just need to check a single form for changes
1840 if ( editViewSnapshots == null || typeof theForm.id == 'undefined' || typeof editViewSnapshots[theForm.id] == 'undefined' || editViewSnapshots[theForm.id] == null ) {
1844 // console.log('DEBUG: Checking one form '+theForm.id);
1845 if ( editViewSnapshots[theForm.id] != snapshotForm(theForm) ) {
1846 // Data has changed.
1847 dataHasChanged = true;
1851 if ( dataHasChanged == true ) {
1852 return SUGAR.language.get('app_strings','WARN_UNSAVED_CHANGES');
1859 function disableOnUnloadEditView(theForm) {
1860 // If you don't pass anything in, it disables all checking
1861 if ( typeof theForm == 'undefined' || typeof editViewSnapshots == 'undefined' || theForm == null || editViewSnapshots == null) {
1862 window.onbeforeunload = null;
1863 editViewSnapshots = null;
1865 // console.log('DEBUG: Disabling all edit view checks');
1868 // Otherwise, it just disables it for this form
1869 if ( typeof(theForm.id) != 'undefined' && typeof(editViewSnapshots[theForm.id]) != 'undefined' ) {
1870 editViewSnapshots[theForm.id] = null;
1873 // console.log('DEBUG : Disabling just checks for '+theForm.id);
1879 * save some forms using an ajax call
1880 * theForms - the ids of all of theh forms to save
1881 * savingStr - the string to display when saving the form
1882 * completeStr - the string to display when the form has been saved
1884 function saveForms( savingStr, completeStr) {
1886 theForms = ajaxFormArray;
1887 function success(data) {
1888 var theForm = document.getElementById(ajaxFormArray[0]);
1889 document.getElementById('multiedit_'+theForm.id).innerHTML = data.responseText;
1890 var saveAllButton = document.getElementById('ajaxsaveall');
1891 ajaxFormArray.splice(index, 1);
1892 if(saveAllButton && ajaxFormArray.length <= 1){
1893 saveAllButton.style.visibility = 'hidden';
1896 if(index == theForms.length){
1897 ajaxStatus.showStatus(completeStr);
1898 window.setTimeout('ajaxStatus.hideStatus();', 2000);
1900 saveAllButton.style.visibility = 'hidden';
1905 if(typeof savingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
1906 ajaxStatus.showStatus(savingStr);
1908 //loop through the forms saving each one
1909 for(i = 0; i < theForms.length; i++){
1910 var theForm = document.getElementById(theForms[i]);
1911 if(check_form(theForm.id)){
1912 theForm.action.value='AjaxFormSave';
1913 YAHOO.util.Connect.setForm(theForm);
1914 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
1916 ajaxStatus.hideStatus();
1918 lastSubmitTime = lastSubmitTime-2000;
1923 // -- start sugarListView class
1924 // js functions used for ListView
1925 function sugarListView() {
1929 sugarListView.prototype.confirm_action = function(del) {
1931 return confirm( SUGAR.language.get('app_strings', 'NTC_DELETE_CONFIRMATION_NUM') + sugarListView.get_num_selected() + SUGAR.language.get('app_strings', 'NTC_DELETE_SELECTED_RECORDS'));
1934 return confirm( SUGAR.language.get('app_strings', 'NTC_UPDATE_CONFIRMATION_NUM') + sugarListView.get_num_selected() + SUGAR.language.get('app_strings', 'NTC_DELETE_SELECTED_RECORDS'));
1938 sugarListView.get_num_selected = function () {
1939 var selectCount = $("input[name='selectCount[]']:first");
1940 if(selectCount.length > 0)
1941 return parseInt(selectCount.val().replace("+", ""));
1945 sugarListView.update_count = function(count, add) {
1946 if(typeof document.MassUpdate != 'undefined') {
1947 the_form = document.MassUpdate;
1948 for(var wp = 0; wp < the_form.elements.length; wp++) {
1949 if(typeof the_form.elements[wp].name != 'undefined' && the_form.elements[wp].name == 'selectCount[]') {
1951 the_form.elements[wp].value = parseInt(the_form.elements[wp].value,10) + count;
1952 if (the_form.select_entire_list.value == 1 && the_form.show_plus.value) {
1953 the_form.elements[wp].value += '+';
1956 if (the_form.select_entire_list.value == 1 && the_form.show_plus.value) {
1957 the_form.elements[wp].value = count + '+';
1959 the_form.elements[wp].value = count;
1966 sugarListView.prototype.use_external_mail_client = function(no_record_txt, module) {
1967 selected_records = sugarListView.get_checks_count();
1968 if(selected_records <1) {
1969 alert(no_record_txt);
1973 if (document.MassUpdate.select_entire_list.value == 1) {
1974 if (totalCount > 10) {
1975 alert(totalCountError);
1980 else if (document.MassUpdate.massall.checked == true)
1984 sugarListView.get_checks();
1986 if(select) { // use selected items
1987 ids = document.MassUpdate.uid.value;
1989 else { // use current page
1990 inputs = document.MassUpdate.elements;
1992 for(i = 0; i < inputs.length; i++) {
1993 if(inputs[i].name == 'mass[]' && inputs[i].checked && typeof(inputs[i].value) != 'function') {
1994 ar.push(inputs[i].value);
1999 YAHOO.util.Connect.asyncRequest("POST", "index.php?", {
2000 success: this.use_external_mail_client_callback
2001 }, SUGAR.util.paramsToUrl({
2004 listViewExternalClient: 1,
2005 action_module: module,
2013 sugarListView.prototype.use_external_mail_client_callback = function(o)
2016 location.href = 'mailto:' + o.responseText;
2019 sugarListView.prototype.send_form_for_emails = function(select, currentModule, action, no_record_txt,action_module,totalCount, totalCountError) {
2020 if ( typeof(SUGAR.config.email_sugarclient_listviewmaxselect) != 'undefined' ) {
2024 maxCount = SUGAR.config.email_sugarclient_listviewmaxselect;
2027 if (document.MassUpdate.select_entire_list.value == 1) {
2028 if (totalCount > maxCount) {
2029 alert(totalCountError);
2034 else if (document.MassUpdate.massall.checked == true)
2039 sugarListView.get_checks();
2040 // create new form to post (can't access action property of MassUpdate form due to action input)
2041 var newForm = document.createElement('form');
2042 newForm.method = 'post';
2043 newForm.action = action;
2044 newForm.name = 'newForm';
2045 newForm.id = 'newForm';
2046 var uidTa = document.createElement('textarea');
2048 uidTa.style.display = 'none';
2050 if(select) { // use selected items
2051 uidTa.value = document.MassUpdate.uid.value;
2053 else { // use current page
2054 inputs = document.MassUpdate.elements;
2056 for(i = 0; i < inputs.length; i++) {
2057 if(inputs[i].name == 'mass[]' && inputs[i].checked && typeof(inputs[i].value) != 'function') {
2058 ar.push(inputs[i].value);
2061 uidTa.value = ar.join(',');
2064 if(uidTa.value == '') {
2065 alert(no_record_txt);
2069 var selectedArray = uidTa.value.split(",");
2070 if(selectedArray.length > maxCount) {
2071 alert(totalCountError);
2074 newForm.appendChild(uidTa);
2076 var moduleInput = document.createElement('input');
2077 moduleInput.name = 'module';
2078 moduleInput.type = 'hidden';
2079 moduleInput.value = currentModule;
2080 newForm.appendChild(moduleInput);
2082 var actionInput = document.createElement('input');
2083 actionInput.name = 'action';
2084 actionInput.type = 'hidden';
2085 actionInput.value = 'Compose';
2086 newForm.appendChild(actionInput);
2088 if (typeof action_module != 'undefined' && action_module!= '') {
2089 var actionModule = document.createElement('input');
2090 actionModule.name = 'action_module';
2091 actionModule.type = 'hidden';
2092 actionModule.value = action_module;
2093 newForm.appendChild(actionModule);
2095 //return_info must follow this pattern."&return_module=Accounts&return_action=index"
2096 if (typeof return_info!= 'undefined' && return_info != '') {
2097 var params= return_info.split('&');
2098 if (params.length > 0) {
2099 for (var i=0;i< params.length;i++) {
2100 if (params[i].length > 0) {
2101 var param_nv=params[i].split('=');
2102 if (param_nv.length==2){
2103 returnModule = document.createElement('input');
2104 returnModule.name = param_nv[0];
2105 returnModule.type = 'hidden';
2106 returnModule.value = param_nv[1];
2107 newForm.appendChild(returnModule);
2114 var isAjaxCall = document.createElement('input');
2115 isAjaxCall.name = 'ajaxCall';
2116 isAjaxCall.type = 'hidden';
2117 isAjaxCall.value = true;
2118 newForm.appendChild(isAjaxCall);
2120 var isListView = document.createElement('input');
2121 isListView.name = 'ListView';
2122 isListView.type = 'hidden';
2123 isListView.value = true;
2124 newForm.appendChild(isListView);
2126 var toPdf = document.createElement('input');
2127 toPdf.name = 'to_pdf';
2128 toPdf.type = 'hidden';
2130 newForm.appendChild(toPdf);
2132 //Grab the Quick Compose package for the listview
2133 YAHOO.util.Connect.setForm(newForm);
2136 success: function(o) {
2137 var resp = YAHOO.lang.JSON.parse(o.responseText);
2138 var quickComposePackage = new Object();
2139 quickComposePackage.composePackage = resp;
2140 quickComposePackage.fullComposeUrl = 'index.php?module=Emails&action=Compose&ListView=true' +
2141 '&uid=' + uidTa.value + '&action_module=' + action_module;
2143 SUGAR.quickCompose.init(quickComposePackage);
2147 YAHOO.util.Connect.asyncRequest('POST','index.php', callback,null);
2149 // awu Bug 18624: Fixing issue where a canceled Export and unselect of row will persist the uid field, clear the field
2150 document.MassUpdate.uid.value = '';
2155 sugarListView.prototype.send_form = function(select, currentModule, action, no_record_txt,action_module,return_info) {
2156 if (document.MassUpdate.select_entire_list.value == 1) {
2158 if(sugarListView.get_checks_count() < 1) {
2159 alert(no_record_txt);
2164 if ( action.indexOf('?') != -1 )
2165 href += '&module=' + currentModule;
2167 href += '?module=' + currentModule;
2170 href += return_info;
2171 var newForm = document.createElement('form');
2172 newForm.method = 'post';
2173 newForm.action = href;
2174 newForm.name = 'newForm';
2175 newForm.id = 'newForm';
2176 var postTa = document.createElement('textarea');
2177 postTa.name = 'current_post';
2178 postTa.value = document.MassUpdate.current_query_by_page.value;
2179 postTa.style.display = 'none';
2180 newForm.appendChild(postTa);
2181 document.MassUpdate.parentNode.appendChild(newForm);
2185 else if (document.MassUpdate.massall.checked == true)
2190 sugarListView.get_checks();
2191 // create new form to post (can't access action property of MassUpdate form due to action input)
2192 var newForm = document.createElement('form');
2193 newForm.method = 'post';
2194 newForm.action = action;
2195 newForm.name = 'newForm';
2196 newForm.id = 'newForm';
2197 var uidTa = document.createElement('textarea');
2199 uidTa.style.display = 'none';
2200 uidTa.value = document.MassUpdate.uid.value;
2202 if(uidTa.value == '') {
2203 alert(no_record_txt);
2207 newForm.appendChild(uidTa);
2209 var moduleInput = document.createElement('input');
2210 moduleInput.name = 'module';
2211 moduleInput.type = 'hidden';
2212 moduleInput.value = currentModule;
2213 newForm.appendChild(moduleInput);
2215 var actionInput = document.createElement('input');
2216 actionInput.name = 'action';
2217 actionInput.type = 'hidden';
2218 actionInput.value = 'index';
2219 newForm.appendChild(actionInput);
2221 if (typeof action_module != 'undefined' && action_module!= '') {
2222 var actionModule = document.createElement('input');
2223 actionModule.name = 'action_module';
2224 actionModule.type = 'hidden';
2225 actionModule.value = action_module;
2226 newForm.appendChild(actionModule);
2228 //return_info must follow this pattern."&return_module=Accounts&return_action=index"
2229 if (typeof return_info!= 'undefined' && return_info != '') {
2230 var params= return_info.split('&');
2231 if (params.length > 0) {
2232 for (var i=0;i< params.length;i++) {
2233 if (params[i].length > 0) {
2234 var param_nv=params[i].split('=');
2235 if (param_nv.length==2){
2236 returnModule = document.createElement('input');
2237 returnModule.name = param_nv[0];
2238 returnModule.type = 'hidden';
2239 returnModule.value = param_nv[1];
2240 newForm.appendChild(returnModule);
2247 document.MassUpdate.parentNode.appendChild(newForm);
2250 // awu Bug 18624: Fixing issue where a canceled Export and unselect of row will persist the uid field, clear the field
2251 document.MassUpdate.uid.value = '';
2255 //return a count of checked row.
2256 sugarListView.get_checks_count = function() {
2259 if(document.MassUpdate.uid.value != '') {
2260 oldUids = document.MassUpdate.uid.value.split(',');
2261 for(uid in oldUids) {
2262 if(typeof(oldUids[uid]) != 'function') {
2263 ar[oldUids[uid]] = 1;
2267 // build associated array of uids, associated array ensures uniqueness
2268 inputs = document.MassUpdate.elements;
2269 for(i = 0; i < inputs.length; i++) {
2270 if(inputs[i].name == 'mass[]') {
2271 ar[inputs[i].value] = (inputs[i].checked) ? 1 : 0; // 0 of it is unchecked
2275 // build regular array of uids
2278 if((typeof(ar[i]) != 'function') && ar[i] == 1) {
2286 // saves the checks on the current page into the uid textarea
2287 sugarListView.get_checks = function() {
2289 if(typeof document.MassUpdate != 'undefined' ){
2290 if(document.MassUpdate.uid.value != '') {
2291 oldUids = document.MassUpdate.uid.value.split(',');
2292 for(uid in oldUids) {
2293 if(typeof(oldUids[uid]) != 'function') {
2294 ar[oldUids[uid]] = 1;
2299 // build associated array of uids, associated array ensures uniqueness
2300 inputs = document.MassUpdate.elements;
2301 for(i = 0; i < inputs.length; i++) {
2302 if(inputs[i].name == 'mass[]') {
2303 ar[inputs[i].value] = (inputs[i].checked) ? 1 : 0; // 0 of it is unchecked
2307 // build regular array of uids
2310 if(typeof(ar[i]) != 'function' && ar[i] == 1) {
2315 document.MassUpdate.uid.value = uids.join(',');
2317 if(uids.length == 0) return false; // return false if no checks to get
2318 return true; // there are saved checks
2323 sugarListView.prototype.order_checks = function(order,orderBy,moduleString){
2324 checks = sugarListView.get_checks();
2325 eval('document.MassUpdate.' + moduleString + '.value = orderBy');
2326 document.MassUpdate.lvso.value = order;
2327 if(typeof document.MassUpdate.massupdate != 'undefined') {
2328 document.MassUpdate.massupdate.value = 'false';
2331 //we must first clear the action of massupdate, change it to index
2332 document.MassUpdate.action.value = document.MassUpdate.return_action.value;
2333 document.MassUpdate.return_module.value='';
2334 document.MassUpdate.return_action.value='';
2335 document.MassUpdate.submit();
2339 sugarListView.prototype.save_checks = function(offset, moduleString) {
2340 checks = sugarListView.get_checks();
2341 if(typeof document.MassUpdate != 'undefined'){
2342 eval('document.MassUpdate.' + moduleString + '.value = offset');
2344 if(typeof document.MassUpdate.massupdate != 'undefined') {
2345 document.MassUpdate.massupdate.value = 'false';
2348 //we must first clear the action of massupdate, change it to index
2349 document.MassUpdate.action.value = document.MassUpdate.return_action.value;
2350 document.MassUpdate.return_module.value='';
2351 document.MassUpdate.return_action.value='';
2352 document.MassUpdate.submit();
2360 sugarListView.prototype.check_item = function(cb, form) {
2362 sugarListView.update_count(1, true);
2365 sugarListView.update_count(-1, true);
2366 if(typeof form != 'undefined' && form != null) {
2367 sugarListView.prototype.updateUid(cb, form);
2370 sugarListView.prototype.toggleSelected();
2373 sugarListView.prototype.toggleSelected = function() {
2375 var numSelected = sugarListView.get_num_selected();
2376 var selectedRecords = document.getElementById("selectedRecordsTop");
2377 var selectActions = document.getElementById("selectActions");
2378 var selectActionsDisabled = document.getElementById("selectActionsDisabled");
2379 if(numSelected > 0) {
2380 $(selectedRecords).removeAttr("style").addClass("show");
2381 $(".selectActionsDisabled").hide();
2382 jQuery('ul[name=selectActions]').each(function () {
2383 jQuery(this).removeAttr("style").addClass("show");
2387 $(selectedRecords).hide();
2388 $(".selectActionsDisabled").removeAttr("style").addClass("show");
2389 jQuery('ul[name=selectActions]').each(function () {
2390 jQuery(this).hide();
2396 /**#28000, remove the unselect record id from MassUpdate.uid **/
2397 sugarListView.prototype.updateUid = function(cb , form){
2398 if(form.name == 'MassUpdate' && form.uid && form.uid.value && cb.value && form.uid.value.indexOf(cb.value) != -1){
2399 if(form.uid.value.indexOf(','+cb.value)!= -1){
2400 form.uid.value = form.uid.value.replace(','+cb.value , '');
2401 }else if(form.uid.value.indexOf(cb.value + ',')!= -1){
2402 form.uid.value = form.uid.value.replace(cb.value + ',' , '');
2403 }else if(form.uid.value.indexOf(cb.value)!= -1){
2404 form.uid.value = form.uid.value.replace(cb.value , '');
2409 sugarListView.prototype.check_entire_list = function(form, field, value, list_count) {
2410 // count number of items
2412 $(document.MassUpdate.massall).each(function(){
2413 $(this).attr('checked', true).attr('disabled', true);
2415 for (i = 0; i < form.elements.length; i++) {
2416 if(form.elements[i].name == field && form.elements[i].disabled == false) {
2417 if(form.elements[i].checked != value) count++;
2418 form.elements[i].checked = value;
2419 form.elements[i].disabled = true;
2422 document.MassUpdate.select_entire_list.value = 1;
2423 sugarListView.update_count(list_count, false);
2424 sugarListView.prototype.toggleSelected();
2427 sugarListView.prototype.check_all = function(form, field, value, pageTotal) {
2428 // count number of items
2430 $(document.MassUpdate.massall).each(function(){$(this).attr('checked', value);});
2431 if (document.MassUpdate.select_entire_list &&
2432 document.MassUpdate.select_entire_list.value == 1)
2434 sugarListView.prototype.toggleSelected();
2435 $(document.MassUpdate.massall).each(function(){$(this).attr('disabled', true);});
2439 $(document.MassUpdate.massall).each(function(){$(this).attr('disabled', false);});
2441 for (i = 0; i < form.elements.length; i++) {
2442 if(form.elements[i].name == field && !(form.elements[i].disabled == true && form.elements[i].checked == false)) {
2443 form.elements[i].disabled = false;
2445 if(form.elements[i].checked != value)
2447 form.elements[i].checked = value;
2449 sugarListView.prototype.updateUid(form.elements[i], form);
2454 sugarListView.update_count(pageTotal);
2456 sugarListView.update_count(count, true);
2458 sugarListView.update_count(-1 * count, true);
2460 sugarListView.prototype.toggleSelected();
2462 sugarListView.check_all = sugarListView.prototype.check_all;
2463 sugarListView.confirm_action = sugarListView.prototype.confirm_action;
2465 sugarListView.prototype.check_boxes = function() {
2466 var inputsCount = 0;
2467 var checkedCount = 0;
2468 var existing_onload = window.onload;
2469 var theForm = document.MassUpdate;
2470 inputs_array = theForm.elements;
2472 if(typeof theForm.uid.value != 'undefined' && theForm.uid.value != "") {
2473 checked_items = theForm.uid.value.split(",");
2474 if (theForm.select_entire_list.value == 1) {
2475 document.MassUpdate.massall.disabled = true;
2476 sugarListView.prototype.toggleSelected();
2477 $("a[name=selectall]:first").click();
2480 for(var wp = 0 ; wp < inputs_array.length; wp++) {
2481 if(inputs_array[wp].name == "mass[]") {
2483 if (theForm.select_entire_list.value == 1) {
2484 inputs_array[wp].checked = true;
2485 inputs_array[wp].disabled = true;
2489 for(i in checked_items) {
2490 if(inputs_array[wp].value == checked_items[i]) {
2492 inputs_array[wp].checked = true;
2493 //Bug#52748: Total # of checked items are calculated in back-end side
2494 //sugarListView.prototype.check_item(inputs_array[wp], document.MassUpdate);
2502 for(var wp = 0 ; wp < inputs_array.length; wp++) {
2503 if(inputs_array[wp].name == "mass[]") {
2504 inputs_array[wp].checked = false;
2505 inputs_array[wp].disabled = false;
2508 if (document.MassUpdate.massall) {
2509 document.MassUpdate.massall.checked = false;
2510 document.MassUpdate.massall.disabled = false;
2512 sugarListView.update_count(0)
2514 if(checkedCount > 0 && checkedCount == inputsCount)
2515 document.MassUpdate.massall.checked = true;
2520 * This function is used in Email Template Module's listview.
2521 * It will check whether the templates are used in Campaing->EmailMarketing.
2522 * If true, it will notify user.
2524 function check_used_email_templates() {
2525 var ids = document.MassUpdate.uid.value;
2527 success:function(r) {
2528 if(r.responseText != '') {
2529 if(!confirm(SUGAR.language.get('app_strings','NTC_TEMPLATES_IS_USED') + r.responseText)) {
2533 document.MassUpdate.submit();
2537 url = "index.php?module=EmailTemplates&action=CheckDeletable&from=ListView&to_pdf=1&records="+ids;
2538 YAHOO.util.Connect.asyncRequest('POST',url, call_back,null);
2542 sugarListView.prototype.send_mass_update = function(mode, no_record_txt, del) {
2543 formValid = check_form('MassUpdate');
2544 if(!formValid && !del) return false;
2547 if (document.MassUpdate.select_entire_list &&
2548 document.MassUpdate.select_entire_list.value == 1)
2553 var ar = new Array();
2557 for(var wp = 0; wp < document.MassUpdate.elements.length; wp++) {
2558 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)+'$');
2559 //when the uid is already in document.MassUpdate.uid.value, we should not add it to ar.
2560 if(typeof document.MassUpdate.elements[wp].name != 'undefined'
2561 && document.MassUpdate.elements[wp].name == 'mass[]'
2562 && document.MassUpdate.elements[wp].checked
2563 && !reg_for_existing_uid.test(document.MassUpdate.uid.value)) {
2564 ar.push(document.MassUpdate.elements[wp].value);
2567 if(document.MassUpdate.uid.value != '') document.MassUpdate.uid.value += ',';
2568 document.MassUpdate.uid.value += ar.join(',');
2569 if(document.MassUpdate.uid.value == '') {
2570 alert(no_record_txt);
2573 if(typeof(current_admin_id)!='undefined' && document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'Users' && (document.MassUpdate.is_admin.value!='' || document.MassUpdate.status.value!='')) {
2574 var reg_for_current_admin_id = new RegExp('^'+current_admin_id+'[\s]*,|,[\s]*'+current_admin_id+'[\s]*,|,[\s]*'+current_admin_id+'$|^'+current_admin_id+'$');
2575 if(reg_for_current_admin_id.test(document.MassUpdate.uid.value)) {
2576 //if current user is admin, we should not allow massupdate the user_type and status of himself
2577 alert(SUGAR.language.get('Users','LBL_LAST_ADMIN_NOTICE'));
2583 var entireInput = document.createElement('input');
2584 entireInput.name = 'entire';
2585 entireInput.type = 'hidden';
2586 entireInput.value = 'index';
2587 document.MassUpdate.appendChild(entireInput);
2588 //confirm(no_record_txt);
2589 if(document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'Users' && (document.MassUpdate.is_admin.value!='' || document.MassUpdate.status.value!='')) {
2590 alert(SUGAR.language.get('Users','LBL_LAST_ADMIN_NOTICE'));
2596 if(!sugarListView.confirm_action(del))
2600 var deleteInput = document.createElement('input');
2601 deleteInput.name = 'Delete';
2602 deleteInput.type = 'hidden';
2603 deleteInput.value = true;
2604 document.MassUpdate.appendChild(deleteInput);
2605 if(document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'EmailTemplates') {
2606 check_used_email_templates();
2612 document.MassUpdate.submit();
2617 sugarListView.prototype.clear_all = function() {
2618 document.MassUpdate.uid.value = '';
2619 document.MassUpdate.select_entire_list.value = 0;
2620 sugarListView.check_all(document.MassUpdate, 'mass[]', false);
2621 $(document.MassUpdate.massall).each(function(){
2622 $(this).attr('checked', false).attr('disabled', false);
2624 sugarListView.update_count(0);
2625 sugarListView.prototype.toggleSelected();
2628 sListView = new sugarListView();
2629 // -- end sugarListView class
2631 // format and unformat numbers
2632 function unformatNumber(n, num_grp_sep, dec_sep) {
2633 var x=unformatNumberNoParse(n, num_grp_sep, dec_sep);
2636 return parseFloat(x);
2641 function unformatNumberNoParse(n, num_grp_sep, dec_sep) {
2642 if(typeof num_grp_sep == 'undefined' || typeof dec_sep == 'undefined') return n;
2643 n = n ? n.toString() : '';
2646 if(num_grp_sep != '')
2648 num_grp_sep_re = new RegExp('\\'+num_grp_sep, 'g');
2649 n = n.replace(num_grp_sep_re, '');
2652 n = n.replace(dec_sep, '.');
2654 if(typeof CurrencySymbols != 'undefined') {
2655 // Need to strip out the currency symbols from the start.
2656 for ( var idx in CurrencySymbols ) {
2657 n = n.replace(CurrencySymbols[idx], '');
2665 // round parameter can be negative for decimal, precision has to be postive
2666 function formatNumber(n, num_grp_sep, dec_sep, round, precision) {
2667 if(typeof num_grp_sep == 'undefined' || typeof dec_sep == 'undefined') return n;
2668 n = n ? n.toString() : '';
2669 if(n.split) n = n.split('.');
2672 if(n.length > 2) return n.join('.'); // that's not a num!
2674 if(typeof round != 'undefined') {
2675 if(round > 0 && n.length > 1) { // round to decimal
2676 n[1] = parseFloat('0.' + n[1]);
2677 n[1] = Math.round(n[1] * Math.pow(10, round)) / Math.pow(10, round);
2678 n[1] = n[1].toString().split('.')[1];
2680 if(round <= 0) { // round to whole number
2681 n[0] = Math.round(parseInt(n[0],10) * Math.pow(10, round)) / Math.pow(10, round);
2686 if(typeof precision != 'undefined' && precision >= 0) {
2687 if(n.length > 1 && typeof n[1] != 'undefined') n[1] = n[1].substring(0, precision); // cut off precision
2689 if(n[1].length < precision) {
2690 for(var wp = n[1].length; wp < precision; wp++) n[1] += '0';
2694 regex = /(\d+)(\d{3})/;
2695 while(num_grp_sep != '' && regex.test(n[0])) n[0] = n[0].toString().replace(regex, '$1' + num_grp_sep + '$2');
2696 return n[0] + (n.length > 1 && n[1] != '' ? dec_sep + n[1] : '');
2699 // --- begin ajax status class
2700 SUGAR.ajaxStatusClass = function() {};
2701 SUGAR.ajaxStatusClass.prototype.statusDiv = null;
2702 SUGAR.ajaxStatusClass.prototype.oldOnScroll = null;
2703 SUGAR.ajaxStatusClass.prototype.shown = false; // state of the status window
2705 // reposition the status div, top and centered
2706 SUGAR.ajaxStatusClass.prototype.positionStatus = function() {
2707 //this.statusDiv.style.top = document.body.scrollTop + 8 + 'px';
2708 statusDivRegion = YAHOO.util.Dom.getRegion(this.statusDiv);
2709 statusDivWidth = statusDivRegion.right - statusDivRegion.left;
2710 this.statusDiv.style.left = YAHOO.util.Dom.getViewportWidth() / 2 - statusDivWidth / 2 + 'px';
2713 // private func, create the status div
2714 SUGAR.ajaxStatusClass.prototype.createStatus = function(text) {
2715 statusDiv = document.createElement('div');
2716 statusDiv.className = 'dataLabel';
2717 statusDiv.id = 'ajaxStatusDiv';
2718 document.body.appendChild(statusDiv);
2719 this.statusDiv = document.getElementById('ajaxStatusDiv');
2722 // public - show the status div with text
2723 SUGAR.ajaxStatusClass.prototype.showStatus = function(text) {
2724 if(!this.statusDiv) {
2725 this.createStatus(text);
2728 this.statusDiv.style.display = '';
2730 this.statusDiv.innerHTML = ' <b>' + text + '</b> ';
2731 this.positionStatus();
2734 this.statusDiv.style.display = '';
2735 if(window.onscroll) this.oldOnScroll = window.onscroll; // save onScroll
2736 window.onscroll = this.positionStatus;
2741 SUGAR.ajaxStatusClass.prototype.hideStatus = function(text) {
2742 if(!this.shown) return;
2744 if(this.oldOnScroll) window.onscroll = this.oldOnScroll;
2745 else window.onscroll = '';
2746 this.statusDiv.style.display = 'none';
2749 SUGAR.ajaxStatusClass.prototype.flashStatus = function(text, time){
2750 this.showStatus(text);
2751 window.setTimeout('ajaxStatus.hideStatus();', time);
2755 var ajaxStatus = new SUGAR.ajaxStatusClass();
2756 // --- end ajax status class
2759 * Unified Search Advanced - for global search
2761 SUGAR.unifiedSearchAdvanced = function() {
2771 SUGAR.unifiedSearchAdvanced.usa_div = document.getElementById('unified_search_advanced_div');
2772 SUGAR.unifiedSearchAdvanced.usa_img = document.getElementById('unified_search_advanced_img');
2774 if(!SUGAR.unifiedSearchAdvanced.usa_div || !SUGAR.unifiedSearchAdvanced.usa_img) return;
2775 var attributes = { height: { to: 300 } };
2776 SUGAR.unifiedSearchAdvanced.anim_open = new YAHOO.util.Anim('unified_search_advanced_div', attributes );
2777 SUGAR.unifiedSearchAdvanced.anim_open.duration = 0.75;
2778 SUGAR.unifiedSearchAdvanced.anim_close = new YAHOO.util.Anim('unified_search_advanced_div', { height: {to: 0} } );
2779 SUGAR.unifiedSearchAdvanced.anim_close.duration = 0.75;
2780 //SUGAR.unifiedSearchAdvanced.anim_close.onComplete.subscribe(function() {SUGAR.unifiedSearchAdvanced.usa_div.style.display = 'none'});
2782 SUGAR.unifiedSearchAdvanced.usa_img._x = YAHOO.util.Dom.getX(SUGAR.unifiedSearchAdvanced.usa_img);
2783 SUGAR.unifiedSearchAdvanced.usa_img._y = YAHOO.util.Dom.getY(SUGAR.unifiedSearchAdvanced.usa_img);
2786 SUGAR.unifiedSearchAdvanced.usa_open = false;
2787 SUGAR.unifiedSearchAdvanced.usa_content = null;
2789 YAHOO.util.Event.addListener('unified_search_advanced_img', 'click', SUGAR.unifiedSearchAdvanced.get_content);
2792 get_content: function(e)
2794 query_string = trim(document.getElementById('query_string').value);
2795 if(query_string != '')
2797 window.location.href = 'index.php?module=Home&action=UnifiedSearch&query_string=' + query_string;
2799 window.location.href = 'index.php?module=Home&action=UnifiedSearch&form_only=true';
2803 animate: function(data) {
2804 ajaxStatus.hideStatus();
2807 SUGAR.unifiedSearchAdvanced.usa_content = data.responseText;
2808 SUGAR.unifiedSearchAdvanced.usa_div.innerHTML = SUGAR.unifiedSearchAdvanced.usa_content;
2810 if(SUGAR.unifiedSearchAdvanced.usa_open) {
2811 document.UnifiedSearch.advanced.value = 'false';
2812 SUGAR.unifiedSearchAdvanced.anim_close.animate();
2815 document.UnifiedSearch.advanced.value = 'true';
2816 SUGAR.unifiedSearchAdvanced.usa_div.style.display = '';
2817 YAHOO.util.Dom.setX(SUGAR.unifiedSearchAdvanced.usa_div, SUGAR.unifiedSearchAdvanced.usa_img._x - 90);
2818 YAHOO.util.Dom.setY(SUGAR.unifiedSearchAdvanced.usa_div, SUGAR.unifiedSearchAdvanced.usa_img._y + 15);
2819 SUGAR.unifiedSearchAdvanced.anim_open.animate();
2821 SUGAR.unifiedSearchAdvanced.usa_open = !SUGAR.unifiedSearchAdvanced.usa_open;
2826 checkUsaAdvanced: function() {
2827 if(document.UnifiedSearch.advanced.value == 'true') {
2828 document.UnifiedSearchAdvanced.query_string.value = document.UnifiedSearch.query_string.value;
2829 document.UnifiedSearchAdvanced.submit();
2836 if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.unifiedSearchAdvanced.init);
2841 * Toggles the header
2843 toggleHeader : function() {
2844 var h = document.getElementById('header');
2848 if(h.style.display == 'none') {
2849 h.style.display = '';
2851 h.style.display = 'none';
2855 alert(SUGAR.language.get("app_strings", "ERR_NO_HEADER_ID"));
2862 * General Sugar Utils
2864 SUGAR.util = function () {
2865 var additionalDetailsCache;
2866 var additionalDetailsCalls;
2867 var additionalDetailsRpcCall;
2870 getAndRemove : function (el) {
2871 if (YAHOO && YAHOO.util && YAHOO.util.Dom)
2872 el = YAHOO.util.Dom.get(el);
2873 else if (typeof (el) == "string")
2874 el = document.getElementById(el);
2875 if (el && el.parentNode)
2876 el.parentNode.removeChild(el);
2880 paramsToUrl : function (params) {
2882 for (var i in params)
2884 if (params.hasOwnProperty(i))
2886 parts.push(encodeURIComponent(i) + '=' + encodeURIComponent(params[i]));
2889 return parts.join("&")+"&";
2891 // Evaluates a script in a global context
2892 // Workarounds based on findings by Jim Driscoll
2893 // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
2894 globalEval: function( data ) {
2895 var rnotwhite = /\S/;
2896 if ( data && rnotwhite.test( data ) ) {
2897 // We use execScript on Internet Explorer
2898 // We use an anonymous function so that context is window
2899 // rather than jQuery in Firefox
2900 ( window.execScript || function( data ) {
2901 window[ "eval" ].call( window, data );
2905 evalScript:function(text){
2907 var waitUntilLoaded = function(){
2908 SUGAR.evalScript_waitCount--;
2909 if (SUGAR.evalScript_waitCount == 0) {
2910 var headElem = document.getElementsByTagName('head')[0];
2911 for ( var i = 0; i < SUGAR.evalScript_evalElem.length; i++) {
2912 var tmpElem = document.createElement('script');
2913 tmpElem.type = 'text/javascript';
2914 tmpElem.text = SUGAR.evalScript_evalElem[i];
2915 headElem.appendChild(tmpElem);
2920 var tmpElem = document.createElement('div');
2921 tmpElem.innerHTML = text;
2922 var results = tmpElem.getElementsByTagName('script');
2923 if (results == null) {
2924 // No scripts found, bail out
2928 var headElem = document.getElementsByTagName('head')[0];
2930 SUGAR.evalScript_waitCount = 0;
2931 SUGAR.evalScript_evalElem = new Array();
2932 for (var i = 0; i < results.length; i++) {
2933 if (typeof(results[i]) != 'object') {
2936 tmpElem = document.createElement('script');
2937 tmpElem.type = 'text/javascript';
2938 if (results[i].src != null && results[i].src != '') {
2939 tmpElem.src = results[i].src;
2941 // Need to defer execution of these scripts until the
2942 // required javascript files are fully loaded
2943 SUGAR.evalScript_evalElem[SUGAR.evalScript_evalElem.length] = results[i].text;
2946 tmpElem.addEventListener('load', waitUntilLoaded);
2947 SUGAR.evalScript_waitCount++;
2948 headElem.appendChild(tmpElem);
2950 // Add some code to handle pages without any external scripts
2951 SUGAR.evalScript_waitCount++;
2954 // Don't try and process things the IE way
2958 var objRegex = /<\s*script([^>]*)>((.|\s|\v|\0)*?)<\s*\/script\s*>/igm;
2960 var result = objRegex.exec(text);
2961 while(result && result.index > lastIndex){
2962 lastIndex = result.index
2964 // Bug #49205 : Subpanels fail to load when selecting subpanel tab
2965 // Change approach to handle javascripts included to body of ajax response.
2966 // To load & run javascripts and inline javascript in correct order load them as synchronous requests
2967 // JQuery library uses this approach to eval scripts
2968 if(result[1].indexOf("src=") > -1){
2969 var srcRegex = /.*src=['"]([a-zA-Z0-9_\-\&\/\.\?=:-]*)['"].*/igm;
2970 var srcResult = result[1].replace(srcRegex, '$1');
2972 // Check is ulr cross domain or not
2973 var r1 = /:\/\//igm;
2974 if ( r1.test(srcResult) && srcResult.indexOf(window.location.hostname) == -1 )
2976 // if script is cross domain it cannot be loaded via ajax request
2977 // try load script asynchronous by creating script element in the body
2978 // YUI 3.3 doesn't allow load scrips synchronously
2980 YUI().use('get', function (Y)
2982 var url = srcResult;
2983 Y.Get.script(srcResult,
2986 onSuccess : function(o) { },
2987 onFailure: function(o) { },
2988 onTimeout: function(o) { }
2991 // TODO: for YUI 3.5 - load scripts as script object synchronous
2993 YUI().use('get', function (Y) {
2994 var url = srcResult;
2995 Y.Get.js([{url: url, async: false}], function (err) {});
3001 // Bug #49205 : Subpanels fail to load when selecting subpanel tab
3002 // Create a YUI instance using the io-base module.
3003 (function (srcResult) {
3004 YUI().use("io-base",function(Y)
3011 success:function(transactionid,response,arguments)
3013 SUGAR.util.globalEval(response.responseText);
3017 // Call synchronous request to load javascript content
3018 // restonse will be processed in success function
3019 response=Y.io(srcResult,cfg);
3024 // Bug #49205 : Subpanels fail to load when selecting subpanel tab
3025 // execute script in global context
3026 // Bug #57288 : don't eval with html comment-out script; that causes syntax error in IE
3027 var srcRegex = /<!--([\s\S]*?)-->/;
3028 var srcResult = srcRegex.exec(result[2]);
3029 if (srcResult && srcResult.index > -1)
3031 SUGAR.util.globalEval(srcResult[1]);
3035 SUGAR.util.globalEval(result[2]);
3040 if(typeof(console) != "undefined" && typeof(console.log) == "function")
3042 console.log("error adding script");
3044 console.log(result);
3047 result = objRegex.exec(text);
3051 * Gets the sidebar object
3052 * @return object pointer to the sidebar element
3054 getLeftColObj: function() {
3055 leftColObj = document.getElementById('leftCol');
3056 while(leftColObj.nodeName != 'TABLE') {
3057 leftColObj = leftColObj.firstChild;
3059 leftColTable = leftColObj;
3060 leftColTd = leftColTable.getElementsByTagName('td')[0];
3061 leftColTdRegion = YAHOO.util.Dom.getRegion(leftColTd);
3062 leftColTd.style.width = (leftColTdRegion.right - leftColTdRegion.left) + 'px';
3067 * Fills the shortcut menu placeholders w/ actual content
3068 * Call this on load event
3070 * @param shortcutContent Array array of content to fill in
3072 fillShortcuts: function(e, shortcutContent) {
3075 // don't do this if leftCol isn't available
3076 if (document.getElementById('leftCol') == undefined) { return; }
3078 spans = document.getElementById('leftCol').getElementsByTagName('span');
3079 hideCol = document.getElementById('HideMenu').getElementsByTagName('span');
3080 w = spans.length + 1;
3082 spans[w] = hideCol[i];
3085 for(je in shortcutContent) {
3087 if(typeof spans[wp].innerHTML != 'undefined' && spans[wp].innerHTML == ('wp_shortcut_fill_' + je)) {
3088 if(typeof spans[wp].parentNode.parentNode == 'object') {
3089 if(typeof spans[wp].parentNode.parentNode.onclick != 'undefined') {
3090 spans[wp].parentNode.parentNode.onclick = null;
3092 // If the wp_shortcut span is contained by an A tag, replace the A with a DIV.
3093 if(spans[wp].parentNode.tagName == 'A' && !isIE) {
3094 var newDiv = document.createElement('DIV');
3095 var parentAnchor = spans[wp].parentNode;
3097 spans[wp].parentNode.parentNode.style.display = 'none';
3099 // Copy styles over to the new container div
3100 if(window.getComputedStyle) {
3101 var parentStyle = window.getComputedStyle(parentAnchor, '');
3102 for(var styleName in parentStyle) {
3103 if(typeof parentStyle[styleName] != 'function'
3104 && styleName != 'display'
3105 && styleName != 'borderWidth'
3106 && styleName != 'visibility') {
3108 newDiv.style[styleName] = parentStyle[styleName];
3110 // Catches .length and .parentRule, and others
3116 // Replace the A with the DIV
3117 newDiv.appendChild(spans[wp]);
3118 parentAnchor.parentNode.replaceChild(newDiv, parentAnchor);
3120 spans[wp].parentNode.parentNode.style.display = '';
3123 spans[wp].innerHTML = shortcutContent[je]; // fill w/ content
3124 if(spans[wp].style) spans[wp].style.display = '';
3130 * Make an AJAX request.
3132 * @param url string resource to load
3133 * @param theDiv string id of element to insert loaded data into
3134 * @param postForm string if set, a POST request will be made to resource specified by url using the form named by postForm
3135 * @param callback string name of function to invoke after HTTP response is recieved
3136 * @param callbackParam any parameter to pass to callback when invoked
3137 * @param appendMode bool if true, HTTP response will be appended to the contents of theDiv, or else contents will be overriten.
3139 retrieveAndFill: function(url, theDiv, postForm, callback, callbackParam, appendMode) {
3140 if(typeof theDiv == 'string') {
3142 theDiv = document.getElementById(theDiv);
3149 var success = function(data) {
3150 if (typeof theDiv != 'undefined' && theDiv != null)
3153 if (typeof appendMode != 'undefined' && appendMode)
3155 theDiv.insertAdjacentHTML('beforeend', data.responseText);
3159 theDiv.innerHTML = data.responseText;
3166 if (typeof callback != 'undefined' && callback != null) callback(callbackParam);
3169 if(typeof postForm == 'undefined' || postForm == null) {
3170 var cObj = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
3173 YAHOO.util.Connect.setForm(postForm);
3174 var cObj = YAHOO.util.Connect.asyncRequest('POST', url, {success: success, failure: success});
3177 checkMaxLength: function() { // modified from http://www.quirksmode.org/dom/maxlength.html
3178 var maxLength = this.getAttribute('maxlength');
3179 var currentLength = this.value.length;
3180 if (currentLength > maxLength) {
3181 this.value = this.value.substring(0, maxLength);
3186 * Adds maxlength attribute to textareas
3188 setMaxLength: function() { // modified from http://www.quirksmode.org/dom/maxlength.html
3189 var x = document.getElementsByTagName('textarea');
3190 for (var i=0;i<x.length;i++) {
3191 if (x[i].getAttribute('maxlength')) {
3192 x[i].onkeyup = x[i].onchange = SUGAR.util.checkMaxLength;
3199 * Renders Query UI Help Dialog
3201 showHelpTips: function(el,helpText,myPos,atPos,id) {
3202 if(myPos == undefined || myPos == "") {
3205 if(atPos == undefined || atPos == "") {
3206 atPos = "right top";
3209 var pos = $(el).offset(),
3210 ofWidth = $(el).width(),
3211 elmId = id || 'helpTip' + pos.left + '_' + ofWidth,
3212 $dialog = elmId ? ( $("#"+elmId).length > 0 ? $("#"+elmId) : $('<div></div>').attr("id", elmId) ) : $('<div></div>');
3213 $dialog.html(helpText)
3216 title: SUGAR.language.get('app_strings', 'LBL_HELP'),
3225 var width = $dialog.dialog( "option", "width" );
3227 if((pos.left + ofWidth) - 40 < width) {
3228 $dialog.dialog("option","position",{my: 'left top',at: 'right top',of: $(el)}) ;
3230 $dialog.dialog('open');
3231 $(".ui-dialog").appendTo("#content");
3235 getStaticAdditionalDetails: function(el, body, caption, show_buttons) {
3236 if(typeof show_buttons == "undefined") {
3237 show_buttons = false;
3240 $(".ui-dialog").find(".open").dialog("close");
3242 var $dialog = $('<div class="open"></div>')
3256 $(".ui-dialog").find('.ui-dialog-titlebar-close').css("display","none");
3257 $(".ui-dialog").find('.ui-dialog-title').css("width","100%");
3261 var width = $dialog.dialog( "option", "width" );
3262 var pos = $(el).offset();
3263 var ofWidth = $(el).width();
3265 if((pos.left + ofWidth) - 40 < width) {
3266 $dialog.dialog("option","position",{my: 'left top',at: 'right top',of: $(el)}) ;
3269 $dialog.dialog('open');
3270 $(".ui-dialog").appendTo("#content");
3274 closeStaticAdditionalDetails: function() {
3275 $(".ui-dialog").find(".open").dialog("close");
3278 * Retrieves additional details dynamically
3280 getAdditionalDetails: function(bean, id, spanId, show_buttons) {
3281 if(typeof show_buttons == "undefined")
3282 show_buttons = false;
3283 var el = '#'+spanId;
3285 oReturn = function(body, caption, width, theme) {
3287 $(".ui-dialog").find(".open").dialog("close");
3289 var $dialog = $('<div class="open"></div>')
3302 $(".ui-dialog").find('.ui-dialog-titlebar-close').css("display","none");
3303 $(".ui-dialog").find('.ui-dialog-title').css("width","100%");
3306 var width = $dialog.dialog( "option", "width" );
3307 var pos = $(el).offset();
3308 var ofWidth = $(el).width();
3310 if((pos.left + ofWidth) - 40 < width) {
3311 $dialog.dialog("option","position",{my: 'left top',at: 'right top',of: $(el)}) ;
3314 $dialog.dialog('open');
3315 $(".ui-dialog").appendTo("#content");
3318 success = function(data) {
3319 eval(data.responseText);
3321 SUGAR.util.additionalDetailsCache[id] = new Array();
3322 SUGAR.util.additionalDetailsCache[id]['body'] = result['body'];
3323 SUGAR.util.additionalDetailsCache[id]['caption'] = result['caption'];
3324 SUGAR.util.additionalDetailsCache[id]['width'] = result['width'];
3325 SUGAR.util.additionalDetailsCache[id]['theme'] = result['theme'];
3326 ajaxStatus.hideStatus();
3327 return oReturn(SUGAR.util.additionalDetailsCache[id]['body'], SUGAR.util.additionalDetailsCache[id]['caption'], SUGAR.util.additionalDetailsCache[id]['width'], SUGAR.util.additionalDetailsCache[id]['theme']);
3330 if(typeof SUGAR.util.additionalDetailsCache[id] != 'undefined')
3331 return oReturn(SUGAR.util.additionalDetailsCache[id]['body'], SUGAR.util.additionalDetailsCache[id]['caption'], SUGAR.util.additionalDetailsCache[id]['width'], SUGAR.util.additionalDetailsCache[id]['theme']);
3333 if(typeof SUGAR.util.additionalDetailsCalls[id] != 'undefined') // call already in progress
3335 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_LOADING'));
3336 url = 'index.php?to_pdf=1&module=Home&action=AdditionalDetailsRetrieve&bean=' + bean + '&id=' + id;
3338 url += '&show_buttons=true';
3339 SUGAR.util.additionalDetailsCalls[id] = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
3343 SUGAR.util.additionalDetailsRpcCall = window.setTimeout('go()', 250);
3345 clearAdditionalDetailsCall: function() {
3346 if(typeof SUGAR.util.additionalDetailsRpcCall == 'number') window.clearTimeout(SUGAR.util.additionalDetailsRpcCall);
3349 * A function that extends functionality from parent to child.
3351 extend : function(subc, superc, overrides) {
3352 subc.prototype = new superc; // set the superclass
3355 for (var i in overrides) subc.prototype[i] = overrides[i];
3358 hrefURL : function(url) {
3360 // IE needs special treatment since otherwise it would not pass Referer
3361 var trampoline = document.createElement('a');
3362 trampoline.href = url;
3363 document.body.appendChild(trampoline);
3365 document.body.removeChild(trampoline);
3367 document.location.href = url;
3371 openWindow : function(URL, windowName, windowFeatures) {
3373 // IE needs special treatment since otherwise it would not pass Referer
3374 win = window.open('', windowName, windowFeatures);
3375 var trampoline = document.createElement('a');
3376 trampoline.href = URL;
3377 trampoline.target = windowName;
3378 document.body.appendChild(trampoline);
3380 document.body.removeChild(trampoline);
3382 win = window.open(URL, windowName, windowFeatures);
3386 //Reset the scroll on the window
3391 //Based on YUI onAvailible, but will use any boolean function instead of an ID
3392 doWhen : function(condition, fn, params, scope)
3394 this._doWhenStack.push({
3398 overrideContext: scope
3401 this._doWhenretryCount = 50;
3402 this._startDoWhenInterval();
3405 _startDoWhenInterval : function(){
3406 if (!this._doWhenInterval) {
3407 this._doWhenInterval = YAHOO.lang.later(50, this, this._doWhenCheck, null, true);
3411 _doWhenInterval : false,
3412 _doWhenCheck : function() {
3413 if (this._doWhenStack.length === 0) {
3414 this._doWhenretryCount = 0;
3415 if (this._doWhenInterval) {
3416 // clearInterval(this._interval);
3417 this._doWhenInterval.cancel();
3418 this._doWhenInterval = null;
3423 if (this._doWhenLocked) {
3428 // Hold off if DOMReady has not fired and check current
3429 // readyState to protect against the IE operation aborted
3431 if (!YAHOO.util.Event.DOMReady) {
3432 this._startDoWhenInterval();
3437 this._doWhenLocked = true;
3440 // keep trying until after the page is loaded. We need to
3441 // check the page load state prior to trying to bind the
3442 // elements so that we can be certain all elements have been
3443 // tested appropriately
3444 var tryAgain = YAHOO.util.Event.DOMReady;
3446 tryAgain = (this._doWhenretryCount > 0 && this._doWhenStack.length > 0);
3452 var executeItem = function (context, item) {
3453 if (item.overrideContext) {
3454 if (item.overrideContext === true) {
3457 context = item.overrideContext;
3461 item.fn.call(context, item.obj);
3465 var i, len, item, test;
3467 // onAvailable onContentReady
3468 for (i=0, len=this._doWhenStack.length; i<len; i=i+1) {
3469 item = this._doWhenStack[i];
3472 if ((typeof(test) == "string" && eval(test)) || (typeof(test) == "function" && test())) {
3473 executeItem(this, item);
3474 this._doWhenStack[i] = null;
3477 notAvail.push(item);
3482 this._doWhenretryCount--;
3485 for (i=this._doWhenStack.length-1; i>-1; i--) {
3486 item = this._doWhenStack[i];
3487 if (!item || !item.check) {
3488 this._doWhenStack.splice(i, 1);
3491 this._startDoWhenInterval();
3493 if (this._doWhenInterval) {
3494 // clearInterval(this._interval);
3495 this._doWhenInterval.cancel();
3496 this._doWhenInterval = null;
3499 this._doWhenLocked = false;
3501 buildAccessKeyLabels : function() {
3502 if (typeof(Y.env.ua) !== 'undefined'){
3504 browserOS = Y.env.ua['os'];
3505 isIE = Y.env.ua['ie'];
3506 isCR = Y.env.ua['chrome'];
3507 isFF = Y.env.ua['gecko'];
3508 isWK = Y.env.ua['webkit'];
3509 isOP = Y.env.ua['opera'];
3512 //first determine the OS
3513 if(browserOS=='macintosh'){
3514 //we got a mac, lets use the mac specific commands while we check the browser
3516 //IE on a Mac? Not possible, but let's assign alt anyways for completions sake
3517 controlKey = 'Alt+';
3518 }else if(isWK || isFF){
3519 //Chrome or safari on a mac
3520 //firefox moved to webkit standard starting with FF14
3521 controlKey = 'Ctrl+Opt+';
3524 controlKey = 'Shift+Esc: ';
3526 //default for everything else on a mac
3527 controlKey = 'Ctrl+';
3530 //this is not a mac so let's use the windows/unix commands while we check the browser
3532 //FF on windows/unix
3533 controlKey = 'Alt+Shift+';
3535 //Opera on windows/unix
3536 controlKey = 'Shift+Esc: ';
3538 //this is the default for safari, IE and Chrome
3539 //if this is webkit and is NOT google, then we are most likely looking at Safari
3540 controlKey = 'Alt+';
3545 //now lets retrieve all elements of type input
3546 allButtons = document.getElementsByTagName('input');
3547 //iterate through list and modify title if the accesskey is not empty
3548 for(i=0;i<allButtons.length;i++){
3549 if(allButtons[i].getAttribute('accesskey') && allButtons[i].getAttribute('type') && allButtons[i].getAttribute('type')=='button'){
3550 allButtons[i].setAttribute('title',allButtons[i].getAttribute('title')+' ['+controlKey+allButtons[i].getAttribute('accesskey')+']');
3553 //now change the text in the help div
3554 $("#shortcuts_dialog").html(function(i, text) {
3555 return text.replace(/Alt\+/g,controlKey);
3557 }// end if (typeof(Y.env.ua) !== 'undefined')
3558 }//end buildAccessKeyLabels()
3561 SUGAR.util.additionalDetailsCache = new Array();
3562 SUGAR.util.additionalDetailsCalls = new Array();
3563 if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.util.setMaxLength); // allow textareas to obey maxlength attrib
3565 SUGAR.savedViews = function() {
3566 var selectedOrderBy;
3567 var selectedSortOrder;
3570 var columnsMeta; // meta data for the display columns
3573 setChooser: function() {
3575 var displayColumnsDef = new Array();
3576 var hideTabsDef = new Array();
3578 var left_td = document.getElementById('display_tabs_td');
3579 if(typeof left_td == 'undefined' || left_td == null) return; // abort!
3580 var right_td = document.getElementById('hide_tabs_td');
3582 var displayTabs = left_td.getElementsByTagName('select')[0];
3583 var hideTabs = right_td.getElementsByTagName('select')[0];
3585 for(i = 0; i < displayTabs.options.length; i++) {
3586 displayColumnsDef.push(displayTabs.options[i].value);
3589 if(typeof hideTabs != 'undefined') {
3590 for(i = 0; i < hideTabs.options.length; i++) {
3591 hideTabsDef.push(hideTabs.options[i].value);
3594 if (!SUGAR.savedViews.clearColumns)
3595 document.getElementById('displayColumnsDef').value = displayColumnsDef.join('|');
3596 document.getElementById('hideTabsDef').value = hideTabsDef.join('|');
3599 select: function(saved_search_select) {
3600 for(var wp = 0; wp < document.search_form.saved_search_select.options.length; wp++) {
3601 if(typeof document.search_form.saved_search_select.options[wp].value != 'undefined' &&
3602 document.search_form.saved_search_select.options[wp].value == saved_search_select) {
3603 document.search_form.saved_search_select.selectedIndex = wp;
3604 document.search_form.ss_delete.style.display = '';
3605 document.search_form.ss_update.style.display = '';
3609 saved_search_action: function(action, delete_lang) {
3610 if(action == 'delete') {
3611 if(!confirm(delete_lang)) return;
3613 if(action == 'save') {
3614 if(document.search_form.saved_search_name.value.replace(/^\s*|\s*$/g, '') == '') {
3615 alert(SUGAR.language.get('app_strings', 'LBL_SAVED_SEARCH_ERROR'));
3620 // This check is needed for the Activities module (Calls/Meetings/Tasks).
3621 if (document.search_form.saved_search_action)
3623 document.search_form.saved_search_action.value = action;
3624 document.search_form.search_module.value = document.search_form.module.value;
3625 document.search_form.module.value = 'SavedSearch';
3626 // Bug 31922 - Make sure to specify that we want to hit the index view here of
3627 // the SavedSearch module, since the ListView doesn't have the logic to save the
3628 // search and redirect back
3629 document.search_form.action.value = 'index';
3631 SUGAR.ajaxUI.submitForm(document.search_form);
3633 shortcut_select: function(selectBox, module) {
3635 selecturl = 'index.php?module=SavedSearch&search_module=' + module + '&action=index&saved_search_select=' + selectBox.options[selectBox.selectedIndex].value
3636 //add searchFormTab to url if it is available. This determines what tab to render
3637 if(typeof(document.getElementById('searchFormTab'))!='undefined'){
3638 selecturl = selecturl + '&searchFormTab=' + document.search_form.searchFormTab.value;
3640 //add showSSDIV to url if it is available. This determines whether saved search sub form should
3641 //be rendered open or not
3642 if(document.getElementById('showSSDIV') && typeof(document.getElementById('showSSDIV') !='undefined')){
3643 selecturl = selecturl + '&showSSDIV='+document.getElementById('showSSDIV').value;
3645 //use created url to navigate
3646 document.location.href = selecturl;
3648 handleForm: function() {
3649 SUGAR.tabChooser.movementCallback = function(left_side, right_side) {
3650 while(document.getElementById('orderBySelect').childNodes.length != 0) { // clear out order by options
3651 document.getElementById('orderBySelect').removeChild(document.getElementById('orderBySelect').lastChild);
3654 var selectedIndex = 0;
3655 var nodeCount = -1; // need this because the counter i also includes "undefined" nodes
3656 // which was breaking Calls and Meetings
3658 for(i in left_side.childNodes) { // fill in order by options
3659 if(typeof left_side.childNodes[i].nodeName != 'undefined' &&
3660 left_side.childNodes[i].nodeName.toLowerCase() == 'option' &&
3661 typeof SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value] != 'undefined' && // check if column is sortable
3662 typeof SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value]['sortable'] == 'undefined' &&
3663 SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value]['sortable'] != false) {
3665 optionNode = document.createElement('option');
3666 optionNode.value = left_side.childNodes[i].value;
3667 optionNode.innerHTML = left_side.childNodes[i].innerHTML;
3668 document.getElementById('orderBySelect').appendChild(optionNode);
3669 if(optionNode.value == SUGAR.savedViews.selectedOrderBy)
3670 selectedIndex = nodeCount;
3673 // Firefox needs this to be set after all the option nodes are created.
3674 document.getElementById('orderBySelect').selectedIndex = selectedIndex;
3676 SUGAR.tabChooser.movementCallback(document.getElementById('display_tabs_td').getElementsByTagName('select')[0]);
3678 // This check is needed for the Activities module (Calls/Meetings/Tasks).
3679 if (document.search_form.orderBy)
3680 document.search_form.orderBy.options.value = SUGAR.savedViews.selectedOrderBy;
3683 if(SUGAR.savedViews.selectedSortOrder == 'DESC') document.getElementById('sort_order_desc_radio').checked = true;
3684 else document.getElementById('sort_order_asc_radio').checked = true;
3689 SUGAR.searchForm = function() {
3692 // searchForm tab selector util
3693 searchFormSelect: function(view, previousView) {
3694 var module = view.split('|')[0];
3695 var theView = view.split('|')[1];
3697 var handleDisplay = function() { // hide other divs
3698 document.search_form.searchFormTab.value = theView;
3699 patt = module+"(.*)SearchForm$";
3700 divId=document.search_form.getElementsByTagName('div');
3701 // Hide all the search forms and retrive the name of the previous search tab (useful for the first load because previousView is empty)
3702 for (i=0;i<divId.length;i++){
3703 if(divId[i].id.match(module)==module){
3704 if(divId[i].id.match('SearchForm')=='SearchForm'){
3705 if(document.getElementById(divId[i].id).style.display == ''){
3706 previousTab=divId[i].id.match(patt)[1];
3708 document.getElementById(divId[i].id).style.display = 'none';
3713 //clear thesearch form accesekeys and reset them to the appropriate link
3714 adv = document.getElementById('advanced_search_link');
3715 bas = document.getElementById('basic_search_link');
3716 adv.setAttribute('accesskey','');
3717 bas.setAttribute('accesskey','');
3718 a_key = SUGAR.language.get("app_strings", "LBL_ADV_SEARCH_LNK_KEY");
3720 //reset the ccesskey based on theview
3721 if(theView === 'advanced_search'){
3723 bas.setAttribute('accesskey',a_key);
3725 adv.setAttribute('accesskey',a_key);
3728 // show the good search form.
3729 document.getElementById(module + theView + 'SearchForm').style.display = '';
3730 //if its not the first tab show there is a previous tab.
3732 thepreviousView=previousView.split('|')[1];
3735 thepreviousView=previousTab;
3737 thepreviousView=thepreviousView.replace(/_search/, "");
3738 // Process to retrieve the completed field from one tab to an other.
3739 for(num in document.search_form.elements) {
3740 if(document.search_form.elements[num]) {
3741 el = document.search_form.elements[num];
3742 pattern="^(.*)_"+thepreviousView+"$";
3743 if(typeof el.type != 'undefined' && typeof el.name != 'undefined' && el.name.match(pattern)) {
3744 advanced_input_name = el.name.match(pattern)[1]; // strip
3745 advanced_input_name = advanced_input_name+"_"+theView.replace(/_search/, "");
3746 if(typeof document.search_form[advanced_input_name] != 'undefined') // if advanced input of same name exists
3747 SUGAR.searchForm.copyElement(advanced_input_name, el);
3753 // if tab is not cached
3754 if(document.getElementById(module + theView + 'SearchForm').innerHTML == '') {
3755 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_LOADING'));
3756 var success = function(data) {
3757 document.getElementById(module + theView + 'SearchForm').innerHTML = data.responseText;
3759 SUGAR.util.evalScript(data.responseText);
3760 // pass script variables to global scope
3761 if(theView == 'saved_views') {
3762 if(typeof columnsMeta != 'undefined') SUGAR.savedViews.columnsMeta = columnsMeta;
3763 if(typeof selectedOrderBy != 'undefined') SUGAR.savedViews.selectedOrderBy = selectedOrderBy;
3764 if(typeof selectedSortOrder != 'undefined') SUGAR.savedViews.selectedSortOrder = selectedSortOrder;
3769 ajaxStatus.hideStatus();
3771 url = 'index.php?module=' + module + '&action=index&search_form_only=true&to_pdf=true&search_form_view=' + theView;
3773 //check to see if tpl has been specified. If so then pass location through url string
3775 if(document.getElementById('search_tpl') !=null && typeof(document.getElementById('search_tpl')) != 'undefined'){
3776 tpl = document.getElementById('search_tpl').value;
3777 if(tpl != ''){url += '&search_tpl='+tpl;}
3780 if(theView == 'saved_views') // handle the tab chooser
3781 url += '&displayColumns=' + SUGAR.savedViews.displayColumns + '&hideTabs=' + SUGAR.savedViews.hideTabs + '&orderBy=' + SUGAR.savedViews.selectedOrderBy + '&sortOrder=' + SUGAR.savedViews.selectedSortOrder;
3783 var cObj = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
3785 else { // that form already retrieved
3790 // copies one input to another
3791 copyElement: function(inputName, copyFromElement) {
3792 switch(copyFromElement.type) {
3795 document.search_form[inputName].value = copyFromElement.value;
3799 // This function is here to clear the form, instead of "resubmitting it
3800 clear_form: function(form, skipElementNames) {
3801 var elemList = form.elements;
3805 for( var i = 0; i < elemList.length ; i++ ) {
3807 if ( typeof(elem.type) == 'undefined' ) {
3811 if ( typeof(elem.type) != 'undefined' && typeof(skipElementNames) != 'undefined'
3812 && SUGAR.util.arrayIndexOf(skipElementNames, elem.name) != -1 )
3817 elemType = elem.type.toLowerCase();
3819 if ( elemType == 'text' || elemType == 'textarea' || elemType == 'password' ) {
3821 } else if (elemType == 'select-one') {
3822 // We have, what I hope, is a select box, time to unselect all options
3823 var optionList = elem.options,
3825 for (var ii = 0; ii < optionList.length; ii++) {
3826 if (optionList[ii].value == '') {
3831 if (optionList.length > 0) {
3832 optionList[selectedIndex].selected = "selected";
3834 } else if (elemType == 'select-multiple') {
3835 var optionList = elem.options;
3836 for ( var ii = 0 ; ii < optionList.length ; ii++ ) {
3837 optionList[ii].selected = false;
3840 else if ( elemType == 'radio' || elemType == 'checkbox' ) {
3841 elem.checked = false;
3842 elem.selected = false;
3844 else if ( elemType == 'hidden' ) {
3846 // For bean selection
3847 elem.name.indexOf("_id") != -1
3848 // For custom fields
3849 || elem.name.indexOf("_c") != -1
3850 // For advanced fields, like team collection, or datetime fields
3851 || elem.name.indexOf("_advanced") != -1
3859 // If there are any collections
3860 if (typeof(collection) !== 'undefined')
3862 // Loop through all the collections on the page and run clean_up()
3863 for (key in collection)
3865 // Clean up only removes blank fields, if any
3866 collection[key].clean_up();
3870 SUGAR.savedViews.clearColumns = true;
3874 // Code for the column/tab chooser used on homepage and in admin section
3875 SUGAR.tabChooser = function () {
3876 var object_refs = new Array();
3878 /* Describe certain transfers as invalid */
3881 movementCallback: function(left_side, right_side) {},
3882 orderCallback: function(left_side, right_side) {},
3884 freezeOptions: function(left_name, right_name, target) {
3885 if(!SUGAR.tabChooser.frozenOptions) { SUGAR.tabChooser.frozenOptions = []; }
3886 if(!SUGAR.tabChooser.frozenOptions[left_name]) { SUGAR.tabChooser.frozenOptions[left_name] = []; }
3887 if(!SUGAR.tabChooser.frozenOptions[left_name][right_name]) { SUGAR.tabChooser.frozenOptions[left_name][right_name] = []; }
3888 if(typeof target == 'array') {
3889 for(var i in target) {
3890 SUGAR.tabChooser.frozenOptions[left_name][right_name][target[i]] = true;
3893 SUGAR.tabChooser.frozenOptions[left_name][right_name][target] = true;
3897 buildSelectHTML: function(info) {
3898 var text = "<select";
3900 if(typeof (info['select']['size']) != 'undefined') {
3901 text +=" size=\""+ info['select']['size'] +"\"";
3904 if(typeof (info['select']['name']) != 'undefined') {
3905 text +=" name=\""+ info['select']['name'] +"\"";
3908 if(typeof (info['select']['style']) != 'undefined') {
3909 text +=" style=\""+ info['select']['style'] +"\"";
3912 if(typeof (info['select']['onchange']) != 'undefined') {
3913 text +=" onChange=\""+ info['select']['onchange'] +"\"";
3916 if(typeof (info['select']['multiple']) != 'undefined') {
3921 for(i=0; i<info['options'].length;i++) {
3922 option = info['options'][i];
3923 text += "<option value=\""+option['value']+"\" ";
3924 if ( typeof (option['selected']) != 'undefined' && option['selected']== true) {
3927 text += ">"+option['text']+"</option>";
3929 text += "</select>";
3933 left_to_right: function(left_name, right_name, left_size, right_size) {
3934 SUGAR.savedViews.clearColumns = false;
3935 var left_td = document.getElementById(left_name+'_td');
3936 var right_td = document.getElementById(right_name+'_td');
3938 var display_columns_ref = left_td.getElementsByTagName('select')[0];
3939 var hidden_columns_ref = right_td.getElementsByTagName('select')[0];
3941 var selected_left = new Array();
3942 var notselected_left = new Array();
3943 var notselected_right = new Array();
3945 var left_array = new Array();
3947 var frozen_options = SUGAR.tabChooser.frozenOptions;
3948 frozen_options = frozen_options && frozen_options[left_name] && frozen_options[left_name][right_name]?frozen_options[left_name][right_name]:[];
3950 // determine which options are selected in left
3951 for (i=0; i < display_columns_ref.options.length; i++)
3953 if ( display_columns_ref.options[i].selected == true && !frozen_options[display_columns_ref.options[i].value])
3955 selected_left[selected_left.length] = {text: display_columns_ref.options[i].text, value: display_columns_ref.options[i].value};
3959 notselected_left[notselected_left.length] = {text: display_columns_ref.options[i].text, value: display_columns_ref.options[i].value};
3964 for (i=0; i < hidden_columns_ref.options.length; i++)
3966 notselected_right[notselected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
3970 var left_select_html_info = new Object();
3971 var left_options = new Array();
3972 var left_select = new Object();
3974 left_select['name'] = left_name+'[]';
3975 left_select['id'] = left_name;
3976 left_select['size'] = left_size;
3977 left_select['multiple'] = 'true';
3979 var right_select_html_info = new Object();
3980 var right_options = new Array();
3981 var right_select = new Object();
3983 right_select['name'] = right_name+'[]';
3984 right_select['id'] = right_name;
3985 right_select['size'] = right_size;
3986 right_select['multiple'] = 'true';
3988 for (i = 0; i < notselected_right.length; i++) {
3989 right_options[right_options.length] = notselected_right[i];
3992 for (i = 0; i < selected_left.length; i++) {
3993 right_options[right_options.length] = selected_left[i];
3995 for (i = 0; i < notselected_left.length; i++) {
3996 left_options[left_options.length] = notselected_left[i];
3998 left_select_html_info['options'] = left_options;
3999 left_select_html_info['select'] = left_select;
4000 right_select_html_info['options'] = right_options;
4001 right_select_html_info['select'] = right_select;
4002 right_select_html_info['style'] = 'background: lightgrey';
4004 var left_html = this.buildSelectHTML(left_select_html_info);
4005 var right_html = this.buildSelectHTML(right_select_html_info);
4007 left_td.innerHTML = left_html;
4008 right_td.innerHTML = right_html;
4010 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
4011 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
4013 this.movementCallback(object_refs[left_name], object_refs[right_name]);
4019 right_to_left: function(left_name, right_name, left_size, right_size, max_left) {
4020 SUGAR.savedViews.clearColumns = false;
4021 var left_td = document.getElementById(left_name+'_td');
4022 var right_td = document.getElementById(right_name+'_td');
4024 var display_columns_ref = left_td.getElementsByTagName('select')[0];
4025 var hidden_columns_ref = right_td.getElementsByTagName('select')[0];
4027 var selected_right = new Array();
4028 var notselected_right = new Array();
4029 var notselected_left = new Array();
4031 var frozen_options = SUGAR.tabChooser.frozenOptions;
4032 frozen_options = SUGAR.tabChooser.frozenOptions && SUGAR.tabChooser.frozenOptions[right_name] && SUGAR.tabChooser.frozenOptions[right_name][left_name]?SUGAR.tabChooser.frozenOptions[right_name][left_name]:[];
4034 for (i=0; i < hidden_columns_ref.options.length; i++)
4036 if (hidden_columns_ref.options[i].selected == true && !frozen_options[hidden_columns_ref.options[i].value])
4038 selected_right[selected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
4042 notselected_right[notselected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
4047 if(max_left != '' && (display_columns_ref.length + selected_right.length) > max_left) {
4048 alert('Maximum of ' + max_left + ' columns can be displayed.');
4052 for (i=0; i < display_columns_ref.options.length; i++)
4054 notselected_left[notselected_left.length] = {text:display_columns_ref.options[i].text, value:display_columns_ref.options[i].value};
4058 var left_select_html_info = new Object();
4059 var left_options = new Array();
4060 var left_select = new Object();
4062 left_select['name'] = left_name+'[]';
4063 left_select['id'] = left_name;
4064 left_select['multiple'] = 'true';
4065 left_select['size'] = left_size;
4067 var right_select_html_info = new Object();
4068 var right_options = new Array();
4069 var right_select = new Object();
4071 right_select['name'] = right_name+ '[]';
4072 right_select['id'] = right_name;
4073 right_select['multiple'] = 'true';
4074 right_select['size'] = right_size;
4076 for (i = 0; i < notselected_left.length; i++) {
4077 left_options[left_options.length] = notselected_left[i];
4080 for (i = 0; i < selected_right.length; i++) {
4081 left_options[left_options.length] = selected_right[i];
4083 for (i = 0; i < notselected_right.length; i++) {
4084 right_options[right_options.length] = notselected_right[i];
4086 left_select_html_info['options'] = left_options;
4087 left_select_html_info['select'] = left_select;
4088 right_select_html_info['options'] = right_options;
4089 right_select_html_info['select'] = right_select;
4090 right_select_html_info['style'] = 'background: lightgrey';
4092 var left_html = this.buildSelectHTML(left_select_html_info);
4093 var right_html = this.buildSelectHTML(right_select_html_info);
4095 left_td.innerHTML = left_html;
4096 right_td.innerHTML = right_html;
4098 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
4099 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
4101 this.movementCallback(object_refs[left_name], object_refs[right_name]);
4106 up: function(name, left_name, right_name) {
4107 SUGAR.savedViews.clearColumns = false;
4108 var left_td = document.getElementById(left_name+'_td');
4109 var right_td = document.getElementById(right_name+'_td');
4110 var td = document.getElementById(name+'_td');
4111 var obj = td.getElementsByTagName('select')[0];
4112 obj = (typeof obj == "string") ? document.getElementById(obj) : obj;
4113 if (obj.tagName.toLowerCase() != "select" && obj.length < 2)
4115 var sel = new Array();
4117 for (i=0; i<obj.length; i++) {
4118 if (obj[i].selected == true) {
4119 sel[sel.length] = i;
4122 for (i=0; i < sel.length; i++) {
4123 if (sel[i] != 0 && !obj[sel[i]-1].selected) {
4124 var tmp = new Array(obj[sel[i]-1].text, obj[sel[i]-1].value);
4125 obj[sel[i]-1].text = obj[sel[i]].text;
4126 obj[sel[i]-1].value = obj[sel[i]].value;
4127 obj[sel[i]].text = tmp[0];
4128 obj[sel[i]].value = tmp[1];
4129 obj[sel[i]-1].selected = true;
4130 obj[sel[i]].selected = false;
4134 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
4135 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
4137 this.orderCallback(object_refs[left_name], object_refs[right_name]);
4142 down: function(name, left_name, right_name) {
4143 SUGAR.savedViews.clearColumns = false;
4144 var left_td = document.getElementById(left_name+'_td');
4145 var right_td = document.getElementById(right_name+'_td');
4146 var td = document.getElementById(name+'_td');
4147 var obj = td.getElementsByTagName('select')[0];
4148 if (obj.tagName.toLowerCase() != "select" && obj.length < 2)
4150 var sel = new Array();
4151 for (i=obj.length-1; i>-1; i--) {
4152 if (obj[i].selected == true) {
4153 sel[sel.length] = i;
4156 for (i=0; i < sel.length; i++) {
4157 if (sel[i] != obj.length-1 && !obj[sel[i]+1].selected) {
4158 var tmp = new Array(obj[sel[i]+1].text, obj[sel[i]+1].value);
4159 obj[sel[i]+1].text = obj[sel[i]].text;
4160 obj[sel[i]+1].value = obj[sel[i]].value;
4161 obj[sel[i]].text = tmp[0];
4162 obj[sel[i]].value = tmp[1];
4163 obj[sel[i]+1].selected = true;
4164 obj[sel[i]].selected = false;
4168 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
4169 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
4171 this.orderCallback(object_refs[left_name], object_refs[right_name]);
4176 }(); // end tabChooser
4178 SUGAR.language = function() {
4180 languages : new Array(),
4182 setLanguage: function(module, data) {
4183 if (!SUGAR.language.languages) {
4186 SUGAR.language.languages[module] = data;
4189 get: function(module, str) {
4190 if(typeof SUGAR.language.languages[module] == 'undefined' || typeof SUGAR.language.languages[module][str] == 'undefined')
4194 return SUGAR.language.languages[module][str];
4197 translate: function(module, str)
4199 text = this.get(module, str);
4200 return text != 'undefined' ? text : this.get('app_strings', str);
4205 SUGAR.contextMenu = function() {
4207 objects: new Object(),
4208 objectTypes: new Object(),
4210 * Registers a new object for the context menu.
4211 * objectType - name of the type
4213 * metaData - metaData to pass to the action function
4215 registerObject: function(objectType, id, metaData) {
4216 SUGAR.contextMenu.objects[id] = new Object();
4217 SUGAR.contextMenu.objects[id] = {'objectType' : objectType, 'metaData' : metaData};
4220 * Registers a new object type
4221 * name - name of the type
4222 * menuItems - array of menu items
4224 registerObjectType: function(name, menuItems) {
4225 SUGAR.contextMenu.objectTypes[name] = new Object();
4226 SUGAR.contextMenu.objectTypes[name] = {'menuItems' : menuItems, 'objects' : new Array()};
4229 * Determines which menu item was clicked
4231 getListItemFromEventTarget: function(p_oNode) {
4233 if(p_oNode.tagName == "LI") {
4238 if(p_oNode.tagName == "LI") {
4243 } while((p_oNode = p_oNode.parentNode));
4248 * handles movement within context menu
4250 onContextMenuMove: function() {
4251 var oNode = this.contextEventTarget;
4252 var bDisabled = (oNode.tagName == "UL");
4253 var i = this.getItemGroups()[0].length - 1;
4255 this.getItem(i).cfg.setProperty("disabled", bDisabled);
4260 * handles clicks on a context menu ITEM
4262 onContextMenuItemClick: function(p_sType, p_aArguments, p_oItem) {
4263 var oLI = SUGAR.contextMenu.getListItemFromEventTarget(this.parent.contextEventTarget);
4264 id = this.parent.contextEventTarget.parentNode.id; // id of the target
4265 funct = eval(SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[id]['objectType']]['menuItems'][this.index]['action']);
4266 funct(this.parent.contextEventTarget, SUGAR.contextMenu.objects[id]['metaData']);
4269 * Initializes all context menus registered
4272 for(var i in SUGAR.contextMenu.objects) { // make a variable called objects in objectTypes containg references to all triggers
4273 if(typeof SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'] == 'undefined')
4274 SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'] = new Array();
4275 SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'].push(document.getElementById(i));
4277 // register the menus
4278 for(var i in SUGAR.contextMenu.objectTypes) {
4279 var oContextMenu = new YAHOO.widget.ContextMenu(i, {'trigger': SUGAR.contextMenu.objectTypes[i]['objects']});
4280 var aMainMenuItems = SUGAR.contextMenu.objectTypes[i]['menuItems'];
4281 var nMainMenuItems = aMainMenuItems.length;
4283 for(var j = 0; j < nMainMenuItems; j++) {
4284 oMenuItem = new YAHOO.widget.ContextMenuItem(aMainMenuItems[j].text, { helptext: aMainMenuItems[j].helptext });
4285 oMenuItem.clickEvent.subscribe(SUGAR.contextMenu.onContextMenuItemClick, oMenuItem, true);
4286 oContextMenu.addItem(oMenuItem);
4288 // Add a "move" event handler to the context menu
4289 oContextMenu.moveEvent.subscribe(SUGAR.contextMenu.onContextMenuMove, oContextMenu, true);
4290 // Add a "keydown" event handler to the context menu
4291 oContextMenu.keyDownEvent.subscribe(SUGAR.contextMenu.onContextMenuItemClick, oContextMenu, true);
4292 // Render the context menu
4293 oContextMenu.render(document.body);
4299 SUGAR.contextMenu.actions = function() {
4302 * redirects to a new note with the clicked on object as the target
4304 createNote: function(itemClicked, metaData) {
4305 loc = 'index.php?module=Notes&action=EditView';
4306 for(i in metaData) {
4307 if(i == 'notes_parent_type') loc += '&parent_type=' + metaData[i];
4308 else if(i != 'module' && i != 'parent_type') loc += '&' + i + '=' + metaData[i];
4310 document.location = loc;
4313 * redirects to a new note with the clicked on object as the target
4315 scheduleMeeting: function(itemClicked, metaData) {
4316 loc = 'index.php?module=Meetings&action=EditView';
4317 for(i in metaData) {
4318 if(i != 'module') loc += '&' + i + '=' + metaData[i];
4320 document.location = loc;
4323 * redirects to a new note with the clicked on object as the target
4325 scheduleCall: function(itemClicked, metaData) {
4326 loc = 'index.php?module=Calls&action=EditView';
4327 for(i in metaData) {
4328 if(i != 'module') loc += '&' + i + '=' + metaData[i];
4330 document.location = loc;
4333 * redirects to a new contact with the clicked on object as the target
4335 createContact: function(itemClicked, metaData) {
4336 loc = 'index.php?module=Contacts&action=EditView';
4337 for(i in metaData) {
4338 if(i != 'module') loc += '&' + i + '=' + metaData[i];
4340 document.location = loc;
4343 * redirects to a new task with the clicked on object as the target
4345 createTask: function(itemClicked, metaData) {
4346 loc = 'index.php?module=Tasks&action=EditView';
4347 for(i in metaData) {
4348 if(i != 'module') loc += '&' + i + '=' + metaData[i];
4350 document.location = loc;
4353 * redirects to a new opportunity with the clicked on object as the target
4355 createOpportunity: function(itemClicked, metaData) {
4356 loc = 'index.php?module=Opportunities&action=EditView';
4357 for(i in metaData) {
4358 if(i != 'module') loc += '&' + i + '=' + metaData[i];
4360 document.location = loc;
4363 * redirects to a new opportunity with the clicked on object as the target
4365 createCase: function(itemClicked, metaData) {
4366 loc = 'index.php?module=Cases&action=EditView';
4367 for(i in metaData) {
4368 if(i != 'module') loc += '&' + i + '=' + metaData[i];
4370 document.location = loc;
4373 * handles add to favorites menu selection
4375 addToFavorites: function(itemClicked, metaData) {
4376 success = function(data) {
4378 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});
4383 //if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.contextMenu.init);
4385 // initially from popup_parent_helper.js
4386 var popup_request_data;
4389 function get_popup_request_data()
4391 return YAHOO.lang.JSON.stringify(window.document.popup_request_data);
4394 function get_close_popup()
4396 return window.document.close_popup;
4399 function open_popup(module_name, width, height, initial_filter, close_popup, hide_clear_button, popup_request_data, popup_mode, create, metadata)
4401 if (typeof(popupCount) == "undefined" || popupCount == 0)
4404 // set the variables that the popup will pull from
4405 window.document.popup_request_data = popup_request_data;
4406 window.document.close_popup = close_popup;
4408 //globally changing width and height of standard pop up window from 600 x 400 to 800 x 800
4409 width = (width == 600) ? 800 : width;
4410 height = (height == 400) ? 800 : height;
4414 + 'module=' + module_name
4417 if (initial_filter != '') {
4418 URL += '&query=true' + initial_filter;
4419 // Bug 41891 - Popup Window Name
4420 popupName = initial_filter.replace(/[^a-z_0-9]+/ig, '_');
4421 windowName = module_name + '_popup_window' + popupName;
4423 windowName = module_name + '_popup_window' + popupCount;
4427 if (hide_clear_button) {
4428 URL += '&hide_clear_button=true';
4431 windowFeatures = 'width=' + width
4432 + ',height=' + height
4433 + ',resizable=1,scrollbars=1';
4435 if (popup_mode == '' || popup_mode == undefined) {
4436 popup_mode='single';
4438 URL+='&mode='+popup_mode;
4439 if (create == '' || create == undefined) {
4442 URL+='&create='+create;
4444 if (metadata != '' && metadata != undefined) {
4445 URL+='&metadata='+metadata;
4448 // Bug #46842 : The relate field field_to_name_array fails to copy over custom fields
4449 // post fields that should be populated from popup form
4450 if(popup_request_data.jsonObject) {
4451 var request_data = popup_request_data.jsonObject;
4453 var request_data = popup_request_data;
4455 var field_to_name_array_url = '';
4457 if (request_data && request_data.field_to_name_array != undefined) {
4458 for(var key in request_data.field_to_name_array) {
4459 if ( key.toLowerCase() != 'id' ) {
4460 field_to_name_array_url += '&field_to_name[]='+encodeURIComponent(key.toLowerCase());
4464 if ( field_to_name_array_url ) {
4465 URL+=field_to_name_array_url;
4468 win = SUGAR.util.openWindow(URL, windowName, windowFeatures);
4472 // put the focus on the popup if the browser supports the focus() method
4476 win.popupCount = popupCount;
4482 * The reply data must be a JSON array structured with the following information:
4483 * 1) form name to populate
4484 * 2) associative array of input names to values for populating the form
4486 var from_popup_return = false;
4488 //Function replaces special HTML chars for usage in text boxes
4489 function replaceHTMLChars(value) {
4490 return value.replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');
4493 function set_return_basic(popup_reply_data,filter)
4495 var form_name = popup_reply_data.form_name;
4496 var name_to_value_array = popup_reply_data.name_to_value_array;
4497 for (var the_key in name_to_value_array)
4499 if(the_key == 'toJSON')
4503 else if(the_key.match(filter))
4505 var displayValue=replaceHTMLChars(name_to_value_array[the_key]);
4506 // begin andopes change: support for enum fields (SELECT)
4507 if(window.document.forms[form_name] && window.document.forms[form_name].elements[the_key]) {
4508 if(window.document.forms[form_name].elements[the_key].tagName == 'SELECT') {
4509 var selectField = window.document.forms[form_name].elements[the_key];
4510 for(var i = 0; i < selectField.options.length; i++) {
4511 if(selectField.options[i].text == displayValue) {
4512 selectField.options[i].selected = true;
4513 SUGAR.util.callOnChangeListers(selectField);
4518 window.document.forms[form_name].elements[the_key].value = displayValue;
4519 SUGAR.util.callOnChangeListers(window.document.forms[form_name].elements[the_key]);
4522 // end andopes change: support for enum fields (SELECT)
4527 function set_return(popup_reply_data)
4529 from_popup_return = true;
4530 var form_name = popup_reply_data.form_name;
4531 var name_to_value_array = popup_reply_data.name_to_value_array;
4532 if(typeof name_to_value_array != 'undefined' && name_to_value_array['account_id'])
4535 var label_data_str = '';
4536 var current_label_data_str = '';
4537 var popupConfirm = popup_reply_data.popupConfirm;
4538 for (var the_key in name_to_value_array)
4540 if(the_key == 'toJSON')
4546 var displayValue=replaceHTMLChars(name_to_value_array[the_key]);
4547 if(window.document.forms[form_name] && document.getElementById(the_key+'_label') && !the_key.match(/account/)) {
4548 var data_label = document.getElementById(the_key+'_label').innerHTML.replace(/\n/gi,'').replace(/<\/?[^>]+(>|$)/g, "");
4549 label_str += data_label + ' \n';
4550 label_data_str += data_label + ' ' + displayValue + '\n';
4551 if(window.document.forms[form_name].elements[the_key]) {
4552 current_label_data_str += data_label + ' ' + window.document.forms[form_name].elements[the_key].value +'\n';
4558 if(label_data_str != label_str && current_label_data_str != label_str){
4560 if (typeof popupConfirm != 'undefined')
4562 if (popupConfirm > -1) {
4563 set_return_basic(popup_reply_data,/\S/);
4565 set_return_basic(popup_reply_data,/account/);
4569 else if(confirm(SUGAR.language.get('app_strings', 'NTC_OVERWRITE_ADDRESS_PHONE_CONFIRM') + '\n\n' + label_data_str))
4571 set_return_basic(popup_reply_data,/\S/);
4575 set_return_basic(popup_reply_data,/account/);
4577 }else if(label_data_str != label_str && current_label_data_str == label_str){
4578 set_return_basic(popup_reply_data,/\S/);
4579 }else if(label_data_str == label_str){
4580 set_return_basic(popup_reply_data,/account/);
4583 set_return_basic(popup_reply_data,/\S/);
4587 function set_return_lead_conv(popup_reply_data) {
4588 set_return(popup_reply_data);
4589 if (document.getElementById('lead_conv_ac_op_sel') && typeof onBlurKeyUpHandler=='function') {
4590 onBlurKeyUpHandler();
4594 function set_return_and_save(popup_reply_data)
4596 var form_name = popup_reply_data.form_name;
4597 var name_to_value_array = popup_reply_data.name_to_value_array;
4599 for (var the_key in name_to_value_array)
4601 if(the_key == 'toJSON')
4607 window.document.forms[form_name].elements[the_key].value = name_to_value_array[the_key];
4611 window.document.forms[form_name].return_module.value = window.document.forms[form_name].module.value;
4612 window.document.forms[form_name].return_action.value = 'DetailView';
4613 window.document.forms[form_name].return_id.value = window.document.forms[form_name].record.value;
4614 window.document.forms[form_name].action.value = 'Save';
4615 window.document.forms[form_name].submit();
4619 * This is a helper function to construct the initial filter that can be
4620 * passed into the open_popup() function. It assumes that there is an
4621 * account_id and account_name field in the given form_name to use to
4622 * construct the intial filter string.
4624 function get_initial_filter_by_account(form_name)
4626 var account_id = window.document.forms[form_name].account_id.value;
4627 var account_name = escape(window.document.forms[form_name].account_name.value);
4628 var initial_filter = "&account_id=" + account_id + "&account_name=" + account_name;
4630 return initial_filter;
4632 // end code from popup_parent_helper.js
4634 // begin code for address copy
4636 * This is a function used by the Address widget that will fill
4637 * in the given array fields using the fromKey and toKey as a
4638 * prefix into the form objects HTML elements.
4640 * @param form The HTML form object to parse
4641 * @param fromKey The prefix of elements to copy from
4642 * @param toKey The prefix of elements to copy into
4643 * @return boolean true if successful, false otherwise
4645 function copyAddress(form, fromKey, toKey) {
4647 var elems = new Array("address_street", "address_city", "address_state", "address_postalcode", "address_country");
4648 var checkbox = document.getElementById(toKey + "_checkbox");
4650 if(typeof checkbox != "undefined") {
4651 if(!checkbox.checked) {
4653 t = toKey + "_" + elems[x];
4654 document.getElementById(t).removeAttribute('readonly');
4658 f = fromKey + "_" + elems[x];
4659 t = toKey + "_" + elems[x];
4661 document.getElementById(t).value = document.getElementById(f).value;
4662 document.getElementById(t).setAttribute('readonly', true);
4668 // end code for address copy
4671 * This function is used in Email Template Module.
4672 * It will check whether the template is used in Campaing->EmailMarketing.
4673 * If true, it will notify user.
4676 function check_deletable_EmailTemplate() {
4677 id = document.getElementsByName('record')[0].value;
4678 currentForm = document.getElementById('form');
4680 success:function(r) {
4681 if(r.responseText == 'true') {
4682 if(!confirm(SUGAR.language.get('app_strings','NTC_TEMPLATE_IS_USED'))) {
4686 if(!confirm(SUGAR.language.get('app_strings','NTC_DELETE_CONFIRMATION'))) {
4690 currentForm.return_module.value='EmailTemplates';
4691 currentForm.return_action.value='ListView';
4692 currentForm.action.value='Delete';
4693 currentForm.submit();
4696 url = "index.php?module=EmailTemplates&action=CheckDeletable&from=DetailView&to_pdf=1&record="+id;
4697 YAHOO.util.Connect.asyncRequest('POST',url, call_back,null);
4701 remove_upload_imagefile : function(field_name) {
4702 var field=document.getElementById('remove_imagefile_' + field_name);
4705 //enable the file upload button.
4706 var field=document.getElementById( field_name);
4707 field.style.display="";
4709 //hide the image and remove button.
4710 var field=document.getElementById('img_' + field_name);
4711 field.style.display="none";
4712 var field=document.getElementById('bt_remove_' + field_name);
4713 field.style.display="none";
4715 if(document.getElementById(field_name + '_duplicate')) {
4716 var field = document.getElementById(field_name + '_duplicate');
4721 confirm_imagefile : function(field_name) {
4722 var field=document.getElementById(field_name);
4723 var filename=field.value;
4724 var fileExtension = filename.substring(filename.lastIndexOf(".")+1);
4725 fileExtension = fileExtension.toLowerCase();
4726 if (fileExtension == "jpg" || fileExtension == "jpeg"
4727 || fileExtension == "gif" || fileExtension == "png" || fileExtension == "bmp"){
4732 alert(SUGAR.language.get('app_strings', 'LBL_UPLOAD_IMAGE_FILE_INVALID'));
4736 lightbox : function(image)
4738 if (typeof(SUGAR.image.lighboxWindow) == "undefined")
4739 SUGAR.image.lighboxWindow = new YAHOO.widget.SimpleDialog('sugarImageViewer', {
4742 id:'sugarMsgWindow',
4745 msg: "<img src='" + image + "'> </img>",
4748 SUGAR.image.lighboxWindow.setBody("<img src='" + image + "'> </img>");
4749 SUGAR.image.lighboxWindow.render(document.body);
4750 SUGAR.image.lighboxWindow.show();
4751 SUGAR.image.lighboxWindow.center()
4755 SUGAR.append(SUGAR.util, {
4756 isTouchScreen: function() {
4757 // first check if we have forced use of the touch enhanced interface
4758 if (Get_Cookie("touchscreen") == '1') {
4762 // next check if we should use the touch interface with our device
4763 if ((navigator.userAgent.match(/iPad/i) != null)) {
4770 isLoginPage: function(content) {
4771 //skip if this is packageManager screen
4772 if(SUGAR.util.isPackageManager()) {return false;}
4773 var loginPageStart = "<!DOCTYPE";
4774 if (content.substr(0, loginPageStart.length) == loginPageStart && content.indexOf("<html>") != -1 && content.indexOf("login_module") != -1) {
4775 window.location.href = window.location.protocol + window.location.pathname;
4780 isPackageManager: function(){
4781 if(typeof(document.the_form) !='undefined' && typeof(document.the_form.language_pack_escaped) !='undefined'){
4783 }else{return false;}
4786 ajaxCallInProgress: function(){
4788 //First check if we are in a popup.
4789 if (typeof (send_back) != "function"){
4790 //If the page content is blank, it means we are probably still waiting on something
4791 var c = document.getElementById("content");
4792 if (!c) return true;
4793 t = YAHOO.lang.trim(SUGAR.util.innerText(c));
4795 return SUGAR_callsInProgress != 0 || t == "";
4797 //Firefox doesn't support innerText (textContent includes script content)
4798 innerText : function(el) {
4799 if (el.tagName == "SCRIPT")
4801 if(typeof(el.innerText) == "string")
4802 return el.innerText;
4804 for (var i in el.childNodes){
4805 var c = el.childNodes[i];
4806 if (typeof(c) != "object")
4808 if (typeof(c.nodeName) == "string" && c.nodeName == "#text")
4811 t += SUGAR.util.innerText(c);
4816 callOnChangeListers: function(field){
4817 var listeners = YAHOO.util.Event.getListeners(field, 'change');
4818 if (listeners != null) {
4819 for (var i = 0; i < listeners.length; i++) {
4820 var l = listeners[i];
4821 l.fn.call(l.scope ? l.scope : this, l.obj);
4826 closeActivityPanel: {
4827 show:function(module,id,new_status,viewType,parentContainerId){
4828 if (SUGAR.util.closeActivityPanel.panel)
4829 SUGAR.util.closeActivityPanel.panel.destroy();
4830 var singleModule = SUGAR.language.get("app_list_strings", "moduleListSingular")[module];
4831 singleModule = typeof(singleModule != 'undefined') ? singleModule.toLowerCase() : '';
4832 var closeText = SUGAR.language.get("app_strings", "LBL_CLOSE_ACTIVITY_CONFIRM").replace("#module#",singleModule);
4833 SUGAR.util.closeActivityPanel.panel =
4834 new YAHOO.widget.SimpleDialog("closeActivityDialog",
4841 constraintoviewport: true,
4842 buttons: [ { text:SUGAR.language.get("app_strings", "LBL_EMAIL_OK"), handler:function(){
4843 if (SUGAR.util.closeActivityPanel.panel)
4844 SUGAR.util.closeActivityPanel.panel.hide();
4846 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_SAVING'));
4847 var args = "action=save&id=" + id + "&record=" + id + "&status=" + new_status + "&module=" + module;
4848 // 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
4849 // TODO: Take id out and regression test. Left id in for now to not create any other unexpected problems
4850 //var args = "action=save&id=" + id + "&status=" + new_status + "&module=" + module;
4854 // Bug 51984: We need to submit the form just incase we have a form already submitted
4855 // so we dont get a popup stating that the form needs to be resubmitted like it doesn,
4856 // when you do a reload/refresh
4857 window.setTimeout(function(){if(document.getElementById('search_form')) document.getElementById('search_form').submit(); else window.location.reload(true);}, 0);
4859 argument:{'parentContainerId':parentContainerId}
4862 YAHOO.util.Connect.asyncRequest('POST', 'index.php', callback, args);
4864 }, isDefault:true },
4865 { text:SUGAR.language.get("app_strings", "LBL_EMAIL_CANCEL"), handler:function(){SUGAR.util.closeActivityPanel.panel.hide(); }} ]
4868 SUGAR.util.closeActivityPanel.panel.setHeader(SUGAR.language.get("app_strings", "LBL_CLOSE_ACTIVITY_HEADER"));
4869 SUGAR.util.closeActivityPanel.panel.render(document.body);
4870 SUGAR.util.closeActivityPanel.panel.show();
4874 setEmailPasswordDisplay: function(id, exists, formName) {
4875 link = document.getElementById(id+'_link');
4876 pwd = document.getElementById(id);
4877 if(!pwd || !link) return;
4879 pwd.style.display = 'none';
4880 link.style.display = '';
4881 if(typeof(formName) != 'undefined')
4882 removeFromValidate(formName, id);
4884 pwd.style.display = '';
4885 link.style.display = 'none';
4889 setEmailPasswordEdit: function(id) {
4890 link = document.getElementById(id+'_link');
4891 pwd = document.getElementById(id);
4892 if(!pwd || !link) return;
4893 pwd.style.display = '';
4894 link.style.display = 'none';
4898 * Compares a filename with a supplied array of allowed file extensions.
4899 * @param fileName string
4900 * @param allowedTypes array of allowed file extensions
4903 validateFileExt: function(fileName, allowedTypes) {
4904 var ext = fileName.split('.').pop().toLowerCase();
4906 for (var i = allowedTypes.length; i >= 0; i--) {
4907 if (ext === allowedTypes[i]) {
4915 arrayIndexOf: function(arr, val, start) {
4916 if (typeof arr.indexOf == "function")
4917 return arr.indexOf(val, start);
4918 for (var i = (start || 0), j = arr.length; i < j; i++) {
4919 if (arr[i] === val) {
4927 SUGAR.clearRelateField = function(form, name, id)
4929 if (typeof form[name] == "object"){
4930 form[name].value = '';
4931 SUGAR.util.callOnChangeListers(form[name]);
4934 if (typeof form[id] == "object"){
4935 form[id].value = '';
4936 SUGAR.util.callOnChangeListers(form[id]);
4939 if(typeof(SUGAR.AutoComplete) == 'undefined') SUGAR.AutoComplete = {};
4941 SUGAR.AutoComplete.getOptionsArray = function(options_index){
4942 var return_arr = [];
4944 var opts = SUGAR.language.get('app_list_strings', options_index);
4945 if(typeof(opts) != 'undefined'){
4947 // Since we are using auto complete, we excluse blank dropdown entries since they can just leave it blank
4948 if(key != '' && opts[key] != ''){
4951 item['text'] = opts[key];
4952 return_arr.push(item);
4959 if(typeof(SUGAR.MultiEnumAutoComplete) == 'undefined') SUGAR.MultiEnumAutoComplete = {};
4961 SUGAR.MultiEnumAutoComplete.getMultiSelectKeysFromValues = function(options_index, val_string){
4962 var opts = SUGAR.language.get('app_list_strings', options_index);
4963 var selected_values = val_string.split(", ");
4964 // YUI AutoComplete adds a blank. We remove it automatically here
4965 if(selected_values.length > 0 && selected_values.indexOf('') == selected_values.length - 1){
4966 selected_values.pop();
4968 var final_arr = new Array();
4969 for(idx in selected_values){
4971 if(selected_values[idx] == opts[o_idx]){
4972 final_arr.push(o_idx);
4979 SUGAR.MultiEnumAutoComplete.getMultiSelectValuesFromKeys = function(options_index, val_string){
4980 var opts = SUGAR.language.get('app_list_strings', options_index);
4981 val_string=val_string.replace(/^\^/,'').replace(/\^$/,'') //fixes bug where string starts or ends with ^
4982 var selected_values = val_string.split("^,^");
4984 // YUI AutoComplete adds a blank. We remove it automatically here
4985 if(selected_values.length > 0 && selected_values.indexOf('') == selected_values.length - 1){
4986 selected_values.pop();
4989 var final_arr = new Array();
4990 for(idx in selected_values){
4992 if(selected_values[idx] == o_idx){
4993 final_arr.push(opts[o_idx]);
5000 function convertReportDateTimeToDB(dateValue, timeValue)
5002 var date_match = dateValue.match(date_reg_format);
5003 var time_match = timeValue.match(/([0-9]{1,2})\:([0-9]{1,2})([ap]m)/);
5004 if ( date_match != null && time_match != null) {
5005 time_match[1] = parseInt(time_match[1]);
5006 if (time_match[3] == 'pm') {
5007 time_match[1] = time_match[1] + 12;
5008 if (time_match[1] >= 24) {
5009 time_match[1] = time_match[1] - 24;
5011 } else if (time_match[3] == 'am' && time_match[1] == 12) {
5014 if (time_match[1] < 10) {
5015 time_match[1] = '0' + time_match[1];
5017 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';