﻿(function($j) {
	$j.fn.photoFlipper = function(options) {
		var rootObj = this;
		var opts = $j.extend({}, $j.fn.photoFlipper.defaults, options);
		var timerCookie = null;
		var current = 0;
		var buttons = $j("#photo-buttons > a", rootObj);

		//--check that we have images and buttons
		if (buttons.length == 0) {
			alert('No flipper buttons found');
			return;
		}

		if ($j("div.photo", rootObj).length == 0) {
			alert('No images found');
			return;
		}

		//--show first image if called for
		if (opts.animateInitialImage)
			changeImage($j(buttons[current]));
		else
			wireTimer();

		//--wire click events
		$j("#photo-buttons a", rootObj).each(
        function() {
        	var link = $j(this);
        	link.click(function() {
        		if (link.hasClass('current-photo') == false)
        			changeImage(link);
        		return false;
        	}
            );
        }
        );

		function wireTimer() {
			//--start timer
			if (timerCookie != null)
				clearTimeout(timerCookie);

			timerCookie = setTimeout(nextImage, opts.wait);
		}

		function nextImage() {
			if (current < buttons.length - 1)
				current++;
			else
				current = 0;

			changeImage($j(buttons[current]));
		}

		function changeImage(selectedLink) {
			var id = selectedLink.context.id.replace("btn-", "");
			$j("#photo-buttons a.current-photo").toggleClass("current-photo", false);
			selectedLink.addClass("current-photo", true);

			$j("div.photo:visible", rootObj).fadeOut(opts.fade);
			$j("#photo-" + id, rootObj).fadeIn(opts.fade);

			current = parseInt(id) - 1;
			wireTimer();
		}
	};
	// private function for debugging
	function debug(line) {
		if (window.console && window.console.log)
			window.console.log(line);
	};
	$j.fn.photoFlipper.defaults = {
		wait: 2000,
		fade: 400,
		animateInitialImage: false
	};
})(jQuery);

