$(function() {
    
    $("#product_image_thumbs a").click(function(event) {
        event.preventDefault();
        $("#product_image_thumbs a").removeClass('active');
        $(this).addClass('active');
        $("#product_image img:first").attr('src', $(this).attr('href'));
    });
    
    $("#tell_a_friend_form").validate();
    
    $("#tell_a_friend_link").click(function(event) {
        event.preventDefault();
        window.open($(this).attr('href'), 'Tell A Friend', 'width=414,height=400,top=300,left=400,location=0,menubar=0,directories=0,toolbar=0,status=0');
    })
    
    $("#contact_form").validate();
    
    $("#newsletter_form").validate();
    
    $(".floating_labels .text").each(function() {
        if ($(this).val() != "")
        {
            $("label[for=" + $(this).attr('id') + "]").not(".error").hide();
        }
    }).focusin(function() {
        $("label[for=" + $(this).attr('id') + "]").not(".error").hide();
    }).focusout(function() {
        if ($(this).val() == "")
            $("label[for=" + $(this).attr('id') + "]").not(".error").show();
    });
    
    function getProductPriceTotal()
    {
        var product_price = parseInt($("#product_shop_price").val());
        
        $(".product_option select").not("#product_quantity").each(function() {
            product_price += parseInt($("option:selected", this).attr('rel'));
        });
        
        product_price *= parseInt($("#product_quantity").val());
        
        $("#product_total_price .price").html('&euro; ' + number_format(product_price, 2, ',', '.'));
    }
    
    if ($("#shop_product_form").length) //shop product page
    {
        getProductPriceTotal();
        $(".product_option select").change(function() {
            getProductPriceTotal()
        });
    }
    
    //basket
    
    $("[name=button_edit_quantity]").live('click', function(e) {
        e.preventDefault();
        if (! $(this).hasClass("inactive"))
        {
            $("#shopping_basket_loading").fadeIn();
            var diff = $(this).attr('rel').split(';')[0];
            var i = $(this).attr('rel').split(';')[1];
            $.post(base_url + 'actions_shop/editQuantity', {diff: diff, i: i}, function() {
                $("#shopping_basket").load(base_url + 'winkelwagen #shopping_basket_content', {t: new Date().getTime()}, function() {
                    $("#shopping_basket_loading").fadeOut();
                });
            });
        }
    });
    
    $("[name=button_delete_item]").live('click', function(e) {
        e.preventDefault();
        if (confirm('Weet u zeker dat u dit product uit uw winkelwagen wilt verwijderen?'))
        {
            $(this).parents(".shopping_basket_item").fadeOut();
            var i = $(this).attr('rel');
            $.post(base_url + 'actions_shop/deleteItem', {i: i}, function() {
                $("#shopping_basket").load(base_url + 'winkelwagen #shopping_basket_content', {t: new Date().getTime()}, function() {
                    $("#shopping_basket_loading").fadeOut();
                });
            });
        }
    });
    
    jQuery.validator.addMethod("accept", function(value, element, param) {
        return value.match(new RegExp("." + param + "$"));
    });
    
    $("#checkout_form").validate({
        rules: {
            postal_code1: {
                maxlength: 4,
                minlength: 4
            },
            postal_code2: {
                accept: "[a-zA-Z]+",
                maxlength: 2,
                minlength: 2
            },
            delivery_postal_code1: {
                maxlength: 4,
                minlength: 4
            },
            delivery_postal_code2: {
                accept: "[a-zA-Z]+",
                maxlength: 2,
                minlength: 2
            },
            delivery_name: {
                required: function(element) {
                    return $("[name=delivery]:checked").val() == '2'
                }
            },
            delivery_address: {
                required: function(element) {
                    return $("[name=delivery]:checked").val() == '2'
                }
            },
            delivery_postal_code1: {
                required: function(element) {
                    return $("[name=delivery]:checked").val() == '2'
                }
            },
            delivery_postal_code2: {
                required: function(element) {
                    return $("[name=delivery]:checked").val() == '2'
                }
            },
            delivery_city: {
                required: function(element) {
                    return $("[name=delivery]:checked").val() == '2'
                }
            },
            // ideal_issuer: {
                // required: function(element) {
                    // alert($("[name=payment_method]:checked").val() == 'ideal');
                    // return $("[name=payment_method]:checked").val() == 'ideal'
                // }
            // }
        },
        errorPlacement: function(error, element) {
             $(element).parents(".checkout_form_row").append(error);
        },
        messages: {
            terms: 'U dient akkoord te gaan met de algemene voorwaarden'
        }//,
        // submitHandler: function(form) {
            // if ($("#checkout_newsletter").is(':checked'))
            // {
                // var name = $("#checkout_name").val();
                // var email = $("#checkout_email").val();
                // $.post('http://mailing.zoevers.nl/subscribeSubmit.asp', {field4: name, field5: email, uitgaveid: 1999});
            // }
            // $(form).submit();
        // }
    })
    
    $(".form_postal_code1").keyup(function() {
        if ($(this).val().length == 4)
            $(this).next().focus();
    });
    
    $(".form_postal_code2").keyup(function() {
        if ($(this).val().length == 2)
            $(this).next().focus();
    });
    
    $("[name=delivery]").change(function() {
        if ($("[name=delivery]:checked").val() == 1)
            $("#checkout_delivery_address_panel").hide();
        else
            $("#checkout_delivery_address_panel").show();
    }).trigger('change');
    
    $("[name=payment_method]").change(function() {
        if ($("[name=payment_method]:checked").val() == 'ideal')
            $("#checkout_ideal_issuer").show();
        else
            $("#checkout_ideal_issuer").hide();
    }).trigger('change');
    
});

function number_format( number, decimals, dec_point, thousands_sep ) {
    // %        nota 1: Para 1000.55 retorna com precisão 1 no FF/Opera é 1,000.5, mas no IE é 1,000.6
    // *     exemplo 1: number_format(1234.56);
    // *     retorno 1: '1,235'
    // *     exemplo 2: number_format(1234.56, 2, ',', ' ');
    // *     retorno 2: '1 234,56'
    // *     exemplo 3: number_format(1234.5678, 2, '.', '');
    // *     retorno 3: '1234.57'
    // *     exemplo 4: number_format(67, 2, ',', '.');
    // *     retorno 4: '67,00'
    // *     exemplo 5: number_format(1000);
    // *     retorno 5: '1,000'
    // *     exemplo 6: number_format(67.311, 2);
    // *     retorno 6: '67.31'
 
    var n = number, prec = decimals;
    n = !isFinite(+n) ? 0 : +n;
    prec = !isFinite(+prec) ? 0 : Math.abs(prec);
    var sep = (typeof thousands_sep == "undefined") ? ',' : thousands_sep;
    var dec = (typeof dec_point == "undefined") ? '.' : dec_point;
 
    var s = (prec > 0) ? n.toFixed(prec) : Math.round(n).toFixed(prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;
 
    var abs = Math.abs(n).toFixed(prec);
    var _, i;
 
    if (abs >= 1000) {
        _ = abs.split(/\D/);
        i = _[0].length % 3 || 3;
 
        _[0] = s.slice(0,i + (n < 0)) +
              _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
 
        s = _.join(dec);
    } else {
        s = s.replace('.', dec);
    }
 
    return s;
}
