// categoryProduct.js - used to store products for the category pages
// - provides ability to filter and sort products on the category page
dojo.require("bec.product.AddToCart");
dojo.require("bec.product.ProductCompare");
dojo.require("bec.product.ProductQuickView");
dojo.require("dijit.form.NumberTextBox");
dojo.require("bec.widget.TextBox");
dojo.require("dijit.form.CheckBox");
dojo.require("bec.widget.VerticalScroller");
dojo.require("bec.widget.DropDownButton");
dojo.require("dijit.TooltipDialog");

var products = new Array();
var filteredProducts;
var filteredProductByIncludeOnly;
var currentPage = 1;
var cp_parentIdentifier = '';
var cp_identifier = '';

var MAX_ITEM_PER_ROWS = 3;
var MAX_ROWS = 4;
var VIEW_ALL = 999;
var MAX_FILTER_COUNT = 15;
var MAX_PAGES = 4;
var numberOfFiltersPerColumn = 8;
var hashString = '';
var disableDisplay = false;
var SORT_HASH = ":s=";
var sortChange = false;
var PAGE_HASH = ":p=";
var pageChange = false;
var sortUsed = "sortBy1";
var busy = false;

/**
 * Call all the individual methods to build page
 */
function categoryInit()
{
	buildFilterList();
	createByPriceFilter();
	enableQuickViewHover();
	buildPagination();
	processHashFilter();
	addHoverToLeftNavIE6();
	initWidget();
}
/**
 * Move seo copy to bottom of the page
 * getting called in-line after seo bottom
 */
function moveSeoCopy()
{
	try
	{
		var seoTop = dojo.byId("seoTop");
		var seoBottom = dojo.byId("seoBottom");
		if (seoTop && seoBottom)
		{
			seoBottom.innerHTML = seoTop.innerHTML;
			seoTop.innerHTML = "";
		}
	}catch(e){}
}

/**
 * init the scroll sliders
 */
function initWidget()
{
	try
	{
		dojo.parser.instantiate([dojo.byId("filterSlider")], {dojoType: "bec.widget.VerticalScroller"});
		dojo.parser.instantiate([dojo.byId("seoTextSlider")], {dojoType: "bec.widget.VerticalScroller"});
	}
	catch(e){}
}

/**
 * Product instance - 
 * These are created in BECCategoryProduct.jspf
 */
function product(name, image, displayPrice, price, rating, attributes, best, productURL, id, partNumber, ratingTotalReviewCount, ratingRecommendPercentage, newIcon, addToCartFlag, superItem)
{
    this.name = name;
    this.image = image;
    this.displayPrice = displayPrice;
    this.price = price;
    if (rating)
    {
		this.avgRating = (rating == '') ? 0 : rating;    	
		this.totalReviewCount = (ratingTotalReviewCount == '') ? 0 : ratingTotalReviewCount;
		this.recommendPercentage = (ratingRecommendPercentage == '') ? 0 : ratingRecommendPercentage;
    }
    
    this.attributes = attributes;
    this.best = best;
    this.productURL = productURL;
    this.id = id;
    this.partNumber = partNumber;
    this.strAttributes = '';
    this.newIcon = newIcon;
    this.addToCartFlag = addToCartFlag;
    this.superItem = superItem;
}

function sortByName(a,b)
{
    var x = a.name.toLowerCase();
    var y = b.name.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

function sortByCount(a,b)
{
    var x = a.count;
    var y = b.count;
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

function sortByCountDesc(a,b)
{
    var x = a.count;
    var y = b.count;
    return ((x < y) ? 1 : ((x > y) ? -1 : 0));
}

function sortByPrice(a,b)
{
    var x = a.price;
    var y = b.price;
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

function sortByPriceDesc(a,b)
{
    var x = a.price;
    var y = b.price;
    return ((x < y) ? 1 : ((x > y) ? -1 : 0));
}

function sortByRating(a,b)
{
    var x = a.avgRating;
    var y = b.avgRating;
    return ((x < y) ? 1 : ((x > y) ? -1 : 0));
}

function sortByBest(a,b)
{
    var x = a.best;
    var y = b.best;
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

function changeSort(id)
{
	sortChange = true;
	sortUsed = id;
	displayProductsByPage(currentPage);	
	sortChange = false;
}

function changeFilter()
{
	pageChange = true;
    displayProductsByPage(1);
    pageChange = false;
}

function displayProducts()
{
	displayProductsByPage(currentPage);	
}

function changePage(page)
{
	pageChange = true;
    displayProductsByPage(page);
    pageChange = false;
}

function displayProductsByPage(page)
{ 
	 if (!disableDisplay)
	 {
		 currentPage = getPageValue(page);
		 hashString = '';
		 
		 var sortValue = getSortValue();
		 
	     if (sortValue == 'priceAsc')
	     {
	     	displayProductsByPrice();
	     }
	     else if (sortValue == 'priceDesc')
	     {
	     	displayProductsByPriceDesc();
	     }
	     else if (sortValue == 'best')
	     {
	     	displayProductsByBest();
	     }
	     else if (sortValue == 'rating')
	     {
	     	displayProductsByRating();
	     }
	     else
	     {
	     	// no sorting
	     	displayFilteredProducts(filter());
	     }
	     
	     updateFilters();
	     
	     window.location.hash = hashString + SORT_HASH + sortValue + PAGE_HASH + currentPage;
	     
	     // call coremetric function to track category selection criteria
	     // Note: function is on BECCategoryDisplay.jsp (can we move to this JS file?)
	     trackCategorySelectionCriteria (getFilterValue("filterByPrice"), getFilterValue("filterSelect"), sortValue, page);
	     
	     // IE6 Hack - remove focus of narrow by and sort by - so mouse wheel scroll will not change select
	     try
	     {
	     	$("#pagination").focus();     	
	     }
	     catch(e){}
	 }
}

function getSortValue()
{
	var sortValue = '';
	try
	{
		var sortSelect = dojo.byId(sortUsed);
	    var hash = window.location.hash;
	    var start = hash.indexOf(SORT_HASH);
	    var end = hash.indexOf(PAGE_HASH);
	    if (end < 0)
	    {
	    	end = hash.length;
	    }
		if (start >=0 && !sortChange)
		{
			sortValue = hash.substring(start+SORT_HASH.length, end);
			setSortSelect(sortSelect, sortValue);
		}
		else
		{
			sortValue = sortSelect[sortSelect.selectedIndex].value;
		}
		syncSortSelect(sortValue);
	}
	catch(e){}
	
	return sortValue;
}

function syncSortSelect(sortValue)
{
	// update other sort field
	var sortSyncId = "sortBy1";
	
	if (sortUsed == sortSyncId)
	{
		sortSyncId = "sortBy2";
	}
	var sortSelect = dojo.byId(sortSyncId);
	setSortSelect(sortSelect, sortValue);
}

function getPageValue(page)
{
	 var pageValue = 1;
	 var hash = window.location.hash;
	 var start = hash.indexOf(PAGE_HASH);
	 
	 if (start >=0 && !pageChange)
	 {
		 pageValue = hash.substring(start+PAGE_HASH.length, hash.length);
	 }
	 else
	 {
		 pageValue = page;
	 }
	 return pageValue;
}

function setSortSelect(select, value)
{
	if (select)
	{
		for(i=0;i<select.length;i++)
		{
			if(select.options[i].value==value)
			{
				select.selectedIndex=i;
				break;
			}
		}
	}
}

function displayProductsByName()
{
    displayFilteredProducts(filter().sort(sortByName));
}

function displayProductsByBest()
{ 
    displayFilteredProducts(filter().sort(sortByBest));
}

function displayProductsByPrice()
{
    displayFilteredProducts(filter().sort(sortByPrice)); 
}

function displayProductsByPriceDesc()
{
    displayFilteredProducts(filter().sort(sortByPriceDesc)); 
}

function displayProductsByRating()
{
    displayFilteredProducts(filter().sort(sortByRating));
}

function updateFilters()
{
	try
	{
		updateComponentFilters();
		updatePriceFilters();
	}
	catch(e)
	{
		console.error("Error in updateFilters. Error = " + e.message);
	}
}

function updateComponentFilters()
{
	var parentObj1 = dojo.byId("filterSelect"); 
	if (parentObj1)
	{
		dojo.forEach(dojo.query(".dijitCheckBox", parentObj1), function(a)
		{ 
			var cb = dijit.byNode(a);
			if (cb.value != 'View All')
			{
				var count = checkValueInFilteredProducts(cb.value);
				if (count > 0)
				{
					cb.attr('disabled', false);
				}
				else
				{
					cb.attr('disabled', true);
					cb.attr('checked', false);
				}
				
				// update the count on the label
				updateLabelCount(cb, count);
			}
			
		}, this);
	}
}

function updatePriceFilters()
{
	var parentObj2 = dojo.byId("filterByPrice"); 
	if (parentObj2)
	{
		dojo.forEach(dojo.query(".dijitCheckBox", parentObj2), function(a)
		{ 
			var cb = dijit.byNode(a);
			if (cb.value != 'View All')
			{
				var count = checkPriceInFilteredProducts(cb.value);
				if (count > 0)
				{
					cb.attr('disabled', false);
				}
				else
				{
					cb.attr('disabled', true);
					cb.attr('checked', false);
				}
				// update the count on the label
				updateLabelCount(cb, count);
			}
		}, this);
	}
}

function updateLabelCount(checkbox, count)
{
	try
	{
		var label = dojo.byId(checkbox.id + 'label');
		label.innerHTML = label.title + ' (' + count + ')';
		
		if (count > 0)
		{
			dojo.removeClass(label, 'disabled');
		}
		else
		{
			dojo.addClass(label, 'disabled');
		}
	}
	catch(e)
	{}
}

function checkPriceInFilteredProducts(value)
{
	var count = 0;
	try
	{
		//use filterd product by inlcudes only here
		var tempProducts = getFilterProductsIncludeOnly();
		if (tempProducts)
		{
			for(var i=0; i < tempProducts.length; i++)
			{
				if (tempProducts[i].price > 0) // only eval product with price
				{
					var values = eval(value);
				 	if (tempProducts[i].price <= values.h && tempProducts[i].price >= values.l)
				    {
						count++
					}
				}
			}
		}
	}
	catch(e)
	{
		console.error("Error in checkPriceInFilteredProducts. Error = " + e.message);
	}
	return count;	
}

function getFilterProductsIncludeOnly()
{
	if (filteredProductByIncludeOnly)
	{
		return filteredProductByIncludeOnly;
	}
	else
	{
		return products;
	}

}
function checkValueInFilteredProducts(value)
{
	var count = 0;
	try
	{
		var tempProducts = getFilteredProducts();
		if (tempProducts)
		{
			var productIncludes;
			for(var i=0; i < tempProducts.length; i++)
			{
				productIncludes = tempProducts[i].strAttributes;
				if (productIncludes == '')
	            {
					productIncludes = convertAttrToString(tempProducts[i].attributes);
	            }
				if (productIncludes && productIncludes.indexOf(value) >= 0)
				{
					count++;
				}
			}
		}
	}
	catch(e)
	{
		console.error("Error in checkValueInFilteredProducts. Error = " + e.message);
	}
	return count;
}

function processHashFilter()
{
	try
	{
		if (window.location.hash != '')
		{
			disableDisplay = true;
			var reload1 = setFilterFromHash("filterSelect", window.location.hash);
			var reload2 = setFilterFromHash("filterByPrice", window.location.hash);
			var reload3 = (window.location.hash.indexOf(SORT_HASH) >= 0);
			var reload4 = (window.location.hash.indexOf(PAGE_HASH) >= 0);
			if (reload1 || reload2 || reload3 || reload4)
			{
				disableDisplay = false;
				displayProductsByPage(1);
			}
			else
			{
				disableDisplay = false;
			}
		}
	}
	catch(e){}
}

function setFilterFromHash(parent, hash)
{
	var reload = false;
	var parentObj = dojo.byId(parent); 
	if (parentObj)
	{
		dojo.forEach(dojo.query(".dijitCheckBox", parentObj), function(a)
		{ 
			var cb = dijit.byNode(a);
			if (cb.value != 'View All')
			{
				if (hash && hash.indexOf(cb.value) >= 0)
				{
					cb.attr('checked', true);
					reload = true;
				}
			}
		}, this);
	}
	
	return reload;
}

/**
 * Get filtered products if set otherwise just return all products
 */
function getFilteredProducts()
{
	if (filteredProducts)
	{
		return filteredProducts;
	}
	else
	{
		return products;
	}
}

/**
 * Show product quick view on the category page for select product
 */
function showQuickView(i) 
{
	var product = getFilteredProducts()[i];		
	var quickView = new bec.product.ProductQuickView(
	    {   catEntryId: product.id,
	        partNumber: product.partNumber,
	        name: product.name,
	        parentIdentifier: cp_parentIdentifier,
	        identifier: cp_identifier,
	        avgRating: product.avgRating,
	        totalReviewCount: product.totalReviewCount,
	        recommendPercentage: product.recommendPercentage,
	        price: product.price,
	        superItem: product.superItem
	    });
	quickView.show();
}

function addToCartCompare(id)
{
	var qty = dojo.byId("qty_" + id);	  
	
	if (qty && addToCartCommon(id, qty.value, ";ProductCompareView"))
	{
		try
		{
			productCompare.close();
			//todo: add coremetrics tracking somehow
		}
		catch(e)
		{
			console.error("error closing and tracking add to cart" + e);
		}
	}
}

/**
 * Add to cart common 
 * - used by top nav feature
 * @param id
 * @param qty
 * @param cmView
 */
function addToCartCommon(id, qty, cmView)
{
	var addToCart = new bec.product.AddToCart();
	return addToCart.submitItem(id, qty, null, cmView, null, null);
}

function enableQuickViewHover()
{
	try
	{
		$('.product-display .group').hover(function(){
			$(this).find('.quickViewLink').show();
		}, function(){
			$(this).find('.quickViewLink').hide();
		});
	}
	catch(e){}
}

/**
 * Display filtered products
 */
function displayFilteredProducts(filteredProds)
{
	var results = dojo.byId('results');
	
	 if (results)
	 {
		 bec.util.html.hideNode('noResults');
		 bec.util.html.set(results, LOADING_MESSAGE);
	 }
	 
	var t=setTimeout(function(){loadProducts(filteredProds);},300);
}

function addRemoveCompareCheck(id, idx)
{
	try
	{
		productCompare.addRemoveCompareCheck(id, getFilteredProducts()[idx].name);
	}
	catch(e)
	{
		var cb = document.getElementById("compareBox"+id);
		if (cb)
		{
			cb.checked = false;
		}
	}
}

function loadProducts(filteredProds)
{
	// default to view all
    var startPos = 0
    var endPos = filteredProds.length;
    var numberOfResultsPerPage = MAX_ITEM_PER_ROWS * MAX_ROWS;
    
    if (endPos < numberOfResultsPerPage)
    {
    	currentPage = 1;
    } 
    
    // change to page viwe if not view all
    if (currentPage != VIEW_ALL)
    {
	    startPos = (currentPage - 1) * numberOfResultsPerPage;
		endPos = startPos + numberOfResultsPerPage;	
		if (filteredProds.length < endPos)
		{
			endPos = filteredProds.length;		
		}
	}
	
	// create product data
    var data = '';
	var count = 0;
    for (var i=startPos; i< endPos; i++)
    { 
    	var seporatorClass = '';
    	count++;
    	//if first row then style first-row
    	if (count <= MAX_ITEM_PER_ROWS)
    	{
    		seporatorClass = ' first-row';
    	}
    	
    	// last product in row - last-product
    	if (((i+1) % MAX_ITEM_PER_ROWS == 0) || ((i+1) == endPos))
    	{
    		seporatorClass = seporatorClass + ' last-product';
    	}
    	
        data += '<div id="quickView_' + i + '" class="group ' + seporatorClass + '">';
        data += '<div class="clearfix"><div class="compare"><a href="#" onclick="productCompare.compareProducts();return false;">Compare</a>';
        data += '<input type="checkbox" id="compareBox'+filteredProds[i].id+'" name="compareBox" value="'+ filteredProds[i].id + '" class="compareBox" ';
        data += 'onclick="addRemoveCompareCheck(\'' + filteredProds[i].id + '\',\'' + i + '\')"></div>';
        if (filteredProds[i].newIcon)
        {
        	data += '<div id="newProductIndicator" class="sprite-product-new"></div>';
        }
        data += '</div><div class="quickViewLink"><a href="javascript:showQuickView(' + i + ');" class="btn btn-square btn-small">Quick View</a></div>';
        data += '<div class="image"><a id="PRODUCTLINK_' + i + '" onclick="viewItem(\'' + filteredProds[i].productURL + '\');return false;" href="' + filteredProds[i].productURL + '"><img src="' + filteredProds[i].image + '" alt="' + filteredProds[i].name + '"/></a></div>';      
        data += '<div class="details clearfix"><div class="name"><a id="PRODUCTLINK_' + i + '" onclick="viewItem(\'' + filteredProds[i].productURL + '\');return false;" href="' + filteredProds[i].productURL + '">' + filteredProds[i].name + '</a></div>';
        avgRating = filteredProds[i].avgRating;
        if (avgRating && avgRating != '0')
        {
        	data += '<div class="rating"><img src="' +  eSiteImgDir + '/reviews/stars' + filteredProds[i].avgRating + '.gif" alt="' + filteredProds[i].avgRating + '"/></div>'; 
        }
        data += filteredProds[i].displayPrice;        
         
        data += '</div></div>';
    
    	if ((i+1) % MAX_ITEM_PER_ROWS == 0)
    	{
    		data += '<div class="clear"></div>';	
    	}
    }
    
    data += '<div class="clear"></div>';
    
    // insert product data on the page
    var results = dojo.byId('results');
    
    if (results)
    {
    	bec.util.html.set(results, data);
    	enableQuickViewHover();
    	button.enhanceAll();
    	productCompare.clear();
    	if (filteredProds.length == 0)
    	{
    		 bec.util.html.showNode('noResults');
    	}
    	 buildPagination();
    }
    else
    {
    	alert('Error loading category page');
    }
}

/**
 * Get a string of all attributes
 */
function convertAttrToString(attributes)
{
    var data = '';
    if (attributes)
    {
	    for (var i=0; i< attributes.length; i++)
	    {
	        data +=  attributes[i] + ' ';
	    }
	}
    
    return data;
}

/**
 * Filter the products based on the filter value selected
 */
function filter()
{ 
	bec.util.html.hideNode('clearAllFacets');
	
	var value = getFilterValue("filterSelect");
	
	updateSelected("filterSelect", value);
	
    if (value && value.length <= 0)
    {
        filteredProducts = products;    
    }
    else
    {
        // filter the products
        filteredProducts = new Array();
        
        var a;
        for (var i=0; i< products.length; i++)
        {
            if (products[i].strAttributes == '' && (products[i].attributes && products[i].attributes.length > 0))
            {
            	products[i].strAttributes = convertAttrToString(products[i].attributes);
            }
            
            var f = 0;
            for (var j=0; j < value.length; j++)
            {
	            if (products[i].strAttributes != '' && products[i].strAttributes.indexOf(value[j])>=0)
	            {
	                f++;
	            }
            }
            if (f == value.length)
            {
            	filteredProducts[filteredProducts.length++] = products[i];
            }
        }
    }
    
    // save off filtered product before filtering by price
    filteredProductByIncludeOnly = filteredProducts;
   
    return filterByPrice(filteredProducts);
}
 
function filterByPrice(products)
{
	var value = getFilterValue("filterByPrice");
	
	updateSelected("filterByPrice", value);
	
	if (value && value.length <= 0)
	{
		filteredProducts = products;
	}
	else
	{
		// filter the products
        filteredProducts = new Array();
        
        var a;
        for (var i=0; i< products.length; i++)
        {
        	 var f = 0;
             for (var j=0; j < value.length; j++)
             {
 	            var values = eval(value[j]);
            	if (products[i].price <= values.h && products[i].price >= values.l)
 	            {
 	                f++;
 	            }
             }
             if (f > 0)
             {
             	filteredProducts[filteredProducts.length++] = products[i];
             }
        }
	}
	
	return filteredProducts;
	
}

function filterContainter(name, count)
{
	this.name = name;
	this.count = count;
}
/**
 * Build the filter list based on product filter attributes
 */
function buildFilterList()
{
	// get filterSelect object
	var filterSelect = document.getElementById("filterSelect");
	
	if (filterSelect)
	{
		// clear out the filterSelect div (remove loading image)
		filterSelect.innerHTML = '';
		var filterList = new Array();
		
		for (var i=0; i< products.length; i++)
		{
			var attributes = products[i].attributes;
			if (attributes)
			{
		     	for (var j=0; j< attributes.length; j++)
		    	{
		    		// add attr to array if not already added - otherwise just count up attrs
		    		var attr = attributes[j];
		    	
		    		if (!(attr in filterList))
		    		{
			    		filterList[attr] = {name:attr, count:1};
					}
					else
					{
						filterList[attr].count = filterList[attr].count + 1;
					}
		    	}
		    }
		}
		
		// create a normal array so we can sort
		var filterList2 = new Array();
		for (x in filterList)
		{
			filterList2[filterList2.length++] = new filterContainter(filterList[x].name, filterList[x].count); 	
		}
		
		if (filterList2.length > 0)
		{
			// sort by count desc
			filterList2.sort(sortByCountDesc);
			
			// grap the top count filter attributes up to the max allowed (8)
			var filterList3 = filterList2.slice(0,MAX_FILTER_COUNT);
			
			// now sort by name
			filterList3.sort(sortByName);
			
			// create select options from filtered double sorted attribute list
			createViewAllCheckbox('filterSelect');
			
			var filterList3Length = filterList3.length;
			if (filterList3Length > 24)
			{
				// make sure we always have 3 columns
				numberOfFiltersPerColumn = Math.ceil(filterList3Length / 3);
			}
			
			var sText;
			for (var x=0; x<filterList3Length; x++)
			{
				sText = filterList3[x].name;
				createGroupedCheckbox(x, sText, filterList3[x].count, sText, 'filterSelect');
			}
		}
		else
		{
			bec.util.html.hideNode('narrowByComponentWrapper');
		}
	}
}

function getFilterValue(parent)
{
 	var returnValue = new Array();
 	
 	var parentObj = dojo.byId(parent); 
	if (parentObj)
	{
	 	dojo.forEach(dojo.query(".dijitCheckBox", parentObj), function(a)
		{ 
			var cb = dijit.byNode(a);
			
			if (cb.value != 'View All')
			{
				if (cb.checked)
		 		{
					returnValue.push(cb.value);
					// add the selected value to the hash
					hashString += cb.value;
		 		}
			}
	 	}, this);
	}
 	
    return returnValue;
}

function removeFacetFilter(parent, value)
{
	var parentObj = dojo.byId(parent); 
	if (parentObj)
	{
		var removed = false;
	 	dojo.forEach(dojo.query(".dijitCheckBox", parentObj), function(a)
		{ 
			var cb = dijit.byNode(a);
			
			if (cb.value == value && cb.checked)
			{
				cb.attr('checked', false);
				removed = true;
			}
	 	}, this);
	
	 	if (removed)
	 	{
	 		displayProductsByPage(1);
	 	}
	}
}

function closeFacet(id)
{
	try
	{
		dijit.byId(id).closeDropDown();
	}
	catch(e)
	{}
}

function checkViewAll(parent)
{
	var parentObj = dojo.byId(parent); 
	if (parentObj)
	{
	 	dojo.forEach(dojo.query(".dijitCheckBox", parentObj), function(a)
		{ 
			var cb = dijit.byNode(a);
			
			if (cb.value == 'View All')
			{
				cb.attr('checked', true);
			}
	 	}, this);
	}
}

function updateSelected(parent, value)
{
	var selectedText = '';
	var selectedObj = dojo.byId(parent + 'Selected');
	if (selectedObj)
	{
		var num = value.length;
		for (i=0; i < num; i++)
		{
			if (parent == 'filterByPrice')
			{
				var values = eval( value[i]);
				selectedText += '<div class="clearfix"><div class="item left">$' + values.l + ' - $' + values.h + '</div><div class="left"><a class="close" onclick="removeFacetFilter(\'' + parent + '\', \'' + value[i] + '\'); return false;"></a>' +'</div></div>';
			}
			else
			{
				selectedText += '<div class="clearfix"><div class="item left">' + value[i] + '</div><div class="left"><a class="close" onclick="removeFacetFilter(\'' + parent + '\', \'' + value[i] + '\'); return false;"></a>' +'</div></div>';
			}
		}
		bec.util.html.set(selectedObj, selectedText);
		if (num == 0)
		{
			checkViewAll(parent);
			bec.util.html.hideNode(selectedObj);
		}
		else
		{
			bec.util.html.showNode('clearAllFacets');
			bec.util.html.showNode(selectedObj);
		}
	}
}

function clearAllFacets()
{
	checkViewAll('filterSelect');
	checkViewAll('filterByPrice');
}

function clearFilters()
{
	var reload1 = clearFilter('filterSelect');
	var reload2 = clearFilter('filterByPrice');
	
	if (reload1 || reload2)
	{
		displayProductsByPage(1);
	}
}
function clearFilter(parent)
{
	var parentObj = dojo.byId(parent); 
	if (parentObj)
	{
		var reload = false;
		disableDisplay = true;
		dojo.forEach(dojo.query(".dijitCheckBox", parentObj), function(a)
		{ 
			var cb = dijit.byNode(a);
			if (cb.value != 'View All')
			{
				if (cb.checked)
				{
					cb.attr('checked', false);
					reload = true;
				}
			}
		}, this);
		disableDisplay = false;
	}
	return reload;
}

function clearViewAllFilter(parent)
{
	var parentObj = dojo.byId(parent); 
	if (parentObj)
	{
		dojo.forEach(dojo.query(".dijitCheckBox", parentObj), function(a)
		{ 
			var cb = dijit.byNode(a);
			if (cb.value == 'View All')
			{
				if (cb.checked)
				{
					cb.attr('checked', false);
				}
			}
		}, this);	
	}
}

var cbGroup;
function createGroupedCheckbox(i, sText, sCount, value, parent)
{
	var group = false;
	if ((i % numberOfFiltersPerColumn) == 0)
	{
		group = true;
	}
	
	if (group)
	{
		var parentObj = dojo.byId(parent);
		if (parentObj)
		{
			cbGroup = dojo.doc.createElement("div"); //global - so we can add multiple to group
			dojo.addClass(cbGroup, 'group left');
			
			dojo.place(cbGroup, parentObj, 'last');
			
			createCheckbox(i, sText, sCount, value, cbGroup, parent);
		}
	}
	else
	{
		if (cbGroup)
		{
			createCheckbox(i, sText, sCount, value, cbGroup, parent);
		}
		else
		{
			createCheckbox(i, sText, sCount, value, parent, parent);
		}
	}
}

function createCheckbox(i, sText, sCount, value, parent, container) 
{  
	if (!container)
	{
		container = parent;
	}
	var parentObj = dojo.byId(parent);
	if (parentObj)
	{
		var idCB = parent + 'CB'+ i;
		
		var checkBox = new dijit.form.CheckBox({
			 id: idCB,
			 name: idCB,
	         value: value,
	         checked: false,
	         onChange: function(b) {
				if (container && b)
				{
					clearViewAllFilter(container);
				}
				changeFilter();
	         }
	     },
	     "checkbox1");
		
		var cbContainer = dojo.doc.createElement("div");
		dojo.addClass(cbContainer, 'cbWrapper');
		var idCBL = idCB + 'label';
		var sTextwCount = sText + ' (' + sCount + ')';
		var cbLabel = dojo.create('label', {'for':idCB, 'innerHTML':sTextwCount, 'id':idCBL, 'title': sText});
		
		// add checkbox and label 
		dojo.place(checkBox.domNode, cbContainer, 'last');
		dojo.place(cbLabel, cbContainer, 'last');
		// add the container to parent
		dojo.place(cbContainer, parentObj, 'last');
	}
}

function createViewAllCheckbox(parent) 
{  
	var parentObj = dojo.byId(parent);
	if (parentObj)
	{
		var idCB = parent + 'CB-viewall';
		
		var checkBox = new dijit.form.CheckBox(
		{
			 id: idCB,
			 name: idCB,
	         value: 'View All',
	         checked: true,
	         onChange: function(b) 
	         {	
				if (b && clearFilter(parent))
				{
					displayProductsByPage(1);
				}
	         },
	         onClick: function(e)
	         {
	        	if (e)
	        	{
	        		if (!this.attr('checked'))
	        		{
	        			this.attr('checked', true);
	        		}
	        	}
	         }
	     },
	     "checkbox1");
		
		var cbContainer = dojo.doc.createElement("div");
		dojo.addClass(cbContainer, 'cbWrapper');
		dojo.addClass(cbContainer, 'view-all');
		var idCBL = idCB + 'label';
		//var sTextwCount = sText + ' (' + sCount + ')';
		var cbLabel = dojo.create('label', {'for':idCB, 'innerHTML':'View All', 'id':idCBL, 'title': 'View All'});
		
		// add checkbox and label 
		dojo.place(checkBox.domNode, cbContainer, 'last');
		dojo.place(cbLabel, cbContainer, 'last');
		// add the container to parent
		dojo.place(cbContainer, parentObj, 'last');
	}
}

function createByPriceFilter()
{
	if (storeId == '10355')
	{
		//WF
		createCheckbox(1, '$20 and Under', '0', '({l:0,h:20})', 'filterByPrice');
		createCheckbox(2, '$20 - $30', '0', '({l:20,h:30})', 'filterByPrice');
		createCheckbox(3, '$30 - $50', '0', '({l:30,h:50})', 'filterByPrice');
		createCheckbox(4, 'Over $50', '0', '({l:50,h:999})', 'filterByPrice');
	}
	else if (storeId == '10255')
	{
		//CU
		createCheckbox(1, '$30 and Under', '0', '({l:0,h:30})', 'filterByPrice');
		createCheckbox(2, '$30 - $40', '0', '({l:30,h:40})', 'filterByPrice');
		createCheckbox(3, '$40 - $50', '0', '({l:40,h:50})', 'filterByPrice');
		createCheckbox(4, '$50 - $60', '0', '({l:50,h:60})', 'filterByPrice');
		createCheckbox(5, 'Over $60', '0', '({l:60,h:999})', 'filterByPrice');
	}
	else
	{
		//HD
		createViewAllCheckbox('filterByPrice');
		createCheckbox(1, 'Under $30', '0', '({l:0,h:30})', 'filterByPrice');
		createCheckbox(2, '$30 - $40', '0', '({l:30,h:40})', 'filterByPrice');
		createCheckbox(3, '$40 - $50', '0', '({l:40,h:50})', 'filterByPrice');
		createCheckbox(4, '$50 - $75', '0', '({l:50,h:75})', 'filterByPrice');
		createCheckbox(5, '$75 - $100', '0', '({l:75,h:100})', 'filterByPrice');
		createCheckbox(6, '$100 - $200', '0', '({l:100,h:200})', 'filterByPrice');
		createCheckbox(7, 'Over $200', '0', '({l:200,h:999})', 'filterByPrice');
	}
	
	updatePriceFilters();
}

function viewItem(url)
{
    bec.util.browser.gotoURLWithHash(url);
}

function buildPagination()
{
	if (getFilteredProducts().length > 0)
	{
		var VIEWALL_MODE = false;
		var numberOfResultsPerPage = MAX_ITEM_PER_ROWS * MAX_ROWS;
		var numberOfPages = Math.floor(getFilteredProducts().length / numberOfResultsPerPage);	
		if (numberOfPages <= 0)
		{
			numberOfPages = 1;	
		}
		if (getFilteredProducts().length > (numberOfResultsPerPage * numberOfPages))
		{
			numberOfPages++;
		}
		
		// save the fact that we are in view all mode
		if (currentPage == VIEW_ALL)
		{
			VIEWALL_MODE = true;
		}
		
		if (currentPage > numberOfPages)
		{
			currentPage = 1;	
		}
		
		var data = '';
		//add link to send items to compare to compare page
		
		// previous page link
		if (currentPage > 1)
		{
			data += '&nbsp;<a href="#" onclick="changePage(' + (currentPage - 1) + '); return false;" class="sprite-pager-left" title="Previous"></a>&nbsp;&nbsp;';
		}
		
		data += ' <span class="colored">Page&nbsp;</span> ';
		
		// determine the pages in pagination to show 
		// (scrolling pages - only show MAX_PAGES(4) at a time
		var startPage = 1;
		var endPage = numberOfPages;
		
		// set max pages to show
		if (numberOfPages > MAX_PAGES)
		{
			endPage = MAX_PAGES;
		}
		// scroll the pages
		if (currentPage >=  MAX_PAGES)
		{
			startPage = currentPage - MAX_PAGES + 2;
			endPage = startPage + MAX_PAGES - 1;
			if (endPage > numberOfPages)
			{
				endPage = numberOfPages;
				if (startPage > 1)
				{
					startPage = startPage - 1;
				}
			}
		}
		
		// page numbers
		for (var i=startPage; i <=endPage; i++)
		{
			if (i == currentPage && !VIEWALL_MODE)
			{
				data += '<span class="activePage">';
			}
			else
			{
				data += '<a href="#" onclick="changePage(' + i + '); return false;">'
			}
			
			data += i;
			
			if (i == currentPage && !VIEWALL_MODE)
			{
				data += '</span>';
			}
			else
			{
				data += '</a>'
			}	
			
			if (i < endPage)
			{
				data += '&nbsp;&nbsp;';
			}
		}
		
		// next page link
		if (currentPage < numberOfPages)
		{
			data += '&nbsp;&nbsp;<a href="#" onclick="changePage(' + (currentPage + 1) + '); return false;" class="sprite-pager-right" title="Next"></a>&nbsp;';
		}
		
		// view all
		if (numberOfPages > 1)
		{
			data += '&nbsp;&nbsp;';
			
			// view all
			if (VIEWALL_MODE)
			{
				data += '<span class="activePage">';
			}
			else
			{
				data += '<a href="#" onclick="changePage(' + VIEW_ALL + '); return false;">';
			}
			
			data += 'View All';
			
			if (VIEWALL_MODE)
			{
				data += '</span>';
			}
			else
			{
				data += '</a>';
			}
		}
		
		// put the pagination on the page
		//$("#pagination").html(data);
		//$("#paginationFooter").html(data);
		bec.util.html.set('pagination', data);
		bec.util.html.set('paginationFooter', data);
	}
}

function toggleCategories()
{
	var hiddenCatList = dojo.byId('hiddenCategories');
	var hiddenCatLink = dojo.byId('hideCategoryText');
	
	if (hiddenCatList && hiddenCatList.style.display == 'none')
	{
		dojo.style(hiddenCatList, "display", "block");
		bec.util.html.set(hiddenCatLink, "Hide Categories");
		//hiddenCatLink.innerHTML = "Hide Categories";
	}
	else
	{
		dojo.style(hiddenCatList, "display", "none");
		bec.util.html.set(hiddenCatLink, "See More Categories");
		//hiddenCatLink.innerHTML = "See More Categories";
	}
}

/**
 * Coremetrics - create coremetric selection criteria element tag  
 */
function trackCategorySelectionCriteria(byPriceFilterValue, byComponentFilterValue, sortBy, page)
{	
	try
	{
		if(isCoremetricOn())
		{	
			var cmPVAttributes = cmAttributes;
			var sortByAttribute = "";
			
			if(page == VIEW_ALL)
			{
				sortByAttribute += cm_merch_cat + ": VIEW ALL";
			}
			else
            {
				sortByAttribute += sortBy;
			}
			
			// Create pageView tag for "by Price" filter
			var byPriceAttribute = "";
			if(byPriceFilterValue != undefined)
			{
				byPriceAttribute = byPriceFilterValue;
			}
			
			// Create pageView tag for "by Component" filter
			var byCompAttribute = "";
			if(byComponentFilterValue != undefined)
			{
				byCompAttribute = byComponentFilterValue;
			}
			
			cmPVAttributes = cmPVAttributes + "-_-" + byPriceAttribute + "-_-" + sortByAttribute + "-_-" + byCompAttribute; 
			// TODO: Expand to support alternative filters (by Occasion, by SubCat...)
			
			cmInitiatePageViewTag(cmPageName,cmCategory,null,null,cmPVAttributes);
		}
	}
	catch(e){}
}

function isCoremetricOn()
{
	return cmPassCoremetrics != 'OFF';
}

/**************************************
 * Club Category Template functions
 */
function displayClubProduct(counter) 	
{
	try
	{
		var clubURL = dojo.byId('clubSelect_' + counter); 
		if (clubURL)
    	{	
			bec.util.browser.gotoURL(clubURL.value);
    	}
	}
	catch(e){}
}

/**
 * Add hover effect for Left Nav in IE6 
 */
function addHoverToLeftNavIE6()
{
	try
	{
		$('#navigation a').hover(function(){
			$(this).parent().addClass('hover');
		}, function(){
			$(this).parent().removeClass('hover');
		});
	}
	catch(e){}
}

