
function trim(value) {
    return value.replace(/^\s+|\s+$/g, "");
}

function formatPhoneFax(field) {
    field.value = trim(field.value);

    var ov = field.value;
    var v = "";
    var x = -1;

    // is this phone number 'escaped' by a leading plus?
    if (0 < ov.length && '+' != ov.charAt(0)) { // format it
        // count number of digits
        var n = 0;
        if ('1' == ov.charAt(0)) {  // skip it
            ov = ov.substring(1, ov.length);
        }

        for (i = 0; i < ov.length; i++) {
            var ch = ov.charAt(i);

            // build up formatted number
            if (ch >= '0' && ch <= '9') {
                if (n == 0) v += "(";
                else if (n == 3) v += ") ";
                else if (n == 6) v += "-";
                v += ch;
                n++;
            }

            // check for extension type section;

            // are spaces, dots, dashes and parentheses the only valid non-digits in a phone number?

            if (! (ch >= '0' && ch <= '9') && ch != ' ' && ch != '-' && ch != '.' && ch != '(' && ch != ')') {
                x = i;
                break;
            }
        }

        // add the extension

        if (x >= 0) v += " " + ov.substring(x, ov.length);

        // if we recognize the number, then format it

        if (n == 10 && v.length <= 40) field.value = v;
    }
    return true;
}


// this function replaces a letter with a given substitute

function replaceChar(origText,origLetter,replaceLetter) {
	var replaceText = "";
	if(origText != null && origText != '') {
        for(i = 0; i < origText.length; i++) {
            var ch = origText.charAt(i);
        	if(ch == origLetter) {
                replaceText += replaceLetter;
            } else {
                replaceText += ch;
            }
        } // end for
      } // end if
	return replaceText;
}


// this function pops up a window alerting user the action button is inactive

function inactiveButton() {
	alert('Under construction!');
}


// this function formats decimal numbers to be like 1,999.90

function formatDollarDecimal(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
		num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
		cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+
            num.substring(num.length-(4*i+3));

	return (((sign)?'':'-') + num + '.' + cents);
}

// this function formats positive decimal numbers to be like 1,999.90

function formatPositiveDollarDecimal(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
		num = "0";
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
		cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (num + '.' + cents);
}



// this function formats integer numbers to be like 1,999

function formatDollarInteger(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
		num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	num = Math.floor(num/100).toString();
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + num);
}

// this function formats positive integer numbers to be like 1,999

function formatPositiveInteger(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
		num = "0";
	num = Math.floor(num*100+0.50000000001);
	num = Math.floor(num/100).toString();
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (num);
}


// this function converts a date with format 999999 to 99/99/99
function formatDate(field) {
    field.value = trim(field.value);

    var origValue = field.value;
    var formattedValue = origValue;
    var x = -1;
    
    if(origValue.length == 6) {
        var modify = 1;
        
        for(i = 0; i < origValue.length; i++) {
            var ch = origValue.charAt(i);
            if(ch == '/') modify = 0;
        } // end for
        
        if(modify == 1) {
            formattedValue = "";
            for(i = 0; i < origValue.length; i++) {
                var ch = origValue.charAt(i);
                if(i == 2 || i == 4) formattedValue += "/";
                formattedValue += ch;
            } // end for
        }
    }
    
    // reset field value
    field.value = formattedValue;
    return true;
}

// this function pops up a list order view screen
function showListOrderView(id) {
  var listOrderView = '/market?page=listorders/list_order_print&isPrintView=yes&listOrderFinanceOption=yes&id='+id;
  listOrderViewWindow = window.open(listOrderView,"ListOrderView","toolbar=no,menubar=1,status=yes,scrollbars=yes,resizable=1");
  listOrderViewWindow .focus();
}


// this function pops up a invoice view screen

function showInvoiceView(id) {
  var invoiceView = '/market?page=finance/invoice_print&isForm=true&popup=yes&id='+id;
  invoiceViewWindow = window.open(invoiceView,"InvoiceView","toolbar=no,menubar=1,status=yes,scrollbars=yes,resizable=1");
  invoiceViewWindow.focus();
}


// this function pops up a payment view screen
function showPaymentView(id) {
  var paymentView = '/market?page=finance/payment_print&isForm=true&popup=yes&id='+id;
  paymentViewWindow = window.open(paymentView,"PaymentView","toolbar=no,menubar=1,status=yes,scrollbars=yes,resizable=1");
  paymentViewWindow.focus();
}

// this function fixes any decimal arithmetic errors
function fixDecimals(value,places) {
if (isNaN(places)){places=2;}
    return parseFloat(parseFloat(value).toFixed(places));
}

// this function opens a window based on given parameters
// added on 5/22/06
function showWindow(window,windowUrl,windowName,windowOption) {
	newWindow = window.open(windowUrl,windowName,windowOption);
	newWindow.focus();
}

// generic toggle function for checkbox
// added 8/2/2006
function togglecb(cb,cbName) {
  	var toggler = document.getElementsByName(cbName);
  	var i=0;

    if (self['mytoggler']) mytoggler(cb,cbName,-1); //pre process

 	if (toggler != null){
   		for( i=0; i<toggler.length; i++ ) {
     		if (cb.form.name == toggler[i].form.name) {
    			toggler[i].checked = cb.checked;
    			if (self['mytoggler']) mytoggler(cb,cbName,i);
   			}
   		}
 	}
 	//set all checkall boxes
    toggler = document.getElementsByName(cb.name);
    i=0;
  	if (toggler != null){
    	for( i=0; i<toggler.length; i++ ) {
     		if (cb.form.name == toggler[i].form.name) {
    			toggler[i].checked = cb.checked;
    			if (self['mytoggler']) mytoggler(cb,cbName,i);
   			}
    	}
 	}

    if (self['mytoggler']) mytoggler(cb,cbName,-2); //post process
}


// generic toggle function for checkbox
// added 2/7/2007
function setAllValues(actionObject) {
  	var actioner = document.getElementsByName(actionObject.name);
  	var i=0;
    
    if (self['mySetAllValues']) mySetAllValues(actionObject,-1); //pre process
    
 	if (actioner != null){
   		for( i=0; i<actioner.length; i++ ) {
     		if (actionObject.form.name == actioner[i].form.name) {
    			actioner[i].value = actionObject.value;
    			if (self['mySetAllValues']) mySetAllValues(actionObject,0);
   			}
   		}
 	}
    
    if (self['mySetAllValues']) mySetAllValues(actionObject,-2); //post process
}

// this function pops up an account view screen
function showAccountView(id) {
  var accountView = '/market?page=accounts/account_print&id='+id;
  accountViewWindow = window.open(accountView,"AccountView","toolbar=no,menubar=1,status=yes,scrollbars=yes,resizable=1");
  accountViewWindow.focus();
}

// this function pops up a contact view screen
function showContactView(id) {
  var contactView = '/market?page=accounts/account_contact_print&id='+id;
  contactViewWindow = window.open(contactView,"ContactView","width=500,height=400,toolbar=no,menubar=1,status=yes,scrollbars=yes,resizable=1");
  contactViewWindow.focus();
}

//will return a blank if value passed is NaN or a zero.
/*
function blankifzero(value) { 
    var retVal ;
	if (isNaN(retVal)){ retVal = "0"; }
	retVal = parseInt(replaceChar(value,',',''));
	retVal = (retVal == 0)  ? "" : retVal;
	return retVal;
}
*/

// check if field value is 0, if so blank it
function blankifzero(value) {
	var newValue = value;
	if(value == '0' || value == '0.0' || value == '0.00') {
		newValue = '';
	}
	return newValue;
}

// this function validates date string
function validateDate(dateString) {
	var returnVal = 0;	// 0 = invalid, 1 = valid
		
	var arrayDate = dateString.split('/');
	if(arrayDate.length == 3) {
		// check each substring and see if in valid range
		if(arrayDate[0] && arrayDate[1] && arrayDate[2]) {
			var testDate = new Date();
			testDate.setDate(1);
			// check month
			if (arrayDate[0] >= 1 && arrayDate[0] <= 12) {
				testDate.setMonth(arrayDate[0]-1);
				// set year
				testDate.setFullYear(arrayDate[2]);
				// get number of days for that year,month
				var yearMonth = new Date(arrayDate[2], arrayDate[0], 0);
				testDate.setDate(arrayDate[1]);
				if (testDate.getMonth() == (arrayDate[0]-1)) {
					returnVal = 1;
				}
			}
		}
	}
	return returnVal;
}

function initPre() {
	if (self['myInitPrePreGlobal']) myInitPrePreGlobal(); //pre process pre global code
	
	
	// initialize ajax search
	var elemSpan = document.createElement("span");
	elemSpan.id = "spanOutput";
	elemSpan.className = "spanTextDropdown";
	document.body.appendChild(elemSpan);
	document.onkeydown=handleDocumentKeyDown;
	//document.onmousedown=handleDocumentMouseDown;

	/*
	// search text
	document.modSearchForm.searchText.obj =
      SetProperties(document.modSearchForm.searchText,
        document.modSearchForm.itemId,'/market?page=general/item_lookup',"",
        true,true,true,false,"No matching Data",false,null,null,
        null,null,false,false);
    */

	// Close orphaned timout window from spawned tabs/windows (IE only)
    try {
        if (window.opener && window.opener.timeoutWindow) 
            window.opener.timeoutWindow.close();
    } catch (err) {
        // sometimes FF throws a security error. ignore it.
    }


	// start session timeout timer using ext. values set in mod_head.jsp
	startTimeoutTimer(sessionTimeoutMins, sessionTimeoutWarnSecs);
	// test setting: 2 minute session, warn at 100 seconds.
	//startTimeoutTimer(2, 100);
  
    if (self['pageInit']) pageInit();	// page specific intialization
    if (self['sortables_init']) sortables_init();	// sortable initialization
    
	if (self['myInitPrePostGlobal']) myInitPrePostGlobal(); //pre process post global code
}

function initPost() {
	if (self['myInitPostPreGlobal']) myInitPostPreGlobal(); //post process pre global code
	
	if (self['myInitPostPostGlobal']) myInitPostPostGlobal(); //post process post global code
    
    // This will pop up a warning if the user a) just logged in and b)is close to his password expiration date.
    if (window.showPWWarning)
        showPWWarning();
}

// called for 'onunload' page events site-wide.
function uninit() {
	if (window.timeoutWindow) window.timeoutWindow.close();
}

function hideSubmitButtons() {
	inputs = document.getElementsByTagName("input");
	for (i=0;i<inputs.length;i++) {
		oneinput = inputs[i];
		if(oneinput.type == 'submit') {
			oneinput.style.display = 'none';
		}
	}
}

function disableButtons() {
	inputs = document.getElementsByTagName("input");
	for (i=0;i<inputs.length;i++) {
		oneinput = inputs[i];
		if(oneinput.type == 'submit') {
			oneinput.disabled = true;
		}
	}
}

function toggleCheckBoxes(checkbox,otherboxes) {
	inputs = document.getElementsByTagName("input");
	for (i=0;i<inputs.length;i++) {
		oneinput = inputs[i];
		if(oneinput.name == otherboxes || oneinput.name == checkbox.name) {
			oneinput.checked = checkbox.checked;
		}
	}
}

/*
  Javascript doesn't support function overloading, so this one was never being executed. The next one down is.
  Commented out on 7/16/09 -kj

function textCounter(field, countfield, maxlimit, object) {
    if (field.value.length > maxlimit) // if too long...trim it!
        field.value = field.value.substring(0, maxlimit);
    // otherwise, update 'characters left' counter
    else
        countfield.value = maxlimit - field.value.length;
    
    warnlevel = .75;
    criticallevel = .9;
    if (document.getElementById) {
        if(field.value.length > (maxlimit * criticallevel)) {
            document.getElementById(object).className = 'critical';
        } else if (field.value.length > (maxlimit * warnlevel)){
            document.getElementById(object).className = 'warning';
        } else {
            document.getElementById(object).className = 'ok';
        }
    } else if (document.layers && document.layers[object]) {
        if(field.value.length > (maxlimit * criticallevel)) {
            document.layers[object].className = 'critical';
        } else if(field.value.length > (maxlimit * warnlevel)) {
            document.layers[object].className = 'warning';
        } else {
            document.layers[object].className = 'ok';
        }
    } else if (document.all) {
        if(field.value.length > (maxlimit * criticallevel)) {
            document.all[object].className = 'critical';
        } else if(field.value.length > (maxlimit * warnlevel)) {
            document.all[object].className = 'warning';
        } else {
            document.all[object].className = 'ok';
        }
    }
}
*/

function textCounter(field, countfield, maxlimit) {
    if (field.value.length > maxlimit) {
        field.value = field.value.substring(0, maxlimit);
    	countfield.value = "There are 0 characters remaining";
    } else // otherwise, update 'characters left' counter
        countfield.value = "There are "+(maxlimit - field.value.length)+" characters remaining";
    countfield.size=countfield.value.length+3;
    warnlevel = .75;
    criticallevel = .9;
    if (field.value.length > (maxlimit * criticallevel)) {
        countfield.className = 'critical';
    } else if (field.value.length > (maxlimit * warnlevel)) {
        countfield.className = 'warning';
    } else { 
        countfield.className = 'ok';
    }
}

function changeOwner() {
	document.ownerEditForm.submit();
}

function formatPercent(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
		num = "0";

    sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;

    if(Math.floor(num/100) > 100) {
    	return '100';
    } else if(Math.floor(num/100) == 100 && cents > 0) {
    	return '100';
    } else {
		num = Math.floor(num/100).toString();
		if(cents<10)
			cents = "0" + cents;
	
		for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
			num = num.substring(0,num.length-(4*i+3))+','+
	
		num.substring(num.length-(4*i+3));
		return (num + '.' + cents);;
	}
}

function urldecode(str) {
    str = unescape(str);	

    var string = "";

    var i = 0;
    var c = c1 = c2 = 0;
 
    while (i < str.length) {
 
        c = str.charCodeAt(i);

        if (c < 128) {
            string += String.fromCharCode(c);
            i++;
        } else if((c > 191) && (c < 224)) {
            c2 = str.charCodeAt(i+1);
            string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
            i += 2;
        } else {
            c2 = str.charCodeAt(i+1);
            c3 = str.charCodeAt(i+2);
            string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }

    }
 
    return string;
}

function parseParams(url) {
   var result = new Array();   

   url = url.substring(url.indexOf('?') + 1);

   params = url.split(/&/);

   for (i = 0; i < params.length; i++) {
       temp = params[i].split(/=/);
       result[temp[0]] = urldecode(temp[1]);
   }

   return result;
}

/** 
 * given a string, it parses the number as a float, ignoring commas, returning the nunber or zero if the
 * string was null or empty. 
 */
function toFloat(str) {
    if (! str || str == '') return 0.0;
    str = str.replace(/,/g, '');
    return parseFloat(str);
}


/*************************************************************************/
// Lookups 
/*************************************************************************/
// Do not call these openXXXXLookup() functions directly.  Instead use the lookup widgets
// in html/FormWidgets.java, when possible.




// Open a lookup window for lists
//
// params:
// idFieldId - id of the list ID field
// nameFieldId - - id of list name field
// extraChar - char(s) to add to lookup value 
function openListLookup(idFieldId, nameFieldId, extraChar, descOfSearch, noMin) 
{  
  // alert( "<openListSearch> : " + idFieldId + ", " + nameFieldId ); 
  var lookupVal = $("#" + nameFieldId ).val();

  if ( extraChar != null && extraChar != '' )
      lookupVal += extraChar;
  //alert( "<openListSearch> : " + lookupVal );
  
  window.open("/market?page=general/list_lookup"
            + "&searchText=" + lookupVal 
            + "&nameFieldId=" + nameFieldId 
            + "&idFieldId=" + idFieldId
            + "&descOfSearch=" + descOfSearch
            + "&noMin=" + noMin,           
            "LookupWindow",
            "width=750,height=500,toolbar=no,menubar=0,status=yes,scrollbars=yes,resizable=no");
}

function getMediaLookupKey(myfield,e,idFieldId, nameFieldId, descOfSearch, noMin)
{
    var keycode;
    if ( window.event ) 
        keycode = window.event.keyCode;
    else if (e) 
        keycode = e.which;
    else return true;
    
    // alert( keycode );
    
    if ( keycode == 42 ) // * - add it to lookupVal
    {
       openListLookup(idFieldId, nameFieldId, "*", descOfSearch, noMin) ;
       return true;
    }
    /***************
    else if ( keycode == 32 ) // space
    {
       openListLookup(idFieldId, nameFieldId, '', descOfSearch, noMin) ;
       return true;
    }
    ******************/
    else
       return true;
}


// Open a lookup window for members
//
// params:
// idFieldId - id of the member ID field
// nameFieldId - - id of member name field
// showStatus - All, A, or I
function openMemberLookup(idFieldId, nameFieldId, showStatus, descOfSearch, extraChar) 
{  
  // alert( "<openMemberLookup> : " + idFieldId + ", " + nameFieldId + ", " + accountId + ", " + showStatus );
  var lookupVal = $("#" + nameFieldId ).val();
               
  if ( extraChar != null && extraChar != '' )
      lookupVal += extraChar;
    
  window.open("/market?page=general/member_lookup"
            + "&searchText=" + lookupVal 
            + "&nameFieldId=" + nameFieldId 
            + "&idFieldId=" + idFieldId
            + "&statusToShow=" + showStatus
            + "&descOfSearch=" + descOfSearch,
            "LookupWindow",
            "width=500,height=400,toolbar=no,menubar=0,status=yes,scrollbars=yes,resizable=no");          
}

function getMemberLookupKey(myfield, e, idFieldId, nameFieldId, showStatus, descOfSearch)
{
    var keycode;
    if ( window.event ) 
        keycode = window.event.keyCode;
    else if (e) 
        keycode = e.which;
    else return true;
    
    // alert( keycode );
    
    if ( keycode == 42 ) // * - add it to lookupVal
    {
       openMemberLookup(idFieldId, nameFieldId, showStatus, descOfSearch, '*');
       return true;
    }
    else
       return true;
}


// Accounts and contacts are often shown as a pair.  In those cases, we need to 
// keep the two in sync - they can't have a contact that is not in the selected account.

// params:
// idFieldId - id of the contact ID field
// nameFieldId - - id of contact name field
// accountIdFieldId - id of related account id field 
// accountNameFieldId - id of related account name field
// roles - ----- (see comment below)
// showNewButton - true to show "New Account" button

// The roles is a string of 'y' and minus signs relating to these: 
//    account_t.broker_yn",
//    account_t.manager_yn",
//    account_t.mailer_yn",
//    account_t.list_owner_yn",
//    account_t.service_bureau_yn"
// e.g. '-y---'
//  all dashes (-----) results in no role criteria being used, so you get everything (the same results, theoretically,
//  as yyyyy, but more efficient).
function openContactLookup(idFieldId, nameFieldId, accountIdFieldId, accountNameFieldId, roles, showNewButton, descOfSearch, extraChar) 
{ 
  var lookupVal = $("#" + nameFieldId ).val();
  if ( extraChar != null && extraChar != '' )
      lookupVal += extraChar;
    
  var accountId = "";
  
  // alert( accountIdFieldId );
  if ( accountIdFieldId != "" )
      accountId = $("#" + accountIdFieldId ).val();
  var accountName = "";
  if ( accountNameFieldId != "" )  
      accountName = $("#" + accountNameFieldId ).val();
  // alert( "<openContactLookup> : " + idFieldId + ", " + nameFieldId + ", " + accountIdFieldId + ", " + showNewButton + ", " + lookupVal );

  var windowName = "LookupWindow";
    
  window.open("/market?page=general/contact_lookup"
            + "&accountId=" + accountId
            + "&accountName=" + accountName
            + "&accountIdFieldId=" + accountIdFieldId 
            + "&accountNameFieldId=" + accountNameFieldId
            + "&searchText=" + lookupVal 
            + "&nameFieldId=" + nameFieldId 
            + "&idFieldId=" + idFieldId
            + "&showNewButton=" + showNewButton
            + "&roles=" + roles           
            + "&descOfSearch=" + descOfSearch,
            windowName,
            "width=600,height=450,toolbar=no,menubar=0,status=yes,scrollbars=yes,resizable=no");
            
}


function getContactLookupKey(myfield, e, idFieldId, nameFieldId, accountIdFieldId, accountNameFieldId, roles, showNewButton, descOfSearch)
{
    /*********************
    var params = "{ roles: " + roles + " }";
    if ( accountIdFieldId != null )
    {
        if ( document.getElementById(accountIdFieldId) != null && document.getElementById(accountIdFieldId).value > 0 )
        {
            var specVal = document.getElementById(accountIdFieldId).value; 
            alert( specVal );
           
            params += ", accountId: " + specVal + " }";
           
        }
    }
    
    alert( "test selector : " + nameFieldId + ", " + $("#" + accountIdFieldId).val() );
    
    var ac = $("#" + nameFieldId)[0].Autocompleter;  // $("#" + nameFieldId)[0].autocompleter; 
    ac.setExtraParams(params);  
    ********************/
        
    var keycode;
    
    if ( window.event ) 
        keycode = window.event.keyCode;
    else if (e) 
        keycode = e.which;
    else return true;
    
    // alert( keycode );
    
    if ( keycode == 42 ) // * - add it to lookupVal
    {
       openContactLookup(idFieldId, nameFieldId, accountIdFieldId, accountNameFieldId, roles, showNewButton, descOfSearch, '*');
       return true;
    }
    else
       return true;
}



// We need to give the account an array of contact fields - there can be more than one.

// params:
// idFieldId - id of the account ID field
// nameFieldId - - id of account name field
// contacttIdFieldIds - array of ids of related contact id field (actually a pipe delimeted string)
// contactNameFieldIds - array of ids of related contact name field (actually a pipe delimeted string)
// roles - -----
// showNewButton - true to show "New Account" button
function openAccountLookup(idFieldId, nameFieldId, contactIdFieldIds, contactNameFieldIds, 
                           roles, showNewButton, descOfSearch,
                           accountToIgnore, extraChar) 
{ 
  var lookupVal = $("#" + nameFieldId ).val();
  if ( extraChar != null && extraChar != '' )
      lookupVal += extraChar;

  var accountId = "";
  
  // alert( "<openContactLookup> : " + idFieldId + ", " + nameFieldId + ", " + accountId + ", " + showNewButton + ", " + lookupVal );
  // if we are doing this from a quick-create from the lookup window, we need to open in a new window.
  // alert( window.name );
  var windowName;
  if ( window.name == "LookupWindow" )
      windowName = "LookupSubWindow";
  else
      windowName = "LookupWindow";
  
  window.open("/market?page=general/acct_lookup"
            + "&idFieldId=" + idFieldId 
            + "&nameFieldId=" + nameFieldId
            + "&contactIdFieldId=" + contactIdFieldIds 
            + "&contactNameFieldId=" + contactNameFieldIds            
            + "&searchText=" + lookupVal 
            + "&showNewButton=" + showNewButton
            + "&roles=" + roles
            + "&descOfSearch=" + descOfSearch 
            + "&accountToIgnore=" + accountToIgnore,
            windowName,
            "width=600,height=450,toolbar=no,menubar=0,status=yes,scrollbars=yes,resizable=no");
            
}    


function getAccountLookupKey(myfield, e, 
                             idFieldId, nameFieldId, contactIdFieldIds, contactNameFieldIds, 
                             roles, showNewButton, descOfSearch,
                             accountToIgnore)
{
    var keycode;
    if ( window.event ) 
        keycode = window.event.keyCode;
    else if (e) 
        keycode = e.which;
    else return true;
    
    // alert( keycode );
    
    if ( keycode == 42 ) // * - add it to lookupVal
    {
       openAccountLookup(idFieldId, nameFieldId, contactIdFieldIds, contactNameFieldIds, 
                             roles, showNewButton, descOfSearch,
                             accountToIgnore, '*');
       return true;
    }
    else
       return true;
}




// This gets both memebrs (member_type_cd = 'NORMAL') and contacts
// params:
// idFieldId - id of the contact ID field
// nameFieldId - - id of contact name field
// typeCodeFieldId - id of field to hold type code (member or contact) 
// 
function openContactPlusMemberLookup(idFieldId, nameFieldId, typeCodeFieldId, descOfSearch, extraChar ) 
{ 
  var lookupVal = $("#" + nameFieldId ).val();
  if ( extraChar != null && extraChar != '' )
      lookupVal += extraChar;
  
  var windowName = "LookupWindow";
    
  window.open("/market?page=general/contact_member_lookup"
            + "&searchText=" + lookupVal 
            + "&nameFieldId=" + nameFieldId 
            + "&idFieldId=" + idFieldId
            + "&typeCodeFieldId=" + typeCodeFieldId
            + "&descOfSearch=" + descOfSearch,  
            windowName,
            "width=600,height=450,toolbar=no,menubar=0,status=yes,scrollbars=yes,resizable=no");
            
}

function openContactPlusMemberLookupKey(myfield, e, 
                             idFieldId, nameFieldId, typeCodeFieldId, descOfSearch)
{
    var keycode;
    if ( window.event ) 
        keycode = window.event.keyCode;
    else if (e) 
        keycode = e.which;
    else return true;
    
    // alert( keycode );
    
    if ( keycode == 42 ) // * - add it to lookupVal
    {
       openContactPlusMemberLookup(idFieldId, nameFieldId, typeCodeFieldId, descOfSearch, '*');
       return true;
    }
    else
       return true;
}


// Lookup Sales person - a member lookup with some complications
// Open a lookup window for members
//
// params:
// idFieldId - id of the member ID field
// nameFieldId - - id of member name field
// showStatus - All, A, or I
//    these last four are only needed for salesperson lookup:
// Comm Plan field ID - if applicable
// commSelectFieldId
// itemFieldId
// itemType
//
function openSalesPersonLookup(idFieldId, nameFieldId, showStatus, commPlanFieldId, commSelectFieldId, itemFieldId, itemType, descOfSearch, extraChar ) 
{  
  if ( commPlanFieldId == null )
      commPlanFieldId = "";
  if ( commSelectFieldId == null )
      commSelectFieldId = "";
  
  var itemId = "";
  if ( itemFieldId != null && itemFieldId != '' )
  {
      // alert( itemFieldId );
      itemId = $("#" + itemFieldId ).val();
  }
  // alert( "ch2" );
  
  // alert( "<openMemberLookup> : " + idFieldId + ", " + nameFieldId + ", " + accountId + ", " + showStatus );
  var lookupVal = $("#" + nameFieldId ).val();
  if ( extraChar != null && extraChar != '' )
      lookupVal += extraChar;
                
  window.open("/market?page=general/sales_person_lookup"
            + "&searchText=" + lookupVal 
            + "&nameFieldId=" + nameFieldId 
            + "&idFieldId=" + idFieldId
            + "&statusToShow=" + showStatus
            + "&commPlanFieldId=" + commPlanFieldId
            + "&commSelectFieldId=" + commSelectFieldId
            + "&descOfSearch=" + descOfSearch 
            + "&itemId=" + itemId
            + "&itemType=" + itemType,
            "LookupWindow",
            "width=500,height=400,toolbar=no,menubar=0,status=yes,scrollbars=yes,resizable=no");          
}

function getSalesPersonLookupKey(myfield, e, 
                             idFieldId, nameFieldId, showStatus, commPlanFieldId, commSelectFieldId, itemFieldId, itemType, descOfSearch)
{
    var keycode;
    if ( window.event ) 
        keycode = window.event.keyCode;
    else if (e) 
        keycode = e.which;
    else return true;
    
    // alert( keycode );
    
    if ( keycode == 42 ) // * - add it to lookupVal
    {
       openSalesPersonLookup(idFieldId, nameFieldId, showStatus, commPlanFieldId, commSelectFieldId, itemFieldId, itemType, descOfSearch, '*');
       return true;
    }
    else
       return true;
}



// Open a lookup window for orders
//
// params:
// idFieldId - id of the member ID field
// nameFieldId - - id of member name field
// showStatus - All, A, or I
function openOrderLookup(idFieldId, nameFieldId, descOfSearch, extraChar ) 
{  
  // alert( "<openMemberLookup> : " + idFieldId + ", " + nameFieldId + ", " + accountId + ", " + showStatus );
  var lookupVal = $("#" + nameFieldId ).val();
  if ( extraChar != null && extraChar != '' )
      lookupVal += extraChar;
       
  window.open("/market?page=general/order_lookup"
            + "&orderNum=" + lookupVal 
            + "&nameFieldId=" + nameFieldId 
            + "&idFieldId=" + idFieldId
            + "&descOfSearch=" + descOfSearch,
            "LookupWindow",
            "width=600,height=450,toolbar=no,menubar=0,status=yes,scrollbars=yes,resizable=no");          
}

function getOrderLookupKey(myfield, e, 
                             idFieldId, nameFieldId, descOfSearch)
{
    var keycode;
    if ( window.event ) 
        keycode = window.event.keyCode;
    else if (e) 
        keycode = e.which;
    else return true;
    
    // alert( keycode );
    
    if ( keycode == 42 ) // * - add it to lookupVal
    {
       openOrderLookup(idFieldId, nameFieldId, descOfSearch, '*');
       return true;
    }
    else
       return true;
}


// clearLookup is also part of the lookup widgets - it should not be used directly, generally.

function clearLookup(id, name ) 
{
      var ITEM_DELIMITER = "zzzz";
    
      // these can be pipe delimited lists
      var fieldIdList = id;
      
      while ( fieldIdList.indexOf( ITEM_DELIMITER ) > 0 )
      {
          var fieldId = fieldIdList.substring( 0, fieldIdList.indexOf( ITEM_DELIMITER ) );
          //alert( fieldId );
          $("#" + fieldId).val("");          
          fieldIdList = fieldIdList.substring( fieldIdList.indexOf( ITEM_DELIMITER ) + ITEM_DELIMITER.length )      
      }
      // and do the last (or only) one in the list.
      if ( fieldIdList.length > 0 )
      {
          $("#" + fieldIdList).val("");          
      }

      // same for name field...
      fieldIdList = name;
      while ( fieldIdList.indexOf( ITEM_DELIMITER ) > 0 )
      {
          var fieldId = fieldIdList.substring( 0, fieldIdList.indexOf( ITEM_DELIMITER ) );
          //alert( fieldId );
          $("#" + fieldId).val("");          
          fieldIdList = fieldIdList.substring( fieldIdList.indexOf( ITEM_DELIMITER ) + ITEM_DELIMITER.length )      
          //alert( fieldId + ", " + fieldIdList );
      }
      // and do the last (or only) one in the list.
      if ( fieldIdList.length > 0 )
      {
          $("#" + fieldIdList).val("");          
      }

}

// roles and dependentFieldId can be used for whatever you need.
// roles will be passed to the lookup module as a string
// we will pass dependednt fieldId as a string, and also assume it is
// a field ID and pass the fields value.
// same for dependentNameField
// For example, on contact fields we use roles to pass roles (duh) and we use
// dependentFieldId to pass the account id field id and value.
// itemToConsider can be used to pass something else.
function addAutoComplete(jqInputs, url, roles, dependentIdFieldId, dependentNameFieldId, itemToConsider ) 
{
    
    // alert( "ch: " +  jqInputs.val() );
    jqInputs.autocomplete(url, 
    {
                // if there is a dependent field that can change (and thereby change the desired results)
                // we cannot use the cache.
                cacheLength: ((dependentNameFieldId != null && dependentNameFieldId != "") ? 0 : 10 ),
                width: 300,
                multiple: false,
                matchContains: true,
                formatItem:   function(row) { return row[0]; },
                formatResult: function(row) { return row[0]; },
                max: 500,
                extraParams: { 
                    roles: roles,
                    dependentIdFieldValue: function() 
                        {
                            // alert(dependentIdFieldId + ", " + $("#" + dependentIdFieldId).val() );
                            if ( dependentIdFieldId != null && dependentIdFieldId != "" ) 
                                return ( $("#" + dependentIdFieldId).val() != null ? $("#" + dependentIdFieldId).val() : "" );
                            else
                                return "";
                        },
                    dependentIdFieldId: (dependentIdFieldId == null ? "" : dependentIdFieldId ),
                    dependentNameFieldValue: function() 
                        {
                            if ( dependentNameFieldId != null && dependentNameFieldId != "" ) 
                                return ( $("#" + dependentNameFieldId).val() != null ? $("#" + dependentNameFieldId).val() : "" ); 
                            else
                                return "";
                        },                  
                    dependentNameFieldId: (dependentNameFieldId == null ? "" : dependentNameFieldId ),
                    accountToIgnore: itemToConsider
                }

    });
    
    jqInputs.result(function(event, data, formatted) 
    {

        // alert( "in result function" );
        var ITEM_DELIMITER = "zzzz";

        var hidden = $(this).prev();
        // alert(hidden.attr('id') + ' = ' + hidden.val());
        hidden.val(data[1]);

        // alert(hidden.attr('id') + ' = ' + hidden.val());
        
        // and set the related fields also
        // alert( "ch1 : " + dependentNameFieldId + ", " + data[2] );
        if ( dependentNameFieldId != null && dependentNameFieldId != "" ) 
        {
            while ( dependentNameFieldId.indexOf( ITEM_DELIMITER ) > 0 )
            {
                var fieldId = dependentNameFieldId.substring( 0, dependentNameFieldId.indexOf( ITEM_DELIMITER ) );
                //alert( fieldId );
                var origValue = $("#" + fieldId).val();
                $("#" + fieldId).val(data[2]);                 
                if ( origValue == "" && $("#" + fieldId).val() != "" ) // if it got filled in by us
                {
                    // alert( "call from addauto" );
                    showRelated( $(this), $("#" + fieldId) );
                }
                
                dependentNameFieldId = dependentNameFieldId.substring( dependentNameFieldId.indexOf( ITEM_DELIMITER ) + ITEM_DELIMITER.length )      
            }
            // and do the last (or only) one in the list.
            if ( dependentNameFieldId.length > 0 )
            {
                var origValue = $("#" + dependentNameFieldId).val();
                $("#" + dependentNameFieldId).val(data[2]);  
                if ( origValue == "" && $("#" + dependentNameFieldId).val() != "" ) // if it got filled in by us
                {
                    // alert( "call from addauto" );
                    showRelated( $(this), $("#" + dependentNameFieldId) );
                }
                
            }
        }
        
        if ( dependentIdFieldId != null && dependentIdFieldId != "" )
        {
            while ( dependentIdFieldId.indexOf( ITEM_DELIMITER ) > 0 )
            {
                var fieldId = dependentIdFieldId.substring( 0, dependentIdFieldId.indexOf( ITEM_DELIMITER ) );
                //alert( fieldId );
                $("#" + fieldId).val(data[3]);          
                dependentIdFieldId = dependentIdFieldId.substring( dependentIdFieldId.indexOf( ITEM_DELIMITER ) + ITEM_DELIMITER.length )      
            }
            // and do the last (or only) one in the list.
            if ( dependentIdFieldId.length > 0 )
            {
                $("#" + dependentIdFieldId).val(data[3]);          
            }
        }  
        
        // indicate change, so page can do its own onchange action.
        hidden.change();        
        
    });
                                                                        
}

// If you want to get change events from a lookup window, you need to provide this method
// in the "opener".  Lookups will call it when an ID field is changed.  The opener can then
// do what it wants to do onchange.
// The lookup, being another window, is not allowed to fire the change event itself.
window.changeMyElement = function(theElement) 
{
    theElement.change();
}

// Use this to show that several fields are related, after one is changed
function showRelated( field1, field2, field3, field4 )
{
    // alert( "show related " + field1.attr("id") + "," + (field2==null?"":field2.attr("id")) + "," +  (field3==null?"":field3.attr("id")) + "," +  (field4==null?"":field4.attr("id")) ); 
    if ( field4 != null )
        showChange( field4 );
    if ( field3 != null )
        showChange( field3 );
    if ( field2 != null )
        showChange( field2 );
    if ( field1 != null )
        showChange( field1 );

    // when initial field loses focus, un-color.  Otherwise fades away slowly.
    field1.blur( function () {
            if ( field1 != null )
            {
                field1.stop();
                field1.animate({"background-color": "rgb(255,255,255)"}, 1000 );
            }
            if ( field2 != null )
            {
                field2.stop();
                field2.animate({"background-color": "rgb(255,255,255)"}, 1000 );
            }
            if ( field3 != null )
            {
                field3.stop();
                field3.animate({"background-color": "rgb(255,255,255)"}, 1000 );
            }
            if ( field4 != null )
            {
                field4.stop();
                field4.animate({"background-color": "rgb(255,255,255)"}, 1000 );
            }
    });    
    
    
    /********************
    if ( field1 != null )
        chgs += field1.attr("id");
    if ( field2 != null )
        chgs += "," + field2.attr("id");
    if ( field3 != null )
        chgs += "," + field3.attr("id");
    if ( field4 != null )
        chgs += "," + field4.attr("id");
    
    showChange( chgs );
    ********************/
    
}


// Use this function to make it apparent to the user that a field has changed as a result of their
// action.
function showChange( fieldToShow )
{
    fieldToShow.stop();
    // alert( fieldToShow.attr("id" ) );
    if ( fieldToShow.val() != "" )
    {
        // fade in to green background, then back out again
        var oldBg = "rgb(255,255,255)"; // fieldToShow.css( "background-color" );
        fieldToShow.animate(
            {"background-color": "rgb(220,230,220)"}, 
                       1000,
                       function() 
                       {
                           // restore to old color very slowly
                           $(this).animate({"background-color": oldBg}, 15000 );
                       }
                   );
    }
}


