(function($)
{
	var MAX_FONT_SIZE = 4;

    Portlet_News_Body = function( id, classname ){

        this.options = {};

        this.events = ['show', 'selectTopic', 'showSimilar', 'addToOverviewList', 'updateOverviewCount', 'hideAddToOverviewList', 'saveNews', 'beforeSaveNews'];

        this.iNewsId = 0;
        this.aFormats = [];
        this.SendToEditorForm;
        this.SendToFriendForm;

        this.listen = [
            [this, 'show', this.loadNews],
            [this, 'showHighlight', this.loadNewsHighlight],
            [this, 'showSearchQuery', this.loadNewsSearchQuery],
            ['News_Topic_NewsLines_Text', 'hideAddToOverviewList', this.hideAddToOverviewList],
            ['News_Body', 'hideAddToOverviewList', this.hideAddToOverviewList],
            ['News_Overview', 'removeFromOverviewList', this.onRemoveFromOverviewList],
            ['News_Topic_NewsLines', 'select', this.showNews],
            ['News_Similar', 'select', this.showNews],
            ['News_SearchResults', 'select', this.showNews],
            //[this, 'beforeSaveNews', this.hideControls],
            ['News_Topic_NewsLines_Text', 'select', this.showNews],
            ['News_SearchResults', 'showNewsSearchQuery', this.showNewsSearchQuery],
            ['News_Topic_NewsLines_Search', 'showNewsSearchQuery', this.showNewsSearchQuery],
            //['News_Topic_NewsLines_Search', 'select', this.showNewsHighlight],
            ['News_Topic_NewsLines_PressRelease', 'select', this.showNews],

            //['News_Topic_NewsLines_PressRelease', 'saveNews', this.reloadNews],
            [this, 'saveNews', this.reloadNews],

            ['News_Topic_NewsLines_Blog', 'select', this.showNews]
        ];

        IApp_Portlet.apply(this, arguments);
    };

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

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

            /** Place for on init actions **/
            var self = this;

            this.$div.find('div.block-decorate-body,div.block-small-decor').css('padding', 0);

            if( typeof this.options.instance.identifier == 'string' && this.options.instance.identifier.length ){
                this.$div.find( '.js-next-news, .js-previous-news' ).unbind().click(function(){
                    if( $(this).attr('rel') ){
                        self.loadNews( $(this).attr('rel') );
                    }
                    return false;
                });
            }

            /** Bind click handler for overview page */
            this.$div.find('.js-add-to-overview').unbind().click(function()
            {
                if (jQuery(this).attr('rel'))
                {
                	self.addToOverviewList(jQuery(this).attr('rel'));
                }

                return false;
            });

            // Print option
            this.$div.find('.js-print').printByUrl();

            // Video content
            var sBasePath = '/';
            $('link[rel=stylesheet]').each(function()
            {
                var sHref = $(this).attr('href');

                if (-1 != sHref.indexOf('css/front.css'))
                {
                    sBasePath = sHref.replace('css/front.css', '');
                }
            });

            if (self.$div.find('p.videoClip').length > 0)
            {
                $.getScript(sBasePath + 'base/js/swfobject.js', function()
                {
                    self.$div.find('p.videoClip').each(function()
                    {
                        var oSwf = new SWFObject(sBasePath + 'images/flvplayer.swf', 'single', '320', '240', '7');
                        oSwf.addParam('allowfullscreen', 'true');
                        oSwf.addVariable('file', $(this).attr('video'));
                        oSwf.addVariable('image', $(this).attr('image'));
                        oSwf.addVariable('displayheight', '240');
                        oSwf.addVariable('width', '320');
                        oSwf.addVariable('height', '240');
                        oSwf.addParam('wmode', 'opaque');
                        oSwf.write('videoClip' + $(this).attr('rel'));

                        $(this).removeClass('videoClip');
                    });
                });
            }

            this.$div.find('.js-edit').unbind().click(function()
            {
                self.editNews();

                return false;
            });

            this.bodySize = $.cookie(this.id + "size");
            if(typeof this.bodySize == 'undefined' || this.bodySize == null) {
            	this.bodySize = 2;
            }
            this.updateFontSize(self.bodySize);
            this.$div.find('.js-font-up').unbind().click(function()
    		{
            	if( self.bodySize < MAX_FONT_SIZE) {
            		self.bodySize ++;
            	}
            	$.cookie(self.id + "size", self.bodySize, {expires: 30, path: '/'} );
            	self.updateFontSize(self.bodySize);
            	return false;
    		});
            this.$div.find('.js-font-down').unbind().click(function()
    		{
            	if( self.bodySize > 0) {
            		self.bodySize --;
            	}
            	$.cookie(self.id + "size", self.bodySize, {expires: 30, path: '/'} );
            	self.updateFontSize(self.bodySize);
            	return false;
    		});

            this.$div.find('.js-send-to-editor').unbind().click(function()
            {
            	var $id = $(this).attr('rel');
            	self.getSendToEditorForm($id);
                return false;
            });

            this.$div.find('.js-send-to-friend').unbind().click(function()
            {
            	var $id = $(this).attr('rel');
            	self.getSendToFriendForm($id);
                return false;
            });

            this.$div.find('a.thickbox').unbind('click');
            tb_init(this.$div.find('a.thickbox'), function(url){
        		self.loadMetadata(url);
            });

            if( (typeof self.options.instance.target == 'string') && self.options.instance.target.length ){
            	self.$div.find('a.js-category-link').unbind().click(function(){
                	var id = $(this).attr('rel');
                	self.dispatchEvent( 'selectTopic', id, self.options.instance.target );
                	return false;
                });
       	 	}

        },

        updateFontSize : function(size){
        	$newsDiv = this.$div.find('div.news-content-block');
        	for(var i = 0; i <= MAX_FONT_SIZE; i++) {
        		$newsDiv.removeClass('font'+i);
        	}
        	$newsDiv.addClass('font'+size);
        },

        getSendToEditorForm : function( $id ){
        	var self = this;
        	if ( typeof $id != 'undefined' || $id != 0 ) {
        		this.callRemoteFunc( 'getSendToEditorForm', { data :[$id], block: this.$div, autoeval: false,
                	callback: function(data)
                	{
                	    self.SendToEditorForm = new Boxy( $('<div />').css({overflow: 'auto'}).append( $(data).filter('div.form') ),
    	            	{
    	            		title: 'kiri toimetusele',
    	            		modal: true,
    	            		center: true,
    	            		draggable: true,
    	            		afterHide: function(el){ self.SendToEditorForm.boxy.remove() }
    	            	} ).resize(370,295,false);

    	            	self.evalDataScripts(data);
            		}
                } );
			}
        },

        getSendToFriendForm : function( $id ){
        	var self = this;
        	if ( typeof $id != 'undefined' || $id != 0 ) {
        		this.callRemoteFunc( 'getSendToFriendForm', { data :[$id], block: this.$div, autoeval: false,
                	callback: function(data)
                	{
                	    self.SendToFriendForm = new Boxy( $('<div />').css({overflow: 'auto'}).append( $(data).filter('div.form') ),
    	            	{
    	            		title: 'saada',
    	            		modal: true,
    	            		center: true,
    	            		draggable: true,
    	            		afterHide: function(el){ self.SendToFriendForm.boxy.remove() }
    	            	} ).resize(330,360,false);

    	            	self.evalDataScripts(data);
            		}
                } );
			}
        },

        showNews : function( id, target ){

        	if( typeof this.options.instance.identifier == 'string' && this.options.instance.identifier == target ){
        		if (parseInt(this.options.instance.scrollTo)){
            		$.scrollTo(this.$div);
            	}
        		this.dispatchEvent( 'show', id, this.options.instance.identifier );
            }
        },

        /*showNewsHighlight : function( id, target, highlightText ){
            if( typeof this.options.instance.identifier == 'string' && this.options.instance.identifier == target ){
            	if (parseInt(this.options.instance.scrollTo)){
            		$.scrollTo(this.$div);
            	}
            	this.dispatchEvent( 'showHighlight', id, highlightText );
            }
        },*/

        loadNews : function( id ){
            var self = this;
            this.callRemoteFunc( 'load', {data: [id], block: this.$div, autoeval: false, callback: function( html ){ self.$div.get(0).innerHTML = html; self.evalDataScripts(html); self.init(); }} )
        },

        /*loadNewsHighlight : function( id, highlightText ){
            var self = this;
            this.callRemoteFunc( 'loadHighlight', {data: [id, highlightText], block: this.$div, autoeval: false, callback: function( html ){ self.$div.get(0).innerHTML = html; self.evalDataScripts(html); self.init(); }} )
        },*/

        showNewsSearchQuery : function( id, target, searchQueryId, highlightText ){
            if( typeof this.options.instance.identifier == 'string' && this.options.instance.identifier == target ){
            	if (parseInt(this.options.instance.scrollTo)){
            		$.scrollTo(this.$div);
            	}
                this.dispatchEvent( 'showSearchQuery', id, searchQueryId, highlightText );
            }
        },

        loadNewsSearchQuery : function( id, searchQueryId, highlightText ){
            var self = this;
            this.callRemoteFunc( 'loadSearchQuery', {data: [id, searchQueryId, highlightText], block: this.$div, autoeval: false, callback: function( html ){ self.$div.get(0).innerHTML = html; self.evalDataScripts(html); self.init(); }} )
        },

        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');
            });
        },

        showSimilar: function(iNewsLineId, sSlugLine, sKeywords)
        {
            this.dispatchEvent('showSimilar', iNewsLineId, sSlugLine, this.options.instance.target, sKeywords);
        },

        hideControls: function()
        {
            this.$div.find('div.edit-side-block').hide();
        },

        editNews: function()
        {
            var self = this;

            this.$_hide = $('<div />').hide();
            this.$div.append( this.$_hide );

            var contentDiv = $('<div />').css({overflow: 'auto', height: 480});

            self.NewsForm = new Boxy(contentDiv, {
                title     : 'Edit News',
                modal     : true,
                center    : true,
                draggable : true,
                afterHide : function(el) {
                    self.NewsForm.boxy.remove();
                }
            }).resize(800, 500, false);

            this.callRemoteFunc('edit', { target: this.$_hide, data: [this.iNewsId], autoeval: false, callback: function(data)
            {
                contentDiv.append(self.$_hide.children());
            }});
        },

        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 (jdata && $.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 (jdata && $.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();
                }
            }});
        },

        reloadNews: function() {
            var self = this;
            this.callRemoteFunc( 'load', {data: [':' + this.iNewsId], block: self.$div, autoeval: false, callback: function( html ){ self.$div.get(0).innerHTML = html; self.evalDataScripts(html); self.init(); }} )
        }

        /*,

        loadMetadata : function(url)
        {
        	if( $('#TB_download').length )
        		var $fullsize = $('#TB_download');
        	else
        		var $fullsize = $('<div id="TB_download"/>').appendTo( $('#TB_window') );

        	var self = this;
        	this.callRemoteFunc('meta', {data: [url], layout: 'json', callback: function(jdata)
            {
        		if ($.trim($(jdata.fullsize).html()).length)
                {
        			$fullsize.html(jdata.fullsize);

                }else{
                	$fullsize.remove();
                }
            }});
        }*/
    });

})(jQuery);
