/**
 * DSBN Website - Includes functions added to all websites
 *
 * @version: 1.0
 * @author: Matt Froese (matt.froese@dsbn.edu.on.ca)
**/

function addLoadEvent(func)
{
	var oldonload = window.onload;
	if( typeof window.onload != 'function' ) 
	{
		window.onload = func;
	} 
	else 
	{
		window.onload = function()
		{
			if( oldonload )
			{
				oldonload();
			}
			func();
		}
	}
}

/*
	Top Bar Elements 
*/

function createAjaxObj() 
{
	var req = false;
	if( window.XMLHttpRequest ) 
	{
		req = new XMLHttpRequest();

		if( req.overrideMimeType ) 
		{
			req.overrideMimeType( "text/xml" );
		}
	}
	else if( window.ActiveXObject ) 
	{
		var xmlHttp = false;
		try 
		{
		  req = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e) 
		{
			try 
			{
				req = new ActiveXObject("Microsoft.XMLHTTP");
			} 
			catch (e2) 
			{
				req = false;
			}
		}
	}
	return req;
}

function getDomain()
{
	var windowLocation = window.location.href;
	if( windowLocation.indexOf( "www.dsbn.org" ) != -1 )
	{
		return "www.dsbn.org";
	}
	else if( windowLocation.indexOf( "dsbn.org" ) != -1 )
	{
		return "dsbn.org";
	}
	else
	{
		return "www.dsbn.edu.on.ca";
	}
}

function DSBNNews()
{
	this.feedUrl = ( window.location.href.indexOf( "https://" ) == 0 ) ? "https://" : "http://";
	this.feedUrl += getDomain() + "/news_xml.aspx?show=true";

	this.containerId = "news-description";
	this.ajaxObj = createAjaxObj();
	this.mouseoverBol = false;
	this.msg = 0;
	this.firstRun = true;
	this.timer = 6;
	this.errorMessage = "";
}

DSBNNews.prototype.init = function() 
{
	if( this.feedUrl == "" ) 
	{
		this.error( "Feed URL empty" );
		return false;
	}
	if( this.ajaxObj ) 
	{
		DSBNNewsInstance = this;		
		this.initLoader();
		this.ajaxObj.onreadystatechange = function() { DSBNNewsInstance.getFeedCallback() };
		try 
		{
			this.ajaxObj.open( "GET", this.feedUrl, true );
		} 
		catch( err ) 
		{ 
			this.error( "XMLHttpRequest.open() failed: " + err ); return;
		}
		this.ajaxObj.send( null );
	}
	else
	{
		this.error( "Init failed" ); return;
	}
}

DSBNNews.prototype.getFeedCallback = function() 
{ 
	if( this.ajaxObj.readyState == 4 && this.ajaxObj.status == 200 ) 
	{
		var xml = this.ajaxObj.responseXML;		
		this.items = xml.getElementsByTagName("item");

		if( this.items.length == 0 ) 
		{
			this.error( "Could not find news (" + this.items.length + ")" );
			return;
		}
		else
		{
			var DSBNNewsInstance = this;
			for( var i = 0; i < this.items.length; i++ ) 
			{
				if( this.items[i].getElementsByTagName("link")[0].firstChild ) 
				{
					this.items[i].setAttribute( "clink", this.items[i].getElementsByTagName("link")[0].firstChild.nodeValue );
				}
				title = this.items[i].getElementsByTagName("title")[0].firstChild.nodeValue;
				title = title.replace(/(<([^>]+)>)/ig,"" ); 
				this.items[i].setAttribute( "ctitle", title );
			}
			document.getElementById( this.containerId ).onmouseover = function(){ DSBNNewsInstance.mouseoverBol = true }
			document.getElementById( this.containerId ).onmouseout = function(){ DSBNNewsInstance.mouseoverBol = false }
		}
		this.rotate();		
	}
}

DSBNNews.prototype.rotate = function() 
{	
	if( this.timer >= 6 ) 
	{
		this.timer = 0;
		if( this.mouseoverBol == false ) 
		{
			if( this.firstRun )
			{
				this.firstRun = false;
				this.msg = 0;
			}
			else
			{
				this.msg = ( this.msg < this.items.length - 1 ) ? this.msg + 1 : 0;
			}
			this.changeMessage( this.msg );
		}
	}
	this.timer++;
	var DSBNNewsInstance = this;
	setTimeout( function() { DSBNNewsInstance.rotate() } , 1000 );	
}

DSBNNews.prototype.next = function() 
{
	if( this.mouseoverBol == false ) 
	{
		this.msg = ( this.msg < this.items.length - 1 ) ? this.msg + 1 : 0;
		this.changeMessage( this.msg );
		this.timer = 0;
	}
}

DSBNNews.prototype.previous = function() 
{
	if( this.mouseoverBol == false ) 
	{
		this.msg = ( this.msg == 0 ) ? this.items.length - 1 : this.msg - 1;
		this.changeMessage( this.msg );
		this.timer = 0;
	}	
}

DSBNNews.prototype.changeMessage = function( msg ) 
{	
	var container = document.getElementById( this.containerId );
	container.innerHTML = "";
	DSBNNewsInstance = this;

	var title = this.items[ msg ].getAttribute("ctitle");
	title = title.length > 30 ? title.substring( 0, 30 ) + "..." : title;
	
	var link = document.createElement( "a" );
	link.href = this.items[ msg ].getAttribute("clink");
	link.target = "_blank";

	link.innerHTML = title;
	container.appendChild( link );

	document.getElementById( "news-more" ).href = this.items[ msg ].getAttribute("clink");
}

DSBNNews.prototype.initLoader = function()
{
	var container = document.getElementById( this.containerId );
	container.innerHTML = "<img id=\"dsbn-topbar-loading\" src=\"http://www.dsbn.edu.on.ca/schools/shared/topbar/images/loading.gif\" alt=\"Loading...\" />";
}

DSBNNews.prototype.error = function( errorMessage ) {
	var container = document.getElementById( this.containerId );
	container.innerHTML = "Error: " + errorMessage;
	container.title = "Error: " + errorMessage;
	this.errorMessage = errorMessage;
}

/*
	Emergency Elements 
*/

function DSBNICOECheckMessages()
{
	var school = "";
	var page = "";
	var uri = window.location.href.toLowerCase();

	if( uri.indexOf( "schools/" ) != -1 )
	{
		buffer = uri.substring( uri.indexOf( "schools/" ) + 8 );
		school = buffer.substring( 0, buffer.indexOf( "/" ) );
		page = buffer.substring( buffer.lastIndexOf( "/" ) + 1 );
	}
	else if( uri.indexOf( "schools.dsbn.edu.on.ca" ) != -1 )
	{
		buffer = uri.substring( uri.indexOf( "schools.dsbn.edu.on.ca/" ) + 23 );
		school = buffer.substring( 0, buffer.indexOf( "/" ) );
		page = buffer.substring( buffer.lastIndexOf( "/" ) + 1 );
	}

	var html = "";
	//if( schoolAlias == "templatepublicschool" )
	//{
	//	html = "<div id=\"icoe-message\"><a class=\"more\" href=\"incaseofemergency.html\"><span class=\"message\">This is an example of emergency messages that can be pushed to each school website. <strong>Click here for more information</strong>.</span></a></div>";
	//}

	//if( page == "index.html" )
	//{
		//html = "<div id=\"icoe-message\">"
		//	+ "<a class=\"more\" href=\"http://www.dsbn.org/index.aspx?id=7820\">"
		//	+ "<span class=\"message\">"
		//	+ "An important message has been posted regarding Inclement Weather Procedures.<br />Click here to view these procedures."
		//	+ "</span>"
		//	+ "</a></div>";
	//}

	if( icoeContainer = document.getElementById( "icoe-container" ) )
	{
		//icoeContainer.innerHTML = html;
		//icoeContainer.style.display = 'block';
		//icoeContainer.style.height = 'auto';
		//icoeContainer.style.fontSize = '12px';
	}

	/*var html = "";
	if( school == "templateps" )
	{
		html = "<div id=\"icoe-message\"><a class=\"more\" href=\"incaseofemergency.html\"><span class=\"message\">This is an example of emergency messages that can be pushed to each school website. <strong>Click here for more information</strong>.</span></a></div>";
	}

	if( icoeContainer = document.getElementById( "icoe-container" ) )
	{
		icoeContainer.innerHTML = html;
	}*/
}

/*
	Map function
*/
function loadSchoolMap( schoolCode ) 
{
	if( GBrowserIsCompatible() )
	{
		var map = new GMap2(document.getElementById("map"));
		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());
		map.setCenter(new GLatLng(43.04681263770761,-79.39132690429688), 10 );
		
		GDownloadUrl("/schools/api/school/?school=" + schoolCode, function( data, responseCode ) 
		{
			if( responseCode == 200 )
			{
				var xml = GXml.parse( data );
				var schools = xml.documentElement.getElementsByTagName("school");

				var baseIcon = new GIcon();
				baseIcon.iconSize=new GSize(32,32);
				baseIcon.shadowSize=new GSize(56,32);
				baseIcon.iconAnchor=new GPoint(16,32);
				baseIcon.infoWindowAnchor=new GPoint(16,0);

				var school = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal2/icon10.png", null, "http://maps.google.com/mapfiles/kml/pal2/icon10s.png");
				
				var name = schools[0].getElementsByTagName("name")[0].firstChild.nodeValue;
				var full_address = schools[0].getElementsByTagName("full_address")[0].firstChild.nodeValue;
				var phone = schools[0].getElementsByTagName("phone")[0].firstChild.nodeValue;
				var website = schools[0].getElementsByTagName("website")[0].firstChild.nodeValue;
				var lat = parseFloat( schools[0].getElementsByTagName("lat")[0].firstChild.nodeValue );
				var lng = parseFloat( schools[0].getElementsByTagName("lng")[0].firstChild.nodeValue );
				var elementary = parseFloat( schools[0].getElementsByTagName("elementary")[0].firstChild.nodeValue );
				
				if( elementary == "1" )
				{
					name += " Public School";
				}
				else
				{
					name += " Secondary School";
				}
				var point = new GLatLng( lat, lng );
				
				marker = new GMarker( point, school );

				GEvent.addListener(marker, "click", function() {
					map.setCenter( point );
					marker.setLatLng( point );
					marker.openInfoWindowHtml( "<span style='font-family: Arial, Helvetica, sans-serif; font-size: 12px;'><span style='font-weight: bold; font-size: 14px;'>" + name + "</span><div style='padding-top: 5px;'>" + full_address + "</div><div style='padding-top: 5px;'>" + phone + "</div>" );
				});					
				
				map.addOverlay( marker );						
				
				map.setCenter( point, 11 );

				document.getElementById( "larger-map" ).href = "http://maps.google.com/maps?f=q&hl=en&geocode=&q=" + full_address + " (" + name + ") @" + lat + "," + lng + "&ie=UTF8&t=h&z=16&iwloc=addr";
			}
			else if( responseCode == -1 )
			{
				alert("Data request timed out. Please try later.");
			}
			else
			{ 
				alert("Request resulted in error. Check XML file is retrievable.");
			}
		});
	}
}

/*
	Onload function
*/

topbarnews = new DSBNNews();
addLoadEvent( function() 
{	
	topbarnews.init();
	DSBNICOECheckMessages();
	if( document.getElementById( "map-school-code" ) != undefined )
	{
		loadSchoolMap( document.getElementById( "map-school-code" ).value );
	}

});

function getUpcomingEvents( schoolId )
{
	if( document.getElementById( 'important_dates' ) == undefined ) return false;

	ajax = createAjaxObj();
	if( ajax ) 
	{	
		calendar = this;

		ajax.onreadystatechange = function() 
		{ 
			if( ajax.readyState == 4 ) 
			{
				if( ajax.status == 200 ) 
				{
					var xml = ajax.responseXML;
					var text = ajax.responseText;
					var days = xml.getElementsByTagName("day");

					var upcomingEventsList = document.getElementById( "important_dates" );
					upcomingEventsList.innerHTML = "";

					if( days.length == 0 )
					{
						var day = document.createElement( "dt" );
						day.innerHTML = "There are no upcoming events";
						upcomingEventsList.appendChild( day );
					}
					else
					{					
						for( i = 0; i < days.length; i++ )
						{
							for( e = 0; e < days[ i ].childNodes.length; e++ )
							{
								if( days[ i ].childNodes[ e ].tagName == "event" )
								{
									title = days[ i ].childNodes[ e ].childNodes[ 1 ].firstChild.nodeValue;
									start = days[ i ].childNodes[ e ].childNodes[ 3 ].firstChild.nodeValue;
									end = days[ i ].childNodes[ e ].childNodes[ 5 ].firstChild.nodeValue;
									allday = days[ i ].childNodes[ e ].childNodes[ 7 ].firstChild.nodeValue;
									startDate = days[ i ].childNodes[ e ].childNodes[ 11 ].firstChild.nodeValue;
									
									var startTime = "";
									if( allday != "1" )
									{
										startTime = start.substr( 11 );
										minutes = startTime.substr( 3, 2 );
										ampm = "AM";
										hours = parseInt( startTime.substr( 0, 2 ), 10 );				
										if( hours > 12 )
										{
											ampm = "PM";
											hours = hours - 12;
										}
										startTime = hours + ":" + minutes + " " + ampm;
									}

									var dayDate = document.createElement( "dt" );
									dayDate.innerHTML = startDate;
									var dayTitle = document.createElement( "dd" );
									dayTitle.innerHTML = title;

									upcomingEventsList.appendChild( dayDate );
									upcomingEventsList.appendChild( dayTitle );
								}
							}

						}
					}
				}
			}
		};

		try 
		{
			var url = ( window.location.href.indexOf( "https://" ) == 0 ) ? "https://" : "http://";
			url += getDomain() + "/schools/api/calendar/upcoming.php?limit=5&school=" + schoolId;

			ajax.open( "GET", url, true );
		} 
		catch( err ) 
		{ 
			alert( "XMLHttpRequest.open() failed: " + err ); 
			return;
		}
		ajax.send( null );
	}
	else
	{
		alert( "Init failed" ); 
		return;
	}
}
