var SwiffyPlayer = function (parameters) {

	
    var _options = {
		language: '',
		rtl: '',
		autoplay: '',
		pause: '',
		playAudio: '',

		strLearn: 'Learn',
		strTest: 'Test',
		strReview: 'Review',
		strScene: 'scene',
		strPrompter: 'prompt',
		strCopyright: 'copyright notice',

		maxIndex: 1,
		audioContainer: '',
		prompter: ''

    };
    _options = $.extend(_options, parameters);

	var index = 0;
    var currentQuestion = 0;
    var animation = new Array();
	//var audio = new Array();
	var audio;
	var voText = new Array();

	var stage;
	var muted = false;

	var title;
	var prefix;
	var soundCount;
    
    var autoPlaying = true;

	var animFinished = false;
	var audioFinished = false;

	//daveh - added sub bool as the slides have multiple audios per slide
	var subFinished = false;

	var isPrompter = false;
	var isPause = 0;

	//daveh - needs to be expose as a param
	var isks4 = true;

	//daveh - added for KS4 to allow the VO to be updated mid slide
	function showVO(a, b) {
		//console.log('showVO called !!!!!!!!!!!!!');	
		//play audio and set VO text here
		//daveh
		var vo = getVoNodeById(b);
		//console.log(vo);
		//console.log(vo["#text"]);
		//label['@id']
		$('#votext-container').show();
		$('#votext-container').empty().html(vo["#text"]);

		//potential method to handle sub and superscript labels
		//handleSubscript();

		audio.muted = muted; 
		var mp3base = vo['@mp3ref'].split('.');
		var mp3source = mp3base[0].toLowerCase() + ".mp3";

		//daveh - reset the audio and sub finished bools
		audioFinished = false;
		subFinished = false;

		// play new audio src
        audio.src = '../content/' + _options.language + '/' + _options.category + '/' + _options.folder + '/audio/' + mp3source;
        audio.play();
        
	};

	//daveh - ks4 helper as the id is no longer numeric
	function getVoNodeById(id) {
		for(var i= 0; i < json1.LO.VOText.VO.length; i++ ) {
			if(json1.LO.VOText.VO[i]["@id"] == id) {
				return json1.LO.VOText.VO[i];
			}
		}
	}

	//daveh - called from the flash once the sub has ended
	//both the sub and the audio must be ended to continue
	function subEnded() {
		subFinished = true;
		if (audioFinished){
			//daveh - introduced a new value of 2 to resume 
			// - this should probalbe to update with more meaniful values
			stage.setFlashVars('isPaused=2');
		}
	}

	//daveh - added an additional is subended to allow current slide to resume
	var audioEnded = function(){		
		audioFinished = true;
		if (animFinished){
			autoPlayNext();
		} else if(subFinished){
			//play opn in the current
			stage.setFlashVars('isPaused=2');
		}		
	}

	var animEnded = function(){
		animFinished = true;		
		if (audioFinished){
			if(isPrompter){
				showSection('test');
			}
			else{
				autoPlayNext();
			}
		}
	}

	var init = function() {
		window.onresize = textScale;
		$('#button-prev').addClass("disabled");
		$('#button-stop').addClass("disabled");
		$('#button-next').addClass("disabled");
		$('#learn-link').addClass("focused");

		/******************************ARABIC RTL***********************************/
		if(_options.rtl == 'true'){
			$('#lo-title').css({'float':'right', 'text-align':'right', 'margin-right': '1.7%'});
			$('#slide-counter').css({'float':'left', 'text-align':'left', 'margin-left': '2.0%'});

			$('#votext-container').css({'direction': 'rtl', 'right':'0px'});
			$('#lo-nav').css({'margin-left': '19%'});
			$('#lo-nav div').css({'float': 'right', 'direction' : 'rtl'});

			$('#lo-mov-section').css({'margin-left': '6%'});
			$('#lo-mov-section div').css({
				'float': 'right',
				'direction' : 'rtl',
				'-webkit-transform': 'rotate(180deg)',
				'-moz-transform': 'rotate(180deg)',
				'-ms-transform': 'rotate(180deg)',
				'-o-transform': 'rotate(180deg)',
				'transform': 'rotate(180deg)'
			});

			$('#quiz-container').css({'direction': 'rtl', 'text-align':'right'});

			$('#lo-quiz-controls').css({'margin-left': '6%'});
			$('#lo-quiz-controls div').css({
				'float': 'right',
				'direction' : 'rtl',
				'-webkit-transform': 'rotate(180deg)',
				'-moz-transform': 'rotate(180deg)',
				'-ms-transform': 'rotate(180deg)',
				'-o-transform': 'rotate(180deg)',
				'transform': 'rotate(180deg)'

			});

			$('#review-container').css({'direction': 'rtl', 'text-align':'right'});

			/* next */

			$('#large-play-button img').css({
				'-webkit-transform': 'rotate(180deg)',
				'-moz-transform': 'rotate(180deg)',
				'-ms-transform': 'rotate(180deg)',
				'-o-transform': 'rotate(180deg)',
				'transform': 'rotate(180deg)'
			});

		}
		/******************************ARABIC RTL***********************************/


		$('#large-play-button').show();
		$('#lo-mov-section').show();

		$("#learn-link").text(_options.strLearn);
		$("#test-link").text(_options.strTest);
		$("#review-link").text(_options.strReview);

		if(isks4) {
			$("#learn-link").hide();
			$("#test-link").hide();
			$("#review-link").hide();
		}

		/*
		$('#button-stop').click(function(){
			$('#button-play').toggleClass('disabled');
		});
		*/
		populateAnim();
		//populateQuiz();
		//populateReview();
		//$('#learn-link').click(function(){showSection('learn')});
		//$('#test-link').click(function(){showSection('test')});
		//$('#review-link').click(function(){showSection('review')});
		setTimeout(function(){ textScale();}, 100);
	}

	var textScale = function() {
	    var scaleSource = $('body').width();
	    var scaleFactor = .12;
	    var maxScale    = 200;
	    var minScale    = 50;

	    // Multiply the width of the body by the scaling factor
	    var fontSize = scaleSource * scaleFactor; 

	    //Enforce the minimum and maximums
	    if (fontSize > maxScale) fontSize = maxScale;
	    if (fontSize < minScale) fontSize = minScale; 

	    $('#votext-container').css('font-size', fontSize + '%');
	    $('#quiz-container').css('font-size', fontSize + '%');

	}

	var showSection = function(id, prompter) {
		isPrompter = false;
		$('#learn-link').removeClass('focused');
		$('#test-link').removeClass('focused');
		$('#review-link').removeClass('focused');
		
		$('#'+id+'-link').addClass('focused');
		
		$('#learn-section').hide();
		$('#test-section').hide();
		$('#review-section').hide();
		
		$('#'+id+'-section').show();

		audio.pause();
		audio.src = '';

		if(id == 'learn'){
			autoPlaying = true;
			$('#lo-mov-section').show();
			$('#slide-counter').show();	
			$('#lo-quiz-controls').hide();	
			
		}
		else if(id == 'test'){
			stopSlides();
			autoPlaying = false;
			$('#lo-mov-section').hide();
			$('#slide-counter').hide();
			$('#lo-quiz-controls').show();	
		}
		else if(id == 'review'){
			stopSlides();
			autoPlaying = false;
			$('#lo-mov-section').hide();
			$('#slide-counter').hide();
			$('#lo-quiz-controls').show();		
		}

		if(prompter == 'prompter'){
			isPrompter = true;
			stopSlides();
			autoPlaying = false;
		}
	}

	var startSlides = function() {
		$('#large-play-button').unbind('click');
		$('#large-play-button').fadeTo(0, 0, function(){	
			$(this).hide();
			$('#button-next').removeClass('disabled');
		});
		showSlide();
	}

	var stopSlides = function(){
		audio.pause();
		isPause = 1;
		stage.setFlashVars('isPaused=' + isPause);
	}

	var muteAudio = function(){
		muted = !muted;
		audio.muted = muted;
		$('#button-audio-mute').toggle();
		$('#button-audio').toggle();
	}

	var nextSlide = function() {
		if(isPrompter){
			audioFinished = false;
			animFinished = false;
			stage.setFlashVars('isPaused=0');
			var timeout = setInterval(function(){
				if(animFinished == true){
					showSection('test');
					clearInterval(timeout);
				}
			},500);
		}
		else{
			if(index < maxIndex) {
				index++;
				showSlide();
			}
			//daveh - for POC ks4 only has learn
			else if(!isks4) {
				showSection('learn', 'prompter');
				index++;
				showSlide();
			}
		}
		
	}

	var prevSlide = function() {
		if(index > 0) {
			index--;
			showSlide();
		}
	}

	var autoPlayNext = function() {
		//if the user has not interacted with the next, prev, replay or stop buttons
		if(autoPlaying == true){
			
			animFinished = false;
			audioFinished = false;
	
			setTimeout(function(){
				if (autoPlaying == true){
					if(index < maxIndex) {
						index++;
						showSlide();
					}
					//daveh - for POC ks4 only has learn
					else if(!isks4) {
						showSection('learn', 'prompter');
						index++;
						showSlide();
					}
				}
			},parseInt(_options.pause) * 1000);
		}
	}


	var handleSubscript = function(){
		//In Flash, set labels with <sub>'s or<sup>'s to render as HTML.
		//In the json change:
		//from:		<sub>SOMETEXT</sub>
		//to:		<tspan>SOMETEXT|1</tspan>
		//note adding |1 (bar 1) to the end of the text within the tags
		//use |2 for superscript
		//Set the configurations below as required, to change font size or if |1 turns out to clash with something

		var SUBSCRIPT_SHIFT = 1.5;
		var SUBSCRIPT_CHAR = '|1';
		var SUBSCRIPT_FONT = 0.8;

		var SUPERSCRIPT_SHIFT = 0.5;
		var SUPERSCRIPT_CHAR = '|2';
		var SUPERSCRIPT_FONT = 0.8;

		//SUBSCRIPT
		$('svg').find('text:contains("' + SUBSCRIPT_CHAR + '")')
			.each(
				function(){
					var elem = $(this);
					elem.attr('y', elem.attr('y') * SUBSCRIPT_SHIFT);
					elem.text(elem.text().replace(SUBSCRIPT_CHAR, ''));
					elem.attr('font-size', elem.attr('font-size') * SUBSCRIPT_FONT);
				});

		//SUPERSCRIPT
		$('svg').find('text:contains("' + SUPERSCRIPT_CHAR + '")')
			.each(
				function(){
					var elem = $(this);
					elem.attr('y', elem.attr('y') * SUPERSCRIPT_SHIFT);
					elem.text(elem.text().replace(SUPERSCRIPT_CHAR, ''));
					elem.attr('font-size', elem.attr('font-size') * SUPERSCRIPT_FONT);
				});

	}

	var showSlide = function() {
		//do housekeeping on the buttons
		$('#button-stop').removeClass('disabled');
		if(index == 0) {
			$('#button-prev').addClass('disabled');
		}
		else {
			$('#button-prev').removeClass('disabled');
		}

		if(index == maxIndex){
			$('#button-next').addClass('disabled');	
		}
		else{
			$('#button-next').removeClass('disabled');	
		}


		if(index > maxIndex) {
			$('#slide-counter').hide();
			$('#votext-container').hide();
		}
		else {
			$('#slide-counter').show();

			var slc = _options.strScene.replace('[X]', (index+1)).replace('[Y]', (maxIndex+1));
			$('#slide-counter').text(/*"Slide " + (index+1) + " of " + (maxIndex+1)*/slc);
			//daveh - ks4 the VO is controlled from the showVO function above, called from the animation	
			/*
			$('#votext-container').show();
			$('#votext-container').empty().html(voText[index]);

			audio.muted = muted; 
			var mp3base = json1.LO.VOText.VO[index]['@mp3ref'].split('.');
			var mp3source = mp3base[0].toUpperCase() + ".mp3";
			// play new audio src
            audio.src = '../content/' + _options.language + '/' + _options.category + '/' + _options.folder + '/audio/' + mp3source;
            audio.play();
            */
		}

		$('#swiffy-container').empty();
		stage = new swiffy.Stage(document.getElementById('swiffy-container'), animation[index]);
		//isPause = 1 to pause and isPause = 0 to replay
		stage.setFlashVars('isRTL=' + ((_options.rtl == 'true')? '1' : '0'));
		stage.start();
		//daveh - resize to 80% for ks4
		//$("#swiffy-container").find("svg").height("80%");
		//LF - 75 is correct and set on svg container
		$("#swiffy-container").height("75%");

	}

	var setButtonState = function(prev, stop, play, next, mute){
		//one is on
		//setButtonState(1,1,1,1,1);
		if(prev == 1){
			$('#button-prev').removeClass('disabled');	
		}else{
			$('#button-prev').addClass('disabled');
		}
		
		if(stop == 1){
			$('#button-stop').removeClass('disabled');
		}else{
			$('#button-stop').addClass('disabled');
		}

		if(play == 1){
			$('#button-play').removeClass('disabled');
		}else{
			$('#button-play').addClass('disabled');
		}

		if(next == 1){
			$('#button-next').removeClass('disabled');
		}else{
			$('#button-next').addClass('disabled');
		}

		if(mute == 1){
			$('#button-audio-mute').removeClass('disabled');
		}else{
			$('#button-audio-mute').addClass('disabled');
		}
	}

	var populateAnim = function(){
		prefix = locontent.properties.movie_prefix;
		title = locontent.properties.TitleLo;

		$('#lo-title').text(title);

		var slideCount = locontent.properties.no_screens;
		maxIndex = slideCount -1;
		
		//If there are no labels create an empty array
		if(json1.LO.Labels == null){
			json1.LO.Labels = {Label: []};
		}
		var labelCount = json1.LO.Labels.Label.length;
		//console.log('labelCount: ' + labelCount);
		

		soundCount = json1.LO.VOText.VO.length;
		//console.log('soundCount: ' + soundCount);

		//load up labels
		var labels = new Array();
		for(var i=0; i<labelCount; i++ ){
			//labels.push(json1.LO.Labels.Label[i]['#text']);
			labels.push(json1.LO.Labels.Label[i]);
		}
		//console.log('labels');
		//console.log(labels);
		
		//load up VO_Text
		for(var i=0; i<soundCount; i++){
			voText.push(json1.LO.VOText.VO[i]['#text'].replace(/\n/g, '<br />'));
		}
		
		audio = document.getElementById("audio1");        
		//daveh - changed the callback here
        audio.addEventListener("ended", audioEnded, false);

		//now obsolete. direct copy for now. remove and rename this later.
		for(var i=1; i<=slideCount;i++){
			animation[i-1] = allSwfs[i-1];
		}

		for(var i=0; i<slideCount; i++){
			var swiffy = animation[i];
			for(var j=0; j<labelCount; j++){
				var label = labels[j];				

				// Returns an array of matching objects
				var ref = getObjects(swiffy, 'variable', label['@id']);
				for (var k in ref){
					// daveh - for RTL text
					// if obj DOES NOT have prop align - then it is left aligned text
					// give obj an algin property of 1 (right aligned)
					// ignore center or already right aligned text
					
					if(_options.rtl == 'true'){
						if(!ref[k].hasOwnProperty("align")) {
			              	ref[k].align = 1;
						}
					}
					ref[k].text = label['#text'];
				}
			}
			animation[i] = swiffy;
		}

		//string injection for prompter :- temporary hardcoded
		var swiffy = prompter[0];
		var ref = getObjects(swiffy, 'variable', 'label1');
		ref[0].text = _options.strPrompter;
		var ref = getObjects(swiffy, 'variable', 'label2');
		ref[0].text = _options.strTest;

		//append prompter to slides
		animation.push(swiffy)

		//string injection for quiz images
		for(var i=0; i<allImages.length; i++){
			var swiffy = allImages[i];
			for(var j=0; j<labelCount; j++){
				var label = labels[j];
				// Returns an array of matching objects
				var ref = getObjects(swiffy, 'variable', 'label' + (j+1));
				for (var k in ref){
					ref[k].text = labels[j];
				}
			}
			allImages[i] = swiffy;
		}

		//string injection for summary
		for(var i=0; i<summaryImage.length; i++){
			var swiffy = summaryImage[i];
			for(var j=0; j<labelCount; j++){
				var label = labels[j];
				// Returns an array of matching objects
				var ref = getObjects(swiffy, 'variable', 'label' + (j+1));
				for (var k in ref){
					ref[k].text = labels[j];
				}
			}
			summaryImage[i] = swiffy;
		}
	}

	var populateReview = function() {
		var review = new Object();
		review.heading1 = json2.text.heading1['#text'];
		review.objective = json2.text.objective['#text'];
		review.heading2 = json2.text.heading2['#text'];
		review.summ = json2.text.summary['#cdata-section'];

	    $.template("reviewTemplate", $("#tmpl-review").text());
	    $.tmpl("reviewTemplate", review).appendTo("#review-container");

	    //tmpl cant insert text with html markup, have to append it mannually.
	    //also problem with encoding in utf-8 for superscript
		$('#cdata-section').html(review.summ);

		if(summaryImage.length > 0){
			$('#swiffy-container-review').empty();
			var stageReview = new swiffy.Stage(document.getElementById('swiffy-container-review'), summaryImage[0]);
			stageReview.start();
		}
	}

	//Quiz functionality
	var answer = function(source, qnum){
		var answer = source.attr('ans');
		$("#answer" + qnum).find('span').hide().eq(answer).show();
		//if (answer == json3[qnum].correct){
			//$('#nextQuestion').show();
		//}
	}

	var populateQuiz = function() {
		var numQuestions = json3.length;

		$("#quiz-container").empty();
	    $.template("quizTemplate", $("#tmpl-quiz").text());
	    $.tmpl("quizTemplate", json3).appendTo("#quiz-container");

	    $('#question0').show();
	    if(numQuestions > 1){
			$('#nextQuestion').removeClass('disabled');
		}

		$('#lo-quiz-controls').off('click', '#nextQuestion').on('click', '#nextQuestion', function(){
			nextQuestion();
		});
		
		$('#lo-quiz-controls').off('click', '#prevQuestion').on('click', '#prevQuestion', function(){
			prevQuestion();
		});

		//show initial image if there is one
		nextImage(currentQuestion);
	}

	var nextImage = function(imagess){
		var diff = imagePosition.length - allImages.length;
		if(allImages.length > 0 && allImages.length > (imagess - diff)){

			

			if (imagePosition[imagess].imageHere == 'True'){
				//console.log(allImages[imagess]);
				$('#swiffy-container-quiz').empty();
				var stageImage = new swiffy.Stage(document.getElementById('swiffy-container-quiz'), allImages[imagess - diff]);
				stageImage.setFlashVars('isRTL=' + ((_options.rtl == 'true')? '1' : '0'));
				stageImage.start();
			}
			else{
				$('#swiffy-container-quiz').empty();
				//console.log('no image at this slide');	
			}
		}
	}

	var nextQuestion = function(){
		if (currentQuestion < json3.length){
			$('#question' + currentQuestion).hide();
			currentQuestion++;
			nextImage(currentQuestion);
			$('#question' + currentQuestion).show();
			$('#prevQuestion').removeClass('disabled');
		}
		if (currentQuestion == json3.length){
			currentQuestion--;
			$('#question' + currentQuestion).show();
			showSection('review');
		}
	}

	var prevQuestion = function(){
		if($('#review-section').is(':visible')){
				showSection('test');
		}
		else{
			if(currentQuestion > 0){
				$('#question' + currentQuestion).hide();
				currentQuestion--;
				nextImage(currentQuestion);
				$('#question' + currentQuestion).show();
				$('#nextQuestion').removeClass('disabled');
			}else{
				showSection('learn');
			}
		}
	}

	//daveh - exposed 2 additional functions
	return {
        init: init,
        startSlides: startSlides,
        stopSlides: stopSlides,
        nextSlide: nextSlide,
        prevSlide: prevSlide,
        muteAudio: muteAudio,
        animEnded: animEnded,
        subEnded: subEnded,
        showVO: showVO,
        answer: answer
    };

}