var Global = {

    /**
     * Writes a debug statement to the Firefox console if it is available. Make sure to use this method instead of
     * console.debug() since that method causes a Javascript error if the console is not available.
     * @param text Debug content.
     */
    debug: function( text )
    {
        if ( typeof(console) != "undefined" && this.enableDebug )
        {
            console.debug( text );
        }
    },

    /**
     * Reloads the current page in the browser.
     */
    reloadPage: function()
    {
        location.reload( true );
    },

    /**
     * Navigates the browser to the given url.
     * @param url
     */
    nav: function( url )
    {
        document.location.href = url;
    },

    /**
     * Builds a modal dialog.
     * @param id Id of the dialog in the dom (optional).
     * @param title Title of the dialog (optional).
     * @param body Body of the dialog (optional)
     */
    buildDialog: function( id, title, body )
    {
        if ( !id )
        {
            id = "dialog_" + (new Date( )).getTime( );
        }
        var dialog = $( '<div id="' + id + '" style="display:none;"></div>' ).appendTo( "body" );

        dialog.dialog( {
            autoOpen: false,
            bgiframe: true,
            resizable: false,
            width: 400,
            modal: true
        } );

        if ( title )
        {
            dialog.dialog( 'option', 'title', title );
        }
        if ( body )
        {
            dialog.html( body );
        }

        return dialog;
    },

    /**
     * Resets the alternating row background colors of the datagrids.
     */
    resetDatagrids: function()
    {
        $( '.datagrid tr:odd' ).addClass( 'odd' );
        $( '.datagrid tr:even' ).removeClass( 'odd' );
    },

    /**
     * Opens the url in a new window.
     * @param url Url.
     * @param name Name of the window.
     */
    openWindow: function( url, name )
    {
        window.open( url, name ).focus( );
    },

    /**
     * Opens a preview window with the given url.
     * @param url Url.
     */
    openPreview: function( url )
    {
        Global.openWindow( url, "preview" );
    }
};
Global.enableDebug = true;

Global.Ajax = {
    /**
     * Handles an error thrown during an AJAX request.
     * @param request Request data.
     * @param textStatus Status of the response (ex: 404)
     * @param errorThrown The error that was thrown.
     */
    handleError: function( request, textStatus, errorThrown )
    {
        var exceptionMsg = request.getResponseHeader( 'ExceptionMsg' );
        alert( "An Error has occured:\n\n\t" + exceptionMsg );
    },

    /**
     * Displays a "loading..." message in the specified dom node.
     * @param node Dom node.
     */
    displayLoading: function( node )
    {
        node.html( "<span class='loading'>loading...</span>" );
    },

    initDelete: function()
    {
        Global.debug( "Global.Ajax.initDelete()" );

        $( "#deleteDialog" ).dialog( {
            autoOpen: false,
            bgiframe: true,
            resizable: false,
            width: 400,
            modal: true,
            buttons: {
                "Delete": function()
                {
                    $( this ).dialog( 'close' );
                    if ( $( this ).dialog.deleteCallback )
                    {
                        $( this ).dialog.deleteCallback( );
                    }
                },
                "Cancel": function()
                {
                    $( this ).dialog( 'close' );
                    if ( $( this ).dialog.cancelCallback )
                    {
                        $( this ).dialog.cancelCallback( );
                    }
                }
            }
        } );

        $( "#deleteDialog" ).dialog.initialized = true;
    },

    /**
     * Displays a "confirm delete" modal dialog.
     * @param deleteCallback Function to call if the delete is approved (optional).
     * @param cancelCallback Function to call if the delete is cancelled (optional).
     */
    confirmDelete: function( deleteCallback, cancelCallback )
    {
        Global.debug( "Global.Ajax.confirmDelete()" );

        var deleteDialog = $( "#deleteDialog" );
        if ( !deleteDialog.dialog.initialized )
        {
            Global.Ajax.initDelete( );
        }
        deleteDialog.dialog.deleteCallback = deleteCallback;
        deleteDialog.dialog.cancelCallback = cancelCallback;
        deleteDialog.dialog( 'open' );
    },

    /**
     * Sends a delete request to the application. If the delete method returns an empty string then it is treated as a
     * successful delete, if any text is returned then it is displayed to the user.
     * @param url Url to the delete method, can contain {id} as a placeholder for the Persistable Id.
     * @param id Id to replace in the url (optional).
     * @param callBack Function to call if the delete is successful.
     */
    doDelete: function( url, id, callBack )
    {
        url = url.replace( "{id}", id );
        Global.debug( "Global.Ajax.doDelete(): url=" + url );

        $.ajax( {
            type: "POST",
            url: url,
            data: { _method: "DELETE"},
            success: function( data )
            {
                if ( data != '' )
                {
                    var dialog = Global.buildDialog( null, "The delete could not be performed", data );
                    dialog.dialog( 'open' );
                }

                else if ( callBack )
                {
                    callBack( );
                }
            },
            error: function( request, textStatus, errorThrown )
            {
                Global.Ajax.handleError( request, textStatus, errorThrown );
            }
        } );
    },

    /**
     * Uses GET to load the given url. Used for requests that do not return content such as "live" calls. If the returned
     * data is an empty string it is considered a successful call, otherwise the data is displayed to the user.
     * @param url Url to call, can contain an optional {id} placeholder.
     * @param id Id to replace in the url.
     * @param callBack Function to call if the request is successful.
     */
    doGet: function( url, id, callBack )
    {
        Global.debug( url );
        url = url.replace( "{id}", id ).replace( "%7Bid%7D", id );
        Global.debug( "Global.Ajax.doGet(): url=" + url );

        $.ajax( {
            type: "GET",
            url: url,
            success: function( data )
            {
                if ( data != '' )
                {
                    var dialog = Global.buildDialog( null, null, data );
                    dialog.dialog( 'open' );
                }

                else if ( callBack )
                {
                    callBack( );
                }
            },
            error: function( request, textStatus, errorThrown )
            {
                Global.Ajax.handleError( request );
            }
        } );
    },

    /**
     * Calls the given url to get data.
     * @param url Url to call, can contain an option {id} placeholder.
     * @param id Id to replace in the url.
     * @param callBack Function to call if the request is successful.
     */
    doGetData: function( url, id, callBack )
    {
        url = url.replace( "{id}", id ).replace( "%7Bid%7D", id );
        Global.debug( "Global.Ajax.doGetData(): url=" + url );

        $.ajax( {
            type: "GET",
            url: url,
            success: function( data )
            {
                callBack( data );
            },
            error: function( request, textStatus, errorThrown )
            {
                Global.Ajax.handleError( request );
            }
        } );
    }

};
