/*
	Loads html content asynchronously from the
	web server into the content div
*/
var currentPage = 'none';

$(document).ready(
	function(){
		menu = new Menu("#menu_bar","#content");
		menu.bindEvents(menu);
	}
);

// Definition of setSelected for Menu object
function setSelected(type){
	
	if(type == 'settings'){
		this.settingsButton.css("background-position","0px -68px");
		this.friendsButton.css("background-position","0px 0px");
		
		if(isLoggedIn()){
			$('#menu_bar').show();
		}
		else{
			$('#menu_bar').hide();
		}
	}
	else if(type == 'friends'){
		if(isLoggedIn()){
			if(isNewRegister()){
				$('#menu_bar')[0].style.display = 'none';
			}
			else{
				$('#menu_bar')[0].style.display = 'block';
			}
		}
		else{
			$('#menu_bar')[0].style.display = 'none';
		}
	
		this.settingsButton.css("background-position","0px 0px");
		this.friendsButton.css("background-position","0px -68px");
	}
	else{
		this.friendsButton.css("background-position","0px 0px");
		this.settingsButton.css("background-position","0px 0px");
		if(isLoggedIn()){
			$('#menu_bar')[0].style.display = 'block';
		}
		else{
			$('#menu_bar')[0].style.display = 'none';
		}	
	}
	
	// Change the current page
	currentPage = type;
}

/*
	Menu object, handles content loading
*/
var Menu = function(menuID, contentID){
	
	this.menuElem = $(menuID);
	this.contentElem = $(contentID);
	this.friendsButton = this.menuElem.find("#friends_button_table");
	this.settingsButton = this.menuElem.find("#settings_button_table");

	// Bind function to change page manually
	this.select = setSelected;

	//Bind events to the buttons
	//Note: The events are 'static' in that the keyword 'this' refers
	//the element that triggered the event, that's why I have passed menu
	//as an argument. There is probably a cleaner way of doing this. 
	this.bindEvents = function(elem){
		this.friendsButton.click(
			function(){
				dhtmlHistory.add('friends','link');
				loadContent("friends/friend_content.jsp");
			}
		);
		this.settingsButton.click(
			function(){
				dhtmlHistory.add('settings','link');
				loadContent("settings/settings_content.jsp");
			}
		);
		
		this.friendsButton.mouseover(
			function(){
				if(currentPage != 'friends'){
					$('#friends_button_table').css("background-position","0px -34px");
				}
			}
		);
		this.settingsButton.mouseover(
			function(){
				if(currentPage != 'settings'){
					$('#settings_button_table').css("background-position","0px -34px");
				}
			}
		);
		
		this.friendsButton.mouseout(
			function(){
				if(currentPage != 'friends'){
					$('#friends_button_table').css("background-position","0px 0px");
				}
			}
		);
		this.settingsButton.mouseout(
			function(){
				if(currentPage != 'settings'){
					$('#settings_button_table').css("background-position","0px 0px");
				}
			}
		);
	}
}