/*
 * This file contains some JavaScript functions to create some log-in functionalities on hosted websites
 * where server-side scripting is not allowed. It creates a hexadecimal MD5 hash from the enteres password
 * and tries to redirect the page to a 'hidden' subdirectory with the same name as the hash.
 * This method is far from perfect. Ones in the directory someone else can easily copy the path of the
 * from the browser address bar of history. However it makes ir VERY hard for visitors to remember the
 * path by looking over yous shoulder and it's almost impossible to guess a good choosen password.
 * WARNING: NEVER link to pages under the secret directory.
 * 
 * Copyleft Koen Van Hul * Distributed under the GPL License
 * See http://www.gnu.org/licenses/gpl-2.0.html
 */
 
 /*
  * Accompanying HTML code:
  *  
  * <form id="JSLoginForm">
  * <label>Password:</Label>
  * <input type="hidden" name="JSLoginErrMsg" value="Login failed, please try again." />
  * <input type="password" name="JSLoginPassword" />
  * <input type="submit" value="Sign In" onclick="JSLogin_doLogin(event);" />
  * </form>
  * <iframe name="JSLoginFrame" frameborder="0" width="0" height="0" style="display:block;"></iframe>
  *
  */
 
function JSLogin_doLogin(event) {
	try {
		//get md5 hash of password and try to open it as a directory in iframe
		frames['JSLoginFrame'].location.href = hex_md5(document.forms['JSLoginForm'].elements['JSLoginPassword'].value);
	} catch (err) {
		JSLogin_handleLoginFailure();
	}
	
	//check loaded directory in iframe after small timeout
	setTimeout(JSLogin_checkLogin, 128);
	
	//cancel default event action
	if (event.preventDefault) {
		//W3C event implementation supported by Mozilla
		event.preventDefault();
	} else {
		//MSIE method to cancel event
		event.returnValue = false;
	}
	//older browsers
	return false;
}

function JSLogin_checkLogin() {
	try {
		//check if 404 error in title exists
		if (frames['JSLoginFrame'].document.title.search(/404/) >= 0) {
			JSLogin_handleLoginFailure();
		} else {
			//everything seems to be ok, redirect to location loaded in iframe
			location.href = frames['JSLoginFrame'].location.href;
		}
	} catch (err) {
		JSLogin_handleLoginFailure();
	}
}

function JSLogin_handleLoginFailure() {
	//display error message
	alert(document.forms['JSLoginForm'].elements['JSLoginErrMsg'].value);
	//select password text
	document.forms['JSLoginForm'].elements['JSLoginPassword'].select();
}