<commit_before>/**
 * Copyright 2015 Longtail Ad Solutions Inc.
 *
 * 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.
 **/

(function () {

    angular
        .module('jwShowcase.core')
        .directive('jwCardMenu', cardMenuDirective);

    /**
     * @ngdoc directive
     * @name jwShowcase.core.directive:jwCardMenu
     * @module jwShowcase.core
     *
     * @scope
     *
     * @param {jwShowcase.core.item}   item     Playlist item.
     * @param {function}               onClose  Callback which is called after the user clicks on the close button.
     *
     * @example
     *
     * ```
     * <jw-card-menu item="item" on-close="onClose()"></jw-card-menu>
     * ```
     */
    cardMenuDirective.$inject = [];
    function cardMenuDirective () {

        return {
            scope:            {
                item:    '='
            },
            require:          '^jwCard',
            controllerAs:     'vm',
            controller:       'CardMenuController',
            bindToController: true,
            replace:          true,
            templateUrl:      'views/core/cardMenu.html',
            link:             link
        };

        function link (scope, element, attr, jwCard) {

            var parents = ionic.DomUtil.getParentOrSelfWithClass,
                pane;

            scope.vm.jwCard = jwCard;

            activate();

            ////////

            /**
             * Initialize directive
             */
            function activate () {

                pane = parents(element[0], 'pane');

                if (pane) {
                    angular.element(pane).on('click', onClickOutside);
                    scope.$on('$destroy', onDestroy);
                }
            }

            /**
             * Handle directive's $destroy event
             */
            function onDestroy () {

                if (pane) {
                    angular.element(pane).off('click', onClickOutside);
                }
            }

            /**
             * Handle click event outside cardMenu
             * @param {Event} evt
             */
            function onClickOutside (evt) {

                // clicked inside card, don't close
                if (parents(evt.target, 'jw-card')) {
                    return;
                }

                scope.$apply(function () {
                    jwCard.closeMenu();
                });

                evt.preventDefault();
            }
        }
    }

}());
<commit_msg>Improve cardMenu onClickOutside<commit_after>/**
 * Copyright 2015 Longtail Ad Solutions Inc.
 *
 * 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.
 **/

(function () {

    angular
        .module('jwShowcase.core')
        .directive('jwCardMenu', cardMenuDirective);

    /**
     * @ngdoc directive
     * @name jwShowcase.core.directive:jwCardMenu
     * @module jwShowcase.core
     *
     * @scope
     *
     * @param {jwShowcase.core.item}   item     Playlist item.
     * @param {function}               onClose  Callback which is called after the user clicks on the close button.
     *
     * @example
     *
     * ```
     * <jw-card-menu item="item" on-close="onClose()"></jw-card-menu>
     * ```
     */
    cardMenuDirective.$inject = [];
    function cardMenuDirective () {

        return {
            scope:            {
                item:    '='
            },
            require:          '^jwCard',
            controllerAs:     'vm',
            controller:       'CardMenuController',
            bindToController: true,
            replace:          true,
            templateUrl:      'views/core/cardMenu.html',
            link:             link
        };

        function link (scope, element, attr, jwCard) {

            var parents = ionic.DomUtil.getParentOrSelfWithClass,
                pane;

            scope.vm.jwCard = jwCard;

            activate();

            ////////

            /**
             * Initialize directive
             */
            function activate () {

                pane = parents(element[0], 'pane');

                if (pane) {
                    angular.element(pane).on('click', onClickOutside);
                    scope.$on('$destroy', onDestroy);
                }
            }

            /**
             * Handle directive's $destroy event
             */
            function onDestroy () {

                if (pane) {
                    angular.element(pane).off('click', onClickOutside);
                }
            }

            /**
             * Handle click event outside cardMenu
             * @param {Event} evt
             */
            function onClickOutside (evt) {

                var node = evt.target;

                do {
                    if (node === element[0]) {
                        return;
                    }
                }
                while(node = node.parentNode);

                scope.$apply(function () {
                    jwCard.closeMenu();
                });

                evt.preventDefault();
            }
        }
    }

}());
<|endoftext|>


<commit_before>'use strict';

angular.module('owners').controller('FinalViewController', ['$scope', '$stateParams', '$location', 'Authentication', 'Owners', '$http', 'socket', 'Bids', 'Histories',
function($scope, $stateParams, $location, Authentication, Owners, $http, socket, Bids, Histories ) {
    $scope.init=function(){
        /*******
        INITIALIZE VALUES
        ******/
        $scope.authentication = Authentication;
        $scope.history=[];

        /******
        GET ALL DATA
        ******/
		// Find a list of Owners
        $http.get('/draftList').
            success(function(data, status){
                $scope.owners=data;
                //get the end rank of the selected owner - for sorting
                $scope.endRank=function(selectedOwner){
                  return selectedOwner.rank[0];
                };
                $scope.displayOwner=$scope.owners[0];
            });
  		// Find History
        $scope.checkId='';
        $http.get('/histories').
            success(function(data, status){
                for(var x=0; x<data.length;x++){
                    if(data[x].player._id!==$scope.checkId){
                        $scope.history.push(data[x]);
                        $scope.checkId===data[x].player._id;
                        console.log($scope.checkId);
                    }
                }
                console.log(data);
//                $scope.history=data;
            });
    };//end initi function
    $scope.init();

    $scope.changeUser=function(owner){
        $scope.displayOwner=owner;
    };

    /*******
    FOR SORTING
    ******/

    $scope.ownerPositionList=function(position){
        if(position.name==='QB'){
            return 1;
        }
        else if(position.name==='WR'){
            return 2;
        }
        else if(position.name==='RB'){
            return 3;
        }
        else if(position.name==='TE'){
            return 4;
        }
        else if(position.name==='K'){
            return 5;
        }
        else{
            return 6;
        }
    };

	}
]);<commit_msg>fix checkid<commit_after>'use strict';

angular.module('owners').controller('FinalViewController', ['$scope', '$stateParams', '$location', 'Authentication', 'Owners', '$http', 'socket', 'Bids', 'Histories',
function($scope, $stateParams, $location, Authentication, Owners, $http, socket, Bids, Histories ) {
    $scope.init=function(){
        /*******
        INITIALIZE VALUES
        ******/
        $scope.authentication = Authentication;
        $scope.history=[];

        /******
        GET ALL DATA
        ******/
		// Find a list of Owners
        $http.get('/draftList').
            success(function(data, status){
                $scope.owners=data;
                //get the end rank of the selected owner - for sorting
                $scope.endRank=function(selectedOwner){
                  return selectedOwner.rank[0];
                };
                $scope.displayOwner=$scope.owners[0];
            });
  		// Find History
        $scope.checkId='';
        $http.get('/histories').
            success(function(data, status){
                for(var x=0; x<data.length;x++){
                    if(data[x].player._id!==$scope.checkId){
                        $scope.history.push(data[x]);
                        $scope.checkId=data[x].player._id;
                        console.log($scope.checkId);
                    }
                }
                console.log(data);
//                $scope.history=data;
            });
    };//end initi function
    $scope.init();

    $scope.changeUser=function(owner){
        $scope.displayOwner=owner;
    };

    /*******
    FOR SORTING
    ******/

    $scope.ownerPositionList=function(position){
        if(position.name==='QB'){
            return 1;
        }
        else if(position.name==='WR'){
            return 2;
        }
        else if(position.name==='RB'){
            return 3;
        }
        else if(position.name==='TE'){
            return 4;
        }
        else if(position.name==='K'){
            return 5;
        }
        else{
            return 6;
        }
    };

	}
]);<|endoftext|>


<commit_before>//Nodig voor autoincrement
var selectedcourseid;
var worksheets = [];
var worksheetsid = [];

//viewmodel for the assess page
function pageViewModel(gvm) {
    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. __("AssessTitle2");}, gvm);
    gvm.userId = -1;

    // Page specific i18n bindings
    gvm.pageHeader = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AssessTitle2");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName");}, gvm);
    gvm.homeManual = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("HomeRapportManual");}, gvm);
    gvm.foundProjects = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("FoundProjects");}, gvm);
    gvm.selectCourse = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SelectCourse");}, gvm);

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

    // Table i18n bindings
    gvm.werkficheID = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("werkficheID");}, gvm);
    gvm.werkficheName = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("werkficheName");}, gvm);
    gvm.werkficheDate = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("werkficheDate");}, gvm);
    gvm.werkficheAction = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("werkficheAction");}, gvm);

    gvm.availableCourses = ko.observableArray([]);
    gvm.availableStudentlists = ko.observableArray([]);
    gvm.availableStudents = ko.observableArray([]);

    gvm.currentCourseId = null;
    gvm.currentStudentlistId = null;
    gvm.currentStudentId = null;

    gvm.updateDropdowns = function() {
        $.getJSON('api/lastdropdownrapporten/' + gvm.userId, function(data) {
            if(!$.isEmptyObject(data)) {
                $.each(data, function(i, item) {
                    $(".btn-courseRapport span:first").text(item.course);
                    $(".btn-studentlist span:first").text(item.studentlist);
                    $('.btn-student span:first').text(item.student);
                    gvm.currentCourseId = item.courseid;
                    selectedcourseid = item.courseid;
                    gvm.currentStudentlistId = item.studentlistid;
                    gvm.currentStudentId = item.studentid;
                    gvm.updateCourseRapport();
                    loadTablePage(item.courseid, 1);
                });
            } else {
                gvm.updateCourseRapport();
            }
        });
    }

    //Houdt bij wat geselecteerd wordt
    //Wordt opgeroepen bij iedere wijziging (niet ingevulde velden = NULL)
    gvm.saveLastSelectedDropdowns = function() {
        data = {};
        data["user"] = gvm.userId;
        data["course"] = $(".btn-courseRapport span:first").text();
        data["courseid"] = gvm.currentCourseId;
        data["studentlist"] = $('.btn-studentlist span:first').text();
        data["studentlistid"] = gvm.currentStudentlistId;
        data["student"] = $(".btn-student span:first").text();
        data["studentid"] = gvm.currentStudentId;
        console.log(data);
        $.ajax({
            type: "POST",
            url: "/api/savedropdownsRapport",
            data: data,
            success: function() {
                console.log("success");
            }
        })
    }

    gvm.updateCourseRapport = function() {
        $.getJSON('/api/coursefromteacher/' + gvm.userId, function(data) {
            console.log(gvm.userId);
            gvm.availableCourses.removeAll();
            $.each(data, function(i, item) {
                //  Put item in list
                gvm.availableCourses.push(item);

                // Add listener to listitem
                $("#coursebtn-" + item.id).click(function(){
                    gvm.currentCourseId = item.id;
                    selectedcourseid = item.id;
                    gvm.currentStudentlistId = null;
                    gvm.currentStudentId = null;
                    gvm.updateStudentlists(item.id, gvm.userId);
                    $(".btn-courseRapport span:first").text($(this).text());
                    $(".btn-studentlist span:first").text("Studentlist");
                    $('.btn-student span:first').text("Student");
                    gvm.saveLastSelectedDropdowns();
                });
            });
        });
    };

    /*
     * Update the student data
     */
    gvm.updateStudentlists = function(cid, uid) {
        //get all studentlists
        $.getJSON('api/studentlistdrop/' + cid + '/' + uid, function(data) {
            gvm.availableStudentlists.removeAll();
            $.each(data, function(i,item) {
                // Put item in list
                gvm.availableStudentlists.push(item);

                // Add listener to listitem
                $("#studentlistbtn-" + item.id).click(function(){
                    gvm.currentStudentlistId = item.id;
                    gvm.currentStudentId = null;
                    gvm.updateStudents(item.id);
                    $(".btn-studentlist span:first").text($(this).text());
                    $('.btn-student span:first').text("Student");
                    gvm.saveLastSelectedDropdowns();
                });
            })
        })
    }

    /*
     * Update the student data
     */
    gvm.updateStudents = function(id) {
        //get all students who follow that course
        $.getJSON('api/studentdrop/' + id, function(data) {
            gvm.availableStudents.removeAll();
            $.each(data, function(i,item) {
                // Put item in list
                gvm.availableStudents.push(item);

                // Add listener to listitem
                $("#studentbtn-" + item.id).click(function(){
                    gvm.currentStudentId = item.id;
                    $(".btn-student span:first").text($(this).text());
                    gvm.saveLastSelectedDropdowns();
                });
            })
        })
    }

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

    // Add data to the table
    gvm.addTableData = function(id, name, lastname, mail, score) {
        // Push data
        var tblOject = {tstudid: id, tname: name, tlname: lastname, tmail: mail, tscore: score};
        gvm.tabledata.push(tblOject);
    }

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    }
}

function getAllWorksheets() {
    worksheets = [];
    worksheetsid = [];
    $.getJSON('/api/worksheets/' + selectedcourseid, function(data) {
        $.each(data, function(i, item) {
            worksheets.push(item.Name);
            worksheetsid.push(item.id);
        });
    });
    return worksheets;
}

function getWorksheetid() {
    var i = 0;
    var worksheet = 0;
    worksheets.forEach(function(entry) {
        console.log(worksheetsid[i]);
        if (new String(entry).valueOf() == new String($('#worksheetComplete').val()).valueOf()) {
            worksheet = worksheetsid[i];
            console.log("hier " + worksheet);
        }
        i+= 1;
    });
    return worksheet;
}

function addWorksheet() {
    /*
    $.ajax({
        url: "/api/coursecouple/" + courseid + "/" + studlijstid + "/" + teacherid,
        type: "POST",
        data: {'course': courseid, 'teacher': teacherid, 'studentlist': teacherid},
        success: function(data) {
            //callback(true);
        },
        error: function(data) {
            console.log('Failed to add new student');
            //callback(false);
        }
    });
    */
}

function loadTablePage(pagenr)
{
    $.getJSON('/api/worksheets/page/' + pagenr, function(data){

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

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

        /* 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);
                });
            }
        });
    });
}

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

    $('#addGroupForm').hide();

    $('#addWorksheetBtn').click(function() {
        $("#addGroupForm").show();
        $('#worksheetComplete').autocomplete({ source: getAllWorksheets() });
    });

    $('#addNewWorksheetBtn').click(function() {
        console.log("toevoegen van "+ getWorksheetid($('#worksheetComplete').val()));
        addWorksheet();

        //table
        loadTablePage(1);

        //Indien gewenst toevoegformulier weer verbergen.
        $('#worksheetComplete').val("");
        $('#addGroupForm').hide();
    });
}<commit_msg>Make it possible to add worksheets for a specific course.<commit_after>//Nodig voor autoincrement
var selectedcourseid;
var worksheets = [];
var worksheetsid = [];

//viewmodel for the assess page
function pageViewModel(gvm) {
    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. __("AssessTitle2");}, gvm);
    gvm.userId = -1;

    // Page specific i18n bindings
    gvm.pageHeader = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AssessTitle2");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName");}, gvm);
    gvm.homeManual = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("HomeRapportManual");}, gvm);
    gvm.foundProjects = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("FoundProjects");}, gvm);
    gvm.selectCourse = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SelectCourse");}, gvm);

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

    // Table i18n bindings
    gvm.werkficheID = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("werkficheID");}, gvm);
    gvm.werkficheName = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("werkficheName");}, gvm);
    gvm.werkficheDate = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("werkficheDate");}, gvm);
    gvm.werkficheAction = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("werkficheAction");}, gvm);

    gvm.availableCourses = ko.observableArray([]);
    gvm.availableStudentlists = ko.observableArray([]);
    gvm.availableStudents = ko.observableArray([]);

    gvm.currentCourseId = null;
    gvm.currentStudentlistId = null;
    gvm.currentStudentId = null;

    gvm.updateDropdowns = function() {
        $.getJSON('api/lastdropdownrapporten/' + gvm.userId, function(data) {
            if(!$.isEmptyObject(data)) {
                $.each(data, function(i, item) {
                    $(".btn-courseRapport span:first").text(item.course);
                    $(".btn-studentlist span:first").text(item.studentlist);
                    $('.btn-student span:first').text(item.student);
                    gvm.currentCourseId = item.courseid;
                    selectedcourseid = item.courseid;
                    gvm.currentStudentlistId = item.studentlistid;
                    gvm.currentStudentId = item.studentid;
                    gvm.updateCourseRapport();
                    loadTablePage(item.courseid, 1);
                });
            } else {
                gvm.updateCourseRapport();
            }
        });
    }

    //Houdt bij wat geselecteerd wordt
    //Wordt opgeroepen bij iedere wijziging (niet ingevulde velden = NULL)
    gvm.saveLastSelectedDropdowns = function() {
        data = {};
        data["user"] = gvm.userId;
        data["course"] = $(".btn-courseRapport span:first").text();
        data["courseid"] = gvm.currentCourseId;
        data["studentlist"] = $('.btn-studentlist span:first').text();
        data["studentlistid"] = gvm.currentStudentlistId;
        data["student"] = $(".btn-student span:first").text();
        data["studentid"] = gvm.currentStudentId;
        console.log(data);
        $.ajax({
            type: "POST",
            url: "/api/savedropdownsRapport",
            data: data,
            success: function() {
                console.log("success");
            }
        })
    }

    gvm.updateCourseRapport = function() {
        $.getJSON('/api/coursefromteacher/' + gvm.userId, function(data) {
            console.log(gvm.userId);
            gvm.availableCourses.removeAll();
            $.each(data, function(i, item) {
                //  Put item in list
                gvm.availableCourses.push(item);

                // Add listener to listitem
                $("#coursebtn-" + item.id).click(function(){
                    gvm.currentCourseId = item.id;
                    selectedcourseid = item.id;
                    gvm.currentStudentlistId = null;
                    gvm.currentStudentId = null;
                    gvm.updateStudentlists(item.id, gvm.userId);
                    $(".btn-courseRapport span:first").text($(this).text());
                    $(".btn-studentlist span:first").text("Studentlist");
                    $('.btn-student span:first').text("Student");
                    gvm.saveLastSelectedDropdowns();
                });
            });
        });
    };

    /*
     * Update the student data
     */
    gvm.updateStudentlists = function(cid, uid) {
        //get all studentlists
        $.getJSON('api/studentlistdrop/' + cid + '/' + uid, function(data) {
            gvm.availableStudentlists.removeAll();
            $.each(data, function(i,item) {
                // Put item in list
                gvm.availableStudentlists.push(item);

                // Add listener to listitem
                $("#studentlistbtn-" + item.id).click(function(){
                    gvm.currentStudentlistId = item.id;
                    gvm.currentStudentId = null;
                    gvm.updateStudents(item.id);
                    $(".btn-studentlist span:first").text($(this).text());
                    $('.btn-student span:first').text("Student");
                    gvm.saveLastSelectedDropdowns();
                });
            })
        })
    }

    /*
     * Update the student data
     */
    gvm.updateStudents = function(id) {
        //get all students who follow that course
        $.getJSON('api/studentdrop/' + id, function(data) {
            gvm.availableStudents.removeAll();
            $.each(data, function(i,item) {
                // Put item in list
                gvm.availableStudents.push(item);

                // Add listener to listitem
                $("#studentbtn-" + item.id).click(function(){
                    gvm.currentStudentId = item.id;
                    $(".btn-student span:first").text($(this).text());
                    gvm.saveLastSelectedDropdowns();
                });
            })
        })
    }

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

    // Add data to the table
    gvm.addTableData = function(id, name, lastname, mail, score) {
        // Push data
        var tblOject = {tstudid: id, tname: name, tlname: lastname, tmail: mail, tscore: score};
        gvm.tabledata.push(tblOject);
    }

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    }
}

function getAllWorksheets() {
    worksheets = [];
    worksheetsid = [];
    $.getJSON('/api/worksheets/' + selectedcourseid, function(data) {
        $.each(data, function(i, item) {
            worksheets.push(item.Name);
            worksheetsid.push(item.id);
        });
    });
    return worksheets;
}

function getWorksheetid() {
    var i = 0;
    var worksheet = 0;
    worksheets.forEach(function(entry) {
        if (new String(entry).valueOf() == new String($('#worksheetComplete').val()).valueOf()) {
            worksheet = worksheetsid[i];
        }
        i+= 1;
    });
    return worksheet;
}

function addWorksheet($worksheetid) {
    console.log("toe te voegenworksheet " + worksheetsid)
    /*
    $.ajax({
        url: "/api/coursecouple/" + courseid + "/" + studlijstid + "/" + teacherid,
        type: "POST",
        data: {'course': courseid, 'teacher': teacherid, 'studentlist': teacherid},
        success: function(data) {
            //callback(true);
        },
        error: function(data) {
            console.log('Failed to add new student');
            //callback(false);
        }
    });
    */
}

function loadTablePage(pagenr)
{
    $.getJSON('/api/worksheets/page/' + pagenr, function(data){

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

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

        /* 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);
                });
            }
        });
    });
}

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

    $('#addGroupForm').hide();

    $('#addWorksheetBtn').click(function() {
        $("#addGroupForm").show();
        $('#worksheetComplete').autocomplete({ source: getAllWorksheets() });
    });

    $('#addNewWorksheetBtn').click(function() {
        addWorksheet(getWorksheetid($('#worksheetComplete').val()));

        //table opnieuw laden
        loadTablePage(1);

        //Indien gewenst toevoegformulier weer verbergen.
        $('#worksheetComplete').val("");
        $('#addGroupForm').hide();
    });
}<|endoftext|>


<commit_before>var breakpoint = 1000;

jQuery(document).ready(function($) {

    initForWindow();

    $('.camera').hover(function () {
        var target = null;
        var selected = $(this);

        selected.toggleClass('highlighted');
        target = selected.closest($('.overlay'));

        target.find($('.feature-text')).fadeToggle();
        target.find($('.feature-image-overlay')).fadeToggle();

    });

    $('.template-article-page .fa-camera').hover(function(){
        $('.feature-text').fadeToggle();
        $('.feature-image-overlay').fadeToggle();
    });

    //scroll down arrow
    $('a[href*=#]:not([href=#])').click(function () {
        if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
            if($(this).attr('href') == '#features'){
                var target = $(this.hash);
                target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');

                var bannerHeight = $('header').height();
                var scrollDestination = target.offset().top - bannerHeight;
                if (target.length) {
                    $('html,body').animate({
                        scrollTop: scrollDestination
                    }, 1000);
                    return false;
                }
            }
        }
    });

    $('.search-form input[type=text]').keydown(function() {
        if($(this).val() != ''){
            $('.clear-button').show();
        }
    });
    $('.clear-button').click(function(){
        $('.search-form input[type=text]').val('');
        $('.clear-button').hide();
        $('#search-box input').focus();
    });

    if ($(".facebook-share-link").length > 0){
        social_setup();
    }

});

//initialize window based on width and height
function initForWindow(){

    var windowHeight = $(window).height();
    var windowWidth = $(window).width();
    var articleTitleWidth = $('article').width() - 0.2*($('article').width());

    if(($('body').hasClass('template-home-page')) || ($('body').hasClass('template-article-page') && $('.jumbotron').length)){
        setFeatureHeight(windowHeight);
    }
    if($('.template-article-page').length && $('.jumbotron').length) {
        if(windowWidth > breakpoint) {
            var height = $('.jumbotron').height() + 100;
            $('ul.share-links').css('top', height + 'px');
        }
        else{
            $('ul.share-links').css('top', '10px');
        }
    }

    setOverlayForWindow(windowWidth);
    toggleHeading(windowWidth, articleTitleWidth);
    setBodyPadding();

    $('html').on('touchstart click', function (e) {
        toggleBox(e);
    });

}

//toggle menu in mobile/small window width view
function toggleBox(e){
    var selected = $(e.target);
    var target = null;
    var menu = $('#main-menu');
    var search = $('#search-box');

    if(selected.closest('button').data('target') == 'main-menu'){
        target = menu;
    }
    else if (selected.closest('button').data('target') == 'search-box') {
        target = search;
    }

    if(target != null){
        if(target == menu){
            if(!(menu.hasClass('open'))){
                if(search.hasClass('open')){
                    search.removeClass('open');
                }

                menu.show( function() {
                    menu.addClass('open');
                });
            }
        }
        if(target == search ){
            if(!(search.hasClass('open'))){
                if(menu.hasClass('open')){
                    menu.removeClass('open');
                }
               search.addClass('open');
                $('#search-box input').focus();
            }
            else{
                search.removeClass('open');
            }
        }
    }
    else{

        if((menu.hasClass('open')) && (!(selected.closest('nav').length))){
            menu.removeClass('open');
        }
        if((search.hasClass('open')) && (!(selected.closest("#search-box").length))){
            search.removeClass('open');
        }
    }

}

//set the Homepage Feature height based on window height
function setFeatureHeight(windowHeight){
    var bannerHeight = $('header').height();
    var gap = 0.05*windowHeight;
    var featureHeight = windowHeight - bannerHeight - gap;

    $('.jumbotron.main-feature').css("height", featureHeight + "px");
}

//set the body padding based on banner height
function setBodyPadding(){
    var bannerHeight = $('header').height();
    $('body').css("padding-top", bannerHeight + "px");
    $('#search-box').css("top", bannerHeight = "px");

}

function setOverlayForWindow(windowWidth){
    if(windowWidth <= breakpoint){
        var overlayFeatures = $('#features').find('.rowheight-2');
        overlayFeatures.each(function(index){
            overlayHeight = $(this).css("height");
            overlayHeight = parseInt(overlayHeight.slice(0, -2));
            $(this).css("height", "280px");
        });
    }
    if(windowWidth > breakpoint){
        var overlayFeatures = $('#features').find('.rowheight-2');
        overlayFeatures.each(function(index){
            if($(this).css("height") == '280px'){
                $(this).css("height", "560px");
            }

        });
    }

}

//toggle Banner heading based on window width and page type∂
function toggleHeading(windowWidth, articleTitleWidth){

    var offset = $('header').height();

    function fullHeader(){
        $('header').removeClass('collapsed');
        $('#search-box').removeClass('small-header');
        $('.toggle-mobile').hide();
        $('nav').removeClass('mobile-menu open');
        $('body').removeClass('article-scroll');

        if($('.template-home-page').length){
            $('.tagline').show();
        }
    }

    function collapsedHeader(){

        $('header').addClass('collapsed');
        $('#search-box').addClass('small-header');
        $('.toggle-mobile').show();

        $('nav').addClass('mobile-menu');
        if($('#article-page').length  && $('body').hasClass('article-scroll')  && windowWidth <= breakpoint){
            $('body').removeClass('article-scroll');
        }
        if($('.template-home-page').length){
            $('.tagline').hide();
        }
    }

    function fullScroll(){
        $('header').toggleClass('collapsed scrolled', $(document).scrollTop() > offset);

        if($('header').hasClass('collapsed')){

            $('#main-menu').hide();
            collapsedHeader();

            if($('#article-page').length ){
                $('body').addClass('article-scroll');
            }
        }
        else{
            $('#main-menu').show();
            fullHeader();
        }
    }

    function collapsedScroll(){
        collapsedHeader();
        $('header').toggleClass('scrolled', $(document).scrollTop() > offset);
    }

    if(windowWidth >= breakpoint){

        if($('body').hasClass('small-article')){
            $('body').removeClass('small-article');
        }

        if($(document).scrollTop() > offset){
           if($('#article-page').length){
                $('body').addClass('article-scroll');
            }
            collapsedHeader();
        }
        else{
            fullHeader();
        }

        $(window).off("scroll touchmove", collapsedScroll );
        $(window).on("scroll touchmove", fullScroll );
    }
    else{

        if($('#article-page').length && $('body').hasClass('article-scroll')){
            $('body').removeClass('article-scroll');
        }
        if($('#article-page').length){
            $('body').addClass('small-article');
        }
        collapsedHeader();

        $(window).off("scroll touchmove", fullScroll );
        $(window).on("scroll touchmove", collapsedScroll );

    }
}

$(window).resize(function(){
    initForWindow();
});

function social_setup(){
  window.fbAsyncInit = function() {
    FB.init({
      appId      : '1209700165722055',
      xfbml      : true,
      version    : 'v2.4'
    });
  };

  (function(d, s, id){
     var js, fjs = d.getElementsByTagName(s)[0];
     if (d.getElementById(id)) {return;}
     js = d.createElement(s); js.id = id;
     js.src = "//connect.facebook.net/en_US/sdk.js";
     fjs.parentNode.insertBefore(js, fjs);
   }(document, 'script', 'facebook-jssdk'));

  $(".facebook-share-link").click(function(){
    var href = $(this).data('url');
    FB.ui(
      {
      method: 'share',
      href: href
    }, function(response){});
    });
}
<commit_msg>OCW-342 #comment added column resize for article titles back in<commit_after>var breakpoint = 1000;

jQuery(document).ready(function($) {

    initForWindow();

    $('.camera').hover(function () {
        var target = null;
        var selected = $(this);

        selected.toggleClass('highlighted');
        target = selected.closest($('.overlay'));

        target.find($('.feature-text')).fadeToggle();
        target.find($('.feature-image-overlay')).fadeToggle();

    });

    $('.template-article-page .fa-camera').hover(function(){
        $('.feature-text').fadeToggle();
        $('.feature-image-overlay').fadeToggle();
    });

    //scroll down arrow
    $('a[href*=#]:not([href=#])').click(function () {
        if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
            if($(this).attr('href') == '#features'){
                var target = $(this.hash);
                target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');

                var bannerHeight = $('header').height();
                var scrollDestination = target.offset().top - bannerHeight;
                if (target.length) {
                    $('html,body').animate({
                        scrollTop: scrollDestination
                    }, 1000);
                    return false;
                }
            }
        }
    });

    $('.search-form input[type=text]').keydown(function() {
        if($(this).val() != ''){
            $('.clear-button').show();
        }
    });
    $('.clear-button').click(function(){
        $('.search-form input[type=text]').val('');
        $('.clear-button').hide();
        $('#search-box input').focus();
    });

    if ($(".facebook-share-link").length > 0){
        social_setup();
    }

});

//initialize window based on width and height
function initForWindow(){

    var windowHeight = $(window).height();
    var windowWidth = $(window).width();
    var articleTitleWidth = $('article').width() - 0.2*($('article').width());

    if(($('body').hasClass('template-home-page')) || ($('body').hasClass('template-article-page') && $('.jumbotron').length)){
        setFeatureHeight(windowHeight);
    }
    if($('.template-article-page').length && $('.jumbotron').length) {
        if(windowWidth > breakpoint) {
            var height = $('.jumbotron').height() + 100;
            $('ul.share-links').css('top', height + 'px');
        }
        else{
            $('ul.share-links').css('top', '10px');
        }
    }

    setOverlayForWindow(windowWidth);
    toggleHeading(windowWidth, articleTitleWidth);
    setBodyPadding();

    $('html').on('touchstart click', function (e) {
        toggleBox(e);
    });

}

//toggle menu in mobile/small window width view
function toggleBox(e){
    var selected = $(e.target);
    var target = null;
    var menu = $('#main-menu');
    var search = $('#search-box');

    if(selected.closest('button').data('target') == 'main-menu'){
        target = menu;
    }
    else if (selected.closest('button').data('target') == 'search-box') {
        target = search;
    }

    if(target != null){
        if(target == menu){
            if(!(menu.hasClass('open'))){
                if(search.hasClass('open')){
                    search.removeClass('open');
                }

                menu.show( function() {
                    menu.addClass('open');
                });
            }
        }
        if(target == search ){
            if(!(search.hasClass('open'))){
                if(menu.hasClass('open')){
                    menu.removeClass('open');
                }
               search.addClass('open');
                $('#search-box input').focus();
            }
            else{
                search.removeClass('open');
            }
        }
    }
    else{

        if((menu.hasClass('open')) && (!(selected.closest('nav').length))){
            menu.removeClass('open');
        }
        if((search.hasClass('open')) && (!(selected.closest("#search-box").length))){
            search.removeClass('open');
        }
    }

}

//set the Homepage Feature height based on window height
function setFeatureHeight(windowHeight){
    var bannerHeight = $('header').height();
    var gap = 0.05*windowHeight;
    var featureHeight = windowHeight - bannerHeight - gap;

    $('.jumbotron.main-feature').css("height", featureHeight + "px");
}

//set the body padding based on banner height
function setBodyPadding(){
    var bannerHeight = $('header').height();
    $('body').css("padding-top", bannerHeight + "px");
    $('#search-box').css("top", bannerHeight = "px");

}

function setOverlayForWindow(windowWidth){
    if(windowWidth <= breakpoint){
        var overlayFeatures = $('#features').find('.rowheight-2');
        overlayFeatures.each(function(index){
            overlayHeight = $(this).css("height");
            overlayHeight = parseInt(overlayHeight.slice(0, -2));
            $(this).css("height", "280px");
        });
    }
    if(windowWidth > breakpoint){
        var overlayFeatures = $('#features').find('.rowheight-2');
        overlayFeatures.each(function(index){
            if($(this).css("height") == '280px'){
                $(this).css("height", "560px");
            }

        });
    }

}

//toggle Banner heading based on window width and page type∂
function toggleHeading(windowWidth, articleTitleWidth){

    var offset = $('header').height();

    function fullHeader(){
        $('header').removeClass('collapsed');
        $('#search-box').removeClass('small-header');
        $('.toggle-mobile').hide();
        $('nav').removeClass('mobile-menu open');
        $('body').removeClass('article-scroll');

        if($('.template-home-page').length){
            $('.tagline').show();
        }
    }

    function collapsedHeader(){

        $('header').addClass('collapsed');
        $('#search-box').addClass('small-header');
        $('.toggle-mobile').show();

        $('nav').addClass('mobile-menu');
        if($('#article-page').length  && $('body').hasClass('article-scroll')  && windowWidth <= breakpoint){
            $('body').removeClass('article-scroll');
        }
        if($('.template-home-page').length){
            $('.tagline').hide();
        }
    }

    function fullScroll(){
        $('header').toggleClass('collapsed scrolled', $(document).scrollTop() > offset);

        if($('header').hasClass('collapsed')){
            $('#main-menu').hide();
            collapsedHeader();

            if($('#article-page').length ){
                $('body').addClass('article-scroll');
                $('header .header-row').removeClass('col-md-4');
            }
        }
        else{
            $('#main-menu').show();
            if(!($('header .header-row').hasClass('col-md-4'))){
                $('header .header-row').addClass('col-md-4');
            }
            fullHeader();

        }
    }

    function collapsedScroll(){
        collapsedHeader();
        $('header').toggleClass('scrolled', $(document).scrollTop() > offset);
    }

    if(windowWidth >= breakpoint){

        if($('body').hasClass('small-article')){
            $('body').removeClass('small-article');
        }

        if($(document).scrollTop() > offset){
           if($('#article-page').length){
                $('body').addClass('article-scroll');
            }
            collapsedHeader();
        }
        else{
            fullHeader();
        }

        $(window).off("scroll touchmove", collapsedScroll );
        $(window).on("scroll touchmove", fullScroll );
    }
    else{

        if($('#article-page').length && $('body').hasClass('article-scroll')){
            $('body').removeClass('article-scroll');
        }
        if($('#article-page').length){
            $('body').addClass('small-article');
        }
        collapsedHeader();

        $(window).off("scroll touchmove", fullScroll );
        $(window).on("scroll touchmove", collapsedScroll );

    }
}

$(window).resize(function(){
    initForWindow();
});

function social_setup(){
  window.fbAsyncInit = function() {
    FB.init({
      appId      : '1209700165722055',
      xfbml      : true,
      version    : 'v2.4'
    });
  };

  (function(d, s, id){
     var js, fjs = d.getElementsByTagName(s)[0];
     if (d.getElementById(id)) {return;}
     js = d.createElement(s); js.id = id;
     js.src = "//connect.facebook.net/en_US/sdk.js";
     fjs.parentNode.insertBefore(js, fjs);
   }(document, 'script', 'facebook-jssdk'));

  $(".facebook-share-link").click(function(){
    var href = $(this).data('url');
    FB.ui(
      {
      method: 'share',
      href: href
    }, function(response){});
    });
}
<|endoftext|>


<commit_before>//viewmodel for the assess page
function pageViewModel(gvm) {
    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. __("AssessTitle2");}, gvm);
    gvm.userId = -1;

+-    // Page specific i18n bindings
    gvm.pageHeader = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AssessTitle2");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName");}, gvm);
    gvm.homeManual = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("HomeRapportManual");}, gvm);
    gvm.foundProjects = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("FoundProjects");}, gvm);
    gvm.selectCourse = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SelectCourse");}, gvm);

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

    // Table i18n bindings
    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.actionTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ActionTableTitle");}, gvm);

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

    gvm.currentCourseId = null;
    gvm.currentLocationId = null;
    gvm.currentTrainingid = null;

    gvm.updateDropdowns = function() {
        $.getJSON('api/lastdropdownchoice/' + gvm.userId, function(data) {
            if(!$.isEmptyObject(data)) {
                $.each(data, function(i, item) {
                    $(".btn-location span:first").text(item.location);
                    $(".btn-training span:first").text(item.training);
                    $(".btn-course span:first").text(item.course);
                    gvm.currentLocationId = item.locationid;
                    gvm.currentTrainingid = item.trainingid;
                    gvm.currentCourseId = item.courseid;
                    gvm.updateLocations();
                    gvm.updateTrainings(item.locationid);
                    gvm.updateCourses(item.trainingid);
                    loadTablePage(item.courseid, 1);
                });
            } else {
                gvm.updateLocations();
            }
        });
    }

    gvm.saveLastSelectedDropdowns = function() {
        data = {};
        data["location"] = $(".btn-location span:first").text();
        data["locationid"] = gvm.currentLocationId;
        data["training"] = $(".btn-training span:first").text();
        data["trainingid"] = gvm.currentTrainingid;
        data["course"] = $(".btn-course span:first").text();
        data["courseid"] = gvm.currentCourseId;
        data["user"] = gvm.userId;
        console.log(data);
        $.ajax({
            type: "POST",
            url: "/api/savedropdowns",
            data: data,
            success: function() {
                console.log("success");
            }
        })
    }

    gvm.saveLastSelectedDropdowns = function() {
        data = {};
        data["location"] = $(".btn-location span:first").text();
        data["locationid"] = gvm.currentLocationId;
        data["training"] = $(".btn-training span:first").text();
        data["trainingid"] = gvm.currentTrainingid;
        data["course"] = $(".btn-course span:first").text();
        data["courseid"] = gvm.currentCourseId;
        data["user"] = gvm.userId;
        console.log(data);
        $.ajax({
            type: "POST",
            url: "/api/savedropdowns",
            data: data,
            success: function() {
                console.log("success");
            }
        })
    }

    gvm.updateLocations = function() {
        $.getJSON('/api/coursesrapport', function(data) {
            gvm.availableLocations.removeAll();
            $.each(data, function(i, item) {
              //  Put item in list
                gvm.availableLocations.push(item);

                // Add listener to listitem
                $("#locbtn-" + item.id).click(function(){
                    gvm.currentLocationId = item.id;
                    gvm.currentTrainingid = null;
                    gvm.currentCourseId = null;
                    gvm.updateTrainings(item.id);
                    $(".btn-location span:first").text($(this).text());
                    $(".btn-training span:first").text("training");
                    $(".btn-course span:first").text("course");
                });
            });
        });
    };

    /*
     * Update the training data
     */
    gvm.updateTrainings = function(id) {
        $.getJSON('/api/trainings/' + id, function(data) {
            gvm.availableTrainings.removeAll();
            $.each(data, function(i, item) {
                gvm.availableTrainings.push(item);

                /* Add listener to listitem */
                $("#trainingbtn-" + item.id).click(function(){
                    gvm.currentTrainingid = item.id;
                    gvm.currentCourseId = null;
                    gvm.updateCourses(item.id);
                    $(".btn-training span:first").text($(this).text());
                    $(".btn-course span:first").text("course");
                });
            });
        });
    }

    /*
     * Update available courses
     */
    gvm.updateCourses = function(id) {
        $.getJSON('/api/courses/' + id, function(data) {
            gvm.availableCourses.removeAll();
            $.each(data, function(i, item) {
                gvm.availableCourses.push(item);

                /* Add listener to listitem */
                $("#coursebtn-" + item.id).click(function(){
                    $(".btn-course span:first").text($(this).text());
                    gvm.currentCourseId = item.id;
                    gvm.saveLastSelectedDropdowns();
                    loadTablePage(item.id, 1);
                });
            });
        });
    }

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

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

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    }
}

function loadTablePage(courseid, pagenr)
{
    $.getJSON('/api/projects/' + courseid + '/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);
        });

        /* 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(courseid, thispagenr);
                });
            }
        });
    });

}

function initPage() {
    $.getJSON('/api/currentuser', function(data) {
        viewModel.userId = data.id;
        viewModel.updateDropdowns();
    });
}<commit_msg>test extreme<commit_after>//viewmodel for the assess page
function pageViewModel(gvm) {
    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. __("AssessTitle2");}, gvm);
    gvm.userId = -1;

+-    // Page specific i18n bindings
    gvm.pageHeader = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AssessTitle2");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectRapportName");}, gvm);
    gvm.homeManual = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("HomeRapportManual");}, gvm);
    gvm.foundProjects = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("FoundProjects");}, gvm);
    gvm.selectCourse = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SelectCourse");}, gvm);

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

    // Table i18n bindings
    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.actionTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ActionTableTitle");}, gvm);

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

    gvm.currentCourseId = null;
    gvm.currentLocationId = null;
    gvm.currentTrainingid = null;

    gvm.updateDropdowns = function() {
        $.getJSON('api/lastdropdownchoice/' + gvm.userId, function(data) {
            if(!$.isEmptyObject(data)) {
                $.each(data, function(i, item) {
                    $(".btn-location span:first").text(item.location);
                    $(".btn-training span:first").text(item.training);
                    $(".btn-course span:first").text(item.course);
                    gvm.currentLocationId = item.locationid;
                    gvm.currentTrainingid = item.trainingid;
                    gvm.currentCourseId = item.courseid;
                    gvm.updateLocations();
                    gvm.updateTrainings(item.locationid);
                    gvm.updateCourses(item.trainingid);
                    loadTablePage(item.courseid, 1);
                });
            } else {
                gvm.updateLocations();
            }
        });
    }

    gvm.saveLastSelectedDropdowns = function() {
        data = {};
        data["location"] = $(".btn-location span:first").text();
        data["locationid"] = gvm.currentLocationId;
        data["training"] = $(".btn-training span:first").text();
        data["trainingid"] = gvm.currentTrainingid;
        data["course"] = $(".btn-course span:first").text();
        data["courseid"] = gvm.currentCourseId;
        data["user"] = gvm.userId;
        console.log(data);
        $.ajax({
            type: "POST",
            url: "/api/savedropdowns",
            data: data,
            success: function() {
                console.log("success");
            }
        })
    }

    gvm.saveLastSelectedDropdowns = function() {
        data = {};
        data["location"] = $(".btn-location span:first").text();
        data["locationid"] = gvm.currentLocationId;
        data["training"] = $(".btn-training span:first").text();
        data["trainingid"] = gvm.currentTrainingid;
        data["course"] = $(".btn-course span:first").text();
        data["courseid"] = gvm.currentCourseId;
        data["user"] = gvm.userId;
        console.log(data);
        $.ajax({
            type: "POST",
            url: "/api/savedropdowns",
            data: data,
            success: function() {
                console.log("success");
            }
        })
    }

    gvm.updateLocations = function() {
        $.getJSON('/api/courserapport', function(data) {
            gvm.availableLocations.removeAll();
            $.each(data, function(i, item) {
              //  Put item in list
                gvm.availableLocations.push(item);

                // Add listener to listitem
                $("#locbtn-" + item.id).click(function(){
                    gvm.currentLocationId = item.id;
                    gvm.currentTrainingid = null;
                    gvm.currentCourseId = null;
                    gvm.updateTrainings(item.id);
                    $(".btn-location span:first").text($(this).text());
                    $(".btn-training span:first").text("training");
                    $(".btn-course span:first").text("course");
                });
            });
        });
    };

    /*
     * Update the training data
     */
    gvm.updateTrainings = function(id) {
        $.getJSON('/api/trainings/' + id, function(data) {
            gvm.availableTrainings.removeAll();
            $.each(data, function(i, item) {
                gvm.availableTrainings.push(item);

                /* Add listener to listitem */
                $("#trainingbtn-" + item.id).click(function(){
                    gvm.currentTrainingid = item.id;
                    gvm.currentCourseId = null;
                    gvm.updateCourses(item.id);
                    $(".btn-training span:first").text($(this).text());
                    $(".btn-course span:first").text("course");
                });
            });
        });
    }

    /*
     * Update available courses
     */
    gvm.updateCourses = function(id) {
        $.getJSON('/api/courses/' + id, function(data) {
            gvm.availableCourses.removeAll();
            $.each(data, function(i, item) {
                gvm.availableCourses.push(item);

                /* Add listener to listitem */
                $("#coursebtn-" + item.id).click(function(){
                    $(".btn-course span:first").text($(this).text());
                    gvm.currentCourseId = item.id;
                    gvm.saveLastSelectedDropdowns();
                    loadTablePage(item.id, 1);
                });
            });
        });
    }

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

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

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    }
}

function loadTablePage(courseid, pagenr)
{
    $.getJSON('/api/projects/' + courseid + '/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);
        });

        /* 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(courseid, thispagenr);
                });
            }
        });
    });

}

function initPage() {
    $.getJSON('/api/currentuser', function(data) {
        viewModel.userId = data.id;
        viewModel.updateDropdowns();
    });
}<|endoftext|>


<commit_before>/**
 * Traditional Chinese translation for bootstrap-datepicker
 * Rung-Sheng Jang <daniel@i-trend.co.cc>
 * FrankWu  <frankwu100@gmail.com> Fix more appropriate use of Traditional Chinese habit
 */
;(function($){
	$.fn.datepicker.dates['zh-TW'] = {
		days: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
		daysShort: ["週日", "週一", "週二", "週三", "週四", "週五", "週六"],
		daysMin:  ["日", "一", "二", "三", "四", "五", "六"],
		months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
		monthsShort: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
		today: "今天",
		format: "yyyy年mm月dd日",
		weekStart: 1,
		clear: "清除"
	};
}(jQuery));
<commit_msg>minor #2526 Update bootstrap-datepicker.zh-TW.js (JaySkyworker)<commit_after>/**
 * Traditional Chinese translation for bootstrap-datepicker
 * Rung-Sheng Jang <daniel@i-trend.co.cc>
 * FrankWu  <frankwu100@gmail.com> Fix more appropriate use of Traditional Chinese habit
 */
;(function($){
	$.fn.datepicker.dates['zh-TW'] = {
		days: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
		daysShort: ["週日", "週一", "週二", "週三", "週四", "週五", "週六"],
		daysMin: ["日", "一", "二", "三", "四", "五", "六"],
		months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
		monthsShort: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
		today: "今天",
		monthsTitle: "月份",
		format: "yyyy/mm/dd",
		weekStart: 0,
		titleFormat: "yyyy年mm月",
		clear: "清除"
	};
}(jQuery));
<|endoftext|>


<commit_before>define([
	'knockout',
	'atlas-state',
	'text!./search.html',
	'appConfig',
	'services/AuthAPI',
	'../PermissionService',
	'components/Component',
	'utils/AutoBind',
	'services/http',
	'pages/vocabulary/const',
	'utils/CommonUtils',
	'services/Vocabulary',
	'components/tabs',
	'components/panel',
	'faceted-datatable',
	'components/empty-state',
	'less!./search.less'
], function (
	ko,
	sharedState,
	view,
	config,
	authApi,
	PermissionService,
	Component,
	AutoBind,
	httpService,
	constants,
	commonUtils,
	vocabularyProvider
) {
	class Search extends AutoBind(Component) {
		constructor(params) {
			super(params);
			this.currentSearch = ko.observable('');
			this.loading = ko.observable(false);
			this.domainsLoading = ko.observable(true);
			this.vocabulariesLoading = ko.observable(true);
			this.canSearch = ko.observable(true);
			this.showAdvanced = ko.observable(false);
			this.domains = ko.observableArray();
			this.vocabularies = ko.observableArray();
			this.selected = {
				domains: new Set(),
				vocabularies: new Set(),
			};
			this.data = ko.observableArray([]);
			this.searchExecuted = ko.observable(false);
			this.searchColumns = ko.observableArray([]);
			this.searchOptions = ko.observable();

			this.isInProgress = ko.computed(() => {
				return this.domainsLoading() === true && this.vocabulariesLoading() === true;
			});
			this.isInProgress.subscribe((isInProgress) => {
				if (!isInProgress) {
					if (params.query()) {
						this.currentSearch(params.query());
						this.executeSearch();
					}
				}
			});
			params.query.subscribe(() => {
				if (!this.isInProgress()) {
					this.currentSearch(params.query());
					this.executeSearch();
				}
			});
			this.currentSearch.subscribe(() => this.searchExecuted(false));
			this.loadingMessage = ko.computed(() => {
				const entities = [];
				if (this.domainsLoading()) {
					entities.push('domains');
				}
				if (this.vocabulariesLoading()) {
					entities.push('vocabularies');
				}
				if (this.loading()) {
					entities.push('search results');
				}
				return `Loading ${entities.join(', ')}`;
			});
			// 'colvis',
			this.buttons = [
				{
					extend: 'colvis',
					columnText: (dt, idx, title) => {
						if (idx === 0) {
							return '';
						}
						return title;
					}
				},
				'copyHtml5',
				'excelHtml5',
				'csvHtml5',
				'pdfHtml5'
			];

			this.searchColumns = [{
				title: '',
				render: function (s, p, d) {
					var css = '';
					var icon = 'fa-shopping-cart';
					if (sharedState.selectedConceptsIndex[d.CONCEPT_ID] == 1) {
						css = ' selected';
					}
					return '';
				},
				orderable: false,
				searchable: false
			}, {
				title: 'Id',
				data: 'CONCEPT_ID'
			}, {
				title: 'Code',
				data: 'CONCEPT_CODE'
			}, {
				title: 'Name',
				data: 'CONCEPT_NAME',
				render: commonUtils.renderLink,
			}, {
				title: 'Class',
				data: 'CONCEPT_CLASS_ID'
			}, {
				title: 'Standard Concept Caption',
				data: 'STANDARD_CONCEPT_CAPTION',
				visible: false
			}, {
				title: 'RC',
				data: 'RECORD_COUNT',
				className: 'numeric'
			}, {
				title: 'DRC',
				data: 'DESCENDANT_RECORD_COUNT',
				className: 'numeric'
			}, {
				title: 'Domain',
				data: 'DOMAIN_ID'
			}, {
				title: 'Vocabulary',
				data: 'VOCABULARY_ID'
			}];

			this.searchOptions = {
				Facets: [{
					'caption': 'Vocabulary',
					'binding': function (o) {
						return o.VOCABULARY_ID;
					}
				}, {
					'caption': 'Class',
					'binding': function (o) {
						return o.CONCEPT_CLASS_ID;
					}
				}, {
					'caption': 'Domain',
					'binding': function (o) {
						return o.DOMAIN_ID;
					}
				}, {
					'caption': 'Standard Concept',
					'binding': function (o) {
						return o.STANDARD_CONCEPT_CAPTION;
					}
				}, {
					'caption': 'Invalid Reason',
					'binding': function (o) {
						return o.INVALID_REASON_CAPTION;
					}
				}, {
					'caption': 'Has Records',
					'binding': function (o) {
						return parseInt(o.RECORD_COUNT.toString().replace(',', '')) > 0;
					}
				}, {
					'caption': 'Has Descendant Records',
					'binding': function (o) {
						return parseInt(o.DESCENDANT_RECORD_COUNT.toString().replace(',', '')) > 0;
					}
				}]
			};

			this.isAuthenticated = authApi.isAuthenticated;
			this.hasAccess = ko.computed(() => PermissionService.isPermittedSearch());

			if (this.hasAccess()) {
				this.getDomains();
				this.getVocabularies();
			}
		}

		searchClick() {
			const redirectUrl = '#/search/' + escape(this.currentSearch());
			if (this.selected.vocabularies.size > 0 || this.selected.domains.size > 0 || document.location.hash === redirectUrl) {
				this.executeSearch();
			} else if (this.currentSearch().length > 2) {
				document.location = redirectUrl;
			} else {
				alert('invalid search');
			}
		}

		clearAllAdvanced() {
			$('.advanced-options input').attr('checked', false);
			this.selected.vocabularies.clear();
			this.selected.domains.clear();
		}

		toggleAdvanced() {
			this.showAdvanced(!this.showAdvanced());
		}

		toggleVocabulary(id) {
			this.selected.vocabularies.has(id)
				? this.selected.vocabularies.delete(id)
				: this.selected.vocabularies.add(id, true);
		}

		toggleDomain(id) {
			this.selected.domains.has(id)
				? this.selected.domains.delete(id)
				: this.selected.domains.add(id, true);
		}

		updateSearchFilters() {
			$(event.target).toggleClass('selected');
			const filters = [];
			$('#wrapperSearchResultsFilter .facetMemberName.selected').each(function (i, d) {
				filters.push(d.id);
			});
			this.feSearch().SetFilter(filters);
			// update filter data binding
			this.feSearch(this.feSearch());
			// update table data binding
			this.data(this.feSearch().GetCurrentObjects());
		}

		onKeyPress(event) {
			if (event.keyCode === 13) {
				this.searchClick();
			} else {
				return true;
			}
		}

		executeSearch() {
			if (!this.currentSearch() && !this.showAdvanced()) {
                this.data([]);
                return;
			}

			this.searchExecuted(false);
			const vocabElements = this.selected.vocabularies;
			const domainElements = this.selected.domains;

			// if we don't have a search and aren't looking up domain or vocabulary details, abort.
			if (
				this.currentSearch() === undefined
				&& vocabElements.size == 0
				&& domainElements.size == 0
			) {
				return;
			}

			const query = this.currentSearch() === undefined ? '' : this.currentSearch();
			this.loading(true);
			this.data([]);

			let searchUrl = `${sharedState.vocabularyUrl()}search`;
			let searchParams = null;
			let promise = null;

			if (vocabElements.size > 0 || domainElements.size > 0) {
				// advanced search
				searchParams = {
					"QUERY": query,
				};
				if (vocabElements.size > 0) {
					searchParams["VOCABULARY_ID"] = Array.from(vocabElements);
				}
				if (domainElements.size > 0) {
					searchParams["DOMAIN_ID"] = Array.from(domainElements);
				}
				promise = httpService.doPost(searchUrl, searchParams);
			} else {
				// simple search
				searchUrl += `/${query}`;
				promise = httpService.doGet(searchUrl, searchParams);
			}

			promise.then(({ data }) => this.handleSearchResults(data))
				.catch(er => {
					console.error('error while searching', er);
				})
				.finally(() => {
					this.loading(false);
					this.searchExecuted(true);
				});
		}

		handleSearchResults(results) {
			if (results.length === 0) {
				throw { message: 'No results found', results };
			}

			const promise = vocabularyProvider.loadDensity(results);
			promise.then(() => {
				this.data(results);
			});

			return promise;
		}

		getVocabularies() {
			httpService.doGet(constants.apiPaths.vocabularies())
				.then(({ data }) => {
					const vocabularies = data.sort(function (a, b) {
						return (a.VOCABULARY_ID.toUpperCase()  b.VOCABULARY_ID.toUpperCase()) ? 1 : 0;
					});
					this.vocabularies(vocabularies);
				})
				.catch(er => console.error('Error occured when loading vocabularies', er))
				.finally(() => {
					this.vocabulariesLoading(false);
				});
		}

		getDomains() {
			httpService.doGet(constants.apiPaths.domains())
				.then(({ data }) => {
					this.domains(data);
				})
				.catch(er => console.error('Error occured when loading domains', er))
				.finally(() => {
					this.domainsLoading(false);
				});
		}

		noResultsFoundMessage() {
			return 'No results found for \"' + this.currentSearch() + '\"';
		}
	}

	return commonUtils.build('vocabulary-search', Search, view);
});
<commit_msg>Vocabulary search - handle special characters (#1653)<commit_after>define([
	'knockout',
	'atlas-state',
	'text!./search.html',
	'appConfig',
	'services/AuthAPI',
	'../PermissionService',
	'components/Component',
	'utils/AutoBind',
	'services/http',
	'pages/vocabulary/const',
	'utils/CommonUtils',
	'services/Vocabulary',
	'components/tabs',
	'components/panel',
	'faceted-datatable',
	'components/empty-state',
	'less!./search.less'
], function (
	ko,
	sharedState,
	view,
	config,
	authApi,
	PermissionService,
	Component,
	AutoBind,
	httpService,
	constants,
	commonUtils,
	vocabularyProvider
) {
	class Search extends AutoBind(Component) {
		constructor(params) {
			super(params);
			this.currentSearch = ko.observable('');
			this.loading = ko.observable(false);
			this.domainsLoading = ko.observable(true);
			this.vocabulariesLoading = ko.observable(true);
			this.canSearch = ko.observable(true);
			this.showAdvanced = ko.observable(false);
			this.domains = ko.observableArray();
			this.vocabularies = ko.observableArray();
			this.selected = {
				domains: new Set(),
				vocabularies: new Set(),
			};
			this.data = ko.observableArray([]);
			this.searchExecuted = ko.observable(false);
			this.searchColumns = ko.observableArray([]);
			this.searchOptions = ko.observable();

			this.isInProgress = ko.computed(() => {
				return this.domainsLoading() === true && this.vocabulariesLoading() === true;
			});
			this.isInProgress.subscribe((isInProgress) => {
				if (!isInProgress) {
					if (params.query()) {
						this.currentSearch(params.query());
						this.executeSearch();
					}
				}
			});
			params.query.subscribe(() => {
				if (!this.isInProgress()) {
					this.currentSearch(params.query());
					this.executeSearch();
				}
			});
			this.currentSearch.subscribe(() => this.searchExecuted(false));
			this.loadingMessage = ko.computed(() => {
				const entities = [];
				if (this.domainsLoading()) {
					entities.push('domains');
				}
				if (this.vocabulariesLoading()) {
					entities.push('vocabularies');
				}
				if (this.loading()) {
					entities.push('search results');
				}
				return `Loading ${entities.join(', ')}`;
			});
			// 'colvis',
			this.buttons = [
				{
					extend: 'colvis',
					columnText: (dt, idx, title) => {
						if (idx === 0) {
							return '';
						}
						return title;
					}
				},
				'copyHtml5',
				'excelHtml5',
				'csvHtml5',
				'pdfHtml5'
			];

			this.searchColumns = [{
				title: '',
				render: function (s, p, d) {
					var css = '';
					var icon = 'fa-shopping-cart';
					if (sharedState.selectedConceptsIndex[d.CONCEPT_ID] == 1) {
						css = ' selected';
					}
					return '';
				},
				orderable: false,
				searchable: false
			}, {
				title: 'Id',
				data: 'CONCEPT_ID'
			}, {
				title: 'Code',
				data: 'CONCEPT_CODE'
			}, {
				title: 'Name',
				data: 'CONCEPT_NAME',
				render: commonUtils.renderLink,
			}, {
				title: 'Class',
				data: 'CONCEPT_CLASS_ID'
			}, {
				title: 'Standard Concept Caption',
				data: 'STANDARD_CONCEPT_CAPTION',
				visible: false
			}, {
				title: 'RC',
				data: 'RECORD_COUNT',
				className: 'numeric'
			}, {
				title: 'DRC',
				data: 'DESCENDANT_RECORD_COUNT',
				className: 'numeric'
			}, {
				title: 'Domain',
				data: 'DOMAIN_ID'
			}, {
				title: 'Vocabulary',
				data: 'VOCABULARY_ID'
			}];

			this.searchOptions = {
				Facets: [{
					'caption': 'Vocabulary',
					'binding': function (o) {
						return o.VOCABULARY_ID;
					}
				}, {
					'caption': 'Class',
					'binding': function (o) {
						return o.CONCEPT_CLASS_ID;
					}
				}, {
					'caption': 'Domain',
					'binding': function (o) {
						return o.DOMAIN_ID;
					}
				}, {
					'caption': 'Standard Concept',
					'binding': function (o) {
						return o.STANDARD_CONCEPT_CAPTION;
					}
				}, {
					'caption': 'Invalid Reason',
					'binding': function (o) {
						return o.INVALID_REASON_CAPTION;
					}
				}, {
					'caption': 'Has Records',
					'binding': function (o) {
						return parseInt(o.RECORD_COUNT.toString().replace(',', '')) > 0;
					}
				}, {
					'caption': 'Has Descendant Records',
					'binding': function (o) {
						return parseInt(o.DESCENDANT_RECORD_COUNT.toString().replace(',', '')) > 0;
					}
				}]
			};

			this.isAuthenticated = authApi.isAuthenticated;
			this.hasAccess = ko.computed(() => PermissionService.isPermittedSearch());

			if (this.hasAccess()) {
				this.getDomains();
				this.getVocabularies();
			}
		}

		replaceSpecialCharacters(str) {
			return str.replace("/", " ");
		}

		encodeSearchString(searchTerm) {
			return encodeURIComponent(this.replaceSpecialCharacters(searchTerm));
		}

		searchClick() {
			const redirectUrl = '#/search/' + this.encodeSearchString(this.currentSearch());
			if (this.selected.vocabularies.size > 0 || this.selected.domains.size > 0 || document.location.hash === redirectUrl) {
				this.executeSearch();
			} else if (this.currentSearch().length > 2) {
				document.location = redirectUrl;
			} else {
				alert('invalid search');
			}
		}

		clearAllAdvanced() {
			$('.advanced-options input').attr('checked', false);
			this.selected.vocabularies.clear();
			this.selected.domains.clear();
		}

		toggleAdvanced() {
			this.showAdvanced(!this.showAdvanced());
		}

		toggleVocabulary(id) {
			this.selected.vocabularies.has(id)
				? this.selected.vocabularies.delete(id)
				: this.selected.vocabularies.add(id, true);
		}

		toggleDomain(id) {
			this.selected.domains.has(id)
				? this.selected.domains.delete(id)
				: this.selected.domains.add(id, true);
		}

		updateSearchFilters() {
			$(event.target).toggleClass('selected');
			const filters = [];
			$('#wrapperSearchResultsFilter .facetMemberName.selected').each(function (i, d) {
				filters.push(d.id);
			});
			this.feSearch().SetFilter(filters);
			// update filter data binding
			this.feSearch(this.feSearch());
			// update table data binding
			this.data(this.feSearch().GetCurrentObjects());
		}

		onKeyPress(event) {
			if (event.keyCode === 13) {
				this.searchClick();
			} else {
				return true;
			}
		}

		executeSearch() {
			if (!this.currentSearch() && !this.showAdvanced()) {
                this.data([]);
                return;
			}

			this.searchExecuted(false);
			const vocabElements = this.selected.vocabularies;
			const domainElements = this.selected.domains;

			// if we don't have a search and aren't looking up domain or vocabulary details, abort.
			if (
				this.currentSearch() === undefined
				&& vocabElements.size == 0
				&& domainElements.size == 0
			) {
				return;
			}

			let query = '';
			if (this.currentSearch() !== undefined) {
				query = this.encodeSearchString(this.currentSearch());
				this.currentSearch(this.replaceSpecialCharacters(this.currentSearch()));
			}
			this.loading(true);
			this.data([]);

			let searchUrl = `${sharedState.vocabularyUrl()}search`;
			let searchParams = null;
			let promise = null;

			if (vocabElements.size > 0 || domainElements.size > 0) {
				// advanced search
				searchParams = {
					"QUERY": query,
				};
				if (vocabElements.size > 0) {
					searchParams["VOCABULARY_ID"] = Array.from(vocabElements);
				}
				if (domainElements.size > 0) {
					searchParams["DOMAIN_ID"] = Array.from(domainElements);
				}
				promise = httpService.doPost(searchUrl, searchParams);
			} else {
				// simple search
				searchUrl += `/${query}`;
				promise = httpService.doGet(searchUrl, searchParams);
			}

			promise.then(({ data }) => this.handleSearchResults(data))
				.catch(er => {
					console.error('error while searching', er);
				})
				.finally(() => {
					this.loading(false);
					this.searchExecuted(true);
				});
		}

		handleSearchResults(results) {
			if (results.length === 0) {
				throw { message: 'No results found', results };
			}

			const promise = vocabularyProvider.loadDensity(results);
			promise.then(() => {
				this.data(results);
			});

			return promise;
		}

		getVocabularies() {
			httpService.doGet(constants.apiPaths.vocabularies())
				.then(({ data }) => {
					const vocabularies = data.sort(function (a, b) {
						return (a.VOCABULARY_ID.toUpperCase()  b.VOCABULARY_ID.toUpperCase()) ? 1 : 0;
					});
					this.vocabularies(vocabularies);
				})
				.catch(er => console.error('Error occured when loading vocabularies', er))
				.finally(() => {
					this.vocabulariesLoading(false);
				});
		}

		getDomains() {
			httpService.doGet(constants.apiPaths.domains())
				.then(({ data }) => {
					this.domains(data);
				})
				.catch(er => console.error('Error occured when loading domains', er))
				.finally(() => {
					this.domainsLoading(false);
				});
		}

		noResultsFoundMessage() {
			return 'No results found for \"' + this.currentSearch() + '\"';
		}
	}

	return commonUtils.build('vocabulary-search', Search, view);
});
<|endoftext|>


<commit_before>'use strict';

angular.module('testruns').controller('TestrunsController', ['$scope', '$stateParams', '$state', 'TestRuns', 'Dashboards', 'Events', '$modal', '$q', 'ConfirmModal',
	function($scope, $stateParams, $state, TestRuns, Dashboards, Events, $modal, $q, ConfirmModal) {

        $scope.productName = $stateParams.productName;

        $scope.dashboardName = $stateParams.dashboardName;

		/* List test runs for dashboard */

        $scope.listTestRunsForDashboard = function () {

            //var pending = false;
            //var intervalId = setInterval(function(){

                TestRuns.listTestRunsForDashboard($scope.productName, $scope.dashboardName, false).success(function (testRuns){

                    //$scope.testRuns = result.testRuns;
                    ///* if all testruns have been persisted, stop polling */
                    //if (result.pending === false){
                    //    clearInterval(intervalId);
                    //}else{
                    //    pending = true;
                    //}

                    $scope.testRuns = testRuns;

                }, function(errorResponse) {
                    $scope.error = errorResponse.data.message;
                });

            //}, 10000);

        };

        $scope.testRunDetails = function(index){

            TestRuns.selected = $scope.testRuns[index];
            $state.go('viewGraphs',{"productName":$stateParams.productName, "dashboardName":$stateParams.dashboardName, "testRunId" : $scope.testRuns[index].testRunId, tag: Dashboards.getDefaultTag(Dashboards.selected.tags) });
        }

        $scope.testRunRequirements = function(index, status){

            TestRuns.selected = $scope.testRuns[index];

            switch (status){

                case null:

                    $scope.testRuns[index].testrunMeetsRequirement = "pending";

                    TestRuns.persistTestRunByIdFromEvents($stateParams.productName,$stateParams.dashboardName, $scope.testRuns[index].testRunId).success(function (testRun){

                        $scope.testRuns[index] = testRun;

                    }, function(errorResponse) {
                        $scope.error = errorResponse.data.message;
                    });
                    break;

                default:

                    var requirementsResult = $scope.testRuns[index].testrunMeetsRequirement ? "passed" : "failed";

                    $state.go('requirementsTestRun',{"productName":$stateParams.productName, "dashboardName":$stateParams.dashboardName, "testRunId" : $scope.testRuns[index].testRunId, "requirementsResult" : requirementsResult });

            }

        }

        $scope.openDeleteTestRunModal = function (size, index) {

            ConfirmModal.itemType = 'Delete test run ';
            ConfirmModal.selectedItemId = index;
            ConfirmModal.selectedItemDescription = $scope.testRuns[index].testRunId;

            var modalInstance = $modal.open({
                templateUrl: 'ConfirmDelete.html',
                controller: 'ModalInstanceController',
                size: size//,
            });

            modalInstance.result.then(function (selectedIndex) {

                $q.all([Events.delete($scope.testRuns[selectedIndex].eventIds[0]), Events.delete($scope.testRuns[selectedIndex].eventIds[1])])
                    .then(TestRuns.delete($scope.productName, $scope.dashboardName, $scope.testRuns[selectedIndex].testRunId))
                    .then(function(results){

                        /* refresh test runs*/
                        TestRuns.listTestRunsForDashboard($scope.productName, $scope.dashboardName).success(function (testRuns){

                            $scope.testRuns = testRuns;

                        }, function(errorResponse) {
                            $scope.error = errorResponse.data.message;
                        });

                        /* refresh view*/

                        $state.go($state.current, {}, {reload: true});

                    })

            }, function () {
                //$log.info('Modal dismissed at: ' + new Date());
            });

        };

    }
]);
<commit_msg>removed reload<commit_after>'use strict';

angular.module('testruns').controller('TestrunsController', ['$scope', '$stateParams', '$state', 'TestRuns', 'Dashboards', 'Events', '$modal', '$q', 'ConfirmModal',
	function($scope, $stateParams, $state, TestRuns, Dashboards, Events, $modal, $q, ConfirmModal) {

        $scope.productName = $stateParams.productName;

        $scope.dashboardName = $stateParams.dashboardName;

		/* List test runs for dashboard */

        $scope.listTestRunsForDashboard = function () {

            //var pending = false;
            //var intervalId = setInterval(function(){

                TestRuns.listTestRunsForDashboard($scope.productName, $scope.dashboardName, false).success(function (testRuns){

                    //$scope.testRuns = result.testRuns;
                    ///* if all testruns have been persisted, stop polling */
                    //if (result.pending === false){
                    //    clearInterval(intervalId);
                    //}else{
                    //    pending = true;
                    //}

                    $scope.testRuns = testRuns;

                }, function(errorResponse) {
                    $scope.error = errorResponse.data.message;
                });

            //}, 10000);

        };

        $scope.testRunDetails = function(index){

            TestRuns.selected = $scope.testRuns[index];
            $state.go('viewGraphs',{"productName":$stateParams.productName, "dashboardName":$stateParams.dashboardName, "testRunId" : $scope.testRuns[index].testRunId, tag: Dashboards.getDefaultTag(Dashboards.selected.tags) });
        }

        $scope.testRunRequirements = function(index, status){

            TestRuns.selected = $scope.testRuns[index];

            switch (status){

                case null:

                    $scope.testRuns[index].testrunMeetsRequirement = "pending";

                    TestRuns.persistTestRunByIdFromEvents($stateParams.productName,$stateParams.dashboardName, $scope.testRuns[index].testRunId).success(function (testRun){

                        $scope.testRuns[index] = testRun;

                    }, function(errorResponse) {
                        $scope.error = errorResponse.data.message;
                    });
                    break;

                default:

                    var requirementsResult = $scope.testRuns[index].testrunMeetsRequirement ? "passed" : "failed";

                    $state.go('requirementsTestRun',{"productName":$stateParams.productName, "dashboardName":$stateParams.dashboardName, "testRunId" : $scope.testRuns[index].testRunId, "requirementsResult" : requirementsResult });

            }

        }

        $scope.openDeleteTestRunModal = function (size, index) {

            ConfirmModal.itemType = 'Delete test run ';
            ConfirmModal.selectedItemId = index;
            ConfirmModal.selectedItemDescription = $scope.testRuns[index].testRunId;

            var modalInstance = $modal.open({
                templateUrl: 'ConfirmDelete.html',
                controller: 'ModalInstanceController',
                size: size//,
            });

            modalInstance.result.then(function (selectedIndex) {

            $q.all([Events.delete($scope.testRuns[selectedIndex].eventIds[0]), Events.delete($scope.testRuns[selectedIndex].eventIds[1])])
                .then(TestRuns.delete($scope.productName, $scope.dashboardName, $scope.testRuns[selectedIndex].testRunId))
                .then(function(results){

                    /* refresh test runs*/
                    TestRuns.listTestRunsForDashboard($scope.productName, $scope.dashboardName).success(function (testRuns){

                        $scope.testRuns = testRuns;

                    }, function(errorResponse) {
                        $scope.error = errorResponse.data.message;
                    });

                })

            }, function () {
                //$log.info('Modal dismissed at: ' + new Date());
            });

        };

    }
]);
<|endoftext|>