// Hold global event handler functions to add / remove events

// RJR 5-Jun-08
// Extended to handle older browsers that don't implement attachEvent or addEventListener
// Original code by Ismael Jurado (handles the this issue in IE, memory leaks)
// http://www.ismaelj.com/articulos/addevent-recoding-contest/ 

function addEvent( obj, type, fn ) 
{ 
	if(obj){
		if(obj.addEventListener){
			obj.addEventListener( type, fn, false ); 
		}else if ( obj.attachEvent ) { 			
			var ev = type+fn;
			obj['e'+ev] = fn; 
			obj[ev] = function(){obj['e'+ev]( window.event );} 
			obj.attachEvent( 'on'+type, obj[ev] ); 
		}else{
			var ev="on"+type;
			var oldevent = obj[ev];
			if (typeof oldevent != "function"){			
				obj[ev]=fn;
			}else{			
				obj[ev] = function(){ oldevent();fn();}
			}
		}	
	}
}

function removeEvent( obj, type, fn ) { 
	if(obj){  
		if(obj.removeEventListener){
			obj.removeEventListener( type, fn, false ); 
		}else if(obj.detachEvent){
			ShowDebug("detachEvent on on"+type+" " + obj.id + " - " + obj.tagName);
			try{
				obj.detachEvent( 'on'+type, obj[type+fn] ); 
				ShowDebug("now set to null")
				obj[type+fn] = null; 
				ShowDebug("detachedEvent on " + obj.id + " - " + obj.tagName);
			}catch(e){}
		}else{
			var exfunc = obj["on"+type];		
			if(exfunc==fn){		
				obj["on"+type]=null;
			}
		}
	}
} 


function addLoadEvent(func) {	
	ShowDebug("IN addLoadEvent typeof = " + typeof(func) + " - " + func.toString())
	if(window.addEventListener){ //handle dom supported
		window.addEventListener("load",func,false);		
		ShowDebug("addEventListener")
	}else if(window.attachEvent){ //handle IE
		ShowDebug("AttachEvent")
		window.attachEvent("onload",func);
	}else{ // handle older browsers
		var oldonload = window.onload;
		if (typeof window.onload != 'function') {
			ShowDebug("set window.onload")
			window.onload = func;
		}else {
			ShowDebug("create new window.onload function")
			window.onload = function() {
				ShowDebug("RUN OLD");
				oldonload();		
				ShowDebug("RUN NEW")
				func();
			}
		}
	}
}
// use to add an event handler and to also add a remove listener to the window.onunload event so that if you don't manually remove
// the listener it will be removed when the page unloads (mainly for IE for memory leaks)
function addHandlers(obj,evType,func){
	//add event listener
	addEvent(obj,evType,func);
	if(obj!=window && evType!="unload"){
		//add handler to remove event listener on page unload (if not a window unload event itself)
		addEvent(window,"unload",function(e){
				removeEvent(obj,evType,func);
			});
	}
}

var bodyFuncs={};
OnBody = function( func ){
	ShowDebug("IN OnBody " + func);	
	if(typeof(func)!="function") return false;
	if(document.getElementsByTagName("body")[0] || document.body){
		if(bodyFuncs[func]){ return; }//function already loaded with onBody
		func(); //run function
		bodyFuncs[func]=true;//set flag so its not run again
	}else{		
		ShowDebug("body has not loaded yet")
		setTimeout(function(){OnBody(func);},200);
	}
	return
}

/*
Use this function to add multiple or single functions to be fired when the DOM is ready.
This will fire before window.onload fires. If you only want the function to be run once everything
else has loaded then use addWinLoadEvent and not this.
*/
var domLoaded = false;
onDocument = function ( lastFunc ) {	
	//ShowDebug("IN onDocument typeof = " + typeof(lastFunc) + " - " + lastFunc.toString());
	// onDocument.ready allows multiple subscriptions to the onDocument 'event handler' by using nested closures. 		
	onDocument["ready"] = (function (priorFunc){
		return function () {
			onDocument["ready"] = function (){};
			if(domLoaded) return;
			//ShowDebug("DOM Loaded!!");
			domLoaded=true;
			if(!arguments.callee.executed) {
				arguments.callee.executed = true; 
				if (priorFunc) priorFunc(); 
				lastFunc();
			}
		}
	})(onDocument["ready"]);
	
	if(Browser.w3cDOM){
		//ShowDebug("w3cDOM supported")
		if(Browser.jscript){
			try{
				var jsOnStatus = "(function(eScript){if(eScript.readyState==='complete'){eScript.parentNode.removeChild(eScript);onDocument.ready();}})(this)";
				document.write("<script defer src='//:' onreadystatechange=\""+jsOnStatus+"\"></"+"script>");
			}catch(e){
				alert("error loading DOM ready script = " + e.toString() + " - " + lastFunc.toString());
			}
		}else{ //gecko browsers support DOMContentLoaded
			var s=false;
			//handle gecko and new opera
			if(document.addEventListener && (Browser.gecko || (Browser.opera&&parseInt(window.opera.version())>=9)) ){
				ShowDebug("Add event listener DOMContentLoaded")
				document.addEventListener("DOMContentLoaded", function(){onDocument["ready"]}, false);
				s=true;
			}
			//hanlde safari and old opera
			ShowDebug("is it webkit or khtml = " + (Browser.webkit||Browser.khtml) + " or opera under v9");
			if(!s && Browser.webkit||Browser.khtml||(Browser.opera&&parseInt(window.opera.version())<9))(				
				function(){
					ShowDebug("yes do readystate load");
					/loaded|complete/.test(document.readyState) ? onDocument["ready"]() : setTimeout(arguments.callee, 1);
				}
			)(); 				
		}

		//add an onload event so if it fires first we dont bother with the DOM func
		addLoadEvent( function(){if(!domLoaded){ lastFunc(); domLoaded=true;}});
	}else{
		ShowDebug("revert to addWindowLoad event");
		//revert to window onload for older DOMs
		addLoadEvent( lastFunc) ;
	}
};


function CancelEvent(e){
	if(e.preventDefault){
		e.preventDefault();
	}else if(e.returnValue){
		e.returnValue = false;
	}
}
function StopPropagation(e){
	if(e.stopPropagation){
		e.stopPropagation();
	}else if(e.cancelBubble){
		e.cancelBubble = true;
	}
}

function StopEvent(e){
	e=GetEvent(e);//get in case it wasnt passed in
	StopPropagation(e);
	CancelEvent(e);
}

// get correct reference to event object as this=window in IE however when in frames you need the correct window reference
function GetEvent(e,el){
	if(!el) el = this;
	e = e || (((el.ownerDocument || el.document || el).parentWindow || window).event);
	return e;
}

function GetElementFromEvent(e){
	var el;
	if(window.event){
		el = window.event.srcElement;
	}else if(e){
		el = e.target;
	}
	//move up from text node
	if (el.nodeType == 3){
		el= el.parentNode;
	}
	return el;
}
