Ext.namespace('Kelda', 'Kelda.Info');

Kelda.Info.NewsFeedCacheId = function(config) {
	Ext.apply(this,config);
	Ext.apply(this,{ok:1});
};
Kelda.Info.NewsFeedCache = function(config) {
	Ext.apply(this,config);
};


Kelda.Info.NewsFeedGrid = Ext.extend(Ext.grid.GridPanel, {
	lastPreviewIndex :-1,
	isFirstLoad : true,
	loadOnShow : true,
	normalFeedIds:null,
	currentStart : 0,
	autoDestroy:false,
	domesticOnly:true,
	foreignOnly:false,
	maxFeedId:0,
    createPagingToolBar : function(owner,s) {
    	var pt = new Ext.PagingToolbar({
    		pageSize: 30,
            store: s,
            displayInfo: true,
            displayMsg: '{0} - {1} '+keldan_lang_text('of') +' {2}',
            beforePageText:keldan_lang_text('page'),
            afterPageText:keldan_lang_text('of')+' {0}',
            emptyMsg: keldan_lang_text('no news'),
            lastText: keldan_lang_text('last page'),
            nextText : keldan_lang_text('next page'),
            refreshText:keldan_lang_text('refresh')
    	});
    	pt.on('beforechange',function(p,ev){
    		p.store.baseParams.start=ev.start;
    		p.store.baseParams.limit=ev.limit;
    	});
    	return pt;
	},
    initComponent :function(){
    	var newsGrid = this;
    	this.normalFeedIds = new Kelda.Info.NewsFeedCache({
    			type:'normal',
    			query:null,
    			filter:null
    	});
    	this.currentFeedIds = this.normalFeedIds;
    	var columns=[{
            id: 'topic', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
            header: keldan_lang_text('topic'),
            dataIndex: 'title',
            fixed:true,
            width: 100,//100
            renderer: function(value,p,record) {
    			//if(record.data.preview != 1)
    				//p.attr = 'qtip="'+record.data.title+'" qtitle="'+record.data.source+'"';
        		return value;
        	},
            sortable: false,
            menuDisabled:true
        },{
        	id:'source',
            header: keldan_lang_text('source'),
            dataIndex: 'source',
            width: (Ext.isIE||Ext.isChrome?50:40),//50
            align: 'right',
            fixed:true,
            sortable: false
            
        },{
            //id: 'date'
        	id:'newsdate',
            header: keldan_lang_text('time'),
            dataIndex: 'newsdate',
            menuDisabled:true,
            align:'left',
            width: (Ext.isGecko3?40:46),
            fixed:true,
            //renderer:Ext.util.Format.dateRenderer('d/m/Y H:i:s'),
            renderer : function(value,p,record) {
        		var d = Date.parseDate(record.data.newsdate,"U");
        		if(!d) return "?";
        		var today = new Date();
        		var mid = today.clearTime(true);
        		var t = today.add(Date.DAY,1);
        		var tmid = t.clearTime(true);
        		Date.monthNames = clock_months_is;
        		//console.log(d);
        		if(d.between(mid,tmid)) {
        			//console.log(mid+"   "+d+"   "+tmid);
        			return d.format('H:i');
        		}
        		else
        			return d.format('d.M');
        		
        	},
            sortable: true
        }/*,{
        	id: 'desc',
            header: "Lýsing",
            dataIndex: 'description',
            width: 70,
            sortable: true,
            hidden:true
        }*/];
    	var newsSourceStore = new Ext.data.JsonStore({
    		root:'result',
    		fields:[{name:'title',type:'string'},{name:'fullSource',type:'string'},
    		        {name:'domestic',type:'string'},{name:'category',type:'string'}],
    		proxy:new Ext.data.HttpProxy({
    			url:window.location.protocol+"//"+window.location.hostname+"/"+basePath+"feeds-sources"
    		}),
    		baseParams:{domestic_usage:(keldan_lang=='is'?true:false)}
    	});
    	
    	var newsstore = new Ext.data.JsonStore({
        	root: 'feedItems',
            totalProperty: 'totalCount',
            autoDestroy:true,
            //idProperty: 'feedId',
            //remoteSort: false,
            fields: [{name:'feedId',type:'int'},
                     {name:'title',convert:function(value,record){
            			//news feed aggregator looses some latin1 characters in translation to utf8.
                    	 return "<ul><li>"+value.replace(/\u0096/g,"&#150;").replace(/\u0084/g,"&#132;").replace(/\u0093/g,"&#147;").replace(/\u0094/g,"&#147;")
                    	 .replace(/\u0091/g,"&#145;").replace(/&amp;bdquo;/g,"&bdquo;").replace(/&amp;ldquo;/g,"&ldquo;")+"</li></ul>";
                    	 
                     },type:'string'},
                     'fullTitle',
                     'source',
                     'sourcelang',
                     'link',
                     {name:'description',convert:function(value,record){
            			//news feed aggregator looses some latin1 characters in translation to utf8.
                    	 return value.replace(/\u0096/g,"&#150;").replace(/\u0084/g,"&#132;").replace(/\u0093/g,"&#147;").replace(/\u0094/g,"&#147;")
                    	 .replace(/\u0091/g,"&#145;").replace(/&amp;bdquo;/g,"&bdquo;").replace(/&amp;ldquo;/g,"&ldquo;");
                     },type:'string'},
                     {name: 'newsdate',type:'int',convert:function(val,rec){
                    	 /*if(rec.source=='HAL') {
                    		var fetchD = new Date();
                    		fetchD.setTime(val);
             				var dstr = rec.link.substring(rec.link.length-11,rec.link.length-1);
                  			var dsplit = dstr.split("-");
                  			var h = new Date();
                  			h.setYear(dsplit[0]);
                  			h.setMonth(dsplit[1]-1);
                  			h.setDate(dsplit[2]);
                  			//must set hour and min or else HAL will always be on top
                  			h.setHours(fetchD.getHours());
                  			h.setMinutes(fetchD.getMinutes());
                  			
                  			//console.log('returning '+h+" millis: "+(h.getTime()/1000).toFixed(0));
                  			return (h.getTime()/1000).toFixed(0);
                  		}*/
                    	return val;
                     }},
                     {name:'preview',type:'int',defaultValue:'0'},
                     {name:'unread',type :'int',defaultValue:'1'},
                     {name:'newFeed',type:'int',defaultValue:'0'},
                     {name:'category'}
                
            ],
            proxy: new Ext.data.HttpProxy({
                url: window.location.protocol+"//"+window.location.hostname+"/"+basePath+"feeds-proxy"
            }),
            sortInfo : {field:'newsdate',direction:'DESC'},
            baseParams:{domesticOnly:newsGrid.domesticOnly,foreignOnly:newsGrid.foreignOnly,domesticUsage:(keldan_lang=='is'?true:false),category:newsGrid.newscategory,
            	start:0,limit:30}
        });
    	
    	newsstore.on('loadexception',function() {
    		//alert('load exception');
    	});
    	toolbarTop = new Ext.Toolbar();
    	
    	var ptb = this.createPagingToolBar(this,newsstore);
    	this.newsFilters = new Ext.grid.GridFilters({
    		id:'filter_'+Math.random()*1000,
    		filters:[
    		 {
    			 id:'listfilter_'+Math.random()*1000,
    			 type:'list',
    			 labelField:'title',
    			 tooltipField:'fullSource',
    			 categoryField:'category',
    			 dataIndex:'source',
    			 store:newsSourceStore,
    			 foreignOnly:newsGrid.foreignOnly,
    			 domesticOnly:newsGrid.domesticOnly,
    			 category:newsGrid.newscategory,
    			 domesticUsage:(keldan_lang=='is'?true:false),
    			 phpMode:true
    		 }
    		],
    		local:false,
    		dataIndex:'source'
    		
    	});
    	
    	
    	Ext.apply(this,{
    		id:'newsgrid_'+Math.random()*101,
    		stateId:'newsp_'+this.newscategory,
    		stateful:false,
    		cls:'news-feeds',
    		store : newsstore,
    	    columns:columns,
    	    autoExpandColumn:'topic',
    	    enableColumnMove:false,
    	    enableHdMenu:true,
    	    plugins:[new Ext.ux.grid.Search({
    	    	//cls:'news-search',
    	    	iconCls:'icon-find',
    	    	searchText:keldan_lang_text('search'),
    	    	searchTipText:keldan_lang_text('enter search term'),
    	    	selectAllText:keldan_lang_text('select all'),
    	    	checkIndexes:['title','description'],
    	    	disableIndexes:['source','link','date','preview'],
    	    	width:160,
    	    	minChars:2,
    	    	position:'top',
    	    	autoFocus:false
    	    }),this.newsFilters],
    	    //width:400,
    	    viewConfig: {
                forceFit:false,
                enableRowBody:true,
                showPreview:false,
                getRowClass : function(record, rowIndex, p, store){
    				var retClass = '';
    				if(record.data.preview==1){
    					//var ael = new Ext.Element();
    					//console.log(record.data.description);
    					var desc = record.data.description.replace(/<a.*<\/a>/g,"");
    					desc = desc.replace(/<hr.*\/>/g,"");
    					//desc = desc.replace(/<div.*"<\/div>"{1}/g,"")
    					//desc = desc.substring(0,300);
    					//desc = desc.replace(/<p>|<\/p>/g,"");
    					//console.log(desc);
    					if( (idx = desc.indexOf("/mm/img")) > 0) {
    						var tmp1 = desc.substring(0,idx);
    						var tmp2 = desc.substring(idx,desc.length);
    						desc = tmp1+"http://www.mbl.is"+tmp2;
    					}
    					var l = record.data.link;
    					var hreftext = '<p><a id="news-more-id" href="'+l+'" class="more-news-link" target="_blank"><b>'+
                        (keldan_lang=='is'?'Meira':'More')+'</b></a>';
    					hreftext = '<p><a id="news-more-id" href="'+l+'" class="more-news-link" target="_blank"><b>'+
                        (keldan_lang=='is'?'Meira':'More')+'</b></a>'; 
    					
                        p.body = '<p><b>'+record.data.title+'</b></p>'+ 
                        '<p>'+desc+'</p>'+hreftext;
                        if(keldan_lang=='is' && record.data.sourcelang!=='is') {
                        	p.body += '<a target="_blank" class="trans-news-link" href="'+
                        	'http://translate.google.com/translate?prev=hp&hl=en&js=y&u='+record.data.link+
                        	'&sl='+record.data.sourcelang+'&tl=is&history_state0="><b>Þýða</b></a></p>';
                        }else if(keldan_lang=='en' && record.data.sourcelang!=='en') {
                        	p.body += '<a target="_blank" class="trans-news-link" href="'+
                        	'http://translate.google.com/translate?prev=hp&hl=en&js=y&u='+record.data.link+
                        	'&sl='+record.data.sourcelang+'&tl=en&history_state0="><b>Translate</b></a></p>';
                        }else {
                        	p.body += "</p>";
                        }
    					
    					//p.body= '<p><b>'+record.data.title+'</b></p>'+'<p>'+record.data.description+'</p>';
                        if(record.data.category=='DOM_FUN') {
                        	retClass = 'x-grid3-row-img x-grid3-row-expanded x-grid3-row-news x-grid3-row-selected';
                        }else {
                        	retClass = 'x-grid3-row-noimg x-grid3-row-expanded x-grid3-row-news x-grid3-row-selected';
                        }
                    }else {
                    	retClass = 'x-grid3-row-collapsed x-grid3-row-news';
                    }
    				if(record.data.unread===0) {
    					retClass += ' x-grid3-col-topic-read';
    				}
    				if(record.data.newFeed==1) {
    					
    					retClass += ' x-grid3-col-topic-new';
    				}
    				
    				return retClass;
                },
                columnsText:keldan_lang_text('columns'),
    			sortAscText:keldan_lang_text('sort ascending'),
    			sortDescText:keldan_lang_text('sort descending')
            },
            bbar: ptb,
            tbar: toolbarTop,
           //height:400,
    		enableHdMenu:false,
    		header:false,
    		hideHeaders:true,
    		//stateId:'newsgrid_'+this.domesticOnly?"dom":"fgn",
    		stateful:true
    	});
   
    	var gridView = this.getView();
    	newsstore.on('beforeload',function(s,o){
    		
    		this.currentStart = o.params ? o.params.start : 0;
    		if(!this.isFirstLoad)
    			for(var l in this.currentFeedIds) {
    				 if(this.currentFeedIds[l] && !(this.currentFeedIds[l].ok===undefined) ) {
    					//console.log('ok is defined');
    					this.currentFeedIds[l].ok=0;
    				 }
    			}
    	},this);
    	newsstore.on("load",function(store,records,options){
    		if(this.loadMask.disable)
    			this.loadMask.disable();
    		//delete store.baseParams.start;
    		//delete store.baseParams.limit;
    		//console.log('CurrentFeedIds query is '+this.currentFeedIds.query);
    		//console.log('NormalFeedIds query is '+this.normalFeedIds.query);
    		//console.log('Current query ' +this.currentFeedIds.query+" Store query : "+options.params.query);
			//console.log('Current filter ' +this.currentFeedIds.filter+" Store filter : "+options.params['filter[0][data][type]']);
    		var l = records.length;
    		var size = 0;
    		if(options.params.start == "0" &&
    				this.currentFeedIds.query == options.params.query && 
    				this.currentFeedIds.filter == options.params['filter[0][data][value]']) {
    		  //console.log('no cache switch');
    		  for(i = 0; i < l; i++) {
    			
    			rec = records[i];
    			var fid = this.currentFeedIds[rec.data.link];
    			if(!fid) {
    				this.currentFeedIds[rec.data.link] = new Kelda.Info.NewsFeedCacheId({
    						feedId:rec.data.feedId,
    						unread:rec.data.unread,
    						preview:rec.data.preview,
    						newFeed:this.isFirstLoad?0:1,
    						ok:1
    				}); 
    				rec.data.newFeed=this.isFirstLoad?0:1;
    				
    			}else {
    				fid.newFeed=0;
    				fid.ok=1;
    				rec.data.unread=fid.unread;
    				rec.data.preview=fid.preview;
    				rec.data.newFeed=0;
    			}
    		}
    		}else if(this.currentFeedIds.query != options.params.query || 
    				this.currentFeedIds.filter != options.params['filter[0][data][value]'] ) {
    			// cache switch !
    			//console.log('cache switch');
    			
    			if(!options.params.query && !options.params['filter[0][data][value]'] ) {
    				//normal default cache.
    				//console.log('switching to default');
    				var tmpFeedIds = this.currentFeedIds;
    				this.currentFeedIds = this.normalFeedIds;
    				this.currentFeedIds.query = options.params.query;
    				this.currentFeedIds.filter = (options.params['filter[0][data][value]']?options.params['filter[0][data][value]']:null);
    				for(ii = 0; ii < l; ii++) {
    					rec = records[ii];
    					var fid = this.currentFeedIds[rec.data.link];
    					if(!fid) {
    						var isNewFeed = (tmpFeedIds[rec.data.link]?false:true);
    						this.currentFeedIds[rec.data.link] = new Kelda.Info.NewsFeedCacheId({
    								feedId:rec.data.feedId,
        							unread:rec.data.unread,
        							preview:rec.data.preview,
        							newFeed:isNewFeed,
        							ok:1
    						}); 
    						rec.data.newFeed=isNewFeed;
    						
    					}else {
    						fid.newFeed=0;
    						fid.ok=1;
    						rec.data.unread=fid.unread;
    						rec.data.preview=fid.preview;
    						rec.data.newFeed=0;
    					}
    				}
    			}else {
    				//console.log('switching to custom');
    				
    				this.currentFeedIds = new Kelda.Info.NewsFeedCache({
    					type : 'custom',
    					query : options.params.query,
    					filter : options.params['filter[0][data][value]']
    				});
    				//console.log('CurrentFeedIds query is now '+this.currentFeedIds.query);
    				for(i = 0; i<l;i++) {
    					rec = records[i];
    				//	console.log('adding link to custom cache ');
    					this.currentFeedIds[rec.data.link] = new Kelda.Info.NewsFeedCacheId({
    						feedId:rec.data.feedId,
    						unread:rec.data.unread,
    						preview:rec.data.preview,
    						newFeed:0,
    						ok:1
    					}); 
    					rec.data.newFeed=0;
    				}
    			}
    		}
    		/*
    		for(var iok in this.currentFeedIds) {
    			if( !(this.currentFeedIds[iok].ok === undefined) )
    				if(this.currentFeedIds[iok].ok==0) {
    					console.log('ok is null,deleting');
    					delete this.currentFeedIds.iok;
    				}
    			
    		}
    		*/
    		for(var l in this.currentFeedIds) {
				 if(this.currentFeedIds[l] && !(this.currentFeedIds[l].ok===undefined) ) {
					
					if(this.currentFeedIds[l].ok==0) {
						//console.log('deleting ok');
						delete this.currentFeedIds[l];
					}
						
				 }
			}
    		for(var jj in this.currentFeedIds) {
    			size++;
    		}
    		this.isFirstLoad=false;
    		//console.log(size);
    		//store.sort('date',"ASC");
    		
    		if(Ext.Msg.isVisible()) {
				keldan_store_count--;
				Ext.Msg.updateProgress((keldan_fixed_stcount-keldan_store_count)/keldan_fixed_stcount
						,keldan_fixed_stcount-keldan_store_count+(keldan_lang=='is' ? ' af ' : ' of ')+keldan_fixed_stcount);
				if(keldan_store_count==0) {
					Ext.Msg.hide();
					keldan_store_count=-1;
				}
			}
    		gridView.refresh();
    		
    	},this);
    	
    	this.on('rowclick',function(grid,rIndex,ev) {
    		var el = ev.getTarget(null,null,true);
    		if(el.dom.parentNode.target=="_blank")return;
    		else if(el.dom.parentNode.target=='_self') {
    			location.reload(true);
    		}
    		var row = grid.getStore().getAt(rIndex);
    		var slength = grid.getStore().data.length;
    		if(row.data.preview===0) {
    			/*if(this.lastPreviewIndex > -1) {
	    			var oldrow = grid.getStore().getAt(this.lastPreviewIndex);
	    			if(oldrow) {
	    				oldrow.data.preview=0;
	    				var crow = this.currentFeedIds[oldrow.data.feedId];
						if(crow) {
							crow.preview=0;
						}
	    			}
	    			
	    		}*/
    			for(i=0;i<slength;i++) {
    				var r = grid.getStore().getAt(i);
    				if(r.data.preview==1) {
    					r.data.preview=0;
    					var oldR = this.currentFeedIds[r.data.link]; 
    					if(oldR)
    						oldR.preview=0;
    				}
    			}
    			this.lastPreviewIndex = rIndex;
    			row.data.preview=1;
    			row.data.unread=0;
    			crow = this.currentFeedIds[row.data.link];
    			if(crow) {
    				crow.unread = 0;
    				crow.preview = 1;
    			}
    			
    		}
			else {
				row.data.preview=0;
				crow = this.currentFeedIds[row.data.link];
    			if(crow) {
    				crow.preview=0;
    			}
				
			}
    		this.getView().refresh();
    		this.getView().focusRow(rIndex);
    	});
    	
    	this.filterMenu = new Ext.menu.Menu();
		this.filterBtn = new Ext.Button({
    		text: keldan_lang_text('sources'),
    		menu:this.filterMenu
    	});
    	this.newstask = {
	        	run:function() {
    				if(newsGrid.currentStart===0)
    					newsstore.reload({params:{start:0, limit:30,domesticOnly:newsGrid.domesticOnly,
    						foreignOnly:newsGrid.foreignOnly,category:newsGrid.newscategory}});
    				else
    					return;
				},
				interval: 60000
		};
    	//this.taskTimeout = setTimeout('Ext.TaskMgr.start(this.newstask)',60000);
    	
    	this.on('destroy',function(){
    		Ext.TaskMgr.stop(this.newstask);
    	});
    	this.on('hide',function(){
    		Ext.TaskMgr.stop(this.newstask);
    	});
    	
    	this.on('show',function(grid1) {
    		if(this.loadOnShow) {
    			Ext.TaskMgr.start(this.newstask);
    		}
    		
		},this);
    	
    	this.on('render',function(){
    		
    		this.getTopToolbar().add(this.filterBtn);
        	
    	},this);
    	
    	
    	this.on('beforestatesave',function(grid,state){
    		this.newsFilters.saveState(grid,state);
    	},this);
    	this.on('beforestaterestore',function(grid,state){
    		this.newsFilters.applyState(grid,state);
    	},this);
    	
    	this.getView().showPreview=false;
    	//newsstore.load({params:{start:0, limit:30}});
    	Kelda.Info.NewsFeedGrid.superclass.initComponent.apply(this,arguments);
    },
    stopPoll : function() {
		Ext.TaskMgr.stop(this.newstask);
	},
	startPoll : function() {
		Ext.TaskMgr.start(this.newstask);
	},
    getFilterMenu : function() {
    	return this.filterMenu;
    },
    getFilterBtn : function() {
    	return this.filterBtn;
    }
    
});
Ext.reg('nfp_Child',Kelda.Info.NewsFeedGrid);
Ext.ux.SliderTip = Ext.extend(Ext.Tip, {
    minWidth: 10,
    offsets : [0, -10],
    init : function(slider){
        slider.on('dragstart', this.onSlide, this);
        slider.on('drag', this.onSlide, this);
        slider.on('dragend', this.hide, this);
        slider.on('destroy', this.destroy, this);
    },

    onSlide : function(slider){
        this.show();
        this.body.update(this.getText(slider));
        this.doAutoWidth();
        this.el.alignTo(slider.thumb, 'b-t?', this.offsets);
    },

    getText : function(slider){
        return slider.getValue();
    }
});
Kelda.Info.NewsFeedPortlet = Ext.extend(Ext.Panel,{
	//id:'NewsFeed',
	/*
	initComponent:function() {
		
		this.on('render',function(){
			if(this.height != undefined)
				return;
			var vp = Ext.getCmp('main-viewport');
			var h = 0;
			if(vp) {
				h = 0;
				if((vp.getSize().height-50) > 760) {
					h = 760;
				}else {
					h = vp.getSize().height-110;
				}
				this.setHeight(h);
			}
			
		});
		//Kelda.Info.NewsFeedPortlet.superclass.initComponent.apply(this,arguments);
	},*/
	layout:'fit',
	listeners: {
		'render' : {
			fn : function() {
				if(this.height != undefined)
					return;
				var vp = Ext.getCmp('main-viewport');
				var h = 0;
				if(vp) {
					h = 0;
					if((vp.getSize().height-50) > 760) {
						h = 760;
					}else {
						h = vp.getSize().height-110;
					}
					this.setHeight(h);
				}
			}
		}
	},
	plugins: [Ext.ux.PortletPlugin],
    closeable: true,
    maximizable:false,
    settings: false,
    resizeable:true,
    collapsible:true,
    version:1.0001,
    width:400
    //height:720
});
Ext.reg('nfp',Kelda.Info.NewsFeedPortlet);



/*
grid1.tip = new Ext.ToolTip({
    view: grid1.getView(),
    target: grid1.getView().mainBody,
    delegate: '.x-grid3-col-topic',
    trackMouse: true,
    renderTo: document.body,
    showDelay:1800,
    hideDelay:0,
    listeners: {
        beforeshow: function updateTipBody(tip) {
			var idx = tip.view.findRowIndex(tip.triggerElement);
			var rec = grid1.getStore().getAt(idx);
			if(rec.data.preview==1)return false;
			
            tip.body.dom.innerHTML = '<b>'+rec.data.source+'</b><br/>'  + rec.data.title;
        }
    }
});
*/