
/*
 *
 * File:      $RCSfile: si_pglayout.js,v $
 * Version:   $Revision: 1.0 $
 * Revised:   $Date:  $
 *            $Author: mbm $
 *
 * Created:   2006-06-01
 * Author:    sectra:mbm
 * Project:   Web
 *
 *
 * Description
 *   Scripted page layout.
 *
 * Compatibility:
 *   IE      >= 5.0 
 *   Mozilla >= 5.0
 *   Opera   >= 7.0
 *   Firefox >= 1.0
 *   Safari  >= 1.0
 *
 * Dependencies:
 *   si_pglayout_b.js
 *
 * General comments:
 *   The si_pglayout.js script is divided in two sections; si_pglayout.js and 
 *   si_pglayout_b.js, the latter included in the page with the deferred 
 *   attribute set to reduce the time before the page can display. Functions 
 *   needed to run immediately at page load at located in si_pglayout.js, 
 *   while the rest, to be called upon firing the onLoad event, is located in 
 *   si_pglayout_b.js.
 *
 *
 *   [c1]: When reloading a page in FF, it the scripts are thrown out of 
 *         context before the actual page, making event handlers still 
 *         attached to elements in the page to cause script errors on, for 
 *         example, mouse over. A test is therefore performed in each event 
 *         handler before calling functions in the script. 
 * 
 *         Also, is seems that the default (function call) context "leaves" 
 *         slightly before the scripts are removed from the window object, so 
 *         for testing for presence of a function in the window context to be 
 *         safe the function must be called on the window context as well.
 */


/*
 * Browser detection
 */

DETECT = new Object();
DETECT.is_opera     = (navigator.userAgent.indexOf("Opera")!=-1)?true:false;
DETECT.is_safari    = (navigator.userAgent.indexOf('Safari')!=-1)?true:false;
DETECT.is_ie        = ((navigator.appName=="Microsoft Internet Explorer")?true:false) && !DETECT.is_opera;
DETECT.is_gecko     = (navigator.product=="Gecko") && !DETECT.is_safari;
DETECT.versionStr   = navigator.userAgent.replace(/.*(MSIE|Opera|Firefox|Netscape|Safari|Mozilla)[^\d\.]+([\d\.]*).*/i, '$2');
DETECT.majorVersion = parseFloat(DETECT.versionStr.replace(/(\d*).*/, '$1'));
DETECT.version      = parseFloat(DETECT.versionStr.replace(/(\d*)\.?(\d*)/, '$1.$2'));
DETECT.is_ie6       = DETECT.is_ie && DETECT.majorVersion >= 6;
DETECT.is_ieLt6     = DETECT.is_ie && !DETECT.is_ie6;
DETECT.is_ie7       = DETECT.is_ie && DETECT.majorVersion >= 7;
DETECT.is_ieLt7     = DETECT.is_ie && !DETECT.is_ie7;


if(DETECT.is_gecko)
{
  if(navigator.userAgent.indexOf("Netscape")==-1)
  {
    DETECT.is_ns   = false;
    DETECT.is_moz  = true;
  }
  else
  {
    DETECT.is_ns   = ((navigator.appName=="Netscape")?true:false) && !DETECT.is_opera  && !DETECT.is_safari;
    DETECT.is_moz  = false;
  }
}




/*===========================================================================
 *
 * Constants
 *
 */

SIP_CONST = {
    
    ZONE: {
      INDICATOR_ID:             'businessareaimg',
      INDICATOR_SRC:            '/%zone%/images/_fw_front_business_area_header.gif',
      DROPMENU_ID:              'businessareadrop',
      DROPMENU_SRC:             '/%zone%/images/_fw_front_business_droparrow.default.gif',
      NAMES:                    ['corporate', 'medical', 'security', 'admin', 'dxr', 'highrex'],
      NONAME:                   'common'
    },

    UNSUPPORTED_FIXES: {
      IESTYLES_OBJELEM_ID:      'si_iecss'
    },

    ACTIVE_LINKS: {
      ROOT_IDS:                 ['canvas', 'businessareadrop', 'minisearchform'],

      EXTERNAL: {
        CLASS_NAME:         'siplinkdecorationexternal',
        TITLE:              'External link',

        SELECT: {
          FILE_PATTERN:      new RegExp('^http.?:\\/\\/(?!(' + window.location.hostname.replace(/\./g, '\\.') + ')|(.*\\.sectra\\.))')
        }
      },
    
      POPUP: {
        CLASS_NAME:         'siplinkdecorationpopup',
        TITLE:              'shows in a popup window',

        SELECT: {
          FILE_PATTERN:       /^[^?]*(\.pdf\b|\.gif\b|\.jpg\b|\.swf\b|\.flv\b)/i,
          IMG_FILE_PATTERN:   /(\.gif\b|\.jpg\b)/i,
          MOVIE_FILE_PATTERN: /(\.swf\b|\.flv\b)/i
        },

        WINDOW: {
            NAME:          '_blank',
            V_MARGIN:      32,
            H_MARGIN:      32,
            MIN_WIDTH:     800
        }
      },

      SPLASH: {
        SELECT: {
          FILE_PATTERN:      /\bsplash\b/
        }
      },

      BTN_HOVER_CLASS_NAME: 'sipbuttonhover',

      SKIP_CLASS_PATTERN:   /followme/i,

      DECORATION: {
          ACTIVE_IMG_PATTERN:   'default',
          CURRENT_PAGE_CLASS:   'sipcurrentpage'
      }

    },

    FLASH: {
      REQUIRE_VERSION:          8
    },

    SORT_TABLES: {
      SORT_DESCENDING_CLASS:    'sipsortup',
      SORT_ASCENDING_CLASS:     'sipsortdown',
      CAPTION_HOVER_CLASS:      'sipsorthover',
      CAPTION_TITLE:            'Click to sort on %text%'
    },

    MINISEARCH: {
        INPUT_ID:               'findwords',
        INPUT_DEFAULT_VALUE:    'Find at sectra.com',
        INPUT_DEFAULT_CLASS:    'sipemptyinput'
    },

    SPLASH: {
        SELECTOR_PATTERN:       /.*sipsplash=(.*)/,
        PATH_PREFIX_ENBALE:     '?',
        PATH_PREFIX:            '/common/php/submit.php?form='
    },

    TEST_URL_PATTERN:  /(http:\/\/tarrekaise|http:\/\/tjidtjak|http:\/\/localhost|http:\/\/web-devel|http:\/\/edit)/,

    URCHIN_CODE:       "UA-2624518-1",
    URCHIN_DOMAIN:     "none"
}


// #PRAGMA COMPACT START SKIP

/*===========================================================================
 *
 * Debug parameters
 *
 */

SIP_DEBUG = {
  ENABLE:       true,
  DREAMWEAVER:  ['C:\\progra~1\\Adobe\\Adobe Dreamweaver CS3\\Dreamweaver.exe', 'C:\\progra~1\\Macromedia\\Dreamweaver 8\\Dreamweaver.exe'],
  CODEEDITOR:   ['C:\\VStudio\\Common\\MSDev98\\Bin\\MSDEV.EXE', 'C:\\Program Files\\Microsoft Visual Studio 8\\Common7\\IDE\\devenv.exe', 'C:\\WINDOWS\\NOTEPAD.EXE', 'C:\\WINNT\\NOTEPAD.EXE'],
  EXPLORE:      ['explorer.exe'],
  SITE_ROOT:    'W:\\Sites\\www.sectra.se\\Version_6\\root'
}

// #PRAGMA COMPACT END SKIP

/*
 * Global variables
 */

SIP_GLOBAL = null;




/*===========================================================================
 *
 * General methods
 *
 */

/*
 * x()
 *   x
 *
 * In:
 *   x
 *
 * Returns
 *   x
 */

function sip_mkId(name)
{
  return(name.replace(/[^a-z0-9_]+/ig, ''));
}


/*
 * x()
 *   x
 *
 * In:
 *   x
 *
 * Returns
 *   x
 */


function _sip_trimStop(chr, quotes)
{
  switch(chr)
  {
    case '\0':
    case ' ':  // space!
    case ' ':  // nbsp!
    case '\t':
    case '\n':
    case '\r':
      break;
    case '"':
    case '\'':
      if(quotes)
        break;
    default:
      return(true);
  }
  return(false);
}


function sip_trim(str, quotes)
{
  var p = -1;
  var q = -1;

  for(i=0; p==-1 && i<str.length; i++)
  {
    if(_sip_trimStop(str.charAt(i), quotes))
      p=i;
  }


  for(i=str.length-1; q==-1 && p>=0; i--)
  {
    if(_sip_trimStop(str.charAt(i), quotes))
      q=i;
  }

  return(str.substring(p, q+1));
}




/*
 * x()
 *   x
 *
 * In:
 *   x
 *
 * Returns
 *   x
 */

function sip_mkArray(value)
{
  if(value!=null && value.sort==null)
    value = new Array(value);
  return(value);
}



/*
 * x()
 *   x
 *
 * In:
 *   x
 *
 * Returns
 *   x
 */

function sip_arrayLength(array)
{
  if(array==null)
    return(0);
  else
    return(array.length);
}



/*
 * x()
 *   x
 *
 * In:
 *   x
 *
 * Returns
 *   x
 */

function sip_ceilArrayIndex(array, index)
{
  if(array==null || array.length==0)
    return(null);
  else if(index>=array.length)
    return(array[array.length-1]);
  else
    return(array[index]);
}



/*
 * x()
 *   x
 *
 * In:
 *   x
 *
 * Returns
 *   x
 */

function sip_stripPath(path)
{
  var path=path.replace(/[#|?].*$/, '').replace(/index.html?/i, '');
  return(path);
}


/*
 * x()
 *   x
 *
 * In:
 *   x
 *
 * Returns
 *   x
 */

function sip_stripUrl(url)
{
  var url=url.replace(/#.*$/, '').replace(/index.html?/i, '');
  return(url);
}



/*
 * x()
 *   x
 *
 * In:
 *   x
 *
 * Returns
 *   x
 */

function sip_url2path(url)
{
  var url=url.replace(/^[^:]*:\/\/[^\/]*/, '');
  return(url);
}



/*
 * x()
 *   x
 *
 * In:
 *   x
 *
 * Returns
 *   x
 */

function sip_getCurrentPath()
{
  return(sip_url2path(sip_stripPath(window.location.href)));
}


/*
 * sip_getSiteTopWindow()
 *   Returns the topmost window (frame) that is loaded from the current site; 
 *   there may still be encapsulating windows from other sites.
 *
 * In:
 *   win: (optional) current window
 *
 * Returns
 *   The topmost window (frame) that is loaded from the same site as 'win'.
 */

function sip_getSiteTopWindow(win)
{
  var top = win != null ? win : window;
  try
  {
    /* Traverse up in the window hierarchy; the access of 
     * top.parent.location.href throws an exception if top.parent is loaded 
     * from another site
     */
    while(top.parent != top && top.parent.location.href != null)
      top = top.parent;
  }
  catch(e){}
  return(top);
}

/*
 * x()
 *   x
 *
 * In:
 *   x
 *
 * Returns
 *   x
 */

function isNativeZone()
{
  var path = sip_getCurrentPath();

  for(var i=0; i<SIP_CONST.ZONE.NAMES.length; i++)
  {
    if(path.indexOf(SIP_CONST.ZONE.NAMES[i])==1)
      return(true);
  }
  return(false);
}



/*
 * x()
 *   x
 *
 * In:
 *   x
 *
 * Returns
 *   x
 */

function sip_getAncestorByTagName(element, tagName, id)
{
  while(element!=null && (element.tagName!=tagName || (id!=null && element.id!=id)))
    element=element.parentNode;
  return(element);
}



/*
 * x()
 *   x
 *
 * In:
 *   x
 *
 * Returns
 *   x
 */

function sip_getNextSiblingByTagName(element, tagName)
{
  while(element!=null && element.tagName!=tagName)
    element=element.nextSibling;
  return(element);
}



/*
 * x()
 *   x
 *
 * In:
 *   x
 *
 * Returns
 *   x
 */

function sip_getPreviousSiblingByTagName(element, tagName)
{
  while(element!=null && element.tagName!=tagName)
    element=element.previousSibling;
  return(element);
}



/*
 * x()
 *   x
 *
 * In:
 *   x
 *
 * Returns
 *   x
 */

function sip_isClass(element, className)
{
  return(element!=null && element.className!=null && element.className.indexOf(className)!=-1);
}



/*
 * x()
 *   x
 *
 * In:
 *   x
 *
 * Returns
 *   x
 */

function sip_mkAttributeString(attributeName, attributeValue, defaultAttributeValue)
{
  if(!attributeValue && defaultAttributeValue)
    attributeValue = defaultAttributeValue;
  if(attributeValue && attributeValue.replace)
    attributeValue = attributeValue.replace(/"/g, '&quot;');
  if(attributeValue)
  {
    if(attributeName)
      return(' ' + attributeName + '="' + attributeValue + '"');
    else
      return('"' + attributeValue + '"');
  }
  else
    return('');
}



/*
 * (IE only) 
 * sip_getHtmlProperty()
 *   Returns the value of a named property of an HTML element, as sepcified 
 *   in the HTML code.
 *
 *   Note: The properties in the attributes collection relects the computed 
 *   values of the CSS (if any) rather than the actual attributes.
 *
 * In:
 *   elem: HTML element to query
 *   property: name of property to query
 *
 * Returns: 
 *   value of the property, or null if not found.
 */

function sip_getHtmlProperty(elem, property)
{
  var re=new RegExp('.*' + property + '=(\\d*).*');
  if(elem.outerHTML!=null && elem.outerHTML.match(re))
    return(elem.outerHTML.replace(re, '$1'));
  else
    return(null);
}


/*
 * (IE only)
 * sip_getImgScaling()
 *   Returns a CSS zoom value for fitting an image in its container.
 *
 *   When called from a stylesheet zoom-property expresssion, scales down 
 *   images to fit the container:
 *
 *   zoom: expression(window.sip_getImgScaling?sip_getImgScaling(this):'normal');
 *
 * In:
 *   elem: <IMG> element to query
 *
 * Returns: 
 *   zoom value.
 */

function sip_getImgScaling(elem)
{
  if(elem._si_origWidth==null)
    elem._si_origWidth=1*sip_getHtmlProperty(elem, 'width');

  var offset = 2;
  var container;
  for(container = elem.parentNode; container!=null && container.tagName!='DIV'; container = container.parentNode);

  if(container!=null)
    elem._si_scaled=container.offsetWidth-offset < elem._si_origWidth;
  if(container!=null && elem._si_scaled)
    return(Math.max(0.1, (container.offsetWidth-offset) / elem._si_origWidth));
  else
    return('normal');
}



/*
 * x()
 *   x
 *
 * In:
 *   x
 *
 * Returns
 *   x
 */

function sip_isTestServer()
{
  return(window.location.href.match(SIP_CONST.TEST_URL_PATTERN)!=null);
}



/*===========================================================================
 *
 * Browser patches
 *
 */

/*
 * sip_closeGroups()
 *   Makes groups enclose floates. 
 *
 *   This is mainly in effect in non-mozilla and non-IE (e.g. Opera) as the 
 *   functionality is also available in CSS as ":last-child:after" pseudoclass 
 *   for W3C compliant browsers and "zoom: 1" for IE (exploiting IE bug).
 */

/* APA: N/U: changed rule not to use :last-child, now worx in Opera!
function sip_closeGroups()
{
  var boxes=window.document.body.getElementsByTagName('DIV');
  for(var i=0; i<boxes.length; i++)
  {
    if(sip_isClass(boxes[i], 'group'))
    {
      var boxCloser = document.createElement('P');
      boxCloser.innerHTML='&nbsp;';
      boxCloser.className=SIP_CONST.UNSUPPORTED_FIXES.CLOSEGROUPS_CLASS;

      boxes[i].appendChild(boxCloser);
    }
  }
}
*/



/*
 * sip_geckoCaptions()
 *   Adjust margin positioning of table-<caption> in Gecko
 *
 *   Note 1: This al has a weakness that it does not consider further layout 
 *           (i.e. window sizing) after computation of the new locations. 
 *   Note 2: It seems impossible to use getComputedStyle() as the style for 
 *           tbody is non existing and the actual margins are implemented in 
 *           the tbody rather than in the table.
 */

function sip_geckoCaptions()
{
  if(DETECT.is_gecko)
  {
    // Loop for all all <captions> elements:
    var captions=window.document.getElementsByTagName('CAPTION');
    for(var i=0; i<captions.length; i++)
    {
      if(captions[i]._sip_geckocaptionwashere)
        continue;
      // Get related table and tbody elements:
      var table = sip_getAncestorByTagName(captions[i],    'TABLE');
      var container = table.parentNode;
      var tbody = sip_getNextSiblingByTagName(captions[i], 'TBODY');
      if(!tbody || !table)
        continue;

      // Remember the old <caption> width:
      var width=captions[i].offsetWidth;

      // Adjust the left margin to fit the table: 
      captions[i].style.marginLeft = tbody.offsetLeft - table.offsetLeft + 'px';

      /* 
       * Re-dock the <caption> to the table, overriding the marginTop of the 
       * table that is in the way!
       * Note: Surprisingly enough the offsetTop of the <caption> is relative 
       * the table parent, not the table!
       */
      captions[i].style.marginBottom = (captions[i].offsetHeight + captions[i].offsetTop 
                                        - (table.offsetTop + tbody.offsetTop)) 
                                       + 'px';

      /* 
       * Restore the width of the <caption>, but dn't make it wider than the 
       * container as it will make it jump back to the left edge again:
       */
      captions[i].style.width=Math.min(container.offsetWidth, width) + 'px';
    
      captions[i]._sip_geckocaptionwashere=true;
    }
  }
}



/*
 * x()
 *   x
 *
 * In:
 *   x
 *
 * Returns
 *   x
 */

function sip_iePng()
{
  // Loop through all images:
  var images = window.document.getElementsByTagName('IMG');
  for(var i=0; i<images.length; i++)
  {
    // Is this a PNG?
    if(images[i].src.indexOf('.png')!=-1)
    {
      // Create a substitute element:
      var substitute = document.createElement('span');
      images[i].insertAdjacentElement('afterEnd', substitute);
  
      // Copy the current style to the div to keep the complete positioning:
      for(var name in images[i].currentStyle)
        substitute.style[name]=images[i].currentStyle[name];

      // Set the alpha filter:
      substitute.style.filter='progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + images[i].src + '", sizingMethod="scale")';

      // Hide the original image (don't remove it as it might be referred to by other scripts):
      images[i].style.display='none';
    }
  }
}



/*
 * x()
 *   x
 *
 * In:
 *   x
 *
 * Returns
 *   x
 */

function sip_unsupported()
{
  // Set up magic IE styles:
  if(DETECT.is_ieLt7 && window.si_iecss_init!=null)
  {
    si_iecss_init(SIP_CONST.UNSUPPORTED_FIXES.IESTYLES_OBJELEM_ID);
    var inlineStyles=window.document.getElementsByTagName('STYLE');
    for(var i=0; i<inlineStyles.length; i++)
    {
      if(!inlineStyles[i].disabled)
        si_iecss_init(inlineStyles[i]);
    }
  }

  // Remove disabled style-sheets (mainly Opera):
  var styleSheets=window.document.getElementsByTagName('LINK');
  for(var i=0; i<styleSheets.length; i++)
  {
    if(styleSheets[i].disabled)
      styleSheets[i].parentNode.removeChild(styleSheets[i]);
  }

  // Adjust margin positioning of table-<caption> in Gecko:
  if(DETECT.is_gecko)
    sip_geckoCaptions();

  if(DETECT.is_ieLt7)
    sip_iePng();

  //APA: sip_closeGroups();
}


/*===========================================================================
 *
 * Scrambeled links decoding
 *
 */

/*
 * sip_mailLinkDecode()
 *   Decodes a single encoded e-mail URL.
 *
 * In:
 *   x
 *
 * Returns
 *   x
 */

function sip_mailLinkDecode(coded)
{
  return(coded.replace(/.*\/mailto[^\?]*\?/, 'mailto:')
              .replace(/.*\/ilmail[^\?]*\?/, 'mailto:')
              .replace(/\{at?\}/g, '@')
              .replace(/\(at?\)/g, '@')
              .replace(/\/at?\//g, '@')
              .replace(/\{d(ot)?\}/g, '.')
              .replace(/\(d(ot)?\)/g, '.')
              .replace(/\/d(ot)?\//g, '.')
              .replace(/@removethis/, ''));
}


/*APA
function sip_formredirect()
{
  if(window.location.href.indexOf('/common/php/submit.php')!=-1)
    return;

  var forms=window.document.body.getElementsByTagName('FORM');
  for(var fi=0; fi<forms.length; fi++)
  {
    if(forms[fi].action.indexOf('/common/php/submit.php')!=-1)
      window.location.replace(SIP_GLOBAL.serverURL + '/common/php/submit.php?form=' + window.location.pathname);
  }
}
*/


/*
 * sip_mkMailAddresses()
 *   Decodes e-mail addresses and updates the links.
 *
 * In:
 *   x
 *
 * Returns
 *   x
 */

function sip_mkMailAddresses()
{
  var links=document.links;

  for(var i=0; (links!=null) && (i<links.length); i++)
  {
    if(links[i].href && ((links[i].href.indexOf('/mailto/')!=-1) || (links[i].href.indexOf('/ilmail/')!=-1)))
    {
      // Update link href and caption:
      // Note: dont turn this upside down - setting href after innerHTML makes the innerHTML mysteriously change in IE6!
      links[i].href      = sip_mailLinkDecode(links[i].href);
      links[i].innerHTML = sip_mailLinkDecode(links[i].innerHTML);
    }
  }
}




/*===========================================================================
 *
 * Flash content
 *
 */

/*
 * x()
 *   x
 *
 * In:
 *   x
 *
 * Returns
 *   x
 */

function sip_getSwfVersion(requireMajor)
{
  var swfVersion = null;

  if(requireMajor!=null)
    requireMajor = '.' + requireMajor;
  else
    requireMajor = '';

  if(navigator.plugins && navigator.mimeTypes.length)
  {
    var plug = navigator.plugins["Shockwave Flash"];
    if(plug && plug.description)
      swfVersion = plug.description.replace(/([a-zA-Z]|\s)+/, "").replace(/(\s+r|\s+b[0-9]+)/, ".").split(".");
    if(swfVersion && requireMajor!='' && requireMajor>swfVersion[0])
      swfVersion = null;
  }
  else
  { 
    var axo = null;
    try
    {
      axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash" + requireMajor);
    }
    catch(e){}
    if(axo!=null)
    {
      try
      {
        swfVersion = [6,0,21];
        axo.AllowScriptAccess = "always";
        swfVersion = null;
        swfVersion = axo.GetVariable("$version").split(" ")[1].split(",");
      }
      catch(e){}
    }
  }
  return(swfVersion);
}




/*
 * sip_createSwfControl()
 *   Writes code to the document to load an SWF movie, circumvents the "grey 
 *   box of death" or "Click to activate and use this control"-misfeature (aka
 *   "EOLAS problem") in IE. 
 *
 *   This approach avoids the layout flicker of the otherwise neather approach 
 *   with scripted "cut/paste-replace" <object> tags included in the HTML page.
 *
 *   Called by inline-script during document load (containerID==null) or after 
 *   load from an event handler (containerID!=null).
 *
 *   See http://msdn.microsoft.com/library/default.asp?url=/workshop/author/dhtml/overview/activating_activex.asp.
 *
 * In:
 *   id:          ID of the new Flash control
 *   URL:         URL of the Flash movie to load
 *   vars:        Variables to pass to the Flash movie. Variables can be 
 *                passed as an URL encoded string or as an associative array.
 *   styles:      (optional) Styles to assign to the new Flash control
 *   containerID: (optional) ID of element to receive the Flash control HTML
 *   baseURL:     (optional) Base URL for relative paths in the Flash movie
 "                   URL: Given URL is the base
 *                   "@": Path of the Flash movie is the base
 *                   Default: Path of the current document is the base
 *   linkURL:     (optional) URL of wrapper link. This allows browser default 
 *                link-actions when clicking the banner, but prevents clicks 
 *                from reaching the banner itself. The link sends mouseover 
 *                and onmouseout interaction events to commandGw at _level0 of 
 *                the Flash control. Note: IE and FF only.
 *   width:       (optional) Width of the new Flash control
 *   height:      (optional) Height of the new Flash control
 *   wmode:       (optional) Window mode, default is "opaque"
 *   bgcolor:     (optional) Background color, default is #ffffff
 *
 * One or more of the attributes id, URL, vars and styles may be arrays to 
 * create multiple controls.
 *   
 *
 * Pre condition: 
 *   Document is loading (use containerID==null)
 *   Document is loaded (use containerID!=null)
 *
 * Post condition: 
 *   Flash control HTML code written to the document or the containerID element.
 */


function sip_createSwfControl(id, 
                              URL, 
                              vars, 
                              styles, 
                              containerID, 
                              baseURL, 
                              linkURL, 
                              width, 
                              height, 
                              wmode, 
                              bgcolor)
{
  if(sip_getSwfVersion(SIP_CONST.FLASH.REQUIRE_VERSION)==null)
    return;

  // Set default values:
  if(!wmode)
    wmode = "opaque";
  if(!bgcolor)
    bgcolor = "#ffffff";

  // Convert args to arrays:
  id        = sip_mkArray(id);
  URL       = sip_mkArray(URL);
  vars      = sip_mkArray(vars);
  styles    = sip_mkArray(styles);
  linkURL   = sip_mkArray(linkURL);
  wmode     = sip_mkArray(wmode);
  bgcolor   = sip_mkArray(bgcolor);

  // Nrof controls to create:
  var count = Math.max(Math.max(sip_arrayLength(id), sip_arrayLength(URL)), Math.max(sip_arrayLength(vars), sip_arrayLength(styles)));
  var html  = '';

  // For each control:
  for(var i=0; i<count; i++)
  {
    // Get the flashvars string, it can be passed as an URL encoded string or 
    // as an associative array:
    var varString = '';
    var varSet    = sip_ceilArrayIndex(vars, i);
    if(varSet!=null && varSet.indexOf==null)
    {
      for(var name in varSet)
      {
        if(varString!='')
          varString += '&';
        varString += name + '=' +   varSet[name];
      }
    }
    else
      varString = varSet;

    var cId     = sip_ceilArrayIndex(id, i);
    var cUrl    = sip_ceilArrayIndex(URL, i);

    if(baseURL=='@')
      baseURL = cUrl.replace(/[^\/]*$/, '');
    else if(!baseURL)
      baseURL = window.location.href.replace(/[^\/]*$/, '');

    if(linkURL!=null)
      html += '<a href="' + sip_ceilArrayIndex(linkURL, i)+ '"\n'
            + '   onmouseover="window.document.title +=\' over\'; window.document.getElementById(\'' + cId + '\').SetVariable(\'commandGw\', \'mouseover\')"\n'
            + '   onmouseout="window.document.title +=\' out\'; window.document.getElementById(\'' + cId + '\').SetVariable(\'commandGw\', \'mouseout\')"\n'
            + '   style="position: absolute; z-index: 100; background: url(/common/images/nothing.gif); ' + sip_ceilArrayIndex(styles, i) + '"></a>\n';

    html += '<object type="application/x-shockwave-flash"\n'
          + '    ' + sip_mkAttributeString('style', sip_ceilArrayIndex(styles, i)) + '\n'
          + '    ' + sip_mkAttributeString('width', width) + '\n'
          + '    ' + sip_mkAttributeString('height', height) + '\n'
          + '    ' + sip_mkAttributeString('id', cId) + '\n';
    if(!DETECT.is_ie)
      html +=  '    ' + sip_mkAttributeString('data', cUrl) + '\n';
    html +=    '  >\n'
         +     '  <param name="movie" ' + sip_mkAttributeString('value', cUrl) + '/>\n'
         +     '  <param name="wmode" ' + sip_mkAttributeString('value', sip_ceilArrayIndex(wmode, i)) + '/>\n'
         +     '  <param name="bgcolor" ' + sip_mkAttributeString('value', sip_ceilArrayIndex(bgcolor, i)) + '/>\n'
         +     '  <param name="FlashVars" ' + sip_mkAttributeString('value', varString, '') + '/>\n'
         +     '  <param name="base" ' + sip_mkAttributeString('value', baseURL, '') + '/>\n'
         +     '  <param name="quality" value="high"/>\n'
         +     '  <param name="autoStart" value="-1"/>\n'
         +     '  <embed quality="high" \n'
         +     '         type="application/x-shockwave-flash"\n'
         +     '         ' + sip_mkAttributeString('wmode', sip_ceilArrayIndex(wmode, i)) + '\n'
         +     '         ' + sip_mkAttributeString('bgcolor', sip_ceilArrayIndex(bgcolor, i)) + '\n'
         +     '         ' + sip_mkAttributeString('src', cUrl) + '\n'
         +     '         ' + sip_mkAttributeString('style', sip_ceilArrayIndex(styles, i)) + '\n'
         +     '         ' + sip_mkAttributeString('width', width) + '\n'
         +     '         ' + sip_mkAttributeString('height', height) + '\n'
         +     '         ' + sip_mkAttributeString('id', cId) + '\n'
         +     '         ' + sip_mkAttributeString('name', cId) + '\n'
         +     '         ' + sip_mkAttributeString('flashvars', sip_ceilArrayIndex(vars, i), '') + '\n'
         +     '         ' + sip_mkAttributeString('base', baseURL, '') + '\n'
         +     '         pluginspage="http://www.macromedia.com/go/getflashplayer"/>\n'
         +     '</object>\n';
  }

  if(containerID)
  {
    // Replace taget's inner objects (possibly ststic image(s)):
    var container = window.document.getElementById(containerID);
    if(container!=null)
    {
      container.siSwfCtrlStatic = container.innerHTML;

      container.innerHTML='';
      var obj = document.createElement('span');
      obj.style.width='100%';
      obj.style.height='100%';
      obj.innerHTML = html;
      container.appendChild(obj);

      // Yield and test for Flash block:
      setTimeout('sip_testSwfBlocker("' + containerID + '")', 10);
    }
  }
  else
  {
    // Output to document stream:
    document.write(html);       
  }
}




/*
 * sip_testSwfBlocker()
 *   Tests the given container, previously populated with flash content via 
 *   sip_createSwfControl(), for the Flashblocker pattern, that is, absence of 
 *   OBJECT tags. If the Flashblocker has taken control of the container, 
 *   reinstall the default (static) content saved by sip_createSwfControl(). 
 *
 * In:
 *   x
 *
 * Returns
 *   x
 */

function sip_testSwfBlocker(containerID)
{
  var container = window.document.getElementById(containerID);
  if(container!=null)
  {
    if(container.getElementsByTagName('OBJECT').length==0)
      container.innerHTML = container.siSwfCtrlStatic;
  }
}



/*===========================================================================
 *
 * Initialization
 *
 */

/*
 * sip_init()
 *   x
 *
 * In:
 *   x
 *
 * Returns
 *   x
 */

function sip_initMenu()
{
  var menuBar=document.getElementById('toc');
  if(!menuBar)
    return(false);

  // Test for the menu script AND "si_pglayout_b" being loaded:
  if(window.sim_init!=null && window.sip_getCurrentZone!=null)
  {
    // Menu is loaded

    var rc = sim_init();
    if(rc)
    {
      // Menus loaded ok
      if(SIP_GLOBAL.menuPending!=null)
      {
        var links = menuBar.getElementsByTagName('A');
        if(SIP_GLOBAL.menuPending < links.length)
          sim_touch(links[SIP_GLOBAL.menuPending]);
      }
    }
    else
    {
      /* No menus loaded!
       * Restore original menu bar content:
       */
      if(menuBar.si_origHtml!=null)
        menuBar.innerHTML = menuBar.si_origHtml;
    } 
    return(rc);
  }
  else
  {
    /* Menu is not yet loaded!
     * 
     * Save original menu bar content:
     */    
    menuBar.si_origHtml = menuBar.innerHTML;
    
    if(isNativeZone())
    {
      // Install temporary click capture until menu is loaded:
      var links = menuBar.getElementsByTagName('A');
      for(var i=0; i<links.length; i++)
      {
        links[i].sip_pendingIndex = i;
        links[i].onclick=function(){SIP_GLOBAL.menuPending=this.sip_pendingIndex; return false;};
      }
    }
    else
      // Clear menubar as it will be changed when the menu is loaded:
      menuBar.innerHTML = '';
  }
  return(true);
}


/*
 * sip_urchinTracker()
 *   x
 *
 * In:
 *   x
 *
 * Returns
 *   x
 */

function sip_urchinTracker()
{
  if(!sip_isTestServer() && window.urchinTracker!=null)
  {
    _uacct = SIP_CONST.URCHIN_CODE;
    _udn = SIP_CONST.URCHIN_DOMAIN;
    urchinTracker();
  }
}


/*
 * sip_init()
 *   x
 *
 * In:
 *   x
 *
 * Returns
 *   x
 */

function sip_initInline()
{
  //sip_formredirect();
  
  // Assign active Browser detection flags to <body> class name:
  for(var name in DETECT)
  {
    if(DETECT[name]==true)
      window.document.body.className += ' ' + name;
  }

  // Decode e-mail addresses:
  sip_mkMailAddresses();

  // Set up menus (I/II):
  sip_initMenu();
  //t.snap('menus');

  // Fix for browser-specific unsupported features:
  sip_unsupported();
  //t.snap('unsupported');

  // Call document defined scripts:
  if(window.whenDocumentLoaded!=null)
    whenDocumentLoaded();
}


/*
 * sip_init()
 *   x
 *
 * In:
 *   x
 *
 * Returns
 *   x
 */

function sip_initDefered()
{
  // #PRAGMA COMPACT START SKIP
  // Set up debugging:
  sip_debug();
  // #PRAGMA COMPACT END SKIP

  // Decorate the header:
  sip_mkHeader();

  // Set up hover links/images, .pdf-document popup links etc:
  sip_mkActiveLinks();
  //t.snap('links');

  sip_initMiniSearchForm();
  //t.snap('miniSearchForm');
  
  sip_initKeyboard();
  //t.snap('initKeyboard');

  sip_sortingTables();

  // Focus first form field:
  sip_focus();

  // Set up menus (II/II):
  sip_initMenu();

  // Popup optional splash box:
  sip_splashBox();

  // Adjust page to a framed environment:
  if(sip_getSiteTopWindow()!=window)
    sip_framed();
    
  // Urchin tracker:
  sip_urchinTracker();

  // Call document defined scripts:
  if(window.whenDocumentComplete!=null)
    whenDocumentComplete();  
}


/*
 * sip_init()
 *   x
 *
 * In:
 *   x
 *
 * Returns
 *   x
 */

function sip_init(body, isLoaded)
{
  if(window.document.getElementsByTagName==null)
    return;

  if(SIP_GLOBAL==null)
  {
    SIP_GLOBAL = {
      // Current URL and normalized:
      curURL:      sip_stripUrl(window.location.href),
      serverURL:   window.location.protocol + '//' + window.location.hostname + ':' + window.location.port,
      curZone:     null,
      scroller:    window.document.body.parentNode,
      imageCache:  new Array(),
      menuPending: null
    }
  }

  //var t=new TimeProbe();
  if(isLoaded)
    sip_initDefered();
  else
    sip_initInline();
  //t.show();

}

// EoF

