﻿Global.load(function () {
    $(".swatch-link").live("click", function () {
        var color = $(this).attr("data-urledcolor");
        findAndSetParentImageColorAndLink($(this), color);

        //hierarchy: a.swatch-link -> li -> ul
        $(this).parent().parent().find(".active").removeClass("active");
        $(this).parent().addClass("active");
    });

    // Automatically selecting the first color swatch on each product and applying a class of active to it.
    $('.productSwatches').each(function () {
        var $this = $(this),
            $swatch = $this.children('li:eq(0)').attr('data-color') != null ? $this.children('li:eq(0)') : $this.children('li:eq(1)');

        // Creates divs on all the swatches to place the checkmarks in if they don't already exist.
        if ($this.find('div.checkmarkOverSwatch').length < 1) {
            $('.swatch-link').each(function () {
                $('<div class="checkmarkOverSwatch small" />').insertBefore($(this).children('div:eq(0)'));
            });
        }

        findAndSetParentImageColorAndLink($swatch.children('a'), $swatch.children('a').attr("data-urledcolor"));
        $swatch.addClass('active');
    });
});

//This function will keep expanding it's scope until it finds a picture or a single product container, do not give a swatch element a swatch-link class if it will not be changing an image at the same scope or greater.
function findAndSetParentImageColorAndLink($element, color) {
    var $product = $element.parents(".product:eq(0)");

    if ($product.length > 0) {
        var $productImage = $product.find(".productImage");
        var imageDirectory = "images/product/icon";
        var productId = $productImage.attr("data-productid");
        var newUrl = imageDirectory + "/" + productId + "_1_" + color + ".jpg";

        $productImage.error(function () {
            $(this).attr("src", "skins/skin_1/images/imageunavailableMedium.gif");
        });
        $productImage.attr("src", newUrl);

        var $productLink = $product.find(".productLink");

        $productLink.each(function () {
            var newProductLink = $(this).attr("href");
            if (newProductLink.indexOf("&colorname=") == -1 && newProductLink.indexOf("?colorname=") == -1) {
                if (newProductLink.indexOf("?") == -1) {
                    newProductLink = newProductLink + "?colorname=" + color;
                } else {
                    newProductLink = newProductLink + "&colorname=" + color;
                }
            } else {
                newProductLink = newProductLink.replace(/colorname(?:=([^&]*))?/, "colorname=" + color);
            }
            $(this).attr("href", newProductLink);
        });
    }
}
