
function prepareOperand(stringOperand) {
    stringOperand = stringOperand.replace(".", "");
    stringOperand = stringOperand.replace(".", "");
    stringOperand = stringOperand.replace(".", "");
    stringOperand = stringOperand.replace(".", "");
    stringOperand = stringOperand.replace(",", ".");
    
    var floatOperand = parseFloat(stringOperand);
    var testeOperand = new String(floatOperand);
    if (testeOperand != "NaN") {
      return floatOperand;       
    } else {
      return 0;
    }
}
    
function calculateTotalGeral() {
    var desenvolvimentoProjeto = new String(document.getElementById("form1:desenvolvimentoProjetoTextField_field").value);
    var preProducao = new String(document.getElementById("form1:preProducaoTextField_field").value);
    var producao = new String(document.getElementById("form1:producaoTextField_field").value);
    var posProducao = new String(document.getElementById("form1:posProducaoTextField_field").value);
    var despesasAdministrativas = new String(document.getElementById("form1:despesasAdministrativasTextField_field").value);
    var encargosTributosTaxas = new String(document.getElementById("form1:encargosTributosTaxasTextField_field").value);
    var taxaGerenciamento = new String(document.getElementById("form1:taxaGerenciamentoTextField_field").value);
    var taxaAgenciamento = new String(document.getElementById("form1:taxaAgenciamentoColocacaoTextField_field").value);
    var comercializacaoDivulgacao = new String(document.getElementById("form1:comercializacaoDivulgacaoTextField_field").value);
    
    var floatDPROJ = prepareOperand(desenvolvimentoProjeto);
    var floatPREP = prepareOperand(preProducao);
    var floatPROD = prepareOperand(producao);
    var floatPPRO = prepareOperand(posProducao);
    var floatDADMIN = prepareOperand(despesasAdministrativas);
    var floatENC = prepareOperand(encargosTributosTaxas);
    var floatTGER = prepareOperand(taxaGerenciamento);
    var floatTAGE = prepareOperand(taxaAgenciamento);
    var floatCOME = prepareOperand(comercializacaoDivulgacao);
    
    var floatTotalGeral = (floatDPROJ + floatPREP +
                           floatPROD + floatPPRO +
                           floatDADMIN + floatENC +
                           floatTGER + floatTAGE +
                           floatCOME);
                       
    var fieldTotalGeral = document.getElementById("form1:totalGeralTextField_field");
    fieldTotalGeral.value = formatCurrency(floatTotalGeral);
}    
    
function calculateTotalFinanciavel() {
    var preProducao = new String(document.getElementById("form1:preProducaoTextField_field").value);
    var producao = new String(document.getElementById("form1:producaoTextField_field").value);
    var posProducao = new String(document.getElementById("form1:posProducaoTextField_field").value);
    var despesasAdministrativas = new String(document.getElementById("form1:despesasAdministrativasTextField_field").value);
    var encargosTributosTaxas = new String(document.getElementById("form1:encargosTributosTaxasTextField_field").value);
    var taxaGerenciamento = new String(document.getElementById("form1:taxaGerenciamentoTextField_field").value);

    var floatPREP = prepareOperand(preProducao);
    var floatPROD = prepareOperand(producao);
    var floatPPRO = prepareOperand(posProducao);
    var floatDADMIN = prepareOperand(despesasAdministrativas);
    var floatENC = prepareOperand(encargosTributosTaxas);
    var floatTAXA = prepareOperand(taxaGerenciamento);
    
    var floatTotalFinanciavel = (floatPREP + floatPROD + floatPPRO + floatDADMIN + floatENC + floatTAXA);
                       
    var fieldTotalFinanciavel = document.getElementById("form1:totalItensFinanciaveisTextField_field");
    fieldTotalFinanciavel.value = formatCurrency(floatTotalFinanciavel);
}    
    
function calculateTotalGeralComercializacao() {
    var copiasServicosAdjacentes = new String(document.getElementById("form1:copiasServTextField_field").value);
    var publicidade = new String(document.getElementById("form1:publicidadeTextField_field").value);
    var outrasDespesas = new String(document.getElementById("form1:outrasDespesasTextField_field").value);
    
    var floatCSADJ = prepareOperand(copiasServicosAdjacentes);
    var floatPUB = prepareOperand(publicidade);
    var floatODESP = prepareOperand(outrasDespesas);
    
    var floatTotalGeral = (floatCSADJ + floatPUB + floatODESP);
                       
    var fieldTotalGeral = document.getElementById("form1:totalGeralTextField_field");
    fieldTotalGeral.value = formatCurrency(floatTotalGeral);
}    
    
function calculateTotalFinanciavelComercializacao() {
    var copiasServicosAdjacentes = new String(document.getElementById("form1:copiasServTextField_field").value);
    var publicidade = new String(document.getElementById("form1:publicidadeTextField_field").value);
    
    var floatCSADJ = prepareOperand(copiasServicosAdjacentes);
    var floatPUB = prepareOperand(publicidade);
    
    var floatTotalFinanciavel = (floatCSADJ + floatPUB);
                       
    var fieldTotalFinanciavel = document.getElementById("form1:totalItensFinanciaveisTextField_field");
    fieldTotalFinanciavel.value = formatCurrency(floatTotalFinanciavel);
}    
    
function multiplyFields(operand1, operand2, resultfield){
    var value1 = new String(operand1.value);
    var value2 = new String(operand2.value);
    value1 = value1.replace(".", "");
    value1 = value1.replace(".", "");
    value1 = value1.replace(".", "");
    value1 = value1.replace(".", "");
    value1 = value1.replace(",", ".");
	
    value2 = value2.replace(".", "");
    value2 = value2.replace(".", "");
    value2 = value2.replace(".", "");
    value2 = value2.replace(".", "");
    value2 = value2.replace(",", ".");
	
    //var temp = String(parseFloat(value1));
	
    var f1 = parseFloat(value1);
    var f2 = parseFloat(value2);
    var numericResult = (f1 * f2);
    //alert(f1 + " - " + f2 + " - " + numericResult);
    resultfield.value = formatCurrency(numericResult);
}


function remainingCharsActivity(){
    var txt2 = document.getElementsByName('JUSTIFICATIVA');
    displayRemainigChars(txt2[0], 'justLenTxt', 500);
}

function remainingCharsTeamMember(){
    var txt = document.getElementsByName('MINICV');
    displayRemainigChars(txt[0], 'miniCvLenTxt', 500);
    var txt2 = document.getElementsByName('JUSTIFICATIVA');
    displayRemainigChars(txt2[0], 'justLenTxt', 500);
}

function remainingCharsProject(){
    var txt = document.getElementsByName('RESUMOPUB');
    displayRemainigChars(txt[0], 'resumoPubLenTxt', 500);
    var txt2 = document.getElementsByName('DESCTEC');
    displayRemainigChars(txt2[0], 'descTecLenTxt', 4000);
    var txt3 = document.getElementsByName('DESCMET');
    displayRemainigChars(txt3[0], 'descMetLenTxt', 4000);
    var txt4 = document.getElementsByName('DESCMEC');
    displayRemainigChars(txt4[0], 'descMecLenTxt', 4000);
    var txt5 = document.getElementsByName('VANTAGENS');
    displayRemainigChars(txt5[0], 'vantagesLenTxt', 4000);
}

function remainingCharsProponent(){
    var txt = document.getElementsByName('HISTEMPRESA');
    displayRemainigChars(txt[0], 'histEmpLenTxt', 4000);
    var txt2 = document.getElementsByName('COMPCAPITAL');
    displayRemainigChars(txt2[0], 'compCapLenTxt', 1000);
    var txt3 = document.getElementsByName('INSTFISICAS');
    displayRemainigChars(txt3[0], 'instFisLenTxt', 1000);
    var txt4 = document.getElementsByName('HISTPD');
    displayRemainigChars(txt4[0], 'histPDLenTxt', 4000);
    var txt5 = document.getElementsByName('HISTFINANC');
    displayRemainigChars(txt5[0], 'histFinLenTxt', 1000);
}

function gravaDados(nomeDofrm,strDestino){
    var frm = document.getElementsByName(nomeDofrm);
    if (frm[0] != null) {
        frm[0].DESTINO.value = strDestino;
        frm[0].submit();
        //alert('then');
    } else {
        window.location=strDestino;
        //alert('else');
    }
}

/**
 * Formats a value to Currency 
 * 
 * @param value1 to be formatted
 */
function formatCurrency(value1){
    var value = new String(value1);
    var valuetest = new String(value1);
    var inteiros = "";
    var decimais = "";
	
    if (value != "NaN") {
        valuetest = valuetest.replace(".", ",");
        var posvirgula = valuetest.indexOf(",");
        if (parseInt(posvirgula) >= 0) {
            inteiros = new String(parseFloat(valuetest.substr(0, posvirgula)));
            decimais = valuetest.substr(posvirgula + 1, 2);
            if (decimais.length < 2) {
                decimais = decimais + "0";
            }
        } else {
            inteiros = new String(parseFloat(valuetest));
            decimais = "00";
        }
        value = inteiros + decimais;
	
        size = value.length;
        if (size < 17) {
            if (size == 1)
                return "0,0" + value;
            if (size == 2)
                return "0," + value;
            if (size >= 3 && size < 6)
                return value.substr(0, size - 2) + ',' + value.substr(size - 2, 2);
            if (size >= 6 && size < 9)
                return value.substr(0, size - 5) + '.' + value.substr(size - 5, 3) + ',' + value.substr(size - 2, 2);
            if (size >= 9 && size < 12)
                return value.substr(0, size - 8) + '.' +
                value.substr(size - 8, 3) + '.' +
                value.substr(size - 5, 3) + ',' +
                value.substr(size - 2, 2);
            if (size >= 12 && size < 15)
                return value.substr(0, size - 11) + '.' +
                value.substr(size - 11, 3) + '.' +
                value.substr(size - 8, 3) + '.' +
                value.substr(size - 5, 3) + ',' +
                value.substr(size - 2, 2);

            // if (size >= 15 && size < 17)
            // Não precisa porque essa é a única possibilidade nesse ponto.
            // Evita warning: ... does not always return a value.
                return value.substr(0, size - 14) + '.' +
                value.substr(size - 14, 3) + '.' +
                value.substr(size - 11, 3) + '.' +
                value.substr(size - 8, 3) + '.' +
                value.substr(size - 5, 3) + ',' +
                value.substr(size - 2, 2);
	
        } else {
            return "Valor grande demais";
        }
    } else {
        return "0,00";
    }
}

/**
 * Counts the size in bytes of a string.
 * 
 * NOTE: Javascript lengh method considers a carriage return + linefeed as 1 character 
 * but the real size in bytes is two for windows systems. So, in some situations, 
 * it is needed to count these characters as two bytes and avoid using: 
 * var size = value.length.
 *  
 * @param string the string.
 */
function getStringSize(string) {
    var size = 0;
    for (i = 0; i < string.length; i++)
        if (string.charAt(i) == '\n')
            size += 2;
    else
        size += 1;
    return size;
}

/**
 * Limits a field to a maximum size in bytes.
 * 
 * @param field the field to be size-limited.
 * @param event the event used to call this function (should be a key event).
 * @param maxSize the maximum size of the field.
 * 
 * @see displayRemainigChars for displaying remaining characters information.
 */
function limitField(field, event, maxSize) {
    var key = (window.event) ? event.keyCode : event.which;
    var value = new String(field.value + key);
    var numBytes = getStringSize(value);

    if (numBytes > maxSize) {
        var maxChars = maxSize + value.length - numBytes;
        field.value = value.substring(0, maxChars) ;
        if ((key != 9) && (key != 8) && (key != 0)) {
            return false;
        }
    } 
    return true;
}

/**
 * Counts how many bytes has been typed in a field by the user and displays remaining bytes 
 * inside a SPAN html tag element.
 * 
 * @param field the field where the text is been typed.
 * @param spanMsgId the id of the span element where the remaining characters will be displayed.
 * @param maxSize the maximum size of the field.
 * 
 * @see limitField for field limiting information.
 */
function displayRemainigChars(field, spanMsgId, maxSize) {
    var text = eval(field);
    var size = getStringSize(text.value);
    var remainingSize = maxSize - size;
    document.getElementById(spanMsgId).innerHTML = remainingSize.toString();
}
							
							
/**
 * Functions for implementing image buttons in HTML forms 
 *
 */								
 
function MM_swapImgRestore() { //v3.0
    var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
    var d=document; if(d.images){
        if(!d.MM_p) d.MM_p=new Array();
        var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
            if (a[i].indexOf("#")!=0){
                d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];
            }
    }
}

function MM_findObj(n, d) { //v4.01
    var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
        d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);
    }
    if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
    for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
    if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
    var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
        if ((x=MM_findObj(a[i]))!=null){
            document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];
        }
}

function mascara(o,f){
    v_obj=o
    v_fun=f
    setTimeout("execmascara()",1)
}

function execmascara(){
    v_obj.value=v_fun(v_obj.value)
}

function calculoTotalGeral(){
    setTimeout("execTotalGeral()",1)
}

function execTotalGeral(){
    calculateTotalGeral()
}

function calculoTotalFinanciavel(){
    setTimeout("execTotalFinanciavel()",1)
}

function execTotalFinanciavel(){
    calculateTotalFinanciavel()
}

function calculoTotalGeralComercializacao(){
    setTimeout("execTotalGeralComercializacao()",1)
}

function execTotalGeralComercializacao(){
    calculateTotalGeralComercializacao()
}

function calculoTotalFinanciavelComercializacao(){
    setTimeout("execTotalFinanciavelComercializacao()",1)
}

function execTotalFinanciavelComercializacao(){
    calculateTotalFinanciavelComercializacao()
}

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
    //de novo (para o segundo bloco de números)
    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 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 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 currency(v){
    v=v.replace(/\D/g,"")                           //Remove tudo o que não é dígito
    v=v.replace(/^([0]+)(\d)/,"$2")
    
    if (v.length == 1) {
        v=v.replace(/(\d{1})/,"0,0$1")
    } else {
        if (v.length == 2) {
            v=v.replace(/(\d{2})/,"0,$1")
        } else {
            v=v.replace(/(\d)(\d{2})$/,"$1,$2")            
            v=v.replace(/(\d)(\d{3})\,(\d{2})$/,"$1.$2,$3")
            v=v.replace(/(\d)(\d{3})\.(\d{3})\,(\d{2})$/,"$1.$2.$3,$4")
            v=v.replace(/(\d)(\d{3})\.(\d{3})\.(\d{3})\,(\d{2})$/,"$1.$2.$3.$4,$5")
            v=v.replace(/(\d)(\d{3})\.(\d{3})\.(\d{3})\.(\d{3})\,(\d{2})$/,"$1.$2.$3.$4.$5,$6")
        }
    }
    return v
}

function data(v){
    v=v.replace(/\D/g,"")
    v=v.replace(/^(\d{2})(\d)/,"$1/$2")
    v=v.replace(/^(\d{2})\/(\d{2})(\d)/,"$1/$2/$3")
    return v
}

function datahora(v){
    v=v.replace(/\D/g,"")
    v=v.replace(/^(\d{2})(\d)/,"$1/$2")
    v=v.replace(/^(\d{2})\/(\d{2})(\d)/,"$1/$2/$3")
    v=v.replace(/^(\d{2})\/(\d{2})\/(\d{4})(\d)/,"$1/$2/$3-$4")
    v=v.replace(/^(\d{2})\/(\d{2})\/(\d{4})\-(\d{2})(\d)/,"$1/$2/$3-$4:$5")
    v=v.replace(/^(\d{2})\/(\d{2})\/(\d{4})\-(\d{2})\:(\d{2})(\d)/,"$1/$2/$3-$4:$5:$6")
    v=v.replace("-"," ")
    return v
}

function site(v){
    //Esse sem comentarios para que você entenda sozinho ;-)
    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 sonumeros(v){
    v=v.replace(/\D/g,"")
    return v
}

function nome(v) {
    v=v.replace(/[0-9!@#$%¨&*()_+{},.;\-\=\[\]\\\/]/g,"")
    return v
}

function semdigitar(field, event){
    return false;
}


