(function($) {
    $._marquee = {
        defaultOptions: {
            delimeter: ' - ',
            scrollamount: 1,
            overwriteScrollAttr: true
        },

        startAnimation: function($content, contentOuterWidth, scrollamount) {
            $content.after($content.clone()).animate({
                'margin-left': '-' + contentOuterWidth + 'px'
            }, (contentOuterWidth / scrollamount) * 100, 'linear', function() {
                $content = $(this).next();
                $(this).remove();
                $._marquee.startAnimation($content, contentOuterWidth, scrollamount);
            });
        }
    }

    $.fn.marquee = function(options) {
        options = $.extend({}, $._marquee.defaultOptions, options);
        
        $(this).each(function() {
		
			// If content is empty
			if( $.trim($(this).text()).length == 0 )
				return;
		
            var $this = $(this),
                // Takes the contents of the marquee element and puts them into a new one
                $content = $this.html($('<span class="content-container"/>').html($this.contents())).children('span:first-child');

            $content.append(options.delimeter);

            var scrollamount = null;
            if($this.is('marquee') && !options.overwriteScrollAttr && $this.is('[scrollamount]')) {
                scrollamount = parseInt($this.attr('scrollamount'));
            }

            if(scrollamount == null || scrollamount == 0) {
                scrollamount = options.scrollamount;
            }

            var contentOuterWidth = parseInt($content.outerWidth()),
                $newMarquee = $('<div/>').css({
                    'overflow': 'hidden',
                    'white-space': 'nowrap'
                });

            // Replace the selected element with a custom one
            $this.replaceWith($newMarquee);

            $newMarquee.html($content);
            $this = $newMarquee;

            if(contentOuterWidth < $this.innerWidth()) {
                var i = Math.round($this.innerWidth() / contentOuterWidth),
                    $contentContainer = $this.find('.content-container');

                for(var j = 0; j < i; j++) {
                    $contentContainer.append($content.clone());
                }

                $content = $contentContainer;
                contentOuterWidth = parseInt($content.outerWidth());
            }

            $._marquee.startAnimation($content, contentOuterWidth, scrollamount);
        });
    }
})(jQuery);
