﻿(function($) {
	// ---------------------------------- < LANDING PAGE > ---------------------------------- \\	
	var siteLoaded = false, minTimeElapsed = false;
	
	var minTimeTimeoutId = setTimeout((function() {
		minTimeElapsed = true;
		proceedToSite(); 
	}), 3000);
	
	
	//initial loading graphic
	var overlayIntervalId = 0, skipOverlay = false;
	$(function() {
		var msIteration = 150, msElapsed = 0, msInterval=15;
		
		overlayIntervalId = setInterval(
			(function() {
				sizeOverlay();
				
				if ((msElapsed += msInterval) < msIteration) return;
				msElapsed = 0;
				var last = $('#loading-boxes > :last');
				var lastFilled = $('#loading-boxes > div.filled:last');
				if (lastFilled.length && last[0] == lastFilled[0]) {
					$('#loading-boxes > div.filled:first').removeClass("filled");
				} else {
					$('#loading-boxes > div:not(.filled):first').addClass("filled");
				} 
			}), msInterval);
		
		var o = $('#overlay'),
			w = $(window),
			logoMaxWidth = 931, logoMaxHeight = 283,
			loadingBoxesWidth = 210,
			logoDisplayWidth;		

    	function sizeOverlay() {
    		var hSpace = w.width() - 40, //40px padding
    		vSpace = w.height() - $('#contact-details').outerHeight(true) - $('#loading-boxes').outerHeight(true) - 20; //20px padding
    		
    		o.width(w.width());
    		
    		if (hSpace > logoMaxWidth && vSpace > logoMaxHeight) //logo fits full size
    			logoDisplayWidth = logoMaxWidth;
    		else if (hSpace/logoMaxWidth < vSpace/logoMaxHeight) //logo needs more horizontal scaling than vertical scaling
    			logoDisplayWidth = hSpace;
    		else //logo needs more vertical scaling than horizontal scaling
    			logoDisplayWidth = vSpace * logoMaxWidth / logoMaxHeight;
    		
    		$('#logo-container, #logo-container > img').width(logoDisplayWidth);
    		$('#logo-container').height(logoDisplayWidth * logoMaxHeight / logoMaxWidth); //set logo container height according to logo width. Positions text beneath logo correctly before uncached logo is loaded.
    		o.css("top", Math.max(0, (w.height() - o.height()) / 2)); //vertically centre landing page graphics    		
    		$('#loading-boxes').css("margin-left", (w.width() - loadingBoxesWidth) / 2); //centre loading boxes    		
    		o.css("visibility", "visible");
        }
    	
    	$(window).resize(sizeOverlay).resize();
	});
	
	function proceedToSite() { //return;
		if (!siteLoaded || !minTimeElapsed) return;
		
		$(window).unbind("resize");
    	if (overlayIntervalId) {
    		clearInterval(overlayIntervalId);
    		overlayIntervalId = 0;
    	}
    	$('#overlay').remove();
    	$('#wrapper').css("visibility", "visible");
    	
    	$(window)
    		.bind('hashchange', function() {    		
	    		var node,
	    			hash = window.location.hash.replace(/\/$/, "").toLowerCase();
	    		
	    		if (hash.replace(/^#\/?/, "").length)
	    			node = $(contentManager.siteData).find('[lc_hash="' + hash + '"]');
	    		else
	    			node = $(contentManager.siteData).find('section[name="news"]');
	    		
	    		if (node.length) {
	    			switch (node[0].tagName) {
	    			case "section":
	    				var sectionName = node.attr("name");      			
	        			$('div.section[id != "' + sectionName + '"]').removeClass("selected");
	        			$('div#' + sectionName)
	        				.addClass("selected")
	        				.find('.categoryList > li').removeClass("selected");
	        			
	        			if (sectionName == "news")
	        				node = node.children("clips").children("clip:first").children('info');
	        			
	        			contentManager.setNode(node[0]);
	    				break;
	    			case "category":
	    				var section = $('div#' + node.closest('section').attr("name")).addClass("selected");
	    				$('div.section').not(section).removeClass("selected");
	        			        			
	        			var catLI = section.children('div.sectionLinks').children('ul.categoryList').children('li').eq(node.index())
	        				.addClass("selected")
	            			.removeClass("highlighted")
	            			.siblings()
	            				.removeClass("selected highlighted")
	            				.end();
	        			
	    				var clipUL = catLI.children('ul.clipList');            		
	            		if (clipUL.length) {
	            			clipUL.children().removeClass("selected");
	            		} else {
	            			// create clip list for category
	            			var clipNodes = $(node).children('clips').children('clip').toArray();                    
	                        $('<ul class="linkList clipList">')
	                        	.append($.tmpl("linkLI", clipNodes, liTemplateOptions))
	                    		.appendTo(catLI);
	            		}
	            		
	            		contentManager.setNode(node[0]);            		
	    				break;
	    			}
	    		} else {
	    			//if (hash != "news") window.location.hash = "#/News";
	    		}
	    	
	    	})
	    	.trigger('hashchange');
	}
	// ---------------------------------- < / LANDING PAGE > ---------------------------------- \\
	
	// ---------------------------------- < IMAGE PRELOADER > ---------------------------------- \\
	//my tiny jQuery plugin to preload images
	$.preloadImages = function(imageUrls, callback, context) {
		var len, remaining = len = imageUrls.length;
		var args = [].slice.call(arguments, 3);
		
		var checkComplete = function() {
			if (!--remaining && $.isFunction(callback))
				callback.apply(context || window, args);
		};
		
		for (i=0; i<len; i++) {
			//null replaces empty string - empty string won't error but won't load either whereas null triggers error.
			$('<img/>').load(checkComplete).error(checkComplete).attr("src", imageUrls[i] || null);
		}
	};
	// ---------------------------------- < / IMAGE PRELOADER > ---------------------------------- \\
	
	// ---------------------------------- < TEMPLATING > ---------------------------------- \\
	//jQuery templating for list item links
	$.template("linkLI",
        '<li>\
			<a href="{{html $item.hash()}}">\
				{{html $item.linkText()}}\
            </a>\
        </li>'
        .replace(/(>|}})\s+/g, '$1'));
	
	//jQuery templating for thumbnail divs
    $.template("thumbDiv",
	    '<div class="thumb-container" style="background-image:url(\'{{html $($item.data).attr(\"thumb_url\")}}\')"><div class="thumb-play"></div></div>');
	
	var liTemplateOptions = {
		hash: function(attrName) {
			return $(this.data).attr("hash") || "#";
		}
		, linkText: function() {
			return $(this.data).attr("link_text");
		}		
	};
	// ---------------------------------- < / TEMPLATING > ---------------------------------- \\
	
    
	// ---------------------------------- < VIDEO PLAYER > ---------------------------------- \\
	//videoPlayer
	$.extend(window, {
		videoPlayer: (function() { 
			var div, swf, tlWidth, playStatus;
			var mouseOverVideo = false, fullscreen = false, fadeDelay = 1500, fadeDuration = 750, fadeElapsed = 0, fadeFrequency=15, fadeIntervalId = 0;
	        
	        function startControlsFade() {
	        	if (fadeIntervalId) return;
	        	fadeIntervalId = setInterval((function() {
					if ((fadeElapsed += fadeFrequency) < fadeDelay) return;
					var currentOpacity = parseFloat($('#play-pause-btn').css("opacity"));
					setControlsOpacity(Math.max(0, currentOpacity - fadeFrequency / fadeDuration));
				}), fadeFrequency);
	        }
	        function resetControlsFade() {
	        	setControlsOpacity(1);
	        	fadeElapsed = 0;
	        	if (fadeIntervalId) {
	        		clearInterval(fadeIntervalId);
	        		fadeIntervalId = 0;
	        	}
	        }
	        function setControlsOpacity(opacity) {
	        	$('#news-play-icon, #news-item-selectors, #play-pause-btn, #full-screen-dummy, #timeline').css("opacity", opacity);
				swf.setControlsOpacity(opacity);
				if (!opacity && fadeIntervalId) {
					clearInterval(fadeIntervalId);
					fadeIntervalId = 0;
				}
			}
			
	        $(function() {
				swf =  document["video_player"] || window["video_player"];
				div = $('#flashvid');				
				$('#top-right')
					.mouseover(function() {
						mouseOverVideo = true;
						if (playStatus == "playing") resetControlsFade();
					})
					.mouseout(function() {
						mouseOverVideo = false;
						if (playStatus == "playing") startControlsFade();
					})
		        	.delegate('#play-pause-btn', "click", function() {
		        		if (playStatus == "playing" || playStatus == "paused") swf.togglePause();
			        	return false;
		        	})
		        	.delegate('#playbar, #playhead', "click", function(e) {
		        		swf.seekTime((e.pageX - $('#playbar').offset().left) / (tlWidth - 1));
			        	return false;
		        	});
			});
			
	        //videoPlayer interface
			return {
				videoIsLoaded: false,
				hide: function() { 
					div.css("top", -1000);
					if (videoPlayer.videoIsLoaded) {
						swf.unloadVideo();
						this.videoLoaded = false;
					}
				},
				play: function(url) {
					if (!(url && url.length)) return;
					div.css("top", 0);
					swf.loadVideo(url);
					this.videoIsLoaded = true;
				},
				updateTimeline: function(loadProgress, playProgress) {
					tlWidth = tlWidth || $('#timeline').width();
					$('#playbar').width(loadProgress * tlWidth);
					$('#playhead').width(1 + playProgress * (tlWidth - 1));
				},
				onPlayStatus: function(status) {
					if ((playStatus = status) == "playing") {
						$('#play-pause-btn, #news-play-icon').addClass("playing");
						if (fullscreen || !mouseOverVideo) startControlsFade();
					} else {
						$('#play-pause-btn, #news-play-icon').removeClass("playing");
						resetControlsFade();
						
						if (playStatus == "stopped") {
							var n = $(contentManager.currentNode);
							contentManager.setNode(n.closest('section').attr("name") == "news" ? n.children('info')[0] : n.closest('category')[0]);
						}
					}
				},
				onToggleFullScreen: function(value) {
					fullscreen = value;
					if (fullscreen && playStatus == "playing") startControlsFade();
					else resetControlsFade();
				},
				onFullScreenMouseMove: function() {
					if (playStatus == "playing") {
						resetControlsFade();
						startControlsFade();
					}
				}
			};
		})(),
		// ---------------------------------- < / VIDEO PLAYER > ---------------------------------- \\
		
		// ---------------------------------- < NEWS ROTATOR > ---------------------------------- \\		
		//newsRotator - alternates news items
		newsRotator: (function() {
			var rotateInterval = 0,
				itemDuration = 5000,
				mouseIsOver = false;
			
			//newsRotator interface
			return {
				start: function() {
					this.stop();
					if (!mouseIsOver) {
			    		rotateInterval = setInterval(
		    				(function() {
				    			var clips = $(contentManager.siteData).find('section[name="news"] > clips');
				    			var currentClip = $(contentManager.currentNode).parent();
				    			contentManager.setNode(currentClip.next().children('info')[0] || clips.children('clip:first').children('info')[0]); 
		    				}), 
		    				itemDuration);
					}
				},
				stop: function() {
					if (rotateInterval) {
		    			clearInterval(rotateInterval);
		    			rotateInterval = 0;
		    		}
				},
				onMouseOver: function() {
					mouseIsOver = true;
					this.stop();
				},
				onMouseOut: function() {
					mouseIsOver = false;
					if (contentManager.currentNode.tagName == "info" && $(contentManager.currentNode).closest("section").attr("name") == "news")
						this.start();
				}
			};
		})(),
		// ---------------------------------- < / NEWS ROTATOR > ---------------------------------- \\
		
		//contentManager
		contentManager: (function() {
			var currLNode = null, currRNode = null,
        		nextLNode = null, nextRNode = null,
        		intervalID = null,  intervalDelay = 15,
        		lOpacity = 0, rOpacity = 0,
        		lFadeElm, rFadeElm,
        		lBlackoutElapsed = 0, rBlackoutElapsed = 0,
        		fadeSettings = { fadeOutDuration:150, blackoutDuration:5, fadeInDuration:150 };
			
			//load site data and initialise
			$(function() {
				$.ajax({
		            type: "GET"
		            , url: "sitedata.xml?" + escape(new Date())
		            , dataType: "xml"
		            , success: function(xml) {
		                contentManager.siteData = xml;
		                $.tmpl("linkLI", $(xml).find('section[name="directors"] > category').toArray(), liTemplateOptions)
	                		.appendTo('#directors .categoryList');
		                $.tmpl("linkLI", $(xml).find('section[name="content"] > category').toArray(), liTemplateOptions)
		                	.appendTo('#content .categoryList');
		                
		                //get all the image urls from the site into an array: imageUrls
		                var imageUrls = ["images/logo_small.png", "images/play.gif", "images/play_highlight.gif", "images/pause.gif", "images/pause_highlight.gif", "images/fullscreen.gif", "images/fullscreen_highlight.gif"];
		                imageUrls = $.merge(imageUrls, $.map($(xml).find("[image_url]"), function(node) { return $(node).attr("image_url"); }));
		                imageUrls = $.merge(imageUrls, $.map($(xml).find("[thumb_url]"), function(node) { return $(node).attr("thumb_url"); }));
		                
		                //preload the images from imageUrls
	                	$.preloadImages(imageUrls, function() {
		                	$(xml).find('section[name="news"] > clips > clip').each(function() {
			                	$('<div class="box"><div class="box-hover-fill"/></div>').appendTo('#news-item-selectors');			                	
			                	$('<img />').attr("src", $(this).attr("image_url")).appendTo('#news-stills');
			                });
			                
			                $('<div class="thumbs section-thumbs directors-thumbs" />')
			                	.append($.tmpl("thumbDiv", $(xml).find('section[name="directors"] clips > clip:first-child').toArray()))
			            		.appendTo('#top-right');
			                
			                $('<div class="thumbs section-thumbs contentTypes-thumbs" />')
			                	.append($.tmpl("thumbDiv", $(xml).find('section[name="content"] clips > clip:first-child').toArray()))
			            		.appendTo('#top-right');
			                
			                $(xml).find('section[name="directors"] > category').each(function(){
			                	$('<div class="thumbs category-thumbs director-thumbs" />')
			                		.append($.tmpl("thumbDiv", $(this).children('clips').children('clip').toArray()))
			                		.appendTo('#top-right');
			                });
			                
			                $(xml).find('section[name="content"] > category').each(function(){
			                	$('<div class="thumbs category-thumbs content-thumbs" />')
			                		.append($.tmpl("thumbDiv", $(this).children('clips').children('clip').toArray()))
			                		.appendTo('#top-right');
			                });
			                
			                $('#news-stills, #flashvid, #contacts, div.thumbs').css({opacity: 0});

			                siteLoaded = true;
		                	proceedToSite();
	                	});
		            }
		        });
			});
						
			//contentManager interface
			return {
				siteData: null,
        		fadeSettings: fadeSettings,
				currentNode: null, // = currRNode
				setNode: setNode,
				onPageLoaded: function(firstDisplayNode) {
					$('#news-stills, #flashvid, #contacts, div.thumbs').css({opacity: 0});
					setNode(firstDisplayNode);
				}
			};
			
			function setNode(node, leftOnly) {				
				nextLNode = node.tagName == "info" ? node : $(node).children("info")[0] || node;		    		
	    		if (leftOnly !== true) nextRNode = node;
				if (!node || node.tagName != "info") newsRotator.stop();		    		
	        	if (!intervalID) intervalID = setInterval((function() { performFade(); }), intervalDelay);
	        	$('img#full-screen-dummy').css("display", $('#timeline').css("display"));
			}
			
			function performFade() {
				// nextLNode / nextRNode null: fading in.	
				// nextLNode / nextRNode not null: fading out.

	        	var inc = (isNaN(fadeSettings.fadeInDuration) || fadeSettings.fadeInDuration <= 0) ? 1 : intervalDelay / fadeSettings.fadeInDuration,
	        		dec = (isNaN(fadeSettings.fadeOutDuration) || fadeSettings.fadeOutDuration <= 0) ? 1 :intervalDelay / fadeSettings.fadeOutDuration;

	        	//left fade
	        	if (nextLNode) {
	        		if (currLNode == nextLNode || !currLNode) {
        				// start fade in on this iteration
        				var requiresInit = currLNode != nextLNode; //no init if fading back in node that faded out
	        			currLNode = nextLNode;
	        			nextLNode = null;
	        			lBlackoutElapsed = 0;
	        			if (requiresInit) initialiseLeftContent(currLNode);
	        		} else {
	        			lOpacity = Math.max(0, lOpacity - dec);
	        			if (!lOpacity) currLNode = null; // switch to fade in next iteration
	        		}
	        	}
	        	
	        	if (currLNode && !nextLNode) {
	        		if (lBlackoutElapsed < fadeSettings.blackoutDuration)
	        			lBlackoutElapsed += intervalDelay;
	        		else
	        			lOpacity = Math.min(1, lOpacity + inc);
	        	}
	        	
	        	lFadeElm.css("opacity", lOpacity);
	        	
	        	// right
	        	if (nextRNode) {
	        		if (currRNode == nextRNode || !currRNode) {
	        			// start fade in on this iteration
	        			var requiresInit = currRNode != nextRNode; //no init if fading back in node that faded out
	        			contentManager.currentNode = currRNode = nextRNode;
	        			nextRNode = null;
	        			rBlackoutElapsed = 0;
	        			if (requiresInit) initialiseRightContent(currRNode);
	        		} else {
	        			rOpacity = Math.max(0, rOpacity - dec);
	        			if (!rOpacity) currRNode = null; // switch to fade in next iteration
	        		}
	        	}
	        	
	        	if (currRNode && !nextRNode) {
	        		if (rBlackoutElapsed < fadeSettings.blackoutDuration)
	        			rBlackoutElapsed += intervalDelay;
	        		else
	        			rOpacity = Math.min(1, rOpacity + inc);
	        	}
	        	
	        	rFadeElm.css("opacity", rOpacity);
	        	
	        	if (rOpacity < 1 || nextRNode) {
		        	//unless fading out of news-item/news-clip before fading into another news-item/news-clip, fade news controls
		        	if ($('#news-item-selectors').css("display") != "none" &&  $(nextRNode).closest("section").attr("name") != "news") {
		        		var currentOpacity = parseFloat($('#news-item-selectors').css("opacity"));
		        		$('#news-item-selectors, #news-play-icon').css("opacity", nextRNode ? Math.min(rOpacity, currentOpacity) : Math.max(rOpacity, currentOpacity));
		        	}
		        	
		        	//unless fading out of vid clip before fading into another vid clip, fade vid controls
		        	if ($('#play-pause-btn').css("display") != "none" &&  (!nextRNode || nextRNode.tagName != "clip")) {
		        		var currentOpacity = parseFloat($('#play-pause-btn').css("opacity"));
		        		$('#play-pause-btn, #full-screen-dummy, timeline').css("opacity", nextRNode ? Math.min(rOpacity, currentOpacity) : Math.max(rOpacity, currentOpacity));
		        	}
	        	}
	        	
	        	
	        	//clearInterval if left and right fully faded in
	        	if (!nextLNode && !nextRNode && (lOpacity == 1 || !currLNode) && (rOpacity == 1 || !currRNode)) {
	        		clearInterval(intervalID);
	        		intervalID = 0;
        			$('img#full-screen-dummy').css("display", "none");
	        	}
	        }
			
			function initialiseLeftContent(node) {
				//called on first iteration of fade in
				
				lFadeElm = $('#top-left > span')
	        		.empty()
	        		.css("opacity", 0);
	        	
	        	var info = $(node)[0].tagName == "info" ? $(node) : $(node).children('info');	        	
	        	if (!info.length) return;
	        	
	        	lFadeElm.html(
	        			info.text()
        					.replace(/ ([^\w\s]*[\w\-]{1,4}[^\w\s]*) *(\n|$)/g, "&nbsp;$1$2") // prevents "widow" or "orphan" text.
	        				.replace(/\n/g,'&nbsp;<br>'));//non-breaking space fixes issue with IE7 and conseuctive line breaks
	        }
			
			function initialiseRightContent(node) {
				//called on first iteration of fade in
				
				//reset
				$('#news-stills, #top-right > div.thumbs, #contacts').css({display:"none", opacity: 0});
				videoPlayer.hide(); //triggers video unload - important when changing from one video to another
				
				var n = $(node),
					sectionName = n.closest("section").attr("name");
				
				$('#news-item-selectors, #news-play-icon').css("display", sectionName == "news" ? "block" : "none");
        		$('#play-pause-btn, #full-screen-dummy, #timeline').css("display", node.tagName == "clip" ? "block" : "none");
				
	        	if (node.tagName == "clip") {
	        		$('div.section.selected li.selected > ul.clipList > li').eq(n.index()).addClass("selected"); //highlight corresponding list-item (required if clip selected by clicking thumb)
	        		rFadeElm = $('#flashvid');
	        		videoPlayer.play(n.attr("video_url"));
	        	} else {
	        		$('div.section.selected li.selected > ul.clipList > li').removeClass("selected"); //remove any clip list-item's green highlight
		        	switch (sectionName) {
		        		case "news":
			        		var itemIndex = n.parent().index();
		        			rFadeElm = $('#news-stills');		        			
		            		rFadeElm.children('img')
	            				.not(':eq(' + itemIndex + ')').css("display", "none")
	            				.end()
	            				.eq(itemIndex).css("display", "block");
		            		
		            		$('#news-item-selectors > div').removeClass("activeItem").eq(itemIndex).addClass("activeItem");
		            		
		            		newsRotator.start();
		            		break;
		        		case "contact":
			        		rFadeElm = $('#contacts');
		        			break;
		    			default:
		        			if (node.tagName == "section") {
	    						rFadeElm = sectionName == "directors" ? $('#top-right > div.directors-thumbs') : $('#top-right > div.contentTypes-thumbs');
	    					} else if (node.tagName == "category") {
	    						var divs = sectionName == "directors" ? $('#top-right > div.director-thumbs') : $('#top-right > div.content-thumbs');
	    						rFadeElm = divs.eq(n.index());
	    						rFadeElm.children().removeClass("dimmed highlighted");
	    					}
		    				break;
		        	}
		        	
		        	rFadeElm.css({display: "block"});
	        	}
	        }
		})()
	});
	
    $(function() {
        // ---------------------------------------- < MOUSE EVENTS: #bottom > ---------------------------------------- \\
        $('#bottom')
        	.delegate('div.section > a.sectionTitle', "click", function() {
        		if (window.location.hash.replace(/\/$/, "") == $(this).attr("href"))
        			$(window).trigger('hashchange');
        	});        
        $('#directors, #content')
        	.delegate('ul.categoryList > li > a', "click", function() {
        		if (window.location.hash.replace(/\/$/, "") == $(this).attr("href"))
        			$(window).trigger('hashchange');
	        })
	        .delegate('ul.categoryList > li > a', "mouseover mouseout", function(e) {
	        	//show play icon when hovering over a director / content-type
	        	
	        	var curr = $(contentManager.currentNode).attr("name");
	        	if (e.type == "mouseover" && curr != "directors" && curr != "content")
	        		return;
	        	
        		var categoryIndex = $(this).closest('li').index();

        		var cssClass = e.liveFired == $('#directors')[0] ? "directors-thumbs" : "contentTypes-thumbs";
        		var thumb = $('#top-right > .' + cssClass + ' > .thumb-container:eq(' + categoryIndex + ')');

        		if (e.type == "mouseover") {
        			thumb
        				.addClass("highlighted")
        				.siblings().addClass("dimmed");
       			 	contentManager.setNode($.tmplItem(this).data, true);
        		} else {
        			thumb
        			 	.removeClass("highlighted")
        			 	.siblings().removeClass("dimmed");
        			contentManager.setNode(contentManager.currentNode, true);
        			
        			/*N.B. this not necessary if info only displayed for directors/content-types when currentNode in ("directors", "content")
        			if (contentManager.currentNode.tagName == "info")
        				newsRotator.start();*/
        		}
	        })
	        .delegate('ul.clipList > li > a', "mouseover mouseout", function(e) {
	        	var categoryLI = $(this).closest('ul').parent();
        		var clipIndex = $(this).closest('li').index();

        		var cssClass = e.liveFired == $('#directors')[0] ? "director-thumbs" : "content-thumbs";
        		var thumb = $('#top-right > .' + cssClass + ':eq(' + categoryLI.index() + ') > .thumb-container:eq(' + clipIndex + ')');
        		
        		if (e.type == "mouseover") {
        			thumb
        				.addClass("highlighted")
        				.siblings().addClass("dimmed");
       			 	contentManager.setNode($.tmplItem(this).data, true);
        		} else {
        			thumb
        			 	.removeClass("highlighted")
        			 	.siblings().removeClass("dimmed");
        			contentManager.setNode(contentManager.currentNode, true);
        		}
	        })
	        .delegate('ul.clipList > li > a', "click", function(e) {
	        	$(this).parent().addClass("selected").siblings().removeClass("selected");
	        	contentManager.setNode($.tmplItem(this).data);
	        	return false;
	        });
        // --------------------------------------- < / MOUSE EVENTS: #bottom > --------------------------------------- \\
        
        // --------------------------------------- < MOUSE EVENTS: #top-right > --------------------------------------- \\
    	$('#top-right')        	
    		// news
    		.delegate('#controls, #news-stills, #news-item-selectors, #news-play-icon', "mouseover mouseout", function(e) {
				e.type == "mouseover" ? newsRotator.onMouseOver() : newsRotator.onMouseOut();
				return false;    			
    		})
    		.delegate('#controls, #news-stills, #news-play-icon', "click", function(e) {
    			if ($(this).attr("id") == "news-play-icon" && contentManager.currentNode.tagName == "clip") {
    				$('#play-pause-btn').click();
    			} else {    			
	    			var currentNode = contentManager.currentNode;    			
	    			if (currentNode.tagName == "info" && $(currentNode).closest("section").attr("name") == "news")
	    				contentManager.setNode($(currentNode).parent()[0]);
    			}
    			newsRotator.stop();
    			return false;
    		})
    		.delegate('#news-item-selectors > div', "click", function(e) {
    			$(this)
    				.addClass("activeItem")
    				.siblings().removeClass("activeItem");
    			contentManager.setNode(
    				$(contentManager.siteData)
    					.find('section[name="news"] clip:eq(' + $(this).index() + ')')
    					.children('info')[0]
				);
    			return false;
    		})

    		// section thumbs (i.e. list directors / list content-types)
    		.delegate('.section-thumbs > .thumb-container', "mouseover mouseout", function(e) {
    			var ulCategory =  $(this).parent().hasClass("directors-thumbs") ? $('#directors ul.categoryList') : $('#content ul.categoryList');
    			var li = $(ulCategory).children('li:eq(' + $(this).index() + ')');
    				
    			if (e.type == "mouseover") {
    				$(this)
						.addClass("highlighted")
						.siblings().addClass("dimmed");
    				
    				var clipNode = $.tmplItem(this).data;
    				var categoryNode = $(clipNode).closest('category')[0];
    				contentManager.setNode(categoryNode, true);
    				li.addClass("highlighted");
    			} else {
    				$(this)
						.removeClass("highlighted")
						.siblings().removeClass("dimmed");
    				
    				contentManager.setNode(contentManager.currentNode, true);
    				li.removeClass("highlighted");
    			}
    			
    			return false;
    		})
    		.delegate('.section-thumbs > .thumb-container', "click", function() {
    			//selectCategory($($.tmplItem(this).data).closest("category")[0]);
    			window.location.hash = $($.tmplItem(this).data).closest('category').attr("hash");
    			return false;
    		})
    		
    		// clip thumbs (for individual director or content type)
    		.delegate('.category-thumbs > .thumb-container', "mouseover mouseout", function(e) {
    			var clipIndex = $($.tmplItem(this).data).index();
    			var clipLI = $('div.section.selected li.selected > ul.clipList > li').eq(clipIndex);
    			
    			if (e.type == "mouseover") {
    				$(this)
    					.addClass("highlighted")
    					.siblings().addClass("dimmed");    				
    				clipLI.addClass("highlighted");		
    				contentManager.setNode($.tmplItem(this).data, true);
    			} else {            			
    				$(this)
    					.removeClass("highlighted")
    					.siblings().removeClass("dimmed");    				
    				clipLI.removeClass("highlighted");
    				contentManager.setNode(contentManager.currentNode, true);
    			}
    			return false;
    		})
    		.delegate('.category-thumbs > .thumb-container', "click", function() {
    			var clipIndex = $($.tmplItem(this).data).index();
    			var clipLI = $('div.section.selected li.selected > ul.clipList > li').eq(clipIndex);
    			clipLI.addClass("selected");
    			contentManager.setNode($.tmplItem(this).data);
    			return false;
    		});
    	// --------------------------------------- < / MOUSE EVENTS: #top-right > --------------------------------------- \\
        	
    	// ------------------------------- < FUNCTIONS CALLED BY MOUSE EVENT HANDLERS > --------------------------------- \\
    	function selectCategory(node) {
    		var catLI = $('div#' + $(node).closest("section").attr("name") + ' > div.sectionLinks > ul.categoryList > li:eq(' + $(node).index() + ')');
    		catLI
    			.addClass("selected")
    			.removeClass("highlighted")
    			.siblings()
    				.removeClass("selected highlighted");
    		
    		var clipUL = catLI.children('ul.clipList');
    		
    		if (clipUL.length) {
    			clipUL.children().removeClass("selected");
    		} else {
    			// create clip list for category
    			var clipNodes = $(node).children('clips').children('clip').toArray();                    
                $('<ul class="linkList clipList">')
                	.append($.tmpl("linkLI", clipNodes, liTemplateOptions))
            		.appendTo(catLI);
    		}
    		
    		contentManager.setNode(node);
    	}
    	// ------------------------------ < / FUNCTIONS CALLED BY MOUSE EVENT HANDLERS > -------------------------------- \\
    });
})(jQuery);

function logConsole() {
	//console.log.apply(this, arguments);
}
