Event.observe(window, "load", function() {
    var body = $$('body')[0];

    var carousel = $("carousel");
    if (carousel) {
        new Carousel(carousel, {
            numVisible: 6,
            buttonStateHandler: carouselButtonStateChanged
        });
    }

    if (body.hasClassName("items") && body.hasClassName("index")) {
        var loc = window.location.toString();
        if (loc.indexOf("#") != -1) {
            var match = /http:\/\/[^\/]+\/categories\/([0-9]+)/(loc);
            if (match) {
                var item = loc.substring(loc.indexOf("#") + 1, loc.length);
                new Ajax.Request('/categories/' + match[1] +
                                 '/items/' + item + '.js',
                                 {
                                     asynchronous: true,
                                     evalScripts: true,
                                     method:'get'
                                 });
            }
        }
    }
});

function carouselButtonStateChanged(button, enabled) {
    button = $(button);

    if (!enabled)
        button.addClassName("disabled");
    else if (button.hasClassName("disabled"))
        button.removeClassName("disabled");
}

function swapEvenOdd(item) {
    var even = item.hasClassName("even");
    item.removeClassName(even ? "even" : "odd").addClassName(even ? "odd" : "even");
}

function deleteItem(item) {
    item = $(item);
    var siblings = item.nextSiblings();
    item.remove();
    siblings.each(swapEvenOdd);
}

function modalboxEdit(link) {
    Modalbox.show(link.href + "?nolayout=t", {width: 600, title: link.title, afterLoad: modalboxWatchFile});
}

var filechanged;
function modalboxFileChanged() {
    if (!filechanged) {
        filechanged = true;
        var button = $('modalbox_save');
        button.form.action += "?" + Hash.toQueryString({"_redirect_on[success]": "/admin"});
        button.onclick = function () { button.form.submit() };
    }
}

function modalboxWatchFile() {
    filechanged = false;
    Event.observe($$("#MB_content input[type=file]").first(), 'change', modalboxFileChanged);
}
