CmdUtils.CreateCommand({
    names: ["zip"],
    arguments: [ {role:'object', nountype: noun_arb_text, label: 'query'} ],
    url: "",
    icon: "http://groovetechnology.co.jp/favicon.ico",
    description: "Searches Zip-Code.",
    homepage: "http://www.serendip.ws/",
    author: { name: "iNo", homepage: "http://www.serendip.ws/" },
    license: "MPL",
    preview: function(pBlock, {object: {text}}) {
        if (!text) {
            pBlock.innerHTML = this.description;
            return;
        }
        var setResultData = function(json) {
            if (json) {
                if (typeof json.zipcode.a1 === 'object') {
                    return json.zipcode.a1;
                } else {
                    return null;
                }
            } else {
                return null;
            }
        };
        var me = this;
        var type = text.match(/^\d+\-?\d+$/) ? 'zipcode=' : 'word=';
        var url = "http://groovetechnology.co.jp/ZipSearchService/v1/zipsearch?" + type + encodeURIComponent(text);

        pBlock.innerHTML = _("Searching ...");
        CmdUtils.previewGet(pBlock, url, function(response) {
            var json = Utils.decodeJson(response);
            var pTemplate = "<div style=\"max-height:400px;overflow:auto;padding:5px 0;\">{for result in zipcode}<div><tt>${result.zipcode}\t${result.prefecture}${result.city}${result.town}</tt></div>{/for}</div>" +
                            "<div style=\"text-align:right;font-style:italic;\">Author iNo (<a href=\"http://www.serendip.ws/\" style=\"color:skyblue;text-decoration:underline;\">Serendip</a>)</div>" +
                            "<div style=\"text-align:right;font-style:italic;\">Powered by <a href=\"http://groovetechnology.co.jp/webservice/\" style=\"color:pink;text-decoration:underline;\">\u30B0\u30EB\u30FC\u30D6\u30C6\u30AF\u30CE\u30ED\u30B8\u30FC\x20Web\x20\u30B5\u30FC\u30D3\u30B9</a></div>";
            pBlock.innerHTML = CmdUtils.renderTemplate(pTemplate, json);

            var result = setResultData(json);
            if (result) {
                me._result.fromdata = (type === 'zipcode=') ? result.zipcode : result.prefecture + result.city + result.town;
                me._result.todata = (type === 'zipcode=') ? result.prefecture + result.city + result.town : result.zipcode;
            } else {
                me._result.fromdata = null;
                me._result.todata = null;
            }
        });
    },
    execute: function() {
        Utils.clipboard.text = this._result.todata;
        displayMessage(this._result.fromdata + "\nCopy : \"" + this._result.todata + "\"");
    },
    _result: { fromdata : null, todata: null }
});

