﻿/// <reference path="../Intellisense.js" />

Agility.RegisterNamespace("CleanEating.Modules");

(function () {

    var SubscriptionFooter = CleanEating.Modules.SubscriptionFooter = function (containerID) {
        this._containerID = containerID;
    };

    SubscriptionFooter.prototype._getChild = function (idSuffix) {
        return $("#" + this._containerID + "_" + idSuffix);
    };

    SubscriptionFooter.prototype.init = function () {
        var module = this,
            form = this._getChild("Form"),
            validator = form.validate({
                rules: {
                    country: {required: true}
                }
            });

        this._getChild("SubmitButton").click(function () {
            if (form.valid()) {
                module._submitForm();   
            }
            return false; 
        });
    };

    SubscriptionFooter.prototype._submitForm = function () {
        var module = this,
            formContainer = module._getChild("FormContainer"),
            ajaxLoader = this._getChild("AjaxLoadingContainer");
        
        formContainer.hide();
        ajaxLoader.show();
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            url: Agility.ResolveUrl("~/WebServices/Subscriptions.asmx/Subscribe"),
            data: this._buildFormDataObject(),
            success: function (data) {
                if (data && data.d && data.d.success === true) {
                    var thankYouContainer = module._getChild("ThankYouContainer"),
                        container = $("#" + module._containerID);
                    container.css("min-height", container.height());
                    ajaxLoader.hide();
                    thankYouContainer.show();
                } else {
                    ajaxLoader.hide();
                    formContainer.show();
                }
            }
        });
    };

    SubscriptionFooter.prototype._buildFormDataObject = function () {
        var fields = ["firstName", "lastName", "address", "address2", "city", "stateProvince", "zipPostalCode", "yourEmailAddress"],
            module = this,
            result = {};
        $.each(fields, function(index, field) {
            result[field] = module._getChild(field).val();
        });
        result.country = $("input[name=country]:checked").val();
        result.optIn = this._getChild("optIn").is(":checked");
        return JSON.encode(result);
    };

}());
