var sizeType        = Array();
var color           = Array();
var size            = Array();
var selectedSizeDOMElement = Array();
var selectedProductVariant = Array();
var selectedSizeType = Array();
var selectedColor = Array();
var displayColor    = Array();
var displaySize     = Array();
var masterSwatches  = Array();
var masterSizes = Array();
var availableColors = Array();
var availableColorsForSizeType = Array();
var availableSizes  = Array();
var undefined;
var JSONData;
var maxIndex = 0;
var genericError = "#genericError";
var genericErrorMessage = "Please correct the error(s) identified below.";
var sizeError = "#sizeError";
var sizeErrorMessage = "Please select a size";
var updateAction = false;
var initialLoad = true;
var outfitPage = false;
var redraw = false;
var ignoreSwatches = false;
function setJSONData(data) {
    JSONData = data;
}

/* Method for setting DefaultSizeType */
function setDefaultSizeType(sizeTypeValue, index) {
    sizeType[index] = sizeTypeValue;
    if(index > maxIndex) {
        maxIndex = index;
    }
}

function sizeTypeSelected(sizeTypeValue, index) {
    //hideGenericErrorMessage();
    sizeType[index] = sizeTypeValue;
    parseJSONForSizeType(index);
}

function parseJSONForSizeType(index) {
    var productJSON = JSONData.products[index];

    /*Find the sizeType object from the JSON data corresponding to the selected sizeType*/
    $.each(productJSON.sizeTypes, function(i, SizeType){
        if(SizeType.name == sizeType[index]) {
            selectedSizeType[index] = SizeType;
            masterSwatches[index] = SizeType.swatchArray;
            displayColor[index] = SizeType.displayColor;
            displaySize[index] = SizeType.displaySize;
            return false;
        }
    });
    /* If displaySize for the product is true, get all available sizes for the selected sizeType
        and render the size icons in default (disabled) state */
    if(displaySize[index]) {
            masterSizes[index] = selectedSizeType[index].masterSizes;
            renderSizes(masterSizes[index], index);
    }
    /* If displayColor for the product is true, get all available colors for the selected sizeType */
    if(displayColor[index]) {
        availableColors[index] = getAvailableColors(selectedSizeType[index], index);
        availableColorsForSizeType[index] = getAvailableColors(selectedSizeType[index], index);
        if(!initialLoad) {
            richFXRedraw(availableColors[index], index, selectedSizeType[index].defaultColor);
        }
    } else {
        color[index] = "EMPTY";
        ignoreSwatches = true;
        parseSizeTypeForColor(index);
        if(displaySize[index]) {
            availableSizes[index] = getAvailableSizes(selectedColor[index]);
            activateAvailableSizes(availableSizes[index], index);
        }
    }


}

function parseSizeTypeForColor(index) {
    $.each(selectedSizeType[index].colors, function(j, Color){
        if(Color.name == color[index]) {
            selectedColor[index] = Color;
            return false;
        }
    });
}

function setDefaultColor(colorValue, index) {
    colorSelected(colorValue, index);
}

function colorSelected(colorValue, index) {
    if (!ignoreSwatches) {
        if(initialLoad) {
            initialLoad = false;
        }
        color[index] = colorValue;
        selectedColor[index] = undefined;
        parseSizeTypeForColor(index);
        if(displaySize[index]) {
            refreshSizes(index);
            availableSizes[index] = getAvailableSizes(selectedColor[index]);
            activateAvailableSizes(availableSizes[index], index);
        } else {
            //TODO
        }
    }
}

function setDefaultSize(sizeValue, index) {
	if(sizeValue != '') {
		size[index] = sizeValue;
	}
}

function setUpdateAction(stringValue) {
    updateAction =  stringValue == "true" ? true : false;
}

function setOutfitPage(boolValue) {
    outfitPage = boolValue;
}

function resetSizes(index) {
    $("#SelectSize_"+ index+" li").each(function(){
        $(this).css("visibility", "hidden");
        $(this).removeClass();
    });
    unselectSize(index);
}

function refreshSizes(index) {
    unselectSize(index);
    $("#SelectSize_"+ index+" li").each(function(i){
            $(this).addClass("disable");
            $(this).unbind("click");
    });
}

function renderSizes(sizes, index) {
    resetSizes(index);
    var diff = sizes.length - $("#SelectSize_"+ index).children().size();
    if(sizes.length > 0) {
        for(var i = 0; i < diff; i ++) {
            $("#SelectSize_"+ index).append("<li><a>0</a></li>"); 
        }
    }
    size[index] = undefined;
    $("#SelectSize_"+ index+" li").each(function(i){
        if(sizes.length > i) {
            $(this).css("visibility", "visible");
            $(this).addClass("size"+sizes[i]);
            $(this).addClass("disable");
        } else {
            return false;
        }
    });
}

function unselectSize(index) {
    if(selectedSizeDOMElement[index] != undefined){
        selectedSizeDOMElement[index].removeClass("selected");
    }
    if(!outfitPage) {
        $("input[name=productVariantId]").val('');
        $("input[name=size]").val('');
    } else {
        $("input[name=productVariantId]")[index].value = '';
    }
    selectedSizeDOMElement[index] = undefined;
    selectedProductVariant[index] = undefined;
}

function clearOutfitsSelections() {
    for(var index = 0; index <= maxIndex; index ++) {
        unselectSize(index);
    }

    $(".the-variant-qtys").each(function() {
        $(this).val("-1");
    });

}

function selectSize(sizeClass, index) {
    selectedSizeDOMElement[index] = $("#SelectSize_"+ index+" li." + sizeClass + " a");
    selectedSizeDOMElement[index].addClass("selected");
    size[index] = selectedProductVariant[index].size;
    if(!outfitPage) {
        $("input[name=productVariantId]").val(selectedProductVariant[index].id);
        $("input[name=size]").val(selectedProductVariant[index].size);
    } else {
        $("input[name=productVariantId]")[index].value = selectedProductVariant[index].id;
    }
}

function activateAvailableSizes(sizes, index) {
    $.each(sizes, function(i, Size){
        $("#SelectSize_"+ index+" li.size" + Size.size).each(function(){
            $(this).removeClass("disable");
            if(size[index] != undefined && Size.size == size[index]) {
                selectedProductVariant[index] = availableSizes[index][i];
                selectSize("size" + size[index], index);
            }
            $(this).click(function(){
                unselectSize(index);
                selectedProductVariant[index] = availableSizes[index][i];
                selectSize(this.className, index);
                if(displayColor[index]) {
                    availableColors[index] = getAvailableColors(selectedSizeType[index], index);
                    richFXRedraw(availableColors[index], index, selectedColor[index]);
                }
               	return false;
            });
            return false;
        });
    });
    if(redraw) {
        redraw = false;
        availableColors[index] = getAvailableColors(selectedSizeType[index], index);
    }
    if(size[index] != undefined && selectedSizeDOMElement[index] == undefined) {
        showGenericErrorMessage();
        showErrorMessage("#sizeError_" + index, "Size"+ size[index]+" is not available in selected Color");
        //size[index] = undefined;
    }
}

function showErrorMessage(errorId, messageHTML) {
    var $this = $(errorId);
    $this.text(messageHTML);
    $this.show();
}

function showGenericErrorMessage() {
    var $this = $(genericError);
    $this.text(genericErrorMessage);
    $this.show();
}

function hideErrorMessage(errorId) {
    $(errorId).hide();
}

function hideGenericErrorMessage() {
    if(!outfitPage) {
        hideErrorMessage(genericError);
        hideErrorMessage(sizeError);
    } else {
        $(".error").each(function() {
           $(this).hide();
        });
    }
}

function showProduct(productId, index) {
    //document.location.href = "product.jsp?productId=" + productId + "&defaultColor=" + selectedColor[index].name + "&defaultSizeType=" + selectedSizeType[index].name;
    document.location.href = "product.jsp?productId=" + productId + "&defaultColorNameFromOutfit=" + selectedColor[index].name;
}

function isValid() {
    hideGenericErrorMessage();
    if(!outfitPage) {
        var productVariantId = $("input[name=productVariantId]").val();
        if(productVariantId == '') {
            showGenericErrorMessage();
            showErrorMessage(sizeError, "Please select a Size.");
            return false;
        } else {
            return true;
        }
    } else {
        var productSelected = false;
        var hasError = false;
        for(var i = 0; i < $(".the-variant-qtys").length; i++){
            var quantity = $("select.the-variant-qtys:eq("+ i +")").val();
            if(selectedProductVariant[i] != undefined && quantity == -1) {
                hasError = true;
                productSelected = true;
                showGenericErrorMessage();
                showErrorMessage("#quantity_"+i, "Please select a quantity.");
            } else if(quantity != -1 && displaySize[i] && selectedProductVariant[i] == undefined) {
                hasError = true;
                productSelected = true;
                showGenericErrorMessage();
                showErrorMessage("#quantity_"+i, "Please select a size.");
            } else if(quantity != -1) {
                productSelected = true;
            }
	    }
        if(!productSelected) {
            hasError = true;
            showErrorMessage("#genericError", "Please make a product selection.");
        }
        return !hasError;
    }
}

function loadProductVariant(sizeTypeValue, colorName, sizeValue, quantityValue, index) {
    sizeTypeSelected(sizeTypeValue, index);
    size[index] = sizeValue;
    redraw = true;
    colorSelected(colorName, index);
    $("#quantity").val(quantityValue);
}

function findColorValueDeltas(attributeName, colors, stringifyFlag, delimiter) {
    if(stringifyFlag) {
        var delta = '';
        $.each(colors, function(i, Color){

            if(attributeName == 'name') {
                delta += (delta != ''? delimiter : "") + Color.name;
            } else {
                delta += (delta != ''? delimiter : "") + Color.code;
            }
        });
        return delta;
    } else {
        var delta = Array();
        var idx = 0;
        $.each(colors, function(i, Color){

            if(attributeName == 'name') {
                delta[idx++] = Color.name;
            } else {
                delta[idx++] = Color.code;
            }
        });
        return delta;
    }
}

function findAvailableSizeValues(index) {
        var sizes = Array();
        var idx = 0;
        $.each(availableSizes[index], function(i, ProductVariant){
            sizes[idx++] = ProductVariant.size;
        });
    return sizes;
}

function getUnAvailableColors(index) {
    var delta = Array();
    var idx = 0;
    $.each(masterSwatches[index], function(i, Swatch){
        var availableColor;
        var masterColor;
        $.each(availableColors[index], function(j, Color){
            masterColor = Swatch;
            if(Swatch.code == Color.code) {
                availableColor = Color;
                return false;
            }
        });

        if(availableColor == undefined) {
            delta[idx++] = masterColor.name;
        }

    });
    return delta;
}

function getMasterSwatch(index) {
    var master = Array();
    var idx = 0;
    $.each(masterSwatches[index], function(i, Swatch){
        master[idx++] = Swatch.name + "[" + Swatch.code + "]";
    });
    return master;
}
function getAvailableColors(SizeType, index) {
    var availableColors = Array();
    if(size[index] == undefined) {
        $.each(SizeType.colors, function(i, Color){
            availableColors[i] = Color;
        });
    } else {
        var idx = 0;
        $.each(SizeType.colors,  function(i, Color){
            $.each(Color.productVariants, function(j, ProductVariant){
                if(ProductVariant.size == size[index]) {
                    availableColors[idx++] = Color;
                    return false;
                }
            });
        });
    }
    return availableColors;
}

function getAvailableSizes(Color) {
    var availableSizes = Array();
    if(Color != undefined) {
        $.each(Color.productVariants, function(k, ProductVariant){
                availableSizes[k] = ProductVariant;
        });
    }
    return availableSizes;
}

function richFXRedraw(availableColors, index, defaultColor) {
    if(!outfitPage) {
        RICHFX.api("productImage", "imageOverlayCC").redraw(findColorValueDeltas("code", availableColors, true, "|"),defaultColor.code, findColorValueDeltas("code", availableColorsForSizeType[index], true, "|"));
    } else {
       RICHFX.api("productImage_" + index, "imageOverlayCC").redraw(findColorValueDeltas("code", availableColors, true, "|"),defaultColor.code, findColorValueDeltas("code", availableColorsForSizeType[index], true, "|"));
    }
}

$(document).ready(function(){ /* Not getting triggered, if we have any js Errors in the JSP. SO going to explicitly call this using docReady() */

    /*for(var index = 0; index <= maxIndex && !updateAction; index ++) {
        sizeTypeSelected(sizeType[index], index);
    }
    initialLoad = false;*/
});

function docReady() {
    for(var index = 0; index <= maxIndex && !updateAction; index ++) {
        sizeTypeSelected(sizeType[index], index);
    }
}




