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 (\d+\.\d+)/)[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:9, max:10}, // IE 9, 10
188 safari : {min:534}, // Safari 5.1
189 mozilla : {min:23.0}, // Firefox 23.0
190 chrome : {min:29} // Chrome 29
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 current = navigator.userAgent.match(/Chrome\/(.*?) /)[1];
204 supported = supportedBrowsers['chrome'];
206 else if($.browser.safari){ // Safari
207 supported = supportedBrowsers['safari'];
210 if (current && supported)
211 return checkMinSupported(current, String(supported.min)) && (!supported.max || checkMaxSupported(current, String(supported.max)));
216 SUGAR.isIECompatibilityMode = function(){
217 var agentStr = navigator.userAgent;
219 if (agentStr.indexOf("MSIE 7.0") > -1 &&
220 (agentStr.indexOf("Trident/5.0") > -1 || // IE9 Compatibility View
221 agentStr.indexOf("Trident/4.0") > -1 // IE8 Compatibility View
230 SUGAR.isIE = isSupportedIE();
231 var isSafari = (navigator.userAgent.toLowerCase().indexOf('safari')!=-1);
233 // escapes regular expression characters
234 RegExp.escape = function(text) { // http://simon.incutio.com/archive/2006/01/20/escape
235 if (!arguments.callee.sRE) {
236 var specials = ['/', '.', '*', '+', '?', '|','(', ')', '[', ']', '{', '}', '\\'];
237 arguments.callee.sRE = new RegExp('(\\' + specials.join('|\\') + ')', 'g');
239 return text.replace(arguments.callee.sRE, '\\$1');
242 function addAlert(type, name,subtitle, description,time, redirect) {
243 var addIndex = alertList.length;
244 alertList[addIndex]= new Array();
245 alertList[addIndex]['name'] = name;
246 alertList[addIndex]['type'] = type;
247 alertList[addIndex]['subtitle'] = subtitle;
248 alertList[addIndex]['description'] = replaceHTMLChars(description.replace(/<br>/gi, "\n"));
249 alertList[addIndex]['time'] = time;
250 alertList[addIndex]['done'] = 0;
251 alertList[addIndex]['redirect'] = redirect;
253 function checkAlerts() {
254 secondsSinceLoad += 1;
257 for(mj = 0 ; mj < alertList.length; mj++) {
258 if(alertList[mj]['done'] == 0) {
259 if(alertList[mj]['time'] < secondsSinceLoad && alertList[mj]['time'] > -1 ) {
260 alertmsg = alertList[mj]['type'] + ":" + alertList[mj]['name'] + "\n" +alertList[mj]['subtitle']+ "\n"+ alertList[mj]['description'] + "\n\n";
261 alertList[mj]['done'] = 1;
262 if(alertList[mj]['redirect'] == '') {
265 else if(confirm(alertmsg)) {
266 window.location = alertList[mj]['redirect'];
272 alertsTimeoutId = setTimeout("checkAlerts()", 1000);
275 function toggleDisplay(id) {
276 if(this.document.getElementById(id).style.display == 'none') {
277 this.document.getElementById(id).style.display = '';
278 if(this.document.getElementById(id+"link") != undefined) {
279 this.document.getElementById(id+"link").style.display = 'none';
281 if(this.document.getElementById(id+"_anchor") != undefined)
282 this.document.getElementById(id+"_anchor").innerHTML='[ - ]';
285 this.document.getElementById(id).style.display = 'none';
286 if(this.document.getElementById(id+"link") != undefined) {
287 this.document.getElementById(id+"link").style.display = '';
289 if(this.document.getElementById(id+"_anchor") != undefined)
290 this.document.getElementById(id+"_anchor").innerHTML='[+]';
294 function checkAll(form, field, value) {
295 for (i = 0; i < form.elements.length; i++) {
296 if(form.elements[i].name == field)
297 form.elements[i].checked = value;
301 function replaceAll(text, src, rep) {
302 offset = text.toLowerCase().indexOf(src.toLowerCase());
303 while(offset != -1) {
304 text = text.substring(0, offset) + rep + text.substring(offset + src.length ,text.length);
305 offset = text.indexOf( src, offset + rep.length + 1);
310 function addForm(formname) {
311 validate[formname] = new Array();
314 function addToValidate(formname, name, type, required, msg) {
315 if(typeof validate[formname] == 'undefined') {
318 validate[formname][validate[formname].length] = new Array(name, type,required, msg);
321 // Bug #47961 Callback validator definition
322 function addToValidateCallback(formname, name, type, required, msg, callback)
324 addToValidate(formname, name, type, required, msg);
325 var iIndex = validate[formname].length -1;
326 validate[formname][iIndex][jstypeIndex] = 'callback';
327 validate[formname][iIndex][callbackIndex] = callback;
330 function addToValidateRange(formname, name, type,required, msg,min,max) {
331 addToValidate(formname, name, type,required, msg);
332 validate[formname][validate[formname].length - 1][jstypeIndex] = 'range';
333 validate[formname][validate[formname].length - 1][minIndex] = min;
334 validate[formname][validate[formname].length - 1][maxIndex] = max;
337 function addToValidateIsValidDate(formname, name, type, required, msg) {
338 addToValidate(formname, name, type, required, msg);
339 validate[formname][validate[formname].length - 1][jstypeIndex] = 'date';
342 function addToValidateIsValidTime(formname, name, type, required, msg) {
343 addToValidate(formname, name, type, required, msg);
344 validate[formname][validate[formname].length - 1][jstypeIndex] = 'time';
347 function addToValidateDateBefore(formname, name, type, required, msg, compareTo) {
348 addToValidate(formname, name, type,required, msg);
349 validate[formname][validate[formname].length - 1][jstypeIndex] = 'isbefore';
350 validate[formname][validate[formname].length - 1][compareToIndex] = compareTo;
353 function addToValidateDateBeforeAllowBlank(formname, name, type, required, msg, compareTo, allowBlank) {
354 addToValidate(formname, name, type,required, msg);
355 validate[formname][validate[formname].length - 1][jstypeIndex] = 'isbefore';
356 validate[formname][validate[formname].length - 1][compareToIndex] = compareTo;
357 validate[formname][validate[formname].length - 1][allowblank] = allowBlank;
360 function addToValidateBinaryDependency(formname, name, type, required, msg, compareTo) {
361 addToValidate(formname, name, type, required, msg);
362 validate[formname][validate[formname].length - 1][jstypeIndex] = 'binarydep';
363 validate[formname][validate[formname].length - 1][compareToIndex] = compareTo;
366 function addToValidateComparison(formname, name, type, required, msg, compareTo) {
367 addToValidate(formname, name, type, required, msg);
368 validate[formname][validate[formname].length - 1][jstypeIndex] = 'comparison';
369 validate[formname][validate[formname].length - 1][compareToIndex] = compareTo;
372 function addToValidateIsInArray(formname, name, type, required, msg, arr, operator) {
373 addToValidate(formname, name, type, required, msg);
374 validate[formname][validate[formname].length - 1][jstypeIndex] = 'in_array';
375 validate[formname][validate[formname].length - 1][arrIndex] = arr;
376 validate[formname][validate[formname].length - 1][operatorIndex] = operator;
379 function addToValidateVerified(formname, name, type, required, msg, arr, operator) {
380 addToValidate(formname, name, type, required, msg);
381 validate[formname][validate[formname].length - 1][jstypeIndex] = 'verified';
384 function addToValidateLessThan(formname, name, type, required, msg, max, max_field_msg) {
385 addToValidate(formname, name, type, required, msg);
386 validate[formname][validate[formname].length - 1][jstypeIndex] = 'less';
387 validate[formname][validate[formname].length - 1][maxIndex] = max;
388 validate[formname][validate[formname].length - 1][altMsgIndex] = max_field_msg;
391 function addToValidateMoreThan(formname, name, type, required, msg, min) {
392 addToValidate(formname, name, type, required, msg);
393 validate[formname][validate[formname].length - 1][jstypeIndex] = 'more';
394 validate[formname][validate[formname].length - 1][minIndex] = min;
398 function removeFromValidate(formname, name) {
399 for(i = 0; i < validate[formname].length; i++)
401 if(validate[formname][i][nameIndex] == name)
403 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
407 function checkValidate(formname, name) {
408 if(validate[formname]){
409 for(i = 0; i < validate[formname].length; i++){
410 if(validate[formname][i][nameIndex] == name){
417 var formsWithFieldLogic=null;
418 var formWithPrecision =null;
419 function addToValidateFieldLogic(formId,minFieldId, maxFieldId, defaultFieldId, lenFieldId,type,msg){
420 this.formId = document.getElementById(formId);
421 this.min=document.getElementById(minFieldId);
422 this.max= document.getElementById(maxFieldId);
423 this._default= document.getElementById(defaultFieldId);
424 this.len = document.getElementById(lenFieldId);
428 //@params: formid- Dom id of the form containing the precision and float fields
429 // valudId- Dom id of the field containing a float whose precision is to be checked.
430 // precisionId- Dom id of the field containing precision value.
431 function addToValidatePrecision(formId, valueId, precisionId){
432 this.form = document.getElementById(formId);
433 this.float = document.getElementById(valueId);
434 this.precision = document.getElementById(precisionId);
437 //function checkLength(value, referenceValue){
441 function isValidPrecision(value, precision){
442 value = trim(value.toString());
448 if( (precision == "0") ){
449 if (value.indexOf(dec_sep)== -1){
456 if(value.charAt(value.length-precision-1) == num_grp_sep){
457 if(value.substr(value.indexOf(dec_sep), 1)==dec_sep){
462 var actualPrecision = value.substr(value.indexOf(dec_sep)+1, value.length).length;
463 return actualPrecision == precision;
465 function toDecimal(original, precision) {
466 precision = (precision == null) ? 2 : precision;
467 num = Math.pow(10, precision);
468 temp = Math.round(original*num)/num;
469 if((temp * 100) % 100 == 0)
471 if((temp * 10) % 10 == 0)
476 function isInteger(s) {
477 if(typeof num_grp_sep != 'undefined' && typeof dec_sep != 'undefined')
479 s = unformatNumberNoParse(s, num_grp_sep, dec_sep).toString();
481 return /^[+-]?[0-9]*$/.test(s) ;
484 function isDecimal(s) {
485 if (typeof s == "string" && s == "") // bug# 46530, this is required in order to
486 return true; // not check empty decimal fields
488 if(typeof num_grp_sep != 'undefined' && typeof dec_sep != 'undefined')
490 s = unformatNumberNoParse(s, num_grp_sep, dec_sep).toString();
492 return /^[+-]?[0-9]*\.?[0-9]*$/.test(s) ;
495 function isNumeric(s) {
499 if (typeof date_reg_positions != "object") var date_reg_positions = {'Y': 1,'m': 2,'d': 3};
500 if (typeof date_reg_format != "string") var date_reg_format = '([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})';
502 function isDate(dtStr) {
504 if(dtStr.length== 0) {
508 // Check that we have numbers
509 myregexp = new RegExp(date_reg_format)
510 if(!myregexp.test(dtStr))
517 var dateParts = dtStr.match(date_reg_format);
518 for(key in date_reg_positions) {
519 index = date_reg_positions[key];
521 m = dateParts[index];
522 } else if(key == 'd') {
523 d = dateParts[index];
525 y = dateParts[index];
529 // Check that date is real
530 var dd = new Date(y,m,0);
531 // reject negative years
534 // reject month less than 1 and greater than 12
537 // reject days less than 1 or days not in month (e.g. February 30th)
538 if (d < 1 || d > dd.getDate())
543 function getDateObject(dtStr) {
544 if(dtStr.length== 0) {
548 myregexp = new RegExp(date_reg_format)
550 if(myregexp.exec(dtStr)) var dt = myregexp.exec(dtStr)
553 var yr = dt[date_reg_positions['Y']];
554 var mh = dt[date_reg_positions['m']];
555 var dy = dt[date_reg_positions['d']];
556 var dtar = dtStr.split(' ');
558 if(typeof(dtar[1])!='undefined' && isTime(dtar[1])) {//if it is a timedate, we should make date1 to have time value
559 var t1 = dtar[1].replace(/am/i,' AM');
560 var t1 = t1.replace(/pm/i,' PM');
561 //bug #37977: where time format 23.00 causes java script error
562 t1=t1.replace(/\./, ':');
563 date1 = new Date(mh+'/'+dy+'/'+yr+' '+t1);
567 date1 = new Date(mh+'/'+dy+'/'+yr);
570 if (isNaN(date1.valueOf())) {
577 function isBefore(value1, value2) {
578 var d1 = getDateObject(value1);
579 var d2 = getDateObject(value2);
580 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.
586 function isValidEmail(emailStr) {
588 if(emailStr.length== 0) {
591 // cn: bug 7128, a period at the end of the string mangles checks. (switched to accept spaces and delimiters)
592 var lastChar = emailStr.charAt(emailStr.length - 1);
593 if(!lastChar.match(/[^\.]/i)) {
596 //bug 40068, According to rules in page 6 of http://www.apps.ietf.org/rfc/rfc3696.html#sec-3,
597 //first character of local part of an email address
598 //should not be a period i.e. '.'
600 var firstLocalChar=emailStr.charAt(0);
601 if(firstLocalChar.match(/\./)){
605 //bug 40068, According to rules in page 6 of http://www.apps.ietf.org/rfc/rfc3696.html#sec-3,
606 //last character of local part of an email address
607 //should not be a period i.e. '.'
609 var pos=emailStr.lastIndexOf("@");
610 var localPart = emailStr.substr(0, pos);
611 var lastLocalChar=localPart.charAt(localPart.length - 1);
612 if(lastLocalChar.match(/\./)){
619 while ((results = reg.exec(emailStr)) != null) {
620 var original = results[0];
621 parsedResult = results[0].replace(';', '::;::');
622 emailStr = emailStr.replace (original, parsedResult);
626 while ((results = reg.exec(emailStr)) != null) {
627 var original = results[0];
628 //Check if we were using ; as a delimiter. If so, skip the commas
629 if(original.indexOf("::;::") == -1) {
630 var parsedResult = results[0].replace(',', '::;::');
631 emailStr = emailStr.replace (original, parsedResult);
635 // mfh: bug 15010 - more practical implementation of RFC 2822 from http://www.regular-expressions.info/email.html, modifed to accept CAPITAL LETTERS
636 //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))
639 //bug 40068, According to rules in page 6 of http://www.apps.ietf.org/rfc/rfc3696.html#sec-3,
640 //allowed special characters ! # $ % & ' * + - / = ? ^ _ ` . { | } ~ in local part
641 var emailArr = emailStr.split(/::;::/);
642 for (var i = 0; i < emailArr.length; i++) {
643 var emailAddress = emailArr[i];
644 if (trim(emailAddress) != '') {
645 if(!/^\s*[\w.%+\-&'#!\$\*=\?\^_`\{\}~\/]+@([A-Z0-9-]+\.)*[A-Z0-9-]+\.[\w-]{2,}\s*$/i.test(emailAddress) &&
646 !/^.*<[A-Z0-9._%+\-&'#!\$\*=\?\^_`\{\}~]+?@([A-Z0-9-]+\.)*[A-Z0-9-]+\.[\w-]{2,}>\s*$/i.test(emailAddress)) {
655 function isValidPhone(phoneStr) {
656 if(phoneStr.length== 0) {
659 if(!/^[0-9\-\(\)\s]+$/.test(phoneStr))
663 function isFloat(floatStr) {
664 if(floatStr.length== 0) {
667 if(!(typeof(num_grp_sep)=='undefined' || typeof(dec_sep)=='undefined')) {
668 floatStr = unformatNumberNoParse(floatStr, num_grp_sep, dec_sep).toString();
671 return /^(-)?[0-9\.]+$/.test(floatStr);
673 function isDBName(str) {
678 // must start with a letter
679 if(!/^[a-zA-Z][a-zA-Z\_0-9]*$/.test(str))
683 var time_reg_format = "[0-9]{1,2}\:[0-9]{2}";
684 function isTime(timeStr) {
685 var timeRegex = time_reg_format;
686 // eliminate the am/pm from the external time_reg_format
687 timeRegex = timeRegex.replace(/[ ]*\([^)]*m\)/i, '');
688 if(timeStr.length== 0){
691 //we now support multiple time formats
692 myregexp = new RegExp(timeRegex);
693 if(!myregexp.test(timeStr)) {
700 function inRange(value, min, max) {
701 if (typeof num_grp_sep != 'undefined' && typeof dec_sep != 'undefined')
702 value = unformatNumberNoParse(value, num_grp_sep, dec_sep).toString();
704 if (typeof min == 'number' && value < min)
708 if (typeof max == 'number' && value > max)
715 function bothExist(item1, item2) {
716 if(typeof item1 == 'undefined') { return false; }
717 if(typeof item2 == 'undefined') { return false; }
718 if((item1 == '' && item2 != '') || (item1 != '' && item2 == '') ) { return false; }
722 trim = YAHOO.lang.trim;
725 function check_form(formname) {
726 if (typeof(siw) != 'undefined' && siw
727 && typeof(siw.selectingSomething) != 'undefined' && siw.selectingSomething)
729 return validate_form(formname, '');
732 function add_error_style(formname, input, txt, flash) {
733 var raiseFlag = false;
734 if (typeof flash == "undefined")
737 inputHandle = typeof input == "object" ? input : document.forms[formname][input];
738 style = get_current_bgcolor(inputHandle);
740 // strip off the colon at the end of the warning strings
741 if ( txt.substring(txt.length-1) == ':' )
742 txt = txt.substring(0,txt.length-1)
744 // Bug 28249 - To help avoid duplicate messages for an element, strip off extra messages and
745 // match on the field name itself
746 requiredTxt = SUGAR.language.get('app_strings', 'ERR_MISSING_REQUIRED_FIELDS');
747 invalidTxt = SUGAR.language.get('app_strings', 'ERR_INVALID_VALUE');
748 nomatchTxt = SUGAR.language.get('app_strings', 'ERR_SQS_NO_MATCH_FIELD');
749 matchTxt = txt.replace(requiredTxt,'').replace(invalidTxt,'').replace(nomatchTxt,'');
751 YUI().use('node', function (Y) {
752 Y.one(inputHandle).get('parentNode').get('children').each(function(node, index, nodeList){
753 if(node.hasClass('validation-message') && node.get('text').search(matchTxt)){
760 errorTextNode = document.createElement('div');
761 errorTextNode.className = 'required validation-message';
762 errorTextNode.innerHTML = txt;
763 if ( inputHandle.parentNode.className.indexOf('x-form-field-wrap') != -1 ) {
764 inputHandle.parentNode.parentNode.appendChild(errorTextNode);
767 inputHandle.parentNode.appendChild(errorTextNode);
770 inputHandle.style.backgroundColor = "#FF0000";
771 inputsWithErrors.push(inputHandle);
775 // We only need to setup the flashy-flashy on the first entry, it loops through all fields automatically
776 if ( inputsWithErrors.length == 1 ) {
777 for(var wp = 1; wp <= 10; wp++) {
778 window.setTimeout('fade_error_style(style, '+wp*10+')',1000+(wp*50));
781 if(typeof (window[formname + "_tabs"]) != "undefined") {
782 var tabView = window[formname + "_tabs"];
783 var parentDiv = YAHOO.util.Dom.getAncestorByTagName(inputHandle, "div");
785 var tabs = tabView.get("tabs");
786 for (var i in tabs) {
787 if (tabs[i].get("contentEl") == parentDiv
788 || YAHOO.util.Dom.isAncestor(tabs[i].get("contentEl"), inputHandle))
790 tabs[i].get("labelEl").style.color = "red";
791 if ( inputsWithErrors.length == 1 )
792 tabView.selectTab(i);
797 window.setTimeout("inputsWithErrors[" + (inputsWithErrors.length - 1) + "].style.backgroundColor = '';", 2000);
801 // Catch errors here so we don't allow an incomplete record through the javascript validation
807 * removes all error messages for the current form
809 function clear_all_errors() {
810 for(var wp = 0; wp < inputsWithErrors.length; wp++) {
811 if(typeof(inputsWithErrors[wp]) !='undefined' && typeof inputsWithErrors[wp].parentNode != 'undefined' && inputsWithErrors[wp].parentNode != null) {
812 if ( inputsWithErrors[wp].parentNode.className.indexOf('x-form-field-wrap') != -1 )
814 inputsWithErrors[wp].parentNode.parentNode.removeChild(inputsWithErrors[wp].parentNode.parentNode.lastChild);
818 inputsWithErrors[wp].parentNode.removeChild(inputsWithErrors[wp].parentNode.lastChild);
822 if (inputsWithErrors.length == 0) return;
824 if ( YAHOO.util.Dom.getAncestorByTagName(inputsWithErrors[0], "form") ) {
825 var formname = YAHOO.util.Dom.getAncestorByTagName(inputsWithErrors[0], "form").getAttribute("name");
826 if(typeof (window[formname + "_tabs"]) != "undefined") {
827 var tabView = window[formname + "_tabs"];
829 var tabs = tabView.get("tabs");
830 for (var i in tabs) {
831 if (typeof tabs[i] == "object")
832 tabs[i].get("labelEl").style.color = "";
836 inputsWithErrors = new Array();
840 function get_current_bgcolor(input) {
841 if(input.currentStyle) {// ie
842 style = input.currentStyle.backgroundColor;
843 return style.substring(1,7);
847 styleRGB = document.defaultView.getComputedStyle(input, '').getPropertyValue("background-color");
848 comma = styleRGB.indexOf(',');
849 style += dec2hex(styleRGB.substring(4, comma));
850 commaPrevious = comma;
851 comma = styleRGB.indexOf(',', commaPrevious+1);
852 style += dec2hex(styleRGB.substring(commaPrevious+2, comma));
853 style += dec2hex(styleRGB.substring(comma+2, styleRGB.lastIndexOf(')')));
858 function hex2dec(hex){return(parseInt(hex,16));}
859 var hexDigit=new Array("0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F");
860 function dec2hex(dec){return(hexDigit[dec>>4]+hexDigit[dec&15]);}
862 function fade_error_style(normalStyle, percent) {
863 errorStyle = 'c60c30';
864 var r1 = hex2dec(errorStyle.slice(0,2));
865 var g1 = hex2dec(errorStyle.slice(2,4));
866 var b1 = hex2dec(errorStyle.slice(4,6));
868 var r2 = hex2dec(normalStyle.slice(0,2));
869 var g2 = hex2dec(normalStyle.slice(2,4));
870 var b2 = hex2dec(normalStyle.slice(4,6));
873 var pc = percent / 100;
875 r= Math.floor(r1+(pc*(r2-r1)) + .5);
876 g= Math.floor(g1+(pc*(g2-g1)) + .5);
877 b= Math.floor(b1+(pc*(b2-b1)) + .5);
879 for(var wp = 0; wp < inputsWithErrors.length; wp++) {
880 inputsWithErrors[wp].style.backgroundColor = "#" + dec2hex(r) + dec2hex(g) + dec2hex(b);
884 function isFieldTypeExceptFromEmptyCheck(fieldType)
887 var exemptList = ['bool','file'];
888 for(var i=0;i<exemptList.length;i++)
890 if(fieldType == exemptList[i])
895 function validate_form(formname, startsWith){
896 requiredTxt = SUGAR.language.get('app_strings', 'ERR_MISSING_REQUIRED_FIELDS');
897 invalidTxt = SUGAR.language.get('app_strings', 'ERR_INVALID_VALUE');
899 if ( typeof (formname) == 'undefined')
903 if ( typeof (validate[formname]) == 'undefined')
905 disableOnUnloadEditView(document.forms[formname]);
909 var form = document.forms[formname];
912 var _date = new Date();
913 if(_date.getTime() < (lastSubmitTime + 2000) && startsWith == oldStartsWith) { // ignore submits for the next 2 seconds
916 lastSubmitTime = _date.getTime();
917 oldStartsWith = startsWith;
919 clear_all_errors(); // remove previous error messages
921 inputsWithErrors = new Array();
922 for(var i = 0; i < validate[formname].length; i++){
923 if(validate[formname][i][nameIndex].indexOf(startsWith) == 0){
924 if(typeof form[validate[formname][i][nameIndex]] != 'undefined' && typeof form[validate[formname][i][nameIndex]].value != 'undefined'){
928 //If a field is not required and it is blank or is binarydependant, skip validation.
929 //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
930 if(!validate[formname][i][requiredIndex] && trim(form[validate[formname][i][nameIndex]].value) == '' && (typeof(validate[formname][i][jstypeIndex]) != 'undefined' && validate[formname][i][jstypeIndex] != 'binarydep'))
935 if(validate[formname][i][requiredIndex]
936 && !isFieldTypeExceptFromEmptyCheck(validate[formname][i][typeIndex])
938 if(typeof form[validate[formname][i][nameIndex]] == 'undefined' || trim(form[validate[formname][i][nameIndex]].value) == ""){
939 add_error_style(formname, validate[formname][i][nameIndex], requiredTxt +' ' + validate[formname][i][msgIndex]);
944 switch(validate[formname][i][typeIndex]){
946 if(!isValidEmail(trim(form[validate[formname][i][nameIndex]].value))){
948 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
952 if( !isTime(trim(form[validate[formname][i][nameIndex]].value))){
954 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
956 case 'date': if(!isDate(trim(form[validate[formname][i][nameIndex]].value))){
958 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
963 if(!isDBName(trim(form[validate[formname][i][nameIndex]].value))){
965 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
968 // Bug #49614 : Check value without trimming before
970 if(!isDBName(form[validate[formname][i][nameIndex]].value)){
972 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
978 var file_input = form[validate[formname][i][nameIndex] + '_file'];
979 if( file_input && validate[formname][i][requiredIndex] && trim(file_input.value) == "" && !file_input.disabled ) {
981 add_error_style(formname, validate[formname][i][nameIndex], requiredTxt + " " + validate[formname][i][msgIndex]);
985 if(!isInteger(trim(form[validate[formname][i][nameIndex]].value))){
987 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
991 if(!isDecimal(trim(form[validate[formname][i][nameIndex]].value))){
993 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
998 if(!isFloat(trim(form[validate[formname][i][nameIndex]].value))){
1000 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
1003 case 'teamset_mass':
1004 var div_element_id = formname + '_' + form[validate[formname][i][nameIndex]].name + '_operation_div';
1005 var input_elements = YAHOO.util.Selector.query('input', document.getElementById(div_element_id));
1006 var primary_field_id = '';
1007 var validation_passed = false;
1008 var replace_selected = false;
1010 //Loop through the option elements (replace or add currently)
1011 for(t in input_elements) {
1012 if(input_elements[t].type && input_elements[t].type == 'radio' && input_elements[t].checked == true && input_elements[t].value == 'replace') {
1014 //Now find where the primary radio button is and if a value has been set
1015 var radio_elements = YAHOO.util.Selector.query('input[type=radio]', document.getElementById(formname + '_team_name_table'));
1017 for(var x = 0; x < radio_elements.length; x++) {
1018 if(radio_elements[x].name != 'team_name_type') {
1019 primary_field_id = 'team_name_collection_' + radio_elements[x].value;
1020 if(radio_elements[x].checked) {
1021 replace_selected = true;
1022 if(trim(document.forms[formname].elements[primary_field_id].value) != '') {
1023 validation_passed = true;
1026 } else if(trim(document.forms[formname].elements[primary_field_id].value) != '') {
1027 replace_selected = true;
1034 if(replace_selected && !validation_passed) {
1035 add_error_style(formname, primary_field_id, SUGAR.language.get('app_strings', 'ERR_NO_PRIMARY_TEAM_SPECIFIED'));
1040 var table_element_id = formname + '_' + form[validate[formname][i][nameIndex]].name + '_table';
1041 if(document.getElementById(table_element_id)) {
1042 var input_elements = YAHOO.util.Selector.query('input[type=radio]', document.getElementById(table_element_id));
1043 var has_primary = false;
1044 var primary_field_id = form[validate[formname][i][nameIndex]].name + '_collection_0';
1046 for(t in input_elements) {
1047 primary_field_id = form[validate[formname][i][nameIndex]].name + '_collection_' + input_elements[t].value;
1048 if(input_elements[t].type && input_elements[t].type == 'radio' && input_elements[t].checked == true) {
1049 if(document.forms[formname].elements[primary_field_id].value != '') {
1058 var field_id = form[validate[formname][i][nameIndex]].name + '_collection_' + input_elements[0].value;
1059 add_error_style(formname, field_id, SUGAR.language.get('app_strings', 'ERR_NO_PRIMARY_TEAM_SPECIFIED'));
1065 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex]);
1069 if(typeof validate[formname][i][jstypeIndex] != 'undefined'/* && !isError*/){
1071 switch(validate[formname][i][jstypeIndex]){
1072 // Bug #47961 May be validation through callback is best way.
1074 if (typeof validate[formname][i][callbackIndex] == 'function')
1076 var result = validate[formname][i][callbackIndex](formname, validate[formname][i][nameIndex]);
1077 if (result == false)
1080 add_error_style(formname, validate[formname][i][nameIndex], requiredTxt + " " + validate[formname][i][msgIndex]);
1085 if(!inRange(trim(form[validate[formname][i][nameIndex]].value), validate[formname][i][minIndex], validate[formname][i][maxIndex])){
1087 var lbl_validate_range = SUGAR.language.get('app_strings', 'LBL_VALIDATE_RANGE');
1088 if (typeof validate[formname][i][minIndex] == 'number' && typeof validate[formname][i][maxIndex] == 'number')
1090 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] + ")");
1092 else if (typeof validate[formname][i][minIndex] == 'number')
1094 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'));
1096 else if (typeof validate[formname][i][maxIndex] == 'number')
1098 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]);
1103 compareTo = form[validate[formname][i][compareToIndex]];
1104 if( typeof compareTo != 'undefined'){
1105 if(trim(compareTo.value) != '' || (validate[formname][i][allowblank] != 'true') ) {
1106 date2 = trim(compareTo.value);
1107 date1 = trim(form[validate[formname][i][nameIndex]].value);
1109 if(trim(date1).length != 0 && !isBefore(date1,date2)){
1112 //jc:#12287 - adding translation for the is not before message
1113 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex] + "(" + date1 + ") " + SUGAR.language.get('app_strings', 'MSG_IS_NOT_BEFORE') + ' ' +date2);
1119 value=unformatNumber(trim(form[validate[formname][i][nameIndex]].value), num_grp_sep, dec_sep);
1120 maximum = parseFloat(validate[formname][i][maxIndex]);
1121 if( typeof maximum != 'undefined'){
1124 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]);
1129 value=unformatNumber(trim(form[validate[formname][i][nameIndex]].value), num_grp_sep, dec_sep);
1130 minimum = parseFloat(validate[formname][i][minIndex]);
1131 if( typeof minimum != 'undefined'){
1134 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'));
1139 compareTo = form[validate[formname][i][compareToIndex]];
1140 if( typeof compareTo != 'undefined') {
1141 item1 = trim(form[validate[formname][i][nameIndex]].value);
1142 item2 = trim(compareTo.value);
1143 if(!bothExist(item1, item2)) {
1145 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex]);
1150 compareTo = form[validate[formname][i][compareToIndex]];
1151 if( typeof compareTo != 'undefined') {
1152 item1 = trim(form[validate[formname][i][nameIndex]].value);
1153 item2 = trim(compareTo.value);
1154 if(!bothExist(item1, item2) || item1 != item2) {
1156 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex]);
1161 arr = eval(validate[formname][i][arrIndex]);
1162 operator = validate[formname][i][operatorIndex];
1163 item1 = trim(form[validate[formname][i][nameIndex]].value);
1164 if (operator.charAt(0) == 'u') {
1165 item1 = item1.toUpperCase();
1166 operator = operator.substring(1);
1167 } else if (operator.charAt(0) == 'l') {
1168 item1 = item1.toLowerCase();
1169 operator = operator.substring(1);
1171 for(j = 0; j < arr.length; j++){
1173 if((operator == "==" && val == item1) || (operator == "!=" && val != item1)){
1175 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
1180 if(trim(form[validate[formname][i][nameIndex]].value) == 'false'){
1181 //Fake an error so form does not submit
1191 /* nsingh: BUG#15102
1192 Check min max default field logic.
1193 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.*/
1194 if(formsWithFieldLogic){
1195 var invalidLogic=false;
1196 if(formsWithFieldLogic.min && formsWithFieldLogic.max && formsWithFieldLogic._default) {
1197 var showErrorsOn={min:{value:'min', show:false, obj:formsWithFieldLogic.min.value},
1198 max:{value:'max',show:false, obj:formsWithFieldLogic.max.value},
1199 _default:{value:'default',show:false, obj:formsWithFieldLogic._default.value},
1200 len:{value:'len', show:false, obj:parseInt(formsWithFieldLogic.len.value,10)}};
1202 var min = (formsWithFieldLogic.min.value !='') ? parseFloat(formsWithFieldLogic.min.value) : 'undef';
1203 var max = (formsWithFieldLogic.max.value !='') ? parseFloat(formsWithFieldLogic.max.value) : 'undef';
1204 var _default = (formsWithFieldLogic._default.value!='')? parseFloat(formsWithFieldLogic._default.value) : 'undef';
1206 /*Check all lengths are <= max size.*/
1207 for(var i in showErrorsOn){
1208 if(showErrorsOn[i].value!='len' && showErrorsOn[i].obj.length > showErrorsOn.len.obj){
1210 showErrorsOn[i].show=true;
1211 showErrorsOn.len.show=true;
1215 if(min!='undef' && max!='undef' && _default!='undef'){
1216 if(!inRange(_default,min,max)){
1218 showErrorsOn.min.show=true;
1219 showErrorsOn.max.show=true;
1220 showErrorsOn._default.show=true;
1223 if(min!='undef' && max!= 'undef' && min > max){
1224 invalidLogic = true;
1225 showErrorsOn.min.show=true;
1226 showErrorsOn.max.show=true;
1228 if(min!='undef' && _default!='undef' && _default < min){
1230 invalidLogic = true;
1231 showErrorsOn.min.show=true;
1232 showErrorsOn._default.show=true;
1234 if(max!='undef' && _default !='undef' && _default>max){
1236 invalidLogic = true;
1237 showErrorsOn.max.show=true;
1238 showErrorsOn._default.show=true;
1243 for(var error in showErrorsOn)
1244 if(showErrorsOn[error].show)
1245 add_error_style(formname,showErrorsOn[error].value, formsWithFieldLogic.msg);
1250 formsWithFieldLogic = null;
1253 if(formWithPrecision){
1254 if (!isValidPrecision(formWithPrecision.float.value, formWithPrecision.precision.value)){
1256 add_error_style(formname, 'default', SUGAR.language.get('app_strings', 'ERR_COMPATIBLE_PRECISION_VALUE'));
1264 if (isError == true) {
1266 if (self.pageYOffset) // all except Explorer
1268 nwX = self.pageXOffset;
1269 seX = self.innerWidth;
1270 nwY = self.pageYOffset;
1271 seY = self.innerHeight;
1273 else if (document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
1275 nwX = document.documentElement.scrollLeft;
1276 seX = document.documentElement.clientWidth;
1277 nwY = document.documentElement.scrollTop;
1278 seY = document.documentElement.clientHeight;
1280 else if (document.body) // all other Explorers
1282 nwX = document.body.scrollLeft;
1283 seX = document.body.clientWidth;
1284 nwY = document.body.scrollTop;
1285 seY = document.body.clientHeight;
1288 var inView = true; // is there an error within viewport of browser
1289 for(var wp = 0; wp < inputsWithErrors.length; wp++) {
1290 var elementCoor = findElementPos(inputsWithErrors[wp]);
1291 if(!(elementCoor.x >= nwX && elementCoor.y >= nwY &&
1292 elementCoor.x <= seX+nwX && elementCoor.y <= seY+nwY)) { // if input is not within viewport, modify for SI bug 52497
1294 scrollToTop = elementCoor.y - 75;
1295 scrollToLeft = elementCoor.x - 75;
1297 else { // on first input within viewport, don't scroll
1303 if(!inView) window.scrollTo(scrollToLeft,scrollToTop);
1308 disableOnUnloadEditView(form);
1315 * This array is used to remember mark status of rows in browse mode
1317 var marked_row = new Array;
1321 * Sets/unsets the pointer and marker in browse mode
1323 * @param object the table row
1324 * @param interger the row number
1325 * @param string the action calling this script (over, out or click)
1326 * @param string the default background color
1327 * @param string the color to use for mouseover
1328 * @param string the color to use for marking a row
1330 * @return boolean whether pointer is set or not
1332 function setPointer(theRow, theRowNum, theAction, theDefaultColor, thePointerColor, theMarkColor) {
1333 var theCells = null;
1335 // 1. Pointer and mark feature are disabled or the browser can't get the
1337 if ((thePointerColor == '' && theMarkColor == '')
1338 || typeof(theRow.style) == 'undefined') {
1342 // 2. Gets the current row and exits if the browser can't get it
1343 if (typeof(document.getElementsByTagName) != 'undefined') {
1344 theCells = theRow.getElementsByTagName('td');
1346 else if (typeof(theRow.cells) != 'undefined') {
1347 theCells = theRow.cells;
1353 // 3. Gets the current color...
1354 var rowCellsCnt = theCells.length;
1355 var domDetect = null;
1356 var currentColor = null;
1357 var newColor = null;
1358 // 3.1 ... with DOM compatible browsers except Opera that does not return
1359 // valid values with "getAttribute"
1360 if (typeof(window.opera) == 'undefined'
1361 && typeof(theCells[0].getAttribute) != 'undefined') {
1362 currentColor = theCells[0].getAttribute('bgcolor');
1365 // 3.2 ... with other browsers
1367 currentColor = theCells[0].style.backgroundColor;
1371 // 4. Defines the new color
1372 // 4.1 Current color is the default one
1373 if (currentColor == ''
1374 || (currentColor!= null && (currentColor.toLowerCase() == theDefaultColor.toLowerCase()))) {
1375 if (theAction == 'over' && thePointerColor != '') {
1376 newColor = thePointerColor;
1378 else if (theAction == 'click' && theMarkColor != '') {
1379 newColor = theMarkColor;
1380 marked_row[theRowNum] = true;
1383 // 4.1.2 Current color is the pointer one
1384 else if (currentColor!= null && (currentColor.toLowerCase() == thePointerColor.toLowerCase())
1385 && (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])) {
1386 if (theAction == 'out') {
1387 newColor = theDefaultColor;
1389 else if (theAction == 'click' && theMarkColor != '') {
1390 newColor = theMarkColor;
1391 marked_row[theRowNum] = true;
1394 // 4.1.3 Current color is the marker one
1395 else if (currentColor!= null && (currentColor.toLowerCase() == theMarkColor.toLowerCase())) {
1396 if (theAction == 'click') {
1397 newColor = (thePointerColor != '')
1400 marked_row[theRowNum] = (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])
1406 // 5. Sets the new color...
1409 // 5.1 ... with DOM compatible browsers except Opera
1411 for (c = 0; c < rowCellsCnt; c++) {
1412 theCells[c].setAttribute('bgcolor', newColor, 0);
1415 // 5.2 ... with other browsers
1417 for (c = 0; c < rowCellsCnt; c++) {
1418 theCells[c].style.backgroundColor = newColor;
1424 } // end of the 'setPointer()' function
1428 * listbox redirection
1430 function goToUrl(selObj, goToLocation) {
1431 eval("document.location.href = '" + goToLocation + "pos=" + selObj.options[selObj.selectedIndex].value + "'");
1436 var json_objects = new Object();
1438 function getXMLHTTPinstance() {
1439 var xmlhttp = false;
1440 var userAgent = navigator.userAgent.toLowerCase() ;
1442 // IE Check supports ActiveX controls
1443 if (userAgent.indexOf("msie") != -1 && userAgent.indexOf("mac") == -1 && userAgent.indexOf("opera") == -1) {
1444 var version = navigator.appVersion.match(/MSIE (\d+\.\d+)/)[1] ;
1445 if(version >= 5.5 ) {
1447 xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
1451 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
1460 if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
1461 xmlhttp = new XMLHttpRequest();
1466 // NOW LOAD THE OBJECT..
1467 var global_xmlhttp = getXMLHTTPinstance();
1469 function http_fetch_sync(url,post_data) {
1470 global_xmlhttp = getXMLHTTPinstance();
1473 if(typeof(post_data) != 'undefined') method = 'POST';
1475 global_xmlhttp.open(method, url,false);
1478 alert('message:'+e.message+":url:"+url);
1480 if(method == 'POST') {
1481 global_xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
1484 global_xmlhttp.send(post_data);
1486 if (SUGAR.util.isLoginPage(global_xmlhttp.responseText))
1489 var args = {"responseText" : global_xmlhttp.responseText,
1490 "responseXML" : global_xmlhttp.responseXML,
1491 "request_id" : typeof(request_id) != "undefined" ? request_id : 0};
1495 // this is a GET unless post_data is defined
1497 function http_fetch_async(url,callback,request_id,post_data) {
1499 if(typeof(post_data) != 'undefined') {
1504 global_xmlhttp.open(method, url,true);
1507 alert('message:'+e.message+":url:"+url);
1509 if(method == 'POST') {
1510 global_xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
1512 global_xmlhttp.onreadystatechange = function() {
1513 if(global_xmlhttp.readyState==4) {
1514 if(global_xmlhttp.status == 200) {
1515 if (SUGAR.util.isLoginPage(global_xmlhttp.responseText))
1517 var args = {"responseText" : global_xmlhttp.responseText,
1518 "responseXML" : global_xmlhttp.responseXML,
1519 "request_id" : request_id };
1520 callback.call(document,args);
1523 alert("There was a problem retrieving the XML data:\n" + global_xmlhttp.statusText);
1527 global_xmlhttp.send(post_data);
1530 function insert_at_cursor(field, value) {
1532 if (document.selection) {
1534 sel = document.selection.createRange();
1538 else if(field.selectionStart || field.selectionStart == '0') {
1539 var start_pos = field.selectionStart;
1540 var end_pos = field.selectionEnd;
1541 field.value = field.value.substring(0, start_pos) + value + field.value.substring(end_pos, field.value.length);
1544 field.value += value;
1548 function checkParentType(type,button) {
1549 if(button == null) {
1552 if(typeof disabledModules != 'undefined' && typeof(disabledModules[type]) != 'undefined') {
1553 button.disabled='disabled';
1556 button.disabled = false;
1560 function parseDate(input, format) {
1562 format = format.replace(/%/g, '');
1563 sep = format.charAt(1);
1564 yAt = format.indexOf('Y')
1565 // 1-1-06 or 1-12-06 or 1-1-2006 or 1-12-2006
1566 if(date.match(/^\d{1,2}[\/-]\d{1,2}[\/-]\d{2,4}$/) && yAt == 4) {
1567 if(date.match(/^\d{1}[\/-].*$/)) date = '0' + date;
1568 if(date.match(/^\d{2}[\/-]\d{1}[\/-].*$/)) date = date.substring(0,3) + '0' + date.substring(3,date.length);
1569 if(date.match(/^\d{2}[\/-]\d{2}[\/-]\d{2}$/)) date = date.substring(0,6) + '20' + date.substring(6,date.length);
1571 // 06-11-1 or 06-1-1
1572 else if(date.match(/^\d{2,4}[\/-]\d{1,2}[\/-]\d{1,2}$/)) {
1573 if(date.match(/^\d{2}[\/-].*$/)) date = '20' + date;
1574 if(date.match(/^\d{4}[\/-]\d{1}[\/-].*$/)) date = date.substring(0,5) + '0' + date.substring(5,date.length);
1575 if(date.match(/^\d{4}[\/-]\d{2}[\/-]\d{1}$/)) date = date.substring(0,8) + '0' + date.substring(8,date.length);
1577 else if(date.match(/^\d{4,8}$/)) { // digits only
1579 if(date.match(/^\d{8}$/)) digits = 8;// match for 8 digits
1580 else if(date.match(/\d{6}/)) digits = 6;// match for 5 digits
1581 else if(date.match(/\d{4}/)) digits = 4;// match for 5 digits
1582 else if(date.match(/\d{5}/)) digits = 5;// match for 5 digits
1587 case 4: date = '20' + date.substring(0,2) + sep + '0' + date.substring(2, 3) + sep + '0' + date.substring(3,4); break;
1588 case 5: date = '20' + date.substring(0,2) + sep + date.substring(2, 4) + sep + '0' + date.substring(4,5); break;
1589 case 6: date = '20' + date.substring(0,2) + sep + date.substring(2, 4) + sep + date.substring(4,6); break;
1590 case 8: date = date.substring(0,4) + sep + date.substring(4, 6) + sep + date.substring(6,8); break;
1595 case 4: date = '0' + date.substring(0,1) + sep + '20' + date.substring(1, 3) + sep + '0' + date.substring(3,4); break;
1596 case 5: date = date.substring(0,2) + sep + '20' + date.substring(2, 4) + sep + '0' + date.substring(4,5); break;
1597 case 6: date = date.substring(0,2) + sep + '20' + date.substring(2, 4) + sep + date.substring(4,6); break;
1598 case 8: date = date.substring(0,2) + sep + date.substring(2, 6) + sep + date.substring(6,8); break;
1602 case 4: date = '0' + date.substring(0,1) + sep + '0' + date.substring(1, 2) + sep + '20' + date.substring(2,4); break;
1603 case 5: date = '0' + date.substring(0,1) + sep + date.substring(1, 3) + sep + '20' + date.substring(3,5); break;
1604 case 6: date = date.substring(0,2) + sep + date.substring(2, 4) + sep + '20' + date.substring(4,6); break;
1605 case 8: date = date.substring(0,2) + sep + date.substring(2, 4) + sep + date.substring(4,8); break;
1610 date = date.replace(/[\/-]/g, sep);
1614 // find obj's position
1615 function findElementPos(obj) {
1618 if (obj.offsetParent) {
1619 while (obj.offsetParent) {
1620 x += obj.offsetLeft;
1622 obj = obj.offsetParent;
1624 }//if offsetParent exists
1625 else if (obj.x && obj.y) {
1629 return new coordinate(x, y);
1633 // get dimensions of the browser window
1634 function getClientDim() {
1635 var nwX, nwY, seX, seY;
1636 if (self.pageYOffset) // all except Explorer
1638 nwX = self.pageXOffset;
1639 seX = self.innerWidth + nwX;
1640 nwY = self.pageYOffset;
1641 seY = self.innerHeight + nwY;
1643 else if (document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
1645 nwX = document.documentElement.scrollLeft;
1646 seX = document.documentElement.clientWidth + nwX;
1647 nwY = document.documentElement.scrollTop;
1648 seY = document.documentElement.clientHeight + nwY;
1650 else if (document.body) // all other Explorers
1652 nwX = document.body.scrollLeft;
1653 seX = document.body.clientWidth + nwX;
1654 nwY = document.body.scrollTop;
1655 seY = document.body.clientHeight + nwY;
1657 return {'nw' : new coordinate(nwX, nwY), 'se' : new coordinate(seX, seY)};
1661 * stop propagation on events
1663 function freezeEvent(e) {
1665 if (e.preventDefault) e.preventDefault();
1666 e.returnValue = false;
1667 e.cancelBubble = true;
1668 if (e.stopPropagation) e.stopPropagation();
1677 function coordinate(_x, _y) {
1686 return new position(this.x + rh.x, this.y + rh.y);
1690 return new position(this.x + rh.x, this.y + rh.y);
1694 // sends theForm via AJAX and fills in the theDiv
1695 function sendAndRetrieve(theForm, theDiv, loadingStr) {
1696 function success(data) {
1697 document.getElementById(theDiv).innerHTML = data.responseText;
1698 ajaxStatus.hideStatus();
1700 if(typeof loadingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
1701 ajaxStatus.showStatus(loadingStr);
1702 oForm = new YAHOO.util.Element(theForm);
1703 if ( oForm.get('enctype') && oForm.get('enctype') == 'multipart/form-data' ) {
1704 // the second argument is true to indicate file upload.
1705 YAHOO.util.Connect.setForm(theForm, true);
1706 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {upload: success, failure: success});
1708 YAHOO.util.Connect.setForm(theForm);
1709 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
1714 //save the form and redirect
1715 function sendAndRedirect(theForm, loadingStr, redirect_location) {
1716 function success(data) {
1717 if(redirect_location){
1718 location.href=redirect_location;
1720 ajaxStatus.hideStatus();
1722 if(typeof loadingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
1723 ajaxStatus.showStatus(loadingStr);
1724 oForm = new YAHOO.util.Element(theForm);
1725 if ( oForm.get('enctype') && oForm.get('enctype') == 'multipart/form-data' ) {
1726 // the second argument is true to indicate file upload.
1727 YAHOO.util.Connect.setForm(theForm, true);
1728 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {upload: success, failure: success});
1730 YAHOO.util.Connect.setForm(theForm);
1731 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
1736 function saveForm(theForm, theDiv, loadingStr) {
1737 if(check_form(theForm)){
1738 for(i = 0; i < ajaxFormArray.length; i++){
1739 if(ajaxFormArray[i] == theForm){
1740 ajaxFormArray.splice(i, 1);
1743 return sendAndRetrieve(theForm, loadingStr, theDiv);
1749 // Builds a "snapshot" of the form, so we can use it to see if someone has changed it.
1750 function snapshotForm(theForm) {
1751 var snapshotTxt = '';
1752 var elemList = theForm.elements;
1756 for( var i = 0; i < elemList.length ; i++ ) {
1758 if ( typeof(elem.type) == 'undefined' ) {
1762 elemType = elem.type.toLowerCase();
1764 snapshotTxt = snapshotTxt + elem.name;
1766 if ( elemType == 'text' || elemType == 'textarea' || elemType == 'password' ) {
1767 snapshotTxt = snapshotTxt + elem.value;
1769 else if ( elemType == 'select' || elemType == 'select-one' || elemType == 'select-multiple' ) {
1770 var optionList = elem.options;
1771 for ( var ii = 0 ; ii < optionList.length ; ii++ ) {
1772 if ( optionList[ii].selected ) {
1773 snapshotTxt = snapshotTxt + optionList[ii].value;
1777 else if ( elemType == 'radio' || elemType == 'checkbox' ) {
1778 if ( elem.selected ) {
1779 snapshotTxt = snapshotTxt + 'checked';
1782 else if ( elemType == 'hidden' ) {
1783 snapshotTxt = snapshotTxt + elem.value;
1790 function initEditView(theForm) {
1791 if (SUGAR.util.ajaxCallInProgress()) {
1792 window.setTimeout(function(){initEditView(theForm);}, 100);
1796 if ( theForm == null || theForm.id == null ) {
1797 // Not much we can do here.
1801 // we don't need to check if the data is changed in the search popup
1802 if (theForm.id == 'popup_query_form' || theForm.id == 'MassUpdate') {
1805 if ( typeof editViewSnapshots == 'undefined' || editViewSnapshots == null ) {
1806 editViewSnapshots = new Object();
1808 if ( typeof SUGAR.loadedForms == 'undefined' || SUGAR.loadedForms == null) {
1809 SUGAR.loadedForms = new Object();
1812 editViewSnapshots[theForm.id] = snapshotForm(theForm);
1813 SUGAR.loadedForms[theForm.id] = true;
1816 function onUnloadEditView(theForm) {
1818 var dataHasChanged = false;
1819 if ( typeof editViewSnapshots == 'undefined' ) {
1820 // No snapshots, move along
1824 if ( typeof theForm == 'undefined' ) {
1825 // Need to check all editViewSnapshots
1826 for ( var idx in editViewSnapshots ) {
1828 theForm = document.getElementById(idx);
1829 // console.log('DEBUG: Checking all forms '+theForm.id);
1830 if ( theForm == null
1831 || typeof editViewSnapshots[theForm.id] == 'undefined'
1832 || editViewSnapshots[theForm.id] == null
1833 || !SUGAR.loadedForms[theForm.id]) {
1837 var snap = snapshotForm(theForm);
1838 if ( editViewSnapshots[theForm.id] != snap ) {
1839 dataHasChanged = true;
1843 // Just need to check a single form for changes
1844 if ( editViewSnapshots == null || typeof theForm.id == 'undefined' || typeof editViewSnapshots[theForm.id] == 'undefined' || editViewSnapshots[theForm.id] == null ) {
1848 // console.log('DEBUG: Checking one form '+theForm.id);
1849 if ( editViewSnapshots[theForm.id] != snapshotForm(theForm) ) {
1850 // Data has changed.
1851 dataHasChanged = true;
1855 if ( dataHasChanged == true ) {
1856 return SUGAR.language.get('app_strings','WARN_UNSAVED_CHANGES');
1863 function disableOnUnloadEditView(theForm) {
1864 // If you don't pass anything in, it disables all checking
1865 if ( typeof theForm == 'undefined' || typeof editViewSnapshots == 'undefined' || theForm == null || editViewSnapshots == null) {
1866 window.onbeforeunload = null;
1867 editViewSnapshots = null;
1869 // console.log('DEBUG: Disabling all edit view checks');
1872 // Otherwise, it just disables it for this form
1873 if ( typeof(theForm.id) != 'undefined' && typeof(editViewSnapshots[theForm.id]) != 'undefined' ) {
1874 editViewSnapshots[theForm.id] = null;
1877 // console.log('DEBUG : Disabling just checks for '+theForm.id);
1883 * save some forms using an ajax call
1884 * theForms - the ids of all of theh forms to save
1885 * savingStr - the string to display when saving the form
1886 * completeStr - the string to display when the form has been saved
1888 function saveForms( savingStr, completeStr) {
1890 theForms = ajaxFormArray;
1891 function success(data) {
1892 var theForm = document.getElementById(ajaxFormArray[0]);
1893 document.getElementById('multiedit_'+theForm.id).innerHTML = data.responseText;
1894 var saveAllButton = document.getElementById('ajaxsaveall');
1895 ajaxFormArray.splice(index, 1);
1896 if(saveAllButton && ajaxFormArray.length <= 1){
1897 saveAllButton.style.visibility = 'hidden';
1900 if(index == theForms.length){
1901 ajaxStatus.showStatus(completeStr);
1902 window.setTimeout('ajaxStatus.hideStatus();', 2000);
1904 saveAllButton.style.visibility = 'hidden';
1909 if(typeof savingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
1910 ajaxStatus.showStatus(savingStr);
1912 //loop through the forms saving each one
1913 for(i = 0; i < theForms.length; i++){
1914 var theForm = document.getElementById(theForms[i]);
1915 if(check_form(theForm.id)){
1916 theForm.action.value='AjaxFormSave';
1917 YAHOO.util.Connect.setForm(theForm);
1918 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
1920 ajaxStatus.hideStatus();
1922 lastSubmitTime = lastSubmitTime-2000;
1927 // -- start sugarListView class
1928 // js functions used for ListView
1929 function sugarListView() {
1933 sugarListView.prototype.confirm_action = function(del) {
1935 return confirm( SUGAR.language.get('app_strings', 'NTC_DELETE_CONFIRMATION_NUM') + sugarListView.get_num_selected() + SUGAR.language.get('app_strings', 'NTC_DELETE_SELECTED_RECORDS'));
1938 return confirm( SUGAR.language.get('app_strings', 'NTC_UPDATE_CONFIRMATION_NUM') + sugarListView.get_num_selected() + SUGAR.language.get('app_strings', 'NTC_DELETE_SELECTED_RECORDS'));
1942 sugarListView.get_num_selected = function () {
1943 var selectCount = $("input[name='selectCount[]']:first");
1944 if(selectCount.length > 0)
1945 return parseInt(selectCount.val().replace("+", ""));
1949 sugarListView.update_count = function(count, add) {
1950 if(typeof document.MassUpdate != 'undefined') {
1951 the_form = document.MassUpdate;
1952 for(var wp = 0; wp < the_form.elements.length; wp++) {
1953 if(typeof the_form.elements[wp].name != 'undefined' && the_form.elements[wp].name == 'selectCount[]') {
1955 the_form.elements[wp].value = parseInt(the_form.elements[wp].value,10) + count;
1956 if (the_form.select_entire_list.value == 1 && the_form.show_plus.value) {
1957 the_form.elements[wp].value += '+';
1960 if (the_form.select_entire_list.value == 1 && the_form.show_plus.value) {
1961 the_form.elements[wp].value = count + '+';
1963 the_form.elements[wp].value = count;
1970 sugarListView.prototype.use_external_mail_client = function(no_record_txt, module) {
1971 selected_records = sugarListView.get_checks_count();
1972 if(selected_records <1) {
1973 alert(no_record_txt);
1977 if (document.MassUpdate.select_entire_list.value == 1) {
1978 if (totalCount > 10) {
1979 alert(totalCountError);
1984 else if (document.MassUpdate.massall.checked == true)
1988 sugarListView.get_checks();
1990 if(select) { // use selected items
1991 ids = document.MassUpdate.uid.value;
1993 else { // use current page
1994 inputs = document.MassUpdate.elements;
1996 for(i = 0; i < inputs.length; i++) {
1997 if(inputs[i].name == 'mass[]' && inputs[i].checked && typeof(inputs[i].value) != 'function') {
1998 ar.push(inputs[i].value);
2003 YAHOO.util.Connect.asyncRequest("POST", "index.php?", {
2004 success: this.use_external_mail_client_callback
2005 }, SUGAR.util.paramsToUrl({
2008 listViewExternalClient: 1,
2009 action_module: module,
2017 sugarListView.prototype.use_external_mail_client_callback = function(o)
2020 location.href = 'mailto:' + o.responseText;
2023 sugarListView.prototype.send_form_for_emails = function(select, currentModule, action, no_record_txt,action_module,totalCount, totalCountError) {
2024 if ( typeof(SUGAR.config.email_sugarclient_listviewmaxselect) != 'undefined' ) {
2028 maxCount = SUGAR.config.email_sugarclient_listviewmaxselect;
2031 if (document.MassUpdate.select_entire_list.value == 1) {
2032 if (totalCount > maxCount) {
2033 alert(totalCountError);
2038 else if (document.MassUpdate.massall.checked == true)
2043 sugarListView.get_checks();
2044 // create new form to post (can't access action property of MassUpdate form due to action input)
2045 var newForm = document.createElement('form');
2046 newForm.method = 'post';
2047 newForm.action = action;
2048 newForm.name = 'newForm';
2049 newForm.id = 'newForm';
2050 var uidTa = document.createElement('textarea');
2052 uidTa.style.display = 'none';
2054 if(select) { // use selected items
2055 uidTa.value = document.MassUpdate.uid.value;
2057 else { // use current page
2058 inputs = document.MassUpdate.elements;
2060 for(i = 0; i < inputs.length; i++) {
2061 if(inputs[i].name == 'mass[]' && inputs[i].checked && typeof(inputs[i].value) != 'function') {
2062 ar.push(inputs[i].value);
2065 uidTa.value = ar.join(',');
2068 if(uidTa.value == '') {
2069 alert(no_record_txt);
2073 var selectedArray = uidTa.value.split(",");
2074 if(selectedArray.length > maxCount) {
2075 alert(totalCountError);
2078 newForm.appendChild(uidTa);
2080 var moduleInput = document.createElement('input');
2081 moduleInput.name = 'module';
2082 moduleInput.type = 'hidden';
2083 moduleInput.value = currentModule;
2084 newForm.appendChild(moduleInput);
2086 var actionInput = document.createElement('input');
2087 actionInput.name = 'action';
2088 actionInput.type = 'hidden';
2089 actionInput.value = 'Compose';
2090 newForm.appendChild(actionInput);
2092 if (typeof action_module != 'undefined' && action_module!= '') {
2093 var actionModule = document.createElement('input');
2094 actionModule.name = 'action_module';
2095 actionModule.type = 'hidden';
2096 actionModule.value = action_module;
2097 newForm.appendChild(actionModule);
2099 //return_info must follow this pattern."&return_module=Accounts&return_action=index"
2100 if (typeof return_info!= 'undefined' && return_info != '') {
2101 var params= return_info.split('&');
2102 if (params.length > 0) {
2103 for (var i=0;i< params.length;i++) {
2104 if (params[i].length > 0) {
2105 var param_nv=params[i].split('=');
2106 if (param_nv.length==2){
2107 returnModule = document.createElement('input');
2108 returnModule.name = param_nv[0];
2109 returnModule.type = 'hidden';
2110 returnModule.value = param_nv[1];
2111 newForm.appendChild(returnModule);
2118 var isAjaxCall = document.createElement('input');
2119 isAjaxCall.name = 'ajaxCall';
2120 isAjaxCall.type = 'hidden';
2121 isAjaxCall.value = true;
2122 newForm.appendChild(isAjaxCall);
2124 var isListView = document.createElement('input');
2125 isListView.name = 'ListView';
2126 isListView.type = 'hidden';
2127 isListView.value = true;
2128 newForm.appendChild(isListView);
2130 var toPdf = document.createElement('input');
2131 toPdf.name = 'to_pdf';
2132 toPdf.type = 'hidden';
2134 newForm.appendChild(toPdf);
2136 //Grab the Quick Compose package for the listview
2137 YAHOO.util.Connect.setForm(newForm);
2140 success: function(o) {
2141 var resp = YAHOO.lang.JSON.parse(o.responseText);
2142 var quickComposePackage = new Object();
2143 quickComposePackage.composePackage = resp;
2144 quickComposePackage.fullComposeUrl = 'index.php?module=Emails&action=Compose&ListView=true' +
2145 '&uid=' + uidTa.value + '&action_module=' + action_module;
2147 SUGAR.quickCompose.init(quickComposePackage);
2151 YAHOO.util.Connect.asyncRequest('POST','index.php', callback,null);
2153 // awu Bug 18624: Fixing issue where a canceled Export and unselect of row will persist the uid field, clear the field
2154 document.MassUpdate.uid.value = '';
2159 sugarListView.prototype.send_form = function(select, currentModule, action, no_record_txt,action_module,return_info) {
2160 if (document.MassUpdate.select_entire_list.value == 1) {
2162 if(sugarListView.get_checks_count() < 1) {
2163 alert(no_record_txt);
2168 if ( action.indexOf('?') != -1 )
2169 href += '&module=' + currentModule;
2171 href += '?module=' + currentModule;
2174 href += return_info;
2175 var newForm = document.createElement('form');
2176 newForm.method = 'post';
2177 newForm.action = href;
2178 newForm.name = 'newForm';
2179 newForm.id = 'newForm';
2180 var postTa = document.createElement('textarea');
2181 postTa.name = 'current_post';
2182 postTa.value = document.MassUpdate.current_query_by_page.value;
2183 postTa.style.display = 'none';
2184 newForm.appendChild(postTa);
2185 document.MassUpdate.parentNode.appendChild(newForm);
2189 else if (document.MassUpdate.massall.checked == true)
2194 sugarListView.get_checks();
2195 // create new form to post (can't access action property of MassUpdate form due to action input)
2196 var newForm = document.createElement('form');
2197 newForm.method = 'post';
2198 newForm.action = action;
2199 newForm.name = 'newForm';
2200 newForm.id = 'newForm';
2201 var uidTa = document.createElement('textarea');
2203 uidTa.style.display = 'none';
2204 uidTa.value = document.MassUpdate.uid.value;
2206 if(uidTa.value == '') {
2207 alert(no_record_txt);
2211 newForm.appendChild(uidTa);
2213 var moduleInput = document.createElement('input');
2214 moduleInput.name = 'module';
2215 moduleInput.type = 'hidden';
2216 moduleInput.value = currentModule;
2217 newForm.appendChild(moduleInput);
2219 var actionInput = document.createElement('input');
2220 actionInput.name = 'action';
2221 actionInput.type = 'hidden';
2222 actionInput.value = 'index';
2223 newForm.appendChild(actionInput);
2225 if (typeof action_module != 'undefined' && action_module!= '') {
2226 var actionModule = document.createElement('input');
2227 actionModule.name = 'action_module';
2228 actionModule.type = 'hidden';
2229 actionModule.value = action_module;
2230 newForm.appendChild(actionModule);
2232 //return_info must follow this pattern."&return_module=Accounts&return_action=index"
2233 if (typeof return_info!= 'undefined' && return_info != '') {
2234 var params= return_info.split('&');
2235 if (params.length > 0) {
2236 for (var i=0;i< params.length;i++) {
2237 if (params[i].length > 0) {
2238 var param_nv=params[i].split('=');
2239 if (param_nv.length==2){
2240 returnModule = document.createElement('input');
2241 returnModule.name = param_nv[0];
2242 returnModule.type = 'hidden';
2243 returnModule.value = param_nv[1];
2244 newForm.appendChild(returnModule);
2251 document.MassUpdate.parentNode.appendChild(newForm);
2254 // awu Bug 18624: Fixing issue where a canceled Export and unselect of row will persist the uid field, clear the field
2255 document.MassUpdate.uid.value = '';
2259 //return a count of checked row.
2260 sugarListView.get_checks_count = function() {
2263 if(document.MassUpdate.uid.value != '') {
2264 oldUids = document.MassUpdate.uid.value.split(',');
2265 for(uid in oldUids) {
2266 if(typeof(oldUids[uid]) != 'function') {
2267 ar[oldUids[uid]] = 1;
2271 // build associated array of uids, associated array ensures uniqueness
2272 inputs = document.MassUpdate.elements;
2273 for(i = 0; i < inputs.length; i++) {
2274 if(inputs[i].name == 'mass[]') {
2275 ar[inputs[i].value] = (inputs[i].checked) ? 1 : 0; // 0 of it is unchecked
2279 // build regular array of uids
2282 if((typeof(ar[i]) != 'function') && ar[i] == 1) {
2290 // saves the checks on the current page into the uid textarea
2291 sugarListView.get_checks = function() {
2293 if(typeof document.MassUpdate != 'undefined' ){
2294 if(document.MassUpdate.uid.value != '') {
2295 oldUids = document.MassUpdate.uid.value.split(',');
2296 for(uid in oldUids) {
2297 if(typeof(oldUids[uid]) != 'function') {
2298 ar[oldUids[uid]] = 1;
2303 // build associated array of uids, associated array ensures uniqueness
2304 inputs = document.MassUpdate.elements;
2305 for(i = 0; i < inputs.length; i++) {
2306 if(inputs[i].name == 'mass[]') {
2307 ar[inputs[i].value] = (inputs[i].checked) ? 1 : 0; // 0 of it is unchecked
2311 // build regular array of uids
2314 if(typeof(ar[i]) != 'function' && ar[i] == 1) {
2319 document.MassUpdate.uid.value = uids.join(',');
2321 if(uids.length == 0) return false; // return false if no checks to get
2322 return true; // there are saved checks
2327 sugarListView.prototype.order_checks = function(order,orderBy,moduleString){
2328 checks = sugarListView.get_checks();
2329 eval('document.MassUpdate.' + moduleString + '.value = orderBy');
2330 document.MassUpdate.lvso.value = order;
2331 if(typeof document.MassUpdate.massupdate != 'undefined') {
2332 document.MassUpdate.massupdate.value = 'false';
2335 //we must first clear the action of massupdate, change it to index
2336 document.MassUpdate.action.value = document.MassUpdate.return_action.value;
2337 document.MassUpdate.return_module.value='';
2338 document.MassUpdate.return_action.value='';
2339 document.MassUpdate.submit();
2343 sugarListView.prototype.save_checks = function(offset, moduleString) {
2344 checks = sugarListView.get_checks();
2345 if(typeof document.MassUpdate != 'undefined'){
2346 eval('document.MassUpdate.' + moduleString + '.value = offset');
2348 if(typeof document.MassUpdate.massupdate != 'undefined') {
2349 document.MassUpdate.massupdate.value = 'false';
2352 //we must first clear the action of massupdate, change it to index
2353 document.MassUpdate.action.value = document.MassUpdate.return_action.value;
2354 document.MassUpdate.return_module.value='';
2355 document.MassUpdate.return_action.value='';
2356 document.MassUpdate.submit();
2364 sugarListView.prototype.check_item = function(cb, form) {
2366 sugarListView.update_count(1, true);
2369 sugarListView.update_count(-1, true);
2370 if(typeof form != 'undefined' && form != null) {
2371 sugarListView.prototype.updateUid(cb, form);
2374 sugarListView.prototype.toggleSelected();
2377 sugarListView.prototype.toggleSelected = function() {
2379 var numSelected = sugarListView.get_num_selected();
2380 var selectedRecords = document.getElementById("selectedRecordsTop");
2381 var selectActions = document.getElementById("selectActions");
2382 var selectActionsDisabled = document.getElementById("selectActionsDisabled");
2383 if(numSelected > 0) {
2384 $(selectedRecords).removeAttr("style").addClass("show");
2385 $(".selectActionsDisabled").hide();
2386 jQuery('ul[name=selectActions]').each(function () {
2387 jQuery(this).removeAttr("style").addClass("show");
2391 $(selectedRecords).hide();
2392 $(".selectActionsDisabled").removeAttr("style").addClass("show");
2393 jQuery('ul[name=selectActions]').each(function () {
2394 jQuery(this).hide();
2400 /**#28000, remove the unselect record id from MassUpdate.uid **/
2401 sugarListView.prototype.updateUid = function(cb , form){
2402 if(form.name == 'MassUpdate' && form.uid && form.uid.value && cb.value && form.uid.value.indexOf(cb.value) != -1){
2403 if(form.uid.value.indexOf(','+cb.value)!= -1){
2404 form.uid.value = form.uid.value.replace(','+cb.value , '');
2405 }else if(form.uid.value.indexOf(cb.value + ',')!= -1){
2406 form.uid.value = form.uid.value.replace(cb.value + ',' , '');
2407 }else if(form.uid.value.indexOf(cb.value)!= -1){
2408 form.uid.value = form.uid.value.replace(cb.value , '');
2413 sugarListView.prototype.check_entire_list = function(form, field, value, list_count) {
2414 // count number of items
2416 $(document.MassUpdate.massall).each(function(){
2417 $(this).attr('checked', true).attr('disabled', true);
2419 for (i = 0; i < form.elements.length; i++) {
2420 if(form.elements[i].name == field && form.elements[i].disabled == false) {
2421 if(form.elements[i].checked != value) count++;
2422 form.elements[i].checked = value;
2423 form.elements[i].disabled = true;
2426 document.MassUpdate.select_entire_list.value = 1;
2427 sugarListView.update_count(list_count, false);
2428 sugarListView.prototype.toggleSelected();
2431 sugarListView.prototype.check_all = function(form, field, value, pageTotal) {
2432 // count number of items
2434 $(document.MassUpdate.massall).each(function(){$(this).attr('checked', value);});
2435 if (document.MassUpdate.select_entire_list &&
2436 document.MassUpdate.select_entire_list.value == 1)
2438 sugarListView.prototype.toggleSelected();
2439 $(document.MassUpdate.massall).each(function(){$(this).attr('disabled', true);});
2443 $(document.MassUpdate.massall).each(function(){$(this).attr('disabled', false);});
2445 for (i = 0; i < form.elements.length; i++) {
2446 if(form.elements[i].name == field && !(form.elements[i].disabled == true && form.elements[i].checked == false)) {
2447 form.elements[i].disabled = false;
2449 if(form.elements[i].checked != value)
2451 form.elements[i].checked = value;
2453 sugarListView.prototype.updateUid(form.elements[i], form);
2458 sugarListView.update_count(pageTotal);
2460 sugarListView.update_count(count, true);
2462 sugarListView.update_count(-1 * count, true);
2464 sugarListView.prototype.toggleSelected();
2466 sugarListView.check_all = sugarListView.prototype.check_all;
2467 sugarListView.confirm_action = sugarListView.prototype.confirm_action;
2469 sugarListView.prototype.check_boxes = function() {
2470 var inputsCount = 0;
2471 var checkedCount = 0;
2472 var existing_onload = window.onload;
2473 var theForm = document.MassUpdate;
2474 inputs_array = theForm.elements;
2476 if(typeof theForm.uid.value != 'undefined' && theForm.uid.value != "") {
2477 checked_items = theForm.uid.value.split(",");
2478 if (theForm.select_entire_list.value == 1) {
2479 document.MassUpdate.massall.disabled = true;
2480 sugarListView.prototype.toggleSelected();
2481 $("a[name=selectall]:first").click();
2484 for(var wp = 0 ; wp < inputs_array.length; wp++) {
2485 if(inputs_array[wp].name == "mass[]") {
2487 if (theForm.select_entire_list.value == 1) {
2488 inputs_array[wp].checked = true;
2489 inputs_array[wp].disabled = true;
2493 for(i in checked_items) {
2494 if(inputs_array[wp].value == checked_items[i]) {
2496 inputs_array[wp].checked = true;
2497 //Bug#52748: Total # of checked items are calculated in back-end side
2498 //sugarListView.prototype.check_item(inputs_array[wp], document.MassUpdate);
2506 for(var wp = 0 ; wp < inputs_array.length; wp++) {
2507 if(inputs_array[wp].name == "mass[]") {
2508 inputs_array[wp].checked = false;
2509 inputs_array[wp].disabled = false;
2512 if (document.MassUpdate.massall) {
2513 document.MassUpdate.massall.checked = false;
2514 document.MassUpdate.massall.disabled = false;
2516 sugarListView.update_count(0)
2518 if(checkedCount > 0 && checkedCount == inputsCount)
2519 document.MassUpdate.massall.checked = true;
2524 * This function is used in Email Template Module's listview.
2525 * It will check whether the templates are used in Campaing->EmailMarketing.
2526 * If true, it will notify user.
2528 function check_used_email_templates() {
2529 var ids = document.MassUpdate.uid.value;
2531 success:function(r) {
2532 if(r.responseText != '') {
2533 if(!confirm(SUGAR.language.get('app_strings','NTC_TEMPLATES_IS_USED') + r.responseText)) {
2537 document.MassUpdate.submit();
2541 url = "index.php?module=EmailTemplates&action=CheckDeletable&from=ListView&to_pdf=1&records="+ids;
2542 YAHOO.util.Connect.asyncRequest('POST',url, call_back,null);
2546 sugarListView.prototype.send_mass_update = function(mode, no_record_txt, del) {
2547 formValid = check_form('MassUpdate');
2548 if(!formValid && !del) return false;
2551 if (document.MassUpdate.select_entire_list &&
2552 document.MassUpdate.select_entire_list.value == 1)
2557 var ar = new Array();
2561 for(var wp = 0; wp < document.MassUpdate.elements.length; wp++) {
2562 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)+'$');
2563 //when the uid is already in document.MassUpdate.uid.value, we should not add it to ar.
2564 if(typeof document.MassUpdate.elements[wp].name != 'undefined'
2565 && document.MassUpdate.elements[wp].name == 'mass[]'
2566 && document.MassUpdate.elements[wp].checked
2567 && !reg_for_existing_uid.test(document.MassUpdate.uid.value)) {
2568 ar.push(document.MassUpdate.elements[wp].value);
2571 if(document.MassUpdate.uid.value != '') document.MassUpdate.uid.value += ',';
2572 document.MassUpdate.uid.value += ar.join(',');
2573 if(document.MassUpdate.uid.value == '') {
2574 alert(no_record_txt);
2577 if(typeof(current_admin_id)!='undefined' && document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'Users' && (document.MassUpdate.is_admin.value!='' || document.MassUpdate.status.value!='')) {
2578 var reg_for_current_admin_id = new RegExp('^'+current_admin_id+'[\s]*,|,[\s]*'+current_admin_id+'[\s]*,|,[\s]*'+current_admin_id+'$|^'+current_admin_id+'$');
2579 if(reg_for_current_admin_id.test(document.MassUpdate.uid.value)) {
2580 //if current user is admin, we should not allow massupdate the user_type and status of himself
2581 alert(SUGAR.language.get('Users','LBL_LAST_ADMIN_NOTICE'));
2587 var entireInput = document.createElement('input');
2588 entireInput.name = 'entire';
2589 entireInput.type = 'hidden';
2590 entireInput.value = 'index';
2591 document.MassUpdate.appendChild(entireInput);
2592 //confirm(no_record_txt);
2593 if(document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'Users' && (document.MassUpdate.is_admin.value!='' || document.MassUpdate.status.value!='')) {
2594 alert(SUGAR.language.get('Users','LBL_LAST_ADMIN_NOTICE'));
2600 if(!sugarListView.confirm_action(del))
2604 var deleteInput = document.createElement('input');
2605 deleteInput.name = 'Delete';
2606 deleteInput.type = 'hidden';
2607 deleteInput.value = true;
2608 document.MassUpdate.appendChild(deleteInput);
2609 if(document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'EmailTemplates') {
2610 check_used_email_templates();
2616 document.MassUpdate.submit();
2621 sugarListView.prototype.clear_all = function() {
2622 document.MassUpdate.uid.value = '';
2623 document.MassUpdate.select_entire_list.value = 0;
2624 sugarListView.check_all(document.MassUpdate, 'mass[]', false);
2625 $(document.MassUpdate.massall).each(function(){
2626 $(this).attr('checked', false).attr('disabled', false);
2628 sugarListView.update_count(0);
2629 sugarListView.prototype.toggleSelected();
2632 sListView = new sugarListView();
2633 // -- end sugarListView class
2635 // format and unformat numbers
2636 function unformatNumber(n, num_grp_sep, dec_sep) {
2637 var x=unformatNumberNoParse(n, num_grp_sep, dec_sep);
2640 return parseFloat(x);
2645 function unformatNumberNoParse(n, num_grp_sep, dec_sep) {
2646 if(typeof num_grp_sep == 'undefined' || typeof dec_sep == 'undefined') return n;
2647 n = n ? n.toString() : '';
2650 if(num_grp_sep != '')
2652 num_grp_sep_re = new RegExp('\\'+num_grp_sep, 'g');
2653 n = n.replace(num_grp_sep_re, '');
2656 n = n.replace(dec_sep, '.');
2658 if(typeof CurrencySymbols != 'undefined') {
2659 // Need to strip out the currency symbols from the start.
2660 for ( var idx in CurrencySymbols ) {
2661 n = n.replace(CurrencySymbols[idx], '');
2669 // round parameter can be negative for decimal, precision has to be postive
2670 function formatNumber(n, num_grp_sep, dec_sep, round, precision) {
2671 if(typeof num_grp_sep == 'undefined' || typeof dec_sep == 'undefined') return n;
2672 n = n ? n.toString() : '';
2673 if(n.split) n = n.split('.');
2676 if(n.length > 2) return n.join('.'); // that's not a num!
2678 if(typeof round != 'undefined') {
2679 if(round > 0 && n.length > 1) { // round to decimal
2680 n[1] = parseFloat('0.' + n[1]);
2681 n[1] = Math.round(n[1] * Math.pow(10, round)) / Math.pow(10, round);
2682 n[1] = n[1].toString().split('.')[1];
2684 if(round <= 0) { // round to whole number
2685 n[0] = Math.round(parseInt(n[0],10) * Math.pow(10, round)) / Math.pow(10, round);
2690 if(typeof precision != 'undefined' && precision >= 0) {
2691 if(n.length > 1 && typeof n[1] != 'undefined') n[1] = n[1].substring(0, precision); // cut off precision
2693 if(n[1].length < precision) {
2694 for(var wp = n[1].length; wp < precision; wp++) n[1] += '0';
2698 regex = /(\d+)(\d{3})/;
2699 while(num_grp_sep != '' && regex.test(n[0])) n[0] = n[0].toString().replace(regex, '$1' + num_grp_sep + '$2');
2700 return n[0] + (n.length > 1 && n[1] != '' ? dec_sep + n[1] : '');
2703 // --- begin ajax status class
2704 SUGAR.ajaxStatusClass = function() {};
2705 SUGAR.ajaxStatusClass.prototype.statusDiv = null;
2706 SUGAR.ajaxStatusClass.prototype.oldOnScroll = null;
2707 SUGAR.ajaxStatusClass.prototype.shown = false; // state of the status window
2709 // reposition the status div, top and centered
2710 SUGAR.ajaxStatusClass.prototype.positionStatus = function() {
2711 //this.statusDiv.style.top = document.body.scrollTop + 8 + 'px';
2712 statusDivRegion = YAHOO.util.Dom.getRegion(this.statusDiv);
2713 statusDivWidth = statusDivRegion.right - statusDivRegion.left;
2714 this.statusDiv.style.left = YAHOO.util.Dom.getViewportWidth() / 2 - statusDivWidth / 2 + 'px';
2717 // private func, create the status div
2718 SUGAR.ajaxStatusClass.prototype.createStatus = function(text) {
2719 statusDiv = document.createElement('div');
2720 statusDiv.className = 'dataLabel';
2721 statusDiv.id = 'ajaxStatusDiv';
2722 document.body.appendChild(statusDiv);
2723 this.statusDiv = document.getElementById('ajaxStatusDiv');
2726 // public - show the status div with text
2727 SUGAR.ajaxStatusClass.prototype.showStatus = function(text) {
2728 if(!this.statusDiv) {
2729 this.createStatus(text);
2732 this.statusDiv.style.display = '';
2734 this.statusDiv.innerHTML = ' <b>' + text + '</b> ';
2735 this.positionStatus();
2738 this.statusDiv.style.display = '';
2739 if(window.onscroll) this.oldOnScroll = window.onscroll; // save onScroll
2740 window.onscroll = this.positionStatus;
2745 SUGAR.ajaxStatusClass.prototype.hideStatus = function(text) {
2746 if(!this.shown) return;
2748 if(this.oldOnScroll) window.onscroll = this.oldOnScroll;
2749 else window.onscroll = '';
2750 this.statusDiv.style.display = 'none';
2753 SUGAR.ajaxStatusClass.prototype.flashStatus = function(text, time){
2754 this.showStatus(text);
2755 window.setTimeout('ajaxStatus.hideStatus();', time);
2759 var ajaxStatus = new SUGAR.ajaxStatusClass();
2760 // --- end ajax status class
2763 * Unified Search Advanced - for global search
2765 SUGAR.unifiedSearchAdvanced = function() {
2775 SUGAR.unifiedSearchAdvanced.usa_div = document.getElementById('unified_search_advanced_div');
2776 SUGAR.unifiedSearchAdvanced.usa_img = document.getElementById('unified_search_advanced_img');
2778 if(!SUGAR.unifiedSearchAdvanced.usa_div || !SUGAR.unifiedSearchAdvanced.usa_img) return;
2779 var attributes = { height: { to: 300 } };
2780 SUGAR.unifiedSearchAdvanced.anim_open = new YAHOO.util.Anim('unified_search_advanced_div', attributes );
2781 SUGAR.unifiedSearchAdvanced.anim_open.duration = 0.75;
2782 SUGAR.unifiedSearchAdvanced.anim_close = new YAHOO.util.Anim('unified_search_advanced_div', { height: {to: 0} } );
2783 SUGAR.unifiedSearchAdvanced.anim_close.duration = 0.75;
2784 //SUGAR.unifiedSearchAdvanced.anim_close.onComplete.subscribe(function() {SUGAR.unifiedSearchAdvanced.usa_div.style.display = 'none'});
2786 SUGAR.unifiedSearchAdvanced.usa_img._x = YAHOO.util.Dom.getX(SUGAR.unifiedSearchAdvanced.usa_img);
2787 SUGAR.unifiedSearchAdvanced.usa_img._y = YAHOO.util.Dom.getY(SUGAR.unifiedSearchAdvanced.usa_img);
2790 SUGAR.unifiedSearchAdvanced.usa_open = false;
2791 SUGAR.unifiedSearchAdvanced.usa_content = null;
2793 YAHOO.util.Event.addListener('unified_search_advanced_img', 'click', SUGAR.unifiedSearchAdvanced.get_content);
2796 get_content: function(e)
2798 query_string = trim(document.getElementById('query_string').value);
2799 if(query_string != '')
2801 window.location.href = 'index.php?module=Home&action=UnifiedSearch&query_string=' + query_string;
2803 window.location.href = 'index.php?module=Home&action=UnifiedSearch&form_only=true';
2807 animate: function(data) {
2808 ajaxStatus.hideStatus();
2811 SUGAR.unifiedSearchAdvanced.usa_content = data.responseText;
2812 SUGAR.unifiedSearchAdvanced.usa_div.innerHTML = SUGAR.unifiedSearchAdvanced.usa_content;
2814 if(SUGAR.unifiedSearchAdvanced.usa_open) {
2815 document.UnifiedSearch.advanced.value = 'false';
2816 SUGAR.unifiedSearchAdvanced.anim_close.animate();
2819 document.UnifiedSearch.advanced.value = 'true';
2820 SUGAR.unifiedSearchAdvanced.usa_div.style.display = '';
2821 YAHOO.util.Dom.setX(SUGAR.unifiedSearchAdvanced.usa_div, SUGAR.unifiedSearchAdvanced.usa_img._x - 90);
2822 YAHOO.util.Dom.setY(SUGAR.unifiedSearchAdvanced.usa_div, SUGAR.unifiedSearchAdvanced.usa_img._y + 15);
2823 SUGAR.unifiedSearchAdvanced.anim_open.animate();
2825 SUGAR.unifiedSearchAdvanced.usa_open = !SUGAR.unifiedSearchAdvanced.usa_open;
2830 checkUsaAdvanced: function() {
2831 if(document.UnifiedSearch.advanced.value == 'true') {
2832 document.UnifiedSearchAdvanced.query_string.value = document.UnifiedSearch.query_string.value;
2833 document.UnifiedSearchAdvanced.submit();
2840 if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.unifiedSearchAdvanced.init);
2845 * Toggles the header
2847 toggleHeader : function() {
2848 var h = document.getElementById('header');
2852 if(h.style.display == 'none') {
2853 h.style.display = '';
2855 h.style.display = 'none';
2859 alert(SUGAR.language.get("app_strings", "ERR_NO_HEADER_ID"));
2866 * General Sugar Utils
2868 SUGAR.util = function () {
2869 var additionalDetailsCache;
2870 var additionalDetailsCalls;
2871 var additionalDetailsRpcCall;
2874 getAndRemove : function (el) {
2875 if (YAHOO && YAHOO.util && YAHOO.util.Dom)
2876 el = YAHOO.util.Dom.get(el);
2877 else if (typeof (el) == "string")
2878 el = document.getElementById(el);
2879 if (el && el.parentNode)
2880 el.parentNode.removeChild(el);
2884 paramsToUrl : function (params) {
2886 for (var i in params)
2888 if (params.hasOwnProperty(i))
2890 parts.push(encodeURIComponent(i) + '=' + encodeURIComponent(params[i]));
2893 return parts.join("&")+"&";
2895 // Evaluates a script in a global context
2896 // Workarounds based on findings by Jim Driscoll
2897 // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
2898 globalEval: function( data ) {
2899 var rnotwhite = /\S/;
2900 if ( data && rnotwhite.test( data ) ) {
2901 // We use execScript on Internet Explorer
2902 // We use an anonymous function so that context is window
2903 // rather than jQuery in Firefox
2904 ( window.execScript || function( data ) {
2905 window[ "eval" ].call( window, data );
2909 evalScript:function(text){
2911 var waitUntilLoaded = function(){
2912 SUGAR.evalScript_waitCount--;
2913 if (SUGAR.evalScript_waitCount == 0) {
2914 var headElem = document.getElementsByTagName('head')[0];
2915 for ( var i = 0; i < SUGAR.evalScript_evalElem.length; i++) {
2916 var tmpElem = document.createElement('script');
2917 tmpElem.type = 'text/javascript';
2918 tmpElem.text = SUGAR.evalScript_evalElem[i];
2919 headElem.appendChild(tmpElem);
2924 var tmpElem = document.createElement('div');
2925 tmpElem.innerHTML = text;
2926 var results = tmpElem.getElementsByTagName('script');
2927 if (results == null) {
2928 // No scripts found, bail out
2932 var headElem = document.getElementsByTagName('head')[0];
2934 SUGAR.evalScript_waitCount = 0;
2935 SUGAR.evalScript_evalElem = new Array();
2936 for (var i = 0; i < results.length; i++) {
2937 if (typeof(results[i]) != 'object') {
2940 tmpElem = document.createElement('script');
2941 tmpElem.type = 'text/javascript';
2942 if (results[i].src != null && results[i].src != '') {
2943 tmpElem.src = results[i].src;
2945 // Need to defer execution of these scripts until the
2946 // required javascript files are fully loaded
2947 SUGAR.evalScript_evalElem[SUGAR.evalScript_evalElem.length] = results[i].text;
2950 tmpElem.addEventListener('load', waitUntilLoaded);
2951 SUGAR.evalScript_waitCount++;
2952 headElem.appendChild(tmpElem);
2954 // Add some code to handle pages without any external scripts
2955 SUGAR.evalScript_waitCount++;
2958 // Don't try and process things the IE way
2962 var objRegex = /<\s*script([^>]*)>((.|\s|\v|\0)*?)<\s*\/script\s*>/igm;
2964 var result = objRegex.exec(text);
2965 while(result && result.index > lastIndex){
2966 lastIndex = result.index
2968 // Bug #49205 : Subpanels fail to load when selecting subpanel tab
2969 // Change approach to handle javascripts included to body of ajax response.
2970 // To load & run javascripts and inline javascript in correct order load them as synchronous requests
2971 // JQuery library uses this approach to eval scripts
2972 if(result[1].indexOf("src=") > -1){
2973 var srcRegex = /.*src=['"]([a-zA-Z0-9_\-\&\/\.\?=:-]*)['"].*/igm;
2974 var srcResult = result[1].replace(srcRegex, '$1');
2976 // Check is ulr cross domain or not
2977 var r1 = /:\/\//igm;
2978 if ( r1.test(srcResult) && srcResult.indexOf(window.location.hostname) == -1 )
2980 // if script is cross domain it cannot be loaded via ajax request
2981 // try load script asynchronous by creating script element in the body
2982 // YUI 3.3 doesn't allow load scrips synchronously
2984 YUI().use('get', function (Y)
2986 var url = srcResult;
2987 Y.Get.script(srcResult,
2990 onSuccess : function(o) { },
2991 onFailure: function(o) { },
2992 onTimeout: function(o) { }
2995 // TODO: for YUI 3.5 - load scripts as script object synchronous
2997 YUI().use('get', function (Y) {
2998 var url = srcResult;
2999 Y.Get.js([{url: url, async: false}], function (err) {});
3005 // Bug #49205 : Subpanels fail to load when selecting subpanel tab
3006 // Create a YUI instance using the io-base module.
3007 (function (srcResult) {
3008 YUI().use("io-base",function(Y)
3015 success:function(transactionid,response,arguments)
3017 SUGAR.util.globalEval(response.responseText);
3021 // Call synchronous request to load javascript content
3022 // restonse will be processed in success function
3023 response=Y.io(srcResult,cfg);
3028 // Bug #49205 : Subpanels fail to load when selecting subpanel tab
3029 // execute script in global context
3030 // Bug #57288 : don't eval with html comment-out script; that causes syntax error in IE
3031 var srcRegex = /<!--([\s\S]*?)-->/;
3032 var srcResult = srcRegex.exec(result[2]);
3033 if (srcResult && srcResult.index > -1)
3035 SUGAR.util.globalEval(srcResult[1]);
3039 SUGAR.util.globalEval(result[2]);
3044 if(typeof(console) != "undefined" && typeof(console.log) == "function")
3046 console.log("error adding script");
3048 console.log(result);
3051 result = objRegex.exec(text);
3055 * Gets the sidebar object
3056 * @return object pointer to the sidebar element
3058 getLeftColObj: function() {
3059 leftColObj = document.getElementById('leftCol');
3060 while(leftColObj.nodeName != 'TABLE') {
3061 leftColObj = leftColObj.firstChild;
3063 leftColTable = leftColObj;
3064 leftColTd = leftColTable.getElementsByTagName('td')[0];
3065 leftColTdRegion = YAHOO.util.Dom.getRegion(leftColTd);
3066 leftColTd.style.width = (leftColTdRegion.right - leftColTdRegion.left) + 'px';
3071 * Fills the shortcut menu placeholders w/ actual content
3072 * Call this on load event
3074 * @param shortcutContent Array array of content to fill in
3076 fillShortcuts: function(e, shortcutContent) {
3079 // don't do this if leftCol isn't available
3080 if (document.getElementById('leftCol') == undefined) { return; }
3082 spans = document.getElementById('leftCol').getElementsByTagName('span');
3083 hideCol = document.getElementById('HideMenu').getElementsByTagName('span');
3084 w = spans.length + 1;
3086 spans[w] = hideCol[i];
3089 for(je in shortcutContent) {
3091 if(typeof spans[wp].innerHTML != 'undefined' && spans[wp].innerHTML == ('wp_shortcut_fill_' + je)) {
3092 if(typeof spans[wp].parentNode.parentNode == 'object') {
3093 if(typeof spans[wp].parentNode.parentNode.onclick != 'undefined') {
3094 spans[wp].parentNode.parentNode.onclick = null;
3096 // If the wp_shortcut span is contained by an A tag, replace the A with a DIV.
3097 if(spans[wp].parentNode.tagName == 'A' && !isIE) {
3098 var newDiv = document.createElement('DIV');
3099 var parentAnchor = spans[wp].parentNode;
3101 spans[wp].parentNode.parentNode.style.display = 'none';
3103 // Copy styles over to the new container div
3104 if(window.getComputedStyle) {
3105 var parentStyle = window.getComputedStyle(parentAnchor, '');
3106 for(var styleName in parentStyle) {
3107 if(typeof parentStyle[styleName] != 'function'
3108 && styleName != 'display'
3109 && styleName != 'borderWidth'
3110 && styleName != 'visibility') {
3112 newDiv.style[styleName] = parentStyle[styleName];
3114 // Catches .length and .parentRule, and others
3120 // Replace the A with the DIV
3121 newDiv.appendChild(spans[wp]);
3122 parentAnchor.parentNode.replaceChild(newDiv, parentAnchor);
3124 spans[wp].parentNode.parentNode.style.display = '';
3127 spans[wp].innerHTML = shortcutContent[je]; // fill w/ content
3128 if(spans[wp].style) spans[wp].style.display = '';
3134 * Make an AJAX request.
3136 * @param url string resource to load
3137 * @param theDiv string id of element to insert loaded data into
3138 * @param postForm string if set, a POST request will be made to resource specified by url using the form named by postForm
3139 * @param callback string name of function to invoke after HTTP response is recieved
3140 * @param callbackParam any parameter to pass to callback when invoked
3141 * @param appendMode bool if true, HTTP response will be appended to the contents of theDiv, or else contents will be overriten.
3143 retrieveAndFill: function(url, theDiv, postForm, callback, callbackParam, appendMode) {
3144 if(typeof theDiv == 'string') {
3146 theDiv = document.getElementById(theDiv);
3153 var success = function(data) {
3154 if (typeof theDiv != 'undefined' && theDiv != null)
3157 if (typeof appendMode != 'undefined' && appendMode)
3159 theDiv.insertAdjacentHTML('beforeend', data.responseText);
3163 theDiv.innerHTML = data.responseText;
3170 if (typeof callback != 'undefined' && callback != null) callback(callbackParam);
3173 if(typeof postForm == 'undefined' || postForm == null) {
3174 var cObj = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
3177 YAHOO.util.Connect.setForm(postForm);
3178 var cObj = YAHOO.util.Connect.asyncRequest('POST', url, {success: success, failure: success});
3181 checkMaxLength: function() { // modified from http://www.quirksmode.org/dom/maxlength.html
3182 var maxLength = this.getAttribute('maxlength');
3183 var currentLength = this.value.length;
3184 if (currentLength > maxLength) {
3185 this.value = this.value.substring(0, maxLength);
3190 * Adds maxlength attribute to textareas
3192 setMaxLength: function() { // modified from http://www.quirksmode.org/dom/maxlength.html
3193 var x = document.getElementsByTagName('textarea');
3194 for (var i=0;i<x.length;i++) {
3195 if (x[i].getAttribute('maxlength')) {
3196 x[i].onkeyup = x[i].onchange = SUGAR.util.checkMaxLength;
3203 * Renders Query UI Help Dialog
3205 showHelpTips: function(el,helpText,myPos,atPos,id) {
3206 if(myPos == undefined || myPos == "") {
3209 if(atPos == undefined || atPos == "") {
3210 atPos = "right top";
3213 var pos = $(el).offset(),
3214 ofWidth = $(el).width(),
3215 elmId = id || 'helpTip' + pos.left + '_' + ofWidth,
3216 $dialog = elmId ? ( $("#"+elmId).length > 0 ? $("#"+elmId) : $('<div></div>').attr("id", elmId) ) : $('<div></div>');
3217 $dialog.html(helpText)
3220 title: SUGAR.language.get('app_strings', 'LBL_HELP'),
3229 var width = $dialog.dialog( "option", "width" );
3231 if((pos.left + ofWidth) - 40 < width) {
3232 $dialog.dialog("option","position",{my: 'left top',at: 'right top',of: $(el)}) ;
3234 $dialog.dialog('open');
3235 $(".ui-dialog").appendTo("#content");
3239 getStaticAdditionalDetails: function(el, body, caption, show_buttons) {
3240 if(typeof show_buttons == "undefined") {
3241 show_buttons = false;
3244 $(".ui-dialog").find(".open").dialog("close");
3246 var $dialog = $('<div class="open"></div>')
3260 $(".ui-dialog").find('.ui-dialog-titlebar-close').css("display","none");
3261 $(".ui-dialog").find('.ui-dialog-title').css("width","100%");
3265 var width = $dialog.dialog( "option", "width" );
3266 var pos = $(el).offset();
3267 var ofWidth = $(el).width();
3269 if((pos.left + ofWidth) - 40 < width) {
3270 $dialog.dialog("option","position",{my: 'left top',at: 'right top',of: $(el)}) ;
3273 $dialog.dialog('open');
3274 $(".ui-dialog").appendTo("#content");
3278 closeStaticAdditionalDetails: function() {
3279 $(".ui-dialog").find(".open").dialog("close");
3282 * Retrieves additional details dynamically
3284 getAdditionalDetails: function(bean, id, spanId, show_buttons) {
3285 if(typeof show_buttons == "undefined")
3286 show_buttons = false;
3287 var el = '#'+spanId;
3289 oReturn = function(body, caption, width, theme) {
3291 $(".ui-dialog").find(".open").dialog("close");
3293 var $dialog = $('<div class="open"></div>')
3306 $(".ui-dialog").find('.ui-dialog-titlebar-close').css("display","none");
3307 $(".ui-dialog").find('.ui-dialog-title').css("width","100%");
3310 var width = $dialog.dialog( "option", "width" );
3311 var pos = $(el).offset();
3312 var ofWidth = $(el).width();
3314 if((pos.left + ofWidth) - 40 < width) {
3315 $dialog.dialog("option","position",{my: 'left top',at: 'right top',of: $(el)}) ;
3318 $dialog.dialog('open');
3319 $(".ui-dialog").appendTo("#content");
3322 success = function(data) {
3323 eval(data.responseText);
3325 SUGAR.util.additionalDetailsCache[id] = new Array();
3326 SUGAR.util.additionalDetailsCache[id]['body'] = result['body'];
3327 SUGAR.util.additionalDetailsCache[id]['caption'] = result['caption'];
3328 SUGAR.util.additionalDetailsCache[id]['width'] = result['width'];
3329 SUGAR.util.additionalDetailsCache[id]['theme'] = result['theme'];
3330 ajaxStatus.hideStatus();
3331 return oReturn(SUGAR.util.additionalDetailsCache[id]['body'], SUGAR.util.additionalDetailsCache[id]['caption'], SUGAR.util.additionalDetailsCache[id]['width'], SUGAR.util.additionalDetailsCache[id]['theme']);
3334 if(typeof SUGAR.util.additionalDetailsCache[id] != 'undefined')
3335 return oReturn(SUGAR.util.additionalDetailsCache[id]['body'], SUGAR.util.additionalDetailsCache[id]['caption'], SUGAR.util.additionalDetailsCache[id]['width'], SUGAR.util.additionalDetailsCache[id]['theme']);
3337 if(typeof SUGAR.util.additionalDetailsCalls[id] != 'undefined') // call already in progress
3339 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_LOADING'));
3340 url = 'index.php?to_pdf=1&module=Home&action=AdditionalDetailsRetrieve&bean=' + bean + '&id=' + id;
3342 url += '&show_buttons=true';
3343 SUGAR.util.additionalDetailsCalls[id] = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
3347 SUGAR.util.additionalDetailsRpcCall = window.setTimeout('go()', 250);
3349 clearAdditionalDetailsCall: function() {
3350 if(typeof SUGAR.util.additionalDetailsRpcCall == 'number') window.clearTimeout(SUGAR.util.additionalDetailsRpcCall);
3353 * A function that extends functionality from parent to child.
3355 extend : function(subc, superc, overrides) {
3356 subc.prototype = new superc; // set the superclass
3359 for (var i in overrides) subc.prototype[i] = overrides[i];
3362 hrefURL : function(url) {
3364 // IE needs special treatment since otherwise it would not pass Referer
3365 var trampoline = document.createElement('a');
3366 trampoline.href = url;
3367 document.body.appendChild(trampoline);
3369 document.body.removeChild(trampoline);
3371 document.location.href = url;
3375 openWindow : function(URL, windowName, windowFeatures) {
3377 // IE needs special treatment since otherwise it would not pass Referer
3378 win = window.open('', windowName, windowFeatures);
3379 var trampoline = document.createElement('a');
3380 trampoline.href = URL;
3381 trampoline.target = windowName;
3382 document.body.appendChild(trampoline);
3384 document.body.removeChild(trampoline);
3386 win = window.open(URL, windowName, windowFeatures);
3390 //Reset the scroll on the window
3395 //Based on YUI onAvailible, but will use any boolean function instead of an ID
3396 doWhen : function(condition, fn, params, scope)
3398 this._doWhenStack.push({
3402 overrideContext: scope
3405 this._doWhenretryCount = 50;
3406 this._startDoWhenInterval();
3409 _startDoWhenInterval : function(){
3410 if (!this._doWhenInterval) {
3411 this._doWhenInterval = YAHOO.lang.later(50, this, this._doWhenCheck, null, true);
3415 _doWhenInterval : false,
3416 _doWhenCheck : function() {
3417 if (this._doWhenStack.length === 0) {
3418 this._doWhenretryCount = 0;
3419 if (this._doWhenInterval) {
3420 // clearInterval(this._interval);
3421 this._doWhenInterval.cancel();
3422 this._doWhenInterval = null;
3427 if (this._doWhenLocked) {
3432 // Hold off if DOMReady has not fired and check current
3433 // readyState to protect against the IE operation aborted
3435 if (!YAHOO.util.Event.DOMReady) {
3436 this._startDoWhenInterval();
3441 this._doWhenLocked = true;
3444 // keep trying until after the page is loaded. We need to
3445 // check the page load state prior to trying to bind the
3446 // elements so that we can be certain all elements have been
3447 // tested appropriately
3448 var tryAgain = YAHOO.util.Event.DOMReady;
3450 tryAgain = (this._doWhenretryCount > 0 && this._doWhenStack.length > 0);
3456 var executeItem = function (context, item) {
3457 if (item.overrideContext) {
3458 if (item.overrideContext === true) {
3461 context = item.overrideContext;
3465 item.fn.call(context, item.obj);
3469 var i, len, item, test;
3471 // onAvailable onContentReady
3472 for (i=0, len=this._doWhenStack.length; i<len; i=i+1) {
3473 item = this._doWhenStack[i];
3476 if ((typeof(test) == "string" && eval(test)) || (typeof(test) == "function" && test())) {
3477 executeItem(this, item);
3478 this._doWhenStack[i] = null;
3481 notAvail.push(item);
3486 this._doWhenretryCount--;
3489 for (i=this._doWhenStack.length-1; i>-1; i--) {
3490 item = this._doWhenStack[i];
3491 if (!item || !item.check) {
3492 this._doWhenStack.splice(i, 1);
3495 this._startDoWhenInterval();
3497 if (this._doWhenInterval) {
3498 // clearInterval(this._interval);
3499 this._doWhenInterval.cancel();
3500 this._doWhenInterval = null;
3503 this._doWhenLocked = false;
3505 buildAccessKeyLabels : function() {
3506 if (typeof(Y.env.ua) !== 'undefined'){
3508 browserOS = Y.env.ua['os'];
3509 isIE = Y.env.ua['ie'];
3510 isCR = Y.env.ua['chrome'];
3511 isFF = Y.env.ua['gecko'];
3512 isWK = Y.env.ua['webkit'];
3513 isOP = Y.env.ua['opera'];
3516 //first determine the OS
3517 if(browserOS=='macintosh'){
3518 //we got a mac, lets use the mac specific commands while we check the browser
3520 //IE on a Mac? Not possible, but let's assign alt anyways for completions sake
3521 controlKey = 'Alt+';
3522 }else if(isWK || isFF){
3523 //Chrome or safari on a mac
3524 //firefox moved to webkit standard starting with FF14
3525 controlKey = 'Ctrl+Opt+';
3528 controlKey = 'Shift+Esc: ';
3530 //default for everything else on a mac
3531 controlKey = 'Ctrl+';
3534 //this is not a mac so let's use the windows/unix commands while we check the browser
3536 //FF on windows/unix
3537 controlKey = 'Alt+Shift+';
3539 //Opera on windows/unix
3540 controlKey = 'Shift+Esc: ';
3542 //this is the default for safari, IE and Chrome
3543 //if this is webkit and is NOT google, then we are most likely looking at Safari
3544 controlKey = 'Alt+';
3549 //now lets retrieve all elements of type input
3550 allButtons = document.getElementsByTagName('input');
3551 //iterate through list and modify title if the accesskey is not empty
3552 for(i=0;i<allButtons.length;i++){
3553 if(allButtons[i].getAttribute('accesskey') && allButtons[i].getAttribute('type') && allButtons[i].getAttribute('type')=='button'){
3554 allButtons[i].setAttribute('title',allButtons[i].getAttribute('title')+' ['+controlKey+allButtons[i].getAttribute('accesskey')+']');
3557 //now change the text in the help div
3558 $("#shortcuts_dialog").html(function(i, text) {
3559 return text.replace(/Alt\+/g,controlKey);
3561 }// end if (typeof(Y.env.ua) !== 'undefined')
3562 }//end buildAccessKeyLabels()
3565 SUGAR.util.additionalDetailsCache = new Array();
3566 SUGAR.util.additionalDetailsCalls = new Array();
3567 if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.util.setMaxLength); // allow textareas to obey maxlength attrib
3569 SUGAR.savedViews = function() {
3570 var selectedOrderBy;
3571 var selectedSortOrder;
3574 var columnsMeta; // meta data for the display columns
3577 setChooser: function() {
3579 var displayColumnsDef = new Array();
3580 var hideTabsDef = new Array();
3582 var left_td = document.getElementById('display_tabs_td');
3583 if(typeof left_td == 'undefined' || left_td == null) return; // abort!
3584 var right_td = document.getElementById('hide_tabs_td');
3586 var displayTabs = left_td.getElementsByTagName('select')[0];
3587 var hideTabs = right_td.getElementsByTagName('select')[0];
3589 for(i = 0; i < displayTabs.options.length; i++) {
3590 displayColumnsDef.push(displayTabs.options[i].value);
3593 if(typeof hideTabs != 'undefined') {
3594 for(i = 0; i < hideTabs.options.length; i++) {
3595 hideTabsDef.push(hideTabs.options[i].value);
3598 if (!SUGAR.savedViews.clearColumns)
3599 document.getElementById('displayColumnsDef').value = displayColumnsDef.join('|');
3600 document.getElementById('hideTabsDef').value = hideTabsDef.join('|');
3603 select: function(saved_search_select) {
3604 for(var wp = 0; wp < document.search_form.saved_search_select.options.length; wp++) {
3605 if(typeof document.search_form.saved_search_select.options[wp].value != 'undefined' &&
3606 document.search_form.saved_search_select.options[wp].value == saved_search_select) {
3607 document.search_form.saved_search_select.selectedIndex = wp;
3608 document.search_form.ss_delete.style.display = '';
3609 document.search_form.ss_update.style.display = '';
3613 saved_search_action: function(action, delete_lang) {
3614 if(action == 'delete') {
3615 if(!confirm(delete_lang)) return;
3617 if(action == 'save') {
3618 if(document.search_form.saved_search_name.value.replace(/^\s*|\s*$/g, '') == '') {
3619 alert(SUGAR.language.get('app_strings', 'LBL_SAVED_SEARCH_ERROR'));
3624 // This check is needed for the Activities module (Calls/Meetings/Tasks).
3625 if (document.search_form.saved_search_action)
3627 document.search_form.saved_search_action.value = action;
3628 document.search_form.search_module.value = document.search_form.module.value;
3629 document.search_form.module.value = 'SavedSearch';
3630 // Bug 31922 - Make sure to specify that we want to hit the index view here of
3631 // the SavedSearch module, since the ListView doesn't have the logic to save the
3632 // search and redirect back
3633 document.search_form.action.value = 'index';
3635 SUGAR.ajaxUI.submitForm(document.search_form);
3637 shortcut_select: function(selectBox, module) {
3639 selecturl = 'index.php?module=SavedSearch&search_module=' + module + '&action=index&saved_search_select=' + selectBox.options[selectBox.selectedIndex].value
3640 //add searchFormTab to url if it is available. This determines what tab to render
3641 if(typeof(document.getElementById('searchFormTab'))!='undefined'){
3642 selecturl = selecturl + '&searchFormTab=' + document.search_form.searchFormTab.value;
3644 //add showSSDIV to url if it is available. This determines whether saved search sub form should
3645 //be rendered open or not
3646 if(document.getElementById('showSSDIV') && typeof(document.getElementById('showSSDIV') !='undefined')){
3647 selecturl = selecturl + '&showSSDIV='+document.getElementById('showSSDIV').value;
3649 //use created url to navigate
3650 document.location.href = selecturl;
3652 handleForm: function() {
3653 SUGAR.tabChooser.movementCallback = function(left_side, right_side) {
3654 while(document.getElementById('orderBySelect').childNodes.length != 0) { // clear out order by options
3655 document.getElementById('orderBySelect').removeChild(document.getElementById('orderBySelect').lastChild);
3658 var selectedIndex = 0;
3659 var nodeCount = -1; // need this because the counter i also includes "undefined" nodes
3660 // which was breaking Calls and Meetings
3662 for(i in left_side.childNodes) { // fill in order by options
3663 if(typeof left_side.childNodes[i].nodeName != 'undefined' &&
3664 left_side.childNodes[i].nodeName.toLowerCase() == 'option' &&
3665 typeof SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value] != 'undefined' && // check if column is sortable
3666 typeof SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value]['sortable'] == 'undefined' &&
3667 SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value]['sortable'] != false) {
3669 optionNode = document.createElement('option');
3670 optionNode.value = left_side.childNodes[i].value;
3671 optionNode.innerHTML = left_side.childNodes[i].innerHTML;
3672 document.getElementById('orderBySelect').appendChild(optionNode);
3673 if(optionNode.value == SUGAR.savedViews.selectedOrderBy)
3674 selectedIndex = nodeCount;
3677 // Firefox needs this to be set after all the option nodes are created.
3678 document.getElementById('orderBySelect').selectedIndex = selectedIndex;
3680 SUGAR.tabChooser.movementCallback(document.getElementById('display_tabs_td').getElementsByTagName('select')[0]);
3682 // This check is needed for the Activities module (Calls/Meetings/Tasks).
3683 if (document.search_form.orderBy)
3685 if (document.search_form.orderBy.length > 1 && document.search_form.orderBy[1].type == 'select-one')
3687 document.search_form.orderBy[1].options.value = SUGAR.savedViews.selectedOrderBy;
3691 document.search_form.orderBy.options.value = SUGAR.savedViews.selectedOrderBy;
3696 if(SUGAR.savedViews.selectedSortOrder == 'DESC') document.getElementById('sort_order_desc_radio').checked = true;
3697 else document.getElementById('sort_order_asc_radio').checked = true;
3702 SUGAR.searchForm = function() {
3705 // searchForm tab selector util
3706 searchFormSelect: function(view, previousView) {
3707 var module = view.split('|')[0];
3708 var theView = view.split('|')[1];
3710 var handleDisplay = function() { // hide other divs
3711 document.search_form.searchFormTab.value = theView;
3712 patt = module+"(.*)SearchForm$";
3713 divId=document.search_form.getElementsByTagName('div');
3714 // Hide all the search forms and retrive the name of the previous search tab (useful for the first load because previousView is empty)
3715 for (i=0;i<divId.length;i++){
3716 if(divId[i].id.match(module)==module){
3717 if(divId[i].id.match('SearchForm')=='SearchForm'){
3718 if(document.getElementById(divId[i].id).style.display == ''){
3719 previousTab=divId[i].id.match(patt)[1];
3721 document.getElementById(divId[i].id).style.display = 'none';
3726 //clear thesearch form accesekeys and reset them to the appropriate link
3727 adv = document.getElementById('advanced_search_link');
3728 bas = document.getElementById('basic_search_link');
3729 adv.setAttribute('accesskey','');
3730 bas.setAttribute('accesskey','');
3731 a_key = SUGAR.language.get("app_strings", "LBL_ADV_SEARCH_LNK_KEY");
3733 //reset the ccesskey based on theview
3734 if(theView === 'advanced_search'){
3736 bas.setAttribute('accesskey',a_key);
3738 adv.setAttribute('accesskey',a_key);
3741 // show the good search form.
3742 document.getElementById(module + theView + 'SearchForm').style.display = '';
3743 //if its not the first tab show there is a previous tab.
3745 thepreviousView=previousView.split('|')[1];
3748 thepreviousView=previousTab;
3750 thepreviousView=thepreviousView.replace(/_search/, "");
3751 // Process to retrieve the completed field from one tab to an other.
3752 for(num in document.search_form.elements) {
3753 if(document.search_form.elements[num]) {
3754 el = document.search_form.elements[num];
3755 pattern="^(.*)_"+thepreviousView+"$";
3756 if(typeof el.type != 'undefined' && typeof el.name != 'undefined' && el.name.match(pattern)) {
3757 advanced_input_name = el.name.match(pattern)[1]; // strip
3758 advanced_input_name = advanced_input_name+"_"+theView.replace(/_search/, "");
3759 if(typeof document.search_form[advanced_input_name] != 'undefined') // if advanced input of same name exists
3760 SUGAR.searchForm.copyElement(advanced_input_name, el);
3764 // Remove the previously selected div, so that only data from current div to be sent as form data to the server-side
3765 if (document.getElementById(module + thepreviousView + '_search' + 'SearchForm'))
3767 document.getElementById(module + thepreviousView + '_search' + 'SearchForm').innerHTML = '';
3771 // if tab is not cached
3772 if(document.getElementById(module + theView + 'SearchForm').innerHTML == '') {
3773 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_LOADING'));
3774 var success = function(data) {
3775 document.getElementById(module + theView + 'SearchForm').innerHTML = data.responseText;
3777 SUGAR.util.evalScript(data.responseText);
3778 // pass script variables to global scope
3779 if(theView == 'saved_views') {
3780 if(typeof columnsMeta != 'undefined') SUGAR.savedViews.columnsMeta = columnsMeta;
3781 if(typeof selectedOrderBy != 'undefined') SUGAR.savedViews.selectedOrderBy = selectedOrderBy;
3782 if(typeof selectedSortOrder != 'undefined') SUGAR.savedViews.selectedSortOrder = selectedSortOrder;
3787 ajaxStatus.hideStatus();
3789 url = 'index.php?module=' + module + '&action=index&search_form_only=true&to_pdf=true&search_form_view=' + theView;
3791 //check to see if tpl has been specified. If so then pass location through url string
3793 if(document.getElementById('search_tpl') !=null && typeof(document.getElementById('search_tpl')) != 'undefined'){
3794 tpl = document.getElementById('search_tpl').value;
3795 if(tpl != ''){url += '&search_tpl='+tpl;}
3798 if(theView == 'saved_views') // handle the tab chooser
3799 url += '&displayColumns=' + SUGAR.savedViews.displayColumns + '&hideTabs=' + SUGAR.savedViews.hideTabs + '&orderBy=' + SUGAR.savedViews.selectedOrderBy + '&sortOrder=' + SUGAR.savedViews.selectedSortOrder;
3801 var cObj = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
3803 else { // that form already retrieved
3808 // copies one input to another
3809 copyElement: function(inputName, copyFromElement) {
3810 switch(copyFromElement.type) {
3813 document.search_form[inputName].value = copyFromElement.value;
3817 // This function is here to clear the form, instead of "resubmitting it
3818 clear_form: function(form, skipElementNames) {
3819 var elemList = form.elements;
3823 for( var i = 0; i < elemList.length ; i++ ) {
3825 if ( typeof(elem.type) == 'undefined' ) {
3829 if ( typeof(elem.type) != 'undefined' && typeof(skipElementNames) != 'undefined'
3830 && SUGAR.util.arrayIndexOf(skipElementNames, elem.name) != -1 )
3835 elemType = elem.type.toLowerCase();
3837 if ( elemType == 'text' || elemType == 'textarea' || elemType == 'password' ) {
3839 } else if (elemType == 'select-one') {
3840 // We have, what I hope, is a select box, time to unselect all options
3841 var optionList = elem.options,
3843 for (var ii = 0; ii < optionList.length; ii++) {
3844 if (optionList[ii].value == '') {
3849 if (optionList.length > 0) {
3850 optionList[selectedIndex].selected = "selected";
3852 } else if (elemType == 'select-multiple') {
3853 var optionList = elem.options;
3854 for ( var ii = 0 ; ii < optionList.length ; ii++ ) {
3855 optionList[ii].selected = false;
3858 else if ( elemType == 'radio' || elemType == 'checkbox' ) {
3859 elem.checked = false;
3860 elem.selected = false;
3862 else if ( elemType == 'hidden' ) {
3864 // For bean selection
3865 elem.name.indexOf("_id") != -1
3866 // For custom fields
3867 || elem.name.indexOf("_c") != -1
3868 // For advanced fields, like team collection, or datetime fields
3869 || elem.name.indexOf("_advanced") != -1
3877 // If there are any collections
3878 if (typeof(collection) !== 'undefined')
3880 // Loop through all the collections on the page and run clean_up()
3881 for (key in collection)
3883 // Clean up only removes blank fields, if any
3884 collection[key].clean_up();
3888 SUGAR.searchForm.clearBasicSearchOrderToDefault(form);
3889 SUGAR.savedViews.clearColumns = true;
3891 // This function sets sorting to default Sugar values after BasicSearch Clear button is pressed
3892 clearBasicSearchOrderToDefault: function(form)
3894 if(form.elements['searchFormTab']){
3895 var formType = form.elements['searchFormTab'].value;
3896 if (formType == 'basic_search')
3898 form.elements['orderBy'].value = 'DATE_ENTERED';
3899 form.elements['sortOrder'].value = 'DESC';
3905 // Code for the column/tab chooser used on homepage and in admin section
3906 SUGAR.tabChooser = function () {
3907 var object_refs = new Array();
3909 /* Describe certain transfers as invalid */
3912 movementCallback: function(left_side, right_side) {},
3913 orderCallback: function(left_side, right_side) {},
3915 freezeOptions: function(left_name, right_name, target) {
3916 if(!SUGAR.tabChooser.frozenOptions) { SUGAR.tabChooser.frozenOptions = []; }
3917 if(!SUGAR.tabChooser.frozenOptions[left_name]) { SUGAR.tabChooser.frozenOptions[left_name] = []; }
3918 if(!SUGAR.tabChooser.frozenOptions[left_name][right_name]) { SUGAR.tabChooser.frozenOptions[left_name][right_name] = []; }
3919 if(typeof target == 'array') {
3920 for(var i in target) {
3921 SUGAR.tabChooser.frozenOptions[left_name][right_name][target[i]] = true;
3924 SUGAR.tabChooser.frozenOptions[left_name][right_name][target] = true;
3928 buildSelectHTML: function(info) {
3929 var text = "<select";
3931 if(typeof (info['select']['size']) != 'undefined') {
3932 text +=" size=\""+ info['select']['size'] +"\"";
3935 if(typeof (info['select']['name']) != 'undefined') {
3936 text +=" name=\""+ info['select']['name'] +"\"";
3939 if(typeof (info['select']['style']) != 'undefined') {
3940 text +=" style=\""+ info['select']['style'] +"\"";
3943 if(typeof (info['select']['onchange']) != 'undefined') {
3944 text +=" onChange=\""+ info['select']['onchange'] +"\"";
3947 if(typeof (info['select']['multiple']) != 'undefined') {
3952 for(i=0; i<info['options'].length;i++) {
3953 option = info['options'][i];
3954 text += "<option value=\""+option['value']+"\" ";
3955 if ( typeof (option['selected']) != 'undefined' && option['selected']== true) {
3958 text += ">"+option['text']+"</option>";
3960 text += "</select>";
3964 left_to_right: function(left_name, right_name, left_size, right_size) {
3965 SUGAR.savedViews.clearColumns = false;
3966 var left_td = document.getElementById(left_name+'_td');
3967 var right_td = document.getElementById(right_name+'_td');
3969 var display_columns_ref = left_td.getElementsByTagName('select')[0];
3970 var hidden_columns_ref = right_td.getElementsByTagName('select')[0];
3972 var selected_left = new Array();
3973 var notselected_left = new Array();
3974 var notselected_right = new Array();
3976 var left_array = new Array();
3978 var frozen_options = SUGAR.tabChooser.frozenOptions;
3979 frozen_options = frozen_options && frozen_options[left_name] && frozen_options[left_name][right_name]?frozen_options[left_name][right_name]:[];
3981 // determine which options are selected in left
3982 for (i=0; i < display_columns_ref.options.length; i++)
3984 if ( display_columns_ref.options[i].selected == true && !frozen_options[display_columns_ref.options[i].value])
3986 selected_left[selected_left.length] = {text: display_columns_ref.options[i].text, value: display_columns_ref.options[i].value};
3990 notselected_left[notselected_left.length] = {text: display_columns_ref.options[i].text, value: display_columns_ref.options[i].value};
3995 for (i=0; i < hidden_columns_ref.options.length; i++)
3997 notselected_right[notselected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
4001 var left_select_html_info = new Object();
4002 var left_options = new Array();
4003 var left_select = new Object();
4005 left_select['name'] = left_name+'[]';
4006 left_select['id'] = left_name;
4007 left_select['size'] = left_size;
4008 left_select['multiple'] = 'true';
4010 var right_select_html_info = new Object();
4011 var right_options = new Array();
4012 var right_select = new Object();
4014 right_select['name'] = right_name+'[]';
4015 right_select['id'] = right_name;
4016 right_select['size'] = right_size;
4017 right_select['multiple'] = 'true';
4019 for (i = 0; i < notselected_right.length; i++) {
4020 right_options[right_options.length] = notselected_right[i];
4023 for (i = 0; i < selected_left.length; i++) {
4024 right_options[right_options.length] = selected_left[i];
4026 for (i = 0; i < notselected_left.length; i++) {
4027 left_options[left_options.length] = notselected_left[i];
4029 left_select_html_info['options'] = left_options;
4030 left_select_html_info['select'] = left_select;
4031 right_select_html_info['options'] = right_options;
4032 right_select_html_info['select'] = right_select;
4033 right_select_html_info['style'] = 'background: lightgrey';
4035 var left_html = this.buildSelectHTML(left_select_html_info);
4036 var right_html = this.buildSelectHTML(right_select_html_info);
4038 left_td.innerHTML = left_html;
4039 right_td.innerHTML = right_html;
4041 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
4042 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
4044 this.movementCallback(object_refs[left_name], object_refs[right_name]);
4050 right_to_left: function(left_name, right_name, left_size, right_size, max_left) {
4051 SUGAR.savedViews.clearColumns = false;
4052 var left_td = document.getElementById(left_name+'_td');
4053 var right_td = document.getElementById(right_name+'_td');
4055 var display_columns_ref = left_td.getElementsByTagName('select')[0];
4056 var hidden_columns_ref = right_td.getElementsByTagName('select')[0];
4058 var selected_right = new Array();
4059 var notselected_right = new Array();
4060 var notselected_left = new Array();
4062 var frozen_options = SUGAR.tabChooser.frozenOptions;
4063 frozen_options = SUGAR.tabChooser.frozenOptions && SUGAR.tabChooser.frozenOptions[right_name] && SUGAR.tabChooser.frozenOptions[right_name][left_name]?SUGAR.tabChooser.frozenOptions[right_name][left_name]:[];
4065 for (i=0; i < hidden_columns_ref.options.length; i++)
4067 if (hidden_columns_ref.options[i].selected == true && !frozen_options[hidden_columns_ref.options[i].value])
4069 selected_right[selected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
4073 notselected_right[notselected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
4078 if(max_left != '' && (display_columns_ref.length + selected_right.length) > max_left) {
4079 alert('Maximum of ' + max_left + ' columns can be displayed.');
4083 for (i=0; i < display_columns_ref.options.length; i++)
4085 notselected_left[notselected_left.length] = {text:display_columns_ref.options[i].text, value:display_columns_ref.options[i].value};
4089 var left_select_html_info = new Object();
4090 var left_options = new Array();
4091 var left_select = new Object();
4093 left_select['name'] = left_name+'[]';
4094 left_select['id'] = left_name;
4095 left_select['multiple'] = 'true';
4096 left_select['size'] = left_size;
4098 var right_select_html_info = new Object();
4099 var right_options = new Array();
4100 var right_select = new Object();
4102 right_select['name'] = right_name+ '[]';
4103 right_select['id'] = right_name;
4104 right_select['multiple'] = 'true';
4105 right_select['size'] = right_size;
4107 for (i = 0; i < notselected_left.length; i++) {
4108 left_options[left_options.length] = notselected_left[i];
4111 for (i = 0; i < selected_right.length; i++) {
4112 left_options[left_options.length] = selected_right[i];
4114 for (i = 0; i < notselected_right.length; i++) {
4115 right_options[right_options.length] = notselected_right[i];
4117 left_select_html_info['options'] = left_options;
4118 left_select_html_info['select'] = left_select;
4119 right_select_html_info['options'] = right_options;
4120 right_select_html_info['select'] = right_select;
4121 right_select_html_info['style'] = 'background: lightgrey';
4123 var left_html = this.buildSelectHTML(left_select_html_info);
4124 var right_html = this.buildSelectHTML(right_select_html_info);
4126 left_td.innerHTML = left_html;
4127 right_td.innerHTML = right_html;
4129 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
4130 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
4132 this.movementCallback(object_refs[left_name], object_refs[right_name]);
4137 up: function(name, left_name, right_name) {
4138 SUGAR.savedViews.clearColumns = false;
4139 var left_td = document.getElementById(left_name+'_td');
4140 var right_td = document.getElementById(right_name+'_td');
4141 var td = document.getElementById(name+'_td');
4142 var obj = td.getElementsByTagName('select')[0];
4143 obj = (typeof obj == "string") ? document.getElementById(obj) : obj;
4144 if (obj.tagName.toLowerCase() != "select" && obj.length < 2)
4146 var sel = new Array();
4148 for (i=0; i<obj.length; i++) {
4149 if (obj[i].selected == true) {
4150 sel[sel.length] = i;
4153 for (i=0; i < sel.length; i++) {
4154 if (sel[i] != 0 && !obj[sel[i]-1].selected) {
4155 var tmp = new Array(obj[sel[i]-1].text, obj[sel[i]-1].value);
4156 obj[sel[i]-1].text = obj[sel[i]].text;
4157 obj[sel[i]-1].value = obj[sel[i]].value;
4158 obj[sel[i]].text = tmp[0];
4159 obj[sel[i]].value = tmp[1];
4160 obj[sel[i]-1].selected = true;
4161 obj[sel[i]].selected = false;
4165 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
4166 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
4168 this.orderCallback(object_refs[left_name], object_refs[right_name]);
4173 down: function(name, left_name, right_name) {
4174 SUGAR.savedViews.clearColumns = false;
4175 var left_td = document.getElementById(left_name+'_td');
4176 var right_td = document.getElementById(right_name+'_td');
4177 var td = document.getElementById(name+'_td');
4178 var obj = td.getElementsByTagName('select')[0];
4179 if (obj.tagName.toLowerCase() != "select" && obj.length < 2)
4181 var sel = new Array();
4182 for (i=obj.length-1; i>-1; i--) {
4183 if (obj[i].selected == true) {
4184 sel[sel.length] = i;
4187 for (i=0; i < sel.length; i++) {
4188 if (sel[i] != obj.length-1 && !obj[sel[i]+1].selected) {
4189 var tmp = new Array(obj[sel[i]+1].text, obj[sel[i]+1].value);
4190 obj[sel[i]+1].text = obj[sel[i]].text;
4191 obj[sel[i]+1].value = obj[sel[i]].value;
4192 obj[sel[i]].text = tmp[0];
4193 obj[sel[i]].value = tmp[1];
4194 obj[sel[i]+1].selected = true;
4195 obj[sel[i]].selected = false;
4199 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
4200 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
4202 this.orderCallback(object_refs[left_name], object_refs[right_name]);
4207 }(); // end tabChooser
4209 SUGAR.language = function() {
4211 languages : new Array(),
4213 setLanguage: function(module, data) {
4214 if (!SUGAR.language.languages) {
4217 SUGAR.language.languages[module] = data;
4220 get: function(module, str) {
4221 if(typeof SUGAR.language.languages[module] == 'undefined' || typeof SUGAR.language.languages[module][str] == 'undefined')
4225 return SUGAR.language.languages[module][str];
4228 translate: function(module, str)
4230 text = this.get(module, str);
4231 return text != 'undefined' ? text : this.get('app_strings', str);
4236 SUGAR.contextMenu = function() {
4238 objects: new Object(),
4239 objectTypes: new Object(),
4241 * Registers a new object for the context menu.
4242 * objectType - name of the type
4244 * metaData - metaData to pass to the action function
4246 registerObject: function(objectType, id, metaData) {
4247 SUGAR.contextMenu.objects[id] = new Object();
4248 SUGAR.contextMenu.objects[id] = {'objectType' : objectType, 'metaData' : metaData};
4251 * Registers a new object type
4252 * name - name of the type
4253 * menuItems - array of menu items
4255 registerObjectType: function(name, menuItems) {
4256 SUGAR.contextMenu.objectTypes[name] = new Object();
4257 SUGAR.contextMenu.objectTypes[name] = {'menuItems' : menuItems, 'objects' : new Array()};
4260 * Determines which menu item was clicked
4262 getListItemFromEventTarget: function(p_oNode) {
4264 if(p_oNode.tagName == "LI") {
4269 if(p_oNode.tagName == "LI") {
4274 } while((p_oNode = p_oNode.parentNode));
4279 * handles movement within context menu
4281 onContextMenuMove: function() {
4282 var oNode = this.contextEventTarget;
4283 var bDisabled = (oNode.tagName == "UL");
4284 var i = this.getItemGroups()[0].length - 1;
4286 this.getItem(i).cfg.setProperty("disabled", bDisabled);
4291 * handles clicks on a context menu ITEM
4293 onContextMenuItemClick: function(p_sType, p_aArguments, p_oItem) {
4294 var oLI = SUGAR.contextMenu.getListItemFromEventTarget(this.parent.contextEventTarget);
4295 id = this.parent.contextEventTarget.parentNode.id; // id of the target
4296 funct = eval(SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[id]['objectType']]['menuItems'][this.index]['action']);
4297 funct(this.parent.contextEventTarget, SUGAR.contextMenu.objects[id]['metaData']);
4300 * Initializes all context menus registered
4303 for(var i in SUGAR.contextMenu.objects) { // make a variable called objects in objectTypes containg references to all triggers
4304 if(typeof SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'] == 'undefined')
4305 SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'] = new Array();
4306 SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'].push(document.getElementById(i));
4308 // register the menus
4309 for(var i in SUGAR.contextMenu.objectTypes) {
4310 var oContextMenu = new YAHOO.widget.ContextMenu(i, {'trigger': SUGAR.contextMenu.objectTypes[i]['objects']});
4311 var aMainMenuItems = SUGAR.contextMenu.objectTypes[i]['menuItems'];
4312 var nMainMenuItems = aMainMenuItems.length;
4314 for(var j = 0; j < nMainMenuItems; j++) {
4315 oMenuItem = new YAHOO.widget.ContextMenuItem(aMainMenuItems[j].text, { helptext: aMainMenuItems[j].helptext });
4316 oMenuItem.clickEvent.subscribe(SUGAR.contextMenu.onContextMenuItemClick, oMenuItem, true);
4317 oContextMenu.addItem(oMenuItem);
4319 // Add a "move" event handler to the context menu
4320 oContextMenu.moveEvent.subscribe(SUGAR.contextMenu.onContextMenuMove, oContextMenu, true);
4321 // Add a "keydown" event handler to the context menu
4322 oContextMenu.keyDownEvent.subscribe(SUGAR.contextMenu.onContextMenuItemClick, oContextMenu, true);
4323 // Render the context menu
4324 oContextMenu.render(document.body);
4330 SUGAR.contextMenu.actions = function() {
4333 * redirects to a new note with the clicked on object as the target
4335 createNote: function(itemClicked, metaData) {
4336 loc = 'index.php?module=Notes&action=EditView';
4337 for(i in metaData) {
4338 if(i == 'notes_parent_type') loc += '&parent_type=' + metaData[i];
4339 else if(i != 'module' && i != 'parent_type') loc += '&' + i + '=' + metaData[i];
4341 document.location = loc;
4344 * redirects to a new note with the clicked on object as the target
4346 scheduleMeeting: function(itemClicked, metaData) {
4347 loc = 'index.php?module=Meetings&action=EditView';
4348 for(i in metaData) {
4349 if(i != 'module') loc += '&' + i + '=' + metaData[i];
4351 document.location = loc;
4354 * redirects to a new note with the clicked on object as the target
4356 scheduleCall: function(itemClicked, metaData) {
4357 loc = 'index.php?module=Calls&action=EditView';
4358 for(i in metaData) {
4359 if(i != 'module') loc += '&' + i + '=' + metaData[i];
4361 document.location = loc;
4364 * redirects to a new contact with the clicked on object as the target
4366 createContact: function(itemClicked, metaData) {
4367 loc = 'index.php?module=Contacts&action=EditView';
4368 for(i in metaData) {
4369 if(i != 'module') loc += '&' + i + '=' + metaData[i];
4371 document.location = loc;
4374 * redirects to a new task with the clicked on object as the target
4376 createTask: function(itemClicked, metaData) {
4377 loc = 'index.php?module=Tasks&action=EditView';
4378 for(i in metaData) {
4379 if(i != 'module') loc += '&' + i + '=' + metaData[i];
4381 document.location = loc;
4384 * redirects to a new opportunity with the clicked on object as the target
4386 createOpportunity: function(itemClicked, metaData) {
4387 loc = 'index.php?module=Opportunities&action=EditView';
4388 for(i in metaData) {
4389 if(i != 'module') loc += '&' + i + '=' + metaData[i];
4391 document.location = loc;
4394 * redirects to a new opportunity with the clicked on object as the target
4396 createCase: function(itemClicked, metaData) {
4397 loc = 'index.php?module=Cases&action=EditView';
4398 for(i in metaData) {
4399 if(i != 'module') loc += '&' + i + '=' + metaData[i];
4401 document.location = loc;
4404 * handles add to favorites menu selection
4406 addToFavorites: function(itemClicked, metaData) {
4407 success = function(data) {
4409 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});
4414 //if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.contextMenu.init);
4416 // initially from popup_parent_helper.js
4417 var popup_request_data;
4420 function get_popup_request_data()
4422 return YAHOO.lang.JSON.stringify(window.document.popup_request_data);
4425 function get_close_popup()
4427 return window.document.close_popup;
4430 function open_popup(module_name, width, height, initial_filter, close_popup, hide_clear_button, popup_request_data, popup_mode, create, metadata)
4432 if (typeof(popupCount) == "undefined" || popupCount == 0)
4435 // set the variables that the popup will pull from
4436 window.document.popup_request_data = popup_request_data;
4437 window.document.close_popup = close_popup;
4439 //globally changing width and height of standard pop up window from 600 x 400 to 800 x 800
4440 width = (width == 600) ? 800 : width;
4441 height = (height == 400) ? 800 : height;
4445 + 'module=' + module_name
4448 if (initial_filter != '') {
4449 URL += '&query=true' + initial_filter;
4450 // Bug 41891 - Popup Window Name
4451 popupName = initial_filter.replace(/[^a-z_0-9]+/ig, '_');
4452 windowName = module_name + '_popup_window' + popupName;
4454 windowName = module_name + '_popup_window' + popupCount;
4458 if (hide_clear_button) {
4459 URL += '&hide_clear_button=true';
4462 windowFeatures = 'width=' + width
4463 + ',height=' + height
4464 + ',resizable=1,scrollbars=1';
4466 if (popup_mode == '' || popup_mode == undefined) {
4467 popup_mode='single';
4469 URL+='&mode='+popup_mode;
4470 if (create == '' || create == undefined) {
4473 URL+='&create='+create;
4475 if (metadata != '' && metadata != undefined) {
4476 URL+='&metadata='+metadata;
4479 // Bug #46842 : The relate field field_to_name_array fails to copy over custom fields
4480 // post fields that should be populated from popup form
4481 if(popup_request_data.jsonObject) {
4482 var request_data = popup_request_data.jsonObject;
4484 var request_data = popup_request_data;
4486 var field_to_name_array_url = '';
4488 if (request_data && request_data.field_to_name_array != undefined) {
4489 for(var key in request_data.field_to_name_array) {
4490 if ( key.toLowerCase() != 'id' ) {
4491 field_to_name_array_url += '&field_to_name[]='+encodeURIComponent(key.toLowerCase());
4495 if ( field_to_name_array_url ) {
4496 URL+=field_to_name_array_url;
4499 win = SUGAR.util.openWindow(URL, windowName, windowFeatures);
4503 // put the focus on the popup if the browser supports the focus() method
4507 win.popupCount = popupCount;
4513 * The reply data must be a JSON array structured with the following information:
4514 * 1) form name to populate
4515 * 2) associative array of input names to values for populating the form
4517 var from_popup_return = false;
4519 //Function replaces special HTML chars for usage in text boxes
4520 function replaceHTMLChars(value) {
4521 return value.replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');
4524 function set_return_basic(popup_reply_data,filter)
4526 var form_name = popup_reply_data.form_name;
4527 var name_to_value_array = popup_reply_data.name_to_value_array;
4528 for (var the_key in name_to_value_array)
4530 if(the_key == 'toJSON')
4534 else if(the_key.match(filter))
4536 var displayValue=replaceHTMLChars(name_to_value_array[the_key]);
4537 // begin andopes change: support for enum fields (SELECT)
4538 if(window.document.forms[form_name] && window.document.forms[form_name].elements[the_key]) {
4539 if(window.document.forms[form_name].elements[the_key].tagName == 'SELECT') {
4540 var selectField = window.document.forms[form_name].elements[the_key];
4541 for(var i = 0; i < selectField.options.length; i++) {
4542 if(selectField.options[i].text == displayValue) {
4543 selectField.options[i].selected = true;
4544 SUGAR.util.callOnChangeListers(selectField);
4549 window.document.forms[form_name].elements[the_key].value = displayValue;
4550 SUGAR.util.callOnChangeListers(window.document.forms[form_name].elements[the_key]);
4553 // end andopes change: support for enum fields (SELECT)
4558 function set_return(popup_reply_data)
4560 from_popup_return = true;
4561 var form_name = popup_reply_data.form_name;
4562 var name_to_value_array = popup_reply_data.name_to_value_array;
4563 if(typeof name_to_value_array != 'undefined' && name_to_value_array['account_id'])
4566 var label_data_str = '';
4567 var current_label_data_str = '';
4568 var popupConfirm = popup_reply_data.popupConfirm;
4569 for (var the_key in name_to_value_array)
4571 if(the_key == 'toJSON')
4577 var displayValue=replaceHTMLChars(name_to_value_array[the_key]);
4578 if(window.document.forms[form_name] && document.getElementById(the_key+'_label') && !the_key.match(/account/)) {
4579 var data_label = document.getElementById(the_key+'_label').innerHTML.replace(/\n/gi,'').replace(/<\/?[^>]+(>|$)/g, "");
4580 label_str += data_label + ' \n';
4581 label_data_str += data_label + ' ' + displayValue + '\n';
4582 if(window.document.forms[form_name].elements[the_key]) {
4583 current_label_data_str += data_label + ' ' + window.document.forms[form_name].elements[the_key].value +'\n';
4589 if(label_data_str != label_str && current_label_data_str != label_str){
4591 if (typeof popupConfirm != 'undefined')
4593 if (popupConfirm > -1) {
4594 set_return_basic(popup_reply_data,/\S/);
4596 set_return_basic(popup_reply_data,/account/);
4600 else if(confirm(SUGAR.language.get('app_strings', 'NTC_OVERWRITE_ADDRESS_PHONE_CONFIRM') + '\n\n' + label_data_str))
4602 set_return_basic(popup_reply_data,/\S/);
4606 set_return_basic(popup_reply_data,/account/);
4608 }else if(label_data_str != label_str && current_label_data_str == label_str){
4609 set_return_basic(popup_reply_data,/\S/);
4610 }else if(label_data_str == label_str){
4611 set_return_basic(popup_reply_data,/account/);
4614 set_return_basic(popup_reply_data,/\S/);
4618 function set_return_lead_conv(popup_reply_data) {
4619 set_return(popup_reply_data);
4620 if (document.getElementById('lead_conv_ac_op_sel') && typeof onBlurKeyUpHandler=='function') {
4621 onBlurKeyUpHandler();
4625 function set_return_and_save(popup_reply_data)
4627 var form_name = popup_reply_data.form_name;
4628 var name_to_value_array = popup_reply_data.name_to_value_array;
4630 for (var the_key in name_to_value_array)
4632 if(the_key == 'toJSON')
4638 window.document.forms[form_name].elements[the_key].value = name_to_value_array[the_key];
4642 window.document.forms[form_name].return_module.value = window.document.forms[form_name].module.value;
4643 window.document.forms[form_name].return_action.value = 'DetailView';
4644 window.document.forms[form_name].return_id.value = window.document.forms[form_name].record.value;
4645 window.document.forms[form_name].action.value = 'Save';
4646 window.document.forms[form_name].submit();
4650 * This is a helper function to construct the initial filter that can be
4651 * passed into the open_popup() function. It assumes that there is an
4652 * account_id and account_name field in the given form_name to use to
4653 * construct the intial filter string.
4655 function get_initial_filter_by_account(form_name)
4657 var account_id = window.document.forms[form_name].account_id.value;
4658 var account_name = escape(window.document.forms[form_name].account_name.value);
4659 var initial_filter = "&account_id=" + account_id + "&account_name=" + account_name;
4661 return initial_filter;
4663 // end code from popup_parent_helper.js
4665 // begin code for address copy
4667 * This is a function used by the Address widget that will fill
4668 * in the given array fields using the fromKey and toKey as a
4669 * prefix into the form objects HTML elements.
4671 * @param form The HTML form object to parse
4672 * @param fromKey The prefix of elements to copy from
4673 * @param toKey The prefix of elements to copy into
4674 * @return boolean true if successful, false otherwise
4676 function copyAddress(form, fromKey, toKey) {
4678 var elems = new Array("address_street", "address_city", "address_state", "address_postalcode", "address_country");
4679 var checkbox = document.getElementById(toKey + "_checkbox");
4681 if(typeof checkbox != "undefined") {
4682 if(!checkbox.checked) {
4684 t = toKey + "_" + elems[x];
4685 document.getElementById(t).removeAttribute('readonly');
4689 f = fromKey + "_" + elems[x];
4690 t = toKey + "_" + elems[x];
4692 document.getElementById(t).value = document.getElementById(f).value;
4693 document.getElementById(t).setAttribute('readonly', true);
4699 // end code for address copy
4702 * This function is used in Email Template Module.
4703 * It will check whether the template is used in Campaing->EmailMarketing.
4704 * If true, it will notify user.
4707 function check_deletable_EmailTemplate() {
4708 id = document.getElementsByName('record')[0].value;
4709 currentForm = document.getElementById('form');
4711 success:function(r) {
4712 if(r.responseText == 'true') {
4713 if(!confirm(SUGAR.language.get('app_strings','NTC_TEMPLATE_IS_USED'))) {
4717 if(!confirm(SUGAR.language.get('app_strings','NTC_DELETE_CONFIRMATION'))) {
4721 currentForm.return_module.value='EmailTemplates';
4722 currentForm.return_action.value='ListView';
4723 currentForm.action.value='Delete';
4724 currentForm.submit();
4727 url = "index.php?module=EmailTemplates&action=CheckDeletable&from=DetailView&to_pdf=1&record="+id;
4728 YAHOO.util.Connect.asyncRequest('POST',url, call_back,null);
4732 remove_upload_imagefile : function(field_name) {
4733 var field=document.getElementById('remove_imagefile_' + field_name);
4736 //enable the file upload button.
4737 var field=document.getElementById( field_name);
4738 field.style.display="";
4740 //hide the image and remove button.
4741 var field=document.getElementById('img_' + field_name);
4742 field.style.display="none";
4743 var field=document.getElementById('bt_remove_' + field_name);
4744 field.style.display="none";
4746 if(document.getElementById(field_name + '_duplicate')) {
4747 var field = document.getElementById(field_name + '_duplicate');
4752 confirm_imagefile : function(field_name) {
4753 var field=document.getElementById(field_name);
4754 var filename=field.value;
4755 var fileExtension = filename.substring(filename.lastIndexOf(".")+1);
4756 fileExtension = fileExtension.toLowerCase();
4757 if (fileExtension == "jpg" || fileExtension == "jpeg"
4758 || fileExtension == "gif" || fileExtension == "png" || fileExtension == "bmp"){
4763 alert(SUGAR.language.get('app_strings', 'LBL_UPLOAD_IMAGE_FILE_INVALID'));
4767 lightbox : function(image)
4769 if (typeof(SUGAR.image.lighboxWindow) == "undefined")
4770 SUGAR.image.lighboxWindow = new YAHOO.widget.SimpleDialog('sugarImageViewer', {
4773 id:'sugarMsgWindow',
4776 msg: "<img src='" + image + "'> </img>",
4779 SUGAR.image.lighboxWindow.setBody("<img src='" + image + "'> </img>");
4780 SUGAR.image.lighboxWindow.render(document.body);
4781 SUGAR.image.lighboxWindow.show();
4782 SUGAR.image.lighboxWindow.center()
4786 SUGAR.append(SUGAR.util, {
4787 isTouchScreen: function() {
4788 // first check if we have forced use of the touch enhanced interface
4789 if (Get_Cookie("touchscreen") == '1') {
4793 // next check if we should use the touch interface with our device
4794 if ((navigator.userAgent.match(/iPad/i) != null)) {
4801 isLoginPage: function(content) {
4802 //skip if this is packageManager screen
4803 if(SUGAR.util.isPackageManager()) {return false;}
4804 var loginPageStart = "<!DOCTYPE";
4805 if (content.substr(0, loginPageStart.length) == loginPageStart && content.indexOf("<html>") != -1 && content.indexOf("login_module") != -1) {
4806 window.location.href = window.location.protocol + window.location.pathname;
4811 isPackageManager: function(){
4812 if(typeof(document.the_form) !='undefined' && typeof(document.the_form.language_pack_escaped) !='undefined'){
4814 }else{return false;}
4817 ajaxCallInProgress: function(){
4819 //First check if we are in a popup.
4820 if (typeof (send_back) != "function"){
4821 //If the page content is blank, it means we are probably still waiting on something
4822 var c = document.getElementById("content");
4823 if (!c) return true;
4824 t = YAHOO.lang.trim(SUGAR.util.innerText(c));
4826 return SUGAR_callsInProgress != 0 || t == "";
4828 //Firefox doesn't support innerText (textContent includes script content)
4829 innerText : function(el) {
4830 if (el.tagName == "SCRIPT")
4832 if(typeof(el.innerText) == "string")
4833 return el.innerText;
4835 for (var i in el.childNodes){
4836 var c = el.childNodes[i];
4837 if (typeof(c) != "object")
4839 if (typeof(c.nodeName) == "string" && c.nodeName == "#text")
4842 t += SUGAR.util.innerText(c);
4847 callOnChangeListers: function(field){
4848 var listeners = YAHOO.util.Event.getListeners(field, 'change');
4849 if (listeners != null) {
4850 for (var i = 0; i < listeners.length; i++) {
4851 var l = listeners[i];
4852 l.fn.call(l.scope ? l.scope : this, l.obj);
4857 closeActivityPanel: {
4858 show:function(module,id,new_status,viewType,parentContainerId){
4859 if (SUGAR.util.closeActivityPanel.panel)
4860 SUGAR.util.closeActivityPanel.panel.destroy();
4861 var singleModule = SUGAR.language.get("app_list_strings", "moduleListSingular")[module];
4862 singleModule = typeof(singleModule != 'undefined') ? singleModule.toLowerCase() : '';
4863 var closeText = SUGAR.language.get("app_strings", "LBL_CLOSE_ACTIVITY_CONFIRM").replace("#module#",singleModule);
4864 SUGAR.util.closeActivityPanel.panel =
4865 new YAHOO.widget.SimpleDialog("closeActivityDialog",
4872 constraintoviewport: true,
4873 buttons: [ { text:SUGAR.language.get("app_strings", "LBL_EMAIL_OK"), handler:function(){
4874 if (SUGAR.util.closeActivityPanel.panel)
4875 SUGAR.util.closeActivityPanel.panel.hide();
4877 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_SAVING'));
4878 var args = "action=save&id=" + id + "&record=" + id + "&status=" + new_status + "&module=" + module;
4879 // 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
4880 // TODO: Take id out and regression test. Left id in for now to not create any other unexpected problems
4881 //var args = "action=save&id=" + id + "&status=" + new_status + "&module=" + module;
4885 // Bug 51984: We need to submit the form just incase we have a form already submitted
4886 // so we dont get a popup stating that the form needs to be resubmitted like it doesn,
4887 // when you do a reload/refresh
4888 window.setTimeout(function(){if(document.getElementById('search_form')) document.getElementById('search_form').submit(); else window.location.reload(true);}, 0);
4890 argument:{'parentContainerId':parentContainerId}
4893 YAHOO.util.Connect.asyncRequest('POST', 'index.php', callback, args);
4895 }, isDefault:true },
4896 { text:SUGAR.language.get("app_strings", "LBL_EMAIL_CANCEL"), handler:function(){SUGAR.util.closeActivityPanel.panel.hide(); }} ]
4899 SUGAR.util.closeActivityPanel.panel.setHeader(SUGAR.language.get("app_strings", "LBL_CLOSE_ACTIVITY_HEADER"));
4900 SUGAR.util.closeActivityPanel.panel.render(document.body);
4901 SUGAR.util.closeActivityPanel.panel.show();
4905 setEmailPasswordDisplay: function(id, exists, formName) {
4906 link = document.getElementById(id+'_link');
4907 pwd = document.getElementById(id);
4908 if(!pwd || !link) return;
4910 pwd.disabled = true;
4911 pwd.style.display = 'none';
4912 link.style.display = '';
4913 if(typeof(formName) != 'undefined')
4914 removeFromValidate(formName, id);
4916 pwd.disabled = false;
4917 pwd.style.display = '';
4918 link.style.display = 'none';
4922 setEmailPasswordEdit: function(id) {
4923 link = document.getElementById(id+'_link');
4924 pwd = document.getElementById(id);
4925 if(!pwd || !link) return;
4926 pwd.disabled = false;
4927 pwd.style.display = '';
4928 link.style.display = 'none';
4932 * Compares a filename with a supplied array of allowed file extensions.
4933 * @param fileName string
4934 * @param allowedTypes array of allowed file extensions
4937 validateFileExt: function(fileName, allowedTypes) {
4938 var ext = fileName.split('.').pop().toLowerCase();
4940 for (var i = allowedTypes.length; i >= 0; i--) {
4941 if (ext === allowedTypes[i]) {
4949 arrayIndexOf: function(arr, val, start) {
4950 if (typeof arr.indexOf == "function")
4951 return arr.indexOf(val, start);
4952 for (var i = (start || 0), j = arr.length; i < j; i++) {
4953 if (arr[i] === val) {
4961 SUGAR.clearRelateField = function(form, name, id)
4963 if (typeof form[name] == "object"){
4964 form[name].value = '';
4965 SUGAR.util.callOnChangeListers(form[name]);
4968 if (typeof form[id] == "object"){
4969 form[id].value = '';
4970 SUGAR.util.callOnChangeListers(form[id]);
4973 if(typeof(SUGAR.AutoComplete) == 'undefined') SUGAR.AutoComplete = {};
4975 SUGAR.AutoComplete.getOptionsArray = function(options_index){
4976 var return_arr = [];
4978 var opts = SUGAR.language.get('app_list_strings', options_index);
4979 if(typeof(opts) != 'undefined'){
4981 // Since we are using auto complete, we excluse blank dropdown entries since they can just leave it blank
4982 if(key != '' && opts[key] != ''){
4985 item['text'] = opts[key];
4986 return_arr.push(item);
4993 if(typeof(SUGAR.MultiEnumAutoComplete) == 'undefined') SUGAR.MultiEnumAutoComplete = {};
4995 SUGAR.MultiEnumAutoComplete.getMultiSelectKeysFromValues = function(options_index, val_string){
4996 var opts = SUGAR.language.get('app_list_strings', options_index);
4997 var selected_values = val_string.split(", ");
4998 // YUI AutoComplete adds a blank. We remove it automatically here
4999 if(selected_values.length > 0 && selected_values.indexOf('') == selected_values.length - 1){
5000 selected_values.pop();
5002 var final_arr = new Array();
5003 for(idx in selected_values){
5005 if(selected_values[idx] == opts[o_idx]){
5006 final_arr.push(o_idx);
5013 SUGAR.MultiEnumAutoComplete.getMultiSelectValuesFromKeys = function(options_index, val_string){
5014 var opts = SUGAR.language.get('app_list_strings', options_index);
5015 val_string=val_string.replace(/^\^/,'').replace(/\^$/,'') //fixes bug where string starts or ends with ^
5016 var selected_values = val_string.split("^,^");
5018 // YUI AutoComplete adds a blank. We remove it automatically here
5019 if(selected_values.length > 0 && selected_values.indexOf('') == selected_values.length - 1){
5020 selected_values.pop();
5023 var final_arr = new Array();
5024 for(idx in selected_values){
5026 if(selected_values[idx] == o_idx){
5027 final_arr.push(opts[o_idx]);
5034 function convertReportDateTimeToDB(dateValue, timeValue)
5036 var date_match = dateValue.match(date_reg_format);
5037 var time_match = timeValue.match(/([0-9]{1,2})\:([0-9]{1,2})([ap]m)/);
5038 if ( date_match != null && time_match != null) {
5039 time_match[1] = parseInt(time_match[1]);
5040 if (time_match[3] == 'pm') {
5041 time_match[1] = time_match[1] + 12;
5042 if (time_match[1] >= 24) {
5043 time_match[1] = time_match[1] - 24;
5045 } else if (time_match[3] == 'am' && time_match[1] == 12) {
5048 if (time_match[1] < 10) {
5049 time_match[1] = '0' + time_match[1];
5051 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';