$(function(){
    Messages.init();
    
    ItemForm.init();
    
    Cart.init();
    
    if($("a[rel^='prettyPhoto']").length){
        $("a[rel^='prettyPhoto']").prettyPhoto({animationSpeed:'normal'});
    }
		
})

Messages = {
    init: function(){
        // Deal with all messages already on the page
        $('ul#messages').hide().slideDown();
    },
    addMessage: function(message){
        if(!$('ul#messages').length){
            $('#header').after('<ul id="messages"></ul>');
        }
        $('<li>'+message+'</li>').hide().appendTo('#messages').slideDown();
        
    },
    clearMessage: function(){
        $(this).closest('li').slideUp(300, Messages._removeMessage);
        return false;
    },
    _removeMessage: function(){
        $(this).remove();
        if(!$('#messages li').length){
            $('#messages').remove();
        }
    }
}

ItemForm = {
    init: function(){
        $('form.add-item').live('submit', ItemForm.submitForm);    
        $('form.remove-item').live('submit', ItemForm.submitForm);
    },
    submitForm: function(){
        $.post(
            $(this).attr('action'),
            $(this).serialize(),
            ItemForm.handleResponse,
            'json'
        )
        return false;
    },
    handleResponse: function(data){
        if(data['message']){
            Messages.addMessage(data['message']);
        }
        if(data['cart_overview']){
            $('#cart-overview').replaceWith(data['cart_overview']);
        }
        if($('#cart').length){
            var _method = $(data['form']).find('input[name=_method]').val();
            // to check that the item really has just been removed
            // the returned form should have an PUT method
            if(_method == 'PUT'){                
                var form_action = $(data['form']).attr('action');
                var row = $('form[action='+form_action+']').closest('tr');
                row.fadeOut();
                row.remove();
                row.queue(function(){
                    if($('#cart tr').length <= 2){
                        $('#cart tr').replaceWith('<p>Your cart is empty</p>')
                    }
                })
            }
            
        } else if(data['form']){
            var form_action = $(data['form']).attr('action');
            $('form[action='+form_action+']').replaceWith(data['form']);
        }
    }
}

Cart = {
    init: function(){
        $('select[name=delivery]').change(function(){
            $.post(
                '/delivery',
                $(this).closest('form').serialize(),
                function(data){
                    console.log(data['delivery'])
                    $('.delivery-value').html(data['delivery']);
                    $('.total-value').html(data['total']);
                    if(data['message']){
                        Messages.addMessage(data['message'])
                    }
                },
                'json'
            )
        })
    }
}
