/**
* "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.tracciato.com.br/midia/icons/activity.gif\" />";
	this.response = null;
	this.indicator = null;
	this.popUpWin=0;
	this.path = '';
	
	//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;
	};
	
	this.maskData = function(objeto){
		strTelefone = objeto.value;
		var re = new RegExp("[\\D+]*", "g");
		strTelefone = strTelefone.replace(re,"");
		strTelefoneFmt = strTelefone.toString();
		intTamTelefone = strTelefoneFmt.length;
		
		if (intTamTelefone > 8) {
			intTamTelefone = 8;
			strTelefoneFmt = strTelefoneFmt.substr(0, 8);
		}
		if (intTamTelefone > 4) {
			strTelefoneFmt = strTelefoneFmt.substr(0, 2) + "/" +
			strTelefoneFmt.substr(2, 2) + "/" +
			strTelefoneFmt.substr(4, 8);
		}
		else if (intTamTelefone > 2) {
			strTelefoneFmt = strTelefoneFmt.substr(0, 2) + "/" +
			strTelefoneFmt.substr(2, 2);
		}
		objeto.value = strTelefoneFmt;
	};
	
	this.maskHorario = function(objeto){
		strTelefone = objeto.value;
		var re = new RegExp("[\\D+]*", "g");
		strTelefone = strTelefone.replace(re,"");
		strTelefoneFmt = strTelefone.toString();
		tam = strTelefoneFmt.length;
		
		if (tam > 4) {
			tam = 4;
			strTelefoneFmt = strTelefoneFmt.substr(0, 4);
		}
		else if (tam > 2) {
			strTelefoneFmt = strTelefoneFmt.substr(0, 2) + "h" +
			strTelefoneFmt.substr(2, 2);
		}
		objeto.value = strTelefoneFmt;
	};
	
	this.maskMult = function (formato, campo) {
		strTelefone = campo.value;
		var re = new RegExp("[\\D+]*", "g");
		strTelefone = strTelefone.replace(re,"");
		str = strTelefone.toString();
	
		// cep
		if (formato == 'cep') {
			separador='-';
			conjunto1=5;
			if (campo.value.length == conjunto1) {
				campo.value=campo.value + separador;
			}
			campo.value = campo.value.substr(0, 9)
			str = campo.value;
		}
	
		// cpf
		else if (formato == 'cpf') {
			str = str.substr(0, 3) + "." + str.substr(3, 3) + "." + str.substr(6, 3) + "-" + str.substr(9, 2);
			campo.value = str;
		}
		
		//dinheiro
		else if (formato == 'dinheiro'){
			var len = str.length;
			if(len > 3){
				if(len > 4){
					str = str.substr(0, 2) + "." + str.substr(2, 3);
				}
				else {
					str = str.substr(0, 1) + "." + str.substr(1, 3);
				}
			}
			campo.value = str;
		}
		
		//numeros
		else if (formato == 'numeros'){
			campo.value = str;
		}
	
		// nascimento
		else if (formato == 'data') {
			str = str.substr(0, 2) + "/" + str.substr(2, 2) + "/" + str.substr(4, 4);
			campo.value = str;
		}
	
		// telefone
		else if (formato == 'telefone') {
			separador1='(';
			separador2=')';
			separador3='-';
			conjunto1=0;
			conjunto2=3;
			conjunto3=8;
			if (campo.value.length == conjunto1) {
				campo.value=campo.value + separador1;
			}
			else if (campo.value.length == conjunto2) {
				campo.value=campo.value + separador2;
			}
			else if (campo.value.length == conjunto3) {
				campo.value=campo.value + separador3;
			}
			campo.value = campo.value.substr(0, 13)
		}
	};
	
	this.maskCNPJ = function(Campo, teclapres){
		Campo.value = Campo.value.substr(0, 17);
		
	   if(window.event){
		var tecla = teclapres.keyCode;
	   }else  tecla = teclapres.which;
	
	   var vr = new String(Campo.value);
	   vr = vr.replace(".", "");
	   vr = vr.replace(".", "");
	   vr = vr.replace("/", "");
	   vr = vr.replace("-", "");
	   vr = vr.replace("[a-zA-Z]", "");
	
	   tam = vr.length + 1;
	
	  
	   if (tecla != 9 && tecla != 8){
		  if (tam > 2 && tam < 6)
			 Campo.value = vr.substr(0, 2) + '.' + vr.substr(2, tam);
		  if (tam >= 6 && tam < 9)
			 Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,tam-5);
		  if (tam >= 9 && tam < 13)
			 Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,3) + '/' + vr.substr(8,tam-8);
		  if (tam >= 13 && tam < 15)
			 Campo.value = vr.substr(0,2) + '.' + vr.substr(2,3) + '.' + vr.substr(5,3) + '/' + vr.substr(8,4)+ '-' + vr.substr(12,tam-12);
		  }
	};
	
	//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){
		this.indicator = indicatorDiv;
		this.load(targetDiv, url);
	}
	
	//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){}
			}
		}
		else {
			handler = function(data){
				ref.clearResponse();
				handle(data);
				//iniciando lightbox
				if(initLightbox){
					initLightbox();
				}
				try {
					M.reset();
				}
				catch(e){}
			}
		}
		if(this.indicator != null){
			this.$(this.indicator).innerHTML = this.progress;
		}
		jx.load(url, handler, "text", "post", vars);
	};
	
	//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;
	};
};
//Cria a variável que será usada pelo site.
var R = new Engine();