// GALLERY PLUGIN

jQuery.fn.gallery = function(options) {

	// options and defaults
	var defaults = {  
		fade: 500,  
		pause: 5000,
		method: 'fade',
		auto: true,
		controls: true
	};  
	var options = $.extend(defaults, options);
	
	this.each(function() {
	
		that = $(this);
		
		// variables
		var current = 1;
		var interval;
		
		// sort out slides
		var slideshow = that.find(".slides");
		var slides = slideshow.children("li");
		var number = slides.length;
		if (number < 2) { return; }
		
		// sort out controls
		that.find(".paging").remove();	// get rid of any existing .paging element
		
		if (options.controls == 'hero') { // special case – front page hero
		
			that.find(".controls").remove();
			slideshow.after("<ul class='controls'></ul>");
			controls = that.find('.controls');
			for (var i=1; i<=number; i++) {
				var text = $(slides[i-1]).find('h2 span').text();
				if (i==1) {
					controls.append("<li class='current'><a>" + text + "</a></li>");
				} else {
					controls.append("<li><a>" + text + "</a></li>");
				}
			}
			controls.find("li a").click(function() {
				var pos = $(this).parent().index() + 1;
				options.auto = false;
				change(pos);
			});		
		} else if (options.controls) { // if we want controls to be visible...
			slideshow.after("<ul class='paging'></ul>");
			var controls = that.find(".paging");
			for (var i=1; i<=number; i++) {
				controls.append((i == 1) ? "<li class='current'><a><span>" + i + "</span></a></li>" : "<li><a><span>" + i + "</span></a></li>");
			}
			controls.find("li a").click(function() {
				if (options.auto = 'semi') { options.auto = false; }
				change(parseInt($(this).text()));
			});
		}
		
		// internal functions
		function change(next) {
		
			if (next == current) { return; }
			
			if (!next) {
				var next = (current === number) ? 1 : current + 1;
			}
			
			var slide_now = $(slides[current-1]);
			var slide_next = $(slides[next-1]);
			
			// change them
			
			slide_next.css('zIndex', 5).show();
			if (options.method == "slide") {
				slide_now.css('zIndex', 10).slideUp(options.fade);
			} else {
				slide_now.css('zIndex', 10).fadeOut(options.fade);
			}
			
			// update the controls
			if (options.controls) {
				controls.children('li').removeClass('current');
				controls.children('li:nth-child(' + next + ')').addClass('current');
			}
			
			current = next;
			
			timer();
			
		}
		
		function timer() {
		
			clearInterval(interval);
			
			if (!options.auto) { return; }
			
			interval = setInterval(function(){
				change();
			}, options.pause + options.fade);
			
		}
		
		// set it all in motion
		timer();
		
	});
	return this;
	
};
