/*  © Copyright 2001 - 2006 Excira Technologies, Inc. All Rights Reserved.
 * -----------------------------------------------------------------------
 *
 */

Excira.Forum = function() {

	var path;
	var topicsStore;
	var topicStore;
	var forumId;
	var topicId;
	
	
	/**
	 * Public interface
	 */
	return {

		/**
		 *
		 */
		init : function(forumId, path) {
		
			Excira.Forum.forumId = forumId;
			Excira.Forum.path = "/" + path;

		 	// Get the title and text of request doc
			Ext.Ajax.request({
				url:"/getForumText.ajax",
				params:{ "forumId": Excira.Forum.forumId },
				success: function(response, action) {
				
					var obj = Ext.util.JSON.decode(response.responseText);
					
					// First get the initial form text
					var forumTextEl = Ext.get("forumText");
					if ( !forumTextEl )
						Ext.DomHelper.append("forum", {tag:"div", id:"forumText"});
						
					var header = new Ext.Panel({
						autoWidth:true,
						border:false,
						items:[{
							border:false,
							html:"<div style=\"background-color:#efefef !important\">Forum: " + obj.title + "</div>",
							width:"50%"
						},{
							border:false,
							html:"<div id=\"allTopics\" onclick=\"window.location.href = Excira.Forum.path\" class=\"link\" style=\"background-color:#efefef !important\">All Topics</div>",
							style:"text-align:right",
							width:"50%"
						}],
						layout:"column"
					});
					
					Ext.DomHelper.append("forumText", {tag:"div", cls:"forumHeader", id:"forumHeader"});
					header.render("forumHeader");						
						
					Ext.DomHelper.append("forumText", {tag:"p", html:obj.text});
					
					// Now display the topics
					Excira.Forum.updateTopicList();
				}
			});			
		},
		
		/**
		 *
		 */
		createTopic : function(btn) {
		
			Ext.QuickTips.init();
			Ext.QuickTips.enable();
			Ext.form.Field.prototype.msgTarget = 'side';
		
			var form = new Ext.FormPanel({
				
				bodyStyle:"padding:10px 10px 10px",	
				buttonAlign:"right",							
				defaults: {width: 230},
				items: [{
							xtype:"textfield",
							allowBlank:false,
					        fieldLabel:"title",
					        name:"title",
							validationEvent:false
				   		},
				   		{
							xtype:"textarea",
							allowBlank:false,
					        fieldLabel:"Text",
					        name:"text",
							validationEvent:false
				}],								
				labelWidth: 110, 
				frame:false,
				width:400	
			});
			
			// Create dialog div for popup if it does
			// not yet exist
			var dialogEl = Ext.get("dialog");
			if ( !dialogEl )
				Ext.DomHelper.append("body", {tag:"div", id:"dialog"});
		
			// Create window and add form
			var dialog = new Ext.Window({
				height:200,
				autoScroll:true,
				buttons:[{
					text:"Submit",
					handler:function() {
	
						form.getForm().submit({
							url:"/createTopic.ajax",
							params:{
								"forumId":Excira.Forum.forumId
							},
							success:function(result, action) {
								
								dialog.hide();
								dialog.destroy();
	
								Excira.Forum.updateTopicList();
							}							
						});				
					}
				}],
				closable:true,
				el:"dialog",
				hideBorder:true,
				keys:[
				{
					key:27,
					fn:function() {
						dialog.hide();
						dialog.destroy();						
					}
				}
				],
				items:form,
				layout:"fit",
				modal:true,
				resizable:false,
				shadow:true,
				title:"Create Topic",
				width:400
			});

			// Render form
			dialog.show(btn);				
		},
		
		/**
		 *
		 */
		updateTopicList : function() {
		
			Excira.Forum.topicsStore = new Ext.data.JsonStore({
				url:"/listTopics.ajax",
				root:"topics",
				fields:[
					{name: "id", mapping:"id"},
				    {name: "title", mapping:"title"}, 
				    {name: "text", mapping:"text"}
				],
				listeners: {
					loadexception: function(store, response, e) {
						console.log("Topics Error: " + e.message);
					}
				}
			});
			
			Excira.Forum.topicsStore.on("load", function() {
				console.log("Topics store loaded....");
				console.log("Topics Store: " + Excira.Forum.topicsStore.getCount());
			});		

			Excira.Forum.topicsStore.load({
				params:{
					"forumId":Excira.Forum.forumId
				},
				callback:function() {
				
					Excira.Forum.createForumBody();
					
					var allTopicsEl = Ext.get("allTopics");
					allTopicsEl.hide();					
					
					var header = new Ext.Panel({
						autoWidth:true,
						border:false,
						items:[{
							border:false,
							html:"<div style=\"background-color:#efefef !important\">Topics</div>",
							width:"50%"
						},{
							border:false,
							html:"<div onclick=\"Excira.Forum.createTopic(this)\" class=\"link\" style=\"background-color:#efefef !important\">Create Topic</div>",
							style:"text-align:right",
							width:"50%"
						}],
						layout:"column"
					});
					
					Ext.DomHelper.append("forumBody", {tag:"div", cls:"forumHeader", id:"topicTitle"});
					header.render("topicTitle");
					
					// Create panel
					var panel = new Ext.Panel({
						autoHeight:true,
						autoWidth:true,
						border:false,
						layout:"fit",
						emptyText:"No topics",
						items:new Ext.DataView({
							store:Excira.Forum.topicsStore,
							tpl:new Ext.XTemplate(
								'<tpl for=".">', 
								'<div class="topic">',
									'<span onclick="Excira.Forum.showTopic(\'{id}\')" class="link">{title}</span>',
								'<p>{text}</p>',
								'</div>',
								'</tpl>'
							),
							itemSelector:".topic"
						})
					});				
					
					console.log("Rendering list....");
					
					// Render topic list!
					panel.render("forumBody");
				}
			});
		},
		
		/**
		 *
		 */
		showTopic : function(topicId) {
		
			Excira.Forum.topicId = topicId;
		
			// Setup the store
			Excira.Forum.topicStore = new Ext.data.JsonStore({
				url:"/getTopic.ajax",
				root:"topic",
				fields:[
					{name: "id", mapping:"id"},
				    {name: "title", mapping:"title"}, 
				    {name: "text", mapping:"text"},
				    {name: "responses", mapping:"responses"}
				],
				listeners: {
					loadexception: function(store, response, e) {
						console.log("Topics Error: " + e.message);
					}
				}
			});

			Excira.Forum.topicStore.load({
				params:{
					"topicId":Excira.Forum.topicId
				},
				callback:function() {
				
					var allTopicsEl = Ext.get("allTopics");
					allTopicsEl.setVisible("true");				
				
					Excira.Forum.createForumBody();

					// Create panel
					var panel = new Ext.Panel({
						autoHeight:true,
						autoWidth:true,
						border:false,
						layout:"fit",
						emptyText:"No topics",
						items:new Ext.DataView({
							store:Excira.Forum.topicStore,
							tpl:new Ext.XTemplate(
								'<tpl for=".">', 
								'<div class="topicTitle">',
									'Topic: {title}',
								'</div>',
								'<div class="topicText" id="topicTitle">{text}</div>',
								'<tpl if="!this.isEmpty(responses)">',
									'<tpl for="responses">',
										'<tpl if="xindex == 1">',
											'<div class="topicTitle">',
												'Responses',
											'</div>',
										'</tpl>',
										'<div class="response">',
											'{title}',
											'<p>{text}</p>',										
										'</div>',
										'</tpl>',
									'</tpl>',
								'</tpl>', {
								
									isEmpty : function(responses) {
										
										return (!responses || responses.length == 0);
									}
								}
							),
							itemSelector:".topic"
						})
					});				
					
					// Render topic list!
					panel.render("forumBody");
					
					Ext.DomHelper.append("topicTitle", {tag:"div", html:"Create Response", cls:"linkRight", id:"createResponse"});
					var createResponseEl = Ext.get("createResponse");
					createResponseEl.on("click", function() {	
						
						Excira.Forum.createResponse(createResponseEl.dom);
					});
				}
			});	
		},
		
		/**
		 *
		 */
		createResponse : function(btn) {
		
			Ext.QuickTips.init();
			Ext.QuickTips.enable();
			Ext.form.Field.prototype.msgTarget = 'side';
		
			var form = new Ext.FormPanel({
				
				bodyStyle:"padding:10px 10px 10px",	
				buttonAlign:"right",							
				defaults: {width: 230},
				items: [{
							xtype:"textfield",
							allowBlank:false,
					        fieldLabel:"title",
					        name:"title",
							validationEvent:false
				   		},
				   		{
							xtype:"textarea",
							allowBlank:false,
					        fieldLabel:"Text",
					        name:"text",
							validationEvent:false
				}],								
				labelWidth: 110, 
				frame:false,
				width:400	
			});
			
			// Create dialog div for popup if it does
			// not yet exist
			var dialogEl = Ext.get("dialog");
			if ( !dialogEl )
				Ext.DomHelper.append("body", {tag:"div", id:"dialog"});
		
			// Create window and add form
			var dialog = new Ext.Window({
				height:200,
				autoScroll:true,
				buttons:[{
					text:"Submit",
					handler:function() {
	
						form.getForm().submit({
							url:"/createResponse.ajax",
							params:{
								"topicId":Excira.Forum.topicId
							},
							success:function(result, action) {
								
								dialog.hide();
								dialog.destroy();
	
								Excira.Forum.showTopic(Excira.Forum.topicId);
							}							
						});				
					}
				}],
				closable:true,
				el:"dialog",
				hideBorder:true,
				keys:[
				{
					key:27,
					fn:function() {
						dialog.hide();
						dialog.destroy();						
					}
				}
				],
				items:form,
				layout:"fit",
				modal:true,
				resizable:false,
				shadow:true,
				title:"Create Response",
				width:400
			});

			// Render form
			dialog.show(btn);			
		},
		
		/**
		 *
		 */
		createForumBody : function() {
		
			var forumBody = Ext.get("forumBody");
			if ( forumBody )
				forumBody.remove();
				
			Ext.DomHelper.append("forum", {tag:"div", id:"forumBody"});
		}
	}; 
}();	