﻿var MAX_PARENTS_TO_SEARCH = 500;

/*

ScanParentsForApi
-Searches all the parents of a given window until
 it finds an object named "API_1484_11". If an
 object of that name is found, a reference to it
 is returned. Otherwise, this function returns null.
*/

function ScanParentsForApi(win)
{
      /*
      Establish an outrageously high maximum number of
      parent windows that we are will to search as a
      safe guard against an infinite loop. This is
      probably not strictly necessary, but different
      browsers can do funny things with undefined objects.
      */

      var nParentsSearched = 0;

      /*
      Search each parent window until we either:
             -find the API,
             -encounter a window with no parent (parent is null
             or the same as the current window)
            -or, have reached our maximum nesting threshold
      */

      while ( (win.API == null) && (win.parent != null) && (win.parent != win) && (nParentsSearched <= MAX_PARENTS_TO_SEARCH))
      {           
            nParentsSearched++;
            win = win.parent;
      }
    
      /*
      If the API doesn't exist in the window we stopped looping on,
      then this will return null.
      */

      return win.API;
}

/*

GetAPI
-Searches all parent and opener windows relative to the
 current window for the SCORM 2004 API Adapter.
 Returns a reference to the API Adapter if found or null
 otherwise.
*/

function GetApi()
{
      var API = null;
      //Search all the parents of the current window if there are any
      if ((window.parent != null) && (window.parent != window))
      {
            API = ScanParentsForApi(window.parent);
      }

      /*
      If we didn't find the API in this window's chain of parents,
      then search all the parents of the opener window if there is one
      */
      if ((API == null) && (window.top.opener != null))
      {
            API = ScanParentsForApi(window.top.opener);
      }

      return API;
}