(function($){

    $.fn.scrollGallery = function(options){

        var
            $images = $(this).find('img'),
            offset = 0,
            totalCount = $images.length,
            loadedCount = 0,
            intervalId,
            defaults = {
                delay: 30,
                distance: 3
            };

        options = $.extend({}, defaults, options);

        /* wait for loading all images */
        $images.load(function(){
            loadedCount++;
            if (loadedCount == totalCount){
                init();
                play();

            }
        });

        /* find widths, put in one row with position absolute */
        function init(){
            $images.each(function(){

                var $this = $(this);
                $this.css({
                    "position": "absolute",
                    "left": offset,
                    "top": 0
                });
                offset += $this.width()

            });
        }

        function play(){
            intervalId = setInterval(function(){

                $images.each(function(){
                    var $this = $(this);

                    $this.css({
                        "left": parseInt($this.css("left"), 10) - options.distance + "px"
                    });
                    var width = $this.width();
                    if(parseInt($this.css("left"), 10) <= -width){
                        $this.css({
                            "left" : offset - width + "px"
                        })
                    }
                })

            }, options.delay)
        }

        function pause(){
            clearInterval(intervalId)
        }

        $(this)
            .mouseover(pause)
            .mouseout(play)
    }

})(jQuery);





