<?php

ob_start();

require_once dirname(__FILE__) . '/php/config.php';

$formId = $utilities->validateData($_GET, 'id');
$hash = $utilities->validateData($_GET, 'token');
$propertyId = $utilities->validateData($_GET, 'pid');
$managementCompanyId = $utilities->validateData($_GET, 'mid');

$embedMode = $utilities->validateData($_GET, 'embed');
$preview = $utilities->validateData($_GET, 'preview');
$timestamp = $utilities->validateData($_GET, 'ts');
$propertyVersion = $utilities->validateData($_GET, 'v');

$userId = $utilities->validateData($_GET, 'uid');

$testMode = $utilities->validateData($_GET, 'test');

$formStructure = null;
$userCurrentPlan = 'Free';

$tracking = array();
$tracking['uri'] = '';
$tracking['userAgent'] = '';
$tracking['clientIp'] = '';
$tracking['referer'] = '';

if (isset($_SERVER['REQUEST_URI']))
{
	$tracking['uri'] = $SITE_URL . trim($_SERVER['REQUEST_URI'], '/');
}

if (isset($_SERVER['HTTP_USER_AGENT']))
{
	$tracking['userAgent'] = $_SERVER['HTTP_USER_AGENT'];
}

if (isset($_SERVER['REMOTE_ADDR']))
{
	$tracking['clientIp'] = $_SERVER['REMOTE_ADDR'];

	if (0 < strlen($tracking['clientIp']))
	{
        try
        {
			$userLocation = json_decode(file_get_contents('https://ipinfo.io/' . $tracking['clientIp'] . '/geo'),  true);

			if ($userLocation)
			{
				$tracking['userLocation'] = $userLocation['city'] . ' / ' . $userLocation['region'] . ' / ' . $userLocation['country'];
			}
    	}
    	catch (Exception $exception)
    	{
    	}
	}
}

if (isset($_SERVER['HTTP_REFERER']))
{
	$tracking['referer'] = $SITE_URL . $_SERVER['HTTP_REFERER'];
}

if (0 < strlen($formId))
{
	$form = new FormBuilderForm($utilities);
	$form->getById($db, $formId);

	if (0 < strlen($form->getVariable('formSetting_redirectToAnother')))
	{
        header('Location: ' . $form->getVariable('formSetting_redirectToAnother'));
		exit(0);
	}
	else if (0 < strlen($form->getVariable('formSetting_redirectToAnotherForm')))
	{
		$formId = $form->getVariable('formSetting_redirectToAnotherForm');

		unset($form);

		$form = new FormBuilderForm($utilities);
		$form->getById($db, $formId);
	}
	else if (0 < strlen($form->getVariable('formSetting_redirectToAnotherPackage')))
	{
		$_GET['id'] = $form->getVariable('formSetting_redirectToAnotherPackage');

		unset($form);

		include_once (dirname(__FILE__) . '/formPackage.php');

		ob_end_flush();

		exit(0);
	}

	$user = new FormBuilderUser($utilities);
	$user->getById($db, $form->getVariable('createdByUserId'));

	if ($user)
	{
		$userCurrentPlan = $user->getVariable('userCurrentPlan');
	}

    $formStructure = json_decode($form->getVariable('formStructure'), true);

	if (isset($formStructure['switchActiveMode']) && (!$formStructure['switchActiveMode']))
	{
		$allowed = false;

		if (1 == $preview)
		{
			if (0 < strlen($timestamp))
			{
            	if ( ($timestamp > time() - 60 * 60 * 1) && ($timestamp < time() + 60 * 60 * 1) )
				{
					$allowed = true;
				}
			}
		}

		if (!$allowed)
		{
			if (0 < strlen($form->getVariable('formSetting_unavailableMessage')))
			{
				$unavailableMessage = html_entity_decode(base64_decode($form->getVariable('formSetting_unavailableMessage')), ENT_QUOTES);

				if (0 < strlen(trim($unavailableMessage)))
				{
					$unavailableMessageHeader = '';
					$unavailableMessageFooter = '';
					$title = $form->getVariable('formName');

					if (isset($formStructure['formHeader']))
					{
						$unavailableMessageHeader = html_entity_decode(base64_decode($formStructure['formHeader']), ENT_QUOTES);
					}

					if (isset($formStructure['formFooter']))
					{
						$unavailableMessageFooter = html_entity_decode(base64_decode($formStructure['formFooter']), ENT_QUOTES);
					}

					include_once (dirname(__FILE__) . '/unavailableMessage.php');
					exit(0);
				}
			}

	        header('Location: ' . $SITE_URL . '400');
			exit(0);
		}
	}

	if (0 < strlen($hash))
	{
		$sqlGetExistingDataRow = "SELECT * FROM `formBuilderFormEntries` WHERE `formBuilderFormEntryDataItem` = ? AND `formBuilderFormEntryDataValue` = ?";
		$rowResults = $db->runSelectQuery($sqlGetExistingDataRow, array('hash', $hash), false, null);

		if (1 == count($rowResults))
		{
    		$formEntry = new FormBuilderFormEntry($utilities);
			$formEntry->getById($db, $rowResults[0]['formBuilderFormEntryId']);

		    $postData = unserialize($formEntry->getVariable('postData'));
		    $formStructure = json_decode($formEntry->getVariable('formStructure'), true);

			// var_dump($postData);
		}
		else
		{
			header('Location: ' . $SITE_URL . '400');
			exit(0);
		}
	}

	if (0 == strlen($managementCompanyId))
	{
		if (0 < strlen($form->getVariable('streamrollClient')))
		{
			$managementCompanyId = $form->getVariable('streamrollClient');
		}
	}
}

if (0 < strlen($propertyId))
{
	require_once ($streamrollDir . '/php/configStreamrollDb.php');
	require_once ($streamrollDir . '/php/classes/StreamrollDb.php');

	$dbStreamroll = StreamrollDb::singleton();
	$dbStreamroll->setUtilities($utilities);

	$property = $dbStreamroll->itemById('Property', $propertyId, 'propertyId');

	if (0 == strcasecmp('new', $propertyVersion))
	{
		require_once ($streamrollDir . '/php/classes/Property_New.php');

		$property = new PropertyNew($utilities);
		$property->getProperty($db, $propertyId);
	}
}
else if (0 < strlen($managementCompanyId))
{
	require_once ($streamrollDir . '/php/configStreamrollDb.php');
	require_once ($streamrollDir . '/php/classes/StreamrollDb.php');

	$dbStreamroll = StreamrollDb::singleton();
	$dbStreamroll->setUtilities($utilities);

	$managementCompany = new ManagementCompany($utilities);
	$managementCompany->getManagementCompany($dbStreamroll, $managementCompanyId);
}

if (0 < strlen($userId))
{
	require_once ($streamrollDir . '/php/configStreamrollDb.php');
	require_once ($streamrollDir . '/php/classes/StreamrollDb.php');

	$dbStreamroll = StreamrollDb::singleton();
	$dbStreamroll->setUtilities($utilities);

	$user = $dbStreamroll->itemById('acl', $userId, 'userId');

    if ($user)
    {
	}
}

if (null == $formStructure)
{
    exit(0);
}
else if (0 == strlen($hash))
{
	$sqlGetExistingDataRow = "SELECT * FROM `formBuilderForms` WHERE `formBuilderFormDataItem` = ? AND `formBuilderFormId` = ?";
	$rowResults = $db->runSelectQuery($sqlGetExistingDataRow, array('viewCount', $formId), false, null);

	if (1 == count($rowResults))
	{
        $success = $db->updateField('formBuilderForms', 'formBuilderFormDataValue', intval($rowResults[0]['formBuilderFormDataValue']) + 1, $rowResults[0]['id'], 'id');
    }
}

?>

<!doctype html>
<html lang="en">
<head>
    <title><?php echo $formStructure['formName']; ?></title>

    <?php include_once('includes/head.php'); ?>

    <style>
		form
		{
			/* margin-bottom: 100px; */
		}

		footer
		{
			/* margin-bottom: 65px; */
		}

		.inputFieldContainer.hasHelperText,
		.inputFieldContainer:not(.hasHelperText) .select-wrapper
		{
			/* margin-bottom: 15px; */
		}

		.form-outline .form-notch .form-notch-middle
		{
			display: none;
		}
    </style>
</head>
<body class="" style="<?php if (1 == $embedMode) echo 'overflow: hidden;'; ?>" data-base="<?php echo $SITE_URL; ?>">

    <div class="container-fluid">
	<?php
		if (1 != $embedMode)
		{
	?>
        <div class="row mt-3 mb-3">
			<div class="col-12">
			<?php
				if (!isset($property))
				{
					if ( (isset($formStructure['formHeaderTemplate'])) && (0 < strlen($formStructure['formHeaderTemplate'])) )
					{
						$editMode = false;

						if (0 < count($formStructure['formHeaderTemplateData']))
						{
							include (dirname(__FILE__) . '/modules/formHeader/' . $formStructure['formHeaderTemplate'] . '.php');
						}
					}
					else if (isset($formStructure['formHeader']))
					{
						echo html_entity_decode(base64_decode($formStructure['formHeader']), ENT_QUOTES);
					}
				}
				else
				{
			?>
				<div class="d-sm-flex align-items-center">
					<div class="flex-shrink-0 text-center text-sm-start">
					<?php
						$propertyStyle = new PropertyStyle($utilities);
						$propertyStyle->getPropertyStyle($db, $property->propertyId());

						if (0 < strlen($propertyStyle->getVariable('propertyLogo')))
						{
							$propertyLogoUrl = $STREAMROLL_ASSETS_URL . '/images/property' . $property->propertyId() . '/imgs/' . $propertyStyle->getVariable('propertyLogo');
					?>
						<img src="https://assets.streamroll.info/managementCompanyLogos/managementCompany190/ARDinc290x110.png" alt="<?php echo $property->propertyName(); ?>">
					<?php
						}
						else
						{
					?>
						<p class="h4">
						<?php
							if (0 < strlen($property->propertyDomainName()))
							{
						?>
							<a class="text-dark" href="//<?php echo $property->propertyDomainName(); ?>" target="_blank">
						<?php
							}

							echo $property->propertyName();

							if (0 < strlen($property->propertyDomainName()))
							{
						?>
							</a>
						<?php
							}
						?>
						</p>
					<?php
						}
					?>
					</div>
					<div class="flex-grow-1 ms-3 text-center text-sm-end">
					<?php
						if (0 < strlen($propertyStyle->getVariable('propertyLogo')))
						{
					?>
						<p class="h4">
						<?php
							if (0 < strlen($property->propertyDomainName()))
							{
						?>
							<a class="text-dark" href="//<?php echo $property->propertyDomainName(); ?>" target="_blank">
						<?php
							}

							echo $property->propertyName();

							if (0 < strlen($property->propertyDomainName()))
							{
						?>
							</a>
						<?php
							}
						?>
						</p>
					<?php
						}
					?>

						<p class="h5"><?php echo $property->propertyStreetAddress() . '<br />' . $property->propertyCity() . ', ' . $property->propertyState() . ' ' . $property->propertyZip(); ?></p>

					<?php
						if (0 < strlen($property->propertyOfficePhone()))
						{
					?>
						<p class="h5"><?php echo $property->propertyOfficePhone(); ?></p>
					<?php
						}
					?>

					<?php
						if (0 < strlen($property->propertyContactEmail()))
						{
					?>
						<p class="h5"><a class="text-dark" href="mailto:<?php echo $property->propertyContactEmail(); ?>"><?php echo $property->propertyContactEmail(); ?></a></p>
					<?php
						}
					?>
					</div>
				</div>
			<?php
				}
			?>
        	</div>
        </div> <!-- row -->
	<?php
		}
	?>
    </div> <!-- container -->

	<?php
		$numInput = 0;
		$numInputFilled = 0;
	?>

	<?php
		if (1 != $embedMode)
		{
	?>
	<div class="scrollStatus sticky-top" data-mdb-scroll-status-init data-mdb-global="true" data-mdb-height="20px">
		<div class="scrollStatus-progress"></div>
	</div>
	<?php
		}
	?>

    <?php include_once('includes/widget_form.php'); ?>

<?php
	if (0 == strcasecmp('on', $form->getVariable('formSetting_enableCaptcha')))
	{
?>
    <div class="container-fluid mb-3">
    	<div class="row mt-3 align-items-center">
			<div class="col">
				<div class="g-recaptcha" id="captcha" data-sitekey="6Ld-wlEfAAAAAFeaA7oxW_ATtIkrPWG7eR9HI8s6"></div>
			</div>
    	</div>
    </div> <!-- container -->
<?php
    }
?>

<?php
	if (1 != $embedMode)
	{
?>
    <div class="container-fluid" style="margin-bottom: 100px;">
        <div class="row">
			<div class="col-12">
			<?php
				if ( (isset($formStructure['formFooterTemplate'])) && (0 < strlen($formStructure['formFooterTemplate'])) )
				{
					$editMode = false;

					if (0 < count($formStructure['formFooterTemplateData']))
					{
						include (dirname(__FILE__) . '/modules/formFooter/' . $formStructure['formFooterTemplate'] . '.php');
					}
				}
				else if (isset($formStructure['formFooter']))
				{
					echo html_entity_decode(base64_decode($formStructure['formFooter']), ENT_QUOTES);
				}
			?>
			</div>
        </div> <!-- row -->
    </div> <!-- container -->
<?php
	}
?>

<?php
	$className = 'mt-3';
	$textClass = '';

	if ( (0 == strcasecmp('on', $form->getVariable('formSetting_submitButtonAlwaysVisible'))) && (1 != $embedMode) )
	{
		$className = 'fixed-bottom bg-dark ms-0 me-0 pt-1 pb-2';
		$textClass = 'text-white';
	}
?>

    <div class="row <?php echo $className; ?>">
	<?php
		if (0 == strcasecmp('on', $form->getVariable('formSetting_showFieldsRemaining')))
		{
	?>
		<div class="col-12 col-sm <?php echo $textClass; ?> mb-3 mb-sm-0 text-center text-sm-start align-self-center">
			<span id="numInputFilled"><?php echo $numInputFilled; ?></span> / <span id="numInputFields"><?php echo $numInput; ?></span>
			<span id="percentFilledIn"></span>
		</div>
    <?php
        }
    ?>

        <div class="col-12 col-sm text-center mb-3 mb-sm-0 ">
	<?php
		if (0 == strcasecmp('on', $form->getVariable('formSetting_allowSaveAndContinue')))
		{
	?>
            <button type="button" class="btn btn-success btn-rounded" id="btnSaveContinue" data-mdb-toggle="modal" data-mdb-target="#modalSubmitLater" <?php if (1 == $form->getVariable('templateMode')) echo 'disabled'; ?>>Save & Continue Later</button>
    <?php
        }
    ?>

	<?php
		if (0 < $numInput)
		{
	?>
            <button type="submit" class="btn btn-primary btn-rounded" id="btnSubmitForm" <?php if (1 == $form->getVariable('templateMode')) echo 'disabled'; ?>>Submit</button>
	<?php
		}
	?>
        </div>

	<?php
		if (0 == strcasecmp('on', $form->getVariable('formSetting_showFieldsRemaining')))
		{
	?>
        <div class="col-12 col-sm text-center mb-3 mb-sm-0 "></div>
    <?php
        }
    ?>
    </div>

    <div class="modal fade" id="formSubmitLoadingModal" tabindex="-1" aria-labelledby="formSubmitLoadingModalLabel" aria-hidden="true" data-mdb-backdrop="static" data-mdb-keyboard="false" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered modal-fullscreen">
            <div class="modal-content">
				<div class="modal-header">
					<h5 class="modal-title">Please Wait</h5>
				</div>
                <div class="modal-body text-center">
                    <p class="lead">We are Submitting your entry.</p>
					<p>This dialog will automatically close once the process is completed.</p>
                    <div class="spinner-border" role="status">
                        <span class="visually-hidden">Submitting ... Please Wait</span>
                    </div>
                </div>
				<div class="modal-footer">
                </div>
            </div>
        </div>
    </div>

	<div class="modal fade" id="modalSubmitLater" tabindex="-1" aria-labelledby="modalSubmitLaterLabel" aria-hidden="true">
		<div class="modal-dialog">
			<div class="modal-content">
				<div class="modal-header">
					<h5 class="modal-title" id="modalSubmitLaterLabel">Contact Info</h5>
					<button type="button" class="btn-close" data-mdb-dismiss="modal" aria-label="Close"></button>
				</div>
				<div class="modal-body">
					<p class="fw-bold">Please enter your name</p>
					<div class="form-outline mb-3">
						<input type="text" class="form-control" name="inputSaveName" value="<?php if (isset($formEntry)) echo $formEntry->getVariable('inputSaveName'); ?>" autocomplete="inputSaveName" />
						<label class="form-label text-wrap">Your Name</label>
					</div>
					<p>and <span class="fw-bold">either an email address or a mobile number</span> in order for us to send you a link to continue filling out the form at a later time.</p>
					<div class="form-outline mb-3">
						<input type="email" class="form-control" name="inputSaveEmail" value="<?php if (isset($formEntry)) echo $formEntry->getVariable('inputSaveEmail'); ?>" autocomplete="inputSaveEmail" />
						<label class="form-label text-wrap">Your Email Address</label>
					</div>
					<p class="text-center fw-bold">or</p>
					<div class="form-outline mb-3">
						<input type="tel" class="form-control" name="inputSavePhone" value="<?php if (isset($formEntry)) echo $formEntry->getVariable('inputSavePhone'); ?>" autocomplete="inputSavePhone" />
						<label class="form-label text-wrap">Your Phone Number</label>
					</div>
				</div>
				<div class="modal-footer">
					<button type="button" class="btn btn-secondary btn-rounded" data-mdb-dismiss="modal">Cancel</button>
					<button type="button" class="btn btn-primary btn-rounded" id="btnSendandSubmit">Send & Save</button>
				</div>
			</div>
		</div>
	</div>

    <?php
		if (1 != $embedMode)
		{
			include_once('includes/footer.php');
		}
	?>

	<div class="container-fluid">
		<div class="row mb-3 d-print-none">
			<div class="col-12 col-sm text-sm-end">
				<div id="google_translate_element"></div>
			</div>
		</div>
	</div>

    <?php include_once('includes/script.php'); ?>
    <?php include_once('includes/analytics.php'); ?>

<?php
	if (0 == strcasecmp('on', $form->getVariable('formSetting_enableCaptcha')))
	{
?>
	<script type="text/javascript" src="https://www.google.com/recaptcha/api.js" async defer></script>
<?php
    }
?>

<?php
	if (1 == $embedMode)
	{
?>
	<script type="text/javascript" src="<?php echo $SITE_URL; ?>js/iframeResizeMessage.js?ts=<?php echo $utilities->fileModTime(dirname(__FILE__) . '/js/iframeResizeMessage.js'); ?>"></script>
<?php
    }
?>

	<script type="text/javascript" src="<?php echo $SITE_URL; ?>js/jSignature/jSignature.min.js?ts=<?php echo $utilities->fileModTime(dirname(__FILE__) . '/js/jSignature/jSignature.min.js'); ?>"></script>
	<script type="text/javascript" src="<?php echo $SITE_URL; ?>js/webforms.js?ts=<?php echo $utilities->fileModTime(dirname(__FILE__) . '/js/webforms.js'); ?>"></script>

    <script type="text/javascript">
        document.addEventListener('DOMContentLoaded', function()
        {
		<?php
			if (1 == $testMode)
			{
		?>
            $('input, textarea', 'form').each(function()
            {
                var element = $(this);

				if ('hidden' != $(this).attr('type'))
				{
					if ( ('radio' != $(this).attr('type')) && ('checkbox' != $(this).attr('type')) )
					{
						if ('currency' == $(this).attr('data-type'))
						{
							element.val(Math.ceil((Math.random() * (100.00 - 1.00 + 1.00) + 1.00).toFixed(2)));
						}
						else if ('date' == $(this).attr('data-type'))
						{
							element.val('<?php echo date('m/d/Y'); ?>');
						}
						else if ('file' != $(this).attr('type'))
						{
	                		element.val(element.attr('id'));
						}
					}
					else if ('textarea' != $(this).attr('type'))
					{
						var items = $('input[name="' + element.attr('name') + '"]');
						var randomIndex = Math.floor(Math.random() * items.length);

						if (!$(items[randomIndex]).prop('checked'))
						{
							$(items[randomIndex]).prop('checked', true);
						}
					}
				}
            });

            $('select', 'form').each(function()
            {
                var element = $(this);
				var options = $(element).find('option[value != ""]');
				var randomIndex = Math.floor(Math.random() * options.length);

				$(options[randomIndex]).prop('selected', true);

				var instance = mdb.Select.getInstance($(this)[0]);
					instance.setValue(randomIndex);
            });
		<?php
			}
		?>

			if (0 < $('[name="latlng"]').length)
			{
				if (navigator.geolocation)
				{
					navigator.geolocation.getCurrentPosition(function(position)
					{
						$('[name="latlng"]').val(position.coords.latitude + ':' + position.coords.longitude);
					});
				}
			}

    		formSubmitLoadingModal = mdb.Modal.getInstance($('#formSubmitLoadingModal')[0]);

    		if (!formSubmitLoadingModal)
    		{
        		formSubmitLoadingModal = new mdb.Modal($('#formSubmitLoadingModal')[0]);
    		}

			$('#formSubmitLoadingModal').on('shown.mdb.modal', function(e)
			{
				$('form').submit();
			});

			$('.signature').jSignature();
			$('.signature').parent().append('<button type="button" class="btn btn-danger btn-sm btnClearSignature mb-3 btn-rounded">Clear Signature</button>');

			$('.btnClearSignature').on('click', function(e)
			{
				$('.signature', $(this).parent()).jSignature('reset');
			});

			$('#modalSubmitLater').on('shown.mdb.modal', function(e)
			{
			});

			$('#modalSubmitLater .btn-primary').on('click', function(e)
			{
				if (0 < $('input[name="inputSaveEmail"]', '#modalSubmitLater').val().length + $('input[name="inputSavePhone"]', '#modalSubmitLater').val().length)
				{
					if (0 < $('#captcha').length)
					{
						e.preventDefault();

						if (0 == grecaptcha.getResponse().length)
						{
							displayModalMessage('Oops', 'You forgot to check the Captcha box.');

							$('#captcha > div').addClass('border');
							$('#captcha > div').addClass('border-danger');

							$([document.documentElement, document.body]).animate(
							{
								scrollTop: $('#captcha').offset().top
							}, 100);

							var modal = mdb.Modal.getInstance(document.getElementById('modalSubmitLater'));
							modal.hide();

							return false;
						}
						else
						{
							$('#captcha > div').removeClass('border-danger');
						}
					}

					$.each($('#modalSubmitLater .form-control'), function()
					{
						$('form').append($(this).clone());
					});

					$('.required', 'form').removeClass('required');
					$('.signature', 'form').removeClass('signature');

					$('#btnSubmitForm').click();
				}
				else
				{
					if (0 == $('input[name="inputSaveEmail"]', '#modalSubmitLater').val().length)
					{
						$('input[name="inputSaveEmail"]', '#modalSubmitLater').parent().addClass('has-error');
					}

					if (0 == $('input[name="inputSavePhone"]', '#modalSubmitLater').val().length)
					{
						$('input[name="inputSavePhone"]', '#modalSubmitLater').parent().addClass('has-error');
					}
				}
			});

			$('#btnSubmitForm').on('click', function(e)
			{
    			var button = $(this);
				button.html('<div class="spinner-border" role="status"><span class="visually-hidden">Submitting...</span></div>');

				$(this).prop('disabled', true);
				e.preventDefault();

		    	var success = false;
				var errorMessage = '';

		    	$('.has-error', 'form').removeClass('has-error');

				if (0 < $('.signature').length)
				{
			    	$.each($('.signature', 'form'), function()
			    	{
                    	if ($(this).is(':visible'))
						{
							if (0 < $('.required-icon', $(this).parent()).length)
							{
								var signatureImage = $(this).jSignature('getData', 'base30');

								if (2 == signatureImage.length)
								{
									if (0 == signatureImage[1].length)
									{
										$(this).addClass('border');
										$(this).addClass('border-danger');
										$(this).addClass('has-error');
									}
									else
									{
										$(this).removeClass('border');
										$(this).removeClass('border-danger');
										$(this).removeClass('has-error');
									}
								}
							}
						}
		    		});

					if (0 < $('.signature.has-error', 'form').length)
					{
						errorMessage += '<a href="#' + $(this).attr('id') + '">Please make sure to sign the form.</a><br/>';
					}
				}

		    	$.each($('.required', 'form'), function()
		    	{
					if (!$(this).hasClass('file-upload-input'))
					{
                    	if ($(this).is(':visible'))
						{
							if ( ('radio' != $(this).attr('type')) && ('checkbox' != $(this).attr('type')) )
							{
		    					if (0 == $(this).val().length)
		    					{
		    						$(this).parent().addClass('has-error');

									errorMessage += '<a href="#' + $(this).attr('id') + '">' + $('.form-label', $(this).parent()).text() + '</a><br/>';
								}
							}
							else
							{
								if (0 == $('input.form-check-input:checked', $(this).parents('.inputFieldContainer')).length)
								{
									if (-1 == errorMessage.indexOf('"#' + $(this).attr('name') + '"'))
									{
										if (!$(this).parents('.inputFieldContainer').hasClass('has-error'))
										{
											$(this).parents('.inputFieldContainer').addClass('has-error');

											errorMessage += '<a href="#' + $(this).attr('id') + '">' + $('.form-label', $(this).parents('.inputFieldContainer')).text() + '</a><br/>';
										}
									}
								}
							}
		    			}
						else if ($(this).hasClass('select'))
						{
							if ($(this).parents('.select-wrapper').is(':visible'))
							{
    							if (0 == $(this).val().length)
    							{
    								$('.form-outline', $(this).parent()).addClass('has-error');

									errorMessage += '<a href="#' + $(this).attr('id') + '">' + $('.select-label', $(this).parent()).text() + '</a><br/>';
								}
							}
						}
					}
					else
					{
						if (0 == $('.file-upload-preview', $(this).parent()).length)
						{
                        	if ($(this).is(':visible'))
							{
								if (0 == $('.uploadedFiles', $(this).parents('form')).length)
								{
		    						$(this).parent().addClass('has-error');

									errorMessage += '<a href="#' + $(this).attr('id') + '">' + $('h6.text-muted', $(this).parents('.inputFieldContainer')).text() + '</a><br/>';
								}
							}
						}
					}
		    	});

		    	$.each($('.requiredOne', 'form'), function()
		    	{
					if (!$(this).hasClass('file-upload-input'))
					{
                    	if ($(this).is(':visible'))
						{
							if ( ('radio' != $(this).attr('type')) && ('checkbox' != $(this).attr('type')) )
							{
							}
							else
							{
								if (0 == $('input.form-check-input:checked', $(this).parents('section.row')).length)
								{
									if (1 == $('h2', $(this).parents('section.row')).length)
									{
										if (!$(this).parents('section.row').hasClass('has-error'))
										{
											$(this).parents('section.row').addClass('has-error');

											errorMessage += $('h2', $(this).parents('section.row')).text() + '<br/>';
										}
									}
									else if (-1 == errorMessage.indexOf('"#' + $(this).attr('name') + '"'))
									{
										if (!$(this).parents('.inputFieldContainer').hasClass('has-error'))
										{
											$(this).parents('.inputFieldContainer').addClass('has-error');

											errorMessage += '<a href="#' + $(this).attr('id') + '">' + $('.form-label', $(this).parents('.inputFieldContainer')).text() + '</a><br/>';
										}
									}
								}
							}
						}
					}
		    	});

		    	if (0 == $('.has-error', 'form').length)
		    	{
					if (0 < $('#captcha').length)
					{
						if (0 == grecaptcha.getResponse().length)
						{
							displayModalMessage('Oops', 'You forgot to check the Captcha box.');

							$('#captcha > div').addClass('border');
							$('#captcha > div').addClass('border-danger');

							document.getElementById('captcha').scrollIntoView(true);

							button.html('Submit');
							$(this).prop('disabled', false);

							return false;
						}
						else
						{
							$('#captcha > div').removeClass('border-danger');
						}
					}

					formSubmitLoadingModal.show();
		    		success = true;

			    	$.each($('.signature', 'form'), function()
			    	{
						$('input[name="' + $(this).attr('id') + '"]').val($(this).jSignature('getData', 'image'));
			    	});

					$('input[name="inputSaveName"]', '#modalSubmitLater').val('');
					$('input[name="inputSaveEmail"]', '#modalSubmitLater').val('');
					$('input[name="inputSavePhone"]', '#modalSubmitLater').val('');

	                $('input, select, textarea', 'form').each(function()
	                {
	                    var element = $(this);

						if (element.hasClass('select'))
						{
							if (1 < element.val().length)
							{
								var temp = element.val();

								if (Array.isArray(temp))
								{
	    							element.find(":selected").val(Base64.encode(temp.join(', ')));
								}
								else
								{
									element.find(":selected").val(Base64.encode(element.find(":selected").val()));
								}
							}
							else if (0 < element.find(":selected").length)
							{
								element.find(":selected").val(Base64.encode(element.find(":selected").val()));
							}
							else
							{
    							element.val(Base64.encode(''));
							}
						}
						else if (!element.hasClass('file-upload-input'))
						{
	                    	element.val(Base64.encode(element.val()));
						}
	                });
		    	}
				else
				{
					displayModalMessage('Missing Required Information', errorMessage.replaceAll('*</a>', '</a>'));

					($('.has-error')[0]).scrollIntoView(
					{
						block: 'end',
						inline: 'nearest',
						behavior: 'smooth',
					});
				}

				if (!success)
				{
					button.html('Submit');
					$(this).prop('disabled', false);
				}

				return success;
			});

			$('.btnDeleteFile').on('click', function(e)
			{
    			var button = $(this);

				var params = {};
					params.id = $(button).attr('data-id');
					params.file = $(button).attr('data-file');

				xhr = $.ajax(
				{
					type: 'POST',
					url: $('body').attr('data-base') + 'php/deleteFormEntryAssets.php',
					data: params,
					dataType: 'json',
					context: document.body,
					success: function(response)
					{
						if (1 == response.success)
						{
                            button.parent().remove();
                        }
					},
					error: function(xhr, type)
					{
					}
				});
			});
        });

		function googleTranslateElementInit()
		{
			new google.translate.TranslateElement({pageLanguage: 'en'}, 'google_translate_element');

			window.setTimeout(function()
			{
				if (0 < $('#google_translate_element').length)
				{
					var queryString = window.location.search;
					var urlParams = new URLSearchParams(queryString);
					var targetLanguage = urlParams.get('tl');

					if (targetLanguage && (0 < targetLanguage.length))
					{
						if (0 < $('.goog-te-combo').length)
						{
							$('select.goog-te-combo option[value="' + targetLanguage + '"]', '#google_translate_element').prop('selected', true);
							$('select.goog-te-combo', '#google_translate_element').val(targetLanguage).change();

							triggerHtmlEvent($('.goog-te-combo')[0], 'change');
						}
					}
				}
			}, 2500);
		}
    </script>

	<script type="text/javascript" src="https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

</body>
</html>

<?php

ob_end_flush();

?>
