//
// Browser vars.
//
var ie = (document.all) ? true : false; 
var ie5 = (ie) && (navigator.userAgent.indexOf('MSIE 5') > 0);
var nav4 =  (document.layers) ? true : false;
var nav6 = ((document.getElementById) && (!ie )) ? true : false; 
var nav = nav4 || nav6;
var iemac = navigator.appVersion.indexOf("Mac") > 0 ? true : false;

//
// Table selection variables.
//
var currSelection;

var cbdJsErrCook = "jsCBDshowErr";
var errCnt = 0;
var errLimit = 12;
var onerrorSet = false;
var initExGlobs = false;
var printDialogOpened = false;

//
// Returns a boolean indicating whether Adobe Acrobat Reader is installed.
//
function jsCBDisAdobeInstalled()
{
   if ( ie && !iemac)
   {
      //
      //  Call a VBScript function to do the check.
      //
      return checkAdobeIE();
   }
   else if(nav) 
   {
      return  navigator.mimeTypes != null &&
              navigator.mimeTypes["application/pdf"] != null;
   }
   else
   {  // IE on MAC or something else
      return true;
   }
}


function jsCBDinitGlobals () {
   if (initExGlobs) {
      return;
   }
   initExGlobs = true;

     // popup window names for popup levels 1-n
   CBD_MODAL_POP1 = "cbdModalWin1";
   CBD_MODAL_POP2 = "cbdModalWin2";
   CBD_MODAL_POP3 = "cbdModalWin3";
   CBD_MODAL_POP4 = "cbdModalWin4";
   CBD_MODAL_POP5 = "cbdModalWin5";
   CBD_MODAL_POP_PRINT = "cbdModalPrintWin";
   CBD_MODAL_POP = "cbdModalWin";

   stdWinDim = new Array( 
     782, 430,
     350, 200,
     500, 200,
     500, 400,
     400, 430,
     625, 350,
     550, 430,
     625, 430,
     500, 300,
     300, 400,
     609, 430,
     766, 430,
     625, 500 );

   //
   // Standard pop up dimensions used by jsCBDopenStdWin().
   //
   POPUP_SIZE1 = 0;
   POPUP_SIZE2 = 2;
   POPUP_SIZE3 = 4;
   POPUP_SIZE4 = 6;
   POPUP_SIZE5 = 8;
   POPUP_SIZE6 = 10;
   POPUP_SIZE7 = 12;
   POPUP_SIZE8 = 14;
   POPUP_SIZE9 = 16;
   POPUP_SIZE10 = 18;
   POPUP_SIZE11 = 20;
   POPUP_SIZE12 = 22;
   POPUP_SIZE13 = 24;

   CBD_PRINT_PARM = "cbdPrint";
   CBD_PRINT_DELAY = "CBDPRINTDELAY";
   CBD_PRINT_DELAY_TIME = "1500";

   //document.domain = "vanguard.com";

}

jsCBDinitGlobals(); // run init function while loading, which works in Net6 whereas inline constants don't


// validate the size of the popup
function jsCBDValidatePopupSize(size)
{
   if ( size < POPUP_SIZE1 || 
        size > POPUP_SIZE13 || 
        size % 2 != 0 )
   {
      return POPUP_SIZE1;
   }
   else
      return size;
}

function jsCBDopenWin(url, winName, scrol, resize, width, height)
{
var winl = (screen.width - width) / 2;
var wint = (screen.height - height) / 2;
var isBrowser = jsCBDopenWin.arguments[6]; //optional 3rd Party Browser window
var cbdWindow = top.window;

if(winName.indexOf(CBD_MODAL_POP) >= 0)
{
if(cbdWindow.name.indexOf(CBD_MODAL_POP) >= 0)
{
winName = cbdWindow.name.substring(0, cbdWindow.name.length-1) + (parseInt(cbdWindow.name.substring(cbdWindow.name.length-1, cbdWindow.name.length)) + 1);
}
else
{
winName = CBD_MODAL_POP1;
}
}

if( width == stdWinDim[POPUP_SIZE1] && height == stdWinDim[POPUP_SIZE1 + 1] )
{
winl = 0;
wint = 0;
}
if (nav4) {
scrol = "yes";
}
if (isBrowser) {
strpara = "toolbar, scrollbars=" + scrol + ",resizable=" + resize + ",width=" + width + ",height=" + height + ",top=" + wint + ",left=" + winl;
}
else {
strpara = "scrollbars=" + scrol + ",resizable=" + resize + ",width=" + width + ",height=" + height + ",top=" + wint + ",left=" + winl;
}
var newWindow = window.open(url, winName, strpara);
if (winName.indexOf(CBD_MODAL_POP) == 0 || winName == CBD_MODAL_POP_PRINT) {
top.document.modalPopup = newWindow;
top.document.modalPopupName = winName;
}
}

//
// Opens a standard size window.
// All possible sizes are listed at 
// http://dvictory0.vanguard.com:21111/Creative_Services/HNWdesign_spec/popup.html
//
// The size argument must be in the range:
// POPUP_SIZE1, POPUP_SIZE2,........., POPUP_SIZE12
// where the ending digits match the numbers from the above popup.html page.
//
function jsCBDopenStdWin(url, windowName, scrol, resize, size )
{
   size = jsCBDValidatePopupSize(size);
   window.popSize = size;
   var isBrowser = jsCBDopenStdWin.arguments[5];  // optional 3rd Party Browser window
   if (isBrowser) {
      jsCBDopenWin( url, windowName, scrol, resize, stdWinDim[size], stdWinDim[size+1], true );
   }
   else {
      jsCBDopenWin( url, windowName, scrol, resize, stdWinDim[size], stdWinDim[size+1] );
   }
}
//
// Opens a standard size browser window.
// All possible sizes are listed at 
// http://dvictory0.vanguard.com:21111/Creative_Services/HNWdesign_spec/popup.html
//
// The size argument must be in the range:
// POPUP_SIZE1, POPUP_SIZE2,........., POPUP_SIZE10
// where the ending digits match the numbers from the above popup.html page.
//
function jsCBDopenBrowser(url, windowName, size )
{
   size = jsCBDValidatePopupSize(size);
   window.popSize = size;
   // Center popup by subtracting popup width and height 
   // from total screen width and height then divide by 2

   var width = stdWinDim[size];
   var height = stdWinDim[size+1];
   var winl = (screen.width - width) / 2;
   var wint = (screen.height - height) / 2;
   var strpara = "scrollbars,toolbar,resizable,directories,menubar,location,status,copyhistory,width=" + width  + ",height=" + height + ",top=" + wint + ",left=" + winl;
   var newWindow = window.open(url, windowName, strpara);
   
}

//
// Resizes the window based on the passed size constant.
//
function jsCBDresizeTo( size )
{
   size = jsCBDValidatePopupSize(size);
   window.resizeTo( stdWinDim[size] + 10, stdWinDim[size+1] + 29)
}

//
// Returns the size of the popup window, when called from that window.
// Will only work, if jsCBDopenStdWin() was used to pop it up.
//
function jsCBDgetPopupSize()
{
   return opener.popSize;
}

//
// Selects or deselects the specified table row.
// When selected, the row's color changes to blue.
// When deselected, it reverts back to white.
//
function selectRow( obj )
{
   //
   // deselect the previously selected row.
   //
   if ( currSelection != null && currSelection != obj )
   {
      selectRow( currSelection );
   }

   if( obj.selected == true  ) 
   {
      setBgc(obj, obj.oldColor );
      obj.selected = false;
      currSelection = null;
   }
   else
   {
      obj.oldColor = getBgc( obj );
      setBgc(obj, "#99CCFF");  
      obj.selected = true;
      currSelection = obj;
   }
}

//
// Sets object's bgcolor.
//
function setBgc( obj, color )
{
   if ( ie )
   {
      obj.style.backgroundColor = color;
   }
   else
   {
      obj.bgColor = color;
   }
}


//
// Gets object's bgcolor.
//
function getBgc( obj )
{
   return ( ie ? obj.style.backgroundColor : obj.bgColor );
}


//
// Flips the visibility of the passed elements.
//	Takes any number of elements' names as its argument.
//
function jsCBDshowHideLayers()
{
	var i; 
	var args = jsCBDshowHideLayers.arguments; //function's args

	for ( i = 0; i < args.length - 1; i += 2 ) 
	{
      if ( args[i] != null )
      {
		document.getElementById(args[i]).style.visibility = ( args[i+1] ) ? 'visible' : 'hidden';
      } 
	}
}


//
// get cookie
//
function jsCBDgetCookie (name) {
   var result = null;
   var myCook = " " + document.cookie+ ";";
   var search = " " + name + "=";
   var start = myCook.indexOf(search);
   var end;
   if (start != -1) {
      start += search.length;  // skip past name
      end = myCook.indexOf(";", start);
      result = unescape (myCook.substring(start, end));
   }
   return result;
}

//
// set cookie
//
function jsCBDsetCookie (name, value, expires, path, domain) {
   var expStr = ((expires == null) ? "" : ("; expires=" + expires.toGMTString()));
   var pathStr = ((path == null) ? "" : ("; path=" + path));
   var domainStr = ((domain == null) ? "" : ("; domain=" + domain));
   document.cookie = name + "=" + escape(value) + expStr + pathStr + domainStr;
}

//
// delete cookie
//
function jsCBDdelCookie (name, path, domain) {
   var TwoDays = 2 * 24 * 60 * 60 * 1000;
   var expDate = new Date();
   expDate.setTime(expDate.getTime() - TwoDays);
   jsCBDsetCookie (name, "", expDate, path, domain); 

}

//
// Cookie debugging
//
function jsCBDdumpCookies (name) {
   alert ("server cookies: " + document.cookie);
   if (name != null) {
      alert (name + " cookie value: " + jsCBDgetCookie (name));
   }
}


//
// Enable the optional onerror event callback function
//
function jsCBDshowErrors () {
   var SixMonth = 180 * 24 * 60 * 60 * 1000;
   var expDate = new Date();
   expDate.setTime(expDate.getTime() + SixMonth);
   jsCBDsetCookie (cbdJsErrCook, "1", expDate, "/", null);
   alert ("Error reporting enabled");
}
function jscbdshowerrors () {
   jsCBDshowErrors();
}

//
// Disable the optional onerror event callback function
//
function jsCBDhideErrors () {
   jsCBDdelCookie (cbdJsErrCook, "/", null);
   alert ("Error reporting disabled");
}
function jscbdhideerrors() {
   jsCBDhideErrors();
}

//
// Optional onerror event callback, enabled via the showErrors() function
//
function reportScriptError (msg, url, lineNum) {
   if (++errCnt <= errLimit) {
      alert ("      *** Javascript Error ***\n\nError: " + msg + 
             "\nLine number: " + lineNum + "\nURL: " + url + 
             "\n\nErrors detected: " + errCnt);
   }
   if (errCnt >= errLimit) {
      alert ("Too many Javascript errors (" + errLimit + ").  Further errors will not be reported.");
      window.onerror = null;
   }
}

//
// Set the onerror callback function to our reporting function
//
function setOnerror () {
   if (onerrorSet == false) {
      if (jsCBDgetCookie (cbdJsErrCook) != null) {
         window.onerror = reportScriptError;
      }
      else {
         window.onerror = null;
      }
      onerrorSet = true;
   }
}

//
// Get window's modal popup
//
function getModalPopup() {
  popup = null;
  
  if (top.document.modalPopup && 
      ! top.document.modalPopup.closed) {
    popup = top.document.modalPopup;
  }
  return popup;
}

//
// Close modal popup
//
// Pages using modal popups should call this function to close all modal popups.  Although this
// function is minimal now, it may take on added functionality later, so developers should
// use this function rather than window.close()
//
function jsCBDcloseModalPop () {
  if (top) {
     top.close();
  }
  else {
    window.close();  // note - must be called after opener focus or the popup doesn't close in Netsc6
  }
}

//
// Set focus to modal popup
//
function focusOnModalPop (popupRef) {
  if (popupRef && ! popupRef.closed) {
    popupRef.focus();
  }
}

//
// Callback function that should be used for various window events in a parent window
// that can have modal popup windows
function jsCBDdoModalCB () {
  jsCBDinitGlobals();  // just in case wasn't called during page load
  setOnerror();

  popupRef = getModalPopup ();
  if (popupRef && popupRef != null && ! popupRef.closed ) {
    setTimeout ("focusOnModalPop (popupRef)", 100);  // focus works better after slight delay 
    //popupRef.focus();  // commented out for now - causes error in IE 5 during popup closing
  }

  return true;
}

//
// Callback function that should be used on the unload event in a parent window
// that can have modal popup windows
//
function jsCBDunloadCB () {
   popup = getModalPopup ();
   if (popup != null && ! popup.closed) {
      popup.close();
   }

   return true;
}

//
// Event handler for printing the current page
//
// Two optional parameters may be specified: delayMultiplier and/or urlParameter
//
function jsCBDprintCB() {
   var printPageURL;
   var poundPos;
   var timeDelay = 1; 
   var docUrl = document.URL;                /*document.URL*/
   var isFirstNum = false;    /*if first parameter is a number then it is the timeDelay*/
   var argLen = jsCBDprintCB.arguments.length;  /*number of arguments*/
   var arg1 = jsCBDprintCB.arguments[0];     /*first argument if any*/
   var arg2 = jsCBDprintCB.arguments[1];     /*second argument if any*/

   //Get rid of hostname to make path relative 
   // start the substring at the 9th position to skip over https://
   docUrl = jsCBDstripServerName(docUrl);
   
   if (argLen > 0) {
      /*parameters passed in*/
      isFirstNum = isInteger(arg1); /*check if first parameter is timeDelay*/
      if (isFirstNum && (argLen == 1)) { /*only param is timeDelay*/
          timeDelay = parseInt(arg1,10);
      }
      else if (argLen==1) {             /*only param is url*/
         docUrl = arg1;
         
      }
      else if (isFirstNum && (argLen == 2)) {
         /*first param is timeDelay, second is url*/
         timeDelay = parseInt(arg1,10);
         docUrl = arg2;
      }
      else {
         /*first param is url second is timeDelay*/
         docUrl = arg1;
         timeDelay = parseInt(arg2,10);
      } 

   }


   poundPos = docUrl.indexOf( "#");
  
   if ( poundPos != -1 ) {
      //
      // Strip the anchor part, which interferes with printing.
      //
      printPageURL = docUrl.substring( 0, poundPos );

      var addlArgPos = docUrl.indexOf( "&", poundPos+1 );

      if ( addlArgPos != -1 ) {
         printPageURL += docUrl.substring( addlArgPos+1 );
      }
   }
   else
   {
      //
      // Leave as is
      //
      printPageURL = docUrl;
   }

   if (docUrl.indexOf("?") != -1) {
      printPageURL += "&" + CBD_PRINT_PARM + "=1";
   }
   else {
      printPageURL += "?" + CBD_PRINT_PARM + "=1";
   }

   if (timeDelay > 1) {
      timeDelay = (timeDelay * parseInt(CBD_PRINT_DELAY_TIME,10));
      printPageURL += "&" + CBD_PRINT_DELAY + "=" + timeDelay.toString();
   }
   
   jsCBDopenWin(printPageURL, CBD_MODAL_POP_PRINT, true, true, 125, 100);
} 
//
// To print the page
//
function jsCBDPrintPage () {
   var delay;
   window.print();
   delay = jsCBDgetQueryValue(CBD_PRINT_DELAY);
   if (delay == "") {
      delay = CBD_PRINT_DELAY_TIME;      /*default value if not specified*/
   }
   else {
      delay = parseInt(delay,10);    /*convert the string value to a number*/
   }
   timeoutId = setTimeout( 'window.close()', delay );
}
//
// When a user hits the browser back button, View Controls and Pulldowns are
// not always displaying the correct value in the Selection List.
// What is odd about this is that if you do a "View Source", the HTML
// is correct but is still not displaying properly.  This function is the fix. 
//
function jsCBDrestoreSelectionList( aSelectionList )
{
	var flag = false;

	for( var i = 0; i < aSelectionList.length; i++ )
	{
		//
		// if the option in the list is selected then set
		// its selection state to true
		//
		if( aSelectionList.options[ i ].defaultSelected == true )
		{
			aSelectionList.options[ i ].selected = true;
			flag = true;
		}
	}

	//
	// if nothing was selected then default to the first item
	//
	if( flag == false )
	{
		aSelectionList.options[ 0 ].selected = true;
	}

	return;
}

//
// When a user hits the browser back button, View Controls and Pulldowns are
// not always displaying the correct value in the Selection List.
// This seems to only happen when the View Control/Pulldown is on a Form that
// submits to the same page... What is odd about this is that if you do 
// a "View Source", the HTML is correct but is still not displaying properly. 
// In order to fix this, we need to call jsCBDrestoreSelectionList() on each 
// View Control/Pulldown on the page. This function loops through all the forms and for 
// each form that contains a Selction List, it calls jsCBDrestoreSelectionList().
//
function jsCBDrestoreAllSelectionLists()
{
	//
	// loop through each form on the page searching for a view control/pulldown
	//
	numForms = document.forms.length;
	for( i = 0; i != numForms; i++ )
	{
		form = document.forms[ i ];
		numFormElements = form.elements.length;
		//
		// for each form, loop through each element looking for
		// a pulldown or view control
		//
		for( j = 0; j != numFormElements; j++ )
		{
			//
			// when found, call jsCBDrestoreSelectionList()
			//
			if( form.elements[ j ].type == "select-one" )
			{
				jsCBDrestoreSelectionList( form.elements[ j ] );
			}
		}
	}
	return;
}

// 
// Reads the query string for the attribute specified and 
// returns its value
//
function jsCBDgetQueryValue(attribute) {
   var myQstr;                /* query string*/
   var value = "";            /*return value*/
   var myArray = new Array(); /*array of attribute values in query string*/
   var attVal = new Array();  /*two(2) element array with attribute[0] and its value[1]*/
   var i;
  
   myQstr = new String(location.search.substring(1));
   myArray = myQstr.split("&"); /*split string delimited by "&" into array rows*/
     
   for (i=0; i < myArray.length; i++ ) {
      /*split string delimited by "=" [0] is attribute, [1] is its value*/

      attVal = myArray[i].split("=");   
        
      if (attVal[0].toUpperCase() == attribute.toUpperCase()) {
         value = attVal[1];   /*grab the attributes value*/
         break;
      }
   }

   return value;

}


//
// Closes all popups and returns the main browser window
//
function jsCBDcloseAllModalPop() {
   /*first popup opened....close this and all popups close*/
   var first_popup = jsCBDgetFirstPopup(); /*start with current popup*/
   var parent_popup = first_popup.opener;             /*get who opened me*/
     
   first_popup.jsCBDcloseModalPop();
   
   return parent_popup;
}
function jsCBDgetFirstPopup() {
   /*first popup opened*/
   var first_popup = window;              /*start with current popup*/
   var parent_popup = opener;             /*get who opened me*/
     
   while (parent_popup.opener != null) {  /*if my parent does not have a parent then I am first*/
      first_popup = parent_popup;         /*first popup is my parent...who also has a parent*/
      parent_popup = first_popup.opener;  /*get my parent*/
   }
       
   return first_popup;
}

function jsQUOTickerSearch(formName)
{
   var formObj = document.getElementById(formName);
   var str = formObj.ticker.value;
   var ws = isWhitespace (str);
   if(ws) {
      formObj.ticker.className = "error";
      var errorURL = "/VGApp/hnw/com/vanguard/quotes/jsp/QUOErrorJSP.jsp?ContentID=4356";
      jsCBDopenStdWin(errorURL,CBD_MODAL_POP2,'no','no',POPUP_SIZE2);
   } else { 
      var URL="/VGApp/hnw/QUOTickerSearch?ticker=" + str + "&formName=" + formName + "&textFieldName=ticker";
      if( formObj.AppTab != null )
         URL = URL + "&AppTab=" + formObj.AppTab.value;
         window.location.href = URL;
      }
}

function jsCBDStartDiv(width, height, bgColor, overflow, iewidth)
{
   if(overflow == null)
      overflow = "overflow:auto;";
   else
      overflow = "overflow:" + overflow + ";";

   if(bgColor == null)
      bgColor = "";
   else
      bgColor = "background-color:" + bgColor + ";";


   if(ie || nav4) 
   {
      if(iewidth != null)
         document.write("<DIV STYLE='" + overflow + bgColor + "height:" + height + "px;width:" + iewidth + "%'>");
      else
         document.write("<DIV STYLE='" + overflow + bgColor + "height:" + height + "px;width:" + width + "px'>");
   }
   else if(nav6) 
   {
      document.write("<DIV STYLE='" + overflow + bgColor + "height:" + height + "px;width:" + width + "px; position:absolute; z-index:1'>");
   }
}

function jsCBDEndDiv(width, height)
{
   document.write("</DIV>");
   
   if(nav6)
   {
      document.write("<DIV STYLE='overflow:none;height:"+ height + "px;width:" + (width - 15) + "px; position:relative'></DIV>");
   }
}


// this function will not print str if Mac is used
function jsCBDprintUnlessIEMac(str)
{
   if(!iemac)
      document.write(str);
}

// determine if url passed in is relative
function isRelativeUrl(url)
{
   if (url.indexOf(":/") != -1) { 
      return false;
   }
   else {
      return true;
   }
}
// strip off the server name of the input url 
// input MUST be in the form http://... or https://... as position is important
function jsCBDstripServerName(url) {
   url = url.substring(url.indexOf("/",8));
   return url;
}
