/**
 * HKIFF Society Photo Slideshow
 * Copyright (c) 2009 Vizztech
 */
;(function($)
{
	var
		currentIndex = 0,
		navButtons = [],
		links = [],
		paused = false,
		ctnrSlideshow = false,
		ctnrNavIndex = false,
		ctnrDescription = false;
		
	$.fn.extend({

		activatePhotoSlideShow: function()
		{
			if (!paused)
			{
				ctnrSlideshow.cycle('resume', false);
			}
		},

		deactivatePhotoSlideShow: function()
		{
			if (!paused)
			{
				ctnrSlideshow.cycle('pause');
			}
		},

		initIndexSlideShow: function() 
		{
			return this.each(function() {
				// give elements an index
				$('#slideshow-photos img', $(this)).each(function(idx){
						$(this).data('idx', idx);
					});
				
				// list buttons
				ctnrNavIndex = $('#slideshow-photo-navindex');

				$('#slideshow-photo-navindex a', $(this)).each(function(idx){
					$(this).data('idx', idx);

					links.push({link: $(this).attr('href'), external: $(this).attr('target') == '_blank'});
					$(this).attr('href', '#').removeAttr('target');

					navButtons[idx] = $(this);
				}).click(navBtnClick);

				$('#slideshow-photos img').each(function(idx) {
					$(this).data('ss-idx', idx);
				}).click(function() {
					var link = links[$(this).data('ss-idx')];
					if (link)
					{
						if (link.external)
						{
							window.open(link['link']);
						}
						else
						{
							document.location.href = link['link'];
						}
					}
				});

				// activate description cycle
				ctnrDescription = $('#slideshow-photo-info', this);

				ctnrDescription.cycle({
					speed: 'fast',
					after:  onTextAfter,
				    speed:   500, 
					timeout: 0
				});

				// activate cycle
				ctnrSlideshow = $('#slideshow-photos', $(this));
				ctnrSlideshow.cycle({
					before: onBefore,
					after:  onAfter,
					next: '#slideshow-photo-nav-next',
					prev: '#slideshow-photo-nav-prev',
					timeout: 7000,
					fx: 'fade',
				    speed:   500, 
					pause: true
				});
				
				$('#slideshow-photo-nav-pause').click(pauseClick);
			});
		}
	});

	function navBtnClick()
	{
		var idx = $(this).data('idx');
		ctnrSlideshow.cycle(idx);
		currentIndex = idx;
		highlightSelected();
	}

	function onBefore(i, o, opt)
	{
		var idx = $(o).data('idx');
		currentIndex = idx;
		if (ctnrDescription)
		{
			ctnrDescription.cycle(idx);
		}

		highlightSelected();
	}

	function highlightSelected()
	{
		$('a', ctnrNavIndex).removeClass('active'); // clear highlight
		navButtons[currentIndex].addClass('active');
	}

	function onAfter(i, o, opt)
	{
	}

	function onTextAfter(i, o, opt)
	{
		if (jQuery.browser.msie)
		{
			$('div', ctnrDescription).each(function()
			{
				this.style.removeAttribute('filter'); 
			});
		}
	}

	function pauseClick()
	{
		if (ctnrSlideshow)
		{
			if (paused)
			{
				$(this).removeClass('active');
				ctnrSlideshow.cycle('resume', true);
			}
			else
			{
				$(this).addClass('active');
				ctnrSlideshow.cycle('pause');
			}
			paused = !paused;
		}
	}

})(jQuery);
