﻿var SplashPhotos = {
	photoIndex: 0,
	photoCount: 0,
	delay: 5000,
	fadeToOpacity: .3,
	cyclePhotos: true,
	init: function() {

		var that = this,
			$photosContainer = $("#splash-photos"),
			photoLoop = 0;

		// fade in overlay
		$("#splash-photo-overlay").fadeTo(2000, .8);

		// load each img into the DOM, from the hidden divs
		$("div", $photosContainer).each(function() {
			photoLoop++;
			var $div = $(this),
			$img = $('<img src="' + $div.text() + '" alt=" ' + $div.attr("title") + '" />');
			if (photoLoop > 1) {
				$img.fadeTo("fast", that.fadeToOpacity);
			} else {
				$img.addClass("first");
			}
			$img.load(function() {
				$photosContainer.append(this);
				that.photoCount++;
			});

		});
		$photosContainer.find("div").remove();

		// cycle through images once
		var timer = setInterval(function() {
			that.photoIndex++;
			if (!that.cyclePhotos || that.photoIndex === that.photoCount) {
				clearInterval(timer);
				return;
			}
			that.changePhoto($photosContainer.find("img:eq(" + that.photoIndex + ")"));
		}, that.delay);

		// listen for click event
		$photosContainer.click(function(e) {
			var $target = $(e.target);
			if ($target.is("img")) {
				that.changePhoto($target);
				that.cyclePhotos = false; // stop cycling
				that.photoIndex = $target.index(); // set current index                   
			}
		});

	},
	changePhoto: function($photo) {
		$photo.fadeTo("fast", 1.0);
		$("#splash-photo").empty().append($photo.clone().fadeTo("slow", 1.0));
		$photo.siblings("img").fadeTo("fast", this.fadeToOpacity);
	}
};

$(function () {
    SplashPhotos.init();
});

