// COPYRIGHT (c) 2006 Mixon/Hill, Inc., ALL RIGHTS RESERVED.
//-----------------------------------------------------------
// SubRegistration.js
//      Gathers the registration information from the Subscriber.
//-----------------------------------------------------------

var oSubscriberData;

//-----------------------------------------------------------
// InitPageCode()
//      This is called when the HTML page is loaded.
//      Put all page initializing code here.
//-----------------------------------------------------------
function InitPageCode()
{
    // Retrieve the list of security questions.
    var oXmlRequest = new XmlRequest();
    oXmlRequest.getXml("GetQuestions.jsp", cbQuestionsResponse);
}


function cbQuestionsResponse(oXml)
{
    var oRows = oXml.documentElement.getElementsByTagName("row");
    var oRow;
    var oList = document.getElementById("questionList");

    if (oRows.length != 0)
    {
        ListboxInsertItem(oList, "(No selection)", "");
        for (var i = 0; i < oRows.length; i++)
        {
            oRow = oRows[i];
            ListboxInsertItem(oList, oRow.getAttribute("question"), oRow.getAttribute("id"));
        }
    }
    
    var oUserName = document.getElementById("userName");
    oUserName.focus();
}


//-----------------------------------------------------------
// Register()
//      Extracts the Subscriber's information from the 
//      fields and submits them to the database.
//-----------------------------------------------------------
function Register()
{
    // Disable the Register button so they don't go through this code twice in a row.
    var oButton = document.getElementById("btn_register");
    oButton.disabled = true;

    // Get the email address/username.
    var sUsername = document.getElementById("userName").value;
    if (sUsername == "")
    {
        alert("The Email Address is a required field.\nIt is your username for My KC Scout.");
        document.getElementById("userName").focus();
        oButton.disabled = false;
        return;
    }

    // Make sure the email address is well-formed.
    var sMsg = ValidEmailAddress(sUsername);
    if (sMsg != "")
    {
        alert(sMsg);
        oButton.disabled = false;
        return;
    }
    
    // Make sure this email address isn't already a Subscriber.
    var oXmlRequest = new XmlRequest();
    oXmlRequest.addParameter("email", sUsername);
    oXmlRequest.getXml("SubCheck.jsp", cbCheckResponse);
}


// ValidEmailAddress()
// Note: This function only checks the form of the email address, not its
// actual contents.  It is still possible to submit bogus addresses.
// A well-formed email address will match the following rules:
//      1.  A username before the "@"
//              A) Usernames can contain the following characters: alpahnumeric, dash, underscore, dot
//      2.  An "@"
//      3.  A domain after the "@"
//              A) Domains can contain the following characters: alphanumeric, dash, dot
//              B) Domains must contain at least 1 dot.
function ValidEmailAddress(sEmailAddr)
{
    // Make sure the string is only made up of allowable characters.
    var sDomainChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-.";
    var sUsernameChars = sDomainChars + "_";
    
    // Split the email address at the "@".
    var sPieces = sEmailAddr.split("@");
    
    // Make sure there are 2 (and only 2) pieces, with non-zero lengths.
    if (sPieces.length != 2)
        return ("The email address you entered is not well-formed.");
    
    var sUsername = sPieces[0];
    var sDomain = sPieces[1];
    
    if (sUsername.length == 0 || sDomain.length == 0)
        return("You appear to be missing part of your email address.");
    
    // Make sure all the characters in the username are valid.
    for (var i = 0; i < sUsername.length; i++)
    {
        var ch = sUsername.charAt(i);
        if (sUsernameChars.indexOf(ch) == -1)
        {
            sMsg = "Invalid character in the name portion of your email address: " + ch;
            if (ch == " ")
                sMsg += "(space)";
            return(sMsg);
        }
    }
    
    // Make sure all the characters in the domain are valid.
    for (var i = 0; i < sDomain.length; i++)
    {
        var ch = sDomain.charAt(i);
        if (sDomainChars.indexOf(ch) == -1)
        {
            sMsg = "Invalid character in the domain portion of your email address: " + ch;
            if (ch == " ")
                sMsg += "(space)";
            return(sMsg);
        }
    }
    
    // Make sure there is at least one dot in the domain name.
    if (sDomain.indexOf(".") == -1)
        return("The domain portion of your email address is incorrect.");

    return("");
}

    
function cbCheckResponse(oXml)
{
    var oResult = oXml.documentElement;
    var oRows = oXml.documentElement.getElementsByTagName("row");

    if (oRows.length == 0)
    {
        setTimeout(FinishRegistration, 100);
    }
    else
    {
        alert("The email address you have supplied is already registered as a Subscriber.\n" +
              "If you have forgotten your password, please click on the \"I forgot my password\" link.");
        var oButton = document.getElementById("btn_register");
        oButton.disabled = false;
    }
}

function FinishRegistration()
{
    var oButton = document.getElementById("btn_register");
    oButton.disabled = true;

    // Get the password.
    var sPassword1 = document.getElementById("password").value;
    if (sPassword1 == "")
    {
        alert("Please enter your password.");
        document.getElementById("password").focus();
        oButton.disabled = false;
        return;
    }

    // Get the password confirmation.
    var sPassword2 = document.getElementById("confirmPassword").value;
    if (sPassword2 == "")
    {
        alert("Please confirm your password by entering it a second time.");
        document.getElementById("confirmPassword").focus();
        oButton.disabled = false;
        return;
    }

    // Make sure the two passwords match.
    if (sPassword1 != sPassword2)
    {
        alert("The two passwords do not match.  Please enter your password and confirm it.");
        document.getElementById("password").value = "";
        document.getElementById("confirmPassword").value = "";

        document.getElementById("password").focus();
        oButton.disabled = false;
        return;
    }

    // Get the ZIP Code.
    var sZipCode = document.getElementById("zipCode").value;
    if (sZipCode == "")
    {
        alert("Please enter your home ZIP Code.");
        document.getElementById("zipCode").focus();
        oButton.disabled = false;
        return;
    }

    // Get the secret question.
    var nQuestion = document.getElementById("questionList").value;
    if (nQuestion == "")
    {
        alert("Please select a security question.\n" +
              "The security question will be used in case you forget your password.");
        oButton.disabled = false;
        return;
    }

    // Get the answer to the secret question.
    var sAnswer = document.getElementById("answer").value;
    if (sAnswer == "")
    {
        alert("Please enter the answer to the security question.");
        document.getElementById("answer").focus();
        oButton.disabled = false;
        return;
    }
    
    // Uppercase the answer.
    sAnswer = sAnswer.toUpperCase();

    // Make sure they have agreed to the Service Agreement.
    var nAgreed = document.getElementById("agreed").checked;
    if (!nAgreed)
    {
        alert("You must agree to the terms of the Service Agreement before you can register.");
        oButton.disabled = false;
        return;
    }
    
    // Create the XmlHttpRequest object and send the request to the database
    var oXmlRequest = new XmlRequest();
    oXmlRequest.addParameter("subId", 0);
    oXmlRequest.addParameter("email", document.getElementById("userName").value);
    oXmlRequest.addParameter("password", sha256_digest(sPassword1));
    oXmlRequest.addParameter("zip", sZipCode);
    oXmlRequest.addParameter("question", nQuestion);
    oXmlRequest.addParameter("answer", sha256_digest(sAnswer));
    oXmlRequest.addParameter("agreed", 1);
    oXmlRequest.getXml("SubRegistration.jsp", GetResponse);
}


//-----------------------------------------------------------
// GetResponse()
//      Process the response from the SQL call.
//-----------------------------------------------------------
function GetResponse(oXml)
{
    var oResult = oXml.documentElement;
    var oRows   = oXml.documentElement.getElementsByTagName("row");
    var nRowsAffected = oResult.getAttribute("rowsAffected");

    // Save the subscriber data returned in a global variable.
    oSubscriberData = oRows[0];
        
    //---------------------------------------------------
    // There should only be 1 row returned from the SQL query.
    // Any other number of rows indicates a problem.
    //---------------------------------------------------
    if (nRowsAffected == 0)
    {
        if (window.confirm("Could not create the Subscriber record:\n" + oResult.getAttribute("errMsg") +
                           "\n\nPress OK to send the confirmation email to " + document.getElementById("userName").value + 
                           "\nor press Cancel to re-enter your data."))
        {
            setTimeout(SendConfirmationEmail, 100);
        }
        else
        {
            return;
        }
    }
    else if (nRowsAffected == 1)
    {
        setTimeout(SendConfirmationEmail, 100);
    }
    
    document.getElementById("btn_register").disabled = false;
}


function SendConfirmationEmail()
{
    var oXmlRequest = new XmlRequest();
    oXmlRequest.addParameter("subId", oSubscriberData.getAttribute("id"));
    oXmlRequest.addParameter("email", oSubscriberData.getAttribute("email"));
    oXmlRequest.getXml("SubSendConfEmail.jsp", cbSendEmailResponse);
}


//-----------------------------------------------------------
// cbSendEmailResponse()
//      The call to SubSendConfEmail.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.")
    {
        document.location = "SubRegistrationDone.html";
    }
    else
    {
        alert("There was a problem sending your confirmation email.\n" +
              oResult.getAttribute("errMsg"));
    }
}


