j(document).ready(function(){

	//When you click on a link with class of poplight and the href starts with a #
	j('a.poplight[href^=#]').click(function() {
		var popID = j(this).attr('rel'); //Get Popup Name
		var popURL = j(this).attr('href'); //Get Popup href to define size

		//Pull Query & Variables from href URL
		var query= popURL.split('?');
		var dim= query[1].split('&');
		var popWidth = dim[0].split('=')[1]; //Gets the first query string value
		var popupHeight = j('#' + popID).height();
		var popMaxHeight = j(window).height();

		//Fade in the Popup and add close button
		j('#' + popID).fadeIn().css({ 'width': Number( popWidth ) }).prepend('<a href="#" class="close"><img src="http://www.sportkm.cz/wp-content/themes/eBusiness/images/close_pop.png" class="btn_close" title="Close Window" alt="Close" /></a>');

		// Check if window height is smaller than popup height:
		if(popMaxHeight<j('#' + popID).outerHeight())
		{
			// Work out new popup height ( screen height minus popup padding/border widths )
			popupHeight = j(window).height()-200;//-(j('#' + popID).outerHeight()-j('#' + popID).height());
			// Set new popup height and add a scrollbar:
			j('#' + popID).css('height', popupHeight).css('overflow-y','scroll');
			j('img.btn_close').css('margin',0);
		}

		//Define margin for center alignment (vertical + horizontal) - we add 80 to the height/width to accomodate for the padding + border width defined in the css
		var popMargTop = (popupHeight + 80) / 2;
		var popMargLeft = (j('#' + popID).width() + 80) / 2;
		

		//Apply Margin to Popup
		j('#' + popID).css({
			'margin-top' : -popMargTop,
			'margin-left' : -popMargLeft
		});

		//Fade in Background
		j('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
		j('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn(); //Fade in the fade layer


		return false;
	});

	//Close Popups and Fade Layer
	j('a.close, #fade').live('click', function() { //When clicking on the close or fade layer...
	  	j('#fade , .popup_block').fadeOut(function() {
			j('#fade, a.close').remove();
	}); //fade them both out

		return false;
	});
});
