/*

	nfGallery - Simple gallery

*/
/*
Array.prototype.sum = function() {
	for(var i=0,sum=0; i<this.length; sum+=this[i++]);
	return sum;
}
*/

jQuery.fn.nfGallery = function(user_opts) {
	$ = jQuery;

	var opts = $.extend({
		'fade_speed_thumb': 200,
		'fade_speed_image': 500,
		'thumb_opacity': 0.4
	}, user_opts);
	
	var gallery = this;

	function setImage(img, user_initiated) {
		var big_img_src = img.parents('a.thumb').attr('href');
		var big_img = $(new Image()).attr('src', big_img_src).fadeTo(0, 0);
		gallery.find(".image img").remove();
		gallery.find(".image").append(big_img);
		big_img.fadeTo(opts['fade_speed_image'], 1.0);

		// Callback
		if (opts.onImgSelect) { opts.onImgSelect(img, user_initiated); }
	}

	function checkImgLoaded() {
		var img = $(this);

		if (img.hasClass('events_loaded')) { return; }

		//var li_width = img.parents('li:eq(0)').innerWidth();
		//$("div.heights").append(img.attr('src') + " - img.width: "+ img.innerWidth() + " -- li_width = "+ li_width +"<BR>");

		if (img.hasClass('img_loaded')) {
			attachImgEvents(img);
		} else {
			img.load(function() {
				attachImgEvents(img);
			});
		}
	}

	function attachImgEvents(img) {
		img.fadeTo(0, opts['thumb_opacity']).hover(function() {
			img.stop().fadeTo(opts['fade_speed_thumb'], 1);
		}, function() {
			img.stop().fadeTo(opts['fade_speed_thumb'], opts['thumb_opacity']);
		});
		img.parents("a.thumb").click(function() {
			setImage(img);
			return(false);
		});

		img.addClass('events_loaded');

		// ---- expand range of slider to fit newly loaded image
		var slidebar = gallery.find(".slider");
		var max_subtracted = slidebar.slider('option', 'max_subtracted'); // boolean for whether or not thumbs_width has been subtracted from the ul_width (it has to be done exactly once)
		var ul_width = slidebar.slider('option', 'max');
		var thumbs_width = gallery.find(".thumbs").width();
		var li_width = img.parents('li:eq(0)').innerWidth();

		if ((ul_width > thumbs_width) && !max_subtracted) {
			ul_width -= thumbs_width;
			slidebar.slider('option', 'max_subtracted', true);
		}

		//$("div.heights").append(img.attr('src') + " - current: "+ ul_width + " - new: "+ (ul_width + li_width) +" -- li_width = "+ li_width +"<BR>");
// http://lord.nuklear.org/pics.php
		slidebar.slider('option', 'max', ul_width + li_width);
		// ----
	}


	gallery.addClass('script').removeClass('noscript');

	gallery.find(".thumbs").after("<div class='slider'></div>");
	gallery.find(".slider").slider({
		min: 0,
		max: 0,
		max_subtracted: false, // custom option, see above
		handle: '.handle',
		slide: function(event, ui) {
			gallery.find(".thumbs ul").css('left', ui.value * -1);
		}
	});

	gallery.find("a.thumb img").each(checkImgLoaded);

	// ---- set active image
	var active = gallery.find("li.active a.thumb img:first");
	if (active.size() == 0) {
		active = gallery.find("a.thumb img:first");
	}
	// ----
	
	active.each(function() {
		setImage($(this), false);
	});

	return(this);
}

