﻿/* Question and Answer List */

com.timmons.srl.qaList = function() {

    //Declare private properties here
    var _qaListJson;
    var _currentQuestionIndex;
    var _currentQaList;
    var _qaValueList;
    var _stateManager;
    var _isInitialized;

    // Private Methods here

    var _initialize = function(qaListJson, stateManager) {

        _resetQaStep(qaListJson);

        _stateManager = stateManager;

        if (!_isInitialized) {

            $('#tbxDetails').maxlength({
                'feedback': '#srlRequestDetailsMessage .charsLeft'
            });

            $('#tbxDetails').keyup(function() {
                _stateManager.setRequestDetails($(this).val());
            });

            _isInitialized = true;
        }
    };

    var _resetQaStep = function(qaListJson) {

        _currentQaList = [];
        _currentQuestionIndex = 0;
        _qaListJson = qaListJson;
        _qaValueList = [];

        $('#srlQaList').html('');

        if (_qaListJson.length > 0) _createNextQuestion(_getQaQuestionId(0));
        _checkReadyNextStep();
    };

    var _getQaArrayPosition = function(questionId) {

        for (var i = 0; i < _qaListJson.length; i++) {

            if (_qaListJson[i].QUESTIONID == questionId) {

                return i;
            }
        }

        return null;
    };

    var _getCurrentQaAnswerText = function(qIndex, answerId) {

        var answerList = _currentQaList[qIndex].ProblemQAList;

        var questionType = _currentQaList[qIndex].QuestionType;

        if (questionType == "YESNO" || questionType == "THISTEXT") {

            for (var i = 0; i < answerList.length; i++) {

                if (answerList[i].ANSWERID == answerId) return answerList[i].ANSWER;
            }
        } else { // FREETEXT or anything else

            return answerId;
        }
        
        //console.log("Exit _qaList.getCurrentQaAnswerText() in qaManager.js return:", null);
        return null;        
    };

    var _getQaQuestionId = function(arrayPos) {

        return _qaListJson[arrayPos].QUESTIONID;
    };

    var _renderVerifyQa = function(selector) {

        var requestQa = _stateManager.getQaList();

        var html = '';

        if (requestQa && _currentQaList) {

            for (var i = 0; i < requestQa.length; i++) {

                html += '<div class="srlVerifyLabel">' + _currentQaList[i].QUESTION + '</div><div class="srlVerifyValue">' + _getCurrentQaAnswerText(i, requestQa[i].answer) + '</div><div class="clear"></div>';
            }
        }

        $(selector).html(html);
    };

    var _createNextQuestion = function(questionId) {

        var origQaListIndex = _getQaArrayPosition(questionId);

        if (_currentQuestionIndex < _qaListJson.length) {

            _currentQaList[_currentQuestionIndex] = _qaListJson[origQaListIndex];

            _addToQaValueList(_currentQaList[_currentQuestionIndex].QUESTIONID, null);

            if (_currentQuestionIndex == 0) {

                var ol = '<ol id="srlQaListList"></ol>';
                $('#srlQaList').html(ol);
            }

            var li = '<li><div class="srlQaWrapper"><label class="srlQaQuestion">' + _currentQaList[_currentQuestionIndex].QUESTION + '</label></div></li>';

            $('#srlQaListList').append(li);

            var lastQuestionWrapper = $('#srlQaListList li:last .srlQaWrapper');

            _createNextAnswer(lastQuestionWrapper);

            lastQuestionWrapper.show('slow');

            _currentQuestionIndex++;
        }
    };

    var _createNextAnswer = function(selector) {

        var answerHtml = '<div class="srlQaAnswer">';

        var questionType = _currentQaList[_currentQuestionIndex].QuestionType;

        if (questionType == "YESNO" || questionType == "THISTEXT") {

            answerHtml += '<select name="srlQaAnswerInput' + _currentQuestionIndex + '" id="srlQaAnswerInput' + _currentQuestionIndex + '" >';

            var answerList = _currentQaList[_currentQuestionIndex].ProblemQAList;

            answerHtml += '<option value="">Please Select</option>';

            for (var i = 0; i < answerList.length; i++) {

                answerHtml += '<option value="' + answerList[i].ANSWERID + '">' + answerList[i].ANSWER + '</option>';
            }

            answerHtml += '</select>';

        } else { // FREETEXT, UNKNOWN or anything else

            answerHtml += '<input type="text" class="ui-corner-all" name="srlQaAnswerInput' + _currentQuestionIndex + '" id="srlQaAnswerInput' + _currentQuestionIndex + '" />';
        }

        // need to handle link at some point

        answerHtml += '</div>';

        selector.append(answerHtml);

        selector.find('select').selectmenu({ style: 'dropdown', maxHeight: 200, width: 200 }); // modified selectmenu core code to account for handle

        _bindAnswerEvents(selector, questionType);
    };

    var _removeFromQaList = function(start, length) {

        _currentQaList.splice(start, length);
        _currentQuestionIndex = start;

        for (var i = start + 1; i < start + length + 1; i++) {

            $('#srlQaListList li:last').remove();
        }
    };

    var _getAnswerArrayPosition = function(answerList, answerValue) {

        for (var i = 0; i < answerList.length; i++) {

            if (answerList[i].ANSWERID == answerValue) return i;
        }
    };

    var _removeFromQaValueList = function(start, length) {

        _qaValueList.splice(start, length);
    };

    var _addToQaValueList = function(questionId, answerValue) {
        //console.log("Enter qaList._addToQaValueList() in qaManager.js");

        //var length = _qaValueList.length;

        //eval('(' + myJSONtext + ')');

        //var myJSONtext = '{"question" : ' + questionId + ', "answer" : ' + answerValue + '}';

        //_qaValueList.push(eval('(' + myJSONtext + ')'));

        //_qaValueList[length].question = questionId;
        //_qaValueList[length].answer = answerValue;
        
        _qaValueList.push({question : questionId,answer : answerValue});
        //console.log("_qaValueList: ", _qaValueList);
        
        //console.log("Exit qaList._addToQaValueList() in qaManager.js");
    };

    var _changeQaValueListValue = function(questionIndex, answerValue) {

        _qaValueList[questionIndex].answer = answerValue;
    };

    var _bindAnswerEvents = function(selector, questionType) {

        var answerList = _currentQaList[_currentQuestionIndex].ProblemQAList;

        var qIndex = _currentQuestionIndex;

        if (questionType == "YESNO" || questionType == "THISTEXT") {

            $('#srlQaAnswerInput' + qIndex).change(function() {

                // need to remove all questions after.

                if ($(this).val() == '') {

                    _removeFromQaList(qIndex + 1, _currentQaList.length - qIndex - 1);
                    _removeFromQaValueList(qIndex + 1, _qaValueList.length - qIndex - 1);

                } else {

                    for (var i = 0; i < answerList.length; i++) {

                        if (answerList[i].ANSWERID == $(this).val()) {

                            //only execute if the next question has changed based on the answer

                            var currentNextQuestion = null;

                            if (_qaValueList[qIndex].answer)
                                currentNextQuestion = answerList[_getAnswerArrayPosition(answerList, _qaValueList[qIndex].answer)].NEXTQUESTIONID;

                            if (answerList[i].NEXTQUESTIONID != currentNextQuestion) {

                                _removeFromQaList(qIndex + 1, _currentQaList.length - qIndex - 1);
                                _removeFromQaValueList(qIndex + 1, _qaValueList.length - qIndex - 1);

                                if (answerList[i].NEXTQUESTIONID) {

                                    _createNextQuestion(answerList[i].NEXTQUESTIONID);
                                }
                            }
                            break;
                        }
                    }
                }

                _changeQaValueListValue(qIndex, $(this).val());

                _checkReadyNextStep();

                _stateManager.setQaList(_qaValueList);
            });

        } else { // FREETEXT, UNKNOWN or anything else


            $('#srlQaAnswerInput' + _currentQuestionIndex).blur(function() {

                var newAnswer = jQuery.trim($(this).val());
                $(this).val(newAnswer);
            });

            $('#srlQaAnswerInput' + _currentQuestionIndex).bind("blur keyup", function() {

                if ($(this).val() == '') {

                    // need to remove all questions after
                    _removeFromQaList(qIndex + 1, _currentQaList.length - qIndex - 1);
                    _removeFromQaValueList(qIndex + 1, _qaValueList.length - qIndex - 1);

                } else {

                    if (answerList[0].NEXTQUESTIONID && qIndex == (_currentQaList.length - 1)) _createNextQuestion(answerList[0].NEXTQUESTIONID);
                }

                _changeQaValueListValue(qIndex, $(this).val());

                _checkReadyNextStep();

                _stateManager.setQaList(_qaValueList);
            });
        }
    };

    var _checkReadyNextStep = function() {

        if (_isStepComplete()) com.timmons.srl.Utility.enableNextButton('#srlDescribe .srlNextStepButton', 2);
        else com.timmons.srl.Utility.disableNextButton('#srlDescribe .srlNextStepButton', 2);
    };

    var _isStepComplete = function() {

        if (_currentQaList.length == 0) {

            return true;

        } else if (_qaValueList[_qaValueList.length - 1].answer) {

            return true;

        } else {

            return false;
        }
    }

    var _saveData = function() {

        _stateManager.setQaList(_qaValueList);
    };

    var _updateQaValueList = function() {

        for (var i = 0; i < _qaValueList.length; i++) {

            //_qaValueList[i].answer = $('#srlQaAnswerInput' + i).val();
            
            var nodeList = $('#srlQaAnswerInput' + i);
            if(nodeList.length > 0){
                _qaValueList[i].answer = nodeList.val();
            }
        }
        
        //console.log("_qaValueList: ", _qaValueList);
        
        //console.log("Exit qaList._updateQaValueList() in qaManager.js");
    };
    
    var _setCurrentQaList = function(currentQaList){
        //console.log("Enter qaList._setCurrentQaList() in qaManager.js");
        
        _currentQaList = currentQaList;
        
        //console.log("Exit qaList._setCurrentQaList() in qaManager.js");
    }
    
    var _setQaValueList = function(qaValueList){
        //console.log("Enter qaList._setQaValueList() in qaManager.js");
        
        _qaValueList = qaValueList;
        
        //console.log("Exit qaList._setQaValueList() in qaManager.js");
    }

    return {
        //Declare public properties here
        //Declare public methods here
        initialize: function(qaListJson, stateManager) {

            _initialize(qaListJson, stateManager);
        },
        saveData: function() {
            
            _saveData();
        },
        addToQaValueList: function(questionId, answerValue){
            //console.log("Enter qaList.addToQaValueList() in qaManager.js");
            
            _addToQaValueList(questionId, answerValue);
            
            //console.log("Exit qaList.addToQaValueList() in qaManager.js");
        },        
        updateQaValueList: function() {
            
            _updateQaValueList();
        },
        getQaValueList: function() {

            return _qaValueList;
        },
        renderVerifyQa: function(selector) {

            _renderVerifyQa(selector);
        },
        clear: function() {
            
            _resetQaStep([]);
        },
        isStepComplete: function() {

            return _isStepComplete();
        },
        setCurrentQaList: function(currentQaList){
            //console.log("Enter qaList.setCurrentQaList() in qaManager.js");
            
            _setCurrentQaList(currentQaList);
            
            //console.log("Exit qaList.setCurrentQaList() in qaManager.js");
        },
        setQaValueList: function(qaValueList){            
            //console.log("Enter qaList.setQaValueList() in qaManager.js");
        
            _setQaValueList(qaValueList);            
            
            //console.log("Exit qaList.setQaValueList() in qaManager.js");
        }
    };
};
