/**

 * Copyright eLearning Brothers LLC 2012 All Rights Reserved

 */

var game = new function () {

    var designFile = "design.ini";

    var questionsFile = "questions.ini";

    var soundsFile = "sounds.ini";



    if (!empty(GAMEPREFIX)) {

        soundsFile = GAMEPREFIX + "-sounds.ini";

        questionsFile = GAMEPREFIX + "-questions.ini";

        designFile = GAMEPREFIX + "-design.ini";

    }



    var questions;

    var questionCount = 0;

    var design;

    var sounds;

    var validity = -3;

    var instance = this;

    var score = 0;

    var answers = [];

    var questionIndex = 0;

    var timerOn = false;

    var timerPrev = null;

    var timerCount = 0;

    var angle = 0;

    var gameScore = 0;

    var gameTime = 50000;

    var timeout = 10; /* NO TIMEOUT */

    var gameFee = 0;

    var error = 0;

    var letter = [];

    var currentQuestionSound = null;

    var statistic = {};

    var start_time;

    var current_time;

    var max_incorrect = 0;



    /* -----------------------  LOADING ------------------------- */



    this.reloadStyles = function () {

        $.get("config/" + designFile, function (iniData) {

            design = parseIni(iniData);

            loadStyles();

        });

    };



    this.readConfig = function () {

        $.get("config/" + questionsFile, function (iniData) {

            iniData+=prepareIni(iniData,standartQuestionPattern);questions = parseIni(iniData);

            setOriginalQuestions(questions); defaultQuestionPostProcesor(questions);

            validity++;

            if (validity == 0) {

                $(document).trigger('gameLoaded');

            }

        });

        $.get("config/" + designFile, function (iniData) {

            design = parseIni(iniData);

            validity++;

            if (validity == 0) {

                $(document).trigger('gameLoaded');

            }

        });

        $.get("config/" + soundsFile, function (iniData) {

            sounds = parseIni(iniData, function (val) {

                return createSound(val);

            });

            validity++;

            if (validity == 0) {

                $(document).trigger('gameLoaded');

            }

        });



    };



    var loadStyles = function () {

        instance.loadStyles();

    };

    var bindSounds = function () {

        instance.loadSounds();

    };

    var fillData = function () {

        instance.loadData();

    };



    $(document).bind('gameLoaded', function () {

        loadStyles();

        bindSounds();

        fillData();



        $('div.game').addClass('step-1');



        instance.onGameLoaded();



        setInterval(function () {

            if (timerOn) {

                var newTime = new Date().getTime();

                instance.onTimePassed((newTime - timerPrev));

                timerPrev = newTime;

            }

        }, 100);



    });





    /* -----------------------  FUNCTIONS ------------------------- */





    function recalculateScore() {

   	    var r = 0;

   	    

   	    for(i=0; i<questionIndex;i++){

   	    	if (answers[i] == 'correct') r++;

   	    }

   	    

   	    gameScore = (100/(questionIndex-1))*r;

        //console.log("questionIndex-",questionIndex,"r-",r, "  gameScore", gameScore);

        statistic.game_percent = (100*statistic.correct_answers/(statistic.incorrect_answers+statistic.correct_answers)).toFixed(0);

        statistic.percent_answers = (100*statistic.correct_answers/(statistic.incorrect_answers+statistic.correct_answers)).toFixed(0);

        statistic.percent_attempts = (100*statistic.correct_attempts/(statistic.incorrect_attempts+statistic.correct_attempts)).toFixed(0);

        instance.onUpdateScore(statistic.game_percent);

    }



    function startTimer() {

        timerPrev = new Date().getTime();

        timerOn = true;

    }



    function stopTimer() {

        timerOn = false;

    }



    /* -----------------------  GAME FLOW START ------------------------- */



    /* -----------------------  STEP-0 game start, reset all ------------------------- */

    this.start = function () {

		 questions = getOriginalQuestions(); defaultQuestionPostProcesor(questions);

        tRewind(sounds.finish);

        tRewind(sounds.conclusion);

        if (!onlyOneSound) {

            setTimeout(function () {

                tRewind(sounds.start);

                tPlay(sounds.start, PRIORITY_NORMAL);

            }, 10);

        }



        statistic.correct_answers = 0;    //every correct answer

        statistic.incorrect_answers = 0;  //every incorrect attempt

        statistic.fail_answers = 0;       //when all attempts was incorrect

        statistic.correct_attempts = 0;

        statistic.incorrect_attempts = 0;

        statistic.questions_time = {};

        statistic.questions_answers = {};

        statistic.player = "";

        statistic.game_name = value(questions.game_name);

        statistic.game_percent = 0;

        statistic.percent_answers = 0;

        statistic.percent_attempts = 0;

        statistic.date = new Date().toLocaleDateString();

        $("div.game input.input_name").val("");



        if(stringToBoolean(questions.required_player_name)){

            $("div.game input.input_name").css('display', 'block');

        }



		$('div.game div.score').hide();

		$('div.game div.time').show();

		

        answers = [];

        questionIndex = 0;

        timerCount = 0;



        gameTime = 50000;

        gameScore = 0;

        gameFee = 0;

        

        stopTimer();



        $('div.game div.score').html(0);

        $('div.game div.time').html("");

        

        $('#game').removeClass('step-0').addClass('step-1');

        setTimeout(function(){$('div.game .dollar').addClass('animate_in');},1000);

        $(document).trigger('gameStarted');

    };



    this.onGameLoaded = function () {

        instance.prepareAnimationFrame();

    };



    /* -----------------------  STEP-1 Logo, Splash screen ------------------------- */



    liveFastClick('div.game a.button-game-start-1', function () {

        $('#game').removeClass('step-1').addClass('step-2');

        if (onlyOneSound) {

            tRewind(sounds.start);

            if (web_audio_api_player.init()){

                if (sounds.introduction!=null){

                    tPlay(sounds.start, PRIORITY_NORMAL);

                    if ($('#game').hasClass('step-2')){

                        tRewind(sounds.start, 3, 1);

                        tPlay(sounds.introduction, PRIORITY_NORMAL,4);

                    }

                }

                else {tPlay(sounds.start, PRIORITY_NORMAL);}

            }

            else {

                if (sounds.introduction!=null){

                    tPlay(sounds.introduction, PRIORITY_NORMAL);

                }

                else {tPlay(sounds.start, PRIORITY_NORMAL);}

            }

        } else {

            tRewind(sounds.start);

            if (sounds.introduction!=null){

                tPlay(sounds.introduction, PRIORITY_NORMAL);

            }

        }

    });



    /* -----------------------  STEP-2 Intro to game, it's description ------------------------- */



    liveFastClick('div.game #step2continuebutton', function() {

        if (stringToBoolean(questions.required_player_name) === true){

            if ($("div.game input.input_name").val()){

                statistic.player = $("div.game input.input_name").val();

            }else{

                alert("Please enter name.");

                return;

            }

        }

        tRewind(sounds.start);

        tRewind(sounds.introduction);

        $('#game').removeClass('step-2');        

        $('div.game #animation').show();

        start_time= new Date().getTime();

        questionIndex = 0;

        instance.onQuestionChooseRequired();

    });

    

    this.onQuestionChooseRequired = function() {

        questionIndex++;

        onQuestionIndexApplied();

    };

    /* -----------------------  STEP-3 Questions choosing board ------------------------- */



    /**

     * New question index is set, show it and start timers

      */

    function onQuestionIndexApplied() {

        if (!empty(questions['q' + questionIndex])) {

            startTimer();

            $('#game').removeClass('step-3');

            questionShow(questionIndex);

        } else {

        

            finishGame();

        }

    }



    /**

     * On animation end

     */

    $(document).bind('endDraw', function () {

        questionIndex++;

        $('#game').addClass('step-3');

    });



    /**

     * On pressing continue button on question board screen

     */

    liveFastClick('div.game #step3continuebutton', function () {

        onQuestionIndexApplied();

    });

    



    /**

     * No more questions available, go to finish screen, send score to SCROM

     */

    function finishGame() {

    

	    stopTimer();

  	

        //$('div.result-block h1').html("" + value(questions.conclusion_title));

   	    $('div.game div.result-block div.description').html("" + value(questions.conclusion_text));

   	    



   	    var r = 0;

   	    var w = '';

   	    for(i=1; i<questionCount+1;i++){

		   	var question = questions['q' + i];

   	    	w+='<div class="'+answers[i-1]+'">'+value(question.word)+'</div>';

   	    	if (answers[i-1] == 'correct') r++;

   	    }



        gameScore = (100/questionCount)*r;

//        instance.onUpdateScore(gameScore);

        $('div.game div.score').show();

        $('div.game div.time').hide();

        recalculateScore();



   	    $('div.game .result-block .word-result-block').html(w);

        if (stringToBoolean(questions.extended_results)){

            $('div.game .info_game_name').html("Game: " + statistic.game_name);

            if(stringToBoolean(questions.required_player_name)){$('div.game .info_player').html("Player: " + statistic.player);}

            else{$('div.game .info_player').hide()}

            $('div.game .info_date').html("Date: " + statistic.date);

            $('div.game .info_score').html("Score: " + statistic.game_percent + "%");

        }



        $('#game').removeClass('step-3');

        $('#game').removeClass('step-4');

        $('#game').addClass('step-5');



        if (sounds.conclusion!=null){

            tPlay(sounds.conclusion, PRIORITY_NORMAL);

        }

        else {tPlay(sounds.finish, PRIORITY_NORMAL);}

        try {

            SCOSetValue("time", gameTime);

            SCOSetValue("score", gameScore);

            SCOSetValue("completed", 1);

            SCOCommit();

        } catch (e) {

            console.error("Scorm failed -", e);

        }

        if('undefined' !==  typeof gameloader ){

            gameloader.send_results(statistic);

        }

        $(document).trigger('gameFinished',[statistic]);

    }





    /* -----------------------  STEP-4 Answers ------------------------- */

    /**

     * Show button keyboard

     */

	function keyboard(){

		var kb='';

		for (i=0; i<letter.length; i++){

			kb +='<div class="button-keypad">'+letter[i]+'</div>';

		}

		$('div.game .keyboard').html(kb);

		

	}

	

	liveFastClick('div.game div.button-keypad', function () {

        if (!$(this).hasClass('up')){

            tPlay(sounds.select, PRIORITY_LOW );

           keypadSelect(this);}

    });

    $('div.game div.button-keypad').live('hover', function () {

            tPlay(sounds.hover, PRIORITY_LOW);

    });



	

	/**

     * Show question board for index i

     * @param this button

     */

	function keypadSelect(kbutton){

        statistic.questions_time['q'+questionIndex]+= (new Date().getTime())-current_time;

        if (currentQuestionSound != null){

            tRewind(currentQuestionSound);

            currentQuestionSound = null;

        }

	   tPlay(sounds.select, PRIORITY_LOW);

       $(kbutton).addClass('up');

       

       var correct = false;

       var b =$(kbutton).text().toLowerCase();

       

       var question = questions['q' + questionIndex];



       	for(q=0; q<question.word.length; q++){

       		if (question.word[q].toLowerCase() == b) correct = true;

       	}



       if (correct) {

			$('div.game .field_of_dreams #'+b).html(b).css('border-color', '#67ddff');

			

			var edding = true;

			

			$('div.game .field_of_dreams div.word_box').each(function(){

				if ($(this).text() == ' ') edding = false;

			});

			

			if (edding) {

                tRewind(sounds.correct);

                tPlay(sounds.correct, PRIORITY_NORMAL);

				$('#game .step-4').removeClass('unanswered').addClass('answered');

	            $('div.game div.error-box').hide();

	            stopTimer();

	            $('div.game .keyboard').html('');

				$('div.game .correct-box').text('CORRECT!').show().css({color:'#1eff00', letterSpacing: '5px'});

				answers.push('correct');

                statistic.questions_answers['q' + questionIndex] = 1;

//                statistic.correct_answers++;

                statistic.correct_answers++;

			}else{statistic.correct_attempts++;}



       } else  {

       		$('div.game div.error-box span').eq(error).addClass('errors');

       		error++;

       		tRewind(sounds.incorrect);

            tPlay(sounds.incorrect, PRIORITY_NORMAL);



            if (error == max_incorrect) {

	            $('#game .step-4').removeClass('unanswered').addClass('answered');

	            stopTimer();

	            $('div.game .keyboard').html('');

       				$('div.game .field_of_dreams div.word_box').each(function(){

                           $(this).html(this.id);

       					//var eq = $(this).index();

       					//$(this).html(question.word[eq]);

       				});

       			answers.push('incorrect');

                statistic.incorrect_answers++;

		    }

            statistic.questions_answers['q' + questionIndex] = 0;

//            statistic.incorrect_answers++;

//            statistic.fail_answers++;

            statistic.incorrect_attempts++;

            }

       

    }

    



    /**

     * Show question board for index i

     * @param i

     */

    function questionShow(i) {

	    

        var question = questions['q' + i];

        

        if (!question) {

        

        finishGame();

        

        } else {



        $('div.game div.progressbar').html(i+'/'+questionCount);

        var error_box= $('div.game div.error-box')

            error_box.empty();

        if (!empty(question.incorrect_answers_max)){

            max_incorrect= Math.min(1*question.incorrect_answers_max,5);

        } else {

            max_incorrect= Math.min(1*questions.incorrect_answers_max,5);

        }

        for (i=1;i<=max_incorrect;i++){

            error_box.append("<span></span>");

        }

            error_box.show();

		

		error = 0;

		

		$('div.game .correct-box').hide();

		$('div.game div.error-box').show();



        if (!empty(question.timeout)){

            gameTime = parseInt(question.timeout)*1000;



        } else {

        gameTime = parseInt(questions.timeout)*1000;

        }

        timeout = gameTime;

	    keyboard();

	   	startTimer();

	    

        $('#game').addClass('step-4');

        

        var l ='<div class="word_wrapper">';



       	for(q=0; q<question.word.length; q++){

       		if (question.word[q] == ' ') l+='</div><div class="letter_space" ></div><div class="word_wrapper">'

       			else l+='<div class="word_box" id="'+question.word[q].toLowerCase()+'"> </div>';

        }

            l+='</div>';

        

        $('div.game .field_of_dreams').html('<span>'+l+'</span>');

        //$('.field_of_dreams span').width(question.word.length*($('.word_box').width()+8));



        var score = nvl(question.score,1); /* Question score is optional, default 1 per question */

        current_time= (new Date().getTime());

        if (statistic.questions_answers['q' + questionIndex] != 0) statistic.questions_time['q' + questionIndex] = 0;//reset question time on start/correct/fail (don't reset on incorrect)

        $('#game').data('question', question).data('score', score);



        $('.step-4').removeClass("type-multiple");

        //conditionalShow($('.question-block h1'),question.title);

        $('div.game .question-block div').html(value(question.text));

        $('div.game .question-choose').html("");

            if(!empty(question.audio)) {

                currentQuestionSound = createSound(value(question.audio), true);

                //console.log("play",currentQuestionSound);

                //currentQuestionSound.play();

                tPlay(currentQuestionSound, PRIORITY_HI);

            } else {

                currentQuestionSound = null;

            }

           removeBackgroundApply($('.question-block-wrapper'), question);

           if (!empty(question.image)) {

               var image = value(question.image);

               var removeBackground = true;

               if (!empty(question.removeBackground)) {

                   removeBackground |= stringToBoolean(value(question.removeBackground));

               }

               $('div.game .question-block-wrapper>div.question-image').css('background-image', 'url("' + parseImgPath(image, true) + '")');

           } else {

               $('div.game .question-block-wrapper>div.question-image').css('background-image', 'none');

           }

        $('#game .step-4').removeClass('answered').addClass('unanswered').removeClass('correct').removeClass('incorrect');

        

	    }

    }





    liveFastClick('div.game a.button-question-continue', function () {

        if(currentQuestionSound) {

            tRewind(currentQuestionSound);

        }

        questionIndex++;

        questionShow(questionIndex);

        recalculateScore();

    });







    /* -----------------------  STEP-5 Results ------------------------- */



    liveFastClick('div.game a.button-result-continue', function () {

        $('#game').removeClass('step-5');

        //game.resetAnimation();

        //game.start();

		window.location.reload(true);

    });



    /* ----------------- ANIMATIONS ----------------- */



    /**

     * Init canvas

     */

    this.prepareAnimationFrame = function () {

        $('div.game #animation').hide();

        $('div.game #animation .finish').hide();

    };



    /**

     * Prepare frame for animation

     */

    this.setupAnimationForQuestion = function () {

    	var l = parseInt($('div.game .dollars-block p').css('line-height'));

		if (questionIndex < 15) $('div.game .current_rate').css({top: (15*l-(questionIndex*l))+'px'});

    };

    /**

     * Run animation

     */

    this.runAnimationToQuestion = function (i, data) {



        //alert(data.answer);

/*

        $('#animation .ball').css('z-index',3).animate({left: middleX, top: middleY}, before, function() {$(this).css('z-index',zIndex)}).animate({left: x, top: y, width: targetDim, height: targetDim, opacity: fadeOut}, after);

        $('#animation .man').animate({marginLeft: shift1}, before, function() {$(this).css('background-position',man_image)}).animate({marginLeft: shift2}, after);

*/



    };



    this.resetAnimation = function () {

        this.runAnimationToQuestion(0);

        $('div.game #animation').fadeOut();

    };



    /* ----------------- TIMER ------------------- */

    this.onTimePassed = function (deltaTime) {

        gameTime-=deltaTime;

        if (timeout !=0){

            if (gameTime <= 0) {

                this.onTimeOut();

            } else {

                $('div.game div.time').html((parseFloat(gameTime) / 1000).toFixed(0));

            }

        }

    };



    this.onTimeOut = function () {

        /* PUT TIMEOUT CODE HERE IF ANY */



        stopTimer();

        tPlay(sounds.incorrect, PRIORITY_HI);

        /* finishGame(); */

        $('#game .step-4').removeClass('unanswered').addClass('answered');

        $('div.game div.error-box').hide();

        $('div.game .keyboard').html('');

        $('div.game .correct-box').text('TIME IS UP!').show().css({color:'#ff0000', letterSpacing: '3px'});

		$('div.game .field_of_dreams div.word_box').each(function(){

            $(this).html(this.id);

			//var eq = $(this).index();

			//var question = questions['q' + questionIndex];

			//$(this).html(question.word[eq]);

		});

        statistic.incorrect_answers++;

		answers.push('incorrect');



    };



    /* ----------------- SCORE ------------------- */

    this.onUpdateScore = function(score) {

        $('div.game div.score').html(score+'%');

    };



    /* -----------------------  GAME FLOW END ------------------------- */







    /* ----------------- GAME SPECIFIC LOADERS ------------------- */

    this.loadStyles = function () {

        applyDefaultStyles(design);



        if (!hoverDisable) {

            dynamicCssInstance.addCompiled("div.game .question-choose .variant:hover", design.question_button_over);

            dynamicCssInstance.addCompiled("div.game a.button:hover", design.button_over);

        }



        dynamicCssInstance.addRule("div.game .question-vertical-shift", design['margin_top_for_questions_screen'], "height: $vpx");

        dynamicCssInstance.addRule("div.game .question-feedback-vertical-shift", design['margin_top_for_questions_feedback'], "height: $vpx");



		if(!empty(design.keyboard)) {

			dynamicCssInstance.addCompiled("div.game div.keyboard", design.keyboard);

			dynamicCssInstance.addCompiled("div.game div.button-keypad", design.button_keypad);

            if(!onlyOneSound){

			    dynamicCssInstance.addCompiled("div.game div.button-keypad:hover", design.button_keypadhover);

            } else {

                dynamicCssInstance.addCompiled("div.game div.button-keypad:active", design.button_keypadhover);



            }

			dynamicCssInstance.addCompiled("div.game div.button-keypad.up", design.button_keypadup);

			

			dynamicCssInstance.addCompiled("div.game div.error-box", design.error_box);

			dynamicCssInstance.addCompiled("div.game div.error-box span", design.error_x);

			

			dynamicCssInstance.addCompiled("div.game div.field_of_dreams", design.field_of_dreams);

			dynamicCssInstance.addCompiled("div.game div.word_box", design.word_box);

			

			dynamicCssInstance.addCompiled("div.game div.correct-box", design.correct_box);

			dynamicCssInstance.addCompiled("div.game div.word-result-block", design.word_result_block);

			dynamicCssInstance.addCompiled("div.game div.word-result-block div.correct", design.word_correct);

			dynamicCssInstance.addCompiled("div.game div.word-result-block div.incorrect", design.word_incorrect);

		}



        dynamicCssInstance.addCompiled("div.game div.logo1", design.logo1);

        dynamicCssInstance.addCompiled("div.game div.logo2", design.logo2);

        dynamicCssInstance.addCompiled("div.game div.logo3", design.logo3);

        dynamicCssInstance.addCompiled("div.game div.logo4", design.logo4);



        dynamicCssInstance.addCompiled("div.game input.input_name", design.name_request_box);



        if(!empty(design.question_screen)) {

            var object = dozerMapper(design.question_screen, ["width", "height", "X", "Y", "padding", "paddingX", "paddingY","margin","marginX","marginY","marginTop","marginBottom","marginLeft","marginRight"]);

            dynamicCssInstance.addCompiled("div.game .question-choose-wrapper", object);

            dynamicCssInstance.addCompiled("div.game .question-block-wrapper", object);

            dynamicCssInstance.addCompiled("div.game .question-answered-block-wrapper", object);

        }



        if(!empty(design.question_choose_wrapper)) {

            dynamicCssInstance.addCompiled("div.game .question-choose-wrapper", design.question_choose_wrapper);

        }



        dynamicCssInstance.addCompiled("div.game .question-choose .variant", design.question_button_up);

        dynamicCssInstance.addCompiled("div.game .question-choose .variant:active", design.question_button_down);

        dynamicCssInstance.addCompiled("div.game .question-choose .variant.choosed", design.question_button_selected);



        dynamicCssInstance.addCompiled("div.game a.button", design.button_up);

        dynamicCssInstance.addCompiled("div.game a.button:active", design.button_down);

        if(!empty(design.score_box)) {

            dynamicCssInstance.addCompiled("div.game div.score", design.score_box);

        }

        if(!empty(design.timer_box)) {

            dynamicCssInstance.addCompiled("div.game div.time", design.timer_box);

        }

        if(!empty(design.scoreboard_box)) {

            dynamicCssInstance.addCompiled("div.game div.scoreboard", design.scoreboard_box);

        }



        dynamicCssInstance.addCompiled("div.game .question-answered-block-wrapper", design.question_feedback_box);

        dynamicCssInstance.addCompiled("div.game .question-block-wrapper>div.question-block-wrapper-inner", design.question_box);

        var object = dozerMapper(design.question_box, ["width", "height", "X", "Y", "padding", "paddingX", "paddingY"]);

        dynamicCssInstance.addCompiled("div.game .question-block-wrapper>div.question-image", object);

        applyDefaultQuestionBoxImage(dynamicCssInstance, design.question_box);



        dynamicCssInstance.addCompiled("div.game div.step-2-description", design.description_panel);

        dynamicCssInstance.addCompiled("div.game div.result-block-wrapper", design.result_panel);

        dynamicCssInstance.addCompiled("div.game .progressbar", design.progressbar_container);

        dynamicCssInstance.addCompiled("div.game .progressbar>div", design.progressbar_item);



        dynamicCssInstance.addCompiled("div.game .progressbar>div.answered", design.progressbar_answered_item);



        if(design.progressbar_answered_correct_item) {

            dynamicCssInstance.addCompiled("div.game .progressbar>div.answered.correct", design.progressbar_answered_correct_item);

        }

        if( design.progressbar_answered_incorrect_item) {

            dynamicCssInstance.addCompiled("div.game .progressbar>div.answered.incorrect", design.progressbar_answered_incorrect_item);

        }

        dynamicCssInstance.addRule("div.game .step-4.answered.correct .question-answered-block-wrapper h1", design.question_answer_correct_color, "color: $v");

        dynamicCssInstance.addRule("div.game .step-4.answered.incorrect .question-answered-block-wrapper h1", design.question_answer_incorrect_color, "color: $v");



        dynamicCssInstance.addRule("div.game .progressbar>div", design.progressbar_container.spacing, "margin-right: $vpx");

        dynamicCssInstance.addRule("div.game .progressbar>div:last-child", design.progressbar_container.spacing, "margin-right: 0px");



        $('div.game .step-4').addClass('vertical').removeClass('horizontal');





        dynamicCssInstance.addCompiled("div.game #step1continuebutton", design.splash_continuebutton);

        dynamicCssInstance.addCompiled("div.game #step2continuebutton", design.intro_continuebutton);

        dynamicCssInstance.addCompiled("div.game #step4continuebutton", design.question_continuebutton);

        dynamicCssInstance.addCompiled("div.game #step4confirmbutton", design.question_confirmbutton);

        dynamicCssInstance.addCompiled("div.game #step5replaybutton", design.results_replaybutton);



        var qCount = 1;

        while (!empty(questions['q' + qCount])) {

            qCount++;

        }

        qCount--;



        var paddingTMP = design.progressbar_container.paddingX || design.progressbar_container.padding || 0;

        var totalWidth = 1*value(design.progressbar_container.width)-qCount*value(design.progressbar_container.spacing) - 2*paddingTMP;

        var elementWidth = Math.floor(totalWidth/qCount);

        dynamicCssInstance.addRule("div.game .progressbar>div", elementWidth, "width: $vpx");



        dynamicCssInstance.addRule("div.game .progressbar>div", design.progressbar_item.width, "width: $vpx");





        dynamicCssInstance.flush();

    };

    this.loadSounds = function () {

        if (questions.introduction_audio != null){

            var media = createSound(questions.introduction_audio, true);



            sounds.introduction = media;

        }

        if (questions.conclusion_audio != null){

            var media = createSound(questions.conclusion_audio, true);



            sounds.conclusion = media;

        }

        if (onlyOneSound) {

            liveFastClick('.game a:not(#step4confirmbutton)', function () {

                tPlay(sounds.select, PRIORITY_LOW);

            });

            liveFastClick('.game .questions div.question:not(.answered):not(.hasOwnSound)', function () {

                tPlay(sounds.select, PRIORITY_LOW);

            });

            liveFastClick('.type-multiple .question-choose .variant', function () {

                tPlay(sounds.select, PRIORITY_LOW);

            });

        } else {

            liveFastClick('.game a, .game .questions div.question:not(.answered), .question-choose .variant', function () {

                tPlay(sounds.select, PRIORITY_LOW);

            });

            if (!hoverDisable) {

                $('.game a, .game .questions div.question:not(.answered), div.game .question-choose .variant').live('mouseenter', function () {

                    tPlay(sounds.hover, PRIORITY_LOW);

                });

            }

        }

    };

    this.loadData = function () {

        questions.randomize_question_order = stringToBoolean(questions.randomize_question_order);

        questions.randomize_answer_order = stringToBoolean(questions.randomize_answer_order);

        timeout = nvl(questions.timeout,300) * 1000;

        letter=JSON.parse(questions.keyboard_layout);



        /* FILL GAME TEXT */

        $("div.game #step1continuebutton").html("" + value(questions.splash_page_button_continue_text));

        $("div.game #step2continuebutton").html("" + value(questions.intro_page_button_continue_text));

        $("div.game #step3continuebutton").html("" + value(questions.questions_page_button_continue_text));

        $("div.game #step4continuebutton").html("" + value(questions.question_page_button_continue_text));

        $("div.game #step4confirmbutton").html("" + value(questions.question_page_button_confirm_text));

        $("div.game #step5replaybutton").html("" + value(questions.result_page_button_replay_text));

        //conditionalShow($('div.step-2-description h1'), questions.introduction_title);

        $('div.game div.step-2-description div.description div').html("" + value(questions.introduction_text));

        //$('div.step-2-description div.racer-description').html("" + value(questions.introduction_racer_description));



        //$('div.result-block h1').html("" + value(questions.conclusion_title));

        $('div.game div.result-block div.description').html("" + value(questions.conclusion_text));



        questionCount=defaultQuestionCount(questions);

    }

};



$(document).ready(function () {

    game.readConfig();

    $('.game').css('opacity', 0.1);

 

});



$(window).load(function () {



});



$(document).bind('gameLoaded', function () {

    SCOPreInitialize();

    SCOInitialize();

    $('.game').css('opacity', 1);

   

    game.start();

});