var bg, sequencer, lInterval,
audio, audioOGG, audioMP3,
stats, counter;
var link, inputTime;
var searchField, aSearch, searchBtn, searchHlp, searchLoaded = false;
var defaultSearchString = "Enter the address of the home where you grew up";
var layoutTopContainer;
var canvasBirds, titleWriter;
var launched = false;
var playing = true;
var resuming = false;

var addressFeedback, storedAddress;

var warning;

var final_drawing, isDrawing=false;
var codeHelper;

var subtitle = document.getElementById("sub-text");
var buttonsArea = document.getElementById("buttons-area");

// console for firefox
try{var console = console || { log: function( value ){ /* alert( value ); */ } };}catch(error){}; // avoid firebug bug :)


/**
 * Setup
 */

bg = document.getElementById("bg");

audio = document.createElement("audio");
audio.appendChild(audioOGG = document.createElement("source"));
audio.appendChild(audioMP3 = document.createElement("source"));
audioOGG.src = "http://cdn.thewildernessdowntown.com/files/wutw.ogg";
audioOGG.type = "audio/ogg; codecs=vorbis";
audioMP3.src = "http://cdn.thewildernessdowntown.com/files/wutw.mp3";
audioMP3.type = "audio/mpeg";


if ( BrowserDetect.browser == "Firefox" && BrowserDetect.version < 3.5 ) {

	createWarning( 'This site will not work with your <a href="http://www.whatbrowser.org">browser</a>. It was designed with Google Chrome in mind, you may need to download <a href="http://www.google.com/chrome">Google Chrome</a> and try launching this site again.' );

} else if ( BrowserDetect.browser == "Firefox" && BrowserDetect.version < 4 ) {

	createWarning( 'This site was designed with Google Chrome in mind and is unable to render properly in your <a href="http://www.whatbrowser.org">browser</a>.<br />For the best viewing experience, we recommend downloading <a href="http://www.google.com/chrome">Google Chrome</a> and trying this site again.' );
	createTryAnywayButton();
	
} else if ( BrowserDetect.browser == "Safari" && BrowserDetect.version <= 3 ) {

	createWarning( 'This site was designed for modern browsers like <a href="http://www.google.com/chrome">Google Chrome</a>, please download it or update to the <a href="http://www.apple.com/safari/download/">newest version</a> of your current browser.' );
	createTryAnywayButton();

} else if ( BrowserDetect.browser == "Opera" ) {

	createWarning( 'This site may not work with your <a href="http://www.whatbrowser.org">browser</a>. It was designed with Google Chrome in mind, you may need to download <a href="http://www.google.com/chrome">Google Chrome</a> and try launching this site again.' );
	createTryAnywayButton();

} else if ( BrowserDetect.browser == "Chrome" && BrowserDetect.version <= 4 ) {

	createWarning( 'Please update your browser for the best viewing experience. For instructions on updating Chrome, please refer to the <a href="http://www.google.com/support/chrome/bin/answer.py?hl=en&answer=95414">Google Chrome Help Center</a>.' );
	createTryAnywayButton();

} else if ( BrowserDetect.browser == "Explorer" && BrowserDetect.version <= 8 ) {

	createWarning( 'This site may not work with your <a href="http://www.whatbrowser.org">browser</a>. It was designed with Google Chrome in mind, you may need to download <a href="http://www.google.com/chrome">Google Chrome</a> and try launching this site again.' );

} else if ( BrowserDetect.browser == "Explorer" && BrowserDetect.version > 8 ) {

	createWarning( 'This site may not work with your <a href="http://www.whatbrowser.org">browser</a>. It was designed with Google Chrome in mind, you may need to download <a href="http://www.google.com/chrome">Google Chrome</a> and try launching this site again.' );
	createTryAnywayButton();

} else {

	createSearchField();
	createPreloader();

}


layoutTopContainer = document.getElementById("top");

if(window.location.hash) aSearch.value = window.location.hash.replace( '#', '' );

/*window.addEventListener("resize", resizeHandler, false);
resizeHandler(null);
*/
lInterval = setInterval(init, 500);

/**
 * Functions
 */

function init(){
	if((audio.readyState >= 3)&&(searchLoaded)){
		clearInterval(lInterval);
		
		totalTime = audio.duration;

		canvasBirds = new CanvasBirds(bg, $(window).width(), $(window).height()/2);

		lInterval = setInterval(loop, 100/6);
			
	}
}

// preload contents
function preload() {

	createPreloader();

	loadMapContents();

	loadInterval = setInterval( function() {

		addToPreloader(Math.round(100 * getLoadedContents()/_contents.length));

		if( checkIfPreloaded() ) {

			clearInterval(loadInterval);
			preloaded();
		}
		
		else if( loadDataFailed() ){
			clearInterval(loadInterval);
			onNotEnoughTileData();
		}

	}, 100);
	
	addToPreloader( Math.round(100 * getLoadedContents()/_contents.length));
	createTip();
	
}

function continuePreloading() {

	createPreloader();

	loadInterval = setInterval( function() {

		addToPreloader( Math.round(100 * getLoadedContents()/_contents.length));

		if( checkIfPreloaded(true) ) {
			clearInterval(loadInterval);
			preloaded();
		}

	}, 100);
	
	addToPreloader( Math.round(100 * getLoadedContents()/_contents.length));
	createTip();
		
}

function preloaded(){
	createLauncher();
	createTip();
	sendStat('/30-End-loading');
}

/**
 * Search field events and functions
 */

function checkAddress(){
	clearButtonsArea();
	removeAddressFeedback();
	removeSuggestionListeners();
	gLocation.checkAddress( aSearch.value, 64 );
	sendStat('/10-Address-search');
}

function checkAddressInputText(event){
	if(aSearch.value === defaultSearchString){
		aSearch.value = "";
	}
}

function restoreAddressInputText(event){
	if(aSearch.value === ""){
		aSearch.value = defaultSearchString;
	}
}

function handleKeyPress(event){
	var key = event.keyCode || event.which;
	if (key==13){
		checkAddress();
	}
}

function onSuccess() {
	launchSequencer();
	preload();
	sendStat('/20-Loading');
}

function onInvalidAddress() {
	removeAddressFeedback();
	appendSearchField();
	
	addressFeedback = document.createElement("div");
	addressFeedback.id = "gc_as";
	addressFeedback.innerHTML = "We're having difficulty finding this address. Please try again.";
	searchField.appendChild(addressFeedback);
	
	addSuggestionListeners();
}

function onNotEnoughData() {		
	removeAddressFeedback();
	appendSearchField();
	
	addressFeedback = document.createElement("div");
	addressFeedback.id = "gc_as";
	addressFeedback.innerHTML = "The entered address does not contain enough data for this experiment to run.";
	searchField.appendChild(addressFeedback);
	
	addSuggestionListeners();
}

function onNotEnoughTileData() {		
	removeAddressFeedback();
	onSuggestionBlur(null);
	clearButtonsArea();
	clearInterval(loadInterval);
	
	createNotEnoughDataLayout();
}

function removeAddressFeedback(){
	try{
		if(addressFeedback != undefined){
			searchField.removeChild(addressFeedback);
		}
	}catch(error){}
}

function start() {
	//if(parseFloat(inputTime.value) > 0) audio.currentTime = parseFloat(inputTime.value);	
	
	clearButtonsArea();

	launchWindowManager();
	createWindowSequence();
	createContentSequence();

	audio.addEventListener("ended", audioEnded, false);
	//document.addEventListener( 'keydown', onDocumentKeyDown, false );
	sendStat('/40-Launch-film');
}

/**
 * Launch me!
 */

function launch(){
	launched = true;
	audio.play();
	clearButtonsArea();
	fadeBlocker(90);
}
 

/**
 * Setup sequencer
 */

function launchSequencer(){
	//console.log("Launch");
	sequencer = new Sequencer();
}

/**
 * The loop
 */

function loop() {

	TWEEN_MANAGER.update();

	if(launched){
		if ( playing ) {
			sequencer.update( audio.currentTime, 0 );
			//controller.update(audio.currentTime, audio.duration);
			
			if(audio.currentTime > 287){
				controller.kill();
			}
		}
	}
	
	else if(!isDrawing){
		canvasBirds.update();
		//titleWriter.update();
	}
	
	else{
		drawingTool.update();
		//console.log("drawing");
	}

}

/**
 * Toggle mute
 */

function toggleMute(){
	audio.muted = !audio.muted;
}

/**
 * Toggle play/pause
 */

function togglePlayPause(){
	audio.paused ? audio.play() : audio.pause();
	playing = !audio.paused;
	if(audio.paused){
		sequencer.pause();
	}
	else{
		sequencer.resume();
	}
}

/**
 * Audio ended event
 */

function audioEnded( event ){
	exitSequencer();//closeWindows();
	createEndButtons();
	launched = false;
	resuming = true;
	fadeBlocker(0);
	sendStat('/80-End-film');
}

/**
 * Paused by close
 */

function pausedByClose(){
	launched = false;
	resuming = true;
	createPausedState();
	fadeBlocker(0);
}

function resumeAfterClose(event){
	windowsReady = 0;
	audio.muted = false;
	resetContents();
	loadContents();
	loadMapContents();
	continuePreloading();
}

function replayVideo(event){
	audio.pause();
	audio.currentTime = 0;
	resumeAfterClose(event);
	sendStat('/Click-on-Replay-your-film');
	sendStat('/20-Loading');
}

function showShareVideo(event){
	if(!document.getElementById('shareVideo')){
		var buttonsArea = document.getElementById("buttons-area");
		var shareVideo = document.createElement("div");	
		shareVideo.id = 'shareVideo';
		buttonsArea.appendChild(shareVideo);
	
		var description = document.createElement("p");
		description.innerHTML = "Copy and paste the link below to send this film <br />to someone with your address built in: ";
		shareVideo.appendChild(description);
	
		var urlInput = document.createElement("input");
		urlInput.id = "aSearch";
		urlInput.value = "http://www.thewildernessdowntown.com/#" + storedAddress.replace(/\ /gi,'+');
		urlInput.setAttribute('readonly', 'readonly');
		shareVideo.appendChild(urlInput);
		urlInput.focus();
	    urlInput.select();
	
		var closeButton = document.createElement("span");	
		closeButton.innerHTML = '<b>[x]</b>';
		closeButton.style.cursor = "pointer";
		closeButton.style.marginLeft = "10px";
		shareVideo.appendChild(closeButton);
		
		closeButton.addEventListener("click", closeShareVideo, false);
	 	
		sendStat('/Click-on-Share-your-film');
	}
}

function closeShareVideo(event){
	try{
		var buttonsArea = document.getElementById("buttons-area");
		var shareVideo = document.getElementById("shareVideo");
		buttonsArea.removeChild(shareVideo);
	}catch(error){};
}

/**
 * Dynamic content in buttons area
 */

function createSearchField(){
	searchLoaded = true;
}

function createWarning( msg ) {
	/*
	var warning = document.createElement("div");
	warning.id = "warning";
	warning.innerHTML = '<p>' + msg + '</p>';
		
	var top = document.getElementById("top");
	top.appendChild(warning);
	*/
}

function createTryAnywayButton() {

	var btn = document.createElement("input");
	btn.setAttribute('class', 'button'); 
	btn.id = "tryanyway";
	btn.type = "button";
	btn.value = "Try Anyway";
	btn.addEventListener("click", function () {
	
		var top = document.getElementById("top");
		var warning = document.getElementById("warning");
		top.removeChild( warning );
		
		createSearchField();
		createPreloader();
	
	}, false);
	
	var warning = document.getElementById("warning");
	warning.appendChild(btn);

}

/*
function createWarning(){
	var warning = document.createElement("div");
	warning.id = "warning";
	if(BrowserDetect.browser=="Chrome"){
		warning.innerHTML = '<p>This site was designed for the latest version of Google Chrome. <br />Please go to About > Update Now</p>';
	}else{
		warning.innerHTML = '<p>This site was designed for modern browsers like <a href="http://www.google.com/chrome/">Google Chrome</a>, <br />please download it or another HTML5-compliant <a href="http://www.whatbrowser.org">web browser</a>.</p>';		
	}
	var top = document.getElementById("top");
	top.appendChild(warning);
}
*/

function downloadChrome(event){
	window.location = "http://www.google.com/chrome/";
	sendStat('/Click-on-Downlod-Chrome');
}

function appendSearchField(){
	clearButtonsArea();
	buttonsArea.appendChild(searchField);
}

function clearButtonsArea(){
	buttonsArea.innerHTML = "";
	while(buttonsArea.lastChild) buttonsArea.removeChild(buttonsArea.lastChild);
}

function createPreloader(){

}

function addToPreloader(amount){
	var preloaderText = document.getElementById("preloaderText");	
	preloaderText.innerHTML = "PLEASE WAIT... LOADING " + amount + " <span id='percentage'>%</span>";
}

function createNotEnoughDataLayout(){
	var btn, txt;
	
	clearButtonsArea();
	
	txt = document.createElement("div");
	txt.setAttribute("class", "centered");
	txt.innerHTML = "Your address doesn't contain enough Street-View and/or Google Maps data to 100% enjoy this experience.<br/><br/>";
	buttonsArea.appendChild(txt);
	
	btn = document.createElement("input");
	btn.type = btn.className = "button";
	btn.id = "continueAnywayButton";
	btn.value = "Continue Anyway";
	txt.appendChild(btn);
	btn.addEventListener("click", continueAnyway, false);
	
	btn = document.createElement("input");
	btn.type = btn.className = "button";
	btn.id = "trySearchAgainButton";
	btn.value = "Search Again";
	txt.appendChild(btn);
	btn.addEventListener("click", trySearchAgain, false);
}

function trySearchAgain(event){
	resetMapContents();
	appendSearchField();
	addSuggestionListeners();
}

function continueAnyway(event){
	continuePreloading();
}

function createTip(){
	if(!document.getElementById("tipText")){
		var tipText = document.createElement("div");
		tipText.setAttribute('class', 'subtitle-inside'); 
		tipText.id = 'tipText';
		tipText.innerHTML = 'This film is processor intensive. <br />Please shut down other programs and close unnecessary browser tabs. Doing this will enhance your viewing experience. Thanks.';
		buttonsArea.appendChild(tipText);
	}
}

function createLauncher(){
	var launcher = document.createElement("div");
	var btn = document.createElement("input");
	btn.setAttribute('class', 'button'); 
	btn.type = "button";
	btn.value = "Play Film";
	btn.id = "launcherButton";
	btn.addEventListener("click", start, false);
	clearButtonsArea();
	
	launcher.innerHTML = "We're ready. Please turn your speakers on.<br/><br/>";
	
	/*
	inputTime = document.createElement("input");
	inputTime.type = "text";
	inputTime.value = "0";
	styleElement(inputTime, "width: 100px; marginRight: 5px");
	launcher.appendChild(inputTime);
	*/
	
	launcher.appendChild(btn);
	
	buttonsArea.appendChild(launcher);
}

function createEndButtons(){
	var launcher = document.createElement("div");
	var btn = document.createElement("input");
	var btn2 = document.createElement("input");
	var btn3 = document.createElement("input");
	var btn4 = document.createElement("input");
	var hlp = document.createElement("span");
	var hlp2 = document.createElement("span");
	var credits = document.createElement("div");
	
	styleElement(launcher, "textAlign: center;");
	
	var bottonWidth = "210px";
	btn.setAttribute('class', 'button'); 
	btn.type = "button";
	btn.value = "Replay Your Film";
	btn.style.marginRight = "15px";
	btn.style.width = bottonWidth;
	btn.addEventListener("click", replayVideo, false);
	
	btn2.setAttribute('class', 'button'); 
	btn2.type = "button";
	btn2.value = "Send your postcard downtown";
	btn2.style.marginRight = "10px";
	btn2.style.width = bottonWidth;
	btn2.addEventListener("click", continueDrawing, false);
	
	hlp.innerHTML = '<b>[?]</b>';
	hlp.style.cursor = "pointer";
	hlp.addEventListener("mouseover", showCodeHelp, false);
	hlp.addEventListener("mouseout", hideHelp, false);
	
	btn4.setAttribute('class', 'button'); 
	btn4.type = "button";
	btn4.value = "Share your film";
	btn4.style.marginRight = "15px";
	btn4.style.marginTop = "20px";
	btn4.style.width = bottonWidth;
	btn4.addEventListener("click", showShareVideo, false);
	
	btn3.setAttribute('class', 'button'); 
	btn3.type = "button";
	btn3.value = "Respond to a postcard";
	btn3.style.marginRight = "10px";
	btn3.style.marginTop = "20px";	
	btn3.style.width = bottonWidth;
	btn3.addEventListener("click", respondPostcard, false);
	
	hlp2.innerHTML = '<b>[?]</b>';
	hlp2.style.cursor = "pointer";
	hlp2.addEventListener("mouseover", showCodeHelp2, false);
	hlp2.addEventListener("mouseout", hideHelp, false);
	
	clearButtonsArea();
	launcher.appendChild(btn);	
	launcher.appendChild(btn2);
	launcher.appendChild(hlp);	
	launcher.appendChild(btn4);
	launcher.appendChild(btn3);	
	launcher.appendChild(hlp2);
	
	buttonsArea.appendChild(launcher);
}

function createPausedState(){
	var launcher = document.createElement("div");
	var btn = document.createElement("input");
	btn.setAttribute('class', 'button'); 
	btn.type = "button";
	btn.value = "Resume";
	btn.addEventListener("click", resumeAfterClose, false);
	styleElement(launcher, "textAlign: center;");
	clearButtonsArea();
	
	launcher.innerHTML = "We Used To Wait has paused because you have closed a window.<br/><br/>";
	launcher.appendChild(btn);
	
	buttonsArea.appendChild(launcher);
}

function continueDrawing(event){
	try{final_drawing.close()}catch(error){};
	var width = 1000;
	var height = 770;
	var left = (screen.width - width)/2;
	var top = (screen.height - height)/2;
	final_drawing = window.open("drawingtool.html", "final_drawing", "width="+width+", height="+height+", left="+left+", top=" + top);
	sendStat('/Click-on-Send-your-postcard-downton');
}

function respondPostcard(event){
	try{final_drawing.close()}catch(error){};
	var width = 1000;
	var height = 770;
	var left = (screen.width - width)/2;
	var top = (screen.height - height)/2;
	final_drawing = window.open("respond.html", "final_drawing", "width="+width+", height="+height+", left="+left+", top=" + top);
	sendStat('/Click-on-Respond-to-a-postcard');
}

/**
 * Resize Handler
 */
function resizeHandler(event){
	var top = document.getElementById("top");
	var y = (window.innerHeight > 700) ? 100 : 100*((window.innerHeight-550)/(700-550));
	if(y<0) y = 0;
	
	if((!launched)&&(canvasBirds != undefined)){
		canvasBirds.resize(window.innerWidth, window.innerHeight);
	}
}

function fadeBlocker(a){
	blockerTween.destroy();
	blockerTween = new TWEEN.Tween(blockerSettings);
	blockerTween.easing(TWEEN.Easing.Linear.EaseOut);
	blockerTween.onUpdate(fadeBlockerUpdate);
	blockerTween.onComplete(checkBlockerVisibility);
	blockerTween.to(1, {opacity: a});
}

function fadeBlockerUpdate(){
	var o = parseInt(blockerSettings.opacity);
	var of = blockerSettings.opacity/100;	
	
	blocker.style['filter'] = "alpha(opacity=" + o + ")";
	blocker.style['opacity'] = of + "";
	blocker.style['-moz-opacity'] = of + "";
	blocker.style['visibility'] = (of > 0.1) ? "visible" : "hidden";
}

function checkBlockerVisibility(){
	var o = (blockerSettings.opacity > 50) ? 90 : 0;
	
	blockerSettings.opacity = o;
	fadeBlockerUpdate();
}

/**
 * Code helper tooltip
 */

function showCodeHelp(event){	
	showHelp(event, "Continue your postcard and send it downtown. It could go to the Wilderness Machine, the Arcade Fire tour visuals, or another Wilderness Downtown user.");
}

function showCodeHelp2(event){	
	showHelp(event, "If you’ve found a postcard you can respond to it here. You’ll need the code in its lower right hand corner to do so.");
}

function showSearchHelp(event){
	showHelp(event, "This can be the home you grew up in or another place from your childhood. Entering the name of a school and the town will work as well.");
}

function showHelp(event, msg){
	hideHelp(event);
	codeHelper = document.createElement("div");
	codeHelper.id = "help";
	codeHelper.innerHTML = msg;
	document.body.appendChild(codeHelper);
	repositionCodeHelper(event);
	event.target.addEventListener("mousemove", repositionCodeHelper, false);
}

function repositionCodeHelper(event){
	codeHelper.style.top = (event.clientY - codeHelper.offsetHeight - 10) + "px";
	codeHelper.style.left = (event.clientX - codeHelper.offsetWidth/2) + "px";
}

function hideHelp(event){
	try{document.body.removeChild(codeHelper)}catch(error){}
}


function hideWarning(event){
	try{document.body.removeChild(warning)}catch(error){}
}

function refresh(even){
	window.location = "/";
}

function openCredits(){
	var width = 465;
	var height = 600;
	var left = (screen.width - width)/2;
	var top = (screen.height - height)/2;
	window.open("credits.html", "credits", "width="+width+", height="+height+", left="+left+", top=" + top + ", location=0, menubar=0, toolbar=0, scrollbars=1");
	sendStat('/Click-on-Credits');
}

function openTerms(){
	var width = 400;
	var height = 600;
	var left = (screen.width - width)/2;
	var top = (screen.height - height)/2;
	window.open("terms.html", "terms", "width="+width+", height="+height+", left="+left+", top=" + top + ", location=0, menubar=0, toolbar=0, scrollbars=1");
	sendStat('/Click-on-Terms');
}

function openPrivacyPolicy(){
	var width = 400;
	var height = 600;
	var left = (screen.width - width)/2;
	var top = (screen.height - height)/2;
	window.open("privacy-policy.html", "privacyPolicy", "width="+width+", height="+height+", left="+left+", top=" + top+ ", location=0, menubar=0, toolbar=0, scrollbars=1");
	sendStat('/Click-on-Privacy-Policy');
}

function openTheWildernessMachine(){
	var width = 465;
	var height = 600;
	var left = (screen.width - width)/2;
	var top = (screen.height - height)/2;
	window.open("the-wilderness-machine.html", "theWildernessMachine", "width="+width+", height="+height+", left="+left+", top=" + top+ ", location=0, menubar=0, toolbar=0, scrollbars=1");
	sendStat('/Click-on-The-Wilderness-Machine');
}


function sendStat(tag){
	//console.log("Stat: " + tag);	
	try{
		pageTracker._trackPageview(tag);
	}catch(error){};
}


