var myConditions = [];

function preLoadCondition(qId,i, cffUrl){
    $("#spinner_"+qId).show();
    $.ajax({
        url: cffUrl,
        success:function(data) {
            myConditions[i] = data;
            var myContent = "";
            for (var x = 0; x < myConditions.length; x++) {
                if (myConditions[x]) {
                    myContent +=  myConditions[x];
                }
            }
            $( "#conditionContainer_"+qId ).html(myContent).fadeIn();
        }, 
        done: function() {
            $("#spinner_"+qId).hide();
        }
    });
}

function insertCondition(cId, qId, aId, cffUrl){
    $("#spinner_"+qId).show();
    $.get(cffUrl,
        { async: false },
        function( data ) {
            $( "#conditionContainer_"+qId ).append($('<div id="'+cId+'-'+qId+'-'+aId+'">').html(data)).fadeIn();
            $("#spinner_"+qId).hide();
            restoreCheckedOnes(cId, qId, aId);
        }
    );
}

/**
 * removes the conditional panel from the DOM
 */
function removeCondition(cId, qId, aId){
    preserveCheckedOnes(cId, qId, aId);
    $('#'+cId+'-'+qId+'-'+aId).remove();
}

/**
 * preserves all the checked checkboxes in the conditional panel to the sessionStorage
 */
function preserveCheckedOnes(cId, qId, aId) {
    var panelId = cId+'-'+qId+'-'+aId;
    var panel = $('#'+panelId);
    var checkedOnes = [];
    panel.find('input[type=checkbox]').each(function() {
        if ($(this).prop('checked')) {
            checkedOnes.push($(this).attr('id'));
        }
    });
    if (checkedOnes.length > 0) {
        sessionStorage.setItem(panelId, JSON.stringify(checkedOnes));
    }
}

/**
 * restores all the checked checkboxes in the conditional panel from the sessionStorage
 */
function restoreCheckedOnes(cId, qId, aId) {
    var panelId = cId+'-'+qId+'-'+aId;
    var checkedOnes = sessionStorage.getItem(panelId);
    if (checkedOnes) {
        var parsed = JSON.parse(checkedOnes);
        parsed.forEach(function(checkBoxId) {
            $('#'+checkBoxId).prop('checked', true);
        });
    }
}