$(document).ready(function() {
	/* Apply fancybox to multiple items */
	
	$("a.ajaxpopup").bind('click', function() {
		align();
	});
	
	$("a.ajaxpopup").fancybox({
		'transitionIn'	:	'fade',
		'transitionOut'	:	'fade',
		'speedIn'		:	600, 
		'speedOut'		:	200, 
		'overlayShow'	:	true,
		'overlayOpacity' : 0.9,
		'overlayColor' : '#000',
		'titleShow' : false,
		'onStart': function() { align(); },
		'onComplete': function() { overlayHeight(); }
	});
	$("a.grouped_elements").fancybox();
	
	function align(){
		toppy = ($(window).scrollTop()) + 20;
		$('#fancybox-wrap').animate({
			top: toppy
		});

	}
	
	// Adjust Fancybox Overlay Height to Large Fancyboxes
	function overlayHeight() {
		align();
		$('#mainImage').load(function(){
			//$('#fancybox-wrap').css('top', toppy + "px");
			bodyHeight = $('body').height();
			fancyBoxHeight = $('#mainImage').height(); 
			if(fancyBoxHeight < bodyHeight){
				finalheight = bodyHeight + 150;
			}else{
				finalheight = fancyBoxHeight + 300;
			}
			$('#fancybox-overlay').css('height', finalheight);
			
			imageWidth = $('#mainImage').width();
			fancyBoxWidth = $('#fancybox-wrap').width();
			//alert("box width:" + fancyBoxWidth + "imageWidth:" + imageWidth);
			if(imageWidth + 20 > fancyBoxWidth){
				difference = (imageWidth + 20) - fancyBoxWidth;
				offSet = $('#fancybox-wrap').offset();
				leftPos = offSet.left;
				//alert("difference:"+difference + "leftPost:" + leftPos);
				$('#fancybox-wrap').animate({
					width: imageWidth + 20,
					left: leftPos - (difference * 0.5)
				});
				$('#fancybox-content').css('width','auto');
			}
			
			//$('#mainImage').load(function() {
			//	$.fancybox.resize();
			//});
		});
	}
});
