function EventCalendar( siteId )
{
	this.dialog = null;
	this.display = null;
	
	if( siteId )
	{
		this.site = siteId;
	}
	else
	{
		this.site = ( window.location + "" ).match( /^http:\/\/(www\.)?(.*\/)/ )[2];
	}
	
	
	this.submission = new Object();
	this.req = null;
	this.date = null;
	
	this.afterLogin = undefined;
	
	this.dialog_fadeFrom = "#FFFFCE";
	this.dialog_fadeTo = "#FFFFFF";
	
	this.categories = new Array();
	this.categories["Community"] = "Community";
	this.categories["Film"] = "Film	";
	this.categories["Literature"] = "Literature";
	this.categories["PerformingArts"] = "Performing Arts";
	this.categories["VisualArts"] = "Visual Arts";
	this.categories[""] = "Misc";
	
	var myURL = window.location + "";
	var queryDate = /(\d{1,2})-(\d{1,2})-(\d{4})/i.exec( myURL );
	if( queryDate != null )
	{
		this.date = new Date( queryDate[3], queryDate[1]-1, queryDate[2] );
	}
	else
	{
		this.date = null;
	}
	
	this.dialog = document.getElementById("ec_Dialog");
	this.display = document.getElementById("ec_Display");
}

EventCalendar.prototype._SetSite = function( siteId )
{
	this.site = siteId;
}

EventCalendar.SetSite = function( siteId )
{
	var ec = EventCalendar.GetInstance();
	if( siteId )
	{
		ec._SetSite( siteId );
	}
	else
	{
		ec._SetSite( "citytv-toronto" );
	}
}

EventCalendar.GetInstance = function()
{
	if( ! EventCalendar.__instance )
	{
		EventCalendar.__instance = new EventCalendar();
	}
	
	return EventCalendar.__instance;
}

EventCalendar.Submission = function(  ) 
{
	var ec = EventCalendar.GetInstance();

	ec.submission = null;
	ec.submission = new Object();
	
	if( LoginManager.GetLoginStatus() == true )
	{
		ec.SubmissionPrompt();
	}
	else
	{
		ec.LoginPrompt( undefined, ec.SubmissionPrompt );
	}
}

EventCalendar.prototype.LoginPrompt = function( errorMessage, afterFunction )
{
	if( afterFunction )
	{
		this.afterLogin = afterFunction;
	}
	
	var promptHTML = "";
		
	if( errorMessage != undefined )
	{
		promptHTML = "<p class='LoginError'>" + errorMessage + "</p>";
	}
	
	promptHTML +=
		"<dl id='ec_LoginPrompt'>"
		+ "<dt>Username:</dt>"
		+ "<dd><input type='text' name='username' id='username' /></dd>"
		+ "<dt>Password:</dt>"
		+ "<dd><input type='password' name='password' id='password'/></dd>"
		+ "<dt><input type='button' id='ec_LoginButton' value='Login' onClick='EventCalendar.PerformLogin();'/></dt>"
		+ "</dl>";
		
	this.dialog.innerHTML = promptHTML;
		
	this.FadeDialog();	
	
}

EventCalendar.PerformLogin = function( )
{
	var ec = EventCalendar.GetInstance();
	
	var loginButton = document.getElementById("ec_LoginButton");
	loginButton.disabled = true;
	loginButton.parentNode.innerHTML += '<img src="/universalInclude/code/classes/eventcalendar/citytvProgressBar.gif" width="159" height="13" border="0" />';

	var owner = ec;
	
	LoginManager.Login( function() { owner.PerformLogin_Handler(); } );
}

EventCalendar.prototype.PerformLogin_Handler = function( )
{
	if( LoginManager.GetLoginStatus() )
	{
		if( this.afterLogin )
		{
			this.afterLogin();
		}
	}
	else
	{
		this.LoginPrompt( "Sorry, that username/password combination was invalid.  Please try again." );
	}
}

EventCalendar.prototype.SubmissionPrompt = function( eventid )
{
	this.dialog.innerHTML = '<img src="/universalInclude/code/classes/eventcalendar/citytvProgressBar.gif" width="159" height="13" border="0" />';
	
	this.req = new XMLHttpRequest();
	var owner = this;
	var query = "/universalInclude/code/modules/eventcalendar/editForm.asp";
	if( eventid != undefined )
	{
		query += "?eventid=" + eventid;
		this.submission.id = eventid;
	}
	this.req.open("GET", query, true);
	this.req.onreadystatechange = function() { owner.SubmissionPrompt_Handler( ) };
	this.req.send( null );
	
}

EventCalendar.prototype.SubmissionPrompt_Handler = function( context )
{
	if( this.req.readyState == 4 )
	{
		this.dialog.innerHTML = this.req.responseText;
		
		//this.FadeDialog();
		this.req = null;
		
		if( this.submission.title != undefined ) 
		{
			document.getElementById("ec_title").value = this.submission.title;
		}
		if( this.submission.description != undefined ) 
		{
			document.getElementById("ec_description").value = this.submission.description.replace( /<br \/>/g, "\n" );
		}
		if( this.submission.website != undefined ) 
		{
			document.getElementById("ec_website").value = this.submission.website;
		}
		if( this.submission.time != undefined ) 
		{
			document.getElementById("ec_time").value = this.submission.time;
		}
		if( this.submission.category != undefined ) 
		{
			document.getElementById("ec_category").value = this.submission.category;
		}
		if( this.submission.startdate != undefined ) 
		{
			document.getElementById("ec_startdate").value = this.submission.startdate;
		}
		if( this.submission.enddate != undefined ) 
		{
			document.getElementById("ec_enddate").value = this.submission.enddate;
		}
		if( this.submission.venueName != undefined ) 
		{
			document.getElementById("ec_venuename").value = this.submission.venueName;
		}
		if( this.submission.venueAddress != undefined ) 
		{
			document.getElementById("ec_venueaddress").value = this.submission.venueAddress.replace( /<br \/>/g, "\n" );
		}

		this.FormatSubmissionPrompt();
		this.SetupFieldDatePicker( "ec_startdate", document.getElementById("ec_startdate").value );
		this.SetupFieldDatePicker( "ec_enddate", document.getElementById("ec_enddate").value );
	}
}

EventCalendar.prototype.FormatSubmissionPrompt = function()
{
	var fields = document.getElementById("ec_SubmissionFields").getElementsByTagName("*");
	for( var i = 0; i < fields.length; i++ )
	{
		// Check required fields.
		if( /required/i.test( fields[i].className ) )
		{
			if( !fields[i].value )
			{
				fields[i].style.background = "lightyellow"; 
			}
			fields[i].onblur = fields[i].onchange = function() 
				{ 
					if( !this.value )
					{
						this.style.background = "pink"; 
					}
					else
					{
						this.style.background = "white";
					}
				}
		}
	}
}

EventCalendar.prototype.VerifySubmissionPrompt = function()
{
	var isVerified = true;

	var fields = document.getElementById("ec_SubmissionFields").getElementsByTagName("*");
	for( var i = 0; i < fields.length; i++ )
	{
		if( fields[i].className.toLowerCase() == "required" )
		{
			if( !fields[i].value )
			{
				fields[i].style.background = "pink";
				isVerified = false;
			}
		}
	}
	
	return isVerified;
}

EventCalendar.prototype.PreviewSubmission = function()
{
	if( !this.VerifySubmissionPrompt() )
	{
		alert( "Please complete all the required fields in red before proceeding.\nThank you." );
		return;
	}

	this.submission.title = EventCalendar.MakeFieldValueSafe( document.getElementById("ec_title").value );
	this.submission.description = EventCalendar.MakeFieldValueSafe( document.getElementById("ec_description").value );
	this.submission.website = EventCalendar.MakeFieldValueSafe( document.getElementById("ec_website").value );
	this.submission.time = EventCalendar.MakeFieldValueSafe( document.getElementById("ec_time").value );
	this.submission.startdate = EventCalendar.MakeFieldValueSafe( document.getElementById("ec_startdate").value );
	this.submission.enddate = EventCalendar.MakeFieldValueSafe( document.getElementById("ec_enddate").value );
	this.submission.category = EventCalendar.MakeFieldValueSafe( document.getElementById("ec_category").value );
	this.submission.venueName = EventCalendar.MakeFieldValueSafe( document.getElementById("ec_venuename").value );
	this.submission.venueAddress = EventCalendar.MakeFieldValueSafe( document.getElementById("ec_venueaddress").value );
		
	this.dialog.innerHTML = "<dl class='ec_SubmissionPreview'>"
		+ "<dt>Title:</dt><dd>" + this.submission.title + "&nbsp;</dd>"
		+ "<dt>Description:</dt><dd>" + this.submission.description.replace( /\n/g, "<br />" )	 + "&nbsp;</dd>"
		+ "<dt>Website:</dt><dd><a href='" + this.submission.website + "' target='_blank'>" + this.submission.website + "</a>&nbsp;</dd>"
		+ "<dt>Time:</dt><dd>" + this.submission.time + "&nbsp;</dd>"
		+ "<dt>Start Date:</dt><dd>" + this.submission.startdate + "&nbsp;</dd>"
		+ "<dt>End Date:</dt><dd>" + this.submission.enddate + "&nbsp;</dd>"
		+ "<dt>Venue Name:</dt><dd>" + this.submission.venueName + "&nbsp;</dd>"
		+ "<dt>Venue Address:</dt><dd>" + this.submission.venueAddress.replace( /\n/g, "<br />" ) + "&nbsp;</dd>"
		+ "<dt>Category:</dt><dd>" + this.submission.category + "&nbsp;</dd>"
		+ "</dl>"
		+ "<input type='button' onclick='EventCalendar.GetInstance().SubmissionPrompt()' value='Edit' />"
		+ "<input type='button' onclick='EventCalendar.GetInstance().SubmitEvent()' value='Submit' />"
		+ "<input type='button' onclick='EventCalendar.GetInstance().CancelDialog()' value='Cancel' />";
}

EventCalendar.MakeFieldValueSafe = function( value )
{
	value = value.replace( /<[^>]*>/g, "" );
	return value;
}

EventCalendar.prototype.SubmitEvent = function() 
{
	if( !confirm( "Are you sure you want to submit this event?" ) )
	{
		this.SubmissionPrompt( this.submission.id );
		return;
	}

	this.dialog.innerHTML = '<img src="/universalInclude/code/classes/eventcalendar/citytvProgressBar.gif" width="159" height="13" border="0" />';
	
	this.req = new XMLHttpRequest();
	var owner = this;
	var query = "/universalInclude/code/modules/eventcalendar/submitevent.asp"
	if( this.submission.id != undefined )
	{	
			query += "?eventid=" + this.submission.id;
	}
	this.req.open("POST", query, true );
	this.req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	this.req.onreadystatechange = function() { owner.SubmitEvent_Handler(); };
	this.req.send( 
		"title=" + escape( this.submission.title ) 
		+ "&description=" + escape( this.submission.description ) 
		+ "&website=" + escape( this.submission.website ) 
		+ "&time=" + escape( this.submission.time ) 
		+ "&startdate=" + escape( this.submission.startdate ) 
		+ "&enddate=" + escape( this.submission.enddate )
		+ "&venuename=" + escape( this.submission.venueName )
		+ "&venueaddress=" + escape( this.submission.venueAddress )
		+ "&site=" + escape( this.site )
		+ "&category=" + escape( this.submission.category )
	);
}

EventCalendar.prototype.SubmitEvent_Handler = function() 
{
	if( this.req.readyState == 4 )
	{
		if( this.req.responseText == "1" )
		{
			this.req = null;
			this.submission = new Object();
			this.dialog.innerHTML = "<p>Thanks, we've received your event!  <a href='javascript:EventCalendar.Submission()'>Submit another event</a></p>";		
			this.FadeDialog();	
		}
		else if( this.req.responseText == "0" )
		{
			// Check if the user is logged in
			this.LoginPrompt( "Sorry, your login appears to have expired.  To submit your event, please login below.", this.SubmitEvent );
		}
		else
		{
			this.dialog.innerHTML = "<p>Sorry, there was a problem sending your event.<br/>"
				+ "<a href='javascript:EventCalendar.GetInstance().SubmitEvent()'>Please click here to try again.</a></p>";
			this.FadeDialog();
		}
	}
}

EventCalendar.ShowDate = function( pDate )
{
	var appendBookmark;
	
	var ec = EventCalendar.GetInstance();
	
	if( pDate != undefined && pDate != null )
	{
		ec.date = pDate;
		appendBookmark = true;
	}
	else
	{	
		if( ec.date == null )
		{
			ec.date = new Date();
			appendBookmark = false;
		}		
	}
	
	//TODO: REENABLE AJAX CALLS TO LOAD CALENDAR WHEN ITS ACCEPTED
	appendBookmark = false;
		
	var y = ec.date.getFullYear();
    var m = ec.date.getMonth() + 1;
    var d = ec.date.getDate();   
    
    if( appendBookmark )
    {
		window.location = ( window.location + "" ).match( /^[^#]+/ )[0] + "#" + m + "-" + d + "-" + y;
	}
    
    ec.display.innerHTML = '<img src="/universalInclude/code/classes/eventcalendar/citytvProgressBar.gif" width="159" height="13" border="0" />';
    
    ec.req = new XMLHttpRequest();
	var owner = ec;
	var query = "/universalInclude/code/modules/eventcalendar/getEvents.asp?date=" + m + "-" + d + "-" + y
		+ "&site=" + ec.site;
		
	ec.req.open("GET", query, true);
	ec.req.onreadystatechange = function() { owner.ShowDate_Handler( ) };
	ec.req.send( null );
}

EventCalendar.prototype.ShowDate_Handler = function( )
{
	if( this.req.readyState == 4 )
	{
		this.display.innerHTML = this.req.responseText;
		this.req = null;
		this.FormatDisplay();
	}
}

EventCalendar.ShowMyEvents = function()
{
	var ec = EventCalendar.GetInstance();

	if( ! LoginManager.GetLoginStatus() )
	{
		ec.LoginPrompt( "You must login to view your events.", EventCalendar.ShowMyEvents );
		return;
	}

	ec.display.innerHTML = '<img src="/universalInclude/code/classes/eventcalendar/citytvProgressBar.gif" width="159" height="13" border="0" />';
    
    ec.req = new XMLHttpRequest();
	var owner = ec;
	var query = "/universalInclude/code/modules/eventcalendar/getEvents.asp?myEvents=1"
		+ "&site=" + ec.site;
	ec.req.open("GET", query, true);
	ec.req.onreadystatechange = function() { owner.ShowMyEvents_Handler( ) };
	ec.req.send( null );

}

EventCalendar.prototype.ShowMyEvents_Handler = function()
{
	if( this.req.readyState == 4 )
	{
		if( this.req.responseText == "0" )
		{
			this.req = null;
			this.display.innerHTML = "";
			this.LoginPrompt( "You must login to view your events.", this.ShowMyEvents );			
		}
		else
		{
			this.dialog.innerHTML = "Below you'll find all the events you've submitted.";
			
			this.display.innerHTML = this.req.responseText;
			this.req = null;
			
			this.FormatDisplay();
			
			this.FadeDialog();
		}
	}
}

EventCalendar.prototype.FormatDisplay = function()
{
	var events;
	var dls = this.display.getElementsByTagName("dl");
	for( var i = 0; i < dls.length; i++ )
	{
		if( dls[i].className == "ec_events" )
		{
			events = dls[i];
			break;
		}
	}
	if( events == undefined )
	{
		// Stop applying formatting since something is wrong.
		return;
	}
	
	var numCategoryEvents;	
	for( categoryId in this.categories )
	{
		var category = document.createElement("DL");
		category.className = "ec_events";
		
		numCategoryEvents = 0;
		
		var eventsNode;
		
		for( var i = 0; i < events.childNodes.length; i++ )
		{
			
			eventsNode = events.childNodes[i];
			
			if( eventsNode.tagName == "DT" && eventsNode.className == categoryId )
			{
				numCategoryEvents++;
				
				var event = new Array();
				event.push( eventsNode );
	
				if( eventsNode.getAttribute("editable") == "true" )
				{
					eventsNode.innerHTML += " <span class='editlink' onmousedown='EventCalendar.EditEvent( this.parentNode );'>(edit)</span>";
				}
				
				eventsNode.onmousedown = function()
				{
					var nextdd = this.nextSibling;
					while( nextdd != undefined && nextdd.tagName != "DT" )
					{
						if( nextdd.style )
						{
							if( !nextdd.style.display || nextdd.style.display == "none" )
							{
								nextdd.style.display = "block";
							}
							else
							{
								nextdd.style.display = "none";
							}
						}
						nextdd = nextdd.nextSibling;
					}
				}
				
				eventsNode = events.childNodes[++i];
				for( ; i < events.childNodes.length && eventsNode != undefined && eventsNode.tagName != "DT";  )
				{
					if( eventsNode.style )
					{
						eventsNode.style.display = "none";
					}
					event.push( eventsNode );
					eventsNode = events.childNodes[++i];
				}
				i -= event.length + 1;
				
				for( var j = 0; j < event.length; j++ )
				{
					category.appendChild( event[j] );
				}
			}			
		}
		
		var numCategoryEventsString;
		if( numCategoryEvents > 0 )
		{
			numCategoryEventsString = " (" + numCategoryEvents + " events)";
			
			var header = document.createElement("h1");
			header.className = "ec_events";
			header.appendChild( document.createTextNode( this.categories[categoryId]  + numCategoryEventsString ) );
			this.display.appendChild( header );
			
			this.display.appendChild( category );
		}
		else
		{
			numCategoryEventsString = "";
		
		}
	}
	
	events.style.display = "none";
}

EventCalendar.EditEvent = function( eventContainer ) 
{
	var ec = EventCalendar.GetInstance();

	var eventid;
	if( ( eventid = (eventContainer.id).match( /\d+/ ) ) == null )
	{
		return;
	}
	else
	{
		ec.dialog.innerHTML = '<img src="/universalInclude/code/classes/eventcalendar/citytvProgressBar.gif" width="159" height="13" border="0" />';
		ec.SubmissionPrompt( eventid );
	}
}

EventCalendar.prototype.DeleteEvent = function( ) 
{

	if( this.submission.id == undefined )
	{
		return;
	}
	
	if( confirm( "Are you sure you want to delete this event?\nThis action cannot be undone." ) )
	{
		this.req = new XMLHttpRequest();
		var owner = this;
		var query = "/universalInclude/code/modules/eventcalendar/deleteEvent.asp?id=" + this.submission.id;
		this.req.open("GET", query, true);
		this.req.onreadystatechange = function() { owner.DeleteEvent_Handler( ) };
		this.req.send( null );
	}
}

EventCalendar.prototype.DeleteEvent_Handler = function( ) 
{
	if( this.req.readyState == 4 )
	{
		if( this.req.responseText == "1" )
		{
			this.dialog.innerHTML = "Deleted successfully.";
			this.req = null;
			EventCalendar.ShowDate();
		}
		else
		{
			this.dialog.innerHTML = "ERROR";
		}
	}
}

EventCalendar.LoadCalendar = function()
{
	var owner = EventCalendar.GetInstance();
	
  calendar = Calendar.setup(
    {
      flat         : "ec_Calendar", // ID of the parent element
      weekNumbers  : false,
      flatCallback : owner.Calendar_DatePicked,          // our callback function
		date	:	owner.date,
		showOthers 	:	true
	}
  );
}

EventCalendar.prototype.Calendar_DatePicked = function( calendar )
{
	
	if (calendar.dateClicked) {
      // OK, a date was clicked, redirect to /yyyy/mm/dd/index.php
      var y = calendar.date.getFullYear();
      var m = calendar.date.getMonth() + 1;     // integer, 1..12
      var d = calendar.date.getDate();      // integer, 1..31
    
		if( /AJAX/i.test( window.location ) )
		{
			// Load into page
			EventCalendar.ShowDate( calendar.date );
		}
		else
		{
			// GO TO NEW PAGE
			window.location = "?date=" + m + "-" + d + "-" + y;
		}
    }
}

EventCalendar.prototype.CancelDialog = function()
{
	this.dialog.innerHTML = "Action cancelled";
	this.FadeDialog();
	this.submission = null;
	this.submission = new Object();
}

EventCalendar.prototype.FadeDialog = function()
{
	var owner = this;
	Fat.fade_element( "ec_Dialog", 15, 1000, this.dialog_fadeFrom, this.dialog_fadeTo );
}

EventCalendar.prototype.SetupFieldDatePicker = function( fieldName, date )
{
	Calendar.setup(
	{
		inputField  : fieldName,         // ID of the input field
		ifFormat    : "%m/%d/%Y",    // the date format
		button      : fieldName + "_button",       // ID of the button
		date		: date
	}
	);
}
