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

Zeromin.Category = function(data) {
    var a = data ? data : [];
    var c = {};
    for ( var i in a ) {
        c[ a[i].id ] = i;
    }
    this.cache = a;
    this.index = c;
}

Zeromin.Category.prototype = {
    "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;
    },
    "get": function (id) {
        var cache = this.cache;
        var i     = this.index[id];
        return i ? cache[i] : { "count": 0, "id": "", "name": "" };
    },
    "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.slurp() || [];
                var ls   = $(document.getElementById("categoryTable"));
                ls.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 tdName = document.createElement("td");
                    tdName.appendChild(
                        document.createTextNode(item.name)
                    );
                    var tdCount = document.createElement("td");
                    tdCount.appendChild(
                        document.createTextNode(item.count)
                    );
                    var trBase = document.createElement("tr");
                    trBase.appendChild(tdBase);
                    trBase.appendChild(tdName);
                    trBase.appendChild(tdCount);
                    ls.append(trBase);
                    self.setIndex(id, i);
                }
                Zeromin.DOM.makePager(ls.parent(),
                    (Zeromin.intval(entriesByPage) || 10));
                Zeromin.DOM.renderLeftMenu("leftBBSMenu");
                Zeromin.DOM.toggleMenu("global");
                Zeromin.DOM.setFunction("CATEGORY - list");
                Zeromin.DOM.statusOK("カテゴリ一覧を表示しました", 1000);
                $(".Container", document).hide();
                $(document.getElementById("categoryRoot")).show();
            },
            this
        );
    },
    "create": function () {
        var self     = this;
        var param    = this.toParam("save",
                           document.getElementById("categoryCreate"));
        var category = 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 = category.id;
                        var removeFrom = new Object();
                        removeFrom[id] = true;
                        self.removeCache(removeFrom);
                        message = "カテゴリを編集しました";
                    }
                    self.setCache({
                        "id":    id,
                        "count": 0,
                        "name": category.name
                    }, true);
                    self.setIndex(id);
                }
                storage.writeStatus(message, {
                    "2": "カテゴリ名がありません",
                    "3": "数字のみのカテゴリは作成できません",
                    "4": "そのカテゴリ名は既に登録済みです"
                });
            },
            null
        );
    },
    "remove": function () {
        var self = this;
        Zeromin.getIO().load(
            this.toParam("remove", document.getElementById("categoryTable")),
            function (storage) {
                var removed = storage.get("removed");
                if ( removed == null ) {
                    Zeromin.DOM.statusNG("指定された処理は実行されませんでした");
                    return;
                }
                else {
                    self.removeCache(removed);
                    Zeromin.DOM.statusOK("カテゴリを削除しました");
                }
            },
            null
        );
    },
    "renderSelectBox": function () {
        var self = this;
        Zeromin.getIO().load(
            this.toParam("load"),
            function (storage) {
                var data = storage.slurp();
                var sel  = $("select.categorySelect");
                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);
                }
            },
            this
        );
    },
    "toParam": function (meth, query) {
        var a = (query != null) ? $(query).fastSerialize() : [];
        a.push({ "name": "C", "value": "category" });
        a.push({ "name": "M", "value": meth });
        return a;
    }
};
