var homeImages = [], distData = [], imageCacher = [], ie6 = ($.browser.msie && $.browser.version.substr(0,1)<7);

homeImages = shuffleArray([
	"/_home/5d/images/slideshow/birds-of-paradise.jpg",
	"/_home/5d/images/slideshow/pine-forest.jpg",
	"/_home/5d/images/slideshow/lee-class.jpg",
	"/_home/5d/images/slideshow/formal-gardens.jpg",		
	"/_home/5d/images/slideshow/adams.jpg",
	"/_home/5d/images/slideshow/back-kerrwood.jpg",
	"/_home/5d/images/slideshow/leaves.jpg",
	"/_home/5d/images/slideshow/front-kerrwood.jpg",
	"/_home/5d/images/slideshow/library.jpg",
	"/_home/5d/images/slideshow/winter-hall.jpg",
	"/_home/5d/images/slideshow/observatory.jpg",
	"/_home/5d/images/slideshow/tv-hill.jpg",
	"/_home/5d/images/slideshow/sunset.jpg",
	"/_home/5d/images/slideshow/westmont-view.jpg",
	"/_home/5d/images/slideshow/beach.jpg"
]);
distData[0] = {img: shuffleArray([
	"/_home/5d/images/slideshow/chorus.jpg",
	"/_home/5d/images/slideshow/winter-lecture-hall.jpg",
	"/_home/5d/images/slideshow/dance.jpg",
	"/_home/5d/images/slideshow/rogers-class.jpg",
	"/_home/5d/images/slideshow/telescope.jpg",
	"/_home/5d/images/slideshow/gallery.jpg",
	"/_home/5d/images/slideshow/dancers.jpg",
	"/_home/5d/images/slideshow/violinist.jpg"])
};
distData[1] = {img: shuffleArray([
	"/_home/5d/images/slideshow/group-prayer.jpg",
	"/_home/5d/images/slideshow/christmas.jpg",
	"/_home/5d/images/slideshow/prayer-chapel.jpg",
	"/_home/5d/images/slideshow/beach-prayer.jpg",
	"/_home/5d/images/slideshow/communion.jpg",
	"/_home/5d/images/slideshow/prayer-circle.jpg",
	"/_home/5d/images/slideshow/chapel.jpg"])
};
distData[2] = {img: shuffleArray([
	"/_home/5d/images/slideshow/downtown.jpg",
	"/_home/5d/images/slideshow/bbq.jpg",
	"/_home/5d/images/slideshow/socializing.jpg",
	"/_home/5d/images/slideshow/urban-house.jpg",
	"/_home/5d/images/slideshow/van-kampen.jpg",
	"/_home/5d/images/slideshow/biking.jpg",
	"/_home/5d/images/slideshow/studying-on-rock.jpg"])
};
distData[3] = {img: shuffleArray([
	"/_home/5d/images/slideshow/outdoor-class.jpg",
	"/_home/5d/images/slideshow/microscope.jpg",
	"/_home/5d/images/slideshow/painting.jpg",
	"/_home/5d/images/slideshow/butler-class.jpg",
	"/_home/5d/images/slideshow/spring-sing.jpg",
	"/_home/5d/images/slideshow/track.jpg"])
};
distData[4] = {img: shuffleArray([
	"/_home/5d/images/slideshow/china.jpg",
	"/_home/5d/images/slideshow/beijing-subway.jpg",
	"/_home/5d/images/slideshow/india.jpg",
	"/_home/5d/images/slideshow/india-children.jpg",
	"/_home/5d/images/slideshow/india-children2.jpg",
	"/_home/5d/images/slideshow/orchestra-tour.jpg"])
};

// returns a random integer between l and h inclusively
function randInt(l, h) {
	return Math.floor(Math.random() * (h - l + 1)) + l;
}


// Consumes an array and returns an array with the same elements but in a random order
function shuffleArray(a1) {
	var a2 = [];
	for (var i = a1.length; i > 0; i--) {
		a2.push(a1.splice(randInt(0, i-1), 1)[0])		
	}
	return a2;
}

// Consumes an array, moves the first item to the end, and then returns that item
function cycleArray(a) {
	var r = a.shift();
	a.push(r);
	return r;
}

$(function() {
			
	// Slideshow functions
	var int, curDist = 0, firstDist = true, slideshowImages, slideshowNav = $("#slideshowNav li"), distDescDiv = $("#distDesc div"), distDescP = $("#distDesc p"), distTitleH = $("#distTitle h3"), distTitleDiv = $("#distTitle div");
	
	function preloadImages() {
		for (var i = 0; i < 5; i++) {
			imageCacher[i] = new Image();
			imageCacher[i].src = distData[i]['img'][0];
		}
	}
	
	function loadImage(url, container, cb) {
		var img = new Image();
		img.src = url;
		$(img).css("opacity", 0);
		container.append(img);
		
		if (img.complete) {
			$(img).fadeTo(2000, 1, callback);
		} else {		
			img.onload = function() {
				$(img).fadeTo(2000, 1, callback);
			}	
		}
		function callback() {
			container.css("background-image", "url(" + img.src + ")");
			$(img).remove();
			if (cb) {
				cb.call();
			}
		}
	}
	
	function loadDist(i, _this) {	
	
		var newWidth;
	
		loadImage(cycleArray(distData[i]['img']), slideshowImages, preloadImages);
		slideshowNav.removeClass("selected").find('.bg').css("opacity", .4);
		_this.addClass("selected").find('.bg').stop().css("opacity", .9);	
	
		if (firstDist) {
			distTitleH.html($("#distInfo").find("dt.dist" + i).html()).css("opacity", "0");
			setTimeout(function() {
				newWidth = distTitleH.outerWidth() - (ie6 ? 2 : 5);
				distTitleDiv.css({left: 0 - newWidth, width: newWidth});			  
			}, 300);
			setTimeout(function() {
				distDescP.html($("#distInfo").find("dd.dist" + i).html()).fadeIn(300);	
				distDescDiv.animate({left: "0px"}, 500);
				distTitleH.css("opacity", "1").type({time: 700, deviation: .5});
				distTitleDiv.delay(300).animate({left: "0"}, 500);
				firstDist = false;
			}, 500);
		} else {		
			distDescDiv.animate({left: "-928px"}, 300, function() {
				$(this).css("left", "928px");
				distDescP.fadeOut(300, function() { $(this).html($("#distInfo").find("dd.dist" + i).html()); }).delay(200).fadeIn(300);	
			}).delay(500).animate({left: "0px"}, 400);
			distTitleDiv.animate({left: "-" + distTitleDiv.width()}, 300);
			distTitleH.untype({time: 500, deviation: .5, callback: function() {  
				distTitleH.html($("#distInfo").find("dt.dist" + i).html());
				newWidth = distTitleH.outerWidth() - (ie6 ? 2 : 5);
				
				distTitleDiv.css({left: (0 - newWidth), width: newWidth});
				distTitleH.type({time: 700, deviation: .5});
				distTitleDiv.delay(300).animate({left: "0"}, 500);
			}});
		}
	}
	
	function loadNextDist() {
		curDist = (curDist == 5) ? 1 : curDist + 1;

		loadDist(curDist - 1, slideshowNav.eq(curDist - 1));
	}
	
	int = setInterval(loadNextDist, 10000);	
	
	slideshowImages = $('#slideshowImages');
	loadImage(homeImages[0], slideshowImages, preloadImages);
	
	slideshowNav.each(function(i) {
		$(this).find('.bg').show().css({"opacity":.4, "left":$(this).width()}).delay((i+1)*150 + 1000).animate({"left": 0}, 333);
		$(this).find('.text').delay((i+1)*150 + 1000).fadeIn(150);
	}).hover(function() {
		if (!$(this).hasClass("selected")) {	
			$(this).find('.bg').stop(false, true).css("opacity", .75);
		}
	}, function() {
		if (!$(this).hasClass("selected")) {
			$(this).find('.bg').fadeTo(150, .4);
		}
	}).each(function(i) {
		$(this).click(function() {
			if (!$(this).hasClass("selected")) {
				clearInterval(int);
				loadDist(i, $(this));
			}
		});
	});
	
	
	// Sends Google Analytics Info for clicking on the Social Network Icons * * */
	$('#social a').click(function() {
		_gaq.push(['_trackEvent', 'Social Buttons', 'Click', $(this).closest("li").attr("id")]);
	});
	
	$('#give').click(function() {
		_gaq.push(['_trackEvent', 'Make a Gift', 'Click', 'home page']);
	});
	
	setVideoIcons("#aside .event.video", "/_home/5d/images/play_button_55.png");
	
	$(".rollover").each(function(i) {
		var src, bg, _this = $(this);
		src = $(this).find('img').eq(0).attr("src");
		src = src.substring(0, src.lastIndexOf(".")) + "-over" + src.substr(src.lastIndexOf("."))
		bg = new Image();
		bg.src = src;
		bg.onload = function() {
			_this.css("background", "url(" + src + ") no-repeat 0 0").hover(
				function() {
					$(this).find('img').eq(0).fadeTo(200, 0);
				},function() {
					$(this).find('img').eq(0).fadeTo(200, 1);
				}
			);
		}
	});
	
});

function news(category, showCount) { // if showCount is blank then show all

	$(function() {
	
		var lt = (showCount) ? ":lt(" + showCount + ")" : "";
		var gt = (showCount) ? ":gt(" + (showCount - 1) + ")" : "";
		
		$('.story:not(.' + category + ')').remove();		
		
		// Removes elements that have past the expiration date/time or if there are more than three in the list
		var curTime = new Date();
		$('.story[exp], .event[exp]').each( function() {
			var expiration, expString, expDate, expTime;
			expString = $(this).attr("exp").split("-");
			expDate = expString[0].split("/");
			expTime = expString[1].split(":");
			expiration = new Date(expDate[2], expDate[0]-1, expDate[1], expTime[0], expTime[1]);
			if (expiration < curTime) {
				$(this).remove();	
			}
		});
		$('.upcoming .event:gt(2)').remove();
		
	
		// Trims the text content to hopefully fit within 5 lines of text, if it still doesn't fit, the shorten function is called later
		$('.story.' + category + ' .content span.text').not('.preserveLength').each( function() {
			var text = $(this).html();
			if (text.length > 250) {
				text = text.substring(0, 245);
				text = text.substring(0, text.lastIndexOf(" "));
				$(this).html(text + " ");
			}
		});
	
		
		$('.story.' + category + gt).addClass("hide");
		$('.story.' + category).show();//css("display", "block");
		$('.story.' + category + lt + ' .content').show();	
		$('.story.' + category + ' p').each( function() {
			shorten($(this));	
		});
	
		$('.story a').click(function() {				  
			window.open($(this).attr('href'),"_self");
			return false;
		});
		
		setVideoIcons("#news .video .content", "/_home/5d/images/play_button.png");
		$("#news .video h4").wrapInner("<span />");
		
			
		$('.story h4').click(function() {
			var e = $(this).parent();
			e.toggleClass("hide");
			e.children('.content').slideToggle(300, function() {
				shorten(e.find("p"));																  
			});						
		});
		
		$('.story').hover(
			function () {
				$(this).toggleClass('over');
			  }, 
			  function () {
				$(this).toggleClass('over');
			  }	
		);
		
		function shorten(element) {
			if (element.height() > 90) {
				var content = element.find('span.text');
				var text = content.html();
				text = text.substring(0, text.length - 2);
				text = text.substring(0, text.lastIndexOf(" "));
				content.html(text + " ");
				shorten(element);	
			}
		}
	
	});	
}

function setVideoIcons(selector, imgURL) {
	$(selector).each(function() {
		var pos, url;
		$(this).css("position", "relative").append('<img class="playButton" src="' + imgURL + '" />');
		
		pos = $(this).find("img").position();
		url = $(this).find("a").attr("href");
		
		$(this).find(".playButton").css({
			"display":"none",
			"position":"absolute",
			"top":pos.top,
			"left":pos.left,
			"cursor":"pointer"
		});
		
		$(this).hover(function() {
				$(this).find(".playButton").fadeIn(300);
		}, function() {
				$(this).find(".playButton").fadeOut(300);
		});
		
		$(this).find(".playButton").click(function() {
			window.open(url, "_blank");														 
		});
	});
}
