/*
'================[DOCUMENTAÇÃO DE PROGRAMA]================
' SISTEMA     : BRZ - Simulador Imobiliario
' TRANSAÇÃO   : Simulador Imobiliário
' PROGRAMA    : brzs01hm.js
' FUNÇÃO      : Java script para as paginas brzw01hw.asp
' ANALISTA    : Dilcéia Alves
' PROGRAMADOR : Tiago De Toni
' DATA        : 19/09/2007
'=======================[MANUTENÇÕES]=======================
' Data        : 17/08/2011
' Programador : Aline Frozi
' Alteração   : Funções para Carência, ITBI e Emolumentos
'=============================================================
' Data        : 18/08/2011
' Programador : Aline Frozi
' Alteração   : Formatação de campos da tela
'===========================================================
*/

/**************************************************************************************************
Função    : function Recalcular()
Descrição : Ajustar campos da tela
**************************************************************************************************/
function Recalcular()
{    
    AjustaCampos(false);
    
    document.getElementById("divRetorno").style.display = "none";
    document.getElementById("erro").style.display = "none";	
    document.getElementById("btnRecalcular").style.display = "none";
    document.getElementById("btnCalcular").style.display = "";
}

/**************************************************************************************************
Função    : function AjustaCampos()
Descrição : Ajustar campos da tela
**************************************************************************************************/
function AjustaCampos(param)
{    
    document.getElementById("cboProponente").disabled = param;
    document.getElementById("cboImovel").disabled = param;
    document.getElementById("txtDataNasc").disabled = param;
    document.getElementById("txtPrazo").disabled = param;
    document.getElementById("txtValorImovel").disabled = param;
    document.getElementById("txtValorFinanc").disabled = param;
    document.frmDados.radTaxa[0].disabled = param;
    document.frmDados.radTaxa[1].disabled = param;
    //Novos campos
    document.getElementById("optCarencia").disabled = param;
    document.getElementById("optItbi").disabled = param;
    document.getElementById("optEmolumentos").disabled = param;
    if (param == false) {
        document.getElementById("lblCarencia").innerHTML           = ' ';
        document.getElementById("lblItbi").innerHTML               = ' ';
        document.getElementById("lblEmolumentos").innerHTML        = ' ';
        document.getElementById("lblTotalFinanciamento").innerHTML = ' ';
    }
}

/**************************************************************************************************
Função    : function MontaHTMLErro()
Descrição : Retorno do Ajax com erro
**************************************************************************************************/
function MontaHTMLErro(request)
{    
    var sHTML = request.responseText;
    document.getElementById("divRetorno").style.display = "none";
    document.getElementById("erro").style.display = "";	
    document.getElementById("erro").innerHTML = sHTML.substr(4);
}

/**************************************************************************************************
Função    : function MontaHTMLErro()
Descrição : Retorno do Ajax com erro
**************************************************************************************************/
function MontaHTMLErroException(sDescricao)
{    
    var sHTML = sDescricao;
    document.getElementById("divRetorno").style.display = "none";
    document.getElementById("erro").style.display = "";	
    document.getElementById("erro").innerHTML = sHTML.substr(4);
}

/**************************************************************************************************
Função    : function MontaHTMLResultado()
Descrição : Retorno do Ajax do Calcular
**************************************************************************************************/
function MontaHTMLResultado(request)
{    
    document.getElementById("erro").style.display = "none"; 
    
    var sHTML = request.responseText;
    if (sHTML.substr(0,4) != "ERRO")
    {
        document.getElementById("divRetorno").style.display = "";	
        document.getElementById("divRetorno").innerHTML = sHTML;    
        document.getElementById("btnRecalcular").style.display = "";
        document.getElementById("btnCalcular").style.display = "none";
        //Novos campos
        //document.getElementById("txtTotalFinanciamento").value = document.getElementById("retTotValFinanc").value;
        //document.getElementById("txtItbi").value = document.getElementById("retValItbi").value;
        //document.getElementById("txtEmolumentos").value = document.getElementById("retValEmol").value;
        //document.getElementById("txtCarencia").value = document.getElementById("retCarencia").value;
        if (document.getElementById("optCarencia").checked)
        {
            var sDescr = '';
            var prazoCarencia = 0;
            prazoCarencia = parseInt(document.getElementById("retCarencia").value);
            if(prazoCarencia == 1)
            {
                sDescr = prazoCarencia + ' mês';
            } else if (prazoCarencia > 1)
            {
                sDescr = prazoCarencia + ' meses';
            }
            document.getElementById("lblCarencia").innerHTML = sDescr;
        }
        if (document.getElementById("optItbi").checked)
            document.getElementById("lblItbi").innerHTML               = 'R$ ' + document.getElementById("retValItbi").value;
        if (document.getElementById("optEmolumentos").checked)
            document.getElementById("lblEmolumentos").innerHTML        = 'R$ ' + document.getElementById("retValEmol").value;
        document.getElementById("lblTotalFinanciamento").innerHTML = 'R$ ' + document.getElementById("retTotValFinanc").value;
        
        AjustaCampos(true);
    }
    else
    {
        MontaHTMLErro(request);
    }  	   			
}

/**************************************************************************************************
Função    : function MontaHTMLResultadoLista()
Descrição : Retorno do Ajax do Calcular
**************************************************************************************************/
function MontaHTMLResultadoLista(request)
{    
    document.getElementById("erro").style.display = "none"; 
    
    var sHTML = request.responseText;
    if (sHTML.substr(0,4) != "ERRO")
    {
        document.getElementById("divRetorno").style.display = "";	
        document.getElementById("divRetorno").innerHTML = sHTML;
    }
    else
    {
        MontaHTMLErro(request);
    }  	   			
}

/**************************************************************************************************
Função    : function MontaHTMLRelatorio()
Descrição : Retorno do Ajax do Relatorio
**************************************************************************************************/
function MontaHTMLRelatorio(request)
{
    document.getElementById("erro").style.display = "none";
    
    var sHTML = request.responseText;	
    
    if (sHTML.substr(0,4) != "ERRO")
    {
        window.open(sHTML.replace("<script>",""), 'Relatório');
    }
    else
    {
        MontaHTMLErro(request);	 
    }  
}	
            
/**************************************************************************************************
Função    : function Seleciona()
Descrição : Após escolher a taxa, vincula Sistema de Amortização
**************************************************************************************************/
function Seleciona()
{      
    if (document.frmDados.radTaxa[0].checked)
    {
        document.getElementById("radSistAmort").innerHTML = "SAC"
    }
    else
    {   
        document.getElementById("radSistAmort").innerHTML = "Price"
    }
}
            
/**************************************************************************************************
Função    : function Imprmir()
Descrição : Print Screen da tela
**************************************************************************************************/
function Imprmir()
{      
    window.print();
    window.focus();
}

/**************************************************************************************************
Função    : function Limpar()
Descrição : Limpa campos da tela
**************************************************************************************************/
function Limpar()
{   
    var oForm = document.frmDados ;	
    
    document.getElementById("cboProponente").disabled = false;
    document.getElementById("cboImovel").disabled = false;
    document.getElementById("txtDataNasc").disabled = false;
    document.getElementById("txtPrazo").disabled = false;
    document.getElementById("txtValorImovel").disabled = false;
    document.getElementById("txtValorFinanc").disabled = false;
    document.frmDados.radTaxa[0].disabled = false;
    document.frmDados.radTaxa[1].disabled = false;
   	
	for(var i=0;i<oForm.length;i++){
	   if((oForm[i].type == 'text') || (oForm[i].type == 'select-one'))
	      oForm[i].value = '';   	      
	}
    
	for(var i=0;i<oForm.length;i++){
	   if((oForm[i].type == 'checkbox'))
	      oForm[i].disabled = ''; 
	      oForm[i].checked = false;  	      
	}
	
	oForm.radTaxa[0].checked = true;
    document.getElementById("radSistAmort").innerHTML = "SAC";
	
    document.getElementById("lblCarencia").innerHTML           = ' ';
    document.getElementById("lblItbi").innerHTML               = ' ';
    document.getElementById("lblEmolumentos").innerHTML        = ' ';
    document.getElementById("lblTotalFinanciamento").innerHTML = ' ';
    
	oForm[0].focus();
	
    document.getElementById("btnRecalcular").style.display = "none";
    document.getElementById("btnCalcular").style.display = "";
    document.getElementById("divRetorno").style.display = "none";
    document.getElementById("divRelarorio").style.display = "none";
    document.getElementById("erro").style.display = "none";
}

/**************************************************************************************************
Função    : function Onload()
Descrição : Função acionada ao carregar a pagina
**************************************************************************************************/
function Onload(msg)
{
	if (msg != '')
	{
		alert(msg);
	}	
	
    document.getElementById("divRetorno").style.display = "none";
    document.getElementById("divRelarorio").style.display = "none";
    
    document.getElementById("btnRecalcular").style.display = "none";
    document.getElementById("btnCalcular").style.display = "";
}

/**************************************************************************************************
Função    : function Valida()
Descrição : Valida campos da tela
**************************************************************************************************/
function Valida()
{
    var oForm = document.frmDados ;
    var bPessoaJuridica = false ;
    
    for(var i=0;i<oForm.length;i++)
    {		   
        if(oForm[i].type=='text')
        {
            if((oForm[i].value == '') && (oForm[i].readOnly == false))
            {
                if (oForm[i].id == 'txtDataNasc')
                {
                    if (!bPessoaJuridica)   
                        alert('Data de Nascimento é obrigatória!');
                }
                if (oForm[i].id == 'txtPrazo')
                    alert('Prazo do Financiamento é obrigatório!');
                if (oForm[i].id == 'txtValorImovel')
                    alert('Valor do Imóvel é obrigatório!');
                if (oForm[i].id == 'txtValorFinanc')
                    alert('Valor do Financiamento é obrigatório!');
                
                if ((!bPessoaJuridica) | (oForm[i].id != 'txtDataNasc'))    
                {
                    oForm[i].focus();
                    return false;
                }
            }
            if ((!bPessoaJuridica) | (oForm[i].id != 'txtDataNasc'))    
            {
                if (oForm[i].id == 'txtDataNasc')
                {
                    if (!DataValida(oForm.txtDataNasc.value))
                    {
                        alert('Data inválida!');
                        oForm.txtDataNasc.focus();
                        return false;          
                    }
                    if (Maioridade(oForm.txtDataNasc.value))
                    {
                        alert('Idade não pode ser inferior a 18 anos!');
                        oForm.txtDataNasc.focus();
                        return false;          
                    }
                } 
            }           
            if ((oForm[i].id == 'txtValorImovel') | (oForm[i].id == 'txtValorFinanc'))
            {
                if ((oForm[i].value == "0,00"))
                {
                    alert('Valor deve ser maior que R$ 0,00');
                    oForm[i].focus();
                    return false;          
                }                
                
                var valor1 = oForm.txtValorImovel.value;
                valor1 = valor1.replace(/[.]/g,"");
                valor1 = valor1.replace(/[,]/g,"");
                var valorNumeric1 = 0;
                valorNumeric1 += Number(valor1);
                
                var valor2 = oForm.txtValorFinanc.value;
                valor2 = valor2.replace(/[.]/g,"");
                valor2 = valor2.replace(/[,]/g,"");
                var valorNumeric2 = 0;
                valorNumeric2 += Number(valor2);
                
                if (valorNumeric1 < valorNumeric2)
                {
                    alert(valorNumeric1 < valorNumeric2);
                    alert('O Valor do Imóvel deve ser maior que o Valor do Financiamento');
                    oForm[i].focus();
                    return false;          
                }
            }           
            if (oForm[i].id == 'txtPrazo')
            {
                if (oForm[i].value < 12)
                {
                    alert('O Prazo de Financiamento deve ser maior ou igual a 12 meses.');
                    oForm[i].focus();
                    return false;          
                }    
                if (oForm[i].value > 360)
                {
                    alert('O Prazo de Financiamento deve ser menor ou igual a 360 meses.');
                    oForm[i].focus();
                    return false;          
                }    
            }                
        }  
        if(oForm[i].type=='select-one')
        {
            if(oForm[i].value == '')
            {
                if (oForm[i].id == 'cboProponente')
                    alert('Tipo Proponente é obrigatório!');
                if (oForm[i].id == 'cboImovel')
                    alert('Tipo do Imóvel é obrigatório!');
                 
                oForm[i].focus();
                return false;
            }
            if (oForm[i].id == 'cboProponente')
            {
                if (oForm[i].value == '05')
                {
                    bPessoaJuridica = true;
                }
                else
                {
                    bPessoaJuridica = false;
                }
            }
        } 
    } 
    
    Calcular(false);
    
    return true;
}

/**************************************************************************************************
Função    : function VerificaProp()
Descrição : Verifica se é Pessoa Juridica e inibi campo
**************************************************************************************************/
function VerificaProp(oCampo)
{
    if (oCampo == '05')
    {
        document.getElementById("divDataNasc").style.display = "none";
        document.getElementById("txtDataNasc").style.display = "none";
        document.getElementById("txtDataNasc").value = "";
    }
    else
    {
        document.getElementById("divDataNasc").style.display = "";
        document.getElementById("txtDataNasc").style.display = "";
    }
}

/**************************************************************************************************
Função    : function 18anos()
Descrição : Verifica se é maior de 18 anos
**************************************************************************************************/
function Maioridade(Data)
{
    var DataAtual = new Date;
    var diaAtual = DataAtual.getDate() ;
    var mesAtual = DataAtual.getMonth() + 1 ;
    var anoAtual = DataAtual.getFullYear() ;
    
    if (diaAtual < 10)
        diaAtual = '0' + diaAtual ;
    if (mesAtual < 10)
        mesAtual = '0' + mesAtual ;      

	for (i=0;i<=Data.length;i++)
	{
		if (isNaN(Data.charAt(i)))
		{
			Separador = Data.charAt(i)
			if (Separador != "/")
				return false;
			dia = Data.substring(0,Data.indexOf(Separador));
			mes = Data.substring(Data.indexOf(Separador) + 1,Data.lastIndexOf(Separador));
			ano = Data.substring(Data.lastIndexOf(Separador) + 1,Data.length);
		}
	}
         
    if ((String(anoAtual - 18) + String(mesAtual) + String(diaAtual)) >= (ano + mes + dia))
	{
	    return false;   
	}	
    return true;
}

/**************************************************************************************************
Função    : function TrocaCheck(campo)
Descrição : Alterna a propriedade checked de um radio button
**************************************************************************************************/
function TrocaCheck(campo)
{
    campo.checked = !campo.checked;
}

/**************************************************************************************************
Função    : function Habilita(campo)
Descrição : Habilita um campo do formulário
**************************************************************************************************/
function Habilita(campo)
{
    document.getElementById(campo).disabled = '';
    document.getElementById(campo).readOnly = '';
    document.getElementById(campo).focus();
}

/**************************************************************************************************
Função    : function Zebrada(idTabela)
Descrição : Alterna as cores das linhas de uma tabela entre 2 cores
**************************************************************************************************/
function Zebrada(idTabela){
  var cor1 = "#dfecfd";
  var cor2 = "#ffffff";
  
  var linha = document.getElementById(idTabela).getElementsByTagName('tr');
  
  for(i=0; i<linha.length; i++)
      if (i%2 == 0)
      {
          linha[i].style.backgroundColor = cor1;
      }
      else
      {
          linha[i].style.backgroundColor = cor2;
      }
}

function SetaCampos(param)
{
    var postString = 'secao_id=<%=Session("Secao_Id")%>';
    var taxa;
    var tempString;
    
    postString = postString + '&COD_TIPO_PROPONENTE=' + document.getElementById("cboProponente").value ;
    tempString = document.getElementById("cboProponente").options[document.getElementById("cboProponente").selectedIndex].text;
    tempString = replaceAll(tempString, " ", "_");
    postString = postString + '&DESCR_PROPONENTE=' + tempString; 
    postString = postString + '&COD_TIPO_IMOVEL='     + document.getElementById("cboImovel").value ;
    tempString =   document.getElementById("cboImovel").options[document.getElementById("cboImovel").selectedIndex].text;
    tempString = replaceAll(tempString, " ", "_");
    postString = postString + '&DESCR_IMOVEL=' + tempString;
    if (document.getElementById("cboProponente").value != '05')
    {
        postString = postString + '&DATA_NASC='           + document.getElementById("txtDataNasc").value ;
    }
    if (document.getElementById("radTaxa").checked)
    {
        postString = postString + '&TAXA='            + '1' ;
        taxa = '1';
    }
    else
    {
        postString = postString + '&TAXA='            + '2' ;
        taxa = '2';
    } 
    if (taxa == '1')
    {
        postString = postString + '&SIST_AMORTIZACAO='+ 'S' ;
    }
    else
    {
        postString = postString + '&SIST_AMORTIZACAO='+ 'P' ;
    }   
    postString = postString + '&PRAZO_FINANCIAMENTO=' + document.getElementById("txtPrazo").value ;
    postString = postString + '&VLR_IMOVEL='          + document.getElementById("txtValorImovel").value ;
    postString = postString + '&VLR_FINANCIAMENTO='   + document.getElementById("txtValorFinanc").value ;
                    
    //*--Novos campos: Carência, ITBI e Emolumentos                
    postString = postString + '&OPT_CARENCIA=' + document.getElementById("optCarencia").checked;
    postString = postString + '&OPT_VLR_ITBI=' + document.getElementById("optItbi").checked;
    postString = postString + '&OPT_VLR_EMOL=' + document.getElementById("optEmolumentos").checked;                                
    
    if (param)
    {
        if (document.getElementById("radDemostrativo").checked)
        {
            postString = postString + '&TIPO_RELATORIO=S';
        }
        else
        {
            postString = postString + '&TIPO_RELATORIO=T';
        }
    }

    return postString;
}

function replaceAll(string, token, newtoken) {
	while (string.indexOf(token) != -1) {
 		string = string.replace(token, newtoken);
	}
	return string;
}
