var currentPosition = 0;
var slideWidth = 289;
var slides;
var numberOfSlides;
var direction = 1;
var userClicked = false;

$(document).ready(function () {
    slides = $('.slide');
    numberOfSlides = slides.length;

    // 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': slideWidth
	            });

    // Set #slideInner width equal to total width of all slides
    $('#slideInner').css('width', slideWidth * numberOfSlides);

    // Insert controls in the DOM
    $('#slideshow')
                .prepend('<span class="control" id="leftControl">Clicking moves left</span>')
                .append('<span class="control" id="rightControl">Clicking moves right</span>');

    // Hide left arrow control on first load
    manageControls(currentPosition);

    // Create event listeners for .controls clicks
    $('.control').bind('click', function () {
        // Determine new position
        currentPosition = ($(this).attr('id') == 'rightControl') ? currentPosition + 1 : currentPosition - 1;
        userClicked = true;
        moveToPosition(currentPosition);
    });
    setTimeout('autoSlide()', 7000);
});

function autoSlide() {
    if (userClicked)
        return;

    if (direction > 0) {
        if (currentPosition + 1 < numberOfSlides)
            currentPosition++;
        else {
            currentPosition--;
            direction = -1;
        }
    } else {
        if (currentPosition - 1 >= 0)
            currentPosition--;
        else {
            currentPosition++;
            direction = 1;
        }
    }

    moveToPosition(currentPosition);
    setTimeout('autoSlide()', 7000);
}

function moveToPosition(position) {
    // Hide / show controls
    manageControls(position);
    // Move slideInner using margin-left
    $('#slideInner').animate({
        'marginLeft': slideWidth * (-position)
    });
}

// manageControls: Hides and Shows controls depending on currentPosition
function manageControls(position) {
    // 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() }
}

