var ajaxContents = new Array(); 
var jsCache = new Array();
var enableCache = true;
var rawAjaxResponse =null; //this is for returning raw ajax requests, which often fail

function addEvent( obj, type, fn ) {
	if (obj.addEventListener) {
		 if (type === 'mouseenter')
			 {obj.addEventListener('mouseover', mouseEnter(fn),false); }
		  else if (type === 'mouseleave')
			 {obj.addEventListener('mouseout', mouseEnter(fn),false); }
		  else {obj.addEventListener( type, fn, false );}
		EventCache.add(obj, type, fn);
	}
	else if (obj.attachEvent) {
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
		EventCache.add(obj, type, fn);
	}
	else {
		obj["on"+type] = obj["e"+type+fn];
	}
}


function mouseEnter(_fn){
   return function(_evt){
      var relTarget = _evt.relatedTarget;
      if (this === relTarget || isAChildOf(this, relTarget))
         { return; }

      _fn.call(this, _evt);
   }
};

function isAChildOf(_parent, _child)
{
   if (_parent === _child) { return false; }
      while (_child && _child !== _parent)
   { _child = _child.parentNode; }

   return _child === _parent;
}

var EventCache = function(){
	var listEvents = [];
	return {
		listEvents : listEvents,
		add : function(node, sEventName, fHandler){
			listEvents.push(arguments);
		},
		flush : function(){
			var i, item;
			for(i = listEvents.length - 1; i >= 0; i = i - 1){
				item = listEvents[i];
				if(item[0].removeEventListener){
					item[0].removeEventListener(item[1], item[2], item[3]);
				};
				if(item[1].substring(0, 2) != "on"){
					item[1] = "on" + item[1];
				};
				if(item[0].detachEvent){
					item[0].detachEvent(item[1], item[2]);
				};
				item[0][item[1]] = null;
			};
		}
	};
}();
addEvent(window,'unload',EventCache.flush);

function ajax_get_contents(type,pathToFile, htmlElement) //types = javascript => eval(), innerHTML => document.getElementById().innerHTML, appendDOM =>appendElement
	{
	 var ajaxIndex = ajaxContents.length;
	  ajaxContents[ajaxIndex] = new sack();
	  ajaxContents[ajaxIndex].requestFile = pathToFile;
	
		if(type=='javascript'){
		  ajaxContents[ajaxIndex].onCompletion = 
		  function(){ ajax_evalJavascript(ajaxIndex,pathToFile); };
		  };
		if(type=='innerHTML'){
		  ajaxContents[ajaxIndex].onCompletion = 
		  function(){ ajax_innerHTML(htmlElement,ajaxIndex,pathToFile); };
		  };
		if(type=='outerHTML'){
		  ajaxContents[ajaxIndex].onCompletion = 
		  function(){ ajax_outerHTML(htmlElement,ajaxIndex,pathToFile); };
		  };
		if(type=='value'){
		  ajaxContents[ajaxIndex].onCompletion = 
		  function(){ ajax_setValue(htmlElement,ajaxIndex,pathToFile); };
		  };
		if(type=='appendDOM'){
		  ajaxContents[ajaxIndex].onCompletion = 
		  function(){ ajax_appendDOM(htmlElement,ajaxIndex,pathToFile); };
		  };
		if(type=='raw'){
		  ajaxContents[ajaxIndex].onCompletion = 
		  function(){ajax_raw(ajaxIndex,pathToFile);};
		  };
	  
	  ajaxContents[ajaxIndex].runAJAX();
	} 
	
	function ajax_raw(ajaxIndex,pathToFile)//sets 
	{
		var text = ajaxContents[ajaxIndex].response;
	  if(enableCache){
		jsCache[pathToFile] = 
		ajaxContents[ajaxIndex].response;
	  }
	  ajaxContents[ajaxIndex] = false;
	   rawAjaxResponse = text;
	}
	
	function ajax_evalJavascript(ajaxIndex,pathToFile)
	{
		rawAjaxResponse=null;
		var text = ajaxContents[ajaxIndex].response;
	  if(enableCache){
		jsCache[pathToFile] = 
		ajaxContents[ajaxIndex].response;
	  }
	  ajaxContents[ajaxIndex] = false;
	  
	  //check if script tags got passed through
	  text.replace(/<script>/i,'');
	  text.replace(/<\/script>/i,'');
	 /*
	 //Make sure it didn't fail because of a login-timeout
	  var patt1=/@_@P@_@/gi;
	  if (text.match(patt1)!=null){//this prevents on security fails
			if (!theObject.id || theObject.id==null){
				theObject.id = random_string();	
			}
			window.run_on_login = "ajax_get_contents('innerHTML','"+pathToFile+"','"+theObject.id+"');";
		}
	  */
	  eval(text);
	}
	
	function ajax_setValue(htmlElement,ajaxIndex,pathToFile)
	{
		if (typeof(htmlElement)=='string') {var theObj = document.getElementById(htmlElement);}
		else {var theObj = htmlElement;}
		var text = ajaxContents[ajaxIndex].response;
	  if(enableCache){
		jsCache[pathToFile] = 
		ajaxContents[ajaxIndex].response;
	  }
	  ajaxContents[ajaxIndex] = false;
	   theObj.value=text;
	}

	function ajax_innerHTML(htmlElement,ajaxIndex,pathToFile)
	{
		var text = ajaxContents[ajaxIndex].response;
		  if(enableCache){
			jsCache[pathToFile] = 
			ajaxContents[ajaxIndex].response;
		  }
		  ajaxContents[ajaxIndex] = false;
		
		if (typeof(htmlElement)=='string') {var theObject = document.getElementById(htmlElement);}
		else {var theObject = htmlElement;}
		
		if(!theObject || theObject==null){
			return false;	
		}
		
		//FIND SECTIONS OF CODE WITH <!--* CODE *--> TO EVALUATE JAVASCRIPT
		//this allows the ajax page to generate both innerHTML and javascript code from the same reply
		var theLeft = (text.lastIndexOf("<!--*"));
		var theRight = (text.lastIndexOf("*-->"));
		if (theLeft == -1){theLeft = -5;}
		var script = text.substring((theLeft +5), theRight);
		var html = (text.substring(0, theLeft + 5) + text.substring(theRight, text.length));
			var patt1=/@_@P@_@/gi;
			if (text.match(patt1)!=null){//this prevents on security fails
				if (!theObject.id || theObject.id==null){
					theObject.id = random_string();	
				}
				window.run_on_login = "ajax_get_contents('innerHTML','"+pathToFile+"','"+theObject.id+"');";
			} else {
				theObject.innerHTML = html;
			}
			eval(script);
	}
	
	function ajax_outerHTML(htmlElement,ajaxIndex,pathToFile)
	{
		//First make sure that the object still exists
		if (typeof(htmlElement)=='string') {var theObject = document.getElementById(htmlElement);}
		else {var theObject = htmlElement;}
		
		var text = ajaxContents[ajaxIndex].response;
		  if(enableCache){
			jsCache[pathToFile] = 
			ajaxContents[ajaxIndex].response;
		  }
		  ajaxContents[ajaxIndex] = false;
		
				
		//FIND SECTIONS OF CODE WITH <!--* CODE *--> TO EVALUATE JAVASCRIPT
		//this allows the ajax page to generate both innerHTML and javascript code from the same reply
		var theLeft = (text.lastIndexOf("<!--*"));
		var theRight = (text.lastIndexOf("*-->"));
		if (theLeft == -1){theLeft = -5;}
		var script = text.substring((theLeft +5), theRight);
		var html = (text.substring(0, theLeft + 5) + text.substring(theRight, text.length));
			var patt1=/@_@P@_@/gi;
			if (text.match(patt1)!=null){//this prevents on security fails
				if (!theObject.id || theObject.id==null){
					theObject.id = random_string();	
				}
				window.run_on_login = "ajax_get_contents('outerHTML','"+pathToFile+"','"+theObject.id+"');";
			} else {
				theObject.outerHTML = html;
			}
			eval(script);
	}
	
	function ajax_appendDOM(htmlElement,ajaxIndex,pathToFile) //similar to innerhtml, but adds content rather than replaces
	{
		var text = ajaxContents[ajaxIndex].response;
		  if(enableCache){
			jsCache[pathToFile] = 
			ajaxContents[ajaxIndex].response;
		  }
		  ajaxContents[ajaxIndex] = false;
				
		//FIND SECTIONS OF CODE WITH <!--* CODE *--> TO EVALUATE JAVASCRIPT
		//this allows the ajax page to generate both innerHTML and javascript code from the same reply
		var theLeft = (text.lastIndexOf("<!--*"));
		var theRight = (text.lastIndexOf("*-->"));
		if (theLeft == -1){theLeft = -5;}
		var script = text.substring((theLeft +5), theRight);
		var theHtml = (text.substring(0, theLeft + 5) + text.substring(theRight, text.length));
				
			if (typeof(htmlElement)=='string') {var theParent = document.getElementById(htmlElement);}
			else {var theParent = htmlElement;}
			if (!theParent){return;};
			var newdiv = document.createElement('span');
			newdiv.innerHTML = theHtml;
			theParent.appendChild(newdiv);
			eval(script);
	}

	function sack(file)
	{
	this.AjaxFailedAlert = "Your browser does not support the enhanced functionality of this website, and therefore you will have an experience that differs from the intended one.\n";
	this.requestFile = file;
	this.method = "POST";
	this.URLString = "";
	this.encodeURIString = true;
	this.execute = false;

	this.onLoading = function() { };
	this.onLoaded = function() { };
	this.onInteractive = function() { };
	this.onCompletion = function() { };

	this.createAJAX = function() {
		/*try {
			this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (err) {*/
				this.xmlhttp = null;
			/*}
		}*/
		if(!this.xmlhttp && typeof XMLHttpRequest != "undefined")
			this.xmlhttp = new XMLHttpRequest();
		if (!this.xmlhttp){
			this.failed = true; 
		}
	};
	
	this.setVar = function(name, value){
		if (this.URLString.length < 3){
			this.URLString = name + "=" + value;
		} else {
			this.URLString += "&" + name + "=" + value;
		}
	}
	
	this.encVar = function(name, value){
		var varString = encodeURIComponent(name) + "=" + encodeURIComponent(value);
	return varString;
	}
	
	this.encodeURLString = function(string){
		varArray = string.split('&');
		for (i = 0; i < varArray.length; i++){
			urlVars = varArray[i].split('=');
			if (urlVars[0].indexOf('amp;') != -1){
				urlVars[0] = urlVars[0].substring(4);
			}
			varArray[i] = this.encVar(urlVars[0],urlVars[1]);
		}
	return varArray.join('&');
	}
	
	this.runResponse = function(){
		eval(this.response);
	}
	
	this.runAJAX = function(urlstring){
		this.responseStatus = new Array(2);
		if(this.failed && this.AjaxFailedAlert){ 
			alert(this.AjaxFailedAlert); 
		} else {
			if (urlstring){ 
				if (this.URLString.length){
					this.URLString = this.URLString + "&" + urlstring; 
				} else {
					this.URLString = urlstring; 
				}
			}
			if (this.encodeURIString){
				var timeval = new Date().getTime(); 
				this.URLString = this.encodeURLString(this.URLString);
				this.setVar("rndval", timeval);
			}
			if (this.element) { this.elementObj = document.getElementById(this.element); }
			if (this.xmlhttp) {
				var self = this;
				if (this.method == "GET") {
					var totalurlstring = this.requestFile + "?" + this.URLString;
					this.xmlhttp.open(this.method, totalurlstring, true);
				} else {
					this.xmlhttp.open(this.method, this.requestFile, true);
				}
				if (this.method == "POST"){
  					try {
						this.xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded')  
					} catch (e) {}
				}

				this.xmlhttp.send(this.URLString);
				this.xmlhttp.onreadystatechange = function() {
					switch (self.xmlhttp.readyState){
						case 1:
							self.onLoading();
						break;
						case 2:
							self.onLoaded();
						break;
						case 3:
							self.onInteractive();
						break;
						case 4:
							self.response = self.xmlhttp.responseText;
							self.responseXML = self.xmlhttp.responseXML;
							self.responseStatus[0] = self.xmlhttp.status;
							self.responseStatus[1] = self.xmlhttp.statusText;
							self.onCompletion();
							if(self.execute){ self.runResponse(); }
							if (self.elementObj) {
								var elemNodeName = self.elementObj.nodeName;
								elemNodeName.toLowerCase();
								if (elemNodeName == "input" || elemNodeName == "select" || elemNodeName == "option" || elemNodeName == "textarea"){
									self.elementObj.value = self.response;
								} else {
									self.elementObj.innerHTML = self.response;
								}
							}
							self.URLString = "";
						break;
					}
				};
			}
		}
	};
this.createAJAX();
}

function get_style(obj,style_property){ //thanks to quirksmode for this one
	if (typeof(obj)=='string'){obj=document.getElementById(obj);};
	if (obj.currentStyle)
		var y = obj.currentStyle[style_property];
	else if (window.getComputedStyle)
		var y = document.defaultView.getComputedStyle(obj,null).getPropertyValue(style_property);
	return y;
}

function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null ) {node = document;}
	if (typeof(node)=='string'){node=document.getElementById(node);}
	if ( tag == null ) {tag = '*';}
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}
