$(document).ready(function() {

    $('.flash').delay(2500).fadeOut('slow');

    $('body').on('click', '.btn-close-flash', function() {
        var flashToClose = $(this).attr('data-flash');
        $('.'+flashToClose).remove();
    })

    // Add to wishlist
    $("body").on("click", ".add-to-wishlist", function() {
        var idProduct = $(this).attr('data-product');
        var item = $(this);
        $.ajax({
            url:'/my-profile/my-wishlist/add/'+idProduct,
            type: "GET",
            async: true,
            success: function (data) {
                if (item.hasClass('in-wishlist')) {
                    item.removeClass('in-wishlist');
                    if ($('.counter-wishlist').length > 0) {
                        var currentCounter = $('.counter-wishlist').html();
                        $('.counter-wishlist').html(currentCounter - 1);
                    }
                } else {
                    item.addClass('in-wishlist');
                    if ($('.counter-wishlist').length > 0) {
                        var currentCounter = $('.counter-wishlist').html();
                        $('.counter-wishlist').html(parseInt(currentCounter) + 1);
                    }
                }
            },
            error: function (data) {
                alert('An error occured. The product has not been added to your wishlist');
            }
        })
    });

    // Newsletter footer
    $('#submit-subscribe-newsletter').click(function() {
        var button = $(this);
        var emailValue = $('#email-subscribe-newsletter').val();
        button.html('Loading...');
        button.removeClass('btn-success');
        if (validateEmail(emailValue)) {
            $.ajax({
                url:'/subscribe/newsletter',
                type: "POST",
                data: {
                    email: emailValue
                },
                async: true,
                success: function (data) {
                    $('#email-subscribe-newsletter').val('');
                    button.html(data);
                    button.addClass('btn-success');
                },
                error: function (data) {
                    alert('An error occured');
                }
            })
        } else {
            button.html('Incorrect email');
        }
    });

    function validateEmail(email)  {
        if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)) {
            return (true)
        }
        return (false)
    }

});