function o(id) { return document.getElementById(id); }
function s(id) { return o(id).style; }

var Atendimento = {
	timeout: null,
	retry: null,
	name: null,
	atname: null,
	session: null,
	last: 0,
	offline: function() {
		o('at-msg').innerHTML = "No momento, este serviço se encontra indisponível.<br/>Por favor, tente novamente mais tarde.";
		s('at-entrada').display = "none";
		s('at-chat').display = "none";
		this.timeout = setTimeout("Atendimento.initCheck()",5000);
	},
	online: function(sid) {
		this.session = sid;
		clearTimeout(this.timeout);
		o('at-msg').innerHTML = "Bem vindo(a) ao atendimento online da <b>Pousada Pedra Salgada</b><br/><br/>";
		s('at-entrada').display = "block";
	},
	sendLogin: function() {
		new Ajax.Request('_atendimento.php',{
			method:'post',
			parameters:{"action":"login","session":Atendimento.session,"name":Atendimento.name},
			onFailure: function(){ Atendimento.offline(); },
			onSuccess: function(transport){
				if (!parseInt(transport.responseText)) { Atendimento.retry = setTimeout("Atendimento.sendLogin()",10000); return; }
				Atendimento.ativaChat();
			}
		});
	},
	login: function() {
		o('at-msg').innerHTML = "Por favor, aguarde um de nossos atendentes... <img src=\"css/img/throbber.gif\"/>";
		s('at-entrada').display = "none";
		this.sendLogin();
	},
	entrar: function() {
		if (!o('at-nome').value.length) { alert("Por favor, entre com seu nome"); o('at-nome').focus(); return false; }
		Atendimento.name = o('at-nome').value;
		Atendimento.login();
	},
	ativaChat: function() {
		o('at-msg').innerHTML = "Olá, <b>"+Atendimento.name+"</b>.<br/>Bem vindo(a) ao atendimento online da <b>Pousada Pedra Salgada</b><br/><br/>";
		s('at-chat').display = "block";
		clearTimeout(this.timeout);
		this.timeout = setTimeout("Atendimento.update()",5000);
		last = 0;
		this.update();
	},
	update: function() {
		new Ajax.Request('_atendimento.php',{
			method:'post',
			parameters:{"action":"update","session":Atendimento.session,"last":Atendimento.last},
			onFailure: function(){ Atendimento.offline(); },
			onSuccess: function(transport){
				if (transport.responseText == 'D') {
					clearTimeout(Atendimento.timeout);
					Atendimento.pushEvent("Ocorreu um erro na conexão com o atendente. <a href=\"atendimento.php\">Clique aqui para tentar novamente.</a>");
					document.getElementById('chat-input').disabled = "disabled";
					clearTimeout(Atendimento.timeout);
					return;
				}
				
				data = transport.responseText.split("\n");
				var i,l;
				for (i = 0;i < data.length;i++) {
					l = data[i].split("¬");
					if (l.length == 4) {
						Atendimento.last = l[0];
						Atendimento.pushText(l[1],l[2],l[3]);
					}
				}
				clearTimeout(Atendimento.timeout);
				Atendimento.timeout = setTimeout("Atendimento.update()",5000);
			}
		});
	},
	pushEvent: function(texto) {
		var p = document.createElement('p');
		p.className = "event";
		p.innerHTML = "* "+texto;
		document.getElementById('chat-text-area').appendChild(p);
		this.moveDown();
	},
	pushText: function(u,nome,texto) {
		if (!texto.length) return;
		var p = document.createElement('p');
		p.innerHTML = '<span class="'+(u?'atend':'user')+'">'+nome+":</span> "+texto.replace(/</, "&lt;").replace(/>/, "&gt;");
		document.getElementById('chat-text-area').appendChild(p);
		this.moveDown();
	},
	moveDown: function() {
		var ct = document.getElementById('chat-text');
		var cta = document.getElementById('chat-text-area');
		if (cta.offsetHeight > ct.offsetHeight) { ct.scrollTop = (cta.offsetHeight - ct.offsetHeight)+10; }
	},
	submit: function() {
		var t = o('chat-input').value;
		if (!t.length) return;
		Atendimento.pushText(0,Atendimento.name,t);
		o('chat-input').value = "";
		o('chat-input').focus();
		new Ajax.Request('_atendimento.php',{
			method:'post',
			parameters:{"action":"text","session":Atendimento.session,"name":Atendimento.name,"text":t},
			onFailure: function(){ },
			onSuccess: function(){ }
		});
		
	},
	checkLogin: function(e) {
		if (e.keyCode == 13) Atendimento.entrar();
	},
	checkSubmit: function(e) {
		if (e.keyCode == 13) Atendimento.submit();
	},
	init: function() {
		try {
			o('at-entrar').addEventListener('click',Atendimento.entrar,false);
			o('chat-input').addEventListener("keydown",Atendimento.checkSubmit,false);
			o('at-nome').addEventListener("keydown",Atendimento.checkLogin,false);
			o('chat-submit').addEventListener("click",Atendimento.submit,false);
		} catch (e) {
			o('at-entrar').attachEvent("onclick",Atendimento.entrar);
			o('chat-input').attachEvent("onkeydown",Atendimento.checkSubmit);
			o('at-nome').attachEvent("onkeydown",Atendimento.checkLogin);
			o('chat-submit').attachEvent("onclick",Atendimento.submit);
		}
		o('at-msg').innerHTML = "Verificando disponibilidade do serviço...<br/><img src=\"css/img/throbber.gif\"/>";
		s('at-entrada').display = "none";
		this.initCheck();
	},
	initCheck: function() {
		this.timeout = setTimeout("Atendimento.offline()",10000);
		new Ajax.Request('_atendimento.php',{
			method:'post',
			parameters:{"action":"check"},
			onFailure: function(){ Atendimento.offline(); },
			onSuccess: function(transport){
				clearTimeout(this.timeout);
				if (!transport.responseText.length) { Atendimento.offline(); return; }
				var data = transport.responseText.split(" ");
				if (data.length != 2) { Atendimento.offline(); return; }
				if (parseInt(data[0]) > 0) { Atendimento.online(data[1]); return; }
				Atendimento.offline();
				return;
			}
		});
	}
}
Atendimento.init();
