/*
Copyright © Interactive Services 2013 - 2015 All Rights Reserved.  
No part of this code may be used, with or without modification, without prior consent from Interactive Services. 
Version 1.0, 01 Jan 2015
*/

//Variables
var audio=null;
var audioAsked=0;
var lastSeen = 0;
var timeoutVar = -1;
var iOS = ( navigator.userAgent.match(/(iPad|iPhone|iPod)/g) ? true : false );

var audioTrack = {};

//++++++++++++++++++++++++++++ initAudio +++++++++++++++++++++++++++++++++++++++++++++++++
// Function to initalise the audio object so that the audio can play for each screen.
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function initAudio(state){
	islDebug("[[ initAudio("+state+") ]]","red")
	if(state==true){
		audioAsked=1;
		//iOS/Android autoplay hack
		if(isMobile()) {
			audioFile=$("#wrapper").attr("audioFile");
			loadAudio('blank.mp3', 'narration');
		}
		return true;
	} else if(state===false) {
		audioAsked=2;
		courseBackgroundAudio="off";
		$(".audioBtn").addClass("disabled");
		return false;
	}	
}

//++++++++++++++++++++++++ setupPageAudio +++++++++++++++++++++++++++++++++++++++++
// Responsible for loading narration and background audio on each screen.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function setupPageAudio(){
	//MAIN AUDIO SETUP
	$("#pFile").text('');
	var audioFile = (typeof($("#wrapper").attr("audioFile"))=="undefined") ? "" : $("#wrapper").attr("audioFile");
	if(($("#wrapper").hasClass("branchCheck")) && (lmsVariables.introAudioPlay == "true")) {
		loadAudio('blank.mp3', 'narration');
	} else {
		loadAudio(audioFile, 'narration');
	}

	if(courseBackgroundAudio === 'on'){
		playBackgroundAudio();
	}

	return true;
}

//++++++++++++++++++++++++ playBackgroundAudio ++++++++++++++++++++++++++++++++++++
// Updated playBackgroundAudio function that is more streamlined and easier to read. 
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function playBackgroundAudio() {

	//iOS limitation to only 1 track at the time
	if(iOS) {
		$("#bFile").text('iOS limited to narration only.');
		return false;
	}

	var bgFile = (typeof($("#wrapper").attr("backgroundAudioFile"))=="undefined") ? "" : $("#wrapper").attr("backgroundAudioFile");

	if(bgFile.length === 0 && audioTrack.background !== undefined) {
		soundManager.stop(audioTrack.background.id);
		soundManager.destroySound(audioTrack.background.id);	 
	}

	$("#bFile").text(bgFile);

	if(loadAudio(bgFile, 'background')) return true;
}

//++++++++++++++++++++++++++++++ loadAudio ++++++++++++++++++++++++++++++++++++++++
// Updated loadAudio function that is more streamlined and easier to read. 
// Global: audioTrack
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function loadAudio(audioFile, audioType) {
	hideLoading();

	if(audioType === undefined) audioType = 'narration';
	if(audioAsked!=1 || $(".audioBtn").hasClass("paused")) {

		if(audioTrack[audioType] !== undefined) {
			soundManager.stop(audioTrack[audioType].id);
			soundManager.destroySound(audioTrack[audioType].id);
			audioTrack[audioType] = undefined;
		}
		//return false;
	}

	//islDebug("loadAudio("+audioFile+")","#ff00ff");
	//islDebug("setAttribute to: course/audio/"+audioFile,"#FFF001");

	if(audioTrack[audioType] !== undefined) {
		soundManager.stop(audioTrack[audioType].id);
		soundManager.destroySound(audioTrack[audioType].id);
		audioTrack[audioType] = undefined;
	}

	if(audioFile !==  undefined && audioFile.length > 0) {

	    audioTrack[audioType] = soundManager.createSound({
	        url: "course/audio/"+audioFile,
	        autoLoad: true,
	        onload: function() {
	        	if(!isMobile()) { 
	        		onAudioLoad(audioType, audioFile); 
	        		if($(".audioBtn").hasClass("paused")){
								this.pause();
							}else{
		        		this.play();
		        	} 
	        	} else {
	        		setTimeout(function(){hideLoading()}, 100);
	        	}
	        },
	        onfinish: function() {
						soundManager.stop(audioTrack[audioType].id);
						soundManager.destroySound(audioTrack[audioType].id);	        	
	        	onAudioFinish(audioType, audioFile);
	     		},
	     		whileloading: function() {
	     			onAudioLoading(audioType, this.bytesLoaded);
					},
					onplay: function() {
						onAudioPlay(audioType);
					}
					/*whileplaying: function() {
						if(isMobile()) hideLoading();
					}*/
	    });

	   	//iOS onload method not supported 
	   	if(isMobile()){
	   		if($(".audioBtn").hasClass("paused")){
					soundManager.pause(audioTrack[audioType].id);
				}else{
      		soundManager.play(audioTrack[audioType].id);
      	} 
			}
			return true;
	}else{
		return false;
	}
	
}

function hideLoading() {
	if($("#loadingIndicator").hasClass("visible")) $("#loadingIndicator").removeClass("visible");
	return true;
}
//++++++++++++++++++++++++ playBackgroundAudio ++++++++++++++++++++++++++++++++++++
// Updated playSfxAudio - responsible for playing SFX sounds. 
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function playSfxAudio(audioTarget) {
	//iOS limitation to only 1 track at the time
	if(isMobile()) {
		$("#sFile").text('Mobile device limited to narration only.');
		return false;
	}	

	if (audioAsked!=1 || audioTarget==="" || $(".audioBtn").hasClass("paused") || iOS) return;

	islDebug("playSfxAudio("+audioTarget+")","#ff00ff");
	$("#sFile").text(audioTarget);
	
	if(loadAudio(audioTarget, 'sfx')) return true;
}

//++++++++++++++++++++++++++++++ onAudioLoading ++++++++++++++++++++++++++++++++++++
// Callback when audio is loading, fire following events.
// Passes bytesLoaded - float
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function onAudioLoading(audioType, bytesLoaded) {

	switch(audioType) {
	    case 'narration':
	    	showProgress(bytesLoaded);
	        break;
	    case 'sfx':
	    	//
	        break;
	    case 'background':
	   	 	//
	        break;	        
	}

	return true;
}

//++++++++++++++++++++++++++++++ onAudioPlay ++++++++++++++++++++++++++++++++++++
// On audio playing callback.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function onAudioPlay(audioType) {

	switch(audioType) {
	    case 'narration':
				$("#loadingIndicator").removeClass("visible");
	    	SyncAudio();
	    	break;
	    case 'sfx':
	    	//
	        break;
	    case 'background':
	   	 	//
	        break;	        
	}

	return true;
}

//++++++++++++++++++++++++++++++ onAudioLoad ++++++++++++++++++++++++++++++++++++
// Callback when audio loads, fire following events.
// --- iOS not supported. ---
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function onAudioLoad(audioType, audioFile) {

	switch(audioType) {
	    case 'narration':
			$("#pFile").text(audioFile);
			$(".audioBtn").removeClass("finished");
			$("#loadingIndicator").removeClass("visible");
	        break;
	    case 'sfx':
			$("#sFile").text(audioFile);
	        break;
	    case 'background':
				audioTrack[audioType].setVolume(courseBackgroundAudioVolume);
	     break;	        
	}
	
	return true;
}

//++++++++++++++++++++++++++++++ onAudioFinish ++++++++++++++++++++++++++++++++++++
// Callback when audio finishes, fire following events.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function onAudioFinish(audioType) {

	switch(audioType) {
	    case 'narration':
			$(".audioBtn").addClass("finished");
	        break;
	    case 'sfx':
			$("#sFile").text('');
	        break;
	}
	
	return true;
}

//++++++++++++++++++++++ showProgress +++++++++++++++++++++++++++++++++++
// Set up and show the progress indicator.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function showProgress(bytesLoaded) {

	var percentageLoad = Math.round(bytesLoaded*100);
	// alert(percentageLoad)
	if(percentageLoad < 100 && !$(".audioBtn").hasClass("paused")) {
		$("#loadingIndicator").addClass('visible');
	}else{
		$('#loadingIndicator div.percentage').text(percentageLoad+"%");
		setTimeout(function(){ 
			$("#loadingIndicator").removeClass("visible");
		}, 100);
	}
	$('#loadingIndicator div.percentage').text(percentageLoad+"%");
	return true;
}

//++++++++++++++++++++++++++ toggleAudio() +++++++++++++++++++++++++++++++
// Function to pause the audio.
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function toggleAudio(pause){

	if(audioAsked!=1 || $(".audioBtn").hasClass("finished")) return;

	if($('.vimeoVideo').length > 0) {
		if($('.audioBtn').hasClass('paused')){
			$f($('.vimeoVideo')[0]).api('setVolume', 0); 
		}else{
			$f($('.vimeoVideo')[0]).api('setVolume', 1);
		}
	}
	
	if(vidObjArray[0] != undefined) {
		if(pause===true) {
			vObj.setVolume(0); 
		} else {
			vObj.setVolume(1); 
		}
	}

	if(audioTrack.narration !== undefined){
		if(pause===true) {
			audioTrack.narration.pause();
			return false;
		} else {
			audioTrack.narration.play();
			return true;
		}
	}
}

//++++++++++++++++++++++++++ checkInView +++++++++++++++++++++++++++++++++
// Check the audio file and see if the browser is still in view - if its
// not then pause the audio.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function checkInView(){
	if(isMobile() === false) return false;
	var hidden = "hidden";
	var isVisible;

    // Standards:
    if (hidden in document)
        document.addEventListener("visibilitychange", onchange);
    else if ((hidden = "mozHidden") in document)
        document.addEventListener("mozvisibilitychange", onchange);
    else if ((hidden = "webkitHidden") in document)
        document.addEventListener("webkitvisibilitychange", onchange);
    else if ((hidden = "msHidden") in document)
        document.addEventListener("msvisibilitychange", onchange);
    // IE 9 and lower:
    else if ('onfocusin' in document)
        document.onfocusin = document.onfocusout = onchange;
    // All others:
    else
        window.onpageshow = window.onpagehide 
            = window.onfocus = window.onblur = onchange;

    function onchange (evt) {
        var v = 'visible', h = 'hidden',
            evtMap = { 
                focus:v, focusin:v, pageshow:v, blur:h, focusout:h, pagehide:h 
            };

        evt = evt || window.event;
        if (evt.type in evtMap)
            var isVisible = evtMap[evt.type];
        else        
            var isVisible = this[hidden] ? "hidden" : "visible";

       	if(isVisible == 'hidden')
	 		soundManager.pauseAll();	 		
       	else
	 		soundManager.resumeAll();	 		

    }
    // set the initial state
    onchange({type:(document.visibilityState == "visible") ? "focus" : "blur"})        
}

//++++++++++++++++++++++++++ SyncAudio +++++++++++++++++++++++++++++++++
// Function for syncing text with audio using 'time' attribute
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function SyncAudio() {
    var AnimateIn = [];
    if($( "*[time]" )[0] ) {
        $( "*[time]" ).each(function( index ) {
            var tweenAudio = new TimelineMax();
            tweenAudio.add(TweenMax.from(this, 1, {autoAlpha:0, scale:0.5, delay: $(this).attr('time')}));
        });        
        return true;
    }
}
