function add_game( id )
{
	$.post( "/profile/_add_game/", { game_id: id }, function( data ) 
	{
		if( data.success == true )
		{
			$("#add-game-search").val( "" );
			if( $("#no-games-message" ).is( ":hidden" ) == false )
			{
				$("#no-games-message" ).slideUp();
			}			
			var game = data.game;

			var game_li = $( "<li id=\"game-" + game.game_id + "\" class=\"game\">"
						+ "<div class=\"manage-game-options\">"
						+ "<a class=\"remove-game\" rel=\"remove-game\" game_id=\"" + game.game_id + "\" href=\"/profile/games/remove/" + game.game_id + "\">Remove Game</a>"
						+ "</div>"
						+ "<div class=\"game-pic\"><img src=\"/" + game.game_coverart + "\" /></div>"
						+ "<h3 class=\"game-title\">" + game.game_title + "</h3>"
						+ "<div class=\"game-info\">" + game.platform_abbreviation + " - Released " + game.release_date + "</div>"
					+ "</li>" );

			game_li.prependTo( "#game-list" );
			
			$("a[rel=remove-game]").click( function( e ) {
				e.preventDefault();
				remove_game( $( this ).attr( "game_id" ) );		
			});
		} else if( data.success == false ) { }
	}, "json");
}

function remove_game( id )
{
	$.post( "/profile/_remove_game/", { game_id: id }, function( data ) {
		if( data.success == true )
		{
			$( "#game-" + data.game_id ).slideUp();

			if( $( "#game-list > li.game" ).size() == 1 )
			{
				$( "#no-games-message" ).slideDown();
			}
		} 
		else if( data.success == false ) 
		{
		}
	}, "json");
}
function remove_friend( id )
{
	$.post( "/profile/_remove_friend/", { friend_id: id }, function( data ) {
		if( data.success == true )
		{
			$( "#friend-" + data.friend_id ).slideUp();

			if( $( "#friends-list > li.friend" ).size() == 1 )
			{
				$( "#no-friends-message" ).slideDown();
			}
		} 
		else if( data.success == false ) 
		{
		}
	}, "json");
}

$(function(){

	$("a[rel=remove-friend]").click( function( e ) {
		// Cancel the link behavior
		e.preventDefault();
		remove_friend( $( this ).attr( "friend_id" ) );		
	});

	$( "#ignore-friend-request" ).click( function() {
		var requester_id = $( this ).attr( "rel" );
		$.post( "/profile/_ignore_friend_request/", { requester_id: requester_id }, function( data ) {
			if( data.success == true )
			{
				$( "#request-" + requester_id ).slideUp();
				if( $( "#request-list > li.request" ).size() == 1 )
				{
					$( "#no-requests-message" ).slideDown();
				}
			} 
			else if( data.success == false ) 
			{ 
				alert( "Error occured: " + data.message );
			}
		}, "json");
	});
	$( "#accept-friend-request" ).click( function() {
		var requester_id = $( this ).attr( "rel" );
		$.post( "/profile/_accept_friend_request/", { requester_id: requester_id }, function( data ) {
			if( data.success == true )
			{
				$( "#request-" + requester_id ).slideUp();
				if( $( "#request-list > li.request" ).size() == 1 )
				{
					$( "#no-requests-message" ).slideDown();
				}
			} 
			else if( data.success == false ) 
			{ 
				alert( "Error occured: " + data.message );
			}
		}, "json");
	});
	
	$( "#send-friend-request" ).click( function() {
		$.post( "/profile/_send_friend_request/", 
		{ 
			friend_id: $( "#friend_id" ).val() 
		}, 
		function( data ) 
		{
			if( data.success == true )
			{
				closeModalWindow();
			} 
			else if( data.success == false ) 
			{ 
				alert( "Error occured: " + data.message)
			}
		}, "json");
	});
	
	$( "#submit-suggest-game" ).click( function() {
		var game = {
			title: $( "#suggest-game-title" ).val(),
			platform: $( "#suggest-game-platform" ).val()
		};
		
		if( $( "#suggest-platform-other" ).val() != "" )
		{
			game.platform = $( "#suggest-platform-other" ).val();
		}

		$.post( "/game/_suggest/", game, function( data ) {
			if( data.success == true )
			{
				$( "#suggest-a-game-step1" ).hide();
				$( "#suggest-a-game-step2" ).show();			
			} 
			else if( data.success == false )
			{
				alert( data.message );
			}
		}, "json");
	});

	$( "#but-suggest-game" ).click( function(){
		$( "#suggest-a-game-step1" ).show();
		$( "#suggest-a-game-step2" ).hide();
		$( "#suggest-game-title" ).val( "" );
		$( "#suggest-platform-other" ).val( "" );
		$( "#platform-other" ).hide();	
	});

	$( "#show-platform-other" ).click( function() {
		$( "#platform-other" ).show();	
	});
	
	$("a[rel=remove-game]").click( function( e ) {
		// Cancel the link behavior
		e.preventDefault();
		remove_game( $( this ).attr( "game_id" ) );		
	});
	$("#add-game-search").autocomplete( "/game/_search/", {
		max: 15,
		highlight: false,			
		minChars: 2,
		multiple: false,		
		matchContains: true,
		multipleSeparator: " ",
		scroll: false,
		formatItem: function( row ) 
		{
			return "<a class=\"add-game\"><span>Add</span></a><img class=\"game-pic\" src=\"" + row[2] + "\" /> <small>" + row[3] + "</small> " + "<span title=\"" + row[0] + "\">" + row[0] + "</span>";
		}
	});	
	$("#add-game-search").result(function(event, data, formatted) {
		$("#add-game-search").attr( "game_id", data[1] );
		add_game( data[1] );
	});


	$("#add-game").click( function() {
		add_game( $("#add-game-search").attr( "game_id" ) );
	});
	$("#add-game-search").click( function() {
		$("#add-game-search").select();
	});

	

	$("#message-post").keyup(function() {
		FitToContent(this, document.documentElement.clientHeight);
	});
	$(".message-reply-text").keyup(function() {
		FitToContent(this, document.documentElement.clientHeight);
	});

	$( "#sub-post" ).click( function(){
		var message = {
			message: $( "#message-post" ).val()
		};
		$.post( "/board/_post/", message, function( data ) {
			if( data.success == true ) {
				/*$( "#messages" ).prepend(
					"<li id=\"message-" + data.message.message_id + "\" class=\"hidden\">"
						+ "<div class=\"message-wrap\">"
							+ "<div class=\"profile-pic user-online\"><a href=\"/" + data.message.user_login + "\"><img src=\"" + data.message.avatar + "\" alt=\"\" /></a></div>"
						+ "<div class=\"message\">"
							+ "<a href=\"/" + data.message.user_login + "\" class=\"user\">" + data.message.user_login + "</a>"
							+ "<span class=\"text\">" + data.message.text + "</span>"
							+ "<div class=\"meta\">" + data.message.date + " - <a messageid=\"" + data.message.message_id + "\" id=\"reply-" + data.message.message_id + "\" class=\"message-reply\">Reply</a>"
							+ "</div>"
						+ "</div>"
					+ "</div>"
					+ "<ul class=\"replies\" id=\"replies-" + data.message.message_id + "\">"
						+ "<li class=\"message-reply-wrap\" id=\"reply-" + data.message.message_id + "\">"
							+ "<div class=\"message-reply-box\">"
								+ "<textarea id=\"reply-" + data.message.message_id + "-message\" class=\"message-reply-text\" name=\"message\" cols=\"40\" rows=\"2\"></textarea>"
							+ "</div>"
							+ "<div>"
								+ "<input type=\"button\" class=\"sub-reply\" id=\"sub-reply-" + data.message.message_id + "\" messageid=\"" + data.message.message_id + "\" value=\"Reply\" /> <a messageid=\"" + data.message.message_id + "\" class=\"cancel-reply\" id=\"reply-" + data.message.message_id + "-cancel\">Cancel</a>"
							+ "</div>"
						+ "</li>"
					+ "</ul>" );
					
				$( "#reply-" + data.message.message_id ).click(function() {
					$( "#reply-" + data.message.message_id + "-box" ).slideDown();
				});
				$( "#message-" + data.message.message_id ).slideDown();*/

				window.location.reload();
			} else if( data.success == false ) {
				$( "#post-error" ).show();
				$( "#post-error" ).html( data.error );
			}
		}, "json");
	});

	$( "#user-nav .login" ).attr( "href", "#" );

	$( ".login" ).click( function() 
	{
		if( $( "#login_menu" ).is( ":hidden" ) ) 
		{
			$( this ).addClass( "on" );
			$( "#login_menu" ).show();
		}
		else
		{
			$( this ).removeClass( "on" );
			$( "#login_menu" ).hide();
		}
	} );
	
	$( "#sub-login" ).click( function(){
		var login = {
			username: $( "#login-username" ).val(), 
			password: $( "#login-password" ).val(), 
			remember: $( "#login-remember" ).is(':checked')
		};
		$.post( "ajax/login.php", login, function( data ) {
			if( data.success == true ) {
				window.location.reload();
			} else if( data.success == false ) {
				$( "#login-error" ).show();
				$( "#login-error" ).html( data.error );
			}
		}, "json");
	});

	$( "#logout" ).click( function(){
		$.post( "/ajax/logout.php", null, function( data ) {
			if( data.success == true ) {
				window.location.reload();
			}
		}, "json");
	});

	$( "#sub-register" ).click( function(){
		var register = {
			username: $( "#reg-username" ).val(),
			password: $( "#reg-password" ).val(),
			confirmPassword: $( "#reg-confirm-password" ).val(),
			email: $( "#reg-email" ).val(),
			submit: true
		};
		if( register.username == "" ) {
			$( "#reg-username-error" ).show();
			$( "#reg-username-error" ).html( "Please enter a username" );
			register.submit = false;
		} else {
			$( "#reg-username-error" ).hide();
			$( "#reg-username-error" ).html( "" );
		}
		if( register.password == "" ) {
			$( "#reg-password-error" ).show();
			$( "#reg-password-error" ).html( "Please enter a password" );
			register.submit = false;
		} else {
			$( "#reg-password-error" ).hide();
			$( "#reg-password-error" ).html( "" );
		}
		if( register.confirmPassword == "" ) {
			$( "#reg-confirm-password-error" ).show();
			$( "#reg-confirm-password-error" ).html( "Please confirm your password" );
			register.submit = false;
		} else {
			$( "#reg-confirm-password-error" ).hide();
			$( "#reg-confirm-password-error" ).html( "" );
		}		
		if( register.confirmPassword != "" && register.password != "" && register.password != register.confirmPassword ) {
			$( "#reg-confirm-password-match-error" ).show();
			$( "#reg-confirm-password-match-error" ).html( "Your passwords must match" );
			register.submit = false;
		} else {
			$( "#reg-confirm-password-match-error" ).hide();
			$( "#reg-confirm-password-match-error" ).html( "" );
		}		
		if( register.email == "" ) {
			$( "#reg-email-error" ).show();
			$( "#reg-email-error" ).html( "Please enter an email address" );
			register.submit = false;
		} else {
			$( "#reg-email-error" ).hide();
			$( "#reg-email-error" ).html( "" );
		}
		if( register.submit ) {
			$.post( "/ajax/register/", register, function( data ) {
				if( data.success == true ) {
					window.location.reload();
				} else if( data.success == false ) {
					$( "#reg-error" ).show();
					$( "#reg-error" ).html( data.error );
				}
			}, "json");
		}
	});

	$(".show-more").click(function() {
		$( "#" + $( this ).attr( "messageid" ) + "-preview" ).hide();
		$( "#" + $( this ).attr( "messageid" ) + "-full" ).show();		
	});

	// rep

	$(".expand-replies").click(function() {
		$( "#replies-" + $( this ).attr( "messageid" ) + " li:hidden" ).each( function(){
			$(this).show();
		});
	});
	
	$(".message-reply").click(function() {
		$( "#reply-" + $( this ).attr( "messageid" ) + "-box" ).slideDown();
	});

	$(".cancel-reply").click(function() {
		$( "#reply-" + $( this ).attr( "messageid" ) + "-box" ).slideUp();
	});

	$(".sub-reply").click(function() {
		var reply = {
			messageid: $( this ).attr( "messageid" ),
			message: $( "#reply-" + $( this ).attr( "messageid" ) + "-message").val()
		};

		$.post( "/board/_reply", reply, function( data ) {
			if( data.success == true ) {
				$( "#reply-" + data.reply.message_id + "-message").val( "" );
				window.location.reload();
			} else if( data.success == false ) {
				$( "#reply-error" ).show();
				$( "#reply-error" ).html( data.error );
			}
		}, "json");
	});

	

	$("#profile-avatar" ).mouseover( function() {
		$("#edit-avatar-button").show();
	});
	$("#profile-avatar" ).mouseout( function() {
		$("#edit-avatar-button").hide();
	});

	$("a[rel=modal-window]").click( function( e ) {

		// Cancel the link behavior
		e.preventDefault();
		// Get the A tag
		var id = $(this).attr('href');
	
		//Get the screen height and width
		var maskHeight = $(document).height();
		var maskWidth = $(window).width();
	
		//Set height and width to mask to fill up the whole screen
		$("body").append( $("<div id=\"mask\"></div>" ) );
		$('#mask').css({'width':maskWidth,'height':maskHeight});
		
		//transition effect		
		$('#mask').show();	
		$('#mask').fadeTo("fast",0.6);	
	
		//Get the window height and width
		var winH = $(window).height();
		var winW = $(window).width();
			  
		//Set the popup window to center
		$(id).css('top',  winH/2-$(id).height()/2);
		$(id).css('left', winW/2-$(id).width()/2);
	
		//transition effect
		$(id).show(); 	
	
	});

	$( ".close-modal-window" ).click( function( e ) {
		e.preventDefault();  
		closeModalWindow();
	});
	$( ".cancel-new-avatar" ).click( function( e ) {
		e.preventDefault();  
		closeModalWindow();
		$( "#edit-avatar-upload" ).show();
		$( "#edit-avatar-customize" ).hide();
		$( "#avatar-image").imgAreaSelect({ "hide": true });
	});
	
	$( "#upload-new-avatar-savethumb" ).click( function()
	{
		thumb = {
			"file" : $( "#avatar-image" ).attr( "filename" ),
			"x1" : $("#avatar-thumb").attr( "x1" ),
			"y1" : $("#avatar-thumb").attr( "y1" ),
			"x2" : $("#avatar-thumb").attr( "x2" ),
			"y2" : $("#avatar-thumb").attr( "y2" ),
			"w" : $("#avatar-thumb").attr( "w" ),
			"h" : $("#avatar-thumb").attr( "h" )
		};

		$.post( "/ajax/thumbnail_avatar/", thumb, function( data ) 
		{
			if( data.success == true )
			{				
				$( "#profile-avatar-image" ).attr( "src", "/av/" + data.avatar + "?" + Math.random()*11 );
				closeModalWindow();

				$( "#edit-avatar-upload" ).show();
				$( "#edit-avatar-customize" ).hide();
				$( "#avatar-image").imgAreaSelect({ "hide": true });
			} 
			else if( data.success == false )
			{
				$( "#post-error" ).show();
				$( "#post-error" ).html( data.error );
			}
		}, "json");
	});

	new AjaxUpload('upload-new-avatar',
	{
		action: '/ajax/upload_avatar',
		name: 'avatar',
		data: {},
		autoSubmit: true,
		responseType: "json",
		onChange: function(file, extension){ },
		onSubmit: function(file, extension) {},
		onComplete: function(file, data) 
		{
			if( data.success == false )
			{
				$( "#upload-avatar-error" ).removeClass( "hidden" );
				$( "#upload-avatar-error" ).html( data.error );
			}
			else
			{
				$( "#edit-avatar-upload" ).hide();
				$( "#edit-avatar-customize" ).show();

				$( "#avatar-thumb img" ).attr( "src", data.avatar );
				$( "#avatar-image" ).attr( "src", data.avatar );

				$( "#avatar-image" ).attr( "filename", data.filename );
				
				thumbval = data.height <= data.width ? data.height : data.width;
				$("#avatar-image").imgAreaSelect({ 
					x1: 0, 
					y1: 0, 
					x2: thumbval,
					y2: thumbval, 
					aspectRatio: "1:1", 
					handles: true, 
					//persistent: true,
					onInit: preview, 
					onSelectChange: preview 
				}); 
			}
		}
	});

});

function FitToContent(id, maxHeight)
{
   var text = id && id.style ? id : document.getElementById(id);
   if ( !text )
      return;

   var adjustedHeight = text.clientHeight;
   if ( !maxHeight || maxHeight > adjustedHeight )
   {
      adjustedHeight = Math.max(text.scrollHeight, adjustedHeight);
      if ( maxHeight )
         adjustedHeight = Math.min(maxHeight, adjustedHeight);
      if ( adjustedHeight > text.clientHeight )
         text.style.height = adjustedHeight + "px";
   }
}

function closeModalWindow()
{
	$('#mask, .modal-window').hide();
}

function preview(img, selection)
{			
	var scaleX = 60 / (selection.width || 1); 
	var scaleY = 60 / (selection.height || 1);
	
	$( "#avatar-thumb img" ).css({ 
		width: Math.round(scaleX * $("#avatar-image").attr("width") ) + 'px', 
		height: Math.round(scaleY * $("#avatar-image").attr("height") ) + 'px', 
		marginLeft: '-' + Math.round(scaleX * selection.x1) + 'px', 
		marginTop: '-' + Math.round(scaleY * selection.y1) + 'px' 
	});

	$("#avatar-thumb").attr( "x1", selection.x1);
	$("#avatar-thumb").attr( "y1", selection.y1);
	$("#avatar-thumb").attr( "x2", selection.x2);
	$("#avatar-thumb").attr( "y2", selection.y2);
	$("#avatar-thumb").attr( "w", selection.width);
	$("#avatar-thumb").attr( "h", selection.height);
}