// Cart Class 

var Cart = Class.create({

	initialize: function() {
	
		// instantiate service
		this.service = new CartService();
	
		// containers
		this.container = $('cart-container');
		this.total_container = $('cart-total');
		this.sub_total_container = $('cart-sub-total')
		this.shipping_total_container = $('cart-shipping-total')
		this.qty_container = $('cart-qty');
		this.item_list_container = $('cart-list-container');
		this.item_list_wrapper = $('cart-list-wrapper');
		this.item_list_container.open = false;
		
		// cart items 
		this.items = $H();
		this.getItems();
		
		// get the total
		this.updateTotal();
		
		// observes
		if(live.page.page_url=='confirm' || live.page.page_url=='receipt') {
		
			
			this.showList = function() {
				return false;
			};
			this.hideList = function() {
				return false;
			}
			
			Event.observe(window,'load', function() {
			
				this.item_list_container.show();
			
			}.bind(this));
			
			
		} else {
			
			this.cart_on = this.container.observe('mouseenter',this.showList.bind(this));
			this.cart_off = this.container.observe('mouseleave', this.hideList.bind(this));
			
		}
		
	},
	
	getItems: function() {
		
		$$('.cart-item').each(function(cart_item) {
			
			var id = cart_item.id.gsub('cart-item-','');
			var qty_field = $('cart-item-qty-'+id);
			var price_field = $('cart-item-price-'+id);
			
			if(id && qty_field) {
				
				var cart_object = {
					element: cart_item,
					qty_field: qty_field,
					qty: parseInt(qty_field.value),
					price_field: price_field,
					price: parseInt(price_field.value)
				} 
				
				this.items.set(id,cart_object);
			}
			
		}.bind(this));
		
		
		if($('cart-item-empty')) {
		
			$('cart-btn-checkout').hide();
		
		} else {
		
			if(live.page.page_url!='confirm' && live.page.page_url!='receipt') {
			
				$('cart-btn-checkout').show();
				
			}
		
		}
		
	},
	
	updateTotal: function() {
		
		//this.getTotal();
		
		this.service.get_total.call();
		this.service.get_total.result = function(result) {
			
			if(result) {
			
				this.sub_total = result.sub_total;
				this.shipping = result.shipping;
				this.total = result.total;
				this.qty = result.qty;
				
				this.shipping_total_container.update('$'+this.shipping);
				this.sub_total_container.update('$'+this.sub_total);
				this.total_container.update('$'+this.total);
				
				new Effect.Highlight('cart-total-container', {
					startcolor:'#d15902',
					endcolor:'#f17319'
				});
				
				this.qty_container.update(this.qty)
				
			} else {
			
				this.sub_total = 0;
				this.shipping = 0;
				this.total = 0;
				this.qty = 0;
			}
			
			this.getItems();
			
		}.bind(this);	
		
	},
	
	updateQty: function(cart_item_id,qty) {	
		
		var qty = parseInt(qty);
		
		var cart_item_id = parseInt(cart_item_id);
		
		if(qty) {
			
			var original_qty = this.items.get(cart_item_id).qty;
			
			if(original_qty != qty) {
				
				this.service.update_qty.call(cart_item_id,qty);
				this.service.update_qty.result = function(cart_item) {
					
					this.displayItem(cart_item,true);
					this.updateTotal();
					
				}.bind(this);
				
			} else {
				return false;
			}
			
		} else {
			return false;
		}
	
	},
	
	displayItem: function(cart_item,item_exsists) {
	
		cart_item.cart_item_price = Math.format_number(cart_item.cart_item_price,{ currency:'$' });
		
		if($('cart-item-empty')) {
			$('cart-item-empty').remove();
		}
		
		if(item_exsists) {
			
			this.items.get(cart_item.cart_item_id).qty_field.value = cart_item.cart_item_qty;
			this.items.get(cart_item.cart_item_id).price_field.value = cart_item.cart_item_price*cart_item.cart_item_qty;
			
		} else {
		
			
			var new_cart_item = Builder.node('div', { id: 'cart-item-'+cart_item.cart_item_id, className:'cart-item wrapper', style:'display:none'},[
			
				Builder.node('div',{id:'item-'+cart_item.item_sku, style:'display:none;'}),
				
				Builder.node('input',{ className:'cart-item-remove', type:'button', value:' ', className:'cart-item-remove', onclick:'Cart.removeItem('+cart_item.cart_item_id+')'}),
                      		                                                                                                 
 		        Builder.node('div',{className:'cart-item-description'},[
 		                Builder.node('strong',cart_item.product_name),
 		                Builder.node('em',cart_item.cart_item_description.truncate(30, '...'))
 		        ]),

				Builder.node('input',{ id:'cart-item-qty-'+cart_item.cart_item_id, type:'text', size:'2', value:cart_item.cart_item_qty, className:'cart-item-qty', onkeyup:'Cart.updateQty('+cart_item.cart_item_id+',this.value);'}),

				Builder.node('div',{ id:'cart-item-price-'+cart_item.cart_item_id, className:'cart-item-price'},cart_item.cart_item_price)
     		        
     		]);
			
     		
     		this.item_list_wrapper.appendChild(new_cart_item);
     		
     		$('cart-item-'+cart_item.cart_item_id).show();
		}
		
	},
	
	deleteItem: function(cart_item_id) {
		
		this.showList();
		
		setTimeout(function(){
			new Effect.Highlight('cart-item-'+cart_item_id, {
				startcolor:'#d15902',
				endcolor:'#f17319'
			});
		},500);
		
		$('cart-item-'+cart_item_id).hide();
		
		setTimeout(function(){
			
			$('cart-item-'+cart_item_id).remove();
			
			var count = $$('.cart-item').length;
			
			if(count==0) {
			
				if(live.page.page_url=='checkout') {
				
					alert('You have no items in your cart and cannot continue with the checkout process. \n\n You will now be redirected back the store.   ');
					
					window.location = "/store";
				
				}
				
				if(live.page.page_url=='confirm') {
		
					alert('You have no items in your cart and cannot continue with the checkout process. \n\nThe shipping and billing information you entered has been saved, except for sensitive credit card information. \n\n You will now be redirected back the store.   ');
					
					window.location = "/store";

				
				}
				
				$('cart-btn-checkout').hide();
			
				var new_cart_item = Builder.node('div', { id: 'cart-item-empty', className:'cart-item wrapper', style:'display:none'},[
				                                		                                                                                                 
	 		        Builder.node('div',{className:'cart-item-description'},[
	 		                Builder.node('em','There are no items in your cart')
	 		        ]),
		
		 		]);
				
				this.item_list_wrapper.appendChild(new_cart_item);
				$('cart-item-empty').show();
				
				if(!this.item_list_container.open) {
					setTimeout(function(){
						this.hideList();
					}.bind(this),3000);
				}
			
			}	
			
		}.bind(this),900);
	
	},

	addItem: function(item_sku,product_sku,product_qty) {
	
		if($('item-'+item_sku)) {
			
			var cart_item = $('item-'+item_sku).up();
			var cart_item_id = cart_item.id.gsub('cart-item-','');
			
			var qty = this.items.get(cart_item_id).qty+1;
			
			this.updateQty(cart_item_id,qty);
			
			alert("Item quantity updated!");
				
		} else {
		
			this.service.add_item.call(item_sku,product_sku,product_qty);
			this.service.add_item.result = function(result) {
				if(result){
					this.updateTotal();
					this.displayItem(result,false);
					alert('Item successfully added to your shopping cart!');

				}	
			}.bind(this);
			
		}
		
		Effect.ScrollTo('cart-header', { duration:'0.2', offset:-20 });
		Effect.Pulsate('cart-header', { pulses: 2, duration: 1.5 });
		this.showList();

	},	
	

	removeItem: function(cart_item_id) {
	
		this.container.stopObserving('mouseleave');
	
		user_confirm = confirm('Are you sure you would like to remove this item from your shopping cart? This action cannot be undone.');
		
			if(user_confirm) {
			
			this.service.remove_item.call(cart_item_id);
			this.service.remove_item.result = function(success) {
				
				if(success) {
					this.updateTotal();
					this.deleteItem(cart_item_id);
					this.cart_off = this.container.observe('mouseleave', this.hideList.bind(this));
					if(live.page.page_url=='confirm') {
						location.reload(true);
					}
				}
				
			}.bind(this);

		} 

	
	},
	
	showList: function() {
		
		clearTimeout(this.item_list_container.timeout);
		
		if(!this.item_list_container.open){
		
			this.item_list_container.timeout = setTimeout(function(){
				
				this.item_list_container.open = true;
				
				this.item_list_container.show();

			}.bind(this),200);
			
		}
		
	},
	
	hideList: function() {
		
		clearTimeout(this.item_list_container.timeout);
		
		if(this.item_list_container.open){
		
			this.item_list_container.timeout = setTimeout(function(){
				
				this.item_list_container.open = false;
				
				this.item_list_container.hide();

			}.bind(this),200);
			
		}
		
	}
	
});

document.observe('dom:loaded',function() {
	
	Cart = new Cart();
	
});

