/*
* $Id: summary.js 633 2008-07-28 17:01:19Z lukejee $
*/
Ext.namespace('NGMP.summary');
Ext.namespace('NGMP.portlets');

NGMP.summary.PortalColumn=Ext.extend(Ext.Container,{
	layout:"anchor",
	autoEl:"div",
	defaultType:"portlet",
	cls:"x-portal-column"
});
Ext.reg("portalcolumn",NGMP.summary.PortalColumn);

NGMP.summary.Portlet=Ext.extend(Ext.Panel,{
	anchor:"100%",
	frame:true,
	collapsible:true,
	draggable:true,
	cls:"x-portlet"
});
Ext.reg("portlet",NGMP.summary.Portlet);

NGMP.summary.Portal=Ext.extend(Ext.Panel,{
	layout:"column",
	autoScroll:true,
	cls:"x-portal",
	defaultType:"portalcolumn",
	initComponent:function(){
		NGMP.summary.Portal.superclass.initComponent.call(this);
		this.addEvents({
			validatedrop:true,
			beforedragover:true,
			dragover:true,
			beforedrop:true,
			drop:true
		});
	},
	initEvents:function(){
		NGMP.summary.Portal.superclass.initEvents.call(this);
		this.dd=new NGMP.summary.Portal.DropZone(this,this.dropConfig);
	}
});
Ext.reg("portal",NGMP.summary.Portal);

NGMP.summary.Portal.DropZone=function(A,B){
	this.portal=A;
	Ext.dd.ScrollManager.register(A.body);
	NGMP.summary.Portal.DropZone.superclass.constructor.call(this,A.bwrap.dom,B);
	A.body.ddScrollConfig=this.ddScrollConfig;
};

Ext.extend(NGMP.summary.Portal.DropZone,Ext.dd.DropTarget,{
	ddScrollConfig:{
		vthresh:50,
		hthresh:-1,
		animate:true,
		increment:200
	},
	createEvent:function(A,D,C,B,F,E){
		return{
			portal:this.portal,
			panel:C.panel,
			columnIndex:B,
			column:F,
			position:E,
			data:C,
			source:A,
			rawEvent:D,
			status:this.dropAllowed
		};
	},
	notifyOver:function(Q,O,R){
		var D=O.getXY(),
		A=this.portal,
		J=Q.proxy;
		if(!this.grid){
			this.grid=this.getGrid();
		}
		var B=A.body.dom.clientWidth;
		if (!this.lastCW){
			this.lastCW=B;
		} else {
			if(this.lastCW!=B){
				this.lastCW=B;
				A.doLayout();
			   	this.grid=this.getGrid();
		   	}
	  	}
		var C=0;
		H=this.grid.columnX;
		I=false;
		for(var M=H.length;	C<M;C++){
			if(D[0]<(H[C].x+H[C].w)){
				I=true;
				break;
			}
	    }
		if(!I){
			C--;
		}
		var L,G=false,F=0,P=A.items.itemAt(C);
		if(!P.items){
			P.initItems();
		}
		var K=P.items.items;
		for(M=K.length;	F<M;F++){
			L=K[F];
			var N=L.el.getHeight();
			if(N!==0&&(L.el.getY()+(N/2))>D[1]){
				G=true;
				break;
			}
		}
		var E=this.createEvent(Q,O,R,C,P,G&&L?F:P.items.getCount());
		if(A.fireEvent("validatedrop",E)!==false&&A.fireEvent("beforedragover",E)!==false){
			J.getProxy().setWidth("auto");
			if (L) {
				J.moveProxy(L.el.dom.parentNode,G?L.el.dom:null);
			} else {
				J.moveProxy(P.el.dom,null);
			}
			this.lastPos={
				c:P,
				col:C,
				p:G&&L?F:false
			};
			this.scrollPos=A.body.getScroll();
			A.fireEvent("dragover",E);
			return E.status;
		} else {
			return E.status;
		}
	},
	notifyOut:function(){
		delete this.grid;
	},
	notifyDrop:function(H,D,C){
		delete this.grid;
		if (!this.lastPos){
			return;
		}
		var F=this.lastPos.c,B=this.lastPos.col,G=this.lastPos.p;
		var A=this.createEvent(H,D,C,B,F,G!==false?G:F.items.getCount());
		if(this.portal.fireEvent("validatedrop",A)!==false&&this.portal.fireEvent("beforedrop",A)!==false){
			H.proxy.getProxy().remove();
			H.panel.el.dom.parentNode.removeChild(H.panel.el.dom);
			if (G!==false) {
				F.insert(G,H.panel);
			} else {
				F.add(H.panel);
			}
			F.doLayout();
				this.portal.fireEvent("drop",A);
				var I=this.scrollPos.top;
				if (I) {
					var E=this.portal.body.dom;
					setTimeout(function(){
						E.scrollTop=I;
					},10);
				}
			}
			delete this.lastPos;
	},
	getGrid:function(){
		var A=this.portal.bwrap.getBox();
		A.columnX=[];
		this.portal.items.each(function(B){
			A.columnX.push({
				x:B.el.getX(),
				w:B.el.getWidth()
			});
		});
		return A;
	}
});

NGMP.summary.SummaryModule = function(C) {
	if(!C){C={};}

	NGMP.summary.portlets=[];

	this.rssFeedPortlet = new NGMP.portlets.rssFeedPortlet();

	NGMP.summary.portlets['portlet-rss-reader'] = new NGMP.summary.Portlet({
		id:'portlet-rss-reader',
		iconCls:'icon-rss',
		title:LANG_hot_topics,
		layout:'fit',
		items:this.rssFeedPortlet,
		tools:[{
			id:'gear',
			handler:function() {

				Ext.Msg.prompt(LANG_url, LANG_please_enter_the_rss_feed_url+':', function(D,E) {
					if (D == 'ok') {
						this.rssFeedPortlet.store.baseParams.addChannel = E;
						this.rssFeedPortlet.store.reload();
						delete this.rssFeedPortlet.store.baseParams.addChannel;
					} 
				}, this);
			},
			scope:this
		},{
			id:'close',
			handler:function(F,E,D) {
				D.ownerCt.remove(D,true);
			}
		},{
			id:'refresh',
			handler:function() {
				this.rssFeedPortlet.store.reload();
			},
			scope:this
		}],
		height:600
	});

	this.formNoteField = new Ext.form.TextArea({
		hideLabel:true,
		name:'text',
		anchor:'100% 100%'
	});

	this.noteForm = new Ext.form.FormPanel({
		url:'ngmp.php',
		baseParams:{
			func:'summaryNote'
		},
		items:this.formNoteField,
		waitMsgTarget: true
	});

	this.noteForm.on('render', function() {
		this.noteForm.load();
	},this);

	this.formNoteField.on('change', function() {
		this.noteForm.form.submit();
	},this);



	NGMP.summary.portlets['portlet-note'] = new NGMP.summary.Portlet({
		id:'portlet-note',
		iconCls:'icon-notes',
		title:LANG_notes,
		layout:'fit',
		tools:[{
			id:'close',
			handler:function(F,E,D) {
				D.ownerCt.remove(D,true);
			}
		}],
		items:this.noteForm,
		height:300
	});

   
 	this.activePortletsIds=Ext.state.Manager.get("active-portlets");
	
	if(!this.activePortletsIds){
		this.activePortletsIds=["portlet-rss-reader","portlet-tasks","portlet-calendar","portlet-note"];
	}     
	
	this.columns=[{
		columnWidth:0.5,
		style:"padding:10px 0 10px 10px",
		border:false
	},{
		columnWidth:0.5,
		style:"padding:10px 0 10px 10px",
		border:false
	}];
	
	var A=Math.ceil(this.activePortletsIds.length/this.columns.length);
	for(var E=0;E<this.activePortletsIds.length;E++){
		if(NGMP.summary.portlets[this.activePortletsIds[E]]) {
			this.activePortlets.push(this.activePortletsIds[E]);
			var B=Math.ceil((E+1)/A)-1;
			var D=this.columns[B];
			if(!D.items){
				D.items=[
					NGMP.summary.portlets[this.activePortletsIds[E]]
				];
			} else {
				D.items.push(NGMP.summary.portlets[this.activePortletsIds[E]]);
			}
		}
	}
	C.items=this.columns;
	for (E in NGMP.summary.portlets) {
		this.availablePortlets.push(NGMP.summary.portlets[E]);
	}
	if (!C.items) {
		C.html="You don't have any items on your startpage.";
	}	
	NGMP.summary.SummaryModule.superclass.constructor.call(this,C);
};
Ext.extend(NGMP.summary.SummaryModule,NGMP.summary.Portal, {
	onShow:function() {
		this.rssFeedPortlet.store.load();
		this.noteForm.load();
		NGMP.summary.SummaryModule.superclass.onShow.call(this);	
	},
	afterRender:function() {
		NGMP.summary.SummaryModule.superclass.afterRender.call(this);
	},
	activePortlets:Array(),
	availablePortlets:Array(),
	showAvailablePortlets:function(){
		var E={portlets:this.availablePortlets};
		var A=new Ext.data.JsonStore({
			id:"id",
			root:"portlets",
			fields:["id","title","iconCls"]
		});
		A.loadData(E);

		var B='<tpl for="."><div class="ngmp-item-wrap">{title}</div></tpl>';

		var D=new NGMP.grid.SimpleSelectList({store:A,tpl:B});

		D.on("click",function(F,H){
			var J=F.store.data.items[H].data.id;
			var G=0;
			for(var I=0;I<this.columns.length;I++){
				if(!this.columns[I].items||this.columns[I].items.length===0||G>this.columns[I].items.length){
					break;
				}
				G=this.columns[I].items.length;
			}
			this.columns[I].add(NGMP.summary.portlets[J]);
			this.columns[I].doLayout();
			D.clearSelections();
			C.close();
		},this);

		var C=new Ext.Window({
			title:LANG_select_portlett,
			layout:"fit",
			modal:true,
			height:400,
			width:600,
			closable:true,
			closeAction:"hide",
			items:new Ext.Panel({
				items:D,
				cls:"ngmp-form-panel"
			})
		});
		C.show();
   }	
});
NGMP.moduleManager.addModule('summary', NGMP.summary.SummaryModule, {
	title:LANG_summary,
	iconCls:'icon-summary'
});

NGMP.portlets.rssFeedPortlet=function(A){
	Ext.apply(this,A);
	
	this.store = new Ext.data.GroupingStore({
		baseParams:{
			func:'summaryFeeds'
		},
		groupField:'channel',
		sortInfo:{
			field:'pubDate',
			direction:'DESC'
		},
		proxy:new Ext.data.HttpProxy({
			url:'ngmp.php'
		}),
		reader: new Ext.data.JsonReader({
			totalProperty:'count',
			root:'results',
			id:'title',
			fields:['channel_id','channel', {name:'pubDate', type:'date'}, 'title', 'author','link']
		})
	});
		
	this.columns=[
		{header:LANG_channel, dataIndex:'channel'},
		{header:LANG_title,dataIndex:"title",sortable:true,width:420,renderer:this.formatTitle},
		{header:LANG_author,dataIndex:"author",width:100,hidden:true,sortable:true},
		{header:LANG_pub_date,dataIndex:"pubDate",width:120,renderer:this.formatDate,sortable:true}
	];

	this.view = new Ext.grid.GroupingView({
		hideGroupedColumn:true,	
		showGroupName:false
	});
		
	NGMP.portlets.rssFeedPortlet.superclass.constructor.call(this,{
		loadMask:{msg:LANG_loading},
		store:this.store,
		sm:new Ext.grid.RowSelectionModel({singleSelect:true}),
		viewConfig:{forceFit:true,enableRowBody:true,showPreview:true,getRowClass:this.applyRowClass}
	});
	
	this.on("rowcontextmenu",this.onContextClick,this);
};
			
Ext.extend(NGMP.portlets.rssFeedPortlet,NGMP.grid.GridPanel,{
	afterRender:function(){
		this.store.load();
		NGMP.portlets.rssFeedPortlet.superclass.afterRender.call(this);
		this.on("rowDblClick",this.rowDoubleClick,this);
	},
	
	rowDoubleClick:function(C,B,D){
		var A=this.store.getAt(B);
		window.open(A.data.link);
	},
	
	onContextClick:function(B,A,C){
		if(!this.menu){
			this.menu=new Ext.menu.Menu({
				id:"grid-ctx",
				items:[{
					iconCls:"new-win",
					text:LANG_go_to_post,
					scope:this,
					handler:function(){
						window.open(this.ctxRecord.data.link);
					}
			    },"-",{
					iconCls:"refresh-icon",
					text:LANG_refresh,
					scope:this,
					handler:function(){
						this.ctxRow=null;
						this.store.reload();
					}
				},{
					iconCls:'icon-delete',
					text:LANG_delete + ' ' + LANG_channel,
					scope:this,
					handler:function() {
						this.store.baseParams.deleteChannel = this.ctxRecord.data.channel_id;
						this.store.reload();
						delete this.store.baseParams.deleteChannel;
					}
			   }]
			});
			
			this.menu.on("hide",this.onContextHide,this);
		}
		C.stopEvent();
		
		if (this.ctxRow) {
			Ext.fly(this.ctxRow).removeClass("x-node-ctx");
		   	this.ctxRow=null;
	   	}
			
		this.ctxRow=this.view.getRow(A);
		this.ctxRecord=this.store.getAt(A);
		Ext.fly(this.ctxRow).addClass("x-node-ctx");
		this.menu.showAt(C.getXY());
    },
	onContextHide:function(){
		if(this.ctxRow){
			Ext.fly(this.ctxRow).removeClass("x-node-ctx");
			this.ctxRow=null;
		}
	},
	
	applyRowClass:function(A,D,C,B){
		if (this.showPreview){
			C.body='<p class="description">'+A.data.description+"</p>";
			return"x-grid3-row-expanded";
		} return "x-grid3-row-collapsed";
	},
	
	formatDate:function(B){ 
		if(!B){return"";}
		var A=new Date();
		var D=A.clearTime(true);
		var C=B.clearTime(true).getTime();
		if(C==D.getTime()){ 
			return LANG_today +' '+B.dateFormat("g:i a");
		}
		D=D.add("d",-6);
			if(D.getTime()<=C){
				return B.dateFormat("D g:i a");
			}
			return B.dateFormat("n/j g:i a");
	},
	formatTitle:function(B,C,A){
		return'<div class="topic"><b>'+B+"</b></div>";
	}
});
