window.onload = init;

function init()
{
    populateLoginInformation('username', 'password', 'rememberMe');
}

function rememberLoginInformation(usernameID, passwordID, rememberMeID)
{
    //Check to see whether remember me is checked
    if (document.getElementById(rememberMeID).checked)
    {
        //If so, store results in a cookie
        createCookie('username', document.getElementById('username').value, 3650);
        createCookie('password', encrypt(document.getElementById('password').value), 3650);
    }
    else
    {
        eraseCookie('username');
        eraseCookie('password');
    }

    return true;
}

function populateLoginInformation(usernameID, passwordID, rememberMeID)
{
	document.getElementById('username').value = readCookie('username');
    document.getElementById('password').value = decrypt(readCookie('password'));
    
    if (document.getElementById('username').value.length > 0) document.getElementById(rememberMeID).checked = true;
	if(document.getElementById('username').value=='null') {document.getElementById('username').value='';} // correction by SMW
}

function encrypt(to_enc)
{
    if (to_enc == null || to_enc=='') return '';
    
	var xor_key = 6;
	var the_res= ''; //the result will be here
	for(i=0;i<to_enc.length;++i)
	{
		the_res += String.fromCharCode(xor_key^to_enc.charCodeAt(i));
	}
	
	return the_res;
}

function decrypt(to_dec)
{
    if (to_dec == null) return '';
    
    var the_res = '';

	var xor_key = 6;
	
	for(i=0;i<to_dec.length;i++)
	{
		the_res += String.fromCharCode(xor_key^to_dec.charCodeAt(i));
	}
	
	return the_res;
}

function createCookie(name,value,days) 
{
	if (days) 
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) 
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) 
{
	createCookie(name,"",-1);
}