/* 
	Author: Daniel Kremin, Christian Hermann Quinders
*/

$(function(){

	$('.tabbed-content').tabbedContent();

});

//
// tabbedContent
//
(function($) {
	//
	// plugin definition
	//
	$.fn.tabbedContent = function(options) {
		// build main options before element iteration
		var opts = $.extend({}, $.fn.tabbedContent.defaults, options);
		
		// iterate and reformat each matched element
		return this.each(function() {
			var $this = $(this),
				$frame = $( opts.frame, this ),
				$wrapper = $( opts.wrapper, this ),
				$items = $( opts.items, this ),
				$nav = $( opts.nav, this ),
				active = 0,
				animating = false;

			$nav.click(function( e ){
				jump( getPos( '#' + this.href.split('#').pop() ) );
				e.preventDefault();
			});
			
			$this.bind('prev',function(e){
				prev();
			}).bind('next',function(e){
				next();
			}).bind('goto',jump);

			function next() {
				var pos = ( active+1 < $items.length ) ? active+1 : 0 ;
				jump( pos );
			};
			
			function prev() {
				var pos = ( active == 0 ) ? $items.length-1 : active-1 ;
				jump( pos );
			};
			
			function jump( pos ) {

				if( !animating && active != pos ) {

					animating = true;
					
					var $active = $items.eq(active),
						$target = $items.eq(pos),
						target_ID = '#'+$target.attr('id');
					
					$active.fadeOut(opts.duration, function(){
						$active.removeClass('active');
						$wrapper.animate({
							height: $target.height()
						}, opts.duration, function(){
							$target.fadeIn(opts.duration, function(){
								$target.addClass('active');
								animating = false;
							});
						});
					});
					
					$nav
						.filter('.active')
							.removeClass('active')
						.end()
						.filter('[href$=' + target_ID + ']')
							.addClass('active');
					
					window.location.hash = target_ID;

					active = pos;
					

				}
				
			};
			
			// get elements id as integer position from $items
			function getPos( elem ) {
				return $items.index( $( elem ) );
			};
			
			// init widget 
			function init() {
				var start = opts.start,
					hash = window.location.hash.replace('#','');
				if( hash != '' ) {
					start = getPos( '#' + hash );
				}
				$items.not( $items.eq( start ) ).hide();
				$wrapper.height( $items.eq( start ).height() ).width('auto');
				$nav.eq( start ).addClass('active');
				active = start;
			}
			
			init();

		});
	};
	//
	// plugin defaults
	//
	$.fn.tabbedContent.defaults = {
		frame: '.frame',
		wrapper: '.slides',
		items: '.slide',
		nav: '.nav a',
		duration: 250,
		start: 0
	};
//
// end of closure
//
})(jQuery);

