$(function () {
    {
        var controller = $(".mark").controller( $("#active-mark-position").val() ).moveMySelf();
        $.hotkeys.add("j", controller.options, function () {
            controller.next();
        });
        $.hotkeys.add("k", controller.options, function () {
            controller.prev();
        });
        $.hotkeys.add("x", controller.options, function () {
            var c = $("#item_checkbox_{0}".format( controller.active )),
                p = $("#item_parent_{0}".format( controller.active ));
            c.attr("checked", !c.attr("checked")).attr("checked") ? p.addClass("active") : p.removeClass("active");
        });
        $.hotkeys.add("d", controller.options, function () {
            $("#item-delete-1").click();
        });
        $.hotkeys.add("o", controller.options, function () {
            var href = $("#item_permalink_{0}".format( controller.active )).attr("href");
            href && ( location.href = href );
        });
        $.hotkeys.add("e", controller.options, function () {
            var href = $("#item_edit_{0}".format( controller.active )).attr("href");
            href && ( location.href = href );
        });
        $.hotkeys.add("return", function () {
            var href = $("#item_edit_{0}".format( controller.active )).attr("href");
            href && ( location.href = href );
        });
        $.hotkeys.add("s", controller.options, function () {
            $("#item_star_{0}".format( controller.active )).click();
        });
        $.hotkeys.add("c", controller.options, function () {
            $("#item_label_{0}".format( controller.active )).click();
        });
    }
    var parent    = $("tr.parent"),
        checkboxs = $("#archive-table :checkbox").each(function (i) {
                        $( this ).bind("click", function () {
                            this.checked ? $( parent[i] ).addClass("active") : $( parent[i] ).removeClass("active");
                            controller.move(i);
                            this.blur && this.blur();
                        });
                        this.checked && $( parent[i] ).addClass("active");
                    }),
        item_deletes = $("#item-delete-1, #item-delete-2"),
        stars = $(".star").each(function (i) {
            var t, f;
            $( this ).bind("click", function () {
                t = $( this ).find("span"),
                f = t.hasClass("star-on");
                if ( f ) {
                    t.removeClass("star-on").addClass("star-off");
                } else {
                     t.removeClass("star-off").addClass("star-on");
                }
                controller.move(i);
                saver.set( checkboxs[i].value, {
                    star_state : f ? 0 : 1,
                    star_def   : f ? 1 : 0
                });
                saver.start();
            });
        }),
        labels = $(".label").each(function (i) {
            $( this ).bind("click", function () {
                var span   = $( this ).find("span"),
                    colors = ["none", "red", "yellow", "green", "blue", "purple"],
                    a = span.attr("title"),
                    n = colors[ colors.indexOf( a ) + 1 ] || colors[0];
                span.removeClass("label-{0}".format(a)).addClass("label-{0}".format(n)).attr("title", n);
                controller.move(i);
                saver.set( checkboxs[i].value, {
                    color_state : n,
                    color_def   : a
                });
                saver.start();
            });
        }),
        saver = (function () {
            return {
                items  : {},
                set : function (item_id, opt) {
                    if ( !this.items[ item_id ] )
                       this.items[ item_id ] = {};
                    if ( typeof this.items[ item_id ].star_def == 'undefined' && typeof opt.star_def != 'undefined' )
                       this.items[ item_id ].star_def = opt.star_def;
                    if ( typeof opt.star_state != 'undefined' )
                       this.items[ item_id ].star_state = opt.star_state;
                    if ( typeof this.items[ item_id ].color_def == 'undefined' && opt.color_def )
                       this.items[ item_id ].color_def = opt.color_def;
                    if ( opt.color_state )
                       this.items[ item_id ].color_state = opt.color_state;
                },
                start : function (timer) {
                    this.stop(function () {
                        this.tid = setTimeout(function () {
                            $.each( saver.items, function (i,o) {
                                ( o.star_def == o.star_state ) && ( o.color_def == o.color_state ) && ( delete saver.items[ i ] );
                            });
                            var data = saver.items.toSource
                                        ? saver.items.toSource().slice(1,-1)
                                        : $.toJSON( saver.items );
                            if ( data.length > 2 ) {
                               $.post("/internal_api/item/update_opt", {
                                   data : data
                               }, function (json) {
                                   eval("var res = " + json);
                                   if ( res.status == 'success' ) {
                                        saver.items = {};
                                   } else {
                                   }
                               });
                            }
                        }, timer || 1000);
                    });
                },
                stop  : function (callback) {
                    if ( this.tid != null ) {
                        clearTimeout( this.tid );
                        this.tid = null;
                    }
                    if ( typeof callback == 'function' )
                       return callback.call(this);
                },
                tid   : null
            }
        })();
    {
        window.onbeforeunload = function () {
            var data = saver.items.toSource ? saver.items.toSource().slice(1,-1) : $.toJSON( saver.items );
            if ( data != '{}' ) {
               $.post("/internal_api/item/update_opt", {
                   data : data
               }, function (json) {});
            }
        }
    }
    $("#select-all-1, #none-select-all-1, #select-all-2, #none-select-all-2").bind("click", function () {
        var s = this.id.indexOf("none") != -1 ? false : true;
        checkboxs.attr("checked", s);
        s ? parent.addClass("active") : parent.removeClass("active") ;
    });
    var cid = setInterval(function () {
        checkboxs.filter(":checked").size() ? item_deletes.attr("disabled", false) : item_deletes.attr("disabled", true);
    }, 200);
    item_deletes.bind("click", function () {
        this.blur();
        var target = $("#archive-table :checkbox").filter(function () {
            return this.checked;
        });
        if ( !target.size() )
           return false;
        if ( confirm("本当に削除しますか?") ) {
            var params = {},
                path   = "";
            if ( target.size() == 1 ) {
               path = "/internal_api/item/delete";
               params["item_id"] = target.val();
            } else {
               var ids = [];
               target.each(function (i,o) { ids.push( o.value ); });
               path = "/internal_api/item/delete_multi";
               params["item_ids"] = ids.join(",");
            }
            Lightbox.show();
            $.post(path, params, function (json) {
                eval("var res = " + json);
                if ( res.status == 'success' ) {
                   setTimeout(function () {
                       location.reload( true );
                   }, 1000);
                } else {

                }
            });
        }
    });
});
