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;
275 function removeFromValidate(formname, name) {
276 for(i = 0; i < validate[formname].length; i++){
277 if(validate[formname][i][nameIndex] == name){
278 validate[formname].splice(i, 1);
282 function checkValidate(formname, name) {
283 if(validate[formname]){
284 for(i = 0; i < validate[formname].length; i++){
285 if(validate[formname][i][nameIndex] == name){
292 var formsWithFieldLogic=null;
293 var formWithPrecision =null;
294 function addToValidateFieldLogic(formId,minFieldId, maxFieldId, defaultFieldId, lenFieldId,type,msg){
295 this.formId = document.getElementById(formId);
296 this.min=document.getElementById(minFieldId);
297 this.max= document.getElementById(maxFieldId);
298 this._default= document.getElementById(defaultFieldId);
299 this.len = document.getElementById(lenFieldId);
303 //@params: formid- Dom id of the form containing the precision and float fields
304 // valudId- Dom id of the field containing a float whose precision is to be checked.
305 // precisionId- Dom id of the field containing precision value.
306 function addToValidatePrecision(formId, valueId, precisionId){
307 this.form = document.getElementById(formId);
308 this.float = document.getElementById(valueId);
309 this.precision = document.getElementById(precisionId);
312 //function checkLength(value, referenceValue){
316 function isValidPrecision(value, precision){
317 value = trim(value.toString());
323 if( (precision == "0") ){
324 if (value.indexOf(".")== -1){
331 var actualPrecision = value.substr(value.indexOf(".")+1, value.length).length;
332 return actualPrecision == precision;
334 function toDecimal(original, precision) {
335 precision = (precision == null) ? 2 : precision;
336 num = Math.pow(10, precision);
337 temp = Math.round(original*num)/num;
338 if((temp * 100) % 100 == 0)
340 if((temp * 10) % 10 == 0)
345 function isInteger(s) {
346 if (typeof s == "string" && s == "")
348 if(typeof num_grp_sep != 'undefined' && typeof dec_sep != 'undefined')
350 s = unformatNumberNoParse(s, num_grp_sep, dec_sep).toString();
352 return parseFloat(s) == parseInt(s) && !isNaN(s);
355 function isNumeric(s) {
356 if(!/^-*[0-9\.]+$/.test(s)) {
364 var date_reg_positions = {'Y': 1,'m': 2,'d': 3};
365 var date_reg_format = '([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})'
366 function isDate(dtStr) {
368 if(dtStr.length== 0) {
372 // Check that we have numbers
373 myregexp = new RegExp(date_reg_format)
374 if(!myregexp.test(dtStr))
381 var dateParts = dtStr.match(date_reg_format);
382 for(key in date_reg_positions) {
383 index = date_reg_positions[key];
385 m = dateParts[index];
386 } else if(key == 'd') {
387 d = dateParts[index];
389 y = dateParts[index];
393 // Check that date is real
394 var dd = new Date(y,m,0);
395 // reject negative years
398 // reject month less than 1 and greater than 12
401 // reject days less than 1 or days not in month (e.g. February 30th)
402 if (d < 1 || d > dd.getDate())
407 function getDateObject(dtStr) {
408 if(dtStr.length== 0) {
412 myregexp = new RegExp(date_reg_format)
414 if(myregexp.exec(dtStr)) var dt = myregexp.exec(dtStr)
417 var yr = dt[date_reg_positions['Y']];
418 var mh = dt[date_reg_positions['m']];
419 var dy = dt[date_reg_positions['d']];
420 var dtar = dtStr.split(' ');
421 if(typeof(dtar[1])!='undefined' && isTime(dtar[1])) {//if it is a timedate, we should make date1 to have time value
422 var t1 = dtar[1].replace(/am/i,' AM');
423 var t1 = t1.replace(/pm/i,' PM');
424 date1 = new Date(Date.parse(mh+'/'+dy+ '/'+yr+' '+t1));
428 var date1 = new Date();
429 date1.setFullYear(yr); // xxxx 4 char year
430 date1.setMonth(mh-1); // 0-11 Bug 4048: javascript Date obj months are 0-index
431 date1.setDate(dy); // 1-31
436 function isBefore(value1, value2) {
437 var d1 = getDateObject(value1);
438 var d2 = getDateObject(value2);
439 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.
445 function isValidEmail(emailStr) {
447 if(emailStr.length== 0) {
450 // cn: bug 7128, a period at the end of the string mangles checks. (switched to accept spaces and delimiters)
451 var lastChar = emailStr.charAt(emailStr.length - 1);
452 if(!lastChar.match(/[^\.]/i)) {
455 //bug 40068, According to rules in page 6 of http://www.apps.ietf.org/rfc/rfc3696.html#sec-3,
456 //first character of local part of an email address
457 //should not be a period i.e. '.'
459 var firstLocalChar=emailStr.charAt(0);
460 if(firstLocalChar.match(/\./)){
464 //bug 40068, According to rules in page 6 of http://www.apps.ietf.org/rfc/rfc3696.html#sec-3,
465 //last character of local part of an email address
466 //should not be a period i.e. '.'
468 var pos=emailStr.lastIndexOf("@");
469 var localPart = emailStr.substr(0, pos);
470 var lastLocalChar=localPart.charAt(localPart.length - 1);
471 if(lastLocalChar.match(/\./)){
478 while ((results = reg.exec(emailStr)) != null) {
479 var original = results[0];
480 parsedResult = results[0].replace(';', '::;::');
481 emailStr = emailStr.replace (original, parsedResult);
485 while ((results = reg.exec(emailStr)) != null) {
486 var original = results[0];
487 //Check if we were using ; as a delimiter. If so, skip the commas
488 if(original.indexOf("::;::") == -1) {
489 var parsedResult = results[0].replace(',', '::;::');
490 emailStr = emailStr.replace (original, parsedResult);
494 // mfh: bug 15010 - more practical implementation of RFC 2822 from http://www.regular-expressions.info/email.html, modifed to accept CAPITAL LETTERS
495 //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))
498 //bug 40068, According to rules in page 6 of http://www.apps.ietf.org/rfc/rfc3696.html#sec-3,
499 //allowed special characters ! # $ % & ' * + - / = ? ^ _ ` . { | } ~ in local part
500 var emailArr = emailStr.split(/::;::/);
501 for (var i = 0; i < emailArr.length; i++) {
502 var emailAddress = emailArr[i];
503 if (trim(emailAddress) != '') {
504 if(!/^\s*[\w.%+\-&'#!\$\*=\?\^_`\{\}~\/]+@([A-Z0-9-]+\.)*[A-Z0-9-]+\.[\w-]{2,}\s*$/i.test(emailAddress) &&
505 !/^.*<[A-Z0-9._%+\-&'#!\$\*=\?\^_`\{\}~]+?@([A-Z0-9-]+\.)*[A-Z0-9-]+\.[\w-]{2,}>\s*$/i.test(emailAddress)) {
514 function isValidPhone(phoneStr) {
515 if(phoneStr.length== 0) {
518 if(!/^[0-9\-\(\)\s]+$/.test(phoneStr))
522 function isFloat(floatStr) {
523 if(floatStr.length== 0) {
526 if(!(typeof(num_grp_sep)=='undefined' || typeof(dec_sep)=='undefined')) {
527 floatStr = unformatNumberNoParse(floatStr, num_grp_sep, dec_sep).toString();
530 return /^(-)?[0-9\.]+$/.test(floatStr);
532 function isDBName(str) {
537 // must start with a letter
538 if(!/^[a-zA-Z][a-zA-Z\_0-9]*$/.test(str))
542 var time_reg_format = "[0-9]{1,2}\:[0-9]{2}";
543 function isTime(timeStr) {
544 time_reg_format = time_reg_format.replace('([ap]m)', '');
545 time_reg_format = time_reg_format.replace('([AP]M)', '');
546 if(timeStr.length== 0){
549 //we now support multiple time formats
550 myregexp = new RegExp(time_reg_format)
551 if(!myregexp.test(timeStr))
557 function inRange(value, min, max) {
558 if (typeof num_grp_sep != 'undefined' && typeof dec_sep != 'undefined')
559 value = unformatNumberNoParse(value, num_grp_sep, dec_sep).toString();
560 return value >= min && value <= max;
563 function bothExist(item1, item2) {
564 if(typeof item1 == 'undefined') { return false; }
565 if(typeof item2 == 'undefined') { return false; }
566 if((item1 == '' && item2 != '') || (item1 != '' && item2 == '') ) { return false; }
570 trim = YAHOO.lang.trim;
573 function check_form(formname) {
574 if (typeof(siw) != 'undefined' && siw
575 && typeof(siw.selectingSomething) != 'undefined' && siw.selectingSomething)
577 return validate_form(formname, '');
580 function add_error_style(formname, input, txt, flash) {
581 if (typeof flash == "undefined")
584 inputHandle = typeof input == "object" ? input : document.forms[formname][input];
585 style = get_current_bgcolor(inputHandle);
587 // strip off the colon at the end of the warning strings
588 if ( txt.substring(txt.length-1) == ':' )
589 txt = txt.substring(0,txt.length-1)
591 if(inputHandle.parentNode.innerHTML.search(txt) == -1) {
592 errorTextNode = document.createElement('span');
593 errorTextNode.className = 'required';
594 errorTextNode.innerHTML = '<br />' + txt;
595 if ( inputHandle.parentNode.className.indexOf('x-form-field-wrap') != -1 ) {
596 inputHandle.parentNode.parentNode.appendChild(errorTextNode);
599 inputHandle.parentNode.appendChild(errorTextNode);
602 inputHandle.style.backgroundColor = "#FF0000";
603 inputsWithErrors.push(inputHandle);
607 // We only need to setup the flashy-flashy on the first entry, it loops through all fields automatically
608 if ( inputsWithErrors.length == 1 ) {
609 for(wp = 1; wp <= 10; wp++) {
610 window.setTimeout('fade_error_style(style, '+wp*10+')',1000+(wp*50));
613 if(typeof (window[formname + "_tabs"]) != "undefined") {
614 var tabView = window[formname + "_tabs"];
615 var parentDiv = YAHOO.util.Dom.getAncestorByTagName(inputHandle, "div");
617 var tabs = tabView.get("tabs");
618 for (var i in tabs) {
619 if (tabs[i].get("contentEl") == parentDiv
620 || YAHOO.util.Dom.isAncestor(tabs[i].get("contentEl"), inputHandle))
622 tabs[i].get("labelEl").style.color = "red";
623 if ( inputsWithErrors.length == 1 )
624 tabView.selectTab(i);
629 window.setTimeout("inputsWithErrors[" + (inputsWithErrors.length - 1) + "].style.backgroundColor = null;", 2000);
633 // Catch errors here so we don't allow an incomplete record through the javascript validation
638 * removes all error messages for the current form
640 function clear_all_errors() {
641 for(var wp = 0; wp < inputsWithErrors.length; wp++) {
642 if(typeof(inputsWithErrors[wp]) !='undefined' && typeof inputsWithErrors[wp].parentNode != 'undefined' && inputsWithErrors[wp].parentNode != null) {
643 if ( inputsWithErrors[wp].parentNode.className.indexOf('x-form-field-wrap') != -1 )
645 inputsWithErrors[wp].parentNode.parentNode.removeChild(inputsWithErrors[wp].parentNode.parentNode.lastChild);
649 inputsWithErrors[wp].parentNode.removeChild(inputsWithErrors[wp].parentNode.lastChild);
653 if (inputsWithErrors.length == 0) return;
655 if ( YAHOO.util.Dom.getAncestorByTagName(inputsWithErrors[0], "form") ) {
656 var formname = YAHOO.util.Dom.getAncestorByTagName(inputsWithErrors[0], "form").getAttribute("name");
657 if(typeof (window[formname + "_tabs"]) != "undefined") {
658 var tabView = window[formname + "_tabs"];
660 var tabs = tabView.get("tabs");
661 for (var i in tabs) {
662 tabs[i].get("labelEl").style.color = "";
666 inputsWithErrors = new Array();
670 function get_current_bgcolor(input) {
671 if(input.currentStyle) {// ie
672 style = input.currentStyle.backgroundColor;
673 return style.substring(1,7);
677 styleRGB = document.defaultView.getComputedStyle(input, '').getPropertyValue("background-color");
678 comma = styleRGB.indexOf(',');
679 style += dec2hex(styleRGB.substring(4, comma));
680 commaPrevious = comma;
681 comma = styleRGB.indexOf(',', commaPrevious+1);
682 style += dec2hex(styleRGB.substring(commaPrevious+2, comma));
683 style += dec2hex(styleRGB.substring(comma+2, styleRGB.lastIndexOf(')')));
688 function hex2dec(hex){return(parseInt(hex,16));}
689 var hexDigit=new Array("0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F");
690 function dec2hex(dec){return(hexDigit[dec>>4]+hexDigit[dec&15]);}
692 function fade_error_style(normalStyle, percent) {
693 errorStyle = 'c60c30';
694 var r1 = hex2dec(errorStyle.slice(0,2));
695 var g1 = hex2dec(errorStyle.slice(2,4));
696 var b1 = hex2dec(errorStyle.slice(4,6));
698 var r2 = hex2dec(normalStyle.slice(0,2));
699 var g2 = hex2dec(normalStyle.slice(2,4));
700 var b2 = hex2dec(normalStyle.slice(4,6));
703 var pc = percent / 100;
705 r= Math.floor(r1+(pc*(r2-r1)) + .5);
706 g= Math.floor(g1+(pc*(g2-g1)) + .5);
707 b= Math.floor(b1+(pc*(b2-b1)) + .5);
709 for(var wp = 0; wp < inputsWithErrors.length; wp++) {
710 inputsWithErrors[wp].style.backgroundColor = "#" + dec2hex(r) + dec2hex(g) + dec2hex(b);
715 function validate_form(formname, startsWith){
716 requiredTxt = SUGAR.language.get('app_strings', 'ERR_MISSING_REQUIRED_FIELDS');
717 invalidTxt = SUGAR.language.get('app_strings', 'ERR_INVALID_VALUE');
719 if ( typeof (formname) == 'undefined')
723 if ( typeof (validate[formname]) == 'undefined')
725 disableOnUnloadEditView(document.forms[formname]);
729 var form = document.forms[formname];
732 var _date = new Date();
733 if(_date.getTime() < (lastSubmitTime + 2000) && startsWith == oldStartsWith) { // ignore submits for the next 2 seconds
736 lastSubmitTime = _date.getTime();
737 oldStartsWith = startsWith;
739 clear_all_errors(); // remove previous error messages
741 inputsWithErrors = new Array();
742 for(var i = 0; i < validate[formname].length; i++){
743 if(validate[formname][i][nameIndex].indexOf(startsWith) == 0){
744 if(typeof form[validate[formname][i][nameIndex]] != 'undefined'){
747 //If a field is not required and it is blank or is binarydependant, skip validation.
748 //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
749 if(!validate[formname][i][requiredIndex] && trim(form[validate[formname][i][nameIndex]].value) == '' && (typeof(validate[formname][i][jstypeIndex]) != 'undefined' && validate[formname][i][jstypeIndex] != 'binarydep'))
754 if(validate[formname][i][requiredIndex] && validate[formname][i][typeIndex] != 'bool'){
755 if(typeof form[validate[formname][i][nameIndex]] == 'undefined' || trim(form[validate[formname][i][nameIndex]].value) == ""){
756 add_error_style(formname, validate[formname][i][nameIndex], requiredTxt +' ' + validate[formname][i][msgIndex]);
761 switch(validate[formname][i][typeIndex]){
763 if(!isValidEmail(trim(form[validate[formname][i][nameIndex]].value))){
765 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
769 if( !isTime(trim(form[validate[formname][i][nameIndex]].value))){
771 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
773 case 'date': if(!isDate(trim(form[validate[formname][i][nameIndex]].value))){
775 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
780 if(!isDBName(trim(form[validate[formname][i][nameIndex]].value))){
782 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
788 if(!isInteger(trim(form[validate[formname][i][nameIndex]].value))){
790 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
795 if(!isFloat(trim(form[validate[formname][i][nameIndex]].value))){
797 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
801 div_element_id = formname + '_' + form[validate[formname][i][nameIndex]].name + '_operation_div';
802 input_elements = YAHOO.util.Selector.query('input', document.getElementById(div_element_id));
803 primary_field_id = '';
804 validation_passed = false;
805 replace_selected = false;
807 //Loop through the option elements (replace or add currently)
808 for(t in input_elements) {
809 if(input_elements[t].type && input_elements[t].type == 'radio' && input_elements[t].checked == true && input_elements[t].value == 'replace') {
811 //Now find where the primary radio button is and if a value has been set
812 radio_elements = YAHOO.util.Selector.query('input[type=radio]', document.getElementById(formname + '_team_name_table'));
814 for(x in radio_elements) {
815 if(radio_elements[x].name != 'team_name_type') {
816 primary_field_id = 'team_name_collection_' + radio_elements[x].value;
817 if(radio_elements[x].checked) {
818 replace_selected = true;
819 if(trim(document.forms[formname].elements[primary_field_id].value) != '') {
820 validation_passed = true;
823 } else if(trim(document.forms[formname].elements[primary_field_id].value) != '') {
824 replace_selected = true;
831 if(replace_selected && !validation_passed) {
832 add_error_style(formname, primary_field_id, SUGAR.language.get('app_strings', 'ERR_NO_PRIMARY_TEAM_SPECIFIED'));
837 table_element_id = formname + '_' + form[validate[formname][i][nameIndex]].name + '_table';
838 if(document.getElementById(table_element_id)) {
839 input_elements = YAHOO.util.Selector.query('input[type=radio]', document.getElementById(table_element_id));
841 primary_field_id = form[validate[formname][i][nameIndex]].name + '_collection_0';
843 for(t in input_elements) {
844 primary_field_id = form[validate[formname][i][nameIndex]].name + '_collection_' + input_elements[t].value;
845 if(input_elements[t].type && input_elements[t].type == 'radio' && input_elements[t].checked == true) {
846 if(document.forms[formname].elements[primary_field_id].value != '') {
855 field_id = form[validate[formname][i][nameIndex]].name + '_collection_' + input_elements[0].value;
856 add_error_style(formname, field_id, SUGAR.language.get('app_strings', 'ERR_NO_PRIMARY_TEAM_SPECIFIED'));
862 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex]);
866 if(typeof validate[formname][i][jstypeIndex] != 'undefined'/* && !isError*/){
868 switch(validate[formname][i][jstypeIndex]){
870 if(!inRange(trim(form[validate[formname][i][nameIndex]].value), validate[formname][i][minIndex], validate[formname][i][maxIndex])){
872 var lbl_validate_range = SUGAR.language.get('app_strings', 'LBL_VALIDATE_RANGE');
873 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] + ") ");
877 compareTo = form[validate[formname][i][compareToIndex]];
878 if( typeof compareTo != 'undefined'){
879 if(trim(compareTo.value) != '' || (validate[formname][i][allowblank] != 'true') ) {
880 date2 = trim(compareTo.value);
881 date1 = trim(form[validate[formname][i][nameIndex]].value);
883 if(trim(date1).length != 0 && !isBefore(date1,date2)){
885 //jc:#12287 - adding translation for the is not before message
886 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex] + "(" + date1 + ") " + SUGAR.language.get('app_strings', 'MSG_IS_NOT_BEFORE') + ' ' +date2);
892 value=unformatNumber(trim(form[validate[formname][i][nameIndex]].value), num_grp_sep, dec_sep);
893 maximum = parseFloat(validate[formname][i][maxIndex]);
894 if( typeof maximum != 'undefined'){
897 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]);
902 value=unformatNumber(trim(form[validate[formname][i][nameIndex]].value), num_grp_sep, dec_sep);
903 minimum = parseFloat(validate[formname][i][minIndex]);
904 if( typeof minimum != 'undefined'){
907 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'));
912 compareTo = form[validate[formname][i][compareToIndex]];
913 if( typeof compareTo != 'undefined') {
914 item1 = trim(form[validate[formname][i][nameIndex]].value);
915 item2 = trim(compareTo.value);
916 if(!bothExist(item1, item2)) {
918 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex]);
923 compareTo = form[validate[formname][i][compareToIndex]];
924 if( typeof compareTo != 'undefined') {
925 item1 = trim(form[validate[formname][i][nameIndex]].value);
926 item2 = trim(compareTo.value);
927 if(!bothExist(item1, item2) || item1 != item2) {
929 add_error_style(formname, validate[formname][i][nameIndex], validate[formname][i][msgIndex]);
934 arr = eval(validate[formname][i][arrIndex]);
935 operator = validate[formname][i][operatorIndex];
936 item1 = trim(form[validate[formname][i][nameIndex]].value);
937 if (operator.charAt(0) == 'u') {
938 item1 = item1.toUpperCase();
939 operator = operator.substring(1);
940 } else if (operator.charAt(0) == 'l') {
941 item1 = item1.toLowerCase();
942 operator = operator.substring(1);
944 for(j = 0; j < arr.length; j++){
946 if((operator == "==" && val == item1) || (operator == "!=" && val != item1)){
948 add_error_style(formname, validate[formname][i][nameIndex], invalidTxt + " " + validate[formname][i][msgIndex]);
953 if(trim(form[validate[formname][i][nameIndex]].value) == 'false'){
954 //Fake an error so form does not submit
965 Check min max default field logic.
966 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.*/
967 if(formsWithFieldLogic){
968 var invalidLogic=false;
969 if(formsWithFieldLogic.min && formsWithFieldLogic.max && formsWithFieldLogic._default) {
970 var showErrorsOn={min:{value:'min', show:false, obj:formsWithFieldLogic.min.value},
971 max:{value:'max',show:false, obj:formsWithFieldLogic.max.value},
972 _default:{value:'default',show:false, obj:formsWithFieldLogic._default.value},
973 len:{value:'len', show:false, obj:parseInt(formsWithFieldLogic.len.value,10)}};
975 var min = (formsWithFieldLogic.min.value !='') ? parseFloat(formsWithFieldLogic.min.value) : 'undef';
976 var max = (formsWithFieldLogic.max.value !='') ? parseFloat(formsWithFieldLogic.max.value) : 'undef';
977 var _default = (formsWithFieldLogic._default.value!='')? parseFloat(formsWithFieldLogic._default.value) : 'undef';
979 /*Check all lengths are <= max size.*/
980 for(var i in showErrorsOn){
981 if(showErrorsOn[i].value!='len' && showErrorsOn[i].obj.length > showErrorsOn.len.obj){
983 showErrorsOn[i].show=true;
984 showErrorsOn.len.show=true;
988 if(min!='undef' && max!='undef' && _default!='undef'){
989 if(!inRange(_default,min,max)){
991 showErrorsOn.min.show=true;
992 showErrorsOn.max.show=true;
993 showErrorsOn._default.show=true;
996 if(min!='undef' && max!= 'undef' && min > max){
998 showErrorsOn.min.show=true;
999 showErrorsOn.max.show=true;
1001 if(min!='undef' && _default!='undef' && _default < min){
1003 invalidLogic = true;
1004 showErrorsOn.min.show=true;
1005 showErrorsOn._default.show=true;
1007 if(max!='undef' && _default !='undef' && _default>max){
1009 invalidLogic = true;
1010 showErrorsOn.max.show=true;
1011 showErrorsOn._default.show=true;
1016 for(var error in showErrorsOn)
1017 if(showErrorsOn[error].show)
1018 add_error_style(formname,showErrorsOn[error].value, formsWithFieldLogic.msg);
1023 formsWithFieldLogic = null;
1026 if(formWithPrecision){
1027 if (!isValidPrecision(formWithPrecision.float.value, formWithPrecision.precision.value)){
1029 add_error_style(formname, 'default', SUGAR.language.get('app_strings', 'ERR_COMPATIBLE_PRECISION_VALUE'));
1037 if (isError == true) {
1039 if (self.pageYOffset) // all except Explorer
1041 nwX = self.pageXOffset;
1042 seX = self.innerWidth;
1043 nwY = self.pageYOffset;
1044 seY = self.innerHeight;
1046 else if (document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
1048 nwX = document.documentElement.scrollLeft;
1049 seX = document.documentElement.clientWidth;
1050 nwY = document.documentElement.scrollTop;
1051 seY = document.documentElement.clientHeight;
1053 else if (document.body) // all other Explorers
1055 nwX = document.body.scrollLeft;
1056 seX = document.body.clientWidth;
1057 nwY = document.body.scrollTop;
1058 seY = document.body.clientHeight;
1061 var inView = true; // is there an error within viewport of browser
1062 for(var wp = 0; wp < inputsWithErrors.length; wp++) {
1063 var elementCoor = findElementPos(inputsWithErrors[wp]);
1064 if(!(elementCoor.x >= nwX && elementCoor.y >= nwY &&
1065 elementCoor.x <= seX && elementCoor.y <= seY)) { // if input is not within viewport
1067 scrollToTop = elementCoor.y - 75;
1068 scrollToLeft = elementCoor.x - 75;
1070 else { // on first input within viewport, don't scroll
1076 if(!inView) window.scrollTo(scrollToLeft,scrollToTop);
1081 disableOnUnloadEditView(form);
1088 * This array is used to remember mark status of rows in browse mode
1090 var marked_row = new Array;
1094 * Sets/unsets the pointer and marker in browse mode
1096 * @param object the table row
1097 * @param interger the row number
1098 * @param string the action calling this script (over, out or click)
1099 * @param string the default background color
1100 * @param string the color to use for mouseover
1101 * @param string the color to use for marking a row
1103 * @return boolean whether pointer is set or not
1105 function setPointer(theRow, theRowNum, theAction, theDefaultColor, thePointerColor, theMarkColor) {
1106 var theCells = null;
1108 // 1. Pointer and mark feature are disabled or the browser can't get the
1110 if ((thePointerColor == '' && theMarkColor == '')
1111 || typeof(theRow.style) == 'undefined') {
1115 // 2. Gets the current row and exits if the browser can't get it
1116 if (typeof(document.getElementsByTagName) != 'undefined') {
1117 theCells = theRow.getElementsByTagName('td');
1119 else if (typeof(theRow.cells) != 'undefined') {
1120 theCells = theRow.cells;
1126 // 3. Gets the current color...
1127 var rowCellsCnt = theCells.length;
1128 var domDetect = null;
1129 var currentColor = null;
1130 var newColor = null;
1131 // 3.1 ... with DOM compatible browsers except Opera that does not return
1132 // valid values with "getAttribute"
1133 if (typeof(window.opera) == 'undefined'
1134 && typeof(theCells[0].getAttribute) != 'undefined') {
1135 currentColor = theCells[0].getAttribute('bgcolor');
1138 // 3.2 ... with other browsers
1140 currentColor = theCells[0].style.backgroundColor;
1144 // 4. Defines the new color
1145 // 4.1 Current color is the default one
1146 if (currentColor == ''
1147 || (currentColor!= null && (currentColor.toLowerCase() == theDefaultColor.toLowerCase()))) {
1148 if (theAction == 'over' && thePointerColor != '') {
1149 newColor = thePointerColor;
1151 else if (theAction == 'click' && theMarkColor != '') {
1152 newColor = theMarkColor;
1153 marked_row[theRowNum] = true;
1156 // 4.1.2 Current color is the pointer one
1157 else if (currentColor!= null && (currentColor.toLowerCase() == thePointerColor.toLowerCase())
1158 && (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])) {
1159 if (theAction == 'out') {
1160 newColor = theDefaultColor;
1162 else if (theAction == 'click' && theMarkColor != '') {
1163 newColor = theMarkColor;
1164 marked_row[theRowNum] = true;
1167 // 4.1.3 Current color is the marker one
1168 else if (currentColor!= null && (currentColor.toLowerCase() == theMarkColor.toLowerCase())) {
1169 if (theAction == 'click') {
1170 newColor = (thePointerColor != '')
1173 marked_row[theRowNum] = (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])
1179 // 5. Sets the new color...
1182 // 5.1 ... with DOM compatible browsers except Opera
1184 for (c = 0; c < rowCellsCnt; c++) {
1185 theCells[c].setAttribute('bgcolor', newColor, 0);
1188 // 5.2 ... with other browsers
1190 for (c = 0; c < rowCellsCnt; c++) {
1191 theCells[c].style.backgroundColor = newColor;
1197 } // end of the 'setPointer()' function
1201 * listbox redirection
1203 function goToUrl(selObj, goToLocation) {
1204 eval("document.location.href = '" + goToLocation + "pos=" + selObj.options[selObj.selectedIndex].value + "'");
1209 var json_objects = new Object();
1211 function getXMLHTTPinstance() {
1212 var xmlhttp = false;
1213 var userAgent = navigator.userAgent.toLowerCase() ;
1215 // IE Check supports ActiveX controls
1216 if (userAgent.indexOf("msie") != -1 && userAgent.indexOf("mac") == -1 && userAgent.indexOf("opera") == -1) {
1217 var version = navigator.appVersion.match(/MSIE (.\..)/)[1] ;
1218 if(version >= 5.5 ) {
1220 xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
1224 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
1233 if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
1234 xmlhttp = new XMLHttpRequest();
1239 // NOW LOAD THE OBJECT..
1240 var global_xmlhttp = getXMLHTTPinstance();
1242 function http_fetch_sync(url,post_data) {
1243 global_xmlhttp = getXMLHTTPinstance();
1246 if(typeof(post_data) != 'undefined') method = 'POST';
1248 global_xmlhttp.open(method, url,false);
1251 alert('message:'+e.message+":url:"+url);
1253 if(method == 'POST') {
1254 global_xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
1257 global_xmlhttp.send(post_data);
1259 if (SUGAR.util.isLoginPage(global_xmlhttp.responseText))
1262 var args = {"responseText" : global_xmlhttp.responseText,
1263 "responseXML" : global_xmlhttp.responseXML,
1264 "request_id" : request_id};
1268 // this is a GET unless post_data is defined
1270 function http_fetch_async(url,callback,request_id,post_data) {
1272 if(typeof(post_data) != 'undefined') {
1277 global_xmlhttp.open(method, url,true);
1280 alert('message:'+e.message+":url:"+url);
1282 if(method == 'POST') {
1283 global_xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
1285 global_xmlhttp.onreadystatechange = function() {
1286 if(global_xmlhttp.readyState==4) {
1287 if(global_xmlhttp.status == 200) {
1288 if (SUGAR.util.isLoginPage(global_xmlhttp.responseText))
1290 var args = {"responseText" : global_xmlhttp.responseText,
1291 "responseXML" : global_xmlhttp.responseXML,
1292 "request_id" : request_id };
1293 callback.call(document,args);
1296 alert("There was a problem retrieving the XML data:\n" + global_xmlhttp.statusText);
1300 global_xmlhttp.send(post_data);
1303 function call_json_method(module,action,vars,variable_name,callback) {
1304 global_xmlhttp.open("GET", "index.php?entryPoint=json&module="+module+"&action="+action+"&"+vars,true);
1305 global_xmlhttp.onreadystatechange=
1307 if(global_xmlhttp.readyState==4) {
1308 if(global_xmlhttp.status == 200) {
1309 // cn: bug 12274 - pass through JSON.parse() to remove security envelope
1310 json_objects[variable_name] = JSON.parse(global_xmlhttp.responseText);
1312 // cn: bug 12274 - safe from CSRF, render response as expected
1313 var respText = JSON.parseNoSecurity(global_xmlhttp.responseText);
1314 var args = {responseText:respText, responseXML:global_xmlhttp.responseXML};
1315 callback.call(document, args);
1318 alert("There was a problem retrieving the XML data:\n" + global_xmlhttp.statusText);
1322 global_xmlhttp.send(null);
1325 function insert_at_cursor(field, value) {
1327 if (document.selection) {
1329 sel = document.selection.createRange();
1333 else if(field.selectionStart || field.selectionStart == '0') {
1334 var start_pos = field.selectionStart;
1335 var end_pos = field.selectionEnd;
1336 field.value = field.value.substring(0, start_pos) + value + field.value.substring(end_pos, field.value.length);
1339 field.value += value;
1343 function checkParentType(type,button) {
1344 if(button == null) {
1347 if(typeof disabledModules != 'undefined' && typeof(disabledModules[type]) != 'undefined') {
1348 button.disabled='disabled';
1351 button.disabled = false;
1355 function parseDate(input, format) {
1357 format = format.replace(/%/g, '');
1358 sep = format.charAt(1);
1359 yAt = format.indexOf('Y')
1360 // 1-1-06 or 1-12-06 or 1-1-2006 or 1-12-2006
1361 if(date.match(/^\d{1,2}[\/-]\d{1,2}[\/-]\d{2,4}$/) && yAt == 4) {
1362 if(date.match(/^\d{1}[\/-].*$/)) date = '0' + date;
1363 if(date.match(/^\d{2}[\/-]\d{1}[\/-].*$/)) date = date.substring(0,3) + '0' + date.substring(3,date.length);
1364 if(date.match(/^\d{2}[\/-]\d{2}[\/-]\d{2}$/)) date = date.substring(0,6) + '20' + date.substring(6,date.length);
1366 // 06-11-1 or 06-1-1
1367 else if(date.match(/^\d{2,4}[\/-]\d{1,2}[\/-]\d{1,2}$/)) {
1368 if(date.match(/^\d{2}[\/-].*$/)) date = '20' + date;
1369 if(date.match(/^\d{4}[\/-]\d{1}[\/-].*$/)) date = date.substring(0,5) + '0' + date.substring(5,date.length);
1370 if(date.match(/^\d{4}[\/-]\d{2}[\/-]\d{1}$/)) date = date.substring(0,8) + '0' + date.substring(8,date.length);
1372 else if(date.match(/^\d{4,8}$/)) { // digits only
1374 if(date.match(/^\d{8}$/)) digits = 8;// match for 8 digits
1375 else if(date.match(/\d{6}/)) digits = 6;// match for 5 digits
1376 else if(date.match(/\d{4}/)) digits = 4;// match for 5 digits
1377 else if(date.match(/\d{5}/)) digits = 5;// match for 5 digits
1382 case 4: date = '20' + date.substring(0,2) + sep + '0' + date.substring(2, 3) + sep + '0' + date.substring(3,4); break;
1383 case 5: date = '20' + date.substring(0,2) + sep + date.substring(2, 4) + sep + '0' + date.substring(4,5); break;
1384 case 6: date = '20' + date.substring(0,2) + sep + date.substring(2, 4) + sep + date.substring(4,6); break;
1385 case 8: date = date.substring(0,4) + sep + date.substring(4, 6) + sep + date.substring(6,8); break;
1390 case 4: date = '0' + date.substring(0,1) + sep + '20' + date.substring(1, 3) + sep + '0' + date.substring(3,4); break;
1391 case 5: date = date.substring(0,2) + sep + '20' + date.substring(2, 4) + sep + '0' + date.substring(4,5); break;
1392 case 6: date = date.substring(0,2) + sep + '20' + date.substring(2, 4) + sep + date.substring(4,6); break;
1393 case 8: date = date.substring(0,2) + sep + date.substring(2, 6) + sep + date.substring(6,8); break;
1397 case 4: date = '0' + date.substring(0,1) + sep + '0' + date.substring(1, 2) + sep + '20' + date.substring(2,4); break;
1398 case 5: date = '0' + date.substring(0,1) + sep + date.substring(1, 3) + sep + '20' + date.substring(3,5); break;
1399 case 6: date = date.substring(0,2) + sep + date.substring(2, 4) + sep + '20' + date.substring(4,6); break;
1400 case 8: date = date.substring(0,2) + sep + date.substring(2, 4) + sep + date.substring(4,8); break;
1405 date = date.replace(/[\/-]/g, sep);
1409 // find obj's position
1410 function findElementPos(obj) {
1413 if (obj.offsetParent) {
1414 while (obj.offsetParent) {
1415 x += obj.offsetLeft;
1417 obj = obj.offsetParent;
1419 }//if offsetParent exists
1420 else if (obj.x && obj.y) {
1424 return new coordinate(x, y);
1428 // get dimensions of the browser window
1429 function getClientDim() {
1430 var nwX, nwY, seX, seY;
1431 if (self.pageYOffset) // all except Explorer
1433 nwX = self.pageXOffset;
1434 seX = self.innerWidth + nwX;
1435 nwY = self.pageYOffset;
1436 seY = self.innerHeight + nwY;
1438 else if (document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
1440 nwX = document.documentElement.scrollLeft;
1441 seX = document.documentElement.clientWidth + nwX;
1442 nwY = document.documentElement.scrollTop;
1443 seY = document.documentElement.clientHeight + nwY;
1445 else if (document.body) // all other Explorers
1447 nwX = document.body.scrollLeft;
1448 seX = document.body.clientWidth + nwX;
1449 nwY = document.body.scrollTop;
1450 seY = document.body.clientHeight + nwY;
1452 return {'nw' : new coordinate(nwX, nwY), 'se' : new coordinate(seX, seY)};
1456 * stop propagation on events
1458 function freezeEvent(e) {
1460 if (e.preventDefault) e.preventDefault();
1461 e.returnValue = false;
1462 e.cancelBubble = true;
1463 if (e.stopPropagation) e.stopPropagation();
1472 function coordinate(_x, _y) {
1481 return new position(this.x + rh.x, this.y + rh.y);
1485 return new position(this.x + rh.x, this.y + rh.y);
1489 // sends theForm via AJAX and fills in the theDiv
1490 function sendAndRetrieve(theForm, theDiv, loadingStr) {
1491 function success(data) {
1492 document.getElementById(theDiv).innerHTML = data.responseText;
1493 ajaxStatus.hideStatus();
1495 if(typeof loadingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
1496 ajaxStatus.showStatus(loadingStr);
1497 YAHOO.util.Connect.setForm(theForm);
1498 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
1502 //save the form and redirect
1503 function sendAndRedirect(theForm, loadingStr, redirect_location) {
1504 function success(data) {
1505 if(redirect_location){
1506 location.href=redirect_location;
1508 ajaxStatus.hideStatus();
1510 if(typeof loadingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
1511 ajaxStatus.showStatus(loadingStr);
1512 YAHOO.util.Connect.setForm(theForm);
1513 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
1517 function saveForm(theForm, theDiv, loadingStr) {
1518 if(check_form(theForm)){
1519 for(i = 0; i < ajaxFormArray.length; i++){
1520 if(ajaxFormArray[i] == theForm){
1521 ajaxFormArray.splice(i, 1);
1524 return sendAndRetrieve(theForm, loadingStr, theDiv);
1530 // Builds a "snapshot" of the form, so we can use it to see if someone has changed it.
1531 function snapshotForm(theForm) {
1532 var snapshotTxt = '';
1533 var elemList = theForm.elements;
1537 for( var i = 0; i < elemList.length ; i++ ) {
1539 if ( typeof(elem.type) == 'undefined' ) {
1543 elemType = elem.type.toLowerCase();
1545 snapshotTxt = snapshotTxt + elem.name;
1547 if ( elemType == 'text' || elemType == 'textarea' || elemType == 'password' ) {
1548 snapshotTxt = snapshotTxt + elem.value;
1550 else if ( elemType == 'select' || elemType == 'select-one' || elemType == 'select-multiple' ) {
1551 var optionList = elem.options;
1552 for ( var ii = 0 ; ii < optionList.length ; ii++ ) {
1553 if ( optionList[ii].selected ) {
1554 snapshotTxt = snapshotTxt + optionList[ii].value;
1558 else if ( elemType == 'radio' || elemType == 'checkbox' ) {
1559 if ( elem.selected ) {
1560 snapshotTxt = snapshotTxt + 'checked';
1563 else if ( elemType == 'hidden' ) {
1564 snapshotTxt = snapshotTxt + elem.value;
1571 function initEditView(theForm) {
1572 if (SUGAR.util.ajaxCallInProgress()) {
1573 window.setTimeout(function(){initEditView(theForm);}, 100);
1576 // we don't need to check if the data is changed in the search popup
1577 if (theForm.id == 'popup_query_form') {
1580 if ( typeof editViewSnapshots == 'undefined' ) {
1581 editViewSnapshots = new Object();
1583 if ( typeof SUGAR.loadedForms == 'undefined' ) {
1584 SUGAR.loadedForms = new Object();
1587 // console.log('DEBUG: Adding checks for '+theForm.id);
1588 editViewSnapshots[theForm.id] = snapshotForm(theForm);
1589 SUGAR.loadedForms[theForm.id] = true;
1593 function onUnloadEditView(theForm) {
1595 var dataHasChanged = false;
1597 if ( typeof editViewSnapshots == 'undefined' ) {
1598 // No snapshots, move along
1602 if ( typeof theForm == 'undefined' ) {
1603 // Need to check all editViewSnapshots
1604 for ( var idx in editViewSnapshots ) {
1606 theForm = document.getElementById(idx);
1607 // console.log('DEBUG: Checking all forms '+theForm.id);
1608 if ( theForm == null
1609 || typeof editViewSnapshots[theForm.id] == 'undefined'
1610 || editViewSnapshots[theForm.id] == null
1611 || !SUGAR.loadedForms[theForm.id]) {
1615 var snap = snapshotForm(theForm);
1616 if ( editViewSnapshots[theForm.id] != snap ) {
1617 dataHasChanged = true;
1621 // Just need to check a single form for changes
1622 if ( editViewSnapshots == null || typeof editViewSnapshots[theForm.id] == 'undefined' || editViewSnapshots[theForm.id] == null ) {
1626 // console.log('DEBUG: Checking one form '+theForm.id);
1627 if ( editViewSnapshots[theForm.id] != snapshotForm(theForm) ) {
1628 // Data has changed.
1629 dataHasChanged = true;
1633 if ( dataHasChanged == true ) {
1634 return SUGAR.language.get('app_strings','WARN_UNSAVED_CHANGES');
1641 function disableOnUnloadEditView(theForm) {
1642 // If you don't pass anything in, it disables all checking
1643 if ( typeof theForm == 'undefined' || typeof editViewSnapshots == 'undefined' || editViewSnapshots == null ) {
1644 window.onbeforeunload = null;
1645 editViewSnapshots = null;
1647 // console.log('DEBUG: Disabling all edit view checks');
1650 // Otherwise, it just disables it for this form
1651 if ( typeof(theForm.id) != 'undefined' && typeof(editViewSnapshots[theForm.id]) != 'undefined' ) {
1652 editViewSnapshots[theForm.id] = null;
1655 // console.log('DEBUG : Disabling just checks for '+theForm.id);
1661 * save some forms using an ajax call
1662 * theForms - the ids of all of theh forms to save
1663 * savingStr - the string to display when saving the form
1664 * completeStr - the string to display when the form has been saved
1666 function saveForms( savingStr, completeStr) {
1668 theForms = ajaxFormArray;
1669 function success(data) {
1670 var theForm = document.getElementById(ajaxFormArray[0]);
1671 document.getElementById('multiedit_'+theForm.id).innerHTML = data.responseText;
1672 var saveAllButton = document.getElementById('ajaxsaveall');
1673 ajaxFormArray.splice(index, 1);
1674 if(saveAllButton && ajaxFormArray.length <= 1){
1675 saveAllButton.style.visibility = 'hidden';
1678 if(index == theForms.length){
1679 ajaxStatus.showStatus(completeStr);
1680 window.setTimeout('ajaxStatus.hideStatus();', 2000);
1682 saveAllButton.style.visibility = 'hidden';
1687 if(typeof savingStr == 'undefined') SUGAR.language.get('app_strings', 'LBL_LOADING');
1688 ajaxStatus.showStatus(savingStr);
1690 //loop through the forms saving each one
1691 for(i = 0; i < theForms.length; i++){
1692 var theForm = document.getElementById(theForms[i]);
1693 if(check_form(theForm.id)){
1694 theForm.action.value='AjaxFormSave';
1695 YAHOO.util.Connect.setForm(theForm);
1696 var cObj = YAHOO.util.Connect.asyncRequest('POST', 'index.php', {success: success, failure: success});
1698 ajaxStatus.hideStatus();
1700 lastSubmitTime = lastSubmitTime-2000;
1705 // -- start sugarListView class
1706 // js functions used for ListView
1707 function sugarListView() {
1711 sugarListView.prototype.confirm_action = function(del) {
1713 return confirm( SUGAR.language.get('app_strings', 'NTC_DELETE_CONFIRMATION_NUM') + sugarListView.get_num_selected() + SUGAR.language.get('app_strings', 'NTC_DELETE_SELECTED_RECORDS'));
1716 return confirm( SUGAR.language.get('app_strings', 'NTC_UPDATE_CONFIRMATION_NUM') + sugarListView.get_num_selected() + SUGAR.language.get('app_strings', 'NTC_DELETE_SELECTED_RECORDS'));
1720 sugarListView.get_num_selected = function () {
1721 if(typeof document.MassUpdate != 'undefined') {
1722 the_form = document.MassUpdate;
1723 for(wp = 0; wp < the_form.elements.length; wp++) {
1724 if(typeof the_form.elements[wp].name != 'undefined' && the_form.elements[wp].name == 'selectCount[]') {
1725 return the_form.elements[wp].value;
1732 sugarListView.update_count = function(count, add) {
1733 if(typeof document.MassUpdate != 'undefined') {
1734 the_form = document.MassUpdate;
1735 for(wp = 0; wp < the_form.elements.length; wp++) {
1736 if(typeof the_form.elements[wp].name != 'undefined' && the_form.elements[wp].name == 'selectCount[]') {
1738 the_form.elements[wp].value = parseInt(the_form.elements[wp].value,10) + count;
1739 if (the_form.select_entire_list.value == 1 && the_form.show_plus.value) {
1740 the_form.elements[wp].value += '+';
1743 if (the_form.select_entire_list.value == 1 && the_form.show_plus.value) {
1744 the_form.elements[wp].value = count + '+';
1746 the_form.elements[wp].value = count;
1753 sugarListView.prototype.use_external_mail_client = function(no_record_txt, module) {
1754 selected_records = sugarListView.get_checks_count();
1755 if(selected_records <1) {
1756 alert(no_record_txt);
1760 if (document.MassUpdate.select_entire_list.value == 1) {
1761 if (totalCount > 10) {
1762 alert(totalCountError);
1767 else if (document.MassUpdate.massall.checked == true)
1771 sugarListView.get_checks();
1773 if(select) { // use selected items
1774 ids = document.MassUpdate.uid.value;
1776 else { // use current page
1777 inputs = document.MassUpdate.elements;
1779 for(i = 0; i < inputs.length; i++) {
1780 if(inputs[i].name == 'mass[]' && inputs[i].checked && typeof(inputs[i].value) != 'function') {
1781 ar.push(inputs[i].value);
1786 YAHOO.util.Connect.asyncRequest("POST", "index.php?", {
1787 success: this.use_external_mail_client_callback
1788 }, SUGAR.util.paramsToUrl({
1791 listViewExternalClient: 1,
1792 action_module: module,
1800 sugarListView.prototype.use_external_mail_client_callback = function(o)
1803 location.href = 'mailto:' + o.responseText;
1806 sugarListView.prototype.send_form_for_emails = function(select, currentModule, action, no_record_txt,action_module,totalCount, totalCountError) {
1807 if (document.MassUpdate.select_entire_list.value == 1) {
1808 if (totalCount > 10) {
1809 alert(totalCountError);
1814 else if (document.MassUpdate.massall.checked == true)
1819 sugarListView.get_checks();
1820 // create new form to post (can't access action property of MassUpdate form due to action input)
1821 var newForm = document.createElement('form');
1822 newForm.method = 'post';
1823 newForm.action = action;
1824 newForm.name = 'newForm';
1825 newForm.id = 'newForm';
1826 var uidTa = document.createElement('textarea');
1828 uidTa.style.display = 'none';
1830 if(select) { // use selected items
1831 uidTa.value = document.MassUpdate.uid.value;
1833 else { // use current page
1834 inputs = document.MassUpdate.elements;
1836 for(i = 0; i < inputs.length; i++) {
1837 if(inputs[i].name == 'mass[]' && inputs[i].checked && typeof(inputs[i].value) != 'function') {
1838 ar.push(inputs[i].value);
1841 uidTa.value = ar.join(',');
1844 if(uidTa.value == '') {
1845 alert(no_record_txt);
1849 var selectedArray = uidTa.value.split(",");
1850 if(selectedArray.length > 10) {
1851 alert(totalCountError);
1854 newForm.appendChild(uidTa);
1856 var moduleInput = document.createElement('input');
1857 moduleInput.name = 'module';
1858 moduleInput.type = 'hidden';
1859 moduleInput.value = currentModule;
1860 newForm.appendChild(moduleInput);
1862 var actionInput = document.createElement('input');
1863 actionInput.name = 'action';
1864 actionInput.type = 'hidden';
1865 actionInput.value = 'Compose';
1866 newForm.appendChild(actionInput);
1868 if (typeof action_module != 'undefined' && action_module!= '') {
1869 var actionModule = document.createElement('input');
1870 actionModule.name = 'action_module';
1871 actionModule.type = 'hidden';
1872 actionModule.value = action_module;
1873 newForm.appendChild(actionModule);
1875 //return_info must follow this pattern."&return_module=Accounts&return_action=index"
1876 if (typeof return_info!= 'undefined' && return_info != '') {
1877 var params= return_info.split('&');
1878 if (params.length > 0) {
1879 for (var i=0;i< params.length;i++) {
1880 if (params[i].length > 0) {
1881 var param_nv=params[i].split('=');
1882 if (param_nv.length==2){
1883 returnModule = document.createElement('input');
1884 returnModule.name = param_nv[0];
1885 returnModule.type = 'hidden';
1886 returnModule.value = param_nv[1];
1887 newForm.appendChild(returnModule);
1894 var isAjaxCall = document.createElement('input');
1895 isAjaxCall.name = 'ajaxCall';
1896 isAjaxCall.type = 'hidden';
1897 isAjaxCall.value = true;
1898 newForm.appendChild(isAjaxCall);
1900 var isListView = document.createElement('input');
1901 isListView.name = 'ListView';
1902 isListView.type = 'hidden';
1903 isListView.value = true;
1904 newForm.appendChild(isListView);
1906 var toPdf = document.createElement('input');
1907 toPdf.name = 'to_pdf';
1908 toPdf.type = 'hidden';
1910 newForm.appendChild(toPdf);
1912 //Grab the Quick Compose package for the listview
1913 YAHOO.util.Connect.setForm(newForm);
1916 success: function(o) {
1917 var resp = YAHOO.lang.JSON.parse(o.responseText);
1918 var quickComposePackage = new Object();
1919 quickComposePackage.composePackage = resp;
1920 quickComposePackage.fullComposeUrl = 'index.php?module=Emails&action=Compose&ListView=true' +
1921 '&uid=' + uidTa.value + '&action_module=' + action_module;
1923 SUGAR.quickCompose.init(quickComposePackage);
1927 YAHOO.util.Connect.asyncRequest('POST','index.php', callback,null);
1929 // awu Bug 18624: Fixing issue where a canceled Export and unselect of row will persist the uid field, clear the field
1930 document.MassUpdate.uid.value = '';
1935 sugarListView.prototype.send_form = function(select, currentModule, action, no_record_txt,action_module,return_info) {
1936 if (document.MassUpdate.select_entire_list.value == 1) {
1938 if(sugarListView.get_checks_count() < 1) {
1939 alert(no_record_txt);
1944 if ( action.indexOf('?') != -1 )
1945 href += '&module=' + currentModule;
1947 href += '?module=' + currentModule;
1950 href += return_info;
1951 var newForm = document.createElement('form');
1952 newForm.method = 'post';
1953 newForm.action = href;
1954 newForm.name = 'newForm';
1955 newForm.id = 'newForm';
1956 var postTa = document.createElement('textarea');
1957 postTa.name = 'current_post';
1958 postTa.value = document.MassUpdate.current_query_by_page.value;
1959 postTa.style.display = 'none';
1960 newForm.appendChild(postTa);
1961 document.MassUpdate.parentNode.appendChild(newForm);
1965 else if (document.MassUpdate.massall.checked == true)
1970 sugarListView.get_checks();
1971 // create new form to post (can't access action property of MassUpdate form due to action input)
1972 var newForm = document.createElement('form');
1973 newForm.method = 'post';
1974 newForm.action = action;
1975 newForm.name = 'newForm';
1976 newForm.id = 'newForm';
1977 var uidTa = document.createElement('textarea');
1979 uidTa.style.display = 'none';
1980 uidTa.value = document.MassUpdate.uid.value;
1982 if(uidTa.value == '') {
1983 alert(no_record_txt);
1987 newForm.appendChild(uidTa);
1989 var moduleInput = document.createElement('input');
1990 moduleInput.name = 'module';
1991 moduleInput.type = 'hidden';
1992 moduleInput.value = currentModule;
1993 newForm.appendChild(moduleInput);
1995 var actionInput = document.createElement('input');
1996 actionInput.name = 'action';
1997 actionInput.type = 'hidden';
1998 actionInput.value = 'index';
1999 newForm.appendChild(actionInput);
2001 if (typeof action_module != 'undefined' && action_module!= '') {
2002 var actionModule = document.createElement('input');
2003 actionModule.name = 'action_module';
2004 actionModule.type = 'hidden';
2005 actionModule.value = action_module;
2006 newForm.appendChild(actionModule);
2008 //return_info must follow this pattern."&return_module=Accounts&return_action=index"
2009 if (typeof return_info!= 'undefined' && return_info != '') {
2010 var params= return_info.split('&');
2011 if (params.length > 0) {
2012 for (var i=0;i< params.length;i++) {
2013 if (params[i].length > 0) {
2014 var param_nv=params[i].split('=');
2015 if (param_nv.length==2){
2016 returnModule = document.createElement('input');
2017 returnModule.name = param_nv[0];
2018 returnModule.type = 'hidden';
2019 returnModule.value = param_nv[1];
2020 newForm.appendChild(returnModule);
2027 document.MassUpdate.parentNode.appendChild(newForm);
2030 // awu Bug 18624: Fixing issue where a canceled Export and unselect of row will persist the uid field, clear the field
2031 document.MassUpdate.uid.value = '';
2035 //return a count of checked row.
2036 sugarListView.get_checks_count = function() {
2039 if(document.MassUpdate.uid.value != '') {
2040 oldUids = document.MassUpdate.uid.value.split(',');
2041 for(uid in oldUids) {
2042 if(typeof(oldUids[uid]) != 'function') {
2043 ar[oldUids[uid]] = 1;
2047 // build associated array of uids, associated array ensures uniqueness
2048 inputs = document.MassUpdate.elements;
2049 for(i = 0; i < inputs.length; i++) {
2050 if(inputs[i].name == 'mass[]') {
2051 ar[inputs[i].value] = (inputs[i].checked) ? 1 : 0; // 0 of it is unchecked
2055 // build regular array of uids
2058 if((typeof(ar[i]) != 'function') && ar[i] == 1) {
2066 // saves the checks on the current page into the uid textarea
2067 sugarListView.get_checks = function() {
2070 if(document.MassUpdate.uid.value != '') {
2071 oldUids = document.MassUpdate.uid.value.split(',');
2072 for(uid in oldUids) {
2073 if(typeof(oldUids[uid]) != 'function') {
2074 ar[oldUids[uid]] = 1;
2079 // build associated array of uids, associated array ensures uniqueness
2080 inputs = document.MassUpdate.elements;
2081 for(i = 0; i < inputs.length; i++) {
2082 if(inputs[i].name == 'mass[]') {
2083 ar[inputs[i].value] = (inputs[i].checked) ? 1 : 0; // 0 of it is unchecked
2087 // build regular array of uids
2090 if(typeof(ar[i]) != 'function' && ar[i] == 1) {
2095 document.MassUpdate.uid.value = uids.join(',');
2097 if(uids.length == 0) return false; // return false if no checks to get
2098 return true; // there are saved checks
2101 sugarListView.prototype.order_checks = function(order,orderBy,moduleString){
2102 checks = sugarListView.get_checks();
2103 eval('document.MassUpdate.' + moduleString + '.value = orderBy');
2104 document.MassUpdate.lvso.value = order;
2105 if(typeof document.MassUpdate.massupdate != 'undefined') {
2106 document.MassUpdate.massupdate.value = 'false';
2109 //we must first clear the action of massupdate, change it to index
2110 document.MassUpdate.action.value = document.MassUpdate.return_action.value;
2111 document.MassUpdate.return_module.value='';
2112 document.MassUpdate.return_action.value='';
2113 document.MassUpdate.submit();
2117 sugarListView.prototype.save_checks = function(offset, moduleString) {
2118 checks = sugarListView.get_checks();
2119 eval('document.MassUpdate.' + moduleString + '.value = offset');
2121 if(typeof document.MassUpdate.massupdate != 'undefined') {
2122 document.MassUpdate.massupdate.value = 'false';
2125 //we must first clear the action of massupdate, change it to index
2126 document.MassUpdate.action.value = document.MassUpdate.return_action.value;
2127 document.MassUpdate.return_module.value='';
2128 document.MassUpdate.return_action.value='';
2129 document.MassUpdate.submit();
2135 sugarListView.prototype.check_item = function(cb, form) {
2137 sugarListView.update_count(1, true);
2139 sugarListView.update_count(-1, true);
2140 if(typeof form != 'undefined' && form != null) {
2141 sugarListView.prototype.updateUid(cb, form);
2146 /**#28000, remove the unselect record id from MassUpdate.uid **/
2147 sugarListView.prototype.updateUid = function(cb , form){
2148 if(form.name == 'MassUpdate' && form.uid && form.uid.value && cb.value && form.uid.value.indexOf(cb.value) != -1){
2149 if(form.uid.value.indexOf(','+cb.value)!= -1){
2150 form.uid.value = form.uid.value.replace(','+cb.value , '');
2151 }else if(form.uid.value.indexOf(cb.value + ',')!= -1){
2152 form.uid.value = form.uid.value.replace(cb.value + ',' , '');
2153 }else if(form.uid.value.indexOf(cb.value)!= -1){
2154 form.uid.value = form.uid.value.replace(cb.value , '');
2159 sugarListView.prototype.check_entire_list = function(form, field, value, list_count) {
2160 // count number of items
2162 document.MassUpdate.massall.checked = true;
2163 document.MassUpdate.massall.disabled = true;
2165 for (i = 0; i < form.elements.length; i++) {
2166 if(form.elements[i].name == field && form.elements[i].disabled == false) {
2167 if(form.elements[i].checked != value) count++;
2168 form.elements[i].checked = value;
2169 form.elements[i].disabled = true;
2172 document.MassUpdate.select_entire_list.value = 1;
2174 sugarListView.update_count(list_count, false);
2175 //else sugarListView.update_count(-1 * count, true);
2178 sugarListView.prototype.check_all = function(form, field, value, pageTotal) {
2179 // count number of items
2181 document.MassUpdate.massall.checked = value;
2182 if (document.MassUpdate.select_entire_list &&
2183 document.MassUpdate.select_entire_list.value == 1)
2184 document.MassUpdate.massall.disabled = true;
2186 document.MassUpdate.massall.disabled = false;
2188 for (i = 0; i < form.elements.length; i++) {
2189 if(form.elements[i].name == field && !(form.elements[i].disabled == true && form.elements[i].checked == false)) {
2190 form.elements[i].disabled = false;
2192 if(form.elements[i].checked != value)
2194 form.elements[i].checked = value;
2196 sugarListView.prototype.updateUid(form.elements[i], form);
2201 sugarListView.update_count(pageTotal);
2203 sugarListView.update_count(count, true);
2205 sugarListView.update_count(-1 * count, true);
2207 sugarListView.check_all = sugarListView.prototype.check_all;
2208 sugarListView.confirm_action = sugarListView.prototype.confirm_action;
2210 sugarListView.prototype.check_boxes = function() {
2211 var inputsCount = 0;
2212 var checkedCount = 0;
2213 var existing_onload = window.onload;
2214 var theForm = document.MassUpdate;
2215 inputs_array = theForm.elements;
2217 if(typeof theForm.uid.value != 'undefined' && theForm.uid.value != "") {
2218 checked_items = theForm.uid.value.split(",");
2219 if (theForm.select_entire_list.value == 1)
2220 document.MassUpdate.massall.disabled = true;
2222 for(wp = 0 ; wp < inputs_array.length; wp++) {
2223 if(inputs_array[wp].name == "mass[]") {
2225 if (theForm.select_entire_list.value == 1) {
2226 inputs_array[wp].checked = true;
2227 inputs_array[wp].disabled = true;
2231 for(i in checked_items) {
2232 if(inputs_array[wp].value == checked_items[i]) {
2234 inputs_array[wp].checked = true;
2240 if (theForm.select_entire_list.value == 0)
2241 sugarListView.update_count(checked_items.length);
2243 sugarListView.update_count(0, true);
2247 for(wp = 0 ; wp < inputs_array.length; wp++) {
2248 if(inputs_array[wp].name == "mass[]") {
2249 inputs_array[wp].checked = false;
2250 inputs_array[wp].disabled = false;
2253 if (document.MassUpdate.massall) {
2254 document.MassUpdate.massall.checked = false;
2255 document.MassUpdate.massall.disabled = false;
2257 sugarListView.update_count(0)
2259 if(checkedCount > 0 && checkedCount == inputsCount)
2260 document.MassUpdate.massall.checked = true;
2266 * This function is used in Email Template Module's listview.
2267 * It will check whether the templates are used in Campaing->EmailMarketing.
2268 * If true, it will notify user.
2270 function check_used_email_templates() {
2271 var ids = document.MassUpdate.uid.value;
2273 success:function(r) {
2274 if(r.responseText != '') {
2275 if(!confirm(SUGAR.language.get('app_strings','NTC_TEMPLATES_IS_USED') + r.responseText)) {
2279 document.MassUpdate.submit();
2283 url = "index.php?module=EmailTemplates&action=CheckDeletable&from=ListView&to_pdf=1&records="+ids;
2284 YAHOO.util.Connect.asyncRequest('POST',url, call_back,null);
2288 sugarListView.prototype.send_mass_update = function(mode, no_record_txt, del) {
2289 formValid = check_form('MassUpdate');
2290 if(!formValid && !del) return false;
2293 if (document.MassUpdate.select_entire_list &&
2294 document.MassUpdate.select_entire_list.value == 1)
2299 var ar = new Array();
2303 for(wp = 0; wp < document.MassUpdate.elements.length; wp++) {
2304 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)+'$');
2305 //when the uid is already in document.MassUpdate.uid.value, we should not add it to ar.
2306 if(typeof document.MassUpdate.elements[wp].name != 'undefined'
2307 && document.MassUpdate.elements[wp].name == 'mass[]'
2308 && document.MassUpdate.elements[wp].checked
2309 && !reg_for_existing_uid.test(document.MassUpdate.uid.value)) {
2310 ar.push(document.MassUpdate.elements[wp].value);
2313 if(document.MassUpdate.uid.value != '') document.MassUpdate.uid.value += ',';
2314 document.MassUpdate.uid.value += ar.join(',');
2315 if(document.MassUpdate.uid.value == '') {
2316 alert(no_record_txt);
2319 if(typeof(current_admin_id)!='undefined' && document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'Users' && (document.MassUpdate.is_admin.value!='' || document.MassUpdate.status.value!='')) {
2320 var reg_for_current_admin_id = new RegExp('^'+current_admin_id+'[\s]*,|,[\s]*'+current_admin_id+'[\s]*,|,[\s]*'+current_admin_id+'$|^'+current_admin_id+'$');
2321 if(reg_for_current_admin_id.test(document.MassUpdate.uid.value)) {
2322 //if current user is admin, we should not allow massupdate the user_type and status of himself
2323 alert(SUGAR.language.get('Users','LBL_LAST_ADMIN_NOTICE'));
2329 var entireInput = document.createElement('input');
2330 entireInput.name = 'entire';
2331 entireInput.type = 'hidden';
2332 entireInput.value = 'index';
2333 document.MassUpdate.appendChild(entireInput);
2334 //confirm(no_record_txt);
2335 if(document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'Users' && (document.MassUpdate.is_admin.value!='' || document.MassUpdate.status.value!='')) {
2336 alert(SUGAR.language.get('Users','LBL_LAST_ADMIN_NOTICE'));
2342 if(!sugarListView.confirm_action(del))
2346 var deleteInput = document.createElement('input');
2347 deleteInput.name = 'Delete';
2348 deleteInput.type = 'hidden';
2349 deleteInput.value = true;
2350 document.MassUpdate.appendChild(deleteInput);
2351 if(document.MassUpdate.module!= 'undefined' && document.MassUpdate.module.value == 'EmailTemplates') {
2352 check_used_email_templates();
2358 document.MassUpdate.submit();
2363 sugarListView.prototype.clear_all = function() {
2364 document.MassUpdate.uid.value = '';
2365 document.MassUpdate.select_entire_list.value = 0;
2366 sugarListView.check_all(document.MassUpdate, 'mass[]', false);
2367 document.MassUpdate.massall.checked = false;
2368 document.MassUpdate.massall.disabled = false;
2369 sugarListView.update_count(0);
2372 sListView = new sugarListView();
2373 // -- end sugarListView class
2375 // format and unformat numbers
2376 function unformatNumber(n, num_grp_sep, dec_sep) {
2377 var x=unformatNumberNoParse(n, num_grp_sep, dec_sep);
2380 return parseFloat(x);
2385 function unformatNumberNoParse(n, num_grp_sep, dec_sep) {
2386 if(typeof num_grp_sep == 'undefined' || typeof dec_sep == 'undefined') return n;
2387 n = n ? n.toString() : '';
2389 num_grp_sep_re = new RegExp('\\'+num_grp_sep, 'g');
2390 n = n.replace(num_grp_sep_re, '').replace(dec_sep, '.');
2392 if(typeof CurrencySymbols != 'undefined') {
2393 // Need to strip out the currency symbols from the start.
2394 for ( var idx in CurrencySymbols ) {
2395 n = n.replace(CurrencySymbols[idx], '');
2403 // round parameter can be negative for decimal, precision has to be postive
2404 function formatNumber(n, num_grp_sep, dec_sep, round, precision) {
2405 if(typeof num_grp_sep == 'undefined' || typeof dec_sep == 'undefined') return n;
2406 n = n ? n.toString() : '';
2407 if(n.split) n = n.split('.');
2410 if(n.length > 2) return n.join('.'); // that's not a num!
2412 if(typeof round != 'undefined') {
2413 if(round > 0 && n.length > 1) { // round to decimal
2414 n[1] = parseFloat('0.' + n[1]);
2415 n[1] = Math.round(n[1] * Math.pow(10, round)) / Math.pow(10, round);
2416 n[1] = n[1].toString().split('.')[1];
2418 if(round <= 0) { // round to whole number
2419 n[0] = Math.round(parseInt(n[0],10) * Math.pow(10, round)) / Math.pow(10, round);
2424 if(typeof precision != 'undefined' && precision >= 0) {
2425 if(n.length > 1 && typeof n[1] != 'undefined') n[1] = n[1].substring(0, precision); // cut off precision
2427 if(n[1].length < precision) {
2428 for(var wp = n[1].length; wp < precision; wp++) n[1] += '0';
2432 regex = /(\d+)(\d{3})/;
2433 while(num_grp_sep != '' && regex.test(n[0])) n[0] = n[0].replace(regex, '$1' + num_grp_sep + '$2');
2434 return n[0] + (n.length > 1 && n[1] != '' ? dec_sep + n[1] : '');
2437 // --- begin ajax status class
2438 SUGAR.ajaxStatusClass = function() {};
2439 SUGAR.ajaxStatusClass.prototype.statusDiv = null;
2440 SUGAR.ajaxStatusClass.prototype.oldOnScroll = null;
2441 SUGAR.ajaxStatusClass.prototype.shown = false; // state of the status window
2443 // reposition the status div, top and centered
2444 SUGAR.ajaxStatusClass.prototype.positionStatus = function() {
2445 this.statusDiv.style.top = document.body.scrollTop + 8 + 'px';
2446 statusDivRegion = YAHOO.util.Dom.getRegion(this.statusDiv);
2447 statusDivWidth = statusDivRegion.right - statusDivRegion.left;
2448 this.statusDiv.style.left = YAHOO.util.Dom.getViewportWidth() / 2 - statusDivWidth / 2 + 'px';
2451 // private func, create the status div
2452 SUGAR.ajaxStatusClass.prototype.createStatus = function(text) {
2453 statusDiv = document.createElement('div');
2454 statusDiv.className = 'dataLabel';
2455 statusDiv.style.background = '#ffffff';
2456 statusDiv.style.color = '#c60c30';
2457 statusDiv.style.position = 'absolute';
2458 statusDiv.style.opacity = .8;
2459 statusDiv.style.filter = 'alpha(opacity=80)';
2460 statusDiv.id = 'ajaxStatusDiv';
2461 document.body.appendChild(statusDiv);
2462 this.statusDiv = document.getElementById('ajaxStatusDiv');
2465 // public - show the status div with text
2466 SUGAR.ajaxStatusClass.prototype.showStatus = function(text) {
2467 if(!this.statusDiv) {
2468 this.createStatus(text);
2471 this.statusDiv.style.display = '';
2473 this.statusDiv.style.zIndex = 20;
2474 this.statusDiv.innerHTML = ' <b>' + text + '</b> ';
2475 this.positionStatus();
2478 this.statusDiv.style.display = '';
2479 if(window.onscroll) this.oldOnScroll = window.onscroll; // save onScroll
2480 window.onscroll = this.positionStatus;
2485 SUGAR.ajaxStatusClass.prototype.hideStatus = function(text) {
2486 if(!this.shown) return;
2488 if(this.oldOnScroll) window.onscroll = this.oldOnScroll;
2489 else window.onscroll = '';
2490 this.statusDiv.style.display = 'none';
2493 SUGAR.ajaxStatusClass.prototype.flashStatus = function(text, time){
2494 this.showStatus(text);
2495 window.setTimeout('ajaxStatus.hideStatus();', time);
2499 var ajaxStatus = new SUGAR.ajaxStatusClass();
2500 // --- end ajax status class
2503 * Unified Search Advanced - for global search
2505 SUGAR.unifiedSearchAdvanced = function() {
2515 SUGAR.unifiedSearchAdvanced.usa_div = document.getElementById('unified_search_advanced_div');
2516 SUGAR.unifiedSearchAdvanced.usa_img = document.getElementById('unified_search_advanced_img');
2518 if(!SUGAR.unifiedSearchAdvanced.usa_div || !SUGAR.unifiedSearchAdvanced.usa_img) return;
2519 var attributes = { height: { to: 300 } };
2520 SUGAR.unifiedSearchAdvanced.anim_open = new YAHOO.util.Anim('unified_search_advanced_div', attributes );
2521 SUGAR.unifiedSearchAdvanced.anim_open.duration = 0.75;
2522 SUGAR.unifiedSearchAdvanced.anim_close = new YAHOO.util.Anim('unified_search_advanced_div', { height: {to: 0} } );
2523 SUGAR.unifiedSearchAdvanced.anim_close.duration = 0.75;
2524 //SUGAR.unifiedSearchAdvanced.anim_close.onComplete.subscribe(function() {SUGAR.unifiedSearchAdvanced.usa_div.style.display = 'none'});
2526 SUGAR.unifiedSearchAdvanced.usa_img._x = YAHOO.util.Dom.getX(SUGAR.unifiedSearchAdvanced.usa_img);
2527 SUGAR.unifiedSearchAdvanced.usa_img._y = YAHOO.util.Dom.getY(SUGAR.unifiedSearchAdvanced.usa_img);
2530 SUGAR.unifiedSearchAdvanced.usa_open = false;
2531 SUGAR.unifiedSearchAdvanced.usa_content = null;
2533 YAHOO.util.Event.addListener('unified_search_advanced_img', 'click', SUGAR.unifiedSearchAdvanced.get_content);
2536 get_content: function(e) {
2537 if(SUGAR.unifiedSearchAdvanced.usa_content == null) {
2538 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_LOADING'));
2539 var cObj = YAHOO.util.Connect.asyncRequest('GET','index.php?to_pdf=1&module=Home&action=UnifiedSearch&usa_form=true',
2540 {success: SUGAR.unifiedSearchAdvanced.animate, failure: SUGAR.unifiedSearchAdvanced.animate}, null);
2542 else SUGAR.unifiedSearchAdvanced.animate();
2545 animate: function(data) {
2546 ajaxStatus.hideStatus();
2549 SUGAR.unifiedSearchAdvanced.usa_content = data.responseText;
2550 SUGAR.unifiedSearchAdvanced.usa_div.innerHTML = SUGAR.unifiedSearchAdvanced.usa_content;
2552 if(SUGAR.unifiedSearchAdvanced.usa_open) {
2553 document.UnifiedSearch.advanced.value = 'false';
2554 SUGAR.unifiedSearchAdvanced.anim_close.animate();
2557 document.UnifiedSearch.advanced.value = 'true';
2558 SUGAR.unifiedSearchAdvanced.usa_div.style.display = '';
2559 YAHOO.util.Dom.setX(SUGAR.unifiedSearchAdvanced.usa_div, SUGAR.unifiedSearchAdvanced.usa_img._x - 90);
2560 YAHOO.util.Dom.setY(SUGAR.unifiedSearchAdvanced.usa_div, SUGAR.unifiedSearchAdvanced.usa_img._y + 15);
2561 SUGAR.unifiedSearchAdvanced.anim_open.animate();
2563 SUGAR.unifiedSearchAdvanced.usa_open = !SUGAR.unifiedSearchAdvanced.usa_open;
2568 checkUsaAdvanced: function() {
2569 if(document.UnifiedSearch.advanced.value == 'true') {
2570 document.UnifiedSearchAdvanced.query_string.value = document.UnifiedSearch.query_string.value;
2571 document.UnifiedSearchAdvanced.submit();
2578 if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.unifiedSearchAdvanced.init);
2583 * Toggles the header
2585 toggleHeader : function() {
2586 var h = document.getElementById('header');
2590 if(h.style.display == 'none') {
2591 h.style.display = '';
2593 h.style.display = 'none';
2597 alert(SUGAR.language.get("app_strings", "ERR_NO_HEADER_ID"));
2604 * General Sugar Utils
2606 SUGAR.util = function () {
2607 var additionalDetailsCache;
2608 var additionalDetailsCalls;
2609 var additionalDetailsRpcCall;
2612 getAndRemove : function (el) {
2613 if (YAHOO && YAHOO.util && YAHOO.util.Dom)
2614 el = YAHOO.util.Dom.get(el);
2615 else if (typeof (el) == "string")
2616 el = document.getElementById(el);
2617 if (el && el.parentNode)
2618 el.parentNode.removeChild(el);
2622 paramsToUrl : function (params) {
2625 url += i + "=" + params[i] + "&";
2629 evalScript:function(text){
2631 var waitUntilLoaded = function(){
2632 SUGAR.evalScript_waitCount--;
2633 if (SUGAR.evalScript_waitCount == 0) {
2634 var headElem = document.getElementsByTagName('head')[0];
2635 for ( var i = 0; i < SUGAR.evalScript_evalElem.length; i++) {
2636 var tmpElem = document.createElement('script');
2637 tmpElem.type = 'text/javascript';
2638 tmpElem.text = SUGAR.evalScript_evalElem[i];
2639 headElem.appendChild(tmpElem);
2644 var tmpElem = document.createElement('div');
2645 tmpElem.innerHTML = text;
2646 var results = tmpElem.getElementsByTagName('script');
2647 if (results == null) {
2648 // No scripts found, bail out
2652 var headElem = document.getElementsByTagName('head')[0];
2654 SUGAR.evalScript_waitCount = 0;
2655 SUGAR.evalScript_evalElem = new Array();
2656 for (var i = 0; i < results.length; i++) {
2657 if (typeof(results[i]) != 'object') {
2660 tmpElem = document.createElement('script');
2661 tmpElem.type = 'text/javascript';
2662 if (results[i].src != null && results[i].src != '') {
2663 tmpElem.src = results[i].src;
2665 // Need to defer execution of these scripts until the
2666 // required javascript files are fully loaded
2667 SUGAR.evalScript_evalElem[SUGAR.evalScript_evalElem.length] = results[i].text;
2670 tmpElem.addEventListener('load', waitUntilLoaded);
2671 SUGAR.evalScript_waitCount++;
2672 headElem.appendChild(tmpElem);
2674 // Add some code to handle pages without any external scripts
2675 SUGAR.evalScript_waitCount++;
2678 // Don't try and process things the IE way
2682 var objRegex = /<\s*script([^>]*)>((.|\s|\v|\0)*?)<\s*\/script\s*>/igm;
2684 var result = objRegex.exec(text);
2685 while(result && result.index > lastIndex){
2686 lastIndex = result.index
2688 var script = document.createElement('script');
2689 script.type= 'text/javascript';
2690 if(result[1].indexOf("src=") > -1){
2691 var srcRegex = /.*src=['"]([a-zA-Z0-9\&\/\.\?=:]*)['"].*/igm;
2692 var srcResult = result[1].replace(srcRegex, '$1');
2693 script.src = srcResult;
2695 script.text = result[2];
2697 document.body.appendChild(script)
2702 result = objRegex.exec(text);
2706 * Gets the sidebar object
2707 * @return object pointer to the sidebar element
2709 getLeftColObj: function() {
2710 leftColObj = document.getElementById('leftCol');
2711 while(leftColObj.nodeName != 'TABLE') {
2712 leftColObj = leftColObj.firstChild;
2714 leftColTable = leftColObj;
2715 leftColTd = leftColTable.getElementsByTagName('td')[0];
2716 leftColTdRegion = YAHOO.util.Dom.getRegion(leftColTd);
2717 leftColTd.style.width = (leftColTdRegion.right - leftColTdRegion.left) + 'px';
2722 * Fills the shortcut menu placeholders w/ actual content
2723 * Call this on load event
2725 * @param shortcutContent Array array of content to fill in
2727 fillShortcuts: function(e, shortcutContent) {
2730 // don't do this if leftCol isn't available
2731 if (document.getElementById('leftCol') == undefined) { return; }
2733 spans = document.getElementById('leftCol').getElementsByTagName('span');
2734 hideCol = document.getElementById('HideMenu').getElementsByTagName('span');
2735 w = spans.length + 1;
2737 spans[w] = hideCol[i];
2740 for(je in shortcutContent) {
2742 if(typeof spans[wp].innerHTML != 'undefined' && spans[wp].innerHTML == ('wp_shortcut_fill_' + je)) {
2743 if(typeof spans[wp].parentNode.parentNode == 'object') {
2744 if(typeof spans[wp].parentNode.parentNode.onclick != 'undefined') {
2745 spans[wp].parentNode.parentNode.onclick = null;
2747 // If the wp_shortcut span is contained by an A tag, replace the A with a DIV.
2748 if(spans[wp].parentNode.tagName == 'A' && !isIE) {
2749 var newDiv = document.createElement('DIV');
2750 var parentAnchor = spans[wp].parentNode;
2752 spans[wp].parentNode.parentNode.style.display = 'none';
2754 // Copy styles over to the new container div
2755 if(window.getComputedStyle) {
2756 var parentStyle = window.getComputedStyle(parentAnchor, '');
2757 for(var styleName in parentStyle) {
2758 if(typeof parentStyle[styleName] != 'function'
2759 && styleName != 'display'
2760 && styleName != 'borderWidth'
2761 && styleName != 'visibility') {
2763 newDiv.style[styleName] = parentStyle[styleName];
2765 // Catches .length and .parentRule, and others
2771 // Replace the A with the DIV
2772 newDiv.appendChild(spans[wp]);
2773 parentAnchor.parentNode.replaceChild(newDiv, parentAnchor);
2775 spans[wp].parentNode.parentNode.style.display = '';
2778 spans[wp].innerHTML = shortcutContent[je]; // fill w/ content
2779 if(spans[wp].style) spans[wp].style.display = '';
2785 * Make an AJAX request.
2787 * @param url string resource to load
2788 * @param theDiv string id of element to insert loaded data into
2789 * @param postForm string if set, a POST request will be made to resource specified by url using the form named by postForm
2790 * @param callback string name of function to invoke after HTTP response is recieved
2791 * @param callbackParam any parameter to pass to callback when invoked
2792 * @param appendMode bool if true, HTTP response will be appended to the contents of theDiv, or else contents will be overriten.
2794 retrieveAndFill: function(url, theDiv, postForm, callback, callbackParam, appendMode) {
2795 if(typeof theDiv == 'string') {
2797 theDiv = document.getElementById(theDiv);
2804 var success = function(data) {
2805 if (typeof theDiv != 'undefined' && theDiv != null)
2808 if (typeof appendMode != 'undefined' && appendMode)
2810 theDiv.innerHTML += data.responseText;
2814 theDiv.innerHTML = data.responseText;
2821 if (typeof callback != 'undefined' && callback != null) callback(callbackParam);
2824 if(typeof postForm == 'undefined' || postForm == null) {
2825 var cObj = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
2828 YAHOO.util.Connect.setForm(postForm);
2829 var cObj = YAHOO.util.Connect.asyncRequest('POST', url, {success: success, failure: success});
2832 checkMaxLength: function() { // modified from http://www.quirksmode.org/dom/maxlength.html
2833 var maxLength = this.getAttribute('maxlength');
2834 var currentLength = this.value.length;
2835 if (currentLength > maxLength) {
2836 this.value = this.value.substring(0, maxLength);
2841 * Adds maxlength attribute to textareas
2843 setMaxLength: function() { // modified from http://www.quirksmode.org/dom/maxlength.html
2844 var x = document.getElementsByTagName('textarea');
2845 for (var i=0;i<x.length;i++) {
2846 if (x[i].getAttribute('maxlength')) {
2847 x[i].onkeyup = x[i].onchange = SUGAR.util.checkMaxLength;
2854 * Retrieves additional details dynamically
2856 getAdditionalDetails: function(bean, id, spanId) {
2858 oReturn = function(body, caption, width, theme) {
2859 var _refx = 25-width;
2860 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);
2863 success = function(data) {
2864 eval(data.responseText);
2866 SUGAR.util.additionalDetailsCache[spanId] = new Array();
2867 SUGAR.util.additionalDetailsCache[spanId]['body'] = result['body'];
2868 SUGAR.util.additionalDetailsCache[spanId]['caption'] = result['caption'];
2869 SUGAR.util.additionalDetailsCache[spanId]['width'] = result['width'];
2870 SUGAR.util.additionalDetailsCache[spanId]['theme'] = result['theme'];
2871 ajaxStatus.hideStatus();
2872 return oReturn(SUGAR.util.additionalDetailsCache[spanId]['body'], SUGAR.util.additionalDetailsCache[spanId]['caption'], SUGAR.util.additionalDetailsCache[spanId]['width'], SUGAR.util.additionalDetailsCache[spanId]['theme']);
2875 if(typeof SUGAR.util.additionalDetailsCache[spanId] != 'undefined')
2876 return oReturn(SUGAR.util.additionalDetailsCache[spanId]['body'], SUGAR.util.additionalDetailsCache[spanId]['caption'], SUGAR.util.additionalDetailsCache[spanId]['width'], SUGAR.util.additionalDetailsCache[spanId]['theme']);
2878 if(typeof SUGAR.util.additionalDetailsCalls[spanId] != 'undefined') // call already in progress
2880 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_LOADING'));
2881 url = 'index.php?to_pdf=1&module=Home&action=AdditionalDetailsRetrieve&bean=' + bean + '&id=' + id;
2882 SUGAR.util.additionalDetailsCalls[spanId] = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
2886 SUGAR.util.additionalDetailsRpcCall = window.setTimeout('go()', 250);
2888 clearAdditionalDetailsCall: function() {
2889 if(typeof SUGAR.util.additionalDetailsRpcCall == 'number') window.clearTimeout(SUGAR.util.additionalDetailsRpcCall);
2892 * A function that extends functionality from parent to child.
2894 extend : function(subc, superc, overrides) {
2895 subc.prototype = new superc; // set the superclass
2898 for (var i in overrides) subc.prototype[i] = overrides[i];
2901 hrefURL : function(url) {
2903 // IE needs special treatment since otherwise it would not pass Referer
2904 var trampoline = document.createElement('a');
2905 trampoline.href = url;
2906 document.body.appendChild(trampoline);
2908 document.body.removeChild(trampoline);
2910 document.location.href = url;
2914 openWindow : function(URL, windowName, windowFeatures) {
2916 // IE needs special treatment since otherwise it would not pass Referer
2917 win = window.open('', windowName, windowFeatures);
2918 var trampoline = document.createElement('a');
2919 trampoline.href = URL;
2920 trampoline.target = windowName;
2921 document.body.appendChild(trampoline);
2923 document.body.removeChild(trampoline);
2925 win = window.open(URL, windowName, windowFeatures);
2931 SUGAR.util.additionalDetailsCache = new Array();
2932 SUGAR.util.additionalDetailsCalls = new Array();
2933 if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.util.setMaxLength); // allow textareas to obey maxlength attrib
2935 SUGAR.savedViews = function() {
2936 var selectedOrderBy;
2937 var selectedSortOrder;
2940 var columnsMeta; // meta data for the display columns
2943 setChooser: function() {
2945 var displayColumnsDef = new Array();
2946 var hideTabsDef = new Array();
2948 var left_td = document.getElementById('display_tabs_td');
2949 if(typeof left_td == 'undefined' || left_td == null) return; // abort!
2950 var right_td = document.getElementById('hide_tabs_td');
2952 var displayTabs = left_td.getElementsByTagName('select')[0];
2953 var hideTabs = right_td.getElementsByTagName('select')[0];
2955 for(i = 0; i < displayTabs.options.length; i++) {
2956 displayColumnsDef.push(displayTabs.options[i].value);
2959 if(typeof hideTabs != 'undefined') {
2960 for(i = 0; i < hideTabs.options.length; i++) {
2961 hideTabsDef.push(hideTabs.options[i].value);
2964 if (!SUGAR.savedViews.clearColumns)
2965 document.getElementById('displayColumnsDef').value = displayColumnsDef.join('|');
2966 document.getElementById('hideTabsDef').value = hideTabsDef.join('|');
2969 select: function(saved_search_select) {
2970 for(var wp = 0; wp < document.search_form.saved_search_select.options.length; wp++) {
2971 if(typeof document.search_form.saved_search_select.options[wp].value != 'undefined' &&
2972 document.search_form.saved_search_select.options[wp].value == saved_search_select) {
2973 document.search_form.saved_search_select.selectedIndex = wp;
2974 document.search_form.ss_delete.style.display = '';
2975 document.search_form.ss_update.style.display = '';
2979 saved_search_action: function(action, delete_lang) {
2980 if(action == 'delete') {
2981 if(!confirm(delete_lang)) return;
2983 if(action == 'save') {
2984 if(document.search_form.saved_search_name.value.replace(/^\s*|\s*$/g, '') == '') {
2985 alert(SUGAR.language.get('app_strings', 'LBL_SAVED_SEARCH_ERROR'));
2990 // This check is needed for the Activities module (Calls/Meetings/Tasks).
2991 if (document.search_form.saved_search_action)
2993 document.search_form.saved_search_action.value = action;
2994 document.search_form.search_module.value = document.search_form.module.value;
2995 document.search_form.module.value = 'SavedSearch';
2996 // Bug 31922 - Make sure to specify that we want to hit the index view here of
2997 // the SavedSearch module, since the ListView doesn't have the logic to save the
2998 // search and redirect back
2999 document.search_form.action.value = 'index';
3001 document.search_form.submit();
3003 shortcut_select: function(selectBox, module) {
3005 selecturl = 'index.php?module=SavedSearch&search_module=' + module + '&action=index&saved_search_select=' + selectBox.options[selectBox.selectedIndex].value
3006 //add searchFormTab to url if it is available. This determines what tab to render
3007 if(typeof(document.getElementById('searchFormTab'))!='undefined'){
3008 selecturl = selecturl + '&searchFormTab=' + document.search_form.searchFormTab.value;
3010 //add showSSDIV to url if it is available. This determines whether saved search sub form should
3011 //be rendered open or not
3012 if(document.getElementById('showSSDIV') && typeof(document.getElementById('showSSDIV') !='undefined')){
3013 selecturl = selecturl + '&showSSDIV='+document.getElementById('showSSDIV').value;
3015 //use created url to navigate
3016 document.location.href = selecturl;
3018 handleForm: function() {
3019 SUGAR.tabChooser.movementCallback = function(left_side, right_side) {
3020 while(document.getElementById('orderBySelect').childNodes.length != 0) { // clear out order by options
3021 document.getElementById('orderBySelect').removeChild(document.getElementById('orderBySelect').lastChild);
3024 var selectedIndex = 0;
3025 var nodeCount = -1; // need this because the counter i also includes "undefined" nodes
3026 // which was breaking Calls and Meetings
3028 for(i in left_side.childNodes) { // fill in order by options
3029 if(typeof left_side.childNodes[i].nodeName != 'undefined' &&
3030 left_side.childNodes[i].nodeName.toLowerCase() == 'option' &&
3031 typeof SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value] != 'undefined' && // check if column is sortable
3032 typeof SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value]['sortable'] == 'undefined' &&
3033 SUGAR.savedViews.columnsMeta[left_side.childNodes[i].value]['sortable'] != false) {
3035 optionNode = document.createElement('option');
3036 optionNode.value = left_side.childNodes[i].value;
3037 optionNode.innerHTML = left_side.childNodes[i].innerHTML;
3038 document.getElementById('orderBySelect').appendChild(optionNode);
3039 if(optionNode.value == SUGAR.savedViews.selectedOrderBy)
3040 selectedIndex = nodeCount;
3043 // Firefox needs this to be set after all the option nodes are created.
3044 document.getElementById('orderBySelect').selectedIndex = selectedIndex;
3046 SUGAR.tabChooser.movementCallback(document.getElementById('display_tabs_td').getElementsByTagName('select')[0]);
3048 // This check is needed for the Activities module (Calls/Meetings/Tasks).
3049 if (document.search_form.orderBy)
3050 document.search_form.orderBy.options.value = SUGAR.savedViews.selectedOrderBy;
3053 if(SUGAR.savedViews.selectedSortOrder == 'DESC') document.getElementById('sort_order_desc_radio').checked = true;
3054 else document.getElementById('sort_order_asc_radio').checked = true;
3059 SUGAR.searchForm = function() {
3062 // searchForm tab selector util
3063 searchFormSelect: function(view, previousView) {
3064 var module = view.split('|')[0];
3065 var theView = view.split('|')[1];
3067 var handleDisplay = function() { // hide other divs
3068 document.search_form.searchFormTab.value = theView;
3069 patt = module+"(.*)SearchForm$";
3070 divId=document.search_form.getElementsByTagName('div');
3071 // Hide all the search forms and retrive the name of the previous search tab (useful for the first load because previousView is empty)
3072 for (i=0;i<divId.length;i++){
3073 if(divId[i].id.match(module)==module){
3074 if(divId[i].id.match('SearchForm')=='SearchForm'){
3075 if(document.getElementById(divId[i].id).style.display == ''){
3076 previousTab=divId[i].id.match(patt)[1];
3078 document.getElementById(divId[i].id).style.display = 'none';
3082 // show the good search form.
3083 document.getElementById(module + theView + 'SearchForm').style.display = '';
3084 //if its not the first tab show there is a previous tab.
3086 thepreviousView=previousView.split('|')[1];
3089 thepreviousView=previousTab;
3091 thepreviousView=thepreviousView.replace(/_search/, "");
3092 // Process to retrieve the completed field from one tab to an other.
3093 for(num in document.search_form.elements) {
3094 if(document.search_form.elements[num]) {
3095 el = document.search_form.elements[num];
3096 pattern="^(.*)_"+thepreviousView+"$";
3097 if(typeof el.type != 'undefined' && typeof el.name != 'undefined' && el.name.match(pattern)) {
3098 advanced_input_name = el.name.match(pattern)[1]; // strip
3099 advanced_input_name = advanced_input_name+"_"+theView.replace(/_search/, "");
3100 if(typeof document.search_form[advanced_input_name] != 'undefined') // if advanced input of same name exists
3101 SUGAR.searchForm.copyElement(advanced_input_name, el);
3107 // if tab is not cached
3108 if(document.getElementById(module + theView + 'SearchForm').innerHTML == '') {
3109 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_LOADING'));
3110 var success = function(data) {
3111 document.getElementById(module + theView + 'SearchForm').innerHTML = data.responseText;
3113 SUGAR.util.evalScript(data.responseText);
3114 // pass script variables to global scope
3115 if(theView == 'saved_views') {
3116 if(typeof columnsMeta != 'undefined') SUGAR.savedViews.columnsMeta = columnsMeta;
3117 if(typeof selectedOrderBy != 'undefined') SUGAR.savedViews.selectedOrderBy = selectedOrderBy;
3118 if(typeof selectedSortOrder != 'undefined') SUGAR.savedViews.selectedSortOrder = selectedSortOrder;
3123 ajaxStatus.hideStatus();
3125 url = 'index.php?module=' + module + '&action=index&search_form_only=true&to_pdf=true&search_form_view=' + theView;
3127 //check to see if tpl has been specified. If so then pass location through url string
3129 if(document.getElementById('search_tpl') !=null && typeof(document.getElementById('search_tpl')) != 'undefined'){
3130 tpl = document.getElementById('search_tpl').value;
3131 if(tpl != ''){url += '&search_tpl='+tpl;}
3134 if(theView == 'saved_views') // handle the tab chooser
3135 url += '&displayColumns=' + SUGAR.savedViews.displayColumns + '&hideTabs=' + SUGAR.savedViews.hideTabs + '&orderBy=' + SUGAR.savedViews.selectedOrderBy + '&sortOrder=' + SUGAR.savedViews.selectedSortOrder;
3137 var cObj = YAHOO.util.Connect.asyncRequest('GET', url, {success: success, failure: success});
3139 else { // that form already retrieved
3144 // copies one input to another
3145 copyElement: function(inputName, copyFromElement) {
3146 switch(copyFromElement.type) {
3149 document.search_form[inputName].value = copyFromElement.value;
3153 // This function is here to clear the form, instead of "resubmitting it
3154 clear_form: function(form) {
3155 var elemList = form.elements;
3159 for( var i = 0; i < elemList.length ; i++ ) {
3161 if ( typeof(elem.type) == 'undefined' ) {
3165 elemType = elem.type.toLowerCase();
3167 if ( elemType == 'text' || elemType == 'textarea' || elemType == 'password' ) {
3170 else if ( elemType == 'select' || elemType == 'select-one' || elemType == 'select-multiple' ) {
3171 // We have, what I hope, is a select box, time to unselect all options
3172 var optionList = elem.options;
3173 for ( var ii = 0 ; ii < optionList.length ; ii++ ) {
3174 optionList[ii].selected = false;
3177 else if ( elemType == 'radio' || elemType == 'checkbox' ) {
3178 elem.checked = false;
3179 elem.selected = false;
3181 else if ( elemType == 'hidden' ) {
3182 // We only want to reset the hidden values that link to the select boxes.
3183 if ( ( elem.name.length > 3 && elem.name.substring(elem.name.length-3) == '_id' )
3184 || ((elem.name.length > 9) && (elem.name.substring(elem.name.length - 9) == '_id_basic'))
3185 || ( elem.name.length > 12 && elem.name.substring(elem.name.length-12) == '_id_advanced' ) ) {
3190 SUGAR.savedViews.clearColumns = true;
3194 // Code for the column/tab chooser used on homepage and in admin section
3195 SUGAR.tabChooser = function () {
3196 var object_refs = new Array();
3198 /* Describe certain transfers as invalid */
3201 movementCallback: function(left_side, right_side) {},
3202 orderCallback: function(left_side, right_side) {},
3204 freezeOptions: function(left_name, right_name, target) {
3205 if(!SUGAR.tabChooser.frozenOptions) { SUGAR.tabChooser.frozenOptions = []; }
3206 if(!SUGAR.tabChooser.frozenOptions[left_name]) { SUGAR.tabChooser.frozenOptions[left_name] = []; }
3207 if(!SUGAR.tabChooser.frozenOptions[left_name][right_name]) { SUGAR.tabChooser.frozenOptions[left_name][right_name] = []; }
3208 if(typeof target == 'array') {
3209 for(var i in target) {
3210 SUGAR.tabChooser.frozenOptions[left_name][right_name][target[i]] = true;
3213 SUGAR.tabChooser.frozenOptions[left_name][right_name][target] = true;
3217 buildSelectHTML: function(info) {
3218 var text = "<select";
3220 if(typeof (info['select']['size']) != 'undefined') {
3221 text +=" size=\""+ info['select']['size'] +"\"";
3224 if(typeof (info['select']['name']) != 'undefined') {
3225 text +=" name=\""+ info['select']['name'] +"\"";
3228 if(typeof (info['select']['style']) != 'undefined') {
3229 text +=" style=\""+ info['select']['style'] +"\"";
3232 if(typeof (info['select']['onchange']) != 'undefined') {
3233 text +=" onChange=\""+ info['select']['onchange'] +"\"";
3236 if(typeof (info['select']['multiple']) != 'undefined') {
3241 for(i=0; i<info['options'].length;i++) {
3242 option = info['options'][i];
3243 text += "<option value=\""+option['value']+"\" ";
3244 if ( typeof (option['selected']) != 'undefined' && option['selected']== true) {
3247 text += ">"+option['text']+"</option>";
3249 text += "</select>";
3253 left_to_right: function(left_name, right_name, left_size, right_size) {
3254 SUGAR.savedViews.clearColumns = false;
3255 var left_td = document.getElementById(left_name+'_td');
3256 var right_td = document.getElementById(right_name+'_td');
3258 var display_columns_ref = left_td.getElementsByTagName('select')[0];
3259 var hidden_columns_ref = right_td.getElementsByTagName('select')[0];
3261 var selected_left = new Array();
3262 var notselected_left = new Array();
3263 var notselected_right = new Array();
3265 var left_array = new Array();
3267 var frozen_options = SUGAR.tabChooser.frozenOptions;
3268 frozen_options = frozen_options && frozen_options[left_name] && frozen_options[left_name][right_name]?frozen_options[left_name][right_name]:[];
3270 // determine which options are selected in left
3271 for (i=0; i < display_columns_ref.options.length; i++)
3273 if ( display_columns_ref.options[i].selected == true && !frozen_options[display_columns_ref.options[i].value])
3275 selected_left[selected_left.length] = {text: display_columns_ref.options[i].text, value: display_columns_ref.options[i].value};
3279 notselected_left[notselected_left.length] = {text: display_columns_ref.options[i].text, value: display_columns_ref.options[i].value};
3284 for (i=0; i < hidden_columns_ref.options.length; i++)
3286 notselected_right[notselected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
3290 var left_select_html_info = new Object();
3291 var left_options = new Array();
3292 var left_select = new Object();
3294 left_select['name'] = left_name+'[]';
3295 left_select['id'] = left_name;
3296 left_select['size'] = left_size;
3297 left_select['multiple'] = 'true';
3299 var right_select_html_info = new Object();
3300 var right_options = new Array();
3301 var right_select = new Object();
3303 right_select['name'] = right_name+'[]';
3304 right_select['id'] = right_name;
3305 right_select['size'] = right_size;
3306 right_select['multiple'] = 'true';
3308 for (i = 0; i < notselected_right.length; i++) {
3309 right_options[right_options.length] = notselected_right[i];
3312 for (i = 0; i < selected_left.length; i++) {
3313 right_options[right_options.length] = selected_left[i];
3315 for (i = 0; i < notselected_left.length; i++) {
3316 left_options[left_options.length] = notselected_left[i];
3318 left_select_html_info['options'] = left_options;
3319 left_select_html_info['select'] = left_select;
3320 right_select_html_info['options'] = right_options;
3321 right_select_html_info['select'] = right_select;
3322 right_select_html_info['style'] = 'background: lightgrey';
3324 var left_html = this.buildSelectHTML(left_select_html_info);
3325 var right_html = this.buildSelectHTML(right_select_html_info);
3327 left_td.innerHTML = left_html;
3328 right_td.innerHTML = right_html;
3330 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3331 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3333 this.movementCallback(object_refs[left_name], object_refs[right_name]);
3339 right_to_left: function(left_name, right_name, left_size, right_size, max_left) {
3340 SUGAR.savedViews.clearColumns = false;
3341 var left_td = document.getElementById(left_name+'_td');
3342 var right_td = document.getElementById(right_name+'_td');
3344 var display_columns_ref = left_td.getElementsByTagName('select')[0];
3345 var hidden_columns_ref = right_td.getElementsByTagName('select')[0];
3347 var selected_right = new Array();
3348 var notselected_right = new Array();
3349 var notselected_left = new Array();
3351 var frozen_options = SUGAR.tabChooser.frozenOptions;
3352 frozen_options = SUGAR.tabChooser.frozenOptions && SUGAR.tabChooser.frozenOptions[right_name] && SUGAR.tabChooser.frozenOptions[right_name][left_name]?SUGAR.tabChooser.frozenOptions[right_name][left_name]:[];
3354 for (i=0; i < hidden_columns_ref.options.length; i++)
3356 if (hidden_columns_ref.options[i].selected == true && !frozen_options[hidden_columns_ref.options[i].value])
3358 selected_right[selected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
3362 notselected_right[notselected_right.length] = {text:hidden_columns_ref.options[i].text, value:hidden_columns_ref.options[i].value};
3367 if(max_left != '' && (display_columns_ref.length + selected_right.length) > max_left) {
3368 alert('Maximum of ' + max_left + ' columns can be displayed.');
3372 for (i=0; i < display_columns_ref.options.length; i++)
3374 notselected_left[notselected_left.length] = {text:display_columns_ref.options[i].text, value:display_columns_ref.options[i].value};
3378 var left_select_html_info = new Object();
3379 var left_options = new Array();
3380 var left_select = new Object();
3382 left_select['name'] = left_name+'[]';
3383 left_select['id'] = left_name;
3384 left_select['multiple'] = 'true';
3385 left_select['size'] = left_size;
3387 var right_select_html_info = new Object();
3388 var right_options = new Array();
3389 var right_select = new Object();
3391 right_select['name'] = right_name+ '[]';
3392 right_select['id'] = right_name;
3393 right_select['multiple'] = 'true';
3394 right_select['size'] = right_size;
3396 for (i = 0; i < notselected_left.length; i++) {
3397 left_options[left_options.length] = notselected_left[i];
3400 for (i = 0; i < selected_right.length; i++) {
3401 left_options[left_options.length] = selected_right[i];
3403 for (i = 0; i < notselected_right.length; i++) {
3404 right_options[right_options.length] = notselected_right[i];
3406 left_select_html_info['options'] = left_options;
3407 left_select_html_info['select'] = left_select;
3408 right_select_html_info['options'] = right_options;
3409 right_select_html_info['select'] = right_select;
3410 right_select_html_info['style'] = 'background: lightgrey';
3412 var left_html = this.buildSelectHTML(left_select_html_info);
3413 var right_html = this.buildSelectHTML(right_select_html_info);
3415 left_td.innerHTML = left_html;
3416 right_td.innerHTML = right_html;
3418 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3419 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3421 this.movementCallback(object_refs[left_name], object_refs[right_name]);
3426 up: function(name, left_name, right_name) {
3427 SUGAR.savedViews.clearColumns = false;
3428 var left_td = document.getElementById(left_name+'_td');
3429 var right_td = document.getElementById(right_name+'_td');
3430 var td = document.getElementById(name+'_td');
3431 var obj = td.getElementsByTagName('select')[0];
3432 obj = (typeof obj == "string") ? document.getElementById(obj) : obj;
3433 if (obj.tagName.toLowerCase() != "select" && obj.length < 2)
3435 var sel = new Array();
3437 for (i=0; i<obj.length; i++) {
3438 if (obj[i].selected == true) {
3439 sel[sel.length] = i;
3442 for (i=0; i < sel.length; i++) {
3443 if (sel[i] != 0 && !obj[sel[i]-1].selected) {
3444 var tmp = new Array(obj[sel[i]-1].text, obj[sel[i]-1].value);
3445 obj[sel[i]-1].text = obj[sel[i]].text;
3446 obj[sel[i]-1].value = obj[sel[i]].value;
3447 obj[sel[i]].text = tmp[0];
3448 obj[sel[i]].value = tmp[1];
3449 obj[sel[i]-1].selected = true;
3450 obj[sel[i]].selected = false;
3454 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3455 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3457 this.orderCallback(object_refs[left_name], object_refs[right_name]);
3462 down: function(name, left_name, right_name) {
3463 SUGAR.savedViews.clearColumns = false;
3464 var left_td = document.getElementById(left_name+'_td');
3465 var right_td = document.getElementById(right_name+'_td');
3466 var td = document.getElementById(name+'_td');
3467 var obj = td.getElementsByTagName('select')[0];
3468 if (obj.tagName.toLowerCase() != "select" && obj.length < 2)
3470 var sel = new Array();
3471 for (i=obj.length-1; i>-1; i--) {
3472 if (obj[i].selected == true) {
3473 sel[sel.length] = i;
3476 for (i=0; i < sel.length; i++) {
3477 if (sel[i] != obj.length-1 && !obj[sel[i]+1].selected) {
3478 var tmp = new Array(obj[sel[i]+1].text, obj[sel[i]+1].value);
3479 obj[sel[i]+1].text = obj[sel[i]].text;
3480 obj[sel[i]+1].value = obj[sel[i]].value;
3481 obj[sel[i]].text = tmp[0];
3482 obj[sel[i]].value = tmp[1];
3483 obj[sel[i]+1].selected = true;
3484 obj[sel[i]].selected = false;
3488 object_refs[left_name] = left_td.getElementsByTagName('select')[0];
3489 object_refs[right_name] = right_td.getElementsByTagName('select')[0];
3491 this.orderCallback(object_refs[left_name], object_refs[right_name]);
3496 }(); // end tabChooser
3498 SUGAR.language = function() {
3500 languages : new Array(),
3502 setLanguage: function(module, data) {
3503 if (!SUGAR.language.languages) {
3506 SUGAR.language.languages[module] = data;
3509 get: function(module, str) {
3510 if(typeof SUGAR.language.languages[module] == 'undefined'
3511 || typeof SUGAR.language.languages[module][str] == 'undefined')
3514 return SUGAR.language.languages[module][str];
3519 SUGAR.contextMenu = function() {
3521 objects: new Object(),
3522 objectTypes: new Object(),
3524 * Registers a new object for the context menu.
3525 * objectType - name of the type
3527 * metaData - metaData to pass to the action function
3529 registerObject: function(objectType, id, metaData) {
3530 SUGAR.contextMenu.objects[id] = new Object();
3531 SUGAR.contextMenu.objects[id] = {'objectType' : objectType, 'metaData' : metaData};
3534 * Registers a new object type
3535 * name - name of the type
3536 * menuItems - array of menu items
3538 registerObjectType: function(name, menuItems) {
3539 SUGAR.contextMenu.objectTypes[name] = new Object();
3540 SUGAR.contextMenu.objectTypes[name] = {'menuItems' : menuItems, 'objects' : new Array()};
3543 * Determines which menu item was clicked
3545 getListItemFromEventTarget: function(p_oNode) {
3547 if(p_oNode.tagName == "LI") {
3552 if(p_oNode.tagName == "LI") {
3557 } while((p_oNode = p_oNode.parentNode));
3562 * handles movement within context menu
3564 onContextMenuMove: function() {
3565 var oNode = this.contextEventTarget;
3566 var bDisabled = (oNode.tagName == "UL");
3567 var i = this.getItemGroups()[0].length - 1;
3569 this.getItem(i).cfg.setProperty("disabled", bDisabled);
3574 * handles clicks on a context menu ITEM
3576 onContextMenuItemClick: function(p_sType, p_aArguments, p_oItem) {
3577 var oLI = SUGAR.contextMenu.getListItemFromEventTarget(this.parent.contextEventTarget);
3578 id = this.parent.contextEventTarget.parentNode.id; // id of the target
3579 funct = eval(SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[id]['objectType']]['menuItems'][this.index]['action']);
3580 funct(this.parent.contextEventTarget, SUGAR.contextMenu.objects[id]['metaData']);
3583 * Initializes all context menus registered
3586 for(var i in SUGAR.contextMenu.objects) { // make a variable called objects in objectTypes containg references to all triggers
3587 if(typeof SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'] == 'undefined')
3588 SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'] = new Array();
3589 SUGAR.contextMenu.objectTypes[SUGAR.contextMenu.objects[i]['objectType']]['objects'].push(document.getElementById(i));
3591 // register the menus
3592 for(var i in SUGAR.contextMenu.objectTypes) {
3593 var oContextMenu = new YAHOO.widget.ContextMenu(i, {'trigger': SUGAR.contextMenu.objectTypes[i]['objects']});
3594 var aMainMenuItems = SUGAR.contextMenu.objectTypes[i]['menuItems'];
3595 var nMainMenuItems = aMainMenuItems.length;
3597 for(var j = 0; j < nMainMenuItems; j++) {
3598 oMenuItem = new YAHOO.widget.ContextMenuItem(aMainMenuItems[j].text, { helptext: aMainMenuItems[j].helptext });
3599 oMenuItem.clickEvent.subscribe(SUGAR.contextMenu.onContextMenuItemClick, oMenuItem, true);
3600 oContextMenu.addItem(oMenuItem);
3602 // Add a "move" event handler to the context menu
3603 oContextMenu.moveEvent.subscribe(SUGAR.contextMenu.onContextMenuMove, oContextMenu, true);
3604 // Add a "keydown" event handler to the context menu
3605 oContextMenu.keyDownEvent.subscribe(SUGAR.contextMenu.onContextMenuItemClick, oContextMenu, true);
3606 // Render the context menu
3607 oContextMenu.render(document.body);
3613 SUGAR.contextMenu.actions = function() {
3616 * redirects to a new note with the clicked on object as the target
3618 createNote: function(itemClicked, metaData) {
3619 loc = 'index.php?module=Notes&action=EditView';
3620 for(i in metaData) {
3621 if(i == 'notes_parent_type') loc += '&parent_type=' + metaData[i];
3622 else if(i != 'module' && i != 'parent_type') loc += '&' + i + '=' + metaData[i];
3624 document.location = loc;
3627 * redirects to a new note with the clicked on object as the target
3629 scheduleMeeting: function(itemClicked, metaData) {
3630 loc = 'index.php?module=Meetings&action=EditView';
3631 for(i in metaData) {
3632 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3634 document.location = loc;
3637 * redirects to a new note with the clicked on object as the target
3639 scheduleCall: function(itemClicked, metaData) {
3640 loc = 'index.php?module=Calls&action=EditView';
3641 for(i in metaData) {
3642 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3644 document.location = loc;
3647 * redirects to a new contact with the clicked on object as the target
3649 createContact: function(itemClicked, metaData) {
3650 loc = 'index.php?module=Contacts&action=EditView';
3651 for(i in metaData) {
3652 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3654 document.location = loc;
3657 * redirects to a new task with the clicked on object as the target
3659 createTask: function(itemClicked, metaData) {
3660 loc = 'index.php?module=Tasks&action=EditView';
3661 for(i in metaData) {
3662 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3664 document.location = loc;
3667 * redirects to a new opportunity with the clicked on object as the target
3669 createOpportunity: function(itemClicked, metaData) {
3670 loc = 'index.php?module=Opportunities&action=EditView';
3671 for(i in metaData) {
3672 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3674 document.location = loc;
3677 * redirects to a new opportunity with the clicked on object as the target
3679 createCase: function(itemClicked, metaData) {
3680 loc = 'index.php?module=Cases&action=EditView';
3681 for(i in metaData) {
3682 if(i != 'module') loc += '&' + i + '=' + metaData[i];
3684 document.location = loc;
3687 * handles add to favorites menu selection
3689 addToFavorites: function(itemClicked, metaData) {
3690 success = function(data) {
3692 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});
3697 //if(typeof YAHOO != 'undefined') YAHOO.util.Event.addListener(window, 'load', SUGAR.contextMenu.init);
3699 // initially from popup_parent_helper.js
3700 var popup_request_data;
3703 function get_popup_request_data()
3705 return window.document.popup_request_data;
3708 function get_close_popup()
3710 return window.document.close_popup;
3713 function open_popup(module_name, width, height, initial_filter, close_popup, hide_clear_button, popup_request_data, popup_mode, create, metadata)
3715 if (typeof(popupCount) == "undefined" || popupCount == 0)
3718 // set the variables that the popup will pull from
3719 window.document.popup_request_data = popup_request_data;
3720 window.document.close_popup = close_popup;
3724 + 'module=' + module_name
3727 if (initial_filter != '') {
3728 URL += '&query=true' + initial_filter;
3729 // Bug 41891 - Popup Window Name
3730 popupName = initial_filter.replace(/[^a-z_0-9]+/ig, '_');
3731 windowName = module_name + '_popup_window' + popupName;
3733 windowName = module_name + '_popup_window' + popupCount;
3737 if (hide_clear_button) {
3738 URL += '&hide_clear_button=true';
3741 windowFeatures = 'width=' + width
3742 + ',height=' + height
3743 + ',resizable=1,scrollbars=1';
3745 if (popup_mode == '' && popup_mode == 'undefined') {
3746 popup_mode='single';
3748 URL+='&mode='+popup_mode;
3749 if (create == '' && create == 'undefined') {
3752 URL+='&create='+create;
3754 if (metadata != '' && metadata != 'undefined') {
3755 URL+='&metadata='+metadata;
3758 win = SUGAR.util.openWindow(URL, windowName, windowFeatures);
3762 // put the focus on the popup if the browser supports the focus() method
3766 win.popupCount = popupCount;
3772 * The reply data must be a JSON array structured with the following information:
3773 * 1) form name to populate
3774 * 2) associative array of input names to values for populating the form
3776 var from_popup_return = false;
3778 function set_return_basic(popup_reply_data,filter)
3780 var form_name = popup_reply_data.form_name;
3781 var name_to_value_array = popup_reply_data.name_to_value_array;
3782 for (var the_key in name_to_value_array)
3784 if(the_key == 'toJSON')
3788 else if(the_key.match(filter))
3790 var displayValue=name_to_value_array[the_key].replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');;
3791 // begin andopes change: support for enum fields (SELECT)
3792 if(window.document.forms[form_name] && window.document.forms[form_name].elements[the_key]) {
3793 if(window.document.forms[form_name].elements[the_key].tagName == 'SELECT') {
3794 var selectField = window.document.forms[form_name].elements[the_key];
3795 for(var i = 0; i < selectField.options.length; i++) {
3796 if(selectField.options[i].text == displayValue) {
3797 selectField.options[i].selected = true;
3802 window.document.forms[form_name].elements[the_key].value = displayValue;
3805 // end andopes change: support for enum fields (SELECT)
3810 function set_return(popup_reply_data)
3812 from_popup_return = true;
3813 var form_name = popup_reply_data.form_name;
3814 var name_to_value_array = popup_reply_data.name_to_value_array;
3815 if(typeof name_to_value_array != 'undefined' && name_to_value_array['account_id'])
3818 var label_data_str = '';
3819 var current_label_data_str = '';
3820 for (var the_key in name_to_value_array)
3822 if(the_key == 'toJSON')
3828 var displayValue=name_to_value_array[the_key].replace(/&/gi,'&').replace(/</gi,'<').replace(/>/gi,'>').replace(/'/gi,'\'').replace(/"/gi,'"');
3829 if(window.document.forms[form_name] && document.getElementById(the_key+'_label') && !the_key.match(/account/)) {
3830 var data_label = document.getElementById(the_key+'_label').innerHTML.replace(/\n/gi,'');
3831 label_str += data_label + ' \n';
3832 label_data_str += data_label + ' ' + displayValue + '\n';
3833 if(window.document.forms[form_name].elements[the_key]) {
3834 current_label_data_str += data_label + ' ' + window.document.forms[form_name].elements[the_key].value +'\n';
3839 if(label_data_str != label_str && current_label_data_str != label_str){
3840 if(confirm(SUGAR.language.get('app_strings', 'NTC_OVERWRITE_ADDRESS_PHONE_CONFIRM') + '\n\n' + label_data_str))
3842 set_return_basic(popup_reply_data,/\S/);
3844 set_return_basic(popup_reply_data,/account/);
3846 }else if(label_data_str != label_str && current_label_data_str == label_str){
3847 set_return_basic(popup_reply_data,/\S/);
3848 }else if(label_data_str == label_str){
3849 set_return_basic(popup_reply_data,/account/);
3852 set_return_basic(popup_reply_data,/\S/);
3856 function set_return_and_save(popup_reply_data)
3858 var form_name = popup_reply_data.form_name;
3859 var name_to_value_array = popup_reply_data.name_to_value_array;
3861 for (var the_key in name_to_value_array)
3863 if(the_key == 'toJSON')
3869 window.document.forms[form_name].elements[the_key].value = name_to_value_array[the_key];
3873 window.document.forms[form_name].return_module.value = window.document.forms[form_name].module.value;
3874 window.document.forms[form_name].return_action.value = 'DetailView';
3875 window.document.forms[form_name].return_id.value = window.document.forms[form_name].record.value;
3876 window.document.forms[form_name].action.value = 'Save';
3877 window.document.forms[form_name].submit();
3881 * This is a helper function to construct the initial filter that can be
3882 * passed into the open_popup() function. It assumes that there is an
3883 * account_id and account_name field in the given form_name to use to
3884 * construct the intial filter string.
3886 function get_initial_filter_by_account(form_name)
3888 var account_id = window.document.forms[form_name].account_id.value;
3889 var account_name = escape(window.document.forms[form_name].account_name.value);
3890 var initial_filter = "&account_id=" + account_id + "&account_name=" + account_name;
3892 return initial_filter;
3894 // end code from popup_parent_helper.js
3896 // begin code for address copy
3898 * This is a function used by the Address widget that will fill
3899 * in the given array fields using the fromKey and toKey as a
3900 * prefix into the form objects HTML elements.
3902 * @param form The HTML form object to parse
3903 * @param fromKey The prefix of elements to copy from
3904 * @param toKey The prefix of elements to copy into
3905 * @return boolean true if successful, false otherwise
3907 function copyAddress(form, fromKey, toKey) {
3909 var elems = new Array("address_street", "address_city", "address_state", "address_postalcode", "address_country");
3910 var checkbox = document.getElementById(toKey + "_checkbox");
3912 if(typeof checkbox != "undefined") {
3913 if(!checkbox.checked) {
3915 t = toKey + "_" + elems[x];
3916 document.getElementById(t).removeAttribute('readonly');
3920 f = fromKey + "_" + elems[x];
3921 t = toKey + "_" + elems[x];
3923 document.getElementById(t).value = document.getElementById(f).value;
3924 document.getElementById(t).setAttribute('readonly', true);
3930 // end code for address copy
3933 * This function is used in Email Template Module.
3934 * It will check whether the template is used in Campaing->EmailMarketing.
3935 * If true, it will notify user.
3938 function check_deletable_EmailTemplate() {
3939 id = document.getElementsByName('record')[0].value;
3940 currentForm = document.getElementById('form');
3942 success:function(r) {
3943 if(r.responseText == 'true') {
3944 if(!confirm(SUGAR.language.get('app_strings','NTC_TEMPLATE_IS_USED'))) {
3948 if(!confirm(SUGAR.language.get('app_strings','NTC_DELETE_CONFIRMATION'))) {
3952 currentForm.return_module.value='EmailTemplates';
3953 currentForm.return_action.value='ListView';
3954 currentForm.action.value='Delete';
3955 currentForm.submit();
3958 url = "index.php?module=EmailTemplates&action=CheckDeletable&from=DetailView&to_pdf=1&record="+id;
3959 YAHOO.util.Connect.asyncRequest('POST',url, call_back,null);
3963 remove_upload_imagefile : function(field_name) {
3964 var field=document.getElementById('remove_imagefile_' + field_name);
3967 //enable the file upload button.
3968 var field=document.getElementById( field_name);
3969 field.style.display="";
3971 //hide the image and remove button.
3972 var field=document.getElementById('img_' + field_name);
3973 field.style.display="none";
3974 var field=document.getElementById('bt_remove_' + field_name);
3975 field.style.display="none";
3977 if(document.getElementById(field_name + '_duplicate')) {
3978 var field = document.getElementById(field_name + '_duplicate');
3983 confirm_imagefile : function(field_name) {
3984 var field=document.getElementById(field_name);
3985 var filename=field.value;
3986 var fileExtension = filename.substring(filename.lastIndexOf(".")+1);
3987 fileExtension = fileExtension.toLowerCase();
3988 if (fileExtension == "jpg" || fileExtension == "jpeg"
3989 || fileExtension == "gif" || fileExtension == "png" || fileExtension == "bmp"){
3994 alert(SUGAR.language.get('app_strings', 'LBL_UPLOAD_IMAGE_FILE_INVALID'));
3998 lightbox : function(image)
4000 if (typeof(SUGAR.image.lighboxWindow) == "undefined")
4001 SUGAR.image.lighboxWindow = new YAHOO.widget.SimpleDialog('sugarImageViewer', {
4004 id:'sugarMsgWindow',
4007 msg: "<img src='" + image + "'> </img>",
4010 SUGAR.image.lighboxWindow.setBody("<img src='" + image + "'> </img>");
4011 SUGAR.image.lighboxWindow.render(document.body);
4012 SUGAR.image.lighboxWindow.show();
4013 SUGAR.image.lighboxWindow.center()
4017 SUGAR.util.isTouchScreen = function()
4019 // first check if we have forced use of the touch enhanced interface
4020 if ( Get_Cookie("touchscreen") == '1' ) {
4024 // next check if we should use the touch interface with our device
4025 if ( (navigator.userAgent.match(/iPad/i) != null) ) {
4032 SUGAR.util.isLoginPage = function(content)
4034 //skip if this is packageManager screen
4035 if(SUGAR.util.isPackageManager()) {return false;}
4036 var loginPageStart = "<!DOCTYPE";
4037 if (content.substr(0, loginPageStart.length) == loginPageStart && content.indexOf("<html>") != -1 && content.indexOf("login_module") != -1) {
4038 window.location.href = window.location.protocol + window.location.pathname;
4043 SUGAR.util.isPackageManager=function(){
4044 if(typeof(document.the_form) !='undefined' && typeof(document.the_form.language_pack_escaped) !='undefined'){
4046 }else{return false;}
4049 SUGAR.util.ajaxCallInProgress = function(){
4050 return SUGAR_callsInProgress != 0;
4053 SUGAR.util.closeActivityPanel = {
4054 show:function(module,id,new_status,viewType,parentContainerId){
4055 if (SUGAR.util.closeActivityPanel.panel)
4056 SUGAR.util.closeActivityPanel.panel.destroy();
4057 var singleModule = SUGAR.language.get("app_list_strings", "moduleListSingular")[module];
4058 singleModule = typeof(singleModule != 'undefined') ? singleModule.toLowerCase() : '';
4059 var closeText = SUGAR.language.get("app_strings", "LBL_CLOSE_ACTIVITY_CONFIRM").replace("#module#",singleModule);
4060 SUGAR.util.closeActivityPanel.panel =
4061 new YAHOO.widget.SimpleDialog("closeActivityDialog",
4068 constraintoviewport: true,
4069 buttons: [ { text:SUGAR.language.get("app_strings", "LBL_EMAIL_OK"), handler:function(){
4070 if (SUGAR.util.closeActivityPanel.panel)
4071 SUGAR.util.closeActivityPanel.panel.hide();
4073 ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_SAVING'));
4074 var args = "action=save&id=" + id + "&record=" + id + "&status=" + new_status + "&module=" + module;
4075 // 20110307 Frank Steegmans: Fix for bug 42361, Any field with a default configured in any activity will be set to this default when closed using the close dialog
4076 // TODO: Take id out and regression test. Left id in for now to not create any other unexpected problems
4077 //var args = "action=save&id=" + id + "&status=" + new_status + "&module=" + module;
4080 { //refresh window to show updated changes
4081 window.location.reload(true);
4083 if(viewType == 'dashlet')
4085 SUGAR.mySugar.retrieveDashlet(o.argument['parentContainerId']);
4086 ajaxStatus.hideStatus();
4088 else if(viewType == 'subpanel'){
4089 showSubPanel(o.argument['parentContainerId'],null,true);
4090 if(o.argument['parentContainerId'] == 'activities'){
4091 showSubPanel('history',null,true);
4093 ajaxStatus.hideStatus();
4095 }else if(viewType == 'listview'){
4096 document.location = 'index.php?module=' + module +'&action=index';
4100 argument:{'parentContainerId':parentContainerId}
4103 YAHOO.util.Connect.asyncRequest('POST', 'index.php', callback, args);
4105 }, isDefault:true },
4106 { text:SUGAR.language.get("app_strings", "LBL_EMAIL_CANCEL"), handler:function(){SUGAR.util.closeActivityPanel.panel.hide(); }} ]
4109 SUGAR.util.closeActivityPanel.panel.setHeader(SUGAR.language.get("app_strings", "LBL_CLOSE_ACTIVITY_HEADER"));
4110 SUGAR.util.closeActivityPanel.panel.render(document.body);
4111 SUGAR.util.closeActivityPanel.panel.show();
4115 SUGAR.util.setEmailPasswordDisplay = function(id, exists) {
4116 link = document.getElementById(id+'_link');
4117 pwd = document.getElementById(id);
4118 if(!pwd || !link) return;
4120 pwd.style.display = 'none';
4121 link.style.display = '';
4123 pwd.style.display = '';
4124 link.style.display = 'none';
4128 SUGAR.util.setEmailPasswordEdit = function(id) {
4129 link = document.getElementById(id+'_link');
4130 pwd = document.getElementById(id);
4131 if(!pwd || !link) return;
4132 pwd.style.display = '';
4133 link.style.display = 'none';