// current scroll position of image list; this is the left offset of the list
var scrollPos = 0;

var scrollLeft = -1;
var scrollStop = 0;
var scrollRight = 1;

/**
 *	The jQuery $(document).ready function, executed when document is loaded.
 */
$(function()
{
	// set up fancybox plugin for displaying certain types of content for those pages that contain student work
	// also, if the page contains a series of works, set up a scrolling carousel for displaying them
	if ($('#base_content').children()[1].id == "studentwork")
	{
		// studentwork div is present
		// make all anchor tags for showing large images display the large images using the FancyBox plugin
		$('a.larger_image').fancybox({
							  'padding'				: 0,
							  'overlayColor'		: '#fff',
							  'overlayOpacity'		: 0.9
		});
		
		// if the unordered list in the studentwork div contains 1 or more items, make an image carousel
		if ($('#studentwork_list div').get().length > 0)
		{
			makeImageCarousel();
		}
	}
});


/**
 *	Function to show/hide subcategory menus on rollover of one of the 4 main categories.
 *
 *	@param	categoryID	css ID of chosen category
 */
function showCategory(categoryID)
{
	// retrieve the selected category div element
	var selectedCatDiv = document.getElementById(categoryID);
	
	// hide all category divs initially
	document.getElementById('makecat').style.position = 'absolute';
	document.getElementById('makecat').style.left = '-4000px';
	document.getElementById('writecat').style.position = 'absolute';
	document.getElementById('writecat').style.left = '-4000px';
	document.getElementById('teachcat').style.position = 'absolute';
	document.getElementById('teachcat').style.left = '-4000px';
	document.getElementById('learncat').style.position = 'absolute';
	document.getElementById('learncat').style.left = '-4000px';
	
	// now show only the selected category div
    selectedCatDiv.style.position = 'relative';
    selectedCatDiv.style.left = '0px';
}


/**
 *	Function for creating a horizontal sliding image carousel for student work.
 */
function makeImageCarousel()
{
	// the studentwork div that contains the student work
	var div = $('#studentwork');
	
	// initialize scrollpoint to 0 (start of list)
	scrollPos = 0;
	
	// default speed to scroll image list (10 ms intervals)
	var interval = 20;
	
	// the left position of the studentwork div relative to the left side of the browser window
	var studentworkDivLeft = 0;
	
	// the width of the studentwork div, as defined by the css
	var studentworkDivWidth = parseInt(div.css('width'));
	
	// midpoint of studentwork div
	var studentworkDivMidpoint;
	
	// get all img elements inside the list
	var images = $('ul img');

	// get the image maps that may be present
	var imageMaps = $('div.scrollItem map area');
	
	// get all text elements in paragraph elements with "scroll_p" attribute
	var text = $('p.scroll_p');
	
	// handle for scrolling function, assigned to value of setInterval when scrolling is started,
	// and passed to clearInterval function to stop scrolling
	var scrollFn;

	// the direction of scrolling
	// 	-1: scroll left
	//	 0: stop scrolling
	//	 1: scroll right
	var direction = scrollStop;
	
	// align the bottoms of all divs in the student work list with the bottom of the studentwork container
	bottomAlignStudentWorkDivs($('#studentwork_list li'));
	
	// get value of offsetLeft property of studentwork div, which is the left position of the div relative
	// to the browser window; this value is necessary for calculating the midpoint of the studentwork div;
	// use the mousemove event of studentwork div in order to get the value of ofsetLeft
	// using div.offsetLeft will not retrieve the offsetLeft value
	div.mousemove(function(e)
	{
		studentworkDivLeft = this.offsetLeft;
	});
	
	// control scrolling as mouse is moved over an image	
	images.mousemove(function(e)
	{
		// stop scrolling
		clearInterval(scrollFn);
		
		// calculate midpoint of studentwork div element, relative to browser window
		studentworkDivMidpoint = (studentworkDivLeft + studentworkDivWidth / 2);
		
		// if mouse cursor is over an image in the left half of studentwork div element, scroll towards right
		// otherwise, scroll towards left	
		if (e.pageX < studentworkDivMidpoint)
		{
			// set scroll direction to right
			direction = scrollRight;
		}
		else
		{
			// set scroll direction to left
			direction = scrollLeft;
		}
		
		// adjust scrolling speed based on x coordinate within studentwork div
		// leftmost & rightmost quarters of div are hotspots for speeding up scrolling
		// center half of div is hotspot for default scrolling speed
		if (e.pageX < studentworkDivMidpoint - studentworkDivWidth / 4 || e.pageX > studentworkDivMidpoint + studentworkDivWidth / 4)
		{
			// use quadruple scrolling speed, and scroll in appropriate direction
			scrollFn = setInterval("scrollImageList(" + direction + ")", interval / 4);
		}
		else
		{
			// use default scrolling speed, and scroll in appropriate direction
			scrollFn = setInterval("scrollImageList(" + direction + ")", interval);
		}
	});
	
	// control scrolling as mouse is moved over an image map	
	imageMaps.mousemove(function(e)
	{
		// stop scrolling
		clearInterval(scrollFn);
		
		// calculate midpoint of studentwork div element, relative to browser window
		studentworkDivMidpoint = (studentworkDivLeft + studentworkDivWidth / 2);
		
		// if mouse cursor is over an image in the left half of studentwork div element, scroll towards right
		// otherwise, scroll towards left	
		if (e.pageX < studentworkDivMidpoint)
		{
			// set scroll direction to right
			direction = scrollRight;
		}
		else
		{
			// set scroll direction to left
			direction = scrollLeft;
		}
		
		// adjust scrolling speed based on x coordinate within studentwork div
		// leftmost & rightmost quarters of div are hotspots for speeding up scrolling
		// center half of div is hotspot for default scrolling speed
		if (e.pageX < studentworkDivMidpoint - studentworkDivWidth / 4 || e.pageX > studentworkDivMidpoint + studentworkDivWidth / 4)
		{
			// use quadruple scrolling speed, and scroll in appropriate direction
			scrollFn = setInterval("scrollImageList(" + direction + ")", interval / 4);
		}
		else
		{
			// use default scrolling speed, and scroll in appropriate direction
			scrollFn = setInterval("scrollImageList(" + direction + ")", interval);
		}
	});
	
	// stop scrolling if user clicks on an image map
	imageMaps.click(function(e)
	{
		// stop scrolling
		clearInterval(scrollFn);
	});
	
	// stop scrolling when mouse cursor is moved onto a caption, and center the div containing the image & caption
	// in the studentwork div
	text.mouseover(function(e)
	{
		// stop scrolling
		clearInterval(scrollFn);
	});
}


/**
 *	Align the bottoms of the list item divs in the studentwork container div.
 *	This is accomplished by increasing the top margins of the divs with respect to their container. 
 */
function bottomAlignStudentWorkDivs(divArray)
{
	// distance to shift down is the height of the studentwork div - the height of the tallest list item div
	var deltaY = parseInt($('#studentwork').css('height')) - getMaxDivHeight(divArray);
	
	// increase each div in the list by deltaY
	for (var i = 0; i < divArray.length; i++)
	{
		// new top margin for div
		var newTopMargin = parseInt($(divArray[i]).css('margin-top')) + deltaY + "px";
		
		// set the top margin in the CSS
		$(divArray[i]).css('margin-top', newTopMargin);
	}
}


/**
 *	Get the height of the tallest div in the specified div array.
 */
function getMaxDivHeight(divArray)
{
	// start max height found at 0
	var maxHeight = 0;
	
	// traverse the array to find the tallest div
	for (var i = 0; i < divArray.length; i++)
	{
		if (divArray[i].clientHeight > maxHeight)
		{
			// new max height found
			maxHeight = divArray[i].clientHeight;
		}
	}
	
	// return height of tallest div
	return maxHeight;
}


/**
 *	Function for scrolling a horizontal list containing images and associated caption text.
 *
 *	@param	direction	indicates whether the list should scroll towards the left (-1) or the right (1)
 *						values other than -1 or 1 have no effect
 */
function scrollImageList(direction)
{
	// get div layer and unordered list elements for faster access
	var div = $('#studentwork');
	
	// get left padding of list items
	var liPaddingLeft = parseInt($('#studentwork_list li').css('padding-left'));
	
	// get right padding of list items
	var liPaddingRight = parseInt($('#studentwork_list li').css('padding-right'));
	
	// the width of the entire list
	// this width is calculated by summing the widths of all the div elements in the list
	var listWidth = 0;
	
	// number of pixels to scroll
	var increment = 2;
	
	// min scroll position
	var minPos = 0;
	
	// calculate width of entire list
	for (var i = 0; i < $('#studentwork_list li div').get().length - 1; i++)
	{
		listWidth += liPaddingLeft + $('#studentwork_list li div').get(i).clientWidth + liPaddingRight;
	}
	
	// scroll list
	if (direction == -1)
	{
		// scroll left 10 pixels, but don't go past left end of list
		div.scrollLeft(scrollPos + increment > listWidth ? scrollPos = listWidth : scrollPos += increment);
	}
	else if (direction == 1)
	{
		// scroll right 10 pixels, but don't go past right end of list
		div.scrollLeft(scrollPos - increment < minPos ? scrollPos = minPos : scrollPos -= increment);
	}
}


/**
 *	Function for jumping to the image at the specified position in a scrollable image menu.
 *	This function depends on each list item in the menu containing a div element that contains
 *	the image and the associated caption text
 *
 *	@param	index	an index into a zero-based array; e.g., the first image is at index 0
 */
function jumpToImage(index)
{
	// get left padding of list items
	var liPaddingLeft = parseInt($('#studentwork_list li').css('padding-left'));
	
	// get right padding of list items
	var liPaddingRight = parseInt($('#studentwork_list li').css('padding-right'));
	
	// offset to jump to
	var offset = 0;
	
	// calculate the distance to jump based on the position
	// offset = sum of (padding + div width) for all divs before pos
	for (var i = 0; i < index; i++)
	{
		offset += liPaddingLeft + $('div.scrollItem').get(i).clientWidth + liPaddingRight;
		
		// haven't figured out where these pixels are coming from yet, but they are necessary for centering divs
		offset += 4;
	}
	
	// final adjustment
	offset += liPaddingLeft;
	
	// calculate the difference in width between list item div and studentwork div container
	var deltaWidth = $('div.scrollItem').get(i).clientWidth - parseInt($('#studentwork').css('width'));
	
	// adjust offset by delta width to center div
	if (deltaWidth < 0)
	{
		// list item div width < studentwork div width; shift right half the difference
		offset -= -deltaWidth / 2;
	}
	else
	{
		// list item div width > studentwork div width; shift left half the difference
		offset += deltaWidth / 2;
	}
	
	// update scrollPos so if user mouses over image list, scrolling begins from current position
	scrollPos = offset;
	
	// scroll studentwork div to specified image
	$('#studentwork').scrollLeft(offset);
}


/**
 *	Return the index of the image in the list over which the mouse cursor is currently located.
 *
 *	@param	divPos	the absolute position of the mouse cursor in the studentwork div
 */
function getImageIndex(divPos)
{
	// get left padding of list items
	var liPaddingLeft = parseInt($('#studentwork_list li').css('padding-left'));
	
	// get right padding of list items
	var liPaddingRight = parseInt($('#studentwork_list li').css('padding-right'));
	
	// stores cumulative width; to find the div element in the list the widths & padding of
	// the div elements in the list must be summed until divPos is reached
	var cumulativeWidth = liPaddingLeft;
	
	// get all div elements inside the list
	var divs = $('div.scrollItem');
	
	// calculate cumulative width, starting with first div element in list
	for (var i = 0; i < divs.length; i++)
	{
		// increment cumulative width by div width + left & right padding
		cumulativeWidth += liPaddingLeft + divs.get(i).clientWidth + liPaddingRight;
		
		// check to see if divPos has been reached
		if (scrollPos + divPos < cumulativeWidth)
		{
			// divPos reached; return index of div in list
			return i;
		}
	}
	
	// return image of last div element in list
	return i - 1;
}


/**
 * Function to enable swf videos to play in FancyBox window.
 * To ensure the FancyBox window is the proper size, the dimensions of the video must be provided.
 *
 * @param	href	the URL to the SWF video to be played
 * @param	width	width of the SWF video
 * @param	height	height of the SWF video
 */
function showPopupSWF(href, width, height)
{
	// call FancyBox plugin with the specified URL and dimensions
	$.fancybox({
			'padding'				: 0,
			'overlayColor'			: '#fff',
			'overlayOpacity'		: 0.9,
			'autoScale'				: true,
			'autoDimensions'		: true,
			'transitionIn'			: 'none',
			'transitionOut'			: 'none',
			'width'					: width,
			'height'				: height,
			'href'					: href,
			'type'					: 'swf',
			'swf'					: {
				'wmode'				: 'transparent',
				'allowfullscreen'	: 'true'
			}
		});
}


/**
 * Function to enable applets to play in FancyBox window.
 * To ensure the FancyBox window is the proper size, the dimensions of the video must be provided.
 * For applets, the type must be set to 'iframe'.
 *
 * @param	href	the URL to the applet to be played
 * @param	width	width of the applet
 * @param	height	height of the applet
 */
function showPopupApplet(href, width, height)
{
	// call FancyBox plugin with the specified URL and dimensions
	$.fancybox({
			'padding'				: 0,
			'margin'				: 0,
			'overlayColor'			: '#fff',
			'overlayOpacity'		: 0.9,
			'autoScale'				: true,
			'autoDimensions'		: true,
			'transitionIn'			: 'none',
			'transitionOut'			: 'none',
			'width'					: width,
			'height'				: height,
			'href'					: href,
			'type'					: 'iframe'
		});
}


/**
 * Function to enable HTML pages to display in FancyBox window.
 * To ensure the FancyBox window is the proper size, the dimensions of the video must be provided.
 * Currently, the implementation is the same as showPopupApplet, but a separate function is provided
 * to allow for future divergence between how applets and HTML pages are handled.
 *
 * @param	href	the URL to the HTML page to be displayed
 * @param	width	width of the HTML content
 * @param	height	height of the HTML content
 */
function showPopupText(href, width, height)
{
	// call FancyBox plugin with the specified URL and dimensions
	$.fancybox({
			'padding'				: 0,
			'margin'				: 0,
			'overlayColor'			: '#fff',
			'overlayOpacity'		: 0.9,
			'autoScale'				: true,
			'autoDimensions'		: true,
			'transitionIn'			: 'none',
			'transitionOut'			: 'none',
			'width'					: width,
			'height'				: height,
			'href'					: href,
			'type'					: 'iframe'
		});
}
