var dockedBtm = false;
var resizeTimer, minmaxTimer, controlTimer,controlHiddenTimer;
var isIE6 = ($.browser.msie && $.browser.version < 7);
$('html').addClass('js');

var navAction = function()
{
	if ( oNavInfo.navhref != null )
	{
		location.href = oNavInfo.navhref;
	}
}

var historyVar;

$(document).ready(function() {
	if (oNavInfo.navMinMax == 'min') {
		minmaxChange();
	}
	setNavPosition();
	checkNavActiveSubMenu();
	menu();

	$('.js #nav, #footer').show();
	$('#snapLimit').css('height',$(window).height());

	$(window).resize(function() {
		windowHeight = $(window).height();
		windowWidth = $(window).width();
		setTimeout(windowResize, 50);
	});
	
	$('#nav').draggable( {
		zIndex:101,
		handle:'#navTop',
		containment:'#snapLimit',
		snap:'#snapLimit',
		snapTolerance:20,
		scroll:false,
		stop: function()
		{
			var navOffset = $('#nav').offset();
			saveNavPosition(navOffset.top, navOffset.left);
		}
	}).addClass('dragit');

	$('#minmax').click(function() {
		minmaxChange();
		return false;
	});	
	
	/*
	$('#navTop').hoverIntent(function() {
		$('#nav').addClass('dragit');
	},function() {
		$('#nav').removeClass('dragit');
	});
	*/
	
	if (oNavInfo.excludeFromHistory != "true") updateHistoryLinks();
});

function minmaxChange() {
//		checkPosition();
		minmaxTimer = setInterval('checkNavHeight()', 100);
		$('#navContent ul.menu, #nav #navBtm').slideToggle(function() {
			setTimeout('clearInterval(' + minmaxTimer + ')', 100);
		});	
		$('#minmax, #navContent').toggleClass('active');
		
		if ($('#navContent').hasClass('active')) {
			var minMax = 'min';
		} else {
			var minMax = 'max';
		}
		setSvar("navMinMax",minMax);
}

function windowResize() {
	if (windowHeight == $(window).height() && windowWidth == $(window).width()) {
		$('#snapLimit').css('height',$(window).height());
		checkPosition();
		resizeTimer = setInterval('checkNavHeight()', 100);
		setTimeout('clearInterval(' + resizeTimer + ')', 100);
	} else {
		windowHeight = $(window).height();
		windowWidth = $(window).width();
	}
}

function checkPosition() {
	var viewHeight = $(window).height();
	var navOffsetTop = document.getElementById('nav').offsetTop;
	var navHeight = $('#nav').height();

	dockedBtm = (navHeight + navOffsetTop >= viewHeight);
}

function hasScrollbar(elem_id) {
	elem = document.getElementById(elem_id);
	if (elem.clientHeight < elem.scrollHeight) {
		$('body').css('height','auto');
	} else {
		$('body').css('height','100%');
	}
} 



function menu() {
	$('#nav ul ul').not('.show').hide();
	$('input').clearOnFocus();		
	
	if (isIE6) {
		$('#footer div ul li:first-child').addClass('first-child');
		$('#navContent ul.menu li.utilityNav ul li:first-child .control').addClass('first-child');
		$('#navContent ul.menu li ul li:first-child').addClass('first-child');
		$('#navContent ul.menu li ul li:first-child a').addClass('first-child');
		$('#navContent ul.menu li ul li:first-child .control').addClass('first-child');
		if ($('body').hasClass('reddress') || $('body').hasClass('cookingEntertaining')) {
			$('body').css('height','100%');
		} else {
			hasScrollbar('html');
		}
	}

	if ($.browser.msie) {
		$('#footer div ul li:last-child').addClass('last-child');
	}
	
	$('#navContent ul li a').click(function() {

		if ($(this).parent().hasClass('utilityNav')) {
			//PUT CODE TO OPEN UTIL LINKS ON TEXT HERE
			controlHiddenTimer = setInterval('checkNavHeight()', 100);
			var $link = $(this);
			if ($link.hasClass('control'))
			{
                $link = $link.next();
            }
			$link.next().slideToggle(function() {
				setTimeout('clearInterval(' + controlHiddenTimer + ')', 100);
			});
			$link.prev().toggleClass('active');
			return false;
		}

		if ($(this).hasClass('control')) {
			$('#navContent ul li a.control').removeClass('active');
			checkPosition();
			var checkElement = $(this).next().next();
			var parent = $(this).parent().parent();
		
			if ( (($(this).parent().is(':first-child')) && !(parent.parent().is('li'))) || (checkElement.is('ul:visible')) ) {
				controlTimer = setInterval('checkNavHeight()', 100);
				parent.find('ul:visible').not('.show').slideToggle(function() {
					setTimeout('clearInterval(' + controlTimer + ')', 100);
				});
				$(this).toggleClass('active');
			} else if (checkElement.is('ul:hidden')) {
				controlHiddenTimer = setInterval('checkNavHeight()', 100);
				parent.find('ul:visible').not('.show').slideToggle(function() {
					setTimeout('clearInterval(' + controlHiddenTimer + ')', 100);
				});
				checkElement.slideToggle(function() {
					setTimeout('clearInterval(' + controlHiddenTimer + ')', 100);
				});
			}
			$(this).toggleClass('active');
			return false;
		}
	});
	
	$('#navContent ul.menu a.link, #logo').click(function()
	{
		if ( $(this).hasClass('util') )
		{
			return false;
		}
		else
		{
			if ( $('#AnchorSite').length > 0 )
			{
				logItem("kill the bad flash!!!");
				killBadFlash(this);
			}
			/*var activeItemID = $(this).parent().attr('id');
			saveNavActiveSubMenu(activeItemID, this.href);
			*/
		}
	});
}

//if ($('#AnchorSite object, #AnchorSite embed, #AnchorSite').html('');  
//if we find the "AnchorSite" (a.k.a Style Series) div, then kill it.
function killBadFlash(ohref)
{
	setTimeout( function(){$('#AnchorSite object, #AnchorSite embed, #AnchorSite').html('');}, 100);
	setTimeout( function(){$('#AnchorSite object, #AnchorSite embed, #AnchorSite').html('');}, 200);
}

function checkNavHeight() {
//	document.title = (new Date()).getTime();
	var viewHeight = $(window).height();
	var navOffsetTop = document.getElementById('nav').offsetTop;
	var navHeight = $('#nav').outerHeight();

	if (navHeight + navOffsetTop > viewHeight) {
		var topPos = (viewHeight - navHeight < 0) ? 0 : (viewHeight - navHeight);
		$('#nav').css({top:topPos});
	} else if ((navHeight + navOffsetTop <= viewHeight) && dockedBtm ) {
		var topPos = (viewHeight - navHeight < 0) ? 0 : (viewHeight - navHeight);
		$('#nav').css({top:topPos});
	}
}


$.fn.clearOnFocus = function(){
	return this.focus(function() {
		var v = $(this).val();
		$(this).val( v === this.defaultValue ? '' : v );
	}).blur(function() {
		var v = $(this).val();
		$(this).val( v.match(/^\s+$|^$/) ? this.defaultValue : v );
	});			 
};


function setNavPosition()
{
	var navTopPosition = oNavInfo.navPositionTop;	
	var navLeftPosition = oNavInfo.navPositionLeft;

	if(navTopPosition == "" && navLeftPosition == "") {
		if ($('body').hasClass("reddress") || $('body').hasClass("styleseries")) {
			navTopPosition = 10;
			navLeftPosition = 10;
		} else {
			var pos = $('#wrapper').position();
			navTopPosition = pos.top;
			navLeftPosition = pos.left;
			/*  Not sure why we are doing this.. we really only want auto margin (centered) and "0" padding,
				in which case the code below returns "0" anyway.
			if (!($.browser.msie)) {
				navLeftPosition += parseInt($('#wrapper').css('margin-left')) + parseInt($('#wrapper').css('padding-left'));
			} */
			
			//if we've gone to the trouble to calculate the position, "save" it in the standard way
			//so we don't have to keep caculating it for every page.
			saveNavPosition(navTopPosition, navLeftPosition);	
		}
	}
	$('#nav').css({top: navTopPosition+'px',left: navLeftPosition+'px'});
}




function saveNavPosition(top, left)
{
	//$.cookie('navPositionCookieTop', top);
	setSvar("navPositionTop", top);
	//$.cookie('navPositionCookieLeft', left);
	setSvar("navPositionLeft", left);
}

function checkNavActiveSubMenu()
{
	if(oNavInfo.navActiveItem != "")
	{
		var itemID = oNavInfo.navActiveItem;
		var obj = $("#"+itemID).children('a.control');

		var checkElement = obj.next().next();
		var parent = obj.parent().parent();
		
		controlHiddenTimer = setInterval('checkNavHeight()', 100);
		parent.find('ul:visible').not('.show').slideToggle(function() {
				setTimeout('clearInterval(' + controlHiddenTimer + ')', 100);
		});
		checkElement.slideToggle(function()
		{
			setTimeout('clearInterval(' + controlHiddenTimer + ')', 100);
		});
		
		obj.toggleClass('active');
		
		return false;
	}
}

function saveNavActiveSubMenu(navid, navhref)
{
	/*
	var navCallback = null;
	if ( navhref )
	{
		oNavInfo.navhref = navhref;
		navCallback = navAction;
	}
	//$.cookie('navActiveItemCookie', navid);
	setSvar("navActiveItem", navid, navCallback);
	*/
}

function setSvar(name, valu, callback)
{
	var dataurl = "/inc/jsp/set-svar-data.jsp?var=" + name + "&val=" + valu;
	logItem("dataurl = " + dataurl);
	var ndx = oNavInfo.datandx + 1;
	oNavInfo.datandx = ndx;
	oNavInfo.dataimg[ndx] = new Image();
	oNavInfo.dataimg[ndx].src = dataurl;
	if ( callback )
	{
		oNavInfo.dataimg[ndx].onload = callback;
		oNavInfo.dataimg[ndx].onerror = callback;
	}
}

function updateHistoryLinks() {
	getHistory();
	var url = document.location.pathname;
	//alert("url=" + url);
	var splitUp = url.split("#");
	var title;
	title = document.title;
	if (title===undefined || title===null || $.trim(title)=="") title = url;
	addToHistory(title,url);
	url = splitUp[0];
};

function getHistory() {
	var tmp = $.cookie("history");
	if (tmp===undefined || tmp===null) tmp = "";
	if ($.trim(tmp)=="") tmp = [];
	else tmp = tmp.split("||");
	historyVar = [];
	$.each(tmp, function(){
		var split = this.split("%%");
		historyVar.push({
			title: split[0],
			url: split[1]
		});
	});
}

function addToHistory(title,url) {
	var newHistory = []
	$.each(historyVar, function(){
		if (this.url!=url) newHistory.push(this);
	});
	historyVar = newHistory;
	if (historyVar.length>=4) {
		historyVar.shift();
	}
	historyVar.push({
		title: title,
		url: url
	});
	saveHistory();
	writeHistory();
}

//This function will save the last viewed site to the cookie
function saveHistory() {
	var tmp = [];
	$.each(historyVar, function(){
		tmp.push(this.title+"%%"+this.url);
	});
	$.cookie("history",tmp.join("||"),{ expires: 60, path: "/" });
}

//This function will create the list of previously viewed sites
function writeHistory() {
	var itemList = $("<ul style='display:none;' />"); 
	var counter = 0;
	$.each(historyVar, function() {
		if (counter < 3) {
			var tmpTitle = this.title;
			if (tmpTitle.indexOf("|") > 0 ) {
				tmpTitle = tmpTitle.substring(0, tmpTitle.indexOf("|") - 1);
			}
			if (tmpTitle.length > 24) {
				tmpTitle = tmpTitle.substring(0, 24) + "...";
			}
			var item = $("<li><a href='#' class='control recent'>+</a><a href='" + this.url + "'>" + tmpTitle + "</a></li>");
			itemList.prepend(item);	
			counter++;
		}
	});
	$("#navHistory").append(itemList);
}

