jQuery(function($) {
	if(!$('.photoBig').get(0)) return false;
	var current = 0;
	var total = $('.images img').size();
	var imgSrc = '/components/com_galleryview/image.php?';
	
	//$('div.gThumbs').width($('.photoBig').width());
	holderMargin = parseInt($('div.gThumbs div.holder').css('marginLeft'))*2;
	imgPrevNextWidth = $('div.imgPrev').width()*2;
	$('div.gThumbs div.holder').width($('.photoBig').width()-holderMargin-imgPrevNextWidth);
	var holderW = $('.gThumbs .holder').width();
	
	$('.photoBig img').load(function(){ hidePreloader(); });
	
	$('.images img').click(function(){
		current = $('.images img').index(this);
		active = $('.images img.active').get(0);
		if(this != active) {
			addPreloader();
			changePic(this);
			scroll(this, active);
		}
	});
	
	if(imagesWidth < holderW) $('.images').css({textAlign:'center', width:holderW+'px'});
	else $('div.images').css('width', imagesWidth+'px');
	
	function addPreloader() {
		img = $('.photoBig img');
		$('.preloader').css({
			display:'block',
			top:img.offset().top+'px',
			left:img.offset().left+'px',
			width:img.width()+'px',
			height:img.height()+'px'
		});
	}
	function hidePreloader() {
		$('.preloader').removeAttr('style');
	}
	
	function scroll(img, currentImg) {
		$(currentImg).removeClass('active');
		$(img).addClass('active');
		imagesImg = $('.images img');
		index = imagesImg.index(img);
		images = $('.images');
		currentImgX = $(currentImg).position().left;
		imgX = $(img).position().left;
		imgXW = imgX+$(img).width()+3;
		if(currentImgX < imgX && imgXW > holderW) {
			plus = 0;
			if(imagesImg[index+1]) plus = ($(imagesImg[index+1]).width()/2)+3;
			images.animate({
				left:(holderW-imgXW-plus-3)+'px'
			}, 'slow');
		}
		if(currentImgX > imgX) {
			imagesLeft = -images.position().left;
			if(imagesLeft > imgX) {
				minus = 0;
				if(imagesImg[current-1]) minus = $(imagesImg[current-1]).width() / 2 + 3;
				images.animate({
					left:-imgX+3+minus+'px'
				}, 'slow');
			}
		}
	}
	
	function changePic(img) {
		setUrlImg = imgSrc+img.className+dimm;
		imgBig = $('.photoBig img');
		imgBig.attr('src', setUrlImg);
		if(imgBig.parent().get(0) && imgBig.parent().attr('rel') == 'lightbox') {
			setUrlA = imgSrc+img.className+':orig';
			imgBig.parent().attr('href', setUrlA);
		}
	}

	$('.imgNext span').click(function(){
		if(current < total-1) {
			addPreloader();
			currentImg = $('.images img')[current];
			current++;
			next = $('.images img')[current];
			changePic(next);
			scroll(next, currentImg);
		}
	});
	$('.imgPrev span').click(function(){
		if(current > 0) {
			addPreloader();
			currentImg = $('.images img')[current];
			current--;
			prev = $('.images img')[current];
			changePic(prev);	
			scroll(prev, currentImg);
		}
	});
});