// ----------------------------------------------------------------------------
// jQuery Dialog-related functions
// ----------------------------------------------------------------------------
// When the document is loaded:
$(document).ready(function(){
    // Add the jqueryDialog div to the document (only the first time)
    if ($("#jqueryDialog").length == 0) {
        // This is the first time the dialog has been opened
        // Create the dialog DIV
        $("body").append("<div id='jqueryDialog'></div>");
    }
    bindDialogOpener();
});

// --------------------
// Bind Dialog Opener
// --------------------
function bindDialogOpener(onLoadFunction) {
    if (!onLoadFunction) onLoadFunction = onLoadDialog; // default onload handler
    $(".jqueryDialog").bind("click",function(e){
	// get the URL from the href attribute
	var url = $(e.target).attr("href");
	getHTMLforDialog(url,onLoadFunction);
	return false; // so that we don't leave this page'
    });
}

// --------------------
// Get HTML for Dialog
//    Arguments: URL (string), callBack (function)
//    - callBack is the function that will be called when the document at the specified url is finished loading.
function getHTMLforDialog(url,callBack,postVars) {
    if (!postVars) postVars = {};
    // use post instead of get to avoid IE's nasty caching bug
    $.post(url,postVars,function(html){
	$("#jqueryDialog").html(html);
	// Get the title from the html
	var title = $("#jqueryDialog p.title").text();
	// Get the width from the title tag's dialogWidth attribute (eg. <p class="title" dialogWidth="500">)
	var width = parseInt($("#jqueryDialog p.title").attr('dialogWidth'));
	if (!width) width=800; // default width=800
	// Get the button label from the buttonLabel attribute of the title tag
	var buttonLabel = $("#jqueryDialog p.title").attr('buttonLabel');
	if (!buttonLabel) buttonLabel = "Cancel";
	var myButton = {};
	myButton[buttonLabel]= function(e){ $(this).dialog("close"); };
	// Remove the title from the body of the dialog (it will be placed in the title bar)
	$("#jqueryDialog p.title").remove();
	// Set the jQuery dialog parameters
	$("#jqueryDialog").dialog({
		title: title,
		buttons: myButton,
		draggable: false,
		modal: true, // this darkens everything else on the page, like Greybox does
		width: width,
		minHeight:290,
		close:closeDialog
	    });
	callBack();
    },'html'); // specify the server response type 'html'
}

// --------------------
// On Load Dialog (gets called after the dialog load is complete)
// --------------------
function onLoadDialog() {
    // This is the default handler if no handler was specified for the dialog.
}

// --------------------
// Close Dialog (Close Dialog handler)
// --------------------
function closeDialog() {
    // Destroy the open dialog
    $("#jqueryDialog").dialog('destroy');
    // Delete the original html in the div
    $("#jqueryDialog").empty();
}