// JavaScript Document
$(document).ready(function(){
	
	$('#error').hide();//hide the error div on page load
	$('#loginForm').submit(function(e){
		e.preventDefault();
		var name = $("#name").val();
		var email = $("#email").val();
		$('#error').fadeOut('slow'); // remove currently visible error message.
		if(name.length == 0){
			$("#name").addClass("highlight");
				return false;
			}else {$("#name").removeClass("highlight");}
		if(email.length == 0){
			$("#email").addClass("highlight");
				return false;
			}else {$("#email").removeClass("highlight");}
			//send login form values to login.php
			$.post('php/login.php',$(this).serialize(),
		function(msg){
			if(msg.status){
				//if submit returns success, redirect to index.php
				//and reload the page to for the session values to show
				window.location = 'index.php';
			}
	else {	/*when an error occurs
				show the error div below the login form
				*/
			
			$('#error').fadeIn('slow');
				
			
			}
		},'json');

					
	});
	
	//listen for submits on the user message form
	$("#message").submit(function(e){
		e.preventDefault();
		$('#error').fadeOut('slow'); // remove currently visible error message.	
		var msg = $("#msg").val();
		if(msg.length == 0){
				
			$("#msg").addClass("highlight");
				return false;
			}else {$("#msg").removeClass("highlight");}
			
			$.post('php/post.php',$(this).serialize(),
			function(msg){
			if(!msg.status){
			$('#error').fadeIn('slow');
			}
		},'json');
		$("#msg").attr("value", "");
		$('#msg').focus();
		return false;
	});
	
	
		
	//Load the file containing the chat log
	function loadChats(){	
		var initialheight = $("#chatbox").attr("height") - 20;
		$.ajax({
			url: "chat/log.html",
			cache: false,
			success: function(html){		
				$("#chatbox").html(html); //Insert chat log into the #chatbox div				
				var currentheight = $("#chatbox").attr("height") - 20;
				if(currentheight > initialheight){
					$("#chatbox").animate({ scrollTop: currentheight }, 'slow'); //Autoscroll to bottom of div
				}				
		  	},
		});
	}
	setInterval (loadChats, 2000);	//Reload file every 2 seconds
	
	//If user wants to end session
	$("#exit").click(function(e){
		window.location = 'php/logout.php?logout=true';		
	});
});


