/**
 * Event handling using the Observer pattern
 * 
 * This code is based loosely on Colin Moock's Ovserver pattern from his
 * EAS2 book.
 * 
 */
var Observable = Class.create();

Observable.prototype = {
	
	changed: false,
	observers: [],
	
	/**
	 * initialize
	 */
	initialize: function(){
		this.observers = [];
	},
	
	/**
	 * addObserver
	 * @param {Object} observer 
	 */
	addObserver: function(observer){
		// don't add a null observer
		if (observer == null) return false;
		
		// don't add an observer more than once
		for (var i=0; i<this.observers.length; i++){
			if (this.observers[i] == observer){
				return false;
			}
		}
		
		// add the observer to our list
		this.observers.push(observer);
		return true;
	},
	
	/**
	 * removeObserver
	 * @param {Object} observer 
	 */
	removeObserver: function(observer){
		for (var i=0; i<this.observers.length; i++){
			if (this.observers[i] == observer){
				this.observers.splice(i,1);
				return true;
			}
		}
		return false
	},
	
	/**
	 * notifyObservers
	 * @param {Object} infoObject 
	 */
	notifyObservers: function(infoObject){
		// use a null infoObject if none is supplied
		if (infoObject == undefined){
			infoObject = null;
		}
		
		// only notify if there has been a change
		if (!this.changed){
			return;
		}
		
		// make a snapshot of the array so that we know it doesn't change during 
		// the course of the loop
		var observersSnapshot = this.observers.slice(0);
		
		// clear our changed value
		this.clearChanged();
		
		// loop through and call update on all of the listeners
		for(var i=0; i<observersSnapshot.length; i++) {
			observersSnapshot[i].update(this, infoObject);
		}
	},
	
	/**
	 * clearObservers
	 */
	clearObservers: function(){
		this.observers = [];
	},
	
	/**
	 * setChanged
	 */
	setChanged: function(){
		this.changed = true;
	},
	
	/**
	 * clearChanged
	 */
	clearChanged: function(){
		this.changed = false;
	},
	
	/**
	 * hasChanged
	 */
	hasChanged: function(){
		return this.changed;
	},
	
	/**
	 * countObservers
	 */
	countObservers: function(){
		return this.observers.length;
	}
}





var Observer = Class.create();

Observer.prototype = {
	
	initialize: function(){
	},
	
	update: function(){
		alert("Observer.update(), please make sure you override me!")
	}
	
}
