var resultado;
var msgCamposObrigatorios = "Os seguintes campos são obrigatórios: ";
var msgCamposNumericos = "Os seguintes campos são numéricos: ";
var msgCamposTelefoneInvalido = "Telefone Inválido";
var msgCamposEmailInvalido = "Email Inválido";
var msgCamposNumeroInvalido = "Número Inválido";
var msgCamposTextoInvalido = "Campo Inválido";

//MSG em EN
var msgCamposObrigatorios_EN = "The following are obligatory fields: ";
var msgCamposNumericos_EN = "The following are numerical fields: ";
var msgCamposTelefoneInvalido_EN = "Invalid phone number";
var msgCamposEmailInvalido_EN = "Invalid Email";
var msgCamposNumeroInvalido_EN = "Invalid number";
var msgCamposTextoInvalido_EN = "Invalid field";

//MSG em FR
var msgCamposObrigatorios_FR = "Les champs suivants sont obligatoires: ";
var msgCamposNumericos_FR = "Les champs suivants sont numériques: ";
var msgCamposTelefoneInvalido_FR = "Numéro de téléphone Invalide";
var msgCamposEmailInvalido_FR = "Email Invalide";
var msgCamposNumeroInvalido_FR = "Numéro Invalide";
var msgCamposTextoInvalido_FR = "Champ Invalide";

//MSG em DE
var msgCamposObrigatorios_DE = "Die folgende Felder sind obligatorisch: "
var msgCamposNumericos_DE = "Die folgende Felder sind numerisch: ";
var msgCamposTelefoneInvalido_DE = "Telefonnummer nicht gültig";
var msgCamposEmailInvalido_DE = "Email nicht gültig";
var msgCamposNumeroInvalido_DE = "Zahl nicht gültig";
var msgCamposTextoInvalido_DE = "Feld nicht gültig";

//MSG em ES
var msgCamposObrigatorios_ES = "Os seguintes campos são obrigatórios: ";
var msgCamposNumericos_ES = "Os seguintes campos são numéricos: ";
var msgCamposTelefoneInvalido_ES = "Telefone Inválido";
var msgCamposEmailInvalido_ES = "Email Inválido";
var msgCamposNumeroInvalido_ES = "Número Inválido";
var msgCamposTextoInvalido_ES = "Campo Inválido";


var firstime = true;
var valConta = true;

var optionsTaxaID = new Array(20);
var optionsTaxaIDText = new Array(20);
var optionsTaxaIDValue = new Array(20);

var camposComProblemas = new Array(50);

var valoresCamposOriginais = new Array(6);
var nomeCamposOriginais = new Array("STEP_ID","ID_SIMULACAO","VertenteCod","VersaoCod", "TipoSimulacaoCod", "EmpresaCod");

// guardar valor variaveis default
var auxIdSimulacao = "";
var auxIdStep = "";
var auxVertenteCod = "";
var auxVersaoCod = "";
var auxTipoSimulacaoCod = "";
var auxEmpresaCod = "";

function validaProponentes(){
	if (document.formSimuladores.NrProponentes.selectedIndex == 0)
		document.formSimuladores.SeguroVida.selectedIndex = 0;
}

function skipObrig(c) {
	if (typeof(arrNomes) == "undefined" || typeof(arrObrigatorios) == "undefined")
		return;
	
	for (x=0; x < arrNomes.length; x++)
		if (arrNomes[x] == c) {
			arrObrigatorios[x] = 0;
			return;
		}
}

function ligaObrig(c) {
	if (typeof(arrNomes) == "undefined" || typeof(arrObrigatorios) == "undefined")
		return;
		
    for (x=0; x < arrNomes.length; x++)
		if (arrNomes[x] == c) {
			arrObrigatorios[x] = 1;
			return;
		}
}

function skipValConta() {
    valConta = false;
}

// recebe um nome de Campo e verifica se é obrigatório
function ehCampoObrigatorio(nomeCampo){
	var n;
	
	for (n = 0; n < arrNomes.length; n++) {
		if (nomeCampo == arrNomes[n]) 
			if (arrObrigatorios[n] == 1)
				return n + 1;
			else
				return false;
	}
	
	return false;
}

//Recebe um nome de campo e verifica se é numero de conta
function ehCampoConta(nomeCampo){
	var n;
	
	for (n = 0; n < arrNomes.length; n++) {
		if (arrNomes[n] == nomeCampo)
			break;
	}
	if (arrTipos[n] == "NUMCONTA")
		return n + 1;
	else 
		return false;
}

// recebe um nome de Campo e verifica se é numérico
function ehCampoNumerico(nomeCampo){
	var n;
	
	for (n = 0; n < arrNomes.length; n++) {
		if (arrNomes[n] == nomeCampo)
			break;
	}
	if (arrTipos[n] == "NUM" || arrTipos[n] == "PRC" || arrTipos[n] == "MOE")
		return n + 1;
	else 
		return false;
}

function validarNumContribuinte(numContribuinte){ 
	if (("" + numContribuinte + "") == "")
		return 0;
		
	cdnc="";
	
	if(numContribuinte=="000000000" || numContribuinte=="123456789") {
		return -1;	
	}
	
	//tabela de pesos para validar o check-digit do nº de central de risco
	cdnc+="987654321";
	//inicialização do acumulador
	cd=0;
	//início do cálculo
	for(i=0;i<8;i++)
	{
		//soma do produto do nº de central pelos pesos
		n1= parseInt(numContribuinte.charAt(i));
		n2= parseInt(cdnc.charAt(i));
		cd+=(n1*n2);
	}
	
	//check-digit
	j=11-(cd%11);
	//se o check-digit for maior ou igual a 10
	if(j>=10)
		j=0;
	//comparação com o check-digit
	if(numContribuinte.charAt(8)!=j) {
		return -1;	
	}
	return 0;
}

function existeCampo(nomeCampo){
	var n;
	for (n = 0; n < document.formSimuladores.elements.length; n++) {

		if (document.formSimuladores.elements[n].name == nomeCampo) {
			return 1;
		}
	}

	return 0;
}

function PreencheProf2(){
	document.formSimuladores.Profissao2.value=(""+document.formSimuladores.ProfNID2.options.item(document.formSimuladores.ProfNID2.selectedIndex).text).substr(0,40);
}

function ValidaSituacao(){
	if((document.formSimuladores.SituacaoResid.value=='1' || document.formSimuladores.SituacaoResid.value=='4' || document.formSimuladores.SituacaoResid.value=='5')
		&& document.formSimuladores.SituacaoResidAnos.value==""){
			
		var identificador_lingua =  document.formSimuladores.ID_LINGUA.value;	
			
			if(identificador_lingua == 1)
				alert(msgCamposObrigatorios_EN + " Nº of years.");
			else if(identificador_lingua == 3)
				alert(msgCamposObrigatorios_FR + " Nº d'années.");
			else if(identificador_lingua == 6)
				alert(msgCamposObrigatorios_DE + " Zahl der Jahre.");
		else if(identificador_lingua == 4)
			alert(msgCamposObrigatorios_ES + " Nº of years.");	
			else
				alert(msgCamposObrigatorios + " Nº de anos.");
			return false;
	}
	return true;
}

function envia(msgAguardar, recuar) {
	var inputElements;
	var nProblemas;
	var empresaCod;
	var n;

	if (typeof(arrNomes) == "undefined")
		return document.formSimuladores.submit();

	inputElements = new Object(document.formSimuladores.elements);

	if (document.getElementById("EmpresaCod") != null)
		empresaCod = document.getElementById("EmpresaCod").value;

	// ***************************************
	// Vamos verificar campos obrigatórios...
	// ***************************************
	
	nProblemas = 0;
	
	if(recuar != 1){
		for (i = 0; i < inputElements.length; i++) {
			// se não estiver vazio, vamos ver se é obrigatório...		
			if (inputElements[i].value == "" && (n = ehCampoObrigatorio(inputElements[i].name))) {
				camposComProblemas[nProblemas++] = arrLabels[n - 1];
	
				// pode ser que o campo esteja escondido... caso seja é ignorado
				if ((inputElements[i].name == "ValorCompra") &&
						(document.formSimuladores.ValorCompra.style.visibility == "hidden")) {					
						nProblemas--;					
						inputElements[i].value = 0;
				}
			}else {
				if ((inputElements[i].name == "ValorCompra") &&
						(document.formSimuladores.ValorCompra.style.visibility == "hidden")) 
					inputElements[i].value = 0;								 
			}
		}
		
		var mensagem;
	
	var identificador_lingua =  document.formSimuladores.ID_LINGUA.value;
	
		if (nProblemas) {
		
		if(identificador_lingua == 1)
			mensagem = msgCamposObrigatorios_EN + " ";
		else if(identificador_lingua == 3)			
			mensagem = msgCamposObrigatorios_FR + " ";
		else if(identificador_lingua == 6)			
		    mensagem = msgCamposObrigatorios_DE + " ";	
		else if(identificador_lingua == 4)			
		    mensagem = msgCamposObrigatorios_ES + " ";	
		else
			mensagem = msgCamposObrigatorios + " ";
		
			for (n = 0; n < nProblemas; n++) {
				mensagem = mensagem + camposComProblemas[n];
				if (n < nProblemas - 1) {
					mensagem = mensagem + ", ";
				}
			}		
			alert (mensagem);
			return false;
		}
	
		// ***************************************
		// Vamos verificar campos numéricos..
		// ***************************************
		var valor;
		var re = /,/g;
		var aux;
		
		nProblemas = 0;
		
		for (i = 0; i < inputElements.length; i++) {
			// se não estiver vazio e se não for numérico, vamos ver se é campo numérico...
			aux = inputElements[i].value;
			valor = retiraFormatacaoCamposMoeda(aux);
			valor = valor.replace(re, ".");
			if (valor != "" && isNaN(valor) && (n = ehCampoNumerico(inputElements[i].name))) {
	//			alert("1 label: [" + arrLabels[n -1] + " n: " + n + " " + arrNomes.length + " " + arrLabels.length);
				camposComProblemas[nProblemas++] = arrLabels[n - 1];
			}	
			if ((valor < 0) && (n = ehCampoNumerico(inputElements[i].name))) {
				camposComProblemas[nProblemas++] = arrLabels[n - 1];
			}
			
			if ((valor < 0) && (n = ehCampoConta(inputElements[i].name))) {
				valor = retiraFormatacaoConta(aux);
				camposComProblemas[nProblemas++] = arrLabels[n - 1];
			}
		}
			
		if (nProblemas) {
	
		if(identificador_lingua == 1)
			mensagem = msgCamposNumericos_EN + " ";
		else if(identificador_lingua == 3)	
			mensagem = msgCamposNumericos_FR + " ";
		else if(identificador_lingua == 6)	
			mensagem = msgCamposNumericos_DE + " ";	
		else if(identificador_lingua == 4)	
			mensagem = msgCamposNumericos_ES + " ";	
		else
			mensagem = msgCamposNumericos + " ";
			
			for (n = 0; n < nProblemas; n++) {
				mensagem = mensagem + camposComProblemas[n];
				if (n < nProblemas - 1) {
					mensagem = mensagem + ", ";
				}
			}		
			alert (mensagem);
			return false;
		}
	}	

	var x;
	
	if (existeCampo("NrContribuinte")) {			
		if (validarNumContribuinte(document.formSimuladores.NrContribuinte.value)) { 
			if(identificador_lingua == 1)
				alert ("Invalid Taxpayer ID number.");
			else if(identificador_lingua == 3)
				alert ("Numéro de contribuable non valable.");	
			else if(identificador_lingua == 6)
				alert ("Steuernummer nicht gültig.");
			else
				alert ("Número de contribuinte inválido.");
			return false;	
		}
	}
	
	if (empresaCod == "BEST" && existeCampo("PatrimonioCliente")) {			
		if (validarMontanteAvaliacao(document.formSimuladores, "PatrimonioCliente")) { 
			alert ("O montante do empréstimo não pode exceder 90% do valor da avaliação");
			return false;	
		}
	}
	
	if (existeCampo("PCAP")) {
		if (existeCampo("PremioCAP") && (!document.formSimuladores.PCAP[0].checked) && firstime) 
			document.formSimuladores.PremioCAP.value = "";
			
		if (existeCampo("ValorCAP") && (!document.formSimuladores.PCAP[0].checked) && firstime) 
			document.formSimuladores.ValorCAP.value = "";
			
		if (existeCampo("ValorCAP") && (!document.formSimuladores.PCAP[0].checked) && firstime) 
			document.formSimuladores.PrazoCAP.value = "";
	}
	
	if(msgAguardar) {
		try {
			document.all['MsgAguardar'].style['display'] = "";
			document.all['EcranPrincipal'].style['display'] = "none";
		} catch (e) {}
	}
	document.forms["formSimuladores"].submit();
}

function selectTipoTaxa(){
	var indexSelectedTaxaID;
	indexSelectedTaxaID = document.formSimuladores.TaxaID.selectedIndex;
	valorTaxa = document.formSimuladores.TaxaID[indexSelectedTaxaID].value;

    var tp_taxa;
    
	if (valorTaxa <= 3 || valorTaxa >= 12)
		tp_taxa = document.formSimuladores.TipoTaxa.value = 1;	

	if (valorTaxa > 3 && valorTaxa < 10)
		tp_taxa = document.formSimuladores.TipoTaxa.value = 2;

	if (valorTaxa == 10)
		tp_taxa = document.formSimuladores.TipoTaxa.value = 3;
	
	if(document.formSimuladores.Finalidade.value == 1)
	    tp_taxa = 0;
	    
	return tp_taxa;	
}

function MudaCampos(step_id, id_simulacao, VertenteCod, VersaoCod, TipoSimulacaoCod, EmpresaCod){	
	if (step_id != "")
		document.formSimuladores.STEP_ID.value = step_id;
	if (id_simulacao != "")
		document.formSimuladores.ID_SIMULACAO.value = id_simulacao;
	if (VertenteCod != "")
		document.formSimuladores.VertenteCod.value = VertenteCod;
	if (VersaoCod != "")
		document.formSimuladores.VersaoCod.value = VersaoCod;
	if (TipoSimulacaoCod != "")
		document.formSimuladores.TipoSimulacaoCod.value = TipoSimulacaoCod;
	if (EmpresaCod != "")		
		document.formSimuladores.EmpresaCod.value = EmpresaCod;
}

function trataValoresOriginais(){
	var n;
	var auxNomeCampos;
	var aux;
	var pos;

	if (document.formSimuladores.FIRST_LOAD.value == 0) {
		auxNomeCampos = "";
		// 1ª vez, guardar os valores originais
		for (n = 0; n < nomeCamposOriginais.length; n++) {
			valoresCamposOriginais[n] = document.formSimuladores.elements[nomeCamposOriginais[n]].value;
			if (!n)
				auxNomeCampos = document.formSimuladores.elements[nomeCamposOriginais[n]].value;
			else
				auxNomeCampos = auxNomeCampos + "," +  document.formSimuladores.elements[nomeCamposOriginais[n]].value;
		}
		document.formSimuladores.FIRST_LOAD.value = auxNomeCampos;
	}
	else {
		aux = document.formSimuladores.FIRST_LOAD.value;
		
		n = 5;
		pos = aux.lastIndexOf(",");
		while (pos != -1) {
			document.formSimuladores.elements[nomeCamposOriginais[n]].value = aux.slice(pos + 1);
			aux = aux.slice(0, pos);				
			pos = aux.lastIndexOf(",");
			n--;
		}
		
		document.formSimuladores.elements[nomeCamposOriginais[n]].value = aux;
	}
}

//NUMERO DE CONTA
function formataConta(campo){
	if(""+campo == "")
		return;
	
	var auxValor;
	var n;
	var valor;
	var valorOut;
	var aux;
	var j;
	var restante;
	var pos;	
	
	valor = retiraFormatacaoConta(campo);	
	aux = "";	
	
	pos = valor.lastIndexOf(",");
	restante = "";
	
	if (pos == -1)
		start = valor.length - 1;
	else {
		start = pos - 1;
		restante = valor.slice(pos, pos + 4);
	}
	
	//verificar aqui se é numero, se não for não corrige
	if (pos == -1) {
		if (isNaN(valor))
			return;	
	}
	else {
		if (pos == valor.length - 1)
			return;
		if (isNaN(valor.slice(0, pos)))
			return;
		
		if (isNaN(valor.slice(pos + 1)))
			return;
	}
	
	// VAMOS FORMATAR O VALOR
	j = 0;
	for (n = start; n >= 0; n-- ) 
	{
		if (j == 4) {
			aux = aux + ".";
			j = 1;
		}
		else
			j = j + 1;
		
		aux = aux + valor.charAt(n);
	}
		
	valorOut = "";
	for (n = aux.length - 1; n >= 0; n-- ) 
		valorOut = valorOut + aux.charAt(n);
	
	campo.value = valorOut + restante;
}

function retiraFormatacaoConta(valorCampo){
	var valor;
	var auxVariaveis;
	var pos;
	var pos2;
	var n;
	var nomes;

	valor = "";
	auxVariaveis = valorCampo;
	
	pos2 = 0;
	pos = auxVariaveis.indexOf(".");
	n = 0;
	while (pos != -1) {
		nomeVariavel = auxVariaveis.slice(pos2,	pos);
		valor = valor + nomeVariavel;
		pos2 = pos + 1;
		pos = auxVariaveis.indexOf("." ,pos2);
		if (n == 10)
			break;
		n++;
	}
	
	nomeVariavel = auxVariaveis.slice(pos2);
	valor = valor + nomeVariavel;
	
	return(valor);	
}

function formataCampoMoeda(campo){
	var auxValor;
	var n;
	var valor;
	var valorOut;
	var aux;
	var j;
	var restante;
	var pos;
	
	valor = retiraFormatacaoCamposMoeda(campo.value);	
			
	aux = "";	
	
	pos = valor.lastIndexOf(",");
	restante = "";
	
	if (pos == -1)
		start = valor.length - 1;
	else {
		start = pos - 1;
		restante = valor.slice(pos, pos + 3);
	}
	
	if (pos == -1) {
		if (isNaN(valor))
			return;	
	}
	else {
		if (pos == valor.length - 1)
			return;
		if (isNaN(valor.slice(0, pos)))
			return;
		
		if (isNaN(valor.slice(pos + 1)))
			return;
	}
	
	j = 0;
	for (n = start; n >= 0; n-- ) {
		if (j == 3) {
			aux = aux + ".";
			j = 1;
		}
		else
			j = j + 1;
		
		aux = aux + valor.charAt(n);
	}
		
	valorOut = "";
	for (n = aux.length - 1; n >= 0; n-- ) 
		valorOut = valorOut + aux.charAt(n);
	
	campo.value = valorOut + restante;
}

function retiraFormatacaoCamposMoeda(valorCampo){
	var valor;
	var auxVariaveis;
	var pos;
	var pos2;
	var n;
	var nomes;

	valor = "";
	auxVariaveis = valorCampo;
	
	pos2 = 0;
	pos = auxVariaveis.indexOf(".");
	n = 0;
	while (pos != -1) {
		nomeVariavel = auxVariaveis.slice(pos2,	pos);
		valor = valor + nomeVariavel;
		pos2 = pos + 1;
		pos = auxVariaveis.indexOf("." ,pos2);
		if (n == 10)
			break;
		n++;
	}
		
	nomeVariavel = auxVariaveis.slice(pos2);
	valor = valor + nomeVariavel;
	
	return(valor);	
}

function validarMontanteAvaliacao(frm, nomeCampoRadio)
{
	var avaliacao;
	var elemento = document.getElementById(nomeCampoRadio); // Descobre o primeiro RadioButton - "Sim"

	if (elemento != null && elemento.checked) // Se o "Sim" está checked
	{
		if (frm.Finalidade.value == 2) // Finalidade de Construção
			avaliacao = frm.ValorConstrucao.value;
		else
			avaliacao = frm.Avaliacao.value;
			
		if ((frm.Montante.value * 1.0 / avaliacao) > 0.90)	
			return true;  // está mal vamos retornar true
	}
		
	return false; // está tudo ok
}

//Validação para o limite máximo de caracteres
function textCounter( field, maxlimit ) {
  if ( field.value.length > maxlimit ){
    field.value = field.value.substring( 0, maxlimit );
    alert('Este campo tem um limite de 200 caracteres.');
    return false;
  }
}

function ValidaProfissaoExecutive( ProfID , ArrayProf , ArrayProfExe ){             
    for (var cnt=0 ; cnt <= ArrayProf.length ; ++ cnt){
        if (  ArrayProf[cnt] == ProfID) {
            document.formSimuladores.CEXE.value= parseInt( ArrayProfExe[cnt] );                                   
            return;
        }
    }  
}
