//testando se é o IE
var isIE = /*@cc_on ! @*/ false;

//inicialização de funções jquery
$('body').ready(function(){
//usando o body.ready pra não usar document.ready e correr o risco de estragar outros 
//documet.ready que tem por outros arquivos

	/* fazendo a substitução dos arrobas falsos */
	var $arrobas = $('span.preenche_arroba');
	$arrobas.html('@');
	var $a_com_arroba = $('a[@href*=preenche_arroba]')
	$a_com_arroba.each(function(){
		var $este = $(this)
		var old_mailto = $este.attr('href');
		var new_mailto = old_mailto.replace('<span class=preenche_arroba> # </span>',"@");
		$este.attr('href',new_mailto);
	})
	
	//estilo para o pessoal que não tem extra-menu
	$lisext = $('#extra-menu li');
	if($lisext.length<1){  //se não tem extra-menu
		$('#extra-menu').css({display: 'none'});
		$('#conteudo').css( { width: 'auto',
							  'margin-left': '10px' })
	}
	
	//zebrando tabelas
	$("tr:nth-child(even)").not('.header').not('.cabec').addClass("tablezebra");
	//obs.: thead e tfoot sempre são zebrados via screen_geral.css
	
});

function ativaEditLite(){
/* setou o edicao lite, tenho que mudar todos os links via jquery */

	var lang = 'edit_lite';

	var as = $('a[@href]'); //todos os links
	as.each(function(){ //mudando todos os links via jquery de acordo com a lang manual setada
		if(this.href.indexOf('mailto')<0){ //pra não pegar mailto
			if(this.href.lastIndexOf('?')>-1){ //já tem outros parametros, então concateno com &
				this.href += "&"+lang;
			}else{//é link limpo, sem parametros ainda, então concateno usando ?
				this.href += "?"+lang;
			}
		}
	});
	
	$('*[@tabela]').each(function(){
		var $this = $(this);
		var $tabela = $this.attr('tabela');
		var $campo = $this.attr('campo');
		var $chave = $this.attr('linha');
		var $tipoinp= $this.attr('tipoinp');
		if($tipoinp.indexOf('Erro table')>-1){ return false; /* se deu erro saio antes de ativar */}
		if(this.nodeName.toUpperCase()!='A' && this.parentNode.nodeName.toUpperCase()!='A'){
			//ativo a edição apenas em quem não é link
		
			var $url_guarda = 'edit-guarda.php?tabela='+$tabela+'&campo='+$campo+'&chave='+$chave;
			var $url_load = 'edit-load.php?tabela='+$tabela+'&campo='+$campo+'&chave='+$chave;
			$this.editable($url_guarda, { 
				postload: $url_load,
				type	: 'textarea',
				indicator : "Salvando...",
				tooltip	: "Duplo clique para editar. ESC para cancelar. TAB > ENTER para salvar",
				event	: "dblclick",
				cssclass: "edit_field",
				submit: "OK",
				cancel: "Cancela",
				onblur: 'ignore'
			});
			$this.mouseover(function(){
				$this.addClass('editavel');
			});
			$this.mouseout(function(){
				$this.removeClass('editavel');
			});
			
		}//endif nodeName==A
		
	});
}


//funções não jquery ----------------------

function htmlEntities(texto){
       //by Micox - elmicox.blogspot.com - www.ievolutionweb.com
    var i,carac,letra,novo='';
    for(i=0;i<texto.length;i++){
        carac = texto[i].charCodeAt(0);
        if( (carac > 47 && carac < 58) || (carac > 62 && carac < 127) ){
            //se for numero ou letra normal
            novo += texto[i];
        }else{
            novo += "&#" + texto[i].charCodeAt(0) + ";";
        }
    }
    return novo;
}

function array_search( busca,oarray){
     //by Micox - elmicox.blogspot.com - www.ievolutionweb.com
    //ve se determinado valor existe no array e retorna sua chave
    for(var i in oarray){
        if(oarray[i]==busca){return i;}    
    }
    return false;
}

function strip_tags($text){
 return $text.replace(/<\/?[^>]+>/gi, '');
}

function replaceHtml(element, html) {
        var oldElement = (typeof element === "string" ? document.getElementById(element): element);
        /*@cc_on // innerHTML puro e mais rápido em IE
                oldElement.innerHTML = html;
                return oldElement;
        @*/
        var newElement = oldElement.cloneNode(false);
        newElement.innerHTML = html;
        oldElement.parentNode.replaceChild(newElement, oldElement);
        /* Como acabamos de remover o elemento antigo do DOM, retornar uma referenca
        ao novo elemento, o qual pode ser utilizado para restaurar referencias da variable */
        return newElement;
};

function number_format(a, b, c, d) {
 /* Made by Mathias Bynens <http://mathiasbynens.be/> */
 a = Math.round(a * Math.pow(10, b)) / Math.pow(10, b);
 e = a + '';
 f = e.split('.');
 if (!f[0]) {
  f[0] = '0';
 }
 if (!f[1]) {
  f[1] = '';
 }
 if (f[1].length < b) {
  g = f[1];
  for (i=f[1].length + 1; i <= b; i++) {
   g += '0';
  }
  f[1] = g;
 }
 if(d != '' && f[0].length > 3) {
  h = f[0];
  f[0] = '';
  for(j = 3; j < h.length; j+=3) {
   i = h.slice(h.length - j, h.length - j + 3);
   f[0] = d + i +  f[0] + '';
  }
  j = h.substr(0, (h.length % 3 == 0) ? 3 : (h.length % 3));
  f[0] = j + f[0];
 }
 c = (b <= 0) ? '' : c;
 return f[0] + c + f[1];
}

/* fazendo o bind */
A = function(enumerable) {
	var array = Array();
	
	for(var i = 0; i < enumerable.length; i)
		array[i] = enumerable[i];
	
	return array;
};

Function.prototype.bind = function() {
	var __method = this, args = A(arguments), object = args.shift();
	return function() {
		return __method.apply(object, args.concat(A(arguments)));
	};
};
/* fim bind */

function $m(quem){
	//substituto mais fácil de digitar para o document.getElementById
	return document.getElementById(quem);
}
String.prototype.trim = function(c, t){
	//* Autor: Yuri Vecchi - 11 August 2005 - E-mail: yuriyoda "arroba" gmail "ponto" com
    return c = "[" + (c == undefined ? " " : c.replace(/([\^\]\\-])/g, "\\\$1")) + "]+",
    this.replace(new RegExp((t != 2 ? "^" : "") + c + (t != 1 ? "|" + c + "$" : ""), "g"), "");
};
function isHtmlObject(objeto){
	//testa se o objeto é um objeto html
	if(typeof(objeto)=="object"){
		if(objeto.nodeName && objeto.parentNode){
			return objeto.nodeName;
		}
	}
	return false;
}
function mouseIsOver(htmObj,e){
	var e = e ? e : window.event;
	var posY = e.pageY
	var altFim = htmObj.offsetTop + htmObj.offsetHeight;
	var posX = e.pageX
	var larFim = htmObj.offsetLeft + htmObj.offsetWidth;
	
	if((htmObj.offsetTop < posY && posY < altFim) &&
	   (htmObj.offsetLeft < posX && posX < larFim) ){
			return true;
		}else{ 
			return false;
		}
}
function array_search(busca,oarray){
	//ve se determinado valor existe no array e retorna sua chave
	for(var i in oarray){
		if(oarray[i]==busca){return i;}	
	}
	return false;
}
function biArraySearch(oarray,buscar,indicebusca,indiceretorno){
	//varre um array bidimensional pesquisando no indicebusca
	//pelo valor que está em 'buscar'. Se achar retorna o valor
	//do indice retorno
	for(x in oarray){
		if(oarray[x][indicebusca]==buscar){ return oarray[x][indiceretorno];}
	}
	return false;
}

function htmlEntities(texto){
	var i,carac,letra,novo='';
	for(i=0;i<texto.length;i++){
		carac = texto[i].charCodeAt(0);
		if( (carac > 47 && carac < 58) || (carac > 62 && carac < 127) ){
			//se for numero ou letra normal
			novo += texto[i];
		}else{
			novo += "&#" + texto[i].charCodeAt(0) + ";";
		}
	}
	return novo;
}
function checaCpf (CPF) {
	//usado no cadastrocampos.php. Verifica se o cpf é válido
	var i,erro;
	CPF = valInt(CPF)
	if (CPF.length != 11 || CPF == "00000000000" || CPF == "11111111111" ||
		CPF == "22222222222" || CPF == "33333333333" || CPF == "44444444444" ||
		CPF == "55555555555" || CPF == "66666666666" || CPF == "77777777777" ||
		CPF == "88888888888" || CPF == "99999999999"){ 	erro = true;  }
	soma = 0;
	for (i=0; i < 9; i ++){	soma += parseInt(CPF.charAt(i)) * (10 - i); }
	resto = 11 - (soma % 11);
	if (resto == 10 || resto == 11) { resto = 0; }
	if (resto != parseInt(CPF.charAt(9))){ erro = true; }
	soma = 0;
	for (i = 0; i < 10; i ++){ soma += parseInt(CPF.charAt(i)) * (11 - i); }
	resto = 11 - (soma % 11);
	if (resto == 10 || resto == 11){ resto = 0; }
	if (resto != parseInt(CPF.charAt(10))){ erro = true; }
	
	return !erro; //CPF TÁ BELEZA!!!
}

function checaCnpj(cnpj) {
	//usado no cadastrocampos.php. Verifica se o cnpj é válido
	var i,x,a=[],b=0,c=[];
	cnpj = valInt(cnpj)
	c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
	for (i=0; i<12; i++){
		a[i] = cnpj.charAt(i);
		b += a[i] * c[i+1];
	}
	if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
	b = 0;
	for (y=0; y<13; y++) {
		b += (a[y] * c[y]);
	}
	if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
	if ((cnpj.charAt(12) != a[12]) || (cnpj.charAt(13) != a[13])){
		return false;
	}else{
		return true;
	}
}

function checaEmail(email){
	//usado no cadastracampos.php. Verifica se o email é válido.
	if (email.search(/^\w+((-\w+)|(\.\w+))*\@\w+((\.|-)\w+)*\.\w+$/) == -1) {
    	return false;
	}else{
	 	return true;
	}
}
function valInt(str){
	//retira tudo nao numérico da string
	var retorno="";
	for(var i=0;i<str.length;i++){
		if(!isNaN(str.charAt(i))){retorno = retorno + str.charAt(i);}
	}
	return retorno
}
function valida(objeto,tipo,mensagem_erro,objeto_mensagem_erro){
	//exemplo: valida($('email'),'email','Email invalido',$('email_cad_inst'))
	//exemplo2: valida('email_cad','email','Email invalido','email_cad_inst')
	var tah_ok,valor;
	objeto = isHtmlObject(objeto) ? objeto : $m(objeto);
	
	switch (tipo){
		case 'email':
			tah_ok = checaEmail(objeto.value.trim());
			break;
		case 'cpf_cnpj'  : 
			if(objeto.value.trim().length>11){
				tah_ok = checaCnpj(objeto.value.trim());
			}else{
				tah_ok = checaCpf(objeto.value.trim());
			}
			break;
		case 'numero' :
			tah_ok = true;
			objeto.value = valInt(objeto.value.trim());
			break;
	}
	
	objeto_mensagem_erro = isHtmlObject(objeto_mensagem_erro) ? objeto_mensagem_erro : $m(objeto_mensagem_erro);
	console.debug(objeto_mensagem_erro.className);
	if(tah_ok){
		
		objeto_mensagem_erro.className.replace(" erroinfo","");
		objeto_mensagem_erro.className.replace(htmlEntities(mensagem_erro),"");
		return true;
	}else{
		if(objeto_mensagem_erro.className.indexOf("erroinfo")<0){
			//se já tá com a mensagem de erro, eu não exibo mensagem dnovo
			objeto.selectionStart=0; objeto.selectionEnd=objeto.textLength;
			setTimeout(function() { objeto.focus() }, 50);
			objeto_mensagem_erro.className += " erroinfo";
			objeto_mensagem_erro.innerHTML = htmlEntities(mensagem_erro);
		}
		return false;
	}
}
function GerarSwfPadrao($onde,$arquivo,$largura,$texto_alternativo,$link_alternativo){
	//by micox - http://elmicox.blogspot.com - micoxjcg@yahoo.com.br
	//exemplo GerarSwf(this,'garantia.swf','95%','Garantia','http://garantia.com')
	var obj = document.createElement('object');
	obj.setAttribute('type','application/x-shockwave-flash');
	obj.setAttribute('data',$arquivo);
	obj.setAttribute('width',$largura);
	obj.setAttribute('wmode','transparent');
	
	var par1 = document.createElement('param');
	par1.setAttribute('movie',$arquivo);
	var par2 = document.createElement('param');
	par2.setAttribute('wmode','transparent');
	
	var alt = document.createElement('a');
	alt.setAttribute('href',$link_alternativo);
	var text = document.createTextNode($texto_alternativo);
	alt.appendChild(text);
	
	obj.appendChild(par1);
	obj.appendChild(par2);
	obj.appendChild(alt);
	
	$onde.appendChild(obj);
}
function GerarSWF($arquivo,$altura,$largura,$texto_alternativo,$link_alternativo){
    var $ret = '\r\n	<object data="' + $arquivo + '" height="' + $altura + '" width="' + $largura;
	$ret += '" type="application/x-shockwave-flash">\r\n';
    $ret += '		<param name="movie" value="' + $arquivo + '" />\r\n';
    $ret += '		<param name="wmode" value="transparent" />\r\n';
	$ret += '		<a href="' + $link_alternativo + '">' + $texto_alternativo + '</a>\r\n';
    $ret += '	</object>\r\n';
	document.write($ret);
}

function DOMgetElementsByClassName($node,$className){
/* Description: retorna um array com todos os elementos dentro
                de $node que possuam a classe indicada em $className
   Versão: 1.0 - 30/08/2006
   Author: Micox - Náiron J.C.G - micoxjcg@yahoo.com.br
   Site:   http://elmicox.blogspot.com 
   Não retire estas informações pra não infringir direitos autorais!
*/
	var $node, $atual, $className, $retorno = new Array(), $novos = new Array();
	$retorno = new Array();
	for (var $i=0;$i<$node.childNodes.length;$i++){
		$atual = $node.childNodes[$i];
		if($atual.nodeType==1){// 1 = XML_ELEMENT_NODE
			$classeAtual = $atual.className;                               
			if(new RegExp("\\b"+$className+"\\b").test($classeAtual)){
			   $retorno[$retorno.length] = $atual;
			}
			if($atual.childNodes.length>0){
			   $novos = DOMgetElementsByClassName($atual,$className);
			   if($novos.length>0){
						   $retorno = $retorno.concat($novos);
			   }
			}
		}
	}
	return $retorno;
}

function addEvent(obj, evType, fn){
    if (obj.addEventListener){
        obj.addEventListener(evType, fn, true)}
    if (obj.attachEvent){
        obj.attachEvent("on"+evType, fn)}
}