/**
 * Key Note report listing
 * 
 * @author Ollie Maitland
 * @copyright Byng Systems LLP
 */
Byng.register('kn.reports', 
{	
	Implements : ByngView,
	
	meta : {
		'file' 	  : 'kn.reports.js',
		'gateway' : {'package' : 'site', 'module' : 'browser'} 
	},
	
	options : {
		'grouping' : {
			'target' : 'title'
		}
	},
	
	/**
	 * Load the report listing screen with events
	 * 
	 */
	initialize : function ()
	{
		switch (this.getProperty('view')) {
			case "list":
				
				// report listing
				
				// interate: all the report listing tables on the page
				($$('.kn-report_list') || []).each(function(table) {
					var sortable = (this.getProperty('sortable') || true);
					this.attachToReportList(table, {'grouping' 	: this.options.grouping,
													'onGroup'	: function (e) {	
															// attach tips
															var tips = $$('.expand');
															tips.each(function(tip) {
																var tipsy = new Element ('div').setStyle('display','block');
																tip.store('tip:title', '');
																tip.store('tip:text', '<strong>Click to Show/Hide Group</strong>');																
															});
															var groupTip = new Tips(tips, {																
															});
													},
													'sortOn' 	: -1, 
													'sortBy' 	: 'ASC',
													'sortable' 	: sortable});
				}.bind(this));
				
				$$('.kn-report_list .toc').addEvent('click', this.open.bindWithEvent(this, ['toc']));
				
				// condition: table to be grouped
				if (this.getProperty('grouped')) {
					var groupedOn = this.getProperty('grouped');
					this.table.options.grouping.axis = groupedOn;
					this.table.group(groupedOn);			
				};
				
			break;
			case "preview":
				this.attachReportControls($('kn-report'));
				this.expandViewport( document.getElement('.kn-report_container iframe') );
				this.options.product = this.getProperty('product');
			break;
			case "search":
				this.attachSearchControls($('kn-advanced_search'));
			break;
			case 'activity':
				this.attachActivityControls();
			break;	
			
		}
	},
	
	/**
	 * Expand the iframe viewport to show the whole report
	 * 
	 * @param {Object} iframe
	 */
	expandViewport : function ( iframe )
	{
		if (!iframe) return;
		iframe.addEvent('load', function () {
			
			var resize = function () {
				try {
					if (Browser.Engine.trident) {
						var height = iframe.contentWindow.document.body.scrollHeight;
					} else {
						var height = iframe.contentDocument.height;
					}
					// only expand the viewport!
					if ( height > iframe.getHeight()) {
						iframe.setStyle('height', height + 50);
						resize.delay(50);
					}
				} catch (e) {
				}
			};
			
			resize.run();
		});
	},

	/**
	 * 
	 * The obvious
	 */
	attachActivityControls : function()
	{
		var Cal = new Calendar({ dateTo: 'Y-m-d' }, { classes: ['calendar'] });
		var Cal2 = new Calendar({ dateFrom: 'Y-m-d' }, { classes: ['calendar'] });
	},
	
	/**
	 * 
	 * @param {Object} form
	 */
	attachSearchControls : function ( form )
	{		
		form.addEvent('submit', function(e) {
			if (e) e.stop();
			
			// condition: no pod for these reports
			if (!this.pod) {
				this.pod = Byng.app.addPod(form.getParent('.kn-center_pod'), {
					'content': Byng.app.tmpl.loading
				});
			} else {
				this.pod.setStyle('display', 'block')
							.getElement('.kn-pod_content')
							.set('html', Byng.app.tmpl.loading);
			}
			
			// clear the default values
			form.getElements('input.text').fireEvent('focus');
			
			// get the pod HTML
			Byng.transit.post({
					'request'	: this.getRequest().setModule('report_search').setAction('get_results'),
					'form' 		: form,
					'target'	: this.pod.getElement('.kn-center_pod_body'),
					'onComplete': this.loadResults.bind(this)
			});
			
		}.bind(this));
		
		// popup a calendar on focus
		form.getElements('input.month').addEvent('focus', function(e) {
				Byng.init('kn.calendar', {
					'input': this
				});
		}).addEvent('blur', function(e) {
			this.set('hasFocus', false);
			if (this.retrieve('calendar')) {
				this.retrieve('calendar').fireEvent('blur');
			}
		});
		
		// set the default values
		form.getElements('input.text').addEvent('focus', function(e) {
			var defaultValue = this.retrieve('defaultValue');
			var currentValue = this.get('value');
			if (!defaultValue) {
				this.store('defaultValue', currentValue);
				this.set('value', '');
			} else if (currentValue == defaultValue || currentValue == '') {
				this.set('value', '');
			} else {
				return;
			}
		}).addEvent('blur', function() {
			var defaultValue = this.retrieve('defaultValue');
			if (this.get('value') == '' && defaultValue) this.set('value', defaultValue);
			else return;
		});
		
		// toggle the inputs for select options
		form.getElements('a.toggle_select').addEvent('click', function (e) {
			e.stop();
			var target = this.normalise(e);
			
			var input = $('search_' + target);

			// condition: is there already a request pending
			if (input.retrieve('inProgress') == true) {
				return;
			} else {
				input.store('inProgress', true);
			}		
			
			// condition: input hidden
			if (input.getStyle('display') == 'none') {
				// display input back and revert the select
				var select = input.retrieve('select');
				select.setStyle('display', 'none');
				input.setStyle('display', 'inline');
				input.store('inProgress', false);
			} else {
			
				// get the pod HTML
				Byng.transit.post({
					'request': this.getRequest().setModule('report_search').setAction('get_select_options'),
					'onComplete': this.toggleSelect.bindWithEvent(this, target)
				}, {
					'target': target
				});
			}
		}.bind(this));
		
		// load if a hash is present
		var request = new ByngRequest();
		if (request.hasHash()) {
			request.fromHash()
			new Hash(request.vars).each(function(v,k) {
				var input = $('search_' + k);
				input.store('defaultValue', input.get('value'));
				input.set('value', v);
			});
			form.fireEvent('submit')
		}		
	},
	
	/**
	 * Toggle the <input /> to <select /> for drop-down selection
	 * 
	 * @param {Object} xml
	 * @param {Object} target
	 */
	toggleSelect : function ( xml, target )
	{
		var resp = Byng.init('byng.ajax.xml', xml);
		var input = $('search_' + target);
			input.store('inProgress', false);
			
		var select = new Element('select', {	'id' 	: 'search_'+ target +'_select',
												'name' 	: 'search['+ target +']'});
		input.store('select', select);
				
		var i = 0;
		select.options[i] = new Option('-- Any '+ target +' --', i++);		
		resp.getParam('titles').each(function(v,k) {
			select.options[i] = new Option(v, v);
			i++;
		});
		
		input.setStyle('display', 'none').getParent('div').adopt(select);
	},
	
	/**
	 * Load the report search results
	 * 
	 * @param {Object} xml
	 */
	loadResults : function(xml) 
	{
		var resp = Byng.init('byng.ajax.xml', xml);
		
		if (resp.getCode() == 0) {
			this.pod.setStyle('display', 'none')
						.getElement('.kn-pod_content')
						.set('html', Byng.app.tmpl.loading);
			alert (resp.getErrors().join("\n"));
			return;
		}
		
		var html = resp.getChildContent('content');
		var slider = this.pod.retrieve('slide');
		slider.toggle().chain(function(html) {
			
			// replace the HTML		
			this.pod.getElement('.kn-pod_content').set('html', html);	
			this.pod.getElement('.kn-pod_content').getParent().setStyle('overflow', 'auto');
			Byng.app.fireEvent('popup', [this.pod]);
			this.attachToReportList(this.pod.getElement('table.listing'), {'sortable' : false});
			this.table.options.grouping.axis = 0;
			this.table.group( 0 );
			slider.toggle();
			
		}.bind(this, [html]));		
		
		if (!$('resultText')) {			
			var feedback = new Element('p', {
				'html': 'Please see below for your results',
				'id':'resultText',
				'styles': {
					'width':'537px',
					'margin-bottom':'0',
					'background':'#efefef',
					'line-height':'29px'
				}
			}).inject($('kn-advanced_search'), 'top' );
		};		

	},
	
	/**
	 * Attach the sortable options to a report list
	 * 
	 * @param {Object} table
	 * @param {Object} options
	 */
	attachToReportList : function ( table, options )
	{
		options = options || {};
		if (!table) return;
		this.table = Byng.init('byng.table.sort', table, { 	'groupable' : true, 'grouping' : {'axis' : null}, 
															'onGroup' 	: options.onGroup, 
															'sortOn' 	: options.sortOn, 
															'sortBy' 	: options.sortBy, 
															'sortable' 	: options.sortable });

		this.table.elements.addEvent('mouseover', function() { this.addClass('highlight'); });
		this.table.elements.addEvent('mouseout', function() { this.removeClass('highlight'); });
	
		table.getElements('a.kn-st_list').addEvent('click', this.toggleFromShortlist.bind(this));
	},
	
	/**
	 * Attach control to a single report view
	 * 
	 * @param {Object} el
	 */
	attachReportControls : function ( el )
	{
		// attach behaviour to these buttons, which may or may not be present on the page
		this.attachButtonControls( el );
		
		var metaContent = el.getElement('.kn-report_meta');
		var slider = new Fx.Slide(metaContent);
	
		// attach the behaviour for sliding out "more info"
		var metaContainer = metaContent.getParent()
			.addClass('kn_report-meta-container')
			.setStyles({
				'width' : 400,
				'margin-left' : '5px'
			});

		this.options.metaContent = metaContent.store("slide", slider.hide()).removeClass('hide');
		
		el.getElement('.kn-report_meta_toggle a').addEvent('click', function (e) {
			var status = this.options.metaContent.retrieve("slide").toggle().open;
			e.target.set('text', (status ? 'More info': 'Less info'));
		}.bind(this));
	},
	
	/**
	 * Attach button controls
	 * 
	 * @param {Object} el
	 */
	attachButtonControls : function ( el )
	{
		try {
			el.getElement('.kn-report_control .purchase a').addEvent('click', this.purchase.bind(this));
		} catch (e) {}
				
		try {
			el.getElement('.kn-report_control .summary a').addEvent('click', this.open.bindWithEvent(this, ['summary']));
		} catch (e) {}
		
		try {
			el.getElement('.kn-report_control .toc a').addEvent('click', this.open.bindWithEvent(this, ['toc']));
		} catch (e) {}
	},
	
	/**
	 * Purchase a report
	 * 
	 * @param {Object} e
	 */
	purchase : function ( e )
	{
			
	},
	
	/**
	 * Open a report view screen in a lightbox
	 * 
	 * @param {Object} e
	 * @param {Object} screen
	 */
	open : function ( e, screen )
	{
		e.stop();
		var product = this.normalise(e.target, 'product');
		if (!product) product = this.options.product;
		else this.options.product = product;
		Byng.app.open(e, {	'request' : this.getRequest(screen).addParam('product', product),
							'onUpdate' : function ( el ) { 
								this.attachButtonControls( el );
							}.bind(this)});
	},
	
	/**
	 * Toggle an option in a shortlist
	 * 
	 * @param {Object} e
	 */
	toggleFromShortlist : function ( e )
	{
		e.stop();
		var anchor = ($(e.target).get('tag') != 'a' ? $(e.target).getParent('a') : $(e.target));
		var productId = this.normalise($(e.target).getParent('tr'), 'productId');
		Byng.transit.post({	'request' : this.getRequest().setAction('toggle_shortlist').addParam('productId', productId),
							'onSuccess' : function( xml ) {
								var resp = Byng.init('byng.ajax.xml', xml);
								if(parseInt(xml.getParam('state')) == 1) {
									anchor.addClass('kn-st_list_active').setProperty('title', 'Remove from Shortlist');
								} else {
									anchor.removeClass('kn-st_list_active').setProperty('title', 'Add to Shortlist');
								}
							}});
	}
	
});

window.addEvent('domready', function()
{
	Byng.app.reports = Byng.init('kn.reports');
});
