﻿var DDSPEED = 10;
var DDTIMER = 15;
var MMDELAY = 500;
var MMTIMER = 10;

var lastMenuViewed;

/*-Menu--------------------------------------------------------------------------------*/
function getMenuCategory()
{
	var pCat = $get('pCat');
	if( pCat !== null )
		return pCat.value;
	else
		return getSearchStringValue('categoryName');	
}
function initMenu(){
	//Setup the event handlers:
	var menuLinks = $get('menuContent').getElementsByTagName('li');
	if( menuLinks !== null )
		for(var i = 0; i < menuLinks.length; i++)
			menuLinks[i].onclick = mClick;
			
	//Set the onhover event handlers for the top level menu (dept)
	$("#menuContent dt").hover(function() {
        $(this).addClass("highlight").stop();
    }, function() {
        $(this).removeClass("highlight").stop();
    });

	//inner menu (Aisle):
	$("#menuContent li").hover(function() {
        $(this).addClass("highlight").stop();
    }, function() {
        $(this).removeClass("highlight").stop();
    });

	//Now open the menu in the correct position:
	var catName = getMenuCategory();
	if( catName !== '' ){
		//Find the correct aisle:
		if( menuLinks !== null )
			for(var i = 0; i < menuLinks.length; i++){
				var cat = menuLinks[i].getAttribute('cat');
				if( cat == catName ){
					//Set the ListItem's (containing this link) class to be selected (to highlight it)
					$(menuLinks[i]).addClass("selected") ;
					
					//Go back up the tree li > ul > dt
					var name = menuLinks[i].parentNode.parentNode.id;
					//get the item number from the ID in the format: ddc{n}
					var num = parseInt(name.substr(3));

					lastMenuViewed = num;
					openMenu(num);
					break;
				}
			}
		//Find the correct department:
		var menuHeaders = $get('menuContent').getElementsByTagName('dt');
		if( menuHeaders !== null )
			for(var i = 0; i < menuHeaders.length; i++){
				var cat = menuHeaders[i].getAttribute('cat');
				if( cat == catName ){
					//Get the name of the header node
					var name = menuHeaders[i].id;
					//get the item number from the ID in the format: ddc{n}
					var num = parseInt(name.substr(3));

					lastMenuViewed = num;
					openMenu(num);
					break;
				}
			}		
	}
}
function mClick()
{
	var retUrl = $get('menuUrl').value;
	var cat = this.getAttribute('cat');
	window.location.href = retUrl.replace('{0}', cat);
}
function openMenu(row){
	var c = $get('ddc' + row);
	if( c )	{
		//Allow the menu expand to the correct height
		c.style['display'] = 'block';
		c.style['height'] = 'auto';
		
		//Check that we have set a max height
		if(!c.maxh){
			c.maxh = c.offsetHeight;
		}
		c.style['height'] = c.maxh + 'px';
		c.style['opacity'] ='1.0';
		c.style['filter'] ='alpha(opacity=100)';

		setHiglight($get('ddh' + row), true);
		
		// Refresh the image menu to display the aisles of the chosen department
		var h = $get('ddh' + row);
		var obj = $get('hdnCategory');
		if ( h && obj ) {
	        var cat = $(h).attr("cat");
	        obj.value = cat;
	        __doPostBack("updImageMenuControl", "");
		}
	}
}
function closeMenu(row){
	var h = document.getElementById('ddh' + row);
	var c = document.getElementById('ddc' + row);
	if( c && h ){
		var ctrl = $get('ddh'+(row+1))
		if(ctrl !== null)ctrl.style['borderTop'] = '';
		clearTimeout(c.timer);
		setHiglight(h, false);
		//wait 50ms before running the collapse function
		h.timer = setTimeout(function(){ddCollapse(c,row)},50);
	}
}
function mToggle(id){
	//If the last menu viewed wasn't this one then close it.
	if( id !== lastMenuViewed ){
		//close the last menu opened
		closeMenu(lastMenuViewed);
		//store the new id
		lastMenuViewed = id;
	}
	var h = document.getElementById('ddh' + id);
	var c = document.getElementById('ddc' + id);
	if(!c.maxh){
		c.style['display'] = 'block';
		c.style['height'] = 'auto';
		c.maxh = c.offsetHeight - 1;
		c.style['height'] = '0px';
	}
	var direction;
	if(c.style['height'] == '0px') direction = 'D';
	else direction = 'U';
  
	if(direction == 'D'){
		clearTimeout(h.timer);
		if(c.maxh && c.maxh <= c.offsetHeight){return}
		setHiglight(h, true);
		c.style['display'] = "block";
		c.timer = setInterval(function(){ddSlide(c,1,id)},DDTIMER);
	}else{
		//Remove the balck top border fromthe next item down
		var ctrl = $get('ddh'+(id+1));
		if(ctrl !== null)ctrl.style['borderTop'] = '';
	
		clearTimeout(c.timer);
		setHiglight(h, false);
		//wait 50ms before running the collapse function
		h.timer = setTimeout(function(){ddCollapse(c,id)},50);
	}

    // Ensures image menu is updated following menu click
    var obj = document.getElementById("hdnCategory");
    if (obj != null)
    {
	    if (direction == 'D') {
            var cat = $(h).attr("cat");
            obj.value = cat;
	    } else {
            obj.value = "";
	    }
        __doPostBack("updImageMenuControl", "");
    }
}
function ddSlide(c,d,id){
	var maxh = c.maxh;
	//var currh = c.offsetHeight;
	var currh = parseInt(c.style['height']);
	var dist;
	if(d == 1){
		dist = (Math.round((c.maxh - currh) / DDSPEED));
	}else{
		dist = (Math.ceil(currh / DDSPEED));
	}
	if(dist <= 1 && d == 1) { dist = 1; }
	//vertSlideMenuItems(id+1,dist);
	c.style['height']  = currh + (dist * d) + 'px';
	c.style['opacity'] = currh/c.maxh;
	c.style['filter']  = 'alpha(opacity=' + (currh * 100 / c.maxh) + ')';
	if((currh < 1) && (d != 1)){
		c.style['display'] = "none";
		clearInterval(c.timer);
	}
	if ((currh >= c.maxh) && (d == 1)){
		clearInterval(c.timer);
	}
}
function ddCollapse(c, id){ 
	c.timer = setInterval(function(){ddSlide(c,-1,id)},DDTIMER); 
}
function setHiglight(c, really){
	if(c !== null) {
		if(really == true){
		    $(c).addClass("selected");
		}else{
		    $(c).removeClass();
		}
	}
}
/*-Filters-----------------------------------------------------------------------------*/
function initFilterManager(){
	//Show the top row of filters	
	var fr = $get('filterRollup');
	if( fr !== null ){
		//var minh = 0;
		var fbs = getElementsByClass('filterBlock', fr, 'div');
		for(var i = 0; i < fbs.length; i++){
			fbs[i].style['display'] = '';
			fbs[i].style.zIndex = 1;

			//assign the filter Unfocus command to the mouseOut event of the filterRollup
			var ul = fbs[i].getElementsByTagName('ul')[0];
			ul.onmouseout = function(e){
				if (!e) {e = window.event;}
				if( checkMouseLeave(e, this) ) filterUnFocus(e, this);
			}
			
			//assign the filter focus command to the "Show more..." list item
			var lis = fbs[i].getElementsByTagName('li');
			for (var j = 0; j < lis.length; j++) 
				if( lis[j].getAttribute("fi") == "sfbtn")
					lis[j].onmouseover = filterFocus;
		}
		hideFilterBtnToggle(false);
	}
}
function ShowAllFilerOptions(filterID){
	var fr = $get(filterID);
	if( fr !== null ){
		fr.style['position'] = "relative"; 
		fr.style['float'] = "none";
		
		var ul = fr.getElementsByTagName('ul')[0];
		ul.onmouseout = '';
		
		var lis = fr.getElementsByTagName('li');
		for(var i = 0; i < lis.length; i++){
			switch(lis[i].getAttribute('fi')){
				case "sfbtn":
				case "hfb":
					lis[i].style['display'] = 'none';
					break;
				case "hfi":
				case "afi":
					lis[i].style['display'] = '';
					break;
				default:
					break;
			}
		}
	}
}
//Called when the 'choose more...' list item is clicked/hovered over
function filterFocus() {
	//Refrence to the filterBlock
	var fB = this.parentNode.parentNode;

	//For IE <= 6
	if( IsIEv6orBefore ){
		fB.parentNode.style.position = 'fixed';
		fB.parentNode.style.zIndex = 10001;
	}

	//Make sure the filterBlock is above all other filter blocks
	fB.style.zIndex = 10002;
	fB.style['border'] = "solid 1px #a2c3f6";
	fB.style['position'] = 'absolute';

	//Hide the 'show more...' list item
	this.style['display'] = 'none';
	
	var lis = this.parentNode.getElementsByTagName('li');
	for (var i = 0; i < lis.length; i++){
		switch(lis[i].getAttribute('fi')){
			case "afi":
			case "sfbtn":
				lis[i].style['display'] = 'none';
				break;
			case "hfb":
			case "hfi":
				lis[i].style['display'] = '';
				break;
			default:
				break;
		}
	}
	//For IE <= 6
    if( this.parentElement )
		placeShimBehindElem(this.parentElement.parentElement);
}

//this is called as the div is rolled off by filterBlock>ul
function filterUnFocus(e, node) {
	//For IE <= 6
	if( node.parentElement !== null )
		removeShimFromBehindElement(node.parentElement);
	
	//Table cell:
	node.parentNode.parentNode.style.zIndex = 1;
	
	//filterBlock:
	node.parentNode.style.zIndex = 1;
	node.parentNode.style['position'] = 'static'; 
	//Reset the border to being the same as the background
	var bkCol = getStyle(node.parentNode, 'background-color');
	node.parentNode.style['border'] = 'solid 1px ' + bkCol;
	
	var lis = node.getElementsByTagName('li');
	for (var i = 0; i < lis.length; i++){
		switch(lis[i].getAttribute('fi')){
			case "sfbtn":
				lis[i].style['display'] = '';
				break;
			case "hfb":
			case "afi":
			case "hfi":
				lis[i].style['display'] = 'none';
				break;
			default:
				break;
		}
	}
}
function hideFilterBtnToggle(displayHideBtn){
	var showFs = $get('showFs');
	if(showFs !== null) 
		showFs.style['display'] = displayHideBtn ? 'none' : '';
	var hideFs = $get('hideFs');
	if(hideFs !== null) 
		hideFs.style['display'] = displayHideBtn ? '' : 'none';
}
function hideFilterRows(){
	var fr = $get('filterRollup');
	if( fr !== null )
	{
		var trs = fr.getElementsByTagName('tr');
		if( trs !== null )
		{
			if(trs.length > 1)
				for(var i = 1; i < trs.length; i++)
					trs[i].style['display'] = 'none';
				
			hideFilterBtnToggle(false);
		}
	}
}
function showFilterRows(){
	var trs = $get('filterRollup').getElementsByTagName('tr');
	if( trs !== null ){
		if(trs.length > 1)
			for(var i = 1; i < trs.length; i++)
				trs[i].style['display'] = '';
			
		hideFilterBtnToggle(true);
	}
}
function addPriceFilter(minPrice, maxPrice){
	window.location.href = insertUrlSearchTerm(window.location.href, 'pr', minPrice + '|' + maxPrice );
}
function addFilter(filterID){
	var value = getSearchStringValue('flt');
	if(value !== '')	{
		var fltIds = value.split('|');
		var i=fltIds.length; 
		var x; 
		while(i--){
			if( fltIds[i] == filterID )	break;
		}
		if(i<0) {
			fltIds[fltIds.length] = filterID;
			value = (fltIds.length > 1) ? fltIds.join('|') : fltIds[0];
		}
	}else{
		value = filterID;
	}
	var url = removeUrlSearchTerm(window.location.href, 'pageIndex' );
	window.location.href = insertUrlSearchTerm(url, 'flt', value );
}
function removeFilter( filterID ){
	var url = removeUrlSearchTerm(window.location.href, 'pageIndex' );
	
	var pr = getSearchStringValue('pr');
	if( pr != '' ){
		url = removeUrlSearchTerm(url, 'pr' );
	}

	var value = getSearchStringValue('flt');
	if(value !== '')	{
		var fltIds = value.split('|');
		var i=0; 
		var newFltIds = new Array();
		
		while( i < fltIds.length ){
			if( fltIds[i] == filterID ){
				//Copy the selected one too...
				newFltIds[i] = fltIds[i];
				break;
			}
			newFltIds[i] = fltIds[i];
			i++;
		}
		
		if( newFltIds.length == 0 ) 
			window.location.href = removeUrlSearchTerm(url, 'flt' );
		else
			window.location.href = insertUrlSearchTerm(url, 'flt', newFltIds.join('|') );
    }
}
function removeAllFilters(  ){
    var url = removeUrlSearchTerm(window.location.href, 'flt');
    url = removeUrlSearchTerm(url, 'pageIndex' );
   	window.location.href = removeUrlSearchTerm(url, 'pr');
}
/*-Search-Results----------------------------------------------------------------------*/
function changeSort(name){
	var selSort = document.getElementById(name);
	var values = selSort[selSort.selectedIndex].value.split(';');
	var newUrl = insertUrlSearchTerm(window.location.href, 'sortField', values[0] );
	newUrl = removeUrlSearchTerm(newUrl, 'pageIndex');
	window.location.href = insertUrlSearchTerm( newUrl, 'SortDirection', values[1] );
}		  
function changeGrouping(name){
	var selGroup = document.getElementById(name);
	var value = selGroup[selGroup.selectedIndex].value;
	if(value == 0){
		var newUrl = removeUrlSearchTerm(window.location.href, 'pageIndex');
		window.location.href = insertUrlSearchTerm(newUrl, 'view', 'UnGrouped' );
	}else{
		if( value == 1 ){
			var newUrl = removeUrlSearchTerm(window.location.href, 'pageIndex');
			window.location.href = insertUrlSearchTerm( newUrl, 'view', 'GroupedByShelf' );
		}
	}
}
/*-Main-Menu---------------------------------------------------------------------------*/
function initMainMenu(){
	var selTabId = null;
	var tabs = document.getElementById('MainTabs').getElementsByTagName('li');
	if( tabs != null ){
		for(var i = 0; i < tabs.length; i++)
		{
			tabs[i].onmouseover = function(e){
				var tab = this;
				SetHoverClassForTab(tab);
				ShowSubMenu(tab);
			};
			tabs[i].onmouseout = function(e){
				var tab = this;
				if (!e) {e = window.event;}
				if( checkMouseLeave(e, tab) ) {
				    
					removeCssClass(tab, 'lihover');
					
					var tabSubMenu = document.getElementById(tab.id + 'subm');
					
					if( tabSubMenu != null ){
			    	    //For IE <= 6
        	            removeShimFromBehindElement(tabSubMenu);
    					
					    HideControl(tabSubMenu);
					}
				}
			};		
		}
	}
			
	var subMenus = getElementsByClass('opt', document.getElementById('MainTabs'), 'div');
	if( subMenus != null ){
		for(var i = 0; i < subMenus.length; i++)
		{
		    //Assign the rolloff hide command when the block looses focus
			subMenus[i].onmouseout = function(e){
				var subMenu = this;
				if (!e) {e = window.event;}
				if( checkMouseLeave(e, subMenu) ) {
				    //Remove the hover class from the parent tab:
					removeCssClass(subMenu.parentNode, 'lihover');
					
			    	//For IE <= 6
        	        removeShimFromBehindElement(subMenu);
					
					HideControl(subMenu);
				}
			}
		}
	}
}
function HideControl(control)
{
    if( control != null )
        control.style['display'] = 'none';
}
function SetHoverClassForTab(tab){
	var tabs = document.getElementById('MainTabs').getElementsByTagName('li');
	if ( tabs != null ){
		for (var i = 0; i < tabs.length; i++){
			//Leave this tab alone:
			if( tabs[i] == tab ) {
			    addCssClass(tabs[i], 'lihover');
            }else{
                removeCssClass(tabs[i], 'lihover');
            }
		}
	}
}
function HideAllSubMenus(forAllButThisOne){
    var menuOpts = getElementsByClass('opt', document.getElementById('MainTabs'), 'div');
	if ( menuOpts != null ){
		for (var i = 0; i < menuOpts.length; i++){
			//Leave this tab alone:
			if( menuOpts[i] == forAllButThisOne ) {continue;}

        	//For IE <= 6
   	        removeShimFromBehindElement(menuOpts[i]);

			removeCssClass(menuOpts[i], 'lihover');
			menuOpts[i].style.zIndex = 1;
			//Now hide it:
			HideControl(menuOpts[i]);
		}
	}
}
function ShowSubMenu(parentTab){
	if( parentTab != null ){
		var tabSubMenu = document.getElementById(parentTab.id + 'subm');
		if( tabSubMenu != null ){
			tabSubMenu.style.zIndex = 10003;
			tabSubMenu.style['display'] = 'block';
			
		    //For IE <= 6
    	    placeShimBehindElem(tabSubMenu);
		}
		HideAllSubMenus(tabSubMenu);
	}
}
/* Use a range from 0-1 */
function setOpacity(element, value)
{
	if( element != null )
	{
		element.style['opacity'] = value;
		element.style['filter']  = 'alpha(opacity='+ (value*100)  +')';
	}
}

function ImageMenuEndRequestHandler(sender, args)
{
    AddHoverToCategories();
    AddHoverToAisles();
    zIndexFix();
}

function AddHoverToCategories()
{
    $("dl.dropdown dt").hover(function() {

        // Add hover class to both text and image
        var cat = $(this).attr("cat");
        $("ul.imageMenu li img[cat='" + cat + "']").addClass("hover").stop();

    }, function() {

        // Remove hover class from both text and image
        var cat = $(this).attr("cat");
        $("ul.imageMenu li img[cat='" + cat + "']").removeClass("hover").stop();

    });

    $("ul.imageMenu li img").hover(function() {

        // Add hover class to both text and image
        var cat = $(this).attr("cat");
        $(this).addClass("hover").stop();
        $("dl.dropdown dt[cat='" + cat + "']").addClass("highlight").stop();

    }, function() {

        // Remove hover class from both text and image
        var cat = $(this).attr("cat");
        $(this).removeClass("hover").stop();
        $("dl.dropdown dt[cat='" + cat + "']").removeClass("highlight").stop();

    });
    
    $("ul.imageMenu li a").hover(function() {
    
        // Add hover class to both text and image
        var cat = $(this).attr("cat");
        $("dl.dropdown dt[cat='" + cat + "']").addClass("highlight").stop();
        $("ul.imageMenu li img[cat='" + cat + "']").addClass("hover").stop();
        
    }, function() {
    
        // Remove hover class from both text and image
        var cat = $(this).attr("cat");
        $("dl.dropdown dt[cat='" + cat + "']").removeClass("highlight").stop();
        $("ul.imageMenu li img[cat='" + cat + "']").removeClass("hover").stop();
            
    });
}

function AddHoverToAisles()
{
    $("dl.dropdown dd ul li").hover(function() {

        // Add hover class to both text and image
        var cat = $(this).attr("cat");
        $("ul.imageMenu li img[cat='" + cat + "']").addClass("hover").stop();

    }, function() {

        // Remove hover class from both text and image
        var cat = $(this).attr("cat");
        $("ul.imageMenu li img[cat='" + cat + "']").removeClass("hover").stop();

    });

    $("ul.imageMenu li img").hover(function() {

        // Add hover class to both text and image
        var cat = $(this).attr("cat");
        $(this).addClass("hover").stop();
        $("dl.dropdown dd ul li[cat='" + cat + "']").addClass("highlight").stop();

    }, function() {

        // Remove hover class from both text and image
        var cat = $(this).attr("cat");
        $(this).removeClass("hover").stop();
        $("dl.dropdown dd ul li[cat='" + cat + "']").removeClass("highlight").stop();

    });                
    
    $("ul.imageMenu li a").hover(function() {
    
        // Add hover class to both text and image
        var cat = $(this).attr("cat");
        $("dl.dropdown dd ul li[cat='" + cat + "']").addClass("highlight").stop();
        $("ul.imageMenu li img[cat='" + cat + "']").addClass("hover").stop();
        
    }, function() {
    
        // Remove hover class from both text and image
        var cat = $(this).attr("cat");
        $("dl.dropdown dd ul li[cat='" + cat + "']").removeClass("highlight").stop();
        $("ul.imageMenu li img[cat='" + cat + "']").removeClass("hover").stop();
            
    });
}

function mImageClick(cat)
{
	var retUrl = $get('menuUrl').value;
    window.location.href = retUrl.replace('{0}', cat);
}

function mImageToggle(cat)
{
    var obj = $("dl.dropdown dt[cat='" + cat + "']");
    
    // Strip any unwanted characters from the id
    var id = $(obj).attr("id").replace("ddh", "").replace("ddc", "");
    
    // Must pass a number variable type
    mToggle( parseInt(id) );
}

