var XMLHTTP=function() {
	var _maximumRequestLength=1500
	var _apiURL='http://calendar.tamu.edu/xmlhttp/'
	this.status=null
	this.statusText=null
	this.responseText=null
	this.responseXML=null
	this.synchronous=false
	this.readyState=0
	this.onreadystatechange=function(){}
	this.onerror=function(){}
	this.onload=function(){}
	this.abort=function() {
		_stop=true
		_destroyScripts()
	}

	this.getResponseHeader=function(name) {
		for(property in _responseHeaders) {
			if(property.toLowerCase()==name.toLowerCase())
				return _responseHeaders[property]
			}
			return null
		}
	
	this.open=function(method,url,sync,userName,password) {
		if(!_checkParameters(method,url)) return
		_method=(method)?method:''
		_url=(url)?url:''
		_userName=(userName)?userName:''
		_password=(password)?password:''
		_setReadyState(1)
	}
	
	this.send=function(data) {
		if(_stop)return
		var src=_createQuery(data)
		_createScript(src)
	}

	var _method=''
	var _url=''
	var _userName=''
	var _password=''
	var _requestHeaders={"HTTP-Referer":escape(document.location),"Content-Type":"application/x-www-form-urlencoded"}
	var _responseHeaders={}
	var _overrideMime=""
	var self=this
	var _id=''
	var _scripts=[]
	var _stop=false
	var _throwError=function(description) {
		self.onerror(description)
		self.abort()
		return false
	}
	var _createQuery=function(data) {
		if(!data)data=''
		var headers=''
		for(property in _requestHeaders)
			headers+=property+'='+_requestHeaders[property]+'&'
			var originalsrc=_method
			+'$'+_id
			+'$'+_userName
			+"$"+_password
			+"$"+headers
			+'$'+_escape(data)
			+'$'+_url
			var src=originalsrc
			var max=_maximumRequestLength,request=[]
			var total=Math.floor(src.length/max),current=0
			while(src.length>0) {
				var query=_apiURL+'?'
				+'multipart'
				+'$'+_id
				+'$'+current++
				+'$'+total
				+'$'+src.substr(0,max)
				request.push(query)
				src=src.substr(max)
			}
			if(request.length==1)
				src=_apiURL+'?'+originalsrc
			else
				src=request
				return src
	}
	
	var _checkParameters=function(method,url) {
		if(!method)
			return _throwError('Please, specify the query method (GET, POST or HEAD)')
		if(!url)
			return _throwError('Please, specify the URL')
		if(method.toLowerCase()!='get'&&method.toLowerCase()!='post'&&method.toLowerCase()!='head')
			return _throwError('Please, specify either a GET, POST or a HEAD method')
		if(url.toLowerCase().substr(0,7)!='http://')
			return _throwError('Only HTTP protocol is supported (http://)')
			return true
	}

	var _createScript=function(src) {
		if('object'==typeof src) {
			for(var i=0;i<src.length;i++)
			_createScript(src[i]);
			return true;
		}
		var script=document.createElement('script');
		script.src=src;
		script.type='text/javascript';
		if(navigator.userAgent.indexOf('Safari')) {
			script.charset='utf-8';
		}
		script=document.getElementsByTagName('head')[0].appendChild(script);
		_scripts.push(script);
		return script;
	}

	var _escape=function(string) {
		string=escape(string)
		string=string.replace('+','%2B')
		return string
	}

	var _destroyScripts=function() {
		for(var i=0;i<_scripts.length;i++)
			if(_scripts[i].parentNode)
			_scripts[i].parentNode.removeChild(_scripts[i])
	}

	var _registerCallback=function() {
		_id='v'+Math.random().toString().substr(2)
		window[_id]=self
	}

	var _setReadyState=function(number) {
		self.readyState=number
		self.onreadystatechange()
		if(number==4)self.onload()
	}

	var _parseXML=function() {
		var type=self.getResponseHeader('Content-type')+_overrideMime
		if(!(type.indexOf('html')>-1||type.indexOf('xml')>-1))return
		if(document.implementation&&document.implementation.createDocument&&navigator.userAgent.indexOf('Opera')==-1) {
			var parser=new DOMParser()
			var xml=parser.parseFromString(self.responseText,"text/xml")
		
			// Prevent the links from using the current domain of the page
			//The first .replace handles the anchor tags that use the " and the second .replace handles the anchor tags that use the '
		
			self.responseText =  self.responseText.replace(/href="\?/g,'href="http://calendar.tamu.edu/?');
			self.responseText =  self.responseText.replace(/href=\'\?/g,'href=\'http://calendar.tamu.edu/?');
		
			self.responseXML=xml
    	} else if(window.ActiveXObject) {            
			var xml=new ActiveXObject('MSXML2.DOMDocument.3.0')  
			// Prevent the links from using the current domain of the page
			self.responseText =  self.responseText.replace(/href="\?/g,'href="http://calendar.tamu.edu/?');    
			self.responseText =  self.responseText.replace(/href=\'\?/g,'href=\'http://calendar.tamu.edu/?');                  
			if(xml.loadXML(self.responseText))
			self.responseXML=xml
		} else {
			var xml=document.body.appendChild(document.createElement('div'))
			// Prevent the links from using the current domain of the page
			self.responseText =  self.responseText.replace(/href="\?/g,'href="http://calendar.tamu.edu/?');    
			self.responseText =  self.responseText.replace(/href=\'\?/g,'href=\'http://calendar.tamu.edu/?');  
			xml.style.display='none'
			xml.innerHTML=self.responseText
			_cleanWhitespace(xml,true)
			self.responseXML=xml.childNodes[0]
			document.body.removeChild(xml)
		}
	}

	var _cleanWhitespace=function(element,deep) {
		var i=element.childNodes.length;
		if(i==0)return
			do {
				var node=element.childNodes[--i]
				if(node.nodeType==3&&!_cleanEmptySymbols(node.nodeValue))
				element.removeChild(node)
				if(node.nodeType==1&&deep)
					_cleanWhitespace(node,true)
			} 
			while(i>0)
	}

	var _cleanEmptySymbols=function(string) {
		string=string.replace('\r','')
		string=string.replace('\n','')
		string=string.replace(' ','')
		return(string.length==0)?false:true
	}

	this._parse=function(object) {
		if(_stop)return true;
		if(object.multipart)return true;
		if(!object.success)
			return _throwError(object.description)
			;_responseHeaders=object.responseHeaders;
			this.status=object.status;
			this.statusText=object.statusText;
			this.responseText=object.responseText;
			_parseXML();
			_destroyScripts();
			_setReadyState(4);
			return true;
	}
	_registerCallback()
}

function fetchURLInto(url,id,err) {
	var xreq=new XMLHTTP();
	xreq.open("GET",url,true);
	xreq.onreadystatechange=function() {
		try {
			if(xreq.readyState==4) {
				if(xreq.status==200) {
					document.getElementById(id).innerHTML=xreq.responseText;
				} else {
					if(undefined==err) {
						document.getElementById(id).innerHTML='Error loading results.';
					} else {
						document.getElementById(id).innerHTML=err;
					}
				}
			}
			xreq=new XMLHTTP();
		}
		catch(e) {
		}
	}
	xreq.send(null);
}

// Helps show the "Today" flag on the small calendar 
function getElementsByClass(node,searchClass,tag){
	var classElements=new Array();
	var els=node.getElementsByTagName(tag);
	var elsLen=els.length;
	var pattern=new RegExp("\\b"+searchClass+"\\b");
	for(i=0,j=0;i<elsLen;i++){
		if(pattern.test(els[i].className)){
			classElements[j]=els[i];j++;
		}
	}
	return classElements;
}

var UNLevent_monthWidget = {
	
	widgetID: 'monthwidget',
	
	init:function(url, widgetID){
		this._ajaxTunnel('GET',url+'/?monthwidget&format=hcalendar','UNLevent_monthWidget._loadWidget');
		this.latestID = '';
		if (widgetID===undefined) {
		UNLevent_monthWidget.widgetID = 'monthwidget';
		} else {
		UNLevent_monthWidget.widgetID = widgetID;
		}
	},
	
	//load the monthly widget
	_loadWidget: function(){		
		var widget_container = document.getElementById(UNLevent_monthWidget.widgetID);
		if (this.readyState == 4) {
			if (this.status == 200) {
				widget_container.innerHTML = this.responseText;
				//yay success! now build the hover tool tip event
				UNLevent_monthWidget._attachHoverEvent(widget_container);
			} else {
				widget_container.innerHTML = 'Error loading results.';
			}
		}
	},
	
	_getCalendarDate: function(t)	{
	   var months = new Array(13);
	   months[0]  = "January";
	   months[1]  = "February";
	   months[2]  = "March";
	   months[3]  = "April";
	   months[4]  = "May";
	   months[5]  = "June";
	   months[6]  = "July";
	   months[7]  = "August";
	   months[8]  = "September";
	   months[9]  = "October";
	   months[10] = "November";
	   months[11] = "December";
	   if(t){
		  var monthname   = months[t];
		  return monthname;
	   }
	   else{
		   var now         = new Date();
		   var monthnumber = now.getMonth();
		   var monthname   = months[monthnumber];
		   var dateString = monthname;
		   return dateString;
	   }
	},

	//generate xmlhttp request
	_ajaxTunnel: function(ajaxType,url,callback){
		var my_calurl = url;			
		var handleReq = new Function('return '+callback);			
		var my_calreq = new XMLHTTP();
		my_calreq.open(ajaxType, my_calurl, true);
		my_calreq.onreadystatechange = handleReq();
		my_calreq.send(null);
	},
	
	//stop event bubbling/propagation
	_stopEvent: function(e){
		if (!e) e = window.event;
		if (e.stopPropagation) {
			e.stopPropagation();
		} else {
			e.cancelBubble = true;
		}
	},
	
	//Primarily shows the "Today" flag
	_attachHoverEvent: function(el){
		var verify1 = getElementsByClass(el, "monthvalue", "span");
		var x = new Date();
		var y = x.getDate();
		//var el = el, previousTimeOut, hoverTime, timeOut;
		var link_container = el.getElementsByTagName('tbody');
		var alink = link_container[0].getElementsByTagName('td');
		var flaggedToday = false;
		for (var i = 0, j = alink.length; i<j; i++){
			var hasEvent = alink[i].getElementsByTagName('a');
			//indicates today icon
			if (flaggedToday == false && verify1[0].id === UNLevent_monthWidget._getCalendarDate() && alink[i].className.indexOf('prev') < 0 && alink[i].className.indexOf('next') < 0) {							
				if (alink[i].innerHTML.indexOf(y) == 0
					|| (hasEvent[0] && hasEvent[0].innerHTML.indexOf(y) == 0) ) {									
					alink[i].className += ' today'
					var imageToday = document.createElement("div");
					imageToday.setAttribute("id","today_image");
					alink[i].appendChild(imageToday);
					flaggedToday = true;
				}
			}
			
		}
		//stupid IE 6 png hack
		if(!window.XMLHttpRequest){
			fnLoadPngs();
		}
	}
	
}
	

