<commit_before>/**
 * Created by Petr Marek on 21.7.2015.
 */

var feedback_endpoints = {
    'movies': {
        'BASE_URL': 'https://docs.google.com/forms/d/1Vra6SgNnso6Nn45adZNd0mVWtTMe5_W4QABhlYxfP8I/formResponse?',
        'FIELDS_IDS': ["entry.557679011", "entry.668964305", "entry.315539511", "entry.807998585", "entry.1331990072",
            "entry.540581579", "entry.799866241", "entry.1492550795", "entry.1983407746"],
        'SUBMIT_REF': '&submit=Submit',
        'FORM_URL': 'https://docs.google.com/spreadsheets/d/1FELqTPH6EUws5l_qR14igg1aomsKJ8V7iQEKJ5VEefM/edit?usp=sharing'
    },
    'live': {
        'BASE_URL': 'https://docs.google.com/forms/d/1_BYRxEZlej9gDgkUsXFw_IcdYvytSYyT1KZTHVi7kQ4/formResponse?',
        'FIELDS_IDS': ["entry.2044281262", "entry.13984642", "entry.728405979", "entry.1756526559", "entry.1872170637",
            "entry.1059431403", "entry.1228282374", "entry.17475393", "entry.2052512670"],
        'SUBMIT_REF': '&submit=Submit',
        'FORM_URL': 'https://docs.google.com/spreadsheets/d/16ynWvmgh3S5byEzgizDp53K9pN7jLoORgauFnHpnzMk/edit'
    }
};

var CORRECT_A = true;
var INCORRECT_A = false;

var correctAnswerFieldNumber = new Object();

var feedbackButtons=[];

var feedback_endpoint = feedback_endpoints['live'];
function setFeedbackEndpoint(name) {
    feedback_endpoint = feedback_endpoints[name];
}

$(document).on('pageshow', '#mainPage', function (e, data) {
    if (localStorage.getItem("previousQuestionActive") == "true") {
        $('#search').val(localStorage.getItem("previousQuestion"));
        $('#search').focus();
        localStorage.setItem("previousQuestionActive", "false");
    }
});

//click on submit button
$(document).on('click', '.form-submit', function () {
    var questionId = event.target.id;
    var email = $('#email' + questionId).val();
    var previousQuestion = $('#search').val();
    if (supports_html5_storage()) {
        localStorage.setItem("email", email);
    }
    if (supports_html5_storage()) {
        localStorage.setItem("previousQuestion", previousQuestion);
        localStorage.setItem("previousQuestionActive", "true");
    }
    sendAndReload(email,questionId);
});

//click on more correct button
$(document).on('click', '.moreCorrectAnswers', function () {
    var questionID = event.target.id;
    var toAppend = $('Correct answer:<input id="ea' +
        (correctAnswerFieldNumber[questionID] + 1) + '_' + questionID + '" placeholder="Correct answer" name="ea' + (correctAnswerFieldNumber[questionID] + 1) + '">');
    $("#ea" + correctAnswerFieldNumber[questionID] + "_" + questionID).parent().after(toAppend);
    $('#ea' + (correctAnswerFieldNumber[questionID] + 1) + "_" + questionID).textinput();
    $("#moreCorrectAnswerContainer" + questionID).css("position", "relative");
    $("#moreCorrectAnswerContainer" + questionID).css("top", 37 * correctAnswerFieldNumber[questionID]);
    correctAnswerFieldNumber[questionID] = correctAnswerFieldNumber[questionID] + 1;
});

//send if answer was correct
function sendAndReload(email,questionID) {
    var question = $('#cardQuestion'+questionID).text();
    var ea = getCorrectAnswers(questionID);
    ea = addFeedbackFromInputFields(ea,questionID);
    if (ea[0] != "") {
        sendFeedbackAndReload(email, question, ea[0], ea[1], ea[2], ea[3], ea[4], ea[5], ea[6]);
        hideFeedback(questionID);
    } else {
        alert("Mark correct answers please.")
    }
}

function addFeedbackFromInputFields(ea,questionID) {
    var inputFieldPosition = 1;
    for (var i = 0; i < ea.length; i++) {
        if (ea[i] == null || ea[i] == "") {
            for (inputFieldPosition; ; inputFieldPosition++) {
                if ($("#ea" + inputFieldPosition+"_"+questionID).length) {
                    if ($("#ea" + inputFieldPosition+"_"+questionID).val() != "") {
                        ea[i] = $("#ea" + inputFieldPosition+"_"+questionID).val();
                        inputFieldPosition++;
                        break;
                    } else {
                        continue;
                    }
                }
                break;
            }
        }
        if (i == 6 && ea[i] != "") {
            for (inputFieldPosition; ; inputFieldPosition++) {
                if ($("#ea" + inputFieldPosition+"_"+questionID).length) {
                    if ($("#ea" + inputFieldPosition+"_"+questionID).val() != "") {
                        ea[i] += "|" + $("#ea" + inputFieldPosition+"_"+questionID).val();
                    } else {
                        continue;
                    }
                } else {
                    break;
                }
            }
        }
    }
    return ea;
}

//checks if browser supports html5 storage
function supports_html5_storage() {
    try {
        return 'localStorage' in window && window['localStorage'] !== null;
    } catch (e) {
        return false;
    }
}

//sends feedback to google form
function sendFeedbackAndReload(email, question, ea1, ea2, ea3, ea4, ea5, ea6, mca) {
    var FIELDS_IDS = feedback_endpoint['FIELDS_IDS'];
    var LEmail = FIELDS_IDS[0];
    var LQuestion = FIELDS_IDS[1];
    var LEa = [];
    LEa[0] = FIELDS_IDS[2];
    LEa[1] = FIELDS_IDS[3];
    LEa[2] = FIELDS_IDS[4];
    LEa[3] = FIELDS_IDS[5];
    LEa[4] = FIELDS_IDS[6];
    LEa[5] = FIELDS_IDS[7];

    var LMca = FIELDS_IDS[8];

    var VEmail = encodeURIComponent(email);
    var VQuestion = encodeURIComponent(question);
    var VEa = [];
    VEa[0] = encodeURIComponent(ea1);
    VEa[1] = encodeURIComponent(ea2);
    VEa[2] = encodeURIComponent(ea3);
    VEa[3] = encodeURIComponent(ea4);
    VEa[4] = encodeURIComponent(ea5);
    VEa[5] = encodeURIComponent(ea6);

    var Vmca = encodeURIComponent(mca);

    var submitURL = (feedback_endpoint['BASE_URL'] +
    LEmail + "=" + VEmail + "&" +
    LQuestion + "=" + VQuestion + "&" +
    LEa[0] + "=" + VEa[0] + "&" +
    LEa[1] + "=" + VEa[1] + "&" +
    LEa[2] + "=" + VEa[2] + "&" +
    LEa[3] + "=" + VEa[3] + "&" +
    LEa[4] + "=" + VEa[4] + "&" +
    LEa[5] + "=" + VEa[5] + "&" +
    LMca + "=" + Vmca +
    feedback_endpoint['SUBMIT_REF']);

    $.post(submitURL).always(function () {
     window.location.href = createURL(null);
     });
}

//restores feedback to default state
function showFeedback(numberOfAnswers, questionID) {
    correctAnswerFieldNumber[questionID] = 1;
    $('#feedback_area' + questionID).append(createFeedbackForm(questionID)).trigger("create");
    showAnswerFeedbackButton(numberOfAnswers, questionID);
    $('#email'+questionID).parent().css("width", "82%");
    $('#email'+questionID).val(localStorage.getItem("email"));
}

function hideFeedback(questionID){
    $('#feedback_area' + questionID).empty();
    var thank=$('
Thank you for the feedback!
')
    $('#feedback_area' + questionID).append(thank);
    for(var i=1;i<=feedbackButtons[questionID].length;i++){
        $('#feedbackButtonArea'+i+'_'+questionID).empty();
    }
    $("#cardfeedbackButtonArea" + questionID).empty();
}

function createFeedbackForm(questionID) {
    return $(
        '
' +
        '
' +
        '
' +
        '           Correct answer:' +
        '           <input id="ea1_' + questionID + '" placeholder="Correct answer" name="ea1">' +
        '
' +
        '
' +
        '
' +
        '       <input type="button" value="Add missing answer" name="moreCorrectAnswers" class="moreCorrectAnswers" id="' + questionID + '" data-inline="true">' +
        '
' +
        '
' +
        '
' +
        '    Email (optional):' +
        '    <input id="email' + questionID + '" placeholder="Email (optional)" name="email">' +
        '
' +
        '
' +
        '    <input id="' + questionID + '" class="form-submit" type="button" data-icon="check" data-theme="d" value="Send feedback">' +
        '
');
}

//Dissables search ability
function disableSearch() {
    $('#askMeButton').parent().prop('disabled', true).addClass('ui-disabled');
    $('#search').addClass('ui-disabled');
    $('#voice').prop('disabled', true).addClass('ui-disabled');
}

//click function on correct button
function clickActionCorrect(i, questionID) {
    if (feedbackButtons[questionID][i] == INCORRECT_A) {
        feedbackButtons[questionID][i] = CORRECT_A;
        $('#feedbackButtonCorrect' + i + '_' + questionID).addClass("ui-icon-myapp-checked");
        $("#feedbackButtonCorrect" + i + '_' + questionID).removeClass('ui-icon-myapp-unchecked');
    } else {
        feedbackButtons[questionID][i] = INCORRECT_A;
        $('#feedbackButtonCorrect' + i + '_' + questionID).addClass("ui-icon-myapp-unchecked");
        $("#feedbackButtonCorrect" + i + '_' + questionID).removeClass('ui-icon-myapp-checked');
    }
}

// shows feedback buttons near answer
function showAnswerFeedbackButton(numberOfAnswers, questionID) {
    showCardFeedbackButton(questionID);
    feedbackButtons[questionID] = [];
    for (var i = 0; i < numberOfAnswers; i++) {
        createFeedbackButton(i, questionID);
    }
}

function showCardFeedbackButton(questionID){
    var feedbackButtonIncorrect = '<button class="ui-btn ui-mini ui-corner-all ui-btn-inline" id="cardFeedbackButtonIncorrect'+questionID+'" style="width: 85px;text-align: center;">Incorrect</button>';
    var feedbackButtonCorrect = '<button class="ui-btn ui-mini ui-corner-all ui-btn-inline" id="cardFeedbackButtonCorrect'+questionID+'" style="width: 85px;text-align: center;">Correct</button>';

    $("#cardfeedbackButtonArea" + questionID).append(feedbackButtonIncorrect);
    $("#cardfeedbackButtonArea" + questionID).append("
");
    $("#cardfeedbackButtonArea" + questionID).append(feedbackButtonCorrect);
    $("#cardfeedbackButtonArea" + questionID).parent().css("overflow", "visible");

    $('#cardFeedbackButtonCorrect'+questionID).on('click', function (e) {
        clickActionCardCorrect(questionID);
        e.preventDefault();
        e.stopPropagation();
        e.stopImmediatePropagation();
    });
}

function clickActionCardCorrect(questionID){
    var email = $('#email' + questionID).val();
    var question = $('#cardQuestion'+questionID).text();
    var ea1=$('#answerText1_'+questionID).text();
    sendFeedbackAndReload(email, question, ea1, "", "", "", "", "", "");
    hideFeedback(questionID);
}

//creates feedback buttons
function createFeedbackButton(i, questionID) {
    feedbackButtons[questionID][i] = INCORRECT_A;

    var feedbackButtonCorrect = '<button class="ui-btn ui-mini ui-corner-all ui-icon-myapp-unchecked ui-btn-icon-left ui-btn-inline ui-nodisc-icon" id="feedbackButtonCorrect' + i + '_' + questionID + '">Correct</button>';
    $("#feedbackButtonArea" + i + "_" + questionID).append(feedbackButtonCorrect);
    $('#feedbackButtonCorrect' + i + '_' + questionID).on('click', function (e) {
        clickActionCorrect(i, questionID);
        e.preventDefault();
        e.stopPropagation();
        e.stopImmediatePropagation();
    });
    $("#feedbackButtonArea" + i + '_' + questionID).parent().css("overflow", "visible");
}

//returns array of correct answers
function getCorrectAnswers(questionID) {
    var corrects = [];
    var position = 0;
    for (var i = 0; i < feedbackButtons[questionID].length; i++) {
        if (feedbackButtons[questionID][i] == true) {
            if (position < 6) {
                corrects[position] = getAnswer(i,questionID);
                position++;
            } else {
                if (corrects[position] == null) {
                    corrects[position] = getAnswer(i,questionID);
                } else {
                    corrects[position] += "|" + getAnswer(i,questionID);
                }
            }
        }
    }
    if (position < 6) {
        for (var i = position; i < 7; i++) {
            corrects[i] = "";
        }
    }
    return corrects;
}

//gets text of answer on i position
function getAnswer(i,questionID) {
    return $('#answerText' + i+'_'+questionID).text();
}
<commit_msg>Not reloading after feedback<commit_after>/**
 * Created by Petr Marek on 21.7.2015.
 */

var feedback_endpoints = {
    'movies': {
        'BASE_URL': 'https://docs.google.com/forms/d/1Vra6SgNnso6Nn45adZNd0mVWtTMe5_W4QABhlYxfP8I/formResponse?',
        'FIELDS_IDS': ["entry.557679011", "entry.668964305", "entry.315539511", "entry.807998585", "entry.1331990072",
            "entry.540581579", "entry.799866241", "entry.1492550795", "entry.1983407746"],
        'SUBMIT_REF': '&submit=Submit',
        'FORM_URL': 'https://docs.google.com/spreadsheets/d/1FELqTPH6EUws5l_qR14igg1aomsKJ8V7iQEKJ5VEefM/edit?usp=sharing'
    },
    'live': {
        'BASE_URL': 'https://docs.google.com/forms/d/1_BYRxEZlej9gDgkUsXFw_IcdYvytSYyT1KZTHVi7kQ4/formResponse?',
        'FIELDS_IDS': ["entry.2044281262", "entry.13984642", "entry.728405979", "entry.1756526559", "entry.1872170637",
            "entry.1059431403", "entry.1228282374", "entry.17475393", "entry.2052512670"],
        'SUBMIT_REF': '&submit=Submit',
        'FORM_URL': 'https://docs.google.com/spreadsheets/d/16ynWvmgh3S5byEzgizDp53K9pN7jLoORgauFnHpnzMk/edit'
    }
};

var CORRECT_A = true;
var INCORRECT_A = false;

var correctAnswerFieldNumber = new Object();

var feedbackButtons=[];

var feedback_endpoint = feedback_endpoints['live'];
function setFeedbackEndpoint(name) {
    feedback_endpoint = feedback_endpoints[name];
}

$(document).on('pageshow', '#mainPage', function (e, data) {
    if (localStorage.getItem("previousQuestionActive") == "true") {
        $('#search').val(localStorage.getItem("previousQuestion"));
        $('#search').focus();
        localStorage.setItem("previousQuestionActive", "false");
    }
});

//click on submit button
$(document).on('click', '.form-submit', function () {
    var questionId = event.target.id;
    var email = $('#email' + questionId).val();
    var previousQuestion = $('#search').val();
    if (supports_html5_storage()) {
        localStorage.setItem("email", email);
    }
    if (supports_html5_storage()) {
        localStorage.setItem("previousQuestion", previousQuestion);
        localStorage.setItem("previousQuestionActive", "true");
    }
    send(email,questionId);
});

//click on more correct button
$(document).on('click', '.moreCorrectAnswers', function () {
    var questionID = event.target.id;
    var toAppend = $('Correct answer:<input id="ea' +
        (correctAnswerFieldNumber[questionID] + 1) + '_' + questionID + '" placeholder="Correct answer" name="ea' + (correctAnswerFieldNumber[questionID] + 1) + '">');
    $("#ea" + correctAnswerFieldNumber[questionID] + "_" + questionID).parent().after(toAppend);
    $('#ea' + (correctAnswerFieldNumber[questionID] + 1) + "_" + questionID).textinput();
    $("#moreCorrectAnswerContainer" + questionID).css("position", "relative");
    $("#moreCorrectAnswerContainer" + questionID).css("top", 37 * correctAnswerFieldNumber[questionID]);
    correctAnswerFieldNumber[questionID] = correctAnswerFieldNumber[questionID] + 1;
});

//send if answer was correct
function send(email,questionID) {
    var question = $('#cardQuestion'+questionID).text();
    var ea = getCorrectAnswers(questionID);
    ea = addFeedbackFromInputFields(ea,questionID);
    if (ea[0] != "") {
        sendFeedback(email, question, ea[0], ea[1], ea[2], ea[3], ea[4], ea[5], ea[6]);
        hideFeedback(questionID);
    } else {
        alert("Mark correct answers please.")
    }
}

function addFeedbackFromInputFields(ea,questionID) {
    var inputFieldPosition = 1;
    for (var i = 0; i < ea.length; i++) {
        if (ea[i] == null || ea[i] == "") {
            for (inputFieldPosition; ; inputFieldPosition++) {
                if ($("#ea" + inputFieldPosition+"_"+questionID).length) {
                    if ($("#ea" + inputFieldPosition+"_"+questionID).val() != "") {
                        ea[i] = $("#ea" + inputFieldPosition+"_"+questionID).val();
                        inputFieldPosition++;
                        break;
                    } else {
                        continue;
                    }
                }
                break;
            }
        }
        if (i == 6 && ea[i] != "") {
            for (inputFieldPosition; ; inputFieldPosition++) {
                if ($("#ea" + inputFieldPosition+"_"+questionID).length) {
                    if ($("#ea" + inputFieldPosition+"_"+questionID).val() != "") {
                        ea[i] += "|" + $("#ea" + inputFieldPosition+"_"+questionID).val();
                    } else {
                        continue;
                    }
                } else {
                    break;
                }
            }
        }
    }
    return ea;
}

//checks if browser supports html5 storage
function supports_html5_storage() {
    try {
        return 'localStorage' in window && window['localStorage'] !== null;
    } catch (e) {
        return false;
    }
}

//sends feedback to google form
function sendFeedback(email, question, ea1, ea2, ea3, ea4, ea5, ea6, mca) {
    var FIELDS_IDS = feedback_endpoint['FIELDS_IDS'];
    var LEmail = FIELDS_IDS[0];
    var LQuestion = FIELDS_IDS[1];
    var LEa = [];
    LEa[0] = FIELDS_IDS[2];
    LEa[1] = FIELDS_IDS[3];
    LEa[2] = FIELDS_IDS[4];
    LEa[3] = FIELDS_IDS[5];
    LEa[4] = FIELDS_IDS[6];
    LEa[5] = FIELDS_IDS[7];

    var LMca = FIELDS_IDS[8];

    var VEmail = encodeURIComponent(email);
    var VQuestion = encodeURIComponent(question);
    var VEa = [];
    VEa[0] = encodeURIComponent(ea1);
    VEa[1] = encodeURIComponent(ea2);
    VEa[2] = encodeURIComponent(ea3);
    VEa[3] = encodeURIComponent(ea4);
    VEa[4] = encodeURIComponent(ea5);
    VEa[5] = encodeURIComponent(ea6);

    var Vmca = encodeURIComponent(mca);

    var submitURL = (feedback_endpoint['BASE_URL'] +
    LEmail + "=" + VEmail + "&" +
    LQuestion + "=" + VQuestion + "&" +
    LEa[0] + "=" + VEa[0] + "&" +
    LEa[1] + "=" + VEa[1] + "&" +
    LEa[2] + "=" + VEa[2] + "&" +
    LEa[3] + "=" + VEa[3] + "&" +
    LEa[4] + "=" + VEa[4] + "&" +
    LEa[5] + "=" + VEa[5] + "&" +
    LMca + "=" + Vmca +
    feedback_endpoint['SUBMIT_REF']);

    $.post(submitURL);
}

//restores feedback to default state
function showFeedback(numberOfAnswers, questionID) {
    correctAnswerFieldNumber[questionID] = 1;
    $('#feedback_area' + questionID).append(createFeedbackForm(questionID)).trigger("create");
    showAnswerFeedbackButton(numberOfAnswers, questionID);
    $('#email'+questionID).parent().css("width", "82%");
    $('#email'+questionID).val(localStorage.getItem("email"));
}

function hideFeedback(questionID){
    $('#feedback_area' + questionID).empty();
    var thank=$('
Thank you for the feedback!
')
    $('#feedback_area' + questionID).append(thank);
    for(var i=1;i<=feedbackButtons[questionID].length;i++){
        $('#feedbackButtonArea'+i+'_'+questionID).empty();
    }
    $("#cardfeedbackButtonArea" + questionID).empty();
}

function createFeedbackForm(questionID) {
    return $(
        '
' +
        '
' +
        '
' +
        '           Correct answer:' +
        '           <input id="ea1_' + questionID + '" placeholder="Correct answer" name="ea1">' +
        '
' +
        '
' +
        '
' +
        '       <input type="button" value="Add missing answer" name="moreCorrectAnswers" class="moreCorrectAnswers" id="' + questionID + '" data-inline="true">' +
        '
' +
        '
' +
        '
' +
        '    Email (optional):' +
        '    <input id="email' + questionID + '" placeholder="Email (optional)" name="email">' +
        '
' +
        '
' +
        '    <input id="' + questionID + '" class="form-submit" type="button" data-icon="check" data-theme="d" value="Send feedback">' +
        '
');
}

//Dissables search ability
function disableSearch() {
    $('#askMeButton').parent().prop('disabled', true).addClass('ui-disabled');
    $('#search').addClass('ui-disabled');
    $('#voice').prop('disabled', true).addClass('ui-disabled');
}

//click function on correct button
function clickActionCorrect(i, questionID) {
    if (feedbackButtons[questionID][i] == INCORRECT_A) {
        feedbackButtons[questionID][i] = CORRECT_A;
        $('#feedbackButtonCorrect' + i + '_' + questionID).addClass("ui-icon-myapp-checked");
        $("#feedbackButtonCorrect" + i + '_' + questionID).removeClass('ui-icon-myapp-unchecked');
    } else {
        feedbackButtons[questionID][i] = INCORRECT_A;
        $('#feedbackButtonCorrect' + i + '_' + questionID).addClass("ui-icon-myapp-unchecked");
        $("#feedbackButtonCorrect" + i + '_' + questionID).removeClass('ui-icon-myapp-checked');
    }
}

// shows feedback buttons near answer
function showAnswerFeedbackButton(numberOfAnswers, questionID) {
    showCardFeedbackButton(questionID);
    feedbackButtons[questionID] = [];
    for (var i = 0; i < numberOfAnswers; i++) {
        createFeedbackButton(i, questionID);
    }
}

function showCardFeedbackButton(questionID){
    var feedbackButtonIncorrect = '<button class="ui-btn ui-mini ui-corner-all ui-btn-inline" id="cardFeedbackButtonIncorrect'+questionID+'" style="width: 85px;text-align: center;">Incorrect</button>';
    var feedbackButtonCorrect = '<button class="ui-btn ui-mini ui-corner-all ui-btn-inline" id="cardFeedbackButtonCorrect'+questionID+'" style="width: 85px;text-align: center;">Correct</button>';

    $("#cardfeedbackButtonArea" + questionID).append(feedbackButtonIncorrect);
    $("#cardfeedbackButtonArea" + questionID).append("
");
    $("#cardfeedbackButtonArea" + questionID).append(feedbackButtonCorrect);
    $("#cardfeedbackButtonArea" + questionID).parent().css("overflow", "visible");

    $('#cardFeedbackButtonCorrect'+questionID).on('click', function (e) {
        clickActionCardCorrect(questionID);
        e.preventDefault();
        e.stopPropagation();
        e.stopImmediatePropagation();
    });
}

function clickActionCardCorrect(questionID){
    var email = $('#email' + questionID).val();
    var question = $('#cardQuestion'+questionID).text();
    var ea1=$('#answerText1_'+questionID).text();
    sendFeedback(email, question, ea1, "", "", "", "", "", "");
    hideFeedback(questionID);
}

//creates feedback buttons
function createFeedbackButton(i, questionID) {
    feedbackButtons[questionID][i] = INCORRECT_A;

    var feedbackButtonCorrect = '<button class="ui-btn ui-mini ui-corner-all ui-icon-myapp-unchecked ui-btn-icon-left ui-btn-inline ui-nodisc-icon" id="feedbackButtonCorrect' + i + '_' + questionID + '">Correct</button>';
    $("#feedbackButtonArea" + i + "_" + questionID).append(feedbackButtonCorrect);
    $('#feedbackButtonCorrect' + i + '_' + questionID).on('click', function (e) {
        clickActionCorrect(i, questionID);
        e.preventDefault();
        e.stopPropagation();
        e.stopImmediatePropagation();
    });
    $("#feedbackButtonArea" + i + '_' + questionID).parent().css("overflow", "visible");
}

//returns array of correct answers
function getCorrectAnswers(questionID) {
    var corrects = [];
    var position = 0;
    for (var i = 0; i < feedbackButtons[questionID].length; i++) {
        if (feedbackButtons[questionID][i] == true) {
            if (position < 6) {
                corrects[position] = getAnswer(i,questionID);
                position++;
            } else {
                if (corrects[position] == null) {
                    corrects[position] = getAnswer(i,questionID);
                } else {
                    corrects[position] += "|" + getAnswer(i,questionID);
                }
            }
        }
    }
    if (position < 6) {
        for (var i = position; i < 7; i++) {
            corrects[i] = "";
        }
    }
    return corrects;
}

//gets text of answer on i position
function getAnswer(i,questionID) {
    return $('#answerText' + i+'_'+questionID).text();
}
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');
var exec = require('child_process').exec;
var opt = {
    encoding: 'utf8'
};
var path = {
  target: path.resolve(__dirname + '/../dist/XmasPresent.js'),
  fixture1: path.resolve(__dirname + '/fixture1.js'),
  fixture2: path.resolve(__dirname + '/fixture2.js')
};

var target = fs.readFileSync(path.target, opt);
var fixture1 = fs.readFileSync(path.fixture1, opt);
var fixture2 = fs.readFileSync(path.fixture2, opt);

// Test failure
if (target !== fixture1 && target !== fixture2) {
  console.error('See: diff dist/XmasPresent.css test/fixture[1-2].js');
  process.stdout.write(stdout);
  process.exit(1);
  return;
}

// All tests passed
console.log('All tests passed');
process.exit(0);
<commit_msg>Fixes printing log bug<commit_after>var fs = require('fs');
var path = require('path');
var exec = require('child_process').exec;
var opt = {
    encoding: 'utf8'
};
var path = {
  target: path.resolve(__dirname + '/../dist/XmasPresent.js'),
  fixture1: path.resolve(__dirname + '/fixture1.js'),
  fixture2: path.resolve(__dirname + '/fixture2.js')
};

var target = fs.readFileSync(path.target, opt);
var fixture1 = fs.readFileSync(path.fixture1, opt);
var fixture2 = fs.readFileSync(path.fixture2, opt);

// Test failure
if (target !== fixture1 && target !== fixture2) {
  console.error('See: diff dist/XmasPresent.css test/fixture[1-2].js');
  process.exit(1);
  return;
}

// All tests passed
console.log('All tests passed');
process.exit(0);
<|endoftext|>


<commit_before>"use strict"

/**
 * @type {Chai.Assert}
 */
var assert = require('chai').assert;
var q = require('q');

var xdmvc = {

    injectEventLogger: function() {

        var EventLogger = function() {
            this.eventNames = ["XDdisconnection", "XDconnection", "XDdevice", "XDroles", "XDsync", "XDserverReady", "XDothersRolesChanged"];
            this.eventCounter = {};

            this.eventNames.forEach((function (event) {
                this.eventCounter[event] = 0;
                XDmvc.on(event, (function (sender) {
                    this.eventCounter[event]++;
                }).bind(this))
            }).bind(this));
        }

        window.eventLogger = window.eventLogger || new EventLogger();
        return 0;
    },

    getEventCounter: function() {
        return window.eventLogger.eventCounter;
    },

    /**
     * @param {WebdriverIO.Client} devices
     * @param {string} baseUrl
     * @returns {WebdriverIO.Client}
     */
    pairDevicesViaURL: function(devices, baseUrl) {
        let urlA

        return devices
            .selectById('A',
                deviceA => deviceA
                    .url(baseUrl)
                    .execute(function () {
                        return 1 + 2;
                    })
                    .then(ret => assert.equal(ret.value, 3))
                    .execute(xdmvc.injectEventLogger)
                    .getUrl().then(url => urlA = url),
                otherDevices => otherDevices
                    .url(urlA)
            )
            .selectById('A', deviceA => deviceA
                .waitUntil(() => deviceA
                    .execute(xdmvc.getEventCounter)
                    .then(ret => devices.getCount().then(count => ret.value.XDconnection === (count - 1)))
                )
            )
    },

    /**
     * @param {WebdriverIO.Client} devices
     * @returns {Q.Promise<U>}
     */
    pairDevicesViaXDMVC: function(devices) {

        // TODO wait for XD "initialized" event?

        let sessionIDsWithoutA = []

        return devices
            .execute(xdmvc.injectEventLogger)
            .selectById('A',
                () => { },
                allButA => allButA
                    .forEach(device => device
                        .execute(function() {
                            return XDmvc.deviceId
                        })
                        .then(ret => sessionIDsWithoutA.push(ret.value))
                    )
            )
            .selectById('A', deviceA => {
                // Connect device A with all other devices
                return q.all(
                    sessionIDsWithoutA.map(otherId => deviceA
                        .execute(function (id) {
                            XDmvc.connectTo(id);
                        }, otherId)
                    )
                ).then(() => deviceA
                    .waitUntil(() => deviceA
                        .execute(xdmvc.getEventCounter)
                        .then(ret => devices.getCount().then(count => ret.value.XDconnection == count - 1))
                    )
                )
            })
    },

    devicesCount : function() {
        var self = this;
        return Object.keys(self.deviceOptions).length;
    }
}

module.exports = xdmvc;
<commit_msg>There are no XD-MVC events after app initialization or rendering<commit_after>"use strict"

/**
 * @type {Chai.Assert}
 */
var assert = require('chai').assert;
var q = require('q');

var xdmvc = {

    injectEventLogger: function() {

        var EventLogger = function() {
            this.eventNames = ["XDdisconnection", "XDconnection", "XDdevice", "XDroles", "XDsync", "XDserverReady", "XDothersRolesChanged"];
            this.eventCounter = {};

            this.eventNames.forEach((function (event) {
                this.eventCounter[event] = 0;
                XDmvc.on(event, (function (sender) {
                    this.eventCounter[event]++;
                }).bind(this))
            }).bind(this));
        }

        window.eventLogger = window.eventLogger || new EventLogger();
        return 0;
    },

    getEventCounter: function() {
        return window.eventLogger.eventCounter;
    },

    /**
     * @param {WebdriverIO.Client} devices
     * @param {string} baseUrl
     * @returns {WebdriverIO.Client}
     */
    pairDevicesViaURL: function(devices, baseUrl) {
        let urlA

        return devices
            .selectById('A',
                deviceA => deviceA
                    .url(baseUrl)
                    .execute(function () {
                        return 1 + 2;
                    })
                    .then(ret => assert.equal(ret.value, 3))
                    .execute(xdmvc.injectEventLogger)
                    .getUrl().then(url => urlA = url),
                otherDevices => otherDevices
                    .url(urlA)
            )
            .selectById('A', deviceA => deviceA
                .waitUntil(() => deviceA
                    .execute(xdmvc.getEventCounter)
                    .then(ret => devices.getCount().then(count => ret.value.XDconnection === (count - 1)))
                )
            )
    },

    /**
     * @param {WebdriverIO.Client} devices
     * @returns {Q.Promise<U>}
     */
    pairDevicesViaXDMVC: function(devices) {
        let sessionIDsWithoutA = []

        return devices
            .execute(xdmvc.injectEventLogger)
            .selectById('A',
                () => { },
                allButA => allButA
                    .forEach(device => device
                        .execute(function() {
                            return XDmvc.deviceId
                        })
                        .then(ret => sessionIDsWithoutA.push(ret.value))
                    )
            )
            .selectById('A', deviceA => {
                // Connect device A with all other devices
                return q.all(
                    sessionIDsWithoutA.map(otherId => deviceA
                        .execute(function (id) {
                            XDmvc.connectTo(id);
                        }, otherId)
                    )
                ).then(() => deviceA
                    .waitUntil(() => deviceA
                        .execute(xdmvc.getEventCounter)
                        .then(ret => devices.getCount().then(count => ret.value.XDconnection == count - 1))
                    )
                )
            })
    },

    devicesCount : function() {
        var self = this;
        return Object.keys(self.deviceOptions).length;
    }
}

module.exports = xdmvc;
<|endoftext|>


<commit_before>sap.ui.define(function () {
	"use strict";

	return {
		name: "QUnit TestSuite for sap.ui.integration",
		defaults: {
			qunit: {
				version: "edge"
			},
			sinon: {
				version: "edge"
			},
			ui5: {
				libs: ["sap.f", "sap.m"],	// Libraries to load upfront in addition to the library which is tested, if null no libs are loaded
				noConflict: true,
				preload: "auto"
			},
			coverage: {
				only: ["sap/ui/integration"]
			},
			autostart: true
		},
		tests: {
			"Card": {
				coverage: {
					only: [
						"sap/ui/integration/widgets/Card"
					]
				}
			},
			"util/CardManifest": {
				coverage: {
					only: [
						"sap/ui/integration/util/CardManifest"
					]
				}
			},
			"util/CustomElements": {
				coverage: {
					only: [
						"sap/ui/integration/util/CustomElements"
					]
				}
			}
		}
	};
});<commit_msg>[INTERNAL] Removed failing test of IE<commit_after>sap.ui.define(function () {
	"use strict";

	return {
		name: "QUnit TestSuite for sap.ui.integration",
		defaults: {
			qunit: {
				version: "edge"
			},
			sinon: {
				version: "edge"
			},
			ui5: {
				libs: ["sap.f", "sap.m"], // Libraries to load upfront in addition to the library which is tested, if null no libs are loaded
				noConflict: true,
				preload: "auto"
			},
			coverage: {
				only: ["sap/ui/integration"]
			},
			autostart: true
		},
		tests: {
			"Card": {
				coverage: {
					only: [
						"sap/ui/integration/widgets/Card"
					]
				}
			},
			"util/CardManifest": {
				coverage: {
					only: [
						"sap/ui/integration/util/CardManifest"
					]
				}
			}
		}
	};
});<|endoftext|>


<commit_before>// Copyright 2002-2013, University of Colorado Boulder

/**
 * Scoreboard for a game.
 *
 * @author Chris Malley (PixelZoom, Inc.)
 */
define( function( require ) {
  'use strict';

  // imports
  var Color = require( 'SCENERY/util/Color' );
  var GameTimer = require( 'VEGAS/GameTimer' );
  var inherit = require( 'PHET_CORE/inherit' );
  var Line = require( 'SCENERY/nodes/Line' );
  var Node = require( 'SCENERY/nodes/Node' );
  var Panel = require( 'SUN/Panel' );
  var PhetFont = require( 'SCENERY_PHET/PhetFont' );
  var SimpleClockIcon = require( 'SCENERY_PHET/SimpleClockIcon' );
  var StringUtils = require( 'PHETCOMMON/util/StringUtils' );
  var Text = require( 'SCENERY/nodes/Text' );
  var TextPushButtonDeprecated = require( 'SUN/TextPushButtonDeprecated' );
  var ReturnToLevelSelectButton = require( 'SCENERY_PHET/ReturnToLevelSelectButton' );
  var TextPushButton = require( 'SUN/buttons/TextPushButton' );

  // strings
  var startOverString = require( 'string!VEGAS/startOver' );
  var pattern_0level = require( 'string!VEGAS/label.level' );
  var pattern_0score = require( 'string!VEGAS/label.score' );
  var pattern_0challenge_1max = require( 'string!VEGAS/pattern.0challenge.1max' );

  /**
   * @param {Property<Number>} challengeIndexProperty which challenge is the user current playing? (index starts at 0, displayed starting at 1)
   * @param {Property<Number>} challengesPerGameProperty how many challenges are in the current game
   * @param {Property<Number>} levelProperty
   * @param {Property<Number>} scoreProperty
   * @param {Property<Number>} elapsedTimeProperty elapsed time in seconds
   * @param {Property<Number>} timerEnabledProperty is the timer enabled?
   * @param {Function} newGameCallback
   * @param {*} options
   * @constructor
   */
  function Scoreboard( challengeIndexProperty, challengesPerGameProperty, levelProperty, scoreProperty, elapsedTimeProperty, timerEnabledProperty, startOverCallback, options ) {

    var thisNode = this;

    options = _.extend( {
      // things that can be hidden
      levelVisible: true,
      challengeNumberVisible: true,
      // all text
      font: new PhetFont( 16 ),
      // "Start Over" button
      startOverButtonText: startOverString,
      startOverButtonBaseColor: new Color( 229, 243, 255 ),
      startOverButtonXMargin: 10,
      startOverButtonYMargin: 5,
      // Timer
      clockIconRadius: 15,
      // Panel
      minWidth: 0,
      xSpacing: 40,
      xMargin: 20,
      yMargin: 10,
      fill: 'rgb( 180, 205, 255 )',
      stroke: 'black',
      lineWidth: 1
    }, options );

    // Level
    var levelNode = new Text( '', { font: options.font, pickable: false } );
    levelProperty.link( function( level ) {
      levelNode.text = StringUtils.format( pattern_0level, level + 1 );
    } );

    // Challenge number
    var challengeNumberNode = new Text( '', { font: options.font, pickable: false } );
    challengeIndexProperty.link( function( challengeIndex ) {
      challengeNumberNode.text = StringUtils.format( pattern_0challenge_1max, challengeIndex + 1, challengesPerGameProperty.get() );
    } );

    // Score
    var scoreNode = new Text( '', { font: options.font, pickable: false } );
    scoreProperty.link( function( score ) {
      scoreNode.text = StringUtils.format( pattern_0score, score );
    } );

    // Timer, always takes up space even when hidden.
    var timerNode = new Node( { pickable: false } );
    var clockIcon = new SimpleClockIcon( options.clockIconRadius );
    var timeValue = new Text( '', { font: options.font } );
    timerNode.addChild( clockIcon );
    timerNode.addChild( timeValue );
    timeValue.left = clockIcon.right + 8;
    timeValue.centerY = clockIcon.centerY;
    elapsedTimeProperty.link( function( elapsedTime ) {
      timeValue.text = GameTimer.formatTime( elapsedTime );
    } );
    timerEnabledProperty.link( function( timerEnabled ) {
      timerNode.visible = timerEnabled;
    } );

    // Start Over button
    var startOverButton = new TextPushButton( options.startOverButtonText, {
      listener: startOverCallback,
      font: options.font,
      baseColor: options.startOverButtonBaseColor,
      xMargin: options.startOverButtonXMargin,
      yMargin: options.startOverButtonYMargin
    } );

    // Content for the panel, one row.
    var subContent = new Node();
    var nodes = [ levelNode, challengeNumberNode, scoreNode, timerNode, startOverButton ];
    if ( !options.levelVisible ) { nodes.splice( nodes.indexOf( levelNode ), 1 ); }
    if ( !options.challengeNumberVisible ) { nodes.splice( nodes.indexOf( challengeNumberNode ), 1 ); }
    for ( var i = 0; i < nodes.length; i++ ) {
      subContent.addChild( nodes[i] );
      if ( i > 0 ) {
        nodes[i].left = nodes[i - 1].right + options.xSpacing;
        nodes[i].centerY = nodes[i - 1].centerY;
      }
    }

    //TODO sun.Panel should support this, instead of having to do it here
    // ensure a minimum width, horizontally center the content.
    var content = subContent;
    if ( subContent.width < options.minWidth ) {
      content = new Node();
      var strut = new Line( 0, 0, options.minWidth, 0, { pickable: false } ); // horizontal strut
      content.addChild( strut );
      content.addChild( subContent );
      subContent.centerX = strut.centerX;
    }

    Panel.call( thisNode, content, options );
  }

  return inherit( Panel, Scoreboard );
} );
<commit_msg>Changed default font size back to 20.<commit_after>// Copyright 2002-2013, University of Colorado Boulder

/**
 * Scoreboard for a game.
 *
 * @author Chris Malley (PixelZoom, Inc.)
 */
define( function( require ) {
  'use strict';

  // imports
  var Color = require( 'SCENERY/util/Color' );
  var GameTimer = require( 'VEGAS/GameTimer' );
  var inherit = require( 'PHET_CORE/inherit' );
  var Line = require( 'SCENERY/nodes/Line' );
  var Node = require( 'SCENERY/nodes/Node' );
  var Panel = require( 'SUN/Panel' );
  var PhetFont = require( 'SCENERY_PHET/PhetFont' );
  var SimpleClockIcon = require( 'SCENERY_PHET/SimpleClockIcon' );
  var StringUtils = require( 'PHETCOMMON/util/StringUtils' );
  var Text = require( 'SCENERY/nodes/Text' );
  var TextPushButtonDeprecated = require( 'SUN/TextPushButtonDeprecated' );
  var ReturnToLevelSelectButton = require( 'SCENERY_PHET/ReturnToLevelSelectButton' );
  var TextPushButton = require( 'SUN/buttons/TextPushButton' );

  // strings
  var startOverString = require( 'string!VEGAS/startOver' );
  var pattern_0level = require( 'string!VEGAS/label.level' );
  var pattern_0score = require( 'string!VEGAS/label.score' );
  var pattern_0challenge_1max = require( 'string!VEGAS/pattern.0challenge.1max' );

  /**
   * @param {Property<Number>} challengeIndexProperty which challenge is the user current playing? (index starts at 0, displayed starting at 1)
   * @param {Property<Number>} challengesPerGameProperty how many challenges are in the current game
   * @param {Property<Number>} levelProperty
   * @param {Property<Number>} scoreProperty
   * @param {Property<Number>} elapsedTimeProperty elapsed time in seconds
   * @param {Property<Number>} timerEnabledProperty is the timer enabled?
   * @param {Function} newGameCallback
   * @param {*} options
   * @constructor
   */
  function Scoreboard( challengeIndexProperty, challengesPerGameProperty, levelProperty, scoreProperty, elapsedTimeProperty, timerEnabledProperty, startOverCallback, options ) {

    var thisNode = this;

    options = _.extend( {
      // things that can be hidden
      levelVisible: true,
      challengeNumberVisible: true,
      // all text
      font: new PhetFont( 20 ),
      // "Start Over" button
      startOverButtonText: startOverString,
      startOverButtonBaseColor: new Color( 229, 243, 255 ),
      startOverButtonXMargin: 10,
      startOverButtonYMargin: 5,
      // Timer
      clockIconRadius: 15,
      // Panel
      minWidth: 0,
      xSpacing: 40,
      xMargin: 20,
      yMargin: 10,
      fill: 'rgb( 180, 205, 255 )',
      stroke: 'black',
      lineWidth: 1
    }, options );

    // Level
    var levelNode = new Text( '', { font: options.font, pickable: false } );
    levelProperty.link( function( level ) {
      levelNode.text = StringUtils.format( pattern_0level, level + 1 );
    } );

    // Challenge number
    var challengeNumberNode = new Text( '', { font: options.font, pickable: false } );
    challengeIndexProperty.link( function( challengeIndex ) {
      challengeNumberNode.text = StringUtils.format( pattern_0challenge_1max, challengeIndex + 1, challengesPerGameProperty.get() );
    } );

    // Score
    var scoreNode = new Text( '', { font: options.font, pickable: false } );
    scoreProperty.link( function( score ) {
      scoreNode.text = StringUtils.format( pattern_0score, score );
    } );

    // Timer, always takes up space even when hidden.
    var timerNode = new Node( { pickable: false } );
    var clockIcon = new SimpleClockIcon( options.clockIconRadius );
    var timeValue = new Text( '', { font: options.font } );
    timerNode.addChild( clockIcon );
    timerNode.addChild( timeValue );
    timeValue.left = clockIcon.right + 8;
    timeValue.centerY = clockIcon.centerY;
    elapsedTimeProperty.link( function( elapsedTime ) {
      timeValue.text = GameTimer.formatTime( elapsedTime );
    } );
    timerEnabledProperty.link( function( timerEnabled ) {
      timerNode.visible = timerEnabled;
    } );

    // Start Over button
    var startOverButton = new TextPushButton( options.startOverButtonText, {
      listener: startOverCallback,
      font: options.font,
      baseColor: options.startOverButtonBaseColor,
      xMargin: options.startOverButtonXMargin,
      yMargin: options.startOverButtonYMargin
    } );

    // Content for the panel, one row.
    var subContent = new Node();
    var nodes = [ levelNode, challengeNumberNode, scoreNode, timerNode, startOverButton ];
    if ( !options.levelVisible ) { nodes.splice( nodes.indexOf( levelNode ), 1 ); }
    if ( !options.challengeNumberVisible ) { nodes.splice( nodes.indexOf( challengeNumberNode ), 1 ); }
    for ( var i = 0; i < nodes.length; i++ ) {
      subContent.addChild( nodes[i] );
      if ( i > 0 ) {
        nodes[i].left = nodes[i - 1].right + options.xSpacing;
        nodes[i].centerY = nodes[i - 1].centerY;
      }
    }

    //TODO sun.Panel should support this, instead of having to do it here
    // ensure a minimum width, horizontally center the content.
    var content = subContent;
    if ( subContent.width < options.minWidth ) {
      content = new Node();
      var strut = new Line( 0, 0, options.minWidth, 0, { pickable: false } ); // horizontal strut
      content.addChild( strut );
      content.addChild( subContent );
      subContent.centerX = strut.centerX;
    }

    Panel.call( thisNode, content, options );
  }

  return inherit( Panel, Scoreboard );
} );
<|endoftext|>


<commit_before>/**
* Created by saxxx027 on 11/10/14.
*/

'use strict';

describe('filter', function() {
    beforeEach(module('umm3601ursamajorApp'));

    describe('isntEmpty', function() {
        it('should return return the title and item ' +
            'if the item is an object with length over 0, not ' +
                'an object, but not "" or null, else altTitle',
          inject(function(isntEmptyFilter) {
              expect(isntEmptyFilter("item1", "First Item", "something else")).toBe("First Item item1");
              expect(isntEmptyFilter(21, "myNumber", "something else")).toBe("myNumber 21");
              expect(isntEmptyFilter(["happy", "days", "testing", "rocks"], "arrays", "something else")).toBe('arrays happy,days,testing,rocks');
              expect(isntEmptyFilter("", "something else", "this was an empty string")).toBe("this was an empty string");
          }));
    });

    describe('fancyLimitTo', function() {
        it('should return first "n" characters of the imputed text',
            inject(function(fancyLimitToFilter){
                expect(fancyLimitToFilter("abc", 1 )).toBe("a[...]");
                expect(fancyLimitToFilter("12345", 0)).toBe("[...]");
                expect(fancyLimitToFilter("", 5)).toBe("[...]");
            }));
    });

});

describe('Functions dealing with submissions...', function() {
    beforeEach(module('umm3601ursamajorApp'));
    beforeEach(module('socketMock'));
    beforeEach(module('authMock'));

    var SublistCtrl, scope;

    beforeEach(inject(function($controller, $rootScope) {
        scope = $rootScope.$new();
        SublistCtrl = $controller('SublistCtrl', {
            $scope: scope
        });
    }));

    beforeEach(function(){
       scope.submissions = [
        {
            _id: "uniqueIdString",
            title: "A Study of the Properties of a Paperclip in the Digestive System of a Sloth",
            format: "Artist Statement",
            abstract: "Many physicists would agree that, had it not been for scatter/gather I/O, the study of link-level acknowledgements might never have occurred. " +
                "While such a claim might seem unexpected, it usually conflicts with the need to provide thin clients to hackers worldwide. " +
                "In fact, few security experts would disagree with the construction of kernels. In order to overcome this question, we construct an analysis of the Ethernet (Mollah)," +
                " which we use to prove that redundancy and replication can interfere to achieve this aim. ",
            presentationType: "Oral Presentation",
            formatChange: false,
            presenterInfo: {first: "Hongya", last: "Zhou", email: "zhoux616@morris.umn.edu"},
            copresenterOneInfo: {first: "Otto", last: "Marckel II", email: "marck018@morris.umn.edu"},
            copresenterTwoInfo: {first: "Dalton", last: "Gusaas", email: "gusaa004@morris.umn.edu"},
            discipline: "Biology",
            sponsors: [], //Might need to worry about if this is static for the DB later.
            adviserInfo: {first: "Maggie", last: "Casale", email: "casal033@morris.umn.edu"},
            coadviserOneInfo: {first: "Dalton", last: "Gusaas", email: "gusaa004@morris.umn.edu"},
            coadviserTwoInfo: {},
            featured: false,
            mediaServicesEquipment: "",
            specialRequirements: "a sloth",
            presenterTeeSize: "M",
            otherInfo: "Maybe",
            approval: true,
            rejection: false,
            status: {strict: "Awaiting Adviser Approval", text: "Your adviser has yet to approve this submission."},
            timestamp: "Mon Oct 20 2014 1:48:54 GMT-0500 (CDT)",
            group: 3,
            resubmissionData: {comment: "Initial Submission", parentSubmission: "testIdForTesting", isPrimary: false, resubmitFlag: false},
            comments: []
        }, {
           _id: "testIdForTesting",
           title: "Blind Construction: Mixed Media",
           format: "Artist Statement",
           abstract: "The basis of this project was to create a garment using mixed media in order to mimic the human body. " +
               "The materials we used to create this piece include: buckram, copper wire, spray paint, fabric paint, a variety of novelty fabrics, and chains.  " +
               "The techniques we created in order to manipulate the piece include: fabric branding and burning, grid painting, sewing, draping, molding buckram, and coiling.  " +
               "Our overall approach was to create a theatrical wearable art piece. " +
               "Upon completion of the assignment we found the piece aesthetically pleasing because of the way it molds to the human body, but can be a piece all on its own.",
           presentationType: "Performance",
           formatChange: false,
           presenterInfo: {first: "Jacob", last: "Opdahl", email: "opdah023@morris.umn.edu"},
           copresenterOneInfo: {first: "Savannah", last: "Farm", email: "farmx009@morris.umn.edu"},
           copresenterTwoInfo: {first: "Maggie", last: "Casale", email: "casal033@morris.umn.edu"},
           discipline: "Art History",
           sponsors: [],
           adviserInfo: {first: "Mark", last: "Lehet", email: "lehet005@morris.umn.edu"},
           coadviserOneInfo: {},
           coadviserTwoInfo: {},
           featured: true,
           mediaServicesEquipment: "",
           specialRequirements: "A space to perform with three people.",
           presenterTeeSize: "M",
           otherInfo: "",
           approval: false,
           rejection: false,
           status: {strict: "Revisions Needed", text: "Your URS submission has been flagged for revisions, and is in need of changes."},
           timestamp: "Tue Oct 21 2014 23:22:54 GMT-0500 (CDT)",
           group: 1,
           resubmissionData: {comment: "Initial Submission", parentSubmission: "", isPrimary: true, resubmitFlag: false},
           comments:[],
           reviewVotes: {
                   Accepted: [],
                   Minor: [],
                   Major: [],
                   TotalRewrite: []
               }
        }
       ]
    });

    it('1 should equal 1...', function () {
        expect(1).toEqual(1);
    });

    describe('Functions controlling filtering...', function(){
        // Injecting the whole filter service here might be bad practice? IDK, but it works.
        it('Default review group filter should show ALL submissions...', inject(['$filter', function($filter) {
            expect($filter('filter')(scope.submissions, scope.reviewGroupFilter).length == scope.submissions.length).toEqual(true);
        }]));

        it('User with admin role should have admin privs.', inject(function(Auth){Auth.setCurrentUser("admin@admin.com", "admin", 1)}), function() {
            expect(scope.hasAdminPrivs()).toEqual(true);
        });

//        it('Should return true if featured is true, return false is featured is false', inject(['$filter', function(featurePresentationFilter) {
//            var $scope.filterData.featurePresentationFilterSelection = "";
//            scope.setFeaturePresentationFilterSelection("All");
//            expect(scope.featurePresentationFilter(scope.submissions[0]).toEqual(true);
////                expect(scope.featurePresentationFilter(scope.submissions[1])).toEqual(false);
//            }]));

        it("Submission's assigned review group members should be in same review group", inject(function(Auth){Auth.setCurrentUser("admin@admin.com", "admin", 3)}), function() {
            expect(scope.isReviewerGroup(scope.submissions[0])).toEqual(true);
        });

        it("Submission not in user's review group shouldn't be in user's review group", inject(function(Auth){Auth.setCurrentUser("admin@admin.com", "admin", 1)}), function(){
            expect(scope.isReviewerGroup(scope.submissions[0])).toEqual(false);
        });

        describe('Functions controlling filter tabs...', function() {
            it('No filtered tabs should be selected by default...', function() {
                for(var key in scope.filterData.tabFilter){
                    if(scope.filterData.tabFilter.hasOwnProperty(key)){
                        expect(scope.filterData.tabFilter[key]).toEqual(false);
                    }
                }
            });

            it('showMySubmissions should set the isPresenter tab to true', function() {
                scope.showMySubmissions();
                expect(scope.filterData.tabFilter.isPresenter).toEqual(true);
            });

            //TODO: more of these need to be written? Functions might need to be refactored to be more testable...
        });

    });

    describe("Functions controlling the selecting...", function() {
        it("No submission should be selected by default", function() {
            expect(scope.selection.selected).toEqual(false);
            expect(scope.selection.selected.item).toEqual(null);
            expect(scope.selection.selected.resubmission).toEqual(null);
        });

        it("selectItem() should set submission as selected", inject(function(Auth){Auth.setCurrentUser("admin@admin.com", "admin", 1)}), function() {
            scope.selectItem(1);
            expect(scope.selection.selected).toEqual(true);
            expect(scope.selection.item != null).toEqual(true);
            expect(scope.selection.item._id).toBe("testIdForTesting");
        });

        it("selectItem() should find resubmission of selected submission", inject(function(Auth){Auth.setCurrentUser("admin@admin.com", "admin", 1)}), function() {
            scope.selectItem(1);
            expect(scope.selection.resubmission != null).toEqual(true);
            expect(scope.selection.resubmission._id).toBe("uniqueIdString");
        });

        it("Selecting when filters are applied should select the correct submission (review group filter)", inject(function(Auth){Auth.setCurrentUser("admin@admin.com", "admin", 1)}), function() {
           expect(scope.selection.item).toEqual(null);
           scope.filterData.reviewGroupFilterSelection = "Review Group 1";
           scope.selectItem(0);
           expect(scope.selection.item.title).toBe("Blind Construction: Mixed Media");
        });

        it("Selecting when filters are applied should select correct submission (tab filters)", inject(function(Auth){Auth.setCurrentUser("opdah023@morris.umn.edu", "admin", 1)}), function() {
           expect(scope.selection.item).toEqual(null);
           scope.filterData.tabFilter.isPresenter = true;
           scope.selectItem(0);
           expect(scope.selection.item.title).toBe("Blind Construction: Mixed Media");
        });

        it("Selecting when filters are applied should select the correct submission (feature presentation)", inject(function(Auth){Auth.setCurrentUser("admin@admin.com", "admin", 1)}), function() {
            expect(scope.selection.item).toEqual(null);
            scope.filterData.featurePresentationFilterSelection = "Wants to be featured";
            scope.selectItem(0);
            expect(scope.selection.item.title).toBe("Blind Construction: Mixed Media");
        });

        it("Selecting when filters are applied should select the correct submission (flagged for resubmission)", inject(function(Auth){Auth.setCurrentUser("admin@admin.com", "admin", 1)}), function() {
            expect(scope.selection.item).toEqual(null);
            scope.filterData.flaggedForResubmitFilterSelection = "Not Flagged";
            scope.selectItem(0);
            expect(scope.selection.item.title).toBe("Blind Construction: Mixed Media");
        });

        it("Selecting when filters are applied should select the correct submission (pending resubmissions)", inject(function(Auth){Auth.setCurrentUser("admin@admin.com", "admin", 1)}), function() {
            expect(scope.selection.item).toEqual(null);
            scope.filterData.pendingResubmissionsOptions = "Not Pending Resubmissions";
            scope.selectItem(0);
            expect(scope.selection.item.title).toBe("Blind Construction: Mixed Media");
        });

    });

    describe('Functions handling resubmissions...', function() {
        it('Should be a resubmission... ', function() {
            expect(scope.isResubmission(scope.submissions[0])).toEqual(true);
        });

        it('Should find the resubmission of a submission', function() {
            expect(scope.getResubmission(scope.submissions[1]) != null).toEqual(true);
            expect(scope.getResubmission(scope.submissions[1])._id).toBe("uniqueIdString");
        })
    });

    describe('Functions handling approve/reject button...', function() {
        it('should be approved...', function () {
            expect(scope.submissions[0].approval).toEqual(true);
        });

        it('should not be rejected...', function (){
            expect(scope.submissions[1].rejection).toEqual(false);
        });

//        it('should be a rejection...', function (){
//           scope.rejectSubmission(scope.submissions);
//           expect(scope.submissions[1].rejection).toEqual(true);
//        });

    });

    describe('Testing the that the additional advisers are indeed in a submission...', function() {
        it('coadviserOneInfo for submission 1 [0] should be Dalton Gusaas...', function() {
            expect(scope.submissions[0].coadviserOneInfo).toEqual({ first : 'Dalton', last : 'Gusaas', email : 'gusaa004@morris.umn.edu'});
        });

        it('coadviserTwoInfo for submission 1 [0] should be blank...', function() {
            expect(scope.submissions[0].coadviserTwoInfo).toEqual({});
        });

        it('both coadvisers should be blank for submission 2 [1]...', function(){
           expect(scope.submissions[1].coadviserOneInfo && scope.submissions[1].coadviserTwoInfo).toEqual({});
        });

    });

});<commit_msg>Added testing for sublist voting aspects<commit_after>/**
* Created by saxxx027 on 11/10/14.
*/

'use strict';

describe('filter', function() {
    beforeEach(module('umm3601ursamajorApp'));

    describe('isntEmpty', function() {
        it('should return return the title and item ' +
            'if the item is an object with length over 0, not ' +
                'an object, but not "" or null, else altTitle',
          inject(function(isntEmptyFilter) {
              expect(isntEmptyFilter("item1", "First Item", "something else")).toBe("First Item item1");
              expect(isntEmptyFilter(21, "myNumber", "something else")).toBe("myNumber 21");
              expect(isntEmptyFilter(["happy", "days", "testing", "rocks"], "arrays", "something else")).toBe('arrays happy,days,testing,rocks');
              expect(isntEmptyFilter("", "something else", "this was an empty string")).toBe("this was an empty string");
          }));
    });

    describe('fancyLimitTo', function() {
        it('should return first "n" characters of the imputed text',
            inject(function(fancyLimitToFilter){
                expect(fancyLimitToFilter("abc", 1 )).toBe("a[...]");
                expect(fancyLimitToFilter("12345", 0)).toBe("[...]");
                expect(fancyLimitToFilter("", 5)).toBe("[...]");
            }));
    });

});

describe('Functions dealing with submissions...', function() {
    beforeEach(module('umm3601ursamajorApp'));
    beforeEach(module('socketMock'));
    beforeEach(module('authMock'));

    var SublistCtrl, scope;

    beforeEach(inject(function($controller, $rootScope) {
        scope = $rootScope.$new();
        SublistCtrl = $controller('SublistCtrl', {
            $scope: scope
        });
    }));

    beforeEach(function(){
       scope.submissions = [
        {
            _id: "uniqueIdString",
            title: "A Study of the Properties of a Paperclip in the Digestive System of a Sloth",
            format: "Artist Statement",
            abstract: "Many physicists would agree that, had it not been for scatter/gather I/O, the study of link-level acknowledgements might never have occurred. " +
                "While such a claim might seem unexpected, it usually conflicts with the need to provide thin clients to hackers worldwide. " +
                "In fact, few security experts would disagree with the construction of kernels. In order to overcome this question, we construct an analysis of the Ethernet (Mollah)," +
                " which we use to prove that redundancy and replication can interfere to achieve this aim. ",
            presentationType: "Oral Presentation",
            formatChange: false,
            presenterInfo: {first: "Hongya", last: "Zhou", email: "zhoux616@morris.umn.edu"},
            copresenterOneInfo: {first: "Otto", last: "Marckel II", email: "marck018@morris.umn.edu"},
            copresenterTwoInfo: {first: "Dalton", last: "Gusaas", email: "gusaa004@morris.umn.edu"},
            discipline: "Biology",
            sponsors: [], //Might need to worry about if this is static for the DB later.
            adviserInfo: {first: "Maggie", last: "Casale", email: "casal033@morris.umn.edu"},
            coadviserOneInfo: {first: "Dalton", last: "Gusaas", email: "gusaa004@morris.umn.edu"},
            coadviserTwoInfo: {},
            featured: false,
            mediaServicesEquipment: "",
            specialRequirements: "a sloth",
            presenterTeeSize: "M",
            otherInfo: "Maybe",
            approval: true,
            rejection: false,
            status: {strict: "Awaiting Adviser Approval", text: "Your adviser has yet to approve this submission."},
            timestamp: "Mon Oct 20 2014 1:48:54 GMT-0500 (CDT)",
            group: 3,
            resubmissionData: {comment: "Initial Submission", parentSubmission: "testIdForTesting", isPrimary: false, resubmitFlag: false},
            comments: [],
            reviewVotes: {
                Accepted: [],
                Minor: [],
                Major: [],
                TotalRewrite: []
            }
        }, {
           _id: "testIdForTesting",
           title: "Blind Construction: Mixed Media",
           format: "Artist Statement",
           abstract: "The basis of this project was to create a garment using mixed media in order to mimic the human body. " +
               "The materials we used to create this piece include: buckram, copper wire, spray paint, fabric paint, a variety of novelty fabrics, and chains.  " +
               "The techniques we created in order to manipulate the piece include: fabric branding and burning, grid painting, sewing, draping, molding buckram, and coiling.  " +
               "Our overall approach was to create a theatrical wearable art piece. " +
               "Upon completion of the assignment we found the piece aesthetically pleasing because of the way it molds to the human body, but can be a piece all on its own.",
           presentationType: "Performance",
           formatChange: false,
           presenterInfo: {first: "Jacob", last: "Opdahl", email: "opdah023@morris.umn.edu"},
           copresenterOneInfo: {first: "Savannah", last: "Farm", email: "farmx009@morris.umn.edu"},
           copresenterTwoInfo: {first: "Maggie", last: "Casale", email: "casal033@morris.umn.edu"},
           discipline: "Art History",
           sponsors: [],
           adviserInfo: {first: "Mark", last: "Lehet", email: "lehet005@morris.umn.edu"},
           coadviserOneInfo: {},
           coadviserTwoInfo: {},
           featured: true,
           mediaServicesEquipment: "",
           specialRequirements: "A space to perform with three people.",
           presenterTeeSize: "M",
           otherInfo: "",
           approval: false,
           rejection: false,
           status: {strict: "Revisions Needed", text: "Your URS submission has been flagged for revisions, and is in need of changes."},
           timestamp: "Tue Oct 21 2014 23:22:54 GMT-0500 (CDT)",
           group: 1,
           resubmissionData: {comment: "Initial Submission", parentSubmission: "", isPrimary: true, resubmitFlag: false},
           comments:[],
           reviewVotes: {
                Accepted: [],
                Minor: [],
                Major: ["reviewer@reviewer.com"],
                TotalRewrite: []
           }
        }
       ]
    });

    it('1 should equal 1...', function () {
        expect(1).toEqual(1);
    });

    describe('Functions controlling filtering...', function(){
        // Injecting the whole filter service here might be bad practice? IDK, but it works.
        it('Default review group filter should show ALL submissions...', inject(['$filter', function($filter) {
            expect($filter('filter')(scope.submissions, scope.reviewGroupFilter).length == scope.submissions.length).toEqual(true);
        }]));

        it('User with admin role should have admin privs.', inject(function(Auth){Auth.setCurrentUser("admin@admin.com", "admin", 1)}), function() {
            expect(scope.hasAdminPrivs()).toEqual(true);
        });

//        it('Should return true if featured is true, return false is featured is false', inject(['$filter', function(featurePresentationFilter) {
//            var $scope.filterData.featurePresentationFilterSelection = "";
//            scope.setFeaturePresentationFilterSelection("All");
//            expect(scope.featurePresentationFilter(scope.submissions[0]).toEqual(true);
////                expect(scope.featurePresentationFilter(scope.submissions[1])).toEqual(false);
//            }]));

        it("Submission's assigned review group members should be in same review group", inject(function(Auth){Auth.setCurrentUser("admin@admin.com", "admin", 3)}), function() {
            expect(scope.isReviewerGroup(scope.submissions[0])).toEqual(true);
        });

        it("Submission not in user's review group shouldn't be in user's review group", inject(function(Auth){Auth.setCurrentUser("admin@admin.com", "admin", 1)}), function(){
            expect(scope.isReviewerGroup(scope.submissions[0])).toEqual(false);
        });

        describe('Functions controlling filter tabs...', function() {
            it('No filtered tabs should be selected by default...', function() {
                for(var key in scope.filterData.tabFilter){
                    if(scope.filterData.tabFilter.hasOwnProperty(key)){
                        expect(scope.filterData.tabFilter[key]).toEqual(false);
                    }
                }
            });

            it('showMySubmissions should set the isPresenter tab to true', function() {
                scope.showMySubmissions();
                expect(scope.filterData.tabFilter.isPresenter).toEqual(true);
            });

            //TODO: more of these need to be written? Functions might need to be refactored to be more testable...
        });

    });

    describe("Functions controlling the selecting...", function() {
        it("No submission should be selected by default", function() {
            expect(scope.selection.selected).toEqual(false);
            expect(scope.selection.selected.item).toEqual(null);
            expect(scope.selection.selected.resubmission).toEqual(null);
        });

        it("selectItem() should set submission as selected", inject(function(Auth){Auth.setCurrentUser("admin@admin.com", "admin", 1)}), function() {
            scope.selectItem(1);
            expect(scope.selection.selected).toEqual(true);
            expect(scope.selection.item != null).toEqual(true);
            expect(scope.selection.item._id).toBe("testIdForTesting");
        });

        it("selectItem() should find resubmission of selected submission", inject(function(Auth){Auth.setCurrentUser("admin@admin.com", "admin", 1)}), function() {
            scope.selectItem(1);
            expect(scope.selection.resubmission != null).toEqual(true);
            expect(scope.selection.resubmission._id).toBe("uniqueIdString");
        });

        it("Selecting when filters are applied should select the correct submission (review group filter)", inject(function(Auth){Auth.setCurrentUser("admin@admin.com", "admin", 1)}), function() {
           expect(scope.selection.item).toEqual(null);
           scope.filterData.reviewGroupFilterSelection = "Review Group 1";
           scope.selectItem(0);
           expect(scope.selection.item.title).toBe("Blind Construction: Mixed Media");
        });

        it("Selecting when filters are applied should select correct submission (tab filters)", inject(function(Auth){Auth.setCurrentUser("opdah023@morris.umn.edu", "admin", 1)}), function() {
           expect(scope.selection.item).toEqual(null);
           scope.filterData.tabFilter.isPresenter = true;
           scope.selectItem(0);
           expect(scope.selection.item.title).toBe("Blind Construction: Mixed Media");
        });

        it("Selecting when filters are applied should select the correct submission (feature presentation)", inject(function(Auth){Auth.setCurrentUser("admin@admin.com", "admin", 1)}), function() {
            expect(scope.selection.item).toEqual(null);
            scope.filterData.featurePresentationFilterSelection = "Wants to be featured";
            scope.selectItem(0);
            expect(scope.selection.item.title).toBe("Blind Construction: Mixed Media");
        });

        it("Selecting when filters are applied should select the correct submission (flagged for resubmission)", inject(function(Auth){Auth.setCurrentUser("admin@admin.com", "admin", 1)}), function() {
            expect(scope.selection.item).toEqual(null);
            scope.filterData.flaggedForResubmitFilterSelection = "Not Flagged";
            scope.selectItem(0);
            expect(scope.selection.item.title).toBe("Blind Construction: Mixed Media");
        });

        it("Selecting when filters are applied should select the correct submission (pending resubmissions)", inject(function(Auth){Auth.setCurrentUser("admin@admin.com", "admin", 1)}), function() {
            expect(scope.selection.item).toEqual(null);
            scope.filterData.pendingResubmissionsOptions = "Not Pending Resubmissions";
            scope.selectItem(0);
            expect(scope.selection.item.title).toBe("Blind Construction: Mixed Media");
        });

    });

    describe('Functions handling resubmissions...', function() {
        it('Should be a resubmission... ', function() {
            expect(scope.isResubmission(scope.submissions[0])).toEqual(true);
        });

        it('Should find the resubmission of a submission', function() {
            expect(scope.getResubmission(scope.submissions[1]) != null).toEqual(true);
            expect(scope.getResubmission(scope.submissions[1])._id).toBe("uniqueIdString");
        })
    });

    describe('Functions handling approve/reject button...', function() {
        it('should be approved...', function () {
            expect(scope.submissions[0].approval).toEqual(true);
        });

        it('should not be rejected...', function (){
            expect(scope.submissions[1].rejection).toEqual(false);
        });

//        it('should be a rejection...', function (){
//           scope.rejectSubmission(scope.submissions);
//           expect(scope.submissions[1].rejection).toEqual(true);
//        });

    });

    describe('Testing the that the additional advisers are indeed in a submission...', function() {
        it('coadviserOneInfo for submission 1 [0] should be Dalton Gusaas...', function() {
            expect(scope.submissions[0].coadviserOneInfo).toEqual({ first : 'Dalton', last : 'Gusaas', email : 'gusaa004@morris.umn.edu'});
        });

        it('coadviserTwoInfo for submission 1 [0] should be blank...', function() {
            expect(scope.submissions[0].coadviserTwoInfo).toEqual({});
        });

        it('both coadvisers should be blank for submission 2 [1]...', function(){
           expect(scope.submissions[1].coadviserOneInfo && scope.submissions[1].coadviserTwoInfo).toEqual({});
        });

    });

    describe('Testing voting by looking for certain statuses...', function() {
        it('Major for submission 2 [1] should be reviewer@reviewer.com...', function() {
            expect(scope.submissions[1].reviewVotes.Major.length).toEqual(1);
        });

        it('Accepted for submission 1 [0] should be blank...', function() {
            expect(scope.submissions[0].reviewVotes.Accepted.length).toEqual(0);
        });

    });

    describe('Testing for statuses in submissions...', function() {
        it('Status for submission 1 [0] should be "Awaiting Adviser Approval"...', function() {
            expect(scope.submissions[0].status).toEqual({strict: 'Awaiting Adviser Approval', text: 'Your adviser has yet to approve this submission.'});
        });

        it('Status for submission 2 [1] should be "Awaiting Adviser Approval"...', function() {
            expect(scope.submissions[1].status).toEqual({strict: 'Revisions Needed', text: 'Your URS submission has been flagged for revisions, and is in need of changes.'});
        });

    });
});<|endoftext|>


<commit_before>const checkParentConsent = (parentConsents) => {
	const agrements = parentConsents.filter((consent) => consent.privacyConsent && consent.termsOfUseConsent);
	if (parentConsents.length !== 0 && agrements.length === parentConsents.length) {
		return true;
	}

	return false;
};

const checkUserConsent = (userConsent) => {
	if (userConsent
		&& userConsent.privacyConsent === true
		&& userConsent.termsOfUseConsent === true
	) {
		return true;
	}

	return false;
};

const defineConsentStatus = (birthday, consent) => {
	if (!consent) {
		return 'missing';
	}

	if (!birthday) {
		return 'unknown';
	}

	const currentDate = new Date();
	const secoundConsentSwitchDate = new Date();
	secoundConsentSwitchDate.setFullYear(currentDate.getFullYear() - 16); // TODO: get age from default.conf
	const firstConsentSwitchDate = new Date();
	firstConsentSwitchDate.setFullYear(currentDate.getFullYear() - 14);

	const { parentConsents, userConsent } = consent;
	let amount = 0;

	if (birthday.getTime() > firstConsentSwitchDate.getTime()) {
		// only parents have to agre
		if (checkParentConsent(parentConsents) === true) {
			amount = 2;
		}
	} else if (birthday.getTime() < secoundConsentSwitchDate.getTime()) {
		// only user have to agre
		if (checkUserConsent(userConsent) === true) {
			amount = 2;
		}
	} else {
		// parents and user have to agre
		amount = checkParentConsent(parentConsents) + checkUserConsent(userConsent);
	}

	switch (amount) {
		case 2:
			return 'ok';

		case 1:
			return 'parentsAgreed';
		default:
			return 'missing';
	}
};

const isParentConsentRequired = (birthday) => {
	const currentDate = new Date();
	const secoundConsentSwitchDate = new Date();
	secoundConsentSwitchDate.setFullYear(currentDate.getFullYear() - 16); // TODO: get age from default.conf

	if (birthday.getTime() < secoundConsentSwitchDate.getTime()) {
		return false;
	}

	return true;
};

module.exports = {
	defineConsentStatus,
	isParentConsentRequired,
};
<commit_msg>fix error when parentConsents undefined<commit_after>const checkParentConsent = (parentConsents = []) => {
	const agrements = parentConsents.filter((consent) => consent.privacyConsent && consent.termsOfUseConsent);
	if (parentConsents.length !== 0 && agrements.length === parentConsents.length) {
		return true;
	}

	return false;
};

const checkUserConsent = (userConsent) => {
	if (userConsent
		&& userConsent.privacyConsent === true
		&& userConsent.termsOfUseConsent === true
	) {
		return true;
	}

	return false;
};

const defineConsentStatus = (birthday, consent) => {
	if (!consent) {
		return 'missing';
	}

	if (!birthday) {
		return 'unknown';
	}

	const currentDate = new Date();
	const secoundConsentSwitchDate = new Date();
	secoundConsentSwitchDate.setFullYear(currentDate.getFullYear() - 16); // TODO: get age from default.conf
	const firstConsentSwitchDate = new Date();
	firstConsentSwitchDate.setFullYear(currentDate.getFullYear() - 14);

	const { parentConsents, userConsent } = consent;
	let amount = 0;

	if (birthday.getTime() > firstConsentSwitchDate.getTime()) {
		// only parents have to agre
		if (checkParentConsent(parentConsents) === true) {
			amount = 2;
		}
	} else if (birthday.getTime() < secoundConsentSwitchDate.getTime()) {
		// only user have to agre
		if (checkUserConsent(userConsent) === true) {
			amount = 2;
		}
	} else {
		// parents and user have to agre
		amount = checkParentConsent(parentConsents) + checkUserConsent(userConsent);
	}

	switch (amount) {
		case 2:
			return 'ok';

		case 1:
			return 'parentsAgreed';
		default:
			return 'missing';
	}
};

const isParentConsentRequired = (birthday) => {
	const currentDate = new Date();
	const secoundConsentSwitchDate = new Date();
	secoundConsentSwitchDate.setFullYear(currentDate.getFullYear() - 16); // TODO: get age from default.conf

	if (birthday.getTime() < secoundConsentSwitchDate.getTime()) {
		return false;
	}

	return true;
};

module.exports = {
	defineConsentStatus,
	isParentConsentRequired,
};
<|endoftext|>


<commit_before>const express = require('express');
const jsonParser = require('body-parser').json({ limit: 10240000 });
const Content = require(__dirname + '/../models/content');
const handleDBError = require(__dirname + '/../lib/handle_db_error');
const jwtAuth = require(__dirname + '/../lib/jwt_auth');

var Readable = require('stream').Readable;
var Writable = require('stream').Writable;

var transformBlur = require('bindings')('matrix');

var PixelStream = require('pixel-stream');
var JPEGDecoder = require('jpg-stream/decoder');
var JPEGEncoder = require('jpg-stream/encoder');
var inherits = require('util').inherits;
var allPixels = [];

function MyPixelStream() {
  PixelStream.apply(this, arguments);
}

inherits(MyPixelStream, PixelStream);

MyPixelStream.prototype._writePixels = function(data, done) {
  for (var i = 0; i < data.length; i++) {
    allPixels.push(data[i]);
  }
  done();
};

MyPixelStream.prototype._end = function(done) {
  var translatedPixels = new Int32Array(allPixels);

  var newPix = transformBlur.blurry(translatedPixels, this.format.width, this.format.height);
  var bufTrans = new Buffer(newPix.length);
  for (var j = 0; j < translatedPixels.length; j++) {
    bufTrans[j] = newPix[j];
  }

  this.push(bufTrans);
  allPixels = null;
  allPixels = [];
  translatedPixels = null;
  newPix = null;
  bufTrans = null;
  done();
};

var contentRouter = module.exports = exports = express.Router();

contentRouter.get('/getlatest', jwtAuth, (req, res) => {
  Content.findOne({ contentId: req.user._id, $sortBy: 'createdOn' }, (err, data) => {
    if (err) return handleDBError(err, res);

    res.status(200).json(data);
  });
});

contentRouter.get('/getAll', jwtAuth, (req, res) => {
  Content.find({ user_id: req.user._id }, (err, data) => {
    if (err) return handleDBError(err, res);

    res.status(200).json(data);
  });
});

contentRouter.post('/newcontent', jwtAuth, jsonParser, (req, res) => {
  if (req.body.content.length > 1000000) {
    return res.status(500).json( { 'msg': 'Error: image too large' } );
  }

  var newContent = new Content();
  newContent.user_id = req.user._id;
  newContent.tOption = req.body.tOption;

  if ( newContent.tOption === 'blur') {
    var tempBuffer = new Buffer(req.body.content.slice(23), 'base64');
    var outArray = [];
    var myStream = Readable();
    var ws = Writable();
    ws._write = function(chunk, enc, next) {
      outArray.push(chunk);
      next();
    };
    ws.on('finish', function() {
      var transfer = new Buffer(req.body.content.length - 23);
      var i = 0;
      for (var k = 0; k < outArray.length; k++) {
        for (var l = 0; l < outArray[k].length; l++) {
          if (i < transfer.length) {
            transfer.writeUInt8(outArray[k][l], i++);
          }
        }
      }
      outArray = null;
      tempBuffer = null;

      newContent.content = 'data:image/jpeg;base64,';
      newContent.content += transfer.toString('base64');
      transfer = null;
      newContent.save((err, data) => {

        if (err) return handleDBError(err, res);

        res.status(200).json(data);
      });
      newContent = null;
    });
    try {
      myStream.push(tempBuffer);
      myStream.push(null);
      myStream.pipe(new JPEGDecoder())
      .pipe(new MyPixelStream())
      .pipe(new JPEGEncoder())
      .pipe(ws);
    } catch (e) {
      return console.log('Error in processing image: ', e);
    }

  } else {
    newContent.content = req.body.content;
    newContent.save((err, data) => {

      if (err) return handleDBError(err, res);

      res.status(200).json(data);
    });
    newContent = null;
  }
});

contentRouter.post('/save', jwtAuth, jsonParser, (req, res) => {
  var newContent = new Content(req.body);
  newContent.user_id = req.user._id;
  newContent.save((err, data) => {
    if (err) return handleDBError(err, res);

    res.status(200).json(data);
  });
});

contentRouter.put('/preview/:id', jwtAuth, jsonParser, (req, res) => {
  var contentData = req.body;
  Content.update({ _id: req.params.id }, contentData, (err) => {
    if (err) return handleDBError(err, res);

    res.status(200).json({ msg: 'Successfully updated content' });
  });
});

contentRouter.delete('/delete/:id', jwtAuth, (req, res) => {
  Content.remove({ _id: req.params.id }, (err) => {
    if (err) return handleDBError(err, res);

    res.status(200).json({ msg: 'Successfully deleted content' });
  });
});
<commit_msg>Increasing possible file size.<commit_after>const express = require('express');
const jsonParser = require('body-parser').json({ limit: 16000000 });
const Content = require(__dirname + '/../models/content');
const handleDBError = require(__dirname + '/../lib/handle_db_error');
const jwtAuth = require(__dirname + '/../lib/jwt_auth');

var Readable = require('stream').Readable;
var Writable = require('stream').Writable;

var transformBlur = require('bindings')('matrix');

var PixelStream = require('pixel-stream');
var JPEGDecoder = require('jpg-stream/decoder');
var JPEGEncoder = require('jpg-stream/encoder');
var inherits = require('util').inherits;
var allPixels = [];

function MyPixelStream() {
  PixelStream.apply(this, arguments);
}

inherits(MyPixelStream, PixelStream);

MyPixelStream.prototype._writePixels = function(data, done) {
  for (var i = 0; i < data.length; i++) {
    allPixels.push(data[i]);
  }
  done();
};

MyPixelStream.prototype._end = function(done) {
  var translatedPixels = new Int32Array(allPixels);

  var newPix = transformBlur.blurry(translatedPixels, this.format.width, this.format.height);
  var bufTrans = new Buffer(newPix.length);
  for (var j = 0; j < translatedPixels.length; j++) {
    bufTrans[j] = newPix[j];
  }

  this.push(bufTrans);
  allPixels = null;
  allPixels = [];
  translatedPixels = null;
  newPix = null;
  bufTrans = null;
  done();
};

var contentRouter = module.exports = exports = express.Router();

contentRouter.get('/getlatest', jwtAuth, (req, res) => {
  Content.findOne({ contentId: req.user._id, $sortBy: 'createdOn' }, (err, data) => {
    if (err) return handleDBError(err, res);

    res.status(200).json(data);
  });
});

contentRouter.get('/getAll', jwtAuth, (req, res) => {
  Content.find({ user_id: req.user._id }, (err, data) => {
    if (err) return handleDBError(err, res);

    res.status(200).json(data);
  });
});

contentRouter.post('/newcontent', jwtAuth, jsonParser, (req, res) => {
  debugger;
  if (req.body.content.length > 16000000) {
    return res.status(500).json( { 'msg': 'Error: image too large' } );
  }

  var newContent = new Content();
  newContent.user_id = req.user._id;
  newContent.tOption = req.body.tOption;

  if ( newContent.tOption === 'blur') {
    var tempBuffer = new Buffer(req.body.content.slice(23), 'base64');
    var outArray = [];
    var myStream = Readable();
    var ws = Writable();
    ws._write = function(chunk, enc, next) {
      outArray.push(chunk);
      next();
    };
    ws.on('finish', function() {
      var transfer = new Buffer(req.body.content.length - 23);
      var i = 0;
      for (var k = 0; k < outArray.length; k++) {
        for (var l = 0; l < outArray[k].length; l++) {
          if (i < transfer.length) {
            transfer.writeUInt8(outArray[k][l], i++);
          }
        }
      }
      outArray = null;
      tempBuffer = null;

      newContent.content = 'data:image/jpeg;base64,';
      newContent.content += transfer.toString('base64');
      transfer = null;
      newContent.save((err, data) => {

        if (err) return handleDBError(err, res);

        res.status(200).json(data);
      });
      newContent = null;
    });
    try {
      myStream.push(tempBuffer);
      myStream.push(null);
      myStream.pipe(new JPEGDecoder())
      .pipe(new MyPixelStream())
      .pipe(new JPEGEncoder())
      .pipe(ws);
    } catch (e) {
      return console.log('Error in processing image: ', e);
    }

  } else {
    newContent.content = req.body.content;
    newContent.save((err, data) => {

      if (err) return handleDBError(err, res);

      res.status(200).json(data);
    });
    newContent = null;
  }
});

contentRouter.post('/save', jwtAuth, jsonParser, (req, res) => {
  var newContent = new Content(req.body);
  newContent.user_id = req.user._id;
  newContent.save((err, data) => {
    if (err) return handleDBError(err, res);

    res.status(200).json(data);
  });
});

contentRouter.put('/preview/:id', jwtAuth, jsonParser, (req, res) => {
  var contentData = req.body;
  Content.update({ _id: req.params.id }, contentData, (err) => {
    if (err) return handleDBError(err, res);

    res.status(200).json({ msg: 'Successfully updated content' });
  });
});

contentRouter.delete('/delete/:id', jwtAuth, (req, res) => {
  Content.remove({ _id: req.params.id }, (err) => {
    if (err) return handleDBError(err, res);

    res.status(200).json({ msg: 'Successfully deleted content' });
  });
});
<|endoftext|>