/**
 * @copyright	: LimePHP 2007, Altamiro Rodrigues. 
 * @author 		: Altamiro Dourado Rodrigues
 * @email		: altamiro27@gmail.com
 * @fone		: ( 75 ) 8806 - 8750
 * @package 	: lime
 * @credito		: Altamiro Rodrigues.
 */
 
 //window.status = "SGC - Sistema de Gerenciamento de Conteúdo - Versão : 1.0";
 
var IE = false;
if (document.all) {IE = true;}

var _documentAll = null;
function DocumentAll() {
	if (_documentAll==null) {
		if (IE) {
			_documentAll = document.all;
		}else{
    		 document.all = (document.all) ? document.all : 
          ((document.getElementsByTagName("*").length > 0) ?
          document.getElementsByTagName("*") : null)
			_documentAll = document.all;
		}	
	}
	return _documentAll;
}

/* menu context */

// 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";
	opResize = 'yes';

	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);
}

// 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].focus();
				return true;
			}
		}
	}
	
	return false
}

// Esta função desativa todos os controles do formulário
function disabledControls() {
	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 != 'button' )
				obj[x].elements[i].disabled = true;
	}
}

// Formata um valor em formato de moeda ( idêntica a do PHP )
function number_format( int_value, int_decimal, str_pointer, str_comma ) {
	var str_result = '';
	
	int_value      = int_value + 1;
	
	str_value      = new String( int_value * 100 );
	
	str_number     = str_value.substr( 0, str_value.length - int_decimal );
	str_decimal    = str_value.substr( str_value.length - int_decimal, int_decimal );
	
	i = 0;
	for ( x = str_number.length; x >= 0; x-- ) {
		if ( i == 4 ) {
			i          = 1;
			str_result = str_pointer + str_result;
		}
		
		str_result   = str_number.substr( x, 1 ) + str_result;
		
		i++;
	}
	
	return ( str_result - 1 ) + str_comma + str_decimal;
}

// Busca o valor gravado em um cookie
function GetCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len   = start + name.length + 1;
	
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) )
		return null;
	
	if ( start == -1 )
		return null;
	
	var end   = document.cookie.indexOf( ";", len );
	
	if ( end == -1 )
		end     = document.cookie.length;
	
	return unescape( document.cookie.substring( len, end ) );
}

// Grava um cookie
function SetCookie( name, value, expires, domain, secure ) {
	var cookieString = name + "=" + escape( value ) +
										( ( expires ) ? ";expires=" + expires.toGMTString() : "" ) +
										";path=/" +
										( ( domain ) ? ";domain=" + domain : "" ) +
										( ( secure ) ? ";secure" : "" );
	
	document.cookie  = cookieString;
}

// Funcção que alterna a exibição de dois layers
function loadToolbar( int_option, str_cookie, str_objOn, str_objOff ) {
	var int_date = new Date();
	
	if ( int_option == 0 ) {
		// Carrega o status da barra lateral
		int_option = GetCookie( str_cookie );
	}
	
	if ( int_option == 1 ) {
		viewElement( str_objOn, true );
		viewElement( str_objOff, false );
	
	} else if ( int_option == 2 ) {
		viewElement( str_objOn, false );
		viewElement( str_objOff, true );
	
	} else {
		int_option = 1;
		
		viewElement( str_objOn, true );
		viewElement( str_objOff, false );
	}
	
	int_date.setTime( int_date.getTime() + ( 365 * 24 * 60 * 60 * 1000 ) );
	
	SetCookie( str_cookie, int_option, int_date );
}


 function cl(nome) {
 	return document.getElementById(nome).value.length;
 }
 
 function cv(nome) {
 	return document.getElementById(nome).value;
 }
 
 function cf(nome) {
 	return document.getElementById(nome).focus();
 }
 
 function ca(msg) {
 	alert(msg);
 }
 
 function cb(nome) {
 	return document.getElementById(nome).disabled = true;
 }
 
 function cd(nome) {
 	return document.getElementById(nome).disabled = false;
 }
 
 function $(el){
	return document.getElementById(el);
 }
 
 function Carregando(obj) {
	$(obj).innerHTML = "<br><br><img src='images/indicator.gif' border='0'><br>Carregando...<br><br><br><br>"; 
 }
 
 
 function redirecionar(url) {
	window.location = url; 
 }
 
/* end menu context */

var editarRows = false;
var rowsId;
var classId;

function selectRows(id, cls) {

	if ( editarRows ) {
		desativarRows(rowsId,classId);
		ativarRows(id,cls);
	} else {
		ativarRows(id,cls);
	}

	
} // END selectRows

function ativarRows(id,cls) {
	rowsId = id;
	classId = cls;
	document.getElementById(id).className='default-grid-selected';
	editarRows = true;
} // END ativarRows

function desativarRows(id,cls) {
	document.getElementById(id).className=cls;
	editarRows = false;
} // END desativarRows


function overButton(obj){
	document.getElementById(obj).className="botoes_bg_over";
}

function outButton(obj){
	document.getElementById(obj).className="botoes_bg";
}

function pesquisaAba(name){
	var objImg = document.getElementById('img'+name);
	if (document.getElementById(name).style.display==""){
		document.getElementById(name).style.display="none";
		document.getElementById("tabPesquisa").title="Mostrar Pesquisa";
		objImg.src = "images/grid/aba_seta_baixo.gif";
	}else{
		document.getElementById(name).style.display="";
		document.getElementById("tabPesquisa").title="Esconder Pesquisa";
		objImg.src = "images/grid/aba_seta_cima.gif";		
	}
}

 function validarEmail(campo) {
 	
 	if ( cv(campo) != "" ) {
			//Expressao Regular utilizada para validar o endereco de email
		var ExpReg = /^[a-zA-Z0-9_\.-]{2,}@([A-Za-z0-9_-]{2,}\.)+[A-Za-z]{2,4}$/;
	
		if ( !ExpReg.test( cv(campo) ) ) {
			//ca("E-MAIL inválido!");
			//cf(campo);
			return false;
		}
	
	}
 	
 }

/** #### MASCARA ###  **/

function mascara(o,f){
    v_obj=o
    v_fun=f
    setTimeout("execmascara()",1)
}

function execmascara(){
    v_obj.value=v_fun(v_obj.value)
}

function leech(v){
    v=v.replace(/o/gi,"0")
    v=v.replace(/i/gi,"1")
    v=v.replace(/z/gi,"2")
    v=v.replace(/e/gi,"3")
    v=v.replace(/a/gi,"4")
    v=v.replace(/s/gi,"5")
    v=v.replace(/t/gi,"7")
    return v
}

function soNumeros(v){
    return v.replace(/\D/g,"")
}

function telefone(v){
    v=v.replace(/\D/g,"")                 //Remove tudo o que não é dígito
    v=v.replace(/^(\d\d)(\d)/g,"($1) $2") //Coloca parênteses em volta dos dois primeiros dígitos
    v=v.replace(/(\d{4})(\d)/,"$1-$2")    //Coloca hífen entre o quarto e o quinto dígitos
    return v
}

function cpf(v){
    v=v.replace(/\D/g,"")                    //Remove tudo o que não é dígito
    v=v.replace(/(\d{3})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
    v=v.replace(/(\d{3})(\d)/,"$1.$2")       //Coloca um ponto entre o terceiro e o quarto dígitos
                                             //de novo (para o segundo bloco de números)
    v=v.replace(/(\d{3})(\d{1,2})$/,"$1-$2") //Coloca um hífen entre o terceiro e o quarto dígitos
    return v
}

function cep(v){
    v=v.replace(/\D/g,"")               //Remove tudo o que não é dígito
    v=v.replace(/^(\d{5})(\d)/,"$1-$2") //Esse é tão fácil que não merece explicações
    return v
}

function data(v){
    v=v.replace(/\D/g,"")                 //Remove tudo o que não é dígito
    v=v.replace(/^(\d{2})(\d)/,"$1/$2")   //Coloca uma barra entre o segundo e o terceiro dígitos
    v=v.replace(/(\d{2})(\d)/,"$1/$2")    //Coloca uma barra entre o quinto e o sexto dígitos
    return v
}

function cnpj(v){
    v=v.replace(/\D/g,"")                           //Remove tudo o que não é dígito
    v=v.replace(/^(\d{2})(\d)/,"$1.$2")             //Coloca ponto entre o segundo e o terceiro dígitos
    v=v.replace(/^(\d{2})\.(\d{3})(\d)/,"$1.$2.$3") //Coloca ponto entre o quinto e o sexto dígitos
    v=v.replace(/\.(\d{3})(\d)/,".$1/$2")           //Coloca uma barra entre o oitavo e o nono dígitos
    v=v.replace(/(\d{4})(\d)/,"$1-$2")              //Coloca um hífen depois do bloco de quatro dígitos
    return v
}

function romanos(v){
    v=v.toUpperCase()             //Maiúsculas
    v=v.replace(/[^IVXLCDM]/g,"") //Remove tudo o que não for I, V, X, L, C, D ou M
    //Essa é complicada! Copiei daqui: http://www.diveintopython.org/refactoring/refactoring.html
    while(v.replace(/^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/,"")!="")
        v=v.replace(/.$/,"")
    return v
}

function site(v){
    //Esse sem comentarios para que você entenda sozinho ;-)
    v=v.replace(/^http:\/\/?/,"")
    dominio=v
    caminho=""
    if(v.indexOf("/")>-1)
        dominio=v.split("/")[0]
        caminho=v.replace(/[^\/]*/,"")
    dominio=dominio.replace(/[^\w\.\+-:@]/g,"")
    caminho=caminho.replace(/[^\w\d\+-@:\?&=%\(\)\.]/g,"")
    caminho=caminho.replace(/([\?&])=/,"$1")
    if(caminho!="")dominio=dominio.replace(/\.+$/,"")
    v="http://"+dominio+caminho
    return v
}

/**
 *
 * PROTÓTIPOS:
 * método String.lpad(int pSize, char pCharPad)
 * método String.trim()
 *
 * String unformatNumber(String pNum)
 * String formatCpfCnpj(String pCpfCnpj, boolean pUseSepar, boolean pIsCnpj)
 * String dvCpfCnpj(String pEfetivo, boolean pIsCnpj)
 * boolean isCpf(String pCpf)
 * boolean isCnpj(String pCnpj)
 * boolean isCpfCnpj(String pCpfCnpj)
 */


var NUM_DIGITOS_CPF  = 11;
var NUM_DIGITOS_CNPJ = 14;
var NUM_DGT_CNPJ_BASE = 8;


/**
 * Adiciona método 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étodo trim() à classe String.
 * Elimina brancos no início 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 número fornecida.
 * @param String pNum
 *      String de número fornecida para ser desformatada.
 * @return String de número 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ário 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ário, é 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ígitos verificadores para o número-efetivo pEfetivo de
 * CNPJ (12 dígitos) ou CPF (9 dígitos) fornecido. pIsCnpj é booleano e
 * informa se o número-efetivo fornecido é CNPJ (default = false).
 * @param String pEfetivo
 *      String do número-efetivo (SEM dígitos verificadores) de CNPJ ou CPF.
 * @param boolean pIsCnpj
 *      Indica se a string fornecida é de um CNPJ.
 *      Caso contrário, é CPF. Default = false (CPF).
 * @return String com os dois dígitos 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álido.
 * Qualquer formatação que não seja algarismos é desconsiderada.
 * @param String pCpf
 *      String fornecida para ser testada.
 * @return <code>true</code> se a String fornecida for um CPF válido.
 */
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ígitos verificadores
	if (numero != base + digitos) return false;

	/* Não serão considerados válidos 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álido.
 * Qualquer formatação que não seja algarismos é desconsiderada.
 * @param String pCnpj
 *      String fornecida para ser testada.
 * @return <code>true</code> se a String fornecida for um CNPJ válido.
 */
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ígitos verificadores
	if (numero != base + ordem + digitos) return false;

	/* Não serão considerados válidos os CNPJ com os seguintes números BÁSICOS:
	 * 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ão será considerado válido CNPJ com número de ORDEM igual a 0000.
	 * Não será considerado válido CNPJ com número de ORDEM maior do que 0300
	 * e com as três primeiras posições do número BÁSICO com 000 (zeros).
	 * Esta crítica não será feita quando o no BÁSICO 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álido.
 * Se a String tiver uma quantidade de dígitos igual ou inferior
 * a 11, valida como CPF. Se for maior que 11, valida como CNPJ.
 * Qualquer formatação que não 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álido.
 */
function isCpfCnpj(pCpfCnpj)
{
	var numero = pCpfCnpj.replace(/\D/g, "");
	if (numero.length > NUM_DIGITOS_CPF)
		return isCnpj(pCpfCnpj)
	else
		return isCpf(pCpfCnpj);
} //isCpfCnpj
