// JavaScript Document


$(function() {
	
	//
	// INITIALIZE THE GALLERY/SLIDESHOW
	//
		$('.gallery_slideshow').each( function() {
			var gallery = this;
			
			// get number of images
			var count = $('.gallery_link', this).length;
			if (count > 0) {
				gallery.count = count;
				
				// ON LINK
				$('.gallery_link', gallery).click(function() {
					if ( !$(this).is('.gallery_link_active') ) {
						gallery.onStop();
						
						// deactivate / activate links
						$('.gallery_link_active', gallery).removeClass('gallery_link_active');
						$(this).addClass('gallery_link_active');
						
						// get index of link and show corresponding slide
						var idx = ( $(this).text() - 1 );
						gallery.onShow( idx );
					}
				});
				
				// ON PLAY
				$('.gallery_play', this).click(function() {
					gallery.onNext();
					gallery.onPlay();
				});
				
				// ON STOP
				$('.gallery_stop', this).click(function() {
					gallery.onStop();
				});
				
				
				// MOVE TO NEXT IMAGE
				gallery.onNext = function() {
					// get next link index
					var idx = $('.gallery_link_active', this).text();
					if (idx == this.count) idx = 0;
					
					// deactivate / activate links
					$('.gallery_link_active', this).removeClass('gallery_link_active');
					$('.gallery_link:eq(' + idx + ')', this).addClass('gallery_link_active');
					this.onShow( idx );
				};
				
				// SHOW/HIDE SLIDES
				gallery.onShow = function( idx ) {
					if ( this.fading ) {
						$('.gallery_slide:visible', this).fadeOut();
						$('.gallery_slide:eq(' + idx + ')', this).fadeIn();
					} else {
						$('.gallery_slide:visible', this).hide();
						$('.gallery_slide:eq(' + idx + ')', this).show();
					}
				};
				
				// PLAY THE SLIDESHOW
				gallery.onPlay = function() {
					$('.gallery_play', this).hide();
					$('.gallery_stop', this).show();
					this.timer = setInterval( function() { gallery.onNext(); }, this.speed );
				};
				
				// STOP THE SLIDESHOW
				gallery.onStop = function() {
					$('.gallery_play', this).show();
					$('.gallery_stop', this).hide();
					if (this.timer) {
						clearInterval( this.timer );
					}
				};
				
				
				// set slideshow speed
				gallery.speed = 2000;
				if ( $('input[name="speed"]', gallery).length == 1 ) {
					if ( !isNaN($('input[name="speed"]', gallery).val()) ) {
						gallery.speed = $('input[name="speed"]', gallery).val();
					}
				}
				
				// set slideshow transition
				gallery.fading = false;
				if ( $('input[name="fading"]', gallery).length == 1 ) {
					if ( $('input[name="fading"]', gallery).val() == 1 ) {
						gallery.fading = true;
					}
				}
				
				// autoplay
				gallery.timer = null;
				gallery.onStop();
				if ( $('input[name="autoplay"]', gallery).length == 1 ) {
					if ( $('input[name="autoplay"]', gallery).val() == 1 ) {
						gallery.onPlay();
					}
				}
				
			}
		});
	// end initialize
	
});

