function displayPopup(event)
{
    $.ajax({
        url: $(this).attr('href'),
        beforeSend: function(xhr) {xhr.setRequestHeader('X-Popup', 'true'); },
        success: function(html) {
            var title = $(html).find('h2').text();
            var dialog = $(html).dialog({modal: true, title: title, width: 'auto'});
            var buttons = Array();
            var form = $(dialog).find('form');
            $(form).next('br').remove();
            $(dialog).find('.buttons').hide();
            $(html).find('.buttons input, .buttons button').each(function(idx, elem) {
                var button = Object();
                button.text = $(elem).val() || $(elem).text();
                var name = $(elem).prop('name');
                if (name === 'cancel') {
                    button.click = function() { $(this).dialog('close'); return false; };
                } else {
                    button.click = function() { $(form).find('[name='+name+']').click(); return false; };
                }
                if (name === 'submit') {
                    button['class'] = 'submit-button';
                } else if (name === 'cancel') {
                    button['class'] = 'cancel-button';
                } else if (name === 'delete') {
                    button['class'] = 'delete-button';
                }
                buttons.push(button);
            });
            buttons.reverse();
            $(dialog).dialog('option', 'buttons', buttons);
            $(dialog).find('h2').remove();
            $(dialog).find('a.cancel').click(function() { $(dialog).dialog('destroy'); return false;});
            $(dialog).find('input[name=cancel]').click(function() { $(dialog).dialog('destroy'); return false;});
            if ($(dialog).find('textarea,input:visible').length) {
                $(dialog).find('textarea,input:visible')[0].focus();
            }
            $(document).trigger('wcs:dialog-loaded', $(dialog));
            return false;
        }
    });
    return false;
}

$(function() {
    $('a[rel=popup]').click(displayPopup);
    $(document).on('wcs:dialog-loaded', function(e, dialog) {
        if ($(dialog).find('input[name$=add_element]').length) {
            prepare_widget_list_elements();
        }
        if (jQuery.fn.colourPicker !== undefined) {
          jQuery('select.colour-picker').colourPicker({title: ''});
        }
    });
});
