// JavaScript Document
var playerExist=0;
var noauto = false;
//var autoplay = "ON";
//var autoadvance = "OFF";
//var countdown = "ON";

var myorigmov;
var myOrigType;
/*!
 * showMovieDiv(mov:String)
 *
 * figures out which movie and what page to show
 *
 */


function showMovieDivCheck(mov, splash, searchselect){
	var noteInProgress = checkMyNoteState();
	
	if(noteInProgress && (eCourseX.textonly == "ON" || (myType == "vid" && transWindow && !transWindow.closed) || (myType == "html" && printWindow && !printWindow.closed))){
		if (confirm(noteprogressClick)){
			$('#noteEntry').css('display', 'none');
			makeNewNote = false;
			showMovieDiv(mov,splash);	
		}
		else{
			if(myType == "vid" && transWindow && !transWindow.closed){
				transWindow.focus();
				//setTimeout(function(){transWindow.document.getElementById("userNote").focus();},2000);			
			}
			else if (myType == "html" && printWindow && !printWindow.closed){
				printWindow.focus();
			}
			else document.getElementById("userNote").focus();
		}
	}
	else{
		showMovieDiv(mov,splash, searchselect);
	}
}

function showMovieDiv(mov, splash, searchselect) {
	if(searchselect){
		var myorigselect = xtraselect;
		xtraselect = searchselect;
		for(a=0;a<selectoptions.length;a++){
			if(selectoptions[a][0] == searchselect) currentSelect = selectoptions[a][1];
		}
	}
	//console.log("mov is " + mov);
	myorigmov = mov;
	if(splash === "first"){
		console.log("turning off autoplay");
		noauto=true;
		
	}
	else {
		noauto=false;
		console.log("turning on autoplay");
	}
	myExistingNote = "";
    var demoChk = "no";
	var demoImgChk = "no";
	var demoNameChk ="no";
	var lastMovieChecker = false;
	var highFlag = 0;
	var lastMovie,
		myMovieIndex;
	myObjectID = mov; 
	if(mov.indexOf("select")>-1 && xtraselect !="none"){
		myObjectID = mov.slice(0, -6);
		myObjectID = myObjectID+xtraselect;
	}
	makeNewNote = false;
	myLessonX = myObjectID.substring(0,myObjectID.indexOf("_"));
	myLessonX = myLessonX.slice(-2);
	var myshortlesson;
    mylessonString = eCodeLC + myLessonX;
	//if(myLessonX.indexOf("0")==0)var myshortlesson = parseInt(myLessonX.substr(1));
	//else var myshortlesson = parseInt(myLessonX);
	//look up myshortlesson in lessReport as num, not as array key
	var mylessrepkeys = Object.keys(eCourseX.lessReport);
//console.log("ecourse lessreport length is " + mylessrepkeys.length);		//go thru lessReport and check 'num' in each, if it matches myLessonX, then use the index from that element as myshortlesson
	
			
			for(a=0;a<mylessrepkeys.length;a++){
			//console.log("a is " +a+" and num is " + eCourseX.lessReport[a]['num']);
			if(eCourseX.lessReport[mylessrepkeys[a]]['num']==myLessonX) myshortlesson = mylessrepkeys[a];
			
		}
	
	//console.log("myshortlesson is " + myshortlesson);
	//if(lessonTitles[0][0].slice(-2)!="00"){
	//	myshortlesson=myshortlesson-1;
	//}
	var mytitle = getMovieName(mov);
    console.log("MYTITLE FIRST IS " + mytitle);
    if(mytitle.indexOf("<")!=0)	mytitle = mytitle.substring(0,mytitle.indexOf("<"));
    else mytitle = mytitle.substring(mytitle.indexOf(">")+1,mytitle.lastIndexOf("<"));	
    console.log("MYTITLE IS " + mytitle);											   
	if(eCourseX.lessReport[myshortlesson]['view']=="undefined" || eCourseX.lessReport[myshortlesson]['view']==""|| eCourseX.lessReport[myshortlesson]['view']==0 ||eCourseX.lessReport[myshortlesson]['view']==null) eCourseX.lessReport[myshortlesson]['view']= new Date();
	var lessDate = new Date(eCourseX.lessReport[myshortlesson]['view']);
	var lessYear = lessDate.getFullYear();
	var lessMon = lessDate.getMonth();
	var lessDay = lessDate.getDate();
	lessDate = lessDay+"/"+lessMon+"/"+lessYear;
	var nowDate = new Date();
	var nowYear = nowDate.getFullYear();
	var nowMon = nowDate.getMonth();
	var nowDay = nowDate.getDate();
	nowDate = nowDay+"/"+nowMon+"/"+nowYear;

	//console.log("current lesson date is " +lessDate+ " which is type " + typeof lessDate);
	//console.log("now date is " + nowDate + " which is type " + typeof nowDate );
	if(eCourseX.lessReport[myshortlesson]['access']=="0" || eCourseX.lessReport[myshortlesson]['access']==null || eCourseX.lessReport[myshortlesson]['access']==0){
		eCourseX.lessReport[myshortlesson]['access']=1;
	}
	else if(lessDate != nowDate ){
		console.log("increasing lesson access count for " + myshortlesson);
		eCourseX.lessReport[myshortlesson]['access']++;
	}

	eCourseX.lessReport[myshortlesson]['view'] = Date.now();
	
	//console.log("in rcplayer and lessrport is " + eCourseX.lessReport[myshortlesson]);
	if(typeof eCourseX.lessReport[myshortlesson]['start']=="undefined" || eCourseX.lessReport[myshortlesson]['start']=="" || eCourseX.lessReport[myshortlesson]['start']==null|| eCourseX.lessReport[myshortlesson]['start']==0){
		eCourseX.lessReport[myshortlesson]['start']= Date.now();
		//console.log("trying to send data for " + myshortlesson + " as " + eCourseX.lessReport[myshortlesson]['start']);
		if(!testarea) window.parent.SetDataChunk(JSON.stringify(eCourseX));
	}

	//if the topic youre playing is not in overview lesson and course-started is 0, set course-started timestamp.
	if(eCourseX.coursestart == 0 || eCourseX.coursestart == null){
		
		if ((lessonTitles.length > 1 && myLessonX != '00') ||(lessonTitles.length == 1 && mov != gMovieArray[0][0])){
			eCourseX.coursestart = Date.now();
			sendXAPIstatement(xstarted,window.location.href +"/"+familycode+"/"+eCode+"/"+myLangCode+"/"+versNum);
		
		}
		
	} 
	var coursedate = new Date(eCourseX.timestamp);
	var courYear = coursedate.getFullYear();
	var courMon = coursedate.getMonth();
	var courDay = coursedate.getDate();
	coursedate = courDay+"/"+courMon+"/"+courYear;
	if(mov != gMovieArray[0][0] && (eCourseX.accessC == 0 || eCourseX.accessC == null)) eCourseX.accessC=1;
	else if(mov!=gMovieArray[0][0] && coursedate != nowDate){
		
		eCourseX.accessC++;
	}
	if(!testarea) window.parent.SetDataChunk(JSON.stringify(eCourseX));

		//initialize lessonMoviesComplete if this is the first movie of the session
	if(splash==="first" || (lessonMoviesComplete[0] != myLessonX)){
		lessonMoviesComplete[0] = myLessonX;
		lessonMoviesComplete[1] = 0;
		eCourseX.lprog = 0;
		for(i=0;i<eCourseX.movieComplete.length;i++){
		//	console.log("moviecomplete lesson is " + eCourseX.movieComplete[i].substring(0,eCourseX.movieComplete[i].indexOf("_")));
	    	if(eCourseX.movieComplete[i].substring(0,eCourseX.movieComplete[i].indexOf("_"))==myLessonX){
		    	lessonMoviesComplete[1]++;
		//		console.log("lessonMoviesComplete increasing to " + lessonMoviesComplete[1]);
		    }
	    }
	 }
	
	if ((mov.indexOf("fade") > -1) && (!gHasBegun)) { 
		myMovieArray = movies000;
		gHasBegun = true;
	}
	else {
		myMovieArray = window["movieArray" + myLessonX];
		highFlag = 1;
	}
	
	$.each(myMovieArray, function (i, v) {
		//	console.log("mov is " + mov + " and v is " + v[0]);
		if ($.inArray(mov, v) >= 0) {
			myType = v[1];
			if(eCourseX.textonly == "ON"){
				if (v[1] == "vid") { 
					myType = "html"; 
					myOrigType = v[1];
				}
			    else {
					myType = v[1];
					myOrigType= "";
				}
			}
			if(mov.indexOf("select")>-1 && xtraselect !="none"){
				for(j=0;j<selectoptions.length;j++){
					if(selectoptions[j][0] == xtraselect) {
						myMovieTime = (v[3][j]) ? v[3][j] : '';
					}	
				}
			}
			elsemyMovieTime = (v[3]) ? v[3] : '';
			myMovieTitle = v[2];
		
			myMovieDetails = (v[4]) ? v[4] : '';
			if(myMovieDetails !='' && myMovieDetails !=' ') $('#addInfo').css('display','inline-block');
			else $('#addInfo').css('display','none');
			if(mov.indexOf("select")>-1 && xtraselect !="none"){
				for(j=0;j<selectoptions.length;j++){
					if(selectoptions[j][0] == xtraselect) {
						myBrightcoveID = (v[5][j]) ? v[5][j] : '';
						myMovieTitle+= ' '+selectoptions[j][1];
					}	
				}
			}
			else myBrightcoveID = (v[5]) ? v[5] : '';
			myMovieIndex = i;
			if (myMovieTitle.indexOf("'>") > -1){
				//console.log("in the demo stuff");
				{demoImgChk = "yes";}
				var start = myMovieTitle.lastIndexOf("'>")+2;
				var imgStripper = myMovieTitle.substr(start);
				myMovieTitle = imgStripper;		
				
				if ((myMovieTitle.substring(0, 4)) == demolabel) {demoChk = "yes";}
				else {demoChk = "no";}	
			}
			if (myObjectID.indexOf('demo') > -1) {demoNameChk = "yes"}
			myTextVersion = myLessonX + '/' + myObjectID + '.htm'; 
            myAccVersion = myLessonX + '/' + myObjectID + '_acc.htm';
			console.log("myaccversion is " + myAccVersion);
			myVTT = myLessonX + '/' + myObjectID + '.vtt';
			myExercise = myLessonX + '/' + myObjectID + '_ex.pdf';			
			myExerciseSoln = myLessonX + '/' + myObjectID + '_exsoln.pdf';
			myExCode = myLessonX + '/' + myObjectID + '_code.htm';
			myExTask = myLessonX + '/' + myObjectID + '_task.htm';
			myExLev1 = myLessonX + '/' + myObjectID + '_l1.htm';
			myExLev2 = myLessonX + '/' + myObjectID + '_l2.htm';
			myExLev3 = myLessonX + '/' + myObjectID + '_l3.htm';
			myExLev4 = myLessonX + '/' + myObjectID + '_l4.htm';
			myExLev5 = myLessonX + '/' + myObjectID + '_l5.htm';
			myHTMLQuiz = myLessonX + '/' + myObjectID + '_quiz.htm';
			mySummary = myLessonX + '/' + myObjectID + '_sum.htm';
			myCP = myLessonX + '/' + myObjectID + '/index.html';
			mySim = myLessonX + '/' + myObjectID + '/index.html';
			mySimSteps = myLessonX + '/' + myObjectID + '_steps.htm';
			myHTMLPath = myLessonX + '/' + myObjectID + ((v[2] == quizlabel) ? '_quiz' : '') + 'x.htm';
			if (hasDemoPDF) {myDemoSteps = myLessonX + '/' + myObjectID + '_demo.pdf';}
			else if (hasDemoHTML) { myDemoSteps = myLessonX + '/' + myObjectID + '_steps.htm';}
		}
		if (i === myMovieArray.length - 1) {lastMovie = v[0];}
	});
	

switch (myType) {
	
	case "vid":
		
		if(allAccFiles.includes(myObjectID+"_acc.htm") && ((typeof hasAccVersion != 'undefined' && hasAccVersion==true) || (typeof hasAccFiles != 'undefined' && hasAccFiles == "yes"))){
			
			$('#transcript').load(myAccVersion, function(){
				console.log("loaded " + myAccVersion);
			    if ($('math').length >0) {MathJax.typeset();}
			    openTranscript('function');
			  });
		}
		else{
			$('#transcript').load(myTextVersion, function(){
				console.log("loaded plain " + myTextVersion);
			    if ($('math').length >0) {MathJax.typeset();}
			   openTranscript('function');
			   });
		}

		/*if ((typeof xtraselect != 'undefined' && xtraselect !="none")&&(mov.indexOf("select")>-1)) {$('#movieTitle').html(myMovieTitle + " " + currentSelect); }
		else*/ $('#movieTitle').html(myMovieTitle);
		$('#printVersion').show();

	  	if ((demoChk === "yes")||(demoNameChk === "yes")||(demoImgChk === "yes")){
	      	if ((hasDemoPDF === true)||(hasDemoHTML === true)) { 
		    	$('#demoSteps').show();
	        	$('#demoSteps').attr("onClick","Javascript: openDemoSteps(myDemoSteps)");
		  	}
			else {
				$('#demoSteps').hide();
		    }	
		 	if (hasExCodeTask === true) { 
				$('#demoSteps').text(stattaskbtn);
				$('#demoSteps').attr("title",stattaskbtn);
				$('#demoSteps').attr("aria-label","Open SAS Studio Task Steps");
		  	}	
	  	}
	  	else {
		  	$('#demoSteps').hide();
	 	}
		if ((typeof xtraselect != 'undefined' && xtraselect !="none")&&(mov.indexOf("select")>-1)) { 
			$('#xtraChange').show();
			$('#xtraChange').attr("onClick","Javascript: openOther('rc_common/xtraselector.htm')");
			$('#xtraSet').removeClass("xtraOff");
			$('#xtraSet').addClass("xtraOn");
		}	
		else {
		 	$('#xtraChange').hide();
		 	$('#xtraSet').removeClass("xtraOn");
		 	$('#xtraSet').addClass("xtraOff");
	 	}
	  	cleanVideoContainer();
	  
		
		
		buildPlayer(myBrightcoveID,myVTT,myObjectID); 
		
	break;
	

	case "exercise":
		seeHTML = 'rc_common/seehtm.htm';
		$('#transcript').load(seeHTML);
		loadNoTranscript();
	   	$('#movieTitle').html('');
		$('#demoSteps').hide();
		
		if(hasExCodeTask == true){  
			myTextVersion = 'rc_common/excodetask_launch.htm';
		}
		else{	
			myTextVersion = 'rc_common/exer_launch_tt.htm';
		}
		
		if  ((playerExist > 0) || ($("#cpContainer").length > 0)) {cleanVideoContainer();}
		if ((typeof xtraselect != 'undefined' && xtraselect !="none")&&(mov.indexOf("select")>-1)) { 
			$('#xtraChange').show();
			$('#xtraChange').attr("onClick","Javascript: openOther('rc_common/xtraselector.htm')");
			$('#xtraSet').removeClass("xtraOff");
			$('#xtraSet').addClass("xtraOn");
		}	
		else {
		 	$('#xtraChange').hide();
		 	$('#xtraSet').removeClass("xtraOn");
		 	$('#xtraSet').addClass("xtraOff");
	 	}
	  	buildHTML(myTextVersion);
		
	break;
		
		
	case "html":
		seeHTML = 'rc_common/seehtm.htm';
		$('#transcript').load(seeHTML);	
        loadNoTranscript();		
	    $('#movieTitle').html(' ');


		if  ((playerExist > 0) || ($("#cpContainer").length > 0)) {cleanVideoContainer();}
		 			
		if(eCourseX.textonly == "ON"){
			if(myOrigType == "vid"){
				if(allAccFiles.includes(myObjectID+"_acc.htm")&& (hasAccVersion == true || hasAccFiles == "yes")){
					buildHTML(myAccVersion);
				}
				else if(allStepsFiles.includes(myObjectID+"_steps.htm")){ 
					buildHTML(myLessonX+"/"+myObjectID+"_steps.htm");
				}
				else {
					buildHTML(myTextVersion);
				}

				if ((demoChk === "yes")||(demoNameChk === "yes")||(demoImgChk === "yes")){
					if (hasDemoPDF === true) { 
					  $('#demoSteps').show();
					  $('#demoSteps').attr("onClick","Javascript: openDemoSteps(myDemoSteps)");
					}
        			else {
						$('#demoSteps').hide();
					}
				}
			}
			else {
				buildHTML(myTextVersion);
				$('#demoSteps').hide();
			}
		}
		else {
			buildHTML(myTextVersion);
			$('#demoSteps').hide();
		}
		if ((typeof xtraselect != 'undefined' && xtraselect !="none")&&(mov.indexOf("select")>-1)) { 
			$('#xtraChange').show();
			$('#xtraChange').attr("onClick","Javascript: openOther('rc_common/xtraselector.htm')");
			$('#xtraSet').removeClass("xtraOff");
			$('#xtraSet').addClass("xtraOn");
		}	
		else {
		 	$('#xtraChange').hide();
		 	$('#xtraSet').removeClass("xtraOn");
		 	$('#xtraSet').addClass("xtraOff");
	 	}
		
	break;

	case "":
		seeHTML = 'rc_common/seehtm.htm';
		$('#transcript').load(seeHTML);	
        loadNoTranscript();		
	    $('#movieTitle').html(' ');
        $('#demoSteps').hide();

		if  ((playerExist > 0) || ($("#cpContainer").length > 0)) {cleanVideoContainer();}
		 	
		
		if(eCourseX.textonly == "ON"){
			if(myOrigType == "vid"){
				if(allStepsFiles.includes(myObjectID+"_steps.htm")){ 
					buildHTML(myLessonX+"/"+myObjectID+"_steps.htm");
					
				}
				else if(allAccFiles.includes(myObjectID+"_acc.htm")&& (hasAccVersion == true || hasAccFiles == "yes")){
					buildHTML(myAccVersion);
				}
				else {
					buildHTML(myTextVersion);
				}
			}
			else buildHTML(myTextVersion);
		}
		else buildHTML(myTextVersion);
		
		
	break;
	
	case "cp":
		seeHTML = 'rc_common/seehtm.htm';
		$('#transcript').load(seeHTML);	
        loadNoTranscript();		
	    $('#movieTitle').html(' ');
		buildCP(myCP);
		
	break;
		
    
	
	case "sim":
		seeHTML = 'rc_common/seehtm.htm';
		$('#transcript').load(seeHTML);	
        loadNoTranscript();		
	 	$('#movieTitle').html('');
		$('#demoSteps').hide();
		myTextVersion = 'rc_common/sim_launch_tt.htm';

		if ((playerExist > 0) || ($("#cpContainer").length > 0)) {cleanVideoContainer();}
		buildHTML(myTextVersion);
		 
	break;
			
			
	default:
	break;
}

	eCourseX.resume = true;
	
	if (highFlag == "1") {
		highlightTOC(mov, splash);
	}
	if (myMovieTitle.indexOf(quizlabel) === -1 && myMovieTitle.indexOf(casestudylabel) === -1 ) {
		if(nocomplete.includes(myMovieTitle)){
			console.log("page coming soon, no completion set");
		}
		else markMovieComplete(mov);
	} 
	else if ((myMovieTitle.indexOf(quizlabel)>-1 && myMovieTitle.length != quizlabel.length) || (myMovieTitle.indexOf(casestudylabel)>-1 && myMovieTitle.length != casestudylabel.length) ){
		//in case it's a movie about completing the quiz or case study-- like an intro...
		markMovieComplete(mov);
	}
	//set the movie for the narrative without opening it
	for(k=0;k<eCourseX.movieComplete;k++){
		//if the first two chars of movieComplete are the same as myLessonX, 
	}
    showMovieName(myObjectID);
	var shortmov = myObjectID.substring(eCode.length);
	eCourseX.currentMovie[myLessonX] = shortmov;
	eCourseX.bookmark = mov;
	console.log("setting bookmark to " + mov);
		//console.log(eCourseX.currentMovie[mylessonString]);
	setLRSdata();
    var mycleantitle = encodeURIComponent(mytitle);
    console.log("mycleantitle is " + mycleantitle);
	sendXAPIstatement(xexperienced,window.location.href  + '/'+familycode+"/"+eCode+"/"+myLangCode+'/'+versNum+'/'+ myLessonX + '/' + mov + '/' + mycleantitle);
	if(searchselect){
		xtraselect = myorigselect;
		for(a=0;a<selectoptions.length;a++){
			if(selectoptions[a][0] == myorigselect) currentSelect = selectoptions[a][1];
		}
	}
}




/*
 * buildPlayer(mov:String)
 *
 *
 *
 */
var myPlayer;
var captionState = "";
var myCCTrack;
var rateValue="1";
function buildPlayer(whichVid,whichVtt,myMovieName) {
    //add the video tag, create the player instance and load it
		$("#contentContainer").append('<video id="BCvideoContainer" data-account="3251589552001" data-embed="default" data-player="default" data-video-id="" class="video-js" controls></video>'); 

	 //add the brightcove JS customizations to video.js   
		bc(document.getElementById('BCvideoContainer'));
		checkPlayButton();	
	
	 //create the player	
	videojs('BCvideoContainer').ready(function(){
		myPlayer = this;
			
	 //   addPlayRateButton();
		
		//load the video
	    myPlayer.catalog.getVideo(whichVid, function(error, video) { 
		myPlayer.catalog.load(video); 
		 
		
		}); // end of getVideo
		
		captionState = eCourseX.captions;
		if(captionState == "showing") console.log("showing captions");
		if(eCourseX.playrate == "0"){ rateValue="1";}
		else { rateValue = eCourseX.playrate;}
		
		// if the video has CC, load the VTT file
		myPlayer.on("loadedmetadata",function(){
		  	if (hasCC){
             	testCC= myPlayer.textTracks();
        //      console.log(testCC);
			 	myPlayer.addRemoteTextTrack({	
			  		kind: 'captions',
			  		language: myLangCode,
			  		label: myLang,
			  		src: whichVtt
				}, true); 
		
			// get a list of textTracks		
				myCCTrack = myPlayer.textTracks();
			//look for the text track that has the caption and turn on or off captions based on captionState 
				var length = myCCTrack.length;		
				for (i=0;i<length;i++){
					if(myCCTrack[i].hasOwnProperty('src')){
						var mySRC = myCCTrack[i].src;
						if (mySRC.indexOf(".vtt") > -1){
							myCCTrack[i].mode = captionState;
						}
					}
				}	
		  	}
		//if autoplay is on, play the video
		    if (eCourseX.autoplay === "ON" && noauto==false) {
				
			    myPlayer.play();
		    }
			

		}); //end of onloadedmetadata
	//	var markedDone = false;
	//watchers for CC or playrate changes 	
        myPlayer.on('timeupdate',function(){
			if (hasCC){
			var length = myCCTrack.length; 
			for (i=0;i<length;i++){
					if(myCCTrack[i].mode === "showing"){
						captionState = "showing";
						eCourseX.captions = "showing";	
						
					} 
					else {
						captionState = "disabled";
						eCourseX.captions = "disabled";					
					}
				}
			}
			//	var viewedEnough = myPlayer.duration()*.8;
				
			//	if(Math.round(myPlayer.currentTime())>=Math.round(viewedEnough) ){
				
			//		if(!markedDone){
			//			markMovieComplete(myMovieName);	
			//			markedDone = true;
						//console.log("marked movie done: " + myMovieName);
			//		}
					
			//	}
		});	// end of ontimeupdate	
	
        //get playback value when paused 
  		myPlayer.on('pause', function(){
    		rateValue = getPlayBackRate();
  		});
			
  		myPlayer.on('ratechange',function(){
			rateValue = getPlayBackRate();
    	//get new playback rate if the player is paused
    		if(myPlayer.paused()){
      			rateValue = getPlayBackRate();
    		}
  		});
  		//set backuped playback rate when playback starts
  		myPlayer.on('play', function(){
    		myPlayer.playbackRate(rateValue);
  		});
	 
		


		//log movieWatched and if autoadvance is on, continueMovie
		myPlayer.on('ended',function(){
			var noteInProgress = checkMyNoteState();
			logMovieEnd(myMovieName, noteInProgress);
        });
		
   }); //end of videoJS()

	playerExist = 1;
} 
	
  	//get method for selected playback rate value 
function getPlayBackRate(){
    rateEl = document.getElementsByClassName('vjs-playback-rate-value')[0];
    rateValue = rateEl.innerText.substr( 0, rateEl.innerText.length-1 );
		eCourseX.playrate = rateValue;
		setLRSdata();
    return rateValue; 
}
function checkPlayButton(){
	if (eCourseX.autoplay === "ON" && noauto == false) {$('.vjs-big-play-button').css('display','none');}

	else {$('.vjs-big-play-button').css('display','');}
}

/* setAutoplay - starts movies automatically when they load. default is ON */
function setAutoplay(){
//	console.log("in autoplay func");
	if (eCourseX.autoplay === "ON") {
		eCourseX.autoplay="OFF";
		checkPlayButton();
		$('#autoplayButt').text(ason + ' (Alt+V)');
		$('#landmarkDivLastItem').text(ason);
		$("<span aria-hidden='true'> (Alt+V)</span>").appendTo($('#landmarkDivLastItem'));
		$('#accPlayButton').text(ason);
		$("<span aria-hidden='true'> (Alt+V)</span>").appendTo($('#accPlayButton'));

		sendXAPIstatement(xinteracted,window.location.href  + "/" + familycode+"/"+eCode+"/"+myLangCode+"/"+versNum+  "/"+myLessonX + "/" + myObjectID + "/autoplayOFF");
	}
	else {
		eCourseX.autoplay="ON";
		checkPlayButton();
	    $('#autoplayButt').text(asoff + ' (Alt+V)');

	    $('#landmarkDivLastItem').text(asoff);
		$("<span aria-hidden='true'> (Alt+V)</span>").appendTo($('#landmarkDivLastItem'));

		$('#accPlayButton').text(asoff);
		$("<span aria-hidden='true'> (Alt+V)</span>").appendTo($('#accPlayButton'));

		sendXAPIstatement(xinteracted,window.location.href  + "/" + familycode+"/"+eCode+"/"+myLangCode+"/"+versNum+  "/"+myLessonX + "/" + myObjectID + "/autoplayON");
	}
	//eCourseX.autoplay = autoplay;
	setLRSdata();
}
/* plays all movies in a series - default is OFF */
function setAutoadvance(){
	if (eCourseX.autoadvance === "OFF") {
		eCourseX.autoadvance="ON";
		$('#autoadvanceButt').text(aaoff);
		$('#countdownButt').show();
		$("<span aria-hidden='true'> (Alt+J)</span>").appendTo($('#autoadvanceButt'));

		sendXAPIstatement(xinteracted,window.location.href  + "/" + familycode+"/"+eCode+"/"+myLangCode+"/"+versNum+  "/"+myLessonX + "/" + myObjectID + "/autoadvanceON");
	}
	else {
		eCourseX.autoadvance="OFF";
		$('#countdownButt').hide();
		if(eCourseX.countdown==="ON") setVideoCountdown();
		$('#autoadvanceButt').text(aaon);
		$("<span aria-hidden='true'> (Alt+J)</span>").appendTo($('#autoadvanceButt'));

		sendXAPIstatement(xinteracted,window.location.href  + "/" + familycode+"/"+eCode+"/"+myLangCode+"/"+versNum+  "/"+myLessonX + "/" + myObjectID + "/autoadvanceOFF");
	}
	//eCourseX.autoadvance = autoadvance;
	setLRSdata();
	
}

/* countdown before continueMovie */
function setVideoCountdown(){
	if (eCourseX.countdown === "OFF") {
		eCourseX.countdown="ON";
		$('#countdownButt').text(cdoff);
		$("<span aria-hidden='true'> (Alt+K)</span>").appendTo($('#countdownButt'));

		sendXAPIstatement(xinteracted,window.location.href  + "/" + familycode+"/"+eCode+"/"+myLangCode+"/"+versNum+  "/"+myLessonX + "/" + myObjectID + "/countdownON");
	}
	else {
		eCourseX.countdown="OFF";
	    $('#countdownButt').text(cdon);
		$("<span aria-hidden='true'> (Alt+K)</span>").appendTo($('#countdownButt'));

		sendXAPIstatement(xinteracted,window.location.href  + "/" + familycode+"/"+eCode+"/"+myLangCode+"/"+versNum+  "/"+myLessonX + "/" + myObjectID + "/countdownOFF")
	}
	//eCourseX.countdown = countdown;
	setLRSdata();
	
}

/* logMovieEnd
   track whether a movie plays to the end and markMovieWatched if it does.
   If autoadvance is on, continueMovie calls markcomplete
   else markMovieComplete
*/
function logMovieEnd(myMovieName, noteInProgress) {
	
	if (myMovieName.indexOf('fade') === -1) {
		//if(eCourseX.movieComplete.indexOf(myMovieName.substring(eCode.length))<0) markMovieComplete(myMovieName);
		sendXAPIstatement(xcompleted,window.location.href  +'/'+familycode+"/"+eCode+"/"+myLangCode+"/"+versNum +'/'+ myLessonX +"/" + myMovieName);
		
	} 
	
	if(noteInProgress && ((transWindow && !transWindow.closed) || (newWindow && !newWindow.closed))){
		if (confirm(noteprogress)) {
			setAutoadvance();
			if(transWindow && !transWindow.closed){
				setTimeout(function(){transWindow.focus();},100);
				
			}
			else if (newWindow && !newWindow.closed){
				setTimeout(function(){newWindow.focus();},100);
				
			}
			else if (printWindow && !printWindow.closed){
				setTimeout(function(){newWindow.focus();},100);
				
			}									
		} 
		else {
			if(SCORMcourse){
				if(myMovieName == myMovieArray[myMovieArray.length-1][0]){
				alert(endlesson);
				}
				else continueMovie();
			}
			else continueMovie();
		}
	}
	else{
	
      if ((eCourseX.autoadvance === "ON") && (eCourseX.countdown === "ON")){
		   if(SCORMcourse){
			  if(myMovieName == myMovieArray[myMovieArray.length-1][0]){
				alert(endlesson);
			  }
			  else videoCountdown(myMovieName);
		   }
		  
			else videoCountdown(myMovieName);
	     }
	  else if ((eCourseX.autoadvance === "ON") && (eCourseX.countdown === "OFF")){
		   if(SCORMcourse){
			  if(myMovieName == myMovieArray[myMovieArray.length-1][0]){
				alert(endlesson);
			  }
			  else continueMovie();
			}
			else continueMovie();
	  }
	}

}

function videoCountdown(myMovie){	
	if (myMovie.indexOf("_acc")>-1) myMovie = myMovie.slice(0,-4);
	else if (myMovie.indexOf("_steps")>-1) myMovie = myMovie.slice(0,-6);
	var timeleft = 4;
	var downloadTimer = setInterval(function(){
		$("#countdown").css('display','block');
		$('.bigTime').html(timeleft);
		timeleft -= 1;
		if(timeleft <= 0){
			clearInterval(downloadTimer);
			if(myMovie==myObjectID) continueMovie();
			resetTimer();
		}
	}, 1000);		
}

function resetTimer(){
	if( $("#countdown").css('display') =="block"){ $("#countdown").css('display','none')}
}


/*!
 * cleanVideoContainer(mov:String)
 *
 * clears out data in the videocontainer for practices and html displaying
 *
 */
function cleanVideoContainer(){
	if (playerExist > 0) myPlayer.dispose();
	$('#contentContainer').removeData().empty(); 
	$('#contentContainer').html('');
	
	playerExist = 0;
}

/*!
 * buildHTML(mov:String)
 *
 * builds HTML page
 *
 */
function buildHTML(myHTM) {
	//console.log("in buildhtml and trying for " + myHTM);
	
	if(myHTM.indexOf("_steps") != -1) myHTM = myHTM + " div[role='main']";
	
	if ($('#overlayContainer').is('*')) {
		$('#overlayContainer').html('');
	}
	else {
		$("#contentContainer").append('<div id="overlayContainer" tabindex="-1" ></div>');
	}
		
	$('#overlayContainer').load(myHTM, function(){
		/*get rid of old icons */
		$("img[src$='readaboutit.png']").css('display','none');
		$("img[src$='thinkaboutit.png']").css('display','none');

		/* get rid of the old button to create a certificate on resources page, text still there */
		$('button.niceButton[onclick*="downloadECertificate()"]').css('display','none');

		

		if(myOrigType == 'vid'){
			$('#overlayContainer').css('padding', '1.5em');
			$('#overlayContainer').css('font-size', '.9em');
			changeVLEimages();
		}
		else{
			$('#overlayContainer').attr('style', '');
		}
			
		writeGUIOther();
				
		if ($('#printthisEmbed').length) {
			myType = 'html3';
		}
		else if($('#printthis2').length) {
			myType = 'html2';
		}
		else if(($('#printthis').length) && ($('#printthis').text().indexOf(notvideomsg)<0)) {
			myType = 'html1';
		}
		else{
			myType = 'html';
		}
		//can add div here to insert user notes, will need styling, etc.


		if(myHTM.indexOf("_steps") != -1) {
			$("#overlayContainer").append('<div id="accLink"><a href="javascript:openOther('+myAccVersion+');">Open a transcript of the video in another window.</a></div>');
		}

		//$("#overlayContainer").append('<div class="userNotes" id="notesShow" style="display:none"><hr><strong>Notes</strong><br><div id="actualNote"></div></div>')
		var notesSection = '<div class="postIt" id="myNote"><div class="noteHead"><div style="display:inline"><strong>Notes</strong><br></div><div class="noteButtons"style="display:inline">';
		notesSection+='<button class="niceButton" onClick="javascript: editNote();" id="editbtn"></button>&nbsp;&nbsp;&nbsp;<button class="niceButton" onClick="Javascript: deleteNote();" id="delbtn">';
		notesSection+='</button></div></div><div id="actualNote"></div><br>	</div></div><div id="noteEntry"><hr width="85%">';
		notesSection+='	<label id="notemsg" for="userNote"></label><br>	<textarea name="noteEntryBox" id="userNote" rows="5" cols="50" wrap="hard"></textarea>';
		notesSection+='	<br><button class="niceButton" onClick="javascript:sendNote()" id="subbtn"></button>&nbsp;&nbsp;<button class="niceButton" onClick="javascript:cancelNote()" id="canbtn"></button>';
		notesSection+='<script>$("#userNote").on("change", function(){makeNewNote = true;});</script>';
		//		$("#overlayContainer").append(notesSection);
	$("#overlayContainer").append('<div class="userNotes" id="notesSection"></div>');
	$('#notesSection').append(notesSection);
	writeGUIOther();
	loadUserNoteMain();

	});
	
	
//	console.log("calling changeVLE stuff");  IS THIS NEEDED?
//    setTimeout(changeVLEimages(),1000);
}


function buildCP(myCP) {
	 cleanVideoContainer();
	 $("#contentContainer").append('<iframe id="cpContainer" src='+ myCP +'></iframe>');
	 $("#FSbutton").show();
	 $("#FSbutton").attr('onClick','Javascript:openCPFS(myCP)');	 
}


