var indexVideosLoaded = false;
var videosInThumbBox = 0;
var scrollPos = 1;
var shareWrapped = false;
var maxVidSize = 980;
var moving = false;
var maximise = false;
var prevVid = 0;
var videoPlaying = false;
var totalLoadingVids = 0;
var playIt = false;
function appendNextImage(jsonVar) {
		var newVidDiv = document.createElement("div");
		vidId = totalVids + 1;
		newVidDiv.id = "video" + vidId;
		newVidDiv.className = "secondaryVideo";
		newVidDiv.style.display = "none";	
		
		var newVidThumb = new Image();
		$(newVidThumb).hide();
		$(newVidThumb).load(function(){
			$(this).hide();
			$(this).parent()[0].style.background = "#fff";
			$(this).fadeIn();
		});
		newVidThumb.src = linkRoot+jsonVar.content.videoStill;
		$(newVidThumb).width(videoWidth);
		$(newVidThumb).height(videoHeight);
		$(newVidDiv).width(videoWidth);
		$(newVidDiv).height(videoHeight);	
		newVidDiv.style.background = "url("+linkRoot+"/images/loading.gif) no-repeat center center";
		newVidDiv.appendChild(newVidThumb);		
		// assign onclick
		newVidDiv.onclick = new Function('moveTo('+vidId+')');
		$('#videoSlider').append(newVidDiv);
		
		
		$(newVidDiv).fadeIn(animationSpeed);	
		
		// update variables
		videoArray.push(
		{"videoTitle":jsonVar.content.videoTitle,
		"videoClient":jsonVar.content.videoClient,"videoVimeo":jsonVar.content.videoVimeo,
		"videoLink":jsonVar.content.videoLink,"videoContent":jsonVar.content.videoContent,
		"id":jsonVar.content.id,"videoStill":jsonVar.content.videoStill,
		"videoTags":jsonVar.content.videoTags}
			);
		totalVids++;
		// increase width of slider
		newSliderWidth = totalVids * (videoWidth +40);
		$('#videoSlider').css('width',(newSliderWidth + " px"));
		$('#videoSliderVid').css('width',(newSliderWidth + " px"));
	}
function expandVidIndex() {
	if($('#alternateVidsContainer').is(':hidden')){
			$('#alternateVidsContainer').slideDown(function(){
				window.location.hash = "vidsBox";
				});
			$('#alternatevidsinfo a').css('background-image','url(images/downArrow.gif)');
			$('.vidSearch').fadeIn();
			refreshVidIndex();
			
		} else {
			$('#alternateVidsContainer').slideUp();
			$('#alternatevidsinfo a').css('background-image','url(images/upArrow.gif)');
			$('.vidSearch').fadeOut();
			$('.altVidsFoot').animate({opacity : '1'}, 400);
			window.location.hash = "";
		}
	}
function showSearch() {
	if($('#alternateVidsContainer').is(':hidden')){
			$('#alternateVidsContainer').slideDown(function(){
				window.location.hash = "vidsBox";
				});
			$('#alternatevidsinfo a').css('background-image','url(images/downArrow.gif)');
			$('.vidSearch').fadeIn();
			refreshVidIndex();
			
		} else {
			$('.altVidsFoot').animate({opacity : '1'}, 400);
		}
	
}
function checkVid(vId, theHref){
	//console.log(vId);
	//checks whether the linked video is already loaded on the page - if it is, we move to it
	retVar = true;
	for(i=0;i<videoArray.length;i++){
		if(videoArray[i].id==vId){
			retVar = false;
			moveTo(i+1);	
			break;	
		}	
	}
	if(retVar){window.location = theHref;}
	//return retVar;
}
function loadIndexVideos(json) {
	var divCounter = 0;
	$.each(json,function(index,thumbData) {
			divCounter ++;
		// Create Thumb Div
			var thumbCont = document.createElement("div");
			thumbCont.className = "thumbContainer";
			thumbCont.id = "thumbCont"+divCounter;
		// Create Thumb Anchor tag
			var thumbAnchor = document.createElement("a");
			thumbAnchor.href = "#";
			//thumbAnchor.href = linkRoot+"videos/"+escape(thumbData.videoLink);
			thumbAnchor.videoTitle = thumbData.videoTitle;
			thumbAnchor.onclick = new Function("checkVid('"+thumbData.id+"', '"+linkRoot+"videos/"+escape(thumbData.videoLink)+"');return false;");
		// Create overlay info div
			var thumbInfo = document.createElement("div");
			thumbInfo.className = "thumbInfoOverlay";
			thumbInfo.id = "thumbInfoOverlay"+divCounter;
			thumbInfo.innerHTML = thumbData.videoTitle;
			$(thumbInfo).click(function(){
				checkVid(thumbData.id, linkRoot+"videos/"+escape(thumbData.videoLink));
				//window.location = linkRoot+"videos/"+escape(thumbData.videoLink);
			});
		// Create Thumb Image
			var thumbImage = new Image();
		//Append them all together
			thumbImage.src = linkRoot+thumbData.videoThumb
			thumbCont.appendChild(thumbAnchor);
			thumbCont.appendChild(thumbInfo);
			thumbAnchor.appendChild(thumbImage);
			$(thumbCont).hide();
		// Append the thumb div			
			$('#alternateVidsDetails').append(thumbCont);
			$(thumbCont).fadeIn('slow');
			$(thumbCont).hover(function(){$(thumbInfo).show();},function(){$(thumbInfo).hide();});
	});
	indexVideosLoaded = true;
	videosInThumbBox = divCounter;
}
function toggleMoreInfo() {
		if($('#contentInfoText').is(':hidden')){
				$('#contentInfoText').slideDown();
				$('#moreInfoButton').text("less info -");
				$('#alternateVidsContainer').slideUp();
				$('.vidSearch').fadeOut();
			}else {
				$('#contentInfoText').slideUp();
				$('#moreInfoButton').text("more info +");
				$('#alternateVidsContainer').slideDown();
				$('.vidSearch').fadeIn();
			}
	}

function loadNextVids(){
	if(currentVid > (totalVids-3)){
		tVid = totalLoadingVids;
		totalLoadingVids ++;
		$.getJSON(linkRoot+'json.php?query='+escape(jsonQuery)+'&vid='+tVid, function(json){
			if(json){
				
				appendNextImage(json);
			}else {
				console.log("image load failed or no more images");
			}
			
			if(!maximise){
				$('#vimeoVid').width(newVimeoWidth).height(newVidHeight);
				}
		});
		}
}
function moveLeft() {
	if(currentVid > 1){
		prevVid = currentVid;
		currentVid --;
		// animate movement left
		moving = true;
		videoPlaying = false;
		$('#videoSlider').animate({
			left: '+='+videoWidth
			}, animationSpeed, function() {
				moving = false;
				
				});
				
		// animate fade up of new image
		$('#video'+currentVid+' img').animate({opacity : '1'}, animationSpeed, function(){});
		// animate fade out of old image
		$('#video'+prevVid+' img').animate({opacity : '0.2'}, animationSpeed, function(){});
		// change Video Description text
		updateVideoText();
	}
}

function moveTo(videoNumber){

	if(videoNumber==currentVid){
		//show its video
			if($('#staticDivHolder').length == 0 || $('#staticDivHolder').is(':hidden')){
				videoClick(videoNumber);
			}
		} else {
			videoPlaying= false;
			differenceToMove = videoNumber - currentVid;
			distanceToMove = videoWidth * differenceToMove;
			if(differenceToMove >0){
				loadNextVids();
			}
			prevVid = currentVid;		
			currentVid = currentVid + differenceToMove;	
			moving = true;
			$('#videoSlider').animate({
			left: '-='+distanceToMove
			}, 1000, function() {
				moving = false;
				});
				
				if(prevVid == 1) {
					$('#video'+prevVid).removeClass("vidActivated");
					$('#video'+prevVid+' img').css('opacity','1');
					};
				updateVideoText();	
		}
}

function moveRight(toPlay){
	if(toPlay){playIt= true;}
	loadNextVids();

	if(currentVid < totalVids){	
		prevVid = currentVid;	
			
		currentVid ++;	
		moving = true;
		$('#videoSlider').animate({
		left: '-='+(videoWidth)
		}, 1000, function() {
			moving = false;
			// if we're meant to play it, play the video

				if(playIt){
						
						videoPlaying = false;
							moveTo(currentVid);
							playIt = false;
					}	
			});
		
		if(prevVid == 1) {
			$('#video'+prevVid).removeClass("vidActivated");
			$('#video'+prevVid+' img').css('opacity','1');
			};
		
		updateVideoText();
		
		}
	}
function updateVideoText(){

				// animate fade up of new image
				$('#video'+currentVid+' img').animate({opacity : '1'}, animationSpeed, function(){});
				// animate fade out of old image
				$('#video'+prevVid+' img').animate({opacity : '0.2'}, animationSpeed, function(){});
				// change Video Description text
				// 1. Hide the current video description if visible
					if($('#contentInfoText').is(':visible')){
							$('#contentInfoText').hide();
							$('#moreInfoButton').text("more info +");
						}
				// 2. fade out the videoTitle div
				if(videoArray[(currentVid-1)].videoClient==null){videoArray[(currentVid-1)].videoClient = " ";}
					$('#contentvideoTitle').hide();
					// a. videoTitle
						$('#videoTitle').text(videoArray[(currentVid-1)].videoTitle);
					// b. Client
						$('#videoClient').text(videoArray[(currentVid-1)].videoClient);
					// c. Content
						$('#contentTextArea').text(videoArray[(currentVid-1)].videoContent);
					// d. Tags
						$('#contentTags').empty();
						addContentTags(videoArray[(currentVid-1)].videoTags);
					// e. Permalink
						createPermalink(videoArray[(currentVid-1)].videoLink,videoArray[(currentVid-1)].videoTitle);
						// 4. If video's showing, replace it with the thumbnail...
					if($('#video'+prevVid+' #vimeoVid')){
						var newImage = new Image();
					
						$('#maxit').remove();
						
						$('#video'+prevVid+' #vimeoVid').replaceWith($('#imageHolder img'));
						videpPlaying = false;
					}
				// 5. Fade in the new videoTitle
					$('#contentvideoTitle').fadeIn('slow');
	
}
function addContentTags(tags) {
		$.each(tags,function(index,tag){
			var tempLink = document.createElement("a");
			tempLink.href = linkRoot+"tags/"+escape(tag);
			$(tempLink).text(tag);
			$('#contentTags').append(tempLink);
			$('#contentTags').append(",&nbsp;");
		});
	}
function createPermalink(permaLink, videoTitle) {
	permaHref = linkRoot+"videos/"+permaLink;
	$('#contentPermalink')[0].href = permaHref;
	//$('#contentPermalink').text(linkRoot+"/videos/"+permaLink);
	// create share this links:
	destinations = [['shareFB','facebook'],['shareTB','tumblr'],['shareEM','email'],['shareIN','linkedin'],['shareTWT','twitter'],['shareGGL','google']];
	var tC;
	
	for(tC=0;tC<destinations.length;tC++){
		if(shareWrapped){
		//unwrap all previous wraps
			$('#'+destinations[tC][0]).unwrap();
		}
		thisLink = 'http://rest.sharethis.com/share/sharer.php?destination='+destinations[tC][1]+'&url='+escape(permaHref)+'&title='+escape(videoTitle)+'&pub_key=1c09cfb3-36b9-405e-9500-a7f76aaf5ce0&access_key=7e348cff85ee34990ed4ef0749773370';
		// unbind any previous actions:
	
		$('#'+destinations[tC][0]).wrap('<a href="'+thisLink+'" target="_blank" title="Share on '+destinations[tC][1]+'"/>');
			
		}	
	shareWrapped=true;
}
function videoClick(vidNo) {
		if(!moving && !videoPlaying){
			vimeoURL = '10438661';
			vimeoURL = videoArray[(vidNo-1)].videoVimeo;
			$('#imageHolder').append($('#video'+vidNo+' img'));
			$('#video'+vidNo).append('<iframe id="vimeoVid" src="http://player.vimeo.com/video/'+vimeoURL+'?api=1&title=0&amp;byline=0&amp;portrait=0&amp;color=ffffff&amp;autoplay=1&amp;player_id=vimeoVid" width="'+(videoWidth+1)+'" height="'+videoHeight+'" frameborder="0"></iframe>');
			if(!isMobile){
			// don't show the maximise button if viewing on a mobile platform
				$('#video'+vidNo).append(createMaximise());
			}
			Froogaloop($('#vimeoVid')[0]).addEvent('ready',frReady);
			videoPlaying = true;
			//$('#video'+vidNo).append('<iframe id="vimeoVid" src="http://player.vimeo.com/video/'+vimeoURL+'?videoTitle=0&amp;byline=0&amp;portrait=0&amp;color=ffffff&amp;autoplay=1" width="'+videoWidth+'" height="'+videoHeight+'" frameborder="0"></iframe>')
		}
	}
function frReady(playerID){
	Froogaloop(playerID).addEvent('playProgress',function(data){
		if(data.percent > 0.995){
		moveItR(playerID);
		
		}
	});
}
function moveItR(playerID){
		Froogaloop(playerID).removeEvent('playProgress');
		Froogaloop(playerID).api('unload');
		setTimeout("moveRight(true);", 1000);
}
function moveThumbRight() {
	var thumbMovement = 810;
	var thumbsPerScreen = 5
	if(videoWidth!=888){ thumbMovement = 324;thumbsPerScreen=2;}
		if(videosInThumbBox > (thumbsPerScreen*scrollPos)){
			//move it right 810 pixels
			$('#alternateVidsDetails').animate({left:'-='+thumbMovement}, 'slow');
			scrollPos++;
		}
}
function moveThumbLeft() {
	var thumbMovement = 810;
	if(videoWidth!=888){ thumbMovement = 324;}
		if(scrollPos > 1){
			//move it left 810 pixels
			$('#alternateVidsDetails').animate({left:'+='+thumbMovement}, 'slow');
			scrollPos --;
		}
	}
function runVideoSearch(searchValue) {
	if(searchValue.length > 1){
	$.getJSON(linkRoot+'videosearch.php?search='+escape(searchValue),function(json){
		if(json.length !=0){
			
			processVidSearch(json);
		} else {
			//empty bottom contents
				$('#alternateVidsDetails').empty();
				$('#alternateVidsDetails').append('<div style="margin:45px;">No Results</div>');
		}
	});
	}
}
function processVidSearch(json){
	// clear out the old videos
	$('#alternateVidsDetails').empty();
	videosInThumbBox = 0;
	loadIndexVideos(json);
	
}
function managePageResize(){
	if($(window).height()<644 && !isMobile){
			$('#alternateVidsFooter').removeClass().addClass('altVidsFootFixed');
		}else{
			$('#alternateVidsFooter').removeClass().addClass('altVidsFoot');
		}
	if($(window).height()<700 && !isMobile){
			//
			$('#siteNav').css('margin','10px 0px 10px');
		} else {
		if(!isMobile){
			$('#siteNav').css('margin','30px 0px 30px');
			}
		}
	if(!isMobile){
		wHeight = $(window).height();
				if(wHeight < 720 && wHeight > 643){
					$('#contentInfoText').height(80);
					}else {
					$('#contentInfoText').height('auto');
					}
				if(wHeight < spaceRatio){wHeight = spaceRatio;}
				if(wHeight > maxVidSize){wHeight = maxVidSize;}
				newVHeight = wHeight - (spaceRatio-313);
				newVidWidth = Math.floor(newVHeight * (16/9));
				if(wHeight < 700){newVidWidth = newVidWidth +60;}
		//If the window resizes to something below the current threshold, this functions resizes the video and navigation smaller
		videoWidth = newVidWidth;
		newVidHeight = Math.floor(newVidWidth * (9/16));
		videoHeight = newVidHeight;
		newVimeoWidth = newVidWidth +1;
		siteNavWidth = newVidWidth + 22;
		vidInfoContWidth = newVidWidth + 50;
		contentInfoWidth = newVidWidth - 483;
		tagCont = newVidWidth -737;
		tagContVid = newVidWidth -283;
		if(contentInfoWidth < 438){
			// deals with situation when more info box pops below
			
			contentInfoWidth = videoWidth + 40;
			tagCont = videoWidth - 340;
		}
		contentInfoWidthVid = videoWidth;
		
		var widths = ['.activeVideo','.secondaryVideo','.secondaryVideo img'];
		var heights = ['.activeVideo','.secondaryVideo','.secondaryVideo img','#videoLayer','#videoSlider','#videoSliderVid','#hoverLeft a','#staticDivHolder'];
		
		// set standard height and widths
		for(i=0;i<widths.length;i++){
			$(widths[i]).width(newVidWidth);
		}
		for(i=0;i<heights.length;i++){
			$(heights[i]).height(newVidHeight);
		}
		$('#staticDiv').height((newVidHeight-70));
		// set offset heights/ widths
			//$('#siteNav').width(siteNavWidth);
			$('#tagsContainerVid').width(tagContVid);
			$('#tagsContainer').width(tagCont);
			$('#videoInfoContainer').width(vidInfoContWidth);
			$('#contentInfoText').width(contentInfoWidth);
			$('#contentInfoTextVid').width(contentInfoWidthVid);
			if(!maximise){
				$('#vimeoVid').width(newVimeoWidth).height(newVidHeight);
				}
			$('#hoverLeft a').css('line-height',(newVidHeight + "px"));
		if((videoWidth)>900){
			staticDivW = videoWidth -120;} else{ staticDivW=780;}
			$('#staticDiv').width(staticDivW);
		// set slider to new point
		newSliderLeft = ((currentVid-1) * videoWidth) * (-1);
		$('#videoSlider').css('left',(newSliderLeft+'px'));
		if(videoWidth>910){
			$('#siteNav').width(videoWidth);
		} else { 
			$('#siteNav').width(910);
		}
	}
}
function closeOverlay() {
	// closes the overlay on the static pages
	$('#staticDivHolder').fadeOut();
	
		$('#coverDiv').fadeOut();
	

}
function showStaticDetails(){
	$('#staticDivHolder').show();
	
		$('#coverDiv').show();
	

}
$(document).ready(function(){
	totalLoadingVids = totalVids;
	//Load the first video's text in
			// a. videoTitle
				$('#videoTitle').text(videoArray[0].videoTitle);
			// b. Client
				$('#videoClient').text(videoArray[0].videoClient);
			// c. Content
				$('#contentTextArea').html(videoArray[0].videoContent);
			// d. Tags
				$('#contentTags').empty();
				addContentTags(videoArray[0].videoTags);
			// e. Permalink
				createPermalink(videoArray[0].videoLink,videoArray[0].videoTitle);
			
		// Fade in the new videoTitle
			$('#contentvideoTitle').fadeIn('slow');
		
		//Assign onclick function to all the videos
			for(i=1;i<=totalVids;i++){
				var tempVida = $('#video'+i+' img')[0];
				tempVida.onclick = new Function('moveTo('+i+')');
				}
		//Assign an OnKeyDown event to the search bar
			$('#vidSearch').keydown(function(){
				runVideoSearch($(this).val());
			});
		//Assign onfocus to search box
			$('#vidSearch').focus(function(){
				$('#vidSearch').removeClass('vidSearchInactive').attr("value","");
				
			});
		//If the window height is less than 765 pixels, remove the bottom float of the video index
		
		if($(window).height()<600 && !isMobile){
			$('#alternateVidsFooter').removeClass().addClass('altVidsFootFixed');
		}
		// Squash logo in if height is less that 765
		if($(window).height()<700 && !isMobile){
			//
			$('#siteNav').css('margin','10px 0px 10px');
		} else {
			if(!isMobile){
			$('#siteNav').css('margin','30px 0px 30px');
			}
		}
		
		managePageResize();
		// add hover function for big left arrow
		$('#videoLayer').hover(function(){
	
		//over
			if(currentVid != 1 && !isMobile){
				$('#hoverLeft').show();
			}
		},function(){
		//out
			$('#hoverLeft').hide();
		});
		if(totalVids == 1){
			$('#navRight').empty().css('background-color','#fff');
			$('#navLeft a').html("&gt;");
		}
		createMinimiseButton();
		
		// load video index json 
		$('#alternateVidsContainer').slideDown();
		$('.vidSearch').fadeIn();
		refreshVidIndex();
});

$(window).resize(function(){
	// deals with bottom bar class when window is resized
	
	managePageResize();

});
prevParent = "";
function maxVideo() {
	maximise = true;
	prevParent = $('#vimeoVid').parent();
	$('#maximise').append($('#vimeoVid')).show(100);
	$('#vimeoVid').width('100%').height('100%').css('position','absolute');
}
function closeMax(){
	maximise = false;
	$('#maximise').hide();
	prevParent.append($('#vimeoVid'));
	$('#vimeoVid').height($('#vimeoVid').parent().height());
	$('#vimeoVid').width($('#vimeoVid').parent().width());
}
function createMaximise() {
	
	var maxDiv = document.createElement("div");
	maxDiv.id = "maxit";
	maxDiv.onclick = new Function("maxVideo();");
	maxDiv.innerHTML = "[maximise]";
	return maxDiv;
}
function createMinimiseButton() {
	var maxDiv = document.createElement("div");
	maxDiv.id = "maximise";
	var closeMax = document.createElement("div");
	closeMax.id = "closeMax";
	closeMax.onclick = new Function("closeMax()");
	closeMax.innerHTML = "[x]";
	maxDiv.appendChild(closeMax);
	$('body').prepend(maxDiv);
}
function refreshVidIndex(){
		if(!indexVideosLoaded){
				//empty bottom contents
				$('#alternateVidsDetails').empty();
				var extra = "";
				if(isPlaylist){extra = 'playlist=1&';}
				//Get json of latest vids
				$.getJSON(linkRoot+'videoIndex.php?'+extra+'query='+jsonQuery, function(json){
						if(json.length != 0){
							loadIndexVideos(json);
						}
					});
			}
}
