var loadingLoop;
var loadingText = "LOADING...";
var count = 0;
var currentImageLink;

$(document).ready(function(){
	$(window).resize(function(){
		$('#lightbox').width($(window).width());
		$('#lightbox').height($(window).height());
		setExactFit($('#lightbox img:first'), $('#lightbox'));
	})
	$('#post-616 a:has(img)').each(function(){
		$(this).click(function(e){
			e.preventDefault();
			lightbox($(this));
		});
	});
	$('#post-616 p').each(function(){
		$(this).find('a:has(img)').wrapAll('<span class="imgWrapper" />');
	});
});
function lightbox(_target){
	currentImageLink = _target;
	
	if($('#lightbox').length == 0) {
		$('body').append('<span id="lightbox"><a href="#" id="lightboxback"><span id="lightboxloading"><strong>LOADING...</strong></span></a></span>');
		$('#lightbox').css('position', 'fixed');
	}
	$('#lightboxback').click(function(e){
		e.preventDefault();
		closeLightbox();
	});
	loadImage(_target);
}
function loadImage(_target){
	$('#lightbox img').remove();
	loadingLoop = setInterval(loop, 50);
	
	var link = _target.attr('href');
	var image = new Image();
	$(image).load(function(){
		$('#lightbox').append($(this));
		setExactFit($(this), $('#lightbox'));
		$(this).css('cursor', 'pointer');
		$(this).click(function(e){
			e.preventDefault();
			getNextImage();
		});
		clearInterval(loadingLoop);
	}).attr({
		src: link
	});
}
function getNextImage(){
	//$(this).siblings('a:has(img)').length;
	if(currentImageLink.next('a:has(img)').length > 0){
		currentImageLink = currentImageLink.next('a:has(img)');
		loadImage(currentImageLink);
	} else {
		closeLightbox();
	};
	
}
function closeLightbox(){
	clearInterval(loadingLoop);
	$('#lightbox').remove();
}
function loop(){
	count ++;
	count > loadingText.length-1 ? count = 0 : 0;
	var pre = loadingText.substr(0, count);
	var post = loadingText.substr(count+2);
	$('#lightboxloading strong').html(pre + "<span style='color:#30FF83'>" + loadingText.substr(count, 2) + "</span>" + post);
}
function setExactFit(image, container){
	var crop = false;
	var margin = 50;
	var containerWidth = container.width() - margin * 2;
	var containerHeight = container.height() - margin * 2;
	containerRatio = containerWidth / containerHeight;
	imageRatio = image.width() / image.height();
	
	var firstRatio;
	var secondRatio;
	
	if(crop == "false"){
		firstRatio = containerRatio;
		secondRatio = imageRatio;
	} else {
		firstRatio = imageRatio;
		secondRatio = containerRatio;
	}
	//
	if (firstRatio > secondRatio) {
		image.css('width', containerWidth);
		image.css('height', 'auto');
	} else {
		image.css('height', containerHeight);
		image.css('width', 'auto');
	}
	image.css('top', (container.height() / 2 - image.height() / 2) + 'px');
	image.css('left', (container.width() / 2 - image.width() / 2) + 'px');
}
