var thisDate = new Date();
var currentDay = thisDate.getDate();
var currentMonth = thisDate.getMonth()+1;
var currentYear = thisDate.getFullYear();


function validateform() {
			errors = '';
			
			if(!IsChecked(document.frmLeaddata.rdoPension.value == '')) errors += 'Please indicate whether you have a UK pension\n';
			//if((document.frmLeaddata.rdoPension[0].checked == false) && (document.frmLeaddata.rdoPension[1].checked == false)) errors += 'Please indicate whether you have a UK pension\n';			
			if(document.frmLeaddata.txtFirstName.value == '') errors += 'You must enter your first name\n';
			if(document.frmLeaddata.txtSurname.value == '') errors += 'You must enter your surname\n';
			if(document.frmLeaddata.txtHouse.value == '') errors += 'You must enter your house no.\n';
			if(document.frmLeaddata.txtRoad.value == '') errors += 'You must enter your road name\n';
			if(document.frmLeaddata.txtTown.value == '') errors += 'You must enter your town/city\n';
			if(document.frmLeaddata.txtCounty.value == '') errors += 'You must enter your county\n';			
			if(document.frmLeaddata.txtPostCode.value == '') errors += 'You must enter your postcode\n';
			if(!checkPostCode(document.frmLeaddata.txtPostCode.value)) errors += 'Please enter your postcode in the correct format\n';
			if(document.frmLeaddata.txtEmailAddress.value == '') errors += 'You must enter your contact email address\n';
			if(!isEmail(document.frmLeaddata.txtEmailAddress)) errors += 'Please enter your contact email address in the correct format\n';
			if((document.frmLeaddata.txtContactNumber.value == '') && (document.frmLeaddata.txtdayNumber.value == '') && (document.frmLeaddata.txtMobileNumber.value == '')) errors += 'You must enter at least one contact number.\n';	
			if(!document.frmLeaddata.txtContactNumber.value == '')
			{
				if(!IsNumeric(document.frmLeaddata.txtContactNumber.value)) errors += 'Please enter your telephone no. in the correct format\n';
			}
			if(!document.frmLeaddata.txtdayNumber.value == '')
			{
				if(!IsNumeric(document.frmLeaddata.txtdayNumber.value)) errors += 'Please enter your work telephone no. in the correct format\n';
			}
			if(!document.frmLeaddata.txtMobileNumber.value == '')
			{
				if(!IsNumeric(document.frmLeaddata.txtMobileNumber.value)) errors += 'Please enter your mobile no. in the correct format\n';
			}			
			if(document.frmLeaddata.txtDay.options[document.frmLeaddata.txtDay.selectedIndex].value == '0') errors += 'Please enter the DAY of your birth\n';
			if(document.frmLeaddata.txtMonth.options[document.frmLeaddata.txtMonth.selectedIndex].value == '0') errors += 'Please enter the MONTH of your birth\n';
			if(document.frmLeaddata.txtYear.value == '') errors += 'You must enter the YEAR of your birth\n';
			
			
			
			var day1 = document.frmLeaddata.txtDay.value;
			var month1 = document.frmLeaddata.txtMonth.value;
			if (((day1 > 29) && (month1 == 2)) || ((day1 > 30) && ((month1 == 4) || (month1 == 6) || (month1 == 9) || (month1 == 11)))) errors += 'Please enter a valid day of the month for your Date of Birth\n';
			var year = document.frmLeaddata.txtYear.value;
			if(!document.frmLeaddata.txtYear.value == '') 
			{
				if ((year >= 2006) || (year < 1850) || (year.length > 4) || (year.length < 4) || (year == 'yyyy'))
				{
					errors += 'Please enter a valid YEAR\n';
				}
			}
			
			/*
			var thisdate = new Date();
			var thismonth = new Date(thisdate.getMonth());
			var thisyear = new Date(thisdate.getFullYear());
					
			if (thismonth >=6)
			{
			thisyear++;
			}		
			var age = thisyear - year;
			if(age < 49.5) errors += 'You must be at least 49 and six months old to claim a pension annuity\n';
			*/
			if(!calculatedAge()) errors += 'You must be at between 49 and six months and 75 years old to eligible to investigate a pension annuity\n';
			
			var FundValue = document.frmLeaddata.txtFundValueUsed.value;
			var taxValue = document.frmLeaddata.txtFundsvalue.value;

			s = FundValue;
			filteredValues = ",";     // Characters to strip out
			var i;
			var returnString = "";
			for (i = 0; i < s.length; i++) 
			{  
				var c = s.charAt(i);
				if (filteredValues.indexOf(c) == -1) returnString += c;
			}
			FundValue = returnString;
			
			if(FundValue == '') errors += 'You must enter the amount of the fund being used to provide an annuity\n';
			if(!FundValue == '')
			{
			//alert(taxValue);
				if(FundValue < 20000) errors += 'It is unlikely Simply Retirement will be able to help unless the amount\n of the fund being used to provide an annuity is at least £20,000\n';
				if((FundValue < 27000) && (taxValue == 'Before tax free cash')) errors += 'It is unlikely Simply Retirement will be able to help unless the amount\n of the fund being used to provide an annuity is at least £27,000 before tax\n';
			}
			
			
									
			if(errors += '') {
				alert(errors);
				return false;
			} else {
				domCollapse('1');
				return true;				
			}
		}

function IsChecked(thisElement)
{
	// set var radioChecked to false
	var blnChecked = false;

	// Loop from zero to the one minus the number of radio button selections
	for (counter = 0; counter < frmLeaddata.rdoPension.length; counter++)
	{
	    // If a radio button has been selected it will return true
	    // (If not it will return false)
		//alert(frmLeaddata.rdoPension[counter].value);	   
	    if (frmLeaddata.rdoPension[counter].checked)
	        {
				//alert(frmLeaddata.rdoPension[counter].value);
				if(frmLeaddata.rdoPension[counter].value == 'NO')
				{
					//alert(frmLeaddata.rdoPension[counter].value);
					errors += 'You cannot progress any further if you do not have a UK pension\n';
					blnChecked = false;
				}
			blnChecked =  true;
	        }
	 }
	return blnChecked;
}		
function validateform2() 
{
	errors = '';
	var day1 = document.frmLeaddata.txtDay3.value;
	var month1 = document.frmLeaddata.txtMonth3.value;
	if (((day1 > 29) && (month1 == 2)) || ((day1 > 30) && ((month1 == 4) || (month1 == 6) || (month1 == 9) || (month1 == 11)))) errors += 'Please enter a valid day of the month for your retirement date\n';
	
	var day2 = document.frmLeaddata.txtDay2.value;
	var month2 = document.frmLeaddata.txtMonth2.value;
	if (((day2 > 29) && (month2 == 2)) || ((day2 > 30) && ((month2 == 4) || (month2 == 6) || (month2 == 9) || (month2 == 11)))) errors += 'Please enter a valid day of month for the Date of Birth of your partner\n';
		
	if(errors += '') 
	{
		alert(errors);
		return false;
	}
	else
	{
		domCollapse('1');
		return true;				
	}
}			


function checkPostCode (toCheck) {
  // This array holds the regular expressions for the valid postcodes
  var pcexp = new Array ();

  // Expression for postcodes: AN NAA, ANN NAA, AAN NAA, and AANN NAA
  pcexp.push (/^([a-z]{1,2}[0-9]{1,2})(\s*)([0-9]{1}[abdefghjlnpqrstuwxyz]{2})$/i);

  // Expression for postcodes: ANA NAA, and AANA  NAA
  pcexp.push (/^([a-z]{1,2}[0-9]{1}[a-z]{1})(\s*)([0-9]{1}[abdefghjlnpqrstuwxyz]{2})$/i);
  
  // Exception for the special postcode GIR 0AA
  pcexp.push (/^(GIR)(\s*)(0AA)$/i);

  // Load up the string to check
  var postCode = toCheck;

  // Assume we're not going to find a valid postcode
  var valid = false;
  
  // Check the string against both post codes
  for ( var i=0; i<pcexp.length; i++) {
    if (pcexp[i].test(postCode)) {
    
      // The post code is valid - split the post code into component parts
      pcexp[i].exec(postCode);
      
      // Copy it back into the original string, converting it to uppercase and
      // inserting a space between the inward and outward codes
      
      postCode = RegExp.$1.toUpperCase() + " " + RegExp.$3.toUpperCase();
      
      // Load new postcode back into the form element
      valid = true;
      
      // Remember that we have found that the code is valid and break from loop

      break;
    }
  }
  
  // Return with either the reformatted valid postcode or the original invalid 
  // postcode
  //if (valid) {return postCode;} else return false;
  if (valid) {return true;} else return false;
}
 function IsNumeric(strString)
   //  check for valid numeric strings	
   {
	var strValidChars = "0123 456 789";
	var strChar;
	var blnResult = true;

	//if (strString.length == 0) return false;
	if (strString.length <= 10) return false;

	//  test strString consists of valid characters listed above
	for (i = 0; i < strString.length && blnResult == true; i++)
      {
      strChar = strString.charAt(i);
      if (strValidChars.indexOf(strChar) == -1)
         {
         blnResult = false;
         }
      }
	return blnResult;
	}

	
function isEmail(formInput)
// Check emailaddress structure
{
	var atPosition, dotPosition, lastPosition;
	with (formInput)
	{
		aPosition = value.indexOf("@");
		dotPosition = value.lastIndexOf(".");
		lastPosition = value.length-1;
		if (aPosition < 1 || dotPosition - aPosition < 2 || lastPosition - dotPosition > 3 || lastPosition - dotPosition < 2)
		{
			return(false);
		}
		return(true);
	}
}

function clearText(thefield)
{
	if (thefield.defaultValue == thefield.value)
	thefield.value = ""
}

function domCollapse(which)
{
  if (which=="0") 
	{
		domShowAll("section1"); 
		document.location.href = '#formtop';
		domHideAll("section2"); 
	} 
else if (which=="1") 
	{
		domShowAll("section2"); 
		document.location.href = '#formtop';
		domHideAll("section1");
		//domHideAll("secRetirementDate"); 
	} 
}
function onLoadDomCollapse(which)
{
  if (which=="0") 
	{
		domShowAll("section1"); 
		domHideAll("section2");
		//domHideAll("secRetirementDate");		
	} 
else if (which=="1") 
	{
		domShowAll("section2"); 
		domHideAll("section1");		
	} 
}
function domShowAll(section){

	//alert(section);
            if (document.getElementById && document.createTextNode){

                        //document.getElementById(section);
                        document.getElementById(section).style.display = "block";

            }

}
function domHideAll(section)
{
            if (document.getElementById && document.createTextNode)
            {
            //alert(section);
			//document.getElementById(section);
            document.getElementById(section).style.display = "none";
            }
}


function checkleapyear(datea)
{
	if(datea.getYear()%4 == 0)
	{
		if(datea.getYear()% 10 != 0)
		{
			return true;
		}
		else
		{
			if(datea.getYear()% 400 == 0)
				return true;
			else
				return false;
		}
	}
return false;
}
function DaysInMonth(Y, M) {
    with (new Date(Y, M, 1, 12)) {
        setDate(0);
        return getDate();
    }
}
function datediff(date1, date2) {
    var y1 = date1.getFullYear(), m1 = date1.getMonth(), d1 = date1.getDate(),
	 y2 = date2.getFullYear(), m2 = date2.getMonth(), d2 = date2.getDate();

    if (d1 < d2) {
        m1--;
        d1 += DaysInMonth(y2, m2);
    }
    if (m1 < m2) {
        y1--;
        m1 += 12;
    }
    return [y1 - y2, m1 - m2, d1 - d2];
}

function calculatedAge()
{
var calculatedDay = document.frmLeaddata.txtDay.value;
var calculatedMonth = document.frmLeaddata.txtMonth.value;
var calculatedYear = document.frmLeaddata.txtYear.value;
	if(currentDay == "" || currentMonth=="" || currentYear=="" || calculatedDay=="" || calculatedMonth=="" || calculatedYear=="")
	{
		alert("please fill all the values and click go -");
	}	
	else
	{
		var currentDate = new Date(currentYear,currentMonth-1,currentDay);
		var calculatedDate = new Date(calculatedYear,calculatedMonth-1,calculatedDay);
		
		var diff =  Date.UTC(currentYear,currentMonth,currentDay,0,0,0) - Date.UTC(calculatedYear,calculatedMonth,calculatedDay,0,0,0);

		var diffDate = datediff(currentDate,calculatedDate);
		
		//document.birthday.age.value=diffDate[0]+" years, "+diffDate[1]+" months, and "+diffDate[2]+" days";
		if((diffDate[0] > 49) && (diffDate[0] <= 75)) 
		{
			//alert("Over required age!");
		    return true;
		}
		else if ((diffDate[0] > 76))
		{
			//alert("Sorry, you are over the age limit to qualify for Equity Release")
			return false;
		}
		else
		{	
			if ((diffDate[0] = 49))
			{
				//alert("equal required age");
				if((diffDate[1] >= 6))
				{
					//alert("Over required age and months");
					return true;
				} 
				else
				{
					//alert("Not over required age by months");
					return false;
				} 
			}
		}

	}
}


