/*|---------------------------------->>  <<----------------------------------|

Include para ser usado na estrutura padrão dos sites. deve chamado 
no arquivo head.inc.php.

Sr. Programador, todas as funções em javascript que serão utilizadas no site
deverão serem declaradas apenas neste arquivo.

|---------------------------------->>  <<----------------------------------|*/
// Função abre nova janela
// utilização: 											PROPRIEDADES
//				abrejanela('PAGINA.htm','TITULO','scrollbars=yes,resizable=no,width=500,height=400')"


function janela(www,h,w)
{
var height = window.screen.height - 160;
var width = window.screen.width;
var top = (height- h)/2;
var left = (width - w)/2;
window.open(www,"nova","top=" + top + ",left="+ left +",width="+w+",height="+h+",toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,scrolling=no,resizable=no")
} 

function evita_letra3(tecla) {
	if (tecla.keyCode < 49 || tecla.keyCode > 57) 
		tecla.returnValue = false;
}
function FormataValor3(campo,tammax,teclapres) 
	{

		var tecla = teclapres.keyCode;
		var vr = campo.value;
		vr = vr.replace( "/", "" );
		vr = vr.replace( "/", "" );
		vr = vr.replace( ",", "" );
		vr = vr.replace( ".", "" );
		vr = vr.replace( ".", "" );
		vr = vr.replace( ".", "" );
		vr = vr.replace( ".", "" );
		tam = vr.length;
	
		if (tam < tammax && tecla != 8){ tam = vr.length + 2 ; }
	
		if (tecla == 8 ){	tam = tam - 1 ; }
			
		if ( tecla == 8 || (tecla >= 48 && tecla <= 57) || (tecla >= 96 && tecla <= 105) ){
			if ( tam <= 2 ){ 
				campo.value = vr ; }
			tam = tam - 1;
			if ( (tam > 2) && (tam <= 5) ){
				campo.value = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam) ; }
			if ( (tam >= 6) && (tam <= 8) ){
				campo.value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, 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 - 2, 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 - 2, 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 trimAll(sString) 
{
  while (sString.substring(0,1) == ' ')
   {
     sString = sString.substring(1, sString.length);
   }
  while (sString.substring(sString.length-1, sString.length) == ' ')
   {
     sString = sString.substring(0,sString.length-1);
   }
  return sString;
}


function rightTrim(sString) 
{
   while (sString.substring(sString.length-1, sString.length) == ' ')
    {
      sString = sString.substring(0,sString.length-1);
    }
      return sString;
}



function leftTrim(sString) 
{
   while (sString.substring(0,1) == ' ')
     {
       sString = sString.substring(1, sString.length);
     }
   return sString;
}


function formatar(src, mask) 
{
  var i = src.value.length;
  var saida = mask.substring(0,1);
  var texto = mask.substring(i)
if (texto.substring(0,1) != saida) 
  {
	src.value += texto.substring(0,1);
  }
}

function abrejanela(url,nome,propriedades){ 
   window.open(url,nome,propriedades);
}

//Checa o campo E-Mail
function verifica_mail(email){
	var campo = email;
	//se a "@" não existe e é o primeiro caractere 
	if (campo.indexOf("@") < 1) return false
	//se o caracter antes da "@" é "." 
	if(campo.charAt(campo.indexOf("@")-1) == ".") return false;
	//se a última incidência de "." está antes da @ 
	if (campo.lastIndexOf(".") <= campo.indexOf("@")) return false;
	//se o último caracter é ponto,
	if (campo.lastIndexOf(".")  == (campo.length-1)) return false; 
	
	return true;
}

function val_cnpj(numero) {
	//numero = numero1.value;
	dig_1 = 0;
	dig_2 = 0;
	controle_1 = 5;
	controle_2 = 6;

if ( (numero.length != 18)  || (numero.substring(2, 3) != ".") || (numero.substring(6, 7) != ".") || (numero.substring(10, 11) != "/") || (numero.substring(15, 16) != "-") ) {
     return false;
}else{ 
  	   numero = (numero.substring(0, 2)) + "" + (numero.substring(3, 6)) + "" + (numero.substring(7, 10))+ "" + (numero.substring(11, 15)) + "" + (numero.substring(16, 18)) 
	   for ( i=0 ; i < 12 ; i++) {
	        dig_1 = dig_1 + parseFloat(numero.substring(i, i+1) * controle_1);
	          controle_1 = controle_1 - 1;
	        if (i == 3) {
	           controle_1 = 9;
	        }
	   }
	   
	   resto = dig_1 % 11;
	   dig_1 = 11 - resto;
	   
	   if ((resto == 0) || (resto == 1)){
	        dig_1 = 0;
	   }
	   
	   for ( i=0 ; i < 12 ; i++) {
	        dig_2 = dig_2 + parseInt(numero.substring(i, i+1) * controle_2);
	          controle_2 = controle_2 - 1;
	        if (i == 4) {
	           controle_2 = 9;
	        }
	   }
	   
	   dig_2 = dig_2 + (2 * dig_1);
	   resto = dig_2 %11;
	   dig_2 = 11 - resto;
	   
	   if ((resto == 0) || (resto == 1)){
	        dig_2 = 0;
	   }
	   
	   dig_ver = (dig_1 * 10) + dig_2;
	   
	   if (dig_ver != parseFloat(numero.substring(numero.length-2,numero.length))) {
	          return false;
	   }
 }
 return true;
}

function FormataCPF(Campo, teclapres){

	var tecla = teclapres.keyCode;

	var vr = new String(Campo.value);
	vr = vr.replace(".", "");
	vr = vr.replace(".", "");
	vr = vr.replace(".", "");
	vr = vr.replace("/", "");
	vr = vr.replace("-", "");

	tam = vr.length + 1 ;

	
	if (tecla != 9 && tecla != 8){
		if (tam >= 10 && tam < 12) {
			Campo.value = vr.substr(0,3) + '.' + vr.substr(3,3) + '.' + vr.substr(6,3) + '-' + vr.substr(9,tam-9);
		} else if (tam >= 7 && tam < 10) {
			Campo.value = vr.substr(0,3) + '.' + vr.substr(3,3) + '.' + vr.substr(6,tam-6);
		} else if (tam > 3 && tam < 7) {
			Campo.value = vr.substr(0, 3) + '.' + vr.substr(3, tam);
		}
	}
}

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);
		}
}

//Valida o cpf 
function val_cpf(numero2) {
  dig_1 = 0;
  dig_2 = 0;
  controle_1 = 10;
  controle_2 = 11;
  lsucesso = 1;
  
  var numero = numero2.substr(0,3) + numero2.substr(4,3) + numero2.substr(8,3) + numero2.substr(12,2);
  
  if (numero == "00000000000" || numero == "11111111111" || numero == "22222222222" || numero == "33333333333" || numero == "44444444444" || numero == "55555555555" || numero == "66666666666" || numero == "77777777777" || numero == "88888888888" || numero == "99999999999") {
  	return false;
  }
  
  if ((numero.length != 11) && (numero.length != 0)) {
     return false;
  }
  else {
     for ( i=0 ; i < 9 ; i++) {
        dig_1 = dig_1 + parseInt(numero.substring(i, i+1) * controle_1);
          controle_1 = controle_1 - 1;
     }
    
     resto = dig_1 % 11;
     dig_1 = 11 - resto;
     if ((resto == 0) || (resto == 1)) {
          dig_1 = 0;
     }
     for ( i=0 ; i < 9 ; i++) {
          dig_2 = dig_2 + parseInt(numero.substring(i, i + 1) * controle_2);
        controle_2 = controle_2 - 1;
     }
     dig_2 = dig_2 + 2 * dig_1;
     resto = dig_2 % 11;
     dig_2 = 11 - resto;
     if ((resto == 0) || (resto == 1)) {
        dig_2 = 0;
     }
     dig_ver = (dig_1 * 10) + dig_2;
     if (dig_ver != parseFloat(numero.substring(numero.length-2,numero.length))) {
          return false;
        }
  }

return true;
}

function abre_impressao(url) {
	window.open(url, "impressao", "width=600,height=450");
}
//Utilização: onkeypress="evita_letra(event)" onKeydown="FormataHora('NOMEDOCAMPO','NOMEDOFORM',event)" maxlength="5"
function FormataHora(campo,formname,teclapres){
	var tecla = teclapres.keyCode;
	vr = document[formname][campo].value;
	vr = vr.replace( ":", "" );
	tam = vr.length + 1;
	
	if ( tecla != 9 && tecla != 8 ){
		if ( tam > 2 && tam < 5 ){
			document[formname][campo].value = vr.substr( 0, tam - 2  ) + ':' + vr.substr( tam - 2, tam );
		}
	}
}
// FUNÇÃO QUE AUTOCOMPLETA DATA COM '/'
// COMO UTILIZAR:    onkeydown="FormataData(this.name,this.form.name,event);" 
function FormataData(campo,formname,teclapres) { // Máscara para os campos de data
	var tecla = teclapres.keyCode;
	vr = document[formname][campo].value;
	vr = vr.replace( ".", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( "/", "" );
	tam = vr.length + 1;

	if ( tecla != 9 && tecla != 8 ){
		if ( tam > 2 && tam < 5 )
			document[formname][campo].value = vr.substr( 0, tam - 2  ) + '/' + vr.substr( tam - 2, tam );
		if ( tam >= 5 && tam <= 10 )
			document[formname][campo].value = vr.substr( 0, 2 ) + '/' + vr.substr( 2, 2 ) + '/' + vr.substr( 4, 4 ); 
	}
}
// COMO UTILIZAR: onkeypress="evita_letra2(event)"
// Não permite digitar letras em um input type=text
function evita_letra2(tecla) {
	if (tecla.keyCode < 48 || tecla.keyCode > 57) 
		tecla.returnValue = false;
}
function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function ToggleAll(checked) {
    len = document.listagem.elements.length;
    var i = 0;
    for(i = 0; i < len; i++) {
        document.listagem.elements[i].checked = checked;
    }
}

function in_array(s,a) {
  for (i = 0; i < a.lenght; i++) {
	  /*if (a[i] == s) {
	  	return true;
	  }*/
	  alert(a[i]+'=='+s.name);
  }
  //return false;
}

function valida(ffff,ele)
{//começa valida
  
  var c=ele.split(',');
  for(x = 0; x<ffff.elements.length; x++)//varre o formulário
  {  
    //alert(c[x]);//atriz com os elementos
	//e = document.getElementById(c[x]);
	
	for(j=0;j<c.length;j++)//varre os obrigatórios
	{
	   var formul=ffff.elements[x];
	   //alert(formul);
       if(formul.name==c[j] &&  leftTrim(formul.value)=='')//se tem o elemento no formulário
	   {
	      alert('O campo '+document.getElementById(formul.name+"_label").innerHTML+' é obrigatorio');
		  document.getElementById(formul.name).focus();
		  return;
		  
	      
	   }
	}//fim for
	
  }//fim for
  ffff.submit();
}//fim valida

/*****************************
FUNÇÃO DA CONTAGEM REGRESSIVA
*****************************/
var Temp2;
var timerID = null;
var timerRunning = false;
function arry() {
	this.length = 12;
	this[0] = 31;
	this[1] = 28;
	this[2] = 31;
	this[3] = 30;
	this[4] = 31;
	this[5] = 30;
	this[6] = 31;
	this[7] = 31;
	this[8] = 30;
	this[9] = 31;
	this[10] = 30;
	this[11] = 31;
}
var date = new arry();

function stopclock() {
	if(timerRunning)
		clearTimeout(timerID);
		timerRunning = false;
}

function startclock() {
	stopclock();
	showtime();
}

function showtime() {
	now = new Date();
	var CurMonth = now.getMonth();
	var CurDate = now.getDate();
	var CurYear = now.getFullYear();
	now = null;
	if (19 < CurDate) {
		CurDate -= date[CurMonth]; CurMonth++;
	}
	if (10 < CurMonth) {
		CurMonth -= 12; CurYear++;
	}

	var Yearleft = 2006 - CurYear;
	var Monthleft = 10 - CurMonth;
	var Dateleft = 19 - CurDate;
	
	document.dateform.a.value = Yearleft;
	document.dateform.b.value = Monthleft;
	document.dateform.c.value = Dateleft;
	
	timerID = setTimeout("showtime()",1000);
	timerRunning = true;
}
//FIM CONTAGEM REGRESSIVA

//CRIPTOGRAFIA MD5 JAVASCRIPT
/*
 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
 * Digest Algorithm, as defined in RFC 1321.
 * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 * Distributed under the BSD License
 * See http://pajhome.org.uk/crypt/md5 for more info.
 */

/*
 * Configurable variables. You may need to tweak these to be compatible with
 * the server-side, but the defaults work in most cases.
 */
var hexcase = 0;  /* hex output format. 0 - lowercase; 1 - uppercase        */
var b64pad  = ""; /* base-64 pad character. "=" for strict RFC compliance   */
var chrsz   = 8;  /* bits per input character. 8 - ASCII; 16 - Unicode      */

/*
 * These are the functions you'll usually want to call
 * They take string arguments and return either hex or base-64 encoded strings
 */
function hex_md5(s){ return binl2hex(core_md5(str2binl(s), s.length * chrsz));}
function b64_md5(s){ return binl2b64(core_md5(str2binl(s), s.length * chrsz));}
function str_md5(s){ return binl2str(core_md5(str2binl(s), s.length * chrsz));}
function hex_hmac_md5(key, data) { return binl2hex(core_hmac_md5(key, data)); }
function b64_hmac_md5(key, data) { return binl2b64(core_hmac_md5(key, data)); }
function str_hmac_md5(key, data) { return binl2str(core_hmac_md5(key, data)); }

/*
 * Perform a simple self-test to see if the VM is working
 */
function md5_vm_test()
{
  return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72";
}

/*
 * Calculate the MD5 of an array of little-endian words, and a bit length
 */
function core_md5(x, len)
{
  /* append padding */
  x[len >> 5] |= 0x80 << ((len) % 32);
  x[(((len + 64) >>> 9) << 4) + 14] = len;

  var a =  1732584193;
  var b = -271733879;
  var c = -1732584194;
  var d =  271733878;

  for(var i = 0; i < x.length; i += 16)
  {
    var olda = a;
    var oldb = b;
    var oldc = c;
    var oldd = d;

    a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
    d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
    c = md5_ff(c, d, a, b, x[i+ 2], 17,  606105819);
    b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
    a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
    d = md5_ff(d, a, b, c, x[i+ 5], 12,  1200080426);
    c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
    b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
    a = md5_ff(a, b, c, d, x[i+ 8], 7 ,  1770035416);
    d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
    c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
    b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
    a = md5_ff(a, b, c, d, x[i+12], 7 ,  1804603682);
    d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
    c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
    b = md5_ff(b, c, d, a, x[i+15], 22,  1236535329);

    a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
    d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
    c = md5_gg(c, d, a, b, x[i+11], 14,  643717713);
    b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
    a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
    d = md5_gg(d, a, b, c, x[i+10], 9 ,  38016083);
    c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
    b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
    a = md5_gg(a, b, c, d, x[i+ 9], 5 ,  568446438);
    d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
    c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
    b = md5_gg(b, c, d, a, x[i+ 8], 20,  1163531501);
    a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
    d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
    c = md5_gg(c, d, a, b, x[i+ 7], 14,  1735328473);
    b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);

    a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
    d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
    c = md5_hh(c, d, a, b, x[i+11], 16,  1839030562);
    b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
    a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
    d = md5_hh(d, a, b, c, x[i+ 4], 11,  1272893353);
    c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
    b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
    a = md5_hh(a, b, c, d, x[i+13], 4 ,  681279174);
    d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
    c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
    b = md5_hh(b, c, d, a, x[i+ 6], 23,  76029189);
    a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
    d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
    c = md5_hh(c, d, a, b, x[i+15], 16,  530742520);
    b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);

    a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
    d = md5_ii(d, a, b, c, x[i+ 7], 10,  1126891415);
    c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
    b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
    a = md5_ii(a, b, c, d, x[i+12], 6 ,  1700485571);
    d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
    c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
    b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
    a = md5_ii(a, b, c, d, x[i+ 8], 6 ,  1873313359);
    d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
    c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
    b = md5_ii(b, c, d, a, x[i+13], 21,  1309151649);
    a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
    d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
    c = md5_ii(c, d, a, b, x[i+ 2], 15,  718787259);
    b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);

    a = safe_add(a, olda);
    b = safe_add(b, oldb);
    c = safe_add(c, oldc);
    d = safe_add(d, oldd);
  }
  return Array(a, b, c, d);

}

/*
 * These functions implement the four basic operations the algorithm uses.
 */
function md5_cmn(q, a, b, x, s, t)
{
  return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}
function md5_ff(a, b, c, d, x, s, t)
{
  return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t)
{
  return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t)
{
  return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t)
{
  return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}

/*
 * Calculate the HMAC-MD5, of a key and some data
 */
function core_hmac_md5(key, data)
{
  var bkey = str2binl(key);
  if(bkey.length > 16) bkey = core_md5(bkey, key.length * chrsz);

  var ipad = Array(16), opad = Array(16);
  for(var i = 0; i < 16; i++)
  {
    ipad[i] = bkey[i] ^ 0x36363636;
    opad[i] = bkey[i] ^ 0x5C5C5C5C;
  }

  var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz);
  return core_md5(opad.concat(hash), 512 + 128);
}

/*
 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
 * to work around bugs in some JS interpreters.
 */
function safe_add(x, y)
{
  var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  return (msw << 16) | (lsw & 0xFFFF);
}

/*
 * Bitwise rotate a 32-bit number to the left.
 */
function bit_rol(num, cnt)
{
  return (num << cnt) | (num >>> (32 - cnt));
}

/*
 * Convert a string to an array of little-endian words
 * If chrsz is ASCII, characters >255 have their hi-byte silently ignored.
 */
function str2binl(str)
{
  var bin = Array();
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < str.length * chrsz; i += chrsz)
    bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);
  return bin;
}

/*
 * Convert an array of little-endian words to a string
 */
function binl2str(bin)
{
  var str = "";
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < bin.length * 32; i += chrsz)
    str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask);
  return str;
}

/*
 * Convert an array of little-endian words to a hex string.
 */
function binl2hex(binarray)
{
  var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i++)
  {
    str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
           hex_tab.charAt((binarray[i>>2] >> ((i%4)*8  )) & 0xF);
  }
  return str;
}

/*
 * Convert an array of little-endian words to a base-64 string
 */
function binl2b64(binarray)
{
  var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i += 3)
  {
    var triplet = (((binarray[i   >> 2] >> 8 * ( i   %4)) & 0xFF) << 16)
                | (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 )
                |  ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF);
    for(var j = 0; j < 4; j++)
    {
      if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
      else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
    }
  }
  return str;
}

/* VALIDA O FORMULÁRIO DE COMENTÁRIO */
function verificaCom(ff) {
	if(document.getElementById('comNome').value==''){
		alert('Digite seu nome.');
		document.getElementById('comNome').focus();
	} else if(document.getElementById('comMsg').value==''){
		alert('Digite sua mensagem.');
		document.getElementById('comMsg').focus();
	} else {
		document.getElementById('comForm').submit();
	}
}

/*FUNÇÃO PARA O MENU DE NAVEGAÇÃO */
function abreMenu(secao) {
	if(document.getElementById( secao ).className=='esconde') {
		document.getElementById( secao ).className='mostra';
	} else if (document.getElementById( secao ).className=='mostra') {
		document.getElementById( secao ).className='esconde';
	}
		
}

//FUNÇÃO PARA ESVAZIAR O CAMPO TEXT
function campoVazio(ff,valor) {
	if(document.getElementById(ff).value=='') {
		document.getElementById(ff).value=valor;
	}
}

//FUNÇÃO PARA VALIDAR O LOGIN
function validaLogin() {
	if(document.getElementById('usuario').value == "") {
		alert('Digite seu login.');
		document.getElementById('usuario').focus();
	} else if(document.getElementById('senha').value == "") {
		alert('Digite sua senha');
		document.getElementById('senha').focus();
	} else {
		document.getElementById('login').submit();
	}
}

// Extended Tooltip Javascript
// copyright 9th August 2002, 3rd July 2005
// by Stephen Chapman, Felgall Pty Ltd

// permission is granted to use this javascript provided that the below code is not altered
var DH = 0;var an = 0;var al = 0;var ai = 0;if (document.getElementById) {ai = 1; DH = 1;}else {if (document.all) {al = 1; DH = 1;} else { browserVersion = parseInt(navigator.appVersion); if ((navigator.appName.indexOf('Netscape') != -1) && (browserVersion == 4)) {an = 1; DH = 1;}}} function fd(oi, wS) {if (ai) return wS ? document.getElementById(oi).style:document.getElementById(oi); if (al) return wS ? document.all[oi].style: document.all[oi]; if (an) return document.layers[oi];}
function pw() {return window.innerWidth != null? window.innerWidth: document.body.clientWidth != null? document.body.clientWidth:null;}
function mouseX(evt) {if (evt.pageX) return evt.pageX; else if (evt.clientX)return evt.clientX + (document.documentElement.scrollLeft ?  document.documentElement.scrollLeft : document.body.scrollLeft); else return null;}
function mouseY(evt) {if (evt.pageY) return evt.pageY; else if (evt.clientY)return evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop); else return null;}
function popUp(evt,oi) {if (DH) {var wp = pw(); ds = fd(oi,1); dm = fd(oi,0); st = ds.visibility; if (dm.offsetWidth) ew = dm.offsetWidth; else if (dm.clip.width) ew = dm.clip.width; if (st == "visible" || st == "show") { ds.visibility = "hidden"; } else {tv = mouseY(evt) + 20; lv = mouseX(evt) - (ew/4); if (lv < 2) lv = 2; else if (lv + ew > wp)
lv -= ew/2; if (!an) {lv += 'px';tv += 'px';} ds.left = lv; ds.top = tv; ds.visibility = "visible";}}}

//Função STRIP_TAGS
function  strip_tags($text){
	return $text.replace(/<\/?[^>]+>/gi, '');
} //vai mostrar 'teste teste2'

//INSERIR TEXTO ONDE O CURSOR ESTÁ
function insertAtCursor(field, text) { 

    var pos = document.getElementById(field).selectionStart; // Try to get cursor position 
    var scrollPos = document.getElementById(field).scrollTop // Save scroll position 

    if( !pos ) { 
        // IE Method 
        // Force focus on the intended field 
        if( !document.getElementById(field).focus() ) document.getElementById(field).focus(); 
        document.selection.createRange().text=text;
    } else { 
        // Standards Compliant Method (Firefox, Opera, ...) 
        document.getElementById(field).value = document.getElementById(field).value.substr(0, pos) + text + document.getElementById(field).value.substr(pos); 
        document.getElementById(field).selectionStart = pos + text.length; 
    } 
     
    // Reset scroll position 
    document.getElementById(field).scrollTop = scrollPos; 
     
}

function insereSmile(campo, smile) {
	document.getElementById(campo).value += smile;
	document.getElementById(campo).focus();
}

function SetCookie(cookieName,cookieValue,nDays) {
 var today = new Date();
 var expire = new Date();
 if (nDays==null || nDays==0) nDays=1;
 expire.setTime(today.getTime() + 3600000*24*nDays);
 document.cookie = cookieName+"="+escape(cookieValue)
                 + ";expires="+expire.toGMTString();
}

function getRadioValue(RadioName){
	var colRadio = document.getElementsByName( RadioName );
	for (var i = 0; i < colRadio.length; i++){
		if (colRadio[i].checked){
			return colRadio[i].value;
		}
	}
	return null;
}


function votar() {
	var enquete = document.getElementById('enquete').value;
	
	SetCookie('votacaoEnquete', enquete, 1);
	document.getElementById('btnEnquete').disabled='disabled';
	ajaxPost('modulo/enquete.php','acao=votar&opcao='+getRadioValue('eqtOpcao'),'eqtForm',true);
}

function addJogoOnline(arquivo, vars) {
	var reply = prompt("Digite o Friend-Code.  Se não souber ou não tiver, digite 0 (zero).", "Digite apenas caracteres numéricos.");
	
	ajaxPost(arquivo, vars + "&fc=" + reply, 'contGeral', true);
}

function editJogoOnline(arquivo, vars, atual) {
	var reply = prompt("Digite o Friend-Code.  Se não souber ou não tiver, digite 0 (zero).", atual);
	if(reply != null)
		ajaxPost(arquivo, vars + "&fc=" + reply, 'contGeral', true);
}


//FUNÇÃO PARA EDITAR SENHA
function alteraSenha() {
	if(document.getElementById('senha_old').value == '') {
		alert('Digite sua senha atual.');
	} else if(document.getElementById('senha1').value == '') {
		alert('Digite sua nova senha.');
	} else if(document.getElementById('senha2').value == '') {
		alert('Redigite sua nova senha.');
	} else if(hex_md5(document.getElementById('senha_old').value) != document.getElementById('oldPassword').value) {
		alert('Sua senha atual está incorreta.');
	} else if(document.getElementById('senha1').value != document.getElementById('senha2').value) {
		alert('Nova senha e confirmação não conferem.');
	} else {
		document.getElementById('addCan').submit();
	}
}

//FUNÇÃO PARA EDITAR DADOS
function alteraDados() {
	if(document.getElementById('nome').value == '') {
		alert('Digite seu nome.');
	} else if(document.getElementById('sobrenome').value == '') {
		alert('Digite seu sobrenome.');
	} else if(document.getElementById('apelido').value == '') {
		alert('Digite seu apelido.');
	} else if(document.getElementById('email').value == '') {
		alert('Digite seu e-mail.');
	} else if(document.getElementById('login').value == '') {
		alert('Digite seu login.');
	} else {
		document.getElementById('addCan').submit();
	}
}
//FUNÇÃO PARA DELETAR CONTA
function deletaConta(usuario) {
	if(confirm('Deseja realmente excluir sua conta?')) {
		if(confirm('Isso deletará todos os seus registros. Tem certeza?')) {
			window.location='?sec=dados&acao=deletar&usuario='+usuario;
		}
	}
}

//FUNÇÃO PARA CONFIRMAR A EXCLUSÃO DE UMA NOTÍCIA
function exclusao(arquivo, id) {
	if(confirm('Deseja realmente deletar este registro?')){
		window.location = '?sec=' + arquivo + '&noti=' + id + '&acao=deletar';
	}
}

//FUNÇÃO PARA VALIDAR O FORM DE CONTATO
function validaContato() {
	if(document.getElementById('nomeCont').value == "") {
		alert('Digite seu nome.');
		document.getElementById('nomeCont').focus();
	} else if(document.getElementById('emailCont').value == "") {
		alert('Digite seu e-mail.');
		document.getElementById('emailCont').focus();
	} else if(document.getElementById('assuntoCont').value == "") {
		alert('Digite o assunto.');
		document.getElementById('assuntoCont').focus();	
	} else if(document.getElementById('msgCont').value == "") {
		alert('Digite sua mensagem.');
		document.getElementById('msgCont').focus();	
	} else {
		document.getElementById('contato').submit();
	}
}

//FUNÇÃO PARA VALIDAR O FORM DE CADASTRO
function validaCadastro() {
	if(document.getElementById('nomeCad').value == "") {
		alert('Digite seu nome.');
		document.getElementById('nomeCad').focus();
	} else if(document.getElementById('sobreCad').value == "") {
		alert('Digite seu sobrenome.');
		document.getElementById('sobreCad').focus();
	} else if(document.getElementById('nickCad').value == "") {
		alert('Digite um apelido.');
		document.getElementById('nickCad').focus();	
	} else if(document.getElementById('emailCad').value == "") {
		alert('Digite um e-mail válido.');
		document.getElementById('emailCad').focus();	
	} else if(document.getElementById('loginCad').value == "") {
		alert('Digite um login.');
		document.getElementById('loginCad').focus();	
	} else if(document.getElementById('senhaCad').value == "") {
		alert('Digite uma senha.');
		document.getElementById('senhaCad').focus();	
	} else if(document.getElementById('senha2Cad').value == "") {
		alert('Redigite sua senha.');
		document.getElementById('senha2Cad').focus();	
	} else if(document.getElementById('senhaCad').value != document.getElementById('senha2Cad').value) {
		alert('Senha e confirmação não conferem.');
		document.getElementById('senhaCad').focus();	
	} else {
		document.getElementById('cadastro').submit();
	}
}

//FUNÇÃO PARA VALIDAR O FORM DE UPLOAD DE LEGENDA
function validaUpload() {
	if(document.getElementById('midia').value == "") {
		alert('Selecione a mídia.');
		document.getElementById('midia').focus();
	} else if(document.getElementById('temporada').value == "") {
		alert('Digite a temporada. Coloque 0 (zero) se for um filme.');
		document.getElementById('temporada').focus();
	} else if(document.getElementById('episodio').value == "") {
		alert('Digite o episódio. Coloque 0 (zero) se for um filme.');
		document.getElementById('episodio').focus();	
	} else if(document.getElementById('rls').value == "") {
		alert('Digite o release.');
		document.getElementById('rls').focus();	
	} else if(document.getElementById('tam_arquivo').value == "") {
		alert('Digite o tamanho do arquivo.');
		document.getElementById('tam_arquivo').focus();	
	} else if(document.getElementById('userfile').value == "") {
		alert('Selecione uma legenda para enviar.');
		document.getElementById('userfile').focus();	
	} else if(document.getElementById('descricao').value == "") {
		alert('Digite a descrição.');
		document.getElementById('descricao').focus();
	} else if(document.getElementById('idioma').value == "") {
		alert('Selecione o idioma.');
		document.getElementById('idioma').focus();
	} else if(document.getElementById('destaque').value == '1' && document.getElementById('userfile2').value == '') {
		alert('Selecione uma imagem para o destaque.');
		document.getElementById('userfile2').focus();
	} else if(document.getElementById('destaque').value == '1' && document.getElementById('rlsShort').value == '') {
		alert('Digite o release (compacto).');
		document.getElementById('rlsShort').focus();
	} else if(document.getElementById('cd').value == "") {
		alert('Digite a quantidade de CDs.');
		document.getElementById('cd').focus();	
	} else if(document.getElementById('fps').value == "") {
		alert('Digite a quantidade de frames por segundo.');
		document.getElementById('fps').focus();
	} else {
		document.getElementById('addCan').submit();
	}
}

// Início do código de Aumentar/ Diminuir a letra
 
// Para usar coloque o comando: "javascript:mudaTamanho('tag_ou_id_alvo', -1);" para diminuir
// e o comando "javascript:mudaTamanho('tag_ou_id_alvo', +1);" para aumentar
 
var tagAlvo = new Array('p'); //pega todas as tags p//
 
// Especificando os possíveis tamanhos de fontes, poderia ser: x-small, small...
var tamanhos = new Array( '9px','10px','11px','12px','13px','14px','15px' );
var tamanhoInicial = 3;
 
function mudaTamanho( idAlvo,acao ){
  if (!document.getElementById) return
  var selecionados = null,tamanho = tamanhoInicial,i,j,tagsAlvo;
  tamanho += acao;
  if ( tamanho < 0 ) tamanho = 0;
  if ( tamanho > 6 ) tamanho = 6;
  tamanhoInicial = tamanho;
  if ( !( selecionados = document.getElementById( idAlvo ) ) ) selecionados = document.getElementsByTagName( idAlvo )[ 0 ];
  
  selecionados.style.fontSize = tamanhos[ tamanho ];
  
  for ( i = 0; i < tagAlvo.length; i++ ){
    tagsAlvo = selecionados.getElementsByTagName( tagAlvo[ i ] );
    for ( j = 0; j < tagsAlvo.length; j++ ) tagsAlvo[ j ].style.fontSize = tamanhos[ tamanho ];
  }
}
// Fim do código de Aumentar/ Diminuir a letra