1 /*********************************************************************************
2 * SugarCRM is a customer relationship management program developed by
3 * SugarCRM, Inc. Copyright (C) 2004-2011 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" ) SUGAR = {};
43 if ( typeof(SUGAR.themes) == "undefined" ) SUGAR.themes = {};
47 * Namespace for Homepage
51 * Namespace for Subpanel Utils
53 SUGAR.subpanelUtils= {};
57 SUGAR.ajaxStatusClass= {};
63 * General namespace for Sugar utils
71 SUGAR.unifiedSearchAdvanced= {};
76 SUGAR.contextMenu= {};
82 var requiredIndex = 2;
88 var compareToIndex = 7;
90 var operatorIndex = 13;
92 var validate = new Array();
94 var requiredTxt = 'Missing Required Field:'
95 var invalidTxt = 'Invalid Value:'
96 var secondsSinceLoad = 0;
97 var inputsWithErrors = new Array();
98 var tabsWithErrors = new Array();
99 var lastSubmitTime = 0;
100 var alertList = new Array();
101 var oldStartsWith = '';
104 function isSupportedIE() {
105 var userAgent = navigator.userAgent.toLowerCase() ;
107 // IE Check supports ActiveX controls
108 if (userAgent.indexOf("msie") != -1 && userAgent.indexOf("mac") == -1 && userAgent.indexOf("opera") == -1) {
109 var version = navigator.appVersion.match(/MSIE (.\..)/)[1] ;
110 if(version >= 5.5 ) {
118 SUGAR.isIE = isSupportedIE();
119 var isSafari = (navigator.userAgent.toLowerCase().indexOf('safari')!=-1);
121 // escapes regular expression characters
122 RegExp.escape = function(text) { // http://simon.incutio.com/archive/2006/01/20/escape
123 if (!arguments.callee.sRE) {
124 var specials = ['/', '.', '*', '+', '?', '|','(', ')', '[', ']', '{', '}', '\\'];
125 arguments.callee.sRE = new RegExp('(\\' + specials.join('|\\') + ')', 'g');
127 return text.replace(arguments.callee.sRE, '\\$1');
130 function addAlert(type, name,subtitle, description,time, redirect) {
131 var addIndex = alertList.length;
132 alertList[addIndex]= new Array();
133 alertList[addIndex]['name'] = name;
134 alertList[addIndex]['type'] = type;
135 alertList[addIndex]['subtitle'] = subtitle;
136 alertList[addIndex]['description'] = description.replace(/<br>/gi, "\n").replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');
137 alertList[addIndex]['time'] = time;
138 alertList[addIndex]['done'] = 0;
139 alertList[addIndex]['redirect'] = redirect;
141 function checkAlerts() {
142 secondsSinceLoad += 1;
145 for(mj = 0 ; mj < alertList.length; mj++) {
146 if(alertList[mj]['done'] == 0) {
147 if(alertList[mj]['time'] < secondsSinceLoad && alertList[mj]['time'] > -1 ) {
148 alertmsg = alertList[mj]['type'] + ":" + alertList[mj]['name'] + "\n" +alertList[mj]['subtitle']+ "\n"+ alertList[mj]['description'] + "\n\n";
149 alertList[mj]['done'] = 1;
150 if(alertList[mj]['redirect'] == '') {
153 else if(confirm(alertmsg)) {
154 window.location = alertList[mj]['redirect'];
160 setTimeout("checkAlerts()", 1000);
163 function toggleDisplay(id) {
164 if(this.document.getElementById(id).style.display == 'none') {
165 this.document.getElementById(id).style.display = '';
166 if(this.document.getElementById(id+"link") != undefined) {
167 this.document.getElementById(id+"link").style.display = 'none';
169 if(this.document.getElementById(id+"_anchor") != undefined)
170 this.document.getElementById(id+"_anchor").innerHTML='[ - ]';
173 this.document.getElementById(id).style.display = 'none'
174 if(this.document.getElementById(id+"link") != undefined) {
175 this.document.getElementById(id+"link").style.display = '';
177 if(this.document.getElementById(id+"_anchor") != undefined)
178 this.document.getElementById(id+"_anchor").innerHTML='[+]';
182 function checkAll(form, field, value) {
183 for (i = 0; i < form.elements.length; i++) {
184 if(form.elements[i].name == field)
185 form.elements[i].checked = value;
189 function replaceAll(text, src, rep) {
190 offset = text.toLowerCase().indexOf(src.toLowerCase());
191 while(offset != -1) {
192 text = text.substring(0, offset) + rep + text.substring(offset + src.length ,text.length);
193 offset = text.indexOf( src, offset + rep.length + 1);
198 function addForm(formname) {
199 validate[formname] = new Array();
202 function addToValidate(formname, name, type, required, msg) {
203 if(typeof validate[formname] == 'undefined') {
206 validate[formname][validate[formname].length] = new Array(name, type,required, msg);
209 function addToValidateRange(formname, name, type,required, msg,min,max) {
210 addToValidate(formname, name, type,required, msg);
211 validate[formname][validate[formname].length - 1][jstypeIndex] = 'range'
212 validate[formname][validate[formname].length - 1][minIndex] = min;
213 validate[formname][validate[formname].length - 1][maxIndex] = max;
216 function addToValidateIsValidDate(formname, name, type, required, msg) {
217 addToValidate(formname, name, type, required, msg);
218 validate[formname][validate[formname].length - 1][jstypeIndex] = 'date'
221 function addToValidateIsValidTime(formname, name, type, required, msg) {
222 addToValidate(formname, name, type, required, msg);
223 validate[formname][validate[formname].length - 1][jstypeIndex] = 'time'
226 function addToValidateDateBefore(formname, name, type, required, msg, compareTo) {
227 addToValidate(formname, name, type,required, msg);
228 validate[formname][validate[formname].length - 1][jstypeIndex] = 'isbefore'
229 validate[formname][validate[formname].length - 1][compareToIndex] = compareTo;
232 function addToValidateDateBeforeAllowBlank(formname, name, type, required, msg, compareTo, allowBlank) {
233 addToValidate(formname, name, type,required, msg);
234 validate[formname][validate[formname].length - 1][jstypeIndex] = 'isbefore'
235 validate[formname][validate[formname].length - 1][compareToIndex] = compareTo;
236 validate[formname][validate[formname].length - 1][allowblank] = allowBlank;
239 function addToValidateBinaryDependency(formname, name, type, required, msg, compareTo) {
240 addToValidate(formname, name, type, required, msg);
241 validate[formname][validate[formname].length - 1][jstypeIndex] = 'binarydep';
242 validate[formname][validate[formname].length - 1][compareToIndex] = compareTo;
245 function addToValidateComparison(formname, name, type, required, msg, compareTo) {
246 addToValidate(formname, name, type, required, msg);
247 validate[formname][validate[formname].length - 1][jstypeIndex] = 'comparison';
248 validate[formname][validate[formname].length - 1][compareToIndex] = compareTo;
251 function addToValidateIsInArray(formname, name, type, required, msg, arr, operator) {
252 addToValidate(formname, name, type, required, msg);
253 validate[formname][validate[formname].length - 1][jstypeIndex] = 'in_array';
254 validate[formname][validate[formname].length - 1][arrIndex] = arr;
255 validate[formname][validate[formname].length - 1][operatorIndex] = operator;
258 function addToValidateVerified(formname, name, type, required, msg, arr, operator) {
259 addToValidate(formname, name, type, required, msg);
260 validate[formname][validate[formname].length - 1][jstypeIndex] = 'verified';
263 function addToValidateLessThan(formname, name, type, required, msg, max, max_field_msg) {
264 addToValidate(formname, name, type, required, msg);
265 validate[formname][validate[formname].length - 1][jstypeIndex] = 'less';
266 validate[formname][validate[formname].length - 1][maxIndex] = max;
267 validate[formname][validate[formname].length - 1][altMsgIndex] = max_field_msg;
270 function addToValidateMoreThan(formname, name, type, required, msg, min) {
271 addToValidate(formname, name, type, required, msg);
272 validate[formname][validate[formname].length - 1][jstypeIndex] = 'more';
273 validate[formname][validate[formname].length - 1][minIndex] = min;
277 function removeFromValidate(formname, name) {
278 for(i = 0; i < validate[formname].length; i++)
280 if(validate[formname][i][nameIndex] == name)
282 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
286 function checkValidate(formname, name) {
287 if(validate[formname]){
288 for(i = 0; i < validate[formname].length; i++){
289 if(validate[formname][i][nameIndex] == name){
296 var formsWithFieldLogic=null;
297 var formWithPrecision =null;
298 function addToValidateFieldLogic(formId,minFieldId, maxFieldId, defaultFieldId, lenFieldId,type,msg){
299 this.formId = document.getElementById(formId);
300 this.min=document.getElementById(minFieldId);
301 this.max= document.getElementById(maxFieldId);
302 this._default= document.getElementById(defaultFieldId);
303 this.len = document.getElementById(lenFieldId);
307 //@params: formid- Dom id of the form containing the precision and float fields
308 // valudId- Dom id of the field containing a float whose precision is to be checked.
309 // precisionId- Dom id of the field containing precision value.
310 function addToValidatePrecision(formId, valueId, precisionId){
311 this.form = document.getElementById(formId);
312 this.float = document.getElementById(valueId);
313 this.precision = document.getElementById(precisionId);
316 //function checkLength(value, referenceValue){
320 function isValidPrecision(value, precision){
321 value = trim(value.toString());
327 if( (precision == "0") ){
328 if (value.indexOf(".")== -1){
335 var actualPrecision = value.substr(value.indexOf(".")+1, value.length).length;
336 return actualPrecision == precision;
338 function toDecimal(original, precision) {
339 precision = (precision == null) ? 2 : precision;
340 num = Math.pow(10, precision);
341 temp = Math.round(original*num)/num;
342 if((temp * 100) % 100 == 0)
344 if((temp * 10) % 10 == 0)
349 function isInteger(s) {
350 if (typeof s == "string" && s == "")
352 if(typeof num_grp_sep != 'undefined' && typeof dec_sep != 'undefined')
354 s = unformatNumberNoParse(s, num_grp_sep, dec_sep).toString();
356 return parseFloat(s) == parseInt(s) && !isNaN(s);
359 function isNumeric(s) {
360 if(!/^-*[0-9\.]+$/.test(s)) {
368 var date_reg_positions = {'Y': 1,'m': 2,'d': 3};
369 var date_reg_format = '([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})'
370 function isDate(dtStr) {
372 if(dtStr.length== 0) {
376 // Check that we have numbers
377 myregexp = new RegExp(date_reg_format)
378 if(!myregexp.test(dtStr))
385 var dateParts = dtStr.match(date_reg_format);
386 for(key in date_reg_positions) {
387 index = date_reg_positions[key];
389 m = dateParts[index];
390 } else if(key == 'd') {
391 d = dateParts[index];
393 y = dateParts[index];
397 // Check that date is real
398 var dd = new Date(y,m,0);
399 // reject negative years
402 // reject month less than 1 and greater than 12
405 // reject days less than 1 or days not in month (e.g. February 30th)
406 if (d < 1 || d > dd.getDate())
411 function getDateObject(dtStr) {
412 if(dtStr.length== 0) {
416 myregexp = new RegExp(date_reg_format)
418 if(myregexp.exec(dtStr)) var dt = myregexp.exec(dtStr)
421 var yr = dt[date_reg_positions['Y']];
422 var mh = dt[date_reg_positions['m']];
423 var dy = dt[date_reg_positions['d']];
424 var dtar = dtStr.split(' ');
425 if(typeof(dtar[1])!='undefined' && isTime(dtar[1])) {//if it is a timedate, we should make date1 to have time value
426 var t1 = dtar[1].replace(/am/i,' AM');
427 var t1 = t1.replace(/pm/i,' PM');
428 //bug #37977: where time format 23.00 causes java script error
429 t1=t1.replace(/\./, ':');
430 date1 = new Date(Date.parse(mh+'/'+dy+ '/'+yr+' '+t1));
434 var date1 = new Date();
435 date1.setFullYear(yr); // xxxx 4 char year
436 date1.setMonth(mh-1); // 0-11 Bug 4048: javascript Date obj months are 0-index
437 date1.setDate(dy); // 1-31
442 function isBefore(value1, value2) {
443 var d1 = getDateObject(value1);
444 var d2 = getDateObject(value2);
445 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.
451 function isValidEmail(emailStr) {
452 if(emailStr.length== 0) {
456 // cn: bug 7128, a period at the end of the string mangles checks. (switched to accept spaces and delimiters)
457 var lastChar = emailStr.charAt(emailStr.length - 1);
458 if(!lastChar.match(/[^\.]/i)) {
461 //bug 40068, According to rules in page 6 of http://www.apps.ietf.org/rfc/rfc3696.html#sec-3,
462 //first character of local part of an email address
463 //should not be a period i.e. '.'
465 var firstLocalChar=emailStr.charAt(0);
466 if(firstLocalChar.match(/\./)){
470 //bug 40068, According to rules in page 6 of http://www.apps.ietf.org/rfc/rfc3696.html#sec-3,
471 //last character of local part of an email address
472 //should not be a period i.e. '.'
474 var pos=emailStr.lastIndexOf("@");
475 var localPart = emailStr.substr(0, pos);
476 var lastLocalChar=localPart.charAt(localPart.length - 1);
477 if(lastLocalChar.match(/\./)){
483 while ((results = reg.exec(emailStr)) != null) {
484 orignial = results[0];
485 parsedResult = results[0].replace(';', '::;::');
486 emailStr = emailStr.replace (orignial, parsedResult);
490 while ((results = reg.exec(emailStr)) != null) {
491 orignial = results[0];
492 var check = results[0].substr(1);// bug 42259 - "Error Encountered When Trying to Send to Multiple Recipients with Commas in Name"
493 // if condition to check the presence of @ charcater before replacing ','
494 //now if ',' is used to separate two email addresses, then only it will be replaced by ::;::
495 //if name has ',' e.g. smith, jr ',' will not be replaced (which was causing the given problem)
496 if(check.indexOf('@') !=-1){
497 parsedResult = results[0].replace(',', '::;::');
498 emailStr = emailStr.replace (orignial, parsedResult);
502 // mfh: bug 15010 - more practical implementation of RFC 2822 from http://www.regular-expressions.info/email.html, modifed to accept CAPITAL LETTERS
503 //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))
506 //bug 40068, According to rules in page 6 of http://www.apps.ietf.org/rfc/rfc3696.html#sec-3,
507 //allowed special characters ! # $ % & ' * + - / = ? ^ _ ` . { | } ~ in local part
508 var emailArr = emailStr.split(/::;::/);
509 for (var i = 0; i < emailArr.length; i++) {
510 emailAddress = emailArr[i];
511 if (trim(emailAddress) != '') {
512 if(!/^\s*[\w.%+\-&'#!\$\*=\?\^_`\{\}~\/]+@([A-Z0-9-]+\.)*[A-Z0-9-]+\.[\w-]{2,}\s*$/i.test(emailAddress) &&
513 !/^.*<[A-Z0-9._%+\-&'#!\$\*=\?\^_`\{\}~]+?@([A-Z0-9-]+\.)*[A-Z0-9-]+\.[\w-]{2,}>\s*$/i.test(emailAddress)) {
522 function isValidPhone(phoneStr) {
523 if(phoneStr.length== 0) {
526 if(!/^[0-9\-\(\)\s]+$/.test(phoneStr))
530 function isFloat(floatStr) {
531 if(floatStr.length== 0) {
534 if(!(typeof(num_grp_sep)=='undefined' || typeof(dec_sep)=='undefined')) {
535 floatStr = unformatNumberNoParse(floatStr, num_grp_sep, dec_sep).toString();
538 return /^(-)?[0-9\.]+$/.test(floatStr);
540 function isDBName(str) {
545 // must start with a letter
546 if(!/^[a-zA-Z][a-zA-Z\_0-9]*$/.test(str))
550 var time_reg_format = "[0-9]{1,2}\:[0-9]{2}";
551 function isTime(timeStr) {
552 time_reg_format = time_reg_format.replace('([ap]m)', '');
553 time_reg_format = time_reg_format.replace('([AP]M)', '');
554 if(timeStr.length== 0){
557 //we now support multiple time formats
558 myregexp = new RegExp(time_reg_format)
559 if(!myregexp.test(timeStr))
565 function inRange(value, min, max) {
566 if (typeof num_grp_sep != 'undefined' && typeof dec_sep != 'undefined')
567 value = unformatNumberNoParse(value, num_grp_sep, dec_sep).toString();
568 return value >= min && value <= max;
571 function bothExist(item1, item2) {
572 if(typeof item1 == 'undefined') { return false; }
573 if(typeof item2 == 'undefined') { return false; }
574 if((item1 == '' && item2 != '') || (item1 != '' && item2 == '') ) { return false; }
578 trim = YAHOO.lang.trim;
581 function check_form(formname) {
582 if (typeof(siw) != 'undefined' && siw
583 && typeof(siw.selectingSomething) != 'undefined' && siw.selectingSomething)
585 return validate_form(formname, '');
588 function add_error_style(formname, input, txt, flash) {
589 if (typeof flash == "undefined")
592 inputHandle = typeof input == "object" ? input : document.forms[formname][input];
593 style = get_current_bgcolor(inputHandle);
595 // strip off the colon at the end of the warning strings
596 if ( txt.substring(txt.length-1) == ':' )
597 txt = txt.substring(0,txt.length-1)
599 // Bug 28249 - To help avoid duplicate messages for an element, strip off extra messages and
600 // match on the field name itself
601 requiredTxt = SUGAR.language.get('app_strings', 'ERR_MISSING_REQUIRED_FIELDS');
602 invalidTxt = SUGAR.language.get('app_strings', 'ERR_INVALID_VALUE');
603 nomatchTxt = SUGAR.language.get('app_strings', 'ERR_SQS_NO_MATCH_FIELD');
604 matchTxt = txt.replace(requiredTxt,'').replace(invalidTxt,'').replace(nomatchTxt,'');
606 if(inputHandle.parentNode.innerHTML.search(matchTxt) == -1) {
607 errorTextNode = document.createElement('span');
608 errorTextNode.className = 'required';
609 errorTextNode.innerHTML = '<br />' + txt;
610 if ( inputHandle.parentNode.className.indexOf('x-form-field-wrap') != -1 ) {
611 inputHandle.parentNode.parentNode.appendChild(errorTextNode);
614 inputHandle.parentNode.appendChild(errorTextNode);
617 inputHandle.style.backgroundColor = "#FF0000";
618 inputsWithErrors.push(inputHandle);
622 // We only need to setup the flashy-flashy on the first entry, it loops through all fields automatically
623 if ( inputsWithErrors.length == 1 ) {
624 for(wp = 1; wp <= 10; wp++) {
625 window.setTimeout('fade_error_style(style, '+wp*10+')',1000+(wp*50));
628 if(typeof (window[formname + "_tabs"]) != "undefined") {
629 var tabView = window[formname + "_tabs"];
630 var parentDiv = YAHOO.util.Dom.getAncestorByTagName(inputHandle, "div");
632 var tabs = tabView.get("tabs");
633 for (var i in tabs) {
634 if (tabs[i].get("contentEl") == parentDiv
635 || YAHOO.util.Dom.isAncestor(tabs[i].get("contentEl"), inputHandle))
637 tabs[i].get("labelEl").style.color = "red";
638 if ( inputsWithErrors.length == 1 )
639 tabView.selectTab(i);
644 window.setTimeout("inputsWithErrors[" + (inputsWithErrors.length - 1) + "].style.backgroundColor = null;", 2000);
648 // Catch errors here so we don't allow an incomplete record through the javascript validation
653 * removes all error messages for the current form
655 function clear_all_errors() {
656 for(var wp = 0; wp < inputsWithErrors.length; wp++) {
657 if(typeof(inputsWithErrors[wp]) !='undefined' && typeof inputsWithErrors[wp].parentNode != 'undefined' && inputsWithErrors[wp].parentNode != null) {
658 if ( inputsWithErrors[wp].parentNode.className.indexOf('x-form-field-wrap') != -1 )
660 inputsWithErrors[wp].parentNode.parentNode.removeChild(inputsWithErrors[wp].parentNode.parentNode.lastChild);
664 inputsWithErrors[wp].parentNode.removeChild(inputsWithErrors[wp].parentNode.lastChild);
668 if (inputsWithErrors.length == 0) return;
670 if ( YAHOO.util.Dom.getAncestorByTagName(inputsWithErrors[0], "form") ) {
671 var formname = YAHOO.util.Dom.getAncestorByTagName(inputsWithErrors[0], "form").getAttribute("name");
672 if(typeof (window[formname + "_tabs"]) != "undefined") {
673 var tabView = window[formname + "_tabs"];
675 var tabs = tabView.get("tabs");
676 for (var i in tabs) {
677 tabs[i].get("labelEl").style.color = "";
681 inputsWithErrors = new Array();
685 function get_current_bgcolor(input) {
686 if(input.currentStyle) {// ie
687 style = input.currentStyle.backgroundColor;
688 return style.substring(1,7);
692 styleRGB = document.defaultView.getComputedStyle(input, '').getPropertyValue("background-color");
693 comma = styleRGB.indexOf(',');
694 style += dec2hex(styleRGB.substring(4, comma));
695 commaPrevious = comma;
696 comma = styleRGB.indexOf(',', commaPrevious+1);
697 style += dec2hex(styleRGB.substring(commaPrevious+2, comma));
698 style += dec2hex(styleRGB.substring(comma+2, styleRGB.lastIndexOf(')')));
703 function hex2dec(hex){return(parseInt(hex,16));}
704 var hexDigit=new Array("0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F");
705 function dec2hex(dec){return(hexDigit[dec>>4]+hexDigit[dec&15]);}
707 function fade_error_style(normalStyle, percent) {
708 errorStyle = 'c60c30';
709 var r1 = hex2dec(errorStyle.slice(0,2));
710 var g1 = hex2dec(errorStyle.slice(2,4));
711 var b1 = hex2dec(errorStyle.slice(4,6));
713 var r2 = hex2dec(normalStyle.slice(0,2));
714 var g2 = hex2dec(normalStyle.slice(2,4));
715 var b2 = hex2dec(normalStyle.slice(4,6));
718 var pc = percent / 100;
720 r= Math.floor(r1+(pc*(r2-r1)) + .5);
721 g= Math.floor(g1+(pc*(g2-g1)) + .5);
722 b= Math.floor(b1+(pc*(b2-b1)) + .5);
724 for(var wp = 0; wp < inputsWithErrors.length; wp++) {
725 inputsWithErrors[wp].style.backgroundColor = "#" + dec2hex(r) + dec2hex(g) + dec2hex(b);
729 function isFieldTypeExceptFromEmptyCheck(fieldType)
732 var exemptList = ['bool','file'];
733 for(var i=0;i<exemptList.length;i++)
735 if(fieldType == exemptList[i])
740 function validate_form(formname, startsWith){
741 requiredTxt = SUGAR.language.get('app_strings', 'ERR_MISSING_REQUIRED_FIELDS');
742 invalidTxt = SUGAR.language.get('app_strings', 'ERR_INVALID_VALUE');
744 if ( typeof (formname) == 'undefined')
748 if ( typeof (validate[formname]) == 'undefined')
750 disableOnUnloadEditView(document.forms[formname]);
754 var form = document.forms[formname];
757 var _date = new Date();
758 if(_date.getTime() < (lastSubmitTime + 2000) && startsWith == oldStartsWith) { // ignore submits for the next 2 seconds
761 lastSubmitTime = _date.getTime();
762 oldStartsWith = startsWith;
764 clear_all_errors(); // remove previous error messages
766 inputsWithErrors = new Array();
767 for(var i = 0; i < validate[formname].length; i++){
768 if(validate[formname][i][nameIndex].indexOf(startsWith) == 0){
769 if(typeof form[validate[formname][i][nameIndex]] != 'undefined'){
772 //If a field is not required and it is blank or is binarydependant, skip validation.
773 //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
774 if(!validate[formname][i][requiredIndex] && trim(form[validate[formname][i][nameIndex]].value) == '' && (typeof(validate[formname][i][jstypeIndex]) != 'undefined' && validate[formname][i][jstypeIndex] != 'binarydep'))
779 if(validate[formname][i][requiredIndex]
780 && !isFieldTypeExceptFromEmptyCheck(validate[formname][i][typeIndex])
782 if(typeof form[validate[formname][i][nameIndex]] == 'undefined' || trim(form[validate[formname][i][nameIndex]].value) == ""){
783 add_error_style(formname, validate[formname][i][nameIndex], requiredTxt +' ' + validate[formname][i][msgIndex]);
788 switch(validate[formname][i][typeIndex]){
790 if(!isValidEmail(trim(form[validate[formname][i][nameIndex]].value))){
792 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
796 if( !isTime(trim(form[validate[formname][i][nameIndex]].value))){
798 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
800 case 'date': if(!isDate(trim(form[validate[formname][i][nameIndex]].value))){
802 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
807 if(!isDBName(trim(form[validate[formname][i][nameIndex]].value))){
809 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
815 if( validate[formname][i][requiredIndex] && typeof( form[validate[formname][i][nameIndex] + '_file'] ) != 'undefined' && trim( form[validate[formname][i][nameIndex] + '_file'].value) == "" && !form[validate[formname][i][nameIndex] + '_file'].disabled ) {
817 add_error_style(formname, validate[formname][i][nameIndex], requiredTxt + " " + validate[formname][i][msgIndex]);
821 if(!isInteger(trim(form[validate[formname][i][nameIndex]].value))){
823 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
828 if(!isFloat(trim(form[validate[formname][i][nameIndex]].value))){
830 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
834 div_element_id = formname + '_' + form[validate[formname][i][nameIndex]].name + '_operation_div';
835 input_elements = YAHOO.util.Selector.query('input', document.getElementById(div_element_id));
836 primary_field_id = '';
837 validation_passed = false;
838 replace_selected = false;
840 //Loop through the option elements (replace or add currently)
841 for(t in input_elements) {
842 if(input_elements[t].type && input_elements[t].type == 'radio' && input_elements[t].checked == true && input_elements[t].value == 'replace') {
844 //Now find where the primary radio button is and if a value has been set
845 radio_elements = YAHOO.util.Selector.query('input[type=radio]', document.getElementById(formname + '_team_name_table'));
847 for(x in radio_elements) {
848 if(radio_elements[x].name != 'team_name_type') {
849 primary_field_id = 'team_name_collection_' + radio_elements[x].value;
850 if(radio_elements[x].checked) {
851 replace_selected = true;
852 if(trim(document.forms[formname].elements[primary_field_id].value) != '') {
853 validation_passed = true;
856 } else if(trim(document.forms[formname].elements[primary_field_id].value) != '') {
857 replace_selected = true;
864 if(replace_selected && !validation_passed) {
865 add_error_style(formname, primary_field_id, SUGAR.language.get('app_strings', 'ERR_NO_PRIMARY_TEAM_SPECIFIED'));
870 table_element_id = formname + '_' + form[validate[formname][i][nameIndex]].name + '_table';
871 if(document.getElementById(table_element_id)) {
872 input_elements = YAHOO.util.Selector.query('input[type=radio]', document.getElementById(table_element_id));
874 primary_field_id = form[validate[formname][i][nameIndex]].name + '_collection_0';
876 for(t in input_elements) {
877 primary_field_id = form[validate[formname][i][nameIndex]].name + '_collection_' + input_elements[t].value;
878 if(input_elements[t].type && input_elements[t].type == 'radio' && input_elements[t].checked == true) {
879 if(document.forms[formname].elements[primary_field_id].value != '') {
888 field_id = form[validate[formname][i][nameIndex]].name + '_collection_' + input_elements[0].value;
889 add_error_style(formname, field_id, SUGAR.language.get('app_strings', 'ERR_NO_PRIMARY_TEAM_SPECIFIED'));
895 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex]);
899 if(typeof validate[formname][i][jstypeIndex] != 'undefined'/* && !isError*/){
901 switch(validate[formname][i][jstypeIndex]){
903 if(!inRange(trim(form[validate[formname][i][nameIndex]].value), validate[formname][i][minIndex], validate[formname][i][maxIndex])){
905 var lbl_validate_range = SUGAR.language.get('app_strings', 'LBL_VALIDATE_RANGE');
906 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] + ") ");
910 compareTo = form[validate[formname][i][compareToIndex]];
911 if( typeof compareTo != 'undefined'){
912 if(trim(compareTo.value) != '' || (validate[formname][i][allowblank] != 'true') ) {
913 date2 = trim(compareTo.value);
914 date1 = trim(form[validate[formname][i][nameIndex]].value);
916 if(trim(date1).length != 0 && !isBefore(date1,date2)){
919 //jc:#12287 - adding translation for the is not before message
920 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex] + "(" + date1 + ") " + SUGAR.language.get('app_strings', 'MSG_IS_NOT_BEFORE') + ' ' +date2);
926 value=unformatNumber(trim(form[validate[formname][i][nameIndex]].value), num_grp_sep, dec_sep);
927 maximum = parseFloat(validate[formname][i][maxIndex]);
928 if( typeof maximum != 'undefined'){
931 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]);
936 value=unformatNumber(trim(form[validate[formname][i][nameIndex]].value), num_grp_sep, dec_sep);
937 minimum = parseFloat(validate[formname][i][minIndex]);
938 if( typeof minimum != 'undefined'){
941 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'));
946 compareTo = form[validate[formname][i][compareToIndex]];
947 if( typeof compareTo != 'undefined') {
948 item1 = trim(form[validate[formname][i][nameIndex]].value);
949 item2 = trim(compareTo.value);
950 if(!bothExist(item1, item2)) {
952 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex]);
957 compareTo = form[validate[formname][i][compareToIndex]];
958 if( typeof compareTo != 'undefined') {
959 item1 = trim(form[validate[formname][i][nameIndex]].value);
960 item2 = trim(compareTo.value);
961 if(!bothExist(item1, item2) || item1 != item2) {
963 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex]);
968 arr = eval(validate[formname][i][arrIndex]);
969 operator = validate[formname][i][operatorIndex];
970 item1 = trim(form[validate[formname][i][nameIndex]].value);
971 if (operator.charAt(0) == 'u') {
972 item1 = item1.toUpperCase();
973 operator = operator.substring(1);
974 } else if (operator.charAt(0) == 'l') {
975 item1 = item1.toLowerCase();
976 operator = operator.substring(1);
978 for(j = 0; j < arr.length; j++){
980 if((operator == "==" && val == item1) || (operator == "!=" && val != item1)){
982 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
987 if(trim(form[validate[formname][i][nameIndex]].value) == 'false'){
988 //Fake an error so form does not submit
999 Check min max default field logic.
1000 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.*/
1001 if(formsWithFieldLogic){
1002 var invalidLogic=false;
1003 if(formsWithFieldLogic.min && formsWithFieldLogic.max && formsWithFieldLogic._default) {
1004 var showErrorsOn={min:{value:'min', show:false, obj:formsWithFieldLogic.min.value},
1005 max:{value:'max',show:false, obj:formsWithFieldLogic.max.value},
1006 _default:{value:'default',show:false, obj:formsWithFieldLogic._default.value},
1007 len:{value:'len', show:false, obj:parseInt(formsWithFieldLogic.len.value,10)}};
1009 var min = (formsWithFieldLogic.min.value !='') ? parseFloat(formsWithFieldLogic.min.value) : 'undef';
1010 var max = (formsWithFieldLogic.max.value !='') ? parseFloat(formsWithFieldLogic.max.value) : 'undef';
1011 var _default = (formsWithFieldLogic._default.value!='')? parseFloat(formsWithFieldLogic._default.value) : 'undef';
1013 /*Check all lengths are <= max size.*/
1014 for(var i in showErrorsOn){
1015 if(showErrorsOn[i].value!='len' && showErrorsOn[i].obj.length > showErrorsOn.len.obj){
1017 showErrorsOn[i].show=true;
1018 showErrorsOn.len.show=true;
1022 if(min!='undef' && max!='undef' && _default!='undef'){
1023 if(!inRange(_default,min,max)){
1025 showErrorsOn.min.show=true;
1026 showErrorsOn.max.show=true;
1027 showErrorsOn._default.show=true;
1030 if(min!='undef' && max!= 'undef' && min > max){
1031 invalidLogic = true;
1032 showErrorsOn.min.show=true;
1033 showErrorsOn.max.show=true;
1035 if(min!='undef' && _default!='undef' && _default < min){
1037 invalidLogic = true;
1038 showErrorsOn.min.show=true;
1039 showErrorsOn._default.show=true;
1041 if(max!='undef' && _default !='undef' && _default>max){
1043 invalidLogic = true;
1044 showErrorsOn.max.show=true;
1045 showErrorsOn._default.show=true;
1050 for(var error in showErrorsOn)
1051 if(showErrorsOn[error].show)
1052 add_error_style(formname,showErrorsOn[error].value, formsWithFieldLogic.msg);
1057 formsWithFieldLogic = null;
1060 if(formWithPrecision){
1061 if (!isValidPrecision(formWithPrecision.float.value, formWithPrecision.precision.value)){
1063 add_error_style(formname, 'default', SUGAR.language.get('app_strings', 'ERR_COMPATIBLE_PRECISION_VALUE'));
1071 if (isError == true) {
1073 if (self.pageYOffset) // all except Explorer
1075 nwX = self.pageXOffset;
1076 seX = self.innerWidth;
1077 nwY = self.pageYOffset;
1078 seY = self.innerHeight;
1080 else if (document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
1082 nwX = document.documentElement.scrollLeft;
1083 seX = document.documentElement.clientWidth;
1084 nwY = document.documentElement.scrollTop;
1085 seY = document.documentElement.clientHeight;
1087 else if (document.body) // all other Explorers
1089 nwX = document.body.scrollLeft;
1090 seX = document.body.clientWidth;
1091 nwY = document.body.scrollTop;
1092 seY = document.body.clientHeight;
1095 var inView = true; // is there an error within viewport of browser
1096 for(var wp = 0; wp < inputsWithErrors.length; wp++) {
1097 var elementCoor = findElementPos(inputsWithErrors[wp]);
1098 if(!(elementCoor.x >= nwX && elementCoor.y >= nwY &&
1099 elementCoor.x <= seX && elementCoor.y <= seY)) { // if input is not within viewport
1101 scrollToTop = elementCoor.y - 75;
1102 scrollToLeft = elementCoor.x - 75;
1104 else { // on first input within viewport, don't scroll
1110 if(!inView) window.scrollTo(scrollToLeft,scrollToTop);
1115 disableOnUnloadEditView(form);
1122 * This array is used to remember mark status of rows in browse mode
1124 var marked_row = new Array;
1128 * Sets/unsets the pointer and marker in browse mode
1130 * @param object the table row
1131 * @param interger the row number
1132 * @param string the action calling this script (over, out or click)
1133 * @param string the default background color
1134 * @param string the color to use for mouseover
1135 * @param string the color to use for marking a row
1137 * @return boolean whether pointer is set or not
1139 function setPointer(theRow, theRowNum, theAction, theDefaultColor, thePointerColor, theMarkColor) {
1140 var theCells = null;
1142 // 1. Pointer and mark feature are disabled or the browser can't get the
1144 if ((thePointerColor == '' && theMarkColor == '')
1145 || typeof(theRow.style) == 'undefined') {
1149 // 2. Gets the current row and exits if the browser can't get it
1150 if (typeof(document.getElementsByTagName) != 'undefined') {
1151 theCells = theRow.getElementsByTagName('td');
1153 else if (typeof(theRow.cells) != 'undefined') {
1154 theCells = theRow.cells;
1160 // 3. Gets the current color...
1161 var rowCellsCnt = theCells.length;
1162 var domDetect = null;
1163 var currentColor = null;
1164 var newColor = null;
1165 // 3.1 ... with DOM compatible browsers except Opera that does not return
1166 // valid values with "getAttribute"
1167 if (typeof(window.opera) == 'undefined'
1168 && typeof(theCells[0].getAttribute) != 'undefined') {
1169 currentColor = theCells[0].getAttribute('bgcolor');
1172 // 3.2 ... with other browsers
1174 currentColor = theCells[0].style.backgroundColor;
1178 // 4. Defines the new color
1179 // 4.1 Current color is the default one
1180 if (currentColor == ''
1181 || (currentColor!= null && (currentColor.toLowerCase() == theDefaultColor.toLowerCase()))) {
1182 if (theAction == 'over' && thePointerColor != '') {
1183 newColor = thePointerColor;
1185 else if (theAction == 'click' && theMarkColor != '') {
1186 newColor = theMarkColor;
1187 marked_row[theRowNum] = true;
1190 // 4.1.2 Current color is the pointer one
1191 else if (currentColor!= null && (currentColor.toLowerCase() == thePointerColor.toLowerCase())
1192 && (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])) {
1193 if (theAction == 'out') {
1194 newColor = theDefaultColor;
1196 else if (theAction == 'click' && theMarkColor != '') {
1197 newColor = theMarkColor;
1198 marked_row[theRowNum] = true;
1201 // 4.1.3 Current color is the marker one
1202 else if (currentColor!= null && (currentColor.toLowerCase() == theMarkColor.toLowerCase())) {
1203 if (theAction == 'click') {
1204 newColor = (thePointerColor != '')
1207 marked_row[theRowNum] = (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])
1213 // 5. Sets the new color...
1216 // 5.1 ... with DOM compatible browsers except Opera
1218 for (c = 0; c < rowCellsCnt; c++) {
1219 theCells[c].setAttribute('bgcolor', newColor, 0);
1222 // 5.2 ... with other browsers
1224 for (c = 0; c < rowCellsCnt; c++) {
1225 theCells[c].style.backgroundColor = newColor;
1231 } // end of the 'setPointer()' function
1235 * listbox redirection
1237 function goToUrl(selObj, goToLocation) {
1238 eval("document.location.href = '" + goToLocation + "pos=" + selObj.options[selObj.selectedIndex].value + "'");
1243 var json_objects = new Object();
1245 function getXMLHTTPinstance() {
1246 var xmlhttp = false;
1247 var userAgent = navigator.userAgent.toLowerCase() ;
1249 // IE Check supports ActiveX controls
1250 if (userAgent.indexOf("msie") != -1 && userAgent.indexOf("mac") == -1 && userAgent.indexOf("opera") == -1) {
1251 var version = navigator.appVersion.match(/MSIE (.\..)/)[1] ;
1252 if(version >= 5.5 ) {
1254 xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
1258 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
1267 if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
1268 xmlhttp = new XMLHttpRequest();
1273 // NOW LOAD THE OBJECT..
1274 var global_xmlhttp = getXMLHTTPinstance();
1276 function http_fetch_sync(url,post_data) {
1277 global_xmlhttp = getXMLHTTPinstance();
1280 if(typeof(post_data) != 'undefined') method = 'POST';
1282 global_xmlhttp.open(method, url,false);
1285 alert('message:'+e.message+":url:"+url);
1287 if(method == 'POST') {
1288 global_xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
1291 global_xmlhttp.send(post_data);
1293 if (SUGAR.util.isLoginPage(global_xmlhttp.responseText))
1296 var args = {"responseText" : global_xmlhttp.responseText,
1297 "responseXML" : global_xmlhttp.responseXML,
1298 "request_id" : typeof(request_id) != "undefined" ? request_id : 0};
1302 // this is a GET unless post_data is defined
1304 function http_fetch_async(url,callback,request_id,post_data) {
1306 if(typeof(post_data) != 'undefined') {
1311 global_xmlhttp.open(method, url,true);
1314 alert('message:'+e.message+":url:"+url);
1316 if(method == 'POST') {
1317 global_xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
1319 global_xmlhttp.onreadystatechange = function() {
1320 if(global_xmlhttp.readyState==4) {
1321 if(global_xmlhttp.status == 200) {
1322 if (SUGAR.util.isLoginPage(global_xmlhttp.responseText))
1324 var args = {"responseText" : global_xmlhttp.responseText,
1325 "responseXML" : global_xmlhttp.responseXML,
1326 "request_id" : request_id };
1327 callback.call(document,args);
1330 alert("There was a problem retrieving the XML data:\n" + global_xmlhttp.statusText);
1334 global_xmlhttp.send(post_data);
1337 function call_json_method(module,action,vars,variable_name,callback) {
1338 global_xmlhttp.open("GET", "index.php?entryPoint=json&module="+module+"&action="+action+"&"+vars,true);
1339 global_xmlhttp.onreadystatechange=
1341 if(global_xmlhttp.readyState==4) {
1342 if(global_xmlhttp.status == 200) {
1343 // cn: bug 12274 - pass through JSON.parse() to remove security envelope
1344 json_objects[variable_name] = JSON.parse(global_xmlhttp.responseText);
1346 // cn: bug 12274 - safe from CSRF, render response as expected
1347 var respText = JSON.parseNoSecurity(global_xmlhttp.responseText);
1348 var args = {responseText:respText, responseXML:global_xmlhttp.responseXML};
1349 callback.call(document, args);
1352 alert("There was a problem retrieving the XML data:\n" + global_xmlhttp.statusText);
1356 global_xmlhttp.send(null);
1359 function insert_at_cursor(field, value) {
1361 if (document.selection) {
1363 sel = document.selection.createRange();
1367 else if(field.selectionStart || field.selectionStart == '0') {
1368 var start_pos = field.selectionStart;
1369 var end_pos = field.selectionEnd;
1370 field.value = field.value.substring(0, start_pos) + value + field.value.substring(end_pos, field.value.length);
1373 field.value += value;
1377 function checkParentType(type,button) {
1378 if(button == null) {
1381 if(typeof disabledModules != 'undefined' && typeof(disabledModules[type]) != 'undefined') {
1382 button.disabled='disabled';
1385 button.disabled = false;
1389 function parseDate(input, format) {
1391 format = format.replace(/%/g, '');
1392 sep = format.charAt(1);
1393 yAt = format.indexOf('Y')
1394 // 1-1-06 or 1-12-06 or 1-1-2006 or 1-12-2006
1395 if(date.match(/^\d{1,2}[\/-]\d{1,2}[\/-]\d{2,4}$/) && yAt == 4) {
1396 if(date.match(/^\d{1}[\/-].*$/)) date = '0' + date;
1397 if(date.match(/^\d{2}[\/-]\d{1}[\/-].*$/)) date = date.substring(0,3) + '0' + date.substring(3,date.length);
1398 if(date.match(/^\d{2}[\/-]\d{2}[\/-]\d{2}$/)) date = date.substring(0,6) + '20' + date.substring(6,date.length);
1400 // 06-11-1 or 06-1-1
1401 else if(date.match(/^\d{2,4}[\/-]\d{1,2}[\/-]\d{1,2}$/)) {
1402 if(date.match(/^\d{2}[\/-].*$/)) date = '20' + date;
1403 if(date.match(/^\d{4}[\/-]\d{1}[\/-].*$/)) date = date.substring(0,5) + '0' + date.substring(5,date.length);
1404 if(date.match(/^\d{4}[\/-]\d{2}[\/-]\d{1}$/)) date = date.substring(0,8) + '0' + date.substring(8,date.length);
1406 else if(date.match(/^\d{4,8}$/)) { // digits only
1408 if(date.match(/^\d{8}$/)) digits = 8;// match for 8 digits
1409 else if(date.match(/\d{6}/)) digits = 6;// match for 5 digits
1410 else if(date.match(/\d{4}/)) digits = 4;// match for 5 digits
1411 else if(date.match(/\d{5}/)) digits = 5;// match for 5 digits
1416 case 4: date = '20' + date.substring(0,2) + sep + '0' + date.substring(2, 3) + sep + '0' + date.substring(3,4); break;
1417 case 5: date = '20' + date.substring(0,2) + sep + date.substring(2, 4) + sep + '0' + date.substring(4,5); break;
1418 case 6: date = '20' + date.substring(0,2) + sep + date.substring(2, 4) + sep + date.substring(4,6); break;
1419 case 8: date = date.substring(0,4) + sep + date.substring(4, 6) + sep + date.substring(6,8); break;
1424 case 4: date = '0' + date.substring(0,1) + sep + '20' + date.substring(1, 3) + sep + '0' + date.substring(3,4); break;
1425 case 5: date = date.substring(0,2) + sep + '20' + date.substring(2, 4) + sep + '0' + date.substring(4,5); break;
1426 case 6: date = date.substring(0,2) + sep + '20' + date.substring(2, 4) + sep + date.substring(4,6); break;
1427 case 8: date = date.substring(0,2) + sep + date.substring(2, 6) + sep + date.substring(6,8); break;
1431 case 4: date = '0' + date.substring(0,1) + sep + '0' + date.substring(1, 2) + sep + '20' + date.substring(2,4); break;
1432 case 5: date = '0' + date.substring(0,1) + sep + date.substring(1, 3) + sep + '20' + date.substring(3,5); break;
1433 case 6: date = date.substring(0,2) + sep + date.substring(2, 4) + sep + '20' + date.substring(4,6); break;
1434 case 8: date = date.substring(0,2) + sep + date.substring(2, 4) + sep + date.substring(4,8); break;
1439 date = date.replace(/[\/-]/g, sep);
1443 // find obj's position
1444 function findElementPos(obj) {
1447 if (obj.offsetParent) {
1448 while (obj.offsetParent) {
1449 x += obj.offsetLeft;
1451 obj = obj.offsetParent;
1453 }//if offsetParent exists
1454 else if (obj.x && obj.y) {
1458 return new coordinate(x, y);
1462 // get dimensions of the browser window
1463 function getClientDim() {
1464 var nwX, nwY, seX, seY;
1465 if (self.pageYOffset) // all except Explorer
1467 nwX = self.pageXOffset;
1468 seX = self.innerWidth + nwX;
1469 nwY = self.pageYOffset;
1470 seY = self.innerHeight + nwY;
1472 else if (document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
1474 nwX = document.documentElement.scrollLeft;
1475 seX = document.documentElement.clientWidth + nwX;
1476 nwY = document.documentElement.scrollTop;
1477 seY = document.documentElement.clientHeight + nwY;
1479 else if (document.body) // all other Explorers
1481 nwX = document.body.scrollLeft;
1482 seX = document.body.clientWidth + nwX;
1483 nwY = document.body.scrollTop;
1484 seY = document.body.clientHeight + nwY;
1486 return {'nw' : new coordinate(nwX, nwY), 'se' : new coordinate(seX, seY)};
1490 * stop propagation on events
1492 function freezeEvent(e) {
1494 if (e.preventDefault) e.preventDefault();
1495 e.returnValue = false;
1496 e.cancelBubble = true;
1497 if (e.stopPropagation) e.stopPropagation();
1506 function coordinate(_x, _y) {
1515 return new position(this.x + rh.x, this.y + rh.y);
1519 return new position(this.x + rh.x, this.y + rh.y);
1523 // sends theForm via AJAX and fills in the theDiv
1524 function sendAndRetrieve(theForm, theDiv, loadingStr) {
1525 function success(data) {
1526 document.getElementById(theDiv).innerHTML = data.responseText;
1527 ajaxStatus.hideStatus();
1529 if(typeof loadingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
1530 ajaxStatus.showStatus(loadingStr);
1531 YAHOO.util.Connect.setForm(theForm);
1532 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
1536 //save the form and redirect
1537 function sendAndRedirect(theForm, loadingStr, redirect_location) {
1538 function success(data) {
1539 if(redirect_location){
1540 location.href=redirect_location;
1542 ajaxStatus.hideStatus();
1544 if(typeof loadingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
1545 ajaxStatus.showStatus(loadingStr);
1546 YAHOO.util.Connect.setForm(theForm);
1547 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
1551 function saveForm(theForm, theDiv, loadingStr) {
1552 if(check_form(theForm)){
1553 for(i = 0; i < ajaxFormArray.length; i++){
1554 if(ajaxFormArray[i] == theForm){
1555 ajaxFormArray.splice(i, 1);
1558 return sendAndRetrieve(theForm, loadingStr, theDiv);
1564 // Builds a "snapshot" of the form, so we can use it to see if someone has changed it.
1565 function snapshotForm(theForm) {
1566 var snapshotTxt = '';
1567 var elemList = theForm.elements;
1571 for( var i = 0; i < elemList.length ; i++ ) {
1573 if ( typeof(elem.type) == 'undefined' ) {
1577 elemType = elem.type.toLowerCase();
1579 snapshotTxt = snapshotTxt + elem.name;
1581 if ( elemType == 'text' || elemType == 'textarea' || elemType == 'password' ) {
1582 snapshotTxt = snapshotTxt + elem.value;
1584 else if ( elemType == 'select' || elemType == 'select-one' || elemType == 'select-multiple' ) {
1585 var optionList = elem.options;
1586 for ( var ii = 0 ; ii < optionList.length ; ii++ ) {
1587 if ( optionList[ii].selected ) {
1588 snapshotTxt = snapshotTxt + optionList[ii].value;
1592 else if ( elemType == 'radio' || elemType == 'checkbox' ) {
1593 if ( elem.selected ) {
1594 snapshotTxt = snapshotTxt + 'checked';
1597 else if ( elemType == 'hidden' ) {
1598 snapshotTxt = snapshotTxt + elem.value;
1605 function initEditView(theForm) {
1606 if (SUGAR.util.ajaxCallInProgress()) {
1607 window.setTimeout(function(){initEditView(theForm);}, 100);
1610 // we don't need to check if the data is changed in the search popup
1611 if (theForm.id == 'popup_query_form') {
1614 if ( typeof editViewSnapshots == 'undefined' ) {
1615 editViewSnapshots = new Object();
1617 if ( typeof SUGAR.loadedForms == 'undefined' ) {
1618 SUGAR.loadedForms = new Object();
1621 // console.log('DEBUG: Adding checks for '+theForm.id);
1622 if ( theForm == null || theForm.id == null ) {
1623 // Not much we can do here.
1626 editViewSnapshots[theForm.id] = snapshotForm(theForm);
1627 SUGAR.loadedForms[theForm.id] = true;
1631 function onUnloadEditView(theForm) {
1633 var dataHasChanged = false;
1635 if ( typeof editViewSnapshots == 'undefined' ) {
1636 // No snapshots, move along
1640 if ( typeof theForm == 'undefined' ) {
1641 // Need to check all editViewSnapshots
1642 for ( var idx in editViewSnapshots ) {
1644 theForm = document.getElementById(idx);
1645 // console.log('DEBUG: Checking all forms '+theForm.id);
1646 if ( theForm == null
1647 || typeof editViewSnapshots[theForm.id] == 'undefined'
1648 || editViewSnapshots[theForm.id] == null
1649 || !SUGAR.loadedForms[theForm.id]) {
1653 var snap = snapshotForm(theForm);
1654 if ( editViewSnapshots[theForm.id] != snap ) {
1655 dataHasChanged = true;
1659 // Just need to check a single form for changes
1660 if ( editViewSnapshots == null || typeof theForm.id == 'undefined' || typeof editViewSnapshots[theForm.id] == 'undefined' || editViewSnapshots[theForm.id] == null ) {
1664 // console.log('DEBUG: Checking one form '+theForm.id);
1665 if ( editViewSnapshots[theForm.id] != snapshotForm(theForm) ) {
1666 // Data has changed.
1667 dataHasChanged = true;
1671 if ( dataHasChanged == true ) {
1672 return SUGAR.language.get('app_strings','WARN_UNSAVED_CHANGES');
1679 function disableOnUnloadEditView(theForm) {
1680 // If you don't pass anything in, it disables all checking
1681 if ( typeof theForm == 'undefined' || typeof editViewSnapshots == 'undefined' || theForm == null || editViewSnapshots == null) {
1682 window.onbeforeunload = null;
1683 editViewSnapshots = null;
1685 // console.log('DEBUG: Disabling all edit view checks');
1688 // Otherwise, it just disables it for this form
1689 if ( typeof(theForm.id) != 'undefined' && typeof(editViewSnapshots[theForm.id]) != 'undefined' ) {
1690 editViewSnapshots[theForm.id] = null;
1693 // console.log('DEBUG : Disabling just checks for '+theForm.id);
1699 * save some forms using an ajax call
1700 * theForms - the ids of all of theh forms to save
1701 * savingStr - the string to display when saving the form
1702 * completeStr - the string to display when the form has been saved
1704 function saveForms( savingStr, completeStr) {
1706 theForms = ajaxFormArray;
1707 function success(data) {
1708 var theForm = document.getElementById(ajaxFormArray[0]);
1709 document.getElementById('multiedit_'+theForm.id).innerHTML = data.responseText;
1710 var saveAllButton = document.getElementById('ajaxsaveall');
1711 ajaxFormArray.splice(index, 1);
1712 if(saveAllButton && ajaxFormArray.length <= 1){
1713 saveAllButton.style.visibility = 'hidden';
1716 if(index == theForms.length){
1717 ajaxStatus.showStatus(completeStr);
1718 window.setTimeout('ajaxStatus.hideStatus();', 2000);
1720 saveAllButton.style.visibility = 'hidden';
1725 if(typeof savingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
1726 ajaxStatus.showStatus(savingStr);
1728 //loop through the forms saving each one
1729 for(i = 0; i < theForms.length; i++){
1730 var theForm = document.getElementById(theForms[i]);
1731 if(check_form(theForm.id)){
1732 theForm.action.value='AjaxFormSave';
1733 YAHOO.util.Connect.setForm(theForm);
1734 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
1736 ajaxStatus.hideStatus();
1738 lastSubmitTime = lastSubmitTime-2000;
1743 // -- start sugarListView class
1744 // js functions used for ListView
1745 function sugarListView() {
1749 sugarListView.prototype.confirm_action = function(del) {
1751 return confirm( SUGAR.language.get('app_strings', 'NTC_DELETE_CONFIRMATION_NUM') + sugarListView.get_num_selected() + SUGAR.language.get('app_strings', 'NTC_DELETE_SELECTED_RECORDS'));
1754 return confirm( SUGAR.language.get('app_strings', 'NTC_UPDATE_CONFIRMATION_NUM') + sugarListView.get_num_selected() + SUGAR.language.get('app_strings', 'NTC_DELETE_SELECTED_RECORDS'));
1758 sugarListView.get_num_selected = function () {
1759 if(typeof document.MassUpdate != 'undefined') {
1760 the_form = document.MassUpdate;
1761 for(wp = 0; wp < the_form.elements.length; wp++) {
1762 if(typeof the_form.elements[wp].name != 'undefined' && the_form.elements[wp].name == 'selectCount[]') {
1763 return the_form.elements[wp].value;
1770 sugarListView.update_count = function(count, add) {
1771 if(typeof document.MassUpdate != 'undefined') {
1772 the_form = document.MassUpdate;
1773 for(wp = 0; wp < the_form.elements.length; wp++) {
1774 if(typeof the_form.elements[wp].name != 'undefined' && the_form.elements[wp].name == 'selectCount[]') {
1776 the_form.elements[wp].value = parseInt(the_form.elements[wp].value,10) + count;
1778 else the_form.elements[wp].value = count;
1783 sugarListView.prototype.use_external_mail_client = function(no_record_txt, module) {
1784 selected_records = sugarListView.get_checks_count();
1785 if(selected_records <1) {
1786 alert(no_record_txt);
1790 if (document.MassUpdate.select_entire_list.value == 1) {
1791 if (totalCount > 10) {
1792 alert(totalCountError);
1797 else if (document.MassUpdate.massall.checked == true)
1801 sugarListView.get_checks();
1803 if(select) { // use selected items
1804 ids = document.MassUpdate.uid.value;
1806 else { // use current page
1807 inputs = document.MassUpdate.elements;
1809 for(i = 0; i < inputs.length; i++) {
1810 if(inputs[i].name == 'mass[]' && inputs[i].checked && typeof(inputs[i].value) != 'function') {
1811 ar.push(inputs[i].value);
1816 YAHOO.util.Connect.asyncRequest("POST", "index.php?", {
1817 success: this.use_external_mail_client_callback
1818 }, SUGAR.util.paramsToUrl({
1821 listViewExternalClient: 1,
1822 action_module: module,
1830 sugarListView.prototype.use_external_mail_client_callback = function(o)
1833 location.href = 'mailto:' + o.responseText;
1836 sugarListView.prototype.send_form_for_emails = function(select, currentModule, action, no_record_txt,action_module,totalCount, totalCountError) {
1837 if (document.MassUpdate.select_entire_list.value == 1) {
1838 if (totalCount > 10) {
1839 alert(totalCountError);
1844 else if (document.MassUpdate.massall.checked == true)
1849 sugarListView.get_checks();
1850 // create new form to post (can't access action property of MassUpdate form due to action input)
1851 var newForm = document.createElement('form');
1852 newForm.method = 'post';
1853 newForm.action = action;
1854 newForm.name = 'newForm';
1855 newForm.id = 'newForm';
1856 var uidTa = document.createElement('textarea');
1858 uidTa.style.display = 'none';
1860 if(select) { // use selected items
1861 uidTa.value = document.MassUpdate.uid.value;
1863 else { // use current page
1864 inputs = document.MassUpdate.elements;
1866 for(i = 0; i < inputs.length; i++) {
1867 if(inputs[i].name == 'mass[]' && inputs[i].checked && typeof(inputs[i].value) != 'function') {
1868 ar.push(inputs[i].value);
1871 uidTa.value = ar.join(',');
1874 if(uidTa.value == '') {
1875 alert(no_record_txt);
1879 var selectedArray = uidTa.value.split(",");
1880 if(selectedArray.length > 10) {
1881 alert(totalCountError);
1884 newForm.appendChild(uidTa);
1886 var moduleInput = document.createElement('input');
1887 moduleInput.name = 'module';
1888 moduleInput.type = 'hidden';
1889 moduleInput.value = currentModule;
1890 newForm.appendChild(moduleInput);
1892 var actionInput = document.createElement('input');
1893 actionInput.name = 'action';
1894 actionInput.type = 'hidden';
1895 actionInput.value = 'Compose';
1896 newForm.appendChild(actionInput);
1898 if (typeof action_module != 'undefined' && action_module!= '') {
1899 var actionModule = document.createElement('input');
1900 actionModule.name = 'action_module';
1901 actionModule.type = 'hidden';
1902 actionModule.value = action_module;
1903 newForm.appendChild(actionModule);
1905 //return_info must follow this pattern."&return_module=Accounts&return_action=index"
1906 if (typeof return_info!= 'undefined' && return_info != '') {
1907 var params= return_info.split('&');
1908 if (params.length > 0) {
1909 for (var i=0;i< params.length;i++) {
1910 if (params[i].length > 0) {
1911 var param_nv=params[i].split('=');
1912 if (param_nv.length==2){
1913 returnModule = document.createElement('input');
1914 returnModule.name = param_nv[0];
1915 returnModule.type = 'hidden';
1916 returnModule.value = param_nv[1];
1917 newForm.appendChild(returnModule);
1924 var isAjaxCall = document.createElement('input');
1925 isAjaxCall.name = 'ajaxCall';
1926 isAjaxCall.type = 'hidden';
1927 isAjaxCall.value = true;
1928 newForm.appendChild(isAjaxCall);
1930 var isListView = document.createElement('input');
1931 isListView.name = 'ListView';
1932 isListView.type = 'hidden';
1933 isListView.value = true;
1934 newForm.appendChild(isListView);
1936 var toPdf = document.createElement('input');
1937 toPdf.name = 'to_pdf';
1938 toPdf.type = 'hidden';
1940 newForm.appendChild(toPdf);
1942 //Grab the Quick Compose package for the listview
1943 YAHOO.util.Connect.setForm(newForm);
1946 success: function(o) {
1947 var resp = YAHOO.lang.JSON.parse(o.responseText);
1948 var quickComposePackage = new Object();
1949 quickComposePackage.composePackage = resp;
1950 quickComposePackage.fullComposeUrl = 'index.php?module=Emails&action=Compose&ListView=true' +
1951 '&uid=' + uidTa.value + '&action_module=' + action_module;
1953 SUGAR.quickCompose.init(quickComposePackage);
1957 YAHOO.util.Connect.asyncRequest('POST','index.php', callback,null);
1959 // awu Bug 18624: Fixing issue where a canceled Export and unselect of row will persist the uid field, clear the field
1960 document.MassUpdate.uid.value = '';
1965 sugarListView.prototype.send_form = function(select, currentModule, action, no_record_txt,action_module,return_info) {
1966 if (document.MassUpdate.select_entire_list.value == 1) {
1968 if(sugarListView.get_checks_count() < 1) {
1969 alert(no_record_txt);
1974 if ( action.indexOf('?') != -1 )
1975 href += '&module=' + currentModule;
1977 href += '?module=' + currentModule;
1980 href += return_info;
1981 var newForm = document.createElement('form');
1982 newForm.method = 'post';
1983 newForm.action = href;
1984 newForm.name = 'newForm';
1985 newForm.id = 'newForm';
1986 var postTa = document.createElement('textarea');
1987 postTa.name = 'current_post';
1988 postTa.value = document.MassUpdate.current_query_by_page.value;
1989 postTa.style.display = 'none';
1990 newForm.appendChild(postTa);
1991 document.MassUpdate.parentNode.appendChild(newForm);
1995 else if (document.MassUpdate.massall.checked == true)
2000 sugarListView.get_checks();
2001 // create new form to post (can't access action property of MassUpdate form due to action input)
2002 var newForm = document.createElement('form');
2003 newForm.method = 'post';
2004 newForm.action = action;
2005 newForm.name = 'newForm';
2006 newForm.id = 'newForm';
2007 var uidTa = document.createElement('textarea');
2009 uidTa.style.display = 'none';
2010 uidTa.value = document.MassUpdate.uid.value;
2012 if(uidTa.value == '') {
2013 alert(no_record_txt);
2017 newForm.appendChild(uidTa);
2019 var moduleInput = document.createElement('input');
2020 moduleInput.name = 'module';
2021 moduleInput.type = 'hidden';
2022 moduleInput.value = currentModule;
2023 newForm.appendChild(moduleInput);
2025 var actionInput = document.createElement('input');
2026 actionInput.name = 'action';
2027 actionInput.type = 'hidden';
2028 actionInput.value = 'index';
2029 newForm.appendChild(actionInput);
2031 if (typeof action_module != 'undefined' && action_module!= '') {
2032 var actionModule = document.createElement('input');
2033 actionModule.name = 'action_module';
2034 actionModule.type = 'hidden';
2035 actionModule.value = action_module;
2036 newForm.appendChild(actionModule);
2038 //return_info must follow this pattern."&return_module=Accounts&return_action=index"
2039 if (typeof return_info!= 'undefined' && return_info != '') {
2040 var params= return_info.split('&');
2041 if (params.length > 0) {
2042 for (var i=0;i< params.length;i++) {
2043 if (params[i].length > 0) {
2044 var param_nv=params[i].split('=');
2045 if (param_nv.length==2){
2046 returnModule = document.createElement('input');
2047 returnModule.name = param_nv[0];
2048 returnModule.type = 'hidden';
2049 returnModule.value = param_nv[1];
2050 newForm.appendChild(returnModule);
2057 document.MassUpdate.parentNode.appendChild(newForm);
2060 // awu Bug 18624: Fixing issue where a canceled Export and unselect of row will persist the uid field, clear the field
2061 document.MassUpdate.uid.value = '';
2065 //return a count of checked row.
2066 sugarListView.get_checks_count = function() {
2069 if(document.MassUpdate.uid.value != '') {
2070 oldUids = document.MassUpdate.uid.value.split(',');
2071 for(uid in oldUids) {
2072 if(typeof(oldUids[uid]) != 'function') {
2073 ar[oldUids[uid]] = 1;
2077 // build associated array of uids, associated array ensures uniqueness
2078 inputs = document.MassUpdate.elements;
2079 for(i = 0; i < inputs.length; i++) {
2080 if(inputs[i].name == 'mass[]') {
2081 ar[inputs[i].value] = (inputs[i].checked) ? 1 : 0; // 0 of it is unchecked
2085 // build regular array of uids
2088 if((typeof(ar[i]) != 'function') && ar[i] == 1) {
2096 // saves the checks on the current page into the uid textarea
2097 sugarListView.get_checks = function() {
2100 if(document.MassUpdate.uid.value != '') {
2101 oldUids = document.MassUpdate.uid.value.split(',');
2102 for(uid in oldUids) {
2103 if(typeof(oldUids[uid]) != 'function') {
2104 ar[oldUids[uid]] = 1;
2109 // build associated array of uids, associated array ensures uniqueness
2110 inputs = document.MassUpdate.elements;
2111 for(i = 0; i < inputs.length; i++) {
2112 if(inputs[i].name == 'mass[]') {
2113 ar[inputs[i].value] = (inputs[i].checked) ? 1 : 0; // 0 of it is unchecked
2117 // build regular array of uids
2120 if(typeof(ar[i]) != 'function' && ar[i] == 1) {
2125 document.MassUpdate.uid.value = uids.join(',');
2127 if(uids.length == 0) return false; // return false if no checks to get
2128 return true; // there are saved checks
2131 sugarListView.prototype.order_checks = function(order,orderBy,moduleString){
2132 checks = sugarListView.get_checks();
2133 eval('document.MassUpdate.' + moduleString + '.value = orderBy');
2134 document.MassUpdate.lvso.value = order;
2135 if(typeof document.MassUpdate.massupdate != 'undefined') {
2136 document.MassUpdate.massupdate.value = 'false';
2139 //we must first clear the action of massupdate, change it to index
2140 document.MassUpdate.action.value = document.MassUpdate.return_action.value;
2141 document.MassUpdate.return_module.value='';
2142 document.MassUpdate.return_action.value='';
2143 document.MassUpdate.submit();
2147 sugarListView.prototype.save_checks = function(offset, moduleString) {
2148 checks = sugarListView.get_checks();
2149 eval('document.MassUpdate.' + moduleString + '.value = offset');
2151 if(typeof document.MassUpdate.massupdate != 'undefined') {
2152 document.MassUpdate.massupdate.value = 'false';
2155 //we must first clear the action of massupdate, change it to index
2156 document.MassUpdate.action.value = document.MassUpdate.return_action.value;
2157 document.MassUpdate.return_module.value='';
2158 document.MassUpdate.return_action.value='';
2159 document.MassUpdate.submit();
2165 sugarListView.prototype.check_item = function(cb, form) {
2167 sugarListView.update_count(1, true);
2169 sugarListView.update_count(-1, true);
2170 if(typeof form != 'undefined' && form != null) {
2171 sugarListView.prototype.updateUid(cb, form);
2176 /**#28000, remove the unselect record id from MassUpdate.uid **/
2177 sugarListView.prototype.updateUid = function(cb , form){
2178 if(form.name == 'MassUpdate' && form.uid && form.uid.value && cb.value && form.uid.value.indexOf(cb.value) != -1){
2179 if(form.uid.value.indexOf(','+cb.value)!= -1){
2180 form.uid.value = form.uid.value.replace(','+cb.value , '');
2181 }else if(form.uid.value.indexOf(cb.value + ',')!= -1){
2182 form.uid.value = form.uid.value.replace(cb.value + ',' , '');
2183 }else if(form.uid.value.indexOf(cb.value)!= -1){
2184 form.uid.value = form.uid.value.replace(cb.value , '');
2189 sugarListView.prototype.check_entire_list = function(form, field, value, list_count) {
2190 // count number of items
2192 document.MassUpdate.massall.checked = true;
2193 document.MassUpdate.massall.disabled = true;
2195 for (i = 0; i < form.elements.length; i++) {
2196 if(form.elements[i].name == field && form.elements[i].disabled == false) {
2197 if(form.elements[i].checked != value) count++;
2198 form.elements[i].checked = value;
2199 form.elements[i].disabled = true;
2202 document.MassUpdate.select_entire_list.value = 1;
2204 sugarListView.update_count(list_count, false);
2205 //else sugarListView.update_count(-1 * count, true);
2208 sugarListView.prototype.check_all = function(form, field, value, pageTotal) {
2209 // count number of items
2211 document.MassUpdate.massall.checked = value;
2212 if (document.MassUpdate.select_entire_list &&
2213 document.MassUpdate.select_entire_list.value == 1)
2214 document.MassUpdate.massall.disabled = true;
2216 document.MassUpdate.massall.disabled = false;
2218 for (i = 0; i < form.elements.length; i++) {
2219 if(form.elements[i].name == field && !(form.elements[i].disabled == true && form.elements[i].checked == false)) {
2220 form.elements[i].disabled = false;
2222 if(form.elements[i].checked != value)
2224 form.elements[i].checked = value;
2226 sugarListView.prototype.updateUid(form.elements[i], form);
2231 sugarListView.update_count(pageTotal);
2233 sugarListView.update_count(count, true);
2235 sugarListView.update_count(-1 * count, true);
2237 sugarListView.check_all = sugarListView.prototype.check_all;
2238 sugarListView.confirm_action = sugarListView.prototype.confirm_action;
2240 sugarListView.prototype.check_boxes = function() {
2241 var inputsCount = 0;
2242 var checkedCount = 0;
2243 var existing_onload = window.onload;
2244 var theForm = document.MassUpdate;
2245 inputs_array = theForm.elements;
2247 if(typeof theForm.uid.value != 'undefined' && theForm.uid.value != "") {
2248 checked_items = theForm.uid.value.split(",");
2249 if (theForm.select_entire_list.value == 1)
2250 document.MassUpdate.massall.disabled = true;
2252 for(wp = 0 ; wp < inputs_array.length; wp++) {
2253 if(inputs_array[wp].name == "mass[]") {
2255 if (theForm.select_entire_list.value == 1) {
2256 inputs_array[wp].checked = true;
2257 inputs_array[wp].disabled = true;
2261 for(i in checked_items) {
2262 if(inputs_array[wp].value == checked_items[i]) {
2264 inputs_array[wp].checked = true;
2270 if (theForm.select_entire_list.value == 0)
2271 sugarListView.update_count(checked_items.length);
2273 sugarListView.update_count(0, true);
2277 for(wp = 0 ; wp < inputs_array.length; wp++) {
2278 if(inputs_array[wp].name == "mass[]") {
2279 inputs_array[wp].checked = false;
2280 inputs_array[wp].disabled = false;
2283 if (document.MassUpdate.massall) {
2284 document.MassUpdate.massall.checked = false;
2285 document.MassUpdate.massall.disabled = false;
2287 sugarListView.update_count(0)
2289 if(checkedCount > 0 && checkedCount == inputsCount)
2290 document.MassUpdate.massall.checked = true;
2296 * This function is used in Email Template Module's listview.
2297 * It will check whether the templates are used in Campaing->EmailMarketing.
2298 * If true, it will notify user.
2300 function check_used_email_templates() {
2301 var ids = document.MassUpdate.uid.value;
2303 success:function(r) {
2304 if(r.responseText != '') {
2305 if(!confirm(SUGAR.language.get('app_strings','NTC_TEMPLATES_IS_USED') + r.responseText)) {
2309 document.MassUpdate.submit();
2313 url = "index.php?module=EmailTemplates&action=CheckDeletable&from=ListView&to_pdf=1&records="+ids;
2314 YAHOO.util.Connect.asyncRequest('POST',url, call_back,null);
2318 sugarListView.prototype.send_mass_update = function(mode, no_record_txt, del) {
2319 formValid = check_form('MassUpdate');
2320 if(!formValid && !del) return false;
2323 if (document.MassUpdate.select_entire_list &&
2324 document.MassUpdate.select_entire_list.value == 1)
2329 var ar = new Array();
2333 for(wp = 0; wp < document.MassUpdate.elements.length; wp++) {
2334 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)+'$');
2335 //when the uid is already in document.MassUpdate.uid.value, we should not add it to ar.
2336 if(typeof document.MassUpdate.elements[wp].name != 'undefined'
2337 && document.MassUpdate.elements[wp].name == 'mass[]'
2338 && document.MassUpdate.elements[wp].checked
2339 && !reg_for_existing_uid.test(document.MassUpdate.uid.value)) {
2340 ar.push(document.MassUpdate.elements[wp].value);
2343 if(document.MassUpdate.uid.value != '') document.MassUpdate.uid.value += ',';
2344 document.MassUpdate.uid.value += ar.join(',');
2345 if(document.MassUpdate.uid.value == '') {
2346 alert(no_record_txt);
2349 if(typeof(current_admin_id)!='undefined' && document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'Users' && (document.MassUpdate.is_admin.value!='' || document.MassUpdate.status.value!='')) {
2350 var reg_for_current_admin_id = new RegExp('^'+current_admin_id+'[\s]*,|,[\s]*'+current_admin_id+'[\s]*,|,[\s]*'+current_admin_id+'$|^'+current_admin_id+'$');
2351 if(reg_for_current_admin_id.test(document.MassUpdate.uid.value)) {
2352 //if current user is admin, we should not allow massupdate the user_type and status of himself
2353 alert(SUGAR.language.get('Users','LBL_LAST_ADMIN_NOTICE'));
2359 var entireInput = document.createElement('input');
2360 entireInput.name = 'entire';
2361 entireInput.type = 'hidden';
2362 entireInput.value = 'index';
2363 document.MassUpdate.appendChild(entireInput);
2364 //confirm(no_record_txt);
2365 if(document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'Users' && (document.MassUpdate.is_admin.value!='' || document.MassUpdate.status.value!='')) {
2366 alert(SUGAR.language.get('Users','LBL_LAST_ADMIN_NOTICE'));
2372 if(!sugarListView.confirm_action(del))
2376 var deleteInput = document.createElement('input');
2377 deleteInput.name = 'Delete';
2378 deleteInput.type = 'hidden';
2379 deleteInput.value = true;
2380 document.MassUpdate.appendChild(deleteInput);
2381 if(document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'EmailTemplates') {
2382 check_used_email_templates();
2388 document.MassUpdate.submit();
2393 sugarListView.prototype.clear_all = function() {
2394 document.MassUpdate.uid.value = '';
2395 document.MassUpdate.select_entire_list.value = 0;
2396 sugarListView.check_all(document.MassUpdate, 'mass[]', false);
2397 document.MassUpdate.massall.checked = false;
2398 document.MassUpdate.massall.disabled = false;
2399 sugarListView.update_count(0);
2402 sListView = new sugarListView();
2403 // -- end sugarListView class
2405 // format and unformat numbers
2406 function unformatNumber(n, num_grp_sep, dec_sep) {
2407 var x=unformatNumberNoParse(n, num_grp_sep, dec_sep);
2410 return parseFloat(x);
2415 function unformatNumberNoParse(n, num_grp_sep, dec_sep) {
2416 if(typeof num_grp_sep == 'undefined' || typeof dec_sep == 'undefined') return n;
2417 n = n ? n.toString() : '';
2420 if(num_grp_sep != '')
2422 num_grp_sep_re = new RegExp('\\'+num_grp_sep, 'g');
2423 n = n.replace(num_grp_sep_re, '');
2426 n = n.replace(dec_sep, '.');
2428 if(typeof CurrencySymbols != 'undefined') {
2429 // Need to strip out the currency symbols from the start.
2430 for ( var idx in CurrencySymbols ) {
2431 n = n.replace(CurrencySymbols[idx], '');
2439 // round parameter can be negative for decimal, precision has to be postive
2440 function formatNumber(n, num_grp_sep, dec_sep, round, precision) {
2441 if(typeof num_grp_sep == 'undefined' || typeof dec_sep == 'undefined') return n;
2442 n = n ? n.toString() : '';
2443 if(n.split) n = n.split('.');
2446 if(n.length > 2) return n.join('.'); // that's not a num!
2448 if(typeof round != 'undefined') {
2449 if(round > 0 && n.length > 1) { // round to decimal
2450 n[1] = parseFloat('0.' + n[1]);
2451 n[1] = Math.round(n[1] * Math.pow(10, round)) / Math.pow(10, round);
2452 n[1] = n[1].toString().split('.')[1];
2454 if(round <= 0) { // round to whole number
2455 n[0] = Math.round(parseInt(n[0],10) * Math.pow(10, round)) / Math.pow(10, round);
2460 if(typeof precision != 'undefined' && precision >= 0) {
2461 if(n.length > 1 && typeof n[1] != 'undefined') n[1] = n[1].substring(0, precision); // cut off precision
2463 if(n[1].length < precision) {
2464 for(var wp = n[1].length; wp < precision; wp++) n[1] += '0';
2468 regex = /(\d+)(\d{3})/;
2469 while(num_grp_sep != '' && regex.test(n[0])) n[0] = n[0].toString().replace(regex, '$1' + num_grp_sep + '$2');
2470 return n[0] + (n.length > 1 && n[1] != '' ? dec_sep + n[1] : '');
2473 // --- begin ajax status class
2474 SUGAR.ajaxStatusClass = function() {};
2475 SUGAR.ajaxStatusClass.prototype.statusDiv = null;
2476 SUGAR.ajaxStatusClass.prototype.oldOnScroll = null;
2477 SUGAR.ajaxStatusClass.prototype.shown = false; // state of the status window
2479 // reposition the status div, top and centered
2480 SUGAR.ajaxStatusClass.prototype.positionStatus = function() {
2481 this.statusDiv.style.top = document.body.scrollTop + 8 + 'px';
2482 statusDivRegion = YAHOO.util.Dom.getRegion(this.statusDiv);
2483 statusDivWidth = statusDivRegion.right - statusDivRegion.left;
2484 this.statusDiv.style.left = YAHOO.util.Dom.getViewportWidth() / 2 - statusDivWidth / 2 + 'px';
2487 // private func, create the status div
2488 SUGAR.ajaxStatusClass.prototype.createStatus = function(text) {
2489 statusDiv = document.createElement('div');
2490 statusDiv.className = 'dataLabel';
2491 statusDiv.style.background = '#ffffff';
2492 statusDiv.style.color = '#c60c30';
2493 statusDiv.style.position = 'absolute';
2494 statusDiv.style.opacity = .8;
2495 statusDiv.style.filter = 'alpha(opacity=80)';
2496 statusDiv.id = 'ajaxStatusDiv';
2497 document.body.appendChild(statusDiv);
2498 this.statusDiv = document.getElementById('ajaxStatusDiv');
2501 // public - show the status div with text
2502 SUGAR.ajaxStatusClass.prototype.showStatus = function(text) {
2503 if(!this.statusDiv) {
2504 this.createStatus(text);
2507 this.statusDiv.style.display = '';
2509 this.statusDiv.style.zIndex = 20;
2510 this.statusDiv.innerHTML = ' <b>' + text + '</b> ';
2511 this.positionStatus();
2514 this.statusDiv.style.display = '';
2515 if(window.onscroll) this.oldOnScroll = window.onscroll; // save onScroll
2516 window.onscroll = this.positionStatus;
2521 SUGAR.ajaxStatusClass.prototype.hideStatus = function(text) {
2522 if(!this.shown) return;
2524 if(this.oldOnScroll) window.onscroll = this.oldOnScroll;
2525 else window.onscroll = '';
2526 this.statusDiv.style.display = 'none';
2529 SUGAR.ajaxStatusClass.prototype.flashStatus = function(text, time){
2530 this.showStatus(text);
2531 window.setTimeout('ajaxStatus.hideStatus();', time);
2535 var ajaxStatus = new SUGAR.ajaxStatusClass();
2536 // --- end ajax status class
2539 * Unified Search Advanced - for global search
2541 SUGAR.unifiedSearchAdvanced = function() {
2551 SUGAR.unifiedSearchAdvanced.usa_div = document.getElementById('unified_search_advanced_div');
2552 SUGAR.unifiedSearchAdvanced.usa_img = document.getElementById('unified_search_advanced_img');
2554 if(!SUGAR.unifiedSearchAdvanced.usa_div || !SUGAR.unifiedSearchAdvanced.usa_img) return;
2555 var attributes = { height: { to: 300 } };
2556 SUGAR.unifiedSearchAdvanced.anim_open = new YAHOO.util.Anim('unified_search_advanced_div', attributes );
2557 SUGAR.unifiedSearchAdvanced.anim_open.duration = 0.75;
2558 SUGAR.unifiedSearchAdvanced.anim_close = new YAHOO.util.Anim('unified_search_advanced_div', { height: {to: 0} } );
2559 SUGAR.unifiedSearchAdvanced.anim_close.duration = 0.75;
2560 //SUGAR.unifiedSearchAdvanced.anim_close.onComplete.subscribe(function() {SUGAR.unifiedSearchAdvanced.usa_div.style.display = 'none'});
2562 SUGAR.unifiedSearchAdvanced.usa_img._x = YAHOO.util.Dom.getX(SUGAR.unifiedSearchAdvanced.usa_img);
2563 SUGAR.unifiedSearchAdvanced.usa_img._y = YAHOO.util.Dom.getY(SUGAR.unifiedSearchAdvanced.usa_img);
2566 SUGAR.unifiedSearchAdvanced.usa_open = false;
2567 SUGAR.unifiedSearchAdvanced.usa_content = null;
2569 YAHOO.util.Event.addListener('unified_search_advanced_img', 'click', SUGAR.unifiedSearchAdvanced.get_content);
2572 get_content: function(e) {
2573 if(SUGAR.unifiedSearchAdvanced.usa_content == null) {
2574 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_LOADING'));
2575 var cObj = YAHOO.util.Connect.asyncRequest('GET','index.php?to_pdf=1&module=Home&action=UnifiedSearch&usa_form=true',
2576 {success: SUGAR.unifiedSearchAdvanced.animate, failure: SUGAR.unifiedSearchAdvanced.animate}, null);
2578 else SUGAR.unifiedSearchAdvanced.animate();
2581 animate: function(data) {
2582 ajaxStatus.hideStatus();
2585 SUGAR.unifiedSearchAdvanced.usa_content = data.responseText;
2586 SUGAR.unifiedSearchAdvanced.usa_div.innerHTML = SUGAR.unifiedSearchAdvanced.usa_content;
2588 if(SUGAR.unifiedSearchAdvanced.usa_open) {
2589 document.UnifiedSearch.advanced.value = 'false';
2590 SUGAR.unifiedSearchAdvanced.anim_close.animate();
2593 document.UnifiedSearch.advanced.value = 'true';
2594 SUGAR.unifiedSearchAdvanced.usa_div.style.display = '';
2595 YAHOO.util.Dom.setX(SUGAR.unifiedSearchAdvanced.usa_div, SUGAR.unifiedSearchAdvanced.usa_img._x - 90);
2596 YAHOO.util.Dom.setY(SUGAR.unifiedSearchAdvanced.usa_div, SUGAR.unifiedSearchAdvanced.usa_img._y + 15);
2597 SUGAR.unifiedSearchAdvanced.anim_open.animate();
2599 SUGAR.unifiedSearchAdvanced.usa_open = !SUGAR.unifiedSearchAdvanced.usa_open;
2604 checkUsaAdvanced: function() {
2605 if(document.UnifiedSearch.advanced.value == 'true') {
2606 document.UnifiedSearchAdvanced.query_string.value = document.UnifiedSearch.query_string.value;
2607 document.UnifiedSearchAdvanced.submit();
2614 if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.unifiedSearchAdvanced.init);
2619 * Toggles the header
2621 toggleHeader : function() {
2622 var h = document.getElementById('header');
2626 if(h.style.display == 'none') {
2627 h.style.display = '';
2629 h.style.display = 'none';
2633 alert(SUGAR.language.get("app_strings", "ERR_NO_HEADER_ID"));
2640 * General Sugar Utils
2642 SUGAR.util = function () {
2643 var additionalDetailsCache;
2644 var additionalDetailsCalls;
2645 var additionalDetailsRpcCall;
2648 getAndRemove : function (el) {
2649 if (YAHOO && YAHOO.util && YAHOO.util.Dom)
2650 el = YAHOO.util.Dom.get(el);
2651 else if (typeof (el) == "string")
2652 el = document.getElementById(el);
2653 if (el && el.parentNode)
2654 el.parentNode.removeChild(el);
2658 paramsToUrl : function (params) {
2661 url += i + "=" + params[i] + "&";
2665 evalScript:function(text){
2667 var waitUntilLoaded = function(){
2668 SUGAR.evalScript_waitCount--;
2669 if (SUGAR.evalScript_waitCount == 0) {
2670 var headElem = document.getElementsByTagName('head')[0];
2671 for ( var i = 0; i < SUGAR.evalScript_evalElem.length; i++) {
2672 var tmpElem = document.createElement('script');
2673 tmpElem.type = 'text/javascript';
2674 tmpElem.text = SUGAR.evalScript_evalElem[i];
2675 headElem.appendChild(tmpElem);
2680 var tmpElem = document.createElement('div');
2681 tmpElem.innerHTML = text;
2682 var results = tmpElem.getElementsByTagName('script');
2683 if (results == null) {
2684 // No scripts found, bail out
2688 var headElem = document.getElementsByTagName('head')[0];
2690 SUGAR.evalScript_waitCount = 0;
2691 SUGAR.evalScript_evalElem = new Array();
2692 for (var i = 0; i < results.length; i++) {
2693 if (typeof(results[i]) != 'object') {
2696 tmpElem = document.createElement('script');
2697 tmpElem.type = 'text/javascript';
2698 if (results[i].src != null && results[i].src != '') {
2699 tmpElem.src = results[i].src;
2701 // Need to defer execution of these scripts until the
2702 // required javascript files are fully loaded
2703 SUGAR.evalScript_evalElem[SUGAR.evalScript_evalElem.length] = results[i].text;
2706 tmpElem.addEventListener('load', waitUntilLoaded);
2707 SUGAR.evalScript_waitCount++;
2708 headElem.appendChild(tmpElem);
2710 // Add some code to handle pages without any external scripts
2711 SUGAR.evalScript_waitCount++;
2714 // Don't try and process things the IE way
2718 var objRegex = /<\s*script([^>]*)>((.|\s|\v|\0)*?)<\s*\/script\s*>/igm;
2720 var result = objRegex.exec(text);
2721 while(result && result.index > lastIndex){
2722 lastIndex = result.index
2724 var script = document.createElement('script');
2725 script.type= 'text/javascript';
2726 if(result[1].indexOf("src=") > -1){
2727 var srcRegex = /.*src=['"]([a-zA-Z0-9\&\/\.\?=:]*)['"].*/igm;
2728 var srcResult = result[1].replace(srcRegex, '$1');
2729 script.src = srcResult;
2731 script.text = result[2];
2733 document.body.appendChild(script)
2738 result = objRegex.exec(text);
2742 * Gets the sidebar object
2743 * @return object pointer to the sidebar element
2745 getLeftColObj: function() {
2746 leftColObj = document.getElementById('leftCol');
2747 while(leftColObj.nodeName != 'TABLE') {
2748 leftColObj = leftColObj.firstChild;
2750 leftColTable = leftColObj;
2751 leftColTd = leftColTable.getElementsByTagName('td')[0];
2752 leftColTdRegion = YAHOO.util.Dom.getRegion(leftColTd);
2753 leftColTd.style.width = (leftColTdRegion.right - leftColTdRegion.left) + 'px';
2758 * Fills the shortcut menu placeholders w/ actual content
2759 * Call this on load event
2761 * @param shortcutContent Array array of content to fill in
2763 fillShortcuts: function(e, shortcutContent) {
2766 // don't do this if leftCol isn't available
2767 if (document.getElementById('leftCol') == undefined) { return; }
2769 spans = document.getElementById('leftCol').getElementsByTagName('span');
2770 hideCol = document.getElementById('HideMenu').getElementsByTagName('span');
2771 w = spans.length + 1;
2773 spans[w] = hideCol[i];
2776 for(je in shortcutContent) {
2778 if(typeof spans[wp].innerHTML != 'undefined' && spans[wp].innerHTML == ('wp_shortcut_fill_' + je)) {
2779 if(typeof spans[wp].parentNode.parentNode == 'object') {
2780 if(typeof spans[wp].parentNode.parentNode.onclick != 'undefined') {
2781 spans[wp].parentNode.parentNode.onclick = null;
2783 // If the wp_shortcut span is contained by an A tag, replace the A with a DIV.
2784 if(spans[wp].parentNode.tagName == 'A' && !isIE) {
2785 var newDiv = document.createElement('DIV');
2786 var parentAnchor = spans[wp].parentNode;
2788 spans[wp].parentNode.parentNode.style.display = 'none';
2790 // Copy styles over to the new container div
2791 if(window.getComputedStyle) {
2792 var parentStyle = window.getComputedStyle(parentAnchor, '');
2793 for(var styleName in parentStyle) {
2794 if(typeof parentStyle[styleName] != 'function'
2795 && styleName != 'display'
2796 && styleName != 'borderWidth'
2797 && styleName != 'visibility') {
2799 newDiv.style[styleName] = parentStyle[styleName];
2801 // Catches .length and .parentRule, and others
2807 // Replace the A with the DIV
2808 newDiv.appendChild(spans[wp]);
2809 parentAnchor.parentNode.replaceChild(newDiv, parentAnchor);
2811 spans[wp].parentNode.parentNode.style.display = '';
2814 spans[wp].innerHTML = shortcutContent[je]; // fill w/ content
2815 if(spans[wp].style) spans[wp].style.display = '';
2821 * Make an AJAX request.
2823 * @param url string resource to load
2824 * @param theDiv string id of element to insert loaded data into
2825 * @param postForm string if set, a POST request will be made to resource specified by url using the form named by postForm
2826 * @param callback string name of function to invoke after HTTP response is recieved
2827 * @param callbackParam any parameter to pass to callback when invoked
2828 * @param appendMode bool if true, HTTP response will be appended to the contents of theDiv, or else contents will be overriten.
2830 retrieveAndFill: function(url, theDiv, postForm, callback, callbackParam, appendMode) {
2831 if(typeof theDiv == 'string') {
2833 theDiv = document.getElementById(theDiv);
2840 var success = function(data) {
2841 if (typeof theDiv != 'undefined' && theDiv != null)
2844 if (typeof appendMode != 'undefined' && appendMode)
2846 theDiv.innerHTML += data.responseText;
2850 theDiv.innerHTML = data.responseText;
2857 if (typeof callback != 'undefined' && callback != null) callback(callbackParam);
2860 if(typeof postForm == 'undefined' || postForm == null) {
2861 var cObj = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
2864 YAHOO.util.Connect.setForm(postForm);
2865 var cObj = YAHOO.util.Connect.asyncRequest('POST', url, {success: success, failure: success});
2868 checkMaxLength: function() { // modified from http://www.quirksmode.org/dom/maxlength.html
2869 var maxLength = this.getAttribute('maxlength');
2870 var currentLength = this.value.length;
2871 if (currentLength > maxLength) {
2872 this.value = this.value.substring(0, maxLength);
2877 * Adds maxlength attribute to textareas
2879 setMaxLength: function() { // modified from http://www.quirksmode.org/dom/maxlength.html
2880 var x = document.getElementsByTagName('textarea');
2881 for (var i=0;i<x.length;i++) {
2882 if (x[i].getAttribute('maxlength')) {
2883 x[i].onkeyup = x[i].onchange = SUGAR.util.checkMaxLength;
2890 * Retrieves additional details dynamically
2892 getAdditionalDetails: function(bean, id, spanId) {
2894 oReturn = function(body, caption, width, theme) {
2895 var _refx = 25-width;
2896 return overlib(body, CAPTION, caption, STICKY, MOUSEOFF, 1000, WIDTH, width, CLOSETEXT, ('<img border=0 style="margin-left:2px; margin-right: 2px;" src=index.php?entryPoint=getImage&themeName='+SUGAR.themes.theme_name+'&imageName=close.gif>'), CLOSETITLE, SUGAR.language.get('app_strings','LBL_ADDITIONAL_DETAILS_CLOSE_TITLE'), CLOSECLICK, FGCLASS, 'olFgClass', CGCLASS, 'olCgClass', BGCLASS, 'olBgClass', TEXTFONTCLASS, 'olFontClass', CAPTIONFONTCLASS, 'olCapFontClass', CLOSEFONTCLASS, 'olCloseFontClass', REF, spanId, REFC, 'LL', REFX, _refx);
2899 success = function(data) {
2900 eval(data.responseText);
2902 SUGAR.util.additionalDetailsCache[spanId] = new Array();
2903 SUGAR.util.additionalDetailsCache[spanId]['body'] = result['body'];
2904 SUGAR.util.additionalDetailsCache[spanId]['caption'] = result['caption'];
2905 SUGAR.util.additionalDetailsCache[spanId]['width'] = result['width'];
2906 SUGAR.util.additionalDetailsCache[spanId]['theme'] = result['theme'];
2907 ajaxStatus.hideStatus();
2908 return oReturn(SUGAR.util.additionalDetailsCache[spanId]['body'], SUGAR.util.additionalDetailsCache[spanId]['caption'], SUGAR.util.additionalDetailsCache[spanId]['width'], SUGAR.util.additionalDetailsCache[spanId]['theme']);
2911 if(typeof SUGAR.util.additionalDetailsCache[spanId] != 'undefined')
2912 return oReturn(SUGAR.util.additionalDetailsCache[spanId]['body'], SUGAR.util.additionalDetailsCache[spanId]['caption'], SUGAR.util.additionalDetailsCache[spanId]['width'], SUGAR.util.additionalDetailsCache[spanId]['theme']);
2914 if(typeof SUGAR.util.additionalDetailsCalls[spanId] != 'undefined') // call already in progress
2916 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_LOADING'));
2917 url = 'index.php?to_pdf=1&module=Home&action=AdditionalDetailsRetrieve&bean=' + bean + '&id=' + id;
2918 SUGAR.util.additionalDetailsCalls[spanId] = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
2922 SUGAR.util.additionalDetailsRpcCall = window.setTimeout('go()', 250);
2924 clearAdditionalDetailsCall: function() {
2925 if(typeof SUGAR.util.additionalDetailsRpcCall == 'number') window.clearTimeout(SUGAR.util.additionalDetailsRpcCall);
2928 * A function that extends functionality from parent to child.
2930 extend : function(subc, superc, overrides) {
2931 subc.prototype = new superc; // set the superclass
2934 for (var i in overrides) subc.prototype[i] = overrides[i];
2939 SUGAR.util.additionalDetailsCache = new Array();
2940 SUGAR.util.additionalDetailsCalls = new Array();
2941 if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.util.setMaxLength); // allow textareas to obey maxlength attrib
2943 SUGAR.savedViews = function() {
2944 var selectedOrderBy;
2945 var selectedSortOrder;
2948 var columnsMeta; // meta data for the display columns
2951 setChooser: function() {
2953 var displayColumnsDef = new Array();
2954 var hideTabsDef = new Array();
2956 var left_td = document.getElementById('display_tabs_td');
2957 if(typeof left_td == 'undefined' || left_td == null) return; // abort!
2958 var right_td = document.getElementById('hide_tabs_td');
2960 var displayTabs = left_td.getElementsByTagName('select')[0];
2961 var hideTabs = right_td.getElementsByTagName('select')[0];
2963 for(i = 0; i < displayTabs.options.length; i++) {
2964 displayColumnsDef.push(displayTabs.options[i].value);
2967 if(typeof hideTabs != 'undefined') {
2968 for(i = 0; i < hideTabs.options.length; i++) {
2969 hideTabsDef.push(hideTabs.options[i].value);
2972 if (!SUGAR.savedViews.clearColumns)
2973 document.getElementById('displayColumnsDef').value = displayColumnsDef.join('|');
2974 document.getElementById('hideTabsDef').value = hideTabsDef.join('|');
2977 select: function(saved_search_select) {
2978 for(var wp = 0; wp < document.search_form.saved_search_select.options.length; wp++) {
2979 if(typeof document.search_form.saved_search_select.options[wp].value != 'undefined' &&
2980 document.search_form.saved_search_select.options[wp].value == saved_search_select) {
2981 document.search_form.saved_search_select.selectedIndex = wp;
2982 document.search_form.ss_delete.style.display = '';
2983 document.search_form.ss_update.style.display = '';
2987 saved_search_action: function(action, delete_lang) {
2988 if(action == 'delete') {
2989 if(!confirm(delete_lang)) return;
2991 if(action == 'save') {
2992 if(document.search_form.saved_search_name.value.replace(/^\s*|\s*$/g, '') == '') {
2993 alert(SUGAR.language.get('app_strings', 'LBL_SAVED_SEARCH_ERROR'));
2998 // This check is needed for the Activities module (Calls/Meetings/Tasks).
2999 if (document.search_form.saved_search_action)
3001 document.search_form.saved_search_action.value = action;
3002 document.search_form.search_module.value = document.search_form.module.value;
3003 document.search_form.module.value = 'SavedSearch';
3004 // Bug 31922 - Make sure to specify that we want to hit the index view here of
3005 // the SavedSearch module, since the ListView doesn't have the logic to save the
3006 // search and redirect back
3007 document.search_form.action.value = 'index';
3009 document.search_form.submit();
3011 shortcut_select: function(selectBox, module) {
3013 selecturl = 'index.php?module=SavedSearch&search_module=' + module + '&action=index&saved_search_select=' + selectBox.options[selectBox.selectedIndex].value
3014 //add searchFormTab to url if it is available. This determines what tab to render
3015 if(typeof(document.getElementById('searchFormTab'))!='undefined'){
3016 selecturl = selecturl + '&searchFormTab=' + document.search_form.searchFormTab.value;
3018 //add showSSDIV to url if it is available. This determines whether saved search sub form should
3019 //be rendered open or not
3020 if(document.getElementById('showSSDIV') && typeof(document.getElementById('showSSDIV') !='undefined')){
3021 selecturl = selecturl + '&showSSDIV='+document.getElementById('showSSDIV').value;
3023 //use created url to navigate
3024 document.location.href = selecturl;
3026 handleForm: function() {
3027 SUGAR.tabChooser.movementCallback = function(left_side, right_side) {
3028 while(document.getElementById('orderBySelect').childNodes.length != 0) { // clear out order by options
3029 document.getElementById('orderBySelect').removeChild(document.getElementById('orderBySelect').lastChild);
3032 var selectedIndex = 0;
3033 var nodeCount = -1; // need this because the counter i also includes "undefined" nodes
3034 // which was breaking Calls and Meetings
3036 for(i in left_side.childNodes) { // fill in order by options
3037 if(typeof left_side.childNodes[i].nodeName != 'undefined' &&
3038 left_side.childNodes[i].nodeName.toLowerCase() == 'option' &&
3039 typeof SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value] != 'undefined' && // check if column is sortable
3040 typeof SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value]['sortable'] == 'undefined' &&
3041 SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value]['sortable'] != false) {
3043 optionNode = document.createElement('option');
3044 optionNode.value = left_side.childNodes[i].value;
3045 optionNode.innerHTML = left_side.childNodes[i].innerHTML;
3046 document.getElementById('orderBySelect').appendChild(optionNode);
3047 if(optionNode.value == SUGAR.savedViews.selectedOrderBy)
3048 selectedIndex = nodeCount;
3051 // Firefox needs this to be set after all the option nodes are created.
3052 document.getElementById('orderBySelect').selectedIndex = selectedIndex;
3054 SUGAR.tabChooser.movementCallback(document.getElementById('display_tabs_td').getElementsByTagName('select')[0]);
3056 // This check is needed for the Activities module (Calls/Meetings/Tasks).
3057 if (document.search_form.orderBy)
3058 document.search_form.orderBy.options.value = SUGAR.savedViews.selectedOrderBy;
3061 if(SUGAR.savedViews.selectedSortOrder == 'DESC') document.getElementById('sort_order_desc_radio').checked = true;
3062 else document.getElementById('sort_order_asc_radio').checked = true;
3067 SUGAR.searchForm = function() {
3070 // searchForm tab selector util
3071 searchFormSelect: function(view, previousView) {
3072 var module = view.split('|')[0];
3073 var theView = view.split('|')[1];
3075 var handleDisplay = function() { // hide other divs
3076 document.search_form.searchFormTab.value = theView;
3077 patt = module+"(.*)SearchForm$";
3078 divId=document.search_form.getElementsByTagName('div');
3079 // Hide all the search forms and retrive the name of the previous search tab (useful for the first load because previousView is empty)
3080 for (i=0;i<divId.length;i++){
3081 if(divId[i].id.match(module)==module){
3082 if(divId[i].id.match('SearchForm')=='SearchForm'){
3083 if(document.getElementById(divId[i].id).style.display == ''){
3084 previousTab=divId[i].id.match(patt)[1];
3086 document.getElementById(divId[i].id).style.display = 'none';
3090 // show the good search form.
3091 document.getElementById(module + theView + 'SearchForm').style.display = '';
3092 //if its not the first tab show there is a previous tab.
3094 thepreviousView=previousView.split('|')[1];
3097 thepreviousView=previousTab;
3099 thepreviousView=thepreviousView.replace(/_search/, "");
3100 // Process to retrieve the completed field from one tab to an other.
3101 for(num in document.search_form.elements) {
3102 if(document.search_form.elements[num]) {
3103 el = document.search_form.elements[num];
3104 pattern="^(.*)_"+thepreviousView+"$";
3105 if(typeof el.type != 'undefined' && typeof el.name != 'undefined' && el.name.match(pattern)) {
3106 advanced_input_name = el.name.match(pattern)[1]; // strip
3107 advanced_input_name = advanced_input_name+"_"+theView.replace(/_search/, "");
3108 if(typeof document.search_form[advanced_input_name] != 'undefined') // if advanced input of same name exists
3109 SUGAR.searchForm.copyElement(advanced_input_name, el);
3115 // if tab is not cached
3116 if(document.getElementById(module + theView + 'SearchForm').innerHTML == '') {
3117 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_LOADING'));
3118 var success = function(data) {
3119 document.getElementById(module + theView + 'SearchForm').innerHTML = data.responseText;
3121 SUGAR.util.evalScript(data.responseText);
3122 // pass script variables to global scope
3123 if(theView == 'saved_views') {
3124 if(typeof columnsMeta != 'undefined') SUGAR.savedViews.columnsMeta = columnsMeta;
3125 if(typeof selectedOrderBy != 'undefined') SUGAR.savedViews.selectedOrderBy = selectedOrderBy;
3126 if(typeof selectedSortOrder != 'undefined') SUGAR.savedViews.selectedSortOrder = selectedSortOrder;
3131 ajaxStatus.hideStatus();
3133 url = 'index.php?module=' + module + '&action=index&search_form_only=true&to_pdf=true&search_form_view=' + theView;
3135 //check to see if tpl has been specified. If so then pass location through url string
3137 if(document.getElementById('search_tpl') !=null && typeof(document.getElementById('search_tpl')) != 'undefined'){
3138 tpl = document.getElementById('search_tpl').value;
3139 if(tpl != ''){url += '&search_tpl='+tpl;}
3142 if(theView == 'saved_views') // handle the tab chooser
3143 url += '&displayColumns=' + SUGAR.savedViews.displayColumns + '&hideTabs=' + SUGAR.savedViews.hideTabs + '&orderBy=' + SUGAR.savedViews.selectedOrderBy + '&sortOrder=' + SUGAR.savedViews.selectedSortOrder;
3145 var cObj = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
3147 else { // that form already retrieved
3152 // copies one input to another
3153 copyElement: function(inputName, copyFromElement) {
3154 switch(copyFromElement.type) {
3157 document.search_form[inputName].value = copyFromElement.value;
3161 // This function is here to clear the form, instead of "resubmitting it
3162 clear_form: function(form) {
3163 var elemList = form.elements;
3167 for( var i = 0; i < elemList.length ; i++ ) {
3169 if ( typeof(elem.type) == 'undefined' ) {
3173 elemType = elem.type.toLowerCase();
3175 if ( elemType == 'text' || elemType == 'textarea' || elemType == 'password' ) {
3178 else if ( elemType == 'select' || elemType == 'select-one' || elemType == 'select-multiple' ) {
3179 // We have, what I hope, is a select box, time to unselect all options
3180 var optionList = elem.options;
3181 for ( var ii = 0 ; ii < optionList.length ; ii++ ) {
3182 optionList[ii].selected = false;
3185 else if ( elemType == 'radio' || elemType == 'checkbox' ) {
3186 elem.checked = false;
3187 elem.selected = false;
3189 else if ( elemType == 'hidden' ) {
3190 // We only want to reset the hidden values that link to the select boxes.
3191 if ( ( elem.name.length > 3 && elem.name.substring(elem.name.length-3) == '_id' )
3192 || ( elem.name.length > 12 && elem.name.substring(elem.name.length-12) == '_id_advanced' ) ) {
3197 SUGAR.savedViews.clearColumns = true;
3201 // Code for the column/tab chooser used on homepage and in admin section
3202 SUGAR.tabChooser = function () {
3203 var object_refs = new Array();
3205 /* Describe certain transfers as invalid */
3208 movementCallback: function(left_side, right_side) {},
3209 orderCallback: function(left_side, right_side) {},
3211 freezeOptions: function(left_name, right_name, target) {
3212 if(!SUGAR.tabChooser.frozenOptions) { SUGAR.tabChooser.frozenOptions = []; }
3213 if(!SUGAR.tabChooser.frozenOptions[left_name]) { SUGAR.tabChooser.frozenOptions[left_name] = []; }
3214 if(!SUGAR.tabChooser.frozenOptions[left_name][right_name]) { SUGAR.tabChooser.frozenOptions[left_name][right_name] = []; }
3215 if(typeof target == 'array') {
3216 for(var i in target) {
3217 SUGAR.tabChooser.frozenOptions[left_name][right_name][target[i]] = true;
3220 SUGAR.tabChooser.frozenOptions[left_name][right_name][target] = true;
3224 buildSelectHTML: function(info) {
3225 var text = "<select";
3227 if(typeof (info['select']['size']) != 'undefined') {
3228 text +=" size=\""+ info['select']['size'] +"\"";
3231 if(typeof (info['select']['name']) != 'undefined') {
3232 text +=" name=\""+ info['select']['name'] +"\"";
3235 if(typeof (info['select']['style']) != 'undefined') {
3236 text +=" style=\""+ info['select']['style'] +"\"";
3239 if(typeof (info['select']['onchange']) != 'undefined') {
3240 text +=" onChange=\""+ info['select']['onchange'] +"\"";
3243 if(typeof (info['select']['multiple']) != 'undefined') {
3248 for(i=0; i<info['options'].length;i++) {
3249 option = info['options'][i];
3250 text += "<option value=\""+option['value']+"\" ";
3251 if ( typeof (option['selected']) != 'undefined' && option['selected']== true) {
3254 text += ">"+option['text']+"</option>";
3256 text += "</select>";
3260 left_to_right: function(left_name, right_name, left_size, right_size) {
3261 SUGAR.savedViews.clearColumns = false;
3262 var left_td = document.getElementById(left_name+'_td');
3263 var right_td = document.getElementById(right_name+'_td');
3265 var display_columns_ref = left_td.getElementsByTagName('select')[0];
3266 var hidden_columns_ref = right_td.getElementsByTagName('select')[0];
3268 var selected_left = new Array();
3269 var notselected_left = new Array();
3270 var notselected_right = new Array();
3272 var left_array = new Array();
3274 var frozen_options = SUGAR.tabChooser.frozenOptions;
3275 frozen_options = frozen_options && frozen_options[left_name] && frozen_options[left_name][right_name]?frozen_options[left_name][right_name]:[];
3277 // determine which options are selected in left
3278 for (i=0; i < display_columns_ref.options.length; i++)
3280 if ( display_columns_ref.options[i].selected == true && !frozen_options[display_columns_ref.options[i].value])
3282 selected_left[selected_left.length] = {text: display_columns_ref.options[i].text, value: display_columns_ref.options[i].value};
3286 notselected_left[notselected_left.length] = {text: display_columns_ref.options[i].text, value: display_columns_ref.options[i].value};
3291 for (i=0; i < hidden_columns_ref.options.length; i++)
3293 notselected_right[notselected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
3297 var left_select_html_info = new Object();
3298 var left_options = new Array();
3299 var left_select = new Object();
3301 left_select['name'] = left_name+'[]';
3302 left_select['id'] = left_name;
3303 left_select['size'] = left_size;
3304 left_select['multiple'] = 'true';
3306 var right_select_html_info = new Object();
3307 var right_options = new Array();
3308 var right_select = new Object();
3310 right_select['name'] = right_name+'[]';
3311 right_select['id'] = right_name;
3312 right_select['size'] = right_size;
3313 right_select['multiple'] = 'true';
3315 for (i = 0; i < notselected_right.length; i++) {
3316 right_options[right_options.length] = notselected_right[i];
3319 for (i = 0; i < selected_left.length; i++) {
3320 right_options[right_options.length] = selected_left[i];
3322 for (i = 0; i < notselected_left.length; i++) {
3323 left_options[left_options.length] = notselected_left[i];
3325 left_select_html_info['options'] = left_options;
3326 left_select_html_info['select'] = left_select;
3327 right_select_html_info['options'] = right_options;
3328 right_select_html_info['select'] = right_select;
3329 right_select_html_info['style'] = 'background: lightgrey';
3331 var left_html = this.buildSelectHTML(left_select_html_info);
3332 var right_html = this.buildSelectHTML(right_select_html_info);
3334 left_td.innerHTML = left_html;
3335 right_td.innerHTML = right_html;
3337 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3338 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3340 this.movementCallback(object_refs[left_name], object_refs[right_name]);
3346 right_to_left: function(left_name, right_name, left_size, right_size, max_left) {
3347 SUGAR.savedViews.clearColumns = false;
3348 var left_td = document.getElementById(left_name+'_td');
3349 var right_td = document.getElementById(right_name+'_td');
3351 var display_columns_ref = left_td.getElementsByTagName('select')[0];
3352 var hidden_columns_ref = right_td.getElementsByTagName('select')[0];
3354 var selected_right = new Array();
3355 var notselected_right = new Array();
3356 var notselected_left = new Array();
3358 var frozen_options = SUGAR.tabChooser.frozenOptions;
3359 frozen_options = SUGAR.tabChooser.frozenOptions && SUGAR.tabChooser.frozenOptions[right_name] && SUGAR.tabChooser.frozenOptions[right_name][left_name]?SUGAR.tabChooser.frozenOptions[right_name][left_name]:[];
3361 for (i=0; i < hidden_columns_ref.options.length; i++)
3363 if (hidden_columns_ref.options[i].selected == true && !frozen_options[hidden_columns_ref.options[i].value])
3365 selected_right[selected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
3369 notselected_right[notselected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
3374 if(max_left != '' && (display_columns_ref.length + selected_right.length) > max_left) {
3375 alert('Maximum of ' + max_left + ' columns can be displayed.');
3379 for (i=0; i < display_columns_ref.options.length; i++)
3381 notselected_left[notselected_left.length] = {text:display_columns_ref.options[i].text, value:display_columns_ref.options[i].value};
3385 var left_select_html_info = new Object();
3386 var left_options = new Array();
3387 var left_select = new Object();
3389 left_select['name'] = left_name+'[]';
3390 left_select['id'] = left_name;
3391 left_select['multiple'] = 'true';
3392 left_select['size'] = left_size;
3394 var right_select_html_info = new Object();
3395 var right_options = new Array();
3396 var right_select = new Object();
3398 right_select['name'] = right_name+ '[]';
3399 right_select['id'] = right_name;
3400 right_select['multiple'] = 'true';
3401 right_select['size'] = right_size;
3403 for (i = 0; i < notselected_left.length; i++) {
3404 left_options[left_options.length] = notselected_left[i];
3407 for (i = 0; i < selected_right.length; i++) {
3408 left_options[left_options.length] = selected_right[i];
3410 for (i = 0; i < notselected_right.length; i++) {
3411 right_options[right_options.length] = notselected_right[i];
3413 left_select_html_info['options'] = left_options;
3414 left_select_html_info['select'] = left_select;
3415 right_select_html_info['options'] = right_options;
3416 right_select_html_info['select'] = right_select;
3417 right_select_html_info['style'] = 'background: lightgrey';
3419 var left_html = this.buildSelectHTML(left_select_html_info);
3420 var right_html = this.buildSelectHTML(right_select_html_info);
3422 left_td.innerHTML = left_html;
3423 right_td.innerHTML = right_html;
3425 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3426 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3428 this.movementCallback(object_refs[left_name], object_refs[right_name]);
3433 up: function(name, left_name, right_name) {
3434 SUGAR.savedViews.clearColumns = false;
3435 var left_td = document.getElementById(left_name+'_td');
3436 var right_td = document.getElementById(right_name+'_td');
3437 var td = document.getElementById(name+'_td');
3438 var obj = td.getElementsByTagName('select')[0];
3439 obj = (typeof obj == "string") ? document.getElementById(obj) : obj;
3440 if (obj.tagName.toLowerCase() != "select" && obj.length < 2)
3442 var sel = new Array();
3444 for (i=0; i<obj.length; i++) {
3445 if (obj[i].selected == true) {
3446 sel[sel.length] = i;
3449 for (i=0; i < sel.length; i++) {
3450 if (sel[i] != 0 && !obj[sel[i]-1].selected) {
3451 var tmp = new Array(obj[sel[i]-1].text, obj[sel[i]-1].value);
3452 obj[sel[i]-1].text = obj[sel[i]].text;
3453 obj[sel[i]-1].value = obj[sel[i]].value;
3454 obj[sel[i]].text = tmp[0];
3455 obj[sel[i]].value = tmp[1];
3456 obj[sel[i]-1].selected = true;
3457 obj[sel[i]].selected = false;
3461 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3462 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3464 this.orderCallback(object_refs[left_name], object_refs[right_name]);
3469 down: function(name, left_name, right_name) {
3470 SUGAR.savedViews.clearColumns = false;
3471 var left_td = document.getElementById(left_name+'_td');
3472 var right_td = document.getElementById(right_name+'_td');
3473 var td = document.getElementById(name+'_td');
3474 var obj = td.getElementsByTagName('select')[0];
3475 if (obj.tagName.toLowerCase() != "select" && obj.length < 2)
3477 var sel = new Array();
3478 for (i=obj.length-1; i>-1; i--) {
3479 if (obj[i].selected == true) {
3480 sel[sel.length] = i;
3483 for (i=0; i < sel.length; i++) {
3484 if (sel[i] != obj.length-1 && !obj[sel[i]+1].selected) {
3485 var tmp = new Array(obj[sel[i]+1].text, obj[sel[i]+1].value);
3486 obj[sel[i]+1].text = obj[sel[i]].text;
3487 obj[sel[i]+1].value = obj[sel[i]].value;
3488 obj[sel[i]].text = tmp[0];
3489 obj[sel[i]].value = tmp[1];
3490 obj[sel[i]+1].selected = true;
3491 obj[sel[i]].selected = false;
3495 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3496 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3498 this.orderCallback(object_refs[left_name], object_refs[right_name]);
3503 }(); // end tabChooser
3505 SUGAR.language = function() {
3507 languages : new Array(),
3509 setLanguage: function(module, data) {
3510 if (!SUGAR.language.languages) {
3513 SUGAR.language.languages[module] = data;
3516 get: function(module, str) {
3517 if(typeof SUGAR.language.languages[module] == 'undefined' || typeof SUGAR.language.languages[module][str] == 'undefined')
3521 return SUGAR.language.languages[module][str];
3524 translate: function(module, str)
3526 text = this.get(module, str);
3527 return text != 'undefined' ? text : this.get('app_strings', str);
3532 SUGAR.contextMenu = function() {
3534 objects: new Object(),
3535 objectTypes: new Object(),
3537 * Registers a new object for the context menu.
3538 * objectType - name of the type
3540 * metaData - metaData to pass to the action function
3542 registerObject: function(objectType, id, metaData) {
3543 SUGAR.contextMenu.objects[id] = new Object();
3544 SUGAR.contextMenu.objects[id] = {'objectType' : objectType, 'metaData' : metaData};
3547 * Registers a new object type
3548 * name - name of the type
3549 * menuItems - array of menu items
3551 registerObjectType: function(name, menuItems) {
3552 SUGAR.contextMenu.objectTypes[name] = new Object();
3553 SUGAR.contextMenu.objectTypes[name] = {'menuItems' : menuItems, 'objects' : new Array()};
3556 * Determines which menu item was clicked
3558 getListItemFromEventTarget: function(p_oNode) {
3560 if(p_oNode.tagName == "LI") {
3565 if(p_oNode.tagName == "LI") {
3570 } while((p_oNode = p_oNode.parentNode));
3575 * handles movement within context menu
3577 onContextMenuMove: function() {
3578 var oNode = this.contextEventTarget;
3579 var bDisabled = (oNode.tagName == "UL");
3580 var i = this.getItemGroups()[0].length - 1;
3582 this.getItem(i).cfg.setProperty("disabled", bDisabled);
3587 * handles clicks on a context menu ITEM
3589 onContextMenuItemClick: function(p_sType, p_aArguments, p_oItem) {
3590 var oLI = SUGAR.contextMenu.getListItemFromEventTarget(this.parent.contextEventTarget);
3591 id = this.parent.contextEventTarget.parentNode.id; // id of the target
3592 funct = eval(SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[id]['objectType']]['menuItems'][this.index]['action']);
3593 funct(this.parent.contextEventTarget, SUGAR.contextMenu.objects[id]['metaData']);
3596 * Initializes all context menus registered
3599 for(var i in SUGAR.contextMenu.objects) { // make a variable called objects in objectTypes containg references to all triggers
3600 if(typeof SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'] == 'undefined')
3601 SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'] = new Array();
3602 SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'].push(document.getElementById(i));
3604 // register the menus
3605 for(var i in SUGAR.contextMenu.objectTypes) {
3606 var oContextMenu = new YAHOO.widget.ContextMenu(i, {'trigger': SUGAR.contextMenu.objectTypes[i]['objects']});
3607 var aMainMenuItems = SUGAR.contextMenu.objectTypes[i]['menuItems'];
3608 var nMainMenuItems = aMainMenuItems.length;
3610 for(var j = 0; j < nMainMenuItems; j++) {
3611 oMenuItem = new YAHOO.widget.ContextMenuItem(aMainMenuItems[j].text, { helptext: aMainMenuItems[j].helptext });
3612 oMenuItem.clickEvent.subscribe(SUGAR.contextMenu.onContextMenuItemClick, oMenuItem, true);
3613 oContextMenu.addItem(oMenuItem);
3615 // Add a "move" event handler to the context menu
3616 oContextMenu.moveEvent.subscribe(SUGAR.contextMenu.onContextMenuMove, oContextMenu, true);
3617 // Add a "keydown" event handler to the context menu
3618 oContextMenu.keyDownEvent.subscribe(SUGAR.contextMenu.onContextMenuItemClick, oContextMenu, true);
3619 // Render the context menu
3620 oContextMenu.render(document.body);
3626 SUGAR.contextMenu.actions = function() {
3629 * redirects to a new note with the clicked on object as the target
3631 createNote: function(itemClicked, metaData) {
3632 loc = 'index.php?module=Notes&action=EditView';
3633 for(i in metaData) {
3634 if(i == 'notes_parent_type') loc += '&parent_type=' + metaData[i];
3635 else if(i != 'module' && i != 'parent_type') loc += '&' + i + '=' + metaData[i];
3637 document.location = loc;
3640 * redirects to a new note with the clicked on object as the target
3642 scheduleMeeting: function(itemClicked, metaData) {
3643 loc = 'index.php?module=Meetings&action=EditView';
3644 for(i in metaData) {
3645 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3647 document.location = loc;
3650 * redirects to a new note with the clicked on object as the target
3652 scheduleCall: function(itemClicked, metaData) {
3653 loc = 'index.php?module=Calls&action=EditView';
3654 for(i in metaData) {
3655 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3657 document.location = loc;
3660 * redirects to a new contact with the clicked on object as the target
3662 createContact: function(itemClicked, metaData) {
3663 loc = 'index.php?module=Contacts&action=EditView';
3664 for(i in metaData) {
3665 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3667 document.location = loc;
3670 * redirects to a new task with the clicked on object as the target
3672 createTask: function(itemClicked, metaData) {
3673 loc = 'index.php?module=Tasks&action=EditView';
3674 for(i in metaData) {
3675 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3677 document.location = loc;
3680 * redirects to a new opportunity with the clicked on object as the target
3682 createOpportunity: function(itemClicked, metaData) {
3683 loc = 'index.php?module=Opportunities&action=EditView';
3684 for(i in metaData) {
3685 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3687 document.location = loc;
3690 * redirects to a new opportunity with the clicked on object as the target
3692 createCase: function(itemClicked, metaData) {
3693 loc = 'index.php?module=Cases&action=EditView';
3694 for(i in metaData) {
3695 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3697 document.location = loc;
3700 * handles add to favorites menu selection
3702 addToFavorites: function(itemClicked, metaData) {
3703 success = function(data) {
3705 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});
3710 //if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.contextMenu.init);
3712 // initially from popup_parent_helper.js
3713 var popup_request_data;
3716 function get_popup_request_data()
3718 return window.document.popup_request_data;
3721 function get_close_popup()
3723 return window.document.close_popup;
3726 function open_popup(module_name, width, height, initial_filter, close_popup, hide_clear_button, popup_request_data, popup_mode, create, metadata)
3728 if (typeof(popupCount) == "undefined" || popupCount == 0)
3731 // set the variables that the popup will pull from
3732 window.document.popup_request_data = popup_request_data;
3733 window.document.close_popup = close_popup;
3735 //globally changing width and height of standard pop up window from 600 x 400 to 800 x 800
3736 width = (width == 600) ? 800 : width;
3737 height = (height == 400) ? 800 : height;
3741 + 'module=' + module_name
3744 if(initial_filter != '')
3746 URL += '&query=true' + initial_filter;
3749 if(hide_clear_button)
3751 URL += '&hide_clear_button=true';
3754 windowName = module_name + '_popup_window' + popupCount;
3757 windowFeatures = 'width=' + width
3758 + ',height=' + height
3759 + ',resizable=1,scrollbars=1';
3761 if (popup_mode == '' && popup_mode == 'undefined') {
3762 popup_mode='single';
3764 URL+='&mode='+popup_mode;
3765 if (create == '' && create == 'undefined') {
3768 URL+='&create='+create;
3770 if (metadata != '' && metadata != 'undefined') {
3771 URL+='&metadata='+metadata;
3774 win = window.open(URL, windowName, windowFeatures);
3778 // put the focus on the popup if the browser supports the focus() method
3782 win.popupCount = popupCount;
3788 * The reply data must be a JSON array structured with the following information:
3789 * 1) form name to populate
3790 * 2) associative array of input names to values for populating the form
3792 var from_popup_return = false;
3794 function set_return_basic(popup_reply_data,filter)
3796 var form_name = popup_reply_data.form_name;
3797 var name_to_value_array = popup_reply_data.name_to_value_array;
3798 for (var the_key in name_to_value_array)
3800 if(the_key == 'toJSON')
3804 else if(the_key.match(filter))
3806 var displayValue=name_to_value_array[the_key].replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');;
3807 // begin andopes change: support for enum fields (SELECT)
3808 if(window.document.forms[form_name] && window.document.forms[form_name].elements[the_key]) {
3809 if(window.document.forms[form_name].elements[the_key].tagName == 'SELECT') {
3810 var selectField = window.document.forms[form_name].elements[the_key];
3811 for(var i = 0; i < selectField.options.length; i++) {
3812 if(selectField.options[i].text == displayValue) {
3813 selectField.options[i].selected = true;
3818 window.document.forms[form_name].elements[the_key].value = displayValue;
3821 // end andopes change: support for enum fields (SELECT)
3826 function set_return(popup_reply_data)
3828 from_popup_return = true;
3829 var form_name = popup_reply_data.form_name;
3830 var name_to_value_array = popup_reply_data.name_to_value_array;
3831 if(typeof name_to_value_array != 'undefined' && name_to_value_array['account_id'])
3834 var label_data_str = '';
3835 var current_label_data_str = '';
3836 for (var the_key in name_to_value_array)
3838 if(the_key == 'toJSON')
3844 var displayValue=name_to_value_array[the_key].replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');
3845 if(window.document.forms[form_name] && document.getElementById(the_key+'_label') && !the_key.match(/account/)) {
3846 var data_label = document.getElementById(the_key+'_label').innerHTML.replace(/\n/gi,'');
3847 label_str += data_label + ' \n';
3848 label_data_str += data_label + ' ' + displayValue + '\n';
3849 if(window.document.forms[form_name].elements[the_key]) {
3850 current_label_data_str += data_label + ' ' + window.document.forms[form_name].elements[the_key].value +'\n';
3855 if(label_data_str != label_str && current_label_data_str != label_str){
3856 if(confirm(SUGAR.language.get('app_strings', 'NTC_OVERWRITE_ADDRESS_PHONE_CONFIRM') + '\n\n' + label_data_str))
3858 set_return_basic(popup_reply_data,/\S/);
3860 set_return_basic(popup_reply_data,/account/);
3862 }else if(label_data_str != label_str && current_label_data_str == label_str){
3863 set_return_basic(popup_reply_data,/\S/);
3864 }else if(label_data_str == label_str){
3865 set_return_basic(popup_reply_data,/account/);
3868 set_return_basic(popup_reply_data,/\S/);
3872 function set_return_and_save(popup_reply_data)
3874 var form_name = popup_reply_data.form_name;
3875 var name_to_value_array = popup_reply_data.name_to_value_array;
3877 for (var the_key in name_to_value_array)
3879 if(the_key == 'toJSON')
3885 window.document.forms[form_name].elements[the_key].value = name_to_value_array[the_key];
3889 window.document.forms[form_name].return_module.value = window.document.forms[form_name].module.value;
3890 window.document.forms[form_name].return_action.value = 'DetailView';
3891 window.document.forms[form_name].return_id.value = window.document.forms[form_name].record.value;
3892 window.document.forms[form_name].action.value = 'Save';
3893 window.document.forms[form_name].submit();
3897 * This is a helper function to construct the initial filter that can be
3898 * passed into the open_popup() function. It assumes that there is an
3899 * account_id and account_name field in the given form_name to use to
3900 * construct the intial filter string.
3902 function get_initial_filter_by_account(form_name)
3904 var account_id = window.document.forms[form_name].account_id.value;
3905 var account_name = escape(window.document.forms[form_name].account_name.value);
3906 var initial_filter = "&account_id=" + account_id + "&account_name=" + account_name;
3908 return initial_filter;
3910 // end code from popup_parent_helper.js
3912 // begin code for address copy
3914 * This is a function used by the Address widget that will fill
3915 * in the given array fields using the fromKey and toKey as a
3916 * prefix into the form objects HTML elements.
3918 * @param form The HTML form object to parse
3919 * @param fromKey The prefix of elements to copy from
3920 * @param toKey The prefix of elements to copy into
3921 * @return boolean true if successful, false otherwise
3923 function copyAddress(form, fromKey, toKey) {
3925 var elems = new Array("address_street", "address_city", "address_state", "address_postalcode", "address_country");
3926 var checkbox = document.getElementById(toKey + "_checkbox");
3928 if(typeof checkbox != "undefined") {
3929 if(!checkbox.checked) {
3931 t = toKey + "_" + elems[x];
3932 document.getElementById(t).removeAttribute('readonly');
3936 f = fromKey + "_" + elems[x];
3937 t = toKey + "_" + elems[x];
3939 document.getElementById(t).value = document.getElementById(f).value;
3940 document.getElementById(t).setAttribute('readonly', true);
3946 // end code for address copy
3949 * This function is used in Email Template Module.
3950 * It will check whether the template is used in Campaing->EmailMarketing.
3951 * If true, it will notify user.
3954 function check_deletable_EmailTemplate() {
3955 id = document.getElementsByName('record')[0].value;
3956 currentForm = document.getElementById('form');
3958 success:function(r) {
3959 if(r.responseText == 'true') {
3960 if(!confirm(SUGAR.language.get('app_strings','NTC_TEMPLATE_IS_USED'))) {
3964 if(!confirm(SUGAR.language.get('app_strings','NTC_DELETE_CONFIRMATION'))) {
3968 currentForm.return_module.value='EmailTemplates';
3969 currentForm.return_action.value='ListView';
3970 currentForm.action.value='Delete';
3971 currentForm.submit();
3974 url = "index.php?module=EmailTemplates&action=CheckDeletable&from=DetailView&to_pdf=1&record="+id;
3975 YAHOO.util.Connect.asyncRequest('POST',url, call_back,null);
3979 remove_upload_imagefile : function(field_name) {
3980 var field=document.getElementById('remove_imagefile_' + field_name);
3983 //enable the file upload button.
3984 var field=document.getElementById( field_name);
3985 field.style.display="";
3987 //hide the image and remove button.
3988 var field=document.getElementById('img_' + field_name);
3989 field.style.display="none";
3990 var field=document.getElementById('bt_remove_' + field_name);
3991 field.style.display="none";
3993 if(document.getElementById(field_name + '_duplicate')) {
3994 var field = document.getElementById(field_name + '_duplicate');
3999 confirm_imagefile : function(field_name) {
4000 var field=document.getElementById(field_name);
4001 var filename=field.value;
4002 var fileExtension = filename.substring(filename.lastIndexOf(".")+1);
4003 fileExtension = fileExtension.toLowerCase();
4004 if (fileExtension == "jpg" || fileExtension == "jpeg"
4005 || fileExtension == "gif" || fileExtension == "png" || fileExtension == "bmp"){
4010 alert(SUGAR.language.get('app_strings', 'LBL_UPLOAD_IMAGE_FILE_INVALID'));
4014 lightbox : function(image)
4016 if (typeof(SUGAR.image.lighboxWindow) == "undefined")
4017 SUGAR.image.lighboxWindow = new YAHOO.widget.SimpleDialog('sugarImageViewer', {
4020 id:'sugarMsgWindow',
4023 msg: "<img src='" + image + "'> </img>",
4026 SUGAR.image.lighboxWindow.setBody("<img src='" + image + "'> </img>");
4027 SUGAR.image.lighboxWindow.render(document.body);
4028 SUGAR.image.lighboxWindow.show();
4029 SUGAR.image.lighboxWindow.center()
4033 SUGAR.util.isTouchScreen = function()
4035 // first check if we have forced use of the touch enhanced interface
4036 if ( Get_Cookie("touchscreen") == '1' ) {
4040 // next check if we should use the touch interface with our device
4041 if ( (navigator.userAgent.match(/iPad/i) != null) ) {
4048 SUGAR.util.isLoginPage = function(content)
4050 //skip if this is packageManager screen
4051 if(SUGAR.util.isPackageManager()) {return false;}
4052 var loginPageStart = "<!DOCTYPE";
4053 if (content.substr(0, loginPageStart.length) == loginPageStart && content.indexOf("<html>") != -1 && content.indexOf("login_module") != -1) {
4054 window.location.href = window.location.protocol + window.location.pathname;
4059 SUGAR.util.isPackageManager=function(){
4060 if(typeof(document.the_form) !='undefined' && typeof(document.the_form.language_pack_escaped) !='undefined'){
4062 }else{return false;}
4065 SUGAR.util.ajaxCallInProgress = function(){
4066 return SUGAR_callsInProgress != 0;
4069 SUGAR.util.callOnChangeListers = function(field){
4070 var listeners = YAHOO.util.Event.getListeners(field, 'change');
4071 if (listeners != null) {
4072 for (var i = 0; i < listeners.length; i++) {
4073 var l = listeners[i];
4074 l.fn.call(l.scope ? l.scope : this, l.obj);
4079 SUGAR.util.closeActivityPanel = {
4080 show:function(module,id,new_status,viewType,parentContainerId){
4081 if (SUGAR.util.closeActivityPanel.panel)
4082 SUGAR.util.closeActivityPanel.panel.destroy();
4083 var singleModule = SUGAR.language.get("app_list_strings", "moduleListSingular")[module];
4084 singleModule = typeof(singleModule != 'undefined') ? singleModule.toLowerCase() : '';
4085 var closeText = SUGAR.language.get("app_strings", "LBL_CLOSE_ACTIVITY_CONFIRM").replace("#module#",singleModule);
4086 SUGAR.util.closeActivityPanel.panel =
4087 new YAHOO.widget.SimpleDialog("closeActivityDialog",
4094 constraintoviewport: true,
4095 buttons: [ { text:SUGAR.language.get("app_strings", "LBL_EMAIL_OK"), handler:function(){
4096 if (SUGAR.util.closeActivityPanel.panel)
4097 SUGAR.util.closeActivityPanel.panel.hide();
4099 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_SAVING'));
4100 var args = "action=save&id=" + id + "&status=" + new_status + "&module=" + module;
4103 { //refresh window to show updated changes
4104 window.location.reload(true);
4106 if(viewType == 'dashlet')
4108 SUGAR.mySugar.retrieveDashlet(o.argument['parentContainerId']);
4109 ajaxStatus.hideStatus();
4111 else if(viewType == 'subpanel'){
4112 showSubPanel(o.argument['parentContainerId'],null,true);
4113 if(o.argument['parentContainerId'] == 'activities'){
4114 showSubPanel('history',null,true);
4116 ajaxStatus.hideStatus();
4118 }else if(viewType == 'listview'){
4119 document.location = 'index.php?module=' + module +'&action=index';
4123 argument:{'parentContainerId':parentContainerId}
4126 YAHOO.util.Connect.asyncRequest('POST', 'index.php', callback, args);
4128 }, isDefault:true },
4129 { text:SUGAR.language.get("app_strings", "LBL_EMAIL_CANCEL"), handler:function(){SUGAR.util.closeActivityPanel.panel.hide(); }} ]
4132 SUGAR.util.closeActivityPanel.panel.setHeader(SUGAR.language.get("app_strings", "LBL_CLOSE_ACTIVITY_HEADER"));
4133 SUGAR.util.closeActivityPanel.panel.render(document.body);
4134 SUGAR.util.closeActivityPanel.panel.show();