/* Code for logging in a user via the login box on the header of every page */

var request_in_progress = false;			// Set this flag when there's a transaction in progress
var animation_timer = null;					// Use this to keep track of the next animation timeout
var animation_delay = 0.1;					// In seconds
var animation_color_counter = 1;			// This will allow us to cycle through the animation colors
var animation_dots = 14;					// How many dots to show for our animations

// These are the colors we cycle through for the "Logging In..." animation
var login_animation_colors = new Array(
	"ffffff",
	"ffcccc",
	"ff9999",
	"ff6666",
	"ff3333",
	"ff0000"
);

// These are URLs that we redirect away from if the user is on them when they log out
var logout_exclusion_pages = new Array(
	"/gold/.*",
	"/pm/.*"
);

// These are URLs that are dynamic, so we need to reload the page, no matter what
var dynamic_paths = new Array(
	"/portal/view",
	"/bbs",
	"/pm"
);

// These are URLs that look dynamic, but we actually DON'T want to reload the page for them
var non_dynamic_paths = new Array(
	"/portal/vote.php",
	"/audio/vote.php"
);

function AttemptLogin()
{
	if(request_in_progress)		// Don't let them kick off simultaneous requests
	{
		return;
	}

	// First check for both fields being filled in
	var username = document.forms["loginboxform"].elements["username"].value;
	var userpass = document.forms["loginboxform"].elements["userpass"].value;
	
	if(username == "")
	{
		alert("Please enter your Grounds Gold username.");
		document.forms["loginboxform"].elements["username"].focus();
		return;
	}
	else if(userpass == "")
	{
		alert("Please enter your Grounds Gold password.");
		document.forms["loginboxform"].elements["userpass"].focus();
		return;
	}
	
	// Note that we're doing a request
	request_in_progress = true;
	
	// OK, if we're here, we've got a username and a pw
	var params = new Array();
	params["u"] = username;
	params["p"] = userpass;
	
	// See if they want to be remembered
	if(document.forms["loginboxform"].elements["remember"].checked)
	{
		params["r"] = 1;
	}
	
	// Swap out our "Login" button to show the "logging in" animation
	DoLoginAnimation("login");
	DivSwap("loginbox_button", "loginbox_animation_login");

	// Now do our HTTP request to see if this guy's valid
	var ajax = new AjaxAgent("/ajax/login.php");
	ajax.Send(params, "HandleLoginResponse");
}

function AttemptLogout()
{
	if(request_in_progress)		// Don't let them kick off simultaneous requests
	{
		return;
	}

	request_in_progress = true;
	
	DoLoginAnimation("logout");
	document.getElementById("loginbox_animation_logout").style.display = "block";
	
	// Do the AJAX - this is a lightweight request
	var ajax = new AjaxAgent("/ajax/logout.php");
	ajax.Send(null, "HandleLogoutResponse");
}

function HandleLoginResponse(http_request)
{
	request_in_progress = false;
	
	if(http_request == null)		// Uh-oh - error!
	{
		alert("We were unable to contact the Newgrounds server.  Please try again.");
		ResetLoginAnimation("login");
		document.forms["loginboxform"].elements["userpass"].value = "";
		return;
	}
	
	// OK, we heard back from the server successfully.  First grab the XML from our request object
	var response_xml = http_request.responseXML.documentElement;
	
	// Check to make sure our XML is in the right format - if not, there are server problems
	var v_arr = response_xml.getElementsByTagName("v");
	if((!(v_arr)) || (v_arr.length != 1) || (!(v_arr[0].firstChild)) || (!(v_arr[0].firstChild.data)) || (v_arr[0].firstChild.data == ""))
	{
		alert("Server error - please try your login again.");
		ResetLoginAnimation("login");
		document.forms["loginboxform"].elements["userpass"].value = "";
		return;
	}
	
	// OK, our response is well-formed.  Let's evaluate the status of the login attempt.
	var login_successful =  response_xml.getElementsByTagName("v")[0].firstChild.data;
	
	if(login_successful == 1)				// Sweet - success!
	{
		// Check to see if we need to reload the page or not - currently, only reload for dynamic pages (PHP)
		if(IsDynamicPage())
		{
			// Let the page refresh take care of changing the loginbox to reflect being logged in
			// Note - refresh it this way, not using .reload(), to get rid of any lingering POST
			window.location.href = window.location.href;

			// Let's return here to keep the "Logging In..." animation running until page refresh occurs
			return;
		}
		else		// Just swap the loginbox around ourselves and stay right here
		{
			// Put their name into the form
			var formatted_username = response_xml.getElementsByTagName("u")[0].firstChild.data;
			SetLoggedInUsername(formatted_username);
			
			// Clear out the password field - it'll be hidden, but you can't be too safe
			document.forms["loginboxform"].elements["userpass"].value = "";
			
			// Now swap in the "logged in" div
			DivSwap("loginbox_notloggedin", "loginbox_loggedin");
		}
	}
	else									// Login failed.  Let's see why.
	{
		var login_errcode = response_xml.getElementsByTagName("e")[0].firstChild.data;
		var errormsg = "";
		
		if(login_errcode == 1)
		{
			errormsg = "No such user \"" + document.forms["loginboxform"].elements["username"].value + "\" is on record in our system.";
		}
		else if(login_errcode == 2)
		{
			errormsg = "Incorrect password.  Please try again.";
		}
		else if(login_errcode == 3)
		{
			errormsg = "This account is not validated.  If you never received the validation e-mail or need to edit your e-mail address, click \"OK\".";
		}
		else if(login_errcode == 4)
		{
			errormsg = "Your account has been locked due to multiple login failures.  E-mail wade@newgrounds.com if you need help.";
		}
		else
		{
			errormsg = "Unknown login error.  Please try again.";
		}
		
		if(login_errcode != 3)
		{
			alert(errormsg);
		}
		else
		{
			if(confirm(errormsg))
			{
				window.location.href = "/gold/amendsignup.php";
			}
		}
		
		document.forms["loginboxform"].elements["userpass"].value = "";
		document.forms["loginboxform"].elements["userpass"].focus();
	}
	
	// End our animation and allow the user to interact again
	ResetLoginAnimation("login");
}

function HandleLogoutResponse(http_request)
{
	request_in_progress = false;

	if(http_request == null)		// Uh-oh - error!
	{
		alert("We were unable to contact the Newgrounds server.  Please try again.");
		ResetLoginAnimation("logout");
		return;
	}

	// Grab the XML DOM from our request object
	var response_xml = http_request.responseXML.documentElement;
	
	// Check to make sure our XML is in the right format - if not, there are server problems
	var v_arr = response_xml.getElementsByTagName("v");
	if((!(v_arr)) || (v_arr.length != 1) || (!(v_arr[0].firstChild)) || (!(v_arr[0].firstChild.data)) || (v_arr[0].firstChild.data == ""))
	{
		alert("Server error - please try your login again.");
		ResetLoginAnimation("logout");
		return;
	}
	
	// OK, if we're here, the logout was successful.	
	if(IsExclusionPage())
	{
		// Redirect to the front page after logging out
		window.location.href = "/";
		return;
	}
	else if(IsDynamicPage())
	{
		// Let the page refresh take care of changing the loginbox to reflect being logged in
		window.location.reload();
		return;
	}
	else
	{
		// Just swap the loginbox around ourselves and stay right here
		DivSwap("loginbox_loggedin", "loginbox_notloggedin");
		ResetLoginAnimation("logout");
	}
}

function IsDynamicPage()
{
	// If it's one of our exclusion pages, then it's not dynamic
	for(var i=0; i<non_dynamic_paths.length; i++)
	{
		if(window.location.pathname.match(non_dynamic_paths[i]))
		{
			return(false);
		}
	}
	
	// Easiest case to check is, does it end in .php/.php3?
	if(window.location.pathname.match(/\.php3?$/))
	{
		return(true);
	}
	
	// Also beware of some places where friendly URLs are actually dynamic.
	for(var i=0; i<dynamic_paths.length; i++)
	{
		if(window.location.pathname.match(dynamic_paths[i]))
		{
			return(true);
		}
	}
	
	// If we're here, then we can assume we're not on a dynamic page.
	return(false);
}

function IsExclusionPage()
{
	for(var i=0; i<logout_exclusion_pages.length; i++)
	{
		if(window.location.pathname.match(logout_exclusion_pages[i]))
		{
			return(true);
		}
	}
	
	return(false);
}

function DoLoginAnimation(animation_type)
{
	var loginmsg_div = document.getElementById("loginbox_animation_" + animation_type);
	var animation_string = loginmsg_div.firstChild.data;
	
	// Loop through and see how many dots we have
	var dot_count = 0;
	for(var i=0; i<animation_string.length; i++)
	{
		if(animation_string.charAt(i) == ".")
		{
			dot_count++;
		}
	}
	
	// See if we need to tack on another dot, or start over
	if(dot_count < animation_dots)
	{
		animation_string += ".";
	}
	else
	{
		animation_string = animation_string.substring(0, animation_string.indexOf("."));
	}
	
	loginmsg_div.firstChild.data = animation_string;
	loginmsg_div.style.color = login_animation_colors[animation_color_counter];
	
	// Also see if we need to start over with our list of animation colors
	if(animation_color_counter == (login_animation_colors.length - 1))
	{
		animation_color_counter = 0;
	}
	else
	{
		animation_color_counter++;
	}
	
	// Call ourselves to keep the animation going
	animation_timer = setTimeout("DoLoginAnimation('" + animation_type + "')", animation_delay * 1000);
}

function ResetLoginAnimation(animation_type)
{
	var loginmsg_div = document.getElementById("loginbox_animation_" + animation_type);
	var animation_string = loginmsg_div.firstChild.data;

	// End the looping animation
	if(animation_timer != null)
	{
		clearTimeout(animation_timer);
	}
		
	// Go through and wipe out any of the dots
	if(animation_string.indexOf(".") >= 0)
	{
		animation_string = animation_string.substring(0, animation_string.indexOf("."));
	}
	
	// Reset the color
	loginmsg_div.style.color = login_animation_colors[0];
	animation_color_counter = 1;
	
	// Cleanup our display to get rid of the animation
	if(animation_type == "login")
	{
		DivSwap("loginbox_animation_login", "loginbox_button");
	}
	else if(animation_type == "logout")
	{
		document.getElementById("loginbox_animation_logout").style.display = "none";
	}
}
