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

$("body").on("submit", "#wordbox-searchbar", function (e) {
    e.preventDefault();
    dolookup($("#wordbox").val());
    return false;
});
//
//$("body").on("keypress", "#wordbox", function (e) {
//    if (e.which == 13) {
//        dolookup($(this).val());
//    }
//    return false;
//});

function dolookup(words) {
    //try {
        words = words.trim().toLowerCase().replace(/\s+/g, ' ');

        if (!/^[a-z ]+?$/i.test(words)) {
            // Not a FixPhrase, run a search
            $.getJSON(SETTINGS.apis.lookup, {
                search: words
            }, function (resp) {
                if (resp.status == "OK") {
                    lookupAndShowCoords(resp.coords[0], resp.coords[1]);
                } else {
                    alert("Error: " + resp.msg);
                }
            });
            return;
        }

        var coords = FixPhrase.decode(words);

        showLocationPopup(coords[0], coords[1], coords[3], coords[2]);
        $("#wordbox").val(coords[3]);

        var zoomlevel = 18;
        switch (coords[2]) {
            case 0.1:
                zoomlevel = 10;
                break;
            case 0.01:
                zoomlevel = 13;
                break;
        }
        map.animateMapIn(coords[0], coords[1], zoomlevel);
//    } catch (e) {
//        alert(e);
//    }
}