function FadeAlerts()
{
	window.setTimeout("Effect.Fade('alert-box', { afterFinish: ClearAlerts });", 3000);
}

function ClearAlerts()
{
	var alerts = document.getElementById('alert-box');
	var alertUL = alerts.getElementsByTagName('ul')[0];
	var items = alertUL.getElementsByTagName('li');
	while (items.firstChild)
	{
		items.removeChild(items.firstChild);
	}
	alerts.parentNode.removeChild(alerts);
}

var sCart = {
	ajaxRequest: null,
	fnSuccess: null,
	cartPage: false,
	lastPostal: null,
	doCheckout: null,
	deleteDiv: null,
	quantityDiv: null,
	shippingError: null,
	shippingErrorDescription: null,
	
	addItem: function(product_id, quantity, size_id, color_id, option1_id, option2_id, event)
	{
		if (!event) event = window.event;
		Event.extend(event);
		
		var params = { product_id: product_id, quantity: quantity };
		
		if (size_id) params.size_id = size_id;
		if (color_id) params.color_id = color_id;
		if (option1_id) params.option1_id = option1_id;
		if (option2_id) params.option2_id = option2_id;
		
		this.ajax("add", params, function(result) {
			if (Prototype.Browser.IE6) {
				var present = new Element('img', { src: '/images/present.png' });
				$(document.body).insert(present);
				present.setStyle({
					position: 'absolute',
					bottom: document.viewport.getHeight() - (event.pointerY() - present.getHeight()/2) + 'px',
					left: event.pointerX() - present.getWidth()/2 + 'px',
					zIndex: '999999'
				});
				
				present.morf({
					style: {
						opacity: '0'
					},
					duration: 0.3,
					afterFinish: function() {
						present.remove();
					}
				});
			}
			else {
				var present = new Element('img', { src: '/images/present.png' });
				$(document.body).insert(present);
				
				present.setStyle({
					position: 'absolute',
					bottom: document.viewport.getHeight() - (event.pointerY() - present.getHeight()/2) + 'px',
					left: event.pointerX() - present.getWidth()/2 + 'px',
					zIndex: '999999'
				});
				
				present.morf({
					style: {
						opacity: '0',
						bottom: -1 * document.viewport.getScrollOffsets().top + 'px',
						left: $('shopping_cart_drawer').down('.handle .btnCartTab_MyCart').cumulativeOffset().left + 'px'
					},
					duration: 0.4,
					afterFinish: function() {
						present.remove();
					}
				});
				
				if(!$('shopping_cart_drawer').hasClassName('open')) {
					$('shopping_cart_drawer').morf({
						style: {
							bottom: '-132px'
						},
						delay: 0.1,
						duration: 0.15
					});
					
					$('shopping_cart_drawer').morf({
						style: {
							bottom: '-152px'
						},
						delay: 0.3,
						duration: 0.15
					});
				}
			}
			
			if (result.title && result.url)
			{
				var html = "<div class=\"cartItem grey\">\r\n";
				html += "<a href=\"" + result.url + "\">\r\n";
				if (result.thumbnail)
				{
					html += "\t<img src=\"" + result.thumbnail + "\" />\r\n";
				}
				html += "\t<div class=\"product\">\r\n";
				html += "\t\t<h2>" + result.title + "</h2>\r\n";
				html += "\t</div>\r\n";
				html += "</a>\r\n";
				html += "</div>";
				
				$("drawer_summary").next(".drawer_scroller").down(".drawer_content").insert(html);
			}
			
			$$('.observesCart').invoke('fire', 'cart:refresh');

			sCart.updateCart(result.totalItems);
			sCart.updateCartTotal(result.total, result.subTotal);

			sCart.lastPostal = null;
		});
	},
	
	deleteItem: function(obj, product_id, size_id, color_id, option1_id, option2_id)
	{
		var params = { product_id: product_id };
		
		if (typeof size_id != "undefined" && size_id) params.size_id = size_id;
		if (typeof color_id != "undefined" && color_id) params.color_id = color_id;
		if (typeof option1_id != "undefined" && option1_id) params.option1_id = option1_id;
		if (typeof option2_id != "undefined" && option2_id) params.option2_id = option2_id;
		
		this.deleteDiv = $(obj).up(".cartItem", 0);
		
		this.ajax("delete", params, function(result) {
			if (result.totalItems == 0)
			{
				location.href = "/cart";
			}
			else
			{
				sCart.updateTotals(result.subTotal, result.shippingTotal, result.taxTotal, result.total, result.country);
				sCart.alertShippingError(result.shippingError, result.shippingErrorDescription);
	
				if (sCart.deleteDiv)
				{
					$(sCart.deleteDiv).remove();
					sCart.zebra();
				}
				
				sCart.lastPostal = $("postal_code").value;
			}
		}, function(result) {
			sCart.deleteDiv = null;
			sCart.error(result.error);
		});
	},
	
	setQuantity: function(obj, product_id, quantity, size_id, color_id, option1_id, option2_id)
	{
		quantity = Math.abs(parseInt(quantity));
		if (isNaN(quantity)) quantity = 0;
		
		obj.value = quantity;
		
		if (quantity == 0)
		{
			this.deleteItem(obj, product_id, size_id, color_id, option1_id, option2_id);
			return;
		}
		
		var params = { product_id: product_id, quantity: quantity };
		
		if (typeof size_id != "undefined" && size_id) params.size_id = size_id;
		if (typeof color_id != "undefined" && color_id) params.color_id = color_id;
		if (typeof option1_id != "undefined" && option1_id) params.option1_id = option1_id;
		if (typeof option2_id != "undefined" && option2_id) params.option2_id = option2_id;
		
		this.quantityDiv = $(obj).up(".cartItem", 0);

		this.ajax("quantity", params, function(result) {
			sCart.updateCart(result.totalItems);
			sCart.updateTotals(result.subTotal, result.shippingTotal, result.taxTotal, result.total, result.country);
			sCart.alertShippingError(result.shippingError, result.shippingErrorDescription);
			sCart.lastPostal = $("postal_code").value;
		});
	},
	
	clearCart: function()
	{
		this.ajax("clear", { }, function(result) {
			location.href = "/cart";
		});
	},
	
	/*
	updateCartTotal: function(total)
	{
		if ($("cart_total")) $("cart_total").update(total.toFixed(2));
		if ($("cart_drawer_total")) $("cart_drawer_total").update(total.toFixed(2));
	},
	*/
	
	getShippingTotal: function()
	{
		if ($("shipping_total").innerHTML && $("postal_code").value == this.lastPostal)
		{
			return $("shipping_total").innerHTML;
		}
		
		if ($("get_shipping_estimate")) $("get_shipping_estimate").addClassName('working');

		var post = null;

		if ($("postal_code"))
		{
			post = $("postal_code").value;
			$("postal_code").removeClassName("invalid");
		}
		else if ($("shipping_postal_code"))
		{
			post = $("shipping_postal_code").value;
		}
		
		this.ajax("shippingtotal", { postal_code: post }, function(result) {
			$("postal_code").value = $("postal_code").value.replace(/\s+/g, "");
			
			if ($("postal_code").value != $("postal_code").value.toUpperCase())
			{
				$("postal_code").value = $("postal_code").value.toUpperCase();
			}
			
			sCart.updateTotals(result.subTotal, result.shippingTotal, result.taxTotal, result.total, result.country);
			sCart.alertShippingError(result.shippingError, result.shippingErrorDescription);

			this.lastPostal = $("postal_code").value;
		
			if (this.doCheckout)
			{
				location.href = "/cart/checkout";
			}

			this.doCheckout = null;
		}, function(result) {
			if ($("get_shipping_estimate"))
			{
				$("get_shipping_estimate").removeClassName("working");
			}
			if ($("postal_code"))
			{
				$("postal_code").addClassName("invalid");
				$("postal_code").focus();
				alert("You must enter a valid postal code.");
			}
			
			sCart.updateTotals();
		});
	},
	
	checkout: function()
	{
		if (this.ajaxRequest)
		{
			window.setTimeout("sCart.checkout()", 500);
		}
		else if (!$("postal_code").value || $("postal_code").value == "Postal Code")
		{
			alert("You must enter a postal code.");
			
			$("postal_code").addClassName("invalid");
			$("postal_code").focus();
		}
		else if ($("shipping_total").innerHTML == "--.--")
		{
			if (this.shippingError && this.shippingErrorDescription)
			{
				this.alertShippingError(this.shippingError, this.shippingErrorDescription);
				return false;
			}
			else
			{
				alert("You must enter a valid postal code.");
				
				$("postal_code").value = "";
				$("postal_code").addClassName("invalid");
				$("postal_code").focus();
			}
		}
		else if ($("postal_code").value != this.lastPostal)
		{
			this.doCheckout = true;
			this.getShippingTotal();
		}
		else
		{
			location.href = "/cart/checkout";
		}
	},
	
	zebra: function()
	{
		var div = document.getElementById("cartContents");
		var divs = div.getElementsByTagName("div");

		var j = 0;
		
		for (var i = 0; i < divs.length; i++)
		{
			if (divs[i].hasClassName("cartItem"))
			{
				if (j % 2)
				{
					if (divs[i].hasClassName("grey")) divs[i].removeClassName("grey");
				}
				else
				{
					if (!divs[i].hasClassName("grey")) divs[i].addClassName("grey");
				}
				j++;
			}
		}
	},
	
	ajax: function(action, params, fnSuccess, fnError)
	{
		if (typeof fnError == "undefined") fnError = function(result) { sCart.error(result.error) };
		
		if (!this.ajaxRequest)
		{
			this.ajaxRequest = new Ajax.Request("/cart/ajax/" + action, { method: "get", parameters: params, onSuccess: this.ajaxSuccess, onFailure: this.ajaxFailure });
			this.fnSuccess = fnSuccess;
			this.fnError = fnError;
		}
		else
		{
			var fn = function() { sCart.ajax(action, params, fnSuccess, fnError); };
			window.setTimeout(fn, 500);
		}
	},
	
	ajaxSuccess: function(xmlRequest)
	{
		var c = xmlRequest.responseXML.documentElement;
		
		var result = {};
		
		for (var i = 0; i < c.attributes.length; i++)
		{
			result[c.attributes.item(i).name] = c.attributes.item(i).value;
		}
		
		if (!result.error)
		{
			sCart.fnSuccess(result);
		}
		else
		{
			sCart.fnError(result);
		}
		
		sCart.ajaxRequest = null;
		sCart.fnSuccess = null;
		sCart.fnError = null;
	},
	
	ajaxFailure: function(xmlRequest)
	{
		this.error("HTTP error " + xmlRequest.status + ", could not process your request.");
	},

	error: function(str)
	{
		alert("Cart error: " + str);
	},
		
	updateCart: function(itemCount, quiet)
	{
		if (typeof quiet == "undefined") quiet = false;
		
		$('shopping_cart_top_link').down('.cartNav').update('I have ' + itemCount + ' item' + ((itemCount == 1) ? '' : 's') + ' in my cart');
		
		if ($("drawer_summary"))
		{
			$("drawer_summary").down("h3.observesCart").update(itemCount + " item" + ((itemCount == 1) ? "" : "s"));
		}

		if (!quiet)
		{
			new Effect.Highlight($('shopping_cart_top_link').down('.cartNav'), {startcolor: '#F26522', endcolor: '#EAEAEA', keepBackgroundImage: true});
		}
	},
	
	updateCartTotal: function(total, subtotal)
	{
		if ($("cart_total"))
		{
			if (typeof total == "undefined" || total == "")
			{
				$("cart_total").update("--.--");
			}
			else
			{
				$("cart_total").update(new Number(total).toFixed(2));
			}
		}

		if ($("cart_total_drawer"))
		{
			if (typeof subtotal == "undefined" || subtotal == "")
			{
				$("cart_total_drawer").update("--.--");
			}
			else
			{
 				$("cart_total_drawer").update(new Number(subtotal).toFixed(2));
 			}
		}
	},
	
	updateTaxTotal: function(total)
	{
		if ($("GST_total"))
		{
			if (typeof total == "undefined" || total == "")
			{
				$("GST_total").update("--.--");
			}
			else
			{
				$("GST_total").update(new Number(total).toFixed(2));
			}
		}
	},
	
	updateShippingTotal: function(total, country)
	{
		if ($("shipping_total"))
		{
			if (typeof total == "undefined" || total == "")
			{
				$("shipping_total").update("--.--");
			}
			else
			{
				$("shipping_total").update(new Number(total).toFixed(2));
			}
		}
			
		if ($("get_shipping_estimate"))
		{
			$("get_shipping_estimate").removeClassName("working");
		}
		
		if (country == "CA")
		{
			$("GST_total_area").show();
		}
		else
		{
			$("GST_total_area").hide();
		}
	},
	
	alertShippingError: function(errno, description)
	{
		if (typeof errno != "undefined" && typeof description != "undefined" && errno && description)
		{
			this.shippingError = errno;
			this.shippingErrorDescription = description;
			
			alert("UPS Error " + errno + ": " + description);
		}
		else
		{
			this.shippingError = null;
			this.shippingErrorDescription = null;
		}
 	},
	
	updateSubTotal: function(total)
	{
		if ($("subtotal"))
		{
			if (typeof total == "undefined" || total == "")
			{
				$("subtotal").update("--.--");
			}
			else
			{
				$("subtotal").update(new Number(total).toFixed(2));
			}
		}
	},

	updateTotals: function(subTotal, shippingTotal, taxTotal, total, country)
	{
		this.updateSubTotal(subTotal);
		this.updateShippingTotal(shippingTotal, country);
		this.updateTaxTotal(taxTotal);
		this.updateCartTotal(total, subTotal);
	},
	
	updateDogName: function()
	{
		document.getElementById("dogNamePaypal").value = document.getElementById("dogName").value;
		document.getElementById("dogNameCC").value = document.getElementById("dogName").value;
	}
};

document.observe("dom:loaded", function() {
	$$('.observesCart').invoke('fire', 'cart:refresh', 'quiet');
});

var ____cart = {
	jar: null,
	country: null,
	
	initialize: function() {
		this.jar = new CookieJar({
			expires:(24*3)*24*60*60,   // three days in seconds
			path: '/'
		});
		
		if(!this.getItems()) {
			this.jar.put('cartItems', []);
		};
		
		// alert($H({items: this.getItems()}).toJSON());
	},
	
	/** 
	 *	itemData: {
	 *		id: [int],
	 *		name: [string],
	 *		price: [float],
	 *		icon: [string],
	 *		options: [string]
	 *	}
	 *	
	 *	cartItem: {
	 *		count: [int],
	 *		itemData: [itemData]
	 *	}
	**/
	addItem: function(itemData, numberToAdd) {
		var items = this.getItems();
		
		$H(itemData).each(function(pair) {
			if(Object.isString(pair.value)) {
				itemData[pair.key] = pair.value.gsub(/'/, '');
			}
		});
		
		for(var index = 0; index < items.size(); index++) {
			var cartItem = items[index];
				
			if($H(cartItem.itemData).toJSON() == $H(itemData).toJSON()) {
				cartItem.count = parseInt(cartItem.count) + parseInt(numberToAdd);
				this.jar.put('cartItems', items);
				$$('.observesCart').invoke('fire', 'cart:refresh');
				return;
			}
		}
		
		items.push({
			count: numberToAdd,
			itemData: itemData
		});
		
		this.jar.put('cartItems', items);
		$$('.observesCart').invoke('fire', 'cart:refresh');
		// alert(items.toJSON());
	},
	
	getTotalItems: function() {
		var count = 0;
		
		this.getItems().each(function(item) {
			count += parseInt(item.count);
		});
		
		return count;
	},
	
	getTotalDimentions: function() {
		var dimensions = {
			length: 0,
			width: 0,
			height: 0,
			weight: 0
		};
		
		cart.getItems().each(function(item) {
			dimensions.length += (parseInt(item.itemData.dimensions.length) * item.count);
			dimensions.width = Math.max(dimensions.width, parseInt(item.itemData.dimensions.width));
			dimensions.height = Math.max(dimensions.height, parseInt(item.itemData.dimensions.height));
			dimensions.weight += (parseInt(item.itemData.dimensions.weight) * item.count);
		});
		
		return dimensions;
	},
	
	/**
	 *	pairs: [
	 *		{
	 *			index: [int],
	 *			count: [int]
	 *		},
	 *		{
	 *			index: [int],
	 *			count: [int]
	 *		},
	 *	...
	 *	]
	**/
	updateCounts: function(pairs) {
		var items = this.getItems();
		
		pairs.each(function(pair) {
			items[pair.index].count = parseInt(pair.count);
		});
		
		var index = 0;
		while(items[index]) {
			var item = items[index];
			if(!item.count || item.count <= 0) {
				items.splice(index, 1);
				index--;
			}
			index++;
		}
		
		this.jar.put('cartItems', items);
		
		$$('.observesCart').invoke('fire', 'cart:refresh');
		if($('get_shipping_estimate')) $('get_shipping_estimate').fire('dom:click');
	},
	
	clearCart: function() {
		this.jar.put('cartItems', []);
		$$('.observesCart').invoke('fire', 'cart:refresh');
	},
	
	getItems: function() {
		return this.jar.get('cartItems');
	},
	
	getSubTotal: function() {
		var items = this.getItems();
		var total = 0.0;
		
		items.each(function(item) {
			total += item.count * item.itemData.price;
		});
		
		return total;
	},
	
	getShippingTotal: function() {
		var total = 0.0;
		
		if($('shipping_total')) {
			var shippingTotal = parseFloat($('shipping_total').innerHTML);
			total += (shippingTotal >= 0)? shippingTotal:0;
		}
		
		return total;
	},
	
	getTaxTotal: function() {
		if(this.country == 'CA')
			return this.getSubTotal() * 0.05;
		else
			return 0.0;
	},
	
	getSubTotal: function() {
		return this.getSubTotal() + this.getShippingTotal();
	},
	
	getTotal: function() {
		return this.getSubTotal() + this.getShippingTotal() + this.getTaxTotal();
	}
};

/*
document.observe("dom:loaded", function() {
	cart.initialize();
	
	$$('[cartItem]').each(function(item) {
		item.observe('click', function(event) {
			var itemData = item.readAttribute('cartItem').evalJSON();
			var count = 1;
			
			if(Object.isFunction(itemData.count)) 
				count = itemData.count(item);
			else
				count = itemData.count;
			
			delete itemData.count;
			
			if(Object.isFunction(itemData.price)) 
				itemData.price = parseFloat(itemData.price(item));
			
			if(Object.isFunction(itemData.options)) 
				itemData.options = itemData.options(item);
			if(!itemData.options) itemData.options = '';
			
			itemData.original_url = window.location.href;
			
			cart.addItem(itemData, count);
			
			if(Prototype.Browser.IE6) {
				var present = new Element('img', { src: '/images/present.png' });
				$(document.body).insert(present);
				present.setStyle({
					position: 'absolute',
					bottom: document.viewport.getHeight() - (event.pointerY() - present.getHeight()/2) + 'px',
					left: event.pointerX() - present.getWidth()/2 + 'px',
					zIndex: '999999'
				});
				
				present.morf({
					style: {
						opacity: '0'
					},
					duration: 0.3,
					afterFinish: function() {
						present.remove();
					}
				});
			}
			else {
				var present = new Element('img', { src: '/images/present.png' });
				$(document.body).insert(present);
				present.setStyle({
					position: 'absolute',
					bottom: document.viewport.getHeight() - (event.pointerY() - present.getHeight()/2) + 'px',
					left: event.pointerX() - present.getWidth()/2 + 'px',
					zIndex: '999999'
				});
				
				present.morf({
					style: {
						opacity: '0',
						bottom: -1 * document.viewport.getScrollOffsets().top + 'px',
						left: $('shopping_cart_drawer').down('.handle .btnCartTab_MyCart').cumulativeOffset().left + 'px'
					},
					duration: 0.4,
					afterFinish: function() {
						present.remove();
					}
				});
				
				if(!$('shopping_cart_drawer').hasClassName('open')) {
					$('shopping_cart_drawer').morf({
						style: {
							bottom: '-132px'
						},
						delay: 0.1,
						duration: 0.15
					});
					
					$('shopping_cart_drawer').morf({
						style: {
							bottom: '-152px'
						},
						delay: 0.3,
						duration: 0.15
					});
				}
			}
			
			event.stop();
		});
	});
	
	if($('shopping_cart_top_link')) $('shopping_cart_top_link').down('.cartNav').addClassName('observesCart');
	if($('shopping_cart_top_link')) $('shopping_cart_top_link').down('.cartNav').observe('cart:refresh', function(event) {
		this.update('I have ' + cart.getTotalItems() + ' item' + ((cart.getTotalItems() == 1)? '':'s') + ' in my cart');
		if(event.memo != 'quiet')
			new Effect.Highlight(this.identify(), {startcolor: '#F26522', endcolor: '#EAEAEA', keepBackgroundImage: true});
	});
	
	if($('update_cart_total')) $('update_cart_total').observe('click', function(event) {
		var pairs = [];
		$$('#main .cartItem').each(function(cartItem) {
			pairs.push({
				index: cartItem.readAttribute('cartIndex'),
				count: cartItem.down('.amount .txtQtyCart').value
			});
		});
		
		cart.updateCounts(pairs);
		
		event.stop();
	});
	
	$$('[cartMarker]').invoke('observe', 'cart:refresh', function(event) {
		var cartMarker = this;
		cartMarker.show();
		
		cartMarker.up().select('.cartItem').invoke('remove');
		
		cart.getItems().each(function(cartItem, index) {
			var itemDiv = new Element('div').addClassName('cartItem');
			if(index % 2 == 0) itemDiv.addClassName('grey');
			cartMarker.insert({before: itemDiv});
			
			var itemImage = new Element('img', {src: cartItem.itemData.icon});
			itemDiv.insert(itemImage);
			
			var itemProduct = new Element('div').addClassName('product');
			itemProduct.insert(new Element('h2').update(cartItem.itemData.name));
			itemProduct.insert(new Element('p').update(cartItem.itemData.options));
			itemDiv.insert(itemProduct);
			
			var itemAmount = new Element('div').addClassName('amount');
			itemAmount.insert(new Element('input', { type: 'text', value: cartItem.count }).addClassName('txtQtyCart'));
			itemAmount.insert(new Element('p').update('x &nbsp;&nbsp;&nbsp; $ ' + cartItem.itemData.price.toFixed(2)));
			itemDiv.insert(itemAmount);
			
			itemDiv.insert(new Element('div').addClassName('clear'));
			
			itemDiv.writeAttribute('cartIndex', index);
		});
		
		cartMarker.hide();
		
		if($('cart_total')) {
			$('cart_total').update(cart.getTotal().toFixed(2));
			$('GST_total').update(cart.getTaxTotal().toFixed(2));
			
			if(cart.getTaxTotal() > 0)
				$('GST_total_area').show();
			else
				$('GST_total_area').hide();
		}
	});
	
	$('drawer_summary').down('h3').observe('cart:refresh', function(event) {
		this.update(cart.getTotalItems() + ' ITEM' + ((cart.getTotalItems() == 1)? '':'S'));
	});
	
	$('cart_total_drawer').observe('cart:refresh', function(event) {
		this.update(cart.getItemTotal().toFixed(2));
	});
	
	if($('checkout_info')) $('checkout_info').down('#payByCC .price .observesCart').observe('cart:refresh', function(event) {
		this.update(cart.getTotal().toFixed(2));
	});
	
	$$('.observesCart').invoke('fire', 'cart:refresh', 'quiet');
});
*/