$(document).ready(function() {
	$("#galleryThumbnails a").click(function(e) {
		setGalleryImage(this);
		return false;
	});
	
	enableNavBtn('prev',false);
	enableNavBtn('next',$('#galleryThumbnails a').length > 1);
	
	$('#prev').click(prevImage).focus(function() { if (this.blur) this.blur(); });
	$('#next').click(nextImage).focus(function() { if (this.blur) this.blur(); });
	
	// init tooltips
	$('.teaserList .thumbnail a img').jHelperTip({
		trigger: 'hover',
		source: 'attribute',
		attrName: 'alt',
		opacity: 0.9,
		autoClose: true
	});
});

function enableNavBtn(which,status) {
	status ? $('#' + which).show() : $('#' + which).hide();
}

function curImage() {
	return $('#galleryThumbnails img.active').parent().get(0);
}

function nextImage() {
	var cur = curImage();
	if (cur.nextSibling) {
		setGalleryImage(cur.nextSibling);
	}
	return false;
}

function prevImage() {
	var cur = curImage();
	if (cur.previousSibling) {
		setGalleryImage(cur.previousSibling);
	}
	return false;
}

function setGalleryImage(tn) {
	if ($(tn).find('img.active').length) {
		return;
	}
	
	var index = jQuery.inArray(tn,$('#galleryThumbnails a'));
	var href = $(tn).attr('href');
	var speed = 'slow';
	
	$('#galleryThumbnails img.active').removeClass('active');
	$($('#galleryThumbnails img').get(index)).addClass('active');
	
	$('#loading').css('display','block');
	var img = $('#galleryDetail .image').hide();
	var i = new Image();
	$(i).load(function() {
		$('#loading').css('display','');
		img.find('img').replaceWith(i);
		img.fadeIn(speed);
		$('#galleryDetail p').hide();
		$('#galleryDetail p').text($(tn).find('img').attr('title')).fadeIn(speed);
	});
	$(i).attr('src',href);
	
	enableNavBtn('prev',!!tn.previousSibling);
	enableNavBtn('next',!!tn.nextSibling);
}
