var deleteItem = function(item, url) {
    $.ajax({
        type:"DELETE",
        url: url,
        success: function(msg) {
            // TODO This should modify the exhibit database rather than reloading the page
            window.location.reload( true );
        },
        error: function(xhr, status, error) {
            deleteFailed(item);
                    
        }
    });
};

function deleteFailed(item) {
    item.qtip("api").updateContent("<div style='display:none;'></div>")
        .updateContent(
            $("<div class='user-dialog-message'>Delete Failed<span class='ok-button button ui-state-default ui-corner-all' title='OK'>OK</span></div>")
            .find(".ok-button").click(function() {
                item.qtip("hide");
            }).end()
        );
}

function createPopup(selector, title, beforeShow) {
    
    selector.qtip({
       content:{
           text: "<img src='/site_media/images/loading.gif' alt='loading'/>",
           title: {
               text: title,
               button: "<span class='ui-icon ui-icon-closethick'/>"
           }
       },position: {
           adjust:{
               screen: true
           }
       },
       show:{when:'click', ready:true,delay:0},
       hide: 'unfocus',
       style: {
         width: {
             min:"0",
             max:"300"
         },
           name: 'themeroller'
       },

       api: {
           beforeShow:  beforeShow,
           onHide: function(event) {
               selector.qtip("destroy");
           }
       }
       
    });
    
    selector.qtip("api").show();
}

$(document).ready(function() {

    // TODO: Move commonalities into one location.
    $("div.freemix-lens")
    .find("a.data_delete").live('click', function() {
        $this = $(this);
        createPopup($this, "Delete this Data Profile", function(event) {
            var url = $this.attr("href");
            var api = $this.qtip("api");
            // Get the list of freemixes
            $.getJSON(url + "?list_freemixes", function(data, status) {
                if (data.items && data.items.length > 0) {

                    var dialog = $("<div class='user-dialog-message'>Deleting this data profile will delete the following Freemixes built on it. <ul class='ui-helper-clearfix'></ul> " +
                            "Really delete this data profile?<div><button class='ok-button' title='OK'>OK</button>" +
                            "<button class='cancel-button' title='Cancel'>Cancel</button></div></div>");
                    if (status == 'success') {
                        $.each(data["items"], function(inx, value) {
                            dialog.find("ul").append("<li><a href='" + value["URL"] + "'>" + value["Title"] + "</a> by <a href='" + value["OwnerURL"] + "'>" + value["Owner"] + "</a></li>");
                        });

                    } else {
                        deleteFailed($this);
                    }
                } else {
                    dialog = $("<div class='user-dialog-message'>Really delete this data profile?<div><button class='ok-button' title='OK'>OK</button>" +
                    "<button class='cancel-button' title='Cancel'>Cancel</button></div></div>");
                }    
                dialog.find(".ok-button").click(function() {
                    $this.qtip("api").updateContent("<img src='/site_media/images/loading.gif' alt='loading'/>");
                    deleteItem($this, $this.attr("href"));
                }).end()
                .find(".cancel-button").click(function() {
                    $this.qtip("hide");
                }).end()
                api.updateContent("<div style='display:none;'></div>");
                api.updateContent(dialog);
            });
            return true;
            
        });
       // deleteItem($(this).attr("href"), "Deleting this data profile will delete any Freemix built on it.  Really delete this data profile?");
        return false;
    }).end();

    $("div.freemix-lens").find("a.freemix_delete").live('click', function() {
        $this = $(this);
        createPopup($this, "Delete this Freemix",function(event) {
              $this.qtip("api").updateContent("<div style='display:none;'></div>");
              $this.qtip("api").updateContent(
                  $("<div class='ui-helper-clearfix user-dialog-message'>Really delete this Freemix?<div><button class='ok-button' title='OK'>OK</button>" +
                        "<button class='cancel-button' title='Cancel'>Cancel</button></div></div>")
                   .find(".ok-button").click(function() {
                       $this.qtip("api").updateContent("<img src='/site_media/images/loading.gif' alt='loading'/>");
                       deleteItem($this, $this.attr("href"));
                   }).end()
                   .find(".cancel-button").click(function() {
                       $this.qtip("hide");
                   }).end()
              );
              return true;
           });
        return false;
    }).end();
    
    var data = [];
    $("link[rel='exhibit/data']").each(function() {
        var url = $(this).attr("href");
        data.push(url);
    });
    $.exhibit.initializeDatabase(data, function() {
        $("body").createExhibit();
    });
    
});