//
// Funções Pop-up
//

function showswf(swf,width,height)
{
	document.write('<object type="application/x-shockwave-flash" width="' + width + '" height="' + height + '" data="' + swf + '">');
	document.write('<param name="movie" value="' + swf + '" />');
	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="' + swf + '" quality="high" type="application/x-shockwave-flash" width="' + width + '" height="' + height + '" wmode="transparent"></embed>');
	document.write('</object>');
}


function pop(link, name, w, h, s)
{
  v=window.open(link, name, "directories=no,height=" + h + ",width=" + w +
  ",hotkeys=no,location=no,menubar=no,resizable=no,scrollbars=" + s +
  ",status=no,toolbar=no,copyhistory=no,screenX=5,screenY=5,top=10,left=10");
  v.focus();
} 

// PopUp Campanha
function fWinImg(vImg,vTitulo) 
{
	//vTitulo="Promocao"
	vJanela="Promocao"
	vImg="Images/"+vImg
	oWindow=window.open("",vJanela,"left=250,top=250,width=288,height=300,resizable=no,menubar=no,toolbar=no,location=no,directories=no,scrollbars=no")
	oWindow.document.open()
	oWindow.document.write("<html><head><title>"+vTitulo+"</title></head><body topmargin=0 leftmargin=0 bgcolor=#dadbef onload='window.resizeTo(window.img.width+5,window.img.height+50)'>")
	oWindow.document.write("<table border=0 width=100% height=100% cellspacing=0 cellpadding=0>")
	oWindow.document.write("<tr><td align=center valign=middle><img id=img src='"+vImg+"'></td></tr></table>")
	oWindow.document.write("</body></html>")
	oWindow.document.close()
	oWindow.focus()
}

function get_random()
{
    var ranNum= Math.round(Math.random()*4);
    return ranNum;
}

function jscategoria_C24()
{
    //window.open('popup/popup_peso_aproximado.htm','Banner'+get_random(),'left=50,top=50,width=400,height=440,resizable=no,menubar=no,toolbar=no,location=no,directories=no,scrollbars=no')
}

//
// Funções Transacionais
//
function fKeyFilter(ki,ke)
{
/*
Objetivo:
  Controlar a entrada de dados no elemento
Parametros:
  ki (string) com caracteres permitidos
  ke (string) com caracteres a ignorar
Include/Exclude suportados:
  [TEXTSTD]     AB..Z ab..z (tenta converte alguns caracteres especiais para correspondente sem acento)
  [TEXTEXT]     AB..Z ab..z caracteres acentuados
  [SINGLEQUOTE] aspa simples (obs: cuidado ao usar a string resultante entre linguagens)
  [DOUBLEQUOTE] aspa dupla   (obs: cuidado ao usar a string resultante entre linguagens)
  [INT]         0123456789
  [UPPER]       apenas no caracter digitado
  [LOWER]       apenas no caracter digitado
  [ENTER]       enter sozinho apenas abilita/desabilita
  [ENTER:xxx]   enter com nome do elemento executa click no elemento
Observacoes:
- Qualquer caracter indicado fora dos filtros acima citados sofre a acao correspondente
Exemplos:
  Permite numeros inteiros e texto sem caracteres acentuados/especiais, mudando para minuscula e eliminando @
    onkeypress = "keyFilter('[TEXTSTD][INT][LOWER]','@')"
  Permite apenas numeros de 1 a 7
    onkeypress = "keyFilter('[INT]','089')"
  Permite apenas numeros de 1 a 3 e ignora o Enter
    onkeypress = "keyFilter('123','[ENTER]')"
  Permite numeros, caracteres "@-_." e texto com caracteres acentuados e eliminando espaco, tipico de um email
    onkeypress = "keyFilter('[TEXTEXT][INT][LOWER]@-_.',' ')"
*/
	// captura tecla
	var kc,kcn,ec,iend,er,kf,i,ii,pi,pf;
	kc = event.keyCode;
	kcn = 0;
	ec = "";
	// consistencia dos parametros
	var er = "ERRO: keyFilter(ki,ke)\n"
		+ "\nki (string) com tipos e caracteres permitidos;"
		+ "\nke (string) com tipos e caracteres a ignorar;"
		+ "\nMaiores detalhes na funcao.";
	if(!ki>"" && !ke>"") // sem parametros
	{
		event.keyCode = 0;
		alert(er);
		return false;
	} else {
		if(typeof(ki)!="string")
		{
			event.keyCode = 0;
			alert(er);
			return false;
		}
	}
	if(ke>"")
		iend = typeof(ki)=="string" ? 2 : 1;
	else
		iend = 1;
	// loop 0 = Inclusao, 1 = Exclusao
	for(i=0;i<iend;i++)
	{
		kf = (i==0) ? ki : ke; // 0 = Inclusao, 1 = Exclusao
		if(kf.indexOf("[TEXTSTD]")>-1)
		{
			// tenta converte alguns caracteres especiais para correspondente sem acento
			kf = kf.replace("[TEXTSTD]","");
			if(kc==32) kcn = (i==0) ? 32 : 0; //espaco
			if((kc>=65 && kc<=90) || (kc>=97 && kc<=122)) kcn = (i==0) ? kc : 0; // A..Z a..z
			if(kc>=192 && kc<=197) kcn = (i==0) ? 65 : 0; //A
			if(kc>=224 && kc<=229) kcn = (i==0) ? 97 : 0; //a
			if(kc>=200 && kc<=203) kcn = (i==0) ? 69 : 0; //E
			if(kc>=232 && kc<=235) kcn = (i==0) ? 101 : 0; //e
			if(kc>=204 && kc<=207) kcn = (i==0) ? 73 : 0; //I
			if(kc>=236 && kc<=239) kcn = (i==0) ? 105 : 0; //i
			if(kc>=210 && kc<=214) kcn = (i==0) ? 79 : 0; //O
			if(kc==240 || (kc>=242 && kc<=246)) kcn = (i==0) ? 111 : 0; //o
			if(kc>=217 && kc<=220) kcn = (i==0) ? 85 : 0; //U
			if(kc>=249 && kc<=252) kcn = (i==0) ? 117 : 0; //u
			if(kc==199) kcn = (i==0) ? 67 : 0; //C
			if(kc==231) kcn = (i==0) ? 99 : 0; //c
			if(kc==209) kcn = 78; //N
			if(kc==241) kcn = 110; //n
			if(kc==221) kcn = 89; //Y
			if(kc==253 || kc==255) kcn = (i==0) ? 121 : 0; //y
		}
		if(kf.indexOf("[TEXTEXT]")>-1)
		{
			kf = kf.replace("[TEXTEXT]","");
			if(kc==32) kcn = (i==0) ? 32 : 0; //espaco
			if((kc>=65 && kc<=90) || (kc>=97 && kc<=122) || (kc>=192 && kc<=255)) kcn = (i==0) ? kc : 0;
		}
		if(kf.indexOf("[DOUBLEQUOTE]")>-1)
		{
			kf = kf.replace("[DOUBLEQUOTE]","");
			if(kc==34) kcn = (i==0) ? kc : 0;
		}
		if(kf.indexOf("[SINGLEQUOTE]")>-1)
		{
			kf = kf.replace("[SINGLEQUOTE]","");
			if(kc==39) kcn = (i==0) ? kc : 0;
		}
		if(kf.indexOf("[INT]")>-1)
		{
			kf = kf.replace("[INT]","");
			if(kc>47 && kc<58) kcn = (i==0) ? kc : 0;
		}
		if(kf.indexOf("[UPPER]")>-1)
		{
			kf = kf.replace("[UPPER]","");
			vChar = String.fromCharCode(kc);
			vChar = (i==0) ? vChar.toUpperCase().charCodeAt(0) : vChar.toLowerCase().charCodeAt(0);
			kcn = vChar;
		}
		if(kf.indexOf("[LOWER]")>-1)
		{
			kf = kf.replace("[LOWER]","");
			vChar = String.fromCharCode(kc);
			vChar = (i==0) ? vChar.toLowerCase().charCodeAt(0) : vChar.toUpperCase().charCodeAt(0);
			kcn = vChar;
		}
		
		pi = kf.indexOf("[ENTER");
	
		if(pi>-1)
		{
			pf = kf.indexOf("]",pi);
			ec = kf.substring(pi+7,pf);			
			if(ec!=']')
			{
				kf = kf.replace("[ENTER:"+ec+"]","");
				if(kc==13)
					kcn = 0;
				else
					ec = "";
			}
			else
			{
				ec = "";
				kf = kf.replace("[ENTER]","");
				if (kc==13) {kcn = 13;}
			}
		}
		// loop para caracteres avulsos
		for(ii=0;ii<kf.length;ii++)
			if(kf.indexOf(String.fromCharCode(kc))>-1) kcn = (i==0) ? kc : 0;
	}
	event.keyCode = kcn;
	if(ec!="")
	{	
		document.getElementById(ec).click();		
	}
}

function maskPaste(objEvent) 
{
var strPasteData = window.clipboardData.getData("Text");
var objInput = objEvent.srcElement;
var i=0;
var letra;
	if (!isValid(strPasteData)) {

		for(i=0;i<strPasteData.length - 1;i++)
			{
				letra=strPasteData.charAt(i);
	
				if(!isValid(letra))
				{
					break;
				}
			}
			
		//alert("Caracter Inválido para a busca na palavra: " + letra);
		objInput.focus();
		return false;
		}
}  

function showFininvest()
{
	v = window.open('https://www.fininvest.com.br/faleconosco_mercadorama.cfm','_winFinin');
	v.focus();
}	

// Adiciona um item ao carrinho
function processaCarrinho(p_strSKU, p_strCat, p_strSubCat)
{
	// Captura caixa de texto com Qtd
	var objQtd = eval('document.frmGeneral.txtQtd_' + p_strSKU);
	// Captura imagem do Tick de produto no basket
	var objTickBasket = document.getElementById('imgTickBasket_' + p_strSKU);
	
	// Verifica a Qtd
	if (IsNumber(objQtd.value) && objQtd.value != "")
	{
		// Adicionando item ao Basket
		iFrameMiniBasket.location.href='nac_addBasket.aspx?Categoria='+p_strCat+'&SubCategoria='+p_strSubCat+'&Produto='+p_strSKU+'&Qtd=' + objQtd.value + '&PaginaDestino=nac_MiniBasket.aspx';
		// Mostrando imagem do Tick
		if (objTickBasket)
			objTickBasket.style.visibility = 'visible';
	}
	else
	{
		// Qtd inválida
		alert("Por favor, informe uma Qtd. válida");
		objQtd.focus();
	}

	return;
}


function processaFrete(p_strGuid)
{
	window.location.href='nac_Fechamento1.aspx?entrega=' + p_strGuid;
}


// Aumenta ou diminiu Qtd de um item
function updQuantidade(p_strField, p_strType){

	var qtde
	
	qtde = eval('document.frmGeneral.' + p_strField + '.value');
	obj = eval('document.frmGeneral.' + p_strField)
	
	if (qtde != (qtde/1) ) {
		qtde = 0;
	}

	if 	(p_strType == 0){		// Plus
		qtde++;
	}else if( p_strType == 1){	// Minus
		qtde--;
	}	
	

	if (qtde > 99){
		qtde--;
	}else if(qtde <= 0){
		qtde = 1;
	}
	
	obj.value = qtde
}


// Valida o Basket
function validaBasket(p_frmBasket)
{
	// Percorrendo os controles do formulario
	for (i=0; i<=p_frmBasket.length-1; i++)
	{
		// Só valida os controles de Qtd
		if (p_frmBasket[i].name.substr(0, 7) == "txtQtd_")
		{
			// Valida se é numero ou se está vazio
			if (!IsNumber(p_frmBasket[i].value) || p_frmBasket[i].value == "")
			{
				alert("Por favor, informe uma Qtd. válida");
				p_frmBasket[i].focus();
				return false;
			}
					
		}
	}

	return true;
}


// Valida a data de validade do cartao
function ValidaDataValidade(p_dtValidade)
{

	// Valida a presenca da barra
	if (p_dtValidade.split("/").length != 2)
		return false;

	// Valida se Ano e Mes são numericos
	if (!IsNumber(p_dtValidade.split("/")[0]))
		return false;
	if (!IsNumber(p_dtValidade.split("/")[1]))
		return false;
		
	var charMes = new String(p_dtValidade.split("/")[0]);
	
	if (charMes.length != 2) 
		return false;
		
	var intMes = new Number(p_dtValidade.split("/")[0]);
	var intAno = new Number(p_dtValidade.split("/")[1]);
	var dtData = new Date();
	var intMesInicial = new Number();

	// Captura mes inicial de validacao
	if (intAno == dtData.getFullYear())
		intMesInicial = dtData.getMonth()+1;
	else
		intMesInicial = 1;

	// Valida se Mes é maior que mes inicial ou se o mes nao possui quatro caracteres
	if (intMes < intMesInicial)
		return false;
	
	if (intMes > 12) 
		return false;
		
	if (intAno.toString().length != 4)
		return false;
	
	// Valida se Ano é maior que ano atual
	if (intAno < dtData.getFullYear() || intAno > 9999)
		return false;

	return true;
}

// Chama evento Click do botão
function ClickButton(idButton)
{
		//document.frmGeneral.onsubmit = "return false";
	// Captura tecla
	var l_strTecla
	if(document.all)
		l_strTecla = event.keyCode;
	else
       l_strTecla = event.which;

	// Se tecla for Enter, chama evento Click
	if (l_strTecla == 13)
	{
		var objButton = document.getElementById(idButton);
		//objButton.focus();
/*
		if(document.all)
			event.keyCode = 0;
		else
			event.which = 0;
*/
		//objButton.onclick = "return false";
		objButton.focus();
		objButton.click();
	}
}


//
// Funções Matemáticas
//

// Verifica se uma variável só possui números.
function IsNumber(numero)
{
   var i;
   var nPonto = 0;

   for (i = 0; i < numero.length; i++)
   {
      if (numero.charAt(i) < "0" || numero.charAt(i) > "9")
      {
	      return false;
      }
   }
   return true;
}

// Verifica se uma variável só possui números.
function IsDecimal(numero, precisao)
{
	var ParteInt, ParteDec;

	//Captura parte inteira
	ParteInt = numero.split(",")[0];

	//Captura parte decimal
	if (numero.split(",").length == 2)
		ParteDec = numero.split(",")[1];
	else if (numero.split(",").length == 1)
		ParteDec = "0";
	else
		return false;


	// Se encontrar ".", verifica formatação
	if (ParteInt.indexOf(".") != -1)
	{
		// Quebra por "." para verificar separator de milhar
		arrParteInt = ParteInt.split(".");
		for(j=0; j <= arrParteInt.length-1; j++)
		{
			// Verifica se parte inteira é numerica
			if (!IsNumber(arrParteInt[j]))
				return false;

			if (j == 0)
			{
				if (arrParteInt[j].length < 1 || arrParteInt[j].length > 3)
					return false;
			}
			else
			{
				if (arrParteInt[j].length != 3)
					return false;
			}
		}
	}
	// Se nao encontrar ".", só verifica se é numero
	else
	{
		if (!IsNumber(ParteInt))
			return false;
	}

	// Verifica se parte decimal é numerica
	if (!IsNumber(ParteDec))
		return false;

	// Verifica se prescisao do numero é maior que a permitida
	if (ParteDec.length > precisao)
		return false;

	// Verifica se as partes do numero nao estão vazias
	if (ParteDec == "")
		return false;


	return true;
}


//
// Funções para verificação de CPF ou CNPJ
//

//Função para Cálculo do Digito do CPF/CNPJ
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;
}

var algUnico, i;
algUnico = true;
	for (i=1; i<11; i++)
	{
		algUnico = algUnico && (numCPFCNPJ.charAt(i-1) == numCPFCNPJ.charAt(i));
	}
	return (!algUnico);

//objCIC.value = FormataCIC(numCPFCNPJ);
strCIC = FormataCIC(numCPFCNPJ);

if (strCIC.match(strCNPJPat)) {
 return true;
}
else if (strCIC.match(strCPFPat)) {
 return true;
}
else {
 //alert("Digite um CPF ou CNPJ válido!");
 return false;
}
}
//Fim da Função para Cálculo do Digito do CPF/CNPJ
