//Funções para as Solicitações de Compras e Serviços...
var contNovoInd = 1;
var cont        = 0;

function calculaTotais(e){

	var valor = validarValor(document.getElementById("valorprevisto"+cont), document.getElementById("valorprevisto"+cont).value, 2);
	valor     = remove(valor, ".", "");
	valor     = remove(valor, ",", ".");
	
	var qtd   = validarValor(document.getElementById("qtd-pedida"+cont), document.getElementById("qtd-pedida"+cont).value, 3);
	qtd       = remove(qtd, ".", "");
	qtd       = remove(qtd, ",", ".");

	var tot   = 0;
	tot       = (valor * qtd);
	tot       = tot.toFixed(2);	

	document.getElementById("vrtotal"+cont).value = tot;	

	//guambi...
	var tot_guambi = 0;
	for (i = 0; i <=cont; i++) {
		tot_guambi = parseFloat(document.getElementById("vrtotal"+i).value) + parseFloat(tot_guambi);
	}
	document.getElementById("visor-valortotal").innerHTML 	   = parseFloat(tot_guambi).toFixed(2);	
	document.getElementById("valortotal-fonte").value 		   = document.getElementById("total_fonte").value - parseFloat(tot_guambi);
	var tot_fone 											   = parseFloat(document.getElementById("total_fonte").value) - parseFloat(tot_guambi);
	document.getElementById("visor-valortotalfonte").innerHTML = tot_fone.toFixed(2);
}

function inserirItem(){
	conteudoSelect = document.getElementById("und-medidas").innerHTML;

	contNovoInd++;

	sContNovoInd = contNovoInd;

	if (contNovoInd < 10) {
		sContNovoInd = "&nbsp;&nbsp;" + contNovoInd;
	}

	var valores = Array();

	numero = 0;

	if (cont > 0) {
		for (i = 0; i < cont; i++) {
			valores[i] = Array();

			numero++;

			if (document.getElementById("unidade" + numero) != null) {
				//valores[i][0] = document.getElementById("unidade" + numero).value;
				listaUnidades     = document.getElementById("unidade" + numero);
				indiceSelecionado = listaUnidades.selectedIndex;
				valores[i][0]     = indiceSelecionado;
			}

			if (document.getElementById("descricao" + numero) != null) {
				valores[i][1] = document.getElementById("descricao" + numero).value;
			}
			
			if (document.getElementById("valorprevisto" + numero) != null) {
				valores[i][2] = document.getElementById("valorprevisto" + numero).value;
			}			
			
			if (document.getElementById("qtd-pedida" + numero) != null) {
				valores[i][3] = document.getElementById("qtd-pedida" + numero).value;
			}			
		}
	}

	numero         = cont + 1;
	novoId         = "id='unidade" + numero + "'";
	conteudoSelect = conteudoSelect.replace("id=unidade", novoId);

	document.getElementById("itens").innerHTML = document.getElementById("itens").innerHTML + "<span id=" + cont + "><table border='0' width='99%'><tr><td width='98px' align='left' height='28'><input type='button' name='remover' value='Remover' onClick=\"javascript: removerItem("+cont+", document.getElementById('valorprevisto"+numero+"').value, document.getElementById('qtd-pedida"+numero+"').value); somarTodos('qtd-pedida','visor-total','total-qtd',3);\"></td><td width='35px' align=center><span id=iditem" + cont + ">" + sContNovoInd + "</span></td><td width='273px' align='center'><textarea id='descricao" + numero + "' name='descricao[]' cols='25' rows='3' onblur=\"javascript: this.value = this.value.toUpperCase(); validarDescricao(this);\"></textarea></td><td align='center'><input type='text' id='valorprevisto" + numero + "' name='valorprevisto[]' class='valores' size='20' onfocus=\"javascript: manterPreenchido(this, 'f', '0,00');\" onblur=\"javascript: this.value = validarValor('valorprevisto" + numero + "', this.value, 2); manterPreenchido(this, 'b', '0,00'); somarTodos('valorprevisto','visor-valortotal','valortotal-qtd',2); calculaTotais(event); \" value=\"0,00\"></td><td align=center><input type='text' id='qtd-pedida" + numero + "' name='qtd-pedida[]' class='valores' size='8' maxlength='10' onfocus=\"javascript: manterPreenchido(this, 'f', '0,000');\" onblur=\"javascript: this.value = validarValor('qtd-pedida" + numero + "', this.value, 3); manterPreenchido(this, 'b', '0,000'); somarTodos('qtd-pedida','visor-total','total-qtd',3); calculaTotais(event); \" value=\"0,000\"></td><td align=center>"+conteudoSelect + "<input type='hidden' id='vrtotal"+numero+"' name='vrtotal[]' size='10'></td></tr><table></span>";

	if (!isIE){
		document.getElementById("unidade").id = "unidade" + numero;
	}

	valores[cont] = Array();
	if (document.getElementById("unidade" + numero) != null) {
		//valores[cont][0] = document.getElementById("unidade" + cont).value;
		listaUnidades = document.getElementById("unidade" + numero);
		indiceSelecionado = listaUnidades.selectedIndex;
		valores[cont][0] = indiceSelecionado;
	}
	
	if (document.getElementById("descricao" + numero) != null) {
		valores[cont][1] = document.getElementById("descricao" + numero).value;
	}
	
	if (document.getElementById("valorprevisto" + numero) != null) {
		valores[cont][2] = document.getElementById("valorprevisto" + numero).value;
	}

	if (document.getElementById("qtd-pedida" + numero) != null) {
		valores[cont][3] = document.getElementById("qtd-pedida" + numero).value;
	}

	numero = 0;

	for (i = 0; i <= cont; i++) {

		numero++;

		if (document.getElementById("unidade" + numero) != null) {
			if (typeof(valores[i][0])=="undefined") {
				valores[i][0] = "";
			}

			listaUnidades = document.getElementById("unidade" + numero);
			listaUnidades.selectedIndex = valores[i][0];
			//document.getElementById("unidade" + numero).value = valores[i][0];
		}

		if (document.getElementById("descricao" + numero) != null) {
			if (typeof(valores[i][1])=="undefined") {
				valores[i][1] = "";
			}
			document.getElementById("descricao" + numero).value = valores[i][1];
		}
		
		if (document.getElementById("valorprevisto" + numero) != null) {
			if (typeof(valores[i][2])=="undefined") {
				valores[i][2] = "";
			}
			document.getElementById("valorprevisto" + numero).value = valores[i][2];
		}
		
		if (document.getElementById("qtd-pedida" + numero) != null) {
			if (typeof(valores[i][3])=="undefined") {
				valores[i][3] = "";
			}
			document.getElementById("qtd-pedida" + numero).value = valores[i][3];
		}		
	}
	cont++;
}

function removerItem(id, valor, qtd) {
	document.getElementById(id).innerHTML = "";
	var valores = Array();
	numero  = 0;
	var vrt = 0		
	valor   = remove(valor, ".", "");
	valor   = remove(valor, ",", ".");	
	qtd     = remove(qtd, ".", "");
	qtd     = remove(qtd, ",", ".");
	vrt     = (valor * qtd);
    
    //alert(cont);
    
	document.getElementById("valortotal-fonte").value          = document.getElementById("valortotal-fonte").value - vrt; 
	document.getElementById("visor-valortotalfonte").innerHTML = document.getElementById("valortotal-fonte").value;

	for (i = 0; i < cont; i++) {
		valores[i] = Array();
        
		numero++;
        
		if (document.getElementById("unidade" + numero) != null) {
			listaUnidades     = document.getElementById("unidade" + numero);
			indiceSelecionado = listaUnidades.selectedIndex;
			valores[i][0]     = indiceSelecionado;			
		}
		if (document.getElementById("descricao" + numero) != null) {
			valores[i][1] = document.getElementById("descricao" + numero).value;
		}

		if (document.getElementById("valorprevisto" + numero) != null) {
			valores[i][2] = document.getElementById("valorprevisto" + numero).value;
		}

		if (document.getElementById("qtd-pedida" + numero) != null) {
			valores[i][3] = document.getElementById("qtd-pedida" + numero).value;
            
		}

		if (document.getElementById("vrtotal" + numero) != null) {
			valores[i][4] = document.getElementById("vrtotal" + numero).value;
		}
	}

	temp = "";

	for (i = 0; i <= cont; i++) {
		if (document.getElementById(i) != null) {
			if (document.getElementById(i).innerHTML != "") {
				temp = temp + "<span id=" + i + ">" + document.getElementById(i).innerHTML + "</span>";
			}
		}
	}

	document.getElementById("itens").innerHTML = temp;

	numero = 0;

	for (i = 0; i <= cont; i++){
		numero++;
        
		if (document.getElementById("unidade" + numero) != null) {
			if (typeof(valores[i][0])=="undefined") {
				valores[i][0] = "";
			}
			listaUnidades = document.getElementById("unidade" + numero);
			listaUnidades.selectedIndex = valores[i][0];
			//document.getElementById("unidade" + numero).value = valores[i][0];
		}
		
		if (document.getElementById("descricao" + numero) != null) {
			if (typeof(valores[i][1])=="undefined") {
				valores[i][1] = "";
			}
			document.getElementById("descricao" + numero).value = valores[i][1];
		}
		
		if (document.getElementById("valorprevisto" + numero) != null) {
			if (typeof(valores[i][2])=="undefined") {
				valores[i][2] = "";
			}
			document.getElementById("valorprevisto" + numero).value = valores[i][2];
            //alert(valores[i][2]);
		}
		
		if (document.getElementById("qtd-pedida" + numero) != null) {
            //alert(document.getElementById("qtd-pedida" + numero).value);
			if (typeof(valores[i][3])=="undefined") {
				valores[i][3] = "";
			}
			document.getElementById("qtd-pedida" + numero).value = valores[i][3];
		}
	}

	contNovoInd--;	
    //alert(contNovoInd + " " + "teste");
	//substraindo os totais...		
	/**/

	contItem = 2;
	for (i = 0; i <= cont; i++) {

		sTempContItem = contItem;
		sContItem 	  = sTempContItem;

		if (contItem < 10) {
			sContItem = "&nbsp;&nbsp;" + sTempContItem;
		}

		if (document.getElementById("iditem" + i) != null) {
			if (document.getElementById("iditem" + i).innerHTML != "") {
				document.getElementById("iditem" + i).innerHTML = sContItem;
				contItem++;
			}
		}
	}
}

function validarDescricao(campo) {
	if (campo.value.length > 480) {
		campo.value = campo.value.substring(0, 480);
		alert("São permitidos apenas 480 caracteres!");
	}
}

function validarObsAplic(campo) {

	//alert("Funcionou!");

	//alert(campo.value.length);

	if (campo.value.length > 480) {

		campo.value = campo.value.substring(0, 480);

		alert("São permitidos apenas 480 caracteres!");

	}

}

function validarSolicitar(nameform) {

	if (document.getElementById("und-solicitante") != null)
		if (document.getElementById("und-solicitante").selectedIndex == 0) {
			alert("Por favor, selecione a Unidade!");
			return false;
		}

	if (document.getElementById("solicitante") != null)
		if (document.getElementById("solicitante").value == "") {
			alert("Por favor, selecione o Solicitante!");
			return false;
		}
		
	if (document.getElementById("acao") != null)
		if (document.getElementById("acao").value == "") {
			alert("Por favor, selecione a Ação!");
			return false;
		}
		



	/*
	if (document.getElementById("fonte") != null)
		if (document.getElementById("fonte").selectedIndex == 0) {
			alert("Por favor, selecione a Fonte de Recursos!");
			return false;
		}

	if (document.getElementById("acao") != null)
		if (document.getElementById("acao").selectedIndex == 0) {
			alert("Por favor, selecione a Ação!");
			return false;
		}

	if (document.getElementById("meta") != null)
		if (document.getElementById("meta").value == "") {
			alert("Por favor, digite a Meta!");
			return false;
		}
	*/

	mensagem_aviso = "";

	permitir_enviar = true;

	nao_existe_itens = true;
	existem_itens_sem_und = false;
	existem_itens_sem_descricao = false;

	for (i = 0; i <= cont; i++) {
		if (document.getElementById("qtd-pedida" + i) != null) {
			//alert("Entrou 0!")
			if (document.getElementById("qtd-pedida" + i).value != "0,000" || document.getElementById("qtd-pedida" + i).value != "0") {
				//alert("Entrou 1!")
				nao_existe_itens = false;
				if (document.getElementById("unidade" + i).selectedIndex == 0) {
					//alert("Entrou 2!")
					existem_itens_sem_und = true;
				}
				if (document.getElementById("descricao" + i).value == "") {
					//alert("Entrou 3!")
					existem_itens_sem_descricao = true;
				}

				if (document.getElementById("valorprevisto" + i).value == ""){
					//alert("Entrou 3!")
					existem_itens_sem_descricao = true;
				}
			}
		}
	}

	if (existem_itens_sem_descricao) {
		permitir_enviar = false;
		mensagem_aviso = "Existem itens que ainda não tem descrição!";
	}

	if (existem_itens_sem_und) {
		permitir_enviar = false;
		mensagem_aviso = "Existem itens que ainda não tem a unidade de medida selecionada!";
	}

	if (nao_existe_itens) {
		permitir_enviar = false;
		mensagem_aviso = "Você não definiu nenhuma quantidade de itens!";
	}

	if (!permitir_enviar){
		alert(mensagem_aviso);
		return false;
	}

	if (document.getElementById("local-entrega") != null)
		if (document.getElementById("local-entrega").value == "") {
			alert("Por favor, digite o local da entrega!");
			return false;
		}

	if (document.getElementById("prazo-entrega") != null)
		if (document.getElementById("prazo-entrega").value == "") {
			alert("Por favor, digite o prazo da entrega!");
			return false;
		}

	if (document.getElementById("forma-pgto") != null)
		if (document.getElementById("prazo-entrega").value == "") {
			alert("Por favor, digite o prazo da entrega!");
			return false;
		}

	if (document.getElementById("garantia") != null)
		if (document.getElementById("garantia").value == "") {
			alert("Por favor, digite o prazo de garantia!");
			return false;
		}


	resposta = confirm("Você tem certeza que deseja submeter esta solicitação?");

	if (resposta) {
		window.document.solicitacao_formulario.submit();
		limparFormulario([["visor-total", "0,000"]]);
		window.document.solicitacao_formulario.reset();
	} else {
		return false;
	}

}

var permitir_validar_avaliar = true;

function validarAvaliar() {

	//alert("Entrou!");

	if (permitir_validar_avaliar) {

		//alert("Entrou em validar!");

		mensagem_aviso = "";

		permitir_enviar = true;

		nao_existe_qtd_autorizada = true;

		//alert(cont);

		if (document.getElementById("fonte") != null)
			if (document.getElementById("fonte").selectedIndex == 0) {
				alert("Por favor, selecione a Fonte de Recursos!");
				return false;
			}

		if (document.getElementById("acao") != null)
			if (document.getElementById("acao").selectedIndex == 0) {
				alert("Por favor, selecione a Ação!");
				return false;
			}

		for (i = 1; i <= cont; i++) {
			if (document.getElementById("qtd-autorizada-" + i) != null) {
				if (document.getElementById("qtd-autorizada-" + i).value != "0,000") {
					nao_existe_qtd_autorizada = false;
				}
			}
		}

		if (nao_existe_qtd_autorizada) {
			permitir_enviar = false;
			mensagem_aviso = "Você não autorizou nenhuma quantidade de itens!";
		}

		if (!permitir_enviar){
			alert(mensagem_aviso);
			return false;
		}

	}

	resposta = confirm("Você tem certeza que deseja submeter esta avaliação?");

	if (resposta) {
		window.document.formulario_avaliar_solicitacao.submit();
	} else {
		return false;
	}

}

