﻿var _tempFormValues;

$(function () {
    $('form.phe-ui-form').attr('method', 'post').submit(function () {
        if ($(this).valid()) {
            var data2 = $.toJSON({ FormValues: $(this).serializeObject() });
            var data = $(this).serializeObject();
            var action = $(this).attr("action");
            var returnFunctionCall = $(this).attr("target");
            var failFunctionCall = $(this).attr("onfail");
            var $valsum = $('.phe-validation-summary', this);
            var $this = $(this);
            var secure = $(this).attr('secure');

            if (secure == 'true') {
                action = 'https://' + location.hostname + action;
            }

            $.ajax({
                type: "POST",
                url: action,
                data: data,
                traditional: true,
                success: function (response) {
                    if (!response.CallSucceeded) {
                        $valsum.pheValidation('load', response);
                        $('input', $this).eq(0).focus();

                        if (failFunctionCall != undefined) {
                            eval(failFunctionCall + "(response)");
                        }

                        $('body').scrollTop('0')
                    }
                    else {
                        if (response.RedirectUrl != '' && response.RedirectUrl != null) {
                            window.location.href = response.RedirectUrl;
                        }
                        else {
                            eval(returnFunctionCall + "(response)");
                            //$valsum.pheValidation('alert', response.SuccessMessage);
                        }
                    }
                }
            });
        }
        else {
            if ($(this).attr('errorMessage')) {
                $('.phe-validation-summary', this).pheValidation('reset');
                $('.phe-validation-summary', this).pheValidation('alert', $(this).attr('errorMessage'));
            }

            $('html, body').scrollTop('0');
            //            else {
            //                $('.phe-validation-summary', this).pheValidation('alert', 'Please correct the errors below.');
            //            }
        }

        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]) {
            // this if statement below will exclude checkbox so an array is not
            // created during serialization, which messes up mvc model binding
            if ($('#' + this.name + '[type="checkbox"]').length == 0) {
                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
    }
}
