$(function () {
    // Toggle between values.
    // (Intended for text- and password-inputs)
    $('.js-toggle-value').each(function () {
        $(this).data('original_value', $(this).val());

        $(this).focus(function () {
            if ($(this).val() === $(this).data('original_value')) {
                $(this).val('');
            }
        }).blur(function () {
            if ($(this).val() === '') {
                $(this).val($(this).data('original_value'));
            }
        });
    });

    // Indicate the current page in the navigation bar (if a link exists there).
    $("#navigation li a").each(function() {
        if(this.href == window.location) $(this).addClass("current");
    });

    // Fancy box
    $("a.fancybox").fancybox({
        'zoomSpeedIn': 300,
        'zoomSpeedOut': 300,
        'overlayShow': true,
        'easingIn' : 'easeOutBack',
        'easingOut' : 'easeInBack'
    });

    // Tooltip
    $("img.tooltip").tooltip({
        track: true,
        delay: 0,
        showURL: false,
        showBody: " - ",
        fixPNG: true,
        opacity: 0.95
    });

    // jQueryUI tabs
    $("#tabs").tabs();

    // Category menu
    $('#category_menu').treeview({
        persist: "location",
        collapsed: true,
        unique: true
    });

    // Add to cart with javascript function from product list
    $('.js-add-to-cart-button').click(function (event) {
        if(put_in_cart(this, 1)) {
            event.preventDefault();
        }
    });    


    // Add to cart with javascript function from product page
    $('#add-to-cart-form').submit(function (event) {
        var amount = $('input[name=amount]', this).val();
        $(this).attr('data-product-id', $('input[name=cartString]').val());
        put_in_cart(this, amount);
        event.preventDefault();
    });

    $('.js-language-button').click(function(event){
        var code = $(this).attr('data-iso-code');
        $.cookie(
            'UseLanguage',
            code,
            {'path': BASE_URL}
        );
    });

});

function put_in_cart(sender, amount)
{
    var productId = $(sender).attr('data-product-id');
    var result = null;
    $.ajax({
        type: "POST",
        url: BASE_URL+"ajax/add_to_cart.php",
        data: "product_id="+productId+"&amount="+amount,
        async: false,
        success: function(msg){
            if(msg == "SUCCESS") {
                put_in_cart_success(sender);
                result = true;
            } else {
                result = false;
            }
        }
    });
    return result;
}

function put_in_cart_success(sender)
{
    $.get(BASE_URL+'ajax/cart.php', function(data) {
        var parent = $(sender).parent();
        $(parent).effect('transfer',{to: ".js-sidebar-cart", className: 'js-cart-transition'},500, function() {
            $('.js-sidebar-cart').html(data);
        });
    });
}

function put_in_cart_error(sender, msg)
{
    return false
}



