﻿
var ajaxUpload = null;

function initializeDocumentLibrary() {

    if ($("input#allowread").val() == "1") {
        if ($("input#allowadd").val() == "1") {
            registerUploadEvent();
        }
        getURLPrefix();
        getFolderContents("");
    }
}

function getURLPrefix() {
    $.ajax({
        type: "GET",
        async: false,
        timeout: 50000,
        cache: false,
        url: "/DocumentLibrary/GetURLPrefix",
        dataType: "text",
        data: { "ProjectID": getProjectID(), "WebsiteCode": getWebsiteCode() },
        success: function (result) {
            $("input#URLPrefix").val(result);
        },
        error: function (error) {
            $("div#message").text("Error: " + error.statusText);
        }
    });
}

function getFolderContents(parentFolder) {

    if (parentFolder == null) parentFolder = "";
    if (parentFolder == "") parentFolder = $("input#URLPrefix").val();

    $.ajax({
        type: "POST",
        timeout: 50000,
        cache: false,
        url: "/DocumentLibrary/GetFolderContents",
        dataType: "json",
        data: { "ProjectID": getProjectID(), "WebsiteCode": getWebsiteCode(), "ParentFolder": parentFolder },
        beforeSend: function () {
            $("div#message").text("Please wait...");
        },
        complete: function () {
            clearMessage();
        },
        success: function (result) {
            if (ajaxUpload != null) { // it can be null when add or read permissions are not available and hence the method "registerUploadEvent" is not executed
                ajaxUpload.setData({ 'CurrentFolderPath': parentFolder, 'ProjectID': getProjectID(), 'WebsiteCode': getWebsiteCode() });
            }
            $("input#CurrentFolder").val(parentFolder);
            buildFolderNavigationTree(parentFolder);
            loadFolderContents(result);
        },
        error: function (error) {
            $("div#message").text("Error: " + error.statusText);
        }
    });
}

function loadFolderContents(result) {

    $("div#documentlist").empty();
    var count = result.length;
    if (count == 0) {
        $("div#message").text("There are no documents in this folder.");
        return;
    }
    var i = 0;
    for (i = 0; i < count; i++) {

        if (result[i].IsFolder) {
            $("div#documentlist").append("<div class='folder_item'><div class='folder'>" +
                "<a href=\"" + "javascript: getFolderContents('" + result[i].ContentPath + "/');\">" + result[i].ContentName + "</a>" +
                "<div class='button_delete'><a href=\"javascript: deleteFolder('" + result[i].ContentPath + "');\"><img title='Delete' width='16' height='16' alt='Delete' src='/Templates/Common/Content/images/delete.png' /></a></div>" + "</div></div>");
        }
        else {
            var dot = result[i].ContentName.lastIndexOf(".");
            var extension = "default";
            if (dot != -1) {
                extension = result[i].ContentName.substr(dot + 1, result[i].ContentName.length);
            }
            $("div#documentlist").append("<div class='folder_item'><div class='file_" + extension + "'>" +
                "<a href=\"" + "javascript: downloadDocument('" + result[i].ContentPath + "');\">" + result[i].ContentName + "</a>" +
                "<div class='button_delete'><a href=\"javascript: deleteDocument('" + result[i].ContentPath + "');\"><img title='Delete' width='16' height='16' alt='Delete' src='/Templates/Common/Content/images/delete.png' /></a></div></div></div>");
        }

    }
}

function deleteDocument(documentPath) {

    if (documentPath != "") {

        var permission = $("input#allowdelete").val();
        if (permission == "0") {
            alert("You don't have permission to delete this document.");
            return;
        }

        if (confirm("Are you sure you want to delete this file?")) {

            $.ajax({
                type: "POST",
                timeout: 30000,
                cache: false,
                url: "/DocumentLibrary/DeleteDocument",
                dataType: "text",
                data: { "ProjectID": getProjectID(), "WebsiteCode": getWebsiteCode(), "DocumentPath": documentPath },
                beforeSend: function () {
                    $("div#message").text("Please wait...");
                },
                complete: function () {
                    clearMessage();
                },
                success: function (result) {
                    reloadCurrentFolder();
                },
                error: function (error) {
                    $("div#message").text("Error: " + error.statusText);
                }
            });
        }
    }
}

function deleteFolder(folderPath) {

    var permission = $("input#allowdelete").val();
    if (permission == "0") {
        alert("You don't have permission to delete this folder.");
        return;
    }

    if (confirm("Are you sure you want to delete this folder and all its contents?")) {

        $.ajax({
            type: "POST",
            timeout: 90000,
            cache: false,
            url: "/DocumentLibrary/DeleteFolder",
            dataType: "text",
            data: { "ProjectID": getProjectID(), "WebsiteCode": getWebsiteCode(), "FolderPath": folderPath },
            beforeSend: function () {
                $("div#message").text("Please wait...");
            },
            complete: function () {
                clearMessage();
            },
            success: function (result) {
                reloadCurrentFolder();
            },
            error: function (error) {
                $("div#message").text("Error: " + error.statusText);
            }
        });
    }
}

function downloadDocument(documentPath) {

    $.ajax({
        type: "GET",
        timeout: 30000,
        cache: false,
        url: "/DocumentLibrary/DownloadDocument",
        dataType: "text",
        data: { "ProjectID": getProjectID(), "WebsiteCode": getWebsiteCode(), "DocumentPath": documentPath },
        beforeSend: function () {
            $("div#message").text("Please wait...");
        },
        complete: function () {
            clearMessage();
        },
        success: function (result) {
            //window.open(result, "Download Document");
            location.href = result;
        },
        error: function (error) {
            $("div#message").text("Error: " + error.statusText);
        }
    });
}

function buildFolderNavigationTree(CurrentFolder) {

    var prefix = $("input#URLPrefix").val();
    var folders = CurrentFolder.substring(prefix.length);

    // truncating the ending slash
    if (folders.charAt(folders.length - 1) == "/") {
        folders = folders.substring(0, folders.length - 1);
    }

    $("div#documentarea_location").html("Location: <a href=\"javascript: getFolderContents('');\">Top</a>");
    if (folders.length > 0) {
        var folderList = folders.split("/");
        var index = 0;
        for (index = 0; index <= folderList.length - 1; index++) {
            $("div#documentarea_location").html($("div#documentarea_location").html() + " > " + "<a href=\"javascript: getFolderContents('" + prefix + folderList[index] + "');\">" + folderList[index] + "</a>");
        }
    }
}

function registerUploadEvent() {

    ajaxUpload = new AjaxUpload('button_upload', {
        // Location of the server-side upload script
        // NOTE: You are not allowed to upload files to another domain
        action: '/DocumentLibrary/UploadDocument',
        // File upload name
        name: 'somefile',
        // Additional data to send
        data: {
            Username: 'set through getFolderContents()',
            WebsiteCode: 'set through getFolderContents()', 
            CurrentFolderPath: 'set through getFolderContents()'
        },
        // Submit file after selection
        autoSubmit: true,
        // The type of data that you're expecting back from the server.
        // HTML (text) and XML are detected automatically.
        // Useful when you are using JSON data as a response, set to "json" in that case.
        // Also set server response type to text/html, otherwise it will not work in IE6
        responseType: false,
        // Fired after the file is selected
        // Useful when autoSubmit is disabled
        // You can return false to cancel upload
        // @param file basename of uploaded file
        // @param extension of that file
        onChange: function (file, extension) { },
        // Fired before the file is uploaded
        // You can return false to cancel upload
        // @param file basename of uploaded file
        // @param extension of that file
        onSubmit: function (file, extension) {
            if (fileExists(file)) {
                alert("A file with the name '" + file + "' already exists.");
                return false;
            }
            if ((extension && /^(exe|vbs|bat|com)$/i.test(extension))) {
                alert('This type of file is now allowed.');
                return false;
            }
            $("div#message").text("Please wait...");
        },
        // Fired when file upload is completed
        // WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!
        // @param file basename of uploaded file
        // @param response server response
        onComplete: function (file, response) {
            reloadCurrentFolder();
        }
    });
}

function reloadCurrentFolder() {
    var currentFolder = $("input#CurrentFolder").val();
    getFolderContents(currentFolder);
}

function createFolder() {

    var folderName = prompt("Please provide folder name", "");
    if (folderName != null && folderName != "") {

        if (!folderExists(folderName)) {

            var folderPath = $("input#CurrentFolder").val() + folderName;

            $.ajax({
                type: "POST",
                timeout: 30000,
                cache: false,
                url: "/DocumentLibrary/CreateFolder",
                dataType: "text",
                data: { "ProjectID": getProjectID(), "WebsiteCode": getWebsiteCode(), "FolderPath": folderPath },
                beforeSend: function () {
                    $("div#message").text("Please wait...");
                },
                complete: function () {
                    clearMessage();
                },
                success: function (result) {
                    reloadCurrentFolder();
                },
                error: function (error) {
                    $("div#message").text("Error: " + error.statusText);
                }
            });
        }
        else
            alert("A folder with the name '" + folderName + "' already exists.");
    }
}

function folderExists(folderName) {

    return $("#documentlist").children("div:contains('" + folderName.toLowerCase() + "')").length > 0;

}

function fileExists(fileName) {

    return $("#documentlist").children("div:contains('" + fileName.toLowerCase() + "')").length > 0;
}

function clearMessage() {
    if ($("div#message").text() != "There are no documents in this folder.") {
        $("div#message").text("");
    }
}

function getProjectID() {
    var pid = $("input#projectid").val();
    return pid;
}

function getWebsiteCode() {
    var wsc = $("input#websitecode").val();
    return wsc;
}
