jQuery(document).ready(function() {

	var current = 1;
	var lastclick = false;
	var lastnewimg = false;

	function mycarousel_initCallback(carousel) {

		car = carousel;
		
		jQuery('#flickr_carousel-next').bind('click', function() {
			carousel.next();
			return false;
		});

	};

	function mycarousel_itemLastInCallback(carousel, item, idx, state) {

		last = idx;

	};

	function mycarousel_itemFirstInCallback(carousel, item, idx, state) {
		first = idx;
	};

	function mycarousel_itemLoadCallback(carousel, state) {

		if (carousel.prevFirst != null) {
			// Remove the last visible items to keep the list small
			for (var i = carousel.prevFirst; i <= carousel.prevLast; i++) {
				// jCarousel takes care not to remove visible items
				carousel.remove(i);
			}
		}

		var per_page = carousel.last - carousel.first + 1;
		var currPage = 0;
		var f,l;
		var cr = carousel;

		for (var i = carousel.first; i <= carousel.last; i++) {
			var page = Math.ceil(i / per_page);

			if (currPage != page) {
				currPage = page;

				f = ((page - 1) * per_page) + 1;
				l = f + per_page - 1;

				f = f < carousel.first ? carousel.first : f;
				l = l > carousel.last ? carousel.last : l;

				if (carousel.has(f, l)) {
					continue;
				}

				mycarousel_makeRequest(carousel, f, l, per_page, page);
			}
		}
	};

	function mycarousel_makeRequest(carousel, first, last, per_page, page) {
		// Lock carousel until request has been made
		carousel.lock();

		jQuery.get(
			'/php_inc/flickr_fetch.php',
			{
				'per_page': per_page,
				'page': page,
				'set_id': flickr_set_id,
				'account': flickr_account
			},
			function(data) {
				mycarousel_itemAddCallback(carousel, first, last, data, page);
			},
			'json'
		);
	};

	function mycarousel_itemAddCallback(carousel, first, last, data, page) {

		c = carousel;
		
		if($("#flickr_carousel li.on").length) {
			$("#flickr_carousel li.on").removeClass("on");
		}
		
		// Unlock
		carousel.unlock();

		total = data.header.total;

		// Set size
		carousel.size(data.header.total);

		var per_page = carousel.last - carousel.first + 1;

		for (var i = first; i <= last; i++) {

			var pos = i - 1;
			var str = "data_"+pos;

			if(typeof data[str] != "undefined") {
				carousel.add(i, data[str]);
			}
		}

		var ii = (!lastclick || lastclick == "next") ? first : last;

		var gal_start = function() {
			gallery_start();
		}

		gallery_load_img($("#flickr_carousel li[jcarouselindex="+ii+"] a"), $("#flickr_gallery .large"), gal_start);
		
		current = ii;
		
		prev_next();

	};

	jQuery('#flickr_carousel').jcarousel({
		scroll: 7,
		initCallback: mycarousel_initCallback,
		itemLastInCallback: mycarousel_itemLastInCallback,
		itemFirstInCallback: mycarousel_itemFirstInCallback,
        itemLoadCallback: mycarousel_itemLoadCallback
	});

	$(".gallery").each(function(){

		var gal = $(this);

		$(".large", gal).hover(function(){
			$(this).addClass("large_hover");
		},function(){
			$(this).removeClass("large_hover");
		});

		$(".large .next", gal).live('click',function(){
			lastclick = "next";
			var on = $("ul li.on", gal);
			on.removeClass("on");
			var next = on.next("li");

			if(current == last) {
				car.next();
				return false;
			}

			current = first+next.index();
			prev_next();

			gallery_load_img($("a", next), $(".large", gal));
			return false;
		});

		$(".large .prev", gal).live('click',function(){
			lastclick = "prev";
			var on = $("ul li.on", gal);
			on.removeClass("on");
			var prev = on.prev("li");

			if(current == first) {
				car.prev();
				return false;
			}

			current = first+prev.index();
			prev_next();

			gallery_load_img($("a", prev), $(".large", gal));
			return false;
		});

		$("ul li a", gal).live('click',function(){

			gallery_stop();

			var li = $(this).closest("li");

			current = first+li.index();
			prev_next();

			gallery_load_img($(this), $(".large", gal),function(){
				gallery_start();
			});

			return false;
		});

	});

	function prev_next() {

		if(current == 1) {
			$("#flickr_gallery .large .prev").hide();
		} else {
			$("#flickr_gallery .large .prev").show();
		}

		if(current == total) {
			$("#flickr_gallery .large .next").hide();
		} else {
			$("#flickr_gallery .large .next").show();
		}

	}

	function gallery_load_img(source, destination, callback) {

		$(destination).addClass("large_loading");

		if(flickr_captions == 1) {
			$("#flickr_gallery .caption span").text("");
		}

		var path = source.attr('href');

		lastnewimg = path;

		var imgsrc = path;
		var newimg = new Image();
		newimg.src = imgsrc;
		newimg.onload = function() {

			$("img.dynamic", destination).css("z-index", "90");

			var randomnumber = Math.floor(Math.random()*11);
			$(destination).prepend('<img src="'+imgsrc+'" style="display: none; z-index: 100;" class="dynamic" />');
			newimg.onload = function(){};
		
			$(destination).removeClass("large_loading");

			$("#flickr_gallery ul li.on").removeClass("on");

			source.closest("li").addClass("on");

			$("img.dynamic:first", destination).fadeIn("1000",function(){

				$("img.dynamic", destination).not(this).remove();

				if(flickr_captions == 1) {
					$("#flickr_gallery .caption span").text($("#flickr_gallery ul li.on img").attr("alt"));
				}

				if($.isFunction(callback)) {
					callback.call();
				}

			});
		}
		newimg.src = imgsrc;
	}

	function gallery_start() {

		var obj = $("#flickr_gallery ul li.on");
		var length = $("#flickr_gallery ul li").length;
		var pos = obj.index() + 1;

		if(pos == length) {
			
			setTimeout(function() {
				$("#flickr_gallery .jcarousel-next").not("[disabled='true']").click();
			},5000);

			if($("#flickr_gallery .jcarousel-next").is("[disabled='true']")) {
				gallery_stop();
				setTimeout(function() {c.scroll("0")},7000);
			}

		} else {

			gallery_timeout = setTimeout(function() {
				var gallery_next = obj.next("li");
				gallery_load_img($("a", gallery_next), $("#flickr_gallery .large"), function(){
					gallery_start();
				});
				
			},7000);

		}
	}

	function gallery_stop() {
		clearTimeout(gallery_timeout);
	}

});

