$(function(){
    checkout.init();
});


var checkout = {
    init: function()
    {
        $('a.remove_item').click(function(e)
        {
            e.preventDefault();
            checkout.removeItem($(this));
        });

        $('select.qty').change(function(e)
        {
            e.preventDefault();
            if($(this).val() == 0)
            {
                checkout.removeItem($(this));            
            }
            else
            {
                checkout.updateQuantity($(this));            
            }

        });
        
        $('#submit_form').click(function(e)
        {
            e.preventDefault();
            $('#checkout_form').submit();
        });
        
        $('#delivery_required').click(function()
        {
            if($(this).attr('checked') == true)
            {
                checkout.activateDelivery();
            }
            else
            {
                checkout.deactivateDelivery();
            }
        });
        
        if($('#checkout_form').length > 0)
        {
            $('#checkout_form').validate();
        }
    },
    removeItem: function(link)
    {
        id = link.parent().parent().attr('id').split('_');
        $.ajax({url: '/checkout/remove?id='+id[1],
                dataType: 'json',
                success: function(response)
                {
                    $('#basket_summary span').html(response.count);
                    $('#item_'+response.id).remove();
                    if($('li.basket_item').length == 0)
                    {
                        $('h3').each(function(){
                            $(this).remove();
                        });
                        $('#basket_sum').remove();
                        $('form').remove();
                        $('#checkout').append('<p>There are no items in your basket.</p>');
                    }
                }
        });
    },
    updateQuantity: function(select)
    {
       id = select.parent().parent().attr('id').split('_');
       $.ajax({url: '/checkout/updateQuantity?id='+id[1]+'&amount='+select.val(),
               dataType: 'json'
        });
    },
    activateDelivery: function()
    {
        $('.del_req').each(function()
        {
            $(this).children('input').addClass('required');
        });
        $('#delivery_address').show('normal');
    },
    deactivateDelivery: function()
    {
        $('.del_req').each(function()
        {
            $(this).children('input').removeClass('required');
        });
        $('#delivery_address').hide('normal');
        
    }
}
