/**
* jQuery AnySlider 1.2
* http://jonathanwilsson.com/projects/jquery-anyslider/
*
* Copyright 2011 Jonathan Wilsson
*
* Free to use and abuse under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*/

(function ($) {

    $.fn.AnySlider = function (options) {

        var vars = {
            currentPos: 0,
            slideWidth: 0,
            slides: $(".slide"),
            numSlides: 0
        },
        defaults = {
            showControls: true,
			showOnHover: false,
            keyboardNav: true,
			speed: 2000,
            prevLabel: "Prev",
            nextLabel: "Next"
        };

        if (options) {
            $.extend(defaults, options);
        }

        function changeSlide(caller) {
            if (caller === 39 || caller === "next") {
                vars.currentPos += 1;
            } else {
                vars.currentPos -= 1;
            }

            if (vars.currentPos < 0) {
                vars.currentPos = vars.numSlides - 1;
            } else if (vars.currentPos >= vars.numSlides) {
                vars.currentPos = 0;
            }

            $(".gallery_slider_inner").animate({marginLeft: vars.slideWidth * (-vars.currentPos)}, vars.speed);
        }

        return this.each(function () {

            var $this = $(this), $arrow;

            vars.slideWidth = $this.width();
            vars.numSlides = vars.slides.length;

            $this.css("overflow", "hidden");

            vars.slides.wrapAll('<div class="gallery_slider_inner"></div>').css({"float": "left", width: vars.slideWidth});

            $('.gallery_slider_inner').css("width", vars.slideWidth * vars.numSlides);

            $this.prepend('<div class="gallery_button" id="gallery_prev"><span id="prev"></span>' + defaults.prevLabel + '</div>').append('<div class="gallery_button" id="gallery_next"><span id="next"></span>' + defaults.nextLabel + '</div>');

			$arrow = $this.find(".gallery_button");

			if (!defaults.showControls) {
				$arrow.hide();
			}

            if (defaults.showOnHover && !defaults.showControls) {
                $this.bind("mouseover", function () {
                    $arrow.show();
                }).bind("mouseout", function () {
                    $arrow.hide();
                });
            }

            $arrow.live("click", function (e) {
                changeSlide(e.target.id);
            });

            if (defaults.keyboardNav) {
                $(document).bind("keydown", function (e) {
                    var key = e.keyCode;

                    if (key === 37 || key === 39) {
                        changeSlide(key);
                    }
                });
            }
        });

    };

}(jQuery));
