/*
 * closes modal windows on click outside
 */
var dialogBlur = function(event) {

    var target = $(event.target);
    
    if ((target.is('.ui-dialog') || target.parents('.ui-dialog').length) && ! target.hasClass("cancelBtn")) {
        return;
    }
    
    $('.ui-dialog:visible').find('.ui-dialog-titlebar-close').trigger('click');

    $(document).unbind('click', dialogBlur);    

} // end of dialogBlur
    

/*
 * shows the dialog
 */
function showDialog(reload) {
    
    var callback = function(){

    $('form', $('#dialog').get())
            .ajaxForm(
                      {    
                        'target': '#dialog', 
                        'success': function(data) { 
                                        var content = $('#dialog').html();
                                        showDialog(content); // call myself again, with the content of the dialog box
                                    } 
                       } 
                      );
    }; // end of callback.
  
    if(typeof reload  == 'object'){
        var url = $(reload).attr('href');                   

        var param = null;   
        
        $("#dialog").load(url, param, callback);
        
        var dialog = $('#dialog').dialog('open');
    }
    else
    {
        callback();
    }

    return false;   
}

/*
 * dynamically creates an ancor element
 */
function target(destination)
{
    var link = document.createElement("a");
    link.href = destination;
    
    return link;
}

/*
 * initialises the dialog 'window'
 * target: url where to get content from
 * width/height
 */
function dialog(target, width, height){
  
    //initialise dialog     
    $('#dialog').dialog({
        autoOpen: false,
        minHeight: 80,
        width: width,
        height: height,
        resizable: false,
        title: '',
        draggable: false,
        modal: true,
        stack: true,
		bgiframe: true,
        close: function(event, ui) { $('#dialog').html('').dialog('destroy'); }
        // open: function(event, ui) { $(document).bind('click', dialogBlur);}
    });
    
    showDialog(target);
}
