var kotti = {
    dom_changed_handlers: new Array()
};

(function($) {

    $.fn.find2 = function(selector) {
        // A find() that also return matches on the root element(s)
        return this.filter(selector).add(this.find(selector));
    };


    kotti.messages = function(node) {
        node.find2("#messages").hide();
        node.find2(".message").each(function() {
            var type = "notice";
            var msg = $(this);
            var text = msg.html();
            var stayTime = 3000;

            if (msg.hasClass("success"))
                type = "success";
            else if (msg.hasClass("error")) {
                type = "error";
                stayTime = 6000;
            }

            $().toastmessage('showToast', {
                text: text,
                type: type,
                stayTime: stayTime,
                sticky: false,
                position: 'center',
                closeText: 'X'
            });

            $('.toast-container').appendTo("#div_toast");

        });
    };


    kotti.dropdowns = function(node) {
        node.find2(".dropdown-trigger").click(function () {
            var target = $($(this).attr("href"));
            // move the dropdown to the correct position
            target.css("left", $(this).position().left);
            $("body").click(function() {
                target.hide();
                $(this).unbind("click");
            });
            target.toggle();
            return false;
        });
    };

    kotti.dom_changed = function(node) {
        $.each(kotti.dom_changed_handlers, function(index, func) {
            func(node);
        });
    };

    kotti.main = function(handlers) {
        var node = $('html');
        if (!handlers) {
            handlers = [kotti.messages, kotti.dropdowns];
        }
        $.each(handlers, function(index, func) {
            kotti.dom_changed_handlers.push(func);
        });
        kotti.dom_changed(node);
    };

 })(jQuery);

