
/*
 * Effect run after an item is added to the stylebook.
 */
var isRunningFavoriteEffect = false;
function pulseFavorites(linkName)
{
    var link = $(linkName);
    if (!isRunningFavoriteEffect && link != null) {
        isRunningFavoriteEffect = true;
        
        Effect.Pulsate(linkName, {
        
            beforeStart : function() {
            },
    
            afterFinish : function() {
                var elt = link;
                elt.setStyle({color: '', zoom: ''});
                isRunningFavoriteEffect = false;
            }
        });
    }
}

function addFavoriteEffect()
{
    store_haveAddedFavorites = true;
    pulseFavorites('mystylebooklink');
    if (document.addFavsShouldRefresh) {
        window.location.reload();
    }
}

function removeFavoriteOnStylebookEffect()
{
    $('favoritesBrowser').mcontext.discardAndReload();
    pulseFavorites('mystylebooklink');
}

function updateMyBrandsEffect()
{
    pulseFavorites('mybrandslink')
    if (document.updateBrandsShouldRefresh) {
        window.location.reload();
    }
}

/*
 * EditLookDialog support
 */
function MEditLookContext()
{
    // note that the "styles" array is defined in EditLookDialog
    this._titleField = document.getElementById('title');
    this._descField = document.getElementById('description');
    this._tagsField = document.getElementById('tags');
    this._lookDiv = document.getElementById('look');
    this._favoritesDiv = document.getElementById('favorites');
    this._showingSpread = true;
    this._showingDetails = false;
    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() { editLookContext.handleClose();}
    this._closeObserver = document.dialogContext.observers.addObserver("close", closeObserver);
    // also watch product details for changes to color
    var colorObserver = function(detailsFetcherDiv) { editLookContext.colorChanged(detailsFetcherDiv);};
    this._changeColorObserver = document.productDetailsContext.observers.addObserver("changeColor", colorObserver);

    selectTextField(this._titleField);
}
 
MEditLookContext.prototype.saveLookClicked = function(event)
{
    this.closeDetails();
    store_disableButton('saveButton');
    store_disableButton('cancelButton');
    
    if($('layoutType').value == 1) {
        this.saveNewStyledLook('styled_look', 'drsElement', 'newlook');
    } else {
        this.saveNewLook(this._lookDiv, 'editLookCell', 'newlook', true);
    }
    this.saveNewLook(this._favoritesDiv, 'editFavoriteCell', 'newfavs', false);
    trimTextArea('description', 2000);
    openDialogForForm('editLookForm');
    Event.stop(event);
}

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

MEditLookContext.prototype.saveNewLook = function(lookDiv, className, listElem, sendColor)
{
    var ids = ";";
    var items = document.getElementsByClassName(className, lookDiv);
    for (var i = 0; i < items.length; i++) {
        if (items[i].style.display != 'none') {
            var colorToken = sendColor ? this.findColorToken(items[i]) : '';
            ids = ids + items[i].id.substring(1) + ',' + colorToken + ';'; 
        }
    }    
    var newlook = document.getElementById(listElem);
    newlook.value = ids;
}

MEditLookContext.prototype.saveNewStyledLook = function(lookDiv, className, listElem)
{   
    var newlook = document.getElementById(listElem);
    var serial = "";
    var colorTokenFunction = this.findColorToken;
    var serial_template = new Template('#{id},#{color},#{left},#{top},#{width},#{height},#{z};')
    $$('#' + lookDiv + ' .' + className).each(function(element) {
        z_index = element.getStyle('zIndex');
        if (z_index == null || z_index == 'normal' || z_index == 'auto') {
            z_index = 1;
        }
        serial += serial_template.evaluate({
            id: element.readAttribute('id').gsub('s',''),
            color: colorTokenFunction(element),
            left: Position.positionedOffset(element)[0],
            top: Position.positionedOffset(element)[1],
            width: element.getWidth(),
            height: element.getHeight(),
            z: z_index
        });
    });
    newlook.value = serial;
}

MEditLookContext.prototype.findColorToken = function(itemDiv)
{
    var img = findChildTagWithId(itemDiv, "IMG", "cellImg");
    if (img != null && img.src != null) {
        return document.productDetailsContext.extractImageUrl(img.src);
    }
    else {
        return '';
    }
}

MEditLookContext.prototype.findFavCell = function(item)
{
    item = item.parentNode;
    while (item != null && item.nodeName != 'DIV') {
        item = item.parentNode;
    }
    return item;
}

MEditLookContext.prototype.moveFavDown = function(item)
{
    this.closeDetails();
    
    var thumb_template = new Template("<div id='#{id}' class='editFavoriteCell'><img border='0' src='#{src}' onClick='document.editLookContext.moveFavUp(this);' />"
    +"</div>");
    
    // get the current product image
    var styledImage = findChildWithId($(item), 'cellImg');
    var productImageUrl = this.calculateProductImageUrl(styledImage.src);
    
    //remove from styled canvas (if it exists)
    if ($(item)) {
        $(item).remove();
        if($(item)) {
            $(item).remove(); //do this twice - safari bug
        }
    }
    
    var basicItem = item.sub('s', 'm');
    $(basicItem).remove();  //remove from basic canvas
    if ($(basicItem)) {
        $(basicItem).remove();
    }
    
    var favImageSource = this.calculateSmallImageUrl(productImageUrl);
    new Insertion.Top('favorites', thumb_template.evaluate({
        id: item,
        src: favImageSource
    }));
    
}

MEditLookContext.prototype.initializeLayouts = function() {
    for (sid in styles) {
        if (styles[sid].inLook) {
            this.initBasicFav(sid);
            this.initStyledFav(sid);
        }
    }
}

MEditLookContext.prototype.showStyled = function() {
    this.closeDetails();
    $('look').hide();
    //styled look needs to be invisible vs. "hidden" so products can be positioned in the background
    $('styled_look').setStyle({
        "visibility": "visible"
    });
    $('layoutType').value = '1';
    $('radio_basic_label').addClassName('radioOff').removeClassName('radioOn');
    $('radio_styled_label').removeClassName('radioOff').addClassName('radioOn');
    $('look_copy').hide();
    $('style_copy').show();
    this._showingSpread = true;
}

MEditLookContext.prototype.showGrid = function() {
    this.closeDetails();
    //styled look needs to be invisible vs. "hidden" so products can be positioned in the background
    $('styled_look').setStyle({
        "visibility": "hidden"
    });
    $('look').show().setStyle({width:'572px', height: '390px', overflow: 'auto'});
    $('layoutType').value = '0';
    $('radio_styled_label').addClassName('radioOff').removeClassName('radioOn');
    $('radio_basic_label').removeClassName('radioOff').addClassName('radioOn');
    $('style_copy').hide();
    $('look_copy').show();
    this._showingSpread = false;
}

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

MEditLookContext.prototype.moveFavUp = function(item)
{
    // find the favorite
    var favCell = this.findFavCell(item);
        
    var id = favCell.id.substring(1);
    
    // put the item on the styled and basics divs
    itemid = 's' + id;
    var basicItem = this._insertBasic(itemid, $('look'), item);
    var styledItem = this._insertStyled(itemid, $('canvas'), item);
    styledItem.setStyle({"zIndex":this.highestz()});

    //remove favorite from the favorites tray
    $(favCell).remove();
    
    //this.adjustDivHeights();
    if (!this._showingSpread) {
        this.scrollToShow(this._lookDiv, basicItem);
    }
    
}

MEditLookContext.prototype.initStyledFav = function(item)
{
    this._insertStyled(item, $('canvas'), null);
}

MEditLookContext.prototype.initBasicFav = function(item)
{
    this._insertBasic(item, $('look'), null);
}

MEditLookContext.prototype._insertStyled = function(item, destination, favImg)
{
    var detailsAction = styles[item].detailsActionStyled;

    var template = null;
    if (detailsAction != null && detailsAction.length > 0) {
        template = new Template(
                '<div id="#{id}" class="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%;">'
                       +'<a id="rawDetailsUrl" style="display:none" href="#{detailsAction}" rel="nofollow"></a>'
                       +'<img id="cellImg" class="hero" src="#{src}" style="width: 100%; height: 100%;" />'
                       +'<span id="changeColorLink" style="display:none"></span>'
                   +'</div>'
                   +'<div class="style_options" onclick="document.editLookContext.moveFavDown(\'#{id}\');">&nbsp;</div>'
                   +'<div onclick="document.editLookContext.styledColorPopup(this, event);" onmousedown="Event.stop(event);" onmouseup="Event.stop(event);" class="chooseColorButton">&nbsp;</div>'
                +'</div>');
    }
    else {
        template = new Template(
                '<div id="#{id}" class="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%;">'
                       +'<img id="cellImg" class="hero" src="#{src}" style="width: 100%; height: 100%;" />'
                   +'</div>'
                   +'<div class="style_options" onclick="document.editLookContext.moveFavDown(\'#{id}\');">&nbsp;</div>'
                +'</div>');
    }
    
    // if we don't have a layout, create a reasonable random one
    if (styles[item].height <= 0) {
        styles[item].height = $('image_for_' + item).getHeight();
        styles[item].width = $('image_for_' + item).getWidth();
        styles[item].left = 60 + Math.floor(Math.random()*240);
        styles[item].top = 20 + Math.floor(Math.random()*180);
        styles[item].zindex = dragresize.zIndex;
    }
    
    // set the image source
    var imageSource = null;
    if (favImg != null) {
        var smallSrc = favImg.src;
        imageSource = this.calculateLargeImageUrl(this.calculateProductImageUrl(smallSrc));
    }
    else {
        imageSource = styles[item].imageLarge;
    }
        
    new Insertion.Bottom(destination, template.evaluate({
        id: item,
        src: imageSource,
        top: styles[item].top,
        left: styles[item].left,
        h: styles[item].height,
        w: styles[item].width,
        zindex: styles[item].zindex,
        detailsAction: detailsAction
    }));

    dragresize.zIndex += 1;
    
    return $(item);
}

MEditLookContext.prototype._insertBasic = function(item, destination, favImg)
{
    var detailsAction = styles[item].detailsActionBasic;
    
    var template = null;
    if (detailsAction != null && detailsAction.length > 0) {
        template = new Template(
        '<div id="#{id}" class="editLookCell">'
        +'<center>'
            +'<img width="21" height="14" border="0" id="ctrl" title="' + store_getMessage('editLookMoveLeft') + '" style="cursor:pointer" src="/im/editlook-left.gif" '
                 +'onclick="document.editLookContext.moveFavLeft(this);"/>'
            +'<img src="/im/chooseColor.gif" style="cursor:pointer;padding-right:2px" border="0" onclick="document.editLookContext.basicColorPopup(this, event);"/>'
            +'<img id="moveFavDown" width="14" height="14" border="0" title="' + store_getMessage('editLookRemove')
               +'" style="cursor:pointer" src="/im/delete-box.gif" title="ognl:removeHint"'
                 +'onclick="document.editLookContext.moveFavDown(\'#{sid}\');"/>'
            +'<img width="22" height="14" border="0" id="ctrl" title="' + store_getMessage('editLookMoveRight') + '" style="cursor:pointer" src="/im/editlook-right.gif" '
                 +'onclick="document.editLookContext.moveFavRight(this);"/>'
          +'<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="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="editLookCell">'
                +'<center>'
                +'<img width="21" height="14" border="0" id="ctrl" title="' + store_getMessage('editLookMoveLeft') + '" style="cursor:pointer" src="/im/editlook-left.gif" '
                     +'onclick="document.editLookContext.moveFavLeft(this);"/>'
                +'<img id="moveFavDown" width="14" height="14" border="0" title="' + store_getMessage('editLookRemove')
                   +'" style="cursor:pointer" src="/im/delete-box.gif" title="ognl:removeHint"'
                     +'onclick="document.editLookContext.moveFavDown(\'#{sid}\');"/>'
                +'<img width="22" height="14" border="0" id="ctrl" title="' + store_getMessage('editLookMoveRight') + '" style="cursor:pointer" src="/im/editlook-right.gif" '
                     +'onclick="document.editLookContext.moveFavRight(this);"/>'
              +'<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="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>');
    }
    
    // change fetcher div id (item begins with 's', we want id starting with 'm')
    var itemId = 'm' + item.substring(1);
    var sid = 's' + item.substring(1);
        
    // change image src
    var imageSource = null;
    if (favImg != null) {
        var smallSrc = favImg.src;
        imageSource = this.calculateMediumImageUrl(this.calculateProductImageUrl(smallSrc));
    }
    else {
        imageSource = styles[sid].imageMedium;
    }
    
    new Insertion.Bottom(destination, template.evaluate({
        id: itemId,
        sid: sid,
        src: imageSource,
        detailsAction: detailsAction,
        commentName: 'c' + item.substring(1),
        comment: styles[sid].comment,
        text: styles[sid].productName
    }));
    
    return $(itemId);
}

MEditLookContext.prototype.moveFavRight = function(item)
{
    this.closeDetails();
    item = this.findFavCell(item);
    var target = item.nextSibling;
    while (target != null && (target.nodeName != 'DIV' || target.style.display == 'none')) {
        target = target.nextSibling;
    }
    if (target != null) {
        target = target.nextSibling;
    }
    while (target != null && (target.nodeName != 'DIV' || target.style.display == 'none')) {
        target = target.nextSibling;
    }
    this._lookDiv.insertBefore(item, target);
}

MEditLookContext.prototype.moveFavLeft = function(item)
{
    this.closeDetails();
    item = this.findFavCell(item);
    var target = item.previousSibling;
    while (target != null && (target.nodeName != 'DIV' || target.style.display == 'none')) {
        target = target.previousSibling;
    }
    if (target != null) {
        this._lookDiv.insertBefore(item, target);
    }
}

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

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

MEditLookContext.prototype.handleClose = function()
{
    // stop observing colorChange events from the details context
    //trace("editlook handleClose " + this._changeColorObserver);
    document.productDetailsContext.observers.removeObserver("changeColor", this._changeColorObserver);
    // and the close observer from the dialog context
    document.dialogContext.observers.removeObserver("close", this._closeObserver);
    
    this.closeDetails();
}

// callback from productdetails - that the color of an item has been changed
MEditLookContext.prototype.colorChanged = function(fetcherDiv)
{
    //trace("editlook colorChanged " + fetcherDiv);
    var topNode = null;
    if (this._showingSpread) {
        topNode = fetcherDiv.parentNode;
    }
    else {
        topNode = findParentWithClass(fetcherDiv, 'editLookCell');
    }
    var item = 's' + topNode.id.substring(1);
    var sourceImg = findChildWithId(fetcherDiv, 'cellImg');
    var productImageUrl = this.calculateProductImageUrl(sourceImg.src);
    
    if (this._showingSpread) {
        // change image of the hidden basic
        var destImg = findChildWithId($('m'+item.substring(1)), 'cellImg');
        destImg.src = this.calculateMediumImageUrl(productImageUrl);
    }
    else {
        var destImg = findChildWithId($(item), 'cellImg');
        destImg.src = this.calculateLargeImageUrl(productImageUrl);
    }
}

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

MEditLookContext.prototype.titleKeyPress = function(event)
{
    if (event.keyCode == Event.KEY_TAB) {
        selectTextField(this._descField);
        Event.stop(event);
    }
}

MEditLookContext.prototype.descriptionKeyPress = function(event)
{
    if (event.keyCode == Event.KEY_TAB) {
        selectTextField(this._tagsField);
        Event.stop(event);
    }
    else if (event.keyCode == Event.KEY_RETURN) {
        this.formIgnoreCR = true;
    }
}

MEditLookContext.prototype.tagsKeyPress = function(event)
{
    if (event.keyCode == Event.KEY_TAB) {
        selectTextField(this._titleField);
        Event.stop(event);
    }
}

MEditLookContext.prototype.adjustDivHeights = function()
{
    // Safari is buggy with overflow:auto so not doing this for now
    /*if (!tx_isSafari()) {
        this.adjustDivHeight(this._lookDiv, 'editLookCell');
        this.adjustDivHeight(this._favoritesDiv, 'editFavoriteCell');
    }*/
}

MEditLookContext.prototype.adjustDivHeight = function(lookDiv, className)
{
    var minHeight = (lookDiv == this._lookDiv ? 195 : 52);
    var maxHeight = (lookDiv == this._lookDiv ? 390 : 92);
    var items = document.getElementsByClassName(className, lookDiv);
    for (var i = 0; i < items.length; i++) {
        if (items[i].style.display != 'none') {
            var height = items[i].offsetTop + items[i].clientHeight;
            if (height > minHeight)
                minHeight = height;
        }
    }
    lookDiv.style.height = (minHeight > maxHeight ? maxHeight : minHeight) + "px";
}

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

// take a product image url and strip it to the minimum
MEditLookContext.prototype.calculateProductImageUrl = function(imageUrl)
{
    // take url up through the image token, and then append .jpg
    var result = imageUrl.match(/(.*\/[A-Za-z0-9]+).*/);
    result = result[1] + '.jpg';
    return result;
}

// given a minimum product image url, calculae the large url we want to use
MEditLookContext.prototype.calculateLargeImageUrl = function(productImageUrl)
{
    return productImageUrl + "?alt=1";
}

MEditLookContext.prototype.calculateMediumImageUrl = function(productImageUrl)
{
    return productImageUrl.replace(/\.jpg/,"_medium.jpg?alt=1");
}

MEditLookContext.prototype.calculateSmallImageUrl = function(productImageUrl)
{
    var result = productImageUrl.replace(/\.jpg/,"_small.jpg?alt=1");
    return result;
}
