var LAGOINHA = window.LAGOINHA || {};
var FORTALEZA = window.FORTALEZA || {};
//document.domain = "uol.com.br";
$.fn.extend( {
	toggleHtml : function() {
		for(var i = 0; i< arguments.length;i++) {
			var n = arguments[i];		
			if($(this).html() == n) {
					if(i==(arguments.length-1)) {
						return $(this).html(arguments[0])
					}else  {
						var j = i+1;
						return $(this).html(arguments[j])
					}
			}
			if(i==(arguments.length-1))  {
				return $(this).html(arguments[1]);
			}
		}
	}
});
$.fn.extend( {
	// http://www.quirksmode.org/js/findpos.html
	// works only for the FIRST ONE element
	// if necessary, use jQuery's eq method before calling this one
	// (klaus)
	find_pos : function()
	{
		if( !this.tagName && this.length )
		{
			obj = this[0];
		}
		else
		{
			return [0,0];
		}
		var curleft = curtop = 0;
		if (obj.offsetParent) {
			curleft = obj.offsetLeft
			curtop = obj.offsetTop
			while (obj = obj.offsetParent) {
				curleft += obj.offsetLeft
				curtop += obj.offsetTop
			}
		}
		return [curleft,curtop];
	}
});
$.fn.ellipsis = function(enableUpdating){
	var s = document.documentElement.style;
	if (!('textOverflow' in s || 'OTextOverflow' in s)) {
		return this.each(function(){
			var el = $(this);
			if(el.css("overflow") == "hidden"){
				var originalText = el.html();
				var w = el.width();
				
				var t = $(this.cloneNode(true)).hide().css({
					'position': 'absolute',
					'width': 'auto',
					'overflow': 'visible',
					'display': 'inline',
					'max-width': 'inherit'
				});
				el.after(t);
				var text = originalText;
				while(text.length > 0 && t.width() > el.width()){
					var width_diff = t.width() - el.width();
					var chars_to_remove = Math.ceil( width_diff / 10 );
					text = text.substr(0, text.length - chars_to_remove);

					t.html(text + "...");
				}
				el.html(t.html());
				
				t.remove();
				
				if(enableUpdating == true){
					var oldW = el.width();
					setInterval(function(){
						if(el.width() != oldW){
							oldW = el.width();
							el.html(originalText);
							el.ellipsis();
						}
					}, 100);
				}
			}
		});
	} else return this;
};
var favoritos = function()
{
	var clickuol = new Image();
	clickuol.src = "http://click.uol.com.br/?rf=toferta-addfavoritos&u=http://img.uol.com.br/x.gif";
	if( navigator.appName == "Microsoft Internet Explorer" )
	{
		var sUrl = document.location;
		var sTitle = document.title;
		window.external.AddFavorite( sUrl, sTitle );
	}
	else
	{
		if( navigator.appName == "Netscape" )
		{
			alert( "Pressione Crtl+D para adicionar ao seus favoritos" );
		}
	}
};
LAGOINHA.addFavLink = function(){
	
	$("#welcome li.help").after('<li class="links addFav last-link"><a href="javascript:favoritos();">Adicionar aos favoritos</a></li>');
}

// the previous name, "debug", conflicts with the tinymce editor code.
function debugme(name, value, e) {
	if( typeof ENV != "undefined" )
	{
		if( ENV && ENV == "dev") {
		try {
			if (value == undefined) { console.debug(name);}
			else { console.debug(name, value); }
			if (e) { console.debug(e.message);}
			}
		catch (e) {
			if (value == undefined) {$("#content").after('<p>'+name.toString()+'</p>');}
			else {$("#content").after('<p>'+name.toString()+','+value.toString()+'</p>');}
			}
		}
	}
}

// Cria um cookie (dã) - http://www.quirksmode.org/js/cookies.html
LAGOINHA.set_cookie = 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=.uol.com.br; path=/;";
}

LAGOINHA.get_cookie = 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 null;
}

LAGOINHA.keygen = function()
{
	return Math.floor( Math.random() * 999999999 );
}

LAGOINHA.newWinLinks = function(){
		$("a[@rel=newWin]").click(function(e){
				e.preventDefault();
				e.stopPropagation();

				linkwindow = window.open(this.href,"linkwindow","");
			})
	}	

LAGOINHA.toogleEditorMode = function(switcher) {
	var editor_id = tinyMCE.getEditorId("listing.productDescription.additionalInfo") || tinyMCE.getEditorId();
    try {
        if(!switcher) {
            tinyMCE.removeMCEControl(editor_id);
            
        } else {
						if( $(".uol-editor").size() == 2 )
						{
							tinyMCE.addMCEControl($(".uol-editor")[1], editor_id);
						}
						else
						{
							tinyMCE.addMCEControl($(".uol-editor")[0], editor_id);
						}
						setTimeout(function() {
							if($.browser.msie) {
								var oIframe = document.getElementsByTagName('iframe')[0];
								var oDoc = (oIframe.contentWindow || oIframe.contentDocument);
								if (oDoc.document) oDoc = oDoc.document;
								if(oDoc.getElementById('seller-area'))
									oDoc.body.style.backgroundColor = oDoc.getElementById('seller-area').style.backgroundColor;
							}
						}, 500);
        }
    } catch(e) {
        //error handling
    }
}

LAGOINHA.start_hover_buttons = function()
{
	$(window).unload(function() {
		$("body").removeClass("submitting");
	});
	// insert any css criteria below for a smart button hover effect. ;)
	// a generic class, js-over, is used.
	$( 'button.link-button, input[@type="submit"].link-button' ).each(
		function()
		{
			if($( this ).is('button')) {
				var tempText=$( this ).html();
			}else{
				var tempText=$( this ).val();
			}
			$( this ).after( "<a href='#' class=\""+$( this ).attr("class")+" hideText\">"+tempText+"</a>" );
			$( this ).next( "a" ).click(
				function(e)
				{
					if ($("body").is(".submitting")) {
						return false;
					} else {
						$("body").addClass("submitting");
					}
					e.preventDefault();
					e.stopPropagation();
				// Click uol - start
					if(typeof($(this).parents("form").attr('class')) != 'undefined' &&$(this).parents("form").attr('class').indexOf('clkuol') != -1){
						var clkTipo = (typeof($(this).parents("form").attr('rel')) != "undefined" && $(this).parents("form").attr('rel') != "")?'-'+$(this).parents("form").attr('rel'):'';
						var numeroBotao = (typeof($('.link-button').index(this)) != "undefined" && $('.link-button').index(this) != -1)?'_bt' + $('.link-button').index(this):'';
						
						if( $(this).parents("form").attr('id') == "product" ){
							var reference = 'anuncio'; 
						}else if( $(this).parents("form").attr('id') == "close-deal-form" ){
							var reference = 'confirmacao';
						}else{
							var reference = $(this).parents("form").attr('id');
						}
						
						clkImg = new Image();
						clkImg.onload = function() { var the_form = $(this).parents("form"); if( !the_form.is( ".hold" ) ){ the_form.submit(); } }
						clkImg.id = "x-gif-ctrl";
						
						$(this).parents("form").append(clkImg);
						$('#x-gif-ctrl').hide()
						clkImg.src = "http://click.uol.com.br/?rf=todao-botao-"+reference+clkTipo+numeroBotao+"&u=http://img.uol.com.br/x.gif";
					} else {
						$(this).parents("form").submit();
					}
				
				}
			).dblclick(function(){ return false; });
			$( this ).remove();
		}
	);
}

LAGOINHA.setup_toggle_buttons = function(){
	
	$("#editor-tabs a").click(function(e){
			
			e.preventDefault();
			e.stopPropagation();
			
			if(!(tinyMCE.getEditorId("listing.productDescription.additionalInfo") || tinyMCE.getEditorId()) && $(this).attr("rel")=="on"){
				$("#editor-tabs li.active").removeClass("active");
				$(this).parents("li").addClass("active");
				$("#info-deschtml").remove()
				LAGOINHA.toogleEditorMode(true);
		 	}else if((tinyMCE.getEditorId("listing.productDescription.additionalInfo") ||tinyMCE.getEditorId()) && $(this).attr("rel")=="off"){
				$("#editor-tabs li.active").removeClass("active");
				$(this).parents("li").addClass("active");
				
				$("#editor-tabs").after('<p class="msg-mini info-mini" id="info-deschtml">O TodaOferta não se responsabiliza pelo uso de classes css que coincidam com as classes utilizadas no TodaOferta. Se as mesmas classes forem utilizadas a página do anúncio pode ser exibida com erros.</p>');
				
				LAGOINHA.toogleEditorMode(false);
		 	}
		})
	
	}
LAGOINHA.display_all_categories = function() {
	// código abaixo apenas para IE 6 ou menor
			$("#sections .tab-todos").mouseover(function(e) {
				if($.browser.msie && $.browser.version == "6.0"){
				    $("select").not("#nav_category").css("visibility","hidden");
				}
				// código abaixo apenas para IE 6 ou menor
				/*@cc_on
					if( /msie 6/.test(navigator.userAgent.toLowerCase()) ){
							$("select").not("#nav_category").css("visibility","hidden");
					}
				@*/
				$("#all-categories").show();
					
			})
			$("#all-categories").mouseout( LAGOINHA.hide_all_categories );
			$("#header div.wrapper").mouseover( LAGOINHA.hide_all_categories );
}
LAGOINHA.hide_all_categories = function(){
				if($.browser.msie && $.browser.version == "6.0"){
				    $("select").not("#nav_category").css("visibility","visible");
				}
				// código abaixo apenas para IE 6 ou menor
				/*@cc_on
					if( /msie 6/.test(navigator.userAgent.toLowerCase()) ){
							$("select").not("#nav_category").css("visibility","visible");
					}
				@*/
				$("#all-categories").hide();
}

LAGOINHA.setup_search_form = function(){
	$("#searchProduct").focus(function(){
		$(this).addClass("focus");
	}).blur(function(){
		$(this).removeClass("focus");
	});
	
	if( !$('#searchProduct').val() ){
		$('#searchProduct').focus();
	}
}
// verifica por tagNtarget dentro do divPai da aba, se existe ele mostra esse conteúdo.
// se não existe faz um ajax tipo .load com a URL do link clicado
// se o link tiver a class jsAjax faz um ajax tipo .getJSON esperando conteúdo JS.
// Em ambos dos casos o script está pronto para abas que precise estar logado
LAGOINHA.ajaxTab = function(linkElm, callback){
	$(linkElm).blur();
	divPai = $(linkElm).parents('div').eq(0);
	ulPai = $(linkElm).parents('ul').eq(0);
	liPai = $(linkElm).parents('li').eq(0);
	ulPai.find('li').removeClass('active');
	liPai.addClass('active');
	tabAtual = (/(tab[0-9]+)/).exec(liPai.attr('class'))[1];
	targetAtual = divPai.find('> div.'+tabAtual+'target');
	if(targetAtual.length > 0) {
		divPai.find('> div').addClass('hidden')
		targetAtual.removeClass('hidden');
		//debugme(targetAtual);
	} else {
			divPai
				.find('> div')
					.addClass('hidden')
					.end()
				.append('<div id="loading-tab" class="generic-info"><p class="msg-mini wait-mini">Aguarde...</p></div>');
			if($(linkElm).is('.jsAjax')) {
				$.getJSON(linkElm.href.replace(/#.*$/,'')+'&flavor=js&', callback);
			} else {
				$('#loading-tab').load(linkElm.href.replace(/#.*$/,'').replace(/&amp;/g,"&")+'&flavor=html&random='+(new Date()).getTime(), function(responseText){
						if(responseText.match(/__NOTAUTHCODE__/gim)){
							try{UOLPROD.TB_login()}catch(e){void(null)}
						}
						if($('#loading-tab > div').length == 0){
							$('#loading-tab > *').wrap('<div class="generic-info"></div>');
						}
						$(this).parents('div').eq(0).append( $('#loading-tab > div')[0] );
						$('#loading-tab').remove();
						if(typeof(callback)!= 'undefined') {
							callback.call(null);
						}
					});
		}
	}
}



LAGOINHA.ajaxTabPagination = function(linkElm, callback){
	divPai = $(linkElm).parents('div.generic-info').parents('div').eq(0);
	urlAjax = $(linkElm).attr('href') + "&flavor=html&";
	urlAjax = urlAjax.replace(/&amp;/g,"&");
	if( urlAjax.indexOf( "random" ) == -1 )
	{
		urlAjax += "&random=" + LAGOINHA.keygen();
	}
	$(linkElm).parents('div.generic-info').eq(0).remove();
	divPai.append('<div id="loading-tab" class="generic-info"><p class="msg-mini wait-mini">Aguarde...</p></div>');
	$('#loading-tab').load(urlAjax, function(){
		if($('#loading-tab').html().match(/__NOTAUTHCODE__/gim)){
			try{UOLPROD.TB_login()}catch(e){void(null)}
		}
		if($('#loading-tab > div').length == 0){
			$('#loading-tab *').wrap('<div class="generic-info"></div>');
		}
		$(this).parents('div').eq(0).append( $('#loading-tab > div')[0] );
		$('#loading-tab').remove();
		if(typeof(callback)!= 'undefined') {
			callback.call(null);
		}
	});
}



LAGOINHA.inviteLink = function(e) {
	e.preventDefault();e.stopPropagation();
	// var tellWidth = 425;var tellHeight = 390;
	var tellWidth = 630;var tellHeight = 310;
	$('body').append('<div id="mailtoTB"></div>');
	$('#mailtoTB').addClass('hidden').html(MARKUP.tellAFriend.replace(/_IFRAME_W_/gim,tellWidth).replace(/_IFRAME_H_/gim,tellHeight));
	TB_show(null,'#TB_inline?width='+(tellWidth-30)+'&height='+(tellHeight+35)+'&inlineId=mailtoTB',null);
}

LAGOINHA.TB_mailto_ok = function() {
	$('#TB_ajaxContent').html(MARKUP.tellAFriendSuccess);
	window.setTimeout(function(){
		$('#TB_ajaxContent p').fadeOut("slow", function(){
			TB_remove();
		});
	}, 2000);
}

FORTALEZA.applyRoiMeterInvite = function() {
	var hashAnn;
	var codRoiMeter;
	if($('[@name="tellAFriendURL"]').length){
		hashAnn = $('[@name="tellAFriendURL"]').val();
		hashAnn = hashAnn.slice(hashAnn.lastIndexOf('-')+1,hashAnn.length)
		if(hashAnn.indexOf('#') != -1)
			hashAnn = hashAnn.slice(0,hashAnn.indexOf('#'));
		if(hashAnn.indexOf('?') != -1)
			hashAnn = hashAnn.slice(0,hashAnn.indexOf('?'));
	}
	else if($('[@name="listingId"]').length){
		hashAnn = $('[@name="listingId"]').val();
	}
	if($('body').is('.fortaleza-imoveis'))
		codRoiMeter = 27;
	else
		codRoiMeter = 28;
	var imgRoiMeter = new Image();
	imgRoiMeter.src = 'http://clicklogger.rm.uol.com.br/?prd='+codRoiMeter+'&grp=hash:'+hashAnn+'&msr=Envio%20para%20Amigo:1&oper=1&rdn='+LAGOINHA.keygen();
	window.setTimeout(function(){
		LAGOINHA.TB_mailto_ok();
	}, 2000);
}

LAGOINHA.open_messenger_iframe = function()
{
	p = {};
	if( typeof encoded_presence_login == "undefined" )
	{
		return;
	}
	$.get( "/presence/default/jid/" + encoded_presence_login + ".xml?key=" + LAGOINHA.keygen(), {},
		function( response )
		{
			var status = $( "status", response ).text();
			if( status == "online" )
			{
				$.get( "/adm/auth/checkBuyer.html?" + LAGOINHA.keygen(), {},
					function( response )
					{
						var status = $( "authorization", response ).text();
						if( status == "OK" )
						{
							// vendedor está online e o comprador está autenticado
							$( "#messenger-frame" )[0].src = "http://webmessenger.uol.com.br/static/lagoa/uolwchat2.html?jid=username%40uol.com.br%2Fweb&base=/bosh&server=uol.com.br&chat=" + presence_login + "&random=" + ( new Date() ).getTime() + "&ann_title=" + escape( product_title );
						}
						else
						{
							// vendedor está online mas o comprador não está autenticado.
							$( "#messenger-frame" )[0].src = "/extras/online-contact.html?chat=" + presence_login + "&product_url=" + product_url;
						}
					}
				);
			}
			else
			{
				// vendedor está offline.
				$( "#messenger-frame" )[0].src = "/extras/offline-contact.html?chat=" + presence_login + "&product_url=" + product_url;
			}
		}
	);
}

LAGOINHA.open_messenger_window = function()
{
	if( $( "#messenger-place" ).size() == 0 || $( ".closed-deal" ).size() > 0 )
	{
		return;
	}
	nickname = presence_login.split( "@" )[0];
	if( nickname.length > 12 )
	{
		nickname = nickname.substr( 0, 12 ) + "...";
	}
	$.get( "/adm/auth/checkBuyer.html?" + LAGOINHA.keygen(), {},
		function( response )
		{
			var status = $( "authorization", response ).text();
			// comprador pode conversar
			if( status == "OK" )
			{
				$.get( "/presence/default/jid/" + encoded_presence_login + ".xml?key=" + LAGOINHA.keygen(), {},
					function( response )
					{
						var status = $( "status", response ).text();
						if( status == "online" )
						{
							/*
							$( "#messenger-place" ).html(
								MARKUP.fake_messenger.replace( /{contact-name}/gim, nickname ).replace( /{contact-status}/gim, "online" )
							);
							$( "#messenger-place" ).unbind().click(
								function()
								{
									//alert( $( "#messenger-place" ).html() );
									iframe_url = 'http://webmessenger.uol.com.br/static/lagoa/uolwchat.html?jid=username%40uol.com.br%2Fweb&base=/bosh&server=uol.com.br&chat=' + presence_login + '&ann_title=' + escape( product_title );
									//alert( iframe_url );
									$( "#messenger-place" ).html( '<iframe id="messenger-frame" frameborder="no" scrolling="no"><\/iframe>' );
									//alert( $( "#messenger-place" ).html() );
									$( "#messenger-frame" )[0].src = iframe_url;
								}
							);
							*/
							//iframe_url = "http://www.terra.com.br";
							iframe_url = 'http://webmessenger.uol.com.br/static/lagoa/uolwchat2.html?jid=username%40uol.com.br%2Fweb&base=/bosh&server=uol.com.br&chat=' + presence_login + '&random=' + ( new Date() ).getTime() + '&ann_title=' + escape( product_title );
							//location.href = iframe_url;
							$( "#messenger-place" ).html( '<iframe id="messenger-frame" name="messenger_frame" frameborder="no" scrolling="no"><\/iframe>' );
							messenger_frame.location.replace( iframe_url );
						}
						else
						{
							// vendedor está offline
							if($( "#messenger-place" ).is(".navright")){
								$( "#messenger-place" ).html('<p class="bt-enviar-pergunta">Enviar pergunta</p>');
							}else{
								$( "#messenger-place" ).html( MARKUP.fake_messenger.replace( /{contact-name}/gim, nickname ).replace( /{contact-status}/gim, "offline" ) );
							}
							if($('body').is('.novo-fortaleza')){
								$( "#messenger-place" ).hide();
								//$( ".messenger-fake").css('cursor','auto');
							}
							else{
								$( "#messenger-place" ).unbind().click(function(){LAGOINHA.ANNOUNCEMENTS.askAQuestion( 'messenger' );});
							}
						}
					}
				);
			}
			// comprador não pode conversar
			else
			{
				messenger_identifier = ( ( top.location.href.indexOf( "?" ) != -1 ) ? "&" : "?" );
				messenger_identifier += "messenger=true";
				// autenticação UOL mas não possui conta no TodaOferta
				if( status == "AUC5053" )
				{
					messenger_click_url = "https://cadastro.uol.com.br/adicionalb.html?promo=PROMOLEILAOCOMP&skin=leilao/comprador&urlBack=" + top.location.href + messenger_identifier;
				}
				// sem cookie de autenticação
				else
				{
					messenger_click_url = 'https://acesso.uol.com.br/login.html?skin=todaoferta&dest=REDIR|' + escape( 'http://todaoferta.uol.com.br/extras/auth-messenger-handler.html?to=' + top.location.href + messenger_identifier );
				}
				$.get( "/presence/default/jid/" + encoded_presence_login + ".xml?key=" + LAGOINHA.keygen(), {},
					function( response )
					{
						var status = $( "status", response ).text();
						if( status == "online" )
						{
							// vendedor está online
							$( "#messenger-place" ).html(
								MARKUP.fake_messenger.replace( /{contact-name}/gim, nickname ).replace( /{contact-status}/gim, "online" )
							);
							$( "#messenger-place" ).unbind().click(	function(){location.href = messenger_click_url;});
						}
						else
						{
							// vendedor está offline
							if($( "#messenger-place" ).is(".navright")){
								$( "#messenger-place" ).html('<p class="bt-enviar-pergunta">Enviar pergunta</p>');
							}else{
								$( "#messenger-place" ).html( MARKUP.fake_messenger.replace( /{contact-name}/gim, nickname ).replace( /{contact-status}/gim, "offline" ) );
							}
							if($('body').is('.novo-fortaleza')){
								$( "#messenger-place" ).hide();
								$( ".messenger-fake").css('cursor','auto');
							}
							else{
								$( "#messenger-place" ).unbind().click(	LAGOINHA.ANNOUNCEMENTS.loginQuestion);
							}
						}
					
					}
				);
			}
		}
	);
}

LAGOINHA.handle_messenger_connection = function()
{
	p = {};
	if( typeof top.encoded_presence_login == "undefined" )
	{
		return;
	}
	presence_login = top.presence_login || "";
	encoded_presence_login = top.encoded_presence_login || "";
	product_url = top.product_url || "";
	product_full_title = top.product_full_title || "";
	product_title = top.product_title || "";
	$.get( "/adm/auth/checkBuyer.html?" + LAGOINHA.keygen(), {},
		function( response )
		{
			var status = $( "authorization", response ).text();
			// comprador está autenticado
			if( status == "OK" )
			{
				$.get( "/presence/default/jid/" + encoded_presence_login + ".xml?key=" + LAGOINHA.keygen(), {},
					function( response )
					{
						var status = $( "status", response ).text();
						if( status == "online" )
						{
							// vendedor está online
							location.replace( "http://webmessenger.uol.com.br/static/lagoa/uolwchat2.html?jid=username%40uol.com.br%2Fweb&base=/bosh&server=uol.com.br&chat=" + presence_login + "&random=" + ( new Date() ).getTime() + "&ann_title=" + escape( product_title ) );
						}
						else
						{
							// vendedor está offline
							location.replace( "/extras/offline-contact.html?chat=" + presence_login + "&product_url=" + product_url );
						}
					}
				);
			}
			// comprador não está autenticado.
			else
			{
				$.get( "/presence/default/jid/" + encoded_presence_login + ".xml?key=" + LAGOINHA.keygen(), {},
					function( response )
					{
						var status = $( "status", response ).text();
						if( status == "online" )
						{
							// vendedor está online
							location.replace( "/extras/not-authenticated-online-user.html?chat=" + top.presence_login + "&product_url=" + top.product_url );
						}
						else
						{
							// vendedor está offline
							location.replace( "/extras/not-authenticated-offline-user.html?chat=" + top.presence_login + "&product_url=" + top.product_url );
						}
					}
				);
			}
		}
	);
}

LAGOINHA.encode_product_title = function( title )
{
	temp_title = "";
	for( var i = 0; i < title.length; i++ )
	{
		if( i != 0 )
		{
			temp_title += ",";
		}
		temp_title += title.charCodeAt( i );
	}
	return temp_title;
}

LAGOINHA.authenticate_and_open_messenger = function()
{
	window.TB_login_callback = function()
	{
		location.reload();
	}
	UOLPROD.TB_login();
}

LAGOINHA.install_search_engine = function( e )
{
	if( window.external && ("AddSearchProvider" in window.external) )
	{
		// Firefox 2 and IE 7, OpenSearch
    window.external.AddSearchProvider("http://stc.todaoferta.uol.com.br/todaoferta.xml");
	}
	e.preventDefault();
	e.stopPropagation();
}
LAGOINHA.insert_search_provider_link = function()
{
	if( window.external && ("AddSearchProvider" in window.external))
	{
		var search_text = 'Inserir busca rápida no seu browser';
		if( navigator.userAgent.match(/MSIE 7/) )
		{
			search_text = 'Inserir busca rápida no Internet Explorer';
		}
		else  if( navigator.userAgent.match(/Firefox/) )
		{
			search_text = 'Inserir busca rápida no Firefox'
		}
		$( "#footerBar" ).not(".bid-flow").append( ' | <a href="http://todaoferta.uol.com.br/" class="search-provider">' + search_text + '</a>' );
		$( "a.search-provider" ).click( LAGOINHA.install_search_engine );
	}
}
LAGOINHA.handle_help_links = function()
{
	$( "#welcome a, #menu a, .slogan a, #extra a, #photos a, .janela-conheca" ).click(
		function( e )
		{
			var target = $( this ).attr( "href" );
			test_path = "/extras/ajuda";
			if( target.indexOf( test_path ) != -1 && location.href.indexOf( test_path ) == -1 )
			{
				$( this ).attr( "target", "_blank" );
			}
			test_path = "/extras/conheca";
			if( target.indexOf( test_path ) != -1 && location.href.indexOf( test_path ) == -1 )
			{
				window.open( this.href, "todaoferta_conheca", "width=570,height=429,resizable=yes,statusbar=yes" );
				e.preventDefault();
				e.stopPropagation();
			}
		}
	);
	// esta classe não deve aparecer em links: <a>
	$( ".started-link" ).click(
		function( e )
		{
			window.open( 'http://todaoferta.uol.com.br/extras/conheca/index.html', "todaoferta_conheca", "width=570,height=429,resizable=yes,statusbar=yes" );
			e.preventDefault();
			e.stopPropagation();
		}
	)
	$( ".abre-cartilha" ).click(
		function( e )
		{
			trigger = $( e.target );
			trigger.attr( "target", "_blank" );
			//window.open( trigger.attr( "href" ), "todaoferta_cartilha", "width=570,height=429,resizable=yes,statusbar=yes" );
			//e.preventDefault();
			//e.stopPropagation();
		}
	)
}

LAGOINHA.check_screen_width = function()
{
	if( $( "body" ).is( "resized" ) == true )
	{
		return;
	}
	
	window_width = 0;
	if(self.innerHeight) // all except Explorer
	{
		window_width = self.innerWidth;
	}
	else if(document.documentElement && document.documentElement.clientHeight) // Explorer 6 Strict Mode
	{
		window_width = document.documentElement.clientWidth;
	}
	else if(document.body) // other Explorers
	{
		window_width = document.body.clientWidth;
	}
	if( window_width > 850 )
	{
		$( "body" ).addClass( "over800" );
	}
	else
	{
		$( "body" ).removeClass( "over800" );
	}
	$( "body" ).addClass( "resized" );
	setTimeout( function()
	{
		$( "body" ).removeClass( "resized" );
	}, 1000 );
}

LAGOINHA.install_help_balloons = function()
{
	$( ".userBadge , .ajudaAutoOferta, .ajudaSeloEmpresa, .ajudaCombinar1" ).mouseover( LAGOINHA.show_help_balloon );
	$( ".userBadge , .ajudaAutoOferta, .ajudaSeloEmpresa, .ajudaCombinar1" ).mouseout( LAGOINHA.mark_for_removal );
}

LAGOINHA.show_help_balloon = function( e )
{

	$( "#badge-help" ).remove();
	trigger = $( e.target );
	var position = trigger.find_pos();
	var correctPosition = 2.1;
	var help_text = "";
	var help_icon = "";
	var baloonWidth = "";
	var left = "";
	if( trigger.attr( "rel" ) == "MEG" )
	{
		help_text = "<strong>Megavendedor</strong>.<br /><a href='http://todaoferta.uol.com.br/extras/ajuda/qualificacao.html#perg8' onclick='this.target = \"_blank\";'>Conheça os requisitos</a>.";
		// help_icon = "diamond";
		left = "";
	}
	if( trigger.attr( "rel" ) == "MEO" )
	{
		help_text = "<strong>Megavendedor Ouro</strong>.<br /><a href='http://todaoferta.uol.com.br/extras/ajuda/qualificacao.html#perg8' onclick='this.target = \"_blank\";'>Conheça os requisitos</a>.";
		// help_icon = "diamond";
		left = "";
	}
	if( trigger.attr( "rel" ) == "MET" )
	{
		help_text = "<strong>Megavendedor Titânio</strong>.<br /><a href='http://todaoferta.uol.com.br/extras/ajuda/qualificacao.html#perg8' onclick='this.target = \"_blank\";'>Conheça os requisitos</a>.";
		// help_icon = "diamond";
		left = "";
	}

	if( (trigger.attr( "id" ) == "AUT")||(trigger.attr( "id" ) == "AUT2") )
	{
		baloonWidth = trigger.attr( "rel" )
		help_text = "<strong>O que é a auto-oferta?</strong><br />É o valor máximo pelo qual você pagaria pelo produto anunciado, o sistema oferecerá sempre o menor preço possível para que você ganhe a negociação.<a href='http://todaoferta.uol.com.br/extras/ajuda/comprador.html#perg9' onclick='this.target = \"_blank\";'> Entenda melhor</a>.";
		// link para ajuda q descreve a auto-oferta;
		left = "";
	}
	if( trigger.attr( "rel" ) == "QUA" )
	{
		correctPosition = .7
		baloonWidth = 18
		help_text = "O Selo é a comprovação que o anunciante é uma empresa formal.<br /><a href='http://todaoferta.uol.com.br/extras/ajuda/seloempresarial.html' onclick='this.target = \"_blank\";'>Saiba Mais</a>.";
		// help_icon = "Selo Empresa";
		left = "";
	}
	if( trigger.attr( "id" ) == "COMB1" )
	{
		baloonWidth = 18
		help_text = "Para obter a forma de pagamento adequada para este produto, você deverá entrar em contato com o vendedor.";
		left = "";
	}
	if( trigger.attr( "id" ) == "COMB2" )
	{
		baloonWidth = 18
		help_text = "Antes de efetuar o pagamento você deverá entrar em contato com o vendedor para definir o valor do frete e a forma de envio.";
		left = '-left';
	}

	if( help_text == "" )
	{
		return;
	}
	
	$( "body" ).append( '<div id="badge-help" class="icon-' + help_icon + '" style="visibility: hidden;">' + help_text + '<span class="arrow' + left + '"></span></div>' );
	help_text = "";
	if( baloonWidth != "" ) $("#badge-help").width(baloonWidth + "em")
	var help_left = position[0] - 6;
	if( left == '' )var help_left = position[0] - $("#badge-help").width() + trigger.width() - 16;
		
	var help_top = position[1] - $( "#badge-help" ).height() - trigger.height() * correctPosition;
	$( "#badge-help" ).css('z-index', '999');
	$( "#badge-help" ).css( { left : help_left, top : help_top, visibility : 'visible' } );
	// $( "#badge-help" ).mouseover( function(){ $( "body" ).addClass( "over-balloon" ); e.stopPropagation(); e.preventDefault(); } );
	$( "#badge-help" ).mousemove( function( e ){ e.preventDefault(); e.stopPropagation(); } );
	// $( "body" ).mousemove( LAGOINHA.hide_balloon );
	// $( "#badge-help" ).mouseout( LAGOINHA.hide_balloon );
	// e.stopPropagation();
	// e.preventDefault();
}

LAGOINHA.mark_for_removal = function( e )
{
	setTimeout( function()
	{
		if( $( "body" ).attr( "class" ).indexOf( "over-balloon" ) == -1 )
		{
			$( "body" ).addClass( "remove-balloon" );
		}
		$( "body" ).mousemove( LAGOINHA.hide_balloon );
	}, 700 );
}

LAGOINHA.hide_help_balloons = function( e )
{
	setTimeout( function()
	{
		if( $( "body" ).attr( "class" ).indexOf( "over-balloon" ) == -1 )
		{
			$( "body" ).unbind( "mousemove" );
			$( "#badge-help" ).remove();
		}
		$( "body" ).mousemove( LAGOINHA.hide_balloon );
	}, 500 );
}

LAGOINHA.hide_balloon = function( e )
{
	if( $( "body" ).attr( "class" ).indexOf( "remove-balloon" ) != -1 )
	{
		// $( "body" ).removeClass( "over-balloon" );
		$( "body" ).removeClass( "remove-balloon" );
		$( "body" ).unbind( "mousemove" );
		$( "#badge-help" ).remove();
	}
}

// =)
LAGOINHA.acts_as_tabbable = function()
{
	$( ".acts-as-tabbable a" ).click( LAGOINHA.handle_tab_click );
}

LAGOINHA.handle_tab_click = function( e )
{
	var trigger = $( e.target );
	var tab = trigger.parents( "li" ).eq(0);
	if( tab.is( ".active" ) == false )
	{
		tab_number = tab.attr( "class" );
		tab.parents( "div" ).eq(0).attr( "class", tab_number + "-selected" );
		$( ".acts-as-tabbable li" ).removeClass( "active" );
		tab.addClass( "active" );
	}
	e.preventDefault();
	e.stopPropagation();
}



//Funções do suggestion
var lastText = "";
var countKeyUp = 0; // javascript: alert(countKeyUp);
var ajaxRequest = []; // javascript: alert(ajaxRequest.join('\n'));
LAGOINHA.suggestions_handleKey = function (e){
	if( !e.which && e.keyCode ){
        e.which = e.keyCode;
    }
	code = e.which
	
	$("#search-box-form").submit(function(e){
		e.preventDefault();e.stopPropagation();
	})
    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 ){
           
           var me = $("#searchProduct");
           
           if($(me).parents("form").is(".clkuol"))
		   {		   		
				e.preventDefault();
				e.stopPropagation();
				
				if ($("body").is(".submitting")) {
					return false;
				} else {
					$("body").addClass("submitting");
				}
				
				// Click uol - start
				
				var clkTipo = (typeof($(me).parents("form").attr('rel')) != "undefined" && $(me).parents("form").attr('rel') != "")?'-'+$(me).parents("form").attr('rel'):'';
				var numeroBotao = (typeof($('.link-button').index(this)) != "undefined" && $('.link-button').index(this) != -1)?'_bt' + $('.link-button').index(this):'';
				
				if( $(me).parents("form").attr('id') == "product" ){
					var reference = 'anuncio'; 
				}else if( $(me).parents("form").attr('id') == "close-deal-form" ){
					var reference = 'confirmacao';
				}else{
					var reference = $(me).parents("form").attr('id');
				}
				
				clkImg = new Image();
				clkImg.src = "http://click.uol.com.br/?rf=todao-botao-"+reference+clkTipo+ numeroBotao+"&u=http://img.uol.com.br/x.gif";
				clkImg.id = "x-gif-ctrl";
				
				$(me).parents("form").append(clkImg);
				
				$('#x-gif-ctrl').hide()
				if( focado.size() > 0 && focado.find('a').size() > 0) {
					$('#x-gif-ctrl').load(function(){ document.location = focado.find('a').attr('href'); });
	            }
	            else {
					$('#x-gif-ctrl').load($(me).parents("form").submit());
	            }
				
		  }
		  else
           $("#search-box-form").submit();
            
        }
    }
}

LAGOINHA.suggestions = 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#searchProduct').attr('autocomplete','off');
    //$("div#searchFast").width($("input#caixa-busca").width());
    $("input#searchProduct").keyup(function(event){
        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 || event.which==13){  //caso tenha lista de resultado a mostra ou tenha digitado o ENTER
                LAGOINHA.suggestions_handleKey( event );
                return false;
            }
        }
        var q = $("input#searchProduct").val();
        if (q == "") {
            LAGOINHA.suggestions_hideSearchFast();
            lastText = "";
        } else if(q != lastText) {
            setTimeout(function(){
                var newQ = $("input#searchProduct").val();
                if( q == newQ ){
                    lastText = q;
                    LAGOINHA.suggestions_retrieveSuggestion(q);
                }
            }, 100)
        }
    })
    
	/* oculta o suggestions ao clicar no combo de categorias */
	$("#nav_category").focus(function(){
		$("#searchFast").hide();
	});

}

LAGOINHA.suggestions_retrieveSuggestion = function(q){
    var counter = 0;
    var limit = 3;
    var term = "term="+q+"&rnd="+LAGOINHA.keygen();
    function callAjax(){
        $.ajax({
            type: "GET",
            data: term,
            url: "/suggestion.html",
            success: function(result){
				// código abaixo apenas para IE 6 ou menor
				/*@cc_on
					if( /msie 6/.test(navigator.userAgent.toLowerCase()) ){
							$("select").not("#nav_category").css("visibility","hidden");
					}
				@*/
                $("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').addClass('twocolumns');
					if(listsize % 2 == 0){
                    	$('div#searchFast li:gt(' + (Math.floor(listsize/2)-1) + ')').appendTo('#suggestions2');
					} else {
                    	$('div#searchFast li:gt(' + (Math.floor(listsize/2)) + ')').appendTo('#suggestions2');
					}
					
                    if( listsize > 8 && $.browser.msie ){
                        $('body').addClass('hideselects');
                    }
                } else if(listsize==0){
                    LAGOINHA.suggestions_hideSearchFast();
				// código abaixo apenas para IE 6 ou menor
				/*@cc_on
					if( /msie 6/.test(navigator.userAgent.toLowerCase()) ){
							$("select").css("visibility","visible");
					}
				@*/
                }
				var selectedCateg = $("#nav_category").val();
				if( selectedCateg != "" ){
					$("#suggestions1 li a").each( function(){
						$(this).attr("href",$(this).attr("href")+"&nav_category="+selectedCateg+"&cat=on")
					});
					$("#suggestions2 li a").each( function(){
						$(this).attr("href",$(this).attr("href")+"&nav_category="+selectedCateg+"&cat=on")
					});
				}
                $("div#searchFast ol#suggestions1").before('<div id="titlefastsearch"><h2 id="sugestitle">Sugestões:</h2><a href="javascript:LAGOINHA.suggestions_hideSearchFast()" id="ahide">fechar</a></div>');
                
                $('#searchFast li a').click(function(e){ 
					var me = $(this);
					e.preventDefault();
					e.stopPropagation();
					// Click uol - start
				
					var clkTipo = (typeof($(me).parents("form").attr('rel')) != "undefined" && $(me).parents("form").attr('rel') != "")?'-'+$(me).parents("form").attr('rel'):'';
					var numeroBotao = (typeof($('.link-button').index(this)) != "undefined" && $('.link-button').index(this) != -1)?'_bt' + $('.link-button').index(this):'';
					
					if( $(me).parents("form").attr('id') == "product" ){
						var reference = 'anuncio'; 
					}else if( $(me).parents("form").attr('id') == "close-deal-form" ){
						var reference = 'confirmacao';
					}else{
						var reference = $(me).parents("form").attr('id');
					}
					
					clkImg = new Image();
					clkImg.src = "http://click.uol.com.br/?rf=todao-botao-"+reference+clkTipo+ numeroBotao+"&u=http://img.uol.com.br/x.gif";
					clkImg.id = "x-gif-ctrl";
					
					$(me).parents("form").append(clkImg);
					
					$('#x-gif-ctrl').hide()
					
					$('#x-gif-ctrl').load(function(){ document.location = $(me).attr('href'); });
				    
					 
				});
                
                //var focado = $('div#searchFast li.focus');
                
            }/*,
            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);
                    }
                }
            }
            */
        });
    };
	if($('#searchProduct').val().length >= 2){
    callAjax();
}
}

LAGOINHA.suggestions_hideSearchFast = function(){
    $('body').removeClass('hideselects');
    $("div#searchFast").hide();
	// código abaixo apenas para IE 6 ou menor
	/*@cc_on
		if( /msie 6/.test(navigator.userAgent.toLowerCase()) ){
				$("select").css("visibility","visible");
		}
	@*/
}

LAGOINHA.setRedirToDocumentLocation = function(){
	/* TODO: add #floating-menu2 .signup a, #instant-messenger-and-banner a to linkCollection
	         right now they set REDIR inline, onclick */
	var linkCollection = $("#footer-strip a");
	linkCollection.each(function(){
		var fixedDestination = $(this).attr("href").split("|")[0] + "|" + location.href.replace(/&/g,'%26');
		$(this).attr("href", fixedDestination);
	});
}

LAGOINHA.validateMaxLength = function(){
	/*
		Adicionar ao elemento a ser validado, input ou textarea, a classe "validate-maxlength", além do atributo "maxlength" com o valor máximo de caracteres correspondente
	*/
	$('.validate-maxlength').each(function(i){
		if($(this).attr('maxlength')){
			$(this).keyup(function(e){
				var auxColor = $(this).css('color');
				var maxlimit = $(this).attr('maxlength');
				if($(this).val().length > maxlimit)
					$(this).val($(this).val().substring(0, maxlimit));
				else{
					/*
						Elemento que contiver a quantidade de caracteres restantes deve ter como id o mesmo id do campo validado, acrescido do prefixo "validateMax_"
					*/
					$('#validateMax_'+$(this).attr('id')).html((maxlimit - $(this).val().length).toString()); 
					if((maxlimit - $(this).val().length) == 0)
						$('#validateMax_'+$(this).attr('id')).addClass('reseted');
					else
						$('#validateMax_'+$(this).attr('id')).removeClass('reseted');
				}
			});
			/*
				Caso o campo ja venha preenchido
			*/
			if($(this).val()!='')
				$(this).keyup();
		}
	});
}

LAGOINHA.persist_header_category = function(){
	var nav_category_match = window.location.search.match("nav_category=([a-z-]+)");
	if (nav_category_match != null){
		// [1] é o conteúdo dos parênteses, ou seja, o valor da variável
		$("select#nav_category option[@value='" + nav_category_match[1] + "']").attr("selected","true");
	}
}

FORTALEZA.inviteLink = function(linkEml) {
	var sendUrl = $(this).attr('href');
	var tellWidth = 630;var tellHeight = 376;
	$('body').append('<div id="mailtoTB"></div>');
	$('#mailtoTB').addClass('hidden').html(MARKUP.tellAFriendFortaleza.replace(/_IFRAME_W_/gim,tellWidth).replace(/_IFRAME_H_/gim,tellHeight-40));
	TB_show(null,'#TB_inline?width='+(tellWidth-30)+'&height='+(tellHeight)+'&inlineId=mailtoTB',null);
	window.TB_HEIGHT = $("#TB_window")[0].offsetHeight;
	TB_position();
}


//painel messenger

LAGOINHA.painelMessenger = function(){
	if( $("#painelContainer").length > 0 ){
		if( LAGOINHA.get_cookie('chatWindow') != 'true'){
			$("#painelContainer #painel").html( '<span class="corner"></span><p><strong>Vendedor</strong> - <a href="http://messenger.todaoferta.uol.com.br/painel.jsp" class="openMessenger">Abra o comunicador do TodaOferta</a> &nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp; <a href="http://todaoferta.uol.com.br/extras/central/msg_oquee.html" target="blank">Como funciona</a></p>' );
		}else{
			$("#painelContainer #painel").html('<span class="corner"></span><p><strong>TÔ online</strong> - Você está <span>online</span> para seus compradores &nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp; <a href="http://todaoferta.uol.com.br/extras/central/msg_oquee.html" target="blank">Como funciona</a></p>' );
		}
		$("a.openMessenger").click(LAGOINHA.openMessenger);
		setTimeout(	"LAGOINHA.painelMessenger()", 1000);
	}
}
LAGOINHA.openMessengerOnLogin = function(){
	if(  ( LAGOINHA.get_cookie('auction_to_online') != '' && LAGOINHA.get_cookie('auction_to_online') != true && LAGOINHA.get_cookie('auction_to_online') != null )  && LAGOINHA.get_cookie('chatWindow') != 'true' && $("#painelContainer").length > 0 && $("#painelContainer").is('.openOnLogin')){
		document.cookie = 'auction_to_online=;expires=0;domain=.adm.todaoferta.uol.com.br; path=/;';
		chatWindow = LAGOINHA.openPop("http://messenger.todaoferta.uol.com.br/painel.jsp" , 'chatWindow',  445, 385, true,false,'resizable=no,toolbar=no,location=no,status=no,menubar=no', 'O bloqueador de pop-ups está impedindo a abertura do Tô online. Para conversar com seus compradores, desabilite o bloqueador de pop-ups.' );
		if(chatWindow != false)	LAGOINHA.set_cookie('chatWindow','true');
	}

}
LAGOINHA.onlineCheckMessenger = function(){
	if( $("#painelContainer").length > 0  ){
		$.get( "/toonline/presence/" + $('#presence_login').val() + ".xml?key=" + LAGOINHA.keygen(), {},
			function( response )
			{	
				var status = $( "status", response ).text();
				if( status != "online" && LAGOINHA.get_cookie('chatWindow') == 'true' ){
					LAGOINHA.set_cookie('chatWindow','false');
				}
			}
		)
	}
}
LAGOINHA.openMessenger = function(e){
		if(typeof(e) != 'undefined'){e.preventDefault();e.stopPropagation();}
		if( LAGOINHA.get_cookie('chatWindow') != 'true'){
			chatWindow = LAGOINHA.openPop("http://messenger.todaoferta.uol.com.br/painel.jsp" , 'chatWindow',  445, 385, true,false,'resizable=no,toolbar=no,location=no,status=no,menubar=no', 'O bloqueador de pop-ups está impedindo a abertura do Tô online. Para conversar com seus compradores, desabilite o bloqueador de pop-ups.' );
			if(chatWindow != false)	LAGOINHA.set_cookie('chatWindow','true');
		}
}

LAGOINHA.normalizeString = function(text) {
		return text.toLowerCase().replace(/[áâàäã]/g, "a").replace(
				/[éêèë]/g, "e").replace(/[íîìï]/g, "i").replace(/[óôòöõ]/g,
				"o").replace(/[úûùü]/g, "u").replace(/ç/g, "c").replace(
				/ñ/g, "n");
}

LAGOINHA.openPop = function(url, name, width, height, centralized, scrolling, opt, text) {
    var l = 18;
    var t = 18;
    if (centralized) {
        l = (screen.availWidth - width)/2;
		t = (screen.availHeight -height)/2;
    }
	var popup = window.open(url, name, 'width=' + width + ', height=' + height + ', left=' + l + ', top=' + t + ', scrollbars=' + ((scrolling) ? 'yes' : 'no') + ((opt) ? ', ' + opt : ''));
	setTimeout(function(){
		try {
			popup.focus();
			return false;
		} catch(error) {
			if(typeof(text) != 'undefined'){
				alert(text);
			}else{
				alert('O bloqueador de pop-ups está impedindo a abertura de uma janela. Dica: desabilite o bloqueador de pop-ups para o TodaOferta. ');
			}			
			return false;
			
		}
	}, 300);
    return popup;
}

LAGOINHA.logoutLink = function(){
	$('#logoutLink').click(function(e){
		e.preventDefault();
		e.stopPropagation();
		connId = LAGOINHA.get_cookie('connId');
			$.ajax({
				type: "GET",
				url: "/toonline/disconnect",
				data: 'id=' + connId,
				error:	function(response){
							location.replace('http://adm.todaoferta.uol.com.br/logout.html?redir=http://todaoferta.uol.com.br')	
						},
				success:	function(response){
							location.replace('http://adm.todaoferta.uol.com.br/logout.html?redir=http://todaoferta.uol.com.br')	
						}
				
			})
			
	})
	
}

LAGOINHA.apply_text_ellipsis = function(){
	if($('.static-ellipsis').length)
		$('.static-ellipsis').ellipsis(false);
	if($('.dynamic-ellipsis').length)
		$('.dynamic-ellipsis').ellipsis(true);
}

FORTALEZA.shBeddroomsOptions = function(value, elm) {
	if(value == 'imovel-comercial-e-industrial' || value == 'terreno-e-lote'){
		$('input:checked',elm).attr('checked','');
		elm.hide();
	}
	else{
		elm.show();
	}
}

FORTALEZA.install_announce_iframe_height_control = function() {
	if($('#send-message')[0].addEventListener){
		$('#send-message').load(FORTALEZA.controlAnnounceIframeHeight);
	}else if($('#send-message')[0].attachEvent){
		$('#send-message')[0].attachEvent("onload", FORTALEZA.controlAnnounceIframeHeight); // IE
	}
}

FORTALEZA.controlAnnounceIframeHeight = function() {
	var hToAjust
	try{
		if(frames['send-message'].$('#sendMessage').length)
			hToAjust = frames['send-message'].$('#sendMessage').height();
		else if(frames['send-message'].$('#all').length)
			hToAjust = frames['send-message'].$('#all').height();
	}catch(e) {
		hToAjust = 190;
	}
	$('#send-message').css('height',hToAjust + 5);
}

FORTALEZA.fill_dummy_years = function(){
	var str = '';
	for(var i=2010; i>1906; i--){
		str += '<option value="'+i+'">'+i+'</option>';
	}
	return str;
}

LAGOINHA.startup = function()
{
	LAGOINHA.display_all_categories();
	LAGOINHA.start_hover_buttons();
	LAGOINHA.apply_text_ellipsis();
	LAGOINHA.setup_toggle_buttons();
	//LAGOINHA.open_messenger_iframe();
	LAGOINHA.setup_search_form();
	LAGOINHA.handle_help_links();
	LAGOINHA.addFavLink();
	LAGOINHA.newWinLinks();
	//LAGOINHA.open_messenger_window();
	LAGOINHA.check_screen_width();
	LAGOINHA.install_help_balloons();
	LAGOINHA.acts_as_tabbable();
	window.onresize = LAGOINHA.check_screen_width;
	LAGOINHA.suggestions();
	LAGOINHA.setRedirToDocumentLocation();
	//LAGOINHA.insert_search_provider_link();
	LAGOINHA.validateMaxLength();
	LAGOINHA.persist_header_category();
	LAGOINHA.painelMessenger();
	LAGOINHA.onlineCheckMessenger();
	LAGOINHA.logoutLink();
	LAGOINHA.openMessengerOnLogin();
}

$( LAGOINHA.startup );



/* Um benchmark simples para medir a velocidade do processador.
*  Animações só deverão ser exibidas quando LAGOINHA.effects == true
* DEVE ESTAR NO FINAL DESTE ARQUIVO, SEMPRE!!! */
LAGOINHA.effects = false;
if( document.cookie.indexOf( "lagoa-effects" ) != -1 )
{
	if( document.cookie.indexOf( "lagoa-effects=yes" ) != -1 )
	{
		LAGOINHA.effects = true;
	}
}
else
{
	var x = new Date();
	i = 0;
	while( i < 50000 )
	{
		i++;
	}
	var y = new Date();
	if( ( y - x ) < 70 )
	{
		LAGOINHA.set_cookie( "lagoa-effects", "yes" );
		LAGOINHA.effects = true;
	}
	else
	{
		LAGOINHA.set_cookie( "lagoa-effects", "none" );
	}
}
/* END: benchmark */


