$(document).ready(function() {
	//When you click on a link with class of poplight and the href starts with a # 
	$('a.modal').click(function(e) {
		var popID = $(this).attr('href'); //Get Popup href to define size
		
		if (popID == "#") {
			return false;
		}
		
		if (popID.substr (0, 1) == "#") {
			modal = $(document.createElement ("div"))
				.attr ('id', 'temp_image')
				.addClass ('popup_block')
				.appendTo ($('body'))
				.hide ();
				
			popID = $(popID).clone ();
			popID
				.removeAttr ('id')
				.appendTo (modal);
			
			loadModal (modal);
		}
		else {
			var imgSrc = popID;
			popID = $(document.createElement ("div"))
				.hide()
				.attr('id', 'temp_image')
				.addClass('popup_block')
				.appendTo ($('body'));
			
			$(document.createElement ("img"))
				.attr('id', 'temp_image_src')
				.appendTo (popID)
				.load ( 
					function () {  
						$("#temp_image")
							.width ($("#temp_image_src").width ())
							.height ($("#temp_image_src").height ());
						
						loadModal ('#temp_image');
					}
				)
				.attr ('src', imgSrc);
		}
		
		e.preventDefault ();
		return false;
	});
	
	//Close Popups and Fade Layer
	$('a.close, #fade').live('click', function() { //When clicking on the close or fade layer...
		$('#fade , .popup_block').fadeOut(function() {
			$('#fade, a.close').remove();  //fade them both out
			$('#temp_image').remove ();
		});
		return false;
	});
	
	function loadModal (popID) {
		//Define margin for center alignment (vertical   horizontal) - we add 80px to the height/width to accomodate for the padding  and border width defined in the css
		var popMargTop = ($(popID).height() + 80) / 2;
		var popMargLeft = ($(popID).width() + 80) / 2;
	
		//Apply Margin to Popup
		$(popID).css({
			'margin-top' : -popMargTop,
			'margin-left' : -popMargLeft
		});
		
		//Fade in the Popup and add close button
		$(popID).fadeIn (
			null, 
			function () {
				$(".btn_close").fadeIn ('fast');
			}
		).prepend (
			'<a href="#" class="close"><img src="img/menu/close.png" class="btn_close" style="display: none" title="Close Window" alt="Close" /></a>'
		);
		
		//Fade in Background
		$('body').append($(document.createElement ('div')).attr ('id', 'fade')); //Add the fade layer to bottom of the body tag.
		$('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn(); //Fade in the fade layer - .css({'filter' : 'alpha(opacity=80)'}) is used to fix the IE Bug on fading transparencies 
	}
});
