
// Funções para o Adiantamento Individual

var limiteContas = 0;
var qtdContas = 0;
var contConta = 0;

function inserirConta() {

	if (qtdContas <= limiteContas) {

		qtdContas++;

		selectContas = document.getElementById("lista_contas");
		limiteContas = selectContas.length - 3;

		listaContas = document.getElementById("lista-contas");
		conteudoSelect = listaContas.innerHTML;

		var valores = Array();

		numero = 0;

		if (contConta > 0) {
			for (i = 0; i < contConta; i++) {
				valores[i] = Array();

				numero++;

				if (document.getElementById("contas" + numero) != null) {
					//valores[i][0] = document.getElementById("contas" + numero).value;
					listaUnidades = document.getElementById("contas" + numero);
					indiceSelecionado = listaUnidades.selectedIndex;
					valores[i][0] = indiceSelecionado;
					//alert(valores[i][0]);
				}

				if (document.getElementById("valor" + numero) != null) {
					valores[i][1] = document.getElementById("valor" + numero).value;
				}
			}
		}

		numero = contConta + 1;

		/*
		alert(conteudoSelect);

		if (conteudoSelect.indexOf("id=lista_contas") > -1) {
			alert("Existe!");
		}
		*/

		novoId = "id='contas" + numero + "'";
		conteudoSelect = conteudoSelect.replace("id=lista_contas", novoId);

		//alert(conteudoSelect);

		document.getElementById("itens").innerHTML = document.getElementById("itens").innerHTML + "\n<span id=" + contConta + ">\n\t<table cellpadding='0' cellspacing='0' border='0' align='center' width='100%'>\n\t\t<tr>\n\t\t\t<td width='130' height='35' align='center' valign='middle'>\n\t\t\t\t<input type='button' name='Remover' value='Remover' onClick=\"javascript: removerConta(" + contConta + "); somarTodosAI('valor','visor-total','total-despesa','valor_quitacao');\">\n\t\t\t</td>\n\t\t\t<td width='420' align='center' valign='middle'>\n" + conteudoSelect + "\n</td>\n\t\t\t<td width='84' align='center' valign='middle'>\n\t\t\t\t<input type='text' id='valor" + numero + "' name='valor[]' class='valores' size='7' maxlength='9' onfocus=\"javascript: manterPreenchidoAI(this, 'f'); this.onkeyup=validarQuantidadeAI;\" onblur=\"javascript: manterPreenchidoAI(this, 'b'); somarTodosAI('valor','visor-total','total-despesa','valor_quitacao');\" value=\"0,00\">\n\t\t\t</td>\n\t\t</tr>\n\t</table>\n</span>";

		document.getElementById("itens").innerHTML = document.getElementById("itens").innerHTML;

		//alert(document.getElementById("itens").innerHTML);

		if (!isIE) {
			//alert("Não é IE!");
			document.getElementById("lista_contas").id = "contas" + numero;
		}

		//alert(document.getElementById(contConta).innerHTML);

		valores[contConta] = Array();
		if (document.getElementById("contas" + numero) != null) {
			//valores[cont][0] = document.getElementById("contas" + cont).value;
			listaUnidades = document.getElementById("contas" + numero);
			indiceSelecionado = listaUnidades.selectedIndex;
			valores[contConta][0] = indiceSelecionado;
			//alert(valores[contConta][0]);
		}
		if (document.getElementById("valor" + numero) != null) {
			valores[contConta][1] = document.getElementById("valor" + numero).value;
		}

		numero = 0;

		for (i = 0; i <= contConta; i++) {

			numero++;

			if (document.getElementById("contas" + numero) != null) {
				if (typeof(valores[i][0])=="undefined") {
					valores[i][0] = "";
				}
				//alert(valores[i][0]);
				listaUnidades = document.getElementById("contas" + numero);
				listaUnidades.selectedIndex = valores[i][0];
			}
			if (document.getElementById("valor" + numero) != null) {
				if (typeof(valores[i][1])=="undefined") {
					valores[i][1] = "";
				}
				//alert(valores[i][1]);
				document.getElementById("valor" + numero).value = valores[i][1];
			}
		}

		contConta++;

	}

}

function removerConta(id) {

	var resultadoValiacaoSelect = validarSelectContasAI("", "contas" + (id + 1));

	if (resultadoValiacaoSelect) {

		qtdContas--;

		document.getElementById(id).innerHTML = "";

		var valores = Array();

		numero = 0;

		for (i = 0; i < contConta; i++) {
			valores[i] = Array();

			numero++;

			if (document.getElementById("contas" + numero) != null) {
				//valores[i][0] = document.getElementById("unidade" + numero).value;
				listaUnidades = document.getElementById("contas" + numero);
				indiceSelecionado = listaUnidades.selectedIndex;
				valores[i][0] = indiceSelecionado;
				//alert(valores[i][0]);
			}
			if (document.getElementById("valor" + numero) != null) {
				valores[i][1] = document.getElementById("valor" + numero).value;
			}
		}

		temp = "";

		for (i = 0; i <= contConta; i++) {
			if (document.getElementById(i) != null) {
				if (document.getElementById(i).innerHTML != "") {
					temp = temp + "\n<span id=" + i + ">" + document.getElementById(i).innerHTML + "</span>";
				}
			}
		}

		document.getElementById("itens").innerHTML = temp;

		numero = 0;

		for (i = 0; i <= contConta; i++) {

			numero++;

			if (document.getElementById("contas" + numero) != null) {
				if (typeof(valores[i][0])=="undefined") {
					valores[i][0] = "";
				}
				//alert(valores[i][0]);
				listaUnidades = document.getElementById("contas" + numero);
				listaUnidades.selectedIndex = valores[i][0];
			}
			if (document.getElementById("valor" + numero) != null) {
				if (typeof(valores[i][1])=="undefined") {
					valores[i][1] = "";
				}
				//alert(valores[i][1]);
				document.getElementById("valor" + numero).value = valores[i][1];
			}
		}

	}
}

var valorAntigo = "";

function validarQuantidadeAI(e) {

	//alert("Entrou!");

	teclaPressionada = -1;

	try {
		var teclaPressionada = e.which;
		//alert("Entrou Gecko!");
		//alert("teclaPressionada: " + teclaPressionada);
	} catch(er) {
	}

	try {
		var teclaPressionada = event.keyCode;
		//alert("Entrou IE!");
	} catch(er) {
	}

	processar = false;

	if ((teclaPressionada != 8) &&
		(teclaPressionada != 16) &&
		(teclaPressionada != 17) &&
		(teclaPressionada != 18) &&
		(teclaPressionada != 20) &&
		(teclaPressionada != 33) &&
		(teclaPressionada != 34) &&
		(teclaPressionada != 35) &&
		(teclaPressionada != 36) &&
		(teclaPressionada != 37) &&
		(teclaPressionada != 38) &&
		(teclaPressionada != 39) &&
		(teclaPressionada != 40) &&
		(teclaPressionada != 45) &&
		(teclaPressionada != 46)){
		processar = true;
	}

	if (processar) {

		avancarCursor = false;

		valorOriginal = this.value;

		//alert("valorOriginal: " + valorOriginal);

		tamanhoValorOriginal = valorOriginal.length;

		//alert("tamanhoValorOriginal: " + tamanhoValorOriginal);

		posicaoCaracter = -1;

		caracteresValor = valorOriginal.split("");

		novosCaracteresValor = Array();

		ind = 0;

		naoExisteVirgula = true;

		for (i = 0; i < tamanhoValorOriginal; i++) {
			if (isNaN(caracteresValor[i])) {
				if (naoExisteVirgula) {
					if (caracteresValor[i] == ",") {
						naoExisteVirgula = false;
						novosCaracteresValor[ind] = caracteresValor[i];
						ind++;
					} else {
						posicaoCaracter = ind;
					}
				}
			} else {
				novosCaracteresValor[ind] = caracteresValor[i];
				ind++;
			}
		}

		novoValor = novosCaracteresValor.join("");

		//alert("novoValor antes: " + novoValor);

		novoTamanhoValor = novoValor.length;

		posicaoVirgula = novoValor.indexOf(",");

		if (posicaoVirgula == -1) {

			if (novoTamanhoValor > 6) {

				avancarCursor = true;

				primeiraParte = novoValor.substring(0, 6);
				segundaParte = novoValor.substring(6, novoTamanhoValor);
				novoValor = primeiraParte + "," + segundaParte;
			}
		}

		//alert("novoValor depois: " + novoValor);

		novoTamanhoValor = novoValor.length;

		posicaoVirgula = novoValor.indexOf(",");

		if (posicaoVirgula == 0) {

			avancarCursor = true;

			novoValor = "0" + novoValor;
		}

		//alert("novoValor depois: " + novoValor);

		novoTamanhoValor = novoValor.length;

		posicaoVirgula = novoValor.indexOf(",");

		if (posicaoVirgula > 0) {

			primeiraParte = novoValor.substring(0, posicaoVirgula);

			//alert("primeiraParte: " + primeiraParte);

			segundaParte = novoValor.substring(posicaoVirgula + 1, novoTamanhoValor);

			//alert("segundaParte: " + segundaParte);

			caracteresSobra = "";

			qtdPrimeiraParte = primeiraParte.length;

			//alert("qtdPrimeiraParte: " + qtdPrimeiraParte);

			if (qtdPrimeiraParte > 6) {

				avancarCursor = true;

				caracteresSobra = primeiraParte.substring(6, qtdPrimeiraParte);
				//alert("caracteresSobra: " + caracteresSobra);
				primeiraParte = primeiraParte.substring(0, 6);
			}

			//alert("primeiraParte: " + primeiraParte);

			segundaParte = caracteresSobra + segundaParte;

			//alert("segundaParte: " + segundaParte);

			qtdSegundaParte = segundaParte.length;

			//alert("qtdSegundaParte: " + qtdSegundaParte);

			if (qtdSegundaParte > 2) {

				avancarCursor = true;

				segundaParte = segundaParte.substring(0, 2);
			}

			novoValor = primeiraParte + "," + segundaParte;

			//alert("novoValor: " + novoValor);

		}

		//alert("novoValor final: " + novoValor);

		this.value = novoValor;


		var trSelection;

		if (isIE) {
			trSelection = this.createTextRange();
		} else {
			trSelection = document.selection.createRange();
		}

		if (posicaoCaracter == -1) {
			posicaoCaracter = getSelectionStart(this);
		}

		if (avancarCursor) {
			posicaoCaracter++;
		}

		trSelection.collapse(true);
		trSelection.moveStart("character", posicaoCaracter);
		trSelection.select();

		valorAntigo = novoValor;
	}
}

function manterPreenchidoAI(campo, origem) {

	if (origem == "f") {

		valorOriginal = campo.value;

		valorOriginal = valorOriginal.replace(".", "");

		valorOriginal = valorOriginal.replace(",", ".");

		valorOriginal = parseFloat(valorOriginal);

		if (valorOriginal == 0) {

			campo.value = "";

		}

	}

	if (origem == "b") {

		valorOriginal = campo.value;

		novoTamanhoValor = valorOriginal.length;

		posicaoVirgula = valorOriginal.indexOf(",");

		if ((valorOriginal == "") || (posicaoVirgula == novoTamanhoValor - 1)) {

			campo.value = "0,00";

		}
	}

}

function somarTodosAI(prefixo, visor, destino, campo_destino) {

	total = 0.00;

	for (var i = 0; i <= contConta; i++) {
		if (document.getElementById(prefixo + i) != null) {
			var campo_valor = document.getElementById(prefixo + i);
			if (campo_valor.id.indexOf(prefixo + i) > -1) {
				valor = campo_valor.value;
				valor = valor.replace(".", "");
				valor = valor.replace(",", ".");
				//alert(valor);
				valor = parseFloat(valor);
				//alert(valor);
				total = total + valor;
			}
		}
	}

	total = total.toString();
	total = total.replace(".", ",");

	//alert(total);

	posicaoVirgula = total.indexOf(",");

	if (posicaoVirgula == -1) {

		total = total + ",00";
	}

	//alert(total);

	posicaoVirgula = total.indexOf(",");

	//alert(posicaoVirgula);

	primeiraParte = total.substring(0, posicaoVirgula);

	//alert(primeiraParte);

	segundaParte = total.substring(posicaoVirgula + 1, total.length);
	segundaParte = segundaParte.substring(0, 2);

	//alert(segundaParte);

	total = primeiraParte + "," + segundaParte;

	if (total == "0") {
		total = "0,00";
	}

	document.getElementById(visor).innerHTML = total;
	document.getElementById(destino).value = total;
	document.getElementById(campo_destino).value = total;
	//alert(document.getElementById(destino).value);
}

var selecionadosContas = Array();

var indiceSelecionadosContas = 0;

function validarSelectContasAI(selectAtual, idSelectZerar) {

	var idSelectAtual;
	var indiceSelecionadoSelectAtual;

	if (idSelectZerar == "") {
		idSelectAtual = selectAtual.id;
		indiceSelecionadoSelectAtual = selectAtual.selectedIndex;
		//alert('idSelectAtual: ' + idSelectAtual);
		//alert('indiceSelecionadoSelectAtual: ' + indiceSelecionadoSelectAtual);
	} else {
		//alert("idSelectZerar: " + idSelectZerar);
		idSelectAtual = idSelectZerar;
		indiceSelecionadoSelectAtual = 0;
	}

	//if (selecionadosContas.length > 0)
		//for (i = 0; i < selecionadosContas.length; i++) {
			//alert(selecionadosContas[i][0]);
			//alert(selecionadosContas[i][1]);
		//}

	if (indiceSelecionadoSelectAtual > 0) {

		permitir_selecionar = true;
		mudarIndiceSelect = true;

		//alert('selecionadosContas.length: ' + selecionadosContas.length);

		if (selecionadosContas.length > 0) {

			for (i = 0; i < selecionadosContas.length; i++) {
				//alert('selecionadosContas[' + i + '][0]: ' + selecionadosContas[i][0] + ' != idSelectAtual: ' + idSelectAtual);
				if (selecionadosContas[i][0] != idSelectAtual) {
					//alert('selecionadosContas[' + i + '][1]: ' + selecionadosContas[i][1] + ' == indiceSelecionadoSelectAtual: ' + indiceSelecionadoSelectAtual);
					if (selecionadosContas[i][1] == indiceSelecionadoSelectAtual) {
						permitir_selecionar = false;
						i = selecionadosContas.length + 1;
					}
				}
			}

		} else {
			selecionadosContas[indiceSelecionadosContas] = Array();
			selecionadosContas[indiceSelecionadosContas][0] = idSelectAtual;
			selecionadosContas[indiceSelecionadosContas][1] = indiceSelecionadoSelectAtual;
			//alert('indiceSelecionadosContas: ' + indiceSelecionadosContas);
			//alert('selecionadosContas[' + indiceSelecionadosContas + '][0]: ' + selecionadosContas[indiceSelecionadosContas][0]);
			//alert('selecionadosContas[' + indiceSelecionadosContas + '][1]: ' + selecionadosContas[indiceSelecionadosContas][1]);
			indiceSelecionadosContas++;
			permitir_selecionar = false;
			mudarIndiceSelect = false;
		}

		if (permitir_selecionar) {

			novoSelecionadoContas = true;

			for (i = 0; i < selecionadosContas.length; i++) {
				//alert('selecionadosContas[' + i + '][0]: ' + selecionadosContas[i][0] + ' == idSelectAtual: ' + idSelectAtual);
				if (selecionadosContas[i][0] == idSelectAtual) {
					//alert('selecionadosContas[' + i + '][1]: ' + selecionadosContas[i][1] + ' != indiceSelecionadoSelectAtual: ' + indiceSelecionadoSelectAtual);
					if (selecionadosContas[i][1] != indiceSelecionadoSelectAtual) {
						selecionadosContas[i][1] = indiceSelecionadoSelectAtual;
						novoSelecionadoContas = false;
						i = selecionadosContas.length + 1;
					}
				}
			}

			if (novoSelecionadoContas) {
				selecionadosContas[indiceSelecionadosContas] = Array();
				selecionadosContas[indiceSelecionadosContas][0] = idSelectAtual;
				selecionadosContas[indiceSelecionadosContas][1] = indiceSelecionadoSelectAtual;
				indiceSelecionadosContas++;
			}
		} else {

			if (mudarIndiceSelect) {

				naoExisteIndice = true;

				for (i = 0; i < selecionadosContas.length; i++) {
					//alert('selecionadosContas[' + i + '][0]: ' + selecionadosContas[i][0] + ' == idSelectAtual: ' + idSelectAtual);
					if (selecionadosContas[i][0] == idSelectAtual) {
						//alert('selecionadosContas[' + i + '][1]: ' + selecionadosContas[i][1] + ' != indiceSelecionadoSelectAtual: ' + indiceSelecionadoSelectAtual);
						if (selecionadosContas[i][1] != indiceSelecionadoSelectAtual) {
							selectAtual.selectedIndex = selecionadosContas[i][1];
							naoExisteIndice = false;
						}
						i = selecionadosContas.length + 1;
					}
				}

				if (naoExisteIndice) {
					selectAtual.selectedIndex = 0;
				}

				alert("Esta Conta já foi selecionada, você não pode selecioná-la novamente!");
				return false;
			}
		}

		return true;
	} else {

		for (i = 0; i < selecionadosContas.length; i++) {
			//alert(selecionadosContas[i][0] + " == " + idSelectAtual);
			//alert(selecionadosContas[i][1]);
			if (selecionadosContas[i][0] == idSelectAtual) {
				selecionadosContas[i][1] = 0;
				i = selecionadosContas.length + 1;
			}
		}
		return true;
	}

}

function validarAI(nameForm) {

	if (document.getElementById('und_solicitante').selectedIndex == 0) {
		alert("Por favor selecione a Unidade!");
		return false;
	}

	if (document.getElementById('solicitante').value == "") {
		alert("Por favor selecione o Solicitante!");
		return false;
	}

	if (document.getElementById('fonte').selectedIndex == 0) {
		alert("Por favor selecione a Fonte de Recursos!");
		return false;
	}

	if (document.getElementById('convenio').selectedIndex == 0) {
		alert("Por favor selecione o Convênio!");
		return false;
	}

	if (document.getElementById('objetivo').value == "") {
		alert("Por favor digite o Objetivo!");
		return false;
	}

	if (document.getElementById('acao').selectedIndex == 0) {
		alert("Por favor selecione a Ação!");
		return false;
	}

	if (document.getElementById('banco').value == "") {
		alert("Por favor digite o nome do Banco!");
		return false;
	}

	if (document.getElementById('agencia').value == "") {
		alert("Por favor digite o número da Agência!");
		return false;
	}

	if (document.getElementById('cc').value == "") {
		alert("Por favor digite o número da Conta Corrente!");
		return false;
	}

	valor_quitacao = document.getElementById('valor_quitacao').value;
	valor_quitacao = valor_quitacao.replace(".", "");
	valor_quitacao = valor_quitacao.replace(",", ".");
	valor_quitacao = parseFloat(valor_quitacao);

	if (valor_quitacao <= 0) {
		alert("Por favor digite o Valor da Quitação!");
		return false;
	}

	if (document.getElementById('data_recebimento').value == "") {
		alert("Por favor selecione a Data de Recebimento!");
		return false;
	}

	if (document.getElementById('local').value == "") {
		alert("Por favor digite o Local!");
		return false;
	}

	mensagem_aviso = "";

	nao_existe_contas = true;
	existem_contas_sem_descricao = false;

	for (i = 0; i <= contConta; i++) {
		if (document.getElementById("valor" + i) != null) {
			//alert("Entrou 0!")
			if (document.getElementById("valor" + i).value != "0,00") {
				//alert("Entrou 1!")
				nao_existe_contas = false;
				if (document.getElementById("contas" + i).selectedIndex == 0) {
					//alert("Entrou 2!")
					existem_contas_sem_descricao = true;
				}
			}
		}
	}

	if (existem_contas_sem_descricao) {
		alert("Existem contas cuja descrição ainda não foi selecionada!");
		return false;
	}

	if (nao_existe_contas) {
		alert("Você não definiu nenhuma conta!");
		return false;
	}

	resposta = confirm("Você tem certeza que deseja submeter esta solicitação?");

	if (resposta) {
		return true;
	} else {
		return false;
	}

}

function validarAvaliarAI() {

	var arrayElements = document.getElementsByTagName('input');

	existe_inputs_text = false;

	for (var i = 0; i < arrayElements.length; i++) {
		if (arrayElements[i].type == 'text') {
			if (arrayElements[i].name.indexOf("nota") > -1) {
				existe_inputs_text = true;
			}
		}
	}

	if (existe_inputs_text) {

		if (document.getElementById('nota_empenho').value == "") {
			alert("O campo para a Nota de Empenho está vazio!");
			return false;
		}

		if (document.getElementById('nota_lancamento').value == "") {
			alert("O campo para a Nota de Lançamento está vazio!");
			return false;
		}

		if (document.getElementById('nota_despesa').value == "") {
			alert("O campo para a Nota de Despesa está vazio!");
			return false;
		}

	}

	resposta = confirm("Você tem certeza que deseja submeter esta avaliação?");

	if (resposta) {
		window.document.formulario_avaliar_adiantamento.submit();
	} else {
		return false;
	}

}
