/*
 * EditLookDialog support
 */
function MEditLookContext2(lookId, nUserFavorites, canvasX, canvasY, showComments, showSpread)
{
    this._favInfo = null;
    this._lookId = lookId;
    this._lookDiv = document.getElementById('basic_look');
    this._showingSpread = showSpread;
    this._showingDetails = false;
    this._canvasWidth = canvasX;
    this._canvasHeight = canvasY;

    this._showCommentFields = showComments;
    
    this._currentElement = null;
    var editLookContext = this;
    // editLookContext needs to watch dialog context for close
    // (if editLookContext was a kind of dialog, rather than independent, this would use methods-calling-super approach)
    var closeObserver = function(dialog) { editLookContext.handleClose(dialog);}
    this._closeObserver = document.dialogContext.observers.addObserver("close", closeObserver);
    // mark the dialog so we can tell which one is closing
    document.dialogContext.getActiveDialog()._dialogName = 'editLook';
    // also watch product details for changes to color
    var colorObserver = function(detailsFetcherDiv) { editLookContext.colorChanged(detailsFetcherDiv);};
    this._changeColorObserver = document.productDetailsContext.observers.addObserver("changeColor", colorObserver);
    document.productDetailsContext.observers.addObserver("cancelColor", colorObserver);
    
    this._favoritesScroller = new SS_scrollLoader('favorites', '.editFavoriteCell', 3, 3, 70, 88, 4, nUserFavorites, loadUserFavorites);
    this._imagesScroller = new SS_scrollLoader('userItems', '.editLookUserImage', 3, 3, 70, 70, 4, 30, null);
    this._productsScroller = new SS_scrollLoader('searchResults', '.editFavoriteCell', 3, 3, 70, 88, 4, 500, loadProducts);
    this._basicScroller = null;

    this._initializeDragResize();

    selectTextField($('title'));
}

MEditLookContext2.prototype._initializeDragResize = function()
{
    this._dragResize = new DragResize('dragresize', { minWidth: 25, minHeight: 25, minTop: 8, minLeft: 8, zIndex: 1, maxTop: this._canvasHeight, maxLeft: this._canvasWidth, constrained: true});
    this._dragResize.isElement = function(elm) { if (elm.className && elm.className.indexOf('drsElement') > -1) return true; };
    this._dragResize.isHandle = function(elm) { if (elm.className && elm.className.indexOf('drsMoveHandle') > -1) return true; };
    this._dragResize.ondragfocus = function() { document.editLookContext.setCurrentElement(this.element); };
    this._dragResize.ondragstart = function(isResize) { document.detailsContext.closeDetailsPopup();};
    this._dragResize.ondragmove = function(isResize) { };
    this._dragResize.ondragend = function(isResize) { };
    this._dragResize.ondragblur = function() { document.editLookContext.deselectElement(this.element); this.zIndex += 10;};
    this._dragResize.apply(document);
    this._dragResize.zIndex = this.highestz() + 10;
}
 
MEditLookContext2.prototype.saveLookClicked = function(event)
{
    this._closeDetails();
    store_disableButton('editLookSaveButton');
    store_disableButton('editLookCancelButton');
    
    $('newlook').value = '';
    $('newfavs').value = '';
    $('newcustomitem').value = '';
    // save the look
    if($('layoutType').value == 1) {
        this._saveSpreadLook('spread_look', 'spreadProductImage', 'newlook');
        this._saveSpreadLook('spread_look', 'spreadUserImage', 'newlook');
    } else {
        this._saveBasicLook(this._lookDiv, '.editLookCell2', 'newlook', true);
    }
    // save the current favorites
    this._saveBasicLook($('favorites'), '.editFavoriteCell', 'newfavs', false);
    this._saveBasicLook($('images'), '.editLookUserImage', 'newfavs', false);
    
    // save the custom image
    var customImage = $('customImage').down('img');
    if (customImage.id == 'originalCustomImage') {
        // no edit
        $('newcustomitem').value = 'originalCustomImage';
    }
    else if (customImage.id != 'customImageEmpty') {
        // we've set an image
        //the value is the id with the modifier stripped off
        $('newcustomitem').value = this._getNumericId(customImage.id);
    }
    // else the value will be left null - indicating a delete
    trimTextArea('description', 2000);
    openDialogForForm('editLookForm');
    Event.stop(event);
}

MEditLookContext2.prototype._closeDetails = function()
{
    if (this._showingDetails) {
        document.detailsContext.closeDetailsPopup();
        this._showingDetails = false;
    }
}

// save the non-spread look
MEditLookContext2.prototype._saveBasicLook = function(lookDiv, selector, listElem, sendColor)
{
    var ids = ";";
    var children = $(lookDiv).descendants();
    for (var i = 0; i < children.length; i++) {
        var element = children[i];
        if (element.match(selector) && element.style.display != 'none') {
            var colorToken = sendColor ? this._getFavInfo(element.id).colorToken : '';
            var type = 'f';
            if (this._isProduct(element.id)) {
                type = 'p';
            }
            else if (this._isUserItem(element.id)) {
                type = 'u';
            }
            ids = ids + this._getNumericId(element.id) + ',' + colorToken + ',' + type + ';'; 
        }
    }    
    $(listElem).value += ids;
}

// save product images from spread
MEditLookContext2.prototype._saveSpreadLook = function(lookDiv, className, listElem)
{   
    var serial = "";
    var serial_template = new Template('#{id},#{color},#{left},#{top},#{width},#{height},#{z},#{transparent},#{type};');
    var context = this;
    $$('#' + lookDiv + ' .' + className).each(function(element) {
        var favInfo = context._getFavInfo(element.id);
        var ttoken = "0";
        if (favInfo != null && favInfo.transparent) {
            ttoken = "1";
        }
        z_index = element.getStyle('zIndex');
        if (z_index == null || z_index == 'normal' || z_index == 'auto') {
            z_index = 1;
        }
        var type = 'f';
        if (context._isProduct(element.id)) {
            type = 'p';
        }
        else if (context._isUserItem(element.id)) {
            type = 'u';
        }
        var colorToken = '0';
        if ((type == 'f' || type == 'p') && favInfo.colorToken) {
            colorToken = favInfo.colorToken;
        }
        serial += serial_template.evaluate({
            id: context._getNumericId(element.id),
            type: type,
            color: colorToken,
            left: Position.positionedOffset(element)[0],
            top: Position.positionedOffset(element)[1],
            width: element.getWidth(),
            height: element.getHeight(),
            z: z_index,
            transparent: ttoken
        });

    });
    $(listElem).value += serial;
}

MEditLookContext2.prototype.removeAllFavorites = function()
{
    for (sid in this._favInfo) {
        if (this._favInfo[sid].inLook) {
            this.removeFav(sid, true);
        }
    }
    
    // take care of arrangements
    this._favoritesScroller.arrange(false);
    if (this._basicInitialized) {
        this._basicScroller.arrange(false);
    }
}

// move item from canvas into favorites list
MEditLookContext2.prototype.removeFav = function(elementId, removingMany)
{
    this._closeDetails();
    
    var thumb_template = new Template("<div id='#{id}' class='editFavoriteCell' style='position:absolute'><img border='0' src='#{src}'/>"
    +"</div>");
    
    //remove from spread canvas (if it exists)
    var spreadElementId = this._getSpreadElementId(elementId);
    if ($(spreadElementId)) {
        $(spreadElementId).remove();
        if($(spreadElementId)) {
            $(spreadElementId).remove(); //do this twice - safari bug
        }
    }
    
    var basicElementId = this._getBasicElementId(elementId);
    if ($(basicElementId)) {
        $(basicElementId).remove();
        if($(basicElementId)) {
            $(basicElementId).remove(); //do this twice - safari bug
        }
    }
    
    var favInfo = this._getFavInfo(elementId);
    favInfo.transparent = false;
    favInfo.colorUrl = null;
    favInfo.colorToken = null;
    favInfo.inLook = false;
    if (this._isFavorite(elementId)) {
        var tabElementId = this._getTabElementId(elementId);
        var html = thumb_template.evaluate({
            id: tabElementId,
            src: this._getTabImageUrl(elementId)
        });
        var favoritesDiv = $('favorites');
        favoritesDiv.insert({top: html});
        if (!removingMany) {
            this._favoritesScroller.arrange(false);
        }
        
        // make the new favorite item draggable
        new Draggable(tabElementId,  {ghosting: true, ghostParent: '#availableItems'});
    }
    
    if (!removingMany && this._basicInitialized) {
        this._basicScroller.arrange(false);
    }
    
    this._canvasChanged();
}

// move user image from canvas into images list
MEditLookContext2.prototype.removeUserImage = function(elementId)
{
    //remove from spread canvas (if it exists)
    if ($(elementId)) {
        $(elementId).remove();
        if($(elementId)) {
            $(elementId).remove(); //do this twice - safari bug
        }
    }
    // no removal from basic because we don't put user items there
    
    this._getFavInfo(elementId).inLook = false;

    /*  this isn't applicable until we can actually delete user images
    if ($(this._getTabElementId(elementId)) == null) {
        // create an image in the user items tab
        this._insertUserImage(this._getItemId(elementId));
        setTimeout("editLookResizeUserImages(0)", 1000);
    }
    */
    this._canvasChanged();
}

MEditLookContext2.prototype._canvasChanged = function()
{
    if ($$('#spread_look .spreadProductImage').length == 0 && $$('#spread_look .spreadUserImage').length == 0 && $$('#basic_look .editLookCell2').length == 0) {
        $('emptyLookHint').show();
    } else {
        $('emptyLookHint').hide();
    }
}

// insert a new user image into the list of available user images
// called via javascript handed back to client from server
MEditLookContext2.prototype.insertUserImage = function(userItemId, imageUrl)
{
    var itemId = 'u' + userItemId;
    // add entry into favInfo
    var favInfo = new Object();
    favInfo.inLook = false;
    favInfo.isProduct = false;
    favInfo.imageLarge = imageUrl;
    favInfo.imageMedium = imageUrl.replace(/\.jpg/, "_medium.jpg");
    favInfo.transparent = false;
    favInfo.height = -1;
    this._favInfo[itemId] = favInfo;

    // add image to sample sizes div
    var sampleTemplate = new Template('<img src="#{src}" id="#{id}" style="visibility:hidden; position: absolute; top:0px; left: 0px;" />');
    var html = sampleTemplate.evaluate({
        id: this._getSampleElementId(itemId),
        src: this._getSampleImageUrl(itemId)
    });
    $('sizeSampler').insert({bottom: html});
    
    // add image to user items tab
    this._insertUserImage(this._getItemId(itemId));

    // kick off resizing again
    setTimeout("editLookResizeUserImages(0)", 1000);

    this._imagesScroller.arrange(false);
}

// insert user item into user images tab
MEditLookContext2.prototype._insertUserImage = function(itemId)
{
    var thumb_template = new Template("<img border='0' id='#{id}' class='editLookUserImage' src='#{src}' style='position:absolute;overflow:hidden' onload='document.editLookContext.loadedUserImage(\"#{itemId}\")'/>");
    
    var tabElementId = this._getTabElementId(itemId);
    var html = thumb_template.evaluate({
        id: tabElementId,
        itemId: itemId,
        src: this._getTabImageUrl(itemId)
    });
    $('userItems').insert({top: html});

    // make the new image draggable
    new Draggable(tabElementId,  {ghosting: true, ghostParent: '#availableItems'});    
}

MEditLookContext2.prototype.initializeLayouts = function(favInfo) {
    this._favInfo = favInfo;

    // arrange the various favorites
    this._favoritesScroller.arrange(true);
    this._imagesScroller.arrange(true);
    // products tab is empty at start, so don't bother arranging
    
    // initialize color information
    for (sid in this._favInfo) {
        var favInfo = this._favInfo[sid];
        if (favInfo.isProduct) {
            var sampleElement = $(this._getSampleElementId(sid));
            favInfo.colorUrl = this._calculateColorUrl(sampleElement.src);
            favInfo.colorToken = document.productDetailsContext.extractImageUrl(sampleElement.src);
        }
    }

    // initialize layouts lazily (let sample images have time to load)
    this._spreadInitialized = false;
    this._basicInitialized = false;
    if (this._showingSpread) {
        this.showSpread();
    }
    else {
        this.showBasic();
    }
    
    // start resizing of user images
    setTimeout("editLookResizeUserImages(0)", 1000);
    setTimeout("editLookResizeCustomImage(0)", 200);

    this._setupSpreadDragDrop();
}

MEditLookContext2.prototype._initializeSpreadLayout = function()
{
    // set up the spread look
    for (sid in this._favInfo) {
        if (this._favInfo[sid].inLook) {
            this._initSpreadFav(sid);
        }
    }
    this._spreadInitialized = true;
    this._canvasChanged();
}

MEditLookContext2.prototype._initializeBasicLayout = function()
{
    // set up the spread look
    for (sid in this._favInfo) {
        if (this._favInfo[sid].inLook && this._favInfo[sid].isProduct) {
            this._initBasicFav(sid);
        }
    }
    this._basicScroller = new SS_scrollLoader('basic_look', '.editLookCell2', 3, 3, 138, 195, 3, 5000, null);
    this._basicScroller.arrange(true);

    this._basicInitialized = true;
}


MEditLookContext2.prototype.showSpread = function() {
    this._closeDetails();

    if (!this._spreadInitialized) {
        this._initializeSpreadLayout();
    }
    
    $('basic_look').hide();
    //spread look needs to be invisible vs. "hidden" so products can be positioned in the background
    $('spread_look').setStyle({
        "visibility": "visible"
    });
    $('layoutType').value = '1';
    $('radio_basic_label').addClassName('radioOff').removeClassName('radioOn');
    $('radio_spread_label').removeClassName('radioOff').addClassName('radioOn');
    store_enableButton('removeBkgd');
    store_enableButton('restoreBkgd');
    store_enableButton('moveBack');
    this._showingSpread = true;
}

MEditLookContext2.prototype.showBasic = function() {
    this._closeDetails();
    
    if (!this._basicInitialized) {
        this._initializeBasicLayout();
    }
    
    //spread look needs to be invisible vs. "hidden" so products can be positioned in the background
    $('spread_look').setStyle({
        "visibility": "hidden"
    });
    $('basic_look').show();
    $('layoutType').value = '0';
    $('radio_spread_label').addClassName('radioOff').removeClassName('radioOn');
    $('radio_basic_label').removeClassName('radioOff').addClassName('radioOn');
    store_disableButton('removeBkgd');
    store_disableButton('restoreBkgd');
    store_disableButton('moveBack');
    this._showingSpread = false;
}

//switch the favorites tab display
MEditLookContext2.prototype.switchFavorites = function(event, showid, newTabId)
{
    Event.stop(event);

    $('favorites').style.display='none';
    $('images').style.display='none';
    $('products').style.display='none';
    $(showid).style.display='block';
    
    $('favoritesTab').removeClassName('active');
    $('imagesTab').removeClassName('active');
    $('productsTab').removeClassName('active');
    $(newTabId).addClassName('active');
    
    return false;
}

MEditLookContext2.prototype.doSearch = function(event)
{
    Event.stop(event);
    // get the information about the products
    var text = $('editLookSearch').value;
    var productInfo = tx_ajaxJSON('/action/editLookSearchProducts?fts=' + text);
    
    // clear out old content
    $('searchResults').update();
    this._productsScroller.reset();
    
    var count = this._loadProducts(productInfo, 'searchResults', 'productSamples');
    
    this._productsScroller.arrange(true);
    
    if (count == 0) {
        $('noMatches').show();
    } else {
        $('noMatches').hide();
    }
    
    return false;
}

function loadProducts(min, count)
{
    // get the information about the products
    var text = $('editLookSearch').value;
    var url = '/action/editLookSearchProducts?fts=' + text + '&min=' + min + '&count=' + count;
    var productInfo = tx_ajaxJSON(url);
    
    document.editLookContext._loadProducts(productInfo, 'searchResults', 'productSamples');
    document.editLookContext._productsScroller.doneLoading();
}

function loadUserFavorites(min, count)
{
    var context = document.editLookContext;
    
    // get the information about the favorites
    var url = '/action/editLookLoadFavorites?lookId=' + context._lookId + '&min=' + min + '&count=' + count + '&isFavorites=1';
    var favoriteInfo = tx_ajaxJSON(url);
    
    context._loadProducts(favoriteInfo, 'favorites', 'sizeSampler');
    context._favoritesScroller.doneLoading();
}

MEditLookContext2.prototype._loadProducts = function(productInfo, tabDivId, sampleDivId)
{
    // create new items - tab & samples.
    var tabTemplate = new Template("<div id='#{tabId}' class='editFavoriteCell' style='position:absolute;top:0px;left:0px'><img border='0' src='#{tabSrc}'/></div>");
    var sampleTemplate = new Template("<img src='#{sampleSrc}' id='#{sampleId}' style='visibility:hidden; position: absolute; top:0px; left: 0px;'/>");
    var count = 0;
    
    for (pid in productInfo) {
        var info = productInfo[pid];
        this._favInfo[pid] = info;
        var tabId = this._getTabElementId(pid);
        var tabHtml = tabTemplate.evaluate({
            tabId: tabId,
            tabSrc: this._getTabImageUrl(pid)
        });
        var sampleSrc = this._getSampleImageUrl(pid);
        var sampleHtml = sampleTemplate.evaluate({
            sampleId: this._getSampleElementId(pid),
            sampleSrc: sampleSrc
        });
        $(tabDivId).insert({bottom: tabHtml});
        $(sampleDivId).insert({bottom: sampleHtml});
        
        info.colorUrl = this._calculateColorUrl(sampleSrc);
        info.colorToken = document.productDetailsContext.extractImageUrl(sampleSrc);

        // make the item draggable
        new Draggable(tabId,  {ghosting: true, ghostParent: '#availableItems'});
        ++count;
    }
    return count;
}

MEditLookContext2.prototype.highestz = function() {
    z = 1;
    $$(".drsElement").each(function(element) {
        new_z = parseInt(element.getStyle('zIndex'));
        if(new_z > z) {
            z = new_z;
        }
    });
    return z;
}

MEditLookContext2.prototype.lowestz = function() {
    z = 999999;
    $$(".drsElement").each(function(element) {
        new_z = parseInt(element.getStyle('zIndex'));
        if(new_z < z) {
            z = new_z;
        }
    });
    return z;
}

function editLookDrop(drag, drop, event)
{
    document.editLookContext._spreadDrop(drag, drop, event);
}

function editBasicDrop(drag, drop, event)
{
    document.editLookContext._basicDrop(drag, drop, event);
}

function editCustomDrop(drag, drop, event)
{
    document.editLookContext._customDrop(drag, drop, event);
}

function editItemGarbageDrop(drag, drop, event)
{
    alert("delete not implemented " + drag.id);
}

MEditLookContext2.prototype._basicDrop = function(drag, drop, event)
{
    // move the drag item before the drop item
    this._closeDetails();
    this._lookDiv.insertBefore(drag, drop);
    this._basicScroller.arrange(false);
}

MEditLookContext2.prototype._spreadDrop = function(drag, drop, event)
{
    var voff = $('canvas').viewportOffset();
    var xx = event.clientX - voff[0];
    var yy = event.clientY - voff[1];
    
    if ($(drag).match('.editLookUserImage')) {
        this._putUserImageInLook(drag, xx, yy);
    }
    else {
        this._putFavInLook(drag, xx, yy);
        this._favoritesScroller.arrange(false);
    }
}

MEditLookContext2.prototype._customDrop = function(drag, drop, event)
{
    var img = $('customImage').down('img');
    img.style.display = 'inline';
    img.src = this._getSpreadImageUrl(drag.id);
    img.id = this._getCustomElementId(drag.id);
    
    var sampleImg = $(this._getSampleElementId(drag.id));
    this._adjustImageSize(img, sampleImg, 230, 145);

    $('customImageDelete').style.display = 'block';
}

MEditLookContext2.prototype.customDelete = function()
{
    var img = $('customImage').down('img');
    img.style.display = 'none';
    img.id = 'customImageEmpty';
    
    $('customImageDelete').style.display = 'none';
}

MEditLookContext2.prototype.loadedUserImage = function(id)
{
    var sampleImg = $(this._getSampleElementId(id));
    var image = $(this._getTabElementId(id));
    this._adjustImageSize(image, sampleImg, 60, 60);
}

function editLookResizeCustomImage(nTries)
{
    var context = document.editLookContext;
    var skipped = 0;
    var items = $$('#customImage img');
    for (var ii=0; ii<items.length; ii++) {
        var image = $(items[ii]);
        if (!image.imageSized) {
            if (image.getWidth() > 0) {
                context._adjustImageSize(image, image, 230, 145);
                image.imageSized = true;
            }
            else {
                skipped++;
            }
        }
    }
    
    if (skipped > 0 && nTries < 10) {
        // reschedule for another try
        setTimeout("editLookResizeCustomImage(" + (nTries+1) + ")", 500);
    }
}

function editLookResizeUserImages(nTries)
{
    var context = document.editLookContext;
    var skipped = 0;
    var items = $$('#userItems .editLookUserImage');
    for (var ii=0; ii<items.length; ii++) {
        var image = $(items[ii]);
        if (!image.imageSized) {
            var sampleImg = $(context._getSampleElementId(image.id));
            if (sampleImg && sampleImg.getWidth() > 0) {
                context._adjustImageSize(image, sampleImg, 60, 60);
                image.imageSized = true;
            }
            else {
                skipped++;
            }
        }
    }
    
    if (skipped > 0 && nTries < 10) {
        // reschedule for another try
        setTimeout("editLookResizeUserImages(" + (nTries+1) + ")", 500);
    }
}

MEditLookContext2.prototype._adjustImageSize = function(image, sampleImg, maxWidth, maxHeight)
{
    var width = sampleImg.getWidth();
    var height = sampleImg.getHeight();
    
    if (width > maxWidth || height > maxHeight) {
        // need to squeeze image, squish the dimension that is most out of bounds, so that we preserve the aspect ratio
        if (width/maxWidth > height/maxHeight) {
            image.width = maxWidth;
            image.height = height * maxWidth/width;
        }
        else {
            image.height = maxHeight;
            image.width = width * maxHeight/height;
        }
    }
    else {
        image.width = width;
        image.height = height;
    }
}

MEditLookContext2.prototype._putUserImageInLook = function(tabElement, centerX, centerY)
{
    // put in spread
    var itemId = this._getItemId(tabElement.id);
    var sampleImg = $(this._getSampleElementId(itemId));
    this._favInfo[itemId].height = -1; // force a new layout
    this._favInfo[itemId].inLook = true;
    var spreadItem = this._insertSpread(itemId, $('canvas'), sampleImg, centerX, centerY);
    
    this._updateSelection(spreadItem);
    this._canvasChanged();
    
    // we do NOT put into the basic look
    
    // don't remove from user image display, so user doesn't end up re-uploading the image
    // $(userImage).remove();
}

MEditLookContext2.prototype._putFavInLook = function(favElement, centerX, centerY)
{
    if (!this._basicInitialized) {
        this._initializeBasicLayout();
    }
    if (!this._spreadInitialized) {
        this._initializeSpreadLayout();
    }

    var itemId = this._getItemId(favElement.id);
    var favImg = $(favElement).down("img");
    
    // put the item on the spread and basics divs
    this._favInfo[itemId].height = -1; // force a new layout
    this._favInfo[itemId].inLook = true;
    var basicItem = this._insertBasic(itemId, $('basic_look'), favImg);
    var spreadItem = this._insertSpread(itemId, $('canvas'), favImg, centerX, centerY);

    if (this._showingSpread) {
        this._updateSelection(spreadItem);
    }
    this._canvasChanged();

    //remove favorite from the favorites tray (arrangement done in caller)
    $(favElement).remove();
    
    this._basicScroller.arrange(false);
    
    if (!this._showingSpread) {
        this.scrollToShow(this._lookDiv, basicItem);
    }
    
}

MEditLookContext2.prototype.setCurrentElement = function(element) {
    this._currentElement = element;
    var favInfo = this._getFavInfo(element.id);
    if (favInfo.isProduct) {
        store_enableButton('removeBkgd');
        store_enableButton('restoreBkgd');
        if (favInfo.transparent) {
            $('removeBkgd').down('div').style.display='none';
            $('restoreBkgd').down('div').style.display='block';
        }
        else {
            $('removeBkgd').down('div').style.display='block';
            $('restoreBkgd').down('div').style.display='none';
        }
    }
    else {
        store_disableButton('removeBkgd');
        store_disableButton('restoreBkgd');
    }
    element.select('.deleteItemButton')[0].show();
    var colorButton = element.select('.chooseColorButton');
    if (colorButton.length > 0) {
    	colorButton[0].show();
    }
    
    return favInfo.zIndex;
}

MEditLookContext2.prototype.deselectElement = function(element) {
	if (element != null) {
	    element.select('.deleteItemButton')[0].hide();
	    var colorButton = element.select('.chooseColorButton');
	    if (colorButton.length > 0) {
	    	colorButton[0].hide();
	    }
	}
}

MEditLookContext2.prototype._updateSelection = function(elem)
{
	if (this._dragResize.element != null) {
	    this._dragResize.deselect(true);
	}
	this._dragResize.select(elem);
}

MEditLookContext2.prototype.toggleBackground = function() {
    if (this._currentElement != null) {
        var itemStyle = this._getFavInfo(this._currentElement.id);
        if (itemStyle.transparent) {
            this._restoreBackground(this._currentElement);
        }
        else {
            this._removeBackground(this._currentElement);
        }
        this.setCurrentElement(this._currentElement);
    }
}

MEditLookContext2.prototype.removeBackground = function() {
    if (this._currentElement != null) {
        this._removeBackground(this._currentElement);
        this.setCurrentElement(this._currentElement);
    }
}

MEditLookContext2.prototype._removeBackground = function(element) {
    var itemStyle = this._getFavInfo(element.id);
    var imgElement = $(element).down("img");
    if (!itemStyle.transparent) {
        itemStyle.transparent = true;
        imgElement.src = this._getSpreadImageUrl(element.id);
        // IE6 hack to handle png transparency
        if (isIE6()) {
            imgElement.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + imgElement.src + "', sizingMethod='scale')";
            imgElement.src = $('cleardot').src;
        }
    }
}
MEditLookContext2.prototype.restoreBackground = function() {
    if (this._currentElement != null) {
        this._restoreBackground(this._currentElement);
        this.setCurrentElement(this._currentElement);
    }
}

MEditLookContext2.prototype._restoreBackground = function(element) {
    var itemStyle = this._getFavInfo(element.id);
    var imgElement = $(element).down("img");
    if (itemStyle.transparent) {
        itemStyle.transparent = false;
        imgElement.src = this._getSpreadImageUrl(element.id);
    }
}

MEditLookContext2.prototype.moveToBack = function() {
    if (this._currentElement != null) {
        var lowestz = this.lowestz();
        if (lowestz > 2) {
            this._currentElement.style.zIndex = lowestz-1;
        }
        else {
            // redo zindex for all the items so we don't push anything behind the canvas
            $$('.drsElement').each(function(element){
                element.style.zIndex = 100 + 10*element.style.zIndex;
            });
            this._currentElement.style.zIndex = 90;
            this._dragResize.zIndex = this.highestz() + 10;
        }
    }
}

MEditLookContext2.prototype._initSpreadFav = function(itemId)
{
    var favInfo = this._getFavInfo(itemId);
    var centerX = 100;
    var centerY = 100;
    if (favInfo.height <= 0) {
        // we don't already have a layout, so create a random position for the item
        centerX = Math.floor(Math.random()*this._canvasWidth);
        centerY = Math.floor(Math.random()*this._canvasHeight);
    }
    else {
        centerX = favInfo.left + favInfo.width/2;
        centerY = favInfo.top + favInfo.height/2;
    }
    var sampleId = this._getSampleElementId(itemId);
    this._insertSpread(itemId, $('canvas'), $(sampleId), centerX, centerY);
}

MEditLookContext2.prototype._initBasicFav = function(itemId)
{
    var sampleId = this._getSampleElementId(itemId);
    this._insertBasic(itemId, $('basic_look'), $(sampleId));
}

MEditLookContext2.prototype._insertSpread = function(itemId, destination, colorImage, centerX, centerY)
{
    var favInfo = this._getFavInfo(itemId);
    var detailsAction = favInfo.detailsActionSpread;

    var html = null;
    if (favInfo.isProduct) {
        var imageHtml = "";
        var colorButton = "";
        if (detailsAction != null && detailsAction.length > 0) {
            imageHtml = 
                '<a id="rawDetailsUrl" style="display:none" href="#{detailsAction}" rel="nofollow"></a>'
                +'<img id="i_#{id}" class="cellImg hero" src="#{src}" />'
                +'<span id="changeColorLink" style="display:none"></span>';
            colorButton = '<div onclick="document.editLookContext.spreadColorPopup(this, event);" onmousedown="Event.stop(event);" onmouseup="Event.stop(event);" class="chooseColorButton" style="display:none">&nbsp;</div>';
        }
        else {
            imageHtml = '<img id="i_#{id}" class="cellImg hero" src="#{src}" />';
        }
    
        html =
            '<div id="#{id}" class="spreadProductImage drsElement drsMoveHandle" style="position: absolute; height: #{h}px; width: #{w}px; top: #{top}px; left: #{left}px; z-index: #{zindex};">'
               +'<div id="editLookFetcher" style="width:100%; height:100%;">'
                   + imageHtml
               +'</div>'
               +'<div class="deleteItemButton" style="display:none" onclick="document.editLookContext.removeFav(\'#{id}\');">&nbsp;</div>'
               + colorButton
            +'</div>';
    }
    else {
        // user image
        html = 
            '<div id="#{id}" class="spreadUserImage drsElement drsMoveHandle" style="position: absolute; height: #{h}px; width: #{w}px; top: #{top}px; left: #{left}px; z-index: #{zindex};">'
                +'<img src="#{src}" style="width: 100%; height: 100%;" />'
                +'<div class="deleteItemButton" style="display:none" onclick="document.editLookContext.removeUserImage(\'#{id}\');">&nbsp;</div>';
            +'</div>';
    }
    
    template = new Template(html);
    
    // if we don't have a layout, create one
    if (favInfo.height <= 0) {
        var sampleImage = $(this._getSampleElementId(itemId));
        favInfo.height = sampleImage.getHeight();
        favInfo.width = sampleImage.getWidth();
        favInfo.transparent = false;
        // make the new item frontmost
        favInfo.zindex = this.highestz() + 10;
    }
    // set the position
    favInfo.left = centerX - favInfo.width/2;
    if (favInfo.left < 0) {
        favInfo.left = 0;
    }
    else if (favInfo.left + favInfo.width > this._canvasWidth) {
        favInfo.left = this._canvasWidth - favInfo.width;
    }
    favInfo.top = centerY - favInfo.height/2;
    if (favInfo.top < 0) {
        favInfo.top = 0;
    }
    else if (favInfo.top + favInfo.height > this._canvasHeight) {
        favInfo.top = this._canvasHeight - favInfo.height;
    }
    
    var spreadElementId = this._getSpreadElementId(itemId);
    var html = template.evaluate({
        id: spreadElementId,
        src: this._getSpreadImageUrl(itemId),
        top: favInfo.top,
        left: favInfo.left,
        h: favInfo.height,
        w: favInfo.width,
        zindex: favInfo.zindex,
        detailsAction: detailsAction
    });
    $(destination).insert({bottom: html});
    
    // IE6 hack to handle png transparency
    if (favInfo.transparent && isIE6()) {
        var theImage = $('i_' + spreadElementId);
        theImage.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + theImage.src + "', sizingMethod='scale')";
        theImage.src = $('cleardot').src;
    }

    //$(itemId).setStyle({"zIndex":favInfo.zindex});
    
    // make sure the drag is above everything
    this._dragResize.zIndex = this.highestz()+10;
    
    return $(spreadElementId);
}

MEditLookContext2.prototype._insertBasic = function(itemId, destination, colorImage)
{
    var favInfo = this._getFavInfo(itemId);
    var detailsAction = favInfo.detailsActionBasic;
    
    var template = null;
    if (detailsAction != null && detailsAction.length > 0) {
        template = new Template(
        '<div id="#{id}" class="editLookCell2">'
        +'<center>'
            +'<img src="/im/chooseColor.gif" style="cursor:pointer;padding-right:2px" border="0" onclick="document.editLookContext.basicColorPopup(this, event);"/>'
            +'<img id="removeFav" width="14" height="14" border="0" title="' + store_getMessage('editLookRemove')
               +'" style="cursor:pointer" src="/im/delete-box.gif" title="ognl:removeHint"'
                 +'onclick="document.editLookContext.removeFav(\'#{id}\');"/>'
          +'<br/>'
          +'<table style="height: 140px;">'
              +'<tr>'
                  +'<td valign="middle" align="center">'
                      +'<div id="editLookFetcher">'
                              +'<a id="rawDetailsUrl" style="display:none" href="#{detailsAction}" rel="nofollow"></a>'
                              +'<span style="margin:auto 0px;">'
                                  +'<img id="#{id}_img" class="cellImg" border="0" src="#{src}"/>'
                              +'</span>'
                              +'<span id="changeColorLink" style="display:none"></span>'
                      +'</div>'
                  +'</td>'
              +'</tr>'
          +'</table>'
          +(this._showCommentFields ? '<div><input type="text" name="#{commentName}" value="#{comment}" size="12" class="userProfileTextField" style="font-size:11px;width:100px"/></div>' :
                                     '<div id="productName" class="productCellText productCellTwoTextLinesFixed">#{text}</div>')
          +'</span>'
        +'</center>'
       +'</div>');
    }
    else {
        template = new Template(
          '<div id="#{id}" class="editLookCell2">'
                +'<center>'
                +'<img id="removeFav" width="14" height="14" border="0" title="' + store_getMessage('editLookRemove')
                   +'" style="cursor:pointer" src="/im/delete-box.gif" title="ognl:removeHint"'
                     +'onclick="document.editLookContext.removeFav(\'#{id}\');"/>'
              +'<br/>'
              +'<table style="height: 140px;line-height:140px;vertical-align:middle;">'
                  +'<tr>'
                      +'<td valign="middle" align="center">'
                          +'<div>'
                                  +'<span style="margin:auto 0px">'
                                      +'<img id="#{id}_img" class="cellImg" border="0" src="#{src}"/>'
                                  +'</span>'
                          +'</div>'
                      +'</td>'
                  +'</tr>'
              +'</table>'
              +(this._showCommentFields ? '<div><input type="text" name="#{commentName}" value="#{comment}" size="12" class="userProfileTextField" style="font-size:11px;width:100px"/></div>' :
              '<div id="productName" class="productCellText productCellTwoTextLinesFixed">#{text}</div>')
            +'</center>'
        +'</div>');
    }
    
    var basicElementId = this._getBasicElementId(itemId);
        
    var html = template.evaluate({
        id: basicElementId,
        src: this._getBasicImageUrl(itemId),
        detailsAction: detailsAction,
        commentName: this._getCommentElementId(itemId),
        comment: favInfo.comment,
        text: favInfo.productName
    });

    $(destination).insert({bottom: html});
    
    // make the item draggable, with scrolling
    new Draggable(basicElementId, {scroll: 'basic_look'});
    // make the outer div droppable (to allow rearrangment)
    Droppables.add(basicElementId, {accept: 'editLookCell2', onDrop: editBasicDrop});
    
    return $(basicElementId);
}

MEditLookContext2.prototype._setupSpreadDragDrop = function()
{
    // make the spread canvas a drop target
    Droppables.add('canvas', {accept: new Array('editFavoriteCell', 'editLookUserImage'), onDrop: editLookDrop});
    
    // make the favorite items draggable
    var favorites = $$('#favorites .editFavoriteCell');
    favorites.each(function(fav) {
        new Draggable(fav.id,  {ghosting: true, ghostParent: '#availableItems'});
    });
    
    // make user images draggable
    var userImages = $$('#images .editLookUserImage');
    userImages.each(function(ui) {
        new Draggable(ui.id,  {ghosting: true, ghostParent: '#availableItems'});
    });

    // make the custom image a drop target for user items
    Droppables.add('customImage', {accept: new Array('editLookUserImage'), onDrop: editCustomDrop});
    // and also the garbage can
    //Droppables.add('itemGarbage', {accept: new Array('editLookUserImage'), onDrop: editItemGarbageDrop});
}

MEditLookContext2.prototype.spreadColorPopup = function(button, event)
{
    var parentDiv = button.parentNode;
    var fetcherDiv = findChildWithId(parentDiv, 'editLookFetcher');
    document.detailsContext.showDetailsPopup(fetcherDiv, event, true);
    this._showingDetails = true;
    Event.stop(event);
}

MEditLookContext2.prototype.basicColorPopup = function(button, event)
{
    var parentDiv = findParentWithClass(button, 'editLookCell2');
    var fetcherDiv = findChildWithId(parentDiv, 'editLookFetcher');
    document.detailsContext.showDetailsPopup(fetcherDiv, event, true);
    this._showingDetails = true;
    Event.stop(event);
}

MEditLookContext2.prototype.handleClose = function(dialogClosing)
{
    if (dialogClosing._dialogName == 'editLook') {
        // we are closing (not some other dialog)
        
        // stop observing colorChange events from the details context
        document.productDetailsContext.observers.removeObserver("changeColor", this._changeColorObserver);
        // and the close observer from the dialog context
        document.dialogContext.observers.removeObserver("close", this._closeObserver);
        
        // help out the garbage collector
        this._dragResize = null;
        this._favInfo = null;
    
        this._closeDetails();
    }
}

// callback from productdetails - that the color of an item has been changed
MEditLookContext2.prototype.colorChanged = function(fetcherDiv)
{
    var topNode = null;
    if (this._showingSpread) {
        topNode = fetcherDiv.parentNode;
    }
    else {
        topNode = findParentWithClass(fetcherDiv, 'editLookCell2');
    }
    var sourceImg = $(fetcherDiv).down(".cellImg");
    var favInfo = this._getFavInfo(topNode.id);
    favInfo.colorUrl = this._calculateColorUrl(sourceImg.src);
    favInfo.colorToken = document.productDetailsContext.extractImageUrl(sourceImg.src);
    
    if (this._showingSpread) {
        // set spread image (to account for transparency)
        sourceImg.src = this._getSpreadImageUrl(topNode.id);
        
        // change image of the hidden basic
        if (!this._basicInitialized) {
            this._initializeBasicLayout();
        }
        var basicId = this._getBasicElementId(topNode.id);
        var destImg = $(basicId).down(".cellImg");
        destImg.src = this._getBasicImageUrl(topNode.id);
    }
    else {
        // change image of the hidden spread
        if (!this._spreadInitialized) {
            this._initializeSpreadLayout();
        }
        var destImg = $(this._getSpreadElementId(topNode.id)).down(".cellImg");
        destImg.src = this._getSpreadImageUrl(topNode.id);
    }
}

MEditLookContext2.prototype.keyPress = function(event)
{
    if (event.keyCode == Event.KEY_RETURN && !this.formIgnoreCR) {
        this.saveLookClicked(event);
    }
    this.formIgnoreCR = false;
}

MEditLookContext2.prototype.titleKeyPress = function(event)
{
    if (event.keyCode == Event.KEY_TAB) {
        selectTextField($('description'));
        Event.stop(event);
    }
}

MEditLookContext2.prototype.descriptionKeyPress = function(event)
{
    if (event.keyCode == Event.KEY_TAB) {
        selectTextField($('tags'));
        Event.stop(event);
    }
    else if (event.keyCode == Event.KEY_RETURN) {
        this.formIgnoreCR = true;
    }
}

MEditLookContext2.prototype.searchKeyPress = function(event)
{
    if (event.keyCode == Event.KEY_TAB) {
        // ignore
        Event.stop(event);
    }
    else if (event.keyCode == Event.KEY_RETURN) {
        // doSearch does an event stop, so we don't need to set formIgnoreCR
        this.doSearch(event);
    }
}

MEditLookContext2.prototype.tagsKeyPress = function(event)
{
    if (event.keyCode == Event.KEY_TAB) {
        selectTextField($('title'));
        Event.stop(event);
    }
}

MEditLookContext2.prototype.scrollToShow = function(lookDiv, elem)
{
    if (lookDiv.style.overflow == 'auto') {
        lookDiv.scrollTop = elem.offsetTop + elem.clientHeight - lookDiv.clientHeight;
    }
}

MEditLookContext2.prototype._getFavInfo = function(id)
{
    return this._favInfo[this._getItemId(id)];
}

// get the numeric portion of the element - note that this loses the distinction between favorites and user items
MEditLookContext2.prototype._getNumericId = function(id)
{
    return this._getItemId(id).substring(1);
}

MEditLookContext2.prototype._getSampleElementId = function(id)
{
    // replace the size modifier with the sample modifier
    return 'q_' + this._getItemId(id);
}

MEditLookContext2.prototype._getSpreadElementId = function(id)
{
    // change the size/sample modifier
    return 's_' + this._getItemId(id);
}

MEditLookContext2.prototype._getBasicElementId = function(id)
{
    // change the size/sample modifier
    return 'b_' + this._getItemId(id);
}

MEditLookContext2.prototype._getTabElementId = function(id)
{
    // change the size/sample modifier
    return 't_' + this._getItemId(id);
}

MEditLookContext2.prototype._getCustomElementId = function(id)
{
    // change size/sample modifier
    return 'k_' + this._getItemId(id);
}

MEditLookContext2.prototype._getCommentElementId = function(id)
{
    // change size/sample modifier
    return 'c_' + this._getItemId(id);
}

MEditLookContext2.prototype._getItemId = function(id)
{
    var c1 = id.charAt(0);
    // u: user item, f: favorite, p: product
    if (c1 == 'u' || c1 == 'f' || c1 == 'p') {
        // this is an itemid already
        return id;
    }
    else {
        // presumably this is an element id - strip off the modifier
        return id.substring(2);
    }
}

MEditLookContext2.prototype._isFavorite = function(id)
{
    return this._getItemId(id).charAt(0) == 'f';
}

MEditLookContext2.prototype._isProduct = function(id)
{
    return this._getItemId(id).charAt(0) == 'p';
}

MEditLookContext2.prototype._isUserItem = function(id)
{
    return this._getItemId(id).charAt(0) == 'u';
}

MEditLookContext2.prototype._getTabImageUrl = function(itemId)
{
    var favInfo = this._getFavInfo(itemId);
    if (this._isUserItem(itemId)) {
        return favInfo.imageMedium;
    }
    else {
        return favInfo.imageSmall;
    }
}

MEditLookContext2.prototype._getSampleImageUrl = function(itemId)
{
    var favInfo = this._getFavInfo(itemId);
    if (this._isUserItem(itemId)) {
        return favInfo.imageLarge;
    }
    else {
        return favInfo.imageMedium;
    }
}


MEditLookContext2.prototype._getSpreadImageUrl = function(itemId)
{
    var favInfo = this._getFavInfo(itemId);
    if (this._isUserItem(itemId)) {
        return this._getFavInfo(itemId).imageLarge;
    }
    else if (favInfo.transparent) {
        // all transparent images come from the same server, modify color if needed
        if (favInfo.colorUrl) {
            var colorToken = favInfo.colorToken;
            var urlhead = favInfo.imageLargeT.match(/(.*\/tim\/)/)[1];
            var colorpath = colorToken.substr(0,2) + '/' + colorToken.substr(2,2) + '/' + colorToken;
            return urlhead + colorpath + '.png';
        }
        else {
            return favInfo.imageLargeT;
        }
    }
    else {
        // for non-transparent images, a whole family of sizes is from the same server, but different colors may be from different servers
        if (favInfo.colorUrl) {
            return favInfo.colorUrl + '.jpg?alt=1';
        }
        else {
            return favInfo.imageLarge;
        }
    }
}

MEditLookContext2.prototype._getBasicImageUrl = function(itemId)
{
    // always a product
    var favInfo = this._getFavInfo(itemId);
    if (favInfo.colorUrl) {
        return favInfo.colorUrl + '_medium.jpg?alt=1';
    }
    else {
        return favInfo.imageMedium;
    }
}

// take an image url and strip it for further use
MEditLookContext2.prototype._calculateColorUrl = function(imageUrl)
{
    // take url up through the image token
    var url = imageUrl.match(/(.*\/[A-Za-z0-9]+).*/)[1];
    return url;
}

//---------------
//SS_scrollLoader
//---------------

function SS_scrollLoader(scrollerId, childSelector, left, top, width, height, perRow, maxItems, loadItems)
{
    this._scroller = $(scrollerId);
    this._childSelector = childSelector;
    this._iLeft = left;
    this._iTop = top;
    this._iWidth = width;
    this._iHeight = height;
    this._perRow = perRow;
    this._maxItems = maxItems;
    this._moreToLoad = true;
    this._loaded = 0;
    this._count = 0;
    this._loading = false;
    this._loadMoreItems = loadItems;

    // use closure to register scroll listener
    // IMPORTANT: there should be no local variables (including args) refering to doc elements or we will leak memory in IE
    var self = this;
    Event.observe(this._scroller, "scroll", function(event) { self.onScroll(event);}, false);
}

SS_scrollLoader.prototype.reset = function()
{
    // clear out items
    this._scroller.update();
    this._loaded = 0;
    this._count = 0;
    this._moreToLoad = true;
    this._loading = false;
}

SS_scrollLoader.prototype.onScroll = function(event)
{
    if (!this._moreToLoad || this._loaded >= this._maxItems || this._loading || this._loadMoreItems == null) {
        return;
    }

    var nFullRows = Math.floor(this._loaded/this._perRow);
    var viewBottom = this._scroller.scrollTop + this._scroller.getHeight();
    var itemBottom = this._iTop + Math.floor(this._count/this._perRow)*this._iHeight;
    // +iHeight so that we'll load even if last row doesn't completely show
    if (viewBottom + this._iHeight > itemBottom) {
        this._loading = true;
        // load 5 more rows of data
        //trace("scroller load " + this._loaded + ":" + this._perRow*5);
        this._loadMoreItems(this._loaded, this._perRow*5);
    }
}

SS_scrollLoader.prototype.doneLoading = function()
{
    var oldCount = this._count;
    this.arrange(false);
    var nLoaded = this._count - oldCount;
    this._loaded += nLoaded;
    this._moreToLoad = nLoaded > 0;
    this._loading = false;
}

SS_scrollLoader.prototype.arrange = function(isInitial)
{
    var children = this._scroller.descendants();
    var index = 0;
    for (var ii=0; ii<children.length; ii++) {
        var child = children[ii];
        if ($(child).match(this._childSelector)) {
            var xx = this._iLeft + (index%this._perRow)*this._iWidth;
            var yy = this._iLeft + Math.floor(index/this._perRow)*this._iHeight;
            child.style.left = xx + 'px';
            child.style.top = yy + 'px';
            index++;
        }
    }
    this._count = index;
    if (isInitial) {
        this._loaded = index;
    }
}

