/*******

	***	Anchor Slider by Cedric Dugas   ***
	*** Http://www.position-absolute.com ***
	
	Never have an anchor jumping your content, slide it.

	Don't forget to put an id to your anchor !
	You can use and modify this script for any project you want, but please leave this comment as credit.
	
*****/

jQuery.fn.gallery = function(settings) {

 	settings = jQuery.extend({
		inner: "gallery_inner",
		images: "gallery_images",
		control: "control",
		waiting: 5000,
		speed: 600,
		easing: "easeInOutExpo"
	}, settings);	
	
	return this.each(function(){
		var caller = this;
		var active = null;
		var timeout = null;
		var length = $('#' + settings.images).find('img').length;
		
		if ( $( $('#' + settings.images).find('img') ).length > 1 ) {

			$( $('#' + settings.images).find('img') ).each(function(i, el) {
				$(el).attr( 'id', "image_" + i );
				addControl(i);
			
				if ( i == 0 ) {
					setActive(i);
				}
			});
			$('body' ).bind('keydown', Handle_KeyControl);
		
			play();
		}
		
		function Handle_KeyControl( e ) {
			switch( e.keyCode ) {
				case 39:
					clearTimeout(timeout);
					moveIt();
				break;
				case 37:
					clearTimeout(timeout);
					if ( active - 1 < 0 ) {
						moveIt( length - 1 );
					}
					else {
						moveIt( active - 1 );
					}
				break;
			}
		}
		
		function play() {
			timeout = window.setTimeout( function() { moveIt() }, settings.waiting );
		}
		
		function addControl( data ) {
			$('#' + settings.control ).prepend(
				"<li><a id='ctrl_"+data+"' href='#image_"+data+"'><span>Image "+data+"</span></a></li>"
			);

			$('#ctrl_' + data ).bind('click', Handle_Control );
		}
		
		function Handle_Control( e ) {
			e.preventDefault();
			
			clearTimeout(timeout);
			moveIt( $(e.currentTarget).attr('id').split('_')[1] );
		}
		function moveIt( id ) {
			if ( id || id == 0 ) {
				el = $('#image_' + parseInt(id) );
			}
			else {
				if ( active + 1 < length ) {
					el = $('#image_' + (active + 1) );
				}
				else {
					el = $('#image_0');
				}
			}
			
			$("#" + settings.images ).animate({'left': $(el).position().left * -1 }, settings.speed, settings.easing);
			setActive( $(el).attr('id').split('_')[1] );
			
			play();
		}
		function setActive( id ) {
			$('#' + settings.control + " li" ).removeClass('active');
			$( $('#ctrl_' + id ).parent() ).addClass('active');
			active = parseInt(id);
		}
	})
}
