// JavaScript Document
/*
Author :		James Woodley
Date :			25 December 2005
Description :	This page contains all the different javascript functions for the PurplePassport Website
Exceptions :	If a javascript function needs some server side code, then it will be run on the page itself
*/

// Generic Scripts re-used throughout the site

var descriptionString;
var bufferString;
var maxStringLength = 3936;

function IsEmail(obj)
{
    var reEmail = new RegExp('^[a-z0-9\._-]+@[a-z0-9][a-z0-9_-]*(\.[a-z0-9_-]+)*'+
        '\.([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|'+
        'int|mil|museum|name|net|org|pro|travel)$', 'i');
    if (!reEmail.test(obj))
        return false;
    else
        return true;     
}

function GetTempID() {
    var result = "&tid=" + (Math.floor(Math.random() * 1000000000) + 1);
    return result;
}

function compareDates(date1, date2)
{
    
    var d = parseInt(date1.substring(0,2));
    var m = parseInt(date1.substring(3,5));
    var y = parseInt(date1.substring(6,10));
    
    var num1 = d + m * 100 + y * 1300;
    
    
    var d = parseInt(date2.substring(0,2));
    var m = parseInt(date2.substring(3,5));
    var y = parseInt(date2.substring(6,10));
    
    var num2 = d + m * 100 + y * 1300;
    
    if (num1 > num2) return -1;
    else if (num1 < num2) return 1;
    else return 0;
}

// Check length of the text in field "txtDescription" which was inputed from clipboard.
function CheckPaste(obj)
{
	descriptionString = obj.value;
    if (descriptionString.length >= maxStringLength)
	{
//		if ((window.event.keyCode != 46) && (window.event.keyCode != 35) && (window.event.keyCode != 33) && (window.event.keyCode != 8) && (window.event.keyCode != 36) && (window.event.keyCode != 39) && (window.event.keyCode != 40) && (window.event.keyCode != 37) && (window.event.keyCode != 38))
//		{
			bufferString = descriptionString.substr(0, maxStringLength);
			obj.value = bufferString;
//		}
	}
}

//Forbids entering any symbol in field "txtDescription" if this field already contains the maximum amount a symbols.
function DoKeyDown(obj)
{
    descriptionString = obj.value;
  
	if (descriptionString.length >= maxStringLength)
	{
		window.event.returnValue = false;
		if ((window.event.keyCode != 46) && (window.event.keyCode != 35) && (window.event.keyCode != 33) && (window.event.keyCode != 8) && (window.event.keyCode != 36) && (window.event.keyCode != 39) && (window.event.keyCode != 40) && (window.event.keyCode != 37) && (window.event.keyCode != 38))
		{
		}
		else
		{
			window.event.returnValue = true;
		}
	}
	return;
}

// This function takes the string and trims leading and following spaces
function trim(str) {
  try
  {     
	  return str.replace(/^\s*|\s*$/g,'');
	}
	catch(e)
	{
	  return str;
	}
}

function SelectSingleNode(xmlDoc, elementPath)
{
	if(window.ActiveXObject)
	{
		return xmlDoc.selectSingleNode(elementPath);
	}
	else
	{
		var xpe = new XPathEvaluator();
		var nsResolver = xpe.createNSResolver( xmlDoc.ownerDocument == null ? xmlDoc.documentElement : xmlDoc.ownerDocument.documentElement);
		var results = xpe.evaluate(elementPath,xmlDoc,nsResolver,XPathResult.FIRST_ORDERED_NODE_TYPE, null);
		return results.singleNodeValue; 
	}
}

// This function returns true if the typeof object is not undefined. In other words, it exists
function objectExists(theObject) {
	if ((typeof(theObject) == "undefined") || (theObject == null)) {
		return false;
	} else {
		return true;
	}
}

// Captures Enter Pressed
function checkEnter(e) 
{
	var characterCode;
	
	if (e && e.which) {
		e = e;
		characterCode = e.which;
	} 
	else 
	{
	  try
	  {
		  e = event;
		  characterCode = e.keyCode;
		}
		catch(e)
		{
		}
	}
	
	if (characterCode == 13) 
	{
		// Execute Function
		login_onSubmit();
	}
}




function createPayPalToken(passportType, purchasedAmount, cost) 
{
	//var grandTotal = document.getElementById('total').innerHTML;
				
	// Fill worldpay token for amount
	//document.paypal_checkout.amount.value = grandTotal.substring(1, grandTotal.length);
  if(purchasedAmount < 1)
  {
    purchasedAmount = 1;
    cost = 0;
  }
	switch (passportType) {
		case "oneyear":
			if (objectExists(document.paypal_checkout.item_name_1)) {
				document.paypal_checkout.quantity_1.value = purchasedAmount;
				document.paypal_checkout.amount_1.value = cost;				
			}
		break;
				
		case "fiveyear":
			if (objectExists(document.paypal_checkout.item_name_2)) {
			  document.paypal_checkout.quantity_2.value = purchasedAmount;
				document.paypal_checkout.amount_2.value = cost;				
			}
		break;
					
		case "tenyear":
			if (objectExists(document.paypal_checkout.item_name_3)) {
				document.paypal_checkout.quantity_3.value = purchasedAmount;
				document.paypal_checkout.amount_3.value = cost;				
			}
		break;
					
		case "lifetime":
			if (objectExists(document.paypal_checkout.item_name_4)) {
				document.paypal_checkout.quantity_4.value = purchasedAmount;
				document.paypal_checkout.amount_4.value = cost;				
			}
		break;
	}				

}
// This function fills out the worldpay purchase token whenever a purchase is being made
function createWorldpayToken(passportType, purchasedAmount, cost) {
	var grandTotal = document.getElementById('total').innerHTML;
				
	// Fill worldpay token for amount
	document.worldpay_checkout.amount.value = grandTotal.substring(1, grandTotal.length);
				
	// For the passportType selected fill the appropriate token with the amount purchased
	switch (passportType) {
		case "oneyear":
			if (objectExists(document.worldpay_checkout.MC_oneYear)) {
				document.worldpay_checkout.MC_oneYear.value = purchasedAmount;
				document.worldpay_checkout.MC_oneYearCost.value = cost;				
			}
		break;
				
		case "fiveyear":
			if (objectExists(document.worldpay_checkout.MC_fiveYear)) {
				document.worldpay_checkout.MC_fiveYear.value = purchasedAmount;
				document.worldpay_checkout.MC_fiveYearCost.value = cost;		
			}
		break;
					
		case "tenyear":
			if (objectExists(document.worldpay_checkout.MC_tenYear)) {
				document.worldpay_checkout.MC_tenYear.value = purchasedAmount;
				document.worldpay_checkout.MC_tenYearCost.value = cost;		
			}
		break;
					
		case "lifetime":
			if (objectExists(document.worldpay_checkout.MC_lifetime)) {
				document.worldpay_checkout.MC_lifetime.value = purchasedAmount;
				document.worldpay_checkout.MC_lifetimeCost.value = cost;		
			}
		break;
	}				
}

// Gets the Date object from a string
function getDateFromString(value) {
	// Built for dd/mm/yyyy
	if (isDate(value))
	{
	    var year = value.substring(6, 10);
	    var month = value.substring(3, 5);
	    var day = value.substring(0, 2);
    	
	    var dateObject = new Date(year, month-1, day);
    	
	    return dateObject;
	}	    
	else
	    return null
}

// Fills the maxlimit areas
function textCounter(field, countfield, maxlimit) {
	if (field.value.length > maxlimit) {
		field.value = field.value.substring(0, maxlimit);
	} else {
		countfield.innerHTML = maxlimit - field.value.length;
	}
}

// Sectors
/*sectors = new Array(
  "Property, housing, cleaning and FM",
  "Retail motor industry",
  "Chemicals, nuclear, oil and gas",
  "Construction",
  "Electricity, gas, waste and water",
  "IT and Telecoms",
  "Financial services industry",
  "Passenger transport",
  "Food and drink manufacturing",
  "Environmental and land-based",
  "Education and Learning",
  "Hospitality, leisure and travel",
  "Science, engineering and manufacturing",
  "Apparel, footwear and textile industry",
  "Social care",
  "Healthcare",
  "Custodial care, community justice and police",
  "Freight and logistics",
  "Active leisure and learning",
  "Broadcast, film and media",
  "Retail",
  "Building services engineering"
);*/

function IsDate(dateStr)
{
	var datePat = /^(\d{1,2})(\/)(\d{1,2})(\/)(\d{4})$/;
	var matchArray = dateStr.match(datePat);
	var datestatus = true;
	if (matchArray == null || matchArray[1] == null) 
		return "Please enter date as mm/dd/yyyy " + "\n";
	else
		if (matchArray[3] == null || matchArray[5] == null)
			return "----- Please enter date as mm/dd/yyyy " + "\n";

	day		= matchArray[1];
	month	= matchArray[3];
	year	= matchArray[5];

	if (month < 1 || month > 12)
		return "----- Month must be between 1 and 12." + "\n";

	if (day < 1 || day > 31)
		return "----- Day must be between 1 and 31." + "\n";

	if ((month==4 || month==6 || month==9 || month==11) && day==31)
		return "----- Month " + month + " doesn`t have 31 days!" + "\n";

	if (month == 2) 
	{ // check for february 29th
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
		if (day > 29 || (day==29 && !isleap)) 
			return "----- February " + year + " doesn`t have " + day + " days!" + "\n";
	}
	if (year < 1900)
		return "Year should be greater than 1900 " + "\n";
	var ValidDate = new Date(year, month - 1, day);
	if  (ValidDate.getFullYear() == year &&
		 ValidDate.getMonth() == month - 1 &&
		 ValidDate.getDate() == day)
			return new String(); 
	else
		return "Please enter date as dd/mm/yyyy " + "\n";
}

function fillHiddenVariables() {
	// Clear fields
	document.getElementById('barcode').value = "";
	document.getElementById('id').value = "";
	
	// Fill fields with new values
	if (document.getElementById('txtIDBC').value.substring(0, 2).toUpperCase() == "BC") {
		document.getElementById('barcode').value = document.getElementById('txtIDBC').value.toUpperCase();
		document.getElementById('txtIDBC').value = "";
	
		for (var i = 0; i < document.getElementById('barcode').value.length; i++) {
			document.getElementById('txtIDBC').value += "*";
		}
	} else {
		document.getElementById('id').value = document.getElementById('txtIDBC').value;
	}
}

// Adds these sectors to given Select Drop Down Box
function selectSectors(theSelect) {
	var theSelect = document.getElementById(theSelect);
	
	sectors.sort();
	
	for (var i = 0; i < sectors.length; i++) {
		var sectorName = sectors[i];
		theSelect.options[i + 1] = new Option(sectorName, sectorName);
	}
}

// When a Sector is selected, redirect the page with a querystring in order for the page to recognise the change
function changeSector(theURL, theSelector) {
	var sector = document.getElementById(theSelector).value;
	var newURL = theURL + '?sector=' + sector;
	document.location.href = newURL;
}

// Displays help tips throughout the site
function tipDisplay(theTip) {
	var tip = document.getElementById(theTip);
	
	if (tip.style.display == "") {
		tip.style.display = "none";
	} else {
		tip.style.display = "";
	}
}

// Scripts for index.asp
function index_onLoad() {
	// JW - 21 April 2006 - Empty Function in myskillsrecord due to menu structure. Can be opened at a later date to select any certain menu option
	//document.getElementById('home').className = 'navItemTextSelected';
}

// Scripts for login.asp
function login_onLoad(loginType) {
	/*if (loginType == "passportHolder") {
		document.getElementById('mLogin').className = 'navItemTextSelected';
	} else {
		document.getElementById('vLogin').className = 'navItemTextSelected';
	}*/
	
	document.getElementById('txtID').focus();
	
	if (location.search.indexOf('error') > 0) {
		document.getElementById('error').style.display = "";
		//document.getElementById('errorSpace').style.display = "";
	}
}

function fred(){
	alert('james changed this')
}

function login_onSubmit() {
	var msg='';
	
	var arrUserType = document.getElementsByName('userType');
	for (var i = 0; i < arrUserType.length; i++) {
		if (arrUserType[i].checked == true) {
			document.login.hUserType.value = arrUserType[i].value;
		}
	}
	
	if (document.login.hUserType.value == "q")
	{
	  showPassport();
	  return false;
	}

	document.login.hidID.value = document.getElementById('txtID').value;
	if(isNaN(document.login.hidID.value))
		msg='The ID field must be a number.\n';
	else if (document.login.hidID.value.length == 0)
        msg += 'You must enter an ID.\n';        
	
	document.login.hidUsername.value = document.getElementById('txtUsername').value;
	if (document.getElementById('txtUsername').value.length == 0)
		msg +='You must enter a user name.\n';

	document.login.hidPassword.value = document.getElementById('txtPassword').value;
	if (document.getElementById('txtPassword').value.length == 0)
		msg +='You must enter a password.\n';

	if (msg != '')
	{
		alert(msg);
		return false;
	}
	else
    	document.login.submit();
}

// Scripts for passportTop.asp
function showVerify() {
	var newWindow = window.open('/howtoverify.asp','howtoverify','height=100,width=550,resizable=no');
	newWindow.opener = this;
}

function nearestVerifier() {
	window.close();
	opener.location.href = '/passportholders/nearestregisteredverifier.asp';
}

// Scripts for Passport Holder's dashboard
function changeMyID() {
	var sure = confirm('You have a requested to change your ID Number. Press OK to Continue, otherwise click Cancel');
	if (sure == true) {
		document.location.href = 'changeid.asp';
	}
}

// Scripts for Verifiers dashboard
function selectPassportHolder(pageType) {
	var positionLeft = (screen.width - 350) / 2;
	var positionTop = (screen.height - 200) / 2;
	var selectPHWindow;	
		
	selectPHWindow = window.open('/popups/selectPassportHolder.asp?searchType=' + pageType,'selectPH','modal=yes,width=350,height=200,left=' + positionLeft + ',top=' + positionTop);
	if (selectPHWindow == null)
		alert("You must enable pop-up windows.");
	else
		selectPHWindow.opener = this;
}

// Scripts for Date Validation
// set date character seperator (used in indexOf references)
// set date strings
var seperator = "/"; 
var strDay;
var strMonth;
var strYear;
var completeDate;

// final Validation confirmation
function ValidateDate(theField, theDisplay)
{
  var dt = document.getElementById(theField);
  var display = document.getElementById(theDisplay);

	if (dt.value != "") {
    	if (isDate(dt.value) == false) {
        	display.style.display = "";
    	}else{
        	display.style.display = "none";
    	}
	}
}

function ValidateDateString(theString)
{
	if (theString != "") {
		return isDate(theString);
	}
	else
	{
		return true;
	}
}

// main checking function
function isDate(dtStr)
{
    // declare proceed variable
    proceed = true;
	
	// set positions of date seperator
    var pos1 = dtStr.indexOf(seperator);
    var pos2 = dtStr.lastIndexOf(seperator);
	
	// set each substring (day, month, year) using seperator positions
    strDay = dtStr.substring(0, pos1);
    strMonth = dtStr.substring(pos1+1, pos2);
    strYear = dtStr.substring(pos2+1, dtStr.length);

    // make each string an integer
    var day = parseFloat(strDay);
    if (isNaN(strDay)) proceed = false;    
    var month = parseFloat(strMonth);
    if (isNaN(strMonth)) proceed = false;
    var year = parseFloat(strYear);
    if (isNaN(strYear)) 
        proceed = false;
    else if (year < 1900)
        proceed = false;
    
	
    // array of 12 months
    var daysInMonth = new Array(12);
    daysInMonth[1] = 31;
	daysInMonth[2] = daysInFebruary(year);
    daysInMonth[3] = 31;
    daysInMonth[4] = 30;
    daysInMonth[5] = 31;
    daysInMonth[6] = 30;
    daysInMonth[7] = 31;
    daysInMonth[8] = 31;
    daysInMonth[9] = 30;
    daysInMonth[10] = 31;
    daysInMonth[11] = 30;
    daysInMonth[12] = 31;

    // check format (date seperators in correct positions)
    if (pos1 != 2 || pos2 != 5) {
        proceed = false;
    }

    // evaluate year
    if (strYear.length != 4) {
        proceed = false;
    }

    // evaluate year
    if (parseInt(strYear) <= 1900) {
        proceed = false;
    }

    // evaluate month
    if (month < 1 || month > 12) {
        proceed = false;
    }

    // evaluate day
    if (strDay.length < 1 || day < 1 || day > daysInMonth[month]) {// || (month == 2 && day > daysInFebruary(year))) {
        proceed = false;
    }
    
    // return value to ValidateDate
    return proceed;
}

// February has 29 days in any year evenly divisible by four
// EXCEPT for centurial years which are not also divisible by 400
function daysInFebruary(year)
{
    return ((year % 4 == 0) && (!(year % 100 == 0)) || (year % 400 == 0) ? 29 : 28);
}  

// Scripts for personaldetails.asp
function personalDetails_onLoad() {
	index_onLoad();
	document.personaldetails.txtTitle.focus();
}

function personalDetails_onSubmit(theType) {
	// Declare message variable
	var message = "";
	
	// Get all the text fields into an array and change the background color to normal
	var textFields = document.personaldetails.getElementsByTagName('input');
	for (var i = 0; i < textFields.length; i++) {
		textFields[i].style.backgroundColor = "";
	}
	
	// Check that First Name field has been filled in
	if (trim(document.personaldetails.txtFirstName.value) == "") {
		document.personaldetails.txtFirstName.style.backgroundColor = "#FAFAFA";
		message += "Please Enter your First Name\n\n";
	}
	
	// Check that Surname field has been filled in
	if (trim(document.personaldetails.txtSurname.value) == "") {
		document.personaldetails.txtSurname.style.backgroundColor = "#FAFAFA";
		message += "Please Enter your Surname\n\n";
	}
	
	// Check that Date of Birth field has been filled in
	if (trim(document.personaldetails.txtDOB.value) == "") {
		document.personaldetails.txtDOB.style.backgroundColor = "#FAFAFA";
		message += "Please Enter your Date of Birth\n\n";
	}

	// Check that Email Address field has been filled in
	if (trim(document.personaldetails.txtEmail.value) == "") {
		document.personaldetails.txtEmail.style.backgroundColor = "#FAFAFA";
		message += "Please Enter your Email Address\n\n";
	}
	
	if (theType == "passportHolder" || theType == "passportHolderNCVYS") {
		// Check that Street Number or House Name field has been filled in
		if (trim(document.personaldetails.txtNumberName.value) == "") {
			document.personaldetails.txtNumberName.style.backgroundColor = "#FAFAFA";
			message += "Please Enter your Street Number or House Name\n\n";
		}
	
		// Check that Street field has been filled in
		if (trim(document.personaldetails.txtStreet.value) == "") {
			document.personaldetails.txtStreet.style.backgroundColor = "#FAFAFA";
			message += "Please Enter your Street Name\n\n";
		}
	
		// Check that Post Code field has been filled in
		if (trim(document.personaldetails.txtPostCode.value) == "") {
			document.personaldetails.txtPostCode.style.backgroundColor = "#FAFAFA";
			message += "Please Enter your Post/Zip Code\n\n";
		}
		else
		{
			if (!isUKPostCode(trim(document.personaldetails.txtPostCode.value))) {
				document.personaldetails.txtPostCode.style.backgroundColor = "#FAFAFA";
				message += "The Post/Zip Code does not appear to be valid. Please re-enter\n\n";
			}
			
		}

	}
	
	// Check the Username box is filled in
	if (!trim(document.personaldetails.txtUsername.value).match(/^\S{4,50}$/)) {
		message += "Please Enter a Username of between 4 and 50 characters\n\n";
		document.personaldetails.txtUsername.style.backgroundColor = "#FAFAFA";
	}
	
	// Check a valid Date is entered in Date of Birth
	if (trim(document.personaldetails.txtDOB.value) != "" && document.getElementById('dobBadDate').style.display == "") {
		document.personaldetails.txtDOB.style.backgroundColor = "#FAFAFA";
		message += "The Date of Birth entered is not a valid date, please re-enter\n\n";
	}

	// Check a valid Date is entered in Date of Birth
	if (isDate(trim(document.personaldetails.txtDOB.value)) == false) {
		document.personaldetails.txtDOB.style.backgroundColor = "#FAFAFA";
		message += "The Date of Birth entered is not a valid date, please re-enter\n\n";
	}

	if (!IsDateInPast(document.personaldetails.txtDOB.value))
	{
		document.personaldetails.txtDOB.style.backgroundColor = "#FAFAFA";
		message += "The Date of Birth does not appear to be valid. Please re-enter\n\n";
	}
  
	// Check a valid Email Address is entered
	if (document.personaldetails.txtEmail.value != "" && !IsEmail(document.personaldetails.txtEmail.value)) {
		document.personaldetails.txtEmail.style.backgroundColor = "#FAFAFA";
		message += "The Email Address entered does not appear to be valid, please re-enter\n\n";
	}


	if (theType == "passportHolderNCVYS")
	{
        var selRole = document.getElementById("selRole").value;
        var txtJobTitle = document.getElementById("txtJobTitle").value;
        var selSubSector = document.getElementById("selSubSector").value;
        var selGender = document.getElementById("selGender").value;
        var selDisability = document.getElementById("selDisability").value;
        var radDisability = document.getElementById("radNo").checked;
        var radDisabilityPr = document.getElementById("radPrefer").checked;
        var selEthnicity = document.getElementById("selEthnicity").value;                
        var selRegion = document.getElementById("selRegion").value;

		if (selRegion == "")    
			message += "Please select your region in the Regions list!\n";

        if (selRole == "")
            message += "Please select your role type in the Role Type list!\n";                    

        if (txtJobTitle == "")
            message += "Job title/Voluntary role field is required and should be filled!\n";                    

        if (selSubSector == "")
            message += "Please select your subsector in the Workforce Sub-Sector list!\n";                    
        
        if (selGender == "")
            message += "Please select your gender in the Gender list!\n";                    
        
        if ((selDisability == "") && (!radDisability) && (!radDisabilityPr))
            message += "Please select your disability in the Disability list!\n";                    
            
        if (selEthnicity == "")
            message += "Please select your ethnicity in the Ethnicity list!\n";                    

	}
		
	// Check the message variable, if it is empty then the form was successfully completed and can be submitted.
	// If it is not empty, then an error was raised and needs to be displayed to the user
	if (message != "") {
		alert(message);
	} else {
		if (theType == "passportHolder") {
			var unverifyAlert = confirm('If you change your Name or Date of Birth then you will need to re-verify your Passport. To do this see your nearest registered verifier\n\nTo confirm your changes please press OK, otherwise click Cancel to return to your Passport.');
		
			if (unverifyAlert == true) {
				document.personaldetails.submit();
			} else {
				document.location.href = "dashboard.asp";
			}
		} else {
			document.personaldetails.submit();
		}
	}	
}

// Scripts for changephoto.asp
function changePhoto_onLoad() {
	if (location.search.indexOf("allowUpdate") >= 0) {
		document.getElementById('updateButton').style.display = "";
	}
}

function changePhoto_onSubmit() {
	if (document.changephoto.filePhoto.value == "") {
		alert('Please choose the Photograph File you wish to preview');
	} else {
		previewImage();
	}
}

function previewImage() {
	document.changephoto.action = "changephoto.asp?type=preview";
	document.changephoto.submit();
}

function updateImage() {
	document.location.href = "changephoto.asp?type=update";
}

function changePhoto_onCancel() {
	document.location.href = "changephoto.asp?type=cancel";
}

// Scripts for changepassword.asp
function changePassword_onLoad() {
	if (location.search.indexOf('error') >= 0) {
		document.getElementById('error').style.display = "";
	}
	if (location.search.indexOf('wrongNewPassword') >= 0) {
		document.getElementById('wrongNewPassword').style.display = "";
	}
}

function updateEmail_onSubmit() {
	// Declare message variable
	var message = ""
	
	// Get all the text fields into an array and change the background color to normal
	var textFields = document.updateEmail.getElementsByTagName('input');
	for (var i = 0; i < textFields.length; i++) {
		textFields[i].style.backgroundColor = "";
	}

	// Check the Old Password field has been filled in
	if (document.updateEmail.txtEmailAddress.value == "") {
		document.updateEmail.txtEmailAddress.style.backgroundColor = "";
		message += "Please Enter your Email Address\n\n";
	}
	
		// Check the Email box is filled in
	if (document.updateEmail.txtEmailAddress.value != "" && !document.updateEmail.txtEmailAddress.value.match(/^\S+@\S+(\.)\S{2,4}$/)) {
		message += "The Email Address entered appears not to be valid. Please check and re-enter\n\n";
		document.updateEmail.txtEmailAddress.style.backgroundColor = "";
	}

	
	// Check message variable, if empty all was fine, otherwise display the message
	if (message != "") {
		alert(message);
	} else {
		document.updateEmail.submit();
	}
}

function ValidPassword(password)
{
	var s5,s2,s3,s4;
	s5 = password.replace(/[^0-9a-zA-Z]/,'$');
	s2 = password.replace(/[0-9]/,'$');
	s3 = password.replace(/[a-z]/,'$');
	s4 = password.replace(/[A-Z]/,'$');
	if(password.length < 8)
	{
		return(false);
	}
	if( (s5.indexOf('$')==-1) && (s2.indexOf('$')>-1) && (s3.indexOf('$')>-1) && (s4.indexOf('$')>-1) ) 
	{
		return(true);
	}
	return (false);
}

function changePassword_onSubmit() {
	// Declare message variable
	var message = ""
	
	// Get all the text fields into an array and change the background color to normal
	var textFields = document.changepassword.getElementsByTagName('input');
	for (var i = 0; i < textFields.length; i++) {
		textFields[i].style.backgroundColor = "";
	}
	
	// Check the Old Password field has been filled in
	if (document.changepassword.txtOldPassword.value == "") {
		document.changepassword.txtOldPassword.style.backgroundColor = "";
		message += "Please Enter your Old Password\n\n";
	}
	
	// Check the New Password field has been filled in
	if (document.changepassword.txtNewPassword.value  == "") {
		document.changepassword.txtNewPassword.style.backgroundColor = "";
		message += "Please Enter your New Password\n\n";
	}
	
	// Check the Confirm Password field has been filled in
	if (document.changepassword.txtConfirmPassword.value == "") {
		document.changepassword.txtConfirmPassword.style.backgroundColor = "";
		message += "Please Confirm your New Password\n\n";
	}
	
	// Check the New and Confirm Password fields match
	if ((document.changepassword.txtNewPassword.value != "" && document.changepassword.txtConfirmPassword.value != "") && document.changepassword.txtNewPassword.value != document.changepassword.txtConfirmPassword.value) {
		document.changepassword.txtNewPassword.style.backgroundColor = "";
		document.changepassword.txtConfirmPassword.style.backgroundColor = "";
		message += "Your Passwords do not match, please retry\n\n";
	}
  	
	// Check message variable, if empty all was fine, otherwise display the message
	if (message != "") 
	{
		alert(message);
	} 
	else 
	{
	    message = "";
	    if(!ValidPassword(document.changepassword.txtNewPassword.value))
	    {
		    document.changepassword.txtNewPassword.style.backgroundColor = "";
		    document.changepassword.txtConfirmPassword.style.backgroundColor = "";
		    message += "We are so sorry, but your Password Validation is failed!\n\nUse the following rules to create a valid password:\n";
		    message += " - password must be at least 8 chars long\n"
            message += " - password must contain at least one number\n"
            message += " - password must contain at least one capital letter\n"
            message += " - password must contain at least one lower case letter"
            alert(message);
	    }			    
	    else
		    document.changepassword.submit();
	}
}


// Scripts for both vieweditskills.asp and quickview.asp
function showManageSkills(skillCode, pageType) {
	var positionLeft = (screen.width - 800) / 2;
	var addSkillLeft = (screen.width - 820) / 2;
	var positionTop = (screen.height - 570) / 2;
	var addSkillTop = (screen.height - 570) / 2;
	var skillDetailWindow;	
		
	if (pageType == "quickview") {
		skillDetailWindow = window.open('/popups/viewskilldetails.asp?skillCode=' + skillCode, 'skillDetails', 'modal=yes,width=800,height=500,left=' + positionLeft + ',top=' + positionTop);
		skillDetailWindow.opener = this;
	} else if (pageType == "addskill") {
		skillDetailWindow = window.open('/popups/addskills.asp', 'skillDetails', 'modal=yes, width=820,height=570,left=' + addSkillLeft + ',top=' + addSkillTop);
		skillDetailWindow.title = "Add Skills";
		skillDetailWindow.opener = this;
	} else if (pageType == "multipleAB") {
	    skillDetailWindow = window.open('/popups/multipleupdate-ab.asp', 'abDetails', 'modal=yes,width=800,height=380,left=' + positionLeft + ',top=' + positionTop);
	    skillDetailWindow.opener = this;	
	} else if (pageType == "volunteering") {
	    skillDetailWindow = window.open('/popups/volunteering.asp?skillCode=' + skillCode, 'volunteering', 'modal=yes,width=840,height=400,scrollbars=yes,left=' + positionLeft + ',top=' + positionTop);
	    skillDetailWindow.opener = this;	
	} else if (pageType == "cpd") {
		skillDetailWindow = window.open('/popups/schedulecpd.asp?parameters=' + skillCode, 'cpd', 'modal=yes,width=800,height=400,left=' + positionLeft + ',top=' + positionTop);
		skillDetailWindow.opener = this;
	} else {		
		skillDetailWindow = window.open('/popups/manageskills.asp?skillCode=' + skillCode, 'skilldetails', 'modal=yes,width=800,height=570,left=' + positionLeft + ',top=' + positionTop);
		skillDetailWindow.opener = this;
	}
}


// Scripts for manageskills.asp
function expiredSession() {
	location.href = "/index.asp";
	//window.close();
}

function expiredWindowSession() {
    window.close();
    opener.location.href = "/index.asp";
}

function closeWindow(url) {
	window.close();
	opener.location.href = url;
}


function editSkillDetails_onSubmit(isVerifier) {
	// Declare message variable
	showFlags();
	var message = "";
		
	// Get todays date
	var todaysDate = new Date();
		
	// Get all the text fields into an array and change the background color to normal
	var textFields = document.editSkillDetails.getElementsByTagName('input');
	for (var i = 0; i < textFields.length; i++) {
		textFields[i].style.backgroundColor = "";
	}
		
	// Check the Skill Title field has been filled in
	if (document.editSkillDetails.txtEditSkillDescription.value == "") {
		document.editSkillDetails.txtEditSkillDescription.style.backgroundColor = "#FAFAFA";
		message += "Please Enter your Skill Title\n\n";
	}
		
	// Check the Skill Type Selectbox has had an option chosen
	if (document.editSkillDetails.selSkillType.value == "") {
		message += "Please Select a Skill Type\n\n";
	}
				
	// Check the Skill Date Acquired has been filled in
	if (document.editSkillDetails.txtEditSkillDateAcquired.value == "") {
		document.editSkillDetails.txtEditSkillDateAcquired.style.backgroundColor = "#FAFAFA";
		message += "Please Enter the Date you Acquired this Skill\n\n";
	}

	if (isDate(document.editSkillDetails.txtEditSkillDateAcquired.value) == false) {
		document.editSkillDetails.txtEditSkillExpiryDate.style.backgroundColor = "#FAFAFA";
		message += "The Date Acquired appears to be invalid, please retry\n\n";
	}
		
	// Check the Skill Date Acquired is not in the future, only needs to be tested if a date is entered
	/*if (todaysDate < getDateFromString(document.editSkillDetails.txtEditSkillDateAcquired.value)) {
		document.editSkillDetails.txtEditSkillDateAcquired.style.backgroundColor = "#FAFAFA";
		message += "This Skill's Acquired Date cannot be in the future\n\n";
	}*/
		
	// If Expiry date is filled in then the alert email and alert notice fields must be filled, check this
	if (document.editSkillDetails.txtEditSkillExpiryDate.value != "") {
		// Check the Expiry date entered was a valid date
		if (isDate(document.getElementById('txtEditSkillExpiryDate').value) == false) {
			document.editSkillDetails.txtEditSkillExpiryDate.style.backgroundColor = "#FAFAFA";
			message += "The Expiry Date appears to be invalid, please retry\n\n";
		}
		
		// Check the Expiry Date is not in the past
		if (todaysDate > getDateFromString(document.editSkillDetails.txtEditSkillExpiryDate.value)) {
			document.editSkillDetails.txtEditSkillExpiryDate.style.backgroundColor = "#FAFAFA";
			message += "This Skill's Expiry Date cannot be in the past\n\n";
		}
		
		// Check the Alert Email has been filled in
		if (document.editSkillDetails.txtEditSkillAlertEmail.value == "") {
			document.editSkillDetails.txtEditSkillAlertEmail.style.backgroundColor = "#FAFAFA";
			message += "Please Enter the Email Address you would like the Expiry Alert to be sent to\n\n";
		}
		
		// Check the Alert Email address validity
		if (!IsEmail(document.editSkillDetails.txtEditSkillAlertEmail.value)) {
			document.editSkillDetails.txtEditSkillAlertEmail.style.backgroundColor = "#FAFAFA";
			message += "The Email Address specified appears to be invalid, please retry\n\n";
		}
		
		// Check the Notice Period has been filled in
		if (document.editSkillDetails.txtEditSkillAlertNotice.value == "") {
			document.editSkillDetails.txtEditSkillAlertNotice.style.backgroundColor = "#FAFAFA";
			message += "Please Enter the amount of days notice you wish to be alerted about this Skill Expiry\n\n";
		}
		
		// Check the Notice Period field only contains numbers
		var checkStr = "0123456789";
		var nonNumber = false;
		for (var i = 0; i < document.editSkillDetails.txtEditSkillAlertNotice.value.length; i++) {
			ch = document.editSkillDetails.txtEditSkillAlertNotice.value.charAt(i);
			if (checkStr.indexOf(ch) < 0) {
				nonNumber = true
			}
		}
		
		if (nonNumber == true) {
			document.editSkillDetails.txtEditSkillAlertNotice.style.backgroundColor = "#FAFAFA";
			message += "Please Enter Numbers only for the Notice Period\n\n";
		}
		
	}

    if (isVerifier) {
        if (document.getElementById("txtVerifyPassword").value == "") {
            message += "Please Enter your Password to Verify this Skill";
        }
        else {
            document.getElementById("verifierPassword").value = document.getElementById("txtVerifyPassword").value;
        }

        var arrVerifySkill = document.getElementsByName('radVerifySkill');
        for (var i = 0; i < arrVerifySkill.length; i++) {
            if (arrVerifySkill[i].checked == true) {
                document.getElementById("VerifySkill").value = arrVerifySkill[i].value;
            }
        }

        
	}
	// Check message variable, if it is not empty then there was a problem and need to display this, otherwise, submit the form
	if (message != "") {
		alert(message);
	} else {
		document.editSkillDetails.submit();
	}
}

function skillNotListed(theForm) {
	if (document.forms[theForm].selAddSkillDescription.value == "other") {
		document.forms[theForm].txtAddSkillOtherDescription.disabled = false;
		//showAB()	
		} else {
		document.forms[theForm].txtAddSkillOtherDescription.disabled = true;
		//hideAB()
	}
	
}

function showFlags()
{
    var date = document.getElementById("txtAddSkillExpiryDate").value;
    var display = "none";
    if (date != "") display = "";
    var tdEmail = document.getElementById("tdEmail");
    var tdNotice = document.getElementById("tdNotice");
    tdEmail.style.display = display;
    tdNotice.style.display = display;
}

function addSkillDetails_onSubmit() {
    showFlags();    
	// Declare message variable
	var message = "";
	// Get todays date
	var todaysDate = new Date();
	
	// Get all the text fields into an array and change the background color to normal
	var textFields = document.addSkillDetails.getElementsByTagName('input');
	for (var i = 0; i < textFields.length; i++) {
		textFields[i].style.backgroundColor = "";
	}
	
	if (document.addSkillDetails.selSkillType.value == 0)
	{
	    document.addSkillDetails.selSkillType.style.backgroundColor = "#FAFAFA";
	    message += "Please Choose your Skill Type from the list\n\n";	
	}
	
	// Check the Skill Title drop down box has a valid value if it is shown on the page
	if (!(typeof(document.addSkillDetails.selAddSkillDescription) == "undefined"))
	{
	    if (document.addSkillDetails.selAddSkillDescription.value == "") {
		    document.addSkillDetails.selAddSkillDescription.style.backgroundColor = "#FAFAFA";
		    message += "Please Choose your Skill from the list provided, or select \"Skill Not Listed\" and Enter it in the \"Other\" box\n\n";
	    }
	}
			
	// Check the Skill Title field has been filled in, if the Skill Title drop down box is on Skill Not Listed (other) or it is undefined (hidden)
	//if (typeof(document.addSkillDetails.selAddSkillDescription) == "undefined") || document.addSkillDetails.selAddSkillDescription.value == "other") {
	if ((typeof(document.addSkillDetails.selAddSkillDescription) == "undefined") || (document.addSkillDetails.selAddSkillDescription.value == "other")) {
		if (document.addSkillDetails.txtAddSkillOtherDescription.value == "") {
			document.addSkillDetails.txtAddSkillOtherDescription.style.backgroundColor = "#FAFAFA";
			message += "Please Enter your Skill Title\n\n";
		}
	}
			
	// Check the Skill Type drop down box has a valid value
	if (document.addSkillDetails.selSkillType.value == "") {
		document.addSkillDetails.selSkillType.style.backgroundColor = "#FAFAFA";
		message += "Please Choose your Skill Type from the list provided\n\n";
	}
			
	// Check the Skill Date Acquired has been filled in
	if (document.addSkillDetails.txtAddSkillDateAcquired.value == "") {
		document.addSkillDetails.txtAddSkillDateAcquired.style.backgroundColor = "#FAFAFA";
		message += "Please Enter the Date you Acquired this Skill\n\n";
	}
	
	//var msg = IsDate(document.addSkillDetails.txtAddSkillDateAcquired.value)
	if (isDate(document.addSkillDetails.txtAddSkillDateAcquired.value)== false) {
		document.addSkillDetails.txtAddSkillDateAcquired.style.backgroundColor = "#FAFAFA";
		message += "The Date Acquired appears to be invalid, please retry\n\n";
	}
			
	// Check that the Date Acquired entered was a valid date
	if (document.getElementById('AddAcquiredBadDate').style.display == "") {
		document.addSkillDetails.txtAddSkillDateAcquired.style.backgroundColor = "#FAFAFA";
		message += "The Date Acquired appears to be invalid, please retry\n\n";
	}
			
	// If Skill Date Acquired has been entered, check it is not in the future
	/*if (document.addSkillDetails.txtAddSkillDateAcquired.value != "") {
		if (todaysDate < getDateFromString(document.addSkillDetails.txtAddSkillDateAcquired.value)) {
			document.addSkillDetails.txtAddSkillDateAcquired.style.backgroundColor = "#FAFAFA";
			message += "This Skill's Acquired Date cannot be in the future\n\n";
		}
	}*/
			
	// If Expiry Date is filled in then the alert email and alert notice fields must be filled, check this
	if (document.addSkillDetails.txtAddSkillExpiryDate.value != "") {
		// Check the Expiry Date entered was a valid date
		if (document.getElementById('AddExpiryBadDate').style.display == "") {
			document.addSkillDetails.txtAddSkillExpiryDate.style.backgroundColor = "#FAFAFA";
			message += "The Expiry Date appears to be invalid, please retry\n\n";
		}
		
		// Check the Expiry Date is not in the past
		if (todaysDate >= getDateFromString(document.addSkillDetails.txtAddSkillExpiryDate.value)) {
			document.addSkillDetails.txtAddSkillExpiryDate.style.backgroundColor = "#FAFAFA";
			message += "This Skill's Expiry Date cannot be in the past\n\n";
		}
				
		// Check the Alert Email has been filled in
		if (document.addSkillDetails.txtAddSkillAlertEmail.value == "") {
			document.addSkillDetails.txtAddSkillAlertEmail.style.backgroundColor = "#FAFAFA";
			message += "Please Enter the Email Address you would like the Expiry Alert to be sent to\n\n";
		}
				
		// Check the Alert Email Address validity
		if (document.addSkillDetails.txtAddSkillAlertEmail.value != "") {
			if (!IsEmail(document.addSkillDetails.txtAddSkillAlertEmail.value)) {
				document.addSkillDetails.txtAddSkillAlertEmail.style.backgroundColor = "#FAFAFA";
				message += "The Email Address specified appears to be invalid, please retry\n\n";
			}
		}
				
		// Check the Notice Period has been filled in
		if (document.addSkillDetails.txtAddSkillAlertNotice.value == "") {
			document.addSkillDetails.txtAddSkillAlertNotice.style.backgroundColor = "#FAFAFA";
			message += "Please Enter the amount of days notice you wish to be alerted about this Skill Expiry\n\n";
		}
			
		// Check the Notice Period field only contains numbers
		if (!document.addSkillDetails.txtAddSkillAlertNotice.value.match(/^\d+$/))
		{
		    document.addSkillDetails.txtAddSkillAlertNotice.style.backgroundColor = "#FAFAFA";
		    message += "Please Enter Numbers only for the Notice Period\n\n";
		}
		/*var checkStr = "0123456789";
		var nonNumber = false;
		for (var i = 0; i < document.addSkillDetails.txtAddSkillAlertNotice.value.length; i++) {
			ch = document.addSkillDetails.txtAddSkillAlertNotice.value.charAt(i);
			if (checkStr.indexOf(ch) < 0) {
				nonNumber = true
			}
		}
					
		if (nonNumber == true) {
			document.addSkillDetails.txtAddSkillAlertNotice.style.backgroundColor = "#FAFAFA";
			message += "Please Enter Numbers only for the Notice Period\n\n";
		}*/
	}
			
	// Check message variable, if it is not empty then there was a problem and need to display this, otherwise move to step 2
	if (message != "") {
		alert(message);
	} else {
		document.addSkillDetails.submit();
	}
}

function addSkillCertImage_onSubmit() {
	// Declare message variable
	var message = "";
	
	// Check an image was submitted
	if (document.addSkillCertImage.fileCertImage.value == "") {
		message = "Please enter the file you wish to upload";
	}
	
	// Check message variable, if it is blank then submit, otherwise alert user
	if (message == "") {
		document.addSkillCertImage.submit();
	} else {
		alert(message);
	}
}

// Disables all inputs apart from the one passed in passed form
function disableABInputs() {
	var inputs = document.addABDetails.getElementsByTagName('input');
	var selects = document.addABDetails.getElementsByTagName('select');
	
	// If chkAB is ticked, disable everything but it, otherwise, enable everything
	if (document.addABDetails.chkAB.checked == true) {
		for (var i = 0; i < inputs.length; i++) {
			if (inputs[i].type != "button")
			{
				if (inputs[i].id != 'actionType')
				{
					inputs[i].disabled = true;
				}
			}
		}
		
		for (var i = 0; i < selects.length; i++) {
			selects[i].disabled = true;
		}		
		
		// Re-enable chkAB
		document.addABDetails.chkAB.disabled = false;
	} else {
		for (var i = 0; i < inputs.length; i++) {
			inputs[i].disabled = false;
		}
		
		for (var i = 0; i < selects.length; i++) {
			selects[i].disabled = false;
		}
	}
}

function enablePassword() {
	var radVerify = document.getElementsByName('radVerifySkill');
	var radValue;
	
	for (var i = 0; i < radVerify.length; i++) {
		if (radVerify[i].checked == true) {
			radValue = radVerify[i].value;
		}
	}
	
	if (radValue == "yes") {
		document.verifySkill.txtVerifyPassword.disabled = false;
	} else {
		document.verifySkill.txtVerifyPassword.disabled = true;
	}
}

function enablePasswordCPD() {
	var radVerify = document.getElementsByName('radVerifyCPD');
	var radValue;
	
	for (var i = 0; i < radVerify.length; i++) {
		if (radVerify[i].checked == true) {
			radValue = radVerify[i].value;
		}
	}
	
	if (radValue == "yes") {
		document.formVerify.txtVerifyPassword.disabled = false;
	} else {
		document.formVerify.txtVerifyPassword.disabled = true;
	}
}

function verifySkill_onSubmit() {
	// Declare message variable
	var message = "";
	
		var todaysDate = new Date();

	if (document.getElementById("txtEditSkillExpiryDate").value != "") 
	{
		// Check the Expiry date entered was a valid date
		if (isDate(document.getElementById('txtEditSkillExpiryDate').value) == false) {
		    document.getElementById("txtEditSkillExpiryDate").style.backgroundColor = "#FAFAFA";
			message += "The Expiry Date appears to be invalid, please retry\n\n";
		}
		
		// Check the Expiry Date is not in the past
        if (todaysDate > getDateFromString(document.getElementById("txtEditSkillExpiryDate").value)) {
            document.getElementById("txtEditSkillExpiryDate").style.backgroundColor = "#FAFAFA";
			message += "This Skill's Expiry Date cannot be in the past\n\n";
		}
		
		// Check the Alert Email has been filled in

        if (document.getElementById("txtEditSkillAlertEmail").value == "") {
            document.getElementById("txtEditSkillAlertEmail").style.backgroundColor = "#FAFAFA";
			message += "Please Enter the Email Address you would like the Expiry Alert to be sent to\n\n";
		}
		
		// Check the Alert Email address validity
        if (IsEmail(document.getElementById("txtEditSkillAlertEmail").value) == false) {
            document.getElementById("txtEditSkillAlertEmail").style.backgroundColor = "#FAFAFA";
			message += "The Email Address specified appears to be invalid, please retry\n\n";
		}
		
		// Check the Notice Period has been filled in

        if (document.getElementById("txtEditSkillAlertNotice").value == "") {
            document.getElementById("txtEditSkillAlertNotice").style.backgroundColor = "#FAFAFA";
			message += "Please Enter the amount of days notice you wish to be alerted about this Skill Expiry\n\n";
		}
		
		// Check the Notice Period field only contains numbers
		var checkStr = "0123456789";
		var nonNumber = false;
		for (var i = 0; i < document.getElementById("txtEditSkillAlertNotice").value.length; i++) {
		    ch = document.getElementById("txtEditSkillAlertNotice").value.charAt(i);
			if (checkStr.indexOf(ch) < 0) {
				nonNumber = true
			}
		}
		
		if (nonNumber == true) {
		    document.getElementById("txtEditSkillAlertNotice").style.backgroundColor = "#FAFAFA";
			message += "Please Enter Numbers only for the Notice Period\n\n";
		}		
	}

    if (document.getElementById("txtVerifyPassword").value == "") {
		message += "Please Enter your Password to Verify this Skill";
	}
    else {
        document.getElementById("verifierPassword").value = document.getElementById("txtVerifyPassword").value;
    }

    var arrVerifySkill = document.getElementsByName('radVerifySkill');
    for (var i = 0; i < arrVerifySkill.length; i++) {
        if (arrVerifySkill[i].checked == true) {
            document.getElementById("VerifySkill").value = arrVerifySkill[i].value;
        }
    }

	if (message == "") {
		document.verifySkill.submit();
	} else {
		alert(message);
	}
}

var worldpayLeft = (screen.width - 820) / 2;
var worldpayTop = (screen.height - 600) / 2;
var interval;
		
var worldpayWindow;

function skillPurchaseAccept() {
	alert("You will now be taken to our payment server to complete this transaction.\n\nUpon successful completion your skill will be accessible on the Passport");
	worldpayWindow = window.open('', 'worldpayWindow', 'scrollbars=yes,width=820,height=600,left=' + worldpayLeft + ',top=' + worldpayTop);
	worldpayWindow.opener = this;
	
	document.worldpay_checkout.submit();
	
	interval = setInterval("redirectOnClose()", 500);
}

function redirectOnClose() {
	if (worldpayWindow.closed) {
		document.location.href = 'addskills.asp?actionType=save';
		window.clearInterval(interval);
	}
}

// Scripts for changeemployer.asp
function optionDisplay(code, description) {
	var positionLeft = (screen.width - 400) / 2;
	var positionTop = (screen.height - 200) / 2;
					
	var myWindow = window.open('popups/changeemployeroptions.asp?code=' + code + '&description=' + description, 'options', 'left=' + positionLeft + ',top=' + positionTop + ',width=400,height=200');
	myWindow.opener = this;
}
				
function addAlert(code, description) {
	var addAlert = confirm('This will add you as an employee to ' + description + '. Click OK to Continue, otherwise Click Cancel');
	if (addAlert == true) {
		document.addemployer.code.value = code;
		document.addemployer.description.value = description;
		document.addemployer.submit();
	}
}	
				
function customEmployer() {
	document.changeemployer.custom.value = 'true';
	document.changeemployer.submit();
}

function customEmployer_onSubmit() {
	// Declare message variable
	var message = "";
	
	// Check Company Name is filled in
	if (document.customEmployer.txtCompanyName.value == "") {
		document.customEmployer.txtCompanyName.style.backgroundColor = "#FAFAFA";
		message += "Please Enter the Company Name\n\n";
	}
	
	// If message variable is blank, submit form, else alert user of error
	if (message != "") {
		alert(message);
	} else {
		document.customEmployer.submit();
	}
}

// Scripts for selectpassportholder.asp
function selectPH_onSubmit(searchType) {
	// Declare message variable
	var message = "";
	
	// Set all inputs to normal background
	var txtIDBC = document.getElementById('txtIDBC');
	txtIDBC.style.backgroundColor = "";
	var txtUsername = document.getElementById('txtUsername');
	txtUsername.style.backgroundColor = "";
	
	// Make sure hidden variables are filled
	fillHiddenVariables();

  if (searchType == "quickview") 
  {
  	
	  // Check that ID / BC is filled in
	  if (document.quickview.txtIDBC.value == "") {
		  document.quickview.txtIDBC.style.backgroundColor = "#FAFAFA";
		  document.quickview.txtIDBC.focus();
		  message += "Please Enter a valid ID, or swipe a Barcode\n\n";
	  }
  	
	  // Check that if an ID (not barcode) was entered, a username is also entered
	  if (document.quickview.txtIDBC.value.substring(0, 2) != "**") 
	  {
		  if (document.quickview.txtIDBC.value.substring(0, 2).toUpperCase() != "BC") {
			  if (document.quickview.txtQVUsername.value == "") {
				  document.quickview.txtQVUsername.style.backgroundColor = "#FAFAFA";
				  message += "Please Enter the Passport Holder's Username\n\n";
			  }
		  }
	  }
	}
	// If message is blank, submit, else show error
	if (message != "") {
		alert(message);
	} else {
		if (searchType != "quickview") {
		/*
			opener.document.selectPassportHolder.barcode.value = document.quickview.barcode.value;
			opener.document.selectPassportHolder.id.value = document.quickview.id.value;
			opener.document.selectPassportHolder.txtUsername.value = document.quickview.txtUsername.value;
		*/
		}
		
		switch (searchType) {
			case "quickview":
				document.quickview.action = "/skillsForwarder.asp?page=quickview.asp";
				document.quickview.submit();
			break;			
			
			case "view":
				opener.document.selectPassportHolder.action = "/skillsForwarder.asp?page=quickview.asp&login=true";
				opener.document.selectPassportHolder.submit()
			break;
			
			case "cv":
				opener.document.selectPassportHolder.action = "/skillsForwarder.asp?page=cvcreator.asp";
				opener.document.selectPassportHolder.submit();
			break;
			
			case "amend":
				opener.document.selectPassportHolder.action = "/skillsForwarder.asp?page=vieweditskills.asp";
				opener.document.selectPassportHolder.submit();
			break;
			
			case "verify":
				opener.document.selectPassportHolder.action = "/skillsForwarder.asp?page=verifiers/verifypassport.asp";
				opener.document.selectPassportHolder.submit();
			break;
			case "keyskills":
			   opener.document.selectPassportHolder.action = "/skillsForwarder.asp?page=verifiers/lsc/summary.asp";
				opener.document.selectPassportHolder.submit();
			break;
			case "cpd":
			    /*
				opener.document.selectPassportHolder.action = "/skillsForwarder.asp?page=cpd.asp";
				opener.document.selectPassportHolder.submit();
				*/
			break;
		}
		
		if (searchType != "quickview") {
			/*self.close();*/
		}
	}
}

// Scripts for Verifier Application
function clearRegNo()
{        
    var plc = document.getElementById('txtPlcRegno');
    var ltd = document.getElementById('txtLtdRegno');
    var llp = document.getElementById('txtLlpRegno');

    if (plc != null) plc.value = "";
    if (ltd != null) ltd.value = "";
    if (llp != null) llp.value = "";
}

function hideRegNo()
{
    var plc = document.getElementById('plcRegno');
    var ltd = document.getElementById('ltdRegno');
    var llp = document.getElementById('llpRegno');

    if (plc != null) plc.style.visibility = "hidden";
    if (ltd != null) ltd.style.visibility = "hidden";
    if (llp != null) llp.style.visibility = "hidden";
}

function regNoShow(theID)
{
    // This function checks the radio button checked and then shows the relevant reg no box
    var plc = document.getElementById('plcRegno');
    var ltd = document.getElementById('ltdRegno');
    var llp = document.getElementById('llpRegno');

    plc.style.visibility = "hidden";
    ltd.style.visibility = "hidden";
    llp.style.visibility = "hidden";

    document.getElementById(theID).style.visibility = "visible";
}
    

function stepProceed(theFromStepDisplay, theToStepDisplay, theFromStep, theToStep, theOriginalStep, theType)
{
    //This function changes the display items from step to step
    var fromStepDisplay = document.getElementById(theFromStepDisplay);
    var toStepDisplay = document.getElementById(theToStepDisplay);    
    var fromStep = document.getElementById(theFromStep);
    var toStep = document.getElementById(theToStep);

    fromStepDisplay.className = "steps-noborder";
    toStepDisplay.className = "steps-current";
    if(typeof(theOriginalStep) != "undefined" && typeof(theType) != "undefined"){
        document.getElementById(theOriginalStep).className = "steps";
    }
    fromStep.style.display = "none";
    toStep.style.display = "";

	
    switch (theToStep) {
        case "step2":
            if(typeof(theType) == "undefined"){
                document.getElementById('applicationHeading').innerHTML = "Verifier Details - (Step 2 of 3)";
            }
            else
            {
                document.getElementById('applicationHeading').innerHTML = "Verifier Application - (Step 2 of 3)";
            }
            if(document.getElementById("step3") == null)
            {
                document.getElementById('applicationHeading').innerHTML = "Verifier Details - (Step 2 of 2)";
            }

        break;
        case "step3":
            document.getElementById('applicationHeading').innerHTML = "Verifier Application - (Step 3 of 3)";
        break;
    }
}

var verifierExists = false;
function validateForm(theStep, theFlag)
{
    switch (theStep) {
        		
		case "step1":
			// Declare proceed variable
			var message = "";
			
			// Firstly check that the company name has been filled in
			if (trim(document.verifierApplication.txtCompanyName.value) == "") {
				message += "Please Enter Company Name\n\n";
				document.verifierApplication.txtCompanyName.style.backgroundColor = "#FAFAFA";
			}
			
			// Check Organisation type and check registered number if applicable
			var orgTypes = document.getElementsByName('radOrgType');
			var orgTypeChecked = false;
			var orgTypeValue;
			
			for (var i = 0; i < orgTypes.length; i++) {
				if (orgTypes[i].checked) {
					orgTypeChecked = true;
					orgTypeValue = orgTypes[i].value;
				}
			}
			if (!orgTypeChecked) message += "Please Select Organisation Type\n\n";
			
			if (orgTypeValue == "5") {
				if (document.verifierApplication.txtPlcRegno.value.length == 0) {
					message += "Please specify Reistered No\n\n";
					document.verifierApplication.txtPlcRegno.style.backgroundColor = "#FAFAFA";
				}
				if (!document.verifierApplication.txtPlcRegno.value.match(/^\d+$/)) {
					message += "Please Enter Valid Registered Number\n\n";
					document.verifierApplication.txtPlcRegno.style.backgroundColor = "#FAFAFA";
				}
			} else if (orgTypeValue == "4") {
				  if (document.verifierApplication.txtLtdRegno.value.length == 0) {
					message += "Please specify Reistered No\n\n";
					document.verifierApplication.txtLtdRegno.style.backgroundColor = "#FAFAFA";
				}

				if (!document.verifierApplication.txtLtdRegno.value.match(/^\d+$/)) {
					message += "Please Enter Valid Registered Number\n\n";
					document.verifierApplication.txtLtdRegno.style.backgroundColor = "#FAFAFA";
				}
			} else if (orgTypeValue == "2") {
				if (document.verifierApplication.txtLlpRegno.value.length == 0) {
					message += "Please specify Reistered No\n\n";
					document.verifierApplication.txtLlpRegno.style.backgroundColor = "#FAFAFA";
				}

				if (!document.verifierApplication.txtLlpRegno.value.match(/^\d+$/)) {
					message += "Please Enter Valid Registered Number\n\n";
					document.verifierApplication.txtLlpRegno.style.backgroundColor = "#FAFAFA";
				}
			}
			
			// Check Number of Years Established is selected
			var noOfYears = document.getElementsByName('radNoYrEstab');
			var yearsChecked = false;
			
			for (var i = 0; i < noOfYears.length; i++) {
				if (noOfYears[i].checked) {
					yearsChecked = true;
				}
			}
			
			if (!yearsChecked) message += "Please Select a Number of Years Established\n\n";
			
			// Check Number of Employees is selected
			var noOfEmployees = document.getElementsByName('radNoOfEmployees');
			var employeesChecked = false;
			
			for (var i = 0; i < noOfEmployees.length; i++) {
				if (noOfEmployees[i].checked) {
					employeesChecked = true;
				}
			}
			
			if (!employeesChecked) message += "Please Select a Number of Employees\n\n";
			
			// Check Street has been filled in
			if (trim(document.verifierApplication.txtStreet.value) == "") {
				message += "Please Enter Street\n\n";
				document.verifierApplication.txtStreet.style.backgroundColor = "#FAFAFA";
			}
			
			// Check Post/Zip Code has been filled in
			if (trim(document.verifierApplication.txtPostcode.value) == "") {
				message += "Please Enter Post/Zip Code\n\n";
				document.verifierApplication.txtPostcode.style.backgroundColor = "#FAFAFA";
			}
			else
			{
				if (!isUKPostCode(trim(document.verifierApplication.txtPostcode.value))) {
					document.verifierApplication.txtPostcode.style.backgroundColor = "#FAFAFA";
					message += "The Post/Zip Code does not appear to be valid. Please re-enter\n\n";
				}
				
			}

			// Check message is blank, if it is continue, otherwise display errors
			if (message != "") {
				alert(message);
			} else {
				if (typeof(theFlag) == "undefined") {
					stepProceed('displayStep1', 'displayStep2', 'step1', 'step2');
				} else {
					stepProceed('displayStep1', 'displayStep2', 'step1', 'step2', theFlag);
				}
			}		
			
		break;

        case "step2":
			var message = "";
			
			// Check that the First Name box is filled in
			if (trim(document.verifierApplication.txtFirstName.value) == "") {
				message += "Please Enter your First Name\n\n";
				document.verifierApplication.txtFirstName.style.backgroundColor = "#FAFAFA";
			}
			
			// Check that the Surname box is filled in
			if (trim(document.verifierApplication.txtSurname.value) == "") {
				message += "Please Enter your Surname\n\n";
				document.verifierApplication.txtSurname.style.backgroundColor = "#FAFAFA";
			}
			
			// Check that the DOB box is filled in
			if (trim(document.verifierApplication.txtDOB.value) == "") {
				message += "Please Enter your DOB\n\n";
				document.verifierApplication.txtDOB.style.backgroundColor = "#FAFAFA";
			}
			else
			{
				// Check the DOB field is of a valid date format
				if (!isDate(trim(document.verifierApplication.txtDOB.value))) 
				{
					document.verifierApplication.txtDOB.style.backgroundColor = "#FAFAFA";
					message += "The Date of Birth does not appear to be valid. Please re-enter\n\n";
				}
				if (!IsDateInPast(trim(document.verifierApplication.txtDOB.value)))
				{
					document.verifierApplication.txtDOB.style.backgroundColor = "#FAFAFA";
					message += "The Date of Birth does not appear to be valid. Please re-enter\n\n";
				}
			  
			}

			// Check that the DOB hasn't been invalidated
			if (document.getElementById('dobBadDate').style.display == "") {
				message += "The Date Of Birth entered appears not to be valid. Please check and re-enter\n\n";
				document.verifierApplication.txtDOB.style.backgroundColor = "#FAFAFA";
			}
			
			// Check the Email box is filled in
			if (!document.verifierApplication.txtEmail.value.match(/^\S+@\S+(\.)\S{2,4}$/)) {
				message += "The Email Address entered appears not to be valid. Please check and re-enter\n\n";
				document.verifierApplication.txtEmail.style.backgroundColor = "#FAFAFA";
			}
			
			// Check the Username box is filled in
			if (!document.verifierApplication.txtUsername.value.match(/^\S{4,50}$/)) {
				message += "Please Enter a Username of between 4 and 50 characters\n\n";
				document.verifierApplication.txtUsername.style.backgroundColor = "#FAFAFA";
			}
			
			// Check message is blank, if not, alert message
			if (message != "") {
				alert(message);
			} else {
				document.verifierApplication.submit();
			}
		break;
            
    }
}

// Scripts for addpassport.asp
function assignPassport() {
	if (selectedPassportType != "") {
		document.location.href = "assignpassport.asp?AssignedType=" + selectedPassportType;
	}
}

function showOtherID() {
	if (document.getElementById('selVerifyID').value == "other") {
		document.getElementById('otherID').style.display = "";
	} else {
		document.getElementById('otherID').style.display = "none";
	}
}

// Scripts for assignpassport.asp
function assignPassport_onSubmit() {
	// Initialise message variable
	var message = "";
	
	// Set all inputs to normal background
	var textFields = document.assignpassport.getElementsByTagName('input');
	for (var i = 0; i < textFields.length; i++) {
		textFields[i].style.backgroundColor = "";
	}
	
	// Check the Firstname field is filled in
	if (document.assignpassport.txtFirstName.value == "") {
		document.assignpassport.txtFirstName.style.backgroundColor = "#FAFAFA";
		message += "Please Enter the Passport Holder's First Name\n\n";
	}
	
	// Check the Surname field is filled in
	if (document.assignpassport.txtSurname.value == "") {
		document.assignpassport.txtSurname.style.backgroundColor = "#FAFAFA";
		message += "Please Enter the Passport Holder's Surname\n\n";
	}
	
	// Check the DOB field is filled in
	if (document.assignpassport.txtDOB.value == "") {
		document.assignpassport.txtDOB.style.backgroundColor = "#FAFAFA";
		message += "Please Enter the Passport Holder's Date of Birth\n\n";
	}
	else
	{
		// Check the DOB field is of a valid date format
		if (!isDate(document.assignpassport.txtDOB.value)) 
		{
			document.assignpassport.txtDOB.style.backgroundColor = "#FAFAFA";
			message += "The Date of Birth does not appear to be valid. Please re-enter\n\n";
		}
		if (!IsDateInPast(document.assignpassport.txtDOB.value))
		{
			document.assignpassport.txtDOB.style.backgroundColor = "#FAFAFA";
			message += "The Date of Birth does not appear to be valid. Please re-enter\n\n";
		}
	  
	}
	
	// Check the DOB field is of a valid date format
	if (document.getElementById('dobBadDate').style.display == "") {
		document.assignpassport.txtDOB.style.backgroundColor = "#FAFAFA";
		message += "The Date of Birth does not appear to be valid. Please re-enter\n\n";
	}
	
	// Check the Email field is filled in
	if (document.assignpassport.txtEmail.value == "") {
		document.assignpassport.txtEmail.style.backgroundColor = "#FAFAFA";
		message += "Please Enter the Passport Holder's Email Address\n\n";
	}
	
	// Check the Email address is valid
	if (!IsEmail(document.assignpassport.txtEmail.value)) {
		document.assignpassport.txtEmail.style.backgroundColor = "#FAFAFA";
		message += "The Email Address does not appear to be valid. Please re-enter\n\n";
	}
	
	// Check the Street Number or House Name field is filled in
	if (document.assignpassport.txtNumberName.value == "") {
		document.assignpassport.txtNumberName.style.backgroundColor = "#FAFAFA";
		message += "Please Enter the Passport Holder's Street Number or House Name\n\n";
	}
	
	// Check the Street field is filled in
	if (document.assignpassport.txtStreet.value == "") {
		document.assignpassport.txtStreet.style.backgroundColor = "#FAFAFA";
		message += "Please Enter the Passport Holder's Street\n\n";
	}
	
	// Check the Post/Zip Code field is filled in
	if (trim(document.assignpassport.txtPostCode.value) == "") {
		document.assignpassport.txtPostCode.style.backgroundColor = "#FAFAFA";
		message += "Please Enter the Passport Holder's Post/Zip Code\n\n";
	}
	else
	{
		if (!isUKPostCode(trim(document.assignpassport.txtPostCode.value))) {
			document.assignpassport.txtPostCode.style.backgroundColor = "#FAFAFA";
			message += "The Post/Zip Code does not appear to be valid. Please re-enter\n\n";
		}
		
	}

	// Check the Username field is filled in
	if (document.assignpassport.txtUsername.value == "") {
		document.assignpassport.txtUsername.style.backgroundColor = "#FAFAFA";
		message += "Please Enter the Passport Holder's Username\n\n";
	}
	
	// Check the Username box is filled in
	if (!document.assignpassport.txtUsername.value.match(/^\S{4,50}$/)) {
		message += "Please Enter a Username of between 4 and 50 characters\n\n";
		document.assignpassport.txtUsername.style.backgroundColor = "#FAFAFA";
	}
	
	// Check the I.D Verified With field is filled in
	if (document.assignpassport.selVerifyID.value == "") {
		document.assignpassport.selVerifyID.style.backgroundColor = "#FAFAFA";
		message += "Please Enter the Document seen to prove this Passport Holder's Identity\n\n";
	}
	
	// If Other was chosen as proof document then be sure the Other field is filled in
	if (document.assignpassport.selVerifyID.value == "other") {
		if (document.assignpassport.txtOtherID.value == "") {
			document.assignpassport.txtOtherID.style.backgroundColor = "#FAFAFA";
			message += "Please Enter the Document seen to prove this Passport Holder's Identity\n\n";
		}
	}
	
	// Check the Copy made radio's have been selected
	var copyMade = document.getElementsByName('radIdCopyMade');
    var copyLength = copyMade.length;
    var copyValue = "";

    for (var i = 0; i < copyLength; i++) {
    	if (copyMade[i].checked == true) {
        	copyValue = copyMade[i].value;
        }
    }

	if (copyValue == "") {
		message += "Please Select whether a copy of the Proof Document was made\n\n";
	}
	
	// Check message variable, if it's empty then submit the form, otherwise show error
	if (message != "") {
		alert(message);
	} else {
		document.assignpassport.submit();
	}
}	

function photograph_onSubmit() {
	if (document.photograph.filePhoto.value == "") {
		alert("A Photograph is needed to complete this Application\n\n");
	} else {
		document.photograph.submit();
	}
}

// Scripts for buypassports.asp
function validateBuyPassports(paymentMethod) {
    // Declare message variable
    var oneYearTotal = 0;
    var fiveYearTotal = 0;
    var tenYearTotal = 0;
    var lifetimeTotal = 0;
    var totalAmount = 0;

    // If the passport type objects exist, then check at least one has an amount to purchase
    // Check also that each field is not blank, if it is, assume it is zero
    if (objectExists(document.getElementById('txtOneYear'))) {
        if (trim(document.getElementById('txtOneYear').value) != "") {
            oneYearTotal = parseInt(document.getElementById('txtOneYear').value);
        }
    }

    if (objectExists(document.getElementById('txtFiveYear'))) {
        if (trim(document.getElementById('txtFiveYear').value) != "") {
            fiveYearTotal = parseInt(document.getElementById('txtFiveYear').value);
        }
    }

    if (objectExists(document.getElementById('txtTenYear'))) {
        if (trim(document.getElementById('txtTenYear').value) != "") {
            tenYearTotal = parseInt(document.getElementById('txtTenYear').value);
        }
    }

    if (objectExists(document.getElementById('txtLifetime'))) {
        if (trim(document.getElementById('txtLifetime').value) != "") {
            lifetimeTotal = parseInt(document.getElementById('txtLifetime').value);
        }
    }

    // Add up the amount of passports purchased
    totalAmount = (oneYearTotal + fiveYearTotal + tenYearTotal + lifetimeTotal);

    // If amount is 0 then alert the user to the need to select the amount they wish to purchase, otherwise continue to worldpay
    if (totalAmount == 0) {
        alert('Please Enter the Amount of Passports for each Passport Type you wish to purchase');
    }
    else {
        if (paymentMethod == 'WorldPay') {
            document.worldpay_checkout.submit();
        }
        else {
            document.paypal_checkout.submit();
        }
    }
}

// Scripts for mypassportholders.asp
var viewType = "";
var previousTab;
function mypassportholders_onLoad() {
		
	if (location.search.indexOf('directEmployees') > -1) {
		document.getElementById('directCreatedByTab').className = "tab";
		document.getElementById('directEmployeeTab').className = "selectedTab";
		document.getElementById('directEmployees').style.display = "";
		previousTab = "directEmployeeTab";
	} else if (location.search.indexOf('directCreatedby') > -1) {
		document.getElementById('directEmployeeTab').className = "tab";
		document.getElementById('directCreatedByTab').className = "selectedTab";
		document.getElementById('directCreatedBy').style.display = "";
		previousTab = "directCreatedByTab";
	} else {
		previousTab = "directEmployeeTab";
		moveTab(previousTab, 'directEmployees');
	}
}

function myverifiers_onLoad() {
		
	if (location.search.indexOf('directEmployees') > -1) {
		document.getElementById('directCreatedByTab').className = "tab";
		document.getElementById('directEmployeeTab').className = "selectedTab";
		document.getElementById('directEmployees').style.display = "";
		previousTab = "directEmployeeTab";
	} else if (location.search.indexOf('directCreatedby') > -1) {
		document.getElementById('directEmployeeTab').className = "tab";
		document.getElementById('directCreatedByTab').className = "selectedTab";
		document.getElementById('directCreatedBy').style.display = "";
		previousTab = "directCreatedByTab";
	} else {
		previousTab = "directEmployeeTab";
		moveTabVerifierReports(previousTab, 'directEmployees');
	}
}

function mysectorskills_onLoad() {
		
	if (location.search.indexOf('directEmployees') > -1) {
		document.getElementById('directCreatedByTab').className = "tab";
		document.getElementById('directEmployeeTab').className = "selectedTab";
		document.getElementById('directEmployees').style.display = "";
		previousTab = "directEmployeeTab";
	} else if (location.search.indexOf('directCreatedby') > -1) {
		document.getElementById('directEmployeeTab').className = "tab";
		document.getElementById('directCreatedByTab').className = "selectedTab";
		document.getElementById('directCreatedBy').style.display = "";
		previousTab = "directCreatedByTab";
	} else {
		previousTab = "directEmployeeTab";
		moveTabSectorSkillsReports(previousTab, 'directEmployees');
	}
}


function chooseLetter(theLetter) {
	document.location.href = "mypassportholders.asp?searchLetter=" + theLetter + "&viewtype=" + viewType;
}

function chooseLetter2(theLetter) {
  var x = '&DivisionID=' + document.getElementById('cmb_multi_ent_multi1').myData + 
          '&DepartmentID=' + document.getElementById('cmb_multi_ent_multi2').myData + 
          '&DivisionValue=' + document.getElementById('cmb_multi_ent1').value + 
          '&DepartmentValue=' + document.getElementById('cmb_multi_ent2').value +
          '&index=' + document.index;
	document.location.href = "PasportHoldersAtOrganisation.asp?searchLetter=" + theLetter + x;
}

function chooseUnlinkLetter(theLetter) {
	document.location.href = "unlinkpassportholders.asp?searchLetter=" + theLetter + "&viewtype=" + viewType;
}

function showPassport(theForm, id, username) {
	document.forms[theForm].id.value = id;
	document.forms[theForm].txtUsername.value = username;
	
	document.forms[theForm].submit();
}

function moveTab(theTab, thePane) {
	// Hide both panes
	document.getElementById('directEmployees').style.display = "none";
	document.getElementById('directCreatedBy').style.display = "none";
	document.getElementById('allEmployees').style.display = "none";
	document.getElementById('allCreatedBy').style.display = "none";
	
	// Set PreviousTab back to normal
	document.getElementById(previousTab).className = "tab";
	
	// Set previousTab to this tab being clicked
	previousTab = theTab;
	
	// Set this tab being clicked to selected
	document.getElementById(theTab).className = "selectedTab";
	
	// Show the pane
	document.getElementById(thePane).style.display = "";
	
	// set view type depending on the tab
	if (theTab == "directEmployeeTab") {
		viewType = "directEmployees";
	} else {
		viewType = "directCreatedby";
	}
}

function moveTabVerifierReports(theTab, thePane) {
	// Hide both panes
	document.getElementById('directEmployees').style.display = "none";
	document.getElementById('directCreatedBy').style.display = "none";
	document.getElementById('allEmployees').style.display = "none";
    
	
	// Set PreviousTab back to normal
	document.getElementById(previousTab).className = "tab";
	
	// Set previousTab to this tab being clicked
	previousTab = theTab;
	
	// Set this tab being clicked to selected
	document.getElementById(theTab).className = "selectedTab";
	
	// Show the pane
	document.getElementById(thePane).style.display = "";
	
	// set view type depending on the tab
	if (theTab == "directEmployeeTab") {
		viewType = "directEmployees";
	} else {
		viewType = "directCreatedby";
	}
	
		
}	

function moveTabSectorSkillsReports(theTab, thePane) {
	// Hide both panes
	document.getElementById('directEmployees').style.display = "none";
	document.getElementById('directCreatedBy').style.display = "none";
    
	
	// Set PreviousTab back to normal
	document.getElementById(previousTab).className = "tab";
	
	// Set previousTab to this tab being clicked
	previousTab = theTab;
	
	// Set this tab being clicked to selected
	document.getElementById(theTab).className = "selectedTab";
	
	// Show the pane
	document.getElementById(thePane).style.display = "";
	
		
}

function gotoPageVerifierID(varItem)        
{            
    window.location="verifierreports.asp?VerifierID="+varItem;             
}
        
function gotoPageCardType(varItem)        
{            
    window.location="verifierreports.asp?CardTypeID="+varItem;             
}
        
        
function removeEmployerLink(phid, name, vid, searchLetter) {
	var sure = confirm('This will remove the link stating that ' + name + ' is employed by your organisation. Click OK to Continue, otherwise click Cancel');
	if (sure == true) { 
		document.location.href = "mypassportholders.asp?actionType=remove&phid=" + phid + "&vid=" + vid + "&searchLetter=" + searchLetter;
	}
}

// Scripts for passport holders application.asp
function getapassport_onSubmit() {
	// Initialise message variable
	var message = "";
	
	// Set all inputs to normal background
	var textFields = document.getapassport.getElementsByTagName('input');
	for (var i = 0; i < textFields.length; i++) {
		textFields[i].style.backgroundColor = "";
	}
	
	// Check the Firstname field is filled in
	if (document.getapassport.txtFirstName.value == "") {
		document.getapassport.txtFirstName.style.backgroundColor = "#FAFAFA";
		message += "Please Enter your First Name\n\n";
	}
	
	// Check the Surname field is filled in
	if (document.getapassport.txtSurname.value == "") {
		document.getapassport.txtSurname.style.backgroundColor = "#FAFAFA";
		message += "Please Enter your Surname\n\n";
	}
	
	// Check the DOB field is filled in
	if (document.getapassport.txtDOB.value == "") {
		document.getapassport.txtDOB.style.backgroundColor = "#FAFAFA";
		message += "Please Enter your Date of Birth\n\n";
	}
	else
	{
		// Check the DOB field is of a valid date format
		if (!isDate(document.getapassport.txtDOB.value)) 
		{
			document.getapassport.txtDOB.style.backgroundColor = "#FAFAFA";
			message += "The Date of Birth does not appear to be valid. Please re-enter\n\n";
		}
		if (!IsDateInPast(document.getapassport.txtDOB.value))
		{
			document.getapassport.txtDOB.style.backgroundColor = "#FAFAFA";
			message += "The Date of Birth does not appear to be valid. Please re-enter\n\n";
		}
	  
	}
	
	// Check the DOB field is of a valid date format
	if (document.getElementById('dobBadDate').style.display == "") {
		document.getapassport.txtDOB.style.backgroundColor = "#FAFAFA";
		message += "The Date of Birth does not appear to be valid. Please re-enter\n\n";
	}
	
	// Check the Email field is filled in
	if (document.getapassport.txtEmail.value == "") {
		document.getapassport.txtEmail.style.backgroundColor = "#FAFAFA";
		message += "Please Enter your Email Address\n\n";
	}
	else
	{
		if (!IsEmail(document.getapassport.txtEmail.value)) {
			document.getapassport.txtEmail.style.backgroundColor = "#FAFAFA";
			message += "The Email Address does not appear to be valid. Please re-enter\n\n";
		}
	}	
	
	// Check the Street Number or House Name field is filled in
	if (document.getapassport.txtNumberName.value == "") {
		document.getapassport.txtNumberName.style.backgroundColor = "#FAFAFA";
		message += "Please Enter your Street Number or House Name\n\n";
	}
	
	// Check the Street field is filled in
	if (document.getapassport.txtStreet.value == "") {
		document.getapassport.txtStreet.style.backgroundColor = "#FAFAFA";
		message += "Please Enter your Street\n\n";
	}
	
	// Check the Post/Zip Code field is filled in
	if (trim(document.getapassport.txtPostCode.value) == "") {
		document.getapassport.txtPostCode.style.backgroundColor = "#FAFAFA";
		message += "Please Enter your Post/Zip Code\n\n";
	}
	else
	{
		if (!isUKPostCode(trim(document.getapassport.txtPostCode.value))) {
			document.getapassport.txtPostCode.style.backgroundColor = "#FAFAFA";
			message += "The Post/Zip Code does not appear to be valid. Please re-enter\n\n";
		}
		
	}
	
	// Check the Username box is filled in
	if (!document.getapassport.txtUsername.value.match(/^\S{4,50}$/)) {
		message += "Please Enter a Username of between 4 and 50 characters\n\n";
		document.getapassport.txtUsername.style.backgroundColor = "#FAFAFA";
	}	
	
	// If Nothing Is Selected in Voucher Choice, show message
	if (!(document.getElementById('radVoucherY').checked) && (!(document.getElementById('radVoucherN').checked)))
	{
	    message += "Please Select whether you have a Voucher Code or not\n\n";
	}
	else
	{
	    if (document.getElementById('radVoucherY').checked)
	    {
	        // Yes was selected, check for presence of voucher code
	        if (trim(document.getElementById('txtVoucherCode').value) == "")
	        {
	            message += "Please Enter your Voucher Code\n\n";
	            document.getElementById('txtVoucherCode').style.backgroundColor = "#FAFAFA";
	        }
	        else
	        {
	            // Voucher code was entered, check it was validated
	            if (document.getElementById('spanVerifier').innerHTML == "")
	            {
	                message += "Please Validate your Voucher Code\n\n";
	                document.getElementById('txtVoucherCode').style.backgroundColor = "#FAFAFA";
	            }
	        }
	    }
	    else
	    {
	        // Check the Payment Type was chosen
	        if (document.getapassport.selPaymentType.value == "") {
		        document.getapassport.selPaymentType.style.backgroundColor = "#FAFAFA";
		        message += "Please Select a Payment Type\n\n";
	        }
	    }
	}

	if (document.getElementById("txtExpireDate").value != "")
	{
	    if (!isDate(document.getElementById("txtExpireDate").value))
	    {
	        document.getapassport.txtExpireDate.style.backgroundColor = "#FAFAFA";
	        message += "Please Enter correct Expire Date(dd.mm.yyyy)\n\n";	    
	    }
	    else if (IsDateInPast(document.getElementById("txtExpireDate").value))
	    {
	        document.getapassport.txtExpireDate.style.backgroundColor = "#FAFAFA";
	        message += "The Membership Expire Date can`t less than currect date!\n\n";	    
	    }
	}	
	
	// Check message variable, if it's empty then submit the form, otherwise show error
	if (message != "") {
		alert(message);
    } else {
		document.getapassport.submit();
	}
}

				
function IsDateInPast(tDate)
{                         
    var firstIndex = tDate.indexOf("/");
    var secondIndex = tDate.lastIndexOf("/");
    
    var d1 = tDate.substring(0,firstIndex);
    var m1 = tDate.substring(firstIndex+1, secondIndex);
    var y1 = tDate.substring(secondIndex+1, tDate.length);
    var tDateFull = m1 + "/" + d1 + "/" +y1;

    var dtDate = new Date(tDateFull);
    var dtCur = new Date();
    
    if(dtDate < dtCur)
        return true;
    else
        return false;  
}	

function renewapassport_onSubmit() {
	// Initialise message variable
	var message = "";
	
	// Set all inputs to normal background
	var textFields = document.getapassport.getElementsByTagName('input');
	for (var i = 0; i < textFields.length; i++) {
		textFields[i].style.backgroundColor = "";
	}
	
	// Check the Payment Type was chosen
	if (document.getapassport.selPaymentType.value == "") {
		document.getapassport.selPaymentType.style.backgroundColor = "#FAFAFA";
		message += "Please Select a Payment Type\n\n";
	}
	
	// Check message variable, if it's empty then submit the form, otherwise show error
	if (message != "") {
		alert(message);
	} else {
		document.getapassport.submit();
	}
}		

// Scripts for skillsearch.asp
function skillSearch_onSubmit() {
	// Declare Message Variable
	var message = "";
	
	if (document.getElementById('normalSearch').style.display == "") {
		if (document.skillSearch.selSkillDescription.value == "other" || document.skillSearch.selSkillDescription.value == "") {
			if (document.skillSearch.txtSkillOtherDescription.value == "") {
				message = "Please Enter The Skill Title";
			}
		}
	} else {
		if (document.skillSearch.selWithSkillDescription.value == "other" || document.skillSearch.selWithSkillDescription.value == "") {
			if (document.skillSearch.txtWithSkillOtherDescription.value == "") {
				message += "Please Enter \"With\" Skill Title\n\n";
			}
		}
	
		if (document.skillSearch.selWithoutSkillDescription.value == "other" || document.skillSearch.selWithoutSkillDescription.value == "") {
			if (document.skillSearch.txtWithoutSkillOtherDescription.value == "") {
				message += "Please Enter \"Without\" Skill Title\n\n";
			}
		}
	}
	
	if (message != "") {
		alert(message);
	} else {
		document.skillSearch.submit();
	}
}

function withWithout() {
	var radioArray = document.getElementsByName('searchType');
	var selected;
	
	for (var i = 0; i < radioArray.length; i++) {
		if (radioArray[i].checked == true) {
			selected = radioArray[i].value;
		}
	}
	
	if (selected == "with/without") {
		document.getElementById('normalSearch').style.display = "none";
		document.getElementById('withWithoutSearch').style.display = "";
	} else {
		document.getElementById('normalSearch').style.display = "";
		document.getElementById('withWithoutSearch').style.display = "none";
	}
}

// Scripts for verifypassport.asp
function otherProof(theForm, theDisplay) {
	if (document.forms[theForm].selVerifyDoc.value == "other") {
		document.getElementById(theDisplay).style.display = "";
	} else {
		document.getElementById(theDisplay).style.display = "none";
	}
}

function verifyPassport_onSubmit(scenario) {
	var message = "";
	
	switch (scenario) {
		case "scenario1":
  	  var radY = document.getElementById("radCopyMadeY").checked;
	    var radN = document.getElementById("radCopyMadeN").checked;
			if (document.verifyPassport1.selVerifyDoc.value == "") {
				message += "Please Select Verification Document\n\n";
			}
			if (document.verifyPassport1.selVerifyDoc.value == "other") {
				if (document.verifyPassport1.txtOtherDoc.value == "") {
					message += "Please Enter the Other Type of Document seen to verify this identity";
				}
			}
			if (!radY && !radN) {
				message += "Please check YES if copy of document was made or NO if wasn`t";
			}
			if (message != "") {
				alert(message);
			} else {
				document.verifyPassport1.submit();
			}
		break;
		
		case "scenario2":
			if (document.verifyPassport2.filePhoto.value == "") {
				message += "Please Select the Photograph to Upload\n\n";
			}
			
			if (message != "") {
				alert(message);
			} else {
				document.verifyPassport2.submit();
			}
		break;
	}
}

function redirect(newUrl)
{
	document.location.href 	= newUrl;
}

function replaceSubstring(inputString, fromString, toString) {
   // Goes through the inputString and replaces every occurrence of fromString with toString
   var temp = inputString;
   if (fromString == "") {
      return inputString;
   }
   if (toString.indexOf(fromString) == -1) { // If the string being replaced is not a part of the replacement string (normal situation)
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } else { // String being replaced is part of replacement string (like "+" being replaced with "++") - prevent an infinite loop
      var midStrings = new Array("~", "`", "_", "^", "#");
      var midStringLen = 1;
      var midString = "";
      // Find a string that doesn't exist in the inputString to be used
      // as an "inbetween" string
      while (midString == "") {
         for (var i=0; i < midStrings.length; i++) {
            var tempMidString = "";
            for (var j=0; j < midStringLen; j++) { tempMidString += midStrings[i]; }
            if (fromString.indexOf(tempMidString) == -1) {
               midString = tempMidString;
               i = midStrings.length + 1;
            }
         }
      } // Keep on going until we build an "inbetween" string that doesn't exist
      // Now go through and do two replaces - first, replace the "fromString" with the "inbetween" string
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + midString + toTheRight;
      }
      // Next, replace the "inbetween" string with the "toString"
      while (temp.indexOf(midString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(midString));
         var toTheRight = temp.substring(temp.indexOf(midString)+midString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } // Ends the check to see if the string being replaced is part of the replacement string or not
   return temp; // Send the updated string back to the user
} // Ends the "replaceSubstring	

	function getBrowserName()
					{
						var detect = navigator.userAgent.toLowerCase();
						var OS,browser,version,total,thestring;
					
						if (checkIt('konqueror'))
						{
							browser = "Konqueror";
							OS = "Linux";
						}
						else if (checkIt('safari')) browser = "Safari"
						else if (checkIt('omniweb')) browser = "OmniWeb"
						else if (checkIt('opera')) browser = "Opera"
						else if (checkIt('webtv')) browser = "WebTV";
						else if (checkIt('icab')) browser = "iCab"
						else if (checkIt('msie')) browser = "Internet Explorer"
						else if (!checkIt('compatible'))
						{
							browser = "Netscape Navigator"
							version = detect.charAt(8);
						}
						else browser = "An unknown browser";
					
						if (!version) version = detect.charAt(place + thestring.length);
					
						if (!OS)
						{
							if (checkIt('linux')) OS = "Linux";
							else if (checkIt('x11')) OS = "Unix";
							else if (checkIt('mac')) OS = "Mac"
							else if (checkIt('win')) OS = "Windows"
							else OS = "an unknown operating system";
						}
					
						return browser;
										
							function checkIt(string)
							{
								place = detect.indexOf(string) + 1;
								thestring = string;
								return place;
							}//end of checkIt function
					}//end of getBrowserName function

function validateTextLength(obj)
{
	if (obj.value.length >= 400) 
		obj.value = obj.value.substring(0, 400);
}

function validateHtmlTags(str)
{
	return escape(str);
}

function enableOnlyDigit(event, keyRE) 
{
    event=event||window.event;
    if ((typeof (event.keyCode) != 'undefined' && event.keyCode > 0 && String.fromCharCode(event.keyCode).search(keyRE) != (-1)) ||
        (typeof (event.charCode) != 'undefined' && event.charCode > 0 && String.fromCharCode(event.charCode).search(keyRE) != (-1)) ||
        (typeof (event.charCode) != 'undefined' && event.charCode != event.keyCode && typeof (event.keyCode) != 'undefined' && event.keyCode.toString().search(/^(8|9|13|45|46|35|36|37|39)$/) != (-1)) ||
        (typeof (event.charCode) != 'undefined' && event.charCode == event.keyCode && typeof (event.keyCode) != 'undefined' && event.keyCode.toString().search(/^(8|9|13)$/) != (-1)) ||
        (typeof (event.keyCode) != 'undefined' && event.keyCode.toString().search(/^(8|9|13|45|46|35|36|37|39)$/) != (-1))) {

        if (event.keyCode == 13)
            showUsersList(window.event ? window.event.srcElement : event.currentTarget);
        return true;
    }
    else
        return false;
}

function disablePasteHandler()
{
	return false;
}
function disablePasteHandlerFF(e)
{
	var str = e.target.value;
	for (var i = 0; i < str.length; i++)
	{
		if (str.charCodeAt(i) > 57 || str.charCodeAt(i) < 48)
		{
			e.target.value = "";
			e.preventDefault();
		}
	}
}

function disablePaste(obj) {
    if (obj.addEventListener)
    {
        obj.addEventListener("input", disablePasteHandlerFF, false);
    }
    else 
		if (obj.attachEvent)
			obj.attachEvent("onpaste", disablePasteHandler);
		else 
			obj.onclick = disablePasteHandler;
}

function GetXmlHttpObject(handler)
{ 
    var objXmlHttp=null;
    var ua = navigator.userAgent.toLowerCase();
    if (ua.indexOf("msie") > -1) {
        try { objXmlHttp = new ActiveXObject("Msxml2.XMLHTTP.6.0"); } 
        catch(e) 
        {
            try { objXmlHttp = new ActiveXObject("Msxml2.XMLHTTP.3.0"); } 
            catch(e) 
            {
                try { objXmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } 
                catch(e) 
                {
                    try { objXmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } 
                    catch(e) 
                    {
                        alert("Error. Scripting for ActiveX might be disabled");
                        return;                    
                    }        
                }    
            }
        } 
    } 
    else 
    {
        objXmlHttp = new XMLHttpRequest();
        objXmlHttp.onload=handler;
        objXmlHttp.onerror=handler;                     
    }    
    objXmlHttp.onreadystatechange = handler;    
    return objXmlHttp;
} 

function showUploadCertificate(PHID,fieldName) {
  if(PHID == "")
  {
    alert('Select ID before Certificate Image upload, please!')
    return false;
  }
	var addSkillLeft = (screen.width - 954) / 2;
	var addSkillTop = (screen.height - 450) / 2;
	var skillDetailWindow;	
		
	skillDetailWindow = window.open('/popups/addCertificateImage.asp?PHID='+PHID+'&fieldName='+fieldName, 'Certificate', 'modal=yes,width=954,height=450,left=' + addSkillLeft + ',top=' + addSkillTop);
	skillDetailWindow.title = "Upload Certificate image";
	skillDetailWindow.opener = this;
}

function setOuterHTML(ElementID, txt)
{
    var someElement = document.getElementById(ElementID); 
    if (someElement.outerHTML)
        someElement.outerHTML = txt;
    else
    {
        var range = document.createRange();
        range.setStartBefore(someElement);
        var docFrag = range.createContextualFragment(txt);
        someElement.parentNode.replaceChild(docFrag, someElement);
    }
    return someElement;
} 

function setCookie (name, value, expires, path, domain, secure) {
      document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

function getCookie(name) {
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookie.indexOf(";", offset)
			if (end == -1) {
				end = cookie.length;
			}
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return(setStr);
}

function isUKPostCode(code)
{

// Matches: M1 1AA | EC1A 1BB | DN55 1PT
// Non-Matches: SW17 8CB
    code = code.toUpperCase();
	var datePat = /^((([A-PR-UWYZ](\d([A-HJKSTUW]|\d)?|[A-HK-Y]\d([ABEHMNPRVWXY]|\d)?))\s*(\d[ABD-HJLNP-UW-Z]{2})?)|GIR\s*0AA)$/;

  return datePat.test(code);
}

function checkSession()
{
    if (('<%= Session("ID")%>' == "") && ('<%= Session("SkillID") %>' == "")) location.href="index.asp";
}
