jQuery(function($) {
    // Modal dialog
    $.extend({
        modalDialog: function(content, options) {
            options = $.extend(true, {
                modal: true,
                width: 'auto',
                resizable: false,
                buttons: { 'Cancel': function() { $(this).dialog('close'); } },
                close: function() { $(this).remove(); }
            }, options);
            
            return $('<div></div>').html(content).dialog(options);
        }
    });
    
    // Default AJAX options
    $.ajaxSetup({
        dataType: 'script',
        beforeSend: function(xhr) { xhr.setRequestHeader('Accept', 'text/javascript'); }
    });
    
    $('ul.gallery-image-list').sortable({
        handle: 'a.move-gallery-image-btn',
        opacity: 0.6,
        
        update: function(e, ui) {
            $.post(e.originalTarget.href, {
                _method: 'put',
                positions: $(this).sortable('toArray')
            });
        }
    });
    
    $('a.new-gallery-image-btn, a.edit-gallery-image-btn').live('click', function() {
        $.get(this.href);
        return false;
    });
    
    $('a.delete-gallery-image-btn').live('click', function() {
        if (confirm('Are you sure you want to delete this image?')) {
            $.post(this.href, { _method: 'delete' });
        }
        
        return false;
    });
    
    $('a.move-gallery-image-btn').live('click', function() {
        // Movement is handled by jQuery UI Sortable.
        return false;
    });
    
    $('a.gallery-image-link').live('click', function() {
        var _this = $(this);
        var container = _this.parents('div.gallery-container');
        
        // Change the displayed image
        container.find('img.gallery-image').attr('src', this.href);
        
        // Change the caption
        container.children('div.gallery-caption').html(_this.find('img.gallery-image-thumbnail').attr('title'));
        
        // Set the thumbnail as selected
        _this.parent().siblings().removeClass('selected').end().addClass('selected');
        
        return false;
    });
});
