function valDiv(divId) {
	// FOR SOME REASON, IE DOES NOT HAVE AN INDEXOF FUNCTION FOR ARRAYS... SO HERE IT IS
	if(!Array.indexOf){
	    Array.prototype.indexOf = function(obj){
	        for(var i=0; i<this.length; i++){
	            if(this[i]==obj){
	                return i;
	            }
	        }
	        return -1;
	    }
	}

	var fields = document.getElementById(divId).getElementsByTagName("input")
	var error = new Array()
	var errorCount = 0
	var divsArray = new Array( 5 )
	var isForeign = false;
	divsArray[0] = "account_div"
	divsArray[1] = "address_div"
	// October 14, 2008 WSH // RE-SEPARATED THE ADDRESS AND SHIPPING PANES, MOVING TO A PHP BASED CHECKOUT
	// July 28, 2008 WSH // MERGED ADDRESS AND SHIPPING PANE TOGETHER
	divsArray[2] = "shipping_div"
	divsArray[3] = "payment_div"
	//divsArray[3] = "comments_div"
	
	// alert(fields.length)
	
	// December 13, 2007 WSH // FIRST, MAKE SURE THAT THE ERROR MESSAGE BOX IS HIDDEN
	document.getElementById( 'errorMessages' ).style.left = '-999px';
	
	for(i=0; i < fields.length; i++) {
		
		// BEGIN GENERAL CHECKING ROUTINE
		var field = fields[i]
		
		if(!field.type || field.type == 'image' || field.type == 'hidden') {
			continue;
		}
		
		// alert(field.type)
		
		if(field.className == 'req') {
			// December 10, 2007 WSH // SET THE BORDER TO BLACK FIRST, SO THAT LATER, ONLY THE MESSED UP ONES SHOW UP IN RED
			setStyleById(field.id, 'border', '1px solid black');
		
			if( !( divId == 'account_div' && document.getElementById( "login_type" ).value == "existing" ) ) {		
				if( !( divId == 'address_div' && document.getElementById( "useBilling" ).getAttribute('useBilling') == "true" && field.name.search( "billing_" ) >= 0 ) ) {
					// CHECK VALUE AND LENGTH (OF TEXT FIELDS)
					if(!field.value) {
						//alert('Field ' + field.name + ' is required but it is blank')
						error[errorCount++] = 'Field ' + field.name + ' is required but it is blank'
						setStyleById(field.id, 'border', '1px solid red');
					}
					else if(field.type == 'text' && field.value.length < 2) {
						//alert('Field ' + field.name + ' must be at least two characters')
						error[errorCount++] = 'Field ' + field.name + ' must be at least two characters'
						setStyleById(field.id, 'border', '1px solid red');
					}
				}
			}			
		}
		// END GENERAL CHECKING ROUTINE
		
		
	}
	
	// STEP 1 - ACCOUNT
	if(divId == 'account_div') {
		try {
			// ONLY DO THIS IF CREATING A NEW ACCOUNT
			if( document.getElementById( "login_type" ).value == "new" ) {
				setStyleById("password", 'password', '1px solid black');
				setStyleById(field.id, 'password_confirmation', '1px solid black');
				setStyleById(field.id, 'email_address', '1px solid black');
			
				// CHECK PASSWORD LENGTH
				if(document.getElementById( "password" ).value.length < 5) {
					//alert('Passwords must be 5 characters or more')
					error[errorCount++] = 'Passwords must be 5 characters or more'
					setStyleById("password", 'border', '1px solid red');
				}
						
				// CHECK PASSWORDS MATCH
				if(!passwordCheck(document.getElementById( "password" ).value, document.getElementById( "password_confirmation" ).value)) {
					//alert('Your passwords do not match')
					error[errorCount++] = 'Your passwords do not match'
					setStyleById(field.id, 'password', '1px solid red');
					setStyleById(field.id, 'password_confirmation', '1px solid red');
				}
						
				// CHECK EMAIL ADDRESS
				if(!emailCheck(document.getElementById( "email_address" ).value)) {
					//alert('Email address does not appear to be a valid format.')
					error[errorCount++] = 'Email address does not appear to be a valid format.'
					setStyleById(field.id, 'email_address', '1px solid red');
				}
				
				// CHECK IF ACCOUNT ALREADY EXIST						
				document.getElementById( "checkingAccount" ).value = "not done";
				
				//ajaxRead('checkAccount.php?email=' + document.getElementById( "email_address" ).value, "checkAccount");
				/*while( document.getElementById( "checkingAccount" ).value == "not done" ) {
					;
					//alert( 'checking' );
				}*/
				
				// problem: the value of accountExists gets updated after this runs
				if( document.getElementById( "accountExists" ).value == "true" && document.getElementById( "login_type" ).value == "new" ) {
					document.getElementById( "email_address_login" ).value = document.getElementById( "email_address" ).value;
					
					//alert( 'Account already exist in our system, please log in.' );
				}
			}
			// TRY TO LOGIN IF EXISTING ACCOUNT
			else {			
				// December 10, 2007 WSH // IF EXISTING ACCOUNT SHOULD STILL CHECK FOR PROPER EMAIL ADDRESS
				var field = document.getElementById( "email_address_login" );
				setStyleById(field.id, 'border', '1px solid black');
				setStyleById(document.getElementById( "password_login" ).id, 'border', '1px solid black');
				
				if(!field.value) {				
					error[errorCount++] = 'Email address is required but it is blank'
					setStyleById(field.id, 'border', '1px solid red');
				}				
				
				if(!document.getElementById( "password_login" ).value) {				
					error[errorCount++] = 'Password is required but it is blank'
					setStyleById(document.getElementById( "password_login" ).id, 'border', '1px solid red');
				}
				
				if(!emailCheck(field.value)) {
					//alert('Email address does not appear to be a valid format.')
					error[errorCount++] = 'Email address does not appear to be a valid format.'
					setStyleById(field.id, 'border', '1px solid red');
				}
			
				if( errorCount > 0 ) {	
					// IF THERE'S ERROfR, DO NOTHING AND JUST LETTING THE ERROR HANDLING FURTHER DOWN DO ITS THING
				}
				else {
					document.checkout_payment.submit();
					return;
				}
			}	
		}
		catch(e) {
			;
		}	
	}
	
	// July 28, 2008 WSH // MERGED ADDRESS AND SHIPPING DIV TOGETHER
	// STEP 2 - ADDRESS
	else if( divId == 'address_div' ) {
		//highlightDiv( 'shipping_div' );
		// TODO : EVENTUALLY WE MIGHT DO ADDRESS VALIDATION, POSSIBLY THROUGH THE UPS US ADDRESS VALIDATION TOOL
		//clearShipping();
		
		// August 18, 2008 WSH // APPARENTLY 0 DOES NOT EVALUATE FALSE
		// August 7, 2008 WSH // ADDED CHECK FOR IF USING SHIPPING ADDRESS FOR BILLING. SHOULD FIX PART OF THE BILLING NOT MATCHING SHIPPING SCENARIOS 				
		if( document.getElementById('useBilling').value > 0) {
			document.getElementById('order_billing').value = document.getElementById('order_shipping').value;
			document.getElementById('billing_firstname').value = document.getElementById('shipping_firstname').value;
			document.getElementById('billing_lastname').value = document.getElementById('shipping_lastname').value;
			document.getElementById('billing_company').value = document.getElementById('shipping_company').value;
			document.getElementById('billing_phone').value = document.getElementById('shipping_phone').value;
			document.getElementById('billing_street_address').value = document.getElementById('shipping_street_address').value;
			document.getElementById('billing_street_address2').value = document.getElementById('shipping_street_address2').value;
			document.getElementById('billing_city').value = document.getElementById('shipping_city').value;
			document.getElementById('billing_country_id').value = document.getElementById('shipping_country_id').value;
			document.getElementById('billing_zone_id').value = document.getElementById('shipping_zone_id').value;
			document.getElementById('billing_postcode').value = document.getElementById('shipping_postcode').value;
			// November 18, 2008 WSH // ADDED TAX ID TO THE LIST OF FIELDS TO COPY
			document.getElementById('billing_tax_id').value = document.getElementById('shipping_tax_id').value;					
		}				
	}
	
	// October 14, 2008 WSH // SEPARATED THE ADDRESS AND SHIPPING DIVS AGAIN
	// STEP 3 - SHIPPING METHOD
	else if( divId == 'shipping_div' ) {
		//highlightDiv( 'payment_div' );
		try {

			var radioValue = document.checkout_payment.shippingOptionsRadio; 
			var checkedShipping = false;
			var checkedValue = null;
			// August 6, 2008 WSH // REMOVED THE TRY CATCH IN THE FOR LOOP. IT WAS SOMEHOW CAUSING INFINITE LOOP WHEN NO SHIPPING IS SELECTED
			for( var i = 0; radioValue.length; i++ ) {
				//try {
					if( radioValue[i].checked ) {
						checkedShipping = true;					
						checkedValue = radioValue[i];
						break;
					}
				//}
				//catch( e ) {
				//	alert( e );
				//	i++
				//}
			}
			
			if( !checkedShipping ) {
				error[errorCount++] = "You must select a shipping method.";
			}
			else {
				// February 21, 2008 WSH // ADDED CHECKING FOR PEOPLE CHOOSING THE SLOWEST CRAPPIEST SHIPPING METHOD POSSIBLE
				var shippingMethod = checkedValue.value;
			}
			
			if( shippingMethod.indexOf( 'Weeks' ) >= 0 ) {
				document.getElementById( "slowShippingMsg" ).style.display='';										
				
				return;
			}
			
			// October 20, 2008 WSH // FOREIGN CHECK ISN'T DONE HERE ANYMORE
			// October 3, 2008 WSH // ADDED CODE TO NOT SHOW CREDIT CARD STUFF IF OUTSIDE NORTH AMERICA
			if( !( document.getElementById('billing_country_id').value == 223 || document.getElementById('billing_country_id').value == 38 ) || !( document.getElementById('shipping_country_id').value == 223 || document.getElementById('shipping_country_id').value == 38 ) ) {					
				//isForeign = true;
			}						
		}
		catch (e) {		
			error[errorCount++] = "Please select a shipping rate.";
		}
	}
	
	// STEP 4 - PAYMENT METHOD
	else if( divId == 'payment_div' ) {
		//highlightDiv( 'comments_div' );
		var paymentOption = document.checkout_payment.payment;

		if( paymentOption.value == 'psigate_xml' ) {
			// CHECK THE CREDIT CARD FILEDS
			var ccFields = new Array();
			ccFields[0] = "cc_owner";
			ccFields[1] = "cc_number";			
			ccFields[2] = "cc_cvv";
			
			for( var i = 0; i < ccFields.length; i++ ) {
				if( document.getElementById( "psigate_xml_" + ccFields[i] ).value == "" ) { 
					//alert("psigate_xml_" + ccFields[i]);
					setStyleById("psigate_xml_" + ccFields[i], '1px solid red');
					error[errorCount++] = ccFields[i].replace( "cc_", "Credit Card " ) + " cannot be left blank.";										
				}
			
				// CHECK THAT CC NUMBER IS ONLY NUMBERS
				if( ccFields[i] != "cc_owner" ) {
					if( !isNumeric( document.getElementById( "psigate_xml_" + ccFields[i] ).value ) ) {
					//	setStyleById("psigate_xml_" + ccFields[i], '1px solid red');
					//	error[errorCount++] = ccFields[i].replace( "cc_", "Credit Card " ) + " can only contain numbers.";							
					}
				}	
			}						
			
			// CHECK THE EXPIRY DATE
			var currentTime = new Date();
			//alert(currentTime);
			// YOU HAVE TO SPECIFY THE NUMBER TO BE BASE 10, OR ELSE 8 AND 9 WON'T WORK, BECAUSE IT TRIES TO GUESS THE NUMBER BASE
			var currentMonth = parseInt( currentTime.getMonth(), 10 ) + 1; // FOR SOME REASON, GET MONTH RETURNS MONTHS IN A ZERO-INDEXED FASHION...
			var currentYear = parseInt( currentTime.getFullYear(), 10 );
			
			var cardMonth = parseInt( document.checkout_payment.psigate_xml_cc_expires_month.value, 10 );
			var cardYear = parseInt( document.checkout_payment.psigate_xml_cc_expires_year.value, 10 ) + 2000;
			
			//alert( cardMonth + " _ " + cardYear + "|" + currentMonth + "_" + currentYear + "---------"  + parseInt( document.checkout_payment.psigate_xml_cc_expires_year.value, 10 ) );
			
			if( cardYear > currentYear ) {
				;
			}
			else if( currentYear == cardYear ) {
				if( cardMonth < currentMonth ) {
					error[errorCount++] = "This credit card has already expired.";
				}
			}
			else {				
				error[errorCount++] = "This credit card has already expired.";
			}
			
			// CHECK THAT CVV NUMBER IS ONLY NUMBERS
		}
		else {
			// DO NOTHING
		}
		
		// August 6, 2008 WSH // DO NOT SUBMIT THE FORM IF ERRORS EXIST
		// July 28, 2008 WSH // MERGED THE PAYMENT AND COMMENTS STEPS, SO PAYMENT IS NOW THE LAST STEP IN CHECKOUT PRIOR TO ORDER CONFIRMATION
		//document.checkout_payment.submit();
		//return;
	}
	
	// STEP 5 - COMMENTS
	else if( divId == 'comments_div' ) {
		document.checkout_payment.submit();
	}	
	
	// December 3, 2007 WSH // IF THERE ARE NO ERRORS, THEN SET THE CURRENT DIV TO DONE
	var errorMessages = document.getElementById( 'errorMessages' );
	errorMessages.innerHTML = "";
	
	if( errorCount > 0 ) {				
		//document.getElementById( divId + '_done' ).src='./images/pixel_trans.gif';	
		
		for( var i = 0; i < error.length; i++ ) {
			errorMessages.innerHTML += error[i] + "<br>\n";
		}
		
		errorMessages.innerHTML += "<a href=\"javascript:toggleDiv('errorMessages');\">Close Window</a>\n";
		
		toggleDiv( 'errorMessages', '200px' );
		window.location = '#errorDisplay';
	}
	else if( divId == 'payment_div' ) {
		document.checkout_payment.submit();
	}
	else if( isForeign ) {
		highlightDiv( divsArray[divsArray.indexOf( divId ) + 1], true ); 	
		updateProgressBar(divsArray[divsArray.indexOf( divId ) + 1]);
		window.location = '#progressBar';
		//document.getElementById( "po_visa" ).style.display = "none";				
		//document.getElementById( "po_mastercard" ).style.display = "none";				
		//document.getElementById( "po_amex" ).style.display = "none";	
		//highlightRow( "paymentOptions", "po_po" );		
		//setBox( "po" );
		//toggle( "psigate_xml", "none" );
		//toggleDiv( "foreignPayment", "200px" );

		document.checkout_payment.action = "index.php?page=checkout&step=" + divsArray[divsArray.indexOf( divId ) + 1];
		document.checkout_payment.submit();
	}
	else {
		//highlightDiv( divsArray[divsArray.indexOf( divId ) + 1], true ); 
		//document.getElementById( divId + '_done' ).src='./images_new/done.gif';		
		//updateProgressBar(divsArray[divsArray.indexOf( divId ) + 1]);
		//window.location = '#progressBar';

		// October 14, 2008 WSH // SWITCHED TO PHP POSTS INSTEAD OF JS DIV SWAPS
		// CHANGE THE ACTION AND SUBMIT THE FORM
		document.checkout_payment.action = "index.php?page=checkout&step=" + divsArray[divsArray.indexOf( divId ) + 1];
		document.checkout_payment.submit();
	}	
}

function getRegion() {
	var akhiArray = new Array();
	akhiArray[0] = "AK"; // ALASKA
	akhiArray[1] = "GU"; // GUAM
	akhiArray[2] = "HI"; // HAWAII
	akhiArray[3] = "MH"; // MARSHALL ISLANDS
	akhiArray[4] = "PR"; // PUERTO RICO
	akhiArray[5] = "PW"; // PALAU
	akhiArray[6] = "VI"; // VIRGIN ISLANDS
	
	var country = $("#co_shipping_country_id").val();
	var state = $("#co_shipping_state_us").val();
	var region = "INTL";	

	try { 
		// DEFINITION OF AKHI SHOULD REALLY BE THE 48 STATES WHICH EXCLUDES PR, VIRGIN ISLANDS, ETC				
		if( country == "223" && ( jQuery.inArray( state, akhiArray ) >= 0 ) ) {
			region = "AKHI";
		}	
		else if( country == "223" ) {
			region = "US";
		}
		else if( country == "38" ) {
			region = "CA";
		}
		else {
			region = "INTL";
		}
	}
	catch( e ) {
		region = "INTL";				
	}

	return( region );
}

function getShippingRates( weight, region ) {
	var rates = new Array();
	var rateLookupArray = new Array();
	rateLookupArray[0] = new Array( "US", "CA", "AKHI", "INTL" );
	rateLookupArray[0]['US'] = new Array( "Free Ground Shipping", "QwikShip", "UPS Ground", "UPS 3-Day", "UPS 2-Day", "UPS Overnight", "Use My Own Account" );
	rateLookupArray[0]['CA'] = new Array( "UPS Ground", "UPS 3-Day", "UPS 2-Day", "UPS Overnight", "Use My Own Account" );
	rateLookupArray[0]['AKHI'] = new Array( "UPS Air", "Use My Own Account" );
	rateLookupArray[0]['INTL'] = new Array( "To Be Determined", "Use My Own Account" );
	
	rateLookupArray[0]['US']['Free Ground Shipping'] = new Array( "0.00" );
	rateLookupArray[0]['US']['QwikShip'] = new Array( "14.95" );
	rateLookupArray[0]['US']['UPS Ground'] = new Array( "9.95" );
	rateLookupArray[0]['US']['UPS 3-Day'] = new Array( "22.95" );
	rateLookupArray[0]['US']['UPS 2-Day'] = new Array( "39.95" );
	rateLookupArray[0]['US']['UPS Overnight'] = new Array( "59.95" );
	rateLookupArray[0]['US']['Use My Own Account'] = new Array( "0.00" );

	rateLookupArray[0]['CA']['UPS Ground'] = new Array( "14.95" );
	rateLookupArray[0]['CA']['UPS 3-Day'] = new Array( "19.95" );
	rateLookupArray[0]['CA']['UPS 2-Day'] = new Array( "29.95" );
	rateLookupArray[0]['CA']['UPS Overnight'] = new Array( "79.95" );
	rateLookupArray[0]['CA']['Use My Own Account'] = new Array( "0.00" );
	
	rateLookupArray[0]['AKHI']['UPS Air'] = new Array( "89.95" );
	rateLookupArray[0]['AKHI']['Use My Own Account'] = new Array( "0.00" );
	
	rateLookupArray[0]['INTL']['To Be Determined'] = new Array( "0.00" );
	rateLookupArray[0]['INTL']['Use My Own Account'] = new Array( "0.00" );

	try {		
		while( $('#co_shipping_rates_table').children().size() > 1 ) {
			$('#co_shipping_rates_table').remove('#co_shipping_rates_table tr:last');
		}
		
		$('#co_shipping_rates_table').empty("");
		
		var tempShippingTable = "";
		tempShippingTable = "<table width='100%' cellpadding='0' cellspacing='0' id='co_shipping_rates_table' class='co_shipping_rates_table' >\n";
		
		var rateIndex = 0;
		var hasGround = false;
		
		var hasFirst = false;
		var firstShipName = "";
		var firstShipRate = 0.00;
		
		for( var i = 0; i < rateLookupArray.length; i++ ) {
			for( var k = 0; k < rateLookupArray[i][region].length; k++ ) {
				// IF I LOOP THROUGH THIS, I SHOULD BE ABLE TO GET ALL THE RATES
				//rates[rateIndex][rateLookupArray[i][region]] = rateLookupArray[i][region][k];
				//alert( rateLookupArray[i][region][rateLookupArray[i][region][k]][0] + "<-- bleh2222" );
				var tempShipName = rateLookupArray[i][region][k];
				var tempShipRate = rateLookupArray[i][region][rateLookupArray[i][region][k]][0];								
				
				// December 4, 2008 WSH // EMU // ADDED FLAG TO DETERMINE WHETHER OR NOT TO OFFER FREE SHIPPING AND QWIKSHIP
				if( $('#co_offer_free_shipping').val() != 1 ) {
					if( tempShipName == "Free Ground Shipping" ) {
						continue;
					}
				}
				if( $('#co_offer_qwikship').val() != 1 ) {
					if( tempShipName == "QwikShip" ) {
						continue;
					}
				}
				
				if( !hasGround ) {
					if( tempShipName == "Free Ground Shipping" || tempShipName == "QwikShip" || tempShipName == "UPS Ground" ) {
						hasGround = true;	
					}
				}
				else {
					if( tempShipName == "Free Ground Shipping" || tempShipName == "QwikShip" || tempShipName == "UPS Ground" ) {
						continue;
					}
				}				
				
				if( !hasFirst ) {
					firstShipName = tempShipName;
					firstShipRate = tempShipRate;
					firstIndex = k
					hasFirst = true;
				}
				
				tempShippingTable += "<tr onClick=\"updateShipping( '" + tempShipName + "', " + tempShipRate + ", " + k + ");\">";
				tempShippingTable += "<td id='shipping_" + k + "' class='shipping_rate_labels'>";
				tempShippingTable += tempShipName;
				tempShippingTable += "</td>";
				tempShippingTable += "<td id='shipping_rate_" + k + "' class='shipping_rate_values'>";
				tempShippingTable += "$" + tempShipRate;
				tempShippingTable += "</td>";
				tempShippingTable += "</tr>";
				
				rates[tempShipName] = tempShipRate;
											
			}
			rateIndex++;
		}

		tempShippingTable += "</table>";

		$('#co_shipping_rates').fadeOut( 1000 );
		$('#co_shipping_rates').fadeIn( 1000 );		
		$('#co_shipping_rates').empty();
		
		if( !( ( region == "US" || region == "CA" ) && $('#co_shipping_state_us').val() == 0 ) ) {
			$('#co_shipping_rates').append( jQuery( tempShippingTable ) );
		}
		else {
			firstShipName = "Please select a shipping method.";
			firstShipRate = 0.00
		}
		
		updateShipping( firstShipName, firstShipRate, firstIndex );
	}
	catch( e ) {
		// What to do if rateLookupArray somehow doesn't exist? 
		rates['Ground'] = 150.00;			
	}

	if( !rates ) {
		var defaultEntry = new Array();
		defaultEntry['2-Day'] = 150.00;
		
		rates = defaultEntry;
	}

	// December 18, 2008 WSH // EMU // IF NO COUNTRY WAS SELECTED THEN RETURN NOTHING
	if( $( '#co_shipping_country_id' ).val() < 1 ) {
		rates = null;
		$('#co_shipping_rates').html( '' );
	}

	return( rates );
}	

function getTax( state ) {
	var stateTaxesArray = new Array( "AB", "BC", "MB", "NF", "NB", "NS", "NT", "NU", "ON", "PE", "QC", "SK", "YT" );
	// July 26, 2010 WSH // BERTHA // BC AND ON NOW HAS HST INSTEAD OF GST
	
	stateTaxesArray['AB'] = new Array( "GST" );	
	stateTaxesArray['BC'] = new Array( "HST" );
	stateTaxesArray['MB'] = new Array( "GST" );
	stateTaxesArray['NF'] = new Array( "HST" );
	stateTaxesArray['NB'] = new Array( "HST" );
	stateTaxesArray['NS'] = new Array( "HST" );
	stateTaxesArray['NT'] = new Array( "GST" );
	stateTaxesArray['NU'] = new Array( "GST" );
	stateTaxesArray['ON'] = new Array( "HST" );
	stateTaxesArray['PE'] = new Array( "GST" );
	stateTaxesArray['QC'] = new Array( "GST" );
	stateTaxesArray['SK'] = new Array( "GST" );
	stateTaxesArray['YT'] = new Array( "GST" );

	var tax = new Array();
	
	var gstRate = 0.05;
	var hstRate = 0.13;

	try {
		tax = stateTaxesArray[state][0];
		
		if( tax == "GST" ) {
			$("#co_tax_rate").val( gstRate );
			$("#co_taxes_name").text( tax + " (" + ( gstRate * 100 ) + "%)" );			
		}
		else if( tax == "HST" ) {
			if(state == "BC") {
				hstRate = 0.12;
			}
			else if( state == "NS") {
				hstRate = 0.15;
			}
			
			$("#co_tax_rate").val( hstRate );
			$("#co_taxes_name").text( tax + " (" + ( hstRate * 100 ) + "%)" );					
		}
		else {
			$("#co_tax_rate").val( 0.00 );
			$("#co_taxes_name").text( "No Tax" );		
		}		
	}
	catch( e ) {
		$("#co_tax_rate").val( 0.00 );
		$("#co_taxes_name").text( "No Tax" );		
	}

	return( tax );
}

function passwordCheck( pass2, pass1 ) {
	
	// CHECK PASSWORDS MATCH
	if (pass2 !== pass1) {
		
		// PASSWORDS DON'T MATCH, RESET THEM BOTH AND DISPLAY ERROR
		//document.getElementById( 'passCheck' ).innerHTML = 'Your passwords do not match, please re-enter them.'
		
		// RESET P1 & P2
		document.getElementById( 'password' ).value = '';
		document.getElementById( 'password_confirmation' ).value = '';
		
		// RESET FOCUS BACK TO INPUT BOX
		//password.focus();
		
		return false;
	}
	else {
		//document.getElementById( 'passCheck' ).innerHTML = 'Your passwords match, please continue.'			
		return true;
	}
}

function shippingRate() {
	this.free_shipping = 0.00;
	this.qwik_ship = 9.95;
	this.ground = 10.95;
}

function copyFields( clear ) {
	
	var fieldsArray = new Array();
	fieldsArray[0] = "firstname";
	fieldsArray[1] = "lastname";
	fieldsArray[2] = "company";
	fieldsArray[3] = "phone";
	fieldsArray[4] = "street_address";
	fieldsArray[5] = "street_address2";
	fieldsArray[6] = "city";
	fieldsArray[7] = "country_id";
	fieldsArray[8] = "zone_id";
	fieldsArray[9] = "state";
	fieldsArray[10] = "state_us";
	fieldsArray[11] = "postcode";
	//fieldsArray[12] = "tax_id"; // December 19, 2008 WSH // EMU // DON'T NEED TAX ID ANYMORE SINCE PRODUCT IS ALL IN TEXAS AND IT MAKES US LOOK FOREIGN

	try {
		if( document.getElementById( "same_as_shipping" ).checked ) {	
			try {
				document.getElementById( "billing" ).value = document.getElementById( "delivery" ).value;
			}
			catch( e ) {
	
			}
		
			for( var i = 0; i < fieldsArray.length ; i++ ) {
				try {
					if( clear > 0 ) {
						document.getElementById( "billing_" + fieldsArray[i] ).value = null;				
					}
					else {					
						document.getElementById( "billing_" + fieldsArray[i] ).value = document.getElementById( "delivery_" + fieldsArray[i] ).value;
					}
	
					if( fieldsArray[i] == "country_id" ) {
						updateState( 'billing' );	
					}
				}
				catch( e ) {
					;
				}
			}
		}
		else if( clear > 0 ) {
			try {
				document.getElementById( "billing" ).value = '';
			}
			catch( e ) {
	
			}
			
			for( var i = 0; i < fieldsArray.length ; i++ ) {
				try {		
					document.getElementById( "billing_" + fieldsArray[i] ).value = '';								
				}
				catch( e ) {
					;
				}
			}
			updateState( 'billing' );
		}
	}
	catch( e ) {
		;
	}
}

function emailCheck(str) {

		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		   return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    return false
		 }
		
		 if (str.indexOf(" ")!=-1){
		    return false
		 }

 		 return true
	}

function calculateTotal( ) {
	// WANT TO ADD UP ALL THE TOTALS ON THE PAGE
	var total = 0.00;
	var rate = 0.00;
	var taxAmont = 0.00;
	
	total += parseFloat( $("#cart_sub_total_display").html().replace( '$', '' ).replace( /,/g, '' ) );
	total += parseFloat( $("#shipping_rate_display").html().replace( '$', '' ) );
	
	rate = parseFloat( $("#co_tax_rate").val() );

	taxAmount = rate * total;
	taxAmount = Math.round( taxAmount * 100 ) / 100;

	$("#co_taxes_value").html( "$" + taxAmount.toFixed(2) );
	
	// January 5, 2008 WSH // EMU // NEED TO UPDATE THE ORIGINAL TAXES HIDDEN FIELDS AS WELL
	$("#shipping_tax_name").val( $("#co_taxes_name").text() );
	$("#shipping_tax_charge").val( taxAmount );
	
	total += taxAmount;	

	total = Math.round( total * 100 ) / 100;

	total = total.toFixed( 2 );		
	$("#co_grand_total_value").html( '$' + addCommas( total ) );
	// January 15, 2009 WSH // FOO // THESE TWO FIELDS THAT WERE ORIGINALLY HERE DOES NEED TO BE UPDATED FOR PAYPAL
	$("#taxes_rate").val( rate );
	$("#taxes_value").val( taxAmount );
	$("#taxes_name").val( $("#co_taxes_name").text() );
	//$("#grand_total").val( total );
	$("#cart_grand_total_display").html( '$' + addCommas( total ) );
	$("#co_grand_total_value").val( total );
	
	return( total );
}

// WSH // Start JAVASCRIPT checkAddress function
function checkAddress( addressName ) {	
	try {
		if(
			document.getElementById( 'billing' + '_firstname' ).value &&
			document.getElementById( 'billing' + '_lastname' ).value && 
			document.getElementById( 'billing' + '_company' ).value && 
			document.getElementById( 'billing' + '_phone' ).value && 
			document.getElementById( 'billing' + '_street_address' ).value && 

			document.getElementById( 'billing' + '_street_address2' ).value &&
			document.getElementById( 'billing' + '_postcode' ).value && 
			document.getElementById( 'billing' + '_city' ).value &&
			document.getElementById( 'billing' + '_country_id' ).value && 
			document.getElementById( 'shipping' + '_address_name' ).value && 
			document.getElementById( 'shipping' + '_firstname' ).value && 
			document.getElementById( 'shipping' + '_lastname' ).value && 
			document.getElementById( 'shipping' + '_company' ).value && 
			document.getElementById( 'shipping' + '_phone' ).value &&
			document.getElementById( 'shipping' + '_street_address' ).value &&

			document.getElementById( 'shipping' + '_street_address2' ).value &&
			document.getElementById( 'shipping' + '_postcode' ).value && 
			document.getElementById( 'shipping' + '_city' ).value && 
			document.getElementById( 'shipping' + '_country_id' ).value 
		) {
			// document.getElementById( 'belowAddress' ).style.display = 'block';
		}
		else {
			// document.getElementById( 'belowAddress' ).style.display = 'none';
		}	
	}
	catch (err) {
		// alert('Address Error' + err);\n";
	}
}

function checkForm ( form ) {
		
		var ret = '';
		var msg = ''; 
		
		//alert("Form contains " + form.length + " fields")	
		var shippingIsChecked = false;
		var paymentIsChecked = true;
		
		var numRequired = 0;
		
		// November 28, 2007 WSH // IF THE BILLING IS SAME AS SHIPPING CHECKBOX IS CHECKED, GET THE VALUES FIRST. WE'RE NOW DEFAULTING TO SAME, SO NEED TO GRAB VALUES AFTER THEY'VE BEEN ENTERED
		if( document.getElementById('useBilling').getAttribute( 'useBilling' ) == 'true' ) {
			getBilling();
		}
		
		for(i=0; i < form.length; i++) {
			if(form[i].type) {
			//alert('form type is ' + form[i].type);
				// RESET STYLE
	 			// form[i].style.border = '1px solid grey;'
	 			if (form[i].type == 'text') {
					setStyleByTag('input', 'border-color', 'grey', 1);
				}
				else {
					// alert("Ignoring field " + form[i].name)
				}
				
				if (form[i].className == 'req' && form[i].value == '' ) {
					// alert("This field is required : " + form[i].name);
					ret += "Field : " + form[i].name.replace(/_/g, " ")  + " is required.<br>\n";
					
					// form[i].style.border = '1px solid red;'
					
					setStyleById(form[i].name, 'border', '1px solid red');
					numRequired++;
				}
				
				// January 9, 2007 WSH // ADDED CODE TO HANDLE REQUIRING SHIPPING RADIO TO BE SET
				if ( form[i].name.search("shippingOptionsRadio") != '-1' ) {
					if( form[i].checked ) {					
						shippingIsChecked = true;
					}
				}
				
				// January 9, 2007 WSH // ADDED CODE TO HANDLE REQUIRING PAYMENT RADIO TO BE SET
				if ( form[i].name.search("payment") != '-1' ) {
					if( form[i].checked ) {
						paymentIsChecked = true;
					}
				}
				
				if ( form[i].name.search("email") != '-1') {
					if( form[i].value ) {
						if ( emailCheck( form[i].value ) == false ) {
							ret += "Field : " + form[i].name.replace(/_/g, " ")  + " does not appear to be a valid email address<br>\n";
							
							setStyleById(form[i].name, 'border', '1px solid red');
						}
					}
				}								

				if ( form[i].name == "password" &&  form[i].value.length < 5 ) {
						ret += "Field : " + form[i].name.replace("_", " ")  + " must be at least 5 characters long<br>\n";						
						setStyleById(form[i].name, 'border', '1px solid red');
				}											
			}
		}

		//if( numRequired < 5 ) {
		//if( document.form.getElementByName('login_type').value == 'existing' ) {
		// January 23, 2007 WSH // NOPE, CAN'T GET THE RADIO BUTTON VALUE BY document.checkout_payment.login_type.value, IT JUST DOESN'T WORK THAT WAY
		try {
			if(document.checkout_payment.login_type[1].checked) {
				shippingIsChecked = true;
				paymentIsChecked = true;
			}
		}
		catch(e) {
			//shippingIsChecked = true;
			//paymentIsChecked = true;
		}

		// January 9, 2007 WSH // ADDED CODE TO HANDLE REQUIRING SHIPPING RADIO TO BE SET
		if( !shippingIsChecked ) {
			ret += "A shipping method must be selected.<br>\n";

		}
		
		// January 9, 2007 WSH // ADDED CODE TO HANDLE REQUIRING PAYMENT RADIO TO BE SET
		if( !paymentIsChecked ) {
			ret += "A payment method must be selected.<br>\n";
		}

		if (ret != '') {
			// October 9,2007 WSH // MADE THE ERROR MSGS RED
			msg = "<h1 style='color : red;'>Your form contains errors</h1><br>\nSorry, I cannot submit your form because you have not filled in all necessary fields or some fields you have entered are not valid.<br><br>\nThe details of fields with errors are listed below.<br><br>" + "<div style='color: #FF0000; font-weight: bold;'>" + ret + "</div>";
			document.getElementById( 'confirmBox' ).innerHTML = msg;
			
			//document.getElementById( 'confirmBox' ).style.padding = '10px';
			//document.getElementById( 'confirmBox' ).style.border = '2px solid red';
			
			window.location = '#top';
			return false;
		}
		else {
			//document.getElementById( 'confirmBox' ).innerHTML = "Form is good";
			document.checkout_payment.submit();
			return true;
		}
		
	
	}


//Content for top of page
//Our 'rapid checkout' allows you to complete your purchase shopping cart through VISA, MASTERCARD or AMEX and to submit your Purchase Order online for review. Acceptance is subject to approval. Terms & Conditions. Order with confidence.

function updateShipping( shippingName, shippingRate, shippingIndex ) {
	// December 3, 2008 WSH // EMU // UPDATE THE DISPLAY FIRST AND THE UPDATE THE HIDDEN FIELDS
	shippingRate = Math.round( shippingRate * 100 ) / 100;
	shippingRate = shippingRate.toFixed( 2 );
	
	$( '#co_shipping_line_price' ).html( "$" + shippingRate );
	$( '#co_shipping_line_total' ).html( "$" + shippingRate );
	
//	$( '#co_shipping_value' ).html( "$" + shippingRate );

	$( '#shipping_method' ).val( shippingName );
	$( '#shipping_charge' ).val( shippingRate );
	calculateTotal();
	
	//$( '#shipping_' + shippingIndex + ", .shipping_rate_labels" ).removeClass( "selected" );
	$( '#shipping_' + shippingIndex + ", .shipping_rate_labels" ).removeClass( "selected" );
	$( '#shipping_' + shippingIndex + ", .shipping_rate_values" ).removeClass( "selected" );
	$( '#shipping_' + shippingIndex + ", #shipping_rate_" + shippingIndex ).addClass( "selected" );
	// December 18, 2008 WSH // EMU // NOW SHOWING THE SELECTED SHIPPING RATE SOMEWHERE
	$( '#co_shipping_method' ).html( $( '#shipping_' + shippingIndex ).text() );
}

function populateAddress( id ) {
	var fieldsArray = new Array();
	fieldsArray[0] = "firstname";
	fieldsArray[1] = "lastname";
	fieldsArray[2] = "company";
	fieldsArray[3] = "phone";
	fieldsArray[4] = "street_address";
	fieldsArray[5] = "street_address2";
	fieldsArray[6] = "city";
	fieldsArray[7] = "country_id";
	fieldsArray[8] = "zone_id";
	fieldsArray[9] = "state";
	fieldsArray[10] = "state_us";
	fieldsArray[11] = "tax_id";
	fieldsArray[12] = "postcode";

	//var selectedAddress = document.getElementById( id ).value;
	var selectedAddress = $('#' + id).val();
	// WSH // SUCKS, DON'T KNOW HOW IT HAPPENS, BUT VALUES SEEM TO BE DIFFERENT BETWEEN IE AND FIREFOX
	if( selectedAddress == '' || selectedAddress == 'Enter new address' ) {
		for( var i = 0; i < fieldsArray.length ; i++ ) {
			try {
			//	document.getElementById( id + fieldsArray[i] ).value = '';
				$( '#' + id + '_' + fieldsArray[i] ).val( '' );
			}
			catch( e ) {
				//alert(e);
			}
		}			
	}
	else {
		try {
			selectedAddress = selectedAddress.replace( ' ', '_' );				
	
			for( var i = 0; i < fieldsArray.length ; i++ ) {
				try {
				//	document.getElementById( id + fieldsArray[i] ).value = '';
					$( '#' + id + '_' + fieldsArray[i] ).val( $( '#' + selectedAddress + '_' + fieldsArray[i] ).val() );
				}
				catch( e ) {
					//alert(e);
				}
			}			
		}
		catch(err) {
	
		}
	}

	try {
		document.getElementById( 'order_' + id ).value = selectedAddress;
	}
	catch(err) {
		// element does exist yet onLoad?? but it sure does work after.\n";
	}	
}

function updateProgressBar(currentStep) {
	var progressBar = document.getElementById( 'progress_bar' );
	var progressImage = "";
	
	if( currentStep == "account_div" ) {
		progressImage = "checkout_sign_in.gif";
	}
	else if( currentStep == "address_div" ) {
		progressImage = "checkout_billing_shipping.gif";	
	}
	else if( currentStep == "payment_div" ) {
		progressImage = "checkout_payment.gif";
	}
	
	
	progressBar.innerHTML = "<img src='images_new/" + progressImage + "' border='0' usemap='#progress_bar'>\n";
}

function checkPasswordConfirmation() {
	// CHECK TO SEE IF PASSWORD AND CONFIRMATION MATCHES
	var matches = false;	
	var password = $( '#password' ).val();
	var passwordConfirmation = $( '#password_confirmation' ).val();

	if( password == passwordConfirmation ) {
		matches = true;
	}
	else {

	}
	
	// IF PASSWORD AND CONFIRMATION DOESN'T MATCH, THEN POP UP MESSAGE SAYING PASSWORDS DON'T MATCH
	// WHAT IS THE BEST WAY TO SHOW THE MESSAGE?? SHOULD IDEALLY BE ON THE DRAW CURRENT MESSAGE DIV
	if( !matches ) {
		$('#password_confirmation_message').html( "passwords do not match" );	
		$('#password_confirmation_message').removeClass( 'green' );
		$('#password_confirmation_message').addClass( 'red' );
	}
	else {
		$('#password_confirmation_message').html( "passwords match" );	
		$('#password_confirmation_message').removeClass( 'red' );
		$('#password_confirmation_message').addClass( 'green' );
	}
	
	return( matches );
}

// July 31, 2008 WSH // SEPARATE FUNCTION FOR CHECKING THE STANDALONE REGISTER SCREEN
function checkRegister() {
	var error = new Array();
	var errorCount = 0;
	var errorMessages = document.getElementById( 'errorMessages' );

	// CHECK PASSWORD LENGTH
	if(document.getElementById( "password" ).value.length < 5) {						
		error[errorCount++] = 'Passwords must be 5 characters or more'
		setStyleById("password", 'border', '1px solid red');
	}
			
	// CHECK PASSWORDS MATCH
	if(!passwordCheck(document.getElementById( "password" ).value, document.getElementById( "password_confirmation" ).value)) {
		error[errorCount++] = 'Your passwords do not match'
		setStyleById('password', 'password', '1px solid red');
		setStyleById('password_confirmation', 'password_confirmation', '1px solid red');
	}
			
	// CHECK EMAIL ADDRESS
	if(!emailCheck(document.getElementById( "email_address" ).value)) {
		error[errorCount++] = 'Email address does not appear to be a valid format.'
		setStyleById('email_address', 'email_address', '1px solid red');
	}
	
	// CHECK FIRST AND LAST NAME
	if(document.getElementById( "login_firstname" ).value.length < 1) {
		error[errorCount++] = 'Firstname must be entered.'
		setStyleById('login_firstname', 'login_firstname', '1px solid red');
	}

	if(document.getElementById( "login_lastname" ).value.length < 1) {
		error[errorCount++] = 'Lastname must be entered.'
		setStyleById('login_lastname', 'login_lastname', '1px solid red');
	}

	errorMessages.innerHTML = "";
	if( errorCount > 0 ) {			
		for( var i = 0; i < error.length; i++ ) {
			errorMessages.innerHTML += error[i] + "<br>";
		}

		errorMessages.innerHTML += "<a href=\"javascript:toggleDiv('errorMessages');\">Close Window</a>";

		toggleDiv( 'errorMessages', '200px' );									
	}
	else {
		document.checkout_payment.submit();
		return;
	}
}