/*
 * Various jQuery setup.
 *
 */
$(function(){
	
	/** Init add to cart buttons **/
	$('.add_item').bind('click', function(){
		
		// bring this item to front
		$('.product-box').css('z-index', '999');
		var row = ($(this).parent().parent().parent());
		row.css('z-index', '1000');		
		
		var _this = $(this);
		if(_this.hasClass('upsell')){
			show_upsell(_this);
			
			return false;
		}
		var product_id = _this.attr('product_id');
		var variant_id = _this.attr('variant_id');
		var variant_list = $('#variant_list_'+product_id);
		if(variant_list.length > 0){
			
			if(variant_list.val() > 0){
				variant_id = variant_list.val();
			}else{
				alert("Please select a product.");
				return false;
			}
		}
		
		// if the item has a prompt
		var comment = "";
		if(_this.attr('prompt')){
			var p = prompt(_this.attr('prompt'));
			if(p)
				comment = "/" + escape(p);
			else
			return false
		}
		
		$.post('/cart/add/' + product_id + '/' + variant_id + '/1' + comment,function(data, statusText){
					if(data.confirm) update_cart_display();
					_this.html("ADDED");
				}, 'json');
		return false;
	});
	
	function show_upsell(_this){
		var upsell = $( "#upsell_" + _this.attr('product_id'));
		upsell.fadeIn();
	}	
	
	$('.show_upsell').bind('click', function(){
		var _this = $(this);
		show_upsell(_this);		
		return false;
	});
	
	
	/** Init add to cart buttons **/
	$('.close_upsell').bind('click', function(){
		var _this = $(this);		
		_this.parent().parent().parent().fadeOut();
		return false;
	});
	
	
	/** Init Variant Lists **/
	
});

function update_cart_display(){
	$.post('/cart/get-sub-total/',function(data, statusText){					
					if(data.confirm){
					$('#cart_sub_total').html('$' + data.message);
				}
			}, 'json');
	$.post('/cart/get-item-count/',function(data, statusText){
				if(data.confirm){
					$('#cart_item_count').html(data.message);
				}
			}, 'json');

}
