(function (){
    var comfiture = {};
    var activeLink;
    var activeContent;
    var player;
    var reader;
    var motds = [
        "Made by Fristi",
        "Fristi? Fristi habe ich nicht.",
        "[Subject quote here]",
        "Press R or Z twice to do a barrel roll",
        "You wouldn't download a car.",
        "The last metroid is in captivity.",
        "Suavemente, bésame",
        "What is love?",
        "Justice in Spades",
        "Let's get Volatile",
        "Yeah, RIP",
        "What a shame.",
        "RED SPY IS IN THE BASE",
        "try fingers, but hole",
        "You don't have the right O you don't have the right"
    ];

    //Set up classes for player and reader
    class Player {
        #container;
        #element;

        constructor() {
            this.#container = document.querySelector('.player');
            if(this.#container) {
                this.#element = this.#container.querySelector('audio');
                this.#container.querySelector('span.times')
                    .addEventListener('click', event => {
                        this.#clear();
                        this.#container.classList.add('hide');
                    });

                document.querySelector('#logs').addEventListener('click', event => {
                    if(event.target.tagName != 'A') return;
                    this.#load(event.target.getAttribute('href'));
                    event.preventDefault();
                });
            }
        }

        #clear() {
            this.#element.pause();
            this.#element.removeAttribute('src');
        }

        #load(href) {
            this.#clear();
            if(this.#container.classList.contains('hide')) {
                this.#container.classList.remove('hide');
            }
            this.#element.setAttribute('src', href);
            this.#element.play();
        }
    }

    class Reader {
        #container;
        #content;
        #tabMain;
        #loader;
        #title;

        constructor() {
            this.#container = document.querySelector('.reader');
            if(this.#container) {
                this.#content = this.#container.querySelector('.reader-content');
                this.#loader = this.#container.querySelector('span.loader');
                this.#tabMain = document.querySelector('.tab-main');
                this.#title = this.#container.querySelector('.title');

                this.#container.querySelector('a.times')
                    .addEventListener('click', event => {
                        this.#clear();
                        this.#container.classList.add('hide');
                        this.#tabMain.classList.remove('hide');
                        this.#title.innerHTML = '';
                    });

                document.querySelector('#blogs .tab-main').addEventListener('click', event => {
                    if(event.target.tagName != 'A') return;
                    this.#load(event.target.getAttribute('href'));
                    event.preventDefault();
                });
            }
        }

        #clear() {
            this.#content.innerHTML = '';
        }

        #load(href) {
            this.#clear();
            this.#tabMain.classList.add('hide');
            this.#container.classList.remove('hide');
            this.#loader.classList.remove('hide');
            this.#title.innerHTML = href.substring(href.lastIndexOf('/')+1);

            ajax(href, response => {
                let converter = new showdown.Converter();
                this.#content.innerHTML = converter.makeHtml(response);
                this.#loader.classList.add('hide')
            }, () => {
                this.#content.innerHTML = "<h1>Could not load resource.</h1> <p>An error occurred, unable to display blog post.</p>";
                this.#loader.classList.add('hide')
            });
        }
    }

    function ajax(url, onSuccess, onError)
    {
        let request = new XMLHttpRequest();
        request.open('GET', url, true);

        request.onload = function() {
            if (this.status >= 200 && this.status < 400) {
                if(typeof onSuccess === 'function') {
                    onSuccess(this.response);
                }
            } else {
                if(typeof onError === 'function') {
                    onError(this.status, this.response);
                }
            }
        };

        request.onerror = function () {
            console.error('Failed request to ' + url + ', could not connect.');
            if(typeof onError === 'function') {
                onError(false, null);
            }
        }

        request.send();
    }

    function switchActiveContent(id)
    {
        let link = document.querySelector('a[href="'+id+'"]');
        let content = document.querySelector(id);

        if(link && content) {
            if(activeLink) activeLink.classList.remove('active');
            if(activeContent) activeContent.classList.add('hide');

            link.classList.add('active');
            content.classList.remove('hide');

            activeLink = link;
            activeContent = content;
        } else {
            console.error('Error: not switching content; link or content element for id ' + id + ' does not exist.');
        }
    }

    //Onload
    window.addEventListener('load', function(){
        //Hide all content
        let contents = document.querySelectorAll('.content-tab');
        contents.forEach(function (element) {
            element.classList.add('hide');
        });

        //Activate content matching hash in url (or home instead)
        let hash = window.location.hash;
        if(!hash) hash = '#home';
        switchActiveContent(hash);

        //Set up reader and player
        player = new Player();
        reader = new Reader();

        //Add click event handlers for header/footer links
        document.querySelectorAll('header, footer').forEach(element => {
            element.addEventListener('click', event => {
                if(event.target.tagName != 'A') return;
                let hash = event.target.getAttribute('href');
                switchActiveContent(hash);
            });
        });
    });

    //Global functions
    comfiture.setupWallpaper = function () {
        let wallpaper = 'a' + (Math.floor(Math.random() * 36) + 1) + '.gif';
        document.querySelector('.background').style.backgroundImage = 'url("backgrounds/'+wallpaper+'")';
    };

    comfiture.printMotd = function () {
        let motd = motds[Math.floor(Math.random() * motds.length)];
        document.write(motd);
    }

    //Expose comfiture object to document
    window.comfiture = comfiture;
})();
