function AdvancedLinkCreatorWindow() {
    this.linkCreator = new LinkCreator(this);
    var _this = this;

    $("#advancedCreateLinkFromPath").val($("#createLinkFromPath").val());
    $("#advancedCreateLinkToUrls").val($("#createLinkToUrls").val());
    $("#page_mask").show();
    $("#advancedCreateLinkDiv").show("slow");
    toggleEditorByElement(true, "#createLinkDescription");
    $("#createLinkToUrl").focus();

    $("#advancedCreateLinkDiv input, #advancedCreateLinkDiv textarea, " +
            "#createLinkFromPath, #createLinkToUrls").bind("blur", function (e) {
        _this.linkCreator.check();
    });

    $("#advancedCreateLinkDiv input, #createLinkFromPath").bind("keypress", function (e) {
        if (e.which == 13) _this.linkCreator.save();
    });

    //    _this.visible = false;
    $("#advancedCreateLinkShowMore").click(function () {
        _this.visible = !_this.visible;
        if (_this.visible) $(".advancedCreateLinkOptions").show();
        else $(".advancedCreateLinkOptions").hide();
    });

    $("#advancedCreateLinkCancel").click(this.close);
    $("#advancedCreateLinkSubmit").click(function () {
        _this.linkCreator.save();
    });
}

AdvancedLinkCreatorWindow.prototype.close = function () {
    $("#advancedCreateLinkDiv *").unbind();

    $("#advancedCreateLinkDiv").hide("slow", function () {
        toggleEditorByElement(false, "#createLinkDescription");
        $("#createLinkDescription").val("");
        $("#page_mask").hide();
        $("#advancedCreateLinkResult").empty();
        $("#advancedCreateLinkToUrls").val("");
        showErrorBorder(false);
    });
};

AdvancedLinkCreatorWindow.prototype.link = function () {
    return {
        urls: $("#advancedCreateLinkToUrls").val(),
        description: getEditorDataByElement("#createLinkDescription"),
        refferer: $("#createLinkRefferer").val(),
        allowEmptyRefferer: $("#createLinkAllowEmptyRefferer").attr("checked"),
        fromPath: $("#advancedCreateLinkFromPath").val(),
        password: $("#createLinkPassword").val(),
        confirmPassword: $("#createLinkPasswordConfirm").val()
    };
};

AdvancedLinkCreatorWindow.prototype.onCheck = function (result) {
    $("#advancedCreateLinkResult").html("");
    if (result.resultCode != "success") {
        checkError1(result, "advancedCreateLinkResult", false);
        return false;
    }

    for (var i = 0; i < result.urls.length; i++) {
        if (result.urls[i].resultCode != "success") {
            checkError1(result, "advancedCreateLinkResult", false);
            return false;
        }
    }

    return true;
};

AdvancedLinkCreatorWindow.prototype.onSave = function (result) {
    if (!this.onCheck(result)) return;
    $("#advancedCreateLinkFromPath").val(result.nextFromPath);
    this.close();
    if (result.type == 4) createDirWithId(result.linkId, result.name);
    showCurrentDir();
};

// ---------------------------------------------------------------------------------------------------------------------

function SimpleLinkCreatorWindow() {
    this.linkCreator = new LinkCreator(this);
    var _this = this;

    $("#createLinkButton").click(function () {
        _this.linkCreator.save();
    });

    $("#showLinks").click(function () {
        $("#tempLinks").toggle();

        var img = $("img", this);
        if (img.attr("src") == "/images/arrowdown.gif") img.attr("src", "/images/arrowup.png");
        else img.attr("src", "/images/arrowdown.gif");
    });

    $("#createLinkToUrls").click(function() {
        if ($(this).val() == "http://") {
            $(this).val("");
        }
    });

    $("#createLinkToUrls").blur(function() {
        $("#createLinkResult").html("");
        if ($(this).val() == "http://") {
        } else if ($(this).val() == "") {
            $(this).val("http://");
        } else {
            _this.linkCreator.check();
        }
    });

    if ($("#createLinkToUrls")[0].setSelectionRange) {
        $("#createLinkToUrls")[0].setSelectionRange($("#createLinkToUrls")[0].value.length, $("#createLinkToUrls")[0].value.length);
    } else if ($("#createLinkToUrls")[0].createTextRange) {
        var range = $("#createLinkToUrls")[0].createTextRange();
        range.moveStart("character", $("#createLinkToUrls")[0].value.length);
        range.moveEnd("character", $("#createLinkToUrls")[0].value.length);
        range.select();
    }
    $("#createLinkToUrls").focus();
}

SimpleLinkCreatorWindow.prototype.link = function () {
    return {urls: $("#createLinkToUrls").val()};
};

SimpleLinkCreatorWindow.prototype.onCheck = function (result) {
    if (result.resultCode != "success") {
        checkError1(result, "createLinkResult", false);
        return false;
    }

    for (var i = 0; i < result.urls.length; i++) {
        if (result.urls[i].resultCode != "success") {
            checkError1(result, "createLinkResult", false);
            return false;
        }
    }

    return true;
};

SimpleLinkCreatorWindow.prototype.refresh = function () {
    $.ajax({
        type: "get",
        url: "tempLinks.jsp",
        cache: false,
        dataType: "html",
        success: function (result) {
            $("#tempLinks ul").html(result);
        }
    });
};

SimpleLinkCreatorWindow.prototype.onSave = function (result) {
    if (!this.onCheck(result)) return;

    var url = splitLocation().server + result.fromPath;
    $("#createdLink input").val(url);
    $("#createdLinkHref").attr("href", url);
    $("#editCreatedLink").attr("href", "javascript:editLink(" + result.linkId + ");");
    $("#createdLink").show();
    $("#createdLink input").select();
    $("#createdLink input").focus();
    $("#tempLinks1").show();
    $("img", this).attr("src", "/images/arrowdown.gif");

    bindCopyToClipboard(document.getElementById("ctcCreatedLink"), url);

    this.refresh();
};

// ---------------------------------------------------------------------------------------------------------------------

function LinkCreator(_window) {
    var _this = this;
    _this._window = _window;


    _this.checkNeed = false;
    _this.checkInterval = setInterval(function () {
        if (!_this.checkNeed) return;

        var link = _this._window.link();

        if (link.password != link.confirmPassword) {
            _this._window.onCheck({
                resultCode: "notEqualsPassword",
                urls: {}
            });
            return;
        }

        var data = {url: link.urls};
        if (link.fromPath) data.fromPath = link.fromPath;

        _this.checkRequest = $.getJSON(
                "/links/check", data,
                function (result) {
                    _this.checkNeed = false;
                    _this.checkRequest = null;
                    _this._window.onCheck(result);
                });
    }, 300);
}

LinkCreator.prototype.cancel = function () {
    if (this.checkRequest) this.checkRequest.abort();
    //    clearInterval(this.checkInterval);
    //    this.checkInterval = null;
    this.checkRequest = null;
    this.checkNeed = false;
};

LinkCreator.prototype.save = function () {
    var _this = this;

    if (_this.saveRequest) return;
    _this.saveRequest = true;
    _this.cancel();

    var link = _this._window.link();
    var data = {
        fromUi: true,
        url: link.urls,
        description: link.description ? link.description : "",
        password: link.password ? link.password : "",
        refferer: link.refferer ? link.refferer : "",
        allowEmptyRefferer: link.allowEmptyRefferer
    };

    if (link.fromPath) data.fromPath = link.fromPath;

    $.ajax({
        type: "post",
        data: data,
        dataType: "json",
        url: "/links/create",
        success: function (result) {
            _this.saveRequest = false;
            _this._window.onSave(result);
        }
    });
};

LinkCreator.prototype.check = function () {
    this.checkNeed = true;
};

// ---------------------------------------------------------------------------------------------------------------------

function hideCreatedLink() {
    $("#createdLink").hide();
}

// ---------------------------------------------------------------------------------------------------------------------

function showStats(linkId) {
    showLoadingSplash("#linksListContainer");
    $.ajax({
        type: "post",
        url: "/includeStats.jsp",
        dataType: "html",
        data: {linkId: linkId},
        success: function (html) {
            $("#linksListContainer").html(html);
        }
    });
}

// ---------------------------------------------------------------------------------------------------------------------

function linkSettingsShow(editUrl) {
    linkSettingsClose();

    var div = $("#linkSettings");

    $("input", div).val(editUrl);
    //    div.css("top", $(document).height() / 2 + $(document).scrollTop());
    div.show("slow");
}

function linkSettingsClose() {
    $("#linkSettings").hide("slow");
}

// ---------------------------------------------------------------------------------------------------------------------

function showCreateDir() {
    createDirCancel();

    $("#createDirNameInput").val("");
    $("#createDirDiv").show("slow");
}

function createDivSave() {
    if ($("#createDirNameInput").val().length > 0) {
        createDirWithName($("#createDirNameInput").val());
        createDirCancel();
        return;
    }

    $("#createDirErrorSpan").html("Empty name!");
    $("#createDirErrorSpan").css("display", "inline");
}

function createDirCancel() {
    var div = $("#createDirDiv");
    $("#createDirErrorSpan").css("display", "none");
    div.hide("slow");
}

// ---------------------------------------------------------------------------------------------------------------------

function splitLocation() {
    var location = window.location.href;
    var gridStart = location.indexOf("/", 8);
    if (gridStart > -1)
        return {
            server: location.substring(0, gridStart + 1),
            page: location.substring(gridStart + 1, location.length)
        };

    return {
        server: location,
        page: null
    };
}

// login ---------------------------------------------------------------------------------------------------------------

function showLoginAfter(sessionTimeout) {
    window.setTimeout(function () {
        window.location = "/?relogin=1";
    }, (sessionTimeout - 60) * 1000);
}

// ---------------------------------------------------------------------------------------------------------------------

window.snaps = {

    init: function () {
        $(".showSnap").each(function () {
            var snapShowA = $(document.createElement("a"));
            snapShowA.attr("infoId", $(this).attr("infoId"));
            snapShowA.html(" [snap]");
            snapShowA.attr("href", "javascript:void(0);");

            snapShowA.bind("mouseout", window.snaps.waitAndRemove);

            snapShowA.bind("mouseover", function (e) {
                window.clearTimeout(window.snaps.timeout);
                window.snaps.remove();

                var infoId = $(this).attr("infoId");
                var snapDiv = document.createElement("div");
                $(snapDiv).css("position", "absolute");
                $(snapDiv).addClass("snap");
                $(snapDiv).css("border", "1px solid #000000");
                $(snapDiv).css("height", 150);
                $(snapDiv).css("width", 150);
                $(snapDiv).css("left", e.pageX);
                $(snapDiv).css("top", e.pageY);
                $(snapDiv).html("<img src=\"/links/snap?infoId=" + infoId + "\" border=\"0\" width=\"150\" height==\"150\" alt=\"Snap.\">");

                $(snapDiv).bind("mouseover", function () {
                    window.clearTimeout(window.snaps.timeout);
                });

                $(snapDiv).bind("mouseout", window.snaps.waitAndRemove);

                document.body.appendChild(snapDiv);
            });
            $(this).after(snapShowA);
        });
    },

    remove: function () {
        $(".snap").remove();
    },

    waitAndRemove: function () {
        window.snaps.timeout = window.setTimeout(function () {
            window.snaps.remove();
        }, 1000);
    }

};

// ---------------------------------------------------------------------------------------------------------------------

function showCurrentDir() {
    showDirWithSort($("#curDirID").html(), true, null);
}

function showCurrentDirWithSort(linkSort) {
    showDirWithSort($("#curDirID").html(), true, linkSort);
}

function showDir(dirId, force) {
    showDirWithSort(dirId, force, null);
}

function showDirWithSort(dirId, force, linkSort) {
    if (!force && $("#curDirID").html() == dirId) return;

    showLoadingSplash("#linksListContainer");
    $("#linksListContainer").load("/homeLinksOnly.jsp", {
        folderId: dirId,
        linkSort: linkSort
    }, configureContextMenu);
}

// ---------------------------------------------------------------------------------------------------------------------

/*
 * We didn't find context menu div, when user doesn't have
 * any right on edit, move or delete links.
 */
function configureContextMenu() {
    jquerycontextmenu.showbox = function ($, $contextmenu, e) {
        var parent = e.target.parentNode;
        while (parent.tagName != "TR") {
            parent = parent.parentNode;
        }

        var fromPath = $(parent).attr("fromPath");

        $("#linksListMenuDelete").attr("href", $(".removeLink", parent).attr("href"));
        $("#linksListMenuEdit").attr("href", $(".editLink", parent).attr("href"));

        $("#linksListRename").attr("href", "javascript:showRenameDir(" + $(parent).attr("linkId") + ");");
        if ($(parent).attr("type1") != "4") $("#linksListRename").hide();
        else $("#linksListRename").show();

        var moveToA = $("#linksListMenuMoveTo");
        moveToA.empty();
        moveToA.append(treeObject.children()[0].innerHTML);
        $("a", moveToA).each(function () {
            this.href = "javascript:dropLink(\"" + fromPath + "\"," + this.parentNode.id + ");";
            $(this.parentNode).css("background-image", "none");
            $(this).css("background-image", "none");
        });

        jquerycontextmenu.buildcontextmenu($, $contextmenu);
        $contextmenu.show();
    };

    if ($(".linksListRow").addcontextmenu)
        $(".linksListRow").addcontextmenu("linksListMenu");
}

// ---------------------------------------------------------------------------------------------------------------------

function toggleEditor(toggle) {
    toggleEditorByElement(toggle, "#description");
}

// ---------------------------------------------------------------------------------------------------------------------

function toggleEditorByElement(toggle, element, width) {
    window.CKEDITOR_BASEPATH = "/ckeditor/";

    if (toggle) {
        if (!window.CKEDITOR) {
            $.ajax({
                cache: true,
                url: "/ckeditor/ckeditor.js",
                dataType: "script",
                success: function () {
                    toggleEditorByElement(toggle, element, width);
                }
            });
            return;
        }

        window.editor = CKEDITOR.replace($(element)[0], {
            width: width ? width : "",
            customConfig: "",
            toolbar: [
                ['Source','-','Cut','Copy','Paste','-','SpellChecker'],
                ['Undo','Redo','-','SelectAll','RemoveFormat'],
                '/',
                ['Bold','Italic','Underline','Strike','-','Subscript','Superscript'],
                ['NumberedList','BulletedList','-','Outdent','Indent','Blockquote','CreateDiv'],
                ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
                ['Link','Unlink','Anchor'],
                ['Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak'],
                '/',
                ['Font','FontSize','TextColor','BGColor']
            ]
        });
    } else {
        if (window.editor) window.editor.destroy();
        window.editor = null;
    }
}

function toggleEditorByElementWithSettings(settings) {
    window.CKEDITOR_BASEPATH = "/ckeditor/";

    if (settings.toggle) {
        if (!window.CKEDITOR) {
            $.ajax({
                cache: true,
                url: "/ckeditor/ckeditor.js",
                dataType: "script",
                success: function () {
                    toggleEditorByElementWithSettings(settings);
                }
            });
            return;
        }

        window.editor = CKEDITOR.replace($(settings.element)[0], {
            width: settings.width ? settings.width : "",
            customConfig: "",
            toolbar: [
                ['Source','-','Cut','Copy','Paste','-','SpellChecker'],
                ['Undo','Redo','-','SelectAll','RemoveFormat'],
                '/',
                ['Bold','Italic','Underline','Strike','-','Subscript','Superscript'],
                ['NumberedList','BulletedList','-','Outdent','Indent','Blockquote','CreateDiv'],
                ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
                ['Link','Unlink','Anchor'],
                ['Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak'],
                '/',
                ['Font','FontSize','TextColor','BGColor']
            ]
        });

        if (settings.success) settings.success();
    } else {
        if (window.editor) window.editor.destroy();
        window.editor = null;
    }
}

function getEditorDataByElement(element) {
    if (window.editor) return window.editor.getData();
    return $(element).val();
}

// ---------------------------------------------------------------------------------------------------------------------

function getSelectedLinkFromPaths() {
    return getSelectedFromPaths(".linksListSelect");
}

function getSelectedLinks() {
    var result = new Array();
    $(".linksListSelect").each(function () {
        if (this.checked) result.push({
            fromPath: $(this.parentNode.parentNode).attr("fromPath"),
            linkId: $(this.parentNode.parentNode).attr("linkId"),
            type: $(this.parentNode.parentNode).attr("type1")
        });
    });
    return result;
}

function excludeAttrFromArray(array, attr) {
    var result = new Array();
    for (var i = 0; i < array.length; i++)
        result.push(array[i][attr]);
    return result;
}

function getSelectedFromPaths(class1) {
    var result = new Array();
    $(class1).each(function () {
        if (this.checked) result.push($(this.parentNode.parentNode).attr("fromPath"));
    });
    return result;
}

function getLinks() {

}

window.selectedFromPaths = {

    show: function (base) {
        var fromPaths = getSelectedFromPaths(".linksListSelect");

        if (fromPaths.length < 1) {
            alert("Select links!");
            return;
        }

        $("#selectedFormPaths").val("");
        for (var i = 0; i < fromPaths.length; i++)
            $("#selectedFormPaths").val($("#selectedFormPaths").val() + (i > 0 ? "\n" : "") + base + fromPaths[i]);

        $("#selectedFormPathsWindow").show("slow", function () {
            $("#selectedFormPaths").focus();
            $("#selectedFormPaths").select();
        });
    },

    close: function () {
        $("#selectedFormPathsWindow").hide();
    }

};

function removeLink(linkId, linkURL) {
    if (confirm('Are you sure want to remove link ' + linkURL)) {
        $.post('/', {removeLinkId: linkId}, function data() {
            setTimeout('showCurrentDir()', 20);
        }, 'text');
    }
}

function splitLink(linkId) {
    $.post("/s/MF", {
        ac: "splitLinks",
        splitLinkId: linkId
    }, function data() {
        showCurrentDir();
    }, "text");
}

function createDir() {
    $("#treeContainer")[0].tree1.create({
        data: {
            rel: "folder",
            title: "New folder",
            icon: "/js/jstree/themes/default/sf.png"
        }
    }, null, 0);
}

function createDirWithName(name) {
    $("#treeContainer")[0].tree1.create({
        data: {
            rel: "folder",
            title: name,
            icon: "/js/jstree/themes/default/sf.png"
        }
    }, null, 0);
}

function createDirWithId(id, name) {
    if (!$("#treeContainer")[0]) return;

    window.treeManualSetId = id;
    $("#treeContainer")[0].tree1.create({
        data: {
            rel: "folder",
            title: name,
            icon: "/js/jstree/themes/default/sf.png"
        }
    }, null, 0);
}

function renameFolder(nodeId, newNodeName) {
    $("#subDirName" + nodeId).html(newNodeName);

    $.post("/dirs/edit", {
        id: nodeId,
        name: newNodeName
    }, function() {
        showCurrentDir();
    }, "json");
}

function createFolder(parentNodeId, nodeName, nodeRef) {
    $.post("/dirs/create", {
        parentId: parentNodeId,
        name: nodeName
    }, function(data) {
        nodeRef.id = data.id;
        $("a", "#" + data.id)[0].style.backgroundImage = "url(/js/jstree/themes/default/sf.png)";
        $("#treeContainer")[0].tree1.select_branch($("a", "#" + data.id));
        //        showDir(data.id);
    }, "json");
}

function upDir() {
    if ($("#treeContainer")[0]) {
        var tree = $("#treeContainer")[0].tree1;
        tree.select_branch(tree.parent(tree.selected));
    } else {
        showDir($("#parentLinkId").html(), false);
    }
}

function moveFolder(nodeId, parentNodeId) {
    $.post("/s/MF", {
        ac: "move",
        parentDirId: parentNodeId,
        dirId: nodeId
    }, function() {
    }, "json");
}

function copyFolder(nodeId, parentNodeId, copyNode) {
    $.post("/links/copy", {
        parentId: parentNodeId,
        id: nodeId
    }, function(data) {
        copyNode.id = data.linkId;
    }, "json");
}

function dropLink(linkId, parentNodeId) {
    if ($("#curDirID").html() == parentNodeId) {
        return;
    }
    $.post('/s/MF', {ac: 'dropLink', parentDirId: parentNodeId, linkId: linkId}, function () {
        removeParentRow(document.getElementById("link-" + linkId));
    }, "json");
}

function removeParentRow(linkElem) {
    var trElem = linkElem.parentNode;
    while (trElem == null || trElem.tagName != 'TR') {
        trElem = trElem.parentNode;
    }
    var parentOfTheRow = trElem.parentNode;
    parentOfTheRow.removeChild(trElem);
    if (parentOfTheRow.getElementsByTagName("TR").length == 2) {
        $('#noLinksRow').show();
        $('#linksListHeaderRow').hide();
    }
}

function deleteFolder(nodeId) {
    $.post("/dirs/remove", {
        ids: nodeId
    }, function () {
    }, "json");
}

function showRenameDir(id) {
    $("#treeContainer")[0].tree1.rename($("#" + id));
}

// ---------------------------------------------------------------------------------------------------------------------

window.login = {

    overOpenId: function () {
        $("#loginEmail").hide();
        $("#loginPassword").hide();
        $("#loginRemember").hide();
        $("#loginOpenid").show();
    },

    overGoogleId: function () {
        $("#loginOpenidInput").val("https://www.google.com/accounts/o8/id");
        $("#login").submit();
    }

};

// ---------------------------------------------------------------------------------------------------------------------

// edit link functions

function doSaveLink() {
    var request = {
        "mode": 1,
        linkId: document.linksForm.linkId.value,
        targetURL: document.linksForm.singleLink.value,
        fromPath: document.getElementById('singleLinkResult').value,
        link: document.getElementById('singleLinkResult').value,
        generate: generate,
        description: getEditorDataByElement(),
        "password": document.linksForm.password.value
    }

    $.post("/s/SL", request, function () {
        if (window.linkCreatorWindow) {
            var url = splitLocation().server + document.getElementById('singleLinkResult').value;
            if (document.linksForm.linkType != 4) $("#createLinkToUrls").val(document.linksForm.singleLink.value);
            $("#createdLinkHref").attr("href", url);
            $("#createdLink input").val(url);
            bindCopyToClipboard(document.getElementById("ctcCreatedLink"), url);
            window.linkCreatorWindow.refresh();
        } else showCurrentDir();

        hideLinkEditor();
    });

}

function checkLink(andSubmit) {
    doCheckSingleLink(generate, true, function () {
        if (andSubmit) {
            if (document.linksForm.error.value == "") {
                doSaveLink();
            }
        }
    });
}

function hideLinkEditor() {
    $("#page_mask").hide();
    $("#editLinkDiv").hide();
}

function editLink(linkId) {
    $("#page_mask").hide();
    $("#editLinkDiv").hide();
    $("#singleLinkCheckResult").html("");
    toggleEditor(false);

    clearErrors();
    $.ajax({
        url: "/links/get",
        type: "get",
        cache: false,
        dataType: "json",
        data: {ids: linkId},
        //            error: function (x, s, e) {
        //                alert(x + s + e);
        //            },
        success: function (json) {
            var link = json.links[0];

            if (link.type == 4) $("#editLinkUrlTr").hide();
            else $("#editLinkUrlTr").show();

            var f = document.linksForm;
            f.linkType = link.type;
            f.linkId.value = link.linkId;
            f.password.value = link.password;
            f.passwordConfirm.value = link.password;
            f.description.value = link.description;
            f.singleLinkResult.value = link.fromPath;
            f.singleLink.value = link.url;
            $("#singleLinkCheckResult").html("");
            $("#singleLinkTextElementDiv").show();

            toggleEditor(true);
            $("#page_mask").show();
            $("#editLinkDiv").show();
        }});
}

$("#page_mask").hide();

function saveLink() {
    checkLink(true);
}

// ---------------------------------------------------------------------------------------------------------------------

function showAll() {
    if (!confirm("Are you sure you want to open all links?")) {
        return;
    }

    $(".link").each(function () {
        window.open(this.href, "_blank");
    });
}

// ---------------------------------------------------------------------------------------------------------------------

function showLoadingSplash(div) {
    var loadingBackDiv = document.createElement("div");
    $(loadingBackDiv).attr("class", "loading");
    $(loadingBackDiv).css("opacity", 0.5);
    $(loadingBackDiv).css("position", "absolute");
    $(loadingBackDiv).css("background-color", "white");
    $(loadingBackDiv).css("left", $(div).position().left);
    $(loadingBackDiv).css("top", $(div).position().top);
    $(loadingBackDiv).css("width", $(div).width());
    $(loadingBackDiv).css("height", $(div).height());
    $(div).append(loadingBackDiv);

    var loadingDiv = document.createElement("div");
    $(loadingDiv).html("<img src=\"/images/loading.gif\" alt=\"Loading\" width=\"20\" height=\"20\" class=\"absmid\"> Loading...");
    $(loadingDiv).attr("class", "loading");
    $(loadingDiv).css("position", "absolute");
    $(loadingDiv).css("left", $(div).position().left);
    $(loadingDiv).css("top", $(div).position().top);
    $(loadingDiv).css("width", $(div).width());
    $(loadingDiv).css("height", $(div).height());
    $(div).append(loadingDiv);
}
