$(function($)
{

	/**
	 * Our scroller has 3 main components: L/R scrolling arrows, the moving slider
	 * and clickable, hoverable portfolio items.
	 * 
	 */
	
	$.fn.gkdportfolio = function(options)
	{
	
		/**
		* Settings and extend options
		*/
		
		var settings = {
			initialId: 'f1',
			columnWidth: 4,
			columnPixels: 80,
			move: 12
		};
		
		// Extend options
		options = options || {};
		$.extend( settings, options );
		
		
		/**
		 * Basic functions variables dealing with getting/setting window ranges
		 */
		
		var isSliding = false;
		
		var window = {
			left: 0,
			right: 11,
			total: this.length * settings.columnWidth - 1,
			elements: this.length
		}
		
		function updateWindowRange( delta )
		{
			window.left += delta;
			window.right += delta;
		}
		
		/**
		 * Slides window left or right
		 * (Called on .scroll click)
		 */
		
		function slideWindow( id )
		{
			var scrollStatus = getScrollStatus();
			// Only run if the scroll is enabled
			if ( scrollStatus[ id ] == 'enabled' )
			{
				// Set isSliding so we don't run into problems double-clicking
				isSliding = true;
				
				switch ( id )
				{
					case 'scroll_left':
						animateSign = '+';
						if ( window.left - settings.move >= 0 )
						{
							pixels = settings.move * settings.columnPixels;
							toMove = settings.move * -1;
						}
						else
						{
							pixels = window.left * settings.columnPixels;
							toMove = window.left * -1;
						}
						break;
						
					case 'scroll_right':
						animateSign = '-';
						if ( window.right + settings.move <= window.total )
						{
							pixels = settings.move * settings.columnPixels;
							toMove = settings.move;
						}
						else
						{
							pixels = ( window.total - window.right ) * settings.columnPixels;
							toMove = window.total - window.right;
						}
						break;
				}
				
				duration = pixels * 0.9;
				$('#pslide-wrapper-inner').animate({ left: animateSign + '=' + pixels + 'px' }, duration, function(){
					// Update our new window positions with delta = toMove
					updateWindowRange( toMove );
					
					// Click either left or right element
					$( '#f' + getPositionEltNum( id ) ).click();
					
					// We're done sliding
					isSliding = false;
				});
			}
		}
		
		/**
		 * getPositionEltNum
		 * @param id (string): the id of the scroll clicked
		 */
		 
		function getPositionEltNum( id )
		{
			return ( id == 'scroll_right' ) ? ( window.left / settings.columnWidth ) + 1 : ( window.right + 1 ) / settings.columnWidth;
		}
		
		/**
		 * updateScrollStatus()
		 * Check window position and enable/disable scrolls accordingly
		 * (Fires on pitem click, meaning it also occurs after every scroll)
		 */
		 
		function updateScrollStatus()
		{
			// Are we all the way right?
			if ( window.right == window.total )		enableDisableScrolls( 'right', false );
			else if ( window.right < window.total )	enableDisableScrolls( 'right', true );
			
			// Are we all the way left?
			if ( window.left == 0 )					enableDisableScrolls( 'left', false );
			else if ( window.right > 0 )			enableDisableScrolls( 'left', true );
		}
		
		/**
		 * getScrollStatus()
		 * Check window position and returns scroll status
		 */
		 
		function getScrollStatus()
		{		
			return {
				'scroll_left': ( window.left == 0 ) ? 'disabled' : 'enabled',
				'scroll_right': ( window.right == window.total ) ? 'disabled' : 'enabled'
			};
		}
		
		/**
		 * enableDisableScrolls()
		 * Enables or disables scrolls. Called by updateScrollStats()
		 */
		
		function enableDisableScrolls( lr, state )
		{
			switch ( state )
			{
				case true:
					$( '#scroll_' + lr ).removeClass( 'disabled' );
					break;
				case false:
					$( '#scroll_' + lr ).addClass(' disabled' );
			}
		}
		
		/**
		 * Attach and bind the scrolls to the body
		 */
		 
		var scroll_left = $('<a />').attr({
			href: '#',
			id: 'scroll_left',
			rel: 'nofollow',
			title: 'Scroll left'
		}).addClass('scroll');
		
		var scroll_right = $('<a />').attr({
			href: '#',
			id: 'scroll_right',
			rel: 'nofollow',
			title: 'Scroll right'
		}).addClass('scroll');
		
		// Attach the scrollers
		$('#pslide-wrapper').before( scroll_left ).before( scroll_right );
		
		// Bind the scrollers
		$('.scroll').each( function(){
			$(this).bind( 'click', function(){
				// We don't want to slide if we're already sliding, or if we're at the end
				if ( !isSliding )
					slideWindow( $(this).attr('id') );
				return false;
			});
		});

		/**
		 * jquery: .pitem
		 * Set up selectbar, hover and click bindings for each pitem
		 */
		
		return this.each( function()
		{
			var $pitem = $(this);
			var $link = $(this).find('a');
			var $img = $(this).find('img');
			
			var selectbar =
				$('<div />').addClass('selectbar clearfix')
				.append( $('<div />').addClass('lt') )
				.append( $('<div />').addClass('rt') )
				.css( { width: $(this).width() + 6 } );
			
			selectbar.appendTo( $pitem );
			
			$link
			.hover(
				function()
				{
					if ( !selectbar.hasClass('sel') )
						doFade( 'hoverin', selectbar, '#5b5b5b', 150 );				
				},
				function()
				{
					if ( !selectbar.hasClass('sel') )
						doFade( 'hoverout', selectbar, '#474747', 150 );
				}
			)
			.click(
				function(){
				
					updateScrollStatus();
				
					if ( selectbar.hasClass('sel') )
					{
						// Already selected, do nothing
					}
					else
					{							
						doFade( 'out', $pitem.parent().find('.selectbar'), '#474747', 0 );
						$('.featured_info').hide();
						$('#' + $(this).attr('id') + '_info').show();
						doFade( 'in', selectbar, '#ecec00', 200 );
					}
					return false;
				}
			);
			
			// Click the link with ID specified in the settings
			if ( $link.attr('id') == settings.initialId )
				$link.click();
			
			// Fades out already selected item
			function doFade( type, e, color, time )
			{
				e
				.animate( { 'background-color': color }, time );
				if ( 'out' == type )
					e.removeClass('sel');
				else if ( 'in' == type )
					e.addClass('sel');						
			}
				
		
		});
		
	};

	// Initialize the portfolio plugin on each .pitem
	$('.pitem').gkdportfolio();

});
