(function($) {
    $.fn.slide = function(options) {
        var defaults = {
            slideWidth: 901,
            autoplay: true,
            duration: 2500,
            showNavigator: true,
            showSlideIndex: true
        };
        var config = $.extend(defaults, options);
        return this.each(function() {
            var slideshow = $(this);
            var o = config;
            var currentPosition = 1;
            var slides = $('.slide');
            var numberOfSlides = slides.length;
			var maxmasuno = numberOfSlides + 1;
            var t;

            // Remove scrollbar in JS
            $('#slidesContainer').css('overflow', 'hidden');

            // Wrap all .slides with #slideInner div
            slides.wrapAll('<div id="slideInner"></div>')

            // Float left to display horizontally, readjust .slides width
			.css({
			    'float': 'left',
			    'width': o.slideWidth
				
			});

            // Insert a clone of first slide 
			$('.slide:last').clone().prependTo('#slideInner');
			$('.slide:eq(1)').clone().appendTo('#slideInner');
			

            // Set #slideInner width equal to total width of all slides
            $('#slideInner').css({'width': o.slideWidth * (numberOfSlides + 2), 'margin-left': -o.slideWidth});

            // Insert controls in the DOM
            if (o.showNavigator) {
                slideshow
				    .prepend('<span class="control" id="leftControl">Clicking moves left</span>')
				    .append('<span class="control" id="rightControl">Clicking moves right</span>')
					.append('<span id="stopgo" >Clicking stopsplays</span>');
					$("span#stopgo", "#slideshow").addClass("pause");
												
							$("span#stopgo").live('click',
								function(event) {
									if (event.target.className == 'pause')
									{
										pause(event); return false;
									}
									else
									{
										play(event); return false;
									}
								}
							
							);

                // Create event listeners for .controls clicks
                $('#leftControl').click(function() { prev(); return false; });
                $('#rightControl').click(function() { next(); return false; });
            }
            // Insert slides index
            if (o.showSlideIndex === true) {
                slideshow.append('<div id="slideIndex"></div>');
                for (var i = 1; i <= numberOfSlides; i++) {
                    $('#slideIndex').append('<span id="slide-' + i + '" class="numbers">' + i + '</span>');
                }
                $('.numbers').click(function() { goto(($('div#slideIndex').children('.active')).attr('id').replace('slide-',''),($(this).attr('id')).replace('slide-', '') , false); return false; });
            }


            //Init function
            function init() {
                manageControls(currentPosition);
                if (o.autoplay === true){ setNextTimeOut(o.duration);}
            }

            // Next
            function next() {
                currentPosition++;
                if (currentPosition >= maxmasuno){ currentPosition = maxmasuno;}
                slideTo(currentPosition, true);
            }

            // Previous
            function prev() {
                currentPosition--;
                if (currentPosition < 1){ currentPosition = 0;}
                slideTo(currentPosition, true);
            }
			
			//Pause
			function pause(event) {
			
				$(event.target).removeClass("pause");
				$(event.target).addClass("play");
				$('#slideInner').stop();
				clearNextTimeOut();
				o.autoplay = false;
			
			}
			
			//Play
			function play(event) {
			
				$(event.target).removeClass("play");
				$(event.target).addClass("pause");
				setNextTimeOut(o.duration);
				o.autoplay = true;
			
			}

            // Go to a slide 
            function goto(from,to) {
                currentPosition = to ;
				if (from === numberOfSlides && to === '1'){ currentPosition = maxmasuno;}
				if (from === '1' && to === numberOfSlides){ currentPosition = 0;}
                slideTo(currentPosition, true);
            }

            // Set time out for next slide
            function setNextTimeOut() {
                t = setTimeout(function() { next(); }, o.duration);
            }

            function clearNextTimeOut()
            { 
                clearTimeout(t);
            }
            // Slide
            function slideTo(position, continuously) {
                $('#slideInner').stop();
                clearNextTimeOut();
                // usual cases
                if (continuously === false || o.autoplay === false || position !== 0 && position != maxmasuno) {
                    $('#slideInner').animate({ 'marginLeft': o.slideWidth * (-position) }, '', '',
						function() {
						    manageControls(position);
						    if (o.autoplay === true){ setNextTimeOut();}
						}
					);
                }
              else if( position === 0 ){
                    // slide to the 'fake' last slide (actually at the last)
                    $('#slideInner').animate({ 'marginLeft': 0 }, '', '',
						function() {
						    //immediately change to the 'true' last slide
						    $('#slideInner').css('marginLeft', o.slideWidth * (-numberOfSlides));
						   currentPosition = numberOfSlides;
						   manageControls(currentPosition);
						   if (o.autoplay === true){ setNextTimeOut();}
						}
					);
                }
                // autoplay: slide from last to first one continuously
                else if(position === (maxmasuno)){
                    // slide to the 'fake' first slide (actually at the last)
                    $('#slideInner').animate({ 'marginLeft': o.slideWidth * (-maxmasuno) }, '', '',
						function() {
						    //immediately change to the 'true' first slide
						    $('#slideInner').css('marginLeft', -o.slideWidth);
						    currentPosition = 1;
							manageControls(currentPosition);
						    if (o.autoplay === true){ setNextTimeOut();}
						}
					);
                }
            }

            // manageControls: Hides and Shows controls depending on currentPosition
            function manageControls(position) {
                if (o.showNavigator) {
                    // Hide left arrow if position is first slide
                    //if (position == 0) { $('#leftControl').hide() } else { $('#leftControl').show() };
                    // Hide right arrow if position is last slide
                    //if (position == (numberOfSlides - 1)) { $('#rightControl').hide() } else { $('#rightControl').show() };
                }
				
                // Hilight the current page
                if (o.showSlideIndex === true) {
                    // remove active class from all pages
                    $('.numbers').removeClass("active");
                    // add only to the current page
                    $('#slide-' + (position)).addClass("active");
                }
            }
			
			// Start
            init();
        });
    };
})(jQuery);
