function addToCart(type) {
	var totaldvds = 0;
	var totalsd = 0;
	var totalhd = 0;
	
	var item;
	for( current in simpleCart.items ){
		item = simpleCart.items[current];
		
		var quantity = parseInt(item.quantity,10);
		if(item.quality == "HD")
			totalhd+=quantity;
		else if(item.quality == "SD")
			totalsd+=quantity;
		else if(item.type == "dvd")
			totaldvds+=quantity;
	}			

	var price = "";
	if(type == "dvd") {
		price = "20.00";
		if(totaldvds == 1)
			price = "12.00";
		else if(totaldvds == 2)
			price = "13.00";
		else if(totaldvds >= 3)
			price = "12.00";
		var sel = (document.formElem.dvd_select.options[document.formElem.dvd_select.selectedIndex].value);
		simpleCart.add('name='+sel , 'price='+price , 'quantity=1', 'type='+type, 'quality=N/A');
	} else if (type == "dd") {
		
		var sel = $('#ass_select option:selected').text() + ' - ' +$('#ens_select option:selected').text();
		var quality = (document.formElem.quality_select.options[document.formElem.quality_select.selectedIndex].value);
		
		if(quality == "HD ($9)") {
			quality = "HD";
			price = "9.00";
			if(totalhd == 1)
				price = "7.00";
			else if(totalhd == 2)
				price = "7.00";
			else if(totalhd >= 3)
				price = "7.00";
		}
		if(quality == "SD ($6)") {
			quality = "SD";
			price = "6.00";
			if(totalsd == 1)
				price = "4.00";
			else if(totalsd == 2)
				price = "4.00";
			else if(totalsd >= 3)
				price = "4.00";
		}
		simpleCart.add('name='+sel , 'price='+price , 'quantity=1', 'type='+type, 'quality='+quality );
	} else if (type == "mod") {
		price = parseFloat($('#adminmod').val());
		var sel = $('#admindesc').val();
		simpleCart.add('name='+sel , 'price='+price , 'quantity=1', 'type='+type, 'quality=N/A');
	}				
}

function fakeClick(event, anchorObj) {
  if (anchorObj.click) {
    anchorObj.click()
  } else if(document.createEvent) {
    if(event.target !== anchorObj) {
      var evt = document.createEvent("MouseEvents"); 
      evt.initMouseEvent("click", true, true, window, 
          0, 0, 0, 0, 0, false, false, false, false, 0, null); 
      var allowDefault = anchorObj.dispatchEvent(evt);
      // you can check allowDefault for false to see if
      // any handler called evt.preventDefault().
      // Firefox will *not* redirect to anchorObj.href
      // for you. However every other browser will.
    }
  }
}

function createRequestObject(){
	var request_;
	var browser = navigator.appName;
	if(browser == "Microsoft Internet Explorer"){
	 	request_ = new ActiveXObject("Microsoft.XMLHTTP");
	}else{
	 	request_ = new XMLHttpRequest();
	}
	return request_;
}

var http = createRequestObject();

function updateEnsembles() {
	http.open('get', 'getEnsembles.php?association=' + document.formElem.ass_select.options[document.formElem.ass_select.selectedIndex].value);
	
	http.onreadystatechange = handleReceipt;
	
	http.send(null);
}

function handleReceipt(){
	if(http.readyState == 1){
	 	// querying still
	}
	
	if(http.readyState == 4){
		// ready
		var response = http.responseText;

			var arrOfEns = response.split(",");
		//alert(arrOfEns[0]);
		document.formElem.ens_select.options.length=0;
		var master = document.formElem.ens_select;
		for (i=0; i<arrOfEns.length; i++){
			master.options[master.options.length]=new Option(arrOfEns[i], arrOfEns[i]);
		}
	}
	
}

function validateEmail() {
	var email = document.formElem.email.value;
	var ver_email = document.formElem.ver_email.value;
	var hasError = false;
	if (email != ver_email) {
		hasError = true;
		$(document.formElem.ver_email).css('background-color','#FFEDEF');
		$(document.formElem.email).css('background-color','#FFEDEF');
	} else {
		$(document.formElem.ver_email).css('background-color','#FFFFFF');
		$(document.formElem.email).css('background-color','#FFFFFF');
	}
	
	var $link = $('#navigation li:nth-child(' + 3 + ') a');
	$link.parent().find('.error,.checked').remove();
	
	var valclass = 'checked';
	if(hasError){
		valclass = 'error';
		$('<span class="'+valclass+'"></span>').insertAfter($link);
	}				
	
}

function updatePaymentInfo() {
/* 	var radioObj = document.getElementById("payment_choice"); */
	/*
var radioObj = document.formElem.payment_choice;
	var pmt;
	for(var i = 0; i < radioObj.length; i++) {
		if(radioObj[i].checked) {
			pmt = radioObj[i].value;
		}
	}
*/			
	var pmt = $('input[name=payment_choice]:checked', '#formElem').val();
	
	var payment_info = document.getElementById("payment_info");
	if(pmt == "paypal")
		$(payment_info).html("<p>Checkout with paypal to use your credit card or existing paypal account to pay instantly for your order.<br/><br/> <b>*No paypal account is required to checkout with paypal.</b></p> <h1>PLEASE DISABLE ANY POPUP BLOCKERS BEFORE HITTING NEXT.</h1><a href='http://www.lbl.gov/ehs/training/webcourses/globalAssets/CourseRequirements/disablePopups/disablepopups.html' target='_blank'>How to Disable Popup Blocker</a>");
	if(pmt == "check")
		$(payment_info).html("<p>Choose this option to avoid credit cards. Make checks payable to <b>Videos of Goodness</b> and mail them within a day of your order to<br/><br/> <b>1000 W Spring Valley Rd #128<br/>Richardson, Tx 75080</b><br/><br/> <span style='color:blue;'>Please print your order email and include it with your check to help us keep things aligned!</span><br/><br/><b>*Checks that bounce will be subject to a $15 fee on top of your order total.</b></p>");

}

function updateCustomerInfo() {
	simpleCart.fname = document.formElem.fname.value;
	simpleCart.lname = document.formElem.lname.value;
	simpleCart.customer_email = document.formElem.email.value;
	simpleCart.customer_phone = document.formElem.phone.value;
	
	simpleCart.address1 = document.formElem.street_address.value;
	simpleCart.address2 = document.formElem.street_address_2.value;
	simpleCart.city = document.formElem.city.value;
	simpleCart.state = document.formElem.state.value;
	simpleCart.zip = document.formElem.zip.value;

	// create html to put in confirmation_text
	var item;
	var dvdCount = 0
	var ddCount = 0;
	for( current in simpleCart.items ){
		item = simpleCart.items[current];
		if (item.type == "dvd")
			dvdCount+=parseInt(item.quantity, 10);
		else
			ddCount+=parseInt(item.quantity, 10);
	}
	
	var dvdsadded = dvdCount ? "<b>" + dvdCount + " DVD(s)</b>" : "";
	var ddsadded = ddCount ? "<b>" + ddCount + " Digital Download(s)</b>" : "";
	var bothadded = " and ";
	if (dvdCount == 0 || ddCount == 0)
		bothadded = "";
		
	var taxShip = dvdCount ? "including tax & shipping." : "including tax.";
	
	var conf = "<h3>Alright " + document.formElem.fname.value + ",</h3><br/>So to review; you've added " + dvdsadded + bothadded + ddsadded + " to your cart, which brings your total to";
	
	conf += "<span style='color:red'> " + simpleCart.currencyStringForPaypalCheckout(simpleCart.finalTotal) + "</span> " + taxShip;
	
	var downloadLinks = ddCount ? "download links & " : "";
	
	conf += "<br/><br/>Your email address where you will be receiving your " + downloadLinks + "order status is: <b>" + document.formElem.email.value + "</b> and your phone number is <b>" + document.formElem.phone.value + "</b> in case we can't reach you by email.<br/><br/>";
	
	/*
var radioObj = document.formElem.payment_choice;
	var pmt;
	for(var i = 0; i < radioObj.length; i++) {
		if(radioObj[i].checked) {
			pmt = radioObj[i].value;
		}
	}
*/
	var pmt = $('input[name=payment_choice]:checked', '#formElem').val();
	
	var paypalInfo = (pmt == "paypal") ? ", which will open in a new window to allow you to complete the purchase." : "";

	conf += "You've chosen to pay via <b>" + pmt + paypalInfo;
	
	conf += "</b><br/><br/>If this all sounds correct, go ahead and hit Confirm Order (just hit it once please)<br/><br/>";
	
	conf += "Once your order has been processed, you will receive a confirmation email which also will be your receipt. <br/><br/>Thank you for your order!<br/><br/> If you have any questions or problems, please contact us at orders@videosofgoodness.com";

	
	document.getElementById('confirmation_text').innerHTML = conf;
	
}

function doCheckout() {
	if($('#formElem').data('errors')){
		alert('Please correct the errors in the Form');
		return false;
	}
	
	updateCustomerInfo();
	
	var jsonStr = JSON.stringify(simpleCart.items);
	$.ajaxSetup({async:true});
	$.post("validateCart.php", {cartItems:jsonStr}, function(data) {
		if(data == "NO ERROR") {
			var pmt = $('input[name=payment_choice]:checked', '#formElem').val();
			if(pmt == "paypal")
				simpleCart.checkoutTo = PayPal;
			if(pmt == "check")
				simpleCart.checkoutTo = Email;
			simpleCart.checkout();
		} else {
			for( var current in simpleCart.items ){
				var item = simpleCart.items[current];			 
				item.remove();
			}
			simpleCart.update();
			updateCustomerInfo();
			alert("There was an error validating your cart pricing. This can happen if you add an item, then remove it and add it again at a lower price. We've emptied your cart, so please go back and add your items again.");
		}
	});	
}
