$(document).ready(function() {
	// apply modalgallery plugin to gallery and navsub
	//$(".navthumb li a, .nav_level3 li.selected ul li a").modalgallery();
	galleryHover();
});

// create closure
(function($) {
 	// ie6 tag so we can compensate for close button position
	var ie6 = $.browser.msie && /MSIE 6.0/.test(navigator.userAgent);

	//
	// Custom modal gallery with thumbnails plugin defenition
	//
 	$.fn.modalgallery = function(options) {
		var currentLink = 0;
		var nextLink = 1;
		var linkArray = [];

		// work out main settings (without metadata) - only do this work once per plugin call
		var main_opts = $.extend({}, $.fn.modalgallery.defaults, options);

		// iterate and reformat each matched element
		// use unbind to limit events to one instance of the plugin
		return this.unbind("click").click(function() {
			$("#modalgallery .next").unbind("click");
			$("#modalgallery .prev").unbind("click");
			$("#modalgallery .close").unbind("click");

			// shortcut
			$this = $(this);

			// if metadata is present, extend main_opts, otherwise just use main_opts
			var opts = $.meta ? $.extend({}, main_opts, $this.data()) : main_opts;

			// assign each full image to our array and give it a class
			$(".navthumb li a").each(function(i) {
				linkArray[i] = $(this).attr("href");
				$(this).addClass("" + i);
			});

			// get max number of images and the prev image default
			lastImg = linkArray.length - 1;
			prevImg = lastImg;

			// show the clicked image, loop until links match
			while ( linkArray[currentLink] != $this.attr("href") )
			{
				currentLink++;
			}

			// get view pane dimensions so we can resize our modal overlay
			var viewPortDimensions = getPageSize();

			// size and fade in modal overlay, then show the current image on callback
			$("#modalbg")
				.css({
					width:			viewPortDimensions[0],
					height:			viewPortDimensions[1],
					backgroundColor:	opts.modalbgColor,
					opacity:		opts.modalbgOpacity
				})
				.fadeIn(opts.fadeInSpeed, function() {
					showActiveImage(currentLink, linkArray, opts);
				});

			// next button click actions
			$("#modalgallery .next").click(function() {
				// Calculate which image in the array is next in line.
				// Make an exception when on the last image.
				nextLink = (currentLink < lastImg) ? currentLink + 1 : 0;
				showActiveImage(nextLink, linkArray, opts);
				currentLink = nextLink;

				// stop default link behavior
				return false;
			});

			// prev button click actions
			$("#modalgallery .prev").click(function() {
				// Calculate which image in array is previous.
				// Make exceptions when on first and last elements.
				prevImg = (currentLink > 0) ? currentLink - 1 : lastImg;
				showActiveImage(prevImg, linkArray, opts);
				currentLink = prevImg;

				// stop default link behavior
				return false;
			});

			// close it up!
			$("#modalgallery .close").click(function() {
				$("#modalgallery, #modalbg").fadeOut();
				currentLink = 0;

				// stop default link behavior
				return false;
			});

			// If window was resized, calculate the new overlay dimensions
			$(window).resize(function() {
				resizeModalBg();
			});

			// stop default link behavior
			return false;
		});
	};

	//
	// Resize the modal bg on changes so it will extend down the page
	//
	function resizeModalBg() {
		// get view port dimensions
		var viewPortDimensions = getPageSize();
		var pageWidth = viewPortDimensions[0];
		var pageHeight = viewPortDimensions[1];

		if ( $.browser.msie ) pageHeight += 150;

		// size and fade in modal overlay
		$("#modalbg").css({
			width:		pageWidth,
			height:		pageHeight
		});
	}
	//
	// Show the current image
	//
	function showActiveImage(activeLink, linkArray, opts) {
		// hide the modal gallery
		$("#modalgallery").hide();

		// load our child page content into the modal
		$("#modalgallery #profile").load(
			linkArray[activeLink],
			function() {
				$("#modalgallery").fadeIn(opts.fadeInSpeed, function(){
					//if ($.browser.msie) resizeModalBg();
					resizeModalBg();
				});
			}
		);
	}

	//
	// private function for debugging
	//
	function debug(msg) {
		if (window.console && window.console.log) {
			window.console.log("debug: " + msg);
		}
		else {
			$("#debug").append("debug: " + msg + "<br />");
		}
	}

	//
	// Cross browser view port dimensions
	//
	function getPageSize() {
		var xScroll, yScroll;
		if (window.innerHeight && window.scrollMaxY) {	
			xScroll = window.innerWidth + window.scrollMaxX;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}
		var windowWidth, windowHeight;
		if (self.innerHeight) {	// all except Explorer
			if(document.documentElement.clientWidth){
				windowWidth = document.documentElement.clientWidth; 
			} else {
				windowWidth = self.innerWidth;
			}
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) { // other Explorers
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}	
		// for small pages with total height less then height of the viewport
		if(yScroll < windowHeight){
			pageHeight = windowHeight;
		} else { 
			pageHeight = yScroll;
		}
		// for small pages with total width less then width of the viewport
		if(xScroll < windowWidth){	
			pageWidth = xScroll;		
		} else {
			pageWidth = windowWidth;
		}
		arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
		return arrayPageSize;
	}

	//
	// plugin defaults
	//
	$.fn.modalgallery.defaults = {
		mainImgBorderWidth: 3,
		mainImgBorderColor: "#e0e0e0",
		nextBtnWidth: 18,
		closeBtnHeight: 15,
		modalbgColor: "black",
		modalbgOpacity: 0.9,
		fadeInSpeed: 300,
		debugOn: false
	};

// end of closure
})(jQuery);

function galleryHover() {
	// image preload arrays
	var rollImgArray = new Array();
	var thumbImgArray = new Array();

	// image sizes
	var thumbImgWidth = 55;
	var thumbImgWidthHover = 114;

	// thumb quality
	var thumbJpegQuality = 95;

	$(".navthumb li a").each(function(l) {
		// keep track of animation state
		var okToAnimate = true;

		// get rollover relative img src
		var rollImgSrc = $(this).children("img").attr("alt");
		var rollRelSrc = "cmsimages/" + rollImgSrc;

		// preload rollover img
		rollImgArray[l] = new Image();
		rollImgArray[l].src = rollRelSrc;

		// preload thumbnail img
		thumbImgArray[l] = new Image();
		thumbImgArray[l].src = "phpThumb.php?src=" + encodeURIComponent(rollRelSrc) + "&w=" + thumbImgWidth + "&q=" + thumbJpegQuality;

		// animate hover image
		$(this).hover(function() {
			// if other animations are not running, animate current anchor
			if ( okToAnimate )
			{
				okToAnimate = false;

				// remove width
				$(this).children("img").removeAttr("width");
				$(this).children("img").removeAttr("height");

				// fade out thumb, fade in rollover
				$(this).fadeTo("fast", 0.01, function() {
					$(this).next(".description").hide();
					$(this).children("img").attr("src", rollImgArray[l].src);
					$(this).addClass("hover");
					$(this).fadeTo("normal", 1.0, function() {
						okToAnimate = true;
					});
				});
			}
		},function() {
			// if mouseout happened before animation was done, reset anchor
			if ( !okToAnimate )
			{
				$(this).dequeue();
				$(this).stop();

				// original state
				$(this).children("img").attr("src", thumbImgArray[l].src);
				$(this).removeClass("hover");
				$(this).next(".description").show();
				$(this).fadeTo(1, 1.0);

				okToAnimate = true;
			}

			// if other animation is not running, reset anchor on mouseout
			if ( okToAnimate )
			{
				okToAnimate = false;

				// original state
				$(this).children("img").attr("src", thumbImgArray[l].src);
				$(this).removeClass("hover");
				$(this).next(".description").show();

				okToAnimate = true;
			}
		});
	});
}
