
(function($){$.fn.photoviewer = function(data, opts)
{
	this.each(function()
	{
	
	var obj				= this;
	var index			= 0;
	var busy			= false;
	var pause			= false;
	var	imgcache		= [];
	var captioncache	= [];
	var queue			= [];
	var caption			= '';
	
	var speed			= opts.speed || 600;
	var tmpspeed		= speed;
	var easing			= opts.easing || 'easeOutExpo';
	var noimagepreload	= opts.noimagepreload || false;

	var newphoto;
	var direction;
	var unlocktimer;
	
	// Prepare loading message
	$('.pv-loading', obj).css({
		opacity: 0,
		visibility: 'visible'		
	});
	
	// Find previous/next index
	var findindex = function(calc)
	{
		myindex		= index + calc;
		if (myindex < 0) myindex = data.length + calc;
		if (myindex > data.length - 1) myindex = -1 + calc;
		return myindex;
	}

	// Previous photo
	var previous = function()
	{
		index = findindex(-1);
		direction = 0;
		setphoto(data[index]);
		return false;
	};

	// Next photo
	var next = function()
	{
		index = findindex(1);
		direction = 1;
		setphoto(data[index]);
		return false;
	};
	
	// Next & previous buttons
	$('.prev', obj).click( function(){
		previous();
	});
	
	$('.next', obj).click( function(){
		next();
	});

	// Load new photo html
	var loadphoto = function(fig_id, preload)
	{
		preload = preload || false;
		if (typeof imgcache[fig_id] == 'undefined')
		{
			var data, html;
			data = {
				name	: 'photoviewer_photo',
				fig_id	: fig_id,
				width	: opts.width,
				height	: opts.height
			};
			$.any.rest.get('anymeta.html.scomp',
					data,
					function (result)
					{
						html = result.html;
                                		imgcache[fig_id] = html;
                                		
						if (!preload) changephoto(fig_id, html);

					},
					function (error)
					{
						$.log(error);
					});
		} else
		{
			if (!preload) changephoto(fig_id, imgcache[fig_id]);
		}
	};
	
	// Change photo
	var changephoto = function(fig_id, html)
	{
		width = (direction ? '' : '-') + opts.width;
		newphoto = $('<div>')
			.addClass('pv-photo')
			.attr('style', 'left:' + width + 'px') // for some reason it ignores css(left:500) ...
			.html(html)
			.appendTo($('.pv-photo-wrapper', obj))
			.find('.fig_image, .dv_image')
				.img_annotations()
				.img_zoomer();

		loadcaption(fig_id);
	};

	// Load new caption html
	var loadcaption = function(fig_id, preload)
	{
		var data;
		preload = preload || false;
	
		if (typeof captioncache[fig_id] == 'undefined')
		{
			data = {
				name	: 'photoviewer_caption',
				fig_id	: fig_id
			};
			$.any.rest.get('anymeta.html.scomp',
					data, 
					function(result)
					{
						if (!preload)
						{
							caption = captioncache[fig_id] = result.html;
						}
						loadcaptiondone();
					},
					function(error)
					{
						$.any.log(error);
					});
		} else if (!preload)
		{
			caption = captioncache[fig_id];
			loadcaptiondone();
		}
	};
	
	// Loading caption done, check if image is already loaded
	var loadcaptiondone = function()
	{
		img = $('.pv-photo', obj).eq(1).find('img:eq(0)');
		if (img.attr('complete') || noimagepreload)
		{
			slideinphoto();
		} else
		{
			img.load(function(){ slideinphoto(); });
		}
	};
	
	// Slide in new photo
	var slideinphoto = function()
	{
		shownewcaption();
		setOverviewActive();
		
		tmpspeed = (queue.length) ? 1 : speed;

		$('.pv-photo', obj).eq(0).animate({
				left: (direction ? '-' : '') + opts.width
			}, tmpspeed, easing, function()
			{
				$(this).remove();
				preload(index);
				busy = false;
				if (queue.length)
				{
					setphoto(queue.shift());
				}
			});
		
		$('.pv-photo', obj).eq(1).animate({left: 0 }, tmpspeed, easing);
	}
	
	// Refresh caption
	var shownewcaption = function()
	{
		$('.pv-caption', obj).html(caption);
		// $.any.ui.scan($('.pv-caption', obj));
	}
	
	// Slide in new picture
	var setphoto = function(fig_id)
	{
		if (!busy) loadphoto(fig_id);
		else queue.push(fig_id);
		busy = true;
	};
	
	// Preload ajax
	var preload = function()
	{
		loadphoto(data[findindex(1)],  1);
		loadphoto(data[findindex(1)], -1);
		loadcaption(data[findindex(1)],  1);
		loadcaption(data[findindex(1)], -1);
	};
	
	// ----------------- Indexing/Clicking ------------------
	
	// Make overview dots
	var overviewWrapper = $('.pv-overview', obj);
	var timeoutContinue;
	var makeOverview = function()
	{
		for (var x in data)
		{
			var pvdot = $('<span class="pv-dot" data-index="'+x+'">'+(parseInt(x) + 1) +'</span>').click(function()
			{
				pause = true;
				clearTimeout(timeoutContinue);
				timeoutContinue = setTimeout(function()
				{
					pause = false;
				}, 10000);
				gotoIndex(parseInt($(this).attr('data-index')));
			}).appendTo(overviewWrapper);
		}
	};
	
	var setOverviewActive = function()
	{
		$('.pv-dot', overviewWrapper).removeClass('pv-dot-active');
		$('.pv-dot', overviewWrapper).eq(index).addClass('pv-dot-active');
	};
	
	var gotoIndex = function(i)
	{
		if (i == index)
		{
			return false;
		}
		
		direction = (i > index) ? 1 : 0; 
		
		index = i;
	
		setOverviewActive();
		setphoto(data[index]);
	};
	
	// Clicking behaviours
	/*
$('.pv-previous', obj).click(previous);
	$('.pv-next', obj).click(next);
*/
	
	// Create overview div
	makeOverview();
	setOverviewActive();
	
	// Preload previous and next
	preload(0);
	
	// Reload every X seconds
	var switchInterval = setInterval(function()
	{
		if (!pause) next();
	}, 7000);
	
	});
}})(jQuery);

