// JavaScript Document

function MiddletScreen( pop_width, pop_length, layer ){

	var screenW = 800, screenH = 600;

	if (parseInt(navigator.appVersion) >3) {
	 screenW = screen.width;
	 screenH = screen.height;
	}
	else if ((navigator.appName == Netscape) 
		&& (parseInt(navigator.appVersion)==3)
		&& (navigator.javaEnabled())) 
		{
			 var jToolkit = java.awt.Toolkit.getDefaultToolkit();
			 var jScreenSize = jToolkit.getScreenSize();
			 screenW = jScreenSize.width;
			 screenH = jScreenSize.height;
		}
	
	var left = (screenW/2) - (pop_width/2);
	var top =  (screenH/2) - (pop_length/2);
	
	eval('document.all.'+layer+'.style.top='+top);
	eval('document.all.'+layer+'.style.left='+left);	

}


function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function jetAbrePopup(theURL, Width, height, winName, left, top, toolbar, location, status, menubar, scrollbars, resizable)
{

	var winName =  (winName == null) ? "_blank" : winName;	
	var Width =  (Width == null) ? 1 : Width;
	
	var height =  (height == null) ? 1 : height;
	var left =  (left == null) ? 0 : left;
	var top  =  (top == null) ? 0 : top;	

	var toolbar = ((toolbar == null)||(toolbar == undefined)||(toolbar == 0)) ? 'no' : 'yes';	
	var location = ((location == null)||(location == undefined)||(location == 0)) ? 'no' : 'yes';	
	var status = ((status == null)||(status == undefined)||(status == 0)) ? 'no' : 'yes';		
	var menubar = ((menubar == null)||(menubar == undefined)||(menubar == 0)) ? 'no' : 'yes';			
	var scrollbars = ((scrollbars == null)||(scrollbars == undefined)||(scrollbars == 0)) ? 'no' : 'yes';			
	var resizable = ((resizable == null)||(resizable == undefined)||(resizable == 0)) ? 'no' : 'yes';

	if ((left < 0)||(top < 0))  // Centro da Tela
	{
		var pop_width = Width, pop_length = height
		var screenW = 800, screenH = 600;
		if (parseInt(navigator.appVersion)>3)
		{
			screenW = screen.width;
			screenH = screen.height;
		}
		else 
			if (navigator.appName == "Netscape" && parseInt(navigator.appVersion)==3 && navigator.javaEnabled()) 
			{
				var jToolkit = java.awt.Toolkit.getDefaultToolkit();
				var jScreenSize = jToolkit.getScreenSize();
				screenW = jScreenSize.width;
				screenH = jScreenSize.height;
			}
		var left = (screenW/2) - (pop_width/2)
		var top =  (screenH/2) - (pop_length/2)		
	}	

	features  = 'width='+Width;
	features += ',height='+height;
	features += ',left='+left;
	features += ',top='+top;	
	features += ',toolbar='+toolbar;
	features += ',location='+location;
	features += ',status='+status;
	features += ',menubar='+menubar;
	features += ',scrollbars='+scrollbars;
	features += ',resizable='+resizable;
	
	window.open(theURL,winName,features);

}

// Validação de Campos em Formulários
// Nos campos <INPUT> utilize a  tag alt="" - Forca Obrigatorio - Coloque a Mensagem que aparecerá como obrigatório
//     		  email (no nome do campo) - faz a validação do Email - ex: txtEmail
//			  cnpj  (no nome do campo) - faz a validação do cnpj- ex: txtCnpj
//			  cpf	(no nome do campo  - faz a validação do CPF - ex: txtCpf
//			  cep   (no nome do campo) - faz a validação do cep - ex: txtCep
// Nos campos <SELECT> utilize a tag title="" - Forca Obrigatorio - Coloque a Mensagem e informe o 1o. <option> como -1
// Nos campos <TEXTAREA> utilize a tag title="" - Forca Obrigatorio - Coloque a Mensagem que aparecerá como obrigatório
function ValidatorForm(theForm){
	for(var y = 0; y <= theForm.length-1; y++){

		n = theForm.elements[y];
		
		if (n.tagName=="INPUT"){			// Verifica se campo é do tipo INPUT
			if (n.alt != ""){				// Verifica se foi colocado a tag "AlT" aonde força obrigatório
				if (n.value.length==0){		// verifica se o campo está vazio
					alert(n.alt + ' !!! É um Campo Obrigatório');
					n.focus();
					return false;				
				}
			}
			if (InStr(n.name.toLowerCase(),'email') > 0) {	// email no nome do campo e faz a validação 
				 if (ValidaEmail(n.value)==false){
					alert(n.alt + ' Incorreto');
					n.focus();
					return false;					 
				 }
			}
			if (InStr(n.name.toLowerCase(),'cnpj') > 0) {  // cnpj no nome faz a validação
				 if (valida_CNPJ(n.value)==false){
					alert(n.alt + ' Incorreto');
					n.focus();
					return false;					 
				 }
			}

			if (InStr(n.name.toLowerCase(),'cep') > 0) {  // Cep no nome faz a validação
				 s = limpa_string(n.value)
				 if (s.length != 8){
					alert(n.alt + ' Incorreto');
					n.focus();
					return false;					 
				 }
			}
		}
		else{
			if (n.tagName=="SELECT"){	// Campo Select
				if (n.title != ""){			// Forca ser Obrigatório
					if (n[0].value == -1){	 // Verifica se o Primeiro item tem o valor para campo sem selecão
						if (n[0].selected){		// Somente aí verifica o estado de seleção
							alert('Por Favor selecione ' + n.title + '!!!');
							n.focus();
							return false;						
						}
					}
				}			
			}
			else{
				if ((n.tagName=="TEXTAREA")&&(n.title != "")){
					if (n.value.length==0){		// verifica se o campo está vazio
						alert(n.title + ' é um Campo Obrigatório');
						n.focus();
						return false;				
					}
				}
			
			}
		
		}
		

	}	
	return true;
}


// ---------------------------------------------------------------------------------------------
// Formata o Campo <input>
// ex: <INPUT name="txtCNPJ" onKeyPress="return txtBoxFormat(this, '99.999.999/9999-99', event);
// ---------------------------------------------------------------------------------------------
function txtBoxFormat(src, sMask, evtKeyPress) { 

	  var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla; 


      if(document.all)
	  { // Internet Explorer 
        nTecla = evtKeyPress.keyCode; 
	  } 
      else if(document.layers) 
	  { // Nestcape 
        nTecla = evtKeyPress.which; 
      } 

      sValue = src.value; 
	  
      // Limpa todos os caracteres de formatação que 
      // já estiverem no campo. 
      sValue = sValue.toString().replace( "-", "" ); 
      sValue = sValue.toString().replace( "-", "" ); 
      sValue = sValue.toString().replace( ".", "" ); 
      sValue = sValue.toString().replace( ".", "" ); 
      sValue = sValue.toString().replace( ".", "" ); 
      sValue = sValue.toString().replace( "/", "" ); 
      sValue = sValue.toString().replace( "/", "" ); 
      sValue = sValue.toString().replace( "(", "" ); 
      sValue = sValue.toString().replace( "(", "" ); 
      sValue = sValue.toString().replace( ")", "" ); 
      sValue = sValue.toString().replace( ")", "" ); 
      sValue = sValue.toString().replace( " ", "" ); 
      sValue = sValue.toString().replace( " ", "" ); 
      fldLen = sValue.length; 
      mskLen = sMask.length; 

	  i = 0; 
      nCount = 0; 
      sCod = ""; 
      mskLen = fldLen;
	
      while (i <= mskLen) { 
        bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/")) 
        bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " ")) 

        if (bolMask) { 
          sCod += sMask.charAt(i); 
          mskLen++;
		   } 
        else { 
          sCod += sValue.charAt(nCount); 
          nCount++; 
        } 

        i++; 
      } 
	
      src.value = sCod; 


      if (nTecla != 8) { // backspace 
        if (sMask.charAt(i-1) == "9") { // apenas números... 
          return ((nTecla > 47) && (nTecla < 58)); } // números de 0 a 9 
        else { // qualquer caracter... 
          return true; 
        } } 
      else { 
        return true; 
      } 
} 


//-------------------------------------------------------------------
function OnLoad() {
if (document.getElementById) // IE5 NN6
	document.getElementById("loading").style.visibility="hidden";
else if (document.layers) // NN4
		document.loading.visibility="hidden";
else if (document.all) // IE4
		document.all.loading.style.visibility="hidden";
}

//-------------------------------------------------------------------
function ConvertValorStr(Numero){
	var strNumero = '';
	strNumero = Numero+'';
	strNumero= replace(strNumero,".",",");
	return strNumero
}


//-------------------------------------------------------------------
function ConvertStrToValor(Numero, Decimals){
	var strNumero = '';
	var dblNumero = 0;
	strNumero = replace(Numero,".","");
	strNumero = replace(strNumero,",",".");
	dblNumero = Arredonda(strNumero,Decimals)
	return dblNumero
}

//-------------------------------------------------------------------
function FormataNumber(tmp,decimal)
{
    var tmp;
	tmp = replace(tmp,'.','');
	tmp = replace(tmp,',','.');	
    
	if(isNaN(tmp)) {tmp = 0.00;}
	if(isNaN(decimal)) {decimal = 2;}
	
	tmp = tmp*100;
    tmp = Math.round(tmp);
    cen = tmp%100;

	tmp = parseInt(tmp/100);
    hun = tmp - ((parseInt(tmp/1000)) *1000);

    tmp = parseInt(tmp/1000)
    tho = tmp - ((parseInt(tmp/1000)) *1000);

    tmp = parseInt(tmp/1000);
    mil = tmp - ((parseInt(tmp/1000)) *1000);

	cen = ","+lZeros(cen,decimal);
	
	if ( (mil>0) || (tho>0) )
	{
		hun = '.' + lZeros(hun,3) 
	}
	else
	{ 
		hun = hun
	}
	

	if ( (mil>0) )
	{
		tho = '.' + lZeros(tho,3) 
	}
	else
	{ 
		tho = tho
	}
	
	return mil+tho+hun+cen

}

function lZeros(valor,digitos){
	 	var ret = valor+'';
		var intlength = ret.length;
		for(i=0 ; i < (digitos - intlength) ; i++){
			ret = '0' + ret;
		}
        return ret
}

function FormataValor(campo,tammax,teclapres) {
	var tecla = teclapres.keyCode;
	//vr = document.all[campo].value;
	vr = campo.value;
	
	vr = replace(vr , "/" , "");
	vr = replace(vr , ",", "" );	
	vr = replace(vr , ".", "" );	

	tam = vr.length;

	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 <= 2 ){ 
	 		campo.value = vr ; }
	 	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 ) ;}
	}
}

// verifica se o parâmetro é composto somente de caracteres numéricos
// - o paramametro i_f indica 1 - inteiros
//                            2 - float, separado por ponto ou vírgula
function verificaNumerico (strAver, i_f)
{
	var i = 0;
	var j = 0;
	var comp;
	var teste = "0123456789.,"
	var subteste;
	var substrAver;
	var flgvg=0;
	// se estiver em branco, retorna Ok
	if (strAver == ""){
		return 1;
	}
	if (i_f == 1){
		comp = 10;
	}else{
		comp = 12;
	}
	// varre cada dígito do número a ser verificado
	while (j < strAver.length){
		substrAver = strAver.charAt (j);
		i = 0;
		// analisa se cada dígito do número a ser verificado é válido
		while (i < comp){
			if (strAver.charAt (j) == teste.charAt (i))	{
				// se for virgula (ou ponto) decimal, não pode ter duas...
				if ((teste.charAt (i) == ".")  ||  (teste.charAt (i) == ",")){
					if (flgvg == 1)	{
						return 0;
					}else{
						flgvg = 1;
					}
				}
				break;
			}else{
				// se o dígito não é válido, retorna ERRO
				if (i == (comp - 1)){
					return 0;
				}
			}
			i++;
		}
		j++;
	}
	return 1;
}


function Arredonda( valor , casas ){
   var novo = Math.round( valor * Math.pow( 10 , casas ) ) / Math.pow( 10 , casas );
   return( novo );
}

function replace(S,string1,string2){
var temp = "";
var digito = "";
for (var i=0; i<S.length; i++){
    digito = S.charAt(i);
    if (string1.indexOf(digito)>=0)
       {temp=temp+string2}
    else{temp=temp+digito}
    }
return temp
}

function calendar(formname,currentdate)
{
 self.name = 'opener';
 remote = open('calendar.asp?name=' + formname + '&sdate=' + currentdate, 'remote', 'width=160,height=165,location=no,scrollbars=no,menubars=no,toolbars=no,resizable=no,fullscreen=no');
 remote.focus();
}


function submitonce(theform){
	//if IE 4+ or NS 6+
	if (document.all||document.getElementById){
	//screen thru every element in the form, and hunt down "submit" and "reset"
	for (i=0;i<theform.length;i++){
		var tempobj=theform.elements[i]
		if(tempobj.type.toLowerCase()=="submit"||tempobj.type.toLowerCase()=="reset"||tempobj.type.toLowerCase()=="button")
		//disable em
		tempobj.disabled=true
		}
	}
}


function validaemail(pmail){
var str=pmail
var filter=/^.+@.+\..{2,3}$/
var testresults
if (filter.test(str))
    testresults = true
else{
    testresults=false
    }
return (testresults)
}

function conta_numeros(S){
var Digitos = "0123456789";
var contador = 0
var digito = "";
for (var i=0; i<S.length; i++){
     digito = S.charAt(i);
     if (Digitos.indexOf(digito)>=0){contador = contador + 1}
}
return contador
}


function limpa_string(S){
// Deixa so' os digitos no numero
var Digitos = "0123456789";
var temp = "";
var digito = "";
    for (var i=0; i<S.length; i++){
      digito = S.charAt(i);
      if (Digitos.indexOf(digito)>=0){temp=temp+digito}
    }
    return temp
}


function valida_CPF(s)
{
	var i;
	s = limpa_string(s);
	var c = s.substr(0,9);
	var dv = s.substr(9,2);
	var d1 = 0;
	for (i = 0; i < 9; i++)
	{
		d1 += c.charAt(i)*(10-i);
	}
        if (d1 == 0) return false;
	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	if (dv.charAt(0) != d1)
	{
		return false;
	}

	d1 *= 2;
	for (i = 0; i < 9; i++)
	{
		d1 += c.charAt(i)*(11-i);
	}
	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	if (dv.charAt(1) != d1)
	{
		return false;
	}
        return true;
}

function valida_CNPJ(s)
{
	var i;
	s = limpa_string(s);
	var c = s.substr(0,12);
	var dv = s.substr(12,2);
	var d1 = 0;
	for (i = 0; i < 12; i++)
	{
		d1 += c.charAt(11-i)*(2+(i % 8));
	}
        if (d1 == 0) return false;
        d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	if (dv.charAt(0) != d1)
	{
		return false;
	}

	d1 *= 2;
	for (i = 0; i < 12; i++)
	{
		d1 += c.charAt(11-i)*(2+((i+1) % 8));
	}
	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	if (dv.charAt(1) != d1)
	{
		return false;
	}
        return true;
}


function valida_numeros(s)
{
	var i; 
	var dif = 0;
	for (i = 0; i < s.length; i++)
	{
		var c = s.charAt(i);
		if (!((c >= "0") && (c <= "9")))
		{
			dif = 1;
		}
	}
	if (dif == 1)
	{
		return false;
	}
	return true;
}

function verif_iguais(s)
{
	var i; 
	var cont = 1;
    s = limpa_string(s);
    for (i = 1; i < s.length; i++){
	     if (s.charAt(i) == s.charAt((i-1))){
	        cont = cont + 1; 
         }
    }
    if (cont == s.length){
       return true ;
    } 
    return false;
}


function mod(num,div){

	var intDiv = (parseInt(num/div))
	return (intDiv * div)-num

}

// -----------------------
function HideLayer(layer) {
if (document.getElementById) // IE5 NN6
	document.getElementById(layer).style.visibility="hidden";
else if (document.layers) // NN4
		eval('document.'+layer+'.visibility="hidden"');
else if (document.all) // IE4
		eval('document.all.'+layer+'.style.visibility="hidden"');
}

// -----------------------
function ShowLayer(layer) {
if (document.getElementById) // IE5 NN6
	document.getElementById(layer).style.visibility="visible";
else if (document.layers) // NN4
		eval('document.'+layer+'.visibility="visible"');
else if (document.all) // IE4
		eval('document.all.'+layer+'.style.visibility="visible"');
}


//--------------------------
function validData(fieldVal)
{
	var datePat = /^(\d{1,2})(\/)(\d{1,2})\2(\d{4})$/;
	var matchArray = fieldVal.match(datePat);
	if (matchArray == null) return false;

	month = matchArray[3];
	day = matchArray[1];
	year = matchArray[4];
	if (month < 1 || month > 12) return false;

	if (day < 1 || day > 31) return false;
	if ((month==4 || month==6 || month==9 || month==11) && day==31) return false;

	if (month == 2)
	{
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 ==0));
		if (day>29 || (day==29 && !isleap)) {return false;}
	}	
	return true;
}





// -----------------------
function URLEncode(strUrl)
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var plaintext = strUrl;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return encoded;
}



// função para displaylimit
// -----------------------------------------------
var ns6=document.getElementById&&!document.all
function restrictinput(maxlength,e,placeholder){
	if (window.event&&event.srcElement.value.length>=maxlength)
		return false
	else if (e.target&&e.target==eval(placeholder)&&e.target.value.length>=maxlength){
			var pressedkey=/[a-zA-Z0-9\.\,\/]/ //detect alphanumeric keys
			if (pressedkey.test(String.fromCharCode(e.which)))
				e.stopPropagation()
			}
}

function countlimit(maxlength,e,placeholder){
	var theform=eval(placeholder)
	var lengthleft=maxlength-theform.value.length
	var placeholderobj=document.all? document.all[placeholder] : document.getElementById(placeholder)
	if (window.event||e.target&&e.target==eval(placeholder)){
		if (lengthleft<0)
			theform.value=theform.value.substring(0,maxlength)
			placeholderobj.innerHTML=lengthleft
	}
}

function displaylimit(theform,thelimit){
	var campo= eval(theform)
	var atual = campo.value.length;
	var limit_text='<b><span id="'+theform.toString()+'">'+(thelimit-atual)+'</span></b> caracteres'
	if (document.all||ns6)
		document.write(limit_text)
		if (document.all){
			eval(theform).onkeypress=function(){ return restrictinput(thelimit,event,theform)}
			eval(theform).onkeyup=function(){ countlimit(thelimit,event,theform)}
		}
	else if (ns6){
		document.body.addEventListener('keypress', function(event) { restrictinput(thelimit,event,theform) }, true); 
		document.body.addEventListener('keyup', function(event) { countlimit(thelimit,event,theform) }, true); 
	}
}
// fim da função displaylimit

// -----------------------------------------------
// function verificaNumerico (strAver, i_f) - verifica se o parâmetro é composto somente de caracteres numéricos o paramametro i_f indica 1 - inteiros, 2 - float, separado por ponto ou vírgula
function verificaNumerico (strAver, i_f)
{
	var i = 0;
	var j = 0;
	var comp;
	var teste = "0123456789.,"
	var subteste;
	var substrAver;
	var flgvg=0;

	// se estiver em branco, retorna Ok
	if (strAver == "")
	{
		return 1;
	}

	if (i_f == 1)
	{
		comp = 10;
	}
	else
	{
		comp = 12;
	}

	// varre cada dígito do número a ser verificado
	while (j < strAver.length)
	{
		substrAver = strAver.charAt (j);

		i = 0;

		// analisa se cada dígito do número a ser verificado é válido
		while (i < comp)
		{
			if (strAver.charAt (j) == teste.charAt (i))
			{
				// se for virgula (ou ponto) decimal, não pode ter duas...
				if ((teste.charAt (i) == ".")  ||
                                    (teste.charAt (i) == ","))
				{
					if (flgvg == 1)
					{
						return 0;
					}
					else
					{
						flgvg = 1;
					}
				}

				break;
			}
			else
			{
				// se o dígito não é válido, retorna ERRO
				if (i == (comp - 1))
				{
					return 0;
				}
			}

			i++;
		}

		j++;
	}

	return 1;
}

