// No if pode-se adicionar mais teclas restritas!
function rejeitaTecla(oEvent){
    var oEvent = oEvent ? oEvent : window.event;
    var tecla = (oEvent.keyCode) ? oEvent.keyCode : oEvent.which;
	if(tecla == 17 || tecla == 44|| tecla == 106){
		alerta();
 	}
}

// Restringe botão ctrl/alt gr
//document.onkeypress = rejeitaTecla;
//document.onkeydown = rejeitaTecla;
//end
// Restringe botão direito do mouse
//document.oncontextmenu = alerta;
// end


//-----------------------------------------------------

function str_ltrim(aString)
{
  return aString.replace(/^[\s]+/g,"");
}
//-----------------------------------------------------

function redireciona(src){
	window.location = src;
}


//-----------------------------------------------------

function str_rtrim(aString)
{
  return aString.replace(/[\s]+$/g,"");
}


//-----------------------------------------------------

function remCaracteres(texto, padrao)
{
   var Char;
   for (i = 0; i < texto.length; i++) 
   { 
	      Char = texto.charAt(i);
	      if (padrao.indexOf(Char) != -1) texto = texto.replace(texto.charAt(i),"");
   }
   return texto;
   
}

//-----------------------------------------------------

function isCpf(s){
   var i;
   var cpf = s.value;
   switch(cpf){
      case "000.000.000-00":
      case "111.111.111-11":
      case "222.222.222-22":
      case "333.333.333-33":
      case "444.444.444-44":
      case "555.555.555-55":
      case "666.666.666-66":
      case "777.777.777-77":
      case "888.888.888-88":
      case "999.999.999-99":
        alert("CPF Invalido");
		s.value = "";
        s.focus();
        return false;
   }
   cpf = remCaracteres(cpf, ".-");
   
   var c = cpf.substr(0,9);
   var dv = cpf.substr(9,2);
   var d1 = 0;
   for (i = 0; i < 9; i++)
   {
    d1 += c.charAt(i)*(10-i);
   }
   if (d1 == 0 && s.value != ""){
    alert("CPF Invalido");
	s.value = "";
    s.focus();
    return false;
   }
   d1 = 11 - (d1 % 11);
   if (d1 > 9) d1 = 0;
   if ((dv.charAt(0) != d1) && s.value != "")
   {
    alert("CPF Invalido");
	s.value = "";
    s.focus();
    return false;
   }
   d1 *= 2;
   for (i = 0; i < 9; i++)
   {
    d1 += c.charAt(i)*(11-i);
   }
   d1 = 11 - (d1 % 11);
   if (d1 > 9) d1 = 0;
   if (dv.charAt(1) != d1 && s.value != "")
   {
    alert("CPF Invalido");
	s.value = "";
    s.focus();
   }
   return true;
}

//-----------------------------------------------------

function isDate(OBJ)
{
  var dia = OBJ.value.substring(0,2);
  
  if (OBJ.value.substring(3,5) < 10)
   var mes = OBJ.value.substring(4,5);
  else
  var mes = OBJ.value.substring(3,5);

  var ano = OBJ.value.substring(6,10);
  
  if(( ano%4==0 && ano%100 !=0 ) || ( ano%400==0 ) )
   fev = 29;
  else
   fev = 28;
   
  var array_mes = new Array(31,fev,31,30,31,30,31,31,30,31,30,31);
  var indice = mes-1;
  if (((dia > array_mes[indice] || dia <= 0) || (mes > 12 || mes <= 0) || (ano < 1910 || ano > 2100)) && (OBJ.value != "")){
   alert("Data Inválida.");
   
   OBJ.value = "";
   OBJ.focus();
   return false;
  }
  
  return true;

}

//-----------------------------------------------------

function isEmail(email) {
   var objRegExp = /^[A-Za-z]([\w\.\-]*)@([A-Za-z0-9\.\-]*)\.(([A-Za-z]{3}\.[A-Za-z]{2}$)|([A-Za-z]{2}\.[A-Za-z]{2}$)|([A-Za-z]{3}$)|([a-z]{2}$))/i;
   if((objRegExp.test(email.value) == false) && (email.value != "")) {
    alert("E-mail inválido.");
    email.value = "";
    email.focus();
   }
}

//-----------------------------------------------------

function isNumeric(str)
{   
    var len = str.value.length;
    
    for (i=0; i<len; i++)
    {   
       c = str.value.charAt(i);
       if (c < '0' || c > '9')
       {
          alert ("Este campo não deve conter letras ou caracteres especiais");
          str.value = "";		  
          str.focus();
          return false;
       }
       
    }    
	str.className = 'formCampo_imovel';
    return true;
}

//-----------------------------------------------------

function mascara_hora(hora_cine){
    var myhora = '';
    myhora = myhora + hora_cine;
    if (myhora.length == 2){
        myhora = myhora + ':';
        document.forms[0].hora_cine.value = myhora;
    }
    if (myhora.length == 5){
       verifica_hora();
    }
}

//-----------------------------------------------------

function verifica_hora(){
    hrs = (document.forms[0].hora_cine.value.substring(0,2));
    min = (document.forms[0].hora_cine.value.substring(3,5));
             
    //alert('hrs '+ hrs);
    //alert('min '+ min);
             
    situacao = "";
    // verifica data e hora
    if ((hrs < 00 ) || (hrs > 23) || ( min < 00) ||( min > 59)){
       situacao = "falsa";
    }
             
    if (document.forms[0].hora_cine.value == "") {
       situacao = "falsa";
    }

    if (situacao == "falsa") {
        alert("Hora inv&aacute;lida!");
        document.forms[0].hora_cine.focus();
    }
} 



//-----------------------------------------------------
 
 function IsNum(valor)
 {
   var numeros = "0123456789.";
   var num = true;
   var Char;

 
   for (i = 0; i < valor.value.length && num == true; i++) 
      { 
      Char = valor.value.charAt(i); 
      if (numeros.indexOf(Char) == -1) 
         {
         	num = false;
			alert ("Este campo não deve conter letras ou caracteres especiais");
			valor.value = "";
			valor.className = 'formCampoErrado_imovel';
			valor.focus();
			return num;
         }
      }
   valor.className = 'formCampo_imovel';
   return num;
 
 }
 
//-----------------------------------------------------
 
 function formataCampo(frm_campo, tipo)
 {
 	var valor = frm_campo.value;
 	var len = valor.lenght;
 	var novo_valor=''; 	
 	
 	switch (tipo){
 	
 		case "cep":	
 		
 			if (len < 8){
 				for (i=1;i<(8-len);i++){
 					novo_valor&='0';
 				}
 			}
 			novo_valor &= 
 			valor.substr(0,3) & '.' &
 			valor.substr(3,3) & '.' &
 			valor.substr(6,3) & '-' &
 			valor.substr(9,2);
 				
 		break;
 			
 		case "cpf":	
 		
 			if (len < 11){
 				for (i=1;i<(11-len);i++){
 					novo_valor&='0';
 				}
 			}
 			novo_valor &= 
 			valor.substr(0,3) & '.' &
 			valor.substr(3,3) & '.' &
 			valor.substr(6,3) & '-' &
 			valor.substr(9,2);
 				
 		break;
 				
 		case "cnpj":
 		
 			if (len < 14){
 				for (i=1;i<(14-len);i++){
 					novo_valor&='0';
 				}
 			} 		
 			novo_valor &= 
 			valor.substr( 0,2) & '.' &
 			valor.substr( 2,3) & '.' &
 			valor.substr( 5,3) & '/' &
 			valor.substr( 8,4) & '-' &
 			valor.substr(12,2);
 			
 		break;
 		
 	}
 }
 
//-----------------------------------------------------
 
 function FormataDado(campo,tammax,pos,teclapres){
	var tecla = teclapres.keyCode;
	vr = document.form[campo].value;
	vr = vr.replace( ".", "" );
	vr = vr.replace( "/", "" );
	tam = vr.length ;

	if (tam < tammax && tecla != 8){ tam = vr.length + 1 ; }

	if (tecla == 8 ){ tam = tam - 1 ; }
			
	if ( tecla == 8 || tecla == 88 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
		if ( tam <= 2 ){
	 		document.form[campo].value = vr ;}
		if ( tam > pos && tam <= tammax ){
			document.form[campo].value = vr.substr( 0, tam - pos ) + '.' + vr.substr( tam - pos, tam );}
	}
	//alert("campo: " + document.form[campo+1].name);
	if ( !teclapres.shiftKey && tecla == 9 && document.form[campo+1].name == "valor_pagamento_titulo_pagamento" && document.applets['tclJava'] ){
		//alert("aki 1");
			document.applets['tclJava'].setFocus();
	}
}

//-----------------------------------------------------
 
 function mostraLegenda(TEXTO) {
		document.legenda.texto.value = TEXTO;
		return true;
 }

//-----------------------------------------------------

function mudaimagem(ID, IMAGEM)	{
		document.getElementById(ID).src = IMAGEM;
}
	
//-----------------------------------------------------

function FormataMoeda(fld, e) { 

	var milSep = ".";
	var decSep = ",";
	var sep = 0; 
	var key = ''; 
	var i = j = 0; 
	var len = len2 = 0; 
	var strCheck = '0123456789'; 
	var aux = aux2 = ''; 
	var whichCode = (window.Event) ? e.which : e.keyCode; 
	
    // Apenas números, backspace ou delete
    if((whichCode > 47 && whichCode < 58) ||
        whichCode == 0 ||
        whichCode == 8)
    {
	
//	if (whichCode == 13) return true;  
		key = String.fromCharCode(whichCode);
//	if (strCheck.indexOf(key) == -1) return false;  
		len = fld.value.length; 
	
//	alert(key);
		
    if(fld.value.length == fld.size)
       fld.value = fld.value.charAt(2) + fld.value.charAt(1) + fld.value.charAt(3) + 
    				fld.value.charAt(4) + fld.value.charAt(6) + fld.value.charAt(5) +
    				fld.value.charAt(7) + fld.value.charAt(8) + key;
        //fld.value = '';
		
	else if (fld.value.length < fld.size) {
		for(i = 0; i < len; i++) 
			if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break; 
		aux = ''; 
		for(; i < len; i++) 
			if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i); 
		aux += key; 
		len = aux.length; 
		if (len == 0) fld.value = ''; 
		if (len == 1) fld.value = '0'+ decSep + '0' + aux; 
		if (len == 2) fld.value = '0'+ decSep + aux; 
		if (len > 2) { 
		aux2 = ''; 
		for (j = 0, i = len - 3; i >= 0; i--) { 
			if (j == 3) { 
				aux2 += milSep; 
				j = 0; 
			} 
			aux2 += aux.charAt(i); 
			j++; 
		} 
		fld.value = ''; 
		len2 = aux2.length; 
		for (i = len2 - 1; i >= 0; i--) 
			fld.value += aux2.charAt(i); 
			fld.value += decSep + aux.substr(len - 2, len); 
		} 
	}
	// Se tecla backspace ou delete
	if (whichCode == 8 || whichCode == 0)
	{
	   fld.value = '';
	   fld.focus();
	}
    }
	return false; 
} 

//-----------------------------------------------------

function moveOptions(origem, destino) 
	{
	  var y=0;
	  var tam_origem = origem.options.length;
	  
	  for ( var x = 0; x < origem.options.length; x++ ) {
	    if ( origem.options[x].selected ) { 
		  destino.options[destino.options.length] = new Option(origem.options[x].text, origem.options[x].value);
	    } else {
		  origem.options[y] = new Option(origem.options[x].text, origem.options[x].value);
		  y++;
		}
	  }
	  for ( var x = tam_origem; y < x; x-- ) 
		origem.options[x-1] = null;
} 	


//-----------------------------------------------------

function formataValorNota(fld, e) { 

	var key = ''; 
	var i = 0; 
	var len = 0; 
	var falta = 'F'; 
	var strCheck = '0123456789,'; 
	    strCheck += falta; 
	    strCheck += String.fromCharCode(110); 
	    strCheck += String.fromCharCode(188); 
	var aux = ''; 
	var whichCode = (window.Event) ? e.which : e.keyCode; 
	
	// limpa o texto selecionado
	//if (document.selection.createRange().text) {
	//	document.selection.clear();
	//}

	if (whichCode == 46) { // ao teclar delete apaga tudo
		fld.value = ''
		return false;
	}

	if ((whichCode == 110 || whichCode == 188) && fld.value.length == 0) //nao permite comecar teclar com virgula
		return false;

	// libera teclas
	if ( whichCode == 8			// backspace
	  || whichCode == 9) 		// tab
	   return true;  

	if(fld.value.indexOf(',')!=-1) { // nao permite mais de duas casas decimais apos a virgula
		dec = fld.value.substring(fld.value.indexOf(','))
		if(dec.length > 2) return false
	}

	if(fld.value.indexOf(falta)!=-1) { // nao permite teclar F e numeros
		fld.value = falta
		return false;
	}

	// libera teclas
	if ( whichCode == 96	|| whichCode == 48	// 0
	  || whichCode == 97	|| whichCode == 49	// 1
	  || whichCode == 98	|| whichCode == 50	// 2
	  || whichCode == 99	|| whichCode == 51	// 3
	  || whichCode == 100	|| whichCode == 52	// 4
	  || whichCode == 101	|| whichCode == 53	// 5
	  || whichCode == 102	|| whichCode == 54	// 6
	  || whichCode == 103	|| whichCode == 55	// 7
	  || whichCode == 104	|| whichCode == 56	// 8
	  || whichCode == 105	|| whichCode == 57)	// 9
	   return true;  

	key = String.fromCharCode(whichCode);  
	if (strCheck.indexOf( key ) == -1) return false;  
	len = fld.value.length;

	if (fld.value.length < fld.size) {
		aux = ''; 
		for(; i < len; i++) 
			if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i); 
		aux += key; 
		len = aux.length; 

		// nao permite teclar mais de uma virgula
		if((whichCode == 110 || whichCode == 188 ) && aux.indexOf(',')>=0) { 
			return false;
		}

		// nao permite teclar mais de um F
		if(aux.indexOf(falta)!=-1) {
			fld.value = falta
			return false;
		}

		return true;
	}
	
	return false; 

}

//-----------------------------------------------------

function verificaData(INICIO, FIM){
	
	var data_inicio = INICIO.split("/");
	var data_fim = FIM.split("/");
	var inicio = new Date (data_inicio[2], data_inicio[1], data_inicio[0]);
	var fim = new Date (data_fim[2], data_fim[1], data_fim[0]);
	var dias = (fim - inicio) / (1000 * 60 * 60 * 24);
	//alert ("A diferen&ccedil;a é de " + dias + " dias.");
	
	return dias;
	
}

//-----------------------------------------------------

// Data atual
function now() {
	
	var objectDate = new Date();
	
	var dia = objectDate.getDate();
	var mes = objectDate.getMonth() + 1;
	var ano = objectDate.getFullYear();
	
	if(dia < 10)
		dia = '0'+dia;
	
	if(mes < 10)
		mes = '0'+mes;
	
	var data = dia+'/'+mes+'/'+ano;
	
	return data;
	
}

//-----------------------------------------------------

function FormataValor(campo,teclapres) {
	var tecla = teclapres.keyCode;
	var tammax = campo.maxLength - 1;

	
	vr = campo.value;
	vr = vr.replace( "/", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( ",", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	tam = vr.length;
	
	if (tam < tammax && tecla != 8){ tam = vr.length + 1 ; }

	if (tecla == 8 ){	tam = tam - 1 ; }
	
	if ( tecla == 8 || (tecla >= 48 && tecla <= 57) || (tecla >= 96 && tecla <= 105) ){
		campo.value = vr.substr( 0, tam - 2 ) + '.' + vr.substr( tam - 2, tam ) ; 
		if ( tam <= 2 ){
			campo.value = vr ; }
			if ( (tam > 2) && (tam <= 5) ){
				if ( (tam >= 6) && (tam <= 8) ){
					campo.value = vr.substr( 0, tam - 5 ) + '' + vr.substr( tam - 5, 3 ) + '.' + vr.substr( tam - 2, tam ) ; }
					if ( (tam >= 9) && (tam <= 11) ){
						campo.value = vr.substr( 0, tam - 8 ) + '' + vr.substr( tam - 8, 3 ) + '' + vr.substr( tam - 5, 3 ) + '.' + vr.substr( tam - 2, tam ) ; }
						if ( (tam >= 12) && (tam <= 14) ){
							campo.value = vr.substr( 0, tam - 11 ) + '' + vr.substr( tam - 11, 3 ) + '' + vr.substr( tam - 8, 3 ) + '' + vr.substr( tam - 5, 3 ) + '.' + vr.substr( tam - 2, tam ) ; }
							if ( (tam >= 15) && (tam <= 17) ){
								campo.value = vr.substr( 0, tam - 14 ) + '' + vr.substr( tam - 14, 3 ) + '' + vr.substr( tam - 11, 3 ) + '' + vr.substr( tam - 8, 3 ) + '' + vr.substr( tam - 5, 3 ) + '.' + vr.substr( tam - 2, tam ) ;}
			}
	} else {
		
		return false;
		
	}

}

// Detect if the browser is IE or not.
// If it is not IE, we assume that the browser is NS.
var IE = document.all?true:false

// If NS -- that is, !IE -- then set up for mouse capture
if (!IE) document.captureEvents(Event.MOUSEMOVE)

// Set-up to use getMouseXY function onMouseMove
document.onmousemove = getMouseXY;

// Temporary variables to hold mouse x-y pos.s
var mouseX = 0
var mouseY = 0

// Main function to retrieve mouse x-y pos.s
function getMouseXY(e) {
  if (IE) { // grab the x-y pos.s if browser is IE
    mouseX = event.clientX + document.body.scrollLeft
    mouseY = event.clientY + document.body.scrollTop
  } else {  // grab the x-y pos.s if browser is NS
    mouseX = e.pageX
    mouseY = e.pageY
  }  
  // catch possible negative values in NS4
  if (mouseX < 0){mouseX = 0}
  if (mouseY < 0){mouseY = 0}  
  
  clearTimeout(autologout);
  auto_logout();
  
  return true
}


var is_unblackout=0;

var autologout;



function htmlentities(s) {
	var ss = new String();
	for( i = 0; i < s.length; i++) {
	   var fs = s.charCodeAt(i);
	   ss += '&#' + fs + ';';
	   }
	return ss;
}


function auto_logout() {
	// desloga sozinho em 10 minutos - a pedidos
	autologout = setTimeout("logout();",600000);
}

function urlencode(plaintext)
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return encoded;
}



var clock_name;
function get_clock(name) { 

	setTimeout ("get_clock('"+name+"');",1000);

   if (window.XMLHttpRequest) { 
      xmlhttp2 = new XMLHttpRequest(); 
   } else if (window.ActiveXObject) { 
      xmlhttp2 = new ActiveXObject("Microsoft.XMLHTTP"); 
   } else { 
       alert("Seu navegador n&atilde;o suporta XMLHttpRequest."); 
      return; 
   }  
   clock_name = name;
    
    var url = "/_engine/jx_getclock.php";
    xmlhttp2.open("GET",url,true);
    //xmlhttp.setRequestHeader("Content-Type",
    // "application/x-www-form-urlencoded; charset=UTF-8");
    xmlhttp2.onreadystatechange = getclock_return; 
    xmlhttp2.send('');

}
function getclock_return() {
    if (xmlhttp2.readyState == 4) { 
       if (xmlhttp2.status == 200) {
			response = xmlhttp2.responseText;
			document.getElementById(clock_name).innerHTML = response;
      } 
    } 
}


function addEvent(obj,event_name,func_name,name){
	eval ('var func=function (e) { return '+func_name+'(e,"'+name+'"); };');
	if (obj.attachEvent){
		obj.attachEvent("on"+event_name, func );
	}else if(obj.addEventListener){
		obj.addEventListener(event_name,func,true);
	}else{
		obj["on"+event_name] = func;
	}
}
function multilist_textbox_focus(name) {
	document.getElementById('multilist_textbox_'+name).className="multilist_textbox multilist_textbox_edit";
	document.getElementById('multilist_all_div_'+name).className="multilist_all_div multilist_all_div_edit";

}
function multilist_textbox_blur(name) {
	document.getElementById('multilist_textbox_'+name).className="multilist_textbox";
	document.getElementById('multilist_all_div_'+name).className="multilist_all_div";

	eval('multilist_tid_'+name+' = setTimeout("multilist_hide_list(\\"'+name+'\\");",200);');
}
function multilist_all_keyup (evt,name) {
	if (evt!=null) {
		if(multilist_all_updown(evt)==false) { return; }
	}	
	eval("var arrN = multilist_names_"+name+";");
	eval("var arrV = multilist_values_"+name+";");
	var newarrN = new Array();
	var newarrV = new Array();
	var j=0;
	var str = document.getElementById("multilist_textbox_"+name).value;
	
	for (var i=0;i<arrN.length;i++) {
		if (arrV[i].indexOf(str)!=-1) {
			newarrN[j]=arrN[i];
			newarrV[j]=arrV[i];
			j++;
		}
	}
	multilist_show_list(newarrN,newarrV,name);
	
	eval("multilist_selected_"+name+" = -1;");
	
	// se soh tiver um e for igual ao q foi digitado, eu seleciono
	if ((j==1)&&(str==newarrV[0])) {
		//alert(newarrV[0]);
		eval("multilist_selected_"+name+" = 0;");
		multilist_all_choose (name);
		multilist_all_click (newarrN[0],newarrV[0],0,name);
	}
}
function multilist_all_updown (evt,name) {
	if (!evt) evt = window.event;
	var k = evt.keyCode;
	
	if (k==38) {
		if (name) { multilist_all_moveup(name); }
        evt.returnValue = false;
        evt.cancel = true;
        evt.preventDefault();
        return false;
	} else if (k==40) {
		if (name) { multilist_all_movedown(name); }
        evt.returnValue = false;
        evt.cancel = true;  
        evt.preventDefault();
        return false;
	} else if (k==13) {
		if (name) { multilist_all_choose(name,1);  }
        evt.returnValue = false;
        evt.cancel = true;  
        evt.preventDefault();
        return false;
	}
}
function multilist_all_click (strN,strV,i,name,hide,add) {

	document.getElementById('multilist_textbox_'+name).value=strV;
	eval("multilist_selected_name_"+name+" = strN;");
	eval("multilist_selected_value_"+name+" = strV;");
	multilist_all_select(i,name,1);

	eval ("var selected = multilist_selected_"+name+";");
	if (selected != i) { 
		multilist_all_deselect(selected,name);
	
		selected = i;
		eval ("multilist_selected_"+name+" = selected;");
	}

	document.getElementById('multilist_textbox_'+name).focus();

	if (hide=="yes") {
		multilist_hide_list(name);
	}
	if (add=="yes") {
		multilist_add(name);
		document.getElementById('multilist_textbox_'+name).value="";
	}
}

function multilist_all_choose (name,doclick) {
	eval ("var selected = multilist_selected_"+name+";");
	if (doclick==1) {
		if (document.getElementById('multilist_all_item_'+name+'_'+selected)) {
			document.getElementById('multilist_all_item_'+name+'_'+selected).onclick();
		}
	}
	multilist_all_select(selected,name);
}
function multilist_all_select (i,name,click) {
	//alert("select "+click);
	if (!document.getElementById('multilist_all_item_'+name+'_'+i)) { return; }
	if (click==1) {
		document.getElementById('multilist_all_item_'+name+'_'+i).className="multilist_all_item_clicked";
	} else {
		document.getElementById('multilist_all_item_'+name+'_'+i).className="multilist_all_item_selected";
	}
}
function multilist_all_deselect(i,name) {
	if (document.getElementById('multilist_all_item_'+name+'_'+i)) {
		document.getElementById('multilist_all_item_'+name+'_'+i).className="multilist_all_item";
	}
}

function multilist_all_moveup (name) {
	eval ("var selected = multilist_selected_"+name+";");
	if (selected==0) { return; }
	selected--;
	
	eval ("multilist_selected_"+name+" = selected;");

	multilist_all_select(selected,name);
	selected++;
	multilist_all_deselect(selected,name);


}
function multilist_all_movedown (name) {
	eval ("var selected = multilist_selected_"+name+";");
	
	list = document.getElementById("multilist_all_"+name);
	if (list.style.visibility=="hidden") {
		selected=-1;
		multilist_all_keyup(null,name);
	}

	selected++;

	if (!document.getElementById('multilist_all_item_'+name+'_'+selected)) { return; }

	eval ("multilist_selected_"+name+" = selected;");

	multilist_all_select(selected,name);
	selected--;
	if (selected!=-1) {
		multilist_all_deselect(selected,name);
	}
}


function multilist_reset(name) {
	var value = document.getElementById('multilist_hidden_'+name).value;
	eval ('multilist_value_'+name+' = value;');
	document.getElementById('multilistdiv_'+name).className='multilistdiv multilistdiv_normal';
}



function select_textbox_focus(name) {
	document.getElementById('select_textbox_'+name).className="select_textbox select_textbox_edit";
	document.getElementById('select_all_div_'+name).className="select_all_div select_all_div_edit";

}
function select_textbox_blur(name) {
	document.getElementById('select_textbox_'+name).className="select_textbox";
	document.getElementById('select_all_div_'+name).className="select_all_div";

	eval('select_tid_'+name+' = setTimeout("select_hide_list(\\"'+name+'\\");",200);');
}

function select_showhide_list (name,blur) {
	list = document.getElementById("select_all_"+name);
	if (list.style.visibility=="hidden") {
		select_show_list(name);
	} else {
		select_hide_list(name);
	}
	document.getElementById("select_textbox_"+name).focus();
	eval ('clearTimeout(select_tid_'+name+');');
}

function select_hide_list (name) {
	document.getElementById("select_all_"+name).style.visibility="hidden";
}
function select_show_list (name) {
	document.getElementById("select_all_"+name).style.visibility="visible";
}

function select_create_list ( arrN,arrV,name,formname) {
	var newdiv;

	document.getElementById("select_all_"+name).innerHTML="";

	for (var i=0;i<arrN.length;i++) {
		if (arrN[i]=="") { continue; };
		newdiv=document.createElement("DIV");
		newdiv.setAttribute("className","select_all_item");
		newdiv.setAttribute("class","select_all_item");
		newdiv.setAttribute("id","select_all_item_"+name+"_"+i);
		eval('newdiv.onclick=function onclick(event) { select_all_click("'+arrN[i]+'","'+arrV[i]+'","'+name+'","'+formname+'"); }');
		newdiv.onmouseover=function onmouseover(event) { this.className='select_all_item_selected'; }
		newdiv.onmouseout=function onmouseout(event) { this.className='select_all_item'; }
		newdiv.innerHTML = htmlentities(arrV[i]);
		
		document.getElementById("select_all_"+name).appendChild(newdiv);
	}
	document.getElementById("select_all_"+name).style.visibility="visible";

}

function select_all_click (value,label,name,formname) {
	document.getElementById("select_textbox_"+name).value=label;
	document.getElementById("select_hidden_"+name).value=value;
	select_hide_list(name);
	
	eval ('select_value = select_value_'+name+';');

	if(value != select_value) {
		if (document.getElementById('selectdiv_'+name))
			document.getElementById('selectdiv_'+name).className='selectdiv selectdiv_edited';
		status_reset(formname);
	} else {
		if (document.getElementById('selectdiv_'+name))
			document.getElementById('selectdiv_'+name).className='selectdiv selectdiv_normal';
	}
}	
function select_reset(name) {
	value = document.getElementById("select_hidden_"+name).value;
	eval ('select_value_'+name+' = value;');
	if (document.getElementById('selectdiv_'+name))
		document.getElementById('selectdiv_'+name).className='selectdiv selectdiv_normal';
}



function textbox_onfocus(name) {
	document.getElementById('textbox_'+name).className='textbox textbox_edit';
}
function textbox_onchange(name,formname) {
	eval ('textbox_value = textbox_value_'+name+';');

	if(document.getElementById('textbox_'+name).value != textbox_value) {
		document.getElementById('textbox_'+name).className='textbox textbox_edited textbox_edit';
		status_reset(formname);
	} else {
		document.getElementById('textbox_'+name).className='textbox textbox_edit';
	}
}
function textbox_onblur (name,formname) {
	eval ('textbox_value = textbox_value_'+name+';');

	if(document.getElementById('textbox_'+name).value != textbox_value) {
		document.getElementById('textbox_'+name).className='textbox textbox_edited';
		status_reset(formname);
	} else {
		document.getElementById('textbox_'+name).className='textbox';
	}
}

function textbox_reset(name,formname) {
	textbox_value = document.getElementById('textbox_'+name).value;
	eval ('textbox_value_'+name+' = textbox_value;');

	textbox_onblur(name,formname);
}

function textarea_onfocus(name) {
	document.getElementById('textarea_'+name).className='textarea textbox_edit';
}
function textarea_onchange(name,formname) {
	eval ('textarea_value = textarea_value_'+name+';');

	if(document.getElementById('textarea_'+name).value != textarea_value) {
		document.getElementById('textarea_'+name).className='textarea textbox_edited textbox_edit';
		status_reset(formname);
	} else {
		document.getElementById('textarea_'+name).className='textarea textbox_edit';
	}
}
function textarea_onblur (name,formname) {
	eval ('textarea_value = textarea_value_'+name+';');

	if(document.getElementById('textarea_'+name).value != textarea_value) {
		document.getElementById('textarea_'+name).className='textarea textbox_edited';
		status_reset(formname);
	} else {
		document.getElementById('textarea_'+name).className='textarea';
	}
}
function textarea_reset(name,formname) {
	textarea_value = document.getElementById('textarea_'+name).value;
	eval ('textarea_value_'+name+' = textarea_value;');

	textarea_onblur(name,formname);
}


function hide_all_selects () {
	selects = document.getElementsByTagName("select");
	for (i=0;i<selects.length;i++) {
		selects[i].style.visibility="hidden";
	}
	//alert("hideados");
} 
function show_all_selects () {
	selects = document.getElementsByTagName("select");
	for (i=0;i<selects.length;i++) {
		selects[i].style.visibility="visible";
	}
	//alert("showed");
}

function blackout () {
	if (checkOpac()==70) { return; }

	hide_all_selects();	
	changeOpac(0,"blackout");
	document.getElementById("blackout").style.visibility="visible";
	opacity("blackout",0,70,200);
}
function unblackout () {
	if (checkOpac()==0) { return; }

	opacity("blackout",70,0,200);
	//document.getElementById("blackout").style.visibility="hidden";
	document.getElementById("blackout2").innerHTML="";

	show_all_selects();
}
function pageblackout () {
	hide_all_selects();
	parent.document.getElementById("blackout").style.visibility="visible";
	changeOpac(100,"blackout",1);
	opacity("blackout",0,100,10,1); // precisa senao o IE pisca...
}
function pageunblackout () {
	is_unblackout=1;
	opacity("blackout",100,0,200,1);
//	parent.document.getElementById("blackout").style.visibility="hidden";
//	parent.document.getElementById("blackout").style.zIndex="-1";

}

function opacity(id, opacStart, opacEnd, millisec, isparent) {
    //speed for each frame
    var speed = Math.round(millisec / 100);
    var timer = 0;

    //determine the direction for the blending, if start and end are the same nothing happens
    if(opacStart > opacEnd) {
        for(i = opacStart; i >= opacEnd; i--) {
            setTimeout("changeOpac(" + i + ",'" + id + "','"+isparent+"')",(timer * speed));
            timer++;
        }
    } else if(opacStart < opacEnd) {
        for(i = opacStart; i <= opacEnd; i++)
            {
            setTimeout("changeOpac(" + i + ",'" + id + "','"+isparent+"')",(timer * speed));
            timer++;
        }
    }
}

//change the opacity for different browsers
function changeOpac(opacity, id, isparent) {
	if (isparent==1) {
	    var object = parent.document.getElementById(id).style;
	    parent.blackout_opac = opacity;
	} else {
	    var object = document.getElementById(id).style;
	    blackout_opac = opacity;
	}

    if (opacity!=0) {
    	object.visibility="visible";
    	if (is_unblackout!=1) {
    		hide_all_selects();
    	}
    }

    object.opacity = (opacity / 100);
    object.MozOpacity = (opacity / 100);
    object.KhtmlOpacity = (opacity / 100);
    object.filter = "alpha(opacity=" + opacity + ")";
    
    if (opacity==0) {
    	object.visibility="hidden";
  		show_all_selects();
    }
} 
function checkOpac (isparent) {
	if (isparent==1) {
	    return parent.blackout_opac;
	} else {
	    return blackout_opac;
	}
}






	function showSubMenu(id){
		obj = "menu"+id;
		obj = document.getElementById(obj);
		obj.className = (obj.className=="menuSubItemDisabled")?"menuSubItemEnabled":"menuSubItemDisabled";
	}

String.prototype.ucFirst = function () {
   var firstLetter = this.substr(0,1).toUpperCase()
   return this.substr(0,1).toUpperCase() + this.substr(1,this.length);
}

		

function validacnpj(FORM){
	 //valida cnpj
	CNPJ = FORM.value;
			 /*
			 if (CNPJ.length < 18) erro += "É necessario preencher corretamente o número do CNPJ! ";
			 if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-"))
			 {
				if (erro.length == 0) erro += "É necess&aacute;rio preencher corretamente o número do CNPJ! ";
			 }
			 */
			//substituir os caracteres que não são números
		   if(document.layers && parseInt(navigator.appVersion) == 4){
				   x = CNPJ.substring(0,2);
				   x += CNPJ. substring (3,6);
				   x += CNPJ. substring (7,10);
				   x += CNPJ. substring (11,15);
				   x += CNPJ. substring (16,18);
				   CNPJ = x;
		   } else {
				   CNPJ = CNPJ. replace (".","");
				   CNPJ = CNPJ. replace (".","");
				   CNPJ = CNPJ. replace ("-","");
				   CNPJ = CNPJ. replace ("/","");
		   }
		   var nonNumbers = /\D/;
		   //if (nonNumbers.test(CNPJ)) erro += "A verifica&ccedil;ão de CNPJ suporta apenas números! ";
		   var a = [];
		   var b = new Number;
		   var 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])){
				alert("CNPJ Invalido");
				FORM.focus();
				return false;
		   }
}	

function tamMax(valor, maximo){
	
	if(valor.value > maximo){
		alert("Valor máximo de "+maximo+". Preencha com um valor inferior ao máximo.");
		valor.focus();
		valor.value = "";
		return false;	
	}
	return true;
	
}

function textCounter(field, maxlimit, countfield) {
	if (field.value.length > maxlimit) // if too long...trim it!
		field.value = field.value.substring(0, maxlimit);
	// otherwise, update 'characters left' counter
	//else 
	///	countfield.value = maxlimit - field.value.length;
}

<!-- Início da Função FormataReais -->
function FormataReais(fld, milSep, decSep, e) {
	var sep = 0;
	var key = '';
	var i = j = 0;
	var len = len2 = 0;
	var strCheck = '0123456789';
	var aux = aux2 = '';
	var whichCode = (window.Event) ? e.which : e.keyCode;
	if ((whichCode == 13) || (whichCode == 0) || (whichCode == 8))
	return true;
	key = String.fromCharCode(whichCode); // Valor para o código da Chave
	if (strCheck.indexOf(key) == -1) return false; // Chave inválida
	len = fld.value.length;
	for(i = 0; i < len; i++)
	if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
	aux = '';
	for(; i < len; i++)
	if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
	aux += key;
	len = aux.length;
	if (len == 0) fld.value = '';
	if (len == 1) fld.value = '0'+ decSep + '0' + aux;
	if (len == 2) fld.value = '0'+ decSep + aux;
	if (len > 2) {
	aux2 = '';
	for (j = 0, i = len - 3; i >= 0; i--) {
	if (j == 3) {
	aux2 += milSep;
	j = 0;
	}
	aux2 += aux.charAt(i);
	j++;
	}
	fld.value = '';
	len2 = aux2.length;
	for (i = len2 - 1; i >= 0; i--)
	fld.value += aux2.charAt(i);
	fld.value += decSep + aux.substr(len - 2, len);
	}
	return false;
}

function SomenteNum(fld, e) {
	var sep = 0;
	var key = '';
	var i = j = 0;
	var len = len2 = 0;
	var strCheck = '0123456789';
	var aux = aux2 = '';
	var whichCode = (window.Event) ? e.which : e.keyCode;
	if ((whichCode == 13) || (whichCode == 0) || (whichCode == 8))
	return true;
	key = String.fromCharCode(whichCode); // Valor para o código da Chave
	if (strCheck.indexOf(key) == -1) return false; // Chave inválida	
}

// Marca os campos errados
function marca_campo(id){
	
	var td_id = '_'+id;
	
	if(document.getElementById(td_id)){
		
		var nome_classe = document.getElementById(td_id).className;
		nome_classe = nome_classe+"_invalido";		
		
		document.getElementById(id).className = "formInputVermelho";
		document.getElementById(td_id).className = nome_classe;
		
	} else {
		$("#"+id).addClass("bg-vermelho");
		$("#"+id).focus(function(){
			$(this).removeClass("bg-vermelho");
		});
		//document.getElementById(id).className = "formCampoVermelho";
	}
}

// Seleciona um campo, marcando ele com a cor branca
function seleciona(id){
	var td_id = '_'+id;
	var classe_antiga = document.getElementById(td_id).className;
	var nome_classe;

	nome_classe = classe_antiga.replace(/_invalido/g,"");
	nome_classe = nome_classe.replace(/_selec/g,"");
	
	nome_classe = nome_classe+"_selec";
	
	document.getElementById(id).focus();
	document.getElementById(td_id).className = nome_classe;
	document.getElementById(id).className = "formInputSelec";
	
}

function selecionaFocus(id){
	var td_id = '_'+id;	
	var classe_antiga = document.getElementById(td_id).className;
	var nome_classe;
	
	nome_classe = classe_antiga.replace(/_invalido/g,"");
	nome_classe = nome_classe.replace(/_selec/g,"");
	
	nome_classe = nome_classe+"_selec";
	
	document.getElementById(td_id).className = nome_classe;
	document.getElementById(id).className = "formInputSelec";
	
}

// Deseleciona o campo marcado com a cor branca
function deseleciona(id){
	//alert('deslect');
	var td_id = '_'+id;
	var classe_antiga = document.getElementById(td_id).className;
	var nome_classe;
	
	nome_classe = classe_antiga.replace(/_invalido/g,"");
	nome_classe = nome_classe.replace(/_selec/g,"");
	
	document.getElementById(td_id).className = nome_classe;
	document.getElementById(id).className = "formInput";	
}

/**
*	validaForm
*	@autor: pabreu
*	@date: 08/07/2010
*	@description: funçao que envia o formulário por AJAX, IFRAME ou PARA MESMA PÁGINA
*/
function validaForm(id_formulario, funcao_retorno){

	var formulario = document.getElementById(id_formulario);
	
	var action = formulario.action;
	var nome_iframe = formulario.target;
	var iframe;
	var ajax;
		
	try{
		ajax = formulario.ajax.value;
	} catch(exception){
		ajax = '0';
	}

	// POR AJAX
	if(ajax == '1'){
		$.post(action, $("#"+id_formulario).serialize(), function(data){
			retorno_ajax = data.trim();
			
			if(typeof funcao_retorno === 'undefined'){				
				
				if(retorno_ajax != '1' && retorno_ajax != '0'){					
					trataValidacao(retorno_ajax);
				} else {
					document.location.reload();
				}
				
			} else {
				eval(funcao_retorno+"('"+retorno_ajax+"');");				
			}
					
		});
		
	// PARA DENTRO DE IFRAME	
	} else if(nome_iframe != ''){

		$("#"+nome_iframe).show();
		if($("#"+id_formulario).attr('onsubmit') == null || $("#"+id_formulario).attr('onsubmit') == "undefined"){
			$("#"+id_formulario).submit();
		}		
		return true;
	
	// PARA MESMA PÁGINA
	} else {

		if($("#"+id_formulario).attr('onsubmit') == null || $("#"+id_formulario).attr('onsubmit') == "undefined"){
			$("#"+id_formulario).submit();
		}
		return true;
	}
	return false;
}

function trataValidacao(retorno_ajax){
	var aux = retorno_ajax.split("#");						
	var cps_errados = aux[0].split(",");
	for(var i in cps_errados){
		marca_campo(cps_errados[i]);	
	}
	mensagem(aux[1]);
}




