/*
 *  Copyright 2007 hkrn <hikarin@users.sourceforge.jp>
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 * Zeromin.Filter.NGWord
 * $Id: ngword.js 79 2007-01-11 12:25:09Z hikarin $
 */

if ( typeof Zeromin.Filter == "undefined" ) {
    Zeromin.Filter = {};
}

Zeromin.Filter.NGWord = function(id, bbs) {
    this.bbsID  = id  || 0;
    this.bbsDir = bbs || '';
    this.cache  = [];
    this.index  = {};
    this.type   = {
        "4": "置換単語への置換",
        "2": "禁止単語の削除",
        "1": "書き込みの禁止"
    }
}

Zeromin.Filter.NGWord.prototype = {
    "getID": function () { return this.bbsID },
    "getBBS": function () { return this.bbsDir },
    "getCache": function () { return this.cache; },
    "setCache": function (cache, add) {
        add ? this.cache.push(cache) : this.cache = cache;
        return this;
    },
    "setIndex": function (key, i) {
        this.index[key] = i || this.cache.length;
    },
    "removeCache": function (data) {
        var count = 0;
        for ( var removedID in data ) {
            if ( !data[removedID] ) continue;
            var i = this.index[removedID];
            if ( i ) {
                delete this.index[removedID];
                this.cache.splice(i, 1);
                count++;
            }
        }
        return count;
    },
    "setBBS": function (id, bbs) {
        if ( this.bbsDir != bbs ) {
            this.bbsID        = id;
            this.bbsDir       = bbs;
            this.cache.length = 0;
        }
        return this;
    },
    "get": function(id) {
        var cache = this.cache;
        var i     = this.index[id];
        return i ? cache[i]
            : { "id":    "",
                "bbs":   "",
                "entry": "",
                "regex": "",
                "type":  "",
                "to":    ""
            }
    },
    "getTypeString": function(typeId) {
        return this.type[typeId] || this.type[1];
    },
    "load": function (entriesByPage) {
        var self = this;
        Zeromin.getIO().load(
            this.toParam("load"),
            function (storage) {
                var data = storage.read() || []
                var root = document.getElementById("filterNGWordRoot");
                var ls = $(document.getElementById("filterNGWordTable"));
                $("ul.nav-page", root).remove();
                ls.empty();
                var bbsId    = self.bbsID;
                var bbsDir   = self.bbsDir;
                var typeHash = self.getType;
                for ( var i in data ) {
                    var item   = data[i];
                    var id     = item.id;
                    var tdBase = document.createElement("td");
                    tdBase.appendChild(
                        $(document.createElement("input")).attr({
                            "type" : "checkbox",
                            "name" : "id",
                            "value": id
                        }).get(0)
                    );
                    var lnk = $(document.createElement('a'));
                    lnk.href("javascript:Zeromin.getFilterNGWord().setBBS("
                        + bbsId + ",\"" + bbsDir + "\").editForm(\""
                        + id + "\")");
                    lnk.append(document.createTextNode(item.entry));
                    var tdWord = document.createElement("td");
                    tdWord.appendChild(lnk.get(0));
                    var tdType = document.createElement("td");
                    tdType.appendChild(
                        document.createTextNode(
                            self.getTypeString(item.type))
                    );
                    var tdSubs = document.createElement("td");
                    tdSubs.appendChild(
                        document.createTextNode(item.to)
                    );
                    var trBase = document.createElement("tr");
                    trBase.appendChild(tdBase);
                    trBase.appendChild(tdWord);
                    trBase.appendChild(tdType);
                    trBase.appendChild(tdSubs);
                    ls.append(trBase);
                    self.setIndex(id, i);
                }
                Zeromin.DOM.makePager(ls.parent(),
                    (Zeromin.intval(entriesByPage) || 15));
                if ( self.bbsID ) {
                    Zeromin.DOM.renderLeftMenu("leftMetaBBSLocalMenu");
                    Zeromin.DOM.toggleMenu("bbs");
                }
                else {
                    Zeromin.DOM.renderLeftMenu("leftMetaGlobalMenu");
                    Zeromin.DOM.toggleMenu("global");
                }
                Zeromin.DOM.setFunction("NGWORD - list");
                Zeromin.DOM.statusOK("NGワード一覧を表示しました", 1000);
                $(".Container", document).hide();
                $(root).show();
            },
            this
        );
    },
    "save": function () {
        var self  = this;
        var param = this.toParam("save",
                        document.getElementById("filterNGWordForm"));
        var ngword  = Zeromin.DOM.deserialize(param);
        Zeromin.getIO().load(
            param,
            function (storage) {
                var message;
                if ( storage.isReturnedSuccess() ) {
                    var id  = storage.get("id");
                    var bbs = Zeromin.intval(ngword.bbs);
                    if ( id != null ) {
                        message = "NGワードを登録しました";
                    }
                    else {
                        id = ngword.id;
                        var removeFrom = new Object();
                        removeFrom[id] = true;
                        self.removeCache(removeFrom);
                        message = "NGワード情報を編集しました";
                    }
                    if ( bbs == self.bbsID ) {
                        self.setCache({
                            "id":    id,
                            "bbs":   bbs,
                            "entry": ngword.entry,
                            "regex": "",
                            "type":  (Zeromin.intval(ngword.type) || 1),
                            "to":    ngword.to
                        }, true);
                    }
                    self.setIndex(id);
                }
                storage.writeStatus( message, { "2": "NGワードがありません" } );
            },
            null
        );
    },
    "remove": function () {
        var self = this;
        Zeromin.getIO().load(
            this.toParam("remove", document.getElementById("filterNGWordTable")),
            function (storage) {
                var removed = storage.get("removed");
                if ( removed == null ) {
                    Zeromin.DOM.statusNG("指定された処理は実行されませんでした");
                    return;
                }
                else {
                    self.removeCache(removed);
                    storage.writeStatus("指定されたNGワードを削除しました");
                }
            },
            null
        );
    },
    "editForm": function(id) {
        var item = this.get(id);
        var root = document.getElementById("filterNGWordForm");
        item["bbs"] = this.bbsID;
        Zeromin.getBBS().renderSelectBox("全ての掲示板");
        Zeromin.DOM.fillForm(root, item, {
            "select-one-callback": function ( item, element ) {
                var val = item[element.name] || "";
                var opt = element.options;
                var len = opt.length;
                for (var i = 0; i < len; i++) {
                    var o      = opt[i];
                    o.selected = (o.value == val ? true : false);
                }
            }
        });
        this.render("edit");
    },
    "render": function (renderType) {
        var bbsId = this.bbsID;
        var root  = document.getElementById("filterNGWordForm");
        if ( bbsId ) {
            Zeromin.DOM.renderLeftMenu("leftMetaBBSLocalMenu");
            Zeromin.DOM.toggleMenu("bbs");
        }
        else {
            Zeromin.DOM.renderLeftMenu("leftMetaGlobalMenu");
            Zeromin.DOM.toggleMenu("global");
        }
        $(".Container", document).hide();
        switch (renderType) {
            case "create":
            default:
            Zeromin.DOM.setFunction("NGWORD - create");
            Zeromin.getBBS().renderSelectBox("全ての掲示板");
            $("input[@name='id']", root).val('');
            $("input[@name='entry']", root).removeAttr("readonly");
            $("select[@name='bbs']", root).each(function(){
                var opt = this.options;
                var len = opt.length;
                for (var i = 0; i < len; i++) {
                    var o      = opt[i];
                    o.selected = (o.value == bbsId ? true : false);
                }
            });
            break;
            case "edit":
            Zeromin.DOM.setFunction("NGWORD - edit");
            $("input[@name='entry']", root).attr({ "readonly": true });
            break;
        }
        $(document.getElementById("filterNGWordForm")).show();
    },
    "toParam": function (meth, query) {
        var a = (query != null) ? $(query).fastSerialize() : [];
        a.push({ "name": "C",    "value": "filter"   });
        a.push({ "name": "M",    "value": meth       });
        a.push({ "name": "type", "value": "ngword"   });
        a.push({ "name": "bbs",  "value": this.bbsID });
        return a;
    },
    "toString": function() { return "" }
};
