var lesson;

function init() {
	if (!FlashDetect.installed || FlashDetect.major <= 8) {
		$('#flashwarning').css('display','block');
	}
	swfobject.embedSWF(mediaURL+"mic-util.swf", "micutil", 1, 1, "9.0.0", null, null, {allowscriptaccess:"always"});
	
	$("#choose-mic").fancybox({
		'zoomSpeedIn': 0,
		'zoomSpeedOut':0,
		'frameHeight':300,
		'frameWidth':488,
		'overlayShow':true,
		'openHook': function() {
			//Fancy box makes a copy of the DOM, so be sure to find the correct #choose-mic-flash
			$('#fancy_div').find("#choose-mic-flash").attr('id','embed-flash-here'); 
			//Embedding this flash dynamically is not ideal, but IE7 will not pass the flashvars otherwise.
			swfobject.embedSWF(mediaURL+"AllowMic.swf", "embed-flash-here", 220, 145, "9.0.0", null, {mode:"choose"}, {allowscriptaccess:"always",wmode:"transparent"});
		},
		'closeHook': function() {
			$(this).parent().find('object').attr('id','remove-this-flash');
			swfobject.removeSWF('remove-this-flash');
		
			//IE specific code to take care of an IE-Flash bug
			//if ($.browser.msie && $.browser.version < 8.0) {
					window.location.reload();
			//}
		}
	});
	
	if ($.browser.msie && ($.browser.version < 7)) {
		$('#ie6-warning').css('display','block');
	}
}

function showMicBox(){
	$('#fancy_close').unbind("click");
	$('#fancy_close').click(function(){
		//safely remove the flash object
		
		
		$.fn.fancybox.close();
	});
	$('#choose-mic').click();
	
}

function micCheckComplete() {
	micUtil = document.getElementById('micutil');
	micDetected = micUtil.checkForMic();
	micMuted = micUtil.isMicMuted();

	if (!micDetected){
		$('#mic-setup').html(MakeMicDetectNotification());
		$('#mic-setup').css('display','block');
	}
	
	else if (micMuted) {
		var params = {
			allowScriptAccess: 'always',
			wmode: 'transparent'
		};
		$('#mic-setup').html(MakeUnmuteNotification());
		swfobject.embedSWF(mediaURL + "AllowMic.swf", "unmute-mic", 220, 145, "9.0.0", null, null, params);
		$('#mic-setup').css('display', 'block');
	}
}

function MakeUnmuteNotification() {
	//Currently, unmuting is not checked sufficiently. If the user clicks the "done" button, we
	//assume that they have checked "allow" in the flash settings panel and set micMuted to false,
	//regardless of what the user actually does. This is because #mic-util's isMicMuted() function
	//is instantiated at page loada and does not reflect realtime status. This is an acceptable bug at the moment since it fails safely (
	//the recordbubble simply won't record, and a fix would involve instantiating another flash object.		
	var unmuteHTML = '<h1>Lingt needs to use your microphone.</h1>\
						<h2>Just check "Allow" and "Remember".</h2><br />\
						<div id="unmute-mic"></div><br /><br />\
						To configure Flash to access your microphone, click the permission check-boxes above. You only have to do this once.<br /><br />\
						<input type="button" value="Done" onclick="unmuteReload()" />';
	return unmuteHTML;
}

function unmuteReload() {
	swfobject.removeSWF('unmute-mic');
	$('#mic-setup').hide();
	window.location.reload();
}

function MakeMicDetectNotification() {
	var detectHTML = '<h1>We can\'t detect a microphone.</h1>\
					<br />Plug in a microphone and reload this page if you want to record your voice.\
					<br /><br /><input type="button" value="Reload" onclick="window.location.reload()" />';
					
	return detectHTML;
}

function showGetName(){
	$('#publish-save').hide('slide',{direction: 'left'},300,function(){
		$('#get-name').show('slide',{direction: 'left'},500,function(){
			$(this).append('<a class="exit-build-confirm" onClick="hideGetName()">X</a>');
			$('#student-name').select();
			$('#student-question').mouseover(function(){
				$('#email-popup').fadeIn('slow');
			})
			$('#student-question').mouseout(function(){
				$('#email-popup').fadeOut('slow');
			})
		});
	});
}

function hideGetName(){
	$('#get-name').hide('slide',{direction: 'left'},300,function(){
		$('#publish-save').show('slide',{direction: 'left'},500);
	});
}

function submit(){
	
	//check that a name has been entered
	if ($('#student-name').val() == '' || $('#student-name').val() == 'required') {
		$('#student-name').css('color','red').val("required");
	}
	else {
		var lessonBoxes = $('#builder-content').children('.lesson-box-response');
		var boxes = $.makeArray(lessonBoxes);
		for (var i in boxes) {
			var inputType = $(boxes[i]).children().attr("class");
			switch (inputType) {
			
				case "voice-input":
					var value = $(boxes[i]).find("object").attr('id');
					var name = i + 'v';
					break;
				case "text-prompt-input":
					var value = $(boxes[i]).children('.text-prompt-input').find('textarea').val();
					var name = i + 't';
					break;
				case "paired-prompt":
					var value = $(boxes[i]).children('.paired-prompt').children(':last').attr('id');
					var name = i + 'v';
					break;
				case "paired-input":
					var value = $(boxes[i]).children('.paired-input').children(':first').attr('id');
					var name = i + 'v';
					break;
			}
			
			EmbedInputValue(name, value);
		}
		
		EmbedInputValue('author', $('#student-name').val())
		EmbedInputValue('email', $('#student-email').val())
		EmbedInputValue('lid', lesson.id);
		
		$('#builder-form').submit();
	}
}

function EmbedInputValue(name,value){
	var inputTag = $('<input type="hidden" name="' + name + '" />');
	inputTag.val(value); 
	$('#builder-form').append(inputTag);
}

function render(lid){
	var lessonJSON = $.getJSON(mediaURL + 'lessons/' + lid + '.js', function(json){
		var lessonObject = eval(json);
		renderLesson(lessonObject);
	});
}

function renderLesson(lessonObject){
	
	lesson = lessonObject;
	$('#title-input').text(lesson.title);
	
	var content = lesson.content;
	var builderContent = $('#builder-content');
	for (var i in content) {
		var type = content[i].type;
		var value = content[i].value;
		
		switch(type){
			
			case 'textinput':
				builderContent.append(renderTextInput(value));
				break;
			
			case 'videoinput':
				builderContent.append(renderVideoInput(value));
				
				var videoURL = 'http://www.youtube.com/v/' + value + '&rel=0&fs=0&border=0';
				var params = {
					allowFullScreen: "false",
					allowScriptAccess: "always",
					wmode: "transparent",
					vid: value
				}
				var width = "480";
				var height = "295";
				swfobject.embedSWF(videoURL, value, width, height, "9.0.0", null, null, params);
				break;
			
			case 'voiceinput':
				if ("mp3mode" in content[i]){
					var mp3mode = "true";
				} else {
					var mp3mode = "false";
				}
				builderContent.append(renderVoiceInput(value));
				var swf = mediaURL + 'recordbubble.swf';
				var params = {
					allowScriptAccess: "always",
					wmode: "transparent"
				};
				var flashvars = {
					fid: value,
					playback: "true",
					instantiate: "true",
					mp3mode: mp3mode
				};
				var width = "95";
				var height = "85";
				swfobject.embedSWF(swf, value, width, height, "9.0.0", null, flashvars, params);
				break;
			
			case 'imageinput':
				builderContent.append(renderImageInput(value));
				break;
				
			case 'textprompt':
				builderContent.append(renderTextPrompt());
				$('textarea').elastic();
				break;
			
			case 'voiceprompt':
				var uniqueID = GetIdentifier();
				builderContent.append(renderVoicePrompt(uniqueID));
				
				var swf = mediaURL + 'recordbubble.swf';
				var flashvars = {
					fid: uniqueID,
					respond: "true"
				};
				var params = {
					allowScriptAccess: "always",
					wmode: "transparent"
				}
				var width = "95";
				var height = "85";
				swfobject.embedSWF(swf, uniqueID, width, height, "9.0.0", null, flashvars, params);
				break;
			
			case 'pairedprompt':
				if ("mp3mode" in content[i]){
					var mp3mode = "true";
				} else {
					var mp3mode = "false";
				}
				var uniqueID = GetIdentifier();
				builderContent.append(renderPairedPrompt(value,uniqueID));
				
				var swf1 = mediaURL + 'recordbubble.swf';
				var flashvars1 = {
					fid: value,
					instantiate: "true",
					playback: "true",
					mp3mode: mp3mode
				};
				var params2 = {
					allowScriptAccess: "always",
					wmode: "transparent"
				}
				var width = "95";
				var height = "85";
				swfobject.embedSWF(swf1, value, width, height, "9.0.0", null, flashvars1, params2);
				
				var swf2 = mediaURL + 'recordbubble.swf';
				var flashvars2 = {
					fid: uniqueID,
					respond: "true",
					reverse: "true"
				};

				swfobject.embedSWF(swf2, uniqueID, width, height, "9.0.0", null, flashvars2, params2);
				
				break;
				
			case 'pairedinput':
				if ("mp3mode" in content[i]){
					var mp3mode = "true";
				} else {
					var mp3mode = "false";
				}
				var uniqueID = GetIdentifier();
				builderContent.append(renderPairedInput(value,uniqueID));
				
				var swf = mediaURL + 'recordbubble.swf';
				var flashvars1 = {
					fid: value,
					instantiate: "true",
					playback: "true",
					reverse: "true",
					mp3mode: mp3mode
				};
				var params = {
					allowScriptAccess: "always",
					wmode: "transparent"
				}
				var width = "95";
				var height = "85";
				swfobject.embedSWF(swf, value, width, height, "9.0.0", null, flashvars1, params2);
				
				var flashvars2 = {
					fid: uniqueID,
					respond: "true"
				};

				swfobject.embedSWF(swf, uniqueID, width, height, "9.0.0", null, flashvars2, params);
				
				break;
		}
	}
}

function renderPairedInput(playbackID, recordID){
	var pairedInput = $('<div class="paired-input" style="width:250px;"><div id="'+recordID+'"></div><div id="'+playbackID+'"></div></div>');
	return WrapInResponseContainer(pairedInput);
}

function renderPairedPrompt(playbackID, recordID){
	var pairedPrompt = $('<div class="paired-prompt" style="width:250px;"><div id="'+playbackID+'"></div><div id="'+recordID+'"></div></div>');
	return WrapInResponseContainer(pairedPrompt);
}

function renderVoicePrompt(value){
	var voicePrompt = $('<div class="voice-input"><div id="'+value+'"></div></div>');
	return WrapInResponseContainer(voicePrompt);
}

function renderVoiceInput(value){
	var voiceInput = $('<div class="voice-input"><div id="'+value+'"></div></div>')
	return WrapInContainer(voiceInput);
}

function renderTextPrompt(){
	var textPrompt = $('<div class="text-prompt-input"></div>');
	textPrompt.append($('<textarea></textarea>').focus(function(){
				$(this).css({'border':'#0071bc solid 3px','background':'white'});
			}).blur(function(){
				$(this).css({'border':'#d2d2d2 solid 3px','background':'white'})
			}));
	return WrapInResponseContainer(textPrompt);
}

//takes an image file with extension.
function renderImageInput(value){
	var imageFile = mediaURL + 'upload/' + value;
	var imageInput = $('<div class="image-input"></div>');
	imageInput.append($('<img />').attr('src', imageFile));
	return WrapInContainer(imageInput);
}

function renderVideoInput(value){
	var videoInput = $('<div class="video-input"><div id="'+value+'"></div></div>');
	return WrapInContainer(videoInput);
}

function renderTextInput(value){
	var textInput = $('<div class="text-input"></div>');
	textInput.append($('<span></span>').html(replaceNewLines(value)));
	return WrapInContainer(textInput);
}

function WrapInResponseContainer(input){
		var container = $(document.createElement('div')).attr('class','lesson-box-response').css('display','block').css('position','relative');
		
		return container.append(input);
}

function WrapInContainer(input){
		var container = $(document.createElement('div')).attr('class','lesson-box').css('display','block').css('position','relative');
		
		return container.append(input);
}

function replaceNewLines(string){
	return string.replace(/\n/g,'<br />');
}

var timestamp = new Date();
timestamp = new String(timestamp.getTime());
//Eleven digits will suffice to create a unique identifier for the next thirty years.
timestamp = timestamp.substring(1,12);
function GetIdentifier(){
	timestamp = parseInt(timestamp)+1;  //must increment in this way since prompts are rendered too quickly to generate unique timestamp each time.
	return uid+''+timestamp;
}