/*
 * rrSpotlight 1.0.0 - Spotlight by Reading Room
 *
 * Copyright (c) 2009 Reading Room Ltd (readingroom.com)
 * Written by Keng Jin Chew (keng.jin@readingroom.com) 
 */
(function($){ $.fn.rrspotlight = function(){

	// Loop through each in case there are multiple selected
	return $(this).each(function(){
		var current = 0,
			parent,
			items = $(this).find(".primarySpotlightInner div.spotlightItem"),
			nav = $(this).find(".featureNavContainer");
		
		// Navigation functions - placed inside loop for closure
		function showItem(c, itm, nav) {
			current = c;
			items.hide().eq(current).show();
			nav.removeClass("on").eq(current+1).addClass("on");
			return false;
		}

		function showDir(dir, items, nav) {
			var next = ((0 > dir && current > 0) || (0 < dir && current < (items.length-1))) ? current + dir : current;
			return showItem(next, items, nav);
		}
		
		// only show nav if more than one
		if (1 < items.length) {

			// hide all items
			items.hide(); 
		
			// navigation html
			var html = '<ul class="featureNav"><li class="prev"><span><a href="#" title="Previous promotion">&lt; <em class="offscreen">Previous</em></a></span></li>';
			items.each(function(i){
				html += '<li><span><a href="#" title="Promotion ' + (i+1) + ' of 5">' + (i+1) + '</a></span></li>';
			});
			html += '<li class="next"><span><a href="#" title="Next promotion"><em class="offscreen">Next</em> &gt;</a></span></li></ul>';
			
			// append navigation
			nav.append($(html));
			
			// bind navigation events
			var nav2 = nav.find("ul.featureNav a");
			nav2.each(function(){
				parent = $(this).parent().parent();
				if (parent.hasClass("prev")) {
					$(this).bind("click", function(e){
						return showDir(-1, items, nav.find("ul li"));
					});
				} else if (parent.hasClass("next")) {
					$(this).bind("click", function(e){
						return showDir(1, items, nav.find("ul li"));
					});
				} else {
					$(this).bind("click", function(e){
						return showItem($(this).text() - 1, items, nav.find("ul li"));
					});
				}
			});
			
			// select first item
			nav2.eq(1).click();
		}
	});
	
}})(jQuery);

$(document).ready(function(){
	$('.primarySpotlight').rrspotlight();
});
