/*
 * 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[class!=noAjax]', $('#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();
    }
    
    // handle the country select field
    handleCountrySelect($('select[name="usr_country_id"]'));

    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) {
    // ie6 - ie8 hide elements
	if (!$.support.leadingWhitespace) {
		$('.hideOnDialogOpen').hide();
	}
	
    //initialise dialog     
    $('#dialog').dialog({
        autoOpen: false,
        minHeight: 80,
        width: width,
        height: height,
        resizable: false,
        title: '',
        draggable: false,
        modal: true,
        stack: false,
		bgiframe: true,
        close: function(event, ui) { $('#dialog').html('').dialog('destroy'); if(! $.support.leadingWhitespace) { $('.hideOnDialogOpen').show(); } }
        //open: function(event, ui) { $(document).bind('click', dialogBlur);}
    });
    
    showDialog(target);
}

