/**
 * This class watches all elements for the form
 * and so you can catch clicks in from all elements
 * in the links var.
 */
var checkAndSave = Class.create({

    /* Like the constructor */
    initialize: function(){
      
        // form to watch if ! then return
        var form = $$('form')[0];
        if (!form) { 
            return;
        }

        // Set initial variables
        this.hasChanged = false;
        var bindSetChange = this.setChange.bind(this);
        var bindGetChange = this.getChange.bind(this);
        var bindCheckAndSave = this.checkAndSave.bind(this, form);

        // SPECIAL CASE FOR NYO ONLY
        var loc = new String(window.location);
        if (!loc.match(/nyoform/) && !loc.match(/gravity/)) {
            alert('See line circa 24 in checkAndSave.js');
        } else {
            if (loc.match(/section8/) && null != $('isMemberInSection8')) {
                this.setChange();
            }
            if (loc.match(/section4/) && null != $('isComposerInSection4')) {
                this.setChange();
            }

        } // END SPECIAL CASE
        
        // Set the change event for all form elements
        form.getElements().each(function(element) {
            element.observe('change', function() {
                bindSetChange();
            });
        });
        
        // Collect all elements for the on click event
        var links = $$('a[href*="section"]');
        
        // Set the observer on click for links
        links.each(function(item){
            // set observation
            item.observe('click', function() {
                if (bindGetChange()) {
                    var href = this.readAttribute('href');
                    if (!Prototype.Browser.IE) {
                        this.writeAttribute('href', 'Javascript:;');
                    } else {
                        this.writeAttribute('href', '#');
                    }
                    bindCheckAndSave(href);
                }
            });
        });
    },

    checkAndSave: function(form, href) {
        var action = form.readAttribute('action');
        form.writeAttribute('action', action + '?goTo=' + href);
        form.submit();
    },

    setChange: function() {
        this.hasChanged = true;
    },

    getChange: function() {
        return this.hasChanged;
    }
});

document.observe("dom:loaded", function() {
    var NYOCheckAndSave = new checkAndSave();
});
