// Preload spinner2 image
var spinner2 = document.createElement('IMG');
spinner2.src = imgDir + '/loading.gif';
spinner2.style.height = '24px';
spinner2.style.width = '24px';

// Catch address bar change
function checkURL(timeout){
    if((getURLPath() || $('list').path != '/') && getURLPath() != $('list').path){
        if($('overlayBG')){
            closeOverlay();
        }
        showSpinner2();
        checkList = new Array();
        currentPage = 0;
        $('checkall').checked = false;
        loadDir(getURLPath());
    }else{
        window.checkURLTimer = window.setTimeout("checkURL("+timeout+")", timeout);
    }
}

// Filemanager functions
var checkList = new Array();
var searched = false;
var currentPage = 0;
var showHome = false;

function fileSearch(string){
    if(!$('list') || !string){
        return false;
    }

    showSpinner2();
    checkList = new Array();

    window.clearTimeout(window.checkURLTimer);
    doCallback(WEB_ROOT + "/ajax.php?mode=search&q="+escape(string), parseFiles, 'POST');
}

function loadDir(path, keepChecked){
    var container = $('list');
    if(!container){
        return false;
    }

    window.clearTimeout(window.checkURLTimer);

    path = path || getPath();

    if(path != getPath() && !keepChecked){
        checkList = new Array();
        $('checkall').checked = false;
        currentPage = 0;
    }

    doCallback(WEB_ROOT + "/ajax.php?mode=ls&perm="+(1*!!showPerm)+"&path="+escape(path), parseFiles, 'POST');
}

function parseFiles(response){
    var container = $('list');

    if(!response){
        setStatus("Communication error!", true);
        return false;
    }
    if(response == 'AUTH'){
        if($('loginMenuLink')){
            createCookie("last_path", getPath(), 30);
            showSpinner2();
            createOverlay($('loginMenuLink').href, null, null, function(response){if(response === false)loadDir('/');});
            return false;
        }else{
            logout();
            return false;
        }
    }
    if(response.indexOf('Error opening "') == 1){
        setStatus(response, true);
        loadDir(readCookie('last_path'));
        return false;
    }

    response = response.split("\n\/\/\/\n");

    if(response[0].substr(0, 1) == '/'){
        path = response[0];
        container.path = path;
        document.location.hash = path;
        createCookie("last_path", path, 30);

        if(searched != 2){
            searched = false;
        }
    }else{
        searched = 1;
    }

    showPerm = parseInt(response[1]);

    var dirs = response[2].split("\n\/\/\n");
    if(response[3]){
        var files = response[3].split("\n\/\/\n");
    }else{
        var files = null;
    }

    for(var i = 0; i < dirs.length; i++){
        dirs[i] = dirs[i].split("\n");
    }
    if(files){
        for(i = 0; i < files.length; i++){
            files[i] = files[i].split("\n");
        }
    }

    if(searched == 1 && !files && (dirs.length == 2 + showHome)){
        setStatus("Your search returned no results.", true);
        searched = false;
        displayFiles();
    }else{
        if(searched == 1){
            $('title').innerHTML = "Search results for \"" + response[0].substr(1) + "\"";
        }else{
            if(path.indexOf('..') < 0){
                var titleLink = document.createElement('A');
                titleLink.href = dirPrefix + path;
                titleLink.target = "_blank";
                titleLink.title = "Open " + shortenPath(path, 1).substr(1) + " in a new window";
                titleLink.innerHTML = shortenPath(path, 3, true);
                $('title').innerHTML = "Index of ";
                $('title').appendChild(titleLink);
            }else{
                $('title').innerHTML = "Index of " + shortenPath(path, 3, true);
            }
        }
        container.items = (files) ? dirs.concat(files) : dirs;
        displayFiles(true);
    }
}

function displayFiles(animate){
    var container = $('list');
    if(!container || !container.items){
        return false;
    }

    window.clearTimeout(window.checkURLTimer);

    var list = sortFiles();
    if(searched == 2){
        currentPage = Math.ceil((list.find(checkList[0], 0) - 2) / perPage) - 1;
        searched = false;
    }

    if(animate){
        lockListSize();
    }

    clearFiles();

    $('path').value = container.path;
    document.title = defaultTitle + ' - ' + shortenPath(container.path, 1, false);
    showHome = false;

    $('sort_T').style.display = (showPerm) ? '' : 'none';

    if(list.length <= perPage + 2 + Number(showHome)){
        currentPage = 0;
    }

    for(var i = 0; i < list.length && i < (currentPage + 1) * perPage + (2 + Number(showHome)); i++){
        var writable = list[i][1].indexOf(" (not writable)") < 0;
        var readable = (list[i][5] && list[i][5] != "DENIED") || !list[i][5] && list[i][1] != 'Broken link' && list[i][1].indexOf("no read permission") < 0;
        var is_link = (list[i][1].indexOf("(") == 0 || list[i][1].indexOf("[") == 0);
        var renameButton = false;
        var deleteButton = false;

        var TR = document.createElement('TR');
            var checkTD = document.createElement('TD');
            checkTD.style.textAlign = 'left';
                var check = document.createElement('INPUT');
                check.type = 'checkbox';
                check.className = 'check';
                check.id = (list[i][5]) ? 'dir_' + i : 'file_' + i ;
                check.value = list[i][0];
                if(!writable){
                    check.disabled = 'true';
                }else{
                    check.checkId = check.id;
                    check.onclick = checkToggle;
                }
            checkTD.appendChild(check);
            var nameTD = document.createElement('TD');
            nameTD.style.textAlign = 'left';
                var nameIMG = document.createElement('IMG');
                var fullpath = list[i][0];
                var iconText = fullpath;
                if(searched && !list[i][5]){
                    fullpath = list[i][1];
                    iconText = list[i][0];
                }else if(is_link){
                    fullpath = list[i][1].substr(1, list[i][1].length - 2);
                    iconText = fullpath;
                }
                nameIMG.src = (list[i][1] == 'Broken link') ? imgDir + '/x.png' : icon(iconText, list[i][5]);
                var name = document.createElement('A');
                if(readable && !list[i][5]){
                    name.href = WEB_ROOT + '/read.php/' + list[i][0];
                    name.target = '_blank';
                    name.checkId = check.id;
                    if(searched){
                        name.path = fullpath;
                    }
                    name.onclick = fileOnClick;
                }else if(readable && list[i][5]){
                    name.href = '#' + list[i][5];
                    name.link = list[i][5];
                    name.onclick = dirOnClick;
                }
                name.title = (is_link) ? 'Link to "' + fullpath + '"' : list[i][1];
                name.appendChild(nameIMG);
                if(is_link){
                    name.style.fontStyle = 'italic';
                }
                if(list[i][0] == '.'){
                    name.appendChild(document.createTextNode(' Current Directory'));
                    name.style.fontWeight = 'bold';
                }else if(list[i][0] == '..'){
                    name.appendChild(document.createTextNode(' Parent Directory'));
                    name.style.fontWeight = 'bold';
                }else if(list[i][0] == '...'){
                    showHome = true;
                    name.appendChild(document.createTextNode(' Home Directory'));
                    name.style.fontWeight = 'bold';
                }else{
                    name.appendChild(document.createTextNode(' ' + list[i][0]));
                }
                if(AUTH && writable && list[i][0] != '...' && list[i][0] != '..' && list[i][0] != '.'){
                    deleteButton = document.createElement('A');
                    var deleteImg = document.createElement('IMG');
                    deleteButton.checkId = check.id;
                    deleteButton.onclick = checkToggle;
                    deleteButton.className = "lsImgButton";
                    deleteButton.href = "javascript:confirmDelete('" + list[i][0].replace(/\'/g, "\\'") + "');";
                    deleteButton.title = "Delete " + list[i][0];
                    deleteImg.src = imgDir + '/delete.png';
                    deleteButton.appendChild(deleteImg);

                    renameButton = document.createElement('A');
                    var renameImg = document.createElement('IMG');
                    renameButton.checkId = check.id;
                    renameButton.onclick = checkToggle;
                    renameButton.className = "lsImgButton";
                    renameButton.href = "javascript:renameDialog('" + list[i][0].replace(/\'/g, "\\'") + "', " + !!(list[i][5]) + ");";
                    renameButton.title = "Rename " + list[i][0];
                    renameImg.src = imgDir + '/rename.png';
                    renameButton.appendChild(renameImg);
                }
                if(AUTH && readable && !list[i][5] && (list[i][1] == 'application/x-empty' || list[i][1].indexOf('text/') > -1 || list[i][1] == "application/x-perl" || list[i][1].indexOf('script') > -1)){
                    var editButton = document.createElement('A');
                    var editImg = document.createElement('IMG');
                    var editPath = (searched) ? fullpath : container.path;
                    var key = MD5(editPath + list[i][0] + (readCookie('user') || ''));
                    editButton.target = '_blank';
                    editButton.checkId = check.id;
                    editButton.onclick = checkToggle;
                    editButton.className = 'lsImgButton';
                    if(list[i][1] == 'application/x-empty'){
                        editButton.href = WEB_ROOT + '/edit.php?file=' + escape(list[i][0]) + '&path=' + editPath + '&key=' + key;
                        editButton.title = 'Edit ' + list[i][0];
                    }else{
                        editButton.href = WEB_ROOT + '/read.php?file=' + list[i][0] + '&path=' + editPath + '&key=' + key;
                        editButton.title = 'View ' + list[i][0];
                    }
                    editImg.src = imgDir + '/edit.png';

                    editButton.appendChild(editImg);
                }
                if((!editButton && readable && list[i][1].indexOf("(") == 0) || (searched && !list[i][5])){
                    var linkButton = document.createElement('A');
                    var linkImg = document.createElement('IMG');
                    linkButton.link = fullpath;
                    if(!list[i][5]){
                        linkButton.link = linkButton.link.substr(0, linkButton.link.lastIndexOf('/') + 1);
                    }
                    linkButton.onclick = dirOnClick;
                    linkButton.className = 'lsImgButton';
                    linkButton.href = '#' + linkButton.link;
                    linkButton.title = 'Go to "' + linkButton.link + '"';
                    linkImg.src = imgDir + '/next.png';
                    if(searched){
                        linkButton.checked = list[i][0];
                    }

                    linkButton.appendChild(linkImg);
                    linkButton.appendChild(document.createTextNode(' '));
                }
                var buttonDiv = document.createElement('DIV');
                buttonDiv.className = "lsButtonDiv";
            if(linkButton){
                buttonDiv.appendChild(linkButton);
                linkButton = false;
            }
            if(editButton){
                buttonDiv.appendChild(editButton);
                editButton = false;
            }
            if(renameButton){
                buttonDiv.appendChild(renameButton);
                renameButton = false;
            }
            if(deleteButton){
                buttonDiv.appendChild(deleteButton);
                deleteButton = false;
            }
            if(buttonDiv.innerHTML){
                nameTD.appendChild(buttonDiv);
            }
            nameTD.appendChild(name);
            var sizeTD = document.createElement('TD');
            sizeTD.style.textAlign = 'right';
            sizeTD.innerHTML = list[i][2] != '?' ? byteUnit(list[i][2]) : '';
            var timeTD = document.createElement('TD');
            var time = new Date(list[i][3] * 1000);
            timeTD.innerHTML = time.formatDate(timeFormat);
            timeTD.title = time.formatDate(defaultClockFormat);
            if(showPerm){
                var permTD = document.createElement('TD');
                permTD.innerHTML = readPerm(list[i][4]);
            }
        if((i == 1 && !showHome) || (i == 2 && showHome) || (i == 0 && showHome)){
                checkTD.className = 'lsdivider';
                nameTD.className = 'lsdivider';
                sizeTD.className = 'lsdivider';
                timeTD.className = 'lsdivider';
                if(showPerm){
                    permTD.className = 'lsdivider';
                }
        }
        TR.appendChild(checkTD);
        TR.appendChild(nameTD);
        TR.appendChild(sizeTD);
        TR.appendChild(timeTD);
        if(showPerm){
            TR.appendChild(permTD);
        }
        TR.id = (searched) ? "row_" + i : "row_" + list[i][0];
        TR.className = 'ls';
        check.checked = (checkList.find(check.value) !== false);
        if(check.checked){
            TR.className += ' lschecked';
        }
        TR.checkId = check.id;
        TR.onclick = checkToggle;

        if(!list[i][5]){
            TR.onmouseover = fileOnMouseOver;
            TR.onmouseout = fileOnMouseOut;
        }else{
            TR.onmouseover = dirOnMouseOver;
            TR.onmouseout = dirOnMouseOut;
            TR.writable = writable;
            TR.dirname = list[i][5];
        }

        if(!searched && readable && list[i][0] != '...' && list[i][0] != '..' && list[i][0] != '.'){
            makeDraggable(TR, $('dragList'), null, fillDragList, firstMoveDragList, dropDragList, true, {x:-8, y:8});
        }else if(readable){
            TR.style.cursor = "default";
        }

        container.tBodies[0].appendChild(TR);

        if(dragObject){
            var dragList = $('dragList');

            if(dragList.action == 'move' && dragList.fromDir == container.path){
                if(dragList.fileList.find(list[i][0]) !== false){
                    TR.style.display = 'none';
                }
            }
        }

        if(showAnimations && animate && TR.style.display != 'none'){
            TR.style.display = 'none';
            fade(TR.id, 1, .08);
        }

        if(list[i][0] == '.' && currentPage != 0){
            i = currentPage * perPage + 1 + showHome;
        }
    }

    if(list.length - 2 - showHome > perPage){
        var pages = Math.ceil((list.length - 2 - showHome) / perPage);
        var pagesToShow = 13;
        var prevPageText = "Last " + perPage;
        var nextPageText = "Next " + perPage;

        var TR = document.createElement("TR");
        var TD = document.createElement("TD");
          TD.colSpan = 5;
          TD.id = "pageNav";

        var prevPageDiv = document.createElement("DIV");
        prevPageDiv.id = "pageNavPrev";

        var nextPageDiv = document.createElement("DIV");
        nextPageDiv.id = "pageNavNext";

        if(currentPage == 0){
            var prevPage = document.createTextNode(prevPageText);
            prevPageDiv.style.color = "#CCC";
        }else{
            var prevPage = document.createElement("A");
            prevPage.innerHTML = prevPageText;
            prevPage.href = "javascript:void(0)";
            prevPage.onclick = function(){currentPage--;displayFiles(true);};
        }
        if(currentPage == pages - 1){
            var nextPage = document.createTextNode(nextPageText);
            nextPageDiv.style.color = "#CCC";
        }else{
            var nextPage = document.createElement("A");
            nextPage.innerHTML = nextPageText;
            nextPage.href = "javascript:void(0)";
            nextPage.onclick = function(){currentPage++;displayFiles(true);};
        }

        prevPageDiv.appendChild(document.createTextNode("< "));
        prevPageDiv.appendChild(prevPage);
        nextPageDiv.appendChild(nextPage);
        nextPageDiv.appendChild(document.createTextNode(" >"));

        var pageIndex = document.createElement("SPAN");
        pageIndex.innerHTML = "[ ";

        var i = 0;
        var j = 0;

        if(pages > pagesToShow && currentPage > Math.floor(pagesToShow / 2) + 1){
            if(currentPage == 0){
                var a = document.createElement("SPAN");
                a.innerHTML = 1;
                a.style.fontWeight = 'bold';
            }else{
                var a = document.createElement("A");
                a.innerHTML = 1;
                a.href = "javascript:void(0)";
                a.onclick = function(){currentPage = 0;displayFiles(true);};
            }

            pageIndex.appendChild(a);
            pageIndex.appendChild(document.createTextNode('... '));
            i = Math.max(1, Math.min(pages - pagesToShow, currentPage - Math.floor(pagesToShow / 2)));
        }

        for(i; i < pages && j < pagesToShow + (currentPage + 1 == pages - Math.ceil(pagesToShow / 2)); i++){
            if(currentPage == i){
                var a = document.createElement("SPAN");
                a.innerHTML = (i + 1);
                a.style.fontWeight = 'bold';
            }else{
                var a = document.createElement("A");
                a.innerHTML = (i + 1);
                a.pageNum = i;
                a.href = "javascript:void(0)";
                a.onclick = function(){currentPage = this.pageNum;displayFiles(true);};
            }

            pageIndex.appendChild(a);
            pageIndex.appendChild(document.createTextNode(' '));
            j++;
        }

        if(pages > pagesToShow && currentPage < pages - Math.ceil(pagesToShow / 2) - 1){
            if(currentPage == pages - 1){
                var a = document.createElement("SPAN");
                a.innerHTML = pages;
                a.style.fontWeight = 'bold';
            }else{
                var a = document.createElement("A");
                a.innerHTML = pages;
                a.href = "javascript:void(0)";
                a.onclick = function(){currentPage = pages - 1;displayFiles(true);};
            }

            pageIndex.appendChild(document.createTextNode('...'));
            pageIndex.appendChild(a);
        }

        pageIndex.appendChild(document.createTextNode(']'));

        TD.appendChild(prevPageDiv);
        TD.appendChild(nextPageDiv);
        TD.appendChild(pageIndex);
        TR.appendChild(TD);
        container.tBodies[0].appendChild(TR);
    }

    if(animate){
        easeListSize();
    }

    checkURL(500);
}

function fileOnMouseOver(){
    if(dragObject){
        $('dragList').toDir = $('list').path;
        $('row_.').className += ' lshover';
    }else{
        this.className += ' lshover';
    }
}

function dirOnMouseOver(){
    this.className += ' lshover';
    this.oldcursor = this.style.cursor;
    if(dragObject){
        var dragList = $('dragList');
        if(!this.writable){
            dragList.toDir = null;
            this.style.cursor = 'no-drop';
        }else if(dragList.toDir != this.dirname){
            dragList.toDir = this.dirname;
            window.dragDir = window.setTimeout("if(dragObject && \"" + this.dirname + "\"!= $('list').path)loadDir(\"" + this.dirname + "\")", 1000);
        }
    }
}

function fileOnMouseOut(){
    this.className = this.className.replace(' lshover', '');
    var currentDir = $('row_.');
    if(currentDir){
        currentDir.className = currentDir.className.replace(' lshover', '');
    }

    if(dragObject){
        $('dragList').toDir = null;
    }
}

function dirOnMouseOut(){
    this.className = this.className.replace(' lshover', '');

    this.style.cursor = this.oldcursor;
    window.clearTimeout(window.dragDir);
    if(dragObject){
        $('dragList').toDir = null;
    }
}

function fileOnClick(){
    checkToggle(this.checkId);
    if(this.path){
        createCookie('last_path', this.path, 30);
    }else{
        createCookie('last_path', $('list').path, 30);
    }
}

function dirOnClick(){
    showSpinner2();
    if(this.checked){
        searched = 2;
        checkList = new Array(this.checked);
    }
    loadDir(this.link, !!this.checked);
}

function clearFiles(){
    var container = $('list');
    if(!container){
        return false;
    }

    container.style.height = '';
    lockListSize();

    while(container.getElementsByTagName('TR').length != 1){
        container.tBodies[0].deleteRow(1);
    }
}

function lockListSize(){
    var main = $('container');
    if(!showAnimations || !main){
        return false;
    }

    if($('list').getElementsByTagName('TR').length == 1){
        main.style.height = main.offsetHeight + parseInt(spinner2.style.height) + 'px';
    }else{
        main.style.height = main.offsetHeight + 'px';
    }
}

function easeListSize(noRestore, duration){
    var main = $('container');
    var list = $('list');
    if(!list){
        return false;
    }
    if(!main){
        return false;
    }

    duration = duration || .2;

    var oldHeight = main.offsetHeight + 'px';
    var newHeight = list.offsetHeight + $('title').offsetHeight + 'px';

    if(!noRestore){
        var end = function(){$('container').style.height='';};
    }

    stretch('container', [null, oldHeight], [null, newHeight], 0, 0, duration, 0, 'out', '', end, 4);
}

function linkLoadDir(){
    showSpinner2();
    loadDir(this.link);
}

function getChecked(){
    var form = $('listForm');
    if(!form){
        return false;
    }

    var inputs = form.elements;
    var checked = new Array();
    for(var i = 0; i < inputs.length; i++){
        if(inputs[i].type == 'checkbox' && inputs[i].id != 'checkall' && inputs[i].checked){
            var row = (ie) ? inputs[i].parentElement.parentElement : inputs[i].parentNode.parentNode;

            if(row.style.display != 'none'){
                checked[checked.length] = row;
            }
        }
    }

    if(checked.length){
        return checked;
    }else{
        return false;
    }
}

function showSpinner2(){
    var list = $('list').tBodies[0];
    var container = $('container');
    var title = $('title');
    if(!list || !title || !container){
        return false;
    }

    clearFiles();

    $('list').style.height = "100%";
    var TR = document.createElement('TR');
    var TD = document.createElement('TD');
    TD.style.height = spinner2.style.height;
    TD.colSpan = 5;
    TD.appendChild(spinner2);
    TR.appendChild(TD);
    TR.style.height = "100%";
    list.appendChild(TR);
}

function getURLPath(){
    return document.location.hash.substr(1);
}

function getPath(){
    if(getURLPath()){
        return getURLPath();
    }else{
        return readCookie('last_path');
    }
}

// Checks if file is the user's home directory
function is_home(file){
    return (file == '...' || (file == '.' && $('list').path == homeDir) || (file == '..' && parentDir($('list').path) == homeDir));
}

function icon(file, isDir){
    var icon = iconDir + '/misc';
    var path = $('list').path;

    if(isDir){
        if(isDir == 'DENIED'){
            icon = imgDir + "/folderl.png";
        }else if(is_home(file)){
            icon = (file == '..') ? imgDir + "/gohome.png" : imgDir + "/home.png";
        }else if(file == ".."){
            icon = imgDir + "/up.png";
        }else if(file == "."){
            icon = imgDir + "/folderc.png";
        }else{
            icon = imgDir + "/folder.png";
        }
    }else{
        var ext = file.substr(file.lastIndexOf('.') + 1).toLowerCase();

        for(var i in icons){
            if(icons[i] == ext){
                icon = iconDir + "/" + ext;
            }
        }
    }

    return icon;
}


// File manager dragging functions
function fillDragList(item, ev){
    var dragList = $('dragList');

    if(!dragList || !dragObject){
        return false;
    }

    dragObject.ok = false;
    window.clearTimeout(window.dragListDelay);
    window.dragListDelay = window.setTimeout("if(dragObject)dragObject.ok = true;", 300);

    var checked = sortCheckList(checkList);
    var as = item.getElementsByTagName('A');
    var dragItem = as[as.length - 1];
    var is_link = (dragItem.style.fontStyle == "italic");
    dragItem = dragItem.innerHTML;
    var itemText = dragItem.substr(dragItem.lastIndexOf(">") + 2);
    dragList.fileList = new Array();
    dragList.innerHTML = '';
    dragList.style.textAlign = 'left';
    var height = ($('list').getElementsByTagName('TR')[1].offsetHeight - 1 - (1 * !ie)) + 'px';

    var action = (ev.shiftKey) ? "link" : ((ev.ctrlKey) ? "copy" : "move");

    var dragAction = document.createElement('SPAN');
    dragAction.innerHTML = "&nbsp;&nbsp;" + action + "&nbsp;&nbsp;";

    dragAction.id = "dragAction";
    dragAction.className = "dragAction";
    dragList.appendChild(dragAction);

    dragList.appendChild(document.createElement("P"));

    if(checked.length && checked.find(itemText) !== false){
        var max = 10;
        var items = $('list').items;
        checked = checkList;
        dragList.fileList = checked;
        var countOffset = 0;
        for(var i = 0; i < checked.length; i++){
            if(i < max + countOffset){
                var item = items[items.find(checked[i], 0)];

                if(item[0] == '.' || item[0] == '..' || item[0] == '...'){
                    countOffset++;
                    continue;
                }

                var div = document.createElement('DIV');
                var img = document.createElement('IMG');

                var iconText = item[0];
                if(searched && !item[5]){
                    iconText = item[0];
                }else if(item[1].indexOf("(") == 0 || item[1].indexOf("[") == 0){
                    div.style.fontStyle = 'italic';
                    iconText = item[1].substr(1, item[1].length - 2);
                }
                img.src = (item[1] == 'Broken link') ? imgDir + '/x.png' : icon(iconText, item[5]);

                div.appendChild(img);
                div.appendChild(document.createTextNode(' ' + checked[i]));
                div.className = 'link';
                div.style.textAlign = 'left';
                div.style.height = height;
                div.style.padding = 0;
                div.style.margin = 0;
                dragList.appendChild(div);
                $(div).setStyle({opacity: (1 - (i - countOffset) / max)});
            }
        }
    }else{
        var div = document.createElement('DIV');
        div.innerHTML = dragItem;
        div.className = 'link';
        div.style.textAlign = 'left';
        div.style.height = height;
        div.style.padding = 0;
        div.style.margin = 0;
        if(is_link){
            div.style.fontStyle = "italic";
        }
        dragList.appendChild(div);
        dragList.fileList = new Array(itemText);
    }

    dragList.fromDir = $('list').path;
    dragList.toDir = dragList.fromDir;
    dragList.action = action;
    document.body.style.cursor = 'no-drop';
}

function firstMoveDragList(){
    var dragList = $('dragList');
    if(!dragList || !dragObject || !dragObject.ok){
        return false;
    }

    for(var i = 0; i < 3; i++){
        var box = $('dir_' + i);
        if(box && box.checked && (box.value == '...' || box.value == '..' || box.value == '.')){
            box.checked = false;
            dl(box);
            checkList.splice(checkList.find(box.value), 1);
        }
    }

    if(dragList.action == 'move'){
        lockListSize();

        if(dragList.fileList.length){
            for(var i = 0; i < dragList.fileList.length; i++){
                if($("row_" + dragList.fileList[i])){
                    $("row_" + dragList.fileList[i]).style.display = 'none';
                }
            }
        }else{
            $(dragList.item).style.display = 'none';
        }

        easeListSize();
    }

    //fade('dragList', 1, .05);
    dragList.style.display = '';
    dragList.style.opacity = 1;

    if(typeof(document.onkeydown) == 'function'){
        dragList.oldkeydown = document.onkeydown;
    }
    if(typeof(document.onkeyup) == 'function'){
        dragList.oldkeyup = document.onkeyup;
    }
    if(typeof(document.onkeypress) == 'function'){
        dragList.oldkeypress = document.onkeypress;
    }

    document.onkeydown = dragListKeyPress;
    document.onkeyup = dragListKeyPress;
    document.onkeypress = null;

    dragObject.moveFunction = null;
}

function dropDragList(){
    document.body.style.cursor = '';

    var dragList = $('dragList');
    if(!dragList || !dragObject || !dragObject.ok){
        return false;
    }

    if(dragList.action == 'move' && $('list').path == dragList.fromDir && (dragList.toDir == null || dragList.toDir == dragList.fromDir)){
        lockListSize();

        for(var i = 0; i < dragList.fileList.length; i++){
            var row = $("row_" + dragList.fileList[i]);
            if(row && row.style.display == 'none'){
                if(showAnimations){
                    fade("row_" + dragList.fileList[i], 1, .2);
                }else{
                    row.style.display = '';
                }
            }
        }

        easeListSize();
    }

    fade('dragList', 0, .1);

    if(typeof(dragList.oldkeydown) == 'function'){
        document.onkeydown = dragList.oldkeydown;
    }else{
        document.onkeydown = null;
    }
    if(typeof(dragList.oldkeyup) == 'function'){
        document.onkeyup = dragList.oldkeyup;
    }else{
        document.onkeyup = null;
    }
    if(typeof(dragList.oldkeypress) == 'function'){
        document.onkeypress = dragList.oldkeypress;
    }else{
        document.oldkeypress= null;
    }

    if(dragList.toDir != null && (dragList.action != 'move' || dragList.toDir != dragList.fromDir)){
        confirmDrag(dragList.fileList, dragList.action, dragList.fromDir, dragList.toDir);
    }else if($('list').path != dragList.fromDir){
        loadDir(dragList.fromDir, true);
    }
}

function mclCallback(response){
    var dragList = $('dragList');

    if(response){
        if(response.substr(0, 3) == "OK\n"){
            setStatus(response.substr(3));
            if($('list').path == dragList.toDir){
                loadDir(null, true);
            }else{
                loadDir();
            }
        }else if(parseInt(response.substr(0, 1))){
            var response = response.split('\n');
            var duplicates = response[0];
            var file = response[1];
            var request = response[2];
            var title = dragList.action.substr(0, 1).toUpperCase() + dragList.action.substr(1);
            var text = "<p>A file named \"" + file + "\" already exists.";
            if(duplicates > 1){
                text += "<br>(There are " + duplicates + " total conflicting file names.)</p>";
                text += "<center><table><tr>";
                text += "<td style='text-align:left'><input type='radio' class='check' name='action' id='mcl_rename' value='rename' checked='checked'>\n";
                text += "<label for='mcl_rename'>Rename</label></td>";
                text += "<td style='text-align:left'><input type='radio' class='check' name='action' id='mcl_rename_all' value='rename_all'>\n";
                text += "<label for='mcl_rename_all'>Rename all</label></td>";

                text += "</tr><tr>";

                text += "<td style='text-align:left'><input type='radio' class='check' name='action' id='mcl_overwrite' value='overwrite'>\n";
                text += "<label for='mcl_overwrite'>Overwrite</label></td>";
                text += "<td style='text-align:left'><input type='radio' class='check' name='action' id='mcl_overwrite_all' value='overwrite_all'>\n";
                text += "<label for='mcl_overwrite_all'>Overwrite all</label></td>";

                text += "</tr><tr>";
                
                text += "<td style='text-align:left'><input type='radio' class='check' name='action' id='mcl_skip' value='skip'>\n";
                text += "<label for='mcl_skip'>Skip</label></td>";
                text += "<td style='text-align:left'><input type='radio' class='check' name='action' id='mcl_skip_all' value='skip_all'>\n";
                text += "<label for='mcl_skip_all'>Skip all</label></td>";
                text += "</tr></table></center>";
            }else{
                text += "</p>";
                text += "<p><input type='radio' class='check' name='action' id='mcl_rename' value='rename' checked='checked'>\n";
                text += "<label for='mcl_rename'>Rename</label>";

                text += "&nbsp;<input type='radio' class='check' name='action' id='mcl_overwrite' value='overwrite'>\n";
                text += "<label for='mcl_overwrite'>Overwrite</label></p>";
            }

            function mclCallback2(response){
                if(response == true){
                    var form = $('overlayFG').getElementsByTagName('FORM')[0];
                    var actions = form.action;
                    var action = null;
                    for(var i = 0; i < actions.length; i++){
                        if(actions[i].checked){
                            action = actions[i].value;
                            break;
                        }
                    }
                    if(action.indexOf('_all') != -1){
                        request += '&' + action + '=1';
                    }else{
                        request += '&' + action + '[]=' + file;
                    }

                    doCallback(WEB_ROOT + "/mcl.php?" + request, mclCallback);
                }else{
                    var a = dragList.action + 'e';
                    setStatus("Canceled " + a.substr(0, a.indexOf('e')) + "ing.");
                    loadDir(dragList.fromDir);
                }
            }

            createDialog(text, title, mclCallback2, "OK", "Cancel");
        }else{
            setStatus(response, true);
            loadDir(dragList.fromDir);
        }
    }else{
        setStatus("Communication error!", true);
        loadDir(dragList.fromDir);
    }
}

function dragListKeyPress(ev){
    if(!ev){
        ev = window.event;
    }

    var dragList = $('dragList');
    var action = (ev.shiftKey) ? "link" : ((ev.ctrlKey) ? "copy" : "move");

    if(action == dragList.action){
        return false;
    }

    var dragAction = $('dragAction');
    dragAction.innerHTML = "&nbsp;&nbsp;" + action + "&nbsp;&nbsp;";

    if(action == 'move' && dragList.fromDir == $('list').path){
        lockListSize();

        if(dragList.fileList.length){
            for(var i = 0; i < dragList.fileList.length; i++){
                if($("row_" + dragList.fileList[i])){
                    $("row_" + dragList.fileList[i]).style.display = 'none';
                }
            }
        }

        easeListSize();
    }else if(dragList.action == 'move' && dragList.fromDir == $('list').path){
        lockListSize();

        for(var i = 0; i < dragList.fileList.length; i++){
            var row = $("row_" + dragList.fileList[i]);
            if(row && row.style.display == 'none'){
                if(showAnimations){
                    fade("row_" + dragList.fileList[i], 1, .2);
                }else{
                    row.style.display = '';
                }
            }
        }

        easeListSize();
    }

    dragList.action = action;
}


// File sorting
function sort_toggle(sort){
    sort = sort || sortType;

    $('sort_' + sortType.substr(0,1)).className = 'ls';

    if(sort == sortType){
        if(sort.substr(1,1) != 'R'){
            sort += 'R';
        }else{
            sort = sort.substr(0,1);
        }
    }

    sortType = sort;
    displayFiles();
}

function sortFiles(){
    var container = $('list');
    if(!container){
        return false;
    }

    var sortHeader = $('sort_' + sortType.substr(0,1));
    if(!sortHeader){
        return false;
    }

    var list = container.items;
    var r = (sortType.substr(1,1) == 'R');

    switch(sortType.substr(0,1)){
        case 'T':
            list = list.sort(sortByType);
            break;
        case 'D':
            list = list.sort(sortByDate);
            break;
        case 'S':
            list = list.sort(sortBySize);
            break;
        default:
            list = list.sort(sortByName);
    }

    if(r){
        list.reverse();
        sortHeader.className = 'ls lssortrev';
    }else{
        sortHeader.className = 'ls lssort';
    }

    return list;

    // Sort functions
    function sortDirsFirst(a, b, override){
        if(a[0] == '...'){
            return (r) ? 1 : -1;
        }
        if(b[0] == '...'){
            return (r) ? -1 : 1;
        }
        if(a[0] == '..'){
            return (r) ? 1 : -1;
        }
        if(b[0] == '..'){
            return (r) ? -1 : 1;
        }
        if(a[0] == '.'){
            return (r) ? 1 : -1;
        }
        if(b[0] == '.'){
            return (r) ? -1 : 1;
        }

        if(dirsFirst || override){
            if(a[5] && !b[5]){
                return (r) ? 1 : -1;
            }
            if(b[5] && !a[5]){
                return (r) ? -1 : 1;
            }
        }

        return 0;
    }

    function sortByName(a, b){
        var z = sortDirsFirst(a, b);
        if(z){
            return z;
        }

        var x = a[0].toLowerCase();
        var y = b[0].toLowerCase();
        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
    }

    function sortBySize(a, b){
        var z = sortDirsFirst(a, b, !dirSizes);
        if(z){
            return z;
        }

        if(a[5] && b[5] && !dirSizes){
            return (a[0].toLowerCase() < b[0].toLowerCase()) ? -1 : 1;
        }

        var x = a[2] * 1;
        var y = b[2] * 1;
        if(x == y){
            x = b[0].toLowerCase();
            y = a[0].toLowerCase();
        }
        return ((x < y) ? 1 : ((x > y) ? -1 : 0));
    }

    function sortByDate(a, b){
        var z = sortDirsFirst(a, b);
        if(z){
            return z;
        }

        var x = a[3] * 1;
        var y = b[3] * 1;
        if(x == y){
            x = b[0].toLowerCase();
            y = a[0].toLowerCase();
        }
        return ((x < y) ? 1 : ((x > y) ? -1 : 0));
    }

    function sortByType(a, b){
        var z = sortDirsFirst(a, b, true);
        if(z){
            return z;
        }

        var x = (a[5]) ? a[0].toLowerCase() : a[1];
        var y = (b[5]) ? b[0].toLowerCase() : b[1];
        if(x == y){
            x = a[0].toLowerCase();
            y = b[0].toLowerCase();
        }
        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
    }
}

function sortCheckList(list){
    var container = $('list');
    if(!container){
        return false;
    }

    return list.sort(sortByContainer);

    function sortByContainer(a, b){
        var x = container.items.find(a, 0) * 1;
        var y = container.items.find(b, 0) * 1;
        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
    }
}

// Row checkbox functions
// Check or uncheck all, or invert selection
function checkAll(invert, clearTopDirs){
    var container = $('list');
    if(!container){
        return false;
    }

    var boxes = container.getElementsByTagName('INPUT');
    if(!boxes){
        return false;
    }

    var checkall = $('checkall');

    for(var i = 0; i < boxes.length; i++){
        var e = boxes[i];

        if(e.id != 'checkall' && !e.disabled && e.type == 'checkbox' && e.value != '...' && e.value != '..' && e.value != '.'){
            if(!e.checked){
                checkList[checkList.length] = e.value;
            }
            e.checked = !invert ? checkall.checked : !e.checked;
            if(!e.checked){
                checkList.splice(checkList.find(e.value), 1);
            }
            hlTog(e);
        }
    }
}

// toggle row highlight
function hlTog(box){
    if(box.checked){
        hl(box);
    }else{
        dl(box);
    }
}

// highlight row
function hl(row){
    if(ie){
        while(row.tagName != "TR"){
            row = row.parentElement;
        }
    }else{
        while(row.tagName != "TR"){
            row = row.parentNode;
        }
    }

    if(row.className.indexOf(' lschecked') < 0){
        row.className += ' lschecked';
    }
}

// de-highlight row
function dl(row){
    if(ie){
        while(row.tagName != "TR"){
            row = row.parentElement;
        }
    }else{
        while(row.tagName != "TR"){
            row = row.parentNode;
        }
    }

    row.className = row.className.replace(' lschecked', '');
}

// change row color when checkbox changes
function checkToggle(checkId){
    if(typeof(checkId) != "string"){
        var checkId = this.checkId;
    }
    var checkbox = $(checkId);

    if(dragObject !== null || !checkbox){
        return false;
    }

    if(checkbox.checked || checkbox.disabled){
        checkbox.checked = false;
        checkList.splice(checkList.find(checkbox.value), 1);
        dl(checkbox);
    }else{
        checkbox.checked = true;
        checkList[checkList.length] = checkbox.value;
        hl(checkbox);
    }
}

// File manager dialogs
function renameDialog(oldName, isDir){
    var title = '<img src="' + imgDir + '/rename.png"> Rename';
    var body = "<p><label for='newName'>New Name:</label><br>";
    body += "<img id='renameFileIcon' src=\"" + icon(oldName, isDir) + "\">\n";
    body += "<input type='text' size='30' name='newName' id='newName' value=\"" + oldName.replace(/\"/g, '\\"') + "\"></p>\n";
    body += "<input type='hidden' name='path' id='newNamePath' value=\"" + $('list').path + "\">";

    var onLoad = isDir ? false : function(){
            $('newName').onkeyup = function(){$('renameFileIcon').src = icon(this.value);};
            $('fgForm').onreset = function(){$('renameFileIcon').src = icon(oldName);};
        };
    createDialog(body, title,
        function(response){
            if(response === true){
                renameFile(oldName, $('newName').value, $('newNamePath').value);
            }
        }, "OK", "Cancel", "Reset", onLoad);
}

function renameFile(oldName, newName, path){
    if(!newName){
        setStatus("You must enter a new name.", true);
    }else if(oldName == newName){
        setStatus("The new name is the same as the old name.", true);
    }else{
        var dragList = $('dragList');
        dragList.fromDir = path;
        dragList.toDir = path;
        dragList.action = 'rename';
        doCallback(WEB_ROOT + "/mcl.php?action=rename&from=" + escape(path + oldName) + "&to=" + escape(path) + "&files[]=" + escape(newName), mclCallback);
    }
}

function createFileDialog(){
    var title = '<img src="' + imgDir + '/create.png"> Create';
    var body = "<p><label for='createFileName'>File/Directory Name:</label><br>";
    body += "<img id='createFileIcon' src=\"" + icon('') + "\">\n";
    body += "<input type='text' size='25' name='createFileName' id='createFileName'></p>\n";
    body += "<p><input type='radio' class='radio' name='createType' id='createTypeFile' checked='checked'>";
    body += "<label for='createTypeFile'>File</label>\n";
    body += "<input type='radio' class='radio' name='createType' id='createTypeDir'>";
    body += "<label for='createTypeDir'>Directory</label></p>\n";
    body += "<input type='hidden' name='path' id='createPath' value=\"" + $('list').path + "\">";

    createDialog(body, title,
        function(response){
            if(response === true){
                createFile($('createFileName').value, $('createPath').value, $('createTypeDir').checked);
            }
        }, "OK", "Cancel", null,
        function(){
            var updateIcon = function(){
                $('createFileIcon').src = icon($('createFileName').value, $('createTypeDir').checked);
            }
            $('createFileName').onkeyup = updateIcon;
            $('createTypeDir').onclick = updateIcon;
            $('createTypeFile').onclick = updateIcon;
        }
    );
}

function createFile(fileName, path, dir){
    if(!fileName){
        setStatus("You must enter a file name.", true);
    }else{
        doCallback(WEB_ROOT + "/create.php?file=" + escape(fileName) + "&path=" + escape(path) + "&dir=" + (dir * 1), genericCallback2, 'POST');
    }
}

function download(files){
    if(!files || !files.length){
        return false;
    }

    var request = "path=" + escape($('list').path);

    if(typeof(files) == 'object'){
        for(var i = 0; i < files.length; i++){
            request += "&files[]=" + escape(files[i]);
        }
    }

    showSpinner();
    setStatus("Creating .zip file...");
    doCallback(WEB_ROOT + "/download.php?" + request, downloadCallback, 'POST');
}

function downloadCallback(response){
    closeOverlay();

    if(response.split("\n")[0] == "OK"){
        window.location = response.split("\n")[1];
    }else if(response){
        setStatus(response, true);
    }else{
        setStatus("Communication error!", true);
    }
}

function confirmDrag(files, action, from, to){
    if(!files || !files.length){
        return false;
    }

    var title = '<img src="' + imgDir + '/next.png"> ' + (action.substr(0, 1).toUpperCase() + action.substr(1));

    if(files.length == 1 || files.find('.') !== false || files.find('..') !== false || files.find('...') !== false){
        var message = "Are you sure you want to " + action + '"' + files[0] + "\" to " + to + "?";
    }else if(typeof(files) == 'object'){
        var message = "Are you sure you want to " + action + " the selected files to " + to + "?";
    }

    createDialog(message, title, 
        function(response){
            if(response === true){
                doDragAction(files, action, from, to);
            }else{
                lockListSize();

                if(action == 'move' && $('list').path == from){
                    for(var i = 0; i < files.length; i++){
                        var row = $("row_" + files[i]);
                        if(row && row.style.display == 'none'){
                            if(showAnimations){
                                fade("row_" + files[i], 1, .2);
                            }else{
                                row.style.display = '';
                            }
                        }
                    }
                }else{
                    loadDir(from, true);
                }

                easeListSize();
            }
        }
    , "Yes", "No");
}

function doDragAction(files, action, from, to){
    var request = "action=" + escape(action) + "&from=" + escape(from) + "&to=" + escape(to);

    for(var i = 0; i < files.length; i++){
        request += "&files[]=" + escape(files[i]);
    }

    doCallback(WEB_ROOT + "/mcl.php?" + request, mclCallback);
}

function confirmDelete(files){
    if(!files || !files.length){
        return false;
    }

    var title = '<img src="' + imgDir + '/delete.png"> Delete';

    if(typeof(files) == 'string' || files.length == 1 || files.find('.') !== false || files.find('..') !== false || files.find('...') !== false){
        if(typeof(files) == 'object'){
            files = files[0];
        }

        var file = files;

        if(is_home(file)){
            createDialog("You cannot delete your home directory.", title);
            return false;
        }
        if(file == '..'){
            file = 'the parent directory';
        }else if(file == '.'){
            file = 'the current directory';
        }else{
            file = '"' + file + '"';
        }

        var message = 'Are you sure you want to delete ' + file + '?';
    }else if(typeof(files) == 'object'){
        var message = "Are you sure you want to delete the selected files?";
    }

    createDialog(message, title, function(response){if(response === true)deleteFiles(files);}, "Yes", "No");
}

function deleteFiles(files){
    var request = "path=" + escape($('list').path);

    if(typeof(files) == 'string'){
        request += "&files=" + escape(files);
    }else if(typeof(files) == 'object'){
        for(var i = 0; i < files.length; i++){
            request += "&files[]=" + escape(files[i]);
        }
    }

    doCallback(WEB_ROOT + "/delete.php?" + request, deleteCallback, 'POST');
}

function deleteCallback(response){
    if(response.substr(0, 2) == "OK"){
        checkList = new Array();
        $('checkall').checked = false;
        loadDir();
        setStatus(response.substr(3));
        closeOverlay();
        return true;
    }else if(response){
        setStatus(response, true);
        loadDir();
        return false;
    }else{
        setStatus("Communication error!", true);
        focus('overlayFG');
        return false;
    }
}

function genericCallback2(response){
    if(response.substr(0, 2) == "OK"){
        loadDir();
        setStatus(response.substr(3));
        closeOverlay();
        return true;
    }else if(response){
        setStatus(response, true);
        loadDir();
        return false;
    }else{
        setStatus("Communication error!", true);
        focus('overlayFG');
        return false;
    }
}

// Autocomplete functions
function auto_file_list(path, obj){
    auto_get_list(path, obj, 1);
}

function auto_path_list(path, obj){
    auto_get_list(path, obj, 0);
}

function auto_get_list(path, obj, listfiles){
    path = parentDir(path + '/');
    if(obj.lastPath != path){
        doCallback(WEB_ROOT + '/ajax.php?mode=autocomplete&listfiles=' + escape(listfiles) + '&path=' + escape(path), getListResponse, 'POST');
        obj.lastPath = path;        
    }else{
        obj.getEligible();
        obj.createDiv();
    }

    function getListResponse(response){
        if(typeof(response) == 'string'){
            obj.suggestions = response.split("\n");
            obj.getEligible();
            obj.createDiv();
        }
    }
}
