var $=function(id) { return document.getElementById(id); };


var upload_status=0,fileajax;
function upload() {
    if(upload_status==0) {
        upload_status=1;
        $('upload').value="Cancel upload";

        $('status').innerHTML="Uploading - 0%";
        $('progress').style.width="0%";

        var file=$('file').files[0];
        var formdata=new FormData();
        formdata.append('file',file);
        fileajax=new XMLHttpRequest();
        fileajax.upload.addEventListener('progress',progressHandler,false);
        fileajax.addEventListener('load',completeHandler,false);
        fileajax.addEventListener('error',errorHandler,false);
        fileajax.addEventListener('abort',abortHandler,false);
        fileajax.open("POST","upload.php");
        fileajax.send(formdata);
    } else {
        fileajax.abort();
        abortHandler();
    }
}

function progressHandler(event) {
    var percent=Math.round((event.loaded/event.total)*100);
    $('status').innerHTML="Uploading - "+percent+"%";
    $('status').style.color="#17181A";
    $('progress').style.width=percent+"%";
}

function completeHandler(event) {
    $('progress').style.width="0%";
    $('status').innerHTML=event.target.responseText;
    $('status').style.color="#AAABAD";

    //$('file').value="";
    //$('filsel').innerHTML="<br />Select file to upload<br />File: none<br /><br />";

    //checkfiles();

    $('list').src=$('list').src;

    $('upload').value="Upload file";
    upload_status=0;
}

function errorHandler(event) {
    $('progress').style.width="0%";
    $('status').innerHTML="Upload failed!";
    $('status').style.color="#AAABAD";

    $('upload').value="Upload file";
    upload_status=0;
}

function abortHandler(event) {
    $('progress').style.width="0%";
    $('status').innerHTML="Upload aborted!";
    $('status').style.color="#AAABAD";

    $('upload').value="Upload file";
    upload_status=0;
}
