// Copyright (c) 2006 Jeremy Kitchen (http://scriptkitchen.com/)
//
// See the LICENSE file included with this distribution for full license

// $Id: behaviour.js 87 2006-08-03 19:45:08Z kitchen $
// This is a clone of Ben Nolan's fine behaviour.js for prototype.
// The documentation for behaviour.js at http://bennolan.com/behaviour/
// applies directly to this library.  It *should* be a fully drop-in
// replacement of Ben Nolan's behaviour.js if you have the right version
// of prototype.js.

// If there are any situations where something works in Ben's behaviour.js
// and not (or not as expected) in this, please let me know.

/* the following is not true, yet... it was, but then I realized I was
    using the Selector class wrong */
// I've also enhanced the Behaviour.apply() function to take a base element
// to start from.  prototype's Selector class has this, so it was a trivial
// addition.  Enjoy!

if (!Selector || !Prototype)
    throw("behaviour.js requires prototype r3432 or above");

var Behaviour = {
    register: function(rules) {
        Object.extend(Behaviour._rules, rules);
        if (Behaviour.loaded) {
            Behaviour.apply();
        }
    },
    apply: function() {
        /* can't be as pretty because Hash#_each skips functions :( */
        for (var rule in Behaviour._rules) {
            var func = Behaviour._rules[rule];
            $$(rule).each(function(element) {
                func(element);
            });
        }
    },
    /* do not extend this with Enumerable, or you will break it! */
    _rules:{}
};

Ajax.Responders.register({onComplete: function() { Behaviour.apply() } });

Event.observe(window, 'load', function(ev) {
    Behaviour.loaded = true;
    Behaviour.apply();
});
