var JSAdded=1;

var IsWebOs=0;	
     

var BASEDIR="";

/**FIX para WebOS*/
try{
if(top.IsWebOs == 1){
    if(top.MyOpener!=null && top.MyOpener[window.name]!=null){    
        opener = top.MyOpener[window.name];    
        window.close = function(){ top.closeMe(window.name) };        
    }
 
    $(document).ready(function(){
        $('a').each(function(){            
			var url = $(this).attr('href');   
            if(url!=null){             
			if (url.indexOf("admin_home.php")!=-1) {
				$(this).attr('href', url.replace(/admin_home\.php/g, "wrapper_home.php") );
				$(this).attr('target',"_blank" );
			}
			if (url.indexOf("admsite-")!=-1) {
				$(this).attr('href', "Z"+url+ (url.indexOf("?")!=-1?"&pop=1":"?pop=1"));
				$(this).attr('target',"_blank" );
			}
            }
        });    
        $('a').each(function(){            
			var url = $(this).attr('href');              
			var tg = $(this).attr('target');   
			if (tg=='_blank') {
			     $(this).attr('href', "javascript:{var x=popF('"+url+"');}");	
                 $(this).attr('target','_self');
                   		
			}
        });                 
    });                 
}
}catch(e){}
/**END OF FIX*/
    
var SouOpener = null;
function pop(link, nome){
    if(top.IsWebOs == 1){
        SouOpener = top.appendPopup(nome!=null?nome:'', link, {width:600,height:400}, self);
        return SouOpener;
    }
	return window.open(link,'','width=600,height=400,resizable=no,toolbar=no,directories=no,location=no,menubar=no,status=no,left=' + ((screen.width-600)/2) + ',top=' + ((screen.height-400)/2) + ',scrollbars=yes');
}



var RESTRICAO_GLOBAL=Array();



function popG(link, x, y, nome){
    try{
    if(top.IsWebOs == 1){
        SouOpener = top.appendPopup(nome!=null?nome:'', link, {width:x,height:y}, self);
        return SouOpener;
    }
    }catch(e){}

	return window.open(link,'','width='+x+',height='+y+',resizable=no,toolbar=no,directories=no,location=no,menubar=no,status=no,left=' + ((screen.width-x)/2) + ',top=' + ((screen.height-y)/2) + ',scrollbars=yes');
}

function popF(link, x, y, nome){
    
	x= screen.availWidth;
	y= screen.availHeight;

    try{
    if(top.IsWebOs == 1){
        SouOpener = top.appendPopup(nome!=null?nome:'', link, {full:1}, self);
        return SouOpener;
    }
    }catch(e){}    
	return window.open(link,'','width='+x+',height='+y+',resizable=no,toolbar=no,directories=no,location=no,menubar=no,status=no,left=' + ((screen.width-x)/2) + ',top=' + ((screen.height-y)/2) + ',scrollbars=yes');
}


function ShowHide(id1, id2) {
  if (id1 != '') expMenu(id1);
  if (id2 != '') expMenu(id2);
}

function expMenu(id) {
  var itm = null;
  if (document.getElementById) {
    itm = document.getElementById(id);
  } else if (document.all){
    itm = document.all[id];
  } else if (document.layers){
    itm = document.layers[id];
  }

  if (!itm) {
   // do nothing
  }
  else if (itm.style) {
    if (itm.style.display == "none") { itm.style.display = ""; }
    else { itm.style.display = "none"; }
  }
  else { itm.visibility = "show"; }
}

function ShowHide2(id1, id2) {
  if (id1 != '') expMenu2(id1);
  if (id2 != '') expMenu2(id2);



}

function expMenu2(id) {
  var itm = null;
  if (document.getElementById) {
    itm = document.getElementById(id);
  } else if (document.all){
    itm = document.all[id];
  } else if (document.layers){
    itm = document.layers[id];
  }

  if (!itm) {
   // do nothing
  }
  else if (itm.style) {
    if (itm.style.display == "none") { itm.style.display = ""; }
    else { itm.style.display = "none"; }
  }
  else { itm.visibility = "show"; }

  //modificacao



}


function ExtraiScript(texto){
	
    var ini, pos_src, fim, codigo;
    var objScript = null;
    ini = texto.indexOf('<script', 0)
    while (ini!=-1){
    	
        var objScript = document.createElement("script");
        pos_src = texto.indexOf(' src', ini)
        ini = texto.indexOf('>', ini) + 1;
        if (pos_src < ini && pos_src >=0){
            ini = pos_src + 4;
            fim = texto.indexOf('.', ini)+4;
            codigo = texto.substring(ini,fim);
            codigo = codigo.replace("=","").replace(" ","").replace("\"","").replace("\"","").replace("\'","").replace("\'","").replace(">","");
            objScript.src = codigo;
        }else{
            fim = texto.indexOf('</script>', ini);
            codigo = texto.substring(ini,fim);
            objScript.text = codigo;

        }

        document.body.appendChild(objScript);
        ini = texto.indexOf('<script', fim);
        objScript = null;
    }
}

function showHide(id1, id2) {
  if (id1 != '') expMenu(id1);
  if (id2 != '') expMenu(id2);
}

function expMenu(id) {
  var itm = null;
  if (document.getElementById) {
    itm = document.getElementById(id);
  } else if (document.all){
    itm = document.all[id];
  } else if (document.layers){
    itm = document.layers[id];
  }

  if (!itm) {
   // do nothing
  }
  else if (itm.style) {
    if (itm.style.display == "none") { itm.style.display = ""; }
    else { itm.style.display = "none"; }
  }
  else { itm.visibility = "show"; }
}


function $X(name){
  if (document.getElementById)
  {
  	return document.getElementById(name);
  }
  else if (document.all)
  {
	return document.all[name];
  }
  else if (document.layers)
  {
   	return document.layers[name];
  }
}
function $X(name){
	return document.getElementById(name);
}

/*
Thiago amaral soalheiro

Adekz.com

Copyright © 2006.

É expressamente proibida a copia parcial ou total de qualquer parte desse arquivo.

Versao 2.0 - 23/10/2006*/

function is_object(x){
	return (typeof(x)=="object");
}
function alerta(x){
	document.write(x);
}
function alerta2(x){
	document.getElementById('tar').value+=x;
}
function space(sn){
	var out="";
	for(var i=0; i<sn;i++) out+="&nbsp;";
	return out;
}
function Obj(){
	this.D = Array();
	this.Ds= Array();
	this.add= function (key, val){
		if (this.Ds[key]==1){
			this.addAsArray(key, val);	
		}else if (this.Ds[key]==2){
			this.addInArray(key, val);	
		}else{
			this.addVal(key, val);	
		}
	}
	this.addVal=function (key, val){
		this.D[key]=val;
		this.Ds[key]=1;
	}
	this.addAsArray=function (key, val){
		var A = new Array();
		A[0]=this.D[key];
		A[1]=val;
		this.D[key]=A;
		this.Ds[key]=2;
	}
	this.addInArray=function (key, val){
		this.D[key][this.D[key].length]=val;
	}

	this.existe= function (key){
		return (this.Ds[key]==1 || this.Ds[key]==2);
	}

	this.isArray=function (key){
		return (this.Ds[key]==2);
	}
	this.size=function (key){
		if (!this.existe(key)) return 0;
		if (!this.isArray(key)) return 1;
		return this.D[key].length;
	}
	
	this.get= function (key){
		if(!this.existe(key)) return null;
		return this.D[key];
	}

	this.getA= function (key){
		if(!this.existe(key)) return null;
		var el = this.D[key];
		if(!this.isArray(key)){
			return Array(el);
		}
		return this.D[key];
	}


	this.var_dump= function(sn){ 
		var out="";
		for(var key in this.D){
			out+=space(sn)+key+"=><br>";
			if (!this.isArray(key)){
				if (!is_object(this.D[key])){
					out += space(sn)+space(5)+this.D[key];  
				}else{
					out += this.D[key].var_dump(sn+10);
				}				
			}else{
				out+=space(sn)+space(5)+"{";
				for(var n in this.D[key]){ 
					out+="<br>";
					if (!is_object(this.D[key][n])){ 
						out += space(sn)+space(5)+this.D[key][n];
					}else{ 
						out += this.D[key][n].var_dump(sn+10);
					}
					out += "<br>";
				}
				out += space(sn)+space(5)+"}";
			}
			out+="<br>";
		}
		return out;
	}
}


function Map(){
	this.D = Array();
	this.set=function(key, val){
		this.D[key]=val;
	}
	this.get=function(key){
		if(this.D[key] != 'unsigned')
			return this.D[key];
		else
			return null;
	}
}




/*
Thiago amaral soalheiro

Adekz.com

Copyright © 2006.

É expressamente proibida a copia parcial ou total de qualquer parte desse arquivo.

Versao 2.0 - 23/10/2006*/

function Pilha(){
	this.n = 0;
	this.V = new Array();
	this.push = function (el){
		this.V[this.n++]=el;
	}	
	this.pop = function (){
		return this.V[--this.n];
	}	
}
/**function parsing(txt){
	var i=0;
	
	var tam=txt.length; alert(tam);
	var c;
	var word="";
	var obj = new Obj();
	var nome="";
	var pilha=new Pilha();
	var divd=0;
	while(i<tam){
		c = txt.charAt(i++);
		if (c=="\\"){ 
			c = txt.charAt(i++);
			word+=c;
		}else if(c==","){
			divd=1;
			obj.add(nome, word);
			word="";
		}else if(c==":"){
			divd=1;
			nome = word;
			word="";
		}else if(c=="{"){
			divd=1;
			pilha.push(obj);
			pilha.push(nome);
			obj = new Obj();
		}else if(c=="}"){
			divd=1;
			var ta = obj;
			nome = pilha.pop();
			obj = pilha.pop();
			obj.add(nome,ta);
		}else{
			word+=c;
		}
	}
	alert('here2');
	if (divd==0) return txt;	
	return obj;
}
**/

/**NOva modif. para acelerar em 27/05/07**/
function parsing(txt){
	var i=0;
	
	var tam=txt.length; //alert(txt);
	var c;
	var word="";
	var obj = new Obj();
	var nome="";
	var pilha=new Pilha();
	var divd=0;
	while(i<tam){

		var op = Array();
		 op[0] = txt.indexOf("\\",i);
		 op[1] = txt.indexOf(",",i);
		 op[2] = txt.indexOf(":",i);
		 op[3] = txt.indexOf("{",i);
		 op[4] = txt.indexOf("}",i);
		var mn=999999999;
		var ql = -1;
		for(var h=0;h<5;h++){
			if(op[h]!=-1&& op[h]<mn){
				mn=op[h];
				ql=h;
			}
		}
		if(mn>i+1){
			word+=txt.substring(i, mn);
			i=mn; 
			continue;
		}

		c = txt.charAt(i++);
		if (c=="\\"){ 
			c = txt.charAt(i++);
			word+=c;
		}else if(c==","){
			divd=1;
			obj.add(nome, word);
			word="";
		}else if(c==":"){
			divd=1;
			nome = word;
			word="";
		}else if(c=="{"){
			divd=1;
			pilha.push(obj);
			pilha.push(nome);
			obj = new Obj();
		}else if(c=="}"){
			divd=1;
			var ta = obj;
			nome = pilha.pop();
			obj = pilha.pop();
			obj.add(nome,ta);
		}else{
			word+=c;
		}
	}
	if (divd==0) return txt;	
	return obj;
}

var SIZE=200;
var DEBUGANDO=0;
function getObj(name)
{
  if (document.getElementById)
  {
  	this.obj = document.getElementById(name);
	this.style = document.getElementById(name).style;
  }
  else if (document.all)
  {
	this.obj = document.all[name];
	this.style = document.all[name].style;
  }
  else if (document.layers)
  {
   	this.obj = document.layers[name];
   	this.style = document.layers[name];
  }
}

function $X(name){
  if (document.getElementById)
  {
  	return document.getElementById(name);
  }
  else if (document.all)
  {
	return document.all[name];
  }
  else if (document.layers)
  {
   	return document.layers[name];
  }
}

function getFormAll(numform, destino){
	for (var i=0;i<document.forms[numform].elements.length; i++){
		if (document.forms[numform].elements[i].type=='radio' 
			|| document.forms[numform].elements[i].type=='checkbox' ){
			if (document.forms[numform].elements[i].checked){
				destino.add(document.forms[numform].elements[i].name,document.forms[numform].elements[i].value);
			}
		}else
			destino.add(document.forms[numform].elements[i].name,document.forms[numform].elements[i].value);
	}
}

function getObj(nme){
	return document.getElementById(nme);
}
 

function AjaxData()
{
	this.n=0;
	this.vk = new Array(256);
	this.vd = new Array(256);
	this.addArray = function (oba){
		for(x in oba){
			this.vk[this.n]=x;
			this.vd[this.n++]=$X(x).value;
		}
	}
	this.add = function(key, data){
		this.vk[this.n]=key;
		this.vd[this.n++]=data;		
	}	
	this.make = function(){
		var ret="";
		for (var i=0;i<this.n ;i++){
			if (i!=0)
				ret+="&"+this.vk[i]+"="+escape(this.vd[i]);
			else
				ret+=this.vk[i]+"="+escape(this.vd[i]);
		}
		return ret;
	}
}

function AjaxObject(url, metodo, ajaxdata, retorno){
	this.url = url;
	this.metodo = metodo;
	this.ajaxdata = ajaxdata;
	this.retorno = retorno;
}

function Lista(){
	this.v= new Array(SIZE);
	for (var i=0; i<SIZE ; i++){
		this.v[i]=null;
	}
	this.ns=0;
	this.ne=0;
	this.add = function (obj){
		if (this.cheia()){ return false; }
		this.v[this.ne]=obj;
		this.ne = (this.ne+1)%SIZE;

	}
	this.cheia = function (){
		return ((this.ns == this.ne)&&(this.v[this.ns]!=null));
	}
	this.vazia = function(){
		return (this.ns == this.ne && this.v[this.ns]==null);
	}
	this.get =  function(){
		if (this.vazia()) return null;
		var obj = this.v[this.ns];
		backup = this.v[this.ns];
		this.v[this.ns]=null;
		this.ns = (this.ns+1)%SIZE;
		return obj;
	}	
	this.print =  function(){
		window.alert(this.ns+"//"+this.ne+"//"+this.v);
	}
}


function Ajax(){
   this.semaf=0;	
   this.lista = new Lista();
   this.xmlhttp=null;
   this.handle="";	
   if (window.XMLHttpRequest) {
      this.xmlhttp = new XMLHttpRequest();
   } else if (window.ActiveXObject) {
      this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
   } else {
      alert("Seu navegador n&atilde;o suporta XMLHttpRequest.");
      return;
   }
   this.enviar = function (url, metodo, ajaxdata, retorno){
		this.lista.add(new AjaxObject(url, metodo, ajaxdata, retorno));
		tmp_executa();
   }
   this.start=function (time){
		this.handle = window.setInterval('tmp_executa();',time);
   }
   this.stop=function (){
		window.clearInterval(this.handle);
   }
}

function AjaxResponse(texto){
	try{
	return  parsing(texto);	
	}catch(xrt){
	
	}
	return texto;
}



function tmp_executa(){ 

	if (ajax.semaf==0){
	if (!ajax.lista.vazia()){

		ajax.semaf=1;
		var dao = ajax.lista.get();

		if (dao.metodo=="GET")
		    ajax.xmlhttp.open(dao.metodo, dao.url+"?"+dao.ajaxdata.make(), true);
		else
		    ajax.xmlhttp.open(dao.metodo, dao.url, true);

	    ajax.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
	    ajax.xmlhttp.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
	    ajax.xmlhttp.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");	
	    ajax.xmlhttp.setRequestHeader("Pragma", "no-cache");	

	    ajax.xmlhttp.onreadystatechange = function(){ 
			
			try{
				//alert(ajax.xmlhttp.readyState+"//"+ajax.xmlhttp.status);
				if (ajax.xmlhttp.readyState == 4) {
					if (ajax.xmlhttp.status == 200) {	
						   if (DEBUGANDO==1) {
								alert(ajax.xmlhttp.responseText);
						   }
						  var retornado = (ajax.xmlhttp.responseText); 
						 
						  dao.retorno(AjaxResponse(retornado));	
						  ajax.semaf=0;	
							//alert('qsed');
						  try{/*alert('ended'); */$X('loading').style.display = 'none'; }catch(ekl){}
					}else{
						alert('Falha no carramento ('+ajax.xmlhttp.status+').');						 
						   if (DEBUGANDO==1) {
								alert(ajax.xmlhttp.responseText);
						   }
						ajax.semaf=0;	 
						try{/*alert('ended'); */$X('loading').style.display = 'none'; }catch(ekl){}
					}
				}

			}catch(e){
				ajax.semaf=0;	
			}
		}

		if (dao.metodo=="GET")
		    ajax.xmlhttp.send(null); 		
		else{
			if (DEBUGANDO==1)
				alert(dao.url+"/"+dao.ajaxdata.make());
		    ajax.xmlhttp.send(dao.ajaxdata.make()); 		
		}
		try{ $X('loading').style.display = ''; }catch(ekl){}

	}		
	}	
}



/*
Thiago amaral soalheiro

Adekz.com

Copyright © 2006.

É expressamente proibida a copia parcial ou total de qualquer parte desse arquivo.

Versao 2.0 - 23/10/2006*/



var ajax = new Ajax();
ajax.start(1000);


/*

var ad = new AjaxData();
ad.add('user', 1);

link('amigos', 'mostrafoto.php', 'mostrafoto', 'default', 'br', 'tela', ad );

*/

function link(modulo, href, tpl, tema, lang, target, info, depois){

	var retorno = function(OB_SRC){		
		aplicaTemplate($X(target), modulo, tpl, tema, lang,  OB_SRC, depois);
	}
	ajax.enviar("modulos/"+modulo+"/"+href, "POST", info, retorno);
}

function linkso(modulo, href, target, info, depois){

	var retorno = function(OB_SRC){		
		$X(target).innerHTML = OB_SRC.content;
		if(depois !=null)
			depois();
	}
	ajax.enviar("modulos/"+modulo+"/"+href, "POST", info, retorno);
}

function linkwork(modulo, href, info, depois){

	var retorno = function(OB_SRC){		
		if(depois !=null)
			depois(OB_SRC);
	}
	ajax.enviar("modulos/"+modulo+"/"+href, "POST", info, retorno);
}


function compilar(){

	var retorno = function(OB_SRC){		
		alert(OB_SRC);
	}
	ajax.enviar("modulos/amigos/compilador.php", "POST", new AjaxData(), retorno);
}

function compilaraiz(){

	var retorno = function(OB_SRC){		
		alert(OB_SRC);
	}
	ajax.enviar("compilador.php", "POST", new AjaxData(), retorno);
}








/**COLOQUE SEUS SCRIPTS ANTES DAQUI AQUI **/



function uniqueCode(){
	return new Date().getTime();
}

	function getSelectCampo(tabela, selec, selec2){

		//alert(tabela);return;

		var ad = new AjaxData();
		ad.add("acao", "selectCampo");
		ad.add("tabela", tabela);

		var toDo = function(o){

			var opt = o.getA('option');

			var ret = "<select name='join_campo' id='join_campo'>\n";

			var ret2 = "<select name='join_mostra' id='join_mostra'>\n";
	
			if(opt!=null && opt.length>0){ 					
				for(var i=0; i<opt.length; i++){

					ret += "<option value='"+opt[i]+"'  "+(opt[i]==selec?"selected":"")+">"+opt[i]+"</option>";
					ret2 += "<option value='"+opt[i]+"' "+(opt[i]==selec2?"selected":"")+">"+opt[i]+"</option>";
				}
			}
			
			ret += "</select>";
			ret2 += "</select>";

			$X('SelectCampoRepos').innerHTML = ret;

			$X('SelectCampoRepos2').innerHTML = ret2;
			 

		}
		//DEBUGANDO = 1;
		linkwork("ajax", "load.php", ad, toDo);	
	}



function moveitem(nome1, nome2) {

	var cx1 = document.getElementsByName(nome1)[0];
	var cx2 = document.getElementsByName(nome2)[0];	
	fl = cx2.length -1;
	for (fl; fl > -1; fl--) {
		if (cx2.options[fl].selected) {			
			t = cx1.length;
			opt = new Option( cx2.options[fl].text, cx2.options[fl].value );
			cx1.options[t] = opt;
			cx2.options[fl] = null;			
		}
	}
}	


function autoShowHide(ob){
	var divpai = ob.parentNode;
	var el = divpai.childNodes;
	for(x in el){
		if(el[x].className!=null && (el[x].className.indexOf("data")!=-1 || el[x].className.indexOf("Interno")!=-1)){
			if(el[x].style!=null && el[x].style.display!=null && el[x].style.display=='')
				el[x].style.display='none';
			else
				el[x].style.display='';
		}
	}

}


function createDiv(id){
	var x = document.createElement("DIV");
	x.setAttribute("id", id);
	return x;
}



function cmpValue(els, val){
	if(els==null) return true;
    
                            
    
	var any=0;
	var one=0;
	for(var i=0; i<els.length; i++){

		if(els[i].type=='checkbox'||els[i].type=='radio'){ 
			one=1;
			if(els[i].checked) any=1;
		}else{

			if(els[i].value.trim() == val){
			     /**FIX.. nao obrigar campos ocultos*/
                 
                                 
                 if($(els[i]).parents('#wpcaixa_'+$(els[i]).attr('name')).css('display') =='none') return false;
                 
                 //if(!$(els[i]).parents('#wpcaixa_'+$(els[i]).attr('name')).is(':visible')) return false;

             
			     return true;
            }
		}
	}
	if(one==1 && any==0) return true;
	return false;
	
}
function temAlgum(els){
	if(els==null) return true;
	var any=0;
	var one=0;
	for(var i=0; i<els.length; i++){
		if(els[i].options.length>0){ return true;}
	}
	if(one==1 && any==0) return true;
	return false;
	
}

function cmpPregValue(els, val){
	if(els==null) return true;
	var any=0;
	var one=0;
	for(var i=0; i<els.length; i++){
		if(els[i].type=='checkbox'||els[i].type=='radio'){ 
			one=1;
			if(els[i].checked) any=1;
		}else{
			var reDigits = val;
			
			if (!reDigits.test(els[i].value)) return true;
		}
	}
	if(one==1 && any==0) return true;
	return false;
	
}
function getElementsByName_iefix(name) {
     
     var elem = document.getElementsByTagName("input");
     var arr = new Array();
     for(i = 0,iarr = 0; i < elem.length; i++) {
          att = elem[i].getAttribute("name");
          if(att == name) {
               arr[iarr] = elem[i];
               iarr++;
          }
     }
     return arr;
}

function movCk(nome){
	var hd = document.getElementsByName(nome+'_list')[0];
	var dt = getElementsByName_iefix(nome);

	hd.value = "";
	for(var x in dt){
		if(dt[x].checked)
			hd.value += (hd.value!=""?";":"")+dt[x].value;
	}
}

function mkHidden(nome){
	var hd = document.getElementsByName(nome+'_list')[0];
	var dt = document.getElementsByName(nome)[0];

	hd.value = "";
	for (var fl=0; fl < dt.length; fl++) {
		hd.value += (fl>0?";":"")+dt.options[fl].value;
	}
}

function movDir(nome){
	var or = document.getElementsByName(nome+'_all')[0];
	var dt = document.getElementsByName(nome)[0];
	var fl = or.length -1;
	var au = dt.length -1;
 
	for (fl; fl > -1; fl--) {
		if (or.options[fl].selected){
			t = dt.length;
			opt = new Option( or.options[fl].text, or.options[fl].value );
			dt.options[t] = opt;
			or.options[fl] =null;
		}
	}
	$(dt).find('option').attr("selected","selected");

	dt.focus();
	mkHidden(nome);
}

function movEsq(nome){
	var or = document.getElementsByName(nome+'_all')[0];
	var dt = document.getElementsByName(nome)[0];

	fl = dt.length -1;

	for (fl; fl > -1; fl--) {
		if (dt.options[fl].selected) {
			
			t = or.length;
			opt = new Option( dt.options[fl].text, dt.options[fl].value );
			or.options[t] = opt;
			dt.options[fl] = null;
			
		}
	}
	$(dt).find('option').attr("selected","selected");	
	dt.focus();
	
	mkHidden(nome);
}

function PREG(er){
	return er;
}




function MascaraMoeda(objTextBox, SeparadorMilesimo, SeparadorDecimal, e){
	if (!e) var e = window.event;


	var sep = 0;
	var key = '';
	var i = j = 0;
	var len = len2 = 0;
	var strCheck = '-0123456789';
	var aux = aux2 = '';
	var whichCode = -1;
	if (e.keyCode) whichCode = e.keyCode;
	else if (e.which) whichCode = e.which;
	
	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 = objTextBox.value.length;
	for(i = 0; i < len; i++)
		if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) break;
	aux = '';
	for(; i < len; i++)
		if (strCheck.indexOf(objTextBox.value.charAt(i))!=-1) aux += objTextBox.value.charAt(i);
	aux += key;
	len = aux.length;
	if (len == 0) objTextBox.value = '';
	if (len == 1) objTextBox.value = '0'+ SeparadorDecimal + '0' + aux;
	if (len == 2) objTextBox.value = '0'+ SeparadorDecimal + aux;
	if (len > 2) {
		aux2 = '';
		for (j = 0, i = len - 3; i >= 0; i--) {
			if (j == 3) {
				aux2 += SeparadorMilesimo;
				j = 0;
			}
			aux2 += aux.charAt(i);
			j++;
		}
		objTextBox.value = '';
		len2 = aux2.length;
		for (i = len2 - 1; i >= 0; i--)
		objTextBox.value += aux2.charAt(i);
		objTextBox.value += SeparadorDecimal + aux.substr(len - 2, len);
	}
	return false;
}

function setaOrdenacao(nome, tabela, chave){
	$("#"+nome).css('cursor', 'move');
	$("#"+nome).sortable({
		update: function(event, ui){
			serial=$("#"+nome).sortable('serialize');
			$.ajax({
				url: BASEDIR+"ajax-orderby?table="+tabela+"&pkname="+chave+"",
				type: "post",
				data: serial,
				error: function(){
					alert("theres an error with AJAX");
				}
				});
		}
	});
	$("#"+nome).disableSelection();	
}


var OB_TRIGED = "";
function trigame(id){
	OB_TRIGED=id;
	pop('admin_codedit.php?pop=1&type=php');
}
function trigame_do(){
	return $X(OB_TRIGED).value;	
}
function trigame_done(x){
	$X(OB_TRIGED).value=x;	
}

var globalMegaMaster=Array();
var globalEscape=Array();


var GLOBAL_TRIGGER_EVENT_CHANGE=Array();

/**Ajax para puxar subselect ao marcar um q seja pai**/
function registra_trigger_mjoin(docampo, nocampo, tabela, cleararray){

	globalMegaMaster[nocampo]=docampo;

	if($('#'+docampo).is('input[type=hidden]')){

    $('#VDT_'+docampo).keyup(function(e){
        if(e.keyCode>30){
    		var more = "<option value='-1'>Selecione...</option>";
            $('#'+nocampo).html(more);
        }
    });
    
    GLOBAL_TRIGGER_EVENT_CHANGE['#'+docampo] = function(){
		
		var more = "<option value='-1'>Selecione...</option>";

		if(!$('#'+nocampo).is('input'))
	        $('#'+nocampo).html(more);
		else
	        $('#'+nocampo).val('');
        
		if(cleararray!=null)
        for(var x in cleararray){
			if(!$('#'+cleararray[x]).is('input'))
		    	$('#'+cleararray[x]).html(more);		
			else
		    	$('#'+cleararray[x]).val('');		
    	}


		$.post(BASEDIR+'ajax-fn?function=ajax_multijoin&_MASTER_'+docampo+'='+$('#'+docampo).val(),{
			p1: tabela,
			p2: nocampo

		},function(o){
			$.each(o, function(i,item){
				globalMegaMaster[nocampo]=docampo;

				if(item.dados!=""){
					if(!$('#'+nocampo).is('input'))
	    				$('#'+nocampo).html(more+unescape(item.dados).replace(/\+/g, " "));
					else
	    				$('#'+nocampo).val('');

				}else{
					if(!$('#'+nocampo).is('input'))
						$('#'+nocampo).html(more);
					else
						$('#'+nocampo).val('');
				}
                
                var solo = "Modelo único";
                $('#'+nocampo+' option').each(function(){
                    if($(this).val()=="-1") return;
                    
                    if($(this).html()==solo){
                        $('#'+nocampo).val($(this).val());
                    }
                });
            });                
		},"json");
        
    };
     
     return;  
    } 
    
    $('select#'+docampo+' , #wpcaixa_'+docampo+" input").change(function(){  

        if($(this).is("select") || $(this).is(":checked") ){   
        }else{
			
			
			return;
		}
        
		var more = "<option value='-1'>Selecione...</option>";

		if(!$('#'+nocampo).is('input'))
	        $('#'+nocampo).html(more);
		else
	        $('#'+nocampo).val('');
        
		if(cleararray!=null)
        for(var x in cleararray){
			if(!$('#'+cleararray[x]).is('input'))
		    	$('#'+cleararray[x]).html(more);		
			else
		    	$('#'+cleararray[x]).val('');		
    	}

		$.post(BASEDIR+'ajax-fn?function=ajax_multijoin&_MASTER_'+docampo+'='+$('#'+docampo).val(),{
			p1: tabela,
			p2: nocampo

		},function(o){
			$.each(o, function(i,item){
				globalMegaMaster[nocampo]=docampo;

				if(item.dados!=""){
					if(!$('#'+nocampo).is('input'))
	    				$('#'+nocampo).html(more+unescape(item.dados).replace(/\+/g, " "));
					else
	    				$('#'+nocampo).val('');

				}else{
					if(!$('#'+nocampo).is('input'))
						$('#'+nocampo).html(more);
					else
						$('#'+nocampo).val('');
				}


			});				
		},"json");
        
    });
	
}

/**Js para chamar restricoes de campo radio**/
function restringe_funcoes_globais(nome,tabela,valorselecionado){ 

    if(valorselecionado=='0')
    if(RESTRICAO_GLOBAL!=null && RESTRICAO_GLOBAL["on_"+tabela+"_"+nome+"_"]!=null){
        RESTRICAO_GLOBAL["on_"+tabela+"_"+nome+"_"]();
    }
    
    $('input[name='+nome+']').change(
        function(){     
            $('input[name='+nome+']:checked').each(                
                function(){
                    if(this.value==valorselecionado &&  this.checked){
                        if(RESTRICAO_GLOBAL!=null && RESTRICAO_GLOBAL["on_"+tabela+"_"+nome+"_"+this.value]!=null){
                            RESTRICAO_GLOBAL["on_"+tabela+"_"+nome+"_"+this.value]();
                        }   
                    }        
                }
                
            );     
        }
    );
    
    
}


/**Js para chamar restricoes de campo select**/
function restringe_funcoes_globais_sel(nome,tabela,valorselecionado){ 

    if(valorselecionado=='-1' || valorselecionado==''){
    if(RESTRICAO_GLOBAL!=null && RESTRICAO_GLOBAL["on_"+tabela+"_"+nome+"_"]!=null){
        RESTRICAO_GLOBAL["on_"+tabela+"_"+nome+"_"]();
    }
	}
    
    $('select[name='+nome+']').change(
        function(){     

                        if(RESTRICAO_GLOBAL!=null && RESTRICAO_GLOBAL["on_"+tabela+"_"+nome+"_"+this.value]!=null){
                            RESTRICAO_GLOBAL["on_"+tabela+"_"+nome+"_"+this.value]();
                        }   
                }
                
                 
        
    );
    
    
}


/***chamada ajax de funcoes****/
function ajax_load_json(funcao, params, after){

		$.post(BASEDIR+'ajax-fn?function='+funcao,params,after,"json");
}



/***chamada ajax de objetos****/
function ajax_load_obj(destino, objeto, params, after, destino2){

		$.post(BASEDIR+'ajax-fn?function=ajax_load_obj&obj='+objeto,params,function(o){
		    if(destino != null)		      
    			destino.html(o);
		    if(destino2 != null)		      
    			destino2.html(o);
            
            if(after!=null)
                after(o);
            				
		},"html");
}


/***chamada ajax de action****/
function ajax_load_action(meudestino, action, params, after, destino2){
    //alert(params);
		$.post(BASEDIR+'acao-'+action,params,function(o){
		    if(meudestino != null){
			     meudestino.html(o);
            }
		    if(destino2 != null)
			     destino2.html(o);
                 
            if(after!=null)
                after(o);
            				
		},"html");
}

/***chamada ajax de action com retorno em JSON****/
function ajax_load_action_json( action, params, after){

		$.post(BASEDIR+'acao-'+action+'?json_mode=1',params,after,"json");
}


/**ADICIONA FUNCIONALIDADE TO JSON**/
(function($){function toIntegersAtLease(n)
{return n<10?'0'+n:n;}
Date.prototype.toJSON=function(date)
{return this.getUTCFullYear()+'-'+
toIntegersAtLease(this.getUTCMonth())+'-'+
toIntegersAtLease(this.getUTCDate());};var escapeable=/["\\\x00-\x1f\x7f-\x9f]/g;var meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'};$.quoteString=function(string)
{if(escapeable.test(string))
{return'"'+string.replace(escapeable,function(a)
{var c=meta[a];if(typeof c==='string'){return c;}
c=a.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+(c%16).toString(16);})+'"';}
return'"'+string+'"';};$.toJSON=function(o,compact)
{var type=typeof(o);if(type=="undefined")
return"undefined";else if(type=="number"||type=="boolean")
return o+"";else if(o===null)
return"null";if(type=="string")
{return $.quoteString(o);}
if(type=="object"&&typeof o.toJSON=="function")
return o.toJSON(compact);if(type!="function"&&typeof(o.length)=="number")
{var ret=[];for(var i=0;i<o.length;i++){ret.push($.toJSON(o[i],compact));}
if(compact)
return"["+ret.join(",")+"]";else
return"["+ret.join(", ")+"]";}
if(type=="function"){throw new TypeError("Unable to convert object of type 'function' to json.");}
var ret=[];for(var k in o){var name;type=typeof(k);if(type=="number")
name='"'+k+'"';else if(type=="string")
name=$.quoteString(k);else
continue;var val=$.toJSON(o[k],compact);if(typeof(val)!="string"){continue;}
if(compact)
ret.push(name+":"+val);else
ret.push(name+": "+val);}
return"{"+ret.join(", ")+"}";};$.compactJSON=function(o)
{return $.toJSON(o,true);};$.evalJSON=function(src)
{return eval("("+src+")");};$.secureEvalJSON=function(src)
{var filtered=src;filtered=filtered.replace(/\\["\\\/bfnrtu]/g,'@');filtered=filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']');filtered=filtered.replace(/(?:^|:|,)(?:\s*\[)+/g,'');if(/^[\],:{}\s]*$/.test(filtered))
return eval("("+src+")");else
throw new SyntaxError("Error parsing JSON, source is not valid.");};})(jQuery);
$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};
/**ADICIONA FUNCIONALIDADE TO JSON**/




$.fn.jSONifica = function()
{
    return $.toJSON(this.serializeObject());

};




/***RESIZE DE IFRAMES**/

function getDocHeight(doc) {
  var docHt = 0, sh, oh;
  if (doc.height) docHt = doc.height;
  else if (doc.body) {
    if (doc.body.scrollHeight) docHt = sh = doc.body.scrollHeight;
    if (doc.body.offsetHeight) docHt = oh = doc.body.offsetHeight;
    if (sh && oh) docHt = Math.max(sh, oh);
  }
  return docHt;
}

var udoch=Array();

function setIframeHeight(ifrm) {
  var iframeWin = window.frames[ifrm];
  var iframeEl = document.getElementById ? document.getElementById(ifrm): document.all ? document.all[ifrm]: null;
  

  if ( iframeEl && iframeWin ) {
    //iframeEl.style.height = "auto"; // helps resize (for some browsers) if new doc is shorter than previous	    
    
    if(iframeWin.location.href.indexOf("site-end")!=-1)
    	iframeEl.src="about:blank";


	if(typeof iframeWin.takeAltura == 'function') { 
	    var docHt = iframeWin.takeAltura();
	}else{
		var docHt = getDocHeight(iframeWin.document);
		//return;
	}
    
    if (docHt)if(udoch[ifrm]!=docHt){ iframeEl.style.height = docHt + 0 + "px"; udoch[ifrm]=docHt;}
  }
}	

function lockDiv(div){
    
    (div).find('.item').css("position","relative");
    if((div).find(".locked").size()<=0){
        (div).find('.item').append("<div class='locked'>&nbsp;</div>");        
    }else{
        (div).find('.locked').remove();
        
    }
}


var VALIDACAO_GERAL_NODES= new Array();
function validacao_geral(){
    var erro = "";
    
     for(var x in VALIDACAO_GERAL_NODES){
    
            var fns = VALIDACAO_GERAL_NODES[x];
     
            var resul = fns[1]();
            if(resul!=""){
                document.getElementById('cpo_'+fns[0]).className = 'comerro';
                erro += resul;
            }else{
                document.getElementById('cpo_'+fns[0]).className = 'semerro';
            }
     }
     return erro;
}
function validacao_geral_add_node(no,funcao){
    VALIDACAO_GERAL_NODES[VALIDACAO_GERAL_NODES.length]=[no,funcao];
}



function tplEstrutural(aba, secao, secaon, campo, acao){
        secaon=secaon==null?1:secaon;
        
        if(campo!=null){
            acao($('#wpcaixa_'+campo));    
        }else{
            if(aba!=null && secao==null){
                acao($('#menu-abas li:nth-child('+aba+')'), $('#wrapper-abas .aba:nth-child('+aba+')'));    
            }else if(aba!=null && secao!=null){
                acao($('#wrapper-abas .aba:nth-child('+aba+') .'+secao+':nth-child('+secaon+')') );  
            }
        }
        
}




	
/***define as abas a exibir e mostra a inicial*/    
function abasshow(array, ini, ativo){
    
    
    var nc=0;
    $('#wrapper-abas .aba').hide();
    $('#wrapper-abas .aba').each(function(){
        nc++;
        
        for(var ex in array){
            if(nc == array[ex]){
                if(nc<=1)
                    $(this).show();
                    
                    
            }            
        }
        
        /**oculta abas não solicitadas*/
        var sim=0;
        if(ativo!=null){
            for(var ex in ativo){
                if(nc == array[ex]){                
                   sim=1;
                }            
            }
            if(sim==0){setReadOnlyAba($(this));}
        }
        
        
    });

    
    var nc=0;
    var obf=null;
    $('#menu-abas > ul > li').hide();
    $('#menu-abas > ul > li').each(function(){
        nc++; 
        for(var ex in array){ 
            if(nc == array[ex]){
                $(this).show();
                if(nc == ini){
                    obf=$(this);
                    obf.trigger('click');                    
                }    
                
            }   
                     
        }
    });

    
    

}    
    
function setReadOnlyAba(aba){
    aba.css('position','relative');
    var oloko = $("<div class='read-only'>&nbsp;</div>");
    aba.append(oloko);    
}
    
var GLOBAL_LOAD_PARAM="";    
    
var GLOBAL_cache_select=Array();
$(document).ready(function() {

    $('#wrapper-center #form_adder  select,  #wrapper-center .ListHeader select, #WrapperRight #form_adder  select,  #WrapperRight .ListHeader select, .wrappered #form_adder  select,  .wrappered .ListHeader select ').live('focus',function(){ 

        var selc = $(this);
        if(selc.find('option').size()<200) return;     
               
        if( globalMegaMaster!=null &&  globalMegaMaster[selc.attr('id')]!=null && selc.parents(".ListHeader").size()==0 ) return;
        if( globalEscape!=null &&  globalEscape[selc.attr('id')]!=null) return;
        
		if(selc.parents('div').find('select').size()>1 && selc.parents('#form_adder').size()>1 ) return;

		
        if(selc.attr('id').indexOf("filter_valor")!=0){ //se é de form
        
            if(GLOBAL_cache_select['p1='+selc.attr('id')+'&p2='+GLOBAL_NOME_TABELA_ATUAL+''+GLOBAL_LOAD_PARAM]==null){
                
                var valorselecionado = selc.val();
                selc.after("<span>Aguarde enquanto os itens são carregados...</span>");
                selc.hide();

                         
                $.post(BASEDIR+"ajax-fn?function=lazyload&p1="+selc.attr('id')+"&p2="+GLOBAL_NOME_TABELA_ATUAL+""+GLOBAL_LOAD_PARAM, null, function(o){
                    if(o==null){
                        selc.next("span").remove();
                        selc.show();
                        return;
                    }                    
                    selc.find('option').remove();                       
                    selc.append("<option value='-1'>Selecione...</option>");

                    var nd = o.nodes;
                    for(var a in nd){    
                        
                        selc.append("<option value='"+nd[a].id+"'>"+nd[a].val+"</option>");                
                    }
                    selc.next("span").remove();
                    if(valorselecionado!=null)
                        selc.val(valorselecionado);
                        
                    selc.show();
                        
                },"json");
                GLOBAL_cache_select["p1="+selc.attr('id')+"&p2="+GLOBAL_NOME_TABELA_ATUAL+GLOBAL_LOAD_PARAM]=1;                    
            }
            
        }else{        //se é de filtro
            
            var qualcampoqeh="";

            if(selc.attr('id')=='filter_valor'){                
                qualcampoqeh=$('#filter_filtro').val().split(".")[1];
            }else{
				if(selc.attr('id').indexOf('filter_valor')!=-1){                
					qualcampoqeh=selc.attr('id').split(".")[1];
				}
			}
            
            if(GLOBAL_cache_select['FT-p1='+qualcampoqeh+'&p2='+GLOBAL_NOME_TABELA_ATUAL+''+GLOBAL_LOAD_PARAM]==null){
                
                var valorselecionado = selc.val();
                selc.after("<span>Aguarde enquanto os itens são carregados...</span>");
                selc.hide();
                               
       
                $.post(BASEDIR+"ajax-fn?function=lazyload&p1="+qualcampoqeh+"&p2="+GLOBAL_NOME_TABELA_ATUAL+""+GLOBAL_LOAD_PARAM, null, function(o){
                    if(o==null){
                        selc.next("span").remove();
                        selc.show();
                        return;
                    }
                    selc.find('option').remove();                         
                    selc.append("<option value='-1'>Selecione...</option>");
                    var nd = o.nodes;
                    for(var a in nd){    
                        
                        selc.append("<option value='fixo:"+nd[a].id+"'>"+nd[a].val+"</option>");                
                    }
                    selc.next("span").remove();
                    if(valorselecionado!=null)
                        selc.val(valorselecionado);
                        
                    selc.show();
                                            
                },"json");
                GLOBAL_cache_select["FT-p1="+qualcampoqeh+"&p2="+GLOBAL_NOME_TABELA_ATUAL+GLOBAL_LOAD_PARAM]=1;                    
            }
        
        }
        
    });

});

