$(document).ready(function() {

	var top;
	
	// uniform
    $('.filters select').uniform();

	// shadowbox
	Shadowbox.init({
		handleOversize:		"resize",
		modal:				true,
		viewportPadding:	0,
		overlayOpacity:		1.0,
		overlayColor:		"#FFF",
        onOpen: function() {
                if((navigator.userAgent.match(/iPhone/i))||(navigator.userAgent.match(/iPad/i))) {
                        $("#sb-container").css("top", $(window).scrollTop());
                        $(window).bind('scroll', function() {
                                $("#sb-container").css("top", $(window).scrollTop());
                        });
                }
        },
        onClose: function() {
                if((navigator.userAgent.match(/iPhone/i))||(navigator.userAgent.match(/iPad/i))) {
                	$(window).unbind('scroll');
                }
        },
        onFinish: function(){ 
			// cufon the title
        	$('#sb-body-inner img').one('click',Shadowbox.next);
        }
	});
    
	$('ul.carousel').each(function() {
		if ($('img', $(this)).length > 5) {
			$(this).jcarousel({
				wrap: 				'circular',
				visible:			'5',
				buttonNextHTML:		'<a></a>',
				buttonPrevHTML:		'<a></a>'
			});
		} else {
			$(this).removeClass('carousel').addClass('nojcarousel');
		}
	})

	// search filter
	$('#searchfilter select').change(function() {
		var selected = $(this).val();
		$('#searchfilter select').each(function() {
			 $(this).val('');
		})
		$(this).val(selected)
		$.uniform.update(); 
		$('#searchfilter').submit();
	});

	$('.fullimage').click(function() {
		$(this).nextImage();
		return false;
	});
	
	$('.imagelist .carousel .imagewrap img, .imagelist .nojcarousel .imagewrap img').click(function() {
		$(this).swapImage();
		return false;
	});
	
	// goto fullsize image & center
	$('.gotofullsize').click(function() {
		position = $(this).offset();
		top = position.top;
		$('.fullsize').fullSize($(this))
		$(document).keypress(function(e) {
			if (e.keyCode == 27) {
				$('div.fullsize .close').trigger('click');
			}
		});
		return false;
	});
	
	// goto fullsize image & center
	$('.open-fullscreen').click(function() {
		position = $(this).offset();
		top = position.top;
		$(document).keypress(function(e) {
			if (e.keyCode == 27) {
				$('div.fullsize .close').trigger('click');
			}
		});
		
		$image = $('img', $('.fullsize'))
		$image
			.removeAttr('src')
			.attr('src', $(this).attr('href'))
			.css({'width': 'auto', 'height': 'auto'})
			.load(function() {
		    	imageWidth = this.width;
		    	imageHeight = this.height;
				if (imageHeight > imageWidth) {
					$image.height($(window).height())
				} else if ($image.outerHeight(true) > $(window).height()) {
					// Image height doesn't fit in the window so adjust height
					$image.height($(window).height())
				}
		    	$image.center();
			})
			
		$('div.container').toggle();
		
		$('.fullsize').toggle();
		return false;
		
	});
	

	// goto fullsize image & center
	$('div.fullsize .close').click(function() {
		$('div.container').toggle();
		$('div.fullsize').toggle();
		$(window).scrollTop(top - 200);
		return false;
	});

	// fullsize resize
	$(window).bind('resize', function() {
		$('.fullsize img').center();
		$('.viewport').scaleViewport();
	});
	
	$('.fullscreen').click(function() {
		var img={
		        player:     'img',
		        content:    $('.fullimage').parent().attr('href'),
		        gallery:    "maas"
		};   
		Shadowbox.open(img, {options:{continuous: true}});
	})
	
	$('.viewport').scaleViewport();
	
});

/**
 * Fullscreen images
 */
$.fn.fullSize = function(fullsizeLink)
{
	
	fullimage = $(fullsizeLink).parents('.imagelist').prev('.imagewrap').find('img');
	$image = $('img', $(this))
	$image
		.removeAttr('src')
		.attr('src', fullimage.attr('src'))
		.css({'width': 'auto', 'height': 'auto'})
		.load(function() {
	    	imageWidth = this.width;
	    	imageHeight = this.height;
			if (imageHeight > imageWidth) {
				$image.height($(window).height())
			} else if ($image.outerHeight(true) > $(window).height()) {
				// Image height doesn't fit in the window so adjust height
				$image.height($(window).height())
			}
	    	$image.center();
		})
		
	$('div.container').toggle();
	
	$(this).toggle();
	return false;
}

/**
 * Swap fullsize image to clicked thumbnail 
 */
$.fn.swapImage = function()
{
	var newsrc = $(this).parent().attr('href');
	
	var fullimage = '.'+$(this).parents('.carousel').attr('id');
	if ($(this).parents('.carousel').length == 0) {
		var fullimage = '.'+$(this).parents('.nojcarousel').attr('id');
	}
	$(fullimage).fadeOut(200, function(){
        $(this).attr('src', newsrc).bind('onreadystatechange load', function(){
        	if (this.complete) {
        		$('.viewport').scaleViewport();
        		$(this).fadeIn(230);
        	}
        });
        $(this).fadeIn(230);
	});
	
	$(this).parent().removeAttr('rel');
	$(fullimage).parent().attr({'href': newsrc});
}

/**
 * Go to the nextImage in the gallery
 */
$.fn.nextImage = function()
{
	var id = $(this).attr('rel');
	
	if ($('#'+id).length > 0) {
		var src = $(this).attr('src');
		var currentImage = $('.carousel .jcarousel-item a[href='+src+']:first', $(this).parent().parent().parent());
		
		if (currentImage.length == 0) {
			var currentImage = $('.nojcarousel .jcarousel-item a[href='+src+']:first', $(this).parent().parent().parent());
		}
		
		var nextImage = currentImage.parent().parent().next().find('.imagewrap');
		
		if (nextImage.length == 0) {
			var nextImage = $('#'+id+' li:first');
		}
		
		var newsrc = $(nextImage).find('a').attr('href')
		
		$(this).fadeOut(200, function(){
	        $(this).attr('src', newsrc).bind('onreadystatechange load', function(){
	
	        	if (this.complete) {
	        		$('.viewport').scaleViewport();
	        		$(this).fadeIn(230);
	        	}
	        });
		});
	}
}

/**
 * Scale viewport automaticly
 */
$.fn.scaleViewport = function()
{
	if ($('.viewport').length > 0) {
		tagsHeight = $('.inline.tags').outerHeight(true);
		headerHeight = $('.viewport header').outerHeight(true);
		carouselHeight = $('.imagelist:first').outerHeight(true);
		leftpaneHeight = $('.leftpane').outerWidth(true);
		windowHeight = $(window).height();
		if (tagsHeight == null) tagsHeight = 30;
		
		viewportUsedHeight = windowHeight - tagsHeight;
		viewportHeightStatic = windowHeight - tagsHeight - headerHeight - carouselHeight - 20;
		
		maxWidth = parseInt($(window).width() - leftpaneHeight -40);
		maxHeight = parseInt(viewportHeightStatic);
		
		if ($('.fullimage').length > 0) {
		
			//calculate height
			$image = $("<img/>")
			.attr('src', $('.fullimage').attr('src'))
			.load(function() {
		    	imageWidth = this.width;
		    	imageHeight = this.height;
		    	
		    	newImageWidth = imageWidth;
		    	newImageHeight = imageHeight;
		
		    	/**
		    	 * Set the max width based on 
		    	 * max height calculation
		    	 */
				newImageHeight =  viewportHeightStatic;
				newImageWidth = (newImageHeight / imageHeight ) * imageWidth;
		    	
		    	$('figure.imagewrap.magnified').width(newImageWidth);
			})
		}
	}
}
