﻿
function retiraNome(field){ 
    if(field.value==field.defaultValue){ 
        field.style.color = "#000000"; 
        field.value=""; 
    } 
} 
function voltaNome(field){ 
    if(field.value==""){ 
        field.value=field.defaultValue; 
        field.style.color = "#666666"; 
    } 
} 	                


function Excluir(caminho,desc_nome,id,tabela,campo_tabela,op,urlRetorno){
    if(window.confirm("Confirma a exclusao do exame "+desc_nome))
      {
       location.href = caminho+"?id="+id+"&tabela="+tabela+"&campo_tabela="+campo_tabela+"&urlRetorno="+urlRetorno+"&op="+op;
      } 
} // Fim da Função 

function vai (url){
  location.href = url;
}

function msgRetorno (msg,url){
  if (msg)
 	 alert(msg);		
  location.replace(url);
}

function number_format (number, decimals, dec_point, thousands_sep){
  var exponent = "";
  var numberstr = number.toString ();
  var eindex = numberstr.indexOf ("e");
  if (eindex > -1)
  {
    exponent = numberstr.substring (eindex);
    number = parseFloat (numberstr.substring (0, eindex));
  }
  
  if (decimals != null)
  {
    var temp = Math.pow (10, decimals);
    number = Math.round (number * temp) / temp;
  }
  var sign = number < 0 ? "-" : "";
  var integer = (number > 0 ? 
      Math.floor (number) : Math.abs (Math.ceil (number))).toString ();
  
  var fractional = number.toString ().substring (integer.length + sign.length);
  dec_point = dec_point != null ? dec_point : ".";
  fractional = decimals != null && decimals > 0 || fractional.length > 1 ? 
               (dec_point + fractional.substring (1)) : "";
  if (decimals != null && decimals > 0)
  {
    for (i = fractional.length - 1, z = decimals; i < z; ++i)
      fractional += "0";
  }
  
  thousands_sep = (thousands_sep != dec_point || fractional.length == 0) ? 
                  thousands_sep : null;
  if (thousands_sep != null && thousands_sep != "")
  {
	for (i = integer.length - 3; i > 0; i -= 3)
      integer = integer.substring (0 , i) + thousands_sep + integer.substring (i);
  }
  
  return sign + integer + fractional + exponent;
}

//Formata número tipo moeda usando o evento onKeyDown
function Formata(campo,tammax,teclapres,decimal){
   var tecla = teclapres.keyCode;
   vr = Limpar(campo.value,"0123456789");
   tam = vr.length;
   dec = decimal;
   if(tam < tammax && tecla != 8){
      tam = vr.length + 1 ;
   }
   if(tecla == 8 ){
      tam = tam - 1 ;
   }
   if( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105){
      if ( tam <= dec ){
         campo.value = vr ;
      }
      if((tam > dec) && (tam <= 5)){
         campo.value = vr.substr( 0, tam - 2 ) + "," + vr.substr( tam - dec, tam ) ;
      }
      if((tam >= 6) && (tam <= 8)){
         campo.value = vr.substr( 0, tam - 5 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ;
      }
      if((tam >= 9) && (tam <= 11)){
         campo.value = vr.substr( 0, tam - 8 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ;
      }
      if((tam >= 12) && (tam <= 14)){
         campo.value = vr.substr( 0, tam - 11 ) + "." + vr.substr( tam - 11, 3 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ;
      }
      if((tam >= 15) && (tam <= 17)){
         campo.value = vr.substr( 0, tam - 14 ) + "." + vr.substr( tam - 14, 3 ) + "." + vr.substr( tam - 11, 3 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - 2, tam ) ;
      }
   }
}

function checkEmail(email)
{
   if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)) || !email) 
     return false;
   else 
     return true;
}


function FormataCNPJ(Campo, teclapres){

   var tecla = teclapres.keyCode;
   var vr = new String(Campo.value);
   vr = vr.replace(".", "");
   vr = vr.replace(".", "");
   vr = vr.replace("/", "");
   vr = vr.replace("-", "");

   tam = vr.length + 1 ;
   
   if (tecla != 9 && tecla != 8){
      if (tam > 2 && tam < 6)
         Campo.value = vr.substr(0, 2) + '.' + vr.substr(2, tam);
      if (tam >= 6 && tam < 9)
         Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,tam-5);
      if (tam >= 9 && tam < 13)
         Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,3) + '/' + vr.substr(8,tam-8);
      if (tam >= 13 && tam < 15)
         Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,3) + '/' + vr.substr(8,4)+ '-' + vr.substr(12,tam-12);
      }
 //Chama a função Bloqueia_Caracteres para só permitir a digitação de números
	return Bloqueia_Caracteres(teclapres);  
}

function janelaCenter(url, nome, parms, width, height) {
 	var str = "height=" + height + ",innerHeight=" + height;
	str += ",width=" + width + ",innerWidth=" + width;
	if (parms != "") {
		str += ", " + parms;
	}
	if (window.screen) {
		var ah = screen.availHeight - 30;
		var aw = screen.availWidth - 10;
		var xc = (aw - width) / 2;
		var yc = (ah - height) / 2;

	} else {
		var xc = 0, xy = 0;
	}
	str += ",left=" + xc + ",screenX=" + xc;
	str += ",top=" + yc + ",screenY=" + yc;
	hwnd = window.open(url, nome, str);
	if(hwnd.window.focus){hwnd.window.focus();}
//	if(text != "") hwnd.document.write(text);
//	hwnd.document.close();
	return hwnd;
}

function valida_camposArray(campo,nome){
  var d = document;
  for (var i = 0;i<campo.length; i++){
    var vlrCampo = d.getElementById(campo[i]).value; 
    if (vlrCampo == ""  || vlrCampo == 0){
		alert ("Campo "+nome[i]+" esta em branco!");
		d.getElementById(campo[i]).focus();
		return false;
    }
  }
  return true;
}

// Fechar Janela 
function fechaJanela(){
	top.window.close();
}

/*funcao para redirecionar*/
function MM_jumpMenu(targ,selObj,restore){
  eval("window.location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}

function voltar(){
   history.back();
}

function fechaJanela(){
  top.window.close();
}

function Envia(){
  var d = document.forms[0];
  d.submit();
}

// Codificar Strings

function url_encode(str) {  
        var hex_chars = "0123456789ABCDEF";  
        var noEncode = /^([a-zA-Z0-9\_\-\.])$/;  
        var n, strCode, hex1, hex2, strEncode = "";  

        for(n = 0; n < str.length; n++) {  
            if (noEncode.test(str.charAt(n))) {  
                strEncode += str.charAt(n);  
            } else {  
                strCode = str.charCodeAt(n);  
                hex1 = hex_chars.charAt(Math.floor(strCode / 16));  
                hex2 = hex_chars.charAt(strCode % 16);  
                strEncode += "%" + (hex1 + hex2);  
            }  
        }  
	return strEncode;  
}  

// Descodificar String 

function url_decode(str) {  
	var n, strCode, strDecode = "";  

	for (n = 0; n < str.length; n++) {  
		if (str.charAt(n) == "%") 
		{  
			strCode = str.charAt(n + 1) + str.charAt(n + 2);  
			strDecode += String.fromCharCode(parseInt(strCode, 16));  
			n += 2;  
		} 
		else 
		{  
			strDecode += str.charAt(n);  
		}  
	}  

	return strDecode;  
} 

function saltaCampo(prox,teclapres){
    var tecla = teclapres.keyCode ? teclapres.keyCode : teclapres.which ? teclapres.which : teclapres.charCode;
	if (tecla == 13){
	  document.getElementById(prox).select(); //se não quiser o foco, desabilite!
	  document.getElementById(prox).focus();
	}
}

// Primeira letra maiuscula 
function primeiraLetraMaiuscula(str) {
	str1 = str.substring(0,1);
	str  = str.replace(str1, str1.toUpperCase());
	return str;
}

function validar_data(campo){
	var expReg = /^(([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/[1-2][0-9]\d{2})$/;
	if ((campo.match(expReg)) && (campo!='')){
		var dia = campo.substring(0,2);
		var mes = campo.substring(3,5);
		var ano = campo.substring(6,10);

		if((mes==4 || mes==6 || mes==9 || mes==11) && dia > 30){
			return false;
		} else{
			if(ano%4!=0 && mes==2 && dia>28){
				return false;
			} else{
				if(ano%4==0 && mes==2 && dia>29){
					return false;
				} else{	
					return true;
				}
			}
		}
	} else {
		return false;
	}
}

function deleteRegistro(descricao, codigo){
	if(window.confirm('Tem certeza de que deseja excluir o registro: '+descricao+' ?')){
		$.ajax({
			url 		: 'actions/deletar.php',
			data		: 'act=1&uId='+codigo,
			dataType	: "text",
			success: function(xml)
			{
				//alert (xml)
				location.reload();
			}		
		});
	}
}

function valida_estado(estado){
	var estados = new Array('AC','AL','AP','AM','BA','DF','CE','ES','GO','MA','MT','MS','MG','PB','PR','PA','PE','PI','RJ','RN','RS','RO','RR','SC','SP','SE','TO');
	for (var i = 0; i < estados.length; i++){
		if (estados[i] == estado.toUpperCase()){
			return true;
		}
	}
	return false;
}


function validaCPF(cpf){
	erro = new String;
	
	cpf = cpf.replace('.', '');
	cpf = cpf.replace('.', '');
	cpf = cpf.replace('-', '');

	if (cpf.length == 11){    
		var nonNumbers = /\D/;
		if (cpf == "00000000000" || 
				cpf == "11111111111" || 
				cpf == "22222222222" || 
				cpf == "33333333333" || 
				cpf == "44444444444" || 
				cpf == "55555555555" || 
				cpf == "66666666666" || 
				cpf == "77777777777" || 
				cpf == "88888888888" || 
				cpf == "99999999999") {
				
				return false;
		}
	
		var a = [];
		var b = new Number;
		var c = 11;
	
		for (i=0; i<11; i++){
				a[i] = cpf.charAt(i);
				if (i < 9) b += (a[i] * --c);
		}
	
		if ((x = b % 11) < 2) { a[9] = 0 } else { a[9] = 11-x }
		b = 0;
		c = 11;
	
		for (y=0; y<10; y++) b += (a[y] * c--); 
	
		if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }
	
		if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10])) {
			return false;
		}
	} else 
		return false;
	
    return true;    
}

function validaCNPJ(cnpj){
	var cnpj = cnpj.replace(".","").replace(".","").replace("-","").replace("/","");
	var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais;
	digitos_iguais = 1;
	
	if (cnpj.length < 14 && cnpj.length < 15)
		return false;
		
	for (i = 0; i < cnpj.length - 1; i++)
		if (cnpj.charAt(i) != cnpj.charAt(i + 1)){
			  digitos_iguais = 0;
			  break;
		}
		if (!digitos_iguais){
			tamanho = cnpj.length - 2
			numeros = cnpj.substring(0,tamanho);
			digitos = cnpj.substring(tamanho);
			soma = 0;
			pos = tamanho - 7;
			for (i = tamanho; i >= 1; i--){
				  soma += numeros.charAt(tamanho - i) * pos--;
				  if (pos < 2)
						pos = 9;
			}
			resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
			if (resultado != digitos.charAt(0))
				  return false;
			tamanho = tamanho + 1;
			numeros = cnpj.substring(0,tamanho);
			soma = 0;
			pos = tamanho - 7;
			for (i = tamanho; i >= 1; i--){
				soma += numeros.charAt(tamanho - i) * pos--;
				if (pos < 2)
					pos = 9;
			}
			resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
			if (resultado != digitos.charAt(1))
				return false;
		
		return true;
	} else
		return false;
} 

function validar_email(email){
   if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)) || !email) 
     return false;
   else 
     return true;
}

function trocaponto(valor){
	return (valor ? valor.replace(".", ",").replace(",",".") : 0);
}

function trocaponto(valor){
	return (valor ? valor.replace(".", "").replace(",",".") : 0);
}

function str_pad (input, pad_length, pad_string, pad_type) {
    // Returns input string padded on the left or right to specified length with pad_string  
    // 
    // version: 1008.1718
    // discuss at: http://phpjs.org/functions/str_pad    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // + namespaced by: Michael White (http://getsprink.com)
    // +      input by: Marco van Oort
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: str_pad('Kevin van Zonneveld', 30, '-=', 'STR_PAD_LEFT');    // *     returns 1: '-=-=-=-=-=-Kevin van Zonneveld'
    // *     example 2: str_pad('Kevin van Zonneveld', 30, '-', 'STR_PAD_BOTH');
    // *     returns 2: '------Kevin van Zonneveld-----'
    var half = '', pad_to_go;
     var str_pad_repeater = function (s, len) {
        var collect = '', i;
 
        while (collect.length < len) {collect += s;}
        collect = collect.substr(0,len); 
        return collect;
    };
 
    input += '';    pad_string = pad_string !== undefined ? pad_string : ' ';
    
    if (pad_type != 'STR_PAD_LEFT' && pad_type != 'STR_PAD_RIGHT' && pad_type != 'STR_PAD_BOTH') { pad_type = 'STR_PAD_RIGHT'; }
    if ((pad_to_go = pad_length - input.length) > 0) {
        if (pad_type == 'STR_PAD_LEFT') { input = str_pad_repeater(pad_string, pad_to_go) + input; }        else if (pad_type == 'STR_PAD_RIGHT') { input = input + str_pad_repeater(pad_string, pad_to_go); }
        else if (pad_type == 'STR_PAD_BOTH') {
            half = str_pad_repeater(pad_string, Math.ceil(pad_to_go/2));
            input = half + input + half;
            input = input.substr(0, pad_length);        }
    }
 
    return input;
}

function comparaDatas(data_inicial, data_final, act)
{  
    //Verifica se a data inicial é maior que a data final  
    dia_inicial      = data_inicial.substr(0,2);  
    dia_final        = data_final.substr(0,2);  
    mes_inicial      = data_inicial.substr(3,2);  
    mes_final        = data_final.substr(3,2);  
    ano_inicial      = data_inicial.substr(6,4);  
    ano_final        = data_final.substr(6,4);  
	switch (act)
	{
		case 1:// Caso a data seja menor que a data atual
			if (ano_inicial < ano_final)
				return false  
			else 
			{  
				if (ano_inicial == ano_final)
				{  
					if (mes_inicial < mes_final)
						return false  
					else 
					{
						if (mes_inicial == mes_final)
						{  
							if (dia_inicial < dia_final)
								return false  
						}
					}
				}
				else
					return false;
			}  
			return true;
			
		case 2: // Caso a data seja maior que a data atual
			if (ano_inicial > ano_final)
				return false  
			else 
			{  
				if (ano_inicial == ano_final)
				{  
					if (mes_inicial > mes_final)
						return false  
					else 
					{
						if (mes_inicial == mes_final)
						{  
							if (dia_inicial > dia_final)
								return false  
						}
					}
				}
				else
					return false;
			}  
			return true;
			
	}
}  
