/** Classe para envio de requisições XMLHTTPRequest.
 *  Contempla métodos para envio via GET, POST e 
 *  métodos de conveniência.
 */
function Request(){
	
	//propriedades
	this.req = null;
	this.url = null;
	this.method = null;
	this.async = 'true';
	this.insert = null;
	this.handleResp = null;
	this.handleError = null;
	this.responseFormat = 'text';
	
	var httpStatus;
	
	//loading msg
	loadingMsg();
	
	//Inicialização do objeto Request
	this.init = function(){
		if(!this.req){
			try{
				this.req = new XMLHttpRequest();
			}catch(e){
				this.req = new ActiveXObject("Microsoft.XMLHTTP");
			}
		}
		return this.req;
	}
	
	//Teste de inicialização do Request.
	this.doReq = function(){
		if(!this.init()){
			alert('Não foi possível enviar a requisição');
			return;
		}
		
		//envio da requisição
		//alert(this.method+" "+this.url+" "+this.async)
		this.req.open(this.method, this.url, this.async);
		var self = this;
		
		//envio assíncrono e definição do callback
		this.req.onreadystatechange = function(){
			var resp = null;
			if(self.req.readyState==4){
				switch (self.responseFormat){
					case 'text':
						resp = self.req.responseText;
						break;
					case 'xml':
						resp = self.req.responseXML;
						break;
				}
				
				if(self.req.status==200){
					self.handleResp(resp);
					document.getElementById("loading").style.display="none";
					if(document.getElementById("handle_error")){
						document.getElementById("handle_error").style.display="none";
					}
				}else{
					self.handleError(resp);
				}
			}
		}
		
		//envio via GET
		if (this.method=='GET'){
			this.req.send(this.insert);
		
		//envio via POST
		}else if (this.method=='POST'){
			this.req.setRequestHeader('Content-Type', 
			'application/x-www-form-urlencoded'); //;charset=ISO-8859-1
			this.req.send(this.insert);
		}
	}
	
	//método padrão de erro
	this.handleError = function(){
		document.getElementById("loading").style.display="none";
		
		var msg = "Houve um problema de comunicação com o banco de dados.<br>"+
		"<i>Erro "+this.req.status+": "+this.req.statusText;
		
		if(!document.getElementById("handle_error")){
			var div = document.createElement('div');
			div.id='handle_error';
			document.body.appendChild(div);
			div.onclick = function(){document.body.removeChild(div);}
		} else {
			var div = document.getElementById("handle_error");
		}
		div.innerHTML=msg;
	}
	
	//método de envio via GET
	this.doGet = function(url, callback, resp_format){
		
		if(resp_format){
			this.responseFormat = resp_format;
		}
		
		document.getElementById("loading").style.display="block";
		this.url = url;
		this.handleResp = callback;
		this.method='GET';
		this.doReq();
	}
	
	//método de envio via POST
	this.doPost = function(url, insert, callback, resp_format){
		
		if(resp_format){
			this.responseFormat = resp_format;
		}
		
		document.getElementById("loading").style.display="block";
		this.url = url;
		this.handleResp = callback;
		this.method='POST';
		this.insert = insert;
		this.doReq();
	}
}

function loadingMsg(){
	if(!document.getElementById("loading")){
		var div = document.createElement('div');
		div.id="loading";
		//div.appendChild(document.createTextNode('aguarde...'));
		
		if(document.body.getElementsByTagName("script")[1]){
			var spt = document.body.getElementsByTagName("script")[1];
			document.body.insertBefore(div, spt);
		}else{
			document.body.appendChild(div);
		}
	}
}
/*EDIÇÃO DE FORMS --------------------------------------------------------------- */
/** Classe responsável por salvar forms.*/
function FormSave(){
	
	//propriedades
	this.ins = null;
	this.url = null;
	this.format = 'text';
	
	//contrutores
	this.funcao = function(str){
		alert(str);
	}
	
	this.postdata = function(){

		var tb = document.forms[0].name;
		var campo = document.forms[0].elements;
		var cpcount = 0;
		for (i=0; i<campo.length; i++){
			
			if((campo[i].nodeName!='BUTTON')&&(campo[i].nodeName!='FIELDSET')){
				if (cpcount==0){
					this.ins = campo[i].name+"="+campo[i].value;
					cpcount++;
				} else {
					this.ins += "&"+campo[i].name+"="+campo[i].value;
				}
			}
		}
		return this.ins;
	}
	
	//métodos
	this.doSalvar = function(){
		var ajax = new Request();
		ajax.doPost(this.url, this.postdata(), this.funcao, this.format);
	}
}

/** Classe responsável por exluir registros.*/
function FormDel(cod, funcao, url){
	
	/*cod: codigo do registro.
	url: url da view que abre após deletar o registro*/
	var ajax = new Request();
	var callback = funcao;
	ajax.doGet(url, callback, "text");
}

//validação de formulário
function validaForm(server_url){
	if (tiny()=="s"){tinyMCE.triggerSave(true,true)}
	
	var c = 0;
	for (var i=0; i<document.forms[0].elements.length; i++){
		
		var el = document.forms[0].elements[i];
		if (el.type!="hidden"){
			
			if ((el.value=="")||(el.value=="<P>&nbsp;</P>")){
				c++;
			}
		}
	}
	
	if (c==0){
		gravaForm(server_url);
	} else {
		var alrt = new buildAlert();
		alrt.msg = "Todos os campos devem ser preenchidos";
		alrt.acao = "";
		alrt.doAlert();
	}
}

//Classe que controi o alert
function buildAlert(str){
	this.msg = "";
	this.acao = "";
	this.doAlert = function(){
		
		if (!document.getElementById('alert')){
			var div = document.createElement("div");
			div.id = "alert";
			var span = document.createElement("span");
			span.id = "alert_span";
			span.appendChild(document.createTextNode(this.msg));
			
			span.onclick=function(){
				span.style.display='none';
				opacity('alert', 70, 0, 160);
				setTimeout("fadeOutAlert()", 70);
			}
			
			changeOpac(0, null, div);
			document.body.appendChild(div);
			document.body.appendChild(span);
			opacity('alert', 0, 70, 160);
		} else {
			
			var al = document.getElementById('alert');
			var sp = document.getElementById('alert_span');
			sp.innerHTML = this.msg;
			al.style.display='block';
			sp.style.display='block';
			changeOpac(0, 'alert', null);
			opacity('alert', 0, 70, 160);
		}
	}
}
function fadeOutAlert(){
	var al = document.getElementById('alert');
	al.style.display='none';
}

//gravaVaga: utiliza a classe RequestClass
function gravaForm(server_url){
	if (tiny()=="s"){tinyMCE.triggerSave(true,true)}
	var save = new FormSave();
	save.funcao = function(str){
		var alrt = new buildAlert(str);
		alrt.msg = "Salvo com sucesso";
		//alrt.acao = "document.location.href='form_vaga.php?cod='+str";
		alrt.doAlert();
	}
	save.url = server_url;
	save.doSalvar();
}

function gravaFormBackground(pk, server_url){
	var url = document.location.toString();
	if (url.indexOf("form")!=-1){
		if (document.forms.length!=0){
			if(eval("document.forms[0]."+pk+".value!=''")){
				if (tiny()=="s"){tinyMCE.triggerSave(true,true)}
				var save = new FormSave();
				save.funcao = function(str){}
				save.url = server_url;
				save.doSalvar();
			}
		}
	}
}

/*MENU GERAL PARA FORMS E VISÕES -------------------------------------------------- */
function buildDl(){
	var div = document.createElement('div');
	div.id = "menu_horizontal";
	var first_node = document.body.firstChild;
	first_node.parentNode.insertBefore(div,first_node);
	
	//adiciona autometicamento o link 'sair', o logout
	addTerm("Sair","logout", "javascript:admLogout()");
	
	//ajusta titulo - provisório: tem que ser o primeiro node que for
	if (document.body.getElementsByTagName('h1')[0]){
		document.body.getElementsByTagName('h1')[0].style.marginTop="38px";
	}
}

/*ADICIONA ITEM DE MENU
desc= descrição do menu.
id = id único da div.
url = case não tenha links abaixo e ele mesmo seja um link*/
function addTerm(desc, id, url){
	this.desc = desc;
	this.id = id;
	
	var div = document.createElement("div");
	var div_links = document.createElement("div");
	div.className = "menu";
	div_links.className = "menu_links";
	div_links.id = this.id+"_links";
	
	div.id = this.id;
	div.appendChild(document.createTextNode(this.desc));
	
	if (url!=undefined){
		div.onclick = function(){
			document.location.href=url;
		}
	} else {
		var loc = document.location.toString();
		div.onmouseover = function(){
			div_links.style.display="block";
			
			//bug ie
			if ((navigator.appName.indexOf("Microsoft")!=-1)&&(loc.indexOf('form')!=-1)){
				var sel = document.forms[0].getElementsByTagName('select');
				for (var i=0; i<sel.length; i++){
					sel[i].style.visibility='hidden';
				}
			}
		}
		
		div.onmouseout = function(){
			div_links.style.display="none";
			
			//bug ie
			if ((navigator.appName.indexOf("Microsoft")!=-1)&&(loc.indexOf('form')!=-1)){
				var sel = document.forms[0].getElementsByTagName('select');
				for (var i=0; i<sel.length; i++){
					sel[i].style.visibility='visible';
				}
			}
		}
		
		div_links.onmouseover = function(){
			div_links.style.display="block";
			
			//bug ie
			if ((navigator.appName.indexOf("Microsoft")!=-1)&&(loc.indexOf('form')!=-1)){
				var sel = document.forms[0].getElementsByTagName('select');
				for (var i=0; i<sel.length; i++){
					sel[i].style.visibility='hidden';
				}
			}
		}
		
		div_links.onmouseout = function(){
			div_links.style.display="none";
			
			//bug ie
			if ((navigator.appName.indexOf("Microsoft")!=-1)&&(loc.indexOf('form')!=-1)){
				var sel = document.forms[0].getElementsByTagName('select');
				for (var i=0; i<sel.length; i++){
					sel[i].style.visibility='visible';
				}
			}
		}
	}
	
	var dl = document.getElementById("menu_horizontal");
	dl.appendChild(div);
	dl.appendChild(div_links);
	var lft = findPos(div)[0];
	var tp = findPos(div)[1];
	div_links.style.top = (tp+25)+"px";
	div_links.style.left = (lft+2)+"px";
	
}

/*ADICIONA OS LINKS AOS 'TERMS'*/
function addLink(url, desc, div_id){
	this.url = url;
	this.desc = desc;
	this.div_id = div_id;
	var div_container = document.getElementById(div_id+"_links");
	var lnk = document.createElement("a");
	lnk.href = this.url;
	lnk.appendChild(document.createTextNode(this.desc));
	div_container.appendChild(lnk);
}


/*FUNÇÕES DE CONVENIÊNCIA -------------------------------------------------------- */
//verifica TinyMce
function tiny(){
	var tiny = "n";
	var sc = document.getElementsByTagName("script");
	for(var s=0; s<sc.length; s++){
		attr = sc[s].getAttribute("src").toString();
		if(attr.indexOf("tiny_mce")!=-1){
			tiny ="s";
			break;
		}
	}
	return tiny;
}
//Faz o efeito "hover" nas linhas de uma tabela
function hoverVisao(id){
	var div = document.getElementById(id);
	var tr = div.getElementsByTagName('tr');
	for (var i=0; i<tr.length; i++){
		if (tr[i].getElementsByTagName('th').length==0){
			tr[i].onmouseover = function(){
				this.style.backgroundImage = "url(../images/fundo_visao_hover.jpg)";
				this.onmouseout = function(){
					this.style.backgroundImage = "none";	
				}
			}
		}
	}
}

//Encontra posição de qualquer elemento: Quirksmode.org
function findPos(obj){
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
}
