/****************************************************************************
 * Copyright (c) 1998-2007 Luna Imaging, Inc.  All Rights Reserved.
 *
 * This software is confidential and proprietary information of
 * Luna Imaging, Inc.  ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Luna Imaging, Inc.
 *
 * The software may not be copied, reproduced, translated or reduced to
 * any electronic medium or machine-readable form without
 * the prior written consent of Luna Imaging.
 *
 * You are not allowed to distribute the binary and source code
 * (if released) to third parties, without the prior written consent from
 * Luna Imaging.
 *
 * You are not allowed to reverse engineer, disassemble or decompile
 * code, or make any modifications of the binary or source code, remove
 * or alter any trademark, logo, copyright or other proprietary notices,
 * legends, symbols, or labels in the Software.
 *
 * You are not allowed to sub-license the Software or any derivative
 * work based on or derived from the Software.
 *
 * LUNA IMAGING MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE
 * SUITABILITY OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT
 * NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR
 * A PARTICULAR PURPOSE, OR NON-INFRINGEMENT, LUNA IMAGING SHALL NOT BE
 * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING,
 * MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
 *
 *  cruiz10020@yahoo.com
 *
 *  TemplatedPanel.js
 *
 *  Description:
 *    Renders a Panel which intern loads the template specifc to the media being displayed.
 *
 *  Structure:
 *
 *
 *  Requires:
 *    prototype.js - http://www.prototypejs.org/
 *    Yahoo Events - http://developer.yahoo.com/yui/event/
 *
 *  Development History:
 *    4-8-2007       - created
 *
 *******************************************************************************/

function TemplatedPanel( postResizeFunction, postDestroyFunction )
{
  // Html dom elements
  this.mContainer = null;
  this.mGlassPlate = null;
  this.mPanel = null;
  this.mBody = null;
  this.mIsCurrentPanel = false;

  // js Objects
  this.mControl = null;
  this.mManager = null;

  // Attributes
  this.mSourceUrl = null;
  this.mFlashPlayerUrl = null;
  this.mTemplateUrlPrefix = null;

  // Flags / state changing attributes
  this.mLoadInProgress = null;
  this.mActionInProgress = null;
  this.mMoveStartingX = null;
  this.mMoveStartingY = null;
  this.mMaximizeOnLoad = false;
  this.mInitialized = false;
  this.mConfirmBeforeClose = true;
  this.mAnimate = true;
  this.isTemplatedPanel = true;

  // Constants
  this.CLASSNAME = 'templatedPanel';
  this.CURRENT_PANEL_CLASSNAME = 'current';
  this.MOVE_CURSOR_CLASSNAME = 'moveCursor';
  this.MOVE_ACTIVE_CURSOR_CLASSNAME = 'activeMoveCursor';

  this.DEFAULT_WIDTH = 240;
  this.DEFAULT_HEIGHT = 230;
  this.MIN_SIZE = 50;

  this.MAX_LOAD_TEMPLATE_ATTEMPTS = 10;

  /**
   * Initializes all values and creates all elements required to display the panel.
   * @param startingX an optional starting x point
   * @param startingY an optional starting y point
   */
  this.init = function( startingX, startingY )
  {
    // Create html elements
    this.mPanel = $( document.createElement( 'div' ) );
    this.mGlassPlate = $( document.createElement( 'div' ) );
    this.mBody = $( document.createElement( 'iframe' ) );

    // add them all to the panel
    this.mPanel.appendChild( this.mBody );

    // add references to the TemplatedPanel
    this.mPanel.mediaPanel = this;
    this.mGlassPlate.mediaPanel = this;
    this.mBody.mediaPanel = this;

    // add events
    this.mPanel.onmousedown = Static_TemplatedPanel_StartMove;
    this.mPanel.onmouseover = Static_TemplatedPanel_MouseIn;
    this.mPanel.onmouseout = Static_TemplatedPanel_MouseOut;

    this.mBody.onmousedown = Static_TemplatedPanel_StartMove;
    this.mBody.onmouseover = Static_TemplatedPanel_MouseIn;
    this.mBody.onmouseout = Static_TemplatedPanel_MouseOut;

    // finally add the panel to the container
    this.mContainer.appendChild( this.mPanel );
    this.mContainer.appendChild( this.mGlassPlate );

    // prep image for freely moving
    this.mPanel.style.position = 'absolute';
    this.mPanel.style.overflow = 'hidden';

    var margin = 10;
    var offset = Position.page( this.mContainer );
    this.mGlassPlate.hide();
    this.mGlassPlate.style.position = 'absolute';
    this.mGlassPlate.style.left = ( offset[0] + margin ) + 'px';
    this.mGlassPlate.style.top = ( offset[1] + margin ) + 'px';
    this.mGlassPlate.style.width = ( this.mContainer.getWidth() - ( 2 * margin ) ) + 'px';
    this.mGlassPlate.style.height = ( this.mContainer.getHeight() - ( 2 * margin ) ) + 'px';
    this.mGlassPlate.style.zIndex = 99999;

    // originally for debugging, turns out IE7 needs a color other wise its as if the div is not there.
    this.mGlassPlate.style.backgroundColor = 'black';
    jshSetOpacity( this.mGlassPlate, .01 );

    this.mBody.style.position = 'absolute';
    this.mBody.style.border = '0';
    this.mBody.frameborder = '0';
    this.mBody.style.width = '100%';
    this.mBody.style.height = '100%';
    this.mBody.scrolling = 'no';

    this.hideControls();

    // set a start size and make sure we have a default level
    this.resize( this.DEFAULT_WIDTH, this.DEFAULT_HEIGHT );

    // position panel
    if( startingX && startingY )
    {
      this.moveTo( startingX, startingY );
    }

    // load the template
    this.mBody.src = this.getTemplateUrl();
    Static_TemplatedPanel_LoadTemplate( this, this.MAX_LOAD_TEMPLATE_ATTEMPTS );


  };

  this.render = function( element, startingX, startingY )
  {
    if( element )
    {
      this.mContainer = element;
      this.init( startingX, startingY );
    }
  };

  /**
   * Resize the panel size capping it to the max panel width and height
   */
  this.resize = function ( width, height, enforceMaxSize )
  {
    var toReturn = true;
    if( width && height )
    {
      // dont allow them to resize larger than the container/workspace
      width = Math.min( width, (this.mContainer.getWidth() - 20) );
      height = Math.min( height, (this.mContainer.getHeight() - 20) );

      // dont allow them to resize small than min
      width = Math.max( width, this.MIN_SIZE );
      height = Math.max( height, this.MIN_SIZE );

      // resize panel
      this.mPanel.style.width = width + 'px';
      this.mPanel.style.height = height + 'px';

      // tell the manager we have changed
      if( this.mManager )
      {
        this.mManager.imagePanelChanged( this );
      }
    }

    return toReturn;
  };

  /**
   * Moves the panel to the given x and y coordinates on the workspace/container.
   */
  this.moveTo = function ( x, y )
  {
    var offset = Position.cumulativeOffset( this.mContainer );

    //debug( '1Move: ', x, ', ', y, ' ; offset: ', offset );

    // keep within limits
    x = Math.max( x, offset[0] );
    if( ( x + this.mPanel.getWidth() ) > ( offset[0] + this.mContainer.getWidth() ) )
    {
      x = ( offset[0] + this.mContainer.getWidth() ) - this.mPanel.getWidth();
    }

    y = Math.max( y, offset[1] );
    if( ( y + this.mPanel.getHeight() ) > ( offset[1] + this.mContainer.getHeight() ) )
    {
      y = ( offset[1] + this.mContainer.getHeight() ) - this.mPanel.getHeight();
    }

    this.mPanel.style.left = x + 'px';
    this.mPanel.style.top = y + 'px';

    return true;
  };

  /**
   * Destroys the panel and notifies the manager.
   * Confirms before destroying if told to.
   */
  this.close = function( forceClose )
  {
    if( ( forceClose == true ) ||
        ( ! this.mConfirmBeforeClose ) ||
        ( confirm( this.CONFIRMATION_BEFORE_CLOSE_MESSAGE ) ) )
    {
      this.hideControls();

      // tell manager to takes us off
      this.mManager.removeImagePanel( this );

      // remove from dom
      this.mContainer.removeChild( this.mPanel );
      this.mContainer.removeChild( this.mGlassPlate );

      // notify of destroy
      if( this.mPostDestoryFunction )
      {
        this.mPostDestoryFunction( this );
      }
    }
  };

  /**
   * Resizes the image to take up as much of the cotnainer ( workspace ) by forcing
   * the image to largest size maintaing the aspect ratio.
   */
  this.maximizePanelToContainer = function ( maintainAspectRatio )
  {
    if( this.mContainer )
    {
      var dimensions = [ this.mContainer.getWidth(), this.mContainer.getHeight() ];
      this.resize( dimensions[0], dimensions[1] );
      this.centerOnContainer();
    }
  };

  /**
   * centers the panel within the container
   */
  this.centerOnContainer = function()
  {
    if( this.mContainer )
    {
      var offset = Position.cumulativeOffset( this.mContainer );
      var dimensions = [ this.mContainer.getWidth(), this.mContainer.getHeight() ];
      var panelDimensions = this.getDimensions();

      var x = Math.round( ( dimensions[0] / 2 ) - ( panelDimensions[0] / 2 ) ) + offset[0];
      var y = Math.round( ( dimensions[1] / 2 ) - ( panelDimensions[1] / 2 ) ) + offset[1];

      this.moveTo( x, y );
    }
  };

  /**
   * Updates the cursor based on the current action
   */
  this.updateCursor = function( isActive )
  {
    // set the right cursor based on current action,
    // only changes if needed to minimize IE's reloading of images
    if( this.equalsCurrentAction( this.mControl.ACTION_MOVE ) )
    {
      if( isActive == true )
      {
        if( ! this.mGlassPlate.hasClassName( this.MOVE_ACTIVE_CURSOR_CLASSNAME ) )
        {
          this.setCurrentImagePanel( this.mIsCurrentPanel );

          this.mPanel.className += ' ' + this.MOVE_ACTIVE_CURSOR_CLASSNAME;
          this.mGlassPlate.className = this.MOVE_ACTIVE_CURSOR_CLASSNAME;
          //this.mBody.className = this.MOVE_ACTIVE_CURSOR_CLASSNAME;
        }
      }
      else
      {
        this.setCurrentImagePanel( this.mIsCurrentPanel );

        this.mPanel.className += ' ' + this.MOVE_CURSOR_CLASSNAME;
        this.mGlassPlate.className = this.MOVE_CURSOR_CLASSNAME;
        //this.mBody.className = this.MOVE_CURSOR_CLASSNAME;
      }
    }

    //alert('isActive: ' + isActive + ' ; ' + this.mPanel.className);
  }

  /**
   * Passthrought to the manger, brings this panel to the front
   */
  this.bringToFront = function()
  {
    if( this.mManager )
    {
      this.mManager.setCurrentImagePanel( this );
    }
  };

  this.reset = function()
  {
    //this.maximizePanelToImage();
  };

  this.maximizePanelToImage = function()
  {
    // need to implement this
  };

  /**
   * Shows the controls by fading them out
   */
  this.hideControls = function()
  {
    if( this.mControl )
    {
      this.mControl.hideControls();
    }
  };

  /**
   * Shows any controls
   */
  this.showControls = function()
  {
    if( this.mControl )
    {
      this.mControl.showControls();
    }
  };

  /**
   * Sets te Panel's Control js object which tells the image panel
   * which operation to use.
   */
  this.setControl = function ( panelControl )
  {
    this.mControl = panelControl;
  };

  /**
   * Sets the Panel Manager
   */
  this.setManager = function( manager )
  {
    this.mManager = manager;
  };

  this.setConfirmBeforeClose = function( confirmBeforeClose )
  {
    this.mConfirmBeforeClose = confirmBeforeClose;
  };

  this.setCurrentImagePanel = function( isCurrent )
  {
    this.mIsCurrentPanel = isCurrent;

    if( this.mIsCurrentPanel )
    {
      this.mPanel.className = this.CLASSNAME + ' ' + this.CURRENT_PANEL_CLASSNAME;
    }
    else
    {
      this.mPanel.className = this.CLASSNAME;
    }
  };

  this.setStackOrder = function( index )
  {
    if( ( index >= 0 ) || ( index < 0 ) )
    {
      this.mPanel.style.zIndex = index;
    }
  };

  this.setFlashPlayerUrl = function( flashPlayerUrl )
  {
    this.mFlashPlayerUrl = flashPlayerUrl;
  };

  this.currentActionHasChanged = function( newAction )
  {
    //this.updateCursor( false );
  };

  this.endCurrentAction = function( cancelAction )
  {
    var obj = new Object();
    obj.srcElement = new Object();
    obj.srcElement.mediaPanel = this;

    if( this.mActionInProgress == true )
    {
      Static_TemplatedPanel_EndMove( obj, cancelAction );
    }
  };

  /**
   * Returns true if the given action is the current one
   */
  this.equalsCurrentAction = function( action )
  {
    if( this.mControl && ( this.mControl.getCurrentAction() == action ) )
    {
      return true;
    }

    return false;
  };

  /**
   * Gets teh current dimensions of the panel as an array
   */
  this.getDimensions = function()
  {
    var toReturn = new Array();
    var borderOffset = jshBorderOffset( this.mPanel, [0, 0] );
    toReturn[ 0 ] = this.mPanel.getWidth() - borderOffset[0];
    toReturn[ 1 ] = this.mPanel.getHeight() - borderOffset[1];

    return toReturn;
  };

  /**
   * Gets the current postion of the panel as an array
   */
  this.getPosition = function()
  {
    var toReturn = new Array();
    toReturn[ 0 ] = parseInt( this.mPanel.getStyle( 'left' ) );
    toReturn[ 1 ] = parseInt( this.mPanel.getStyle( 'top' ) );

    return toReturn;
  };

  this.getStackOrder = function()
  {
    return parseInt( this.mPanel.getStyle( 'zIndex' ) );
  };

  /**
   * Sets the image source url
   */
  this.setSourceUrl = function( sourceUrl )
  {
    if( sourceUrl )
    {
      this.mSourceUrl = sourceUrl;
    }
  };

  this.getTemplateUrl = function()
  {
	// really the media types handled should match that of the player -- flow player (flash)
	// can handle mpg, mp4 etc with no issue.
    var extensions = jshGetExtensionFromUrl( this.mSourceUrl, new Array ('mp3','flv','mpg'), 'default' );
    var url = this.mTemplateUrlPrefix;
    
    if( url.indexOf('ext=') > 0 )
      url = url.replace('ext=', 'ext=' + extensions);
    else
      url += '&ext=' + extensions;
      
    url += '&rand=' + Math.random();

    return url;
  };

  this.getAdditionalSaveAttributes = function()
  {
    if( this.mBody.contentWindow.getAdditionalSaveAttributes )
    {
      return this.mBody.contentWindow.getAdditionalSaveAttributes();
    }

    return {};
  };

  this.restoreFromState = function( derivedState )
  {
    if( this.mBody.contentWindow.restoreFromState )
    {
      this.mBody.contentWindow.restoreFromState( derivedState, debug )
    }
    else
    {
      var mp = this;
      var ds = derivedState;
      setTimeout( function(){ mp.restoreFromState(ds); }, 400 );
    }
  };

  this.setTemplateUrlPrefix = function( templateUrlPrefix )
  {
    this.mTemplateUrlPrefix = templateUrlPrefix;
  };
}


/**
 * Marks the end of a panel move operation
 */
function Static_TemplatedPanel_EndMove( e, cancelAction )
{
  var sourceElement = jshGetSourceElement( e );

  //debug( 'ending move cancelAction:' + cancelAction, sourceElement, ' ; ', sourceElement.mediaPanel, ' ; ', sourceElement.mediaPanel.mControl.getCurrentAction() );
  if( sourceElement.mediaPanel )
  {
    var mediaPanel = sourceElement.mediaPanel;

    if( mediaPanel.mActionInProgress == true )
    {
      // reset variables
      mediaPanel.mActionInProgress = null;

      // lastly reset the action
      if( mediaPanel.mControl )
      {
        mediaPanel.mControl.setAction( null );
      }
      mediaPanel.updateCursor( false );

      // reset events
      mediaPanel.mGlassPlate.hide();
      mediaPanel.mGlassPlate.onmouseup = null;
      mediaPanel.mGlassPlate.onmousemove = null;
      mediaPanel.mGlassPlate.onmousedown = null;
      mediaPanel.mGlassPlate.onmouseout = null;
      mediaPanel.mContainer.onmouseup = null;
      mediaPanel.mContainer.onmousemove = null;
      mediaPanel.mContainer.onmousedown = null;
      mediaPanel.mContainer.mediaPanel = null;
      mediaPanel.mContainer.onmouseout = null;

      // reset poistion to original
      if( cancelAction == true )
      {
        if( mediaPanel.equalsCurrentAction( mediaPanel.mControl.ACTION_MOVE ) )
        {
          mediaPanel.moveTo( mediaPanel.mOriginalMoveStartingX, mediaPanel.mOriginalMoveStartingY );
        }
        else if ( mediaPanel.equalsCurrentAction( mediaPanel.mControl.ACTION_RESIZE_TOP_LEFT ) ||
            mediaPanel.equalsCurrentAction( mediaPanel.mControl.ACTION_RESIZE_TOP_RIGHT ) ||
            mediaPanel.equalsCurrentAction( mediaPanel.mControl.ACTION_RESIZE_BOTTOM_RIGHT ) ||
            mediaPanel.equalsCurrentAction( mediaPanel.mControl.ACTION_RESIZE_BOTTOM_LEFT ) )
        {
          //mediaPanel.resize( mediaPanel.mResizeStartingWidth, mediaPanel.mResizeStartingHeight );
        }
      }
      else
      {
        // action was completed fine, so not canceled
        if( mediaPanel.equalsCurrentAction( mediaPanel.mControl.ACTION_RESIZE_TOP_LEFT ) ||
            mediaPanel.equalsCurrentAction( mediaPanel.mControl.ACTION_RESIZE_TOP_RIGHT ) ||
            mediaPanel.equalsCurrentAction( mediaPanel.mControl.ACTION_RESIZE_BOTTOM_RIGHT ) ||
            mediaPanel.equalsCurrentAction( mediaPanel.mControl.ACTION_RESIZE_BOTTOM_LEFT ) )
        {
          // notify after resize
          if( mediaPanel.mPostResizeFunction )
          {
            // notify only if there was a change in size
            var dimensions = mediaPanel.getDimensions();
            if( ! ( ( mediaPanel.mResizeStartingWidth == dimensions[0] ) &&
                    ( mediaPanel.mResizeStartingHeight == dimensions[1] ) ) )
            {
              mediaPanel.mPostResizeFunction( mediaPanel, dimensions );
            }
          }
        }
      }

      mediaPanel.mBody.show();

      // reset the last of the variables
      mediaPanel.mMoveStartingX = null;
      mediaPanel.mMoveStartingY = null;
      mediaPanel.mResizeStartingWidth = null;
      mediaPanel.mResizeStartingHeight = null;
      mediaPanel.mOriginalMoveStartingX = null;
      mediaPanel.mOriginalMoveStartingY = null;
      mediaPanel.mOriginalPanStartingX = null;
      mediaPanel.mOriginalPanStartingY = null;
      mediaPanel.mOriginalStartingX = null;
      mediaPanel.mOriginalStartingY = null;
      mediaPanel.mResizeStartingWidth = null;
      mediaPanel.mResizeStartingHeight = null;
      mediaPanel.mMoveStartingX = null;
      mediaPanel.mMoveStartingY = null;
    }
  }
}

/**
 * Marks the state of a panel move operation
 */
function Static_TemplatedPanel_StartMove( e )
{
  e = jshGetEvent( e );
  var sourceElement = jshGetSourceElement( e );

  debug( 'Static_TemplatedPanel_StartMove:', sourceElement, ' ; ', sourceElement.mediaPanel, ' ; ', sourceElement.mediaPanel.mControl.getCurrentAction() );

  if( sourceElement.mediaPanel )
  {
    var mediaPanel = sourceElement.mediaPanel;

    if( mediaPanel.mControl )
    {
      if( mediaPanel.equalsCurrentAction( mediaPanel.mControl.ACTION_MOVE ) ||
          mediaPanel.equalsCurrentAction( mediaPanel.mControl.ACTION_RESIZE_TOP_LEFT ) ||
          mediaPanel.equalsCurrentAction( mediaPanel.mControl.ACTION_RESIZE_TOP_RIGHT ) ||
          mediaPanel.equalsCurrentAction( mediaPanel.mControl.ACTION_RESIZE_BOTTOM_RIGHT ) ||
          mediaPanel.equalsCurrentAction( mediaPanel.mControl.ACTION_RESIZE_BOTTOM_LEFT ) )
      {
        if( !( mediaPanel.mActionInProgress == true ) )
        {
          mediaPanel.bringToFront();
          mediaPanel.updateCursor( true );

          mediaPanel.mActionInProgress = true;

          // FireFox 3 has issues with iframes stealing mouse events
          // for now lets just hide the iframe while doing any DnD stuff
          if( jshIsFF3() )
          {
            mediaPanel.mBody.hide();
          }

          // back up some values in case we cancel or need a reference
          var offset = Position.page( mediaPanel.mPanel );
          mediaPanel.mOriginalMoveStartingX = offset[0];
          mediaPanel.mOriginalMoveStartingY = offset[1];

          var dimensions = mediaPanel.getDimensions();
          mediaPanel.mResizeStartingWidth = dimensions[0];
          mediaPanel.mResizeStartingHeight = dimensions[1];

          // this guy gets updated
          mediaPanel.mMoveStartingX = Event.pointerX( e );
          mediaPanel.mMoveStartingY = Event.pointerY( e );

          // this guy stays the same
          mediaPanel.mOriginalStartingX = Event.pointerX( e );
          mediaPanel.mOriginalStartingY = Event.pointerY( e );

          // set events on other elements to get a "smooth" motion
          mediaPanel.mGlassPlate.show();
          mediaPanel.mGlassPlate.mediaPanel = mediaPanel;
          mediaPanel.mGlassPlate.onmousemove = Static_TemplatedPanel_Move;
          mediaPanel.mGlassPlate.onmouseup = Static_TemplatedPanel_EndMove;
          mediaPanel.mGlassPlate.onmouseout = Static_TemplatedPanel_EndMove;

          mediaPanel.mContainer.mediaPanel = mediaPanel;
          mediaPanel.mContainer.onmousemove = Static_TemplatedPanel_Move;
          mediaPanel.mContainer.onmouseup = Static_TemplatedPanel_EndMove;
        }
      }
    }
  }
}

/**
 * The actual work of a Move operation which can be either a
 * Panel move or pan based on what the control is set to
 */
function Static_TemplatedPanel_Move( e )
{
  e = jshGetEvent( e );
  var sourceElement = jshGetSourceElement( e );

  //debug( 'Static_TemplatedPanel_Move:', sourceElement, ' ; ', sourceElement.mediaPanel, ' ; ', sourceElement.mediaPanel.mControl.getCurrentAction() );

  if( sourceElement.mediaPanel )
  {
    // move the panel if we are in move mode
    var mediaPanel = sourceElement.mediaPanel;
    if( mediaPanel.mActionInProgress == true )
    {
      // current mouse position
      var endingX = Event.pointerX( e );
      var endingY = Event.pointerY( e );

      // cal how many px we are moving
      var difference = $( [ ( endingX - mediaPanel.mMoveStartingX ), ( endingY - mediaPanel.mMoveStartingY ) ] );

      // update values for next time
      mediaPanel.mMoveStartingX = endingX;
      mediaPanel.mMoveStartingY = endingY;

      mediaPanel.updateCursor( true );

      // do the action
      if( mediaPanel.equalsCurrentAction( mediaPanel.mControl.ACTION_MOVE ) )
      {
        // calc actual new move position
        var offset = Position.cumulativeOffset( mediaPanel.mPanel );
        var x = offset[0] + difference[0];
        var y = offset[1] + difference[1];

        mediaPanel.moveTo( x, y );
        if( mediaPanel.mControl )
        {
          mediaPanel.mControl.positionControls();
        }
      }
      else if( mediaPanel.equalsCurrentAction( mediaPanel.mControl.ACTION_RESIZE_TOP_LEFT ) )
      {
        var position = mediaPanel.getPosition();
        var dimensions = mediaPanel.getDimensions();

        mediaPanel.resize( ( dimensions[0] - difference[0] ), ( dimensions[1] - difference[1] ) );
        mediaPanel.moveTo( ( position[0] + difference[0] ), ( position[1] + difference[1] ) );
        if( mediaPanel.mControl )
        {
          mediaPanel.mControl.positionControls();
        }
      }
      else if( mediaPanel.equalsCurrentAction( mediaPanel.mControl.ACTION_RESIZE_TOP_RIGHT ) )
      {
        var position = mediaPanel.getPosition();
        var dimensions = mediaPanel.getDimensions();

        mediaPanel.resize( ( dimensions[0] + difference[0] ), ( dimensions[1] - difference[1] ) );
        mediaPanel.moveTo( position[0], ( position[1] + difference[1] ) );
        if( mediaPanel.mControl )
        {
          mediaPanel.mControl.positionControls();
        }
      }
      else if( mediaPanel.equalsCurrentAction( mediaPanel.mControl.ACTION_RESIZE_BOTTOM_RIGHT ) )
      {
        var dimensions = mediaPanel.getDimensions();

        mediaPanel.resize( ( dimensions[0] + difference[0] ), ( dimensions[1] + difference[1] ) );
        if( mediaPanel.mControl )
        {
          mediaPanel.mControl.positionControls();
        }
      }
      else if( mediaPanel.equalsCurrentAction( mediaPanel.mControl.ACTION_RESIZE_BOTTOM_LEFT ) )
      {
        var position = mediaPanel.getPosition();
        var dimensions = mediaPanel.getDimensions();

        mediaPanel.resize( ( dimensions[0] - difference[0] ), ( dimensions[1] + difference[1] ) );
        mediaPanel.moveTo( ( position[0] + difference[0] ), position[1] );
        if( mediaPanel.mControl )
        {
          mediaPanel.mControl.positionControls();
        }
      }
    }
  }
}

/**
 * Static event function when a mouse in occurs
 */
function Static_TemplatedPanel_MouseIn( e )
{
  e = jshGetEvent( e );
  var sourceElement = jshGetSourceElement( e );

  // check the parent to see if he has an mediaPanel.
  if( ! sourceElement.mediaPanel )
  {
    sourceElement = sourceElement.up();
  }

  if( sourceElement.mediaPanel )
  {
    var mediaPanel = sourceElement.mediaPanel;

    // show controls
    mediaPanel.showControls();
  }
}

/**
 * Static event function when a mouse out occurs
 */
function Static_TemplatedPanel_MouseOut( e )
{
  var e = jshGetEvent( e );
  var sourceElement = jshGetSourceElement( e );

  if( sourceElement.mediaPanel )
  {
    var mediaPanel = sourceElement.mediaPanel;

    // skip it if we are in the middle of a move, pan, or resize
    if( ( mediaPanel.mActionInProgress != true ) )
    {
      // hide controls
      mediaPanel.hideControls();
    }
  }
}

function Static_TemplatedPanel_LoadTemplate( templatedPanel, attempts )
{
  if( templatedPanel )
  {
    if( templatedPanel.mBody && templatedPanel.mBody.contentWindow && templatedPanel.mBody.contentWindow.initalizeTemplate )
    {
      // call the initialize template method
      templatedPanel.mBody.contentWindow.initalizeTemplate(
          templatedPanel.mContainer,
          templatedPanel.mediaInfo,
          templatedPanel.mAnimate,
          templatedPanel );
    }
    else if( templatedPanel && ( attempts > 0 ) )
    {
      // must not been ready
      var tp = templatedPanel
      var at = attempts--;
      var func = function(){ Static_TemplatedPanel_LoadTemplate( tp, at ); };
      setTimeout( func, 500 );
    }
  }
}























