jQuery(document).ready(function() {
    swatchItems.initialize();
});

var swatchItems = {
    jsonData : null,
    selectedSwatch : null,

    initialize : function() {
        this.jsonData = detailData;
        this.bindEvents();
    }

    , bindEvents : function() {
        var parentThis = this;

        jQuery(".swatchImage").click(function() {
           // jQuery("#swatchImages .swatchImage").removeClass("swatchSelected");
            jQuery(this).addClass("swatchSelected");
            parentThis.selectedSwatch = jQuery(this).attr("id");
            parentThis.updateImages();
            parentThis.updateSwatches();
        });

        jQuery("#swatchImages .swatchImage").hover(function() {
            jQuery(this).addClass("swatchImageHover");
        }, function() {
            jQuery(this).removeClass("swatchImageHover");
        });

    }

    , updateImages : function() {
        var parentThis = this;
        //Get the JSON object for the selected color
        var selectedSwatchArray = parentThis.jsonData.imageData[parentThis.selectedSwatch];
        if(selectedSwatchArray.mainImage == null) {
            return; //No image for this color, just return
        }
        var largeImageUrl = selectedSwatchArray.mainImage;

        //Swap the main image and select the first thumbnail
        jQuery("#product_image_" + selectedSwatchArray.productIndex).attr("src", largeImageUrl);
    }

    , updateSwatches : function(){
        var parentThis = this;
        var selectedProductIndex = parentThis.jsonData.imageData[parentThis.selectedSwatch].productIndex;
        var selectedSwatchIndex = parentThis.jsonData.imageData[parentThis.selectedSwatch].imageIndex;
        var swatchArrayIndexes = parentThis.jsonData.productData[selectedProductIndex].imageIndex;
        jQuery.each(swatchArrayIndexes, function(){
            if (this != selectedSwatchIndex){
                jQuery("#swatch_" + selectedProductIndex + "_" + this).removeClass("swatchSelected");        
            }
        });
    }

};
