$(document).ready(function() {
	document.getElementById('videolink').href = '#TB_inline?width=640&height=395&inlineId=video';
	
	$(".slide").click(function(){
		if (loggedIn) {
			window.location = '/view';
		} else {
			var state = $('#content').css('top');
			if (state === "-90px") {
				$('#content').animate({
					top: "0px"
				}, 500);
				$('.slide').html('Close panel');
			}
			else {
				$('#content').animate({
					top: "-90px"
				}, 500)
				$('.slide').html('Login to manage a device with Paranoia')
			};
		}
		return false;
	});
	$('#input').submit(function(){
		var e = document.getElementById("loginSubmit");
			e.value = 'Logging in...';
			e.disabled = true;
		var s = document.getElementById("status");
			s.textContent = '';
		var username = $('#user').val();
		var password = sha1($('#pass').val());
		submitLogin(username, password);
		return false;
	});
	
	function reenableLogin(textStatus) {
		var s = document.getElementById("status");
				s.textContent = textStatus;
		var e = document.getElementById("loginSubmit");
			e.value = 'Log in';
			e.disabled = false;
	}
	function onLoginSuccess(data) {
		if (data.success) {
			window.location = '/view';
		} else {
			reenableLogin('Invalid credentials.');
		}
	}
	
	function onLoginFail(xhr, textStatus, errorThrown) {
		reenableLogin(textStatus);
	}
	
	function submitLogin (username, password) {
		$.ajax({
			data: {'username': username, 'password': password},
			type: 'POST',
			url: '/user/login',
			dataType: 'json',
			error: onLoginFail,
			success: onLoginSuccess
		});
	}
});