/**
* "Classe" para gerenciar aspectos gerais de comunicação.
* Dependente do script jx.
* @author	Thiago Ricieri
*/

function Engine() {
	
	//Variáveis
	this.progress = "<img src=\"http://www.compactapremoldados.com.br/preview/midia/icons/activity.gif\" />";
	this.response = null;
	this.indicator = null;
	this.popUpWin=0;
	this.path = '';
	
	this._thickbox_init = function(){
		tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
		imgLoader = new Image();// preload image
		imgLoader.src = tb_pathToImage;
	}
	
	//Função para retornar referência de objeto
	this.$ = function(id){
		return document.getElementById(id);
	};
	
	this.replaceAll = function(s, r, str){
		do {
			var tag = str.indexOf(s);
			str = str.replace(s, r);
		} while(tag >= 0);
		return str;
	};
	
	//abrir janela
	this.newWindow = function(nome, path, width, height){
		var left = (window.screen.width/2) - (width/2);
		var top = (window.screen.height/2) - (height/2);
		if(this.popUpWin) {
			if(!this.popUpWin.closed)
				this.popUpWin.close();
		}
		this.popUpWin = window.open(path, nome, 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbar=no,resizable=no,copyhistory=yes,width='+width+',height='+height+',left='+left+', top='+top+',screenX='+left+',screenY='+top+'');
	};
        
	this.formatEntry = function(obj, tipo){
		switch(tipo){
			case "login": 
				obj.value = obj.value.replace(/[^0-9a-zA-Z]/i, "");
				obj.value = obj.value.toLowerCase();
		}
		return true;
	};
	
	this.loadShowingActivity = function(targetDiv, indicatorDiv, url, nhandle, vars){
		this.indicator = indicatorDiv;
		this.load(targetDiv, url, nhandle, vars);
	}
	
	//Carregando...
	this.load = function(targetDiv, url, nhandle, vars, useHandle){
		this.response = targetDiv;
		this.nhandle = nhandle;
		this.indicator = this.indicator == null ? targetDiv : this.indicator;
		useHandle = useHandle == null ? false : true;
		var ref = this;
		//
		if(!useHandle){
			var handle = function(data){
				ref.$(ref.response).innerHTML = data;
				ref.parseScript(data);
				if(ref.nhandle){
					ref.nhandle(data);
				}
			}
		}
		else {
			var handle = function(data){
				ref.parseScript(data);
				if(ref.nhandle){
					ref.nhandle(data);
				}
			}
		}
		if(!vars){
			vars = "";
		}
		//window.alert(url);
		//this.makeHistory(url);
		this.initializeLoad(url, handle, vars);
	};
	
	this.parseScript = function(data){
		var last = 0;
		var iTag = 0; 
		do {
			iTag = data.indexOf("<script", last);
			if(iTag > -1){
				last = data.indexOf("</script>", iTag);
				var scr = data.substring(data.indexOf(">", iTag)+1, last);
				eval(scr);
			}
		} while(iTag >= 0);
	}
	
	//Função para enviar todos os dados de um formulário
	this.sendForm = function(form, url, responseDiv, handle){
		
		this.response = responseDiv;
		this.indicator = this.response;
		var f = this.$(form);
		var vars = "";
		
		if(this.$('submitbtn')){
			this.$('submitbtn').disabled = true;
		}
		
		for(var i=0; i<f.length; i++){
			try {
				var oEditor = FCKeditorAPI.GetInstance(f[i].getAttribute('name'));
				vars += "&"+f[i].getAttribute('name')+"="+escape(oEditor.GetXHTML());
			}
			catch(e){
				if(f[i] && f[i].getAttribute){
					var theType = f[i].getAttribute("type");
					var theName = f[i].getAttribute("name");
					if(theType == "radio"){
						if(f[i].checked){
							vars += "&" + theName + "=" + f[i].value;
						}
					}
					else if(theType != null || theName != null){
						vars += "&" + theName + "=" +(theType == "checkbox" ? (f[i].checked ?"1":"0") : escape(f[i].value));
					}
				}
			}
		}
		
		this.initializeLoad(url, handle, vars);
		return false;
	};
	
	this.formatInlineURL= function(str){
		return this.replaceAll("&", escape("&"), str);
	};
	
	//Inicializa o carregamento
	this.initializeLoad = function(url, handle, vars){
		var ref = this;
		if(!handle){
			handler = function(data){
				ref.clearResponse();
				ref.$(ref.response).innerHTML = data;
				/*iniciando lightbox
				if(initLightbox){
					initLightbox();
				}
				try {
					M.reset();
				}
				catch(e){}*/
				ref._thickbox_init();
			}
		}
		else {
			handler = function(data){
				ref.clearResponse();
				handle(data);
				/*iniciando lightbox
				if(initLightbox){
					initLightbox();
				}
				try {
					M.reset();
				}
				catch(e){}*/
				ref._thickbox_init();
			}
		}
		if(this.indicator != null){
			this.$(this.indicator).innerHTML = this.progress;
		}
		jx.load(url, handler, "text", "post", vars);
	};
	
	this.getSelectedRadio = function(form, field){
		var f = this.$(form);
		for(i=0; i<f.length; i++){
			if(f[i].getAttribute("name") == field && f[i].checked){
				return f[i].value;
			}
		}
		return "#";
	}
	
	//Limpa o carregando
	this.clearResponse = function(){
		if(this.$('submitbtn')){
			this.$('submitbtn').disabled = false;
		}
		this.$(this.response).innerHTML = "";
		if(this.indicator != null){
			this.$(this.indicator).innerHTML = "";
		}
		this.indicator = null;
	};
	
	this.selectByValue = function(data, value){
		var s = this.$(data);
		for(var i=0; i<s.length; i++){
			if(s[i].value == value){
				s.selectedIndex = i;
				break;
			}
		}
}
};
//Cria a variável que será usada pelo site.
var R = new Engine();