var LAGOINHA = window.LAGOINHA || {};
LAGOINHA.ANNOUNCEMENTS = window.LAGOINHA.ANNOUNCEMENTS || {};

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=320&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();});
	if($("a.simulateShipping").length > 0) {
		$('#TB_ajaxContent .question').prepend('<p class="simulate">Está em dúvida sobre o custo de envio? Você pode <a class="simulateShipping" href="#">simular o frete para o seu CEP</a></p>');
		$('#TB_ajaxContent .question .simulateShipping').click(function(e){
			$("#TB_window").fadeOut("fast");
			$('#TB_window,#TB_overlay,#TB_HideSelect').remove();
			LAGOINHA.ANNOUNCEMENTS.shippingSimulator(e);
			return;
		})
	}
	//$('#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.listenTuring = function(e){
	debugme('listenTuring');
	e.preventDefault();e.stopPropagation();
	$('#TB_ajaxContent td.imgTD').html('<iframe width="220" height="100" src="'+window.lastTuringHost+'/'+window.lastTuringToken+'.wav" frameborder="0" border="0"></iframe>');
}
LAGOINHA.ANNOUNCEMENTS.showQuestions = function(e){
	$("#ann-questions").remove();
	$("#questionsContainer").append('<div id="loading-tab" class="generic-info"><p class="msg-mini wait-mini">Aguarde...</p></div>');
	$("#questionsContainer").load("/perguntas.html?id=" + $("#listingId").val() + '&simulateShipping=' + $("#simulateShipping").val() + '&flavor=html&random='+(new Date()).getTime(),
		function(responseText){
			if(responseText.match(/__NOTAUTHCODE__/gim)){
				try{UOLPROD.TB_login()}catch(e){void(null)}
			}else{
				$('.generic-info p.nav button.askButton').attr("disabled", "");
			}
			$("#loading-tab").remove();
			$(".simulateShipping").each( function(){ $(this).click(LAGOINHA.ANNOUNCEMENTS.shippingSimulator) } );
			LAGOINHA.ANNOUNCEMENTS.addNewQuestionClick();
			LAGOINHA.ANNOUNCEMENTS.PaginationClicks();
		}
	);
}
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") );		
	});
	$(".simulateShipping").click(LAGOINHA.ANNOUNCEMENTS.shippingSimulator);
	LAGOINHA.ANNOUNCEMENTS.addNewQuestionClick();
}
LAGOINHA.ANNOUNCEMENTS.addNewQuestionClick = function(){
	$('.generic-info p.nav button.askButton').unbind().click(function(e){
		e.preventDefault();e.stopPropagation();
		LAGOINHA.ANNOUNCEMENTS.loginQuestion(this);
	});
}
LAGOINHA.ANNOUNCEMENTS.PaginationClicks = function() {
	$('.product-tab .generic-info thead a, .product-tab .generic-info div.pagination a').click(function(e){
		e.preventDefault();e.stopPropagation();
		LAGOINHA.ANNOUNCEMENTS.ajaxPagination(this, LAGOINHA.ANNOUNCEMENTS.PaginationClicks);
	});
	LAGOINHA.ANNOUNCEMENTS.addNewQuestionClick();
}

LAGOINHA.ANNOUNCEMENTS.ajaxPagination = function(linkElm, callback){
			divPai = $(linkElm).parents('div.generic-info').parent('div');
			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').parent('div').load(urlAjax, 
				function(responseText){
					if(responseText.match(/__NOTAUTHCODE__/gim)){try{UOLPROD.TB_login()}catch(e){void(null)}}
					$('#loading-tab').remove();
					if(typeof(callback)!= 'undefined') {
						callback.call(null);
					}
				}
			);

	
}
LAGOINHA.ANNOUNCEMENTS.swingPhotosClicks = function() {
	if( $('#photos ul.photos li').length > 1 ) {
		$('#photos ul.photos a').click(LAGOINHA.ANNOUNCEMENTS.swingPhoto);
		window.lastPhotoRotated = 1;
		window.autoRotate = setInterval(LAGOINHA.ANNOUNCEMENTS.autoRotatePhotos, 5*1000);
	} else {
		$('#photos ul.photos a').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) {	
	//try{$(linkElm).blur();}catch(e){void(null);}
	$('#photos ul.photos li a').removeClass('active');
	$(linkElm).addClass('active');
	myImg = $(linkElm).find('img').eq(0);
	altImg = $('#photos p.super-photo img').attr('alt');
	$('#photos p.super-photo img')
		.addClass('willRemove')
		.before('<img class="hidden" src="'+myImg.attr('src').replace('smallPhoto', 'bigPhoto')+'" alt="' + altImg + '"/>');
	$('#photos p.super-photo img.willRemove').remove();
	$('#photos p.super-photo img').removeClass('hidden');
	$('#photos p.legend-super-photo span').html(myImg.attr('alt'));
}
LAGOINHA.ANNOUNCEMENTS.autoRotatePhotos = function() {
	if(window.lastPhotoRotated == $('#photos ul.photos li').length) {
		window.lastPhotoRotated = 1;
	} else {
		window.lastPhotoRotated++;
	}
	try {photoElm = $('#photos ul.photos li a').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.install_update_confirmation_details = function(){
	$( "#quantity-input" ).change( LAGOINHA.update_confirmation_details );
	$( "#zip-options-target" ).click( LAGOINHA.check_for_shipping_method_change );
	$( "#combinar input:radio" ).click( LAGOINHA.combinar_change );
}
LAGOINHA.combinar_change = function(){
	if( $( "#combinar input:radio:checked" ).val() == 'S'){
		$( "#combinar #combinarValue" ).attr( "disabled", "" );
		$( "#combinar #combinarValue" ).keypress(LAGOINHA.combinar_value_change);
		$( "#combinar #combinarValue" ).keyup(LAGOINHA.combinar_value_change2);
		}else{
		$( "#combinar #combinarValue" ).val( "" );
		$( "#combinar #combinarValue" ).attr( "disabled", "disabled" );
		LAGOINHA.combinar_value_change2();
		$( "#combinar #combinarValue" ).unbind();
	}
}
LAGOINHA.combinar_reset = function(){
	if($( "#combinar").length != 0 ){
		$( "#combinar #combinarRadioN").attr( "checked", "checked" );
		$( "#combinar td" ).hide();
		$( "#combinar #combinarValue" ).val( "" );
		$( "#combinar #combinarValue" ).attr( "disabled", "disabled" );
	}
}
LAGOINHA.combinar_value_change = function(e){	
	//window.alert(e.keyCode)

	if((e.charCode && ( (e.charCode >= 48 && e.charCode <= 57) || e.charCode == 44 || e.charCode == 8 || e.charCode == 39 || e.charCode == 127 || e.keyCode == 37 || e.keyCode == 39 )) || 
	((e.keyCode >= 48 && e.keyCode <= 57) || e.keyCode == 44 || e.keyCode == 8 || e.keyCode == 39 || e.keyCode == 127 ) ){
		return true;
	}else{
		return false;
	}
}
LAGOINHA.combinar_value_change2 = function(e){

		product_price = parseFloat( $( "#display-total-price" ).text().replace( "R$", "" ).replace( ".", "" ).replace( ".", "" ).replace( ".", "" ).replace( ",", "." ) );
		shipping_price = parseFloat( $( "#combinar #combinarValue" ).val().replace( ",", "." ) );
		
		if( isNaN( shipping_price ) )
		{
			shipping_price = 0;
			$( "#combinar #combinarValue" ).val("");
		}
		total_price = product_price + shipping_price;
		if( total_price.toFixed )
		{
			total_price = total_price.toFixed(2);
		}
		$( "#master-total" ).html( "R$ " + LAGOINHA.format_number( total_price.replace( ".", "," ) ) );
}

LAGOINHA.update_confirmation_details = function( e ){
	var quantity = parseInt( $( "#quantity-input" ).val() );
	if( isNaN( quantity ) && quantity != null )
	{
		$( "#quantity-input" ).val( $( "#quantity-input" ).val().replace( /\D/gim, "" ) );
		return;
	}
	var remainingItems = parseFloat( $("#remainingItems").text() );
	if( quantity <= 1 )
	{
		$( "#quantity-input" ).val(1);
		var quantity = parseInt( $( "#quantity-input" ).val() );
		LAGOINHA.enable_frete_options_due_to_quantity();
		LAGOINHA.update_shipping_method_values();
	}
	else
	{	
		if(quantity > remainingItems){
			quantity = remainingItems;
			$( "#quantity-input" ).val(remainingItems);
		}
		if( $( "#responsible" ).val() != "V"){ LAGOINHA.disable_frete_options_due_to_quantity(); }
		LAGOINHA.update_shipping_method_values();
	}
	if( $( "#display-unit-price" ).size() == 1 )
	{
		var price = $( "#display-unit-price" ).text();
	}
	else
	{
		var price = $( "#field-unit-price" ).val();
	}
	price = parseFloat( price.replace( "R$ ", "" ).replace( ".", "" ).replace( ".", "" ).replace( ".", "" ).replace( ",", "." ) );

	var total_price = quantity * price;
	if( total_price.toFixed )
	{
		total_price = total_price.toFixed(2);
	}
	//$( "#display-quantity" ).html( quantity.toString() );
	$( "#display-total-price" ).html( "R$ " +  LAGOINHA.format_number( total_price.replace( ".", "," ) ) );
	LAGOINHA.recalculate_total_price();
}
LAGOINHA.handle_zip_change_link = function( e ){
	var link = $( "#frete-cep .zip-action" );
	var cancellink = $( "#frete-cep .zip-action-cancel" );
	if( link.attr( "rel" ) == "change" )
	{
		$( "#frete-zip" ).attr( "readonly", "" );
		cancellink.attr( "rel", $( "#frete-zip" ).val() );
		link.attr( "rel", "" );
		link.html( "Confirmar" );
		cancellink.show();
		$( "#frete-details" ).hide();
		$( "#bt-fcompra" ).hide();
		$( "#frete-zip" ).removeClass( "disabled" );
		setTimeout(
			function()
			{
				$( "#frete-zip" ).val("");
				$( "#frete-zip" )[0].focus();
						
			}
		, 100 );
	}
	else
	{
		if( $( "#frete-zip" ).val().length < 8	){
			alert( 'Por favor, preencha o CEP da entrega corretamente' );
			e.preventDefault();
			e.stopPropagation();
			return false;
		}
		
		LAGOINHA.start_zip_loading();
		if( $( "#zip-options-target" ).size() == 1 )
		{
			var shippingId = $( "#zip-options-target input:checked" ).attr("id");
			$("#lastShipping").val(shippingId);
			$( "#zip-options-target" ).html( "" );
			$( "#zip-value" ).val( $( "#frete-zip" ).val() );
			$( "#frete-extra-fields-target" ).load( "/cep/verifyPostalCode.html?cep=" + $( "#frete-zip" ).val() + "&key=" + LAGOINHA.keygen() );
			$( "#zip-options-target" ).load( "/shippingTax/calculate.html?listingId=" + $( "#listingId" ).val() + "&postalCode=" + $( "#frete-zip" ).val() + "&key=" + LAGOINHA.keygen(), {}, LAGOINHA.end_zip_loading );
		}
		else
		{
			$( "#frete-extra-fields-target" ).load( "/cep/verifyPostalCode.html?cep=" + $( "#frete-zip" ).val() + "&key=" + LAGOINHA.keygen(), {}, LAGOINHA.end_zip_loading );
		}

		$( "#frete-zip" ).attr( "readonly", "readonly" );
		link.attr( "rel", "change" );
		link.html( "Alterar o CEP" );
		cancellink.hide();

		$( "#bt-fcompra" ).show();
		$( "#frete-zip" ).addClass( "disabled" );

		
	}
	if( e )
	{
		e.preventDefault();
		e.stopPropagation();
	}
}
LAGOINHA.cancel_zip_change_link = function( e ){
	var link = $( "#frete-cep .zip-action" );
	var cancellink = $( "#frete-cep .zip-action-cancel" );
	$( "#frete-zip" ).attr( "readonly", "readonly" );
	$( "#frete-zip" ).val( cancellink.attr( "rel" ) );
	link.attr( "rel", "change" );
	link.html( "Alterar o CEP" );
	$( "#frete-details" ).show();
	$( "#bt-fcompra" ).show();
	$( "#frete-zip" ).addClass( "disabled" );
	cancellink.hide();
	if( e )
	{
		e.preventDefault();
		e.stopPropagation();
	}
}
LAGOINHA.listen_to_new_zip = function( e ){
	if(e.keyCode == 13 || e.charCode == 13) {
		e.preventDefault();e.stopPropagation();
		return false;
	}
	$( "#frete-zip" ).val( $( "#frete-zip" ).val().replace( /\D/gim, "" ) );
}
LAGOINHA.check_for_shipping_method_change = function( e ){
	trigger = $( e.target );
	if( trigger.is( "input" ) )
	{
		LAGOINHA.update_shipping_method_values();
	}
}
LAGOINHA.update_shipping_method_values = function(){
	if( $( "#zip-options-target input" ).attr("disabled") ){
		return;
	}
	var shipping_price = 0;
	var shipping_text = "";
	if( $( "#zip-options-target .shippingLabel input:checked" ).size() == 1 && parseInt( $( "#quantity-input" ).val() ) == 1 )
	{
		shipping_price = parseFloat( $( "#zip-options-target .shippingLabel input:checked" ).attr( "rel" ) );
		shipping_text = $.trim( $( "#zip-options-target .shippingLabel input:checked" ).parent().text() );
	}
	if(shipping_price == 0){
		if( $( "#zip-options-target .shippingLabel input:checked" ).val() == "ER1"){
			$( "#frete-cep td" ).show();
			return
		}else{
			$( "#frete-cep td" ).hide();
			$( "#combinar td" ).show();
		}
		if( $( "#responsible" ).val() == "V" ){
			if( $( "#zip-options-target .shippingLabel input:checked" ).val() != "COM" ){
				$( "#frete-details" ).show();
				$( "#frete-cep td" ).show();
			}else{
				$( "#frete-details" ).hide();
				$( "#frete-cep td" ).hide();
			}
			$( "#combinar td" ).hide();
		
		}else{
			$( "#frete-details" ).hide();
			//qc 2553
			$( "#frete-cep td" ).hide();
			$( "#combinar td" ).show();
		}
	}else{
		$( "#frete-details" ).show();
		$( "#frete-cep td" ).show();
		LAGOINHA.combinar_reset();
	}
	if( shipping_price.toFixed )
	{
		shipping_price = shipping_price.toFixed(2);
	}
	$( "#frete-name span" ).html( shipping_text );
	$( "#display-unit-frete" ).html( "R$ " + shipping_price.replace( ".", "," ) );
	//$( "#display-total-frete" ).html( "R$ " + shipping_price.replace( ".", "," ) );
	LAGOINHA.recalculate_total_price();
}
LAGOINHA.recalculate_total_price = function(){
	var shipping_price = 0;
	product_price = parseFloat( $( "#display-total-price" ).text().replace( "R$", "" ).replace( ".", "" ).replace( ".", "" ).replace( ".", "" ).replace( ",", "." ) );
	if( parseInt( $( "#quantity-input" ).val() ) == 1 ){
		shipping_price = parseFloat( $( "#display-unit-frete" ).text().replace( "R$", "" ).replace( ",", "." ) );
	}else{
		$( "#display-unit-frete" ).text("");
	}
	//shipping_price = parseFloat( $( "#display-total-frete" ).text().replace( "R$", "" ).replace( ",", "." ) );
	if( isNaN( shipping_price ) )
	{
		shipping_price = 0;
	}
	total_price = product_price + shipping_price;
	if( total_price.toFixed )
	{
		total_price = total_price.toFixed(2);
	}
	$( "#master-total" ).html( "R$ " + LAGOINHA.format_number( total_price.replace( ".", "," ) ) );
}
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.start_zip_loading = function(){
	$( "#zip-loading" ).show();
	$( "#frete-details" ).hide();
	$( "#frete-cep .zip-action" ).hide();
}
LAGOINHA.end_zip_loading = function(){	
	var shippingId = $( "#lastShipping").val();
	$("#zip-options-target #"+shippingId).attr("checked", "checked");
	$( "#zip-loading" ).fadeOut();
	$( "#frete-details" ).show();
	$( "#frete-cep .zip-action" ).show();
	if( $( "#zip-options-target" ).size() == 1 )
	{
		$( "#zip-options-target" ).click( LAGOINHA.check_for_shipping_method_change );
		LAGOINHA.update_shipping_method_values();
	}
}
LAGOINHA.disable_frete_options_due_to_quantity = function(){
	$( "#max-quantity-warning" ).show();
	$( "#zip-options-target input" ).attr( "disabled", "disabled" );
	LAGOINHA.combinar_reset();
	$("#combinar td").hide();
}
LAGOINHA.enable_frete_options_due_to_quantity = function(){
	$( "#max-quantity-warning" ).hide();
	$( "#zip-options-target input" ).attr( "disabled", "" );
	LAGOINHA.update_shipping_method_values()
}
LAGOINHA.install_check_for_postal_area_id_existance = function(){
	//$( "#close-deal-form" ).submit( LAGOINHA.check_for_postal_area_id_existance );
}
LAGOINHA.check_for_postal_area_id_existance = function( e ){
	// para frete a combinar com o campo para o valor do frete
	if( $( "#combinar input:radio:checked" ).val() == 'S' && ( $( "#combinar #combinarValue" ).val() == "" || $( "#combinar #combinarValue" ).val() == 0 ) ){
		window.alert("Por favor preencha o valor de frete combinado com o vendedor.");
		e.preventDefault();
		e.stopPropagation();
		return false;
	}
	if( $( "#frete-zip" ).length == 0 ) return true;
	
	if( $( "#frete-zip" ).val().length < 8 )
	{
		alert( 'Por favor, preencha o CEP da entrega corretamente.' );
		e.preventDefault();
		e.stopPropagation();
		return false;
	} else if($( "#frete-zip" ).is( ".disabled" ) == false)
	{
		LAGOINHA.handle_zip_change_link();
		return false;
	}
	
	if( 
	( ($( "#frete-address" ).val().length == 0 || $('#frete-number').val().length == 0) && !$( "#zip-options-target input" ).attr( "disabled" ) )
	&& $( "#zip-options-target input:checked" ).val() != "COM" )
	{
		alert("Por favor, preencha o endereço de entrega.");
		$( "#frete-address" ).focus();
		e.preventDefault();
		e.stopPropagation();
		return false;
	}
	return true;
}

LAGOINHA.install_set_click_uol_for_auction = function(){
	$( ".confirm-buy" ).click( LAGOINHA.set_click_uol_for_auction );
}

LAGOINHA.set_click_uol_for_auction = function(e){
		e.preventDefault();
		e.stopPropagation();
		if(!LAGOINHA.check_for_postal_area_id_existance()) return false;
		var numeroBotao = $(".confirm-buy").index(e.target);
		var clkTipo = $("#close-deal-form").attr('rel');
		var fase = 'confirmacao';
		myImage = new Image();
		myImage.src = "http://click.uol.com.br/?rf=todao-botao-"+fase+"-"+clkTipo+"_bt"+numeroBotao+"&u=http://img.uol.com.br/x.gif";
		myImage.id = "x-gif-ctrl";
		$("#close-deal-form").append(myImage);
		$('#x-gif-ctrl').load( function() {	 $("#close-deal-form").submit();	});
	}

LAGOINHA.set_lowest_shippingtax = function( ){
	var lowest = parseFloat($("input[@name=shippingMethod]:first").attr( "rel" ));
	$("input[@name=shippingMethod]").each( function(i){
		var shipping = parseFloat($(this).attr( "rel" ));
		if( shipping <= lowest){
			$(this).attr( "checked", "checked" );
			lowest = shipping;
		}

	}
	
	)
	LAGOINHA.update_shipping_method_values();

}
LAGOINHA.install_frete_actions = function(){
	$( "#frete-cep .zip-action" ).click( LAGOINHA.handle_zip_change_link );
	$( "#frete-cep .zip-action-cancel" ).click( LAGOINHA.cancel_zip_change_link );
	$( "#frete-zip" ).keyup( LAGOINHA.listen_to_new_zip );
}
LAGOINHA.ANNOUNCEMENTS.togglePhone = function(){
	// TODO: $!listing.hashKey não funciona aqui. Posso confiar neste método de pegar hashKey?
	var hashKey = $("input[@name='listingId']:first").val();
	var url = "http://comprar.todaoferta.uol.com.br/listingDetail/getPhoneNumber.html?id=" + hashKey;
	var clickedLink = $(this);
	clickedLink.next().load(url, function(){
		clickedLink.hide();
		$(this).show();
	});
	return false;
}
LAGOINHA.ANNOUNCEMENTS.print = function(e){
	e.preventDefault();e.stopPropagation();
	window.print();
}

LAGOINHA.ANNOUNCEMENTS.signUp = function(e){
e.preventDefault();e.stopPropagation();
window.location = $(".howtoSignUp").attr("href").split('|')[0] + '|' + location.href;
}
LAGOINHA.ANNOUNCEMENTS.shippingSimulator = function(e){
	e.preventDefault();e.stopPropagation();
	if($('#shippingSimulator').length == 0) $('body').append('<div id="shippingSimulator" class="hidden"></div>');
	$('#TB_window,TB_HideSelect').remove();
	TB_show(null,'#TB_inline?height=300&width=170&inlineId=shippingSimulator',null);
	$('#TB_ajaxContent').html('<h3>Simular frete</h3><p id="simulateWait" class="msg-mini wait-mini">Aguarde...</p>');
	$('#TB_ajaxContent').load("/shippingTaxSimulate/simulate.html?listingId=" + $("[@name=listingId]").val() + "&postalCode=",{}, 
		function(){
			//$('#shippingSimulator').html("");
			LAGOINHA.ANNOUNCEMENTS.shippingSimulatorHandle();
			setTimeout("$( '#postalCode' ).focus()", 500)
		}
	);
}

LAGOINHA.ANNOUNCEMENTS.shippingSimulatorHandle = function(){
	$( "#postalCode" ).keyup(LAGOINHA.ANNOUNCEMENTS.shippingSimulatorCode);
	$( "#postalCode" ).val(LAGOINHA.get_cookie("postalCode"));
	if($( "#postalCode" ).val().length == 8){
		$("#shippingTaxSimulator button").attr('disabled','');
	}
	$("#shippingTaxSimulator button").click( function(e){
		e.preventDefault();e.stopPropagation();
		$(".simulateContainer").hide();
		$("#simulateWait").show();
		$('#TB_ajaxContent').load("/shippingTaxSimulate/simulate.html?listingId=" + $("[@name=listingId]").val() + "&postalCode=" + $( "#postalCode" ).val(), {}, LAGOINHA.ANNOUNCEMENTS.shippingSimulatorHandle  );
	}
	)
	setTimeout("$( '#postalCode' ).focus()", 500)
}

LAGOINHA.ANNOUNCEMENTS.shippingSimulatorCode = function(e){
		$( "#postalCode" ).val( $( "#postalCode" ).val().replace( /\D/gim, "" ) );
		if($( "#postalCode" ).val().length == 8){
			$("#shippingTaxSimulator button").attr('disabled','');
			if(e.keyCode == 13) {
				e.preventDefault();e.stopPropagation();
				$(".simulateContainer").hide();
				$("#simulateWait").show();
				$('#TB_ajaxContent').load("/shippingTaxSimulate/simulate.html?listingId=" + $("[@name=listingId]").val() + "&postalCode=" + $( "#postalCode" ).val(), {}, LAGOINHA.ANNOUNCEMENTS.shippingSimulatorHandle  );
			}
		}else{
			$("#shippingTaxSimulator button").attr('disabled', 'disabled');
		}
}
LAGOINHA.ANNOUNCEMENTS.installClickUolLinks = function(){
	$("a.clkuol").click(LAGOINHA.ANNOUNCEMENTS.setClickUolLinks);
}
LAGOINHA.ANNOUNCEMENTS.setClickUolLinks = function(e){
		ref = $(this).attr("rel");
	
		myImage = new Image();
	myImage.src = "http://click.uol.com.br/?rf=todao-link-"+ ref +"&u=http://img.uol.com.br/x.gif?" + LAGOINHA.keygen();

}
LAGOINHA.ANNOUNCEMENTS.install_chat_links = function(){
	$( "div#to-online a" ).unbind().click(
		function( e )
		{
			e.preventDefault();
			e.stopPropagation();
			p = {};
			p.trigger = trigger = $( this );
			LAGOINHA.ANNOUNCEMENTS.start_conversation( p );
		}
	);
}

LAGOINHA.ANNOUNCEMENTS.start_conversation = function( p ){
	$.get( "/toonline/presence/" + p.trigger.attr( "rel" ).replace( /;/gim, "&" ).split( "&" )[0] + ".xml?key=" + LAGOINHA.keygen(), {},
		function( response )
		{
			if($( "div#to-online a img" ).length > 0){
				$( "div#to-online a" ).css("background-image", 'url(' + $( "div#to-online a" ).css("background-image").replace(/^url|[\(\)]/g, '')  + LAGOINHA.keygen() + ')')
			}
			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, "&" ) + location.pathname.split('/')[1], "chatWindowB",  445, height, true,scrollPop,'resizable=no,toolbar=no,location=no,status=no,menubar=no' );
			// vendedor está offline
			}else{
				LAGOINHA.ANNOUNCEMENTS.loginQuestion(); 
			}
		}
	)
}

// ***************************************************************************

LAGOINHA.ANNOUNCEMENTS.extendedPhotos = null;
LAGOINHA.ANNOUNCEMENTS.extendedPlans = null;

LAGOINHA.ANNOUNCEMENTS.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') || ''
			}
		}
		LAGOINHA.ANNOUNCEMENTS.extendedPhotos = new LAGOINHA.ANNOUNCEMENTS.extendedImage();
		LAGOINHA.ANNOUNCEMENTS.extendedPhotos.start("lighboxPhotos",arrPhotos);
	}
}

LAGOINHA.ANNOUNCEMENTS.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 = 655;//540
	me.opacityAmount = 0.4;
	me.fadeSpeed = 300;
	me.start = function(id, listThumbs){
		var liToAppend = '';
		me.id = id;
		me.listThumbs = listThumbs;
		$('body').append(MARKUP.openExtendedImageMkt.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();
		$("#TB_ajaxContent").css("overflow", "hidden");
		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);
			}else{
				me.viewImage(me.listThumbs.length - 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);
			}else{
				me.viewImage(0);
			}
		});
	};
	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(){
	
	$('.openExtendedPhoto').click(function(e){
		e.preventDefault();
		e.stopPropagation();
		LAGOINHA.ANNOUNCEMENTS.extendedPhotos.open($('ul.photos a').index($('ul.photos a.active')[0]));
	});

}

LAGOINHA.ANNOUNCEMENTS.showChangeHistory = function(e){
	if( $(".hidden-row").length > 0 ){
		$(".hidden-row").addClass("show-hidden-row").removeClass("hidden-row");
		$("#ver-mais-trigger").html( "Fechar" ).addClass("close");
	} else {
		$(".show-hidden-row").addClass("hidden-row").removeClass("show-hidden-row");
		$("#ver-mais-trigger").html( "Ver todas as alterações" ).removeClass("close");
	}
}
// ***************************************************************************


LAGOINHA.ANNOUNCEMENTS.startup = function(){
	LAGOINHA.ANNOUNCEMENTS.swingPhotosClicks();
	$('#product-details li a').click(LAGOINHA.ANNOUNCEMENTS.TabClicks);
	$('#product-seller a.outrasformas, #product-seller a.outrasformas-novo, .box-bottom .flagsBottom a.outrasformas').click(LAGOINHA.ANNOUNCEMENTS.openPaymentTab);
	$('#product-seller a.verhistorico').click(LAGOINHA.ANNOUNCEMENTS.openBuyerTab);
	$('li.friend a.invitelink').click(LAGOINHA.inviteLink);
	$('li.wishlist a').click(LAGOINHA.ANNOUNCEMENTS.wishlist);
	LAGOINHA.install_update_confirmation_details();
	LAGOINHA.install_frete_actions();
	if($( "#frete-zip" ).html() != null) LAGOINHA.update_confirmation_details();
	if($( "#frete-zip" ).html() != null) LAGOINHA.install_check_for_postal_area_id_existance();
	if($("#close-deal-form" ).attr('rel') != null && ( $("#close-deal-form" ).attr('rel').indexOf('leilao') != -1 || $("#close-deal-form" ).attr('rel').indexOf('fixo') != -1 || $("#close-deal-form" ).attr('rel').indexOf('imediato') != -1 )) LAGOINHA.install_set_click_uol_for_auction();
	LAGOINHA.set_lowest_shippingtax();
	$('#proposal-trigger').click(LAGOINHA.ANNOUNCEMENTS.TB_proposal);
	$("#content-product-seller a.phone-toggle").click(LAGOINHA.ANNOUNCEMENTS.togglePhone);
	LAGOINHA.ANNOUNCEMENTS.questionTabClicks();
	$("#print").click(LAGOINHA.ANNOUNCEMENTS.print);
	$(".howtoSignUp").click(LAGOINHA.ANNOUNCEMENTS.signUp);
	$(".simulateShipping").each( function(){ $(this).click(LAGOINHA.ANNOUNCEMENTS.shippingSimulator) } );
	$(".simulateShippingBt").each( function(){ $(this).click(LAGOINHA.ANNOUNCEMENTS.shippingSimulator) } );
	LAGOINHA.ANNOUNCEMENTS.addNewQuestionClick();
	LAGOINHA.ANNOUNCEMENTS.installClickUolLinks();
	LAGOINHA.ANNOUNCEMENTS.install_chat_links();
	LAGOINHA.ANNOUNCEMENTS.install_view_extended_photo();
	LAGOINHA.ANNOUNCEMENTS.createThumbLists();
	$("#ver-mais-trigger").click(LAGOINHA.ANNOUNCEMENTS.showChangeHistory);
}

$(
	function()
	{
		if( $( "body" ).is( ".ann-startup" ) )
		{
			LAGOINHA.ANNOUNCEMENTS.startup();
		}
	}
);
