function makeid() {
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    for (var i = 0; i < 5; i++)
        text += possible.charAt(Math.floor(Math.random() * possible.length));
    return text;
}

function dropdown(i,e) {
    document.getElementById(i).innerHTML = e;
    document.getElementById(i +'h').value = e;
    if (i == "serverbutton") {
        $.ajax({
            type: 'POST',
            url: "?rand="+ makeid(),
            data: "serverbuttoni="+ e,
            success: function(response) { 
                document.getElementById('drivesdiv').innerHTML = response;
            },
        });
    }
}

function post(path, params, method) {
    method = method || "post";
    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);
    for(var key in params) {
        if(params.hasOwnProperty(key)) {
            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", params[key]);
            form.appendChild(hiddenField);
        }
    }
    document.body.appendChild(form);
    form.submit();
}

$('#confirm-delete').on('click', '.btn-ok', function(e) {
    var $modalDiv = $('#confirm-detele'.delegateTarget);
    var dname = $(this).data('deleteName');
    var did = $(this).data('deleteId');
    var delwhat = $(this).data('deleteWhat');
    post('?', {delwhat: delwhat,deleteid: did,deletename: dname});
});
$('#confirm-delete').on('show.bs.modal', function(e) {
    var data = $(e.relatedTarget).data();
    $('.title', this).text(data.deleteVm);
    if (data.deleteWhat == "image"){
        var server = $('#imageserverbuttonsource').html();
        var dir = $('#imagedirbutton'+ server +'source').html();
        var img = $('#ld').find(":selected").text();
        document.getElementById('modaltext2').innerHTML = data.deleteText + img;
        $('.btn-ok', this).data({'deleteWhat': data.deleteWhat,'deleteName': server,'deleteId': dir +";"+ img});

    } else {
    document.getElementById('modaltext2').innerHTML = data.deleteText;
    $('.btn-ok', this).data({'deleteWhat': data.deleteWhat,'deleteName': data.deleteName,'deleteId': data.deleteId});
    }
});

function submitbutton(formid){
    data = $('#'+ formid).serialize();
    $.ajax({
        type: 'POST',
        url: "?rand="+ makeid(),
        data: data,
        success: function(response) { 
            if (response != "success"){
                window.alert('Failure!\n'+ response);
            } else {
                window.location.href = "";
            }
        },
    });
}

function arrow(dir, id){
    data = "&neworder="+ dir +"&vid="+ id;
    $.ajax({
        type: 'POST',
        url: "?rand="+ makeid(),
        data: data,
        success: function(response) {
            if (response != "success"){
                window.alert('Failure!\n' + response);
            } else {
                window.location.href = "";
            }
        },
    });
}

function imagemgmt(mode, server){
    if(mode == "show") {
        $('#imagemgmt').modal('show');
        $.ajax({
        type: 'POST',
        url: "?rand="+ makeid(),
        data: "&imagemgmt="+ server,
        success: function(response) {
            $('#imagemodaltext2').html(response);
            var server = $('#imageserverbuttonsource').html();
            imgdropdown('dir', server, $('#imagedirbutton'+ server +'source').html(), 'source')
        },
    });       
    }
}

function imgdropdown(mode,server,dir,dmode){
    $('#imagedirbutton'+ server +""+ dmode).html(dir);
    if(mode == "server"){
        $('#imageserverbutton'+ dmode).html(server);
        $("[id^=imagedirdropd][id$="+ dmode +"]").addClass('d-none');
        $('#imagedirdropd'+ server +''+ dmode).removeClass('d-none');
    }
    if(dmode == "source"){
        $.ajax({
            type: 'POST',
            url: "?rand="+ makeid(),
            data: "&listdir="+ dir +"&server="+ server,
            success: function(response) {
                $('#listimgd').html(response);
            },
        });
    }
}

function actioncheck(){
    $.ajax({
        type: 'POST',
        url: "?rand="+ makeid(),
        data: "&progress="+ jresponse,
        success: function(response) {
            if (response == "done") {
                cdone = "yes";
            } else {
                if (response == "sorry, no progress available"){
                    $('#imgprogd').html(response);
                }
                if (response == "fail"){
                    cdone = "yes";
                    window.alert("Failed to copy!");
                } else {
                    $('#imgprogbar').val(response);
                    $('#imgprogd').html(response +"%");
                }
            }
        }
    });  
    if (cdone == "yes") {
        $('#imgprog').addClass('d-none');
        $('#imgprogr').addClass('d-none');
        $('#imagemodaltext2').removeClass('d-none');
        $('#imgprogbar').val("0");
        clearInterval(interval);
    }
}

function imgcopy(){
    if ($('#copybtn').html() == "copy"){
        $('#copytargetd').removeClass('d-none');
        $('#copybtn').html("start copy");
        $('#copybtn').removeClass('btn-primary');
        $('#copybtn').addClass('btn-warning');
        $('#newimgdiv').addClass('d-none');
        $('#delimgbutton').addClass('d-none');
    } else {
        var sserver = $('#imageserverbuttonsource').html();
        var sdir = $('#imagedirbutton'+ sserver +"source").html();
        var sfile = $('#ld').val();
        var tserver = $('#imageserverbuttontarget').html();
        var tdir = $('#imagedirbutton'+ tserver +"target").html();
        var tfile = $('#targetfilename').val();
        $.ajax({
            type: 'POST',
            url: "?rand="+ makeid(),
            data: "&copyss="+ sserver +"&copysf="+ sdir +"/"+ sfile +"&copyts="+ tserver +"&copytf="+ tdir +"/"+ tfile,
            success: function(response) {
                jresponse = response;
                if (Number.isInteger(+jresponse)){
                    $('#imgprogr').removeClass('d-none');
                    $('#imgprog').removeClass('d-none');
                    $('#imagemodaltext2').addClass('d-none');
                    interval= setInterval(actioncheck,3000);
                    cdone = "no";
                } else {
                    cdone = "fail";
                    window.alert("FAIL! nana"+ jresponse +"nana");
                }
            },
        });
    }
}

function createimg(){
    var server = $('#imageserverbuttonsource').html();
    var dir = $('#imagedirbutton'+ server +'source').html();
    var imgname = $('#newimg').val();
    var imgsize = $('#newimgsize').val();
    $.ajax({
        type: 'POST',
        url: "?rand="+ makeid(),
        data: "createimgs="+ server +"&createimgd="+ dir +"&createimg="+ imgname +"&createimgsize="+ imgsize,
        success: function(response){
            var imgsuc = new RegExp("createimg completed")
            if (imgsuc.test(response)){
                window.location.href = "";
            } else {
                window.alert("Failure\r "+ response);
            }
        }
    });
}

function genmac(field){
    freemacfound = "no";
    while (freemacfound == "no"){
        var text = "";
        var possible = "abcdef0123456789";
        for (j=0; j < 4; j++){
            text += ":";
            for (var i = 0; i < 2; i++)
                text += possible.charAt(Math.floor(Math.random() * possible.length));
        }
        var newmac = "52:54:00"+ text;
        freemacfound = checkmac(newmac, field);
    }
}

function checkmac(newmac,field){
    $.ajax({
        type: 'POST',
        url: "?rand="+ makeid(),
        data: "checkmac="+ newmac,
        success: function(response){
            if (response == "mac is free"){
                $('#'+ field).val(newmac);
                return newmac;
            } else {
                return "no";
            }
        }
    });
}
