$(function() {
	var cartCFC = "cms/cfc/cart.cfc"
	$cart = $('#cart');
	cartHeight = $cart.height();
	hideHeight = $cart.find('.hide').height() + $cart.find('.summery').height();
	var itemHtml = $("<div class='item'></div>");
	itemHtml.append("<a href='' class='name'></a>");
	itemHtml.append("<span class='cost'></span>")
	itemHtml.append("<span class='Qty'>Qty</span><span class='vcount'>1</span>");
	itemHtml.append("<button class='add'>+</button>");
	itemHtml.append("<button class='sub'>-</button>");
	itemHtml.append("<input type='hidden' size=1 value='1' class='count'>");
	
	itemHtml.append("<input class='id' type='hidden' value=''>");
	itemHtml.append("<input class='perItem' type='hidden' value=''><hr>");
	itemHeight = 65;
	$('#cart .add').live(
		'click',
		function() {
			var $this = $(this);

			$.ajax({
				type : "get",
				url : cartCFC,
				contentType : "application/json; charset=utf-8",
				dataType : 'json',
				data : ( {
					method : "addItem",
					id : $this.siblings('.id')[0].value,
					amount : 1
				})
			}).success(function(response) {
				if (response.SUCCESS) {
					var num = $this.siblings('.count')[0].value++;
					var val = (num + 1)* parseFloat($this.siblings('.perItem')[0].value);
					$this.siblings('.cost').text('$' + val.toFixed(2));
					total();
					$this.siblings('.vcount').text($this.siblings('.count')[0].value);
					toast("Item added");
				} else {
					toast("Action was unsuccessful please try again: " + response.ERRORS)
				}
			}).error(function(response) {
				toast("There was a network problem please try again");
			});		
			return false;
		});
	
	$('#cart .sub').live(
		'click',
		function(){
			var $this = $(this).parent();
			$.ajax({
				type : "get",
				url : cartCFC,
				contentType : "application/json; charset=utf-8",
				dataType : 'json',
				data : ( {
					method : "removeItem",
					id : $this.find('.id')[0].value,
					amount : 1
				})
			}).success(function(response) {
				var num = $this.find('.count')[0].value--;
				if (num === 1) {
					var items = $cart.find('.item');
					$this.slideUp('normal', function() {
						$this.remove();
					});
								
					if (items.length === 1) {
						$cart.find('.summery').slideUp();
						$cart.find('.checkoutBtn').fadeOut();
						var empty = itemHtml.clone()
							.addClass('empty')
							.css('display', 'none')
							.text('Your cart is empty');
						$cart.find('.summery').before(empty);
						empty.slideDown();
										
						$cart.animate({
							height : (cartHeight + 30 + 65) + 'px'
						})
					} else {
						$cart.animate( {
							height : (cartHeight + hideHeight + ((items.length - 1) * itemHeight)) + 'px'
						})
					}

				} else {
					var cost = $this.find('.perItem')[0].value;
					var val = (num - 1)	* parseFloat($this.find('.perItem')[0].value);
					$this.find('.cost').text('$'+ val.toFixed(2));
				}
				total();
				$this.find('.vcount').text($this.find('.count')[0].value);
				toast('item removed');
			}).error(function() {
				toast("There was a network problem please try again");
			});
		return false;
		});

	$('.summery').click(function() {
		if ($cart.height() === cartHeight) {
			var items = $cart.find('.item');
			$cart.animate( {
				height : (cartHeight + hideHeight + (items.length * itemHeight) + ($cart.find('.empty').length > 0? -30 : 0)) + 'px'
			});
			$(this).find('.expand>img').attr('src' , 'img/hdr_arrow.gif');
		} else {
			$cart.animate( {
				height : cartHeight + 'px'
			});
			$(this).find('.expand>img').attr('src' , 'img/hdr_arrow_up.gif');
		}
		return false;
	})

	$cart.find('.hide').click(function() {
		$cart.animate( {
			height : cartHeight + 'px'
		});
		$cart.find('.expand>img').attr('src' , 'img/hdr_arrow.gif');
	});

	$('.product .add')
			.click(
					function() {
						var $this = $(this);
						$
								.ajax( {
									type : "get",
									url : cartCFC,
									contentType : "application/json; charset=utf-8",
									dataType : 'json',
									data : ( {
										method : "addItem",
										id : $this.siblings('.id').text(),
										amount : 1
									}),
									success : function(response) {

										var $item = $cart
												.find('.item>.id[value=' + $this
														.siblings('.id').text() + ']');

										if ($item.length > 0) {
											var num = $item.siblings('.count')[0].value++;
											var val = (num + 1)
													* parseFloat($item
															.siblings('.perItem')[0].value);
											$item.siblings('.cost').text('$' +
													val.toFixed(2));
											
											$item.siblings('.vcount').text($item.siblings('.count')[0].value);
										} else {
											var newItem = itemHtml.clone(true);

											var content = $this.parent().find('.name');
											$cart.find('.summery').before(
															newItem
																	.html(
																			content
																					.html()
																					+ newItem
																							.html())
																	.css(
																			'display',
																			'none'));
											var price = $this
													.siblings('.price').text()
											newItem.find('.cost').text('$' + price);
											newItem.find('.count').value = 1;
											newItem.find('.id')[0].value = $this
													.siblings('.id').text();
											newItem.find('.perItem')[0].value = price;

											var $empty = $cart.find('.empty');
											if ($cart.height() === cartHeight) {
												$empty.remove();
												newItem.css('display', 'block');
											} else {
												if ($empty.length > 0) {
													$cart.find('.summery').slideDown();
													$cart.find('.checkoutBtn').slideDown();
													
													$cart
													.animate( {
														height : (hideHeight + cartHeight + itemHeight) + 'px'
													});
													
													$empty
															.slideUp(
																	'normal',
																	function() {
																		$empty
																				.remove();
																	});
												} else {
													$cart
															.animate( {
																height : (hideHeight + cartHeight + (itemHeight * $cart.find('.item').length)) + 'px'
															});
												}
												newItem.slideDown();
											}
										}
										total();
										toast('item added')
									},
									error : function() {
										toast("There was a network problem please try again");
									}
								})
						return false;
					});

	function total() {
		var total = 0;
		var itemTotal = 0;
		$cart.find('.item>.count').each(
				function() {

					itemTotal += Number(this.value);
					total += parseFloat($(this).siblings('.perItem')[0].value)
							* Number(this.value);
				})
		$('.summery .total').text('$' + total.toFixed(2));
		$('.summery .items').text(itemTotal + ' item(s)')
	}
});
