<commit_before>// View model for the courses page
function pageViewModel(gvm) {
    // Page specific i18n bindings
    gvm.app  = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName")}, gvm);
    gvm.title = ko.computed(function(){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("CourseTitle2");}, gvm);
    gvm.pageHeader = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("CourseTitle2");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName");}, gvm);

    gvm.availableLocations = ko.observableArray([]);
    gvm.availableTrainings = ko.observableArray([]);
    gvm.availableCourses = ko.observableArray([]);

    /*Teacher*/
    gvm.availableTeacher = ko.observableArray([]);
    gvm.currentteacherid = null;
    /*teacher*/

    // Pagination i18n bindings
    gvm.addBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddBtn")}, gvm);

    gvm.codeTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("CodeTableTitle");}, gvm);
    gvm.nameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("NameTableTitle");}, gvm);
    gvm.descTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("DescTableTitle");}, gvm);
    gvm.teacherTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("TeacherTableTitle");}, gvm);
    gvm.actionTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ActionTableTitle");}, gvm);

    // The table data observable array
    gvm.tabledata = ko.observableArray([]);

    // Add data to the table
    gvm.addTableData = function(id, code, name, desc, teach) {
        // Push data
        var tblOject = {tid: id, tcode: code, tname: name, tdesc: desc, tteach:teach};
        gvm.tabledata.push(tblOject);

        // Attach delete handler to delete button
        $('#removebtn-' + id).bind('click', function(event, data){
            // Delete the table item
            deleteTableItem(id, tblOject);
            event.stopPropagation();
        });

        // Attach edit handler to edit button
        $('#editbtn-' + id).bind('click', function(event, data){
            // Edit the table item
            showEditProjectTypeModal(code, name, desc, id);
            event.stopPropagation();
        });

        // Attach copy handler to copy button
        $('#copybtn-' + id).bind('click', function(event, data){
            // Delete the table item
            copyTableItem(id, tblOject);
            event.stopPropagation();
        });

        //Attach manage handler to manage competences, subcompetences and indicators to manage button
        $('#managebtn-' + id).bind('click', function(event, data) {
            //TODO
        });

        /*$('#studentbtn-' + id).bind('click', function(event, data) {
            showCoupleStudentListModal(id);
            gvm.currentprojectid = id;
            gvm.currentselectedlist = -1;
            event.stopPropagation();
            loadCoupleDropdown();
        });*/
    }

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    }
    /*
    gvm.updateDropdowns = function() {
        $.getJSON('api/teacherrapport/' + gvm.userId, function(data) {
            if(!$.isEmptyObject(data)) {
                $.each(data, function(i, item) {
                    $(".btn-teacher span:first").text(item.teacher);
                    gvm.currentteacherid = item.id;
                    gvm.updateTeacher(item.id);
                    LoadTablePage(item.currentteacherid, 1);
                });
            } else {
                gvm.updateTeacher();
            }
        });
    }*/

    /*gvm.updateTeacher = function(id) {
    $.getJSON('/api/getteacherrapport/' + id, function(data) {
        gvm.availableTeacher.removeAll();
        $.each(data, function(i, item) {
            console.log(item);
            gvm.availableTeacher.push(item);
            $("#teacherbtn-" + item.id).click(function(){
                $(".btn-teacher span:first").text($(this).text());
                gvm.currentteacherid = item.id;
                gvm.saveLastSelectedDropdowns();
                loadTablePage(item.id, 1);
            });
        });
    });
    }*/

    gvm.updateTeacher = function(id) {
        $.getJSON('/api/getteacherrapport/' + id, function(data) {
            gvm.availableTeacher.removeAll();
            $.each(data, function(i, item) {
                console.log(item);
                gvm.availableTeacher.push(item);
                $("#teacherbtn-" + item.id).click(function(){
                    $(".btn-teacher span:first").text($(this).text());
                    gvm.currentteacherid = item.id;
                    gvm.saveLastSelectedDropdowns();
                    loadTablePage(item.id, 1);
                });
            });
        });
    }

    }
/*
 * Delete item from table given the id.
 */
function deleteTableItem(id, tblOject) {
    showYesNoModal("Bent u zeker dat u dit item wil verwijderen? \r\n Let op: verwijderde items blijven in het systeem en kunnen weer actief gezet worden door een administrator. \r\n Gelieve de administrator te contacteren om een vak definitief te verwijderen.", function(val){
        if(val){
            $.ajax({
                url: "/api/coursedelete/" + id,
                type: "DELETE",
                success: function() {
                    viewModel.tabledata.remove(tblOject);
                }
            });
        }
    });
}
/*
 * Delete item from table given the id.
 */
function copyTableItem(id, tblOject) {
    showYesNoModal("Bent u zeker dat u dit item wil verwijderen? \r\n Let op: verwijderde items blijven in het systeem en kunnen weer actief gezet worden door een administrator. \r\n Gelieve de administrator te contacteren om een vak definitief te verwijderen.", function(val){
        if(val){
            $.ajax({
                url: "/api/coursedelete/" + id,
                type: "DELETE",
                success: function() {
                    viewModel.tabledata.remove(tblOject);
                }
            });
        }
    });
}

/*
 * Add a new projecttype
 */
function addNewProjecttypeForm(serialData, callback) {
    $.ajax({
            url: "/api/courserapport",
            type: "POST",
            data: serialData,
            success: function(data) {
                viewModel.addTableData(data['id'], data['code'], data['name'], data['description']);
                callback(true);
            },
            error: function(data) {
                callback(false);
            }
        });
}

/*
 * Add a new projecttype
 */
function addNewProjecttypeRaw(code, name, description, callback) {
    addNewProjecttypeForm("code=" + encodeURIComponent(code) + "&name=" + encodeURIComponent(name) + "&description=" + encodeURIComponent(description), callback);
}

/*
 * Update the projecttype
 * @param {type} id
 * @param {type} code
 * @param {type} name
 * @param {type} description
 * @param {type} callback
 * @returns {undefined}
 */
function updateProjecttypeForm(id, serialData, callback) {
    $.ajax({
        url: "/api/courseupdate/" + id,
        type: "PUT",
        data: serialData,
        success: function(data) {
            //viewModel.addTableData(data['id'], data['code'], data['name'], data['description']);
            loadTablePage(1); //TODO now it is refreshing table after updating but it redirects to pagenr 1     WERKT NIET
            callback(true);
        },
        error: function(data) {
            callback(false);
        }
    });
}

/**
 * update project type
 * @param {type} id
 * @param {type} code
 * @param {type} name
 * @param {type} description
 * @param {type} callback
 * @returns {undefined}
 */
function updateProjecttypeRaw(id, code, name, description, callback) {
    updateProjecttypeForm(id, "code=" + encodeURIComponent(code) + "&name=" + encodeURIComponent(name) + "&description=" + encodeURIComponent(description), callback);
}

/*
 * Load page of the table
 */
function loadTablePage(pagenr)
{
    $.getJSON('/api/coursesrapport/page/' + pagenr, function(data){

        /* Clear current table page */
        viewModel.clearTable();

        // Load table data
        $.each(data.data, function(i, item) {
            viewModel.addTableData(item.id, item.code, item.name, item.description, item.leerkracht);
        });

        /* Let previous en next buttons work */
        if(data.prev == "none"){
            $('#pager-prev-btn').addClass('disabled');
        } else {
            $('#pager-prev-btn').removeClass('disabled');
            $('#pager-prev-btn a').click(function(){
                loadTablePage(data.prev);
            });
        }

        if(data.next == "none"){
            $('#pager-next-btn').addClass('disabled');
        } else {
            $('#pager-next-btn').removeClass('disabled');
            $('#pager-next-btn a').click(function(){
                loadTablePage(data.next);
            });
        }

        // Number of pager buttons
        var numItems = $('.pager-nr-btn').length;

        /* Calculate for the pager buttons */
        var lowPage = Math.floor(pagenr/numItems) + 1;

        $('.pager-nr-btn').each(function() {
            /* calculate current page number */
            var thispagenr = lowPage++;

            /* Add the page number */
            $(this).html('' + thispagenr + '');

            /* Add active class to current page */
            if(thispagenr == pagenr) {
                $(this).addClass('active');
            } else {
                $(this).removeClass('active');
            }

            /* Disable inactive classes and bind handlers to active classes */
            if(thispagenr > data.pagecount) {
                $(this).addClass('disabled');
            } else {
                /* Add click listener for button */
                $(this).click(function() {
                    loadTablePage(thispagenr);
                });
            }
        });
    });

}

/**
 * Show a new projecttype modal.
 * @returns {undefined}
 */
function showNewProjectTypeModal()
{
    resetGeneralModal();
    setGeneralModalTitle(i18n.__("AddNewCourse"));
    setGeneralModalBody('<form id="newprojectform"> \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('CodeTableTitle') + '" " name="code"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('NameTableTitle') + '" name="name"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('DescTableTitle') + '" name="description"> \

 \

' +
                '<button class="btn btn-wide btn-default btn-teacher dropdown-toggle" type="button" id="availableTeacher" data-toggle="dropdown" aria-expanded="true" placeholder="' + i18n.__('TeacherTableTitle') + '">' +
                'Teacher' + '' +
                '</button>' +
                '
' +
                '

' +
                '
' +
            '
' +
            '</form>' );

    addGeneralModalButton(i18n.__("AddBtn"), function(){
        console.log($('#newprojectform').serialize());
       addNewProjecttypeForm($('#newprojectform').serialize(), function(result){
            hideModal();
        });
    });

    showGeneralModal();
}

/**
 * Show the edit projecttype modal.
 * @param {type} code
 * @param {type} name
 * @param {type} description
 * @param {type} tid
 * @returns {undefined}
 */
function showEditProjectTypeModal(code, name, description, tid)
{
  resetGeneralModal();
    setGeneralModalTitle(i18n.__("EditProjectTitle2"));
    setGeneralModalBody('<form id="updateprojectform"> \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('CodeTableTitle') + '" " name="code" value="' + code + '"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('NameTableTitle') + '" name="name" value="' + name + '"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('DescTableTitle') + '" name="description" value="' + description + '"> \

 \
        </form>');
    $.getJSON()

    addGeneralModalButton(i18n.__("SaveBtn"), function(){
        updateProjecttypeForm(tid, $('#updateprojectform').serialize(), function(result){
            hideModal();
        });
    });

    addGeneralModalButton(i18n.__("CancelBtn"), function(){
        hideModal();
    })

    showGeneralModal();
}

function showCoupleStudentListModal(projectid) {
    viewModel.currentselectedlist = -1;
    resetGeneralModal();
    setGeneralModalTitle(i18n.__("CoupleStudentList"));
    setGeneralModalBody(
        '
' +
            '<button class="btn btn-default dropdown-toggle" type="button" id="dropdownStudLists" data-toggle="dropdown" aria-expanded="true">' +
                'Dropdown' +
                '' +
            '</button>' +
            '
' +
            '
' +
        '
');

    addGeneralModalButton(i18n.__("SaveBtn"), function() {
        updateListForm(viewModel.currentselectedlist, $('#coupleform').serialize(), function(result){
            hideModal();
        });
    });

    addGeneralModalButton(i18n.__("CancelBtn"), function(){
        hideModal();
    })
    showGeneralModal();
}
function loadCoupleDropdown() {
    $.getJSON('/api/studentlists/' + viewModel.userId, function(data) {
        $.each(data, function(i, item) {
            $("#ddlLists").append('
' + item.name + '
')
            $("#dropdownitem-" + item.id).click(function(){
                $(this).parent().parent().parent().removeClass("open");
                $(this).parent().parent().parent().find(".btn").html($(this).text() + '');
                viewModel.currentselectedlist = item.id;
            });
        });
    });
    $("#dropdownStudLists").click(function() {
        $(this).parent().toggleClass("open");
    });
}

function updateListForm(id, serialData, callback) {
    $.ajax({
        url: "/api/project/" + viewModel.currentprojectid + "/studentlist/" + id,
        type: "POST",
        data: serialData,
        success: function(data) {
            callback(true);
        },
        error: function(data) {
            callback(false);
        }
    });
}

function initPage() {
    // Add button handlers
    $('#addProjectTypeBtn').click(function(){
        showNewProjectTypeModal();
    });

    $.getJSON('/api/currentuser', function(data) {
        viewModel.userId = data.id;
        /*viewModel.updateDropdowns();*/
    });

    loadTablePage(1);
}

<commit_msg>update/edit courses<commit_after>// View model for the courses page
function pageViewModel(gvm) {
    // Page specific i18n bindings
    gvm.app  = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName")}, gvm);
    gvm.title = ko.computed(function(){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("CourseTitle2");}, gvm);
    gvm.pageHeader = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("CourseTitle2");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName");}, gvm);

    gvm.availableLocations = ko.observableArray([]);
    gvm.availableTrainings = ko.observableArray([]);
    gvm.availableCourses = ko.observableArray([]);

    /*Teacher*/
    gvm.availableTeacher = ko.observableArray([]);
    gvm.currentteacherid = null;
    /*teacher*/

    // Pagination i18n bindings
    gvm.addBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddBtn")}, gvm);

    gvm.codeTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("CodeTableTitle");}, gvm);
    gvm.nameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("NameTableTitle");}, gvm);
    gvm.descTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("DescTableTitle");}, gvm);
    gvm.teacherTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("TeacherTableTitle");}, gvm);
    gvm.actionTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ActionTableTitle");}, gvm);

    // The table data observable array
    gvm.tabledata = ko.observableArray([]);

    // Add data to the table
    gvm.addTableData = function(id, code, name, desc, teach) {
        // Push data
        var tblOject = {tid: id, tcode: code, tname: name, tdesc: desc, tteach:teach};
        gvm.tabledata.push(tblOject);

        // Attach delete handler to delete button
        $('#removebtn-' + id).bind('click', function(event, data){
            // Delete the table item
            deleteTableItem(id, tblOject);
            event.stopPropagation();
        });

        // Attach edit handler to edit button
        $('#editbtn-' + id).bind('click', function(event, data){
            // Edit the table item
            showEditProjectTypeModal(code, name, desc, id);
            event.stopPropagation();
        });

        // Attach copy handler to copy button
        $('#copybtn-' + id).bind('click', function(event, data){
            // Delete the table item
            copyTableItem(id, tblOject);
            event.stopPropagation();
        });

        //Attach manage handler to manage competences, subcompetences and indicators to manage button
        $('#managebtn-' + id).bind('click', function(event, data) {
            //TODO
        });

        /*$('#studentbtn-' + id).bind('click', function(event, data) {
            showCoupleStudentListModal(id);
            gvm.currentprojectid = id;
            gvm.currentselectedlist = -1;
            event.stopPropagation();
            loadCoupleDropdown();
        });*/
    }

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    }
    /*
    gvm.updateDropdowns = function() {
        $.getJSON('api/teacherrapport/' + gvm.userId, function(data) {
            if(!$.isEmptyObject(data)) {
                $.each(data, function(i, item) {
                    $(".btn-teacher span:first").text(item.teacher);
                    gvm.currentteacherid = item.id;
                    gvm.updateTeacher(item.id);
                    LoadTablePage(item.currentteacherid, 1);
                });
            } else {
                gvm.updateTeacher();
            }
        });
    }*/

    /*gvm.updateTeacher = function(id) {
    $.getJSON('/api/getteacherrapport/' + id, function(data) {
        gvm.availableTeacher.removeAll();
        $.each(data, function(i, item) {
            console.log(item);
            gvm.availableTeacher.push(item);
            $("#teacherbtn-" + item.id).click(function(){
                $(".btn-teacher span:first").text($(this).text());
                gvm.currentteacherid = item.id;
                gvm.saveLastSelectedDropdowns();
                loadTablePage(item.id, 1);
            });
        });
    });
    }*/

    gvm.updateTeacher = function(id) {
        $.getJSON('/api/getteacherrapport/' + id, function(data) {
            gvm.availableTeacher.removeAll();
            $.each(data, function(i, item) {
                console.log(item);
                gvm.availableTeacher.push(item);
                $("#teacherbtn-" + item.id).click(function(){
                    $(".btn-teacher span:first").text($(this).text());
                    gvm.currentteacherid = item.id;
                    gvm.saveLastSelectedDropdowns();
                    loadTablePage(item.id, 1);
                });
            });
        });
    }

    }
/*
 * Delete item from table given the id.
 */
function deleteTableItem(id, tblOject) {
    showYesNoModal("Bent u zeker dat u dit item wil verwijderen? \r\n Let op: verwijderde items blijven in het systeem en kunnen weer actief gezet worden door een administrator. \r\n Gelieve de administrator te contacteren om een vak definitief te verwijderen.", function(val){
        if(val){
            $.ajax({
                url: "/api/coursedelete/" + id,
                type: "DELETE",
                success: function() {
                    viewModel.tabledata.remove(tblOject);
                }
            });
        }
    });
}
/*
 * Delete item from table given the id.
 */
function copyTableItem(id, tblOject) {
    showYesNoModal("Bent u zeker dat u dit item wil verwijderen? \r\n Let op: verwijderde items blijven in het systeem en kunnen weer actief gezet worden door een administrator. \r\n Gelieve de administrator te contacteren om een vak definitief te verwijderen.", function(val){
        if(val){
            $.ajax({
                url: "/api/coursedelete/" + id,
                type: "DELETE",
                success: function() {
                    viewModel.tabledata.remove(tblOject);
                }
            });
        }
    });
}

/*
 * Add a new projecttype
 */
function addNewProjecttypeForm(serialData, callback) {
    $.ajax({
            url: "/api/courserapport",
            type: "POST",
            data: serialData,
            success: function(data) {
                viewModel.addTableData(data['id'], data['code'], data['name'], data['description']);
                callback(true);
            },
            error: function(data) {
                callback(false);
            }
        });
}

/*
 * Add a new projecttype
 */
function addNewProjecttypeRaw(code, name, description, callback) {
    addNewProjecttypeForm("code=" + encodeURIComponent(code) + "&name=" + encodeURIComponent(name) + "&description=" + encodeURIComponent(description), callback);
}

/*
 * Update the projecttype
 * @param {type} id
 * @param {type} code
 * @param {type} name
 * @param {type} description
 * @param {type} callback
 * @returns {undefined}
 */
function updateProjecttypeForm(id, serialData, callback) {
    $.ajax({
        url: "/api/courseupdate/" + id,
        type: "PUT",
        data: serialData,
        success: function(data) {
            //viewModel.addTableData(data['id'], data['code'], data['name'], data['description']);
            loadTablePage(1); //TODO now it is refreshing table after updating but it redirects to pagenr 1     WERKT NIET
            callback(true);
        },
        error: function(data) {
            callback(false);
        }
    });
}

/**
 * update project type
 * @param {type} id
 * @param {type} code
 * @param {type} name
 * @param {type} description
 * @param {type} callback
 * @returns {undefined}
 */
function updateProjecttypeRaw(id, code, name, description, callback) {
    updateProjecttypeForm(id, "code=" + encodeURIComponent(code) + "&name=" + encodeURIComponent(name) + "&description=" + encodeURIComponent(description), callback);
}

/*
 * Load page of the table
 */
function loadTablePage(pagenr)
{
    $.getJSON('/api/coursesrapport/page/' + pagenr, function(data){

        /* Clear current table page */
        viewModel.clearTable();

        // Load table data
        $.each(data.data, function(i, item) {
            viewModel.addTableData(item.id, item.code, item.name, item.description, item.firstname);
        });

        /* Let previous en next buttons work */
        if(data.prev == "none"){
            $('#pager-prev-btn').addClass('disabled');
        } else {
            $('#pager-prev-btn').removeClass('disabled');
            $('#pager-prev-btn a').click(function(){
                loadTablePage(data.prev);
            });
        }

        if(data.next == "none"){
            $('#pager-next-btn').addClass('disabled');
        } else {
            $('#pager-next-btn').removeClass('disabled');
            $('#pager-next-btn a').click(function(){
                loadTablePage(data.next);
            });
        }

        // Number of pager buttons
        var numItems = $('.pager-nr-btn').length;

        /* Calculate for the pager buttons */
        var lowPage = Math.floor(pagenr/numItems) + 1;

        $('.pager-nr-btn').each(function() {
            /* calculate current page number */
            var thispagenr = lowPage++;

            /* Add the page number */
            $(this).html('' + thispagenr + '');

            /* Add active class to current page */
            if(thispagenr == pagenr) {
                $(this).addClass('active');
            } else {
                $(this).removeClass('active');
            }

            /* Disable inactive classes and bind handlers to active classes */
            if(thispagenr > data.pagecount) {
                $(this).addClass('disabled');
            } else {
                /* Add click listener for button */
                $(this).click(function() {
                    loadTablePage(thispagenr);
                });
            }
        });
    });

}

/**
 * Show a new projecttype modal.
 * @returns {undefined}
 */
function showNewProjectTypeModal()
{
    resetGeneralModal();
    setGeneralModalTitle(i18n.__("AddNewCourse"));
    setGeneralModalBody('<form id="newprojectform"> \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('CodeTableTitle') + '" " name="code"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('NameTableTitle') + '" name="name"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('DescTableTitle') + '" name="description"> \

 \

' +
                '<button class="btn btn-wide btn-default btn-teacher dropdown-toggle" type="button" id="availableTeacher" data-toggle="dropdown" aria-expanded="true" placeholder="' + i18n.__('TeacherTableTitle') + '">' +
                'Teacher' + '' +
                '</button>' +
                '
' +
                '

' +
                '
' +
            '
' +
            '</form>' );

    addGeneralModalButton(i18n.__("AddBtn"), function(){
        console.log($('#newprojectform').serialize());
       addNewProjecttypeForm($('#newprojectform').serialize(), function(result){
            hideModal();
        });
    });

    showGeneralModal();
}

/**
 * Show the edit projecttype modal.
 * @param {type} code
 * @param {type} name
 * @param {type} description
 * @param {type} tid
 * @returns {undefined}
 */
function showEditProjectTypeModal(code, name, description, tid)
{
  resetGeneralModal();
    setGeneralModalTitle(i18n.__("EditProjectTitle2"));
    setGeneralModalBody('<form id="updateprojectform"> \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('CodeTableTitle') + '" " name="code" value="' + code + '"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('NameTableTitle') + '" name="name" value="' + name + '"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('DescTableTitle') + '" name="description" value="' + description + '"> \

 \
        </form>');
    $.getJSON()

    addGeneralModalButton(i18n.__("SaveBtn"), function(){
        updateProjecttypeForm(tid, $('#updateprojectform').serialize(), function(result){
            hideModal();
        });
    });

    addGeneralModalButton(i18n.__("CancelBtn"), function(){
        hideModal();
    })

    showGeneralModal();
}

function showCoupleStudentListModal(projectid) {
    viewModel.currentselectedlist = -1;
    resetGeneralModal();
    setGeneralModalTitle(i18n.__("CoupleStudentList"));
    setGeneralModalBody(
        '
' +
            '<button class="btn btn-default dropdown-toggle" type="button" id="dropdownStudLists" data-toggle="dropdown" aria-expanded="true">' +
                'Dropdown' +
                '' +
            '</button>' +
            '
' +
            '
' +
        '
');

    addGeneralModalButton(i18n.__("SaveBtn"), function() {
        updateListForm(viewModel.currentselectedlist, $('#coupleform').serialize(), function(result){
            hideModal();
        });
    });

    addGeneralModalButton(i18n.__("CancelBtn"), function(){
        hideModal();
    })
    showGeneralModal();
}
function loadCoupleDropdown() {
    $.getJSON('/api/studentlists/' + viewModel.userId, function(data) {
        $.each(data, function(i, item) {
            $("#ddlLists").append('
' + item.name + '
')
            $("#dropdownitem-" + item.id).click(function(){
                $(this).parent().parent().parent().removeClass("open");
                $(this).parent().parent().parent().find(".btn").html($(this).text() + '');
                viewModel.currentselectedlist = item.id;
            });
        });
    });
    $("#dropdownStudLists").click(function() {
        $(this).parent().toggleClass("open");
    });
}

function updateListForm(id, serialData, callback) {
    $.ajax({
        url: "/api/project/" + viewModel.currentprojectid + "/studentlist/" + id,
        type: "POST",
        data: serialData,
        success: function(data) {
            callback(true);
        },
        error: function(data) {
            callback(false);
        }
    });
}

function initPage() {
    // Add button handlers
    $('#addProjectTypeBtn').click(function(){
        showNewProjectTypeModal();
    });

    $.getJSON('/api/currentuser', function(data) {
        viewModel.userId = data.id;
        /*viewModel.updateDropdowns();*/
    });

    loadTablePage(1);
}

<|endoftext|>


<commit_before>define('tempo30/view/layer/tempo30-antraege', [
    'jquery',
    'leaflet',
    'gettext!tempo30',
    'tempo30/model/osm-points-tags',
    'leaflet-layer-overpass',
], function ($, L, gt, osmTags) {

    'use strict';

    var endpoint= 'https://overpass-api.de/api/';
    var loadingDiv=$('
').text(gt('Loading OpenStreetMap POIs, please wait (this will take normaly 30 seconds) ...'));

    var query= '[out:json][timeout:60];(';
    var url='https://tools.adfc-hamburg.de/tempo30-backend/master/antragsmap.php',
        request = new XMLHttpRequest();

//    url = requirejs.toUrl('d');

    request.open("GET", url, true);
    var opl = new L.FeatureGroup([]);

    request.onload = function() {
        if (this.status === 200) {
            var reference = {instance: self};
            var data=JSON.parse(this.response);
            for(var i=0;i<data.length;i++) {
                var e = data[i];
                var color='blue';
                var pos = new L.LatLng(e.lat, e.lon);
                var popup;
                popup='
Nr. '+e.id+'
';
                var circle = L.circle(pos, 50, {
                    color: color,
                    fillColor: 'blue',
                    fillOpacity: 0.4
                }).bindPopup(popup);
                opl.addLayer(circle);
            }
//          loadingDiv.remove();
        } else {
        }
    };
    request.onreadystatechange = function()
    {
        if ((this.readyState === 4) && (this.status != 200)){
            alert('Error loading OSM Pois'+ request.statusText);
//          loadingDiv.remove();
        }
    };
//    $('body').append(loadingDiv);
    request.send('data=' + query);
    return opl;
});
<commit_msg>Display Antrags-Status<commit_after>define('tempo30/view/layer/tempo30-antraege', [
    'jquery',
    'leaflet',
    'gettext!tempo30',
    'tempo30/model/osm-points-tags',
    'leaflet-layer-overpass',
], function ($, L, gt, osmTags) {

    'use strict';

    var endpoint= 'https://overpass-api.de/api/';
    var loadingDiv=$('
').text(gt('Loading OpenStreetMap POIs, please wait (this will take normaly 30 seconds) ...'));

    var query= '[out:json][timeout:60];(';
    var url='https://tools.adfc-hamburg.de/tempo30-backend/master/antragsmap.php',
        request = new XMLHttpRequest();

//    url = requirejs.toUrl('d');

    request.open("GET", url, true);
    var opl = new L.FeatureGroup([]);

    request.onload = function() {
        if (this.status === 200) {
            var reference = {instance: self};
            var data=JSON.parse(this.response);
            for(var i=0;i<data.length;i++) {
                var e = data[i];
                var color='blue';
                var status='Antragstools benutzt';
                if (e.status==='1') {
		            color='green';
                    status='Antrag wird doch nicht mehr gestellt';
		        }
		        if (e.status==='2') {
		            color='red';
                    status='Antrag bei Behörde gestellt';
		        }
                var pos = new L.LatLng(e.lat, e.lon);
                var popup;
                popup='
Nr. '+e.id+'
'+status+'
';
                var circle = L.circle(pos, 50, {
                    color: color,
                    fillColor: color,
                    fillOpacity: 0.4
                }).bindPopup(popup);
                opl.addLayer(circle);
            }
//          loadingDiv.remove();
        } else {
        }
    };
    request.onreadystatechange = function()
    {
        if ((this.readyState === 4) && (this.status != 200)){
            alert('Error loading OSM Pois'+ request.statusText);
//          loadingDiv.remove();
        }
    };
//    $('body').append(loadingDiv);
    request.send('data=' + query);
    return opl;
});
<|endoftext|>


<commit_before>{% load knockout %}

var {{ view_model_string }} = function(data) {
    var self = this;

    {{ model_string}}

	{{ model_list_string }}
}
<commit_msg>move model to global, add class def to end brace<commit_after>{% load knockout %}
{{ model_string }}
var {{ view_model_string }} = function(data) {
    var self = this;
	{{ model_list_string }}
} // {{ view_model_string }}
<|endoftext|>


<commit_before>//adopted from: has-glob <https://github.com/jonschlinkert/has-glob>
// Copyright (c) 2015, Jon Schlinkert. (MIT)

'use strict';

var isGlob = require('./is-glob');

function hasGlob (val) {
  if (val == null) return false
  if (typeof val === 'string') return isGlob(val)

  if (Array.isArray(val)) {
    var len = val.length

    while (len--) {
      if (isGlob(val[len])) return true
    }
  }
  return false
}

module.exports = hasGlob

<commit_msg>update glob/has-glob -- lint<commit_after>//adopted from: has-glob <https://github.com/jonschlinkert/has-glob>
// Copyright (c) 2015, Jon Schlinkert. (MIT)

'use strict'

var isGlob = require('./is-glob')

function hasGlob (val) {
  if (val == null) return false
  if (typeof val === 'string') return isGlob(val)

  if (Array.isArray(val)) {
    var len = val.length

    while (len--) {
      if (isGlob(val[len])) return true
    }
  }
  return false
}

module.exports = hasGlob
<|endoftext|>


<commit_before>define(function (require) {

    'use strict';

    var Cartesian3D = require('./component/Cartesian3D');
    var App3D = require('../core/App3D');
    var number = require('../core/number');
    var colorTool = require('../core/color');

    var vendor = require('qtek/core/vendor');
    var DynamicGeometry = require('qtek/DynamicGeometry');
    var Scene = require('qtek/Scene');
    var PerspectiveCamera = require('qtek/camera/Perspective');
    var OrthoCamera = require('qtek/camera/Orthographic');
    var qtekUtil = require('qtek/core/util');
    var Renderable = require('qtek/Renderable');
    var Node3D = require('qtek/Node');
    var glMatrix = require('qtek/dep/glmatrix');
    var vec4 = glMatrix.vec4;
    var OrbitControl = require('./component/OrbitControl');

    var Sequence = require('../generator/Sequence');

    var rangeOfData = number.rangeOfData;

    var BLACK = [0, 0, 0, 1];

    var DEFAULTS = {

        axisLineWidth: 1,

        axisWireframeLineWidth: 1,

        axisWireframeLineColor: 'grey',

        showWireframe: true,

        wireframeLineColor: '#111',

        wireframeLineWidth: 1,

        projection: 'orthographic',

        renderer: 'auto',

        autoRotate: true,

        parametric: false,

        color: ['red', 'green'],

        // If parametric is true
        parameters: {
            u: new Sequence(0, 1, 0.05),
            v: new Sequence(0, 1, 0.05)
        }
    };

    var BOX_SIZE = 100;
    /**
     * Surface Graph
     * @param {HTMLCanvasElement} canvas
     * @param {Object} opts
     */
    function SurfaceGraph(canvas, opts) {

        this._init(canvas, opts);
    }

    SurfaceGraph.prototype = {

        constructor: SurfaceGraph,

        resize: function (width, height) {
            this._app3d.resize(width, height);

            var camera = this._camera;
            var aspect = this._app3d.getRenderer().getViewportAspect();
            if (camera instanceof OrthoCamera) {
                camera.left = -BOX_SIZE * aspect;
                camera.right = BOX_SIZE * aspect;
            }
            else {
                camera.aspect = aspect;
            }
        },

        _init: function (canvas, opts) {
            // Clone and extend default options
            opts = qtekUtil.extend({}, opts);
            qtekUtil.defaults(opts, DEFAULTS);

            var app3d = new App3D(canvas, {
                renderer: opts.renderer
            });
            this._app3d = app3d;

            var dataOpts = this._convertData(opts);
            var data = dataOpts.data;
            var xRange = opts.xAxis.range || rangeOfData(data.map(function (a) {return a.x}));
            var yRange = opts.yAxis.range || rangeOfData(data.map(function (a) {return a.y}));
            var zRange = opts.zAxis.range || rangeOfData(data.map(function (a) {return a.z}));

            var cartesian = new Cartesian3D(app3d, {
                xAxis: qtekUtil.extend({
                        range: xRange
                    }, opts.xAxis),
                yAxis: qtekUtil.extend({
                        range: yRange
                    }, opts.yAxis),
                zAxis: qtekUtil.extend({
                        range: zRange
                    }, opts.zAxis),
                renderer: opts.renderer,
                axisLineWidth: opts.axisLineWidth,
                axisWireframeLineWidth: opts.axisWireframeLineWidth,
                axisWireframeLineColor: opts.axisWireframeLineColor,
                size: BOX_SIZE
            });
            this._cartesian = cartesian;

            var scene = new Scene();
            // Dummy node
            var dummy = new Node3D();
            dummy.rotation
                .rotateX(Math.PI / 5)
                .rotateY(-Math.PI / 4);
            var control = new OrbitControl(app3d, {
                target: dummy,
                autoRotate: opts.autoRotate
            });
            this._orbitControl = control;

            var root = new Node3D();
            root.add(cartesian.root);

            dummy.add(root);
            scene.add(dummy);

            // Z UP
            root.rotation.rotateX(-Math.PI / 2);
            root.position.set(-BOX_SIZE / 2, -BOX_SIZE / 2, BOX_SIZE / 2);

            var aspect = app3d.getRenderer().getViewportAspect();
            var camera = opts.projection.toLowerCase() === 'orthographic'
                ? new OrthoCamera({
                    left: -BOX_SIZE * aspect,
                    right: BOX_SIZE * aspect,
                    bottom: -BOX_SIZE,
                    top: BOX_SIZE,
                    near: 0,
                    far: BOX_SIZE * 10
                })
                : new PerspectiveCamera({
                    aspect: aspect,
                    far: BOX_SIZE * 10,
                    fov: 50
                });

            camera.position.set(0, 0, BOX_SIZE * 2.5);
            camera.lookAt(scene.position);

            this._scene = scene;
            this._camera = camera;
            this._root = root;

            this._constructSurface(dataOpts, opts);

            app3d.on('render', this._doRender, this);
            app3d.on('frame', this._frameUpdate, this);

            this.resize();
        },

        _doRender: function (renderer) {
            renderer.render(this._scene, this._camera);
        },

        _frameUpdate: function (deltaTime) {
            this._orbitControl.update(deltaTime);
        },

        _convertData: function (opts) {

            var xData = opts.xAxis.data;
            var yData = opts.yAxis.data;
            var zData = opts.zAxis.data;

            var xDataFunction = typeof xData == 'function';
            var yDataFunction = typeof yData == 'function';
            var zDataFunction = typeof zData == 'function';

            var parametric = opts.parametric;
            var data = [];

            var uLen;
            var vLen;
            if (parametric) { // Parametric Surface
                // Two optional data source
                // 1. x.data, y.data, z.data are all functions
                // 2. All data are m-by-n matrix
                if (xDataFunction && yDataFunction && zDataFunction) {
                    var parameters = opts.parameters;
                    var uGen = parameters.u;
                    var vGen = parameters.v;

                    if (!((uGen instanceof Sequence) && (vGen instanceof Sequence))) {
                        console.warn('Parameters u, v must be grapher.generator.Sequence')
                        return;
                    }
                    uLen = uGen.length();
                    vLen = vGen.length();

                    for (var i = 0; i < uLen; i++) {
                        var u = uGen.at(i);
                        for (var j = 0; j < vLen; j++) {
                            var v = vGen.at(j);

                            var x = xData(u, v);
                            var y = yData(u, v);
                            var z = zData(u, v);

                            data.push({
                                x: x,
                                y: y,
                                z: z
                            });
                        }
                    }
                }
                else {
                    if (! number.sameDimensions(xData, yData, zData)) {
                        console.warn('x, y, z don\'t have same dimensions');
                    }

                    var dims = number.getDimensions(xData);
                    vLen = dims[0];
                    uLen = dims[1];

                    for (var i = 0; i < vLen; i++) {
                        for (var j = 0; j < uLen; j++) {
                            var x = xData(u, v);
                            var y = yData(u, v);
                            var z = zData(u, v);

                            data.push({
                                x: x,
                                y: y,
                                z: z
                            });
                        }
                    }
                }
            }
            else {
                // 1. x.data, y.data are grapher.generator.Sequence, default are [0, 100, 5]
                // 2. x.data is m-array, y.data is n-array
                //
                // 1. z.data is a generator function
                // 2. z.data is n-by-m matrix

                xData = xData || new Sequence(0, 100, 5);
                yData = yData || new Sequence(0, 100, 5);

                var xDataSequence = xData instanceof Sequence;
                var yDataSequence = yData instanceof Sequence;
                uLen = xDataSequence ? xData.length() : xData.length;
                vLen = yDataSequence ? yData.length() : yData.length;

                for (var i = 0; i < vLen; i++) {
                    var y = yDataSequence ? yData.at(i) : yData[i];
                    for (var j = 0; j < uLen; j++) {
                        var x = xDataSequence ? xData.at(j) : xData[j];
                        var z;
                        if (zDataFunction) {
                            z = zData(x, y);
                        }
                        else {
                            z = zData[i][j];
                        }
                        data.push({
                            x: x,
                            y: y,
                            z: z
                        });
                    }
                }
            }

            return {
                uLen: uLen,
                vLen: vLen,
                data: data
            }
        },

        _constructSurface: function (dataOpts, opts) {
            var surfaceGeo = new DynamicGeometry();
            var gridGeo = opts.showWireframe && new DynamicGeometry();

            var attributes = surfaceGeo.attributes;
            var positionAttrib = attributes.position;
            var colorAttrib = attributes.color;
            var cartesian = this._cartesian;

            var uLen = dataOpts.uLen;
            var vLen = dataOpts.vLen;
            var data = dataOpts.data;

            var xRange = rangeOfData(data.map(function (a) {return a.x}));;
            var yRange = rangeOfData(data.map(function (a) {return a.y}));;
            var zRange = rangeOfData(data.map(function (a) {return a.z}));;

            // Color gradient
            var colorCfg = opts.color;
            var isColorGradient = colorCfg instanceof Array;
            var isColorFunction = typeof colorCfg === 'function';
            var colorSteps;
            if (isColorGradient) {
                colorSteps = colorCfg.map(function (c) {
                    return colorTool.parse(c) || BLACK;
                });
            }

            for (var i = 0; i < data.length; i++) {
                var value = data[i];
                var coord = cartesian.valueToCoord(value);
                var z = coord.z;
                positionAttrib.set(i, [coord.x, coord.y, coord.z]);

                var color;
                if (isColorGradient) {
                    var zPercent = (value.z - zRange[0]) / (zRange[1] - zRange[0]);
                    var nColorStep = colorSteps.length;
                    if (zPercent === 1) {
                        color = colorSteps[nColorStep - 1].slice();
                    }
                    else {
                        var pp = (nColorStep - 1) * zPercent;
                        var idx = Math.floor(pp);
                        color = vec4.lerp([], colorSteps[idx], colorSteps[idx + 1], pp - idx);
                    }
                }
                else {
                    var xPercent = (value.x - xRange[0]) / (xRange[1] - xRange[0]);
                    var yPercent = (value.y - yRange[0]) / (yRange[1] - yRange[0]);
                    var zPercent = (value.z - zRange[0]) / (zRange[1] - zRange[0]);
                    color = colorTool.parse(colorCfg(xPercent, yPercent, zPercent, x, y, z)) || BLACK;
                }

                colorAttrib.set(i, color);
            }
            // Build triangles
            var faces = surfaceGeo.faces = [];
            var idx = 0;

            var positionArr = positionAttrib.value;
            var gridPositionAttrib = gridGeo && gridGeo.attributes.position;
            for (var i = 0; i < uLen; i++) {
                for (var j = 0; j < vLen; j++) {
                    var i2 = i * vLen + j;
                    var i1 = i * vLen + j + 1;
                    var i4 = (i + 1) * vLen + j + 1;
                    var i3 = (i + 1) * vLen + j;

                    if (i < uLen - 1 && j < vLen - 1 ) {
                        faces.push([i1, i2, i4], [i2, i3, i4]);

                        if (gridGeo) {
                            // Line1
                            gridPositionAttrib.set(idx++, positionArr[i1]);
                            gridPositionAttrib.set(idx++, positionArr[i2]);
                            // Line2
                            gridPositionAttrib.set(idx++, positionArr[i2]);
                            gridPositionAttrib.set(idx++, positionArr[i3]);
                        }
                    }
                    else if (i === uLen - 1 && j === vLen - 1) {
                        continue;
                    }
                    // Wireframes
                    else if (i === uLen - 1) {
                        if (gridGeo) {
                            gridPositionAttrib.set(idx++, positionArr[i1]);
                            gridPositionAttrib.set(idx++, positionArr[i2]);
                        }
                    }
                    else {
                        if (gridGeo) {
                            gridPositionAttrib.set(idx++, positionArr[i2]);
                            gridPositionAttrib.set(idx++, positionArr[i3]);
                        }
                    }
                }
            }

            var app3d = this._app3d;
            var root = this._root;
            var surfaceMesh = new Renderable({
                geometry: surfaceGeo,
                material: app3d.createColorMaterial([1, 1, 1], 1, true),
                culling: false
            });

            root.add(surfaceMesh);

            if (gridGeo) {
                var mat = app3d.createColorMaterial(colorTool.parse(opts.wireframeLineColor) || BLACK, 1);
                var lineWidth = opts.wireframeLineWidth;
                var GL_LINES = Renderable.LINES;
                var gridMesh1 = new Renderable({
                    geometry: gridGeo,
                    material: mat,
                    culling: false,
                    lineWidth: lineWidth,
                    mode: GL_LINES
                });

                var gridMesh2 = new Renderable({
                    geometry: gridGeo,
                    material: mat,
                    culling: false,
                    lineWidth: lineWidth,
                    mode: GL_LINES
                });

                root.add(gridMesh1);
                root.add(gridMesh2);
                // Avoid z-fighting
                // FIXME Better solution ?
                gridMesh1.scale.set(1.002, 1.002, 1.002);
                gridMesh2.scale.set(0.999, 0.999, 0.999);
            }
        }
    }

    SurfaceGraph.DEFAULTS = DEFAULTS;

    return SurfaceGraph;
});<commit_msg>Default axisLineWidth changed to 3<commit_after>define(function (require) {

    'use strict';

    var Cartesian3D = require('./component/Cartesian3D');
    var App3D = require('../core/App3D');
    var number = require('../core/number');
    var colorTool = require('../core/color');

    var vendor = require('qtek/core/vendor');
    var DynamicGeometry = require('qtek/DynamicGeometry');
    var Scene = require('qtek/Scene');
    var PerspectiveCamera = require('qtek/camera/Perspective');
    var OrthoCamera = require('qtek/camera/Orthographic');
    var qtekUtil = require('qtek/core/util');
    var Renderable = require('qtek/Renderable');
    var Node3D = require('qtek/Node');
    var glMatrix = require('qtek/dep/glmatrix');
    var vec4 = glMatrix.vec4;
    var OrbitControl = require('./component/OrbitControl');

    var Sequence = require('../generator/Sequence');

    var rangeOfData = number.rangeOfData;

    var BLACK = [0, 0, 0, 1];

    var DEFAULTS = {

        axisLineWidth: 3,

        axisWireframeLineWidth: 1,

        axisWireframeLineColor: 'grey',

        showWireframe: true,

        wireframeLineColor: '#111',

        wireframeLineWidth: 1,

        projection: 'orthographic',

        renderer: 'auto',

        autoRotate: true,

        parametric: false,

        color: ['red', 'green'],

        // If parametric is true
        parameters: {
            u: new Sequence(0, 1, 0.05),
            v: new Sequence(0, 1, 0.05)
        }
    };

    var BOX_SIZE = 100;
    /**
     * Surface Graph
     * @param {HTMLCanvasElement} canvas
     * @param {Object} opts
     */
    function SurfaceGraph(canvas, opts) {

        this._init(canvas, opts);
    }

    SurfaceGraph.prototype = {

        constructor: SurfaceGraph,

        resize: function (width, height) {
            this._app3d.resize(width, height);

            var camera = this._camera;
            var aspect = this._app3d.getRenderer().getViewportAspect();
            if (camera instanceof OrthoCamera) {
                camera.left = -BOX_SIZE * aspect;
                camera.right = BOX_SIZE * aspect;
            }
            else {
                camera.aspect = aspect;
            }
        },

        _init: function (canvas, opts) {
            // Clone and extend default options
            opts = qtekUtil.extend({}, opts);
            qtekUtil.defaults(opts, DEFAULTS);

            var app3d = new App3D(canvas, {
                renderer: opts.renderer
            });
            this._app3d = app3d;

            var dataOpts = this._convertData(opts);
            var data = dataOpts.data;
            var xRange = opts.xAxis.range || rangeOfData(data.map(function (a) {return a.x}));
            var yRange = opts.yAxis.range || rangeOfData(data.map(function (a) {return a.y}));
            var zRange = opts.zAxis.range || rangeOfData(data.map(function (a) {return a.z}));

            var cartesian = new Cartesian3D(app3d, {
                xAxis: qtekUtil.extend({
                        range: xRange
                    }, opts.xAxis),
                yAxis: qtekUtil.extend({
                        range: yRange
                    }, opts.yAxis),
                zAxis: qtekUtil.extend({
                        range: zRange
                    }, opts.zAxis),
                renderer: opts.renderer,
                axisLineWidth: opts.axisLineWidth,
                axisWireframeLineWidth: opts.axisWireframeLineWidth,
                axisWireframeLineColor: opts.axisWireframeLineColor,
                size: BOX_SIZE
            });
            this._cartesian = cartesian;

            var scene = new Scene();
            // Dummy node
            var dummy = new Node3D();
            dummy.rotation
                .rotateX(Math.PI / 5)
                .rotateY(-Math.PI / 4);
            var control = new OrbitControl(app3d, {
                target: dummy,
                autoRotate: opts.autoRotate
            });
            this._orbitControl = control;

            var root = new Node3D();
            root.add(cartesian.root);

            dummy.add(root);
            scene.add(dummy);

            // Z UP
            root.rotation.rotateX(-Math.PI / 2);
            root.position.set(-BOX_SIZE / 2, -BOX_SIZE / 2, BOX_SIZE / 2);

            var aspect = app3d.getRenderer().getViewportAspect();
            var camera = opts.projection.toLowerCase() === 'orthographic'
                ? new OrthoCamera({
                    left: -BOX_SIZE * aspect,
                    right: BOX_SIZE * aspect,
                    bottom: -BOX_SIZE,
                    top: BOX_SIZE,
                    near: 0,
                    far: BOX_SIZE * 10
                })
                : new PerspectiveCamera({
                    aspect: aspect,
                    far: BOX_SIZE * 10,
                    fov: 50
                });

            camera.position.set(0, 0, BOX_SIZE * 2.5);
            camera.lookAt(scene.position);

            this._scene = scene;
            this._camera = camera;
            this._root = root;

            this._constructSurface(dataOpts, opts);

            app3d.on('render', this._doRender, this);
            app3d.on('frame', this._frameUpdate, this);

            this.resize();
        },

        _doRender: function (renderer) {
            renderer.render(this._scene, this._camera);
        },

        _frameUpdate: function (deltaTime) {
            this._orbitControl.update(deltaTime);
        },

        _convertData: function (opts) {

            var xData = opts.xAxis.data;
            var yData = opts.yAxis.data;
            var zData = opts.zAxis.data;

            var xDataFunction = typeof xData == 'function';
            var yDataFunction = typeof yData == 'function';
            var zDataFunction = typeof zData == 'function';

            var parametric = opts.parametric;
            var data = [];

            var uLen;
            var vLen;
            if (parametric) { // Parametric Surface
                // Two optional data source
                // 1. x.data, y.data, z.data are all functions
                // 2. All data are m-by-n matrix
                if (xDataFunction && yDataFunction && zDataFunction) {
                    var parameters = opts.parameters;
                    var uGen = parameters.u;
                    var vGen = parameters.v;

                    if (!((uGen instanceof Sequence) && (vGen instanceof Sequence))) {
                        console.warn('Parameters u, v must be grapher.generator.Sequence')
                        return;
                    }
                    uLen = uGen.length();
                    vLen = vGen.length();

                    for (var i = 0; i < uLen; i++) {
                        var u = uGen.at(i);
                        for (var j = 0; j < vLen; j++) {
                            var v = vGen.at(j);

                            var x = xData(u, v);
                            var y = yData(u, v);
                            var z = zData(u, v);

                            data.push({
                                x: x,
                                y: y,
                                z: z
                            });
                        }
                    }
                }
                else {
                    if (! number.sameDimensions(xData, yData, zData)) {
                        console.warn('x, y, z don\'t have same dimensions');
                    }

                    var dims = number.getDimensions(xData);
                    vLen = dims[0];
                    uLen = dims[1];

                    for (var i = 0; i < vLen; i++) {
                        for (var j = 0; j < uLen; j++) {
                            var x = xData(u, v);
                            var y = yData(u, v);
                            var z = zData(u, v);

                            data.push({
                                x: x,
                                y: y,
                                z: z
                            });
                        }
                    }
                }
            }
            else {
                // 1. x.data, y.data are grapher.generator.Sequence, default are [0, 100, 5]
                // 2. x.data is m-array, y.data is n-array
                //
                // 1. z.data is a generator function
                // 2. z.data is n-by-m matrix

                xData = xData || new Sequence(0, 100, 5);
                yData = yData || new Sequence(0, 100, 5);

                var xDataSequence = xData instanceof Sequence;
                var yDataSequence = yData instanceof Sequence;
                uLen = xDataSequence ? xData.length() : xData.length;
                vLen = yDataSequence ? yData.length() : yData.length;

                for (var i = 0; i < vLen; i++) {
                    var y = yDataSequence ? yData.at(i) : yData[i];
                    for (var j = 0; j < uLen; j++) {
                        var x = xDataSequence ? xData.at(j) : xData[j];
                        var z;
                        if (zDataFunction) {
                            z = zData(x, y);
                        }
                        else {
                            z = zData[i][j];
                        }
                        data.push({
                            x: x,
                            y: y,
                            z: z
                        });
                    }
                }
            }

            return {
                uLen: uLen,
                vLen: vLen,
                data: data
            }
        },

        _constructSurface: function (dataOpts, opts) {
            var surfaceGeo = new DynamicGeometry();
            var gridGeo = opts.showWireframe && new DynamicGeometry();

            var attributes = surfaceGeo.attributes;
            var positionAttrib = attributes.position;
            var colorAttrib = attributes.color;
            var cartesian = this._cartesian;

            var uLen = dataOpts.uLen;
            var vLen = dataOpts.vLen;
            var data = dataOpts.data;

            var xRange = rangeOfData(data.map(function (a) {return a.x}));;
            var yRange = rangeOfData(data.map(function (a) {return a.y}));;
            var zRange = rangeOfData(data.map(function (a) {return a.z}));;

            // Color gradient
            var colorCfg = opts.color;
            var isColorGradient = colorCfg instanceof Array;
            var isColorFunction = typeof colorCfg === 'function';
            var colorSteps;
            if (isColorGradient) {
                colorSteps = colorCfg.map(function (c) {
                    return colorTool.parse(c) || BLACK;
                });
            }

            for (var i = 0; i < data.length; i++) {
                var value = data[i];
                var coord = cartesian.valueToCoord(value);
                var z = coord.z;
                positionAttrib.set(i, [coord.x, coord.y, coord.z]);

                var color;
                if (isColorGradient) {
                    var zPercent = (value.z - zRange[0]) / (zRange[1] - zRange[0]);
                    var nColorStep = colorSteps.length;
                    if (zPercent === 1) {
                        color = colorSteps[nColorStep - 1].slice();
                    }
                    else {
                        var pp = (nColorStep - 1) * zPercent;
                        var idx = Math.floor(pp);
                        color = vec4.lerp([], colorSteps[idx], colorSteps[idx + 1], pp - idx);
                    }
                }
                else {
                    var xPercent = (value.x - xRange[0]) / (xRange[1] - xRange[0]);
                    var yPercent = (value.y - yRange[0]) / (yRange[1] - yRange[0]);
                    var zPercent = (value.z - zRange[0]) / (zRange[1] - zRange[0]);
                    color = colorTool.parse(colorCfg(xPercent, yPercent, zPercent, x, y, z)) || BLACK;
                }

                colorAttrib.set(i, color);
            }
            // Build triangles
            var faces = surfaceGeo.faces = [];
            var idx = 0;

            var positionArr = positionAttrib.value;
            var gridPositionAttrib = gridGeo && gridGeo.attributes.position;
            for (var i = 0; i < uLen; i++) {
                for (var j = 0; j < vLen; j++) {
                    var i2 = i * vLen + j;
                    var i1 = i * vLen + j + 1;
                    var i4 = (i + 1) * vLen + j + 1;
                    var i3 = (i + 1) * vLen + j;

                    if (i < uLen - 1 && j < vLen - 1 ) {
                        faces.push([i1, i2, i4], [i2, i3, i4]);

                        if (gridGeo) {
                            // Line1
                            gridPositionAttrib.set(idx++, positionArr[i1]);
                            gridPositionAttrib.set(idx++, positionArr[i2]);
                            // Line2
                            gridPositionAttrib.set(idx++, positionArr[i2]);
                            gridPositionAttrib.set(idx++, positionArr[i3]);
                        }
                    }
                    else if (i === uLen - 1 && j === vLen - 1) {
                        continue;
                    }
                    // Wireframes
                    else if (i === uLen - 1) {
                        if (gridGeo) {
                            gridPositionAttrib.set(idx++, positionArr[i1]);
                            gridPositionAttrib.set(idx++, positionArr[i2]);
                        }
                    }
                    else {
                        if (gridGeo) {
                            gridPositionAttrib.set(idx++, positionArr[i2]);
                            gridPositionAttrib.set(idx++, positionArr[i3]);
                        }
                    }
                }
            }

            var app3d = this._app3d;
            var root = this._root;
            var surfaceMesh = new Renderable({
                geometry: surfaceGeo,
                material: app3d.createColorMaterial([1, 1, 1], 1, true),
                culling: false
            });

            root.add(surfaceMesh);

            if (gridGeo) {
                var mat = app3d.createColorMaterial(colorTool.parse(opts.wireframeLineColor) || BLACK, 1);
                var lineWidth = opts.wireframeLineWidth;
                var GL_LINES = Renderable.LINES;
                var gridMesh1 = new Renderable({
                    geometry: gridGeo,
                    material: mat,
                    culling: false,
                    lineWidth: lineWidth,
                    mode: GL_LINES
                });

                var gridMesh2 = new Renderable({
                    geometry: gridGeo,
                    material: mat,
                    culling: false,
                    lineWidth: lineWidth,
                    mode: GL_LINES
                });

                root.add(gridMesh1);
                root.add(gridMesh2);
                // Avoid z-fighting
                // FIXME Better solution ?
                gridMesh1.scale.set(1.002, 1.002, 1.002);
                gridMesh2.scale.set(0.999, 0.999, 0.999);
            }
        }
    }

    SurfaceGraph.DEFAULTS = DEFAULTS;

    return SurfaceGraph;
});<|endoftext|>


<commit_before>//var socket = require('socket.io-client')('http://isaacparker.co:3030');
//var socket = require('socket.io-client')('http://192.168.86.38:8300');
var socket = require('socket.io-client')('http://heylex.us:8300');
var rpio = require('rpio');

const PIN_REMOTE_START = 12;
const PIN_UNLOCK = 16;
const PIN_LOCK = 18;

rpio.open(PIN_REMOTE_START, rpio.OUTPUT); // RS Trigger
rpio.open(16, rpio.OUTPUT); // Unlock
rpio.open(18, rpio.OUTPUT); // Lock

socket.on('connect', function(){
	console.log("Connected");
});

socket.on('disconnect', function(){
	console.log("Disconnected");
});

function confirmAction(action, eventId) {
	socket.emit('lex-confirm', {
		action: action,
		eventId: eventId
	});
}

function pulsePin(pin, duration) {
	var pulseDuration = 500;
	if(typeof(duration) !== 'undefined') {
		pulseDuration = duration;
	}
	rpio.write(pin, rpio.HIGH);
	rpio.msleep(pulseDuration);
	rpio.write(pin, rpio.LOW);
}

var commandHistory = {};

socket.on('lex-command', function incoming(message) {
    console.log('GPIO Command: %s', message);

	commandHistory[message] ? commandHistory[message]+=1 : commandHistory[message] = 1;

    if(message === "remote-start:engine:on" || message === "remote-start:engine:off") {
        pulsePin(PIN_REMOTE_START);
		confirmAction(message, commandHistory[message]);
	}

    if(message === "remote-start:security:unlock") {
        pulsePin(16);
		confirmAction(message, commandHistory[message]);
	}

    if(message === "remote-start:security:lock") {
        pulsePin(18);
		confirmAction(message, commandHistory[message]);
	}

});
<commit_msg>Minor updates to test deployments<commit_after>//var socket = require('socket.io-client')('http://isaacparker.co:3030');
//var socket = require('socket.io-client')('http://192.168.86.38:8300');
var socket = require('socket.io-client')('http://heylex.us:8300');
var rpio = require('rpio');

const PIN_REMOTE_START = 12;
const PIN_UNLOCK = 16;
const PIN_LOCK = 18;

rpio.open(PIN_REMOTE_START, rpio.OUTPUT); // RS Trigger
rpio.open(16, rpio.OUTPUT); // Unlock
rpio.open(18, rpio.OUTPUT); // Lock

socket.on('connect', function(){
	console.log("Connected");
});

socket.on('disconnect', function(){
	console.log("Disconnected");
});

function confirmAction(action, eventId) {
	socket.emit('lex-confirm', {
		action: action,
		eventId: eventId
	});
}

function pulsePin(pin, duration) {
	var pulseDuration = 500;
	if(typeof(duration) !== 'undefined') {
		pulseDuration = duration;
	}
	rpio.write(pin, rpio.HIGH);
	rpio.msleep(pulseDuration);
	rpio.write(pin, rpio.LOW);
}

var commandHistory = {};

socket.on('lex-command', function incoming(message) {
    console.log('GPIO Command: %s', message);

	commandHistory[message] ? commandHistory[message]+=1 : commandHistory[message] = 1;

    if(message === "remote-start:engine:on" || message === "remote-start:engine:off") {
        pulsePin(PIN_REMOTE_START);
		confirmAction(message, commandHistory[message]);
	}

    if(message === "remote-start:security:unlock") {
        pulsePin(PIN_UNLOCK);
		confirmAction(message, commandHistory[message]);
	}

    if(message === "remote-start:security:lock") {
        pulsePin(18);
		confirmAction(message, commandHistory[message]);
	}

});
<|endoftext|>


<commit_before>/**
 * Licensed under the Apache License, Version 2.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.apache.org/licenses/LICENSE-2.0
 *
 * 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.
 */

goog.provide('org.apache.flex.jquery.ToggleTextButton');

goog.require('org.apache.flex.html.Button');

/**
 * @constructor
 * @extends {org.apache.flex.html.Button}
 */
org.apache.flex.jquery.ToggleTextButton = function() {
  org.apache.flex.jquery.ToggleTextButton.base(this, 'constructor');

  /**
   * @private
   * @type {boolean}
   */
  this.selected_ = false;
};
goog.inherits(org.apache.flex.jquery.ToggleTextButton,
    org.apache.flex.html.Button);

/**
 * Metadata
 *
 * @type {Object.<string, Array.<Object>>}
 */
org.apache.flex.jquery.ToggleTextButton.prototype.FLEXJS_CLASS_INFO =
    { names: [{ name: 'ToggleTextButton',
                qName: 'org.apache.flex.jquery.ToggleTextButton'}] };

/**
 * @expose
 * Used to provide ids to the ToggleTextButton.
 */
org.apache.flex.jquery.ToggleTextButton.toggleCounter = 0;

/**
 * @override
 */
org.apache.flex.jquery.ToggleTextButton.prototype.createElement =
    function() {

  // the radio itself
  this.input = document.createElement('input');
  this.input.type = 'checkbox';
  this.input.name = 'checkbox';
  this.input.id = '_toggle_' + org.apache.flex.jquery.ToggleTextButton.toggleCounter++;

  this.labelFor = document.createElement('label');
  this.labelFor.htmlFor = this.input.id;

  this.positioner = document.createElement('div');
  this.positioner.appendChild(this.input);
  this.positioner.appendChild(this.labelFor);
  this.element = this.input;

  this.input.flexjs_wrapper = this;
  this.labelFor.flexjs_wrapper = this;
  this.positioner.flexjs_wrapper = this;

  return this.element;
};

/**
 * @override
 */
org.apache.flex.jquery.ToggleTextButton.prototype.addedToParent =
    function() {
  org.apache.flex.jquery.ToggleTextButton.base(this, 'addedToParent');
  $(this.element).button();
};

/**
 * @expose
 * @return {string} The text getter.
 */
org.apache.flex.jquery.ToggleTextButton.prototype.get_text = function() {
  return this.labelFor.innerHTML;
};

/**
 * @expose
 * @param {string} value The text setter.
 */
org.apache.flex.jquery.ToggleTextButton.prototype.set_text =
    function(value) {
  this.labelFor.innerHTML = value;
};

/**
 * @expose
 * @return {boolean} The selected getter.
 */
org.apache.flex.jquery.ToggleTextButton.prototype.get_selected =
    function() {
  return this.input.selected_;
};

/**
 * @expose
 * @param {boolean} value The selected setter.
 */
org.apache.flex.jquery.ToggleTextButton.prototype.set_selected =
    function(value) {
  if (this.input.selected_ != value) {
    this.inputselected_ = value;
/*
    var className = this.className;
    if (value) {
      if (className.indexOf(this.SELECTED) == className.length - this.SELECTED.length)
        this.set_className(className.substring(0, className.length - this.SELECTED.length));
    }
    else {
      if (className.indexOf(this.SELECTED) == -1)
        this.set_className(className + this.SELECTED);
    }
*/
  }
};

/**
 * @type {string} The selected setter.
 */
org.apache.flex.jquery.ToggleTextButton.prototype.SELECTED = '_Selected';

<commit_msg>ToggleButton overrides set_id to set the id on its children.<commit_after>/**
 * Licensed under the Apache License, Version 2.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.apache.org/licenses/LICENSE-2.0
 *
 * 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.
 */

goog.provide('org.apache.flex.jquery.ToggleTextButton');

goog.require('org.apache.flex.html.Button');

/**
 * @constructor
 * @extends {org.apache.flex.html.Button}
 */
org.apache.flex.jquery.ToggleTextButton = function() {
  org.apache.flex.jquery.ToggleTextButton.base(this, 'constructor');

  /**
   * @private
   * @type {boolean}
   */
  this.selected_ = false;
};
goog.inherits(org.apache.flex.jquery.ToggleTextButton,
    org.apache.flex.html.Button);

/**
 * Metadata
 *
 * @type {Object.<string, Array.<Object>>}
 */
org.apache.flex.jquery.ToggleTextButton.prototype.FLEXJS_CLASS_INFO =
    { names: [{ name: 'ToggleTextButton',
                qName: 'org.apache.flex.jquery.ToggleTextButton'}] };

/**
 * @expose
 * Used to provide ids to the ToggleTextButton.
 */
org.apache.flex.jquery.ToggleTextButton.toggleCounter = 0;

/**
 * @override
 */
org.apache.flex.jquery.ToggleTextButton.prototype.createElement =
    function() {

  // the radio itself
  this.input = document.createElement('input');
  this.input.type = 'checkbox';
  this.input.name = 'checkbox';
  this.input.id = '_toggle_' + org.apache.flex.jquery.ToggleTextButton.toggleCounter++;

  this.labelFor = document.createElement('label');
  this.labelFor.htmlFor = this.input.id;

  this.positioner = document.createElement('div');
  this.positioner.appendChild(this.input);
  this.positioner.appendChild(this.labelFor);
  this.element = this.input;

  this.input.flexjs_wrapper = this;
  this.labelFor.flexjs_wrapper = this;
  this.positioner.flexjs_wrapper = this;

  return this.element;
};

/**
 * @override
 */
org.apache.flex.jquery.ToggleTextButton.prototype.addedToParent =
    function() {
  org.apache.flex.jquery.ToggleTextButton.base(this, 'addedToParent');
  $(this.element).button();
};

/**
 * @override
 */
org.apache.flex.jquery.ToggleTextButton.prototype.set_id = function(value) {
  org.apache.flex.jquery.ToggleTextButton.base(this, 'set_id', value);
  this.labelFor.id = value;
  this.labelFor.htmlFor = value;
};

/**
 * @expose
 * @return {string} The text getter.
 */
org.apache.flex.jquery.ToggleTextButton.prototype.get_text = function() {
  return this.labelFor.innerHTML;
};

/**
 * @expose
 * @param {string} value The text setter.
 */
org.apache.flex.jquery.ToggleTextButton.prototype.set_text =
    function(value) {
  this.labelFor.innerHTML = value;
};

/**
 * @expose
 * @return {boolean} The selected getter.
 */
org.apache.flex.jquery.ToggleTextButton.prototype.get_selected =
    function() {
  return this.input.selected_;
};

/**
 * @expose
 * @param {boolean} value The selected setter.
 */
org.apache.flex.jquery.ToggleTextButton.prototype.set_selected =
    function(value) {
  if (this.input.selected_ != value) {
    this.inputselected_ = value;
/*
    var className = this.className;
    if (value) {
      if (className.indexOf(this.SELECTED) == className.length - this.SELECTED.length)
        this.set_className(className.substring(0, className.length - this.SELECTED.length));
    }
    else {
      if (className.indexOf(this.SELECTED) == -1)
        this.set_className(className + this.SELECTED);
    }
*/
  }
};

/**
 * @type {string} The selected setter.
 */
org.apache.flex.jquery.ToggleTextButton.prototype.SELECTED = '_Selected';

<|endoftext|>