/**
 * Key Note web application
 * 
 * Presents the JavaScript framework for the Key Note application
 * 
 * @author Ollie Maitland
 * @copyright Byng Systems LLP
 */

var Kn = {}

Kn.app = new Class(
{
	Implements : [ByngApp],
	
	/**
	 * Holds meta data on this application
	 * 
	 */
	meta	: {
		'name'	    : 'Key Note',
		'version'   : '0.1.0',
		'author'    : 'ollie@byng-systems.com',
		'copyright' : 'Byng Systems LLP',
		'date'  	: '2009-03-20'
	},
	
	icons : {
		'loader' : '/html/images/indicators/loader_small.gif'
	},
	
	tmpl : {
		loading : '<div class="kn-pod_loading"><span>Loading...</span></div>',
		container : '<div class="kn-center_pod_top"><!-- --></div><div class="kn-center_pod_body">'
						+ '<div class="kn-pod_content">{content}</div>'
						+ '</div><div class="kn-center_pod_bottom"><!-- --></div>'
			
	},
	
	/**
	 * Initialise application
	 * 
	 */
	initialize : function ()
	{
		
		this.addEvent('load', function() {
			var search = $('kn-search');
			if ($type(search) == 'element') {
				
				if (window.location.hash == '#fayt') {
					this.search = Byng.init('kn.search.reports', {
						minLength: 5
					});
				}
				
				// event: validate search form submission
				search.addEvent('submit', function (e) {
					var input = $(e.target).getElement('input');
					if (input.get('value').length < 3) {
						e.stop();
						alert ("Please enter a word with at least three characters");
						input.focus();
					} else {
						Byng.ui.dom.showLoader($(e.target));
					}
					input.form.submit();
				});
				
				// cache loading icon
				var img = new Element('img', {'src' : this.icons.loader});
								
				// event: submit icon is clicked
				search.getElement('.kn-sm_submit').addEvent('click', function(e) {
					e.stop();
					e.target = search
					search.fireEvent('submit', [e]);
				}.bind(this));
			}
			this.loadEnvironment();
		});
	},
	
	loadEnvironment : function ()
	{	

		if ($('flashtag')) {
			swfobject.embedSWF("/html/flash/kn_flow_chart.swf", "flashtag", "585", "707", "9.0.0", "/html/flash/KN_flow_chart.swf");
		}

		if ($('flashhelp')) {
			swfobject.embedSWF("/html/flash/kn_slides.swf", "flashhelp", "594", "720", "9.0.0", "/html/flash/kn_slides.swf");
		}

		if ($('flashcorporate')) {
			swfobject.embedSWF("/html/flash/kn_slides_corporate.swf", "flashcorporate", "594", "720", "9.0.0", "/html/flash/kn_slides_corporate.swf");
		}
		
		// load any slide shows
		var slides = $$('.kn-slides');
		if (slides.length >  0) {
			slides.each(function(slide) {
				Byng.init('kn.slideshow', {'container' : slide});
			});
		}
		
		// load any scrollable panes
		var panes = $$('.kn-panes');
		if (panes.length > 0) {
			
			panes.each(function(pane) {
				myTabs = new SlidingTabs(document.getElement('.kn-pane_buttons'), pane);
				
				$$('.kn-pane_previous').addEvent('click', myTabs.previous.bind(myTabs));
				$$('.kn-pane_next').addEvent('click', myTabs.next.bind(myTabs));
				
				window.addEvent('resize', myTabs.recalcWidths.bind(myTabs));
			});
		}
		
		// load any scrollable panes
		var panes = $$('.kn-report_pane');
		if (panes.length > 0) {
			var navigateLink = $$('.kn-download_recent_report');

			var images = $$('.kn-gallery .imageElement');
			
			images[0].addClass('active');
			
			images.each(function(img) {
				if (img.hasClass('active') == false) {
					img.setOpacity(0);
				}
				img.setStyle('position','absolute');				
			});
			
			panes.each(function(pane, indexOf) {

				var myTabs = new SlidingTabs(document.getElement('.kn-pane_buttons'), pane);
				
				$$('.kn-pane_previous').addEvent('click', myTabs.previous.bind(myTabs));
				$$('.kn-pane_next').addEvent('click', myTabs.next.bind(myTabs));
				
				window.addEvent('resize', myTabs.recalcWidths.bind(myTabs));
				
				// on changing the link update the download report link
				myTabs.addEvent('change', function (options) {			
					var link = options.target.getElement('a.kn-product_link');
					var articleId = options.target.getAttribute('accesskey');

					if (link) {
						navigateLink.removeClass('hide')
							.removeEvents('click')
							.setProperty('href', link.getProperty('href'))
							.addEvent('click', function(e, link){
								e.stop();
								window.location.href = link.getProperty('href');
						}.bindWithEvent(null, link));
					} else {
						navigateLink.addClass('hide');
					}
					
					var destination = null;
					var from = null;					
					images.each(function(img) {					
						if (img.getAttribute('accesskey') == articleId) {
							destination = img;
						} else if (img.hasClass('active')) {
							from = img;
						} else {
							
						}
					});
					
					if (from && destination && (from != destination)) {
					
						if (destination.fx) {
							destination.fx.cancel();
						}
						if (from.fx) {
							from.fx.cancel();
						}
						
						destination.fx = new Fx.Morph(destination.addClass('active'), {duration: 1000}).start({'opacity' : 1});
						from.fx = new Fx.Morph(from.removeClass('active'), {duration: 1000}).start({'opacity' : 0});
					}
					
				});
				
				pane.store('slideFx', myTabs);
			});

			// link up the first link without the panel changing
			panes[0].retrieve('slideFx').fireEvent('change', {target : panes[0].getElement('.kn-fade_rotate')});
		}
		
		// load the navigation
		var contact = document.getElement('.kn-contact_pod');
		if ( contact ) {		
			new multipleOpenAccordion(contact.getElements('.toggler'), contact.getElements('.togglee'));
		}

		var nav = document.getElement('.nav');
		if ( nav ) {
			var togglee = nav.getElements('.togglee').setStyle('display','block');
			var toggler = nav.getElements('.toggler').setProperty('href','#nohref');			
			new multipleOpenAccordion(toggler, togglee);
			nav.getElements('.on').fireEvent('click');
		}

		// load the FAQ pages
		if ($$('.question')) {
			new multipleOpenAccordion($$('.question'),$$('.answer'));
			$$('.question .on').fireEvent('click');
		}
	
		// load the call to actions
		var callToActions = $$('.kn-call_to_action_small')
		if (callToActions.length > 0) {
			callToActions.addEvents({
				'mouseover': function(){
					this.addClass('expand').getElement('p a').setStyle('display', 'block');
				}, 'mouseout': function() {
					this.removeClass('expand').getElement('p a').setStyle('display', 'none');
				}
			});

		}
		
		// create the tooltips  
		var tips = $$('.tips').filter(function(el) {
			var title = el.getProperty('title').split("::");
			el.store('tip:title', title[0]).store('tip:text', (title[1] ? title[1] : '')); 	
			return true;
		});
		var tooltips = new Tips(tips,{  
			 className: 'kn-tips',  
			 fixed: false,  
			 hideDelay: 50,  
			 showDelay: 50
		 });

		Byng.app.addEvent('popup', function(popup) {
			this.attach(popup.getElements('.se-tool_tip'));
		}.bind(tooltips));	
	},
	
	open : function ( e, options )
	{
		SqueezeBox.fromElement(e.target.setProperty('href', options.request.composeAsString()), 
		{
			size: {x: '800', y: (window.getHeight()-100)},
			ajaxOptions: {
				method: 'get'
			},
			url: options.request.composeAsString(),
			onUpdate: (options.onUpdate ? options.onUpdate : $empty),
			onClose : (options.onClose 	? options.onClose : $empty),
			zIndex : 500
		});
	},
	
	addPod : function ( parent, contents ) 
	{
		contents = ($type(contents) == 'object' ? contents : {'content' : contents});
		var pod = new Element('div', {'class': 'kn-center_pod'})
					.set('html', this.tmpl.container.substitute(contents))
					.inject(parent, 'after');
		var body = pod.getElement('.kn-pod_content');
		return pod.store('slide', new Fx.Slide(body));
	}
});

/**
 * The worlds most compact slideshow
 * 
 * @author Ollie Maitland
 * @copyright Byng Systems LLP
 */
Byng.register('kn.slideshow', {
	
	current : 0,
	slides : [],
	fx: {},
	options : {
		duration : 10000
	},
	
	Implements : Options,
	
	/**
	 * Initialize the slideshow
	 * 
	 * @param {Object} options
	 */
	initialize : function (options)
	{
		this.setOptions(options);
		this.slides 	= this.options.container.getElements('.slide');
		if (!this.fx.slider) {
			// new slider FX
			this.fx.slider = new Fx.Slide(this.options.container, {}).slideOut().chain(function(){
				this.rotate();
			}.bind(this));
		}
	},
	
	/**
	 * Rotate the slide to the next one
	 * 
	 */
	rotate : function ()
	{
		if ((this.current + 1) < this.slides.length) {
			this.current++;
		} else {
			this.current = 0;
		}
		this.slides.addClass('hide');
		this.slides[this.current].removeClass('hide');
		this.fx.slider.slideIn();
		
		(function(){
			// slide out and then rotate
			this.fx.slider.slideOut().chain(function() {
				this.rotate();
			}.bind(this));
		}).delay(this.options.duration, this);
	}
});

/* some quirks to circumvent broken stuff in mt1.2 */
function isBody(element){
	return (/^(?:body|html)$/i).test(element.tagName);
};
Element.implement({
	getPosition: function(relative){
		if (isBody(this)) return {x: 0, y: 0};
		var el = this, position = {x: 0, y: 0};
		while (el){
			position.x += el.offsetLeft;
			position.y += el.offsetTop;
			el = el.offsetParent;
		}
		var rpos = (relative) ? $(relative).getPosition() : {x: 0, y: 0};
		return {x: position.x - rpos.x, y: position.y - rpos.y};
	}
});
	
// Set the Key Note application
Byng.setApp( new Kn.app );

// Set the input handles
Byng.setInput( Byng.init('byng.input') );

Byng.setTransit( Byng.init('byng.transit') );

// load the Byng user interface object
Byng.setUi ( Byng.init('byng.ui', UI_FLAG_AJAX) );

window.addEvent('domready', function() {
	Byng.app.fireEvent('load');
});