var product = null;
var showOnOnePage = true;
/** Retreiving product data **/
var isInitialLoad = true;
var initialProductCount = 0;
var isFiltered = false;
var tempSelectedColorCode = 0;
var selectedColorCode = 0;
var tempSelectedColor = '';
var selectedColor = "White" ;
var products;
var currentPage;
var countPages;
var PRODUCTS_PER_ROW = 3;
var PRODUCTS_PER_PAGE = 9;
var countProducts;
var pagingSpan;
var lastSort = 'alpha';
 // filter options
var minimumRoughInOptions;
var tankTypeFilterOptions;
var bowlShapeFilterOptions;
var flushingTechnologyFilterOptions;
var lastUpdatedFilterName;
var quickLookProduct;
var filteredResults;
var filteredCurrentProductList;
var currentColorCodes = null;
var currentTankTypes = null;
var currentBowlShapes = null;
var currentFlushingTechnologys = null;
var currentCoordinatingSuites = null;
var currentComfortHeight = null;
var currentAda = null;
var currentMinimumRoughIn = null;
var currentCompleteSolution = null;
var waterSavingsOptions = null;
var currentWaterSense = null;
var isCA = isCA;
var itemColor;
var fadeToiletModuleState = "out";
var loadedFromCookie = false;
var hasColorFromCookie = false;
var cookieSeparator = "";
var priceSlider_valueInternal = 0.0;
var priceSlider_valueInternal2 = 0.0;


function getTsCookie() {
    var cookiename = "tst_status";
    var cookiestring=""+document.cookie;
    var index1=cookiestring.indexOf(cookiename);
    if (index1==-1 || cookiename=="") return "";
    var index2=cookiestring.indexOf(';',index1);
    if (index2==-1) index2=cookiestring.length;
    return unescape(cookiestring.substring(index1+cookiename.length+1,index2));
}

function setTsCookie(value) {
    var tsValue = (value==null)? getTsValsToString() : value;
    var today = new Date();
    var expires = new Date(today.getTime() + 24 * 60 * 60 * 1000); // one day
    document.cookie	= "tst_status=" + escape(tsValue) + ";"
                    + " expires=" + expires.toGMTString() + ";"
                    + " path=/;";
}

function getTsValsToString() {
    var result = new StringBuffer();
    var otherCheckBoxes = $("input[name='Tank Type'], input[name='Bowl Shape'], input[name='Flushing Technology'], input[name='Minimum Rough In'], input[name='Comfort Height'], input[name='ADA Compliant'], input[name='Coordinating Suites']");
    var otherResult = "";
    var otherSeparator = "";
    var optsAreFiltered = false; var interesting = false;
    for (var i = 0; i < otherCheckBoxes.length; i++) {
        if (otherCheckBoxes[i].checked) {
            if (otherResult =="") { otherResult = "other="; }
            otherResult += otherSeparator + otherCheckBoxes[i].id;
            if (otherSeparator == "") { otherSeparator = "_"; }
        }
    }
    if (otherResult.indexOf("other=12") > -1 && otherResult.length < 11) {
        interesting = true;
    } else {
        optsAreFiltered = true;
    }
    if (priceSlider._valueInternal != priceList[0] || priceSlider._valueInternal2 != priceList[priceList.length - 1]) {
        result.append(getCookieSeparator() + "price=" + priceSlider._valueInternal + "_" +priceSlider._valueInternal2);
    }
    if (lastSort != "alpha") { result.append(getCookieSeparator() + "lastSort=" + lastSort); }
    if (tempSelectedColorCode != 0) { result.append(getCookieSeparator() + "color=" + selectedColor + "_" + tempSelectedColorCode); optsAreFiltered = true; }
    if ($("input[name=WaterSense]")[0].checked) { result.append(getCookieSeparator() + "waterSense=yes"); optsAreFiltered = true; }
    if ($("input[name=Complete Solution]")[0].checked) { result.append(getCookieSeparator() + "completeSolutions=yes"); optsAreFiltered = true; }
    if (cookieSeparator == "|") {
       result.append(getCookieSeparator() + "onePage=" + ((showOnOnePage) ? "yes":"no")); 
    }
    if (optsAreFiltered && otherResult.length > 0) {
        result.append(getCookieSeparator() + otherResult);
    }
    cookieSeparator = "";
    return result.toString();
}

function getCookieSeparator() {
    if (cookieSeparator=="") { cookieSeparator="|"; return ""; }
    return cookieSeparator;
}

function setTsDefaultsFromCookie() {
    var cval = getTsCookie();
    if (cval != null && cval.length > 0) {
        var cvalAr = cval.split("|");
        var wasFiltered = false;
        var hasRoughIn12 = false;
        var hasColor = false;
        for (var i=0; i<cvalAr.length; i++) {
            var myPairs = cvalAr[i].split("=");
            var myOption = myPairs[0];
            var myVal = myPairs[1];
            var myOpts = [];
            switch(myOption) {
                case "waterSense":
                    currentWaterSense = "Yes";
                    $("input[name=WaterSense]")[0].checked = true;
                    wasFiltered = true;
                    break;
                case "completeSolutions":
                    currentCompleteSolution = "Yes";
                    $("input[name=Complete Solution]")[0].checked = true;
                    wasFiltered = true;
                    break;
                case "price" :
                    myOpts = myVal.split("_");
                    if (myOpts.length == 2) {
                        minFilterPrice = myOpts[0];
                        maxFilterPrice = myOpts[1];
                    }
                    break;
                case "onePage":
                    showOnOnePage = (myVal=="yes");
                    break;
                case "lastSort" :
                    lastSort = myVal;
                    break;
                case "color":
                    if (myVal != null && myVal.length > 0) {
                        myOpts = myVal.split("_");
                        if (myOpts.length == 2 && myOpts[1] != 0) {
                            selectedColor = myOpts[0];
                            tempSelectedColor = selectedColor;
                            selectedColorCode = myOpts[1];
                            currentColorCodes = [];
                            colorCodeFilter.addColorCode(selectedColorCode);
                            hasColorFromCookie = true;
                            wasFiltered = true;
                        }
                    }
                    break;
                default:
                    if (myVal != null && myVal.length > 0) {
                        myOpts = myVal.split("_");
                        for (var j=0;j<myOpts.length;j++) {
                            var opt = $("#" + myOpts[j]);
                            if (opt && opt[0].type && opt[0].type == "checkbox") {
                                opt[0].checked = true; wasFiltered = true;
                                if (myOpts[j] =="Comfort-Height") {
                                    currentComfortHeight.push("Yes");
                                } else if (myOpts[j] =="ADA-Compliant") {
                                    currentAda.push("Yes");
                                } else if (myOpts[j] == "Coordinating-Suites") {
                                     currentCoordinatingSuites.push("Yes");
                                }
                            }
                            if (!hasRoughIn12 && myOpts[j] =="12") { hasRoughIn12 = true; }
                        }
                    }
                    break;
                
            }
        }
        if (wasFiltered && !hasRoughIn12) {
            $("#12")[0].checked = false;
        }
        isFiltered = wasFiltered;
        loadedFromCookie = wasFiltered;
        setTsCookie(""); // empty cookie
    }
}

if (!Array.prototype.filter)
{
    Array.prototype.filter = function(fun /*, thisp*/)
    {
        var len = this.length;
        if (typeof fun != "function") { throw new TypeError(); }
        var res = new Array();
        for (var i = 0; i < len; i++)
        {
            if (i in this)
            {
                var val = this[i]; // in case fun mutates this
                if (fun(val)) { res.push(val); }
            }
        }
        return res;
    };
}

if (!Array.prototype.indexOf)
{
    Array.prototype.indexOf = function(elt /*, from*/)
    {
        var len = this.length;

        var from = Number(arguments[1]) || 0;
        from = (from < 0)
                ? Math.ceil(from)
                : Math.floor(from);
        if (from < 0)
            from += len;

        for (; from < len; from++)
        {
            if (from in this &&
                this[from] === elt)
                return from;
        }
        return -1;
    };
}

function helpLayer(whichHelp)
{
    if (document.getElementById('tst-helper' + whichHelp).style.display == 'block' )
    {
        $("#entry").css("display", "none");
        document.getElementById('tst-helper' + whichHelp).style.display = 'none';
        $("#tst-opacity-layer").css("display", "none");
        filterResultsOpcty('off');
    }
    else
    {
        document.getElementById('tst-filter' + whichHelp).style.zIndex = 99;
        document.getElementById('tst-helper' + whichHelp).style.display = 'block';
        document.getElementById('tst-opacity-layer').style.display = 'block';
    }


}
//alert("made it here " + 1 )
function showHideFilter(whichFilter) {
    if (document.getElementById('tst-filters-' + whichFilter).style.display == 'none') {
        document.getElementById('tst-filters-' + whichFilter).style.display = 'block';
        document.getElementById('filter-arrow-' + whichFilter).src = '/common/images/nav-arrow-on.gif';
    } else {
        document.getElementById('tst-filters-' + whichFilter).style.display = 'none';
        document.getElementById('filter-arrow-' + whichFilter).src = '/common/images/nav-arrow.gif';
    }
}

function showHideSorting() {
    if (document.getElementById('sort-order-dropdown').style.display == 'block') {
        document.getElementById('sort-order-dropdown').style.display = 'none';
        document.getElementById('sort-order').style.backgroundColor = '#CAD7DE';
    } else {
        document.getElementById('sort-order-dropdown').style.display = 'block';
        document.getElementById('sort-order').style.backgroundColor = '#E2EBEF';
    }
}

function showSwatchInfo(whichSwatch, colorName) {
    document.getElementById('over-' + whichSwatch).style.display = 'block';
    document.getElementById('overCarat-' + whichSwatch).style.display = 'block';
    tempSelectedColor = colorName;
}

function hideSwatchInfo(whichSwatch) {
    $('#' + 'over-' + whichSwatch).html('');
    document.getElementById('over-' + whichSwatch).style.display = 'none';
    document.getElementById('overCarat-' + whichSwatch).style.display = 'none';
    tempSelectedColor = "";
}

function initFeaturedContentHeight() {
    if (document.getElementById('tst-opacity-layer')) {
        document.getElementById("tst-opacity-layer").style.height = eval(document.body.scrollHeight + 15) + "px";
        document.getElementById("tst-opacity-layer").style.width = document.body.scrollWidth + "px";
    }
}

var priceList;
var colorOptions;

var maxFilterPrice;
var minFilterPrice;
var maxGallonsPerFlush;
var minGallonsPerFlush;

function omnitureUpdate()
{
    s.linkTrackVars='prop39';

    s.prop39 =  (( currentTankTypes == null || currentTankTypes.length == 0 ) ? 'All' : currentTankTypes) + ':' +
                (( currentBowlShapes == null || currentBowlShapes.length == 0 ) ? 'All' : currentBowlShapes) + ':' +
                (( currentFlushingTechnologys == null || currentFlushingTechnologys.length == 0 ) ? 'All' : currentFlushingTechnologys) + ':' +
                (( selectedColor == null || selectedColor.length == 0 ) ? 'All' : selectedColor) + ':' +
                (( currentCoordinatingSuites == null || currentCoordinatingSuites.length == 0 ) ? 'No' : currentCoordinatingSuites) + ':' +
                (( currentComfortHeight == null || currentComfortHeight == '' ) ? 'No' : currentComfortHeight) + ':' + //  **** ISSUE *******
                (( minFilterPrice == null || minFilterPrice.length == 0 ) ? '0.00' : minFilterPrice) + '-' +
                (( maxFilterPrice == null || maxFilterPrice.length == 0 ) ? '0.00' : maxFilterPrice) + ':' +
                (( minGallonsPerFlush == null || minGallonsPerFlush.length == 0 ) ? '0.0' : minGallonsPerFlush) + '-' +
                (( maxGallonsPerFlush == null || maxGallonsPerFlush.length == 0 ) ? '0.0' : maxGallonsPerFlush) + ':' +
                (( currentMinimumRoughIn == null || currentMinimumRoughIn.length == 0 ) ? '0.0' : currentMinimumRoughIn) + ':' +
                (( currentWaterSense == null || currentWaterSense == '' ) ? 'No' : currentWaterSense) + ':' +
                (( currentCompleteSolution == null || currentCompleteSolution == '' ) ? 'No' : currentCompleteSolution) + ':' +
                (( currentComfortHeight == null || currentComfortHeight == '' )  ? 'No' : currentComfortHeight );

    s.tl(this,'o','selector.jsp');
}

function initSliders() {

    //   maxFilterPrice = parseFloat(priceList[0]);
    //   minFilterPrice = parseFloat(priceList[priceList.length - 1]);

    priceSlider = new Bs_Slider();
   // waterSavingsSlider = new Bs_Slider();

    /* ***PRICE SLIDER ***/
    priceSlider.arrowAmount = 50;
    priceSlider.width = 250;
    priceSlider.height = 16;
    priceSlider.imgDir = '';
    priceSlider.setBackgroundImage('images/bg-slider.gif', 'no-repeat');
    priceSlider.fieldName = 'slider2_start';
    priceSlider.minVal = parseFloat(priceList[0]);
    priceSlider.maxVal = parseFloat(priceList[priceList.length - 1]);
    priceSlider.valueInterval = 50;
    priceSlider.valueDefault = priceList[0];
    priceSlider.setSliderIcon('images/slider.gif', 12, 16);
    priceSlider.useInputField = 0;
    priceSlider.styleValueFieldClass = 'sliderInput';
    priceSlider.useSecondKnob = true;
    priceSlider.preventValueCrossing = true;
    priceSlider.wheelAmount = 0; //disable mouse wheeling cause we have 2 knobs.
    priceSlider.attachOnChange(function (priceSlider)
    {
        var priceSliderMaxValue = 0;
        if (isNaN(Number(priceSlider._valueInternal2).toFixed(2)))
        {
            priceSliderMaxValue = priceList[0];
        }
        else
        {
            priceSliderMaxValue = Number(priceSlider._valueInternal2).toFixed(2);
        }

        $("#priceRangeDiv").html('$ ' + Number(priceSlider._valueInternal).toFixed(2) + ' to $' + priceSliderMaxValue);
    });
    priceSlider.attachOnSlideEnd(function (priceSlider)
    {
        maxFilterPrice = priceSlider._valueInternal2;
        minFilterPrice = priceSlider._valueInternal;
        updateFilteredProductList("Price");
    });
    priceSlider.fieldName2 = 'slider2_end';
    priceSlider.minVal2 = parseFloat(priceList[0]);
    priceSlider.maxVal2 = parseFloat(priceList[priceList.length - 1]);
    priceSlider.valueInterval2 = .01;
    priceSlider.valueDefault2 = priceList[priceList.length - 1];
    priceSlider.setSliderIcon2('images/slider.gif', 12, 16);
    priceSlider.useInputField2 = 0;
    priceSlider.styleValueFieldClass2 = 'sliderInput';
    priceSlider.drawInto('priceSliderDiv');
    $('#priceRangeDiv').html('$' + Number(priceList[0]).toFixed(2) + ' to $' + Number(priceList[priceList.length - 1]).toFixed(2));  // initial price on load
    $('#priceFullRange').html('Full Range: $' + Number(priceList[0]).toFixed(2) + ' to $' + Number(priceList[priceList.length - 1]).toFixed(2));
}

/**
 * @param object sliderObj
 * @param int val (the value)
 * @param int newPos
 * @param int knobNo
 */
function bsSliderChange(sliderObj, val, newPos, knobNumber) {
    document.getElementById('slider1knob' + knobNumber).value = val;
}

function showDetails() {
    $("#prodDetails").fadeIn("250");
}

// initiate the fadeIn of opacity that sits underneath the tool, hit the callbacks
function showDim() {
    $("span.start").click(function () {
        elem = $("#dimLayer");
        checkWinHeight();
        elem.css("height", winH);
        elem.fadeIn("200", callbacks);
    });
}                                   

// function for showing the helper overlays
function showHelper() {
    $("span.helper").click(function() {
        // first: intiaite lightbox effect
        $("#helpDim").fadeIn("200");
        OpacAdjust($("#helpDim"), "200", 0.7);
		// next: this iteration ~ brutte force ~ show Bowl Shape helper. refactor later
        $("#helperContent").css("display", "block");
        $("#bowlShapeHelper").css({display:"block"});
        OpacAdjust($("#bowlShapeHelper"), "100", 1);
    });
}

function checkWinHeight() {
    winH = $(window).height();
    return winH;
}

function callbacks() {
    OpacAdjust($("#dimLayer"), "100", 0.7);
    showTst();
    showEnt();
    filterResultsOpcty('on');
}

function OpacAdjust(oaElem, oaTime, oaLevel) {
    // this is what you pass to this function: which element to work with, the timeframe in which to operate, and opacity level
    oaElem.fadeTo(oaTime, oaLevel);
}

function showTst() {
    $("#tstCanvas").css("display", "block");
    winH = parseInt($('#tstCanvas').css("height"));
    winH += 20;												// just make it so the bottom of selector tool is not flush up against the bottom of the browser screen
    $("#dimLayer").css("height", winH);
}

function showEnt() {
    $("#entry").css("display", "block");
    $("#entry img.entryArrow").css("display", "block");
}

function filterResultsOpcty(param) {
    // on
    if (param == 'on') {
        // for IE
        if ($.browser.msie) {
            $("#filteredResults *").css("filter", "alpha(opacity=20)");
        } else {
            // others
            $("#filteredResults").css("opacity", ".2");
        }
    } else {
        // off
        // for IE
        if ($.browser.msie) {
            $("#filteredResults *").css("filter", "alpha(opacity=100)");
			// IE was doing some weird over-bolding to the h4 after opacity was being turned off, so this is to adjust
            $("#filteredResults h4").css({fontFamily:"Verdana",letterSpacing:"0.4px", fontSize:"10px"});
        } else {
            // others
            $("#filteredResults").css("opacity", "1");
        }
    }
}

function swatch() {
    
    jQuery.fn.extend({
        check: function() {
            return this.each(function() {
                this.checked = true;
            });
        },
        uncheck: function() {
            return this.each(function() {
                this.checked = false;
            });
        }
    });
  
    $("#flushingTechnologyClear").bind("click", function() {
        // $("flushingTechnology").uncheck();
        $("input[name=Flushing Technology]").uncheck();
        updateFilteredProductList('Flushing Technology');
    }
            );

    $("#flushingTechnologyCheck").bind("click", function() {
        // $("flushingTechnology").uncheck();
        $("input[name=Flushing Technology]").check();
        updateFilteredProductList('Flushing Technology');
    }
            );

    $("#minimumRoughInClear").bind("click", function() {
        // $("flushingTechnology").uncheck();
        $("input[name=Minimum Rough In]").uncheck();
        updateFilteredProductList('Minimum Rough-In');
    }
            );

    $("#minimumRoughInCheck").bind("click", function() {
        // $("flushingTechnology").uncheck();
        $("input[name=Minimum Rough In]").check();
        updateFilteredProductList('Minimum Rough-In');
    }
            );

    setDefaultFilters();
}


function populateTextBoxes()
{
    // ** Tank Type
    var tankTypeHTML =

            '<table border="0" cellspacing="0" cellpadding="0" width="275">' +
            '<tbody>';

    for (var i = 0; i < tankTypeFilterOptions.length; i++)
    {
        if (tankTypeFilterOptions[i] != null)
        {
            if (i % 3 == 0)
            {
                tankTypeHTML = tankTypeHTML + '<tr>';
            }

            tankTypeHTML = tankTypeHTML +
                           '<td width="19" valign="top"> <input id="' + tankTypeFilterOptions[i] + '" type="checkbox" name="Tank Type" value="' + tankTypeFilterOptions[i] + '" onclick="updateFilteredProductList(\'' + tankTypeFilterOptions[i] + '\');"></td>' +
                           '<td valign="top" width="72"><label for="' + tankTypeFilterOptions[i] + '">' + tankTypeFilterOptions[i] + '</label></td>';

            if (( i % 3 == 0 && i > 0 ) || (i + 1 == tankTypeFilterOptions.length )) //if last row or third row
            {

                if (( i + 1 == tankTypeFilterOptions.length ) && (( (i + 1) % 3 ) != 0 && i > 0  ))
                    tankTypeHTML = tankTypeHTML + '<td width="91" colspan="2">&nbsp;</td>';

                tankTypeHTML = tankTypeHTML + '</tr>';
               // if last row and  not visiable by 3
            }

        }
    }

    tankTypeHTML = tankTypeHTML + '</tbody></table>';

    $("#tankTypeForm").html(tankTypeHTML);

    // ** Bowl Shape
    var bowlShapeHTML =
            '<table border="0" cellspacing="0" cellpadding="0" width="275">' +
            '<tbody>';

    var bowlShapeCellCount = 1;
    for (var i = 0; i < bowlShapeFilterOptions.length; i++)
    {
        if (bowlShapeFilterOptions[i] != null)
        {
            if (i % 3 == 0)
            {
                bowlShapeCellCount = 1;
                bowlShapeHTML = bowlShapeHTML + '<tr>';
            }

            bowlShapeHTML = bowlShapeHTML +
                            '<td width="19" valign="top"> <input id="' + bowlShapeFilterOptions[i].replace(" ", "-") + '" type="checkbox" name="Bowl Shape" value="' + bowlShapeFilterOptions[i] + '" onclick="updateFilteredProductList(\'Bowl Shape\');"></td>' +
                            '<td valign="top" width="72"><label for="' + bowlShapeFilterOptions[i].replace(" ", "-") + '">' + bowlShapeFilterOptions[i] + '</label></td>';

            if (bowlShapeCellCount == 3 || (i + 1 == bowlShapeFilterOptions.length )) //if last row or third row but not the first record
            {
                // loop for each empty space
                if (( i == bowlShapeFilterOptions.length - 1 ) && (( (i + 1) % 3 ) != 0 && i > 0  ))
                {
                    bowlShapeHTML = bowlShapeHTML + '<td width="91" colspan="2">&nbsp;</td>';
                }

                if (bowlShapeCellCount == 3)
                {
                    bowlShapeHTML = bowlShapeHTML + '</tr>';
                }
                bowlShapeCellCount ++;
               // if last row and  not visiable by 3
            }

        }
    }

    bowlShapeHTML = bowlShapeHTML + '</tbody></table>';

    $("#bowlShapeForm").html(bowlShapeHTML);

   //** Flushing Technology

      var flushingTechnologyCatCombo;
      var flushingTechnologyCellCount = 0;
      var flushingTechnologyHTML =
              '<table border="0" cellspacing="0" cellpadding="0" width="275">' +
              '<tbody>';

      var priorFlushingTechnologyCatCombo;
      // Add to java. . .
      for (var i = 0; i < flushingCategoryFilterOptions.length; i++)
      {
          //Add a new row

          if (flushingTechnologyFilterOptions[i] != null)
          {
             flushingTechnologyCatCombo = flushingCategoryFilterOptions[i].split("|")[0];
              if  ( priorFlushingTechnologyCatCombo != flushingTechnologyCatCombo )
              {
                 flushingTechnologyHTML = flushingTechnologyHTML + '<tr><td colspan="3"><h3>' + flushingTechnologyCatCombo + '</h3></td></tr>'
                 flushingTechnologyCellCount = 0; // new row;
              }
              if ( flushingTechnologyCellCount % 3 == 0 )
              {
                  flushingTechnologyHTML = flushingTechnologyHTML + '<tr>';
                  flushingTechnologyCellCount = 0;
              }

              flushingTechnologyHTML = flushingTechnologyHTML +
                                       '<td width="19" valign="top"> <input id="' + flushingCategoryFilterOptions[i].split("|")[1].replace(" ", "-") + '" type="checkbox" name="Flushing Technology" value="' + flushingCategoryFilterOptions[i].split("|")[1]  + '" onclick="updateFilteredProductList(\'Flushing Technology\');"></td>' +
                                       '<td valign="top" width="72"><label for="' + flushingCategoryFilterOptions[i].split("|")[1].replace(" ", "-")  + '">' + flushingCategoryFilterOptions[i].split("|")[1]  + '</label></td>';

              if (flushingTechnologyCellCount == 3 || ( i + 1 == flushingTechnologyFilterOptions.length )) //if last row or third row
              {
                  if (( i + 1 == flushingTechnologyFilterOptions.length ) && (( (i + 1) % 3 ) != 0 && i > 0  ))
                      flushingTechnologyHTML = flushingTechnologyHTML + '<td width="91" colspan="2">&nbsp;</td>';

                  if ( flushingTechnologyCellCount % 3 == 0)
                  {
                      flushingTechnologyHTML = flushingTechnologyHTML + '</tr>';
                  }
              }
          }
              flushingTechnologyCellCount ++;
              priorFlushingTechnologyCatCombo = flushingTechnologyCatCombo;
      }

      flushingTechnologyHTML = flushingTechnologyHTML + '</tbody></table>';
         //alert(flushingTechnologyHTML);
      $("#flushingTechnologyForm").html(flushingTechnologyHTML);

}
function reset()
{
    loadedFromCookie = false; hasColorFromCookie = false; 
    currentWaterSense = null;
    currentColorCodes = null;
    currentTankTypes = null;
    currentBowlShapes = null;
    currentFlushingTechnologys = null;
    currentCoordinatingSuites = null;
    currentComfortHeight = null;
    currentAda = null;
    currentMinimumRoughIn = null;
    currentCompleteSolution = null;
    selectedColor = "White";
    selectedColorCode = 0;
    // currentWaterSense = [];
    currentColorCodes = [];
    currentTankTypes = [];
    currentBowlShapes = [];
    currentFlushingTechnologys = [];
    currentCoordinatingSuites = [];
    currentComfortHeight = [];
    currentAda = [];
    currentMinimumRoughIn = [];
    currentCompleteSolution = [];
    priceSlider.setValue(priceList[0], 1);
    priceSlider.setValue(priceList[priceList.length - 1], 2);
    $("#currentColor").html(selectedColor);
 //   waterSavingsSlider.setValue(waterSavingsOptions[0], 1);
 //   waterSavingsSlider.setValue(waterSavingsOptions[waterSavingsOptions.length - 1 ], 2);
    setDefaultFilters();
    $("input").removeAttr("disabled");
}

function displayProdSwatchInfo(colorName, colorCode)
{
    // $("#currentColor").html( selectedColor );
    colorCodeFilter.addColorCode(colorCode);
    updateFilteredProductList("Colors");
}

function getItemByProductId(productId, selectedColorCode)
{

    var product = findProduct(productId) ;
    var productItem = '';
      //alert( ' product id ' + productId + ' color code '+ selectedColorCode )
    for (var i = 0; i < product.productItems.length; i++)
    {
        //alert ( productItem.colorFinishCode + ' ' + selectedColorCode)
        if (productItem.colorFinishCode == selectedColorCode)
        {
            //alert("found product item")
            productItem = product.productItems[i];
        }
    }

    return productItem;
}

function getItemByColor(productId)
{

    var product = findProduct(productId) ;
    var productItem = '';
        //alert( ' product id: ' + productId + ' color code '+ selectedColorCode )
    for (var i = 0; i < product.productItems.length; i++)
    {
        //alert ( product.productItems[i].colorFinishCode + ' ' + selectedColorCode)
        if (product.productItems[i].colorFinishCode == selectedColorCode)
        {
            productItem = product.productItems[i];
        }
    }

    return productItem;
}


function getListPrice(price, brandName, quickLook)
{
    var priceMessageSuffix = " <span class=\"andup norm\">and up</span>";
    if (isCA) {
        priceMessageSuffix = " <span class=\"andup norm\">CAD and up</span>";
    }
    var newPrice = "";

            //alert("Is QuickLook? " + quickLook );
    if (quickLook == null)
    {
        // alert("This is a Quick Look " + quickLook + " " + price);
        newPrice = " and up";
        priceMessagePrefix = "List price: $";
    }
    else
    {
        priceMessagePrefix = "$";
    }
    if (price != null && price.indexOf("Note") < 0)
    {
        if (isCA) {
            newPrice = priceMessagePrefix + price + priceMessageSuffix;
        } else {
            newPrice = priceMessagePrefix + price + priceMessageSuffix;
        }
    }
    else
    {
        if (price == "") {
            newPrice = "Please contact dealer for pricing";
        }
        else
        {
            if (price == ("Note 1")) {
                newPrice = "Please contact your " + brandName + " distributor for this product's pricing information.";
            }
            if (price == "Note 2") {
                newPrice = "This product is only available regionally, please contact your " + brandName + " distributor for more information.";
            }
            if (price == "Note 3") {
                newPrice = "This product is only available regionally, please contact your " + brandName + " distributor for more information.";
            }
            if (price == "Note 4") {
                newPrice = "This product is only available for job business only, please contact your " + brandName + " distributor for more information.";
            }
            if (price == "Note 5") {
                newPrice = "This product is only available for job business only, please contact your " + brandName + " distributor for more information.";
            }
        }
    }

    return newPrice;
}


function displayItemQuickLookInfo(productId, itemId)
{

    //TODO: price
    var product = findProduct(productId);
    var productItem = "";
    var quickLookImage;

    for (var i = 0; i < product.productItems.length; i++)
    {
        // alert(product.productItems[i] + ' ' + itemId)
        if (product.productItems[i].itemId == itemId)
        {
            productItem = product.productItems[i];

            if (productItem.jpgItemImage == null || productItem.jpgItemImage == "")
            {
                quickLookImage = product.jpgPhotoName;

            } else
            {
                quickLookImage = productItem.jpgItemImage;
            }
        }
    }
     //Updating quick look price
    var price = getListPrice(productItem.price, product.brandName, null);
    if (isCA) {
        price = getListPrice(productItem.listPriceAltCurrency, product.brandName, null);
    }
    $('#quickLookPrice').html(price);
    $('#quickLookImg').html('');
    $('#quickLookImg').html('<div id="quickLookImg"><img src="/onlinecatalog/125x160/' + quickLookImage + '" width="125px" height="160px" alt="" title="product image" border="0" /></div>');

    var selectedColorPrice = getListPrice(productItem.price, product.brandName, "Yes");
    if (isCA) {
        selectedColorPrice = getListPrice(productItem.listPriceAltCurrency, product.brandName, "Yes");
    }
    $("#selectedColor").html("Select " + productItem.colorFinishName + ", " + selectedColorPrice); //Populate quick look details

}

function setDefaultFilters() // Set on load and reset
{
    if (!loadedFromCookie) {
        $(".filters").css("background-color", "#E2EBEF");
        $("input[name=WaterSense]").uncheck();
        $("input[name=Flushing Technology]").uncheck();
        $("input[name=Bowl Shape]").uncheck();
        $("input[name=Coordinating Suites]").uncheck();
        $("input[name=Complete Solution]").uncheck();
        $("input[name=Minimum Rough In]").uncheck();
        $("input[name=Comfort Height]").uncheck();
        $("input[name=ADA Compliant]").uncheck();
        $("input[id=One-piece]").uncheck();
        $("input[id=Two-piece]").uncheck();
        $("input[id=12]").check();
        $("input[name=WaterSense]").uncheck();
        minFilterPrice = parseFloat(priceList[0]);
        maxFilterPrice = parseFloat(priceList[priceList.length - 1]);
        if (!hasColorFromCookie) { $("span.andup").show(); }
    }
    updateFilteredProductList("");
    loadedFromCookie = false; hasColorFromCookie = false;  // so works next time
}

var colorCodeFilter = function() {

    currentColorCodes = ['0'];   // set the default values

    var addColorCode = function(colorCode) {

        currentColorCodes.push(colorCode);
        tempSelectedColorCode = colorCode;

    }
    var removeColorCode = function(colorCode) {
        //alert('remove color code.' + colorCode);
        currentColorCodes.pop(colorCode);

    }
    var isColorCode = function(element, index, array) {
        var colorAvailable;

        for (i = 0; i < element.colorOptions.length; i++)
        {
            colorAvailable = false;
            if (element.colorOptions[i] == currentColorCodes[0])
            {
                colorAvailable = true;
                break;
            }
        }

                      // alert ( (colorAvailable) +  ' ' + element.colorOptions.toString() + '  input color code:' +  currentColorCodes[0]);
        return colorAvailable;

    }

    var getCurrentColorCode = function() {
        if (currentColorCodes != null && currentColorCodes.length > 0) {
            return currentColorCodes[0];
        }
        return 0;
    }

    var filterColorCodes = function(prods) {

        return prods.filter(isColorCode);
    }

    return {
        addColorCode: addColorCode,
        removeColorCode: removeColorCode,
        filterColorCodes : filterColorCodes,
        getCurrentColorCode : getCurrentColorCode
    }
}();

var tankTypeFilter = function() {
    currentTankTypes = [];   // set the default values

    var addTankType = function(tankType) {

        currentTankTypes.push(tankType);
    }
    var removeTankType = function(tankType) {

        currentTankTypes.pop(tankType);

    }
    var isTankType = function(element, index, array) {

        return currentTankTypes.indexOf(element.tankType) != -1
    }

    var filterTankTypes = function(prods) {
        //alert(isTankType);
        return prods.filter(isTankType);
    }

    return {
        addTankType: addTankType,
        removeTankType: removeTankType,
        filterTankTypes : filterTankTypes
    }
}();

var bowlShapeFilter = function() {
    currentBowlShapes = [];   // set the default values

    var addBowlShape = function(bowlShape) {
        currentBowlShapes.push(bowlShape);
    }
    var removeBowlShape = function(bowlShape) {
        currentBowlShapes.pop(bowlShape);
    }
    var isBowlShape = function(element, index, array) {
        if (currentBowlShapes == null) { return true; }
        for (var i=0; i < currentBowlShapes.length; i++) {
            if (currentBowlShapes[i].replace("-", " ").indexOf(element.bowlShape) == 0) {
                return true;
            }
        }
        return false;
    }

    var filterBowlShapes = function(prods) {
        return prods.filter(isBowlShape);
    }

    return {
        addBowlShape: addBowlShape,
        removeBowlShape: removeBowlShape,
        filterBowlShapes : filterBowlShapes
    }
}();


var flushingTechnologyFilter = function() {

    currentFlushingTechnologys = [];   // set the default values

    var addFlushingTechnology = function(flushingTechnology) {
        currentFlushingTechnologys.push(flushingTechnology);
    }
    var removeFlushingTechnology = function(flushingTechnology) {
        currentFlushingTechnologys.pop(flushingTechnology);
    }
    var isFlushingTechnology = function(element, index, array) {
        if (currentFlushingTechnologys == null) { return true; }
        for (var i=0; i < currentFlushingTechnologys.length; i++) {
            if (currentFlushingTechnologys[i].replace("-", " ").indexOf(element.flushingTechnology) == 0) {
                return true;
            }
        }
        return false;
    }

    var filterFlushingTechnologys = function(prods) {
        return prods.filter(isFlushingTechnology);
    }

    return {
        addFlushingTechnology: addFlushingTechnology,
        removeFlushingTechnology: removeFlushingTechnology,
        filterFlushingTechnologys : filterFlushingTechnologys
    }
}();

var coordinatingSuitesFilter = function() {

    currentCoordinatingSuites = [];   // set the default values

    var addCoordinatingSuites = function(coordinatingSuites) {
        currentCoordinatingSuites.push(coordinatingSuites);
    }
    var removeCoordinatingSuite = function(coordinatingSuite) {
        currentCoordinatingSuites.pop(coordinatingSuite);
    }
    var isCoordinatingSuite = function(element, index, array) {
        return currentCoordinatingSuites.indexOf(element.coordinatingSuites) != -1
    }

    var filterCoordinatingSuites = function(prods) {
        return prods.filter(isCoordinatingSuite);
    }

    return {
        addCoordinatingSuites: addCoordinatingSuites,
        removeCoordinatingSuite: removeCoordinatingSuite,
        filterCoordinatingSuites : filterCoordinatingSuites
    }
}();

var comfortHeightFilter = function() {
    currentComfortHeight = [];   // set the default values

    var addComfortHeight = function(comfortHeight) {

        currentComfortHeight.push(comfortHeight);

    }
    var removeComfortHeight = function(comfortHeight) {

        currentComfortHeight.pop(comfortHeight);

    }
    var isComfortHeight = function(element, index, array) {

        return currentComfortHeight.indexOf(element.aDACompliant) != -1
    }

    var filterComfortHeight = function(prods) {

        return prods.filter(isComfortHeight);
    }

    return {
        addComfortHeight: addComfortHeight,
        removeComfortHeight: removeComfortHeight,
        filterComfortHeight : filterComfortHeight
    }
}();

var adaFilter = function() {
    currentAda = [];   // set the default values

    var addAda = function(ada) {
        currentAda.push(ada);
    }
    var removeAda = function(ada) {
        currentAda.pop(ada);
    }
    var isAda = function(element, index, array) {
        return currentAda.indexOf(element.aDACompliant) != -1
    }

    var filterAda = function(prods) {
        return prods.filter(isAda);
    }

    return {
        addAda: addAda,
        removeAda: removeAda,
        filterAda : filterAda
    }
}();


/**var adaFilter = function() {

    var isAda = function(element, index, array)
    {
        //alert(element.waterSense  + ' element > current ' + currentWaterSense );
        return element.aDACompliant == currentAda;
    }

    var filterAda = function(prods) {

        return prods.filter(isAda);
    }

    return {
        filterAda : filterAda
    }
}(); **/



var minimumRoughInFilter = function() {
    currentMinimumRoughIn = [];   // set the default values

    var addMinimumRoughIn = function(minimumRoughIn) {
        currentMinimumRoughIn.push(minimumRoughIn);
    }
    var removeMinimumRoughIn = function(minimumRoughIn) {
        minimumRoughInCheckBoxes.pop(minimumRoughIn);
    }

    var isMinimumRoughIn = function(element, index, array) {
        for (var i = 0; i < currentMinimumRoughIn.length; i++)
        {
            if (element.minimumRoughIn != null && element.minimumRoughIn.indexOf("|" + currentMinimumRoughIn[i]) > -1)
            {
                return true;
            }
        }
        return false;
    }

    var filterMinimumRoughIn = function(prods) {
        return prods.filter(isMinimumRoughIn);
    }

    return {
        addMinimumRoughIn: addMinimumRoughIn,
        removeMinimumRoughIn: removeMinimumRoughIn,
        filterMinimumRoughIn : filterMinimumRoughIn
    }
}();

var completeSolutionFilter = function() {
    currentCompleteSolution = [];   // set the default values

    var addCompleteSolution = function(completeSolution) {
        currentCompleteSolution.push(completeSolution);

    }
    var removeCompleteSolution = function(completeSolution) {
        currentCompleteSolution.pop(completeSolution);
    }
    var isCompleteSolution = function(element, index, array) {
        return currentCompleteSolution.indexOf(element.completeSolution) != -1
    }

    var filterCompleteSolution = function(prods) {

        return prods.filter(isCompleteSolution);
    }

    return {
        addCompleteSolution: addCompleteSolution,
        removeCompleteSolution: removeCompleteSolution,
        filterCompleteSolution : filterCompleteSolution
    }
}();


var priceFilter = function() {


    var isPriceValid = function(element, index, array)
    {

        var productItem = getItemByColor(element.parentItemId)
        var itemPrice = productItem.price;
        if (isCA) {
            itemPrice = productItem.listPriceAltCurrency;
        }

        // alert('element price: ' + productItem.price  + ' min price: ' + minFilterPrice + ' max price: ' + maxFilterPrice + ' '  + (productItem.price >= minFilterPrice &&  productItem.price <= maxFilterPrice) );
        return parseFloat(itemPrice) >= parseFloat(minFilterPrice) && parseFloat(itemPrice) <= parseFloat(maxFilterPrice);
    }

    var filterPrice = function(prods) {

        return prods.filter(isPriceValid);
    }

    return {
        filterPrice : filterPrice
    }
}();

/**
var waterSavingsFilter = function() {

    var isWaterSavingsValid = function(element, index, array)
    {
        //alert("products gallon per flush: " + element.gallonsPerFlush + ' min: ' + minGallonsPerFlush + ' max: ' + maxGallonsPerFlush + (element.gallonsPerFlush >= minGallonsPerFlush && element.gallonsPerFlush <= maxGallonsPerFlush));
        return element.gallonsPerFlush >= minGallonsPerFlush && element.gallonsPerFlush <= maxGallonsPerFlush;
    }

    var filterWaterSavings = function(prods) {

        return prods.filter(isWaterSavingsValid);
    }

    return {
        filterWaterSavings : filterWaterSavings
    }
}();
**/

var waterSenseFilter = function() {

    var isWaterSenseValid = function(element, index, array)
    {
        //alert(element.waterSense  + ' element > current ' + currentWaterSense );
        return element.waterSense == currentWaterSense;
    }

    var filterWaterSense = function(prods) {

        return prods.filter(isWaterSenseValid);
    }

    return {
        filterWaterSense : filterWaterSense
    }
}();


function findProduct(parentItemId)
{
    for (var countProducts = 0; countProducts < initialProducts.length; countProducts++)
    {
        if (initialProducts[countProducts].parentItemId == parentItemId)
            return  initialProducts[countProducts];
    }
}

function loadColorOptions()
{
    var warmImageHTML = "";
    var coolImageHTML = "";
    var whiteImageHTML = "";
    var COLOR_SWATCH_PRODUCT = "12138702";  
    var colorSwatchProduct = "";

    for (var i = 0; i < colorOptions.length; i++)
    {
        for (var countProducts = 0; countProducts < initialProducts.length; countProducts++)
        {
            itemColor = colorOptions[i];

            if (initialProducts[countProducts].parentItemId == COLOR_SWATCH_PRODUCT) // don't need to hit each time
            {

                colorSwatchProduct = initialProducts[countProducts];
                    // alert (colorSwatchProduct);

                for (var countItems = 0; countItems < colorSwatchProduct.productItems.length; countItems++)
                {
                    //alert (itemColor.colorFinishCode  + ' compare ' + colorSwatchProduct.productItems[countItems].colorFinishCode)
                    if (itemColor.colorFinishCode == colorSwatchProduct.productItems[countItems].colorFinishCode)
                    {
                        var toiletColorJPG = colorSwatchProduct.productItems[countItems].jpgItemImage;
                        var toiletColorName = colorSwatchProduct.productItems[countItems].colorFinishName;
                    }
                }

                break;
            }
        }

        var imgSwatchHTML = '<span class="color-swatch-box"><div class="color-swatch" onmouseover="showSwatchInfo(\'' + toiletColorJPG + i + '\',' + '\'' + toiletColorName + '\');" onmouseout="hideSwatchInfo(\'' + toiletColorJPG + i + '\');"><img id="' + itemColor.colorFinishCode + '" onclick="currentColorCodes = []; colorCodeFilter.addColorCode(this.id); updateFilteredProductList(\'Colors\')" class="colorSwatch" name="colorSwatch" src="/common/images/colors/50x50/' + itemColor.gifFileSwatch + '" alt="" border="0" name="" width="29" height="29" /><img src="images/bg-popupColorBottom.png" width="149" height="12" alt="" border="0" id="overCarat-' + toiletColorJPG + i + '" class="color-popupCarat" /></div><div id="over-' + toiletColorJPG + i + '" class="color-popup"><img src="/onlinecatalog/125x160/' + toiletColorJPG + '" width="125" height="160" /><div class="color-popup-name">' + toiletColorName + '</div></div></span>';

        if (colorOptions[i].colorFamily != null && colorOptions[i].colorFamily.trim() == "Warm Colors")
        {
            warmImageHTML = warmImageHTML + imgSwatchHTML;
        }
        else if (colorOptions[i].colorFamily != null && colorOptions[i].colorFamily.trim() == "Cool Colors")
        {
            coolImageHTML = coolImageHTML + imgSwatchHTML;
        }
        else if (colorOptions[i].colorFamily != null && colorOptions[i].colorFamily.trim() == "Whites & Neutrals")
        {
            whiteImageHTML = whiteImageHTML + imgSwatchHTML;
        }

    }

    $("#cool").html(coolImageHTML);
    $("#warm").html(warmImageHTML);
    $("#white").html(whiteImageHTML);
}


function priceArraySort(a, b)
{
	if((a.indexOf('Note')>=0) ||(b.indexOf('Note')>=0)){
		return 0;//ignore Note as price, if not ignored causes a Not a number exception. if put at front or end of the list causes page to stop showing any results.
	}else{
     
	return (a - b); //causes an array to be sorted numerically and ascending
	}
		
}

/*function waterSavingsArraySort(a, b)
{
    var x = parseInt(a);
    var y = parseInt(b);
    return ((x < y) ? -1 : ((x > y) ? 1 : 0)); //causes an array to be sorted numerically and ascending
}
*/

function sortProducts(typeOfSort)
{
    lastSort = typeOfSort;
    var sortedProducts;

    if (filteredCurrentProductList.length == 0)
    {
        $("#sortDiv").css("display", "none");
        return;
    }
    else if (typeOfSort == 'model')
    {
        sortedProducts = filteredCurrentProductList.sort(function (a, b) {
            var x = a.parentItemNumber.toLowerCase();
            var y = b.parentItemNumber.toLowerCase();
            return ((x < y) ? -1 : ((x > y) ? 1 : 0));
        });
    }
    else if (typeOfSort == 'catalog')
    {
        sortedProducts = filteredCurrentProductList.sort(function (a, b) {
            var x = a.catalogPage.toLowerCase();
            var y = b.catalogPage.toLowerCase();
            return ((x < y) ? -1 : ((x > y) ? 1 : 0));
        });
    }

    else if (typeOfSort == 'price')
    {
        sortedProducts = filteredCurrentProductList.sort(function (a, b) {
            var x = parseInt(a.priceArray[0]);
            var y = parseInt(b.priceArray[0]);
            if (isCA) {
                x = parseInt(a.priceArrayAltCurrency[0]);
                y = parseInt(b.priceArrayAltCurrency[0]);
            }
            return ((x < y) ? -1 : ((x > y) ? 1 : 0));
        });
    }
    else if (typeOfSort == 'alpha')
    {
        sortedProducts = filteredCurrentProductList.sort(function (a, b) {
            if (a.thumbDesc != null) {
                var x = a.description.toLowerCase();
                var y = b.description.toLowerCase();
                return ((x < y) ? -1 : ((x > y) ? 1 : 0));
            }
        });
    }

    calculatePages(sortedProducts);
    pageProducts(1, sortedProducts);

    // $("#sortDiv").css("display", "none");
}


var quickLookWrite = '<div id="prodDetails">' +
                     '<div id="pdmMid">' +
                     '<div id="qlContent" class="clearfix">' +
                     '<div id="toiletDetails">' +
                     '<img src="/onlinecatalog/selector/images/placeholder125_160.gif" width="125" height="160" alt="" title="" border="0" />' +
                     '</div>' +
                     '<div id="toiletTabs">' +
                     '<img class="close" id="ent" src="/onlinecatalog/selector/images/close.gif" width="13" height="13" alt="Close" title="Close" border="0" />' +
                     '<div id="tabs-holder">' +
                     '<div class="tab" id="productTab">Product Description</div>' +
                     '<div class="tab" id="colorsTab">Colors</div>' +
                     '</div>' +
                     '<div id="prodTabContent"></div>' +
                     '<div id="prodTabColorsContent" style="display:none">' +
                     '<div id="selectedColor"></div>' +
                     '<div class="colorGroup">' +
                     'White &amp; Neutrals<br />' +
                     '<div id = "whiteDetail"></div>' +
                     '</div>' +
                     '<div class="colorGroup">' +
                     '<div id="ql-coolColors">' +
                     'Cool Colors<br />' +
                     '<div id="coolDetail"></div>' +
                     '</div>' +
                     '<div id="ql-warmColors">' +
                     'Warm Colors<br />' +
                     '<div id="warmDetail"></div>' +
                     '</div>' +
                     '</div>' +
                     '</div>' +
                     '</div>' +
                     '</div>' +
                     '</div>' +
                     '<div id="pdSahdowBottom"></div>' +
                     '</div>';

function populateQuickLookDetails(productItemNumber, whichRow)
{

    $("#prodDetails").css("display", "none");
    if (document.getElementById('prodDetails') != 'undefined') {
        $("#prodDetails").remove();
    }
    $("#productRow" + whichRow).prepend(quickLookWrite);

    var prodTabContent = "<ul>";
    var toiletDetails;
    var prodTabColorsContent;
    var productColorOption;
    var warmImageHTML = "";
    var coolImageHTML = "";
    var whiteImageHTML = "";
    $("#coolDetail").html("");
    $("#warmDetail").html("");
    $("#whiteDetail").html("");
    $("#prodTabContent").html("");
    // $("#prodTabColorsContent").html("");
    $("#ql-warmColors").html("");
    $("#ql-coolColors").html("");

    var product = findProduct(productItemNumber);


    if (!product)
        return;

    var listPrice = getListPrice(product.priceArray[0], product.brandName, null)
    if (isCA) {
        listPrice = getListPrice(product.priceArrayAltCurrency[0], product.brandName, null)
    }

    toiletDetails =
    '<div id="quickLookImg"><img src="/onlinecatalog/125x160/' + product.jpgPhotoName + '" width="125px" height="160px" alt="" title="product image" border="0" /></div>' +
    '<h4>' + product.thumbDesc + '</h4>' +
    '<span id="quickLookPrice">' + listPrice + '</span>' +
    '<ul><li class="link"><a href="../detail.jsp?from=thumb&frm=&module=Toilets&item=' + product.parentItemId + '&prod_num=' + product.parentItemNumber + '&section=2&category=13" target="_blank">See Product Details </a></li></ul>';
    $("#toiletDetails").html(toiletDetails);
    $("#toiletDetails").css("display", "block");
    $("#prodDetails").css("display", "block");
			// $("#selectedColor").innerHtml = "Select" + ", " +listPrice;

    // Populate Copy
//  alert("made it here " + 3 )
    if (product.copyArray)
    {
        for (var copyCount = 0; copyCount < product.copyArray.length; copyCount++)
        {
            prodTabContent = prodTabContent + "<li>" + product.copyArray[copyCount] + "</li>";
        }
    }
          //alert("number of product items")
    for (var i = 0; i < product.productItems.length; i++)
    {
        //alert("test")
        var productItem = product.productItems[i];
                  //alert(productItem)
        var imgSwatchHTML = '<img id= "productItem.gifFileSwatch" name="colorSwatch" src="/common/images/colors/50x50/' + productItem.gifFileSwatch +
                            '" alt="" border="0" name="" width="29" height="29" onclick="displayItemQuickLookInfo(' + product.parentItemId + ',' + productItem.itemId + ')">';

        prodTabColorsContent = '<div id="selectedColor"></div>' + prodTabColorsContent + imgSwatchHTML;

        if (productItem.colorFamily != null && productItem.colorFamily.trim() == "Warm Colors")
        {
            $('#ql-warmColors').html('Warm Colors<br /><div id="warmDetail"></div>');
            warmImageHTML = warmImageHTML + imgSwatchHTML;
        }
        else if (productItem.colorFamily != null && productItem.colorFamily.trim() == "Cool Colors")
        {
            $('#ql-coolColors').html('Cool Colors<br /><div id="coolDetail"></div>');
            coolImageHTML = coolImageHTML + imgSwatchHTML;
        }
        else if (productItem.colorFamily != null && productItem.colorFamily.trim() == "Whites & Neutrals")
        {
            whiteImageHTML = whiteImageHTML + imgSwatchHTML;
        }

    }


    $("#coolDetail").html(coolImageHTML);
    $("#warmDetail").html(warmImageHTML);
    $("#whiteDetail").html(whiteImageHTML);
    $("#prodTabContent").html(prodTabContent);
    $("#prodTabContent").css("display", "block");
    $("#prodTabColorsContent").css("display", "none");
    $("#productTab").bind("click", function()
    {
        $("#colorsTab").css("backgroundImage", "url('/onlinecatalog/selector/images/quickLook-tab-inactive.gif')");
        $("#productTab").css("backgroundImage", "url('/onlinecatalog/selector/images/quickLook-tab-active-prodDesc.gif')");
        $("#prodTabContent").css("display", "block");
        $("#prodTabColorsContent").css("display", "none");
    });

    $("#colorsTab").bind("click", function()
    {
        $("#colorsTab").css("backgroundImage", "url('/onlinecatalog/selector/images/quickLook-tab-active-colors.gif')");
        $("#productTab").css("backgroundImage", "url('/onlinecatalog/selector/images/quickLook-tab-inactive.gif')");
        $("#prodTabColorsContent").css("display", "block");
        $("#prodTabContent").css("display", "none");
        $("#selectedColor").css("display", "block");

    });
   	// close for Entry Panel via 'Product Details'
    $("#prodDetails img.close").click(function() {
        $("#prodDetails").remove();
    });

    var defaultQuickLookItem = getItemByColor(product.parentItemId)


    displayItemQuickLookInfo(product.parentItemId, defaultQuickLookItem.itemId);
}


function updateFilteredProductList(lastUpdatedFilter)
{
    $("#tst-loading-div").css("display", "block");
    fadeToiletModule("out");
    if (tempSelectedColor != "")
    {
        selectedColor = tempSelectedColor;
    }

    lastUpdatedFilterName = lastUpdatedFilter;

    var currentProductCount = 0;
    var filteredProducts = new Array();
    currentTankTypes = [];

   //** Tank Type filter
    var tankTypeCheckBoxes = $("input[name='Tank Type']");

    for (var i = 0; i < tankTypeCheckBoxes.length; i++)
    {
        if (tankTypeCheckBoxes[i].checked == true)
        {
            tankTypeFilter.addTankType(tankTypeCheckBoxes[i].id);
        }
    }

     //** Bowl Shape
    currentBowlShapes = [];

    var bowlShapeCheckBoxes = $("input[name='Bowl Shape']");

    for (var i = 0; i < bowlShapeCheckBoxes.length; i++)
    {
        if (bowlShapeCheckBoxes[i].checked == true)
        {
            bowlShapeFilter.addBowlShape(bowlShapeCheckBoxes[i].id);
        }
    }


      //**Flushing Technology

  
    currentFlushingTechnologys = [];

    var flushingTechnologyCheckBoxes = $("input[name='Flushing Technology']");

    for (var i = 0; i < flushingTechnologyCheckBoxes.length; i++)
    {
        if (flushingTechnologyCheckBoxes[i].checked == true)
        {
            flushingTechnologyFilter.addFlushingTechnology(flushingTechnologyCheckBoxes[i].id);
        }
    }

     //**Minimum Rough In
    currentMinimumRoughIn = [];

    var minimumRoughInCheckBoxes = $("input[name='Minimum Rough In']");

    for (var i = 0; i < minimumRoughInCheckBoxes.length; i++)
    {
        if (minimumRoughInCheckBoxes[i].checked == true)
        {
            minimumRoughInFilter.addMinimumRoughIn(minimumRoughInCheckBoxes[i].id);
        }
    }

    filteredProducts  = initialProducts;  // Default filter data if no chekboxes are selected - LJ

    if (currentTankTypes.length > 0)
        filteredProducts = tankTypeFilter.filterTankTypes(initialProducts);

    if (currentColorCodes.length > 0)
    {
        //alert(selectedColor);
        $("#currentColor").html(selectedColor);
        filteredProducts = colorCodeFilter.filterColorCodes(filteredProducts);
    }  //alert ("****" + filteredProducts.length);
    if (currentBowlShapes.length > 0)
        filteredProducts = bowlShapeFilter.filterBowlShapes(filteredProducts);

    if (currentFlushingTechnologys.length > 0)
        filteredProducts = flushingTechnologyFilter.filterFlushingTechnologys(filteredProducts);

    if (currentCoordinatingSuites.length > 0)
        filteredProducts = coordinatingSuitesFilter.filterCoordinatingSuites(filteredProducts);

    if (currentComfortHeight.length > 0)
        filteredProducts = comfortHeightFilter.filterComfortHeight(filteredProducts);

    if (currentAda.length > 0)
        filteredProducts = adaFilter.filterAda(filteredProducts);

    if (currentWaterSense == "Yes")
    {
        filteredProducts = waterSenseFilter.filterWaterSense(filteredProducts);
    }

    filteredProducts = priceFilter.filterPrice(filteredProducts);

   // filteredProducts = waterSavingsFilter.filterWaterSavings(filteredProducts);

    if ( isInitialLoad )
         initialProductCount =  initialProducts.length;

    if (currentMinimumRoughIn.length > 0)
        filteredProducts = minimumRoughInFilter.filterMinimumRoughIn(filteredProducts);

    $("#pagingTotal").html(filteredProducts.length + " of " + initialProductCount + " Shown");

    $(".filters").css("background-color", "#E2EBEF");

    if (filteredProducts.length == 0)
    {
        $("#toiletModule").html("");
        var productInfo = "<h4>Your choices have hidden all " + initialProductCount + "  toilets!</h4>" +
                          "<span>Adjust the lefthand filters to show more results</span>." +
                          "<h5>" + lastUpdatedFilterName + " was the last filter adjusted.</h5>" +
                          "<span><a onclick='reset();' name ='resetFilters' href='javascript:void(0);' style='padding-top:10px';> Reset all filters </a></span>"
        $("#toiletModule").createAppend('div', { id:'noProducts' + currentProductCount, className: 'noProducts'}, productInfo);


        var SELECTED_FILTER_BACKGROUND = 'yellow';
        $(".filters").css("background-color", "#E2EBEF");
        if (lastUpdatedFilterName == 'Tank Type')  $("#tst-filter2").css("background-color", SELECTED_FILTER_BACKGROUND)
        if (lastUpdatedFilterName == 'Bowl Shape')  $("#tst-filter3").css("background-color", SELECTED_FILTER_BACKGROUND)
        if (lastUpdatedFilterName == 'Flushing Technology')  $("#tst-filter4").css("background-color", SELECTED_FILTER_BACKGROUND)
        if (lastUpdatedFilterName == 'Colors')  $("#tst-filter5").css("background-color", SELECTED_FILTER_BACKGROUND)
        if (lastUpdatedFilterName == 'Coordinating Suites')  $("#tst-filter6").css("background-color", SELECTED_FILTER_BACKGROUND)
        if (lastUpdatedFilterName == 'Comfort Height')  $("#tst-filter7").css("background-color", SELECTED_FILTER_BACKGROUND)
        if (lastUpdatedFilterName == 'Price')  $("#tst-filter8").css("background-color", SELECTED_FILTER_BACKGROUND)
        if (lastUpdatedFilterName == 'Water Savings')  $("#tst-filter9").css("background-color", SELECTED_FILTER_BACKGROUND)
        if (lastUpdatedFilterName == 'WaterSense')  $("#tst-filter9").css("background-color", SELECTED_FILTER_BACKGROUND)
        if (lastUpdatedFilterName == 'Minimum Rough In')  $("#tst-filter10").css("background-color", SELECTED_FILTER_BACKGROUND)
        if (lastUpdatedFilterName == 'Complete Solution')  $("#tst-filter11").css("background-color", SELECTED_FILTER_BACKGROUND)
        if (lastUpdatedFilterName == 'ADA Compliant')  $("#tst-filter13").css("background-color", SELECTED_FILTER_BACKGROUND)
    }

    filteredCurrentProductList = filteredProducts;
    sortProducts( lastSort );

//    if (filteredProducts.length > 0 && isInitialLoad == true) // already paged the products in the sort. . .
//    {
//        pageProducts(1, filteredProducts)
//    }

    if (!isInitialLoad) { if (!loadedFromCookie) { doFormEnabler(lastUpdatedFilter); }}
    else { isInitialLoad = false; }
    
    // omnitureUpdate();

    if ((lastUpdatedFilter != null && lastUpdatedFilter == "Colors") || colorCodeFilter.getCurrentColorCode() != 0) {
        $("span.andup").hide();
    }

    $("#tst-loading-div").css("display", "none");
    fadeToiletModule("in");
   
}

function fadeToiletModule(how) {
    if (how == 'in') {
        $("#toiletModule").fadeIn("2000");
        fadeToiletModuleState = "in";
    } else {
        $("#toiletModule").fadeOut("2000");
        fadeToiletModuleState = "out";
    }
}

var disableTheseFormFields = [];
function doFormEnabler(lastFilter) {
    $("input").removeAttr("disabled");
    if (lastFilter == null || lastFilter == "") {
       return; 
    }
    var lastFilterEnablerName = $("#" + lastFilter).attr("name");
    if (lastFilterEnablerName == null) {
        lastFilterEnablerName = lastFilter;
    }
    disableTheseFormFields = getFieldsThatCanBeDisabled(lastFilterEnablerName);
    
    for (var i = 0; i<filteredCurrentProductList.length; i++) {
        if (getLeftToDoFormEnabler() == 0) {
            break;
        }
        doFormEnableTankType(filteredCurrentProductList[i]);
        doFormEnableBowlShape(filteredCurrentProductList[i]);
        doFormEnableComfortHeight(filteredCurrentProductList[i]);
        doFormEnableAda(filteredCurrentProductList[i]);
        doFormEnableSuites(filteredCurrentProductList[i]);
        doFormEnableWaterSavings(filteredCurrentProductList[i]);
        doFormEnableRoughIn(filteredCurrentProductList[i]);
        doFormEnableFlushingTech(filteredCurrentProductList[i]);
    }

    for (var i=0; i<disableTheseFormFields.length; i++) {
        if (disableTheseFormFields[i] ==  null) { continue; }
        $(disableTheseFormFields[i]).attr("disabled", true);
    }

}

function getLeftToDoFormEnabler() {
    return formEnablerTankTypeDone + formEnablerBowlShapeDone + formEnablerComfortHeightDone +
           formEnablerAdaDone + formEnablerSuitesDone + formEnablerWaterSavingsDone +
           formEnablerRoughInDone + formEnablerFlushingTechDone;
}

function getFieldsThatCanBeDisabled(lastFilterName) {
    // reset defaults
    formEnablerTankTypeDone = 2;
    formEnablerBowlShapeDone = 3;
    formEnablerComfortHeightDone = 1;
    formEnablerAdaDone = 1;
    formEnablerSuitesDone = 1;
    formEnablerWaterSavingsDone = 1;
    formEnablerRoughInDone = 4;
    formEnablerFlushingTechDone = 7;
    
    var result = [];
    if (lastFilterName != "Tank Type") {
        $.merge(result, $("input#One-piece, input#Two-piece"));
    } else { formEnablerTankTypeDone = 0; }
    
    if (lastFilterName != "Bowl Shape") {
        $.merge(result, $("input#Compact-Elongated, input#Elongated, input#Round-Front"));
    } else { formEnablerBowlShapeDone = 0; }

    if (lastFilterName != "Comfort Height") {
        $.merge(result, $("input#Comfort-Height"));
    } else { formEnablerComfortHeightDone = 0; }
    if (lastFilterName != "ADA Compliant") {
        $.merge(result, $("input#ADA-Compliant"));
    } else { formEnablerAdaDone = 0; }

    if (lastFilterName != "Coordinating Suites") {
        $.merge(result, $("input#Coordinating-Suites"));
    } else { formEnablerSuitesDone = 0; }

    if (lastFilterName != "WaterSense") {
        $.merge(result, $("input#WaterSense"));
    } else { formEnablerWaterSavingsDone = 0; }

    if (lastFilterName != "Minimum Rough In") {
        $.merge(result, $("input#12, input#10, input#14, input#4"));
    } else { formEnablerRoughInDone = 0; }

    if (lastFilterName != "Flushing Technology") {
        $.merge(result, $("input#Power-Lite, input#Pressure-Lite, input#Class-Five, input#Class-Six, input#Ingenium, input#Rim-Jet, input#Dual-Flush"));
    } else { formEnablerFlushingTechDone = 0; }

    return result;
}

function removeFieldForFormEnabler(fieldId) {
    var found = -1;
    for (var i = 0; i < disableTheseFormFields.length; i++) {
        if ($(disableTheseFormFields[i]).attr("id") == fieldId) {
            found = i;
            break;
        }
    }
    if (found > -1) {
        disableTheseFormFields[found] = null;
    }
    return found > -1;
}

var formEnablerTankTypeDone = 2;
function doFormEnableTankType(product) {
    if (formEnablerTankTypeDone == 0) { return; }
    if (product != null) {
        if (product.tankType == "One-piece") {
            if (removeFieldForFormEnabler("One-piece")) {
                formEnablerTankTypeDone--;
            }
        } else if(product.tankType == "Two-piece") {
            if (removeFieldForFormEnabler("Two-piece")) {
                formEnablerTankTypeDone--;
            }
        }
    }
}
var formEnablerBowlShapeDone = 3;
function doFormEnableBowlShape(product) {
    if (formEnablerBowlShapeDone == 0) { return; }
    if (product != null) {
        if (product.bowlShape == "Compact Elongated") {
            if (removeFieldForFormEnabler("Compact-Elongated")) {
                formEnablerBowlShapeDone--;
            }
        } else if(product.bowlShape == "Elongated") {
            if (removeFieldForFormEnabler("Elongated")) {
                formEnablerBowlShapeDone--;
            }
        }
        else if(product.bowlShape == "Round Front") {
            if (removeFieldForFormEnabler("Round-Front")) {
                formEnablerBowlShapeDone--;
            }
        }
    }
}
var formEnablerComfortHeightDone = 1;
function doFormEnableComfortHeight(product) {
    if (formEnablerComfortHeightDone == 0) { return; }
    if (product != null) {
        if (product.aDACompliant != null && product.aDACompliant == "Yes") {
            removeFieldForFormEnabler("Comfort-Height");
            formEnablerComfortHeightDone = 0;
        }
    }
}
var formEnablerAdaDone = 1;
function doFormEnableAda(product) {
    if (formEnablerAdaDone == 0) { return; }
    if (product != null) {
        if (product.aDACompliant != null && product.aDACompliant == "Yes") {
            removeFieldForFormEnabler("ADA-Compliant");
            formEnablerAdaDone = 0;
        }
    }
}
var formEnablerSuitesDone = 1;
function doFormEnableSuites(product) {
    if (formEnablerSuitesDone == 0) { return; }
    if (product != null) {
        if (product.coordinatingSuites != null) {
            removeFieldForFormEnabler("Coordinating-Suites");
            formEnablerSuitesDone = 0;
        }
    }
}
var formEnablerWaterSavingsDone = 1;
function doFormEnableWaterSavings(product) {
    if (formEnablerWaterSavingsDone == 0) { return; }
    if (product != null) {
        if (product.waterSense != null && product.waterSense == "Yes") {
            removeFieldForFormEnabler("WaterSense");
            formEnablerWaterSavingsDone = 0;
        }
    }
}
var formEnablerRoughInDone = 4;
function doFormEnableRoughIn(product) {
    if (formEnablerRoughInDone == 0) { return; }
    if (product != null && product.minimumRoughIn != null) {
        if (product.minimumRoughIn.indexOf("|" + 12) > -1) {
            if (removeFieldForFormEnabler("12")) {
                formEnablerRoughInDone--;
            }
        } else if(product.minimumRoughIn.indexOf("|" + 10) > -1) {
            if (removeFieldForFormEnabler("10")) {
                formEnablerRoughInDone--;
            }
        }
        else if(product.minimumRoughIn.indexOf("|" + 14) > -1) {
            if (removeFieldForFormEnabler("14")) {
                formEnablerRoughInDone--;
            }
        }
        else if(product.minimumRoughIn.indexOf("|" + 4) > -1) {
            if (removeFieldForFormEnabler("4")) {
                formEnablerRoughInDone--;
            }
        }
    }
}
var formEnablerFlushingTechDone = 7;
function doFormEnableFlushingTech(product) {
    if (formEnablerFlushingTechDone == 0) { return; }
    if (product != null) {
        if (product.flushingTechnology == "Power Lite") {
            if (removeFieldForFormEnabler("Power-Lite")) {
                formEnablerFlushingTechDone--;
            }
        } else if(product.flushingTechnology == "Pressure Lite") {
            if (removeFieldForFormEnabler("Pressure-Lite")) {
                formEnablerFlushingTechDone--;
            }
        }
        else if(product.flushingTechnology == "Class Five") {
            if (removeFieldForFormEnabler("Class-Five")) {
                formEnablerFlushingTechDone--;
            }
        } else if(product.flushingTechnology == "Class Six") {
            if (removeFieldForFormEnabler("Class-Six")) {
                formEnablerFlushingTechDone--;
            }
        }
        else if(product.flushingTechnology == "Ingenium") {
            if (removeFieldForFormEnabler("Ingenium")) {
                formEnablerFlushingTechDone--;
            }
        }
        else if(product.flushingTechnology == "Rim Jet") {
            if (removeFieldForFormEnabler("Rim-Jet")) {
                formEnablerFlushingTechDone--;
            }
        }
        else if(product.flushingTechnology == "Dual Flush") {
            if (removeFieldForFormEnabler("Dual-Flush")) {
                formEnablerFlushingTechDone--;
            }
        }
    }
}

 // Runs after the page loads
function calculatePages(filteredProducts)
{

    if (filteredProducts != null)
        products = filteredProducts;

    pagingSpan = document.getElementById("pageNumbers");
    pagingSpan.innerHTML = "";
    countProducts = products.length;
    countPages = parseInt(countProducts / PRODUCTS_PER_PAGE)

    if ((countProducts % PRODUCTS_PER_PAGE) > 0)
    {
        countPages = countPages + 1;
    }
     //alert("calc: count of pages: " + countPages)

    for (var i = 1; i <= countPages; i++)
    {
        pagingSpan.innerHTML = pagingSpan.innerHTML + '<a ' + 'id="page' + i + '" href="javascript:void(0);" onclick="pageProducts(' + i + ');">' + i + '</a>';
    }
}


function pageProducts(selectedPage, filteredProducts, isSetup)
{

   // $("#toiletModule").fadeOut("2000");
    //console.log ("paging products")
    if (filteredProducts != null)
        products = filteredCurrentProductList;

    var startProduct;
    var endProduct;
    var myIsSetup = isSetup;
    if (myIsSetup == null) { myIsSetup = false; }

    if (selectedPage == -1 || showOnOnePage) // show on multiple pages
    {
        selectedPage = -1;
        showOnOnePage = true;
        
        $('#show').html('<a href="javascript:void(0);" onclick="showOnOnePage = false;pageProducts(\'1\');">Show on mutliple pages</a>');
        $("#navigate").css("display", "none");
    }
    else
    {
        showOnOnePage = false;
        $('#show').html('<a href="javascript:void(0);" onclick="showOnOnePage = true;pageProducts(\'-1\'); ">Show on 1 page</a>');
        $("#navigate").css("display", "inline");
    }

    if (isInitialLoad && !showOnOnePage)
    {
        selectedPage = 1;
        currentPage = 1;
    }


    if (selectedPage == 'pageLeft')
    {
        if (currentPage > 1)
        {
            currentPage = parseInt(currentPage) - 1;
            selectedPage = currentPage;
            myIsSetup = false;
        }
        else
        {
            return;
        }
    }
    else  if (selectedPage == 'pageRight')
    {
        if (currentPage < countPages)
        {
            currentPage = parseInt(currentPage) + 1;
            selectedPage = currentPage;
            myIsSetup = false;
        }
        else
        {
            return;
        }
    }
    else if (selectedPage == -1 || selectedPage == 1)
    {
        startProduct = 0;
        endProduct = initialProducts.length;  // 9*1 -1
    }

    if (selectedPage != -1)
    {
        products = null; //  reinitialize products
        products = new Array(PRODUCTS_PER_PAGE);
        endProduct = (selectedPage * PRODUCTS_PER_PAGE) - 1;

        if (endProduct > filteredCurrentProductList.length)
        {
            startProduct = ((selectedPage - 1) * PRODUCTS_PER_PAGE); //previous pages end
            endProduct = ((selectedPage - 1) * PRODUCTS_PER_PAGE) - 1;
            endProduct = (endProduct + ( filteredCurrentProductList.length % PRODUCTS_PER_PAGE));

        }
        else
        {
            startProduct = (endProduct + 1) - (PRODUCTS_PER_PAGE);
        }
    }

    if (startProduct < 0) startProduct = 0;
    if (endProduct < 0) endProduct = 0;

    currentPage = selectedPage;
    var prodCount = 0;

    if (filteredCurrentProductList == null)
    {
        for (var i = startProduct; i < endProduct; i++)
        {
            products[prodCount] = initialProducts[i];      // display count of this product from the initial.
            prodCount++;
        }
    }
    else
    {
        for (var i = startProduct; i <= endProduct; i++)
        {
            products[prodCount] = filteredCurrentProductList[i];      // display count of this product from the initial.
            prodCount++;
        }
    }
           // Remove rows from table
    var filteredResults = document.getElementById("toiletModule");
    filteredResults.innerText = "";      // Causing an issue in ie
    filteredResults.innerHTML = "";
    populateProductsInitial();  // Need to reset product table
    for (var i = 1; i < countPages + 1; i++)
    {
        $("#page" + i).css("font-weight", "normal").css("text-decoration", "underline");
    }
    $("#page" + selectedPage).css("font-weight", "bold").css("text-decoration", "none");

    if (colorCodeFilter.getCurrentColorCode() != 0) {
        $("span.andup").hide();
    }

    if (!myIsSetup) { fadeToiletModule("in"); }
}

function StringBuffer() {
   this.buffer = [];
 }

 StringBuffer.prototype.append = function append(string) {
   this.buffer.push(string);
 }; 

 StringBuffer.prototype.toString = function toString() {
   return this.buffer.join("");
 };


function populateProductsInitial()
{
    // check to see if there is a product first
    var productInfo = null;
    var rowCount = 0;
    var jpgPhotoNameOverride = "";
    var priceOverride = "";
    var productItem = "";
    var zIndexCount = 100;

    for (var productCount = 0; productCount < products.length; productCount++) // Loop through producrts
    {
        $("#toiletModule").hide();
        if (products[productCount] != null && products[productCount].catalogPage != '')
        {
            if (productCount % PRODUCTS_PER_ROW == 0)   //  ** new row
            {   //Build text for product here
                zIndexCount = zIndexCount - rowCount;
                $("#toiletModule").createAppend(
                    'div', { id: 'productRow' + rowCount, className: 'product-info-row', style: 'z-index:' + zIndexCount + ';'}, [
                        'table', { width: '567px' }, [
                            'tbody', {}, [
                                'tr', {}, [
                                      'td', { id: 'tableRow' + productCount, width: '189px', style: 'vertical-align:top; padding-right:10px;' }, []
                                    , 'td', { id: 'tableRow' + parseInt(productCount + 1), width: '189px', style: 'vertical-align:top; padding-right:10px;' }, []
                                    , 'td', { id: 'tableRow' + parseInt(productCount + 2), width: '189px', style: 'vertical-align:top; padding-right:10px;' }, []
                                ]
                            ]
                        ]
                    ]
            )};

            if (products[productCount].brandName != null) products[productCount].brandName = products[productCount].brandName.replace("|", "");
            //Override with toilet image

            for (var i = 0; i < products[productCount].productItems.length; i++)
            {

                productItem = products[productCount].productItems[i];
                if (productItem.colorFinishCode == colorCodeFilter.getCurrentColorCode())
                {

                  //  console.log ("selectedColorCode: " + selectedColorCode + "productItem.jpgItemImage: " + productItem.jpgItemImage);

                    if (productItem.jpgItemImage != null && productItem.jpgItemImage != "")  
                    {
                        jpgPhotoNameOverride = productItem.jpgItemImage;
                    }
                    else
                    {
                        jpgPhotoNameOverride = products[productCount].jpgPhotoName;
                    }

                    if (!isCA) {
                        priceOverride = getListPrice(productItem.price, products[productCount].brandName, null);
                    } else {
                        priceOverride = getListPrice(productItem.listPriceAltCurrency, products[productCount].brandName, null);
                    }
                }
            }


            productInfo = new StringBuffer();
            productInfo.append(
                '<a href="../detail.jsp?from=thumb&frm=&module=Toilets&item=' + products[productCount].parentItemId + '&prod_num=' + products[productCount].parentItemNumber + '&section=2&category=13" onclick="setTsCookie();"><img class="qlProdImg" src="/onlinecatalog/125x160/' + jpgPhotoNameOverride + '" width="125px" height="160px" alt="" title="product image" border="0" prodId="' + products[productCount].parentItemId + '" row="' + rowCount + '" /></a>' +
                '<div class="toiletModuleCopy"> ' +
                '<a href="../detail.jsp?from=thumb&frm=&module=Toilets&item=' + products[productCount].parentItemId + '&prod_num=' + products[productCount].parentItemNumber + '&section=2&category=13" onclick="setTsCookie();">' + 'K-' + products[productCount].parentItemNumber + '</a>'
            );
            if (products[productCount].thumbDesc != null)
            {
                productInfo.append('<h4><a href="../detail.jsp?from=thumb&frm=&module=Toilets&item=' + products[productCount].parentItemId + '&prod_num=' + products[productCount].parentItemNumber + '&section=2&category=13" onclick="setTsCookie();">' + products[productCount].thumbDesc + '</a></h4>');
            }
            else
            {
                products[productCount].thumbDesc;
            }

            var completeSolutionText = '';

            if (currentCompleteSolution.length > 0 && products[productCount].completeSolution == "Yes")
                completeSolutionText = '<span id="completeSolutionText" style="display:block"><img class="close" id="ent" src="/onlinecatalog/selector/images/tstCheckBox.gif" style="padding-right:3px" border="0" />Complete Toilet Solution</span>';

            productInfo.append(completeSolutionText + priceOverride);  // show the smallest price

            cartId = 'cartidToilets' + cartFieldDelim + products[productCount].catalogPage + cartFieldDelim + products[productCount].parentItemNumber;


            // compare
            if (productsInCart != null && productsInCart.length > 0 && isProductInCart(products[productCount].parentItemNumber)) {
                 productInfo.append(
                    '<br><a href="selector.jsp?action=remove&prodnum=3564&page=01.001.001"><img src="/common/images/icon-remove.gif" alt="Remove" style="margin-right: 8px;" width="11" border="0" height="9">Delete from Compare</a>'
                 );
            } else {
                productInfo.append(
                    '<br><input id="'+cartId+'" name="cartid" value="'+cartId+'" class="checkbox" type="checkbox"><label for="'+cartId +
                        '" class="over" onmouseover="this.style.color=\'#990000\'; this.style.textDecoration=\'underline\';"' +
                        ' onmouseout="this.style.color=\'#666666\'; this.style.textDecoration=\'none\';" style="cursor: pointer; color: rgb(102, 102, 102); text-decoration: none;">Add to Compare</label>'
                );
            }

            productInfo.append(
                    '<br/><a class="asterik myfolderLink" href="javascript:void(0);" title="'+products[productCount].parentItemNumber+'"><img height="11" border="0" width="11" style="margin-right: 5px;" alt="Add" src="/common/images/icon-save.gif"/>Save to My Kohler Folder</a>'
            );
            if (isAdaCompliantOrWaterSense(products[productCount])) {
                productInfo.append('     <div class="productResult-adaLogo">');
                if (products[productCount].waterSense != null && products[productCount].waterSense == "Yes") {
                    productInfo.append('         <a href="/savewater/watersense/landing.htm"><img src="/common/images/watersense.gif" alt="WaterSense Logo" border="0"></a>');
                }
                if (products[productCount].aDACompliant != null && products[productCount].aDACompliant == "Yes") {
                    productInfo.append('         <a href="/onlinecatalog/ada.jsp"><img height="25" border="0" width="36" alt="ADA Logo" src="/common/images/ada.gif"/></a>');
                }
                productInfo.append('     </div>');
            }

            productInfo.append('</div>');
            $("#tableRow" + productCount).html($("#tableRow" + productCount)[0].innerHTML + productInfo.toString());


            if (productCount % PRODUCTS_PER_ROW == 2) {
                rowCount++;
            }
        }
    }
    $(".product-info-row table tbody tr").after('<tr><td><br/><img height="18" width="95" border="0" onmouseout="this.src=\'/common/images/button-compareitems.gif\'" onmouseover="this.src=\'/common/images/button-compareitems-on.gif\'" style="margin-right: 8px;" onclick="submitCompareForm()" alt="Compare Items" src="/common/images/button-compareitems.gif"/></td></tr>');
    $(".myfolderLink").click(function() {
        if (!isUserLoggedIn) {
            KPNA.userAction("login", "/onlinecatalog/selector/selector.jsp");
        } else {
            openColorWin($(this).attr("title"), 'fromDetail', '/project_folder/');
        }
    });

     quickllook2.addProdImageEvent();
}

function isAdaCompliantOrWaterSense(product) {
    return (   (product.aDACompliant != null && product.aDACompliant == "Yes") ||
               (product.waterSense != null && product.waterSense == "Yes")
            );
}

function isProductInCart(parentItemNo) {
    if (productsInCart.length == 0) {
        return false;
    }
    for (var i=0; i<productsInCart.length; i++) {
        if (productsInCart[i] == parentItemNo) { return true; }
    }
    return false;
}

function submitCompareForm() {
    var sfurl = "selector.jsp?fwd=true";
    var addToCompareLocation = getCompareKeys();
    if ((addToCompareLocation.length > 0) ) {
        setTsCookie();
        document.cookie = 'kohlerPlumbingTargetedContent=COMPARE; path=/';
        self.location.href = sfurl + addToCompareLocation;
    }
}

function getCompareKeys() {
    var addToCompareLocation= "";
    $("input[name=cartid]:checked").each(function() {
        addToCompareLocation += "&compareKey=" + escape($(this).val());
    });
    return addToCompareLocation;
}



// On DOM-load
$(document).ready(function() {

    showDim();

    if ($.query.get('waterSense')!="") {
        currentWaterSense = "Yes";
        setTsCookie("");
    } else if ($.query.get('completeSolution')!="") {
        currentCompleteSolution = "Yes";
        setTsCookie("");
    } else {
        setTsDefaultsFromCookie();
    }

    //closeTst();
    swatch();
    showHelper();
    // Need to refactor close functionality -------------------
    // close for Selector Tool
    $("#header img.close").click(function() {
        if ($("#entry").css("display")) {
            $("#entry").css("display", "none");
        }
        $("#tstCanvas").css("display", "none");
        $("#dimLayer").css("display", "none");
    });

	// close for Entry Panel via close button

    $("#entry img.close").click(function() {
        $("#entry").css("display", "none");
        $("#tst-opacity-layer").css("display", "none");
        filterResultsOpcty('off');
    });

    $(".sort-button").click(function () {
        //alert("hiding display tab.");
        $("#sort-order-dropdown").css("display", "none");
    });


    $("#sortOrder").click(function() {
        $("#sortDiv").css("display", "block");
		//filterResultsOpcty('off');
    });

       // close filter
    $("img.helperClose").click(function() {
        $("div.filters").css("zIndex", "2");
        $("div.helper").css("display", "none");
        $("#tst-opacity-layer").css("display", "none");
    });

    // close for Entry Panel via 'Show Toilets' link
    $("#showT").click(function() {
        $("#entry").css("display", "none");
        filterResultsOpcty('off');
    });

	// END Need to refactor close functionality -------------------

   

    elem = $("#tst-load-opacity-layer");
    checkWinHeight();
	//$("#tst-filters").css("borderWidth", "1px");
    //$("#tst-filters").css("borderStyle", "solid");
    //$("#tst-filters").css("borderColor", "#900");
    //$("#tst-filters div").css("zIndex", 99);
    //$("#tst-header").css("zIndex", 99);
    //elem.css("backgroundColor", "white")
    //elem.css("height", winH);
    //elem.fadeIn("200", callbacks);

    $("#tst-loading-div").css("display", "none");

    if ($.query.get('waterSense')!="") {
        $("input[name=WaterSense]").check();
    } else if ($.query.get('completeSolution')!="") {
        $("input[name=Complete Solution]").check();
    }

});

// jquery query param plugin
new function(settings){var $separator=settings.separator||'&';var $spaces=settings.spaces===false?false:true;var $suffix=settings.suffix===false?'':'[]';var $prefix=settings.prefix===false?false:true;var $hash=$prefix?settings.hash===true?"#":"?":"";jQuery.query=new function(){var is=function(o,t){return o!=undefined&&o!==null&&(!!t?o.constructor==t:true)};var parse=function(path){var m,rx=/\[([^[]*)\]/g,match=/^(\S+?)(\[\S*\])?$/.exec(path),base=match[1],tokens=[];while(m=rx.exec(match[2]))tokens.push(m[1]);return[base,tokens]};var set=function(target,tokens,value){var o,token=tokens.shift();if(typeof target!='object')target=null;if(token===""){if(!target)target=[];if(is(target,Array)){target.push(tokens.length==0?value:set(null,tokens.slice(0),value))}else if(is(target,Object)){var i=0;while(target[i++]!=null);target[--i]=tokens.length==0?value:set(target[i],tokens.slice(0),value)}else{target=[];target.push(tokens.length==0?value:set(null,tokens.slice(0),value))}}else if(token&&token.match(/^\s*[0-9]+\s*$/)){var index=parseInt(token,10);if(!target)target=[];target[index]=tokens.length==0?value:set(target[index],tokens.slice(0),value)}else if(token){var index=token.replace(/^\s*|\s*$/g,"");if(!target)target={};if(is(target,Array)){var temp={};for(var i=0;i<target.length;++i){temp[i]=target[i]}target=temp}target[index]=tokens.length==0?value:set(target[index],tokens.slice(0),value)}else{return value}return target};var queryObject=function(a){var self=this;self.keys={};if(a.queryObject){jQuery.each(a.get(),function(key,val){self.SET(key,val)})}else{jQuery.each(arguments,function(){var q=""+this;q=q.replace(/^[?#]/,'');q=q.replace(/[;&]$/,'');if($spaces)q=q.replace(/[+]/g,' ');jQuery.each(q.split(/[&;]/),function(){var key=this.split('=')[0];var val=this.split('=')[1];if(!key)return;if(/^[+-]?[0-9]+\.[0-9]*$/.test(val))val=parseFloat(val);else if(/^[+-]?[0-9]+$/.test(val))val=parseInt(val,10);val=(!val&&val!==0)?true:val;if(val!==false&&val!==true&&typeof val!='number')val=decodeURIComponent(val);self.SET(key,val)})})}return self};queryObject.prototype={queryObject:true,has:function(key,type){var value=this.get(key);return is(value,type)},GET:function(key){if(!is(key))return this.keys;var parsed=parse(key),base=parsed[0],tokens=parsed[1];var target=this.keys[base];while(target!=null&&tokens.length!=0){target=target[tokens.shift()]}return typeof target=='number'?target:target||""},get:function(key){var target=this.GET(key);if(is(target,Object))return jQuery.extend(true,{},target);else if(is(target,Array))return target.slice(0);return target},SET:function(key,val){var value=!is(val)?null:val;var parsed=parse(key),base=parsed[0],tokens=parsed[1];var target=this.keys[base];this.keys[base]=set(target,tokens.slice(0),value);return this},set:function(key,val){return this.copy().SET(key,val)},REMOVE:function(key){return this.SET(key,null).COMPACT()},remove:function(key){return this.copy().REMOVE(key)},EMPTY:function(){var self=this;jQuery.each(self.keys,function(key,value){delete self.keys[key]});return self},empty:function(){return this.copy().EMPTY()},copy:function(){return new queryObject(this)},COMPACT:function(){function build(orig){var obj=typeof orig=="object"?is(orig,Array)?[]:{}:orig;if(typeof orig=='object'){function add(o,key,value){if(is(o,Array))o.push(value);else o[key]=value}jQuery.each(orig,function(key,value){if(!is(value))return true;add(obj,key,build(value))})}return obj}this.keys=build(this.keys);return this},compact:function(){return this.copy().COMPACT()},toString:function(){var i=0,queryString=[],chunks=[],self=this;var addFields=function(arr,key,value){if(!is(value)||value===false)return;var o=[key];if(value!==true){o.push("=");o.push(encodeURIComponent(value))}arr.push(o.join(""))};var build=function(obj,base){var newKey=function(key){return!base||base==""?[key].join(""):[base,"[",key,"]"].join("")};jQuery.each(obj,function(key,value){if(typeof value=='object')build(value,newKey(key));else addFields(chunks,newKey(key),value)})};build(this.keys);if(chunks.length>0)queryString.push($hash);queryString.push(chunks.join($separator));return queryString.join("")}};return new queryObject(location.search,location.hash)}}(jQuery.query||{});
