(function($) {
        $.widget("ui.carousel", {
            _init: function() {
                this.isAnimating = false;
                this.numPages = this._countPages();
                this.currentPage = 1;
                this._setupContainers();
                this.pageWidth = this.element.parent().width();
                this.addButtons();
                this.addHandlers();
                if(this.options.startPage > 1){
                    this.slideTo(this.options.startPage);
                }
            },

            addButtons: function(){
                var nextButton = $(document.createElement("div"))
                        .addClass("ui-state-default ui-corner-all carousel-icon")
                        .append($(document.createElement("div"))
                            .addClass("ui-icon ui-icon-carat-1-e"));
                var prevButton = $(document.createElement("div"))
                        .addClass("ui-state-default ui-corner-all carousel-icon").
                        append($(document.createElement("div"))
                            .addClass("ui-icon ui-icon-carat-1-w"));
                this.element.parent()
                        .before(prevButton)
                        .after(nextButton);

            },

            addHandlers: function(){
                var self = this;
                this.element.parent().prev().click(function(){
                    if(self.currentPage > 1){
                        self.currentPage--;
                        self.slide(self.pageWidth);
                    }
                }).bind("mouseenter", function(){
                    $(this).addClass("ui-state-hover");
                }).bind("mouseleave", function(){
                    $(this).removeClass("ui-state-hover");
                });
                this.element.parent().next().click(function(){
                    if(self.currentPage < self.numPages){
                        self.currentPage++;
                        self.slide(-self.pageWidth);
                    }
                }).bind("mouseenter", function(){
                    $(this).addClass("ui-state-hover");
                }).bind("mouseleave", function(){
                    $(this).removeClass("ui-state-hover");
                });
            },

            slide: function(distance){
                if(!this.isAnimating){
                    distance = (distance) ? distance : this.pageWidth;
                    var self = this,
                        curLeft = (this.element.css('left') == 'auto') ? 0 : parseInt(this.element.css('left'));
                    this.isAnimating = true;
                    distance = curLeft+distance;
                    this.element.animate({left: distance+"px"}, 500, "swing", function(){ self.isAnimating = false; });
                }
            },

            slideTo: function(page){
                var diff = this.currentPage-page;
                this.slide(diff*this.pageWidth);
                this.currentPage = page;
            },

            _countPages: function(){
                return Math.ceil(($("div > img", this.element).length/this.options.perPage));
            },

            _setupContainers: function(){
                var self = this;
                this.element.addClass("inner-carousel").wrap($(document.createElement("div")).addClass("carousel"));
                var carousel = this.element.parent();
                var cWidth = (this.options.thumbWidth*this.options.perPage)+(this.options.marginHoriz*this.options.perPage)+(this.options.borderWidth*2*this.options.perPage);
                carousel.css({
                    'height': (this.options.thumbHeight+(this.options.marginVert*2)+(this.options.borderWidth*2))+"px",
                    'width': cWidth+"px"
                });
                carousel.wrap($(document.createElement("div")).addClass("ui-widget ui-widget-content ui-corner-all")
                        .css({"height": (this.options.thumbHeight+(this.options.marginVert*2))+"px",
                              "width": (cWidth+76)+"px"}));

                this._setupThumbContainers();
                if(self.options.mode == "letterbox"){
                    self._setupLetterbox();
                } else if (self.options.mode == "stretch"){
                    self._setupStretch();
                }

            },

            _setupLetterbox: function(){
                var self = this;
                var thumbContainers = $("div", this.element);
                thumbContainers.each(function(i, thumb){
                    thumbContainers.css({"background-color": self.options.thumbBg,
                                         "height": self.options.thumbHeight+"px",
                                         "width": self.options.thumbWidth+"px",
                                         "border": self.options.borderWidth+"px solid " + self.options.borderColor});
                    var img = $("img", thumb);
                    if(img.height() < self.options.thumbHeight){
                        img.css({'margin-top': Math.floor((self.options.thumbHeight-img.height())/2)+"px"});
                    }
                    if(img.width() < self.options.thumbWidth){
                        img.css({'margin-top': Math.floor((self.options.thumbWidth-img.width())/2)+"px"});
                    }
                });
            },

            _setupStretch: function(){
               var self = this;
               var thumbContainers = $("div", this.element);
                thumbContainers.each(function(i, thumb){
                    var img  = $("img", thumb);
                    img.height(self.options.thumbHeight+"px");
                    img.width(self.options.thumbWidth+"px");
                });
            },

            _setupThumbContainers: function(){
                var self = this;
                var thumbContainers = $("div", this.element);
                thumbContainers.each(function(i, thumb){
                    $(thumb).css({"margin-top": self.options.marginVert+"px",
                                  "margin-left": (self.options.marginHoriz/2)+"px",
                                  "margin-right": (self.options.marginHoriz/2)+"px",
                                  "margin-botom": self.options.marginVert+"px"});
                });
            }

        });
    })(jQuery);

$.extend($.ui.carousel, {
    version: 0.5,
    defaults: {
        perPage: 3,
        startPage: 1,
        thumbWidth: 50,
        thumbHeight: 50,
        marginVert: 10,
        marginHoriz: 10,
        mode: "letterbox", /* Can be letterbox or stretch */
        thumbBg: "#000",
        borderColor: "#000",
        borderWidth: 1
    }
});

$(document).ready(function(){
    $('#slide').carousel({thumbWidth: 78, thumbHeight: 58});
});