var lastText = "";
var countKeyUp = 0; // javascript: alert(countKeyUp);
var ajaxRequest = []; // javascript: alert(ajaxRequest.join('\n'));
function handleKey(code){
	if($('div#searchFast li.focus').size() == 0 && code == 40){
		$('div#searchFast li:first').addClass('focus');
	}
	else {
		var totalElements = $('div#searchFast li').size();
		var focado = $('div#searchFast li.focus');
		if( code == 39 && focado.parent('#suggestions1').size()>0){
			focado.removeClass('focus')
			var meuIndice = $('#suggestions1 li').index(focado[0]);
			if( $('#suggestions2 li').size() >= meuIndice ){
				$('#suggestions2 li').eq(meuIndice).addClass('focus');
			} else if ($('#suggestions2 li').size()>0){
				$('#suggestions2 li:first').addClass('focus');
			}
		} else if( code == 37 && focado.parent('#suggestions2').size()>0 ){
			focado.removeClass('focus')
			var meuIndice = $('#suggestions2 li').index(focado[0]);
			$('#suggestions1 li').eq(meuIndice).addClass('focus');
		} else if( code == 38 ){
			focado.removeClass('focus')
			if( focado.prev().size()> 0){
				focado.prev().addClass('focus');
			} else if(focado.parent('#suggestions2').size()>0){
				$('#suggestions1 li:last').addClass('focus')
			}
		} else if( code == 40 ){
			focado.removeClass('focus')
			if( focado.next().size()> 0){
				focado.next().addClass('focus');
			} else if(focado.parent('#suggestions1').size()>0){
				$('#suggestions2 li:first').addClass('focus')
			}
		} else if( code == 13 ){
			if( focado.size() > 0 && focado.find('a').size() > 0) {
				document.location = focado.find('a').attr('href');
			} else {
				$('#shopping-busca form')[0].submit();
			}
		}
	}
}
$(function(){
	/* remove hover setado pelo teclado quando o mouse entra em ação */
	$('div#searchFast').mouseover(function(){
		$('div#searchFast ol li').removeClass('focus');
	})

	mesq = $(".vitrine-refina").height(); //altura do refinamento
	mdir = $("#sResults").height();// altura das tabelas
	// define altura das tabelas quando menor que refinamento
	if(mesq > mdir){
		$("#sResults").height(mesq);
	}

	// autocomplete
	$('input#caixa-busca').attr('autocomplete','off');
	//$("div#searchFast").width($("input#caixa-busca").width());
	$("input#caixa-busca").keyup(function(event){
		var par = location.href.match(/([a-z0-9]{1,})\.?mejorprecio.com.ar/i);
		
		// não escreve o seggestion nos parceiros
		//if($('div#masterContentsFast').size() == 0 && par == null){
		if($('div#masterContentsFast').size() == 0 && (par == null || (par != null && (par[1] == "detalhe" || par[1] == "compare" || par[1] == "busca" || par[1] == "terra" || par[1] == "www") ) ) ){
			var html = '<div id="masterContentsFast"><div id="contentsFast"><div id="innerContentsFast"><div id="searchFast"></div></div></div></div>';
			$('div#tudo').prepend(html);
		}
		
		if( !event ) return false;
		if( !event.which && event.keyCode ){
			event.which = event.keyCode;
		}
		if ( (event.which > 36 && event.which < 41) || event.which == 13  ){
			if( $('div#searchFast li').size() > 0){
				handleKey( event.which );
				return false;
			}
		}
		var q = $("input#caixa-busca").val();
		if (q == "") {
			hideSearchFast();
			lastText = "";
		} else if(q != lastText) {
			setTimeout(function(){
				var newQ = $("input#caixa-busca").val();
				if( q == newQ ){
					lastText = q;
					retrieveSuggestion(q);
				}
			}, 100)
		}
	})

})

function retrieveSuggestion(q){
	var counter = 0;
	var limit = 3;
	var term = "term="+q;
	function callAjax(){
		hideListBox();
		
		$.ajax({
			type: "GET",
			data: term,
			url: "suggestion.html",
			success: function(result){
				$("div#searchFast").show().removeClass('twocolumns');
				$("div#searchFast").html('<ol id="suggestions1">' + result + '</ol><ol id="suggestions2"></ol>');
				var listsize = $('div#searchFast li').size();
				if( listsize > 5 ){
					$('div#searchFast li:gt('+(Math.floor(listsize/2)-1)+')').appendTo('#suggestions2');
					if( listsize > 8 && $.browser.msie ){
						$('body').addClass('hideselects');
					}
				} else if(listsize==0){
					hideSearchFast();
				}
				$("div#searchFast ol#suggestions1").before('<div id="titlefastsearch"><h2 id="sugestitle">Sugerencias:</h2><a href="javascript:hideSearchFast()" id="ahide">cerrar</a></div>');
			}/*,
			error: function(){
				counter++;
				if(counter < limit){
					callAjax();
				} else {
					if( arguments ){
						var x = [];
						for( var i=0; i<arguments.length; i++){
							if( typeof arguments[i] != 'string'){
								x.push(typeof arguments[i])
							} else {
								x.push(arguments[i])
							}
						}
						alert(x.join('\n') + '\n'+ counter);
					}
				}
			}
			*/
		});
	};
	callAjax();
}

function hideSearchFast(){
	$('body').removeClass('hideselects');
	$("div#searchFast").hide();
	
	showListBox();
}

/* FUNÇÕES showListBox() E hideListBox() CRIADAS PARA SANAR UM BUG DO I.E.6 */
function showListBox(){
	$("#orderType").css({visibility:"visible"});
	$("#resultOffset").css({visibility:"visible"});
}

function hideListBox(){
	$("#orderType").css({visibility:"hidden"});
	$("#resultOffset").css({visibility:"hidden"});
}

var busca = new Object();

// iniAbas: Método que insere os comportamentos nas abas da barra de navegação.
busca.iniAbas = function()
{

	$("#secoes li[@class^=aba-]").each(function(i){
		var anchor = $(this).find("a:eq(0)");
		try {var isSelfLink = (decodeURIComponent(anchor.attr("href"))==decodeURIComponent(window.location.href)||decodeURIComponent(anchor.attr("href"))==decodeURIComponent(window.location.href+"index.html"));}
		catch(e){
			void(0);
		}
		
		if (isSelfLink){
				anchor
				.click(function(e){
						$(this).blur();
					});
		};
		if($(this).is(".aba-todos") && document.all){
				$(this).mouseover(busca.abreTodosDeptos);
			};
		})

};

// abreTodosDeptos: Torna visível a caixa flutuante de todos os departamentos.
// IE apenas!
busca.abreTodosDeptos = function(e)
{
	e.stopPropagation();
	var gatilho = ( ( window.event ) ? window.event.srcElement : e.target );
	
	
	$("#posiciona-deptos").css({"display":"block"});
	$("select").css({"visibility":"hidden"})
	$("#barrauol select").css({"visibility":"visible"});
	$(this).unbind("mouseover",busca.abreTodosDeptos).mouseout(busca.fechaTodosDeptos);
}

// fechaTodosDeptos: Torna invisível a caixa flutuante de todos os departamentos.
// IE apenas!
busca.fechaTodosDeptos = function(e)
{

	e.stopPropagation();
	
	$("#posiciona-deptos").css({"display":"none"});
	$(this).unbind("mouseout",busca.fechaTodosDeptos).mouseover(busca.abreTodosDeptos);
	
	$("select").css({"visibility":"visible"});

}

// criaCookie: Cria um cookie (dã) - http://www.quirksmode.org/js/cookies.html
uol.criaCookie = function (name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; domain=.mejorprecio.com.ar; path=/;";
}

busca.limitaCategorias = function() {
	$(".refina-colunas").eq(1).each(function(){
			$(this).css({"height":this.offsetHeight+'px'});
		})
	var initialValue = $(".refina-colunas + p.action").find("a").html();
	$(".refina-colunas + p.action").find("a").click(function(e){
		e.preventDefault();
		e.stopPropagation();
			$(this)
				.parent("p")
					.prev("div.refina-colunas").eq(0)
					.toggleClass("open-cats")
				.end()
			.end()
			.end()
			.toggleHtml(initialValue,"Cerrar");
		})
}
$(function(){

	$('.refinamento').width(); /* hack for ie6 - show the refine box */

	/* reduz qt de caracteres das últimas buscas */
	$('#lastSearch a.countSize').each(function(){
		var s = $(this).html().toString();
		if( s.length > 16 ){
			s = s.substring(0,15) + ' (...)';
		}
		$(this).html(s);
	})

	busca.iniAbas();
	busca.limitaCategorias();
	})



