function formatcurrency(amount)
{
	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	return "$" + s;
}

function getElement(element) {
	if (document.getElementById) {
		return document.getElementById(element);
	}	
	else if (document.all) {
		return document.all(element);
	}
	else if (document.layers){
		return document.layers[element];
	}
	else {
		return null;
	}
}

function getDocElement(doc, element) {
	if (doc.getElementById) {
		return doc.getElementById(element);
	}	
	else if (doc.all) {
		return doc.all(element);
	}
	else if (doc.layers){
		return doc.layers[element];
	}
	else {
		return null;
	}
}

function setSpanText(id, text) {
	var spanObj = getElement(id);
	spanObj.innerHTML = text;
}

function changeCountry(akey, aval, theform, prefix) {
	var elname = "document." + theform.name + "." + prefix + "state";
	var selobj = eval(elname);

	for(j=selobj.length; j >= 0; j--) {
		selobj.options[j] = null;
	}

	selobj.options.length = 0;
	for(i=0; i < akey.length; i++) {
		selobj.options[i] = new Option( aval[i], akey[i] );
	}
}

function borderit(which,color){
	//if IE 4+ or NS 6+
	if (document.all||document.getElementById){
		which.style.borderColor=color;
	}
}

function cvv2info() {
	msg =       "If you are using a Visa or MasterCard, please provide the 3-digit CVV\n";
	msg = msg + "(Customer Verification Value). This is the number printed on\n";
	msg = msg + "the signature area on the back of the card following the Visa\n"; 
	msg = msg + "or MC card account number.\n\n";
	
	msg = msg + "If your credit card is an American Express card please provide the\n";
	msg = msg + "4-digit CID (Confidential Identifier Number). This is the 4 digit number\n";
	msg = msg + "printed above your account number on the front of your card.\n";

	alert(msg);
}

/////////////////////////////////////////////////////////////////////////////////////////////////////
// SEARCH FORM FUNCTIONS
//search bar rollovers, select and submit
	var which = "PartNumber"; //set default search method to "keyword"
	function rolloverCap( oSender ){
		
		which = oSender.name; //set which search method to use; used with image swap and form submission
		
		document.formsearch.searchtype.value = ( which == "PartNumber" )? "sku" : "keyword" ;
		
		switch(which){
			
				case "KeyWord": document.getElementById("PartNumber").src = "images/partnumber_notselected.gif";
								document.getElementById("KeyWord").src = "images/keyword_selected.gif";
					break;
				case "PartNumber": document.getElementById("PartNumber").src = "images/partnumber_selected.gif";
								   document.getElementById("KeyWord").src = "images/keyword_notselected.gif";
					break;
				
			}
			
		
		
	}

//submits the form, passing the old parameters from the new layout
	function doSearch( sKeywords, sHidden){
		
		if( document.formsearch[sKeywords].value == "" ){ return false; } //running empty searches are bad
		else{
			
			var sKeywords = document.formsearch[sKeywords].value;
			var sHidden = document.formsearch[sHidden].value;
			var QueryString = "";
			switch(which){
				case "KeyWord": QueryString = "?keysearch=1&search="+sKeywords+"&searchtype=keyword";
					break;
				case "PartNumber": QueryString = "?psearch=1&search="+sKeywords+"&searchtype=SKU";
					break;
				
			}
			
			window.location = "results.php"+QueryString;
			
		}
		
		return false;
		
	}
	
	
	
/////////////////////////////////////////////////////////////////////////////////////////////////////
// FORM FUNCTIONS
	
	function trim ( s ) { //trim leading and trailing spaces?
		//return rtrim(ltrim(s));
		s = s.replace( /^\s*/, "" );
		s = s.replace( /\s*$/, "" );
		return s;
	}
	
	function moreInfoPopup() {
		
		switch( document.catalog.referer.selectedIndex ){
			case 1:
			case 2:
			case 3:
			case 6: document.getElementById('tr_referer').style.visibility = 'visible';
				break;
			default: document.getElementById('tr_referer').style.visibility = 'hidden';

		}
	   
	}
	
	function checkMail( sEmail ){
		var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		if( filter.test( sEmail ) ){ return false; }else{ return true; }
	}
	
	function newsletterMail( sEmail ){
		if( checkMail( sEmail ) ){ 
			alert('Please enter a valid email address'); 
			document.newsletter['newsletterEmail'].select();
			return false;
		}
	}
	
	function checkform(tf) {
		company = trim(tf.company.value);
		fname = trim(tf.fname.value);
		lname = trim(tf.lname.value);
		address1 = trim(tf.address1.value);
		city = trim(tf.city.value);
		state = trim(tf.state.value);
		zip = trim(tf.zip.value);
		phone = trim(tf.phone.value);
		email = trim(tf.email.value);
	
		formok = true;
		var msg = "The following fields are required:\n";
		if(company == "") {
			msg = msg + "Company\n";
			formok = false;
		}
		if(fname == "") {
			msg = msg + "First Name\n";
			formok = false;
		}
		if(lname == "") {
			msg = msg + "Last Name\n";
			formok = false;
		}
		if(address1 == "") {
			msg = msg + "Address\n";
			formok = false;
		}
		if(city == "") {
			msg = msg + "City\n";
			formok = false;
		}
		if(state == "") {
			msg = msg + "State\n";
			formok = false;
		}
		if(zip == "") {
			msg = msg + "Zip Code\n";
			formok = false;
		}
		if(phone == "") {
			msg = msg + "Phone\n";
			formok = false;
		}
		if( checkMail(email) ) {
			msg = msg + "Email\n";
			formok = false;
		}
			
		if(formok) {
			return true;
		} else {
			alert(msg);
			return false;
		}
	}
	
	
// CHECKOUT 

	function getPaymentType( sValue ){
		
		document.getElementById("payinfo").value = sValue;
		//alert(document.getElementById("payinfo").value);
		
		switch( sValue ){
			case "po":
					document.getElementById("ccinfo").style.display = 'none';
					document.getElementById("poinfo").style.display = 'block';
				break;
			case "creditcard":
					document.getElementById("ccinfo").style.display = 'block';
					document.getElementById("poinfo").style.display = 'none';
				break;
			
		}
		
	}
	
	
/// CHECK INQUIRY

	function checkInquiry( oForm, isFriend ){
		
		var msg = "The following fields are required:\n";
		var formok = true;
		
		if( oForm['name'].value == "") {
			msg = msg + "Name\n";
			formok = false;
		}
		if( checkMail( oForm['email'].value ) ){
			msg = msg + "Email\n";
			formok = false;
		}
		if(isFriend == 1){
			if( checkMail( oForm['friend'].value ) ){
				msg = msg + "To Address\n";
				formok = false;
			}
		}
		if( oForm['subject'].value == "") {
			msg = msg + "Subject\n";
			formok = false;
		}
		if( oForm['message'].value == "") {
			msg = msg + "Massage\n";
			formok = false;
		}
				
		if(formok) {
			return true;
		} else {
			alert(msg);
			return false;
		}

	}
	

			

// FAVORITES //////////////////////////////////////////////////////////
	function checkAll( oForm ){
		
		var isChecked = ( oForm['MainCheck'].checked )? true : false ;
		
		for( i = 0; i < oForm.length; i++ ){
			
			if( oForm[i].type == "checkbox" ){
				oForm[i].checked = isChecked;
			}
			
		}
		
	}
	
	// grabs checked items from FAVORITES for use with email or cart
	function doFavorites( oForm ){
		
		var sItems = "";
		var j=0;
		for( i = 0; i < oForm.length; i++ ){ //find the SELECT input in the form
			
			if( ( oForm[i].type == "checkbox" && oForm[i].name != "MainCheck" ) ){
													   
				j++; //increment by row, not element
				
				if( oForm[i].checked ){ //if row is checked, grab the data
				  
					sItems += ( sItems != "" )? ':' : "" ;
					sItems += oForm['item'+j].value;
				
				}
				
			}
			
		}
		
		if( sItems != "" ){
			oForm['transfer'].value = sItems;
			return true;
		}else{
			alert( "Please select at least one item to transfer." );
			return false;
		}
		
	}
	
	//puts the option saved in FAVORITES to display
	function getOption( sOption ){
		
		var oForm = document.itemdetail;
		var FormLength = oForm.length;
		
		for( i = 0; i < FormLength; i++ ){ //find the SELECT input in the form
			
			if( oForm[i].type == "select-one" ){ //now, find the index of the referenced value
				
				for( j = 0; j < oForm[i].length; j++ ){ //search option values for sOption
					
					if( oForm[i].options[j].value.toLowerCase() == sOption.toLowerCase() ){
						oForm[i].selectedIndex = j; //select index
					}
					
				}
				
			}
			
		}
		
	}
	
	
	function doCalc( sLoc, sDest, sSID ){
		
		document.getElementById( 'shippingClone' ).innerHTML ="";
		
		sQuery = 'doShipping.php?sid=' + sSID + '&location=' + sLoc;
		
		loadHTML( sQuery, sDest);
		
	}


	function shippingZip( oObj ){
		
		if(oObj.maxLength == 5 ){ return; }
		
		oObj.value = "";
		oObj.maxLength = 5
		oObj.style.color = '#000';
		
	}
	
	//sets up Shipping Calculator on Cart OnLoad events.
	function shippingList( sSID ){

		loadHTML( 'doShipping.php?sid=' + sSID, 'shippingOutput' );
		
	}
	//sets up Shipping Calculator on Checkout OnLoad events.
	function shippingFinal( sSID ){
		
		loadHTML( 'doShipping.php?sid=' + sSID + '&final=1', 'shippingOutput' );
		
	}
	
	function doNDA( sSID, sMethod, sLocation, final ){
		document.getElementById( 'shippingClone' ).innerHTML ="";
		if( sMethod.charAt(sMethod.length-1) == "S" ){ sMethod = '&method=S'; }
		else if( sMethod == "X" ){ window.location = window.location.pathname; return; }
		else{ sMethod = ''; }
		
		loadHTML( 'doShipping.php?sid=' + sSID + '' + sMethod + '&location=' + sLocation + '&final=' + final, 'shippingOutput' );
	
	}
	
	
	//////////////////////////////////////////////////////////////////////////////////////////
	// SKU LOOKUP
	
	function getSku(){

		//check if fields are blank
		if( document.getElementById( 'sku' ).value == "" || document.getElementById( 'qty' ).value == "" ){ return; }
		else{ //if not, run the process
		
//			var sku = document.getElementById( 'sku' ).value;
//			var qty = document.getElementById( 'qty' ).value;
//			
//			window.cart.location = '../cart.php?action=add&sku=' +sku+ '&qty=' +qty;
			
			document.getElementById( 'sku' ).select();
			
		}
			
	}
	
	//////////////////////////////////////////////////////////////////////////////////////////
	//AJAX crap
		var request;
		var dest;

		var viewcart = new Array();
			viewcart['width'] = "57px";
			
			
		//process state change check
		function processOptionsChange(){

			if (request.readyState == 4){
				
				contentDiv = document.getElementById(dest);
				if (request.status == 200){
					response = request.responseText;
					contentDiv.innerHTML = response;
				} else {
					contentDiv.innerHTML = "Error: Status "+request.status;
				}
				
			}

		}		
		
			//
	function formatNumber( sValue ){

		if( sValue == "" ) return "";
		
		sNewValue = "" + Math.round(sValue*100)/100 + "";
			
		if( sNewValue.indexOf( '.' ) == -1 ){
			sNewValue += ".00";
		}else if( (sNewValue.length - sNewValue.indexOf( '.' ) ) > 1 ){
			sNewValue += "0";
		}
		
		var cents = sNewValue.substring( sNewValue.indexOf( '.' ), sNewValue.indexOf( '.' )+3 );

		var whole = sNewValue.substring( 0, sNewValue.indexOf('.') );
		var i = 0;
		var comma = new Array();
		while( whole.length > 3 ){
			comma[i] = whole.substring( (whole.length - 3), whole.length );
			whole = whole.substring( 0, (whole.length - 3) );
		i++;
		}
		
		whole = ( comma !="" )? whole +',' : whole ;
		
		return "$"+ whole + comma + cents;
					
	}
	

		//process state change check : Shipping AJAX
		function processStateChange(){

			if (request.readyState == 4){
				
				contentDiv = document.getElementById(dest);
				if (request.status == 200){
					response = request.responseText;
					contentDiv.innerHTML = response;
				} else {
					contentDiv.innerHTML = "Error: Status "+request.status;
				}
				
				
				//okay, AJAX may have a flaw where elements placed after the output element cause an "Unknown Runtime Error"
				//		when trying to access elements placed after it in the code. This fix placed the output div after the 
				//		form, then clones its contents to the location where we want it. 
				//
				//
				//		IMPORTANT!!!!!!!!!!
				//		document.getElementById( 'shippingClone' ).innerHTML ="";
				//		The clone element MUST be cleared before it can be written to again
				
				var oOutput = document.getElementById( 'shippingOutput' ).getElementsByTagName( 'INPUT' );
				
				var location = '"' + window.location + '"';
				//alert(location.indexOf( 'checkout' ));
				
					
					//modify desired elements
					var sales_tax = document.getElementById('sales_tax').value;

					document.getElementById( 'shippingNote' ).innerHTML = oOutput.shippingNote.value;
										
					if( oOutput.shippingTotal.value == "" ){
						document.getElementById( 'shippingTotal' ).innerHTML = "";
					}else if( document.getElementById( 'ship_method' ).value == "call" ||  document.getElementById( 'ship_method' ).value == "S" ){
						document.getElementById( 'shippingTotal' ).innerHTML = "<span class='ShipMsg'>Requires Manual Quote</span><input type='hidden' name='shipping' value='S' />" ;
					
					}else{
						document.getElementById( 'shippingTotal' ).innerHTML = formatNumber( parseFloat(oOutput.shippingTotal.value) + parseFloat(sales_tax) );
					
					document.getElementById( 'shippingNoteMsg' ).innerHTML = oOutput.shippingNoteMsg.value;
					}
					
					
					if( oOutput.shippingNoteMsg.value != "" && location.indexOf( 'checkout' ) != -1 ){
						document.getElementById( 'shippingClone' ).style.width = 
							document.getElementById( 'shippingTotal' ).style.width = '100%';
						document.getElementById( 'shippingClone' ).style.textAlign = 
							document.getElementById( 'shippingTotal' ).style.textAlign = 'right';
					}else if( oOutput.shippingNoteMsg.value != "" ){
						document.getElementById( 'shippingClone' ).style.width = 
							document.getElementById( 'shippingTotal' ).style.width = '100%';
						document.getElementById( 'shippingClone' ).style.textAlign = 
							document.getElementById( 'shippingTotal' ).style.textAlign = 'left';
					}else if( location.indexOf( 'checkout' ) == -1 ){
						document.getElementById( 'shippingClone' ).style.width = 
							document.getElementById( 'shippingTotal' ).style.width = '57px';
						document.getElementById( 'shippingClone' ).style.textAlign = 
							document.getElementById( 'shippingTotal' ).style.textAlign = 'right';
					}else if( location.indexOf( 'checkout' ) != -1 ){
						document.getElementById( 'shippingClone' ).style.width = 
							document.getElementById( 'shippingTotal' ).style.width = '100%';
						document.getElementById( 'shippingClone' ).style.textAlign = 
							document.getElementById( 'shippingTotal' ).style.textAlign = 'right';
					}
				
				//Clone the AJAX output into the form
				document.getElementById( 'shippingClone' ).innerHTML = document.getElementById( 'shippingOutput' ).innerHTML;	

			}

		}		
			
		//creates the XMLHttpRequest object 
		function loadHTML( URL, destination ){
			URL += "&Destination=" + destination;
			dest = destination;

			//try{
				if (window.XMLHttpRequest){
					request = new XMLHttpRequest();
					request.onreadystatechange = processStateChange;
					request.open("GET", URL, true);
					request.send(null);
				} else if (window.ActiveXObject) {
					request = new ActiveXObject("Microsoft.XMLHTTP");
					if (request) {
						request.onreadystatechange = processStateChange;
						request.open("GET", URL, true);
						request.send();
					}
				}
									
			//}catch(e){ alert( "Error: Status "+request.status ); return; }
			
		}			
		
		//creates AJAX object for use with SKU LOOKUP get-options-by-keying-sku thingy
		function findOptions( URL, destination, sSku ){
			
			URL = '../' + URL + '?sku=' +sSku;
			dest = destination;
			
			//try{
				if (window.XMLHttpRequest){
					request = new XMLHttpRequest();
					request.onreadystatechange = processOptionsChange;
					request.open("GET", URL, true);
					request.send(null);
				} else if (window.ActiveXObject) {
					request = new ActiveXObject("Microsoft.XMLHTTP");
					if (request) {
						request.onreadystatechange = processOptionsChange;
						request.open("GET", URL, true);
						request.send();
					}
				}
									
			//}catch(e){ alert( "Error: Status "+request.status ); return; }
			
			//loadHTML( '../' + URL + '?sku=' +sSku, destination )
			
		}

	//### addPrice( oSender )
	//##
	//#   parses option select menu to get price to be added to subtotal
	function addPrice( oSender ){
		
		var value = oSender.value;
		document.itemdetail.show_price.value = value;
		
	}














