﻿var cartPage = {
    updatePage: function(data) {
        // is the cart now empty?
        if(!data.cart.contents.length)
            window.location.reload();
        
        // are there new items in the cart?
        for(var i = 0; i < data.cart.contents.length; ++i)
            if(!$('#jsCart' + data.cart.contents[i].id).length)
                window.location.reload();
        
        // have items been removed from the cart?
        $('#jsCart tr.JsCartRow').each(function() {
            var thisId = this.id.replace(/[^\d]/g, '');
            for(var i = 0; i < data.cart.contents.length; ++i)
                if(data.cart.contents[i].id == thisId)
                    return;
            
            $(this).fadeOut('slow', function() { $(this).remove(); });
        });
        
        // update cart information
        for(var i = 0; i < data.cart.contents.length; ++i) {
            var item = data.cart.contents[i];
            $('#jsCart' + item.id + '_price').html(formatMoney(item.price));
            $('#jsCart' + item.id + '_total').html(formatMoney(item.total));
            $('#jsCart' + item.id + '_added').html(item.added);
            $('#jsCart' + item.id + '_quantity').attr('value', item.quantity);
        }
        
        // update cart totals
        $('#jsSubtotal').html(formatMoney(data.cart.totals.subtotal));
        $('#jsShipping').html(formatMoney(data.cart.totals.shipping));
        $('#jsPromotionDiscount').html(formatMoney(data.cart.totals.promotion.discount));
        $('#jsPromotionReason').html(data.cart.totals.promotion.reason);
        $('#jsTax').html(formatMoney(data.cart.totals.tax));
        $('#jsTotal').html(formatMoney(data.cart.totals.total));
        $('#jsShippingMethod').attr('value', data.shipping.method.id ? data.shipping.method.id : '');
        $('#jsShippingZip').attr('value', data.shipping.zip ? formatZipCode(data.shipping.zip) : '');
        $('#jsShippingCity').html(data.shipping.city && data.shipping.state ? data.shipping.city + ', ' + data.shipping.state : '');
        $('#jsBillingZip').attr('value', data.billing.zip ? formatZipCode(data.billing.zip) : '');
        $('#jsBillingCity').html(data.billing.city && data.billing.state ? data.billing.city + ', ' + data.billing.state : '');
        $('#jsPromotionCode')
            .attr('value', data.cart.totals.promotion.code ? data.cart.totals.promotion.code : '')
            .attr('disabled', !data.shipping.method.id || !data.shipping.zip);
    },
    
    fireJson: function(queryString, focusOnFailure) {
        $('#jsWait').css('visibility', 'visible');
        $.ajax({
            async: true,
            cache: false,
            dataType: 'json',
            error: function() {
                $('#jsWait').css('visibility', 'hidden');
                if(focusOnFailure)
                    setTimeout(function() { $(focusOnFailure).focus().select(); }, 50);
            },
            success: function(data, textStatus) {
                $('#jsWait').css('visibility', 'hidden');
                if(data && data.message) {
                    if(data.success) cartPage.updatePage(data);
                    else {
                        alert(data.message);
                        if(focusOnFailure)
                            setTimeout(function() { $(focusOnFailure).focus().select(); }, 50);
                    }
                }
                else {
                    alert('There was a problem communicating with the JSON service.');
                    if(focusOnFailure)
                        setTimeout(function() { $(focusOnFailure).focus().select(); }, 50);
                }
            },
            type: 'GET',
            url: '../js/jsonService.aspx?' + queryString
        });
    },
    
    removeFromCart: function(id) {
        if(confirm('Are you sure you want to remove this item from your cart?'))
            this.fireJson('request=removefromcart&id=' + id);
        else
            this.fireJson('request=query');
    },
    
    adjustCartQuantity: function(id, sender) {
        var quantity = !sender || !sender.value || sender.value == '' ? 0 : sender.value;
        if(!/^\d{1,4}$/.test(quantity)) {
            alert('The quantity you entered is not valid.');
            setTimeout(function() { $(sender).focus().select(); }, 50);
        }
        else if(quantity == 0)
            this.removeFromCart(id);
        else
            this.fireJson('request=adjustcartquantity&id=' + id + '&quantity=' + quantity, sender);
    },
    
    setShippingMethod: function(sender) {
        if(sender && sender.value)
            this.fireJson('request=setshippingmethod&id=' + sender.value);
    },
    
    setShippingZip: function(sender) {
        if(sender && sender.value) {
            if(/^\d{5}$/.test(sender.value)) this.fireJson('request=setshippingzip&zip=' + sender.value, sender);
            else {
                alert('Your zip code is not valid.');
                setTimeout(function() { $(sender).focus().select(); }, 50);
            }
        }
    },
    
    setBillingZip: function(sender) {
        if(sender && sender.value) {
            if(/^\d{5}$/.test(sender.value)) this.fireJson('request=setbillingzip&zip=' + sender.value, sender);
            else {
                alert('Your zip code is not valid.');
                setTimeout(function() { $(sender).focus().select(); }, 50);
            }
        }
    },
    
    setPromotionCode: function(sender) {
        if(sender && sender.value && sender.value != '')
            this.fireJson('request=setpromotioncode&code=' + sender.value, sender);
    },
    
    update: function() {
        this.fireJson('request=query');
    }
};

