(function ($) {
    $.fn.imageScroller = function (options) {
        return this.each(function () {
            var $this = $(this);
            var loadImgs = 0;
            var opt = $.extend({
                speed: "2000",
                loading: "Loading images...",
                direction: "left",
                mouse: false
            }, options || {});
            $this.children().hide();
            $this.append("<div style='clear:both; padding: 0px; margin: 0px;'>" + "<div id='loading'>" + opt.loading + "</div>" + "</div>");
            $("img", $this).each(

            function () {
                var img = new Image();
                var soc = $(this).attr('src');
                $(img).load(

                function () {
                    loadImgs++;
                }).attr("src", soc);
            });
            var intVal = window.setInterval(

            function () {
                if (loadImgs == $("img", $this).length) {
                    window.clearInterval(intVal);
                    $("#loading").remove();
                    $this.children().show();
                    var totImg = 0;
                    $.each(
                    $this.children(":not(div)"), function () {
                        if ($(this).children().length) {
                            $(this).width($(this).children(":eq(0)").width());
                        }
                        totImg += $(this).width();
                        $(this).css({
                            margin: "0px",
                            padding: "0px",
                            clear: "both"
                        });
                        $("div:eq(0)", $this).append($(this));
                    });
                    $("div:eq(0)", $this).css("width", totImg + "px");
                    scrollStart($("div:eq(0)", $this), opt);
                }
            }, 100);

            function scrollStart($scroll, opt) {
                var pos = -($scroll.children(":eq(0)").width());
                var spd = opt.speed - (Math.abs(parseInt($scroll.css("marginLeft"))) * (opt.speed / $scroll.children(":eq(0)").width()));
                $scroll.animate({
                    marginLeft: (pos || "0") + "px"
                }, spd, "linear", function () {
                    $scroll.append($(this).children(":eq(0)"));
                    $scroll.css("marginLeft", "0px");
                    scrollStart($scroll, opt);
                });
            };
        });
    };
})(jQuery);
