//wrap these in an object function
smClip = {width: 320, height: 205};
gutter = 20;
lgClip = {width: smClip.width*2+gutter, height: smClip.height*2+gutter};

smClipMM = {width: 29, height: 16};
gutterMM = 2;
lgClipMM = {width: smClipMM.width*2+gutterMM, height: smClipMM.height*2+gutterMM};

ytPlayer = null;
ytPlayerState = null;

playCount = 0;

siteContentVisible=false;
lastNavBtnClicked = null;
lastSubNavBtnClicked = null;

excerptOrder = ['appliance', 'rockintherainbow', 'fatchance', 'myboyfriendspackage', '214', 'thedayithoughtidied', 'happypills', 'doyouwantout', 'dinneratlucys', 'thetranslator'];
excerptOrderByID= {'JIyUUjqHvZ8': 0,'JMsSNbLrwFQ':1,'o4dgNQvpLuc':2,'GJFIGJba41U':3,'eJo4ha6kXig':4,'er6Y89tOlWQ':5,'R7r4MiT1R00':6,'FyjDJfRA9v4':7,'6yUIZEk6DA0':8,'mFSSyiUcozs':9};
excerptThumbURLs= {'JIyUUjqHvZ8': 'images/appliance_th.jpg','JMsSNbLrwFQ':'images/rockintherainbow_th.jpg','o4dgNQvpLuc':'images/fatchance_th.jpg','GJFIGJba41U':'images/myboyfriendspackage_th.jpg','eJo4ha6kXig':'images/214_th.jpg','er6Y89tOlWQ':'images/thedayithoughtidied_th.jpg','R7r4MiT1R00':'images/happypills_th.jpg','FyjDJfRA9v4':'images/doyouwantout_th.jpg','6yUIZEk6DA0':'images/dinneratlucys_th.jpg','mFSSyiUcozs':'images/thetranslator_th.jpg'};

window.tagsArray = new Object();

window.blockNumber=0;

totalClips = 0;
totalThumbnailImages = 0;
thumbnailImagesLoaded = 0;

window.columnArray1 = new Array();
window.columnArray2 = new Array();
window.columnArray3 = new Array();
window.columnArray4 = new Array();
window.columnArray5 = new Array();

window.columnMetaArray = new Array(5);

columnMetaArray[0]=columnArray1;
columnMetaArray[1]=columnArray2;
columnMetaArray[2]=columnArray3;
columnMetaArray[3]=columnArray4;
columnMetaArray[4]=columnArray5; 

window.rawYtData = new Array();

function incrementThumbsLoaded(){
	thumbnailImagesLoaded+=1;
	//console.log('Total images loaded: ' + thumbnailImagesLoaded);
	if(thumbnailImagesLoaded>=totalThumbnailImages){
		//console.log('Dropping columns');
		dropInColumn(1);
	}
}

function VideoInfo(ytid, cap, tags, imgURL) {
	this.ytID = ytid;
	this.caption = cap;
	this.tags= tags;
	this.imgURL = imgURL;
}

function getYtData (startIndex) {
	//console.log('startIndex ' + startIndex);
	if(startIndex<91){
		var url='http://gdata.youtube.com/feeds/api/users/theBIGmoments/uploads?alt=json-in-script&start-index=' + startIndex + '&max-results=30&format=5&callback=?';
		$.getJSON(url, function(ytData) {
			//console.dir(ytData);
			
			//hardcoded - better to use version below
			//rawYtData[rawYtData.length] = ytData;
			//getYtData(startIndex+30);
			
			// Use this if the number of videos uploaded is not fixed at 90 OR if the feed sometimes returns fewer results than called for
			if(ytData.feed.entry.length==30){
				rawYtData[rawYtData.length] = ytData;
				getYtData(startIndex+30);
			} else if (30>ytData.feed.entry.length>0) {
				rawYtData[rawYtData.length] = ytData;
				processYtData();
			} else if (!ytData.feed.entry) {
				processYtData();
			}
		});
	} else {
		processYtData();
	}
}

function processYtData() {
	//console.log('Processing data from YouTube...');
	
	//console.dir(rawYtData);
	
	for(var i=0;i<rawYtData.length;i++){
		//console.log(rawYtData[i].feed.entry.length + " clips in feed pull " + (i+1));
		totalClips+=rawYtData[i].feed.entry.length;
	}
	//console.log('Total entries: ' + totalClips);
	
	//fix for weird 'Fat Chance' problem
	
	if(rawYtData[2].feed.entry[29] == "undefined" || rawYtData[2].feed.entry[29] == null){
		//console.log('yep');
		//look for an excerpt clip to duplicate as a template
		for(var i=0; i<rawYtData.length; i++){
			for(j=0; j<rawYtData[i].feed.entry.length; j++){
				var tagStringTemp1=rawYtData[i].feed.entry[j].media$group.media$keywords.$t;
				//console.log(tagStringTemp1);
				if(tagStringTemp1.indexOf("excerpt")!=-1){
					//console.log('subbing in clips');
					rawYtData[2].feed.entry[29] = jQuery.extend(true, {}, rawYtData[i].feed.entry[j]);
					breakFor = true;
					break;
				}
			}
			if(breakFor==true){
				break;
			}
		}
		
		// replace necessary info in duplicate entry with Fat Chance info
		rawYtData[2].feed.entry[29].id.$t = "http://gdata.youtube.com/feeds/api/videos/o4dgNQvpLuc";
		rawYtData[2].feed.entry[29].media$group.media$description.$t= '"Fat Chance" was produced as part of Little Films About Big Moments. See more short films and behind-the-scenes footage at http://www.littlefilms.ca. In the film, a woman gets caught with her hand in the cookie jar and realizes her life is in jeopardy. A scene from "Fat Chance", by Beatriz Yuste. "Fat Chance" features Cara Volchoff and Kiran Friesen.';
		rawYtData[2].feed.entry[29].media$group.media$keywords.$t = 'excerpt, Fat Chance, Beatriz Yuste, Cara Volchoff, Kiran Friesen';
	}
		
	for(var g=0;g<rawYtData.length;g++){
		//console.dir(rawYtData[g]);
		fisherYates(rawYtData[g].feed.entry);
		for(var h=0;h<rawYtData[g].feed.entry.length;h++){
			var idtemp = rawYtData[g].feed.entry[h].id.$t.split('/');
			var id = idtemp[idtemp.length-1];
			var caption = rawYtData[g].feed.entry[h].media$group.media$description.$t.replace("Explore more behind-the-scenes footage at www.littlefilms.ca. ", "");
			if(caption.indexOf("In this clip ") != -1 && caption.indexOf("In this clip") != -1) {
				caption = caption.replace(/In this clip /g, "In this clip: ");
			}
			var tagsString = rawYtData[g].feed.entry[h].media$group.media$keywords.$t;
			
			tags = tagsString.split(', ');
			
			tagsString=tags.join(',');
			//console.log('tagsArray: ' + tags);
			//console.log('tagsString: ' + tagsString);
			
			var imgURL = rawYtData[g].feed.entry[h].media$group.media$thumbnail[3].url;
			
			var tempColumn="";
			
			//console.log('Tags for clip #' + (h+1) + ': ' + tags);
			var categoryTagFound = false;
			for(var j=0;j<tags.length;j++){
				if(tags[j] in {'pre-production':'', 'production1':'', 'production2':'', 'post-production':'', 'excerpt':''}) {
					tempColumn=tags[j];
					if(tags[j]=="production1" || tags[j]=="production2"){
						tags[j]="during production";
					}
					categoryTagFound=true;
				}
			}
			
			if(categoryTagFound==false){
				//console.log("Clip " + id + " \ '" + caption + " is missing a category tag!");
			}
			
			totalThumbnailImages+=1;
			
			switch(tempColumn)
			{
			case "pre-production":
				columnMetaArray[0][columnMetaArray[0].length] =  new VideoInfo(id, caption, tags, imgURL);
				break;
			case "production1":
				columnMetaArray[1][columnMetaArray[1].length] =  new VideoInfo(id, caption, tags, imgURL);
				break;
			case "production2":
				columnMetaArray[2][columnMetaArray[2].length] =  new VideoInfo(id, caption, tags, imgURL);
				break;
			case "post-production":
				columnMetaArray[3][columnMetaArray[3].length] =  new VideoInfo(id, caption, tags, imgURL);	
				break;
			case "excerpt":
				imgURL = excerptThumbURLs[id];
				//console.log('matching ids: YTID: ' + id + ', position: ' + excerptOrderByID[id]);
				columnMetaArray[4][excerptOrderByID[id]] =  new VideoInfo(id, caption, tags, imgURL);
				//$('#minimapColumn5 .mm_block').eq(excerptOrderByID[id]).data('tags', tagsString);	
				break;
			case "":
				//console.log('Clip lacks column tag (' + caption + ')');
				totalThumbnailImages-=1;
				break;
			}
		}
	}
	
	//console.log('Total clips properly formatted: ' + totalThumbnailImages);
	//console.dir(columnMetaArray);

	for(var h=0;h<5;h++){
		if(h==4){
			for(var i=0;i<columnMetaArray[h].length;i++){
				tagsArray['#minimapBlock' + (h*20+(i+0.5)*2)] = columnMetaArray[h][i].tags;
				$('#block_' + (h+1+i*5)).data('id', columnMetaArray[h][i].ytID).data('tags', columnMetaArray[h][i].tags)
					.find("img.block_thumb_hd").attr('src', columnMetaArray[h][i].imgURL);
			}
		} else {
			for(var i=0;i<columnMetaArray[h].length;i++){
				tagsArray['#minimapBlock' + (h*20+i+1)] = columnMetaArray[h][i].tags;
				$('#block_' + (h+1+i*5)).data('id', columnMetaArray[h][i].ytID).data('caption', columnMetaArray[h][i].caption).data('tags', columnMetaArray[h][i].tags)
					.find("img.block_thumb").attr('src', columnMetaArray[h][i].imgURL);
			}
		}
	}
	
	createCloud(true, 20);
}


$(document).ready(function(){

	// test for outdated browsers & those which don't support inline youtube objects
	
	userAgentStr = navigator.userAgent.toLowerCase();
	hasRequestedVersion = DetectFlashVer(8, 0, 0);
	
	window.showFullSite = true;
	
	if(hasRequestedVersion == false) {
		window.showFullSite = false;
		window.showSiteWarning = "noflash";
	}
	
	if(userAgentStr.indexOf('msie 6.') != -1 || jQuery.support.boxModel == false) {
		window.showFullSite = false;
		window.showSiteWarning = "obsoletebrowser";
	} 
	
	if(userAgentStr.indexOf('iphone') != -1 || userAgentStr.indexOf('ipod') != -1) {
		window.showFullSite = false;
		window.showSiteWarning = "iphone";
	}
	
	// sets external urls to open in new window
	$('a').each(function() {
		if($(this).attr('rel')=='external'){
			$(this).attr('target', '_blank');
		}
	});
	
	// sets click function for site-content nav bar
	
	$('#navbar_container .navbar_btn').click(function(){
		var thisBtn = $(this);
		var thisBtnText = thisBtn.attr('rel');
		
		if(siteContentVisible==false){
			$('#site_content_container').html('<div style="text-align:center;"><p class="load_placeholder">Loading...<p></div>').fadeIn('fast').load(thisBtnText + '.html', function(){
				// sets external urls to open in new window
				if(window.showFullSite==true){
					$('a').each(function() {
						if($(this).attr('rel')=='external'){
							$(this).attr('target', '_blank');
						}
					});
				}
				// adds message if full site is not being displayed
				if(window.showFullSite==false){
					if(thisBtnText=='about'){
						$('#show_filmlist').html('<p><a href="http://www.youtube.com/watch?v=JIyUUjqHvZ8">APPLIANCE</a></p><p><a href="http://www.youtube.com/watch?v=JMsSNbLrwFQ">ROCKIN&rsquo; THE RAINBOW</a></p><p><a href="http://www.youtube.com/watch?v=o4dgNQvpLuc">FAT CHANCE</a></p><p><a href="http://www.youtube.com/watch?v=GJFIGJba41U">MY BOYFRIEND&rsquo;S PACKAGE</a></p><p><a href="http://www.youtube.com/watch?v=eJo4ha6kXig">2:14 PM</a></p><p><a href="http://www.youtube.com/watch?v=er6Y89tOlWQ">THE DAY I THOUGHT I DIED</a></p><p><a href="http://www.youtube.com/watch?v=R7r4MiT1R00">HAPPY PILLS</a></p><p><a href="http://www.youtube.com/watch?v=FyjDJfRA9v4">DO YOU WANT OUT?</a></p><p><a href="http://www.youtube.com/watch?v=6yUIZEk6DA0">DINNER AT LUCY&rsquo;S</a></p><p><a href="http://www.youtube.com/watch?v=mFSSyiUcozs">THE TRANSLATOR</a></p>');
					}
					if (showSiteWarning=="noflash"){
						$('#show_copy').prepend('<p class="siteCompatibilityMessage"><strong>Our site requires Adobe Flash Player</strong> (version 8 or higher), so we can&rsquo;t show you all the cool stuff we&rsquo;ve put together. If you install Flash Player <a href="http://get.adobe.com/flashplayer/">here</a>, you&rsquo;ll be able to see the full site. Until then, you can check out excerpts of our films on YouTube using the links to the left.');
					} else if(showSiteWarning=="obsoletebrowser"){
						$('#show_copy').prepend('<p class="siteCompatibilityMessage">We&rsquo;ve detected that you&rsquo;re using an <strong>outdated web browser</strong> (like Internet Explorer 6), which isn&rsquo;t able to display the full version of this site. To see the full site, and to improve your safety and security online, consider upgrading to a modern web browser like <a href="http://www.getfirefox.com">Firefox</a> or <a href="http://www.microsoft.com/windows/internet-explorer/default.aspx">Internet Explorer 8</a>.</p>');
					} else if (showSiteWarning=="iphone"){
						$('#show_copy').prepend('<p class="siteCompatibilityMessage"><strong>We&rsquo;ve detected that you&rsquo;re using iPhone OS.</strong> Our site uses Flash to play YouTube videos within a browser, <strong>so the cool stuff won&rsquo;t work on your iPhone, iPod touch, or iPad</strong>. You can watch excerpts of our films on YouTube by clicking on the film titles to the left, and we hope you come back to check out the full site from your laptop or desktop. <br /><strong>Protip:</strong> you can <strong>scroll up or down</strong> here using a two-finger drag.</p>');
					}
				}
			});
			siteContentVisible = true;
			thisBtn.addClass('nav_selected');
		} else if(siteContentVisible==true){
			//console.log('content visible, btn clicked');
			if(lastNavBtnClicked==thisBtnText){
				//console.log('btns the same');
				if(window.showFullSite==true) {
					thisBtn.removeClass('nav_selected');
					$('#site_content_container').fadeOut('fast');
					siteContentVisible = false;
				}
			} else {
				// clear all highlighted buttons
				$('#navbar_container li').each(function(){
					if($(this).hasClass('nav_selected')) { $(this).removeClass('nav_selected'); };
				});
				thisBtn.addClass('nav_selected');
				$('#site_content_container').html('<div style="text-align:center;"><p class="load_placeholder">Loading...<p></div>').fadeIn('fast').load(thisBtnText + '.html', function(){
					if(window.showFullSite==false){
						if(thisBtnText=='about'){
							$('#show_filmlist').html('<p><a href="http://www.youtube.com/watch?v=JIyUUjqHvZ8">APPLIANCE</a></p><p><a href="http://www.youtube.com/watch?v=JMsSNbLrwFQ">ROCKIN&rsquo; THE RAINBOW</a></p><p><a href="http://www.youtube.com/watch?v=o4dgNQvpLuc">FAT CHANCE</a></p><p><a href="http://www.youtube.com/watch?v=GJFIGJba41U">MY BOYFRIEND&rsquo;S PACKAGE</a></p><p><a href="http://www.youtube.com/watch?v=eJo4ha6kXig">2:14 PM</a></p><p><a href="http://www.youtube.com/watch?v=er6Y89tOlWQ">THE DAY I THOUGHT I DIED</a></p><p><a href="http://www.youtube.com/watch?v=R7r4MiT1R00">HAPPY PILLS</a></p><p><a href="http://www.youtube.com/watch?v=FyjDJfRA9v4">DO YOU WANT OUT?</a></p><p><a href="http://www.youtube.com/watch?v=6yUIZEk6DA0">DINNER AT LUCY&rsquo;S</a></p><p><a href="http://www.youtube.com/watch?v=mFSSyiUcozs">THE TRANSLATOR</a></p>');
						}
					}
				});
			}
		}
		lastNavBtnClicked = thisBtnText;
	});
	
	// Sets click function for site content sub-navbar buttons
	$('#content_navbar li').live('click', function(){
		if($(this)!=lastSubNavBtnClicked){
			$('#content_navbar li').css('background-color', 'transparent')
			$(this).css('background-color', '#bbbbbb')
			$('.site_content').css('display', 'none');
			var subPage = $(this).find('h6').text().toLowerCase().replace(' ', '').replace("'", '');
			$('#' + subPage).css('display', 'block');	
			
		}
		lastSubNavBtnClicked = $(this);
	});
	
	// Sets click functions for films listed in 'About | Show'
	$('#show_filmlist p').live('click', function(){
		var $aList = $('#show_filmlist p');
		var filmIndex = $aList.index($(this));
		$('#navbar_btn1').click();
		$('#minimapBlock' + (80+((filmIndex+0.5)*2))).click();
	});
	
	// load full site content if supported		
	if(showFullSite == true) {
		
		// sets load event used to delay showing the clip grid until all the thumbnails are loaded
		// NB THIS MAY NOT WORK IN IE		
		$('#base_layer_container .block_thumb, #base_layer_container .block_thumb_hd').load(function(){
			incrementThumbsLoaded();
		});
		
		// handles starting clip, including 'one-page' behaviour -- www.littlefilms.ca/translator should load the page, then take us to the 'Translator' excerpt
		// will have to change for actual site -- add prelim test to check if there is any pathname before looping
		startingExcerpt = getGETvars()['film'];
		window.firstClip = $('#minimapBlock1');
		
		for(var i=0; i<excerptOrder.length; i++){
			if(startingExcerpt==excerptOrder[i]){
				firstClip=$('#minimapBlock' + (81 + (i * 2)));
			}
		}		
		
		// makes YouTube API call
		getYtData(1);	
		
		window.$baseLayer=$('#base_layer_container');
	
		// Manually set base layer state
		$baseLayer.data('currentRow', 1).data('currentColumn', 1)
			.data('previousRow', 2).data('previousColumn', 2)
			.data('destinationRow', 1).data('destinationColumn', 1)
			.data('animating', false);
		
		// Add target rows/cols to nav buttons
		
		updateNavButtonTargets($baseLayer, false, 'up', 'back', false);
		
		// Sets click functions for tag category buttons
		$('#tag_people, #tag_films, #tag_more').click(function(){
			var thisBtn = $(this);
			if(!thisBtn.hasClass('selected')){
				$('#tag_header .tag_btn').removeClass('selected');
				thisBtn.addClass('selected');
				$('#dynacloud_container .dynacloud').css('display', 'none');
				$('#' + thisBtn.attr('id').replace('tag', 'dynacloud')).css('display', 'inline');
			}		
		});
		
		// Sets click function for nav buttons
		// (disabled as it's slower) $('.nav_button:not(.disabled)').live('click', function() {
		$('#nav_up:not(.disabled), #nav_back:not(.disabled), #nav_down:not(.disabled), #nav_forward:not(.disabled)').live('click', function() {
			if($baseLayer.data('animating')==false){
			 	switchClips($(this).data('row'), $(this).data('column'));
			} else {
				//console.log("Animation in Progress. Click disabled.");
			}
		});
		
		// Sets click function for clips in minimap
		$('#minimap .mm_block').live('click', function() {
			if($baseLayer.data('animating')==false){
				if(!$(this).hasClass('minimap_current')){
					var blockClasses = $(this).attr('class');		
					var row = blockClasses.substring(blockClasses.indexOf('row')+3, blockClasses.indexOf(' ', blockClasses.indexOf('row')));
					var column = blockClasses.substring(blockClasses.indexOf('column')+6, blockClasses.length);
					
					switchClips(parseInt(row), parseInt(column));
					
					//console.log('from minimap: row: ' + row + ' | column: ' + column);
				}
			} else {
				//console.log("Animation in Progress. Click disabled.");
			}
		});
		
		// Sets click function for 'explore' button which appears when in the last column (HD excerpts)
		
		$('#btn_explore').live('click', function(){
			$('#nav_back').click();
		});
		
	} else {
		// limit site to 'overlay' content (about / press / contact)
		
		// display 'about' tab
		$('#navbar_btn1').click();
		
	}
		
	//console.log('document.ready done!');
	


});

function dropInColumn(k){	
	if(k==6){
		$('#minimap_yah').css('visibility', 'visible');
		$('#minimap_indicator').css('visibility', 'visible');
		window.firstClip.click();
	} else if(k>1 && k<6){
		$('#minimapColumn'+k).animate({
			top: "+=362px"
		}, 500, "easeInExpo");
		
		$('#column_'+k).animate({
			top: "+=4480px"
		}, 500, "easeInExpo", function(){
			k++;
			dropInColumn(k);
		});
	} else if(k==1){
		//fadeTo breaks IE8 png alpha transparency
		if($.browser.msie){
			$('#nav_up, #nav_down, #nav_back, #nav_forward, #minimap, #tag_container').css('visibility', 'visible');
			$('#minimapColumn1').animate({
				top: "+=362px"
			}, 500, "easeInExpo");
			
			$('#column_1').animate({
				top: "+=4480px"
			}, 500, "easeInExpo", function(){
				k++;
				dropInColumn(k);
			});
		} else {
			$('#nav_up, #nav_down, #nav_back, #nav_forward, #minimap').css('opacity', '0').css('visibility', 'visible').fadeTo('normal', 1);
			$('#tag_container').css('opacity', '0').css('visibility', 'visible').fadeTo('normal', 1, function(){
				$('#minimapColumn1').animate({
					top: "+=362px"
				}, 500, "easeInExpo");
				
				$('#column_1').animate({
					top: "+=4480px"
				}, 500, "easeInExpo", function(){
					k++;
					dropInColumn(k);
				});
			});
		}	
	}
}
	
function switchClips(toRow, toColumn) {
	//display loading animation
	$('#context_header').addClass('loading');
	
	//set nav buttons to appear disabled
	$('#nav_up, #nav_down, #nav_back, #nav_forward, #btn_explore').addClass('tempDisabled');
	
	var	$baseLayer=$('#base_layer_container');
	var fromRow;
	var fromColumn;
	
	var toLargeClip = false;
	var toEdgeRow;
	var toEdgeColumn;
	
	// if moving from column four to five, need to cheat and add a vertical component for lower of two rows
	var cheatUp = false;
	
	var sizeTransition = "none";
	
	var deltaBsLyr = {};
	var deltaMinimap = {};
	var animateTime = null;
	
	// update base layer state
	$baseLayer.data('previousRow', $baseLayer.data('currentRow')).data('previousColumn', $baseLayer.data('currentColumn'))
		.data('currentRow', 0).data('currentColumn', 0)
		.data('destinationRow', toRow).data('destinationColumn', toColumn);

	fromRow = $baseLayer.data('previousRow');
	fromColumn = $baseLayer.data('previousColumn');
	
	// update minimap current highlight
	fromMMBlock = (parseInt(fromColumn)-1)*20+parseInt(fromRow);
	toMMBlock = (parseInt(toColumn)-1)*20+parseInt(toRow);
	$('#minimapBlock' + fromMMBlock).removeClass('minimap_current');
	$('#minimapBlock' + toMMBlock).addClass('minimap_current');
	
	// update highlighted tags (first remove, then add)
	var currentTags = tagsArray['#minimapBlock' + fromMMBlock];
	for(var i=0; i<currentTags.length; i++){
 		//console.log('currentTag :' + currentTags[i]);
		var currentTagString = currentTags[i].replace(/[': %&;]/g, '');
		$('#' + currentTagString).removeClass('bluelight');
	}
	
	currentTags = tagsArray['#minimapBlock' + toMMBlock];
	for(var i=0; i<currentTags.length; i++){
 		//console.log('currentTag :' + currentTags[i]);
		var currentTagString = currentTags[i].replace(/[': %&;]/g, '');
		$('#' + currentTagString).addClass('bluelight');
	}
	
	// pause video in current row/column
	
	if(fromColumn<5){
		var blockNumber=(fromRow-1)*5+fromColumn;
	} else {
		var blockNumber=(Math.round(fromRow/2)*5);
	}

	if(document.getElementById('ytVideoPlayer_' + blockNumber)){
		var ytPlayer=document.getElementById('ytVideoPlayer_' + blockNumber);
		ytPlayer.pauseVideo();	
	}
	
	//$('#block_' + blockNumber).css('opacity', '0.35');
		
	// resolve characteristics of destination (ie edge row/col, large clip)
	if(toColumn==5){
		toLargeClip = true;
		toEdgeColumn = "forward";
	} else if(toColumn == 1){
		toEdgeColumn = "back";
	}
	
	if(toRow==1){
		toEdgeRow = "up";
	} else if(toRow==20 || (toRow==19 && toLargeClip==true)){
		toEdgeRow = "down";
	}
	
	if(toColumn == 4 && toRow % 2 == 0){
		cheatUp = true;
	}
		
	if(fromColumn <5 && toColumn == 5){
		sizeTransition = "sm_to_lg";
	}
	
	if(fromColumn==5 && toColumn < 5){
		sizeTransition = "lg_to_sm";
	}
	
	// set button states
	updateNavButtonTargets($baseLayer, toLargeClip, toEdgeRow, toEdgeColumn, cheatUp);
	
	
	// calculate distances
	deltaBsLyr.x = -(toColumn-fromColumn)*(smClip.width+gutter);
	deltaBsLyr.y = -(toRow-fromRow)*(smClip.height+gutter);
	
	deltaMinimap.x = (toColumn-fromColumn)*(smClipMM.width+gutterMM);
	deltaMinimap.y = (toRow-fromRow)*(smClipMM.height+gutterMM);
	 
	//console.log('Delta baselayer: ' + Math.sqrt(deltaBsLyr.x*deltaBsLyr.x+deltaBsLyr.y*deltaBsLyr.y));
	
	var deltabaselayer = Math.sqrt(deltaBsLyr.x*deltaBsLyr.x+deltaBsLyr.y*deltaBsLyr.y);
	if(deltabaselayer<2085){
		animateTime=1000;
	} else {
		animateTime=2000;
	}
	
	//console.log('animateTime: ' + animateTime);
	
	// load quote & kill caption
	if(toColumn<5){
		loadQuote(toColumn);
		$('#caption').html('<p>Loading caption...</p>');
	}
	
	// animate base layer and minimap
	$('#base_layer_container').data('animating', true)
	
	// this ungainly split of the minimap animation between here and adjustViewport() is necessary to animate the size adjust and translation synchronously
	// since we don't see it -- cheat?
	// (right now lg-to-sm calls move and shrink simutaneously; sm-to-lg calls move first, then grow with a callback)
	
	if(sizeTransition=="lg_to_sm"){
		adjustViewport("shrink");
		$('#minimap_indicator').animate({
			top: "+=" + deltaMinimap.y + "px",
			left: "+=" + deltaMinimap.x + "px"		
		}, 1000, "swing");
		
	} else {
		$('#minimap_indicator').animate({
			top: "+=" + deltaMinimap.y + "px",
			left: "+=" + deltaMinimap.x + "px"
		}, animateTime, "swing");
	}
		
		
	$('#base_layer_container').animate({
			top: "+=" + deltaBsLyr.y + "px",
			left: "+=" + deltaBsLyr.x + "px"
		}, animateTime, "swing", function(){
			if(sizeTransition=="sm_to_lg"){
				adjustViewport("grow", toRow, toColumn);
			} else {
				// the below is either called here (if viewport stays the same size) or in the adjustViewport function
				//console.log("calling startVideo");
				startVideo(toRow, toColumn);
			}
		}
	);
			
	// update base layer state
	$baseLayer.data('currentRow', toRow).data('currentColumn', toColumn)
		.data('destinationRow', 0).data('destinationColumn', 0);
	
	// logging
/*
	//console.log('..............................................');
	//console.log('Previous row: ' + $baseLayer.data('previousRow') + ' | column: ' + $baseLayer.data('previousColumn'));
	//console.log('Current  row: ' + $baseLayer.data('currentRow') + ' | column: ' + $baseLayer.data('currentColumn'));
	//console.log('Button Targets');
	//console.log('		' + $('#nav_up').data('row') + "," + $('#nav_up').data('column'));
	//console.log($('#nav_back').data('row') + "," + $('#nav_back').data('column') + '				' + $('#nav_forward').data('row') + "," + $('#nav_forward').data('column'));
	//console.log('		' + $('#nav_down').data('row') + "," + $('#nav_down').data('column'));
	
	//console.log("viewport adjustment: " + sizeTransition);
	//console.log("cheat up: " + cheatUp);
*/
}
	

function startVideo(row, column){
	//console.log("startVideo called");
	
	if(column<5){
		blockNumber=(row-1)*5+column;
	} else {
		blockNumber=(Math.round(row/2)*5);
	}
	
	$block = $('#block_' + blockNumber);
	
	$('#context_container #caption').replaceWith('<div id="caption"><p>' + $block.data('caption') + '</a></p></div>');
	
	if($('#ytVideoPlayer_' + blockNumber).length == 0){
		// if we have not loaded the player for this grid block yet
		if(column<5){
			videoLoadHTML='<div id="ytVideo_' + blockNumber + '">'+
			'<script type="text\/javascript">'+
		    'var params = { allowScriptAccess: "always", wmode: "opaque"  };'+
			'var atts = { id: "ytVideoPlayer_'+ blockNumber + '"};'+
			'swfobject.embedSWF("http:\/\/www.youtube.com\/v\/' + $block.data('id') + '&enablejsapi=1&playerapiid=ytVideoPlayer_'+ blockNumber + '&rel=0&showinfo=0&disablekb=1&iv_load_policy=3&autoplay=0", "ytVideo_' + blockNumber + '", "320", "205", "8", null, null, params, atts);'+
			'<\/script></div>';
		} else {
			videoLoadHTML='<div id="ytVideo_' + blockNumber + '">'+
			'<script type="text\/javascript">'+
		    'var params = { allowScriptAccess: "always", wmode: "opaque"  };'+
			'var atts = { id: "ytVideoPlayer_'+ blockNumber + '"};'+
			'swfobject.embedSWF("http:\/\/www.youtube.com\/v\/' + $block.data('id') + '&enablejsapi=1&playerapiid=ytVideoPlayer_'+ blockNumber + '&hd=1&rel=0&showinfo=0&disablekb=1&iv_load_policy=3&autoplay=0", "ytVideo_' + blockNumber + '", "660", "430", "8", null, null, params, atts);'+
			'<\/script></div>';
		}	
		
		
		$('.video_thumbnail', $block).fadeOut("normal", function(){
			$block.find('.scrim_img').css('display', 'none');
			$block.append(videoLoadHTML);
		});
	} else {
		onYouTubePlayerReady();
	}
	//console.log('startVideo done');
}

function onYouTubePlayerReady(){
	//console.log('onYouTubePlayerReady called');
	ytPlayer = document.getElementById('ytVideoPlayer_' + blockNumber);
	playCount+=1;	
	ytPlayer.addEventListener('onStateChange', 'onYTStateChange');
	ytPlayer.addEventListener('onError', 'onYTError');
	ytPlayer.playVideo();

	if($baseLayer.data('currentColumn') == 5){
		//console.log('Switching video to 480p');
		setTimeout('ytPlayer.setPlaybackQuality("large"); //console.log("playYtVideo done");', 500);
	} else {
		//console.log("onYouTubePlayerReady done");
	}	
}
	
function updateNavButtonTargets($baseLayer, toLargeClip, toEdgeRow, toEdgeColumn, cheatUp){
	// Update targets for buttons -- this has to be done every move and on page load	
	var k=1;
	var l=0;
	
	//adjust these based on tests earlier
	if(toLargeClip==true){k=2};
	if(cheatUp==true){l=1};
	
	$('#nav_up').data('row', $baseLayer.data('destinationRow')-k*1).data('column', $baseLayer.data('destinationColumn'));
	$('#nav_down').data('row', $baseLayer.data('destinationRow')+k*1).data('column', $baseLayer.data('destinationColumn'));
	$('#nav_forward').data('row', $baseLayer.data('destinationRow')-l).data('column', $baseLayer.data('destinationColumn')+1);
	$('#nav_back').data('row', $baseLayer.data('destinationRow')).data('column', $baseLayer.data('destinationColumn')-1);
	
	
	// enable and disable buttons as necessary
	if(toEdgeRow){
		$('#nav_' + toEdgeRow + ':not(.disabled)').addClass('disabled');

		if(toEdgeRow=='up' && $('#nav_down').hasClass('disabled')){
			$('#nav_down').removeClass('disabled');
		}
		if (toEdgeRow=='down' && $('#nav_up').hasClass('disabled')){
			$('#nav_up').removeClass('disabled');
		}
	} else {
		$('#nav_up,#nav_down').each(function(){
			if($(this).hasClass('disabled')){$(this).removeClass('disabled');}
		});
	}
	
	if(toEdgeColumn){
		$('#nav_' + toEdgeColumn + ':not(.disabled)').addClass('disabled');
		
		if(toEdgeColumn=='back' && $('#nav_forward').hasClass('disabled')){
			$('#nav_forward').removeClass('disabled');
		}
		if (toEdgeColumn=='forward' && $('#nav_back').hasClass('disabled')){
			$('#nav_back').removeClass('disabled');
		}
	} else {
		$('#nav_back,#nav_forward').each(function(){
			if($(this).hasClass('disabled')){$(this).removeClass('disabled');}
		});	
	}
}
	
function adjustViewport(adjustType, toRow, toColumn){
	var k;
	
	if(adjustType=="shrink"){
		k = "-=";
		$('#nav_forward').fadeIn();
		$('#btn_explore').fadeOut(250);
	} else if(adjustType=="grow"){
		k = "+=";
		$('#nav_forward').fadeOut();
	}
	
	$('#base_layer_container, #context_container, #navigation_container').animate({
		left: k + "-476px" //(smClip.width + gutter)*(-1.4)
	}, 1000, "swing");
	
	$('#nav_back').animate({	
		left: k + "-476px" // (smClip.width + gutter)*(-1.4)
	}, 1000, "swing");

	$('#nav_down').animate({
		top: k + (smClip.height + gutter)
	}, 1000, "swing", function(){
		if(adjustType=="grow"){
			$('#btn_explore').fadeIn(250);
			//console.log("calling startVideo");
			startVideo(toRow, toColumn);
		}
	});
	
	
}


// Read a page's GET URL variables and return them as an associative array.
function getGETvars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

pageFullyLoaded = (function(){
	//console.log('pageFullyLoaded called')
	var timesCalled = 0;
	return function(){
		if(timesCalled>0){
			return;
		}
		timesCalled++;
		//console.log('Page + video load complete');
	};
})();


// Loads quotes via AJAX
function loadQuote(column) {
	//console.log('loadQuote called');
	$.ajaxSetup({
		cache: false
	});
	
	var ajax_load = "<p>Loading quote...</p>";
	var stage;
	
	if(column==1){
		stage="1";
	} else if(column==4){
		stage="3";
	} else if(column==2 || column == 3){
		stage="2";
	}
	
	var load_url = "quotes.php?stage=" + stage;
	
	$("#quote").html(ajax_load).load(load_url);
	//console.log('loadQuote done');
}

function fisherYates ( myArray ) {
  var i = myArray.length;
  if ( i == 0 ) return false;
  while ( --i ) {
     var j = Math.floor( Math.random() * ( i + 1 ) );
     var tempi = myArray[i];
     var tempj = myArray[j];
     myArray[i] = tempj;
     myArray[j] = tempi;
   }
}

function onYTStateChange(state){
	//console.log("Video state change registered: " + state);
	
	//plays next video in row on finish
	if(state==0){
		if($baseLayer.data('currentColumn')<5){
			//console.log("Moving to next video in row...");
			$("#nav_forward").click();
		}
	}
	
	//keeps nav controls inactive until video is finished buffering and has started playing
	if(state==1){
		//console.log('made it to if');
		//console.log('animating: ' + $baseLayer.data('animating'));
		//if this is the first play, call our fake document.ready analog
		if(playCount==1){
			pageFullyLoaded();
		};
		if($baseLayer.data('animating')==true){
			//console.log('made it to if 2');
			$baseLayer.data('animating', false);
			//set nav buttons to appear enabled
			$('#nav_up, #nav_down, #nav_back, #nav_forward, #btn_explore').removeClass('tempDisabled');
			$('#context_header').removeClass('loading');
		}
	}
	ytPlayerState=state;
	//console.log('onYTStateChange done');
}

function onYTError(error){
	//console.log("YouTube Error: " + error);
	if($baseLayer.data('animating')==true){
		$baseLayer.data('animating', false);
	}
}

function createCloud(sort, inMax){
	var cloud = {};
	//console.log('createCloud called');
	//console.log('indexing tagsArray: ' + window.tagsArray.length + ' items');
	for(var h in tagsArray){
		//console.log('tagsArray ' + h + ': ' + tagsArray[h]);
		var tagString = "" + tagsArray[h];
		var elems = tagString.replace(/[^A-Z\xC4\xD6\xDCa-z\xE4\xF6\xFC\x,\x'\x:\x?\x.\-\x \xDF0-9_]/g, '').split(',');
		for(var i=0; i<elems.length; i++){
			var cl = [];
			var max = 0;
			var t = elems[i].toLowerCase();
			if (typeof cloud[t] == 'undefined') {
				cloud[t] = { count: 1, el: elems[i] };
			} else {
				cloud[t].count += 1;
			}
			max = Math.max(cloud[t].count, max);
		}
	}
	
	$.each(cloud, function(i, n) {
		cl[cl.length] = n;
	});
		
	cl.sort(sortByTag);
/*
	if(sort==true) {
		cl.sort(function(a, b) {
		   	if (a.count == b.count) {
	  			return a.el < b.el ? -1 : (a.el == b.el ? 0 : 1);
    		} else {
     			return a.count < b.count ? 1 : -1;
    		}
		});
	}
*/	
	var out1 = $('#dynacloud_people');
	var out2 = $('#dynacloud_films');
	var out3 = $('#dynacloud_more');
			
	out1.empty();
	out2.empty();
	out3.empty();
	
	var regexCaps = /[A-Z]/;
	
	var listStringPeople = '<ul>';
	var listStringFilms = '<ul>';
	var listStringMore = '<ul>';
	
  	//var l = inMax == -1 ? cl.length : Math.min(inMax, cl.length);

	//console.dir(tagsArray);
	
  	for (var i = 0; i < cl.length; ++i) {
  		//console.log(cl[i]);
  		var tagStringID = cl[i].el;
  		//console.log(tagStringID);
  		//console.log('after regex: ' + tagStringID.replace(/[': %&;]/g, ''));
 		if(cl[i].el.search(regexCaps)!=-1){
 			if(cl[i].el in {"Appliance": "", "Rockin' the Rainbow": "", "Fat Chance": "", "My Boyfriend's Package": "", "2:14 PM": "", "The Day I Thought I Died": "", "Happy Pills":"", "Do You Want Out?":"", "Dinner at Lucy's":"", "The Translator":""}) {
				listStringFilms+=('<li><a href="#' + cl[i].el + '"" id="' + tagStringID.replace(/[': %&;]/g, '') + '"><span>' + cl[i].el + '</span></a></li>');
			} else {
				listStringPeople+=('<li><a href="#' + cl[i].el + '"" id="' + tagStringID.replace(/[': %&;]/g, '') + '"><span>' + cl[i].el + '</span></a></li>');
			}
 		} else {
 			listStringMore+=('<li><a href="#' + cl[i].el + '"" id="' + tagStringID.replace(/[': %&;]/g, '') + '"><span>' + cl[i].el + '</span></a></li>'); 	 	
   		}
   	}

  	listStringPeople+=('</ul>');
  	listStringFilms+=('</ul>');
  	listStringMore+=('</ul>');
  	  	
  	out1.append(listStringPeople); 
  	out2.append(listStringFilms);
  	out3.append(listStringMore);
  	  	
  	$('#dynacloud_container a').each(function() {
   		$(this).click(function() {
			//console.log('Tag click registered');
    		if($(this).hasClass('highlight')==true){    	
		    //deselect this object
	    	//remove highlights
			    $('#minimap .mm_block.noise_highlight').removeClass('noise_highlight');
			    $('#dynacloud_container a').removeClass('highlight');
			} else {
				//select new object
					//remove highlights
			   	$('#minimap .mm_block.noise_highlight').removeClass('noise_highlight');
			    $('#dynacloud_container a').removeClass('highlight');
					//add highlights
				$(this).addClass('highlight');
			
				var blockData = $(this).text().toUpperCase();
				//console.log(blockData);
				//console.dir(window.tagsArray);
				for(var i in window.tagsArray){
					var tagString = "" + window.tagsArray[i];
					if(tagString.toUpperCase().indexOf(blockData)!=-1){
						//console.log('matched tag found');
						$(i).addClass('noise_highlight');
					}
				}		
			}	
   		return false;
   		});
  	});
}

function sortByTag(a,b){
	var x = a.el.toLowerCase();
    var y = b.el.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
