if (typeof(console) == "undefined" ) console = { log: function(value) { } };

$(document).ready(function() {
    var test;
    var startTime, estimatedTime, wpm;
    var actionURL = 'rtest.php';
    var resultURL = 'testResult.php';

    var textRulesForm = $('#test_rules');
    var testTextForm = $('#test_text');
    var questionsForm = $('#test_questions');
    var loadingImg = $('#progress');
    var wpmResultForm = $('#wpm_result');
    var questionResultForm = $('#question_result');
    var signupForm = $('#signup_form');
    var wayOfContactForm = $('#wayOfContact_holder');

    var signature = $('#signature');

    

    $('#test_start_btn').click(function() {        
        if (textRulesForm.valid()) {
            textRulesForm.hide();
            loadingImg.show();
            $('#langValue').val($.getUrlVar('lang'));

            $.post(
                actionURL,
                { language: "" + $.getUrlVar('lang'), email: $('#email').val(), test_id: "" + $.getUrlVar('test_id'), signature: "" + $.getUrlVar('signature')},
                function(data, textStatus) {
                    console.log(textStatus);
                    console.log(data);

                    if (textStatus == "success") {
                        test = data;

			testTextForm.children('.title').html(test.title);
                        testTextForm.children('.content').html(test.text);
                        testTextForm.show();
                        loadingImg.hide();

                        startTime = new Date();
                    }
                },
                "json"
            );
        }
    });

    $('#reading_stop_btn').click(function() {
        var wordsCount = testTextForm.children('.content').html().split(' ').length;
	console.log("wordsCount", wordsCount);
        estimatedTime = (new Date() - startTime)/60000;
	console.log("estimatedTime", estimatedTime);
        wpm = Math.round(wordsCount/estimatedTime);
        $('span', wpmResultForm).html(wpm);

        if (wpm < 200) $('#wpm_low').show();
        if (200 <= wpm  && wpm <=260) $('#wpm_aver').show();
        if (wpm > 260) $('#wpm_high').show();
        
        testTextForm.children('button').hide();
        wpmResultForm.show();
	$(window).scrollTop(999999);
    });

    $('#show_questions_btn').click(function() {
        testTextForm.hide();
        loadingImg.show();
        		
        $.post(
            actionURL,
            { id: test.id },
            function(data, textStatus) {				
                console.log(textStatus);
                console.log(data);

                if (textStatus == "success") {
                    $('#testID').val(test.id);
                    $('#wpmValue').val(wpm);
                    $('#userEmail').val($('#email').val());
                    $('#isEducated').val(($('#haveComplited').is(':checked"') ? 1 : 0));
                    
                    for(var qi in data) {
                        var question = data[qi];					

                        var questionHtml =
                            '<p><b>' + question.text  +'</b></p>' +
                            '<ul>';

                        for(var ai in question.answers) {
                            var answer = question.answers[ai];
                            var isTrue = (answer && answer.isTrue ? 'class="true required" ' : 'class="required" ');
                            
                            questionHtml +=
                                '<li>' +
                                    '<input ' + isTrue + 'type="radio" name="question_' + question.id + '" value="' + answer.id + '" onclick="checkAnswer(this);" />' +
                                    '<span>' + answer.text + '</span>' +
                                '</li>';

                        }
                        questionHtml += '</ul>'
			
                        questionsForm.children('.content').append(questionHtml);                        
                    }
                    
                    loadingImg.hide();
                    questionsForm.show();
					questionsForm.scrollTop(999999);
                }
            },
            "json"
        );
    });

    $('#questions_result_btn').click(function() {
        var correctAnswers = $('.right', questionsForm).length;
        var wrongAnswers =   $('.wrong', questionsForm).length;
        var totalAnswers =   $('.true', questionsForm).length;

        if (correctAnswers + wrongAnswers == totalAnswers) {
            $(this).hide();

            $('#rightAnswers').html(correctAnswers);
            $('#persComplited').html(Math.round(correctAnswers*100/totalAnswers));
            $('#totalAnswers').html(totalAnswers);
            $('#testResultValue').val(correctAnswers*100/totalAnswers);

            questionResultForm.show();
            $('#validation_summary').hide();
        } else {
            $('#validation_summary').show();
        }
	
	$(window).scrollTop(9999999);
    });

    $('#final_step_btn').click(function() {
        questionsForm.hide();
        if (test.isNew) {
            signupForm.show();
        } else {
            loadingImg.show();

            $.post(
                actionURL,
                signupForm.serializeArray(),
                function(data, textStatus) {
                    console.log(textStatus);
                    console.log(data);

                    if (textStatus == "success") {
                        loadingImg.hide();
                        window.location.href = resultURL + "?id=" + data.id + "&lang=" + data.lang + "&signature=" + data.signature;
                    }
                },
                "json"
            );
        }
    });

    $('#needTraining').click(function() {
        if (this.checked) {
            wayOfContactForm.show();
            $('#wayOfContact')[0].disabled = false;
        } else {
            $('#wayOfContact')[0].disabled = true;
            wayOfContactForm.hide();
        }        
    });

    $('#show_result_btn').click(function() {
        if (signupForm.valid()) {
            signupForm.hide();
            loadingImg.show();

            $.post(
                actionURL,
                signupForm.serializeArray(),
                function(data, textStatus) {
                    console.log(textStatus);
                    console.log(data);
                   
                    if (textStatus == "success") {
                        loadingImg.hide();
                        window.location.href = resultURL + "?id=" + data.id + "&lang=" + data.lang + "&signature=" + data.signature;
                    }
                    
                },
                "json"
            );
        }
    });
});

function checkAnswer(element) {
    var jElement = $(element);    
    var answersLi = $('input', $(element).parents('ul'));
    var isCorrect = jElement.hasClass('true');

    answersLi.each(function(index, domEl) {        
        var radioBtn = $(domEl);
        domEl.disabled = true;

        if (radioBtn.hasClass('true')) {
            if (isCorrect) {
                radioBtn.next('span').addClass('correct');
                jElement.addClass('right');                
            } else {
                radioBtn.next('span').addClass('answer');
                jElement.next('span').addClass('wrong');                
            }
        }
    });
}
