(function($){

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

        this.sDisplayType = 'images';
        //this.iTotal       = 0;
        this.iTopicId     = 0;
        this.iFirstShown  = 1;
        this.iLastShown   = 0;

        this.aTooltips = [];
        this.events = ['show'];

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

        IApp_Portlet.apply(this, arguments);
    };

    Portlet_News_Topic_NewsLines_Images.prototype = $.extend(new IApp_Portlet,
    {
        init : function()
        {
            IApp_Portlet.prototype.init.apply(this, arguments);

            /** Place for on init actions **/

            this.initAutoReload();

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

            //this.$div.find('a.thickboxI').unbind();
            //tb_init(this.$div.find('a.thickboxI'));
        },

        initAutoReload : function()
        {
            var self = this;
            if ('string' == typeof this.options.instance.autoreload)
            {
                timeout = parseInt(this.options.instance.autoreload);

                if (!isNaN(timeout) && timeout > 0)
                {
                    if (this.reloadTimer)
                    {
                        clearTimeout(this.reloadTimer);
                    }

                    this.reloadTimer = setTimeout(function()
                    {
                        if (self.iFirstShown <= 1)
                        {
                            self.loadTopic(self.iTopicId);
                        }

                    }, timeout *  60 * 1000);
                }
            }
        },

        showTopic : function(id, target)
        {
            if ('string' == typeof this.options.instance.identifier && this.options.instance.identifier == target)
            {
                this.dispatchEvent('show', id, 0, this.options.instance.identifier);
            }
        },

        loadTopic : function(iTopicId)
        {
            var self = this;

            this.$div.loadUI();
            this.callRemoteFunc('load', {data: [iTopicId], callback: function(sContent)
            {
                self.$div.unloadUI();
                self.$div.html(sContent);

                self.init();
            }});
        },

        loadPaging : function(oCarousel, sState, iOffset)
        {
        	if(typeof iOffset == "undefined") iOffset = 0;
            var self         = this;
            this.iFirstShown = oCarousel.first;
            this.iLastShown  = oCarousel.last;

			//alert(oCarousel.first + ':' + oCarousel.last);

			if(!iOffset) {
	            for (var i = oCarousel.first; i <= oCarousel.last; i++)
	            {
	                if (!oCarousel.has(i))
	                {
	                	iOffset = i;
	                    break;
	                }
	            }
			}

            if (iOffset)
            {
            	oCarousel.lock();
                this.callRemoteFunc('getPaging', {data: [this.iTopicId, iOffset - 1], layout: 'json', callback: function(aNews)
                {
                	oCarousel.unlock();
                	if (0 == aNews.length)
                    {
                    	oCarousel.size(iOffset - 1);
                    }
                    else
                    {
                    	//oCarousel.size(null);
                    }

                	self.fillCarousel(aNews, oCarousel, iOffset, true);
                }});
            }
        },

        fillCarousel : function(aNews, oCarousel, iOffset, bCheckSlot)
        {
            if (!oCarousel)
            {
            	return;
            }

            for (var i in aNews)
            {
                if (!bCheckSlot || !oCarousel.has(iOffset))
                {
/*
                    var $container = $('<div />');

                    var $img = $('<a></a>').attr('href', aNews[i]['rel']).attr('rel', aNews[i]['portlet']).addClass('thickboxI').addClass('item-image').attr('target', '_blank').append(
                        $('<img />').attr('src', aNews[i]['src']).attr('alt', '').attr('rel', aNews[i]['line']));
*/
///*
                    var $html = '<a href="' + aNews[i]['rel'] + '" rel="' + aNews[i]['portlet'] + '" class="thickboxI item-image" target="_blank">\
                    	<img src="' + aNews[i]['src'] + '" alt="" rel="' + aNews[i]['line'] + '" />\
                    </a>\
                    ';
//*/

                    //$container.append($img);
                    if ('Show' == this.options.instance.paragraph)
                    {
                        //var $caption = $('<a></a>').attr('href', aNews[i]['rel']).attr('rel', aNews[i]['portlet']).addClass('thickboxI').addClass('item-caption').attr('target', '_blank').append(aNews[i]['alt']);
                        //$container.append($caption);
                        $html += '<a href="' + aNews[i]['rel'] + '" class="thickboxI item-caption" target="_blank">' + aNews[i]['alt'] + '</a>';
                    }

                    oCarousel.add(iOffset || 0,
						$html);
                    	//$container.html());
                }

                iOffset++;
            }

            var self = this;
            this.$div.find('a.thickboxI.item-image').unbind('click');
            tb_init(this.$div.find('a.thickboxI.item-image'), function(url){ 
            	$countEl = self.$div.find('a.thickboxI.item-image').size();
            	$urlPreLastEl = self.$div.find('a.thickboxI.item-image').eq($countEl-2).attr('href');
            	if($urlPreLastEl == url) {
            		self.loadPaging(oCarousel, '', $countEl+1);
            	}
        		self.loadMetadata(url);
            }, true);
 
           

            if ('Show as tooltip' ==  this.options.instance.paragraph)
            {
                this.initTooltip(this.$div);
            }
        },
        
        loadMetadata : function(url)
        {
        	var self = this;
        	
        	this.TB_margin_top = this.TB_margin_top || parseInt($('#TB_window').css('margin-top'));
        	if( $('#TB_download').length )
        		var $fullsize = $('#TB_download'); 
        	else
        		var $fullsize = $('<div id="TB_download"/>').appendTo( $('#TB_window') );
        	
        	if( $('#TB_meta').length )
        		var $meta = $('#TB_meta'); 
        	else
        		var $meta = $('<div id="TB_meta">Loading...</div>').appendTo( $('#TB_window') );
        	
        	$('#TB_window').css('margin-top', this.TB_margin_top );
        	var self = this;
        	this.callRemoteFunc('meta', {data: [url, this.options.instance.period], layout: 'json', callback: function(jdata)
            {
        		if ($.trim($(jdata.paragraph).html()).length)
                {
        			$meta.html($(jdata.paragraph).html())
        			$('#TB_window').css('margin-top', self.TB_margin_top - parseInt($meta.height() / 2) );
                }else{
                	$meta.remove();
                }
        		
    			if ($.trim($(jdata.fullsize).html()).length)
                {
        			$fullsize.html(jdata.fullsize);
        			$fullsize.find('a.ftp').click(function(){
        				
        				$('#TB_ftp').remove();
        						
        				$('<div id="TB_ftp">ftp:// <input type="text" name="ftp" /> <a class="ftp_send" href="#">Send</a> | <a class="ftp_cancel" href="#">Cancel</a></div>')
        					.find('a.ftp_cancel').click(function(){$(this).parent().remove();}).end()
        					.find('a.ftp_send').click(function(){ 
        						
        						var $cont = $(this).parent();
        						
        						self.callRemoteFunc('sendImageToFtp', {data: [url, $cont.find('input').val()], target: $cont, callback: function(){ setTimeout(function(){ $cont.fadeOut('slow'); }, 2000) } });
    							$cont.html('Sending data...');	
        					}).end()
        					.insertAfter( $fullsize );
        			});
                }else{
                	$fullsize.remove();
                }
            }});
        },
        
        initTooltip : function($container)
        {
            var self = this;

            $container.find('li a').tooltip(
            {
                bodyHandler: function () {
                    return '<div>Loading...</div>';
                    },
                track:true,
                showURL: false,
                onshow: function(el, oTooltip) {
                    oTooltip.parent.css({visibility: 'visible'});
                    var result;
                    var newsLines_rel = $(el).parent().find('img').attr('rel');
                    oTooltip.parent.show();
                    var is_need_load  = true;
                    for (var tooltip_name in self.aTooltips)
                    {
                        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.aTooltips[newsLines_rel] = jdata;

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

                            oTooltip.body.html(jdata);
                        }});
                    }
                    else if (0 != $.trim($(self.aTooltips[newsLines_rel]).html()).length)
                    {
                        oTooltip.body.html(self.aTooltips[newsLines_rel]);
                    }
                    else
                    {
                        oTooltip.parent.hide().css({visibility: 'hidden'});
                    }

                    return false;
                    },
                onhide: function(el, oTooltip) {return false;}
            });
        }
    });

})(jQuery);
