
var currentDir = $("#dir").val();

function updateDir() {
    currentDir = $("#dir").val();//
    $.address.value(currentDir);
}

function openFile(name, is_dir) {
    currentDir = (currentDir.charAt(currentDir.length-1) == '/')?currentDir.substr(0, currentDir.length-1):currentDir;
    if (is_dir == "true") {
        currentDir = currentDir + "/" + name;//
        $.address.value(currentDir);
    } else {
        window.location.href = getParentDir($.address.baseURL()) + "/browse/open" + currentDir + "/" + name;
    }
}

function getParentDir(currentDir) {
    currentDir = (currentDir.charAt(currentDir.length-1) == '/') ? currentDir.substr(0, currentDir.length-1):currentDir;
    var parentDir = currentDir.substring(0, currentDir.lastIndexOf("/"));
    if (parentDir == "") parentDir = "/";
    return parentDir;
}

function parentDir() {
    var parentDir = getParentDir(currentDir);
    currentDir = parentDir;//
    $.address.value(parentDir);
}

function deleteFile(name) {
    var url = "browse/del" + currentDir + "/" + name;
    $.ajax({
        url: url,
        type: "DELETE",
        success: getFileList,
        statusCode: {
            405: function() {
                alert("Directory not empty");
            },
            403: function() {
                alert("Access denied");
            },
            404: function() {
                alert("File not found");
            },
            500: function() {
                alert("Delete file error")
            }
        }
    });
}

function mkdir(name) {
    var url = "browse/create" + currentDir + "/" + name;
    $.ajax({
        url: url,
        type: "PUT",
        success: getFileList,
        statusCode: {
            409: function() {
                alert("Directory already exists");
            },
            500: function() {
                alert("Create directory error")
            }

        }
    });
}

function upload(formData) {
    var url = "browse/upload" + currentDir;
    $.ajax({
        url: url,
        type: "POST",
        data: formData,
        contentType: false,
        processData: false,
        success: getFileList,
        statusCode: {
            500: function() {
                alert("Upload file error")
            }
        }
    });
}

function refreshFileList(fileList, status, jqXHR) {
    var len = fileList.length;
    var contentDiv = $("#content");
    if (len != 0) {
        var table = $('<table>');
        for (var i = 0; i < len; i++) {
            if(!fileList[i].hidden) {
                var row = $('<tr>')
                var name = fileList[i].filename;
                var dir = fileList[i].dir;
                if (dir) {
                    row.append('<td class="file_dir"><figure><img class="file_image" src="image/folder.png" height="15" width="19" alt='+ dir +'></figure></td>');
                } else {
                    row.append('<td class="file_dir"><figure><img class="file_image" src="image/file.png" height="15" width="19" alt='+ dir +'></figure></td>');
                }
//                row.append('<td class="file_name">' + name + '</td>');
//                var openButtonDivision = $('<td><input type="button" class="file_open" value="open" name="' + name + '"/></td>');
                var openButtonDivision = $('<td><input type="button" class="file_open" size="10" value=' + name + '></td>');//
                var openButton = openButtonDivision.find("input");
                row.append(openButtonDivision);
                openButton.attr("disabled", !fileList[i].canRead);
//                var delButtonDivision = $('<td><input type="button" class="file_delete" value="delete" name="' + name + '"/></td>');
                var delButtonDivision = $('<td><input type="image" class="file_delete" src="image/delete.png" height="15" width="15"/></td>');//
                var delButton = delButtonDivision.find("input");
                row.append(delButtonDivision);
                delButton.attr("disabled", !fileList[i].canDelete);
                table.append(row);
            }
        }
        contentDiv.html(table);
    } else {
        showFileListError("Empty Folder");
    }
}

function getFileList() {
    var url = "browse/list" + currentDir;
    $.ajax({
        url: url,
        type: "GET",
        success: refreshFileList,
        statusCode: {
            403: function() {
                showFileListError("Access denied");
            },
            404: function() {
                showFileListError("File not found");
            },
            500: function() {
                showFileListError("Access error");
            }
        }
    });
}

function showFileListError(message) {
    $("#content").html("<table><th>" + message + "</th></table>");
}

$(document).ready(function() {
    updateDir();

    var triggers = $(".newDirInput").overlay({
        mask: {
            color: '#ebecff',
            loadSpeed: 200,
            opacity: 0.9
        },

        closeOnClick: false
    });

    $("#dirPrompt form").submit(function(e) {
        triggers.overlay().close();
        var input = $("input", this).val();
        if (input != "") {
            mkdir(input);
        }
        return e.preventDefault();
    });

    var triggers2 = $(".uploadInput").overlay({
        mask: {
            color: '#ebecff',
            loadSpeed: 200,
            opacity: 0.9
        },

        closeOnClick: false
    });

    $("#uploadPrompt form").submit(function(e) {
        triggers2.overlay().close();
        var formData = new FormData($(this)[0]);
        var input = $("input", this).val();
        if (input != "") {
            upload(formData);
        }
        return e.preventDefault();
    });

    $(".file_delete").live("click", function() {
        if (confirm("Are you sure you want to delete the file?")) {
//            var filename = $(this).closest("tr").find(".file_name").text();
            var filename = $(this).closest("tr").find(".file_open").val();
            deleteFile(filename);
        }
    });

    $(".file_open").live("click", function() {
        var is_dir = $(this).closest("tr").find(".file_image").attr("alt");
//        var filename = $(this).closest("tr").find(".file_name").text();
        var filename = $(this).val();//
        openFile(filename, is_dir);
    });

    $.address.change(function(event) {
        $("#dir").val(event.value);
        getFileList(event.value);
    });
});
