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

function SSBlogWidget(widgetInfo, widgetType)
{
    this._data = widgetInfo;
    this._haveLookInfo = (widgetInfo.host !== undefined);
    this._originalLookId = widgetInfo.originalLookId;

    this._widgetType = widgetType;
}

// create the look selection list
SSBlogWidget.prototype.makeLookSelect = function()
{
    var lkSelect = $('lookSelector');
    if (lkSelect !== null) {
        if (this._data.looks.length > 1) {
            lkSelect.appendChild(this._buildOption(-1, this._data.latestTitle, false));
        }

        var ii=0;
        for (ii=0; ii<this._data.looks.length; ii++) {
            var li = this._data.looks[ii];
            var title = li.title + ((li.type === 1) ? (' ' + this._data.spreadTag) : '');
            lkSelect.appendChild(this._buildOption(ii, title, this._originalLookId === li.id));
        }
    }
};

// helper for makeLookSelect (generally useful option builder)
SSBlogWidget.prototype._buildOption = function(value, label, selected)
{
    var opt = document.createElement('option');
    opt.value = value;
    opt.appendChild(document.createTextNode(label));
    opt.selected = selected;

    return opt;
};

// set initial values for the various data inputs
SSBlogWidget.prototype.showLookOptions = function() {
    if ($('lookSelector') !== null) {
        var lookIndex = document.picker.lookSelector.value;
        if (lookIndex < 0) { lookIndex = 1;} // latest look
        if (this._data.looks[lookIndex].type === 0) {
            $$('.basicLook').invoke('show');
            $$('.spreadLook').invoke('hide');
            $('rows').value = "1";
            $('columns').value = "3";
        } else {
            $$('.basicLook').invoke('hide');
            $$('.spreadLook').invoke('show');
            $('rows').value = "1";
            $('columns').value = "2";
            $('size').value = "medium";
            $('sidebar').checked = false;
        }
    }
};

SSBlogWidget.prototype.sizeChanged = function(value) {
    var sidebarBox = $('sidebar');
    if (sidebarBox !== null) {
        sidebarBox.disabled = (value === 'small');
        sidebarBox.checked = false;
    }
    if (value === 'xlarge') {
        $('columns').selectedIndex = 0;
        $('rows').selectedIndex = 0;
    }
};

SSBlogWidget.prototype.typeChanged = function(value) {
    document.picker.psize.disabled = (value === "2");
    if (document.picker.showbrand !== undefined) {
        document.picker.showbrand.disabled = (value === "2");
    }
    if (document.picker.widgetLocation !== undefined) {
        document.picker.widgetLocation.disabled = (value === "2");
    }
};

SSBlogWidget.prototype.productChanged = function(element, changeSelected) {
    if (changeSelected){
        if ($('productSelected')){
            $('productSelected').removeAttribute('id');
        }
        element.parentNode.setAttribute('id','productSelected');
    }

    $$('.productSelect').each(function(e){e.removeClassName('productSelect');});
    element.parentNode.addClassName('productSelect');
    var raw = $(element).down('.details').innerHTML;
    var product = Tx.evaluate(raw.replace(/[\n\r]/g,''));

    // update the widget data with the new data
    this._data.name = product.name;
    this._data.productLink = product.productLink;
    this._data.purchaseLink = product.purchaseLink;
    this._data.images = product.images;
    this._data.seeMoreUrl = product.seeMoreUrl;
    this._data.brandPrompt = product.brandPrompt;
    this._data.poweredByAlt = product.poweredByAlt;
    this.makeWidget();
};

SSBlogWidget.prototype.clickToRetailer = function()
{
    // disable or enable the widgets related to regular spread looks
    //var toRetailer = document.picker.sclickthrough.checked
    //document.picker.ssize.disabled = toRetailer;
    //document.picker.ssidebar.disabled = toRetailer;

    this.makeWidget();
};

SSBlogWidget.prototype.loadInfoAndMakeWidget = function()
{
    var indx, li, context, loaded, url, optionsDict;

    if (!this._haveLookInfo) {
        return false;
    }
    if (this._widgetType === 1) {
        // for a look widget, we need to check to make sure we have complete data
        indx = document.picker.lookSelector.value;
        if (indx < 0) {
            indx = 1; // to get latest look
        }
        li = this._data.looks[indx];
        context = this;
        if (!li.description) {
            // we need to load the data and then make the widget
            loaded = function(xmlhttp) {
                var jsonContents = Tx.getResponseText(xmlhttp);
                var result = Tx.evaluate(jsonContents);
                context._data.looks[indx] = result.data.looks[0];
                context.makeWidget();
            };
            url = "/action/lookInfoForWidget?lookId=" + li.id;
            optionsDict = {
                method: 'get',
                onSuccess: loaded
            };
            Tx.ajax(url, optionsDict);
            return true;
        }
    }

    // if we're here, we can make the widget
    this.makeWidget();
    return true;
};

SSBlogWidget.prototype.makeWidget = function() {

    if (this._haveLookInfo) {
        var widgetUrl = this._data.host;
        var siteHost = this._data.siteHost;
        var thePicker = document.picker;

        var size;
        var sidebar;
        var cellWidth, cellHeight;
        var widgetLocation = "0";
        var catUrl, search, indx, look, li;
        var results = new Array(1);

        if (thePicker.widgetLocation !== undefined) {
            widgetLocation = thePicker.widgetLocation.value;
        }

        if (this._widgetType === 0) {
            search = !thePicker.search ? '' : thePicker.search.value;
            size = thePicker.size.selectedIndex;   // 0=small, 1=large
            catUrl = thePicker.category.value;
            cellWidth = thePicker.columns.value;
            cellHeight = thePicker.rows.value;
            results[0] = this.makeSearchWidget(siteHost, widgetUrl, size, widgetLocation, search, catUrl, cellWidth, cellHeight);
        }
        else if (this._widgetType === 1 && this._data.looks !== undefined && this._data.looks.length > 0) {
            indx = 0;
            look = 0;
            if ($('lookSelector') !== null) {
                indx = thePicker.lookSelector.value;
            }
            if (indx < 0) {
                indx = 1; // to get latest look
            }
            li = this._data.looks[indx];
            look = li.id;

            if (li.type === 0) {  // basic look
                size = thePicker.size.selectedIndex;   // 0=small, 1=large
                sidebar = thePicker.sidebar && thePicker.sidebar.checked && size > 0;
                cellWidth = thePicker.columns.value;
                cellHeight = thePicker.rows.value;
                results[0] = this._makeGridLookWidget(li, widgetUrl, look, this._data.user, size, widgetLocation, cellWidth, cellHeight, sidebar);
            }
            else { // spread look
                size = thePicker.ssize.selectedIndex;   // 0=small, 1=large
                sidebar = thePicker.ssidebar.checked;
                var toRetailer = thePicker.sclickthrough.selectedIndex === 1;
                var showText = thePicker.sshowtext.checked;
                results[0] = this.makeClickthroughSpreadLookWidget(this._data, li, size, sidebar, showText, toRetailer, widgetLocation);
            }
        }
        else if (this._widgetType === 2) {
            size = thePicker.size.selectedIndex;   // 0=small, 1=large
            results[0] = this.makeLookBrowserWidget(siteHost, widgetUrl, this._data.searchUser, this._data.searchGroup, this._data.searchTags, size, widgetLocation, this._data.seeMoreLabel);
        }
        else if (this._widgetType === 3) {
            size = thePicker.psize.selectedIndex;   // 0=small, 1=medium, 2=large
            var style = thePicker.pstyle.selectedIndex;
            var showBrand = true;
            if (thePicker.showbrand !== undefined) {
                showBrand = thePicker.showbrand.checked;
            }
            results = this.makeProductWidget(style, size, widgetLocation, showBrand, this._data.purchaseLink, this._data.productLink, this._data.siteHost,
                    this._data.images, this._data.name, this._data.brandPrompt, this._data.seeMoreUrl, this._data.poweredByAlt);
        }
        else if (this._widgetType === 4) {
            size = 1; // large
            catUrl = thePicker.category.value;
            cellWidth = thePicker.columns.value;
            cellHeight = thePicker.rows.value;
            results[0] = this.makeTrendWidget(siteHost, widgetUrl, size, widgetLocation, catUrl, cellWidth, cellHeight, this._data.seeMoreLabel);
        }
        else if (this._widgetType === 5) {
            cellWidth = thePicker.columns.value;
            cellHeight = thePicker.rows.value;
            results[0] = this.makeBrandWidget(siteHost, widgetUrl, cellWidth, cellHeight, this._data.seeMoreLabel);
        }
        else if (this._widgetType === 6) {
            catUrl = thePicker.category.value;
            cellWidth = thePicker.columns.value;
            cellHeight = thePicker.rows.value;
            results[0] = this.makePromotionWidget(siteHost, widgetUrl, catUrl, cellWidth, cellHeight, this._data.seeMoreLabel);
        }
        else if (this._widgetType === 7) {
            var version = $F(thePicker.version);
            var category = $F(thePicker.category);
            size = $F(thePicker.size);
            var color = $F(thePicker.color);
            results = this.makeAdUnit(siteHost, widgetUrl, version, category, size, color);
        }
        else {
            results[0] = '';
        }

        var demoCode, sampleCode;
        demoCode = results[0];
        if (results.length === 1) {
            sampleCode = demoCode;
            if (sampleCode.search(/<iframe/i) >= 0) {
                sampleCode = sampleCode.replace(/\&local=1\&conservative=1/, '');
            }
        }
        else {
            sampleCode = results[1];
        }


        if (this._widgetType === 7) {
            thePicker.sampleText.value = sampleCode;
            var sampleDiv = $('widgetbuilder-sample');
            if (demoCode === 'ad-frame-728x90-Expand') {
                sampleDiv.hide();
                $('ad-frame-468x60-Expand').hide();
                $('ad-frame-728x90-Expand').show();
            }
            else if (demoCode === 'ad-frame-468x60-Expand') {
                sampleDiv.hide();
                $('ad-frame-728x90-Expand').hide();
                $('ad-frame-468x60-Expand').show();
            }
            else {
                $('ad-frame-728x90-Expand').hide();
                $('ad-frame-468x60-Expand').hide();
                sampleDiv.replace(demoCode);
                sampleDiv.show();
            }
        }
        else if ($('widgetbuilder-sample')) {
            thePicker.sampleText.value = sampleCode;
            $('widgetbuilder-sample').update(demoCode);
        }
        else {
            thePicker.sampleText.value = sampleCode;
            document.getElementById('sampleFrame').innerHTML = demoCode;
        }

        this.makeSearchBox();
    }

    return false;
};

SSBlogWidget.prototype.getWidth = function(size, cellWidth, sidebar)
{
    var width;
    if (size === 0) {
        width = Math.max(70 * cellWidth + 10, 102);
    }
    else if (size === 1) {
        width = (sidebar ? 115 : 10) + (138 * cellWidth);
    }
    else if (size === 2) {
        width = (sidebar ? 115 : 10) + (184 * cellWidth);
    }
    else { // x-large
        width = (sidebar ? 115 : 10) + (348 * cellWidth);
    }
    return width;
};

SSBlogWidget.prototype.getHeight = function(size, cellHeight, hasFooter)
{
    var height;
    if (size === 0) {
        height = 84 * cellHeight + 74;
    }
    else if (size === 1) {
        height = 190 * cellHeight + (hasFooter ? 64 : 54);
    }
    else if (size === 2) {
        height = 255 * cellHeight + (hasFooter ? 64 : 54);
    }
    else { // x-large
        height = 460 * cellHeight + (hasFooter ? 64 : 54);
    }
    return height;
};

SSBlogWidget.prototype.appendCommonParams = function(url)
{
    var commonParams = this._data.commonParams;
    if (commonParams) {
        if (url.indexOf("?") > -1) {
            return url + '&' + commonParams;
        } else {
            return url + '?' + commonParams;
        }
    }
    return url;
};

SSBlogWidget.prototype._headerDivTemplate = new Template('<div style="position:relative; border:1px solid #bfbfbf; background:white; width:#{width}px;#{location}">');

SSBlogWidget.prototype._footerLinksTemplate = new Template('<div style="position:absolute; left:0; bottom:2px; height:18px; line-height:12px; width:100%;"><div style="position:absolute; left:0; padding:2px 0 0 6px">' +
        '<a href="#{seeMoreLink}" style="font:11px verdana,sans-serif;text-decoration:underline;border:0;background-color:transparent;color:#606060">#{seeMoreLabel}</a></div>' +
        '<div style="position:absolute; right:0; padding:3px 4px 3px 0"><a style="border:0" href="#{homeLink}?pid=#{pid}">' +
        '<img src="#{imageHost}/im/widget/ShopStyleLogo_powered#{logoSuffix}.png" alt="ShopStyle" style="border:0;margin:0;padding:0"></img></a></div></div></div>'
);

SSBlogWidget.prototype._makeGridLookWidget = function(lookInfo, widgetUrl, look, user, size, widgetLocation, cellWidth, cellHeight, sidebar)
{
    var width = this.getWidth(size, cellWidth, sidebar);
    var height = this.getHeight(size, cellHeight, false);
    var locationStyle = this.getLocationStyle(widgetLocation, false);

    var str = this._headerDivTemplate.evaluate({
        width: width,
        location: locationStyle});
    str += '<iframe width="' + width + '" height="' + height + '" frameborder="0" scrolling="no" ';
    var url = widgetUrl;
    url = this.appendCommonParams(url);

    str += 'src="' + url;

    if (look === -1) {
        str += '&user=' + user;
    }
    else if (look) {
        str += '&look=' + look;
    }

    if (size === 0) {
        str += '&size=Small';
    } else if (size === 2) {
        str += '&size=Large';
    } else if (size === 3) {
        str += '&size=XLarge';
    }
    str += '&width=' + cellWidth;
    str += '&height=' + cellHeight;
    str += '&layouttype=0';
    str += '&border=0&footer=0';

    if (sidebar) {
        str += '&sidebar=1';
    }

    str += '&local=1&conservative=1"></iframe>';

    var brandUrl = lookInfo.siteU + "/browse/" + lookInfo.brandU + "?pid=" + this._data.pid;
    str += this._footerLinksTemplate.evaluate({
        imageHost: this._data.resourceHost,
        homeLink: lookInfo.siteU,
        pid: this._data.pid,
        logoSuffix: this.logoSuffix(size, cellWidth),
        seeMoreLink: brandUrl,
        seeMoreLabel: (size === 0 && cellWidth < 4) ? '' : lookInfo.brandN});

    return str;
};

SSBlogWidget.prototype._calculateSpreadImageWidth = function(lookInfo)
{
    var favorites = lookInfo.favorites;
    var imageRight = 0;
    var imageBottom = 0;
    var fav;
    var ii;
    for (ii=0; ii<favorites.length; ii++) {
        fav = favorites[ii];
        if (fav.left + fav.width > imageRight) {
            imageRight = fav.left + fav.width;
        }
        if (fav.top + fav.height > imageBottom) {
            imageBottom = fav.top + fav.height;
        }
    }
    var userImages = lookInfo.userImages;
    var ui;
    for (ii=0; ii<userImages.length; ii++) {
        ui = userImages[ii];
        if (ui.left + ui.width > imageRight) {
            imageRight = ui.left + ui.width;
        }
        if (ui.top + ui.height > imageBottom) {
            imageBottom = ui.top + ui.height;
        }
    }

    return [imageRight, imageBottom];
};

// make a widget for a spread look that allows clickthroughs to retailer (rather than to look)
SSBlogWidget.prototype._clickThroughSpreadTemplateHead = new Template(
    "<div class=\"ShopStyleSpreadLook\" style=\"width:#{width}px;position:relative;background-color:white;border:1px solid #b9b9b9;padding:0;#{location}\">"
    );

SSBlogWidget.prototype._clickThroughSpreadTitleTemplate = new Template(
    "<div style=\"width:95%;text-align:center;color:#606060;font:12px Verdana,sans-serif;text-decoration:none;margin:8px auto\">#{title}" +
    "</div>"
    );

SSBlogWidget.prototype._clickThroughToRetailerHeadTemplate = new Template(
    "<div style=\"width:100%;height:#{height}px;position:relative;overflow:hidden\">" +
        "<div style=\"position:absolute;left:#{imageLeft}px;top:1px;padding:0;margin:0\">" +
            "<img src=\"#{imageUrl}\" alt=\"#{imageAlt}\" style=\"margin:0;padding:0;border:0 none;box-shadow:none;background:none;position:absolute;left:0;top:0\"></img>"
    );

SSBlogWidget.prototype._clickThroughToLookTemplate = new Template(
    "<div style=\"width:100%;height:#{height}px;position:relative;overflow:hidden\">" +
        "<div style=\"position:absolute;left:#{imageLeft}px;top:1px;padding:0;margin:0\">" +
            "<a href=\"#{lookUrl}\"  style=\"outline:none;border:none\">" +
                "<img src=\"#{imageUrl}\" alt=\"#{imageAlt}\" style=\"margin:0;padding:0;border:0 none;box-shadow:none;background:none;position:absolute;left:0;top:0\"></img>" +
            "</a>"
    );

SSBlogWidget.prototype._clickThroughToRetailerTemplate = new Template(
    "<a href=\"#{siteU}/action/apiVisitRetailer?id=#{productId}&pid=#{partnerId}\" target=\"_blank\" style=\"background-color:transparent\">" +
        "<img src=\"#{cleardotUrl}\" style=\"position:absolute;left:#{left}px;top:#{top}px;width:#{width}px;height:#{height}px;z-index:#{zindex};cursor:pointer;border:0 none;background-color:transparent\"></img>" +
    "</a>"
    );

SSBlogWidget.prototype._clickThroughSidebarTemplate = new Template(
    "<div style=\"position:absolute;top:2px;width:#{width}px;height:#{height}px;text-align:center;padding-right:4px;border-right:1px solid #d8d8d8\">" +
        "<img src=\"#{imageUrl}\">"+
    "</div>"
    );

SSBlogWidget.prototype._clickThroughDescriptionTemplate = new Template(
    "<div style=\"width:95%;text-align:center;color:#606060;font:11px Verdana,sans-serif;text-decoration:none;margin:8px auto\">#{description}" +
    "</div>"
    );

SSBlogWidget.prototype._crossLinkHeaderTemplate = new Template(
    "<div style=\"position:relative;height:#{height}px;width:100%;bottom:0px;left:3px;line-height:normal;letter-spacing:normal;font:11px Verdana,sans-serif;color:#606060;\">" +
    "<div style=\"position:absolute;left:3px;top:5px;width:#{crossWidth}px\">"
    );

SSBlogWidget.prototype._clickThroughCrosslinkTemplate = new Template(
        "<a href=\"#{ctUrl}\" style=\"color:#606060;background-color:transparent;font:11px Verdana,sans-serif;text-decoration:none\"><span style=\"text-decoration:underline\">#{ctCat}</span>#{ctBrRet}</a><br/>"
    );

SSBlogWidget.prototype._clickThroughPoweredTemplate = new Template(
        "<a href=\"#{homeLink}?pid=#{pid}\"><img src=\"#{imageHost}/im/widget/ShopStyleLogo_powered.png\" alt=\"ShopStyle\" style=\"border-style:none;position:absolute;right:6px;bottom:6px;margin:0\"></img></a>"
    );

SSBlogWidget.prototype.makeClickthroughSpreadLookWidget = function(lookData, lookInfo, size, sidebar, showText, toRetailer, widgetLocation)
{
    var favorites = lookInfo.favorites;
    var imageSize = this._calculateSpreadImageWidth(lookInfo);
    var imageRight = imageSize[0];
    var imageBottom = imageSize[1];
    var fav;
    var brandList = "";
    var isLarge, scale, overallWidth, sidebarImageHeight, sidebarImageWidth, sidebarBottom, sidebarWidth;
    var imageUrl, html, ii, cl, cross;
    var crossProd, spanBegin, spanEnd, catName, brandOrRetailer;

    for (ii=0; ii<favorites.length; ii++) {
        fav = favorites[ii];
        if (fav.brandN) {
            if (brandList.indexOf(fav.brandN) < 0) {
                if (brandList.length > 0) {
                    brandList += ', ';
                }
                brandList += fav.brandN;
            }
        }
        if (brandList.length > 40) {
            break;
        }
    }

    isLarge = (size !== 0);

    scale = isLarge ? 1.0 : 0.58;
    overallWidth = 2 + Math.floor(476 * scale);
    imageRight = 2 + Math.floor(imageRight*scale);
    imageBottom = Math.floor(imageBottom*scale);

    // calculate the effect of the sidebar image (if any)
    // in the large case we may know the size of the image, and we can optimize for that
    // in the small case we don't know the image size - because it is some complicated function of resizing
    sidebarImageHeight = 0;
    sidebarImageWidth = 0;
    sidebarBottom = 0;
    sidebarWidth = 0;
    if (sidebar) {
        if (isLarge) {
            sidebarImageHeight = lookInfo.customImageHeight || 350;
            sidebarImageWidth = lookInfo.customImageWidth || 250;
        }
        else {
            sidebarImageHeight = 147;
            sidebarImageWidth = 107;
        }
        sidebarBottom = sidebar ? (sidebarImageHeight+2) : 0;
        sidebarWidth = sidebar ? (sidebarImageWidth + 10) : 0;
    }

    imageUrl = lookInfo.spreadImage;
    if (!isLarge) {
        imageUrl = imageUrl.replace(/\.jpg/, '_58.jpg');
    }

    html = this._clickThroughSpreadTemplateHead.evaluate({
        width: overallWidth + sidebarWidth,
        location: this.getLocationStyle(widgetLocation, true)
    });

    if (showText) {
        html += this._clickThroughSpreadTitleTemplate.evaluate({
            title: lookInfo.title
        });
    }

    if (toRetailer) {
        // clicks take us to retailer
        // note that the imageUrl is to a specific version of the look - it won't get updated if the look changes
        // this is because the divs for each favorite will be fixed and would be wrong for a later version
        html += this._clickThroughToRetailerHeadTemplate.evaluate({
            height: Math.max(imageBottom, sidebarBottom),
            imageLeft: Math.floor((overallWidth - imageRight)/2 + sidebarWidth),  // center the image, note that in layout coordinates the image left is at zero
            imageUrl: imageUrl,
            imageAlt: brandList
        });

        for (ii=0; ii<favorites.length; ii++) {
            fav = favorites[ii];
            html += this._clickThroughToRetailerTemplate.evaluate({
                cleardotUrl: this._data.cleardotUrl,
                left: Math.floor(fav.left*scale),
                top: Math.floor(fav.top*scale),
                width: Math.floor(fav.width*scale),
                height: Math.floor(fav.height*scale),
                zindex: fav.zindex,
                productId: fav.productId,
                partnerId: lookData.pid,
                siteU: lookInfo.siteU
            });
        }
    }
    else {
        // clicks take us to look
        // note that the imageUrl is an action that serves up the latest image
        // we can use the latest image in this case because we don't have to worry about out-of-date layout divs
        html += this._clickThroughToLookTemplate.evaluate({
            height: Math.max(imageBottom, sidebarBottom),
            imageLeft: Math.floor((overallWidth - imageRight)/2 + sidebarWidth),  // center the image, note that in layout coordinates the image left is at zero
            imageUrl: (lookInfo.siteU + '/action/spreadWidgetImage?look=' + lookInfo.id + ((size === 1) ? '&size=Large' : '')),
            imageAlt: brandList,
            lookUrl: this.appendCommonParams(lookInfo.siteU + '/action/viewLook?id=' + lookInfo.id)
        });
    }
    html += "</div>"; // close of image & clickthrough divs

    if (sidebar) {
        imageUrl = lookInfo.customImage;
        if (imageUrl && !isLarge) {
            imageUrl = imageUrl.replace(/\.jpg/, '_medium.jpg');
        }
        html += this._clickThroughSidebarTemplate.evaluate({
            width: sidebarImageWidth + 2,
            height: sidebarImageHeight,
            imageUrl: imageUrl || this._data.cleardotUrl
        });
    }
    html += "</div>"; // close of main body div (started with _clickThroughSpreadTemplateHead)

    if (showText) {
        html += this._clickThroughDescriptionTemplate.evaluate({
            description: lookInfo.description
        });
    }

    cross = lookInfo.crosslinks;

    // header for crosslinks
    html += this._crossLinkHeaderTemplate.evaluate({
        height: ((cross.length > 1) ? 38 : 25),
        headerWidth: (isLarge ? 458 : 265) + sidebarWidth,
        crossWidth: (isLarge ? 400 : 265)
    });

    if (cross) {
        for (cl=0; cl<cross.length; cl++) {
            crossProd = cross[cl];
            // the seeMoreLabel looks like <span>Infant Girls' Jeans</span> by Pumpkin Patch
            // break out the category name and the brand/retailer name, demarcated by span tag
            spanBegin = crossProd.seeMoreLabel.indexOf('<span>');
            spanEnd = crossProd.seeMoreLabel.indexOf('</span>');
            if (spanBegin >= 0 && spanEnd >= 0) {
                catName = crossProd.seeMoreLabel.substring(spanBegin+6, spanEnd);
                brandOrRetailer = crossProd.seeMoreLabel.substring(spanEnd+7);
            }
            else {
                catName = crossProd.seeMoreLabel;
                brandOrRetailer = "";
            }
            html += this._clickThroughCrosslinkTemplate.evaluate({
                ctUrl: Tx.replaceParam(crossProd.seeMoreUrl, 'pid', this._data.pid),
                ctCat: catName,
                ctBrRet: brandOrRetailer,
                pid: this._data.pid
            });
        }
    }

    html += "</div>"; // close of crosslinks div

    if (size !== 0 || sidebar) {
        html += this._clickThroughPoweredTemplate.evaluate({
            homeLink: Tx.removeParam(lookInfo.siteU, 'pid'),
            imageHost: this._data.resourceHost,
            pid: this._data.pid
        });
    }

    html += "</div></div>"; // close of footer div and widget div
    return html;
};

SSBlogWidget.prototype.makeSearchWidget = function(siteHost, widgetUrl, size, widgetLocation, search, catUrl, cellWidth, cellHeight)
{
    var width = this.getWidth(size, cellWidth, false);
    var height = this.getHeight(size, cellHeight, false);
    var locationStyle = this.getLocationStyle(widgetLocation, false);

    var str = this._headerDivTemplate.evaluate({
        width: width,
        location: locationStyle});
    str += '<iframe name="shopstyle_search" ';
    str += 'width="' + width + '" height="' + height + '" frameborder="0" scrolling="no" ';
    var url = widgetUrl;
    url = this.appendCommonParams(url);

    str += 'src="' + url;
    str += '&fts=' + encodeURIComponent(search);
    if (catUrl) {
        str += '&cat=' + catUrl;
    }
    str += '&width=' + cellWidth;
    str += '&height=' + cellHeight;
    if (size === 0) {
        str += '&size=Small';
    } else if (size === 2) {
        str += '&size=Large';
    } else if (size === 3) {
        str += '&size=XLarge';
    }

    str += '&border=0&footer=0';
    str += '&local=1&conservative=1"></iframe>';

    var moreUrl = siteHost + "/browse?fts=" + encodeURIComponent(search) + '&pid=' + this._data.pid;
    str += this._footerLinksTemplate.evaluate({
        imageHost: this._data.resourceHost,
        homeLink: siteHost,
        pid: this._data.pid,
        logoSuffix: this.logoSuffix(size, cellWidth),
        seeMoreLink: moreUrl,
        seeMoreLabel: (size === 0 && cellWidth < 4) ? '' : search});

    return str;
};

SSBlogWidget.prototype._searchBoxTemplate = new Template('<form action="#{host}" target="shopstyle_search">\n' +
        '<input type="hidden" name="pid" value="#{pid}"/>\n' +
        '<input type="hidden" name="footer" value="0"/>\n' +
        '<input type="hidden" name="border" value="0"/>\n' +
        '#{prompt}\n' +
        '<input type="text" name="fts"/> <input type="submit" value="#{goLabel}"/>\n</form>');

SSBlogWidget.prototype.makeSearchBox = function() {
    var box = $('sampleSearchBox');
    if (box !== null) {
        box.value = this._searchBoxTemplate.evaluate({
        host: this._data.host,
        pid: this._data.pid,
        prompt: this._data.searchBoxPrompt,
        goLabel: Store.getMessage('searchWidgetGoButtonLabel')});
    }
};

SSBlogWidget.prototype.makeLookBrowserWidget = function(siteHost, widgetUrl, searchUser, searchGroup, searchTags, size, widgetLocation, seeMoreLabel)
{
    var locationStyle = this.getLocationStyle(widgetLocation, false);
    var url = widgetUrl;
    var width = (size === 0) ? 270 : 480;
    var height = (size === 0) ? 290 : 456;
    url = this.appendCommonParams(url);

    var str = this._headerDivTemplate.evaluate({
        width: width,
        location: locationStyle});
    str += '<iframe src="' + url + '&';
    if (searchUser !== undefined) {
        str += 'searchUser=' + encodeURIComponent(searchUser);
    }
    else if (searchGroup !== undefined) {
        str += 'groupId=' + searchGroup;
     }
    else {
        str += 'searchTags=' + encodeURIComponent(searchTags);
    }

    if (size === 1) {
        str += '&size=Large';
    }
    str += '&border=0&footer=0';
    str += '&local=1&conservative=1" ';
    str += 'width="' + width + '" height="' + height + '" ';
    str += 'frameborder="0" scrolling="no"></iframe>';

    str += this._footerLinksTemplate.evaluate({
        imageHost: this._data.resourceHost,
        homeLink: siteHost,
        pid: this._data.pid,
        logoSuffix: (size === 0 ? '_small' : ''),
        seeMoreLink: siteHost + '/page/BrowseStylebooks?pid=' + this._data.pid,
        seeMoreLabel: seeMoreLabel});

    return str;
};

SSBlogWidget.prototype.makeProductWidget = function(widgetStyle, widgetSize, widgetLocation, showBrand, purchaseLink, productLink, siteHost, images, productName, brandPrompt, seeMoreUrl, poweredByAlt)
{
    if (purchaseLink === undefined) {
        return '';
    }
    var textSizeStyle = 'font-size:12px;';
    var poweredImage = 'ShopStyleLogo_powered_small.png';
    var imageUrl;
    if (widgetSize === 0) {
        imageUrl = images[0];
        textSizeStyle = 'font-size:10px;';
    }
    else if (widgetSize === 2) {
        imageUrl = images[2];
        poweredImage = 'ShopStyleLogo_powered.png';
    }
    else {
        imageUrl = images[1];
        textSizeStyle = 'font-size:11px;';
    }
    var seeMoreHref = siteHost + seeMoreUrl;
    if (seeMoreHref.indexOf('?') > -1) {
        seeMoreHref += '&pid=' + this._data.pid;
    }
    else {
        seeMoreHref += '?pid=' + this._data.pid;
    }

    var locationStyle = this.getLocationStyle(widgetLocation, true);
    var url = purchaseLink;
    url = this.appendCommonParams(url);
    var results = new Array(2);

    if (widgetStyle === 0 || widgetStyle === 1) {
        var str = '<table style="clear:both;';
        if (showBrand) {
            str += 'font-family:Verdana,Arial,Helvetica,sans-serif;';
        }
        if (locationStyle) {
            str += locationStyle;
        }
        str += '"><tr><td>';
        str += '<div style="border:1px solid #bfbfbf; background:white;">';
        str += '<div style="text-align:center;padding:5px">';

        str += '<a href="' + url +'" style="border:0" rel="nofollow" target="_blank">';
        str += '<img src="' + imageUrl + '" style="border-style:none"/>';
        str += '</a>';
        if (showBrand && productName !== undefined) {
            var width = this.getWidth(widgetSize === 2 ? 3 : widgetSize, 1, false);
            str += '<div style="margin:3px;width:' + width + 'px;' + textSizeStyle + '">';
            str += '<a href="' + this.appendCommonParams(productLink) + '" style="text-decoration:none;color:#606060">' + productName;
            str += '</a></div>';
        }
        /*if (brandPrompt !== undefined) { // TODO brand link replaced by product link above
            str += '<a href="' + seeMoreHref + '" style="text-decoration:none">';
            str += '<div style="margin:3px;color:#606060;' + textSizeStyle + '">'+brandPrompt+'</div>';
            str += '</a>';
        }*/
        str += '</div>';
        if (widgetStyle === 0) {  // include logo
            str += '<div style="text-align:right;padding:0px 2px 2px 2px">';
            str += '<a href="'+seeMoreHref+'" style="border:0;color:#909090">';
            str += '<img src="' + this._data.resourceHost + '/im/widget/'+poweredImage+'" alt="'+poweredByAlt+'" style="border-style:none;"/>';
            str += '</a></div>';
        }
        str += '</div></td></tr></table>';

        var dummyContent = '';
        if (locationStyle) {
            dummyContent = ' Sample content from your blog: Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod ' +
                'tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris ' +
                'nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu ' +
                'fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id ' +
                'est laborum. ';
        }

        results[0] = str + dummyContent;
        results[1] = str;
    }
    else {  // link only
        results[0] = url;
        results[1] = url;
    }

    return results;
};

SSBlogWidget.prototype.makeTrendWidget = function(siteHost, widgetUrl, size, widgetLocation, catUrl, cellWidth, cellHeight, seeMoreLabel)
{
    var width = this.getWidth(size, cellWidth, false);
    var height = this.getHeight(size, cellHeight, false);
    var locationStyle = this.getLocationStyle(widgetLocation, false);

    var str = this._headerDivTemplate.evaluate({
        width: width,
        location: locationStyle});
    str += '<iframe width="' + width + '" height="' + height + '" frameborder="0" scrolling="no" ';
    var url = widgetUrl;
    url = this.appendCommonParams(url);

    str += 'src="' + url;
    if (catUrl) {
        str += '&cat=' + catUrl;
    }
    str += '&border=0&footer=0';
    str += '"></iframe>';

    str += this._footerLinksTemplate.evaluate({
        imageHost: this._data.resourceHost,
        homeLink: siteHost,
        pid: this._data.pid,
        logoSuffix: this.logoSuffix(size, cellWidth),
        seeMoreLink: siteHost + '/brands/Popular?pid=' + this._data.pid,
        seeMoreLabel: (size === 0 && cellWidth < 4) ? '' : seeMoreLabel});

    return str;
};

SSBlogWidget.prototype.makeBrandWidget = function(siteHost, widgetUrl, cellWidth, cellHeight, seeMoreLabel)
{
    var width = 165 * cellWidth;
    var height = 191 * cellHeight + 54;

    var str = this._headerDivTemplate.evaluate({
        width: width,
        location: ''});
    str += '<iframe width="' + width + '" height="' + height + '" frameborder="0" scrolling="no" ';
    var url = widgetUrl;
    url = this.appendCommonParams(url);

    str += 'src="' + url;
    str += '&border=0&footer=0';
    str += '"></iframe>';

    str += this._footerLinksTemplate.evaluate({
        imageHost: this._data.resourceHost,
        homeLink: siteHost,
        pid: this._data.pid,
        logoSuffix: '',
        seeMoreLink: siteHost + '/brands/Popular?pid=' + this._data.pid,
        seeMoreLabel: seeMoreLabel});

    return str;
};

SSBlogWidget.prototype.makePromotionWidget = function(siteHost, widgetUrl, catUrl, cellWidth, cellHeight, seeMoreLabel)
{
    var width = 344 * cellWidth;
    var height = 164 * cellHeight + 46;

    var str = this._headerDivTemplate.evaluate({
        width: width,
        location: ''});
    str += '<iframe width="' + width + '" height="' + height + '" frameborder="0" scrolling="no" ';
    var url = widgetUrl;
    url = this.appendCommonParams(url);

    str += 'src="' + url;
    if (catUrl) {
        str += '&cat=' + catUrl;
    }
    str += '&border=0&footer=0';
    str += '"></iframe>';

    str += this._footerLinksTemplate.evaluate({
        imageHost: this._data.resourceHost,
        homeLink: siteHost,
        pid: this._data.pid,
        logoSuffix: '',
        seeMoreLink: siteHost + '/page/Promotions?pid=' + this._data.pid,
        seeMoreLabel: seeMoreLabel});

    return str;
};

SSBlogWidget.prototype.logoSuffix = function(size, columns)
{
    return (size === 0 || (size === 1 && columns < 3) || (size === 2 && columns < 2)) ? '_small' : '';
};

SSBlogWidget.prototype.getLocationStyle = function(widgetLocation, isBlock)
{
    if (widgetLocation === "-1") {
        return 'float:left;margin-right:10px;';
    }
    else if (widgetLocation === "1") {
        return 'float:right;margin-left:10px;';
    }
    else if (widgetLocation === "0" && !isBlock) {
        return 'display:block;';
    }
    /* -- to support an "inline" option, which looks ugly
    else if (widgetLocation == 2 && isBlock) {
        return 'display:inline;';
    }
    */
    else {
        return '';
    }
};

SSBlogWidget.prototype.makeAdUnit = function(siteHost, widgetUrl, version, cat, size, color)
{
    var expandIdx = size.search(/-Expand/i);
    var popup = false;
    if (expandIdx >= 0) {
        popup = true;
        size = size.substring(0, expandIdx);
    }
    var sizeInfo = size.split('x');
    var width = sizeInfo[0];
    var height = sizeInfo[1];

    if (siteHost.indexOf('http://') === 0) {
        siteHost = siteHost.substring(7);
    }

    var url = widgetUrl + '?';
    if (siteHost !== 'www.shopstyle.com' && siteHost.indexOf('localhost') < 0) {
        url += 'site=' + siteHost + '&';
    }
    url += "size=" + size + "&cat=" + cat + "&v=" + version + "&color=" + color;
    var pid = this._data.pid;
    if (pid === 'anonymous') {
        pid = '2254';
    }
    url += "&pid=" + pid;

    if(popup) {
        url += "&expand=true";
    }

    var results = new Array(2);
    results[1] = "<script src='" + url + "' language='Javascript'><\/script>";
    if (popup) {
//        results[0] = '<div id="widgetbuilder-sample" style="height:' + height + 'px;">' +
//            '<script>alert("src=' + url + '");</script><script src="' + url + '"></script></div>';
      results[0] = 'ad-frame-' + size + '-Expand';
    }
    else {
        results[0] =
            '<iframe id="widgetbuilder-sample" src="' + url + '&iframe=true" marginheight="0" marginwidth="0" ' +
            'frameborder="0" width="' + width + '" height="' + height + '" scrolling="no" width="300"> </iframe>';
    }

    return results;
};

SSBlogWidget.prototype.getResourcePath = function()
{
    // This is a hack which doesn't work on local instances but works on dev and prod
    var cleardotUrl = this._data.cleardotUrl;
    var idx = cleardotUrl.lastIndexOf('/');
    return cleardotUrl.substring(0,idx + 1);
};

