function $(id) { // short hand for getElementById
	return document.getElementById(id);
}

function init() {
	$('register').style.display='none'; // hide the register div
	$('registerlink').style.display='block'; // show the toggle link
}

function toggleRegisterForm() { // toggles register form
	if($('register').style.display=='block') {
		$('register').style.display='none';
		$('login').style.display='block';
		$('registerlink').innerHTML='register';
	} else {
		$('register').style.display='block';
		$('login').style.display='none';
		$('registerlink').innerHTML='login';
	}
}

function hashPass() { // hash the password field from login form
	$('login_pass_md5').value=MD5($('login_password').value); // set the value of the hidden field
	$('login_password').value=''; // clear the password field
}

function hashPasses() { // hash the password fields from register form
	$('register_pass_1_md5').value=MD5($('register_password_1').value);
	$('register_pass_2_md5').value=MD5($('register_password_2').value);
	$('register_password_1').value='';
	$('register_password_2').value='';
}

// declare AJAX request variable
var http_request;

function newHTTPRequest() { // create a new http request
	if (window.XMLHttpRequest) { // create http request for any decent browser...
		return new XMLHttpRequest();
	} else if (window.ActiveXObject) { // ... for Internet Explorer
		try {
			return new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				return new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	// Something went wrong
	if (!http_request) {
		return false;
	}
}

function showErrorMessage(top,text) {
	$('error').style.marginTop=top+'px';	// set the top value
	$('error_content').innerHTML=text;		// set the error text
	$('error').style.display="block";		// and show the error popup
	// start the timer to hide the error popup after two seconds
	helptimer=window.setTimeout("document.getElementById('error').style.display = 'none';",2000);
}

/**** LOGIN *******************************************/
function checkLogin() { // CHECK THE LOGIN
	// check if login username is empty
	if($('login_name').value=="") { // no login name
		showErrorMessage(16,'Please enter a username!'); // and pop the error message
	} else {
		// No error so far? Then let's send the database query via AJAX
		http_request=newHTTPRequest(); // create new AJAX request
		if(!http_request) { // creating new request failed, return true so that form is posted
			return true;
		}
		// This funtion will be called each time the state of the request changes. (like a Windows event handler)
		http_request.onreadystatechange=refreshLoginForm;
		// Open the request
		http_request.open('POST','functions.php',true);
		// tell the server that we are POSTing information
		http_request.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		// Send the request with the POST variables
		http_request.send('action=login&login_name='+$('login_name').value+'&login_pass_md5='+$('login_pass_md5').value);
	}
	return false; // return false to prevent the form from submitting!
}

function refreshLoginForm() { // this is the event handler function for login form AJAX requests
	// check the state of the request ( 0 = not initialised; 1 = loading; 2 = loaded; 3 = interacting; 4 = complete).
	if (http_request.readyState == 4) { // request complete! 
		$('submit_button').value = "Login"; // Set the button text.
		// check the response status - should be 200 (not 404 or 301....)
		if (http_request.status==200) {
			var result=http_request.responseText; // get the response
			switch(result) {
				case '0':
					// all correct, show message
					$('wrapper').innerHTML='<div><form name="logout_form" action="" method="post"><p style="color:#FFFFFF;">Hello '+$('login_name').value+'! You are logged in.</p><p><a href="another_page.php">Another page.</a></p><p><input type="submit" name="submit_logout" value="Log me out" /></p></form></div>';
					break;
				case '3':
					// password incorrect
					showErrorMessage(41,'Password is incorrect!');
					break;
				default:
					// user not found
					showErrorMessage(16,'Username does not exist!');
					break;
			}
		} else { // server error (404, 301)
			alert('Server Error!');
		}
	} else { // not yet ready, show loading
		$('submit_button').value = "Checking..."; // Set the button text.
	}
}
/***************************************************/

/****** REGISTRATION *****************************/
function checkRegistration() {
	// first, some basic checks like empty fields
	if($('register_name').value=="") { // check username
		showErrorMessage(16,'Please enter a username!');
	} else if($('register_pass_1_md5').value!=$('register_pass_2_md5').value) { // check password match
		showErrorMessage(66,'Passwords do not match!');
	} else if(!$('register_email').value.match(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/)) { // check email
		showErrorMessage(91,'Please enter a valid email!');
	} else { // do AJAX
		// No error so far? Then let's send the database query via AJAX
		http_request=newHTTPRequest(); // create new AJAX request
		if(!http_request) { // creating new request failed, return true so that form is posted
			return true;
		}
		// This funtion will be called each time the state of the request changes. (like a Windows event handler)
		http_request.onreadystatechange=refreshRegistrationForm;
		// Open the request
		http_request.open('POST','functions.php',true);
		// tell the server that we are POSTing information
		http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		// Send the request with the POST variables
		http_request.send('action=register&register_name='+$('register_name').value+'&register_pass_1_md5='+$('register_pass_1_md5').value+'&register_pass_2_md5='+$('register_pass_2_md5').value+'&register_email='+$('register_email').value);
	}
	return false; // return false stops the form action!
}

function refreshRegistrationForm() {
	// check the state of the request ( 0 = not initialised; 1 = loading; 2 = loaded; 3 = interacting; 4 = complete).
	if (http_request.readyState==4) { // request complete! 
		$('submit_button2').value="Login"; // Set the button text.
		// check the response status - should be 200 (not 404 or 301....)
		if (http_request.status==200) {
			var result=http_request.responseText; // get the response
			result=result.substring(0,1); // get the first error
			switch(result) {
				case '0':
					// all correct, show message
					$('wrapper').innerHTML='<div><form name="logout_form" action="" method="post"><p style="color:#FFFFFF;">Hello '+$('login_name').value+'! You are logged in.</p><p><a href="another_page.php">Another page.</a></p><p><input type="submit" name="submit_logout" value="Log me out" /></p></form></div>'; window.location.reload( false );
					break;
				case '3':
					// strange error.... usually shouldn't occur....
					$('wrapper').innerHTML='<div><p class="error">'+$('login_name').value+' was registered but could not be logged in! Please try logging in again or contact the site administrator.</p></div>';
					break;
				case '4':
					// user already exists
					showErrorMessage(16,'This username already exists!');
					break;
				case '5':
					// passwords didn't match
					showErrorMessage(66,'Passwords do not match!');
					break;
				case '6':
					// invalid email format
					showErrorMessage(91,'Please enter a valid email!');
					break;
				case '7':
					// database error
					alert('DATABASE ERROR!\nPlease try again or contact the site admin.');
					break;
				default:
					// catch all other errors
					alert('UNKNOWN ERROR!\nPlease try again or contact the site admin.');
					break;
			}
		} else { // server error (404, 301)
			alert('Server Error!');
		}
	} else { // not ready yet.....
		$('submit_button2').value = "Checking..."; // Set the button text.
	}
}
/***************************************************/