//Register PWA service worker
if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('sw.js');
}
//Redirect HTTP to HTTPS
if(location.protocol=="http:"){
    location.href="https"+location.href.substring(4);
}

//Example functions
function ID(e){
    return document.getElementById(e);
}
function testConnection(success,failure){
    var xhr=new XMLHttpRequest();
    xhr.onload=function(){
        success();
    };
    xhr.onerror=function(){
        failure();
    }
    xhr.open("GET","test.dat?r="+Math.random(),true);
    xhr.send();
}
function populateSongList(){
    var xhr=new XMLHttpRequest();
    xhr.onload=function(){
        try{
            var songs=JSON.parse(xhr.responseText);
            ID("list").innerHTML="";
            songs.forEach(function(s){
                var d=document.createElement("div");
                d.className="song";
                var e=document.createElement("div");
                e.className="title";
                e.innerText=s.title;
                d.appendChild(e);
                var e=document.createElement("div");
                e.className="artist";
                e.innerText=s.artist;
                d.appendChild(e);
                var e=document.createElement("div");
                e.className="year";
                e.innerText=s.year;
                d.appendChild(e);
                var e=document.createElement("div");
                e.className="clickableOverlay";
                e.onclick=function(){
                    var player=ID("player");
                    player.src="songs/"+s.filename;
                    player.onerror=function(){
                        alert("You're offline :(");
                        document.querySelectorAll("div.song").forEach(function(ss){
                            ss.className="song";
                        });
                    }
                    /*player.oncanplaythrough=function(){
                        console.log("Caching fully loaded song: "+player.src);
                        caches.open("pwaes4").then(function(cache){
                            cache.add(player.src);
                        });
                    }*/
                    player.play();
                    document.querySelectorAll("div.song").forEach(function(ss){
                        ss.className="song";
                    });
                    d.className="song playing";
                };
                d.appendChild(e);
                ID("list").appendChild(d);
            });
        }catch(e){
            ID("list").innerText="Internal error :(";
        }
    };
    xhr.onerror=function(){
        ID("list").innerText="Failed to fetch the song list";
    }
    xhr.open("GET","songs/list.json",true);
    xhr.send();
}
