
/* support for registry editing dialogs */

function MEditRegistryContext()
{
    // note that this state is per-page, not per product detail
    this._selectedColorDiv = null;
    this._selectedSizeSpan = null;
    this._currentFavoriteId = null;
    this._availableSizes = null;
    this._availableColors = null;
    this._colorInfo = null;
    this._productImg = null;
}

MEditRegistryContext.prototype.prepareRegistryDialog = function()
{
    document.colorSizeContext = this;
}

// --ML no longer used 10/31
MEditRegistryContext.prototype.selectFavorite = function(item)
{
    if (this._currentFavoriteId != null) {
        var oldDiv = document.getElementById(this._currentFavoriteId);
        $(oldDiv).removeClassName('chosenFavoriteHilite');
    }
    $(item).addClassName('chosenFavoriteHilite');
    this._currentFavoriteId = item.id;
    
    var parentDiv = null;
    if (item.nodeName == 'TD') {
        parentDiv = item;
    }
    else {
        parentDiv = this.findParentOfType(item, 'TD');
    }
    this.fetchDetails(parentDiv);
}

MEditRegistryContext.prototype.findParentOfType = function(item, nodeName)
{
    item = item.parentNode;
    while (item != null && item.nodeName != nodeName) {
        item = item.parentNode;
    }
    return item;
}

MEditRegistryContext.prototype.fetchDetails = function(parentDiv)
{
    var handleAjaxResponse = function(xmlhttp) {
        var dialogContents = getResponseText(xmlhttp);
        if (!handleAjaxExceptionPage(dialogContents)) {
            var tempDiv = document.createElement("div");
            tempDiv.innerHTML = dialogContents;
            targetDiv = document.getElementById('detailsdiv');
            targetDiv.parentNode.replaceChild(tempDiv.firstChild, targetDiv);
            findAndEvalJavascript(dialogContents);
            document.editRegistryContext.setColorSelection();
            document.editRegistryContext.findSizeSelection();
        }
    };
    var optionsDict = {
            asynchronous: true,
            method: 'get',
            onSuccess: handleAjaxResponse
    };
    var detailsUrlTag = findChildTagWithId(parentDiv, "a", "registryDetailsUrl");
    var url = detailsUrlTag.href;
    new Ajax.Request(url, optionsDict);
}

/**
 * Submits the form and check the result.
 */
MEditRegistryContext.prototype.submitForm = function(link, event, editing)
{
    Event.stop(event);
    var formElement = document.getElementById('registryItemDetails');
    var url = link.href;

    var handleAjaxResponse = function(xmlhttp) {
        var dialogContents = getResponseText(xmlhttp);
            if (handleAjaxExceptionPage(dialogContents)) {
                return;
            }
            else if (dialogContents.indexOf('success') == -1) {
                document.editRegistryContext.clearDetailsDisplay("error in response after adding item");
            }
            else {
                if (!editing) {
                    pulseFavorites('mywishlistlink');
                }
                goToPendingUrl(document.dialogContext.getActiveDialog(), false);
            }
    };

    var formValuesString = Form.serialize(formElement);
    var optionsDict = {
        method: 'post',
        contentType:  'application/x-www-form-urlencoded',
        postBody: formValuesString,
        onSuccess: handleAjaxResponse
    };
    new Ajax.Request(url, optionsDict);
}

MEditRegistryContext.prototype.clearDetailsDisplay = function(message)
{
    var tempDiv = document.createElement("div");
    tempDiv.id = "detailsdiv";
    tempDiv.appendChild(document.createTextNode(message));
    targetDiv = document.getElementById('detailsdiv');
    targetDiv.parentNode.replaceChild(tempDiv, targetDiv);

}

MEditRegistryContext.prototype.setColors = function(colors)
{
    this._colorInfo = colors;
}

/* handleColorMouseOver, handleColorMouseOut, handleColorClick, handleSizeMouseOver, handleSizeMouseOut, handleSizeClick share an interface with productdetails.js - see ColorTable.java */

MEditRegistryContext.prototype.handleColorMouseOver = function(detailsColorDiv, event, availableSizes, colorIndex)
{
    $(detailsColorDiv).addClassName('detailsColorHilite');
    Event.stop(event);
    
    this._availableSizes = availableSizes;
    var detailsDiv = document.getElementById('productDisplay');
    var colorInfo = this._colorInfo[colorIndex];
    document.productDetailsContext.swizzleProductImage(detailsDiv, colorInfo.image);
    this._availableSizes = availableSizes;
}

MEditRegistryContext.prototype.handleColorMouseOut = function(detailsColorDiv, event)
{
    $(detailsColorDiv).removeClassName('detailsColorHilite');
    Event.stop(event);

    var detailsDiv = $('productDisplay');
    document.productDetailsContext.swizzleProductImage(detailsDiv, null);
}

MEditRegistryContext.prototype.handleColorClick = function(detailsColorDiv, event, colorIndex)
{
    $(this._selectedColorDiv).removeClassName('chosenHilite');
    $(detailsColorDiv).addClassName('chosenHilite');
    this._selectedColorDiv = detailsColorDiv;
    
    var colorNameInput = $('colorname');
    colorNameInput.value = this._colorInfo[colorIndex].name;
    
    // change default image to what is chosen
    var detailsDiv = $('productDisplay');
    var productImg = findChildTagWithId(detailsDiv, "IMG", "cellImg");
    detailsDiv.productImgSrc = productImg.src;
    
    document.productDetailsContext.updateSizesForColor($('sizetable'), this._availableSizes);
}

MEditRegistryContext.prototype.handleSizeMouseOver = function(detailsSizeSpan, event, availableColors)
{
    if (availableColors != null) {
        $(detailsSizeSpan).addClassName('detailsSizeHilite');
    }
    this._availableColors = availableColors;
    Event.stop(event);
}

MEditRegistryContext.prototype.handleSizeMouseOut = function(detailsSizeSpan, event)
{
    $(detailsSizeSpan).removeClassName('detailsSizeHilite');
    var detailsDiv = $('colortable');
    Event.stop(event);
}

MEditRegistryContext.prototype.handleSizeClick = function(detailsSizeSpan, event, sizeName)
{
    $(this._selectedSizeSpan).removeClassName('chosenHilite');
    this._selectedSizeSpan = detailsSizeSpan;
    $(this._selectedSizeSpan).addClassName('chosenHilite');
    
    var sizeInput = $('retailersize');
    sizeInput.value = sizeName;
    
    document.productDetailsContext.updateColorsForSize($('colortable'), this._availableColors);
}

MEditRegistryContext.prototype.initializeColorsAndSizes = function(availableColors, availableSizes)
{
    document.productDetailsContext.updateColorsForSize($('colortable'), availableColors);
    document.productDetailsContext.updateSizesForColor($('sizetable'), availableSizes);
}

MEditRegistryContext.prototype.setColorSelection = function()
{
    this._productImg = document.productDetailsContext.initializeProductImg($('productDisplay'));
    var productImgUrl = this._productImg.src;
    var productImgToken = document.productDetailsContext.extractImageUrl(productImgUrl);
    
    var parenttd = $('colortable');
    
    var divs = parenttd.getElementsByTagName("div");
    var divsLength = divs.length;
    var colorIndex = 0;
    var chosenDiv = null;
    for (var divIndex = 0; divIndex < divsLength; divIndex++) {
        var div = divs[divIndex];
        if (!$(div).hasClassName('detailsColorHilitable') && !$(div).hasClassName('detailsColorText')) {
            continue;
        }
        if (productImgToken == this._colorInfo[colorIndex].token) {
            chosenDiv = div;
            break;
        }
        if (chosenDiv == null) {
            // make sure we always have something chosen
            chosenDiv = div;
        }
        colorIndex++;
    }
    
    // didn't find color match, use first color div (if any colors)
    if (chosenDiv != null) {
        $(chosenDiv).addClassName('chosenHilite');
    }
    this._selectedColorDiv = chosenDiv;
    return chosenDiv;
}

MEditRegistryContext.prototype.findSizeSelection = function()
{
    var parenttd = $('sizetable');
    var spans = parenttd.getElementsByTagName("span");
    var eLength = spans.length;
    for (var ii = 0; ii < eLength; ii++) {
        var span = spans[ii];
        if (span.className.indexOf('chosenHilite') >= 0) {
            this._selectedSizeSpan = span;
            return span;
        }
    }
    return null;
}

MEditRegistryContext.prototype.handleClickOutside = function(event)
{
    Event.stop(event);
}

//////////////////////////////////////////////////////////////////////////////////////
//Below this point code executes upon parsing.  Above are all functions definitions.
//////////////////////////////////////////////////////////////////////////////////////

document.editRegistryContext = new MEditRegistryContext();
