/**
 * Home Page Component Javascript
 */

document.observe('dom:loaded', function() 
{
	AS4Home.getInstance().flashDetect();
});

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

var AS4Home = Class.create({
	
	/**
	 * @type AS4PortalPage instance of a portal page controller
	 */
	portalPage: null,
	
	/**
	 * @type {Array} Array of statically loaded channels
	 */
	channels: null,
	// flash detect variables

	// Major version of Flash required
	requiredMajorVersion: 9,
	// Minor version of Flash required
	requiredMinorVersion: 0,
	// Minor revision of Flash required
	requiredRevision: 0,	
	
	// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
	
	/**
	 * @constructor
	 */	
	initialize: function()
	{
		this.portalPage = new AS4PortalPage();
		this.portalPage.onPanelDropped = function(container)
		{
			container = $(container);

			if (container.select('.panel').length == 0 && !container.hasClassName('blank_column')) 
				container.addClassName('blank_column');
			else 
				container.removeClassName('blank_column');

			AS4Home.getInstance().saveLayout();
		};
	},
	
	// # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
	// Interface methods

	/**
	 * Method triggered by the user clicking the add panel button
	 */	
	addPanel: function()
	{
		var params = {
			callback: this.onAddPanel.bind(this),
			width: 400,
			height: 380
		};
		
		AS4Shell.getInstance().showLightbox(params); 
	},
	
	/**
	 * Method to display the add external feed form inside the lightbox content
	 * @return {void}
	 */
	showExternalFeedForm: function()
	{
		if(!$('add_panel_form'))
			return;
			
		var url = '/home/add_panel_external_form';

		var params = {
			renderMode: 'update'
		};
		
		AS4Shell.getInstance().ajaxUpdate(url, params, 'add_panel_form', $A(), {showIndicator: false});
		
		$('add_panel_form').update('<div id="add_panel_container">' +
									'<div class="centre" style="padding-top: 40%">' +
										'<img src="/app/common/assets/images/ajax-loader.gif" alt="Loading..>" width="24" height="24" /><br />Loading...' +
									'</div>' +
								'</div>');
	},
	
	/**
	 * Method to display the add external feed form inside the lightbox content
	 * @return {void}
	 */
	showControlsForm: function()
	{
		if(!$('add_panel_form'))
			return;
			
		var url = '/home/add_panel_controls';

		var params = {
			renderMode: 'update'
		};
		
		AS4Shell.getInstance().ajaxUpdate(url, params, 'add_panel_form', $A(), {showIndicator: false});
		
		$('add_panel_form').update('<div id="add_panel_container">' +
									'<div class="centre" style="padding-top: 40%">' +
										'<img src="/app/common/assets/images/ajax-loader.gif" alt="Loading..>" width="24" height="24" /><br />Loading...' +
									'</div>' +
								'</div>');
	},
	
	// # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
	// AJAX Callback methods
	
	/**
	 * Callback method to load the add panel content into the shell lightbox
	 * @return string
	 */
	onAddPanel: function()
	{
		var url = '/home/add_panel_lightbox/mode/channels';

		var params = {
			renderMode: 'lightbox',
			mode: 'channels'
		};
		
		AS4Shell.getInstance().ajaxUpdate(url, params, 'add_panel_container', $A(), {showIndicator: false});
		
		return	'<div id="add_panel_container">' +
					'<div class="centre" style="padding-top: 40%">' +
						'<img src="/app/common/assets/images/ajax-loader.gif" alt="Loading..>" width="24" height="24" /><br />Loading...' +
					'</div>' +
				'</div>';
	},
	
	onSaveLayoutComplete: function(transport, target)
	{
		// Pass
	},
	
	// # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
	// Portal Page methods
	
	saveLayout: function() 
	{
		// We can only save the layout if we are authenticated!
		if(!AS4Shell.getInstance().authenticated)
			return;

		var url = '/home/save_layout';
		
		var params = {
			schema: this.portalPage.serialize()
		};
		
		AS4Shell.getInstance().ajaxUpdate(url, params, null, $A([this.onSaveLayoutComplete.bind(this)]), {message: 'Saving Layout...', method: 'post'});
	},

	/**
	 * Update and rebuild the dynamic iGoogly homepage
	 *
	 * @param {String} [schema] Optional JSON-encoded schema to use. If this is not set, the schema will be loaded from the database via an AJAX call
	 */
	rebuild: function(schema)
	{
		// Eval the schema JSON
		var schema = eval(schema);
		
		var columnIds = $A(['tertiary_column', 'secondary_column', 'primary_column']);
		var count = 0;

		// Parse JSON schema and rebuild homepage
		$H(schema).each(function(pair){
			var column = pair[0];
			
			$A(pair[1]).each(function(panel) {
				switch(panel.type)
				{
					case 'feed':
						this.createPanel(AS4PortalPanel.FEED_PANEL, panel.title, panel.options, $(column));
						break;
				
					case 'navigation':
						this.createPanel(AS4PortalPanel.NAVIGATION_PANEL, panel.title, panel.options, $(column));
						break;
						
					case 'control':
						this.createPanel(AS4PortalPanel.CONTROL_PANEL, panel.title, panel.options, $(column));
						break;
						
					case 'ulearn':
						this.createPanel(AS4PortalPanel.ULEARN_PANEL, panel.title, panel.options, $(column));
						break;
						
					default:
						this.createPanel(AS4PortalPanel.STATIC_PANEL, panel.title, panel.options, $(column));
						break;
				};
			}.bind(this));
			
			// Move to next column
			count++;
		}.bind(this));
	},

	/**
	 * Sets the static-loaded list of channels to negate the need for AJAX requests
	 * @param {string} json JSON-encoded array of channels
	 */
	setChannels: function(json)
	{
		this.channels = eval(json);
	},

	/**
	 * An event method triggered from the lightbox to add a selection of checked
	 * channel ids to the panel as new feed panels
	 */
	addSelectedChannelsAsPanels: function()
	{
		$('channels_list').select('input').each(function(element){
			var id = $(element).id.split('_')[1];	// channel_id_url
			var url = $(element).id.split('_')[2];
			
			if($(element).checked)
				this.createPanel(AS4PortalPanel.FEED_PANEL, $F(element), {uri: '/' + url + '?rss=true', items: 5}, $('tertiary_column')); 
		}.bind(this));
		
	},
	
	/**
	 * An event method triggered from the lightbox to add a selection of checked
	 * feed URLS to the panel as new feed panels
	 */
	addSelectedFeedsAsPanels: function()
	{
		// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
		// Add the custom feed URL if set
		if($F('feed_url'))
			this.createPanel(AS4PortalPanel.FEED_PANEL, $F('feed_url'), {uri: 'http://' + $F('feed_url').replace('http://', ''), items: 5}, $('tertiary_column'));
		
		// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
		// Add any checked preset external feeds
		$('feeds_list').select('input').each(function(element){
			var title = $(element).id.split('_')[1]; // channel title 
			var url = $F(element); // URL
			
			if($(element).checked)
				this.createPanel(AS4PortalPanel.FEED_PANEL, title, {uri: url, items: 5}, $('tertiary_column')); 
		}.bind(this));
	},
	
	/**
	 * An event method triggered from the lightbox to add a selection of checked
	 * control panels to the panel as new panels
	 */
	addSelectedControlPanels: function()
	{
		// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
		// Add any checked preset external feeds
		$('controls_list').select('input').each(function(element){
			if ($(element).checked) 
			{
				switch ($(element).id) {
					case 'navigation_panel':
						this.createPanel(AS4PortalPanel.NAVIGATION_PANEL, 'Channels', {}, $('secondary_column'));			
						break;
						
					case 'members_panel':
						this.createPanel(AS4PortalPanel.CONTROL_PANEL, 'Members', {}, $('secondary_column'));
						break;
						
					default:
						break;
				}
			} 
		}.bind(this));
	},
	
	/**
	 * Check to see if flash is available
	 */
	flashDetect: function()
	{
		// Version check based upon the values entered above in "Globals"
		var hasRequestedVersion = DetectFlashVer(this.requiredMajorVersion, this.requiredMinorVersion, this.requiredRevision);

		// Check to see if the version meets the requirements for playback
		if (!hasRequestedVersion) {	
				var params = {
				callback: this.onFlashDetect.bind(),
				width: 400,
				height: 375
			};
			
			AS4Shell.getInstance().showLightbox(params); 

		}	

	},
	
	/**
	 * Callback method to load the add panel content into the shell lightbox
	 * @return string
	 */
	onFlashDetect: function()
	{
		var url = '/home/system_check_lightbox';

		var params = {
			renderMode: 'lightbox'
		};
		
		AS4Shell.getInstance().ajaxUpdate(url, params, 'system_requirements_container', $A(), {showIndicator: false});
		
		return	'<div id="system_requirements_container">' +
					'<div class="centre" style="padding-top: 40%">' +
						'<img src="/app/common/assets/images/ajax-loader.gif" alt="Loading..>" width="24" height="24" /><br />Loading...' +
					'</div>' +
				'</div>';
		
	},	
	/**
	 * Create a new instance of a panel and insert it into the current portal page
	 *
	 * @param {String} panelType The type of panel to create. See static properties of AS4PortalPanel.js
	 * @param {String} title Displayed title of the new panel
	 * @param {Object} options Array of custom options for the panel, e.g. feed_url
	 * @param {Element} column Element into which the panel will be placed
	 * @return void
	 */
	createPanel: function(panelType, title, options, column) 
	{
		var panel;
		switch(panelType)
		{
			case AS4PortalPanel.NAVIGATION_PANEL:
				// Do we have an array of static channels? If so, use those to populate the channels panel (3rd parameter)
				// and remove the need for an AJAX request
				panel = new AS4ChannelPortalPanel(title, options, this.channels);
				break;
			
			case AS4PortalPanel.CONTROL_PANEL:
				panel = new AS4ControlPortalPanel(title, options);
				break;
				
			case AS4PortalPanel.FEED_PANEL:
				panel = new AS4FeedPortalPanel(title, options);
				panel.onChangeItemCount = function() {
					AS4Home.getInstance().saveLayout();
				};
				break;
			
			case AS4PortalPanel.ULEARN_PANEL:
				panel = new AS4UlearnPortalPanel(title, options);
				break;
			
			default:
				panel = new AS4PortalPanel(title, options);
				break;
		}

		panel.onClose = function()
		{
			AS4Home.getInstance().saveLayout();
		};

		// Build the DIV element
		var uuid = panel.generateUniqueId(); 

		var html = '<div class="panel">' + 
					'<!-- header -->' + 
					'<div class="header">' + 
					'<div class="top">' + 
					'<span class="left">' + 
					'<div class="break"></div>' + 
					'</span>' + 
					'<span class="right">' + 
					'<div class="break"></div>' + 
					'</span>' + 
					'</div>' +
					'<div class="title">' +
					'<div class="backing">' +
					'<div class="controls">' + 
					panel.getControlStripHTML(uuid) + 
					'</div>' + 
					'<h4>' + title + '</h4>' + 
					'</div>' + 
					'</div>' + 
					'</div>' +
					'<div class="main">' + 
					'<div class="content_wrapper">' + 
					'<div class="content">' + 
					'<p></p>' + 
					'</div>' + 
					'</div>' + 
					'<div class="bottom">' + 
					'<span class="left">' + 
					'<div></div></span>' +
					'<span class="right"><div></div></span>' + 
					'</div>' + 
					'</div>' + 
					'</div>';

		// Join the panel with the display element
		element = Builder.build(html);
		element.id = uuid;
		
		panel.element = $(element);
		element.controller = panel;
		 
		// Append the panel to the homepage
		this.portalPage.appendPanel(panel, column);
		
		// Trigger an update to the panel
		loader = function() {panel.reload();};
		
		loader.defer();
	}
});

// # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
// Static methods/properties

AS4Home.instance = null;


/**
 * Return a static instance of the AS4Home controller
 */
AS4Home.getInstance = function()
{  
	if(!AS4Home.instance)
		AS4Home.instance = new AS4Home();
		
	return AS4Home.instance;
}
