/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

$(".addpackagebtn").click(function () {
    if ($("input[name=number]").val().trim() == "") {
        playSound("error");
        app.toast.show({
            text: "Please fill in a street number.",
            position: "bottom",
            destroyOnClose: true,
            closeTimeout: 1000 * 10
        });
        return;
    }
    if ($("input[name=street]").val().trim() == "") {
        playSound("error");
        app.toast.show({
            text: "Please fill in a street name.",
            position: "bottom",
            destroyOnClose: true,
            closeTimeout: 1000 * 10
        });
        return;
    }
    if ($("input[name=citystate]").val().trim() == "") {
        playSound("error");
        app.toast.show({
            text: "Please fill in a city and state.",
            position: "bottom",
            destroyOnClose: true,
            closeTimeout: 1000 * 10
        });
        return;
    }
    if ($("input[name=zipcode]").val().trim() == "") {
        playSound("error");
        app.toast.show({
            text: "Please fill in a ZIP code.",
            position: "bottom",
            destroyOnClose: true,
            closeTimeout: 1000 * 10
        });
        return;
    }

    // Save city/state if changed
    if (getStorage("citystate") != $("input[name=citystate]").val().trim()) {
        setStorage("citystate", $("input[name=citystate]").val().trim());
    }

    if (getStorage("zipcode") != $("input[name=zipcode]").val().trim()) {
        setStorage("zipcode", $("input[name=zipcode]").val().trim());
    }

    var address = ($("input[name=number]").val() + " " + $("input[name=street]").val()).toUpperCase();
    $("#no-history").addClass("display-none");
    addPackageByAddress(
            $("input[name=number]").val().toUpperCase(),
            $("input[name=unit]").val().toUpperCase(),
            $("input[name=street]").val().toUpperCase(),
            $("input[name=citystate]").val().toUpperCase(),
            $("input[name=zipcode]").val().toUpperCase(),
            $("input[name=itemtype]:checked").val(),
            function (ids) {
                var packageObj = getPackage(ids.packageID);
                // Reset item type to default
                $("input[name=itemtype][data-default=1]").prop("checked", true);
                $("#historylist").prepend('<li class="history-list-item item-content" data-package="' + ids.packageID + '">'
                        + '  <div class="item-media">'
                        + '    <i class="icon ' + getIconForType(packageObj.type) + '"></i>'
                        + '  </div>'
                        + '  <div class="item-inner">'
                        + '    <div class="item-title">'
                        + '      ' + packageObj.address
                        + '    </div>'
                        + '  </div>'
                        + '</li>');
                $("#tap-to-remove-history-prompt").removeClass("display-none");
            });
});

// Remove any pre-existing click handlers from the history list,
// otherwise the user will see a number of confirm prompts equal to the number
// of times they've opened the add items page
$(".view-main").off("click", "#historylist .history-list-item");

$(".view-main").on("click", "#historylist .history-list-item", function () {
    console.log("Info", "Asking to delete ", $(this).data("package"));
    confirmDeletePackage(getPackage($(this).data("package")), function (id) {
        console.log("Info", "Removing history item", id);
        $('#historylist .history-list-item[data-package="' + id + '"]').remove();
        if ($('#historylist .history-list-item').length == 0) {
            $("#no-history").removeClass("display-none");
            $("#tap-to-remove-history-prompt").addClass("display-none");
        }
    });
});

document.getElementById("housenumberinput").onfocus = function () {
    document.getElementById("housenumberinput").value = "";
}

document.getElementById("unitinput").onfocus = function () {
    document.getElementById("unitinput").value = "";
}

// Restore user's last entered city/state combo
if (inStorage("citystate")) {
    $("input[name=citystate]").val(getStorage("citystate").replace(/\s*[0-9]{5}$/, ""));
}
if (inStorage("zipcode") && getStorage("zipcode").trim() != "") {
    $("input[name=zipcode]").val(getStorage("zipcode"));
} else {
    if (inStorage("citystate") && /^.+ [0-9]{5}$/.test(getStorage("citystate"))) {
        $("input[name=zipcode]").val(getStorage("citystate").split(" ").pop());
    }
}

function toggleLettersInAddressNumber() {
    if ($("#address-has-letters-checkbox").prop("checked")) {
        // disallow
        $("#address-has-letters-checkbox").prop("checked", false);
        $("#housenumberinput").attr("type", "number");
        $("#housenumberinput").attr("placeholder", "1234");
        $("#housenumberinput").attr("inputmode", "numeric");
    } else {
        // allow
        $("#address-has-letters-checkbox").prop("checked", true);
        $("#housenumberinput").attr("type", "text");
        $("#housenumberinput").attr("placeholder", "1A2B3");
        $("#housenumberinput").attr("inputmode", "text");
    }
}


function setTabSwipable() {
    var page = $(".page[data-name=add]");

    // If the page has grown larger, refresh to disable swiping tabs
    if (page.width() >= 768 && $(".tabs-swipeable-wrap")[0]) {
        router.refreshPage();
    }
}

function addPackageBarcode(code) {
    playSound("scan");
    if (code != "") {
        addPackageByBarcode(code, $("input[name=itemtype]:checked").val(),
                function (ids) {
                    var packageObj = getPackage(ids.packageID);
                    // Reset item type to default
                    $("input[name=itemtype][data-default=1]").prop("checked", true);
                    $("#historylist").prepend('<li class="history-list-item item-content" data-package="' + ids.packageID + '">'
                            + '  <div class="item-media">'
                            + '    <i class="icon ' + getIconForType(packageObj.type) + '"></i>'
                            + '  </div>'
                            + '  <div class="item-inner">'
                            + '    <div class="item-title">'
                            + '      ' + packageObj.address
                            + '    </div>'
                            + '  </div>'
                            + '</li>');
                    $("#tap-to-remove-history-prompt").removeClass("display-none");
                    $("#no-history").addClass("display-none");
                });
    } else {
        app.dialog.alert("Invalid barcode.", "Error");
    }
}

$(".scanbarcodebtn").click(function () {
    scanBarcode(function (code) {
        addPackageBarcode(code);
    }, function (error) {
        app.dialog.alert(error, "Error");
    });
});


$(window).on('resize', setTabSwipable);

setTabSwipable();