var atualiza_botoes_atalho = true;
var atualiza_valor_text = true;

function acrescenta_valor_lance(leilao_id, lote_id, valor, prefixo)
{
	if(!prefixo) {
		prefixo = '';
	}
	field = prefixo + "vl_" + leilao_id + "_" + lote_id;
	var valor_atual = parseInt($("#" + field).val());

	if (isNaN(valor_atual)) {
		valor_atual = 0;
	} 

	if (isNaN(valor)) {
		valor = 0;
	}

	$("#" + field).val(valor_atual + valor);
}


function envialance(leilao_id, lote_id, vl_lance, nu_lote, prefixo)
{	
	if(!usuario_logado) {
		jAlert("Voc&ecirc; precisa esta logado para enviar lance", "Envio de Lance");
		return;
	}
	
        jConfirm("Deseja enviar o lance no valor de R$ " + vl_lance  + " no lote " + nu_lote + "?", "Envio de Lance", function(r) {
            if (r) {
                envialanceajax(leilao_id, lote_id, vl_lance, 0, nu_lote, prefixo, 1);
            } else {
                jAlert("Envio de lance cancelado", "Envio de Lance");
            }
        });
}

function envialanceajax(leilao_id, lote_id, vl_lance, is_telao, nu_lote, prefixo, lance_confirmado){
	
    if (is_telao == 0){
        //From atalho
        if (lance_confirmado != 1){
            jConfirm("Deseja enviar o lance no valor de R$ " + vl_lance  + " no lote " + nu_lote + "?", "Envio de Lance", function(r) {
                if (r) {
                    envialanceajax(leilao_id, lote_id, vl_lance, 0, 0, prefixo, 1);
                } else {
                    jAlert("Envio de lance cancelado", "Envio de Lance");
                }
            });
            return false;
        }
    }

    
    vl_lance = vl_lance.replace('.', '').replace(',', '.');
    loadAjax();
       
    $.ajax ({
            type: "GET",
            url: urllance,
            data: "leilao_id=" + leilao_id + "&lote_id=" + lote_id + "&vl_lance=" + vl_lance,
            success: function(msg){
    	
	            	try {
						var dados = eval ('(' + msg + ')');
					} catch(err) {
						alertaErroInterno();
						return;
					}
                    
                    if(dados['erro']) {
                            jAlert(dados['msg_erro'], "Envio de Lance");
                    } else {
                       atualizaLote(dados, prefixo);
                    }
            }
    });
}

function unloadAjax(){
    $("#status_conexao").html("");
}

function loadAjax(){
    $("#status_conexao").html("<img src='/image/pestana/loading.gif'>");
}

/*
 * Retorno do processo de atualiza��o por ajax
 * Recebe as informa��es da:
 * - Abas abertas
 * - Lista de lotes
 * - Lote em preview
 * - Lote em preg�o
 */
function atualizaLote(dados, prefixo)
{
	if(!prefixo) {
		prefixo = '';
	}
	lotes_abertos = dados['lote_aberto'];
	
	//alert(lotes_abertos);
	
	//Dados de html da listagem do leil�o
	if (dados['listagem'] != null){
		$("#listagem").html(dados['listagem']);
	}
	
	if (dados['dados_lote_preview'] != null){
		label = "#preview_" + dados['dados_lote_preview']['leilao_id']  + "_" + dados['dados_lote_preview']['lote_id']; 
		setDadosLote(label, dados['dados_lote_preview'], "preview_",dados['usuario_id']);
		//Atualiza select html de listagem de lotes
	   	$(label + " #cmb_lotes").html(dados['lotes_combo']['id']);
	}
		

	
	if(dados['bypass_lote_empregao'] == null) {		
		if (dados['dados_lote_empregao'] != null){		
			
			label = "#empregao_" + dados['dados_lote_empregao']['leilao_id'];

			$("#aba_em_pregao").css('display', '');
			//$("#aba_em_pregao").show();		
			
			if(lote_empregao_id == '') {			
				$("#lote_em_pregao").html(dados['html_lote_empregao']);
			} else {
				setDadosLote(label, dados['dados_lote_empregao'], "empregao_",dados['usuario_id']);
			}
			
		}else{
			if(tabView != null && tabView.get('activeIndex') == 1) {
				exibeLista();
			}
			
			$("#aba_em_pregao").hide();
			$("#lote_em_pregao").hide();			

		}
	}
	
	if (dados['dados_abas'] != null){
		for (var lote_id_abas in dados['dados_abas']){
			label = "#aba_" + dados['dados_abas'][lote_id_abas]['leilao_id']  + "_" + dados['dados_abas'][lote_id_abas]['lote_id']; 
			setDadosLote(label, dados['dados_abas'][lote_id_abas], "aba_",dados['usuario_id']);
			atualiza_status_aba(dados['dados_abas'][lote_id_abas]['leilao_id'], dados['dados_abas'][lote_id_abas]['lote_id'], dados['dados_abas'][lote_id_abas]['status_aba_icone'], dados['dados_abas'][lote_id_abas]['nu'])
		}
		
	}
	
	if(dados['lotes_repasse_md5'] != null && lotes_repasse_md5 != null) {
		//	Atualiza lista de lotes em repasse
		if(dados['lotes_repasse_md5'] != lotes_repasse_md5) {
			$("#lotes_repasse").html(dados['lotes_repasse']);
			init_lotes_repasse();
			lotes_repasse_md5 = dados['lotes_repasse_md5'];
		}
		
	}

	$(".icone_loading").hide();
}


/*
 * Processa as informa��es da ficha seja ela da "preview", "em preg�o" ou "aba"
 */
function setDadosLote(label, lote, prefixo,usuario_logado){

	
	if(lote['statuslote'] != "Vendido"){
		eval("vencedor_" + lote['lote_id'] + "= true");
	}
	
	//alert(usuario_logado);
	
	if (prefixo == "empregao_"){
		if(lote['lote_id'] != lote_empregao_id) {
			loadGaleria(lote['lote_id'], "empregao_");
			
			var html_lance = $("#lance_enviar").html();
			$("#empregao_lance_enviar").hide();
			//$("#empregao_historico_lance_box").hide();
			$("#empregao_lance_enviar_mensagem").show();
			lote_empregao_id = lote['lote_id'];
		}

		
		if($("#empregao_historico_lance_box") && $("#empregao_historico_lance_box").attr("href")) {
			var href = $("#empregao_historico_lance_box").attr("href").replace(/lote_id=[0-9]+/, "lote_id=" + lote['lote_id']);
			$("#empregao_historico_lance_box").attr("href", href);
		}
			
		if($("#empregao_limite_lance_box") &&  $("#empregao_limite_lance_box").attr("href")) {
			href = $("#empregao_limite_lance_box").attr("href").replace(/lote_id=[0-9]+/, "lote_id=" + lote['lote_id']);
			$("#empregao_limite_lance_box").attr("href", href);
		}
	}
	
	
	
	
	//Verifica se a aba ativa � a aba em pregao
/*	if(tabView.get('activeTab') == "Tab aba_em_pregao")
	{
		//Verifica se o lote foi trocado, exibe mensagem de aviso ao usuario
		if($(label + " #lote_nu").html() != lote['nu']){
	
			//Esconde os controles de lance
			
			var html_lance = $("#lance_enviar").html();
			$("#empregao_lance_enviar").hide();
			$("#empregao_historico_lance_box").hide();
			$("#empregao_lance_enviar_mensagem").show();*/
			
//			jConfirm("Lote em pregão alterado!\nDeseja participar do próximo lote?", "Lote em pregão alterado",function(ok) {
//				if(ok) {
//						//Exibe os controles de lance
//					
//						//$("#lance_enviar").html(html_lance);
//						
//						$("#lance_enviar").show();
//						$("#lance_enviar_mensagem").hide();
//		        }
//		        else {
//		                jAlert("Participação Cancelada", "Participação Cancelada");
//		                tabView.set('activeIndex', 0);
//		                $("#listagem").show();
//		                $("#lance_enviar").show();
//		        }
//			});
//		}
//	}
	
	$(label + " #lote_usuariostatus").html(lote['usuario_status']);
	// lanceautomatico
	$(label + " #lote_usuariolanceautomatico").html(text_format(lote['vl_lanceautomatico']));
	if(lote['vl_lanceautomatico_raw'] > 0) {
		// visible botao excluir
		$(label + " #lote_usuariolanceautomatico_botao_excluir").show();
	} else {
		// hide botao excluir
		$(label + " #lote_usuariolanceautomatico_botao_excluir").hide();
	}
	
	$(label + " #lote_titulo_lance").html(lote['titulo_lance']);
	
	if(lote['nm_usuario'] != '')
	{
		var separador = "/";
	}else{
		var separador = "";
	}
	
	if(lote['nm_uf'] == null) {
		$(label + " #lote_usuario_apelido_uf").html(lote['nm_usuario']);
	} else {
		$(label + " #lote_usuario_apelido_uf").html(lote['nm_usuario'] + separador + lote['nm_uf']);	
	} 
		
	$(label + " #lote_lanceatual").html(lote['vl_lance']);
	$(label + " #lote_temlanceauto").val(lote['tem_lance_auto']);
	//TODO Verificar $(label + " #lote_statuslote").html(lote['statuslote']);
	
	if(lote['statuslote'] != "Repasse com Lance"){
		$(label + " #lote_statuslote_nobr").html(lote['statuslote']);	
	}else{
		$(label + " #lote_statuslote_nobr").html("Repasse");
	}
	
	
	//Tratamento para exibir a mensagem para o arrematante do lote.
	if(lote['statuslote'] == "Vendido" && eval("vencedor_" + lote['lote_id']) == true && $("#lote_id_atual").val() == lote['lote_id'] && usuario_logado == lote['usuario_id'])
	{
		jAlert('Parabéns '+lote['nm_usuario']+', você venceu o lote '+lote['nu']+', '+lote['nm_titulo'],'Parabéns');
		eval("vencedor_" + lote['lote_id'] + "= false");
	}
	

	$(label + " #lote_statusloteIcone").css("background-image", "url(/image/" + lote['status_aba_icone'] + ")");
	$(label + " #lote_statusloteBg").css("background-image", "url(/image/" + lote['statusLoteBg'] + ")");
	
	
	$(label + " #lote_incremento").html(lote['vl_incremento']);
	$(label + " #lote_apelido").html(lote['nm_usuario']);

	$(label + " #lote_nu").html(lote['nu']);
	$(label + " #lote_imgStatus").attr("src", "/image/" + lote['status_aba_icone']);
	
	$(label + " #lote_data").html(lote['dt_fechamento_formatado']);
	$(label + " #lote_previsao").html(lote['dt_fechamento_formatado']);
	$(label + " #lote_descr").html(lote['nm_titulo']);
	$(label + " #lote_titulo").html(lote['nm_titulo']);
	$(label + " #lote_lance").html(text_format(lote['vl_lance']));
	$(label + " #lote_vencendo").html(text_format(lote['nm_usuario']));
	$(label + " #lote_usuariolanceatual").html(text_format(lote['usuario_lance_atual']));
	//$(label + " #lote_nu_lance").val("xxxxxxxxxxx");
	$(label + " #lote_id_lance").val(text_format(lote['lote_id']));
	$(label + " #lote_nm_titulo_vistoria").val(text_format(lote['nm_titulo']));
	$(label + " #lote_nu_lance").val(text_format(lote['nu']));
	
	var cleilao_id = $("#cleilao_id").val();
    var atual_lance_sugerido = $(label + " #lote_vl_sugerido");
    var atual_lance = $(label + " #lote_vl");
    
    var atualiza_atalho=false;
    var atualiza_text=false;
    
    var x = $(label + " #lote_atualiza_botoes_atalho");
    var perm = $(label + " #lote_permissao_lance").val();
    
    if (prefixo == "empregao_"){
    	var label_xcontrol = prefixo + 'xcontrol';
    	var label_scroll = prefixo + 'scroll';
    	var label_botoes_incremento = 'botoes_incremento_pregao';
    	
    	//Esconde os controles de proximo/anterior | Op��es de visualiza��o
		$(label + " #navegacao_lotes").hide();
		$(label + " #opcoes_visualizacao").hide();
		
		//loadGaleria(lote['lote_id'], "empregao_"); 
    	
    }else{
    	var label_xcontrol = prefixo + 'xcontrol_' + lote['lote_id'];
    	var label_scroll = prefixo + 'scroll_' + lote['lote_id']
    	var label_botoes_incremento = 'botoes_incremento_' + lote['lote_id'];    	
    }
     
    	
    if(usuario_logado && perm == '1') {
        if (parseFloat(atual_lance_sugerido.val()) != parseFloat(lote['vl_lance_sugerido_raw'])) {	
            if (x.val() == 'true' && eval(label_xcontrol + ' == false')){                                        	
                eval(label_xcontrol + ' = true');	
               
            	eval('var bti = window.' + label_botoes_incremento);
            	
            	for (var x in bti) {
            		if(bti[x] == lote['vl_lance_sugerido']) {
            			eval(label_scroll + '.seekTo(' + x + ', 400);');                   	
            		}
            	}
            	
            	var botoes_atalho = $(label + " #lote_item_botao");
                var s  = '<input type="button" onClick="confirma_envialanceabas(' + lote['leilao_id'] + ',' + lote['lote_id'] + ',' + '\'' + lote['vl_lance_sugerido'] + '\', \'' + lote['nu'] + '\' , \'' + prefixo + '\', \'' + lote['nm_titulo'] + '\' );" class="box_lances" value="' + lote['vl_lance_sugerido'] + '" />'
                    s += '<input type="button" onClick="confirma_envialanceabas(' + lote['leilao_id'] + ',' + lote['lote_id'] + ',' + '\'' + lote['vl_lance_sugerido2'] + '\', \'' + lote['nu'] + '\', \'' + prefixo + '\', \'' + lote['nm_titulo'] + '\' );" class="box_lances" value="' + lote['vl_lance_sugerido2'] + '" />';
                    s += '<input type="button" onClick="confirma_envialanceabas(' + lote['leilao_id'] + ',' + lote['lote_id'] + ',' + '\'' + lote['vl_lance_sugerido3'] + '\', \'' + lote['nu'] + '\', \'' + prefixo + '\', \'' + lote['nm_titulo'] + '\' );" class="box_lances" value="' + lote['vl_lance_sugerido3'] + '" />';
                    s += '<input type="button" onClick="confirma_envialanceabas(' + lote['leilao_id'] + ',' + lote['lote_id'] + ',' + '\'' + lote['vl_lance_sugerido4'] + '\', \'' + lote['nu'] + '\', \'' + prefixo + '\', \'' + lote['nm_titulo'] + '\' );" class="box_lances" value="' + lote['vl_lance_sugerido4'] + '" />';
                    s += '<input type="button" onClick="confirma_envialanceabas(' + lote['leilao_id'] + ',' + lote['lote_id'] + ',' + '\'' + lote['vl_lance_sugerido5'] + '\', \'' + lote['nu'] + '\', \'' + prefixo + '\', \'' + lote['nm_titulo'] + '\' );" class="box_lances" value="' + lote['vl_lance_sugerido5'] + '" />';
                    s += '<input type="button" onClick="confirma_envialanceabas(' + lote['leilao_id'] + ',' + lote['lote_id'] + ',' + '\'' + lote['vl_lance_sugerido6'] + '\', \'' + lote['nu'] + '\', \'' + prefixo + '\', \'' + lote['nm_titulo'] + '\' );" class="box_lances" value="' + lote['vl_lance_sugerido6'] + '" />';
                    s += '<input type="button" onClick="confirma_envialanceabas(' + lote['leilao_id'] + ',' + lote['lote_id'] + ',' + '\'' + lote['vl_lance_sugerido7'] + '\', \'' + lote['nu'] + '\', \'' + prefixo + '\', \'' + lote['nm_titulo'] + '\' );" class="box_lances" value="' + lote['vl_lance_sugerido7'] + '" />';
                    s += '<input type="button" onClick="confirma_envialanceabas(' + lote['leilao_id'] + ',' + lote['lote_id'] + ',' + '\'' + lote['vl_lance_sugerido8'] + '\', \'' + lote['nu'] + '\', \'' + prefixo + '\', \'' + lote['nm_titulo'] + '\' );" class="box_lances" value="' + lote['vl_lance_sugerido8'] + '" />';
                    s += '<input type="button" onClick="confirma_envialanceabas(' + lote['leilao_id'] + ',' + lote['lote_id'] + ',' + '\'' + lote['vl_lance_sugerido9'] + '\', \'' + lote['nu'] + '\', \'' + prefixo + '\', \'' + lote['nm_titulo'] + '\' );" class="box_lances" value="' + lote['vl_lance_sugerido9'] + '" />';
                                            
                botoes_atalho.html(s);
                               
                eval(label_scroll + '.seekTo(0, 0);');

                var str_eval =  '' + label_botoes_incremento;
                eval(str_eval + ' = new Array();');
                eval(str_eval + '.push("' + lote['vl_lance_sugerido'] + '")');
                eval(str_eval + '.push("' + lote['vl_lance_sugerido2'] + '")');
                eval(str_eval + '.push("' + lote['vl_lance_sugerido3'] + '")');
                eval(str_eval + '.push("' + lote['vl_lance_sugerido4'] + '")');
                eval(str_eval + '.push("' + lote['vl_lance_sugerido5'] + '")');
                eval(str_eval + '.push("' + lote['vl_lance_sugerido6'] + '")');
                eval(str_eval + '.push("' + lote['vl_lance_sugerido7'] + '")');
                eval(str_eval + '.push("' + lote['vl_lance_sugerido8'] + '")');
                eval(str_eval + '.push("' + lote['vl_lance_sugerido9'] + '")');
                                    
                atualiza_atalho=true;
                eval(label_xcontrol + ' = false');
                
            }

            if (atualiza_valor_text){
                atual_lance.val(lote['vl_lance_sugerido'], 2, ',', '.');
                
                atualiza_text=true;
            }

            if ((atualiza_atalho==true) && (atualiza_text==true)){
                atual_lance_sugerido.val(lote['vl_lance_sugerido_raw']);
                atualiza_atalho=false;
                atualiza_text=false;
            }
        }    
	}
    
    // mensagens do leiloeiro
	var mensagem_leiloeiro = '';
	for (var x in lote['mensagens_lote']) {
		mensagem_leiloeiro += '<tr>';
		mensagem_leiloeiro += '<td><img src="/image/img_alert_' + lote['mensagens_lote'][x]['statusmensagem_id'] + '.png" alt=""></td>';
		mensagem_leiloeiro += '<td>';
		mensagem_leiloeiro += '<strong>' + lote['mensagens_lote'][x]['data'] + '</strong><br>';
		mensagem_leiloeiro += lote['mensagens_lote'][x]['nm_mensagem'];
		mensagem_leiloeiro += '</td>';
		mensagem_leiloeiro += '</tr>';
	}	
	$(label + " #lote_mensagem").html(mensagem_leiloeiro);
	
	$(label + " #lote_vistoria").html(lote['vistorias_render']);  
	
	if(lote['lote_id'] != $(label + " #lote_id_atual").val())
	{
		//Adiciona as imagens do lote para atualizar via ajax		
		$(label + " #lote_fotos").html(lote['fotos_lote']);
		$(label + " #lote_id_atual").val(lote['lote_id']);
	
		if (prefixo == "empregao_"){
			loadGaleria(lote['lote_id'], "empregao_");
		}
	
	}	
	//Atualiza informa��es sobre lance automatico
	$(label + " #lote_usuariolanceautomatico").val(lote['vl_lanceautomatico']);
}

function atualizaLanceAutomatico(){
	$(label + " #lote_usuariolanceautomatico").html('');
	$(label + " #lote_usuariolanceautomatico_botao_excluir").hide();
}

function atualizaLoteLimiteLance(dados,prefixo,lote_id){
	
	$(label + " #lote_usuariolanceautomatico").html(dados['lotes'][lote_id]['vl_lanceautomatico']);
	$(label + " #lote_usuariolanceautomatico_botao_excluir").show();
}

function text_format(str) {
	if (str == null || str.length == 0 || str == "" || str == " ") {
		return "-";
	} else {
		return str;
	}
}

function desabilitaElementos(content) {
	toggleDisabled(content);
}
		function toggleDisabled(el) {
			try {
				el.disabled = el.disabled ? false : true;
			}
		catch(E){
		}
			if (el.childNodes && el.childNodes.length > 0) {
			for (var x = 0; x < el.childNodes.length; x++) {
				toggleDisabled(el.childNodes[x]);
			}
		}
	}
		
//MENU
	$(document).ready(function(){  
		
		$('#jsddm > li').hover(function() {
	        $(this).find('ul').css('visibility', 'visible');
	    },
	    function() {
	      $(this).find('ul').css('visibility', 'hidden');;
	    });
	
	});	


