#!/usr/bin/perl -Tw -I. -I/usr/local/positive/Perl 

use strict;
use Pos::Webtop::Web::ModuleLoader;
use Pos::Webtop::Web::OEMLoader;
use CGI qw/:standard/;
use CGI::Cookie ();
use Digest::MD5();
use Pos::WebService::Modules::MyCalls;
use Pos::WebService::Modules::ParseServerXmlResponse;
use LWP::UserAgent;
use HTTP::Request;
use Config::General;
use URI::Escape;
use HTML::Entities;
use MIME::Base64;
use Pos::MessageQueue::Put::MQI;

my $mqi = MQI->new();
my $mqiHostName  = $mqi->getHostName();
my $mqiQueueName = $mqi->getQueueNameByType( type=> "queueRunSql" );

my $conf = new Config::General("/usr/local/positive/conf/WebService.conf");
my %config = $conf->getall;

my $tb = Pos::Webtop::Toolbox->new();
my $client = $tb->getClient();
my $cgi = $tb->getCgi();
my $oem = $tb->getOem;
my $isMobile = $client->isMobileWebtop(); 
my $myCallsObj = Pos::WebService::Modules::MyCalls->new();
my $xmlResponseParserObj = Pos::WebService::Modules::ParseServerXmlResponse->new();
my $effectiveOemId = Pos::Webtop::Web::OEMLoader::getSkinOemId( oemId=> $tb->getOemId() );

my $a = $cgi->param('a');
my $z = $cgi->param('z');
my $un = $cgi->param('un');
my $pw = $cgi->param('pw');
my $err;
$err = undef unless $cgi->param('err') and $err = $cgi->param('err');
my $showLogin = 1;

my $mode = $cgi->param('mode') || "";
my $challenge = $cgi->param('challenge');

# This is used to close the session window if it's open when someone logs out.
my $closeWindowJs = "";
my @anxParms;
#my $startUrl;
# 
# if logout then kill session
#
if ( defined $cgi->param('logout') )
{
	$client->checkSession(ignoreAuxAuth => 1);
	# if here, session was good, let's kill the session.

	my $si = $client->getSessionId();

	my $db = $tb->getWebtopDbWriter();
	$db->do( sql=> "delete from client_sessions where client_session_id = $si" );

	(@anxParms) = $db->query( sql=> "select a_param,z_param from anx_portal_sessions where client_session_id = $si" );

	foreach my $anxparms(@anxParms)
	{
		my ($anxA,$anxZ) = @{$anxparms};
		
		my $response = $myCallsObj->checkUserSession( a => $anxA, z => $anxZ ) ;
		
		if ($response)
		{
			$xmlResponseParserObj->parseResponse( response => $response ) or warn "COULD NOT PARSE XML FROM CHECKUSERSESSION() on logout\n\n";	
		}
		else
		{
			warn "COULT NOT PARSE XML FROM CHECKUSERSESSION() on logout\n\n";
		}
		
		if (lc($xmlResponseParserObj->getMessageInfoText()) eq "ok")
		{
			$db->do( sql=> "delete from anx_portal_sessions where client_session_id = $si" );
		}
	}
	
	$db->commit();

	$closeWindowJs = "
		<script type='text/javascript'>
		
			if ((window.opener != null) &&
				 (window.opener.closed != true) && 
				 (window.opener.name == 'OcxWindow'))
				window.opener.close();

		</script>
		";
}

if ( (defined($a) && defined($z)) || (defined($un) && defined($pw)) ) 
{
	# we have a login request..
	my $db = $tb->getWebtopDbReader();
	my $expired;
	my $isTrialExpired;
	my $userId;


	if (defined($un) && length($un))
	{
		my $pw2 = $pw;
		$pw2 = HTML::Entities::encode( $pw2 );
		$pw2 = encode_base64( $pw2 );
		$pw2 = uri_escape( $pw2 );

		my $r = "
		<root>
			<type>Request</type>
			<remoteRequestor>
				<ipAddress></ipAddress>
				<datetime></datetime>
				<key></key>
				<sessionId></sessionId>
			</remoteRequestor>
			<command>
				<operation>UserOperator</operation>
				<method>checkUser</method>
			</command>
			<parameters>
				<parameterCount>2</parameterCount>
				<parameter>
					<name>uslId</name>
					<value></value>
				</parameter>
				<parameter>
					<name>uUserName</name>
					<value><![CDATA[$un]]></value>
				</parameter>
				<parameter>
					<name>uPwd</name>
					<value><![CDATA[$pw2]]></value>
				</parameter>
			</parameters>
		</root>
		";

		my $request = HTTP::Request->new(GET => $config{webserviceurl} . "?r=$r" );
		
		my $ua = LWP::UserAgent->new;
		my $response = $ua->request( $request );
		
		if ($response)
		{
			$xmlResponseParserObj->parseResponse( response => $response->content ) or warn "COULD NOT PARSE XML FROM CHECKUSER()\n\n";	
		}
		else
		{
			warn "COULT NOT PARSE XML FROM CHECKUSER()\n\n";
		}
		
		if (lc($xmlResponseParserObj->getMessageInfoText()) eq "ok")
		{
			($userId) = $db->query( sql => "
				select 
					user_id
				from 
					users
				where
					upper(user_name) = '" . uc( $db->escape( dirty => $un ) ) . "'
				");

				warn "USERID $userId\n\n";
		}

		$isTrialExpired = $xmlResponseParserObj->getMessageInfoTrialExpired();
		$expired = $xmlResponseParserObj->getMessageInfoExpired();
		$challenge = $xmlResponseParserObj->getMessageInfoChallenge();

	}
	else
	{
		my $response = $myCallsObj->checkUserSession( a => $a, z => $z ) ;
		
		if ($response)
		{
			$xmlResponseParserObj->parseResponse( response => $response ) or warn "COULD NOT PARSE XML FROM CHECKUSERSESSION()\n\n";	
		}
		else
		{
			warn "COULT NOT PARSE XML FROM CHECKUSERSESSION()\n\n";
		}
		
		if (lc($xmlResponseParserObj->getMessageInfoText()) eq "ok")
		{
			$un = $xmlResponseParserObj->getParameter( parameter => "uUserName" );
			
			($userId) = $db->query( sql => "
				select 
					user_id
				from 
					users
				where
					upper(user_name) = '" . uc($db->escape( dirty=> $un )) . "'
				");
		
		}
	}
	
	#
	# create a session for the user if the user
	# and pass are correct
	#
	if($userId)
	{
		$client->createSession( userId => $userId, userName => $un, passwd => $pw, uslId => $xmlResponseParserObj->getParameter( parameter => "uslId" ), a=>$a, z=>$z );

		if ($challenge || $isTrialExpired)
		{
			$userId = "";
		}
	}

	#
	#	if there is a userId then it seems to be a valid user
	#	so lets go
	#
	if(defined($userId) and length($userId) )
	{
		$client->setRestrictionSetId(tb=>$tb);	
		# checks to see if this is a support account...if it is
		# we see if it has been a hour since last_password_reset...
		# if it has you get owed
		my $isSupportAccount = $client->isSupportAccount( db=> $db, userId=> $userId );
		my $isSupportAccountActive = 1;

		if ( $isSupportAccount )
		{
			$isSupportAccountActive = $client->isSupportAccountActive( db=> $db, userId=> $userId );	
		}
		
		# does user have access to webtop
		my $userHasAccess = $client->isWebtopAccessEnabled( db=>$db, userId=>$userId );
	
		# has the user registered
		my $hasRegistered = $client->isUserRegistered( db=>$db, userId=>$userId );

		# does the user have vpn access and can the user download the vpn client
		my ($userHasVPNAccess,$canDownloadVpn) = @{$client->isVpnAccessEnabled(db=> $db, userId=>$userId)};
		
		# get the user type
		my $userType = $client->getUserType(db=>$db, userId=>$userId);	

		my $requiredToChangePassword;

		#
		# if the user has already registered check to 
		# see if they are required to change their password
		#
		if ($hasRegistered)
		{
			$requiredToChangePassword = $client->requiredToChangePassword();
		}

		#
		# check to see if the user is required to load the activex
		#
		my $ocxRequired = $client->isOcxRequired( tb=> $tb );	
		
		#
		# can the user change thier password?
		#
		my ($canChangePassword) = $client->canUserChangePassword(db=>$db, userId=>$userId);
	
		# 
		# if useing lame browser they can only get email from owa 
		# which will also give them intranet acces
		#
		my $isLame = $client->isLameHandheldThatSux(dow => 0);
		
		my $usingOwa = 0;
		my $owaServer = 0;

		if ($isLame)
		{
			$usingOwa = $client->isLameUsingOwa(db=>$db, userId=>$userId);
		}

		if ($usingOwa)
		{
			$owaServer = $client->getOwaServer(db=>$db, userId=>$userId);
		}
			
		# if the user is using a mobile device and they are
		# required to use the activex control, own them
		#
		if ($isMobile and $ocxRequired)
		{	
			$err = "ERROR: The ActiveX control is not supported on Mobile devices and has been required by your administrator.";		
		}
		elsif (($isLame && !$usingOwa) || ($isLame && $ocxRequired) || ($isLame && !$owaServer))
		{
			$err = "ERROR: You are not enabled to view your email through this device.";
		}
		elsif (($expired || $requiredToChangePassword) && !$canChangePassword )
		{
			$err = "ERROR: Your password is expired but your administrator has not given you access to change it.";		
		}
		#
		# $isSupportAccountActive is 1 by default...so if userId is all
		# good in the hood then we start a bunch of stuff
		# rename var
		elsif ( defined($userId) and $isSupportAccountActive )
		{
			# first thing we have to do is consult external policy sources
			my ($sourceId) = $db->query( sql=> "select external_policy_source_id from user_external_policy_sources where user_id = $userId" );
			if ( defined $sourceId )
			{
				$ENV{'PATH'} = "/bin:/usr/bin:/usr/local/bin";
				system("/usr/bin/perl -I/usr/local/positive/WebInterface -I/usr/local/positive/Policy -I/usr/local/positive/Perl -w /usr/local/positive/Policy/externalPolicySourcesOnSignon.pl $userId >&2");
			}
			
			my $sh = $client->getSessionHash();
			my $si = $client->getSessionId();
	
			my $cookieWsi = new CGI::Cookie(-name=>'wsi', -value=>$si);
			my $cookieWsh = new CGI::Cookie(-name=>'wsh', -value=>$sh);

			print "Set-Cookie: $cookieWsi\n";
			print "Set-Cookie: $cookieWsh\n";

			# Aux Auth: Populate the client_session_aux_auths table 
			#
			$db->do(sql=> "delete from client_session_aux_auths 
				where client_session_id = $si");
			
			$db->do(sql=> "
				insert into client_session_aux_auths (
					client_session_id,
					aux_auth_id,
					passed,
					expired,
					tries_left,
					tag
				) 
				select 
					$si,
					aux_auth_id,
					false,
					false,
					case when max_tries is null then 3 else max_tries end,
					tag
				from user_aux_auths
				where user_id = '" . $db->escape(dirty=> $userId) . "'");
			
			# 
			# if you are using a lame mobile device we probably don't want
			# to send you through the registration page and stuff since that
			# may piss you off cause of your lame mobile
			#
			if ($isLame)
			{	
				my $temp = "main.pl?module=Intranet&" . $client->getSessionParams() . "&action=rwPopup&url=" . HTML::Entities::encode($owaServer) . "";
			
				print $tb->getRefreshFormHtml(refreshUrl=> $temp);

				exit;
			}
			# valid login.. session was setup
			#
			# if register is defined, or the user has never registered and doesn't
			# have webtop access we allow the user to go to reg.pl to register
			# reg.pl
			#
			# params:
			# 			auth=register,expired
			# 			mode=vpn,netcon
			# 			username=guess
			# 			password=guess
			# 			nostep=0,1
			# 			oemId = guess
			#
			if (($cgi->param('register') || !$hasRegistered ) && !$isSupportAccount && $userType ne 'NAT AGENT')
			{
				 my ($mustRegister) = $db->query(sql => "
                			select
                        			must_register
                			from
                        			user_webtop_access
                			where
                        			user_id = '$userId'

                			");	

				if(! $mustRegister )
				{
					my $sql =  "update user_enrollment_metrics set registration_date=" . $db->getCurrentDateString() . " where user_id = '$userId';" ;
					$mqi->insertMessageQueue( hostname=>$mqiHostName, queuename=>$mqiQueueName, value=>$sql );

					$sql = "update users set register_complete = 1 where user_id = $userId ";
					$mqi->insertMessageQueue( hostname=>$mqiHostName, queuename=>$mqiQueueName, value=>$sql );

					my $startUrl = "main.pl?r=1&displayFrameset=1&pVwsh=$sh&pVwsi=$si";
					print $tb->getRefreshFormHtml(refreshUrl=> $startUrl);
					
					exit;

					#$hasRegistered = 1;
				}
			}

			if (($cgi->param('register') || !$hasRegistered ) && !$isSupportAccount && $userType ne 'NAT AGENT')
			{	
				my $temp = "reg.pl?pVwsh=$sh&pVwsi=$si&nostep=1" . ($cgi->param('register') ? "&auth=register" : "") . "&mode=" . HTML::Entities::encode($mode) . "&username=" . HTML::Entities::encode($un) . "&oemId=" . HTML::Entities::encode($cgi->param('oemId')) . "";
			
				print $tb->getRefreshFormHtml(refreshUrl=> $temp);

				exit;
			}
			#
			# if the user is required to change their pw on login
			# or their password has expired (support accounts exempted)
			# they will be redirected to reg.pl expired passwordness
			# reg.pl
			#
			# params:
			# 			auth=register,expired
			# 			mode=vpn,netcon
			# 			username=guess
			# 			password=guess
			# 			nostep=0,1
			# 			oemId = guess
			#
			elsif (($expired || $requiredToChangePassword) && !$isSupportAccount && $userType ne 'NAT AGENT')
			{
				my $temp = "reg.pl?pVwsh=$sh&pVwsi=$si&nostep=1&auth=expired&mode=" . HTML::Entities::encode($mode) . "&username=" . HTML::Entities::encode($un) . "&oemId=" . HTML::Entities::encode($cgi->param('oemId')) . "";

				print $tb->getRefreshFormHtml(refreshUrl=> $temp);

				exit;
			}	
		

			# 
			# are you a netcon user ?
			#
			my $netConUser = undef;
			
			if ( $mode eq "netcon" )
			{
				if ($userType eq "NAT AGENT")
				{
					$netConUser = 1;
				}
			}

			#
			#	get a list of acceptable browsers
			#	for the user
			#
			my @br = $db->query( sql=> "
				select web_browser_match_regex, web_browser_match_name from w_user_required_web_browsers r, web_browser_matches b         
				where b.web_browser_match_id = r.web_browser_match_id and user_id = $userId
			");

			my $badBrowser = ( @br ? 1 : 0 );
			my $userAgent = $ENV{'HTTP_USER_AGENT'};
			$userAgent = "" unless defined $userAgent;
			my @acceptableBrowsers = (); # this will be filled if nothing matches
			
			foreach ( @br )
			{
				my ($regex,$name) = @{ $_ };
				
				if ( $userAgent =~ /$regex/i )
				{
					$badBrowser = 0;
					last;
				}

				push @acceptableBrowsers, $name;
			}
		
			#	
			#	if you are not try'n to download the vpn installer
			#	then get pissed if they are not using a acceptable browser
			#
			if ( $mode ne "vpn" and $mode ne "netcon" and $badBrowser )
			{
				$err = "Your account requires you to use one of the following web browsers: " . 
					HTML::Entities::encode( join(", ",@acceptableBrowsers) ) . ".";
			}
			#
			#	if the user is not downloading the vpn or netcon installer
			#	and they don't have access to webtop then get pissed and don't let them in
			#
			elsif ($mode ne "vpn" and $mode ne "netcon"  and (not defined($userHasAccess) or ($userHasAccess == 0)))
			{

				$err = "Your account is currently not enabled for " . $oem->getSetting(setting=>'webtopProductName') . " access. Please contact " . $oem->getSetting(setting => 'rebrandName') . " technical support for more information.";

			}
			#
			#	if the user is trying to go to the vpn download page but
			#	user does not have access to the vpn then own them
			#
			elsif ($mode eq "vpn" and (not defined $userHasVPNAccess or !$userHasVPNAccess))
			{
				$err = "Your account is currently not enabled for " . $oem->getSetting(setting=>'vpnProductName') . " access. Please contact " . $oem->getSetting(setting => 'rebrandName') . " technical support for more information.";
				
			}
			#
			#	if the user is trying to go to the vpn download page but
			#	user does not have access to the vpn then own them
			#
			elsif ($mode eq "vpn" and (not defined $canDownloadVpn or !$canDownloadVpn))
			{
				$err = "Your account currently prevents downloading the " . $oem->getSetting(setting=>'vpnProductName') . ". Please contact " . $oem->getSetting(setting => 'rebrandName') . " technical support for more information.";
			
			}
			#
			#	if the user is trying to download the netcon and they are
			#	not a netcon user then own them
			#
			elsif ( $mode eq "netcon" and (not defined($netConUser)) )
			{
				$err = "Your account is currently not enabled for " . $oem->getSetting(setting=>'networkConnectorName') . " access. Please contact " . $oem->getSetting(setting => 'rebrandName') . " technical support for more information.";
				
			}
			else 
			{
				$showLogin = 0;

				# it's frustrating but we have to manually seed the persisted values to do a refresh
				# since we can't rely on js in the 'low level' login.pl

				my $jump = $client->getPersistedValue( name=>'jump' );

				if ( defined $jump )
				{
					$jump = "&" . $jump;
				}
				else
				{
					$jump = "";
				}

				my $startUrl;
				my $isWebTopLogin = 0;

				#
				#	send to the download page 
				#	vpndownload.pl
				#
				#	params:
				#			mode=vpn,netcon
				#			is95=0,1
				#			is98=0,1
				#			isME=0,1
				#
				if( defined $mode and ($mode eq 'vpn' or $mode eq 'netcon') )
				{
					$startUrl = "vpndownload.pl?pVwsh=$sh&pVwsi=$si&mode=$mode";
				}
				else
				{
					#
					#	send to main with the session info
					#	main.pl
					#
					#	params:
					#			action= ?
					#			module=FileShare,Intranet, etc...
					#			confPassed= ?
					#			displayFrameset=1,0
					#			bottomFrame=1,0
					#			bottomFrameStatus= ?
					#			bottomFrameSupport = ?
					#
					$startUrl = "main.pl?displayFrameset=1&pVwsh=$sh&pVwsi=$si" . $jump;

					#
					#	get your metrics on
					#	
					my ($d) = $db->query( sql=> "select webtop_login_date from user_enrollment_metrics where user_id = " . $client->getUserId() );

					if ( not defined $d )
					{
                                                #
                                                # VPN-4153  
                                                # 2012-04-19 - LM:
                                                #
						my $dbw = $tb->getWebtopDbWriter();
						#$dbw->do( sql=> " update user_enrollment_metrics set webtop_login_date=" . $dbw->getCurrentTimeStampString() . " where user_id = " . $client->getUserId() );
						#$dbw->commit();
						my $sql =  "update user_enrollment_metrics set webtop_login_date=" . $dbw->getCurrentTimeStampString() . " where user_id = " . $client->getUserId();
                                                $mqi->insertMessageQueue( hostname=>$mqiHostName, queuename=>$mqiQueueName, value=>$sql );
					}

					$isWebTopLogin = 1;
				}

				# We now check to see if the user requires a confidence online scan, but only if it's an actual webtop login, not a VPN download.
				if ($isWebTopLogin)
				{
				# Disabling confidence online support 1/3/2006 -mm
				#	my ($scanRequired) = $db->query(sql => "
				#		select
				#			user_id
				#		from
				#			user_conf_online_settings
				#		where
				#			scan_required = 1
				#			AND conf_online_server_id is not null
				#			AND user_id = '" . $client->getUserId() . "'
				#		");
				#	
				#	if (defined($scanRequired) and $scanRequired == $client->getUserId()) {
				#
				#		# If the user does indeed require a scan, we must redirect them to confidence.pl
				#		$startUrl = "confidence.pl?pVwsh=$sh&pVwsi=$si";	
				#
				#	} else {
				#
				#		# Otherwise we flag their sessions as having passed the scan, even though we didn't do it.
				#		$db->do(sql => "
				#			update
				#				client_sessions
				#			set
				#				confidence_scan_passed = 1
				#			where
				#				web_session_id = '" . $db->escape(dirty => $si) . "'
				#			");
				#
				#		$db->commit;
				#
				#	}
				}
			
				# just load the damn page
				print $tb->getRefreshFormHtml(refreshUrl=> $startUrl);
				exit;
				
			}
		}
	}
	#
	# find out if the trial period for this customer has ended
	#
	elsif ($isTrialExpired)
	{
		$err = "Your sign on failed since your company's trial 
		       of the PositivePRO VPN service has expired.  Please contact your company
		       administrator.";
	}
	#
	# if we got a state attr back from createSession, then we're dealing
	# with an access-challenge from a radius server
	#
	elsif ($challenge)
	{
		# 
		# check the db to see if we got a message back with our challenge and
		# use that as the prompt
		#
		($err) = $db->query( sql=> "
			select 
				message 
			from 
				radius_challenges 
			where 
				user_name = '" . $db->escape(dirty => $un) . "'");

		if (!defined($err) || !length($err))
		{
			$err = "You must enter a new PIN before continuing.";
		}
	}
	else
	{
		# invalid login... set err and drop out.
		$err = "Invalid Sign On";
	}
}

my $desc = undef;

$desc = $client->getPersistedValue( name=> "desc" );

if ( defined $desc )
{
	$client->repersistValues( values=> ['desc'] );
}
else
{
	if ( defined $cgi->param('desc') )
	{
		$client->setPersistedValue( name=> 'desc', value=> $cgi->param('desc') );
		$desc = $cgi->param('desc');
	}
}

if ($cgi->param('idle'))
{
	$desc = "Your connection was idle and was disconnected for security reasons";
}
	
if ( $showLogin && !scalar(@anxParms) )
{
	#
	# lets clear the session cookie stuff 
	#
	my $cookieWsi = new CGI::Cookie(-name=>'wsi', -value=>'');
	my $cookieWsh = new CGI::Cookie(-name=>'wsh', -value=>'');

	print "Set-Cookie: $cookieWsi\n";
	print "Set-Cookie: $cookieWsh\n";
	
	my $jump = undef;
	
	$jump = $client->getPersistedValue( name=> "jump" );
	
	if ( defined $jump )
	{
		$client->repersistValues( values=> ['jump'] );
	}
	else
	{
		my @params = ();
		foreach ( $cgi->param() )
		{	
			next if $_ eq "desc";
			push @params, "$_=" . $cgi->param($_);
		}

		# this doesn't handle all escaping correctly but it should be fine for the limited use of this feature

		$client->setPersistedValue( name=> 'jump', value=> join('&',@params) );
	}

	my $oem = $tb->getOem();
	my $isMobile = $client->isMobileWebtop();
	
	$oem->printHtmlHeader( title=> "Sign-On", isLogin=> 1);
	$oem->printBodyHeader( noLink => 1, isMobile=> $isMobile  );

	print $closeWindowJs;
	print "<span class='LOGINSTYLE'>";
	
	print "
			<script type=\"text/javascript\">
			
			function finalize()
			{
				var signOn = document.getElementById('signOnButton');
				signOn.disabled = true;
			}

			</script>
			";

	print "
			<form autocomplete='off' method='POST' name='loginForm' onSubmit='return finalize();'>
				<input type='hidden' name='register' value=\"" . (defined($cgi->param('register')) ? HTML::Entities::encode($cgi->param('register')) : "") . "\">
				<input type='hidden' name='oemId' value=\"" . (defined($cgi->param('oemId')) ? HTML::Entities::encode($cgi->param('oemId')) : "" ) . "\">
	";
	
	print $client->getFormInputs();

	my $newPos = 0;

	if ( $effectiveOemId == 1 )
	{
		# new positive specific login page that uses some static graphics
		$newPos = 1;
	}
	
	my $b1 = $tb->createBox( type=> "webTheme", title=> "Please Sign on", width=> "300" );
	
	print "
			<noscript>
			
				<br>
				<center>
					<font color=red>
						<b>It looks like javascript has been disabled in your browser. Please enable javascript before logging in.</b>
					</font>
				</center>

			</noscript>
	";
	
	$oem->printBodyContent( mode=> $mode, desc=> $desc, b1=> $b1,isMobile => $isMobile);

	my $pwtype = $cgi->param('pwtype');
	$pwtype = 'password' unless defined $pwtype;

	my $brokenLoginUserName = $cgi->param('un') || "";

	print "<script language='JavaScript1.3' version='1.3'>
				if ((is_win95))
				{
					var is95 = document.getElementById('is95')
					is95.value = 1;
				}
				if ((is_win98))
				{
					var is98 = document.getElementById('is98')
					is98.value = 1;
				}
				if ((is_winme))
				{
					var isME = document.getElementById('isME')
					isME.value = 1;
				}
			</script>
			";

	if ($challenge)
	{
		print "
			<input type='hidden' name='un' value='" . HTML::Entities::encode($brokenLoginUserName) . "'/>
			<input type='hidden' name='challenge' value='1'/>
		</tr>
		<tr>
			<td class='PASSWORDTD' align='right'>
				<b>
					<div id='passwordLabel' class='PASSWORDTD'>
						Response:
					</div>
				</b>
			</td>
		";
	}
	else
	{
		print "
			<td class='USERNAMETD' align='right'>
				<b>
					Username:
				</b>
			</td>
			<td class='USERNAMEINPUTTD' align='left'>
				<input type='text' size=\"" . ($isMobile ? "10" : "20") . "\" name='un' value=\"" . HTML::Entities::encode($brokenLoginUserName) . "\" id='un'/>
			</td>
		</tr>
		<tr>
			<td class='PASSWORDTD' align='right'>
				<b>
					<div id='passwordLabel' class='PASSWORDTD'>
						Password:
					</div>
				</b>
			</td>
		";
	}

	print "
			<td class='PASSWORDINPUTTD' align='left'>
				<input type='password' size=\"" . ($isMobile ? "10" : "20") . "\" name='pw' id='pw'/>&nbsp;";
	!$isMobile and $oem->printPasswordHelp();
	print "
		</tr>
		<tr>
			<td class='SIGNONBUTTON' align='center' colspan='2'>
		
		";

	$oem->printBodyContentFooter( err=> $err, b1=> $b1, mode=> $mode, isMobile => $isMobile);

	print "
			</center>
			</form>
			</span>
		";

	if ( $brokenLoginUserName eq '' )
	{
		print "
			<script language='JavaScript1.3' TYPE='text/javascript'>
					document.loginForm.un.focus();
			</script><br><br><br>
		";
	}
	else
	{

		print "
			<script language='JavaScript1.3' TYPE='text/javascript'>
					document.loginForm.pw.focus();
			</script><br><br><br>
		";
	}

	$oem->printBodyFooter();
	$oem->printHtmlFooter();
}
elsif ( $cgi->param('logout') || $cgi->param('pwreset') )
{
	my $oem = $tb->getOem();
	my $isMobile = $client->isMobileWebtop();
	
	$oem->printHtmlHeader( title=> "Sign-On", isLogin=> 1);
	$oem->printBodyHeader( noLink => 1, isMobile=> $isMobile  );

	print "<center><br><br>";
	print $desc;
	print "You may now close this window.";

	$oem->printBodyFooter();
	$oem->printHtmlFooter();

}
else
{
print "Content-type: text/html\n\n";
print "
<html>
<head>
<meta http-equiv=\"refresh\" content=\"1;url=" . $config{anxredirecturl} . "\" />
<title></title>
</head>
<body>
</body>
</html>
";
}

exit;

