var nuit = {};

// Setup Functions

nuit.csrftoken = $.cookie('csrftoken');

nuit.csrfSafeMethod = function(method) {
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
};

nuit.setup = function() {

    // Enable AJAX requests in Django
    $.ajaxSetup({
        crossDomain: false,
        beforeSend: function(xhr, settings) {
            if (!nuit.csrfSafeMethod(settings.type)) {
                xhr.setRequestHeader("X-CSRFToken", nuit.csrftoken);
                xhr.setRequestHeader('Accept', 'application/json');
            }
        }
    });

    // Hightlight current page in menu
    $('.nuit-active-menu').each(function() {
        $('.menu-' + $(this).html()).addClass('active');
    });

    // Highlight current breadcrumb
    $('.nuit-breadcrumbs li:last-child').addClass('current');

    // Fix right-menu modals when they're closed
    $(document).on('closed', '[data-reveal]', function () {
        var modal = $(this);
        modal.attr('style', '');
    });

    // Add correct links for cog-menu
    $('.sidebar.on-right > section').each(function() {
        $this = $(this);
        if ($this.data('reveal') === "") {
            $('#right-menu-drop').append("<li><a href='#' data-reveal-id='" + $this.attr('id') + "'>" + $this.data('link') + "</a></li>");
        } else {
            $nav = $this.find('nav');
            if ($nav.length) {
                $nav.find('ul li').each(function() {
                    $li = $(this);
                    $('#right-menu-drop').append($li.clone());
                });
            }
        }
    });

    // Add left-menu links to application menu on small screens
    $('.sidebar.on-left > section').each(function() {
        $this = $(this);
        $nav = $this.find('nav');
        if ($nav.length) {
            $title = $this.find('h5');
            $append_to = $('#left-menu-drop');
            if ($title.length && !$this.hasClass('main-nav')) {
                $new_li = $('<li></li>').addClass('show-for-small-only').addClass('has-dropdown');
                $new_li.append("<a href='#'>" + $title.html() + "</a>");
                $append_to.append($new_li);
                $new_ul = $("<ul class='dropdown'></ul>");
                $new_li.append($new_ul);
                $append_to = $new_ul;
            }
            $nav.find('ul li').each(function() {
                $li = $(this);
                $append_to.append($li.clone().addClass('show-for-small-only'));
            });
            $('#left-menu-drop').append("<li class='show-for-small-only divider'></li>");
        }
    });

    nuit.trigger_button_bars();
    nuit.trigger_responsive_tables();

    // Setup foundation
    $(document).foundation();

};

// User functions

nuit.trigger_button_bars = function() {
    $('.button-bar .button-group').each(function() {
        var $button_group = $(this);
        var $buttons = $(this).find('.button');
        $buttons.click(function(e) {
            e.preventDefault();
            $buttons.removeClass('alert');
            $(this).addClass('alert');
            $button_group.trigger('change', $(this).data('value'));
        });
    });
};

nuit.button_bar_value = function($button_bar, value) {
    if (value === undefined) {
        return $button_bar.find('.button.alert').data('value');
    } else {
        $button_bar.find('.button').each(function() {
            $button = $(this);
            if ($button.data('value') != value) {
                $button.removeClass('alert');
            } else {
                $button.addClass('alert');
            }
        });
    }
};

nuit.trigger_responsive_tables = function() {
    // Set headers for grouped responsive tables
    $('table.responsive.grouped').find('td').each(function() {
        $td = $(this);
        $td.attr('data-title', $td.closest('table').find('th').eq($td.index()).html());
    });
    $('table.responsive.scroll').each(function () {
        $table = $(this);
        classes = 'responsive scroll';
        if ($table.hasClass('medium-down')) {
            classes += ' medium-down';
        }
        $table.wrap('<div class="' + classes + '"></div>');
    });
};

nuit.add_message = function(alert_type, message) {
    message_html = '<div data-alert class="alert-box ' + alert_type.toLowerCase() + '">' + message + '<a href="#" class="close">&times;</a></div>';
    var $message = $(message_html);
    $('.nuit-messages').append($message).foundation('reflow');
};

nuit.confirmation_box = function(user_options) {
    var defaults = {
        title:          'Confirmation required',
        description:    'Are you sure you wish to perform this action?',
        size:           'tiny',
        yes:            'Yes',
        no:             'No',
        on_confirm:     function () { console.log('Confirmed!'); },
        on_abort:       function () { console.log('Aborted!'); },
    };
    var options = $.extend({}, defaults, user_options);

    var modal = $('<div data-reveal></div>')
        .addClass('reveal-modal ' + options.size)
        .append('<h2>' + options.title + '</h2>')
        .append(options.description);

    var confirm_button = $('<a href="#" class="button">' + options.yes + '</a> ');
    var abort_button = $('<a href="#" class="right button alert">' + options.no + '</a>');

    modal.append(confirm_button);
    modal.append(abort_button);

    confirm_button.click(function() {
        modal.foundation('reveal', 'close');
        options.on_confirm();
    });

    abort_button.click(function() {
        modal.foundation('reveal', 'close');
        options.on_abort();
    });

    modal.on('closed', function() {
        $(this).remove();
    });

    $('body').append(modal);
    modal.foundation('reflow').foundation('reveal', 'open');

    console.log(options);
};

// Initialisation
nuit.setup();

@@ -2724,24 +2724,229 @@
  functions%0A%0A
+nuit.button_bar_handler = function(e) %7B%0A    e.preventDefault();%0A    e.data.buttons.removeClass('alert');%0A    $(this).addClass('alert');%0A    e.data.button_group.trigger('change', $(this).data('value'));%0A%7D%0A%0A
 nuit.trigger
@@ -3132,141 +3132,157 @@
 ons.
-click(function(e) %7B%0A            e.preventDefault();%0A            $buttons.removeClass('alert');%0A            $(this).addClass('alert');
+off('click', nuit.button_bar_handler);%0A        $buttons.on(%0A            'click',%0A            null,%0A            %7B%0A                'buttons': $buttons,
 %0A   
@@ -3286,25 +3286,29 @@
             
-$
+    '
 button_group
@@ -3311,50 +3311,76 @@
 roup
-.trigger('change', $(this).data('value'));
+': $button_group,%0A            %7D,%0A            nuit.button_bar_handler
 %0A   
@@ -3376,33 +3376,32 @@
 handler%0A        
-%7D
 );%0A    %7D);%0A%7D;%0A%0An

Fix button bar event handlers being bound more than once.