﻿function NewLogin()
{
	var THIS = this;
	var divLoginpopup = document.getElementById("divLoginpopup");
	var txtUserName = document.getElementById("txtUserName");
	var txtPassword = document.getElementById("txtPassword");
	var chkRememberMe = document.getElementById("chkRememberMe");
	var chkRememberPassword = document.getElementById("chkRememberPassword");
	var loginMessage = document.getElementById("loginMessage");
	var btnLogin = document.getElementById("btnLogin");
	var btnCancel = document.getElementById("btnCancel");
	var lnkForgotPassword = document.getElementById("lnkForgotPassword");
	var chkRedirectOnLogin = document.getElementById("chkRedirectOnLogin");
	var tdForgotPassword = document.getElementById("tdForgotPassword");

	var txtCurrentPassword = document.getElementById("txtCurrentPassword");
	var txtNewPassword = document.getElementById("txtNewPassword");
	var txtConfirmPassword = document.getElementById("txtConfirmPassword");
	var divChangePassword = document.getElementById("changePassword");
	var btnChangePassword_Cancel = document.getElementById("btnChangePassword_Cancel");
	var btnChangePassword = document.getElementById("btnChangePassword");
	var txtLoginRedirect = document.getElementById("strLoginRedirect_Value");
	var strLoginRedirect = txtLoginRedirect != null ? txtLoginRedirect.value : "";

	if (strLoginRedirect.toLowerCase().indexOf("session.aspx") != -1)
		strLoginRedirect = "";

	if (tdForgotPassword != null)
	{
		if (tdForgotPassword.attachEvent)
			tdForgotPassword.attachEvent("onclick", lnkForgotPassword_Click);
		else
			tdForgotPassword.addEventListener("click", lnkForgotPassword_Click, false);
	}
	
	this.ChangePasswordPopup = null;

	if (divChangePassword != null)
		this.ChangePasswordPopup = new NewPopup(divChangePassword);

	this.LoginPopup = null;

	if (divLoginpopup != null)
		this.LoginPopup = new NewPopup(divLoginpopup);

	if (this.LoginPopup != null)
	{
		btnCancel.onclick = btnCancel_Click;
		btnLogin.onclick = btnLogin_Click;
		chkRememberMe.onkeypress = txtPassword_KeyPress;
		txtPassword.onkeypress = txtPassword_KeyPress;
		chkRememberMe.onclick = chkRememberMe_Click;
		if (chkRememberPassword != null)
			chkRememberPassword.onclick = chkRememberPassword_Click;
		txtUserName.onchange = txtUserName_Change;

		var objSource = new DOMStorage_AutoCompleteSource("previousUserNames");

		this.UserNameAutoComplete = new NewAutoComplete(txtUserName, objSource);
		this.UserNameAutoComplete.ItemSelected = UserNameAutoComplete_ItemSelected;
		this.UserNameAutoComplete.UpperCaseOptions = false;
		this.UserNameAutoComplete.Focus = UserNameAutoComplete_Focus;
		this.UserNameAutoComplete.TextChanged = UserNameAutoComplete_TextChanged;
	}

	if (this.ChangePasswordPopup != null)
	{
		btnChangePassword.onclick = btnChangePassword_Click;
		btnChangePassword_Cancel.onclick = btnChangePassword_Cancel_Click;
	}

	if (loginMessage != null)
	{
		if (loginMessage.attachEvent)
			loginMessage.attachEvent("onclick", loginMessage_Click);
		else
			loginMessage.onclick = loginMessage_Click;
	}

	//====================================================
	// A key has been pressed in the username drop down
	//====================================================
	function UserNameAutoComplete_TextChanged(objAutoComplete, strValue)
	{
		try
		{
			if (objAutoComplete.Data && !objAutoComplete.Data[objAutoComplete.Input.value])
				txtPassword.value = "";
		}
		catch (exc)
		{
			HtmlPopup.Error(exc);
		}
	}

	//====================================================
	// The username text box has been focused
	//====================================================
	function UserNameAutoComplete_Focus(evt, objAutoComplete, txtInput)
	{
		try
		{
			objAutoComplete.OpenList();
		}
		catch (exc)
		{
			HtmlPopup.Error(exc);
		}
	}

	//====================================================
	// Focus the username entry
	//====================================================
	this.focusUserName = function focusUserName()
	{
		try
		{
			if (txtUserName != null)
				txtUserName.focus();
		}
		catch (exc)
		{
			HtmlPopup.Error(exc);
		}
	}

	//====================================================
	// Focus the password entry
	//====================================================
	function focusPassword()
	{
		try
		{
			if (txtPassword != null)
				txtPassword.focus();
		}
		catch (exc)
		{
			HtmlPopup.Error(exc);
		}
	}

	//====================================================
	// Focus the new password entry
	//====================================================
	function focusNewPassword()
	{
		try
		{
			if (txtNewPassword != null)	
				txtNewPassword.focus();
		}
		catch (exc)
		{
			HtmlPopup.Error(exc);
		}
	}

	//====================================================
	// Focus the current password entry
	//====================================================
	function focusCurrentPassword()
	{
		try
		{
			if (txtCurrentPassword != null)
				txtCurrentPassword.focus();
		}
		catch (exc)
		{
			HtmlPopup.Error(exc);
		}
	}

	//====================================================
	// Open the login popup
	//====================================================
	function openLogin()
	{
		try
		{
			if (THIS.LoginPopup != null)
				THIS.LoginPopup.Open();

			if (txtUserName == null)
				return;

			if (txtUserName.value == "")
				txtUserName.focus();
			else
			{
				txtUserName_Change(null);
				if (txtPassword != null)
					txtPassword.focus();
			}
		}
		catch (exc)
		{
			HtmlPopup.Error(exc);
		}
	}

	//====================================================
	// Save the password for the given user
	//====================================================
	function saveUser(strUserName, strPassword)
	{
		try
		{
			if (!strPassword || strPassword == null)
				strPassword = "";

			if (DOMStorage.Supported && DOMStorage.Supported() || DOMStorage.UseCookiesIfNotSupported)
			{
				if (DOMStorage.Set)
					DOMStorage.Set("user_" + strUserName, strPassword);

				//add the user to the | delimited array of usernames

				if (DOMStorage.GetData)
				{
					var intCount = 0;
					var strKeys = "";
					var strPrefix = "user_";

					for (var strKey in DOMStorage.GetData())
					{
						if (strKey.indexOf(strPrefix) == 0)
						{
							if (strKeys != "")
								strKeys += "|";

							strKeys += strKey.substring(strPrefix.length);
						}
					}

					DOMStorage.Set("previousUserNames", strKeys);
				}
			}
		}
		catch (exc)
		{
			HtmlPopup.Error(exc);
		}
	}

	//====================================================
	// Set the last user name
	//====================================================
	function setLastUser(strUserName)
	{
		try
		{
			if (DOMStorage.Supported() || DOMStorage.UseCookiesIfNotSupported)
				DOMStorage.Set("lastUser", strUserName);
		}
		catch (exc)
		{
			HtmlPopup.Error(exc);
		}
	}

	//====================================================
	// Get the last user name
	//====================================================
	function getLastUser()
	{
		try
		{
			if (DOMStorage.Supported() || DOMStorage.UseCookiesIfNotSupported)
			{
				var strUserName = DOMStorage.Get("lastUser");
				if (strUserName)
					return strUserName;

				return "";
			}
			else
				return "";
		}
		catch (exc)
		{
			HtmlPopup.Error(exc);
		}
	}

	//====================================================
	// Get the saved password for the given user
	//====================================================
	function getPassword(strUserName)
	{
		try
		{
			if (DOMStorage.Supported() || DOMStorage.UseCookiesIfNotSupported)
			{
				var strPassword = DOMStorage.Get("user_" + strUserName);
				if (strPassword == null)
					strPassword = "";

				return strPassword;
			}

			return "";
		}
		catch (exc)
		{
			HtmlPopup.Error(exc);
		}
	}

	//====================================================
	// Clear the password for the given user
	//====================================================
	function clearPassword(strUserName)
	{
		try
		{
			if (DOMStorage.Supported() || DOMStorage.UseCookiesIfNotSupported)
				DOMStorage.Set("user_" + strUserName, "");
		}
		catch (exc)
		{
			HtmlPopup.Error(exc);
		}
	}

	//====================================================
	// Clear the password for the given user
	//====================================================
	function clearUser(strUserName)
	{
		try
		{
			if (DOMStorage.Supported() || DOMStorage.UseCookiesIfNotSupported)
				DOMStorage.Set("user_" + strUserName, null);
		}
		catch (exc)
		{
			HtmlPopup.Error(exc);
		}
	}

	//====================================================
	// A username has been selected from the auto complete
	//====================================================
	function UserNameAutoComplete_ItemSelected(objAutoComplete, strUserName)
	{
		try
		{
			txtPassword.value = "";
			txtUserName.value = strUserName;
			txtUserName_Change(null);
			txtPassword.focus();

			//if (txtPassword.value != "")
			//	btnLogin_Click(null);
		}
		catch (exc)
		{
			HtmlPopup.Error(exc);
		}
	}

	//====================================================
	// The username has changed, update the password if one is saved
	//====================================================
	function txtUserName_Change(evt)
	{
		try
		{
			var strPassword = getPassword(txtUserName.value);
			
			if (txtPassword != null)
				txtPassword.value = strPassword;
		}
		catch (exc)
		{
			HtmlPopup.Error(exc);
		}
	}

	//====================================================
	// Forgot password link has been clicked
	//====================================================
	function lnkForgotPassword_Click(evt)
	{
		try
		{
			if (txtUserName.value == "")
			{
				HtmlPopup.Alert("Please enter your email address.", this.focusUserName);
				return;
			}

			if (txtUserName.value.indexOf("@") == -1)
			{
				if (!confirm("The email you have entered does not appear to be valid.\nIf this email is valid, press 'OK' to send a password reminder about this account."))
				{
					txtUserName.focus();
					return;
				}
			}

			var blnAdminAccount = txtUserName.value.toLowerCase().indexOf("admin@") != -1;

			if (blnAdminAccount)
			{
				HtmlPopup.Alert("The username you have entered appears to for a 'global account'.\nPlease contact Truckfile support to get your password reset.");
				return;
			}

			WaitWindow.Show("Sending request, please wait...");

			var params = new SOAPClientParameters();
			params.add("strUserName", txtUserName.value);
			SOAPClient.invoke("/webservices/newdesign.asmx", "ForgotPassword", params, true, PasswordReminderSent, null);
		}
		catch (exc)
		{
			HtmlPopup.Error(exc);
			WaitWindow.Hide();
		}
	}

	//====================================================
	// The password reminder has been sent
	//====================================================
	function PasswordReminderSent(strXML, docXML, sender)
	{
		try
		{
			if (typeof (strXML) == "object" && strXML != null)
				throw new Error(docXML);

			if (strXML == "true")
				HtmlPopup.Alert("An password reminder email has been successfully sent to '" + txtUserName.value + "'.\nIt may take a few minutes to arrive.", "Password Reminder");
			else
				HtmlPopup.Alert("An password reminder could not be sent to '" + txtUserName.value + "'.\nContact Truckfile support for more assistance.", "Password Reminder", "/images/error.png");
		}
		catch (exc)
		{
			HtmlPopup.Error(exc);
		}
		finally
		{
			WaitWindow.Hide();
		}
	}

	//====================================================
	// The cancel button has been clicked, close the popup
	//====================================================
	function btnCancel_Click(evt)
	{
		try
		{
			THIS.LoginPopup.Close();
		}
		catch (exc)
		{
			HtmlPopup.Error(exc);
		}
	}

	//====================================================
	// The login button has been clicked, validate and perform login
	//====================================================
	function btnLogin_Click(evt)
	{
		try
		{
			if (txtUserName.value == "")
			{
				HtmlPopup.Alert("Please enter your email address.", null, null, this.focusUserName);
				return;
			}

			if (txtUserName.value.indexOf("@") == -1)
			{
				txtUserName.value = '';
				HtmlPopup.Alert("Please enter your email address.", null, null, this.focusUserName);
				return;
			}

			if (txtPassword.value == "")
			{
				HtmlPopup.Alert("Please enter your password.", null, null, focusPassword);
				return;
			}

			if (BrowserDetect.browser == "Explorer" && BrowserDetect.version == 6)
			{
				var strMessage = "";

				strMessage += "You are using Internet Explorer, version 6\n";
				strMessage += "We strongly suggest you use a later version of Internet Explorer\n";
				strMessage += "or use one of the following browsers: -\n\n";
				strMessage += " - Mozilla Firefox\n";
				strMessage += " - Apple Safari\n";
				strMessage += " - Google Chrome\n";
				strMessage += "\n";
				strMessage += "You may still login, however some sections of the website may not work correctly.";

				if (!confirm(strMessage))
				{
					txtPassword.value = "";
					return;
				}
			}

			WaitWindow.Show("Logging in, please wait...");
			THIS.LoginPopup.Shadow.style.zIndex = "100";
			txtPassword.readOnly = true;

			var params = new SOAPClientParameters();
			params.add("strUserName", txtUserName.value);
			params.add("strPassword", txtPassword.value);
			SOAPClient.invoke("/webservices/newDesign.asmx", "ValidateLogin", params, true, validateLoginResponse, null);
		}
		catch (exc)
		{
			txtPassword.readOnly = false;
			HtmlPopup.Error(exc);
			WaitWindow.Hide();
		}
	}

	//====================================================
	// The login has been validated
	//====================================================
	function validateLoginResponse(strXML, docXML, sender)
	{
		try
		{
			if (typeof (strXML) == "object" && strXML != null)
				throw new Error(docXML);

			var strSessionId = strXML;

			if (strSessionId != null && strSessionId.indexOf("EXPIRED:") == 0)
			{
				strSessionId = strSessionId.substring(8, strSessionId.length);
				if (strSessionId != "")
					HtmlPopup.Alert(strSessionId);

				Navigate("/operator/paymentTelephone.aspx", false, null);
				return;
			}
			else if (strSessionId != null && strSessionId.indexOf("Exception:") > 0)
			{
				strXML = strXML.substring(strSessionId.indexOf("Exception:") + 10, strSessionId.indexOf("|"));
				
				WaitWindow.Hide();
				txtPassword.value = "";
				HtmlPopup.Alert(strXML, null, null, focusPassword);
				return;
			}
			else if (strSessionId != null && strSessionId.indexOf("NOACCESS") == 0)
			{
				WaitWindow.Hide();
				txtPassword.value = "";

				HtmlPopup.Alert("You are not permitted to login to the Truckfile VMS website.", null, null, focusPassword);
				return;
			}
			else if (strSessionId != null && strSessionId.indexOf("OK:") == 0)
			{
				strSessionId = strSessionId.substring(3, strSessionId.length);
				var aResponse = strSessionId.split('|');

				objUserDetail = new Object();
				objUserDetail["UserName"] = txtUserName.value;

				divLoginpopup.style.display = "none";

				if (chkRememberMe != null && chkRememberMe.checked == true)
				{
					if (chkRememberPassword != null && chkRememberPassword.checked)
						saveUser(txtUserName.value, txtPassword.value); //rememeber the username and the password
					else
						saveUser(txtUserName.value, ""); //rememeber the username but not the password
				}

				createCookie("ASP.NET_SessionId", aResponse[0]);

				setLastUser(txtUserName.value);
				THIS.LoginPopup.Dispose();

				var blnRedirect = true;
				if (chkRedirectOnLogin != null && chkRedirectOnLogin.checked == false)
					blnRedirect = false;

				//valid session
				try
				{
					// Check if the user's password is set to 'password'.
					if (txtPassword.value.toLowerCase() == 'password')
					{
						// Set the password change cookie.
						SetCookie('PasswordChangedRequired', true, 1);
						WaitWindow.Hide();
						THIS.ChangePassword();
						Functions.DisplayMessage('You must change your password from \'Password\' before you can use Truckfile.', 'Password Change Required', 'Information');
						return;
					}
					
					// Set the password change cookie to false.
					SetCookie('PasswordChangedRequired', false, 1);
					
					if (strLoginRedirect == "" || !blnRedirect)
					{
						Navigate("/common/loginRedirect.aspx?SessionId=" + strSessionId, false, "Entering system, please wait...");
					}
					else
					{
						Navigate(strLoginRedirect, false, "Entering system, please wait...");
					}
				}
				catch (exc) { }
			}
			else
			{
				WaitWindow.Hide();
				txtUserName.value = "";
				txtPassword.value = "";
				HtmlPopup.Alert("You have entered either an incorrect email address or password. Please try again.", null, null, this.focusUserName);
				return;
			}
		}
		catch (exc)
		{
			HtmlPopup.Error(exc);
			WaitWindow.Hide();
		}
		finally
		{
			txtPassword.readOnly = false;
			THIS.LoginPopup.Shadow.style.zIndex = "";
		}
	}

	//====================================================
	// A key has been pressed on the password entry
	//====================================================
	function txtPassword_KeyPress(evt)
	{
		try
		{
			evt = window.event ? window.event : evt;
			var intKeyCode = evt.keyCode ? evt.keyCode : evt.which;

			if (intKeyCode == KEYCODE_ENTER)
			{
				evt.returnValue = false;
				if (evt.preventDefault)
					evt.preventDefault();
				btnLogin_Click(evt);

				return false;
			}
		}
		catch (exc)
		{
			HtmlPopup.Error(exc);
		}
	}

	//====================================================
	// The remember me option has been changed
	//====================================================
	function chkRememberMe_Click(evt)
	{
		try
		{
			if (chkRememberMe.checked == false)
				clearUser(txtUserName.value); //will also clear password

			if (chkRememberPassword != null)
			{
				chkRememberPassword.disabled = !chkRememberMe.checked;
				chkRememberPassword.checked = chkRememberMe.checked;
			}
		}
		catch (exc)
		{
			HtmlPopup.Error(exc);
		}
	}

	//====================================================
	// The remember password option has been changed
	//====================================================
	function chkRememberPassword_Click(evt)
	{
		try
		{
			if (chkRememberPassword != null && chkRememberPassword.checked == false)
				clearPassword(txtUserName.value);
		}
		catch (exc)
		{
			HtmlPopup.Error(exc);
		}
	}

	//====================================================
	// The login option has been clicked
	//====================================================
	function loginMessage_Click(evt)
	{
		try
		{
			WaitWindow.Show('Please wait...');
			
			// Check for a service message.
			var soapClient = new SoapClient();
			soapClient.SendRequest('/WebServices/CMS.asmx', 'http://www.truckfile.co.uk/', 'ServiceMessage_Select', THIS.ServiceMessage_Select_Completed);
		}
		catch (exc)
		{
			HtmlPopup.Error(exc);
			WaitWindow.Hide();
		}
	}
	
	//====================================================
	// Service message soap completed handler.
	//====================================================
	this.ServiceMessage_Select_Completed = function ServiceMessage_Select_Completed(Response)
	{
		try
		{
			WaitWindow.Hide();
			
			var aResponse = Response.split('|');
			
			// Check if an error occured.
			if (aResponse[0] == 'ERROR')
			{
				HtmlPopup.Error(aResponse[1]);
				return;
			}
			
			// Check if there is a service message to display.
			if (aResponse[1] == "")
			{
				// Check if a password change is required.
				if ((GetCookie('PasswordChangedRequired') == 'true') && (getUserDetail() != null))
				{
					THIS.ChangePassword();
					Functions.DisplayMessage('You must change your password from \'Password\' before you can use Truckfile.', 'Password Change Required', 'Information');
				}
				else
				{
					if (getUserDetail() == null)
					{
						openLogin();
					}
					else
					{
						Navigate("/common/loginRedirect.aspx", false, null);
					}
				}
			}
			else
			{
				Functions.DisplayMessage(aResponse[1], 'Service Message', 'Information', THIS.ServiceMessage_OKHandler);
			}
		}
		catch (exc)
		{
			HtmlPopup.Error(exc);
			WaitWindow.Hide();
		}
		return;
	}

	//====================================================
	// Logout
	//====================================================
	this.ServiceMessage_OKHandler = function ServiceMessage_OKHandler()
	{
		try
		{
			// Check if a password change is required.
			if ((GetCookie('PasswordChangedRequired') == 'true') && (getUserDetail() != null))
			{
				THIS.ChangePassword();
				Functions.DisplayMessage('You must change your password from \'Password\' before you can use Truckfile.', 'Password Change Required', 'Information');
			}
			else
			{
				if (getUserDetail() == null)
				{
					openLogin();
				}
				else
				{
					Navigate("/common/loginRedirect.aspx", false, null);
				}
			}
		}
		catch (exc)
		{
			HtmlPopup.Error(exc);
			WaitWindow.Hide();
		}
		return true;
	}

	//====================================================
	// Logout
	//====================================================
	this.Logout = function Logout()
	{
		try
		{
			if(!LeavingPage(this,1, THIS.Logout))
				return;
				
			if (getUserDetail() == null)
				return;

			var strMessage = "";

			var objButtons = new Object();
			objButtons["Logout"] = fncLogout;
			
			// Check if the current user is impersonated.
			if (getUserDetail()["Impersonated"] == true)
			{
				objButtons["Switch Back"] = DoUnimpersonate;
				strMessage = "Do you want to logout, or switch back to your original account?";
			}
			else
			{
				strMessage = "Are you sure you want to logout?";
			}

			objButtons["Cancel"] = "CLOSE";
			HtmlPopup.Confirm(strMessage, objButtons);
		}
		catch (exc)
		{
			HtmlPopup.Error(exc);
			WaitWindow.Hide();
		}
	}

	//====================================================
	// Perform the logout
	//====================================================
	function fncLogout(evt, objPopup, btnButton)
	{
		try
		{
			WaitWindow.Show("Logging out, please wait...");
			objPopup.Close();
			window.location = "/home.aspx?logout";
		}
		catch (exc)
		{
			HtmlPopup.Error(exc);
			WaitWindow.Hide();
		}
	}

	//====================================================
	// ChangePassword
	//====================================================
	this.ChangePassword = function ChangePassword()
	{
		try
		{
			txtCurrentPassword.value = "";
			txtNewPassword.value = "";
			txtConfirmPassword.value = "";

			this.ChangePasswordPopup.Open();
			txtCurrentPassword.focus();
		}
		catch (exc)
		{
			HtmlPopup.Error(exc);
		}
	}

	//====================================================
	// Change the password for this user
	//====================================================
	function btnChangePassword_Click(evt)
	{
		try
		{
			// Check if the user has entered their current password.
			if (txtCurrentPassword.value == "")
			{
				HtmlPopup.Alert("You must enter your current password.", this.focusCurrentPassword);
				return;
			}

			// Check if the user has entered a new password.
			if (txtNewPassword.value == "")
			{
				HtmlPopup.Alert("You must enter your new password. Passwords cannot be blank.", this.focusNewPassword);
				return;
			}
			
			// Check if the user has the Trucfile administration permission.
			var blnAdministrator = false;
			
			if (objUserDetail['Permissions'] != undefined)
			{
				var aPermissions = objUserDetail['Permissions'].split(',');
				for(var intCounter = 0; intCounter < aPermissions.length; intCounter++)
				{
					if (Number(aPermissions[intCounter]) == 11)
					{
						blnAdministrator = true;
						break;
					}
				}
			}

			if (!blnAdministrator)
			{
				var passed = validatePassword(txtNewPassword.value, {
																		length:   [6, Infinity],
																		lower:    1,
																		upper:    1,
																		numeric:  1,
																		special:  0,
																		badWords: ["password", "pass"],
																		badSequenceLength: 4
																	});

				// Check the value of the new password.
				if (!passed)
				{
					var strPasswordComplexity = ' Your password must match the following rules: -\n\n';
					strPasswordComplexity += '1. A minimum of 6 characters.\n'
					strPasswordComplexity += '2. At least 1 lowercase letter.\n'
					strPasswordComplexity += '3. At least 1 uppercase letter.\n'
					strPasswordComplexity += '4. At least 1 number.\n'
					//strPasswordComplexity += '5. At least 1 special character, e.g a dash \'-\'.\n'
					strPasswordComplexity += '5. Cannot contain a sequence of letters or numbers.\n'
					
					HtmlPopup.Alert('You cannot have a password of \'' + txtNewPassword.value + '\'.' + strPasswordComplexity, this.focusNewPassword);
					txtNewPassword.value = "";
					txtConfirmPassword.value = "";
					txtCurrentPassword.value = "";
					return;
				}
				
				// Check if the new password contains the user's name.
				var strUserName = objUserDetail['UserName'].toLowerCase().replace(/\W/gi, '');
				var strNewPassword = txtNewPassword.value.toLowerCase().replace(/\W/gi, '');
				
				if (strUserName.indexOf(strNewPassword) != -1)
				{
					HtmlPopup.Alert('Your password cannot contain match any part of your name.', this.focusNewPassword);
					txtNewPassword.value = "";
					txtConfirmPassword.value = "";
					txtCurrentPassword.value = "";
					return;
				}
				
				// Check the length of the new password.
				if (txtNewPassword.value.length < 4)
				{
					txtNewPassword.value = "";
					txtConfirmPassword.value = "";
					txtCurrentPassword.value = "";
					HtmlPopup.Alert('Your password must be a minimum of 4 characters.', this.focusNewPassword);
					return;
				}
			}

			// Check if the new and confirm passwords match.
			if (txtNewPassword.value != txtConfirmPassword.value)
			{
				txtNewPassword.value = "";
				txtConfirmPassword.value = "";
				txtCurrentPassword.value = "";
				HtmlPopup.Alert("Your new passwords do not match, please re-enter them.");
				return;
			}

			// Save the new password.
			var params = new SOAPClientParameters();
			params.add("strCurrentPassword", txtCurrentPassword.value);
			params.add("strNewPassword", txtNewPassword.value);
			SOAPClient.invoke("/webservices/newDesign.asmx", "ChangePassword", params, true, ChangePassword_Result, null);
		}
		catch (exc)
		{
			HtmlPopup.Error(exc);
		}
	}

	//====================================================
	// The password has been changed
	//====================================================
	function ChangePassword_Result(strXML, docXML, sender)
	{
		try
		{
			if (typeof (strXML) == "object" && strXML != null)
				throw new Error(docXML);

			if (strXML == "SUCCESS")
			{
				btnChangePassword_Cancel_Click(null);
				Functions.DisplayMessage('Your password has been successfully changed', 'Password Changed', 'Information', PasswordChanged);
			}
			else
			{
				if (strXML.toString().indexOf("Error") == -1)
					HtmlPopup.Alert("Your password could not be changed. " + strXML);
				else
					HtmlPopup.Alert("Your password could not be changed, please contact the help desk.");
			}
		}
		catch (exc)
		{
			HtmlPopup.Error(exc);
		}
	}

	//====================================================
	// Cancel the change password popup
	//====================================================
	function btnChangePassword_Cancel_Click(evt)
	{
		try
		{
			THIS.ChangePasswordPopup.Close();
		}
		catch (exc)
		{
			HtmlPopup.Error(exc);
		}
	}

	if (txtUserName != null)
		txtUserName.value = getLastUser();

	if (strLoginRedirect != "")
		openLogin();
}

//====================================================
// Password changed.
//====================================================
function PasswordChanged()
{
	var blnRedirect = (GetCookie('PasswordChangedRequired') == 'true');
	
	// Set the password change cookie to false.
	SetCookie('PasswordChangedRequired', false, 1);
	
	// Check if a redirect is required.
	if (blnRedirect)
		Navigate("/common/loginRedirect.aspx", false, null);
	return true;
}

var m_objNewLogin = null;
NewLogin.Create = function Create()
{
	try
	{
		if (m_objNewLogin == null)
			m_objNewLogin = new NewLogin();

		return m_objNewLogin;
	}
	catch (exc)
	{
		HtmlPopup.Error(exc);
	}
}

addInitMethod(NewLogin.Create);

NewLogin.Logout = function Logout()
{
	try
	{
		NewLogin.Create().Logout();
	}
	catch (exc)
	{
		HtmlPopup.Error(exc);
	}
}

NewLogin.ChangePassword = function ChangePassword()
{
	try
	{
		NewLogin.Create().ChangePassword();
	}
	catch (exc)
	{
		HtmlPopup.Error(exc);
	}
}

function validatePassword (pw, options) {
	// default options (allows any password)
	var o = {
		lower:    0,
		upper:    0,
		alpha:    0, /* lower + upper */
		numeric:  0,
		special:  0,
		length:   [0, Infinity],
		custom:   [ /* regexes and/or functions */ ],
		badWords: [],
		badSequenceLength: 0,
		noQwertySequences: false,
		noSequential:      false
	};

	for (var property in options)
		o[property] = options[property];

	var	re = {
			lower:   /[a-z]/g,
			upper:   /[A-Z]/g,
			alpha:   /[A-Z]/gi,
			numeric: /[0-9]/g,
			special: /[\W_]/g
		},
		rule, i;

	// enforce min/max length
	if (pw.length < o.length[0] || pw.length > o.length[1])
		return false;

	// enforce lower/upper/alpha/numeric/special rules
	for (rule in re) {
		if ((pw.match(re[rule]) || []).length < o[rule])
			return false;
	}

	// enforce word ban (case insensitive)
	for (i = 0; i < o.badWords.length; i++) {
		if (pw.toLowerCase().indexOf(o.badWords[i].toLowerCase()) > -1)
			return false;
	}

	// enforce the no sequential, identical characters rule
	if (o.noSequential && /([\S\s])\1/.test(pw))
		return false;

	// enforce alphanumeric/qwerty sequence ban rules
	if (o.badSequenceLength) {
		var	lower   = "abcdefghijklmnopqrstuvwxyz",
			upper   = lower.toUpperCase(),
			numbers = "0123456789",
			qwerty  = "qwertyuiopasdfghjklzxcvbnm",
			start   = o.badSequenceLength - 1,
			seq     = "_" + pw.slice(0, start);
		for (i = start; i < pw.length; i++) {
			seq = seq.slice(1) + pw.charAt(i);
			if (
				lower.indexOf(seq)   > -1 ||
				upper.indexOf(seq)   > -1 ||
				numbers.indexOf(seq) > -1 ||
				(o.noQwertySequences && qwerty.indexOf(seq) > -1)
			) {
				return false;
			}
		}
	}

	// enforce custom regex/function rules
	for (i = 0; i < o.custom.length; i++) {
		rule = o.custom[i];
		if (rule instanceof RegExp) {
			if (!rule.test(pw))
				return false;
		} else if (rule instanceof Function) {
			if (!rule(pw))
				return false;
		}
	}

	// great success!
	return true;
}
