// JavaScript Document
  $(document).ready(function(){   

//		
		$('.password-clear').show();
		$('.password-password').hide();
		
		$('.password-clear').focus(function() {
			$('.password-clear').hide();
			$('.password-password').show();
			$('.password-password').focus();
		});
		$('.password-password').blur(function() {
			if($('.password-password').val() == '') {
				$('.password-clear').show();
				$('.password-password').hide();
			}
		});

//
		$('.password2-clear').show();
		$('.password2-password').hide();
		
		$('.password2-clear').focus(function() {
			$('.password2-clear').hide();
			$('.password2-password').show();
			$('.password2-password').focus();
		});
		$('.password2-password').blur(function() {
			if($('.password2-password').val() == '') {
				$('.password2-clear').show();
				$('.password2-password').hide();
			}
		});
	

		//Abas
		$(".container_aba").hide();
		// mostra somente  a primeira aba
		$(".container_aba:first").show();
		// seta a primeira aba como selecionada (na lista de abas)
		$(".abas a:first").addClass("ativo");
		// quando clicar no link de uma aba
		$(".abas a").click(function(){
		// oculta todas as abas
		$(".container_aba").hide();
		// tira a seleção da aba atual
		$(".abas a").removeClass("ativo");
		// adiciona a classe selected na selecionada atualmente
		$(this).addClass("ativo");
		// mostra a aba clicada
		$($(this).attr("href")).show();
		// pra nao ir para o link
		return false;
		});
		//
		
		//box diversos
		 $(".box_g").before("<div class=box_g_abre>&nbsp;</\div>");
		 $(".box_g").after("<div class=box_g_fecha>&nbsp;</\div>");
		 $(".box_m").before("<div class=box_m_abre>&nbsp;</\div>");
		 $(".box_m").after("<div class=box_m_fecha>&nbsp;</\div>");
		 $(".box_p").before("<div class=box_p_abre>&nbsp;</\div>");
		 $(".box_p").after("<div class=box_p_fecha>&nbsp;</\div>");

		 $(".box").append("<div class=box_fecha>&nbsp;<\/div>");
		 $('.box span').toggle (function(){
					    $(this).addClass('on'),
						$(this).next().fadeOut('fast');
						 },
						 function () {
					    $(this).removeClass('on'),
						$(this).next().fadeIn('fast');

					  });

		

		//Formatação dos inputs e botoes
		$("#conteudo input:checkbox").addClass('checkbox');
		$("#conteudo input:radio").addClass('radio');
		$("#conteudo input:reset").addClass('reset');
		$("#conteudo input:submit").addClass('botsubmit');
		$("#conteudo input:submit, #conteudo input:button").wrap("<div class='container_submit'><\/div>"); 


		
		
//Efeito hover dos inputs
		$('textarea, #conteudo input:text, #conteudo input:password').focus (function() { 
													 $(this).addClass('focus');}).blur(function() { $(this).removeClass('focus');  
					            }); 
         
		 $('#conteudo input:text').addClass('inputtext');	
			
		//Caixa abre e fecha	
		if(!$(".caixa_abre_fecha dt").children().not(".titulo").is("span")){
		
			$(".caixa_abre_fecha dt").prepend("<span class=abre> + <\/span>") 		
		}
		$(".caixa_abre_fecha").find("dd").hide();
		$(".caixa_abre_fecha").find("dt").toggle(function(){
			$(this).next().fadeIn("normal");	
			$(this).find("span").not(".titulo").remove();
			$(this).addClass('ativo');
			$(this).prepend("<span class=fecha> - <\/span>");
				
			}, function() {
				
				$(this).next().fadeOut("fast");
				$(this).removeClass('ativo');
				$(this).find("span").not(".titulo").remove();	
				$(this).prepend("<span class=abre> + <\/span>");
		});
		//

		  
		$("#campo_busca").focus(function(){
							$(".form_erro").fadeOut("slow");
							  });
	
		 $("#box_erro").click(function() {
					$("#box_erro").fadeOut("fast"),
					$("#erro").empty();
			   });
		 
		 $(".janela").before("<span class=fecha_box title=Fechar>Fechar</\span>");
		 
		 $(".fecha_box").click(function() {
					$(this).next().fadeOut("fast"),
					$(this).remove();
								});



		 $(".recomenda").click(function() {
					$("#recomenda").append('<iframe src="recomenda.asp" frameborder="0" scrolling="no" name="winrecomenda" id="winrecomenda"><\/iframe>'),
					$("#recomenda").fadeIn("slow");
					$("#recomenda .fechar").show();					
					});
		  $("#recomenda .fechar").click(function() {
					$(this).hide();							 
					$("#recomenda").fadeOut("fast"),
					$("#recomenda iframe").remove();
					});

		//$(".comente").click(function() {
				//	$("#formcomentarios").fadeIn();
				//	});
		
	 $(".comente").toggle(function() {
			$("#formcomentarios").fadeIn("slow");},						
		 function() {
			$("#formcomentarios").fadeOut("fast");
								});

		$("#semcoment").click(function() {
					$(this).hide();		   
					$("#formcomentarios").fadeIn();
					});

		 $(".pagina table").addClass("especial2");
		 $(".especial2 tr:odd").addClass("alt");
		 
		 $(".soumedico").click(function(event) {
			$(".acesso").hide(),
			$("#form_paciente").hide(),
			$("#form_login").fadeIn('slow');
			});
		 $(".soupaciente").click(function(event) {
			$(".acesso").hide(),
			$("#form_login").hide(),
			$("#form_paciente").fadeIn('slow');
			});
		 $(".acessovolta").click(function(event) {
			$("#form_paciente").hide(),
			$("#form_login").hide(),
			$(".acesso").fadeIn('medium');
			});

		 

});
//
function valida_busca() { //v4.0
  if (document.form_busca.txt_busca.value=='') {
		//alert('Você deve digitar uma palavra para realizar sua busca');
		$(".form_erro").fadeIn("slow");
		} else {
	document.form_busca.submit();
	}
}



// validação geral
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 sizeFont2 (elem, acao)
{
    // tamanho inicial da fonte (em px)
    var tamInic = 13;
    
    // Tamanho mínimo da fonte (em px)
    var tamMin = 11;
    
    // Tamanho máximo da fonte (em px)
    var tamMax = 22;

    // Pega o tamanho da fonte. Se não foi setada ainda (primeira vez
    // que a função é executada) terá como tamanho padrão 'tamInic'.
    if (document.getElementById(elem).style.fontSize == "") 
      var tamFonte = tamInic;
    else
      var tamFonte = parseInt(document.getElementById(elem).style.fontSize);
    switch (acao)
    {
      // Aumenta o tamanho, enquanto foi menor que 'tamMax'
      case '+':
        if (tamFonte < tamMax)
          document.getElementById(elem).style.fontSize = (tamFonte + 2) + "px";
      break;
      
      // Diminui o tamanbo, enquanto for maior que 'tamMin'
      case '-':
        if (tamFonte > tamMin)
          document.getElementById(elem).style.fontSize = (tamFonte - 2) + "px";
      break;
    }
}

//======= funcoes calculadoras
function Arredonda(valor , casas){	
  var novo = Math.round(valor * Math.pow(10, casas)) / Math.pow(10 ,casas);
  return(novo);
}

function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

function calcula_imc() {
	var peso       = document.getElementById("peso").value;
	var metro      = document.getElementById("metro").value;
	var centimetro = document.getElementById("centimetro").value;
	var altura     = 0;
	var resultado  = 0;
	var selLinha   = "";
	
	if((!isFinite(peso)) || (!isFinite(metro)) || (!isFinite(centimetro))) {
		//alert("Por favor, digite os valores do peso e da altura.");
    $("#erro").append ('<a class="fechar">Fechar<\/a><strong>Atenção!<\/strong> Por favor, digite os valores corretos referentes ao seu peso e altura.'),
  	$("#box_erro").fadeIn("fast");
		return;
	}
	
	altura    = parseInt(metro) + (parseInt(centimetro) / 100);
	resultado = Arredonda(peso / (Math.pow(altura, 2)), 1);
	
	if (resultado < 16) selLinha = "magreza3"
	else if ((resultado >= 16) && (resultado <= 16.9)) selLinha = "magreza2"
	else if ((resultado >= 17) && (resultado <= 18.4)) selLinha = "magreza1"
	else if ((resultado >= 18.5) && (resultado <= 24.9)) selLinha = "eutrofia"
	else if ((resultado >= 25) && (resultado <= 29.9)) selLinha = "preobeso"
	else if ((resultado >= 30) && (resultado <= 34.9)) selLinha = "obeso1"
	else if ((resultado >= 35) && (resultado <= 39.9)) selLinha = "obeso2"
	else if (resultado >= 40) selLinha = "obeso3";
	
	document.getElementById(selLinha).className="linhaSelecionada";
	
	document.getElementById("resultado").innerHTML = resultado;
}

function calcula_mdrd() {
	/* formula utilizada para calculo:
			MDRD: 186.3 * (creatinina elevado a -1.154) * ( idade elevado a -0.203)
			Se for de cor Negra multiplica o resultado por 1,21
			Se for Mulher multiplica o resultado por 0,742
	*/
	
	//===== constantes
	var fatorMDRD       = 186.3;
	var fatorCreatinina = -1.154;
	var fatorIdade      = -0.203;
	var fatorNegra      = 1.21;
	var fatorFeminino   = 0.742;
	
	var sCreatinina = new String(document.getElementById("creatinina").value);
	var creatinina  = sCreatinina.replace(',', '.');
	var idade       = document.getElementById("idade").value;
	var sexo        = getCheckedValue(document.forms['formMDRD'].elements['sexo']);
	var cor         = getCheckedValue(document.forms['formMDRD'].elements['cor']);
	var resultado   = 0;
	
	resultado = fatorMDRD * (Math.pow(creatinina, fatorCreatinina)) * (Math.pow(idade, fatorIdade));
	
	if (sexo=="F") resultado = resultado * fatorFeminino;
	if (cor=="N") resultado = resultado * fatorNegra;
	
	document.getElementById("resultado").innerHTML = Arredonda(resultado, 1);
}

function calcula_cce() {
	/*formula utilizada para calculo:
		Cockroft:   ((140 - idade) * Peso) / (creatinina * 72) e se for mulher este resultado deve ser multiplicado por 0,85
	*/
	
	//===== constantes
	var fatorCreatinina = 72;
	var fatorIdade      = 140;
	var fatorFeminino   = 0.85;
	
	var sCreatinina = new String(document.getElementById("creatinina").value);
	var creatinina  = sCreatinina.replace(',', '.');
	var sPeso       = new String(document.getElementById("peso").value);
	var peso        = sPeso.replace(',', '.');
	var idade       = document.getElementById("idade").value;
	var sexo        = getCheckedValue(document.forms['formCCE'].elements['sexo']);
	var resultado   = 0;

	resultado = ((fatorIdade - idade) * peso) / (creatinina * fatorCreatinina);
	
	if (sexo=="F") resultado = resultado * fatorFeminino;
	
	document.getElementById("resultado").innerHTML = Arredonda(resultado, 1);
}

//
	function f(e){
	var e = e || event;
	var k = e.keyCode || e.which;
	if (k==13) { document.form_login.submit(); }
	}

	function p(e){
	var e = e || event;
	var k = e.keyCode || e.which;
	if (k==13) { document.form_paciente.submit(); }
	}


function MM_validateForm() { //v4.0
  var i,p,q,nm,nc,test,num,min,max,errors='',args=MM_validateForm.arguments;
  for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);
    if (val) { nm=val.name; nc=val.title; if ((val=val.value)!="") {
      if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
        if (p<1 || p==(val.length-1)) errors+='<br\/>- O <u>'+nc+'<\/u> deve ser um endereço válido.<\/br>\n';
      } else if (test!='R') { num = parseFloat(val);
        if (isNaN(val)) errors+='<br\/>- <u>'+nc+'<\/u> deve conter apenas números.\n';
        if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
          min=test.substring(8,p); max=test.substring(p+1);
          if (num<min || max<num) errors+='<br\/>- <u>'+nc+'<\/u> deve conter um número entre '+min+' e '+max+'.\n';
    } } } else if (test.charAt(0) == 'R') errors += '<br\/>- <u>'+nc+'<\/u> é obrigatório.\n'; }
  } if (errors)
  	$("#erro").empty(),
	$("#box_erro").hide(),
    $("#erro").append ('<a class="fechar">Fechar<\/a><strong>Atenção!<\/strong> Preencha corretamente o formulário:<br\/>\n'+errors+'\n'),
  	$("#box_erro").fadeIn("fast");
	
  document.MM_returnValue = (errors == '');

}
