
/**
 * Autoplay
 * Version 1.0
 * Copyright (c) 2011 Kevin Yaun - info(at)autoplay(dot)co
 *
 */



var t_running = false;
var t = false;
var playerSetup = false;
var ytplayer;
var playing_intro_video;
var categories = new Object();
var iscueopen=true;
var player_offset_default = 160;
var player_offset = player_offset_default;
var mouseTimer;
var viewOpen;
var myScroll;


$(document).ready(function() {
	
	// Initial Function
	
	autoPlay();
	
	// Global
	
	$(window).bind("resize", resizeWindow);
	$(window).hashchange( function(){
		loadVideoFromTitle( location.hash );
	});
	$(window).keypress(function(e) {
		switch (e.keyCode) {
			case 32: pausePlayTheVideo(); break;
			case 39: skipVideo(); break;
		}
	});
	
	
	// Rollovers / Actions
	
	$("#open_cue").click(function () { 
		openTheCue();dCinema();
	}).mouseenter(function(){$(this).animate({opacity:0.5},200);dCinema();
	}).mouseleave(function(){$(this).animate({opacity:1},100);rCinema();
	});
	
	$("#close_cue").click(function () { 
		openTheCue();rCinema();
	}).mouseenter(function(){$(this).animate({opacity:0.7},200);
	}).mouseleave(function(){$(this).animate({opacity:0.95},100);
	});

	$("#skip_video").click(function () { 
		skipVideo();
	}).mouseenter(function(){$(this).animate({opacity:0.5},200);dCinema();
	}).mouseleave(function(){$(this).animate({opacity:1},100);rCinema();
	});

	$("#play_video").click(function () { 
		playTheVideo();
	}).mouseenter(function(){$(this).animate({opacity:0.5},200);dCinema();
	}).mouseleave(function(){$(this).animate({opacity:1},100);rCinema();
	});

	$("#pause_video").click(function () { 
		pauseTheVideo();
	}).mouseenter(function(){$(this).animate({opacity:0.5},200);dCinema();
	}).mouseleave(function(){$(this).animate({opacity:1},100);rCinema();
	});

	$("#volume_on").click(function () { 
		volumeOn();
	}).mouseenter(function(){$(this).animate({opacity:0.5},200);dCinema();
	}).mouseleave(function(){$(this).animate({opacity:1},100);rCinema();
	});

	$("#volume_off").click(function () { 
		volumeOff();
	}).mouseenter(function(){$(this).animate({opacity:0.5},200);dCinema();
	}).mouseleave(function(){$(this).animate({opacity:1},100);rCinema();
	});

	$("#info_icon").mouseenter(function(){$(this).animate({opacity:0.5},200);dCinema();
	}).mouseleave(function(){$(this).animate({opacity:1},100);rCinema();
	});

	$("#powered_by").click(function () { 
		window.open('http://www.autoplay.co','_blank');
	}).mouseenter(function(){$(this).animate({opacity:0.7},200);dCinema();
	}).mouseleave(function(){$(this).animate({opacity:1},100);rCinema();
	});

	$(".nav_page").mouseenter(function(){$(this).animate({opacity:0.7},200);dCinema();
	}).mouseleave(function(){$(this).animate({opacity:0.95},100);rCinema();
	});
	
	$(".cue_item").mouseenter(function(){$(this).animate({opacity:1},200);
	}).mouseleave(function(){
		if($(this).attr("id") != "cue_item_" + video_IDs[video_current]) $(this).animate({opacity:0.5},200);
		$("#titlesOverlay").delay(200).fadeOut(400);
	});

	$(".cue_category").mouseenter(function(){$(this).animate({opacity:0.5},200);
	}).mouseleave(function(){$(this).animate({opacity:1},100);
	});
	
	$("#playerOverlay").css("cursor","pointer").click(function () { 
		skipVideo();rCinema();
	}).mousemove(function(){cinemaOff();
	}).mousestop(5000,function(){cinemaOn();
	});
});


function autoPlay(){
	
	// Setup stage
	resizeWindow();
	setOptions();
	hideTheCue();
	myScroll = new iScroll('cue', {hScroll:true,vScroll:false});
	
	// Select video to load
	
	// Check for deep link
	if(location.hash){
	  titleIndex = video_title_urlsafe.indexOf(location.hash.substring(1));
	  if(titleIndex != -1 && titleIndex != video_current){
			loadNewVideo(titleIndex);
	  }else{
		  loadNewVideo();
	  }
	  
	// No deep link, load intro
	}else if(intro_video){
		loadIntroVideo();
		
	// No intro, load video
	}else{
		loadNewVideo();
	}
}

function hidePreloader(){
	$(QueryLoader.loadBar).css('float','right');
	$(QueryLoader.loadBar).animate({width:0,opacity:0},300,'easeInOutQuart',function(){
		$(QueryLoader.loadBarBG).fadeOut(300,function(){
			$('#content').css('opacity',1);
			$(QueryLoader.overlay).css('display','none');
			$(QueryLoader.preloader).remove();
			$('#header').css('display','none').slideDown(300,'easeOutCubic');
			$('#footer').css('display','none').slideDown(300,'easeOutCubic');
			//$(window).delay(1000).queue(function(n){ hideTheCue(); });
		});
	});
}

function resizeWindow() {
	var docheight = $(document.body).height();
	var docwidth = $(document.body).width();
	$("#playerOverlay").height( docheight - player_offset );
	$("#cue").width( docwidth );
	$("#cuecontainer").width( (cueCurrentLength * 130) + 10 );
	$("#video_title").width(docwidth - 380);
	$("#buffering").css({'left':(docwidth/2) - 36, 'top':(docheight/2) - 36});
	
}

function openTheCue() {
	if(!iscueopen){
		togglePage();
		iscueopen=true;
		dimStage();
		$("#open_cue").hide(0);
		$("#close_cue").fadeIn(100);
		$("#cue_categories").delay(100).slideDown(100,'easeInOutCubic',function(){
			loadCueCategory();
		});
		viewOpen = true;
	}else if(iscueopen){
		hideTheCue();
	}
}

function hideTheCue(){
	iscueopen=false;
	$(".cue_category").animate({"color":"#000","background-color":"#eee"},100);
	$('#cue').slideUp(200,'easeInOutCubic',function(){
		$("#cue_categories").slideUp(100,'easeInOutCubic',function(){
			$("#close_cue").fadeOut(100,function(){
				$("#open_cue").fadeTo(200,0.95);
			});
		});
	});
	unDimStage();
	viewOpen = false;
}

function loadCueCategory(ID){
	$('#cue').slideUp(200,'easeInOutCubic',function(){
		setActiveCategory(ID);
		if(ID){
			$(".cue_item").hide();
			for(i=0;i<categories[ID].length;i++){
				$("#cue_item_" + categories[ID][i] ).show();
			}
			cueCurrentLength = categories[ID].length;
			resizeWindow();
		}else{
			$(".cue_item").show();
			cueCurrentLength = cueCurrentLengthDefault;
			resizeWindow();
		}
		$('#cue').slideDown(300,'easeInOutCubic',function(){
			// Make sure cue scrollbar is sized
			setTimeout(function () {
				myScroll.refresh();
			}, 0);	
		});
	});
}

function rolloverCueItem(ID){
	$("#titlesOverlay").delay(100).stop(true, true).html("<div id='titlescontainer'><h2>Click to play</h2><h1>" + video_titles[ID] + "</h1></div>").fadeTo(400,0.6);
	$("#titlescontainer").css("top", ($(document.body).height() - ($("#titlescontainer h1").height() + 40)) / 2 );
}

function displayError(errorValue){
	$("#titlesOverlay").delay(100).stop(true, true).html("<div id='titlescontainer'><h1>" + errorValue + "</h1></div>").fadeTo(400,0.6);
	$("#titlescontainer").css("top", ($(document.body).height() - ($("#titlescontainer h1").height() + 40)) / 2 );
	hideBuffering();
}

function onYouTubePlayerReady(playerId) {
	ytplayer = document.getElementById("myytplayer");
	ytplayer.addEventListener("onStateChange", "onPlayerStateChange");
	ytplayer.addEventListener("onError", "onError");
}

function setupYoutubePlayer(youtube_id){
	var params = { allowScriptAccess: "always",wmode: "opaque" };
    var atts = { id: "myytplayer" };
    swfobject.embedSWF("http://www.youtube.com/e/" + youtube_id + "?enablejsapi=1&playerapiid=ytplayer&controls=0&iv_load_policy=3&showinfo=0&enablejsapi=1&modestbranding=1&wmode=opaque&autoplay=1&disablekb=1", "ytapiplayer", "100%", "100%", "9.0.0", null, null, params, atts);
	playerSetup = true;
}

/*

Potential mobile functionality

function forcePlayerClick(){
	$(document.elementFromPoint($(document.body).width() / 2, $(document.body).height() / 2)).click();
}

*/

function loadIntroVideo(){
	showBuffering();
	playing_intro_video = true;
	setupYoutubePlayer(intro_video);
}

function loadNewVideo(vidToLoad){
	
	$("#static_content").fadeOut(200);
	$("#player").animate({'opacity':0.05},200,function(){
		//$("#player").css("opacity",0);
		showBuffering();
		  
		playing_intro_video = false;
		
		// Hack to keep video from disappearing on cue open
		if($.browser.chrome){ $('#cue').css('display','block'); }
		
		if(t_running) clearTimeout(t);
		t_running=false;
		
		video_gostatic = false;
		if(vidToLoad !== undefined){
			video_current = vidToLoad;
			video_cue = video_current + 1;
			if(video_cue > video_titles.length - 2) video_cue = 0;
		}else if(!randomization) {
			video_current = video_cue;
			video_cue += 1;
			if(video_cue > video_titles.length - 2) video_cue = 0;
		}else{
			if(!(video_rand_IDs.length > 0)) createIDsArray();
			var r = Math.floor(Math.random()*(video_rand_IDs.length - 1));
			video_cue = video_rand_IDs[r];
			video_rand_IDs.splice(r,1);
			video_current = video_cue;
		}
		  
		if(video_urls[video_current]){
			
			if(!playerSetup){
				setupYoutubePlayer(video_urls[video_current]);
			}else{
				ytplayer.loadVideoById(video_urls[video_current]);
			}
			//updateVideoDetails();
		}else{
			//staticCard();
			displayError("No videos to show");
		}
		
		setActiveThumbnail();
	});

}

function cinemaOn(){
	if(!viewOpen && ytplayer.getPlayerState() == 1){
		$("#header").animate({'opacity':0.001,'height':0},800);
		$("#footer").animate({'opacity':0.001,'height':0},800);
	}
}

function cinemaOff(){
	$("#header").animate({'opacity':1,'height':'80px'},300);
	$("#footer").animate({'opacity':1,'height':'80px'},300);
}

function dCinema(){
	$.mousestopDelay = 100000000;	
}

function rCinema(){
	$.mousestopDelay = 1000;
}

function setActiveThumbnail(){
	$(".cue_item").css({"opacity":0.5,"top":0});
	$("#cue_item_" + video_IDs[video_current]).animate({"opacity":1,"top":"10px"},300);
}

function setActiveCategory(ID){
	$(".cue_category").animate({"color":"#000","background-color":"#eee"},200);
	if(ID) $("#category_" + ID).animate({"color":"#fff","background-color":"#1c1c1c"},200);
	else $("#category_0").animate({"color":"#fff","background-color":"#1c1c1c"},200);
}
	  
function pauseTheVideo(){
	if(ytplayer) ytplayer.pauseVideo();
}
	  
function playTheVideo(){
	if(ytplayer) ytplayer.playVideo();
}

function skipVideo(){
	loadNewVideo();
}

function pausePlayTheVideo(){
	if(ytplayer.getPlayerState() == 1){
		ytplayer.pauseVideo();
		cinemaOff();
	}else if(ytplayer.getPlayerState() == 2){
		ytplayer.playVideo();
	}
}
	  
function updateVideoDetails(){
	  
	if($.cookie('ap_volume') == 'off'){
		volumeOn();
	}else{
		volumeOff();
	}
	
	if(!playing_intro_video){
	  //$("#info_icon").fadeIn(200);
	
		$("#titlesOverlay").stop(true, true).html("<div id='titlescontainer'><h2>Now playing</h2><h1>" + video_titles[video_current] + "</h1></div>").fadeTo(400,0.6).delay(2000).fadeOut(400);
		$("#titlescontainer").css("top", ($(document.body).height() - ($("#titlescontainer h1").height() + 40)) / 2 );
			
	  $('#video_title').fadeOut(200).queue(function(n) { $(this).html(video_titles[video_current]);n();}).fadeIn(200);
	  window.location = '#' + video_title_urlsafe[video_current];
	}
}
  
function onError(e){
	t_running = true;
	t=setTimeout("loadNewVideo()",5000);
}

function onPlayerStateChange(event) {
	// ENDED
	if (event == 0) {
		loadNewVideo();
		
	// PLAYING
	}else if(event == 1) {
		$("#player").animate({'opacity':1},400);
		hideBuffering();
		updateVideoDetails();
		$("#play_video").fadeOut(200,function(){
			$("#pause_video").fadeIn(200);
		});
		
	// PAUSED
	}else if(event == 2) {
		if(!video_gostatic){
			$("#pause_video").fadeOut(200,function(){
				$("#play_video").fadeIn(200);
			});
		}
		
	// CUED
	}else if(event == 5) {
		ytplayer.playVideo();
		
	// UNSTARTED
	}else if(event == -1) {
		ytplayer.playVideo();
		
	// BUFFERING
	}else if(event == 3){
		$("#player").animate({'opacity':0.5},400);
		showBuffering();
	}
}

function loadVideoFromTitle(theHash){
	titleIndex = video_title_urlsafe.indexOf(theHash.substring(1));
	if(titleIndex != -1 && titleIndex != video_current){
		  loadNewVideo(titleIndex);
	}
}

function showBuffering(){
	$("#buffering").fadeIn(400);
}

function hideBuffering(){
	$("#buffering").fadeOut(400);
}

/*

COMING SOON

function staticCard(){
	
	//showBuffering();
	
	video_gostatic = true;
	
	$("#player").animate({'opacity':0},200);
	
	$("#static_content").delay(200).queue(function(n) {
	  // Set content
	  $(this).html("<div id='static_container'><div id='static_cell'><h1>" + video_titles[video_current] + "</h1><h2>" + video_description[video_current] + "</h2></div></div>");
	
	  // Set background image
	  if(video_feature[video_current]){
		  var img = new Image();
		  $(img).one('load',function() {
			  $("#static_content").css('background-image','url(' + video_feature[video_current] + ')').fadeIn(200);
			  setStaticTimeout();
			  hideBuffering();
		  });
		  img.src = video_feature[video_current];
		  if( img.complete ) $(img).load();
		  
	  }else{
		  $("#static_content").css('background-image','none').fadeIn(200);
		  setStaticTimeout();
		  hideBuffering();
	  }
	  
	  n();
	});
	
	ytplayer.pauseVideo();
	
	$("#volume_on").fadeOut(100);
	$("#volume_off").fadeOut(100);
	$("#pause_video").fadeOut(100);
	$("#play_video").fadeOut(100);
	$("#info_icon").fadeOut(100);
	$("#video_title").fadeOut(100).html("");
	
}
	  
function setStaticTimeout(){
	  
	if(video_delay[video_cue]) var delayAmmount = video_delay[video_current];
	else var delayAmmount = 4000;
	
	t_running = true;
	t=setTimeout("loadNewVideo()",delayAmmount);
  
}
*/
		
		
function volumeOn(){
	if(ytplayer) ytplayer.mute();
	$("#volume_on").fadeOut(100,function(){
		$("#volume_off").fadeIn(100);
	});
	$.cookie('ap_volume','off');	
}
		
function volumeOff(){
	if(ytplayer) ytplayer.unMute();
	$("#volume_off").fadeOut(100,function(){
		$("#volume_on").fadeIn(100);
	});
	$.cookie('ap_volume','on');	
}
		
function setOptions(){
	if(bg_color){
		$('#header').css('background-color',bg_color);
		$('#footer').css('background-color',bg_color);
		$('#static_content').css('background-color',bg_color);
		$('a.cue_item_link').css('background-color',bg_color);
	}
	if(powered_by == 1) $('#powered_by').hide();
}

function createIDsArray(){
	video_rand_IDs = new Array();
	for(i=0;i<video_titles.length - 1;i++){
		video_rand_IDs.push(i);
	}
}

function togglePage(ID){
	$(".page_content").css("display","none");
	if(!ID){
		$(".page").slideUp(300,'easeInOutCubic',function(){
			hideHighlightedNav();
		});
		viewOpen = false;
		unDimStage();
	}if($("#"+ID).css("display") == "none"){
		hideHighlightedNav();
		hideTheCue();
		$("#nav_"+ID).animate({"background-color" : "#ffffff", "color" : "#1c1c1c","opacity":0.95},200);
		$(".page").slideUp(200);
		$("#"+ID).delay(200).slideDown(500,'easeInOutCubic',function(){
			$(".page_content").fadeIn(200,function(){
				//myPageScroll = new iScroll(ID, {hScroll:true,vScroll:false});	
			});
			viewOpen = true;
		});
		dimStage();
	}else{
		$("#"+ID).slideUp(300,'easeInOutCubic',function(){
			hideHighlightedNav();
		});
		viewOpen = false;
		unDimStage();
	}
}

function hideHighlightedNav(){
	$(".nav_page").animate({"background-color" : "#1c1c1c", "color" : "#666"},100);		
}

function dimStage(){
	$('#stage').fadeTo(200, 0.5);	
}

function unDimStage(){
	$('#stage').fadeTo(200, 1);
}



