// 02012012KB v1.1

// $('.ma_slideshow').mAss();

(function ($) {

	// Massachusetts Accessibile Slide Show
	$.fn.mAss = function (options) {

		var defaults = {
				fx: 'none',
				speed:  1000,
				timeout: 0
			},
			settings = $.extend({}, defaults, options);

		return this.each(function (idx) {
			var $t = $(this),
				kbU;

			// prepare slideshow;
			$('div.slides > ul', $t).cycle({
				fx: settings.fx,
				speed: settings.speed,
				timeout: settings.timeout,
				next: $('.next', $t),
				//prev: $('.prev', $t),
				pager: $('.slides_nav', $t),
				pagerAnchorBuilder: function (i, slide) {
					// attaches necessary jQuery cycle events to tabs
					var $ss = $(slide).closest('.ma_slideshow');
					return $('.slides_nav li', $ss).eq(i);
				},
				after: function (curr, next, ops) {
					if (kbU) {
						$(next).find('a:first').focus();
					}
				},
				pauseOnPagerHover: true,
				pause: true
			});

			// prepare slideshow controls
			var $ss_pause_play = $('.ss_pause_play', $t);
			$ss_pause_play.addClass('paused').css('visibility', 'visible').text('Pause');

			$ss_pause_play.toggle(function () {
				$(this).closest('.ma_slideshow').find('div.slides > ul').cycle('pause');
				$(this).attr({ 'class': 'ss_pause_play play'}).text('Play');
			}, function () {
				kbU = false;
				$(this).closest('.ma_slideshow').find('div.slides > ul').cycle('resume', true);
				$(this).attr({ 'class': 'ss_pause_play paused'}).text('Pause');
			});
			
			// on keyboard focus within slideshow => pause
			$t.delegate('a', 'focus', function () {
				kbU = true;
				if (!$t.find('.slides > ul')[0].cyclePause) { //check for paused mAss
					$t.find('div.slides > ul').cycle('pause');
					$ss_pause_play.attr({ 'class': 'ss_pause_play play'}).text('Play');
				}
			});

			// accessibility considerations & aria compatability. winning
			var ss_id = 'ma_ss-' + idx, // unique slideshow id for aria-labelledby
				ss_titles = $('h3', $t), // add descriptive text to buttons
				ss_nav_a = $('.slides_nav a', $t), // get slide # triggers
				ss_lm_a = $('.learn_more > a', $t); // get learn_more
			
			// set unique id
			$('> h2', $t).attr('id', ss_id);

			// aria region
			$t.attr('role', 'region').attr('aria-labelledby', ss_id);

			// aria polite on slides container
			$t.find('div.slides > ul').attr('aria-live', 'polite');

			// iterate over slide controls, insert accessibility html based on slide title's
			$.each(ss_titles, function (i, s) {
				ss_titles[i] = '<span class="accessibility"> about ' + s.innerHTML + '</span>';
				$(ss_nav_a[i]).append(ss_titles[i]);
				$(ss_lm_a[i]).append(ss_titles[i]);
			});
		});
	};

})(jQuery);

jQuery(document).ready(function ($) {

	$('body').addClass('js');
	$('.ma_slideshow').mAss({timeout: 7000});

});
