<commit_before>'use strict';

var singleForm,
    monthNames = [
        "Jan", "Feb", "Mar",
        "Apr", "May", "Jun", "Jul",
        "Aug", "Sep", "Oct",
        "Nov", "Dec"
    ];

document.addEventListener("DOMContentLoaded", () => {
    // Initializes the Single Form variable
    singleForm = document.getElementById("single-form");

    if (singleForm) {
        // Add an event listener to the Single Form
        document.addEventListener("click", pageClick)
        singleForm.addEventListener('submit', submitHandler);
        singleForm.addEventListener('keyup', escapeHandler)

        // Get all the edit buttons and initialize them
        var btns = document.getElementsByClassName("edit");
        Array.from(btns).forEach(editHandler);

        // Initialize add button
        document.getElementById("add").addEventListener("click", newHandler);
        document.getElementById("delete").addEventListener("click", deleteHandler);
        document.getElementById("edit").addEventListener("click", editMultipleHandler);

        document.getElementById('expand').addEventListener('click', function(event) {
            event.preventDefault();
            singleForm.classList.toggle("show");
        });

        let rows = document.querySelectorAll('tr');
        Array.from(rows).forEach((row) => {
            row.addEventListener('click', function(event) {
                this.classList.toggle('highlight');
            });
        });
    }

    highlight();
});

function highlight() {
    let hash = window.location.hash.replace('#', '');
    let items = hash.split(',')

    for (var i = 0; i < items.length; i++) {
        let row = document.querySelector('tr[data-id="' + items[i] + '"]');
        if (typeof row == 'undefined' || row == null) continue;
        row.classList.add('highlight');
    }
}

function pageClick(event) {
    for (let i = 0; i < event.path.length; i++) {
        if (event.path[i].id == "add" ||
            event.path[i].id == "single-form" ||
            event.path[i].id == "delete" ||
            event.path[i].id == "edit") {
            return true;
        }

        if (event.path[i].className == "edit") {
            return true;
        }
    }

    if (singleForm.classList.contains("show")) {
        singleForm.classList.remove("show");
    }
}

function escapeHandler(event) {
    if (event.key == "Escape") {
        document.getElementById("single-form").classList.remove("show");
    }
}

function newHandler(event) {
    if (!singleForm.classList.contains("show")) {
        singleForm.classList.add('show');
    }

    clearForm(singleForm);
    singleForm.children[1].children[3].focus();
}

function editHandler(btn) {
    btn.addEventListener("click", function(e) {
        e.preventDefault();
        singleForm.querySelector('#edit-text').style.display = "block";
        singleForm.querySelector('#new-text').style.display = "none";
        singleForm.classList.add("show");
        copyRowToForm(btn.parentElement.parentElement);
        singleForm.children[1].children[3].focus();
    });
}

function editMultipleHandler(event) {
    event.preventDefault();

    var div = singleForm.children[1];

    singleForm.querySelector('#edit-text').style.display = "block";
    singleForm.querySelector('#new-text').style.display = "none";
    document.getElementById('barID').innerHTML = "multiple";

    for (var x = 0; x < div.childElementCount; x++) {
        let type = div.children[x].type;

        if (typeof type == "undefined") {
            continue;
        }

        div.children[x].value = "";

        switch (type) {
            case "checkbox":
                div.children[x].dataset.initial = false;
                div.children[x].checked = false;
                break;
            default:
                div.children[x].placeholder = "(multiple values)";
                break;
        }
    }

    singleForm.classList.add("show");
}

function deleteHandler(event) {
    event.preventDefault();

    Array.from(document.querySelectorAll('tr.highlight')).forEach((row) => {
        let link = "/admin/" + window.location.pathname.split("/")[2] + "/" + row.dataset.id
        let request = new XMLHttpRequest();

        request.open("DELETE", link);
        request.onreadystatechange = function() {
            if (request.readyState == 4) {
                if (request.status == 200) {
                    row.querySelector('td[data-name="Deactivated"] input[type="checkbox"]').checked = true;
                    row.classList.remove("highlight");
                }
            }
        }
        request.send();
    });
}

function submitHandler(event) {
    event.preventDefault();

    let data = copyFormToObject(this);
    let method = (data.ID == 0) ? 'POST' : 'PUT';
    let link = this.dataset.link;

    if (data.ID != 0) {
        link += "/" + data.ID;
    }

    let request = new XMLHttpRequest();
    request.open(method, link);
    request.send(JSON.stringify(data));
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            if (request.status == 200) {
                singleForm.className = "Down";

                if (method == "PUT") {
                    copyFormToRow(document.querySelector('tr[data-id="' + data.ID + '"]'));
                } else {
                    window.location.pathname = "/admin/" + window.location.pathname.split("/")[2] + "/" + request.responseText;
                }
            } else {
                formError("Something went wrong.", "error")
            }
        }
    }
}

function copyFormToRow(row) {
    let form = singleForm;

    if (typeof form == 'undefined') {
        return;
    }

    let div = form.querySelector('div');

    if (typeof div == 'undefined') {
        return;
    }

    for (var i = 0; i < div.childElementCount; i++) {
        let name = div.children[i].name;

        if (typeof name == 'undefined' || name == null || name == "") {
            continue;
        }

        let space = row.querySelector('td[data-name="' + name + '"]');

        if (typeof space == 'undefined' || space == null) {
            continue;
        }

        switch (div.children[i].type) {
            case "datetime-local":
                space.innerHTML = getPrettyDate(new Date(div.children[i].value));
                break;
            case "checkbox":
                space.querySelector('input[type="checkbox"]').checked = div.children[i].checked;
                break;
            default:
                space.innerHTML = div.children[i].value;
        }
    }
}

// getPrettyDate puts the date in a 22 Oct 99 08:48 UTC pretty format
function getPrettyDate(date) {
    let pretty;

    let normalize = function(number) {
        if (number.length == 1) {
            return "0" + number;
        }

        return number;
    }

    pretty = normalize(date.getUTCDate().toString()) + " "
    pretty += monthNames[date.getUTCMonth()] + " "
    pretty += date.getUTCFullYear().toString().substr(2, 2) + " "
    pretty += normalize(date.getUTCHours().toString()) + ":"
    pretty += normalize(date.getUTCMinutes().toString()) + " UTC"

    return pretty;
}

// Copies the information from a row to the editor form
function copyRowToForm(row) {
    let form = singleForm;

    if (typeof form == 'undefined') {
        return;
    }

    for (var x = 0; x < row.childElementCount - 1; x++) {
        let data = row.children[x].dataset.name,
            input = form.querySelector("input[name=" + data + "]"),
            barID = form.querySelector("#barID");

        if (data == "ID") {
            barID.innerHTML = row.children[x].innerHTML;
        }

        switch (input.type) {
            case "datetime-local":
                input.value = new Date(row.children[x].innerHTML).toISOString().substr(0, 16);
                break;
            case "checkbox":
                input.checked = row.children[x].children[0].checked;
                break;
            default:
                input.value = row.children[x].innerHTML;
        }
    }
}

function copyFormToObject(form) {
    let object = new Object();
    object.ID = 0;

    let div = form.querySelector('div');

    for (var i = 0; i < div.childElementCount; i++) {
        let name = div.children[i].name;

        if (typeof name == 'undefined' || name == null || name == "") {
            continue;
        }

        switch (div.children[i].type) {
            case "number":
                object[name] = parseInt(div.children[i].value);
                break;
            case "datetime-local":
                object[name] = (new Date(div.children[i].value)).toISOString();
                break;
            case "checkbox":
                object[name] = div.children[i].checked;
                break;
            default:
                object[name] = div.children[i].value;
        }
    }

    if (isNaN(object.ID)) object.ID = 0;
    return object;
}

function clearForm(form) {
    var div = form.children[1];

    singleForm.querySelector('#edit-text').style.display = "none";
    singleForm.querySelector('#new-text').style.display = "block";

    for (var x = 0; x < div.childElementCount; x++) {
        let type = div.children[x].type;

        if (typeof type == "undefined") {
            continue;
        }

        switch (type) {
            case "checkbox":
                div.children[x].checked = false;
                break;
            case "number":
                div.children[x].value = "0";
                break;
            default:
                div.children[x].value = "";
        }
    }
}
<commit_msg>make activate button work<commit_after>'use strict';

var singleForm,
    monthNames = [
        "Jan", "Feb", "Mar",
        "Apr", "May", "Jun", "Jul",
        "Aug", "Sep", "Oct",
        "Nov", "Dec"
    ];

document.addEventListener("DOMContentLoaded", () => {
    // Initializes the Single Form variable
    singleForm = document.getElementById("single-form");

    if (singleForm) {
        // Add an event listener to the Single Form
        document.addEventListener("click", pageClick)
        singleForm.addEventListener('submit', submitHandler);
        singleForm.addEventListener('keyup', escapeHandler)

        // Get all the edit buttons and initialize them
        var btns = document.getElementsByClassName("edit");
        Array.from(btns).forEach(editHandler);

        // Initialize add button
        document.getElementById("add").addEventListener("click", newHandler);
        document.getElementById("delete").addEventListener("click", deleteHandler);
        document.getElementById("edit").addEventListener("click", editMultipleHandler);
        document.getElementById("activate").addEventListener("click", activateHandler);

        document.getElementById('expand').addEventListener('click', function(event) {
            event.preventDefault();
            singleForm.classList.toggle("show");
        });

        let rows = document.querySelectorAll('tr');
        Array.from(rows).forEach((row) => {
            row.addEventListener('click', function(event) {
                this.classList.toggle('highlight');
            });
        });
    }

    highlight();
});

function highlight() {
    let hash = window.location.hash.replace('#', '');
    let items = hash.split(',')

    for (var i = 0; i < items.length; i++) {
        let row = document.querySelector('tr[data-id="' + items[i] + '"]');
        if (typeof row == 'undefined' || row == null) continue;
        row.classList.add('highlight');
    }
}

function pageClick(event) {
    for (let i = 0; i < event.path.length; i++) {
        if (event.path[i].id == "add" ||
            event.path[i].id == "single-form" ||
            event.path[i].id == "delete" ||
            event.path[i].id == "edit") {
            return true;
        }

        if (event.path[i].className == "edit") {
            return true;
        }
    }

    if (singleForm.classList.contains("show")) {
        singleForm.classList.remove("show");
    }
}

function escapeHandler(event) {
    if (event.key == "Escape") {
        document.getElementById("single-form").classList.remove("show");
    }
}

function newHandler(event) {
    if (!singleForm.classList.contains("show")) {
        singleForm.classList.add('show');
    }

    clearForm(singleForm);
    singleForm.children[1].children[3].focus();
}

function editHandler(btn) {
    btn.addEventListener("click", function(e) {
        e.preventDefault();
        singleForm.querySelector('#edit-text').style.display = "block";
        singleForm.querySelector('#new-text').style.display = "none";
        singleForm.classList.add("show");
        copyRowToForm(btn.parentElement.parentElement);
        singleForm.children[1].children[3].focus();
    });
}

function editMultipleHandler(event) {
    event.preventDefault();

    var div = singleForm.children[1];

    singleForm.querySelector('#edit-text').style.display = "block";
    singleForm.querySelector('#new-text').style.display = "none";
    document.getElementById('barID').innerHTML = "multiple";

    for (var x = 0; x < div.childElementCount; x++) {
        let type = div.children[x].type;

        if (typeof type == "undefined") {
            continue;
        }

        div.children[x].value = "";

        switch (type) {
            case "checkbox":
                div.children[x].dataset.initial = false;
                div.children[x].checked = false;
                break;
            default:
                div.children[x].placeholder = "(multiple values)";
                break;
        }
    }

    singleForm.classList.add("show");
}

function deleteHandler(event) {
    event.preventDefault();

    Array.from(document.querySelectorAll('tr.highlight')).forEach((row) => {
        let link = "/admin/" + window.location.pathname.split("/")[2] + "/" + row.dataset.id
        let request = new XMLHttpRequest();

        request.open("DELETE", link);
        request.onreadystatechange = function() {
            if (request.readyState == 4) {
                if (request.status == 200) {
                    row.querySelector('td[data-name="Deactivated"] input[type="checkbox"]').checked = true;
                    row.classList.remove("highlight");
                }
            }
        }
        request.send();
    });
}

function activateHandler(event) {
    event.preventDefault();

    Array.from(document.querySelectorAll('tr.highlight')).forEach((row) => {
        let link = "/admin/" + window.location.pathname.split("/")[2] + "/" + row.dataset.id

        copyRowToForm(row);
        let data = copyFormToObject(singleForm);
        data["Deactivated"] = false;

        let request = new XMLHttpRequest();
        request.open("PUT", link);
        request.send(JSON.stringify(data));
        request.onreadystatechange = function() {
            if (request.readyState == 4) {
                if (request.status == 200) {
                    row.querySelector('td[data-name="Deactivated"] input[type="checkbox"]').checked = false;
                    row.classList.remove("highlight");
                }
            }
        }
    });
}

function submitHandler(event) {
    event.preventDefault();

    let data = copyFormToObject(this);
    let method = (data.ID == 0) ? 'POST' : 'PUT';
    let link = this.dataset.link;

    if (data.ID != 0) {
        link += "/" + data.ID;
    }

    let request = new XMLHttpRequest();
    request.open(method, link);
    request.send(JSON.stringify(data));
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            if (request.status == 200) {
                singleForm.className = "Down";

                if (method == "PUT") {
                    copyFormToRow(document.querySelector('tr[data-id="' + data.ID + '"]'));
                } else {
                    window.location.pathname = "/admin/" + window.location.pathname.split("/")[2] + "/" + request.responseText;
                }
            } else {
                formError("Something went wrong.", "error")
            }
        }
    }
}

function copyFormToRow(row) {
    let form = singleForm;

    if (typeof form == 'undefined') {
        return;
    }

    let div = form.querySelector('div');

    if (typeof div == 'undefined') {
        return;
    }

    for (var i = 0; i < div.childElementCount; i++) {
        let name = div.children[i].name;

        if (typeof name == 'undefined' || name == null || name == "") {
            continue;
        }

        let space = row.querySelector('td[data-name="' + name + '"]');

        if (typeof space == 'undefined' || space == null) {
            continue;
        }

        switch (div.children[i].type) {
            case "datetime-local":
                space.innerHTML = getPrettyDate(new Date(div.children[i].value));
                break;
            case "checkbox":
                space.querySelector('input[type="checkbox"]').checked = div.children[i].checked;
                break;
            default:
                space.innerHTML = div.children[i].value;
        }
    }
}

// getPrettyDate puts the date in a 22 Oct 99 08:48 UTC pretty format
function getPrettyDate(date) {
    let pretty;

    let normalize = function(number) {
        if (number.length == 1) {
            return "0" + number;
        }

        return number;
    }

    pretty = normalize(date.getUTCDate().toString()) + " "
    pretty += monthNames[date.getUTCMonth()] + " "
    pretty += date.getUTCFullYear().toString().substr(2, 2) + " "
    pretty += normalize(date.getUTCHours().toString()) + ":"
    pretty += normalize(date.getUTCMinutes().toString()) + " UTC"

    return pretty;
}

// Copies the information from a row to the editor form
function copyRowToForm(row) {
    let form = singleForm;

    if (typeof form == 'undefined') {
        return;
    }

    for (var x = 0; x < row.childElementCount - 1; x++) {
        let data = row.children[x].dataset.name,
            input = form.querySelector("input[name=" + data + "]"),
            barID = form.querySelector("#barID");

        if (data == "ID") {
            barID.innerHTML = row.children[x].innerHTML;
        }

        switch (input.type) {
            case "datetime-local":
                input.value = new Date(row.children[x].innerHTML).toISOString().substr(0, 16);
                break;
            case "checkbox":
                input.checked = row.children[x].children[0].checked;
                break;
            default:
                input.value = row.children[x].innerHTML;
        }
    }
}

function copyFormToObject(form) {
    let object = new Object();
    object.ID = 0;

    let div = form.querySelector('div');

    for (var i = 0; i < div.childElementCount; i++) {
        let name = div.children[i].name;

        if (typeof name == 'undefined' || name == null || name == "") {
            continue;
        }

        switch (div.children[i].type) {
            case "number":
                object[name] = parseInt(div.children[i].value);
                break;
            case "datetime-local":
                object[name] = (new Date(div.children[i].value)).toISOString();
                break;
            case "checkbox":
                object[name] = div.children[i].checked;
                break;
            default:
                object[name] = div.children[i].value;
        }
    }

    if (isNaN(object.ID)) object.ID = 0;
    return object;
}

function clearForm(form) {
    var div = form.children[1];

    singleForm.querySelector('#edit-text').style.display = "none";
    singleForm.querySelector('#new-text').style.display = "block";

    for (var x = 0; x < div.childElementCount; x++) {
        let type = div.children[x].type;

        if (typeof type == "undefined") {
            continue;
        }

        switch (type) {
            case "checkbox":
                div.children[x].checked = false;
                break;
            case "number":
                div.children[x].value = "0";
                break;
            default:
                div.children[x].value = "";
        }
    }
}
<|endoftext|>


<commit_before>import { Microservices } from '../configs/microservices';
import rp from 'request-promise';

export default {
    name: 'deck',
    // At least one of the CRUD methods is Required
    read: (req, resource, params, config, callback) => {
        let args = params.params? params.params : params;
        if (resource === 'deck.content') {
            /* Create promise for deck data success */
            let deckRes = rp.get({uri: Microservices.deck.uri + '/deck/' + args.sid});
            /* Create promise for slides data success */
            let slidesRes = rp.get({uri: Microservices.deck.uri + '/deck/' + args.sid + '/slides'});
            /* Catch errors from deck data response */
            let deckPromise = deckRes.catch((err) => {
                callback({msg: 'Error in retrieving deck meta data ' + Microservices.deck.uri + ',', content: err}, {});
            });
            /* Catch erros from slides data response */
            let slidesPromise = slidesRes.catch((err) => {
                callback({msg: 'Error in retrieving slides data from ' + Microservices.deck.uri + ' service! Please try again later...', content: err}, {});
            });
            /* Create user data promise which is dependent on deck data promise */
            let userRes = deckPromise.then((deckData) => {
                //TODO Replace user id '4' with JSON.parse(data[0]).user when deckservice and userservice data is in sync
                return rp.get({uri: Microservices.user.uri + '/user/' + '15'});//(JSON.parse(deckData).user).toString()});//JSON.parse(deckData).user});
            });
            /* Catch errors from the user data response */
            let userPromise = userRes.catch((err) => {
                callback({msg: 'Error in retrieving user data from ' + Microservices.user.uri, content: err}, {});
            });

            /* Create promise which resolves when all the three promises are resolved or fails when any one of the three promises fails */
            Promise.all([deckPromise, slidesPromise, userPromise]).then((data) => {
                //console.log('deck data:', JSON.parse(data[0]));
                //console.log('slides data:', JSON.parse(data[1]));
                //console.log('user data:', JSON.parse(data[2]));
                callback(null, {deckData: JSON.parse(data[0]), slidesData: JSON.parse(data[1]), userData: JSON.parse(data[2])});
            }).catch((err) => {
                //console.log(err);
                callback({msg: 'Error in resolving promiese', content: err}, {});
            });
        }
        else if (resource === 'deck.properties') {
            /*********connect to microservices*************/
            //todo
            /*********received data from microservices*************/
            let deckProps = {
                'title': 'Sample Deck Title',
                'language': 'EN',
                'tags': ['RDF', 'Semantic Web', 'Linked Data']
            };
            callback(null, {deckProps: deckProps});
        }
    },
    // other methods
    create: (req, resource, params, body, config, callback) => {

        if(resource === 'deck.create') {
            if (params.tags.length === 1 && params.tags[0].length === 0)
                params.tags = undefined;
            let toSend = {
                description: params.description ? params.description : 'empty',
                language: params.language,
                translation: {
                    status: 'original'
                },
                tags: params.tags,
                title: params.title,
                user: params.userid.toString(),
                license: params.licence
            };
            rp({
                method: 'POST',
                uri: Microservices.deck.uri + '/deck/new',
                json: true,
                body: toSend
            }).then((deck) => callback(false, deck))
            .catch((err) => callback(err));
        }
    },
    update: (req, resource, params, body, config, callback) => {
        if(resource === 'deck.update') {
            if (params.tags.length === 1 && params.tags[0].length === 0)
                params.tags = undefined;
            let toSend = {
                description: params.description ? params.description : 'empty',
                language: params.language,
                tags: params.tags,
                title: params.title,
                user: params.userid.toString(),
                license: params.licence
            };
            rp({
                method: 'PUT',
                uri: Microservices.deck.uri + '/deck/' + params.deckId,
                json: true,
                body: toSend
            }).then((deck) => callback(false, deck))
            .catch((err) => callback(err));
        }
    }
    // delete: (req, resource, params, config, callback) => {}
};
<commit_msg>#SWIK-409, testing without hard coded user id<commit_after>import { Microservices } from '../configs/microservices';
import rp from 'request-promise';

export default {
    name: 'deck',
    // At least one of the CRUD methods is Required
    read: (req, resource, params, config, callback) => {
        let args = params.params? params.params : params;
        if (resource === 'deck.content') {
            /* Create promise for deck data success */
            let deckRes = rp.get({uri: Microservices.deck.uri + '/deck/' + args.sid});
            /* Create promise for slides data success */
            let slidesRes = rp.get({uri: Microservices.deck.uri + '/deck/' + args.sid + '/slides'});
            /* Catch errors from deck data response */
            let deckPromise = deckRes.catch((err) => {
                callback({msg: 'Error in retrieving deck meta data ' + Microservices.deck.uri + ',', content: err}, {});
            });
            /* Catch erros from slides data response */
            let slidesPromise = slidesRes.catch((err) => {
                callback({msg: 'Error in retrieving slides data from ' + Microservices.deck.uri + ' service! Please try again later...', content: err}, {});
            });
            /* Create user data promise which is dependent on deck data promise */
            let userRes = deckPromise.then((deckData) => {
                // TODO Replace hard coded user id '15' with the commented JSON data;
                // This should be done when deckservice and userservice data is in sync;
                return rp.get({uri: Microservices.user.uri + '/user/' + '15'});//(JSON.parse(deckData).user).toString()});
            });
            /* Catch errors from the user data response */
            let userPromise = userRes.catch((err) => {
                callback({msg: 'Error in retrieving user data from ' + Microservices.user.uri, content: err}, {});
            });

            /* Create promise which resolves when all the three promises are resolved or fails when any one of the three promises fails */
            Promise.all([deckPromise, slidesPromise, userPromise]).then((data) => {
                //console.log('deck data:', data[0]);
                //console.log('slides data:', data[1]);
                //console.log('user data:', data[2]);
                callback(null, {deckData: JSON.parse(data[0]), slidesData: JSON.parse(data[1]), userData: JSON.parse(data[2])});
            }).catch((err) => {
                //console.log(err);
                callback({msg: 'Error in resolving promiese', content: err}, {});
            });
        }
        else if (resource === 'deck.properties') {
            /*********connect to microservices*************/
            //todo
            /*********received data from microservices*************/
            let deckProps = {
                'title': 'Sample Deck Title',
                'language': 'EN',
                'tags': ['RDF', 'Semantic Web', 'Linked Data']
            };
            callback(null, {deckProps: deckProps});
        }
    },
    // other methods
    create: (req, resource, params, body, config, callback) => {

        if(resource === 'deck.create') {
            if (params.tags.length === 1 && params.tags[0].length === 0)
                params.tags = undefined;
            let toSend = {
                description: params.description ? params.description : 'empty',
                language: params.language,
                translation: {
                    status: 'original'
                },
                tags: params.tags,
                title: params.title,
                user: params.userid.toString(),
                license: params.licence
            };
            rp({
                method: 'POST',
                uri: Microservices.deck.uri + '/deck/new',
                json: true,
                body: toSend
            }).then((deck) => callback(false, deck))
            .catch((err) => callback(err));
        }
    },
    update: (req, resource, params, body, config, callback) => {
        if(resource === 'deck.update') {
            if (params.tags.length === 1 && params.tags[0].length === 0)
                params.tags = undefined;
            let toSend = {
                description: params.description ? params.description : 'empty',
                language: params.language,
                tags: params.tags,
                title: params.title,
                user: params.userid.toString(),
                license: params.licence
            };
            rp({
                method: 'PUT',
                uri: Microservices.deck.uri + '/deck/' + params.deckId,
                json: true,
                body: toSend
            }).then((deck) => callback(false, deck))
            .catch((err) => callback(err));
        }
    }
    // delete: (req, resource, params, config, callback) => {}
};
<|endoftext|>


<commit_before>import {Microservices} from '../configs/microservices';
import rp from 'request-promise';
const log = require('../configs/log').log;

export default {
    name: 'deck',
    // At least one of the CRUD methods is Required
    read: (req, resource, params, config, callback) => {
        req.reqId = req.reqId ? req.reqId : -1;
        log.info({Id: req.reqId, Service: __filename.split('/').pop(), Resource: resource, Operation: 'read', Method: req.method});
        let args = params.params ? params.params : params;
        if (resource === 'deck.legacy'){
            rp.get({uri: Microservices.deck.uri + '/legacy/' + params.oldid}).then((res) => {
                //console.log('RES:' + res);
                callback(null, {new_id: res});
            }).catch((err) => {
                callback(err, {new_id: null});
            });
        }
        if (resource === 'deck.featured') {
            //logger.info({reqId: req.reqId, file: __filename.split('/').pop(), Resource: resource});
            /*********connect to microservices*************/
            let limit, offset = 0;
            if (args.limit) limit = args.limit;
            if (args.offset) offset = args.offset;
            rp.get({uri: Microservices.deck.uri + '/allfeatured/' + limit + '/' + offset}).then((res) => {
                callback(null, {featured: JSON.parse(res)});
            }).catch((err) => {
                callback(err, {featured: []});
            });
        }
        if (resource === 'deck.recent') {
            //logger.info({reqId: req.reqId, file: __filename.split('/').pop(), Resource: resource});
            /*********connect to microservices*************/
            let limit, offset = null;
            if (args.limit) limit = args.limit;
            if (args.offset) offset = args.offset;
            rp.get({uri: Microservices.deck.uri + '/allrecent/' + limit + '/' + offset}).then((res) => {
                callback(null, {recent: JSON.parse(res)});
            }).catch((err) => {
                callback(err, {featured: []});
            });
        }
        if (resource === 'deck.content') {
            //logger.info({reqId: req.reqId, file: __filename.split('/').pop(), Resource: resource});
            /* Create promise for deck data success */
            let deckRes = rp.get({uri: Microservices.deck.uri + '/deck/' + args.sid});
            /* Create promise for slides data success */
            let slidesRes = rp.get({uri: Microservices.deck.uri + '/deck/' + args.sid + '/slides'});
            /* Catch errors from deck data response */
            let deckPromise = deckRes.catch((err) => {
                callback({msg: 'Error in retrieving deck meta data ' + Microservices.deck.uri + ',', content: err}, {});
            });
            /* Catch erros from slides data response */
            let slidesPromise = slidesRes.catch((err) => {
                callback({
                    msg: 'Error in retrieving slides data from ' + Microservices.deck.uri + ' service! Please try again later...',
                    content: err
                }, {});
            });

            // the forkCount API requires just the deck id, not the revision (a deck may be a fork of any revision)
            let deckId = parseInt(args.sid); // we rely on parseInt
            let forkCountPromise = rp.get({uri: Microservices.deck.uri + '/deck/' + deckId + '/forkCount'}).catch((err) => {
                callback({
                    msg: 'Error in retrieving fork count',
                    content: err
                }, {});
            });

            /* Create user data promise which is dependent on deck data promise */
            let usersPromise = deckPromise.then((deckRes) => {
                // This should be done when deckservice and userservice data is in sync;
                let deck = JSON.parse(deckRes);
                let currentRevision = deck.revisions.length === 1 ? deck.revisions[0] : deck.revisions.find((rev) => {
                    return rev.id === deck.active;
                });
                let users = [deck.user, currentRevision.user];
                if (deck.origin != null && deck.origin.user != null){
                    users.push(deck.origin.user);
                }
                let userPromisesMap = {};
                let userPromises = users.map((user) => {
                    return userPromisesMap[user] = userPromisesMap[user] || rp.get({uri: Microservices.user.uri + '/user/' + user.toString()});
                });
                return Promise.all(userPromises);
            }).catch((err) => {
                callback({msg: 'Error in retrieving user data from ' + Microservices.user.uri, content: err}, {});
            });

            /* Create promise which resolves when all the three promises are resolved or fails when any one of the three promises fails */
            Promise.all([deckPromise, slidesPromise, forkCountPromise, usersPromise]).then((data) => {
                let deckData = JSON.parse(data[0]);
                deckData.forkCount = JSON.parse(data[2]);
                callback(null, {
                    deckData: deckData,
                    slidesData: JSON.parse(data[1]),
                    creatorData: JSON.parse(data[3][0]),
                    ownerData: JSON.parse(data[3][1]),
                    originCreatorData: data[3][2] != null ? JSON.parse(data[3][2]) : {}
                });
            }).catch((err) => {
                //console.log(err);
                callback({msg: 'Error in resolving promises', content: err}, {});
            });
        } else if (resource === 'deck.permissions') {
            rp({
                method: 'GET',
                uri: Microservices.deck.uri + '/deck/' + args.id + '/permissions',
                headers: { '----jwt----': args.jwt },
                json: true
            })
            .then((body) => {
                callback(null, body);
            })
            .catch((err) => callback(err));
        } else if (resource === 'deck.properties') { //this is only used for deck edit - thus we call all the api routes with one service call
            //logger.info({reqId: req.reqId, file: __filename.split('/').pop(), Resource: resource});
            let deckPromise = rp.get({uri: Microservices.deck.uri + '/deck/' + args.sid}).promise().bind(this);
            let editorsPromise = rp.get({uri: Microservices.deck.uri + '/deck/' + args.sid + '/editors'}).promise().bind(this);
            Promise.all([deckPromise, editorsPromise]).then((res) => {
                let revision,
                    deck = JSON.parse(res[0]),
                    editors = JSON.parse(res[1]);
                //if deck's sid does not specify revision, find the active revision from the corresponding field
                if (args.sid.split('-').length < 2) {
                    revision = deck.revisions.find((rev) => {
                        return rev.id === deck.active;
                    });
                } else {
                    revision = deck.revisions[0];
                }
                let deckProps = {
                    description: revision.description != null ? revision.description : deck.description,
                    language: revision.language,
                    tags: revision.tags != null ? revision.tags : deck.tags,
                    title: revision.title != null ? revision.title : deck.title,
                    license: revision.license != null ? revision.license : deck.license,
                    theme: revision.theme != null ? revision.theme : deck.theme,
                    editors: editors.editors || {
                        users: [],
                        groups: []
                    },
                    deckOwner: deck.user,
                    revisionOwner: revision.user,
                    sid: args.sid,
                    localRootDeck: args.id
                };
                let contributors = (editors.contributors) ? editors.contributors.reduce((array, element) => {array.push(element.id);return array;}, []) : [];
                // console.log('Returned editors of deck:', editors.editors);
                callback(null, {
                    deckProps: deckProps,
                    editors: contributors
                });
            }).catch((err) => {
                callback(err);
            });
        } else if (resource === 'deck.numberofslides') {
            //logger.info({reqId: req.reqId, file: __filename.split('/').pop(), Resource: resource});
            let args = params.params ? params.params : params;
            rp.get({uri: Microservices.deck.uri + '/deck/' + args.id + '/slides'}).then((res) => {
                callback(null, {noofslides: JSON.parse(res).children.length});
            }).catch((err) => {
                console.log('serviceErr', err);
                callback(null, {noofslides: 0});
            });
        } else if (resource === 'deck.forks') {
            rp({
                method: 'GET',
                uri: Microservices.deck.uri + '/deck/' + args.id.split('-')[0] + '/forks',
                qs: args.user != null ? {user: args.user} : {},
                json: true
            }).then((body) => {
                callback(null, body);
            }).catch((err) => callback(err));
        } else if (resource ==='deck.slides'){

            let args = params.params ? params.params : params;
            rp.get({uri: Microservices.deck.uri + '/deck/' + args.id + '/slides'}).then((res) => {
                callback(null, {slides: JSON.parse(res).children});
            }).catch((err) => {
                callback({
                    msg: 'Error in retrieving slides data from ' + Microservices.deck.uri + ' service! Please try again later...',
                    content: err
                }, {slides: []});
            });
        }
    },
    // other methods
    create: (req, resource, params, body, config, callback) => {
        req.reqId = req.reqId ? req.reqId : -1;
        log.info({Id: req.reqId, Service: __filename.split('/').pop(), Resource: resource, Operation: 'create', Method: req.method});
        if (resource === 'deck.create') {
            //logger.info({reqId: req.reqId, file: __filename.split('/').pop(), Resource: resource});
//            if (params.tags.length === 1 && params.tags[0].length === 0)
//                params.tags = undefined;
            let toSend = {
                description: params.description ? params.description : 'empty',
                language: params.language,
                translation: {
                    status: 'original'
                },
                tags: params.tags,
                title: params.title,
                user: params.userid.toString(),
                license: params.license,
                theme: params.theme
            };
            rp({
                method: 'POST',
                uri: Microservices.deck.uri + '/deck/new',
                json: true,
                body: toSend
            }).then((deck) => callback(false, deck))
            .catch((err) => callback(err));
        }
    },
    update: (req, resource, params, body, config, callback) => {
        req.reqId = req.reqId ? req.reqId : -1;
        log.info({Id: req.reqId, Service: __filename.split('/').pop(), Resource: resource, Operation: 'update', Method: req.method});
        if (resource === 'deck.update') {
            //logger.info({reqId: req.reqId, file: __filename.split('/').pop(), Resource: resource});
            try {
                if (params.tags.length === 1 && params.tags[0].length === 0)
                    params.tags = undefined;
            } catch (e) {

            }
            let toSend = {
                description: params.description ? params.description : 'empty',
                language: params.language,
                tags: params.tags? params.tags: [],
                title: params.title,
                user: params.userid.toString(),
                license: params.license,
                theme: params.theme,
                new_revision: false,
                top_root_deck: String(params.selector.id),
                tags: params.tags
            };
            // console.log('send:', toSend, 'editors:', toSend.editors, 'to', Microservices.deck.uri + '/deck/' + params.deckId);
            rp({
                method: 'PUT',
                uri: Microservices.deck.uri + '/deck/' + params.deckId,
                json: true,
                body: toSend
            }).then((deck) => callback(false, deck))
            .catch((err) => callback(err));
            //update a deck by creating a new revision and setting it as active
        } else if (resource === 'deck.updateWithRevision') {
            //logger.info({reqId: req.reqId, file: __filename.split('/').pop(), Resource: resource});
            let selector = {
                'id': String(params.selector.id),
                'spath': params.selector.spath,
                'sid': String(params.selector.sid),
                'stype': params.selector.stype
            };

            try {
                if (params.tags.length === 1 && params.tags[0].length === 0)
                    params.tags = undefined;
            } catch (e) {

            }
            let toSend = {
                description: params.description ? params.description : 'empty',
                language: params.language,
                tags: params.tags,
                title: params.title,
                user: params.userid.toString(),
                license: params.license,
                theme: params.theme,
                new_revision: true,
                top_root_deck: selector.id,

            };
            if (params.root_deck != null) {
                toSend.root_deck = params.root_deck;
            }
            rp({
                method: 'PUT',
                uri: Microservices.deck.uri + '/deck/' + params.deckId,
                json: true,
                body: toSend
            }).then((deck) => callback(false, deck))
            .catch((err) => callback(err));
        } else if (resource === 'deck.fork') {
            //logger.info({reqId: req.reqId, file: __filename.split('/').pop(), Resource: resource});
            rp({
                method: 'PUT',
                uri: Microservices.deck.uri + '/deck/' + params.deckId + '/fork',
                json: true,
                body: {
                    user: params.userid.toString()
                }
            }).then((res) => callback(false, res))
            .catch((err) => callback(err));
        }
        else if (resource === 'deck.updateEditors') {
            rp({
                method: 'PUT',
                uri: Microservices.deck.uri + '/deck/' + params.deckId + '/editors',
                json: true,
                body: {
                    editors: {
                        groups: params.editors.groups,
                        users: params.editors.users
                    }
                },
                headers: { '----jwt----': params.jwt }
            }).then((deck) => callback(false, deck))
            .catch((err) => callback(err));
        } else if (resource === 'deck.updateTags'){

            // send tags to tag-service
            rp.post({
                uri: Microservices.tag.uri + '/tag/upload',
                json: true,
                body: {
                    user: params.userid,
                    tags: params.tags
                }
            }).then((tags) => {

                // send tagName and defaultName to deck-service
                let deckTags = tags.map( (t) => {
                    return {
                        tagName: t.tagName,
                        defaultName:  t.defaultName
                    };
                });

                rp.put({
                    uri: Microservices.deck.uri + '/deck/' + params.selector.id + '/tags',
                    json: true,
                    body: deckTags
                }).catch( (err) => {
                    console.log(err);
                    callback(err);
                });

                callback(null, {tags: tags});
            }).catch((err) => callback(err));
        }
    }
    // delete: (req, resource, params, config, callback) => {}
};
<commit_msg>correctly set tags to subdecks - minor fix<commit_after>import {Microservices} from '../configs/microservices';
import rp from 'request-promise';
const log = require('../configs/log').log;

export default {
    name: 'deck',
    // At least one of the CRUD methods is Required
    read: (req, resource, params, config, callback) => {
        req.reqId = req.reqId ? req.reqId : -1;
        log.info({Id: req.reqId, Service: __filename.split('/').pop(), Resource: resource, Operation: 'read', Method: req.method});
        let args = params.params ? params.params : params;
        if (resource === 'deck.legacy'){
            rp.get({uri: Microservices.deck.uri + '/legacy/' + params.oldid}).then((res) => {
                //console.log('RES:' + res);
                callback(null, {new_id: res});
            }).catch((err) => {
                callback(err, {new_id: null});
            });
        }
        if (resource === 'deck.featured') {
            //logger.info({reqId: req.reqId, file: __filename.split('/').pop(), Resource: resource});
            /*********connect to microservices*************/
            let limit, offset = 0;
            if (args.limit) limit = args.limit;
            if (args.offset) offset = args.offset;
            rp.get({uri: Microservices.deck.uri + '/allfeatured/' + limit + '/' + offset}).then((res) => {
                callback(null, {featured: JSON.parse(res)});
            }).catch((err) => {
                callback(err, {featured: []});
            });
        }
        if (resource === 'deck.recent') {
            //logger.info({reqId: req.reqId, file: __filename.split('/').pop(), Resource: resource});
            /*********connect to microservices*************/
            let limit, offset = null;
            if (args.limit) limit = args.limit;
            if (args.offset) offset = args.offset;
            rp.get({uri: Microservices.deck.uri + '/allrecent/' + limit + '/' + offset}).then((res) => {
                callback(null, {recent: JSON.parse(res)});
            }).catch((err) => {
                callback(err, {featured: []});
            });
        }
        if (resource === 'deck.content') {
            //logger.info({reqId: req.reqId, file: __filename.split('/').pop(), Resource: resource});
            /* Create promise for deck data success */
            let deckRes = rp.get({uri: Microservices.deck.uri + '/deck/' + args.sid});
            /* Create promise for slides data success */
            let slidesRes = rp.get({uri: Microservices.deck.uri + '/deck/' + args.sid + '/slides'});
            /* Catch errors from deck data response */
            let deckPromise = deckRes.catch((err) => {
                callback({msg: 'Error in retrieving deck meta data ' + Microservices.deck.uri + ',', content: err}, {});
            });
            /* Catch erros from slides data response */
            let slidesPromise = slidesRes.catch((err) => {
                callback({
                    msg: 'Error in retrieving slides data from ' + Microservices.deck.uri + ' service! Please try again later...',
                    content: err
                }, {});
            });

            // the forkCount API requires just the deck id, not the revision (a deck may be a fork of any revision)
            let deckId = parseInt(args.sid); // we rely on parseInt
            let forkCountPromise = rp.get({uri: Microservices.deck.uri + '/deck/' + deckId + '/forkCount'}).catch((err) => {
                callback({
                    msg: 'Error in retrieving fork count',
                    content: err
                }, {});
            });

            /* Create user data promise which is dependent on deck data promise */
            let usersPromise = deckPromise.then((deckRes) => {
                // This should be done when deckservice and userservice data is in sync;
                let deck = JSON.parse(deckRes);
                let currentRevision = deck.revisions.length === 1 ? deck.revisions[0] : deck.revisions.find((rev) => {
                    return rev.id === deck.active;
                });
                let users = [deck.user, currentRevision.user];
                if (deck.origin != null && deck.origin.user != null){
                    users.push(deck.origin.user);
                }
                let userPromisesMap = {};
                let userPromises = users.map((user) => {
                    return userPromisesMap[user] = userPromisesMap[user] || rp.get({uri: Microservices.user.uri + '/user/' + user.toString()});
                });
                return Promise.all(userPromises);
            }).catch((err) => {
                callback({msg: 'Error in retrieving user data from ' + Microservices.user.uri, content: err}, {});
            });

            /* Create promise which resolves when all the three promises are resolved or fails when any one of the three promises fails */
            Promise.all([deckPromise, slidesPromise, forkCountPromise, usersPromise]).then((data) => {
                let deckData = JSON.parse(data[0]);
                deckData.forkCount = JSON.parse(data[2]);
                callback(null, {
                    deckData: deckData,
                    slidesData: JSON.parse(data[1]),
                    creatorData: JSON.parse(data[3][0]),
                    ownerData: JSON.parse(data[3][1]),
                    originCreatorData: data[3][2] != null ? JSON.parse(data[3][2]) : {}
                });
            }).catch((err) => {
                //console.log(err);
                callback({msg: 'Error in resolving promises', content: err}, {});
            });
        } else if (resource === 'deck.permissions') {
            rp({
                method: 'GET',
                uri: Microservices.deck.uri + '/deck/' + args.id + '/permissions',
                headers: { '----jwt----': args.jwt },
                json: true
            })
            .then((body) => {
                callback(null, body);
            })
            .catch((err) => callback(err));
        } else if (resource === 'deck.properties') { //this is only used for deck edit - thus we call all the api routes with one service call
            //logger.info({reqId: req.reqId, file: __filename.split('/').pop(), Resource: resource});
            let deckPromise = rp.get({uri: Microservices.deck.uri + '/deck/' + args.sid}).promise().bind(this);
            let editorsPromise = rp.get({uri: Microservices.deck.uri + '/deck/' + args.sid + '/editors'}).promise().bind(this);
            Promise.all([deckPromise, editorsPromise]).then((res) => {
                let revision,
                    deck = JSON.parse(res[0]),
                    editors = JSON.parse(res[1]);
                //if deck's sid does not specify revision, find the active revision from the corresponding field
                if (args.sid.split('-').length < 2) {
                    revision = deck.revisions.find((rev) => {
                        return rev.id === deck.active;
                    });
                } else {
                    revision = deck.revisions[0];
                }
                let deckProps = {
                    description: revision.description != null ? revision.description : deck.description,
                    language: revision.language,
                    tags: revision.tags != null ? revision.tags : deck.tags,
                    title: revision.title != null ? revision.title : deck.title,
                    license: revision.license != null ? revision.license : deck.license,
                    theme: revision.theme != null ? revision.theme : deck.theme,
                    editors: editors.editors || {
                        users: [],
                        groups: []
                    },
                    deckOwner: deck.user,
                    revisionOwner: revision.user,
                    sid: args.sid,
                    localRootDeck: args.id
                };
                let contributors = (editors.contributors) ? editors.contributors.reduce((array, element) => {array.push(element.id);return array;}, []) : [];
                // console.log('Returned editors of deck:', editors.editors);
                callback(null, {
                    deckProps: deckProps,
                    editors: contributors
                });
            }).catch((err) => {
                callback(err);
            });
        } else if (resource === 'deck.numberofslides') {
            //logger.info({reqId: req.reqId, file: __filename.split('/').pop(), Resource: resource});
            let args = params.params ? params.params : params;
            rp.get({uri: Microservices.deck.uri + '/deck/' + args.id + '/slides'}).then((res) => {
                callback(null, {noofslides: JSON.parse(res).children.length});
            }).catch((err) => {
                console.log('serviceErr', err);
                callback(null, {noofslides: 0});
            });
        } else if (resource === 'deck.forks') {
            rp({
                method: 'GET',
                uri: Microservices.deck.uri + '/deck/' + args.id.split('-')[0] + '/forks',
                qs: args.user != null ? {user: args.user} : {},
                json: true
            }).then((body) => {
                callback(null, body);
            }).catch((err) => callback(err));
        } else if (resource ==='deck.slides'){

            let args = params.params ? params.params : params;
            rp.get({uri: Microservices.deck.uri + '/deck/' + args.id + '/slides'}).then((res) => {
                callback(null, {slides: JSON.parse(res).children});
            }).catch((err) => {
                callback({
                    msg: 'Error in retrieving slides data from ' + Microservices.deck.uri + ' service! Please try again later...',
                    content: err
                }, {slides: []});
            });
        }
    },
    // other methods
    create: (req, resource, params, body, config, callback) => {
        req.reqId = req.reqId ? req.reqId : -1;
        log.info({Id: req.reqId, Service: __filename.split('/').pop(), Resource: resource, Operation: 'create', Method: req.method});
        if (resource === 'deck.create') {
            //logger.info({reqId: req.reqId, file: __filename.split('/').pop(), Resource: resource});
//            if (params.tags.length === 1 && params.tags[0].length === 0)
//                params.tags = undefined;
            let toSend = {
                description: params.description ? params.description : 'empty',
                language: params.language,
                translation: {
                    status: 'original'
                },
                tags: params.tags,
                title: params.title,
                user: params.userid.toString(),
                license: params.license,
                theme: params.theme
            };
            rp({
                method: 'POST',
                uri: Microservices.deck.uri + '/deck/new',
                json: true,
                body: toSend
            }).then((deck) => callback(false, deck))
            .catch((err) => callback(err));
        }
    },
    update: (req, resource, params, body, config, callback) => {
        req.reqId = req.reqId ? req.reqId : -1;
        log.info({Id: req.reqId, Service: __filename.split('/').pop(), Resource: resource, Operation: 'update', Method: req.method});
        if (resource === 'deck.update') {
            //logger.info({reqId: req.reqId, file: __filename.split('/').pop(), Resource: resource});
            try {
                if (params.tags.length === 1 && params.tags[0].length === 0)
                    params.tags = undefined;
            } catch (e) {

            }
            let toSend = {
                description: params.description ? params.description : 'empty',
                language: params.language,
                tags: params.tags? params.tags: [],
                title: params.title,
                user: params.userid.toString(),
                license: params.license,
                theme: params.theme,
                new_revision: false,
                top_root_deck: String(params.selector.id),
                tags: params.tags
            };
            // console.log('send:', toSend, 'editors:', toSend.editors, 'to', Microservices.deck.uri + '/deck/' + params.deckId);
            rp({
                method: 'PUT',
                uri: Microservices.deck.uri + '/deck/' + params.deckId,
                json: true,
                body: toSend
            }).then((deck) => callback(false, deck))
            .catch((err) => callback(err));
            //update a deck by creating a new revision and setting it as active
        } else if (resource === 'deck.updateWithRevision') {
            //logger.info({reqId: req.reqId, file: __filename.split('/').pop(), Resource: resource});
            let selector = {
                'id': String(params.selector.id),
                'spath': params.selector.spath,
                'sid': String(params.selector.sid),
                'stype': params.selector.stype
            };

            try {
                if (params.tags.length === 1 && params.tags[0].length === 0)
                    params.tags = undefined;
            } catch (e) {

            }
            let toSend = {
                description: params.description ? params.description : 'empty',
                language: params.language,
                tags: params.tags,
                title: params.title,
                user: params.userid.toString(),
                license: params.license,
                theme: params.theme,
                new_revision: true,
                top_root_deck: selector.id,

            };
            if (params.root_deck != null) {
                toSend.root_deck = params.root_deck;
            }
            rp({
                method: 'PUT',
                uri: Microservices.deck.uri + '/deck/' + params.deckId,
                json: true,
                body: toSend
            }).then((deck) => callback(false, deck))
            .catch((err) => callback(err));
        } else if (resource === 'deck.fork') {
            //logger.info({reqId: req.reqId, file: __filename.split('/').pop(), Resource: resource});
            rp({
                method: 'PUT',
                uri: Microservices.deck.uri + '/deck/' + params.deckId + '/fork',
                json: true,
                body: {
                    user: params.userid.toString()
                }
            }).then((res) => callback(false, res))
            .catch((err) => callback(err));
        }
        else if (resource === 'deck.updateEditors') {
            rp({
                method: 'PUT',
                uri: Microservices.deck.uri + '/deck/' + params.deckId + '/editors',
                json: true,
                body: {
                    editors: {
                        groups: params.editors.groups,
                        users: params.editors.users
                    }
                },
                headers: { '----jwt----': params.jwt }
            }).then((deck) => callback(false, deck))
            .catch((err) => callback(err));
        } else if (resource === 'deck.updateTags'){

            // send tags to tag-service
            rp.post({
                uri: Microservices.tag.uri + '/tag/upload',
                json: true,
                body: {
                    user: params.userid,
                    tags: params.tags
                }
            }).then((tags) => {

                // send tagName and defaultName to deck-service
                let deckTags = tags.map( (t) => {
                    return {
                        tagName: t.tagName,
                        defaultName:  t.defaultName
                    };
                });

                rp.put({
                    uri: Microservices.deck.uri + '/deck/' + params.selector.sid + '/tags',
                    json: true,
                    body: deckTags
                }).catch( (err) => {
                    console.log(err);
                    callback(err);
                });

                callback(null, {tags: tags});
            }).catch((err) => callback(err));
        }
    }
    // delete: (req, resource, params, config, callback) => {}
};
<|endoftext|>


<commit_before>// ==UserScript==
// @name sevichat
// @namespace http://keyboardfire.com/
// @author SE user Doorknob <andy@keyboardfire.com>
// @version 0.1
// @description sevichat == SE vi chat; vim-esque keyboard shortcuts for Stack Exchange chat
// @grant none
// @copyright MIT
// @include *://chat.stackoverflow.com/*
// @include *://chat.stackexchange.com/*
// @include *://chat.meta.stackexchange.com/*
// ==/UserScript==

// this will inject the code as a <script> element, because Safari doesn't seem
// to be using the page's jQuery properly
function withJQuery(f) {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.textContent = '(' + f + ')(jQuery)';
    document.head.appendChild(script);
}
withJQuery(sevichat);

function sevichat($) {
    var input = $('#input');

    var currentMsg;
    var setCurrentMsg = function(m) {
        if (currentMsg) currentMsg.css('background-color', '');
        currentMsg = m;
        if (m) {
            m.css('background-color', 'rgba(0, 255, 0, 0.1)');
            document.body.scrollTop = m[0].offsetTop;
        }
    };

    var clickMenuItem = function(item) {
        currentMsg.find('.action-link').click();
        var intr = setInterval(function() {
            var popup = $('.popup');
            if (popup.length) {
                popup.find(item).click();
                clearInterval(intr);
            }
        }, 10);
    };

    var savedEdits = {}, msgEditing;

    input.keydown(function(e) {
        if (e.which == 27) {
            e.preventDefault();
            if ($('#cancel-editing-button').css('display') !== 'none') {
                savedEdits[msgEditing] = this.value;
                $('#cancel-editing-button').click();
            }
            setCurrentMsg();
        } else if (!currentMsg) {
            // ctrl+O
            if (e.which == 79 && e.ctrlKey) {
                e.preventDefault();
                setCurrentMsg($('.message:last'));
            }
        } else {
            e.preventDefault();
            switch (e.which) {
                case 68:  // d
                    if (confirm('ya sure about that?')) {
                        $.post('http://chat.stackexchange.com/messages/' +
                            currentMsg.attr('id').split('-')[1] + '/delete', {
                                fkey: fkey().fkey
                            });
                    }
                    setCurrentMsg();
                    break;
                case 69:  // e
                    msgEditing = currentMsg.attr('id');
                    clickMenuItem('.edit');
                    if (savedEdits[msgEditing]) {
                        $('#input').val(savedEdits[msgEditing]);
                    }
                    setCurrentMsg();
                    break;
                case 70:  // f
                    currentMsg.find('.flags .vote').click();
                    setCurrentMsg();
                    break;
                case 74:  // j
                    var next = currentMsg.next('.message');
                    if (!next.length) {
                        next = currentMsg.closest('.monologue')
                            .nextAll('.monologue').eq(0).find('.message:first');
                    }
                    if (next.length) setCurrentMsg(next);
                    break;
                case 75:  // k
                    var prev = currentMsg.prev('.message');
                    if (!prev.length) {
                        prev = currentMsg.closest('.monologue')
                            .prevAll('.monologue').eq(0).find('.message:last');
                    }
                    if (prev.length) setCurrentMsg(prev);
                    break;
                case 80:  // p
                    clickMenuItem('.owner-star');
                    setCurrentMsg();
                    break;
                case 82:  // r
                    var replyBtn = currentMsg.find('.newreply');
                    if (replyBtn.length) replyBtn.click();
                    else $('#input').val(':' + currentMsg.attr('id')
                        .split('-')[1] + ' ' + $('#input').val().trimLeft());
                    setCurrentMsg();
                    break;
                case 83:  // s
                    currentMsg.find('.stars:first .vote').click();
                    setCurrentMsg();
                    break;
                case 89:  // y
                    prompt('hit ctrl+c', location.origin +
                        currentMsg.find('.action-link').attr('href'));
                    setCurrentMsg();
                    break;
            }
        }
    });

    // fire our listener before any other listener
    var kdevts = $('#input').data('events').keydown;
    kdevts.unshift(kdevts.pop());
}
<commit_msg>Hack a kludgehack<commit_after>// ==UserScript==
// @name sevichat
// @namespace http://keyboardfire.com/
// @author SE user Doorknob <andy@keyboardfire.com>
// @version 0.1
// @description sevichat == SE vi chat; vim-esque keyboard shortcuts for Stack Exchange chat
// @grant none
// @copyright MIT
// @include *://chat.stackoverflow.com/*
// @include *://chat.stackexchange.com/*
// @include *://chat.meta.stackexchange.com/*
// ==/UserScript==

// this will inject the code as a <script> element, because Safari doesn't seem
// to be using the page's jQuery properly
function withJQuery(f) {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.textContent = '(' + f + ')(jQuery)';
    document.head.appendChild(script);
}
withJQuery(sevichat);

function sevichat($) {
    var input = $('#input');

    var currentMsg;
    var setCurrentMsg = function(m) {
        if (currentMsg) currentMsg.css('background-color', '');
        currentMsg = m;
        if (m) {
            m.css('background-color', 'rgba(0, 255, 0, 0.1)');
            document.body.scrollTop = m[0].offsetTop;
        }
    };

    var clickMenuItem = function(item) {
        currentMsg.find('.action-link').click();
        var intr = setInterval(function() {
            var popup = $('.popup');
            if (popup.length) {
                popup.find(item).click();
                clearInterval(intr);
            }
        }, 10);
    };

    var savedEdits = {}, msgEditing;

    input.keydown(function(e) {
        if (e.which == 27) {
            e.preventDefault();
            if ($('#cancel-editing-button').css('display') !== 'none') {
                savedEdits[msgEditing] = this.value;
                $('#cancel-editing-button').click();
            }
            setCurrentMsg();
        } else if (!currentMsg) {
            // ctrl+O
            if (e.which == 79 && e.ctrlKey) {
                e.preventDefault();
                setCurrentMsg($('.message:last'));
            }
        } else {
            e.preventDefault();
            switch (e.which) {
                case 68:  // d
                    if (confirm('ya sure about that?')) {
                        $.post('http://chat.stackexchange.com/messages/' +
                            currentMsg.attr('id').split('-')[1] + '/delete', {
                                fkey: fkey().fkey
                            });
                    }
                    setCurrentMsg();
                    break;
                case 69:  // e
                    msgEditing = currentMsg.attr('id');
                    clickMenuItem('.edit');
                    if (savedEdits[msgEditing]) {
                        setTimeout(function() {
                            $('#input').val(savedEdits[msgEditing]);
                        }, 1000);
                    }
                    setCurrentMsg();
                    break;
                case 70:  // f
                    currentMsg.find('.flags .vote').click();
                    setCurrentMsg();
                    break;
                case 74:  // j
                    var next = currentMsg.next('.message');
                    if (!next.length) {
                        next = currentMsg.closest('.monologue')
                            .nextAll('.monologue').eq(0).find('.message:first');
                    }
                    if (next.length) setCurrentMsg(next);
                    break;
                case 75:  // k
                    var prev = currentMsg.prev('.message');
                    if (!prev.length) {
                        prev = currentMsg.closest('.monologue')
                            .prevAll('.monologue').eq(0).find('.message:last');
                    }
                    if (prev.length) setCurrentMsg(prev);
                    break;
                case 80:  // p
                    clickMenuItem('.owner-star');
                    setCurrentMsg();
                    break;
                case 82:  // r
                    var replyBtn = currentMsg.find('.newreply');
                    if (replyBtn.length) replyBtn.click();
                    else $('#input').val(':' + currentMsg.attr('id')
                        .split('-')[1] + ' ' + $('#input').val().trimLeft());
                    setCurrentMsg();
                    break;
                case 83:  // s
                    currentMsg.find('.stars:first .vote').click();
                    setCurrentMsg();
                    break;
                case 89:  // y
                    prompt('hit ctrl+c', location.origin +
                        currentMsg.find('.action-link').attr('href'));
                    setCurrentMsg();
                    break;
            }
        }
    });

    // fire our listener before any other listener
    var kdevts = $('#input').data('events').keydown;
    kdevts.unshift(kdevts.pop());
}
<|endoftext|>


<commit_before>// ==UserScript==
// @name        SfReader
// @namespace   http://gmscripts.bhe.me
// @author      hitsmaxft <mfthits#gmail.com>
// @description Better SF reader UI
// @include     http://comic.sfacg.com/*
// @version     3.0
// @require http://code.jquery.com/jquery-1.11.0.min.js
//
// @grant GM_info
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_xmlhttpRequest
// @grant GM_registerMenuCommand
// @grant unsafeWindow
//
// @require http://sizzlemctwizzle.com/130400js?show
// ==/UserScript==

var debug_mode = false;

if (typeof unsafeWindow == "undefined") {
	unsafeWindow = window

}

//port jquery into unsafeWindow
if(debug_mode) {
	unsafeWindow.$=jQuery
	unsafeWindow.jQuery=jQuery
}

this.$ = this.jQuery = jQuery.noConflict(true)

;(
	function(jQuery){
		var $ = jQuery

		var debug = function (msg) {
			if (debug_mode) {
				console.log(msg)
			}
		}

		var SfReader = function() {
			this.debug = debug_mode

			this.initAttr = function(){
				var attr = [
				'comicName'
				, 'picCount'
				, 'picAy'
				]

				for (i in attr) {
					var name = attr[i]
					this[name] = unsafeWindow[name]
				}

				this.cur = unsafeWindow.GetArgsFromHref(unsafeWindow.location.href, "p") - 1
				this.hostId = unsafeWindow.getHost()
				this.host = unsafeWindow.hosts[unsafeWindow.getHost()]
				this.cache = [];

				this.$curPic = $("#curPic")

				this.$statusBar = this.renderStatusBar()
				this.notif = this.$statusBar.find("#reader_notification")
				this.$pager_text = this.$statusBar.find("#page_indicator span")
				this.notif_text = this.notif.find("span")

				var imgLoadEvent = $.Deferred()
				this.$EImgLoading = imgLoadEvent

				$("#curPic").on('load', function(e) {
					$(this).get(0).scrollIntoView()
					imgLoadEvent.resolve(function(){})
				})

				$(document.body).prepend(this.$statusBar)
			}

		}

		SfReader.prototype.hookRenderPager= function() {
			setInterval((function() {
				this.$pager_text.text("第" + (this.cur+1) + "/" + this.picCount + "页")

			}).bind(this), 100);
		}

		SfReader.prototype.renderStatusBar= function(msg) {
			var box = $("

")
			box.attr("id", "sfreader_box")
			box.attr("style", "position:fixed;z-index:9999999;background-color:none;padding:10px 30px;width:100%")
			var inner_box = $("

")
			inner_box.attr("id" , "reader_notification")
			inner_box.attr("style", "display:none;")
			var pager_box = $("

")
			pager_box.attr("id", "page_indicator")
			var clean_box = $("

")
			var inner_span = $("")
			inner_span.attr("style", "padding:3px 5px;font-size:1.8em;float:left;color:#fff;background-color:#AF2F15")
			pager_box.append(inner_span[0].cloneNode(true))
			inner_box.append(inner_span)
			inner_span.attr("id", "sfreader-notif-text")
			inner_box.append(clean_box)
			box.append(pager_box)
			box.append(inner_box)
			return  box
		}

		SfReader.prototype.sendMsgWithCallback = function(callback, msg, done_text) {
			this.notif_text.text(msg)
			this.notif.fadeIn()
			this.$EImgLoading.done(
				(function(callback){
					debug("loading fadeout")
				// fadeOut with done text
				setTimeout( (function() {
					this.notif.fadeOut()
					if (done_text)
						this.notif_text.text(done_text)
				}).bind(this), 600)
			}).bind(this)
				)

			callback()
		}

		SfReader.prototype.sendMsg = function(msg, timeout) {
			var latency = timeout || 2;
			this.notif_text.text(msg)
			this.notif.fadeIn()
			setTimeout(
				(function(){this.fadeOut()}).bind(this.notif)
				, 400)
		}
		SfReader.prototype.start = function(page) {
			this.initAttr();

			this.bindPagerButton();
			this.hookRenderPager();
			debug("enjoy sf reader")
		}

		SfReader.prototype.bindPagerButton = function() {

			var pagers = $(".page_turning")
			var pre_links  =  pagers.find(".redfont_input:contains(上一页)")

			var next_links  = pagers.find(".redfont_input:contains(下一页)")

			next_links.push($("#curPic").parent()[0])

			var self = this

			pre_links.each(function(ind , item){
				item.href = "javascript:;"
				item.onclick = (function(e) {
					e.preventDefault();
					this.nav2Page(-1);
				}).bind(self)
			})
			next_links.each(function(ind , item){
				item.href = "javascript:;"
				item.onclick = (function(e) {
					e.preventDefault();
					this.nav2Page(1);
				}).bind(self)
			})

		}

		SfReader.prototype.setImg = function(page) {
			var imgEl = this.$curPic
			imgEl.attr("src" , this.host  + this.picAy[page])
			this.cur = page
			debug("set img url 2 " + imgEl.src)
		}
		SfReader.prototype.render = function(page) {
			debug("rend nothing with page " + page)
		}
		SfReader.prototype.nav2Page = function(pos) {
			if (pos !== -1  && pos !== 1) {
				debug("erro in pos nav : " + pos)
				return false
			}

			var page_id = parseInt(this.cur, 0) + parseInt(pos, 0)

			if (
				page_id < 0
				|| page_id >= this.picCount
				) {

				debug("out of range")
			this.sendMsg("到头啦, 看其他话吧")
			return false
		}

		debug(" go to pageid : " + page_id)

		this.sendMsgWithCallback(
			(function(){
				debug("make resolve")
				this.setImg(page_id)
			}).bind(this)
			, "翻页中..."
			, "翻页完成"
			)

		debug("end of callback")

		setTimeout(this.render(page_id), 0)
	};

	var reader  = new SfReader()

	$(document).ready(function() {
			reader.start()
	})

})($)
<commit_msg>remove auto update<commit_after>// ==UserScript==
// @name        SfReader
// @namespace   http://gmscripts.bhe.me
// @author      hitsmaxft <mfthits#gmail.com>
// @description Better SF reader UI
// @include     http://comic.sfacg.com/*
// @version     3.0
// @require http://code.jquery.com/jquery-1.11.0.min.js
//
// @grant GM_info
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_xmlhttpRequest
// @grant GM_registerMenuCommand
// @grant unsafeWindow
//
// @norequire http://sizzlemctwizzle.com/130400js?show
// ==/UserScript==

var debug_mode = false;

if (typeof unsafeWindow == "undefined") {
	unsafeWindow = window

}

//port jquery into unsafeWindow
if(debug_mode) {
	unsafeWindow.$=jQuery
	unsafeWindow.jQuery=jQuery
}

this.$ = this.jQuery = jQuery.noConflict(true)

;(
	function(jQuery){
		var $ = jQuery

		var debug = function (msg) {
			if (debug_mode) {
				console.log(msg)
			}
		}

		var SfReader = function() {
			this.debug = debug_mode

			this.initAttr = function(){
				var attr = [
				'comicName'
				, 'picCount'
				, 'picAy'
				]

				for (i in attr) {
					var name = attr[i]
					this[name] = unsafeWindow[name]
				}

				this.cur = unsafeWindow.GetArgsFromHref(unsafeWindow.location.href, "p") - 1
				this.hostId = unsafeWindow.getHost()
				this.host = unsafeWindow.hosts[unsafeWindow.getHost()]
				this.cache = [];

				this.$curPic = $("#curPic")

				this.$statusBar = this.renderStatusBar()
				this.notif = this.$statusBar.find("#reader_notification")
				this.$pager_text = this.$statusBar.find("#page_indicator span")
				this.notif_text = this.notif.find("span")

				var imgLoadEvent = $.Deferred()
				this.$EImgLoading = imgLoadEvent

				$("#curPic").on('load', function(e) {
					$(this).get(0).scrollIntoView()
					imgLoadEvent.resolve(function(){})
				})

				$(document.body).prepend(this.$statusBar)
			}

		}

		SfReader.prototype.hookRenderPager= function() {
			setInterval((function() {
				this.$pager_text.text("第" + (this.cur+1) + "/" + this.picCount + "页")

			}).bind(this), 100);
		}

		SfReader.prototype.renderStatusBar= function(msg) {
			var box = $("

")
			box.attr("id", "sfreader_box")
			box.attr("style", "position:fixed;z-index:9999999;background-color:none;padding:10px 30px;width:100%")
			var inner_box = $("

")
			inner_box.attr("id" , "reader_notification")
			inner_box.attr("style", "display:none;")
			var pager_box = $("

")
			pager_box.attr("id", "page_indicator")
			var clean_box = $("

")
			var inner_span = $("")
			inner_span.attr("style", "padding:3px 5px;font-size:1.8em;float:left;color:#fff;background-color:#AF2F15")
			pager_box.append(inner_span[0].cloneNode(true))
			inner_box.append(inner_span)
			inner_span.attr("id", "sfreader-notif-text")
			inner_box.append(clean_box)
			box.append(pager_box)
			box.append(inner_box)
			return  box
		}

		SfReader.prototype.sendMsgWithCallback = function(callback, msg, done_text) {
			this.notif_text.text(msg)
			this.notif.fadeIn()
			this.$EImgLoading.done(
				(function(callback){
					debug("loading fadeout")
				// fadeOut with done text
				setTimeout( (function() {
					this.notif.fadeOut()
					if (done_text)
						this.notif_text.text(done_text)
				}).bind(this), 600)
			}).bind(this)
				)

			callback()
		}

		SfReader.prototype.sendMsg = function(msg, timeout) {
			var latency = timeout || 2;
			this.notif_text.text(msg)
			this.notif.fadeIn()
			setTimeout(
				(function(){this.fadeOut()}).bind(this.notif)
				, 400)
		}
		SfReader.prototype.start = function(page) {
			this.initAttr();

			this.bindPagerButton();
			this.hookRenderPager();
			debug("enjoy sf reader")
		}

		SfReader.prototype.bindPagerButton = function() {

			var pagers = $(".page_turning")
			var pre_links  =  pagers.find(".redfont_input:contains(上一页)")

			var next_links  = pagers.find(".redfont_input:contains(下一页)")

			next_links.push($("#curPic").parent()[0])

			var self = this

			pre_links.each(function(ind , item){
				item.href = "javascript:;"
				item.onclick = (function(e) {
					e.preventDefault();
					this.nav2Page(-1);
				}).bind(self)
			})
			next_links.each(function(ind , item){
				item.href = "javascript:;"
				item.onclick = (function(e) {
					e.preventDefault();
					this.nav2Page(1);
				}).bind(self)
			})

		}

		SfReader.prototype.setImg = function(page) {
			var imgEl = this.$curPic
			imgEl.attr("src" , this.host  + this.picAy[page])
			this.cur = page
			debug("set img url 2 " + imgEl.src)
		}
		SfReader.prototype.render = function(page) {
			debug("rend nothing with page " + page)
		}
		SfReader.prototype.nav2Page = function(pos) {
			if (pos !== -1  && pos !== 1) {
				debug("erro in pos nav : " + pos)
				return false
			}

			var page_id = parseInt(this.cur, 0) + parseInt(pos, 0)

			if (
				page_id < 0
				|| page_id >= this.picCount
				) {

				debug("out of range")
			this.sendMsg("到头啦, 看其他话吧")
			return false
		}

		debug(" go to pageid : " + page_id)

		this.sendMsgWithCallback(
			(function(){
				debug("make resolve")
				this.setImg(page_id)
			}).bind(this)
			, "翻页中..."
			, "翻页完成"
			)

		debug("end of callback")

		setTimeout(this.render(page_id), 0)
	};

	var reader  = new SfReader()

	$(document).ready(function() {
			reader.start()
	})

})($)
<|endoftext|>


<commit_before>/*
 * Copyright 2006-2007 The Kuali Foundation.
 *
 * Licensed under the Educational Community License, Version 1.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.opensource.org/licenses/ecl1.php
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
// Toggles a tab to show / hide and changes the source image to properly reflect this
// change. Returns false to avoid post. Example usage:
// onclick="javascript: return toggleTab(document, this, ${currentTabIndex}) }
function toggleTab(doc, tabIndex) {
	if (doc.forms[0].elements['tabState[' + tabIndex + '].open'].value == 'false') {
        showTab(doc, tabIndex);
    } else {
        hideTab(doc, tabIndex);
	}
	return false;
}

function expandAllTab(doc, tabStatesSize) {
	for (var tabIndex = 0; tabIndex <= tabStatesSize.value; tabIndex++) {
        showTab(doc, tabIndex);
	}
	return false;
}

function collapseAllTab(doc, tabStatesSize) {
	for (var tabIndex = 0; tabIndex <= tabStatesSize.value; tabIndex++) {
        hideTab(doc, tabIndex);
	}
	return false;
}

function showTab(doc, tabIndex) {
    // replaced 'block' with '' to make budgetExpensesRow.tag happy.
    doc.getElementById('tab-' + tabIndex + '-div').style.display = '';
    doc.forms[0].elements['tabState[' + tabIndex + '].open'].value = 'true';
    var image = doc.getElementById('tab-' + tabIndex + '-imageToggle');
    image.src = jsContextPath + '/kr/images/tinybutton-hide.gif';
    image.alt = image.alt.replace(/^show/, 'hide');
    image.alt = image.alt.replace(/^open/, 'close');
    image.title = image.title.replace(/^show/, 'hide');
    image.title = image.title.replace(/^open/, 'close');
    return false;
}

function hideTab(doc, tabIndex) {
    doc.getElementById('tab-' + tabIndex + '-div').style.display = 'none';
    doc.forms[0].elements['tabState[' + tabIndex + '].open'].value = 'false';
    var image = doc.getElementById('tab-' + tabIndex + '-imageToggle');
    image.src = jsContextPath + '/kr/images/tinybutton-show.gif';
    image.alt = image.alt.replace(/^hide/, 'show');
    image.alt = image.alt.replace(/^close/, 'open');
    image.title = image.title.replace(/^hide/, 'show');
    image.title = image.title.replace(/^close/, 'open');
    return false;
}

var formHasAlreadyBeenSubmitted = false;
var excludeSubmitRestriction = false;
function hasFormAlreadyBeenSubmitted() {
    if (formHasAlreadyBeenSubmitted && !excludeSubmitRestriction) {
       alert("Page already being processed by the server.");
       return false;
    } else {
       formHasAlreadyBeenSubmitted = true;
       return true;
    }
    excludeSubmitRestriction = false;
}

function submitForm() {
    document.forms[0].submit();
}

/* script to prevent the return key from submitting a form unless the user is on a button or on a link. fix for KULFDBCK-555 */
function isReturnKeyAllowed(buttonPrefix , event) {
	/* use IE naming first then firefox. */
    var elemType = event.srcElement ? event.srcElement.type : event.target.type;
    if (elemType != null && elemType.toLowerCase() == 'textarea') {
      // KULEDOCS-1728: textareas need to have the return key enabled
      return true;
    }
	var initiator = event.srcElement ? event.srcElement.name : event.target.name;
	var key = event.keyCode;
	/* initiator is undefined check is to prevent return from doing anything if not in a form field since the initiator is undefined */
	/* 13 is return key code */
	/* length > 0 check is to allow user to hit return on links */
	if ( key == 13 ) {
		if( initiator == undefined || ( initiator.indexOf(buttonPrefix) != 0 && initiator.length > 0) ) {
		  // disallow enter key from fields that dont match prefix.
		  return false;
		}
	}
    return true;
}

//The following javascript is intended to resize the route log iframe
// to stay at an appropriate height based on the size of the documents
// contents contained in the iframe.
//  NOTE: this will only work when the domain serving the content of kuali
//         is the same as the domain serving the content of workflow.
var routeLogResizeTimer = ""; // holds the timer for the  route log iframe resizer
var currentHeight = 500; // holds the current height of the iframe
var safari = navigator.userAgent.toLowerCase().indexOf('safari');

function setRouteLogIframeDimensions() {
  var routeLogFrame = document.getElementById("routeLogIFrame");
  var routeLogFrameWin = window.frames["routeLogIFrame"];
  var frameDocHeight = 0;
  try {
    frameDocHeight = routeLogFrameWin.document.height;
  } catch ( e ) {
    // unable to set due to cross-domain scripting
    frameDocHeight = 0;
  }
  if ( frameDocHeight > 0 ) {
	  if (routeLogFrame && routeLogFrameWin) {

	    if ((Math.abs(frameDocHeight - currentHeight)) > 20 ) {
	      if (safari > -1) {
	        if ((Math.abs(docHt - currentHeight)) > 59 ) {
	          routeLogFrame.style.height = currentHeight + 30 + "px";
	          currentHeight = frameDocHeight;
	        }
	      } else {
	        routeLogFrame.style.height = currentHeight + 30 + "px";
	        currentHeight = frameDocHeight;
	      }
	    }

	    if (routeLogResizeTimer == "" ) {
	      routeLogResizeTimer = setInterval("resizeTheRouteLogFrame()",300);
	    }
	  }
  }
}

function resizeTheRouteLogFrame() {
  setRouteLogIframeDimensions();
}
<commit_msg>KULRICE-295 : fixed route log iframe collapsing issue<commit_after>/*
 * Copyright 2006-2007 The Kuali Foundation.
 *
 * Licensed under the Educational Community License, Version 1.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.opensource.org/licenses/ecl1.php
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
// Toggles a tab to show / hide and changes the source image to properly reflect this
// change. Returns false to avoid post. Example usage:
// onclick="javascript: return toggleTab(document, this, ${currentTabIndex}) }
function toggleTab(doc, tabIndex) {
	if (doc.forms[0].elements['tabState[' + tabIndex + '].open'].value == 'false') {
        showTab(doc, tabIndex);
    } else {
        hideTab(doc, tabIndex);
	}
	return false;
}

function expandAllTab(doc, tabStatesSize) {
	for (var tabIndex = 0; tabIndex <= tabStatesSize.value; tabIndex++) {
        showTab(doc, tabIndex);
	}
	return false;
}

function collapseAllTab(doc, tabStatesSize) {
	for (var tabIndex = 0; tabIndex <= tabStatesSize.value; tabIndex++) {
        hideTab(doc, tabIndex);
	}
	return false;
}

function showTab(doc, tabIndex) {
    // replaced 'block' with '' to make budgetExpensesRow.tag happy.
    doc.getElementById('tab-' + tabIndex + '-div').style.display = '';
    doc.forms[0].elements['tabState[' + tabIndex + '].open'].value = 'true';
    var image = doc.getElementById('tab-' + tabIndex + '-imageToggle');
    image.src = jsContextPath + '/kr/images/tinybutton-hide.gif';
    image.alt = image.alt.replace(/^show/, 'hide');
    image.alt = image.alt.replace(/^open/, 'close');
    image.title = image.title.replace(/^show/, 'hide');
    image.title = image.title.replace(/^open/, 'close');
    return false;
}

function hideTab(doc, tabIndex) {
    doc.getElementById('tab-' + tabIndex + '-div').style.display = 'none';
    doc.forms[0].elements['tabState[' + tabIndex + '].open'].value = 'false';
    var image = doc.getElementById('tab-' + tabIndex + '-imageToggle');
    image.src = jsContextPath + '/kr/images/tinybutton-show.gif';
    image.alt = image.alt.replace(/^hide/, 'show');
    image.alt = image.alt.replace(/^close/, 'open');
    image.title = image.title.replace(/^hide/, 'show');
    image.title = image.title.replace(/^close/, 'open');
    return false;
}

var formHasAlreadyBeenSubmitted = false;
var excludeSubmitRestriction = false;
function hasFormAlreadyBeenSubmitted() {
    if (formHasAlreadyBeenSubmitted && !excludeSubmitRestriction) {
       alert("Page already being processed by the server.");
       return false;
    } else {
       formHasAlreadyBeenSubmitted = true;
       return true;
    }
    excludeSubmitRestriction = false;
}

function submitForm() {
    document.forms[0].submit();
}

/* script to prevent the return key from submitting a form unless the user is on a button or on a link. fix for KULFDBCK-555 */
function isReturnKeyAllowed(buttonPrefix , event) {
	/* use IE naming first then firefox. */
    var elemType = event.srcElement ? event.srcElement.type : event.target.type;
    if (elemType != null && elemType.toLowerCase() == 'textarea') {
      // KULEDOCS-1728: textareas need to have the return key enabled
      return true;
    }
	var initiator = event.srcElement ? event.srcElement.name : event.target.name;
	var key = event.keyCode;
	/* initiator is undefined check is to prevent return from doing anything if not in a form field since the initiator is undefined */
	/* 13 is return key code */
	/* length > 0 check is to allow user to hit return on links */
	if ( key == 13 ) {
		if( initiator == undefined || ( initiator.indexOf(buttonPrefix) != 0 && initiator.length > 0) ) {
		  // disallow enter key from fields that dont match prefix.
		  return false;
		}
	}
    return true;
}

//The following javascript is intended to resize the route log iframe
// to stay at an appropriate height based on the size of the documents
// contents contained in the iframe.
//  NOTE: this will only work when the domain serving the content of kuali
//         is the same as the domain serving the content of workflow.
var routeLogResizeTimer = ""; // holds the timer for the  route log iframe resizer
var currentHeight = 500; // holds the current height of the iframe
var safari = navigator.userAgent.toLowerCase().indexOf('safari');

function setRouteLogIframeDimensions() {
  var routeLogFrame = document.getElementById("routeLogIFrame");
  var routeLogFrameWin = window.frames["routeLogIFrame"];
  var frameDocHeight = 0;
  try {
    frameDocHeight = routeLogFrameWin.document.height;
  } catch ( e ) {
    // unable to set due to cross-domain scripting
    frameDocHeight = 0;
  }

  if ( frameDocHeight > 0 ) {
	  if (routeLogFrame && routeLogFrameWin) {

	    if ((Math.abs(frameDocHeight - currentHeight)) > 20 ) {
	      if (safari > -1) {
	        if ((Math.abs(docHt - currentHeight)) > 59 ) {
	          routeLogFrame.style.height = (frameDocHeight + 30) + "px";
	          currentHeight = frameDocHeight;
	        }
	      } else {
	        routeLogFrame.style.height = (frameDocHeight + 30) + "px";
	        currentHeight = frameDocHeight;
	      }
	    }

	    if (routeLogResizeTimer == "" ) {
	      routeLogResizeTimer = setInterval("resizeTheRouteLogFrame()",300);
	    }
	  }
  }
}

function resizeTheRouteLogFrame() {
  setRouteLogIframeDimensions();
}
<|endoftext|>