/*
jquery.slideshow.js
-------------------
A simple slideshow plugin for jQuery, developed for NSCU. This is the uncompressed version; use
jquery.slideshow-compressed.js for live environments. A whopping 4KB! :-)

Usage
-----  

The slideshow object is instantiated like so (note that it requires the DOM to have loaded!):

	jQuery(document).ready(function() { jQuery.slideshow(); });

You can override the default params by passing an anonymous object when initializing, e.g.: 

	jQuery(document).ready(function() { 
		jQuery.slideshow({
			autoPlay: false,
			fadeSpeed: 1200
		}); 
	});

The optional parameters are documented in the code. They determine the various classes used by the script
and fade-in / fade-out speeds. None of the CSS classes / IDs are hardcoded, so it should be very portable 
to other sites and uses.


Notes
-----

This plugin expects the "pages" of the slideshow to already exist in the web page. These are just elements containing whatever
content needs to be hidden/shown. The navigation is dynamically generated and inserted into the slideshow element, based on 
whatever classes are specified in the options.

Sample HTML:

<ul id="homePromo" class="homePromo">
	<!-- page 1 -->
	<li class="promoItem promoItem1 current">
		<div>
			<h2><img alt="Life on your terms." src="<?php echo $rootURL; ?>/SharedContent/images/HomeWidget/promoHeading.gif" /></h2>
			<a class="primaryAction" href="#" title="Open a 3% term deposit"><img src="<?php echo $rootURL; ?>/SharedContent/images/HomeWidget/promoCtaButton.gif" /></a>
			<a class="secondaryAction" href="#" title="Learn more">Learn more</a>
		</div>
	</li>
	<!-- page 2 -->
	<li class="promoItem promoItem2">
		<div>
			<h2>Achieve your portfolio's potential.</h2>
			<a class="primaryAction" href="#" title="Open a 3% term deposit"><img src="<?php echo $rootURL; ?>/SharedContent/images/HomeWidget/promoCtaButton.gif" /></a>
			<a class="secondaryAction" href="#" title="Learn more">Learn more</a>
		</div>
	</li>
</ul>

Limitations
-----------

You can only instantiate one slideshow in a page.
*/
(function($){
	$.extend({

		options: {},
		slideshowPages: [],
		autoPlayInterval: null,

		// our constructor. This creates and (if required) starts auto-playing the slideshow
		slideshow: function(opts){
			var options = {
				slideshowElement: "promoShow",			// the name of the wrapper slideshow elements
				slideshowPageClass: "promoItem",		// the class name of the pages
				slideshowNavClass: "promoPagination",	// the class applied to the (generated) nav element 
				slideshowNavItemPrefix: "item",			// the class applied to all nav items 
				slideshowNavItemSelected: "current",	// the nav item class identifying the current page
				slideshowPlayBtnClass: "control",		// the class of the play button
				slideshowPlayBtnActiveClass: "play",	// the class of the play button when auto-playing
				autoPlay: true,							// whether or not it should auto-play on instantiation
				currentPage: 1,							// the current selected page
				fadeSpeed: 800,							// the speed at which the pages fade in and out 
				pageDuration: 6000,						// how long each page should appear
				useHBXTracking: false,				  // whether or not we'll log the user activity with HBX

				// HBX Tracking settings
				trackingDebug: false, // when enabled, alerts all messages sent to Omniture
				trackingPage: "",	 // the page the widget is being used on (e.g. "Homepage", "About Us")
				trackingClickPageSuffix: "(nav page clicked)",
				trackingLearnMoreSuffix: "(learn more)",
				trackingMainButtonSuffix: "(page clicked)"
			};
			jQuery.extend(options, opts);
			this.options = options;

			// locate the pages in the slideshow and stash them in slideshowPages
			this.slideshowPages = $("." + options.slideshowPageClass);

			// create and insert the slideshow nav 
			this.createNav();

			// if HBX tracking is enabled, override the default "Learn More" links
			if (options.useHBXTracking)
				this.overrideSlideshowPageLinks();

			// if requested, start auto-play
			if (options.autoPlay)
				this.startAutoPlay();
		},

		// called on initialization; this creates and embeds the navigation into the DOM 
		createNav: function(){
			var navLi = $("<li></li>");
			var nav = $("<ul></ul>");
			navLi.attr("class", this.options.slideshowNavClass);

			var currSlideshow = this;
			var playBtn = $("<li></li>");
			playBtn.text("pause");
			playBtn.addClass(this.options.slideshowPlayBtnClass);

			if (this.options.autoPlay)
				playBtn.addClass(this.options.slideshowPlayBtnActiveClass);

			playBtn.bind("click", function(e) { currSlideshow.toggleAutoPlay(e); });
			nav.append(playBtn);
			
			// add the nav items
			for (var i=1; i<=this.slideshowPages.length; i++){
			var item = $("<li></li>");
			item.addClass(this.options.slideshowNavItemPrefix + i);
				if (this.options.currentPage == i)
					item.addClass(this.options.slideshowNavItemSelected);

				item.bind("click", {page: i},  function(e) { e.data.isFromUser = true; currSlideshow.showPage(e); });
				item.text(i);
				nav.append(item);
			};

			// insert the nav into the page
			navLi.append(nav);
			$("." + this.options.slideshowElement).prepend(navLi);
		},

		// Shows an actual page, hiding the last one
		showPage: function(e){
			var page = e.data.page; 
			var opts = this.options;
			if (page == opts.currentPage)
				return;
			if (e.data.isFromUser && opts.useHBXTracking && window._hbLink)
			{
				var altContent = this._getImageAltContent(page, opts);
				var trackingStr = this._cleanHBXStr(opts.trackingPage + " " + altContent + " " + opts.trackingClickPageSuffix);
				window._hbLink(trackingStr);
				if (opts.trackingDebug)
					alert(trackingStr);
			}
			this.stopAutoPlay();
			this._updateNavClasses(opts, opts.currentPage, page);
			this.options.currentPage = page;
		},
		// called by the auto-play mechanism only
		showNextPage: function(){
			var opts = this.options;
			var currPage = opts.currentPage;
			var nextPage = (currPage % this.slideshowPages.length) + 1;
			this._updateNavClasses(opts, currPage, nextPage);
			this.options.currentPage = nextPage;
		},
		startAutoPlay: function(){
			$("." + this.options.slideshowNavClass + " li:first").removeClass(this.options.slideshowPlayBtnActiveClass);
			this.options.autoPlay = true;
			var currSlideshow = this;
			this.options.autoPlayInterval = setInterval(function() { currSlideshow.showNextPage(); }, this.options.pageDuration);
		},
		stopAutoPlay: function(){
			$("." + this.options.slideshowNavClass + " li:first").addClass(this.options.slideshowPlayBtnActiveClass);
			window.clearInterval(this.options.autoPlayInterval);
			this.options.autoPlay = false;
		},
		toggleAutoPlay: function(){
			if (this.options.autoPlay){
				this.stopAutoPlay();
			} else {
				// we immediately move to the next page. If we wait, it looks like clicking the button did nothing
				this.showNextPage();
				this.startAutoPlay();
			}
		},
		overrideSlideshowPageLinks: function(){
			var numPages = this.slideshowPages.length;
			var opts = this.options;
			for (var i=1; i<=numPages; i++)
			{
				var altContent = this._getImageAltContent(i, opts);
				// append click handler to main button
				var trackingStr = this._cleanHBXStr(opts.trackingPage + " " + altContent + " " + opts.trackingMainButtonSuffix);
				$("." + opts.slideshowPageClass + i + " .primaryAction").bind("click", {str:trackingStr, debug:opts.trackingDebug}, 
					function(e) {
						window._hbLink(e.data.str);
						if (e.data.debug)
							alert(e.data.str);
					}
				);
				// append click handler to Learn More link
				var trackingStr = this._cleanHBXStr(opts.trackingPage + " " + altContent + " " + opts.trackingLearnMoreSuffix);
				$("." + opts.slideshowPageClass + i + " .secondaryAction").bind("click", {str:trackingStr, debug:opts.trackingDebug}, 
					function(e) {
						window._hbLink(e.data.str);
						if (e.data.debug)
							alert(e.data.str);
					}
				);
			}
		},
		_getImageAltContent: function(page, opts){
			var images =$("." + opts.slideshowPageClass + page + " img");
			return $(images[0]).attr("alt");
		},
		_updateNavClasses: function(opts, from, to){
			$("." + opts.slideshowPageClass + from).fadeOut(opts.fadeSpeed);
			$("." + opts.slideshowNavItemPrefix + from).removeClass(opts.slideshowNavItemSelected);
			$("." + opts.slideshowPageClass + to).fadeIn(opts.fadeSpeed);
			$("." + opts.slideshowNavItemPrefix + to).addClass(opts.slideshowNavItemSelected);
		},
		_cleanHBXStr: function(str)
		{
			return str.replace(/[^a-zA-Z()+,-.0-9?@_{}\[\] ]/g, "");
		}
	});
})(jQuery);

