﻿var _tempFormValues;

$(function () {
    $('form.phe-ui-form').autowireForm();
});

$.fn.autowireForm = function () {
    $(this).attr('method', 'post').submit(function () {
        if ($(this).valid()) {
            $(this).trigger('OnFormSubmitting');
            var data = $.toJSON({ FormValues: $(this).serializeObject() });
            var action = $(this).attr("action");
            var returnFunctionCall = $(this).attr("target");
            var $this = $(this);

            $.ajax({
                type: "POST",
                url: "/ws/Ajax/Form.asmx/" + action,
                data: data,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    if (returnFunctionCall) {
                        eval(returnFunctionCall + "(data)");
                    }
                    $this.trigger('OnFormSubmittedSuccess', data);
                },

                error: function (data) {
                    $this.trigger('OnFormSubmittedError', data);
                },
                complete: function (data) {
                    $this.trigger('OnFormSubmittedComplete', data);
                }


            });
        }
        else {
            $(this).trigger('OnFormSubmitCanceled');

        }
        return false;
    });

    // - serializeArray() does not work for divs
    // - maybe someday
    //    $('input:submit', 'div.phe-ui-form').bind('click', function() {
    //        var form = $(this).closest('div.phe-ui-form');
    //        var data = $.toJSON($(form).serializeObject());
    //        alert(data);
    //        return false;
    //    });


    $('.phe-ui-formsubmit', 'form.phe-ui-form').bind('click', function () {
        var form = $(this).parents().filter('form.phe-ui-form');
        if (form) {
            $(form).submit();
        }
        return false;
    });

};



$.fn.serializeFormValues = function () {
    var o = {};
    var params = Array();
    var a = this.serializeArra(y);
    $.each(a, function () {
        var p = {};
        p.Name = this.name;
        p.Value = this.value;
        params.push(p);
    });
    return params;
};

$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

$.fn.populateForm = function (type) {
    var data = $.toJSON({ Form: type });
    var form = $('form[action=' + type + ']');
    if (!(form.hasClass('Populated'))) {
        $.ajax({
            type: "POST",
            url: "/ws/Ajax/Form.asmx/Populate",
            data: data,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                populateForm(data.d, form);
            }
        });
    }
};

function populateForm(data, form) {
    var d = data;
    try {
        for (var key in d) {
            if (d.hasOwnProperty(key)) {
                var $input = $('[name=' + key + ']');
                if ($input.is('select')) {
                    $('option', $input).each(function () {
                        if ($(this).attr('value').toUpperCase() == d[key].toUpperCase()) {
                            $(this).attr('selected', 'selected');
                        }
                    });

                }
                else if ($input.is('input:checkbox')) {
                    $input.val('True');
                    if (!!d[key])
                        $input.attr('checked', 'checked');
                    else
                        $input.removeAttr('checked');


                }
                else {
                    $input.val(d[key]);
                }
                $('span#' + key).text(d[key]);



            }
        }
        form.addClass('Populated');
    }
    catch (err) {
        //Handle errors here
    }
}


//Address Validation

$(function () {
    $('.AddressBox').bind('click', function () {
        $.fancybox.close();
    });
});

function VerifyLevel1(data) {
    $('#MessageBox').text(data.d.Message);
    var form = $('#BillingInfoForm');
    populateForm(data.d.Address, form);
    $('<a href="#MessageBox" id="MessageBoxLink" />').fancybox().click();
}
function VerifyLevel2(data) {
    var a = data.d.Address;
    _tempFormValues = a;
    $('#msg1').html("Is this your address?");
    $('#addr1').html(a.Address1 + "<br/>" + a.City + ", " + a.State + " " + a.ZipCode);
    $('<a href="#AddressConfirmBox" id="MessageBoxLink" />').fancybox().click();
}
function VerifyLevel3(data) {
    $('#MessageBox').text(data.d.Message);
    $('<a href="#MessageBox" id="MessageBoxLink" />').fancybox().click();
}
function VerifyLevel4(data) {
    $('#MessageBox').text(data.d.Message);
    $('<a href="#MessageBox" id="MessageBoxLink" />').fancybox().click()
}
function VerifyLevel5(data) {
    var list = data.d.AddressPicklist;
    var ul = $('#AddressPickBox ul');
    ul.empty();
    $(list).each(function (i) {
        $('<li><input type="radio" value="' + list[i].Moniker + '" name="AddressPicklist" /> ' + list[i].Text + '</li>').appendTo(ul);
    });
    $('<a href="#AddressPickBox" />').fancybox().click();
}
function VerifyLevel0(data) {
    _tempFormValues = data.d.PreviousAddress;
    $('#msg2').html("Address Not Found.");
    $('#addr2').html("Keep this address?");

    $('<a href="#AddressNotFoundBox" id="MessageBoxLink" />').fancybox().click();
}
