/*
	PBehaviour 1.0 June 2009 by Tom Callahan tom at thomascallahan.org
		Requires Prototype (probably any version but originally used 1.6.0.3)
		Rewrite/simplification of Behaviour v1.1 by Ben Nolan, June 2005
		which was in turn based largely on the work of Simon Willison.
     
	Description:
   	
		Uses css selectors to apply javascript behaviours to enable
		unobtrusive javascript in html documents.
		
		Added as part of switch to Prototype:
		
			--functions are now passed the element and the index of that element
			--apply flags each element with a "pbehaviour" attribute as behaviours
			  are applied and does not reapply them (intended to improve speed)
			--apply takes optional parameters:
				force: force reapplication of behaviors even if pbehavior attribute is set
				selectors: array of selectors to reapply (another way to improve speed)
   	
	Usage:   
   
		var myrules = {
			'b.someclass' : function(element,index){
				element.innerHTML='This is link number ' + index;
				element.onclick = function(){
					alert(this.innerHTML);
				}
			},
			'#someid u' : function(element){
				element.onmouseover = function(){
					this.innerHTML = "BLAH!";
				}
			}
		};
	
		Behaviour.register(myrules);
	
		// Call Behaviour.apply() to re-apply the rules (if you
		// update the dom, etc).

	License:
   
		This file is entirely BSD licensed.
   	
	More information:
   	
		http://ripcord.co.nz/behaviour/
   
*/   

var Behaviour = {
	
	list : new Array,
	
	register : function(sheet) {
		for (selector in sheet) {
			Behaviour.list[selector]=sheet[selector];
		}
	},
	
	apply : function(force,selectors) {
		applyList=[];
		for (selector in Behaviour.list){
			$$(selector).each(function(el,ix){
				if (
					(el.readAttribute('pbehaviour')!='applied' || force)
					&&
					(typeof(selectors)!='Array' || selectors.include(selector))
				){
					applyList[selector]=Behaviour.list[selector];
				}
			});
		}
		Behaviour.applyEngine(applyList);
	},
	
	applyEngine : function(inList) {
		for (selector in inList){
			$$(selector).each(function(el,ix){
				inList[selector](el,ix);
				el.writeAttribute('pbehaviour','applied');
			});
		}
	}
}

Event.observe(window,'load',Behaviour.apply);

