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

//Implementazione
function ID(e){
    return document.getElementById(e);
}
var disegnando=false;
var prevX=-1,prevY=-1;
function inizializza(){
    var c=ID("canvas");
    c.width=1024;
    c.height=1024;
    var ctx=c.getContext("2d");
    canvas.addEventListener("mousedown",function(e){
        disegnando=true;
        prevX=(e.clientX-c.offsetLeft+window.pageXOffset)*(c.width/c.clientWidth);
        prevY=(e.clientY-c.offsetTop+window.pageYOffset)*(c.height/c.clientHeight);
        ctx.beginPath();
        ctx.moveTo(prevX,prevY);
    });
    canvas.addEventListener("mouseup",function(e){
        disegnando=false;
    });
    canvas.addEventListener("mouseout",function(e){
        disegnando=false;
    });
    canvas.addEventListener("mousemove",function(e){
        if(disegnando){
            var currX=(e.clientX-c.offsetLeft+window.pageXOffset)*(c.width/c.clientWidth), currY=(e.clientY-c.offsetTop+window.pageYOffset)*(c.height/c.clientHeight);
            ctx.lineWidth=ID("spessore").value;
            ctx.strokeStyle=ID("colore").value;
            ctx.lineTo(currX,currY);
            ctx.stroke();
            prevX=currX;
            prevY=currY;
        }else{
            prevX=-1;
            prevY=-1;
        }
    });
    cancella();
    /*var xhr=new XMLHttpRequest();
    xhr.onload=function(){
        eval(xhr.responseText);
    };
    xhr.open("GET","FileSaver.js",true);
    xhr.send();*/
    var s=document.createElement("script");
    s.src="FileSaver.js";
    document.head.appendChild(s);
}
function cancella(){
    var c=ID("canvas");
    var ctx=c.getContext("2d");
    ctx.fillStyle="#FFFFFF";
    ctx.fillRect(0,0,c.width,c.height);
}
function salvaInLS(){
    var c=ID("canvas");
    localStorage.immagineSalvata=c.toDataURL();
    alert("Immagine salvata");
}
function caricaDaLS(){
    if(localStorage.immagineSalvata){
        cancella();
        var img=new Image();
        img.src=localStorage.immagineSalvata;
        img.onload=function(){
            ID("canvas").getContext("2d").drawImage(img,0,0);
            setTimeout(function(){alert("Immagine caricata");},1);
        }
    }else{
        alert("Non c'è un'immagine salvata");
    }
}
function salvaSuFile(){
    ID("canvas").toBlob(function(blob){saveAs(blob,"disegno.png")},"image/png");
}
