/*
	Upcoming Chapter Events
	Author:			John W. Hill - jowhill -at- indiana.edu
	Creation Date:	11/30/2007
	Last Updated:	12/07/2007
	
	This script will pull a chapters calendar rss feed, parse it, and then display
	upcoming events for the chapter.
	Before this script is included two javascript variables must be defined:
		chapter, and numEvents
		Example:
			var calendar		= "monroe";
			var numEvents 		= 3;
*/

function myCalendars() {
    this.asr = "367499";
    this.bartholomew = "2650";
    this.birmingham = "2796";
    this.boise = "320575";
    this.boone = "3223";
    this.boston = "2710";
    this.carolina = "1666";
    this.cleveland = "362647";
    this.centralflorida = "375610";
    this.centralillinois = "446027";
    this.indy = "2257";
    this.iowa = "3228";
    this.cass = "339078";
    this.charlotte = "3180";
    this.chicago = "2936";
    this.connecticut = "1734";
    this.dallas = "3153";
	this.daneco = "464287";
    this.denver = "3134";
    this.dc = "496597";
    this.eastIndiana = "2655";
    this.elkhart = "2221";
    this.sunCoast = "3158";
    this.cincinnati = "3038";
    this.evansville = "3163";
    this.greensboro = "2720";
    this.greenvilleSC = "3188";
    this.hilton = "3184";	
    this.howard = "329185";
    this.houston = "2792";
    this.jacksonville = "1873";
    this.johnson = "2959";
    this.kosciusko = "2660";
    this.kokomo = "1543";
    this.lakeshore = "2690";
    this.latino = "2867";
    this.lexington = "1614";
    this.losAngeles = "1466";
    this.louisville = "2705";
    this.madison = "2665";
    this.manasota = "3158";
    this.marshall = "2670";
    this.michigan = "377512";
    this.monroe = "2675";
    this.newYork = "2192";
    this.northeastIndiana = "2685";
    this.orange = "3148";
    this.palmBeach = "2975";
    this.pittsburgh = "339000";
    this.phoenix = "2700";
    this.philadelphia = "333456";
    this.portland = "386899";
	this.sacramento = "464273";
    this.sanAntonio = "3233";
    this.sanDiego = "3219";
    this.seattle = "2680";
    this.southSanFrancisco = "3176";
    this.SanFrancisco = "338759";
    this.southwestFlorida = "362651";
    this.southwestIndiana = "2695";
    this.stJoseph = "496423";
    this.stLouis = "2715";
    this.tampaBay = "2954";
    this.thailand = "2230";
    this.toledo = "2725";
    this.twinCities = "368107";
    this.westCentralIndiana = "2927";
    this.vegas = "377085";
    this.asian = "2271";
    this.nealMarshall = "2285";
    this.glbtaa = "2239";
    this.hollywood = "419553";
    this.latino = "2867";
    this.saa = "492419";
    this.singingHoosiers = "3121";
    this.education = "3046";
    this.iub = "2996";
    this.iupuc = "2090";
    this.iueast = "1837";
    this.ipfw = "1910";
    this.iuk = "1543";
    this.iunw = "1407";
    this.iusb = "2991";
    this.iuse = "3200";
    this.iassociation = "414707";
    this.iassoc = "414707";
    this.austin = "412629";
	this.rhaa = "483250";

}

var myCal = new myCalendars();
// create some variables to use
// var url  			= "/inc/events/getCalendarFeed.php?calendar=" + calendar;
var url = "/inc/events/" + myCal[calendar] + ".xml";
var eventsDiv		= $( 'events' );
var calendarLink	= $( 'calendarLink' );
var titles			= [];
var links			= [];
var descriptions	= [];
var month			= new Array( 12 );
month[0]			= "Jan";
month[1]			= "Feb";
month[2]			= "Mar";
month[3]			= "Apr";
month[4]			= "May";
month[5]			= "Jun";
month[6]			= "Jul";
month[7]			= "Aug";
month[8]			= "Sep";
month[9]			= "Oct";
month[10]			= "Nov";
month[11]			= "Dec";

var feedDate		= new Date();
var feedYear		= feedDate.getFullYear();
var feedMonth		= feedDate.getMonth() + 1;
var feedDay			= feedDate.getDate();

var calID			= calendarLink.getAttribute( 'href' ).toQueryParams([seperator = ';'])["calID"];

var feedURL			= "http://events.iu.edu/webevent.cgi?cmd=rss_export;calID=";
feedURL				+= calID + ";days=180";

//Add the RSS Feed link within the Calendar
title = eventsDiv.select('h2')[0];
title.insert( {before: "<a id=\"eventsWidgetRSSIcon\" href=\"" + feedURL + "\" title=\"Subscribe to the upcoming events RSS feed\"><img src=\"/img/rss.gif\" alt=\"RSS\" /></a>"} );



// some HTML for the loading image
var loadingBoxHTML	= "<div id=\"loading_box\" style=\"margin:5px 55px 5px 55px; display:none;\">";
loadingBoxHTML	   += "<img src=\"/img/icons/loading.gif\" alt=\"Loading Image\" />";
loadingBoxHTML	   += "</div>";

calendarLink.insert( {before: loadingBoxHTML} ); // add the loading image div just above the full calendar link
var loadingBox		= $( 'loading_box' ); // grab it for later use

// pass the calendar variable over to a php script, URL, which retrieves the feed.
new Ajax.Request( url,
	{
		method:'get',
		onLoading: function() { loadingBox.show(); }, // while loading the feed, show the loading box
		// upon succesfull load of the feed, send it to the parser
		onSuccess: function(transport) { checkValidResponse( transport.responseText ); },
		// if there is an error getting the feed, show an error message
		onFailure: function() { sendFeedError(); } 
	});

function checkValidResponse( xmlText )
{
	if( xmlText )
	{
		eventsFeedParser( xmlText );
	}
	else
	{
		sendFeedError();
	}
}



// sendFeedError takes no arguments, it calls a PHP mailer script and sends out an error message
// to the webteam staff. It informs the user of the error and of the error email status (sent or not sent)
function sendFeedError()
{
	//Special debug info
	var x = navigator;
    
	var output = "";
    output += "|CodeName-" + x.appCodeName;
    output += "|MinorVersion-" + x.appMinorVersion;
    output += "|Name-" + x.appName;
    output += "|Version-" + x.appVersion;
    output += "|CookieEnabled-" + x.cookieEnabled;
    output += "|CPUClass-" + x.cpuClass;
    output += "|OnLine-" + x.onLine;
    output += "|Platform-" + x.platform;
    output += "|UA-" + x.userAgent;
    output += "|BrowserLanguage-" + x.browserLanguage;
    output += "|SystemLanguage-" + x.systemLanguage;
    output += "|UserLanguage-" + x.userLanguage;
	
	
	var errorMailer = "/inc/events/mailer.php?type=feed&calendar=" + calendar + "&page=" + document.location.href + "&debug=" + output;
		//location.href=errorMailer;
	new Ajax.Request( errorMailer,
	{
		// this function merely calls a PHP script, it returns nothing (it's a no op)
		method:'get',
		onSuccess: function() 
			{
				var errorMessage = "Events could not be loaded, please check the calendar. Our staff has been informed";
				printEventError( errorMessage, "exclamation.png" ); 
			},
		onFailure: function() 
			{
				var errorMessage = "Events could not be loaded, please check the calendar. ";
				errorMessage    += "Additionally there was an error informing our staff to the problem.";
				printEventError( errorMessage, "exclamation.png" ); 
			} 
	});
}

// load the xml (comes as a string) into an actual xml document, browser side
// then parse out the events and show the upcoming events,
// print any errors if they occur
function eventsFeedParser( xmlText )
{
	var xmlDoc			= parseXMLFromString( xmlText ); // load the xml string into an xml document
	var events			= xmlDoc.getElementsByTagName( "item" ); // get all of the events, called item(s)
	var maxEvents		= Math.min( numEvents, events.length ); // get the lower of numEvents or the number of events in the feed
	var numEventsShown	= 0; // a variable to store how many events have been shown
	
	// first make sure that we have a true xml document to work with
	if( xmlDoc.childNodes.length > 0 )
	{	
		for( var i = 0; i < events.length; i++ ) // loop through all of the found events
		{
			// get some information for each event node and load it into a cooresponding array
			titles[i]		= events[i].getElementsByTagName( "title" )[0].firstChild.nodeValue;
			links[i]		= events[i].getElementsByTagName( "event_link" )[0].firstChild.nodeValue;
			descriptions[i]	= events[i].getElementsByTagName( "description" )[0].firstChild.nodeValue;
			//alert(events[i].getElementsByTagName( "description" )[0].firstChild.nodeValue);
		}
		
		if( events.length > 0 )
			loadingBox.remove(); // hide the loading box
			
		for( var i = 0; i < events.length; i++ ) // loop through all of the found events
		{			
			if( numEventsShown < maxEvents ) // if we have an event to show, then show it
			{
				displayEvent( titles[i], links[i], descriptions[i] ); // actually display the event
				numEventsShown++; // increment the number of events shown so far
			}
		}
		
		if( numEventsShown == 0 ) // there were no events to be shown
		{
			printEventError( "No upcoming events found, please check the calendar.", "events/noCalendar.gif" ); // print an error
		}
		else // we did show some events, now we want to remove some styling from the last event shown
		{
			var eventsShown	= $$( 'div.event' ); // get all events
			eventsShown[eventsShown.length - 1].addClassName( "last" ); // give the last event a new class name of last
		}
	}
	else // we did not get a valid feed returned to us from the xml string, print an error
	{
		printEventError( "Error loading events, please check the calendar.", "exclamation.png" );
		sendFeedError();
	}
}

// this function takes in the event information, creates the HTML nodes for it, and shows the event
function displayEvent( title, eLink, desc )
{
	// first create the necessary HTML nodes, and the text for them
	var eventDiv 		= document.createElement( "div" );
	eventDiv.className	= "event";
	
	var dateDiv			= document.createElement( "div" );
	dateDiv.className	= "eventDate";
	
	var spanMonth		= document.createElement( "span" );
	spanMonth.className = "month";
	var month			= findMonthInText( "Date:", desc );
	var monthText		= document.createTextNode( month );
	
	var spanDay			= document.createElement( "span" );
	spanDay.className	= "day";
	var day				= findDayInText( "Date:", desc );
	var dayText			= document.createTextNode( day );
	
	var spanTime		= document.createElement( "span" );
	spanTime.className	= "time";
	var actualTime		= findTimeInText( "Time:", desc );
	var timeText		= document.createTextNode( actualTime );
	
	var eventTitle		= document.createElement( "h3" );
	var eventLink		= document.createElement( "a" );
	eventLink.href		= eLink.strip();
	eventLink.title		= title.strip();
	eventLink.target	= "_blank";
	var linkText		= document.createTextNode( title.strip().truncate(38, ' [...]') );
	
	var eventDesc		= document.createElement( "p" );
	var description		= findDescriptionInText( desc );
	
	var descText		= document.createTextNode( description.truncate(58, ' [...]') );
	
	// now start putting everything together in order
	spanMonth.appendChild( monthText );
	spanDay.appendChild( dayText );
	spanTime.appendChild( timeText );
	
	dateDiv.appendChild( spanMonth );
	dateDiv.appendChild( spanDay );
	dateDiv.appendChild( spanTime );
	
	eventDesc.appendChild( descText );
	eventLink.appendChild( linkText );
	eventTitle.appendChild( eventLink );
	
	eventDiv.appendChild( dateDiv );
	eventDiv.appendChild( eventTitle );
	eventDiv.appendChild( eventDesc );
	
	// finally go ahead and insert the new event HTML into the actual HTML document 
	calendarLink.insert( {before: eventDiv} );
}

// this will load an xml document from an xml string
function parseXMLFromString( xmlText )
{
	// varies per browser
	if( window.ActiveXObject ) // for internet explorer
	{
		var doc		= new ActiveXObject( "Microsoft.XMLDOM" );
		doc.async	= "false";
		doc.loadXML( xmlText );
	}
	else // code for Mozilla, Firefox, Opera, etc.
	{
		var parser	= new DOMParser();
		var doc		= parser.parseFromString( xmlText, "text/xml" );
	}
	
	return doc;
}

// this will find the time in the given string for the event feed
function findTimeInText( string, text )
{
	var actualTime	= text.split( string );
	
	if( actualTime.length > 1 )
	{
		actualTime	= actualTime[1].substring(0,9);
		actualTime	= actualTime.strip();
		
		if( !actualTime.endsWith("PM") && !actualTime.endsWith("AM") )
		{
			actualTime	= actualTime.substring(0,5);
		}

		return actualTime.strip();
	}
	else
	{
		return "All Day";	
	}
}

// this will find the day in the given string for the event feed
function findDayInText( string, text )
{
	var day	= text.split( string );
	day		= day[1].substring(10,12);

	if( day.substring(1,2) == "," )
		day = day.substring(0,1);
	
	return day.strip();
}

// this will find the month in the given string for the event feed
function findMonthInText( string, text )
{
	var month	= text.split( string );
	month		= month[1].substring(6,9);
	
	return month.strip();
}

// this will find the event description in the given string for the event feed
function findDescriptionInText( text )
{
	//alert(text);
	// var descArray 	= text.split( "||_" );
	var descArray   = text.split( "<br /><delim/>" );
	var description = "";
	
	if (descArray.length <= 2)
		return "";
	else
		return descArray[2];
}

// this will remove the loading box, and then print an error message
function printEventError( errorMessage, errorImage )
{
	if( loadingBox ) // only if its actually there should we remove it
		loadingBox.remove();
	
	var errorDiv	= document.createElement( "div" );
	errorDiv.id		= "error";
	
	var img			= document.createElement( "img" );
	img.src			= "/img/icons/" + errorImage;
	img.alt			= "Calendar error image";
	
	var message		= document.createElement( "p" );
	var messageText	= document.createTextNode( errorMessage );
	message.appendChild( messageText );
	
	errorDiv.appendChild( img );
	errorDiv.appendChild( message );
	
	calendarLink.insert( {before: errorDiv} ); // now insert the error just above the calendar link
}