/*
	Functions and var used by CommonInclude.jsp
*/
	function getXmlHttpRequestObject() {
		if (window.XMLHttpRequest) {
			return new XMLHttpRequest(); //Not IE
		} else if(window.ActiveXObject) {
			return new ActiveXObject("Microsoft.XMLHTTP"); //IE
		} else {
			alert("Your browser doesn't support asynchronous JavaScript.  You need to upgrade to a later version.");
		}
	}
	var receiveReq = getXmlHttpRequestObject();

	function keepAlive() {
		// If our XmlHttpRequest object is not in the middle of a request, start the new asyncronous call.
		if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
			receiveReq.open("GET", '/vgn-ext-templating/MainStay/Common/keepAlive.jsp', true);
			receiveReq.send(null);
		}
	}
	function trackPage(audSerialNum, pageID, pageType, audience) {
		// If our XmlHttpRequest object is not in the middle of a request, call the tracking page
		if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
			receiveReq.open("GET", '/vgn-ext-templating/MainStay/Common/trackPage.jsp?audSerialNum='+audSerialNum+'&pageID='+pageID+'&pageType='+pageType+'&audience='+audience, true);
			receiveReq.send(null);
		}
	}
	function doLogin() {
		document.cookie = 'TargetPath=' + location.href + '; path=/';
		document.cookie = 'LoginSite=' + loginLocation + '; path=/';
		window.location.replace("/portal/site/login");
	}
	function doChildLogin() {
		doLogin();
	}
	function openWin(url, winName, x, y) {
		var newLeft = (screen.width - x) / 2 ;
		var newTop =  (screen.height - y) / 3 ;
		var newWin = window.open(url, winName, 'toolbar=no,location=no,directories=no,menubar=yes,scrollbars=yes,status=no,resizable=1,width='+x+',height='+y+',left ='+newLeft+',top='+newTop);
		newWin.focus();
	}
	function popupAudiences() {
		openWin('/portal/site/' + siteName + '/template.NylimSolo/','SelectAudience', 400, 300);
	}


/*
	Functions and vars from the Grid
*/
	var prompttitle = "Session Timeout";
	var timeoutmessage = "Sorry, your session has timed out.";
	var message = "Do you want to continue using MainStay Online Sales Desk? <br>";
	var logOffTimer;
	var message2 = "If you do not respond, you will be logged off at ";
	var timedOutHTML = "<table cellspacing='0' cellpadding='1' border='0' class='bgMain' width='100%'><tr width='100%'><td><table cellspacing='0' cellpadding='8' border='0' width='100%'><tr valign='middle' width='100%'><td colspan='2' class='bgMain'><b><font size='+1'>" + prompttitle + "</font></b></td></tr><tr width='100%'><td colspan='2' class='bgInterior'>" + timeoutmessage + "</td></tr><tr width='100%'><td align='middle' class='bgInterior' colspan='2'><br><img src='/vgn-ext-templating/MainStay/Resources/images/BUT_login.gif' border='0' class='formElements' onClick='loguseroff(false); document.getElementsByTagName(\"body\")[0].removeChild(document.getElementById(\"prompt2\"))'></td></tr></table></td></tr></table>";
	var innerDivHTML = "<table cellspacing='0' cellpadding='1' border='0' class='bgMain'><tr><td><table cellspacing='0' cellpadding='8' border='0' width='100%'><tr valign='middle'><td colspan='2' class='bgMain'><b><font size='+1'>" + prompttitle + "</font></b></td></tr> <tr><td colspan='2' class='bgInterior'>" + message + "</td></tr><tr><td align='middle' class='bgInterior' colspan='2'> <img src='/vgn-ext-templating/MainStay/Resources/images/buttons_yes.gif?x=92309' border='0' onClick='decide(true);'> <img src='/vgn-ext-templating/MainStay/Resources/images/buttons_no.gif?x=92309' border='0' onClick='decide(false);'> </td></tr><tr><td colspan='2' class='bgInterior'>" + message2;
	var innerDivHtmlEndMessage = ".</td></tr></table></td></tr></table>";
	var tab1 = "<table border=\"0\" width=\"600\"><tr class=\"print\">";
	var tab2 = "<table id=\"mainTable\" border=\"0\" bordercolor=\"green\" cellspacing=\"0\" cellpadding=\"0\" align=\"center\" class=\"mainTable\"><tr>";
	var initialTimeoutMsg = 1200000; // millis
	var timedOutMsgIntrvl = 600; //seconds
	var sURL = unescape(window.location.pathname);

	function getScrollXY () {
		var scrOfX = 0, scrOfY = 0;
		var scrOfArr = new Array(2);

		if (typeof( window.pageYOffset ) == 'number' ) {
			//Netscape compliant
			scrOfY = window.pageYOffset;
			scrOfX = window.pageXOffset;
		} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
			//DOM compliant
			scrOfY = document.body.scrollTop;
			scrOfX = document.body.scrollLeft;
		} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
			//IE6 standards compliant mode
			scrOfY = document.documentElement.scrollTop;
			scrOfX = document.documentElement.scrollLeft;
		}
		scrOfArr[0] = scrOfX;
		scrOfArr[1] = scrOfY;
		// return [ scrOfX, scrOfY ];
		return scrOfArr;
	}
	function resetLoggedTime () {
		// Reset the initial timer and add a new one
		clearTimeout(logOffTimer);
		window.setTimeout("checkLoggedTime()", initialTimeoutMsg);
	}
	function loguseroff (doQuietly) {
		sLogoutUrl = hostAndPort + "/portal/site/MainStay/template.MainStayLogout?TargetPath=/portal/site/MainStay";
		if (doQuietly) {
			// Open a window in the background to log the user out
			newwindow = window.open(sLogoutUrl, "logoff", "toolbar=no,location=no,directories=no,menubar=no,scrollbars=no,status=no,resizable=0,width=1,height=1");
			window.focus();
			window.setTimeout("newwindow.close()", 5000);
		} else {
			window.location.href = sLogoutUrl;
		}
	}
	function showWindowsObjects (bShow) {
		// Toggles all objects incompatible with <div>'s
		var windowedObjectTags = new Array("SELECT", "IFRAME", "OBJECT", "APPLET","EMBED");
		var windowedObjects = new Array();
		var j=0;
		//Assemble all objects to be turned off
		for (var i=0; i < windowedObjectTags.length; i++) {
			//if (document.all) var tmpTags = document.all.tags(windowedObjectTags[i]);
			var tmpTags = document.getElementsByTagName(windowedObjectTags[i]);
			if (tmpTags.length > 0) {
				for (var k=0; k<tmpTags.length; k++) {
					windowedObjects[j++] = tmpTags[k];
				}
			}
		}
		//make these objects hidden
		for (var i=0; i < windowedObjects.length; i++) {
			if (!bShow) windowedObjects[i].style.visibility = "hidden";
			else windowedObjects[i].style.visibility = "visible";
		}
	}
	function promptAlert (promptid, pos, v_top, v_left, v_width, v_innerHTML) {
		promptbox = document.createElement('div');
		promptbox.setAttribute ('id' , promptid);
		promptbox.setAttribute('z-index', '3');
		document.getElementsByTagName('body')[0].appendChild(promptbox);
		promptbox = eval("document.getElementById(promptid).style");
		var xy = getScrollXY();
		promptbox.position = pos;
		promptbox.top = xy[1] + v_top;
		promptbox.left = xy[0] + v_left;
		promptbox.width = v_width;
		promptbox.border = 'outset 1 #bbbbbb';
		document.getElementById(promptid).innerHTML = v_innerHTML;
		showWindowsObjects(false);
	}
	function decide (arg) {
		var staticDiff = timedOutMsgIntrvl; //30;
		showWindowsObjects(true);
			document.getElementsByTagName("body")[0].removeChild(document.getElementById("prompt"));
		if (arg == true) {
			diff = ((new Date()).getTime() - currentT.getTime()) / 1000;
			if (diff > staticDiff) {
				promptAlert('prompt2', 'absolute', 220, 300, 220, timedOutHTML);
			} else {
				resetLoggedTime();
			}
		} else {
			loguseroff(false);
		}
	}
	function checkLoggedTime () {
		// Initialize the new date/time
		currentT = new Date();
		var dLogOff = new Date(currentT.getTime() + (timedOutMsgIntrvl * 1000));
		logOffTimer = window.setTimeout("loguseroff(true)", timedOutMsgIntrvl * 1000);
		self.focus();
		promptAlert('prompt', 'absolute', 220, 300, 300, innerDivHTML + formatTime(dLogOff) + innerDivHtmlEndMessage);
	}
	function formatTime (dDate) {
		// returns a date in the form "5:19:29 PM"
		var s = dDate.getHours();
		if (s > 12) s = (s - 12);
		if (s == 0) s = 12;
		s += ":";
		if (dDate.getMinutes() < 10) s += "0";
		s += dDate.getMinutes() + ":";
		if (dDate.getSeconds() < 10) s += "0";
		s += dDate.getSeconds();
		s += (dDate.getHours() > 11 ? " PM" : " AM");
		return s;
	}



/*
	Functions and var from PrintFunctions.js
*/
	function doPrint () {
		newwindow=window.open(window.location+'&print=1','Print');
		if (window.focus) newwindow.focus();
		return false;
	}
	function getPrint () {
		return print;
	}
	function bookmark (siteName) {
		title = (siteName == null ? "" : siteName + " - ");
		title += document.title;
		if (window.sidebar) {
			// Mozilla Firefox Bookmark
			window.sidebar.addPanel(title, window.location,"");
		} else if( window.external ) {
			// IE Favorite
			window.external.AddFavorite( window.location, title);
		} else {
			alert("Browser not supported. Please bookmark manually.");
		}
	}
	function gup (name) {
		name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
		var regexS = "[\\?&]" + name + "=([^&#]*)";
		var regex = new RegExp(regexS);
		var results = regex.exec(window.location.href);
		if (results == null) {
			return "";
		} else {
			return results[1];
		}
	}
	var print = gup('print');

/*
	Search functions from Header.jsp
*/
	function searchQuery(queryElem) {
		queryVal = queryElem.value;
		if (queryVal != "") {
			queryVal = queryVal.replace(/[&]+/g, '%26');
			window.location = searchPage + '&queryText=' + queryVal;
		} else {
			alert("Please enter the Search text and try again");
		}
	}
	function doKeyPress(eve, txt){
		if (eve.keyCode == 13) {
			searchQuery(txt);
		}
	}


/*
	Functions and vars from ICAPTabs.js
*/
	var nSelectedMenuTab = -1;
	var nHighlightedMenuTab = -1;
	var nSelectedSubMenuTab = -1;
	var aSubMenus = new Array();
	var iHideTimer = 0;
	var selectedImage = "";
	var strSiteColor = "333333";
	var nSubMenuHeight = 16;
	var nMaxTabs = 0;

	function CreateLink(clink, ispopup, popup_attribs) {
		// builds a link based on whether the menu is popup or not
		if (ispopup) {
			clink = "window.open('" + clink + "', '', '" + popup_attribs + "')";
		} else {
			clink = "document.location='" + clink + "'";
		}
		return clink;
	}
	function CreateMenu(ctext, imenuid, clink, ispopup, popup_attribs) {
		// Call once for each tab, with imenuid starting at 1 and incrementing by 1 in order
		clink = CreateLink(clink, ispopup, popup_attribs);
		document.write('<td id="MenuTabTd' + imenuid + '" class="MenuTabUnselected"><span onclick="' + clink + '" onmouseover="HighlightMenuTab(' + imenuid + ')" onmouseout="RevertMenuTab()">' + ctext + '</span></td>');

		aSubMenus[imenuid] = "";
		if (imenuid > nMaxTabs) nMaxTabs = imenuid;
	}
	function CreateSubMenu(ctext, iparentid, clink, ispopup, subMenuID, popup_attribs) {
		// Call once for each sub-menu, with each subMenuID being unique
		clink = CreateLink(clink, ispopup, popup_attribs);
		cmenu = "'HM_Menu" + subMenuID + "'";
		sLink = '<td id="SubLink' + subMenuID + '" onclick="' + clink + '" onmouseover="HighlightSubMenuTab(' + subMenuID + ')"  onmouseout="UnHighlightSubMenuTab(' + subMenuID + ')" class="MenuTabSub">' + ctext + '</td>';

		// add the link to the appropriate submenu layer
		if (aSubMenus[iparentid] == "") {
			aSubMenus[iparentid] = sLink;
		} else {
			aSubMenus[iparentid] = aSubMenus[iparentid] + '<td class="MenuTabSubDivider">|</td>' + sLink;
		}
	}
	function initSubTabs () {
		// Sends html for sublayers
		for (i=1; i < aSubMenus.length; i++) {
			if (document.layers) {
			} else {
				if (aSubMenus[i] == "") {
					aSubMenus[i] = '<td class="MenuTabSub">&nbsp;</td>';
				}
				document.write('<div id="MenuTabLayer' + i + '" style="display:none; position:relative; z-index:5"><table cellpadding="0" id="MenuTabSubTable' + i + '" cellspacing="0" border="0" height="' + nSubMenuHeight + '"><tr>' + aSubMenus[i] + '</tr></table></div>');
			}
		}
	}
	function HighlightMenuTab (tabNumber) {
		// Gives 'Focus' to the selected tab
		UnHighlightMenuTab();

		if (tabNumber != nSelectedMenuTab) {
			document.getElementById("MenuTabTd" + tabNumber).className = "MenuTabHighlight";
			CancelRevert();
		}

		// Show the sublayer
		document.getElementById("MenuTabLayer" + tabNumber).style.display = "block";

		nHighlightedMenuTab = tabNumber;
		AdjustSubLayer(tabNumber);
	}
	function UnHighlightMenuTab () {
		// Removes 'Focus' from the tab that has it
		if (nHighlightedMenuTab > -1) {
			if (nHighlightedMenuTab != nSelectedMenuTab) {
				// Change to the 'Unfocused' font if not the Selected tab
				document.getElementById("MenuTabTd" + nHighlightedMenuTab).className = "MenuTabUnselected";
			}
			// Hide the sublayer
			document.getElementById("MenuTabLayer" + nHighlightedMenuTab).style.display = "none";

			nHighlightedMenuTab = -1;
		}
	}
	function RevertMenuTab() {
		// to be called on mouseout to highlight the selected tab
		if (iHideTimer == 0) {
			iHideTimer = setTimeout("HighlightMenuTab(nSelectedMenuTab)", 800);
		}
	}
	function CancelRevert() {
		// Cancels the call to RevertMenuTab above allowing the menu to stay up longer
		if (iHideTimer > 0) {
			clearTimeout(iHideTimer);
			iHideTimer = 0;
		}
	}
	function AdjustSubLayer (layerID) {
		// Position the sublayer centered under the menutab
		var padding = 10;
		var oMenu = document.getElementById("MenuTabTd" + layerID);
		var oSubMenu = document.getElementById("MenuTabSubTable" + layerID);
		var oLayer = document.getElementById("MenuTabLayer" + layerID);
		var menuCenter = oMenu.offsetLeft + (oMenu.offsetWidth /  2);
		var subRadius = oSubMenu.offsetWidth /  2
		var newLeft = menuCenter - subRadius;
		var newRight = menuCenter + subRadius;
		var iMaxWidth = oMenu.parentNode.offsetWidth;
		var iOffset = 0;
		if (newLeft < padding) {
			iOffset = newLeft - padding;
		} else if (newRight > (iMaxWidth - padding)) {
			iOffset = (newRight - iMaxWidth) + padding;
		}
		oLayer.style.width = oSubMenu.offsetWidth;
		oLayer.style.left = newLeft - iOffset;
	}
	function TurnTabOn (tabNumber, subMenuID) {
		// Selects the tab
		if (subMenuID) {
			TurnSubMenuTabOn(subMenuID);
		}
		if (tabNumber != nSelectedMenuTab) {
			TurnMenuTabOff(nSelectedMenuTab);
			nSelectedMenuTab = tabNumber;

			HighlightMenuTab(tabNumber);

			var oMenuTab = document.getElementById("MenuTabTd" + tabNumber);
			oMenuTab.className = "MenuTabSelected";
			if (selectedImage != "") {
				if (tabNumber > 1) {
					oMenuTab.style.background = strSiteColor + " url(" + selectedImage + ") no-repeat bottom left";
				}
			}
			if (tabNumber == nMaxTabs) {
				// Remove any right border on the tab
				oMenuTab.style.borderRight = "0px solid";
			}
		}
	}
	function TurnMenuTabOff (tabNumber) {
		if (tabNumber > -1) {
			var oMenuTab = document.getElementById("MenuTabTd" + tabNumber);
			oMenuTab.className = "MenuTabUnselected";
			oMenuTab.background="";
		}
	}
	function TurnSubMenuTabOn (subMenuID) {
		nSelectedSubMenuTab = subMenuID;
		document.getElementById("SubLink" + subMenuID).className = "MenuTabSubSelect";
	}
	function HighlightSubMenuTab (subMenuID) {
		oSubLink = document.getElementById("SubLink" + subMenuID);
		if (nSelectedSubMenuTab != subMenuID) {
			oSubLink.className = "MenuTabSubHighlight";
		}
		CancelRevert();

		// Now position the HM menu layer under that
		try {
			var HM_Menu = document.getElementById("HM_Menu" + subMenuID);
			var SubLinkLeft = document.getElementById("SubLink" + subMenuID).offsetLeft + 3;
			HM_Menu.tree.MenuLeft = SubLinkLeft;
		} catch (e) {}
	}
	function UnHighlightSubMenuTab (subMenuID) {
		if (nSelectedSubMenuTab != subMenuID) {
			document.getElementById("SubLink" + subMenuID).className = "MenuTabSub";
		}
		RevertMenuTab();
	}
	function bodyLoaded() {
		AdjustSubLayer(nHighlightedMenuTab);
	}


// Used in retirement my accounts	 Added by RQ (09/17/2009)
//=======================================SHA-1 code================================//

	var hex_chr = "0123456789abcdef";
	function hex(num)
	{
	  var str = "";
	  for(var j = 7; j >= 0; j--)
	    str += hex_chr.charAt((num >> (j * 4)) & 0x0F);
	  return str;
	}

	/*
	 * Convert a string to a sequence of 16-word blocks, stored as an array.
	 * Append padding bits and the length, as described in the SHA1 standard.
	 */
	function str2blks_SHA1(str)
	{
	  var nblk = ((str.length + 8) >> 6) + 1;
	  var blks = new Array(nblk * 16);
	  for(var i = 0; i < nblk * 16; i++) blks[i] = 0;
	  for(i = 0; i < str.length; i++)
	    blks[i >> 2] |= str.charCodeAt(i) << (24 - (i % 4) * 8);
	  blks[i >> 2] |= 0x80 << (24 - (i % 4) * 8);
	  blks[nblk * 16 - 1] = str.length * 8;
	  return blks;
	}

	/*
	 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
	 * to work around bugs in some JS interpreters.
	 */
	function add(x, y)
	{
	  var lsw = (x & 0xFFFF) + (y & 0xFFFF);
	  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
	  return (msw << 16) | (lsw & 0xFFFF);
	}

	/*
	 * Bitwise rotate a 32-bit number to the left
	 */
	function rol(num, cnt)
	{
	  return (num << cnt) | (num >>> (32 - cnt));
	}

	/*
	 * Perform the appropriate triplet combination function for the current
	 * iteration
	 */
	function ft(t, b, c, d)
	{
	  if(t < 20) return (b & c) | ((~b) & d);
	  if(t < 40) return b ^ c ^ d;
	  if(t < 60) return (b & c) | (b & d) | (c & d);
	  return b ^ c ^ d;
	}

	/*
	 * Determine the appropriate additive constant for the current iteration
	 */
	function kt(t)
	{
	  return (t < 20) ?  1518500249 : (t < 40) ?  1859775393 :
		 (t < 60) ? -1894007588 : -899497514;
	}

	/*
	 * Take a string and return the hex representation of its SHA-1.
	 */
	function calcSHA1(str)
	{
	  var x = str2blks_SHA1(str);
	  var w = new Array(80);

	  var a =  1732584193;
	  var b = -271733879;
	  var c = -1732584194;
	  var d =  271733878;
	  var e = -1009589776;

	  for(var i = 0; i < x.length; i += 16)
	  {
	    var olda = a;
	    var oldb = b;
	    var oldc = c;
	    var oldd = d;
	    var olde = e;

	    for(var j = 0; j < 80; j++)
	    {
	      if(j < 16) w[j] = x[i + j];
	      else w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1);
	      t = add(add(rol(a, 5), ft(j, b, c, d)), add(add(e, w[j]), kt(j)));
	      e = d;
	      d = c;
	      c = rol(b, 30);
	      b = a;
	      a = t;
	    }

	    a = add(a, olda);
	    b = add(b, oldb);
	    c = add(c, oldc);
	    d = add(d, oldd);
	    e = add(e, olde);
	  }
	  return hex(a) + hex(b) + hex(c) + hex(d) + hex(e);
	}
	//=======================================SHA-1 code================================//

	// Extended Tooltip Javascript
	// copyright 9th August 2002, by Stephen Chapman, Felgall Pty Ltd

	// permission is granted to use this javascript provided that the below code is not altered
	var DH = 0;
	var an = 0;
	var al = 0;
	var ai = 0;
	if (document.getElementById) {
		ai = 1; DH = 1;
	}else {
		if (document.all) {
			al = 1; DH = 1;
		} else {
			browserVersion = parseInt(navigator.appVersion);
			if ((navigator.appName.indexOf('Netscape') != -1) && (browserVersion == 4)) {
				an = 1; DH = 1;
			}
		}
	}


	function fd(oi,ws) {
		if (ws == 1) {
			if (ai) {
				return (document.getElementById(oi).style);
			} else {
				if (al) {
					return (document.all[oi].style);
				} else {
					if (an) {
						return (document.layers[oi]);
					}
				};
			}
		} else {
			if (ai) {
				return (document.getElementById(oi));
			} else {
				if (al) {
					return (document.all[oi]);
				} else {
					if (an) {
						return (document.layers[oi]);
					}
				};
			}
		}
	}

	function pw() {
		if (window.innerWidth != null)
			return window.innerWidth;
		if (document.body.clientWidth != null)
			return document.body.clientWidth; return (null);
	}

	function popUp(evt,oi) {
		if (DH) {
			var wp = pw();
			ds = fd(oi,1);
			dm = fd(oi,0);
			st = ds.visibility;
			if (dm.offsetWidth)
				ew = dm.offsetWidth;
			else if (dm.clip.width)
				ew = dm.clip.width;
			if (st == "visible" || st == "show") {
				ds.visibility = "hidden";
			} else  {
				if (evt.y || evt.pageY) {
					if (evt.pageY) {
						tv = evt.pageY + 20;
						lv = evt.pageX - (ew/4);
					} else {
						tv = evt.y + 20 + document.body.scrollTop;
						lv = evt.x  - (ew/4) + document.body.scrollLeft;
					}
					if (lv < 2)
						lv = 2;
					else if (lv + ew > wp)
						lv -= ew/2;
					ds.left = lv;
					ds.top = tv;
				}
				ds.visibility = "visible";
			}
		}
	}
