/**
 * Marquee jquery plugin
 *
 * @author coder_
 */

(function( $ ){
    $.fn.marquee = function() {
        var distance = $(this).width();
        var dragging = false;
        var dragOffset = 0;

        $this = this;

        function moveSingle(element)
        {
            var singleWidth = $('span:first', $(element)).width() + distance;

            var toGo = singleWidth + parseInt($('span:first', $(element)).css('margin-left').replace('px', ''));

            var speed = parseInt(toGo/33);

            $('span:first', element).animate({
                'marginLeft': '-' + singleWidth
            }, speed * 1000, 'linear', function(){
                el = $(this).clone();
                $(this).remove();
                el.css('margin-left', 0);
                $('div',element).append(el);
                moveSingle(element);
            });
        }

        return this.each(function() {

            var content = $($this).html();

            content = $('<span></span>').html(content);

            content = $('<div></div>').addClass('marquee_container').append($(content)).append($(content).clone());

            $($this).html(content);

            distance -= $('span', $this).width();

            distance = Math.max(distance, 0);

            $('span', $this).css({
                'padding-right': distance,
                'user-select' : 'none',
                '-moz-user-select' : 'none',
                '-webkit-user-select' : 'none',
                'cursor' : 'pointer'
            });

            $('span:first', $this).css('margin-left', $($this).width());

            $(this).hover(function(){
                $('span:first',this).stop();
            }, function(){
                dragging = false;
                moveSingle(this);
            });


            $('span', $this).live('mousedown', function(e){
                dragging = true;
                dragOffset = e.clientX - $($this).offset().left - parseInt($('span:first', $this).css('margin-left').replace('px', ''));
            });

            $('span', $this).live('mouseup', function(e){
                dragging = false;
            });

            $('span', $this).live('mousemove', function(e){
                if(dragging)
                {
                    var current = e.clientX - $($this).offset().left;
                    $('span:first', $this).css('margin-left', current - dragOffset);
                }
            });

            moveSingle($this);
        });
    };
})( jQuery );
