// Behavior for /product/view pages

// This is needed by other scripts loading on this page
jQuery.noConflict();

jQuery(function ($) {
    var menu = $(".product-variation-multi");

    // Tabs
    // Note that this is using an old tabs plugin (as jqerty-tabs.js [sic]),
    // not jQuery UI tabs.
    $("#container").tabs();

    // Select menu
    menu.selectmenu({
        handleWidth: 0,
        style: "popup",
        // Add price spans to things that look like dollar amounts
        // Put "out of stock" in a span
        format: function (f) {
            return f.replace(/(\$[\d|,]+\.\d+)/g,
                             "<span class='price-text'>\$1</span>").
                     replace(/^(out of stock)/i,
                             "<span class='out-of-stock'>\$1</span>");
        }
    });

    // Change the starting/vetrx price when changing
    (function () {
        var prices = $("#product-selector p.price"),
            basePriceContainer = prices.find("s"),
            effPriceContainer = prices.find("b"),
            savePriceContainer = prices.find(".savings");

        menu.change(function (event) {
            var option = $(this).find(":selected"),
                basePrice = Number(option.data("baseprice")),
                effPrice = Number(option.data("effectiveprice"));

            if (isFinite(basePrice) && isFinite(effPrice)) {
                basePriceContainer.html("$" + (basePrice / 100).toFixed(2));
                effPriceContainer.html("$" + (effPrice / 100).toFixed(2));
                savePriceContainer.html("$" + ((basePrice - effPrice) / 100).
                                        toFixed(2));
            }
        });
    }());
});

