function fn2ViaBoleto(PEDIDO)
{
   var pstrpagina = "boleto.aspx?pedido=" + PEDIDO;
   var largura = "700"
   var altura = "600"
   var barra_rolagem = 'yes';
   
   abrePopUp(pstrpagina, largura, altura, barra_rolagem);
}

function ondeComprar(Produto)
{
   var pstrpagina = "OndeComprar.aspx?Produto=" + Produto;
   var largura = "400"
   var altura = "500"
   var barra_rolagem = 'yes';
   
   abrePopUp(pstrpagina, largura, altura, barra_rolagem);
}

function fnIndique(vAuxCProd,vAuxDProd)
{
   var pstrpagina = "indiqueProd.aspx?cp=" + vAuxCProd + "&dp=" + vAuxDProd;
   var largura = "600"
   var altura = "300"
   var barra_rolagem = 'yes';
   
   abrePopUp(pstrpagina, largura, altura, barra_rolagem);
}

function abreNovoEndereco(pagina)
{
     abrePopUp(pagina, "500", "600", "yes"); 
}

function abrePopPagamento(pUrl, pNomeJanela, pLargura, pAltura) {
    Retorno = window.showModalDialog('PagamentoPopup.aspx?url=' + pUrl, pNomeJanela, 'dialogWidth=' + pLargura + 'px; dialogHeight=' + pAltura + 'px; status=no; toolbars=no; help=no; scroll=Yes; center=Yes');
    if(Retorno)
    {
        return true;
    }
    else
    {
        return false;
    }
}


/// <sumary>
/// 	OBJETIVO: Valida e-mail
/// 	AUTOR:	  GK_MIYASAKA - 26/09/2007
/// 	EXEMPLO:  <input id="txtEMail" type="text" onblur="validaMail(this.id)" />
/// </sumary>
function validaMail(valor)
{
	var mail = document.getElementById(valor).value;
	var emailfilter = /^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i;
	var returnval = emailfilter.test(mail);
	if (returnval == false)
	{
		alert("Por Favor entre com um E-mail valido!");
		document.getElementById(valor).focus();
	}
	else
	{
		var string_email = mail.substr(mail.indexOf("@"), mail.length);		
		
		var meuVet = new Array();
		meuVet = string_email.split(".");
		
		if ((meuVet.length == 5) || ((string_email.length-1) >= 255)) 
		{
			alert("Por Favor entre com um E-mail valido!");
			document.getElementById(valor).focus();
			return;
		}
		
		for (var i = 0; i <= meuVet.length-1; i++)
		{
			if((meuVet[i].length) > 63)
			{
				alert("Por Favor entre com um E-mail valido!");
				document.getElementById(valor).focus();
//				alert('O trecho ' + meuVet[i] + ' eh invalido. Por favor, corrija.');
				return;
			}
		}
	}
}

/// <sumary>
/// 	OBJETIVO: Valida tamanho máximo de um campo (função MAXLENGTH para textarea)
/// 	AUTOR:	  GK_MIYASAKA - 26/09/2007
/// 	EXEMPLO:  <textarea id="txtRelatorio" onkeypress="ValidaTamanhoCampo(this.id, 'Relatorio', 4000)"></textarea>
/// </sumary>

function ValidaTamanhoCampo(campo, nome, tamanho)
{
	if(document.getElementById(campo).innerText.length >= tamanho)
	{
		alert('O campo ' + nome + ' ultrapassou o limite de ' + tamanho + ' caracteres. Por favor, corrija.');
		document.getElementById(campo).focus();
		event.keyCode = 0;
	}
}

/// <sumary>
/// 	OBJETIVO:	Função para aceitar somente letras e numeros, não aceita caracteres especiais
/// 	AUTOR:		GK_MIYASAKA - 16/08/2007
/// 	EXEMPLO:	<input id="txtRgPreposto" type="text" onblur="return soNumeroLetras(this.id)" />
/// </sumary>

function soNumeroLetras(campo)
{		
	var iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?";	
	for (var i = 0; i < document.getElementById(campo).value.length; i++) 
	{
  		if (iChars.indexOf(document.getElementById(campo).value.charAt(i)) != -1) 
		{
  			alert("O campo possui caracteres especiais, por favor, preencha novamente!");
			document.getElementById(campo).value = "";
			document.getElementById(campo).focus();
  			return false;
  		}
	}	
}

/// <sumary>
/// 	OBJETIVO:	Formatar um campo Hora
/// 	AUTOR:		GK_MIYASAKA - 16/08/2007
/// 	EXEMPLO:	<input id="txtHoraAud" type="text" onkeypress="formataHora(this)" onblur="validaHora(this.value, this.id)" />
/// </sumary>
function formataHora(input)
{	
	if(event.keyCode >= 48 && event.keyCode <= 57)
	{
		if (input.value.length==2)
		{		
			input.value=input.value + ":" ;	
		}
	}
	else
	{
		event.keyCode = 0;
	}
}
/// <sumary>
/// 	OBJETIVO:	Retirar caracter de string
/// 	AUTOR:		GK_MIYASAKA - 16/08/2007
/// 	EXEMPLO:	retiraCaracter(horario, ':');
/// </sumary>
function retiraCaracter(string, caracter) {
    var i = 0;
    var final = '';
    while (i < string.length) {
        if (string.charAt(i) == caracter) {
            final += string.substr(0, i);
            string = string.substr(i+1, string.length - (i+1));
            i = 0;
        }
        else {
            i++;
        }
    }
    return final + string;
}

/// <sumary>
/// 	OBJETIVO:	Validar um campo hora
/// 	AUTOR:		GK_MIYASAKA - 16/08/2007
/// 	EXEMPLO:	<input id="txtHoraAud" type="text" onkeypress="formataHora(this)" onblur="validaHora(this.value, this.id)" />
/// </sumary>
function validaHora(horario, input) {
	if(horario.length > 0 && horario.length < 5)
	{
		alert('Hora Invalida!');
		document.getElementById(input).value = "";		
		document.getElementById(input).focus();
		return;
	}
	
    var hora, minuto;
    if (!(horario.match(/^[0-9]{2,2}[:]{0,1}[0-9]{2,2}$/))) {
        return false;
    }
    horario = retiraCaracter(horario, ':');
    hora = parseInt(horario.substr(0,2));
    minuto = parseInt(horario.substr(2,2));
    if ((hora < 0) || (hora >23)) {
        alert('Hora Invalida!');
		document.getElementById(input).value = "";		
		document.getElementById(input).focus();
		return;
    }
    if ((minuto < 0) || (minuto >59)) {
		alert('Minuto Invalido!');
		document.getElementById(input).value = "";
		document.getElementById(input).focus();
        return;
    }
}

/// <sumary>
/// 	OBJETIVO:	Permitir a digitação apenas de números, pontos e vírgulas em um campo.
/// 	AUTOR:		JB_BASALI - 05/09/2006
/// 	EXEMPLO:	<input type="text" name="txtExemplo" id="txtExemplo" onkeypress="return isDecimal();" />
/// </sumary>
/// <returns>
///		Retorna True caso o valor da tecla pressionada seja um número, ponto ou vírgula.
///		Retorna False para qualquer outra tecla pressionada.
///	</returns>
function isDecimal()
{
	
	var intKeyId = event.keyCode;

	switch(intKeyId)
	{
		case 48: // 0 (zero)
			return true;
			break;
		case 49: // 1 (um)
			return true;
			break;
		case 50: // 2 (dois)
			return true;
			break;
		case 51: // 3 (três)
			return true;
			break;
		case 52: // 4 (quatro)
			return true;
			break;
		case 53: // 5 (cinco)
			return true;
			break;
		case 54: // 6 (seis)
			return true;
			break;
		case 55: // 7 (sete)
			return true;
			break;
		case 56: // 8 (oito)
			return true;
			break;
		case 57: // 9 (nove)
			return true;
			break;
		case 44: // , (vírgula)
			return true;
			break;
		case 46: // . (ponto)
			return true;
			break;
		default:
			return false;
			break;
	}
}

/// <sumary>
/// 	OBJETIVO:	Permitir a digitação apenas de números.
/// 	AUTOR:		JB_BASALI - 05/09/2006
/// 	EXEMPLO:	<input type="text" name="txtExemplo" id="txtExemplo" onkeypress="return isNumeric();" />
/// </sumary>
/// <returns>
///		Retorna True caso o valor da tecla pressionada seja um número.
///		Retorna False para qualquer outra tecla pressionada.
///	</returns>
function isNumeric()
{
	var intKeyId = event.keyCode;

	switch(intKeyId)
	{
		case 48: // 0 (zero)
			return true;
			break;
		case 49: // 1 (um)
			return true;
			break;
		case 50: // 2 (dois)
			return true;
			break;
		case 51: // 3 (três)
			return true;
			break;
		case 52: // 4 (quatro)
			return true;
			break;
		case 53: // 5 (cinco)
			return true;
			break;
		case 54: // 6 (seis)
			return true;
			break;
		case 55: // 7 (sete)
			return true;
			break;
		case 56: // 8 (oito)
			return true;
			break;
		case 57: // 9 (nove)
			return true;
			break;
		default:
			return false;
			break;
	}
}

/// <sumary>
/// 	OBJETIVO:	Trocar ponto por vírgula em um campo, caso o valor da tecla pressionada seja ponto.
/// 	AUTOR:		JB_BASALI - 05/09/2006
/// 	EXEMPLO:	<input type="text" name="txtExemplo" id="txtExemplo" onkeyup="pontoParaVirgula(this.id);" />
/// </sumary>
/// <param name="strId">
/// 	Id do campo onde a alteração deve ser feita.
/// </param>
function pontoParaVirgula(strId)
{
	var strValor = document.getElementById(strId).value;
	document.getElementById(strId).value = strValor.replace('.', ',');
}

function formataReais(fld, milSep, decSep, e, intSize)
{
	// <!-- Autor: Francisco C Paulino -->
	// <!-- Data: 08/11/2002 - 11:55hs -->
	// <!-- Script que formata Valores em reais ao digitar -->

	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;

	if(len > intSize) return false;

	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 formataCodigoIBM(fld, event)
{
	var strCodIBM = '';
	var i, len = 0;
	var intKeyId = event.keyCode;
	
	if(intKeyId == 8) return false;
	
	len = fld.value.length;

	if(len < 3 || len > 12) return false;

	for(i = 0; i < len; i++)
	{
		strCodIBM = strCodIBM + fld.value.charAt(i);
		if(fld.value.charAt(i+1) != '.' && fld.value.charAt(i+1) != '-')
		{
			if(i == 1 || i == 4 && fld) strCodIBM = strCodIBM + '.';
			if(i == 8) strCodIBM = strCodIBM + '-';
		}
	}
	fld.value = strCodIBM;

	return false;
}

function formataCodigoGemco(fld, event)
{
	// <!-- Autor: Bruno Freitas -->
	// <!-- Data:  05/12/2006    -->
	// <!-- Script que formata código GEMCO -->
	
	var strDigito = '';
	var strCodigo = '';

	fld.value = fld.value.replace('-', '');

	if(fld.value.length < 2) return false;

	strCodigo = fld.value.substring(0, fld.value.length - 1);
	strDigito = fld.value.substring(fld.value.length - 1, fld.value.length);

	fld.value = strCodigo + '-' + strDigito;
}

function formataData(input,event)
{
	// <!-- Autor: rf_couto -->
	// <!-- Data: 18/08/2006 -->
	// <!-- Script que formata os campos do tipo data -->

	if ((event.keyCode<48)||(event.keyCode>57)) // Se for número
	{
		event.returnValue = false; 
	}
	else
	{ 
		if ((input.value.length==2)||(input.value.length==5)) // Insere a "/" da data automaticamente
			input.value=input.value + "/" ;
	}
}

function validaData(data)
{
	// <!-- Autor: rf_couto -->
	// <!-- Data: 18/08/2006 -->
	// <!-- Script que verifica se a data é válida -->

	var dataCorreta = /^((0?[1-9]|[12]\d)\/(0?[1-9]|1[0-2])|30\/(0?[13-9]|1[0-2])|31\/(0?[13578]|1[02]))\/(19|20)?\d{2}$/;
	if (dataCorreta.test(data)) // Se estiver correto
	{
		return true;
	}
	else if (data != null && data != "") // Se foi digitado algo e estiver inválido
	{
		alert('Data Invalida!');
		return false;
	}
}

function validaDataIntervalo(dtaIni, dtaFim) {
	// <!-- Autor: jb_basali -->
	// <!-- Data: 05/09/2006 -->
	// <!-- Script que recebe uma Data Inicial dtaIni e uma Data Final dtaFim -->
	// <!-- e valida se o intervalo é válido, ou seja, se a Data Final é maior que a Data Inicial -->
	if ((dtaIni != '') && (dtaFim != '')) {
		dtaIni = dtaIni.substr(6,4) + dtaIni.substr(3,2) + dtaIni.substr(0,2);
		dtaFim = dtaFim.substr(6,4) + dtaFim.substr(3,2) + dtaFim.substr(0,2);

		if (dtaIni > dtaFim) {
			return false;
		}
		else
		{
			return true;
		}
	}
}

function abrePopUp(pstrpagina, largura, altura, barra_rolagem) //barra_rolagem ('yes' ou 'no')
{
	// <!-- Autor: rf_couto -->
	// <!-- Data: 22/08/2006 -->
	// <!-- Script que abre janela limpa (sem toolbar, barra de rolagem, etc...) -->

	// Variável de parâmetros
	var strAtributos = "";
	// Largura da janela
	strAtributos = strAtributos + "width=" + largura + ",";
	// Altura da janela
	strAtributos = strAtributos + "height=" + altura + ",";
	// Centraliza a janela
	strAtributos = strAtributos + "top=" + (screen.height-altura)/2 + ",";
	strAtributos = strAtributos + "left=" + (screen.width-largura)/2 + ",";
	// Permitir redimencionamento
	strAtributos = strAtributos + "resizable=no,";
	// Barra de rolagem
	strAtributos = strAtributos + "scrollbars=" + barra_rolagem + ",";
	// Barra de status
	strAtributos = strAtributos + "status=no,";
	// Barra de endereço
	strAtributos = strAtributos + "location=no,";
	// Barra de ferramentas
	strAtributos = strAtributos + "toolbar=no,";
	// Barra de menu
	strAtributos = strAtributos + "menubar=no,";
	// Exibindo efetivamente a janela, seguindo os parâmetros
	window.open(pstrpagina, '', strAtributos);
}

function abreModal(pstrpagina, largura, altura)
{
	// <!-- Autor: rf_couto -->
	// <!-- Data: 22/08/2006 -->
	// <!-- Script que abre janela do tipo modal -->

	// Variável de parâmetros
	var strAtributos = "";
	// Largura da janela
	strAtributos = strAtributos + "dialogWidth:" + largura + "px;";
	// Altura da janela
	strAtributos = strAtributos + "dialogHeight:" + altura + "px;";
	// Centralizar a janela
	strAtributos = strAtributos + "center:yes;";
	// Ocultar o dialogo
	strAtributos = strAtributos + "dialogHide:yes;";
	// Botão ajuda
	strAtributos = strAtributos + "help:no;";
	// Permitir redimencionamento
	strAtributos = strAtributos + "resizable:no;";
	// Barra de rolagem
	strAtributos = strAtributos + "scroll:no;";
	// Barra de status
	strAtributos = strAtributos + "status:no;";
	// Exibindo efetivamente a janela, seguindo os parâmetros
	window.showModalDialog(pstrpagina, 0, strAtributos);
}

			
function mascaraCep (fld,event)
{
	// <!-- Autor: jb_basali -->
	// <!-- Data: 25/08/2006 -->
	// <!-- Script que formata um valor de cep no campo fld passado como parâmetro -->
	var strCep = '';
	var i, len = 0;
	var intKeyId = event.keyCode;
	
	if(intKeyId == 8 || intKeyId == 9 || intKeyId == 14 || intKeyId == 15) return false;
	
	len = fld.value.length;

	// Se ainda não chegou o momento de adicionar o ponto (3º carac.) ou se a string já estiver completa, não precisa fazer nada.
	if(len < 3 || len > 10) return false;
	
	if (len == 10 && ((fld.value.lastIndexOf('.') < 0) || (fld.value.lastIndexOf('-') < 0)))
	{
		strCep = fld.value.replace('.', '').replace('-', '');
		strCep = strCep.substring(0, 2) + '.' + strCep.substring(2, 5) + '-' + strCep.substring(5, 8);
	}
	else
	{
		for(i = 0; i < len; i++)
		{
			strCep = strCep + fld.value.charAt(i);
	
			if(fld.value.charAt(i+1) != '.' && fld.value.charAt(i+1) != '-')
			{
				if(i == 1) strCep = strCep + '.';
				if(i == 5) strCep = strCep + '-';
			}
		}
	}
	
	fld.value = (strCep.length > 10) ? strCep.substring(0, 10) : strCep;

	return false;
}

function zerosDireita (fld, intLen)
{
	// <!-- Autor: jb_basali -->
	// <!-- Data: 01/07/2006 -->
	// <!-- Script que recebe um campo fld e um length intLen esperado, -->
	// <!-- e retorna uma string com o texto do campo acrescidos de zeros a direita -->
	// <!-- até atingir o tamanho intLen esperado n caracteres iniciais da string str. -->
	var strTexto = fld.value;
	var i = 0;

	// Caso a string já esteja no tamanho certo, não faz nada.
	if(strTexto.length == intLen) return false;

	for(i = strTexto.length; i < intLen; i++)
	{
		strTexto = strTexto + '0';
	}

	fld.value = strTexto;
	return false;
}

function Left(str, n){
	// <!-- Autor: jb_basali -->
	// <!-- Data: 05/09/2006 -->
	// <!-- Script que recebe uma string str e uma quantidade n de caracteres -->
	// <!-- e retorna a substring com os n caracteres iniciais da string str. -->
	if (n <= 0)
		return "";
	else if (n > String(str).length)
		return str;
	else
		return String(str).substring(0,n);
}

function Right(str, n){
	// <!-- Autor: jb_basali -->
	// <!-- Data: 05/09/2006 -->
	// <!-- Script que recebe uma string str e uma quantidade n de caracteres -->
	// <!-- e retorna a substring com os n caracteres finais da string str. -->
	if (n <= 0)
	return "";
	else if (n > String(str).length)
	return str;
	else {
	var iLen = String(str).length;
	return String(str).substring(iLen, iLen - n);
	}
}

function LTrim( value ){
	// <!-- Autor: jb_basali -->
	// <!-- Data: 21/09/2006 -->
	// <!-- Script que recebe uma string value e retorna -->
	// <!-- seu valor sem os espaços vazios a esquerda. -->
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
}

function RTrim( value ){
	// <!-- Autor: jb_basali -->
	// <!-- Data: 21/09/2006 -->
	// <!-- Script que recebe uma string value e retorna -->
	// <!-- seu valor sem os espaços vazios a direita. -->
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");
}

function Trim( value ){
	// <!-- Autor: jb_basali -->
	// <!-- Data: 21/09/2006 -->
	// <!-- Script que recebe uma string value e retorna -->
	// <!-- seu valor sem os espaços vazios a esquerda e a direita. -->
	return LTrim(RTrim(value));
}

function atualizaIframe_old( strId ){
	// <!-- Autor: jb_basali -->
	// <!-- Data: 11/11/2006 -->
	// <!-- Script que recebe o Id de uma DIV que engloba todo o conteúdo da página, obtém o height -->
	// <!-- do HTML Final e a partir dele atualiza o height do iFrame que chamou esta página. -->
	if(parent.document.getElementById('ifML') && document.getElementById(strId)) {
		var tamanho = document.getElementById(strId).offsetHeight;
		parent.document.getElementById('ifML').height = tamanho + 110;
	}
}

//function mudarTamanho(Tam)
//{
//	parent.document.getElementById("ifML").height = Tam;
//}


function atualizaIframe1( strId  ){
	//window.parent.mudarTamanho(document.getElementById(strId).offsetHeight);
}

function abriJanelaModal(strUrl, intAltura, intLargura, fld)
{
	/*
	OBJETIVO: ABRIR UMA JANELA MODAL COM OS RESULTADOS DA PESQUISA EFETUADA E
                  RETORNAR O CÓDIGO DO PRODUTO SELECIONADO
	AUTOR:    BRUNO FREITAS
	DATA:     28/11/2006
	*/
	
	var strRetorno = "", strCodItProd = "", strDigItProd = "";
	var intTamanho = 0;

	
	strRetorno = window.showModalDialog(strUrl, null, "dialogHeight: " + intAltura + "px; dialogWidth: " + intLargura + "px; dialogHide: yes; edge: Raised; center: Yes; help: No; resizable: No; status: No; unadorned: yes");

	if(strRetorno)
	{
		intTamanho = strRetorno.length;
		strCodItProd = strRetorno.substring(0, intTamanho - 1);
		strDigItProd = strRetorno.substring(intTamanho - 1, intTamanho);

		fld.item("txtCodItProd").value = strCodItProd + '-' + strDigItProd;
		fld.item("txtDescricao").value = "";

		__doPostBack('btnPesquisar','');
	}
	else
	{
		return false;
	}
}


/// <sumary>
/// 	OBJETIVO:	Exibir ou ocultar um elemento área (div, span) na página, de acordo com seu modo de exibição,
/// 				ou seja, caso esteja visível, oculta, e caso esteja oculto, exibe.
/// 				ao clicar no label deste campo, ele se transforma em um campo para receber o código IBM.
/// 	AUTOR:		JB_BASALI - 26/03/2007
/// 	EXEMPLO:	<input type="button" id="btnAvancado" onclick="exibeOcultaArea('pesquisaAvancada');">
/// </sumary>
/// <param name="strIdArea">
/// 	Id da área que precisa ser exibida ou ocultada.
/// </param>
function exibeOcultaArea(strIdArea){
	if (document.getElementById){
		style2 = document.getElementById(strIdArea).style;
		style2.display = style2.display == "none" ? "block" : "none";
	}else if (document.all){
		style2 = document.all[strIdArea].style;
		style2.display = style2.display == "none" ? "block" : "none";
	}else if (document.layers){
		style2 = document.layers[strIdArea].style;
		style2.display = style2.display == "none" ? "block" : "none";	
	}
}


/// <sumary>
/// 	OBJETIVO:	Alterna o tipo de informação que recebe um campo no formulário ao clicar no label do Campo,
/// 				conforme mesma funcionalidade existente no Gemco. Ex: Um campo que recebe código do Item Gemco,
/// 				ao clicar no label deste campo, ele se transforma em um campo para receber o código IBM.
/// 	AUTOR:		JB_BASALI - 27/03/2007
/// 	EXEMPLO:	<label id="lblTeste" onclick="alternaCampo(this.id, new Array('Código Gemco', 'Código IBM'), new Array('divCodGemco', 'divCodIbm'));">
/// </sumary>
/// <param name="strIdLabel">
/// 	Id do Label que chama a procedure no evento onclick.
/// </param>
/// <param name="arrayTextoLabel">
/// 	Array com os textos para as possíveis trocas do campo.
/// </param>
/// <param name="arrayArea">
/// 	Array com as áreas (divs, spans) onde estão os campos. Este array e o anterior devem ter a mesma quantidade
/// 	de elementos. Cada área deve estar na mesma posição que seu respectivo texto no parâmetro anterior.
/// </param>
function alternaCampo(strIdLabel, arrayTextoLabel, arrayArea, strTextoSelecionar) {
	if (arrayTextoLabel && arrayArea) {
		if (arrayTextoLabel.length > 0 && arrayArea.length > 0) {
			if (arrayTextoLabel.length == arrayArea.length) {
				for (var i = 0; i < arrayTextoLabel.length; i++) {
					if (strTextoSelecionar) {
						if (strTextoSelecionar == arrayTextoLabel[i]) {
							var j = i;
							document.getElementById(strIdLabel).innerHTML = arrayTextoLabel[j];
							for (var x in arrayArea) {
								styleObj = document.getElementById(arrayArea[x]).style;
								styleObj.display = (x == j) ? "block" : "none";
							}
							break;
						}
					}
					else
					{
						if (document.getElementById(strIdLabel).innerHTML == arrayTextoLabel[i]) {
							var j = (i+1 < arrayTextoLabel.length) ? i+1 : 0;
							document.getElementById(strIdLabel).innerHTML = arrayTextoLabel[j];
							for (var x in arrayArea) {
								styleObj = document.getElementById(arrayArea[x]).style;
								styleObj.display = (x == j) ? "block" : "none";
							}
							break;
						}
					}
				}
			}
		}
	}
}


/// <sumary>
/// 	OBJETIVO:	Identifica se a tecla pressionada é uma de navegação.
/// 	AUTOR:		LPE_PEREIRA - 12/04/2007
/// 	EXEMPLO:	
/// </sumary>
function teclaNavegacao()
{
	var key = event.keyCode;
	
	if(key != 8 && key != 9 && key != 16 && key != 35 && key != 36 && key != 37 && key !=39 && key != 46)
	{
		return true;
	}
	
	return false;
}

function limparCampo(fld)
{
	/*
	OBJETIVO: LIMPAR UM CAMPO ESPECÍFICO
	AUTOR:    ROGÉRIO COUTO
	DATA:     27/02/2007
	*/

	fld.value = "";
}

/// <sumary>
/// 	OBJETIVO:	Identifica a versao do browser.
/// 	AUTOR:		MO_JUNQUEIRA - 06/06/2007
/// 	EXEMPLO:	
/// </sumary>
function msieversion()
            {
                var ua = window.navigator.userAgent
                var msie = ua.indexOf ( "MSIE " )

                if ( msie > 0 )      // If Internet Explorer, return version number
                    return parseInt (ua.substring (msie+5, ua.indexOf (".", msie )))
                else                 // If another browser, return 0
                    return 0

        }

// <!-- Autor: mo_junqueira -->
// <!-- Data: 05/06/2007 -->
// <!-- Script que recebe o Id de uma DIV que engloba todo o conteúdo da página, obtém o height -->
// <!-- do HTML Final e a partir dele atualiza o height do iFrame que chamou esta página. -->
//<!-- verifica a versao do browser atraves do v_browser, onde caso for o 7.0 acrescenta um valor a mais para a height da div -->
function atualizaIframe( strId ){
	// <!-- Autor: mo_junqueira -->
	// <!-- Data: 05/06/2007 -->
	// <!-- Script que recebe o Id de uma DIV que engloba todo o conteúdo da página, obtém o height -->
	// <!-- do HTML Final e a partir dele atualiza o height do iFrame que chamou esta página. -->
	//<!-- verifica a versao do browser atraves do v_browser, onde caso for o 7.0 acrescenta um valor a mais para a height da div -->

	if(parent.document.getElementById('ifML') && document.getElementById(strId)) 
	{
		var tamanho = document.getElementById(strId).offsetHeight;
		var v_browser = msieversion();
		if (v_browser >= 7)
		{
			parent.document.getElementById('ifML').height = tamanho + 110;
		}
		else
		{
			parent.document.getElementById('ifML').height = tamanho;
		}
	}
}

function verifica_enter(evento,consulta)
// parâmetro 'consulta' --> "direta" para Consulta Direta ou "filtro" para Consulta com filtro
{
  var keyCodigo;
	keyCodigo = evento.keyCode;
	if (keyCodigo == 13){
		consulta_prod(consulta);
	}
}

function soNumeroPress(evento){
	//if (keyCodigo == 0){
		keyCodigo = evento.keyCode;
	//}
	if ((keyCodigo == 8 || keyCodigo == 13 || keyCodigo == 9 || keyCodigo == 71 || keyCodigo == 46 || keyCodigo  == 37  || keyCodigo  == 39) || (keyCodigo >= 48 && keyCodigo <= 57)) 
	{
		//alert('numero' + keyCodigo);
		return true;
	} else 
	{
		//alert('other' + keyCodigo);
		return false;
	}
}

function formataFone(input,event)
{
	// <!-- Autor: rf_couto -->
	// <!-- Data: 23/10/2007 -->
	// <!-- Script que formata os campos do tipo telefone no seguinte formato: (99) 9999-9999 -->

	if ((event.keyCode<48)||(event.keyCode>57)) // Se for número
	{
		event.returnValue = false; 
	}
	else
	{ 
		if (input.value.length==0) // Insere a "(" da data automaticamente
			input.value=input.value + "(" ;
		if (input.value.length==3) // Insere a ")" da data automaticamente
			input.value=input.value + ")" ;
		if (input.value.length==4) // Insere a " " da data automaticamente
			input.value=input.value + " " ;
		if (input.value.length==9) // Insere a "-" da data automaticamente
			input.value=input.value + "-" ;
		}
}

//Mostrar foto frente e verso
function virarFoto(produto, verso) {
    $("#Foto" + (verso ? "V" : "F") + produto).css("display", "block");
    $("#Foto" + (verso ? "F" : "V") + produto).css("display", "none");
    $("#Link" + produto).attr("href", "javascript:virarFoto(\"" + produto + "\"," + (verso ? "false" : "true") + ")");
}

//Trocar as fotos das cores
function mudaFotosCatalogo(produto, obj, fotoFrente, fotoVerso, precocor) {

    if (fotoVerso.indexOf("foto_nao_disponivel", 0) >= 0) {
        $("#Link" + produto).css("display", "none");
    }
    else{
        $("#Link" + produto).css("display", "block");
    }
    
    $("#Link" + produto).attr("href", "javascript:virarFoto(\"" + produto + "\",true)");
    $("#FotoF" + produto).css("display", "block");
    $("#FotoV" + produto).css("display", "none");

    $(".SelectedColor").each(function() {
        if ($(this).attr("produto") == produto)
            $(this).attr("class", "NormalColor");
    });
    
    $(obj).attr("class", "SelectedColor");

    if (fotoFrente != "") {
        $("#FotoF" + produto + " img").attr("src", fotoFrente);
    }

    if (fotoVerso != "") {
        $("#FotoV" + produto + " img").attr("src", fotoVerso);
    }

    //mudar preço
    if (precocor != "") {
        $("#preco"+produto).html(precocor);
    }
}

function AtualizarQtdeItens() {
    $.ajax({
        url: "api.aspx?tipo=attsacola",
        dataType: ($.browser.msie) ? "text" : "xml",
        success: function(data) {
            var xml;
            if (typeof data == "string") {
                xml = new ActiveXObject("Microsoft.XMLDOM");
                xml.async = false;
                xml.loadXML(data);
            }
            else {
                xml = data;
            }

            if (xml != null) {
                $(xml).find('attsacola').each(function() {
                    var QtdeItens = $(this).find("QTD_ITENS").text();
                    var valorTotal = $(this).find("VALOR_TOTAL").text();

                    $(".numero-itens em").text(QtdeItens);
                    $(".total-carrinho em").text(valorTotal);

                });
            }
        }
    });

    $.ajax({
        url: "api.aspx?tipo=attverificaacesso",
        dataType: ($.browser.msie) ? "text" : "xml",
        success: function(data) {
            var xml;
            if (typeof data == "string") {
                xml = new ActiveXObject("Microsoft.XMLDOM");
                xml.async = false;
                xml.loadXML(data);
            }
            else {
                xml = data;
            }

            if (xml != null) {
                $(xml).find('attverificaacesso').each(function() {
                    var ativo = $(this).find("ATIVO").text();
                    var apelido = $(this).find("APELIDO").text();

                    if (ativo == "1") {
                        $(".usuario-nome").html("Olá, " + apelido + " <a href=\"Login.aspx?logout=1\" title=\"Deslogar do site\">(Sair)</a>");
                    }
                    else {
                        $(".usuario-nome").html("Seja bem vindo! <a href=\"Login.aspx\" title=\"Entrar no site\">(Entrar)</a>");
                    }


                });
            }
        }
    });
}
