/*
   Datei: add_event.js
   Datum: 16.02.2009
   Version: 0.2.0

   Einen Eventaufruf einem Objekt zufügen.

   Folgende Parameter werden Übergeben:
   
   addEvent( obj, event, func);

   obj 		- Das Objekt auf dem der Event stattfindet. [Default: window]
   event 	- Der Event der beobachtet werden soll (ohne 'on') [Default: load]
   function - Eine Funktionsreferenz

   
*/

function addEvent(obj, name, func) {
	// Defaultwerte 
	if(!obj) obj = window;
	if(!name) name = 'load';
	if( typeof func != 'function') throw('no function. usage addEvent( object, name, *function*)');
	
	// Den Eventhandler für das Objekt erzeugen
	if(!obj['on' + name])  obj['on' + name] = EventHandler(name);
	
	/* Event Objekt*/
	function Event(n, obj) {
	var cancel = false;
	var o = obj;
	var evt = {};
	
	this.name = n;
	this.set = function(e) {
		evt = e ||  window.event || {};
		evt.returnValue = true;
		
		var body = window.document.body;
		// Position im Dokument
		this.Y = evt.pageY ? evt.pageY : evt.clientY + body.scrollTop;
		this.X = evt.pageX ? evt.pageX : evt.clientX + body.scrollLeft;
		
		// Position im Browserfenster
		this.clientX = evt.clientX ? evt.clientX : evt.pageX - window.pageXOffset;
		this.clientY = evt.clientY ? evt.clientY : evt.pageY - window.pageYOffset;
		this.type = evt.type;
		
		this.obj = evt.target ? evt.target : evt.srcElement ? evt.srcElement : document.body;
		this.tagName = this.obj.tagName || '[unknown]';

		this.self = this.obj == o;

		cancel = false;
	};
	this.getPos = function() {return [this.X, this.Y]; };

	this.isCancel = function() { return cancel;};
	/* stoppt das "hochblubbern" des events auf übergoerdnete Elemente */
	this.stopPropagation = function() {
		if (evt.stopPropagation) evt.stopPropagation();
		else evt.cancelBubble = true;
		cancel = true;
	};
	/* stoppt den Orginalhandler */
	this.preventDefault = function() {
		if (evt.preventDefault) evt.preventDefault();
		evt.returnResult = false;
		evt.returnValue = false;
	};
	}
	
	function EventHandler(n) {
		var chain = [];
		var o = obj;
		var evt = new Event(n, o);

		var f = function(e) {
			evt.set(e);
			for(var i = 0; i < chain.length; ++i) {
				chain[i].call(o, evt);
				if(evt.isCancel()) break;
			}
			return evt.returnValue;
		}
		;
		f.add = function(f){
			if(typeof f != 'function') throw('not a function');
			
			for(var i = 0; i < chain.length; ++i) {
				if(chain[i].toString() == f.toString()) return null;
			}
			return chain.push(f) - 1;
		};
		
		f.remove = function(idx){	
			if(typeof idx == 'number') return chain.splice(idx, 1);
			
			for(var i = 0; i < chain.length; ++i) {
				if(chain[i] == idx ){
					return chain.splice(i, 1);
					return true;
				}
			}
			return false;
		};
		
		return f;
	}
	
	// Den Event hinzufügen
	return obj['on' + name].add(func);
}
function removeEvent(o, n, f) {
	if(o['on' + n]) o['on' + n].remove(f);
}