document.getElementById("upload").addEventListener("change", upload, false);
document.getElementById("download").addEventListener("click", download, false);

function upload(e) {

    var data = null;
    var file = e.target.files[0];

    var reader = new FileReader();
    reader.readAsText(file);
    reader.onload = function (event) {
        var csvData = event.target.result;

        var parsedCSV = d3.csv.parseRows(csvData);

        parsedCSV.forEach(function (d, i) {
            if (i == 0) return true; // skip the header
            document.getElementById(d[0]).value = d[1];
        });

    }
}

function download(e) {
    
    data = [["id","value"]];
    
    var f = d3.selectAll("#csvForm input, select")[0];
    
    f.forEach(function(d,i){
      	data.push([d.id, d.value]);
    });
    
    console.log(data);
    
    var csvContent = "data:text/csv;charset=utf-8,";
    data.forEach(function (d, i) {
        dataString = d.join(",");
        csvContent += i < data.length ? dataString + "\n" : dataString;
    });
    
    var url = window.location.pathname;
    var filename = url.substring(url.lastIndexOf('/')+1);
    var fname = filename.split(".")[0];
    var csvname = fname+".csv";

    var encodedUri = encodeURI(csvContent);
    var link = document.createElement("a");
    link.setAttribute("href", encodedUri);
    link.setAttribute("download", csvname);
    link.click();
}