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