function somatorioDistribuicao()
{
    var f = document.formInteresse;
    var elementoP = document.getElementById("divulga02");
    var elementoF = elementoP.getElementsByTagName('DIV');
    var elementosFQ = elementoF.length;

    for (var j = 0 ; j < elementosFQ ; j++){
        
    	var total = 0;
        
        elementoPF = document.getElementById("div_distribuicao_" + j);
        elementoFF = elementoPF.getElementsByTagName('INPUT');
        
        var elementosFQF = elementoFF.length;
        
        for (var i = 0 ; i < elementosFQF ; i++){
        
        	if (((elementoFF[i]).name == 'somatorioDistribuicao_'+ j +'_[]') && ((elementoFF[i]).name != null)){
                
        		if(elementoFF[i].value != ''){
                
        			valor = elementoFF[i].value.replace(/\./g, "");
                    valor = valor.replace(/,/g, ".");
                    total = parseFloat(total) + parseFloat(valor); 
                }
            }
        }
        total = Arredonda(total,2);
        teste = document.getElementById('total_' + j);
        teste.value = total;
    }
}

//##################PARTE#NOVA#CRIACAO#DE#DIVS######################
/*preproducao*/
/**
* funÃ§Ã£o para a criaÃ§Ã£o de divs dinamicas.
*/
function createDivPreProd()
{
    var valor = document.formInteresse.incrementaPreProd.value;
    var campoForm = document.formInteresse.incrementaPreProd;
    var divTag = document.createElement('div');
    var master = document.getElementById("form_preprod");

    valor++;
    divTag.id = 'div_preprod_' + valor;
    divTag.setAttribute('name', 'div_preprod_' + valor);
    divTag.innerHTML = '<table cellspacing="0" cellpadding="0" border="0" id="preproducao' + valor +'"><tbody><tr><td class="item"><input type="text" id="fase" name="fase[]" value="1.' + parseFloat(parseFloat(valor) + parseFloat(1)) +'" class="numeral" disabled="disabled"/></td><td class="colunaAtividades"><input type="text" value="" size="15" title="DescriÃ§Ã£o das atividades" id="descricaopreprod_' + valor +'" class="campoFormPlanilha" name="descricao[]"></td><td bgcolor="#fbffea" class="colunaNome"><input type="text" value="" size="12" title="Nomes" id="nomepreprod_' + valor +'" class="campoFormPlanilha" name="nome[]"></td><td class="colunaCPF"><input type="text" value="" maxlength="14" size="14" title="CPF ou CNPJ" id="cpfcnpjpreprod_' + valor +'" class="campoFormPlanilha" onkeypress="mascara(this,soNumeros)" name="cpfcnpj[]"></td><td bgcolor="#fbffea" class="colunaQuantidade"><input type="text" value="" size="7" title="Quantidade" id="qtdepreprod_' + valor +'" class="campoFormPlanilha" onkeyup="somatorio(\'0\');" onkeypress="mascara(this,soNumeros)" name="qtde[]"></td><td class="colunaUnidade"><input type="text" value="" size="7" title="Unidade" id="unidadepreprod_' + valor +'" class="campoFormPlanilha" name="unidade[]"></td><td bgcolor="#fbffea" class="colunaQuantidade"><input type="text" value="" size="6" title="Quantidade" maxlength="60" id="qtde_unidpreprod_' + valor +'" class="campoFormPlanilha" onkeyup="somatorio(\'0\');" onkeypress="mascara(this,soNumeros)" name="qtde_unid[]"></td><td class="colunaValor"><input type="text" value="" size="9" title="Valor unitï¿½rio" id="vlr_unitariopreprod_' + valor +'" class="campoFormPlanilha" onkeyup="somatorio(\'0\');" onkeypress="reais(this,event);" onkeydown="backspace(this,event);" name="vlr_unitario[]"></td><td bgcolor="#fbffea" class="colunaValor"><input type="text" readonly="readonly" value="" size="9" title="Valor total" id="vlr_totalpreprod_' + valor +'" class="campoFormPlanilha" name="vlr_total[]"></td><td><select title="Fonte de Financiamento" id="fte_financpreprod_' + valor +'" class="selectFormPlanilha" onchange="somatorio(\'0\');" name="fte_financ[]"><option value="1">Proponente</option><option value="2">Comercialização</option><option value="3">Doações</option><option value="4">Convênios</option><option value="5">Prefeituras</option><option value="6">MinC</option><option value="7">LIC-RS</option></select></td></tr></tbody></table>';
    master.appendChild(divTag);
    campoForm.value = valor;
}
/**
 * funÃ§Ã£o para remover as div dinamicas.
 */
function removeDivPreProd()
{
    var id_rem;
    var campoForm_rem;

    campoForm_rem = document.formInteresse.incrementaPreProd;
    id_rem = document.formInteresse.incrementaPreProd.value;

    if (id_rem > 0) {
        var pai = document.getElementById("form_preprod");
        var filho = document.getElementById("div_preprod_"+id_rem);
        var removido = pai.removeChild(filho);

        id_rem--;
        campoForm_rem.value = id_rem;
    }
	
	somatorio('0');
	
}

/*#########################################################################################*/
/*producao*/
function createDivProd()
{
	var valor = document.formInteresse.incrementaProd.value;
	var campoForm = document.formInteresse.incrementaProd;
	var divTag = document.createElement('div');
	var master = document.getElementById("form_prod");

	valor++;
	divTag.id = 'div_prod_' + valor;
	divTag.setAttribute('name', 'div_prod_' + valor);
	divTag.innerHTML = '<table cellspacing="0" cellpadding="0" border="0" id="producao' + valor +'"><tbody><tr><td class="item"><input type="text" id="fase" name="fase[]" value="2.' + parseFloat(parseFloat(valor) + parseFloat(1)) +'" class="numeral" disabled="disabled"/></td><td class="colunaAtividades"><input type="text" value="" size="15" title="DescriÃ§Ã£o das atividades" id="descricaoproducao_' + valor +'" class="campoFormPlanilha" name="descricao[]"></td><td bgcolor="#fbffea" class="colunaNome"><input type="text" value="" size="12" title="Nomes" id="nomeproducao_' + valor +'" class="campoFormPlanilha" name="nome[]"></td><td class="colunaCPF"><input type="text" value="" maxlength="14" size="14" title="CPF ou CNPJ" id="cpfcnpjproducao_' + valor +'" class="campoFormPlanilha" onkeypress="mascara(this,soNumeros)" name="cpfcnpj[]"></td><td bgcolor="#fbffea" class="colunaQuantidade"><input type="text" value="" size="7" title="Quantidade" id="qtdeproducao_' + valor +'" class="campoFormPlanilha" onkeyup="somatorio(\'1\');" onkeypress="mascara(this,soNumeros)" name="qtde[]"></td><td class="colunaUnidade"><input type="text" value="" size="7" title="Unidade" id="unidadeproducao_' + valor +'" class="campoFormPlanilha" name="unidade[]"></td><td bgcolor="#fbffea" class="colunaQuantidade"><input type="text" value="" size="6" title="Quantidade" maxlength="60" id="qtde_unidproducao_' + valor +'" class="campoFormPlanilha" onkeyup="somatorio(\'1\');" onkeypress="mascara(this,soNumeros)" name="qtde_unid[]"></td><td class="colunaValor"><input type="text" value="" size="9" title="Valor unitï¿½rio" id="vlr_unitarioproducao_' + valor +'" class="campoFormPlanilha" onkeyup="somatorio(\'1\');" onkeypress="reais(this,event);" onkeydown="backspace(this,event);" name="vlr_unitario[]"></td><td bgcolor="#fbffea" class="colunaValor"><input type="text" readonly="readonly" value="" size="9" title="Valor total" id="vlr_totalproducao_' + valor +'" class="campoFormPlanilha" name="vlr_total[]"></td><td><select title="Fonte de Financiamento" id="fte_financproducao_' + valor +'" class="selectFormPlanilha" onchange="somatorio(\'1\');" name="fte_financ[]"><option value="1">Proponente</option><option value="2">Comercialização</option><option value="3">Doações</option><option value="4">Convênios</option><option value="5">Prefeituras</option><option value="6">MinC</option><option value="7">LIC-RS</option></select></td></tr></tbody></table>';
	master.appendChild(divTag);
	campoForm.value = valor;
}

function removeDivProd()
{
	var id_rem;
	var campoForm_rem;
	
	campoForm_rem = document.formInteresse.incrementaProd;
	id_rem = document.formInteresse.incrementaProd.value;
	
	if (id_rem > 0) {
		var pai = document.getElementById("form_prod");
		var filho = document.getElementById("div_prod_"+id_rem);
		var removido = pai.removeChild(filho);
		
		id_rem--;
		campoForm_rem.value = id_rem;
	}
	
	somatorio('1');
}

/*############################################################################################*/
/*3 - DIVULGAÃ‡ÃƒO*/
function createDivDivu()
{
	var valor = document.formInteresse.incrementaDivulgacao.value;
	var campoForm = document.formInteresse.incrementaDivulgacao;
	var divTag = document.createElement('div');
	var master = document.getElementById("form_divulgacao");

	valor++;
	divTag.id = 'div_divulgacao_' + valor;
	divTag.setAttribute('name', 'div_divulgacao_' + valor);
	divTag.innerHTML = '<table cellspacing="0" cellpadding="0" border="0" id="divulgacao' + valor +'"><tbody><tr><td class="item"><input type="text" id="fase" name="fase[]" value="3.' + parseFloat(parseFloat(valor) + parseFloat(1)) +'" class="numeral" disabled="disabled"/></td><td class="colunaAtividades"><input type="text" value="" size="15" title="DescriÃ§Ã£o das atividades" id="descricaodivulgacao_' + valor +'" class="campoFormPlanilha" name="descricao[]"></td><td bgcolor="#fbffea" class="colunaNome"><input type="text" value="" size="12" title="Nomes" id="nomedivulgacao_' + valor +'" class="campoFormPlanilha" name="nome[]"></td><td class="colunaCPF"><input type="text" value="" maxlength="14" size="14" title="CPF ou CNPJ" id="cpfcnpjdivulgacao_' + valor +'" class="campoFormPlanilha" onkeypress="mascara(this,soNumeros)" name="cpfcnpj[]"></td><td bgcolor="#fbffea" class="colunaQuantidade"><input type="text" value="" size="7" title="Quantidade" id="qtdedivulgacao_' + valor +'" class="campoFormPlanilha" onkeyup="somatorio(\'2\');" onkeypress="mascara(this,soNumeros)" name="qtde[]"></td><td class="colunaUnidade"><input type="text" value="" size="7" title="Unidade" id="unidadedivulgacao_' + valor +'" class="campoFormPlanilha" name="unidade[]"></td><td bgcolor="#fbffea" class="colunaQuantidade"><input type="text" value="" size="6" title="Quantidade" maxlength="60" id="qtde_uniddivulgacao_' + valor +'" class="campoFormPlanilha" onkeyup="somatorio(\'2\');" onkeypress="mascara(this,soNumeros)" name="qtde_unid[]"></td><td class="colunaValor"><input type="text" value="" size="9" title="Valor unitï¿½rio" id="vlr_unitariodivulgacao_' + valor +'" class="campoFormPlanilha" onkeyup="somatorio(\'2\');" onkeypress="reais(this,event);" onkeydown="backspace(this,event);" name="vlr_unitario[]"></td><td bgcolor="#fbffea" class="colunaValor"><input type="text" readonly="readonly" value="" size="9" title="Valor total" id="vlr_totaldivulgacao_' + valor +'" class="campoFormPlanilha" name="vlr_total[]"></td><td><select title="Fonte de Financiamento" id="fte_financdivulgacao_' + valor +'" class="selectFormPlanilha" onchange="somatorio(\'2\');" name="fte_financ[]"><option value="1">Proponente</option><option value="2">Comercialização</option><option value="3">Doações</option><option value="4">Convênios</option><option value="5">Prefeituras</option><option value="6">MinC</option><option value="7">LIC-RS</option></select></td></tr></tbody></table>';
	master.appendChild(divTag);
	campoForm.value = valor;
}

function removeDivDivu()
{
	var id_rem;
	var campoForm_rem;
	
	campoForm_rem = document.formInteresse.incrementaDivulgacao;
	id_rem = document.formInteresse.incrementaDivulgacao.value;
	
	if (id_rem > 0) {
		var pai = document.getElementById("form_divulgacao");
		var filho = document.getElementById("div_divulgacao_"+id_rem);
		var removido = pai.removeChild(filho);
		
		id_rem--;
		campoForm_rem.value = id_rem;
	}
	somatorio('2');
}

/*############################################################################################*/

/*custo administrativo*/
function createDivAdmin()
{
	var valor = document.formInteresse.incrementaAdministrativo.value;
	var campoForm = document.formInteresse.incrementaAdministrativo;
	var divTag = document.createElement('div');
	var master = document.getElementById("form_administrativo");

	valor++;
	divTag.id = 'div_administrativo_' + valor;
	divTag.setAttribute('name', 'div_administrativo_' + valor);
	divTag.innerHTML = '<table cellspacing="0" cellpadding="0" border="0" id="administrativo' + valor +'"><tbody><tr><td class="item"><input type="text" id="fase" name="fase[]" value="4.' + parseFloat(parseFloat(valor) + parseFloat(1)) + '" class="numeral" disabled="disabled"/></td><td class="colunaAtividades"><input type="text" value="" size="15" title="Descrição das atividades" id="descricaoadministrativo_' + valor +'" class="campoFormPlanilha" name="descricao[]"></td><td bgcolor="#fbffea" class="colunaNome"><input type="text" value="" size="12" title="Nomes" id="nomeadministrativo_' + valor +'" class="campoFormPlanilha" name="nome[]"></td><td class="colunaCPF"><input type="text" value="" maxlength="14" size="14" title="CPF ou CNPJ" id="cpfcnpjadministrativo_' + valor +'" class="campoFormPlanilha" onkeypress="mascara(this,soNumeros)" name="cpfcnpj[]"></td><td bgcolor="#fbffea" class="colunaQuantidade"><input type="text" value="" size="7" title="Quantidade" id="qtdeadministrativo_' + valor +'" class="campoFormPlanilha" onkeyup="somatorio(\'3\');" onkeypress="mascara(this,soNumeros)" name="qtde[]"></td><td class="colunaUnidade"><input type="text" value="" size="7" title="Unidade" id="unidadeadministrativo_' + valor +'" class="campoFormPlanilha" name="unidade[]"></td><td bgcolor="#fbffea" class="colunaQuantidade"><input type="text" value="" size="6" title="Quantidade" maxlength="60" id="qtde_unidadministrativo_' + valor +'" class="campoFormPlanilha" onkeyup="somatorio(\'3\');" onkeypress="mascara(this,soNumeros)" name="qtde_unid[]"></td><td class="colunaValor"><input type="text" value="" size="9" title="Valor unitï¿½rio" id="vlr_unitarioadministrativo_' + valor +'" class="campoFormPlanilha" onkeyup="somatorio(\'3\');" onkeypress="reais(this,event);" onkeydown="backspace(this,event);" name="vlr_unitario[]"></td><td bgcolor="#fbffea" class="colunaValor"><input type="text" readonly="readonly" value="" size="9" title="Valor total" id="vlr_totaladministrativo_' + valor +'" class="campoFormPlanilha" name="vlr_total[]"></td><td><select title="Fonte de Financiamento" id="fte_financadministrativo_' + valor +'" class="selectFormPlanilha" onchange="somatorio(\'3\');" name="fte_financ[]"><option value="1">Proponente</option><option value="2">Comercialização</option><option value="3">Doações</option><option value="4">Convênios</option><option value="5">Prefeituras</option><option value="6">MinC</option><option value="7">LIC-RS</option></select></td></tr></tbody></table>';
	master.appendChild(divTag);
	campoForm.value = valor;
}

function removeDivAdmin()
{
	var id_rem;
	var campoForm_rem;
	
	campoForm_rem = document.formInteresse.incrementaAdministrativo;
	id_rem = document.formInteresse.incrementaAdministrativo.value;
	
	if (id_rem > 0) {
		var pai = document.getElementById("form_administrativo");
		var filho = document.getElementById("div_administrativo_"+id_rem);
		var removido = pai.removeChild(filho);
		
		id_rem--;
		campoForm_rem.value = id_rem;
	}
	
	somatorio('3');
}

/*############################################################################################*/


/*imposto*/
function createDivImp()
{

	var valor = document.formInteresse.incrementaImposto.value;
	var campoForm = document.formInteresse.incrementaImposto;
	var divTag = document.createElement('div');
	var master = document.getElementById("form_imposto");

	valor++;
	divTag.id = 'div_imposto_' + valor;
	divTag.setAttribute('name', 'div_imposto_' + valor);
	divTag.innerHTML = '<table cellspacing="0" cellpadding="0" border="0" id="impostos' + valor +'"><tbody><tr><td class="item"><input type="text" id="fase" name="fase[]" value="5.' + parseFloat(parseFloat(valor) + parseFloat(1)) +'" class="numeral" disabled="disabled" disabled="disabled"/></td><td class="colunaAtividades"><input type="text" value="" size="15" title="DescriÃ§Ã£o das atividades" id=descricaoimposto_' + valor +' class="campoFormPlanilha" name="descricao[]"></td><td bgcolor="#fbffea" class="colunaNome"><input type="text" value="" size="12" title="Nomes" id="nomeimposto_' + valor +'" class="campoFormPlanilha" name="nome[]"></td><td class="colunaCPF"><input type="text" value="" maxlength="14" size="14" title="CPF ou CNPJ" id="cpfcnpjimposto_' + valor +'" class="campoFormPlanilha" onkeypress="mascara(this,soNumeros)" name="cpfcnpj[]"></td><td bgcolor="#fbffea" class="colunaQuantidade"><input type="text" value="" size="7" title="Quantidade" id="qtdeimposto_' + valor +'" class="campoFormPlanilha" onkeyup="somatorio(\'4\');" onkeypress="mascara(this,soNumeros)" name="qtde[]"></td><td class="colunaUnidade"><input type="text" value="" size="7" title="Unidade" id="unidadeimposto_' + valor +'" class="campoFormPlanilha" name="unidade[]"></td><td bgcolor="#fbffea" class="colunaQuantidade"><input type="text" value="" size="6" title="Quantidade" maxlength="60" id="qtde_unidimposto_' + valor +'" class="campoFormPlanilha" onkeyup="somatorio(\'4\');" onkeypress="mascara(this,soNumeros)" name="qtde_unid[]"></td><td class="colunaValor"><input type="text" value="" size="9" title="Valor unitï¿½rio" id="vlr_unitarioimposto_' + valor +'" class="campoFormPlanilha" onkeyup="somatorio(\'4\');"  onkeypress="reais(this,event);" onkeydown="backspace(this,event);" name="vlr_unitario[]"></td><td bgcolor="#fbffea" class="colunaValor"><input type="text" readonly="readonly" value="" size="9" title="Valor total" id="vlr_totalimposto_' + valor +'" class="campoFormPlanilha" name="vlr_total[]"></td><td><select title="Fonte de Financiamento" id="fte_financimposto_' + valor +'" class="selectFormPlanilha" onchange="somatorio(\'4\');" name="fte_financ[]"><option value="1">Proponente</option><option value="2">Comercialização</option><option value="3">Doações</option><option value="4">Convênios</option><option value="5">Prefeituras</option><option value="6">MinC</option><option value="7">LIC-RS</option></select></td></tr></tbody></table>';
	master.appendChild(divTag);
	campoForm.value = valor;
}

function removeDivImp()
{
	var id_rem;
	var campoForm_rem;
	
	campoForm_rem = document.formInteresse.incrementaImposto;
	id_rem = document.formInteresse.incrementaImposto.value;
	
	if (id_rem > 0) {
		var pai = document.getElementById("form_imposto");
		var filho = document.getElementById("div_imposto_"+id_rem);
		var removido = pai.removeChild(filho);
		
		id_rem--;
		campoForm_rem.value = id_rem;
	}
	somatorio('4');
}

function mascara(o,f)
{    
    v_obj=o;
    v_fun=f;
    setTimeout("execmascara()",1);
    
}

function execmascara()
{
    v_obj.value=v_fun(v_obj.value);
    
}

function protoSPI(v)
{
    v=v.replace(/\D/g,"");                 //Remove tudo o que não é dígito
    v=v.replace(/(\d{6})(\d)/,"$1-$2");    //Coloca hífen entre o quarto e o quinto dígitos
    v=v.replace(/(\d{9})(\d)/,"$1.$2");    //Coloca hífen entre o quarto e o quinto dígitos
    v=v.replace(/(\d{12})(\d)/,"$1/$2");    //Coloca hífen entre o quarto e o quinto dígitos
    v=v.replace(/(\d{16})(\d)/,"$1-$2");    //Coloca hífen entre o quarto e o quinto dígitos
    
    return v;
}

function leech(v)
{
    v=v.replace(/o/gi,"0");
    v=v.replace(/i/gi,"1");
    v=v.replace(/z/gi,"2");
    v=v.replace(/e/gi,"3");
    v=v.replace(/a/gi,"4");
    v=v.replace(/s/gi,"5");
    v=v.replace(/t/gi,"7");
    
    return v;
}

function soNumeros(v)
{
    return v.replace(/\D/g,"");
}

function telefone(v)
{
    v=v.replace(/\D/g,"");                 //Remove tudo o que não é dígito
    v=v.replace(/^(\d\d)(\d)/g,"($1) $2"); //Coloca parênteses em volta dos dois primeiros dígitos
    v=v.replace(/(\d{4})(\d)/,"$1-$2");    //Coloca hífen entre o quarto e o quinto dígitos
    
    return v;
}

function cpf(v)
{
    v=v.replace(/\D/g,"");                    //Remove tudo o que não é dígito
    v=v.replace(/(\d{3})(\d)/,"$1.$2");       //Coloca um ponto entre o terceiro e o quarto dígitos
    v=v.replace(/(\d{3})(\d)/,"$1.$2");       //Coloca um ponto entre o terceiro e o quarto dígitos
    v=v.replace(/(\d{3})(\d{1,2})$/,"$1-$2"); //Coloca um hífen entre o terceiro e o quarto dígitos
    
    return v;
}

function cep(v)
{
    v=v.replace(/D/g,"");                //Remove tudo o que não é dígito
    v=v.replace(/^(\d{5})(\d)/,"$1-$2"); //Esse é tão fácil que não merece explicações
    
    return v;
}

function cnpj(v)
{
    v=v.replace(/\D/g,"");                           //Remove tudo o que não é dígito
    v=v.replace(/^(\d{2})(\d)/,"$1.$2");             //Coloca ponto entre o segundo e o terceiro dígitos
    v=v.replace(/^(\d{2})\.(\d{3})(\d)/,"$1.$2.$3"); //Coloca ponto entre o quinto e o sexto dígitos
    v=v.replace(/\.(\d{3})(\d)/,".$1/$2");           //Coloca uma barra entre o oitavo e o nono dígitos
    v=v.replace(/(\d{4})(\d)/,"$1-$2");              //Coloca um hífen depois do bloco de quatro dígitos
    
    return v;
}

function romanos(v)
{
    v=v.toUpperCase();
    v=v.replace(/[^IVXLCDM]/g,"");

    while(v.replace(/^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/,"")!=""){

        v=v.replace(/.$/,"");
        
    }

    return v;
}

function site(v)
{
    v=v.replace(/^http:\/\/?/,"");
    dominio=v;
    caminho="";
    
    if(v.indexOf("/")>-1)
    
        dominio=v.split("/")[0];
        caminho=v.replace(/[^\/]*/,"");
    dominio=dominio.replace(/[^\w\.\+-:@]/g,"");
    caminho=caminho.replace(/[^\w\d\+-@:\?&=%\(\)\.]/g,"");
    caminho=caminho.replace(/([\?&])=/,"$1");
    
    if(caminho!="")dominio=dominio.replace(/\.+$/,"");
    
    v="http://"+dominio+caminho;
    
    return v;
}

function data(v)
{
    v=v.replace(/\D/g,"");
    v=v.replace(/(\d{2})(\d)/,"$1/$2");
    v=v.replace(/(\d{2})(\d)/,"$1/$2");
    
    return v;
}

function hora(v)
{
    v=v.replace(/\D/g,"");
    v=v.replace(/(\d{2})(\d)/,"$1:$2");
    
    return v;
}

/**
 * função para a criação de divs dinamicas.
 */
function createDiv()
{

    var valor = document.formInteresse.incrementaDistribuicao.value;
    var campoForm = document.formInteresse.incrementaDistribuicao;
    var divTag = document.createElement('div');
    var master = document.getElementById("divulga02");

    valor++;
    divTag.id = 'div_distribuicao_' + valor;
    divTag.setAttribute('name', 'div_distribuicao_' + valor);
    divTag.className = 'campoadicional';
    divTag.innerHTML = '<table align = "right" cellpadding = "0" id = "tab_programacao_' + valor + '" cellspacing = "0" class = "tabela" width = "100%"><tr><td rowspan="5" ><textarea name="pecas_distribuicao_' + valor + '" cols="70" rows="6" class="campoForm" id="pecas_distribuicao_' + valor + '" title="pe&ccedil;as de distribui&ccedil;&atilde;o"></textarea></td><td class="colunaDestino"><input type="text" maxlength="50" size="20" title="destino" id="destino_1_' + valor + '" class="campoForm" name="destino_1_' + valor + '" /></td><td class = "colunaEtapa"><input type = "text" id = "quantidade_1_' + valor + '" name = "somatorioDistribuicao_' + valor + '_[]" maxlength = "100" size = "20" class="campoForm" onblur="somatorioDistribuicao();" onfocus="somatorioDistribuicao();" /></td></tr><tr><td class="colunaDestino"><input type="text" maxlength="10" size="20" title="Destino" id="destino_2_' + valor + '" class="campoForm" name="destino_2_' + valor + '" /></td><td class = "colunaEtapa"><input type = "text" id = "quantidade_2_' + valor + '" name = "somatorioDistribuicao_' + valor + '_[]" maxlength = "100" size = "20" class="campoForm" onblur="somatorioDistribuicao();" onfocus="somatorioDistribuicao();" /></td></tr><tr><td class="colunaDestino"><input type="text" maxlength="100" size="20" title="Destino" id="destino_3_' + valor + '" class="campoForm" name="somatorioDistribuicao_3_' + valor + '" /></td><td class = "colunaEtapa"><input type="text" id = "quantidade_3_' + valor + '" name = "somatorioDistribuicao_' + valor + '_[]" maxlength = "100" size = "20" class="campoForm" onblur="somatorioDistribuicao();" onfocus="somatorioDistribuicao();" /></td></tr><tr><td class="colunaDestino"><input type="text" maxlength="100" size="20" title="Destino"  id="destino_4_' + valor + '" class="campoForm" name="destino_4_' + valor + '" /></td><td class = "colunaEtapa"><input type = "text" id = "quantidade_4_' + valor + '" name = "somatorioDistribuicao_' + valor + '_[]" maxlength = "100" size = "20" class="campoForm" onblur="somatorioDistribuicao();" onfocus="somatorioDistribuicao();" /></td></tr><tr><td class="colunaDestino"><input type="text" maxlength="100" size="20" title="Destino" id="destino_5_' + valor + '" class="campoForm" name="destino_5_' + valor + '" /></td><td class = "colunaEtapa"><input type = "text" id = "quantidade_5_' + valor + '" title="quantidade" name = "somatorioDistribuicao_' + valor + '_[]" maxlength = "100" size = "20" class="campoForm" onblur="somatorioDistribuicao();" onfocus="somatorioDistribuicao();" /></td></tr><tr class = "linhasubTotal"><td></td><td class = "colunaDestino">TOTAL</td><td class = "colunaEtapa"><input type = "text" id = "total_' + valor + '" name = "total_' + valor + '" maxlength="100" size="20" class="campoForm" readonly = "readonly"/></td></tr></table>';
    master.appendChild(divTag);
    campoForm.value = valor;
}

function removeDiv()
{
    var id_rem;
    var campoForm_rem;

    campoForm_rem = document.formInteresse.incrementaDistribuicao;
    id_rem = document.formInteresse.incrementaDistribuicao.value;

    if (id_rem > 0) {
    	
        var pai = document.getElementById("divulga02");
        var filho = document.getElementById("div_distribuicao_"+id_rem);
        var removido = pai.removeChild(filho);

        id_rem--;
        campoForm_rem.value = id_rem;
    }
}


function formatCurrency(num) {
   num = num.toString().replace(/\$|\,/g,'');
   if(isNaN(num))
     num = "0";
   sign = (num == (num = Math.abs(num)));
   num = Math.floor(num*100+0.50000000001);
   cents = num%100;
   num = Math.floor(num/100).toString();
   if(cents<10)
      cents = "0" + cents;
   for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
      num = num.substring(0,num.length-(4*i+3))+'.'+
   num.substring(num.length-(4*i+3));
   return (num + ',' + cents);
}

function currencyFormat(fld, milSep, decSep, e)
{
   var sep = 0;
   var key = '';
   var i = j = 0;
   var len = len2 = 0;
   var strCheck = '0123456789';
   var aux = aux2 = '';
   var whichCode = (window.Event) ? e.which : e.keyCode;

   if (whichCode == 13) return true;
   if (whichCode == 8) return true;
   key = String.fromCharCode(whichCode);
   if (strCheck.indexOf(key) == -1) return false;
   len = fld.value.length;
   for(i = 0; i < len; i++)
   if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
   aux = '';
   for(; i < len; i++)
   if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
   aux += key;
   len = aux.length;
   if (len == 0) fld.value = '';
   if (len == 1) fld.value = '0'+ decSep + '0' + aux;
   if (len == 2) fld.value = '0'+ decSep + aux;
   if (len > 2) {
     aux2 = '';
     for (j = 0, i = len - 3; i >= 0; i--) {
       if (j == 3) {
         aux2 += milSep;
         j = 0;
       }
       aux2 += aux.charAt(i);
       j++;
     }
     fld.value = '';
     len2 = aux2.length;
     for (i = len2 - 1; i >= 0; i--)
     fld.value += aux2.charAt(i);
     fld.value += decSep + aux.substr(len - 2, len);
   }
   return false;
}

function Arredonda( valor , casas )
{
   var novo = Math.round( valor * Math.pow( 10 , casas ) ) / Math.pow( 10 , casas );

   return( novo );
}


function envia(f)
{
    var valor = true;
    var swp = Array();
	
	var msg
	
	msg = "";
	
	if (f.tituloProjeto.value == "") 			{	msg += f.tituloProjeto.title + '\n'; 	}
	if(f.segmentocultural.options[f.segmentocultural.selectedIndex].value == 0){ 
		msg += f.segmentocultural.title + '\n'; 
	}
	if (f.periodoInicialProjeto.value == "") 	{	msg += f.periodoInicialProjeto.title + '\n'; 	}
	if (f.periodoFinalProjeto.value == "") 		{	msg += f.periodoFinalProjeto.title + '\n';	}
	if(f.localidade.options[f.localidade.selectedIndex].value == 0){
		msg += f.localidade.title + '\n';
	}
	if (f.localEventoProjeto.value == "") 	{	msg += f.localEventoProjeto.title + '\n';	}
	if (f.valorSolicitado.value == "") 		{   msg += f.valorSolicitado.title + '\n'; 	}
	if (f.valorTotal.value == "") 			{   msg += f.valorTotal.title + '\n';    		}
    if (f.carregaProjetoFAC.value == "") 	{   msg += f.carregaProjetoFAC.title + '\n';  }
	if (f.carregaPlanilha.value == "") 		{   msg += f.carregaPlanilha.title + '\n';  }

	if (f.tituloProjeto.value == "" || f.segmentocultural.options[f.segmentocultural.selectedIndex].value == 0 || f.periodoInicialProjeto.value == "" || f.periodoFinalProjeto.value == "" || f.localidade.options[f.localidade.selectedIndex].value == 0 || f.localEventoProjeto.value == "" || f.valorSolicitado.value == "" || f.valorTotal.value == "" || f.carregaProjetoFAC.value == "" || f.carregaPlanilha.value == "" ) {

		alert("Os seguintes campos obrigatórios estão em branco:\n"+msg);
		if (f.carregaPlanilha.value == "") 		{ 	f.carregaPlanilha.focus();	}
		if (f.carregaProjetoFAC.value == "") 	{ 	f.carregaProjetoFAC.focus();	}
		if (f.valorTotal.value == "") 			{   f.valorTotal.focus();			}
		if (f.valorSolicitado.value == "") 		{   f.valorSolicitado.focus();		}
		if (f.localEventoProjeto.value == "") 	{   f.localEventoProjeto.focus();	}
		if(f.localidade.options[f.localidade.selectedIndex].value == 0){	f.localidade.focus(); }
		if (f.periodoFinalProjeto.value == "") 	{	f.periodoFinalProjeto.focus();	 }
		if (f.periodoInicialProjeto.value == ""){ 	f.periodoInicialProjeto.focus();  	}
		if(f.segmentocultural.options[f.segmentocultural.selectedIndex].value == 0){ f.segmentocultural.focus(); }
		if (f.tituloProjeto.value == "") 		{	f.tituloProjeto.focus();		 }
        return false;
		
    }
	
	// Verifica as datas
	// Data de Início tem que ser >= periodo inicio e <= periodo fim 
	// Daata de Térmio tem que ser >=90 dias q a  data de inicio  e <= periodo fim
	
	dt_fac_ini = f.dataperiodoInicial.value;
	ar_data    = dt_fac_ini.split("-");
	dt_fac_ini = ar_data[2]+"/"+ar_data[1]+"/"+ar_data[0]
	dt_fac_fim = f.dataPeriodoFinal.value;
	ar_data    = dt_fac_fim.split("-");
	dt_fac_fim = ar_data[2]+"/"+ar_data[1]+"/"+ar_data[0]
	dt_periodo_ini	= f.periodoInicialProjeto.value;
	dt_periodo_fim	= f.periodoFinalProjeto.value;
	dt_periodo_90 = SomaqtdDias(dt_periodo_ini, 90);
	
	
	dt2 = validacampodata(dt_periodo_ini);
	if (dt2 == 2) {
		alert("Período de Realização Inicial inválido. Digite dd/mm/aaaa!");
		f.periodoInicialProjeto.focus();
		return false;
	} else if (dt2 == 3) {
		alert("Período de Realização Inicial Inválido!");
		f.periodoInicialProjeto.focus();
		return false;
	}
	
	dt2 = validacampodata(dt_periodo_fim);
	if (dt2 == 2) {
		alert("Período de Realização Final inválido. Digite dd/mm/aaaa!");
		f.periodoInicialProjeto.focus();
		return false;
	} else if (dt2 == 3) {
		alert("Período de Realização Final Inválido!");
		f.periodoInicialProjeto.focus();
		return false;
	}
	
	//verifica as diferenças de datas
	// Data inicial com data inicial estipulado no BD
	diff = verificadiff(dt_fac_ini, dt_periodo_ini);
	if (diff < 0) {
		alert("Período de Realização Inicial não está de acordo com o período Inicial estipulado");
		f.periodoInicialProjeto.focus();
		return false;
	}
	
	//data inicial com data final estipulado no BD 
	diff = verificadiff(dt_periodo_ini, dt_fac_fim );
	if (diff < 0) {
		alert("Período de Realização Inicial não está de acordo com o período Final estipulado");
		f.periodoInicialProjeto.focus();
		return false;
	}
	
	// data final com data final do perido estipulado no BD
	diff = verificadiff(dt_periodo_fim, dt_fac_fim);
	if (diff < 0) {
		alert("Período de Realização Final não está de acordo com o período Final estipulado");
		f.periodoFinalProjeto.focus();
		return false;
	}
	
	// data final com data inicial+90 dias
	diff = verificadiff(dt_periodo_90,dt_periodo_fim);
	if (diff < 0) {
		alert("O intervalo entre a data de início do projeto e a data final tem que ser de no mínimo de 3 meses.");
		f.periodoFinalProjeto.focus();
		return false;
	}
	
	
	var valorSolicitado = f.valorSolicitado.value;
    valorSolicitado = valorSolicitado.replace(/\./i,"");
    valorSolicitado = valorSolicitado.replace(/,/i,".");

    if (parseFloat(valorSolicitado) > parseFloat(f.valorPeriodo.value)) {
        alert('O valor solicitado não pode ser maior do que ' + f.valorPeriodo.value + '.');
        f.valorSolicitado.focus();
        return false;
    }
	
    f.submit();
}

// Diferença entre datas
function verificadiff(d1, d2){
	t1=d1;
	t2=d2;
	var one_day=1000*60*60*24; 
	
	var x=t1.split("/");     
	var y=t2.split("/");

	var date1=new Date(x[2],(x[1]-1),x[0]);

	var date2=new Date(y[2],(y[1]-1),y[0])
	var month1=x[1]-1;
	var month2=y[1]-1;
	
	return Math.ceil((date2.getTime()-date1.getTime())/(one_day)); 
		
}
// Validata data válida
function validacampodata(cmpdata) {
	erro=0;
	barras = cmpdata.split("/");
	if (barras.length == 3)
	{	dia = barras[0];
		mes = barras[1];
		ano = barras[2];
		teste = isValidDate(dia,mes-1,ano)
		if (teste == false)
		{ 	return 3; 	}
	} else {
		return 2; // Formato de data invalido. Digite dd/mm/aaaa!"
	}
	return 1; // ok
}

// INICIAL: Verificação das datas 
function isValidDate(day,month,year){
	var dteDate;
	dteDate=new Date(year,month,day);
	return ((day==dteDate.getDate()) && (month==dteDate.getMonth()) && (year==dteDate.getFullYear()));
}

// Função para somar dias
function numdias(mes,ano) {
    if((mes<8 && mes%2==1) || (mes>7 && mes%2==0)) return 31;
    if(mes!=2) return 30;
    if(ano%4==0) return 29;
    return 28;
}
// Função para somar dias
function SomaqtdDias(data, dias) {// data, dias
   data=data.split('/');
   diafuturo=parseInt(data[0])+dias;
   mes=parseInt(data[1]);
   ano=parseInt(data[2]);
   while(diafuturo>numdias(mes,ano)) {
       diafuturo-=numdias(mes,ano);
       mes++;
       if(mes>12) {
           mes=1;
           ano++;
       }
   }

   if(diafuturo<10) diafuturo='0'+diafuturo;
   if(mes<10) mes='0'+mes;

   return diafuturo+"/"+mes+"/"+ano;
}



function verificaMaior(datasA)
{

    var valor = 1;

    for(var i = 0 ; i < 4 ; i++){

        var data = datasA[i].split(/[.,\/ -]/);
        var dia = parseFloat(data['2']);

        if((dia < 10) && (dia > 0)){
            dia = '0' + dia;
        }

        var mes = parseFloat(data['1']) - parseFloat('1');

        if((mes < 10) ){
            mes = '0' + mes;
        }

        datasA[i] = strtotime((data['0'] + "-" + mes + "-" + dia));
    }

    if (datasA[2] < datasA[0]) { valor = 0; }
    if (datasA[3] > datasA[1]) { valor = 0; }

    return valor;
}


function somaFinanciamento()
{
	var quantidade = 'quantidade_';
	var valor = 'valor_';
	var totalQuant = 'tot_quant_';
	var totalValor = 'total_';
	var quantN = 0;
	var valorN = 0;
	var valorTotal = 0;
	var totalFinanc = $('incrementaComercializacao').value;

	for ( var j = 0 ; j <= totalFinanc ; j++) {

		for ( var i = 1 ; i < 6 ; i++) {

			quantN += parseFloat($(quantidade + i + '_' + j).value ? $(quantidade + i + '_' + j).value : 0);
			valorN += parseFloat(formatCalc($(valor + i + '_' + j).value ? $(valor + i + '_' + j).value : 0));
			valorTotal += parseFloat(formatCalc($(valor + i + '_' + j).value ? $(valor + i + '_' + j).value : 0)) * parseFloat($(quantidade + i + '_' + j).value ? $(quantidade + i + '_' + j).value : 0); 
		}
		$(totalQuant + j).value = quantN; 
		$(totalValor + j).value = formatCurrency(valorTotal);
		valorTotal = 0;
		quantN = 0;
		valorN = 0;
	}

}

function formatCalc(num)
{
	if(num == '') num = '0,00';
	expre1 = /\./;
	expre2 = /,/;
	
	num = num.replace(expre1, '');
	num = num.replace(expre1, '');
	num = num.replace(expre2, '.');
	
	return num;
}

function formatCurrency(num) {
    num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num))
      num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10)
       cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
       num = num.substring(0,num.length-(4*i+3))+'.'+
    num.substring(num.length-(4*i+3));
    return (num + ',' + cents);
}

function formatamoney(c) {  
    var t = this; if(c == undefined) c = 2;        
    var p, d = (t=t.split("."))[1].substr(0, c);  
    for(p = (t=t[0]).length; (p-=3) >= 1;) {  
           t = t.substr(0,p) + "." + t.substr(p);  
    }  
    return t+","+d+Array(c+1-d.length).join(0);  
}  
  
/**
 * conjunto de funções para a formatação dos campos com , 
 */
String.prototype.formatCurrency=formatamoney  
  
function demaskvalue(valor, currency)
{  
/* 
* Se currency Ã© false, retorna o valor sem apenas com os nÃºmeros. Se Ã© true, os dois Ãºltimos caracteres sÃ£o considerados as  
* casas decimais 
*/  
var val2 = '';  
var strCheck = '0123456789';  
var len = valor.length;  
   if (len== 0){  
      return 0.00;  
   }  
  
   if (currency ==true){     
      /* Elimina os zeros Ã  esquerda  
      * a variÃ¡vel  <i> passa a ser a localizaÃ§Ã£o do primeiro caractere apÃ³s os zeros e  
      * val2 contÃ©m os caracteres (descontando os zeros Ã  esquerda) 
      */  
        
      for(var i = 0; i < len; i++)  
         if ((valor.charAt(i) != '0') && (valor.charAt(i) != ',')) break;  
        
      for(; i < len; i++){  
         if (strCheck.indexOf(valor.charAt(i))!=-1) val2+= valor.charAt(i);  
      }  
  
      if(val2.length==0) return "0.00";  
      if (val2.length==1)return "0.0" + val2;  
      if (val2.length==2)return "0." + val2;  
        
      var parte1 = val2.substring(0,val2.length-2);  
      var parte2 = val2.substring(val2.length-2);  
      var returnvalue = parte1 + "." + parte2;  
      return returnvalue;  
        
   }  
   else{  
         /* currency Ã© false: retornamos os valores COM os zeros Ã  esquerda,  
         * sem considerar os Ãºltimos 2 algarismos como casas decimais  
         */  
         val3 ="";  
         for(var k=0; k < len; k++){  
            if (strCheck.indexOf(valor.charAt(k))!=-1) val3+= valor.charAt(k);  
         }           
   return val3;  
   }  
}  
  
function reais(obj,event){  
  
var whichCode = (window.Event) ? event.which : event.keyCode;  
/* 
Executa a formataÃ§Ã£o apÃ³s o backspace nos navegadores !document.all 
*/  
if (whichCode == 8 && !documentall) {     
/* 
Previne a aÃ§Ã£o padrÃ£o nos navegadores 
*/  
   if (event.preventDefault){ //standart browsers  
         event.preventDefault();  
      }else{ // internet explorer  
         event.returnValue = false;  
   }  
   var valor = obj.value;  
   var x = valor.substring(0,valor.length-1);  
   obj.value= demaskvalue(x,true).formatCurrency();  
   return false;  
}  
/* 
Executa o Formata Reais e faz o format currency novamente apÃ³s o backspace 
*/  
FormataReais(obj,'.',',',event);  
} // end reais  
  
documentall = document.all;
function backspace(obj,event){  
/* 
Essa funÃ§Ã£o basicamente altera o  backspace nos input com mÃ¡scara reais para os navegadores IE e opera. 
O IE nÃ£o detecta o keycode 8 no evento keypress, por isso, tratamos no keydown. 
Como o opera suporta o infame document.all, tratamos dele na mesma parte do cÃ³digo. 
*/  
  
var whichCode = (window.Event) ? event.which : event.keyCode;  
if (whichCode == 8 && documentall) {     
   var valor = obj.value;  
   var x = valor.substring(0,valor.length-1);  
   var y = demaskvalue(x,true).formatCurrency();  
  
   obj.value =""; //necessÃ¡rio para o opera  
   obj.value += y;  
     
   if (event.preventDefault){ //standart browsers  
         event.preventDefault();  
      }else{ // internet explorer  
         event.returnValue = false;  
   }  
   return false;  
  
   }// end if        
}// end backspace  
  
function FormataReais(fld, milSep, decSep, e) {  
var sep = 0;  
var key = '';  
var i = j = 0;  
var len = len2 = 0;  
var strCheck = '0123456789';  
var aux = aux2 = '';  
var whichCode = (window.Event) ? e.which : e.keyCode;  
  
//if (whichCode == 8 ) return true; //backspace - estamos tratando disso em outra funÃ§Ã£o no keydown  
if (whichCode == 0 ) return true;  
if (whichCode == 9 ) return true; //tecla tab  
if (whichCode == 13) return true; //tecla enter  
if (whichCode == 16) return true; //shift internet explorer  
if (whichCode == 17) return true; //control no internet explorer  
if (whichCode == 27 ) return true; //tecla esc  
if (whichCode == 34 ) return true; //tecla end  
if (whichCode == 35 ) return true;//tecla end  
if (whichCode == 36 ) return true; //tecla home  
  
/* 
O trecho abaixo previne a aÃ§Ã£o padrÃ£o nos navegadores. NÃ£o estamos inserindo o caractere normalmente, mas via script 
*/  
  
if (e.preventDefault){ //standart browsers  
      e.preventDefault()  
   }else{ // internet explorer  
      e.returnValue = false  
}  
  
var key = String.fromCharCode(whichCode);  // Valor para o cÃ³digo da Chave  
if (strCheck.indexOf(key) == -1) return false;  // Chave invÃ¡lida  
  
/* 
Concatenamos ao value o keycode de key, se esse for um nÃºmero 
*/  
fld.value += key;  
  
var len = fld.value.length;  
var bodeaux = demaskvalue(fld.value,true).formatCurrency();  
fld.value=bodeaux;  
  
/* 
Essa parte da funÃ§Ã£o tÃ£o somente move o cursor para o final no opera. Atualmente nÃ£o existe como movÃª-lo no konqueror. 
*/  
  if (fld.createTextRange) {  
    var range = fld.createTextRange();  
    range.collapse(false);  
    range.select();  
  }  
  else if (fld.setSelectionRange) {  
    fld.focus();  
    var length = fld.value.length;  
    fld.setSelectionRange(length, length);  
  }  
  return false;  
  
}

/**
 * funÃ§Ã£o em jscript para percorrer todos os elementos do formulario 
 * e procurar o especifico e ver se estÃ¡ prenchido, caso nÃ£o esteja, 
 * para o envio e lanÃ§a um alerta.
 * f nome do formulario
 * arrCampos aonde irÃ¡ conter os 5 campos: quantidade, quantidade por unidade, vlr unitario, total por linha, total por coluna. Mais o campo aonde fica o somatÃ³rio.
 * 
 * 
 */

function inicializaSoma()
{

	for ( var int = 0; int < 5; int++) {

		somatorio(int);
	}
}

var arrfinanc = Array(Array());
var totalOrcN = Array('0','0','0','0','0');
var totalOrcL = Array('0','0','0','0','0');
var arrDados = Array();
arrDados[0] = Array('qtdepreprod_' , 'qtde_unidpreprod_' , 'vlr_unitariopreprod_' , 'vlr_totalpreprod_' , 'totalpreprod' , 'incrementaPreProd' , 'fte_financpreprod_');
arrDados[1] = Array('qtdeproducao_' , 'qtde_unidproducao_' , 'vlr_unitarioproducao_' , 'vlr_totalproducao_' , 'totalprod' , 'incrementaProd' , 'fte_financproducao_');
arrDados[2] = Array('qtdedivulgacao_' , 'qtde_uniddivulgacao_' , 'vlr_unitariodivulgacao_' , 'vlr_totaldivulgacao_' , 'totaldivulgacao' , 'incrementaDivulgacao' , 'fte_financdivulgacao_');
arrDados[3] = Array('qtdeadministrativo_' , 'qtde_unidadministrativo_' , 'vlr_unitarioadministrativo_' , 'vlr_totaladministrativo_' , 'totaladministrativo' , 'incrementaAdministrativo' , 'fte_financadministrativo_');
arrDados[4] = Array('qtdeimposto_' , 'qtde_unidimposto_' , 'vlr_unitarioimposto_' , 'vlr_totalimposto_' , 'totalimposto' , 'incrementaImposto' , 'fte_financimposto_');
arrayDestinoN = Array('vlr_1' , 'vlr_2' , 'vlr_3' , 'vlr_4' , 'vlr_5');
arrayDestinoL = Array('vlr_lic_1' , 'vlr_lic_2' , 'vlr_lic_3' , 'vlr_lic_4' , 'vlr_lic_5');

function somatorio(num)
{
    var quantidade = 0;
    var quantidadeUnitario = 0;
    var vlrUnitario = 0;
    var totalLinha = 0;
    var totalColuna = 0;
    var totalPlanilha = 0;
    var destino = 0;
    var resumoN = 0;
    var resumoL = 0;
    var somaOrcL = 0;
    var somaOrcN = 0;
    var valorCampo = 0;
    var formLen = document.formInteresse.elements;
    var posicao = 0;
	var subtotal = 0;
	var idiTem = 0;
	var calculo = 0;
	var totalFianc = 0;
	var calcPcto = 0;
	var i=0;
	var j= 0;
	
	for ( var int = 0; int < formLen.length; int++) {
		
		if((formLen[int].type == "text") && (formLen[int].name == "vlr_financ[]")){
			
			formLen[int].value = 0;
		}
		
		if((formLen[int].type == "text") && (formLen[int].name == "pcto_financ[]")){
			
			formLen[int].value = 0;
		}
		
		if((formLen[int].type == "text") && (formLen[int].name == "pcto_orcamento[]")){

			formLen[int].value = 0;
		}
	}

    elementoP = document.getElementById(arrDados[num][5]).value;
	
	resumoN = 0;
	for(var i = 0 ;i <= elementoP ; i++) {

    	quantidade = $(arrDados[num][0]+i).value;
		quantidadeUnitario = $(arrDados[num][1] + i).value;
		vlrUnitario = $(arrDados[num][2] + i).value;
		vlrUnitario = vlrUnitario.replace("." , "");
		vlrUnitario = vlrUnitario.replace("." , "");
		vlrUnitario = vlrUnitario.replace("," , ".");
		totalLinha = parseFloat(parseFloat(quantidade) * parseFloat(quantidadeUnitario) * parseFloat(vlrUnitario));
		totalLinha = isNaN(parseFloat(totalLinha)) ? 0 : parseFloat(totalLinha);
		$(arrDados[num][3] + i).value = formatCurrency(parseFloat(totalLinha));
		totalColuna += parseFloat(totalLinha);
		destino = arrDados[num][6] + i;
	
    	resumoN = parseFloat(parseFloat(resumoN) + parseFloat(totalLinha));
    	if(resumoN != '')somaOrcN = parseFloat(resumoN);
	    if($(destino).value == 7){
	    	
	    	resumoL = parseFloat(resumoL) + parseFloat(totalLinha);
	    	if(resumoL != '')somaOrcL = parseFloat(resumoL);
	    }

	    totalOrcN[num] = somaOrcN;
	    totalOrcL[num] = somaOrcL;
	    $(arrDados[num][4]).value   = formatCurrency(totalColuna);
	    $(arrayDestinoL[num]).value = formatCurrency(parseFloat(resumoL));
	    $(arrayDestinoN[num]).value = formatCurrency(parseFloat(resumoN));
	}

    totalOrcamentoN = parseFloat(totalOrcN[0]) + parseFloat(totalOrcN[1]) + parseFloat(totalOrcN[2]) + parseFloat(totalOrcN[3]) + parseFloat(totalOrcN[4]);
    $('vlr_total_custo').value = formatCurrency(totalOrcamentoN);
    totalOrcamentoL = parseFloat(totalOrcL[0]) + parseFloat(totalOrcL[1]) + parseFloat(totalOrcL[2]) + parseFloat(totalOrcL[3]) + parseFloat(totalOrcL[4]);
    $('vlr_total_custo_lic').value = formatCurrency(totalOrcamentoL);
    totalPlanilha = parseFloat(formatCalc($(arrDados[0][4]).value)) + parseFloat(formatCalc($(arrDados[1][4]).value)) + parseFloat(formatCalc($(arrDados[2][4]).value)) + parseFloat(formatCalc($(arrDados[3][4]).value)) + parseFloat(formatCalc($(arrDados[4][4]).value));
    $("totaltotal").innerHTML = formatCurrency(totalPlanilha);

    for ( var int = 0; int < formLen.length; int++) {
		
    	if((formLen[int].type == "text") && (formLen[int].name == "vlr_total[]")){
			
			subtotal = formatCalc(formLen[int].value ? formLen[int].value : 0);
    	}
		

		if((formLen[int].type == "select-one") && (formLen[int].name == "fte_financ[]")){
            
			posicao = formLen[int].value ? formLen[int].value : 0;
            idiTem = 'vlr_financ' + posicao;
            pctoItem = 'pcto_financ' + posicao;
            calculo = formatCalc($(idiTem).value ? $(idiTem).value : 0);
            totalFianc = parseFloat(calculo) + parseFloat(subtotal);
			
            $(idiTem).value = formatCurrency(totalFianc);
        
            if ((totalFianc > 0) && (totalPlanilha > 0)) {
            
            	$(pctoItem).value = formatCurrency((parseFloat(totalFianc) * parseFloat(100)) / parseFloat(totalPlanilha));
			}
            calculo = 0;
        }
	}
    $('vlr_total_financiamento').value = formatCurrency(totalPlanilha);
    i = 1;
    j = 1;

    for ( var int = 0; int < formLen.length; int++) {
    
    	if((formLen[int].type == "text") && (formLen[int].name == "vlr_orcamento[]")){
    		
    		valorCampo = formatCalc((formLen[int].value == '') ? 0 : formLen[int].value);
    		calcPcto = parseFloat(valorCampo) * parseFloat(100) / parseFloat(totalOrcamentoN);
    		pctoCampo = 'pcto_' + i;
    		$(pctoCampo).value = formatCurrency(calcPcto);
    		i++;
		}

    	if((formLen[int].type == "text") && (formLen[int].name == "vlr_orcamento_lic[]")){
    		
    		valorCampoL = formatCalc((formLen[int].value == '') ? 0 : formLen[int].value);
    		calcPctoL = parseFloat(valorCampoL) * parseFloat(100) / parseFloat(totalOrcamentoL);
    		pctoCampoL = 'pcto_lic_' + j; 
    		$(pctoCampoL).value = formatCurrency(calcPctoL);
    		j++;
		}
	}
}


function validaData2(m,ant)
{
	var consulta = /^([0][1-9]|[1|2][0-9]|[3][0|1])\/([0][1-9]|[1][0-2])\/([0-9]{4})$/gi;
	var rst = false;

	rst = m.value.match(consulta);

	if($(ant).value){
		if(!rst){
		    alert('Verifique a digitação, o padrão adotado é dd/mm/aaaa');
		    document.getElementById(m.id).style.backgroundColor='red';
		    return rst;
		}else{
			document.getElementById(m.id).style.backgroundColor='';
			return rst;
	    }
	}
}

function removeProjeto(proj){
	
	r = confirm("Deseja remover definitivamente o projeto ");
	if (r == true) {
		window.location = proj;	
	}
}
