/////////////////////////////////////////////////////////////
//  Documento Java Script                                  //
/////////////////////////////////////////////////////////////

function MostrarCEP()
{
openWin('http://www.correios.com.br/servicos/cep/cep_default.cfm','ShowCep','730','400','1','no');
}

function MascaraCEP (objeto)
{
var caract = new RegExp(/^[0-9/]+$/i);
var caract = caract.test(String.fromCharCode(event.keyCode));
if ((!caract) && (event.keyCode != 13)) {
	event.keyCode=0;
	return;
}else{
	campo = eval (objeto);
	caracteres = '01234567890';
	separacoes = 1;
	separacao1 = '-';
	conjuntos = 2;
	conjunto1 = 5;
	conjunto2 = 3;
	if ((caracteres.search(String.fromCharCode (event.keyCode))!=-1) && campo.value.length < (conjunto1 + conjunto2 + 1))
	{
		if (campo.value.length == conjunto1){
			campo.value = campo.value + separacao1;
		}
	}else{
		event.returnValue = false;
	}
}
}

function Confirma(exibemsg,msg,form) {
var ok = false;
if (msg==""){
	msg = "Confirma operação?";
} 
if (exibemsg){
	ok = (window.confirm(msg));
}else{
	ok = true;
}
if (ok){	
	form.submit(); return true;
}else{
	return false;
}
}

function DefineMaxLength(obj,maxLengt){
var text1 = obj.value;

if ((text1.length>maxLengt)) {
	var aux =  obj.value;
	obj.value = aux.substring(0, maxLengt);
	alert ("Por favor, seu texto não deve ter mais de " + maxLengt.toString() + " caracteres");   
}   
}

/*
function countChars(obj_texto,obj_contador) {
  var text1 = obj_texto.value;
  var text2 = frm.Nome_Orig.value;
	var text3 = frm.Tel_Orig.value;
	 frm.totalCounter.value = 145 - text1.length;
 
	if (text2.length >= 1){
		 frm.totalChars.value = text1.length + text2.length;
		 frm.totalCounter.value = 145 - (text1.length + text2.length );
		 frm.msg_total.value = text1;
	}

	if (text3.length >= 1){
		 frm.totalChars.value = text1.length + text2.length + text3.length;
		 frm.totalCounter.value = 145 - (text1.length + text2.length + text3.length);
		 frm.msg_total.value = text1;
	}

	if ( frm.totalCounter.value < 1) {
		var aux =  frm.Mensagem1.value;
		var chars = aux.length - 1;
		 frm.Mensagem1.value = aux.substring(0, chars);
		alert ("Por favor, sua mensagem não deve ter mais de 145 caracteres");
	}
}

*/
function GetLength(obj){
var text1 = obj.value;
return text1.length
}

function So_Numeros(tipo)
{
if (tipo == 'INT'){
	var caract = new RegExp(/^[0-9/]+$/i); 
}else{
	var caract = new RegExp(/^[0-9 . , /]+$/i); 
}
//var caract = new RegExp(/^[0-9 . , /]+$/i); //Para aceitar mais caracteres.
//var caract = new RegExp(/^[0-9]+$/i); 
var caract = caract.test(String.fromCharCode(event.keyCode));
if ((!caract) && (event.keyCode != 13)) {
             //alert("Caracter inválido : " +String.fromCharCode(event.keyCode)+"\n Entrar somente com números.");
             event.keyCode=0;  
             return;
           }
}

function reLoad(){
	opener.location.reload();
	self.close();
}

function openParentWin(url){
	opener.location.replace(url);
	self.close();
}
function carrega_url(url){
	window.location.replace(url);
}
function openFullScreen(mypage){
	window.open(mypage, 'big', 'fullscreen=yes');
}	

function createModal(url_source,w,h)
{
  var x = window.showModalDialog(url_source,"","dialogWidth:"+w+"px; dialogHeight:"+h+"px; center:yes; help:no; resizable:no; status:no");
}

function quantidade(tipo, obj){
	if (obj.value==""){
		obj.value="0";
	}
	if (tipo == "+")
	{
		obj.value = parseInt(obj.value) + 1;
	}
	else if (tipo == "-")
	{
		if (parseInt(obj.value) > 1)
		{
			obj.value = parseInt(obj.value) - 1;
		}
	}
}
function openWin(mypage,myname,w,h,scroll,resizable){
  var win= null;
  var winl = (screen.width-w)/2;
  var wint = (screen.height-h)/2;
  var settings  ='height='+h+',';
      settings +='width='+w+',';
      settings +='top='+wint+',';
      settings +='left='+winl+',';	  
      settings +='scrollbars='+scroll+',';
      settings +='resizable='+resizable;
  win=window.open(mypage,myname,settings);
  if(parseInt(navigator.appVersion) >= 4){win.window.focus();}
}

function quantidade(tipo, obj){
	if (obj.value==""){
		obj.value="0";
	}
	if (tipo == "+")
	{
		obj.value = parseInt(obj.value) + 1;
	}
	else if (tipo == "-")
	{
		if (parseInt(obj.value) > 1)
		{
			obj.value = parseInt(obj.value) - 1;
		}
	}
}
/*
function add_Item_Cesta(parent,id_produto,obj,origem){
	//origem=="cesta" - carrega a cesta ao incluir um item
	if ((obj.value == null) || (obj.value == "")) {
		obj.value="1";
	}
	if  ((parseInt(obj.value) > 0) || (origem=="cesta")){
		qtde = obj.value;
		obj.value="";
		if (origem!=""){
			var_url = "&or="+origem;
		}else{
			var_url = "";
		}
		if (parent==""){
			window.location.replace('../shopping/manutencao_cesta.php?op=atualiza&id='+id_produto+'&qt='+qtde+var_url);
		}else{
			opener.location.replace('../shopping/manutencao_cesta.php?op=atualiza&id='+id_produto+'&qt='+qtde+var_url);
			self.close();		
		}
	}else{
		alert("Informe a quantidade de livros");
		obj.focus();
	}	
}
*/
function voltar() {
	history.go(-1);
}
function inicio(){
	window.open('index.php', 'big', 'fullscreen=yes');
}
function link(end){

window.open(end,"nova","height=300,width=500,left=20,top=20");

}

function emailCheck (obj) {
	if ((obj.value == null) || (obj.value == "")) {
		return true;
	}
	emailStr = new String(obj.value);

	/* The following variable tells the rest of the function whether or not
	to verify that the address ends in a two-letter country or well-known
	TLD.  1 means check it, 0 means don't. */

	var checkTLD=1;

	/* The following is the list of known TLDs that an e-mail address must end with. */
	
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
	
	/* The following pattern is used to check if the entered e-mail address
	fits the user@domain format.  It also is used to separate the username
	from the domain. */
	
	var emailPat=/^(.+)@(.+)$/;
	
	/* The following string represents the pattern for matching all special
	characters.  We don't want to allow special characters in the address.
	These characters include ( ) < > @ , ; : \ " . [ ] */
	
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	
	/* The following string represents the range of characters allowed in a
	username or domainname.  It really states which chars aren't allowed.*/
	
	var validChars="\[^\\s" + specialChars + "\]";
	
	/* The following pattern applies if the "user" is a quoted string (in
	which case, there are no rules about which characters are allowed
	and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
	is a legal e-mail address. */
	
	var quotedUser="(\"[^\"]*\")";
	
	/* The following pattern applies for domains that are IP addresses,
	rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
	e-mail address. NOTE: The square brackets are required. */
	
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
	
	/* The following string represents an atom (basically a series of non-special characters.) */
	
	var atom=validChars + '+';
	
	/* The following string represents one word in the typical username.
	For example, in john.doe@somewhere.com, john and doe are words.
	Basically, a word is either an atom or quoted string. */
	
	var word="(" + atom + "|" + quotedUser + ")";
	
	// The following pattern describes the structure of the user
	
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
	
	/* The following pattern describes the structure of a normal symbolic
	domain, as opposed to ipDomainPat, shown above. */
	
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
	
	/* Finally, let's start trying to figure out if the supplied address is valid. */
	
	/* Begin with the coarse pattern to simply break up user@domain into
	different pieces that are easy to analyze. */
	
	var matchArray=emailStr.match(emailPat);

	if (matchArray==null) {
		/* Too many/few @'s or something; basically, this address doesn't
		even fit the general mould of a valid e-mail address. */		
		alert("Endereço de email parece incorreto (verificar @ e .'s)");
		obj.focus();
		obj.select();
		return false;
	}
	
	var user=matchArray[1];
	var domain=matchArray[2];

	// Start by checking that only basic ASCII characters are in the strings (0-127).

	for (i=0; i<user.length; i++) {
		if (user.charCodeAt(i)>127) {
			alert("O nome do usuário contêm caracteres inválidos.");
			obj.focus();
			obj.select();
			return false;
		}
	}
	
	for (i=0; i<domain.length; i++) {
		if (domain.charCodeAt(i)>127) {
			alert("O domínio contêm caracteres inválidos.");
			obj.focus();
			obj.select();
			return false;
   		}
	}

	// See if "user" is valid

	if (user.match(userPat)==null) {
	// user is not valid
		alert("O nome do usuário parerce não ser válido.");
		obj.focus();
		obj.select();
		return false;
	}

	/* if the e-mail address is at an IP address (as opposed to a symbolic
	host name) make sure the IP address is valid. */

	var IPArray=domain.match(ipDomainPat);
	if (IPArray!=null) {
	// this is an IP address
		for (var i=1;i<=4;i++) {
			if (IPArray[i]>255) {
				alert("Endereço IP de destino é inválido!");
				obj.focus();
				obj.select();
				return false;
			}
		}		
		return true;
	}

	// Domain is symbolic name.  Check if it's valid.
	
	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;
	for (i=0;i<len;i++) {
		if (domArr[i].search(atomPat)==-1) {
			alert("O nome do domínio parece não ser válido.");
			obj.focus();
			obj.select();
			return false;
		}
	}

	/* domain name seems valid, but now make sure that it ends in a
	known top-level domain (like com, edu, gov) or a two-letter word,
	representing country (uk, nl), and that there's a hostname preceding
	the domain or country. */
	
	if (checkTLD && domArr[domArr.length-1].length!=2 && domArr[domArr.length-1].search(knownDomsPat)==-1) {
		alert("O endereço tem de finalizar com um domínio bem conhecido ou com duas letras do país");
		obj.focus();
		obj.select();
		return false;
	}

	// Make sure there's a host name preceding the domain.
	
	if (len<2) {
		alert("Está faltando o hostname!");
		obj.focus();
		obj.select();
		return false;
	}

	// If we've gotten this far, everything's valid!
	return true;
}

//Função para Cálculo do Digito do CPF/CNPJ
/*
function VerificaCPF_CNPJ(obj)
{
 if (obj.value == "")
 {
  return true
 }
 if (ConfereCIC(obj))
 {
    return true;
 }
 else
 {

     obj.focus();
     obj.select();
     return false;

 }
}

function DigitoCPFCNPJ(numCIC) {
        var numDois = numCIC.substring(numCIC.length-2, numCIC.length);
        var novoCIC = numCIC.substring(0, numCIC.length-2);
        switch (numCIC.length){
                case 11 :
                        numLim = 11;
                        break;
                case 14 :
                        numLim = 9;
                        break;
                default : return false;
        }
        //
        var numSoma = 0;
        var Fator = 1;
        for (var i=novoCIC.length-1; i>=0 ; i--) {
                Fator = Fator + 1;
                if (Fator > numLim) {
                        Fator = 2;
                }
                numSoma = numSoma + (Fator * Number(novoCIC.substring(i, i+1)));
        }
        numSoma = numSoma/11;
        var numResto = Math.round( 11 * (numSoma - Math.floor(numSoma)));
    if (numResto > 1) {
                numResto = 11 - numResto;
    }
    else {
                numResto = 0;
    }
    //-- Primeiro dígito calculado.  Fará parte do novo cálculo.
    //--
    var numDigito = String(numResto);
    novoCIC = novoCIC.concat(numResto);
    //--
        numSoma = 0;
        Fator = 1;
        for (var i=novoCIC.length-1; i>=0 ; i--) {
                Fator = Fator + 1;
                if (Fator > numLim) {
                        Fator = 2;
                }
                numSoma = numSoma + (Fator * Number(novoCIC.substring(i, i+1)));
        }
        numSoma = numSoma/11;
        numResto = numResto = Math.round( 11 * (numSoma - Math.floor(numSoma)));
    if (numResto > 1) {
                numResto = 11 - numResto;
    }
    else {
                numResto = 0;
    }
        //-- Segundo dígito calculado.
        numDigito = numDigito.concat(numResto);
        //
        if (numDigito == numDois) {
                return true;
        }
        else {
                return false;
        }
}
//--< Fim da Função >--

//-- Retorna uma string apenas com os números da string enviada

function ApenasNum(strParm) {
        strParm = String(strParm);
        var chrPrt = "0";
        var strRet = "";
        var j=0;
        for (var i=0; i < strParm.length; i++) {
                chrPrt = strParm.substring(i, i+1);
                if ( chrPrt.match(/\d/) ) {
                        if (j==0) {
                                strRet = chrPrt;
                                j=1;
                        }
                        else {
                                strRet = strRet.concat(chrPrt);
                        }
                }
        }
        return strRet;
}
//--< Fim da Função >--

//-- Somente aceita os caracteres válidos para CPF e CNPJ.
function PreencheCIC(objCIC) {
        var chrP = objCIC.value.substring(objCIC.value.length-1, objCIC.value.length);

        if ( !chrP.match(/[0-9]/) && !chrP.match(/[\/.-]/) ) {
                objCIC.value = objCIC.value.substring(0, objCIC.value.length-1);
                return false;
        }
        return true;
}
//--< Fim da Função >--

function FormataCIC (numCIC) {
        numCIC = String(numCIC);
        switch (numCIC.length){
        case 11 :
                return numCIC.substring(0,3) + "." + numCIC.substring(3,6) + "." + numCIC.substring(6,9) + "-" + numCIC.substring(9,11);
        case 14 :
                return numCIC.substring(0,2) + "." + numCIC.substring(2,5) + "." + numCIC.substring(5,8) + "/" + numCIC.substring(8,12) + "-" + numCIC.substring(12,14);
        default :
                alert("Tamanho incorreto do CPF ou CNPJ!");
                return "";
        }
}

//-- Remove os sinais, deixando apenas os números e reconstroi o CPF ou CNPJ, verificando a validade
//-- Recebe como parâmetros o número do CPF ou CNPJ, com ou sem sinais e o atualiza com sinais é validado.

function ConfereCIC(objCIC) {
        if (objCIC.value == null) {
                alert("Preenchimento obrigatório do CPF ou CNPJ");
                return false;
        }
        var strCPFPat  = /^\d{3}\.\d{3}\.\d{3}-\d{2}$/;
        var strCNPJPat = /^\d{2}\.\d{3}\.\d{3}\/\d{4}-\d{2}$/;

        numCPFCNPJ = ApenasNum(objCIC.value);

        if (!DigitoCPFCNPJ(numCPFCNPJ)) {
                alert("Atenção o Dígito verificador do CPF ou CNPJ é inválido!");
                return false;
        }

        objCIC.value = FormataCIC(numCPFCNPJ);

        if (objCIC.value.match(strCNPJPat)) {
                objCIC.value = numCPFCNPJ
                return true;
        }
        else if (objCIC.value.match(strCPFPat)) {
                objCIC.value = numCPFCNPJ
                return true;
        }
        else {
                alert("Digite um CPF ou CNPJ válido!");
                objCIC.value = numCPFCNPJ
                return false;
        }
}
*/
//Fim da Função para Cálculo do Digito do CPF/CNPJ

/////////////////////////////////////////////////////////////
// Caixa de Mensagem
function alertar(mensagem)
{
 alert(mensagem)
 return mensagem;
 }
////////////////////////////////////////////////////////////
// Validar Formulário Interessado
function validate(f)
{

  if (f.elements["NOME_INT"].value == "") {
    f.elements["NOME_INT"].focus();
    alert("Preencha o campo Nome do Interessado")
    return false;
  }
  if (f.elements["CPF_CNPJ_INT"].value == "") {
    f.elements["CPF_CNPJ_INT"].focus();
    alert("Preencha o campo CPF/CNPJ")
    return false;
  }
  if (f.elements["PWD_INT"].value == "") {
    f.elements["PWD_INT"].focus();
    alert("Preencha o campo Senha")
    return false;
  }
  if (f.elements["PWD_INT"].value.length < 6)
  {
        f.elements["PWD_INT"].focus();
        alert("A Senha deve conter entre 6 e 8 dígitos");
        return false;
  }
return true;
}
  function check_date(field)
   {
      var checkstr = "0123456789";
      var DateField = field;
      var Datevalue = "";
      var DateTemp = "";
      var seperator = "/";
      var day;
      var month;
      var year;
      var leap = 0;
      var err = 0;
      var i;
      err = 0;
      DateValue = DateField.value;
      /* Deletando todos os caracteres exceto o 0..9 */
      for (i = 0; i < DateValue.length; i++)
      {
         if (checkstr.indexOf(DateValue.substr(i,1)) >= 0)
            {
                DateTemp = DateTemp + DateValue.substr(i,1);
            }
      }
      DateValue = DateTemp;
      /* Exectutando a data para 8 digitos - string*/
      /* if entrada do ano com 2-digitos / exemplo 20xx */
      if (DateValue.length == 6)
         {
            DateValue = DateValue.substr(0,4) + '20' + DateValue.substr(4,2);
         }
      if (DateValue.length != 8)
         {
            err = 19;
         }
      /* Se o ano for errado = 0000 */
      year = DateValue.substr(4,4);
      if (year == 0)
         {
            err = 20;
         }
      /* Validando o mês*/
      month = DateValue.substr(2,2);
      if ((month < 1) || (month > 12))
         {
            err = 21;
         }
      /* Validando o dia*/
      day = DateValue.substr(0,2);
      if (day < 1)
         {
            err = 22;
         }
      /* Validando ano Bissexto / fevereiro / dia */
      if ((year % 4 == 0) || (year % 100 == 0) || (year % 400 == 0))
         {
            leap = 1;
         }
      if ((month == 2) && (leap == 1) && (day > 29))
         {
            err = 23;
         }
      if ((month == 2) && (leap != 1) && (day > 28))
         {
            err = 24;
         }
      /* Validando o mês */
      if ((day > 31) && ((month == "01") || (month == "03") || (month == "05") || (month == "07") || (month == "08") || (month == "10") || (month == "12")))
         {
            err = 25;
         }
      if ((day > 30) && ((month == "04") || (month == "06") || (month == "09") || (month == "11")))
         {
            err = 26;
         }
      /* if 00 houvendo entrada, sem erros */
      if ((day == 0) && (month == 0) && (year == 00))
         {
            err = 0; day = ""; month = ""; year = ""; seperator = "";
         }
      /* if sem erros, escrevo a data completa no Input-Field (e.x. 13/12/2001) */
      if (err == 0)
         {
            DateField.value = day + seperator + month + seperator + year;
			return true;
         }
      /* Mensagem de erro if err != 0 */
      else
         {
            alert("Atenção, sua Data está Incorreta!");
            DateField.select();
            DateField.focus();
			return false
         }
}
//Fim da Função para Máscara e Validação de Datas
///////////////////////////////////////////////////////////
//Início da Função Formata Valores em Reais
//Chamada: onKeyPress="return(FormataReais(this,'.',',',event))"
function FormataReais(fld, milSep, decSep, e) {
var sep = 0;
var key = '';
var i = j = 0;
var len = len2 = 0;
var strCheck = '0123456789';
var aux = aux2 = '';
var whichCode = (window.Event) ? e.which : e.keyCode;
if (whichCode == 13) return true;
key = String.fromCharCode(whichCode);  // Valor para o código da Chave
if (strCheck.indexOf(key) == -1) return false;  // Chave inválida
len = fld.value.length;
for(i = 0; i < len; i++)
if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
aux = '';
for(; i < len; i++)
if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
aux += key;
len = aux.length;
if (len == 0) fld.value = '';
if (len == 1) fld.value = '0'+ decSep + '0' + aux;
if (len == 2) fld.value = '0'+ decSep + aux;
if (len > 2) {
aux2 = '';
for (j = 0, i = len - 3; i >= 0; i--) {
if (j == 3) {
aux2 += milSep;
j = 0;
}
aux2 += aux.charAt(i);
j++;
}
fld.value = '';
len2 = aux2.length;
for (i = len2 - 1; i >= 0; i--)
fld.value += aux2.charAt(i);
fld.value += decSep + aux.substr(len - 2, len);
}
return false;
}

function strtran(strField,strSearched,strReplacement){
	var sValue;
    sValue = strField.value;
    // Limpa todos os caracteres de formatação que
    // já estiverem no campo.
    sValue = sValue.toString().replace( strSearched, strReplacement );
	strField.value = sValue;
}	  
//Fim da Função Formata Valores em Reais
///////////////////////////////////////////////////////////
//Início da Função Máscaras Gerais
//Chamadas:<input type="text" name="nomeCampo" maxlength="20" size="20"
             //onkeypress="return txtBoxFormat(document.Form, 'nomeCampo', '99.999999999/9999-99', event);">
function txtBoxFormat(objForm, strField, 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 = objForm[strField].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( " ", "" );
      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++;
      }

      objForm[strField].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;
      }
    }
//Fim da Função Máscaras Gerais
//////////////////////////////////////////////////////////