﻿/* Question and Answer List */

com.timmons.srl.qaList = function(dataManager) {

    //Declare private properties here
    var _qaListJson;
    var _currentQuestionIndex;
    var _currentQaList;
    var _qaValueList;
    var _stateManager;
    var _isInitialized;
    var _dataManager;

    // Private Methods here

    var _initialize = function(qaListJson, stateManager, dataManager) {
        //console.log("Enter qaList._initialize() in qaManager.js");
        
        //console.log("qaListJson: ", qaListJson);
        //console.log("stateManager: ", stateManager);
        
        _resetQaStep(qaListJson);

        if(dataManager){_dataManager = dataManager;};
        

        _stateManager = stateManager;

        if (!_isInitialized) {

            $('#tbxDetails').maxlength({
                'feedback': '#srlRequestDetailsMessage .charsLeft'
            });

            $('#tbxDetails').keyup(function() {
                _stateManager.setRequestDetails($(this).val());
            });

            _isInitialized = true;
        }
        
        //console.log("Exit qaList._initialize() in qaManager.js");
    };

    var _resetQaStep = function(qaListJson) {
        //console.log("Enter qaList._resetQaStep() in qaManager.js");
        
        //console.log("qaListJson: ", qaListJson);

        _currentQaList = [];
        _currentQuestionIndex = 0;
        _qaListJson = qaListJson;
        _qaValueList = [];

        $('#srlQaList').html('');

        if (_qaListJson.length > 0) _createNextQuestion(_getQaQuestionId(0));
        _checkReadyNextStep();
        
        //console.log("Exit qaList._resetQaStep() in qaManager.js");
    };

    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) {
        //console.log("Enter _qaList.getCurrentQaAnswerText() in qaManager.js");

        var answerList = _currentQaList[qIndex].ProblemQAList;
        //console.log("answerList: ", answerList);

        var questionType = _currentQaList[qIndex].QuestionType;
        //console.log("questionType: ", questionType);

        if (questionType == "YESNO" || questionType == "THISTEXT") {

            for (var i = 0; i < answerList.length; i++) {

                if (answerList[i].ANSWERID == answerId){
                    //console.log("Exit qaList._getCurrentQaAnswerText() in qaManager.js return ", answerList[i].ANSWER);
                    return answerList[i].ANSWER;
                }                    
            }
        } else { // FREETEXT or anything else
            //console.log("Exit qaList._getCurrentQaAnswerText() in qaManager.js return ", answerId);
            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) {
        //console.log("Enter qaList._renderVerifyQa() in qaManager.js");
        
        //console.log("selector: ", selector);

        //The list representing the questions for the current problem type
        //console.log("_currentQaList:", _currentQaList);
        
        //I think this is the list containing the user's responses
        var requestQa = _stateManager.getQaList();
        //console.log("requestQa:", requestQa);
        
        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);
        
        //console.log("Exit qaList._renderVerifyQa() in qaManager.js");
    };

    var _createNextQuestion = function(questionId) {
        //console.log("Enter qaList._createNextQuestion() in qaManager.js");

        

        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++;
        }
        
        //console.log("Exit qaList._createNextQuestion() in qaManager.js");
    };

    var _createNextAnswer = function(selector) {
        //console.log("Enter qaList._createNextAnswer() in qaManager.js");
        
        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
            
            if(_currentQaList[_currentQuestionIndex].ProblemQAList[0] && _currentQaList[_currentQuestionIndex].ProblemQAList[0].ANSWERID){
                answerHtml += '<input type="text" class="ui-corner-all" maxlength="250" name="srlQaAnswerInput' + _currentQuestionIndex + '" id="srlQaAnswerInput' + _currentQuestionIndex + '" answerId="'+ _currentQaList[_currentQuestionIndex].ProblemQAList[0].ANSWERID + '" />';
            }else{
                answerHtml += '<input type="text" class="ui-corner-all" maxlength="250" 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);
        
        //console.log("Exit qaList._createNextAnswer() in qaManager.js");
    };

    var _removeFromQaList = function(start, length) {
        //console.log("Enter qaList._removeFromQaList() in qaManager.js");

        _currentQaList.splice(start, length);
        _currentQuestionIndex = start;

        for (var i = start + 1; i < start + length + 1; i++) {

            $('#srlQaListList li:last').remove();
        }
        
        //console.log("Exit qaList._removeFromQaList() in qaManager.js");
    };

    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;
        _qaValueList[questionIndex].answerValue = _getCurrentQaAnswerText(questionIndex, answerValue) ;
    };

    var _bindAnswerEvents = function(selector, questionType) {
        //console.log("Enter qaList._bindAnswerEvents() in qaManager.js");

        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()) {
                            
                           _dataManager.getRLQUESTIONANSWER(answerList[i].ANSWERID, this._processQuestionAnswerTableInformation, _processQuestionAnswerTableInformation);
                            
                            //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);
                                }
                            }
                            
                            _dataManager.getRLQUESTIONANSWER($(this).attr('answerid'), this._processQuestionAnswerTableInformation, _processQuestionAnswerTableInformation);
                            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() {
                _dataManager.getRLQUESTIONANSWER($(this).attr('answerid'), this._processQuestionAnswerTableInformation, _processQuestionAnswerTableInformation);
                
                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] && answerList[0].NEXTQUESTIONID && qIndex == (_currentQaList.length - 1)){
                        _createNextQuestion(answerList[0].NEXTQUESTIONID);
                     }
                    
                }

                _changeQaValueListValue(qIndex, $(this).val());

                _checkReadyNextStep();

                _stateManager.setQaList(_qaValueList);
            });
            
            
        }
        
        //console.log("Exit qaList._bindAnswerEvents() in qaManager.js");
    };

    var _processQuestionAnswerTableInformation = function(rlQuestionAnswerInfo) {
        
        _hideAnswerInfoLinks();
        
        _addQuestionAnswerInfo(rlQuestionAnswerInfo);
        
        _addQuestionAnswerListOfLinks(rlQuestionAnswerInfo);
        
    };

    var _hideAnswerInfoLinks = function(){
    
        $('#srlAnswerInfoLinks').html('');
        $('#srlAnswerInfoLinks').hide();
    };

    var _showAnswerInfoLinks = function(level){
        //level = 0 is normal
        //level = 1 is Critical
        
        $('#srlAnswerInfoLinks').css({'background-color': 'black', 'color': 'red', 'font-size': '16pt', 'padding-left': '5px', 'padding-top': '5px', 'padding-bottom': '5px'});
        $('#srlAnswerInfoLinks').show();
    };
    
    var _addQuestionAnswerListOfLinks = function(rlQuestionAnswerInfo){
    
        if(rlQuestionAnswerInfo.PROBLEMSID == 0){
            _mapRequired = -1;
            return false;
        }
    
        if(rlQuestionAnswerInfo.ListOfLinks.length > 0){
        
            _showAnswerInfoLinks(0);
        
             var docHtml = '<ul>';
             $('#srlAnswerInfoLinks').append(docHtml);
             for (var i = 0; i < rlQuestionAnswerInfo.ListOfLinks.length; i++) {
                docHtml = '<li class="srlRequestInfoData"><a class="RLProfileLinks" href="' + rlQuestionAnswerInfo.ListOfLinks[i].URL + '" target="_blank">' + rlQuestionAnswerInfo.ListOfLinks[i].DESCRIPTION + '</a></li>';
                $('#srlAnswerInfoLinks').append(docHtml);
             }
            var docHtml = '</ul>';
             $('#srlAnswerInfoLinks').append(docHtml);
        }
    };
    
    var _addQuestionAnswerInfo = function(rlQuestionAnswerInfo){
        var docHtml = '';
        if(rlQuestionAnswerInfo.PROBLEMSID == 0){
            _mapRequired  = -1;
            return false;
        }
        
        if(rlQuestionAnswerInfo.ADDITIONALINFORMATION.length > 0){
            _showAnswerInfoLinks(0);
            
             docHtml = '</br>' + rlQuestionAnswerInfo.ADDITIONALINFORMATION + '</br>';
             
            $('#srlAnswerInfoLinks').append(docHtml);
                _showAnswerInfoLinks(1);
        }

        // STOPTYPEID	STOPTYPE
        //     1       Immediate
        //     2       Optional
        //     3       No Stop
        
        if(rlQuestionAnswerInfo.STOPTYPEID == 1)
        {
            $('#srlMap').hide();
            $('#srlContactInfo').hide();
            $('#srlVerifySubmit').hide();
            com.timmons.srl.Utility.disableSteps(3);
            com.timmons.srl.Utility.disableSteps(4);
            com.timmons.srl.Utility.disableSteps(5);
        }else{
            $('#srlContactInfo').show();
            $('#srlVerifySubmit').show();
        }
        
        // MapRequiredId	Map Required
        //    0	        Skip Map
        //    1	        Map Required
        //    2	        Map Optional
        if(rlQuestionAnswerInfo.PROBLEMSID > 0){
            _mapRequired = rlQuestionAnswerInfo.MAPREQUIRED;
        }
        
        
        if(_mapRequired == 0)
        {
            mapHide();
        }else{
            mapShow();
        }
        
        if(_mapRequired == 1)
        {
            com.timmons.srl.Utility.disableNextButton('#srlStepButtons3 .srlNextStepButton');
        }                
        if(rlQuestionAnswerInfo.MAPREQUIRED == 2)
        {
            com.timmons.srl.Utility.enableNextButton('#srlStepButtons3 .srlNextStepButton');
            $('#srlStepButtons3 .srlNextStepButton').unbind('click');
            $('#srlStepButtons3 .srlNextStepButton').click(function() {
                com.timmons.srl.Utility.enableSteps(3);
                com.timmons.srl.Utility.showStep(3);
                
                $('#srlStepButtons4 .srlNextStepButton').unbind('click');
                $('#srlStepButtons4 .srlNextStepButton').click(function() {
                    com.timmons.srl.Utility.enableSteps(4);
                    com.timmons.srl.Utility.showStep(4);
                });  
                
            });  
        }
    };    

    var _mapRequired = -1;

    function mapHide(){
        $('#srlMap').hide();
    
        //Reset the numbers on the Step Panels...
        $('#srlContactInfo .srlStepNumber').text('3');

        $('#srlVerifySubmit .srlStepNumber').text('4');   

        $('#srlStepButtons2 .srlNextStepButton').unbind('click');
        $('#srlStepButtons2 .srlNextStepButton').click(function() {
            com.timmons.srl.Utility.enableSteps(3);
            com.timmons.srl.Utility.showStep(3);
            com.timmons.srl.Utility.enableNextButton('#srlStepButtons4 .srlNextStepButton', 5);
            $('#srlStepButtons4 .srlNextStepButton').unbind('click');
            $('#srlStepButtons4 .srlNextStepButton').click(function() {
                com.timmons.srl.Utility.enableSteps(4);
                com.timmons.srl.Utility.showStep(4);
            });
            
            
        });    
        
        $('#srlStepButtons4 .srlPreviousStepButton').unbind('click');
        $('#srlStepButtons4 .srlPreviousStepButton').click(function() {
            com.timmons.srl.Utility.showStep(1);
        });        
    }
    
    function mapShow(){
        $('#srlMap').show();
        
        //Reset the numbers on the Step Panels...
        $('#srlContactInfo .srlStepNumber').text('4');

        $('#srlVerifySubmit .srlStepNumber').text('5');   

        $('#srlStepButtons2 .srlNextStepButton').unbind('click');
        $('#srlStepButtons2 .srlNextStepButton').click(function() {
            com.timmons.srl.Utility.enableSteps(2);
            com.timmons.srl.Utility.showStep(2);
            com.timmons.srl.Utility.enableNextButton('#srlStepButtons4 .srlNextStepButton', 4);
            $('#srlStepButtons4 .srlNextStepButton').unbind('click');
            $('#srlStepButtons4 .srlNextStepButton').click(function() {
                com.timmons.srl.Utility.enableSteps(4);
                com.timmons.srl.Utility.showStep(4);
            });        
        });        
    }

    var _checkReadyNextStep = function() {

        if (_isStepComplete()) {
            com.timmons.srl.Utility.enableNextButton('#srlDescribe .srlNextStepButton', 2);
            if($('#srlContactInfo .srlStepNumber').text() == '3'){
                mapHide();
            }else{
                mapShow();
            }
        }else{
            com.timmons.srl.Utility.disableNextButton('#srlDescribe .srlNextStepButton', 2);
        }

        if(_mapRequired == 0){
           
           mapHide();       
        }
        
        if(_mapRequired == 1 || _mapRequired == 2){
           mapShow();          
        }
    };

    var _isStepComplete = function() {

        if (_currentQaList.length == 0) {

            return true;

        } else if (_qaValueList[_qaValueList.length - 1].answer) {

            return true;

        } else {

            return false;
        }
    }


    var _saveData = function() {
        //console.log("Enter qaList._saveData() in qaManager.js");
        
        //console.log("qaValueList: ", _qaValueList);
        _stateManager.setQaList(_qaValueList);
        
        //console.log("Exit qaList._saveData() in qaManager.js");        
    };

    var _updateQaValueList = function() {
        //console.log("Enter qaList._updateQaValueList() in qaManager.js");
        
        //console.log("_qaValueList: ", _qaValueList);

        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, dataManager) {
            //console.log("Enter qaList.initialize() in qaManager.js");
            
            _initialize(qaListJson, stateManager, dataManager);
            
            //console.log("Exit qaList.initialize() in qaManager.js");
        },
        saveData: function() {
            //console.log("Enter qaList.saveData() in qaManager.js");
            
            _saveData();
            
            //console.log("Exit qaList.saveData() in qaManager.js");
        },
        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() {
            //console.log("Enter qaList.updateQaValueList() in qaManager.js");
            
            _updateQaValueList();
            
            //console.log("Exit qaList.updateQaValueList() in qaManager.js");
        },
        getQaValueList: function() {
            //console.log("Enter getQaValueList() in qaManager.js");
            
            //console.log("Exit qaList.getQaValueList() in qaManager.js return", _qaValueList);
            return _qaValueList;
        },
        renderVerifyQa: function(selector) {
            //console.log("Enter qaList.renderVerifyQa() in qaManager.js");
            
            _renderVerifyQa(selector);
            
            //console.log("Exit qaList.renderVerifyQa() in qaManager.js");
        },
        clear: function() {
            //console.log("Enter qaList.clear() in qaManager.js");
            
            _resetQaStep([]);
            
            //console.log("Exit qaList.clear() in qaManager.js");
        },
        isStepComplete: function() {
            //console.log("Enter qaList.isStepComplete() in qaManager.js");
            
            //console.log("Exit qaList.isStepComplete() in qaManager.js return ", _isStepComplete);
            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");
        }
    };
};
