var LAGOINHA = window.LAGOINHA || {};

LAGOINHA.start_photos_magnifier = function()
{
	$( ".mixed-results-l .zoom, .mixed-results-g .zoom" ).mouseover( LAGOINHA.show_super_photo );
	$( ".mixed-results-l .zoom, .mixed-results-g .zoom" ).mouseout( LAGOINHA.hide_super_photo );
}

LAGOINHA.more_results_link = function(){
	$('#categories dd.moresubslink a').click(function(e) {
		e.preventDefault();e.stopPropagation();
		$(this).parents('dl').eq(0).find('dd.moresubs').removeClass('moresubs');
		$(this).parents('dd').eq(0).remove();
	});
	$('#categories dt.morecategslink a').click(function(e) {
		e.preventDefault();e.stopPropagation();
		$('#categories dl.morecategs').removeClass('morecategs');
		$(this).parents('dl').eq(0).remove();
	});
}

LAGOINHA.search_img_error = function(img){
	//debugme(img);
	if( location.search.indexOf( "photo=true" ) == -1 )
	{
		$(img)
			.attr('src',noImageUrl)
			.attr('width','22')
			.attr('height','22')
			.attr('alt','Imagem indisponível')
			.unbind('error')
			.removeAttr('onerror')
			.parents('td').eq(0).removeClass('image-medium').addClass('no-image');
	}
	else
	{
		$(img)
			.attr('src','http://img.todaoferta.uol.com.br/interface/unavailable/normalPhoto.jpg')
			.attr('alt','Imagem indisponível')
			.unbind('error')
			.removeAttr('onerror')
	}
}
LAGOINHA.treat_search_images = function(){
	$("#content a").each(function(i){
		if(this.href.match(/shopping\.uol\.com\.br/gim)) {
			$(this).click(function(e) {
				e.preventDefault();e.stopPropagation();
				window.open(this.href);
			});
		}
		
	});	
}
LAGOINHA.show_super_photo = function( e )
{
	trigger = $( this );
	if( trigger.is( "a" ) == false )
	{
		trigger = trigger.parents( "a" ).eq(0);
	}
	if( $( ".super-photo", trigger ).size() == 0 )
	{
		if($( "img" ,trigger ).eq(0).attr( "alt" )){
			var legenda = $( "img" ,trigger ).eq(0).attr( "alt" );
		}
		else {
				var legenda = ' ';
		}
		$( ".imageContainer" ,trigger ).eq(0).after( '<div class="super-photo"><a href="#" class="hide-super-photo">fechar</a><div class="zoomImageContainer"><img alt="" src="' + $( "img" ,trigger ).eq(0).attr( "src" ).replace( "normalPhoto", "bigPhoto" ).replace( "galeryPhoto", "bigPhoto" ) + '" /></div><p>'+legenda+'</p><span class="arrow">&nbsp;</span></div>' );
	}
	$( ".super-photo", trigger ).show();
	$( trigger ).parents( "p" ).addClass( "higher" );
	e.stopPropagation();
}

LAGOINHA.hide_super_photo = function( e )
{
	trigger = $( this );
	$( ".mixed-results-l .super-photo, .mixed-results-g .super-photo" ).hide();
	$( ".mixed-results-g tbody .cel-image p" ).removeClass( "higher" );
	e.stopPropagation();
}

LAGOINHA.start_order_by_lists = function()
{
	$( "body" ).click( LAGOINHA.hide_order_by_options );
	$( "tr.order-by td.order-list" ).each(
		function()
		{
			var text = $.trim( $( ".active a", this ).text() );
			$( "span em", this ).after( "<a class='selected' href='#display-list'>" + text + "</a>" );
		}
	);
	$( "tr.order-by td.order-list a.selected" ).mouseover( LAGOINHA.display_order_by_options );
}

LAGOINHA.display_order_by_options = function( e )
{
	$( "tr.order-by td.order-list ul" ).css( "display", "none" );
	trigger = $( this );
	trigger.parents( ".order-list" ).children( "ul" ).css( "display", "block" );
	e.preventDefault();
	e.stopPropagation();
}

LAGOINHA.hide_order_by_options = function( e )
{
	trigger = $( this );
	if( trigger.parents( "td.order-list" ).size() == 0 )
	{
		$( "tr.order-by td.order-list ul" ).css( "display", "none" );
	}
}

LAGOINHA.install_chat_links = function()
{
	$( ".chat-on a" ).unbind().click(
		function( e )
		{
			e.preventDefault();
			e.stopPropagation();
			p = {};
			p.trigger = trigger = $( this );
			LAGOINHA.start_conversation( p );
		}
	);
}


LAGOINHA.start_conversation = function( p )
{
	$.get( "/toonline/presence/" + p.trigger.attr( "rel" ).replace( /;/gim, "&" ).split( "&" )[0] + ".xml?key=" + LAGOINHA.keygen(), {},
		function( response )
		{
			var status = $( "status", response ).text();
			// vendedor está online
			if( status == "online" ){
				scrollPop = false;
				height = 385;
				if($.browser.mozilla){
					scrollPop = true;
					height = 400;
				}
				chatWindowB = LAGOINHA.openPop( "/extras/toonline-handler.html?" + p.trigger.attr( "rel" ).replace( /;/gim, "&" ), "chatWindowB",  445, height, true,scrollPop,'resizable=no,toolbar=no,location=no,status=no,menubar=no' );
			// vendedor está offline
			}else{
				location.replace( p.trigger.attr( "href") );
			}
		}
	)
}


LAGOINHA.setup_filters_list_links = function(){
		$("#categories a[@rel=open]").click(function(e){
				e.preventDefault();
				e.stopPropagation();
				$(this).toggleHtml("Ver todos","Esconder").toggleClass("up").parent().prev("dl").toggleClass("showFilters");
			})
	}

findMeorPrevUntil = function(self, findSel){
	if (self.is(findSel)) {
		return self;
	} else {
		if(self.prev().is(findSel)) {
			return self.prev();
		} else {
			return findMeorPrevUntil(self.prev(), findSel);
		}
	}
}

var left_button = 0;
if( $.browser.msie )
{
	left_button = 1;
}
LAGOINHA.every_click_desires_a_target = function(){
	$("#content tbody tr a.zoom").click(function(){ return false; });
	if ($('#content table').is('.mixed-results-g')) {
		$('#content tbody td').mouseup(function(e) {
			if ( $(e.target).is(".hide-super-photo") ){
				e.preventDefault();e.stopPropagation();
				LAGOINHA.hide_super_photo(e);
				return false;
			}
			
			if( e.ctrlKey || e.shiftKey || e.button > left_button  )
			{
				return false;
			}
			if($(this).attr('className').match(/(col-[ab])/)) {
				myClass = $(this).attr('className').match(/(col-[ab])/)[1];
				myPar = $(this).parents('tr').eq(0);
				finalTr = findMeorPrevUntil(myPar, '.title-line');
				
				relAttr = finalTr.find('.'+myClass+' h3 a').attr('rel').split(" ")
				LAGOINHA.set_cookie(relAttr[0], relAttr[1] + ":" + document.location)
				
				if( $(e.target).is("a") ) return false;
				
				goTo = finalTr.find('.'+myClass+' h3 a').attr('href');
				
				if(goTo.match("comprar.todaoferta")){
					document.location = goTo;
				}
			}
		});
		$('.mixed-results-g tbody td').addClass( "hand" );
	} else {
		$('#content tbody tr').mouseup(function(e){
			if ( $(e.target).is(".hide-super-photo") ){
				e.preventDefault();e.stopPropagation();
				LAGOINHA.hide_super_photo(e);
				return false;
			}
			
			if( e.ctrlKey || e.shiftKey || e.button > left_button )
			{
				return false;
			}
			
			relAttr = $('h3 a',this).attr('rel').split(" ")
			LAGOINHA.set_cookie(relAttr[0], relAttr[1] + ":" + document.location)
			if( $(e.target).is("a") ) return false;
			
			e.preventDefault();e.stopPropagation();
			goTo = $('h3 a',this).attr('href');
			if(goTo.match("comprar.todaoferta")){
				document.location = goTo;
			}
		});
		$('.mixed-results-l tbody td').addClass( "hand" );
	}
}

LAGOINHA.align_borders = function(){
	LAGOINHA.check_screen_width();
	var elmBorder = $(
	'.mixed-results-g .title-line .border-a div,'+
	'.mixed-results-g .title-line .border-b div,'+
	'.mixed-results-g .seller-line .border-a div,'+
	'.mixed-results-g .seller-line .border-b div'
	);
	for(var i=0; i<elmBorder.length; i++){
		if(elmBorder.eq(i).parent().height() > elmBorder.eq(i).height() )
			elmBorder.eq(i).css('height',elmBorder.eq(i).parent().height());
	}
}

var startup = function()
{
	LAGOINHA.start_photos_magnifier();
	LAGOINHA.start_order_by_lists();
	LAGOINHA.install_chat_links();
	LAGOINHA.setup_filters_list_links();
	LAGOINHA.treat_search_images();
	LAGOINHA.more_results_link();
	if($('.sell-form').length == 0)
		LAGOINHA.every_click_desires_a_target();
	//LAGOINHA.align_borders();
	//window.onresize = LAGOINHA.align_borders;
}
$( startup );

/* START: smart ad */

var smartad = window.smartad || {};

smartad.limit = 5;
smartad.days = 1;
smartad.delimitadorItens = '\\';
smartad.delimitadorNomeOrigem = '|';
smartad.read = function(name){
	var nameEQ = name + "=";	
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return "";
}

smartad.update = function(name, origem){
	var atuais = smartad.read(name);
	var dL = document.location.toString();
	if( dL.match(/[\?\&](?:q|busca|as_q)\=([\w\%\-\.\:\/,\s\+]+)/) ){
		var newQuery = unescape(RegExp.$1).toLowerCase();
		newQuery = escape(newQuery.replace(' ','+')) + smartad.delimitadorItens + origem;
		if(atuais.indexOf(newQuery)<0){
			// cria item na primeira posição
			var filaAtual = atuais.split(smartad.delimitadorNomeOrigem);
			filaAtual.unshift(newQuery);
			while (filaAtual.length > smartad.limit){
				filaAtual.pop();
			}
			atuais = filaAtual.join(smartad.delimitadorNomeOrigem)
		} else if(atuais.indexOf(newQuery)>0) {
			var filaAtual = atuais.split(smartad.delimitadorNomeOrigem);
			var filaNova = []
			for (var i=0; i<filaAtual.length; i++){
				if(filaAtual[i]!=newQuery){
					filaNova.push(filaAtual[i])
				}
			}
			filaNova.unshift(newQuery);
			atuais = filaNova.join(smartad.delimitadorNomeOrigem)
		}
		if(atuais!=''){
			atuais = atuais.replace( new RegExp( smartad.delimitadorNomeOrigem + "$"), "")
			LAGOINHA.set_cookie(name, atuais, smartad.days)
		}
	}
}
if( LAGOINHA.set_cookie ) {
	smartad.update('AdUol','busca_todaoferta');
}
