/*
 * $Revision: 1.20 $
 * $Author: wbonde $
 */
if( window.jQuery )
{
  ( function( $ )
  {
    var ddJSONParser;

    /**
     * ddJSONParser - special JSON parsing functionality to allow for funtions in JSON returned to DynamicDialog
     *
     * !!! For use only in DynamicDialog !!!
     *
     * TODO - clean up all interfaces which rely on such non-standard JSON returns and remove this band-aid
     */
    ddJSONParser = function( sJSON )
    {
      //Borrowed (as is) from jQuery 1.3.2
      return window["eval"]("(" + sJSON + ")");
    };

    $.DynamicDialog = function( oOptions )
    {
      var oThis = this;

      /**
       * These is to allow processes which instantiate a DynamicDialog
       * to get a handle on the xhr request and the respective
       * dialogs.
       */
      oThis.xhr                 = null;
      oThis.oInteractiveDialog  = null;
      oThis.oLoadingDialog      = null;

      /* Defaults and Check for URL*/
      var oCallback = null;
      if( typeof oOptions !== 'object' || oOptions === null )
      {
        return null;
      }

      if(( typeof oOptions.sURL === 'undefined' ) ||
         ( oOptions.sURL.replace( /^\s*$/, '' ) == '' ))
      {
        return null;
      }

      if(( typeof oOptions.sLoadingMessage === 'undefined' ) ||
         ( oOptions.sLoadingMessage.replace( /^\s*$/, '' ) == '' ))
      {
        oOptions.sLoadingMessage = 'Loading...';
      }

      sDynamicDialogId = 'jqDynamicDialog';
      if(( typeof oOptions.sDynamicDialogId !== 'undefined' ) &&
         ( oOptions.sDynamicDialogId.replace( /^\s*$/, '' ) != '' ))
      {
        sDynamicDialogId = oOptions.sDynamicDialogId;
      }

      if( typeof oOptions.show !== 'undefined' )
      {
        delete oOptions.show;
      }

      if( typeof oOptions.oRequestParameters === 'undefined' )
      {
        oOptions.oRequestParameters = {};
      }

      if( typeof oOptions.oCallback === 'function'  )
      {
        oCallback = oOptions.oCallback;
        delete oOptions.oCallback;
      }

      var bUseModal = true;
      if( typeof oOptions.bUseModal == 'boolean' )
      {
        bUseModal = oOptions.bUseModal;
        delete oOptions.bUseModal;
      }

      var mPosition = "center";
      if( typeof oOptions.oPosition !== 'undefined' )
      {
        mPosition = oOptions.oPosition;
        delete oOptions.oPosition;
      }

      //Will be called in scope of the final dialog
      var onDialogOpen = function(){};
      if( typeof oOptions.onDialogOpen === 'function' )
      {
        onDialogOpen = oOptions.onDialogOpen;
      }

      /*Create container*/
      var oThisContainer = $( '<div id="' + sDynamicDialogId + '"></div>').hide();
      var oLoadingContainer = $( '<div><div class="ui-widget ui-state-active ui-corner-all"><img src="/images/loadingsmall.gif" />' + oOptions.sLoadingMessage + '</div></div>');

      /*Show loading*/
      oThis.oLoadingDialog = oLoadingContainer.dialog( {
        autoOpen: true,
        modal: bUseModal,
        bgiframe: true,
        position: mPosition,
        width: 200,
        height: 75,
        closeOnEscape: false,
        dialogClass: 'dialogLoading',
        overlay: {
          opacity: 0.5,
          background: "white"
        },
        resizable: false,
        /* Animations on this dialog cause a race condition where it may
         * get removed before it is done showing, leaving dead elements
         * on screen.  For the same reason, we won't begin loading the real
         * dynamic dialog until this one has opened (inside th open method)
         */
        show: null,
        open: function()
        {
          $(this).parent().find( '.ui-dialog-titlebar-close' ).hide();

          /*Get Requested Dialog*/
          oThis.xhr = $.ajax( {
            url: oOptions.sURL,
            type: 'POST',
            data: oOptions.oRequestParameters,
            /* Custom data type used by DynamicDialog for non-standard JSON return */
            dataType: 'text ybx_dd_json',
            /* Map dynamic dialogs' custom data type to our private, non-standard JSON parser */
            converters: {
              'text ybx_dd_json': ddJSONParser
            },
            success: function( oData )
            {
              /*Set Default Options*/
              var oDialogOptions = {
                autoOpen: true,
                modal: bUseModal,
                bgiframe: true,
                position: mPosition,
                dialogClass: 'contentAdd',
                overlay:        {
                  opacity: 0.5,
                  background: 'white'
                },
                closeOnEscape:  false,
                open: function()
                {
                  onDialogOpen.call( this );
                },
                close:          function()
                {
                  oLoadingContainer.dialog( 'close' ).remove();
                  $( this ).dialog( 'destroy' ).remove();

                  oThis.oInteractiveDialog = null;
                  oThis.oLoadingDialog = null;

                  if( typeof oCallback === 'function' )
                  {
                    oCallback();
                  }
                }
              };
              /*Overwrite default options with options from the request*/
              if( typeof oData.oDialogOptions !== 'undefined' && oData.oDialogOptions !== null )
              {
                oDialogOptions = $.extend( oDialogOptions, oData.oDialogOptions );
              }

              $( 'body' ).append( oThisContainer );

              /*Close and remove the loading dialog*/
              oLoadingContainer.dialog( 'close' ).remove();

              /*Display the new dialog*/
              oThis.oInteractiveDialog = oThisContainer.html( oData.page_data ).dialog( oDialogOptions );
              $LAB.executeQueue();
            }
          } );
        },
        close: function()
        {
          $( this ).dialog( 'destroy' ).remove();
          oThis.oLoadingDialog = null;
        }
      } );
    };
  } )( window.jQuery );
}
