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: '',

        contentdir: '../content/'
    };
    _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;
    var isPrompter = false;
    var isPause = 0;



    var audioEnded = function () {
        console.log('audio done');
        audioFinished = true;
        if (animFinished) {
            autoPlayNext();
        }
    }

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

    var prompterEnded = function () {
        showSection('test');
    }

    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***********************************/



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

        /*
		$('#button-stop').click(function(){
			$('#button-play').toggleClass('disabled');
		});
		*/
        populateAnim();
        populateQuiz();
        populateReview();
        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 + '%');
        $('#review-container').css('font-size', fontSize + '%');
    }


    var showSection = function (id, prompter) {
        $('#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();

            showStage(id);

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

            showStage(id);

            var toppad = $('#question' + currentQuestion).find('.questionText').height() / 2;
            $('#swiffy-container-quiz').css({ 'padding-top': toppad + 'px' });

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

            showStage(id);

            $('#cdata-section').height(
				$('#review-container').height() - ($('.reviewh1').height() + $('.reviewp1').height() + $('.reviewh2').height() + 15)
			);

        }

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

    var showStage = function (section, questionNum) {
        if (section == 'learn') {
            if (stage) stage.destroy();
            animFinished = false;
            $('#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();
        }
        else if (section == 'test') {
            nextImage(currentQuestion);
        }
        else if (section == 'review') {
            if (summaryImage.length > 0) {
                $('#swiffy-container-review').empty();
                var stageReview = new swiffy.Stage(document.getElementById('swiffy-container-review'), summaryImage[0]);
                stageReview.setFlashVars('isRTL=' + ((_options.rtl == 'true') ? '1' : '0'));
                stageReview.start();
            }
        }
    }

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

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

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

    var nextSlide = function () {
        console.log('next:' + index);
        cancelTimeout = true;
        isPrompter = checkPrompter();

        if (isPrompter) {
            audioFinished = true;
            animFinished = false;
            stage.setFlashVars('isPaused=0');
            var timeout = setInterval(function () {
                if (animFinished == true) {
                    showSection('test');
                    clearInterval(timeout);
                }
            }, 500);
        }
        else {
            index++;
            showSection('learn');
            showSlide();
        }

    }

    var checkPrompter = function () {
        if (index > maxIndex)
            return true;
        else
            return false;
    }

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

    var cancelTimeout = false;
    var autoPlayNext = function () {
        console.log('auto');
        //if the user has not interacted with the next, prev, replay or stop buttons
        animFinished = false;
        audioFinished = false;
        if (autoPlaying == true) {



            cancelTimeout = false;
            setTimeout(function () {
                if (cancelTimeout == false) {
                    nextSlide();
                }
            }, parseInt(_options.pause) * 1000);
        }
    }

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

        isPrompter = checkPrompter();
        if (index > maxIndex) {
            $('#slide-counter').hide();
            $('#votext-container').hide();
        }
        else {
            autoPlaying = true;

            $('#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);
            $('#votext-container').show();
            $('#votext-container').empty().html(voText[index]);

            audio.muted = muted;

            //changed this to just use locontent prefix, some xml dont have mp3ref in the vo tag.
            //var mp3base = json1.LO.VOText.VO[index]['@mp3ref'].split('.');
            //var mp3source = mp3base[0].toUpperCase() + ".mp3";

            var mp3base = locontent.properties.movie_prefix;
            var mp3source = mp3base.toUpperCase() + (index + 1 < 10 ? '0' + (index + 1) : index + 1) + ".mp3";

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

    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;
        soundCount = json1.LO.VOText.VO.length;

        //load up labels
        var labels = new Array();
        for (var i = 0; i < labelCount; i++) {
            labels.push(json1.LO.Labels.Label[i]['#text']);
        }

        //load up VO_Text
        for (var i = 0; i < soundCount; i++) {
            if (typeof json1.LO.VOText.VO[i]['#text'] == 'undefined') {
                voText.push(json1.LO.VOText.VO[i]['#cdata-section'].replace(/\n/g, '<br />'));
            }
            else {
                voText.push(json1.LO.VOText.VO[i]['#text'].replace(/\n/g, '<br />'));
            }
        }

        audio = document.getElementById("audio1");
        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];
        }

        var alignInt = (_options.rtl == 'true' ? 1 : 0);

        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' + (j + 1));
                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 (ref[k].hasOwnProperty("align")) {
                        if (ref[k].align == 3) {
                            ref[k].align = alignInt;
                        }
                    }


                    /*
					if(_options.rtl == 'true'){
						if(!ref[k].hasOwnProperty("align")) {
			              	ref[k].align = 1;
						}
					}
					*/
                    ref[k].text = labels[j];
                }
            }
            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'];

        if (typeof json2.text.summary['#cdata-section'] == 'undefined') {
            console.log(json2.text.summary['#text']);
            review.summ = json2.text.summary['#text'].replace(/»/g, '<br>&#187').replace(/«/g, '<br>&#187').replace(/•/g, '<br>&#187');;
        }
        else {
            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);
    }

    //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 (typeof imagePosition[imagess] != 'undefined') {

            if (imagePosition[imagess].imageHere == 'True') {
                $('#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();
        }
    }

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


            var toppad = $('#question' + currentQuestion).find('.questionText').height();
            $('#swiffy-container-quiz').css({ 'padding-top': toppad + 'px' });

        }
        if (currentQuestion == json3.length) {
            currentQuestion--;
            $('#question' + currentQuestion).show();
            showSection('review');
        }
    }

    var prevQuestion = function () {
        if ($('#review-section').is(':visible')) {
            showSection('test');
            var toppad = $('#question' + currentQuestion).find('.questionText').height();
            $('#swiffy-container-quiz').css({ 'padding-top': toppad + 'px' });
        }
        else {
            if (currentQuestion > 0) {
                $('#question' + currentQuestion).hide();
                currentQuestion--;
                nextImage(currentQuestion);
                $('#question' + currentQuestion).show();
                $('#nextQuestion').removeClass('disabled');
                var toppad = $('#question' + currentQuestion).find('.questionText').height();
                $('#swiffy-container-quiz').css({ 'padding-top': toppad + 'px' });
            } else {
                showSection('learn');
            }
        }
    }


    return {
        init: init,
        startSlides: startSlides,
        stopSlides: stopSlides,
        nextSlide: nextSlide,
        prevSlide: prevSlide,
        muteAudio: muteAudio,
        animEnded: animEnded,
        prompterEnded: prompterEnded,
        answer: answer
    };

}