// categoryProduct.js - used to store products for the category pages
// - provides ability to filter and sort products on the category page
var products = new Array();
var filteredProducts;
var currentPage = 1;
var cp_parentIdentifier = '';
var cp_identifier = '';
var openedQuickView;
var openedQuickViewProduct;

var MAX_ITEM_PER_ROWS = 3;
var MAX_ROWS = 4;
var VIEW_ALL = 999;
var MAX_FILTER_COUNT = 8;
var MAX_PAGES = 3;
var IMAGE_WIDTH = 230;
var IMAGE_HEIGHT = 230;

/**
 * Product instance - 
 * These are created in BECCategoryProduct.jspf
 */
function product(name, image, displayPrice, price, rating, attributes, best, productURL, id, partNumber)
{
    this.name = name;
    this.image = image;
    this.displayPrice = displayPrice;
    this.price = price;
    this.rating = 0;
    if (rating != '')
    {
    	this.rating = rating;
    }
    
    this.attributes = attributes;
    this.best = best;
    this.productURL = productURL;
    this.id = id;
    this.partNumber = partNumber;
    this.strAttributes = '';
}

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.rating;
    var y = b.rating;
    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 displayProducts()
{
	displayProductsByPage(currentPage);	
}

function displayProductsByPage(page)
{
	 //cursor_wait();
	 currentPage = page;
	 
	 var sortSelect = document.getElementById("sortBySelect");
    
     var sortValue = sortSelect[sortSelect.selectedIndex].value;
     
     if (sortValue == 'priceAsc')
     {
     	displayProductsByPrice();
     }
     else if (sortValue == 'priceDesc')
     {
     	displayProductsByPriceDesc();
     }
     else if (sortValue == 'best')
     {
     	displayProductsByBest();
     }
     else if (sortValue == 'rating')
     {
     	displayProductsByRating();
     }
     else
     {
     	// no sorting
     	displayFilteredProducts(filter(getFilterValue()));
     }
     
     buildPagination();
     //cursor_clear();
     
     // call coremetric function to track category selection criteria
     // Note: function is on BECCategoryDisplay.jsp (can we move to this JS file?)
     trackCategorySelectionCriteria (getFilterValue(), sortValue);
     
     // IE6 Hack - remove focus of narrow by and sort by - so mouse wheel scroll will not change select
     try
     {
     	$("#pagination").focus();     	
     }
     catch(e){}
}

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

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

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

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

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

/**
 * 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 quickViewUrl = 'BECProductQuickView?storeId=' + storeId + '&catalogId=' + catalogId + '&langId=' + langId + '&productId=' + product.id + '&parentIdentifier=' + cp_parentIdentifier + '&identifier=' + cp_identifier;
	
	var id = 'quickViewPopUp';
	var title = 'Product Quick View';
	
	openedQuickView = alertFloatingModalAtPosition(id, title, quickViewUrl, 600, 440, null, 'screen-center' , 10, 10, '');
	
	// save the product for coremetric tagging
	openedQuickViewProduct = product;
	
	trackProductQuickPageView();
}

/**
 * Add product to cart from the quick view
 */
function AddToCart(id)
{
	 var hiddenQuantity = document.getElementById("quantity_0");
	 var hiddenCatEntry = document.getElementById("catEntryId_0");
	 var visableQuantity = document.getElementById("quantity_" + id);
	 
	 hiddenCatEntry.value = id;
	 
	 try
	 {
	 	hiddenQuantity.value = visableQuantity.value; 
	 }catch(e)
	 {alert('Error getting quantity\n\n' + e);}
	 
	 AjaxAddToCart(document.OrderItemAddForm);
	 
	 try
	 {
	 	openedQuickView.closeWindow();
	 	trackQuickViewAddToCart(hiddenQuantity.value);
	 }
	 catch(e){}
}

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

function enableQuickViewHoverImg()
{
	try
	{
		$('.quickViewLink').hover(function(){
			$(this).find('img').attr('src', '/images/category/bt-quickview-over.gif');
		}, function(){
			$(this).find('img').attr('src', '/images/category/bt-quickview-up.gif');
		});
	}
	catch(e){}
}

/**
 * Display filtered products
 */
function displayFilteredProducts(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 = '<div id="product-display">';
    var data = '';
    for (var i=startPos; i< endPos; i++)
    { 
        data += '<div id="quickView_' + i + '" class="group">';
        data += '<div class="quickViewLink"><a href="javascript:showQuickView(' + i + ');"><img src="/images/category/bt-quickview-up.gif" border="0"></a></div>';
        data += '<div class="image"><a id="PRODUCTLINK_' + i + '" href="' + filteredProds[i].productURL + '"><img src="' + filteredProds[i].image + '" width="'+ IMAGE_WIDTH + '" height="' + IMAGE_HEIGHT + '" alt="' + filteredProds[i].name + '"/></a></div>';      
        data += '<div class="name"><a id="PRODUCTLINK_' + i + '" href="' + filteredProds[i].productURL + '">' + filteredProds[i].name + '</a></div>';
        data += filteredProds[i].displayPrice;
        if (filteredProds[i].rating != '0')
        {
        	data += '<div class="rating"><img src="/images/reviews/stars' + filteredProds[i].rating + '.gif" alt="' + filteredProds[i].rating + '"/></div>'; 
        }
        
        data += '</div>';
    
    	if ((i+1) % MAX_ITEM_PER_ROWS == 0)
    	{
    		data += '<div class="clear"></div>';	
    	}
    	else
    	{
    		data += '<div class="spacer"><img src="/images/spacer.gif"/></div>';
    	}
    }
    
    // add blank table columns for page format 
    if (filteredProds.length % MAX_ITEM_PER_ROWS != 0)
    {
		var addCols = MAX_ITEM_PER_ROWS - (filteredProds.length % MAX_ITEM_PER_ROWS);
		for (var i=0; i < addCols; i++)
		{
			data += '<div class="group"></div>';
		}
	}	
	
    //data += '</div>';
    
    // insert product data on the page
    // uses jQuery notation
    var results = $("#results");
    
    if (results)
    {
    	results.html(data);
    	enableQuickViewHover();
    	enableQuickViewHoverImg();
    }
    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(value)
{ 
    if (value == '')
    {
        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);
            }
           
            if (products[i].strAttributes != '' && products[i].strAttributes.indexOf(value)>=0)
            {
                filteredProducts[filteredProducts.length++] = products[i];   
            }
        }
     }
     
    return filteredProducts;
}

function getFilterValue()
{
    var filterSelect = document.getElementById("filterSelect");
    var returnValue = "";
    try
    {
	    if (filterSelect)
	    {
	   		returnValue = filterSelect[filterSelect.selectedIndex].value;
	    }
	}
	catch(e)
	{
		// no filter option available
	}
    
    return returnValue;
}

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)
	{
		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)
		{
			// create default option
			var newOpt = document.createElement("option");
			newOpt.value = "";
			newOpt.innerHTML = 'View Entire Selection (' + products.length + ')';
			filterSelect.appendChild(newOpt);
			
			// 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 
			for (var x=0; x<filterList3.length; x++)
			{
				// create new option
				newOpt = document.createElement("option");
				newOpt.value = filterList3[x].name;
				newOpt.innerHTML = filterList3[x].name + ' (' + filterList3[x].count + ')';
				filterSelect.appendChild(newOpt);
			}
			
			$("#narrowBy").show();
		}
		else
		{
			$("#narrowBy").hide();
		}
	}
}

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 = '';
		
		// previous page link
		if (currentPage > 1)
		{
			data += '<a href="#" onclick="displayProductsByPage(' + (currentPage - 1) + '); return false;"><img alt="Previous" src="/images/category/pager-arrow-left.gif" border=0 /></a>&nbsp;';
		}
		
		data += '&nbsp;Page&nbsp;';
		
		// 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)
			{
				data += '<b>';
			}
			else
			{
				data += '<a href="#" onclick="displayProductsByPage(' + i + ');return false;">'
			}
			
			data += i;
			
			if (i == currentPage)
			{
				data += '</b>';
			}
			else
			{
				data += '</a>'
			}	
			
			if (i < endPage)
			{
				data += '&nbsp;|&nbsp;';
			}
		}
		
		// next page link
		if (currentPage < numberOfPages)
		{
			data += '&nbsp;<a href="#" onclick="displayProductsByPage(' + (currentPage + 1) + '); return false;"><img alt="Next" src="/images/category/pager-arrow-right.gif" border=0 /></a>';
		}
		
		// view all
		if (numberOfPages > 1)
		{
			data += '&nbsp;&nbsp;';
			
			// view all
			if (VIEWALL_MODE)
			{
				data += '<b>';
			}
			else
			{
				data += '<a href="#" onclick="displayProductsByPage(' + VIEW_ALL + '); return false;">';
			}
			
			data += 'View All';
			
			if (VIEWALL_MODE)
			{
				data += '</b>';
			}
			else
			{
				data += '</a>';
			}
		}
		
		// put the pagination on the page
		//var paginationContainer = document.getElementById("pagination");
		//paginationContainer.innerHTML = data; 
		
		$("#pagination").html(data);
	}
}

/**
 * Coremetrics - Product Quick View page view tag
 */
function trackProductQuickPageView()
{
	try
   	{
   		if(isCoremetricOn())
		{ 
   			var cmProductPageTagName = 'ProductQuickView:' + openedQuickViewProduct.partNumber;
   			cmCreatePageviewTag(cmProductPageTagName, cm_merch_cat, '');
   		}
   	}
   	catch(e){}
}

/**
 * Coremetrics - create coremetric selection criteria element tag  
 */
function trackCategorySelectionCriteria(narrowBy, sortBy)
{	
	try
	{
		if(isCoremetricOn())
		{	
			var elementId = "";
			// narrow by not available on all sites
			if (narrowBy != '')
			{
				elementId += "narrow by: " + narrowBy + "; ";
			}
			elementId += "sort by: " + sortBy;
						
			//Create element tag for Selection criteria
			cmInitiateElementTag(elementId, cm_merch_cat);
		}
	}
	catch(e){}
}

/**
 * Coremetrics - Product Quick View Shop 5 tag
 */
function trackQuickViewAddToCart(qty)
{
	try
	{
		if(isCoremetricOn())
		{
		
			var cmPage = "ProductQuickViewAddedToCart";
			var cmCategory = "Item-Added-to-Cart";
			var cmItemCat = cm_merch_cat;	
			var cmItemPrice = openedQuickViewProduct.price;
			var cmItemQuant = qty;
			var cmItemNumber = openedQuickViewProduct.partNumber;
			
			cmCreateShopAction5Tag(cmItemNumber, cmItemName, cmItemQuant, cmItemPrice, cmItemCat);
			//cmDisplayShop5s();
			//cmCreatePageviewTag(cmPage, cmCategory, '');
		}
	}
	catch(e){}
}

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