﻿$(document).ready(function () {  
    var catcher = function () {
        var changed = false;
        $('#main form').each(function () {
            if ($(this).data('initialForm') != $(this).serialize()) {
                changed = true;
                $(this).addClass('changed');
            } else {
                $(this).removeClass('changed');
            }
        });
        if (changed) {
            return "Vous n'avez pas enregistré.";
        }
    };

    if (!IsRecensementOrInspection()) return;

    $('#main :input').each(function () {
        $(this).data('initialValue', $(this).serialize());
    }).blur(function () {
        if ($(this).data('initialValue') != $(this).serialize()) {
            $(this).addClass("dirty");
            $(this).closest("form").find("input[type='submit']:not(.no-dirty)").each(function () {
                if (!$(this).hasClass("dirty-submit")) {
                    $(this).addClass("dirty-submit");
                    var pathToImg = $("#hidden-baseurl").val() + "Content/Images/warning_16x13.png";
                    $(this).before("<img alt='Vous n'avez pas enregistré vos modifications!' src='" + pathToImg + "' style='padding-right: 5px;' />")
                }
            });
        }
    })

    $(function () {
        if (!IsRecensementOrInspection()) return;

        $('#main form').each(function () {
            $(this).data('initialForm', $(this).serialize());
        }).submit(function (e) {
            var formEl = this;
            var changed = false;
            $('#main form').each(function () {
                if (this != formEl && $(this).data('initialForm') != $(this).serialize()) {
                    changed = true;
                    $(this).addClass('changed');
                } else {
                    $(this).removeClass('changed');
                }
            });
            if (changed && !jConfirm("Vous n'avez pas enregistré.", "Êtes-vous sûr?")) {
                e.preventDefault();
            } else {
                window.onbeforeunload = null;
            }
        });
        window.onbeforeunload = catcher;
    });
});
