var dimmer_div,logger_div,login_form,window_loc,removed_node;

function init()
{
	// prepare the login link
	if (document.getElementById('log-in') !== null)
	{
		var log	= document.getElementById('log-in');			// id of menu link for logging in
		var hel	= window.location;								// get current href of window
		log.onclick = function () { return init_login_form(hel) };
	}
	
	if (document.getElementById('log-out') !== null)		// prepare the logout link
	{
		var log	= document.getElementById('log-out');			// id of menu link for logging in
		log.onclick = function () { return logout() };
	}
	
	window_loc = window.location;
}

function strip_spaces(x) 
{
    while (x.substring(0,1) == ' ') 
    	x = x.substring(1);
    return x;
}

function build_dimmer_div()
{
	dimmer_div 							= document.createElement('div');
	dimmer_div.id						= 'dimmer';
	dimmer_div.setAttribute('name','dimmer');
	dimmer_div.style.display			= 'none';
	document.getElementsByTagName("body")[0].appendChild(dimmer_div);
}

function build_login_div()
{
	logger_div 							= document.createElement('div');
	logger_div.id						= 'logger-div';
	logger_div.setAttribute('name','logger-div');
	logger_div.style.display			= 'none';
	document.getElementById("dimmer").appendChild(logger_div);
}

function hide_form()
{
	if (dimmer_div != undefined || dimmer_div != null)	// define non-defined elements
	{
		dimmer_div.style.display	= 'none';
		logger_div.style.display	= 'none';
	}

}

function build_login_form(href)		// creates the content of the login form
{
	var login_form	= document.createElement('form');		// the form element
	var control_div	= document.createElement('div');		// the div element
	var main_fs		= document.createElement('fieldset');	// the fieldset
	var main_lgn	= document.createElement('legend');		// the legend
	var main_label	= document.createElement('label');
	var main_input	= document.createElement('input');		// submit button / username field / password field
	var main_reset	= document.createElement('input');		// reset button
	var forgot_par	= document.createElement('p');
	var forgot_lnk	= document.createElement('a');
	var main_br		= document.createElement('br');
	
	// build textnodes
	var main_lgn_txt	= document.createTextNode('User Log-in');
	var spacer_text		= document.createTextNode('  ');
	var name_lab_txt	= document.createTextNode('Username:');
	var pass_lab_txt	= document.createTextNode('Password:');
	var forgot_txt		= document.createTextNode('I forgot my password');
	
	// set attributes that can be cloned for other elements
	main_input.setAttribute('type','text');					// set type to 'text' (change for submit & password)
	main_input.setAttribute('size',20);
	main_input.setAttribute('maxlength',20);

	// clone elements
	var password_in = main_input.cloneNode(false);
	var submit_btn	= main_input.cloneNode(false);
	var user_label  = main_label.cloneNode(false);			// username label
	var pass_label	= main_label.cloneNode(false);			// password label
	var br_1		= main_br.cloneNode(false);
	var br_2		= main_br.cloneNode(false);
	var br_3		= main_br.cloneNode(false);
	var br_4		= main_br.cloneNode(false);
	var error_par	= forgot_par.cloneNode(false);
	
	// assemble form
	login_form.setAttribute('id','logger');					// form id
	login_form.setAttribute('name','logger');				// form name
	login_form.setAttribute('method','post');				// form method
	login_form.onsubmit = function() { return validator() };	// form action
	login_form.onreset = hide_form;							// reset action
	main_fs.setAttribute('id','login');						// fieldset id
	login_form.appendChild(main_fs);						// place field as child of form
	main_lgn.setAttribute('id','top-legend');				// legend id
	main_lgn.appendChild(main_lgn_txt);						// legend text as child
	main_fs.appendChild(main_lgn);							// place legend as child of fieldset
	error_par.setAttribute('class','err');
	error_par.setAttribute('id','login-err');				// set error paragraph id
	error_par.style.display = 'none';						// error paragraph does not display initially			
	main_fs.appendChild(error_par);							// place error paragraph as child of fieldset
	user_label.setAttribute('for','lusername');				// username label for -- ** note we use "lusername" to avoid conflicts
	user_label.appendChild(name_lab_txt);					// label text as child
	main_fs.appendChild(user_label);						// username label as child of fieldset
	main_input.setAttribute('name','lusername');			// username input name  -- ** note we use "lusername" to avoid conflicts
	main_input.setAttribute('id','lusername');				// username input id  -- ** note we use "lusername" to avoid conflicts
	main_fs.appendChild(main_input);						// username input as child of fieldset
	main_fs.appendChild(br_1);								// break as child of fieldset
	pass_label.setAttribute('for','password');				// password label for
	pass_label.appendChild(pass_lab_txt);					// label text as child
	main_fs.appendChild(pass_label);						// password label as child of fieldset
	password_in.setAttribute('type','password');			// password type
	password_in.setAttribute('id','password');				// password input id
	password_in.setAttribute('name','password');			// password input name
	main_fs.appendChild(password_in);						// password input as child of fieldset
	main_fs.appendChild(br_2);								// break as child of fieldset
	control_div.setAttribute('id','control-block');			// div id
	main_fs.appendChild(control_div);						// div as child of fieldset
	submit_btn.setAttribute('type','submit');				// submit button type
	submit_btn.setAttribute('name','submit');				// submit button name
	submit_btn.setAttribute('value','Log-In');				// submit button value
	control_div.appendChild(submit_btn);					// submit button as child of div
	control_div.appendChild(spacer_text);					// nonbreaking space as child of div
	main_reset.setAttribute('type','reset');				// reset button type
	main_reset.setAttribute('id','reset');					// reset button id
	main_reset.setAttribute('name','reset');				// reset button name
	main_reset.setAttribute('value','Cancel');				// reset button value
	control_div.appendChild(main_reset);					// reset button as child of div
	control_div.appendChild(br_3);							// break as child of div
	control_div.appendChild(br_4);							// break as child of div
	forgot_lnk.setAttribute('title','Click here if you have forgotten your password');
	forgot_lnk.setAttribute('href','forgot.php');
	forgot_lnk.appendChild(forgot_txt);						// text as child of anchor
	control_div.appendChild(forgot_lnk);					// link as child of div

	return login_form;

}

function init_login_form(href)		// builds requisite divs, fetches form and places it in div
{
	if (dimmer_div === undefined || dimmer_div === null) 	// define non-defined elements
		build_dimmer_div();
				
	if (logger_div === undefined || logger_div === null)
		build_login_div();
	
	if (login_form === undefined || login_form === null)
		login_form = build_login_form(href);	// returns a constructed form
	
	dimmer_div.appendChild(logger_div);			// append logger_div to dimmer
	logger_div.appendChild(login_form);			// append login_form to that div
	
	// show divs (revealing form)
	dimmer_div.style.display			= 'block';
	logger_div.style.display			= 'block';
	
	// focus on username
	document.getElementById('lusername').focus();  //-- ** note we use "lusername" to avoid conflicts
	
	return false;
}


function notify(valid,message)		// valid is true/false
{
	var error_par = document.getElementById('login-err');
	
	error_par.style.display = 'block';
	
	if (valid)
	{
		error_par.style.color	= '#390';
		replace_text(error_par,message);
		return true;
	}
	else
	{
		error_par.style.color	= '#F00';
		replace_text(error_par,message);
		return false;
	}
}
	
function validator(e)
{	

	var p_el	= document.getElementById('password');			// password element
	var u_el	= document.getElementById('lusername');			// username element  -- ** note we use "lusername" to avoid conflicts
	if (strip_spaces(u_el.value) == '')
		return notify(false,'Username field is empty!');
	else if (strip_spaces(p_el.value) == '')
		return notify(false,'Password field is empty!');

	validate_login(u_el.value,p_el.value);		//username,password

	return false;
}

function logout()
{
	logout_user();
	return false;
}

function validate_login(username,password) 
{
	var url = 'login_validator.php?username=' + escape(username) + '&password=' + escape(password); 
	var http = this.http;
	http.open("GET", url, true);
	http.onreadystatechange = function() {
	  if (http.readyState == 4) 
	  {
		var msg_arr = http.responseText.split("*");				// validation msg is comprised of ERR* or OK* with add'l text
		if (msg_arr[0] == 'ERR')
			notify(false,msg_arr[1]);
		else
		{
			notify(true,msg_arr[1]);							// display validation message
			document.getElementsByTagName("body")[0].removeChild(dimmer_div);	// remove form from DOM
			window.location.href = window_loc;					// reload current window (to show new logged-in menu)
		}
	  }
	}
	http.send(null);
}

function logout_user() 
{
	var url = 'login_validator.php?logout';
	var http = this.http;
	http.open("GET", url, true);
	http.onreadystatechange = function() {
	  if (http.readyState == 4) 
	  {
		var msg_arr = http.responseText.split("*");				// validation msg is comprised of ERR* or OK* with add'l text
		if (msg_arr[0] == 'ERR')
			notify(false,msg_arr[1]);
		else
		{
			window.location.href = window_loc;					// reload current window (to show new logged-in menu)
		}
	  }
	}
	http.send(null);
}

function getHTTPObject() 
{
    if (typeof XMLHttpRequest != 'undefined') 
    {
		return new XMLHttpRequest();
    }
    try 
    {
		return new ActiveXObject("Msxml2.XMLHTTP");
    } 
    catch (e) 
    {
        try 
        {
			return new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch (e) {}
    }
    return false;
}


var http = getHTTPObject(); 	// Create the HTTP Object

add_onload(init);				// add init function to onload queue of events
