/*
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 2.1, 01 March 2015
*/
var mqCurrentSlide;

/********************************************************************************************/
/********************************* IMAGE REVEL TEMPLATE *************************************/
/********************************************************************************************/
function imgReveal() {
	//on mousemove over the image show the image below
	$('.image_reveal').mousemove(function(event) {
			var newPos = event.pageX - $(this).offset().left;
			var imgWidth = $('.img_left').width();
			//change the width of the container
			newPos = (newPos<0)? 0 : newPos
			newPos = (newPos>imgWidth)? imgWidth : newPos
			$('.sliderContainer').css({"width": newPos+"px"});
			positionSlider();

			if((newPos>=(imgWidth*0.75)) && ($('.sliderContainer').hasClass("controlnav")==true)){
				$('.sliderContainer').removeClass("controlnav")
				checkRestrictedNav();
			}
	});

	//touch functionality for tablets
	$(".image_reveal").unbind("touchstart touchmove").bind("touchstart touchmove", function(e) {
			//Disable scrolling by preventing default touch behaviour
			e.preventDefault();
			var orig = e.originalEvent;
			var newPos = orig.changedTouches[0].pageX - $(this).offset().left;
			var imgWidth = $('.img_left').width();
			//change the width of the container
			newPos = (newPos<0)? 0 : newPos
			newPos = (newPos>imgWidth)? imgWidth : newPos

			$('.sliderContainer').css({"width": newPos+"px"});
			positionSlider();


			if((newPos>=(imgWidth*0.75)) && ($('.sliderContainer').hasClass("controlnav")==true)){
				$('.sliderContainer').removeClass("controlnav")
				checkRestrictedNav();
			}
	});

	function positionSlider(){
		var newPos = $('.sliderContainer').width()-15;
		$(".slider").css("left", newPos+"px")
	}

	$(".img_left").load(function() {
		positionSlider();
  });
}



/********************************************************************************************/
/*************************************** SCENARIO *******************************************/
/********************************************************************************************/
//CALLED BY updateGUI() IN THE framework_navigation.js FILE
function addLSindicator(){
	if($(".ls_breadcrumb").length){
		 updateLSBreadcrumb();
		 return false;
	}
	$("#wrapper").addClass("linear_scenario")
	$("#wrapper").append("<div class='ls_breadcrumb'></div>")

	for (var i=0; i < currentPage.parent.pageNodes.length; i++){
		if(currentPage.parent.pageNodes[i].type=="question"){
			$('.ls_breadcrumb').append("<div class='ls_crumb' data-ref='"+currentPage.parent.pageNodes[i].src+"'></div>")
			if(currentPage.parent.pageNodes[i+1].type=="question"){
				$('.ls_breadcrumb').append("<div class='ls_connector'></div>")
			}
		}
	}
	$('.ls_breadcrumb').css("margin-left", ($('.ls_breadcrumb').width()/2)*-1);
	updateLSBreadcrumb();
}

function updateLSBreadcrumb(){
	$(".ls_crumb").each(function() {
		var pageObj = findPageBySrc(course, $(this).data("ref"))
		if(pageObj.scoreProgress != undefined && pageObj.scoreProgress ==1){
			$(this).addClass("correct")
		}else if(pageObj.scoreProgress != undefined && pageObj.scoreProgress ==0){
			$(this).addClass("incorrect")
		}
	});
}

function getScenarioFeedback() {
	var numCorrect = 0
	var numQuestions = 0
	var numNotAnswered = 0
	for(i = 0; i<currentPage.parent.pageNodes.length;i++){
		if(currentPage.parent.pageNodes[i].type == "question"){
			numQuestions++;
			numCorrect = (currentPage.parent.pageNodes[i].scoreProgress != undefined && currentPage.parent.pageNodes[i].scoreProgress == 1) ? numCorrect+1 : numCorrect
			numNotAnswered = (currentPage.parent.pageNodes[i].scoreProgress == undefined) ? numNotAnswered+1 : numNotAnswered
			islDebug(currentPage.parent.pageNodes[i].src+"  "+currentPage.parent.pageNodes[i].scoreProgress)
		}
	}

	if(numNotAnswered != 0 && currentPage.parent.examscore!=-1){
		var percentage = parseInt(currentPage.parent.examscore);
		var numCorrect = (percentage*numQuestions)/100;
	}else{
		var percentage = Math.round(numCorrect/numQuestions * 100);
	}

	currentPage.parent.examscore = (percentage >currentPage.parent.examscore) ? percentage : currentPage.parent.examscore
	var txt = (percentage >= $("#wrapper").data("passrate")) ? $("div[feedback_type='positive']").html() : $("div[feedback_type='negative']").html()
	txt = txt.split("xxx").join(numCorrect);
	txt = txt.split("yyy").join(numQuestions);
	txt = txt.split("zzz").join(percentage);
	$(".final_text").html(txt);

	var promptTxt = (percentage >= $("#wrapper").data("passrate")) ? $("div[prompt_type='positive']").html() : $("div[prompt_type='negative']").html()
	$(".instruction").html(promptTxt)

	if(percentage >= $("#wrapper").data("passrate")){
		$("#retryQuiz").addClass("invisible")

		$("#passImage").removeClass("invisible")
		$("#failImage").addClass("invisible")
	}else{
		$("#retryQuiz").removeClass("invisible")

		$("#passImage").addClass("invisible")
		$("#failImage").removeClass("invisible")
	}
}


function setUpScenario(){
	$("#e1").css("left","0px");
	$("#e1").addClass("curSlide")
	checkForSettings($("#e1"))
	$('.scenarioSlide').each(function() {
		if(!$(this).hasClass("curSlide")){
			$(this).css("display", "none")
		}
	});
	resizeWindowCheck();

	$('.progress_indicator').each(function() {
		updateProgressBar($(this), "reset");
	});

	sn_progressIndicator();

	$('.sc_btn').each(function(i) {
		$(this).unbind("click touch").bind("click touch", {obj:$(this)}, sc_btnAction);
	});
}

function update_scenarioHolder_height(){
	$('.scenarioHolder').css("min-height","0px")
	var holderOffset = $(".scenarioHolder ").offset()
	var minHeight = ($('.curSlide').length == 0) ? $("#e1").height() :  $('.curSlide').height();
	var maxHeight = $(".centreContentContainer").height() - holderOffset.top;
	var newHeight = (maxHeight > minHeight) ? maxHeight : minHeight


	$('.scenarioHolder').css("min-height", newHeight)
}

function sc_btnAction(event){
	var btnObj = event.data.obj;
	var scObj = find_slide(btnObj, "scenarioSlide");

	if(btnObj.hasClass("sc_question")){
		if(btnObj.hasClass("sc_disabled") || btnObj.hasClass("sc_selected"))return false;
		btnObj.addClass("sc_selected")
		$(".curSlide").removeClass("curSlide")
		stopMedia(scObj)

		if(btnObj.data('indicator_1') != undefined){
			updateProgressBar($('.indicator_1'), parseInt(btnObj.data('indicator_1')));
		}

		//CHECK IF THE USER HAS FAILED THE SCENARIO
		var existingScore= parseInt($('.indicator_1').attr("curScore"));
		if(existingScore == 0){
			var targetObj = $("#efail");
		}else{
			//var targetObj = $("#"+scObj.find(".sc_selected").data('go').toString());
			var targetObj = $("#"+btnObj.data('go').toString());
		}

		//SET UP THE NEXT SLIDES INITIAL & END POSITIONS
		var targetPos = 0-(parseInt(scObj.css("height").split("px")[0]))
		var startPos = parseInt(scObj.css("height").split("px")[0])

		//CHECK IF IT IS THE FINAL SCREEN
		if(targetObj.attr('id') != undefined && targetObj.attr('id').toLowerCase()=="epass"){
			setUpResultsSlide(targetObj, existingScore);
		}
		update_sn_progressIndicator(targetObj)
		targetObj.addClass("curSlide")
		checkTargetAnimations(targetObj, "scAnimation")

		var slidetoScreen_tl = new TimelineMax();
		slidetoScreen_tl.set($(".centreContentContainer"), {scrollTop:0});
		slidetoScreen_tl.set(targetObj, {display:"block"});
		slidetoScreen_tl.addLabel("twoSlidesMove")
		slidetoScreen_tl.to(scObj, 1, {top:targetPos+"px", ease:Linear.easeNone, onComplete:resizeWindowCheck},"twoSlidesMove");
		slidetoScreen_tl.to(targetObj, 1, {top:"0px", startAt:{left:"0px", top:startPos+"px", zIndex:7}, ease:Linear.easeNone, onComplete:hideScenarioSlides, onCompleteParams:[targetObj]},"twoSlidesMove");

	}else if(btnObj.hasClass("sc_retry")){
		restartScenario(scObj);
	}else{
		$(".curSlide").removeClass("curSlide")
		stopMedia(scObj)

		var targetObj = $("#"+btnObj.data('go').toString());
		var targetPos = 0-(parseInt(scObj.css("height").split("px")[0])+100)
		var startPos = parseInt(scObj.css("height").split("px")[0])+100

		targetObj.addClass("curSlide")
		resizeWindowCheck();
		update_sn_progressIndicator(targetObj)
		checkTargetAnimations(targetObj, "scAnimation")

		if(btnObj.data('indicator_1') != undefined){
			updateProgressBar($('.indicator_1'), parseInt(btnObj.data('indicator_1')));
		}

		//CHECK IF IT IS THE FINAL SCREEN
		if(targetObj.attr('id') != undefined && targetObj.attr('id').toLowerCase()=="epass"){
			var existingScore= parseInt($('.indicator_1').attr("curScore"));
			setUpResultsSlide(targetObj, existingScore);
		}

		var slidetoScreen_tl = new TimelineMax();
		slidetoScreen_tl.set($(".centreContentContainer"), {scrollTop:0});
		slidetoScreen_tl.set(targetObj, {display:"block"});
		slidetoScreen_tl.addLabel("twoSlidesMove")
		slidetoScreen_tl.to(scObj, 1, {top:targetPos+"px", ease:Linear.easeNone},"twoSlidesMove");
		slidetoScreen_tl.to(targetObj, 1, {top:"0px", startAt:{left:"0px", top:startPos+"px", zIndex:7}, ease:Linear.easeNone, onComplete:hideScenarioSlides, onCompleteParams:[targetObj]},"twoSlidesMove");

	}
}


function updateProgressBar(obj, curScore){
	if(curScore == "reset"){
		curScore = obj.data('start1')
		var newScore = curScore;
	}else{
		var existingScore= parseInt(obj.attr("curScore"));
		var newScore = existingScore += curScore;
		newScore = (newScore>100) ? 100 : newScore;
		newScore = (newScore<0) ? 0 : newScore;
	}

	var progress_text = obj.find(".ptext")
	var progress_bar = obj.find(".pbar")
	TweenMax.to(progress_bar, 0.5, {width:newScore+"%", ease:Power4.easeIn});
	progress_text.html(newScore +"%");
	obj.attr("curScore",newScore);
}

function setUpResultsSlide(obj, userScore){
	var passingScore = parseInt(obj.data('passrate'));

	if(userScore >= passingScore){
		var txt = obj.find("p[feedback_type='passed']").html()
		obj.find(".sc_pass").each(function(i) {
			$(this).removeClass("invisible");
		});
		obj.find(".sc_fail").each(function(i) {
			$(this).addClass("invisible");
		});
	}else{
		var txt = obj.find("p[feedback_type='failed']").html()
		obj.find(".sc_pass").each(function(i) {
			$(this).addClass("invisible");
		});
		obj.find(".sc_fail").each(function(i) {
			$(this).removeClass("invisible");
		});
	}
	txt = txt.split("XX").join(userScore)
	obj.find('.finalText').html(txt)
}

function restartScenario(scObj){
	$(".curSlide").removeClass("curSlide")
	stopMedia(scObj)

	var targetObj = $("#e1");
	var targetPos = 0-(parseInt(scObj.css("height").split("px")[0])+100)
	var startPos = parseInt(scObj.css("height").split("px")[0])+100

	targetObj.addClass("curSlide")
	resizeWindowCheck();
	update_sn_progressIndicator(targetObj)
	checkTargetAnimations(targetObj, "scAnimation")

	TweenMax.to(scObj, 1, {top:targetPos+"px", ease:Linear.easeNone});
	TweenMax.to(targetObj, 1, {top:"0px", startAt:{left:"0px", top:startPos+"px", display:"block", zIndex:7}, ease:Linear.easeNone, onComplete:hideScenarioSlides, onCompleteParams:[targetObj]});

	$('.progress_indicator').each(function() {
		updateProgressBar($(this), "reset");
	});

	$('.sc_btn').each(function(i) {
		$(this).unbind('click touch').bind("click touch", {obj:$(this)}, sc_btnAction);
		$(this).css("cursor", "pointer");
		$(this).removeClass("sc_selected").removeClass("sc_disabled").removeClass("correct").removeClass("incorrect");
	});

	$('.sc_tick').each(function(i) {
		$(this).removeClass("sc_tick_correct").removeClass("sc_tick_incorrect")
	});
}

function sn_progressIndicator(){
	var totalWidth = 0;
	var firstDot = false
	$('.dotSlide').each(function(index) {
		if(firstDot == false){
			$('.sn_indicatorHolder').append("<div class='sn_dot orange' data-slideref='"+$(this).attr("id")+"'></div>")
			firstDot = true;
		}else{
			$('.sn_indicatorHolder').append("<div class='sn_dot' data-slideref='"+$(this).attr("id")+"'></div>")
		}
		var dot_width = parseInt($(".sn_dot").css('width')) + parseInt($(".sn_dot").css('margin-right'))+ parseInt($(".sn_dot").css('margin-left'))
		totalWidth+=dot_width;
	});
	$('.sn_indicatorHolder').css("width", totalWidth+"px")
}

function update_sn_progressIndicator(obj){
	if(obj.attr('id') == "efail"){
		$('.sn_indicatorHolder').css("visibility", "hidden")
	}else if(!obj.hasClass("dotSlide")){
		return false;
	}else{
		$('.sn_indicatorHolder').css("visibility", "visible")
	}

	$('.sn_dot').each(function(index) {
		$(this).removeClass("orange");
		if($(this).data('slideref')==obj.attr('id')){
			$(this).addClass("orange");
		}
	});
}

//+++++++++++++++++++++++++++++++++++++ hideScenarioSlides ++++++++++++++++++++++++++++++++++++++++++++++
// Hide the slides off screen when the animation finishes.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function hideScenarioSlides(obj){
	checkForSettings(obj)
	$('.scenarioSlide').each(function() {
		if(!$(this).hasClass("curSlide")){
			$(this).css("display", "none")
		}
	});
}



/********************************************************************************************/
/********************************** TIMELINE TEMPLATE ***************************************/
/********************************************************************************************/
var curTimeSlide = null;
var targets = null;
function setUpTimeline(){

	targets = $($('.timeContent')[0]).children(); //List of target slides
	var iMax = targets.length -1;
	var lastPos, diff,$oldTarget;
	var isSliding = false;
	var curSlideNum = 1;
	curTimeSlide = null;
	var tl = new TimelineMax({onUpdate:updateSlider}); //Main timeline

	//Setup the sequence of target animations
	for (var i = 0; i <= iMax; i++){
		var $newTarget = $(targets[i]);

		if(i==0) var isFirst = ' first'; else if(i==iMax) var isFirst = ' last'; else var isFirst = '';
		if(i%2 == 0) var arrow_class='arrow_box_slider'; else var arrow_class = 'arrow_box_slider_bt';

		//Create a grid on the timeline bar
		if (i<iMax)
			$('#slider').append('<div class="timeSliderGrid"><div class="' + arrow_class + isFirst + '"></div></div>');
		else if(i==iMax)
			$('.timeSliderGrid').last().append('<div class="' + arrow_class + isFirst + '"></div>');

		//Next animation target
		$newTarget.css('z-index', iMax - i);
		//Add animation to main timeline
		tl.add(getTargetAnimation($newTarget, $oldTarget), 'label' + i);
		$oldTarget = $newTarget;
	}

	//Percentage width on the grid
	$('.timeSliderGrid').css('width', 100/iMax+'%');

  //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	//Add in the labels to the timeline
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	for (var i = 0; i <= iMax; i++){
		var txt = $(targets[i]).data("label")
		var maxWidth = 100/(iMax+1)
		var topPos = (i%2 == 0) ? "-18px" : "25px"
		var indicatorPos = (i%2 == 0) ? "-22px" : "15px"

		if(i == 0){
			var leftPos = 0
		}else if(i==iMax){
			var leftPos = 100 -maxWidth;
		}else{
			var leftPos = ((100/iMax)*i)-(maxWidth/2);
		}

		$(targets[i]).attr("data-labelnum", (i+1))
		$('#timeSlider').append('<div class="time_label timeline_label_txt_1 labels'+(i+1)+'" labelNum="'+(i+1)+'" style="top:'+topPos+';left: '+leftPos+'%; width:'+maxWidth+'%;">'+txt+'<div class="timeline_viewed" style="top:'+indicatorPos+';"></div></div>')
	}

	$('.time_label').unbind("click touch").bind("click touch",function(event) {
		$('.time_label').removeClass('currentClick');
		$(this).addClass('currentClick');
		if(curTimeSlide != null) stopMedia(curTimeSlide);
		var labelNum = parseInt($(this).attr('labelNum'));
		if(curSlideNum == labelNum){
			if(curTimeSlide == null) curTimeSlide = $(targets[0]);
			initSlide(curTimeSlide)
		}else if(labelNum == 1){
			tl.tweenFromTo("label"+(labelNum+1), "label"+labelNum)
		}else if(curSlideNum < labelNum){
			tl.tweenFromTo("label"+(labelNum-1), "label"+labelNum)
		}else if(curSlideNum > labelNum){
			tl.tweenFromTo("label"+(labelNum+1), "label"+labelNum)
		}
		curSlideNum = labelNum;
	});

	//Add a final label
	tl.add('label' + (iMax + 1));
	tl.pause();

	//Setup a percentage slider
	$( "#slider" ).slider({
    min: 0,
    max: 100,
		step:.1,
		slide: function (event, ui){
			//Synch animation to slider
			tl.progress(ui.value/100).pause();
			//Determine the direction of movement
			diff = ui.value - lastPos;
			lastPos = ui.value;
			if(curTimeSlide != null)stopMedia(curTimeSlide)
			isSliding = true;
		},
		stop: function(event, ui){
			//Play to either the closest or next/previous stop point (depending on distance and direction)
			var label;
			if($(event.srcElement).hasClass('time_label')){
				var time_label = parseInt($(event.srcElement).attr('labelnum'))+1;
				label = 'label' + time_label;
			}else{
				lastPos = ui.value;
				var nearestLabel = curSlideNum = parseInt(Math.round(lastPos/(100/iMax)))+1;
				label = 'label' + nearestLabel;
			}
			isSliding = false;
			if (label != null){
				tl.tweenTo(label);
			}
		}
  });

	//SET UP THE SLIDESHOW NAVIGATION ELEMENTS
	$(".timeTarget").each(function(index) {

		var maxNum = $(".timeTarget").length;
		var curNum = index+1;

		var backNum = (curNum == 1 )? "null" : curNum-1
		var nextNum = (curNum == maxNum)? "null" : curNum+1

		$(this).attr("data-back", backNum)
		$(this).attr("data-next", nextNum)
		$(this).addClass("tl_hidden");
	});

	//Set the first target to visible and tween the wrapper instead
	if(!onPhoneCourse){
		TweenMax.set($(targets[0]), {autoAlpha: 1, scale:1, y: 0});
		TweenMax.fromTo($('.timeContent'), 1.5, {autoAlpha:0, scale:0.2, y: -150}, {autoAlpha: 1, scale:1, y: 0, onComplete:initSlide, onCompleteParams:[$(targets[0])]});
	}

	$("#wrapper").addClass("timeline")
	//MAKE THE FIRST ELEMENT VISIBLE
	initSlide($(".timeTarget:first"))

	//BACK ARROW NAVIGATION
	$(".tl_back").click(function(index) {
		if($(this).hasClass("disabled") || curTimeSlide.data('back')==null) return
		var targetObj = findTargetObj(curTimeSlide.data('back'));
		targetObj.addClass("tl_visble");
		var targetPos = parseInt(curTimeSlide.css("width").split("px")[0])
		var startPos = 0-parseInt(curTimeSlide.css("width").split("px")[0])-20
		var curObj = curTimeSlide;
		curSlideNum = parseInt(curTimeSlide.data('back'));

		var timeline_back_tl = new TimelineMax();
		timeline_back_tl.set(targetObj, {left:startPos+"px", top:"0px"});
		timeline_back_tl.addLabel("twoSlidesMove")
		timeline_back_tl.to(curObj, 0.5, {left:targetPos+"px", ease:Power4.easeIn, onComplete:resetSlide, onCompleteParams:[curObj]},"twoSlidesMove");
		timeline_back_tl.to(targetObj, 0.5, {left:"0px", ease:Power4.easeIn, onComplete:initSlide, onCompleteParams:[targetObj]}, "twoSlidesMove");
		timeline_back_tl.set(targetObj, {autoAlpha: 1, scale:1, y: 0});

		$("#slider").slider("value", (((curSlideNum-1)/iMax) * 100));
	});

	//NEXT ARROW NAVIGATION
	$(".tl_next").click(function(index) {
		if( $(this).hasClass("disabled") || curTimeSlide.data('next')==null) return

		var targetObj = findTargetObj(curTimeSlide.data('next'));
		targetObj.addClass("tl_visble");
		var targetPos = 0-parseInt(curTimeSlide.css("width").split("px")[0])
		var startPos = parseInt(curTimeSlide.css("width").split("px")[0])+20
		var curObj = curTimeSlide;
		curSlideNum = parseInt(curTimeSlide.data('next'));

		var timeline_next_tl = new TimelineMax();
		timeline_next_tl.set(targetObj, {left:startPos+"px", top:"0px"});
		timeline_next_tl.addLabel("twoSlidesMove")
		timeline_next_tl.to(curObj, 0.5, {left:targetPos+"px", ease:Power4.easeIn, onComplete:resetSlide, onCompleteParams:[curObj]},"twoSlidesMove");
		timeline_next_tl.to(targetObj, 0.5, {left:"0px", ease:Power4.easeIn, onComplete:initSlide, onCompleteParams:[targetObj]}, "twoSlidesMove");
		timeline_next_tl.set(targetObj, {autoAlpha: 1, scale:1, y: 0});

		$("#slider").slider("value", (((curSlideNum-1)/iMax) * 100));

	});

	function findTargetObj(num){
		var obj = null;
		$(".timeTarget").each(function(index) {
			if($(this).data('labelnum').toString() == num){
				obj = $(this)
			}
		});
		return obj
	}


	//Setup the back & forth animations of the old and new target
	function getTargetAnimation($newTarget, $oldTarget) {
		//Container timeline for old and new animations
    var targetTimeline = new TimelineMax();
		if ($oldTarget) {
			//Each animation requires its own timeline
			var t1 = new TimelineMax();
			var t2 = new TimelineMax();
	  	if(!isIE8){
		  	t1.fromTo($newTarget, 1.5, {autoAlpha:0, scale:0.2, y: -150, startAt:{left:"0px"}}, {autoAlpha: 1, scale:1, y: 0,  ease:Power1.easeOut, onReverseComplete:initSlide, onComplete:initSlide, onCompleteParams:[$newTarget], onReverseCompleteParams:[$oldTarget]});
				t2.to($oldTarget, 1.5, {autoAlpha:0, scale:1.5, y: 150, startAt:{left:"0px"}, ease:Power1.easeOut});
			}else{
		  	t1.to($newTarget, 0.1, {display: "block", scale:1, startAt:{scale:1}, onReverseComplete:initSlide, onComplete:initSlide, onCompleteParams:[$newTarget], onReverseCompleteParams:[$oldTarget]});
				t1.to($oldTarget, 0.1, {display: "none", scale:1, startAt:{scale:1}, ease:Power1.easeOut});
			}
			//Add both timelines as array to execute them at the same time
			targetTimeline.add([t1, t2]);
		}
		return targetTimeline;
  }
  //+++++++++++++++++++++++++++++++++++++++++ initSlide  ++++++++++++++++++++++++++++++++++++++++++++++++++
	// Call the function when the slide has stopped in place.
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  function initSlide(obj){
  	if(!isSliding){
  		if(curTimeSlide != null) stopMedia(curTimeSlide);
  		curTimeSlide = obj;
  		checkContainerSize();
  		if (curTimeSlide.attr("data-video") != undefined) {
  			curTimeSlide.css("z-index", 100);
	  		curTimeSlide.children().removeClass("invisible");
	  		curTimeSlide.children("img").hide();
	  		curTimeSlide.children("video").css("height", curTimeSlide.height());
  		}
	  	checkForSettings(obj);

	  	if($("#wrapper").hasClass("controlnav") && currentPage.progress!=2){
	  		if($(targets[0]).hasClass("controlnav")) $(targets[0]).removeClass("controlnav")
				obj.removeClass("controlnav")
				checkRestrictedNav();
			}
	  }

	  obj.removeClass("tl_hidden")

		$(".timeTarget").each(function(index) {
			$(this).removeClass("tl_visble");
		});
		obj.addClass("tl_visble")

		if(obj.data('back')==null){
			$(".tl_back").addClass("disabled");
		}else{
			$(".tl_back").removeClass("disabled");
		}

		if(obj.data('next')==null){
			$(".tl_next").addClass("disabled");
		}else{
			$(".tl_next").removeClass("disabled");
		}

		if(obj.find(".tl_crumb").length ==0){
			$(".timeTarget").each(function(index) {
				$(".tl_crumb:first").clone().appendTo($(this));
				$(this).find(".tl_crumb_right").html(getCrumbText($(this), "next"));
				$(this).find(".tl_crumb_left").html(getCrumbText($(this), "back"));
			});
		}
  }

  function getCrumbText(obj, target){
  	if(obj.data(target)==null){
  		return ""
  	}else{
  		var txt = "";
  		$(".timeTarget").each(function(index) {
				if(obj.data(target)==$(this).data("labelnum")){
					txt = (target=="next") ? " ___ " +$(this).data("label"): $(this).data("label")+" ___ "
				}
			});
  		return txt;
  	}
  }

  function resetSlide(obj){
  	obj.css("left", "0px");
  	obj.css("visibility", "hidden");
  	obj.addClass("tl_hidden")
  }

	//Synch slider to animation
	function updateSlider() {
		$("#slider").slider("value", tl.progress() * 100);
	}

	//Check if the slider is close to any of the notches (by a fraction of the distance)
	function checkDistance(){
		var fraction = (100/iMax)/6;
		for (var i = 0; i <=iMax; i++){
			var d = Math.abs(lastPos - (100/iMax * i));
			if (d < fraction) {
				return i+1;
			}
		}
		return -1;
	}

}



function checkContainerSize(){
	if(targets == null) return;
	$(".timeContainer").css("height", $(".timeContainer").css("min-height"));
	if(curTimeSlide == null) curTimeSlide = $(targets[0]);
	$(".timeContainer").css("height", (curTimeSlide.height()+20)+"px")
	setViewedIndicator(curTimeSlide)
}

function setViewedIndicator(){
	$(".time_label").each(function(index) {
		if($(this).attr("labelnum") == curTimeSlide.data("labelnum")){
			$(this).find(".timeline_viewed").addClass("visited")
		}
	});
}

/********************************************************************************************/
/********************************* ACCORDIAN TEMPLATES **************************************/
/********************************************************************************************/
function setUpAccordian(){
	$(".accordHeader").click(function(index) {
		stopAccordionMedia();
		if($(this).hasClass("currentSlide")){
			$('.accordBody').slideUp("fast");
			$('.currentSlide').removeClass("currentSlide");

		}else{
			$('.accordBody').slideUp("fast");
			$('.currentSlide').removeClass("currentSlide");
			$(this).addClass("currentSlide")
			$(this).parent().find(".accordBody").slideDown("slow");
			if($(this).hasClass("controlnav") && $(this).parent().data("video")!=undefined){
				//Do not check controlled navigation
			}else	if(!$(this).hasClass("accordVisited")){
				$(this).addClass("visited")
				launchControlledNavBtn($(this))
			}

			checkForSettings($(this).parent())
			if(navigator.userAgent.toLowerCase().indexOf('firefox')){
				$(this).parent().find(".accordBody").css("display", "flex")
			}
		}
	});
}

function stopAccordionMedia(){
	$(".accordHeader").each(function(index) {
		stopMedia($(this).parent());
	});
}

/********************************************************************************************/
/********************************** SLIDESHOW TEMPLATES *************************************/
/********************************************************************************************/
var curObj = null;
var disableNavBtns = false
var orgHeight = null;

function setUpSlideShow(){
	curObj = $("#e1");
	curObj.css("left","0px");
	orgHeight=null;
	setupDots();
	setUpSlide(curObj)
	updateSlideshowHeights();
	if(onPhoneCourse) repositionArrows()

	$(".scene_back").click(function(index) {
		closeOpenComponent();
		if(disableNavBtns || $(this).hasClass("disabled")) return
		disableNavBtns = true;

		var targetObj = $("#"+curObj.data('back').toString());
		var targetPos = parseInt(curObj.css("width").split("px")[0])
		var startPos = 0-parseInt(curObj.css("width").split("px")[0])

		TweenMax.to(curObj, 0.5, {left:targetPos+"px", ease:Power4.easeIn});
		TweenMax.to(targetObj, 0.5, {left:"0px", startAt:{left:startPos+"px", top:"0px"}, ease:Power4.easeIn, onComplete:setUpSlide, onCompleteParams:[targetObj]});
	});

	$(".scene_next").click(function(index) {
		closeOpenComponent();
		if(disableNavBtns || $(this).hasClass("disabled")) return
		disableNavBtns = true;

		var targetObj = $("#"+curObj.data('next').toString());
		var targetPos = 0-parseInt(curObj.css("width").split("px")[0])
		var startPos = parseInt(curObj.css("width").split("px")[0])

		TweenMax.to(curObj, 0.5, {left:targetPos+"px", ease:Power4.easeIn});
		TweenMax.to(targetObj, 0.5, {left:"0px", startAt:{left:startPos+"px", top:"0px"}, ease:Power4.easeIn, onComplete:setUpSlide, onCompleteParams:[targetObj]});
	});

	$(".scene_up").click(function(index) {
		if(disableNavBtns || $(this).hasClass("disabled")) return
		disableNavBtns = true;

		var targetObj = $("#"+curObj.data('back').toString());
		var targetPos = getHeight(curObj)
		var startPos = 0-getHeight(curObj)

		TweenMax.to(curObj, 0.5, {top:targetPos+"px", ease:Power4.easeIn});
		TweenMax.to(targetObj, 0.5, {top:"0px", startAt:{top:startPos+"px", left:"0px"}, ease:Power4.easeIn, onComplete:setUpSlide, onCompleteParams:[targetObj]});
	});

	$(".scene_down").click(function(index) {
		if(disableNavBtns || $(this).hasClass("disabled")) return
		disableNavBtns = true;

		var targetObj = $("#"+curObj.data('next').toString());
		var targetPos = 0-getHeight(curObj)
		var startPos = getHeight(curObj)

		TweenMax.to(curObj, 0.5, {top:targetPos+"px", ease:Power4.easeIn});
		TweenMax.to(targetObj, 0.5, {top:"0px", startAt:{top:startPos+"px", left:"0px"}, ease:Power4.easeIn, onComplete:setUpSlide, onCompleteParams:[targetObj]});
	});
}

function setupDots(){
	var totalWidth = 0;
	var firstDot = false
	$('.ss_slide').each(function(index) {
		if(firstDot == false){
			$('.slideBreadCrumb').append("<div class='ss_dot full' data-slideref='"+$(this).attr("id")+"'></div>")
			firstDot = true;
		}else{
			$('.slideBreadCrumb').append("<div class='ss_dot' data-slideref='"+$(this).attr("id")+"'></div>")
		}
		var dot_width = parseInt($(".ss_dot").css('width')) + parseInt($(".ss_dot").css('margin-right'))+ parseInt($(".ss_dot").css('margin-left'))
		totalWidth+=dot_width;

		$(this).unbind("click touch").bind("click touch", {dotObj: $(this)}, slideDotNav);
	});

	if($(".slideshowHolder").data("dotnav").toLowerCase()=="on"){
		$('.ss_dot').each(function(index) {
			$(this).addClass("dot_nav");
			$(this).unbind("click touch").bind("click touch", {dotObj: $(this)}, slideDotNav);
		});
	}


	$('.slideBreadCrumb').css("width", totalWidth+"px")
	$('.slideBreadCrumb').css("margin-left", "-"+(totalWidth/2)+"px")
}

function updateDots(ref){
	$('.ss_dot').each(function(index) {
		$(this).removeClass("full");
		if($(this).data('slideref')==ref){
			$(this).addClass("full");

			if($(".slideshowHolder").data("dotnav").toLowerCase()=="on"){
				$(this).addClass("visited_dot");
			}


		}
	});
}

function slideDotNav(event){
	  closeOpenComponent();
	var obj = event.data.dotObj;

	var targetObj = $("#"+obj.data("slideref").toString());
	var targetPos = 0-parseInt(curObj.css("width").split("px")[0])
	var startPos = parseInt(curObj.css("width").split("px")[0])

	TweenMax.to(curObj, 0.5, {left:targetPos+"px", ease:Power4.easeIn});
	TweenMax.to(targetObj, 0.5, {left:"0px", startAt:{left:startPos+"px", top:"0px"}, ease:Power4.easeIn, onComplete:setUpSlide, onCompleteParams:[targetObj]});

}

function setUpSlide(obj){
	curObj = obj;
	checkForSettings(obj);
	$(".curSlide").removeClass("curSlide")
	curObj.addClass("curSlide")
	if(obj.data('back')==null){
		$(".scene_back").addClass("disabled")
		$(".scene_up").addClass("disabled")
	}else{
		$(".scene_back").removeClass("disabled")
		$(".scene_up").removeClass("disabled")
	}

	if(obj.data('next')==null){
		$(".scene_next").addClass("disabled")
		$(".scene_down").addClass("disabled")
	}else{
		$(".scene_next").removeClass("disabled")
		$(".scene_down").removeClass("disabled")
	}

	var curPage = obj.attr("id").slice(1,2);
	var totalPages = $(".ss_slide").length;
	updateDots(obj.attr("id"))
	//$('.slideBreadCrumb').html(txt_label_page+curPage+txt_label_of+totalPages)

	setTimeout(function(){updateSlideshowHeights()}, 1000);
	updateSlideshowHeights();
	disableNavBtns = false;

	if($("#wrapper").hasClass("controlnav") && currentPage.progress!=2){
		obj.removeClass("controlnav")
		checkRestrictedNav();
	}
}

function updateSlideshowHeights(){
	if(curObj == null) return

	$('.ss_slide').each(function() {
		if(!$(this).hasClass("curSlide")){
			$(this).css("left", "2000px")
		}
	});

	curObj.find('.ss_text').css("min-height", "0px")
	curObj.find('.ss_text').css("min-height", ($(".ss_img").height()-35)+"px")
	$('.slideshowHolder').css("min-height", curObj.height()+"px")
}


function getHeight(obj){
	var slideHeight = null;
	$('.ss_slide').each(function() {
		if($(this).hasClass("curSlide")){
			slideHeight = $(this).height();
		}
	});
	return slideHeight
}

function repositionArrows(){
	$(".arrowHolder").appendTo("#wrapper");
	$(".slideBreadCrumb").appendTo(".phone_breadcrumb");
}

/********************************************************************************************/
/***************************** CONTENT NAVIGATION TEMPLATES *********************************/
/********************************************************************************************/
function setUpContentNav(){
	$("#e1").css("left","0px");

	$(".cn_btn").each(function() {
		if($(this).data('bg') != undefined){
			$(this).css("background-image", "url("+$(this).data('bg')+")")
		}
	});

	$(".cnPanel").each(function() {
		if($(this).data('bg') != undefined){
			$(this).css("background-image", "url("+$(this).data('bg')+")")
		}
	});

	$(".cn_btn").click(function(index) {
		var cnObj = find_slide($(this), "cnSlide");
		$(".curSlide").removeClass("curSlide")
		stopMedia(cnObj)


		var targetObj = $("#"+$(this).data('go').toString());
		var targetPos = parseInt(cnObj.css("width").split("px")[0])
		var startPos = 0-parseInt(cnObj.css("width").split("px")[0])

		//SEE IF THERE ARE ANY QUESTION SETTING
		if(targetObj.data('question') != undefined && (targetObj.data('question').toLowerCase()=="samc" ||targetObj.data('question').toLowerCase()=="mamc")){
			setUpQuestion(targetObj);
		}

		if($(this).data('subscreen') != undefined && $(this).data('subscreen') == "on"){
			checkSubScreen($(this), targetObj)
		}else if(targetObj.data('question') != undefined && (targetObj.data('question').toLowerCase()=="samc" ||targetObj.data('question').toLowerCase()=="mamc")){
			checkQuestionScreen($(this), targetObj)
		}else if($(this).children('.cn_visited').length ==0 && !$(this).hasClass('cn_back')){
			$(this).prepend("<div class=\"cn_visited\"></div>")
			$(this).removeClass("controlnav")
		}

		checkForSettings(targetObj);
		checkTargetForSubScreens(targetObj)

		targetObj.addClass("curSlide")
		checkTargetAnimations(targetObj, "cnAnimation")

		TweenMax.to(cnObj, 0.5, {left:startPos+"px", startAt:{zIndex:6}, ease:Power1.easeIn});
		TweenMax.to(targetObj, 0.5, {left:"0px", startAt:{left:startPos+"px", top:"0px", zIndex:7}, ease:Power1.easeIn, onComplete:hideSlides, onCompleteParams:[targetObj]});

		if($("#wrapper").hasClass("controlnav") && currentPage.progress!=2){
			checkTargetForSubScreens($("#e1")) //Check the home screen for controlled navigation - dont want to have to navigate all the way back to check.
			checkRestrictedNav();
		}
	});
}

//+++++++++++++++++++++++++++++++++++++++++ hideSlides ++++++++++++++++++++++++++++++++++++++++++++++++++
// hide the slides off screen when the animation finishes.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function hideSlides(obj){
	checkForSettings(obj)
	$('.cnSlide').each(function() {
		if(!$(this).hasClass("curSlide")){
			$(this).css("left", "2000px")
		}
	});
}

//+++++++++++++++++++++++++++++++++++++++++ find_slide ++++++++++++++++++++++++++++++++++++++++++++++++++
// Recursive function to find the parent slide no matter how many levels down it is.
// ie with a holder or not
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function find_slide(obj, target){
	if(obj.hasClass(target)){
		return obj
	}else{
		return find_slide(obj.parent(), target)
	}
}

//++++++++++++++++++++++++++++++++++++ checkTargetAnimations ++++++++++++++++++++++++++++++++++++++++++++
// Check if a greensock animation needs to run - search for the target flag (cnAnimation) and run the
// animation if that is found.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function checkTargetAnimations(obj, target){
	obj.find('.'+target).each(function() {
		run_gs_animation($(this));
	});
}

//++++++++++++++++++++++++++++++++++++ checkSubScreen +++++++++++++++++++++++++++++++++++++++++++++++++++
// If a progress indicator on a button is dependent on all the buttons of a subscreen being visited then
// check those buttons before setting the indicator.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function checkSubScreen(btn, obj){
	var totalButtons = 0
	var visitedButtons = 0;
	obj.find('.cn_btn:not(.cn_back)').each(function(i) {
		totalButtons++
		visitedButtons = ($(this).children('.cn_visited').length>0 || $(this).children('.mq_correct').length>0 || $(this).children('.mq_incorrect').length>0) ? visitedButtons+1 : visitedButtons
	});

	if(totalButtons==visitedButtons && btn.children('.cn_visited').length ==0 && !btn.hasClass('cn_back')){
		btn.append("<div class=\"cn_visited\"></div>")
		btn.removeClass("controlnav")
	}
}

//+++++++++++++++++++++++++++++++ checkTargetForSubScreens ++++++++++++++++++++++++++++++++++++++++++++++
// Check the buttons on the slide we are navigating to, to check if the progress indicator on any of
// them is dependant on all the buttons in the subscreen being visited.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function checkTargetForSubScreens(obj){
	obj.find('.cn_btn').each(function(i) {
		var targetObj = $("#"+$(this).data('go').toString());
		if($(this).data('subscreen') != undefined && $(this).data('subscreen') == "on"){
			checkSubScreen($(this), targetObj)
		}else if(targetObj.data('question') != undefined && (targetObj.data('question').toLowerCase()=="samc" ||targetObj.data('question').toLowerCase()=="mamc")){
			var targetScreenObj = $("#"+$(this).data('go').toString());
			checkQuestionScreen($(this), targetScreenObj)
		}
	});
}
//++++++++++++++++++++++++++++++++++++ checkForSettings ++++++++++++++++++++++++++++++++++++++++++++++++++++
// Check if there is media on the target slide and play it as required.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function checkForSettings(obj){
	//SEE IF THERE IS AUDIO OR VIDEO TO PLAY
	if(obj.data('video') != undefined && obj.data('video').toLowerCase() != "vimeo"){
		if(audioAsked==1) {
			//No need to reload the video if its already there
			if(obj.find("#cnVideo").attr("src") == undefined || obj.find("#cnVideo").attr("src").indexOf(obj.data('video')) == -1){
            playVideo(obj.data('video'), obj.find("#cnVideo"));
			}else{
				obj.find('video').get(0).play();
			}
			//$(".audioBtn").addClass("disabled");
		}else if(audioAsked!=1){
			$("#mediaLock").removeClass("invisible");
			obj.find('video').css("position","absolute")
			obj.find('video').css("top","-1500px")
		}
	}else if(obj.data('audio') != undefined && audioAsked==1){
		loadAudio(obj.data('audio'));
		if(obj.data('question') != undefined && (obj.data('question').toLowerCase()=="samc" ||obj.data('question').toLowerCase()=="mamc")){
			if(obj.hasClass("qAudio")){
				stopMedia(obj)
			}else{
				obj.addClass("qAudio")
			}
		}
	}else if(obj.find('.vimeoVideo').length > 0 && audioAsked==1) {
		$f(obj.find('.vimeoVideo')[0]).api('play');
	}

	//CHANGE BACKGROUND
	if(obj.data('bgimage') != undefined){
		$("#centreContent").css("background-image", "url("+obj.data('bgimage')+")")
	}
}

//++++++++++++++++++++++++++++++++++++ stopMedia ++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Turn off the media on the current slide if it is being closed.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function stopMedia(obj){
	if((obj.find('.vimeoVideo')[0]!=undefined) || (obj.data('video') == "vimeo")){
		$f(obj.find('.vimeoVideo')[0]).api('pause');
	}else	if(obj.data('video') != undefined){
		for(var i=0; i<vidObjArray.length; i++){
			vidObjArray[i].pause();
		}
	}else if(obj.data('audio') != undefined){
		loadAudio("");
	}
	$(".audioBtn").removeClass("disabled");
}



/********************************************************************************************/
/******************************* MULTI QUESTION TEMPLATE ************************************/
/********************************************************************************************/
function setUpMultiQuestion(){
	updateMultiquestionHeight();
	//$("#qFeedback").css("opacity", 0);
	$("#e1").css("left","0px");
	$("#e1").css("visibility","visible");
	$("#e1").addClass("curSlide")

	if($("#wrapper").hasClass("controlnav") && currentPage.progress!=2){
		checkRestrictedNav();
	}


	$(".cnPanel").each(function() {
		if($(this).data('bg') != undefined){
			$(this).css("background-image", "url("+$(this).data('bg')+")")
		}
	});

	$(".cn_btn").click(function(index) {
		var cnObj = find_slide($(this), "cnSlide");
		$(".curSlide").removeClass("curSlide")
		stopMedia(cnObj)

		var targetObj = $("#"+$(this).data('go').toString());
		var startPos = 0-parseInt(cnObj.css("height").split("px")[0])

		//Check if the multiQuestion has been answered and we can unlock the next button
		if($("#wrapper").hasClass("controlnav") && ($(this).hasClass("cn_back")|| $(this).hasClass("questionbank"))){
			checkRestrictedNav();
		}

		//update the height of multiquestion screen
		mqCurrentSlide = targetObj;

		//SEE IF THERE ARE ANY QUESTION SETTING
		if(targetObj.data('question') != undefined && (targetObj.data('question').toLowerCase()=="samc" ||targetObj.data('question').toLowerCase()=="mamc")){
			setUpQuestion(targetObj);
		}

		targetObj.addClass("curSlide")
		checkTargetAnimations(targetObj, "cnAnimation")
		close_feedback_overlay(true);

		var showQuestion_tl = new TimelineMax();
		showQuestion_tl.set($(".centreContentContainer"), {scrollTop:0});
		showQuestion_tl.addLabel("twoSlidesMove")
		showQuestion_tl.to(cnObj, 0.5, {left:"0px",top:(startPos-cnObj.height()+20)+"px", startAt:{zIndex:6}, ease:Linear.easeNone, onComplete:updateMultiquestionHeight},"twoSlidesMove");
		showQuestion_tl.to(targetObj, 0.5, {left:"0px", top:"0px", startAt:{left:"0px", top:startPos+"px", zIndex:7}, ease:Linear.easeNone, onComplete:hideSlides, onCompleteParams:[targetObj]},"twoSlidesMove");
	});
}

//update the height of multiquestion screen
function updateMultiquestionHeight() {
	var holderOffset = $(".mq .contentNavHolder").offset()
	var minHeight = (mqCurrentSlide == undefined) ? $("#e1 > .subHolder").height() : mqCurrentSlide.find(".subHolder").height();
	var maxHeight = $(".centreContentContainer").height() - holderOffset.top;
	var newHeight = (maxHeight > minHeight) ? maxHeight : minHeight
	$(".mq .contentNavHolder").css("min-height",newHeight);
}

//++++++++++++++++++++++++++++++++++++ setUpQuestion ++++++++++++++++++++++++++++++++++++++++++++++++++++
// Set up a slide to be a question - setup clicks, randomisation, scoring etc
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function setUpQuestion(obj){

	if(obj.hasClass("init")){
		stopMedia(obj)
		if(!obj.hasClass("qCorrect") && !obj.hasClass("qIncorrect")){
			obj.find(".tappedOpt").each(function(i) {
				$(this).removeClass("tappedOpt");
			});
			obj.find("#mcSubmit").addClass("disabled");
		}
		return;
	}else{
		obj.addClass("init");
	}
	obj.find("#mcSubmit").unbind("click touch").bind("click touch", {qObj: obj}, mq_evalAnswer);
	obj.find("#mcSubmit").addClass("disabled");

	if(obj.data('question').toLowerCase() == "samc" || obj.data('question').toLowerCase() == "mamc"){
		//Assign the number of the question so we can find it after the randomisation
		obj.find('.qOpt').each(function(i) {
			$(this).attr('q_id', i);
		});
		//randomise the options
		if(obj.data('random').toLowerCase() == "on"){
			var $container = obj.find(".options_container");
			$container.html(shuffle($container.children().get()));
		}
		//Assign the functionality after they have been randomised as the options essentially get rebuilt during the randomisation.
		obj.find('.qOpt').each(function(i) {
			$(this).unbind("click touch").bind("click touch", {obj: $(this)}, multi_mc_func);
		});

		if(answerindicator == true){
			var answer_style = applyColor(obj.data('qstyle')).split("");

			obj.find('.qOpt').each(function(i) {
				if(answer_style[parseInt($(this).attr('q_id'))] == 1){
					$(this).addClass("mc_correct");
				}else if(answer_style[parseInt($(this).attr('q_id'))] == 0){
					$(this).addClass("mc_incorrect");
				}
			});
		}

	}
}

//++++++++++++++++++++++++++++++++++++ multi_mc_func ++++++++++++++++++++++++++++++++++++++++++++++++++++
// Functionality for when a question option is clicked.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function multi_mc_func(event){
	var curOption = event.data.obj;
	var cnObj = find_slide($(this), "cnSlide");

	if(cnObj.data('question') != undefined && cnObj.data('question').toLowerCase() == "samc" ){
		if(curOption.hasClass("tappedOpt")){
			curOption.removeClass("tappedOpt");
		}else{
			$(".tappedOpt").removeClass("tappedOpt");
			curOption.addClass("tappedOpt");
		}
	}else if(cnObj.data('question') != undefined && cnObj.data('question').toLowerCase() == "mamc" ){
		curOption.toggleClass("tappedOpt");
	}

	if(cnObj.find(".tappedOpt").length>0){
		cnObj.find("#mcSubmit").removeClass("disabled");
	}else{
		cnObj.find("#mcSubmit").addClass("disabled");
	}

	event.stopPropagation();
	event.preventDefault();
}

//++++++++++++++++++++++++ mq_evalAnswer() ++++++++++++++++++++++++++++++++++++
// Evaluate the users answers to see if they answered the question correctly
// and display the appropiate feedback
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function mq_evalAnswer(event){
	var obj = event.data.qObj;
	if(obj.find("#mcSubmit").hasClass("disabled"))return;
	obj.find("#mcSubmit").addClass("disabled");

	mq_disableOptions(obj)
	var answer_style = applyColor(obj.data('qstyle')).split("");
	var question_type = obj.data('question').toLowerCase();
	var numCorrect = 0;
	var numIncorrect = 0;
	var numCorrectOpts= 0;
	var maxAttempts= (obj.data('attempts') != undefined) ? parseInt(obj.data('attempts')) : islQuestions.attempts
	var curAttempts = (obj.attr("attempts")== undefined) ? 1 : parseInt(obj.attr("attempts"))+1;
	obj.data("attempts", curAttempts)

	//FIND NUMBER OF CORRECT ANSWERS
	for(var i=0;i<answer_style.length; i++){
		numCorrectOpts += parseInt(answer_style[i])
	}

	if(question_type=="samc" || question_type=="mamc"){
		obj.find(".qOpt").each(function(index) {
			if(answer_style[parseInt($(this).attr('q_id'))] == 1 && $(this).hasClass('tappedOpt')){
				numCorrect++;
			}else if(answer_style[parseInt($(this).attr('q_id'))] != 1 && $(this).hasClass('tappedOpt')){
				numIncorrect++;
			}
		});
	}

	cn_showFeedback(numCorrect, numIncorrect, numCorrectOpts, curAttempts, maxAttempts, obj);

	event.stopPropagation();
	event.preventDefault();
}

//++++++++++++++++++++++++ resetQuestion() ++++++++++++++++++++++++++++++++++++
// Reset the question so that the user can attempt the questions again
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function resetQuestion(obj){
	mq_enableOptions(obj);
	obj.find("#qFeedback").hide();


	var retryBtnObj =  obj.find("#mcSubmit")
	retryBtnObj.removeClass("retryBtn");
	retryBtnObj.addClass("disabled");
	retryBtnObj.html(txt_label_submit);
	retryBtnObj.unbind("click touch").bind("click touch", {qObj: obj}, mq_evalAnswer);

}

//+++++++++++++++++++++ mq_disableOptions() +++++++++++++++++++++++++++++++++++
// Disable the question options while the feedback is on screen
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function mq_disableOptions(obj){
	var question_type = obj.data('question').toLowerCase();
	if(question_type=="samc" || question_type=="mamc"){
		obj.find(".qOpt").each(function(index) {
			$(this).off('click');
			$(this).off('mouseover');
			$(this).css("cursor", "default");
		});
	}
}
//+++++++++++++++++++++ mq_enableOptions() ++++++++++++++++++++++++++++++++++++
// Enable all the question options again
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function mq_enableOptions(qObj){
	var question_type = qObj.data('question').toLowerCase();
	if(question_type=="samc" || question_type=="mamc"){
		qObj.find(".qOpt").each(function(index) {
			$(this).unbind("click touch").bind("click touch", {obj: $(this)}, multi_mc_func);
			$(this).removeClass("tappedOpt");
			$(this).css("cursor", "pointer");
		});
	}
}

//+++++++++++++++++++++ showFeedback() ++++++++++++++++++++++++++++++++++++++++
// Show the feedback based on the number of correct|incorrect responses.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//function cn_showFeedback(numCorrect, numIncorrect, numCorrectOpts, curAttempts, maxAttempts, obj){
function cn_showFeedback(correct, incorrect, correctOpts, curAttempts, maxAttempts, obj){
	stopMedia(obj)
	$("#guiFeedback").find(".guiRetryBtn").addClass("invisible");
	onPhoneCourse = ($('.phonePanel').css("display").toLowerCase()=="table") ? true : false

	var feedbackTarget = (onPhoneCourse) ? $("#guiFeedback") : obj.find("#qFeedback")
	var feedbackTextObj = feedbackTarget.find("#feedbackTxt");
	$(feedbackTarget).removeClass("correct").removeClass("partial").removeClass("incorrect");
	$("#closeMobileFeedback_btn").removeClass("invisible");
	$(".fb_img_1").attr("src", $(".fb_img_1").attr("incorrect_img"))

	if(incorrect == 0 && correct==correctOpts){
		$(".fb_img_1").attr("src", $(".fb_img_1").attr("correct_img"))
		feedbackTarget.addClass("correct");

		feedbackTextObj.empty();
		feedbackTextObj.html(obj.find("p[feedback_type='correct']").html());

		setQBBtn(obj);
		$(".pFeedback").removeClass("disabled");
  	obj.addClass("qCorrect"); //The question slide has been completed
		mc_showTicks(obj);
	}else if((curAttempts < maxAttempts) && correct>0){
		feedbackTarget.addClass("incorrect");
		feedbackTextObj.empty().html(obj.find("p[feedback_type='retry']").html());

		setMQRetryBtn(obj);
		$("#closeMobileFeedback_btn").addClass("invisible");
		$(".pFeedback").addClass("disabled");
	}else if((curAttempts < maxAttempts) && (incorrect>0 || correct>0) ){
		feedbackTarget.addClass("incorrect");
		feedbackTextObj.empty().html(obj.find("p[feedback_type='retry']").html());

		setMQRetryBtn(obj);
		$("#closeMobileFeedback_btn").addClass("invisible");
		$(".pFeedback").addClass("disabled");

	}else if((curAttempts == maxAttempts) && correct>0 ){
		feedbackTarget.addClass("incorrect");
		feedbackTextObj.empty().html(obj.find("p[feedback_type='partically']").html());

		setQBBtn(obj);
  	obj.addClass("qIncorrect"); //The question slide has been completed
		mc_showTicks(obj);
		$(".pFeedback").removeClass("disabled");

	}else if((curAttempts == maxAttempts) && incorrect>0 ){feedbackTarget.addClass("incorrect");
		feedbackTextObj.empty().html(obj.find("p[feedback_type='incorrect']").html());

		setQBBtn(obj);
  	obj.addClass("qIncorrect"); //The question slide has been completed
		mc_showTicks(obj);
		$(".pFeedback").removeClass("disabled");
	}

	if(onPhoneCourse){
		open_feedback_overlay(false)
	} else {
		feedbackTarget.css("visibility", "visible" )
		TweenMax.from(feedbackTarget, 0.2, {y:-30, startAt:{display:"block"}, ease:Power1.easeIn});
		resizeWindowCheck();
	}
}

//++++++++++++++++++++++++ setMQRetryBtn() ++++++++++++++++++++++++++++++++++++
// Set up the retry button in the question.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function setMQRetryBtn(obj){
	if(onPhoneCourse){
		$("#guiFeedback").find(".guiRetryBtn").removeClass("invisible");
		$("#guiFeedback").find(".guiRetryBtn").html(txt_label_retry);
		$("#guiFeedback").find(".guiRetryBtn").removeClass("questionbank");
		$("#guiFeedback").find(".guiRetryBtn").unbind("click touch").bind("click touch",function(event){
			resetQuestion(obj)
			close_feedback_overlay(true);
			event.stopPropagation();
			event.preventDefault();
		});
	}else{
		var retryBtnObj =  obj.find("#mcSubmit")
		retryBtnObj.addClass("retryBtn");
		retryBtnObj.removeClass("disabled");
		retryBtnObj.html(txt_label_retry);
		retryBtnObj.unbind("click touch").bind("click touch",function(event) {
			resetQuestion(obj)
			event.stopPropagation();
			event.preventDefault();
		});
	}
}

//++++++++++++++++++++++++ setQBBtn() ++++++++++++++++++++++++++++++++++++
// Set up the question bank button in the mobile feedback.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function setQBBtn(obj){
	if(onPhoneCourse){
		$("#guiFeedback").find(".guiRetryBtn").removeClass("invisible");
		$("#guiFeedback").find(".guiRetryBtn").html(txt_label_qb);
		$("#guiFeedback").find(".guiRetryBtn").addClass("questionbank")
		$("#guiFeedback").find(".guiRetryBtn").unbind("click touch").bind("click touch",function(event){
			obj.find("#mcBack").click();
			close_feedback_overlay(true);
			event.stopPropagation();
			event.preventDefault();
		});
	}
}

//++++++++++++++++++++++ mc_showTicks ++++++++++++++++++++++++++++++++++++++++
// Show the correct|incorrect tick indicators on each option
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function mc_showTicks(obj) {
	var question_type = obj.data('question').toLowerCase();
	var answer_style = applyColor(obj.data('qstyle')).split("");

	if(question_type=="samc" || question_type=="mamc"){
		obj.find(".qOpt").each(function(index) {
			$(this).prepend("<div class='overhang mq_tick'></div>")
			if(answer_style[parseInt($(this).attr('q_id'))] == 1){
				$(this).addClass("correctOption");
			}else if(answer_style[parseInt($(this).attr('q_id'))] == 0){
				$(this).addClass("incorrectOption");
			}
		})
	}
  if($("#wrapper").data('screen_type')!= undefined && $("#wrapper").data('screen_type')== "multi_question"){
  	checkTargetForSubScreens($("#e1"));
	  checkQuizComplete();
	}
  if ($("#wrapper").attr("mq_submit") != "toggleOff") enableFeedbackToggle(obj);
}

//++++++++++++++++++++++++++++++++++++ checkQuestionScreen ++++++++++++++++++++++++++++++++++++++++++++++
// If a progress indicator on a button is dependent on all the buttons of a subscreen being visited then
// check those buttons before setting the indicator.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function checkQuestionScreen(btn, obj){
	if(obj.hasClass("qCorrect") && btn.children('.mq_correct').length ==0){
		btn.append("<div class=\"mq_correct\"></div>")
		btn.removeClass("controlnav")
		btn.addClass("mqBtn_correct")
	}else if(obj.hasClass("qIncorrect") && btn.children('.mq_incorrect').length ==0){
		btn.append("<div class=\"mq_incorrect\"></div>")
		btn.removeClass("controlnav")
		btn.addClass("mqBtn_incorrect")
	}
}

//++++++++++++++++++++++++++++++++++++ checkQuizComplete ++++++++++++++++++++++++++++++++++++++++++++++++
// Check if the user has completed all the questions in the multi question template and calculate the
// result and disply the appropiate feedback
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function checkQuizComplete(){
	var homeScreen = $('.mq_home')
	var numQuestions = 0;
	var numCorrect = 0;
	var numIncorrect = 0;

	$('.mq_question').each(function() {
		numQuestions++
		if($(this).hasClass("qCorrect")){
			numCorrect++
		}else if($(this).hasClass("qIncorrect")){
			numIncorrect++
		}
	});

	if((numCorrect+numIncorrect) == numQuestions){
		$("#wrapper").addClass("mq_complete");
		var quizPercentage = parseInt(numCorrect/numQuestions*100)
		var passRate = parseInt(homeScreen.data('passrate'))
		homeScreen.attr("quizPercentage", quizPercentage)
		if(quizPercentage >= passRate){
			homeScreen.find(".mq_pass").removeClass("invisible");
			homeScreen.find(".mq_pass").html(homeScreen.find(".mq_pass").html().split("XX").join(quizPercentage))
			homeScreen.find(".mq_pass #printcert").unbind("click touch").bind("click touch", function(event) {
			  printCert();
				event.stopPropagation();
				event.preventDefault();
			});
			$(".contentNavHolder").removeClass("controlnav");
		}else{
			homeScreen.find(".mq_fail").removeClass("invisible");
			homeScreen.find(".mq_fail").html(homeScreen.find(".mq_fail").html().split("XX").join(quizPercentage))
			homeScreen.find(".mq_fail #retryQuiz").unbind("click touch").bind("click touch", function(event) {
				retry_mqQuiz();
				event.stopPropagation();
				event.preventDefault();
			});
		}
	}
}

//++++++++++++++++++++++++++++++++++++ enableFeedbackToggle +++++++++++++++++++++++++++++++++++++++++++++
// Change the submit button to act as a toggle button between the feedback and the question as the
// feedback overlays the question text.
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function enableFeedbackToggle(obj){
	var btn = obj.find("#mcSubmit");
	btn.removeClass("disabled")
	btn.html(txt_label_togglefboff)
	btn.unbind("click touch").bind("click touch", {qObj: obj, fb_btn: btn}, tooggleFb);
}

function tooggleFb(event){
	var feedbackObj = event.data.qObj.find("#qFeedback")
	if(feedbackObj.css("top")=="-200px"){
		TweenMax.to(feedbackObj, 0.5, {top:"0px", ease:Power1.easeIn, onComplete:togglefb_btn, onCompleteParams:[event.data.fb_btn, txt_label_togglefboff]});
	}else{
		TweenMax.to(feedbackObj, 0.5, {top:"-200px", ease:Power1.easeIn, onComplete:togglefb_btn, onCompleteParams:[event.data.fb_btn, txt_label_togglefbon]});
	}
}

//++++++++++++++++++++++++++++++++++++ togglefb_btn ++++++++++++++++++++++++++++++++++++++++++++++++
// Change the text on the button when the feedback has moved on|off screen
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function togglefb_btn(btn, txt){
	btn.html(txt);
}

//++++++++++++++++++++++++++++++++++++ retry_mqQuiz ++++++++++++++++++++++++++++++++++++++++++++++++
// If the user is going to retry the quiz then reset all the settings back to their default states.
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function retry_mqQuiz(){
	$("#wrapper").removeClass("mq_complete");
	$(".correctOption ").removeClass("correctOption ")
	$(".incorrectOption ").removeClass("incorrectOption ")
	$(".qCorrect ").removeClass("qCorrect ")
	$(".qIncorrect ").removeClass("qIncorrect ")


	$(".mq_btn").removeClass("mqBtn_correct").removeClass("mqBtn_incorrect")
	$(".mq_correct").remove();
	$(".mq_incorrect").remove();
	$(".overhang").remove();

	$('.mq_question').each(function() {
		$(this).attr("attempts", 0)
		$(this).find("#qFeedback").css("visibility","hidden")
		mq_enableOptions($(this))

		var btn = $(this).find("#mcSubmit");
		btn.addClass("disabled")
		btn.html(txt_label_submit)
		btn.unbind("click touch").bind("click touch", {qObj: $(this)}, mq_evalAnswer);
	});

	var targetObj = $('.mq_home').find(".mq_fail")

	//TweenMax.to(targetObj, 0.5, {x:"-300px", ease:Power1.easeIn, onComplete:hideFinalFeedback, onCompleteParams:[targetObj]});

	var retryQuiz_tl = new TimelineMax();
	retryQuiz_tl.to(targetObj, 0.5, {x:"-300px", ease:Power1.easeIn, onComplete:hideFinalFeedback, onCompleteParams:[targetObj]});
	retryQuiz_tl.to($(".centreContentContainer"), 0.5, {scrollTop:0, ease:Linear.easeNone, onComplete:resizeWindowCheck});
}

//++++++++++++++++++++++++++++++++++++ hideFinalFeedback +++++++++++++++++++++++++++++++++++++++++++
// When the final feedback panel has slid off screen then reset all the parameters and positions
// back to their defaults.
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function hideFinalFeedback(panel){
	$('.mq_home').find(".mq_fail").addClass("invisible")
	var quizScore = $('.mq_home').attr('quizPercentage')
	$('.mq_home').find(".mq_fail").html($('.mq_home').find(".mq_fail").html().split(quizScore+"%").join("XX%")) //reset the replace text in case the user fails a second time

	TweenMax.to(panel, 0.1, {x:"0px", opacity:1, ease:Power1.easeIn}); //reset the panel back to its start position
}

/********************************************************************************************/
/**************************** POPUP CONVERSATION TEMPLATE ***********************************/
/********************************************************************************************/

var curConversation = null;

//++++++++++++++++++++++++++++++++++++ popupConversation +++++++++++++++++++++++++++++++++++++++++++
// Called when the conversation button is pressed.  Hide any open conversations and show the one
// that the user selected.
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function popupConversation(obj) {
	curConversation = $("#"+obj.data("target"));

	$(".cb_converHolder").css("display", "none");
	$(".conversationOpen").removeClass("conversationOpen");

	initConversation(curConversation)

	$("#wrapper").find(".converHoldAll").each(function(index) {
		$(this).removeClass("invisible");
		$(this).css("display", "none");
	});

	$(".selected").removeClass("selected");
	obj.addClass("selected");

	$("#wrapper").find(".conversationBtn").each(function(index) {
		$(this).addClass("conversationOpen");
	});

	if(onPhoneCourse){
		var openConversation = new TimelineMax();
		openConversation.set($(".cb_converHolder"), {display:"block"});
		openConversation.to(curConversation, 0.6, {left:"0px", opacity:1, startAt:{left:"100px", opacity:0, display:"block"}, ease:Back.easeOut, onComplete:upDateConversationHeight});
	}else{
		$(".cb_converHolder").css("display", "block");
		curConversation.css("display", "block");
		TweenMax.to(curConversation, 0.5, {left:"0px", opacity:1, startAt:{left:"100px", opacity:0}, ease:Back.easeOut});
		upDateConversationHeight();
	}
}

function upDateConversationHeight(){
	if(curConversation == null) return;
	if(onPhoneCourse){
		$(".cb_elements").css("min-height", (curConversation.height()+125)+"px");
	}else{
		$(".cb_elements").css("min-height", (curConversation.height())+"px")
	}
}

//+++++++++++++++++++++++++++++++++++++ initConversation +++++++++++++++++++++++++++++++++++++++++++
// Set up the conversation - hide all the slides, set up the breadcrumb and assign functionality
// to the next|back buttons.
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function initConversation(obj){
	var numSlides = obj.find(".cSlide").length;


	obj.find(".cb_close").unbind("click touch").bind("click touch", function(e) {
		$(".cb_converHolder").css("display", "none");
		$(".conversationOpen").removeClass("conversationOpen");
		$(".selected").removeClass("selected");
	});

	obj.find(".cb_breadcrumb").each(function(index) {
		$(this).html((index+1)+"/"+numSlides)
	});

	obj.find(".cSlide").each(function(index) {
		slideObj = $(this);
		slideObj.find(".cb_arrow").each(function(index) {
			slideObj.attr("arrowPos",$(this)[0].style.left)
		});

		if(index==0){
			$(this).find(".cb_back").addClass("disabled");
			$(this).removeClass("invisible");
		}

		if(index>0 && $(this).hasClass("invisible") != true){
			$(this).addClass("invisible");
		}

		if((index+1) == numSlides){
			$(this).find(".cb_next").addClass("disabled");
			$(this).addClass("last");
		}

		$(this).find(".cb_back").unbind("click touch").bind("click touch", {qObj: $(this), cbDir: "back"}, navConversation);
		$(this).find(".cb_next").unbind("click touch").bind("click touch", {qObj: $(this), cbDir: "next"}, navConversation);

	});

			if(obj.find(".cSlide").first().data("audio") != undefined && obj.find(".cSlide").first().data("audio") != "") {
			   loadAudio(obj.find(".cSlide").first().data("audio"));
			}


}

//+++++++++++++++++++++++++++++++++++++ navConversation +++++++++++++++++++++++++++++++++++++++++++
// Functionality to move the user through the conversations - when the user reaches the end
// of the conversation the controlled navigation is checked.
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function navConversation(event){

	$(".audioBtn").removeClass("finished");

	var obj = event.data.qObj;
	if((event.data.cbDir=="back" && obj.data("back") == null) || (event.data.cbDir =="next" && obj.data("next") == null)){
		return false;
	}

	obj.parent().find(".cSlide").each(function(index) {
		$(this).addClass("invisible");
	});

	var targetSlide = $("#"+obj.data(event.data.cbDir))
	targetSlide.removeClass("invisible");

	if(targetSlide.data("audio") != undefined && targetSlide.data("audio") != "") {
     loadAudio(targetSlide.data("audio"));
}

	if($("#"+obj.data(event.data.cbDir)).hasClass("last")){
		$("#wrapper").find(".conversationBtn").each(function(index) {
			if($(this).data("target") == obj.parent().attr("id")){
				$(this).find(".cb_complete").removeClass("invisible")
			}
		});
		obj.parent().removeClass("controlnav")
		checkRestrictedNav();
	}
	if(!isIE8){
		var arrowStartPoint = obj.find(".cb_arrow")[0].style.left; //TO GET AROUND A SAFARI BUG THE LEFT POSITION IS FOUND LIKE THIS.
		var arrowEndPoint = targetSlide.attr("arrowPos");

		TweenMax.to(targetSlide.find(".cb_arrow"), 0.5, {left:arrowEndPoint, startAt:{left:arrowStartPoint}, ease:Power1.easeIn});
		TweenMax.from(targetSlide.find(".cb_img"), 0.4, {opacity:0, x:"-20px", ease:Back.easeOut});
	}
}


//++++++++++++++++++++++++++++++++++++ Hotspot Popup Responsive +++++++++++++++++++++++++++++++++++++++++++
function hotspotPopRes() {
	if ($("#wrapper").data("screen_type") != undefined && $("#wrapper").data("screen_type") == "hotspot") {
		$(".spots").each(function(i){
			$(this).css({
				top: $(this).data("top") + "%",
				left: $(this).data("left") + "%",
				width: $(this).parent().data("spot_width") + "%",
				height: $(this).parent().data("spot_height") + "%"
			});
			$(".small_image_res" + (i+1)).css({
				top: $(this).data("top") + "%",
				left: $(this).data("left") + "%",
				width: $(this).parent().data("tick_width") + "%"
			});
		});
	}
	if ($(".spots").length && !$(".spots").hasClass("res")) {
		$(".spots").click(function() {
			$(this).addClass("visitedSpot");
		});
	}
}
function hsQRes() {
	$(".res").click(function(){
		if ($("#questionPanel").attr("q_type") == "MAMC_HS"){
			$(this).toggleClass("visitedSpot");
		}
		else if ($("#questionPanel").attr("q_type") == "SAMC_HS") {
			if ($(this).hasClass("visitedSpot")) {
				$(this).removeClass("visitedSpot");
			}
			else {
				$(".visitedSpot").removeClass("visitedSpot");
				$(this).addClass("visitedSpot");
			}

		}
		$(".visitedSpot").css("border-color", $(this).parent().data("spot_color"));
	});
}

//+++++++++   confirm button  ++++++++++++++++++//

$("#btn_confirm").click(function changeState() {
		$("#btn_confirm").removeClass("btn_confirm");
		 $(this).addClass("btn_confirm");
         removeClass("btn_confirm").addClass("btn_confirm_disabled");
 });

//++++++++++++++++++++++++++++++++++++++++//
