
/* Custom Scripting
 ######################################################################### */

function sum_food_price () {
    return parseFloat($('#sum-food-price').text());
}

function sum_food_tax () {
    return sum_food_price() * 0.10714;
}

function sum_delivery_price () {
    return parseFloat($('#sum-delivery-price').text());
}

function sum_delivery_tax () {
    return sum_delivery_price() * 0.2;
}

function sum_packeting_price () {
    return parseFloat($('#sum-packeting-price').text());
}

function sum_packeting_tax () {
    return sum_packeting_price() * 0.2;
}


function sum_calculate_total () {
    $('#sum-total-price').text(sum_food_price() + sum_delivery_price() + sum_packeting_price())
    $('#sum-total-tax').text((sum_food_tax() + sum_delivery_tax() + sum_packeting_tax()).toFixed(2))
}

function sum_set_packeting_price (routine_a, routine_b) {
    var sum = 0
    if(routine_a == 'UF')
        sum = ufPrice;
    else if(routine_a == 'EF')
        sum =  parseFloat($('#special-ef-price').text())
    
    if(routine_b == 'UF' && routine_a != 'UF')
        sum += ufPrice;
    else if(routine_b == 'EF')
        sum +=  parseFloat($('#other-ef-price').text())

    $('#sum-packeting-price').text(sum + ' kr');
    
    sum_calculate_total()
}

function sum_set_delivery_price (routine) {
    var sum = 0
    if(routine == 'LA')
        sum = parseFloat($('#delivery-price').text())

    $('#sum-delivery-price').text(sum + ' kr');
    sum_calculate_total()    
}

function sum_set_food_price () {
    var sum = 0
    
    $('#cart-details tbody tr').each(function (i) {
        var count = parseFloat($('select', this).val());
        var unitprice = parseFloat($('.unitprice', this).text())
        sum += count * unitprice;
    });
    
    $('#sum-food-price').text(sum + ' kr');
    sum_calculate_total()
}

$(function () {
    $('.product-listing input').hide()
});

$(document).ready(function() {
    ufPrice = parseFloat($('#special-uf-price').text())
    
    $('#cart-details select').change(function(e) {
        var count = parseFloat($(this).val())
        var unitprice = parseFloat($(this).parent().siblings('.unitprice').text());
        
        $(this).parent().siblings('.totalprice').text((count * unitprice) + ' kr');

        sum_set_food_price()
    });
    
    $('#packeting-alternatives-special input').change(function(e) {
        var special_routine = $('#packeting-alternatives-special input:checked').val();
        var other_routine = $('#packeting-alternatives-other input:checked').val();
        
        if(special_routine == 'UF') {
            if(other_routine != 'UF') {
                 $('#other-uf-price').text('0 kr');
            }
        } else {
             $('#other-uf-price').text(ufPrice + ' kr');            
        }
        
        sum_set_packeting_price(special_routine, other_routine);
    });
    
    $('#packeting-alternatives-other input').change(function(e) {
        var special_routine = $('#packeting-alternatives-special input:checked').val();
        var other_routine = $('#packeting-alternatives-other input:checked').val();
        
        if(other_routine == 'UF') {
            if(special_routine != 'UF') {
                 $('#special-uf-price').text('0 kr');
            }
        } else {
             $('#special-uf-price').text(ufPrice + ' kr');            
        }
        
        sum_set_packeting_price(special_routine, other_routine);
    });
    
    if(!$('#confirmation-options input:checked').length) {
        $('#confirmation-details').hide();
    }
    
    var currentPaymentRoutine = $('#payment-routine input:checked').val();

    if(currentPaymentRoutine != 'IN') 
        $('#invoice-details').hide();

    if(currentPaymentRoutine != 'CR') {
        $('#card-details').hide();
    }
    
    if(currentPaymentRoutine != 'CA') 
        $('#cash-details').hide();
        
    if(currentPaymentRoutine != 'LA') 
        $('#delivery-address:not(.with-errors)').hide();

    $('#delivery-routine input').click(function(e) {
        if($(this).val() != 'LA')
            $('#delivery-address').slideUp();
        else
            $('#delivery-address').slideDown();
       
        sum_set_delivery_price($(this).val())
    });

    $('.product-listing select').change(function(e) {
        $self = $(this);
        cartHandler.addToCart($self.parent().attr('rel'), $self.val());
    });


    $('#invoice-details input:first-child').change(function (e) {
        $('#id_confirmation_email').val($(this).val());
    });
    

    $('#payment-routine input').click(function(e) {
        var routine = $('#payment-routine input:checked').val();
        if(currentPaymentRoutine != routine) {
            $('#cash-details, #invoice-details').hide();
            if(routine == 'IN') // Invoice
                $('#invoice-details').show();
            else if(routine == 'CA')
                $('#cash-details').show();
            else if(routine == 'CR') {
                $('#card-details').show();
            }

           currentPaymentRoutine = routine;
        }
        return true;
    });
    
    // Fix for IE
    function paymentRoutineChanged() {
    };
    
    $('#id_confirmation').click(function () {
        if($(this).attr('checked'))
            $('#confirmation-details').show('slow');
        else {
            $('#confirmation-details').hide('slow', function () {
                $('#id_confirmation_email').val('');
            });
        }
    });

    if($('#id_delivery_time_1').length > 0) {

        var $timeInput = $('#id_delivery_time_1')
        $timeInput.hide();
        
        
        var hourSelector = '<select>'

        for(var i = 10; i < 19; i++)
            hourSelector += '<option value="' + i + '">' + i + '</option>';

        hourSelector += '</select>';
        
        var $hourInput = $(hourSelector);
        
        var minSelector = '<select>'

        for(var i = 0; i < 4; i++) {
            var val = '00';
            if(i!=0)
                val = (i * 15)
            minSelector += '<option value="' + val + '">' + val + '</option>';
        }

        minSelector += '</select>';
        
        // var d = new Date()
        // 
        // d = d.addHours(2);
        // 
        // if(d.getHours() > 21) {
        //     d = d.addDays(1);
        //     d = new Date(d.getFullYear(), d.getMonth(), d.getDate(), 10, 0);
        // } else if(d.getHours() < 10) {
        //     d = new Date(d.getFullYear(), d.getMonth(), d.getDate(), 10, 0);
        // }
        
        var $minInput = $(minSelector);
        
        $('#delivery-time').append('Klockan:').append($hourInput).append($minInput);
        
        $hourInput.change(function (e) {
            updateTimeInput();
        });
        
        $minInput.change(function (e) {
            updateTimeInput();
        })
        
        $hourInput.val($timeInput.val().split(':')[0]);

        $minInput.val($timeInput.val().split(':')[1]);
        
        function updateTimeInput() {
            $timeInput.val($hourInput.val() + ':' + $minInput.val() + ':00');
        }
        
    	$('#id_delivery_time_0').datePicker();
        
        $('label[@for="id_delivery_time_0"]').text('Datum: ')
    }
    
    
    $('.cart-item .remove-item').click(function(e) {
        var $me = $(this);
        cartHandler.removeItem($me.attr('rel'));
        e.preventDefault();
    });
    $('.cart-item .remove-item').mouseover(function() {
        $(this).parent().css('background', '#ffcccc');
        $('.info', $(this).parent()).css('color', '#333');
    });
    $('.cart-item .remove-item').mouseout(function() {
        $(this).parent().css('background', 'white');
        $('.info', $(this).parent()).css('color', '#999');
    });
    
/*    
    
    if ($('#ctl00_cphContents_radioBtnNewAddress').val()) {
        $('#delivery-address').show();        
    }
    
    $('#ctl00_cphContents_radioBtnStore').click(function(e) {
        $('#delivery-address').hide('slow');
    });
    
    */
    cartHandler.init();

    
});

var cartHandler = {
    init: function() {
        cartHandler.cart_element = $('#cart');
        cartHandler.cart_inner = $('#cart-inner');
    },
        
    addToCart: function(id, quantity) {
        if (quantity == "-") {
            cartHandler.removeItem(id);
        } else {
            $.ajax({
                url: '/cart/add/' + id + '/',
                type: "POST",
                dataType: 'json',
                data: "quantity=" + quantity,
                success: function(data){
                    cartHandler.buildRow(data);
                },
                error: function (e) {
                    document.write(e.responseText)
                }
            });
        }

    },
    removeItem: function(id) {
        var $me = $(this);
        $.ajax({
            url: '/cart/remove/' + id + '/',
            type: "GET",
            success: function() {
                $('#cart-item-' + id).hide('slow', function() {
                    $('select[@rel=' + id + ']').val('-');

                    $(this).remove();
                    if ($('.cart-item-content', cartHandler.cart_inner).length == 0) {
                        cartHandler.initialCart();
                    } else {
                        cartHandler.calculateTotalPrice();
                    }                     
                });
            }
        });
    },
    buildRow: function(item) {
        
        if($('#cart-summary').length == 0) {
            $('#cart-inner').html('<div id="cart-summary"></div>')
        }

        var $item = $('#cart-item-' + item.id);
        
        if (!$item.is('div')) {
            $item = $(
                '<div id="cart-item-' + item.id + '" class="cart-item">' +
                    '<div class="cart-item-content">' +
                        '<p class="cart-item-title"></p>' +
                        '<p class="cart-item-data"><span class="quantity"></span> st à <span class="ppu"></span> kr (<span class="ppr"></span> kr)</p>' +
                    '</div>' +
                '</div>'
            );
            var $anchor = $('<a href="/cart/remove/' + item.id + '/" rel="' + item.id + '" class="remove-item"><img src="/site_media/imgs/trash.gif" /></a>');
            $anchor.click(function(e) {
                var $me = $(this);
                cartHandler.removeItem($me.attr('rel'));
                e.preventDefault();
            });
            $anchor.mouseover(function() {
                $(this).parent().css('background', '#ffcccc');
                $('.info', $(this).parent()).css('color', '#333');
            });
            $anchor.mouseout(function() {
                $(this).parent().css('background', 'white');
                $('.info', $(this).parent()).css('color', '#999');
            });
            
            $item.prepend($anchor);
            $('#cart-summary').before($item);
        }
        
        // build output
        $('.cart-item-title', $item).text(item.category + ' - ' + item.title);
        $('.cart-item-data .quantity', $item).text(item.quantity);
        $('.cart-item-data .ppu', $item).text(item.price);
        $('.cart-item-data .ppr', $item).text(item.price * item.quantity);
        
        $('#listing-product-' + item.id + ' select').val(item.quantity);
        
        $item.css('background', '#ffff66');
        setTimeout(function() {
            $item.css('background', 'transparent');
        }, 2000);
        
        cartHandler.calculateTotalPrice();
    },
    calculateTotalPrice: function() {
        var $items = $('.cart-item', cartHandler.cart_inner);
        if ($items.length == 0) {
            return;
        }
        
        var sum = 0;
        
        for (var i = 0; i < $items.length; i++) {
            sum += parseInt($('.ppr', $items[i]).text());
        }
        
        var vat = 0.12 * sum;

        $('#cart-summary').html('<strong>Totalt ' + sum + ' kr inkl. moms</strong> <span>(moms: ' + vat.toFixed(2) + ' kr)</span>');
        $('#cart-summary').append('<p><a href="/checkout/cart/empty">Töm varukorgen</a><a href="/checkout/cart/">Gå till kassan</a></p>');
    }
}

