#!/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::Policy::ProvisionBuddy;
use Pos::Policy::PolicyCache;
use Pos::Webtop::Toolbox ();
use Digest::MD5;


my @dict = ();
for ('a'..'z', 0..9, 'A'..'Z') { push @dict, $_; }
my $tb = Pos::Webtop::Toolbox->new();
my $cgi = $tb->getCgi();
my $db = $tb->getPolicyDb();

my $customerName = "Olathe";

my $adminLink = "http://omc.positivenetworks.net/admin/";
my $positiveLinkName = "Positive";
my $customerLinkName = $customerName;
my $acceptedLinkName = "Accepted";
my $rejectedLinkName = "Rejected";
#my $nameOfFile = "doctoradmin.pl";
#my $customerId = 16;
my $nameOfFile = "index.pl";
my $customerId = 3160;
my $defaultGroup = "Doctors";
my $imgSource = "LocalWebLib/techphoto1.jpg";
my $method = $cgi->param('method');

print "Content-type: text/html\n\n";

print "
			<html>
				<head>
					<title>
						Positive Networks: $customerName Signup Admintools	
					</title>
					<style type='text/css'>
						td.BOXTD1 { background-color: #00A000; font-family: verdana; font-size: 12pt; color: white;} 
						td.BOXTD2 { background-color: #white; font-family: verdana; font-size: 10pt;}
						td.BOXTD3 { background-color: #00A000; font-family: verdana; font-size: 10pt;}
						a.mainlink:link { color: white; }
						a.mainlink:visited { color: white; }
						a.mainlink:hover ( color: red; }
					</style>
				</head>

				<body marginheight='0' leftmargin='0' topmargin='0' marginwidth='0'>
					<table cellspacing='0' cellpadding='0' width='100%' border='0'>
						<tr>
							<td>
								<img src='$imgSource'><br>
							</td>
						</tr>
						<tr>
							<td bgcolor='#00270c'><img height='1' src='LocalWebLib/space.gif'></td>
						</tr>
						<tr>
							<td bgcolor='#ff9700'><img height='11' src='LocalWebLib/space.gif'></td>
						</tr>
						<tr>
							<td bgcolor='#00270c'><img height='1' src='LocalWebLib/space.gif'></td>
						</tr>
					</table>
					<center>
					<table cellpadding='0' cellspacing='0'width='100%'>
						<tr>
							<td border='0' bgcolor='00A000'>
							<center>
								<table border='0' width='500'>
									<tr>
										<td class='BOXTD3'>
											<a href='$nameOfFile?method=showPositive' class='mainlink'>$positiveLinkName</a>
										</td>
										<td class='BOXTD3'>
											<a href='$nameOfFile?method=showCustomer' class='mainlink'>$customerLinkName</a>
										</td>
										<td class='BOXTD3'>
											<a href='$nameOfFile?method=showAccepted' class='mainlink'>$acceptedLinkName</a>
										</td>
										<td class='BOXTD3'>
											<a href='$nameOfFile?method=showRejected' class='mainlink'>$rejectedLinkName</a>
										</td>
										<td class='BOXTD3'>
											<a href='$nameOfFile?method=emailNotificationList&entity=positive' class='mainlink'>PosEmail</a>
										</td>
										<td class='BOXTD3'>
											<a href='$nameOfFile?method=emailNotificationList&entity=customer' class='mainlink'>$customerLinkName Email</a>
										</td>
									</tr>
								</table>
							</td>
						</tr>
					</table>
		";

if (not defined($method))
{
}
elsif ($cgi->param('unreject'))
{
	my $individualSignupId = $cgi->param('signupId');
	
	$db->do( sql=> "update
							individual_signups
						set
							customer_reject = NULL 
						where
							individual_signup_id = $individualSignupId
						");
	$db->commit();
}
elsif ($method eq 'deleteUser')
{
	my $individualSignupId = $cgi->param('signupId');

	$db->do( sql=> "delete from individual_signups where individual_signup_id = $individualSignupId " );
	$db->commit();
}
elsif ($method eq 'emailNotificationList')
{
	my $entity = $cgi->param('entity');
	
	emailNotification(
			entity => $entity);	
}
elsif ( $method eq 'emailUpdate')
{
	my $entity = $cgi->param('entity');

	if ( $entity eq 'positive' )
	{
		# delete the existing email addreses
		$db->do( sql=> "delete from customer_pos_ind_signup_emails where customer_id = $customerId" );
	}
	elsif ( $entity eq 'customer' )
	{
		# delete the existing email addreses
		$db->do( sql=> "delete from customer_ind_signup_emails where customer_id = $customerId" );

	}
	my @addresses = $cgi->param('emailAddresses');
	
	my $cnt = 1;
	foreach my $email ( @addresses )
	{
		# if the address doesn't look right, ignore it
		if ( ! ( $email =~ /.+\@.+\..+/ ) )
		{
			warn "The email address $email did not look like an email address.\n";
			next;
		}

		# escape the email address
		$email = $db->escape( dirty=>$email );
		
		my $individualSignupId = $db->getNextSequenceValue( sequence=> "individual_signups_pk" );
		
		if ( $entity eq 'positive' ) 
		{
			# insert a new row for this email address for this customer
			$db->do( sql=> "
				INSERT into customer_pos_ind_signup_emails(
					CUSTOMER_ID,
					EMAIL_ID,
					EMAIL_ADDRESS
				) VALUES (
					$customerId,
					$individualSignupId,
					'$email'
				)
				" );
		}
		elsif ( $entity eq 'customer' )
		{
			# insert a new row for this email address for this customer
			$db->do( sql=> "
				INSERT into customer_ind_signup_emails(
					CUSTOMER_ID,
					EMAIL_ID,
					EMAIL_ADDRESS
				) VALUES (
					$customerId,
					$individualSignupId,
					'$email'
				)
				" );
		}
		$cnt++;
	}
	$db->commit();
	emailNotification( entity => $entity );
}
elsif ($method eq 'acceptOrReject')
{
	
	my $lastName = $cgi->param('lastName');
	my $firstName = $cgi->param('firstName');
	warn "WARNING: $firstName"; 
	my $signupId = $cgi->param('signupId');
	my $comments = $cgi->param('comments');
	my $decision = $cgi->param('decision');
	my $entity   = $cgi->param('entity');
	my $pb;
	my $userId;	
	my $userName = $cgi->param('userName');	
	my $tmpPass;
	my $pass;	

	
	my $groupId = $cgi->param('groupList');
	if ( $decision eq 'Accept' )
	{
		#add the user
		$pb = Pos::Policy::ProvisionBuddy->new( customerId=> $customerId, db=> $db );
			
		# createUser is now passed initializePolicyCache as 0 since in the old createUser, 
		# the policy cache was not generated... in the new version, it IS... since
		# we cannot move the two independently of each other, we need to make this use
		# either version correctly.  To do this, we tell createUser to not initialize
		# the cache... on old version, this does nothing, on new version, it makes it act
		# like old version, we will then manually generate the cache with a call to 
		# the policy cache api.

		$userId = $pb->createUser( userName=> $userName, groupId=> $groupId,
			initializePolicyCache=> 0);
		if((defined($userId) && length($userId)))
		{
			$pb->activateUser( userId=> $userId, active=> 1 );
			$pb->billUser( userId=> $userId, billing=> 1 );
		
			$tmpPass = getPass();
		
			$db->do( sql=> "
					update users 
					set password=md5sum('$tmpPass') 
					where 
					user_id = $userId
				");
		
			# regenerate cache
			Pos::Policy::PolicyCache::scheduleUserPolicyCacheRegeneration(
				userId=> $userId,
				db=> $db
			);
		}
		$db->commit();
	}
	
	acceptOrReject(
			firstName => $firstName,
			lastName => $lastName,
			signupId => $signupId,
			entity   => $entity,
			decision => $decision,
			comments => $comments,
			tmpPass => $tmpPass,
			userName => $userName);
}
elsif ($method eq 'viewSignup')
{
	my $signupId = $cgi->param('signupId');
	my $entity   = $cgi->param('entity');

	viewSignup(
			signupId => $signupId,
			entity   => $entity);
}
elsif ($method eq 'showPositive')
{
	my @positiveList = $db->query( sql => "
		select 
			first_name,
			last_name,
			individual_signup_id
		from
			individual_signups
		where
			customer_id = $customerId 
			and 
			positive_accept IS NULL
			and
			positive_reject IS NULL
			and
			customer_accept IS NULL
			and
			customer_reject IS NULL
		order by
			upper(last_name),
			upper(first_name)
		");

	print "
			<br/>
			<table border='0' width='500'>
				<tr>
					<td class='BOXTD1' align='left' colspan='3'>
						<nobr><b>Positive queue</b></nobr>
					</td>
				</tr>
			";

	foreach my $posList ( @positiveList )
	{
		my ($firstName,$lastName,$individualSignupId) = @{ $posList };
		
		print " 
				<tr>
					<td class='BOXTD2'>
						$lastName, $firstName
					</td>
					<td align='right' width='75'>
						<a href='$nameOfFile?method=viewSignup&signupId=$individualSignupId&entity=positive' > View Info </a>
					</td>
					<td align='right' width='75'>
						<a href='$nameOfFile?method=deleteUser&signupId=$individualSignupId&entity=positive' > Delete User </a>
					</td>
				</tr>
				";	
	}	

	print "
			</table>
		";
}
elsif ($method eq 'showCustomer')
{
	my @customerList = $db->query( sql => "
		select 
			individual_signup_id,
			first_name,
			last_name
		from
			individual_signups
		where
			customer_id = '$customerId'
			and 
			positive_accept IS NULL
			and
			positive_reject IS NOT NULL
			and
			customer_accept IS NULL
			and
			customer_reject IS NULL
		order by
			upper(last_name),
			upper(first_name)
		");

	print "
			<br/>
			<table width='500'>
				<tr>
					<td class='BOXTD1' colspan='2'>
						<b>Forwarded to $customerName for Action</b>
					</td>
				</tr>
			";

	foreach my $customerList ( @customerList )
	{
		my ( $id, $firstName, $lastName ) = @{ $customerList };
		
		print " 
				<tr>
					<td class='BOXTD2'>
						$lastName, $firstName
					</td>
					<td align='right'>
						<a href='$nameOfFile?method=viewSignup&signupId=$id&entity=customer' > View Info </a>
					</td>
				</tr>
				";	
	}	

	print "
			</table>
		<br/>
		<br/>
		" . scalar(@customerList) . " user" . ((scalar(@customerList) != 1)?"s":"") . " forwarded to $customerName for action.";
}
elsif ($method eq 'showAccepted')
{
	my @acceptedList = $db->query( sql => "
		select 
			individual_signup_id,
			first_name,
			last_name
		from
			individual_signups
		where
			customer_id = '$customerId'
			and (
				positive_accept IS NOT NULL
				or
				customer_accept IS NOT NULL
			)
		order by
			upper(last_name),
			upper(first_name)
		");

	print "
		<br/>
		<table width='500'>
			<tr>
				<td class='BOXTD1' align='left' colspan='2'>
					<b>Accepted</b>
				</td>
			</tr>
		";

	foreach my $acceptedList ( @acceptedList )
	{
		my ( $individualSignupId, $firstName, $lastName ) = @{ $acceptedList };
		
		print " 
			<tr>
				<td class='BOXTD2' align='left'>
					$lastName, $firstName
				</td>
				<td align='right'>
					<a href='$nameOfFile?method=viewSignup&signupId=$individualSignupId&entity=acceptedList' > View Info </a>
				</td>	
			</tr>
				";	
	}	

	print "
		</table>
		<br/>
		<br/>
		" . scalar(@acceptedList) . " accepted user" . ((scalar(@acceptedList) != 1)?"s":"") . ".";	
	
}
elsif ($method eq 'showRejected')
{
	my @rejectedList = $db->query( sql => "
		select
			individual_signup_id,
			first_name,
			last_name
		from
			individual_signups
		where
			customer_id = '$customerId'
			and positive_reject IS NOT NULL
			and customer_reject IS NOT NULL
		order by
			upper(last_name),
			upper(first_name)
		");

	print "
		<br/>
		<table width='500'>
			<tr>
				<td class='BOXTD1' align='left' colspan='2'>
					<b>Rejected</b>
				</td>
			</tr>
		";


	foreach my $rejectedList ( @rejectedList )
	{
		my ( $individualSignupId, $firstName, $lastName ) = @{ $rejectedList };
		
		print " 
			<tr>
				<td class='BOXTD2' align='left'>
					$lastName, $firstName
				</td>
				<td align='right'>
					<a href='$nameOfFile?method=viewSignup&signupId=$individualSignupId&entity=rejectedList' > View Info </a>
				</td>	
				<td align='right' width='75'>
					<a href='$nameOfFile?method=deleteUser&signupId=$individualSignupId&entity=positive' > Delete User </a>
				</td>
			</tr>
				";	
	}	

	print "
		</table>
		<br/>
		<br/>
		" . scalar(@rejectedList) . " rejected user" . ((scalar(@rejectedList) != 1)?"s":"") . "."; 	
}

print "
						</center>
						</form>
					</body>
				</html>
			";	


sub viewSignup
{
	my ($signupId, $entity) = @{{@_}}{qw/signupId entity/};
	my @userInfoList = $db->query ( sql => "
		select
			first_name,
			middle_initial,
			last_name,
			primary_email_address,
			secondary_email_address,
			user_name,
			last_four_social,
			date_of_birth,
			home_address1,
			home_address2,
			home_city,
			home_state,
			home_zip_code,
			home_phone,
			primary_office_name,
			primary_office_address1,
			primary_office_address2,
			primary_office_city,
			primary_office_state,
			primary_office_zipcode,
			secondary_office_name,
			secondary_office_address1,
			secondary_office_address2,
			secondary_office_city,
			secondary_office_state,
			secondary_office_zip_code,
			comments
		from
			individual_signups	
		where
			individual_signup_id = $signupId
			and
			customer_id = $customerId
		");
	my @fields = (
		"BANNER: Account Setup Information",
		"First Name",
		"Middle Initial",
		"Last Name",
		"Primary Email",
		"Secondary Email",
		"Cerner User ID",
		"Social",
		"Date of Birth",
		"BANNER: Home Address",
		"Address 1",
		"Address 2",
		"City",
		"State",
		"Zip Code",
		"Phone",
		"BANNER: Primary Office Address",
		"Name of Office, Clinic, or Hospital",
		"Address 1",
		"Address 2",
		"City",
		"State",
		"Zip Code",
		"BANNER: Secondary Office Address",
		"Name of Office, Clinic, or Hospital",
		"Address 1",
		"Address 2",
		"City",
		"State",
		"Zip Code",
		"BANNER: Comments",
		"Comments"
	);
	my @currentGroups = $db->query ( sql => "
				select
					group_id,
					group_name
				from 
					groups
				where
					customer_id = $customerId
				order by group_name
			");


	my ($userName) = $db->query ( sql => "
			select
				primary_email_address
			from
				individual_signups
			where
				individual_signup_id = $signupId
				and
				customer_id = $customerId
			");

	my $firstNameUserInfo;
	my $lastNameUserInfo;
	if (scalar(@userInfoList) > 0)
	{
		my @fields = @{ $userInfoList[0] };

		$firstNameUserInfo = $fields[0];
		$lastNameUserInfo = $fields[2];
	}
			
	print "
			<br/>
			
				<form method='POST' >
					<input type='hidden' name='signupId' value='" . HTML::Entities::encode($signupId) . "'>
					<input type='hidden' name='method' value='acceptOrReject'>
					<input type='hidden' name='entity' value='" . HTML::Entities::encode($entity) . "'>
					<input type='hidden' name='userName' value='" . HTML::Entities::encode($userName) . "'>	
					<input type='hidden' name='firstName' value='" . HTML::Entities::encode($firstNameUserInfo) . "'>
					<input type='hidden' name='lastName' value='" . HTML::Entities::encode($lastNameUserInfo) . "'>
					<table border='0' cellspacing='1' cellpadding='1'>
			";
	foreach my $userInfoList ( @userInfoList )
	{
		my @userFields = @{ $userInfoList };
		my $fieldNumber = 0;
		print "
							<tr>
								<td colspan='2' class='BOXTD2'>
									<b>" . $userFields[2] . ", " . $userFields[0] . "</b>
								</td>
							</tr>
				";

		foreach my $userField (@userFields)
		{
			if ($fields[$fieldNumber] =~ /BANNER:/)
			{
				my ($ignore, $title) = split /:/, $fields[$fieldNumber];

				print "
							<tr>
								<td class='BOXTD1' colspan='2' align='center'>
									<b>$title</b>
								</td>
							</tr>
					";

				$fieldNumber++;
			}

			print " 
							<tr>
								<td class='BOXTD2' align='left'>
									<nobr>" . $fields[$fieldNumber] . ":</nobr>
								</td>
								<td colspan='3'>
									";

			if ($fields[$fieldNumber] eq 'Comments' && ($entity ne 'acceptedList' and $entity ne 'rejectedList'))
			{
				print "<textarea cols='25' rows='10' name='comments'>" . HTML::Entities::encode($userField) . "</textarea>";
			}
			elsif ($fields[$fieldNumber] eq 'Comments' && ($entity eq 'acceptedList' or $entity eq 'rejectedList'))
			{
				print "<pre>" . HTML::Entities::encode($userField) . "</pre>";
			}
			else
			{
				print  HTML::Entities::encode($userField);
			}

			print "
								</td>
							</tr>
					";	
		
			$fieldNumber++;
		}

	}	
	if ($entity ne 'acceptedList' and $entity ne 'rejectedList')
	{
			print "				<tr>
										<td class='BOXTD2' align='right'>
											Select Group:
										</td>
										<td>
											<select name='groupList'>
					";

					foreach my $groupList ( @currentGroups )
					{
						my ( $groupNumber, $groupName ) = @{ $groupList };

						print "			<option value='$groupNumber'" . ($groupName eq $defaultGroup?" selected":"") . ">$groupName";
					}
											
			print "
											</select>
										</td>
									</tr>
				";				
				
	}

	if ($entity ne 'acceptedList' and $entity ne 'rejectedList')
	{
		print "
							<tr>
								<td class='BOXTD1' colspan='2' align='center'>
									<br/>
									<input type='submit' name='decision' value='Accept'>
									<input type='submit' name='decision' value='Reject'>
									<input type='submit' name='decision' value='Save'>
									<br/>
									<br/>
								</td>
							</tr>
			";
	}
	
	if ($entity eq 'rejectedList')
	{
		print "
							<tr>
								<td class='BOXTD1' colspan='2' align='center'>
									<br/>
									<input type='submit' name='unreject' value='Unreject'>
									<br/>
									<br/>
								</td>
							</tr>
			";
	}

	print "
						</table>
						</form>
						
						</center>
						</form>
					</body>
				</html>
			";	
}

sub acceptOrReject
{
	my ($firstName, $lastName, $signupId, $entity, $decision, $comments, $tmpPass, $userName) = @{{@_}}{qw/firstName lastName signupId entity decision comments tmpPass userName/};
	my $field;
	my ($customerId) = $db->query(sql => "
			select
				customer_id
			from
				individual_signups
			where
				individual_signup_id = '" . $db->escape(dirty => $signupId) . "'
			");
	my @emails;

	$decision = 'Accept' if (not defined($decision));

	if (defined($comments) and length($comments) > 0)
	{
		$db->do(sql => "
			update
				individual_signups
			set 
				comments = '" . $db->escape(dirty => $comments) . "'
			where
				individual_signup_id = '" . $db->escape(dirty => $signupId) . "'
			");
		$db->commit();
	}

	if ($decision eq 'Save')
	{
		print "
			<table>
				<tr>
					<td class='BOXTD2'>
						$userName has been saved.
					</td>
				</tr>
			</table>
		";
		return;
	}

	$field = 'positive_accept' if ($entity eq 'positive' and $decision eq 'Accept');
	$field = 'positive_reject' if ($entity eq 'positive' and $decision eq 'Reject');
	$field = 'customer_accept' if ($entity eq 'customer' and $decision eq 'Accept');
	$field = 'customer_reject' if ($entity eq 'customer' and $decision eq 'Reject');

	if (defined($field))
	{
		$db->do(sql => "
				update
					individual_signups
				set
					$field = " . $db->getCurrentTimeStampString() . "
				where
					individual_signup_id = '" . $db->escape(dirty => $signupId) . "'
				");
				$db->commit();
	}

	if ($entity eq 'positive')
	{
		if ($decision eq 'Accept')
		{
			# customer
			@emails = $db->query(sql => "
					select
						email_address
					from
						customer_ind_signup_emails 
					where
						customer_id = '$customerId'
					union
					select
						email_address
					from
						customer_pos_ind_signup_emails
					where
						customer_id = '$customerId'
					order by
						email_address
					");
			


					
		}	
		elsif ($decision eq 'Reject')
		{
			# positive & customer
			@emails = $db->query(sql => "
					select
						email_address
					from
						customer_ind_signup_emails 
					where
						customer_id = '$customerId'
					union
					select
						email_address
					from
						customer_pos_ind_signup_emails 
					where
						customer_id = '$customerId'
					order by
						email_address
					");
		}
	}
	elsif ($entity eq 'customer')
	{
		if ($decision eq 'Accept')
		{
			# positive
			@emails = $db->query(sql => "
					select
						email_address
					from
						customer_pos_ind_signup_emails 
					where
						customer_id = '$customerId'
					order by
						upper(email_address)
					");
		}	
		elsif ($decision eq 'Reject')
		{
			# positive
			@emails = $db->query(sql => "
					select
						email_address
					from
						customer_pos_ind_signup_emails 
					where
						customer_id = '$customerId'
					order by
						upper(email_address)
					");
		}
	}

	print "
		<table>
			<tr>
				<td class='BOXTD2'>
					$userName has been " . lc($decision) . "ed.
				</td>
			</tr>
			<tr>
				<td class='BOXTD2'>
					Email was sent to the following address(es):
				</td>
			</tr>
		</table>
		<br>
		<table>
				
			";
		foreach my $line(@emails)
		{
			print "<tr>
						<td class='BOXTD2'>
							$line <br>
						</td>
					</tr>";
		}
	print "	
			</table>";
	if (scalar(@emails))
	{
		$ENV{'PATH'} = "/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin";
		my $subjectString;
		my $bodyString;

		if ($decision eq 'Reject')
		{
			$subjectString = "Forwarded to $customerName for Action";
			$bodyString = "Positive has forwarded a signup form submitted by $firstName $lastName ($userName) to $customerName for action. 

You may view the user's information by clicking on the following link:

$adminLink

If you have any questions or problems, please contact our Support Desk: 

Local support:          913-469-0005
Toll-free support:      877-9-POSITIVE (877-976-7484)
Email support:         support\@positivenetworks.net

Telephone and email support is available to you during the following times:

Monday-Friday:    7am-10pm Central
Saturday:         10am-3pm Central

Sincerely,

Positive Networks

" if ($entity eq 'positive');
			$bodyString = "$customerName has rejected a signup form submitted by $firstName $lastName ($userName). 
You may view the user's information by clicking on the following link:

$adminLink

If you have any questions or problems, please contact our Support Desk: 

Local support:          913-469-0005
Toll-free support:      877-9-POSITIVE (877-976-7484)
Email support:         support\@positivenetworks.net

Telephone and email support is available to you during the following times:

Monday-Friday:    7am-10pm Central
Saturday:         10am-3pm Central

Sincerely,

Positive Networks

" if ($entity eq 'customer');
		}	
		else
		{
			$subjectString = "User accepted";
			$bodyString = "Positive has accepted the signup from submitted by $firstName $lastName ($userName).

You may view the user's information by clicking on the following link:

$adminLink

If you have any questions or problems, please contact our Support Desk:

Local support:          913-469-0005
Toll-free support:      877-9-POSITIVE (877-976-7484)
Email support:         support\@positivenetworks.net

Telephone and email support is available to you during the following times:

Monday-Friday:    7am-10pm Central
Saturday:         10am-3pm Central

Sincerely,

Positive Networks

			" if ($entity eq 'positive');
			$bodyString = "$customerName has accepted the signup from submitted by $firstName $lastName ($userName).

You may view the user's information by clicking on the following link:

$adminLink

If you have any questions or problems, please contact our Support Desk:

Local support:          913-469-0005
Toll-free support:      877-9-POSITIVE (877-976-7484)
Email support:         support\@positivenetworks.net

Telephone and email support is available to you during the following times:

Monday-Friday:    7am-10pm Central
Saturday:         10am-3pm Central

Sincerely,

Positive Networks

			" if ($entity eq 'customer');
		}	
		
		my $from = "\"Positive Networks\" <support\@positivenetworks.net>";

		email( subject=> $subjectString, from=> $from, body=> $bodyString, to=> \@emails );
	}	

	#email the user
	if ( $decision eq 'Accept')
	{
		$ENV{'PATH'} = "/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin";

		my $subjectString = "Welcome to Positive Networks";
		my $bodyString = "Dear Dr. $lastName,

Welcome to Positive Networks - your Remote Access and End-Point Security Service!  You now have access to your company's network from anywhere you have Internet access!  This VPN service is available through our partnership with OHSI and will allow you to access your Cerner applications when working remotely.

We encourage you to call us for new-user orientation so that one of our Remote Access specialists can walk you through getting connected securely.  Please make sure you have your user name and password ready and open your web browser to verify your internet connection.  Then, simply call 877-9-POSITIVE (877-976-7484) and a representative will guide you through the next steps.

If you would like to get started on your own, you may, but remember that we are standing by to help you at any point.  Please don't hesitate to call 877-9-POSITIVE (877-976-7484), and we will help get you started!

To begin using the VPN client, please follow these steps:
 
1. Open your web browser and go to http://www.positivenetworks.com/.
2. Click on the 'Getting Started' link in the upper right-hand corner of the page.
3. Click on the 'Install Now' link at the top of the page.
4. Use the following username and password to sign in to the download page:
   Username: $userName
   Password: $tmpPass
5. After completing the registration process and choosing a permanent password, click the 'Install Now' link to begin the download.
6. Once the software is installed, double-click on the P icon in your system tray (next to your clock) to bring up the Sign On dialog.
7. To Sign On to PositivePRO, enter your username from above and the password you chose for yourself.
8. To launch Cerner, just click on the new shortcut on your desktop 'Cerner - Olathe Medical' or launch Internet Explorer.
9. Here, you will use your normal Cerner login credentials.
 
If you have any questions or problems, please contact our Support Desk:
 
Toll-free support:      877-9-POSITIVE (877-976-7484)
Email support:         support\@positivenetworks.net
 
Telephone and email support is available to you during the following times:
 
Monday-Friday:    7am-10pm Central
Saturday:         10am-3pm Central
 
We look forward to serving you!
 
Sincerely,
 
User Support Desk
Positive Networks
";
		
		my $from = "\"Positive Networks\" <support\@positivenetworks.net>";

		email( subject=> $subjectString, from=> $from, body=> $bodyString, to=> $userName );
	}
	
}

sub emailNotification
{

	my $entity = @{{@_}}{qw/entity/};

	print "

			
				
		<script language='JavaScript'>
		// <!--

			function addValue( myform )
			{
				var re1 = /.+\@.+\\..+/;

				if ( ! myform.add_value.value.match(re1) )
				{
					alert('Please enter a valid email address.');
				}
				else
				{
				var i = myform.emailAddresses.length;

				

				if (myform.add_value.value.length > 0) {
					
					myform.emailAddresses.options[i] = 
						new Option(
						myform.add_value.value,
						myform.add_value.value
						);

					myform.add_value.value= '';	}
				}
			

			} // end addValue;


			
			function deleteValue( myform ) {

				var i = 0;

				while (i < myform.emailAddresses.options.length) {
		
					if ( myform.emailAddresses.options[i].selected ) {
	
						myform.emailAddresses.options[i] = null; // options[] shrinks
	
					} else {
						
						i++;
					} 
	
				} // end while


			} // end toastCrispy


			function selectSelectAll(selectObject,selectState) {
	
				var i;
	
				for (i=0; i < selectObject.options.length; i++) {
	
					selectObject.options[i].selected = selectState;
	
				}
				
			}

			var addTextIsFocused=0;
	
			
			function finalize( myform ) {

				if ( addTextIsFocused > 0 ) {
					
					// we are focused on the add box... lets not submit, rather, add that value

					addValue( myform );

					myform.add_value.focus();

					return false;

				} else {

					selectSelectAll(myform.emailAddresses,true);

					// taint checking here
					
					return true;

				}


			}

		// -->
		</script>
		";
			
print "<center><form method='POST' onSubmit='return finalize(this);'>";
			
			print "<input type='hidden' name='entity' value='$entity'>
						<input type='hidden' name='method' value='emailUpdate'>";
			

	## Actions -- if applicable
print "<br>
			<br>
					
		<table width='300'>
			<tr>
				<td class='BOXTD1'>
					<B> New email address: </b><br>
				</td>
			</tr>
			<tr>
				<td class='BOXTD2'>
						<input onFocus='addTextIsFocused=1;' onBlur='addTextIsFocused=0;' type='text' size=30 name='add_value'>
						<input type='button' value='Add' onClick='addValue(form)'><br>
				</td>
			</tr>
			<tr>
				<td class='BOXTD1'>
					<b>Email Address List:</b><br>
				</td>
			</tr>
			<tr>
				<td class='BOXTD2'>
						<select size=5 multiple name='emailAddresses' class=PSMULTISELECT>
		";	
		my @currentOptions;
		if ( $entity eq 'positive' )
		{
			 @currentOptions = $db->query ( sql=> "
					SELECT EMAIL_ADDRESS from 
						customer_pos_ind_signup_emails
					where 
						customer_id=$customerId 
					order by
						upper(email_address)
			" );
		}
		elsif ( $entity eq 'customer' )
		{
			 @currentOptions = $db->query ( sql=> "
					SELECT EMAIL_ADDRESS from 
						customer_ind_signup_emails
					where 
						customer_id=$customerId 
					order by
						upper(email_address)
			" );
		}
			foreach my $currentEmail ( @currentOptions )	
			{
				print "<option value='" . HTML::Entities::encode($currentEmail) ."'>" . HTML::Entities::encode($currentEmail) . "</option>";		
			}

print "		
						</select><br>
						<input type='button' value='Delete Selected' onClick='deleteValue( form )'><br>
				</td>
			</tr>
			<tr>
				<td class='BOXTH'>
					<center>
								<input type='submit' name='saveEmail' value='Save'>
					
					</center>
				</td>
			</tr>
	
	</table>
	</form></center>
</body>
</html>
	";

}

sub getPass
{
	my $pass = "";

	while ( not ( $pass =~ /[A-Z]/ and $pass =~ /[a-z]/ and $pass =~ /[0-9]/ ) )
	{
		$pass = "";
		foreach ( 1..8 )
		{
			$pass .= $dict[ rand(scalar(@dict)) ];
		}
	}
return $pass;
}


sub email
{
	my ($subject,$from,$body,$to) = @{{@_}}{qw/subject from body to/};
	
	my $bto;
	my $cto;

	if ( ref($to) eq "ARRAY" )
	{
		$bto = join(', ',@{ $to });
		
		my @goodCtos = ();

		foreach my $badCto ( @{ $to } )
		{
			$badCto =~ s/(\W)/\\$1/g;
			push @goodCtos, $badCto;
		}

		$cto = join(' ',@goodCtos);
		$cto =~ /^(.*)$/;
		$cto = $1;
	}
	else
	{
		$bto = $to;
		$cto = $to;

		$cto =~ s/(\W)/\\$1/g;
		$cto =~ /^(.*)$/;
		$cto = $1;
	}

	$ENV{'PATH'} = "/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin";
	open(MAILPIPE,"| sendmail $cto");
	print MAILPIPE "From: $from\n";
	print MAILPIPE "To: $bto\n";
	print MAILPIPE "Subject: $subject\n";
	print MAILPIPE "\n";
	print MAILPIPE "$body\n";
	close(MAILPIPE);
}
