$(document).ready(function() {
	// animate hover image
	$("#gallery-portfolio ul li a").hover(function() {
		$(this).children("img").fadeTo("normal", 0.7);
	},function() {
		$(this).children("img").fadeTo("normal", 1.0);
	});
	
	// apply modalgallery plugin to #modalgallery
	$(".navthumb li a").modalgallery();

	// set custom portfolio image depending on which page they came from
	var file = getQueryKey("file");
	if (file != undefined) {
		var imgFile = "cmsimages/" + getQueryKey("file");
		$("#content img").attr("src", imgFile);
	}
});

function getQueryKey(searchKey) {
	var query = location.href.split('?')[1];

	if ( query != undefined ) {
		var pairs = query.split("&");
		var split, key, val, found = false;

		for (var i = 0; i < pairs.length; i++) {
			split = pairs[i].split("=");
			key = split[0];
			val = split[1];

			if (key == searchKey) {
				found = val;
				found = unescape(found);
				found.replace(/\+/g, " ");
				found.replace(/\%20/g, " ");
				return found;
			}
		}

		if (found == false) {
			return undefined;
		}
	}
	else {
		return undefined;
	}
}

// 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) {
		//debug(this);

		var currentImg = 0;
		var nextImg = 1;
		var thumbArray = [];

		// 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
		return this.unbind("click").click(function() {
			$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
			$(".navbox .modalnavthumb li a").each(function(i) {
				thumbArray[i] = $(this).attr("href");
				$(this).addClass("" + i);
			});

			// get max number of images and the prev image default
			lastImg = thumbArray.length - 1;
			prevImg = lastImg;

			// show the clicked image, loop until links match
			while ( thumbArray[currentImg] != $this.attr("href") )
			{
				currentImg++;
			}

			// get view pane dimensions so we can resize our modal overlay for IE6
			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(currentImg, thumbArray, 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.
				nextImg = (currentImg < lastImg) ? currentImg + 1 : 0;
				showActiveImage(nextImg, thumbArray, opts);
				currentImg = nextImg;
				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 = (currentImg > 0) ? currentImg - 1 : lastImg;
				showActiveImage(prevImg, thumbArray, opts);
				currentImg = prevImg;
				return false;
			});

			// thumb click actions
			$("#modalgallery .modalnavthumb li a").click(function() {
				var imgId = parseInt($(this).attr("class"), 10);
				showActiveImage(imgId, thumbArray, opts);
				currentImg = imgId;
				return false;
			});
			
			// close it up!
			$("#modalgallery .close").click(function() {
				$("#modalgallery, #modalbg").fadeOut();
				currentImg = 0;
				return false;
			});

			// If window was resized, calculate the new overlay dimensions
			$(window).resize(function() {
				// get view pane dimensions so we can resize our modal overlay for IE6
				var viewPortDimensions = getPageSize();

				// size and fade in modal overlay
				$("#modalbg").css({
					width:		viewPortDimensions[0],
					height:		viewPortDimensions[1]
				});
			});

			// stop default link behavior
			return false;
		});
	};

	//
	// Show the current image
	//
	function showActiveImage(activeImage, thumbArray, opts) {
		var imgObj = new Image();

		imgObj.onload = function() {
			imgBoxWidth = imgObj.width + (opts.mainImgBorderWidth * 2) + (opts.nextBtnWidth * 2);
			imgBoxHeight = imgObj.height + (opts.mainImgBorderWidth * 2) + opts.closeBtnHeight;
			thumbNavWidth = imgObj.width + (opts.mainImgBorderWidth * 2);
			nextPrevMargin = Math.round(imgObj.height * 0.65);

			$("#modalgallery").hide();

			$("#modalgallery .imgbox img")
				.attr("src", thumbArray[activeImage])
				.css("border", opts.mainImgBorderWidth + "px solid " + opts.mainImgBorderColor)
				.width(imgObj.width);

			$("#modalgallery .imgbox .prev, #modalgallery .imgbox .next")
				.css("top", nextPrevMargin);

			// position close button to compensate for IE 6
			if ( ie6 ) {
				var closeBtnPosBottom = 0;
				// landscape
				if ( imgObj.width > imgObj.height) {
					closeBtnPosBottom = -1;
				}
				// portrait
				else if ( imgObj.width < imgObj.height) {
					closeBtnPosBottom = -1;
				}
				$("#modalgallery .imgbox .close").css("bottom", closeBtnPosBottom);
			}

			resizeNavContainer(imgBoxWidth, thumbNavWidth, imgBoxHeight);
			$("#modalgallery").fadeIn(opts.fadeInSpeed);
		}

		imgObj.src = thumbArray[activeImage];
	}

	//
	// Resize image container div
	//
	function resizeNavContainer(imgBoxWidth, thumbNavWidth, imgBoxHeight) {
		$('#modalgallery .imgbox').width(imgBoxWidth).height(imgBoxHeight);
		$('#modalgallery .navbox').width(thumbNavWidth);
	}

	//
	// private function for debugging
	//
	function debug($obj, msg) {
		if (window.console && window.console.log)
			window.console.log('modalgallery selection count: ' + $obj.size());
	}

	//
	// Cros 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);

