
$(document).ready(function($) {


		/* Functionality for the home page modules
		--------------------------------------------------------*/
		(function() {

			var showFredTimeOut = null;
			var modules = $("#homeModules > li");
			var moduleData = []; //Module data will be stored here later
			
			var fadeSpeed = 120;
			var resizeSpeed = 300;

			var summaryFullWidth = 320;
			var summarySmallWidth = 270;
			var summaryHeight = 170;
			var summaryMargin = 20;
			var fullLargeWidth = 418;
			var fullLargeHeight = 278;

			var selectedModule; //Used as a reference to the currently selected module to open

			var shrinkToSmallSummary = true; //If this is true, when the shrink function is called it should shrink to the small summary view, if it's false, it means all items will be shrunk to the full summary view (with images)
			
			function initializeModules() {

				//Hide the full content divs
				modules.find("div.full").hide();
				
				//Apply link styling to the li summary and hide the summary anchors
				modules.find("div.summary").css("cursor", "pointer").find("a").hide();
				
				//Apply absolute positioning to the modules instead of floating them
				modules.css({
					float: "none",
					position: "absolute",
					bottom: 20,
					marginLeft:20
				});
				
				modules.each(function(i) {

					var startingLeftPosition = (summaryFullWidth + 2 + summaryMargin) * i; //The 2 is for border width
					var smallLeftPosition = (summarySmallWidth + 2 + summaryMargin) * i;
					
					var fullLeft = (summarySmallWidth + summaryMargin + 2) * i; //Calculates the left position of the module when it would be fully open
					
					//Initialize the data for this particular module
					moduleData[i] = {
						animating:                 false,                 //whether or not this particular module is currently animating
						atInitialState:            true,                  //whether or not this particular module is currently in it's initial state
						atSmallSummaryState:       false,                 //whether or not this item is currently in small summary state
						summaryVisible:            true,                  //whether or not the summary is visible
						summaryImageVisible:       true,                  //whether or not the summary image is visible
						itemResized:               false,                 //whether or not the item has been re-sized
						fullContentVisible:        false,                 //whether or not the full content layer is visible
						fullContentShadowsAdded:   false,                 //whether or not the full content layer has had drop-shadows applied
						startingLeftPosition:      startingLeftPosition,  //the starting left position of this module in its initial state
						smallSummaryLeftPosition:  smallLeftPosition,     //the base left position of the module when it's in small summary state
						fullLeftPosition:          fullLeft,              //the base left position of the module when it's at its fully open state
						lastCalledAnimation:       "shrink",              //the last animation type to happen
						elem:                      $(this)                //the jQuery object for this module
					};
					
					//Set the starting left position
					moduleData[i].elem.css("left", startingLeftPosition);

				});

			}
			
			function stopItemAnimation(item) {
				//Stop all animation on this item
				item.stop().find("div.summary, div.summary img, div.full").stop();
			}
		
			function growItem(item) {
			
				//Determine the item index of this item
				var itemIndex = modules.index(item);
				
				//Stop any animation that might be taking place on this item
				stopItemAnimation(item);

				//Start by fading out the summary
				fadeOutSummary();
				
				function fadeOutSummary() {
				
					moduleData[itemIndex].atInitialState = false;			

					var summaryDiv = item.find("div.summary");
				
					//Fade out the summary
					moduleData[itemIndex].summaryVisible = false;

					summaryDiv.fadeTo(fadeSpeed, 0, function() {
						
						summaryDiv.hide();
						resizeItem();
					
					});
				}
				
				function resizeItem() {
				
					// When the user expands the item, the signInLink is closed, if it was open.
					toggleFred();
						
					moduleData[itemIndex].itemResized = true;
					
					item.animate({
						width: fullLargeWidth,
						height: fullLargeHeight,
						left: moduleData[itemIndex].fullLeftPosition
					}, resizeSpeed, showFullContent);
					
				}
				
				function showFullContent() {
				
					//Add shadow divs for all browsers except <= IE6
					if (!($.browser.msie && $.browser.version < 7)) {
						item.css("overflow", "").append("<div class=\"shadow shadowTop\"></div><div class=\"shadow shadowLeft\"></div><div class=\"shadow shadowRight\"></div>");
						moduleData[itemIndex].fullContentShadowsAdded = true;
					}
					
					var fullDiv = item.find("div.full");
					
					//If the div is hidden, set opacity to 0 and show it
					if (String(fullDiv.css("display")).toLowerCase() == "none") {
						fullDiv.fadeTo(0, 0).show();
					}
					
					moduleData[itemIndex].fullContentVisible = true;

					fullDiv.fadeTo(fadeSpeed, 1, function() {
						fullDiv.css({opacity: ""}); //set opacity to empty (mostly for IE's benefit)

									});
				}
							}
			
			function shrinkItem(item) {

				//Determine the item index of this item
				var itemIndex = modules.index(item);
				
				//Stop any animation that might be taking place on this item
				stopItemAnimation(item);
				
				//Remove shadows if they're present
				item.find("div.shadow").remove();
				moduleData[itemIndex].fullContentShadowsAdded = false;

				if (moduleData[itemIndex].fullContentVisible) {
					fadeOutFullContent();
				}
				else {
					//If none of the above conditions are met, shrink to the small summary
					fadeOutImage();
				}
				
				function fadeOutFullContent() {
				
					var fullDiv = item.find("div.full");
					
					//If the div is hidden, set opacity to 0 and show it
					if (String(fullDiv.css("display")).toLowerCase() == "none") {
						fullDiv.fadeTo(0, 0).show();
					}
					
					fullDiv.fadeTo(fadeSpeed, 0, function() {
					
						// When the user shrinks the item, the signInLink is opened, if it was closed.
						toggleFred();


						moduleData[itemIndex].fullContentVisible = false;
					
						fullDiv.hide();
						resizeItem();
					
					});
					
				}
				
				function resizeItem() {
					
					var propertiesToAnimate = {height: summaryHeight};
					
					if (shrinkToSmallSummary) {
						propertiesToAnimate.width = summarySmallWidth;
						
						//Left position will depend on whether or not to small summary is before or after the selected item
						var leftOffset = 0;
						
						if (modules.index(item) > modules.index(selectedModule)) {
							leftOffset = fullLargeWidth - summarySmallWidth;
						}
						
						propertiesToAnimate.left = moduleData[itemIndex].smallSummaryLeftPosition + leftOffset;
					}
					else {
						propertiesToAnimate.width = summaryFullWidth;
						propertiesToAnimate.left = moduleData[itemIndex].startingLeftPosition;
					}
					
					if (shrinkToSmallSummary) {
						//Hide img first (if it's visible) and then animate
						item.find("div.summary img").hide();
						item.animate(propertiesToAnimate, resizeSpeed, function() {
							fadeInSummary();
						});
					}
					else {
						//animate
						item.animate(propertiesToAnimate, resizeSpeed, function() {
							fadeInSummary();
						});
					}

					moduleData[itemIndex].atInitialState = false;

				}
				
				function fadeInSummary() {

					var summaryDiv = item.find("div.summary");

					moduleData[itemIndex].itemResized = false;

					//If the div is hidden, set opacity to 0 and show it
					if (String(summaryDiv.css("display")).toLowerCase() == "none") {
						summaryDiv.fadeTo(0, 0).show();
					}

					summaryDiv.fadeTo(fadeSpeed, 1, function() {
						
						var summaryImage = summaryDiv.find("img");
						
						//If there's no image, we need to create a fake one in order to preserve the positioning/animation of all other modules...
						if (summaryImage.length < 1) {
							summaryImage = $("<img width=\"0\" height=\"0\" class=\"noImage\" />").css({width: 0, height: 0}).appendTo(summaryDiv);
						}
						
						moduleData[itemIndex].summaryVisible = true;
						
						if (!shrinkToSmallSummary) {
							moduleData[itemIndex].atInitialState = true;

							//If the image is hidden, set opacity to 0 and show it
							if (String(summaryImage.css("display")).toLowerCase() == "none") {
								summaryImage.fadeTo(0, 0).show();
							}
							
							item.find("div.fullSummaryText div.summaryText").removeAttr("style");

							summaryImage.fadeTo(fadeSpeed, 1);

						}
					});
				}
				
				function fadeOutImage() {
					
					var summaryDiv = item.find("div.summary");
					var summaryImage = summaryDiv.find("img");
						
					//If there's no image, we need to run a hidden animation on someting in order to preserve the positioning/animation of all other modules...
					if (summaryImage.length < 1) {
						summaryImage = $("<img width=\"0\" height=\"0\" class=\"noImage\" />").css({width: 0, height: 0}).appendTo(summaryDiv);
					}
					
					summaryImage.fadeTo(fadeSpeed, 0, function() {
						summaryImage.hide();
						resizeItem();
					});
				}

			}
			
			function toggleFred() {
				if (showFredTimeOut) {
					clearTimeout(showFredTimeOut);
				}
				showFredTimeOut = setTimeout(function()
				{
					if($("#homeModules .module.over").size() > 0) {
						if($("#userLogin").hasClass("disclosureOpen")) {
							$("#signInLink").trigger("click");
						}
					}
				},
				500);
			}
			
			var mouseTimer;
			var adTimer;
			
			modules.bind("mouseover", function(event) {

				clearTimeout(mouseTimer);

				var currentItem = $(this);

				if (currentItem.hasClass("over")) {
					return;
				}
				
				//Update classes
				modules.removeClass("over");
				currentItem.addClass("over");

				shrinkToSmallSummary = true;

				if (!selectedModule) {
					selectedModule = currentItem;
					currentItem.growHomeModule();
					modules.not(currentItem).shrinkHomeModule();
				}
				else if (selectedModule.get(0) == currentItem.get(0)) {
					//This item is currently open, shrink all modules to full summary size
					selectedModule = null;
					shrinkToSmallSummary = false;
					modules.shrinkHomeModule();
				}
				else {
					selectedModule = currentItem;
					currentItem.growHomeModule();
					modules.not(currentItem).shrinkHomeModule();
				}
				
				sprintHomePageModuleOpen = true;

			}).bind("mouseout", function(event) {

				clearTimeout(adTimer);
				
				var currentItem = $(this);
				
				if (!moduleData[modules.index(currentItem)].atInitialState) {
					
					mouseTimer = setTimeout(function() {
						selectedModule = null;
						shrinkToSmallSummary = false;
						modules.shrinkHomeModule();
						currentItem.removeClass("over");
						
						//Only clear this variable if Fred is closed.
						if (!($("#userLogin.disclosureOpen").length > 0 || $("#userLoggedIn").css("display") == "block")) {
							sprintHomePageModuleOpen = false;
						}
						
					}, 10);
					
				}

			});
			
			initializeModules();
			
			$.fn.growHomeModule = function() {
				return this.each(function() {
					growItem($(this));
				});
			}

			$.fn.shrinkHomeModule = function() {
				return this.each(function() {
					shrinkItem($(this));
				});
			}

		})();

	});


