var FormChange = (function() {

    var _formChange = function(options) {

        var init = true;

        this.currentKey = "";
        this.form = $("form");

        this.options = $.extend({
            excludedForms: [
                $('form[name$="advanced_search[search]"]'),
                $('form[name$="advancedsearch"]'),
                $('form[name$="admin_search[search]"]'),
                $('form[name$="search')
            ],
            elementsToOffAction: [
                { element: this.form, event: "submit" },
                { element: $('[href="#translate"]'), event: "click" },
                { element: $('[data-behaviour="delete"]'), event: "click" },
                { element: $('[data-action="cancel-form"]'), event: "click" },
                { element: $('#change_content_type_destinationType'), event: "change" }
            ]
        }, options);

        $.each(this.options.excludedForms, function(k,v){
            if (v.length > 0) {
                init = false;
            }
        });

        if (init === true) {
            var _this = this;

            _this.currentKey = _this.generateKey();

            this.bindEvents();

        }
    };

    _formChange.prototype.bindEvents = function() {
        var _this = this;

        $.each(this.options.elementsToOffAction, function(k,v){
            if (v.element.length) {
                v.element.on(v.event, function(){
                    _this.offCheckEvent();
                });
            }
        });

        $(window).on('beforeunload', function(e) {
            if (_this.currentKey !== _this.generateKey()) {
                return Translator.trans("common.messages.form_changes");
            }
        });
    };

    _formChange.prototype.offCheckEvent = function() {
        $(window).off('beforeunload');
    };

    _formChange.prototype.generateKey = function() {

        var formData = this.form.serialize();

        return btoa(formData);
    };

    _formChange.prototype.excludedForms = function() {
        return this.options.excludedForms;
    };

    _formChange.prototype.elementsToOffAction = function() {
        return this.options.elementsToOffAction;
    };

    return {
        init: function(options) {
            return new _formChange(options);
        }
    };
})();
