/*
Funções diversas, usadas no sistema

*/
function soNumeros() {
	//EVENTO OnKeyDown
	//Permite somente caracteres numéricos, + "," e "."
	var Tecla = window.event.keyCode;
	if (!(	(Tecla > 95 && Tecla < 106) || 
		(Tecla > 44 && Tecla < 58) 		|| 
			(Tecla > 32 && Tecla < 41)  ||
				(
				Tecla == 17  ||
				Tecla == 16  ||
				Tecla == 8   || 
				Tecla == 9   || 
				Tecla == 13  ||
				Tecla == 144 ||
				Tecla == 188 ||
				Tecla == 190 ||
				Tecla == 110 ||
				Tecla == 194 
				)
			)
		)
	{window.event.returnValue = false;}
}

function soNumeros2() {
	//EVENTO OnKeyDown (return soNumeros2();
	//Permite somente caracteres numéricos
	var Tecla = window.event.keyCode;
	if (!(	(Tecla > 95 && Tecla < 106) || 
		(Tecla > 44 && Tecla < 58) 		|| 
			(Tecla > 32 && Tecla < 41)  ||
				(
				Tecla == 17  ||
				Tecla == 16  ||
				Tecla == 8   || 
				Tecla == 9   || 
				Tecla == 13  ||
				Tecla == 144
				)
			)
		)
	{window.event.returnValue = false;}
}

function SomenteNumero(e) {
	//Função melhorada, funciona no Firefox também
	//onkeypress="return SomenteNumero(event)"
	var tecla=(window.event)?event.keyCode:e.which;
	if ((tecla > 47 && tecla < 58))
		return true;
	else {
		if (tecla != 8)
			return false;
		else
			return true;
	}
}

function fnContar(obj, qtd) {
	// EVENTOS onKeyPress, onKeyUp
	// Limita o máximo de caracteres em campos TEXTEDIT
	if (obj.value.length >= qtd) {
		obj.value = obj.value.substring(0,qtd);
		return false;
	}
}


function fnCompletaZero(obj, n) {
	while (obj.value.length < n)
		obj.value = '0' + obj.value;
}


function RetornaNumeros(Texto) {
	var objRegExp = new RegExp("[^0-9]","gi")
	return Texto.replace(objRegExp,'')
}


function MascaraCPF(Obj, Opcao)
{var KeyCod = window.event.keyCode;
 //PARA EVENTO ONBLUR / ONKEYUP
 if(Opcao == 0 && ((!(KeyCod == 16 || KeyCod == 8 || (KeyCod > 34 && KeyCod < 41)) && ((KeyCod > 47 && KeyCod < 58) || (KeyCod > 95 && KeyCod < 106))) || (KeyCod == 0)) || (RetornaNumeros(Obj.value).length == 11 && (!(KeyCod == 16 || KeyCod == 8 || (KeyCod > 34 && KeyCod < 41)))))
	{
	var txt = '';
	 var txtAntigo = RetornaNumeros(Obj.value)
	 if(txtAntigo.length > 11)
		{txtAntigo = txtAntigo.substr(0,11)}
	 for(Pos=0; Pos<txtAntigo.length; Pos++)
		{txt+= txtAntigo.substr(Pos,1)
		 if(txt.length == 3 || txt.length == 7)
			{txt+= '.'}
		 if(txt.length == 11) 
			{txt+= '-'}
		}
	 Obj.value = txt
	}
}





function oSwf(url, l, a, id) {
	document.write('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"'+ 
	' codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0"'+
	' width="'+l+'" height="'+a+'" id="'+id+'" align="middle">');
	document.write('<param name="allowScriptAccess" value="sameDomain" />');
	document.write('<param name="movie" value="'+url+'" />');
	document.write('<param name="quality" value="high" />');
	document.write('<param name="menu" value="false" />');
	document.write('<param name="wmode" value="transparent" />');
	document.write('<embed src="'+url+'" quality="high" menu="false" wmode="transparent" '+
	' width="'+l+'" height="'+a+'" name="'+id+'" align="middle"'+
	' allowScriptAccess="sameDomain" type="application/x-shockwave-flash"'+
	' pluginspage="http://www.macromedia.com/go/getflashplayer" />');
	document.write('</object>');
}


function EmailValido(str) {
  var objRegExp  = /^[A-Za-z]([\w\.-]*)@([A-Za-z0-9\.-]*)\.(([A-Za-z]{3}\.[A-Za-z]{2}$)|([A-Za-z]{3}$)|([a-z]{2}$))/i ;
  return objRegExp.test(str);
}



function CpfValido(str) {
	if (str.replace(/^\s*|\s*$/g,"") == "")
		return false;

  var cpf = new String;
  for (i=0; i<str.length; i++) {
    if (str.charAt(i) != '.' && str.charAt(i) != '-') {
      cpf = cpf + str.charAt(i)
    }
  }
  var nonNumbers = /\D/;
  if (nonNumbers.test(cpf))
    return false;

  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;

	return true;
}



function validaCPF(obj) {
	var cpf_full = obj.value;
	if (cpf_full.replace(/^\s*|\s*$/g,"") == "")
		return true;

	if (!CpfValido(cpf_full)) {
    alert('CPF inválido');
    obj.focus();
    return false;
  }
}



function CnpjValido(str) {
  CNPJ = str;
  if (CNPJ.replace(/^\s*|\s*$/g,"") == "") {
    return false;
  }
  if (CNPJ.length < 18 && CNPJ.length > 0) {
    return false;
  } else if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")) {
    return false;
  }
  //substituir os caracteres que não são números
  if (document.layers && parseInt(navigator.appVersion) == 4) {
    x = CNPJ.substring(0,2);
    x += CNPJ.substring(3,6);
    x += CNPJ.substring(7,10);
    x += CNPJ.substring(11,15);
    x += CNPJ.substring(16,18);
    CNPJ = x; 
  } else {
    CNPJ = CNPJ.replace(".","");
    CNPJ = CNPJ.replace(".","");
    CNPJ = CNPJ.replace("-","");
    CNPJ = CNPJ.replace("/","");
  }
  var nonNumbers = /\D/;
  if (nonNumbers.test(CNPJ)) {
    return false;
  }
  var a = [];
  var b = new Number;
  var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
  for (i=0; i<12; i++) {
    a[i] = CNPJ.charAt(i);
    b += a[i] * c[i+1];
  }
  if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
  b = 0;
  for (y=0; y<13; y++) {
    b += (a[y] * c[y]); 
  }
  if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
  if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])) {
    return false;
  }
  return true;
}


// Função que valida o CNPJ - onBlur
function validaCNPJ(obj) {
  CNPJ = obj.value;
  if (CNPJ.replace(/^\s*|\s*$/g,"") == "") {
    return true;
  }
  if (CNPJ.length < 18 && CNPJ.length > 0) {
    alert('Preencha corretamente o número do CNPJ!');
    obj.focus();
    return false;
  } else if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")) {
    alert('Preencha corretamente o número do CNPJ!');
    obj.focus();
    return false;
  }
  //substituir os caracteres que não são números
  if (document.layers && parseInt(navigator.appVersion) == 4) {
    x = CNPJ.substring(0,2);
    x += CNPJ.substring(3,6);
    x += CNPJ.substring(7,10);
    x += CNPJ.substring(11,15);
    x += CNPJ.substring(16,18);
    CNPJ = x; 
  } else {
    CNPJ = CNPJ.replace(".","");
    CNPJ = CNPJ.replace(".","");
    CNPJ = CNPJ.replace("-","");
    CNPJ = CNPJ.replace("/","");
  }
  var nonNumbers = /\D/;
  if (nonNumbers.test(CNPJ)) {
    alert('Preencha corretamente o número do CNPJ!');
    obj.focus();
    return false;
  }
  var a = [];
  var b = new Number;
  var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
  for (i=0; i<12; i++) {
    a[i] = CNPJ.charAt(i);
    b += a[i] * c[i+1];
  }
  if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
  b = 0;
  for (y=0; y<13; y++) {
    b += (a[y] * c[y]); 
  }
  if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
  if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])) {
    alert('CNPJ inválido!');
    obj.focus();
    return false;
  }
  return true;
}


// Mostra imagem numa nova janela, do tamanho da imagem
var wi = null;
function openPopImage(img) {
	if (wi)
		wi.close();
	var x = 0, y = 0, l, t, i, stm;
	i = new Image();
	i.src=img;
	x=(i.width+10)/screen.width;
	y=(i.height+40)/screen.height;
	if(x>=1||y>=1) {
		if(x>y) {mai=x;} else {mai=y;}
		i.width=(i.width/mai)-10;
		i.height=(i.height/mai)-10;
	}
	x=i.width;
	y=i.height;
	if (x == 0 || y == 0)
		stm = setTimeout("openPopImage('" + img + "')", 500);
	else {
		clearTimeout(stm);
		l = (screen.width - x) / 2;
		t = (screen.height - y) / 2;
		wi = window.open('', 'Img', 'left=' + l + ',top=' + t + ', width=' + x + ',height=' + y);
		wi.title = '';
		with (wi.document) {
			write("<html>\n");
			write("<title> </title>\n");
			write("<body leftmargin='0' topmargin='0' rightmargin='0' bottommargin='0'>\n");
			write("<img src='" + img + "' id='imgM' border='0' width='" + i.width + "' height='" + i.height + "' style='cursor: pointer;' onClick='window.close();' title='Clique na imagem para fechar a janela'>\n");
			write("</body>\n");
			write("</html>");
		}
		wi.focus();
	}
}


var oImg = new Array();
var img = new Array();
function fnImgMaxDim(id, fim) {
// Redimensiona uma imagem em dimensões máximas, considerando proporções
	var x = 0, y = 0, mai, stm;
	x = img[id].width / 184;
	y = img[id].height / 138;
	if (fim>=50) return true;
	if (x==0 || y==0)
		stm = setTimeout("fnImgMaxDim(" + id + ", " + (fim+1) + ")", 50)
	else {
		clearTimeout(stm);
		if (x > 0 || y > 0) {
			if (x > y) {mai = x} else {mai = y}
			oImg[id].width = (img[id].width / mai);
			oImg[id].height = (img[id].height / mai);
		} else {
			oImg[id].width = img[id].width;
			oImg[id].height = img[id].height;
		}
	}
}


//Função que remove as chaves "{}" de uma string, quantas houver
function fnRemChaves(str) {
	var str2 = str.replace('}', '').replace('{', '');
	if (str2.indexOf('}') > -1 || str2.indexOf('{') > -1)
		str2 = fnRemChaves(str2);
	return str2;
}

