﻿var _isJavascriptAware;
var _itemsPerPage;
var _rowset;
var data=[];
var dString;
var filter = [];
var keywords;
var msrp;
var sortOrder = 0;
(
    function($) {
        var cLoc = location.href;
        var cHash = location.href.split('#')[1];
        var pLoc = "";
        var pHash = "";
        var intTime = 100;
        var checkLoc = function() {
            //if (cLoc != location.href) {
            pLoc = cLoc;
            pHash = cHash;
            cLoc = location.href;
            cHash = location.href.split('#')[1];
            if (cHash == undefined) {
                cHash = "pg1";
            }
            //$(location).trigger("change");
            //}
        }
//        if (!location.hash) {
//            location.hash = '#pg1';
//            location.replace;
//        }
        setInterval(checkLoc, intTime);
    }
)(jQuery);

    $(document).ready(function() {
        _isJavascriptAware = $(".hidden_javascript_aware").val();
        if (_isJavascriptAware == "true") {
            data_manifest();                                            // Initialize data manifest (called once unless reloaded)
            window.onload = function() {
                changeUp();                                             // Call changeUp() upon pageload.
                $(location).bind("change", function() {
                    changeUp();                                         // Only called if URL is changed without a true page reload (i.e., hashtags).
                });
            };

            $("#productList #listContainer .topBar .lblPaginationHolder a, #productList #listContainer .topBar .viewAllLink").live("click", function() {
                //changeUp();
                setTimeout(changeUp, 100);
            });

            $('#listContainer').tabs({                                  // If tabs exist we need to account for the extra level of hierarchy.
                select: function(event, ui) {
                    var url = ui.tab.hash.split('#')[1];
                    var page = location.href.split('?tab=')[0].split('#pg')[1];
                    location.href = '#pg' + page + '?tab=' + url;
                    location.reload;
                }
            });


            $(".narrowMenu #narrowItDown .removeFilters").live('click', function() {
                $("#keywords").val("");
                filter = [];
                msrp = '';
                msrp_menu();
                keywords = "";
                changeUp();
            });


            // If the Narrow it Down exists...fire.
            $(".narrowDownPrice input[type=checkbox]").live('click', function() {
                if ($(this).is(':checked')) {
                    msrp = $(this).attr("id");
                    msrp_menu($(this).attr("id"));
                } else {
                    msrp = '';
                    msrp_menu();
                }
                changeUp();
            });
            $(".narrowDownOptions input[type=checkbox]").live('click', function() {
                if ($(this).is(':checked')) {
                    i = 0;
                    $(".narrowDownOptions input[type=checkbox]:checked").each(function() {
                        filter[i] = $(this).attr("id");
                        i++;
                    });
                } else {
                    if (filter) {
                        var jChecked = $(this).attr("id");
                        i = 0;
                        $(filter).each(function() {
                            if (filter[i] == jChecked) filter.splice(i, 1);
                            i++;
                        });
                    }
                }
                changeUp();
            });

            //Commented for bug# 7547: Result set repeating because ChangeUp() was called twice        
                        $(".narrowDownBar").bind('change', function() {
                            if ($(this).val()) {
                                filter = $(this).val();
                            } else {
                            }
                            changeUp();
                        });


            $("#narrowItDown input[type=submit]").click(function() {
                keywords = $("#narrowItDown #keywords").val();
                //if (keywords != "") {
                changeUp();
                //}
                return false;
            });


            $("#topCompareSubmit, #bottomCompareSubmit").live('click', function() {
                var checked = $(".product input[type=checkbox]:checked");
                var url = document.location.protocol + "//" + document.location.host + "/pages/products_accessories/ComparePlaceHolder.aspx?";
                if (checked.length > 1) {
                    var i = 1;
                    $.each(checked, function() {
                        url += "prod" + i + "=" + $(this).attr("id") + "&";
                        i += 1;
                    });
                    $.fancybox(url,
		            {
		                'width': '75%',
		                'height': '85%',
		                'autoScale': false,
		                'titleShow': 'true',
		                'type': 'iframe',
		                'centerOnScroll': 'true',
		                'title': 'Compare'
		            });
                }
                else {
                    alert("Please select 2 or 3 products to compare.");
                }
                return false;
            });

            $(".product input[type=checkbox]:checked").live('click', function(e) {
                if ($(".product input[type=checkbox]:checked").length > 3) {
                    alert("You may only compare up to 3 products at a time");
                    $(this).attr('checked', false);
                }
            });


            $("#topSort").live('change', function(e) {
                sortOrder = $(this).val();
                changeUp();
            });
        }
    });

    function data_manifest() {

    // Service and rowset to be used.
    if ($(".hidden_service").val()) _service = $(".hidden_service").val();
    if ($(".hidden_rowset").val()) _rowset = $(".hidden_rowset").val();

    data = '';
    // Compile data string to send to the web service. These settings are largely determined in the corresponding ASCX file.
    // More values may be placed here and concatinated into the superstring.
    if ($(".hidden_consumer_touchpoint_id").val()) data += "'consumerTouchPointId':'" + $(".hidden_consumer_touchpoint_id").val() + "',";
    
    // These are product list-specific using 'GetProducts' service.
    if ($(".hidden_itemsPerPage").val()) data += "'itemsPerPage':'" + $(".hidden_itemsPerPage").val() + "',";
    if ($(".hidden_totalItems").val()) data += "'totalItems':'" + $(".hidden_totalItems").val() + "',";
    
    if (location.search.split("category=")[1] != null) data += "'categoryId':'" + location.search.split("category=")[1] + "',";
    else if ($(".hidden_category").val()) data += "'categoryId':'" + $(".hidden_category").val() + "',";

    if (location.search.split("terms=")[1] != null) data += "'searchQuery':'" + location.search.split("terms=")[1] + "',";
    else if ($(".hidden_terms").val()) data += "'searchQuery':'" + $(".hidden_terms").val() + "',";

    if ($(".hidden_limit").val()) data += "'limit':'" + $(".hidden_limit").val() + "',";

    if ($(".hidden_featured").val()) data += "'isFeaturedOnly':'" + $(".hidden_featured").val() + "',";
    if ($(".hidden_recommended").val()) data += "'recommendedProduct':'" + $(".hidden_recommended").val() + "',";
    if ($(".hidden_newproducts").val()) data += "'isNewOnly':'" + $(".hidden_newproducts").val() + "',";
    if ($(".hidden_discontinued").val()) data += "'excludeDiscontinued':'" + $(".hidden_discontinued").val() + "',";
    if ($(".hidden_sortCode").val()) data += "'sortCode':'" + $(".hidden_sortCode").val() + "',"; // Remove whenever possible.


    // Narrow Down-Specific

    if (msrp) data += "'msrpIndex':'" + msrp + "',";
    else if ($(".hidden_msrp").val()) data += "'msrpIndex':'" + $(".hidden_msrp").val() + "',";

    if ($(".hidden_filterList").val()) {
        if (filter) data += "'filterList':'" + filter + "',";
        else if ($(".hidden_filterList").val('')) data += "'filterList':'" + $(".hidden_filterList").val() + "',";
    } else {
        if (filter) data += "'jsonFilterList':'" + filter + "',";
        else if ($(".hidden_filter").val('')) data += "'jsonFilterList':'" + $(".hidden_filter").val() + "',";
    }    
     
    if (keywords) data += "'keywords':'" + keywords + "',";
    else if ($(".hidden_keywords").val()) data += "'keywords':'" + $(".hidden_keywords").val() + "',";

    if (sortOrder) data += "'sortOrder':'" + sortOrder + "',";
    else if ($(".hidden_sortOrder").val()) data += "'sortOrder':'" + $(".hidden_sortOrder").val() + "',";
}

function changeUp() {

        data_manifest(); 
        var tab = location.href.split('?tab=')[1];
        var page = location.href.split('?tab=')[0].split('#pg')[1];
        if (tab) $('a[href=#' + tab + ']').trigger('click');
        else tab = 'entries';
        if (page) {
            $('.' + tab).html('');
            var _data = '';

            list_generator(page, _service, _rowset, tab, msrp, filter, keywords, sortOrder);
        } else {
        $('.' + tab).html('');
            var _data = '';
            list_generator(1, _service, _rowset, tab, msrp, filter, keywords, sortOrder);
        }
    
}

function list_generator(page, service, rowset, target, msrp, filter, keywords, sortOrder) { // This makes the actual service call.
    var dString = "{" + data + "'culture':'" + culture + "','currentPage':'" + page + "'}";
//    alert(dString);
    setTimeout(function() {
        $.ajax({
            type: "post",
            url: service,
            dataType: "json",
            cache: true,
            data: dString,
            contentType: "application/json; charset=utf-8",
            success: function(json) {
                //alert(json.d); 
                var jObj = jQuery.parseJSON(json.d);                // Native jQuery parses JSON into proper objects.
                if (jObj.length > 0) {
                    pagination(jObj[0][0], jObj[1].length);         // This handles the pagination by passing prod obj length and page info obj
                    eval(rowset)(jObj[1], target);                  // Detects the correct rowscheme and sends for parsing item list
                    if (jObj[2]) narrow_menu(jObj[2]);              // If it exists, set up the Narrow Down Menu
                } else {
                    alert("No Products Found.");
                }

            },
            error: function(response) {
                alert("JSON Error Response:\r\n" + response.responseText);
            }
        });
    }, 100);
}

function pagination(d, lng, elem) {
    var pages = '';
    var pg = '';                                                    // Initialize paginator area
    var cpg = d.PageIndex;                                          // Current Page #
    var ppg = d.ItemsPerPage;                                       // Listings per Page
    var tpg = d.TotalPageCount;                                     // Total # of Pages
    var st = ((cpg - 1) * d.ItemsPerPage) + 1;                      // Start of the Range
    if (d.ItemsPerPage == lng) var plng = cpg * d.ItemsPerPage;     // # of Listings Returned: Page
    else var plng = d.TotalItemCount;
    var length = d.TotalItemCount;                                  // # of Listings Returned: Total
    if (location.href.split('?tab=')[1]) var tab = '?tab=' + location.href.split('?tab=')[1];
    else tab = '';
    for (i=1;i<=d.TotalPageCount;i++) {
        if (i == cpg) {
            pages += '<span class="lblPaginationHolder"><a href="#pg' + i + tab + '"><span class="current">' + i + '</span></a></span>';
        } else {
            pages += '<span class="lblPaginationHolder"><a href="#pg' + i + tab + '">' + i + '</a></span>';
        }
    };
    pg += '<span class="lblSearchResultsCountHolder">'+ st + '-' + plng + ' of ' + length + '</span>';
    pg += pages;
    pg += '<a href="#pg9999" class="viewAllLink">View All</a>';
    pg += '<select id="topSort" style="float:right;margin-right:15px;">';
    pg += '<option value="0">Sort by</option>';
    if ($(".hidden_service").val() != "/webservices/ProductService.asmx/GetMyRegisteredProductsPaginated") {
        pg += '<option value="1">New Products on Top</option>';
        pg += '<option value="2">Price High–to-Low</option>';
        pg += '<option value="3">Price Low-to-High</option>';
    }
    pg += '<option value="4">Name A – Z</option>';
    pg += '<option value="5">Name Z – A</option>';
    pg += '</select>';
    $('.topBar').html(pg);  // Inject results into Paginator Class

    $("#topSort option").removeAttr('selected');
    if (sortOrder) $("#topSort option[value='" + sortOrder+ "']").attr('selected', 'selected');
}

function msrp_menu(id) {
    var msrpMenu = '';
    msrpMenu += "<h3><span>MSRP</span></h3>";
    msrpMenu += "<ul class='narrowCheck'>";
    switch (id) {
        case '1':
            msrpMenu += "<li><input type='checkbox' id='1' CHECKED/><label>$1 - $50</label></li>";
            break;
        case '2':
            msrpMenu += "<li><input type='checkbox' id='2' CHECKED/><label>$51 - $100</label></li>";
            break;
        case '3':
            msrpMenu += "<li><input type='checkbox' id='3' CHECKED/><label>$101 - $150</label></li>";
            break;
        case '4':
            msrpMenu += "<li><input type='checkbox' id='4' CHECKED/><label>$151 - $200</label></li>";
            break;
        case '5':
            msrpMenu += "<li><input type='checkbox' id='5' CHECKED/><label>$201 - $300</label></li>";
            break;
        case '6':
            msrpMenu += "<li><input type='checkbox' id='6' CHECKED/><label>$301 - $500</label></li>";
            break;
        default:
            msrpMenu += "<li><input type='checkbox' id='1' /><label>$1 - $50</label></li>";
            msrpMenu += "<li><input type='checkbox' id='2' /><label>$51 - $100</label></li>";
            msrpMenu += "<li><input type='checkbox' id='3' /><label>$101 - $150</label></li>";
            msrpMenu += "<li><input type='checkbox' id='4' /><label>$151 - $200</label></li>";
            msrpMenu += "<li><input type='checkbox' id='5' /><label>$201 - $300</label></li>";
            msrpMenu += "<li><input type='checkbox' id='6' /><label>$301 - $500</label></li>";
            break;
    }
    msrpMenu += "</ul>";
    $(".narrowDownPrice").html(); // Clear this div. 
    $(".narrowDownPrice").html(msrpMenu);
}

function sortOrder_dropdown(id) {
}

function narrow_menu(d) {
    var newMenu = '';
    i = 0;
    if ($(".hidden_filterList").val()) {
            newMenu += "<option value='" + $(".hidden_filterList").val() + "'>View All</option>";
            $(d).each(function() {
                if (d[i].Error) {
                    newMenu += "<option>No Filters Available</option>";
                } else {
                if (filter == d[i].GSACollection) var selected = 'selected';
                    newMenu += "<option value='" + d[i].GSACollection + "' " + selected + ">" + d[i].FilterName + " (" + d[i].FilterCount + ")</option>";
                    i++;
                }
            });
    } else {
        $(d).each(function() {
            if (d[i].Error) {
                newMenu += "<h3><span>No Available Filters</span></h3>";
                $(".narrowDownPrice").hide();
            } else {
                $(".narrowDownPrice").show();
                newMenu += "<h3><span>" + d[i].ShortDescription + " (" + d[i].ProductCount + ")</span></h3>";
                newMenu += "<ul class='narrowCheck'>";
                j = 0;
                $(d[i].FilterSummarySpecs).each(function() {
                    var check = '';
                    if (d[i].FilterSummarySpecs[j].IsSelected == true) check = 'CHECKED';
                    newMenu += "<li><input type='checkbox' id='" + d[i].FilterSummarySpecs[j].ID + "' " + check + "/><label>" + d[i].FilterSummarySpecs[j].Description + " (" + d[i].FilterSummarySpecs[j].ProductCount + ")</label></li>";
                    j++;
                });
                newMenu += "</ul>";
                i++;
            }
        });
    }
    $(".narrowDownOptions").html(); // Clear this div. 
    $(".narrowDownOptions").html(newMenu);
}

// CHANNEL INTELLIGENCE INJECTOR

function ciRowBlock(model, length) {
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = "http://blackanddecker.links.channelintelligence.com/scripts/cii_CBL_DataService.asp?sSKU=" + model;
    head.appendChild(script);
    //cii_ShowCBLButton(model, oCIIPrimaryLink, oCIIAlternateLink, 1);
}

// LISTS: ROW DEFINITIONS

function listProducts(d, target) {
    // Build out the list
    var row = '';
    if (!d[0].Error) {                                                   // Initialize the content area.
        $.get("/html/lists/ProductRow.htm", function(contents) {
            i = 0;
            $(d[0]).each(function() {                                                       // Cycle through and render listings
                ciRowBlock(d[0][i].ProductKey);
                row = contents;                                                          // Assign the template as a row
                $('.' + target).append(row);                                             // Append the row (held in the 'target' variable)
                if (i % 2 == 1) $('.' + target + ' .product:last').addClass('odd');      // Begin injecting JSON data & zebra rows
                $('.' + target + ' .product_image:last').attr('src', d[0][i].ProductImagePath);
                $('.' + target + ' .product_image:last').attr('alt', d[0][i].ProductImageAltText);
                $('.' + target + ' .product_title:last').attr('href', location.protocol + "//" + location.host + d[0][i].ProductURL);
                $('.' + target + ' .moreInfo a:last').attr('href', location.protocol + "//" + location.host + d[0][i].ProductURL);
                $('.' + target + ' .buyNow a:last').attr('href', "javascript:manu_CDLink('blackanddecker','" + d[0][i].ProductKey + "',null,null,null);");
                $('.' + target + ' .wishList a:last').attr('id', 'wishListItem' + i);
                $('.' + target + ' .wishList a:last').attr('href', 'javascript:createWishlist("' + d[0][i].ProductKey + '", "wishListItem' + i + '");');
                $('.' + target + ' .pluck_rating:last').html("TEST");
                $('.' + target + ' .product_title:last').html(d[0][i].DisplayName);
                $('.' + target + ' .product_description:last').html(d[0][i].ProductKey);
                //$('.' + target + ' .model_number:last').html(d[0][i].ModelNumber);
                if (d[0][i].MSRP) $('.' + target + ' .product_msrp:last').html(d[0][i].MSRP);
                else $('.' + target + ' .msrp:last').hide();
                //
                i++;                                                                     // Iterate
            });
        });
    } else {
        $('.' + target).html("<div><h3>No Products Found</h3></div>");
    }
}

function listProductsGen(d, target) {
    var row = '';
    var pluckRatingHTML = "";
    var pluckRating = 0;
    if (!d[0].Error) {
        $('.topRatedProduct').show();
        $.get("/html/lists/GenProductRow.htm", function(contents) {
            i = 0;
            $(d).each(function() {                                      // Cycle through and render listings
                ciRowBlock(d[i].ProductKey);
                row = contents;                                         // Assign the template as a row
                $('.' + target).append(row);                              // Append the row (held in the 'target' variable)
                if (i % 2 == 1) $('.' + target + ' .product:last').addClass('odd');     // Begin injecting JSON data & zebra rows
                $('.' + target + ' .product_image:last').attr('src', d[i].ProductImagePath);
                $('.' + target + ' .product_image:last').attr('alt', d[i].ProductImageAltText);
                $('.' + target + ' .product_image_link:last').attr('href', location.protocol + "//" + location.host + d[i].ProductURL);
                $('.' + target + ' .compare:last').attr('id', d[i].ProductId);
                $('.' + target + ' .product_title:last').attr('href', location.protocol + "//" + location.host + d[i].ProductURL);
                $('.' + target + ' .moreInfo a:last').attr('href', location.protocol + "//" + location.host + d[i].ProductURL);
                $('.' + target + ' .wishList a:last').attr('id', 'wishListItem' + i);
                $('.' + target + ' .wishList a:last').attr('href', 'javascript:createWishlist("' + d[i].ProductKey + '", "wishListItem' + i + '");');
                $('.' + target + ' .buyNow a:last').attr('href', "javascript:manu_CDLink('blackanddecker','" + d[i].ProductKey + "',null,null,null);");
                pluckRatingHTML = "<span class=\"starRatings\">" + Math.round(d[i].PluckRatingAverage) + "</span> Reviews: " + d[i].NumberOfReviews;
                $('.' + target + ' .pluck_rating:last').html(pluckRatingHTML); 
                $('.' + target + ' .product_title:last').html(d[i].DisplayName);
                $('.' + target + ' .product_description:last').html(d[i].ProductKey);
                //$('.' + target + ' .model_number:last').html(d[0][i].ModelNumber);
                if (d[i].MSRP) $('.' + target + ' .product_msrp:last').html(d[i].MSRP);
                else $('.' + target + ' .msrp:last').hide();
                i++;                                                    // Iterate

            });

            $(".pluck_rating .starRatings").each(function() {
                var currentRating = $(this).html();
                var currentRatingHTML = "";
                for (i = 1; i <= 5; i++) {
                    if (currentRating >= i) {
                        currentRatingHTML += "<span class='star filled'>&nbsp;</span>";
                    } else {
                        currentRatingHTML += "<span class='star'>&nbsp;</span>";
                    }
                }
                //alert("current rating: " + currentRating);
                $(this).html(currentRatingHTML);
            });
        });
    } else {
        $('.topBar:first').html("<strong>Please revise your search.</strong>");
        $('.topBar.bottomBar').html("<strong>No Products Available</strong>");
        $('.' + target).html("");
        $('.topRatedProduct').hide();
    }

}

function listRegistered(d, target) {
    var row = '';
    $.get("/html/lists/RegProductRow.htm", function(contents) {
        i = 0;
        $(d[0]).each(function() {
            row = contents;
            $('.' + target).append(row);
            if (i % 2 == 1) $('.' + target + ' .product:last').addClass('odd');
            if (d[0][i].ProductItem.ProductImagePath != "" && d[0][i].ProductItem.ProductImagePath != null) {
                $('.' + target + ' .product_image:last').attr('src', d[0][i].ProductItem.ProductImagePath);
            } else {
                $('.' + target + ' .product_image:last').attr('src', "/assets/images/" + culture + "/noImageAvailable110.gif");
            }
            $('.' + target + ' .product_image:last').attr('alt', d[0][i].ProductItem.ProductImageAltText);
            $('.' + target + ' .product_title:last').attr('href', d[0][i].ProductItem.ProductURL);
            $('.' + target + ' .prod_detail a:last').attr('href', d[0][i].ProductItem.ProductURL);
            $('.' + target + ' .regProduct_label:last').attr('href', d[0][i].ProductItem.ProductURL);
            $('.' + target + ' .product_title:last').html(d[0][i].ProductItem.DisplayName);
            $('.' + target + ' .model_number:last').html(d[0][i].ModelNumber);
            //$('.' + target + ' .brand_name:last').html(d[0][i].BrandID);
            $('.' + target + ' .purchase_type:last').html(d[0][i].PurchaseTypeID);
            $('.' + target + ' .purchase_date:last').html(d[0][i].OriginalDateOfPurchase);
            /*Manuals*/
            var fileURL = "";
            var docDesc = "";
            var currentDocument;
            if (d[0][i].Documents == null) {
                var documentLength = 0;
            } else {
                var documentLength = d[0][i].Documents.length;
            }
            if (documentLength > 0) {
                //                //alert(d[0][i].Documents.length);
                for (r = 0; r < documentLength; r++) {
                    currentDocument = d[0][i].Documents[r];
                    fileURL = currentDocument.Url;
                    docDesc = currentDocument.DocumentDescription;
                    $('.' + target + ' .ProductManualOption option:last').after("<option onclick=\"window.open('" + fileURL + "');\">" + docDesc + "</option>");
                    //alert(fileName + ": " + docDesc);
                }
            } else {
                $('.' + target + ' .downloadManuals').hide();
            }
            /*******/
            i++;
        });
    });
}

function wishListProducts(d, target) {
    var row = '';                                                   // Initialize the content area.
    $.get("/html/lists/WishListRow.htm", function(contents) {
        i = 0;
        $(d[0]).each(function() {                                   // Cycle through and render listings
            ciRowBlock(d[0][i].ProductKey);
            row = contents;                                         // Assign the template as a row
            $('.' + target).append(row);                              // Append the row (held in the 'target' variable)
            if (i % 2 == 1) $('.' + target + ' .product:last').addClass('odd');     // Begin injecting JSON data & zebra rows
            $('.' + target + ' .product_image:last').attr('src', d[0][i].ProductImagePath);
            $('.' + target + ' .product_image:last').attr('alt', d[0][i].ProductImageAltText);
            $('.' + target + ' .product_title:last').attr('href', d[0][i].ProductURL);
            $('.' + target + ' .product_title:last').html(d[0][i].DisplayName);
            $('.' + target + ' .moreInfo a:last').attr('href', d[0][i].ProductURL);
            $('.' + target + ' .removewishList a:last').attr('href', 'javascript:removeWishlist("' + d[0][i].WishListId + '","' + d[0][i].ProductKey + '");');
            $('.' + target + ' .buyNow a:last').attr('href', "javascript:manu_CDLink('blackanddecker','" + d[0][i].ProductKey + "',null,null,null);");
            $('.' + target + ' .product_description:last').html(d[0][i].ShortDescription);

            var ratingHtml = '';

            if (d[0][i].PluckRatingAverage) {
                var stars = '';
                var rating = new Number(d[0][i].PluckRatingAverage);

                for (var s = 1; s < rating; s++) {
                    stars += '*';
                }

                ratingHtml += stars;
            }

            if (d[0][i].NumberOfReviews) {
                ratingHtml += ' ' + d[0][i].NumberOfReviews + ' Reviews';
            }
            $('.' + target + ' .blogRating:last').html(ratingHtml);
            if (d[0][i].MSRP) $('.' + target + ' .product_msrp:last').html(d[0][i].MSRP);
            else $('.' + target + ' .msrp:last').hide();
            i++;                                                    // Iterate
        });
    });
}

function listSearch(d, target) {
    var row = '';
    if (!d[0].Error) {
        $.get("/html/lists/SearchItemRow.htm", function(contents) {
            i = 0;
            $(d).each(function() {     
                                             // Cycle through and render listings
                ciRowBlock(d[i].ProductKey);
                row = contents;                                         // Assign the template as a row
                
                $('.' + target).append(row);                              // Append the row (held in the 'target' variable)
                if (i % 2 == 1) $('.' + target + ' .searchItem:last').addClass('odd');     // Begin injecting JSON data & zebra rows
                if (d[i].ItemImg) {
                    //$('.' + target + ' .page_image:last').attr('href', d[i].Url);
                    $('.' + target + ' .page_image:last').attr('src', d[i].ItemImg);
                    $('.' + target + ' .page_image:last').attr('alt', d[i].Title);
                }
                else $('.' + target + ' .prodImg:last').hide();
                $('.' + target + ' .page_title:last').attr('href', d[i].Url);
                $('.' + target + ' .page_title:last').html(d[i].Title);
                $('.' + target + ' .page_summary:last').html(d[i].Summary);
                $('.' + target + ' .page_url:last').attr('href', d[i].Url);
                $('.' + target + ' .page_url:last').html(d[i].Url);

                if (d[i].ProductKey) {
                    $('.' + target + ' .page_link:last').attr('href', d[i].Url);
                    $('.' + target + ' .prod_wishlist a:last').attr('id', 'wishListItem' + i);
                    $('.' + target + ' .prod_wishlist a:last').attr('href', 'javascript:createWishlist("' + d[i].ProductKey + '", "wishListItem' + i + '");');
                    $('.' + target + ' .buyNow a:last').attr('href', "javascript:manu_CDLink('blackanddecker','" + d[i].ProductKey + "',null,null,null);");
                }
                else {
                    $('.' + target + ' .page_link:last').hide();
                    $('.' + target + ' .wishList:last').hide();
                    $('.' + target + ' .buyNow:last').hide();
                }
                if (d[i].MSRP) $('.' + target + ' .product_msrp:last').html(d[i].MSRP);
                else $('.' + target + ' .msrp:last').hide();

                i++;                                                    // Iterate
            });
        });
    } else {
        $('.' + target).html("<div><h3>No Search Results Found.</h3></div>");
    }
}
//function listSearch(d, target) {
//    var row = '';
//    if (!d[0].Error) {
//        $.get("/html/lists/SearchItemRow.htm", function(contents) {
//            i = 0;
//            $(d).each(function() {                                      // Cycle through and render listings
//                ciRowBlock(d[i].ProductKey);
//                row = contents;                                         // Assign the template as a row
//                $('.' + target).append(row);                              // Append the row (held in the 'target' variable)
//                if (i % 2 == 1) $('.' + target + ' .searchItem:last').addClass('odd');     // Begin injecting JSON data & zebra rows
//                if (d[i].ItemImg) {
//                    $('.' + target + ' .page_image:last').attr('src', d[i].ItemImg);
//                    $('.' + target + ' .page_image:last').attr('alt', d[i].Title);
//                    $('.' + target + ' .moreInfo a:last').attr('href', d[i].Url);

//                }
//                if (d[i].ProductKey) {
//                    $('.' + target + ' .wishList a:last').attr('href', 'javascript:createWishlist("' + d[i].ProductKey + '");');
//                    $('.' + target + ' .buyNow a:last').attr('href', "javascript:manu_CDLink('blackanddecker','" + d[i].ProductKey + "',null,null,null);");

//                }
//                else $('.' + target + ' .page_image:last').hide();
//                $('.' + target + ' .page_title:last').attr('href', d[i].Url);
//                $('.' + target + ' .page_title:last').html(d[i].Title);
//                $('.' + target + ' .page_summary:last').html(d[i].Summary);
//                i++;                                                    // Iterate
//            });
//        });
//    } else {
//        $('.' + target).html("<div><h3>No Search Results Found.</h3></div>");
//    }
//}

