/**
 ******************************************************************************
 * Copyright 2001-2008. EMC Corporation.  All Rights Reserved.
 ******************************************************************************
 *
 * Project        Lister
 * File           modal.js
 * Description    the javascript responsible for modal inline dialogs - requires locate.js
 * Created on     19th November 2001
 * Tab width      3
 *
 ******************************************************************************
 *
 * PVCS Maintained Data
 *
 * Revision       $$
 * Modified on    $$
 *
 * Log at EOF
 *
 ******************************************************************************
 */

//----------------------------------------------------------------------------
// Initialisation

// initialise modal window and frame path
if (typeof(getTopLevelWnd().modalWnd) == "undefined")
{
   getTopLevelWnd().modalWnd = null;
}

// -- information on modal popup
if (typeof(wdk) == "undefined")
{
   wdk = {};
}
if (typeof(wdk.modalPopupConfig) == "undefined")
{
   wdk.modalPopupConfig = {};
}

if (typeof wdk.modalPopupConfig.WindowSize == "undefined")
{ // support portal

   g_frameMap = new FrameMap();

    /**
    * window size configuration
    */
   wdk.modalPopupConfig.WindowSize = new function()
   {
      this.widthByName = {};
      this.heightByName = {};

      /**
       * called by the tag handler to register a configured size
       * @param strSizeName the name of the size
       * @param nWidth      the width
       * @param nHeight     the height
       */
      this.register = function(strSizeName, nWidth, nHeight)
      {
         this.widthByName[strSizeName] = nWidth;
         this.heightByName[strSizeName] = nHeight;
      }

      /**
       * get the width of a named size
       * @param strSizeName   the size
       * @reurn the width.
       */
      this.getWidth = function(strSizeName)
      {
         var nWidth = 550;
         if (strSizeName != null && typeof(strSizeName) != "undefined")
         {
            var nVal = this.widthByName[strSizeName];
            if (nVal)
            {
               nWidth = nVal;
            }
         }

         return nWidth;
      }

      /**
       * get the height of a named size
       * @param strSizeName   the size
       * @reurn the height.
       */
      this.getHeight = function(strSizeName)
      {
         var nHeight = 450;
         if (strSizeName != null && typeof(strSizeName) != "undefined")
         {
            var nVal = this.heightByName[strSizeName];
            if (nVal)
            {
               nHeight = nVal;
            }
         }
         return nHeight;
      }
   }
} // end if (typeof wdk.modalPopupConfig.WindowSize == "undefined")


//----------------------------------------------------------------------------
// Public interface

/**
 * Enter modal execution
 */

function beginModal()
{
   var topLevelWnd = getTopLevelWnd();

   // We're Initiating modality if this is the first window to call beginModal [ since the last endModal ]
   var bInitiatingModality = (topLevelWnd.modalWnd == null);

   // We're Maintaining modality when another window has already called beginModal but this window has been removed.
   // This would happen for nested components (A), which nest to other components (B) inside their onInit methods.
   // Window B would be registered as the modal window, and when returning to A, would get removed.
   var bMaintainingModality = ((topLevelWnd.modalWnd != null) && doesWindowExist(topLevelWnd.modalWnd) == false);

   if (bInitiatingModality || bMaintainingModality)
   {
      // Register currently modal window
      topLevelWnd.modalWnd = window;

      // Only resize if we're Initiating modality. If we try to resize while maintaining
      // modality we lose the backed up (non modal) frameset sizing values.
      if (bInitiatingModality)
      {
         if (topLevelWnd.document.body.tagName == 'FRAMESET')
         {
            if (g_clientInfo.isBrowser(ClientInfo.SAFARI))
            {
               g_frameMap.fill(topLevelWnd);
            }

            resizeFrameset(topLevelWnd.document.body);

            if (g_clientInfo.isBrowser(ClientInfo.SAFARI))
            {
               g_frameMap.clear();
            }
         }
      }
      // we don't want to invoke this as focus is already on the modal dialog - 
      // forcing this unnecesarily steals focus 
      if (!isModalPopup())
      {
         // ensure focus is set on modal window
         window.focus();
      }
   }
}

/**
 * End modal execution
 */
function endModal(bForced)
{
   var topLevelWnd = getTopLevelWnd();
   var bAllowEndModal = (doesWindowExist(topLevelWnd.modalWnd) == false || bForced);

   if (topLevelWnd.modalWnd != null && bAllowEndModal)
   {
      // clear modality (but only if the window is the modal window)
      topLevelWnd.modalWnd = null;

      // traverse frameset structures restoring cols and rows appropriately
      if (g_clientInfo.isBrowser(ClientInfo.SAFARI))
      {
         g_frameMap.fill(topLevelWnd);
      }

      restoreFrameset(topLevelWnd.document.body);

      if (g_clientInfo.isBrowser(ClientInfo.SAFARI))
      {
         g_frameMap.clear();
      }
   }
}

//----------------------------------------------------------------------------
// Implementation

/**
 * FrameMap is used to store a associative array (HashMap) used to lookup windows,
 * corresponding to a frame DOM elements.
 *
 * It is intended to be used as an alternative to frame.contentWindow.
 *
 * FrameMap.fill(wnd) is used to fill the map, by recurrsively traversing wnd and all child frames. A unique lookup
 * attribute value is assigned to the document of each frame window and this lookup is used as the map key.
 *
 * FrameMap.getWindow(frame) can then be used to lookup the window with the lookup as key.
 *
 */
function FrameMap()
{
   /* Private Member variables */
   this.prefix = "DCTM_FRAME";
   this.map = new Array();

   /* Public Methods */
   this.fill = function(win)
   {
      // Checking for isAccesible was thought to be unneccessary here since we fill using getTopLevelWnd
      if (win.frames.length > 0)
      {
         for (var j=0; j < win.frames.length; j++)
         {
            var frame = win.frames[j];
            if (isAccessibleWindow(frame))
            {
               this.addFrame(frame);

               if (frame.frames.length > 0)
               {
                  this.fill(frame);
               }
            }
         }
      }
   };

   this.getWindow = function(frame)
   {
      var lookup = null;
      try
      {
         lookup = frame.document.lookup;
      }
      catch(e)
      {
         // Used to trap Cross-browser scripting violations when accessing frames outside our domain.
      }
      return (lookup == null) ? null : this.map[lookup];
   };

   this.clear = function()
   {
      this.map = new Array();
   };

   /* Private Methods */
   this.addFrame = function(frame)
   {
      var uniqueName = this.generateUniqueLookup(frame.name);
      frame.document.lookup = uniqueName;

      if (Trace_MODAL) modal_trace("Adding - " + frame.document.lookup + "," + frame.name);

      this.map[uniqueName] = frame;
   };

   this.generateUniqueLookup = function(frameName)
   {
      var idx = 0;
      var noName = false;
      var uniqueName = frameName;

      // The check for "<!--" is a Safari 1.2 issue
      // Safari needs a unique name for all frames.
      // If you don't have a frame name, or you have duplicate names,
      // it generates one, using an HTML comment syntax with the frame path

      if (!uniqueName || uniqueName.indexOf("<!--") != -1)
      {
         noName = true;
         uniqueName = this.prefix + "_" + idx;
      }

      while (typeof this.map[uniqueName] != 'undefined')
      {
         if (noName)
         {
            uniqueName = this.prefix + "_" + (idx++)
         }
         else
         {
            uniqueName = frameName + "_" + (idx++);
         }
      }

      return uniqueName;
   };
}

/**
 * resizes the passed frameset, and any descendants so that the modal frame is maximized, and only
 * frames marked as 'ignoreModal' are preserved
 *
 * @param frameset  Frameset object
 * @return size of frameset (null, 0, or 100%)
 */

function resizeFrameset(frameset)
{
   var framesetSize = null;  // return value: frameset size (null, 0, or 100%)

   // get the frameset's rows/cols
   var rowsCols;

   if (frameset.rows != null && frameset.rows != "")
   {
      rowsCols = frameset.rows;
   }
   else
   {
      rowsCols = frameset.cols;
   }

   var rowsColsArray = rowsCols.split(',');

   var newRowsCols = "";
   var bCollapseAll = true;

   // for the child frames/framesets
   var childFrames = getChildFrames(frameset);

   for (var i = 0; i < childFrames.length; i++)
   {
      var size = rowsColsArray[i];
      var childFrame = childFrames[i];

      if (childFrame.tagName == 'FRAME')
      {
         if (Trace_MODAL) modal_trace("Resizing Frame : " + childFrame.name);

         // Hide frame border after backing up original values
         setCustomAttribute(childFrame, 'resized', true);
         setCustomAttribute(childFrame, 'prev_noResize', getCustomAttribute(childFrame, 'noResize'));
         setCustomAttribute(childFrame, 'prev_marginHeight', getCustomAttribute(childFrame, 'marginHeight'));
         setCustomAttribute(childFrame, 'prev_marginWidth', getCustomAttribute(childFrame, 'marginWidth'));
         setCustomAttribute(childFrame, 'prev_scrolling', getCustomAttribute(childFrame, 'scrolling'));
         setCustomAttribute(childFrame, 'noResize', false);
         setCustomAttribute(childFrame, 'marginHeight', 0);
         setCustomAttribute(childFrame, 'marginWidth', 0);

         // There is a bug on Firefox 1.5+ (340465) where setting this property at this point causes any
         // applets on the page to be initialized several times. Not setting this here doesn't
         // seem to have any adverse side effects.
         if (!g_clientInfo.isBrowser(ClientInfo.FIREFOX))
         {
            childFrame.scrolling    = 'no';
         }
         
         var childWnd = getWindowReference(childFrame);

         // Test for cross-frame scripting before trying to access frame window properties
         if (childWnd && isAccessibleWindow(childWnd) == true)
         {

            if (childWnd.document.body && childWnd.document.body.tagName == 'FRAMESET')
            {
               // frame document contains a frameset.
               childFrame = childWnd.document.body;
            }
            else
            {
               // frame document is a regular page.
               if (childWnd == getTopLevelWnd().modalWnd || resizeIFrames(childWnd, getTopLevelWnd().modalWnd))
               {
                  // maximize size of modal window
                  size = "100%";
                  framesetSize = "100%";
               }
               else if (typeof(childWnd.ignoreModal) == "undefined")
               {
                  // minimize size on non modal windows
                  size = "0";

                  // Even though we have childWnd we use childFrame for IE support.
                  // See blockKeyboardAccess for details.
                  blockKeyboardAccess(childFrame);
               }
               else
               {
                  // retain existing size
                  bCollapseAll = false;
               }
            }
         }
      }

      if (childFrame.tagName == 'FRAMESET') // child frameset
      {
         // recurse for each nested frameset
         var newsize = resizeFrameset(childFrame);

         // set frame size
         if (newsize != null)
         {
            size = newsize;
            if (size == "100%")
            {
               framesetSize = "100%";
            }
         }
      }

      // build new row/cols
      if (newRowsCols != "")
      {
         newRowsCols += ',';
      }
      newRowsCols += size;
   }

   // resize frameset
   if (frameset.rows != null && frameset.rows != "")
   {
      setCustomAttribute(frameset, 'prev_rows', getCustomAttribute(frameset, 'rows'));
      setCustomAttribute(frameset, 'rows', newRowsCols);
   }
   else
   {
      setCustomAttribute(frameset, 'prev_cols', getCustomAttribute(frameset, 'cols'));
      setCustomAttribute(frameset, 'cols', newRowsCols);
   }

   // hide border after backing up original values
   setCustomAttribute(frameset, 'resized', true);
   setCustomAttribute(frameset, 'prev_border', getCustomAttribute(frameset, 'border'));
   setCustomAttribute(frameset, 'prev_frameBorder', getCustomAttribute(frameset, 'frameBorder'));
   setCustomAttribute(frameset, 'prev_frameSpacing', getCustomAttribute(frameset, 'frameSpacing'));
   setCustomAttribute(frameset, 'border', 0);
   setCustomAttribute(frameset, 'frameBorder', 0);
   setCustomAttribute(frameset, 'frameSpacing', 0);

   // return frameset size
   if (bCollapseAll && framesetSize == null)
   {
      framesetSize = "0";
   }

   return framesetSize;
}

/**
 * restores the cols/rows of the passed frameset, and any descendants
 *
 * @param frameset  Frameset to restore
 */

function restoreFrameset(frameset)
{
   // for the child frames/framesets
   var childFrames = getChildFrames(frameset);
   for (var i = 0; i < childFrames.length; i++)
   {
      var childFrame = childFrames[i];

      if (childFrame.tagName == 'FRAME')     // frame
      {
         // Restore Frame, if it has been resized by a resizeFrameset call
         if (getCustomAttribute(childFrame,'resized'))
         {
            if (Trace_MODAL) modal_trace("Restoring Frame :" + childFrame.name);
            setCustomAttribute(childFrame, 'noResize', getCustomAttribute(childFrame, 'prev_noResize'));
            setCustomAttribute(childFrame, 'marginHeight', getCustomAttribute(childFrame, 'prev_marginHeight'));
            setCustomAttribute(childFrame, 'marginWidth', getCustomAttribute(childFrame, 'prev_marginWidth'));
            setCustomAttribute(childFrame, 'scrolling', getCustomAttribute(childFrame, 'prev_scrolling'));
            setCustomAttribute(childFrame, 'resized', false);
         }

         var childWnd = getWindowReference(childFrame);

         // Test for cross-frame scripting before trying to access frame window properties
         if (childWnd && isAccessibleWindow(childWnd) == true)
         {
            // Restore Keyboard Access
            restoreKeyboardAccess(childFrame);

            if (childWnd.frames.length > 0)
            {
               if (childWnd.document.body.tagName == "BODY")
               {
                  //restore iframes
                  restoreIFrames(childWnd);
               }
               else
               {
                  // Frames document contains a frameset
                  childFrame = childWnd.document.body;
               }
            }
         }
      }

      if (childFrame && childFrame.tagName == 'FRAMESET')
      {
         // Recurse for each nested frameset
         restoreFrameset(childFrame);
      }
   }

   // Restore border, if it has been resized by a resizedFrameset call
   if (getCustomAttribute(frameset, 'resized'))
   {
      setCustomAttribute(frameset, 'border', getCustomAttribute(frameset, 'prev_border'));
      setCustomAttribute(frameset, 'frameBorder', getCustomAttribute(frameset, 'prev_frameBorder'));
      setCustomAttribute(frameset, 'frameSpacing', getCustomAttribute(frameset, 'prev_frameSpacing'));
      // restore cols/rows
      var framesetRows = getCustomAttribute(frameset, 'rows');
      if (framesetRows != null && framesetRows != "")
      {
         setCustomAttribute(frameset, 'rows', getCustomAttribute(frameset,'prev_rows'));
      }
      else
      {
         setCustomAttribute(frameset, 'cols', getCustomAttribute(frameset,'prev_cols'));
      }

      setCustomAttribute(frameset, 'resized', false);
   }
}

/**
 * returns child frames/framesets of the passed frameset
 *
 * @param frameset  Frameset object
 * @return array of child frames/framesets
 */
function getChildFrames(frameset)
{
   var childFrames = [];

   var iChildFrames = 0;
   for (var iChild = 0; iChild < frameset.childNodes.length; iChild++)
   {
      var child = frameset.childNodes[iChild];
      if (child.tagName == 'FRAME' || child.tagName == 'FRAMESET')
      {
         childFrames[iChildFrames++] = child;
      }
   }

   return childFrames;
}

/**
 * Obtains the Window Reference of the Frame DOM element passed in.
 * For browsers which don't support contentWindow, we need to rely on the g_frameMap lookup.
 *
 * @param frame  Frame for which a window reference is required.
 * @return window Window reference for frame.
 */
function getWindowReference(frame)
{
   var win = (frame.contentWindow) ? frame.contentWindow : g_frameMap.getWindow(frame);
   return win;
}

/**
 * PRIVATE : Helper method to set custom attributes on Frame/Frameset elements, to account for Safari
 * which doesn't let you set custom attributes on frame and frameset objects.
 *
 * @param frame     Frame or Frameset on which custom attribute needs to be set
 *                  [ If using Safari, passing in any other elements may cause execeptions if setAttribute not supported ]
 * @param attrName  Custom Attribute Name.
 * @param attrValue Custom Attribute Value.
 */
function setCustomAttribute(frame, attrName, attrValue)
{
   if (frame && attrName)
   {
      if (g_clientInfo.isBrowser(ClientInfo.SAFARI))
      {
         frame.setAttribute(attrName, attrValue);
      }
      else
      {
         frame[attrName] = attrValue;
      }
   }
}
/**
 * PRIVATE : Helper method to get custom attributes on Frame/Frameset elements. Safari 3 does not allow custom
 * attributes to be retreived using <element>.<attribute> shorthand notation, if the element has used
 * setAttribute(attributeName) to set the attribute. Safari 3 needs elements: either to be set and retreived using
 * setAttribute() and getAttribute() methods or use <element>.<attribute> shorthand notation to set and retreive.
 * The combination of set/getAttribute and <element>.<attribute> shorthand notation does not work.
 * @param frame     Frame or Frameset on which custom attribute needs to be set
 * @param attrName  Custom Attribute Name.
 * @param attrValue Custom Attribute Value.
 */
function getCustomAttribute(frame, attributeName)
{
   var attributeValue = null;
   if (frame && attributeName)
   {
      if (g_clientInfo.isBrowser(ClientInfo.SAFARI))
      {
         attributeValue = frame.getAttribute(attributeName);
      }
      else
      {
         attributeValue = frame[attributeName];
      }
   }
   return attributeValue;
}

/**
 * PRIVATE Blocks access to the (hidden) frame via the Tab Key
 *
 * BROWSER NOTE : IE doesn't handle onFocus when set on the frame's WINDOW object dynamically.
 * It does support onFocus when set on the FRAME object, but it doesn't fire the event if the modal page is reloaded.
 * Hence for IE, we use the frame object and use tabIndex to block access.
 *
 * The frame must be accessible [ viz. no cross-scripting across domains ]
 *
 * @param frame frame for which keyboard access is to be blocked.
 */
function blockKeyboardAccess(frame)
{
   if (g_clientInfo.isBrowser(ClientInfo.MSIE))
   {
      frame.prev_tabIndex = frame.tabIndex;
      frame.tabIndex = -1;
   }
   else
   {
      var frameWnd = getWindowReference(frame);
      if (frameWnd)
      {
         // No need for Safari switch to set attributes because this is on a WINDOW object, which Safari allows.
         frameWnd.prev_onfocus = frameWnd.onfocus;
         frameWnd.onfocus = function() {
            if (getTopLevelWnd().modalWnd)
            {
               getTopLevelWnd().modalWnd.focus();
            }
         };
      }
   }
}

/**
 * PRIVATE Restores keyboard access to the (hidden) frame blocked by blockKeyboardAccess call.
 *
 * See blockKeyboardAccess(frame) for details.
 * The frame must be accessible [ viz. no cross-scripting across domains ]
 *
 * @param frame frame for which keyboard access is to be restored.
 */
function restoreKeyboardAccess(frame)
{
   if (g_clientInfo.isBrowser(ClientInfo.MSIE))
   {
      frame.tabIndex = (frame.prev_tabIndex) ? frame.prev_tabIndex : null;
   }
   else
   {
      var frameWnd = getWindowReference(frame);
      if (frameWnd)
      {
         frameWnd.onfocus = (frameWnd.prev_onfocus) ? frameWnd.prev_onfocus : null;
      }
   }
}

/**
 * return whether currently in modal mode
 */
function isModal()
{
   var topLevelWnd = getTopLevelWnd();
   return (topLevelWnd.modalWnd != null);
}

/**
 * returns whether the passed window exists (in the current frameset)
 *
 * @param wnd  Window to test for
 *
 * @return Whether window exists
 */
function doesWindowExist(wnd)
{
   return _doesWindowExist(getTopLevelWnd(), wnd);
}
function _doesWindowExist(parentWnd, wnd)
{
   for (var i = 0; i < parentWnd.frames.length; i++)
   {
      var childWnd = parentWnd.frames[i];
      if (childWnd == wnd || _doesWindowExist(childWnd, wnd) == true)
      {
         return true;
      }
   }

   return false;
}

/**
 * Trace modality.
 * @param msg trace message
 */
function modal_trace(msg)
{
   Trace_println("modal.js: " + msg);
}

/* Functions for popup modal dialogs */

if (typeof(getTopLevelWnd().modalPopupWindow) == "undefined")
{
   getTopLevelWnd().modalPopupWindow = null;
}

function registerModalPopupWindow(modalPopupWindow)
{
   getTopLevelWnd().modalPopupWindow = modalPopupWindow;
}

function unregisterModalPopupWindow()
{
   getTopLevelWnd().modalPopupWindow = null;
}

function getRegisteredModalPopupWindow()
{
   return getTopLevelWnd().modalPopupWindow;
}

function beginModalPopupMode(strFrameName, strFormId, strPopupWindowSize, strRefreshParentWindow)
{
   var targetWindow = null;
   var formElement = null;

   if (strFrameName != null && strFrameName.length > 0)
   {
      targetWindow = eval(getAbsoluteFramePath(strFrameName));
   }

   if (targetWindow == null)
   {
      targetWindow = window;
   }

   if (strFormId != null && strFormId.length > 0)
   {
      formElement = targetWindow.document.forms[strFormId];
   }
   else
   {
      formElement = targetWindow.document.forms[0];
   }
   
   if (formElement  != null)
   {
      formElement.__dmfUseModalPopup.value = "true";
      formElement.__dmfModalPopupWindowSize.value = strPopupWindowSize;
      formElement.__dmfRefreshParentWindow.value = strRefreshParentWindow;
   }
   else
   {
      throw "Cannot locate formElement given these frame and form names : " + strFrameName + ", " + strFormId + ".";   
   }
}

function endModalPopupMode(strFrameName, strFormId)
{
   var targetWindow = null;
   var formElement = null;

   unregisterModalPopupWindow();

   if (strFrameName != null && strFrameName.length > 0)
   {
      targetWindow = eval(getAbsoluteFramePath(strFrameName));
   }

   if (targetWindow == null)
   {
      targetWindow = window;
   }
   
   if (strFormId != null && strFormId.length > 0)
   {
      formElement = targetWindow.document.forms[strFormId];
   }
   else
   {
      formElement = targetWindow.document.forms[0];
   }
   
   if (formElement  != null)
   {
      formElement.__dmfUseModalPopup.value = "false";
      formElement.__dmfModalPopupWindowSize.value = "";
      formElement.__dmfRefreshParentWindow.value = "";
   }
   else
   {
      throw "Cannot locate formElement given these frame and form names : " + strFrameName + ", " + strFormId + "."; 
   }
}

function getPopupWindowName(win, nestDepth)
{
   var postFix = "_popup_window_";
   var windowName = win.name;
   var popupName = windowName + postFix;

   if (g_clientInfo.isBrowser(ClientInfo.MSIE))
   {
      var index = parseInt(nestDepth) + 1;

      // We have stack windows in IE. Need to embed the window depth into the name.
      // It will be used by return.jsp to calculate when to close the window.
      if (windowName.indexOf(postFix) > -1)
      {
         // Subsequent popup window
         popupName = windowName.substring(0, windowName.lastIndexOf("_") + 1) + index;
      }
      else
      {
         // First popup window
         popupName = windowName + postFix + index;
      }
   }

   return popupName;
}

function openModalPopupWindow(parentWin, strParentFormId, strPopupWindowSize, strPopupWindowName, strUrl)
{
   if (g_clientInfo.isBrowser(ClientInfo.MSIE))
   {
      var args = new Object();
      args.m_parentWindow = parentWin;
      args.m_parentFormId = strParentFormId;
      args.m_popupWindowName = strPopupWindowName;
      args.m_isWDKModalPopup = true;
      var topLevelWindow = parentWin;

      if((!!(topLevelWindow.dialogArguments)) && (!!(topLevelWindow.dialogArguments.m_isWDKModalPopup))) {
            topLevelWindow = dialogArguments.topLevelWindow;
      }

      args.topLevelWindow = topLevelWindow;
      
      // Determine the size of the popup window
      var width = getModalPopupWindowWidth(strPopupWindowSize);
      var height = getModalPopupWindowHeight(strPopupWindowSize);

      // Position the popup window on the center of the parent window
      var left = getWindowLeft(parentWin) + getWindowWidth(parentWin)/2  - width/2;
      var top = getWindowTop(parentWin) + getWindowHeight(parentWin)/2 - height/2;

      var strFeatures = "dialogWidth:" + width + "px;" + "dialogHeight:" + height + "px;" +
                        "dialogLeft:" + left + "px;" + "dialogTop:" + top + "px;" +
                        "status:no;resizable:yes;scroll:no;";

      var strClientEvents = showModalDialog(strUrl, args, strFeatures);

      // Eval client event script if the dialog returns one
      if (typeof (strClientEvents) != "undefined")
      {
         var clientEvents = eval(strClientEvents);
         processClientEvents(clientEvents);
      }
   }
}

function getModalPopupWindowWidth(strSize)
{
   return wdk.modalPopupConfig.WindowSize.getWidth(strSize);
}

function getModalPopupWindowHeight(strSize)
{
   return wdk.modalPopupConfig.WindowSize.getHeight(strSize);
}

function resizeModalPopupWindowWithDimension(win, width, height)
{
   if (win.getWindowOpener() != null)
   {
      // resize the window
      if (g_clientInfo.isBrowser(ClientInfo.MSIE))
      {
         win.dialogWidth = width + "px";
         win.dialogHeight = height + "px";
      }
   }
}

function resizeModalPopupWindow(win, size)
{
   resizeModalPopupWindowWithDimension(win, getModalPopupWindowWidth(size), getModalPopupWindowHeight(size));
}

function centerModalPopupWindow(win)
{
   if (win.getWindowOpener() != null)
   {
      // resize the popup window
      if (g_clientInfo.isBrowser(ClientInfo.MSIE))
      {
         // Position the popup window on the center of the parent window
         var parentWin = win.getWindowOpener();         
         win.dialogLeft = getWindowLeft(parentWin) + getWindowWidth(parentWin)/2 - getWindowWidth(win)/2;
         win.dialogTop = getWindowTop(parentWin) + getWindowHeight(parentWin)/2 - getWindowHeight(win)/2;
      }
   }
}

function getWindowWidth(win)
{
   var width = screen.availWidth;
   if (win)
   {
      if (win.dialogWidth)
      {
         // showModalDialog dialogWidth format is "[num]px". Need to strip the "px" and return [num].
         width = parseInt(win.dialogWidth.substring(0, win.dialogWidth.length - 2))
      }
   }
   return width;
}

function getWindowHeight(win)
{
   var height = screen.availHeight;
   if (win)
   {
      if (win.dialogHeight)
      {
         // showModalDialog dialogHeight format is "[num]px". Need to strip the "px" and return [num].
         height = parseInt(win.dialogHeight.substring(0, win.dialogHeight.length - 2));
      }
   }
   return height;
}

function getWindowLeft(win)
{
   var left = 0;
   if (win)
   {
      if (win.dialogLeft)
      {
         // showModalDialog dialogLeft format is "[num]px". Need to strip the "px" and return [num].
         left = parseInt(win.dialogLeft.substring(0, win.dialogLeft.length - 2));
      }
      else if (win.screenLeft)
      {
         var topWin = getTopLevelWnd();
         left = topWin.screenLeft;
      }
   }
   return left;
}

function getWindowTop(win)
{
   var top = 0;
   if (win)
   {
      if (win.dialogTop)
      {
         // showModalDialog dialogTop format is "[num]px". Need to strip the "px" and return [num].
         top = parseInt(win.dialogTop.substring(0, win.dialogTop.length - 2));
      }
   }
   return top;
}

/**
 * This function was meant to only be triggered when the modal dialog is closed. However, the way it is implemented
 * it will be triggered on every unload of anything inside the modal dialog.
 */
function onBeforeUnloadModalPopup(evt)
{
   if (typeof(evt) == 'undefined')
   {
      evt = window.event;
   }
   //Bug 159990 - Don't consider event coordinates during unload.
   if (evt)
   {
      // user clicks [X] button
      var parentWindow = window.getWindowOpener();
      if (parentWindow != null)
      {
         parentWindow.endModalPopupMode(null, parentWindow.document.forms[0].name);
      }
   }
}

if (window.isModalPopup())
{
   if (g_clientInfo.isBrowser(ClientInfo.MSIE))
   {
      attachEvent("onbeforeunload", onBeforeUnloadModalPopup);
   }
}

/**
 * PRIVATE : visit child iframes and invoke the handler if modal window is found
 * @param wnd window object
 * @param modalWnd modal window
 * @return true of any of child iframe window matches the modal window, false otherwise
 */
function resizeIFrames(wnd, modalWnd)
{
   var isFound = false;
   for (var i=0; i<wnd.frames.length; i++)
   {
      if (wnd.frames[i] === modalWnd)
      {
         isFound = true;
         break;
      }
      else
      {
         if (resizeIFrames(wnd.frames[i], modalWnd))
         {
            isFound = true;
            break;
         }
      }
   }

   //handler is called on the way up to the root iframe
   if (isFound)
   {
      setCustomAttribute(wnd, "visited", true)
       //call beginModalHandler for this iframe
      if (typeof (wnd.beginModalHandler) === 'function')
      {
         wnd.beginModalHandler(modalWnd);
      }

   }
   return isFound;
}

/**
 * PRIVATE : call endModalHandler() for all the "visited" iframes
 * @param wnd window object
 */
function restoreIFrames(wnd)
{
   if (wnd.visited)
   {
      setCustomAttribute(wnd, "visited", false);
      if (typeof (wnd.endModalHandler)  === 'function')
      {
         wnd.endModalHandler();
      }
   }
   //restore children
   for (var i=0; i< wnd.frames.length; i++)
   {
      restoreIFrames(wnd.frames[i]);
   }
}


