/* 
 *      Functions for Simulation Scenarios creation and maintenance
 */

var currentSim;
var currentSimData;
var currentSimTime;
var currentSimTimeMax;
var currentSimTimer;
var currentSimCorrectAnswers;
var currentSimWrongAnswers;
var currentSimWrongAnswersThatHurt;
var currentSimHits;
var currentSimReady;
var currentSimReadyCounter;
var currentSimDependencies = false;
var ID;

function simUpdateNickname( status ) {
    
    if ( status === undefined ) status = 'submit';
    
    if ( status === 'submit' ) {
	var nickname = $('#sim-nickname-input').val();
	nickname = nickname.replace(/[^a-zA-Z0-9]/g, '');

	if ( nickname.length > 0 ) {
	    nickname = nickname.substring(0, simNicknameSize);
	    zork('So you name is ' + nickname + '!');
	    courseStatus.nickname = nickname;
	    finish();
	    next();
	} else {
	    $('#sim-nickname-input').attr( 'placeholder', sim_nickname_required );
	}
    } else if ( status === 'start' ) {
	$('#sim-nickname-input').attr( 'placeholder', sim_nickname_start );
    }
}

// Sim Hud Management
function simUpdateLives() {
    var livesShowing = $( '#sim-lives .sim-life' ).length;
    var lives = courseStatus.lives;
    
    zork( 'The HUD is showing ' + livesShowing + ' lives, and you have ' + lives + '.');
    
    if ( livesShowing > lives ) {
	for ( i = livesShowing; i > lives; i-- ) {
	    $('.sim-life:nth-child(' + i + ')').fadeOut(500);
	    
	    setTimeout( function() {
		$('.sim-life:last-child()').remove();
	    }, 500 );
	    
	    zork( 'Eliminating life ' + i + '.');
	}
    } else if ( livesShowing < lives ) {
	for ( i = 0; i < lives; i++ ) {
	    $( '#sim-lives' ).append( '<img class="sim-life" src="images/sim/lives.png">' );
	}
    }
}

function simUpdateHealth() {
    var health = courseStatus.health;
    
    //var delay = currentSimWrongAnswers * 500;
    var delay = currentSimWrongAnswersThatHurt * 500;
    
    // Normalizes health
    if ( health < 100 && health > 0 ) {
	
    } else if ( health >= 100 ) {
	courseStatus.health = 100;
    } else if ( health <= 0 ) {
	courseStatus.health = 0;
	setTimeout( function() {
	    simLivesLose();
	}, delay);
    }
    
    // Update health bar
    $( '#sim-health-current' ).css( 'width', courseStatus.health + '%' );
    zork( 'You are ' + courseStatus.health + '% healthy!' );
    
    $( '#sim-health-current' ).removeClass( 'dead-health' );
    $( '#sim-health-current' ).removeClass( 'low-health' );
    $( '#sim-health-current' ).removeClass( 'medium-health' );
    $( '#sim-health-current' ).removeClass( 'high-health' );
    $( '.sim-life' ).removeClass( 'animated-shake-infinite' );
    
    if ( courseStatus.health > simHighHealth ) {
	$( '#sim-health-current' ).removeClass( 'dead-health' );
	$( '#sim-health-current' ).addClass( 'high-health' );
	zork( 'You are fine as a fiddle! A bass fiddle...' );
    } else if ( courseStatus.health > simMediumHealth && courseStatus.health <= simHighHealth ) {
	$( '#sim-health-current' ).addClass( 'medium-health' );
	zork( 'You are still pretty well off...' );
    } else if ( courseStatus.health > simLowHealth && courseStatus.health <= simMediumHealth ) {
	$( '#sim-health-current' ).addClass( 'low-health' );
	zork( 'You aren\'t that good. You should see a Doctor...');
    } else if ( courseStatus.health <= simLowHealth ) {
	$( '#sim-health-current' ).addClass( 'dead-health' );
	zork( 'You are almost DEAD!!!' );
	$( '.sim-life:last-child()' ).addClass( 'animated-shake-infinite' );
    }
}

function simUpdateScore( instant, delay ) {
    
    if ( instant === undefined ) instant = true;
    if ( delay === undefined ) delay = 0;

    
    var score = courseStatus.score;
    var scoreShown = parseInt( $( '#sim-points' ).text() );
    var scoreUpdate = scoreShown;
   
    if ( instant === true || scoreShown >= score ) {
	$( '#sim-points' ).html( score );
	zork( 'You have ' + score + ' SCORES!' );
    } else if ( scoreShown < score ) {
	playerSFXPlay( 'score-up' );
	scoreUpdate = scoreShown + 1;
	$( '#sim-points' ).html( scoreUpdate );

	setTimeout( function() {
	    simUpdateScore( false, 0 );
	}, 1);
    }
    if ( scoreShown >= score - 1 && instant !== true ) { 
	playerSFXPlay( 'coin' );
    }
}

function simJoinScores() {
    courseStatus.score = courseStatus.score_1 + courseStatus.score_2 + courseStatus.score_3;
}

function simRaiseValue( element, score, instant ) {

    if ( instant === undefined ) instant = false;
    
    var target = $( '#'+ element );
    var scoreShown = parseInt( target.text() );
    var scoreUpdate = 0;
    
    if ( score === undefined || isNaN(score) ) {
	score = 0;
    }
    if ( scoreShown === undefined || isNaN(scoreShown) ) {
	score = 0;
    }
    
    if ( instant === true || scoreShown >= score ) {
	target.html( score );
	zork( 'You have ' + score + ' SCORES!' );
    } else if ( scoreShown < score ) {
	playerSFXPlay( 'score-up' );
	
	scoreUpdate = scoreShown + 1;
	target.html( scoreUpdate );

	setTimeout( function() {
	    simRaiseValue( element, score );
	}, 1);
    }
    if ( scoreShown === score - 1 ) { 
	playerSFXPlay( 'coin' );
    }
}

function simAddPoints() {
    var targetTop = $( '#sim-points' ).position().top;
    var targetLeft = $( '#sim-points' ).position().left;
    
    for ( i = 0; i < currentSimData.answers_src.length; i++ ) {
	if ( $( '#sim-answer-' + i ).hasClass( 'selected sim-answer-correct' ) ||
		$( '#sim-answer-' + i + ':not(.selected)' ).hasClass( 'sim-answer-incorrect' )) {
	    
	    $( '#slide-'+ courseStatus.position ).append(
		'<div style="' + currentSimData.feedback_style[ i ] +   '" class="sim-point-gain">' + simPoints + ' ' + sim_points_name + '</div>'
		);
	    
	} 
    }
    
    setTimeout(function(){
	$( '.sim-point-gain' ).css( 'top', targetTop + 'px' );
	$( '.sim-point-gain' ).css( 'left', targetLeft + 'px' );
	$( '.sim-point-gain' ).css( 'transform', 'scale(0.5) translate(-50%, -50%' );
	$( '.sim-point-gain' ).css( 'opacity', '0.1' );
    }, 3000);
    
    setTimeout(function(){
	simUpdateScore( false );
    }, 3400);
    
    setTimeout(function(){
	$( '.sim-point-gain' ).remove();
    }, 3500);
}

function simGlobalFeedback() {
    if ( currentSimData.global_feedback_positive !== false || currentSimData.global_feedback_negative !== false ) {
	if ( currentSimCorrectAnswers > 0 && currentSimWrongAnswers <= 0 ) {
	    $( '#slide-'+ courseStatus.position ).append(
		    '<div class="sim-global-feedback-positive">' + currentSimData.global_feedback_positive + '</div>'
		    );
	} else {
	    $( '#slide-'+ courseStatus.position ).append(
		    '<div class="sim-global-feedback-negative">' + currentSimData.global_feedback_negative + '</div>'
		    );
	}
	setTimeout(function(){
	    $( '.sim-global-feedback-positive' ).remove();
	    $( '.sim-global-feedback-negative' ).remove();
	}, 5500);
    }
}

function simUpdateHud() {
    simUpdateLives();
    simUpdateHealth();
    simUpdateScore();
}

function simHealthHit( times ) {
    var currentSimHits = times;
    zork( 'You character\'s going to be hit ' + times +' times.' );
    times -= 1;
    if ( times > 0 ) {
	playerSFXRestart( 'hurt' );
	setTimeout( function(){
	    simHealthHit( times );
	},300);
    }
    var hitLeft = $( '#sim-health-current' ).position().left + $( '#sim-health-current' ).width();
    var hitTop = $( '#sim-health-current' ).position().top + $( '#sim-health-current' ).height();
    
    $( '#slide-'+ courseStatus.position ).append(
	    '<div style="position: absolute; top: '+hitTop+'px;left: '+hitLeft+'px; z-index: 10000;" class="sim-health-hit">' + simDamage + '</div>'
	);
    setTimeout(function(){
	$( '.sim-health-hit:nth-child(1)' ).remove();
    }, 5000);
}

function simAddDamage() {
    var targetTop = $( '#sim-health-max' ).position().top;
    var targetLeft = $( '#sim-health-max' ).position().left;
    var delayCounter = 0;
    var delay = 0;
    
    if ( currentSimTime > 0 && simTimeOut === 'fail' || simTimeOut === 'submit' ) {
	for ( i = 0; i < currentSimData.answers_src.length; i++ ) {
	    
	    var itWillHurt = false;
	    
	    if ( simNotRequiredButSelectedDamage === true && $( '#sim-answer-' + i + '.selected' ).hasClass( 'sim-answer-incorrect' ) ) {
		itWillHurt = true;
	    }
	    
	    if ( $( '#sim-answer-' + i + ':not(.selected)' ).hasClass( 'sim-answer-correct' ) ) {
		itWillHurt = true;
	    }
	    
	    if ( itWillHurt === true ) {    
		zork( 'Adding damage image and points to answer ' + i + '.');
		
		delay = delayCounter * 1000;
		var delaySeconds = delay / 1000;
		
		$( '#slide-'+ courseStatus.position ).append(
		    '<img style="' + currentSimData.feedback_style[ i ] + ';animation-delay:'+delaySeconds+'s;" class="sim-damage-image" src="' + currentSimData.damage_src[ i ] + '">' +
		    '<div style="' + currentSimData.feedback_style[ i ] +  ';animation-delay:'+delaySeconds+'s;" class="sim-damage-gain">' + simDamage + ' ' + sim_damage_name + '</div>'
		    );
		
		
		$( '#layer-sim' ).append(
		    '<img style="' + currentSimData.character_style +';animation-delay:'+delaySeconds+'s;" class="sim-element sim-injury-image animated-fade-in" src="' + currentSimData.injury_src[ i ] + '">' 
		    );

		var sound = currentSimData.damage_sound[ i ];
		playerSFXPlayAfter( sound, delay );
		delayCounter += 1;

	    } 
	}
    } else if ( currentSimTime <= 0 && simTimeOut === 'fail' ) {
	zork( 'Adding damage to everything!!!');
	for ( i = 0; i < currentSimData.answers_src.length; i++ ) {
	    
	    
	delay = delayCounter * 1000;
	var delaySeconds = delay / 1000;

	$( '#slide-'+ courseStatus.position ).append(
	    '<img style="' + currentSimData.feedback_style[ i ] + ';animation-delay:'+delaySeconds+'s;" class="sim-damage-image" src="images/sim/damage/wrong.png">'
	    );
    
	//if ( currentSimData.keys.includes( i ) ) {
	//if ( stringIncludes( currentSimData.keys, i ) ) {
	if ( currentSimData.keys.indexOf( i ) > -1 ) {
	    $( '#slide-'+ courseStatus.position ).append(
		'<div style="' + currentSimData.feedback_style[ i ] +  ';animation-delay:'+delaySeconds+'s;" class="sim-damage-gain">' + simDamage + ' ' + sim_damage_name + '</div>'
		);
	    currentSimWrongAnswersThatHurt += 1;
	}

	var sound = currentSimData.damage_sound[ i ];
	playerSFXPlayAfter( 'damage-wrong', delay );
	delayCounter += 1;

	}
    }
    
    //var damage = simDamage * currentSimWrongAnswers;
    var damage = simDamage * currentSimWrongAnswersThatHurt;
    
    delay += 1000;
    
    setTimeout(function(){
	$( '.sim-damage-gain' ).css( 'top', targetTop + 'px' );
	$( '.sim-damage-gain' ).css( 'left', targetLeft + 'px' );
	$( '.sim-damage-gain' ).css( 'transform', 'scale(0.5) translate(-50%, -50%' );
	$( '.sim-damage-gain' ).css( 'opacity', '0.1' );
	$( '.sim-damage-image' ).css( 'transform', 'scale(0) translate(-50%, -50%' );
	$( '.sim-damage-image' ).fadeOut(500);
    }, delay);
    
    delay += 1000;

    setTimeout(function(){
	$( '.sim-damage-gain' ).remove();
	$( '.sim-damage-image' ).remove();
	simHealthDamage( damage );
    }, delay);
}

function simMakeCharacterCry() {
    $( '#sim-character' ).attr( 'src', 'images/character/crying/crying-' + courseStatus.character + '.png' );
    if ( currentSimData.character_geared === false ) {
	$( '#sim-gear' ).attr( 'src', 'images/character/damaged/damaged-' + courseStatus.character + '.png' );
    } else if ( currentSimData.character_geared === true ) {
	$( '#sim-gear' ).attr( 'src', currentSimData.character_gear_src );
    }
}

function simHealthDamage( damage ){
    if ( damage > 0 ) {
	var points = damage;

	if ( typeof damage === 'undefined' || typeof damage === null || typeof damage === '' ) {
	    points = simDamage;
	}

	var times = damage / simDamage;

	courseStatus.health -= points;
	zork( 'You lost ' + points + '% of health!' );
	simHealthHit( times );
	playerSFXPlay( 'health-down' );
	simUpdateHealth();
    }
}

function simHealthHeal( heal ){
    var points = heal;
    if ( typeof heal === 'undefined' || typeof heal === null || typeof heal === '' ) {
	points = simDamage;
    }
    
    courseStatus.health += points;
    zork( 'You gained ' + points + '% of health!' );
    simUpdateHealth();
}

function simLivesLose( lives ) {
    var number = lives;
    
    if ( typeof lives === 'undefined' || typeof lives === null || typeof lives === '' ) {
	number = 1;
    }
    
    zork( 'Losing ' + number + ' lives...');
    
    if ( courseStatus.lives > number ) {    
	courseStatus.lives -= number;
	playerSFXPlay( 'lose-life' );
	simUpdateLives();
	
	setTimeout( function() {
	    simHealthHeal( 100 );
	}, 1000);
	
    } else if ( courseStatus.lives <= number ) {
	courseStatus.lives = 0;
	simUpdateLives();
	simGameOver();
    }
}

// Sim medals (UNUSED)
function simMedal( medalNumber, firstSim, lastSim ) {
    var win = true;
    var length = lastSim - firstSim; 
    for( i = firstSim; i < length; i++ ) {
	if ( courseStatus.sim_percentage[i] < 100 ) {
	    win = false;
	}
    }
    
    var score = 0;
    
    if ( win === true ) {
	if ( medalNumber === 1 ) {
	    courseStatus.medal_1 = true;
	    score = courseStatus.score_1;
	    courseStatus.score_1 += score;
	} else if ( medalNumber === 2 ) {
	    courseStatus.medal_2 = true;
	    score = courseStatus.score_2;
	    courseStatus.score_2 += score;
	} else if ( medalNumber === 3 ) {
	    courseStatus.medal_3 = true;
	    score = courseStatus.score_3;
	    courseStatus.score_3 += score;
	}
	simJoinScores();
	$( '#medal-' + medalNumber ).show();
	playerSFXPlay( 'win' );
    } 
}

// Sim Timer

function simTimerCreate() {
    if ( typeof currentSimData.time === 'number' ) {
	currentSimTimeMax = currentSimData.time;
	currentSimTime = currentSimData.time;
    } else {
	currentSimTimeMax = simTimeLimit;
	currentSimTime = simTimeLimit;
    }    
    
    var seconds = convertMSToSeconds( currentSimTime );
    
    $('#slide-'+ courseStatus.position).append(
	    '<div id="sim-timer-bar">' +
		'<span id="sim-time-left">'+seconds+'</span>' +
	    '</div>'
	    );
    setTimeout( function(){
	$('#sim-timer-bar').circleProgress({
	    //https://github.com/kottenator/jquery-circle-progress
	    value: 1,
	    size: 128,
	    startAngle: -1.55,
	    thickness: 5,
	    lineCap: 'round',
	    animationStartValue: 1.0,
	    animation: {
		duration: 1000,
		easing: 'linear'
	    },
	    fill: {
		color: ['#ffec1b']
	    }
	});
    }, 500);
    if ( simGraded() === false ) {
	setTimeout( function(){
	    simTimerStart();
	}, currentSimData.delay );
    }
    
    
}

function simTimerStart() {
    var seconds = convertMSToSeconds( currentSimTime );
    
    window.clearInterval(currentSimTimer);
    
    currentSimTimer = setInterval(function() {
	simTimerUpdate();
    }, 1000);
    zork('Starting timer! You have ' + seconds + ' seconds. That can be a lot!' );
}

function simTimerUpdate() {
    currentSimTime -= 1000;
    
    if ( $( '#sim-time-left' ).length <= 0 || currentSimTime < 0 ) {
	currentSimTime = 0;
	window.clearInterval(currentSimTimer);
	zork('Clearing timer...' );
    } else {
	var seconds = convertMSToSeconds( currentSimTime );
	$('#sim-time-left').html( seconds );
	zork('You have ' + seconds + ' seconds left...' );

	var percentage = currentSimTime / currentSimTimeMax;

	var bar = $('#sim-timer-bar').circleProgress('value');
	$('#sim-timer-bar').circleProgress({ animationStartValue: bar, value: percentage });

	var percentageLow = simMediumHealth / 100;
	var percentageMed = simHighHealth / 100;

	if ( percentage <= 0 ) {
	    currentSimTime = 0;
	    $('#sim-timer-bar').circleProgress({ fill: { color: ['#ffec1b']}});
	    $( '#sim-timer-bar' ).removeClass( 'really-panic' );
	    window.clearInterval(currentSimTimer);
	    playerSFXStop( 'panic' );
	    playerMusicSpeed( 1 );
	    simSubmit( 'time-out' );
	} else if ( percentage > percentageLow && percentage <= percentageMed ) {
	    $( '#sim-timer-bar' ).addClass( 'panic' );
	    $('#sim-timer-bar').circleProgress({ fill: { color: ['#e2574c']}});
	    playerMusicSpeed( 1.15 );
	} else if ( percentage > 0 && percentage <= percentageLow ) {
	    playerSFXPlay( 'panic' );
	    playerMusicSpeed( 1.3 );
	    $( '#sim-timer-bar' ).removeClass( 'panic' );
	    $( '#sim-timer-bar' ).addClass( 'really-panic' );
	    $('#sim-timer-bar').circleProgress({ fill: { color: ['#e2574c']}});
	}
    }
}

// Sim Questions

function simMakeVariables() {
    if ( courseStatus.sim_points === undefined ) {
	courseStatus.sim_points = new Array;
    }
    if ( courseStatus.sim_percentage === undefined ) {
	courseStatus.sim_percentage = new Array;
    }
    if ( courseStatus.sim_time_taken === undefined ) {
	courseStatus.sim_time_taken = new Array;
    }
    if ( courseStatus.sim_time_left === undefined ) {
	courseStatus.sim_time_left = new Array;
    }
}

function simLoadData( sim ) {
    if ( ID === undefined ) {
	ID = currentSim;
    }
    simMakeVariables();
    if ( simLazyLoad === true ) {
	$.getScript( 'config/sim-questions/sim-questions-' + sim + '.js');
	zork('I needed to fetch this "sim-questions-' + sim + '.js" data...');
    }
}

function simDataLoaded( sim ) {
    zork('Let\'s check if the sim data has been loaded...');
    currentSimReadyCounter -= 1;
    if ( simQuestions[ sim ] !== undefined || currentSimReadyCounter <= 0 ) {
	zork('Yup!');
	
	
	if ( currentSimDependencies === true && courseStatus.sim_previous > -1 ) {
	    currentSimData = simQuestions[ sim ][ courseStatus.sim_previous ];
	    zork( 'For this simulation we\'ll be using question ' + sim + ' with the previous option ' + courseStatus.sim_previous + '.' );
	} else {
	    var length = simQuestions[ sim ].length;
	    var random = Math.floor(Math.random() * length);
	    currentSimData = simQuestions[ sim ][ random ];
	    courseStatus.sim_previous = random;
	    zork( 'For this simulation we\'ll be using question ' + sim + ' with option ' + random + '.' );
	}
	simConstruct( sim );
	clearInterval(currentSimReady);
    } else {
	zork('Nope...');
    }
}

function simAddHud() {
    $('#slide').append(
	'<div id="sim-hud" style="display: none;">'+
	    '<div id="sim-score" title="' + sim_score_name + '">'+
		'<img src="images/sim/score.png"> <span id="sim-points">0</span>'+
	    '</div>'+
	    '<div id="sim-lives" title="' + sim_lives_name + '">'+
		'<img class="sim-life" src="images/sim/lives.png">'+
		'<img class="sim-life" src="images/sim/lives.png">'+
		'<img class="sim-life" src="images/sim/lives.png">'+
	    '</div>'+
	    '<div id="sim-health" title="' + sim_healthbar_name + '">'+
		'<div id="sim-health-max">'+
		    '<div id="sim-health-current">'+
		    '</div>'+
		'</div>'+
	    '</div>'+
	'</div>'
	);
    simUpdateHud();
}


function simBuildHtml( sim, dependency ) {
    
    if ( dependency === undefined ) dependency = false; 
    
    currentSimDependencies = dependency;
    
    if ( ID === undefined ) {
	ID = currentSim;
    }
    
    currentSimData = false;
    currentSim = sim;
    simQuestions = [];
    simLoadData( sim );
    currentSimReady = setInterval( function() {
	simDataLoaded( sim );
	currentSimReadyCounter = 100;
    }, 250);
    
}

function simConstruct( sim ) {
    courseStatus.level = currentSimData.level;
	zork('Creating Layer system' );
	$('#slide-'+ courseStatus.position).append(
	    '<div id="layers">' +
		'<div id="layer-sim" class="layer layer-content layer-sticky animated-pop-in">' +

		'</div>'+
	    '</div>'
	);

	setTimeout( function() {
	    zork('Building Simulation basics!');

	    $('#slide-'+ courseStatus.position + ' #layer-sim').append(
		'<h2 id="sim-question" class="sim-element" style="' + currentSimData.question_style + '">' + currentSimData.question_message + '</h2>' +
		currentSimData.bg_objects 
		);

	    var answers = currentSimData.answers_src.length;

	    var clearButton = '';
	    var specialSelection = '';

	    if ( currentSimData.buttons === 'clear' ) {
		clearButton = 'sim-clear-button';
	    }
	    if ( currentSimData.selection === 'special' ) {
		specialSelection = 'sim-special-selection';
	    }

	    for ( i = 0; i < answers; i++ ) {
		var delayInSeconds = 4;
		var delayTutorial = 5 + i;
		if ( currentSimData.delay !== false ) {
		    delayInSeconds = currentSimData.delay / 1000;
		    delayTutorial = delayInSeconds + 1 + ( i / 2 );
		}

		$('#slide-'+ courseStatus.position + ' #layer-sim').append(
		    '<img src="' + currentSimData.answers_src[i] + '" id="sim-answer-' + i + '" class="sim-selection sim-element sim-answer ' + clearButton +' ' + specialSelection +' button-click button-select animated-pop-in animation-delay-4 ' + currentSimData.answers_class[i] + '" style="' + currentSimData.answers_style[i] + ' animation-delay: ' + delayInSeconds + 's, ' + delayTutorial + 's;">' 
		    );
		setTimeout( function() {
		    $( '#sim-answer-' + i ).removeClass( 'animated-pop-in' );
		}, delayTutorial * 1000 ); 
	    }


	    if ( currentSimData.selection === 'special' ) {

		for ( i = 0; i < answers; i++ ) {
		    $('#slide-'+ courseStatus.position + ' #layer-sim').append(
			'<img src="' + currentSimData.selection_src[i] + '" id="sim-contour-' + i + '" class="sim-contour ' + clearButton +' ' + specialSelection +' sim-element" style="' + currentSimData.answers_style[i] + '">' 
			);
		}
	    }

	    if ( currentSimData.character_hidden === false ) {
		zork('Adding character!');

		$('#slide-'+ courseStatus.position + ' #layer-sim').append(
			'<img src="images/character/naked/character-' + courseStatus.character + '.png" id="sim-character" class="sim-element ' + currentSimData.character_class + ' " style="' + currentSimData.character_style + '">'
		    );

		if ( currentSimData.character_geared === true ) {
		    zork('Adding badass gear!!!');
		    $('#slide-'+ courseStatus.position + ' #layer-sim').append(
			'<img src="' + currentSimData.character_gear_src + '" id="sim-gear" class="sim-element" style="' + currentSimData.character_gear_style + '">'
			 );
		} else {
		    zork('Adding "human" clothes...');
		    $('#slide-'+ courseStatus.position + ' #layer-sim').append(
			'<img src="images/character/clothes/clothes-' + courseStatus.character + '.png" id="sim-gear" class="sim-element ' + currentSimData.character_gear_class + '" style="' + currentSimData.character_gear_style + '">'
			);
		}
	    }

	    zork('Adding instructions!');

	    $('#slide-'+ courseStatus.position + ' #layer-sim').append(
		currentSimData.instruction 
		);

	    zork('Adding submit button!');

	    if ( currentSimData.submit_fail !== false ) {
		$('#slide-'+ courseStatus.position + ' #layer-sim').append(
		    '<div id="sim-submit-fail" class="sim-submit button-click sim-hover sim-text-button animated-pop-in ' + currentSimData.submit_fail_class + '" style="' + currentSimData.submit_fail_style + 'display: none;" onclick="simSubmitFail(); return false;">' + currentSimData.submit_fail + '</div>'
		    );
	    }

	    $('#slide-'+ courseStatus.position + ' #layer-sim').append(
		'<div id="sim-submit" class="sim-submit button-click sim-hover sim-text-button animated-pop-in ' + currentSimData.submit_class + '" style="' + currentSimData.submit_style + 'display: none;" onclick="simSubmit( \'submit\' ); return false;">' + currentSimData.submit + '</div>'
		);

	    zork('Adding feedback!');
	    if ( simGameOverWindow === 'window' ) {
		$('#slide-'+ courseStatus.position + ' #layers').append(
		    '<div id="layer-game-over" class="sim-feedback animated-fade-in" style="display: none">' +
			'<img src="images/sim/game-over.png" title="Game Over" id="sim-game-over" class="sim-feedback-image animated-fade-in animation-delay-2"/>' +
			'<h2 class="animated-fade-in animation-delay-4">' + sim_game_over_message_1 + '</h2>' +
			'<h3 class="animated-fade-in animation-delay-6">' + sim_game_over_message_2 + '</h3>' +
			'<div class="button-click sim-hover sim-text-button sim-game-over-try-again animated-pop-in animation-delay-7" onclick="courseResetSoft(); reload(); return false">' + sim_game_over_try_again + '</div>' +
			'<div class="button-click sim-hover sim-text-button sim-game-over-quit animated-pop-in animation-delay-8" onclick="courseResetSoft(); exit(); return false">' + sim_game_over_quit + '</div>' +
		    '</div>'
		);
	    }
	    $( '.sim-answer-answered' ).removeClass( 'sim-tutorial' );
	    //$( '.sim-answer' ).hover( function() { $( '.sim-answer' ).removeClass( 'sim-tutorial' ); } );
	    $( '.sim-answer' ).click( function() { $( '.sim-answer' ).removeClass( 'sim-tutorial' ); } );

	    //$( '.sim-submit' ).hover( function() { $( '.sim-submit' ).removeClass( 'sim-tutorial' ); } );
	    $( '#sim-submit' ).click( function() { $( '#sim-submit' ).removeClass( 'sim-tutorial' ); } );
	    $( '#sim-submit-fail' ).click( function() { $( '#sim-submit-fail' ).removeClass( 'sim-tutorial' ); } );
	    simUpdateLLWindow();
	}, 500);

	simUpdateHud();

	simTimerCreate();

	setTimeout( function() {
	    if ( courseStatus.health <= 0 && courseStatus.lives <= 0 || simGraded() ) {
		simSubmitUpdateAnswers();
		simSubmit('done');
	    } else {
		simSubmitClear();
	    }
	}, 500);
}

function simSubmitClear() {
    $( '.sim-answer:not(.sim-answer-correct, .sim-answer-incorrect, .sim-answer-answered)' ).click(
	function(){
	    $( '#sim-submit' ).show();
	    $( '#sim-instruction' ).fadeOut(500);
	}	
    );
    $( '.sim-answer.sim-answer-correct' ).unbind( 'click' );
    $( '.sim-answer.sim-answer-incorrect' ).unbind( 'click' );
    $( '.sim-answer.sim-answer-answered' ).unbind( 'click' );
}

function simGearUpCharacter() {
    $( '#sim-character' ).attr( 'src', 'images/character/happy/happy-' + courseStatus.character + '.png' );
    $( '#sim-gear' ).attr( 'src', currentSimData.character_gear_src);
    $( '.sim-injury-image' ).remove();
    if ( currentSimData.character_geared === false ) {
	playerSFXPlay( 'dress-up' );
    }
    
}


function simSubmitUpdateAnswers() {
    currentSimCorrectAnswers = 0;
    currentSimWrongAnswers = 0;
    currentSimWrongAnswersThatHurt = 0;
    
    window.clearInterval(currentSimTimer);
    
    var answers = currentSimData.answers_src.length;
    
    if ( simGraded() === false ) {
	if ( currentSimTime > 0 && simTimeOut === 'fail' || simTimeOut === 'submit') {
	    for ( i = 0; i < answers; i++ ) {

		zork( 'Checking answer ' + i +'...');

		$( '#sim-answer-' + i ).removeClass( 'sim-selection button-click button-select' );

		if( $( '#sim-answer-' + i ).hasClass( 'selected' ) ){
		    $( '#sim-answer-' + i ).attr('src', currentSimData.selected_src[i] );
		    zork( 'It was selected... And that is...');
		} else if( !$( '#sim-answer-' + i ).hasClass( 'selected' ) ) {
		    $( '#sim-answer-' + i ).attr('src', currentSimData.unselected_src[i] ); 
		    zork( 'It wasn\'t selected... And that is...');
		}

		//var correct = currentSimData.keys.includes(i);
		//var correct = stringIncludes( currentSimData.keys, i );
		var correct = currentSimData.keys.indexOf(i) > -1;

		if ( correct ) {
		    zork( '(it was a requirement)');
		}

		if ( correct === true ) {
		    $( '#sim-answer-' + i ).addClass( 'sim-answer-correct' );
		    if ( $( '#sim-answer-' + i ).hasClass( 'selected' ) ) {
			zork( 'Good!');
			currentSimCorrectAnswers += 1;
			simScore( simPoints, currentSimData.level );
			$( '#slide-'+ courseStatus.position ).append(
			    '<div style="'+ currentSimData.feedback_style[i] + ' " class="sim-feedback-message sim-feedback-super-right">' + currentSimData.selected_message[i] + '</div>'
			    );
		    } else {
			zork( 'Bad!');
			currentSimWrongAnswersThatHurt += 1;
			currentSimWrongAnswers += 1;
			$( '#slide-'+ courseStatus.position ).append(
			    '<div style="'+ currentSimData.feedback_style[i] + ' " class="sim-feedback-message sim-feedback-wrong">' + currentSimData.unselected_message[i] + '</div>'
			    );
		    }
		} else {
		    $( '#sim-answer-' + i ).addClass( 'sim-answer-incorrect' );
		    if ( $( '#sim-answer-' + i ).hasClass( 'selected' ) ) {
			zork( 'Bad!');
			if ( simNotRequiredButSelectedDamage === true ) {
			    currentSimWrongAnswersThatHurt += 1;
			}
			currentSimWrongAnswers += 1;
			$( '#slide-'+ courseStatus.position ).append(
			    '<div style="'+ currentSimData.feedback_style[i] + ' " class="sim-feedback-message sim-feedback-wrong sim-feedback-not-needed">' + currentSimData.selected_message[i] + '</div>'
			    );
		    } else {
			zork( 'Good!');
			currentSimCorrectAnswers += 1;
			simScore( simPoints, currentSimData.level );
			$( '#slide-'+ courseStatus.position ).append(
			    '<div style="'+ currentSimData.feedback_style[i] + ' " class="sim-feedback-message sim-feedback-right">' + currentSimData.unselected_message[i] + '</div>'
			    );
		    }
		}
		zork( currentSimCorrectAnswers + ' right answers...');
		zork( currentSimWrongAnswers + ' wrong answers...');
		zork( currentSimWrongAnswersThatHurt + ' of which HURT!');
	    }
	} else if ( currentSimTime <= 0 && simTimeOut === 'fail' ) {
	    for ( i = 0; i < answers; i++ ) {

		zork( 'Clearing answer ' + i +'...');

		$( '#sim-answer-' + i ).removeClass( 'sim-selection button-click button-select selected' );

		currentSimWrongAnswers += 1;
		
		//var correct = currentSimData.keys.includes(i);
		//var correct = stringIncludes( keys, i );
		var correct = currentSimData.keys.indexOf(i) > -1;
		
		$( '#sim-answer-' + i ).addClass( 'sim-answer-incorrect' );
		
		if( correct ) {
		    $( '#sim-answer-' + i ).attr('src', currentSimData.unselected_src[i] );
		} else {
		    $( '#sim-answer-' + i ).attr('src', currentSimData.selected_src[i] ); 
		}
	
	    }
	}
	simGrade();
	simSubmitClear();
    } else {
	zork( 'You\'ve done this already! And you were ' + courseStatus.sim_points[currentSim] + '% correct!' );
	for ( i = 0; i < answers; i++ ) {
	    $( '#sim-answer-' + i ).removeClass('sim-selection button-click button-select selected');
	    $( '#sim-answer-' + i ).addClass( 'sim-answer-answered' );
	    simGearUpCharacter();
	}
	$('#sim-submit').hide(500);
	$('#sim-instruction').hide(500);
    }
}

function simScore( score, level ) {
    
    if ( score === undefined ) score = simPoints;
    if ( level === undefined ) level = currentSimData.level;

    parseIfInteger(score);
    zork(parseIfInteger(score));
    if ( level === 1 ) {
	courseStatus.score_1 += score;
    } else if ( level === 2 ) {
	courseStatus.score_2 += score;
    } else if ( level === 3 ) {
	courseStatus.score_3 += score;
    }
    courseStatus.score = courseStatus.score_1 + courseStatus.score_2 + courseStatus.score_3;
    var addedScore = courseStatus.score_1 + courseStatus.score_2 + courseStatus.score_3;
    zork( 'Your score is ' + addedScore + '!');
}

function simGameOver() {
    zork( 'You LOST! It\'s GAME OVER!' );
    if ( simGameOverWindow === 'window' ) {
	game_over = 1;
	playerMusicStop( slideTrack );
	playerSFXPlay( 'game-over' );
	playerSFXPlay( 'sad' );
	layer( 'game-over' );
	if ( simGameOverAction === 'grade' ) {
	    courseGrade();
	}
    } else if ( typeof simGameOverWindow === 'number' ) {
	slideGoTo( simGameOverWindow, true);
    }
}

function simSubmitFail() {
    $( '.sim-answer-incorrect' ).fadeOut(500);
    $( '.sim-feedback-message' ).fadeOut(500);
    
    $( '.sim-answer-correct' ).addClass( 'sim-make-green' );
    $( '.selected' ).removeClass( 'selected' );
    
    setTimeout( function() {
	$( '.sim-answer-incorrect' ).remove();
	$( '.sim-feedback-message' ).remove();
    }, 1000);
    simSubmit( 'done' );
    simGearUpCharacter();
}

function simSubmit( condition ) {

    $('#sim-submit').fadeOut(500);
    $( '#sim-timer-bar' ).removeClass( 'really-panic' );
    window.clearInterval(currentSimTimer);
    playerSFXStop( 'panic' );
    playerMusicSpeed( 1 );
    if ( condition === 'submit' ) {
	simFeedback('score');
    } else {
	simFeedback( condition );
    }
}

function simGraded() {
    if ( courseStatus.sim_points[currentSim] === undefined || courseStatus.sim_points[currentSim] === 'undefined' ) {
	return false;
	zork('This simulation wasn\'t graded...');
    } else {
	return true;
	zork('This simulation was already graded...');
    }
}

function simGrade() {
    var totalAnswers = currentSimData.answers_src.length;
    var correctAnswers = currentSimCorrectAnswers;
    var percentageCorrect = Math.round( correctAnswers * 100 / totalAnswers );
    var timeLeft = currentSimTime / 1000;
    var timeTaken = 0;
	    
    if ( typeof currentSimData.time === 'number') {
	timeTaken = currentSimData.time / 1000 - timeLeft;
    } else {
	timeTaken = simTimeLimit / 1000 - timeLeft;
    }
    
    if ( simGraded() === false ) {
	courseStatus.sim_points[currentSim] = 0 + correctAnswers * simPoints;
	courseStatus.sim_percentage[currentSim] = percentageCorrect;
	courseStatus.sim_time_taken[currentSim] = timeTaken;
	courseStatus.sim_time_left[currentSim] = timeLeft;
	zork('This simulation was graded ' + percentageCorrect + '%');
	simUpdateLLWindow();
    }
    simScore( false, false );
}

function simFeedback( condition ) {
    zork( 'Running feedback!' );
    $( '.sim-answer' ).removeClass( 'sim-tutorial' );
    $( '#sim-instruction' ).fadeOut(500);
    if ( condition === 'time-out' ) {
	zork( 'Time-out feedback!' );
	zork( 'You timed-out!' );
	playerSFXPlay( 'time-out' );
	setTimeout( function(){
	    simFeedback( 'score' );
	}, 2000);
    } else if ( condition === 'score' ) {
	zork( 'Scoring feedback!' );
	simSubmitUpdateAnswers();
	simGlobalFeedback();
	zork( 'Showing score and...' );
	if ( currentSimCorrectAnswers > 0 && currentSimWrongAnswers <= 0 ) {
	    zork( '... you got everything right!' );
	    simGearUpCharacter();
	    playerSFXPlay( 'win' );
	    setTimeout( function(){
		simFeedback( 'done' );
	    }, 4000);
	    simAddPoints();
	} else if ( currentSimCorrectAnswers > 0 && currentSimWrongAnswers > 0 ) {
	    zork( '... you missed some things...' );
	    playerSFXPlay( 'win-lose' );
	    setTimeout( function(){
		simFeedback( 'health' );
	    }, 4000);
	    simAddPoints();
	} else if ( currentSimCorrectAnswers <= 0 && currentSimWrongAnswers > 0 ) {
	    zork( '... YOU FAILED!!!' );
	    playerSFXPlay( 'lose' );
	    simFeedback( 'health' );
	} else {
	    zork( '... and no nothing!' );
	}
    } else if ( condition === 'health' ) {
	zork( 'Damage feedback!' );
	if ( currentSimWrongAnswers > 0 ) {
	    zork( 'Showing injuries and accounting damage...' );
	    simMakeCharacterCry();
	    setTimeout( function() {
		simAddDamage();
	    }, 1000);
	}
	var delay = currentSimWrongAnswers * 1000 + 4000;
	setTimeout( function(){
	    if ( currentSimData.submit_fail !== false ) {
		$( '#sim-submit-fail').show();
		courseSave();
	    } else {
		simFeedback('done');
	    }
	}, delay);
    } else if ( condition === 'done' ) {
	zork( 'You are done feedback!' );
	$( '#sim-submit-fail').fadeOut(500);
	if ( courseStatus.lives > 0 ) {
	    zork( 'You passed!' );
	    finish();
	} else if ( courseStatus.health <= 0 && courseStatus.lives <= 0 ) {
	    courseSave();
	    simGameOver();
	}
    }
}

function simOverworldUpdateCharacter( type ) {
    
    if ( type === undefined ) type = 'normal';
    
    if ( type === 'normal' ) {
	$( '#sim-overworld-body' ).attr( 'src', 'images/character/naked/character-' + courseStatus.character + '.png' );
	$( '#sim-overworld-clothes' ).attr( 'src', 'images/character/clothes/clothes-' + courseStatus.character + '.png' );
	$( '#sim-overworld-nickname' ).html( courseStatus.nickname );
    } else if ( type === 'hurt' ) {
	$( '#sim-overworld-body' ).attr( 'src', 'images/character/crying/crying-' + courseStatus.character + '.png' );
	$( '#sim-overworld-clothes' ).attr( 'src', 'images/character/clothes/clothes-' + courseStatus.character + '.png' );
	$( '#sim-overworld-nickname' ).html( courseStatus.nickname );
    } else if ( type === 'happy' ) {
	$( '#sim-overworld-body' ).attr( 'src', 'images/character/happy/happy-' + courseStatus.character + '.png' );
	$( '#sim-overworld-clothes' ).attr( 'src', 'images/character/clothes/clothes-' + courseStatus.character + '.png' );
	$( '#sim-overworld-nickname' ).html( courseStatus.nickname );
    }
}

function simUpdateLLWindow() {
    $( '.llwindow-sim' ).show();
    $( '#llwindow-data-sim-name' ).text( currentSimData.name );
    $( '#llwindow-data-sim' ).text( currentSim );
    $( '#llwindow-data-sim-score' ).text( courseStatus.sim_points[currentSim] );
    $( '#llwindow-data-sim-key' ).text( currentSimData.keys );
    $( '#llwindow-zork' ).text( '' );
}