/* $Id: assessmentItemResult.js 59330 2010-05-11 11:46:13Z johnarne $ */

var initializationStack = [];
var hintsByQuestionId = [];
var hotspots = [];
var correctResponses = [];
var questionInfoObjects = [];

itemSessionStatus = ['initial', 'pendingSubmission', 'pendingResponseProcessing', 'final'];


var debugOutput = '';
if(document.getElementById("debugOutput")){
    debugOutput = document.getElementById("debugOutput").innerHTML;
}

function runInit(){
    if(initializationStack && initializationStack.length > 0){

        for(var i =0; i< initializationStack.length;i++){
            //alert("runInit "+initializationStack[i]);
            if(!initializationStack[i].hasBeenRun){
                initializationStack[i].call();
                initializationStack[i].hasBeenRun = true;
            }
            initializationStack[i] = null;
        }
        initializationStack = [];
//        alert('runInit ' +initializationStack.length);
    }
}

function addInitializationScript(argFunction){
    //alert('addInitializationScript'+ initializationStack.length+' '+argFunction);
    initializationStack[initializationStack.length] = argFunction;
}

function LZ(x) { return (x>=10||x<0?"":"0") + x }

Date.prototype.ISOlocaltimeStr =
  new Function("  /* Date.ISOlocaltimeStr hh:mm:ss */\n" +
    "  with (this)\n    return" +
    " LZ(getHours())+':'+LZ(getMinutes())+':'+LZ(getSeconds())")

Date.prototype.ISOlocaldateStr =
  new Function("  /* Date.ISOlocaldateStr YYYY-MM-DD */\n" +
    "  with (this)\n    return " +
    "getFullYear()+'-'+LZ(getMonth()+1)+'-'+LZ(getDate())")

Date.prototype.ISOlocalDTstr =
  new Function("  /* Date.ISOlocalDTstr YYYY-MM-DD'T'hh:mm:ss */\n" +
    "   with (this) return " +
    "ISOlocaldateStr()+'T'+ISOlocaltimeStr()")



function getDatestamp(){
    var d = new Date();

    return d.ISOlocalDTstr();
}


/** Based on the structure from QTI21 report.xml */
function getItemResultXML(questionId){
    var qIO = questionInfoObjects[questionId];
    var _assessmentTracker = getAssessmentTracker();
    var _sequenceIndex = 1;
    if(_assessmentTracker != null){
        var jsItem = _assessmentTracker.questions[questionId];
//        alert(jsItem);
//        alert(jsItem.sequenceIndex);
        _sequenceIndex = jsItem.sequenceIndex;
    }
    if (typeof qIO === 'undefined' || qIO.resetMe) {
        // TODO: include numAttempts = 0 and duration = 0?
        return '\n<itemResult identifier="'+questionId+'" sequenceIndex="'+_sequenceIndex+(noQtiTimeRecording?'':('" datestamp="'+getDatestamp()))+'" sessionStatus="'+itemSessionStatus[0]+'"/>';
    }
    
    if(_assessmentTracker == null ){ // acoqti-43 : not setting final for all questions in 'individual mode (only when answer-button is pressed)
        qIO.sessionStatus = itemSessionStatus[3]; // PGS-205, to be able to determine when we want feedback or continuation of assessment
    }
//    alert("getItemResultXML questionInfo.sessionStatus="+questionInfo.sessionStatus);
    var iR_XML = '\n<itemResult identifier="'+questionId+'" sequenceIndex="'+_sequenceIndex+(noQtiTimeRecording?'':('" datestamp="'+getDatestamp()))+'" sessionStatus="'+qIO.sessionStatus+'">';
    iR_XML += getNumAttemptsXML(questionId);
    if (!noQtiTimeRecording) iR_XML += getDurationXML(questionId);
    if(typeof submissionMode != 'undefined' && submissionMode == 'individual' && (qIO.sessionStatus != itemSessionStatus[3])){
        // ACOQTI-43 dont submit responses unless user has submitted individually 
    }else{
        iR_XML += getHintsResponseVariableXML( hintsByQuestionId[questionId]);
        iR_XML += getResponseVariablesXML(qIO);
    }
/*lbg 2007-04-17:letting the general evaluation template do this        itemResultXML += getHintsScoreXML(questionId);*/
    iR_XML += '\n</itemResult>';

    return iR_XML;
}
function getResponseVariablesXML(qIO){
    if(!qIO.responseVariables || qIO.responseVariables.length == 0){
        //alert('getResponseVariablesXML ingen responseVariables');
        return '';
    }
    var theXML = '';
    for(var i =0; i< qIO.responseVariables.length; i++){
        var _rV = qIO.responseVariables[i];
//        alert('getResponseVariablesXML respVar.interactionType '+_rV.interactionType);
        if (_rV.interactionType == 'hotspotInteraction' || _rV.interactionType == 'gapMatchInteraction' ||
                   _rV.interactionType == 'graphicGapMatchInteraction' || _rV.interactionType == 'customInteraction') {
            theXML += getFlexappAllResponsesXML(qIO.questionId);
        }else if(_rV.interactionType == 'extendedTextInteraction'){

            theXML += '\n<responseVariable identifier="'+_rV.identifier+'" cardinality="'+_rV.cardinality+'" baseType="'+_rV.baseType+'">';
            theXML += '\n<candidateResponse>';
            theXML += '\n<value>'+document.getElementById(_rV.ident).value+'</value>';
            theXML += '\n</candidateResponse>';
            theXML += '\n</responseVariable>';
        }else if(_rV.interactionType == 'choiceInteraction' || _rV.interactionType == 'inlineChoiceInteraction'){

            theXML += '\n<responseVariable identifier="'+_rV.identifier+'" cardinality="'+_rV.cardinality+'" baseType="'+_rV.baseType+'" choiceSequence="'+_rV.choiceSequence+'">';
            theXML += '\n<candidateResponse>';
            if(_rV.interactionType == 'inlineChoiceInteraction'){
                var selectbox = $(qIO.questionId+'_'+_rV.identifier)
//                alert('ja '+ selectbox[selectbox.selectedIndex].id);
                theXML += '\n<value>'+selectbox[selectbox.selectedIndex].id+'</value>';
            }else if(_rV.userAnswers){
                for(var j = 0; j < _rV.userAnswers.length;j++){
                    theXML += '\n<value>'+_rV.userAnswers[j]+'</value>';
                }
            }
            theXML += '\n</candidateResponse>';
            theXML += '\n</responseVariable>';
        }else if(_rV.interactionType == 'matchInteraction'){
        	if(typeof qIO.flexApp != 'undefined'){
        		theXML += getFlexappAllResponsesXML(qIO.questionId);
        	}else{
        		theXML += getMatchInteractionResponse(qIO.questionId, _rV);
        	}
        }else if (_rV.interactionType == 'textEntryInteraction'){
//            alert('textEntryInteraction respVar.identifier='+respVar.identifier+" value="+$(respVar.identifier).value);
            var htmlValue = legalXMLString($(qIO.questionId+'_'+_rV.identifier).value);
            if(_rV.baseType == 'float'){
                var htmlValueFloat = ''+htmlValue;
                htmlValueFloat = htmlValueFloat.replace(',', '.');
//                alert("regexp "+REGEXP_FLOAT.test(htmlValueFloat));
                if( htmlValue != '' && typeof REGEXP_FLOAT !== 'undefined' && !REGEXP_FLOAT.test(htmlValueFloat)){
                    alert(getCaption("INVALID_FLOAT")+": "+htmlValue);
                    throw 'INVALID_FLOAT';
                }
            }
            theXML += '\n<responseVariable identifier="'+_rV.identifier+'" cardinality="'+_rV.cardinality+'" baseType="'+_rV.baseType+'">';
            theXML += '\n<candidateResponse>';
            theXML += '\n<value>'+htmlValue+'</value>';
            theXML += '\n</candidateResponse>';
            theXML += '\n</responseVariable>';
            theXML += clickWordSpecial(qIO, _rV);
        }else if(_rV.interactionType == 'orderInteraction'){
            var choiceSequenceAttr = '';
            if(_rV.choiceSequence && _rV.choiceSequence.length > 0){
                choiceSequenceAttr = ' choiceSequence="'+_rV.choiceSequence+'"';
            }
            theXML += '\n<responseVariable identifier="'+_rV.identifier+'" cardinality="'+_rV.cardinality+'" baseType="'+_rV.baseType+'"'+choiceSequenceAttr+'>';
            theXML += '\n<candidateResponse>';
            if (_rV.userAnswers) {
                for(var k = 0; k < _rV.userAnswers.length;k++){
                    theXML += '\n<value>'+_rV.userAnswers[k]+'</value>';
                }
            }
            theXML += '\n</candidateResponse>';
            theXML += '\n</responseVariable>';
        }else{
            alert('Ukjent interactionType');
        }
    }
//    try{
//        flexAppCommon.resetQuestionData();
//    }catch(err){
//
//    }
    return theXML;
}


/** Keep the id of the word to enable resume. (Just the string does not seem sufficient as same string may be sparate
 * instances.)
 * @param questionInfo
 * @param respVar
 */
clickWordSpecial = function(questionInfo, respVar){
    var field = $(questionInfo.questionId+'_'+respVar.identifier+'_wordId');
    var theXML = '';
    if(field){
        theXML += '\n<responseVariable identifier="'+respVar.identifier+'_wordId" cardinality="'+respVar.cardinality+'" baseType="'+respVar.baseType+'">';
        theXML += '\n<candidateResponse>';
        theXML += '\n<value>'+legalXMLString(field.value)+'</value>';
        theXML += '\n</candidateResponse>';
        theXML += '\n</responseVariable>';
    }
    return theXML;
}


getMatchInteractionSelected = function(questionId, respVar){
    var tbl = $(questionId+'_'+respVar.identifier+'_table');
    var a_Resp = getDescendantsByClassName(questionId+'_'+respVar.identifier+'_selected', tbl);
    var sel_Resp = []
    for(var i = 0;i< a_Resp.length;i++){
        if(a_Resp[i].checked){
            sel_Resp[sel_Resp.length] = a_Resp[i];
        }
    }
    return sel_Resp;
}


getMatchInteractionResponse = function(questionId, respVar){
    var theXML = '';
    theXML += '\n<responseVariable identifier="'+respVar.identifier+'" cardinality="'+respVar.cardinality+'" baseType="'+respVar.baseType+'" choiceSequence="'+respVar.choiceSequence+'">';
    theXML += '\n<candidateResponse>';

    var correctResponses = getMatchInteractionSelected(questionId, respVar);
    for(var i = 0;i< correctResponses.length;i++){
        theXML += '\n<value>'+correctResponses[i].value+'</value>';
    }
    theXML += '\n</candidateResponse>';
    theXML += '\n</responseVariable>';

    return theXML;
}


function getNumAttemptsXML(questionId){
    var s_XML = '\n<responseVariable identifier="numAttempts" cardinality="single" baseType="integer">';
    s_XML += '\n<candidateResponse>';
    s_XML += '\n<value>'+questionInfoObjects[questionId].numAttempts+'</value>';
    s_XML += '\n</candidateResponse>';
    s_XML += '\n</responseVariable>';

    return s_XML;
}


function getDurationXML(questionId){
    var duration =0;
    if(getAssessmentTracker() != null){
        duration = questionInfoObjects[questionId].duration
    }else{
        duration = (new Date()).getTime() - questionInfoObjects[questionId].attemptStart;
        if(questionInfoObjects[questionId].duration){
            duration += questionInfoObjects[questionId].duration;
        }
    }
//    alert('duration questionid:'+questionId+' duration:'+duration);
    var s_XML = '\n<responseVariable identifier="duration" cardinality="single" baseType="duration">';
    s_XML += '\n<candidateResponse>';
    s_XML += '\n<value>'+duration+'</value>';
    s_XML += '\n</candidateResponse>';
    s_XML += '\n</responseVariable>';

    return s_XML;
}

/*
isQuestionAttemptedNoFinish = function(questionId){
    // pgs-335 : introduced as 'addParam("onclick", "setSelectedDrapogslipp' on swfobject doesn't seem to work in ie
    var isIt = isQuestionAttemptedx(questionId);
    //alert(isIt+' questionId '+questionId);
    return isIt;
}
*/

isQuestionAttempted = function(questionId){
    // pgs-335 : introduced as 'addParam("onclick", "setSelectedDrapogslipp' on swfobject doesn't seem to work in ie
    var isIt = isQuestionAttemptedx(questionId);
    //alert(isIt+' questionId '+questionId);
    if(isIt){
        if(typeof submissionMode != 'undefined' && submissionMode == "individual"){
            var qIO = questionInfoObjects[questionId];
            if (!(typeof qIO === 'undefined' ||qIO.resetMe) && qIO.sessionStatus == itemSessionStatus[3])  setFinished(questionId);
        }else setFinished(questionId);
    }
    return isIt;
}

isQuestionAttemptedx = function(questionId){
    var qIO = questionInfoObjects[questionId];
    if (typeof qIO === 'undefined' ||qIO.resetMe) return false;
    if(qIO.sessionStatus != itemSessionStatus[0]){
        return true;
    }
    if(qIO.flexApp){

        var l_userResponses = [];

        if(!qIO.localResult){
            //alert("ikke localresult");   //usually occurs if module isnt given time to load before leaving
        }else{
            l_userResponses = qIO.localResult;
        }
//        alert('questionInfoObject.qType '+questionInfoObject.qType);
//        alert("l_userResponses "+l_userResponses+" l_userResponses.length="+l_userResponses.length);
        if(l_userResponses && l_userResponses.length > 0){
//            for(var i = 0; i <l_userResponses.length;i++){
//                alert('debug '+i+' : '+logObject_str(l_userResponses[i]));
//            }
            if(qIO.qType == 'hotspot' ){
                for(var i = 0; i <l_userResponses.length;i++){
                    if(l_userResponses[i] != null && l_userResponses[i].identifier.indexOf('_pointer') > 0){
                        setAttempted(qIO);
                        //alert("hotspot complete ");
                        return true;
                    }
                }
                //alert("hotspot not");
                return false;
            }else if(qIO.qType == 'graphicgapmatch' || qIO.qType == 'gapmatch'){
                for(var i = 0; i <l_userResponses.length;i++){
                    if(l_userResponses[i] != null && l_userResponses[i].baseType == 'point'){
                        setAttempted(qIO);
                        return true;
                    }
                }
                return false;
            }else if(qIO.qType == 'plotter' || qIO.qType == 'chart' || qIO.qType == 'clock' || qIO.qType == 'fraction' || qIO.qType == 'customslide' || qIO.qType == 'chart3d' || qIO.qType == 'measuring'  ){
                for(var i = 0; i <l_userResponses.length;i++){
                    if(l_userResponses[i] != null && l_userResponses[i].identifier == 'RESPONSE' && l_userResponses[i].value == null){
                        return false;
                    }
                }

            }else if(qIO.qType == 'barchart' ){
                for(var i = 0; i <l_userResponses.length;i++){
                    if(l_userResponses[i] != null && l_userResponses[i].identifier == 'POINTS'){
                        setAttempted(qIO);
                        return true;
                    }
                }
                return false;
            }else if(qIO.qType == 'match' ){
                for(var i = 0; i <l_userResponses.length;i++){
                        if(l_userResponses[i] != null && l_userResponses[i].baseType == 'directedPair' && l_userResponses[i].value != null){
                            setAttempted(qIO)
                            return true;
                        }
                        return false;
                    }
            }else {
                try{
                    for(var i = 0; i <l_userResponses.length;i++){ // mapruler/weightinteraction  statusbar
                        if(l_userResponses[i] != null && l_userResponses[i].identifier.indexOf('RESPONSE') > -1 && l_userResponses[i].value == null){
                            return false;
                        }
                    }
                }catch(xerr){
//                    alert('isQuestionAttemptedx '+xerr);
                }
            }

            setAttempted(qIO);
            return true;
        }
    }
    if(qIO.responseVariables && qIO.responseVariables.length > 0){
        for(var i =0; i< qIO.responseVariables.length; i++){
            var respVar = qIO.responseVariables[i];
            if(respVar.interactionType == 'matchInteraction'){
                var selectedMatch = getMatchInteractionSelected(qIO.questionId, respVar);
//                alert(selectedMatch.length);
                if(selectedMatch.length > 0 ){
                    setAttempted(qIO);
                    return true;
                }
            }else if(respVar.interactionType == 'textEntryInteraction'){
                if($(questionId+'_'+respVar.identifier).value && $(questionId+'_'+respVar.identifier).value != null){
                    setAttempted(qIO);
                    return true;
                }
            }else if(respVar.interactionType == 'extendedTextInteraction'){
                var _value = $(respVar.interactionType+'_'+respVar.identifier).value;
                if(_value && _value != null && _value != ''){
                    if(qIO.sessionStatus == itemSessionStatus[0]){
                        qIO.sessionStatus = itemSessionStatus[1];
                    }
                    return true;
                }
            }
        }
    }


    // todo:add types
    return false;
}

/**
 * Helper for  isQuestionAttemptedx
 * @param questionInfoObject
 */
setAttempted = function(qIO){
    if(qIO.sessionStatus == itemSessionStatus[0]){
        qIO.sessionStatus = itemSessionStatus[1];
    }
}





function getFlexappResponseXML(questionId, respVar){

    //alert('getFlexappResponseXML');
    var flexPApp = questionInfoObjects[questionId].flexApp;
    if(respVar.baseType == "object"){
        // lbg: override. unsure if object might be intended, but it does not seem to work. easiest quickfix is to change basetype
        respVar.baseType = "string";
    }
    var rV_XML = '\n<responseVariable identifier="'+respVar.identifier+'" cardinality="'+respVar.cardinality+'" baseType="'+respVar.baseType+'">';
    rV_XML += getCorrectResponseXML(questionId);
    rV_XML += '\n<candidateResponse>';

    //flexPApp.checkResponse();
    var l_userResponses =[];
    if(!flexPApp){
        //alert('!flexPApp');
        //would have liked to give a message here
    }else if(flexPApp.getUserResponses){
        l_userResponses= flexPApp.getUserResponses();
    }else if (flexPApp.getCustomUserResponses){
        l_userResponses= flexPApp.getCustomUserResponses()[0].userValues;
    }else{
        alert('finner ikke metode for brukersvar');
    }
    var valuesXML = '';

    if(l_userResponses){
        for(var i = 0; i < l_userResponses.length; i++){
            //alert(logObject_str(l_userResponses[i]));
            if(l_userResponses[i].color){
                //if(l_userResponses[i].is){
                valuesXML += '\n<value>'+l_userResponses[i].color+'</value>';
            }else{
                valuesXML += '\n<value>'+l_userResponses[i]+'</value>';
            }

        }
    }

    rV_XML += valuesXML;


    rV_XML += '\n</candidateResponse>';
    rV_XML += '\n</responseVariable>';
    //alert('getFlexappResponseXML ferdig');
    return rV_XML;
}

/**
 *
 * @param questionInfo
 * @param l_userResponses
 */
setLocalResultToQuestionInfo = function(qInfo, l_uResp){
    if(typeof l_uResp !== 'undefined' && l_uResp != null && l_uResp != [] && l_uResp.length > 0){
        qInfo.localResult = l_uResp;
    }
}


function getFlexappAllResponsesXML(questionId) {
    var theXML = '';

    var flexPApp = flexAppCommon;
//    alert('getFlexappAllResponsesXML '+flexPApp);

    if(flexPApp == null || typeof flexPApp === 'undefined' || typeof flexPApp.getUserResponses === 'undefined'){
//        alert("getFlexappAllResponsesXML tomt");
    }else if(flexPApp && flexPApp.getUserResponses ){
//        alert('getFlexappAllResponsesXML flexPApp.getUserResponses '+flexPApp.getUserResponses);
        try{
            var l_userResponses = flexPApp.getUserResponses();
            var questionInfo = questionInfoObjects[questionId];
//            alert('questionInfo.qType '+questionInfo.qType);
            setLocalResultToQuestionInfo(questionInfo, l_userResponses);

            if(l_userResponses){
                if(l_userResponses.length == 1 && l_userResponses[0].operator){
                    l_userResponses = l_userResponses[0].values;
                }
                if(l_userResponses.length == 0 && (questionInfo.localResult != null && questionInfo.localResult.length > 0))l_userResponses = questionInfo.localResult;
                for(var i = 0; i < l_userResponses.length; i++){
                    var respVar = l_userResponses[i];
//                    alert('getFlexappAllResponsesXML respVar.identifier='+respVar.identifier);
                    
//                    alert(logObject_str(respVar));
                    if(questionInfo.qType == 'chart3d'){
                        theXML += '\n<responseVariable identifier="'+respVar.identifier+'" cardinality="'+respVar.cardinality+'" baseType="string" inspera:baseType="point3d">';
                    }else{
                        theXML += '\n<responseVariable identifier="'+respVar.identifier+'" cardinality="'+respVar.cardinality+'" baseType="'+respVar.baseType+'">';
                    }
                    theXML += '\n<candidateResponse>';
                    if(respVar.value == null){
                    }else if(respVar.cardinality == 'ordered' || respVar.cardinality == 'multiple' || respVar.value instanceof Array){
                        // hard to distinguish between string and array, may need to check type/identifier to accomodate points
                        for(var j=0;j<respVar.value.length;j++){
                            theXML += '\n<value>'+respVar.value[j]+'</value>';
                        }
                    }else{
                        theXML += '\n<value>'+respVar.value+'</value>';
                    }

                    theXML += '\n</candidateResponse>';
                    theXML += '\n</responseVariable>';
//                    if(questionInfo.qType == "coloring" && respVar.identifier == "POINTS"){
//                        //alert("adding points for coloring");
//                        questionInfo.localResult = respVar;
//                    }
                }
//                alert('set response on userquestion '+theXML);
//                if(questionInfo.qType != "coloring")

            }
        }catch(err){
            //alert('getFlexappAllResponsesXML '+err);
        }
    }

    return theXML;
}

function getCorrectResponseXML(questionId){
    var rV_XML = '';
    if(correctResponses != null && correctResponses[questionId] != null){
        rV_XML += '\n<correctResponse>';
        for(var i = 0; i < correctResponses[questionId].length; i++){
            rV_XML += '\n<value>'+correctResponses[questionId][i]+'</value>';
        }
        rV_XML += '\n</correctResponse>';
    }    
    return rV_XML;
}


function getHintsResponseVariableXML( hintsArray){
    if(!hintsArray){
        return '';
    }
    var s_XML = '\n<responseVariable ';
    s_XML += ' identifier="HINTREQUEST"';
    s_XML += ' cardinality="multiple"';
    s_XML += ' baseType="identifier"';
    s_XML += ' choiceSequence="';
    var candidateResponses = '';
    for(var i =0; i < hintsArray.length;i++){
        if(i > 0) s_XML += ' ';
        s_XML += hintsArray[i].identifier;
        if(hintsArray[i].displayed){
            candidateResponses += '\n<value>'+hintsArray[i].identifier+'</value>';
        }
    }
    s_XML +='">';

    s_XML +='\n<candidateResponse>';
    s_XML += candidateResponses;
    s_XML +='\n</candidateResponse>';
    s_XML +='\n</responseVariable>';

    return s_XML;
}


function getHintsScoreXML(questionId){
    var a_hints = hintsByQuestionId[questionId];
    var h_Score = 0;
    for(var i =0; i < a_hints.length;i++){
        if(a_hints[i].displayed){
            h_Score += a_hints[i].cost;
        }
    }
    var hS_XML = '\n<outcomeVariable identifier="HINT_SCORE" cardinality="single" baseType="float">';
    hS_XML += '\n<value>'+h_Score+'</value>';
    hS_XML += '\n</outcomeVariable>';

    return hS_XML;
}


function disableGapImages(flexApp){
    flexApp.disableGapImages(); // låser dra-objektene
}
function enableGapImages(flexApp){
    flexApp.enableGapImages(); // låser opp dra-objektene 
}
function checkResponse(flexApp){
    flexApp.checkResponse(); // slår på rett/feil-markeringer (og ingenting mer)
}
function clearMarkings(flexApp){
    flexApp.clearMarkings(); // fjerner rett/feil-markeringer
}

function removeObjectFromDoc(elementToRemove){
    elementToRemove.parentNode.removeChild(elementToRemove);
}


/** See XSLTools2.jsOverAjaxReplacer
*/
function replaceNorChars(str){
	var s = str.replace("_oe",String.fromCharCode(248));
    s = s.replace("_ae",String.fromCharCode(230));
    s = s.replace("_aa",String.fromCharCode(229));
    s = s.replace("_Aa",String.fromCharCode(197));
    s = s.replace("_Oe",String.fromCharCode(216));
    s = s.replace("_Ae",String.fromCharCode(198));

    return s;
}

function logObj(_obj){
    var strdebug = '';
    for(var x in _obj){
        strdebug += ' _ '+x;
    }
    alert(strdebug);
}

function setClass(elementId) {
	alert(elementId);
	
}
									
function updateInlineSimpleChoiceAnswer(elem_changedElement, elementId,str_questionId, str_responseIdentifier, parentDiv){
	var rV = null;
    var respVariables = questionInfoObjects[str_questionId].responseVariables;
    
    for (var i=0;i < respVariables.length; i++){
        if(respVariables[i].identifier == str_responseIdentifier){
            rV = respVariables[i];
        }
    }
    if(!rV.userAnswers){
        rV.userAnswers = [];
    }
    
    rV.userAnswers[0] = elem_changedElement;
    
    questionInfoObjects[str_questionId].sessionStatus = itemSessionStatus[1];
    
	/* $$('#'+parentDiv+' .current').each(function(classDiv){
	 	alert("remove");
           classDiv.removeClassName('current');
    })*/
    var parentDivTag = $(parentDiv);
    var classDiv = getDescendantsByClassName('current',parentDivTag);

    for(var j = 0; j < classDiv.length;j++){
	$(classDiv[j]).removeClassName('current');        
    }
    var _inline = $('inline_'+elementId);
    if(typeof _inline !== 'undefined' && _inline != null){
        _inline.addClassName('current');
        rV.userAnswers[0] = $(elementId).value;
    }    


    $$('#qti_assessmentTrackDiv .sectionid_'+str_questionId).each(function(classDiv){
		classDiv.removeClassName('current');
		classDiv.addClassName('finished current');
    })
	//$(elementId).value = elementId;
}

function setFractionAnswer(resultId) {
	$(resultId).value= $(resultId+'_numerator').value+'/'+$(resultId+'_denominator').value;
}

function setFinished(str_questionId) {
     $$('#qti_assessmentTrackDiv .sectionid_'+str_questionId).each(function(classDiv){
		//classDiv.removeClassName('current');
		classDiv.addClassName('finished');
    })
}

function updateWordFeedback(parentDiv, useranswer) {
	$(parentDiv+'_yourAnswer').innerHTML = getCaption('ASSESSMENT_CLICK_WORD_YOUR_ANSWER')+': '+useranswer;
}

function updateWord(str_questionId, parentDiv, wordId) {
	var divId = str_questionId+''+wordId;
	var str_responseIdentifier = $(str_questionId+'_responseIdentifier').value;
//    alert('updateWord str_responseIdentifier='+ str_responseIdentifier);
//    alert('updateWord parentDiv='+ parentDiv);
//    alert('updateWord wordId='+ wordId);

    if(!parentDiv.id && $(parentDiv).id){
        parentDiv = $(parentDiv);
    }
    $(str_responseIdentifier).value = $(divId).innerHTML.replace(/^\s+|\s+$/g,'');
	if ($(divId).className == 'current')
		$(divId).removeClassName('current');
	else {

		$$('#'+parentDiv.id+' .current').each(function(classDiv){
           classDiv.removeClassName('current');
    	})
		
		$(divId).addClassName('current');
		
	}
	
	$$('#qti_assessmentTrackDiv .sectionid_'+str_questionId).each(function(c_Div){
		// PGS-327 lbg : unsure if current needs to be here, seems like it should be sufficient to add finished
        if(c_Div.hasClassName('current')){
            c_Div.removeClassName('current');
		    c_Div.addClassName('finished current');
        }else{
            c_Div.addClassName('finished');
        }
    })
    
    $$('#'+parentDiv.id+' .hover').each(function(classDiv){
           classDiv.removeClassName('hover');
    })
    
    var r_String = $(str_responseIdentifier).value;
 
    if (r_String.indexOf(".") != -1)
    {	
    	var replaceChars = r_String.split("");
    	while (replaceChars[replaceChars.length-1] == "." ){
    		replaceChars.pop()
	    }
	    r_String = replaceChars.toString();
	}  
	
	if (r_String.indexOf("?") != -1)
    {	
    	while (r_String.indexOf("?") != -1)
    	{
    		r_String = r_String.replace("?","");
    	}
	}  
	

    r_String =  r_String.replace(/,/g,"");
   
    r_String =  r_String.replace(/!/g,"");
    r_String =  r_String.replace(/:/g,"");
    r_String =  r_String.replace(/&nbsp;/gi,' ');
    r_String =  r_String.replace(/\s+/gi, ' ');   // PGS-415
    
    $(str_responseIdentifier).value = r_String;
    
	$(parentDiv.id+'_yourAnswer').innerHTML = getCaption('ASSESSMENT_CLICK_WORD_YOUR_ANSWER')+': '+$(str_responseIdentifier).value;
//    alert(str_responseIdentifier+'_wordId');
    if($(str_responseIdentifier+'_wordId')){
        $(str_responseIdentifier+'_wordId').value = wordId;
    }
}

function addHover(id) {
	$(id).addClassName('hover');
}

function removeHover(id) {
	if ($(id).className == 'hover')
		$(id).removeClassName('hover');
}

function updateSimpleChoiceAnswer(elem_c, str_questionId, str_responseIdentifier, elementId){
//  elem_c was elem_changedElement
//    alert(elem_changedElement);
//    alert(elem_changedElement.tagName);
//    alert(elem_changedElement.type);
    var rV = null;
    var respVariables = questionInfoObjects[str_questionId].responseVariables;
    for (var i=0;i < respVariables.length; i++){
        if(respVariables[i].identifier == str_responseIdentifier){
            rV = respVariables[i];
        }
    }
    if(!rV.userAnswers){
        rV.userAnswers = [];
    }
    questionInfoObjects[str_questionId].sessionStatus = itemSessionStatus[1];
    //alert(elem_changedElement.type);
    if( elem_c.type == 'radio'){
    	elem_c.checked = true;
    	
    	setSelectedMC(elementId, str_responseIdentifier, str_questionId);
        rV.userAnswers[0] = elem_c.value;
    }else if ( elem_c.type == 'checkbox'){
    		
    		if( elem_c.checked == true)
    			elem_c.checked = false;
    		else
    			elem_c.checked = true;
    	   
           var wrapperDiv = $(str_questionId+'_'+str_responseIdentifier);
           var selectBoxes = getDescendantsByClassName(str_questionId+'_'+str_responseIdentifier,wrapperDiv);
//           alert("selectboxes "+selectBoxes.length);

            rV.userAnswers = [];
            for(var i=0; i<selectBoxes.length;i++){
                if(selectBoxes[i].checked){
                    rV.userAnswers[rV.userAnswers.length] = selectBoxes[i].value
                }
                setSelectedMR(selectBoxes[i].id,selectBoxes[i].checked);
            }
        

    }else if(elem_c.type == 'select-one' || elem_c instanceof HTMLSelectElement){
        rV.userAnswers = [];
        for(i = 0; i < elem_c.length;i++){
            if(elem_c[i].selected){
                rV.userAnswers[rV.userAnswers.length] = elem_c[i].id;
            }
        }

//    lbg: ACOQTI-43 removed this, letting the assessment determine if "finished
//         $$('#qti_assessmentTrackDiv .sectionid_'+str_questionId).each(function(c_Div){
//		// PGS-327 lbg : unsure if current needs to be here, seems like it should be sufficient to add finished
//        if(c_Div.hasClassName('current')){
//            c_Div.removeClassName('current');
//		    c_Div.addClassName('finished current');
//        }else{
//            c_Div.addClassName('finished');
//        }
//    })

    }else{
        alert("Ukjent element "+elem_c.type);
    }
}

function setSelectedMC(elementId, wrapper,str_questionId){
	$$('#'+str_questionId+'_'+wrapper+' .current').each(function(classDiv){
		classDiv.removeClassName('current');
	})
	$$('#'+str_questionId+'_'+wrapper+' .hover').each(function(classDiv){
		classDiv.removeClassName('hover');
	})
	
	$('simpleChoice_'+elementId).addClassName('current');
	
//	$$('#qti_assessmentTrackDiv .sectionid_'+str_questionId).each(function(classDiv){
//        // PGS-327 lbg : unsure if current needs to be here, seems like it should be sufficient to add finished
//        if(classDiv.hasClassName('current')){
//            classDiv.removeClassName('current');
//		    classDiv.addClassName('finished current');
//        }else{
//            classDiv.addClassName('finished');
//        }
//
//	})
    
}

function setSelectedMR(elementId,selected){
	
	if(selected == true) {
		$('simpleChoice_'+elementId).addClassName('current');
	}
	else {
		$('simpleChoice_'+elementId).removeClassName('current');
    }
    
}

/**
 *
 * @param qIO questionInfoObject
 * @param str_rIdent str_respIdentifier
 */
function getResponsevariable(qIO, str_rIdent){
    for(var i =0; i< qIO.responseVariables.length; i++){
        var respVar = qIO.responseVariables[i];
        if(respVar.identifier == str_rIdent){
            return respVar;
        }
    }
    return null;
}


reloadQTI2 = function(questionId) {
	
	var resultInput = document.getElementById('question_'+questionId+'_itemResultXML');
    if(resultInput == null ) return;
    resultInput.value = getItemResultXML(''+questionId);
//    alert(resultInput.value);
//    alert(getAssessmentTracker());
	if(getAssessmentTracker() != null){
        try{
            var _tracker = getAssessmentTracker();
            var jsItem = _tracker.questions[questionId];
            //alert(resultInput.value);
            var url1=getUrlPrefix() + jsItem.url1;
            //alert(url1+' '+jsItem.id);
            var url2 =$('questionform_'+questionId).serialize();
            url2 += '&trackingAssessmentId='+_tracker.trackingContextId+'&submissionMode='+_tracker.submissionMode;
            new Ajax.Updater(''+jsItem.id,url1,{evalScripts:true,asynchronous:false,method:'post',parameters:url2});
        }catch(err){
            alert('reloadQTI2 ' +err);
        }
    }else if(typeof getNextitem !== 'undefined'  && $('newcoursecontent')){
        // nrk hack
        var url2 =$('questionform_'+questionId).serialize();
        new Ajax.Updater('newcoursecontent',Servlet_ContentPreview,{evalScripts:true,asynchronous:false,method:'post',parameters:url2});
    }else{
		document.getElementById('questionform_'+questionId).submit();
	}
}



getAssessmentTracker = function(){
	try{
	    return _aT;
	}catch(errr){

	}
	return null;
}

/**
 * 
 */
getUrlPrefix = function (){
    return getAssessmentTracker().Servlet_ContentDisplay;
}

loadContentByURL = function(url, params, targetElementId){
    <!--alert(targetElementId);-->
    <!--alert(url);-->
    var myAjax = new Ajax.Updater(
    {success: targetElementId},
    url,
    {
        method: 'get',
        parameters: params,
        evalScripts:true,
        onFailure: reportError
    });
}

reportError = function (request)
{
    alert(getCaption('ALERT_AJAX_FAILED'));
}


function setSelectedDrapogslipp(str_questionId) {
	//alert('setSelectedDrapogslipp');
	$$('#qti_assessmentTrackDiv .sectionid_'+str_questionId).each(function(classDiv){
		classDiv.removeClassName('current');
		classDiv.addClassName('finished current');
    })
}


function legalXMLString(str){
    return str.escapeHTML();
}

function getStyleSheet(StyleSheetURL) {
	//<![CDATA[	
	if(document.createStyleSheet) {	
        document.createStyleSheet(StyleSheetURL);	
	}	
	else {	
        var styles = "@import url("+StyleSheetURL+");";        
        var newSS=document.createElement('link');        
        newSS.rel='stylesheet';        
        newSS.href='data:text/css,'+escape(styles);        
        document.getElementsByTagName("head")[0].appendChild(newSS);
	}	
	//]]>
}


/**
 * Set the question to unanswered state. Initially just used for custominteraction.
 * @param questionId
 */
resetQuestion = function(questionId){
    var qIO = questionInfoObjects[questionId];
    qIO.resetMe = true;
    var _tracker = getAssessmentTracker();

//    var respDecl = questionInfo.initialResponseDeclarationObjects;
//
//    if(respDecl){
//        alert('asxasc '+respDecl.length);
//        for(var i = 0; i < respDecl.length;i++){
//            respDecl[i].userValues = [];
//        }
//        questionInfo.flexApp.setCustomUserResponses(respDecl);
//    }else alert("ingen respdecl");

    if(_tracker != null){
        var _item = _tracker.questions[questionId];
        _item.sessionStatus = itemSessionStatus[0];
        qIO.sessionStatus = itemSessionStatus[0];
        storeItemResult(questionId, false);

        _item.status = 'reset';
        $(prefix_activate+_item.id).removeClassName('seq_answered');
        $$('#qti_assessmentTrackDiv .sectionid_'+questionId).each(function(classDiv){
            while(classDiv.hasClassName("finished")){
                classDiv.removeClassName('finished');
            }

        })
        gotoItem(''+_item.id, ''+_item.section.id);
    }else{
        location.reload();
    }
}

/**
 * Copied from resetQuestion, but does not submit to server or navigate to question.
 */
resetQuestionInClient = function(questionId){
    var qIO = questionInfoObjects[questionId];
    if (qIO) {
        qIO.resetMe = true;
        qIO.sessionStatus == itemSessionStatus[0];
        qIO.evalIsAnswered = false;
    }
    var _tracker = getAssessmentTracker();

    if(_tracker != null){
        var _item = _tracker.questions[questionId];
        _item.sessionStatus = itemSessionStatus[0];
        _item.isAnswered=false;
        
        if (_item.flexAppLoad) {
            _item.flexAppLoad = null;
        }
        qIO.sessionStatus = itemSessionStatus[0];
        //storeItemResult(questionId, false);

        _item.status = 'reset';
        $(prefix_activate+_item.id).removeClassName('seq_answered');
        $$('#qti_assessmentTrackDiv .sectionid_'+questionId).each(function(classDiv){
            while(classDiv.hasClassName("finished")){
                classDiv.removeClassName('finished');
            }
        })
    }else{
        location.reload();
    }
}
/**
 * Remove button if part of assessment
 * @param questionId
 */
checkSubmitButton = function(questionId){
    if(getAssessmentTracker() != null){
        if(getAssessmentTracker().submissionMode && getAssessmentTracker().submissionMode == 'simultaneous'){
            var submitButton = $('submitBtn_'+questionId);
            submitButton.parentNode.removeChild(submitButton);
        }
    }
}

/**
 * Construct questionInfoObject
 * @param questionId
 * @param numAttempts
 * @param sessionStatus
 * @param questionType
 * @param duration
 */
newQIO = function(questionId, numAttempts, sessionStatus, questionType, duration){
    questionInfoObjects[''+questionId]= qio = new Object();
    qio.questionId = questionId;
    qio.attemptStart = (new Date()).getTime();
    qio.numAttempts = numAttempts;
    qio.qType = questionType;
    qio.sessionStatus = sessionStatus;
    qio.duration = duration;
}

/**
 * NAT-277 this method is also in assessmentItemGapMatch.js, but is not accessible for nrk-kurs template 
 * @param _original
 */
replaceEmptyPTags = function (_ori){
    _ori = replaceAllStr(_ori, "GAP", "gap");
    _ori = replaceAllStr(_ori, "<p> </p>", "<p/>");
    _ori = replaceAllStr(_ori, "<p> </p>", "<P/>");
    _ori = replaceAllStr(_ori, "P>", "p>");
    _ori = replaceAllStr(_ori, "BLOCKQUOTE", "blockquote");
    return _ori;
}

/**
 * PGS-849
 * @param _this
 * @param event
 */
validateNumericEntry = function(_this, event){
    if(!numbersonly(_this, event, document.forms[0])) return false;

    return true;
}

/**
 * PGS-849
 * @param _this
 * @param event
 */
validateNumericChange = function(_this, event){
    
    if(typeof _this.expected_decimals !== 'undefined'){
        var nrOfDecimals = parseInt(_this.expected_decimals);
        if(''+nrOfDecimals != 'NaN'){
            var commaPos = _this.value.lastIndexOf(',');
            var dotPos = _this.value.lastIndexOf('.');
            if(dotPos > commaPos) commaPos = dotPos;
//            alert('commaPos '+commaPos +" value.length "+_this.value.length);
            if(nrOfDecimals > 0 && commaPos > -1 && (_this.value.length - (commaPos+1)) > nrOfDecimals){
                alert(getCaption('ASSESSMENT_TO_MANY_DECIMALS'));
                _this.value = _this.lastGoodValue;
                return false;
            }else if(nrOfDecimals == 0 && commaPos > -1){
                _this.value = _this.lastGoodValue;
                return false;
            }
        }
    }
    _this.lastGoodValue = _this.value;
}




requestHint =function (hintToCheck, questionId){
    var hintsArray = hintsByQuestionId[''+questionId];
    hintsArray[hintToCheck].displayed = true;
    updateHintsList(questionId);
}

updateHintsList = function(questionId){
    var hintsDisplayDiv = document.getElementById('hints_display_'+questionId);
    var hinstListDiv = document.getElementById('hintsList_'+questionId);
    var hintsArray = hintsByQuestionId[''+questionId];
    var qI = questionInfoObjects[''+questionId];
    if(!hintsDisplayDiv || !hinstListDiv){
        return;
    }
    //hintsDisplayDiv.innerHTML = '';
    hinstListDiv.innerHTML = '';

    for(var i = 0; i < hintsArray.length;i++){
        var checkHint = hintsArray[i];
        if(checkHint.displayed){
            //hintsDisplayDiv.innerHTML += '<b><xsl:value-of select="java:no.inspera.utils.XSLTools.getCaption('ASSESSMENT_HINT',$languageId,$marketplaceId)"/> '+(i+1)+'</b> '+checkHint.text_value+'<br/>';
            if(!$(checkHint.identifier)){
                hintsDisplayDiv.innerHTML += '<b>'+getCaption('ASSESSMENT_HINT')+' ' +(i+1)+'</b> ';
                hintsDisplayDiv.innerHTML += '<div id="'+checkHint.identifier+'"></div><br/>';
                loadContentByURL(Servlet_qti21Assessment+'&method=getHint&questionId='+questionId+'&hintId='+checkHint.identifier, '', checkHint.identifier);
            }
        }else if(typeof qI == 'undefined' || (typeof qI.sessionStatus !== 'undefined' && qI.sessionStatus == itemSessionStatus[3])){
            // ACOQTI-128 no need to offer more hints when displaying feedback
        }else if(checkHint.displayed == false){
            if(i == 0){

                hinstListDiv.innerHTML += '<h3>'+getCaption('ASSESSMENT_WANT_HINT')+'</h3><br/>';
            }
            hinstListDiv.innerHTML += '<a href="javascript:requestHint('+i+','+ questionId+')">'+getCaption('ASSESSMENT_HINT')+' '+(i+1)+'</a>&#160;'+getCaption('ASSESSMENT_POINT_PENALTY')+': '+checkHint.cost;
            return;
        }
    }

    hinstListDiv.innerHTML = ''+getCaption('ASSESSMENT_NO_MORE_HINTS');
}