/**
 * Gallery.js
 * @author Ben Tadiar <ben@assemblystudios.co.uk>, Andy Bacon <andy@assemblystudios.co.uk>
 * @version 0.1
 * @todo Add image transitions
 */
(function ($) {
	"use strict";
	$.fn.gallery = function (config) {
		var defaults = { cycle: false, interval: 10000, hoverTrigger:false },
			options = $.extend({}, defaults, config),
			selector = this.attr('id'),
			image = $('#' + selector + ' .image'),
			urls = getUrls(),
			timer = null,
			current = 0,
			action = 'next';
		
		image.attr('src', urls[current]);
		if (options.cycle && !options.hoverTrigger) { timer = window.setTimeout(loadNext, options.interval); }
		
		$('#' + selector + ' .next').click(function () {
			loadNext();
		});
		
		$('#' + selector + ' .prev').click(function () {
			loadPrev();
		});
		
		$('#' + selector + ' .thumbs span').click(function (event) {
			event.preventDefault();
			var id = $(this).attr('rel');
			loadImage(id);
			current = id;
		});
		
		// if the gallery instance is set to cycle on hover event
		if ( options.hoverTrigger ){
			$('#' + selector).hover(
					
					function(){
						loadNext();
					},
					
					function(){
						window.clearTimeout(timer);
						image.attr('src', urls[0]);
						current = 0;
					}
					
				);
		}
		
		function loadPrev() {
			var prev = current - 1;
			if (current === 0) { prev = urls.length - 1; }
			action = 'prev';
			loadImage(prev);
			current = prev;
		}
		
		function loadNext() {
			var next = parseInt(current, 10) + 1;
			if (current === urls.length - 1) { next = 0; }
			action = 'next';
			loadImage(next);
			current = next;
		}
		
		function loadImage(index) {
			if (timer !== null) { window.clearTimeout(timer); }
			$('#' + selector + ' .loader').show();
			var newImage = new Image();
			newImage.src = urls[index];
			newImage.onload = function () {
				$('#' + selector + ' .loader').hide();
				image.attr('src', urls[index]);
				if (options.cycle) { timer = window.setTimeout(loadNext, options.interval); }
			};
			newImage.onerror = function () {
				if(action == 'next') loadNext();
				else loadPrev();
			}
		}
		
		function getUrls() {
			var temp = [];
			$('#' + selector + ' .thumbs').find('span').each(
				function (i, val) {
					temp[i] = $(val).attr('id');
					$(val).attr('rel', i);
				}
			);
			return temp;
		}
	};
}(jQuery));
