var PerPage = 12;
var PerLine = 4;
var MinCatCount = 24;
var MinBrandCount = 4;  // limited at top level only
var PartnerId = "uid209-802047-76";  // stylecom

var currentTrendId;
var currentBrand = "";
var currentSale = "";

function fetchLook(host)
{
    // Get a look to prepend. Do this first so we can adjust min/count for main query;
    // always fetching at least one so we have a total count.
    // Note we skip if cat/filter supplied.
    currentTrendId = getParameter("trend");
    if (currentTrendId == null) {
        currentTrendId = "1";
    }
    if (typeof(AllTrends[currentTrendId]) == 'undefined') {
        currentTrendId = "-1";
    }
    
    var look = AllTrends[currentTrendId].look;
    if (look != null && getParameter("cat") == null && getParameter("b") == null && getParameter("s") == null) {
        var scriptSrc = host + '/action/apiGetLook?pid=' + PartnerId + '&look=' + look + '&format=jsonvar';
        writeScript(scriptSrc);
    } else {
        shopstyle_look = null;
    }
    
}

// modified from tx.js
function getParameter(param)
{
    var i = window.location.search.indexOf(param + "=");
    if (i > -1) {
        i += param.length + 1;
        var j = window.location.search.indexOf("&", i);
        if (j == -1)
            j = window.location.search.length;
        return window.location.search.substring(i, j);
    }
    return null;
}

function replaceParam(url, param, value)
{
    var start = url.indexOf(param + '=');
    var paramValue = (value == '' ? '' : param + '=' + value);
    if (start > -1) {
        var end = url.indexOf('&', start);
        return url.substring(0, start) + paramValue + (end > -1 ? url.substring(end) : '');            
    }
    else {
        return url + (url.indexOf('?') > -1 ? '&' : '?') + paramValue;
    }
}

function removeParam(url, param)
{
    var i = url.indexOf(param + "=");
    if (i > -1) {
        var j = url.indexOf("&", i);
        if (j == -1) {
            if (i > 0 && url.charAt(i - 1) == '?' || url.charAt(i - 1) == '&') {
                i--;
            }
            return url.substring(0, i);
        } else {
            return url.substring(0, i) + url.substring(j + 1, url.length);
        }
    }
    return url;
}

function writeScript(scriptUrl)
{
    document.write('<script src="' + scriptUrl + '" language="JavaScript" type="text/javascript"></scr'+'ipt>');
}

function fetchProducts(host)
{
    var min = getParameter("min");
    if (min == null) {
        min = "0";
    }
    currentCat = getParameter("cat");
    if (currentCat == null) {
        currentCat = "women";
    }
    var count = "" + PerPage;
    var brand = getParameter("b");
    if (brand != null) {
        currentBrand = "&fl=b" + brand;
    }
    var sale = getParameter("s");
    if (sale != null) {
        if (sale == "0") {
            currentSale = "&fl=d0";
        } else if (sale == "100") {
            currentSale = "&fl=p7&fl=p8&fl=p9";
        } else if (sale == "250") {
            currentSale = "&fl=p7&fl=p8&fl=p9&fl=p10&fl=p11";
        }
    }

    if (typeof shopstyle_look=='undefined') {
        shopstyle_look = null;
    }   
    if (shopstyle_look != null && shopstyle_look.products.length > 0) {
        min = Math.max(0, min - shopstyle_look.products.length);
    }

    var scriptSrc = host + '/action/apiSearch?pid=' + PartnerId + '&pflt=' + currentTrendId + '&min=' + min + '&cat=' + currentCat + '&count=' + count +
        '&format=jsonvar' + currentBrand + currentSale;
    writeScript(scriptSrc);
    
    scriptSrc = host + '/action/apiGetCategoryHistogram?pid=' + PartnerId + '&pflt=' + currentTrendId + '&format=jsonvar';
    writeScript(scriptSrc);

    scriptSrc = host + '/action/apiGetFilterHistogram?filterType=Brand&pid=' + PartnerId + '&pflt=' + currentTrendId + '&cat=' + currentCat +
        '&format=jsonvar' + currentSale;
    writeScript(scriptSrc);
    
    document.write('<title>Shop ' + AllTrends[currentTrendId].title + '</ti'+'tle>');
}

function totalCount()
{
    return parseInt(shopstyle_searchResult.totalCount) + (shopstyle_look == null ? 0 : shopstyle_look.products.length);
}

function writeBanner()
{
    var image = AllTrends[currentTrendId].name;
    if (AllTrends[currentTrendId].cat) {
        image = "Generic-Header";
    }
    write("<img src=\"/partner/stylecom/im/STL-" + image + ".png\" width=\"826\" height=\"84\">");
}

function writeProducts(host)
{
    var min = getParameter("min");
    if (min == null) {
        min = 0;
    } else {
        min = parseInt(min);
    }

    // TODO 'shop all' link won't include products from look
    var shopUrl = host + "/browse";
    if (currentCat != null) {
        shopUrl += "/" + currentCat;
    }
    shopUrl += "?pflt=" + currentTrendId;
    shopUrl += currentBrand;
    shopUrl += currentSale;
    shopUrl += "&nodept=1";
    if (min > 0) {
        shopUrl += "#" + min + "_0";
    }
    write("<div style=\"position:absolute;left:10px;top:4px;font-size:13px\"><a href=\"" + shopUrl + "\" class=\"storeLink\">shop all &#8250;</a></div>");

    write("<div style=\"text-align:center; padding-bottom:15px; font-size:12px\">");

    if (totalCount() == 0) {
        write("<p class='large'>No products found. Select a new category or look at left.</p>");
        return;
    }
    
    if (min >= PerPage) {
        var prev = replaceParam(window.location.href, 'min', '' + (min - PerPage));
        write("<a href=\"" + prev + "\"><img src=\"/partner/stylecom/im/left-button-active.png\" border=0 style=vertical-align:-6px></a>");
    }
    else {
        write("<img src=\"/partner/stylecom/im/left-button-inactive.png\" border=0 style=vertical-align:-6px>");
    }
    write("<span style=padding:2px>" + (Math.ceil(min / PerPage) + 1) + " of " + Math.ceil(totalCount() / PerPage) + "</span>");
    if (totalCount() > min + PerPage) {
        var next = replaceParam(window.location.href, 'min', min + PerPage);
        write("<a href=\"" + next + "\"><img src=\"/partner/stylecom/im/right-button-active.png\" border=0 style=vertical-align:-6px></a>");
    }
    else {
        write("<img src=\"/partner/stylecom/im/right-button-inactive.png\" border=0 style=vertical-align:-6px>");
    }
    write("</div>");
    write("<table><tr>");

    var itemCount = 0;
    var i = 0;
    if (shopstyle_look != null && min < shopstyle_look.products.length) {
        for (i = min; i < shopstyle_look.products.length; i++) {
            writeProduct(shopstyle_look.products[i], i);
            if (++itemCount == PerPage) {
                break;
            }
        }
    }

    if (itemCount < PerPage) {
        for (var j = 0; j < shopstyle_searchResult.products.length; j++) {
            writeProduct(shopstyle_searchResult.products[j], j + i);
            if (++itemCount == PerPage) {
                break;
            }
        }
    }
    write("</tr></table>");
}

function writeProduct(product, index)
{
    write("<td>");
    write("<div class=\"product\">");
    write("<a href=\"" + product.url + "\" target=\"shopstyle_product\" class=\"productImage\">");
    write("<img src=\"" + product.images[1].url + "\" border=0>");
    write("</a></div>");
    write("<div class=\"productText\">");
    write("<div class=\"productName\">" + product.name + "</div>");
    if (product.salePriceLabel != null) {
        write("<span class=\"originalPrice\">" + product.priceLabel + "</span> " + product.salePriceLabel);
    } else {
        write(product.priceLabel);
    }
    write(" &ndash; " + product.retailer);
    write("</div></td>");
    if ((index+1) % PerLine == 0) {
        write("</tr><tr>");
    }
}

// Note these clear other filters in effect
function writeSidebarCats()
{
    write("<span style=\"font-weight:bold\">" + shopstyle_searchResult.queryDetails.powerFilter + "</span>");
    if (!AllTrends[currentTrendId].cat) {
        write("<div style=\"padding-left:10px\">");
        writeCat("womens-accessories", "Accessories");
        writeCat("handbags", "Bags");
        writeCat("dresses", "Dresses");
        writeCat("jewelry", "Jewelry");
        writeCat("pants-shorts", "Pants");
        writeCat("skirts", "Skirts");
        writeCat("womens-shoes", "Shoes");
        writeCat("womens-tops", "Tops");
        write("</div>");
    }
}

// TODO slow scanning of array. convert to map
function writeCat(id, name)
{
    for (var i = 0; i < shopstyle_categoryHistogram.categories.length; i++) {
        var cat = shopstyle_categoryHistogram.categories[i];
        if (cat.id == id && cat.count >= MinCatCount) {
            var url = removeParam(window.location.search, 'b');
            url = removeParam(url, 's');
            url = removeParam(url, 'min');
            if (id == getParameter('cat')) {
                url = removeParam(url, 'cat');
            } else {
                url = replaceParam(url, 'cat', id);
            }
                        
            write("<a ");
            if (id == getParameter('cat')) {
                write("class=\"selected\" ");
            }
            write("href=\"" + url + "\">" + name + "</a><br>");
            break;
        }
    }
}

function writeSidebarFilters()
{
    var sale = getParameter("s");
    write("<div>");
    writeFilter("s", "0", sale, "On sale");
    writeFilter("s", "100", sale, "Under $100");
    writeFilter("s", "250", sale, "Under $250");

    write("</div>");
}

function writeFilter(key, id, value, name)
{
    var url = removeParam(window.location.search, 'min');
    if (id == value) {
        url = removeParam(url, key);
    } else {
        url = replaceParam(url, key, id);
    }
    write("<a ");
    if (id == value) {
        write("class=\"selected\" ");
    }
    write("href=\"" + url + "\" id=\"" + key + id + "\">" + name + "</a><br>");
}

function writeSidebarBrands()
{
    var brand = getParameter("b"); 
    for (var i = 0; i < shopstyle_filterHistogram.filters.length; i++) {
        if (currentCat != "women" || currentSale != "" || parseInt(shopstyle_filterHistogram.filters[i].count) >= MinBrandCount) {
            writeFilter("b", shopstyle_filterHistogram.filters[i].id, brand, shopstyle_filterHistogram.filters[i].name);
        }
    }
    if (brand != null) {
        $('brands').scrollTop = $("b" + brand).offsetTop;
    }
}

function writeSidebarTrends(isCategories)
{
    for (var trend in AllTrends) {
        if (trend > 0 && (isCategories == AllTrends[trend].cat)) {
            write("<a ");
            if (trend == currentTrendId) {
                write("class=\"selected\" ");
            }
            write("href=\"?trend=" + trend + "\" id=\"t" + trend + "\">" + AllTrends[trend].title + "</a><br>");
        }
    }
    if (!AllTrends[currentTrendId].cat) {
        $('trends').scrollTop = $("t" + currentTrendId).offsetTop;
    }
}

function write(line)
{
    document.writeln(line);
}

function writeAdTag(keyword, size, tile)
{
    if (typeof ord=='undefined') {ord=Math.random()*10000000000000000;}
    document.write('<script language="JavaScript1.1" src="http://ad.doubleclick.net/adj/style.dart.shopstyle/shopstyle;kw=shopstyle;kw=' + keyword + ';tile=' + tile + ';dcopt=ist;sz=' + size + ';ord=' + ord + '?" type="text/javascript"><\/script>');
    
    if ((!document.images && navigator.userAgent.indexOf('Mozilla/2.') >= 0)|| navigator.userAgent.indexOf("WebTV") >= 0) {
        document.write('<a href="http://ad.doubleclick.net/jump/style.dart.shopstyle/shopstyle;kw=shopstyle;kw=' + keyword + ';tile=' + tile + ';sz=' + size + ';ord=123456789?" target="_blank">');
        document.write('<img src="http://ad.doubleclick.net/ad/style.dart.shopstyle/shopstyle;kw=shopstyle;kw=' + keyword + ';tile=' + tile + ';sz=' + size + ';ord=123456789?" width="300" height="600" border="0" alt=""><\/a>');
    }
}
