// JavaScript Document

$(document).ready(function(){
	clearClick();
	setBrowserClass();
	if(!hasFlash){
		$('.no_flash').show();
		
		// Center-align the dropdown nav menus
		$('#nav>li>a').each(function(i){
			var $w = $(this).outerWidth()/2;
			var $p = $(this).position();
			var $li = $(this).parent();
			try{
				var $ul = $li.find('ul');
				var $ulw = $ul.outerWidth()/2
				var $newpos = $w - $ulw;
				$ul.css("margin-left", $newpos);
			}catch(e){}
		});
		
		initSearchField();
	}
	if(isIE6()){
		$(document).pngFix();
	}
});

var suggestBoxTimeout;

function initSearchField(){
	$('#searchterm').keyup(function(event){
		if(keyPressed(event, 40)){
			if($('#suggestion_box ul a').length > 0){
				$('#suggestion_box ul li:first a').focus();
				$('#suggestion_box ul li:first a').attr('class','current');
			}
		}else if(!isEnterKey(event)){
			var value = $('#searchterm').val();
			$('#suggestion_box').load('/includes/store/ajax/keywords.php?keywords='+escape(value), null, function(){
				suggestBoxTimeout = setTimeout("$('#suggestion_box ul').remove();", 8000);
			});
		}
	});
	
	$('#suggestion_box').hover(
		function(){ clearTimeout(suggestBoxTimeout); },
		function(){ suggestBoxTimeout = setTimeout("$('#suggestion_box ul').remove();", 8000); }
	);
	$('#suggestion_box a').hover(
		function(){ clearTimeout(suggestBoxTimeout); },
		function(){}
	);
	$('#suggestion_box a').focus(
		function(){ clearTimeout(suggestBoxTimeout); }
	);
	
	$('#suggestion_box').keyup(function(event){
		if($('#suggestion_box ul a.current').length == 0){
			$('#suggestion_box ul li:first a').focus();
			$('#suggestion_box ul li:first a').attr('class','current');
		}else{
			var li = $('#suggestion_box ul a.current').parent();
			$('#suggestion_box ul a').attr('class','');
			if(keyPressed(event, 40)){
				clearTimeout(suggestBoxTimeout);
				$(li).next().find('a').focus();
				$(li).next().find('a').attr('class','current');
			}else if(keyPressed(event, 38)){
				clearTimeout(suggestBoxTimeout);
				$(li).prev().find('a').focus();
				$(li).prev().find('a').attr('class','current');
			}
		}
	});
}

function chooseKeyword(target){
	var keyword = $(target).text().trim();
	$('#searchterm').val(keyword);
	$('#suggestion_box ul').remove();
	$('#searchterm').focus();
}