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

#
# This software is copyright (c) 2001-2004 Positive Networks, Inc.  All rights reserved.
#
# This software is the proprietary and confidential property of Positive Networks, Inc.
# Possession, transmission, publication, or use of this software is prohibited except by prior written consent.
#

use strict;
use Pos::Webtop::Web::ModuleLoader;
use warnings;  # RP - DEBUG

my $tb          = Pos::Webtop::Toolbox->new();
my $db          = $tb->getWebtopDbReader();
my $client      = $tb->getClient();
my $cgi         = $tb->getCgi();
my $oem         = $tb->getOem();
my $ocxFailed   = $cgi->param('ocxFailed');
my $csiFailed   = $cgi->param('csiFailed');
my $trustedSiteInstructions = $cgi->param('trustedSiteInstructions');
my $oemId = $tb->getOemId();
my $codeOemId = Pos::Webtop::Web::OEMLoader::getSkinOemId(oemId=> $oemId);
my $isMobile = $client->isMobileWebtop();

$ocxFailed = 0 if (not defined($ocxFailed));
$csiFailed = 0 if (not defined($csiFailed));
$trustedSiteInstructions = 0 if (not defined($trustedSiteInstructions));

$client->checkSession();
my $rid = $client->checkActiveRestrictionSetId(tb => $tb);

my $webtopUrl = "https://" . $ENV{'HTTP_HOST'};
my $webtopInstallerPath = $oem->getSetting( setting=>"webtopInstallerPath" );

my $ocxCheckPassed = 0; 
my $userId         = $client->getUserId();
my $ocxRequired    = 0;
my $somTitle       = "";
my $somBody        = "";
my $somRequired    = 0;

my ($majorRelease,$minorRelease,$ocxVersion) = @{$client->getWebtopOcxVersion(db=> $db, userId => $userId)};

my @params = $cgi->param();
my $parms = '';

foreach my $v (@params) 
{
	if ($v eq 'displayFrameset') 
	{
		next;
	}
	
	if ($v eq 'trustedSiteInstructions') 
	{
		next;
	}

	if (length($parms)) { $parms .= "&"; }

	$v =~ /(.*)/;
	$v = $1;

	my $p = $cgi->param($v);

	$p =~ /(.*)/;
	$p = $1;

	$parms .= URI::Escape::uri_escape($v, "\\W") . "=" . URI::Escape::uri_escape($p, "\\W");
}


# If the OCX failed to load, check to see if it is required for this session.
if ($ocxFailed)
{
	warn "portal.pl - ocx failed to load!!!";
	$ocxRequired    = $client->isOcxRequired(tb => $tb, ocxFailed => 1);
	$ocxCheckPassed = 1;
	$rid = $client->setRestrictionSetId(tb=>$tb);

	# Check to see if the user is required to acknowledge a sign on message
	my @msg = $db->query(sql => "
		select
			title_text,
			message_text
		from
			pol_signon_messages
		where
			pol_signon_message_id = (
				select
					pol_signon_message_id
				from
					user_signon_message
				where
					user_id = $userId
					and restrict_set_id = $rid
			)");

	# If the user has a sign on message that they must acknowledge, save it
	# and flag required as one
	if (scalar(@msg))
	{
		($somTitle, $somBody) = @{ $msg[0] };

		$somBody     = HTML::Entities::encode($somBody);
		$somBody     =~ s/_BR_/<br>/g;
		$somRequired = 1;
	}
}
else
{
	$client->usingOcx(tb => $tb);	
}

print $oem->getMainHtmlHeader(title => "Support Center", onLoad => "checkCaptivePortal()", noLink=> 1,isMobile=>$isMobile);

print $tb->getDomJs . "

			<script language='javascript' version='1.3'>

				var currentStep = 0;
				var maxSteps    = 0;

				function getStatusFrame()
				{
					var status = parent.statusFrame;

					if ((status == null) ||
					    (status.isStatusLoaded == null) ||
					    (!status.isStatusLoaded()))
						return null;

					return status;				
				}

				var is_csi_signon_failure = $csiFailed;

				function checkCaptivePortal()
				{
					var status = getStatusFrame();

					// If the ocx failure check passed once, call the handler again to do the next stage of checks
					if ($ocxCheckPassed)
					{
						onOcxLoadFailure();
						return;
					}

					// If the status frame could not be obtained, set a timeout callback to run
					// ourself again in one second.
					if (status == null)
					{
						setTimeout('checkCaptivePortal();', 1000);
						return;
					}
					
					if(status.isPluginBlocked()) 
					{
						onCaptivePortalSetStepDetailText('Browser security settings appear to be blocking the Webtop Plugin from running. If you are running Safari, please open the Security tab of Safari Preferences and click the \"Manage Website Settings...\" button. Select WebtopPlugin from the left pane and under the drop down menu next to webtop.positivenetworks.net on the right, choose \" Allow Always\" and click Done. Once complete, click the \"Sign off\" button below and sign on to Webtop once more. We apologize for any inconvenience.');
					}				

					// If we are captive portalized, update the wizard
					if (status.isCaptivePortalized())
					{
						// If the OCX is online...
						if (status.isOcxOnline())
							refreshWizard();
					}
					else 
					{
						redirectBodyToMain();
					}

					return;
				}

				// Redirect the document body to the main portal
				function redirectBodyToMain()
				{
					var status = getStatusFrame();

					if ((status == null) || (status.isOcxOnline()) || (!$ocxRequired) )
						document.location = 'main.pl?" . $client->getSessionParams() . "&$parms';
				}

				// Redirect the document body back to the portal, optionally with an indication that the ocx failed to load
				function redirectBodyToPortal(OcxFailure, TrustedSiteInstructions)
				{
					document.location = 'portal.pl?" . $client->getSessionParams() . "&$parms' + ((OcxFailure) ? '&ocxFailed=1' : '') + ((TrustedSiteInstructions) ? '&trustedSiteInstructions=1' : '') + ((is_csi_signon_failure) ? '&csiFailed=1' : '');
				}



				function refreshWizard()
				{
					var status = getStatusFrame();
					var backwards;
					var forwards;
					var summary;
					var detail;
					var currentStep;
					var maxSteps;

					if (status == null) {
						return;
					}

					backwards   = status.getCaptivePortalBackwardsMovement();
					forwards    = status.getCaptivePortalForwardsMovement();
					summary     = status.getCaptivePortalStepSummaryText();
					detail      = status.getCaptivePortalStepDetailText();
					currentStep = status.getCaptivePortalCurrentStep();
					maxSteps    = status.getCaptivePortalMaxSteps();
					
					// If the summary is valid, update the wizard.  This is for cases where
					// the portal was not displayed, but the user violated a captive portal
					// monitored item and is being pushed into the captive portal.
					if (summary != null)
					{
						onCaptivePortalSetBackwardsMovement(backwards);
						onCaptivePortalSetForwardsMovement(forwards);
						onCaptivePortalSetStepSummaryText(summary);
						onCaptivePortalSetStepDetailText(detail);
						onCaptivePortalSetCurrentStep(currentStep);
						onCaptivePortalSetMaxSteps(maxSteps);
					}

					showPortal();
				}
			
				//
				// Frame-to-Frame API
				//
				
				function onCsiSignonFailure()
				{
					is_csi_signon_failure = true;
				}
				
				function onOcxLoadFailure()
				{
					if ($ocxCheckPassed)
					{
						if ( (!$ocxRequired) && 
						    ( !isBrowserOnXpSp2() && !isBrowserIE7() ))
						{
							if ($somRequired)
								showSignOnMessage();
							else
								redirectBodyToMain();
						}
						else
							showOcxFailure();
					}
					else
						redirectBodyToPortal(true,false);
				}
				
				//
				// User interaction clicks
				//

				function notifyCaptivePortalResolutionEvent(event, addend)
				{
					var status = getStatusFrame();

					if (status == null)
						return;

					if (addend == null)
						addend = 0;

					status.onCaptivePortalResolutionEvent(event, addend);
				}

				function onHelpClick()
				{
					" . ((defined($oem->{'helpUrl'})) ? "
					window.open(' " . $oem->{'helpUrl'} . "', 'WebTopTutorial');
					" : "") . "
				}

				function onBackClick()
				{
					notifyCaptivePortalResolutionEvent('back');
				}

				function onNextClick()
				{
					if ($ocxFailed)
						redirectBodyToMain();
					else
						notifyCaptivePortalResolutionEvent('next');
				}
				
				function onSignOffClick()
				{
					window.top.location = 'login.pl';
				}
				
				function onCancelClick()
				{	
					var msg;

					msg  = 'Before you can access your corporate network, you must complete the tasks listed in ';
					msg += 'the Support Center.  Click OK to signoff without resolving the tasks.  The next time ';
					msg += 'you attempt to access your corporate network, you again will be asked to complete ';
					msg += 'these tasks.  If you wish to continue, click CANCEL.';

					var ok = confirm(msg);

					if (ok)
						window.top.location = 'login.pl';
				}

				//
				// Captive portal interface change notifications
				//

				function onCaptivePortalSetBackwardsMovement(enable)
				{
					var back = getObjectById(\"captivePortalBack\");

					if (back != null)
						back.style.display = (enable) ? 'block' : 'none';
				}

				function onCaptivePortalSetForwardsMovement(enable)
				{
					var next = getObjectById(\"captivePortalNext\");

					if (next != null)
						next.style.display = (enable) ? 'block' : 'none';
				}

				function onCaptivePortalSetStepSummaryText(summary)
				{
					var summaryTextSpan = getObjectById(\"captivePortalStepSummaryText\");

					if (summaryTextSpan != null)
						summaryTextSpan.innerHTML = summary;
				}

				function onCaptivePortalSetStepDetailText(detail)
				{
					var detailTextSpan = getObjectById(\"captivePortalStepDetailText\");
					var re = /\\n/g;

					detail = String(detail).replace(re, '<br>');	
					
					if (detailTextSpan != null)
						detailTextSpan.innerHTML = detail;
				}

				function onCaptivePortalSetCurrentStep(step)
				{
					var currentStepSpan = getObjectById(\"captivePortalCurrentStep\");

					currentStep = step;

					if (currentStepSpan != null)
						currentStepSpan.innerHTML = (maxSteps && step >= maxSteps) ? step : step + 1;
				}

				function onCaptivePortalSetMaxSteps(steps)
				{
					var maxStepsSpan = getObjectById(\"captivePortalMaxSteps\");
					var prevMaxSteps = maxSteps;

					maxSteps = steps;
					
					if (maxStepsSpan != null)
						maxStepsSpan.innerHTML = steps;

					// If there are no resolution steps, redirect to the main portal.
					if (maxSteps == 0)
						redirectBodyToMain();
				}

				function onCaptivePortalStepFinished(tf)
				{
				}

				function onCaptivePortalResolutionFinished(tf)
				{
					onCaptivePortalSetStepDetailText('You now have access to your corporate network.  Please wait as you are redirected...');

					if (tf)
						checkCaptivePortal();
				}

				//
				// Signon progression
				//
				
				function showProgressTable(scope, tf)
				{
					var progressTableText = getObjectById(scope + \"ProgressTableText\");
					var progressTable     = getObjectById(scope + \"ProgressTable\");
					var intermTable       = getObjectById('intermTable');

					if (progressTable == null || progressTableText == null)
						return;

					if (tf)
					{
						progressTable.style.display     = 'block';
						progressTableText.style.display = 'block';
						intermTable.style.display       = 'none';
					}
					else
					{
						progressTable.style.display     = 'none';
						progressTableText.style.display = 'none';
					}
				}

				function setProgressText(scope, text) 
				{

					var cell = getObjectById(scope + \"ProgressTextCell\");

					if (cell != null)
						cell.innerHTML = text;

				}

				function setProgressPercent(scope, position, range) 
				{

					var fullPercentage  = ((position / range) * 100);
					var emptyPercentage = 100 - fullPercentage;
					var fullCell        = getObjectById(scope + \"ProgressFullCell\");
					var emptyCell       = getObjectById(scope + \"ProgressEmptyCell\");

					if (fullCell == null || emptyCell == null || position > range)
						return;

					var re = /\\\..+\$/;

					fullPercentage  = String(fullPercentage).replace(re, '');
					emptyPercentage = String(emptyPercentage).replace(re, '');

					fullCell.style.width  = fullPercentage + '%';
					emptyCell.style.width = emptyPercentage + '%';
				}

				//
				// General UI
				//

				function showPortal()
				{
					var portal = getObjectById('portalBody');
					var signon = getObjectById('signonBody');

					portal.style.display = 'block';
					signon.style.display = 'none';
				}

				function isCsiSignonFailure()
				{
					return is_csi_signon_failure;
				}

				function showOcxFailure()
				{
					var portal = getObjectById('portalBody');
					var signon = getObjectById('signonBody');
					var fail   = getObjectById('ocxFailureBody');    

					// figure out what text to display depending their browser or if it's a csi failure
					if (isCsiSignonFailure())
					{
						fail.innerHTML =  '<b>Sign on failed.</b>';
						fail.innerHTML += '<br/><br/>';
						fail.innerHTML += \"Please click <a href='login.pl' target='_top'>here</a> to log in again.\";
					}
					else if (isBrowserOnXpSp2() || isBrowserIE7())
					{
						fail.innerHTML = '<table width=70% align=center cellspacing=1 cellpadding=0><tr><td class=BOXTD1 align=left><b>The " . $oem->getSetting( setting=>"webtopProductName" ) . " access ActiveX component could not be installed.  Please try the following:</b></td></tr></table><br/>';
						fail.innerHTML += '<table width=70% align=center cellspacing=1 cellpadding=0><tr><td class=BOXTD1 align=left><b><li>Use the Information Bar to install the ActiveX</b></td></tr></table>';
						fail.innerHTML += '<table width=70% align=center cellspacing=1 cellpadding=0><tr><td class=BOXTD1 align=center><img border=0 src=LocalWebLib/infobarActiveX.png alt=\"Information Bar\"/></td></tr></table>';
						fail.innerHTML += '<table width=70% align=center cellspacing=1 cellpadding=0><tr><td class=BOXTD1 align=left width=3>&nbsp;&nbsp;&nbsp;&nbsp;</td><td class=BOXTD1 align=left>Click on the bar and choose the \"Install ActiveX Control...\" option.  Follow the prompts to install.</td></tr></table></br>';
						fail.innerHTML += '<table width=70% align=center cellspacing=1 cellpadding=0><tr><td class=BOXTD1 align=left><b><li>Add $webtopUrl to trusted sites</b></td></tr></table>';
						
						if ($trustedSiteInstructions)
						{
							fail.innerHTML += '<table width=70% align=center cellspacing=1 cellpadding=0><tr><td class=BOXTD1 align=left><br/><ul><li> Select the <b>Tools / Internet Options...</b> menu option<li> Click on the <b>Security</b> tab<li> Click on the <b>Trusted Sites</b> icon<li> Click on the <b>Sites...</b> button<li> Enter <b>$webtopUrl</b> in the <b>Add this Web site to the zone</b> textbox<li> Click the <b>Add</b> button<li> Click the <b>OK</b> button<li> Click the <b>OK</b> button in the <b>Internet Options</b> dialog<li> Press <b>F5</b> to refresh the page</ul></td></tr></table>';
						}
						else
						{
							fail.innerHTML += '<table width=70% align=center cellspacing=1 cellpadding=0><tr><td class=BOXTD1 align=left width=3>&nbsp;&nbsp;&nbsp;&nbsp;</td><td class=BOXTD1 align=left>For step-by-step instructions <a href=\"javascript:redirectBodyToPortal(true,true);\">click here</a>.</td></tr></table><br/>';
						}
						
						fail.innerHTML += '<table width=70% align=center cellspacing=1 cellpadding=0><tr><td class=BOXTD1 align=left><b><li>Install the ActiveX component directly</b></td></tr></table>';
						fail.innerHTML += '<table width=70% align=center cellspacing=1 cellpadding=0><tr><td class=BOXTD1 align=left width=3>&nbsp;&nbsp;&nbsp;&nbsp;</td><td class=BOXTD1 align=left>If the first two options were not successful, <a href=\"" . $oem->getSetting( setting=>'webtopInstallerPath' ) . "\">click here</a> to install.</td><tr></table><br/>';
						fail.innerHTML += '<table width=70% align=center cellspacing=1 cellpadding=0><tr><td class=BOXTD1 align=left><b><li>Contact customer support for assistance</b></td></tr></table>';
						fail.innerHTML += '<table width=70% align=center cellspacing=1 cellpadding=0><tr><td class=BOXTD1 align=left width=3>&nbsp;&nbsp;&nbsp;&nbsp;</td><td class=BOXTD1 align=left>Call customer support toll free at " . $oem->getSetting( setting=>"customerServicePhone" ) . (($oem->getSetting( setting=>"id" ) == 1)?" or <a href=\"http://server.iad.liveperson.net/hc/45311511/?cmd=file&file=visitorWantsToChat&site=45311511&byhref=1&SESSIONVAR!skill=operations\" target=\"chat45311511\"  onClick=\"javascript:window.open(\\\'http://server.iad.liveperson.net/hc/45311511/?cmd=file&file=visitorWantsToChat&site=45311511&byhref=1&SESSIONVAR!skill=operations&referrer=\\\'+escape(document.location),\\\'chat45311511\\\',\\\'width=472,height=320\\\');return false;\" >click here</a> to start a live chat.":".") . "</td><tr></table>';
						
						if (!$ocxRequired)
						{
							fail.innerHTML += '<br/><table width=70% align=center cellspacing=1 cellpadding=0><tr><td class=BOXTD1 align=left><b><li>Proceed without installing the ActiveX component</b></td></tr></table>';
							fail.innerHTML += '<table width=70% align=center cellspacing=1 cellpadding=0><tr><td class=BOXTD1 align=left width=3>&nbsp;&nbsp;&nbsp;&nbsp;</td><td class=BOXTD1 align=left>Many WebTop features are available without the ActiveX component.  <a href=\"javascript:" . ($somRequired ? "showSignOnMessage();" : "redirectBodyToMain();") . "\">Click here</a> to proceed.</td><tr></table><br/>';
						}
					}
					else
					{
						fail.innerHTML  = '<b>Your browser does not support the plugins required.</b><br/><br/>';
						fail.innerHTML += 'You must use a browser such as Microsoft Internet Explorer that supports ActiveX or Safari Mac with Java in order<br/>';
						fail.innerHTML += 'to gain full access to your corporate network.<br/><br/>';
						fail.innerHTML += \"Once you have enabled these plugins/controls, please click <a href='login.pl' target='_top'>here</a> to log in again.\";
					}

					portal.style.display = 'none';
					signon.style.display = 'none';
					fail.style.display = 'block';

				}

				function showSignOnMessage()
				{
					var body = \"$somBody<br><br>Please click next to continue.\";

					onCaptivePortalSetStepSummaryText(\"" . HTML::Entities::encode($somTitle) . "\");
					onCaptivePortalSetStepDetailText(body);
					onCaptivePortalSetForwardsMovement(true)
					
					var portal = getObjectById('portalBody');
					var signon = getObjectById('signonBody');
					var fail   = getObjectById('ocxFailureBody');    
					
					portal.style.display = 'block';
					signon.style.display = 'none';
					fail.style.display = 'none';
				}

				//
				// XP SP2
				//
				
				function isBrowserOnXpSp2()
				{
					return (window.navigator.userAgent.indexOf('SV1') != -1);
				}

				function isBrowserIE7()
				{
					var rv = -1; // Return value assumes failure
					if (navigator.appName == 'Microsoft Internet Explorer')
					{
						var ua = navigator.userAgent;
						var re  = new RegExp(\"MSIE ([0-9]{1,}[\.0-9]{0,})\");
						if (re.exec(ua) != null)
						rv = parseFloat( RegExp.\$1 );
					}

					if (rv >= 7.0)
					{
						return 1;
					}
					else
					{
						return 0;
					}
				}
			</script>

			<noscript>
			
				<b>Your browser does not support javascript.</b>

			</noscript>

			<br/>
			<br/>
			<center>
				<div id='portalBody' name='portalBody' style='display: none'>
					";

		my $wizard = $tb->createBox(title => "Support Center", width => 400);

		print $wizard->getHeaderHtml();

		print "
					<table border='0' cellspacing='0' cellpadding='2'>
						<tr>
							<td class='CLMPREVIEW' width='100%' valign='middle'>
								<b>
									<span id='captivePortalStepSummaryText' name='captivePortalStepSummaryText'>
										Checking your computer's security...
									</span>
								</b>
							</td>
							<td class='CLMPREVIEW' valign='middle' style='display: none'>
								<nobr>
									Step
									<span id='captivePortalCurrentStep' name='captivePortalCurrentStep'>1</span>
									of
									<span id='captivePortalMaxSteps' name='captivePortalMaxSteps'>1</span>
								</nobr>
							</td>
						</tr>
					</table>

					<hr>

					<table border='0' cellspacing='0' cellpadding='2' height='250'>
						<tr>
							<td class='CLMPREVIEW' valign='top'>
								<span id='captivePortalStepDetailText' name='captivePortalStepDetailText'> 
									Please wait while the security of your computer is validated.  This process may take a few moments...
								</span>
							</td>
						</tr>
					</table>

					<hr>

					<table border='0' cellspacing='0' cellpadding='1'>
						<tr>
							<td align='left' width='70%'>
								<nobr>
								<input type='button' value='Help' onClick='onHelpClick();'/>
								<input type='button' value='Sign Off' onClick='onSignOffClick();'/>
								</nobr>
							</td>
							<td align='left' width='10%'>
								<input id='captivePortalBack' name='captivePortalBack' type='button' value='Back' onClick='onBackClick();' style='display: none'/>
							</td>
							<td align='left' width='10%'>
								<input id='captivePortalNext' name='captivePortalNext' type='button' value='Next' onClick='onNextClick();' style='display: none'/>
							</td>
							<td align='left' width='10%'>
								<input type='button' value='Cancel' onClick='onCancelClick();'/>
							</td>	
								
						</tr>
					</table>

			";

		print $wizard->getFooterHtml();

		print "
				</div>

				<div id='signonBody' name='signonBody'>
					<img src='LocalWebLib/OEM/" . $codeOemId . "/loading-animation.gif'>
					<br/><br/>
					<table id='overallProgressTableText' name='overallProgressTableText' style='display: none' width='250' cellspacing='1' cellpadding='0'>
						<tr>
							<td class='BOXTD1' id='overallProgressTextCell' name='overallProgressTextCell' align='left'>
								<nobr>
									<span id='overallProgressTextCell' name='overallProgressTextCell'>
										Initializing...
									</span>
								</nobr>
							</td>
						</tr>
					</table>
					<table id='overallProgressTable' name='overallProgressTable' width='250' style='display: none' cellspacing='1' bgcolor='black' cellpadding='0'>
						<tr>
							<td>
								<table style='height: 10px' width='100%' cellspacing='0' cellpadding='0' bgcolor='white'>
									<tr>
										<td id='overallProgressFullCell' name='overallProgressFullCell' align='left' bgcolor='black' style='width: 0%'></td>
										<td id='overallProgressEmptyCell' name='overallProgressEmptyCell' align='left' style='width: 100%'></td>
									</tr>
								</table>
							</td>
						</tr>
					</table>

					<table id='currentProgressTableText' name='currentProgressTableText' style='display: none' width='250' cellspacing='1' cellpadding='0'>
						<tr>
							<td class='BOXTD1' align='left'>
								<nobr>
									<span id='currentProgressTextCell' name='currentProgressTextCell'>
									</span>
								</nobr>
							</td>
						</tr>
					</table>
					<table id='currentProgressTable' name='currentProgressTable' width='250' style='display: none' cellspacing='1' bgcolor='black' cellpadding='0'>
						<tr>
							<td>
								<table style='height: 10px' width='100%' cellspacing='0' cellpadding='0' bgcolor='white'>
									<tr>
										<td id='currentProgressFullCell' name='currentProgressFullCell' align='left' bgcolor='black' style='width: 0%'></td>
										<td id='currentProgressEmptyCell' name='currentProgressEmptyCell' align='left' style='width: 100%'></td>
									</tr>
								</table>
							</td>
						</tr>
					</table>
					<table id='intermTable' name='intermTable'>
						<tr>
							<td align='center' style='font-size: 8pt; font-family: \"Verdana\", \"Arial\", \"Helvetica\", sans-serif;'>
								Loading...

							</td>
						</tr>
					</table>
				</div>

				<div id='ocxFailureBody' name='ocxFailureBody' style='display: none'>
				</div>
			</center>

		<script language='javascript' version='1.3'>

			function isLoaded()
			{
				return 1;
			}
			
		</script>
	";

print $oem->getMainHtmlFooter();
