var turnoGeral;
var nColab = 1;
function Validar(theCPF)
{

    if (theCPF.value == "")
    {
        alert("Campo inválido. É necessário informar o CPF ou CNPJ");
        theCPF.focus();
        return false;
    }
    if (((theCPF.value.length == 11) && (theCPF.value == 11111111111) || (theCPF.value == 22222222222) || (theCPF.value == 33333333333) || (theCPF.value == 44444444444) || (theCPF.value == 55555555555) || (theCPF.value == 66666666666) || (theCPF.value == 77777777777) || (theCPF.value == 88888888888) || (theCPF.value == 99999999999) || (theCPF.value == 00000000000)))
    {
        alert("CPF/CNPJ inválido.");
        theCPF.focus();
        return (false);
    }


    if (!((theCPF.value.length == 11) || (theCPF.value.length == 14)))
    {
        alert("CPF/CNPJ inválido.");
        theCPF.focus();
        return (false);
    }

    var checkOK = "0123456789";
    var checkStr = theCPF.value;
    var allValid = true;
    var allNum = "";
    for (i = 0;  i < checkStr.length;  i++)
    {
        ch = checkStr.charAt(i);
        for (j = 0;  j < checkOK.length;  j++)
            if (ch == checkOK.charAt(j)) break;
        if (j == checkOK.length)
        {
            allValid = false;
            break;
        }
        allNum += ch;
    }
    if (!allValid)
    {
        alert("Favor preencher somente com dígitos o campo CPF/CNPJ.");
        theCPF.focus();
        return (false);
    }

    var chkVal = allNum;
    var prsVal = parseFloat(allNum);
    if (chkVal != "" && !(prsVal > "0"))
    {
        alert("CPF zerado !");
        theCPF.focus();
        return (false);
    }

    if (theCPF.value.length == 11)
    {
        var tot = 0;

        for (i = 2;  i <= 10;  i++)
            tot += i * parseInt(checkStr.charAt(10 - i));

        if ((tot * 10 % 11 % 10) != parseInt(checkStr.charAt(9)))
        {
            alert("CPF/CNPJ inválido.");
            theCPF.focus();
            return (false);
        }

        tot = 0;

        for (i = 2;  i <= 11;  i++)
            tot += i * parseInt(checkStr.charAt(11 - i));

        if ((tot * 10 % 11 % 10) != parseInt(checkStr.charAt(10)))
        {
            alert("CPF/CNPJ inválido.");
            theCPF.focus();
            return (false);
        }
    }
    else
    {
        var tot  = 0;
        var peso = 2;

        for (i = 0;  i <= 11;  i++)
        {
            tot += peso * parseInt(checkStr.charAt(11 - i));
            peso++;
            if (peso == 10)
            {
                peso = 2;
            }
        }

        if ((tot * 10 % 11 % 10) != parseInt(checkStr.charAt(12)))
        {
            alert("CPF/CNPJ inválido.");
            theCPF.focus();
            return (false);
        }

        tot  = 0;
        peso = 2;

        for (i = 0;  i <= 12;  i++)
        {
            tot += peso * parseInt(checkStr.charAt(12 - i));
            peso++;
            if (peso == 10)
            {
                peso = 2;
            }
        } m

        if ((tot * 10 % 11 % 10) != parseInt(checkStr.charAt(13)))
        {
            alert("CPF/CNPJ inválido.");
            theCPF.focus();
            return (false);
        }
    }
    return(true);
}

function criaRequest() {
    try {
        request = new XMLHttpRequest();
    } catch (trymicrosoft) {
        try {
            request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (othermicrosoft) {
            try {
                request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (failed) {
                request = null;
            }
        }
    }

    if (request == null)
        alert("Error creating request object!");
}
function maskDt(campoData){
    var data = campoData.value;
    if (data.length == 2){
        data = data + '/';
        document.getElementById(campoData.name).value = data;
        return true;
    }
    if (data.length == 5){
        data = data + '/';
        document.getElementById(campoData.name).value = data;
        return true;
    }
}

function mudaOrelha(orelha){
    if(orelha == 1){
        document.getElementById('geral').style.display = 'block';
        document.getElementById('1').style.background = '#C5BEC1';
        document.getElementById('2').style.background = '#E0DEE0';
        document.getElementById('end').style.display = 'none';
    }else
    if(orelha == 2){
        document.getElementById('geral').style.display = 'none';
        document.getElementById('1').style.background = '#E0DEE0';
        document.getElementById('2').style.background = '#C5BEC1';
        document.getElementById('end').style.display = 'block';
    }
}
function sair(){
    window.location = 'index.php?sair=1';
}
function habilitaCat(tipo){
    document.getElementById('id_categoria').disabled = false;
    if(tipo == "0")
        if(document.getElementById('id_categoria').disabled == false)
            document.getElementById('id_categoria').disabled = true;
}
function liberaTipoColab(){
    if(document.getElementById('tp').value == 2){
        document.getElementById('id_tp_colab').disabled = false;
    }
    else{
        document.getElementById('id_tp_colab').disabled = true;
    }
}
function mudaInputFiles(){
    if(document.getElementById('arq').type == 'file'){
        document.getElementById('input_arq').innerHTML = "<input type='text' size=50 name='arq' id='arq'>";
        document.getElementById('lab_arq').innerHTML = 'Link:';
    }else{
        document.getElementById('input_arq').innerHTML = "<input type='file' size=58 name='arq' id='arq'>";
        document.getElementById('lab_arq').innerHTML = 'Arquivo:';

    }

}

function liberaTurno(turno){
    //Status do campo turno
    var i_turno		= turno - 1;
    var s_turno		= document.form1.turnos[i_turno];
    var nm_turno	=  document.getElementById('dsc_'+turno);
    var qtd_turno	=  document.getElementById('qtd_'+turno);
    var div			= document.createElement("div");
    var h			= document.createElement("h5");
    h.setAttribute("id","hText"+turno);
    var hText		= document.createTextNode('Turno '+turno);
    var boxColab	= document.createElement("select");
    boxColab.setAttribute("id","colab"+turno);
    boxColab.setAttribute("name","colab"+turno);
    var boxColab2	= document.createElement("select");
    boxColab2.setAttribute("id","colab2_"+turno);
    boxColab2.setAttribute("name","colab2_"+turno);
    var boxColab3	= document.createElement("select");
    boxColab3.setAttribute("id","colab3_"+turno);
    boxColab3.setAttribute("name","colab3_"+turno);
    turnoGeral = turno;
    if(s_turno.checked){
        nm_turno.disabled  = false;
        qtd_turno.disabled = false;
        //Cria??o da camada com os campos de inser??o do nome das turmas do turno
        if(!document.getElementById("turno"+turno)){
            div.setAttribute("id","turno"+turno);
            div.style.cssText = "width:49%;float:left;margin-left:6px;";
            div.setAttribute("style","width:49%;float:left;margin-left:5px;");
            h.appendChild(hText);
            div.appendChild(h);
            div.appendChild(document.createElement("br"));
            div.appendChild(document.createTextNode("Colaborador responsável: "));
            div.appendChild(boxColab);
            div.appendChild(document.createElement("br"));
            div.appendChild(document.createTextNode("Colaborador responsável: "));
            div.appendChild(boxColab2);
            div.appendChild(document.createElement("br"));
            div.appendChild(document.createTextNode("Colaborador responsável: "));
            div.appendChild(boxColab3);
            div.appendChild(document.createElement("br"));
            div.appendChild(document.createElement("hr"));
            div.appendChild(document.createElement("br"));
            document.getElementById('div-turmas').appendChild(div);
        	this.criaComboColab();
        }
    }else{
        if(document.getElementById("turno"+turno))
            document.getElementById('div-turmas').removeChild(document.getElementById("turno"+turno));
        nm_turno.value	= "Turno "+turno;
        qtd_turno.value = "";
        nm_turno.disabled  = true;
        qtd_turno.disabled = true;
    }
}
function mudaDscTurno(obj){
    var turno	= obj.id.split("_");
    turno = turno[1];
    var h		= document.getElementById("hText"+turno);
    var hText	= document.createTextNode(obj.value);
    h.removeChild(h.firstChild);
    h.appendChild(hText);
}
function geraTurmas(turno){
    var qtdBox		= document.getElementById("qtd_"+turno);
    var qtdBoxValue = qtdBox.value;
    var divTurno	= document.getElementById("turno"+turno);
    var divTurnoTam = divTurno.childNodes.length;
    if(qtdBoxValue > 0){
        if(divTurnoTam > 5){
            for(j=10; j < divTurnoTam; j++)
                divTurno.removeChild(divTurno.lastChild);
        }
        divTurno.appendChild(document.createElement("br"));
        for(i=0; i < qtdBoxValue; i++){
            if(!document.getElementById("turma"+turno+"_"+i)){
                var labelBox = document.createElement("label");
                labelBox.appendChild(document.createTextNode("Turma "+(i+1)+":"));
                var textBox	 = document.createElement("input");
                textBox.setAttribute("type","text");
                textBox.setAttribute("name","turma"+turno+"_"+i);
                textBox.setAttribute("id","turma"+turno+"_"+i);
                textBox.setAttribute("size","50");
                divTurno.appendChild(labelBox);
                divTurno.appendChild(textBox);
                divTurno.appendChild(document.createElement("br"));
            }
        }
        divTurno.appendChild(document.createElement("hr"));
        divTurno.appendChild(document.createElement("br"));
    }
}
function criaComboColab(){
    criaRequest();
    var url = "criaComboColab.php";
    request.open("GET", url, true);
    request.onreadystatechange = carregaComboColab;
    request.send(null);
}
function carregaComboColab(){
    if(request.readyState == 4) {
		var resposta = request.responseXML;
        var filhos = resposta.firstChild.childNodes.length;
        if(nColab == 1)
			document.getElementById('colab'+turnoGeral).length = 1;
        else
			document.getElementById('colab'+nColab+'_'+turnoGeral).length = 1;
        for(var f=1;f<=filhos;f++){
            if((f % 2) != 0){
                var opcoes = document.createElement('option');
                opcoes.setAttribute('value',resposta.firstChild.childNodes[f-1].firstChild.nodeValue);
                var texto_recebido = resposta.firstChild.childNodes[f].firstChild.nodeValue;
                texto_recebido = texto_recebido.replace(/\+/g," "); // Substitue o ?+? por um espa?o.
                texto_recebido = unescape(texto_recebido); // Desfaz o que a fun??o urlencode(); fez.
                var texto = document.createTextNode(texto_recebido);
                opcoes.appendChild(texto);
				if(nColab == 1)
					document.getElementById('colab'+turnoGeral).appendChild(opcoes);
				else
					document.getElementById('colab'+nColab+'_'+turnoGeral).appendChild(opcoes);
			}
        }
		nColab++;
		if(nColab <= 3)
			criaComboColab();
		if(nColab == 4)
			nColab = 1;
    }
}
//O par?metro numCols ? o n?mero de colunas do turno em quest?o
function calculaCamposPlan(campo,turno,col,linha,numCols,linhas){
    var valor = document.getElementById(campo).value;
    var campo_media = document.getElementById("turno"+turno+"_"+linha);
    var campo_mediaT = document.getElementById("mediaT"+turno+"_"+col);
    var campo_totalFunc = document.getElementById("totalFunc"+turno+"_"+linha);
    var campo_totalFuncT = document.getElementById("totalFuncT"+turno);
	var campo_mediaFuncTurma = document.getElementById("mediaFuncTurma"+turno+col);
	var totalTurno = 0;
    var cont = 0;
    var contTotalTurno = 0;
    var totalTurnoL = 0;
    var totFuncTurnoL = 0;
    var mediaTTurno = 0;
    if(campo_totalFunc)
        var perc = true;
    if(!isNaN(valor)){
		for(i = 0; i < numCols; i++){
            var nm_campo = turno+"_"+i+"_"+linha;
            var vl = document.getElementById(nm_campo).value;
            if(vl){
                totalTurno = parseInt(vl,10) + totalTurno;
                contTotalTurno++;
            }
        }
        for(i = 0; i < linhas; i++){
            var nm_campo = turno+"_"+col+"_"+i;
            var nm_campo_func = "tot"+turno+"_"+col+"_"+i;
            var vl = document.getElementById(nm_campo).value;
            if(document.getElementById(nm_campo_func))
                var vl_func = document.getElementById(nm_campo_func).value;
            if(vl)
                totalTurnoL = parseInt(vl,10) + totalTurnoL;
            if(vl_func)
                totFuncTurnoL =  parseInt(vl_func,10) + totFuncTurnoL;
        }
        if(perc){
            if(campo_totalFunc.value){
                vl = ((totalTurno * 100) / campo_totalFunc.value);
                if(vl)
                    campo_media.value = vl.toFixed(2)+"%";

                vl = (totalTurnoL * 100) / totFuncTurnoL;
                if(campo_mediaT && vl)
                    campo_mediaT.value = vl.toFixed(2)+"%";
            }
        }
        else{
            vl = ((totalTurno / contTotalTurno));
            if(vl)
                campo_media.value = vl.toFixed(2);
            vl = (totalTurnoL / totFuncTurnoL);
            if(campo_mediaT && vl)
                campo_mediaT.value = vl.toFixed(2);
        }
        for(i = 0; i < linhas; i++){
            if(document.getElementById("turno"+turno+"_"+i).value){
                mediaTTurno = parseFloat(document.getElementById("turno"+turno+"_"+i).value) + mediaTTurno;
                cont++;
            }
        }
        if(perc){
            vl = mediaTTurno / cont;
            if(!isNaN(vl))
                if(document.getElementById("mediaTTurno"+turno))
                    document.getElementById("mediaTTurno"+turno).value = vl.toFixed(2)+"%";
        }
        else{
            vl = (mediaTTurno) / cont;
            if(document.getElementById("mediaTTurno"+turno))
                document.getElementById("mediaTTurno"+turno).value = vl.toFixed(2);
        }
    }
    else
    if(isNaN(valor)){
        alert("Você deve digitar apenas números nos campos!");
        document.getElementById(campo).value = "";
        document.getElementById(campo).focus();
    }
    if(campo_totalFuncT)
        mediaTotalFuncs(turno,linhas,numCols,linha);

	if(campo_mediaFuncTurma){
		 var mediaPTurma = 0;
		 var contador = 0;
		 for(i = 0; i < linhas; i++){
			var nm_campo = turno+"_"+col+"_"+i;
            if(document.getElementById(nm_campo)){
				if(document.getElementById(nm_campo).value){
					mediaPTurma = parseFloat(document.getElementById(nm_campo).value)+mediaPTurma;
					contador++;
				}
			}
		 }
		 if(!isNaN(mediaPTurma)){
			var result = (mediaPTurma / contador);
			if(!isNaN(result.toFixed(2))){
				campo_mediaFuncTurma.value = result.toFixed(2);
			}
		 }
	}
}
function mediaTotalFuncs(turno, linhas, numCols, linha){
    var total = 0;
    var cont = 0;
    var contTotalTurno = 0;
    var campo_totalFunc;
    //for(i = 0; i < linhas; i++){
		if(document.getElementById("totalFunc"+turno+"_"+linha).value){
            total = parseInt(document.getElementById("totalFunc"+turno+"_"+linha).value,10) + total;
            var totalTurno = 0;
            for(t = 0; t < numCols; t++){
                var nm_campo = turno+"_"+t+"_"+linha;
                var vl = document.getElementById(nm_campo).value;
				if(vl){
                    totalTurno = parseInt(vl,10) + totalTurno;
                    contTotalTurno++;
                    campo_totalFunc = document.getElementById("totalFunc"+turno+"_"+linha);
                    var campo_media = document.getElementById("turno"+turno+"_"+linha);
                    vl = ((totalTurno * 100) / campo_totalFunc.value);
                    if(vl)
                        campo_media.value = vl.toFixed(2)+"%";
                }
            }
            cont++;
        }
    //}
    if(total != 0)
        if(document.getElementById("totalFuncT"+turno)){
            vl = total.toFixed(2)/cont;
            document.getElementById("totalFuncT"+turno).value = vl.toFixed(2);
        }
    if(document.getElementById("mediaTTurno"+turno)){
        var mediaTTurno = 0;
        var cont = 0;
        for(i = 0; i < linhas; i++){
            if(document.getElementById("turno"+turno+"_"+i).value){
                mediaTTurno = parseFloat(document.getElementById("turno"+turno+"_"+i).value) + mediaTTurno;
                cont++;
            }
		}
        vl = mediaTTurno / cont;
        if(!isNaN(vl))
            if(document.getElementById("mediaTTurno"+turno))
                document.getElementById("mediaTTurno"+turno).value = vl.toFixed(2)+"%";
    }
}
function geraPlanilha(){
    var cliente = document.getElementById("id_usuario");
    var mes = document.getElementById("mes");
    var ano = document.getElementById("ano");
    var dias_semana = document.form1.dias;
    var dias_checked = false;
    var turnos = document.form1.turnos;
    var turnos_checked = false;
    for(var i = 0; i < dias_semana.length; i++)
        if(dias_semana[i].checked)
            dias_checked = true;
    for(var i = 0; i < turnos.length; i++)
        if(turnos[i].checked)
            turnos_checked = true;
    if(!cliente.value)
        alert("Escolher um cliente é obrigatório!");
    else
    if(!mes.value)
        alert("Digitar um mês é obrigatório!");
    else
    if(!ano.value)
        alert("Digitar um ano é obrigatório!");
    else
    if(!dias_checked)
        alert("Escolher ao menos um dia da semana é obrigatório!");
    else
    if(!turnos_checked)
        alert("Escolher ao menos um turno é obrigatório!");
    else
    if(confirm("Você tem certeza que deseja gerar a planilha agora?")){
        document.form1.action = "?cmd=gerarPlanilha";
        document.form1.submit();
    }
}
function salvaPlanilha(){
    if(confirm("Você tem certeza que deseja salvar a planilha agora?")){
        document.form1.action = "?cmd=beforeInsert";
        document.form1.submit();
    }
}
function copiaTotalFunc(turno,linhas,numCols){
	var valor_campo = document.getElementById('totalFunc'+turno+'_0').value;
    if(valor_campo)
        if(confirm("Deseja realmente copiar o conteúdo desta célula para as demais?")){
            for(var i = 1; i < linhas; i++){
                document.getElementById('totalFunc'+turno+'_'+i).value = valor_campo;
                mediaTotalFuncs(turno, linhas, numCols, i);
            }
        }
}
function copiaTotalTurma(turno,col,linhas,linha,numCols){
	var valor_campo = document.getElementById("tot"+turno+'_'+col+'_'+0).value;
    if(valor_campo)
        if(confirm("Deseja realmente copiar o conteúdo desta célula para as demais?")){
            for(var i = 1; i < linhas; i++){
                document.getElementById("tot"+turno+'_'+col+'_'+i).value = valor_campo;
                totalFuncTurno("tot"+turno+'_'+col+'_'+i,turno,col,i,numCols,linhas);
                if(i == linhas-1)
                    calculaCamposPlan(turno+"_"+col+"_"+linha,turno,col,linha,numCols,linhas);
            }
            mediaTotalFuncs(turno,linhas,numCols,linha);
        }
}
function totalFuncTurno(campo,turno,col,linha,numCols,linhas){
	var valor = document.getElementById(campo).value;
    var campoTotal = document.getElementById("totalFunc"+turno+"_"+linha);
    var valorTotal = 0;
    for(i = 0; i < numCols; i++){
        var nm_campo = "tot"+turno+"_"+i+"_"+linha;
        var vl = document.getElementById(nm_campo).value;
        if(vl)
            valorTotal = parseInt(vl,10) + valorTotal;
    //else
    //	document.getElementById(nm_campo).value = 0;
    }
    if(valorTotal != 0)
        campoTotal.value = valorTotal;
    calculaCamposPlan(turno+"_"+col+"_"+linha,turno,col,linha,numCols,linhas);
    mediaTotalFuncs(turno,linhas,numCols,linha);
}
function geraPlanilhaAfast(){
    var cliente = document.getElementById("id_usuario");
    var cnae = document.getElementById("cnae");
    var ini = document.getElementById("ini");
    var fim = document.getElementById("fim");
    var qtd_reg = document.getElementById("qtd_reg");
    if(!cliente.value){
        alert("Escolher uma empresa é obrigatório!");
        cliente.focus();
    }else
    if(!cnae.value){
        alert("Digitar um CNAE é obrigatório!");
        cnae.focus();
    }else
    if(!ini.value || !fim.value){
        alert("Digitar um período é obrigatório!");
        if(!fim.value)
            fim.focus();
        if(!ini.value)
            ini.focus();
    }else
    if(!qtd_reg.value){
        alert("Digitar uma quantidade de registros é obrigatório!");
        qtd_reg.focus();
    }else{
        if(confirm("Você tem certeza que deseja gerar a planilha agora?")){
            document.form1.action = "?cmd=gerarPlanilha";
            document.form1.submit();
        }
    }
}
function converteDiasHoras(linha){
    var dias = document.getElementById("3_"+linha)
    var horas =  document.getElementById("4_"+linha)
    var dias_horas = 0;
    if(dias){
        dias_horas = dias.value * 8;
        if(dias_horas)
            horas.value = dias_horas;
    }
}
function calculaMedia(linha){
	var dias = document.getElementById("3_"+linha)
    var horas =  document.getElementById("4_"+linha)
    var nPessoas =  document.getElementById("5_"+linha)
    //M?dia de dias ou horas
    var mediaDH =  document.getElementById("6_"+linha)
    var media = 0;
    if(horas){
        media = horas.value/nPessoas.value;
    }else
        if(dias)
            media = dias.value/nPessoas.value;
    if(media)
        mediaDH.value = media.toFixed(2);
}
function calculaCusto(linha,linhas){
    //M?dia de dias ou horas
    var mediaDH =  document.getElementById("6_"+linha)
    var valorHora =  document.getElementById("7_"+linha)
    var custo =  document.getElementById("8_"+linha)
    var custoTemp = mediaDH.value * valorHora.value;
    if(custoTemp){
        custo.value = "R$"+custoTemp.toFixed(2);
		calculaCustoTotal(linhas);
	}
}
function calculaCustoTotal(linhas){
	var valorTotal = 0;
	for(i = 0; i < linhas; i++){
		var mediaDH =  document.getElementById("6_"+i)
		var valorHora =  document.getElementById("7_"+i)
		var custo = mediaDH.value * valorHora.value;;
    	if(custo){
			valorTotal = parseFloat(custo)+valorTotal;
		}
	}
	document.getElementById("custoTotal").value = "R$"+valorTotal.toFixed(2);
}
function copiaPlanilha(){
    if(confirm("Você tem certeza que deseja criar uma cópia desta planilha com a data informada?")){
        var mes = document.getElementById("mes");
        var ano = document.getElementById("ano");
        var form = 	document.getElementById("form1");
        if(!mes.value){
            alert("Informar um mês é obrigatório!");
            mes.focus();
        }else
        if(!ano.value){
            alert("Informar um ano é obrigatório!");
            ano.focus();
        }else{
            if(mes.value < 1 || mes.value > 12){
                alert("Mês inválido!");
                mes.value = "";
                mes.focus();
            }
            else
            if(ano.value.length != 4){
                alert("Ano inválido!");
                ano.value = "";
                ano.focus();
            }else{
                form.action = "?cmd=copiaPlanilha";
                form.submit();
            }
        }
    }
}
function alteraPlanilha(){
   if((confirm("Você está certo de que deseja alterar esta planilha?")))
       document.form1.submit();

}
function salvaAdesao(tipo){
	if(confirm("Tem certeza que deseja salvar a planilha?")){
		if(tipo == 1){ 
			var index = 0;
		}
		else{ 
			var index = 1;
			var dados = "obs="+document.getElementById('obs').value+"&id_adesao="+document.getElementById('id_adesao').value;
		}
		var elementos = document.forms[index].elements.length; 
		for(var i = 0; i < elementos; i++){
			if(document.forms[index].elements[i].name != 'obs' && document.forms[index].elements[i].name != 'id_adesao')
				dados += "&"+document.forms[index].elements[i].name+"="+document.forms[index].elements[i].value;
		}
		criaRequest();
		if(tipo == 1){
			var url = "salvaAdesao.php?salvar=1";
		}else{
			var url = "salvaAdesao.php";
		}
		request.open("POST", url, true);
		request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
		request.onreadystatechange = carregaTeste;
		request.send(dados);
	}
}
function carregaTeste(){
	if(request.readyState == 4) {
		if(request.status ==200){
			alert(request.responseText);
		}else{
			alert("Não foi possível alterar a planilha! Tente novamente em alguns minutos. Se o problema persistir contate o administrador do sistema.");
		}
		document.getElementById("carregando").style.visibility = 'hidden';
	}
	else{
		document.getElementById("carregando").style.visibility = 'visible';
	}
}

function calculaPorcAvaliados(numAval,grupo,questao){
	var numAval = document.getElementById("numAvaliados"+numAval).value;
	var campo = document.getElementById("campo_"+grupo+"_"+questao);
	if(numAval && campo.value){
		var porc = document.getElementById("porc_"+grupo+"_"+questao);
		var calc = (campo.value*100)/numAval;
		porc.value = calc.toFixed(2);
	}
}
function calculaPorcAvaliados2(numAval,grupo,questao,col){
	var numAval = document.getElementById("numAvaliados"+numAval+"_"+col).value;
	var campo = document.getElementById("campo_"+grupo+"_"+questao+"_"+col);
	if(numAval && campo.value){
		var porc = document.getElementById("porc_"+grupo+"_"+questao+"_"+col);
		var calc = (campo.value*100)/numAval;
		porc.value = calc.toFixed(2);
	}
}
function atualizaAvaliacao(numAval){
	var todos_campos = document.getElementsByTagName('input');
	for (var i=0; i < todos_campos.length; i++){
		var el = todos_campos[i];
		var tempName = el.name.split('_');
		if((el.type == 'text') && (tempName[0] == 'campo') && (el.value)){
			calculaPorcAvaliados(numAval,tempName[1],tempName[2]); 
		}
	}

}

function atualizaReavaliacao(numAval){
	var todos_campos = document.getElementsByTagName('input');
	for (var i=0; i < todos_campos.length; i++){
		var el = todos_campos[i];
		var tempName = el.name.split('_');
		if((el.type == 'text') && (tempName[0] == 'campo') && (el.value)){
			calculaPorcAvaliados(numAval,tempName[1],tempName[2]); 
		}
	}

}
//Função para reavaliação
function atualizaReavaliacao(numAval,index){
	var flag = false;
	if(index == 999999) flag = true;
	var todos_campos = document.getElementsByTagName('input');
	for (var i=0; i < todos_campos.length; i++){
		var el = todos_campos[i];
		var tempName = el.name.split('_');
		if(flag){
			if((el.type == 'text') && (tempName[0] == 'campo') && (el.value)){
				calculaPorcReavaliados(numAval,index,tempName[1],tempName[2],flag); 
			}
		}else{
			if((el.type == 'text') && (tempName[0] == 'campo') && (el.value) && (tempName[3] == index)){
				calculaPorcReavaliados(numAval,index,tempName[1],tempName[2],flag); 
			}
		}
	}

}

function calculaPorcReavaliados(numAval,index,grupo,questao,flag){
	if(flag){
		var numAval = document.getElementById("numAvaliados"+numAval).value;
		var campo = document.getElementById("campo_"+grupo+"_"+questao);
	}else{
		var numAval = document.getElementById("numAvaliados"+numAval+"_"+index).value;
		var campo = document.getElementById("campo_"+grupo+"_"+questao+"_"+index);
	}
	if(numAval && campo.value){
		if(flag){
			var porc = document.getElementById("porc_"+grupo+"_"+questao);
		}else{
			var porc = document.getElementById("porc_"+grupo+"_"+questao+"_"+index);
		}
		var calc = (campo.value*100)/numAval;
		porc.value = calc.toFixed(2);
	}
}
function atualizaReavaliacaoGeral(numAval,qtdReaval){
	for(var a=0; a < qtdReaval; a++){
		atualizaReavaliacao(numAval,a);
	}
}
function salvarAvaliacao(){
	if(confirm("Tem certeza que deseja salvar a avaliação?")){
		document.formAvaliacao.submit();
	}
}

function salvarReavaliacao(){
	if(confirm("Tem certeza que deseja salvar a reavaliação?")){
		document.formAvaliacao.submit();
	}
}
function geraRelatorioAdesao(){
	var mesIni = document.getElementById("mesIni").value;
	var mesFim = document.getElementById("mesFim").value;
	var anoIni = document.getElementById("anoIni").value;
	var anoFim = document.getElementById("anoFim").value;
	var cliente = document.getElementById("id_usuario");

	var flag = false;
	if(cliente){
		if(!cliente.value){
			alert("Informar um cliente é obrigatório");
			flag = true;
		}
	}
	if(!mesIni && !flag){
		alert("Informar um mês inicial é obrigatório");
		flag = true;
	}
	if(!anoIni && !flag){
		alert("Informar um ano inicial é obrigatório");
		flag = true;
	}
	if(!mesFim && !flag){
		alert("Informar um mês final é obrigatório");
		flag = true;
	}
	if(!anoFim && !flag){
		alert("Informar um ano final é obrigatório");
		flag = true;
	}
	if(!flag){
		if(confirm("Tem certeza que deseja gerar o relatório?")){
			window.open("graficoAdesao.php?id_usuario="+cliente.value+"&mesIni="+mesIni+"&anoIni="+anoIni+"&mesFim="+mesFim+"&anoFim="+anoFim+"",'Relatório','width=900,height=1000');
			
			//window.open("_adesaoGerar.php?id_usuario="+cliente.value+"&mesIni="+mesIni+"&anoIni="+anoIni+"&mesFim="+mesFim+"&anoFim="+anoFim+"",'Relatório','width=800,height=400');
			//document.form1.action = "?cmd=gerarRelatorio";
			//document.form1.submit();
		}
	}
}
