﻿registerNS("Tegud.Stuff");

Tegud.Stuff.Init = function () {
    $("#SelectAllCategories,#SelectAllStates").bind("click", function () { Tegud.Stuff.ToggleSelectAll($(this).closest("div").next()); });

    $("#FilterName,#NewItemStuffName").bind("keydown", function (event) { Tegud.Stuff.NameFilterChange(event, $(this)); });

    $("#StuffCategory, #StuffState").delegate("li", "click", function () {
        $(this).children(".Checkbox").toggleClass("Checked");
        Tegud.Stuff.Filter();
    });

    $("#StuffItems").delegate("li", "click", function () {
        Tegud.Stuff.LentToControlsForItem($(this));
    });

    $("body")
        .delegate("#ControlsLentControlsCancel", "click", function () {
            $("#StuffItems").children(".Selected").removeClass("Selected");
            $("#ControlsLentControls").remove();
        })
        .delegate("#ControlsLentControlsOK", "click", function () {
            var selectedItem = $("#StuffItems").children(".Selected");

            if (!selectedItem.length)
                return;

            var id = selectedItem.attr("id").replace("StuffItem_", "");
            var lentOutChecked = $("#ControlsLentControls > div.ControlsLentControlsLentTo > div.Checkbox.Checked").length;
            var lentOutValue = $("#ControlsLentControlsLentToField").val();

            if (lentOutChecked && lentOutValue == "") {
                alert("If item is lent out, you must say who it lent out to.");
                return;
            }

            Tegud.AJAX.SendRequest("/Stuff/SetStuffLentTo",
                                    {
                                        "id": id,
                                        "lentTo": (lentOutChecked ? lentOutValue : "")
                                    },
                                    {
                                        Success: function () {
                                            var title;

                                            if (lentOutChecked) {
                                                selectedItem.addClass("LentOut");
                                                title = "Lent to: " + lentOutValue;
                                            } else {
                                                selectedItem.removeClass("LentOut");
                                                title = "At Home";
                                            }

                                            selectedItem
                                                .attr("title", title)
                                                .removeClass("Selected");

                                            $("#ControlsLentControls").remove();
                                            Tegud.Stuff.Filter();
                                        }
                                    });
        })
        .delegate("#ControlsLentControls > div > div.Label", "click", function () { $(this).prev().click(); })
        .delegate("#ControlsLentControls > div > div.Checkbox", "click", function () {
            if ($(this).hasClass("Checked"))
                return;

            var notSelectedField = $(this)
                .addClass("Checked")
                .parent()
                .siblings()
                    .children(".Checkbox")
                        .removeClass("Checked")
                    .end();

            if (notSelectedField.hasClass("ControlsLentControlsLentTo")) {
                notSelectedField
                    .children("input")
                        .attr("disabled", "disabled");
            } else {
                $(this)
                    .parent()
                        .children("input")
                            .removeAttr("disabled")
                            .focus();
            }
        });

    $("#NewItemStuffCategory").delegate("li", "click", function () {
        var checkbox = $(this).children(".Checkbox");

        if (checkbox.hasClass("Checked"))
            checkbox.removeClass("Checked");
        else
            checkbox
                .addClass("Checked")
                .parent()
                .siblings()
                    .children(".Checkbox")
                    .removeClass("Checked");
        Tegud.Stuff.Filter();
    });

    $("#AddNewStuffItem")
        .button()
        .bind("click", Tegud.Stuff.CreateNewItem);

    $("#StuffTabPanel").tabs({
        show: Tegud.Stuff.Filter
    });
}

Tegud.Stuff.CreateNewItem = function () {
    var category = $("#NewItemStuffCategory > li:has(.Checked)").text();
    var name = $("#NewItemStuffName").val();

    if ((category || "") == "") {
        alert("You must select a category.");
        return;
    }

    if ((name || "") == "") {
        alert("You must enter a name.");
        return;
    }

    Tegud.AJAX.SendRequest("/Stuff/CreateNewStuffItem",
                            {
                                "name": name,
                                "categoryName": category
                            },
                            {
                                Success: function (data) {
                                    $("#NewItemStuffName").val("");

                                    var newItem = $("<li />", {
                                        "id": "StuffItem_" + data.NewItemID,
                                        "class": category
                                                    .replace(" ", "_")
                                                    .replace("(", "")
                                                    .replace(")", "")
                                    })
                                        .html("<span class=\"StuffItemName\">" + name + "</span>, <i>" + category + "</i><div class=\"LentOutStatusIndicator\"></div>");

                                    var insertBefore;

                                    $("#StuffItems").children().each(function () {
                                        if ($(this).children(".StuffItemName").text() > name) {
                                            insertBefore = $(this);
                                            return false;
                                        }
                                    });

                                    if (insertBefore)
                                        newItem.insertBefore(insertBefore);
                                    else
                                        $("#StuffItems").append(newItem);

                                    Tegud.Stuff.Filter();
                                }
                            });
}

Tegud.Stuff.NameFilterChange = function (event, field) {
    var currentTimeout = field.data("Timeout");
    if (currentTimeout)
        clearTimeout(currentTimeout);

    field.data("Timeout", setTimeout(Tegud.Stuff.Filter, 200));
}

Tegud.Stuff.ToggleSelectAll = function (div) {
    var checkboxes = div.children("li").children(".Checkbox");

    if (checkboxes.filter(".Checked").size() < checkboxes.size())
        checkboxes.addClass("Checked");
    else
        checkboxes.removeClass("Checked");

    Tegud.Stuff.Filter();
}

Tegud.Stuff.Filter = function () {
    var showAtHome;
    var showLentOut;

    if (!$("#StuffStateLentOut").is(":visible")) {
        showLentOut = true;
        showAtHome = true;
    }
    else {
        showLentOut = $("#StuffStateLentOut:has(.Checked)").length;
        showAtHome = $("#StuffStateAtHome:has(.Checked)").length;
    }

    var allItems = $("#StuffItems").children();

    // If we're not showing items of any state, then hide everything.
    if (!showAtHome && !showLentOut) {
        allItems.addClass("Hidden");
        $("#StuffItemCount").text("0");
        return;
    }

    // Show all by default.
    allItems.removeClass("Hidden");

    if (!showAtHome)
        allItems.filter(":not(.LentOut)").addClass("Hidden");

    if (!showLentOut)
        allItems.filter(".LentOut").addClass("Hidden");

    var categoryField = $("#StuffCategory:visible,#NewItemStuffCategory:visible");

    var unSelectedCategories = categoryField.children("li:not(:has(.Checked))");
    var filterCategoryListVisible = $("#StuffCategory:visible").length;

    if (unSelectedCategories.size() >= categoryField.children("li").size() && filterCategoryListVisible) {
        allItems.addClass("Hidden");
        $("#StuffItemCount").text("0");
        return;
    }

    if (unSelectedCategories.length && (filterCategoryListVisible || unSelectedCategories.size() < categoryField.children("li").size())) {
        // Not all categories are selected.
        var categoryHideFilter = "";

        unSelectedCategories.each(function (i) {
            var categoryClass = ($(this).attr("id") || "").replace("CategoryFilter_", "");
            categoryHideFilter += (i > 0 ? "," : "") + "." + categoryClass;
        });

        allItems.filter(categoryHideFilter).addClass("Hidden");
    }

    var nameFilter = $("#FilterName:visible,#NewItemStuffName:visible").val().toLowerCase();

    if (nameFilter.length < 1) {
        $("#StuffItemCount").text($("#StuffItems").children(":not(.Hidden)").size());
        return;
    }

    allItems.each(function () {
        if ($(this).text().toLowerCase().indexOf(nameFilter) > -1)
            return true;
        $(this).addClass("Hidden");
    });

    $("#StuffItemCount").text($("#StuffItems").children(":not(.Hidden)").size());
}

Tegud.Stuff.LentToControlsForItem = function (item) {
    var controls = $("#ControlsLentControls");

    if (item.hasClass("Selected")) {
        item.removeClass("Selected");
        controls.remove();
        return;
    }

    item
        .addClass("Selected")
        .siblings()
            .removeClass("Selected");

    var width = item.outerWidth() - 8;
    var strLentOutTo = item.attr("title");

    if (strLentOutTo.indexOf("Lent to:") > -1)
        strLentOutTo = strLentOutTo.substring(9);
    else
        strLentOutTo = "";

    if (controls.length) {
        if (strLentOutTo == "")
            controls
                .children(".ControlsLentControlsAtHome")
                    .children(".Checkbox")
                        .addClass("Checked")
                    .end()
                .end()
                .children(".ControlsLentControlsLentTo")
                    .children(".Checkbox")
                        .removeClass("Checked")
                    .end()
                    .children("input")
                        .val("")
                        .attr("disabled", "disabled");
        else
            controls
                .children(".ControlsLentControlsAtHome")
                    .children(".Checkbox")
                        .removeClass("Checked")
                    .end()
                .end()
                .children(".ControlsLentControlsLentTo")
                    .children(".Checkbox")
                        .addClass("Checked")
                    .end()
                    .children("input")
                        .val(strLentOutTo)
                        .removeAttr("disabled");
    }
    else
        controls = $("<div />", {
            "id": "ControlsLentControls"
        })
            .append($("<div />", { "class": "ControlsLentControlsAtHome" })
                .append($("<div />", { "class": "Checkbox" + (strLentOutTo == "" ? " Checked" : "") }))
                .append($("<div />", {
                    "class": "Label",
                    text: "At Home"
                })))
            .append($("<div />", { "class": "ControlsLentControlsLentTo" })
                .append($("<div />", { "class": "Checkbox" + (strLentOutTo != "" ? " Checked" : "") }))
                .append($("<div />", {
                    "class": "Label",
                    text: "Lent To:"
                }))
                .append($("<input />", {
                    "type": "text",
                    "val": strLentOutTo,
                    "id": "ControlsLentControlsLentToField",
                    "disabled": (strLentOutTo == "" ? "disabled" : ""),
                    css: {
                        width: (width - 30),
                        marginLeft: "22px"
                    }
                }))
            .append($("<button />",
                {
                    "text": "OK",
                    "id": "ControlsLentControlsOK" 
                }).button())
            .append($("<button />",
                {
                    "text": "Cancel",
                    "id": "ControlsLentControlsCancel" 
                }).button()));

    controls
        .css({ width: width })
        .appendTo("body")
        .position({
            my: "left bottom",
            at: "left top",
            of: item,
            offset: "0 -3"
        })
        .children(".ControlsLentControlsLentTo")
            .children("input")
                .css({ width: (width - 30) });
}
