/**
 * Copyright (c) 2009 Yakabod, inc.
 * File: MicroProfile.inc
 *
 * $Id: MicroProfileDialog.js,v 1.8 2009/08/14 06:13:01 yli Exp $
 * $Revision: 1.8 $
 * $Date: 2009/08/14 06:13:01 $
 * Last edited by: $Author: yli $
 *
 * A dialog display of a MicroProfile
 * displayed automatically when an object is added
 * via the Content Add framework/
 *
 */


var nLoadedScripts = 0;
var nNeedScripts = 0;

function getMicroProfile(oEvent, oData)
{
  /* Method that we will bind to the success event. */
  var aUrn = oData.object.sURN.split(":");
  if (aUrn[2] != null && aUrn[2].toLowerCase() != 'message')
  {
    loadMicroProfile(oData.object.sURN, oData);
  }
};

function loadMicroProfile(sURN, oData)
{
  /* Load the MicroProfile - we can call this in the Firebug console for testing. */
  /* Find out if we need to load any scripts just-in-time */

  nNeedScripts = 0;
  if (typeof(bindMicroProfile) == "undefined")
  {
    nNeedScripts++;
  }
  if (typeof(appendScriptsToDOM) == "undefined")
  {
    nNeedScripts++;
  }
  if (nNeedScripts == 0)
  {
    var oMicroProfileDialog = new MicroProfileDialog(sURN, oData);
  }
  else
  {
    /* setTimeOut is needed because, even though we get the callback from
       $.getScipt, in Firefox3 and Safari, it isn't quite done yet
       and an additional wait (as little as 100ms) is needed.
    */

    nLoadedScripts = 0;
    if (typeof(appendScriptsToDOM) == "undefined")
    {
      $.getScript( '/js/vne/scriptImport.js', function()
                                              {
                                                setTimeout(function()
                                                           {
                                                             loadDialog(sURN, oData);
                                                           },
                                                           100);
                                              });
    }

    if (typeof(bindMicroProfile) == "undefined")
    {
      $.getScript('/js/vne/microProfiles.js', function()
                                              {
                                                setTimeout(function()
                                                           {
                                                              loadDialog(sURN, oData);
                                                           },
                                                           100);
                                              });
      }
  }
}

function loadDialog(sURN, oData)
{
  /* Once everything is loaded, fire off the dialog */

  nLoadedScripts++;
  if ( nLoadedScripts == nNeedScripts)
  {
    var oMicroProfileDialog = new MicroProfileDialog(sURN, oData);
  }
}

MicroProfileDialog = function(sURN, oData)
{
  this.init = function( sURN, oData )
  {
    this.sURN  = sURN;
    this.oData = oData || {};

    var url = "/microProfiles/viewMicroProfile.html?urn=" + this.sURN;
    var sDialogDiv = 'sDialogDiv';
    var sMicroProfileDiv = 'sNewMicroProfileDiv';

    var oDialogDiv = document.getElementById( sDialogDiv );
    var oMicroProfileDiv = document.getElementById( sMicroProfileDiv );
    if (oDialogDiv != null && oMicroProfileDiv != null)
    {
      bindMicroProfile(sMicroProfileDiv, url);
    }
    else
    {
      /* UI Objects */
      this.oDialog = null;              /* Container for Dialog */
      this.oMicroProfile = null;        /* Container for MicroProfile*/

      this._showMicroProfile(sDialogDiv, sMicroProfileDiv, url);
    }
  };

  this._showMicroProfile = function(sDialogDiv, sMicroProfileDiv, url)
  {
    var oThis = this;

    this.oDialog = $( document.createElement( 'div' ) ).attr( 'name', sDialogDiv ).attr( 'id', sDialogDiv );
    $( 'body' ).append( this.oDialog );

    var sMessage = 'Thanks, You Just Published the Following:';
    if(( typeof oThis.oData == 'object' ) && ( typeof oThis.oData.sMessage == 'string' ))
    {
      sMessage = oThis.oData.sMessage;
    }
    this.oMessage = $( document.createElement( 'h2' )).text( sMessage );
    this.oDialog.append( this.oMessage );
 
 		this.oMicroProfile = $( document.createElement( 'div' )).attr( 'name', sMicroProfileDiv ).attr( 'id', sMicroProfileDiv );
    this.oMessage.after( this.oMicroProfile );

    bindMicroProfile(sMicroProfileDiv, url);

    this.oDialog.dialog({ modal : false,
                          bgiframe: true,
                                  position  : "center",
                                  title     : 'New Item Confirmation',
                                  width     : 600,
                                  height    : 450,
                                  closeOnEscape: false,
                                  overlay   : {
                                                opacity: 0.5,
                                                background: "black"
                                              },
                                  buttons   : {
                                              "Close": function()
                                                        {
                                                          $(this).dialog("close");
                                                        }
                                              },
                                  close     : function(event, ui)
                                              {
                                                oThis._destroyModalContainer();
                                              },
                                  open      : function( event, ui )
                                              {
                                                oThis._bindCloseToMicroProfile();
                                              },
                                  resizable : false,
                                  draggable : true} ).dialog( 'open' );
  };

  ( function( oThis )
  {

    var nInterval, bFunctionRunning = false, bContinueWaiting = true, bBehaviorAdded = false;
    oThis._bindCloseToMicroProfile = function()
    {
      if( ! bFunctionRunning )
      {
        var $oMicroProfileDiv;

        bFunctionRunning = true;

        if( typeof nInterval !== 'number' )
        {
          nInterval = window.setInterval( oThis._bindCloseToMicroProfile, 10 )
        }

        $oMicroProfileDiv = oThis.oDialog.find( 'div.microprofile' );

        if( $oMicroProfileDiv.length > 0 )
        {
          $oMicroProfileDiv.find( 'a, button' ).each( function()
          {
            if( ! $( this ).hasClass( 'btnFavorite' ) )
            {
              $( this ).click( function()
              {
                oThis.oDialog.dialog( 'close' );
              } );
            }
          } );
          bBehaviorAdded = true;
        }

        if( ! bContinueWaiting || bBehaviorAdded)
        {
          window.clearInterval( nInterval );
        }

        bFunctionRunning = false;
      }
    };

    oThis._destroyModalContainer = function()
    {
      /* tell above interval to stop waiting for microprofile DIV if it hasn't found it yet */
      bContinueWaiting = false;
      /* empty and remove this dialog */
      oThis.oMicroProfile.empty().remove();
      oThis.oDialog.empty().remove();
    };
  } )( this );

  /* call constructor */
  this.init( sURN, oData );
};


$( document ).bind( ContentAddModuleController.callbacks.defaultEvents.success, getMicroProfile);
