
getPageTemplates();

var countdown;
var count = 9; //Delay will be one second, so start at n-1
var donationContributor = null;

window.onbeforeunload = function () {
    if(countdown != null) clearInterval(countdown);
    count = 9;
}

function callService(url, data, isAsync, onSuccess, beforeSend) {
    var responseData = null;

    $.ajax({
        type: "POST",
        url: url,
        data: JSON.stringify(data),
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        async: isAsync,
        beforeSend: function () {
            if (beforeSend != null) {
                eval(beforeSend + '();');
            }
        },
        success: function (msg) {
            responseData = msg;
            if (onSuccess != null) {
                eval(onSuccess + '(msg);');
            }
        },
        error: function (msg) {
            callService("Service.asmx/LogError", JSON.parse(msg.responseText), false, "showErrorText", null);
        }
    });

    return responseData;
}

function clearText(input, defaultValue) {
    if (input.value == defaultValue) {
        input.value = '';
        input.className = "input";
    }
}

function refreshText(input, defaultValue) {
    if (input.value == '') {
        input.value = defaultValue;
        input.className = "waterMark";
    }
}

function getPageTemplates() {
    var pageTemplates = callService("Service.asmx/GetPageTemplates", { "pageName": "contribute" }, false, null);

    $.each(pageTemplates, function (i, pageTemplate) {
        $.template(pageTemplate.ID, pageTemplate.Body);
    });
}

function clearRequiredFields() {
    $.each($("input[class*='required']"), function (i, v) {
        $(v).removeClass("required");
    });
}

function validateContributorForm() {

    clearRequiredFields();

    var formIsValid = true;
    var invalidControls = new Array();

    var valCount = 0;

    //Validate Required fields
    var regEx = /\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;

    $("#emailAddress")

    if(!regEx.test($("#emailAddress").val())) {
        invalidControls[invalidControls.length] = "emailAddress";
        $("#emailAddress").addClass("required");
    }

    var stateIsValid = callService("Service.asmx/ValidateState", { "state": $("#state").val() }, false, null);
    if (!stateIsValid) {
        invalidControls[invalidControls.length] = "state";
        $("#state").addClass("required");
    }

    switch (controlMode) {
        case "Volunteer": //Validate "Volunteer" options
            if ($("[name='volunteerOptions']:checked").val() == null) {
                invalidControls[invalidControls.length] = "volunteerOptions";
                $(".volunteerOptions").addClass("required");
                alert('Please select at least one group to volunteer for');
            }
            break;
        case "Donation": //Validate Donation info
            var amount = getDonationAmount();

            if (amount == null || amount == "") {
                invalidControls[invalidControls.length] = "donationAmount";
                alert("Please select a donation amount");
            }

            if (amount >= 200) {
                if ($("#occupation").val() == null || $("#occupation").val() == "") {
                    invalidControls[invalidControls.length] = "occupation";
                    $("#occupation").addClass("required");
                }
                if ($("#employerName").val() == null || $("#employerName").val() == "") {
                    invalidControls[invalidControls.length] = "employerName";
                    $("#employerName").addClass("required");
                }
            }

            //Show the user that they are required to fill in the "Other" field
            if ($("[name='donationAmount']:radio:checked").val() == "other" && String.IsNullOrEmpty($("#otherAmount").val())) {
                invalidControls[invalidControls.length] = "otherAmount";
                $("#otherAmount").addClass("required");
            }

            break;
        case "Subcommittee": //Validate Subcommittees
            if ($("[name='subcommittees']:checked").val() == null) {
                invalidControls[invalidControls.length] = "subcommittees";
                alert('Please select at least one subcommittee to volunteer for');
            }
            break;
    }

    if (invalidControls.length > 0) {
        formIsValid = false;
        $("#" + invalidControls[0]).focus();
    }

    return formIsValid;
}

function renderVolunteerPage() {

    var contributor = callService("Service.asmx/GetContributor", {}, false, null);

    $.tmpl("contributeOptionsTemplate", { "Mode": controlMode, "Contributor": contributor }).appendTo("#volunteerOptions");

    switch (controlMode) {
        case "Volunteer":
            break;
        case "Donation":
            $("#creditCardText").css('display', 'block');
            break;
        case "Subcommittees":
            break;
    }

    $("#state").autocomplete({
        source: function (req, add) {

            //pass request to server
            var stateList = callService("Service.asmx/GetState", { "term": req.term }, false, null);

            //pass array to callback  
            add(stateList);
        }
    });

    $('#pageDialog').dialog({ autoOpen: false, modal: true, draggable: false, resizable: false, closeOnEscape: false, width: 400, height: 200 });

}

function showErrorText() {
    $("#pageDialog").dialog('close');
    $('#responseMessage').html("An error occurred while processing your request.  An administrator has been notified.  In the mean time, if you would like to volunteer to contibute manually, please follow the instructions below.");
    $.tmpl("downloadFormTemplate", formLinkData).appendTo('#responseMessage');
    $("#contributeContent").hide();
}

function showDialog() {
    $('#pageDialog').dialog('open');
}

function hideDialog(contributor) {

    $('#pageDialog').dialog('close');

    $('#contributeContent').hide();

    //Show page appropriate messages
    switch (controlMode) {
        case "Volunteer":
        case "Subcommittee":
            //Hide window and show message indicating 
            $('#responseMessage').html("Thank you for volunteering!");

            break;
        case "Donation":
            //Update modal window to let the user know that they will be taken to PayPal for processing
            $('#responseMessage').html($.tmpl("donationRedirectTemplate", {}));
            donationContributor = contributor;
            //Start Timer
            countdown = setInterval(function () {
                $("#countdownDisplay").html(count);
                if (count == 0) {
                    redirect(contributor);
                }
                count--;
            }, 1000);

            break;
    }
}

function redirect(contributor) {

    var redirectURL = "Redirect.asp?ta=" + contributor.DonationAmount + 
        "&fn=" + contributor.FirstName + 
        "&ln=" + contributor.LastName + 
        "&a1=" + contributor.StreetAddress + 
        "&a2=" + contributor.MailingAddress +
        "&c=" + contributor.City +
        "&s=" + contributor.State +
        "&z=" + contributor.PostalCode;

    window.location = redirectURL;
}

function getDonationAmount() {
    return $("[name='donationAmount']:radio:checked").val() == "other" ? $("#otherAmount").val() : $("[name=donationAmount]:radio:checked").val();
}

function saveContributor() {

    $("#pageDialog").html($.tmpl("savingProgressModalTemplate", {}));

    if (validateContributorForm()) {

        var contributor = {
            "ID": 0,
            "FirstName": $("#firstName").val(),
            "LastName": $("#lastName").val(),
            "StreetAddress": $("#streetAddress").val(),
            "MailingAddress": $("#mailingAddress").val(),
            "City": $("#city").val(),
            "State": $("#state").val(),
            "PostalCode": $("#postalCode").val(),
            "EmailAddress": $("#emailAddress").val(),
            "PhoneNumber": $("#phoneNumber").val(),
            "EmployerName": $("#employerName").val(),
            "Occupation": $("#occupation").val(),
            "DonationAmount": getDonationAmount(),
            "VolunteerOptions": new Array(),
            "Subcommittees": new Array()
        }

        $.each($("[name='volunteerOptions']:checked"), function (i, v) {
            contributor.VolunteerOptions[contributor.VolunteerOptions.length] = {
                "Key": v.id.substring(3),
                "Selected": true,
                "Description": $("label[for='" + v.id + "']")[0].innerHTML
            }
        });

        $.each($("[name='subcommittees']:checked"), function (i, v) {
            contributor.Subcommittees[contributor.Subcommittees.length] = { 
                "Id": 0,
                "Name": v.id.substring(3),
                "DisplayText": $("label[for='" + v.id + "']")[0].innerHTML,
                "Enabled": true,
                "Selected": true
            }
        });

        //Save volunteer
        var contributor = callService("Service.asmx/SaveContributor", { "contributor": contributor, "mode": controlMode }, true, "hideDialog", "showDialog");

    }
}

function openDonationWindows(contributor) {
    

     window.open(redirectURL);
 }

String.IsNullOrEmpty = function(value) {
    var isNullOrEmpty = true;
    if (value) {
    if (typeof (value) == 'string') {
        if (value.length > 0)
            isNullOrEmpty = false;
        }
    }
    return isNullOrEmpty;
}

//#region Old Code

//#endregion
