function updateCartCounts(req) {
	if(!req) {
		new Ajax.Request(
			'/ajax/getCartSummary.php',
			{
				method:'post',
				parameters:'count=true',
				onComplete: updateCartCounts
			}
		)
	} else {
		var c = getText($TG(req.responseXML, 'count')[0])
		updateCountSpans(c)
	}
}

function updateCountSpans(c) {
	var text = '(' + c + ' item' + (c==1?'':'s') + ' in cart) :: <a href="cart.php">checkout/view</a>';
	$('cart').innerHTML = text
	try { $('bottomCartCount').innerHTML = text
	} catch (e) { /* may not exist on a given page */ ; }
}


function removeItemFromCart(id) {
	Alert.setContents('<div align="center"><strong>Really remove from cart?</strong><br /><a href="javascript:reallyRemoveItemFromCart(\'' + id + '\');">remove item</a> &nbsp; &nbsp; <a href="javascript:Alert.hide();">cancel</a></div>')
	var pos = Position.cumulativeOffset($('remove_' + id))
	Alert.setPosition(pos[0]-100, pos[1]-50)
	Alert.show()
}

function reallyRemoveItemFromCart(id) {
	var params = getize(
		'id', id
	)
	var pos = Position.cumulativeOffset($('remove_' + id))
	Alert.setPosition(pos[0]-100, pos[1]-50)
	var html = '<div style="width:210px;text-align:center;">Removing item from cart...</div>'
	Alert.setContents(html)
	Alert.show()
	new Ajax.Request(
		'/ajax/removeItemFromCart.php',
		{
			method: 'post',
			parameters: params,
			onComplete: removeItemFromCartHandler
		}
	)
	urchinTracker('/cart/removeitem');
}

function removeItemFromCartHandler(req) {
	var elem = $TG(req.responseXML, 'status')[0]
	updateCountSpans(getAttribute(elem, 'count'))
	updateCartSummary()
	var message = getText(elem)
	var id = getAttribute(elem, 'id')
	if (message == 'OK') {
		$('item_' + id).style.visibility = 'hidden';
		setTimeout(function() {$('item_' + id).style.display = 'none';}, 500)
		Alert.hide()
	} else {
		var html = '<div style="width:210px;text-align:center;">There was an error in trying to remove this item from you cart. Please try again.</div>'
		var pos = Position.cumulativeOffset($('addToCartLink'))
		Alert.setPosition(pos[0]+20,pos[1]+20)
		Alert.setContents(html)
		Alert.show()
	}
}

function updateCartSummary(req) {
	if(!req) {
		new Ajax.Request(
			'/ajax/getCartSummary.php',
			{
				method:'post',
				parameters:'full=true',
				onComplete: updateCartSummary
			}
		)
	} else {
		var content = getText($TG(req.responseXML, 'content')[0])
		$('cartSummary').innerHTML = content
		SalesTax.calculate()
	}
}

function addPQToCart(id, cat, cid) {
	var pos = Position.cumulativeOffset($('add_' + id))
	Alert.setPosition(pos[0]+100,pos[1]-50)
	var qtyStr = 1;
	try {
		qtyStr = $F('qty_' + id);
	} catch(e) {}
	var qty
	try {
		qty = parseInt(qtyStr, 10)
		if(qty+'' != qtyStr) {
			throw 'exception'
		}
	} catch (e) {
		Alert.setContents('Please enter a valid quantity')
		Alert.show()
		return
	}
	var color = $('clr_' + id).innerHTML;
	var params = getize(
		'id', id,
		'color', color,
		'quantity', qty,
		'cat', cat,
		'catid', cid
	)
	var html = '<div style="width:210px;text-align:center;">Adding custom wording to cart...</div>'
	Alert.setContents(html)
	Alert.show()
	new Ajax.Request(
		'/ajax/addItemToCart.php',
		{
			method: 'post',
			parameters: params,
			onComplete: addPQToCartHandler
		}
	)
	urchinTracker('/cart/add/' + cat + '/' + id);
}

function addPQToCartHandler(req) {
	var elem = $TG(req.responseXML, 'status')[0]
	updateCountSpans(getAttribute(elem, 'count'))
	var id = getAttribute(elem, 'id')
	var message = getText(elem)
	if (message == 'OK') {
		message = '<div style="font:100 12px Arial;" align="left"><strong>This item has been added to your cart.</strong>' +
					'<br /><a href="javascript:Alert.hide();">Keep Shopping</a>'+ 
					'<br /><a href="cart.php">View Cart/Check Out</a>'
	}
	var html = '<div style="width:210px;text-align:center;">' + message + '</div>'
	var pos = Position.cumulativeOffset($('add_' + id))
	Alert.setPosition(pos[0]+100,pos[1]-50)
	Alert.setContents(html)
	Alert.show()
}

function addCustomItemToCart(req) {
	if(!req) {
		var inputs = document.getElementsByTagName('input')
		var size = 0
		for(var i=0; i<inputs.length; i++) {
			if(inputs[i].type == 'radio' && inputs[i].name == 'product' && inputs[i].checked) {
				size = inputs[i].value.split('|')[1]
				break
			}
		}
		var params = getize(
			'size', size,
			'font', previewAtts['font'],
			'color', previewAtts['color'],
			'wording', previewAtts['wording'],
			'quantity', $F('quantity')
		)
		var pos = Position.cumulativeOffset($('addToCartLink'))
		Alert.setPosition(pos[0]-180,pos[1]-50)
		var html = '<div style="width:210px;text-align:center;">Adding custom wording to cart...</div>'
		Alert.setContents(html)
		Alert.show()
		new Ajax.Request(
			'/ajax/addCustomItemToCart.php',
			{
				method: 'post',
				parameters: params,
				onComplete: addCustomItemToCart
			}
		)
		urchinTracker('/cart/add/custom');
	} else {
		var elem = $TG(req.responseXML, 'status')[0]
		updateCountSpans(getAttribute(elem, 'count'))
		var message = getText(elem)
		if (message == 'OK') {
			message = '<div style="font:100 12px Arial;" align="left"><strong>This item has been added to your cart.</strong>' +
						'<br /><a href="javascript:{Alert.hide(); scrollTo(0,0)};">Keep Shopping</a>'+ 
						'<br /><a href="cart.php">View Cart/Check Out</a>'
		}
		var html = '<div style="width:210px;text-align:center;">' + message + '</div>'
		var pos = Position.cumulativeOffset($('addToCartLink'))
		Alert.setPosition(pos[0]-180,pos[1]-50)
		Alert.setContents(html)
		Alert.show()
	}
	
}

function textAreaEffects() {
	var tas = $TG(document, 'textarea')
	var z = tas.length
	for(var i=0; i<z; i++) {
		if(!tas[i].id || tas[i].id.toString().length < 1) {
			tas[i].id = 'taComments' + i
		}
		if(Element.hasClassName(tas[i].id, 'inactive')) {
			var on = function() {
						Element.addClassName( this.id , 'active')
					}
			var off = function() {
						Element.removeClassName( this.id , 'active')
					}
			Event.observe(tas[i], 'focus', on , false);
			Event.observe(tas[i], 'blur', off , false);
		}
	}
}

function saveInstructions(id) {
	var elemId = 'ta_' + id
	var tas = $TG(document, 'textarea')
	var z = tas.length
	for(var i=0; i<z; i++) {
		if(!tas[i].id || tas[i].id.toString() == elemId) {
			if(tas[i].value == 'Comments...')
				return
			var params = getize(
				't', tas[i].value,
				'i', id
			)
			//window.open('/src/ajax/updateItemComments.php?' + params)
			//return
			new Ajax.Request(
				'/ajax/updateItemComments.php',
				{
					method: 'post',
					parameters: params,
					onComplete: saveInstructionsHandler
				}
			)
			Alert.setContents('Saving instructions...')
			var pos = Position.cumulativeOffset($('remove_' + id))
			Alert.setPosition(pos[0]-80, pos[1]-60)
			Alert.show()
			return
		}
	}
}

function saveInstructionsHandler(req) {
	var status = getText($TG(req.responseXML, 'status')[0])
	if(status == 'OK') {
		Alert.setContents('Saved.')
	} else {
		Alert.setContents('There was an error.<br />Please try again.')
	}
}


Event.observe(window, 'load', textAreaEffects, false);





var SalesTax = {
	idaho : false,
	amount : 0.0,
	calculate : function() {
		var subTotal = parseFloat($('subSpan').innerHTML.substring(1))
		var tax = parseFloat((this.idaho) ? subTotal * 0.06 : 0)
		var sh = parseFloat($('shSpan').innerHTML.substring(1))
		var total = subTotal + tax + sh
		tax = tax.toFixed(2) + ''
		if(tax.length <= 3)
			tax = '0' + tax
		$('taxSpan').innerHTML = '$' + tax
		$('totalSpan').innerHTML = '$' + total.toFixed(2)
	},
	toggle : function() {
		this.idaho = !this.idaho
		this.calculate()
	}
}


function updateShippingPreference(req) {
	if(!req) {
		new Ajax.Request(
			'/ajax/updateShippingPreference.php',
			{
				method: 'post',
				parameters: 'shipping=' + getSelectedRadioByName('sahoption'),
				onComplete: updateShippingPreference
			}
		)
	} else {
		updateCartSummary();
	}
}



function promptForCoupon() {
	Alert.setContents('<form onsubmit="validateCouponCode();return false;"><strong>Enter your code:</strong><br />' +
			'<input type="text" id="couponCode" style="width:120px;margin:10px 0 10px;" /><br />' +
			'<input type="submit" value="Apply" /></form>');
	var pos = Position.cumulativeOffset($('haveCouponA'));
	Alert.setPosition(pos[0], pos[1]+22);
	Alert.show();
}


function validateCouponCode() {
	var code = $F('couponCode').trim();
	if(code.length < 1) {
		Alert.hide();
		return;
	}
	Alert.setContents('Applying coupon, please wait...');
	new Ajax.Request(
		'/ajax/applyCoupon.php',
		{	method: 'post',
			parameters: 'code=' + code,
			onComplete: applyCouponCode
		}
	);
}

function proceedToPayPal() {
	new Ajax.Request(
		'/ajax/order.php',
		{	method: 'post',
			parameters: 'id=' + $('order_id').value,
			onComplete: moveOnToPayPal
		}
	);
}

function moveOnToPayPal() {
	document.paypalform.submit();
}


function applyCouponCode(req) {
	var xmlDoc = req.responseXML;
	var discount = getAttribute(xmlDoc.getElementsByTagName('discount')[0], 'value');
	discount = Math.round(parseFloat(discount) * 100);
	if(isNaN(discount)) {
		Alert.setContents('Wholesale discount.');
		urchinTracker('/cart/discountapplied');
	} else if(discount == 0) {
		Alert.setContents('Invalid Coupon Code<br />No Coupon Applied.');
	} else {
		Alert.setContents(discount + '% discount applied.');
		urchinTracker('/cart/discountapplied');
	}
	updateCartSummary();
	setTimeout(Alert.hide.bind(Alert), 1250);
}






