var LAGOINHA = window.LAGOINHA || {};
LAGOINHA.ANNOUNCEMENTS = window.LAGOINHA.ANNOUNCEMENTS || {};
var FORTALEZA = window.FORTALEZA || {};

LAGOINHA.ANNOUNCEMENTS.wishlist = function(e) {
	e.preventDefault();e.stopPropagation();
	LAGOINHA.ANNOUNCEMENTS.wishlistHelpper(this);
}
LAGOINHA.ANNOUNCEMENTS.wishlistHelpper = function(linkEml) {
	$('body').append('<div id="wishResponse" class="hidden"></div>')
	window.wishAjaxURL = $(linkEml).attr('href')+'&flavor=html&random='+(new Date()).getTime();
	// bloco para garantir o login funcionando - START
	//window.nonAuthMessage = NOT_AUTH_FAV;
	window.TB_login_callback = function() {
		$('#TB_ajaxContent').load(window.wishAjaxURL);
	}
	// bloco para garantir o login funcionando - END
	$('#wishResponse').load(window.wishAjaxURL, function(responseText){
		TB_show(null,'#TB_inline?height=170&width=300&inlineId=wishResponse',null);
		if(responseText.match(/__NOTAUTHCODE__/gim)){
			$('#TB_ajaxContent #watchItemResponse *').not('h3').remove();
			$('#TB_ajaxContent #watchItemResponse').append('<p class="msg-mini wait-mini">Aguarde...</p>')
			try{UOLPROD.TB_login()}catch(e){void(null)}
		}
	});
}
LAGOINHA.ANNOUNCEMENTS.loginQuestion = function() {
	debugme('loginQuestion');
	window.nonAuthMessage = "Para enviar uma pergunta ao vendedor, é necessário identificar-se";
	window.TB_login_callback = function() {
		// Eu desafio alguém a remover esse IF idiota e não disparar o bug de foco no IE7 !!
		/*
		if($.browser.msie) {
			willOpen = document.location.href.toString().replace(/[#\?].*$/gim,'')+'?opentab=4';
			document.location.href=willOpen;
			//document.location.reload();
		} else {
			try {linkElm = $('#product-details li.tab4 a').get(0)}
			catch(e){linkElm = false}
			if(linkElm)LAGOINHA.ajaxTab(linkElm, LAGOINHA.ANNOUNCEMENTS.questionTabClicks);
		}
		*/
		LAGOINHA.ANNOUNCEMENTS.askAQuestion();
	}
	$.get( "/adm/auth/checkBuyer.html?" + LAGOINHA.keygen(), {},
		function( response )
		{
			if( $( "authorization", response ).text() == "OK" )
			{
				LAGOINHA.ANNOUNCEMENTS.askAQuestion();
			}
			else
			{
				try{
					UOLPROD.TB_login();UOLPROD.TB_login(); // o segundo é para o IE...
				}catch(e){void(null)}
			}
		}
	);
}
LAGOINHA.ANNOUNCEMENTS.askAQuestion = function() {
	debugme('askAQuestion');
	// Mais da metade das linhas abaixo é pra arrumar o problema do ThickBox
	$('body').append('<div id="askTB"><div class="askhere">&nbsp;</div></div>');
	$('#askTB').addClass('hidden');
	$( "#TB_window" ).html( "" );
	if( arguments && arguments[0] && arguments[0].indexOf )
	{
		TB_show(null,'#TB_inline?height=320&width=580&inlineId=askTB',null);
		if( arguments[0] == "messenger" )
		{
			MARKUP.TB_ask_messenger = MARKUP.TB_ask_messenger.replace( "{messenger-text}", "Este vendedor não está disponível para conversação. Envie sua pergunta para ele." );
		}
		else if( arguments[0] == "messenger-unavailable" )
		{
			MARKUP.TB_ask_messenger = MARKUP.TB_ask_messenger.replace( "{messenger-text}", "O sistema de mensagens não está disponível no momento. Envie sua pergunta para o vendedor." );
		}
		$('#TB_ajaxContent .askhere').html(MARKUP.TB_ask_messenger);
	}
	else
	{
		TB_show(null,'#TB_inline?height=280&width=580&inlineId=askTB',null);
		$('#TB_ajaxContent .askhere').html(MARKUP.TB_ask);
		LAGOINHA.validateMaxLength();
	}
	$('#TB_ajaxContent [@name="id"]').val($('.announcement-code').html());
	$('#TB_ajaxContent form').eq(0).unbind().submit(function(e){e.preventDefault();e.stopPropagation();});
	//$('#TB_ajaxContent input.turingBt').unbind().click(LAGOINHA.ANNOUNCEMENTS.turingQuestion);
	$('#TB_ajaxContent input.turingBt').unbind().click(LAGOINHA.ANNOUNCEMENTS.doQuestion)
	$('#TB_ajaxContent #askFirstStep input.cancelaBt').unbind().click(TB_remove);
	$('#TB_ajaxContent textarea')[0].focus();
	setTimeout( function(){ $( "#TB_window textarea" ).focus() }, 300 );
}
LAGOINHA.ANNOUNCEMENTS.turingQuestion = function(){
	debugme('turingQuestion');
	$('#TB_ajaxContent .turing').remove();
	//$('.ajaxAskLoadingIco,p.response.msg, p.response.msg-mini').remove();
	$('#TB_ajaxContent #askFirstStep').css({'height':'0px','overflow':'hidden'});
	$.getJSON('/turing/show.html?random='+(new Date()).getTime(), function(turing){
		$('#TB_ajaxContent #askFirstStep').eq(0).after(MARKUP.turingTest.replace(/__TOKEN__/gim, turing.token).replace(/__TURING_HOST__/gim, turing.host));
		window.lastTuringToken = null; window.lastTuringHost = null;
		window.lastTuringToken = turing.token;
		window.lastTuringHost = turing.host;
		$('#TB_ajaxContent form').eq(0).unbind().submit(LAGOINHA.ANNOUNCEMENTS.doQuestion);
		$('#TB_ajaxContent input.turingBt').unbind();
		$('#TB_ajaxContent .reload-turing button').eq(0).unbind().click(LAGOINHA.ANNOUNCEMENTS.turingQuestion);
		$('#TB_ajaxContent .hear-turing button').eq(0).unbind().click(LAGOINHA.ANNOUNCEMENTS.listenTuring);
		$('#TB_ajaxContent input.enviaBt').unbind();
		$('#TB_ajaxContent #askSecondStep input.cancelaBt').unbind().click(TB_remove);
		$('#TB_ajaxContent #turing-test')[0].focus();
	});
}
LAGOINHA.ANNOUNCEMENTS.doQuestion = function(e){
	debugme('doQuestion');
	e.preventDefault();e.stopPropagation();
	try {formElm = $('#TB_ajaxContent form').get(0)}
	catch(e){formElm = false}
	if(formElm)LAGOINHA.ANNOUNCEMENTS.doQuestionHelpper(formElm);
}
LAGOINHA.ANNOUNCEMENTS.doQuestionHelpper = function(formElm){
	debugme('doQuestionHelpper');
	// bloco para garantir o login funcionando - START
	//window.nonAuthMessage = NOT_AUTH_FAV;
	window.TB_login_callback = function() {
		try {formElm = $('#TB_ajaxContent form').get(0)}
		catch(e){formElm = false}
		if(formElm)LAGOINHA.ANNOUNCEMENTS.doQuestionHelpper(formElm);
	}
	// bloco para garantir o login funcionando - END
	dataForm = UOLPROD.escapedDataFormString(formElm);
	
	//resolvendo bug no ff3 de encoding
	
	if (/Firefox[\/\s](3+\.\d+)/.test(navigator.userAgent)){
		dataForm = unescape(dataForm);
		dataForm = dataForm.replace(/%/g, "%25");
	}
	
	//
	dataForm += '&flavor=js&';
	dataForm += '&random='+(new Date()).getTime()+'&';
	$('.ajaxAskLoadingIco').remove();
	$(formElm).after('<p class="ajaxAskLoadingIco msg-mini wait-mini">Aguarde...</p>');
	$.ajax({ 
		type: 'POST',
		data: dataForm,
		url: $(formElm).attr('action'),
		processData: false,
		dataType: "script"
	});
}
LAGOINHA.ANNOUNCEMENTS.TabClicks = function(e){
	e.preventDefault();e.stopPropagation();
	if($(this).parents('li').eq(0).is('.tab4')) {
		// bloco para garantir o login funcionando - START
		window.nonAuthMessage = "Para ter acesso às perguntas e respostas, é necessário identificar-se";
		window.TB_login_callback = function() {
			// Eu desafio alguém a remover esse IF idiota e não disparar o bug de foco no IE7 !!
			if($.browser.msie) {
				willOpen = document.location.href.toString().replace(/[#\?].*$/gim,'')+'?opentab=4';
				document.location.href=willOpen;
				//document.location.reload();
			} else {
				try {linkElm = $('#product-details li.tab4 a').get(0)}
				catch(e){linkElm = false}
				if(linkElm)LAGOINHA.ajaxTab(linkElm, LAGOINHA.ANNOUNCEMENTS.questionTabClicks);
			}
		}
		// bloco para garantir o login funcionando - END
		LAGOINHA.ajaxTab(this, LAGOINHA.ANNOUNCEMENTS.questionTabClicks);
		questions_click_uol = new Image();
		// questions_click_uol.onload = function(){ alert( 'carregou a imagem!' ); };
		questions_click_uol.src = "http://click.uol.com.br/?rf=todao-ver-perguntas&u=http://img.uol.com.br/x.gif"
	} else {
		LAGOINHA.ajaxTab(this, LAGOINHA.ANNOUNCEMENTS.PaginationClicks);
	}
}
LAGOINHA.ANNOUNCEMENTS.questionTabClicks = function() {
	LAGOINHA.ANNOUNCEMENTS.PaginationClicks();
	$('#customLoginLink').each(function(index) {
		$(this).attr('href', $(this).attr('href').replace('dest=REDIR|http://todaoferta.uol.com.br',"dest=REDIR|"+document.location.href.toString().replace(/[?#].*/gim,'')+"?opentab=4") );		
	});
	LAGOINHA.ANNOUNCEMENTS.addNewQuestionClick();
}
LAGOINHA.ANNOUNCEMENTS.addNewQuestionClick = function(){
	$('#product-details .generic-info:visible p.nav button').unbind().click(function(e){
		e.preventDefault();e.stopPropagation();
		LAGOINHA.ANNOUNCEMENTS.loginQuestion(this);
	});
}
LAGOINHA.ANNOUNCEMENTS.PaginationClicks = function() {
	$('#product-details .generic-info:visible thead a, #product-details .generic-info:visible div.pagination a').click(function(e){
		e.preventDefault();e.stopPropagation();
		LAGOINHA.ajaxTabPagination(this, LAGOINHA.ANNOUNCEMENTS.PaginationClicks);
	});
	LAGOINHA.ANNOUNCEMENTS.addNewQuestionClick();
}
LAGOINHA.ANNOUNCEMENTS.ajaxDescription = function(){
	//if($("#user-description a#ajaxDescriptionLink").length > 0) {
		try {url = $("#user-description a#ajaxDescriptionLink").get(0).href+'?random='+(new Date()).getTime()+'&';}
		catch(e){url = false}
		debugme(url);
		if(url && $('#user-description').length > 0)$('#user-description').load(url);
	//}
}
LAGOINHA.ANNOUNCEMENTS.ajaxHitCounter = function(){
	try {
		//$("#visits").load("/listingDetail/numberOfVisits.html?id="+(/hash([0-9A-Z]+)/).exec($('#visits').attr('className'))[1]);
		$("#visits").append(counter);
	}
	catch(e){
		void(null);
	}
}
LAGOINHA.ANNOUNCEMENTS.swingPhotosClicks = function() {
	if( $('#photos ul.photos li.rotate').length > 1 ) {
		$('#photos ul.photos a.rotate').click(LAGOINHA.ANNOUNCEMENTS.swingPhoto);
		window.lastPhotoRotated = 1;
		window.autoRotate = setInterval(LAGOINHA.ANNOUNCEMENTS.autoRotatePhotos, 5*1000);
	} else {
		$('#photos ul.photos a.rotate').click(function(e) {e.preventDefault();e.stopPropagation();});
	}
}
LAGOINHA.ANNOUNCEMENTS.swingPhoto = function(e) {
	e.preventDefault();e.stopPropagation();
	try{window.clearInterval(window.autoRotate);}catch(e){void(null);}
	LAGOINHA.ANNOUNCEMENTS.swingPhotoHelpper(this);
}
LAGOINHA.ANNOUNCEMENTS.swingPhotoHelpper = function(linkElm) {	
	$('#photos ul.photos li a.rotate').removeClass('active');
	$(linkElm).addClass('active');
	myImg = $(linkElm).find('img').eq(0);
	altImg = $('#photos .super-photo img').attr('alt');
	$('#photos .super-photo img')
		.addClass('willRemove')
		.before('<img class="hidden photo" src="'+myImg.attr('src').replace('smallPhoto', 'bigPhoto')+'" alt="' + altImg + '"/>');
	$('#photos .super-photo img.willRemove').remove();
	$('#photos .super-photo img').removeClass('hidden');
}
LAGOINHA.ANNOUNCEMENTS.autoRotatePhotos = function() {
	if(window.lastPhotoRotated == $('#photos ul.photos li.rotate').length) {
		window.lastPhotoRotated = 1;
	} else {
		window.lastPhotoRotated++;
	}
	try {photoElm = $('#photos ul.photos li a.rotate').get(window.lastPhotoRotated-1)}
	catch(e){photoElm = false;}
	if(photoElm) LAGOINHA.ANNOUNCEMENTS.swingPhotoHelpper( photoElm );
}
LAGOINHA.ANNOUNCEMENTS.openPaymentTab = function(e) {
	// não cancela a propagação do evento para funcionar a âncora
	try {linkElm = $('#product-details li.tab3 a').get(0)}
	catch(e){linkElm = false}
	if(linkElm)LAGOINHA.ajaxTab(linkElm, LAGOINHA.ANNOUNCEMENTS.PaginationClicks);
}
LAGOINHA.ANNOUNCEMENTS.openBuyerTab = function(e) {
	// não cancela a propagação do evento para funcionar a âncora
	try {linkElm = $('#product-details li.tab5 a').get(0)}
	catch(e){linkElm = false}
	if(linkElm)LAGOINHA.ajaxTab(linkElm, LAGOINHA.ANNOUNCEMENTS.PaginationClicks);
}
LAGOINHA.format_number = function( n ){
   x = n.split(',');
   x1 = x[0];
   x2 = x.length > 1 ? ',' + x[1] : '';
   var rgx = /(\d+)(\d{3})/;
   while (rgx.test(x1)) {
     x1 = x1.replace(rgx, '$1' + '.' + '$2');
   }
   return x1 + x2;
}

LAGOINHA.ANNOUNCEMENTS.togglePhone = function(){
	var imgRoiMeter = new Image();
	// TODO: $!listing.hashKey não funciona aqui. Posso confiar neste método de pegar hashKey?
	var hashKey = $("input[@name='listingId']:first").val();
	var url = "/listingDetail/getPhoneNumber.html?id=" + hashKey;
	var clickedLink1 = $("#content-product-seller a.phone-toggle");
	var clickedLink2 = $(".proposal a.phone-toggle");
	clickedLink1.next().load(url, function(){
		clickedLink2.parent().html("<span class='data phone-toggle'>"+$(this).html()+"</span>");
		clickedLink1.hide();
		$(this).show();		
		var codRoiMeter;
		if($('body').is('.fortaleza-imoveis')){
			codRoiMeter = 27;
			$('body').append('<iframe name="ROIMeterCodeInjection" style="display:none" src="http://clicklogger.rm.uol.com.br/?msr=Conversoes:1&prd=27&oper=15&grp=mod:1"></iframe>');
		} else {
			codRoiMeter = 28;
			$('body').append('<iframe name="ROIMeterCodeInjection" style="display:none" src="http://clicklogger.rm.uol.com.br/?msr=Conversoes:1&prd=28&oper=15&grp=mod:1"></iframe>');
		}
		imgRoiMeter.src = 'http://clicklogger.rm.uol.com.br/?prd='+codRoiMeter+'&grp=hash:'+hashKey+'&msr=Visualizacoes%20de%20Telefonemas:1&oper=1&rdn='+LAGOINHA.keygen();
	}).addClass("phone-toggle");
	return false;
}
LAGOINHA.ANNOUNCEMENTS.print = function(e){
	e.preventDefault();e.stopPropagation();
	window.print();
}

LAGOINHA.ANNOUNCEMENTS.contadorCaracteres = function(obj){
	if(obj.value.length >500){
		obj.value = obj.value.substring(0,500);
		return false;
	}	
	$("#numCaracteres").text(""+obj.value.length);
}


LAGOINHA.ANNOUNCEMENTS.getTuringData = function(showTuring){
	var randNum = LAGOINHA.keygen();
	if(showTuring){
		$('#proposal-turing').show();
		$('#content-announcement #proposal .btSendMessage').parent().parent().hide();
		$('#proposal-turing .btConfirmSendProposal').unbind().click( function(e){LAGOINHA.ANNOUNCEMENTS.submitProposal(e)})
		$("#user-response").focus();
	}
	$.getJSON("/turing/show.html?"+ randNum ,{}, LAGOINHA.ANNOUNCEMENTS.processTuring );
}

LAGOINHA.ANNOUNCEMENTS.listenTuring = function(e){
	debugme('listenTuring');
	e.preventDefault();e.stopPropagation();
	$('#proposal-turing td.imgTD').html('<iframe width="220" height="100" src="'+window.lastTuringHost+'/'+window.lastTuringToken+'.wav" frameborder="0" border="0"></iframe>');
}

LAGOINHA.ANNOUNCEMENTS.processTuring = function(turing){
	imagePath=turing.host+"/"+turing.token+".jpg";
	$('#proposal-turing td.imgTD').html("<img id='turing-image' src=''></img> ")
	$('#turing-image').attr("src",imagePath);
	$('#turing-token').val(turing.token);
	window.lastTuringToken = null; window.lastTuringHost = null;
	window.lastTuringToken = turing.token;
	window.lastTuringHost = turing.host;
	$('#proposal-turing #turing-refresh').eq(0).unbind().click(LAGOINHA.ANNOUNCEMENTS.getTuringData);
	$('#proposal-turing #hear-turing').eq(0).unbind().click(LAGOINHA.ANNOUNCEMENTS.listenTuring);
}

LAGOINHA.ANNOUNCEMENTS.submitProposal = function(e){
	e.stopPropagation();
	e.preventDefault();
	oForm = $('#submitProposal').get(0)
	//var dataToSubmit = UOLPROD.dataPostAjaxForm(oForm);
	if (/Firefox[\/\s](3+\.\d+)/.test(navigator.userAgent)){
		myForm = document.forms[oForm.name];
		var dataToSubmit = '';
		for(var i=0, myEl; myEl = myForm[i]; i++) {
			if(myEl.name == 'token'){
				dataToSubmit += myEl.name+'='+escape(myEl.value)+'&';
			}else{
				if(myEl.type != 'checkbox' && myEl.type != 'radio' ){
					dataToSubmit += myEl.name+'='+myEl.value+'&';
				} else {
					if(myEl.checked){
						dataToSubmit += myEl.name+'='+myEl.value+'&';
					}
				}
			}
		}
	} else {
	var dataToSubmit = UOLPROD.escapedDataFormString(oForm)
	}
	$.ajax({ 
		type: 'POST',
		data: dataToSubmit,
		url: $("#submitProposal").attr('action'),
		success: function(msg){
			if(msg.match(/proposal-success/gim)){
				var codRoiMeter;
				var annHash = $('input[@name=listingId]').val();
				if($('body').is('.fortaleza-imoveis')){
					codRoiMeter = 27;
					$('body').append('<iframe name="ROIMeterCodeInjection" style="display:none" src="http://clicklogger.rm.uol.com.br/?msr=Conversoes:1&prd=27&oper=15&grp=mod:1"></iframe>');
				} else {
					codRoiMeter = 28;
					$('body').append('<iframe name="ROIMeterCodeInjection" style="display:none" src="http://clicklogger.rm.uol.com.br/?msr=Conversoes:1&prd=28&oper=15&grp=mod:1"></iframe>');
				}
				var imgRoiMeter = new Image();
				imgRoiMeter.src = 'http://clicklogger.rm.uol.com.br/?prd='+codRoiMeter+'&grp=hash:'+annHash+'&msr=Propostas%20Enviadas:1&oper=1&rdn='+LAGOINHA.keygen();
			}
			$('#content-announcement #ajax_response_proposal_container').html(msg)
			LAGOINHA.ANNOUNCEMENTS.getTuringData(true);
			LAGOINHA.ANNOUNCEMENTS.contadorCaracteres($('#proposal-description')[0]);
			LAGOINHA.start_hover_buttons();
			$('#proposal-turing .btConfirmSendProposal').unbind().click( function(e){LAGOINHA.ANNOUNCEMENTS.submitProposal(e)});
			$('#content-announcement .proposal #turing-refresh').click(function(){ LAGOINHA.ANNOUNCEMENTS.getTuringData()});
			$('#proposal-turing #hear-turing').eq(0).unbind().click(LAGOINHA.ANNOUNCEMENTS.listenTuring);
		}
	});
}

LAGOINHA.ANNOUNCEMENTS.sendAnotherProposal = function(e){
	$.ajax({ 
		type: 'GET',
		url: '/proposal/show.html',
		success: function(msg){
			$('#content-announcement #ajax_response_proposal_container').html(msg);
			LAGOINHA.ANNOUNCEMENTS.getTuringData(true);
			LAGOINHA.ANNOUNCEMENTS.contadorCaracteres($('#proposal-description')[0]);
			LAGOINHA.start_hover_buttons();
			$('#proposal-turing .btConfirmSendProposal').unbind().click( function(e){LAGOINHA.ANNOUNCEMENTS.submitProposal(e)})
			$('#content-announcement .proposal #turing-refresh').click(function(){ LAGOINHA.ANNOUNCEMENTS.getTuringData()});
			$('#proposal-turing #hear-turing').eq(0).unbind().click(LAGOINHA.ANNOUNCEMENTS.listenTuring);
			$('.receive-copy').attr('checked','checked');
			$('#listingHash').val($('#hiddenAuxHash').val());
			$('#proposal_searchUrl').val($('#hiddenAuxURL').val());
			$('#proposalName').focus();
		}
	});
}

LAGOINHA.ANNOUNCEMENTS.countHotsiteView = function(e){
	var countViews = new Image();
	setTimeout(function(){
		countViews.src='/listingDetail/increaseHotSiteViewCounter.html?id='+$('input#idRef').val()+'&rdn='+LAGOINHA.keygen()+'&listingId='+$('input[@name=listingId]').val();
	}
	,50)
}

LAGOINHA.listCarousel = function(){
	/*
		Exemplo de como deve ficar a marcação do carrossel:
		<div class="carousel"> //elemento que contém todo o carrossel
			<div class="content"> //elemento que terá aplicado um possível padding
				<div class="hideOverflow"> //elemento que servirá como "máscara", deve ter overflow:hidden
					<ul> //lista de elementos que será movimentada no carrossel
						<li>
							Item da lista
						</li>
					</ul>
				</div>
			</div>
			<div class="nav-left"> //elemento que conterá o botão de navegação para a esquerda
				<a href="#">&lt;</a>
			</div>
			<div class="nav-right"> //elemento que conterá o botão de navegação para a direita
				<a href="#">&gt;</a>
			</div>
		</div>
	*/
	var me = this;
	me.objContainer = ''; //seletor do elemento pai do carrossel a ser passado como argumento. ex: "div#id-do-div .carousel"
	me.aObjPrev = '';
	me.aObjNext = '';
	me.objToMove = '';
	me.paddingToDiscount = 0; //para descontar a distancia do padding-left do div ".content" do carrossel ao realizar a animação
	me.slideSpeed = 800; //tempo em milisegundos que durará a animação de deslize do carrossel
	me.fadeSpeed = 300; //tempo em milisegundos que durará o efeito de "fade" ao desabilitar um dos botões de navegação
	me.opacityAmount = 0.4; //o quanto o botão de navegação ficará opaco
	me.alignButtons = true;
	me.start = function(objContainer){
		me.objContainer = $(objContainer);
		me.aObjPrev = $('.nav-left a',me.objContainer);
		me.aObjNext = $('.nav-right a',me.objContainer);
		me.objToMove = $('.content ul',me.objContainer);
		me.paddingToDiscount = ($('.content',me.objContainer).css('padding-left').replace('px',''))*1;
		me.setListWidth();
		me.aObjPrev.click(me.prevPlanList);
		me.aObjNext.click(me.nextPlanList);
		me.enableDisableNav(me.aObjPrev,'add');
		if(me.alignButtons){
			var totalHeight =  me.objContainer[0].offsetHeight;
			var distanceTop = (totalHeight - me.aObjPrev.height())/2;
			me.aObjPrev.parent().css('top',distanceTop);
			me.aObjNext.parent().css('top',distanceTop);
		}
	}
	me.setListWidth = function(e){
		var totalWidth = 0;
		$('li',me.objToMove).each(function(i){
			totalWidth += ($(this).width() + ($(this).css('margin-left').replace('px',''))*1 + ($(this).css('margin-right').replace('px',''))*1)*1;
		});
		me.objToMove.css('width',totalWidth);
	}
	me.discountDifferences = function(moveAmount){
		//Função para descontar as margens e os paddings dos elementos ao calcular a quantidade de px para o carrossel movimentar
		return moveAmount = moveAmount - ($('li',me.objToMove).eq(0).css('margin-left').replace('px',''))*1 - me.paddingToDiscount;
	}
	me.nextPlanList = function(e){
		if(e){
			e.stopPropagation();
			e.preventDefault();
		}
		var objToMove = me.objToMove;
		var marginObj = (objToMove.css('margin-left').replace('px',''))*1;
		var hiddenSpace =  Math.abs(marginObj) + me.objContainer.width();
		if(!objToMove.is('.animating') && hiddenSpace < objToMove.width()){
			var moveAmount = me.objContainer.width() - (marginObj)*1;
			moveAmount = me.discountDifferences(moveAmount.toFixed(1));
			objToMove.addClass('animating');
			objToMove.animate({
				marginLeft: -moveAmount
			},me.slideSpeed,
				function(){
					objToMove.css('margin-left',-moveAmount);
					objToMove.removeClass('animating');
					me.enableDisableNav(me.aObjPrev,'remove');
					if((moveAmount + me.objContainer.width()) > objToMove.width()){
						me.enableDisableNav(me.aObjNext,'add');
					}
					else{
						me.enableDisableNav(me.aObjNext,'remove');
					}
				}
			);
		}
	}
	me.prevPlanList = function(e){
		if(e){
			e.stopPropagation();
			e.preventDefault();
		}
		var objToMove = me.objToMove;
		var marginObj = (objToMove.css('margin-left').replace('px',''))*1;
		if(!objToMove.is('.animating') && marginObj < 0){
			var moveAmount = me.objContainer.width() + (marginObj)*1;
			moveAmount = me.discountDifferences(moveAmount.toFixed(1));
			objToMove.addClass('animating');
			objToMove.animate({
				marginLeft: moveAmount
			},me.slideSpeed,
				function(){
					objToMove.css('margin-left',moveAmount);
					objToMove.removeClass('animating');
					me.enableDisableNav(me.aObjNext,'remove');
					if(moveAmount >= 0){
						me.enableDisableNav(me.aObjPrev,'add');
					}
					else{
						me.enableDisableNav(me.aObjPrev,'remove');
					}
				}
			);
		}
	}
	me.enableDisableNav = function(aObj,action){
		if(action == 'add'){
			aObj.addClass('disable');
			aObj.animate({ 
				opacity: me.opacityAmount
			}, me.fadeSpeed );
		}
		else if(action == 'remove'){
			aObj.removeClass('disable');
			if(aObj.css('opacity') < 1){
				aObj.animate({ 
					opacity: 1
				}, me.fadeSpeed );
			}
		}
	}
}

LAGOINHA.ANNOUNCEMENTS.install_plan_carousel = function(e){
	if($('#launch-plan').length && $('#launch-plan').is('.active')){
		var planCarousel = new LAGOINHA.listCarousel();
		planCarousel.start('.active .carousel');
	}
}
 
LAGOINHA.ANNOUNCEMENTS.install_open_lightbox_plan = function(){
	$('#launch-plan .carousel ul').click(LAGOINHA.ANNOUNCEMENTS.openLightboxPlan);
}

LAGOINHA.ANNOUNCEMENTS.openLightboxPlan = function(e){
	e.preventDefault();
	var elmA = '';
	if($(e.target).is('a')){
		elmA = e.target;
	}else if($(e.target).parents('a').is('a')){
		elmA = $(e.target).parents('a')[0];
	}
	if(elmA != ''){
		FORTALEZA.extendedPlans.open($('#launch-plan .carousel ul a').index(elmA));
	}
}
FORTALEZA.openPopPrint = function(e){
	e.stopPropagation();
	e.preventDefault();
	LAGOINHA.openPop($(this).attr('href'),'print_window',642,500,true,true);
	var countPrint = new Image();
	setTimeout(function(){
		countPrint.src='/listingDetail/increasePrintAdViewCounter.html?id='+$('input#idRef').val()+'&rdn='+LAGOINHA.keygen()+'&listingId='+$('input[@name=listingId]').val();
	}
	,50)
}

FORTALEZA.extendedPhotos = null;
FORTALEZA.extendedPlans = null;

FORTALEZA.createThumbLists = function(){
	if($('ul.photos').length){
		var arrPhotos = [];
		var elmPhotos = $('ul.photos img');
		for(var i=0; i<elmPhotos.length; i++){
			arrPhotos[i] = {
				"thumb": elmPhotos.eq(i).attr('src'),
				"extended": elmPhotos.eq(i).parents('a').attr('href'),
				"alt": elmPhotos.eq(i).attr('alt') || ''
			}
		}
		FORTALEZA.extendedPhotos = new LAGOINHA.extendedImage();
		FORTALEZA.extendedPhotos.start("lighboxPhotos",arrPhotos);
	}
	if($('#launch-plan').length){
		var arrPlans = [];
		var elmPlans = $('.carousel ul img');
		for(var i=0; i<elmPlans.length; i++){
			arrPlans[i] = {
				"thumb": elmPlans.eq(i).attr('src').replace(/planThumb/g,'planLightboxThumb'),
				"extended": elmPlans.eq(i).parents('a').attr('href'),
				"alt": elmPlans.eq(i).attr('alt') || ''
			}
			if(arrPlans[i].alt.indexOf('-') != -1)
				arrPlans[i].alt = arrPlans[i].alt.split('-')[0].toUpperCase() + '-' + '<span class="planDesc">' + arrPlans[i].alt.split('-')[1] + '</span>';
			else
				arrPlans[i].alt = arrPlans[i].alt.toUpperCase();
		}
		FORTALEZA.extendedPlans = new LAGOINHA.extendedImage();
		FORTALEZA.extendedPlans.title = $('#launch-plan h3').html();
		FORTALEZA.extendedPlans.captionTitle = 'PLANTA';
		FORTALEZA.extendedPlans.start("lighboxPlans",arrPlans);
		LAGOINHA.ANNOUNCEMENTS.install_open_lightbox_plan();
	}
}

LAGOINHA.extendedImage = function(){
	var me = this;
	me.id = '';
	me.title = 'Fotos';
	me.captionTitle = 'Foto';
	me.htmlBackup = '';
	me.oldClose = null;
	me.thumbsCarousel = null;
	me.listThumbs = [];
	me.actualImage = 0;
	me.qtdPag = 10;
	me.boxWidth = 598;
	me.boxHeight = 651;//540
	me.opacityAmount = 0.4;
	me.fadeSpeed = 300;
	me.start = function(id, listThumbs){
		var liToAppend = '';
		me.id = id;
		me.listThumbs = listThumbs;
		$('body').append(MARKUP.openExtendedImage.replace(/__ID_CONTAINER__/g,me.id));
		for(var i=0; i<me.listThumbs.length; i++){
			var classPage = '';
			if(i%me.qtdPag == 0)
				classPage = ' class="nextPage"';
			liToAppend = liToAppend + '<li'+classPage+'><a href="'+me.listThumbs[i].extended+'"><span class="imageContainer"><img src="'+me.listThumbs[i].thumb+'" alt="'+me.listThumbs[i].alt.replace(/<[a-zA-Z\/][^>]*>/g,'')+'" title="'+me.listThumbs[i].alt.replace(/<[a-zA-Z\/][^>]*>/g,'')+'" /></span></a></li>';
		}
		$('#'+me.id+' .lightbox-carousel ul').html(liToAppend);
		$('#'+me.id+' .guideNav .total').html(me.listThumbs.length);
		$('#'+me.id+' h3').html(me.title);
		$('#'+me.id+' .captionTitle').html(me.captionTitle);
		if(me.listThumbs.length > 1)
			$('#'+me.id+' .extendedImageBox').addClass('active-arrows');
		else
			$('#'+me.id+' .extendedImageBox').removeClass('active-arrows');
		
		if(me.listThumbs.length > me.qtdPag)
			$('#'+me.id+' .lightbox-carousel').addClass('active-lightbox-carousel');
		else
			$('#'+me.id+' .lightbox-carousel').removeClass('active-lightbox-carousel');
	};
	me.open = function(index){
		if(index >= 0 && index < me.listThumbs.length) me.actualImage = index;
		me.oldClose = window.TB_remove;
		window.TB_remove = me.onClose;
		me.htmlBackup = '<div class="hideLightbox" id="open-'+me.id+'">'+$('#open-'+me.id).html()+'</div>'
		TB_show(null,'#TB_inline?width='+(me.boxWidth)+'&height='+(me.boxHeight)+'&inlineId=open-'+me.id,null);
		$('#open-'+me.id).not('#TB_window #open-'+me.id).remove();
		window.TB_HEIGHT = $("#TB_window")[0].offsetHeight;
		me.position();
		if(me.listThumbs.length > me.qtdPag){
			me.thumbsCarousel = new LAGOINHA.listCarousel();
			me.thumbsCarousel.start('#'+me.id+' .lightbox-carousel');
		}
		me.viewImage(me.actualImage);
		if(me.listThumbs.length > 1){
			me.install_nav_left();
			me.install_nav_right();
			me.install_click_thumb();
		}
		$(window).unbind('scroll',window.TB_position);
		$(window).unbind('resize',window.TB_position);
		$(window).resize(me.position);
	};
	me.viewImage = function(index){
		if(index >= 0)
			me.actualImage = index;
		if(me.actualImage >= 0 && me.actualImage < me.listThumbs.length){
			if(me.listThumbs.length > me.qtdPag){
				if(me.actualImage >= me.qtdPag)
					me.thumbsCarousel.nextPlanList();
				else
					me.thumbsCarousel.prevPlanList();
			}
			$('#'+me.id+' .imageContainer').addClass('loading');
			var imgToLoad = $('#'+me.id+' img.lightboxImage')[0];
			imgToLoad.src = 'http://img.todaoferta.uol.com.br/interface/px.gif';
			imgToLoad.onerror = imgToLoad.onload = function(){
				$('#'+me.id+' .imageContainer').removeClass('loading');
			};
			imgToLoad.src = me.listThumbs[me.actualImage].extended;
			$('#'+me.id+' .guideNav .actual').html(me.actualImage+1);
			$('#'+me.id+' .caption').html(me.listThumbs[me.actualImage].alt || '&nbsp;');
			$('#'+me.id+' .lightbox-carousel ul li a.selected').removeClass('selected');
			$('#'+me.id+' .lightbox-carousel ul li a').eq(me.actualImage).addClass('selected');
			if(me.listThumbs.length > 1){
				if(me.actualImage==0)
					me.enableDisableNav($('#'+me.id+' .extendedImageBox .nav-left a'),'add');
				else
					me.enableDisableNav($('#'+me.id+' .extendedImageBox .nav-left a'),'remove');
				if(me.actualImage==me.listThumbs.length-1)
					me.enableDisableNav($('#'+me.id+' .extendedImageBox .nav-right a'),'add');
				else
					me.enableDisableNav($('#'+me.id+' .extendedImageBox .nav-right a'),'remove');
			}
		}
	};
	me.onClose = function(){
		$('body').append(me.htmlBackup);
		me.oldClose();
		window.TB_remove = me.oldClose;
		$(window).scroll(TB_position);
		$(window).unbind('resize',me.position);
		$(window).resize(TB_position);
		return false;
	};
	me.position = function(){
		var pagesize = TB_getPageSize();	
		var arrayPageScroll = TB_getPageScrollTop();	
		$("#TB_window").css({width:TB_WIDTH+"px",left: (arrayPageScroll[0] + (pagesize[0] - TB_WIDTH)/2)+"px", top: (arrayPageScroll[1] + 10)+"px" });
	}
	me.install_click_thumb = function(){
		$('#'+me.id+' .lightbox-carousel ul li a').click(function(e){
			e.preventDefault();
			e.stopPropagation();
			me.viewImage($('#'+me.id+' .lightbox-carousel ul li a').index(this));
		});
	};
	me.install_nav_left = function(){
		$('#'+me.id+' .extendedImageBox .nav-left a').click(function(e){
			e.preventDefault();
			e.stopPropagation();
			if(me.thumbsCarousel)
				if(me.thumbsCarousel.objToMove.is('.animating'))
					return false;
			if(me.actualImage > 0)
				me.viewImage(me.actualImage-1);
		});
	}
	me.install_nav_right = function(){
		$('#'+me.id+' .extendedImageBox .nav-right a').click(function(e){
			e.preventDefault();
			e.stopPropagation();
			if(me.thumbsCarousel)
				if(me.thumbsCarousel.objToMove.is('.animating'))
					return false;
			if(me.actualImage+1 < me.listThumbs.length)
				me.viewImage(me.actualImage+1);
		});
	};
	me.enableDisableNav = function(aObj,action){
		if(action == 'add'){
			aObj.addClass('disable');
			aObj.animate({ 
				opacity: me.opacityAmount
			}, me.fadeSpeed );
		}
		else if(action == 'remove'){
			aObj.removeClass('disable');
			if(aObj.css('opacity') < 1){
				aObj.animate({ 
					opacity: 1
				}, me.fadeSpeed );
			}
		}
	};
}

LAGOINHA.ANNOUNCEMENTS.install_view_extended_photo = function(){
	if($('.viewExtended').length && !$('body').is('.esconde')){
		$('.openExtendedPhoto').click(function(e){
			e.preventDefault();
			e.stopPropagation();
			FORTALEZA.extendedPhotos.open($('ul.photos a').index($('ul.photos a.active')[0]));
		});
	}
}

FORTALEZA.verify_presence = function(e){
	var hiddenParams = $('#messengerParams');
	if(e){
		e.preventDefault();
		e.stopPropagation();
		var windowToClose = LAGOINHA.openPop("/extras/toonline-handler.html?" + hiddenParams.val().replace( /;/gim, "&" ),'chatWindow',445,385,true,true,'resizable=yes');
	}
	$.get( "/toonline/presence/" + hiddenParams.val().replace( /;/gim, "&" ).split( "&" )[0] + ".xml?key=" + LAGOINHA.keygen(), {},
		function( response )
		{	
			var status = $( "status", response ).text();
			// vendedor está online
			if( status == "online" ){
				if(!e){
					var toAppend = '<a id="openMessenger" style="background-image:url(http://messenger.todaoferta.uol.com.br/presence/image/'+hiddenParams.val().replace( /;/gim, "&" ).split( "&" )[0]+'.gif?rnd='+ LAGOINHA.keygen()+');" href="#">Tô online</a>';
					$('#messenger-place').show().html(toAppend);
					$('#openMessenger').click(FORTALEZA.verify_presence);
				}
			// vendedor está offline
			}else{
				$('#messenger-place').html('');
				if(windowToClose)
					windowToClose.close();
			}
		}
	)
}

LAGOINHA.ANNOUNCEMENTS.startup = function(){
	//LAGOINHA.ANNOUNCEMENTS.ajaxDescription();
	//$("#print").click(LAGOINHA.ANNOUNCEMENTS.print);
	//$('#product-details li a').click(LAGOINHA.ANNOUNCEMENTS.TabClicks);
	//$('#product-seller a.outrasformas, #product-seller a.outrasformas-novo').click(LAGOINHA.ANNOUNCEMENTS.openPaymentTab);
	//$('#product-seller a.verhistorico').click(LAGOINHA.ANNOUNCEMENTS.openBuyerTab);
	//LAGOINHA.defaultTab();
	//LAGOINHA.ANNOUNCEMENTS.ajaxHitCounter();
	//LAGOINHA.ANNOUNCEMENTS.questionTabClicks();
	$('.lnkHotSite a, .launch-banner a').click(LAGOINHA.ANNOUNCEMENTS.countHotsiteView);
	LAGOINHA.ANNOUNCEMENTS.swingPhotosClicks();
	LAGOINHA.ANNOUNCEMENTS.install_plan_carousel();
	if(!$('body').is('.esconde')){
		LAGOINHA.ANNOUNCEMENTS.install_view_extended_photo();
		$('li.wishlist a').click(LAGOINHA.ANNOUNCEMENTS.wishlist);
		$('li.print a').click(FORTALEZA.openPopPrint);
		$('li.friend a.invitelink').click(FORTALEZA.inviteLink);
		$("#content-product-seller a.phone-toggle, .proposal a.phone-toggle").click(LAGOINHA.ANNOUNCEMENTS.togglePhone);
		if($("#content-announcement .btSendMessage").html()){
			$("#content-announcement .btSendMessage").unbind().click(function(e){
				e.preventDefault();
				e.stopPropagation();
				LAGOINHA.ANNOUNCEMENTS.getTuringData(true);
			});
		}
		FORTALEZA.createThumbLists();
		if($('#messenger-place').length)
			FORTALEZA.verify_presence();
	}
	else{
		$('a').click(function(e){return false})
	}
}

$(
	function()
	{
		if( $( "body" ).is( ".ann-startup" ) )
		{
			LAGOINHA.ANNOUNCEMENTS.startup();
		}
	}
);
