
	//
	// Calendar Setup
	//
	$(document).ready(function() {


		//
		// On click of a calendar checkbox: if a title, expand all, if not
		// load up the selected calendar
		//
		$("ul.calendar_subnav li input[type='checkbox']").click( function() {
			var show = this.checked;
			if( $(this).parent('li').hasClass('calendar_title') ) {

				$(this).parent('li').siblings('li').show().find("input[type='checkbox']").each( function() {
					this.checked = show;
					toggleCalendar( $(this).attr('id'), show );
				});

			} else {

				toggleCalendar( $(this).attr('id'), show );
			}
		});


		//
		// On click of title label <div>, show/hide all of its sub-calendars
		//
		$("ul.calendar_subnav li.calendar_title").children('div, span').click( function() {

			$(this).closest('ul').children('li').not('.calendar_title').toggle();
			var symbol = ( $(this).parent().children('span').html() == '+' ) ? '&ndash;' : '+';
			$(this).parent().children('span').html(symbol);

		});


		//
		// On click of the details +/- for a particular event:
		// if the description contains a link trigger its click (and thus the carousel open)
		// otherwise expand the description to make it visible
		//
		$('a.toggler').live('click', function() {

			if( $(this).closest('.calendar_item').children('.calendar_desc').children('a').length ) {

				$(this).closest('.calendar_item').children('.calendar_desc').children('a').click();

			} else {

				$(this).text( ($(this).text() == '+') ? '-' : '+' ).closest('.calendar_item').children('.calendar_desc').slideToggle('slow');
			}
		});


		//
		// On mouseover/mouseout of an item highlight it with gray.
		//
		$('div.calendar_item').live('mouseover', function() {
			$(this).addClass('stripe');
		}).live('mouseout', function() {
			$(this).removeClass('stripe');
		});


		//
		// On click of a link in an event description, open the carousel
		// and load the link's contents there
		//
		$('.calendar_desc a').live('click', function() {
			var loc = $(this).attr('href');
			loadCarouselUrl(loc);
			return false;
		});


		//
		// launch date picker
	    //


		$("input.dcms-date").datepicker({
			dateFormat: 'yy-mm-dd',
			showOn: 'both',
			buttonImage: '/img/cal-icon.png',
			buttonImageOnly: true
		});


		//
		// attach event to clicking on a tag
		//
		$('a.clicktag').live('click', function() {
			var tag = $(this).text();
			clickTag(tag);
		});

	});


	//
	// toggleCalendar
	//
	// if we are showing this calendar, first decide if the data has been loaded
	// if so, simply show the events, if not queue up the ajax call to load the calendar data
	//
	// if not showing this calendar, hide all of its events.
	//
	// @param code - the code name of the calendar
	// @param show - true if we are turning this calendar on, false if we're turning it off.
	//
	function toggleCalendar( code, show ) {

		unclickTag();

		if( show ) {
			var $lbl = $('input#' + code).parent();
			if( $('div.' + code).length || $lbl.children('b').length ) {
				$('div.' + code).show();
			} else {
				var url = '/cal/load/';
				url += '?calendar=' + code;
				url += '&start=' + $('#start').val();
				url += '&stop=' + $('#stop').val();

				$lbl.parent('li').css('background', 'url(/img/loader.gif) no-repeat right top');
				dynamItLoadDataQueue( url, 'calendar', function(data) {
					eval( 'var gdata = ' + data + ';' );
					$lbl.append('<b> (' + gdata.length + ')</b>').parent('li').css('background', 'none').removeAttr('style');
					loadCalendar(data);
				});

			}
		} else {
			$('div.' + code).hide();
			$('ul.calendar_subnav').children('li').not('calendar_title').find('input:checked').each( function() {
				$('div.' + $(this).attr('id')).show();
			});
		}

		$('div.calendar_desc').filter('div.' + code).hide();

	hideDupes();
	
	}


	//
	// loadCalendar
	//
	// look at each event already in the calendar and through all of the events
	// we've loaded via ajax. while the ajaxed events have an earlier start time,
	// insert it before our current calendar event.
	//
	// if a loaded event has a later start time, go to the next existing event to
	// find where it fits.
	//
	// note that if a certain event has already been loaded by a previous calendar
	// we do not duplicate it, rather note it belongs to the new calendar as well.
	//
	// @param gdata - event data loaded via ajax in json format
	//
	function loadCalendar( gdata ) {
		eval( 'var gdata = ' + gdata + ';' );

		if( gdata.length ) {

			var j = 0;

			var $events = $("#events_table").children('div.calendar_item');
			var $e;

			for( var i = 0; i < $events.length; i++ ) {
				$e = $events.eq(i);

				while( j < gdata.length && parseInt(gdata[j]['starttime']) < parseInt($e.attr('stamp')) ) {

					var $cur = $("div[titlehash='" + gdata[j]['titlehash'] + "']");
					if( $cur.length && $cur.attr('stamp') == gdata[j]['starttime'] ) {
						$cur.addClass(gdata[j]['code']).show();
					} else {
						$e.before( calendarRow(gdata[j]) );
					}

					j++;

				}
			}

			while( j < gdata.length ) {

				var $cur = $("div[titlehash='" + gdata[j]['titlehash'] + "']");
				if( $cur.length && $cur.attr('stamp') == gdata[j]['starttime'] ) {
					$cur.addClass(gdata[j]['code']).show();
				} else {
					$("#events_table").append( calendarRow(gdata[j]) );
				}

				j++;
			}

		}

	hideDupes();
	
	}


	//
	// calendarRow
	//
	// build the html for a single calendar row.
	//
	// @param e - javascript object for a particular event
	// @return (string) html to display a single calendar row.
	//
	function calendarRow( e )  {

		var code = e['code'];
		var type = e['type'];
		var tags = '&nbsp;';
		if( e['where'].length ) {
			tags = e['where'].split('#');
			tags.shift();
			for( var i in tags ) {
				tags[i] = '<a href="javascript:;" class="clicktag">' + tags[i] + '</a>';
			}
			tags = tags.join(',');
		}

		var row = '' +
'<div class="calendar_item ' + code + ' ' + type + '" stamp="' + e['starttime'] + '" titlehash="' + e['titlehash'] + '">' +
'	<div class="calendar_date">' + date( "m\/d\/Y", e['starttime'] )+ ' </div>';

		if( type == 'news' ) {
			row += '' +
'		<div class="calendar_time">&nbsp;</div>';
		} else {
				
	    	if( e['startdate'] != e['enddate'] ) {

				if( e['startdate'] == date( "Y-m-d", e['endtime'] - 3601 ) ) {
					row += '' +
					'		<div class="calendar_time"> ALL DAY </div>';
				} else {
					row += '' +
					'		<div class="calendar_time"> to ' + date( "m\/d\/Y", e['endtime'] - 3601 ) + '</div>';
				}

			} else {
				row += '' +
				'	<div class="calendar_time">' + date( "h:i a", e['starttime'] ) + ' - ' + date( "h:i a", e['endtime'] ) + '</div>';
			}
		}
		row += '' +
'	<div class="calendar_name">' + e['title'] + '</div>' +
'	<div class="clr"></div>' +
'	<div class="calendar_desc">' + e['description'] + '</div>';
'</div>';

		return row;

	}


	function clickTag(tag) {
		$('div.calendar_tags').not('div.calendar_tags:contains(' + tag + ')').parent('.calendar_item').addClass('tagFilter').hide();
		$('div.calendar_filter').html('Viewing items tagged as <b><i>' + tag + '</i></b>. <a href="javascript:unclickTag()">Click here to remove filter</a>.');
	}

	function unclickTag() {
		$('.calendar_item.tagFilter').removeClass('tagFilter').show();
		$('div.calendar_filter').html('');
	}

	function loadCarouselUrl(url) {
		
		if (url.substring(19,0) == 'http://www.ccad.edu')
			urlfile = url.substr(19);
		else
			urlfile = url;

		urlfile = '/pages' + urlfile + '.php';
		
		dynamItLoadData(urlfile, '', function(data){
			output = '<div id="event"><div class="padd">' + data + '</div></div><div id="close"><a href="javascript:closeCarousel();"><img src="/img/btn-closeimg.png" alt="close" /></a></div>';
			$('#carousel').html(output);
			$('#carousel').slideDown('slow');
		});

		// Track page view with Google Analytics
		pageTracker._trackPageview(url);

	}

	function newsLinks(on) {
		var other = (on == 'News') ? 'Events' : 'News';
		$('#btnAll' + on).show();
		$('#btnAll' + other).hide();

	}

	function refreshCalendar(f) {
		var url = '/cal/display';
		url += '?start=' + f.start.value;
		url += '&stop=' + f.stop.value;

		$('ul.calendar_subnav li label input:checked').each(function() {

			url += '&q[]=' + $(this).attr('id');

		});


		location.href = url;
		return false;
	}
	
	// Hide duplicate calendar items
	function hideDupes() {
		$('div.calendar_item').each(function(){
			if( $(this).attr("titlehash") == $(this).prev('div.calendar_item').attr("titlehash") ) {
				$(this).hide();
			}
		});
	}