var jsonarray = new Array();

function historyhandel(hash){
	if (hash){
		if (parseUri(hash).queryKey.date) d = parseUri(hash).queryKey.date.split(",");
		e = parseUri(hash).queryKey.eventid;
		if (d){
			d = new Date(d[0],(d[1]-1),d[2]);
			geteventdata (d,e)
		} else if (e){
			showdetails( e );
		}
	}	
}

function calendarclick(hash){
	//$.jGrowl(hash);
	d = hash.split("/")
	$.historyLoad("?date="+ d[2]+","+d[0]+","+d[1]);
}

function isDate(sDate) {
	var scratch = new Date(sDate);
	if (scratch.toString() == "NaN" || scratch.toString() == "Invalid Date") {
		return false;
	} else {
		return true;
	}
}

function CheckIfHasEvent(date) {

	m = date.getMonth();
	y = date.getFullYear(); 
	d = date.getDate();
	
	try {
		e = jsonarray[y+""+m].events;
		for (x=0;x<e.length;x++){
			if (e[x].StartDate.day == d){
				return [true, ''];
			}
		}
		return [false, ''];
	} catch (error) {
		return [false, '']; 
	}
}

function selectDate(date,eventid){
	date = new Date(date);
	$("#cal1Container").datepicker("setDate",new Date(date));
	//wipe the current data off the page
	showloader();
	eventsrender(date);
	nd = new Date();
	if (
		nd.getFullYear() == date.getFullYear() && 
		nd.getMonth() == date.getMonth() &&
		nd.getDate() == date.getDate()
	) {
		$("#today").attr("disabled","disabled");
	}else{
		$("#today").attr("disabled","");
	}
	
	//if an eventid was passed in open it. 
	
	if (eventid){
		showdetails( eventid )
	}
}

function geteventdata(d,eventid){
	//$.jGrowl("geteventdata "+ d + " "+eventid);
	month = d.getMonth();
	year = d.getFullYear();
	day = d.getDate();
	if (jsonarray[year+""+month] == null) {
		qs = "month="+(month+1)+"&year="+year;
		$.getJSON("json.php", qs, function(json){
			//add the jason to the array so we can reparse it later
			jsonarray[year+""+month] = json;
			selectDate(d,eventid);
		});
	} else {
		selectDate(d,eventid);
	}
}

function makeevent(event){
	StartDate = new Date(event.StartDate.year, (event.StartDate.month-1), event.StartDate.day, event.StartDate.hour, event.StartDate.minute, 0);
	EndDate = new Date(event.EndDate.year, (event.EndDate.month-1), event.EndDate.day, event.EndDate.hour, event.EndDate.minute, 0);

	if (StartDate.format("shortTime") == "12:00 AM") {
		etime = "All Day";
	}else{
		etime = StartDate.format("shortTime");
	}
	
	approved = "";
	if (event.Approved != 'Y' || event.RoomApproved !='Y') {
		approved = " pending ";
	}

	cats = " ";
	$(event.categories).each(function(){
		cats+= " cat_" +this ;
	});


	var temp='';
	temp+= "\n"+"<li id='"+event.EventId+"' class='event "+approved + " " + cats +"'>";
	temp+= "\n"+"	<a class='title' >"+ event.Title +"</a>";
	temp+= "\n"+"	<span class='time' value='" + StartDate.format("HHMM") + "' >" + etime + "</span>";
	temp+= "\n"+"	<div class='popups'>";
	temp+= "\n"+"		<div class='bubbleInfo vcallink'>";
	temp+= "\n"+"			<a class='trigger'>Download as vCal</a>";
	temp+= "\n"+"			<div class='popup'>Download as vCal</div>";
	temp+= "\n"+"		</div>";
	temp+= "\n"+"		<div class='bubbleInfo gwlink'>";
	temp+= "\n"+"			<a class='trigger'>Add to Groupwise</a>";
	temp+= "\n"+"			<div class='popup'>Add to GroupWise</div>";
	temp+= "\n"+"		</div>";
	if (event.edit == 'true') {
		temp+= "\n"+"		<div class='bubbleInfo info'><a class='trigger'>Info</a><div class='popup'>Created by "+ event.SubmittedBy +" on "+ event.SubmittedOn +"  <br/>Edited by "+ event.EditedBy +" on "+ event.EditedOn +"</div></div>";
		temp+= "\n"+"		<div class='bubbleInfo edit'><a class='trigger'>Edit</a><div class='popup'>Edit this event</div></div>";
		temp+= "\n"+"		<div class='bubbleInfo delete'><a class='trigger'>delete</a><div class='popup'>Delete this event</div></div>";
	}
	if (event.RecurringFrequency != 'None') {
		temp+= "\n"+"		<div class='bubbleInfo RecurringFrequency'><a class='trigger'>Recurring</a><div class='popup'>Recurring Event <!--"+event.RecurringFrequency+" until "+event.RecurringEndDate+"--></div></div>";
	}


	temp+= "\n"+"	</div>";

	//location info
	
	temp+= "\n"+"	<div class='details'>";
	temp+= "\n"+"		<ul>";
	
	
	if (event.EndDate.hour > 0) { 
		temp += "<li class='longtime'><strong>From</strong> " + StartDate.format("shortTime") + " to " + EndDate.format("shortTime");
	}

	
	if (event.Location.oncampus != null) { 
		temp+= "\n"+"	<li class='location'><strong>Location</strong>: ";
			if (event.Location.oncampus.Building) {
				temp+= "\n"+"	<a href='/map/index.php?building=" +event.Location.oncampus.Building + "'>";
				temp+= "\n"+"	"+eval("jsonarray['d'].buildings."+event.Location.oncampus.Building);
				temp+= "\n"+"	</a>";
			}
			if (event.Location.oncampus.Room) temp+= ": "+event.Location.oncampus.Room ;
			if (event.Location.oncampus.Other) temp+= "	: " +event.Location.oncampus.Other ;
		temp+= "\n"+"	</li>";
	};
	
	if (event.Location.offcampus != null) { 
		temp+= "\n"+"	<li class='location'><strong>Location</strong>:";
			temp+= "\n"+"	<a href='http://maps.google.com/maps?q=";
				if 	(!event.Location.offcampus.Address) {
					temp+= event.Location.offcampus.Name + ", ";
					temp+= event.Location.offcampus.CityStateZip;
				} else {
					temp+= event.Location.offcampus.Address + ", ";
					temp+= event.Location.offcampus.CityStateZip + ", ";
					temp+= "(" + event.Location.offcampus.Name + ")";
				}
			temp+= "' target='_blank'>";
				if (event.Location.offcampus.Name) temp+= "\n"+ event.Location.offcampus.Name + "<br/>";
				if (event.Location.offcampus.Address) temp+= "\n"+ event.Location.offcampus.Address + "<br/>";
				if (event.Location.offcampus.CityStateZip) temp+= "\n"+ event.Location.offcampus.CityStateZip + "<br/>";
			temp+= "\n"+"	</a>";
		temp+= "\n"+"	</li>";
	}

	//other info
	if (event.categories.length > 0 ){
		temp += "<li class='categories'><strong>Calendars: </strong> ";
		var ctemp = "";
		$(jsonarray['d'].categories).each(function(){
			c = this;
			$(event.categories).each(function(){
				a = this
				if (c.CategoryID == a){
					if (ctemp != '') ctemp+= ", ";
					ctemp += "<span>" + c.CategoryName + "</span>";
				}
			});
			if (c.sub){
				$(c.sub).each(function(){
					a = this;
					$(event.categories).each(function(){
						sub = this;
						if (sub.CategoryID == a) {
							if (ctemp != '') ctemp+= ", ";
							ctemp += "<span>" + sub.CategoryName + "</span>";
						}
					});
				});
			}
		});
		temp += ctemp+ "</li>";
	}
	if (event.Sponsor) { temp += "<li class='Sponsor'><strong>Sponsor:</strong> "+event.Sponsor+"</li>"};
	if (event.Cost) { temp += "<li class='Cost'><strong>Cost:</strong> "+event.Cost+"</li>"};
	if (event.URL) { temp += "<li class='URL'><strong>Website:</strong> <a href='http://"+event.URL.replace("http://", "")+"' target='_blank'>"+event.URL+"</a></li>"};
	if (event.Image) { temp += "<li class='Image'>"+event.Image+"</li>"};

	temp+= "\n"+"		</ul>";
	temp+= "\n"+"		<div class='LongDescription'><div class='loading'>Loading Description</div></div>";
	temp+= "\n"+"	</div>";
	temp+= "\n"+"</li>";

	return temp;
}

function eventsrender(d) {
	var titletext = ( dateFormat(d, "fullDate") );
	$("h2 span").text(titletext);
	document.title = "Events for " + titletext + " - Drew University";

	$("#eventslist").empty();	

	var e = jsonarray[d.getFullYear()+""+d.getMonth()];

	var z = 0;
	for (x=0;x<e.events.length;x++){
		if ( d.getDate() == e.events[x].StartDate.day ){
			z++;
			$("#eventslist").append( makeevent(e.events[x]) )
		}
	}
	if (z == 0) {
		$("#eventslist").append("<li>There are no events for the selected day.</li>");
	}
	
	if ( $("#eventslist li.event").length % 2){
		$("#eventslist li.event:nth-child(odd)").addClass("altrow");
	}else{
		$("#eventslist li.event:nth-child(even)").addClass("altrow");
	}
	bubblepop();
	attachclick();
	selectcats();
	showevents();
};

function GWEvent(eventid){
	//$.jGrowl(eventid);
	$.get("rtce_subscribe.php?eventid="+eventid, function(data){
		//$.jGrowl(data);
		if ( $("#"+eventid).length > 0 ) $("#"+eventid).append("<div id='notice"+eventid+"' style='display:block;' class='eventnotice'></div>");
		if (data == "login") {
			window.location = 'https://ichain.drew.edu/ICSLogin/?"http://'+ parseUri(window.location).host + "/calendar/?add=true&eventid="+eventid  +'"';
		} else if (data == "added"){
			$("#"+eventid+ " .gwlink .popup").text("Remove from GroupWise");
			$("#notice"+eventid).text("Event added to your calendar");
		} else if (data == "deleted"){
			$("#"+eventid+ " .gwlink .popup").text("Add to GroupWise");
			$("#notice"+eventid).text("Event removed from your calendar");
		}
		$("#notice"+eventid).fadeIn(1000).fadeTo(3000, 1).fadeOut();
	});
}

function attachclick(){
	//vcal 
	$(".vcallink").click(function(){
		window.location = "vcal.php?EventID=" + $(this).parents('.event').attr("id");
	});

	//edit
	$(".edit").click(function() {
		editevent($(this).parents('.event').attr("id"));
	});

	//delete
	$(".delete").click(function() {
		id = $(this).parents('.event').attr("id")
		
		if (confirm("Are you sure you want to delete '"+ $(this).parents(".event").find(".title").text() +"'?"+id)){
			//is this a recurring event, if so find all other and delete them
				//code to follow
			//send the list of events to be deleted. 
			$.get("delete.php?eventid=" + id, function (data){
				if (data.indexOf("Error") < 0 ) {
					//$.nyroModalManual({	content: "<p>The event has been removed.</p>"});
					nd = $("#cal1Container").datepicker( "getDate" )
					//if it was a reoccuring event flush all data and rebuild form the start month
					for (x=0;x<jsonarray.length;x++){
						if (jsonarray[x] != jsonarray['d']) jsonarray[x]=null;
					}
					showloader();
					geteventdata(nd);
				} else {
					$.nyroModalManual({
						content: "<span style='color:#000;'>"+data+"<br/> If you have any questions contact the <a href='mailto:webmaster@drew.edu'>Webmaster</a></span>"
					});
				}
			});
		}

	});

	//deal with the gW link
	$(".gwlink").click(function() {
		GWEvent($(this).parents('.event').attr("id"));
	}).each(function(){
		$(this).find(".popup").load("gwcheck.php?eventid="+ $(this).parents('.event').attr("id") );
	});
	
	//show the details
	$(".title").click(function(){
		var id = $(this).parents('li').attr("id");
		nd = new Date(	$("#cal1Container").datepicker("getDate") );
		if (
			"?date="+nd.getFullYear()+","+(nd.getMonth()+1)+","+nd.getDate()+"&eventid="+id
			==
			parseUri(window.location).anchor
		){
			$("#" + id + " .details").toggle();
		} else {
			$.historyLoad("?date="+nd.getFullYear()+","+(nd.getMonth()+1)+","+nd.getDate()+"&eventid="+id);
		}
	});
}
function showdetails(id){
	$("#" + id + " .LongDescription ").load( "eventdetails.php?eventid="+ id );
	$("#" + id + " .details").toggle();
}

function findparent(event, d){
	t = false;
	$(jsonarray[d.getFullYear()+""+d.getMonth()].events).each(function(){
		if (this.EventId == event.ParentId){
			t = this
		}
	});
	return t;
}

function editevent(id){
	//get the date
	d = $("#cal1Container").datepicker( "getDate" )
	
	var event;
	
	$(jsonarray[d.getFullYear()+""+d.getMonth()].events).each(function(){
		if (this.EventId == id){
			event = this;
		}
	});

	if (event.RecurringFrequency != "None"){
		d = new Date(event.StartDate.year,(event.StartDate.month-1),event.StartDate.day)
		
		t = findparent(event, d);
		if (t) {
			event = t;
		}else{
			d.setMonth( d.getMonth() - 1);
			t = findparent(event, d);
			if (t){
				event = t;
			}else{
				$(jsonarray).each(function(){
					$(this.events).each(function(){
						if (this.EventId == event.ParentId){
							event = this;
						}
					});
				});
			}
		}
		
	}
	
	//$("#dumphere").html(dump(event,false));
	
	//reset the form 
	$("#editevent").resetForm();
	$("form #starttime").show();
	$("form #endtime").show();		
	$("form #to").show();		


	//populate the form
	var ed = tinyMCE.get('bodydetail');
	ed.setContent('');

	$("#submit").attr("disabled","").val("Update Event");
	
	$("#eventid").val(id);
	$("#parentid").val(event.ParentId);
	$("#jsonid").val(id);

	$("#title").val(event.Title.replace(/&amp;/g, '&').replace(/&quot;/g, '"'));

	//add the date and time
	startdate = new Date(event.StartDate.year, (event.StartDate.month -1), event.StartDate.day, event.StartDate.hour, event.StartDate.minute, 0)
	enddate = new Date(event.EndDate.year, (event.EndDate.month -1), event.EndDate.day, event.EndDate.hour, event.EndDate.minute, 0)
	$("#startdate").val( startdate.format("m/d/yyyy") );
	if (event.AllDay == true){
		$("#allday").attr("checked","checked");
		$("form #starttime").hide();
		$("form #endtime").hide();
		$("form #to").hide();
	} else {
		$("#allday").attr("checked","");
		$("form #starttime").show();
		$("form #endtime").show();
		$("form #to").show();
	}
	
	if (event.StartDate.hour > 0){
		$(".starttime").val( startdate.format("shortTime") );
	} else {
		$(".starttime").val("");
	}
	if (event.EndDate.hour > 0){
		$(".endtime").val( enddate.format("shortTime") );
	} else {
		$(".endtime").val("");
	}
	
	$("#sponsor").val(event.Sponsor);
	$("#cost").val(event.Cost);
	$("#url").val(event.URL);

	if (event.Location.oncampus != null) { 
		if (event.Location.oncampus.Building != '') {	$("[value='" + event.Location.oncampus.Building + "']").attr("selected","selected") };
		$("#room").val(event.Location.oncampus.Room);
		$("#other").val(event.Location.oncampus.Other);
		
		$("#name").val("");
		$("#address").val("");
		$("#csz").val("");
		
		$("#location").tabs("select", '#oncampus');
		
	} else if (event.Location.offcampus != null){
		$("#locaiton [selected='selected']").attr("selected","");
		$("#room").val("");
		$("#other").val("");
	
		$("#name").val(event.Location.offcampus.Name);
		$("#address").val(event.Location.offcampus.Address);
		$("#csz").val(event.Location.offcampus.CityStateZip);

		$("#location").tabs("select", '#offcampus');
	}
	
	//set the categories 
	
	for (x=0;x<event.categories.length;x++){
		$("#categorylist input[value='"+event.categories[x]+"']").attr("checked","checked");
	}	

	$("#ContentApproved input[value='" + event.Approved + "']").attr("checked","checked").click();
	$("#BookingApproved input[value='" + event.RoomApproved + "']").attr("checked","checked").click();
	$("#BookingApproved input[value='" + event.RoomApproved + "']").attr("checked","checked").click();

	if (event.HoldTheDate == "Y") {
		$("#EventHoldTheDate").attr("checked","checked");
	} else { 
		$("#EventHoldTheDate").attr("checked","");
	}
	if (event.HoldTheDateImportant == "Y") {
		$("#EventHoldTheDateImportant").attr("checked","checked");
	}else{
		$("#EventHoldTheDateImportant").attr("checked","");
	}
	
	//Put in the reoccuring info
	
	$("#Recurring option[value='" + event.RecurringFrequency + "']").attr("selected","selected");
	$("#Recurring").change();
	
	switch (event.RecurringFrequency) {
		case "Daily":
			$("#Recurring_daily option[value='" + event.RecurringVariableA + "']").attr("selected","selected");
		break;
		
		case "Weekly":
			$("#RecurringVariableA_weekly option[value='" + event.RecurringVariableA + "']").attr("selected","selected");

			$("#Weekly input").clearFields();
			var dayarray = event.RecurringVariableB.split(",");
			for (x=0;x<dayarray.length;x++){
				$("#Weekly input[value='" + dayarray[x] + "']").attr("checked","checked");
			}
		break;
		
	} 
	$("#RecurringEndDate").val( event.RecurringEndDate );
	

	//get the main body
	$.get("eventdetails.php?eventid="+ id, function(data){
		var ed = tinyMCE.get('bodydetail');
		ed.setContent(data);
	});
	
	//expose the form and overlay it on the main page. 
	showeditor();
}
function showloader(){
	$("#loading").show();
	$("#cal1Container").show();
	$("#today").hide();
	$("#editevent").hide();
	$("#addyourevent").hide();
	$("#datetitle").hide();
	$("#eventslist").hide();
}
function showevents(){
	$("#editevent").hide();
	$("#loading").hide();
	$("#today").show();
	$("#addyourevent").show();
	$("#cal1Container").show();
	$("#datetitle").show();
	$("#eventslist").show();
}
function showeditor(){
	$("#submit").attr("disabled","");
	$("#editevent").show();
	$("#today").hide();
	$("#loading").hide();
	$("#addyourevent").hide();
	$("#cal1Container").hide();
	$("#datetitle").hide();
	$("#eventslist").hide();
}

function selectcats(){
	li = $(this).parent();
	a = $(this);
	
	a.toggleClass("SelectedAnchor");
	
	//does this item have children
	
	if (li.find("li").length > 0){
		if (a.hasClass("SelectedAnchor")){
			li.find("li a").addClass("SelectedAnchor");
		} else {
			li.find("li a").removeClass("SelectedAnchor");
		}
	}
	
	//hide all the events and then loop the list for whats active and only show those. also rezebra the list. 
	$(".event").show();

	$("#categoriesmenu ul a:not(.SelectedAnchor)").each(function(){
		$("."+$(this).parent().attr("id")).hide();
	});

	$(".event").removeClass('altrow');
	

	

	li = $(".event:visible");
		
	if ( li.length % 2){
		$(".event:visible:even").addClass("altrow");
	}else{
		$(".event:visible:odd").addClass("altrow");
	}

	
}
function bubblepop () {
	$('.bubbleInfo').each(function () {
		// options
		var distance = 10;
		var time = 150;
		var hideDelay = 100;
		
		var hideDelayTimer = null;
		
		// tracker
		var beingShown = false;
		var shown = false;
		
		var trigger = $('.trigger', this);
		var popup = $('.popup', this).css({'opacity':0});
		
		// set the mouseover and mouseout on both element
		$([trigger.get(0), popup.get(0)]).mouseover(function () {
			// stops the hide event if we move from the trigger to the popup element
			if (hideDelayTimer) clearTimeout(hideDelayTimer);
			// don't trigger the animation again if we're being shown, or already visible
			if (beingShown || shown) {
				return;
			} else {
				beingShown = true;
				// reset position of popup box
				popup.css({
					top: -10,
					left: -($(popup).width()/2),
					display: 'block' // brings the popup back in to view
				})
				.animate({
					top: '-=' + distance + 'px',
					opacity: 1
				}, time, 'swing', function() {
					// once the animation is complete, set the tracker variables
					beingShown = false;
					shown = true;
				});
			}
		}).mouseout(function () {
			// reset the timer if we get fired again - avoids double animations
			if (hideDelayTimer) clearTimeout(hideDelayTimer);
		
			// store the timer so that it can be cleared in the mouseover if required
			hideDelayTimer = setTimeout(function () {
				hideDelayTimer = null;
				popup.animate({
					top: '-=' + distance + 'px',
					opacity: 0
				}, time, 'swing', function () {
					// once the animate is complete, set the tracker variables
					shown = false;
					// hide the popup entirely after the effect (opacity alone doesn't do the job)
					popup.css('display', 'none');
				});
			}, hideDelay);
		});
	});
}

$(document).ready(function(){
	//push the url into a #to enable the history
	var query = window.location + "";
	anchor = parseUri(query.toLowerCase()).anchor;
	if ( parseUri(query).queryKey.eventid){
		rd = parseUri(window.location).protocol+ "://";
		rd+= parseUri(window.location).host;
		rd+= parseUri(window.location).path;
		rd+="#?eventid="+parseUri(query).queryKey.eventid;
		if ( parseUri(query).queryKey.add) rd+="&add=true";
		window.location = rd
	}

	//init the enviroment vars and set up the html

	//today button
	$("#today").click(function(){
		d = new Date();
		//selectDate(d)
		$.historyLoad("?date="+ d.getFullYear() +","+(d.getMonth()+1)+","+d.getDate());
	});

	//login button
	$("#loginbutton").click(function(){
		eid = '';
		if (parseUri(window.location).queryKey.eventid) eid = "?eventid="+parseUri(window.location).queryKey.eventid;
		window.location = 'https://ichain.drew.edu/ICSLogin/?"http://'+ parseUri(window.location).host + '/calendar/'+ eid +'"';
	});


	//begin the data load, (buildigns, catageories, user access), then finish init;
	$.getJSON("json-misc.php", function(json){
		jsonarray['d'] = json;
		
		$.historyInit(historyhandel);			

		if (parseUri(anchor).queryKey.eventid){
			firstload = 0;
		} else {
			firstload = 3;
		}
		//set the Calendar
		
		$("#cal1Container").datepicker({
			hideIfNoPrevNext: true,
			changeYear: false,
			changeMonth: false,
			changeFirstDay: false,
			createButton:false,		
			beforeShowDay:CheckIfHasEvent,
			onSelect: calendarclick,
			onChangeMonthYear: function(year, month){
				if (firstload < 2) {
					firstload++;
				} else {
					$.historyLoad("?date="+ year +","+ month +",1");
				}
			}
		}); 
		
		
		//generate a catagory list
		c = json.categories;
		/*
		$("#Menu").append("<ul id='categoriesmenu'><li><a>Calendars</a><ul></ul></li></ul>")
		for (a=0;a<c.length;a++){
			$("#categoriesmenu ul:eq(0)").append("\n<li id='cat_"+c[a].CategoryID+"'><a  class='SelectedAnchor'>"+c[a].CategoryName+"</a></li>");
			if (c[a].sub){
				$("#cat_"+c[a].CategoryID).append("\n\t<ul class='MenuShowMe'>\n\t</ul>")
				for (b=0;b<c[a].sub.length;b++){
					$("#cat_"+c[a].CategoryID +" ul ").append("\n\t\t<li id='cat_"+c[a].sub[b].CategoryID+"' title='subcat'><a  class='SelectedAnchor'   >"+c[a].sub[b].CategoryName+"</a></li>");
				}
			}
		}
		$("#categoriesmenu a").click(selectcats);
		*/
		//put the categories into the editor
		for (a=0;a<json.categories.length;a++){
			if (
					( c[a].Class != 'N' && jsonarray['d'].userlevel.Categories == 'Y') 
					||
					( c[a].Class == 'N' )
			){
				$("#categorylist").append("\n\t<label><input type='checkbox' name='Categories[]' id='Categories[]' value='" + json.categories[a].CategoryID + "' />" + json.categories[a].CategoryName + "</label>");
				if (json.categories[a].sub){
					for (b=0;b<json.categories[a].sub.length;b++){
						$("#categorylist input[value="+json.categories[a].CategoryID+"]").parent().after("\n\t<label class='sub'><input type='checkbox' name='Categories[]' id='Categories[]' value='" + json.categories[a].sub[b].CategoryID + "' />" + json.categories[a].sub[b].CategoryName + "</label>");
					}
				}
			}
		}

		tcats = $("#categorylist label").length;
		tcats = Math.round(tcats/3)
		$("#categorylist label:lt("+ (tcats) +")").wrapAll("<div></div>");
		$("#categorylist label:lt("+ (tcats * 2) +"):gt("+ (tcats -1) +")").wrapAll("<div></div>");
		$("#categorylist label:gt("+ ((tcats * 2) -1) + ")").wrapAll("<div></div>");
		
		//put the building list into the edit form selector
		for (var i in json.buildings) {
			$("#editevent #Building").append("\n<option value='" + i + "'>" + json.buildings[i] + "</option>")
		}

		var query = window.location + "";
		query = query.toLowerCase();
	
		//if the url has a eventid in it then look it up via ajax othewise procede as normal

		anchor = parseUri(query).anchor.toLowerCase();
		
		if (parseUri(anchor).queryKey.eventid){
			eventid = parseUri(anchor).queryKey.eventid;
			qs = "eventid="+eventid;
			$.get("eventlookup.php", qs, function(data){
				if (data != ''){
					data = data.split("-");
					d = new Date(data[0],(data[1]-1),data[2]);
					geteventdata (d,eventid);
				} else {
					d = new Date();
					$.historyLoad("?date="+ d.format("yyyy,mm,dd"));
				}
			});
		} else {
			//load the events for this month
			d = new Date();
			$.historyLoad("?date="+ d.format("yyyy,mm,dd"));
		}

		//Form approvals
		userlevel = jsonarray['d'].userlevel;
		
		if (userlevel.ContentAprover == 'Y'){
			$("#ContentApproved").show();
		}else{
			$("#ContentApproved").hide();
		}
		
		if (userlevel.Booking == 'Y'){
			$("#BookingApproved").show();
		}else{
			$("#BookingApproved").hide();
		}
		
		if (userlevel.Superuser == 'Y'){
			$("#holdthedate").show();
		}else{
			$("#holdthedate").hide();
		}
		
	});

	//set up the editor
		//commands

			//new event
			$("#addyourevent").click(function(){
				showeditor()
				$("#submit").attr("disabled","").val("Add Event");
				$("#editevent").resetForm();
				$("form #starttime").show();
				$("form #endtime").show();		
				$("form #to").show();		
				$("#eventid").val("");
				$("#bodydetail").empty();
				var ed = tinyMCE.get('bodydetail');
				ed.setContent('');
			});

			//cancel editing
			$("#editevent #cancel").click(showevents);

			//add/edit an event
			$("#editevent #submit").click(function (){
				var ed = tinyMCE.get('bodydetail');
				$("#bodydetail").text(ed.getContent());
				$("#submit").attr("disabled","disabled");
				$('#editevent').ajaxSubmit({ 
					//target:     '#dumphere', 
					url:       'add.php', 
					type:		'POST',
					success:    function(data) { 
						//if there was an error show it. and stop.
						if (data.indexOf("Error:") >= 0 ) {
							$.nyroModalManual({
								content: "<span style='color:#000;'>"+data+"<br/> If you have any questions contact the <a href='mailto:webmaster@drew.edu'>Webmaster</a></span>"
							});
						}else{
							sd = $("#startdate").val().split("/");
							nd = new Date (sd[2],(sd[0]-1),sd[1]);
							if ($("#Recurring").fieldValue() == 'None'){
								//if it was a single event, flush that month and rebuild
								jsonarray[sd[2]+""+(sd[0]-1)] = null;
								geteventdata(nd);
							}else{
								//if it was a reoccuring event flush all data and rebuild form the start month
								for (x=0;x<jsonarray.length;x++){
									if (jsonarray[x] != jsonarray['d']) jsonarray[x]=null;
								}
								geteventdata(nd);
							}
						}
					} 
				}); 	
			});
		//tabs
			$("#location").tabs({
				 panelTemplate: '<fieldset></fieldset>' 
				,select: function(event, ui) { 
					//$.jGrowl(ui.tab);
					$("#onoffcampus").val(parseUri(ui.tab).anchor);
					return true;
				}

			});
		//time and date
			$(".startdate").datepicker();
			$(".starttime").clockpick({
					starthour : 8,
					endhour : 23,
					showminutes : true,
					minutedivisions : 4
				});
			$(".endtime").clockpick({
				starthour : 8,
				endhour : 23,
				showminutes : true,
				minutedivisions : 4
			});
			$("form #allday").change(function () {
			if ($("form #allday:checked").length == 1) {
				$("form #starttime").hide();
				$("form #endtime").hide();
				$("form #to").hide();
			} else {
				$("form #starttime").show();
				$("form #endtime").show();		
				$("form #to").show();		
			}
		});

			$("#RepeatOptions").hide()
			$("#Recurring").change(function(){
				switch($("#Recurring option:selected").val()){
					case "None":
						$("#RepeatOptions").hide();
					break;
		
					case "Daily":
						$("#RepeatOptions").show();
						$("#Daily").show();
						$("#Weekly").hide();
					break;
		
					case "Weekly":
						$("#RepeatOptions").show();
						$("#Daily").hide();
						$("#Weekly").show();
					break;
				}
			})
			$("#RecurringEndDate").datepicker();
		//Approvals
			$("#editevent #ContentApproved input").click(function(){
				$("#editevent #ContentApproved").removeClass().addClass($(this).val());
			})
		
			$("#editevent #BookingApproved input").click(function(){
				$("#editevent #BookingApproved").removeClass().addClass($(this).val());
			})
});