/*
 * doUserQuiz.js
 */
 
(function($) {
    // definition
    $.fn.doUserQuiz = function($params) {
        var $defaults = {
            bad_question: 'Please tell us why you think this question is bad',
            friend_email: 'Please enter your friends email address',
            answer: 'Please choose an answer',
            rate_saved: 'Saved. Thanks!',
            saving: 'Saving...',
            name: 'Please enter your name',
            error_answer: 'Please provide at least two answers',
            error_correct_answer: 'Please select the correct answer',
            error_question: 'Please enter a question',
            error_upload: '',
            label_true: 'true',
            label_false: 'false'
        };
        var $p = $.extend($defaults, $params);
        
        var newMethods = {
            initiate_quiz: function() {
                $('#submit_answer').attr('disabled', true);
                $('input[name=answer_id]').click(function() {
                    $('#submit_answer').attr('disabled', false);
                });
                $('#qform').submit(function() { 
                    return $(this).checkAnswer();
                });
                // rate question
                $('#like-question span.yes').click(function() {
                    $(this).rateQuestion('good');
                });
                $('#like-question span.no').click(function() {
                    $(this).rateQuestion('bad');
                });
                // tell a friend and report bad question
                $('#friend').click(function() {
                    $(this).showHideBlock('#tellfriend');
                });
                $('#bad_question').click(function() {
                    $(this).showHideBlock('#badquestion');
                });
                $('#tellform').submit(function() {
                    return $(this).tellFriend();
                });
                $('#badform').submit(function() {
                    return $(this).badQuestion();
                });
            },
            initiate_create: function() {
                $('.error').css('display', 'none');
                $('#anonymous').click(function() {
                    $('#allowed, .nickname ').toggleClass('hide');
                    var checked = $(this).is(':checked') ? '' : 'checked';
                    $('#form_question .nickname input:checkbox').each(function(){
                        $(this).attr('checked', checked);
                    });
                });
                $('#qTypeID').change(function(){
                    $(this).questionType();
                });
                $(this).loadQuestion();
                $('#form_question').submit(function() {
                    return $(this).checkQuestion();
                });
            },
            showHideBlock: function(element) {
                var elemStyle = $(element).css('display') || 0;
                if (elemStyle == "none") {
                    $(element).fadeIn('slow');
                } else {
                    $(element).slideUp('fast');
                }
            },
            questionType: function() {
                if($(this).val() == "type_multiple") {
                    $('#qmultiple').css('display', 'block');
                    $('#qtf').css('display', 'none');
                    $("#qTypeID option:selected");
                } else {
                    $('#qmultiple').css('display', 'none');
                    $('#qtf').css('display', 'block');
                }
                $('#qmultiple_left .txt').attr('value', '');
                $('#qmultiple_left input[name=correct_answer]').each(function(){
                    $(this).attr('checked', 'false');
                });
            },
            badQuestion: function() {
                if ($('#reportbad').val() == "") {
                    $('#errorBadQuestion').css('display', 'block').html($p.bad_question);
                    $('#reportbad').focus();
                } else {
                    var question_id = $('#question_id').val();
                    var bad_reason = $('#reportbad').val();
                    $.post('/community/quiz/quiz_handler.html', {
                        bad_question: 1,
                        question_id: question_id,
                        bad_reason: bad_reason
                    }, function(data) {
                        $('#badquestion').fadeOut('slow');
                        $('#report_conf').fadeIn('slow');
                    });
                }
                return false;
            },
            tellFriend: function() {
                if ($('#femail').val() == "") {
                    $('#errorFriendEmail').css('display', 'block').html($p.friend_email);
                    $('#femail').focus();
                } else {
                    var femail = $('#femail').val();
                    var fmessage = $('#fmessage').val();
                    $.post('/community/quiz/quiz_handler.html', {
                        tell_a_friend: 1,
                        femail: femail,
                        fmessage: fmessage
                    }, function(data) {
                        $('#tellfriend').fadeOut('slow');
                        $('#friend_conf').fadeIn('slow');
                    });
                }
                return false;
            },
            checkAnswer: function() {
                var ans = $('input[name=answer_id]').length;
                var got_ans = false;
                for (x=0; x<ans; x++){
                    if ($('input[name=answer_id]')[x].checked){
                        got_ans = true;
                    }
                }
                if (got_ans == false) {
                    $('#errorAnswer').css('display', 'block');
                    $('#errorAnswer').html($p.answer);
                }
                return got_ans;
            },
            rateQuestion: function(rate) {
                var question_id = $('#like-question input[name=prev_question_id]').val();
                var rate_question_good = 0;
                var rate_question_bad = 0;
                if (rate == "good") {
                    rate_question_good = $(this).attr('data-rate-good');
                } else {
                    rate_question_bad = $(this).attr('data-rate-bad');
                }
                $('#like-question').html("<img src=\"/images/icons/ajax_load_black.gif\">" + $p.saving);
                $.post('/community/quiz/rate_question.html', {
                    question_id: question_id,
                    rate_question_good: rate_question_good,
                    rate_question_bad: rate_question_bad
                }, function(data) {
                    $('#like-question').html($p.rate_saved);
                });
                return false;
            },
            // create_question.html
            loadQuestion: function() {
                var type = $('#qTypeID option:selected').val();
                if (type == 'type_multiple') {
                    $('#qmultiple').css('display', 'block');
                    $('#qtf').css('display', 'none');
                    if ($p.error_upload == '') {
                        $('#qmultiple_left .txt').attr('value', '');
                        $('input[name=correct_answer]').attr('checked', false);
                    }
                    
                } else {
                    $('#qmultiple').css('display', 'none');
                    $('#qtf').css('display', 'block');
                }
            },
            checkQuestion: function() {
                var type = $('#qTypeID option:selected').val();
                var valid = true;
                var anon = $("#anonymous").is(':checked');
                var author = $("#author").attr('value');
                
                if ((anon == false) && (author == '')) {
                    $('#errorName').css('display', 'block').html($p.name);
                    $('#author').focus();
                    valid = false;
                } else {
                    $('#errorName').css('display', 'none');
                }
                if (type == "type_multiple") {
                    var correct_ans = 0;
                    var num = 0;
                    var regex = new RegExp("[A-Za-z0-9]+");
                    
                    $('#qmultiple_left input[type=radio]').each(function() {
                        if($(this).is(':checked')) {
                            correct_ans = $(this).val();
                        }
                    });
                    // Correct answer not set or has no value
                    var text_name = 'answer_text_'+correct_ans;
                    var correct_question = $('input[name='+text_name+']').val();
                    if ((correct_ans == 0) || (correct_question == '')) {
                        $('#errorCorrect').css('display', 'block').html($p.error_correct_answer);
                        valid = false;
                    } else {
                        $('#errorCorrect').css('display', 'none');
                    }
                    // Check theres at least 2 questions
                    $('#qmultiple_left input[type=text]').each(function() {
                        if($(this).val().match(regex) != null) {
                            num ++;
                        }
                    });
                    if (num < 2) {
                        $('#errorAnswers').css('display', 'block').html($p.error_answer);
                        $('#qmultiple_left input[name=answer_text_1]').focus();
                        valid = false;
                    } else {
                        $('#errorAnswers').css('display', 'none');
                    }
                } else {
                    // type = true/false
                    $('#qmultiple_left input[name=answer_text_1]').val($p.label_true);
                    $('#qmultiple_left input[name=answer_text_2]').val($p.label_false);
                    if ($('#type_true').is(':checked')) {
                        $('#qmultiple_left input[type=radio]').eq(0).attr('checked', 'true');
                    } else {
                        $('#qmultiple_left input[type=radio]').eq(1).attr('checked', 'true');
                    }
                }
                
                // Add check for upload bad_file_type / bad_file_size
                
                var question_val = $('textarea[name=question_text]').val();
                if(question_val == '') {
                    $('#errorQuestion').css('display', 'block').html($p.error_question);
                    $('textarea[name=question_text]').focus();
                    valid = false;
                } else {
                    $('#errorQuestion').css('display', 'none');
                    var validate_question = $('textarea[name=question_text]').filterNum(question_val);
                    $('textarea[name=question_text]').val(validate_question);
                }
                return valid;
            },
            filterNum: function(str) {
                re = /[?.]/g;
                return str.replace(re, "");
            }
        };
        $.each(newMethods, function(i) {
            $.fn[i] = this;
        });
        
        return this.each(function(){
            $this = $(this);
        });
    };
})(jQuery);

