//      ================================
//      ==  go2web_CommonHeaderClient ==
//      ================================

// Author:    DGT
// Date:      07 Nov 2002
// Revision:  1.0

MODIFIED=   "30 Apr 2009 - Remove GO2WEB_TITLE processing for non-framed pages. Left over from frames based sites."
//		"22 Jan 2007 - Add over-rideable onBodyLoadCustom Fn."
//          "20 Jan 2007 - [NM] Add Google search code."
//          "09 Dec 2005 - Make alt CSS sticky using window.name property"
//          "23 Nov 2005 - Add setActiveStyleSheet()"
//          "26 Oct 2005 - Fix full date 1977 -> 3977!"
//           "21 Oct 2005 - Avoid pasreInt bug (leading zeros) sDateOK "
//          "05 Oct 2005 - Add radio button unchecked fn."
//           "13 Jul 2005 - Make Map show/hide Moxilla compatible."
//           "17 Jan 2005 - Add sSetQryParam Fn."
//           "14 Jan 2005 - Call SetQrySelects() in onLoadBody()"
//           "13 Jan 2005 - Add SetQrySelects()"
//           "12 Dec 2003 - [NM] Fix SlideShow"
//            "09 Dec 2003 - oGetById updated[5]."
//            02 Dec 2003 - Add sDateOK fn.
//            25 Sep 2003 - Add HID click to go to URL.
//            12 Feb 2003 - Fix MasterSeg Draft issue.
//            25 Jul 2002 - Add random functions.
//            25 Apr 2002 - Fix rollover error if page load not complete.  Yet Again!!!
//            01 Mar 2002 - Fix ROLO error when no onover event.
//            26 Feb 2002 - Fix for NS4.7 . NOTE: try / catch code inside eval statement to avoid NS4.7 error on page load.
//            28 Nov 2001 - Add element reveal/hide mouse event handlers.
//            27 Nov 2001 - Fix RegExp for Main in URL.
//            26 Nov 2001 - Fix case sensitivity to Main dir. Fix image not loaded yet error.
//            17 Nov 2001 - Second version of preload images.
//            14 Nov 2001 - Fix duoble Site title in Title Bar.
//            12 Nov 2001 - Allow for Rollover Button / Text pair.
//            10 Nov 2001 - Adjust Rolo code - File name and  save.
//            07 Nov 2001 - [DGT] Handle <TITLE> tags without <GO2WEB_TITLE> tags.
//                        - Fixes Title in NoFrames sites.
//                        - Add Rollover image processing

if (document.location.href.toUpperCase().indexOf("/DRAFT_COPY/") != -1)
  bDraft = true
else
  bDraft = false

if ( (self == top) && bDraft)
{
  sPath = document.location.pathname;
  sFile = sPath.substring(sPath.lastIndexOf("/") + 1, sPath.length);
  document.location.href = "HomePage.inc?go2=" + sFile;
}
if (self != top)
{
  re = new RegExp("(<GO2WEB_TITLE>)?([^<]*)(<\\x2FGO2WEB_TITLE>)?", "i");  //[DGT] 07Nov2001
  if (parent.TitleFrame)
  {
    re.exec(parent.TitleFrame.document.title);
    sTFTitle = RegExp.$2;
    re.exec(parent.ContentFrame.document.title);
    sCFTitle = RegExp.$2;
    if (RegExp.$1) // Old pages have <GO2WEB_TITLE Tags and No SiteTitle text
      parent.document.title = sTFTitle + " - " + sCFTitle;
    else
      parent.document.title = sCFTitle;
  }
}


//==== iRandomInRange ============================================
// Return random integer in range specified INCLUSIVE.
function iRandomInRange(iMin, iMax) {
  var fRand = Math.random()
  return Math.round((iMax-iMin) * fRand)+ iMin
}

//==== sRandList ============================================
// Return random selection from text list of items.
// Optional separator (RE OK) as second  param. Default = comma.
function sRandList(sIn) {
  var sSep = ','
  if (sRandList.arguments.length > 1)
    sSep = sRandList.arguments[1]
  var arList = sIn.split(sSep)
  return arList[iRandomInRange(0,arList.length-1)]
}

//==== bDocumentReady ============================================
// Return TRUE if document loadinf complete.
function bDocumentReady() {
    return (document.readyState == 'complete') || (document.readyStateClone == 'complete')
}


//==== ROLLOVER IMAGE HANDLING ============================================================================
// Anchor mouse events pass params to Rolo Fn. Over event passes extra data which is stored in global vars.
// NOTE: Mouse over cursor style and hyperlink URL following must be done manually - see below.
var oRoloSrc
var sRoloID = ''
function Rolo(sState, sImgID, oSrc) {
  if (bDraft) // [DGT] 12Feb2003 disable on Draft page.
    return
  if (!bDocumentReady()) // [DGT] 24Apr2002
    return
  window.focus() // Remove focus (black outline) from image
  var sImgName = (sState == 'Up' ? 'Over' : sState) // Use same image for Up as Over.
  if (Rolo.arguments.length > 1) {
    oRoloSrc = oSrc  // If Image ID passed must be "Over" event so save source object ref.
    sRoloID = sImgID // and IMG tag name for use in other events.
  }
  else
    if (!sRoloID) return // [DGT] 01Mar2002 If no ID set by over event just exit.
  if ( (sState == '') || (sState.match(/Over|Down|Up/)) )
    // If large or many roll-over images to load the one needed may not be loaded yet! [DGT]26Nov2001
    if (bBrowserOK) // Use try / catch if browser capable...
      document[sRoloID].src = eval('try { ar' + sImgName + 'Img[' + document[sRoloID].iImgIndex + '].src} catch (e) {status = "ALERT: Roll-over image not loaded yet!"}')
    else
      document[sRoloID].src = eval('ar' + sImgName + 'Img[' + document[sRoloID].iImgIndex + '].src')
  else
    alert("Rollover image name error: src = " + document[sRoloID].src)
  if ( (sState == 'Up') && (oRoloSrc.href) ) { // If mouse Up & src object has a href
    if ( (!oRoloSrc.target) || (oRoloSrc.target == 'ContentFrame') ) // If no target specified OR CF
      document.location.href = oRoloSrc.href // Must handle hyperlink manually to current window.
    else
      if (oRoloSrc.target == '_top' )
        top.location.href =  oRoloSrc.href
      else
        window.open(oRoloSrc.href, oRoloSrc.target)
  }
}


//==== DYNAMIC ELEMENT REVEAL/HIDE HANDLING ==============================================================
// Handle mouse over and down events to reveal / hide segments of HTML code on the page.
// NOTE: Over & Down suffix to id MUST be lower case for Mozilla! [DGT] 13Jan05
var oShowHideSrc  // Save source control object object ref.
var sLastShowHideoverID   // Save target object id.
var sLastShowHidedownID   // Save target object id.
function ShowHide(oSrc, sRefID) { // Called with NO PARAMS on "Down" event as object ref already saved & state implicit.
  if ( sBrowserStatus != 'OK') {// Do not run code if browser not capable
    if (sBrowserStatus) {
      alert(sBrowserStatus)
      sBrowserStatus = ''
    }
  }
  if (!bBrowserOK) // Do not execute code if browser not capable.
    return
  if (ShowHide.arguments.length > 1) {    // If params passed must be "Over" event else "Down".
    sEvent = 'over'
    sTargetID = sRefID + '_' + sEvent
  }
  else {
    sEvent = 'down'
    sTargetID = sLastShowHideoverID.replace(/_over$/, '_down')
  }
  sOLdTargetID = eval('sLastShowHide' + sEvent + 'ID')
  if (sOLdTargetID) // a previous element already revealed - need to hide it IF EXISTS
    eval('try{document.getElementById(sOLdTargetID).style.display = "none"} catch (e) {;}') // Else NOP
  if (sEvent == 'over') { // Need to save new Last element data
    oShowHideSrc = oSrc
    sLastShowHideoverID = sTargetID // and IMG tag name for use in other events.
  }
  else {
    sLastShowHidedownID = sTargetID
    if (oShowHideSrc.go2URL) {    // [DGT] 25Sep2003 - Add click to navigate option. AREA proterty go2URL is destination.
      document.location.href = oShowHideSrc.go2URL
      return
    }
  }
//  eval('try{document.getElementById(sTargetID).style.display = "block"} catch (e) {status = "No element on page with id = " + sTargetID}')
  eval('try{document.getElementById(sTargetID).style.display = ""} catch (e) {status = "No element on page with id = " + sTargetID}')
}

function is_main()
{
  return !bDraft    // [DGT] Use existing flag.
}

// search feature used on eCommerce/DB sites.
function go2web_search()
{
  var arLocation = location.href.split('/');
  if (is_main())
  {
    if (document.forms['SearchForm'] && document.forms['SearchForm'].eboSearch.value != '')
      document.forms['SearchForm'].submit();
  }
}

function change_background(obj, color)
{
  obj.style.backgroundColor = color;
}

function visit(url)
{
  if (is_main())
    document.location.href = url;
}

function open_window_with_size(url, width, height)
{
  if (is_main())
  {
    var features = 'width=' + width + ',height=' + height;
    window.open(url, '', features);
  }
}

var arDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var arMonths = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

function current_date()
{
  if (is_main())
  {
    var oDate = new Date();
    var sDay = arDays[oDate.getDay()];
    var sMonth = arMonths[oDate.getMonth()];
    document.write(sDay + ', ' + oDate.getDate() + ' ' + sMonth + ' ' + oDate.getFullYear());
  }
}

///////////////////////////////////////////////////////////////////////////////////////////////
// SLIDESHOW                                                                     [NM] 12Dec2003
///////////////////////////////////////////////////////////////////////////////////////////////

var __arImages;        // array of image urls
var __iIndex = 0;      // index of currently displayed image
var __oSlideShow;      // img object
var __iTimerID;        // timer id from window.setInterval

// changeImage - Changes the current images for the next.
//               Go back to the beginning once all images have been displayed.
//               Only use filters if they exists - works fine on any sane browser.
function changeImage()
{
  if (__oSlideShow)
  {
    if (__oSlideShow.filters && __oSlideShow.filters[0]) __oSlideShow.filters[0].Apply();
    __oSlideShow.src = __arImages[__iIndex++];
    if (__oSlideShow.filters && __oSlideShow.filters[0]) __oSlideShow.filters[0].Play();
    if (__iIndex == __arImages.length) __iIndex = 0;

  }
}

// startSlideShow - Creates a slideshow, where an image changes at regular intervals.
//                  This may be called from an onload event for the img object, so any
//                  existing timer must be cancelled before creating a new one. Otherwise
//                  the timers will build up and kill the browser.
//
//   oSlideShow - img object
//   arImages   - array of image urls
//   iInterval  - interval between images in milliseconds
function startSlideshow(oSlideShow, arImages, iInterval)
{
  __oSlideShow = oSlideShow;
  __arImages = arImages;

  if (__iTimerID)
  {
    window.clearInterval(__iTimerID);
    __iTimerID = null;
  }

  if (!bDraft)
  {
    __iTimerID = window.setInterval(changeImage, iInterval);
  }
}



// Return valid date string in form dd Mmmmmm yyyy or "" if invalid.
function sDateOK(sDateIn) {
  sIn = String(sDateIn)
  if (sIn.match(/0?(\d+)\/0?(\d+)\/(\d+)/)){ // [DGT]21Oct05 - avoid parseInt bug pasreInt('09') -> 0 
    iYear = parseInt(RegExp.$3)
    if (iYear < 100) iYear += 2000
    if (parseInt(RegExp.$1) < 1) return ""
    if (parseInt(RegExp.$1) > 31) return ""
    if (parseInt(RegExp.$2) < 1) return ""
    if (parseInt(RegExp.$2) > 12) return ""
    sIn = RegExp.$2 + '/' + RegExp.$1 + '/' + iYear
  }
  if (sIn.match(/(\d+)\s*([a-zA-Z]+)\s*(\d+)/)) {
    iYear = parseInt(RegExp.$3)
    if (iYear < 100) iYear += 2000
    if (parseInt(RegExp.$1) < 1) return ""
    if (parseInt(RegExp.$1) > 31) return ""
    sIn = RegExp.$1 + ' ' + RegExp.$2 + ' ' + iYear
  }
  oD = new Date()
  sOut = oD.setTime(Date.parse(sIn))
  if (sOut)
    return oD.toLocaleString().match(/(.*) \d+:\d+:\d+/)[1]
  return ""
}

// get Element By name IE & Mozilla within any form.
// NOTE: return object ref. or collection ref if more than one!
function oGetInForms(sIn) {
  for (var i=0; i < document.forms.length;i+=1) {
    if (document.forms[i][sIn])
      return document.forms[i][sIn]
  }
}

// getElementById (OR name) IE & Mozilla even within forms if not found outside.
// NOTE: Return object ref. or null - if collection return 1st element or all if bAll set.
function oGetById(sId, bFirst) {
  oRef = document.all
  if (oRef && oRef[sId])
    oRef = oRef[sId]
  else {
    if (document.getElementById) {
      oRef = document.getElementById(sId)
      if (!oRef)
        if (document.getElementsByName && document.getElementsByName(sId)[0])
          oRef = document.getElementsByName(sId)
        else
          oRef = oGetInForms(sId)        
    }
  }
  if (oRef) {
    if (!oRef.tagName)
        oRef = oRef[0]
    if ((oRef.id == sId) || (oRef.name == sId))
      return oRef
  }
}

// Change style: visibility to visible for element id/name specified.
function bShow(sId){
  oTarget = oGetById(sId)
  if (oTarget) {
    oTarget.style.visibility = 'visible'
    return 1
  }
  return 0
}
// Change style: visibility to hidden for element id/name specified.
function bHide(sId){
  oTarget = oGetById(sId)
  if (oTarget) {
    oTarget.style.visibility = 'hidden'
    return 1
  }
  return 0
}
// Return currently selected option object for SELECT element id/named .
// NOTE: If no match return empty Object.
function oSelected(sId) {
  oTarget = oGetById(sId)
  if (oTarget)
    if (String(oTarget.selectedIndex)!= "undefined")
      return oTarget[oTarget.selectedIndex]
  return new Object()
}


//==== SetQrySelects ===========================================================================
// Set any select boxes on page to match query params in URL in found.
// Query name MUST match SELECT element id/name AND value must match element value or text.
// SELECT element may be within FORM element or not.
function SetQrySelects() 
{
    // Default to NOT debug mode. Turned on by presence of SQSDEBUG query param.
    var i, j, bDEBUG = 0, sDEBUG, arNameVal, arParams, arQry, oSelect, sVal;
    
    // Get array of query params...
    arQry = String(document.location).match(/\?.*/);
    if (arQry) 
    {
        arParams = arQry[0].slice(1).split('&');
        // Check for each if from object exists...
        sDEBUG = 'DEBUG\n';
        
        for (i = 0; i < arParams.length; i++)
        {
            arNameVal = arParams[i].split('=');
            if (arNameVal[0] == "SQSDEBUG")
            {
                bDEBUG = 1;
            }
            else 
            {
                oSelect = oGetById(unescape(arNameVal[0]));
                if (oSelect && oSelect.type && oSelect.type.match('select')) 
                {
                    // If object is select check for option match to query value
                    sVal = unescape(arNameVal[1]);
                    for (j=0; j < oSelect.length; j++) 
                    {
                        sDEBUG += 'sVal/name/value/text = ' + sVal + '/' + arNameVal[0] + '/' 
                            + String(oSelect[j].value) + '/' + String(oSelect[j].text) + '\n';
                            
                        if ((oSelect[j].value == sVal) || (oSelect[j].text == sVal)) 
                        {
                            // Match! so set as current selection.
                            oSelect.selectedIndex = j;
                            break;
                        }
                    }
                }
            }
        }
    }
    
    if (bDEBUG)
    {
        alert(sDEBUG);
    }
}


//==== sSetQryParam ============================================================================
// Set the query name and value pair in URL. Note: may already be present with '?' or '&' prefix!
// If Present, just replace value.
// If NOT present, If NO params, add with '?' prefix. Else add with '&' prefix.
// If sNewPage parameter supplied replace page name in URL - NOT extension!
function sSetQryParam(sURL, sName, sValue) {
    if (sSetQryParam.arguments.length > 3)
        sURL = sURL.replace(/([\\\/])[^\\\/.]+\.(asp|htm)($|\?)/i, '$1' + sSetQryParam.arguments[3] + '$3')
    if (!sURL.match(/\?/))
        return sURL + '?' + sName + '=' + sValue
    else {
        var re2 = new RegExp('(.*)([?&]' + sName  + '=)([^&]+)(.*)')        
        if (sURL.match(re2))
            return RegExp.$1 + RegExp.$2 + sValue + RegExp.$4 
        else
            return sURL + '&' + sName + '=' + sValue
    }
}


//==== sRadioUnchecked ============================================================================
// Return name of first radio button set found with NO ITEM CHECKED - empty string of none.
function sRadioUnchecked(oForm) {
    sUnchecked = ""
    oE = oForm.getElementsByTagName('INPUT')    // Check only INPUT elements
    sName = ""
    bChecked = 0
    for (i=0; i < oE.length; i+=1) {
        if (oE[i].type == 'radio') {                        // Only RADIO types
            if (oE[i].name != sName) {                  // Grouped by name - when new name chk last group result
                if (bChecked == 0)
                    if (sName != "") {
                        sUnchecked = sName              // If last group had no checked element name it & abort loop
                        break
                    }
                sName = oE[i].name                      // New group - sert new name
                bChecked = 0
            }
            if (oE[i].checked){                         // If an element is checked set flag for this group
                bChecked = 1
            }
        }
    }
    if ((sName) && (bChecked == 0))         // If last group had no checked element name it.
        sUnchecked = sName
    return sUnchecked
}


//==== Dummy Fn to redefine for onBodyLoad custom code. ==============================================
function onLoadBodyCustom() {
    return
}

//==== OnLoadBody ============================================
// Preload Over & Down images for fast response.
var arImg = new Array()
var arOverImg = new Array()
var arDownImg = new Array()
var sBrowserStatus = ''
var bBrowserOK = false
function onLoadBody() {
  var oNavSelect = oGetById('oNavSelect');
  if (oNavSelect)
  {
    oNavSelect.selectedIndex = 0;
    oNavSelect.blur();
  }

  if (is_main())
  {
    var form0 = document.forms[0];
    if (form0)
    {
      var eboUserName = document.forms[0].eboUserName;
      if (eboUserName)
      {
        eboUserName.focus();
      }
    }
  }

  // Check for browser compatability.
  if (String(document.getElementById) == 'undefined') // Browser INCAPABLE of code below!!
    sBrowserStatus = 'WARNING: This page may not function correctly unless viewed with IE 5.0 / Netscape 6.2 or newer!'
  else {
    sBrowserStatus = 'OK'
    bBrowserOK = true
  }

  if (!bBrowserOK) return;

  var sSiteImagesDir = document.location.href.match(/(.*\/)Main\/[^\/]+\./i) ? RegExp.$1 + 'Images/' : ''  // [DGT] 27Nov2001

  for (var i = 0; i < document.images.length; i++)  // Can't use "for (i in ..."!
  {
    if (document.images[i].name)
    {
      if (String(document.images[i].name).match(/SEG\d_\d/))
      {
        if (document.images[i].src.match(/.*\/([^\/]+)(\.\w+)$/))
        {
          document.images[i].iImgIndex = i
          arImg[i] = new Image()
          arImg[i].src = document.images[i].src // Use already loaded normal image.
          arOverImg[i] = new Image()
          arOverImg[i].src = sSiteImagesDir + RegExp.$1 + '__Over' + RegExp.$2 // Get Over image
          arDownImg[i] = new Image()
          arDownImg[i].src = sSiteImagesDir + RegExp.$1 + '__Down' + RegExp.$2
        }
      }
    }
  }
  // Set ready state variable for Mozilla
  if (!document.readyState)
      document.readyStateClone = "complete"
  //window.status = 'onLoadBody() OK';

  // Sync select boxes with matching query params if exist.
  SetQrySelects()
  
  // Carry alternate style sheet selection with page move if not default - saved in window.name property.
  if (window.name && (String(window.name).substr(0,4) == 'CSS='))
    setActiveStyleSheet(String(window.name).substr(4))
    
  // Call dummy fn which can be over-ridded by custom page code.
  onLoadBodyCustom()  
}

//==== setActiveStyleSheet ============================================================================
// Set the Style Sheet to named alternative. Need more than one and all named!
// NOTE: Alternates MUST be loaded with page like: '<link type="text/css" rel="alternate stylesheet" href="css/admin.css" title="High Visibility" />'
// Default style sheet SiteStyle.css MUST have title="Default". Called oy onBodyLoad to make selection sticky and by link on page to set.
function setActiveStyleSheet(sTitle) {
    var i, oEls, oActive
    oEls = document.getElementsByTagName("link")
    for (i=0; i < oEls.length; i++) {
        if ((oEls[i].getAttribute("rel").indexOf("style") != -1) && oEls[i].getAttribute("title")) {
            if (oEls[i].getAttribute("title") == sTitle) {
                oActive = oEls[i]
                if (sTitle != "Default")    // Save name of style in window.name property if not the default style.
                    window.name = 'CSS=' + sTitle
                else
                    window.name = null  // If default style clear window.name property.
            }
            oEls[i].disabled = true       // If named stylesheet does not exist NO style will apply!
        }                
    }
    if (oActive)
        oActive.disabled = false    
}


function googleSearchBox(id, page, form_style, input_style, button_style)
{
    if (!is_main())
    {
        return;
    }
    
    if (page == null)
    {
        page = 'http://www.go2.ie/home/Main/TestSearch.htm';
    }
    
    if (form_style == null)
    {
        form_style = 'display: inline;';
    }
    
    if (input_style == null)
    {
        input_style = 'width:120px; border: 1px solid #ffffff;';
    }
    
    if (button_style == null)
    {
        button_style = 'font-weight: bold; color: #ffffff; border: 1px solid #6a9130; background-color: #6a9130; cursor: pointer;';
    }
    
    document.write('<form id="searchbox_' + id + '" action="' + page + '" style="' + form_style + '"><input type="hidden" name="cx" value="' + id + '" /><input class="CF-Page-Text" name="q" type="text" style="' + input_style + '" />&nbsp;&nbsp;<input class="CF-Page-Text" type="submit" name="sa" value="Go" style="' + button_style + '" /><input type="hidden" name="cof" value="FORID:11" /></form><sc' + 'ript type="text/javascript" src="http://google.com/coop/cse/brand?form=searchbox_' + escape(id) + '"></sc' + 'ript>');
}

function googleSearchResults(id, width)
{
    if (!is_main())
    {
        return;
    }
    
    document.write('<div id="results_' + id + '"></div><sc' + 'ript type="text/javascript">var googleSearchIframeName = "results_' + id + '"; var googleSearchFormName = "searchbox_' + id + '"; var googleSearchFrameWidth = ' + width + ';  var googleSearchFrameborder = 0; var googleSearchDomain = "google.com"; var googleSearchPath = "/cse";</sc' + 'ript><sc' + 'ript type="text/javascript" src="http://www.google.com/afsonline/show_afs_search.js"></sc' + 'ript>');
}


function altavistaTranslationBox()
{
    if (!is_main())
    {
        return;
    }
    
    document.write('<script language="JavaScript1.2" src="http://www.altavista.com/static/scripts/translate_engl.js"></script>');
}

