// test the user's browser functionality
if (!document.getElementById) {
	alert("Your browser does not support document.getElementById.  You may not be able to fully utilize this shopping cart.");
}

// Some stuff that'll help us access the cart contents easier, later
var cartContentsID = "cartContents";

function getHandleToCartContents() {
	if (document.getElementById) {
		var cartContents = document.getElementById(cartContentsID);		
		return cartContents;
	}
}

//------------- Ajax handling functions -------------------------------------------
var cartPostReq = false;	// the XMLHttpRequest		
function handleCartRequest(theForm) {

	if(window.XMLHttpRequest) {
		try {
			cartPostReq = new XMLHttpRequest();
		} catch(e) {
			cartPostReq = false;
		}
	} else if(window.ActiveXObject) {
		try {
			cartPostReq = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			try {
				cartPostReq = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e) {
				cartPostReq = false;
			}
		}
	}
	
	if(cartPostReq && theForm) {
		// gather up the post data we want to send - based on the form that was supplied
		formElements = theForm.elements;
		var postData = "";
		for (var i=0; i < formElements.length; i++) {
			postData += "&"+formElements[i].name+"="+formElements[i].value;
		}
		// pass along the flag that says we want to use AJAX on the form elements
		//postData += "&use_ajax=<?=$useAJAX?>";
		postData += "&use_ajax=true";

		//var postData = "newClientName="+encodeURI(document.getElementById('newClientName').value) +
		//	"&action=ADD_CLIENT";

		cartPostReq.onreadystatechange = processCartResponse;
		cartPostReq.open("POST", 'ajaxCartRequestProcessor.php', true);
		cartPostReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		cartPostReq.setRequestHeader("Content-length", postData.length);
		cartPostReq.setRequestHeader("Connection", "close");
		cartPostReq.send(postData);
	} 
}

function processCartResponse() {
	if(cartPostReq.readyState == 4) {
		if(cartPostReq.status == 200) {			
			var theResponse = cartPostReq.responseText.split("|");
			if (theResponse[0] == 'OK') {
				// show the status message
				//alert("Got a status of OK");
				var cartContents = getHandleToCartContents();
				cartContents.innerHTML = theResponse[1];
			
				giveAJAXFeedback("purchaseButton", "ajaxFeedback", "Product(s) added to Cart!");

				return;				
			}
			else if (theResponse[0] == 'FL') {
				alert("Error - "+theResponse[1]);
				return;	
			}
			else {
				alert("Got an UNKNOWN status - "+theResponse);
				return;	
			}
		} else {
			// oh noes, http error
			alert("HTTP Error");
			return;
		}
	}
}

function giveAJAXFeedback(buttonID, feedbackID, message) {
	if (document.getElementById) {		
		// get handles to the elements we care about
		var theButton = document.getElementById(buttonID);
		var theFeedback =document.getElementById(feedbackID);
		var theFeedbackMessage =document.getElementById(feedbackID+"_message");
		if (theButton && theFeedback && theFeedbackMessage && theFeedbackMessage.innerHTML) {
			// set the message
			theFeedbackMessage.innerHTML = message;
			// hide the button
			theButton.style.display='none';
			// show the message
			theFeedback.style.display='block';

			// and now set it all back to normal in a few seconds
			setTimeout("resetAJAXFeedback('"+buttonID+"', '"+feedbackID+"')", 5000);
		}
	}
}

function resetAJAXFeedback(buttonID, feedbackID) {
	if (document.getElementById) {
		// get handles to the elements we care about
		var theButton = document.getElementById(buttonID);
		var theFeedback =document.getElementById(feedbackID);
		var theFeedbackMessage =document.getElementById(feedbackID+"_message");
		if (theButton && theFeedback && theFeedbackMessage && theFeedbackMessage.innerHTML) {
			// hide the message
			theFeedback.style.display='none';
			// clear the message
			theFeedbackMessage.innerHTML = "&nbsp;";
			// show the button
			theButton.style.display='block';
		}
	}
}

//------------- END Ajax handling functions ---------------------------------------

//------------- Credit Card handling functions ------------------------------------
function mod10( cardNumber ) { // LUHN Formula for validation of credit card numbers.
	var ar = new Array( cardNumber.length );
	var i = 0,sum = 0;

	for( i = 0; i < cardNumber.length; ++i ) {
		ar[i] = parseInt(cardNumber.charAt(i));
	}
	for( i = ar.length -2; i >= 0; i-=2 ) { // you have to start from the right, and work back.
		ar[i] *= 2;							 // every second digit starting with the right most (check digit)
		if( ar[i] > 9 ) ar[i]-=9;			 // will be doubled, and summed with the skipped digits.
	}										 // if the double digit is > 9, ADD those individual digits together 


	for( i = 0; i < ar.length; ++i ) {
		sum += ar[i];						 // if the sum is divisible by 10 mod10 succeeds
	}
	return (((sum%10)==0)?true:false);	 	
}

function expired( month, year ) {
	var now = new Date();							// this function is designed to be Y2K compliant.
	var expiresIn = new Date(year,month,0,0,0);		// create an expired on date object with valid thru expiration date
	expiresIn.setMonth(expiresIn.getMonth()+1);		// adjust the month, to first day, hour, minute & second of expired month
	if( now.getTime() < expiresIn.getTime() ) return false;
	return true;									// then we get the miliseconds, and do a long integer comparison
}

function validateCard(cardNumber,cardType,cardMonth,cardYear) {
	var errorMessage = "";
	if( cardNumber.length == 0 ) {						//most of these checks are self explanitory
		//alert("Please enter a valid card number.");		
		errorMessage = "Please enter a valid card number.";
		markMissed('card_number_label', true);
		showErrorMessage(errorMessage);
		return false;				
	}
	for( var i = 0; i < cardNumber.length; ++i ) {		// make sure the number is all digits.. (by design)
	var c = cardNumber.charAt(i);
		if( c < '0' || c > '9' ) {
			//alert("Please enter a valid card number. Use only digits. Do not use spaces or hyphens.");			
			errorMessage = "Please enter a valid card number. Use only digits. Do not use spaces or hyphens.";
			markMissed('card_number_label', true);
			showErrorMessage(errorMessage);
			return false;
		}
	}
	var length = cardNumber.length;			//perform card specific length and prefix tests
	switch( cardType ) {
		case 'Amex':
			if( length != 15 ) {
				//alert("Please enter a valid American Express Card number.");
				errorMessage = "Please enter a valid American Express Card number.";
				markMissed('card_number_label', true);
				showErrorMessage(errorMessage);
				return false;
			}
			var prefix = parseInt( cardNumber.substring(0,2));
				if( prefix != 34 && prefix != 37 ) {
					//alert("Please enter a valid American Express Card number.");
					errorMessage = "Please enter a valid American Express Card number.";
					markMissed('card_number_label', true);
					showErrorMessage(errorMessage);
					return false;
				}
				break;
		case 'Discover':
			if( length != 16 ) {
				//alert("Please enter a valid Discover Card number.");
				errorMessage = "Please enter a valid Discover Card number.";
				markMissed('card_number_label', true);
				showErrorMessage(errorMessage);
				return false;
			}
			var prefix = parseInt( cardNumber.substring(0,4));

			if( prefix != 6011 ) {
				//alert("Please enter a valid Discover Card number.");
				errorMessage = "Please enter a valid Discover Card number.";
				markMissed('card_number_label', true);
				showErrorMessage(errorMessage);
				return false;
			}
			break;
		case 'Mastercard':
			if( length != 16 ) {
				//alert("Please enter a valid MasterCard number.");
				errorMessage = "Please enter a valid MasterCard number.";
				markMissed('card_number_label', true);
				showErrorMessage(errorMessage);
				return false;
			}
			var prefix = parseInt( cardNumber.substring(0,2));
			if( prefix < 51 || prefix > 55) {
				//alert("Please enter a valid MasterCard Card number.");
				errorMessage = "Please enter a valid MasterCard Card number.";
				markMissed('card_number_label', true);
				showErrorMessage(errorMessage);
				return false;
			}
			break;
		case 'Visa':
			if( length != 16 && length != 13 ) {
				//alert("Please enter a valid Visa Card number.");
				errorMessage = "Please enter a valid Visa Card number.";
				markMissed('card_number_label', true);
				showErrorMessage(errorMessage);
				return false;
			}
			var prefix = parseInt( cardNumber.substring(0,1));

			if( prefix != 4 ) {
				//alert("Please enter a valid Visa Card number.");
				errorMessage = "Please enter a valid Visa Card number.";
				markMissed('card_number_label', true);
				showErrorMessage(errorMessage);
				return false;
			}
			break;
	}
	if( !mod10( cardNumber ) ) { 		// run the check digit algorithm
		//alert("Sorry! this is not a valid credit card number.");
		errorMessage = "Sorry! this is not a valid credit card number.";
		markMissed('card_number_label', true);
		showErrorMessage(errorMessage);
		return false;
	}

	// we're still here, so this card number must be okay - so clear any error highlighting on it
	markMissed('card_number_label', false);

	if( expired( cardMonth, cardYear ) ) {							// check if entered date is already expired.
		//alert("Sorry! The expiration date you have entered would make this card invalid.");
		errorMessage = "Sorry! The expiration date you have entered would make this card invalid.";
		markMissed('card_expiration_label', true);
		showErrorMessage(errorMessage);
		return false;
	}
				
	// at this point card has not been proven to be invalid - so clear any error highlighting and return true	
	markMissed('card_expiration_label', false);
	return true; 
}

function markMissed(labelID, missed) {
	if (document.getElementById) {
		// get a handle to the label
		var theLabel = document.getElementById(labelID);
		if (theLabel) {
			if (missed) {
				theLabel.className='missed';
			}
			else {
				theLabel.className='';
			}
		}
	}	
	
}

function showErrorMessage(theMessage) {
	if (document.getElementById) {
		var theElement = document.getElementById('ccErrorBox');
		if (theElement) {
			theElement.innerHTML = theMessage;
		}
		else {
			alert(theMessage);
		}
	}
	else {
		alert(theMessage);
	}
}

//------------- END Credit Card handling functions --------------------------------

/***************************************
Tie this function to the onblur event of 
a text input field, and it will limit all
input characters to digits only
***************************************/
function scrubNonDigits(theElement, forceZero) {
	theElement.value = theElement.value.replace(/[^\d]/g, '');
	if (forceZero && (theElement.value == '' || theElement.value == null)) {
		theElement.value = '0';
	}
}

function useBillingAsShipping(theCheckbox, theForm) {
	if (document.getElementById) {		
		if (theCheckbox.checked) {
			theForm.shipping_name.value = theForm.billing_name.value;
			theForm.shipping_address1.value = theForm.billing_address1.value;
			theForm.shipping_address2.value = theForm.billing_address2.value;
			theForm.shipping_city.value = theForm.billing_city.value;
			theForm.shipping_state.value = theForm.billing_state.value;
			theForm.shipping_zip.value = theForm.billing_zip.value;
			theForm.shipping_country.value = theForm.billing_country.value;
			theForm.shipping_phone.value = theForm.billing_phone.value;
		}
	}
}
