﻿// required fields for validation
var aryRequiredFields = [   { "Name": "First Name", "ID": "FirstName" },
							{ "Name": "Last Name", "ID": "LastName" },
							{ "Name": "Email Address", "ID": "Email" }
						];

var goSubmit = true; // for testing purposes

$(document).ready(function()
{
    $("div.AlertMessage").click(function() { $(this).stop().fadeOut("slow"); });
    $("#btnSubmit").removeAttr("disabled").click(function() { if (Validate()) { Submit(); } else { return false } });
    $("#freeEvaluation").removeAttr("checked").click(function()
    {
        if ($(this).is(":checked"))
            $("#addtlQuestions").slideDown("slow");
        else
            $("#addtlQuestions").slideUp("slow");
    });

    if (document.location.href.indexOf("siteeval=1") >= 0)
    {
        $("#freeEvaluation").attr("checked", "checked");
        $("#addtlQuestions").slideDown("slow");
    }
});

function Validate()
{
    var formValid = true;
    var aryInvalidFields = new Array();

    for (itemIndex in aryRequiredFields)
        if ($.trim($("#" + aryRequiredFields[itemIndex].ID).val()).length == 0)
            aryInvalidFields.push("* " + aryRequiredFields[itemIndex].Name);

    if (aryInvalidFields.length > 0)
        $("div.AlertMessage").stop().html("The following fields are required:<br /><br />" + aryInvalidFields.join("<br />")).fadeIn("slow").fadeTo(6000, 1).fadeOut("slow");
    else
        $("div.AlertMessage").stop().fadeOut(300);

    return !(aryInvalidFields.length > 0);
}

function Submit()
{
    var NewPerson = new Object();
    
    $("#btnSubmit").attr({ "disabled": "disabled", "value": "Sending..." });
    $("input[type=text], textarea, input[type=checkbox], select").each(function() { NewPerson[this.id] = this.value; });

    Dump(JSON.stringify({ "NewPerson": NewPerson }));

    if (goSubmit) // for testing on dev server, bypass the ajax page.
    {
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "Default.aspx/SubmitForm",
            data: JSON.stringify({ "NewPerson": NewPerson }),
            dataType: "json",
            success: function(msg)
            {
                if (msg.d.StatusId > 1)
                    alert(msg.d.StatusMessage);
                else
                    document.location.href="thankYou.html";

            },
            error: function(error) { alert(error); }
        });
    }
    else
        $("#questions").fadeOut(500, function() { $("#thankYou").fadeIn(500); });
}

// remove before going live!!
function Dump(text) { $("div.Dump").append("<div>" + text + "</div>"); }