(function(){

    Portlet_News_Topic_NewsLines_Text = function( id, classname ){

        this.options = $.extend( {
            news_line: '.js-news-line'
        }, this.options || {} );

        this.events = ['select', 'show', 'addToOverviewList', 'updateOverviewCount', 'hideAddToOverviewList'];

        this.listen = [
            [this, 'show', this.loadTopic],
            [this, 'load_page', this.loadTopic],
            ['News_Topics', 'selectTopic', this.showTopic],
            ['News_Body', 'selectTopic', this.showTopic],
            ['News_Topic_Selector', 'selectTopic', this.showTopic],
            ['News_Topic_NewsLines_Text', 'hideAddToOverviewList', this.hideAddToOverviewList],
            ['News_Topic_NewsLines_Search', 'hideAddToOverviewList', this.hideAddToOverviewList],
            ['News_Body', 'hideAddToOverviewList', this.hideAddToOverviewList],
            ['News_Overview', 'removeFromOverviewList', this.onRemoveFromOverviewList]
        ];

        this.topics_id = false;
        this.start = 0;
        this.lastId = undefined;
        this.lastDateLine = undefined;
        this.tooltips = [];
        this.tooltip_result = false;

        IApp_Portlet.apply(this, arguments);
    };

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

        init : function(){
    		
    		IApp_Portlet.prototype.init.apply(this, arguments);            
            
            /** Place for on init actions **/
            var self = this;
            
            this.initAjaxLinks();            
            
            this.$div.find('div.block-decorate-body,div.block-small-decor').css('padding', 0);
            this.$div.find('div.block-container-hidden,div.block-container-auto').css('width', '100%');
            this.$div.find('div.block-small-decor div.butt-portlet-config').css('margin-right', 9);
            
            /** Bind click handler for overview page */
            this.$div.find('.add-to-link').unbind().click(function()
            {
                if (jQuery(this).attr('rel'))
                {
                	self.addToOverviewList(jQuery(this).attr('rel'));
                }

                return false;
            });
            
            if( ! this.topics )
                this.topics = this.options.instance.topic_id;

           
            this.initAutoReload();            
            
            this.checkLastNews();
            if ( 'Show as tooltip' ==  this.options.instance.paragraph)
            {
            	this.initTooltip( this.$div );
            }
        },

        initAjaxLinks : function(){
            var self = this;
            if( (typeof this.options.instance.target == 'string') && this.options.instance.target.length ){
                this.$div.find('a.js-news-link').each(function(i, a){
                	self.initAjaxLink(this);
                });
            }
            this.$div.find('.news-line-wrapper-hidden').css('visibility', 'visible');
        },

        initAjaxLink : function( link ){
            var self = this;
            if( (typeof this.options.instance.target == 'string') && this.options.instance.target.length ){
                $( link ).click(function(){ self.select( $(this).attr('rel') ); return false; });
            }
        },

        initAutoReload : function(){
            var self = this;
            if( typeof this.options.instance.autoreload == 'string' ){
                timeout = parseInt( this.options.instance.autoreload );
                if( ! isNaN( timeout ) && timeout > 0 ){
                    if( this.reloadTimer ){
                        clearTimeout( this.reloadTimer );
                    }
                    this.reloadTimer = setTimeout( function(){ if( 0 == self.start){ self.reloadTopic(); } }, timeout * 60 * 1000 );
                }
            }
        },

        initTooltip : function( container ){
            var self = this;

            container.find('.js-news-link').tooltip({
  					bodyHandler: function () {
  						return '<div>Loading...</div>';
  					},
  					track:true,
  					showURL: false,
  					onshow: function(el, oTooltip){
  					    oTooltip.parent.css({visibility: 'visible'});
  						var a = self;
  						var result;
  						var newsLines_rel = $(el).attr('rel');
  						var is_need_load = true;
  						for(tooltip_name in self.tooltips) {
							if(tooltip_name==newsLines_rel){
									is_need_load = false;
								}
  						}
  						if (is_need_load) {
  							self.callRemoteFunc( 'paragraph', { data: [newsLines_rel], layout: 'json', callback:function(jdata){
  								var j_responce = jdata;
  								self.tooltips[newsLines_rel] = j_responce;

  								if (0 == $.trim($(j_responce).html()).length)
  	                            {
  	                                oTooltip.parent.hide();
  	                            }

  								oTooltip.body.html(j_responce);

  							} } );
  						}
  						else if (0 != $.trim($(self.tooltips[newsLines_rel]).html()).length)
  	                    {
  	                        oTooltip.body.html(self.tooltips[newsLines_rel]);
  	                    }
  						else
  	                    {
  						    oTooltip.parent.hide().css({visibility: 'hidden'});
  						}
  						return true;
  					},
  					onhide: function(el, oTooltip){return false;}

            });
        },

        checkLastNews : function()
        {
        	if (this.$div.find('.js-last-news-line').length)
            {
        		var $newsLine     = this.$div.find( '.js-last-news-line' );
                var aParams       = $newsLine.attr('rel').split(':');
                this.lastId       = aParams[0] + ':' + aParams[1];
                this.lastDateLine = aParams[2];

                // Remove newslines older then 20 lates entries
                var $newsLines = this.$div.find('div.js-newsline-container');
                if ('All' != this.options.instance.news_cnt && this.options.instance.news_cnt && $newsLines.length > new Number(this.options.instance.news_cnt))
                {
                    $newsLines.slice(new Number(this.options.instance.news_cnt)).slideUp().remove();
                }

                // Remove empty days after deleting old newslines
                this.$div.find('div.news-day-list').each(function()
                {
                    if (0 == $(this).find('div.js-newsline-container').length)
                    {
                        $(this).slideUp().remove();
                    }
                });
            }
        },

        select : function( id ){
        	if( (typeof this.options.instance.target == 'string') && this.options.instance.target.length ){
                this.dispatchEvent( 'select', id, this.options.instance.target );
            }
        },

        showTopic : function( id, target ){
        	if( typeof this.options.instance.identifier == 'string' && this.options.instance.identifier == target ){
        		//if changes in topic selector set start page to 0
        		if (id != this.topics){
        			this.start = 0;
        		}
        		this.dispatchEvent( 'show', id, this.start, this.options.instance.identifier );
        		//this.dispatchEvent( 'show', id, 0, this.options.instance.identifier );
            }
        },

        createNews : function( id, topic_id, i_day, i_daysys, i_datetime, i_timestamp, url, last_class, is_flash, is_urgent, title, add_to_overview_display_class, data ){
        	var self = this;
        	var $timeline    = $('<span />').html( i_datetime ).addClass('time');
        	var $content     = $('<div />').addClass('news_content').html(data);

        	// this is a simple quick fix, but this entire mechanism isn't quite good
        	// html in "data" compromises the idea of passing json
        	// different code for init of initial content and added by autoreload has caused a number of issues already
        	// (that for new items added by autoreload some buttons do not work, etc.) and might cause more in the future
        	this.initAjaxLink($content.find('a.js-news-link'));

        	if( typeof this.options.instance.no_links == 'undefined' || ! parseInt(this.options.instance.no_links) ){
        	    var $link        = $('<a />').addClass('js-news-link').addClass(last_class).attr('href', url).attr('rel', topic_id + ':' + id + ':' + i_timestamp).html(title);
        	    this.initAjaxLink( $link );
        	}else
        	    var $link        = $('<span />').addClass('js-news-link').addClass(last_class).attr('rel', topic_id + ':' + id + ':' + i_timestamp).html(title);

        	var $linkWrapper = $('<div />').addClass('newsline-container-link');

        	if (is_flash)
        	{
        	    $linkWrapper.addClass('active1').append( $('<strong />').html('!&nbsp;'));
        	}
        	else if (is_urgent)
        	{
        	    $linkWrapper.addClass('active2').append( $('<strong />').html('!&nbsp;'));
        	}

        	if ( !add_to_overview_display_class ) {
        		add_to_overview_display_class = '';
        	}
        	
        	
        	if( this.options.instance.show_overview && parseInt(this.options.instance.show_overview) ) {
        		$linkAddToOverview = $('<a rel="' + id + '" href="#" />')
	        		.addClass('add-to-link')
	        		.addClass('js-add-to-overview')
	        		.addClass(add_to_overview_display_class)
	        		.text(' ')
	        		.click( function() {
	                	self.addToOverviewList(id);
		                return false;
		            });
        	} else {
        		$linkAddToOverview = $('<!-- -->');
        	}

        	$linkWrapper.append($link).append($content).append($('<div />').html('<!-- -->').addClass('clear'));

        	var $container    = $('<div />').addClass('js-newsline-container').append($timeline).append($linkAddToOverview).append($linkWrapper);
        	var $dayContainer = this.$div.find('div.js-news-line')/*.filter('> h2:contains("' + i_day + '")')*/;

        	var bDayFound = false;
            $dayContainer.find('h2').each(function()
            {
                if (i_daysys == $(this).attr('rel'))
                {
                    bDayFound = true;
                }
            });

        	if (!bDayFound)
        	{
        	    $dayContainer = $('<div />')
        	        .addClass('news-day-list')
        	        .addClass('js-news-line')
        	        .append($('<h2 />').attr('rel', i_daysys).append(document.createTextNode(i_day)))
        	        .insertBefore(this.$div.find('div.js-news-line:first'));
        	    
        	}

            $dayContainer.find('h2').each(function()
            {
                if (i_daysys == $(this).attr('rel'))
                {
                	if( ! $(this).parent().children('div.js-newsline-container').length ) { 
                		$(this).after($container);
                	} else {
                		var found = false;
                		var $prev = $(this);
                		$(this).parent().children('div.js-newsline-container').each(function(){
                			if( found ) {
                				return;
                			}
                			var $newsLine     	= $(this).find('.js-news-link');
                            var aParams       	= $newsLine.attr('rel').split(':');
                            var Id 		= aParams[0] + ':' + aParams[1];
                            var Time 	= aParams[2];
                            
                            if( parseInt(Time) <= parseInt(i_timestamp) ) {
                            	found = true;
                            	return;
                            }
                            
                            $prev = $( this );
                		});
                		
                		$prev.after($container);
                	}
                }
            });

        	if ('Show as tooltip' == this.options.instance.paragraph)
            {
                this.initTooltip($container);
            }
        },

        processJson : function( newsLines ){
            //var newsLines = eval( json );
            if( typeof newsLines == 'object' && newsLines.length ){

            	this.$div.find('.js-last-news-line').removeClass('js-last-news-line');

                for( var i = (newsLines.length - 1); i >= 0; i-- ){
                    var o = newsLines[i];
                    var $newsLine = this.createNews(
                        o.id,
                        o.topic_id,
                        o.day,
                        o.daysys,
                        o.datetime,
                        o.timestamp,
                        o.url,
                        o.last_class,
                        o.is_flash,
                        o.is_urgent,
                        o.title,
                        o.add_to_overview_display_class,
                        o.data
                    );

                }

                this.checkLastNews();
            }
        },

        reloadTopic : function(topId, topTime, lastTime){
        	var self = this;
            var topic_id = this.topics;
            
            self.$div.loadUI();
            
            if( typeof lastTime == 'undefined' ) {
	            var $newsLine     	= this.$div.find( '.js-news-link:last' );
	            if ($newsLine.length == 0) {
	            	lastTime = false; 
            	} else {
            		var aParams       	= $newsLine.attr('rel').split(':');
            		lastTime 			= aParams[2];
            	}
            }
            
            if( typeof topId == 'undefined' || typeof topTime == 'undefined' ) {
            	var _topId = false;
            	var _topTime = false;
            	
	            this.$div.find( '.js-news-link' ).each(function(){
	            	$newsLine     	= $(this); 
            		aParams       	= $newsLine.attr('rel').split(':');
            		if( ! _topId || parseInt(aParams[1]) > _topId ) {
            			_topId = parseInt(aParams[1]);
            			topId = aParams[0] + ':' + aParams[1];
            		}
            		if( ! _topTime || parseInt(aParams[2]) > _topTime ) {
            			_topTime = parseInt(aParams[2]);
            			topTime = aParams[2];
            		}
	            });
	            
            }
            
            this.callRemoteFunc( 'get', { data: [topic_id, topId+','+topTime+','+lastTime], layout: 'json', callback: function(j_data){
                self.$div.unloadUI();
                self.processJson( j_data );
                self.initAutoReload();
            }, error: function(xhr){
            	if(! self.ajaxErrorHandler(xhr)){ 
            		self.$div.unloadUI();
                    self.initAutoReload();
            	}
            }, headers:{'X-Autoreload':'1'}} );
        },

        loadTopic : function( id, start ){
            var self = this;

            if( typeof id == 'undefined' )
                id = this.topics;
            else
                this.topics = id;

            if( typeof start == 'undefined' ){
            	start = 0;
            }
            this.start = start;

            this.callRemoteFunc( 'load', { data: [id, start], target: this.$div, 
            	callback: function(){
            		self.init(); 
            	} } );
            
        },

        setDisplayType: function(sType)
        {
            this.sDisplayType = sType;
        },
        
        addToOverviewList: function(iNewsLineId)
        {
        	var self = this;
            this.dispatchEvent('hideAddToOverviewList', iNewsLineId);
            this.callRemoteFunc('addToOverviewList',
            {
                data     : [iNewsLineId],
                layout   : 'json',
                callback : function(iNewsCount)
                {
	                self.dispatchEvent('addToOverviewList', iNewsLineId);
	                self.dispatchEvent('updateOverviewCount', iNewsCount);
            	}
            });
        },
        
        hideAddToOverviewList: function(iNewsLineId)
        {
        	this.$div.find('.js-add-to-overview[rel=' + iNewsLineId + ']').each(function()
            {
            	$(this).addClass('addToOverviewHidden');
            });
        },
        
        onRemoveFromOverviewList: function(iNewsLineId)
        {
        	this.$div.find('.js-add-to-overview[rel=' + iNewsLineId + ']').each(function()
            {
        		$(this).removeClass('addToOverviewHidden');
            });
        }

    });

})(jQuery);
