/*
File: textsave.js

Description: Initialize an onbeforeunload-Event in Redmine, if changes in a form are made, but do not ask, if we submit a form

Author: mathias.fischer@berlinonline.de

*/

var TextSave = Class.create({
    observedForms: false,
    observedElements: false,
    changedForms: false,

    initialize: function(){
        this.observedForms = $$('form');
        //Use #main to ignore the Search-Box
        this.observedElements =  $$('#main textarea','#main input','#main select');

        this.observedElements.each(this.observeChange.bind(this));
        this.observedForms.each(this.submitAction.bind(this));

        //Event.stop returns "false", so we cannot use Prototypes Event.observe() here...
        window.onbeforeunload = this.unload.bind(this);
    },

    //Stuff to do before unload, confirm-box is display if a return-value is given
    unload: function(){
        if(this.changedForms)
            return "There are unsaved changes.";
    },

    setChanged: function(){
        this.changedForms = true;
    },

    setUnchanged: function(){
        this.changedForms = false;
    },

    observeChange: function(element){
        element.observe('change',this.setChanged.bindAsEventListener(this));
    },

    submitAction: function(element){
        element.observe('submit',this.setUnchanged.bindAsEventListener(this));
    }

});


document.observe("dom:loaded", function() {
    new TextSave();
});

