// JavaScript Document

	$(document).ready(function() {
		// Add click function to all images
		$("figure").click(function(){
			// alert("Click figure");
			popUpFigure($(this));
		});
		$("#figurePopUp").click(function(){
			// alert("Click figure");
			closeFigure($(this));
		});
		c3preloadImages();
	});
	
	function popUpFigure(clickedFigure) {
		
		var offset = clickedFigure.children("img").offset();
		
		positionPopup(parseInt(offset.left), parseInt(offset.top), clickedFigure.children("img").attr("width"), clickedFigure.children("img").attr("height"), clickedFigure.children("img").attr("src"));
		
		// alert(clickedFigure.children("img").attr("src"));
	}
	
	//centering popup
	function positionPopup(xPos, yPos, width, height, src){
	
		$("#figurePopUp").css({
			"display": "block",
			"top": (parseInt(yPos) - 20) + "px",
			"left": (parseInt(xPos) - 20) + "px",
			"width": width + "px",
			"height": height + "px",
			"z-index":"1998"
		});
		
		$("#figurePopUp").html('<img src="' + src.slice(0, 22) + '_main.jpg' + ' " width="200" height="133" />');
		
		$("#figurePopUp").animate({
			width: "900px",
			height: "603px",
			left: (($(window).width() - 940) / 2) + "px",
			top: (($(window).height() - 643) / 2 + $(window).scrollTop()) + "px"
		}, 500 );
		
		$("#figurePopUp").children("img").animate({
			width: "900px",
			height: "603px"
		}, 500 );
		
	}
	
	function closeFigure(clickedFigure) {
		clickedFigure.fadeOut();
	}
	
	function c3preloadImages() {
		$('article img').each(function(index) {
    		// alert(index + ': ' + $(this).attr('src'));
			var cacheImage = document.createElement('img');
			cacheImage.src = $(this).attr('src').slice(0, 22) + '_main.jpg';
			// alert('ATTEMPTING TO PRELOAD: ' + $(this).attr('src').slice(0, 22) + '_main.jpg');
  		});
	}
