Shadowbox.init({
	viewportPadding: 1,
	flashParams: {allowScriptAccess: 'always'}
});

var current = 0;			
var themes = new Array({themeClass: "t1", large: 2, medium: 3, small:2}, {themeClass: "t2", large: 2, medium: 3, small:2}, {themeClass: "t3", large: 2, medium: 3, small:2});			
var colors = new Array("red", "green", "yellow", "blue");
var outOfContent = false;

function onYouTubePlayerReady(playerId) {
	document.getElementById("sb-player").addEventListener("onStateChange", "onYouTubeStateChange");								
}

function onYouTubeStateChange(state){
	if(state==0){
		//close video if at end
		Shadowbox.close();
	}
}
	
function afterNext(){
	toggleNav();
	panelCount = $("#lanternGallery ul li").length;
	if(panelCount <= current + 2){
		preload();
	}
}			

function afterPrev(){
	toggleNav();
}

function toggleNav(){
	//works out whether the next and/or previous buttons should be visible
	
	if(current > 0){
		//show previous button
		$("#prev").fadeIn("fast");
	}
	if(current < $("#lanternGallery ul li").length - 1){
		//show next button
		$("#next").fadeIn("fast");
	}
	
}

function bounceLanterns(lanternSize, amount){
	currPanel = $("#lanternGallery ul li:eq(" + current + ")");
	currPanel.find("." + lanternSize).animate(
           { top: "-="+amount+"px" }, {
                    duration: 2000,
                    easing: 'easeOutSine'
                }).animate(
           { top: "+="+amount+"px" }, {
                    duration: 2000,
                    easing: 'easeInSine'
                })
}

function addLanternHandlers(){
	currPanel = $("#lanternGallery ul li:eq(" + current + ")");
	
	currPanel.find("a.youtube").hoverIntent({
		over: function(){
			targ = $(this);
			showBubble(targ, "Click to watch <b>" + targ.attr("rel") + "</b>", "youtube");
		},
		out: function(){
			$("#bubble").fadeOut();
		},	
		interval: 50
		}		
	).click(
		function(){
			Shadowbox.open({
					content: $(this).attr("href") + "?autoplay=1&enablejsapi=1&version=3&playerapiid=sb-player",
					/* content: $(this).attr("href") + "?autoplay=1", */ //Uncomment this line and comment out the previous line to disable autoclose on lantern vids. 
					player: "swf",
					width: 640,
					height: 385
			});
			return false;
		}
	)

	currPanel.find("a.twitter").hoverIntent({
		over: function(){
			targ = $(this);						
			showBubble(targ, "<b>@" + targ.attr("rel") + "</b> says " + targ.find(".thumb").text(), "twitter");
		},
		out: function(){
			$("#bubble").fadeOut();
		},
		interval: 50
		}				
	).click(
		function(){
			return false;
		}
	)
					
	currPanel.find("a.facebook").hoverIntent({
		over: function(){
			targ = $(this);						
			showBubble(targ, "<b>" + targ.attr("rel") + "</b> likes this", "facebook");
		},
		out: function(){
			$("#bubble").fadeOut();
		},
		interval: 50
		}				
	).click(
		function(){
			return false;
		}
	)
}

function showBubble(targ, content, lanternType){
	var bubble = $("#bubble");
	var lanternGallery = $("#lanternGallery");
	bubble.hide().find(".inner").html("<div class='"+lanternType+"'></div>" + content)
	
	var targOff = targ.offset();
	var lanternGalleryOff = lanternGallery.offset();
	
	var bubbleTop = targOff.top - lanternGalleryOff.top - (bubble.outerHeight() + 10);
	var bubbleLeft = targOff.left - lanternGalleryOff.left - ((bubble.outerWidth() / 2) - (targ.innerWidth() / 2));
	
	bubble.css("top", bubbleTop).css("left", bubbleLeft).fadeIn();
}

function removeLanternHandlers(){
	$("#lanternGallery .lantern").unbind();
}

function preload(){
	if(!outOfContent){
		//append panel, load with content. Always have 2 panels after the current preloaded.				
		container = $("#lanternGallery ul");	
		panelCount = container.find("li").length;	
		panelContent = 	getPanelContent();
		if(panelContent){
			// if there was content to fill each lantern, add the panel
			container.width((panelCount+1) * 950).append(panelContent);
			toggleNav();
		}	
		else {
			//out of content!
			outOfContent = true;
		}	
	}
}		

			
function getPanelContent(){
	theme = getRandom(themes);
	innerHTML = "<li class='" + theme.themeClass + "'>";
	for(i=1; i <= theme.large; i++){
		lanternContent = getLanternContent("large");
		if(lanternContent){
			innerHTML += "<div class='lantern large a" + i + " " + getRandom(colors) + "'>"+ lanternContent +"</div>";
		}
		else {	
			//out of content!					
			return false
		}					
	}
	for(i=1; i <= theme.medium; i++){
		lanternContent = getLanternContent("medium");
		if(lanternContent){
			innerHTML += "<div class='lantern medium b" + i + " " + getRandom(colors) + "'>"+ lanternContent +"</div>";
		}
		else {	
			//out of content!					
			return false
		}					
	}
	for(i=1; i <= theme.small; i++){
		lanternContent = getLanternContent("small");
		if(lanternContent){
			innerHTML += "<div class='lantern small c" + i + " " + getRandom(colors) + "'>"+ lanternContent +"</div>";
		}
		else {	
			//out of content!					
			return false
		}
	}
	innerHTML += "</li>";
	return innerHTML;
}
			
function getLanternContent(size){
	innerContent = "";
	url = "";
	switch(size){
		case "large":
			//Large always has YT content, falling back to twitter, then facebook as last resort
			ytVid = getYouTubeVid();
			if(ytVid){
				bgImage = "http://img.youtube.com/vi/"+ ytVid.vidId +"/default.jpg";
				title = ytVid.caption;
				lClass = "youtube";
				url = "http://www.youtube.com/v/"  + ytVid.vidId;
			}
			else {
				tweet = getTweet();
				if(tweet){
					bgImage = tweet.profile_image_url;
					title = tweet.from_user;
					innerContent = tweet.text;
					lClass = "twitter";
				} 
				else {
					fbProfile = getFacebookProfile();
					if(fbProfile){
						bgImage = "http://graph.facebook.com/" + fbProfile.id + "/picture";
						title = fbProfile.name;
						lClass = "facebook";
					} 
					else {
						//out of content!
						return false;
					}
				}							
			}
			
		break;
		case "medium":
			//medium either has YT (which falls back to twitter then facebook content) or twitter (falling back to facebook)
			if(coinToss()){
				ytVid = getYouTubeVid();
				if(ytVid){
					bgImage = "http://img.youtube.com/vi/"+ ytVid.vidId +"/default.jpg";
					title = ytVid.caption;
					lClass = "youtube";
					url = "http://www.youtube.com/v/"  + ytVid.vidId;
				}
				else {
					tweet = getTweet();
					if(tweet){
						bgImage = tweet.profile_image_url;
						title = tweet.from_user;
						innerContent = tweet.text;
						lClass = "twitter";
					} 
					else {
						fbProfile = getFacebookProfile();
						if(fbProfile){
							bgImage = "http://graph.facebook.com/" + fbProfile.id + "/picture";
							title = fbProfile.name;
							lClass = "facebook";
						} 
						else {
							//out of content!
							return false;
						}
					}
				}
			}
			else {
				tweet = getTweet();
				if(tweet){
					bgImage = tweet.profile_image_url;
					title = tweet.from_user;
					innerContent = tweet.text;
					lClass = "twitter";
				} 
				else {
					fbProfile = getFacebookProfile();
					if(fbProfile){
						bgImage = "http://graph.facebook.com/" + fbProfile.id + "/picture";
						title = fbProfile.name;
						lClass = "facebook";
					} 
					else {
						//out of content!
						return false;
					}
				}
			}
		break;
		case "small":
			//small has either twitter (falling back to facebook) or facebook.
			if(coinToss()){
				tweet = getTweet();
				if(tweet){
					bgImage = tweet.profile_image_url;
					title = tweet.from_user;
					innerContent = tweet.text;
					lClass = "twitter";
				} 
				else {
					fbProfile = getFacebookProfile();
					if(fbProfile){
						bgImage = "http://graph.facebook.com/" + fbProfile.id + "/picture";
						title = fbProfile.name;
						lClass = "facebook";
					} 
					else {
						//out of content!
						return false;
					}
				} 
			}
			else {
				fbProfile = getFacebookProfile();
				if(fbProfile){
					bgImage = "http://graph.facebook.com/" + fbProfile.id + "/picture";
					title = fbProfile.name;
					lClass = "facebook";
				} 
				else {
					tweet = getTweet();
					if(tweet){
						bgImage = tweet.profile_image_url;
						title = tweet.from_user;
						innerContent = tweet.text;
						lClass = "twitter";
					} 
					else {				
						//out of content!
						return false;
					}
				}
			}
		break;
	}
	return("<a " + ((url)?"href='"+ url +"'" : "") + " class='"+ lClass +"'  rel=\""+title+"\"><div class='thumb' style='background-image:url("+bgImage+")'>"+ innerContent +"</div><div class='mediaIcon'></div></a>");
}

function getYouTubeVid(){
	if(youtube_featured.length > 0){
		return youtube_featured.shift();
	}
	else{
		if(youtube_responses.length > 0){
			return youtube_responses.shift();
		}
		else return null;
	}
}

function getTweet(){
	if(twitter_hashtag.length > 0){
		return twitter_hashtag.shift();
	}
}

function getFacebookProfile(){
	if(facebook_pics.length > 0){
		return facebook_pics.shift();
	}
}

function getRandom(array) {
	//return array[0];
	return array[(Math.floor(Math.random()*array.length))];
}

function coinToss(){
	//simulate a coin toss, basically to give a random choice from 2 options
	return Math.round(Math.random());
}

$(function(){
	//On Page Load				
	$("#pleas_so_far").text(count.total);	
	preload();
	preload();
	preload();
	addLanternHandlers();
	
/*
	//Bob animation
	window.setInterval(function(){bounceLanterns("large", 20)}, 6000);
	window.setInterval(function(){bounceLanterns("medium", 15)}, 6000);
	window.setInterval(function(){bounceLanterns("small", 10)}, 6000);
*/


	$("#next").click(function(){		
		$(".navControls").fadeOut("fast");
		removeLanternHandlers();
		container = $("#lanternGallery ul")	
			
		if(current < $("#lanternGallery ul li").length - 1){
			//stops user from double clicking past the end of the panel set
			current++;										
			container.animate(
				{ marginLeft: (current * -950)}, 
				{ queue:false, duration:1500, easing: 'easeOutQuint', complete: afterNext}
			);	
		}
		addLanternHandlers();
		return false;
	});
	
	$("#prev").click(function(){
		$(".navControls").fadeOut("fast");
		removeLanternHandlers();
		container = $("#lanternGallery ul")
		
		if(current > 0){
			//stops user from double clicking past the beginning of the panel set
			current--;	
			container.animate(
				{ marginLeft: (current * -950)}, 
				{ queue:false, duration:1500, easing: 'easeOutQuint', complete: afterPrev}
			);
		}
		addLanternHandlers();
		return false;
	});
	

})
