$(document).ready(function(){
    
    var baseURL = '';
    
    //enable spry menu        
    var MenuBar1 = new Spry.Widget.MenuBar("MenuBar1", {imgDown:"/SpryAssets/SpryMenuBarDownHover.gif", imgRight:"/SpryAssets/SpryMenuBarRightHover.gif"});
    
    $('#add_to_cart_form').submit(function(){
        return false;
    })
    
    $('.add_to_cart').click(function(){
        
        var product_id = $('#product_id').val();
        var quantity = $('#stock_option').val();
        
        if (parseInt(quantity) && parseInt(product_id)) {
            $.get(baseURL+'/cart/add_to_cart/'+product_id+'/'+quantity+'/1/', function(data){
                refresh_cart_overview();
                $('#cart_results').html('Your item has been added');
                $('#cart_results').slideDown();
            });
        } else {
            $('#cart_results').html('Please choose your amount before ordering');
            $('#cart_results').slideDown();
        }
        
    })
    
    $('.remove_item').click(function(){
        var id = $(this).siblings('.product_id_value').text();
        $.get(baseURL+'/cart/remove_from_cart/'+id, function(){
            refresh_cart_overview();
        });
    })
    
    function refresh_cart_overview() {
        $.get('/cart/get_mini_cart', function(data){
            $('#cart_overview').html(data); 
            $('.remove_item').each(function(){
                $(this).bind('click', function(){
                    var id = $(this).siblings('.product_id_value').text();
                    $.get(baseURL+'/cart/remove_from_cart/'+id, function(){
                        refresh_cart_overview();
                    });
                })
            })
        });
    }
    
    $('#show_hide_costs').click(function(){
        $('#costs-viewer').slideToggle();
    })
    
    $('#print_page').click(function(){
        window.print();
    })
    
    $('#finalise-cart').click(function(){
        
        var v_alternate_address = $('#alternate_delivery_address').val();
        $('#process-output').html('<p>Processing...</p>');
        $('#process-output').slideDown();
        $.get('/cart/process_cart/', function(data){
            v_order_id = $.trim(data);
            if (v_alternate_address != '') {
                $.post(baseURL+'/orders/add_alternate_address/', {
                    alternate_address: v_alternate_address,
                    order_id: v_order_id
                }, function(data){
                    data = $.trim(data);
                    if (data == 'alternate_address_added') {
                        window.location = '/cart/confirm_payment/'+v_order_id;
                    }
                })
            } else {
                window.location = '/cart/confirm_payment/'+v_order_id;
            }
        })
        
        //stops the a href firing
        return false;
        
    })
    
})
