var discount = 0;

function copyPayeeToDelivery()
{
    $('#order_delivery_name').val($('#order_payer_name').val());
    $('#order_delivery_surname').val($('#order_payer_surname').val());
    $('#order_delivery_address1').val($('#order_payer_address1').val());
    $('#order_delivery_address2').val($('#order_payer_address2').val());
    $('#order_delivery_zipcode').val($('#order_payer_zipcode').val());
    $('#order_delivery_city').val($('#order_payer_city').val());
    $('#order_delivery_phone').val($('#order_payer_phone').val());
    $('#order_delivery_mobile').val($('#order_payer_mobile').val());
    $('#order_delivery_name')[0].disabled = 'disabled';
    $('#order_delivery_surname')[0].disabled = 'disabled';
    $('#order_delivery_address1')[0].disabled = 'disabled';
    $('#order_delivery_address2')[0].disabled = 'disabled';
    $('#order_delivery_zipcode')[0].disabled = 'disabled';
    $('#order_delivery_city')[0].disabled = 'disabled';
    $('#order_delivery_phone')[0].disabled = 'disabled';
    $('#order_delivery_mobile')[0].disabled = 'disabled';
    $('#order_delivery_name, #order_delivery_surname, #order_delivery_address1, #order_delivery_address2, #order_delivery_zipcode, #order_delivery_city, #order_delivery_country, #order_delivery_phone, #order_delivery_mobile').css('background-color', '#222222');
    $('#order_delivery_name, #order_delivery_surname, #order_delivery_address1, #order_delivery_address2, #order_delivery_zipcode, #order_delivery_city, #order_delivery_country, #order_delivery_phone, #order_delivery_mobile').css('color', '#aaaaaa');
}

function checkVoucher(update)
{
    var voucher = $('#order_voucher').val();
    if (voucher.length < 3) {
        var currency = $("#val_currency").val();
        var currency_is_prefix = parseFloat($("#val_currency_is_prefix").val());
        $('#voucher_value').html((currency_is_prefix ? currency + " " : "") + 0 + (!currency_is_prefix ? " " + currency : ""));
        $('#voucher-status').html('');
        discount = 0;
        updateValues(false);
        return false;
    }
    var n = $('[name=order[months]]:checked').val();
    var color = $('[name=order[color]]:checked').val();
    var price = parseFloat($("#val_price_" + n).val());
    var loader = $('#voucher-loader');
    var country_short = $('#country_short').val();
    loader.show();
    $.get('/shop/verify-voucher', {months: n, price: price, code: voucher, country_short: country_short, color: color }, function(data){
        data = eval('(' + data + ')');
        loader.hide();
        $('#voucher_value').html(data.discount_with_currency);
        discount = data.discount;
        if(data.code) {
            $('#voucher-status').html('Voucher accepted');
        } else {
            if(data.error != 1) $('#voucher-status').html('<span style="color: #955;">' + data.error + '</span>');
            else $('#voucher-status').html('');
        }
        updateValues(false);
    });
    return true;
}

function updateValues(check_code)
{
    var currency = $("#val_currency").val();
    var n = $('[name=order[months]]:checked').val();
    var tax_percent = parseFloat($("#val_tax").val());
    var shipping = parseFloat($("#val_shipping_" + n).val());
    var price = parseFloat($("#val_price_" + n).val());
    var tax;
    var currency_is_prefix = parseFloat($("#val_currency_is_prefix").val());
    
    if(!n || typeof(n) == 'undefined' || n == 'undefined') {
        shipping = 0;
        price = 0;
        tax = 0;
    }
    
    if(price < 0) {
        price = 0;
    }
    
    if(tax < 0) {
        tax = 0;
    }
    
    if(shipping < 0) {
        shipping = 0;
    }
    
    var val = $("#order_start_month :selected").text();
    val = val.replace(/^\s*/, '');
    val = val.replace(/\s*$/, '');
    var color = $('[name=order[color]]:checked').val();
    if(val == 'Immediate' && color != 'giftcard') {
        var immediate_shipping_cost = parseFloat($('#immediate_shipping_cost').val());
        shipping = shipping + immediate_shipping_cost;
    }

    if(check_code && checkVoucher()) {
       return;
    }
    var sum = Math.round(price + shipping - discount, 2);
    if(sum > 0) {
         tax = Math.round(sum * (tax_percent / 100), 2)
    } else {
        sum = 0;
        tax = 0;
    }
    $('#subtotal').html((currency_is_prefix ? currency + " " : "") + price + (!currency_is_prefix ? " " + currency : ""));
    $('#tax').html((currency_is_prefix ? currency + " " : "") + tax + (!currency_is_prefix ? " " + currency : ""));
    $('#shipping').html((currency_is_prefix ? currency + " " : "") + shipping + (!currency_is_prefix ? " " + currency : ""));
    $('#totals').html((currency_is_prefix ? currency + " " : "") + sum + (!currency_is_prefix ? " " + currency : ""));
}

function enableGiftCard()
{
    $('.delivery_for_colors').fadeOut(300, function() {
        $('.delivery_for_giftcard').fadeIn(300);
    });
    updateValues(true);
}

function disableGiftCard()
{
    $('.delivery_for_colors').fadeIn(300, function() {
        $('.delivery_for_giftcard').fadeOut(300);
    });
    updateValues(true);
}

$(document).ready(function(){
    if($('#dibs_form')[0]) {
        setTimeout("$('#dibs_form')[0].submit();", 1000);
        setTimeout("$('#dibs_text').slideUp(500);", 1500);
    }
    
    $(".timepicker input").bind('change', function(){
        updateValues(true);
    });
    
    $("#order_start_month").bind('change', function() {
        updateValues(false);
    });
    
    $("#order_color_7").bind('change', function() {
        if($(this)[0].checked) enableGiftCard();
    });
    
    $("#order_color_1, #order_color_2, #order_color_3, #order_color_4, #order_color_5, #order_color_6").bind('change', function() {
        if($(this)[0].checked) disableGiftCard();
    });
    
    $('#order_voucher').bind('keyup', function(){
        checkVoucher();
    });
    
    $('#order_payer_date_of_birth').bind('focus', function(){
        if($(this).val() == '') {
            $(this).attr('value', 'YYYY-MM-DD');
        }
    });
    
    $('#order_payer_date_of_birth').bind('click', function(){
        $(this)[0].select();
    });
    
    $("table.address input").bind('blur', function() {
        var id = $(this)[0].id;
        var extra = null;
        var values;
        values = { value: $(this).val() };
        id = id.replace(/order_payer_/, '').replace(/order_delivery_/, '').replace(/order_giftcard_/, '');
        if(id == 'phone') id = 'telephone';
        if(id == 'mobile') id = 'mobilephone';
        if(id == 'email2') {
            extra = $("#" + $(this)[0].id.replace(/email2/, 'email')).val();
            id = 'repeat-email';
            values = { value: $(this).val(), extra: extra };
        }
        if(id == 'name') id = 'firstname';
        if(id == 'surname') id = 'lastname';
        if(id == 'date_of_birth') id = 'birthdate';
        if(id == 'address1') id = 'address';
        if(id == 'address2') id= 'address-secondary';
        var $this = $(this);
        $.get('/validate/' + id, values, function(data) {
            data = eval('(' + data + ')');
            if(data.valid) {
                $this.css('background-color', '#000000');
                $this.attr('value', data.value);
            } else {
                $this.css('background-color', '#f9008a');
            }
        });
    });
    
    $("input#payer_and_delivery_same").bind('click', 
        function() { 
            if($(this)[0].checked) copyPayeeToDelivery(); 
            else {
                $('#order_delivery_name')[0].disabled = null;
                $('#order_delivery_surname')[0].disabled = null;
                $('#order_delivery_address1')[0].disabled = null;
                $('#order_delivery_address2')[0].disabled = null;
                $('#order_delivery_zipcode')[0].disabled = null;
                $('#order_delivery_city')[0].disabled = null;
                $('#order_delivery_phone')[0].disabled = null;
                $('#order_delivery_mobile')[0].disabled = null;
                $('#order_delivery_name').css('background-color', $('#order_payer_name').css('background-color'));
                $('#order_delivery_surname').css('background-color', $('#order_payer_surname').css('background-color'));
                $('#order_delivery_address1').css('background-color', $('#order_payer_address1').css('background-color'));
                $('#order_delivery_address2').css('background-color', $('#order_payer_address2').css('background-color'));
                $('#order_delivery_zipcode').css('background-color', $('#order_payer_zipcode').css('background-color'));
                $('#order_delivery_city').css('background-color', $('#order_payer_city').css('background-color'));
                $('#order_delivery_country').css('background-color', $('#order_payer_country').css('background-color'));
                $('#order_delivery_phone').css('background-color', $('#order_payer_phone').css('background-color'));
                $('#order_delivery_mobile').css('background-color', $('#order_payer_mobile').css('background-color'));
                $('#order_delivery_name, #order_delivery_surname, #order_delivery_address1, #order_delivery_address2, #order_delivery_zipcode, #order_delivery_city, #order_delivery_phone, #order_delivery_mobile').css('color', '#ffffff');
                $('#order_delivery_country').css('color', '#eeeeee');
            }
        }
    );
    
    if(document.location.hash.length > 0) {
        var re = new RegExp(/color=([1-7])/);
        var re2 = new RegExp(/type=(3|6|12)/);
        var re3 = new RegExp(/voucher=(\w+)/);
        var re4 = new RegExp(/giftcard=1/);
        
        if(match_array = re.exec(document.location.hash)){
            $("#order_color_"+match_array[1]).attr('checked', true);
            if(match_array[1] == 7) enableGiftCard();
        }
        
        if(match_array = re4.exec(document.location.hash)){
            $("#order_color_7").attr('checked', true);
            enableGiftCard();
        }
        
        if(match_array = re2.exec(document.location.hash)){
            var e = $("#order_months_"+match_array[1])[0];
            $(e).trigger('click');
            $(e).trigger('change');
            //$("#order_months_"+match_array[1]).trigger('change');
        }
        
        if(match_array = re3.exec(document.location.hash)){
            // match_array[1]; contains the voucher-code predefined in the url
            $('#order_voucher').attr('value', match_array[1]);
        }
    }
    checkVoucher(false);
});

