
/*
** This method shows the sign in box when someone has clicked the "sign in" button.
** The cursor is moved into the user name text box.
*/
function showSignInWindow()
{
    document.getElementById("signInWindow").innerHTML = "<div class=\"signInBox\">" + 
        "User name <input id=\"userName\" type=\"textbox\" class=\"signInText\"></input> &nbsp; Password " + 
        "<input id=\"password\" type=\"password\" class=\"signInText\"></input>" + 
        "<input type=\"submit\" value=\"Sign in\" onclick=\"signInUser();\"></input><div id=\"error\"></div></div>";
    document.getElementById("userName").select();
}

function showDefaultWindow()
{
        document.getElementById("signInWindow").innerHTML = "<div id=\"signInWindow\" class=\"signInWindow\">" + 
            "To write an update " + 
            "<a href=\"#\" onclick=\"showSignInWindow();\">Sign in</a> or <a href=\"signup.php\">Register</a>" +
            "</div>";
}
/*
** Shows the update form.
*/
function showUpdateForm()
{
    var cookies = document.cookie;
    var cookieName = "wmjUser=";
    var pos = cookies.indexOf(cookieName);
    var value;
    if (pos != -1)
    {
        pos += cookieName.length;
        var end = cookies.indexOf(";", pos);
        if (end == -1)
        {
            end = cookies.length;
        }
        value = cookies.substring(pos, end);
        value = unescape(value);
    }
    var formString = "<form method=\"POST\" action=\"code/addUpdate.php\">" 
    + "<textarea id=\"inputTextArea\" name=\"comment\"> </textarea>" 
    + "<input type=\"hidden\" name=\"userName\"value=\"" + value + "\"/>" 
    + "<div class=\"buttonRight\"><input type=\"submit\" value=\"Update\"/></div></form>";

    document.getElementById("signInWindow").innerHTML = formString;    
}
/*
** Sign in the user with the credentials provided.
** If the sign in process is successful, a cookie is created 
** with the users name, and the text field to write updates is displayed.
*/
function signInUser()
{
    var userName = document.getElementById("userName").value;
    var password = document.getElementById("password").value;
    var xhConn = new XHConn();      
    var queryString = "username=" + userName + "&password=" + password;
	var callFunction = 
		function(xh) 
		{
			var response = xh.responseText;
			if (response == "success")
			{			    
			    var expirationDate = new Date(  );
			    expirationDate.setMonth(expirationDate.getMonth() + 1);	
				document.cookie = "wmjUser=" + userName + ";expires= " + expirationDate.toGMTString();
				location.href="index.php";							
			}
			else
			{
				document.getElementById("error").innerHTML = "<br />Sign in failed.";
			}
		};
	xhConn.connect("code/signInUser.php", "POST", queryString, callFunction);
}

