// JavaScript EUNANET
var http_request = false;
function makeRequest(metodo,divexibe,pagina,variaveis_post) {
	http_request = false;
	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			// set type accordingly to anticipated content type
			//http_request.overrideMimeType('text/xml');
			http_request.overrideMimeType('text/html');
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	if (!http_request) {
		alert('Cannot create XMLHTTP instance');
		return false;
	}
	http_request.onreadystatechange = function() {
		if (http_request.readyState == 4) {
			//texto=unescape(xmlhttp.responseText.replace(/\+/g," "));
			//document.getElementById(destino).innerHTML=texto;
			// executa scripts
			//extraiScript(texto);			
			if (http_request.status == 200) {
				//alert(http_request.responseText);
				result = http_request.responseText;
				document.getElementById(divexibe).innerHTML = result;
				extraiScript(result)
			} else {
				alert('Houve um problema com a requisição HTML.');
			}
		} else {
			document.getElementById(divexibe).innerHTML='<img src="../images/loading.gif">';
		}
	}
	if(metodo=='G'){
		//alert(variaveis_post+" - "+pagina);
		//http_request.open('GET', noCache(pagina+variaveis_post), true);
		//http_request.setRequestHeader( "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT" );
		http_request.open('GET', pagina+variaveis_post, true);		
		http_request.send(null);		
	} else {
		//alert(variaveis_post+" - "+pagina);
		http_request.open('POST', noCache(pagina), true);
		http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=ISO-8859-1");
		http_request.setRequestHeader("Content-length", variaveis_post.length);
		http_request.setRequestHeader("Connection", "close");
		http_request.send(variaveis_post);
	}	
	
	
	
}
function enviando(modo,id,formulario,divexibe,pagina)
{
	var formulario = document.forms[formulario];
	var variaveis_post = "";
	var div = divexibe;
	var i;
	var metodo = modo;
	var id_form = id;
	if(metodo == "G") {
		var pag = pagina+'.php?';
	} else {
		var pag = pagina+'.php';
	}
	if(id_form=="F") {
		//alert("Passei aqui");
		//******************************************************
		// Concatena POST pelo elements
		for (i=0; i<formulario.elements.length; i++)
		{
			//alert("Passei aqui");
				if (formulario.elements[i].tagName == "TEXTAREA")
				{
					{
						variaveis_post += formulario.elements[i].name + "=" + encodeURI(formulario.elements[i].value) + "&"; }
				}
				if (formulario.elements[i].tagName == "INPUT")
				{
					if (formulario.elements[i].type == "text") 	{ variaveis_post += formulario.elements[i].name + "=" + encodeURI(formulario.elements[i].value) + "&"; }
					if (formulario.elements[i].type == "hidden") 	{ variaveis_post += formulario.elements[i].name + "=" + encodeURI(formulario.elements[i].value) + "&"; }
					if (formulario.elements[i].type == "password") { variaveis_post += formulario.elements[i].name + "=" + encodeURI(formulario.elements[i].value) + "&"; }
					if (formulario.elements[i].type == "checkbox") {
						if (formulario.elements[i].checked) { variaveis_post += formulario.elements[i].name + "=" + formulario.elements[i].value + "&"; }
						else { variaveis_post += formulario.elements[i].name + "=&"; }
					}
					if (formulario.elements[i].type == "radio")
					{
						if (formulario.elements[i].checked) { variaveis_post += formulario.elements[i].name + "=" + formulario.elements[i].value + "&"; }
					}
				}
				else if (formulario.elements[i].tagName == "SELECT")
				{
					var sel = formulario.elements[i];
					variaveis_post += sel.name + "=" + sel.options[sel.selectedIndex].value + "&";
				}
		}
		//******************************************************/
		//alert("Passei aqui");
	} else {
		variaveis_post = id;	
	}
	makeRequest(metodo,div,pag,variaveis_post);
	return false;
	
}
/// Controla Exibição das Divs AJAX
function statusdiv(d1,d2,d3,d4,d5) { 
	if(d1!=null){
		var boxesconde = document.getElementById('div1');
		boxesconde.style.display=d1;
	}
	if(d2!=null){
		var boxesconde = document.getElementById('div2');
		boxesconde.style.display=d2;
	}
	if(d3!=null){
		var boxesconde = document.getElementById('div3');
		boxesconde.style.display=d3;
	}	
	if(d4!=null){
		var boxesconde = document.getElementById('div4');
		boxesconde.style.display=d4;
	}
	if(d5!=null){
		var boxesconde = document.getElementById('div5');
		boxesconde.style.display=d5;
	}			
	return false;
}
function statusdivgeral(divesconde,tipo) { 
	var boxesconde = document.getElementById(divesconde);
	boxesconde.style.display=tipo;
	return false;
}
function listando(rotina,qde,escopo) { 
	var vescopo         = escopo;
	var pag       		= document.getElementsByName('numpag_tab');
	var vpag      		= pag[0].value;	
	var pesq          	= document.getElementsByName('pesquisa_tab');
	var vpesq         	= pesq[0].value;
	if(rotina == "adm_foruns") {
		var pest          	= document.getElementsByName('id_cmc');
		vescopo         	= vescopo+"&cmc="+pest[0].value;		
	}
	if(rotina == "adm_varas") {
		var pest          	= document.getElementsByName('id_fru');
		vescopo         	= vescopo+"&fru="+pest[0].value;		
	}	
	if(rotina == "adm_cidades") {
		var pest          	= document.getElementsByName('id_est');
		vescopo         	= vescopo+"&est="+pest[0].value;		
	}
	if(rotina == "adm_estados") {
		var ppai          	= document.getElementsByName('id_pai');
		vescopo         	= vescopo+"&pai="+ppai[0].value;		
	}	
	if(qde=="T") {
		pesq[0].value = vpesq = "";
	}
	enviando('G','nreg='+vpag+"&psq="+vpesq+vescopo,'','div1',rotina+'_lista');
	return false;		
}
function marcaregtab(vardel) {
   var cks = document.getElementsByName(vardel);
   for (i=0;i<cks.length;i++) 
	  if(cks[i].type == "checkbox") 
		if(cks[i].checked==1)
			cks[i].checked=0
		else	 
			cks[i].checked=1
		 return false;
}		
function delregtab(vardel,rotina) { 
   var temreg = 0;
   var cks = document.getElementsByName(vardel);
   var qde = 0;
   for (i=0; i<cks.length;i++) {
		if(cks[i].checked) {
			temreg = 1;
			qde++;
		}
	}
	if (temreg == 1) { 
		if (confirm("Confirma a Exclusão dos Registros Marcados ("+qde+")?")) {
			statusdiv('inline','none','inline');
			enviando('P','F','formdeleta','div3',rotina+'_delete');
		} else {
			alert("Exclusão Concelada!");
		}
		return false; 
	}
	alert("Selecione pelo menos um Registro para apagar!!!"); 
	return false; 
}
//Imagem UPLOAD
function ajaxFileUpload(inputid,pagina,pagexibe,ordem,ebk)
{
	var divinput = inputid;
	$("#loading")
	.ajaxStart(function(){
		$(this).show();
	})
	.ajaxComplete(function(){
		$(this).hide();
	});

	$.ajaxFileUpload
	(
		{
			url:pagina+'.php?id='+divinput+'&ordem='+ordem+'&ebk='+ebk,
			secureuri:false,
			fileElementId:divinput,
			dataType: 'json',
			success: function (data, status)
			{
				if(typeof(data.error) != 'undefined')
				{
					if(data.error != '')
					{
						alert(data.error);
					}else{	
						enviando('G','ordem='+ordem+'&ebk='+ebk,'','box_'+divinput,pagexibe);
						//alert(data.msg);
					}
				}
			},
			error: function (data, status, e)
			{
				alert(e);
			}
		}
	)
	
	return false;

}
/// Controla Aumento das Fontes
///$(document).ready(function(){  
///	var fonte = 12;  
///	$("#aumenta_fonte").click(function(){  
///		if (fonte<17){  
///			 fonte = fonte + 1;  
///			 $("p").css({"font-size" : fonte+"px"});  
///		 }  
///	 });  
///	 $("#reduz_fonte").click(function(){  
///		 if (fonte>9){  
///			 fonte = fonte - 1;  
///			 $("p").css({"font-size" : fonte+"px"});  
///		 }  
///	 });   
/// }); 
//Tootips e Favoritos
function TipPro(texto,imagem,larg,altu) {
	Tip(texto+"<br /><br /> <img src='showimg.php?id="+imagem+"'; width='"+larg+"' height='"+altu+"'>", WIDTH, 200, PADDING, 6, BGCOLOR, '#000000', FONTCOLOR, '#ffffff');
	return false;
}

function TipEu(texto,imagem,larg,altu) {
	Tip(texto+"<br /><br /> <img src='images/"+imagem+"'; width='"+larg+"' height='"+altu+"'>", WIDTH, 250, PADDING, 6, BGCOLOR, '#000000', FONTCOLOR, '#ffffff');
	return false;
}

function TipTxt(texto) {
	Tip(texto, WIDTH, 250, PADDING, 6, BGCOLOR, '#000000', FONTCOLOR, '#ffffff');
	return false;
}
function addFavoritos(url,title) {
	if (window.sidebar) {
		window.sidebar.addPanel(title, url,"");
	} else if( document.all ) {
		window.external.AddFavorite( url, title);
	} else {
		alert ("Para adicionar a EUNANET ao Favoritos neste navegador, aperte CTRL+D");
	}
}
// No Cache
function noCache(
  uri  
  // uri string to open
 ){

 return uri.concat( 
  // concat String prototype,
  // the fastest way to produce
  // a complete string using multiple values

  /\?/.test(uri) ?
  // if uri has a query string

   "&"
  // add last value using & separator char
   :

  // else
   "?",
  // add a query string to this url

  "noCache=",
  // this should be a "cool name" for generated key

  (new Date).getTime(),
  // the noCache value will be milliseconds
  // from 1970/01/01

  ".",
  // plus a dot ...

  Math.random()*1234567
  // ... and a random value using
  // a "big" integer as generator
 );

 // then this is a return example using uri: http://host.com/mypage.html
 // http://host.com/mypage.html?noCache=1166301156233.332083.6663326991

 // while this is an example using uri: http://host.com/mypage.html?v0=1&v2=a
 // http://host.com/mypage.html?v0=1&v2=a&noCache=1166301168420.631416.7190624559
};
/**  
 * Função para aplicar máscara em campos de texto
 * Copyright (c) 2008, Dirceu Bimonti Ivo - http://www.bimonti.net 
 * All rights reserved. 
 * @constructor  
 */ 
 
/* Version 0.27 */

/**  
  * Função Principal 
  * @param w - O elemento que será aplicado (normalmente this).
  * @param e - O evento para capturar a tecla e cancelar o backspace.
  * @param m - A máscara a ser aplicada.
  * @param r - Se a máscara deve ser aplicada da direita para a esquerda. Veja Exemplos.
  * @param a - 
  * @returns null  
  */
function maskIt(w,e,m,r,a){
    
    // Cancela se o evento for Backspace
    if (!e) var e = window.event
    if (e.keyCode) code = e.keyCode;
    else if (e.which) code = e.which;
    
    // Variáveis da função
    var txt  = (!r) ? w.value.replace(/[^\d]+/gi,'') : w.value.replace(/[^\d]+/gi,'').reverse();
    var mask = (!r) ? m : m.reverse();
    var pre  = (a ) ? a.pre : "";
    var pos  = (a ) ? a.pos : "";
    var ret  = "";

    if(code == 9 || code == 8 || txt.length == mask.replace(/[^#]+/g,'').length) return false;

    // Loop na máscara para aplicar os caracteres
    for(var x=0,y=0, z=mask.length;x<z && y<txt.length;){
        if(mask.charAt(x)!='#'){
            ret += mask.charAt(x); x++;
        } else{
            ret += txt.charAt(y); y++; x++;
        }
    }
    
    // Retorno da função
    ret = (!r) ? ret : ret.reverse()    
    w.value = pre+ret+pos;
}

// Novo método para o objeto 'String'
String.prototype.reverse = function(){
    return this.split('').reverse().join('');
};
function extraiScript(texto){
        // inicializa o inicio ><
        var ini = 0;
        // loop enquanto achar um script
        while (ini!=-1){
                // procura uma tag de script
                ini = texto.indexOf('<script', ini);
                // se encontrar
                if (ini >=0){
                        // define o inicio para depois do fechamento dessa tag
                        ini = texto.indexOf('>', ini) + 1;
                        // procura o final do script
                        var fim = texto.indexOf('</script>', ini);
                        // extrai apenas o script
                        codigo = texto.substring(ini,fim);
                        // executa o script
                        eval(codigo);
                }
        }
}
function ativafocus(txt){
	document.getElementById(txt).className="focus_in";
	return false;
}

function desativafocus(txt){ 
	document.getElementById(txt).className="focus_out";
	return false;
}
