// COPYRIGHT (c) 2006 Mixon/Hill, Inc., ALL RIGHTS RESERVED.
//-----------------------------------------------------------
// SubForgotPassword.js
//      Gets the security question and answer for the given email address
//      from the database.  Presents the question to the user
//      and encrypts the answer given, and then compares it
//      to the answer in the database.  If the answers match,
//      it resets the password and sends an email to the user.
//-----------------------------------------------------------

var sNewPassword = "";

//-----------------------------------------------------------
// InitPageCode()
//      This is called when the HTML page is loaded.
//      Put all page initializing code here.
//-----------------------------------------------------------
function InitPageCode()
{
    var oXmlRequest = new XmlRequest();
    oXmlRequest.getXml("GetSession.jsp", cbGetSessionResponse);
}


function cbGetSessionResponse(oXml)
{
    // This function is empty.
    // It is just here to allow the Xml response to go somewhere.
}


//-----------------------------------------------------------
// Submit()
//      Retrieve the security question and password for a given
//      email address.
//-----------------------------------------------------------
function Submit()
{
    // Make sure the user has entered something into the email field.
    var oEmail = document.getElementById("userName");
    if (oEmail.value == "")
    {
        alert("Please enter your My KC Scout Primary email address.");
        oEmail.focus();
        return;
    }
    
    // Create the XmlHttpRequest object and send the request to the database
    var oXmlRequest = new XmlRequest();
    oXmlRequest.addParameter("email", oEmail.value);
    oXmlRequest.getXml("SubGetUserQuestion.jsp", cbGetSecurityInfo);
}


//-----------------------------------------------------------
// cbGetSecurityInfo()
//      Process the response from the SQL call.
//-----------------------------------------------------------
function cbGetSecurityInfo(oXml)
{
    var oResult = oXml.documentElement;
    var oRows = oXml.documentElement.getElementsByTagName("row");
    var oRow;

    if (oRows.length == 0)
    {
        alert("Could not retrieve the User record for\n" + document.getElementById("userName").value + "\n" +
              "Please make sure you have entered your email address correctly.\n" +
              "If your email address is correct, please contact Kansas City Scout at (816) 622-6500.");
        return;
    }
    else if (oRows.length == 1)
    {
        oRow = oRows[0];
        var sAnswer = window.prompt("Please answer the following security question:\n" + oRow.getAttribute("question"), "");
        if (sAnswer != null && sAnswer != "")
        {
            sAnswer = sha256_digest(sAnswer.toUpperCase());
            if (sAnswer != oRow.getAttribute("answer"))
                alert("Invalid answer.");
            else
            {
                setTimeout(ResetPassword, 100);
            }
        }
    }
}


function ResetPassword()
{
    sNewPassword = MakePassword();

    // Create the XmlHttpRequest object and send the request to the database
    var oXmlRequest = new XmlRequest();
    oXmlRequest.addParameter("email", document.getElementById("userName").value);
    oXmlRequest.addParameter("password", sha256_digest(sNewPassword));
    oXmlRequest.getXml("SubResetPassword.jsp", cbResetPassword);
}


function MakePassword()
{
    // Note: In the letters below, the following letters have been purposefully omitted:
    //          0 ==> the number 'zero'
    //          1 ==> the number 'one'
    //          O ==> the uppercase letter 'owe'
    //          l ==> the lowercase letter 'ell'
    var sLetters = "23456789ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
    var sPassword = "";

    for (var i = 0; i < 8; i++)
        sPassword += sLetters.charAt(Math.floor(Math.random() * sLetters.length))

    return(sPassword);
}


function cbResetPassword(oXml)
{
    var oResult = oXml.documentElement;
    var nRowsAffected = oResult.getAttribute("rowsAffected");
    
    if (nRowsAffected == 1)
    {
        var oXmlRequest = new XmlRequest();
        oXmlRequest.addParameter("email", document.getElementById("userName").value);
        oXmlRequest.addParameter("password", sNewPassword);
        oXmlRequest.getXml("SubSendPWEmail.jsp", cbSendEmailResponse);
    }
    else
    {
        alert("The password could not be reset.");
    }
}


//-----------------------------------------------------------
// cbSendEmailResponse()
//      The call to SubSendPWEmail.jsp doesn't return anything.
//      This is here just to give the XML handler a place to
//      send the response.
//-----------------------------------------------------------
function cbSendEmailResponse(oXml)
{
    var oResult = oXml.documentElement;
    if (oResult.getAttribute("errMsg") == "Message sent.")
    {
        alert("An email containing your new password has been sent to\nyour email address.\n\n" +
              "You will have to change your password the next time you\nlog into My KC Scout.");
        document.location = "SubLogin.html";
    }
    else
    {
        alert("There was a problem sending your Password Reset email:\n" +
              oResult.getAttribute("errMsg"));
    }
}


//-----------------------------------------------------
// returnOnEnter()
//      Makes the ForgotPassword screen work when the user presses enter 
//      on the email address field.
//-----------------------------------------------------
function returnOnEnter(myfield, e)
{
    var key;
    var keychar;

    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;

    // Calls the appropriate function if the user hits enter   
    if (key == 13) 
    {
        setTimeout(Submit, 100);
        return(false);
    }
}

