//---------------------------------------------------------------------
/// <summary>
/// Globals
/// </summary>
//---------------------------------------------------------------------

var gIsDirty = false;
var gExcludeList = "";
var gIncludeExtraList = "";
var gProcessingMessage = "";

var monthNames = new Array();

monthNames.length = 12;

monthNames[1] = "January";
monthNames[2] = "February";
monthNames[3] = "March";
monthNames[4] = "April";
monthNames[5] = "May";
monthNames[6] = "June";
monthNames[7] = "July";
monthNames[8] = "August";
monthNames[9] = "September";
monthNames[10] = "October";
monthNames[11] = "November";
monthNames[12] = "December";

//---------------------------------------------------------------------
/// <summary>
/// Fix for handling of IE, page load <object>
/// </summary>
//---------------------------------------------------------------------
function WindowOnLoadExtra()
{
	if(document.getElementById( 'hidRcvStartTime' ))
	{
	    document.getElementById( 'hidRcvStartTime' ).value = getDtTime();
	}
	else if(document.forms[0])
	{
		var rcvStartTime = document.createElement("input");
		rcvStartTime.setAttribute("type", "hidden");
		rcvStartTime.setAttribute("name", "hidRcvStartTime");
		rcvStartTime.setAttribute("id", "hidRcvStartTime");
		rcvStartTime.setAttribute("value",getDtTime() );
		document.forms[0].appendChild(rcvStartTime);		
	}
	else
	{
	  var frmMain = document.createElement("form");
	  var rcvStartTime = document.createElement("input");
	  rcvStartTime.setAttribute("type", "hidden");
	  rcvStartTime.setAttribute("name", "hidRcvStartTime");
	  rcvStartTime.setAttribute("id", "hidRcvStartTime");
	  rcvStartTime.setAttribute("value",getDtTime() );
	  frmMain.appendChild(rcvStartTime);
	  frmMain.method = "POST";
	  document.body.appendChild(frmMain);
	 }
	
  
	if (document.getElementsByTagName) 
	{
			// Get all the tags of type object in the page.
		var objs = document.getElementsByTagName("object");
		for (i=0; i<objs.length; i++) 
		{
			// Get the HTML content of each object tag
			// and replace it with itself.
			objs[i].outerHTML = objs[i].outerHTML;
		}
	}

	//document.getElementById( 'hidRcvDuration' ).value = getDtTime()-dateTime;
}

//---------------------------------------------------------------------
/// <summary>
/// Converts a date (string) to a Date object
/// E.g. 2009-03-26 12:13:41.307
/// </summary>
//---------------------------------------------------------------------
function splitDate( sDate )
{	
	var a1 = sDate.toString().split( ' ' );
	
	var a1Date = a1[0].split( '-' );
	var a1Year = a1Date[0];
	var a1Month = a1Date[1];
	var a1Day = a1Date[2];
	
	var a1Time = a1[1].split( ':' );
	var a1Hour = a1Time[0];
	var a1Minute = a1Time[1];
	
	var a1Second = a1Time[2].split( '.' );
	var a1Seconds = a1Second[0];
	var a1MilliSeconds = a1Second[1];
		
	var ab1 = new Date( );
	ab1.setYear( a1Year );
	ab1.setMonth( a1Month );
	ab1.setDate( a1Day );
	
	ab1.setHours( a1Hour );
	ab1.setMinutes( a1Minute );
	ab1.setSeconds( a1Seconds );
	ab1.setMilliseconds( a1MilliSeconds );
	
	return ab1;
}

//---------------------------------------------------------------------
/// <summary>
/// Calculate Date Difference In Minutes
/// </summary>
//---------------------------------------------------------------------
function CalculateDateDifferenceInMinutes( sDate1, sDate2 )
{
	var date1 = splitDate( sDate1 );
	var date2 = splitDate( sDate2 );
	var difference = new Date();
 
    // sets difference date to difference of first date and second date
    difference.setTime( Math.abs( date1.getTime() - date2.getTime() ) );

    timediff = difference.getTime();

	mins = Math.floor( timediff / ( 1000 * 60 ) );
  
	return mins
}

//---------------------------------------------------------------------
/// <summary>
/// Fix for handling of IE, page unload <object>
/// </summary>
//---------------------------------------------------------------------
window.onunload = function() 
{
  if (document.getElementsByTagName) 
  {
    //Get all the tags of type object in the page.
    var objs = document.getElementsByTagName("object");
    for (i=0; i<objs.length; i++) 
    {
      // Clear out the HTML content of each object tag
      // to prevent an IE memory leak issue.
      objs[i].outerHTML = "";
    }
  }
  
}
//---------------------------------------------------------------------
/// <summary>
/// cfPostPopulate
/// </summary>
//---------------------------------------------------------------------

function cfPostPopulate()
{
	var frmObject;

	if( document.frmMain )
	{
		frmObject = document.frmMain;
	}
	else if(document.form1)
	{
		frmObject = document.form1;	
	}
	
	for(i=0; i<frmObject.elements.length; i++)
	{
		if(String(formField[frmObject.elements[i].name]) != 'undefined')
		{
			switch(frmObject.elements[i].type)
			{
				case 'hidden':
				case 'text':
				case 'password':
				case 'textarea':
					frmObject.elements[i].value = formField[frmObject.elements[i].name];
				break;
				case 'checkbox':
				case 'radio':
					var values = formField[frmObject.elements[i].name].split(',');
					var selected=false;
					for(j=0; j<values.length; j++)
					{
						if(frmObject.elements[i].value == values[j])
							selected=true;
					}				
					frmObject.elements[i].checked=selected;					
				break;
				case 'select-one':
				case 'select-multiple':
					var values = formField[frmObject.elements[i].name].split(',');
					var selected=false;
					for(k=0; k<frmObject.elements[i].length; k++)
					{
						for(j=0; j<values.length; j++)
						{
							if(frmObject.elements[i][k].value == values[j])
								frmObject.elements[i][k].selected=true;
						}				
					}
				break;				
			}
		}		
	}
}

//---------------------------------------------------------------------
/// <summary>
/// cboGoTo_onchange
/// </summary>
//---------------------------------------------------------------------

function cboGoTo_onchange()
{
	if(document.getElementById( 'hidSndStartTime' ))
	{
		document.getElementById( 'hidSndStartTime' ).value = getDtTime();
	}
	else if(document.forms[0])
	{
		var sndStartTime = document.createElement("input");
		sndStartTime.setAttribute("type", "hidden");
		sndStartTime.setAttribute("name", "hidSndStartTime");
		sndStartTime.setAttribute("id", "hidSndStartTime");
		sndStartTime.setAttribute("value",getDtTime() );
		document.forms[0].appendChild(sndStartTime);
	}
	else
	{
		var frmMain = document.createElement("form");
		var sndStartTime = document.createElement("input");
		sndStartTime.setAttribute("type", "hidden");
		sndStartTime.setAttribute("name", "hidSndStartTime");
		sndStartTime.setAttribute("id", "hidSndStartTime");
		sndStartTime.setAttribute("value",getDtTime() );
		frmMain.appendChild(sndStartTime);
		frmMain.method = "POST";
		document.body.appendChild(frmMain);
	}
	
	var domain = new String( GetCurrentDomain() );
	
	if( domain != "localhost" )
	{
		document.domain = domain;
	}
	
	if ( document.frmMain.cboGoTo.value.length > 0 )
	{
		var value = new String();
		var mustPop = new String();
		var mode = new String();
		
		value = document.frmMain.cboGoTo.value;
		var split = value.split( "|" );
		
		document.frmMain.hidLinkProcessId.value = split[0];		
		document.frmMain.hidLinkActivityId.value = split[1];
		document.frmMain.hidLinkInstanceId.value = split[2];
		mustPop = split[3];							// split[3] == mustpop
		mode = split[4];							// split[4] == mode
		
		if(mustPop.toUpperCase() == "Y")
		{
			linkGoTo(split[0], split[1], split[2], "Y", "",  split[4]);
		}
		else
		{
			document.frmMain.hidNavigateToValue.value = "LinkGoTo";
			document.frmMain.submit();
		}
	}
}

//---------------------------------------------------------------------
/// <summary>
/// cboGoTo_onchange
/// </summary>
//---------------------------------------------------------------------

function breadCrumb_onchange( processId, activityId, instanceId, parameter2, sysMode )
{
	if(document.getElementById( 'hidSndStartTime' ))
	{
		document.getElementById( 'hidSndStartTime' ).value = getDtTime();
	}
	else if(document.forms[0])
	{
		var sndStartTime = document.createElement("input");
		sndStartTime.setAttribute("type", "hidden");
		sndStartTime.setAttribute("name", "hidSndStartTime");
		sndStartTime.setAttribute("id", "hidSndStartTime");
		sndStartTime.setAttribute("value",getDtTime() );
		document.forms[0].appendChild(sndStartTime);
	}
	else
	{
		var frmMain = document.createElement("form");
		var sndStartTime = document.createElement("input");
		sndStartTime.setAttribute("type", "hidden");
		sndStartTime.setAttribute("name", "hidSndStartTime");
		sndStartTime.setAttribute("id", "hidSndStartTime");
		sndStartTime.setAttribute("value",getDtTime() );
		frmMain.appendChild(sndStartTime);
		frmMain.method = "POST";
		document.body.appendChild(frmMain);
	}
	
	var frmObject;

	if( document.frmMain )
	{
		frmObject = document.frmMain;
	}
	else if(document.form1)
	{
		frmObject = document.form1;	
	}

	//var domain = new String( GetCurrentDomain() );
	
	//if( domain != "localhost" )
	//{
	//	document.domain = domain;
	//}
	
	//if ( document.frmMain.cboGoTo.value.length > 0 )
	//{
		var value = new String();
		var mustPop = new String();
		var mode = new String();
		
		//value = document.frmMain.cboGoTo.value;
		//var split = value.split( "|" );
		
		frmObject.hidLinkProcessId.value = processId;		
		frmObject.hidLinkActivityId.value = activityId;
		frmObject.hidLinkInstanceId.value = instanceId;
		mustPop = parameter2;							// split[3] == mustpop
		mode = sysMode;							// split[4] == mode
		
		if(mustPop.toUpperCase() == "Y")
		{
			linkGoTo(processId, activityId, instanceId, "Y", "",  sysMode);
		}
		else
		{
			frmObject.hidNavigateToValue.value = "LinkGoTo";
			frmObject.submit();
		}
	//}
}

//---------------------------------------------------------------------
/// <summary>
/// linkGoTo
/// </summary>
//---------------------------------------------------------------------

function linkGoTo( processId, activityId, instanceId, mustPop, popFeatures, mode, extraQuerystring )
{
	
	if(extraQuerystring == null || extraQuerystring == undefined)
	{
	    extraQuerystring ="";
	}
	
	if(document.getElementById( 'hidSndStartTime' ))
	{
		document.getElementById( 'hidSndStartTime' ).value = getDtTime();
	}
	else if(document.forms[0])
	{
		var sndStartTime = document.createElement("input");
		sndStartTime.setAttribute("type", "hidden");
		sndStartTime.setAttribute("name", "hidSndStartTime");
		sndStartTime.setAttribute("id", "hidSndStartTime");
		sndStartTime.setAttribute("value",getDtTime() );
		document.forms[0].appendChild(sndStartTime);
	}
	else
	{
		var frmMain = document.createElement("form");
		var sndStartTime = document.createElement("input");
		sndStartTime.setAttribute("type", "hidden");
		sndStartTime.setAttribute("name", "hidSndStartTime");
		sndStartTime.setAttribute("id", "hidSndStartTime");
		sndStartTime.setAttribute("value",getDtTime() );
		frmMain.appendChild(sndStartTime);
		frmMain.method = "POST";
		document.body.appendChild(frmMain);
	}
	
	var frmObject;

	if( document.frmMain )
	{
		frmObject = document.frmMain;
	}
	else if(document.form1)
	{
		frmObject = document.form1;	
	}

	//var domain = new String( GetCurrentDomain() );
	
	//if( domain != "localhost" )
	//{
	//	document.domain = domain;
	//}

	if ( mode && ( mode != "view" ) )
	{
		if ( activityId == "8300" ) 
		{	
			var conf = window.confirm("The Final Client Report is an important part of the audit trail.  All of the information contained in the final\nreport will be locked and the U-Skan analysis link will no longer be available.  Do you wish to proceed?");	
			
			if( !conf )
			{
				return false;
			}
		}
	}
	 
	if ( ( !mustPop ) || ( mustPop != "Y" ) )
	{ 
		frmObject.hidLinkProcessId.value = processId;
		frmObject.hidLinkActivityId.value = activityId;
		frmObject.hidLinkInstanceId.value = instanceId;
			
		frmObject.hidNavigateToValue.value = "LinkGoTo";

		frmObject.submit();
		
		return;
	}
	
	var sFeatures = popFeatures;
	
	if ( ( !popFeatures ) || ( popFeatures == "" ) )
	{
		window.open("ReenterActivity.aspx?_wpid=" + frmObject.hidWPID.value + "&processId=" + processId + "&activityId=" + activityId + "&instanceId=" + instanceId + "&routeId=1001" + extraQuerystring  , 'popADS');
	}
	else
	{
		window.open("ReenterActivity.aspx?_wpid=" + frmObject.hidWPID.value + "&processId=" + processId + "&activityId=" + activityId + "&instanceId=" + instanceId + "&routeId=1001" + extraQuerystring , 'popADS', sFeatures);
	}	
}


//---------------------------------------------------------------------
/// <summary>
/// Reenter at specific node
/// </summary>
//---------------------------------------------------------------------

function GetIframeSrc( processId, activityId, instanceId, nodeName, queryString )
{
	var url = "";
	
	if(GetCurrentHost() == "localhost")
	{
		url += "http://localhost/OldMutual.UI.WebController/"	
	}
	
	url += "ReenterActivity.aspx?_wpid=" + document.frmMain.hidWPID.value + "&processId=" + processId + "&activityId=" + activityId + "&instanceId=" + instanceId + "&routeId=1001&nodeName=" + nodeName;
	
	
	url += "&extraQueryString="+queryString+"&doNotAuth=1&junk="+(new Date()).valueOf();	

	return url;
}

//---------------------------------------------------------------------
/// <summary>
/// btnLinkEdit_onclick
/// </summary>
//---------------------------------------------------------------------

function btnLinkEdit_onclick( processId, activityId, instanceId )
{
	if(document.getElementById( 'hidSndStartTime' ))
	{
		document.getElementById( 'hidSndStartTime' ).value = getDtTime();
	}
	else if(document.forms[0])
	{
		var sndStartTime = document.createElement("input");
		sndStartTime.setAttribute("type", "hidden");
		sndStartTime.setAttribute("name", "hidSndStartTime");
		sndStartTime.setAttribute("id", "hidSndStartTime");
		sndStartTime.setAttribute("value",getDtTime() );
		document.forms[0].appendChild(sndStartTime);
	}
	else
	{
		var frmMain = document.createElement("form");
		var sndStartTime = document.createElement("input");
		sndStartTime.setAttribute("type", "hidden");
		sndStartTime.setAttribute("name", "hidSndStartTime");
		sndStartTime.setAttribute("id", "hidSndStartTime");
		sndStartTime.setAttribute("value",getDtTime() );
		frmMain.appendChild(sndStartTime);
		frmMain.method = "POST";
		document.body.appendChild(frmMain);
	}
	
	document.frmMain.hidLinkProcessId.value = processId;
	document.frmMain.hidLinkActivityId.value = activityId;
	document.frmMain.hidLinkInstanceId.value = instanceId;
		
	document.frmMain.hidNavigateToValue.value = "LinkEdit";

	document.frmMain.submit();
}

//---------------------------------------------------------------------
/// <summary>
/// btnLinkEdit_onclick
/// </summary>
//---------------------------------------------------------------------

function btnLinkError_onclick( processId, activityId, instanceId )
{
	if(document.getElementById( 'hidSndStartTime' ))
	{
		document.getElementById( 'hidSndStartTime' ).value = getDtTime();
	}
	else if(document.forms[0])
	{
		var sndStartTime = document.createElement("input");
		sndStartTime.setAttribute("type", "hidden");
		sndStartTime.setAttribute("name", "hidSndStartTime");
		sndStartTime.setAttribute("id", "hidSndStartTime");
		sndStartTime.setAttribute("value",getDtTime() );
		document.forms[0].appendChild(sndStartTime);
	}
	else
	{
		var frmMain = document.createElement("form");
		var sndStartTime = document.createElement("input");
		sndStartTime.setAttribute("type", "hidden");
		sndStartTime.setAttribute("name", "hidSndStartTime");
		sndStartTime.setAttribute("id", "hidSndStartTime");
		sndStartTime.setAttribute("value",getDtTime() );
		frmMain.appendChild(sndStartTime);
		frmMain.method = "POST";
		document.body.appendChild(frmMain);
	}
	
	document.frmMain.hidLinkProcessId.value = processId;
	document.frmMain.hidLinkActivityId.value = activityId;
	document.frmMain.hidLinkInstanceId.value = instanceId;
		
	document.frmMain.hidNavigateToValue.value = "LinkError";

	document.frmMain.submit();
}

//---------------------------------------------------------------------
/// <summary>
/// Form1 Submit
/// </summary>
//---------------------------------------------------------------------

function frm1Submit( navigateToValue )
{	

	if(document.getElementById( 'hidSndStartTime' ))
	{
		document.getElementById( 'hidSndStartTime' ).value = getDtTime();
	}
	else if(document.forms[0])
	{
		var sndStartTime = document.createElement("input");
		sndStartTime.setAttribute("type", "hidden");
		sndStartTime.setAttribute("name", "hidSndStartTime");
		sndStartTime.setAttribute("id", "hidSndStartTime");
		sndStartTime.setAttribute("value",getDtTime() );
		document.forms[0].appendChild(sndStartTime);
	}
	else
	{
		var frmMain = document.createElement("form");
		var sndStartTime = document.createElement("input");
		sndStartTime.setAttribute("type", "hidden");
		sndStartTime.setAttribute("name", "hidSndStartTime");
		sndStartTime.setAttribute("id", "hidSndStartTime");
		sndStartTime.setAttribute("value",getDtTime() );
		frmMain.appendChild(sndStartTime);
		frmMain.method = "POST";
		document.body.appendChild(frmMain);
	}
	
	if( document.form1 && document.form1.hidNavigateToValue )
	{
		// For changes made for Digital Certificates, click back button redirct digital certificate homepage.
		if (( navigateToValue == "Previous" ) && ( document.form1.hidSysLastUrl.value.indexOf("eifa") > -1) && (document.form1.hidDcLogon.value == "Y"))
		{  
			document.location.href = "StartProcess.aspx?processId=20700";
		}
		else
		{
			document.form1.hidNavigateToValue.value = navigateToValue;
			document.form1.submit();
		}
	}
}

//---------------------------------------------------------------------
/// <summary>
/// Form Submit
/// </summary>
//---------------------------------------------------------------------

function frmSubmit( navigateToValue )
{

	if(document.getElementById( 'hidSndStartTime' ))
	{
		document.getElementById( 'hidSndStartTime' ).value = getDtTime();
	}
	else if(document.forms[0])
	{
		var sndStartTime = document.createElement("input");
		sndStartTime.setAttribute("type", "hidden");
		sndStartTime.setAttribute("name", "hidSndStartTime");
		sndStartTime.setAttribute("id", "hidSndStartTime");
		sndStartTime.setAttribute("value",getDtTime() );
		document.forms[0].appendChild(sndStartTime);
	}
	else
	{
	  var frmMain = document.createElement("form");
	  var sndStartTime = document.createElement("input");
	  sndStartTime.setAttribute("type", "hidden");
	  sndStartTime.setAttribute("name", "hidSndStartTime");
	  sndStartTime.setAttribute("id", "hidSndStartTime");
	  sndStartTime.setAttribute("value",getDtTime() );
	  frmMain.appendChild(sndStartTime);
	  frmMain.method = "POST";
	  document.body.appendChild(frmMain);
	 }
	
	if( gProcessingMessage.length > 0 )
	{
		cfShowProcessing();
	}
	
	// For changes made for Digital Certificates, click back button redirct digital certificate homepage.
	if (( navigateToValue == "Previous" ) && ( document.frmMain.hidSysLastUrl.value.indexOf("eifa") > -1) && (document.frmMain.hidDcLogon.value == "Y"))
	{  
		document.location.href = "StartProcess.aspx?processId=20700";
	}
	else
	{
		document.frmMain.hidNavigateToValue.value = navigateToValue;
		document.frmMain.submit();
	}
}

//---------------------------------------------------------------------
/// <summary>
/// JavaScript trim function
/// </summary>
//---------------------------------------------------------------------
function Trim(text) 
{ 
    //  leading spaces 
    while (text.substring(0,1) == ' ') 
		{
			text = text.substring(1, text.length);
		}
    //  trailing spaces 
    while (text.substring(text.length-1,text.length) == ' ')
    {	
			text = text.substring(0, text.length-1);
		}
   return text;
} 

//---------------------------------------------------------------------
/// <summary>
/// Returns true if value is numeric
/// </summary>
//---------------------------------------------------------------------

function IsPercentInteger( num )
{
	var checkOK = "0123456789";
	var checkStr = num;
	var allValid = true;
	var validGroups = true;
	var decPoints = 0;
	var allNum = "";

	for (i = 0;  i < checkStr.length;  i++)
	{
		ch = checkStr.charAt(i);
		for (j = 0;  j < checkOK.length;  j++)
		{
			if (ch == checkOK.charAt(j))
				{
					break;
		}		}
			
		if (j == checkOK.length)
		{
			allValid = false;
			break;
		}
		
	}	
	
	if (allValid)
	{
		return true;
	}	
	
	return false;
}

//---------------------------------------------------------------------
/// <summary>
/// Returns true if value is numeric
/// </summary>
//---------------------------------------------------------------------

function IsNumericOnly(num)
{
	var checkOK = "0123456789.";
	var checkStr = num;
	var allValid = true;
	var validGroups = true;
	var decPoints = 0;
	var allNum = "";

	for (i = 0;  i < checkStr.length;  i++)
	{
		ch = checkStr.charAt(i);
		for (j = 0;  j < checkOK.length;  j++)
		{
			if (ch == checkOK.charAt(j))
				{
					break;
		}		}
			
		if (j == checkOK.length)
		{
			allValid = false;
			break;
		}
		
	}	
	
	if (allValid)
	{
		return true;
	}	
	
	return false;
}

//---------------------------------------------------------------------
/// <summary>
/// Date Validation Methods
/// </summary>
//---------------------------------------------------------------------


// function to determine if value is in acceptable range
function inRange(inputStr, lo, hi) 
{
	var num = parseInt(inputStr, 10)
	if (num < lo || num > hi) {
		return false
	}
	return true
}

function ValidateMonth(monthValue) 
{
	if (monthValue.length < 2)
	{
		alert("Month must be in the form mm");
		return false;
	}

	var input = parseInt(monthValue, 10);
	
	if (isNaN(input)) 
	{
		alert("Month must be numeric");
		return false;
	} 
	else 
	{
		if (!inRange(input,1,12)) 
		{
			alert("Month must be between 01 (January) and 12 (December)");
			return false;
		}
	}

	return true
}

function ValidateDay(dayValue, monthValue) 
{
	if (dayValue.length < 2)
	{
		alert("Day must be in the form dd");
		return false;
	}

	var input = parseInt(dayValue, 10);
	
	if (isNaN(input)) 
	{
		alert("Day must be numeric");
		return false;
	} 
	else 
	{
		
		if (!ValidateMonth(monthValue))	// month value must be valid
		{ 
			return false; 
		}
		
		var monthVal = parseInt(monthValue, 10);
		
		var monthMax = new Array(31,31,29,31,30,31,30,31,31,30,31,30,31);
		var top = monthMax[monthVal];
		if (!inRange(input,1,top)) 
		{
			alert("For this month, day must be between 1 and " + top );
			return false;
		}
	}
	
	return true;
}

function ValidateYear(yearValue) 
{
	if (yearValue.length < 4)
	{
		alert("Year must be in the form yyyy");
		return false;
	}

	var input = parseInt(yearValue, 10);

	if (isNaN(input)) 
	{
		alert("Year must be numeric");
		return false;
	} 
	if(input<1900)
	{
		alert("Year must be greater than 1900");
		return false;
	}
	return true;
}

function ValidateDate(dd, mm, yyyy)
{
	if (ValidateDay(dd,mm))
	{
		if (ValidateYear(yyyy))
		{
			return true;
		}
	}
	
	return false;
}

//---------------------------------------------------------------------
/// <summary>
/// End Date Validation Methods
/// </summary>
//---------------------------------------------------------------------


//---------------------------------------------------------------------
/// <summary>
/// Ensures 2 numbers after the decimal
/// </summary>
//---------------------------------------------------------------------
function Decimal2(n) 
{
  var s = "" + Math.round(n * 100) / 100
  var i = s.indexOf('.')
  if (i < 0) return s + ".00"
  var t = s.substring(0, i + 1) + s.substring(i + 1, i + 3)
  if (i + 2 == s.length) t += "0"
  return t
}

//---------------------------------------------------------------------
/// <summary>
/// Rounds number to 2 decimal places (is dependant on Decimal2()) and formats number in comma separated form
/// </summary>
//---------------------------------------------------------------------
function FormatComma(number) 
{
    var left;
    var right;
    var dot;
    
    number = '' + number;
    
    dot = number.indexOf(".");
    
    //alert(dot);
    //alert(number.substr(0, dot));
    
    
    if (dot != -1)
		{
			left  = number.substr(0, dot);
			right = number.substr(dot, number.length);
			if (right.length == 2 )
			{
				right = right + "0";
			}
			
			//alert(left + "\n" + right );
		}
    else
		{
			left = number;
			right = ".00";
		}
    
    if (left.length > 3) 
		{
		    var mod = left.length%3;
		    var output = (mod > 0 ? (left.substring(0,mod)) : '');
		    for (i=0 ; i < Math.floor(left.length/3) ; i++) 
				{
					if ((mod ==0) && (i ==0))
						{
							output+= left.substring(mod+3*i,mod+3*i+3);
						}
					else
						{
							output+= ',' + left.substring(mod+3*i,mod+3*i+3);
						}
				}
				output = output + right;
		    return (output);
		}
    else return Decimal2(number);
}


//---------------------------------------------------------------------
/// <summary>Help page-xsl relationship</summary>
//---------------------------------------------------------------------

function GetHelpXsl(which)
{
	var aHelpXsl = new Array();

	aHelpXsl["AssetAllocationGrowth"] = "AssetAllocation.Growth.ChartHelp.Xsl";	
	aHelpXsl["AssetAllocationGrowthProjection"] = "AssetAllocation.Growth.GraphHelp.Xsl";	
	aHelpXsl["AssetAllocationSCRA"] = "AssetAllocation.Growth.ChartHelp.Xsl";	
	aHelpXsl["AssetAllocationSCRAProjection"] = "AssetAllocation.Growth.GraphHelp.Xsl";	
	
	if(!aHelpXsl[which])
	{
		return "AssetAllocation.Help.Xsl";
	}
	else
	{
		return aHelpXsl[which];
	}
	
}


//---------------------------------------------------------------------
/// <summary>Dynamic help popup</summary>
//---------------------------------------------------------------------
function LaunchHelp()
{
	var path = new String();
	var pageName = new String();
	var pageNameNoExtension = new String();
	var xsl = new String();
	var qsProductId = new String();
	var href = new String();
	var wpid = new String();
	
	path = location.pathname;
	pageName =  path.substring((path.lastIndexOf("/") + 1), path.length);
	pageNameNoExtension = pageName.substring(0, ((pageName.lastIndexOf(".") )));
	href = location.href;
	wpid = href.substr(href.indexOf("_wpid"), 42  )	// 36 for quid, 5 for _wpid=, 1 for 0 based
	
	xsl = GetHelpXsl(pageNameNoExtension);
		
	qsProductId = "";
	if(frmMain.hidProductId)
	{
		qsProductId = "&productId=" + frmMain.hidProductId.value
	}

	window.open("AssetAllocationHelp.aspx?" + wpid + "&xsl=" + xsl + qsProductId,'popup',"width=516,height=400, toolbar=no,menubar=no,location=no,scrollbars=yes,status=yes,screenX=-100,screenY=0,top=0")
}

//---------------------------------------------------------------------
/// <summary>Returns integer year since date passed</summary>
//---------------------------------------------------------------------
function HowLongSince(startdate, startmonth, startyear) 
{
	sdate=startdate;
	smonth=startmonth-1;
	syear=startyear;
	var DaysInMonth = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
	today = new Date()
	var thisyear	= today.getFullYear();
	var thismonth	= today.getMonth();
	var thisdate	= today.getDate();
	mstart = new Date(syear,(smonth==12?1:smonth+1),1);
	days1 = (mstart - new Date(syear,smonth,sdate))/(24*60*60*1000)-1;
	mend = new Date(thisyear,thismonth,1);
	days2 = (new Date(thisyear,thismonth,thisdate) - mend)/(24*60*60*1000)+1;
	dayst = days1 + days2;
	if (dayst >= DaysInMonth[smonth])  
		{
			AddOneMonth = 1; 
			dayst -= DaysInMonth[smonth]; 
		}
	else AddOneMonth = 0;

	ydiff1 = thisyear-mstart.getFullYear();
	mdiff1 = thismonth-mstart.getMonth()+AddOneMonth;
	if (mdiff1 >11) { mdiff1=0; ydiff1++; }
	if (mdiff1 < 0) { mdiff1 = mdiff1 + 12; ydiff1--; }
	temp = (ydiff1==0?"":(ydiff1==1?ydiff1+"":ydiff1));
	//temp += (mdiff1==0?"0 months, and ":(mdiff1==1?mdiff1+" month, and ":mdiff1+" months, and "));
	//temp += (dayst==0?"no days":(dayst==1 ? " 1 day." : dayst + " days." ));
	if (temp == ""){temp=0;}
	gYear = temp;
	gDays = dayst;
	return temp;
}

//---------------------------------------------------------------------
/// <summary>Returns integer year since date passed in</summary>
//---------------------------------------------------------------------
function GetAge( yyyy, mm, dd )
{
	var birthday = new Date( yyyy, mm-1, dd );
	
	var today = new Date();
	today.setHours( 0, 0, 0, 0 );
	
	var years = today.getFullYear() - birthday.getFullYear();
	
	birthday.setYear( today.getFullYear() );
  
	return( ( today < birthday ) ? --years : years );
}
//---------------------------------------------------------------------
/// <summary>Launch FactSheet window
/// </summary>
//---------------------------------------------------------------------
function LaunchFactSheet(mexid)
{
	var redirectURL = new String();
	
	redirectURL = location.protocol + "//" + GetCurrentHost() + "/ErrorPage.asp";
	
	var url = "http://uskan.financialexpress.net/fundfactsheet.aspx?code=" + mexid + "&redirect=" + redirectURL;
			
	window.open( url, '_blank',"width=637,height=600,toolbar=no,menubar=no,location=no,scrollbars=yes,status=yes,resizable=yes,screenX=-100,screenY=0,top=0");
}

function ValidateLifeAssuredAge(dobDD, dobMM, dobYYYY)
{
	//---------------------------------------------------------------------
	/// <rule no="Val00031"></rule>
	//---------------------------------------------------------------------	
	if (!ValidateDate(dobDD, dobMM, dobYYYY))
	{
		return false;
	}

	var minAge = new Number();
	var maxAge = new Number();
		
	minAge = 3/12;  //in year : So 3 months 0.25 of the year
	maxAge = 80;    //in year
	
	var min_age_months = new Number()
	min_age_months = minAge.toFixed(2)*12; //value in terms of months
	
	//subtract 1 from dobMM to fitt Javascript counting of months starting at zero for Januray
	var birthday = new Date(dobYYYY, dobMM-1, dobDD);
	var today = new Date();
	
	if (birthday > today) 
	{
		alert( "The investor's birth date of cannot be greater than todays date.");
		return false;				
	}
    
	var invAge = GetAge(dobYYYY, dobMM, dobDD);
	if( invAge > maxAge)
	{
		alert( "The age of the life assured " + invAge + " is greater than the maximum age.");
		return false;			
	}
	
	//investor age in months
	var proposedDate = cfGetEndDT(birthday, 3);
	if( today < proposedDate )
	{
		alert( "The age of the life assured is less than the minimum age of " + min_age_months.toString().valueOf() + " months.");
		return false;
	}
	
	return true;
}
//---------------------------------------------------------------------
/// Get an end date a specified number of months from the inputdate
//---------------------------------------------------------------------
function cfGetEndDT(inputDate, noOfMonths)
{
	var inputDayOfMonth = parseInt(inputDate.getDate());
	var inputMonth = parseInt(inputDate.getMonth());
	var inputYear = parseInt(inputDate.getFullYear());
	
	var monthToCalc;
	var yearToCalc;
	
	var proposedMonth = inputMonth + noOfMonths;
	
	if (proposedMonth > 12)
	{
		monthToCalc = proposedMonth - 12;
		yearToCalc = inputYear + 1;
	}
	else
	{
		monthToCalc = inputMonth + noOfMonths;
		yearToCalc =  inputYear;
	}
	var endDate = new Date(yearToCalc, monthToCalc, "01");
	
	var lastDayOfMonth = cfLastDayOfTheMonth(endDate);
	
	if (inputDayOfMonth >= lastDayOfMonth  ) 
	{
		endDate.setDate(lastDayOfMonth);		
	}
	else
	{
		endDate.setDate(inputDayOfMonth);
	}

	return endDate;
}

//---------------------------------------------------------------------
/// <summary>Returns host part of current url</summary>
//---------------------------------------------------------------------
function GetCurrentHost()
{
	return location.hostname;
}

function iframeDisplay(iframeId, processId, activityId, instanceId, nodeName, queryString)
{	
	if(document.getElementById(iframeId).style.display=="block")
	{
		if(document.getElementById('btnPlusMinus' + iframeId))
		{
			document.getElementById('btnPlusMinus' + iframeId).src = '/images/btn_skandia_1200_expand.gif';
		}
		
		document.getElementById(iframeId).style.display="none";
	}
	else
	{
		if(document.getElementById('btnPlusMinus' + iframeId))
		{
			document.getElementById('btnPlusMinus' + iframeId).src = '/images/btn_skandia_1200_collapse.gif';
		}
		
		if(document.getElementById(iframeId).src == "javascript:false;")
		{
			document.getElementById(iframeId).src = GetIframeSrc( processId, activityId, instanceId, nodeName, queryString )
		}
		else
		{
			resizeFrame(iframeId, (document.getElementById(iframeId).style.display=="none"));
		}
	}
}

function resizeFrame(iframeId, display)
{
	if (document.getElementById)
	{
		var dyniframe;				 
		
		dyniframe = document.getElementById(iframeId);
		
		if( display )
		{	
			dyniframe.style.display="block"
			dyniframe.style.height = dyniframe.Document.body.scrollHeight - 10;
		}		
	}
}


//---------------------------------------------------------------------
/// <summary>Set Dirty Events</summary>
//---------------------------------------------------------------------	

function gSetIsDirtyEvents()
{
	for (idx=0; idx < document.frmMain.elements.length ; idx++) 
	{
// Only process those not in Exclude list and of the types below in the switch statement	
		if( !gInExcludeList(document.frmMain.elements[idx].name) )
		{
			switch(document.frmMain.elements[idx].type)
			{
				case "text":
					document.frmMain.elements[idx].attachEvent("onchange",gSetDirtyFlag);
				break;
				case "textarea":
					document.frmMain.elements[idx].attachEvent("onchange",gSetDirtyFlag);
				break;
				case "checkbox":
					document.frmMain.elements[idx].attachEvent("onclick",gSetDirtyFlag);
				case "radio":
					document.frmMain.elements[idx].attachEvent("onclick",gSetDirtyFlag);		
				break;
				case "select-one":
					document.frmMain.elements[idx].attachEvent("onchange",gSetDirtyFlag);	
				break;
				case "select-multiple":
					document.frmMain.elements[idx].attachEvent("onchange",gSetDirtyFlag);	
				break;
			}
// Include elements of other types eg.hidden that have been specified in the include list- only hidden currently catered for		
			if (gInIncludeExtraList(document.frmMain.elements[idx].name) )
			{
				switch(document.frmMain.elements[idx].type)
				{
					case "hidden":
						document.frmMain.elements[idx].attachEvent("onchange",gSetDirtyFlag);
					break;
				}	
			}

		}						
    }
}
function gInExcludeList(sCheck)
{
	var sList = new String();
	var aList = new Array();
	
	sList = gExcludeList;
	aList = sList.split("|");
	
	for(idxCheck = 0; idxCheck < aList.length; idxCheck++)
	{
		if(sCheck.toLowerCase() == aList[idxCheck].toLowerCase())	
		{
			return true;			
		}
	}
	
	return false;
}
function gInIncludeExtraList(sCheck)
{
	var sList = new String();
	var aList = new Array();
	
	sList = gIncludeExtraList;
	aList = sList.split("|");
	
	for(idxCheck = 0; idxCheck < aList.length; idxCheck++)
	{
		if(sCheck.toLowerCase() == aList[idxCheck].toLowerCase())	
		{
			return true;			
		}
	}
	
	return false;
}
//---------------------------------------------------------------------
/// <summary>generic save method</summary>
//---------------------------------------------------------------------	

function gSetDirtyFlagFalse()
{
	gIsDirty = false;
}
//---------------------------------------------------------------------
/// <summary>Set Dirty Flag</summary>
//---------------------------------------------------------------------

function gSetDirtyFlag() 
{
  gIsDirty = true;
}


//---------------------------------------------------------------------
/// <summary>RebuildFromOpener</summary>
//---------------------------------------------------------------------

function RebuildFromOpener()
{
	var openerForm;
	
	if( opener.document.frmMain )
	{
		openerForm = opener.document.frmMain;
	}
	else
	{
		openerForm = opener.document.form1;
	}
	
	for(i=0; i < openerForm.elements.length;i++)
	{
		var el = openerForm.elements[i];
		var val = new String();
		
		if(el.name == "__VIEWSTATE")
		{
			continue;
		}
		
		if(el.name == "")
		{
			continue;
		}
		
		if (el.type == "radio")
		{
			//alert(el.name + "\t" + el.checked + "\t" + el.value);
			if(el.checked == true)
			{	
				val = el.value;
		
				if(document.getElementById(el.name))
				{
					document.getElementById(el.name).value = val;
				}
			}
		}
		else if (el.type == "checkbox")
		{
			//alert(el.name + "\t" + el.checked + "\t" + el.value);
			if (el.checked == true)
			{
				val = el.value;
			}
			else
			{
				val = "";
			}
			if (document.getElementById(el.name))
			{
				//alert("name: " + document.getElementById(el.name).name + "\tval: " + val);
				document.getElementById(el.name).value = val;
			}
		}
		else
		{
			val = el.value;
			if(val != "")
			{
				if(document.getElementById(el.name))
				{
					document.getElementById(el.name).value = val;
				}
			}
		}
	}	
}
//---------------------------------------------------------------------
/// <summary>
/// cfValidateExpectedRetirementAge
/// </summary>
//---------------------------------------------------------------------

function cfExpectedRetirementAge(expectedRetirementAge, investorAge, lowPensionAge, expRetirementDate, birthday)
{

	var ageToCheck;
	var currAgePlus1;
	
	var currentYear = new Date();

	var currAgePlus1 = investorAge + 1;

	if (lowPensionAge.length > 0 && lowPensionAge != 0 )
	{
		if ( parseInt(lowPensionAge) > currAgePlus1)
		{
			ageToCheck = parseInt(lowPensionAge);
		}
		else
		{
			ageToCheck = currAgePlus1
		}	
	}
	else
	{
		if (currAgePlus1 < 50)
		{
			if (currentYear.getFullYear() >= 2006 && currentYear.getFullYear() <= 2010)
			{
				ageToCheck = 50;
			}
			else
			{
				ageToCheck = 55;
			}
		}
		else
		{
			ageToCheck = currAgePlus1;
		}
	}

	if (ageToCheck == 75)
	{
		if (expectedRetirementAge != 75)
		{
			alert("The retirement age must be 75");
			return false;
		}	
	}
	else
	{
		if (ageToCheck > 75)
		{
			if (expectedRetirementAge > 75)
			{
				alert("The retirement age must be less than 76");
				return false;
			}	
		}
		else
		{	
			if ( (expRetirementDate != '') && ( expectedRetirementAge == 75) )
			{
				alert("aaa\n|" + expRetirementDate + "|\n" + expectedRetirementAge);
				if ( (expRetirementDate.getMonth() < birthday.getMonth()) )  
				{
				}
				else
				{
					alert("The retirement age must be between " + ageToCheck + " and 75 inclusive");
					return false;
				}
			}

		
			if ((expectedRetirementAge < ageToCheck) || ( expectedRetirementAge > 75 ))
			{
				alert("The retirement age must be between " + ageToCheck + " and 75 inclusive");
				return false;
			}
		}	
	}

	//sumretdate = (retage - sumretdate);
	//difretage = (expectedRetirementAge - investorAge);
	//difretage = parseInt(difretage);
		
	//if (difretage > 50)
//	{
//		alert("Your investor has a considerable time left before retirement, therefore, please can you contact the Business Support Team on 08456 410410 for an illustration.");
//		return false;
//	}				


	return true;
}

//---------------------------------------------------------------------
/// <summary>
/// cfValidateExpectedRetirementAge
/// </summary>
//---------------------------------------------------------------------

function cfWarningRetirementAge(lowPensionAge, expectedRetirementAge)
{
	var currentYear = new Date();
/*
	//Warning message for < Low Pension Age or < 50 if no low pension age		
	if (lowPensionAge.length > 0 && lowPensionAge != 0 )
	{
		if ( expectedRetirementAge < parseInt(lowPensionAge) )
		{
			var blnAnswer = new Boolean();

			blnAnswer = window.confirm("Warning: The retirement age is less than the low pension age of " +  lowPensionAge);
			
			if ( !blnAnswer )
			{
				return false;	
			}
		}
	}
	else
	{
*/
/*		if (currentYear.getFullYear() >= 2006 && currentYear.getFullYear() <= 2010)
		{
			if ( expectedRetirementAge < 50 )
			{
				var blnAnswer = new Boolean();
	
				blnAnswer = window.confirm("Warning: The retirement age is less than 50");
				
				if ( !blnAnswer )
				{
					return false;	
				}
			}
		}
		else
		{
			if ( expectedRetirementAge < 55 )
			{
				var blnAnswer = new Boolean();
	
				blnAnswer = window.confirm("Warning: The retirement age is less than 55");
				
				if ( !blnAnswer )
				{
					return false;	
				}
			}
		}
//	}		
*/
	return true;		
}
//---------------------------------------------------------------------
/// <summary>
/// cfValidateSpouseAge
/// </summary>
//---------------------------------------------------------------------

function cfValidateSpouseAge(spouseAge)
{

	if (spouseAge < 16)
	{
		alert("Spouse/civil partner must be aged 16 or older");
		return false;
	}
	
	return true;
}

function cfShowProcessing()
{
	document.getElementById('tdProcessing').innerHTML = gProcessingMessage;
	document.getElementById('divProcessing').style.visibility = 'visible';
}

//---------------------------------------------------------------------
/// <summary>Returns integer year since date passed in</summary>
//---------------------------------------------------------------------
function GetAgeAtDate( investorYYYY, investorMM, investorDD, enteredYYYY, enteredMM, enteredDD  )
{
	var birthday = new Date( investorYYYY, investorMM-1, investorDD );
	
	var enteredDate = new Date( enteredYYYY, enteredMM-1, enteredDD );

	var years = enteredDate.getFullYear() - birthday.getFullYear();

	birthday.setYear( enteredDate.getFullYear() );
 
	return( ( enteredDate < birthday ) ? --years : years );
}

//---------------------------------------------------------------------
/// <summary>
/// cfValidateTFCAge
/// </summary>
//---------------------------------------------------------------------

function cfTFCAge(TFCAge, investorAge, lowPensionAge)
{
	var ageToCheck;
	var currAgePlus1;
	
	var currentYear = new Date();

	var currAgePlus1 = investorAge + 1;

	if (lowPensionAge.length > 0 && lowPensionAge != 0 )
	{
		if ( parseInt(lowPensionAge) > currAgePlus1)
		{
			ageToCheck = parseInt(lowPensionAge);
		}
		else
		{
			ageToCheck = currAgePlus1
		}	
	}
	else
	{
		if (currAgePlus1 < 50)
		{
			if (currentYear.getFullYear() >= 2006 && currentYear.getFullYear() <= 2010)
			{
				ageToCheck = 50;
			}
			else
			{
				ageToCheck = 55;
			}
		}
		else
		{
			ageToCheck = currAgePlus1;
		}
	}

	if (ageToCheck == 74)
	{
		if (TFCAge != 74)
		{
			alert("The age tax free cash is expected to be taken must be 74");
			return false;
		}	
	}
	else
	{
		if (ageToCheck > 74)
		{
			if (TFCAge > 74)
			{
				alert("The age tax free cash is expected to be taken must be less than 75");
				return false;
			}	
		}
		else
		{	
			if ((TFCAge < ageToCheck) || ( TFCAge > 74 ))
			{
				alert("The age tax free cash is expected to be taken must be between " + ageToCheck + " and 74 inclusive");
				return false;
			}
		}	
	}
	
	return true;
}

//---------------------------------------------------------------------
/// <summary>
/// cfValidateAgeFirstIncWith
/// </summary>
//---------------------------------------------------------------------

function cfValidateAgeFirstIncWith(dateFirstIncWithAge, investorAge, lowPensionAge)
{
	var ageToCheck;
	var currAgePlus1;
	
	var currentYear = new Date();

	var currAgePlus1 = investorAge + 1;

	if (lowPensionAge.length > 0 && lowPensionAge != 0 )
	{
		if ( parseInt(lowPensionAge) > currAgePlus1)
		{
			ageToCheck = parseInt(lowPensionAge);
		}
		else
		{
			ageToCheck = currAgePlus1
		}	
	}
	else
	{
		if (currAgePlus1 < 50)
		{
			if (currentYear.getFullYear() >= 2006 && currentYear.getFullYear() <= 2010)
			{
				ageToCheck = 50;
			}
			else
			{
				ageToCheck = 55;
			}
		}
		else
		{
			ageToCheck = currAgePlus1;
		}
	}

	if (ageToCheck == 75)
	{
		if (dateFirstIncWithAge != 75)
		{
			alert("The age first income withdrawal is expected to be taken must be 75");
			return false;
		}	
	}
	else
	{
		if (ageToCheck > 75)
		{
			if (dateFirstIncWithAge > 75)
			{
				alert("The age first income withdrawal is expected to be taken must be less than 76");
				return false;
			}	
		}
		else
		{	
			if ((dateFirstIncWithAge < ageToCheck) || ( dateFirstIncWithAge > 75 ))
			{
				alert("The age first income withdrawal is expected to be taken must be between " + ageToCheck + " and 75 inclusive");
				return false;
			}
		}	
	}
	
	return true;
}


//---------------------------------------------------------------------
/// <summary>Returns the domain for the current url</summary>
//---------------------------------------------------------------------

function GetCurrentDomain()
{

	var host = new String( location.hostname );

	if( host.toLowerCase() == "localhost" )
	{
		return host;
	}

	var arrDomain = new Array();
	arrDomain = host.split(".");
	
	var selestia = new Boolean();
	
	selestia = false;
	
	var domain = new String( GetParameterValue( "Constants.DomainCompanyPart" ) );
	
	for(i = 0; i < arrDomain.length ; i++)
	{
		if( arrDomain[i].toLowerCase() == domain )
		{
			selestia = true;
			continue;
		}
		
		if( selestia )
		{
			domain += "." + arrDomain[i].toLowerCase();
		}
	}
	
	return domain;

}
//---------------------------------------------------------------------
/// <summary>
/// Work out the last day of the month for an entered month and year
/// </summary>
//---------------------------------------------------------------------

function cfLastDayOfTheMonth(endDate)
{
	var month = endDate.getMonth();
	var daysInMonth;

	if ( (month == 1) || (month == 3) || (month == 5) || (month == 7) || (month == 8) || (month == 10) || (month == 12))
	{
		daysInMonth = 31;
	}
	else
	{
		if (month == 2) 
		{
			if (cfIsLeapYear(endDate.getFullYear()))
			{
				daysInMonth = 29;
			}
			else
			{
				daysInMonth =  28;
			}
		}
		else
		{
			daysInMonth = 30;
		}
	}
			 
	return	daysInMonth;
}


//---------------------------------------------------------------------
/// <summary>
/// returns true if year entered is a leap year, false if not
/// </summary>
//---------------------------------------------------------------------

function cfIsLeapYear(year)
{

	if ((year % 4) > 0 )
	{
		//Not divisible by 4 therefore not leap year.	
		return false;
	}
	else
	{
		if ((year % 100) > 0 )
		{
		//Is not divisible by 100 so definitely is a leap year since it is divisible by 4.
			return true;
		}
		else
		{
			if ((year % 400) > 0 )
			{
			//Not divisible by 400 so not a leap year
				return false;
			}
			else
			{
			//Divisible by 400 so must be a leap year.
				return true;
			}
		}
	}
	
} 
//---------------------------------------------------------------------
/// <summary>
/// Get an end date a specified number of months from today
/// </summary>
//---------------------------------------------------------------------

function cfGetEndDate(inputDate, noOfMonths)
{
	var inputDayOfMonth = parseInt(inputDate.getDate());
	var inputMonth = parseInt(inputDate.getMonth());
	var inputYear = parseInt(inputDate.getFullYear());
	
	var monthToCalc;
	var yearToCalc;
	
	if (inputMonth >= 10)
	{
		monthToCalc = (inputMonth + noOfMonths) - 10;
		yearToCalc = inputYear + 1;
	}
	else
	{
		monthToCalc = inputMonth + noOfMonths;
		yearToCalc =  inputYear;
	}

	
	var endDate = new Date(yearToCalc, monthToCalc, "01");
	
	var lastDayOfMonth = cfLastDayOfTheMonth(endDate);


	if (inputDayOfMonth >= lastDayOfMonth  ) 
	{
		endDate.setDate(lastDayOfMonth);
	}
	else
	{

		endDate.setDate(inputDayOfMonth);
	}

	return endDate;

}

//---------------------------------------------------------------------
/// <summary>
/// Get month and year investor will be 75
/// </summary>
//---------------------------------------------------------------------

function cfGetMMYYAtAge( investorDOBMM, investorDOBYYYY, desiredAge )
{
	investorDOBYYYY = parseInt( investorDOBYYYY );
	investorDOBMM = parseInt( investorDOBMM );

	var year = new Number();
	
	year = investorDOBYYYY + parseInt( desiredAge ) ;
	
	return "" + monthNames[ investorDOBMM ] + " " + year;
	
}

//---------------------------------------------------------------------
/// <summary>
/// cfValidateExpectedRetirementAge
/// </summary>
//---------------------------------------------------------------------

function cfExpectedRetirementDate(expectedRetirementDateMM, expectedRetirementDateYYYY, investorAge, lowPensionAge, investorYYYY, investorMM, investorDD )
{
	var currentDate = new Date();
	currentDate.setHours(0,0,0,0);
		
	var retireDD	= "01";
	var retireMM	= expectedRetirementDateMM;
	var retireYYYY	= expectedRetirementDateYYYY;				

	var currentYYYY =  currentDate.getFullYear();
	var currentMM =  currentDate.getMonth() + 1;
	
	var earliestRetireMM = new Number( currentMM );
	var earliestRetireYYYY = new Number( currentYYYY );
	
	if( ( parseInt(currentMM) + 1 ) > 12 )
	{
		earliestRetireMM = "01";
		earliestRetireYYYY = currentYYYY + 1;
	}
	else
	{
		earliestRetireMM = currentMM + 1;
	}
	
	var expRetireDate = new Date(retireYYYY, retireMM - 1, retireDD); 

	expRetireDate.setHours(0,0,0,0);

	if (expRetireDate <= currentDate)
	{
		alert( "Expected retirement date must be greater than today's date" );
		return false;
	}	
	
	if( investorMM.charAt(0) == "0" )
	{
		investorMM = investorMM.substr(1,1);
	}
	
	investorMM = parseInt( Trim(investorMM) );
	
	var ageToCheck = new Number();
	
	if (lowPensionAge.length > 0 && lowPensionAge != 0 )
	{
		if ( parseInt(lowPensionAge) > investorAge)
		{
			ageToCheck = parseInt( lowPensionAge );
			earliestRetireYYYY = earliestRetireYYYY + ( lowPensionAge - investorAge );
		}
		else
		{
			if( investorAge < 50 )
			{
				ageToCheck = 50;
				earliestRetireYYYY = earliestRetireYYYY + ( investorYYYY + 50 );
			}
		}	
		
		earliestRetireMM = investorMM;
	}	
	else
	{
		if( investorAge <= 50 )
		{
			ageToCheck = 50;
			earliestRetireYYYY = parseInt( investorYYYY ) + 50;
			earliestRetireMM = investorMM;
		}	
		else
		{
			ageToCheck = investorAge;
		}
	}
	
	/*				
	if(  retireYYYY == currentYYYY  )
	{
		if( retireMM == currentMM )
		{
			if( ( parseInt(retireMM) + 1 ) > 12 )
			{
				alert( "The earliest possible retirement date is 01/" + (currentYYYY + 1) );
			}
			else
			{
				alert( "The earliest possible retirement date is " + ( parseInt(currentMM) + 1 ) + "/" + currentYYYY );
			}
			return false;						
		}
	}	
	*/	
	
	var ageAtDate = GetAgeAtDate( investorYYYY, investorMM, investorDD, retireYYYY, retireMM, retireDD  );
	
	//alert( "ageToCheck\t" + ageToCheck + "\ninvestorAge\t" + investorAge + "\nageAtDate\t" + ageAtDate);
	
	ageAtDate = parseInt( ageAtDate );
	
	if( ageAtDate < ageToCheck )
	{
		alert( "The retirement date must be between " + monthNames[ earliestRetireMM ] + " " + earliestRetireYYYY + " and " +  cfGetMMYYAtAge( investorMM , investorYYYY, 75 ) + ", when you reach the age of 75." );			
		return false;
	}
	
	if( ageAtDate > 75 )
	{
		alert( "The retirement date must be between " + monthNames[ earliestRetireMM ] + " " + earliestRetireYYYY + " and " +  cfGetMMYYAtAge( investorMM, investorYYYY, 75 ) + ", when you reach the age of 75." );		
		return false;
	}
	
	return true;

}

//---------------------------------------------------------------------
/// <summary>
/// enable required fields
/// </summary>
//---------------------------------------------------------------------

function enableRequiredFields()
{
	for( var i =0; i<gArrFieldsRequired.length; i++ )
	{
	if(document.getElementById(gArrFieldsRequired[i]) != null)
	{
		if( document.getElementById(gArrFieldsRequired[i]).value == '' )
		{
			document.getElementById(gArrFieldsRequired[i]).onkeyup = function (evt) { validateRequired( this ); }
			if( document.getElementById(gArrFieldsRequired[i]).value == '' )
			{
				document.getElementById('div_'+gArrFieldsRequired[i]).style.visibility = 'visible';
			}
		}
	 }
	}
}


//---------------------------------------------------------------------
/// <summary>
/// validate required fields
/// </summary>
//---------------------------------------------------------------------

function validateRequired( fieldElement )
{
	
	var fieldId = fieldElement.name;
	
	if( document.getElementById(fieldId).value == '' )
	{  
		document.getElementById('div_'+fieldId).style.visibility = 'visible';
	}
	else
	{
		document.getElementById('div_'+fieldId).style.visibility = 'hidden';
	}
					
}

//---------------------------------------------------------------------
/// <summary>
/// popup blocker resistant window - no toolbars (Sean Jarvis)
/// </summary>
//--------------------------------------------------------------------</>-

function wopen(url, name, w, h)
{
w += 22;
h += 96;
 var win = window.open(url,
  name, 
  'width=' + w + ', height=' + h + ', ' +
  'location=no, menubar=no, ' +
  'status=no, toolbar=no, scrollbars=yes, resizable=no');
 win.resizeTo(w, h);
 win.focus();
}



//---------------------------------------------------------------------
// Image randomizer
//--------------------------------------------------------------------</>-

var theImages = new Array() // do not change this

// To add more image files, continue with the pattern below, adding to the array. Rememeber to increment the theImages[x] index!

theImages[0] = '/images/headers/Hdr_Skandia_1200_01of11.jpg'
theImages[1] = '/images/headers/Hdr_Skandia_1200_02of11.jpg'
theImages[2] = '/images/headers/Hdr_Skandia_1200_03of11.jpg'
theImages[3] = '/images/headers/Hdr_Skandia_1200_04of11.jpg'
theImages[4] = '/images/headers/Hdr_Skandia_1200_05of11.jpg'
theImages[5] = '/images/headers/Hdr_Skandia_1200_06of11.jpg'
theImages[6] = '/images/headers/Hdr_Skandia_1200_06of11.jpg'
theImages[7] = '/images/headers/Hdr_Skandia_1200_07of11.jpg'
theImages[8] = '/images/headers/Hdr_Skandia_1200_08of11.jpg'
theImages[9] = '/images/headers/Hdr_Skandia_1200_09of11.jpg'
theImages[10] = '/images/headers/Hdr_Skandia_1200_10of11.jpg'
theImages[11] = '/images/headers/Hdr_Skandia_1200_11of11.jpg'

// ======================================
// do not change anything below this line
// ======================================

var j = 0
var p = theImages.length;

var preBuffer = new Array()
for (i = 0; i < p; i++){
   preBuffer[i] = new Image()
   preBuffer[i].src = theImages[i]
}

var whichImage = Math.round(Math.random()*(p-1));
function showImage(){
//document.write('<img src="'+theImages[whichImage]+'">');
if( document.getElementById("tblRandomImage") )
{
document.getElementById("tblRandomImage").background=theImages[whichImage];
}
}

function ValidateFutureDate( dd,mm,yyyy )
{
	var bDate = new Date( yyyy, mm-1, dd );
	bDate.setHours( 0, 0, 0, 0 );	
	
	var today = new Date();
	today.setHours( 0, 0, 0, 0 );	
		
	if( bDate > today )
	{
		return false;
	}
	else
	{
		return true;
	}
}
//----------------------------------------------------------------------------
/// Begin : New method getDtTime is used for datetime stamp for UserExperience
//----------------------------------------------------------------------------
function getDtTime()
{
	var dt = new Date();
	var month = dt.getMonth();
	var days = dt.getDate();
	var hours = dt.getHours();
	var minutes = dt.getMinutes();
	var seconds = dt.getSeconds();
	var milliseconds = dt.getMilliseconds();

	month = parseFloat(month) + 1;
	
	if ( month.toString().length == 1 )
	{
		month = "0" + month;
	}
	
	if ( days.toString().length == 1 )
	{
		days = "0" + days;
	}
	
	if ( hours.toString().length == 1 )
	{
		hours = "0" + hours;
	}
	
	if ( minutes.toString().length == 1 )
	{
		minutes = "0" + minutes;
	}
	
	if ( seconds.toString().length == 1 )
	{
		seconds = "0" + seconds;
	}
	
	/* // Pads milliseconds to 3 digits
	if ( milliseconds.toString().length == 1 )
	{
		milliseconds = milliseconds + "00";
	}
	else if ( milliseconds.toString().length == 2 )
	{
		milliseconds = milliseconds + "0";
	}
	*/

	//var dtTime = dt.getFullYear() + '-' + month  +'-' + dt.getDate() + ' ' + dt.getHours() + ':' + dt.getMinutes() + ':' + dt.getSeconds() + ':' + dt.getMilliseconds();
	var dtTime = dt.getFullYear() + '-' + month  + '-' + days + ' ' + hours + ':' + minutes + ':' + seconds + '.' + milliseconds;

	return ( dtTime );
}
//-End

//------------------------------------------------------------------------------
// Begin 
// saveUserExperience is used to save UserExperience details using AJAX
//------------------------------------------------------------------------------
function saveUserExperience( type )
{
	var url = new String();
	var userDetails = new String();
	var dateTime = getDtTime();
	if ( document.getElementById( 'hidUserExpID1' ) != null )
	{
		var uniquePageID1 = document.getElementById( 'hidUserExpID1' ).value;
		var uniquePageID2 = document.getElementById( 'hidUserExpID2' ).value;
		var pageID = document.getElementById( 'hidWPID' ).value;  
		var userExpURL = document.getElementById( 'hidUrlHost' ).value;
		if ( uniquePageID1 == '' )
		{
			uniquePageID1 ='null';
		}
		
		userDetails =  pageID + '|' + dateTime + '|' + uniquePageID1 + '|' + uniquePageID2 + '|' + type ;
		
		url = 'http://' + userExpURL  + '/Skandia/UserExperience.aspx?userExpDts=' + userDetails ;
		
		// Make HTTP call
		AJAX( "GET", url );
	}
}
// End
// Error handling - JSON

//---------------------------------------------------------------------
/// Constants variable
//---------------------------------------------------------------------	

var Constants = null;

//---------------------------------------------------------------------
/// Returns parameter value for parameter name
//---------------------------------------------------------------------	


function GetParameterValue( parameterName )
{

	var hier = new Array();
	
	hier = parameterName.split( "." );
	
	//---------------------------------------------------------------------
	/// If only one level deep, assume value must come from constants
	//---------------------------------------------------------------------		
	
	if( hier.length == 1 )
	{
		SetupParametersConstants();
		return eval( "Constants." + hier[0] );
	}
	
	//---------------------------------------------------------------------
	/// Setup JSON object based on first part of parameter passed in
	//---------------------------------------------------------------------	
	
	try
	{	
		eval( "SetupParameters" + hier[0] + "()" );
	}
	catch( exc )
	{
		var errorMessage = new String();
		
		errorMessage = "Cannot find method " + "SetupParameters" + hier[0] + "()";
		errorMessage += "\n";
		errorMessage += "You must define this method in your .js";
		
		return errorMessage;
	}
	
	//---------------------------------------------------------------------
	/// Return parametervalue
	//---------------------------------------------------------------------	
			
	return eval( parameterName )
}

function AJAX( method, url )
{
	var xmlHttp = null;

	try
	{
		xmlHttp = new XMLHttpRequest();
	}
	catch (e)
	{
		// Internet Explorer
		try
		{
			xmlHttp = new ActiveXObject( "Msxml2.XMLHTTP" );
		}
		catch (e)
		{
			try
			{
				xmlHttp = new ActiveXObject( "Microsoft.XMLHTTP" );
			}
			catch (e)
			{
				return false;
			}
		}
	}
	
	xmlHttp.open( method.toUpperCase(), url, true );
		
	xmlHttp.send( null );
	
	xmlHttp = null;
}

//---------------------------------------------------------------------
/// <summary>
/// String format - behaves in exactly the same way as 
/// the c# String.Format method
/// </summary>
//---------------------------------------------------------------------

function cfStringFormat( stringToFormat, args)
{
	var tempString = new String( "" );
	
	tempString = stringToFormat;
	
	if( cfStringFormat.arguments.length > 1 )
	{
		var idx = new Number();
		
		for( idx = 1; idx <= cfStringFormat.arguments.length; idx++ )
		{
			var pattern = "\\{" + (idx-1) + "\\}";
			var regExpr = new RegExp(pattern,'g');
			tempString = tempString.replace(regExpr,  cfStringFormat.arguments[idx] );
		}
	}		
	
	return tempString;
}

//---------------------------------------------------------------------
/// <summary>
/// Interception point for client-side alerts
/// </summary>
//---------------------------------------------------------------------

function cfAlert( stringToAlert )
{
	alert( stringToAlert );
}

//------------------------------------------------------------------------
/// <summary>
/// Replace all characters passed as the input character
/// with replacement character
/// </summary>
//---------------------------------------------------------------------

function ReplaceCharacter(controlName, replaceChar, replaceWithChar) {
    var controlArray = document.getElementsByName(controlName);

    if (controlArray != null) {
        var getValue = "";
        var setValue = "";

        if (controlArray.length > 0) {
            for (i = 0; i < controlArray.length; i++) {
                getValue = controlArray[i].value;
                setValue = controlArray[i].value.replace(replaceChar, String.fromCharCode(replaceWithChar));
                controlArray[i].value = setValue;
            }
        }
    }
}

function ReplaceComboCharacter(controlName, replaceChar, replaceWithChar) 
{
    var controlArray = document.getElementsByName(controlName);

    if (controlArray != null) {
        var getValue = "";
        var setValue = "";

        if (controlArray.length > 0) {
            for (i = 0; i < controlArray.length; i++) {
                for (j = 0; j < controlArray[i].options.length; j++) {
                    getValue = controlArray[i].options[j].value;
                    setValue = controlArray[i].options[j].value.replace(replaceChar, replaceWithChar);
                    controlArray[i].options[j].value = setValue;
                }
            }
        }
    }
}

//------------------------------------------------------------------------
/// <summary>
/// Replace all occurrences of specified string with replacement string
/// </summary>
//---------------------------------------------------------------------

function cfStringReplace( stringToFormat, findString, replaceString )
{	
	var tempString = new String( "" );
	
	tempString = stringToFormat;
	
	var regExpr = new RegExp( findString, 'g' );
	
	tempString = tempString.replace( regExpr, replaceString );

	return tempString;
}