﻿/// <reference path="jquery-1.5-min.js" />

(function ($) {
    $.fn.slider = function () {
        var slideShow = this;
        var currentPos = 0;
        var slideWidth = this.children().children().width();
        var slides = $('.slide');
        var slideNum = slides.length;

        // Remove scrollbar
        slideShow.children().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
        slideShow.children().children('#slideInner').css('width', slideWidth * slideNum);

        slideShow
            .prepend('<span class="control" id="leftControl">Prev</span>')
            .append('<span class="control" id="rightControl">Next</span>');

        // Hide previous control on first load
        manageControls(currentPos);

        // Create event listeners for .controls clicks
        slideShow.children('.control')
            .bind('click', function () {
                // Determine new position
                currentPos = ($(this).attr('id') == 'rightControl') ? currentPos + 1 : currentPos - 1;

                // Hide / show controls
                manageControls(currentPos)

                // Move slideInner using margin-left
                slideShow.children().children('#slideInner').animate({
                    'marginLeft': slideWidth * (-currentPos)
                }, {
                    duration: 1000
                });
            });

        // Hides and shows controls based upon currentPos
        function manageControls(position) {
            if (position == 0) {
                slideShow.children('#leftControl').hide();
            } else {
                slideShow.children('#leftControl').show();
            }

            if (position == slideNum - 1) {
                slideShow.children('#rightControl').hide();
            } else {
                slideShow.children('#rightControl').show();
            }
        }
    }
})(jQuery);
