$(document).ready(function(){
    "use strict";

    function ChoirEvent(obj){
        let self = this;
        self.eventType = obj.eventType;
        self.notes = obj.notes;
        self.start = obj.start;
        self.end = obj.end;
        self.location = obj.location;
    }

    function ViewModel(){
        let self = this;
        self.events = ko.observableArray([]);

        function initialize(){
            loadEvents();
        }

        function loadEvents(){
            self.events([]);
            $.get({
                url: "api/_loadEvents.php"
            }).done(function(response){
                var obj = jQuery.parseJSON(response);
                if(obj.success === "true"){
                    let array = [];
                    obj.events.forEach(e => {
                        array.push(new ChoirEvent(e));
                    });
                    array.sort(function(a, b){
                        if(a.start < b.start){
                            return -1;
                        }
                        if(a.start > b.start){
                            return 1;
                        }
                        return 0;
                    })
                    self.events(array);
                }
            });
        }

        initialize();
    }

    ko.applyBindings(new ViewModel(), document.getElementById("content"));
});