
var speed;

var img2Scroll;
var loadedImg;
var scrollerWidth;
var contentWidth;
var showScroller;
var goScroll;
var goScrollFancy;
var imgPreloader;

$(document).ready(function(){
	
	$("#Scroller.gallery a").live("click",function() {
		$.fancybox({
			'autoScale'			: true,
			'transitionIn'		: 'none',
			'transitionOut'		: 'none',
			'type'				: 'image',
			'href'				: this,
			'onStart'			: function() { goScrollFancy = false; },
			'onClosed'			: function() { goScrollFancy = showScroller; }
		});
		return false;
	});
	
	img2Scroll = $("#Scroller img");
	if(img2Scroll.length) {
		$(img2Scroll).css({"display":"none"});
		contentWidth = $("#GalleryInside").innerWidth();
		scrollerWidth = 0;
		loadedImg = 0;
		showScroller = false;
		goScroll = false;
		goScrollFancy = false;
		imgPreloader = new Array();
		Loader();
	}
	
});

function Loader() {
	imgPreloader[loadedImg] = new Image();
	imgPreloader[loadedImg].onload = function(){ setTimeout("CheckLoadedPic()",15); }
	
	if(loadedImg<img2Scroll.length) imgPreloader[loadedImg].src = $(img2Scroll[0]).attr("src");
	else{
		goScroll = true;
		goScrollFancy = true;
		StartScroll();
	}
	
}

function CheckLoadedPic() {
	var pw = $(img2Scroll[loadedImg]).innerWidth();
	if(pw>0) {
		scrollerWidth += pw;
		$(img2Scroll[loadedImg]).css({"display":"block"});
		$("#Scroller").css({"width":scrollerWidth});
		if(!showScroller && scrollerWidth>contentWidth) {
			showScroller = true;
			$("#Scroller").css({"display":"none","visibility":"visible"}).animate({ opacity: 'show'}, "slow");
		}
		loadedImg++;
		Loader();
	}else setTimeout("CheckLoadedPic()",15);
}

function StartScroll() {
	if(goScroll && goScrollFancy) {
		var pos = $("#Scroller").css("left").split("px")[0]*1 - speed;
		if((pos-contentWidth)<(-scrollerWidth)) {
        	$("#Scroller a").filter(':last' ).after($("#Scroller a").filter(':first').clone());
			pos += $("#Scroller img:first").innerWidth();
			$("#Scroller a").filter(':first').remove();
		}
		$("#Scroller").css({"left":pos+"px"});
	}
	setTimeout("StartScroll()",15);
}
