Public Class Login1
    Inherits System.Web.UI.Page

    Private Sub Me_Init(sender As Object, e As EventArgs) Handles Me.Init
        
        ' Clients and drivers are sharing computers, so log them all out here.
        SessionVars.ClientId(Session) = 0
        SessionVars.DriverId(Session) = 0

        ' Save the redirect URL for after login.
        Dim r = Logic.Conversion.ToString(Request.Params("r"))
        If r.Length Then
            SessionVars.PostLoginUrl(Session) = r
        End If

    End Sub

    Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
        SessionVars.PostLoginUrl(Session) = Nothing
        Response.Redirect("../")
    End Sub

	Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click, btnDefault.Click
		Dim LoginSuccessful As Boolean = True
		Try
			Dim account = New Logic.ClientAccount(txtUsername.Text, txtPassword.Text)
			SessionVars.ClientId(Session) = account.id
		Catch ex As ArgumentOutOfRangeException
			phInvalid.Visible = True
			txtPassword.Focus()
			LoginSuccessful = False
		Catch ex As Exception
			Dim errorId = Logic.Error.Log(ex)
			Response.Redirect("/Error.aspx?id=" & errorId)
		Finally
			If LoginSuccessful Then
				Response.Redirect(_GetRedirectTarget())
			End If
		End Try
	End Sub

	' Returns whence we should redirect the user.
	Private Function _GetRedirectTarget() As String

        ' Magic...  true if other is same origin as this website
        Dim isSameOrigin = Function(other As String) As Boolean
                               Return 0 = Uri.Compare(Request.Url, New Uri(other),
                                   UriComponents.SchemeAndServer, UriFormat.SafeUnescaped, StringComparison.Ordinal)
                           End Function

        ' Return where they were, if valid
        Dim req = SessionVars.PostLoginUrl(Session)
        SessionVars.PostLoginUrl(Session) = ""
        If req.Length AndAlso isSameOrigin(req) Then
            Return req
        End If

        ' On fail, just return the default
        Return "Default.aspx"

    End Function

End Class