/*jslint devel: false, browser: true, undef: true, unparam: true, sloppy: true, vars: true, white: true, nomen: true, plusplus: true, maxerr: 50, indent: 4 */
/*global $, Event, Form, Tx, SSDialog, Store, SSFav, SSPDetails */

/* 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;
    this._previousColorSizeContext = null;
    this._refreshPageOnClose = true;
}

MEditRegistryContext.prototype.prepareRegistryDialog = function(refreshOnClose)
{
    this._previousColorSizeContext = SSPDetails.colorSizeContext;
    this._refreshPageOnClose = refreshOnClose;
    var registryContext = this;
    SSPDetails.colorSizeContext = registryContext;

    var closeObserver = function() {
        SSPDetails.colorSizeContext = registryContext._previousColorSizeContext;
        SSDialog.dialogContext.observers.removeObserver("close", closeObserver);
    };
    SSDialog.dialogContext.observers.addObserver("close", closeObserver);
};

// --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 = Tx.getResponseText(xmlhttp);
        if (!Tx.handleAjaxExceptionPage(dialogContents)) {
            var tempDiv = document.createElement("div");
            tempDiv.innerHTML = dialogContents;
            var targetDiv = document.getElementById('detailsdiv');
            targetDiv.parentNode.replaceChild(tempDiv.firstChild, targetDiv);
            Tx.findAndEvalJavascript(dialogContents);
            this.setColorSelection();
            this.findSizeSelection();
        }
    };
    var optionsDict = {
            asynchronous: true,
            method: 'get',
            onSuccess: handleAjaxResponse
    };
    var detailsUrlTag = Tx.findChildTagWithId(parentDiv, "a", "registryDetailsUrl");
    var url = detailsUrlTag.href;
    Tx.ajax(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 context = this;

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

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

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

};

MEditRegistryContext.prototype.setColors = function(colors, productId)
{
    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];
    SSPDetails.singleton.swizzleProductImage(detailsDiv, colorInfo.image);
    this._availableSizes = availableSizes;
};

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

    var detailsDiv = $('productDisplay');
    SSPDetails.singleton.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 = $(detailsDiv).down(".cellImg");
    detailsDiv.productImgSrc = productImg.src;

    SSPDetails.singleton.updateSizesForColor($('sizetable'), this._availableSizes);
};

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

MEditRegistryContext.prototype.handleSizeMouseOut = function(detailsSizeSpan, event)
{
    $(detailsSizeSpan).removeClassName('detailsSizeHilite');
    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;

    SSPDetails.singleton.updateColorsForSize($('colortable'), this._availableColors);
};

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

MEditRegistryContext.prototype.setColorSelection = function()
{
    // (Kevin 7/28/11) allow the continue
    /*jslint continue: true */

    this._productImg = SSPDetails.singleton.initializeProductImg($('productDisplay'));
    var productImgUrl = this._productImg.src;
    var productImgToken = SSPDetails.singleton.extractImageUrl(productImgUrl);

    var parenttd = $('colortable');

    var divs = parenttd.getElementsByTagName("div");
    var divsLength = divs.length;
    var colorIndex = 0;
    var chosenDiv = null;
    var divIndex;
    for (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;
    var ii;
    for (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);
};

// create singleton instance of the class
MEditRegistryContext.singleton = new MEditRegistryContext();

