/////////////////////////////////

// Determina o browser usado

/////////////////////////////////

isIE=document.all;

isNN=!document.all&&document.getElementById;

isN4=document.layers;

//////////////////////////////////////////////////////////////////

// Aguarda o evento para executar a função doSomething

//////////////////////////////////////////////////////////////////

if (isIE||isNN){

	document.onmousedown=doSomething;

}

else{

	document.captureEvents(Event.MOUSEDOWN || Event.MOUSEUP);

	document.onmouseup=doSomething;

}

function nocontextmenu(e){

	e.cancelBubble = true, e.returnValue = false;

	return false;

}

//////////////////////////////////////////////////////////////////

// Função que abre o menu alternativo

//

// @param e (evento) - evento do clique do mouse

//

//////////////////////////////////////////////////////////////////

function doSomething(e)

{

	var posx = 0;

	var posy = 0;

	var div = document.getElementById('tempmenu');

	var vis;

	if (!e)

		var e = window.event;



	if (e.pageX || e.pageY)

	{

		posx = e.pageX;

		posy = e.pageY;

	}

	else if (e.clientX || e.clientY)

	{

		posx = e.clientX + document.body.scrollLeft;

		posy = e.clientY + document.body.scrollTop;

	}

	if (e.which == 3)

		vis = 'visible';

	else if (e.which == 1)

		vis = 'hidden';

	else if (e.button == 2)

		vis = 'visible';

	else if (e.button == 1)

		vis = 'hidden';

	if (!vis) {

		vis = 'visible';

	}



	if (vis == 'visible') {

		nocontextmenu(e);

		MenuPrincipal.moveTo(posx, posy);

		MenuPrincipal.show();

		return true;

	}

	else {

		setTimeout('MenuPrincipal.moveTo(0, 0)', 100);

		setTimeout('MenuPrincipal.hide()', 100);

		return true;

	}

}

////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////



////////////////////////////////////////////////////////////////////////////////////

// Função que determina a visibilidade de determinado objeto

//

// @param objeto (objeto) -> o objeto que deseja aplicar a visibilidade

//

////////////////////////////////////////////////////////////////////////////////////

function visibilidade(objeto) {



	var obj = document.getElementById(objeto);



	if (obj.style.display == 'block'){

		obj.style.display = 'none';

		return 0;

	}

	else {

		obj.style.display = 'block';

		return 1;

	}

}

////////////////////////////////////////////////////////////////////////////////////

// Função que marca ou desmarca todos os checkboxes de determinada tabela

//

// @param idcat (string) -> ID da tabela que contem os checkboxes

// @param cat (objeto) -> o checkbox que chama a função

//

////////////////////////////////////////////////////////////////////////////////////

function checacat(idcat, cat) {

	table = document.getElementById(idcat);

	inputs = table.getElementsByTagName('input');

	var checkboxes = new Array();

	for (i = 0; i < inputs.length; i++)

	{

	  if (!inputs[i].length)

	  {

		if (inputs[i].type == 'checkbox')

		  checkboxes[checkboxes.length] = inputs[i];

	  } else

	  {

		for(k = 0; k < inputs[i].length; k++)

		{

		  if (inputs[i][k].type == 'checkbox')

			checkboxes[checkboxes.length] = inputs[i];

		}

	  }

	}



	// checkboxes now is an array of all checkboxes

	// in the table with id "mytablesid".  Now perform some

	// action on the checkboxes.  In this case, check

	// them all.



	for (i = 0; i < checkboxes.length; i++)

	  checkboxes[i].checked = cat.checked;

}

//////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////





//////////////////////////////////////////////////////////

// Envia um alerta com confirmação de exclusão de registro

//

// @param endereco (string) -> pagina para onde vai ser enviado

// @param dados (string) -> informações que serão enviadas para o endereço

//

//////////////////////////////////////////////////////////

function exclui(endereco, dados) {

	if(confirm("Deseja excluir este registro?")){

		window.location = "principal.php?centro="+endereco+"&dados="+dados;

	}

}



////////////////////////////////////////////////////////////////////////////////////

// Seta a classe de estilo 'obrigatorio' para os campos de preenchimento obrigatório

//

// @param obrigatorio (array) -> array com o nome dos campos obrigatórios

// @param form (form) -> o formulário onde estão os campos

// @param classe (string) -> a classe que será aplicada

//

////////////////////////////////////////////////////////////////////////////////////

function ColoreObrigatorio(obrigatorio, form, classe) {



	for (var i = 0; i < obrigatorio.length; i++) {

		form.elements[obrigatorio[i]].className = classe;

	}



}



////////////////////////////////////////////////////////////////////////////////////

// Seta a classe de estilo 'obrigatorio' para os campos de preenchimento obrigatório

//

// @param obrigatorio (array) -> array com o nome dos campos obrigatórios

// @param form (form) -> o formulário onde estão os campos

//

// @return (bool) -> retorna false se algum campo estiver em branco

//

////////////////////////////////////////////////////////////////////////////////////

function checaObrigatorio(obrigatorio, form) {

	var erro = new Array();

	ColoreObrigatorio(obrigatorio, form, 'obrigatorio');





	for (var i = 0; i < obrigatorio.length; i++) {

		if (form.elements[obrigatorio[i]].value == "") {

			 erro.push(obrigatorio[i]);

		}

	}

	if (erro.length > 0) {

		ColoreObrigatorio(erro, form, 'erro');

		alert('Os campos com (*) precisam ser preenchidos');

		return false;

	}







}












////////////////////////////////////////
///obrigatório sem data

function checaObrigatorioSemData(obrigatorio, form) {

	var erro = new Array();

	ColoreObrigatorio(obrigatorio, form, 'obrigatorio');





	for (var i = 0; i < obrigatorio.length; i++) {

		if (form.elements[obrigatorio[i]].value == "") {

			 erro.push(obrigatorio[i]);

		}

	}

	if (erro.length > 0) {

		ColoreObrigatorio(erro, form, 'erro');

		alert('Os campos em destaque precisam ser preenchidos');

		return false;

    }else {

		return true;

	}



}
////////////////////////////////////////////////////////////////////////////
//
///
//
// obrigatorio para vincular pessoa ao seu responsavel
//
//
//
//
/////////////////////////////////////////////////////////////////////////////

function checaObrigatorio_v(obrigatorio_v, form) {

	var erro = new Array();


	for (var i = 0; i < obrigatorio_v.length; i++) {

		if (form.elements[obrigatorio_v[i]].value == "") {

			 erro.push(obrigatorio_v[i]);

		}

	}

	if (erro.length > 0) {

      alert('O campo vínculo precisa ser preenchido e uma pessoa tem que ser selecionada');

		return false;

	}



}



////////////////////////////////////////////////////////////////////////////////////

// Funções de máscara para campos como CPF, CNPJ, data

//

// @param objeto (objeto) -> referencia um campo input

// @param e (event) -> o evento do clique

//

////////////////////////////////////////////////////////////////////////////////////


function mascaracpf(objeto, e){

	if (checkkey(e) == 1) {

		return false;

	}

	else if(checkkey(e) == 0){

		campo = eval(objeto);

		if((campo.value.length == 3) || (campo.value.length == 7))

			campo.value = campo.value+'.';

		if(campo.value.length == 11)

			campo.value = campo.value+'-';

	}

}



function mascaracnpj(objeto, e){

	if (checkkey(e) == 1) {

		return false;

	}

	else if(checkkey(e) == 0){

		campo = eval(objeto);

		if((campo.value.length == 2) || (campo.value.length == 6))

			campo.value = campo.value+'.';

		if(campo.value.length == 10)

			campo.value = campo.value+'/';

		if(campo.value.length == 15)

			campo.value = campo.value+'-';

	}

}



function isnumero(e) {

	if (checkkey(e) == 1) {

		return false;

	}

	else {

		return true;

	}

}



function checkkey(e) {

	var keychar;

	var key;

	if (window.event)

	   key = window.event.keyCode;

	else if (e)

	   key = e.which;

	else

	   return true;

	keychar = String.fromCharCode(key);

	// control keys

	if ( (key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27) ) {

	   e.key;

	   return 2;

	}

   	else if ((("0123456789").indexOf(keychar) <= -1))

		return 1;

	else

		return 0;

}



////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////



////////////////////////////////////////////////////////////////////////////////////

// Função que seleciona um item de um select de acordo com o valor passado

//

// @param objeto (objeto) -> referencia o campo select

// @param texto (string) -> o texto que vai ser procurado dentro do select

//

////////////////////////////////////////////////////////////////////////////////////

function checkSelect(objeto, texto) {



	for (var i = 0; i < objeto.length; i++){

		if (objeto.options[i].value == texto){

			objeto.options[i].selected = true;

		}

	}

}



////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////





////////////////////////////////////////////////////////////////////////////////////

// Descrição da função

//

// @param ativo (bool) -> identifica se está listando usuários ativos ou inativos

// @param ativar (bool) -> indica qual ação tomar (ativar ou desativar)

// @param dados (string) -> passa os dados do usuário (idusuario criptografado)

// @param erro (string) -> passa uma mensagem de erro se estiver ativando um usuário

//

////////////////////////////////////////////////////////////////////////////////////

function confirmaAtivo(ativo, ativar, dados, erro){

	if(ativo == "TRUE"){

		ativo = "desativar";

	}

	else{

		ativo = "ativar";

	}

	var resp = confirm('Deseja realmente '+ativo+' este usuário?');

	if(resp){

		if(ativo == "desativar")

			window.location = 'principal.php?centro=usuario/excluiusuario&dados='+dados+'&ativar='+ativar;

		else

			window.location = 'principal.php?centro=usuario/alterausuario&dados='+dados+'&ativar='+ativar+'&erro='+erro;

	}

}

////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////



////////////////////////////////////////////////////////////////////////////////////

// Checa se o formulário tem pelo menos um campo preenchido

//

// @param form (object) -> formulário a ser checado

//

////////////////////////////////////////////////////////////////////////////////////

function checaBuscaCEP(form) {

	if (form.bairro.value == "" && form.regiao.value == "" && form.logradouro.value == "") {

		alert("Você precisa selecionar pelo menos um campo diferente de 'Tipo'");

		return false;

	}

	else {

		return true;

	}

}



////////////////////////////////////////////////////////////////////////////////////

// Muda a imagem do projeto e dá visibilidade à tabela daquele beneficiado

//

// @param id (int) -> id da tabela e da imagem a ser modificada

//

////////////////////////////////////////////////////////////////////////////////////

function projetoBeneficiado(id) {

	var check = visibilidade('tb'+id);



	if (check == 1) {

		document.getElementById('img'+id).src = 'img/projetoup.gif';

	}

	else {

		document.getElementById('img'+id).src = 'img/projetodown.gif';

	}

}



////////////////////////////////////////////////////////////////////////////////////

// Muda a imagem do projeto e dá visibilidade à tabela daquele beneficiado

//

// @param id (int) -> id da tabela e da imagem a ser modificada

//

////////////////////////////////////////////////////////////////////////////////////

function turmaUnidade(id) {

	var check = visibilidade('tb'+id);



	if (check == 1) {

		document.getElementById('img'+id).src = 'img/turmaup.gif';

	}

	else {

		document.getElementById('img'+id).src = 'img/turmadown.gif';

	}

}





function checkAtendimento(form) {

	var tcheck = false;

	for (i = 0; i < form.idturma.length; i++){

		if (form.idturma[i].checked==true && form.idturma[i].value!="") {

		   //alert(form.idturma[i].checked);

		   tcheck = true;

		}

	}



	if (tcheck==false) {

		alert('Selecione uma turma');

		return false;

	}

	if (form.idsolicitacao.value=='') {

		alert('Selecione uma solicitação');

		return false;

	}

	else {

		return true;

	}

}



function janela(mypage, myname, w, h) {

   var winl = (screen.width - w) / 2;

   var wint = (screen.height - h) / 2;

   winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars=YES,noresizable,status=yes, location=no, toolbar=no, menubar=no';

   win = window.open(mypage, myname, winprops)

}



function doAprovaSolicitacao(campo) {

	dados = getRadioSelected(campo);

	janela("projeto/checksolicitacao.php?dados="+dados , "CHECK_SOLICITACAO",  300, 200);

}



function fichaIndividual(dados) {

	janela("composicao/fichaindividual.php?dados="+dados , "FICHA_INDIVIDUAL",  700, 500);

}



function protocoloSolicitacao(dados) {

	janela("solicitacao/protocolo.php?dados="+dados , "PROTOCOLO",  400, 200);

}



/////////////////////////////////////////////////////////

// Função que pega o valor selecionado em um campo radio

/////////////////////////////////////////////////////////



function getRadioSelected(campo) {

	var user_input = "";



	for (i = 0; i < campo.length; i++) {

		if (campo[i].checked) {

			user_input = campo[i].value;

		}

	}



	return user_input;

}



////////////////////////////////////////////////////////////

// Função para onchange da combo de unidade nos relatórios

////////////////////////////////////////////////////////////



function Unidade(object) {

  alert("estou aqui !!!!")

}





////////////////////////////////////////////////////////////

// Função para validar campos moeda

////////////////////////////////////////////////////////////



function MascaraMoeda(objTextBox, SeparadorMilesimo, SeparadorDecimal, 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;

    key = String.fromCharCode(whichCode); // Valor para o código da Chave

    if (strCheck.indexOf(key) == -1) return false; // Chave inválida

    len = objTextBox.value.length;

    for(i = 0; i < len; i++)

        if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) break;

    aux = '';

    for(; i < len; i++)

        if (strCheck.indexOf(objTextBox.value.charAt(i))!=-1) aux += objTextBox.value.charAt(i);

    aux += key;

    len = aux.length;

    if (len == 0) objTextBox.value = '';

    if (len == 1) objTextBox.value = '0'+ SeparadorDecimal + '0' + aux;

    if (len == 2) objTextBox.value = '0'+ SeparadorDecimal + aux;

    if (len > 2) {

        aux2 = '';

        for (j = 0, i = len - 3; i >= 0; i--) {

            if (j == 3) {

                aux2 += SeparadorMilesimo;

                j = 0;

            }

            aux2 += aux.charAt(i);

            j++;

        }

        objTextBox.value = '';

        len2 = aux2.length;

        for (i = len2 - 1; i >= 0; i--)

        objTextBox.value += aux2.charAt(i);

        objTextBox.value += SeparadorDecimal + aux. substr(len - 2, len);

    }

    return false;

}



////////////////////////////////////////////////////////////

// Função para formatar data

////////////////////////////////////////////////////////////



function FormataData(campo,teclapres,tamanho,formul) {

		itamanho = parseInt(tamanho,10);

		var tecla = teclapres.keyCode;

		vr = formul[campo].value;

		if (tecla < 48 || tecla > 57 ) {

		   teclapres.keyCode = 00;

		}

		else {

		     tam = vr.length;

		     if (tam < itamanho) {

		        vr = vr + String.fromCharCode(tecla);

		        tam ++;

		        vr = vr.replace( ".", "" );

		        vr = vr.replace( "/", "" );

		        vr = vr.replace( "/", "" );

		if ( tam > 2 && tam < 5 ) {

		vr = vr.substr( 0, tam - 2 ) + '/' + vr.substr( tam - 2, tam );

		}

		if ( tam >= 5 && tam <= 10 ) {

		vr = vr.substr( 0, 2 ) + '/' + vr.substr( 2, 2 ) + '/' + vr.substr( 4, 4 );

		}

		formul[campo].value = vr;

		}

		teclapres.keyCode = 00;

		}

}

