/**
* @fileoverview Controller for the media viewer
* @author Rebecca Murphey rebecca@rebeccamurphey.com
*/

/* required for audio player, do not remove */
var playerReady = function() {
	window.player = document.getElementById('audioPlayer');
};

var mana = {
	
	/** 
	 * colors for names
	 */
	nameColors : {
			'Jemma' : '#fff200',
			'Mana' : '#f6a9cb',
			'Bernard' : '#00acd1',
			'Chris' : '#009569', 
			'John' : '#cb3a39', 
			'Amy' : '#917ebb'
	},
		
	/** 
	 * heights based on body id
	 */
	heights : {
		'homepage' : {
			containerParent : {
				'open' : '517px',
				'closed' : '445px'
			},
			container : {
				'open' : '360px',
				'closed' : '180px'
			}
		},
		
		'default' : {
			containerParent : {
				'open' : '545px',
				'closed' : '445px'
			},
			container : {
				'open' : '360px',
				'closed' : '150px'
			}
		}
	},
	
	bar : {
		visible : false
	},
	
	/**
	* cache for html responses, by hash
	*/
	cache : {},
	
	/**
	* cache for carousel items, by hash
	*/
	items : {},
	
	/**
	* cache for selections
	*/
	el : {},
	
	/**
	* callbacks to run for matching hashes
	*/
	hashCallbacks : {
		'about' : function() { 
			mana.hideBarPrevNext(); 
			mana.hideNavBanner();
			$('.aa-about').cycle({
				    fx:     'scrollHorz',
				    speed:  300,
				    timeout: 0,
					easing: "easeInQuint",
				    next:   'a.next-about',
				    prev:   'a.prev-about'
			});
		},
		
		'services' : function() {
			mana.hideNavBanner();
		},
		
		'contact' : function() {
			mana.hideNavBanner();
		}
	},
	
	init : function() {
		/**
		 * key configuration options off body ID;
		 * for now, there are only two config options:
		 * 'homepage' or 'default'
		 */
		mana.page = $('body').attr('id') == 'homepage' ? 'homepage' : 'default';

		// cache selections for reuse
		mana.el.carousel = {};
		mana.el.bar = {};
		
		mana.el.carousel.$container = $(mana.config.carousel.container);
		
		mana.el.bar.$container = $(mana.config.bar.container);
		mana.el.bar.$prevButton = $(mana.config.bar.prevButton);
		mana.el.bar.$nextButton = $(mana.config.bar.nextButton);
		mana.el.bar.$closeButton = $(mana.config.bar.closeButton);
		mana.el.bar.$nav = $(mana.config.bar.nav);
		
		mana.el.$introbar = $('#introbar');
		mana.el.$menu = $('#globalnav .menu');
		mana.el.$navBanner = $('#nav-banner');
		
		mana.el.$content = $(mana.config.content);
		mana.el.$globalNav = $(mana.config.globalNav);
		
		mana.el.$load = $('<div id="load"/>').appendTo(mana.el.bar.$container.find('.borderwrap')).hide();
		mana.el.$overlay = $('<div id="overlay"/>').appendTo('body').css({ opacity : 0.4 }).hide();
		
		// cache carousel items by hash
		mana.el.carousel.$container.find('li').each(function() {
			var hash = mana.getHash($(this).find('a').attr('href'));
			mana.items[hash] = $(this);
		});
	
		mana.initCarousel();
		mana.hideBar();
		mana.initSubmenus();
		
		$.historyInit(mana.populateBar);
		
		$('li.history a').bind(
			'click',
			function(e) {
				e.preventDefault();
				var hash = mana.getHash($(this).attr('href'));
				$.historyLoad(hash);
				mana.hideBarPrevNext();
			}
		);
		
		mana.el.bar.$prevButton.bind('click', mana.showPrev);
		mana.el.bar.$nextButton.bind('click', mana.showNext);
		mana.el.bar.$closeButton.bind('click', function() { $.historyLoad(''); });
		
	},
	
	/**
	 * initialize submenu behavior 
	 */
	initSubmenus : function() {
		$("li#nav-licensing ul, li#nav-services ul").hide();
		
		$("li#nav-licensing")
			.hover(function() {
			 	$("li#nav-licensing ul").fadeIn(400);	
			}, function() {
				$("li#nav-licensing ul").fadeOut(150);
			});
		
		$("li#nav-services")
			.hover(function() {
				$("li#nav-services ul").fadeIn(400);
			}, function() {
				$("li#nav-services ul").fadeOut(150);
			});
	},
	
	/** 
	* initialize the carousel
	*/
	initCarousel : function() {
		var c = mana.config.carousel;
		
		mana.config.carouselConfig[mana.page].btnNext = c.next;
		mana.config.carouselConfig[mana.page].btnPrev = c.prev;
	    
		mana.el.carousel.$container.jCarouselLite(mana.config.carouselConfig[mana.page]);
		$(c.prev).css({ opacity: 0.1 });
				$(c.next).click(function(){
					$(c.prev).animate( {opacity: "1" }, 2000);
				});
		
		mana.el.carousel.$container.find('li')
			.bind(
				'click', 
				function(e) {
					e.preventDefault();
					mana.showItem($(this));
				}
			)	
			.hover(function() {
				$(this).find("a").animate({ opacity: 0.4 }, 300);
				$(this).find(".plus").animate({ opacity: 0.8 }, 300);
			}, function() {
				$(this).find("a").animate({ opacity: 0.8 }, 300);
				$(this).find(".plus").animate({ opacity: 0 }, 300);
			});
		
		mana.el.carousel.$container.find('a').css("opacity", "0.8");
	}, 
	
	/**
	* show an item
	* @param $item {Object} jQuery containing list item to show
	*/
	showItem : function($item) {
		var hash = mana.getHash($item.find('a').attr('href'));
		$.historyLoad(hash);
	},
	
	/**
	* show the next sibling of the current carousel item
	* @param e {Object} jQuery event object
	*/
	showNext : function(e) {
		e.preventDefault();
		if (!mana.currentItem) { 
			mana.showItem(mana.el.carousel.$container.find('li:first')); 
			return;
		}

		var $item = mana.currentItem.next();
		if (!$item.length) {
			$item = mana.el.carousel.$container.find('li:first');
		}
		mana.showItem($item);
	},
	
	/**
	* show the previous sibling of the current carousel item
	* @param {Object} jQuery event object
	*/
	showPrev : function(e) {
		e.preventDefault();
		if (!mana.currentItem) { 
			mana.showItem(mana.el.carousel.$container.find('li:first')); 
			return;
		}

		var $item = mana.currentItem.prev();
		if (!$item.length) {
			$item = mana.el.carousel.$container.find('li:last');
		}
		mana.showItem($item);
	},
	
	/**
	* show the content area
	*/
	showBar : function(callback) {
		
		mana.el.carousel.$container.parent().hide();

		mana.el.$introbar.hide();
		mana.el.$menu.hide();
		
		mana.showOverlay();
		
		mana.el.bar.$container.parent().animate(
			{ 
		    	height: mana.heights[mana.page].containerParent.open,
				bottom: "40%",
				marginBottom: "-200px"
			}, 
			250
		);
		
		mana.el.bar.$container.animate(
			{ 
				height: mana.heights[mana.page].container.open,
				bottom: "40%",
				marginBottom: "-200px"
			}, 
			250, 
			function() {
				mana.el.$load.fadeIn(200);
				callback && callback();
			} 
		);
		
		mana.el.$globalNav.find("li#nav-banner").nextAll().hide();
		mana.el.bar.$nav.find("a").show();
		
		mana.bar.visible = true;
	},
	
	/**
	* hide the content area
	* @param {Object} jQuery event object
	*/
	hideBar : function(e) {
		e && e.preventDefault();
		
		mana.hideContent();
		mana.el.bar.$nav.find("a").hide();
		
		if (!mana.bar.visible) {
			return;
		}
		
		mana.hideOverlay();
		
		mana.el.$introbar.show();
		mana.el.$menu.show();
		
		mana.el.bar.$container.parent().animate(
			{ 
				height: mana.heights[mana.page].containerParent.closed,
				bottom: "15%",
				marginBottom: "0"
			}, 
			250 
		);
		
		mana.el.bar.$container.animate(
			{ 
				height: mana.heights[mana.page].container.closed,
				bottom: "15%",
				marginBottom: "0"
			}, 
			250 
		);
		
		mana.el.carousel.$container.show();
		mana.el.carousel.$container.parent().fadeIn(800);
		mana.el.$globalNav.find("li#nav-banner").nextAll().show();
		
		mana.bar.visible = false;
		
	},
	
	hideBarPrevNext : function() {
		mana.el.bar.$prevButton.hide();
		mana.el.bar.$nextButton.hide();
	},
	
	hideNavBanner : function() {
		mana.el.$navBanner.css({opacity:0.1});
	},
	
	showNavBanner : function() {
		mana.el.$navBanner.css({opacity:1});
	},
	
	showContent : function(hash) {
		mana.el.$content.hide().fadeIn(450, function(){
			$('#load').fadeOut(1200);
			
			if ($('#video').length && $('#video_file').length) {
				$('#video').flash({
					swf : 'assets/flash/player.swf',
					width : 640,
					height : 360,
					params : {
						flashvars : {
							file : $('#video_file').val(),
							image : $('#video_image').val(),
							skin : 'assets/flash/stylish_slim.swf',
							controlbar : 'over',
							screencolor : '#000000',
							bgcolor : '#000000'
							// frontcolor : '#FFFFFF'
						},
						allowfullscreen : 'true',
						wmode: 'opaque',
						menu: 'false',
						allowscriptaccess : 'always'
					}
				});
			}
			
			var flashParams = {
				allowfullscreen : 'false',
				allowscriptaccess : 'always'
			};
			
			var flashVars = {
				file : $('#audio_file').val(),
				controlbar : 'bottom',
				skin : 'assets/flash/stylish_slim.swf',
				backcolor : '#FFFFFF',
				frontcolor : '#444444'
			};
			
			var flashAttributes = {
				id : 'audioPlayer',
				name : 'audioPlayer'
			};
			
			swfobject.embedSWF(
				'assets/flash/player.swf', 
				'audio', 
				960, 
				30, 
				'10', 
				false, 
				flashVars, 
				flashParams, 
				flashAttributes
			);
		});										   
	},
	
	hideContent : function() {
		$('#load').hide();
		mana.el.$content.empty().hide();
		mana.showNavBanner();
	},
	
	/**
	* load the content for the bar using the provided hash
	* @param hash {String} hash to use to load content
	*/
	populateBar : function(hash) {
		if (!hash) {
			mana.hideBar();
			return;
		}
		
		mana.hideContent();
		
		mana.showBar(function() {
			var url = mana.getUrl(hash);

			var callback = function() {
				(mana.hashCallbacks[hash] && mana.hashCallbacks[hash]()) 
					|| mana.showNavBanner();
				mana.enableLinks();
				mana.colorizeNames();
				mana.colorizeGrid();
				mana.enableAudio();
				mana.showContent(hash);
			};

			if (mana.cache[hash]) {
				mana.el.$content.html(mana.cache[hash]);
				callback();
			} else {
				$('#video').remove();
				$.ajax({
					type : 'GET',
					dataType : 'html',
					url : url,
					success : function(html) {
						mana.el.$content.html(html);
						mana.cache[hash] = html;
						callback();
					}
				});
			}

			mana.currentItem = mana.items[hash] || mana.currentItem;
		});
		
	},
	
	/**
	* enable intra-site links in content area
	*/
	enableLinks : function() {
		mana.el.$content.find('.isl a')
			.bind(
				'click',
				function(e) {
					e.preventDefault();
					var hash = mana.getHash($(this).attr('href'));
					$.historyLoad(hash);
					mana.hideBarPrevNext();
				}
			);
	},
	
	/** 
	* colorize names on the catalogues page
	*/
	colorizeNames : function() {
		mana.el.$content.find('.isl a')
			.each(function() {
				var $a = $(this);
				var t = $a.html();
				$.each(mana.nameColors, function(person, color) {
					if (t.match(person) !== null) {
						$a.html(t.replace(person, '<span>' + person + '</span>'));
						$a.find('span').css({ color : color, fontWeight : 'bold' });
					}
				});
			});
		
	},
	
	/**
	 * colorize the grid items
	 */
	colorizeGrid : function() {
		// only run this on the catalogues page
		if (! $('body').attr('id') == 'catalogues') { return; }
		
		/**
		 * this is a bit of a hack but it works
		 */
		var colors = [
			'#3e8db6',
			'#a96723',
			'#849a38',
			'#9b1920',
			'#c4b822',
			'#ad8098',
			'#849a38',
			'#a96723',
			'#3e8db6'
		];
		
		$('.grid a')
			.each(function(index) {
				$(this).find('span')
					.css({ backgroundColor: colors[index], opacity : 0 });
			})
			.hover(function() {
				$(this).find('span').animate({ opacity : 0.9 }, 300);
			}, function() {
				$(this).find('span').animate({ opacity : 0 }, 200);
			});
	},
	
	/**
	 * make the links in the grid run the audio player
	 */
	enableAudio : function() {
		// only run this on the catalogues page
		if (! $('body').attr('id') == 'catalogues') { return; }
		
		$('.grid a').click(function(e) {
			e.preventDefault();
			
			var $a = $(this);
			var audio = $a.attr('href');
			
			window.player.sendEvent('STOP');
			window.player.sendEvent('LOAD', audio);
			window.player.sendEvent('PLAY');
			
		});
	},
	
	/**
	* show an overlay while the bar area is showing
	*/
	showOverlay : function() {
		mana.el.$overlay.fadeIn(300);
	},
	
	hideOverlay : function() {
		mana.el.$overlay.fadeOut(300);
	},
	
	/**
	* @returns a hash based on the provided URL
	*/
	getHash : function(href) {
		return href.replace(/^.*#/, '').replace('.html','');
	},

	/**
	* @returns a URL based on the provided hash
	*/
	getUrl : function(hash) {
		return hash + '.html';
	}
};

mana.config = {
	carouselConfig : {
		'homepage' : {
			scroll: 1,
			easing: "easeInQuart",
			visible: 3,
			speed: 250
		},
		'default' : {
			scroll: 2,
			easing: "easeInQuart",
			visible: 4,
			speed: 250
		}
	},
	
	carousel : {
		container : '#slider',
		next : '#slidernext',
		prev : '#sliderprev'
	},
	
	bar : {
		container : '#bar',
		prevButton : '#barnavprev',
		nextButton : '#barnavnext',
		closeButton : '#barnavclose',
		nav : '#barnav'
	},
	
	content : '#content',
	globalNav : '#globalnav'
};

$(document).ready(mana.init);