/*
 *  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.Cgroup
 * $Id: cgroup.js 79 2007-01-11 12:25:09Z hikarin $
 */

Zeromin.Cgroup = function(id, bbs) {
    this.bbsID    = id  || 0;
    this.bbsDir   = bbs || '';
    this.cache = [];
    this.index = {};
}

Zeromin.Cgroup.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 - 1;
    },
    "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) {
        this.bbsID  = id;
        this.bbsDir = bbs;
        return this;
    },
    "get": function(id) {
        var cache = this.cache;
        var i     = this.index[id];
        return i ? cache[i]
            : { "id":    "",
                "count": 0,
                "name":  "",
                "bbs":   0,
                "gname": ""
        };
    },
    "getName": function (id) {
        return this.get(id).name;
    },
    "load": function (entriesByPage) {
        var self = this;
        Zeromin.getIO().load(
            this.toParam("load"),
            function (storage) {
                var data = storage.read() || [];
                var root = document.getElementById("capGroupRoot");
                $("ul.nav-page", root).remove();
                var ls = $(document.getElementById("capGroupTable")).empty();
                var zBBS = Zeromin.getBBS();
                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.getCgroup().setBBS("
                        + self.getID() + ",\"" + self.getBBS()
                        + "\").editForm(\"" + id + "\")");
                    lnk.append(document.createTextNode(item.name));
                    var tdName = document.createElement("td");
                    tdName.appendChild(lnk.get(0));
                    var tdRange = document.createElement("td");
                    tdRange.appendChild(
                        document.createTextNode(
                            zBBS.getName(item.bbs) || "全ての掲示板"
                        )
                    );
                    var tdBelongs = document.createElement("td");
                    tdBelongs.appendChild(
                        document.createTextNode(String(item.count))
                    );
                    var trBase = document.createElement("tr");
                    trBase.appendChild(tdBase);
                    trBase.appendChild(tdName);
                    trBase.appendChild(tdRange);
                    trBase.appendChild(tdBelongs);
                    ls.append(trBase);
                    self.setIndex(id, i);
                }
                Zeromin.DOM.makePager(ls.parent(),
                    (Zeromin.intval(entriesByPage) || 15));
                Zeromin.DOM.renderLeftMenu("leftCgroupMenu");
                Zeromin.DOM.toggleMenu("global");
                Zeromin.DOM.setFunction("CAP GROUP - list");
                Zeromin.DOM.statusOK("キャップグループ一覧を表示しました", 1000);
                $(".Container", document).hide();
                $(root).show();
            },
            this
        );
    },
    "save": function () {
        var self   = this;
        var param  = this.toComplicatedParam("save",
                         document.getElementById("capGroupForm"));
        var cgroup = Zeromin.DOM.deserialize(param);
        Zeromin.getIO().load(
            param,
            function (storage) {
                var message;
                if ( storage.isReturnedSuccess() ) {
                    var id = storage.get("id");
                    if ( id != null ) {
                        message = "キャップグループを作成しました";
                    }
                    else {
                        id = cgroup.id;
                        var removeFrom = new Object();
                        removeFrom[id] = true;
                        self.removeCache(removeFrom);
                        message = "キャップグループを編集しました";
                    }
                    self.setCache({
                        "id":        id,
                        "count":     0,
                        "name":      cgroup.name,
                        "bbs":       cgroup.bbs,
                        "privilege": cgroup.p
                    }, true);
                    self.setIndex(id);
                }
                storage.writeStatus(
                    message, {
                        "2": "キャップグループ名がありません",
                        "8": "存在しないキャップグループのため、保存出来ません"
                    }
                );
            },
            null
        );
    },
    "remove": function () {
        var self = this;
        Zeromin.getIO().load(
            this.toParam("remove", document.getElementById("capGroupTable")),
            function (storage) {
                var removed = storage.get("removed");
                if ( removed == null ) {
                    Zeromin.DOM.statusNG("指定された処理は実行されませんでした");
                    return;
                }
                else {
                    self.removeCache(removed);
                    storage.writeStatus("指定されたキャップグループを削除しました");
                }
            },
            null
        );
    },
    "editForm": function(id) {
        var item = this.get(id);
        var root = document.getElementById("capGroupForm");
        var map  = { "p": "privilege", "bbs": "bbs" };
        this.render("edit");
        Zeromin.DOM.fillForm(root, item, {
            "radio-callback": function ( item, element ) {
                var v = $.grep(item["bbs"], function (i) { return i == 0 });
                element.checked |= (v.length && element.value == 1);
            },
            "select-multiple-callback": function ( item, element ) {
                var val = item[ map[ element.name ] ];
                var opt = element.options;
                var len = opt.length;
                if ( val.constructor == Array ) {
                    for ( var i = 0; i < len; i++ ) {
                        var o = opt[i];
                        var v = o.value;
                        o.selected
                            = $.grep(val,
                                function (i) { return i == v }).length
                            ? true : false;
                    }
                }
                else {
                    for ( var i = 0; i < len; i++ ) {
                        var o = opt[i];
                        o.selected = (o.value & val ? true : false)
                    }
                }
            }
        });
    },
    "render": function (renderType) {
        Zeromin.getBBS().renderSelectBox();
        Zeromin.DOM.renderLeftMenu("leftCgroupMenu");
        Zeromin.DOM.toggleMenu("global");
        $(".Container", document).hide();
        switch (renderType) {
            case "create":
            default:
            var cf = document.getElementById("capGroupForm");
            Zeromin.DOM.resetForm(cf);
            Zeromin.DOM.setFunction("cgroup - create");
            break;
            case "edit":
            Zeromin.DOM.setFunction("cgroup - edit");
            break;
        }
        $(document.getElementById("capGroupForm")).show();
    },
    "renderSelectBox": function() {
        var self = this;
        Zeromin.getIO().load(
            this.toParam("load"),
            function (storage) {
                var data = storage.read();
                if ( data.length == 0 ) return;
                var sel  = $("select.capGroupSelect");
                sel.empty();
                for ( var i in data ) {
                    var item  = data[i];
                    var opt   = document.createElement("option");
                    opt.value = item.id;
                    opt.appendChild(document.createTextNode(item.name));
                    sel.append(opt);
                }
                Zeromin.DOM.hideState();
            },
            this
        );
    },
    "toComplicatedParam": function(meth, query) {
        var a = [];
        var range_all = false;
        $("input,select", query).each(function () {
            var type = this.type;
            if ( type == "text" || type == "hidden" ) {
                a.push({
                    "name":  this.name,
                    "value": this.value
                });
            }
            else if ( type == "radio" ) {
                if ( this.checked && this.value == 1 ) {
                    a.push({ "name":  "bbs", "value": "0" });
                    range_all = true;
                }
            }
            else if ( type == "select-multiple" ) {
                var name = this.name;
                if ( name == "bbs" && !range_all ) {
                    $("option:selected", this).each(function () {
                        a.push({
                            "name":  name,
                            "value": this.value
                        });
                    });
                }
                else {
                    var privilege = 0;
                    $("option:selected", this).each(function () {
                        privilege += Number(this.value);
                    });
                    a.push({
                        "name":  name,
                        "value": privilege
                    });
                }
            }
        });
        a.push({ "name": "C",    "value": "cap"   });
        a.push({ "name": "M",    "value": meth    });
        a.push({ "name": "type", "value": "group" });
        return a;
    },
    "toParam": function (meth, query) {
        var a = (query != null) ? $(query).fastSerialize() : [];
        a.push({ "name": "C",    "value": "cap"   });
        a.push({ "name": "M",    "value": meth    });
        a.push({ "name": "type", "value": "group" });
        return a;
    },
    "toString": function() { return "" }
};
