// Reconhece o browser
var ns4 = ( document.layers ) ? true : false
var ie4 = ( document.all ) ? true : false

var iens6 = document.all || document.getElementById;
var ieBox = iens6 && (document.compatMode == null || document.compatMode != 'CSS1Compat');

// Abre uma janela popup
function popup ( url, nome, largura, altura, posicao, resize, barras ) {
	if ( posicao == 0 ) {
		posleft = 20;
		postop  = ( screen.height ) ? ( screen.height - altura ) / 2 - 50 : 100;
	} else if ( posicao == 1 ) {
		posleft = ( screen.width ) ? ( screen.width - largura ) / 2 : 100;
		postop  = ( screen.height ) ? ( screen.height - altura ) / 2 - 50 : 100;
	} else if (posicao == 2 ) {
		posleft = ( screen.width ) ? ( screen.width - largura ) - 28 : 100;
		postop  = ( screen.height ) ? ( screen.height - altura ) / 2 - 50 : 100;
	}
	opBarras = ( barras ) ? "yes" : "no";
	opResize = ( resize ) ? "yes" : "no";
	
	settings = 'z-lock=yes, width=' + largura + ', height=' + altura + ', top=' + postop + ', left=' + posleft + ', scrollbars=' + opBarras + ', location=no, directories=no, status=no, menubar=no, toolbar=no, resizable=' + opResize;
	window.open( url, nome, settings );
}

//
// Abre a tela das screenshots
//
/*function screenshot( image, width, height ) {
	popup( '/?show=screenshot&str_image=' + image, 'screenshot', width, height, 1, 0, 0 );
}*/

//
// Faz uma pergunta
//
function question( str_question ) {
	if ( confirm( str_question ) )
		return true;
	else
		return false;
}

//
// Escreve dinamicamente dentro de um layer
//
function writer( id, txt ) {
	if ( ns4 ) {
		var lyr = document.layers[id].document;
		lyr.write( txt );
		lyr.close();
	} else
		document.getElementById( id ).innerHTML = txt;
}

//
// Recupera um elemento
//
function getElement( id ) {
	if ( ns4 )
		return document.layers[id].document;
	else
		return document.getElementById(id);
}

function getElementByName( formname, elementname ) { 
	var elements = eval( "document." + formname + ".elements" );
	for( var i = 0; i < elements.length; i++ )
	{
		if( elements[i].name == elementname )
		{
			return elements[i];
		}
	}
	return null;
}

function overMenu( int_option, boo_status ) {
	var str_class, str_imgA, str_imgB, str_imgC, str_imgD, str_imgE;
	
	str_class = ( boo_status ) ? 'itemsubmenu_over' : 'itemsubmenu';
	str_imgA  = ( boo_status ) ? 'submnutlover' : 'submnutl';
	str_imgB  = ( boo_status ) ? 'submnutrover' : 'submnutr';
	str_imgC  = ( boo_status ) ? 'submnublover' : 'submnubl';
	str_imgD  = ( boo_status ) ? 'submnubrover' : 'submnubr';
	
	getElement( 'lyr_submenu' + int_option ).className = str_class;
	getElement( 'img_submenu' + int_option + 'a' ).src = '/tpl/lang/br/default/img/' + str_imgA + '.gif';
	getElement( 'img_submenu' + int_option + 'b' ).src = '/tpl/lang/br/default/img/' + str_imgB + '.gif';
	getElement( 'img_submenu' + int_option + 'c' ).src = '/tpl/lang/br/default/img/' + str_imgC + '.gif';
	getElement( 'img_submenu' + int_option + 'd' ).src = '/tpl/lang/br/default/img/' + str_imgD + '.gif';
}

// Exibe ou oculta um elemente
function viewElement( str_element, boo_status ) {
	// Recupera o elemento
	obj = getElement( str_element );
	if ( boo_status )
		obj.style.display = '';
	else
		obj.style.display = 'none';
}

// Filtra as teclas pressionadas
/*function filtra(obj, padrao) {
	tk    = (ie4) ? event.keyCode : event.which;
	letra = String.fromCharCode(tk);

	for (x = 0; x < padrao.length; x++)
		if (padrao.slice(x, x + 1) == letra) return true;

	return false;
}*/

// Bloqueia caracteres excedentes em textareas
function maximo( obj, valor ) {
	if ( obj.value.length >= valor ) return false;
}

// Retorna a largura da tela
function getWindowWidth() {
	return iens6 ? ( ieBox ? ( document.body.clientWidth  + document.body.scrollLeft ) : ( document.documentElement.clientWidth + document.documentElement.scrollLeft ) ) : window.innerWidth;
}

//
// Retorna a altura da tela
//
function getWindowHeight() {
	if ( iens6 ) {
		if ( ieBox )
			teste = document.body.clientHeight + document.body.scrollTop;
		else
			teste = document.documentElement.clientHeight + document.documentElement.scrollTop;
	} else
		teste = window.innerHeight;

	return teste;
}

//
// Esta fun�o coloca o foco no primeiro campo text que existir na tela
//
function loadFocus() {
	var obj       = document.forms;
	
	for ( x = 0; x < obj.length; x++ ) {
		var objetos = obj[x].length;
		
		for ( i = 0; i < objetos; i++ )
			if ( ( ( obj[x].elements[i].type == 'text' ) || ( obj[x].elements[i].type == 'textarea' ) || ( obj[x].elements[i].type == 'password' ) ) && ( obj[x].elements[i].disabled == false ) && ( obj[x].elements[i].style.visibility == 'visible' ) ) {
				obj[x].elements[i].focus();
				return true;
			}
	}
	
	return false
}

//
// Fun�o que preenche um combo box
//
function fillSelect( obj_combo, str_result ) {
	// Limpa o combo
	while ( obj_combo.length > 0 )
		obj_combo.options[obj_combo.length - 1] = null;
	
	eval( str_result );
	
	// Insere os novos elementos no array
	for ( x = 0; x < arr_array.length; x++ )
		obj_combo.options[x] = new Option( arr_array[x][1], arr_array[x][0] );
}

function checkNumbers(e)
				{
					var key;
					var keychar;
					var reg;

					if(window.event) {
						// for IE, e.keyCode or window.event.keyCode can be used
						key = e.keyCode;
					}
					else if(e.which) {
						// netscape
						key = e.which;
					}
					else {
						// no event, so pass through
						return true;
					}

					keychar = String.fromCharCode(key);
					reg = /\d/;

					if ( key == 8 ) {
						return true;
					} else {
						return reg.test(keychar);
					}
				}


//--------------------------------------------------------------
//- Objetivo: Verifica o conteudo do campo
//--------------------------------------------------------------
function VerCampoNumericoValor() {
	if(event.keyCode==188|event.keyCode==110) {
		if (event.srcElement.value.search(",")==-1)
			event.returnValue=true;
		else
			event.returnValue=false;
	}	else {
	if ((event.keyCode<47)|(event.keyCode>95&event.keyCode<106)|(event.keyCode>47&event.keyCode<58&event.shiftKey==false))
		event.returnValue=true;
	else
		event.returnValue=false;
	}
}

//
//- Objetivo: Verifica o conteudo do campo
//
function VerCampoNumerico() {
	if ((event.keyCode<47)|(event.keyCode>95&event.keyCode<106)|(event.keyCode>47&event.keyCode<58&event.shiftKey==false))
		event.returnValue=true;
	else
		event.returnValue=false;
}

//
//- Objetivo: Desformata o conteudo do campo
//
function DesFormataValor(strValor) {
	var re;
	re = /\,/g;
	strValor=strValor.replace(re,'');
	re = /\./g;
	strValor=strValor.replace(re,'.');
	return strValor;
}

//
//- Objetivo: Formata o conteudo do campo
//
function FormataValor(e) {

	var isNN = (navigator.appName.indexOf("Netscape")!=-1)
	var strValor   = '';
	var strRetorno = '';
	if (isNN)
		strValor = e.target.value;
	else
		strValor = event.srcElement.value;
	
	if (strValor.length>0)
		{
			var num = DesFormataValor(strValor);
			num = num.toString().replace(/\$|\,/g,'');
			
			if(isNaN(num))
				{
					num = "";
					return false;
				}
				
			sign = (num == (num = Math.abs(num)));
			num = Math.floor(num*100+0.50000000001);
			cents = num%100;
			num = Math.floor(num/100).toString();
			
			if(cents<10)
				cents = "0" + cents;
			for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
				num = num.substring(0,num.length-(4*i+3))+num.substring(num.length-(4*i+3));
			strRetorno = (((sign)?'':'-') + num + '.' + cents);
		}
	
	if (isNN)
		e.target.value = strRetorno;
	else
		event.srcElement.value = strRetorno;	
}

//Identifica o Browser
var isNN = (navigator.appName.indexOf("Netscape")!=-1);

var nomecamposvalor	   = new Array(0);
var nomecamposnumerico = new Array(0);	
nomecamposvalor[0] = "amount";
nomecamposvalor[1] = "max_offers";

//Objetivo  : Auto-Tabular entre campos
//Par�etros: input = campo com o foco
//	     len   = maxlength do campo
//	     e	   = objeto do evento		 
function autoTab(input,len, e) 
{
    var keyCode = (isNN) ? e.which : e.keyCode; 
    var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
    if(input.value.length >= len && !containsElement(filter,keyCode)) 
    {
        input.value = input.value.slice(0, len);
        input.form[(getIndex(input)+1) % input.form.length].focus();
    }

    function containsElement(arr, ele) {
        var found = false, index = 0;
        while(!found && index < arr.length)
        if(arr[index] == ele)
            found = true;
        else
            index++;
        return found;
    }

    function getIndex(input) {
        var index = -1, i = 0, found = false;
        while (i < input.form.length && index == -1)
        if (input.form[i] == input)index = i;
        else i++;
            return index;
    }
    return true;
}

//Objetivo  : Permitir somente a digita�o de caracters num�icos
//Premissa  : Cria�o do array nomecamposnumerico
function ValidaTecla(e)
{
	var key;
	var srcElement;
	
	if (navigator.appName == 'Netscape') 
	{
		srcElement = e.target.name;
		key = e.which;
	}
	else
	{
		key = window.event.keyCode;
		srcElement = window.event.srcElement.name
	}
	
	
	var varcountaux;
	var camponumerico = false;
	var campovalor    = false;
		
	if (key==0x0D) 
		{		
		Enviar();
		if (navigator.appName != 'Netscape') 						   
			window.event.keyCode = 0;
		return;
		}		
	
	for(countaux=0;countaux<nomecamposnumerico.length;countaux++)
	   {	
	   if(srcElement==nomecamposnumerico[countaux])
	    camponumerico = true;	
	   }		

	for(countaux=0;countaux<nomecamposvalor.length;countaux++)
	   {	
	   if(srcElement==nomecamposvalor[countaux])
	    campovalor = true;	
	   }			   
	
	if (camponumerico==true)
		{
			if (key==0x08)
				{
				return true;
				}
			
			if( key < 0x30 || key > 0x39 )
				{
				if (navigator.appName == 'Netscape') 			
					{
					//e.which = 0;
					return false;
					}
				else
					{
					window.event.keyCode = 0;
					}
				}
		}
	
	if (campovalor == true)
		{
			if (key==0x08)
				{
				return true;
				}
			
			if (key==46)
				{
				window.event.keyCode=44;
				key=44;
				}
			if (key==44)
				{	
					
					if (navigator.appName == 'Netscape') 								
						{
						if(e.target.value.search(",")!=-1)
						  return false;
						else
						  return true; 		
						}												
					else
						{
						if(window.event.srcElement.value.search(",")!=-1)
						  window.event.keyCode = 0;
						else
						  return true; 		
						}
				}
			
			if( key < 0x30 || key > 0x39 )
				{
				if (navigator.appName == 'Netscape') 			
					{
					//e.which = 0;
					return false;
					}
				else
					{
					window.event.keyCode = 0;
					}
				}		
			else
				{
				if (navigator.appName == 'Netscape') 			
					{
					if(e.target.value.search(",")!=-1 & (e.target.value.search(",")+2)<e.target.value.length)
						return false;
					}
				else
					{
					if(window.event.srcElement.value.search(",")!=-1 &  (window.event.srcElement.value.search(",")+2)<window.event.srcElement.value.length)
						window.event.keyCode = 0;												
					}
				}	
		}
	
}

function ValidaTeclaValor(e)
{
	var key;
	var srcElement;
	
	if (navigator.appName == 'Netscape') 
	{
		srcElement = e.target.name;
		key = e.which;
	}
	else
	{
		key = window.event.keyCode;
		srcElement = window.event.srcElement.name
	}
	
	var varcountaux;
	var camponumerico = false;
	var campovalor    = true;
		
	if (key==0x0D) 
		{		
		Enviar();
		if (navigator.appName != 'Netscape') 						   
			window.event.keyCode = 0;
		return;
		}		
	
	for(countaux=0;countaux<nomecamposnumerico.length;countaux++)
	   {	
	   if(srcElement==nomecamposnumerico[countaux])
	    camponumerico = true;	
	   }		

	for(countaux=0;countaux<nomecamposvalor.length;countaux++)
	   {	
	   if(srcElement==nomecamposvalor[countaux])
	    campovalor = true;	
	   }			   
	
	if (camponumerico==true)
		{
			if (key==0x08)
				{
				return true;
				}
			
			if( key < 0x30 || key > 0x39 )
				{
				if (navigator.appName == 'Netscape') 			
					{
					//e.which = 0;
					return false;
					}
				else
					{
					window.event.keyCode = 0;
					}
				}
		}
	
	if (campovalor == true)
		{
			
			if (key==0x08)
				{
				return true;
				}
			
			if (key==44) {
				if(window.event) {
					window.event.keyCode=46;
				
				}	else
					return false;
				
				key=46;
			}
			
			if (key==44)
				return false;
			
			if (key==46) {	
					
 					if(window.event) {
						if(window.event.srcElement.value.search(",")!=-1)
						  window.event.keyCode = 0;
						else
						  return true; 		
					}	else {
						if(e.target.value.search(",")!=-1)
						  return false;
						else
						  return true; 		
					
					}
 					
			}
			
			if( key < 0x30 || key > 0x39 )
				{
				if (navigator.appName == 'Netscape') 			
					{
					//e.which = 0;
					return false;
					}
				else
					{
					window.event.keyCode = 0;
					}
				}		
			else
				{
				if (navigator.appName == 'Netscape') 			
					{
					if(e.target.value.search(",")!=-1 & (e.target.value.search(",")+4)<e.target.value.length)
						return false;
					}
				else
					{
					if(window.event.srcElement.value.search(",")!=-1 &  (window.event.srcElement.value.search(",")+2)<window.event.srcElement.value.length)
						window.event.keyCode = 0;												
					}
				}	
		}
	
}


function validaCPFCNPJ(val){
	var pIsCnpj = isCnpj(val);
	var pIsCpf  = isCpf(val);
	//pForm = document.forms[0];
	//var val = pForm.cnpj.value;
	if (!val) return;
	if (!isCpfCnpj(val))
		alert("CPF/CNPJ Inválido");
	
	var base = val.substring(0, val.length-2);
	//alert("CNPJ:"
	//	+ "\nDesformatado = " + unformatNumber(val)
	//	+ "\nFormatado = " + formatCpfCnpj(val, true, true)
	//	+ "\nDVs = " + dvCpfCnpj(base, true)
	//	+ "\nV�ido = " + isCnpj(val));
	if ( pIsCnpj ) {
		document.form.cpf_cnpj.value = formatCpfCnpj(val, true, true);
	}	else if ( pIsCpf ) {
		document.form.cpf_cnpj.value = formatCpfCnpj(val, true, false);
	}
} 

var NUM_DIGITOS_CPF  = 11;
var NUM_DIGITOS_CNPJ = 14;
var NUM_DGT_CNPJ_BASE = 8;

/**
 * Adiciona m�odo lpad() �classe String.
 * Preenche a String �esquerda com o caractere fornecido,
 * at�que ela atinja o tamanho especificado.
 */
String.prototype.lpad = function(pSize, pCharPad)
{
	var str = this;
	var dif = pSize - str.length;
	var ch = String(pCharPad).charAt(0);
	for (; dif>0; dif--) str = ch + str;
	return (str);
} //String.lpad


/**
 * Adiciona m�odo trim() �classe String.
 * Elimina brancos no in�io e fim da String.
 */
String.prototype.trim = function()
{
	return this.replace(/^\s*/, "").replace(/\s*$/, "");
} //String.trim


/**
 * Elimina caracteres de formata�o e zeros �esquerda da string
 * de nmero fornecida.
 * @param String pNum
 *      String de nmero fornecida para ser desformatada.
 * @return String de nmero desformatada.
 */
function unformatNumber(pNum)
{
	return String(pNum).replace(/\D/g, "").replace(/^0+/, "");
} //unformatNumber


/**
 * Formata a string fornecida como CNPJ ou CPF, adicionando zeros
 * �esquerda se necess�io e caracteres separadores, conforme solicitado.
 * @param String pCpfCnpj
 *      String fornecida para ser formatada.
 * @param boolean pUseSepar
 *      Indica se devem ser usados caracteres separadores (. - /).
 * @param boolean pIsCnpj
 *      Indica se a string fornecida �um CNPJ.
 *      Caso contr�io, �CPF. Default = false (CPF).
 * @return String de CPF ou CNPJ devidamente formatada.
 */
function formatCpfCnpj(pCpfCnpj, pUseSepar, pIsCnpj)
{
	if (pIsCnpj==null) pIsCnpj = false;
	if (pUseSepar==null) pUseSepar = true;
	var maxDigitos = pIsCnpj? NUM_DIGITOS_CNPJ: NUM_DIGITOS_CPF;
	var numero = unformatNumber(pCpfCnpj);

	numero = numero.lpad(maxDigitos, '0');
	if (!pUseSepar) return numero;

	if (pIsCnpj)
	{
		reCnpj = /(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})$/;
		numero = numero.replace(reCnpj, "$1.$2.$3/$4-$5");
	}
	else
	{
		reCpf  = /(\d{3})(\d{3})(\d{3})(\d{2})$/;
		numero = numero.replace(reCpf, "$1.$2.$3-$4");
	}
	return numero;
} //formatCpfCnpj


/**
 * Calcula os 2 d�itos verificadores para o nmero-efetivo pEfetivo de
 * CNPJ (12 d�itos) ou CPF (9 d�itos) fornecido. pIsCnpj �booleano e
 * informa se o nmero-efetivo fornecido �CNPJ (default = false).
 * @param String pEfetivo
 *      String do nmero-efetivo (SEM d�itos verificadores) de CNPJ ou CPF.
 * @param boolean pIsCnpj
 *      Indica se a string fornecida �de um CNPJ.
 *      Caso contr�io, �CPF. Default = false (CPF).
 * @return String com os dois d�itos verificadores.
 */
function dvCpfCnpj(pEfetivo, pIsCnpj)
{
	if (pIsCnpj==null) pIsCnpj = false;
	var i, j, k, soma, dv;
	var cicloPeso = pIsCnpj? NUM_DGT_CNPJ_BASE: NUM_DIGITOS_CPF;
	var maxDigitos = pIsCnpj? NUM_DIGITOS_CNPJ: NUM_DIGITOS_CPF;
	var calculado = formatCpfCnpj(pEfetivo, false, pIsCnpj);
	calculado = calculado.substring(2, maxDigitos);
	var result = "";

	for (j = 1; j <= 2; j++)
	{
		k = 2;
		soma = 0;
		for (i = calculado.length-1; i >= 0; i--)
		{
			soma += (calculado.charAt(i) - '0') * k;
			k = (k-1) % cicloPeso + 2;
		}
		dv = 11 - soma % 11;
		if (dv > 9) dv = 0;
		calculado += dv;
		result += dv
	}

	return result;
} //dvCpfCnpj


/**
 * Testa se a String pCpf fornecida �um CPF v�ido.
 * Qualquer formata�o que n� seja algarismos �desconsiderada.
 * @param String pCpf
 *      String fornecida para ser testada.
 * @return <code>true</code> se a String fornecida for um CPF v�ido.
 */
function isCpf(pCpf)
{
	var numero = formatCpfCnpj(pCpf, false, false);
	var base = numero.substring(0, numero.length - 2);
	var digitos = dvCpfCnpj(base, false);
	var algUnico, i;

	// Valida d�itos verificadores
	if (numero != base + digitos) return false;

	/* N� ser� considerados v�idos os seguintes CPF:
	 * 000.000.000-00, 111.111.111-11, 222.222.222-22, 333.333.333-33, 444.444.444-44,
	 * 555.555.555-55, 666.666.666-66, 777.777.777-77, 888.888.888-88, 999.999.999-99.
	 */
	algUnico = true;
	for (i=1; i<NUM_DIGITOS_CPF; i++)
	{
		algUnico = algUnico && (numero.charAt(i-1) == numero.charAt(i));
	}
	return (!algUnico);
} //isCpf


/**
 * Testa se a String pCnpj fornecida �um CNPJ v�ido.
 * Qualquer formata�o que n� seja algarismos �desconsiderada.
 * @param String pCnpj
 *      String fornecida para ser testada.
 * @return <code>true</code> se a String fornecida for um CNPJ v�ido.
 */
function isCnpj(pCnpj)
{
	var numero = formatCpfCnpj(pCnpj, false, true);
	var base = numero.substring(0, NUM_DGT_CNPJ_BASE);
	var ordem = numero.substring(NUM_DGT_CNPJ_BASE, 12);
	var digitos = dvCpfCnpj(base + ordem, true);
	var algUnico;

	// Valida d�itos verificadores
	if (numero != base + ordem + digitos) return false;

	/* N� ser� considerados v�idos os CNPJ com os seguintes nmeros B�ICOS:
	 * 11.111.111, 22.222.222, 33.333.333, 44.444.444, 55.555.555,
	 * 66.666.666, 77.777.777, 88.888.888, 99.999.999.
	 */
	algUnico = numero.charAt(0) != '0';
	for (i=1; i<NUM_DGT_CNPJ_BASE; i++)
	{
		algUnico = algUnico && (numero.charAt(i-1) == numero.charAt(i));
	}
	if (algUnico) return false;

	/* N� ser�considerado v�ido CNPJ com nmero de ORDEM igual a 0000.
	 * N� ser�considerado v�ido CNPJ com nmero de ORDEM maior do que 0300
	 * e com as tr� primeiras posi�es do nmero B�ICO com 000 (zeros).
	 * Esta cr�ica n� ser�feita quando o no B�ICO do CNPJ for igual a 00.000.000.
	 */
	if (ordem == "0000") return false;
	return (base == "00000000" || parseInt(ordem, 10) <= 300 || base.substring(0, 3) != "000");
} //isCnpj

/**
 * Testa se a String pCpfCnpj fornecida �um CPF ou CNPJ v�ido.
 * Se a String tiver uma quantidade de d�itos igual ou inferior
 * a 11, valida como CPF. Se for maior que 11, valida como CNPJ.
 * Qualquer formata�o que n� seja algarismos �desconsiderada.
 * @param String pCpfCnpj
 *      String fornecida para ser testada.
 * @return <code>true</code> se a String fornecida for um CPF ou CNPJ v�ido.
 */
function isCpfCnpj(pCpfCnpj)
{
	var numero = pCpfCnpj.replace(/\D/g, "");
	if (numero.length > NUM_DIGITOS_CPF)
		return isCnpj(pCpfCnpj)
	else
		return isCpf(pCpfCnpj);
} //isCpfCnpj