//© Copyright SoftAware Ltd 2007
var winPopUp = null;
var AAS_URL = "news/aas.htm";
var WPSS_URL = "news/wpss.htm";
var TA_URL = "news/ta.htm";
var ITS_URL = "news/its.htm";
var SEMINAR_URL = "news/seminar.htm";
var ITS1_URL = "news/its1_04_2005.htm";
var ANN_PUR_Q_URL = "news/ann_pur_q.htm";
var ANN_PUR_R_URL = "news/ann_pur_r.htm";
var LATEST_BROCHURE_URL = "news/latest_brochure.htm";
var MNFR_URL = "news/mnfr.htm";
var PRIVACY_URL = "/privacy.htm";
var PA2004Seminar_URL = "/news/pa2004_seminar.htm";
var survey_login_URL = "/news/survey_login.aspx";
var annuity_calc_latest_news_URL = "/news/annuity_calc.htm";
var ln_2007_07_04_URL = "/news/ln_2007_07_04.htm";

// Blink Text Variables
var on_color = "#000000";
var off_color = "#CCCCCC";
var blink_onoff = 1;
var blinkrate= 1000;

function CorrectFrame(pageObject){
	var correct_frame = 0 + (parent.nav ? 1 : 0);
	//try
	//{
		if (parent.location.href == self.location.href)
		{
			window.location.href = 'index.htm?'+pageObject;
		}
	//}
	//catch
	//{
	//	window.location.href = 'index.htm?'+pageObject;
	//}
}



// This function creates a popup window with set properties
function CreatePopUp(target,name,w,h,scroll,pos,res){
    var LeftPos = 50
    var TopPos = 50
    var objWin;

    if(pos=="center"){
        LeftPos=(screen.width)?(screen.width-w)/2:100;
        TopPos=(screen.height)?(screen.height-h)/2:100;
    }
    var settings='width='+w+',height='+h+',top='+TopPos+',left='+LeftPos+',scrollbars='+scroll+',location=no,directories=no,status=no,menubar=no,fullscreen=no,toolbar=no,resizable='+res;

    objWin = window.open(target,name,settings);
    objWin.focus();
    return objWin;
}

// The following functions launch the news items
function launchMNFR(){
    winPopUp = CreatePopUp(MNFR_URL,'new',610,350,'yes','center','no');
}

function launchWPSS(){
    winPopUp = CreatePopUp(WPSS_URL,'new',610,250,'no','center','no');
}

function launchAAS(){
    winPopUp = CreatePopUp(AAS_URL,'new',610,280,'no','center','no');
}

function launchTA(){
    winPopUp = CreatePopUp(TA_URL,'new',610,250,'no','center','no');
}

function launchITS(){
    winPopUp = CreatePopUp(ITS_URL,'new',610,250,'no','center','no');
}

function launchSeminar(){
    winPopUp = CreatePopUp(SEMINAR_URL,'new',610,260,'no','center','no');
}

function launchITS1(){
    winPopUp = CreatePopUp(ITS1_URL,'new',610,260,'no','center','no');
}

function launchAnn_Pur_Q(){
    winPopUp = CreatePopUp(ANN_PUR_Q_URL,'new',610,230,'no','center','no');
}

function launchAnn_Pur_R(){
    winPopUp = CreatePopUp(ANN_PUR_R_URL,'new',610,230,'no','center','no');
}

function launch_latest_brochure(){
    winPopUp = CreatePopUp(LATEST_BROCHURE_URL,'new',610,230,'no','center','no');
}

function launchPrivacy(){
    winPopUp = CreatePopUp(PRIVACY_URL,'new',610,400,'yes','center','no');
}

function LaunchIdeasSheetsPopUp(sPage){
	winPopUp = CreatePopUp(sPage,'new',610,320,'no','center','no');
}

function launchCV(url){
    winPopUp = CreatePopUp(url,'new',610,400,'yes','center','no');
}

function launchPA2004Seminar(){
    winPopUp = CreatePopUp(PA2004Seminar_URL,'new',610,470,'yes','center','no');
}

function launchSurveyLogin(){
    winPopUp = CreatePopUp(survey_login_URL,'new',610,240,'yes','center','no');
}

function launchAnnuityCalcLatestNewsPopup(){
    winPopUp = CreatePopUp(annuity_calc_latest_news_URL,'new',610,240,'yes','center','no');
}

function launch_ln_2007_07_04(){
    winPopUp = CreatePopUp(ln_2007_07_04_URL,'new',610,375,'yes','center','no');
}

// This function prints the page
function printPage(){
   window.print();
}

// This function takes the current page back once
function goBack(){
    window.history.back(-1);
}

// This function closes the active window
function quitPage(){
    window.close();
}

// This function resets an HTML form
function clearForm(){
    document.docForm.reset();
}

// This function submits an HTML form
function submitForm(){
    document.docForm.submit();
}

function calculateTotal(){
	var purchaseA;
	var purchaseB;
	var total;

	purchaseA = document.docForm.txtPurchaseA.value;
	purchaseB = document.docForm.txtPurchaseB.value;
	total = document.docForm.txtTotal.value;

	if(purchaseA == ''){
		purchaseA = 0;
	}
	if(purchaseB == ''){
		purchaseB = 0;
	}

	if(isNaN(parseFloat(purchaseA)) || isNaN(parseFloat(purchaseB))){
		total = ''
		// Display the total in txtTotal
		document.docForm.txtTotal.value = total;
	}	
	else{
		// Display the total in txtTotal
		document.docForm.txtTotal.value = eval(parseFloat(purchaseA) + parseFloat(purchaseB))
		if(document.docForm.txtTotal.value > 120000){
			alert("Better rates may be available due to the high \purchase price, please contact us for further details")
		}
	}	
}

function disableTextbox(){
	document.docForm.txtTotal.blur();
}

function checkPartnerPension(){
	var partnerPension;
	if (document.docForm != null){
		partnerPension = document.docForm.cmbPartnerPension.value;
		if(partnerPension == 'SNG' || partnerPension == ''){
			document.docForm.txtPartnerAge.value = '';
			document.docForm.txtPartnerAge.disabled = true;
		}
		else{
			document.docForm.txtPartnerAge.disabled = false;
		}	
	}	
}

function checkEmail(emailStr)
{
    var emailPat=/^(.+)@(.+)$/
    var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
    var validChars="\[^\\s" + specialChars + "\]"
    var quotedUser="(\"[^\"]*\")"
    var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
    var atom=validChars + '+'
    var word="(" + atom + "|" + quotedUser + ")"
    var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
    var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")


    //need a check that will look to see that if the last two characters of the string are .uk then
    // there needs to be either a .co.uk or a .org.uk or somthing similar...this means the
    //script deviates from the typical checks make...but it was failed by the test team
    //because someone@rubusco.uk was allowed, so this is added
    var nStartUK = emailStr.lastIndexOf('.uk')
    //if the uk thing is the last part of their email address
    if (nStartUK == emailStr.length -3)
    {
        if( (emailStr.indexOf('.co.uk') == -1) &&
                (emailStr.indexOf('.org.uk') == -1) &&
                (emailStr.indexOf('.gov.uk') == -1) &&
                (emailStr.indexOf('.ac.uk') == -1) &&
                (emailStr.indexOf('.com.uk') == -1) &&
                (emailStr.indexOf('.net.uk') == -1) )
        {
            return false
        }
    }
    //the end of the mail for UK addresses changes

    var matchArray=emailStr.match(emailPat)
    if(matchArray==null)
    {
        return false
    }
    var user=matchArray[1]
    var domain=matchArray[2]

    if(user.match(userPat)==null)
    {
        return false
    }

    var IPArray=domain.match(ipDomainPat)
    if (IPArray!=null)
    {
        // this is an IP address
        for(var i=1;i<=4;i++)
        {
            if(IPArray[i]>255)
            {
                return false
            }
        }
        return true
    }
    var domainArray=domain.match(domainPat)
    if (domainArray==null)
    {
        return false
    }

    var atomPat=new RegExp(atom,"g")
    var domArr=domain.match(atomPat)
    var len=domArr.length
    if(domArr[domArr.length-1].length<2 || domArr[domArr.length-1].length>3)
    {
        return false
    }
    if(len<2)
    {
        return false
    }
    return true;
}

function validatePA2004Seminar(form){

	var fullName;
	var company;
	var position;
	var address1;
	var postcode;
	var phone;
	var email;
	var errorMessage;
	
	errorMessage = "";
	fullName = form.txtFullName.value;
	company = form.txtCompany.value;
	position = form.txtPosition.value;
	address1 = form.txtAddress1.value;
	postcode = form.txtPostcode.value;
	phone = form.txtPhone.value;
	email = form.txtEmail.value;
	
	//Full name
	if(fullName.length <= 0){
		errorMessage = errorMessage + "Please enter your name in full. \n";
	}
	//Company
	if(company.length <= 0){
		errorMessage = errorMessage + "Please enter the name of the company you work for. \n";
	}
	//Position
	if(position.length <= 0){
		errorMessage = errorMessage + "Please enter your position in the company you work for. \n";
	}
	//Address 1
	if(address1.length <= 0){
		errorMessage = errorMessage + "Please enter your address (at least one line must be entered). \n";
	}
	//Postcode
	if(postcode.length <= 0){
		errorMessage = errorMessage + "Please enter your postcode. \n";
	}
	//Phone
	if(phone.length <= 0){
		errorMessage = errorMessage + "Please enter your telephone number. \n";
	}
	//Email
	if(email.length <= 0){
		errorMessage = errorMessage + "Please enter your email address. \n";
	}
	else{
		if (checkEmail(email) == false){
			errorMessage = errorMessage + "The email address you have entered appears to be invalid. \n";
		}
	}
	//Decide whether to submit or not
	if (errorMessage.length > 0){
		alert(errorMessage);
	}
	else{
		form.submit();
	}
}

// ------------------------------------------------------------------------------
// Whitbread specific functions - Start
// ------------------------------------------------------------------------------
// This function is called by the onClick event for the Calculate button
function readyToCalculate(){
	var returnVal = false;
	returnVal = whitbreadCheckTotalPurchase();
	// Return to the caller
	if (returnVal == false){
		return false;
	}
	else{
		return true;
	}
}
// This function checks the total purchase price
function whitbreadCheckTotalPurchase(){
	var purchaseA;
	var purchaseB;
	var totalPurchase;
	var errorOccurred = false;
	// Grab the values entered from the form
	purchaseA = document.docForm.txtPurchaseA.value;
	purchaseB = document.docForm.txtPurchaseB.value;
	// Assign default values if no value entered
	if(purchaseA == ''){
		purchaseA = 0;
	}	
	if(purchaseB == ''){
		purchaseB = 0;
	}
	// Calculate total
	totalPurchase = eval(parseFloat(purchaseA) + parseFloat(purchaseB));
	// If the total is less than £750 then display alert box and do not submit the form
	if(totalPurchase < 750){
		alert("Total purchase price must be at least \u00A3750.")
		errorOccurred = true;
	}
	// Determine if error occured
	if (errorOccurred == true){
		return false;
	}
	else{
		return true;
	}
}
// ------------------------------------------------------------------------------
// Whitbread specific functions - End
// ------------------------------------------------------------------------------

// ------------------------------------------------------------------------------
// Blinking text function
// ------------------------------------------------------------------------------
function blink()
{
	if( blink_onoff == 1) {
           document.all.blink.style.color = on_color;
	   blink_onoff = 0;
	}
	else {
	   document.all.blink.style.color = off_color;
	   blink_onoff = 1;
	}
}
//-------------------------------------------------------------------------------

//------------------------------------------------------------------------------------
//Origo calc specific functions
//------------------------------------------------------------------------------------
function ShowHideTbodyStep1(ShowMarriedAlert){
	//Variable to determine whether the partner details checkbox is selected or not
	var objChkPartnerDetails
	var objChkPRFundExists
	var checkboxSelected = false
	var objDropDownMaritalStatus		
	var selIndex;
	
	objChkPartnerDetails = document.getElementById("chkPartnerDetails");
	objChkPRFundExists = document.getElementById("chkPRFundExists");
	objDropDownMaritalStatus=document.getElementById("cmbMaritalStatus");
	
	selIndex = objDropDownMaritalStatus.selectedIndex;
	
/*	if ((objDropDownMaritalStatus.options[selIndex].value=='Married')||(objDropDownMaritalStatus.options[selIndex].value=='Civil Partnership')){	
		objChkPartnerDetails.checked='True';
		if (ShowMarriedAlert=='True') {
			alert("If you have selected 'Married' or 'Civil Partnership' then partner details must be entered.");
		}
	} */
	if	((objChkPartnerDetails.checked == true)||(objChkPRFundExists.checked == true && (objDropDownMaritalStatus.options[selIndex].value=='Married'||objDropDownMaritalStatus.options[selIndex].value=='Civil Partnership'))){
		
		tbodyPartnerDetails.style.display = '';	
		document.docForm.txtHiddenPartnerDetails.value = 'True';
		document.docForm.txtHiddenHasPartner.value = 'True';
		
		if (objChkPartnerDetails.checked == true){
			document.docForm.txtHiddenChkPartnerDetails.value = 'True';
		}
		else{
			document.docForm.txtHiddenPartnerDetails.value = 'False';
		}
		if ((objChkPRFundExists.checked == true)&&(objDropDownMaritalStatus.options[selIndex].value=='Married')||(objDropDownMaritalStatus.options[selIndex].value=='Civil Partnership')){
			document.docForm.txtHiddenPRExists.value = 'True';
		}
		else{
			document.docForm.txtHiddenPRExists.value = 'False';
		}
	}
	else if (objChkPRFundExists.checked == true){
		tbodyPartnerDetails.style.display = 'none';	
		document.docForm.txtHiddenPartnerDetails.value = 'False';
		document.docForm.txtHiddenChkPartnerDetails.value = 'False';
		document.docForm.txtHiddenPRExists.value = 'True';
		document.docForm.txtHiddenHasPartner.value = 'False';
	}
	else{
		tbodyPartnerDetails.style.display = 'none';	
		document.docForm.txtHiddenPartnerDetails.value = 'False';
		document.docForm.txtHiddenChkPartnerDetails.value = 'False';
		document.docForm.txtHiddenPRExists.value = 'False';
		document.docForm.txtHiddenHasPartner.value = 'False';
	}
	return true;
}


//Function to appear or disapper fund increase dropdowns
/*function ShowHideTbodyStep3(){
	//
	var query
	var i=0
	var pairs
	var pos;
	
	//Get the querystring
	sQuery = window.location.search.substring(1);
	//Split the querystring into an array
	pairs = sQuery.split('&');
	
	//loop through pairs array to extract values
	 if (sQuery!=''){ 
		for (i; i<pairs.length; i++) {
			pos = pairs[i].indexOf('=');
			if (pos > 0) {
				//If npr qstring = 1 then we have a npr fund so display npr increase dropdown
				if (pairs[i].substring(0,pos)=='npr_increase' && pairs[i].substring(pos+1)==1){
					document.docForm.txtHiddenNprExists.value='True';
					tbody_npr_increase.style.display='';
				}
				//If pr qstring = 1 then we have a pr fund so display pr increase dropdown
				if (pairs[i].substring(0,pos)=='pr_increase' && pairs[i].substring(pos+1)==1){
					document.docForm.txtHiddenPrExists.value='True';
					tbody_pr_increase.style.display='';
				}
				//If partner = 1 then we have partner details so display overlap and anyspouse
				if (pairs[i].substring(0,pos)=='partner' && pairs[i].substring(pos+1)==1){
					tbody_overlap_anyspouse.style.display='';
					document.docForm.txtHiddenPartnerExists.value='True';
				}
				//else{
				//	document.docForm.txtHiddenPartnerExists.value='False';
				//}
			}
		}
	}
	else{
		if (document.docForm.txtHiddenNprExists.value=='True'){
			tbody_npr_increase.style.display='';
		}
		if (document.docForm.txtHiddenPrExists.value=='True'){
			tbody_pr_increase.style.display='';
		}
		if (document.docForm.txtHiddenPartnerExists.value=='True'){
			tbody_overlap_anyspouse.style.display='';
		}
	}
	return true;
} */

//Function to appear or disapper fund increase dropdowns and overlap anyspouse
function ShowHideTbodyStep3(){
var frm
frm = document.docForm
		
	if (frm.txtHiddenNprExists.value=='True'){
		tbody_npr_increase.style.display='';
	}
	if (frm.txtHiddenPrExists.value=='True'){
		tbody_pr_increase.style.display='';
	}
	if (frm.txtHiddenPartnerExists.value=='True'){
		tbody_overlap_anyspouse.style.display='';
	}
	ShowHideTbodyStep3StartDate();
	return true;
}

//Function to appear or disapper start date text box
function ShowHideTbodyStep3StartDate(){
var radASB

	radASB = document.docForm.radAnnuityStartBasis
	for (var i = 0;i < radASB.length; i++) {
			if (radASB[i].checked) {
				break
				}
			}
	if (radASB[i].value=='Specified Date'){
		tbody_start_date.style.display='';
	}
	else {
		tbody_start_date.style.display='none';
	}
	return true;
}

//Function to calculate the 25% tax free cash in step 2
function calculateResult(){
	var fundValue;
	fundValue = document.all.txtFund.value; 
	//Variable to determine whether the 25% tax free checkbox is selected or not
	var checkboxSelected = false;
	for(var i=0; i<document.docForm.elements.length; i++){
		if(document.docForm.elements[i].type == "checkbox"){
			if(document.docForm.elements[i].disabled == false && document.docForm.elements[i].checked == true){
				checkboxSelected = true;
			}
		}
	}
	//Action to take if the 25% tax free checkbox is selected	
	if (checkboxSelected == true){
		if (Number(fundValue)){
			document.all.spanResult.innerHTML = (fundValue * 0.75);
		}
		else{
			alert("Please enter a valid number in the textbox for the pension amount.");	
		}
	}
	else{
		document.all.spanResult.innerHTML = "No tax free cash chosen.";	
	}
}

function calculateTotalFundValue(){
	var purchaseA;
	var purchaseB;
	var total;

	purchaseA = document.docForm.txtFund_npr.value;

	if (null==document.docForm.txtFund_pr){
		purchaseB=0;
	}
	else{
		purchaseB = document.docForm.txtFund_pr.value;
	}

	total = document.docForm.txtTotalFund.value;
	
	if(purchaseA == ''){
		purchaseA = 0;
	}
	if(purchaseB == ''){
		purchaseB = 0;
	}
	
	if(isNaN(parseFloat(purchaseA)) || isNaN(parseFloat(purchaseB))){
		total = 'Please enter numbers only';
	}
	else{
		// Display the total in txtTotal
		if(purchaseA+purchaseB==0){
			total = 0.00;
		}
		else{
			total = formatCurrency(eval(parseFloat(purchaseA) + parseFloat(purchaseB)));
		}
	}
	// Display the total in txtTotal
	document.docForm.txtTotalFund.value = total;
}

function formatCurrency(strValue)
{
	strValue = strValue.toString().replace(/\$|\,/g,'');
	dblValue = parseFloat(strValue);
	blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
	dblValue = Math.floor(dblValue*100+0.50000000001);
	intUnits = dblValue%100;
	strUnits = intUnits.toString();
	dblValue = Math.floor(dblValue/100).toString();
	if(intUnits<10){
		strUnits = "0" + strUnits;
	}
	for (var i = 0; i < Math.floor((dblValue.length-(1+i))/3); i++)
		dblValue = dblValue.substring(0,dblValue.length-(4*i+3))+','+
		dblValue.substring(dblValue.length-(4*i+3));
	return (((blnSign)?'':'-') + '\u00A3' + dblValue + '.' + strUnits);
}

function disableTotalTextbox(){
	document.docForm.txtTotalFund.blur();
}

//Function to display help window
function launchHelpWindow(bookMark){
    winPopUp = CreatePopUp('/help/help.htm#'+ bookMark,'HelpWindow',500,190,'yes','center','no');
}

//When No Quote, we need to display the provider's error explanation to the user.
function launch_provider_error_details(q_string){
	if(q_string !=''){
		winPopUp = CreatePopUp('/calculators/origocalculator/step5_error_details.aspx?Provider='+ encodeURIComponent(q_string),'error_Window',500,150,'yes','center','no');;
	} 
}

