var Cart = {
    //INIT LIGHTBOX COUNTER
    'lightboxShowed': 0,
        
    //BIND SECTION EVENTS
	'bindEvents': function () {
        $('#checkout-button').click(function () { Cart.showHolidayMessage('checkout', Cart.checkout)});
        $('#paypal-button').click(function () { Cart.showHolidayMessage('paypal', Cart.paypal)});
		$('#shopping-button').click(function () { window.location = '/' });
		$('#applypromo-button').click(this.applyPromo);
		
		$('#update-cart').click(this.updateCart);
		$('#empty-cart').click(this.emptyCart);
		
		$('.remove-product').livequery('click', this.removeProductConfirm);
		$('.update-product').livequery('click', function () { Cart.updateProduct.call(this); window.location.reload(true); });
	},
    
	//APPLY PROMO BY CODE
	'applyPromo': function () {
		if ( ! Cart.checkTotalAmount())
            return false;
		
		$.getJSON(
			'/cart/promos/'+Common.urlencode($('#promocode').val()),
			function (data) {
				if( ! data.success) {
					alert(data.message);
					return false;
				}
				
				//data.promos - hash of products promos arrays
				for(var productid in data.promos)
					$('#pp'+productid+' td').html('<em>'+data.promos[productid].join('<br/>')+'</em>');
				
				if(typeof productsByCategory == 'object') {
					//StaffOrder.updateCart();
					window.location = '/admin/stafforder';
				} else {
					Cart.updateCart();
					//window.location.reload(true);
				}
					
				return true;
			}
		);
		
		return true;
	},
	
    //HOLIDAY MESSAGE LIGHTBOX
    'showHolidayMessage': function (type, handle) {
        /*
		if ( ! Cart.checkTotalAmount()) {
			return false;
		}
		*/
		
        if (!Cart.lightboxShowed && holidayMessageActivated) {
            Shadowbox.open({
                player: 'iframe',
                title: '',
                content: '/messages/holiday/' + type,
                height: 250,
                width: 350
            });
			
            Cart.lightboxShowed = 1;
        } else {
			handle();
			return false;
		}
    },
    
    //CHECKOUT WITH PAYPAL
    'paypal': function () {
       	if(orderid == 0 && installedid == 0) {
			if( ! Checkout.createOrder())
				return false;
		}
		
        $.getJSON(
			'/checkout/setpaymenttype', { paymenttype: 'paypal' }, 
			function(data) {
				if(installedid)
					window.location = '/cart/schedule/'+orderid+'/'+installedid;
				else
					window.location = '/checkout/info/'+orderid+'/'+installedid;
			}
		);
       
		return false;
    },
	
	//PROCEED TO CHECKOUT
	'checkout': function () {
		if(orderid == 0 && installedid == 0) {
			if( ! Checkout.createOrder())
				return false;
		}
		
        $.getJSON(
			'/checkout/setpaymenttype', { paymenttype: 'card' },
			function(data) {
				if(installedid)
					window.location = '/cart/schedule/'+orderid+'/'+installedid;
				else
					window.location = '/checkout/info/'+orderid+'/'+installedid;
			}
		);
        
		return false;
	},
	
	//EMPTY WHOLE CART
	'emptyCart': function () {
		if ( !$('.remove-product').size() > 0 ||  !confirm('Would you like to clear all items from your cart?'))
			return false;
        
		$.map(
			$('.remove-product'),
			function(object) { Cart.removeProduct.call(object); }
		);
		
		totalAmount = 0;
        Cart.checkTotalAmount();
		
		return false;
	},
    
    //REMOVE PRODUCT FROM LIST WITH CONFIRMATION
    'removeProductConfirm': function () {
        if (confirm('Would you like to delete this item from your cart?')) {
            Cart.removeProduct.call(this);
			window.location.reload(true);
		}
	},
	
	//REMOVE PRODUCT FROM LIST
	'removeProduct': function () {
		var productId = $(this).attr('product-id');
		
		$.ajax({
			type: 'GET',
			async: false,
			url: '/cart/remove/'+productId
		});
			
		$('#p'+productId).remove();
		$(this).parent().parent().next().eq(0).remove();
		$(this).parent().parent().next().eq(0).remove();
		$(this).parent().parent().remove();
		
		cartProducts[productId] = 0;
		$('#product-total').html('Product Total: $'+Cart.calculateTotal(cartProducts).toFixed(2));
        totalAmount = Cart.calculateTotal(cartProducts);
        Cart.checkTotalAmount();
		
		return false;
	},
	
	//CALCULATE CART TOTAL
	'calculateTotal': function (cartProducts) {
		var total = 0;
		
		for(var i in cartProducts)
			if(typeof cartProducts[i] == 'object')
				total += cartProducts[i].amount*cartProducts[i].price - cartProducts[i].discount;
		
		return total;
	},
    
    //CHECK TOTAL AMOUNT FOR ZERO
    'checkTotalAmount': function() {
        if (typeof totalAmount != 'undefined' && totalAmount <= 0) {
            $('#empty-cart-box').show();
            return false;
        }
        return true;
    },
	
	//UPDATE CART TOTAL
	'updateCart': function () {
		$.map(
			$('.update-product'),
			function(object) { Cart.updateProduct.call(object); }
		);
		
		if(typeof tax == 'undefined')
			tax = 0;
		
		if(typeof shipping == 'undefined')
			shipping = 0;
		
		total = Cart.calculateTotal(cartProducts)+tax+shipping;
		
		$('#total').html('Total Due: $'+total.toFixed(2));
		
		return false;
	},
	
	//UPDATE PRODUCTS SUBTOTALS
	'updateProduct': function () {
		var productId = $(this).parent().parent().attr('id').replace('p', '');
		var promocode = ($('#promocode').val() ? $('#promocode').val() : 0);
		
		cartProducts[productId].amount = $(this).siblings().filter('input .input_quantity').attr('value');
		
		if( ! parseInt(cartProducts[productId].amount)) {
			Cart.removeProduct.call($(this).parent().parent().next().children().find('.remove-product').eq(0));
			return 0;
		}
		
		$.ajax({
			type: 'GET',
			async: false,
			url: '/cart/update/'+productId+'/'+cartProducts[productId].amount+'/'+Common.urlencode(promocode),
			
			success: function (response) {
				var data = eval('('+response+')');
				
				if( ! data.success) {
					return false;
				}
				
				if(typeof cartProducts != 'undefined')
					cartProducts[productId].discount = data.discount;
				else
					return 1;
				
				if(typeof tax == 'undefined')
					tax = 0;
				
				if(typeof shipping == 'undefined')
					shipping = 0;
		
				total = Cart.calculateTotal(cartProducts)+tax+shipping;
				
				//update savings, subtotal and total
                $('#p'+productId+' .savings').html(data.discount.toFixed(2) > 0 ? '$'+data.discount.toFixed(2) : '-');
				$('#p'+productId+' .subtotal').html('$'+(cartProducts[productId].amount*cartProducts[productId].price - data.discount).toFixed(2));
				$('#product-total').eq(0).html('Product Total: $'+Cart.calculateTotal(cartProducts).toFixed(2));
				$('#total').html('Total Due: $'+total.toFixed(2));
			}
		});
		
		/*
		$.getJSON(
			'/cart/update/'+productId+'/'+cartProducts[productId].amount+'/'+Common.urlencode(promocode),
			function (data) {
				if( ! data.success) {
					return false;
				}
				
				cartProducts[productId].discount = data.discount;
				
				//update savings, subtotal and total
                $('#p'+productId+' .savings').html(data.discount.toFixed(2) > 0 ? '$'+data.discount.toFixed(2) : '-');
				$('#p'+productId+' .subtotal').html('$'+(cartProducts[productId].amount*cartProducts[productId].price - data.discount).toFixed(2));
				$('.product_total').eq(0).html('Product Total: $'+Cart.calculateTotal(cartProducts).toFixed(2));
    		}
		);
		*/
		
		return false;
	},
	
	//SERVER PING
	'ping': function () {
		$.ajax({ type: 'GET', url: '/ping' });
		setTimeout('Cart.ping()', 3*60*1000);
	}
};


$(document).ready(function() {
    Cart.checkTotalAmount();
    $('.input_quantity').validation({ type: 'int' });
	Date.format = 'mm/dd/yyyy';
	Cart.bindEvents();
	$('.date').datePicker();
	
	setTimeout('Cart.ping()', 3*60*1000);
});
