// MedlinePlus General Purpose JavaScript Library
//
//Purpose: Central repository for javascript functions for both the MedlinePlus Application
//and Static Site. Functions which are exclusively used by the application belong in dynamic.js
function include(file) {
  var script  = document.createElement('script');
   _proxy_jslib_assign('', script, 'src', '=', ( file));
  script.type = 'text/javascript';
  script.defer = true;

  var node =  _proxy_jslib_handle(document, 'getElementsByTagName', '', 1, 0)('head').item(0);
  node.appendChild(script);
}

//frame breaking script
var notGovSite =  _proxy_jslib_handle(document, 'referrer', '', 0, 0).indexOf('.gov/') < 0;

// Allow www.ala.org and www.zhost.com base on LO's request. 02/28/2008 Ta-Sun
var notalaorg  =  _proxy_jslib_handle(document, 'referrer', '', 0, 0).indexOf('www.ala.org/') < 0;
var notzhostcom=  _proxy_jslib_handle(document, 'referrer', '', 0, 0).indexOf('www.zhost.com/') < 0;

var trackingImg = "http://wwwdev.nlm.nih.gov/results/medlineplus/leavemplus.html?";


// Allow olos.ala.org/goodhealth/ base on LO's request 9/18/2008 Ta-Sun
var notolosalaorg =  _proxy_jslib_handle(document, 'referrer', '', 0, 0).indexOf('olos.ala.org/goodhealth/') < 0;

if ( _proxy_jslib_handle( _proxy_jslib_handle(null, 'top', top, 0, 0), 'location', '', 0, 0) !=  _proxy_jslib_handle(self, 'location', '', 0, 0) &&
    notGovSite &&
    notalaorg &&
    notzhostcom &&
    notolosalaorg) {

   _proxy_jslib_handle( _proxy_jslib_handle(null, 'location', location, 0, 0), 'replace', '', 1, 0)('http://www.nlm.nih.gov/medlineplus/framing.html');
}


buttonStates=new (Object);
if (undefined == imageNames) {
  imageNames = false;
}
if (document.images && imageNames)   {
  for(var button in imageNames)
  {

     _proxy_jslib_assign('', buttonStates, (button+"On"), '=', (  new (Image)()));
     _proxy_jslib_assign('', buttonStates, (button+"Off"), '=', ( new (Image)()));
     _proxy_jslib_assign('',  _proxy_jslib_handle(buttonStates, (button+"On"), 0, 0), 'src', '=', (  imagePath + "/" + button + "_button2" + langExt + ".gif"));
     _proxy_jslib_assign('',  _proxy_jslib_handle(buttonStates, (button+"Off"), 0, 0), 'src', '=', ( imagePath + "/" + button + "_button1" + langExt + ".gif"));

  }

}

function depress(thisImg) {
      if (document.images) {
      //alert(buttonStates[(thisImg + "On")].src);
          imgOn = ( _proxy_jslib_handle( _proxy_jslib_handle(buttonStates, ((thisImg + "On")), 0, 0), 'src', '', 0, 0));
           _proxy_jslib_assign('',  _proxy_jslib_handle(document.imgForm , (thisImg), 0, 0), 'src', '=', ( imgOn));
      }
  }

function unpress(thisImg) {
      if (document.images) {
          imgOff = ( _proxy_jslib_handle( _proxy_jslib_handle(buttonStates, ((thisImg + "Off")), 0, 0), 'src', '', 0, 0));
           _proxy_jslib_assign('',  _proxy_jslib_handle(document.imgForm , (thisImg), 0, 0), 'src', '=', ( imgOff));
      }
  }



var isW3C = ( _proxy_jslib_handle(document, 'getElementById', '', 0, 0)) ? true : false;
var isAll = (document.all) ? true : false;
var isOperaMac = (navigator.userAgent.indexOf('Opera') != -1 && navigator.platform.indexOf('MacPPC') != -1 ) ? true : false;
var HSCALE=0.9; //default percentage to scale popup windows horizontally
var VSCALE=0.9; //default percentage to scale popup windows vertically

//
//function centeredPopup(url, name, noChrome, width, height)
//Description: Replacement for three previous js functions opens a named popup window
//  url - string, required, relative or full url to the html which will populate the new window
//  name - string, optional, the name of this new popup window - default="theNewWin"
//  noChrome - boolean, optional, the newly created window will have all or no features - default="false"
//  width - number/int, optional, the width of the desired popup - default=percentage (based on const HSCALE) of parent window width
//  height - number/int, optional, the height of the desired popup - default=none, allow the client system to manage the height of the popup
//Usage:
//<a href="myurl.server.gov/mypage.html" onclick="return centeredPopup(this.href, myWindow, false, 640, 480);" target="_BLANK">Click</a>
//
function centeredPopup(url, name, noChrome, width, height) {
  var features;
  var popupDimensions=defaultPopupDims(); //obj holds the default popuDimensions, based on Parent Window

  //availheight and width mostly for Opera interoperability
  var myAvailWidth=getAvailWidth();
  var myAvailHeight=getAvailHeight();

  if( url )
  {
    //handle calls using the old Mplus popup window javascript
    if(url=="#")
    {
      url='';
    }

    if(!name)
    {
      name="TheNewWin";
    }

    //ensure width bounds checking, if it doesn't have a value, give it the default
    if( isNaN(width) )
    {
      width=popupDimensions.width;
    }

    if(width > myAvailWidth || width < 0)
    {
      width=parseInt(myAvailWidth * HSCALE);
    }

    //check whether this will be a chromeless window
    if( noChrome == true
 || noChrome == "true"
 || noChrome == "True"
 )
    {
      if (-1==name.indexOf("insidermedicine")) {
        features='toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=' + width + ',';
      }
      else {
        features='toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=' + width + ',';
      }
    }
    else
    {
      features='toolbar=yes,location=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes,width=' + width+ ',';
    }

    //if height wasn't defined get default
    //note: default height for IE will be 0, IE doesn't give us sufficient info
    //to calculate parent window dimensions
    if(!height)
    {
      height=popupDimensions.height;
      //alert(height);
    }

    //check the height attrib, ensure it doesn't exceed viewable real estate
    //if so, the reduce it to VSCALE set by script designer.
    if(height > myAvailHeight || height < 1)
    {
      height=parseInt(myAvailHeight * VSCALE -100)
 }
    else
    {
      //Opera 6.x Macintosh PPC requires a height value when rendering a new window (if you specify width)
      if( isOperaMac )
      {
        //alert("detected Macintosh Opera!");
        height=parseInt(myAvailHeight *VSCALE);
      }
    }


    features+='height='+height+',';
    features += getCenteredCoords(myAvailWidth,myAvailHeight,width,height);
    //alert("Features: " + features);

    popUpWin =  _proxy_jslib_handle(window, 'open', '', 1, 0)(url, name, features);

    if( window.focus && !isOperaMac)
    {
      popUpWin.focus();
    }
    return false;
  }
  return true;
}

//workaround for Opera in MDI mode, must calc the "real" availWidth.
function getAvailWidth() {
  var myWidth=screen.availWidth;

  if(self.screenX && self.screenLeft && (self.screenX != self.screenLeft) )
  {
    myWidth = myWidth - self.screenLeft + self.screenX;
  }

  return myWidth;
}

function getAvailHeight() {
  var myHeight=screen.availHeight;

  if(self.screenY && self.screenTop && (self.screenY != self.screenTop) )
  {
    myHeight = myHeight - (self.screenTop - self.screenY);
  }
  //alert("myHeight: " + myHeight);
  return myHeight;
}



function getCenteredCoords(myAvailWidth, myAvailHeight, width, height) {
  var coords="";
  var top, left;

  if(width)
  {
    left=parseInt(.5 * (myAvailWidth - width) );
    if(left < 0)
      left=0;
    coords+='left='+left+',screenX='+left;

    //calculate the centered position for height only if we have a value for it
    if(height)
    {

       top= _proxy_jslib_assign_rval('', 'top', '=', (parseInt(0.5* (myAvailHeight - height) - 50)), top);
      if( _proxy_jslib_handle(null, 'top', top, 0, 0) < 0)
         top= _proxy_jslib_assign_rval('', 'top', '=', (0), top);
      coords += ',top='+ _proxy_jslib_handle(null, 'top', top, 0, 0)+',screenY='+ _proxy_jslib_handle(null, 'top', top, 0, 0);
    }

    //alert("Coordinates: " + coords);
    return coords;
  }
  return;
}

//function defaultPopupDims()
//Description: Helper Function for centeredPopup(), called when user doesn't specify
//  a width and height for the new window.
//In: Nothing
//Out: dimensions in object form obj.width=width, obj.height=height

function defaultPopupDims() {
  //first set an absolute fallback value, in case the object sniffing breaks due to weird
  //browsers
  var dims = new (Object)();
  dims.width = 700;
  dims.height = 700;

  //work out the width and height of Netscape 4.x, Mozilla, & Opera 7.x Browser
  if( !isNaN( window.innerWidth) && window.innerWidth > 0 )
  {
      //Non-IE browsers e.g. Netscape, Opera, Safari, etc.
      dims.width = parseInt(window.innerWidth * HSCALE);
      dims.height = parseInt(window.innerHeight * VSCALE);
      //alert('for netscape 4 mozilla and opera');
  }
  else
  {
    if( document.documentElement && document.documentElement.offsetWidth )
    {
      //IE 6+, and any IE Compatible Browsers that supports the documentElement properties
      dims.width = parseInt(document.documentElement.offsetWidth * HSCALE);
      dims.height = parseInt(document.documentElement.offsetHeight * VSCALE);
      //alert('for ie 6+ and any ie compatible browser support documentelement properties');

    }
    else
    {
      if(  _proxy_jslib_handle(document, 'body', '', 0, 0) &&  _proxy_jslib_handle(document, 'body', '', 0, 0).offsetWidth)
      {
        //IE 4 and above compatible
        dims.width = parseInt( _proxy_jslib_handle(document, 'body', '', 0, 0).offsetWidth * HSCALE);
        dims.height = parseInt( _proxy_jslib_handle(document, 'body', '', 0, 0).offsetHeight * VSCALE);
        //alert('ie 4 and above ');

      }
    }
  }

  if (dims.width == undefined || dims.height == undefined ||
      isNaN(dims.width) || isNaN(dims.height))
  {
    dims.width = 700;
    dims.height = 700;
    //alert('dims.width is '+dims.width+'  dims.height is '+dims.height);
  }

  return dims;
}


//these functions are deprecated, they are here to ensure nothing breaks during the transition
//after all instances have been removed in the code, they will be removed.
function openOutWin(url) {
  //
  if(!url)
    url='#';
  centeredPopup(url, 'TheNewWin');
  return true;

}

function openNewWin(windowName) {
    centeredPopup('#', windowName);
  return true;
}

function openNamedOutWin(url, name) {
    centeredPopup(url,name, true, 750);
}

function openNakedWin(windowName) {
  centeredPopup('#', windowName, true);
  return true;
}

function orLivePopup(url) {
  centeredPopup(url, "orLive", true, 780, 460);
  return true;
}

function insiderPopup(url) {
  centeredPopup(url, "insidermedicine", true, 840, 520);
  return true;
}

//end deprecated functions

function isEmpty(inputStr) {
    for(var i=0; i<inputStr.length; i++) {
        oneChar = inputStr.charAt(i);
        if ((oneChar != ' ') && (oneChar != '\n') && (oneChar !='\t') && (oneChar != '\r'))
            return false;
    }
    return true;
}
function isNetscape() {
    if (navigator.appName == 'Netscape')
        return true;
    else
        return false;
}


function tempPop(url) {
  var theight=parseInt(screen.availHeight * 0.65);
  var tfeature="toolbar=yes,location=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes,width=900,height="+ theight + ",left=75";
  var name="myName";
  var popUpWin =  _proxy_jslib_handle(window, 'open', '', 1, 0)(url, name, tfeature);
}


//this is copied from a the feedback.pl cgi
function checkFeedback(myForm) {
    //errMsg depends on the language context this form has been called in.
    var errMsg="$textLang->{errMsg}";
    if( _proxy_jslib_handle(myForm.subject, 'value', '', 0, 0) != "" &&  _proxy_jslib_handle(myForm.message2, 'value', '', 0, 0) != "")
    {
        //The user has filled out the required fields, continue submission.

        //if a state has been selected, deselect the country
        if ( myForm.state[0].selected == false )
        {
            myForm.country[0].selected = true;
        }
        //now we return true to allow the form submission
        return true;
    }
    else
    {
        //user forgot to fill in one of the required fields
        alert(errMsg);
        //cancel submit
        return false;
    }
}

image1 = new (Image)(); image2 = new (Image)(); image3 = new (Image)(); image4 = new (Image)(); image5 = new (Image)(); image6 = new (Image)(); image7 = new (Image)();


//cit script for opening a popup window for a videocast
function iwin(_url,_w,_h) {
     _proxy_jslib_handle(window, 'open', '', 1, 0)(_url,"_accordent","width="+ _w +",height="+ _h +",resizable=no,scrollbars=no,status=yes",true);
}

//use for the goLocal Box on Mplus topic pages, merely decides whether or not to open the FoLocal Url in a popup or not.

function goLocalPage(url) {
  if(url)
  {
    //if the site is hosted, go there else pop open window
    if (url.indexOf('nlm.nih.gov') > 0)
       _proxy_jslib_assign('',  _proxy_jslib_handle(null, 'location', location, 0, 0), 'href', '=', (url));
    else
      {
        openOutWin(url);
      }
  }
  return false;
}


function AddListDividers(container_id,interval) {

  if( _proxy_jslib_handle(document, 'getElementById', '', 0, 0)) {

    var container =  _proxy_jslib_handle(document, 'getElementById', '', 1, 0)(container_id);
    var listitems =  _proxy_jslib_handle(container, 'getElementsByTagName', '', 1, 0)("li");

    var adjusteditems = new (Array)(listitems.length);

    for(var i=0; i<listitems.length;i++) {
       _proxy_jslib_assign('', adjusteditems, (i+1), '=', (  _proxy_jslib_handle(listitems, (i), 0, 0)));
    }

    for(var i=1; i<listitems.length;i++) {
      if((i % interval) == 0) {
         _proxy_jslib_handle(adjusteditems, (i), 0, 0).className='divider';
      }
    }

  }

}



function LoopAlphaListsForDividers(prefix,interval) {

  if( _proxy_jslib_handle(document, 'getElementById', '', 0, 0)) {

    var alphabet = new (Array)('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');

    for(i=0;i<alphabet.length;i++) {
      var element_id = (prefix +  _proxy_jslib_handle(alphabet, (i), 0, 0));
      var element =  _proxy_jslib_handle(document, 'getElementById', '', 1, 0)(element_id);

      if(element) {
        AddListDividers(element_id,interval);
      }
    }
  }
}


  function getElementsByClass(searchClass,node,tag) {
  var classElements = new (Array)();
  if ( node == null )
    node = document;
  if ( tag == null )
    tag = '*';
  var els =  _proxy_jslib_handle(node, 'getElementsByTagName', '', 1, 0)(tag);
  var elsLen = els.length;
  var pattern = new (RegExp)("(^|\s)"+searchClass+"(\s|$)");
  for (i = 0, j = 0; i < elsLen; i++) {
    if ( pattern.test( _proxy_jslib_handle(els, (i), 0, 0).className) ) {
       _proxy_jslib_assign('', classElements, (j), '=', (  _proxy_jslib_handle(els, (i), 0, 0)));
      j++;
    }
  }
  return classElements;
}

  // this function is needed to work around
  // a bug in IE related to element attributes
  function hasClass(obj) {
     var result = false;
     if (obj.getAttributeNode("class") != null) {
         result =  _proxy_jslib_handle(obj.getAttributeNode("class"), 'value', '', 0, 0);
     }
     return result;
  }

//function listSpacing()
//Purpose: given the ID of an HTML list, will loop through list items
//  and add the the class "listSpace" every nth list element where n=frequency
//  this eliminates the need for adding the HTML directly to the page (problematic in XSLT)
//  or adding additional HTML markup
//Usage: <body onload="listSpacing('myList', 5);">
//Arguments:
//  - String: name of the ID of the list that is to be modified
//  - Integer: frequency of the spacing (Optional)
 function listSpacing(listID, frequency) {
  var list= _proxy_jslib_handle(document, 'getElementById', '', 1, 0)(listID).childNodes;  //list is now equal to the array of child nodes
  var listNodeCounter=1;
  if(! isDefined(frequency)){
    frequency=5;
  }
  for (var h = 0; h < list.length; h++) {
    if( _proxy_jslib_handle(list, (h), 0, 0).nodeType ==1){             //ensure the child node is an actual element, not whitespace or text
      if(listNodeCounter % frequency == 0){
         _proxy_jslib_handle(list, (h), 0, 0).className="listSpace";
      }
      listNodeCounter = listNodeCounter +1;
    }

  }
  return;
}

//library function to mimic the isDefined functionality of higher level languages
// returns true if variable passed is defined, false otherwise
function isDefined(testArgument) {
  if(typeof testArgument == 'undefined'){
    return false;
  }
   return true;
 }

//Created for printing flash movie scrollable text area contents. Using fscommand to pass flash contents to new window.-- Jeff Bao
function windowPrint(args) {
   var myAvailWidth=getAvailWidth();
   var myAvailHeight=getAvailHeight();
   var features;
   var msgWindow;
   var csspath='<LINK REL="STYLESHEET" HREF="'+imagePath+'/stylesheet.css" TYPE="text/css">';
   var popupDimensions=defaultPopupDims(); //obj holds the default popuDimensions, based on Parent Window
   height=popupDimensions.height;
   width=popupDimensions.width;
   features='toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=' + width + ',height=' + height;
   features += getCenteredCoords(myAvailWidth,myAvailHeight,width,height);
   msgWindow= _proxy_jslib_handle(window, 'open', '', 1, 0)("","PrintWindow",features)
  _proxy_jslib_handle(msgWindow.document, 'open', '', 1, 0)()
  _proxy_jslib_handle(msgWindow.document, 'write', '', 1, 0)("<head><title>MedlinePlus Print Message Window<\/title><\/head>")
  _proxy_jslib_handle(msgWindow.document, 'write', '', 1, 0)(csspath+args)
  _proxy_jslib_handle(msgWindow.document, 'close', '', 1, 0)()
 msgWindow.focus()
}
function leavemplus(param1, param2) {
    var img = document.createElement("img");
     _proxy_jslib_handle(img, 'setAttribute', '', 1, 0)("src",trackingImg + param1);
    //alert(trackingImg + param1);
}

include('http://www.nlm.nih.gov/medlineplus/images/trace.js');
 ;
_proxy_jslib_flush_write_buffers() ;