var pdpOtherProductsImageToUrlMapping = new Array();
var pdpStockAvailabilityMap = {};
var pdpSizeOptionsMap = {};

function addOtherProductImage(product, url, caption)
{
	pdpOtherProductsImageToUrlMapping.push(new Array(product, url, caption));
}

function addSizeOptions(id, fullname, isdefault, displaySellPrice, displayDiscountPrice)
{
	var sizeMap = pdpSizeOptionsMap;
	if (! pdpSizeOptionsMap[id]) pdpSizeOptionsMap[id] = {};

	var sizeObj = {
		name: fullname,
		isdefault: isdefault,
		displaysellprice: displaySellPrice,
		displaydiscountprice: displayDiscountPrice
	};
	pdpSizeOptionsMap[id] = sizeObj;
}

function addToStockAvailabilityMap(product, color, size, message, allowAddToCart) {
	var productToColorMap = pdpStockAvailabilityMap;
	
	if (! productToColorMap[product]) productToColorMap[product] = {};
	var colorToSizeMap = productToColorMap[product];
	
	if (! colorToSizeMap[color]) colorToSizeMap[color] = {};
	var sizeToMessageAndCartFlagMap = colorToSizeMap[color];
	
	var stockAvailabilityObj = {
		message: message,
		allowAddToCart: allowAddToCart
	};
	
	sizeToMessageAndCartFlagMap[size] = stockAvailabilityObj;
}

function getStockAvailabilityMessage(product, color, size)
{
	if (! color) color = getFirstKeyFromMap(pdpStockAvailabilityMap[product]);
	if (!color || !pdpStockAvailabilityMap[product]) return null;
	if (! pdpStockAvailabilityMap[product][color]) return null;
	if (! size) size = getFirstKeyFromMap(pdpStockAvailabilityMap[product][color]);
	
	return (pdpStockAvailabilityMap[product][color][size]) 
			? pdpStockAvailabilityMap[product][color][size].message
			: null;
}

function allowAddToCart(product, color, size)
{
	if (! color) color = getFirstKeyFromMap(pdpStockAvailabilityMap[product]);
	if (!color || !pdpStockAvailabilityMap[product]) return null;
	if (! pdpStockAvailabilityMap[product][color]) return null;
	if (! size) size = getFirstKeyFromMap(pdpStockAvailabilityMap[product][color]);
	
	return (pdpStockAvailabilityMap[product][color][size]) 
			? pdpStockAvailabilityMap[product][color][size].allowAddToCart
			: null;
}

function initializeSizeOptions(){
	var productId = $('#productId').html();
	var color = $("#colorField").attr("value");
	$("#size_"+productId).empty();
	$("#size_"+productId).hide();
	for (var sizeId in pdpSizeOptionsMap){
		var showAddToCartButton = allowAddToCart(productId, color, sizeId);
		if (showAddToCartButton == null || showAddToCartButton != 'false'){
			var selectedAttr = (pdpSizeOptionsMap[sizeId].isdefault=='true') ? "selected='selected'" : "";
			$("#size_"+productId).append("<option value='" + sizeId + "' " + selectedAttr + " >" + pdpSizeOptionsMap[sizeId].name + "</option>");
		}
	}
	if ($(".sizeDropDown option:selected").length == 0)
		$("#size_"+productId+" option:first").attr("selected","selected");
	
	if ($("#size_"+productId).children().length > 0)
		$("#size_"+productId).show();
}

function showAvailabilityMessage(){
	var productId = $('#productId').html();
	var color = $("#colorField").attr("value");
	var sizeId = $(".sizeDropDown option:selected").attr("value");
	var message = getStockAvailabilityMessage(productId, color, sizeId);
	var showAddToCartButton;
	if (message) {
		showAddToCartButton = allowAddToCart(productId, color, sizeId);

		$("#productAvailabilityMessage").hide();	
		$("#stockAvailabilityOverrideMessage").text(message);	
		$("#stockAvailabilityOverrideMessage").show();	
	} else {
		$("#stockAvailabilityOverrideMessage").hide();
		$("#productAvailabilityMessage").show();
		showAddToCartButton = $("#productAvailabilityMessage").attr("class").split('-')[1];
	}
	if (showAddToCartButton == 'false'){
		$(".addtocartbutton").hide();
		$("#stockAvailabilityText").addClass("color-red");
	}else {
		$(".addtocartbutton").show();
		$("#stockAvailabilityText").removeClass("color-red");
	}
}

(function($) {
    var HelpWindow;

    $(document).ready(function() {
        $('.storeProductDetail').each(function() {
            initializePDP();
        });
    });

    function initializePDP() {
        $('.coloroption').click(function() {
            // update hidden color fields
            var idArr = ($(this).attr('id')).split('_');
            $('#colorField').attr('value', idArr[1]);

            // clear the previously selected color
            $('.coloroptionselected').removeClass('coloroptionselected');

            $(this).children('img').addClass('coloroptionselected');

            initializeSizeOptions();

            showAvailabilityMessage();
        });

        $('.coloroption').mouseover(function() {
            // put border on selected image
            $(this).children('img').addClass('coloroptionmouseover');

            // update selected color text
            var name = $(this).children('img').attr('alt');
            $('#defaultColor').html('(' + name + ')');

            var colorId = $(this).attr('id').split('_')[1];

            // update product image
            updateProductImage(colorId);

            // update thumbnails
            updateProductThumbnails(colorId);

        });

        $('.coloroption').mouseout(function() {
            //$(this).removeClass('coloroptionmouseover');
            $(this).children('img').removeClass('coloroptionmouseover');

            // return to default color
            var colorId = $('#colorField').attr('value');
            var name = $('#color_' + colorId).children('img').attr('alt');
            $('#defaultColor').html('(' + name + ')');

            updateProductImage(colorId);

            // update thumbnails
            updateProductThumbnails(colorId);
        });

        $('.perspectiveThumbnail').click(function() {
            var perspectiveName = $(this).children('img').attr('alt');
            // update perspectiveName
            $('#perspectiveName').html(perspectiveName);
            // update product image
            var colorId = $('#colorField').attr('value');
            updateProductImage(colorId);
        });

        $('.perspectiveThumbnailText').click(function() {
            var perspectiveName = $(this).children('label').html();
            $('#perspectiveName').html(perspectiveName);
            updateProductImage();
        });

        $('#additionalThumbnail').click(function() {
            var url = $(this).children('img').attr('src');
            $('#productImage').attr('src', url);
        });

        $('#viewLargerLink').click(function() {
            var productId = $('#productId').html();
            if ($(".calendarLinksContainer").html() || $(".audiocdinfo").html() || $(".bookdetailsdiv").html())
            {
            	doViewLarger('/cp/get_latest_product_view.aspx?showBleed=false&ProductNo=' + productId, 'height=610, width=650, scrollbars=1');
            }
            else
            {
            	doViewLarger('/cp/moredetails.aspx?showBleed=false&ProductNo=' + productId, 'height=610, width=650, scrollbars=1');
            }
        });

        $('#sizeChartLink').click(function() {
            doViewLarger('/cp/moredetails.aspx?showBleed=false&ProductNo=' + $('#productId').html() + '&tab=3', 'height=610, width=650, scrollbars=1');
        });

        $('.fitTitle').children('a').attr('href', '#');
        $('.fitTitle').children('a').click(function() {
            launchHelpInShop('/cp/info/help/help_fit.aspx', 'height=600,width=600,scrollbars=1');
        });

        $('#pdp_carousel > li').remove(); // remove the empty li or else jcarousel won't load any products. The empty li is for html validation.

        $('#pdp_carousel').jcarousel({
            size: pdpOtherProductsImageToUrlMapping.length,
            itemLoadCallback: {
                onBeforeAnimation: pdp_carousel_itemLoadCallback
            }
        });

        if (pdpOtherProductsImageToUrlMapping.length <= 0)	// hide the carousel if the store doesn't have any additional products
        {
            $('#productCarouselDiv').hide();
            $('.carouselcontainer').hide();
        }
        else {
            $('#productCarouselDiv').show();
            $('.carouselcontainer').show();
        }

        $('.sizeDropDown').bind("change", function() {
            updateSellPriceBasedOnSize();
            showAvailabilityMessage();
        });

        updateSellPriceBasedOnSize();
        initializeSizeOptions();
        showAvailabilityMessage();

        $('.audioTrack').click(function() {
            var url = $(this).attr("href");
            var iJukebox = document.location.href.indexOf("jukebox");
            if (iJukebox > 0)
                url = url + "&jukebox=yes";
            launchHelpInShop(url, 'height=250,width=300,scrollbars=0');
            return false;
        });

        $('.qty').click(function() {
            var url = $(this).attr("href");
            var iJukebox = document.location.href.indexOf("jukebox");
            if (iJukebox > 0)
                url = url + "&jukebox=yes";
            launchHelpInShop(url, 'height=250,width=300,scrollbars=0');
            return false;
        });

        $('input#qtyId').keyup(function() {
            removeNonNumbers($('input#qtyId')[0]);
        });
    };

    function updateSellPriceBasedOnSize() {
        var sizeId = $(".sizeDropDown option[selected]").attr("value");
        if (sizeId) {
            $("#markedDownPrice").html(pdpSizeOptionsMap[sizeId].displaydiscountprice);
            $("#origSellPrice").html(pdpSizeOptionsMap[sizeId].displaysellprice);
        }
    }

    function updateProductImage(colorId) {
        var perspectiveName = $('#perspectiveName').html();
        $('#productImage').attr('src', getProductImageUrl($('#productId').html(), perspectiveName, 350, colorId));
    }

    function updateProductThumbnails(colorId) {
        $('.perspectiveThumbnail').each(function() {
            var perspectiveName = $(this).children('img').attr('alt');
            $(this).children('img').attr('src', getProductImageUrl($('#productId').html(), perspectiveName, 48, colorId));
        });
        //also update the additonal views if present
        var additionalImg = $('#additionalThumbnail > img');
        if (additionalImg) {
            var additionalImgSrc = additionalImg.attr('src');
            var pattern = "_c\\d{1,}_1";
            var re = new RegExp(pattern, "g");
            var newImgSrc = additionalImgSrc.replace(re, "_c" + colorId + "_1");
            additionalImg.attr('src', newImgSrc);
        }
    }

    function doViewLarger(theUrl, newFeatures) {
        var colorId = $('#colorField').attr('value');
        if (colorId && colorId != 0)
            theUrl = theUrl + '&colorNo=' + colorId;
        var perspectiveName = $('#perspectiveName').html();
        theUrl += (perspectiveName.toLowerCase() == 'back') ? '&pr=B' : '&pr=F';
        launchHelpInShop(theUrl, newFeatures);
    }

    function pdp_carousel_itemLoadCallback(carousel, state) {
        var items = pdpOtherProductsImageToUrlMapping;
        for (var i = carousel.first; i <= carousel.last; i++) {
            if (carousel.has(i)) {
                continue;
            }

            if (i > items.length) {
                break;
            }

            carousel.add(i, pdp_carousel_getItemHTML(items[i - 1]));
        }
    };

    function pdp_carousel_getItemHTML(item) {
        return '<div class="carouselitem"><a href="' + getUrl(item[0]) + '" rel="nofollow"><img src="' + item[1] + '" alt="' + item[2] + '" /></a><br/><a href="' + getUrl(item[0]) + '" rel="nofollow">' + item[2] + '</a></div>';
    };

    function getUrl(productId) {
        var url = document.URL;
        var dotIndex = url.lastIndexOf('.');
        var url2 = url.substring(0, dotIndex + 1);
        return url2 + productId;
    };

    function roundNumber(rnum, rlength) {
        return Math.round(rnum * Math.pow(10, rlength)) / Math.pow(10, rlength);
    }

    function removeNonNumbers(mytextbox) {
        var myNumbers = "0123456789";
        var w = "";
        for (i = 0; i < mytextbox.value.length; i++) {
            x = mytextbox.value.charAt(i);
            if (myNumbers.indexOf(x, 0) != -1) {
                w += x;
            }
        }
        mytextbox.value = w;
    }

})(jQuery);
