(function($){

    Portlet_News_Topic_NewsLines_Ticker = function( id, classname ){

        Portlet_News_Topic_NewsLines_Text.apply(this, arguments);

        this.options = $.extend( this.options || {}, {
            refresh:        4000,  // Refresh Time in sec
            direction:      "Horizontal", // Horizontal,Vertical
            speed:          5,    // Set the Scroller Speed
            ticker:         ".ticker-body",
            cont_ticker:    ".ticker-container",
            news_line:      "li.ticker-item",
            ignore:         1000
        });

        this.options.permanent = 0;

        this.interval = 0;

        this.events = this.events || [];
        this.events.push('select');

        this.listen = this.listen || [];
        this.listen.push([this, 'select', this.showTopicNews]);

        this.items = new Array();
        this.interval = 0;
        this.ignore = false;
        this.$first = false;
        this._calls = new Array();
        this.needResize = false;

    };

    Portlet_News_Topic_NewsLines_Ticker.prototype = $.extend( new Portlet_News_Topic_NewsLines_Text , {

        init : function(){
            Portlet_News_Topic_NewsLines_Text.prototype.init.apply(this, arguments);

            var self = this;

            if( typeof this.options.instance.ticker_move != 'undefined' && this.options.instance.ticker_move == 'Permanent' )
            	this.options.permanent = 1;

            if( typeof this.options.instance.ticker_type != 'undefined' )
                this.options.direction = this.options.instance.ticker_type;

            if( typeof this.options.instance.ticker_speed != 'undefined' )
                this.options.speed = this.options.instance.ticker_speed;

            if( typeof this.options.instance.ticker_sleep != 'undefined' )
                this.options.refresh = parseInt(this.options.instance.ticker_sleep) * 1000;

            if( ($fullButton = this.$div.find('a.fullButton')) && $fullButton.length ){
                var window_width = ( parseInt(self.options.instance.fullscreen_width) > 0 ? parseInt(self.options.instance.fullscreen_width) : 0 );
                var window_height = ( parseInt(self.options.instance.fullscreen_height) > 0 ? parseInt(self.options.instance.fullscreen_height) : 0 );

                $fullButton.click(function(){
                    window.open($(this).attr('href'), '', (window_width ? 'width=' + window_width + ',' : '') + (window_height ? 'height=' + window_height + ',' : '') + 'location=no,menubar=no,resizable=no,scrollbars=yes,status=no,toolbar=no');
                    return false;
                });
            }

            /** Place for on init actions **/
            this.$ticker = this.$div.find(this.options.ticker);
            this.$tickerCont = this.$div.find(this.options.cont_ticker);

            if(this.options.permanent) {
            	if( self.options.direction == 'Horizontal' ){
            		this.options.refresh = this.options.speed * 10;
            	}else{
            		this.options.refresh = this.options.speed * 40;
            	}
            }

            if( this.$ticker.length && this.$tickerCont.length ){
                this.initTicker();
            }
        },

        initSizes : function()
        {
            if( ! this.interval ){
                this._initSizes();
            }else{
                this.needResize = true;
            }
        },

        _initSizes : function()
        {
            var self = this;

            this.needResize = false;

            this.width = this.$tickerCont.width();
            this.height = this.$tickerCont.height();

            if( this.options.permanent ) {
            	if( self.options.direction == 'Horizontal' ){
            		this.width = 'auto';
            	}else{
            		this.height = 'auto';
            	}
            }

            var twidth = 0;

            this.$ticker.find('.ticker-item').each(function(){
                $(this).width( self.width ).height( self.height );
                if( self.options.permanent && self.options.direction == 'Horizontal' ) {
                	$(this).find('a.news_line').css('margin-right', 15).css('margin-left', 0);
                }
                twidth += $(this).outerWidth() + 15;
            });

            if( self.options.direction == 'Horizontal' && twidth ){
                this.$ticker.width( twidth + 100 );
            }
        },

        parseItems : function()
        {
            var self = this;

            var has_items = false;

            this.$ticker.find('.ticker-item').each(function(){

            	has_items = true;

                if( ! self.$first ){
                    self.$first = $(this);
                }

                if( self.options.direction == 'Horizontal' ){
                    $(this).css('float', 'left');
                }
            });


            this.initSizes();
            this.checkLastNews();

            if( has_items ) {
            	this.startScroll();
            }
        },

        initTicker : function()
        {
            var self = this;

            this.$ticker.css({position: 'absolute', left: 0, top: 0});
            this.$ticker.find("a").click(function(){
                window.open( this.href );
                return false;
            });

            var onmouseover = false;
            this.$tickerCont
                .css('height', this.$tickerCont.parent().height() - self.$tickerCont.parent().children('.ticker-header').height(), 'overflow','hidden')
                .mouseover( function(){
                    onmouseover = self.stopScroll( false );
                } )
                .mouseout( function(){
                    if( onmouseover ) {
                        self.startScroll( false );
                    }
                } );

            this.$div.find('a.playButton').click(function(){
                self.startScroll( true );
                return false;
            });

            this.$div.find('a.pauseButton').click(function(){
                self.stopScroll( true );
                return false;
            });

            this.$div.find('a.nextButton').click(function(){
                var res = self.stopScroll( false );
                self.doScroll( self.options.direction == 'Horizontal' ? 'left' : 'top', function(){
                    if( res ) {
                        self.startScroll( false )
                    }
                } );
                return false;
            });

            this.$div.find('a.prevButton').click(function(){
                var res = self.stopScroll( false );
                self.doScroll( self.options.direction == 'Horizontal' ? 'right' : 'bottom', function(){
                    if( res ) {
                        self.startScroll( false )
                    }
                } );
                return false;
            });

            this.parseItems();
            setTimeout( function(){ self.initSizes(); }, 3000 );
            $(window).resize( function(){ self.initSizes(); } );
        },

        startScroll : function( show )
        {
            var show = ( typeof show != 'undefined' ? show : true );
            var res = false;

            if( ! this.interval) {
                var self = this;
                this.interval = window.setInterval( function(){ self.doScroll(); }, this.options.refresh );
                res = true;
            }
            if( show ){
                this.$div.find('a.pauseButton').show();
                this.$div.find('a.playButton').hide();
            }
            return res;
        },

        stopScroll : function( show )
        {
            var show = ( typeof show != 'undefined' ? show : true );
            var res = false;
            if( this.interval ) {
                window.clearInterval( this.interval );
                this.interval = 0;
                res = true;
            }
            if( show ){
                this.$div.find('a.pauseButton').hide();
                this.$div.find('a.playButton').show();
            }
            return res;
        },

        doScroll : function( direction, callback )
        {
            var direction = direction || ( this.options.direction == 'Horizontal' ? 'left' : 'top' );
            var callback = callback || function(){};

            if( this.options.permanent ) {
            	this._doMove(direction, callback);
            } else {
	            this._calls.push({ direction: direction, callback: callback });
	            if( this._calls.length == 1 ){
	            	this._doScroll();
	            }
            }
        },

        _doMove : function(direction, callback)
        {
        	var self = this;

        	switch( direction ){
                case 'top':
                    anim = { top: parseInt( self.$ticker.css('top') ) - 1 };

                    _callback = function(){
                    	var $tickerItem = self.$ticker.find('.ticker-item').slice(0,1);
                    	
                        var theight = $tickerItem.outerHeight();
                        if( theight < -parseInt(self.$ticker.css('top')) ) {
                        	$tickerItem.appendTo( self.$ticker.find('ul.ticker-items') );
                        	self.$ticker.css({
                                top: parseInt( self.$ticker.css('top') ) + theight
                            });
                        }

                        callback();
                    }
                    break;

                case 'left':
                    anim = { left: parseInt( self.$ticker.css('left') ) - 1 };

                    _callback = function(){
                        var $tickerItem = self.$ticker.find('.ticker-item').slice(0,1)
                        var twidth = $tickerItem.width();
                        if( twidth < -parseInt(self.$ticker.css('left')) ) {
                        	$tickerItem.appendTo( self.$ticker.find('ul.ticker-items') );
                        	self.$ticker.css({
                                left: parseInt( self.$ticker.css('left') ) + twidth + 10
                            });
                        }

                        callback();
                    }
                    break;
            }

            this.$ticker.css( anim );

            _callback();

            if( self.needResize ){
                self._initSizes();
            }
        },

        _doScroll : function()
        {
            var self = this;

            var direction = this._calls[0].direction;
            var callback = this._calls[0].callback;

            var anim = {};
            var _callback = callback;

            switch( direction ){
                case 'top':
                    anim = { top: parseInt( self.$ticker.css('top') ) - parseInt( self.height ) };

                    _callback = function(){
                        self.$ticker.find('.ticker-item').slice(0,1).appendTo( self.$ticker.find('ul.ticker-items') );
                        self.$ticker.css({
                            top: parseInt( self.$ticker.css('top') ) + parseInt( self.height )
                        });
                        callback();
                    }
                    break;

                case 'bottom':
                    self.$ticker.find('.ticker-item').slice(-1).prependTo( self.$ticker.find('ul.ticker-items') );
                    self.$ticker.css({
                        top: parseInt( self.$ticker.css('top') ) - parseInt( self.height )
                    });

                    anim = { top: parseInt( self.$ticker.css('top') ) + parseInt( self.height ) };
                    _callback = callback;
                    break;

                case 'left':
                    anim = { left: parseInt( self.$ticker.css('left') ) - parseInt( self.width ) };

                    _callback = function(){
                        self.$ticker.find('.ticker-item').slice(0,1).appendTo( self.$ticker.find('ul.ticker-items') );
                        self.$ticker.css({
                            left: parseInt( self.$ticker.css('left') ) + parseInt( self.width )
                        });
                        callback();
                    }
                    break;

                case 'right':
                    self.$ticker.find('.ticker-item').slice(-1).prependTo( self.$ticker.find('ul.ticker-items') );
                    self.$ticker.css({
                        left: parseInt( self.$ticker.css('left') ) - parseInt( self.width )
                    });

                    anim = { left: parseInt( self.$ticker.css('left') ) + parseInt( self.width ) };
                    _callback = callback;
                    break;
            }

            this.$ticker.animate( anim, {
                duration: this.options.speed * 100,
                queue: false,
                complete: function(){
                    self._calls.shift();
                    _callback();

                    if( self.needResize ){
                        self._initSizes();
                    }

                    if( self._calls.length ){
                        self._doScroll();
                    }
                }
            });
        },

        createNews : function( id, topic_id, date_line, date_line_formatted, title, url, content, urgent ){

            $newsLine = $('<li />')
                    .addClass('ticker-item')
                    .attr('rel', id)
                    .width(this.width)
                    .height(this.height)
                    .append($('<span />').addClass('news_line_date').attr('rel', date_line).html(date_line_formatted))
                    .append(
                    	! parseInt(this.options.instance.no_links) ?
                		$('<a />').addClass('news_line').addClass('urgent'+urgent).attr('rel', topic_id + ':' + id).attr('href', url).html(title) :
            			$('<span />').addClass('news_line').addClass('urgent'+urgent).attr('rel', topic_id + ':' + id).html(title)
            		)
                    .append($('<span />').addClass('news_content').html(content));

            if( this.options.direction == 'Horizontal' ){
                $newsLine.css('float', 'left');
            }

            $newsLine.find('a').click(function(){
                window.open( this.href );
                return false;
            });

            return $newsLine;
        },

        processJson : function( newsLines ){
            //var newsLines = eval( json );
            if( typeof newsLines == 'object' && newsLines.length ){
                while( newsLines.length ){
                    var o = newsLines.pop();
                    var $newsLine = this.createNews(
                        o.id,
                        o.topic_id,
                        o.dateline,
                        o.dateline_formatted,
                        o.title,
                        o.url,
                        o.data,
                        o.urgent
                    );

                    if( this.$first.parent().length && this.$ticker.find('.ticker-item').length >= parseInt( this.options.instance.news_cnt ) ){
                        if( this.$first.prev( '.ticker-item' ).length ){
                            $replace = this.$first.prev( '.ticker-item' );
                        }else{
                            $replace = this.$ticker.find('.ticker-item').slice(-1);
                        }
                        $replace.replaceWith( $newsLine );
                        this.$first = $newsLine;
                    }else{
                        this.$ticker.find('ul.ticker-items').append( $newsLine );
                        if( this.$ticker.find('.ticker-item').length == 1 )
                            this.$first = $newsLine;
                    }
                }

                this.checkLastNews();
            }
        },

        checkLastNews : function(){
            if( this.$first ){
                var $newsLine = this.$first;
                this.lastId = '0:' + $newsLine.attr('rel');
                this.lastDateLine = $newsLine.find('.news_line_date').attr('rel');
            }
        },

        reloadTopic : function(){
            if( this.interval ){

            	var _topId = false;
            	var topId = false;
            	var topTime = false;
            	var lastTime = false;

            	this.$div.find('span.news_line_date').each(function(){

            		if( ! topId || parseInt( $(this).parent().attr('rel') ) > _topId )
            		{
            			_topId = $(this).parent().attr('rel') ;
            			topId = $(this).next().attr('rel') ;
            		}

            		if( ! topTime || parseInt( $(this).attr('rel') ) > topTime )
            		{
            			topTime = parseInt( $(this).attr('rel') );
            		}

            		if( ! lastTime || parseInt( $(this).attr('rel') ) < lastTime )
            		{
            			lastTime = parseInt( $(this).attr('rel') );
            		}
            	});

                Portlet_News_Topic_NewsLines_Text.prototype.reloadTopic.apply(this, [topId, topTime, lastTime]);
            }else{
                this.initAutoReload();
            }
        },

        selectProduct : function( id )
        {
            this.dispatchEvent( 'select', id );
        },

        showTopicNews : function(sNewsCategoriesId)
        {
            var self                = this;
            this.topics             = sNewsCategoriesId;
            var sNewsCategoryIdSend = this.topics;

            self.$div.loadUI();
            this.callRemoteFunc( 'get', { data: [sNewsCategoryIdSend], layout: 'json', callback: function(json){
                self.$div.unloadUI();
                self.$ticker.find('.ticker-item').remove();
                self.processJson( json );
                self.initAutoReload();
            }, error: function(){
                self.$div.unloadUI();
                self.initAutoReload();
            }});
        }
    });

})(jQuery);
