var UserController = Class.create({
	initialize: function() {
		this.FriendsController = new UserFriendsController();
		
		this.AJAX_LOGIN_PAGE = '/users/login';
		this.AJAX_LOGOUT_PAGE = '/users/logout';
		
		this.busy = false;
		
		// Store the last used username in memory to redisplay it if the password is incorrect
		this.username = '';
		
		this.UserId = '0';
		this.Username = '';
		this.SignedIn = false;
		this.PasswordHelp = false;
		this.PasswordToolTip;
	},
	
	LogIn: function() {
		//One request at a time
		if(this.busy) {
			return;
		}
		
		var username = Trim($F('username'));
		var password = Trim($F('password'));
		
		if(username == '') {
			$('username').focus();
			alert('Please enter your username.');
			return;
		}
		
		this.username = username;
		
		if(password == '') {
			$('password').focus();
			alert('Please enter your password.');
			return;
		}
		
		//Get the parameters from the form
		var params = $('login-form').serialize();
		
		//display the loading animation
		$('login-box').innerHTML = this.LoadingAnimation();
		
		//Make the request
		this.busy = true;
		
		new Ajax.Request(this.AJAX_LOGIN_PAGE,
		{
			method:'post',
			parameters: params,
			onSuccess: function(transport) {
				//The server's part is done
				this.busy = false;
				
				//Parse response
				var response = transport.responseText.evalJSON();
				
				//This user is now a guest
				this.UserId = response.userId;
				this.Username = response.username;
				
				//Display the appropriate html
				$('login-box').innerHTML = response.display;
				
				//See the entered user exists
				if(!response.userExists) {
					$('username').value = this.username;
					$('username').focus();
					alert('The username you entered doesn\'t exist!');
					if(!this.PasswordHelp) {
						this.PasswordToolTip = new Tooltip('login-form', {mouseFollow: false, autoHide: false, customTitle: '<a href="/users/recover/" id="login-trouble">Having trouble?</a>', showArrow: false, borderColor: '#333', offset: {x: -120, y:-6}});
						this.PasswordHelp = true;
					}
					return;
				}
				
				if(!response.correctPassword) {
					$('username').value = this.username;
					$('password').focus();
					alert('The password you entered is incorrect.');
					if(!this.PasswordHelp) {
						this.PasswordToolTip = new Tooltip('login-form', {mouseFollow: false, autoHide: false, customTitle: '<a href="/users/recover/" id="login-trouble">Having trouble?</a>', showArrow: false, borderColor: '#333', offset: {x: -120, y:-6}});
						this.PasswordHelp = true;
					}
					return;
				}
				
				if(this.PasswordHelp) {
					this.PasswordToolTip.hide();
					this.PasswordHelp = false;
				}
				
				this.SignedIn = true;

				//Refresh the window if looking at a user-specific page
				if(is_dynamic_page) {
					window.location = window.location;
				}
				
				// Reload the game so the new user can save their scores
				if(is_scored_game) {
					var doReload = confirm('Since this is a scored game, the game must be reloaded in order to save your scores.  Would you like to do so now?');
				
					if(doReload) {
						// Reload the swf
						eval(loadSWF);
						// Reload the publisher bridge with the new options
						options.userID = CurrentUser.UserId;
						options.username = CurrentUser.Username;
						delete options.denyScores;
						Mochi.addLeaderboardIntegration(options);
					}
				}
			}.bind(this)
		});
	},
	
	LogOut: function() {
		//One request at a time
		if(this.busy) {
			return;
		}
		
		//display the loading animation
		$('login-box').innerHTML = this.LoadingAnimation();
		
		new Ajax.Request(this.AJAX_LOGOUT_PAGE,
		{
			method:'get',
			onSuccess: function(transport) {
				//The server's part is done
				this.busy = false;
				
				//Parse response
				var response = transport.responseText.evalJSON();
				
				//This user is now a guest
				this.UserId = 0;
				
				//Display the appropriate html
				$('login-box').innerHTML = response.display;
				
				//Refresh the window if looking at a user-specific page
				if(is_dynamic_page){
					window.location = window.location;
				}
				
				this.SignedIn = false;
			}.bind(this)
		});
	},
	
	LoadingAnimation: function() {
		return '<div id="loading">Loading...</div>';
	}
});

var UserFriendsController = Class.create({
	initialize: function() {
		this.AJAX_SUBMIT_PAGE = '/friends/';
		
		this.ADD_FRIEND_HTML = '<a href="javascript:CurrentUser.FriendsController.Add();">Add to Friends</a>';
		this.REMOVE_FRIEND_HTML = '<a href="javascript:CurrentUser.FriendsController.Remove();">Remove from Friends</a>';
		
		this.Action = '';
		
		this.busy = false;
	},
	
	GetFriendId: function() {
		return $('user_id').value;
	},
	
	AddByName: function() {
		if(this.busy) {
			return;
		}
		
		var friendUsername = Trim($F('user_id'));
		
		if(friendUsername == '') {
			$('user_id').focus();
			alert('Please enter a username to add as a friend.');
			return;
		}
		
		if(!CurrentUser.SignedIn) {
			alert('You must be signed in to do that.');
			return;
		}
		
		this.Action = 'addbyname';
		this.MakeRequest();
	},
	
	Add: function() {
		if(this.busy){
			return;
		}
		
		if(!CurrentUser.SignedIn) {
			alert('You must be signed in to do that.');
			return;
		}
		
		if(CurrentUser.UserId == this.GetFriendId()){
			alert('You can\'t add yourself as a friend!');
			return;
		}
		
		$('user-control-friend').innerHTML = this.REMOVE_FRIEND_HTML;
		this.Action = 'add';
		this.MakeRequest();
	},
	
	Remove: function() {
		if(this.busy){
			return;
		}
		
		if(!CurrentUser.SignedIn) {
			alert('You must be signed in to do that.');
			return;
		}
		
		if(CurrentUser.UserId == this.GetFriendId()) {
			$('user-control-friend').innerHTML = this.ADD_FRIEND_HTML;
			return;
		}
		
		$('user-control-friend').innerHTML = this.ADD_FRIEND_HTML;
		this.Action = 'remove';
		this.MakeRequest();
	},
	
	MakeRequest: function() {
		if(this.busy){
			return;
		}

		if(!CurrentUser.SignedIn) {
			alert('You must be signed in to do that.');
			return;
		}

		if(this.Action == 'addbyname') {
			if(CurrentUser.Username == this.GetFriendId()) {
				alert('You can\'t add yourself as a friend!');
				return;
			}
		} else {
			if(CurrentUser.UserId == this.GetFriendId()) {
				alert('You can\'t add yourself as a friend!');
				return;
			}
		}

		if (this.Action != 'add' && this.Action != 'remove' && this.Action != 'addbyname'){
			return;
		}
		
		var params = new Array();
		params['data[Friend][friend_id]'] = this.GetFriendId();
		
		this.busy = true;
		
		new Ajax.Request(this.AJAX_SUBMIT_PAGE+this.Action,
		{
			method:'post',
			parameters: params,
			onSuccess: this.HandleResponse.bind(this)
		});
	},
	
	HandleResponse: function(transport) {
		//document.write(transport.responseText);
		if(this.Action != 'addbyname') {
			this.busy = false;
		}
		
		var response = transport.responseText.evalJSON();
		
		/*if(!response.signedIn) {
			alert('You must be signed in to do that.');
			$('user-control-friend').innerHTML = this.ADD_FRIEND_HTML;
			return;
		}*/
		
		/*if(response.isSelf) {
			alert('You can\'t add yourself as a friend!');
			$('user-control-friend').innerHTML = this.ADD_FRIEND_HTML;
			return;
		}*/
		if(this.Action == 'addbyname') {
			if(!response.userExists) {
				alert("That user doesn't exist!");
			}
			
			if(response.alreadyFriends) {
				alert(this.GetFriendId() + " is already your friend.");
			}
			
			window.location = window.location;
		} else {
			//The person is already a friend, so just make them think they added them
			if(response.alreadyFriends) {
				$('user-control-friend').innerHTML = this.REMOVE_FRIEND_HTML;
				return;
			}
		}
	}
});

function Search(){
	var query = $F('search-query');
	
	if(!NumberIsBetween(query.length, 3, 25)){
		alert('Please keep your search between 3 and 25 characters.');
		return;
	}
	
	window.location = "/games/search/"+query+'/';
}