(function(){

    Portlet_News_Topic_NewsLines = function( id, classname ){

        this.options = $.extend( {
            news_line: 'p.news_line'
        }, this.options || {} );

        this.events = ['select', 'show'];

        this.listen = [
            [this, 'show', this.loadTopic],
            [this, 'load_page', this.loadTopic],
            ['News_Topics', 'selectTopic', this.showTopic],
            ['News_Topic_Selector', 'selectTopic', this.showTopic]
        ];

        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.prototype = $.extend( new IApp_Portlet, {

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

            /** Place for on init actions **/
            this.initAjaxLinks();

            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.news_line').each(function(){
                    self.initAjaxLink(this);
                });
            }
        },

        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('a.news_line').tooltip({
      					bodyHandler: function () {
      						return '<div>Loading...</div>';
      					},
      					track:true,
      					showURL: false,
      					onshow: function(el, oTooltip){
      						var a = self;
      						var result;
      						var newsLines_rel = el.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;
      								oTooltip.body.html(j_responce);

      							} } );
      						} else {
      							oTooltip.body.html(self.tooltips[newsLines_rel]);
      						}
      						return false;
      					},
      					onhide: function(el, oTooltip){return false;}

                });
        },

        checkLastNews : function(){
            if( this.$div.find( this.options.news_line ).length ){
                var $newsLine = this.$div.find( this.options.news_line ).slice(0, 1);
                this.lastId = $newsLine.attr('rel');
                this.lastDateLine = $newsLine.find('.news_line_date').attr('rel');
            }
        },

        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 ){
                this.dispatchEvent( 'show', id, 0, this.options.instance.identifier );
            }
        },

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

            var $link = $('<a />').addClass('news_line').attr('href', url).attr('rel', topic_id+':'+id).text( title );
            this.initAjaxLink( $link );

            $newsLine = $('<p />')
                    .addClass('news_line').attr('rel', id)
                    .append( $('<span />').addClass('news_line_date').attr('rel', date_line).text(date_line_formatted) )
                    .append( $link )
                    .append( $('<div />').html( content ) );

            if( typeof urgent != 'undefined' && urgent )
                $newsLine.addClass('urgent');

            return $newsLine;
        },

        processJson : function( json ){
            var newsLines = eval( json );
            if( typeof newsLines == 'object' && newsLines.length ){
                for( var i = 0; i < newsLines.length; i++ ){
                    var o = newsLines[i];
                    var $newsLine = this.createNews(
                            o.id,
                            o.topic_id,
                            o.dateline,
                            o.dateline_formatted,
                            o.title,
                            o.url,
                            o.data,
                            o.urgent
                        );

                    if( this.$div.find( this.options.news_line ).length ){
                        $newsLine.insertBefore( this.$div.find( this.options.news_line ).slice(0, 1) );

                        this.initTooltip( $newsLine );

                        this.$div.find( this.options.news_line ).slice(-1).remove();
                    }
                }

                this.checkLastNews();
            }
        },

        reloadTopic : function(){
            var self = this;
            var topic_id = this.topics;

            self.$div.loadUI();
            this.callRemoteFunc( 'get', { data: [topic_id, this.lastId+','+this.lastDateLine], layout: 'json', callback: function(json){
                self.$div.unloadUI();
                self.processJson( json );
                self.initAutoReload();
            }, error: function(){
                self.$div.unloadUI();
                self.initAutoReload();
            }});
        },

        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(); } } )
        }

    });

})(jQuery);