
/** Common Quiz functions. ****************************************************/

//Quiz constructor
function Quiz(container, options) {



    var country = /\/(\w{2,4})\/ADS\//.exec(location.href)[1];

    var defaultoptions = {
        adid : /ADS\/(\d+)/.exec(location.href)[1],
        ajaxurl : '/' + country + '/ajax/quiz',
        ajaxurl_setintro : '/' + country + '/ajax/setintro',
        advance_type     : 'standard'
    };

    this.container = container;
    this.options   = options;
    for (var i in defaultoptions) {
        if (typeof this.options[i] == 'undefined') {
            this.options[i] = defaultoptions[i];
        }
    }

    this.loading   = [];
    this.lastdata  = {};
    this.fireEvent('construct', this);

    this.quizclick();

}

Quiz.prototype.createMarkup = function(data, ord) {

    var html = "<div id='quiz'>";
    html+= "<div id='quiz_counter'>";
    if (typeof this.options.text != 'undefined' && typeof this.options.text.counter != 'undefined') {
        var cnt = this.options.text.counter;
        cnt = cnt.replace(/%ord/i, ord + 1);
        cnt = cnt.replace(/%total/i, this.options.total);
        html+= cnt;
    }
    else {
        html+= (ord * 1 + 1) + '/' + this.options.total;
    }
    html+= "</div>";
    html+= "<input type='hidden' name='quiz_question_id' id='quiz_question_id' value='"+ data.id +"'>";
    html+= "<div id='quiz_question'>"+ data.text +"</div>";
    for (var i=0, le=data.item.length; i < le; i++) {
        html+= "<div class='quiz_answer'><input type='radio' name='qz_answer' id='"+ data.item[i].id +"'/><label for='"+ data.item[i].id +"'>"+data.item[i].text+"</label></div>";
    }
    html+= "<a id='quiz_next'>";
    if (typeof this.options.text != 'undefined' && typeof this.options.text.next != 'undefined') {
        html+= this.options.text.next;
    }
    html+= "</a>";
    html+= "</div>";
    return html;

};

/**
 * Sets up event handlers on already created markup.
 * Needs to be called after the markup is created.
 */
Quiz.prototype.setupAdvance = function(ord) {
//    console.log('setupAdvance');
//    console.log(this.options.advance_type);
    //save this for the closures
    var _this = this;
    var parts = this.options.advance_type.split(' ');

    if (parts[0] == 'standard') {
        //usual operation - clicking on the label or radio button will load next question
        //shit IE will not fire click on input if it is hidden, so we need click handler both on
        //label and on input, and avoid them to submit twice
        $('#quiz label').click(function() {
            var lastanswer = $(this).parent().find('input').attr('id');
            _this.advance(ord, lastanswer);
            //this is to avoid the input click event
            //might cause input not being marked when clicked label, but avoids duplication of click event
            return false;
        });
        $('#quiz input').click(function() {
            _this.advance(ord);
        });
    }
    else if (parts[0] == 'buttonpress') {
        //advance happens when clicking on next button, if a radio is selected
        $('#quiz_next').click(function() {
            _this.advance(ord);
        });
    }

   
};

Quiz.prototype.submitHelpForm = function() {

    var country = /\/(\w{2,4})\/ADS\//.exec(location.href)[1];
    var parts = $('#quiz_question_id').val().split('-');
    $.ajax({
        type: "GET",
        url: '/'+ country + '/ADS/' + quiz_support_adid + '/submit?questionId=' + parts[1] + '&msisdn=' + $('#msisdnQuizSupport').val(),
        data: "",
        success: function(result){
            $('#quizSupportForms').html(result);
            $('#quizSupportForms').show();
        },
        error: function(){
            $('#quizSupportForms').html ('<div id="quizSupportError"><div id="closeHelp"></div>	<div id="nextQuizSupport"></div></div>' );
        }
    });

     $('#inputBox').val($('#msisdnQuizSupport').val());
     $('#inputBox').css('display','none');
     
     $('#enterphone_new_label').css('display','block');
     $('#enterPhone label').css('display','none');

};

Quiz.prototype.showHelpForm = function() {

    var country = /\/(\w{2,4})\/ADS\//.exec(location.href)[1];

    $.get('/ajax/quizsupport/' + country + '/' + quiz_support_adid , '', function(result) {

        $('#quizSupportForms').html(result);
        $('#quizSupportForms').show();
    });

};

//get the next question
Quiz.prototype.advance = function(ord, lastanswer) {
    if (!lastanswer) {
        //check if any radio is selected
        lastanswer = $('#quiz input:checked').attr('id');
    }
    if (!lastanswer) {
        return false;
    }
    var parts = this.options.advance_type.split(' ');
    if (parts[1] == 'checkanswer' && !this.checkAnswer(lastanswer)) {
        return false;
    }

    //disable the old question until the new one loads
    $('#quiz').addClass('disabled');
    this.showQuestion(ord + 1, lastanswer);


};


//this function is used to call Quiz support Service forms
//it provides us to e able to fire click events for elements in QuizSuportForms
Quiz.prototype.quizclick = function(){
    var _this = this;
    
     //show Quiz Support form
    $('#quizSupportHTML').live("click",function() {
            _this.showHelpForm();
    });

    //Close button for Support Forms
    $('#closeHelp').live("click", function() {
        $('#quizSupportForms').hide();
    });

    //Close button for Support Forms
    $('#nextQuizSupport').live("click", function() {
        $('#quizSupportForms').hide();
        $('#quizSupportOK').hide();
    });

   //Close button for Support Forms
    $('#submitButtonQuizSupport').live("click", function() {

        //validate number with javascript
        if (validateQuizSupportForm()){

             _this.submitHelpForm();

        }else{
            $('#msisdnQuizSupport').focus();
        }

    });


}

Quiz.prototype.checkAnswer = function(lastanswer) {
    for (var i = 0, le = this.lastdata.item.length; i < le; i++) {
        if (this.lastdata.item[i].id == lastanswer) {
            if (this.lastdata.item[i].score == 0) {
                if (typeof this.options.text != 'undefined' && typeof this.options.text.wrong_answer != 'undefined') {
                    this.showAlert(this.options.text.wrong_answer);
                }
                return false;
            }
            break;
        }
    }
    return true;
}

Quiz.prototype.showForm = function() {
    $('#quiz').hide();
    $('#form').show();
    $('#inputBox').focus();
    if (typeof javaBaby == "function") {
        javaBaby();
    }
};

//normally you should override this
Quiz.prototype.showAlert = function(text) {
    alert(text);
};

Quiz.prototype.showQuestion = function(ord, lastanswer) {
    if (this.loading[ord] == 1) {
        //there is already an ajax request loading this question
        return false;
    }
    //alert('showQuestion');
    this.loading[ord] = 1;
    var postdata = {};
    postdata.adid = this.options.adid;
    postdata.ord  = ord;
    if (typeof lastanswer != 'undefined') {
        postdata.lastanswer = lastanswer;
    }

    //save this for the closure
    var _this = this;

    if (_this.options.ajaxurl) {
        $.ajax({
            url : _this.options.ajaxurl,
            data : postdata,
            dataType : 'json',
            type : 'POST',
            error: function() {
                _this.showForm();
            },
            success: function(data) {

                //console.log(data);
                //clean up loading status
                _this.loading[ord] = 0;
                if (!data) {
                    //no more questions - go to the form
                    _this.showForm();
                    return;
                }
                _this.lastdata = data;
                var tmp = _this.createMarkup(data, ord);
                //console.log(tmp);
                if ($('#quiz').get(0)) {
                    //if already exists, replace it
                    $('#quiz').replaceWith(tmp);
                }
                else {
                    $(_this.container).append(tmp);
                }
                _this.setupAdvance(ord);
            }
        });
    }
};


/**
 * To fire callback hooks on custom events, passing them the object of the event.
 * @author adam
 * @param evt The type of event
 * @param obj The object of the event. (can be an id, a string, an object, whatever is most relevant)
 */
Quiz.prototype.fireEvent = function(evt, obj) {
    //console.log("Firing event: " + evt);
    if (typeof this.options.callbacks == 'undefined') {return;}
    if (typeof this.options.callbacks[evt] == 'function') {
        return this.options.callbacks[evt](obj);
    }
    else if (typeof this.options.callbacks[evt] == 'string') {
        //check the global space
        if (typeof window[this.options.callbacks[evt]] == 'function') {
            return window[this.options.callbacks[evt]](obj);
        }
    }

};


Quiz.prototype.setIntroContent = function(intro) {
    var postdata = {};
    postdata.adid  = this.options.adid;
    postdata.intro = intro;

    //save this for the closure
    var _this = this;

    if (_this.options.ajaxurl_setintro) {
        $.ajax({
            url : _this.options.ajaxurl_setintro,
            data : postdata,
            dataType : 'html',
            type : 'POST',
            success: function(data) {
                //do nothing
            }
        });
    }
};


//@todo: Mesut: needs to be re-moved to QuizSupportService template
function validateQuizSupportForm() {
    if (!validateNumeric($('#msisdnQuizSupport').val()) || $('#msisdnQuizSupport').val().length < $('#msisdnQuizSupport').attr("maxlength")) {
        errorQuizSupportMsg();
        return false;
    } else {
        return true;
    }
}

function validateNumeric(strValue){
	var objRegExp  = /^\d+$/;
	return objRegExp.test(strValue);
}


function errorQuizSupportMsg(){
	$("#incorrectPhoneErrorQuizSupport").fadeIn();
}

