/**************************************************
And now for something completely different...
(most of the script written from scratch by Grant Gatchel)
***************************************************/
// updates the rest of the numbers and calculates the totals in real time
var _order = {
	products : {
		"PickTwo1stEd" :
		{ 
			"price" : 13.95,
			"desc"  : "Pick Two 1st edition",
			"family": "picktwo",
			"specials" : [],
			"qty"   : 0
		},
		"PickTwoEnglish" :
		{ 
			"price" : 15.95,
			"desc"  : "Pick Two English edition",
			"family": "picktwo",
			"specials" : [],
			"qty"   : 0
		},
		"PickTwoSpanish" :
		{ 
			"price" : 16.95,
			"desc"  : "Pick Two Spanish edition",
			"family": "picktwo",
			"specials" : [],
			"qty"   : 0
		},
		"PickTwoSpanishAccents" :
		{
			"price" : 16.95,
			"desc"  : "Pick Two Spanish edition (with accents)",
			"family": "picktwo",
			"specials" : [],
			"qty"   : 0
		},
		"PickTwoFrench" :
		{ 
			"price" : 16.95,
			"desc"  : "Pick Two French edition",
			"family": "picktwo",
			"specials" : [],
			"qty"   : 0
		},
		"PickTwoFrenchAccents" :
		{ 
			"price" : 16.95,
			"desc"  : "Pick Two French edition (with accents)",
			"family": "picktwo",
			"specials" : [],
			"qty"   : 0
		},
		"PickTwoGerman" :
		{ 
			"price" : 16.95,
			"desc"  : "Pick Two German edition",
			"family": "picktwo",
			"specials" : [],
			"qty"   : 0
		},
		"PickTwoLatin" :
		{ 
			"price" : 16.95,
			"desc"  : "Pick Two Latin edition",
			"family": "picktwo",
			"specials" : [],
			"qty"   : 0
		},
		"PickTwoItalian" :
		{ 
			"price" : 16.95,
			"desc"  : "Pick Two Italian edition",
			"family": "picktwo",
			"specials" : [],
			"qty"   : 0
		},
		"BumpEnglish" :
		{ 
			"price" : 11.95,
			"desc"  : "Bump English edition ",
			"family": "bump",
			"specials" : [],
			"qty"   : 0
		},
		"BumpFL" :
		{ 
			"price" : 12.95,
			"desc"  : "Bump Foreign Language edition",
			"family": "bump",
			"specials" : [],
			"qty"   : 0
		},
		"AnswersUP" :
		{ 
			"price" : 17.95,
			"desc"  : "Answers UP",
			"family": "answersup",
			"specials" : [],
			"qty"   : 0
		},
		"GooseEgg" :
		{ 
			"price" : 17.95,
			"desc"  : "Goose Egg",
			"family": "gooseegg_orig",
			"specials" : [],
			"qty"   : 0
		},
		"GooseEggDiv" :
		{ 
			"price" : 11.95,
			"desc"  : "Goose Egg for Division",
			"family": "gooseegg_div",
			"specials" : [],
			"qty"   : 0
		},
		"GottaBeQuick" :
		{ 
			"price" : 15.95,
			"desc"  : "Gotta Be Quick (no accents)",
			"family": "gottabequick",
			"specials" : [],
			"qty"   : 0
		},
		"GottaBeQuickAccents" :
		{ 
			"price" : 15.95,
			"desc"  : "Gotta Be Quick (with accents)",
			"family": "gottabequick",
			"specials" : [],
			"qty"   : 0
		}
	},
	subtotal : 0.00,
	totaldiscount : 0.00,
	shipping : 0.00,
	total : 0.00,
    applyCoupon : function (coupon) {}
};

function applyPrices()
{
	var prices = document.getElementsByTagName('DIV');
	for (var i in prices)
	{
		if ((prices[i].className) && (prices[i].className == "price"))
		{
			var id = parseProductName(prices[i].id);
			prices[i].innerHTML = "$" + _order.products[id].price;
		}
	}
};


function applyCoupons(coupons)
{
	if (!coupons)
	{
		return;
	}
	
	var d_coupons = decode(coupons).split(',');
	for (coupon in d_coupons)
	{
		_order.applyCoupon(d_coupons[coupon]);
	}
	
	document.getElementById("discounts_label").style.display = "block";
	document.getElementById("discounts_value").style.display = "block";
	
}

function update_calculations()
{
	var discount_quantity = 0;
	var discount_subtotal = 0.00;
	var shipping_quantity = 0;

	_order.subtotal = 0.00;
	
	for (p in _order.products)
	{
		if (_order.products[p].qty > 0)
		{		
			var item_total = parseFloat(_order.products[p].price) * parseFloat(_order.products[p].qty);
			_order.subtotal += item_total;
			shipping_quantity += _order.products[p].qty;
		}
	}

	_order.totaldiscount = 0.00;

	for (p in _order.products)
	{
		var item_price = _order.products[p].price;
		for (var s in _order.products[p].specials)
		{
			if (_order.products[p].specials[s].getItemDiscount)
			{
				_order.totaldiscount += parseFloat(fix(parseFloat(_order.products[p].specials[s].getItemDiscount(p)) * parseFloat(_order.products[p].qty)));
			}
			
			if (_order.products[p].specials[s].getOrderDiscount)
			{
				_order.totaldiscount += parseFloat(fix(_order.products[p].specials[s].getOrderDiscount(p)));
			}
			
			if (_order.products[p].specials[s].adjustShippingQuantity)
			{
				shipping_quantity += _order.products[p].specials[s].adjustShippingQuantity(p);
			}
		}
	}

	//figure out shipping
	switch (shipping_quantity)
	{
		 case 0 : _order.shipping = 0.00; break;
		 case 1 : _order.shipping = 4.50; break;
		 case 2 : _order.shipping = 6.50; break;
		 case 3 : _order.shipping = 9.00; break;
		 case 4 : _order.shipping = 11.00; break;
		default : _order.shipping = 13.00;
	}
	
	_order.subtotal -= _order.totaldiscount;

	_order.total = _order.subtotal + _order.shipping;
}

function update_form()
{
	with (document.TahDahOrderForm)
	{
		for (p in _order.products)
		{
			var chosen = _order.products[p].qty > 0;
			eval(p + "_qty.value = (chosen) ? _order.products[p].qty : '';");
			eval(p + "_total.value = (chosen) ? \"$\"+fix(parseFloat(_order.products[p].qty) * parseFloat(_order.products[p].price)) : '';");
		}

		Discounts.value = (_order.totaldiscount > 0) ? "-$"+fix(_order.totaldiscount) : "";
		Subtotal.value = "$"+fix(_order.subtotal);
		Shipping.value = "$"+fix(_order.shipping);
		Total.value = "$"+fix(_order.total);
	}
}

function validate_form()
{
	var retval = false;
	try 
	{
		update_calculations();
		update_form();
		retval = generate_paypal_inputs();
	}
	catch (e)
	{
		alert(e.name + ": " + e.message);
	}
	return retval;
}
var paypal_item_num = 0;
var createPaypalItem = function(name, value, qty)
{
	paypal_item_num++;
	
	var item_name_ = document.createElement('INPUT');
	item_name_.type = 'hidden';
	item_name_.className = "paypal_input";
	item_name_.name = "item_name_" + paypal_item_num;
	item_name_.id = "item_name_" + paypal_item_num;
	item_name_.value = name;
	document.TahDahOrderForm.appendChild(item_name_);

	var amount_ = document.createElement('INPUT');
	amount_.type = 'hidden';
	amount_.className = "paypal_input";
	amount_.name = "amount_" + paypal_item_num;
	amount_.id = "amount_" + paypal_item_num;
	amount_.value = fix(value);
	document.TahDahOrderForm.appendChild(amount_);

	var quantity_ = document.createElement('INPUT');
	quantity_.type = 'hidden';
	quantity_.className = "paypal_input";
	quantity_.name = "quantity_" + paypal_item_num;
	quantity_.id = "quantity_" + paypal_item_num;
	quantity_.value = qty;
	document.TahDahOrderForm.appendChild(quantity_);
}

var paypal_submit_counter = 0;
function generate_paypal_inputs()
{
	// clear previous inputs
	var inputs = document.getElementsByTagName('INPUT');
	var paypal_inputs = new Array();
	for (var i in inputs)
	{
		if ((inputs[i].className) && (inputs[i].className == "paypal_input"))
		{
			paypal_inputs.push(inputs[i].id);
		}
	}
	
	if (paypal_inputs.length > 0)
	{
		for (var i in paypal_inputs)
		{
			document.TahDahOrderForm.removeChild(document.getElementById(paypal_inputs[i]));
		}
	}

	// generate new inputs
	var canSubmit = false;
	
	// reset the paypal item generator
	paypal_item_num = 0;

	var give_the_customer_a_free_game = false;
	
	/////// HACK /////// HACK //////// HACK ////////
	
	if ((_order.products["GooseEggDiv"].specials["Mailing List"]) && (_order.products["GooseEggDiv"].qty > 0))
	{
		give_the_customer_a_free_game = true;

		// deduct one from the quantity of this game to work around paypal's rediculous inability to apply coupons to orders
		_order.products["GooseEggDiv"].qty--;
	}
	

	/////// HACK /////// HACK //////// HACK ////////

	
			
	for (var p in _order.products)
	{
		if (_order.products[p].qty > 0)
		{
			canSubmit = true;
			
			var item_name_value = _order.products[p].desc;
			var amount_value = _order.products[p].price;

			var coupons = '';
			for (var s in _order.products[p].specials)
			{
				/////// HACK /////// HACK //////// HACK ////////
				if (s != "Mailing List")
				{
					coupons += ((coupons == '') ? "Discounted: " : ", ") + s;
					amount_value -= _order.products[p].specials[s].getItemDiscount ? _order.products[p].specials[s].getItemDiscount(p) : 0.00 ;
				}
				/////// HACK /////// HACK //////// HACK ////////
			}
				
			if (coupons != '')
				item_name_value += " *** " + coupons + " ***";

			createPaypalItem(item_name_value, amount_value, _order.products[p].qty);
		}
	}

	/////// HACK /////// HACK //////// HACK ////////
	if (canSubmit)
	{
		if (give_the_customer_a_free_game)
		{
			// add that previously removed game back to the original quantity in case the back button is hit
			_order.products["GooseEggDiv"].qty++;
			createPaypalItem("**** Free " + _order.products["GooseEggDiv"].desc + " included with order ****", 0.00, 1);
		}
		
		var shipping = document.createElement('INPUT');
		shipping.type = 'hidden';
		shipping.className = "paypal_input";
		shipping.name = "shipping";
		shipping.id = "shipping";
		shipping.value = fix(_order.shipping);
		document.TahDahOrderForm.appendChild(shipping);
		
		// pass information through the payment system without alerting the customer.
		var form_info = document.createElement('INPUT');
		form_info.type = 'hidden';
		form_info.className = "paypal_input";
		form_info.name = "custom";
		form_info.id = "custom";
		form_info.value = "Order form location: " + document.location.href;
		document.TahDahOrderForm.appendChild(form_info);
	}

	return canSubmit;
}

function makeSpecial(element)
{
	var node = element;
	while(node.parentNode)
	{
		if (node.className != "item_row")
		{
			node = node.parentNode;
		}
		else
		{
			var item_desc_cell = null;
			for (td in node.childNodes)
			{
				if ((node.childNodes[td].className) && (node.childNodes[td].className == "item_desc"))
				{
					item_desc_cell = node.childNodes[td];
					break;
				}
			}
			
			if (item_desc_cell)
			{
				for (td in item_desc_cell.childNodes)
				{
					if ((item_desc_cell.childNodes[td].nodeName) &&
					    (item_desc_cell.childNodes[td].nodeName.toLowerCase() == "table"))
					{
						item_desc_cell.childNodes[td].className = "special";
						break;
					}
				}
			}

			break;
		}
	}
}

function parseProductName(product)
{
	return product.substring(0, product.indexOf("_"));
}

function update_quantity(quantity, refresh)
{
	var productName = parseProductName(quantity.name);
	_order.products[productName].qty = 0;
	if (quantity.value!="0" && quantity.value!="")
	{
		if (isNaN(quantity.value) || (quantity.value < 0))
		{
			// the quantity is bogus
			if (refresh == true)
			{
				update_calculations();
				update_form();
			}
			quantity.select();						// highlight the bogus input
			alert("Please enter a valid quantity");	// and tell the user to get a clue.
			return;
		}
		else
		{
			_order.products[productName].qty = parseInt(quantity.value);
			if (_order.products[productName].onQtyUpdate)
			{
				_order.products[productName].onQtyUpdate(productName);
			}
		}
	}
	
	if (refresh == true)
	{
		update_calculations();
		update_form();
	}
}

function replaceCheckout()
{
	var checkout_node = document.createElement('DIV');
	checkout_node.id = 'checkout_node';

	var reset_button = document.createElement('INPUT');
	reset_button.type = 'reset';
	reset_button.name = "Reset";
	reset_button.value = "Reset";
	checkout_node.appendChild(reset_button);
	
	var spacer = document.createElement('SPAN');
	spacer.innerHTML = "&nbsp;&nbsp;";
	checkout_node.appendChild(spacer);

	var submit_button = document.createElement('INPUT');
	submit_button.type = 'submit';
	submit_button.name = "Checkout";
	submit_button.value = "Checkout";
	//submit_button.onclick = document.TahDahOrderForm.submit;
	checkout_node.appendChild(submit_button);
	
	var noscript_node = document.getElementById('checkout');
	if (noscript_node)
	{
		var parent = noscript_node.parentNode;
		parent.removeChild(noscript_node);
		parent.appendChild(checkout_node);
	}

}

function applyQtyActions()
{
	with (document.TahDahOrderForm)
	{
		for (var i in elements)
		{
			if ((elements[i]) && (elements[i].name))
			{

				if ((elements[i].name.indexOf) && (elements[i].name.indexOf('_qty') != -1))
				elements[i].onblur = function() { update_quantity(this, true); };
			}
		}
	}
}

function applyPageArgs()
{
	if (page_args["coupon"])
	{
        applyCoupons(page_args["coupon"]);
	}
}


addLoadEvent(applyQtyActions);
addLoadEvent(applyPrices);
addLoadEvent(applyPageArgs);
addLoadEvent(replaceCheckout);



