/*
 *	List of Functions:
 *              playerLoad()                    Hides loader and loads player
 *		playerConfig()			Sets initial width of the player
 *		playerFit( ratioX, ratioY )	Scales and aligns the player
 *		playerResize()			Determines what ratio to use
 *
 *		playerMediaUpdateVolume()	Plays/stops audio and video
 *		playerControlsToggleMenu()	Shows/hides menu
 *		playerControlsToggleAudio()	Toggles audio on/off
 *		playerControlsExit()		Exits window
 *		playerControlHome()             User goes home
 *              
 *              slideUnload
 *              slideLoad( target )
 *              slideGoTo( target )             Goes to slide Number
 *              slideNext()                     Goes to next slide
 *              slidePrev()                     Goes to Neverland!
 *              slidePreload()                  Preloads a slide
 *              slideAutoPreload()              Preloads next and previous slides
 *              
 *              playerUpdateNavigation()       Updates next and previous buttons
 *              playerHideNavigation()
 *              playerUpdateControls()
 *              playerHideControls()
 *              playerUpdateMenu()
 *              
 *              slideChecker()                  Check if slide is complete
 *              slideComplete()                 Completes current slide
 *              slideCompleteUpTo( target )     Completes all slides up to...
 *              
 *              courseReset()                   Resets current course
 *              courseSave()                    Saves current course status
 *              courseLoad()                    Loads current course status
 *
 */


/*Common variables for the player*/
/* global courseIndex, courseStatus, localCourse, Storage, playerPreload, godMode, amnesiaMode */
var slidePrevious;
var slideNavigation = true;
var slideActive;
var slideTimedAdvance;
var slideTrack = 0;
var autoplay = false;
var useriOS = false;
var userMobile = false;
var userAndroid = false;
var userIE = false;
var interactionDelay = 2;
var useriOSTouch = false;
var vpFirstTimeIsPlayed=true;
var previousNextFree = true;
var ratio = 1;

/*Admin Control*/
function zork( string ) {
    if ( zorkMode === true ) {
        console.log( 'Zork says: ' + string );
	
	if ( adminMode === true ) {
	    $( '#llwindow-zork').append( 'Zork says: ' + string + '\r\n');
	    
	    var textarea = document.getElementById('llwindow-zork');
	    textarea.scrollTop = textarea.scrollHeight;
	}
    }
}
		
/*Check if iOS*/
function checkiOS() {
    if ( navigator.userAgent.match(/(iPod|iPhone|iPad)/) ) {
	useriOS = true;
	$( 'body' ).addClass( 'iphone' );
	playerResize();
	interactionDelay = 4;
	zork('You are on an I Phone!');
    } else {
	useriOS = false;
	zork('You are NOT on an I Phone!');
    }
}
/*Check if Android*/
function checkAndroid() {
    if( navigator.userAgent.match(/Android/i) ) {
	userAndroid = true;
    }
}
/*Check if Mobile*/
function checkMobile() {
    if( navigator.userAgent.match(/Android/i)
    || navigator.userAgent.match(/webOS/i)
    || navigator.userAgent.match(/iPhone/i)
    || navigator.userAgent.match(/iPad/i)
    || navigator.userAgent.match(/iPod/i)
    || navigator.userAgent.match(/BlackBerry/i)
    || navigator.userAgent.match(/Windows Phone/i)
    ){
	userMobile = true;
	interactionDelay = 3;
	zork('You are on a phone!');
	$('body').addClass('mobile');
	$('header h2').addClass('mobile');
	$('header h3').addClass('mobile');

//        alert('YOU ARE ON A PHONE!');
    } else {
	userMobile = false;
	
	zork('You are NOT on a phone!');
    }
}

function checkIE() {
    if((navigator.userAgent.indexOf("MSIE") != -1 ) || (!!document.documentMode == true )) { //IF IE > 10 
	userIE = true;
        $('body').addClass('internet-explorer');
    }  
}


/*Load Player*/
function playerLoad() {
    loaderHide();
    courseLoad();
    playerMediaCheckPermission();
    checkiOS();
    checkMobile();
    checkAndroid();
    checkIE();
    playerGoFullscreenAndroidWarning();
    if ( adminMode === true || autoLLWindow === true ) {
	    llwindowOpen();
    }
}


/*Player Ratio and Fit*/
//Sets initial width of the slide, header and footer controls

function playerConfig() {	
    $( '#slide' ).css( 'width', playerWidth + 'px' );
    $( '#slide' ).css( 'height', playerHeight + 'px' );
    $( '#slide' ).css( 'min-width', playerWidth + 'px' );
    $( '#slide' ).css( 'min-height', playerHeight + 'px' );
    $( '#slide' ).css( 'max-width', playerWidth + 'px' );
    $( '#slide' ).css( 'max-height', playerHeight + 'px' );

    playerSlideWidth( playerWidth );
}

function playerSlideWidth( value ) {
    if ( playerControls === 'width' ) {
	$( '.slide-width' ).css( 'width', value + 'px' );
	$( '.slide-width' ).css( 'min-width', value + 'px' );
	$( '.slide-width' ).css( 'max-width', value + 'px' );
    } else {
	$( '.slide-width' ).css( 'width', '100%' );
	$( '.slide-width' ).css( 'min-width', '100%' );
	$( '.slide-width' ).css( 'max-width', 'auto' );
    }
}


//Scales the player, header and footer to the most effective ratio, also, raises ou drops the header and footer

function playerFit( ratioX, ratioY ) {
    var ratioSelected;
    if ( ratioX > ratioY ) {
	$( '#slide' ).css( 'transform', 'scale(' + ratioY + ')' );
        ratioSelected = ratioY;
        ratio = ratioY;
	playerSlideWidth( playerWidth * ratioY );
    } else {
	$( '#slide' ).css( 'transform', 'scale(' + ratioX + ')' );
	ratioSelected = ratioX;
        ratio = ratioX;
	playerSlideWidth( playerWidth * ratioX );
    }
    if ( userIE ) {
        if (    playerWidth > window.innerWidth || 
                playerHeight > window.innerHeight ) {

            idealMargin = window.innerWidth - $('#slide').outerWidth() * ratioSelected;

            youNeedToMove = $('#slide').position().left - idealMargin / 2;
            zork(youNeedToMove);
            $('#slide').css( 'margin-left', '-' + youNeedToMove  + 'px');
        }
    }

    //Clear previous resize
    $( '#slide-header' ).removeAttr( 'style' );
    $( '#slide-container' ).removeAttr( 'style' );
    $( '#slide-footer' ).removeAttr( 'style' );
    var contentHeight = $( '#slide-header' ).height() + $( '#slide' ).height() + $( '#slide-footer' ).height();

    if ( playerSize === 'optimal' && $( window ).height() > contentHeight ) {

	if ( playerPosition === 'fit' ) {
	    $( '#slide-header' ).css( 'height', ( $( window ).height() - playerHeight ) / 2 + 'px' );
	    $( '#slide-container' ).css( 'top', ( $( window ).height() - playerHeight ) / 2 + 'px' );
	    $( '#slide-container' ).css( 'height', playerHeight + 'px' );
	    $( '#slide-footer' ).css( 'height', ( $( window ).height() - playerHeight ) / 2 + 'px' );
	} else if ( playerPosition === 'top' ) {
	    $( '#slide-container' ).css( 'height', playerHeight + 'px' );
	    $( '#slide-footer' ).css( 'height', $( window ).height() - playerHeight - $( '#slide-header' ).height() + 'px' );
	} else if ( playerPosition === 'bottom' ) {
	    $( '#slide-container' ).css( 'height', playerHeight + 'px' );
	    $( '#slide-container' ).css( 'top', $( window ).height() - playerHeight - $( '#slide-footer' ).height() + 'px' );
	    $( '#slide-header' ).css( 'height', $( window ).height() - playerHeight - $( '#slide-footer' ).height() + 'px' );
	}
    }
}

function playerGoFullscreen() {
    zork('Can I go fullscreen?');
    var elem = document.documentElement;
    if (elem.requestFullscreen) {
	elem.requestFullscreen();
    } else if (elem.mozRequestFullScreen) { /* Firefox */
	elem.mozRequestFullScreen();
    } else if (elem.webkitRequestFullscreen) { /* Chrome, Safari and Opera */
	elem.webkitRequestFullscreen();
    } else if (elem.msRequestFullscreen) { /* IE/Edge */
	elem.msRequestFullscreen();
    }
}
function playerGoFullscreenAndroidWarning() {
    if ( userAndroid === true && playerFullscreenMobile === true ) {
	zork( 'You are on Android, and you will go fullscreen!' );
	$( '#screen-fullscreen' ).css( 'opacity', 1 );
	$( '#screen-fullscreen' ).css( 'display', 'flex' );
	$( '#screen-fullscreen' ).click( function() {
	    $( '#screen-fullscreen' ).remove();
	});
    }
}

function playerResize() {
	//Determines what ratio to use
	var ratioX = $( '#slide-container' ).width() / $( '#slide' ).width();
	var ratioY = $( '#slide-container' ).height() / $( '#slide' ).height();
	
	if ( playerSize === 'optimal' && ratioX > 1 && ratioY > 1 ) {
		playerFit( 1, 1 );
	} else {
		playerFit( ratioX, ratioY );
	}
	playerBackgroundResize();
}

function playerDirection() {
    if ( playerHorizontal === false ) {
	$( '#screen-rotation' ).remove();
    }
}

function loaderHide(){
    setTimeout( function(){
        $( '#loader' ).fadeOut(1000, function() {
//            $( '#loader' ).remove();
        });
    }, 3000);
}

function playerBackgroundResize( target ) {
    
    if ( target === undefined ) target = courseStatus.position;
    
    zork( 'Updating BG!' );
    var bg = courseIndex[ target ].background;
  
    var containerHeight = $('#slide')[0].getBoundingClientRect().height;
    var containerWidth = $('#slide')[0].getBoundingClientRect().width;    

    $('#slide-container').css( 'background-size', containerWidth + 'px ' + containerHeight + 'px, auto ' + containerHeight + 'px, '+ containerWidth + 'px auto');
    
    if ( bg !== false ) {
	$( '#slide-container' ).css( 'background-image', 'url(images/background/' + bg + '), url(images/background/horizontal/' + bg + '), url(images/background/vertical/' + bg + ')');   
    }
}


/*Media management*/

function playerMediaUpdateVolume() {
    if ( courseStatus.audio === 0 ) {
        $('audio').prop( 'volume', 0);
        $('video').prop( 'volume', 0);
	$('iframe').contents().find('audio').prop( 'volume', 0);
	$('iframe').contents().find('video').prop( 'volume', 0);
        $( '.audio-off').show();
        $( '.audio-on').hide();
	    $( '.music-on').show();
        $( '.music-off').hide();
	    playerMusicOff();
    } else {
        $('audio').prop( 'volume', 1);
        $('video').prop( 'volume', 1);
	    $('iframe').contents().find('audio').prop( 'volume', 1);
	    $('iframe').contents().find('video').prop( 'volume', 1);
        $( '.audio-on').show();
        $( '.audio-off').hide();
	if ( courseStatus.music === 0 ) {
	    playerMusicOff();
	    $('.music-player').prop( 'volume', 0);
	    $( '.music-on').show();
	    $( '.music-off').hide();
	} else {
	    playerMusicOn();
	    $('.music-player').prop( 'volume', 1);
	    $( '.music-on').hide();
	    $( '.music-off').show();
	}
	if ( courseStatus.sfx === 0 ) {
	    $('.sfx-player').prop( 'volume', 0);
	} else {
	    $('.sfx-player').prop( 'volume', 1);
	}
    }
}

function playerMediaCheckPermission() {
    // Audio file data URIs from comments in
    // [this gist](https://gist.github.com/westonruter/253174)
    // via [mudcube](https://github.com/mudcube)
    var mp3 = 'data:audio/mpeg;base64,/+MYxAAAAANIAUAAAASEEB/jwOFM/0MM/90b/+RhST//w4NFwOjf///PZu////9lns5GFDv//l9GlUIEEIAAAgIg8Ir/JGq3/+MYxDsLIj5QMYcoAP0dv9HIjUcH//yYSg+CIbkGP//8w0bLVjUP///3Z0x5QCAv/yLjwtGKTEFNRTMuOTeqqqqqqqqqqqqq/+MYxEkNmdJkUYc4AKqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq';

    var ogg = 'data:audio/ogg;base64,T2dnUwACAAAAAAAAAADqnjMlAAAAAOyyzPIBHgF2b3JiaXMAAAAAAUAfAABAHwAAQB8AAEAfAACZAU9nZ1MAAAAAAAAAAAAA6p4zJQEAAAANJGeqCj3//////////5ADdm9yYmlzLQAAAFhpcGguT3JnIGxpYlZvcmJpcyBJIDIwMTAxMTAxIChTY2hhdWZlbnVnZ2V0KQAAAAABBXZvcmJpcw9CQ1YBAAABAAxSFCElGVNKYwiVUlIpBR1jUFtHHWPUOUYhZBBTiEkZpXtPKpVYSsgRUlgpRR1TTFNJlVKWKUUdYxRTSCFT1jFloXMUS4ZJCSVsTa50FkvomWOWMUYdY85aSp1j1jFFHWNSUkmhcxg6ZiVkFDpGxehifDA6laJCKL7H3lLpLYWKW4q91xpT6y2EGEtpwQhhc+211dxKasUYY4wxxsXiUyiC0JBVAAABAABABAFCQ1YBAAoAAMJQDEVRgNCQVQBABgCAABRFcRTHcRxHkiTLAkJDVgEAQAAAAgAAKI7hKJIjSZJkWZZlWZameZaouaov+64u667t6roOhIasBACAAAAYRqF1TCqDEEPKQ4QUY9AzoxBDDEzGHGNONKQMMogzxZAyiFssLqgQBKEhKwKAKAAAwBjEGGIMOeekZFIi55iUTkoDnaPUUcoolRRLjBmlEluJMYLOUeooZZRCjKXFjFKJscRUAABAgAMAQICFUGjIigAgCgCAMAYphZRCjCnmFHOIMeUcgwwxxiBkzinoGJNOSuWck85JiRhjzjEHlXNOSuekctBJyaQTAAAQ4AAAEGAhFBqyIgCIEwAwSJKmWZomipamiaJniqrqiaKqWp5nmp5pqqpnmqpqqqrrmqrqypbnmaZnmqrqmaaqiqbquqaquq6nqrZsuqoum65q267s+rZru77uqapsm6or66bqyrrqyrbuurbtS56nqqKquq5nqq6ruq5uq65r25pqyq6purJtuq4tu7Js664s67pmqq5suqotm64s667s2rYqy7ovuq5uq7Ks+6os+75s67ru2rrwi65r66os674qy74x27bwy7ouHJMnqqqnqq7rmarrqq5r26rr2rqmmq5suq4tm6or26os67Yry7aumaosm64r26bryrIqy77vyrJui67r66Ys67oqy8Lu6roxzLat+6Lr6roqy7qvyrKuu7ru+7JuC7umqrpuyrKvm7Ks+7auC8us27oxuq7vq7It/KosC7+u+8Iy6z5jdF1fV21ZGFbZ9n3d95Vj1nVhWW1b+V1bZ7y+bgy7bvzKrQvLstq2scy6rSyvrxvDLux8W/iVmqratum6um7Ksq/Lui60dd1XRtf1fdW2fV+VZd+3hV9pG8OwjK6r+6os68Jry8ov67qw7MIvLKttK7+r68ow27qw3L6wLL/uC8uq277v6rrStXVluX2fsSu38QsAABhwAAAIMKEMFBqyIgCIEwBAEHIOKQahYgpCCKGkEEIqFWNSMuakZM5JKaWUFEpJrWJMSuaclMwxKaGUlkopqYRSWiqlxBRKaS2l1mJKqcVQSmulpNZKSa2llGJMrcUYMSYlc05K5pyUklJrJZXWMucoZQ5K6iCklEoqraTUYuacpA46Kx2E1EoqMZWUYgupxFZKaq2kFGMrMdXUWo4hpRhLSrGVlFptMdXWWqs1YkxK5pyUzDkqJaXWSiqtZc5J6iC01DkoqaTUYiopxco5SR2ElDLIqJSUWiupxBJSia20FGMpqcXUYq4pxRZDSS2WlFosqcTWYoy1tVRTJ6XFklKMJZUYW6y5ttZqDKXEVkqLsaSUW2sx1xZjjqGkFksrsZWUWmy15dhayzW1VGNKrdYWY40x5ZRrrT2n1mJNMdXaWqy51ZZbzLXnTkprpZQWS0oxttZijTHmHEppraQUWykpxtZara3FXEMpsZXSWiypxNhirLXFVmNqrcYWW62ltVprrb3GVlsurdXcYqw9tZRrrLXmWFNtBQAADDgAAASYUAYKDVkJAEQBAADGMMYYhEYpx5yT0ijlnHNSKucghJBS5hyEEFLKnINQSkuZcxBKSSmUklJqrYVSUmqttQIAAAocAAACbNCUWByg0JCVAEAqAIDBcTRNFFXVdX1fsSxRVFXXlW3jVyxNFFVVdm1b+DVRVFXXtW3bFn5NFFVVdmXZtoWiqrqybduybgvDqKqua9uybeuorqvbuq3bui9UXVmWbVu3dR3XtnXd9nVd+Bmzbeu2buu+8CMMR9/4IeTj+3RCCAAAT3AAACqwYXWEk6KxwEJDVgIAGQAAgDFKGYUYM0gxphhjTDHGmAAAgAEHAIAAE8pAoSErAoAoAADAOeecc84555xzzjnnnHPOOeecc44xxhhjjDHGGGOMMcYYY4wxxhhjjDHGGGOMMcYYY0wAwE6EA8BOhIVQaMhKACAcAABACCEpKaWUUkoRU85BSSmllFKqFIOMSkoppZRSpBR1lFJKKaWUIqWgpJJSSimllElJKaWUUkoppYw6SimllFJKKaWUUkoppZRSSimllFJKKaWUUkoppZRSSimllFJKKaWUUkoppZRSSimllFJKKaWUUkoppZRSSimllFJKKaVUSimllFJKKaWUUkoppRQAYPLgAACVYOMMK0lnhaPBhYasBAByAwAAhRiDEEJpraRUUkolVc5BKCWUlEpKKZWUUqqYgxBKKqmlklJKKbXSQSihlFBKKSWUUkooJYQQSgmhlFRCK6mEUkoHoYQSQimhhFRKKSWUzkEoIYUOQkmllNRCSB10VFIpIZVSSiklpZQ6CKGUklJLLZVSWkqpdBJSKamV1FJqqbWSUgmhpFZKSSWl0lpJJbUSSkklpZRSSymFVFJJJYSSUioltZZaSqm11lJIqZWUUkqppdRSSiWlkEpKqZSSUmollZRSaiGVlEpJKaTUSimlpFRCSamlUlpKLbWUSkmptFRSSaWUlEpJKaVSSksppRJKSqmllFpJKYWSUkoplZJSSyW1VEoKJaWUUkmptJRSSymVklIBAEAHDgAAAUZUWoidZlx5BI4oZJiAAgAAQABAgAkgMEBQMApBgDACAQAAAADAAAAfAABHARAR0ZzBAUKCwgJDg8MDAAAAAAAAAAAAAACAT2dnUwAEAAAAAAAAAADqnjMlAgAAADzQPmcBAQA=';

    try {
        var audio = new Audio();
        var src = audio.canPlayType('audio/ogg') ? ogg : mp3;
        audio.autoplay = true;
        audio.volume = 0;

        // this will only be triggered if autoplay works
        $(audio).on('play', function() {
            autoplay = true;
	    zork( 'Audio is allowed!' );
//	    customAudioPreLoad();
	    setTimeout( function() {
		playerMusicUpdateBG();
	    }, 1000);
        });

        audio.src = src;
	
    } catch(e) {
        zork( 'No audio allowed...' );
    }
}


/*Player Controls*/

function playerControlsToggleMenu() {	//Shows/hides menu
    if ( $( '#slide-menu' ).hasClass( 'active' ) ) {
        $( '#slide-menu' ).removeClass( 'active' );
    } else {
        $( '#slide-menu' ).addClass( 'active' );
    }
}

function playerControlsHideMenu() {	//Shows/hides menu
    if ( $( '#slide-menu' ).hasClass( 'active' ) ) {
        $( '#slide-menu' ).removeClass( 'active' );
    }
}

function playerControlsToggleAudio() {	//Toggles audio on/off
    
    if ( courseStatus.audio === 0 ) {
	zork('Audio On');
        courseStatus.audio = 1;
    } else {
	zork('Audio Off');
        courseStatus.audio = 0;
    }
    playerMediaUpdateVolume();
}

function playerControlsToggleMusic() {	//Toggles audio on/off
    if ( courseStatus.music === 0 ) {
	zork('Music On');
        courseStatus.music = 1;
    } else {
	zork('Music Off');
        courseStatus.music = 0;
    }
    playerMediaUpdateVolume();
}

function playerControlsToggleSFX() {	//Toggles audio on/off
    if ( courseStatus.sfx === 0 ) {
	zork('SFX On');
        courseStatus.sfx = 1;
    } else {
	zork('SFX Off');
        courseStatus.sfx = 0;
    }
    playerMediaUpdateVolume();
}

function playerControlsExitWindow() {
    playerSFXPlay('robotBtnSimpleClick');
    if( $( '#closing-window' ).css('display') === 'none') {
	$( '#closing-window' ).fadeIn( 500 );
    } else {
	$( '#closing-window' ).fadeOut( 500 );
    }
    $('#closing-window #statsBadge').attr('src', 'images/badges/' + courseStatus.playerBadge + '.png')
    $('#closing-window #badgeType').text(courseStatus.playerBadgeTitle)
    $("#closing-window #statsPoints").text(courseStatus.playerPoints + '  pts')
}

function playerControlsExit() {		//So you're a quitter hun?
    courseSave();
    window.parent.close();
}

function playerControlsHome() {         //E.T. phone home!
    slideGoTo( playerHome );
}

/*Slide controls*/

function slideLoad( target, hidden ) {          //Load the target slide
    
    if ( hidden === undefined ) {
	hidden = false;
    }
    
    zork( 'Loading slide ' + target + '.' );
    
    var background;
    
    
    if ( hidden === false ) {
	if ( $( '#slide-' + target ).length <= 0 ){

	    $( '#slide' ).append( '<section id="slide-' + target + '" data-current-slide="' + target + '" class="slide slide-current" style="display:none;"></section>');

	    $( '#slide-' + target ).load( 'slides/' + courseIndex[ target ].reference, function() {
		$( '#slide-' + target ).hide().fadeIn(500);
		zork('Slide ' + target + ' loaded!');
	    });

	    playerBackgroundResize( target );
	} else if ( $( '#slide-' + target ).length >= 1 ) {
	    $( '#slide-' + target ).addClass( 'slide-current' );
	    $( '#slide-' + target ).fadeIn( 500 );
	}
    } else {
	
	$( '#slide' ).append( '<section id="slide-' + target + '" data-current-slide="' + target + '" class="slide" style="display:none;"></section>');

	$( '#slide-' + target ).load( 'slides/' + courseIndex[ target ].reference, function() {
	    zork('Slide ' + target + ' pre-loaded!');
	});
	
    }
    
    		
    
}

function slideUnLoad( target ) {        //Removes previous slide
    if ( target === undefined ){
	$('.slide-current').first().fadeOut(500, function(){
	    var name = $('.slide-current').first().data('current-slide');
	    $('.slide-current').first().remove();
	    zork('Slide ' + name + ' removed!');
	});
//        setTimeout( function(){
//	    var name = $('.slide-current').first().data('current-slide');
//            $('.slide-current').first().remove();
//	    zork('Slide ' + name + ' removed!');
//        }, 500);
    } else if ( target === 'all' ) {
	$( '.slide' ).fadeOut(500, function(){
	    $( '.slide' ).remove();
	    zork('Removing all slides!');
	});
//        setTimeout( function(){
//	    $( '.slide' ).remove();
//	    zork('Removing all slides!');
//        }, 500);
    } else {
	$('#slide-' + target ).first().fadeOut(500, function(){
	    var name = $('#slide-' + target ).data('current-slide');
	    $('#slide-' + target ).remove();
	    zork('Slide ' + name + ' removed!');
	});
//        setTimeout( function(){
//	    var name = $('#slide-' + target).data('current-slide');
//            $('#slide-' + target).remove();
//	    zork('Slide ' + name + ' removed!');
//        }, 500);
    }
}

function slideClear( safeHaven ) {
    if ( safeHaven === undefined ) {
	safeHaven = courseStatus.position;
    }
    
    var extraDigit = 0;
    
    if ( playerPreload === true ) {
	extraDigit = 1;
    }
    if ( safeHaven === 'all' ) {
	zork('Clearing all slides!');
	slideUnLoad( 'all' );
    } else {
	$( '.slide' ).each(function (index, value) { 
	    var slideID = parseInt($(this).attr('data-current-slide'));
	    zork('This slide is ' + slideID + '!');
	    if ( slideID !== safeHaven && slideID !== safeHaven + extraDigit ) {
		zork('We just want to see slide ' + courseStatus.position + '...');
		slideUnLoad( slideID );
	    }
	});
    }
//    $( '.slide-current' ).each(function (index, value) { 
//	var slideID = parseInt($(this).attr('data-current-slide'));
//	zork('This slide is ' + slideID + '!');
//	if ( slideID !== courseStatus.position ) {
//	    zork('We just want to see slide ' + courseStatus.position + '...');
//	    slideUnLoad( slideID );
//	}
//    });
    
}

function slideGoTo( target, forced ) {              //Goes to target slide if possible
    
    if ( forced === undefined ) forced = false;
    
    clearTimeout( slideTimedAdvance );
    
    playerControlsHideMenu();
    
    target = parseIfInteger(target);

    var isCompleted = slideCheckCompletion( target );
    
    
    if ( isCompleted || godMode === true || forced === true ) {
        if ( slideNavigation === true && courseIndex[ target ] !== undefined && target !== slideActive ) {
            
            if ( courseIndex[ courseStatus.position ].completion === 'video' && $('#slide-' + courseStatus.position + ' video') > 0 ) {
                $('#slide-' + courseStatus.position + ' video').get(0).pause();
                
                $('#slide-' + courseStatus.position + ' video').get(0).remove();
            }
            
            slideNavigation = false;
            slideCompleteUpTo( courseStatus.position - 1 );
//            playerHideControls();
            playerHideNavigation();
	    if ( courseStatus.position > target ) {
		courseStatus.position = target;
		slideClear( 'all' );
	    } else {
		courseStatus.position = target;
		slideClear();
	    }
            playerBackgroundResize( target );
	    setTimeout( function() {
		slideLoad( target );
		if ( playerPreload === true && courseIndex[ target + 1 ]  !== undefined ) {
		    slideLoad( target + 1, true );
		}
            }, 500);

            setTimeout( function() {
		slideNavigation = true;
                slidePrevious = courseStatus.position;
		slideActive = courseStatus.position;
		slideChecker();
		playerMediaUpdateVolume();
		playerUpdateMenu();
		playerUpdateNavigation();
		playerUpdateControls();
		playerUpdateProgressBar();
		playerBackgroundResize();
                playerSFXStop( 'all' );
		// customFunctions();
		//simUpdateHud();
		$( '#forward-instruction' ).fadeOut(500);
		courseSave();
		llwindowEmpty();
		llwindowUpdate();
		if ( $( '.slide-current > video' ).length > 0 ) {
//                    $('#slide-' + courseStatus.position + ' video')[0].play();
//		    $( '.slide-current > video' )[0].play();
		}
            }, 500);
	    
	    setTimeout( function() {
		//contentHover();
		contentSelect();
            }, 500 * interactionDelay );
	    
            setTimeout( function() {
		if ( $('#slide-' + slideActive ).length === 0 ) {
                    zork('NO SLIDE FOUND!!!');
                    slideLoad( target );
                }
            }, 1000);
            
	    if ( useriOS === true ) {
		useriOSTouch = false;
	    }
            
            playerMediaUpdateVolume();
	    
	    
        } else if( slideNavigation === false ) {
	    zork('Not so fast!');
	} else if( courseIndex[ target ] === undefined ) {
	    zork('That slide ('+target+') doesn\'t exist!');
	} else if( target === slideActive ) {
	    zork('You are already there!');
	}
    } else if( isCompleted === false ) {
        zork('You can\'t go to slide ' + target + ' yet!');
    }
}

function slideNext() {              //Goes to next slide
    if( previousNextFree ) {
        var target = courseIndex[ courseStatus.position ].next;

        if ( target === true ) {
            slideGoTo( 1 + courseStatus.position );
        } else if ( typeof target === 'number' ) {
            slideGoTo( target );
        }
        previousNextFree = false;
        setTimeout( function() {
            previousNextFree = true;
        }, 1500 );
    } else {
        zork('Wait a minute mr postman!');
    }
}

function slidePrev() {                  //Goes to previous slide
    if( previousNextFree ) {
        var target = courseIndex[ courseStatus.position ].previous;

        if ( target === true ) {
            slideGoTo( courseStatus.position - 1 );
        } else if ( typeof target === 'number' ) {
            slideGoTo( target );
        }
        previousNextFree = false;
        setTimeout( function() {
            previousNextFree = true;
        }, 1500 );
    } else {
        zork('Wait a minute mr postman!');
    }
}



function playerUpdateNavigation() {     //Updates visibility of Navigation arrows
    var isCompleted = slideCheckCompletion( courseStatus.position );
    var previous = courseIndex[ courseStatus.position ].previous_button;
    var next = courseIndex[ courseStatus.position ].next_button;

    if ( previous === true && courseStatus.position > 0 /*|| godMode === true && courseStatus.position > 0*/ ) {
        $( '#slide-previous-button' ).fadeIn( 500 );
    } else {
        $( '#slide-previous-button' ).fadeOut( 500 );
    }
    
    if ( isCompleted === true && next === true && courseStatus.progress >= courseStatus.position /*|| godMode === true && courseIndex[ courseStatus.position + 1 ] !== undefined*/ ) {
        $( '#slide-next-button' ).fadeIn( 500 );
    } else {
        $( '#slide-next-button' ).fadeOut( 500 );
    }
    
}

function playerHideNavigation() {   //Hides Navigation arrows
    $( '#slide-previous-button' ).fadeOut( 500 );
    $( '#slide-next-button' ).fadeOut( 500 );
}

function playerUpdateControls() {   //Updates visibility of Player controls
    var isCompleted = slideCheckCompletion( courseStatus.position );
    var home = courseIndex[ courseStatus.position ].home_button;
    var menu = courseIndex[ courseStatus.position ].menu_button;
    
    if ( home === true ) {
        $( '#player-controls-home').fadeIn( 500 );
    } else {
        $( '#player-controls-home').fadeOut( 500 );
    }
    
    if ( menu === true ) {
        $( '#player-controls-menu').fadeIn( 500 );
	$( '#sim-hud').fadeIn( 500 );
    } else {
        $( '#player-controls-menu').fadeOut( 500 );
	$( '#sim-hud').fadeOut( 500 );
    }
}

function playerHideControls() { //Hides Player controls
    $( '#player-controls-home').fadeOut( 500 );
    $( '#player-controls-menu').fadeOut( 500 );
}

function playerUpdateMenu(){    //Updates menu according to index
    
//    var indexSize = 0;		//Check size of index
//    for (i in courseIndex) {
//	indexSize++;
//	if ( courseIndex[i] === undefined ){
//	    break;
//	}
//    }
    
    var indexSize = courseIndex.length;
    
    var lastLink = 0;
    
    $( '#slide-menu section' ).empty();	//Empty the menu
    
    for ( i = 0; i < indexSize; i++ ) {
	var link = courseIndex[i];
	
	var isCompleted = slideCheckCompletion( i );
	
	var linkExtras = '';

	if ( link.indexed === true ) {	//Check to see if slide is to be indexed or not
	    $( '#slide-menu section' ).append( '<a id="menu-link-' + i + '" href="#" class="' + linkExtras + '" onclick="slideGoTo(' + i + ')">' + link.name + '</a>' );
	    
	    if ( slideActive >= i ) {
		lastLink = i;
	    }
	}
	if ( isCompleted === false ) {
	    $( '#menu-link-' + i ).addClass( 'button-locked' );
	}
    }

    $( '#menu-link-' + lastLink ).addClass( 'link-active' );
    if ( playerSubTitle === true ) {
	$( '#slide-title' ).html( courseIndex[ lastLink ].name );
    } else {
	$( '#slide-title' ).remove();
    }
}

function playerUpdateProgressBar() {
    if ( playerProgressBar === true ) {
	var size = courseIndex.length - 1;
	var position = courseStatus.position;
	var progress = courseStatus.progress + 1;

	if ( position > 0 ) {
	    var currentPosition = position * 100 / size;
	    var currentProgress = progress * 100 / size;
	    var currentProgressUnlocked = 100 - currentProgress;

	    $( '#progress-bar-position' ).css( 'left', currentPosition + '%' );
	    $( '#progress-bar-cover' ).css( 'width', currentProgressUnlocked + '%' );
	}
    } else {
	$( '#progress-bar' ).remove();
    }
}

function slideChecker() {       //Auto slide unlocker
    if ( typeof courseIndex[ courseStatus.position ].completion === 'number' ) {
        zork( 'Unlocking slide in ' + courseIndex[ courseStatus.position ].completion / 1000 + ' seconds.');
        slideTimedAdvance = setTimeout( function(){
            slideComplete();
            
        }, courseIndex[ courseStatus.position ].completion );
    } else if ( courseIndex[ courseStatus.position ].completion === 'video' ) {
        zork( 'Advancing when the video ends.');
        setTimeout( function() { 
//            $( 'video' ).first().on( 'ended', function() {
//                zork( 'Video ended.');
//                slideComplete();
//            });
            $('#slide-' + courseStatus.position + ' video').on('ended', function () {
                zork('Video ended.');
                slideComplete();
            });
        }, 1500 );
    } else {
        
        zork( 'I\'m waiting for something on your end...');
        
    }
}

function slideComplete( target ) {      //Set completion status
    if ( typeof courseIndex[ courseStatus.position ].unlocks === 'number' ) {
        if ( courseIndex[ courseStatus.position ].unlocks > courseStatus.progress ) {
            slideCompleteUpTo( courseIndex[ target ].unlocks );
	    zork('Progress updated to ' + courseIndex[ target ].unlocks + '.');
        } 
    } else {
        if ( courseStatus.position > courseStatus.progress ) {
            slideCompleteUpTo( courseStatus.position );
	    zork('Progress updated to ' + courseStatus.position + '.');
        } 
    }
    zork('Slide completed!');
    if ( courseIndex[ courseStatus.position ].auto === true ) {
        slideNext();
    }
    courseSave();
}

function slideCheckCompletion( target ) {
    var isCompleted = false;
    
    if ( coursePrecedence === true && courseIndex[ target ] !== undefined ) {
	if ( courseIndex[ target ].precedence === true ) {
	    var prog = target - 1;
	    isCompleted = courseStatus.progress >= target - 1;
	} else if (typeof courseIndex[ target ].precedence === 'number' ) {
	    isCompleted = courseStatus.progress >= courseIndex[ target ].precedence;
	} else if ( courseIndex[ target ].precedence === false ) {
	    isCompleted = true;
	}
    } else {
        isCompleted = true;
    }
    return isCompleted;
}

function slideCompleteUpTo( target ) {
    if ( target > courseStatus.progress ) {
        courseStatus.progress = target;
        zork( 'Course progress updated: ' + courseStatus.progress );
    }
    courseSave();
    playerUpdateNavigation();
    playerUpdateMenu();
}

/*Save and Load*/

function courseReload() {
    setTimeout( function(){
	zork( 'Bye bye!');
    }, 500);
    setTimeout( function(){
	location.reload(false);
    }, 1000);
}

function courseReset() {
    courseStatus = {};
    courseSaveData( 'reset' );
    zork( 'I forget...');
    courseReload();
}

function courseResetSoft() {
    courseSaveData( courseSaveImportantStuff() );
    zork( 'I \'m coming back to the start!!!');
    courseReload();
}
function courseResetCheckpoint() {
    if ( courseStatus.checkpoint > 0 ) {
	courseSaveData( courseSaveCheckpointStuff() );
	zork( 'I \'m going back to the last points I checked!');
	courseReload();
    } else {
	zork( 'I haven\'t checked anything...' );
    }
}

function coursePrintStatus() {
    for ( var i in courseStatus ) {
	    if ( courseStatus[i].constructor  === Array ){
		for ( f = 0; f < courseStatus[i].length; f++ ) {
		    zork(  i + '['+f+']' + ':' + courseStatus[i][f] );
		}
	    } else {
		zork( i + ':' + courseStatus[i] );
	    }
        }
}

function courseSave() {
    courseSaveData();
}

function courseLoad() {
    var saveData = '';

    
    if ( amnesiaMode === false ) {
        if ( courseMode === 'local' ) {
            saveData = localStorage.getItem('suspend_data');
        } else if ( courseMode === 'scorm' ) {
            saveData = SCORMLoadData();
        } else if ( courseMode === 'webserver' ) {
            //saveData = fetchBDData();
        } else if ( courseMode === 'hse' ) {
            saveData = getFromServer();
        }
    }
    
    if ( saveData === null ) {
	saveData = '';
    }
    
    if ( saveData.length > 0 ) {
	
        zork( 'I remember this: ' + saveData );
	
	saveData = saveData.split("|");
	
        for ( i = 0; i < saveData.length; i++ ) {
	    var variable = saveData[ i ].split(':');
	    var status = variable[0];
	    var data = variable[1];
	    //zork('Loading ' + status + '...' );
	    
	    //if ( saveData[ i ].includes('[') && saveData[ i ].includes(']' ) ) {
	    //if ( stringIncludes( saveData[ i ], '[' ) && stringIncludes( saveData[ i ], ']' ) ) {
	    if ( saveData[ i ].indexOf('[') > -1 && saveData[ i ].indexOf(']' ) > -1 ) {
		
		status = status.split(/\[|\]/);	//Get Variable name and ID

		var statusName = status[0];
		var statusID = parseIfInteger( status[1] );
		
		//if ( data.includes(',') ) {
		//if ( stringIncludes( data, ',' ) ) {
		if ( data.indexOf(',') > -1 ) {
		    
		    data = data.split(',');
		    
		    for ( d = 0; d < data.length; d++ ) {
			data[ d ] = parseIfInteger( data[ d ] );
		    }
		    
		    courseStatus[statusName][statusID] = new Array;
		    courseStatus[statusName][statusID] = data;
		    
		} else {
		    data = parseIfInteger( data );
		    
		    courseStatus[statusName][statusID] = data;
		}
		//zork('Loaded ' + statusName + '[' + statusID + ']:' + data + '!');

	    } else {
		data = parseIfInteger( variable[1] );
		
		courseStatus[status] = data;
		
		//zork('Loaded ' + status + ':' + data + '!');
	    }
	    
	    
        }
    } else {
        zork( 'I don\'t remember no nothing!' );
    }
    
    // if ( playerHomeStandard === false ) {
    //     if ( courseStatus.position <= courseStatus.progress + 1 ) {
    //         slideGoTo( courseStatus.position );
    //     } else {
    //         slideGoTo( courseStatus.progress );
    //     }
    // } else {
    //     if ( courseStatus.progress >= playerHome ) {
    //         slideGoTo( playerHome );
    //     } else {
    //         if ( courseStatus.position <= courseStatus.progress + 1 ) {
    //             slideGoTo( courseStatus.position );
    //         } else {
    //             slideGoTo( courseStatus.progress );
    //         }
    //     }
    // }

    customFunctions()
    
    $( '#llwindow-save-input' ).val(saveData);
    zork( 'Course loaded to slide ' + courseStatus.position + '.');
}

function courseSaveData( saveString ) {
    
    if ( saveString === undefined ) saveString = '';
    
    if ( amnesiaMode === false ) {
	if ( saveString !== 'reset' && saveString.length === 0 ) {
	    var saveData = '';
	    //Prepare data to be saved...
	    for ( var i in courseStatus ) {
		if ( courseStatus[i].constructor  === Array ){
		    for ( f = 0; f < courseStatus[i].length; f++ ) {
			saveData += i + '['+f+']' + ':' + courseStatus[i][f];
			saveData += '|';
			//zork( 'Saved ' + i + '['+f+']' + ':' + courseStatus[i][f] );
		    }
		} else {
		    saveData += i + ':' + courseStatus[i];
		    saveData += '|';
		    //zork( 'Saved ' + i + ':' + courseStatus[i] );
		}
	    }
	    saveData = saveData.substring(0,saveData.length - 1);
	} else if ( saveString === 'reset' ){
	    saveData = '';
	    zork('Resetting...');
	} else {
	    saveData = saveString;
	    zork('Custom save!');
	}

	//Save in local, scorm or other...
        if ( courseMode === 'local' ) {
            if ( typeof( Storage ) !== 'undefined' ) { 
                localStorage.setItem('suspend_data', saveData);
		zork( 'Course saved locally!');
            } else {
                zork( 'This bowser doesn\'t support localStorage... What gives!?' );
            } 
        } else if ( courseMode === 'scorm' ) {
            SCORMSaveData( saveData );
	    zork( 'Course saved in SCORM!');
        } else if ( courseMode === 'hse' ) {
	    saveInServer( saveData );
	}
	
	$( '#llwindow-save-input' ).val(saveData);
	
        zork( 'I recorded this: ' + saveData );

    } else {
        zork( 'I don\'t remember good...');
    }
}

// End course
function courseGrade() {
    if ( courseMode === 'local' ) {
	courseStatus.game_over = 1;
	var grade = courseStatus.grade;
	zork( 'You completed the course with grade ' + grade + '! This was just a test, obviously...');
    } else if ( courseMode === 'scorm' ) {
	var grade = courseStatus.grade;
	var status = courseFailStatus;
	if ( courseStatus.completed === 1 ) {
	    status = courseEndStatus;
	}
	SCORMSetGrade( grade, 0, 100, status );
	courseSave();
    } else if ( courseMode === 'hse' ) {
	courseStatus.game_over = 1;
	courseSave();
	zork('Mamma Mia!');
    }
}

function courseComplete() {
    var status = courseFailStatus;
    if ( courseStatus.completed === 1 ) {
	status = courseEndStatus;
    }
    courseStatus.completed = 1;
    if ( courseMode === 'local' ) {
	courseSave();
	zork( 'You completed the course! This was just a test, obviously...');
    } else if ( courseMode === 'scorm' ) {
	scorm.setvalue('cmi.completion_status', status);
	SB.gradeIt();
	SB.commit();
	courseSave();
	zork( 'You completed the course! You can close this window...');
    }
}


// SFX Manager
function playerSFXPlay( track ) {
    if ( courseStatus.audio === 1  ) {
	if ( $( '#sfx-' + track )[0].readyState > 0 ) {
	    if ( $( '#sfx-' + track )[0].paused ) {
		$( '#sfx-' + track )[0].volume = 1;
		$( '#sfx-' + track )[0].currentTime = 0;
		$( '#sfx-' + track )[0].play();
//		zork( 'Playing ' + track + ' SFX.' );
	    } else {
		if ( $( '#sfx-' + track )[0].currentTime >= $( '#sfx-' + track )[0].duration - 0.01 ) {
		    playerSFXStop( track );
		}
		$( '#sfx-' + track )[0].play();
//		zork( 'Playing ' + track + ' SFX.' );
	    }
	}
    } else {
//	zork( 'But you don\'t like hearing SFX!' );
    }
}

function playerSFXRestart( track ) {
    if ( courseStatus.audio === 1 ) {
	if ( $( '#sfx-' + track )[0].readyState > 0 ) {
//	    zork( 'Replaying ' + track + ' SFX.' );
	    $( '#sfx-' + track )[0].pause();
	    $( '#sfx-' + track )[0].volume = 1;
	    $( '#sfx-' + track )[0].currentTime = 0;
	    setTimeout( function() {
		$( '#sfx-' + track )[0].play();
//		zork( 'Playing ' + track + ' SFX.' );
	    }, 100);
	}
    } else {
//	zork( 'But you don\'t like hearing SFX!' );
    }
}

function playerSFXStop( track ) {
    if ( track !== 'all' ) {
	if ( $( '#sfx-' + track )[0].readyState > 0 ) {
	    $( '#sfx-' + track )[0].pause();
//	    zork( 'Stoping ' + track + ' SFX.' );
	    $( '#sfx-' + track )[0].currentTime = 0;
	}
    } else if ( track === 'all' ) {
	var size = document.getElementsByClassName('sfx-player').length;
    
	for ( i = 0; i < size; i++ ) {
	    $( '.sfx-player' )[i].pause();
	    $( '.sfx-player' )[i].currentTime = 0;
	}
	/*$( '.sfx-player' ).each(function(){
	    this.pause();
	    this.currentTime = 0;
	});
	*/
	zork( 'Stoping all SFX.' );
    }
}

function playerSFXPause( track ) {
    if ( audio !== 'all' && $( '#sfx-' + track )[0].readyState > 0 ) {
	$( '#sfx-' + track )[0].pause();
	zork( 'Pausing ' + track + ' SFX.' );
    } else if ( track === 'all' ) {
	$( '.sfx-player' ).each(function(){
	    this.pause();
	}); 
	zork( 'Pausing all SFX.' );
    }
}

function playerSFXPlayAfter( audio , time ) {
    
    if ( time === undefined ) time = 0;
    
    setTimeout( function() {
	playerSFXRestart( audio );
    }, time );
}

// Music manager
function playerMusicUpdateBG() {
    var slide = courseStatus.position;
    var track = courseIndex[ slide ].bg_music;
    
    if ( autoplay === true && track !== false && courseStatus.music === 1 ) {
	    playerMusicFadeIn( track );
        $('.audio-off').hide();
        $('.audio-on').show();  
	zork( 'Playing background music track ' + track + '!');
    } else {
        $('.audio-on').hide();
        $('.audio-off').show();
	playerMusicFadeOut( track );
    }
    slideTrack = track;
}


function playerMusicFadeIn( track ) {
    if ( $( '#music-bg-' + track )[0].paused ) {
	$( '#music-bg-' + track ).prop( 'volume', 0 );
	$( '#music-bg-' + track )[0].play();
	zork( 'Playing music track ' + track + '.' );
	setTimeout( function() {
	    playerMusicFadeIn( track );
	}, 10);
    } else {
	var soundLevel = $( '#music-bg-' + track ).prop( 'volume' );
	if ( soundLevel < 1 - 0.01 ) {
	    soundLevel += 0.01;
	    $( '#music-bg-' + track ).prop( 'volume', soundLevel );
	    setTimeout( function() {
		playerMusicFadeIn( track );
	    }, 5);
	} else {
	    soundLevel = 1;
	    $( '#music-bg-' + track ).prop( 'volume', soundLevel );
	    zork('Playing music track ' + track + ' loud and clear!');
	}
    }
}

function playerMusicFadeOut( track ) {

    if ( track !== false && track !== 'all' ) {
	if ( !$( '#music-bg-' + track )[0].paused && useriOS === false ) {
	    var soundLevel = $( '#music-bg-' + track ).prop( 'volume' );
	    if ( soundLevel > 0 + 0.01 ) {
		soundLevel -= 0.01;
		$( '#music-bg-' + track ).prop( 'volume', soundLevel );
		setTimeout( function() {
		    playerMusicFadeOut( track );
		}, 5);
	    } else {
		soundLevel = 0;
		$( '#music-bg-' + track ).prop( 'volume', soundLevel );
		zork( 'Stoping music track ' + track + '.' );
		playerMusicStop( track );
	    }
	} else if ( !$( '#music-bg-' + track )[0].paused && useriOS === true ) {
	    playerMusicStop( track );
	}
    } else if ( track === 'all' ) {
	var tracks = $( '.music-bg' ).length;
	for ( i = 0; i < tracks; i++ ) {
	    if ( i !== slideTrack ) {
		playerMusicFadeOut( i );
	    }
	    
	}	
    }
}

function playerMusicStop( track ) {
    if ( $( '#music-bg-' + track )[0].readyState > 0 ) {
	if ( !$( '#music-bg-' + track )[0].paused ) {
	    $( '#music-bg-' + track )[0].pause();
	    zork( 'Stoping ' + track + ' track.' );
	    $( '#music-bg-' + track )[0].currentTime = 0;
	}
    } else {
	$( '#music-bg-' + track )[0].volume = 0;
	$( '#music-bg-' + track )[0].play();
	setTimeout( function() {
	    playerMusicStop( track );
	}, 50);
    }
}

function playerMusicSpeed( speed ) {
    var track = slideTrack;
    if ( track !== undefined && track !== false ) {
	$('#music-bg-' + track )[0].playbackRate = speed;
    }
}

function playerMusicOff() {
    courseStatus.music = 0;
    playerMusicUpdateBG();
}

function playerMusicOn() {
    courseStatus.music = 1;
    playerMusicUpdateBG();
}

function playerMusicToggle() {
    if ( courseStatus.music === 1 ) {
	playerMusicOff();
    } else if ( courseStatus.music === 0 ) {
	playerMusicOn();
    } 
}

function playerMusicSetVolume( volume ) {
    if ( courseStatus.music === 1 ) {
        $('.music-bg').animate({volume: volume }, 500);
        zork('Setting music volume to ' + volume + '...');
    } else {
        $('.music-bg').animate({volume: 0}, 500);
    }
    
    
}

//Admin

var llwindowKeys = { 
  76: 'l',
  87: 'w',
  73: 'i',
  78: 'n',
  68: 'd',
  79: 'o',
  87: 'w'
};

var llwindowCode = [ 'l', 'l', 'w', 'i', 'n', 'd', 'o', 'w'];

var llwindowPosition = 0;


// Add keydown event listener

document.addEventListener('keydown', function(e) {
    // get the value of the key code from the key map
    var key = llwindowKeys[e.keyCode];
    // get the value of the required key from the konami code
    var requiredKey = llwindowCode[llwindowPosition];

    // compare the key with the required key
    if ( key == requiredKey ) {

	// move to the next key in the konami code sequence
	llwindowPosition++;

	// if the last key is reached, activate cheats
	if ( llwindowPosition == llwindowCode.length ) {
	    llwindowOpen();
	    llwindowPosition = 0;
	}
    } else {
	llwindowPosition = 0;
    }
});

var llwindowKonamiCode = [ 1, 3, 1, 3, 4, 2, 4, 2 ];

var llwindowKonamiPosition = 0;

// LLWINDOW Morse Code

function llwindowKonami(event) {
    var mouseX = event.pageX;
    var mouseY = event.pageY;
    var viewWidth = $(window).width();
    var viewHeight = $(window).height();
    var tolerance = 25;
    var direction = 0;
    
    var up = viewHeight * tolerance / 100;
    var down = viewHeight - up;
    var left = viewWidth * tolerance / 100;
    var right = viewWidth - left;
    
    if ( mouseY <= up ) {
	direction = 1;
    }
    if ( mouseY >= down ) {
	direction = 3;
    }
    if ( mouseX <= left ) {
	direction = 4;
    }
    if ( mouseX >= right ) {
	direction = 2;
    }
    if ( llwindowKonamiCode[ llwindowKonamiPosition ] === direction ) {
	llwindowKonamiPosition += 1;
	//zork('+1!');
    }  else if ( llwindowKonamiCode[ llwindowKonamiPosition ] !== direction ){
	llwindowKonamiPosition = 0;
    }
    
    if ( llwindowKonamiPosition === llwindowKonamiCode.length ) {
	llwindowOpen();
	llwindowKonamiPosition = 0;
    }
    
}


// Make LLWINDOW element draggagle:



function dragElement(elmnt) {
    var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
    if (document.getElementById(elmnt.id )) {
	/* if present, the header is where you move the DIV from:*/
	document.getElementById(elmnt.id + 'header' ).onmousedown = dragMouseDown;
    } else {
	/* otherwise, move the DIV from anywhere inside the DIV:*/
	elmnt.onmousedown = dragMouseDown;
    }

    function dragMouseDown(e) {
	e = e || window.event;
	e.preventDefault();
	// get the mouse cursor position at startup:
	pos3 = e.clientX;
	pos4 = e.clientY;
	document.onmouseup = closeDragElement;
	// call a function whenever the cursor moves:
	document.onmousemove = elementDrag;
    }

    function elementDrag(e) {
	e = e || window.event;
	e.preventDefault();
	// calculate the new cursor position:
	pos1 = pos3 - e.clientX;
	pos2 = pos4 - e.clientY;
	pos3 = e.clientX;
	pos4 = e.clientY;
	// set the element's new position:
	elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
	elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
    }

    function closeDragElement() {
	/* stop moving when mouse button is released:*/
	document.onmouseup = null;
	document.onmousemove = null;
    }
}

function llwindowOpen() {
    
    if ( $('#llwindow').length === 0 ) {
        $('body').append(
                '<section id="llwindow">'+
'	<header id="llwindowheader">'+
'	    <h2>Modo de Administrador</h2>'+
'	    '+
'	    <a href="#" title="Fechar" class="llwindow-control" id="llwindow-close" onclick="llwindowClose(); return false;">⨉</a>'+
'	    <a href="#" title="Minimizar" class="llwindow-control" id="llwindow-minimize" onclick="llwindowMinimize(); return false;">˄</a>'+
'	    <a href="#" title="Maximizar" class="llwindow-control" id="llwindow-maximize" onclick="llwindowMaximize(); return false;" style="display: none;">˅</a>'+
'	</header>'+
'	<main>'+
'	    <p title="Nome do slide"><span id="llwindow-data-name"></span></p>'+
'	    <div class="llwindow-clear"></div>'+
'	    <p title="">Nota do curso: <span id="llwindow-data-grade"></span></p>'+
'	    <p title="">Concluído: <span id="llwindow-data-completed"></span></p>'+
'	    <p title="">Slide #: <span id="llwindow-data-position"></span></p>'+
'	    <p>Progresso <span id="llwindow-data-progress"></span></p>'+
'	    '+
'	    <div class="llwindow-clear"></div>'+
'	    <p style="display: none;" class="llwindow-sim" title="Nome da simulação"><span id="llwindow-data-sim-name"></span></p>'+
'	    <p style="display: none;" class="llwindow-sim">Sim #: <span id="llwindow-data-sim"></span></p>'+
'	    <p style="display: none;" class="llwindow-sim" title="">Nota: <span id="llwindow-data-sim-score">%</span></p>'+
'	    <p style="display: none;" class="llwindow-sim" title="">Chave: <span id="llwindow-data-sim-key"></span></p>'+
'	    '+
'	    '+
'	    <div class="llwindow-clear"></div>'+
'	    <p style="display: none;" class="llwindow-quiz" title="Nome do teste"><span id="llwindow-data-quiz-name"></span></p>'+
'	    <p style="display: none;" class="llwindow-quiz">Quiz #: <span id="llwindow-data-quiz"></span></p>'+
'	    <div class="llwindow-clear"></div>'+
'	    <p style="display: none;" class="llwindow-quiz" title="">Última nota: <span id="llwindow-data-last"></span></p>'+
'	    <p style="display: none;" class="llwindow-quiz" title="">Melhor nota: <span id="llwindow-data-best"></span></p>'+
'	    <p style="display: none;" class="llwindow-quiz" title="">Tentativas: <span id="llwindow-data-attempts"></span></p>'+
'	    <div class="llwindow-clear"></div>'+
'	    <p style="display: none;" class="llwindow-quiz" title="">Banco de perguntas: <span id="llwindow-data-bank"></span></p>'+
'	    <p style="display: none;" class="llwindow-quiz" title="">Pergunta: <span id="llwindow-data-question"></span></p>'+
'	    <p style="display: none;" class="llwindow-quiz" title="">Resposta certa: <span id="llwindow-data-answer"></span></p>'+
'	    <div class="llwindow-clear"></div>'+
'	    <textarea id="llwindow-zork" readonly></textarea>'+
'	    <input class="llwindow-control" id="llwindow-save-input" contenteditable="true">'+
'	    <a href="#" class="llwindow-control" title="Regravar..." id="llwindow-save-force" onclick="courseSaveData( $( \'#llwindow-save-input\' ).val() ); return false;">🖫</a>'+
'	</main>'+
'	<footer>'+
'	    <a href="#" class="llwindow-control" title="Limpar resposta" id="llwindow-reset" onclick="courseStatus.sim_points[currentSim] = undefined; courseStatus.sim_percentage[currentSim] = undefined; courseSave(); courseReload(); return false;">⌧</a>'+
'	    <a href="#" class="llwindow-control" title="Debloquear curso" id="llwindow-reset" onclick="godMode = true; return false;">◬</a>'+
'	    <a href="#" class="llwindow-control" title="Desligar/ligar música" id="llwindow-music" onclick="playerMusicToggle();return false;">𝅘𝅥𝅮</a>'+
'	    <a href="#" class="llwindow-control" title="Desligar/ligar som" id="llwindow-sound" onclick="playerControlsToggleAudio();return false;">🕪</a>'+
'	    <a href="#" class="llwindow-control" title="Mostrar variáves" id="llwindow-print" onclick="coursePrintStatus(); return false;">🖶</a>'+
'	    <a href="#" class="llwindow-control" title="Gravar" id="llwindow-save" onclick="courseSave(); return false;">🖪</a>'+
'	    <a href="#" class="llwindow-control" title="Reiniciar curso" id="llwindow-reset" onclick="courseReset(); return false;">↺</a>'+
'	    <a href="#" class="llwindow-control" title="Completar slide" id="llwindow-complete" onclick="slideComplete(); return false;">☑</a>'+
'	    <a href="#" class="llwindow-control" title="Anterior" id="llwindow-prev" onclick="slidePrev(); return false;">⯇</a>'+
'	    <input class="llwindow-control" id="llwindow-go-input" contenteditable="true">'+
'	    <a href="#" class="llwindow-control" title="Ir para..." id="llwindow-go" onclick="slideGoTo( $( \'#llwindow-go-input\' ).val() ); return false;">▷</a>'+
'	    <a href="#" class="llwindow-control" title="Seguinte" id="llwindow-next" onclick="slideNext(); return false;">⯈</a>'+
'	</footer>'+
'</section>'
                );
        dragElement(document.getElementById('llwindow'));
    }
    
    $( '#llwindow' ).fadeIn( 500 );
    $( '#llwindow-zork').empty();
    llwindowUpdate();
    zorkMode = true;
    adminMode = true;
    godMode = true;
    zork( 'Enabling admin mode!' );
}

function llwindowClose() {
    $( '#llwindow' ).fadeOut( 500 );
    zork( 'Disabling admin mode!' );
    zorkMode = false;
    adminMode = false;
    godMode = false;
}

function llwindowUpdate() {
    $( '#llwindow-data-name' ).text( courseIndex[courseStatus.position].name );
    
    $( '#llwindow-data-grade' ).text( courseStatus.grade );
    $( '#llwindow-data-completed' ).text( courseStatus.completed );
    $( '#llwindow-data-position' ).text( courseStatus.position );
    $( '#llwindow-data-progress' ).text( courseStatus.progress );

}

function llwindowEmpty() {
    $( '#llwindow-data-name' ).empty();
    
    $( '#llwindow-data-grade' ).empty();
    $( '#llwindow-data-completed' ).empty();
    $( '#llwindow-data-position' ).empty();
    $( '#llwindow-data-progess' ).empty();
    
    $( '#llwindow-data-quiz-name' ).empty();
    $( '#llwindow-data-quiz' ).empty();
    $( '#llwindow-data-bank' ).empty();
    $( '#llwindow-data-question' ).empty();
    $( '#llwindow-data-answer' ).empty();
    
    $( '.llwindow-quiz' ).hide();

}

function llwindowMaximize() {
    $( '#llwindow-maximize' ).hide();
    $( '#llwindow-minimize' ).show();
    $( '#llwindow main' ).show();
    
    var textarea = document.getElementById('llwindow-zork');
    textarea.scrollTop = textarea.scrollHeight;
}

function llwindowMinimize() {
    $( '#llwindow-maximize' ).show();
    $( '#llwindow-minimize' ).hide();
    $( '#llwindow main' ).hide();
}

// Detect Touch
$( document ).click(function (event) {   
    //contentHover();
    if ( useriOSTouch === false ) {
	contentSelect();
	useriOSTouch = true;
    }
    //contentSelect();
    llwindowKonami(event);
    if ( autoplay === false ) {
	autoplay = true;
//	customAudioPreLoad();
	setTimeout( function() {
	    playerMusicUpdateBG();
	}, 1000);
	
    }
    if ( userMobile === true && useriOS !== true) {
	playerGoFullscreen();
    }
});

// Load everything player related!
$( document ).ready( function () {	//Initial configuration
    playerConfig();
    playerResize();
    playerDirection();
    
    $(window).resize( function() {	//Updates on resize
	playerResize();
    });
});

$( window ).on( 'load', function() { //Auto stuff
    playerLoad();
});

$( window ).on( 'beforeunload', function() {
    courseSave();
});