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

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

Zeromin.Cap.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;
    },
    "get": function(id) {
        var cache = this.cache;
        var i     = this.index[id];
        return i ? cache[i] : { "id": "", "name": "", "gname": "" };
    },
    "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;
    },
    "load": function (entriesByPage) {
        var self = this;
        Zeromin.getIO().load(
            this.toParam("load"),
            function(storage){
                var data = storage.read() || [];
                var root = document.getElementById("capRoot");
                $("ul.nav-page", root).remove();
                var ls   = $(document.getElementById("capTable")).empty();
                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.getCap().setBBS("
                        + self.getID() + ",\"" + self.getBBS()
                        + "\").editForm(\"" + id + "\")");
                    lnk.append(document.createTextNode(item.name));
                    var tdName = document.createElement("td");
                    tdName.appendChild(lnk.get(0));
                    var tdGroup = document.createElement("td");
                    tdGroup.appendChild(
                        document.createTextNode(item.gname)
                    );
                    var trBase = document.createElement("tr");
                    trBase.appendChild(tdBase);
                    trBase.appendChild(tdName);
                    trBase.appendChild(tdGroup);
                    ls.append(trBase);
                    self.setIndex(id, i);
                }
                Zeromin.DOM.makePager(ls.parent(),
                    (Zeromin.intval(entriesByPage) || 15));
                Zeromin.DOM.renderLeftMenu("leftCapMenu");
                Zeromin.DOM.toggleMenu("global");
                Zeromin.DOM.setFunction("CAP - list");
                Zeromin.DOM.statusOK("キャップ一覧を表示しました", 1000);
                $(".Container", document).hide();
                $(root).show();
            },
            this
        );
    },
    "save": function () {
        var self  = this;
        var param = this.toParam("save", document.getElementById("capForm"));
        var cap   = 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 = cap.id;
                        var removeFrom = new Object();
                        removeFrom[id] = true;
                        self.removeCache(removeFrom);
                        message = "キャップアカウントを編集しました";
                    }
                    self.setCache({
                        "id":    id,
                        "name":  cap.name,
                        "gname": Zeromin.getCgroup().getName(cap.group)
                    }, true);
                    self.setIndex(id);
                }
                storage.writeStatus(
                    message, {
                        "2": "キャップ名がありません",
                        "3": "キャップグループが設定されていません",
                        "4": "キャップのパスワードが設定されていません",
                        "5": "キャップの確認用パスワードがが設定されてません",
                        "6": "キャップのパスワードと確認用のパスワードが一致していません",
                        "7": "存在しないキャップグループが設定されています"
                    }
                );
            },
            null
        );
    },
    "remove": function () {
        var self = this;
        Zeromin.getIO().load(
            this.toParam("remove", document.getElementById("capTable")),
            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("capForm");
        Zeromin.DOM.fillForm(root, item, {
            "select-one-callback": function ( item, element ) {
                var val = item["gid"];
                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) {
        Zeromin.getCgroup().renderSelectBox();
        Zeromin.DOM.renderLeftMenu("leftCapMenu");
        Zeromin.DOM.toggleMenu("global");
        $(".Container", document).hide();
        switch (renderType) {
            case "create":
            default:
            var cf = document.getElementById("capForm");
            Zeromin.DOM.resetForm(cf);
            Zeromin.DOM.setFunction("CAP - create");
            break;
            case "edit":
            Zeromin.DOM.setFunction("CAP - edit");
            break;
        }
        $(document.getElementById("capForm")).show();
    },
    "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": "individual" });
        return a;
    },
    "toString": function() { return "" }
};
