//
//	NAVIGATION
//





function selectLeftNavigationMenuItem(key)
{
	if (window.parent && window.parent.frames["ContextNav"])
	{
		if (SessionInfo_Get("userType") == "A" || SessionInfo_Get("userType") == "I" || SessionInfo_Get("newlhn") == "y")
		{
			var LHN = key.split("|");
			var lid1 = LHN[0];
			var lid2 = LHN[1];
			if (lid2 && lid1)
			{
				window.parent.frames["ContextNav"].makeactive(lid2, lid1);
			}
			else if (lid1)
			{
				window.parent.frames["ContextNav"].makeactive(lid1, null);
			}
			else
			{
				window.parent.frames["ContextNav"].makeactive(null, null);
			}
		}
		else
		{
			window.parent.frames["ContextNav"].selectThisMenuItem(key);
		}
	}
	return;
}

var _leftMenuKey = "";
var _topMenuKey = "";
var _enforce = false;
var _CallbackCounter = 0;

// callback function called if lhn is not loaded yet.
function selectNavigationMenuCallback()
{
	return selectNavigationMenu(_leftMenuKey, _topMenuKey, _enforce);
}

// if using new LHN look and feel, then separate level 2 and level 3 nav items with a |
function selectNavigationMenu(leftMenuKey, topMenuKey, enforce)
{
	try
	{
		if (SessionInfo_Get("userType") == "E")
			return;
	
		if ((leftMenuKey || topMenuKey) && window.parent != null && window.parent.frames["ContextNav"].document.getElementById('loaded') != null)
		{
			var hrefNew;
			// new LHN look and feel
			if (SessionInfo_Get("userType") == "A" || SessionInfo_Get("userType") == "I" || SessionInfo_Get("newlhn") == "y")
			{
				if (enforce)
				{
					reloadLHN(leftMenuKey);
					return;
				}
				window.parent.resizeCaller(true);
				window.top.setPersonalDetails();
				var LHNarray = leftMenuKey.split("|");
				var id1 = LHNarray[0];
				var id2 = LHNarray[1];
				if (id2 && id1)
				{
					makeActiveLHNItem(id2, id1);
				}
				else if (id1)
				{
					makeActiveLHNItem(id1, null);
				}
				else
				{
					makeActiveLHNItem(null, null);
				}
				
				return;
			}
			else
			{
				hrefNew = "/FirstNet/NavigationDynamic.asp?NavOpt=" + leftMenuKey;
			}
			if (enforce == true || !isSameHref(window.parent.frames["ContextNav"].location.href, hrefNew))			
				window.parent.frames["ContextNav"].location.href = hrefNew; 	
		}	
		else
		{
			// left nav has not loaded yet
			if (_CallbackCounter > 240)
			{
				// tried 240 times (2 minutes). Just resize the content page
				window.parent.resizeCaller(true);
				return;
			}
			else
			{
				// left nav ahs not loaded yet. Wait 500 ms and try again
				_leftMenuKey = leftMenuKey;
				_topMenuKey = topMenuKey;
				if (enforce != null)
					_enforce = enforce;
				_CallbackCounter++;
				window.setTimeout("selectNavigationMenuCallback()", 500);
			}
		}
		
		if (topMenuKey && window.top && window.top.frames["AccountNav"])			
		{
			var hrefNew = GetTopNav(topMenuKey);	
			if (enforce == true || !isSameHref(window.top.frames["AccountNav"].location.href, hrefNew))
				window.top.frames["AccountNav"].location.href = hrefNew;				
		}	
	}
	catch (e) 
	{
		//alert(e);
	}		
}



// UserType Context sensitive TopNav Menus
function GetTopNav(topMenuKey)
{
	switch(SessionInfo_Get("userType"))
	{
		case "D":
			return "/FirstNet/dealer/accountnav.asp?strPage=" + topMenuKey;
	}
	// Default is adviser top nav
	return "/FirstNet/accountnav.asp?strPage=" + topMenuKey;
}

function makeActiveLHNItem(lvl2, lvl3)
{
	if (window.parent.frames["ContextNav"])
	{
		if (lvl3 == null)
		{
			if (lvl2 != null)
			{
				if (SessionInfo_Get("MenuTabType") == "Client" || SessionInfo_Get("MenuTabType") == "MyAccount" || SessionInfo_Get("MenuTabType") == "publicformstools")
				{
					window.parent.frames["ContextNav"].toggleMenu1(lvl2);
				}
				else
				{
					window.parent.frames["ContextNav"].toggleMenu2(lvl2);
				}
			}
		}
		else
		{
			if (SessionInfo_Get("MenuTabType") == "Client" || SessionInfo_Get("MenuTabType") == "MyAccount" || SessionInfo_Get("MenuTabType") == "publicformstools")
			{
				window.parent.frames["ContextNav"].toggleMenu1(lvl3, lvl2);
			}
			else
			{
				window.parent.frames["ContextNav"].toggleMenu2(lvl3, lvl2);
			}
		}
		window.parent.frames["ContextNav"].makeactive(lvl2, lvl3);
	}
}
// reload new LHN
function reloadLHN(initialMenu)
{
	window.parent.parent.setPersonalDetails();
	var hrefNew = "/FirstNet/LHN.aspx";
	if (initialMenu) hrefNew += "?initialMenu=" + initialMenu;
	window.parent.frames["ContextNav"].location.href = hrefNew;
	
}
//
function isSameHref(href1, href2)
{
	href1 = href1.toLowerCase(); 
	href2 = href2.toLowerCase();		
	//
	return href1.substr(href1.indexOf("firstnet")) == href2.substr(href2.indexOf("firstnet"));
}
//
function validateCallBackResult(result, suppressError)
{
	if (!result.status)
	{
		if (result.data.toLowerCase().indexOf("session") >= 0)	
			window.top.location.href = "/firstnet/errors/Inc_ERR_Inv_Session.asp";
		else if (suppressError == null || !suppressError)
			alert(result.data);
		return false;
	}
	else
		return true;
}
// goes to "toPage" after selecting the client OIN and account
function navigateToClientAcct(clientOIN, clientName, acctNo, toPage)
{
	var noOfArguments = arguments.length;
		
	var redirectTo = "";
	
	// fix for Heat 409040
	// for linkg from tracking tool, it will pass extra parameter to indicate that it is from tracking tool
	// therefore this function have to check that argument is more than 4	
	if(noOfArguments > 4)
	{
		
		// if this is the redirect from tracking tool with status = In progress && status = transaction new ( withdraw , additional investment ...)
		isTransaction= arguments[4];
		
		if(isTransaction == "true" && toPage.trim() != "")
			redirectTo = "&IsTracking=true&toPage=" + escape(toPage);		
	}
	
	
	passSecure('/firstnet/adviser.asp?navacc=' + acctNo + '&MenuTabType=Client&frommodels=1' + redirectTo, '_top', 'SummaryInfo.aspx', 'Client', 'SummaryInfo', clientOIN, clientName, '', acctNo);
}

function SessionInfo_Get(name) 
{
	// ToDo: This function needs to be optimised.
	var start = document.cookie.indexOf("sessioninfo=");
	var len = start + 12;
	if ( ( !start ) && ( "sessioninfo" != document.cookie.substring( 0, 11 ) ) )
	{
		return null;
	}
	if ( start == -1 ) 
		return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) 
		end = document.cookie.length;
	var strSessionInfo = unescape( document.cookie.substring( len, end ) );
	var SessionArray = strSessionInfo.split("&");
	for(var i=0;i < SessionArray.length;i++)
	{
		var c = SessionArray[i];
		var hash = c.split("=");
		if (hash[0].toLowerCase() == name.toLowerCase())
		{
			return hash[1];
		}
	}
	return null;
}

function getQueryVariable(variable) 
{

	var query = window.parent.location.search.substring(1);
	query = unescape(query);
	var vars = query.split("&");
	for (var i=0;i<vars.length;i++)
	{
		var pair = vars[i].split("=");
		if (pair[0] == variable) 
		{
			return pair[1];
		}
	}
	// if we can't find the querystring from NavigationAndContentChild frame, get it from ContentChild frame
	query = window.location.search.substring(1);
	query = unescape(query);
	var vars = query.split("&");
	for (var i=0;i<vars.length;i++)
	{
		var pair = vars[i].split("=");
		if (pair[0] == variable) 
		{
			return pair[1];
		}
	}
	// can't find querystring

	return false;
}

function Account_formatNumber(accountNum, accountType)
{
	var num;
	switch (accountType)
	{
		case "UT" :
		case "SF" :
		case "PP" :
		case "R" :
			//Remove company code from account number
			accountNum = Right(accountNum, 12);
			accountNum = ZeroPad(accountNum, accountNum.length + (4 - accountNum.length % 4) % 4);
			num = Left(accountNum,4);
			for (var i=4; i < accountNum.length; i += 4)
			{
				num = num + " " + accountNum.substring(i, i+4);
			}
			return num;
			break;
		case "CM" :
		case "CF" :
		case "C" :
			if (Left(accountNum,1) != "0")
			{
				accountNum = "0" + accountNum;
			}
			num = Left(accountNum,3) + "-" + accountNum.substring(3,6) + "-" + accountNum.substring(6);
			return num;
			break;
		case "" :
 			switch (accountNum.length)
			{
				case 14 :
				case 15 :
					if (Left(accountNum,1) != "0")
					{
						accountNum = "0" + accountNum;
					}
					num = Left(accountNum,3) + "-" + accountNum.substring(3,6) + "-" + accountNum.substring(6);
					return num;
					break;
				case 0 :
					return accountNum;
					break;
				default :
					accountNum = Right(accountNum, 12);
					accountNum = ZeroPad(accountNum, accountNum.length + (4 - accountNum.length % 4) % 4);
					num = Left(accountNum,4);
					for (var i=4; i < accountNum.length; i += 4)
					{
						num = num + " " + accountNum.substring(i,i+4);
					}
					return num;
					break;
			}
		default :
			return accountNum;

	}
}

// simulates the Left asp string manipulation function
function Left(str, n){
	if (n <= 0)
	    return "";
	else if (n > String(str).length)
	    return str;
	else
	    return String(str).substring(0,n);
}

// simulates the Right asp string manipulation function
function Right(str, n){
    if (n <= 0)
       return "";
    else if (n > String(str).length)
       return str;
    else {
       var iLen = String(str).length;
       return String(str).substring(iLen, iLen - n);
    }
}

// simulates ZeroPad function in util.asp
function ZeroPad(str, n)
{
	var returnstring;
	if (str.length < n)
	{
		for (var i=0; i < (n-str.length); i++)
		{
			returnstring += "0";
		}
		returnstring += str;
		return returnstring;
	}
	else
	{
		return str;
	}
}

function getSessionPopupWindowName()
{
	if(document.cookie)
	{
		var sid = SessionInfo_Get('sid');
		if(sid)
			return sid;
	}
		
	return "PopupWnd";
}

function removeNode(n){
    if(n.hasChildNodes()){
        for(var i=0;i<n.childNodes.length;i++){
            n.parentNode.insertBefore(n.childNodes[i].cloneNode(true),n);
        }
    }
    n.parentNode.removeChild(n);
}



function DisableEnableLinks(xHow, frameIndex){

  if(frameIndex!=null && window.frames[frameIndex]!=null)
	{
	objLinks = self.frames[frameIndex].document.links;
	 
	}
  else
	objLinks = document.links;
 	
  for(i=0;i<objLinks.length;i++){
 
    // change style
	if(objLinks[i]!=null)
	{
		objLinks[i].style.color = "black";
		objLinks[i].style.textDecoration = "none";
	}
    //link with onclick
    if(objLinks[i].onclick && xHow){  
        objLinks[i].onclick = new Function("return false;");
    }
    //link without onclick
    else if(xHow){  
      objLinks[i].onclick = function(){return false;}
    }
    //remove return false with link without onclick
    else if(!xHow && objLinks[i].onclick.toString().indexOf("function(){return false;}") != -1){            
      objLinks[i].onclick = null;
    }
    
  }
}




function getThePrintDate()
{
	var myMonths=new Array("January","February","March","April","May","June","July","August","September","October","November","December");
	var myDays= new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday");
	today=new Date();
	thisDay=myDays[today.getDay()];
	thisMonth=myMonths[today.getMonth()];
	thisYear=today.getFullYear();
	thisDate=today.getDate();
	switch (thisDate) {
		case 1:
		dateSuffix="st"
		break
		case 21:
		dateSuffix="st"
		break
		case 31:
		dateSuffix="st"
		break    
		case 2:  
		dateSuffix="nd"  
		break    
		case 22:
		dateSuffix="nd"
		break;   
		case 3:
		dateSuffix="rd"  
		break     
		case 23:
		dateSuffix="rd"  
		break      
		default:   
		dateSuffix="th"
	}
	return thisDay +", "+thisDate+dateSuffix+" "+thisMonth+" "+thisYear; 
	
}



//Generating Pop-up Print Preview page
function CreatePrintView(print_area, customHeader)
{ 
	
	try
	{
		popup("/firstnet/print.aspx?PrintId=" + print_area + (customHeader ? "&CustomHeader=True" : ""), 705,600);
	}
	catch(ex)
	{
		 window.open("/firstnet/print.aspx?PrintId=" + print_area + (customHeader ? "&CustomHeader=True" : ""));	
	}

}
/*
 * This print page is used for RIP & BPay confirmation step 3 
 * */
function CreatePrintViewConfirmation(print_area)
{

	try
	{
		popup("/firstnet/printconfirmation.aspx", null , null);
	
	}
	catch(ex)
	{
		window.open("/firstnet/printconfirmation.aspx");
	
	}
}

function UpdateIFramePrintLinks(html)
{
	var pattern = /(<iframe.+src=[\"\'])(.+?)([\"\'].*?>)/gi
	return html.replace(pattern, "$1$2&Print=true$3");
}

//Validate Tax File Number. Must not contain spaces or dashes.
// Returns "" is valid or error message if invalid.
function isValidTFN(taxFileNumber, isIndividual)
{
	var errMsg = "Invalid TFN";
	var tfnMin = isIndividual ? 9  : 8 ;
	var tfnMax = 9;				
	var taxFileNumberString = '';
	
	taxFileNumberString = taxFileNumber + '';
	
	if (taxFileNumberString == '') {
		return "Mandatory";
	}

	if (isNaN(taxFileNumber)) {
		return errMsg;
	}
	
	if (taxFileNumber == 0)
		return errMsg;
	
	if (taxFileNumberString.length < tfnMin || taxFileNumber.length > tfnMax)
	{
		errMsg = "The TFN must be " + (!isIndividual ? " 8 or" : "") + " 9 digits in length";
		return errMsg;
	}
	
	var checkSum =  taxFileNumberString.substring(0, 1) * 10 +  
					taxFileNumberString.substring(1, 2) * 7 +
					taxFileNumberString.substring(2, 3) * 8 +
					taxFileNumberString.substring(3, 4) * 4 +
					taxFileNumberString.substring(4, 5) * 6 +
					taxFileNumberString.substring(5, 6) * 3 +
					taxFileNumberString.substring(6, 7) * 5; 
					
	if (taxFileNumberString.length == 8)
	{
		checkSum += taxFileNumberString.substring(7, 8) * 1;
	}
	else if (taxFileNumberString.length == 9)
	{
		checkSum += taxFileNumberString.substring(7, 8) * 2 +
					taxFileNumberString.substring(8, 9) * 1; 
	}
	
	remainder = checkSum % 11;
	return remainder == 0 ? "" : errMsg;
}

function isFinestOnlineSSO()
{
   return SessionInfo_Get("IsSSO") == "Y" && SessionInfo_Get("FinestOnlineID") != "";
}

function getSSOText()
{
    if(isFinestOnlineSSO())
        return " FirstNet ";
    else
        return " ";
}


function PopupPartialOutageNotification()
{
    var partialOutageNotificationWindow = 
        window.open("/firstnet/PartialOutage/Notification.aspx", "Popup",
                    "width=400,height=150,resizable=no,scrollbars=no");
                    
    partialOutageNotificationWindow.focus();

}