// JavaScript Document

function submitLoginWithEnter(evt)
{
    evt = (evt) ? evt : event;
    var charCode = (evt.charCode) ? evt.charCode : ((evt.which) ? evt.which : evt.keyCode);
  
    if (charCode == 13) 
	{
		ajaxLoginUser();
		return false;
    }
	
    return true;
}

function get_radio_value(radio)
{
	for (var i = 0; i < radio.length; i++)
	{
		if (radio[i].checked)
		{
			return radio[i].value;
		}
	}
	
	return false;
}

function ajaxLoginUser()
{
	var username = document.getElementById('username').value;
	var password = document.getElementById('password').value;
	var username_regex = /^([a-zA-Z0-9_-]+)$/; 
	var password_regex = /^([a-zA-Z0-9]+)$/;
		
	var data = "username=" + username + "&password=" + password;
	var url = "./register/login.php";
	var error;
	
	if (username == '' || username.length < 6 || !username_regex.test(username))
	{
		error = "Username must be at least 6 alphanumeric characters.";
	}
	else if (password == '' || password.length < 6 || !password_regex.test(password))
	{
		error = "Password must be at least 6 alphanumeric characters.";
	}
	
	if (typeof(error) !== 'undefined')
	{
		showLoginMessage(error);
		return;
	}
	
	showLoginMessage("");
	
	var login_box = document.getElementById('login_box');
	var ajax_login_loading = document.getElementById('ajax-login-loading');
	
	login_box.style.display = 'none';
	ajax_login_loading.style.display = 'block';
	
	new Ajax.Request(
		url, 
		{
			method: 'post', 
			parameters: data, 
			onComplete: function(response) { check_login_status(response); },
			onFailure: 
			function (response)
			{			
				alert("There was a problem logging you in!\n" +
					  "Please try again, or contact us at info@gradedpianorepertoire.com, " + 
					  "providing us your GPR username, and the current date/time of your last login attempt. '"
                );

                // Close Modal Dialog
                $.fancybox.close();
                parent.$.fancybox.close();
			}
		});		
}

function check_login_status(response)
{
	var response_text = response.responseText;
	var successPattern = /^SUCCESS.+$/;
	
	if (200 == response.transport.status)
	{
		if (successPattern.test(response_text))
		{
			var values = response_text.split("|");
			
			userLoggingIn = values[1];
			sessionId = values[2];
				
			// Close Modal Dialog
			$.fancybox.close();
			parent.$.fancybox.close();
		}
		else
		{
			// Show login failure message..
			showLoginMessage(getLanguageMessage(response_text));
		}
				
		var login_box = document.getElementById('login_box');
		var ajax_login_loading = document.getElementById('ajax-login-loading');
		
		login_box.style.display = 'block';
		ajax_login_loading.style.display = 'none';
	}
}

function showLoginMessage(message)
{
	var login_message_div = document.getElementById('login_message_div');
	
	if (login_message_div != null)
	{
		login_message_div.innerHTML = message;
		login_message_div.style.display = 'block';
	}
	else
	{
		alert(message);	
	}
}

function ajaxGetNewCaptcha(element_id)
{
	new Ajax.Request(
		'./generate_captcha.php', 
		{
			method: 'post', 
			onComplete: function(response) { showNewCaptcha(response, element_id); },
			onFailure: 
			function () 
			{			
				alert("There was a problem getting a new captcha image");
			}
		});		
}

function showNewCaptcha(response, element_id)
{
	var response_text = response.responseText;
	var successPattern = /^SUCCESS.+$/;
	
	if (200 == response.transport.status)
	{
		if (successPattern.test(response_text))
		{
			var values = response_text.split("|");
			document.getElementById('hid_conf_code').value = values[1];
			document.getElementById('confirm_id').value = values[2];
			document.getElementById(element_id).innerHTML = values[3];	
		}
		else
		{
			alert("There was a problem getting a new captcha image");
		}		
	}
}

// TODO - closeLoginLogoutBox() is not currently used, as the AJAX updating of the 
// index/home page seems to mess up the fancybox popup sometimes..
function closeLoginLogoutBox(loggingIn, username, session_id)
{
	var topNav = document.getElementById('topNav');
			
	if (loggingIn)
	{
		topNav.innerHTML = "Logged in as: <strong>" + username + 
						   "</strong><a id=\"logout\" href=\"./register/logout.php?sid=" + 
						   session_id + "\" class=\"links\">[ logout ]</a>";
	}
	else
	{
		 topNav.innerHTML = "<a href=\"./index.php?page=register\" class=\"links\" target=\"theFrame\">Register</a>" +
			  "<a id=\"login\" href=\"./register/login_box.html\" class=\"links\">Login</a>";
	}
	
	parent.frames['theFrame'].window.location.reload();	
}

function getLanguageMessage(key)
{
	var please_contact = "If you are continuing to experience an issue, " + 
			"please <a href=\"mailto:info@gradedpianorepertoire.com\">contact us</a>.";
			
	var error_contact = "If you believe this is an error, " + 
			"please <a href=\"mailto:info@gradedpianorepertoire.com\">contact us</a>, and we will attend to the issue immediately.";
	
	switch(key)
	{
		case "LOGIN_ERROR_ATTEMPTS":
			return "You exceeded the maximum allowed number of login attempts. " + 
			   "In addition to your username and password you now also have to solve the CAPTCHA below.";
			   
		case "LOGIN_ERROR_EXTERNAL_AUTH_APACHE":
			return "You have not been authenticated by Apache.";
			   
		case "LOGIN_ERROR_PASSWORD":
			return "You have specified an incorrect password. Please check your password and try again. " + please_contact;
			   
		case "LOGIN_ERROR_PASSWORD_CONVERT":
			return "It was not possible to convert your password when updating this bulletin board�s software. " + 
			   "Please request a new password. " + please_contact;
			   
		case "LOGIN_ERROR_USERNAME":
			return "You have specified an incorrect username. Please check your username and try again. " + please_contact;
			
		case "ACTIVE_ERROR":
			return "Your account is not active. Most likely, your subscription has expired, or your PayPal payment has not yet cleared. " + error_contact;
		
		default:
			return "Unknown message '" + key + "'.";
	}
}

