/*
 * 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/.
 */


function requestPickup() {
    if (isNaN($("#pickupRequestForm #packagecount").val())) {
        app.dialog.alert("Tell us how many packages you're sending so we'll know if we miss any.", "Whoops!");
        return;
    }
    if ($("#pickupRequestForm #streetaddress").val() == "") {
        app.dialog.alert("We need an address to get the packages from. Don't have one? Find your location on fixphrase.com and use that.", "Whoops!");
        return;
    }
    if (($("#pickupRequestForm #packagelocation").val() == "" || $("#pickupRequestForm #packagelocation").val() == "OTHER") && $("#pickupRequestForm #instructions").val() == "") {
        app.dialog.alert("Give us some instructions so we know how to find your packages.", "Whoops!");
        return;
    }

    var instructions = "";
    instructions = $("#pickupRequestForm #packagelocation").val();
    instructions += " " + $("#pickupRequestForm #instructions").val();

    setStorage("lastpickupaddress", $("#pickupRequestForm #streetaddress").val());
    setStorage("lastpickupzipcode", $("#pickupRequestForm #zipcode").val());

    app.dialog.preloader("Requesting Pickup...");
    apirequest(SETTINGS.apis.requestpickup, {
        accountnumber: getStorage("accountnumber"),
        accountkey: getStorage("accountkey"),
        count: $("#pickupRequestForm #packagecount").val(),
        address: $("#pickupRequestForm #streetaddress").val() + " " + $("#pickupRequestForm #zipcode").val(),
        instructions: instructions
    }, function (success) {
        app.dialog.close();
        if (success.status == "OK") {
            app.dialog.alert(success.msg, "Pickup Requested!");
            sendActionReport("Pickup", "Pickup requested");
        } else {
            app.dialog.alert(success.msg, "Error");
            sendErrorReport("Pickup", "Pickup request", success.msg);
        }
    }, function (xhr, status, error) {
        app.dialog.close();
        app.dialog.alert("There's a server or network problem. Check your Internet connection or try again later.", "Error");
        sendErrorReport("Pickup", "Couldn't request pickup", "Server/network problem: " + xhr.status + ": " + xhr.statusText);
    }, "POST");
}