
function trim(value) {
    if (value == null)
        return null;
    return value.replace(/^\s+|\s+$/g, "");
}

// Updates a field's value in place to format it as a nice phone number. Returns true on success.
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;
}

function validateTwitter(field) 
{

    var fieldValue = trim($("#" + field).val());
    if ( fieldValue != "" )
    {
        // allow url or user name
        if ( fieldValue.indexOf( "http://twitter.com/" ) != 0 
          && fieldValue.indexOf( "https://twitter.com/" ) != 0 
          && fieldValue.indexOf( "http://www.twitter.com/" ) != 0 
          && fieldValue.indexOf( "https://www.twitter.com/" ) != 0 
          && fieldValue.indexOf( "@" ) != 0 )
        {
            nmAlert( "The address you entered does not appear to be a valid Twitter URL or User Name.  Please try again.", field );
            return false;
        }
    }
    return true;
}

function validateLinkedIn(field) 
{
    
    // http://www.linkedin.com    
    fieldValue = trim($("#" + field).val());
    if ( fieldValue != "" )
    {
        if ( fieldValue.indexOf( "http://www.linkedin.com/" ) != 0 && fieldValue.indexOf( "https://www.linkedin.com/" ) != 0 )
        {
            nmAlert( "The address you entered does not appear to be a valid LinkedIn URL.  Please try again.", field );
            return false;
        }
    }   
    return true;
}

function validateFacebook(field) 
{
    // http://www.facebook.com
    fieldValue = trim($("#" + field).val());
    if ( fieldValue != "" )
    {
        if ( fieldValue.indexOf( "http://www.facebook.com/" ) != 0 && fieldValue.indexOf( "https://www.facebook.com/" ) != 0 )
        {
            nmAlert( "The address you entered does not appear to be a valid Facebook URL.  Please try again.", field );
            return false;
        }
    }
    return true;
}



// this function replaces a letter with a given substitute, safely handling null

function replaceChar(origText,origLetter,replaceLetter) {
    if(origText != null && origText != '') 
        return origText.replace(new RegExp(origLetter,"g"),replaceLetter);
    else 
        return "";
}


// 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) {
    if (num == null)
        num = "0";

    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 integer numbers to be like 1,999

function formatDollarInteger(num) {
    if (num == null)
        num = "0";
    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));
    if (num == "0")
        return num; // fix "-0" error
    else
        return ((sign ? '' : '-') + 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=orders/order_print&isPrintView=yes&listOrderFinanceOption=yes&id='+id;
  listOrderViewWindow = window.open(listOrderView,"OrderView","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 ( mm/dd/[yy]yy )
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;
		}
	}
}

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);;
    }
}

/** 
 * 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.


var itemTableName = "";
var searchLookupUrl = "";
var sortLookupUrl = "";
var savedSortLookupUrl = "";
var savedSearchLookupUrl = "";
var savedOpenerIdFieldId = "";
var savedOpenerNameFieldId = "";
var defaultSortColumn = 0;
var sortDir = 0;
var sortRecent = 0;
var openerIdFieldId = "";
var openerNameFieldId = "";
var openerTypeCodeFieldId = "";       
var openerRelatedIdFieldId = "";
var openerRelatedNameFieldId = "";        
var savedOpenerRelatedIdFieldId = "";
var savedOpenerRelatedNameFieldId = "";        

var standardCursorElems = 'body, a, img';
var lastItemShown = 0;
var ITEM_DELIMITER = "zzzz";


// 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) 
{  
    
    // set params for this lookup
    itemTableName = "ListItemTable";
    defaultSortColumn =1;
    sortDir = 0;
    sortRecent = 1;
    
    searchLookupUrl = "/market?page=general/list_lookup"
            + "&idFieldId=" + idFieldId
            + "&nameFieldId=" + nameFieldId 
            + "&descOfSearch=" + descOfSearch
            + "&noMin=" + noMin;
    sortLookupUrl = "/market?page=general/ajax_list_lookup_next"
           + "&toDo=sort"
           + "&noMin=" + noMin
           + "&nameFieldId=" + nameFieldId
           + "&idFieldId=" + idFieldId;
    
    openerIdFieldId = idFieldId;
    openerNameFieldId = nameFieldId;    
    
    // alert( "<openListSearch> : " + idFieldId + ", " + nameFieldId ); 
    var lookupVal = $("#" + nameFieldId ).val();
    if ( extraChar != null && extraChar != '' )
        lookupVal += extraChar;
    //alert( "<openListSearch> : " + lookupVal );   

    var minOk = "no";
    if ( noMin != 1 )
        minOk = "yes";  

    // remove in case close was used and did not remove it (it doesn't - but the buttons do).
    
    addLookupDiv( "List" );
    	
    // Now make an ajax call to get the contents for this thing.
    var url =  "/market?page=general/list_lookup";
    $("html").addClass( "busy" );
    
      var fullUrl = url
            + "&searchText=" + lookupVal 
            + "&nameFieldId=" + nameFieldId 
            + "&idFieldId=" + idFieldId
            + "&descOfSearch=" + descOfSearch
            + "&noMin=" + noMin;
    
      $.post(
           
           fullUrl,
           
           {
           },
           
           
           function(data)  
           { 
               // alert( data );
               var itemSize = Number( $("#item_count", data).html() );
               
               // alert( itemSize );
               $("html").removeClass( "busy" );

               // what we got back is the empty table and all the js methods 
               $("#lookupListDlgDivInner").prepend( data );  // $("#content", data).html() ); - messes things up
                
               // add the endless scroll function
               addEndlessScroll("general/ajax_list_lookup_next", "", "lookupListDlgDiv", "lookupListDlgDivInner", "&minOk=" + minOk );

               // get the first chunk of data
               sortItems( 1 );
                
               $("#ListItemTable #searchText").focus();
               
           },
           
           "html"
       );    

    createLookupDlg( "List", descOfSearch );
            
}

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) 
{  
     var showStatusCol = "yes";  // ??     
        
    
    // set params for this lookup
    itemTableName = "MemberItemTable";
    defaultSortColumn = 70;
    sortDir = 0;
    sortRecent = 70;
    
    searchLookupUrl = "/market?page=general/member_lookup"
            + "&idFieldId=" + idFieldId
            + "&nameFieldId=" + nameFieldId 
            + "&descOfSearch=" + descOfSearch;
    sortLookupUrl = "/market?page=general/ajax_member_lookup_next"
           + "&toDo=sort"
           + "&showStatusCol=" + showStatusCol
           + "&nameFieldId=" + nameFieldId
           + "&idFieldId=" + idFieldId;
    
    openerIdFieldId = idFieldId;
    openerNameFieldId = nameFieldId;    
    
    
    var lookupVal = $("#" + nameFieldId ).val();
    if ( extraChar != null && extraChar != '' )
      lookupVal += extraChar;
   
     addLookupDiv( "Member" );
     
    // Now make an ajax call to get the contents for this thing.
    var url =  "/market?page=general/member_lookup";
    $("html").addClass( "busy" );
    
      var fullUrl = url
            + "&searchText=" + lookupVal 
            + "&nameFieldId=" + nameFieldId 
            + "&idFieldId=" + idFieldId
            + "&statusToShow=" + showStatus
            + "&descOfSearch=" + descOfSearch;
    
      $.post(
           
           fullUrl,
           
           {
           },
           
           
           function(data)  
           { 
               
               var itemSize = Number( $("#item_count", data).html() );
               
               // alert( itemSize );
               $("html").removeClass( "busy" );

               // what we got back is the empty table and all the js methods 
               $("#lookupMemberDlgDivInner").prepend( data );  // $("#content", data).html() ); - messes things up
                
               // add the endless scroll function
               addEndlessScroll("general/ajax_member_lookup_next", showStatusCol, "lookupMemberDlgDiv", "lookupMemberDlgDivInner");
                               
               // get the first chunk of data
               sortItems( 70 );
                
               $("#MemberItemTable #searchText").focus();
               
           },
           
           "html"
       );    


    createLookupDlg( "Member", descOfSearch );
         
}

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, email, orgId) 
{ 
    
     var showStatusCol = "yes";  // ??     
     
    // set params for this lookup
    itemTableName = "ContactItemTable";
    defaultSortColumn = 29; 
    sortDir = 0; 
    sortRecent = 29;

    searchLookupUrl = "/market?page=general/contact_lookup"
            + "&idFieldId=" + idFieldId
            + "&nameFieldId=" + nameFieldId 
            + "&showNewButton=" + showNewButton
            + "&roles=" + roles
            + "&descOfSearch=" + descOfSearch
            + "&isEmail=" + email
            + "&orgId=" + orgId;
    sortLookupUrl = "/market?page=general/ajax_contact_lookup_next"
           + "&toDo=sort"
           + "&showStatusCol=" + showStatusCol
           + "&nameFieldId=" + nameFieldId
           + "&idFieldId=" + idFieldId
           + "&isEmail=" + email
           + "&orgId=" + orgId;
    
    openerIdFieldId = idFieldId;
    openerNameFieldId = nameFieldId;
    openerRelatedIdFieldId = accountIdFieldId;
    openerRelatedNameFieldId = accountNameFieldId;        
    
    
    var lookupVal = trim( $("#" + 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 );
     
  
    addLookupDiv( "Con" );
	
    // Now make an ajax call to get the contents for this thing.
    var url =  "/market?page=general/contact_lookup";
    $("html").addClass( "busy" );
    
    // if this is an email lookup, then the first time in we will use the 
    // text already entered as a start into an email search instead of a name search
    var emailText = "";
    if ( "yes" == email )
    {
        emailText = lookupVal;
        lookupVal = "";
    }
        
      var fullUrl = url
            + "&accountId=" + accountId
            + "&accountName=" + accountName
            + "&accountIdFieldId=" + accountIdFieldId 
            + "&accountNameFieldId=" + accountNameFieldId
            + "&searchText=" + lookupVal 
            + "&nameFieldId=" + nameFieldId 
            + "&idFieldId=" + idFieldId
            + "&showNewButton=" + showNewButton
            + "&roles=" + roles   
            + "&isEmail=" + email
            + "&email=" + emailText
            + "&descOfSearch=" + descOfSearch
            + "&orgId=" + orgId;      
          
      $.post(
           
           fullUrl,
           
           {
           },
           
           
           function(data)  
           { 
               
               var itemSize = Number( $("#item_count", data).html() );
               
               // alert( itemSize );
               $("html").removeClass( "busy" );

               // what we got back is the empty table and all the js methods 
               $("#lookupConDlgDivInner").prepend( data );  // $("#content", data).html() ); - messes things up
                
               // add the endless scroll function
               addEndlessScroll("general/ajax_contact_lookup_next", showStatusCol, "lookupConDlgDiv", "lookupConDlgDivInner", "&isEmail=" + email );
                               
               // get the first chunk of data
               sortItems( 29 ); // <%=SortConstants.SORT_BY_CONTACT_NAME%> );
                
               $("#ContactItemTable #searchText").focus();        
               
               // if there is an account field tied to the contact field.
               if ( accountIdFieldId != "" )
               {
                  var accId = $("#" + accountIdFieldId).val();
                  // alert( "tryin 1 : " + accountIdFieldId + " --- "  + accId  );
                  if ( !isNaN(accId)  &&  (Number(accId) > 0) )
                  {
                       // disable it, but re-enable when submitting, so the criteria is submitted.
                       $("#" + itemTableName + " #accountName").attr("disabled", true);
                       $("#" + itemTableName + " #accountName").attr("className", "readonly");
                       
                       // and load the hidden accountId field, so it gets submitted on searches -
                       // otherwise we match on name, and similar names end up matching
                       $("#" + itemTableName + " #accountId").val(accId);
                       //alert( $("#" + itemTableName + " #accountId").val() );
                  }
               }
               
               
           },
           
           "html"
       );    
	
	


    // And then display the dialog
    createLookupDlg( "Con", descOfSearch );

    if ( showNewButton ) 
    {
        $("#lookupConDlgDiv").dialog( "option", "buttons", 
            {
            'New Contact': function() 
                {
                    openNewContactEditor(idFieldId, nameFieldId, accountIdFieldId, accountNameFieldId, roles, showNewButton, descOfSearch, extraChar);
                }
            });
    } else {
    	// added 9/13/2010, IMP 0315
    	$("#lookupConDlgDiv").dialog( "option", "buttons", 
                {
                'New Contact': function() 
                    {
                        openNewContactEditor(idFieldId, nameFieldId, accountIdFieldId, accountNameFieldId, roles, showNewButton, descOfSearch, extraChar);
                    }
                });
    	
    	var buttons =  $("#lookupConDlgDiv").parent().find("button");

    	for ( var i = 0; i < buttons.length; ++i )
    	  {
    	     var jButton = $( buttons[i] );
    	     if ( jButton.text() == 'New Contact' )
    	     {
    	        
    	        jButton.attr('disabled', 'disabled' );
    	        jButton.addClass( 'ui-state-disabled' );
    	     }
    	  }
    }
    
    
}



function openNewContactEditor(idFieldId, nameFieldId, accountIdFieldId, accountNameFieldId, roles, showNewButton, descOfSearch, extraChar) 
{

    // We may be opening an account lookup from here - so save the contact URLs
    savedSortLookupUrl = sortLookupUrl;
    savedSearchLookupUrl = searchLookupUrl;
    // and save the original opener fields
    savedOpenerIdFieldId = openerIdFieldId;
    savedOpenerNameFieldId = openerNameFieldId;
    savedOpenerRelatedIdFieldId = openerRelatedIdFieldId;
    savedOpenerRelatedNameFieldId = openerRelatedNameFieldId;
    
    // remove in case close was used and did not remove it (it doesn't - but the buttons do).

    $("#newAcctDlgDiv").remove();
    $("body").prepend( '<div id="newAcctDlgDiv" width="600px"></div>' );
    
    // customize the color of the title bar
    $("#newAcctDlgDiv").prepend(
      '<style type="text/css">'
      + '    .ui-dialog .ui-dialog-titlebar { border-color: #5884b9; background: #5884b9; }'
      + '    .ui-dialog .ui-dialog-buttonpane { text-align: left; border-width: 1px 0 0 0; background-image: none; margin: .5em 0 0 0; padding: .3em 1em .3em .4em; }'
      + '    .ui-dialog .ui-dialog-buttonpane button {  margin: .5em .4em .5em 0; cursor: pointer; padding: 0em .1em 0em .1em; line-height: 1.4em; width:auto; overflow:visible; }'
    + '</style>' );    
    
    // Now make an ajax call to get the contents for this thing.
    var url =  "/market?page=general/quick_create_contact";
    $("html").addClass( "busy" );
    
      var fullUrl = url + "&roles=" + roles
                        + "&accountName=" + $("#" + accountNameFieldId).val()
                        + "&accountId=" + $("#" + accountIdFieldId).val(); 

      $.post(
           
           fullUrl,
           
           {
               link : "/market?page=" + "general/quick_create_contact"
           },
           
           
           function(data) 
           { 
               
               $("html").removeClass( "busy" );

               $("#newAcctDlgDiv").prepend( data );
                    
               $("#newAcctDlgDiv #<%=FormConstants.ACCT_NAME%>").focus();    
               
               //alert( "ch3" );
           },
           
           "html"
       ); 
      

    $("#newAcctDlgDiv").dialog({
        bgiframe: true, 
        autoOpen: false, 
        height: 450, 
        width: 600,
        modal: true,
        resizable: true,
        show: 'fade',
        title: "Create New Contact",
        buttons: {
            Save: function() 
                {
                    if ( validateContact(idFieldId, nameFieldId, accountIdFieldId, accountNameFieldId, roles, showNewButton, descOfSearch, extraChar) )
                    {
                        $("#newAcctDlgDiv").dialog('close');
                        $("#newAcctDlgDiv").dialog('destroy');
                        $("#newAcctDlgDiv").remove();
                    }
                },
            Cancel: function() 
                {
                    restoreSavedContactInfo();
                    $("#newAcctDlgDiv").dialog('close');
                    $("#newAcctDlgDiv").dialog('destroy');
                    $("#newAcctDlgDiv").remove();                    
                }
            }

    });
    
    $("#newAcctDlgDiv").dialog('open');    
       
}

function validateContact(idFieldId, nameFieldId, accountIdFieldId, accountNameFieldId, roles, showNewButton, descOfSearch, extraChar)
{
    

    var contactName = document.getElementById( "account_contact_first_name" );
    var accountName = document.getElementById( "dummyContactAcctName" );
    
    if ( trim(contactName.value) == "" )
    {
        nmAlert( "Please enter a contact name.", "account_contact_first_name" );
        return false;
    }
    else if ( trim(accountName.value) == "" )
    {
        nmAlert( "Please select an account.", "dummyContactAcctName" );
        return false;
    }
    else
    {
    	// update hidden state and country field if corresponding input fields are cleared
    	var stateInput = document.getElementById('stateInput');
    	if(stateInput != null && trim(stateInput.value) == '') {
    		document.getElementById('account_contact_state').value = '';
    	}
    	var countryInput = document.getElementById('countryInput');
    	if(countryInput != null && trim(countryInput.value) == '') {
    		document.getElementById('account_contact_country').value = '';
    	}
                
        // get the contact name they just created, before it goes away
        var lookupVal = $("#contact_name" ).val();        
    
        // now do an ajax submit, and put the results in the "window"
        var url =  "/market?page=general/contact_lookup";
        $("html").addClass( "busy" );
    
        var fullUrl = url;  
          
        $.post(
               
               fullUrl,
    
               $("#contactEditForm").serializeArray(),
              
               function(data) 
               { 
                   sortDir = 0; 
                   itemTableName = "ContactItemTable";  // restore - it got to be account there for a bit.
                   restoreSavedContactInfo();

                   sortItems( 29 );
           },
           
           "html"
       ); 

    
      return true;
    }

}

function restoreSavedContactInfo()
{
    
       // restore the contact sort url -
       sortLookupUrl = savedSortLookupUrl;
       searchLookupUrl = savedSearchLookupUrl;
       openerIdFieldId = savedOpenerIdFieldId;
       openerNameFieldId = savedOpenerNameFieldId;
       openerRelatedIdFieldId = savedOpenerRelatedIdFieldId;
       openerRelatedNameFieldId = savedOpenerRelatedNameFieldId;
    
}


function getContactLookupKey(myfield, e, idFieldId, nameFieldId, accountIdFieldId, accountNameFieldId, 
                            roles, showNewButton, descOfSearch, email, orgId)
{
        
    var keycode;
    
    if ( window.event ) 
        keycode = window.event.keyCode;
    else if (e) 
        keycode = e.which;
    else return true;
    
    // alert( email );
    
    if ( keycode == 42 ) // * - add it to lookupVal
    {
       openContactLookup(idFieldId, nameFieldId, accountIdFieldId, accountNameFieldId, 
                         roles, showNewButton, descOfSearch, '*', email, orgId);
       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, orgId, extraChar) 
{ 
     var showStatusCol = "yes";  // ??         
    
    // set params for this lookup
    itemTableName = "AccountItemTable";
    defaultSortColumn = 25; // <%=SortConstants.SORT_BY_ACCOUNT_NAME%>;
    sortDir = 0; // <%=SortConstants.ASEN_ORDER%>;
    sortRecent = 25; //<%=SortConstants.SORT_BY_ACCOUNT_NAME%>;
    
    searchLookupUrl = "/market?page=general/acct_lookup"
            + "&idFieldId=" + idFieldId
            + "&nameFieldId=" + nameFieldId 
            + "&showNewButton=" + showNewButton
            + "&roles=" + roles
            + "&descOfSearch=" + descOfSearch
            + "&accountToIgnore=" + accountToIgnore
            + "&orgId=" + orgId;
    sortLookupUrl = "/market?page=general/ajax_acct_lookup_next"
           + "&toDo=sort"
           + "&showStatusCol=" + showStatusCol
           + "&nameFieldId=" + nameFieldId
           + "&idFieldId=" + idFieldId
           + "&orgId=" + orgId;
    
     openerIdFieldId = idFieldId;
     openerNameFieldId = nameFieldId;
     openerRelatedIdFieldId = contactIdFieldIds;  // not actually needed
     openerRelatedNameFieldId = contactNameFieldIds; // not needed       
           

    var lookupVal = $("#" + nameFieldId ).val();
    if ( extraChar != null && extraChar != '' )
      lookupVal += extraChar;
       
    addLookupDiv( "Account" );
	
    // Now make an ajax call to get the contents for this thing.
    var url =  "/market?page=general/acct_lookup";
    $("html").addClass( "busy" );
    
      var fullUrl = url + "&idFieldId=" + idFieldId 
            + "&nameFieldId=" + nameFieldId
            + "&contactIdFieldId=" + contactIdFieldIds 
            + "&contactNameFieldId=" + contactNameFieldIds            
            + "&searchText=" + lookupVal 
            + "&showNewButton=" + showNewButton
            + "&roles=" + roles
            + "&descOfSearch=" + descOfSearch 
            + "&accountToIgnore=" + accountToIgnore
            + "&orgId=" + orgId;
    
      $.post(
           
           fullUrl,
           
           {
           },
           
           
           function(data)  
           { 
               
               var itemSize = Number( $("#item_count", data).html() );
               
               // alert( itemSize );
               $("html").removeClass( "busy" );

               // what we got back is the empty table and all the js methods 
               $("#lookupAccountDlgDivInner").prepend( data );  // $("#content", data).html() ); - messes things up
                
               // add the endless scroll function
               addEndlessScroll("general/ajax_acct_lookup_next", showStatusCol, "lookupAccountDlgDiv", "lookupAccountDlgDivInner");
                               
               // get the first chunk of data
               sortItems( 25 ); // <%=SortConstants.SORT_BY_ACCOUNT_NAME%> );
                
               $("#AccountItemTable #searchText").focus();
               
           },
           
           "html"
       );    
	
	


    // And then display the dialog
       
    createLookupDlg( "Account", descOfSearch );

    if ( showNewButton ) 
    {
        $("#lookupAccountDlgDiv").dialog( "option", "buttons", 
            {
            'New Account': function() 
                {
                    openNewAccountEditor(idFieldId, nameFieldId, contactIdFieldIds, contactNameFieldIds, 
                           roles, showNewButton, descOfSearch,
                           accountToIgnore, extraChar);
                }
            });
    }  else { 
    	$("#lookupAccountDlgDiv").dialog( "option", "buttons", 
                {
                'New Account': function() 
                    {
                        openNewAccountEditor(idFieldId, nameFieldId, contactIdFieldIds, contactNameFieldIds, 
                               roles, showNewButton, descOfSearch,
                               accountToIgnore, extraChar);
                    }
                });


    	var buttons =  $("#lookupAccountDlgDiv").parent().find("button");

    	for ( var i = 0; i < buttons.length; ++i )
    	  {
    	     var jButton = $( buttons[i] );
    	     if ( jButton.text() == 'New Account' )
    	     {
    	        
    	        jButton.attr('disabled', 'disabled' );
    	        jButton.addClass( 'ui-state-disabled' );
    	     }
    	  }
 
    }
  
}  


function openNewAccountEditor(idFieldId, nameFieldId, contactIdFieldIds, contactNameFieldIds, 
                           roles, showNewButton, descOfSearch,
                           accountToIgnore, extraChar)
{

    // remove in case close was used and did not remove it (it doesn't - but the buttons do).

    $("#newAcctDlgDiv").remove();
    $("body").prepend( '<div id="newAcctDlgDiv" width="600px"></div>' );
    
    // customize the color of the title bar
    $("#newAcctDlgDiv").prepend(
      '<style type="text/css">'
      + '    .ui-dialog .ui-dialog-titlebar { border-color: #5884b9; background: #5884b9; }'
      + '    .ui-dialog .ui-dialog-buttonpane { text-align: left; border-width: 1px 0 0 0; background-image: none; margin: .5em 0 0 0; padding: .3em 1em .3em .4em; }'
      + '    .ui-dialog .ui-dialog-buttonpane button {  margin: .5em .4em .5em 0; cursor: pointer; padding: 0em .1em 0em .1em; line-height: 1.4em; width:auto; overflow:visible; }'
    + '</style>' );    
    
    // Now make an ajax call to get the contents for this thing.
    var url =  "/market?page=general/quick_create_account";
    $("html").addClass( "busy" );
    
      var fullUrl = url + "&roles=" + roles; 

      $.post(
           
           fullUrl,
           
           {
               link : "/market?page=" + "general/quick_create_account"
           },
           
           
           function(data) 
           { 
               
               $("html").removeClass( "busy" );

               $("#newAcctDlgDiv").prepend( data );
                                   
               $("#newAcctDlgDiv #account_name").focus();        

           },
           
           "html"
       ); 
      

    $("#newAcctDlgDiv").dialog({
        bgiframe: true, 
        autoOpen: false, 
        height: 450, 
        width: 600,
        modal: true,
        resizable: true,
        show: 'fade',
        title: "Create New Account",
        buttons: {
            Save: function() 
                {
                    if ( validateAccount(idFieldId, nameFieldId, contactIdFieldIds, contactNameFieldIds, 
                           roles, showNewButton, descOfSearch,
                           accountToIgnore, extraChar) )
                    {
                        $("#newAcctDlgDiv").dialog('close');
                        $("#newAcctDlgDiv").dialog('destroy');
                        $("#newAcctDlgDiv").remove();
                    }
                },
            Cancel: function() 
                {
                    $("#newAcctDlgDiv").dialog('close');
                    $("#newAcctDlgDiv").dialog('destroy');
                    $("#newAcctDlgDiv").remove();                    
                }
            }

    });
    
    $("#newAcctDlgDiv").dialog('open');    
           
}

function validateAccount(idFieldId, nameFieldId, contactIdFieldIds, contactNameFieldIds, 
                           roles, showNewButton, descOfSearch,
                           accountToIgnore, extraChar)
{
    

    var brk = document.getElementById( "account_broker" );
    var mlr = document.getElementById( "account_mailer" );
    var mgr = document.getElementById( "account_manager" );
    var sb = document.getElementById( "account_bureau" );
    var own = document.getElementById( "account_list_owner" );

    var accountName = document.getElementById( "account_name" );
    
    if ( trim(accountName.value) == "" )
    {
        nmAlert( "Please enter an account name.", "account_name" );
        return false;
    }
    else if ( !brk.checked && ! mgr.checked && ! mlr.checked && !own.checked && !sb.checked  )
    {
        nmAlert( "Please select at least one role." );
        return false;
    } 
    else
    {
    	// update hidden state and country field if corresponding input fields are cleared
    	var billStateInput = document.getElementById('billStateInput');
    	if(billStateInput != null && trim(billStateInput.value) == '') {
    		document.getElementById('account_bill_state').value = '';
    	}
    	var billCountryInput = document.getElementById('billCountryInput');
    	if(billCountryInput != null && trim(billCountryInput.value) == '') {
    		document.getElementById('account_bill_country').value = '';
    	}
    	var shipStateInput = document.getElementById('shipStateInput');
    	if(shipStateInput != null && trim(shipStateInput.value) == '') {
    		document.getElementById('account_ship_state').value = '';
    	}
    	var shipCountryInput = document.getElementById('shipCountryInput');
    	if(shipCountryInput != null && trim(shipCountryInput.value) == '') {
    		document.getElementById('account_ship_country').value = '';
    	}
    	
                
        // get the account name they just created, before it goes away
        // var lookupVal = $("#account_name" ).val();        
    
        // now do an ajax submit, and put the results in the "window"
        var url =  "/market?page=general/acct_lookup";
        $("html").addClass( "busy" );
    
        var fullUrl = url;  
          
        $.post(
               
               fullUrl,
    
               $("#accountEditForm").serializeArray(),
              
               function(data) 
               { 
                   
                   sortDir = 0;               
                   sortItems( 25 );
    
                    // we just want to get the new account into the search results. 
                    // put the new search string into the field, to trick openAccount Lookup into doing the new search.
                   // $("#" + nameFieldId).val(lookupVal);
                
                   // openAccountLookup(idFieldId, nameFieldId, contactIdFieldIds, contactNameFieldIds, 
                   //            roles, showNewButton, descOfSearch,
                   //            accountToIgnore, extraChar);
                   
               
           },
           
           "html"
       ); 

    
      return true;
    }
    
}


function getAccountLookupKey(myfield, e, 
                             idFieldId, nameFieldId, contactIdFieldIds, contactNameFieldIds, 
                             roles, showNewButton, descOfSearch,
                             accountToIgnore, orgId)
{
    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, orgId, '*');
       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 showStatusCol = "yes";  // ??
    
    // set params for this lookup
    itemTableName = "ContactMemberItemTable";
    defaultSortColumn = 73; 
    sortDir = 0;
    sortRecent = 73;

    searchLookupUrl = "/market?page=general/contact_member_lookup"
            + "&idFieldId=" + idFieldId
            + "&nameFieldId=" + nameFieldId 
            + "&typeCodeFieldId=" + typeCodeFieldId
            + "&descOfSearch=" + descOfSearch;
    sortLookupUrl = "/market?page=general/ajax_contact_member_lookup_next"
           + "&toDo=sort"
           + "&showStatusCol=" + showStatusCol
           + "&typeCodeFieldId=" + typeCodeFieldId
           + "&nameFieldId=" + nameFieldId
           + "&idFieldId=" + idFieldId;
    
     openerIdFieldId = idFieldId;
     openerNameFieldId = nameFieldId;
     openerTypeCodeFieldId = typeCodeFieldId;    
    
    var lookupVal = $("#" + nameFieldId ).val();
    if ( extraChar != null && extraChar != '' )
      lookupVal += extraChar;
       
    
    addLookupDiv( "ContactMember" );
	    
    // Now make an ajax call to get the contents for this thing.
    var url =  "/market?page=general/contact_member_lookup";
    $("html").addClass( "busy" );

      var fullUrl = url
            + "&searchText=" + lookupVal 
            + "&nameFieldId=" + nameFieldId 
            + "&idFieldId=" + idFieldId
            + "&typeCodeFieldId=" + typeCodeFieldId
            + "&descOfSearch=" + descOfSearch;

      $.post(
           
           fullUrl,
           
           {
           },
           
           
           function(data)  
           { 
               // alert( data );
               
               var itemSize = Number( $("#item_count", data).html() );
               
               // alert( itemSize );
               $("html").removeClass( "busy" );

               // what we got back is the empty table and all the js methods 
               $("#lookupContactMemberDlgDivInner").prepend( data );  // $("#content", data).html() ); - messes things up
                
               // add the endless scroll function
               addEndlessScroll("general/ajax_contact_member_lookup_next", showStatusCol, "lookupContactMemberDlgDiv", "lookupContactMemberDlgDivInner");
                               
               // get the first chunk of data
               sortItems( 73 ); 
                
               $("#ContactMemberItemTable #searchText").focus();
               
           },
           
           "html"
       );    

    createLookupDlg( "ContactMember", descOfSearch ); 
                     
}

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 - comm plan select field
// itemFieldId - related item - a list or an account
// itemType - list or acct
//
function openSalesPersonLookup(idFieldId, nameFieldId, showStatus, descOfSearch, extraChar ) 
{  
       
  
  var showStatusCol = "yes";  // ??  
  
      // set params for this lookup
    itemTableName = "SalesPersonItemTable";
    defaultSortColumn = 75;
    sortDir = 0;
    sortRecent = 75;
    
    searchLookupUrl = "/market?page=general/sales_person_lookup"
            + "&idFieldId=" + idFieldId
            + "&nameFieldId=" + nameFieldId 
            + "&descOfSearch=" + descOfSearch;
    sortLookupUrl = "/market?page=general/ajax_salesperson_lookup_next"
           + "&toDo=sort"
           + "&showStatusCol=" + showStatusCol
           + "&nameFieldId=" + nameFieldId
           + "&idFieldId=" + idFieldId;
    
    openerIdFieldId = idFieldId;
    openerNameFieldId = nameFieldId;    

  
    var lookupVal = $("#" + nameFieldId ).val();
    if ( extraChar != null && extraChar != '' )
      lookupVal += extraChar;
   
     var showStatusCol = "yes";  // ??     
    
    addLookupDiv( "SalesPerson" );
	
    // Now make an ajax call to get the contents for this thing.
    var url =  "/market?page=general/sales_person_lookup";
    $("html").addClass( "busy" );
    
      var fullUrl = url
            + "&searchText=" + lookupVal 
            + "&nameFieldId=" + nameFieldId 
            + "&idFieldId=" + idFieldId
            + "&statusToShow=" + showStatus
            + "&descOfSearch=" + descOfSearch;

      $.post(
           
           fullUrl,
           
           {
           },
           
           
           function(data)  
           { 
               
               var itemSize = Number( $("#item_count", data).html() );
               
               // alert( itemSize );
               $("html").removeClass( "busy" );

               // what we got back is the empty table and all the js methods 
               $("#lookupSalesPersonDlgDivInner").prepend( data );  // $("#content", data).html() ); - messes things up
                
               // add the endless scroll function
               addEndlessScroll("general/ajax_salesperson_lookup_next", showStatusCol, itemSize, "lookupSalesPersonDlgDiv", "lookupSalesPersonDlgDivInner");
                               
               // get the first chunk of data
               sortItems( 75 ); // <%=SortConstants.SORT_BY_ACCOUNT_NAME%> );
                
               $("#SalesPersonItemTable #searchText").focus();
               
           },
           
           "html"
       );    

    createLookupDlg( "SalesPerson", descOfSearch );
                                        
}

function getSalesPersonLookupKey(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
    {
       openSalesPersonLookup(idFieldId, nameFieldId, showStatus, 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 ) 
{  

    // set params for this lookup
    itemTableName = "OrderItemTable";
    defaultSortColumn = 7;
    sortDir = 0;
    sortRecent = 7;
    
    searchLookupUrl = "/market?page=general/order_lookup"
            + "&idFieldId=" + idFieldId
            + "&nameFieldId=" + nameFieldId 
            + "&descOfSearch=" + descOfSearch;
    sortLookupUrl = "/market?page=general/ajax_order_lookup_next"
           + "&toDo=sort"
           + "&nameFieldId=" + nameFieldId
           + "&idFieldId=" + idFieldId;
    
    openerIdFieldId = idFieldId;
    openerNameFieldId = nameFieldId;    
    
    
    var lookupVal = $("#" + nameFieldId ).val();
    if ( extraChar != null && extraChar != '' )
      lookupVal += extraChar;
   
     var showStatusCol = "yes";  // ??     
    
    addLookupDiv( "Order" );
	
    // Now make an ajax call to get the contents for this thing.
    var url =  "/market?page=general/order_lookup";
    $("html").addClass( "busy" );
    
      var fullUrl = url
            + "&orderNum=" + lookupVal 
            + "&nameFieldId=" + nameFieldId 
            + "&idFieldId=" + idFieldId
            + "&descOfSearch=" + descOfSearch;

      $.post(
           
           fullUrl,
           
           {
           },
           
           
           function(data)  
           { 
               
               // alert( data );
               var itemSize = Number( $("#item_count", data).html() );
               
               // alert( itemSize );
               $("html").removeClass( "busy" );

               // what we got back is the empty table and all the js methods 
               $("#lookupOrderDlgDivInner").prepend( data );  // $("#content", data).html() ); - messes things up
                
               // add the endless scroll function
               addEndlessScroll("general/ajax_order_lookup_next", showStatusCol, "lookupOrderDlgDiv", "lookupOrderDlgDivInner");
                               
               // get the first chunk of data
               sortItems( 7 ); 
                
               $("#OrderItemTable #searchText").focus();
               
           },
           
           "html"
       );    


      createLookupDlg( "Order", descOfSearch );  

}

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 ) 
{
    
      // 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("");          
      }

}

var outOfData = false;

// For lookup diaologs - adds endless scroll
function addEndlessScroll(deliveringPage, showStatusCol, containerDiv, contentDiv, otherUrlParams)
{
    
    var last_item;
    if ( containerDiv == "lookupConDlgDiv" )
       last_item = "table#ContactItemTable tr:last";
    else if ( containerDiv == "lookupMemberDlgDiv" )
       last_item = "table#MemberItemTable tr:last";
    else if ( containerDiv == "lookupContactMemberDlgDiv" )
       last_item = "table#ContactMemberItemTable tr:last";
    else if ( containerDiv == "lookupAccountDlgDiv" )
       last_item = "table#AccountItemTable tr:last";
    else if ( containerDiv == "lookupOrderDlgDiv" )
       last_item = "table#OrderItemTable tr:last";
    else if ( containerDiv == "lookupListDlgDiv" )
       last_item = "table#ListItemTable tr:last";
    else if ( containerDiv == "lookupDirectoryDlgDiv" )
        last_item = "table#OrgItemTable tr:last";
    else if ( containerDiv == "lookupDirectoryContactDlgDiv" )
        last_item = "table#DirectoryContactItemTable tr:last";
    
    var junk = '<tr><td colspan="10">xxx</td></tr>'
             + '<tr><td colspan="10">xxx</td></tr>'
             + '<tr><td colspan="10">xxx</td></tr>';
   
    outOfData = false;
   
    $(document).endlessScroll(
    {
      // Here is what fireOnce and fireDelay mean:
      // fireDelay has no effect if fireOnce is false.  
      // If fireonce is true, then fireDelay is the time (in millisecs) until the event
      // can fire again.  If 0, it is like fireOnce is false.  
      scrollableContainer: $("#" + containerDiv),    // $("#lookupDlgDiv"),
      scrollableContent: $("#" + contentDiv),   // $("#lookupDlgDivInner"),
      fireOnce: true,
      fireDelay: 0,  //150,
      loader: "<div class=\"loading\"><div>",
      insertAfter: last_item,
      bottomPixels: 50,
      data: junk,
      ceaseFire: function()
      {
          return outOfData; 
      },
      callback: function(fireSeq)
      {
          //alert( "in callback " + fireSeq );
          // if ( lastItemShown < itemsSize ) - don't bother checking - that way we do not need it
          // so we do not have to re-init this every time the list changes
          {   
            
            var url =  "/market?page=" + deliveringPage;
            if ( otherUrlParams != null )
                url += otherUrlParams;
            $("html").addClass( "busy" );
            
            lastItemShown += 3;            
            
            $.post(
               url + "&lastshown=" + (lastItemShown-1)
                   + "&toDo=getnext"
                   + "&showStatusCol=" + showStatusCol,
               {
                   link : "/market?page=" + deliveringPage,
                   action : "getnext"
               },
               
               function(data) 
               { 
                   if ( $.trim(data).length == 0 )
                       outOfData = true;
                   
                   //  alert( data );
                   $("html").removeClass( "busy" );
                   
                   var rowsGotten = 0;
   
                   // insert the data at end of table
                   if ( ! outOfData )
                       $(last_item).after(data);
                    
                   // remove the dummy rows we added (in jquery.endlessscroll.js).
                   $("tr#endless_scroll_data_" + fireSeq).remove();
                   
               },
               
               "html"
           );
          
          }         
          
      }
      
    }
    );
    
    
}

// for lookup dialogs - sorts the items
function sortItems( sortee )
{    
    if ( sortee != sortRecent )
    {
        sortRecent = sortee;
        sortDir = 0;  // ascending
    }
    
    // empty the table   
    $("#" + itemTableName + " TR.evenRow").remove();    
    $("#" + itemTableName + " TR.oddRow").remove();    
    // need to account for all HTML5 possibilities
    $("#" + itemTableName + " TR.evenrow").remove();    
    $("#" + itemTableName + " TR.oddrow").remove();    
    $("#" + itemTableName + " tr.evenRow").remove();    
    $("#" + itemTableName + " tr.oddRow").remove();    
    $("#" + itemTableName + " tr.evenrow").remove();    
    $("#" + itemTableName + " tr.oddrow").remove();    

    // img ids are Up_<sortee> and Down_<sortee>
    hideArrows();
    if ( sortDir == 0 )
        $("IMG#Up_" + sortee).css("display","inline");
    else
        $("IMG#Down_" + sortee).css("display","inline");        
    
    lastItemShown = 0;
 
    $("html").addClass( "busy" );
        
      $.post(
           
           sortLookupUrl,
           
           {
               sortBy: sortee,
               lastshown: lastItemShown,
               sortDir: sortDir
           },
             
           function(data) 
           { 
               // alert( "XXX" + data + "XXX" );
               $("html").removeClass( "busy" );
    
                var toReturn = $.trim(data);      
                
                if ( toReturn != "" )
                {
                    var last_item = $("table#" + itemTableName + " tr:last");
                    last_item.after(toReturn);
                
                    lastItemShown += 25; // <%= LOOKUP_INITIAL_RESULT_LENGTH %>;
               
                    sortDir = (sortDir + 1) % 2;
                }
           },
           
           "html"
       );    
      
}

// for lookup dialogs - adds the lookup dialog div
function addLookupDiv( lookupType )
{
    
    var divId = "lookup" + lookupType + "DlgDiv";
    var innerDivId = "lookup" + lookupType + "DlgDivInner";
    
    $("#" + divId).remove();
    $("body").prepend( '<div id="' + divId + '" width="600px"></div>' );
    
    // customize the color of the title bar, and make buttons with less padding
    $("#" + divId).prepend(
      '<style type="text/css">'
      + '    .ui-dialog .ui-dialog-titlebar { border-color: #5884b9; background: #5884b9; }'
      + '    .ui-dialog .ui-dialog-buttonpane { text-align: left; border-width: 1px 0 0 0; background-image: none; margin: .5em 0 0 0; padding: .3em 1em .3em .4em; }'
      + '    .ui-dialog .ui-dialog-buttonpane button {  margin: .5em .4em .5em 0; cursor: pointer; padding: 0em .1em 0em .1em; line-height: 1.4em; width:auto; overflow:visible; }'
    + '</style>' );    
    
    
    $("#" + divId).append( '<div id="' + innerDivId + '" width="100%"></div>' ); 
    
}

// for lookup dialogs - creates the dialog
function createLookupDlg( lookupType, descOfSearch )
{
    var divId = "lookup" + lookupType + "DlgDiv";
    var innerDivId = "lookup" + lookupType + "DlgDivInner";
    
    $("#" + divId).dialog({
    bgiframe: true, 
    autoOpen: false, 
    height: 450, 
    width: 600,
    modal: true,
    resizable: false,
    show: 'fade',
    title: "Lookup " + descOfSearch

    });
        
    $("#" + divId).dialog('open');    
    
}

// for lookup dialogs - hide of the sort direction arrows
function hideArrows()
{
   $("IMG[ludlgarrow=yes]").css("display","none");
}

// for lookup dialogs - the search function 
function getSearchedDataKey(myfield,e, doWhat)
{
    var keycode;
    if (window.event) 
        keycode = window.event.keyCode;
    else if (e) 
        keycode = e.which;
    else return true;
    
    if (keycode == 13)
    {
       getSearchedData(doWhat);
       return false;  // so form won't be submitted
    }
    else
       return true;
}

// for lookups - search function
function getSearchedData(doWhat)
{
    
    // a little special stuff for list lookup
    if ( itemTableName == "ListItemTable" 
     && ( $("#" + itemTableName + " #searchText").val() == "" 
       ||  trim($("#" + itemTableName + " #searchText").val()) == "*" ) )
    {
        nmAlert( "Please limit your search by entering a keyword in the Name field", "searchText" );
    }    
    else
    {
    // alert( "ch1" );
    // pull searchText, status from their fields - we include anything needed by any
    // of the lookup widgets (account, status, searchText, etc.).
    
    var lookupVal = $("#" + itemTableName + " #searchText").val();
    var stat = $("#" + itemTableName + " #statusChoice").val();
    var acct = $("#" + itemTableName + " #accountName").val();    
    var acctId = $("#" + itemTableName + " #accountId").val();    
    var source = $("#" + itemTableName + " #sourceChoice").val();    
    var orderNum = $("#" + itemTableName + " #orderNum").val();
    var address = $("#" + itemTableName + " #address").val();	// directory_org_lookup.jsp
    var company = $("#" + itemTableName + " #company").val();	// directory_member_lookup.jsp
    var email = $("#" + itemTableName + " #email").val();	// directory_member_lookup.jsp, contact_lookup
    // alert( lookupVal + " - " + email );   
    
    lastItemShown = 0;
        
    $("html").addClass( "busy" );    
    
    // Now make an ajax call to get the contents for this thing.    
      var fullUrl = searchLookupUrl;
    
            // alert( "url: " + fullUrl );    

      $.post(
           
           fullUrl,
           
           {
               statusChoice: stat,
               searchText: lookupVal,
               accountName: acct,
               accountId: acctId,
               sourceChoice: source,
               orderNum: orderNum,
               address: address,
               company: company,
               email: email
           },
           
           
           function(data) 
           { 
               // alert( data );
               $("html").removeClass( "busy" );
                
               // get the first chunk of data
               sortDir = 0;               
               sortItems( defaultSortColumn );
                
           },
           
           "html"
       ); 
       
    }

}


// for lookups - this is called when an item is selected from lookup dialog
// itemType - String indicating Contact, Account, List, etc
// itemId - id of the item selected
// itemName - name of the item selected
// itemTypeCode - type of the item selected (not always applicable - e.g. member or contact
// relatedId - id of related item (account if itemType is Contact)
// relatedName - name of related item
function selectItem(itemType, itemId, itemName, itemTypeCode, relatedId, relatedName) 
{
  // alert( "<selectItem> : " + itemId + ", " + itemName + ", " + relatedId + ", " + relatedName );

  $("#" + openerIdFieldId).val(itemId);
 
  while(itemName.indexOf('-----') >= 0) {
  	itemName = itemName.replace("-----","\"");
  }
  while(itemName.indexOf('+++++') >= 0) {
  	itemName = itemName.replace("+++++","\'");
  }

  $("#" + openerNameFieldId).val(itemName);   
  
  // some items have a type code
  if ( itemTypeCode != null && itemTypeCode != '' ) 
      $("#" + openerTypeCodeFieldId).val(itemTypeCode);   


  // if there is an related field tied to the field.
  // This is the only bit of special handling we provide - it is not recommended.  
  // Instead, get things you need using ajax_item_retriever.jsp, and load them when
  // field is changed.
  if ( relatedId != null && relatedId != '' && openerRelatedIdFieldId != "" )
  {

      $("#" + openerRelatedIdFieldId).val(relatedId);  

      if ( relatedName != null )
      {
          while(relatedName.indexOf('-----') >= 0) 
          {
            relatedName = relatedName.replace("-----","\"");
          }
          while(relatedName.indexOf('+++++') >= 0) 
          {
            relatedName = relatedName.replace("+++++","\'");
          }
          
          // there may or may not be an related name field also
          if ( openerRelatedNameFieldId != "" ) 
          {
    
                var origValue = $("#" + openerRelatedNameFieldId).val();
                  
                $("#" + openerRelatedNameFieldId).val(relatedName);         
         
                if ( origValue == "" ) // if it got filled in by us
                    showRelated( $("#" + openerNameFieldId), $("#" + openerRelatedNameFieldId) );
                
          }          
      }          

  }  
  
  
  // Fire a change event on the ID field, so the lookup calling page can refresh itself or whatever it wants to
  // do on change.  Note that this: window.opener.jQuery("#<%=openerIdFieldId%>").change();  does not
  // work.  Apparently a security thing - unable to fire the event across windows?  So we call the openers change
  // method, if it has one.  (Now that lookup is in same window as caller, we don't need to do it this way, but it still works).
  changeMyElement(jQuery("#" + openerIdFieldId));  

  $("#lookup" + itemType + "DlgDiv").dialog('close');
  $("#lookup" + itemType + "DlgDiv").dialog('destroy');
  $("#lookup" + itemType + "DlgDiv").remove();  
  
  // restore the focus
  $("#" + openerNameFieldId).focus();

}




// 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,
                minChars : (url.indexOf("acct_lookup") > 0) ? 3 : 1,
                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 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 );
            }
    });    
    
    
}


// 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 );
                       }
                   );
    }
}

var autocompleteClicked = false;
function autocompleteClick() {
	autocompleteClicked = true;
	log("global.js: autocompleteClick(): autocompleteClicked="+autocompleteClicked);
}

function log(msg){
	  if (window.console && console.log) {
	    console.log(msg); //for firebug
	  }
}

