// -------------------------------------------------------------------------------------------------------------
// openWindow
//
//    Opens the give URL in a popup window with the given name, width, height and options.
//

function openWindow(url, name, width, height, options)
{
   var left, top, windowOptions;

   left = (screen.availWidth - width) / 2;
   top = (screen.availHeight - height) / 2;

   windowOptions = 'resizable=yes,toolbar=no,status=no,menubar=no,width=' + width + ',height=' + height + ',left=' + left + ',top=' + top;

   if (options != null)
   {
      windowOptions = windowOptions + ',' + options;
   }
   
   popup = window.open(url, name, windowOptions);

   return false;
}


// -------------------------------------------------------------------------------------------------------------
// openMainWindow
//
//    Attempts to open the given URL in a full-size window if it exists (the "main window", which is the window 
//    which opened the current popup window, if that window was not itself a popup). Otherwise, it opens the 
//    URL in a new window. 
//

function openMainWindow(url)
{
   var mainWindow = getMainWindow(top.window);

   if (mainWindow != null)
   {
      mainWindow.focus();
      mainWindow.location.href = url;
   }
   else
   {
      openNewMainWindow(url);
   }

   return false;
}


// -------------------------------------------------------------------------------------------------------------
// openNewMainWindow
//
//    Opens the given URL in a new full-size window. 
//

function openNewMainWindow(url)
{
   window.open(url, null, "location=yes,menubar=yes,resizable=yes,scrollbars=yes,status=yes,toolbar=yes");

   return false;
}


// -------------------------------------------------------------------------------------------------------------
// refreshMainWindow
//
//    Attempts to reload the URL in the main window.
//

function refreshMainWindow()
{
   var mainWindow = getMainWindow(top.window);

   if (mainWindow != null)
   {
      mainWindow.location.reload();
   }

   return false;
}


// -------------------------------------------------------------------------------------------------------------
// getMainWindow
//
//    Attempts to get a reference to the main window given a child window (the main window is considered the 
//    window which opened this window, ie, the opener). If the main window cannot be found, null is returned.
//

function getMainWindow(childWindow)
{
   /* ***NOTE***
    * The following attempts to find a reference to the window that opened this window if 
    * it still exists.
    *
    * The trick is getting this to work in Netscape and IE. typeof on the window.opener
    * is a general test that makes sure we have a window opener object. This appears to
    * always be the case with popup windows in both browsers, but is not with regular 
    * windows. Regular windows may set the top.window.opener property to be null. Since
    * I don't know if a browser will have this property null or undefined, we test both
    * (typeof = object means !undefined, which you can't test for directly)
    * 
    * More comments regarding how this is done are below. However, the comments are from
    * memory after working on this code for a couple hours, so they may not be 100% accurate.
    * Your mileage may vary.
    *
    * Tested in Netscape 4.7, 6.1 and IE 4.0, 5.0.
    *
    *
    * ***NOTE***
    * This function was originally written to detect the full-size window that launched a popup
    * window. Hence main window is equivalent to full-size window, and child window is equivalent
    * to popup window. It has been made more generic for future development when it is necessary to 
    * recursively navigate up a window hierarchy.
    */

   var mainWindow = null;

   // First, test to see if this window was opened by another window [IE4] by testing that 
   // window.opener is an object. Is always an object in Netscape 4, only when it exists 
   // in IE 4.
   //
   if (typeof(childWindow.opener) == "object")
   {
      // Next, continue testing to see if this window was opened by another window [Netscape 4]
      // by testing to make sure the opener is not null. Is null in Netscape 4 if window
      // never had an opener.
      //
      if (childWindow.opener != null)
      {
         // Next, test to see if the window is still open. This is a bit of a strange test. In
         // IE4/IE5 childWindow.opener.name becomes unknown when the window is closed, in 
         // Netscape 4 it becomes undefined, in Netscape 6 it stays a string but any window name 
         // becomes an empty string. It is always a string when the window is open in all browsers 
         // tested.
         //
         // The real reason for having this here is that IE4 (but not IE5) creates an exception if 
         // it attempts to access the childWindow.opener.closed property, but accessing this property 
         // is required for the script to work properly in Netscape 6. 
         //
         if (typeof(childWindow.opener.name) == "string")
         {
            // Next, continue testing to see if the window is still open. This works in Netscape 4, 6
            // and IE 5, but only Netscape 6 will get this far because of the previous test.
            //
            if (!childWindow.opener.closed)
            {
               // Finally, make sure the child window was not opened by another child
               // window (in which case the main window is not the immediate predecessor). 
               // 
               // Project for later is to recurse up the hierarchy and still open it in the
               // main window even if this is a child window opened by a child window. No time right now.
               //
               if (typeof(childWindow.opener.top) != "object" || childWindow.opener.top == null ||
                   typeof(childWindow.opener.top.opener) != "object" || childWindow.opener.top.opener == null)
               {
                  mainWindow = childWindow.opener;
               }
            }
         }
      }
   }

   return mainWindow;
}


// -------------------------------------------------------------------------------------------------------------
// doAction
//
//    Performs the action contained in the action string. Any variables needing to be resolved are resolved
//    through the given form.
//

function doAction(actionString, form)
{
   var parameters;
   var parameterArray, parameterName, parameterValue, parsedParameter;


   // -------------------------
   // Setup Defaults
   // -------------------------
   parameters = new Array();

   parameters['action']  = "popup";
   parameters['options'] = "scrollbars=yes";


   // -------------------------
   // Read Parameters
   // -------------------------
   parameterArray = actionString.split(";");

   for (var i=0; i<parameterArray.length; i++)
   {
      if (parameterArray[i].indexOf("=") > 0) 
      {
         // Parse everything up to first equals sign as parameter name,
         // everything else as parameter value (including any additional
         // equal signs)
         //
         parsedParameter = parameterArray[i].split("=");

         parameterName = parsedParameter[0];

         parsedParameter[0] = "";

         parameterValue = parsedParameter.join("=");
         parameterValue = parameterValue.substring(1, parameterValue.length);

         parameters[parameterName] = parameterValue;
      }
   }


   // -------------------------
   // Execute Action
   // -------------------------
   if (parameters['action'] == "popup")
   {
      parameters['url'] = resolveFormFields(parameters['url'], form);

      openWindow(parameters['url'], parameters['name'], parameters['width'], parameters['height'], parameters['options']);
   }
   else if (parameters['action'] == "profile")
   {
      parameters['width']   = 540;
      parameters['height']  = 420;
      parameters['name']   = "profile_$UserID$";

      if (typeof(parameters['section']) == "string")
         parameters['url']    = "/SiteApps/profile/view-profile-popup.asp?UserID=$UserID$&Section=" + parameters['section'];
      else
         parameters['url']    = "/SiteApps/profile/view-profile-popup.asp?UserID=$UserID$";

      parameters['url']  = resolveFormFields(parameters['url'], form);
      parameters['name'] = resolveFormFields(parameters['name'], form);

      openWindow(parameters['url'], parameters['name'], parameters['width'], parameters['height'], parameters['options']);
   }
   else if (parameters['action'] == "goto")
   {
      parameters['url']  = resolveFormFields(parameters['url'], form);

      location.href = parameters['url'];
   }
   else if (parameters['action'] == "alert")
   {
      parameters['message']  = resolveFormFields(parameters['message'], form);

      alert(parameters['message']);
   }

   return false;
}


// -------------------------------------------------------------------------------------------------------------
// resolveFormFields
//
//    Returns a string where any instances of $formFieldName$ are replaced with the value of the given
//    form field, based on values in the given form.
//

function resolveFormFields(inString, inForm)
{
   var startIndex, endIndex, fieldName, fieldValue;

   if (inForm != null)
   {
      startIndex = inString.indexOf("$");
      endIndex   = inString.indexOf("$", startIndex + 1);

      while (startIndex >=0 && endIndex >=0)
      {
         fieldName  = inString.substring(startIndex + 1, endIndex);

         if (typeof(inForm.elements[fieldName]) == "object")
         {
            fieldValue = inForm.elements[fieldName].value;
         }
         else
         {
            fieldValue = "";
         }

         inString = inString.substring(0, startIndex) + fieldValue + inString.substring(endIndex + 1, inString.length);

         startIndex = inString.indexOf("$");
         endIndex   = inString.indexOf("$", startIndex + 1);
      }
   }

   return inString;
}
