var windowIsIdle = true;
var idleWaiting = null;
var firstChatId = '';
var chatId = '';
var chatMessage = '';
var chatMessageSent = 0;

function scrollMove() {
	if (!this) {
		return;
	}
	if (this.isScrolledToBottom) {
		this.scrollToBottom();
	}
	if (typeof(this.scrollTopTarget) != 'undefined') {
		if (this.scrollTopTarget != this.scrollTop) {
			this.scrollTop = this.scrollTop + Math.floor((this.scrollTopTarget-this.scrollTop)/3);
		}
	}
}
function scrollUp() {
	if (!this) {
		return;
	}
	var oldScrollTopTarget = this.scrollTopTarget;
	this.scrollTopTarget = Math.max(0, this.scrollTopTarget-150);
	if (oldScrollTopTarget == this.scrollTopTarget) {
		this.scrolling = false;
	}
	else if (this.scrolling) {
		scrollEl = this;
		setTimeout(function () {scrollEl.scrollUp();}, scrollEl.scrollSpeedTimeout);
		scrollEl.scrollSpeedTimeout = Math.max(Math.round(scrollEl.scrollSpeedTimeout-(scrollEl.scrollSpeedTimeout/4)), 100);
	}
	this.isScrolledToBottom = false;
}
function scrollDown() {
	if (!this) {
		return;
	}
	var oldScrollTopTarget = this.scrollTopTarget;
	this.scrollTopTarget = Math.min(this.scrollHeight-this.offsetHeight+4, this.scrollTopTarget+150);
	if (oldScrollTopTarget == this.scrollTopTarget) {
		this.scrolling = false;
	}
	else if (this.scrolling) {
		scrollEl = this;
		setTimeout(function () {scrollEl.scrollDown();}, scrollEl.scrollSpeedTimeout);
		scrollEl.scrollSpeedTimeout = Math.max(Math.round(scrollEl.scrollSpeedTimeout-(scrollEl.scrollSpeedTimeout/4)), 100);
	}
	if (Math.abs(this.scrollTopTarget+this.offsetHeight-this.scrollHeight)<=10) {
		this.isScrolledToBottom = true;
	}
}
function scrollToBottom() {
	if (!this) {
		return;
	}
	this.scrollTopTarget = this.scrollHeight-this.offsetHeight+4;
	this.isScrolledToBottom = true;
}
function scrollToTop() {
	if (!this) {
		return;
	}
	this.scrollTopTarget = 0;
	this.isScrolledToBottom = false;
}
function windowBlur() {
	if (!windowIsIdle) {
		if (idleWaiting) {
			clearTimeout(idleWaiting);
		}
		idleWaiting = setTimeout(function(){windowIsIdle = true; document.title += ' - pe loc repaus';}, 60000);
	}
}
function windowFocus() {
	if (idleWaiting) {
		clearTimeout(idleWaiting);
	}
	if (windowIsIdle) {
		windowIsIdle = false;
		document.title = document.title.replace(/ - pe loc repaus/g, '');
		if ($('chat')) {
			updateChat();
		}
		if ($('servers_status')) {
			updateServersStatus();
		}
	}
}

Event.observe(window, 'load', function () {
	windowIsIdle = false;
	if(!Prototype.Browser.IE) {
		Event.observe(window, 'blur', windowBlur);
		Event.observe(window, 'focus', windowFocus);
	}
	else {
		document.onfocusin = windowFocus;
		document.onfocusout = windowBlur;
	}

	$$('.scroll-y').each(function(el){
		var scrollElements =
			'<div class="scroll-y">' +
			'	<a class="scroll-up" href="javascript:void(0)"></a>' +
			'	<a class="scroll-down" href="javascript:void(0)"></a>' +
			'</div>';
		el.insert({after: scrollElements});

		el.scrollTopTarget = 0;
		el.scrollSpeedTimeout = 500;
		el.isScrolledToBottom = true;
		el.scrolling = false;
		el.scrollUp = scrollUp;
		el.scrollDown = scrollDown;
		el.scrollMove = scrollMove;
		el.scrollToBottom = scrollToBottom;
		el.scrollToTop = scrollToTop;
		el.scrollInterval = null;
		el.scrollIntervalStart = function() {
			var scrollEl = this;
			self.scrollInterval = window.setInterval(function(){scrollEl.scrollMove();}, 50);
		}
		el.scrollIntervalStart();

	});

	$$('.scroll-y .scroll-up').each(function(el){
		scrollEl = el.parentNode.previousSibling;
		Event.observe(el, 'mousedown', function(){scrollEl.scrolling = true; scrollEl.scrollUp();});
		Event.observe(el, 'mouseup', function(){scrollEl.scrolling = false; scrollEl.scrollSpeedTimeout = 500;});
	});

	$$('.scroll-y .scroll-down').each(function(el){
		scrollEl = el.parentNode.previousSibling;
		Event.observe(el, 'mousedown', function(){scrollEl.scrolling = true; scrollEl.scrollDown();});
		Event.observe(el, 'mouseup', function(){scrollEl.scrolling = false; scrollEl.scrollSpeedTimeout = 500;});
	});

	$$('a.input-file').each(function(link){
		var input = link.descendants()[0];
		link.style.width = (
			Element.getWidth(link)-
			parseInt(Element.getStyle(link, 'paddingLeft'), 10)-
			parseInt(Element.getStyle(link, 'paddingRight'), 10)-
			parseInt(Element.getStyle(link, 'marginLeft'), 10)-
			parseInt(Element.getStyle(link, 'marginRight'), 10)
			)+'px';
		link.style.height = (
			Element.getHeight(link)-
			parseInt(Element.getStyle(link, 'paddingTop'), 10)-
			parseInt(Element.getStyle(link, 'paddingBottom'), 10)-
			parseInt(Element.getStyle(link, 'marginTop'), 10)-
			parseInt(Element.getStyle(link, 'marginBottom'), 10)
			)+'px';

		Event.observe(link, 'mousemove', function(e){
			var input = link.descendants()[0];
			var mouse_x = Event.pointerX(e), mouse_y = Event.pointerY(e);
			var link_position = link.cumulativeOffset();
			var link_x = link_position[0], link_y = link_position[1];
			var input_dimensions = input.getDimensions();
			var input_w = input_dimensions.width, input_h = input_dimensions.height;
			input.style.left = (mouse_x-link_x-input_w+20)+'px';
			input.style.top = (mouse_y-link_y-Math.round(input_h/2)+(Prototype.Browser.IE ? 10 : 0))+'px';
		});
		Event.observe(input, 'change', function(e){
			var link = input.offsetParent;
			bg = link.getStyle('backgroundImage').replace(/icon_open.jpg/, 'icon_open_full.jpg');
			link.setStyle({backgroundImage: bg});
		});
	});
	if ($('chat')) {
		updateChat();
	}
	if ($('servers_status')) {
		updateServersStatus();
	}
});

function submitAction(action, form) {
	$('action').value = action;
	(form ? $(form) : document.forms[0]).submit();
	return false;
}

function setCheckbox(el) {
	input = $(el.id ? el.id.replace(/_label/, '') : '');
	if (input) {
		input.value = input.value == '1' ? '0' : '1';
		el.className = input.value == '1' ? 'checkbox-checked' : 'checkbox';
	}
}

function updateServersStatus() {
	new Ajax.Request(
		'async_servers.php',
		{
			onComplete: function(response) {
				if (response.status==200) {
					$('servers_status').update(response.responseText);
				}
				if (!windowIsIdle) {
					setTimeout(updateServersStatus, 30000);
				}
			}
		}
	)
}

function loginKeyDown(e) {
	if ((e.keyCode==Event.KEY_RETURN)) {
		submitAction('login');
		return false;
	}
	else document.title = e.keyCode;
	return true;
}

function chatLineKeyDown(e) {
	if ((e.keyCode==Event.KEY_RETURN)) {
		if ($F('chat_line')) {
			sendChatMessage();
		}
		return false;
	}
	return true;
}

function chatLineKeyUp(e) {
	if (e.keyCode==Event.KEY_ESC) {
		$('chat_line').value = '';
	}
}

function sendChatMessage() {
	if (chatMessageSent==0) {
		chatMessage = $F('chat_line');
		$('chat_line').value = '';
		$('chat_line').disable();
	}
	else if (chatMessageSent>=3) {
		alert('Mesajul nu a putut fi trimis (am incercat de 3 ori, renunt...)');
		chatMessage = '';
		chatMessageSent = 0;
		$('chat_line').enable();
		return;
	}

	new Ajax.Request(
		'async_chat.php',
		{
			method: 'post',
			parameters: {action: 'insert_message', message: chatMessage},
			onComplete: function(response) {
				if ((response.status==200) && (response.responseJSON.success=='true')) {
					chatMessage = '';
					chatMessageSent = 0;
					$('chat_line').enable();
					$('chat_line').focus();
				}
				else {
					chatMessageSent++;
					sendChatMessage();
				}
			}
		}
	);

}

function updateChat() {
	new Ajax.Request(
		'async_chat.php',
		{
			method: 'post',
			parameters: {action: 'get_messages', id: chatId},
			onComplete: function(response) {
				if ((response.status==200) && response.responseJSON) {
					if (chatId=='') {
						$('chat-content-tbody').update();
						if (response.responseJSON.have_archive=='true') {
							$('view_older').show();
						}
						if (response.responseJSON.messages[0]) {
							firstChatId = response.responseJSON.messages[0].id;
						}
					}
					response.responseJSON.messages.each(function(message){
						chatId = message.id;
						$('chat-content-tbody').insert(message.text);
					});
					if ($('chat').isScrolledToBottom) {
						$('chat').scrollToBottom();
					}
				}
				if (!windowIsIdle) {
					setTimeout(updateChat, 1000);
				}
			}
		}
	);
}

function updateOlderChat() {
	new Ajax.Request(
		'async_chat.php',
		{
			method: 'post',
			parameters: {action: 'get_messages', before_id: firstChatId},
			onComplete: function(response) {
				if ((response.status==200) && response.responseJSON) {
					if (response.responseJSON.have_archive=='false') {
						$('view_older').hide();
					}
					response.responseJSON.messages.each(function(message){
						firstChatId = message.id;
						$('chat-content-tbody').firstDescendant().insert({before: message.text});
					});
					$('chat').scrollToTop();
				}
			}
		}
	);

}