<?php
//error_reporting(E_ALL);
//ini_set('display_errors', 1);

	/***********************************************************************************
	*   Filename    : index.php
	*   Description : Petsafe Index/Home page
	*
	*   Date        Modification By      Description
	*   20/10/2008  Shane Schokman       Initial Creation
	*   23/01/2009  Kenneth Ho           Adaptation to Digivet-Petsafe
	*   28/08/2015  Jaime Aramburo       Change functionality of multiple regos. BEFORE: Owner details had to be entered every time for multiple regos. NOW: Multiple regos are associated to one owner until that transaction is finished.
   	*
	*   Copyright Keysoft Pty Ltd 2009
	***********************************************************************************/
	


	/******************** Global Settings ********************/
	require_once '../phpobjects/common/global.php';

	/********************* Page Settings *********************/
	$gaPage['title'] = 'Petsafe.com.au';
	$gaPage['root_directory'] = '..';
	
	/********************* Page Defaults *********************/
    fDefaultParameter('type', $_GET, '');
    fDefaultParameter('v', $_GET, $_SESSION['VetID']);
	
	fDefaultParameter('err_code', $_GET, '');
	$err_code = $_GET['err_code'];
    
    $rego_type = $_GET['type'] == 'breeder' ? 'breeder' : 'owner';
    $v = $_GET['v'];
    

	// default values
	if (empty($_POST['owner_state'])) {
		$selected_state = '';
	} else {
		$selected_state = $_POST['owner_state'];
	}
	if (empty($_POST['owner_suburb'])) {
		$selected_suburb = '';
	} else {
		$selected_suburb = $_POST['owner_suburb'];
	}
	if (empty($_POST['owner_postcode'])) {
		$selected_postcode = '';
	} else {
		$selected_postcode = $_POST['owner_postcode'];
	}
	if (empty($_POST['pet_state'])) {
		$selected_petstate = '';
	} else {
		$selected_petstate = $_POST['pet_state'];
	}
	if (empty($_POST['pet_suburb'])) {
		$selected_petsuburb = '';
	} else {
		$selected_petsuburb = $_POST['pet_suburb'];
	}
	if (empty($_POST['pet_postcode'])) {
		$selected_petpostcode = '';
	} else {
		$selected_petpostcode = $_POST['pet_postcode'];
	}
	if (empty($_POST['mail_state'])) {
		$selected_mailstate = '';
	} else {
		$selected_mailstate = $_POST['mail_state'];
	}
	if (empty($_POST['mail_suburb'])) {
		$selected_mailsuburb = '';
	} else {
		$selected_mailsuburb = $_POST['mail_suburb'];
	}
	if (empty($_POST['mail_postcode'])) {
		$selected_mailpostcode = '';
	} else {
		$selected_mailpostcode = $_POST['mail_postcode'];
	}

	$fm = \Keysoft\FileMaker\Client::getInstance();			// * Init
	
	// check if cookie id is in session - if yes, and if exists in the FM system, then check its unpaid!
	// else init cookie id in session
	if ($_SESSION['cookieid'] != ''){
		$odataQuery = $fm->buildODataQuery([
			'filter' => "cookie_transaction_id eq '".$_SESSION['cookieid']."'",
			'select' => ['content'],
			'count' => true
		]);
		$fmrTransaction = $fm->get('Web_Payments', $odataQuery ,$allPages = true );
		// $aRequest = array();
		// $aRequest['cookie_transaction_id'] = '="' . $_SESSION['cookieid'] . '"';
		// $fmrTransaction = fFMPerformFind('petsafe', 'All Fields - Web_Payments', $aRequest);
		if (!$fmrTransaction["success"] || $fmrTransaction["data"]["count"] < 1){
			$_SESSION['cookieid'] = '';
			//echo 'trans not found';
		}
		else {
			$fmcTransaction = $fmrTransaction["data"]["value"][0];
			if (trim(fReformatDate($fmcTransaction['transaction_finish'])) != ''){
				$_SESSION['cookieid'] = '';
				//echo 'cookie removed';
			}
		}
	}

	// check email - ajax call
	if (isset($_GET['ajax_check_email'])) {
		$email_error = '';
		if ( empty($_GET['email']) or $_GET['email'] == '' ) {
			$email_error = '<span style="color:red">Email address is empty!</span>';
		} else {
			$odataQuery = $fm->buildODataQuery([
				'filter' => "Email eq '".$_GET['email']."'",
				'select' => ['content'],
				'count' => true
			]);
			$fmrEmail = $fm->get('Owners', $odataQuery ,$allPages = true );
			$fmcEmail = $fmrEmail["data"]["value"];
			$countOwnerEmails = count($fmcEmail);
			$validCount = 0; // email being updated - there should be no other email like the updated value
			if ($countOwnerEmails > $validCount){
				$email_error = '<span style="color:red">An owner with this email address already exists on our records!<br/>Please enter a valid and unique email address OR <a href="memberlogin.php">login</a> with this email address and then register a pet.</span>';
			}
		}
		echo $email_error;
		die;
	}

	// check tag - ajax call
	if (isset($_GET['ajax_check_tag'])) {
		$tag_error = '';
		if ( empty($_GET['tag']) or $_GET['tag'] == '' ) {
			$tag_error = '<span style="color:red">Petsafe Tag is empty!</span>';
		} else {
			// $aRequest = array();
			// $aRequest['Tag'] = '="' . $_GET['tag'] . '"'; 
			// $fmrTag = fFMPerformFind('petsafe', 'Web - Pets', $aRequest);


			$odataQuery = $fm->buildODataQuery([
				'filter' => "Tag eq '".$_GET['tag']."'",
				'select' => ['content'],
				'count' => true
			]);
			$fmrTag = $fm->get('Pets', $odataQuery ,$allPages = true );
			if (!$fmrTag["success"] || $fmrTag["data"]["count"] < 1){
				//do nothing
			} else {
				$tag_error = '<span style="color:red">This Tag number is already attached to a Pet on our database!<br/>Please enter a unique Tag number for this pet registration.</span>';
			}
		}
		echo $tag_error; 
		die;
	}

	// check chip - ajax call from ?
	if (isset($_GET['ajax_check_chip'])) {
		$chip_error = '';
		if ( empty($_GET['chip']) or $_GET['chip'] == '' ) {
			$chip_error = '<span style="color:red">Microchip is empty!</span>';
		} else {
			$odataQuery = $fm->buildODataQuery([
				'filter' => "Chip No eq '".$_GET['chip']."'",
				'select' => ['content'],
				'count' => true
			]);
			$fmrChip = $fm->get('Pets', $odataQuery ,$allPages = true );
			// $aRequest = array();
			// $aRequest['Chip No'] = '="' . $_GET['chip'] . '"';

			// $fmrChip = fFMPerformFind('petsafe', 'Web - Chips', $aRequest, null, null, FALSE);
			if (!$fmrChip["success"] || $fmrChip["data"]["count"] < 1){
				// no duplicates
				$chip_error = '';
			} else {
				// POSSIBLE duplicate found
				$fmcChip = $fmrChip["data"]["value"];
				$duplicate = 0;
				foreach ($fmcChip as $chip){
					$petid = $chip['_sk_pet_id'];
					if (trim($petid) != ''){
						$duplicate = 1;
						break;
					}
				}
				if ($duplicate == 1){
					// duplicate found - confirmed
					$chip_error = '<span style="color:red">This Chip number is already attached to a Pet on our database!<br/>Please enter a unique Microchip number for this pet registration.</span>';
				}
			}
			//$chip_error .= $_SESSION['cookieid'];
			//look for chip number in current transaction (FOR MULTIPLE REGOS)
			if ($_SESSION['cookieid'] != '' and $chip_error == ''){
				// $aRequest = array();
				// $aRequest['microchip_no'] = '="' . $_GET['chip'] . '"';
				// $aRequest['cookie_transaction_id'] = '="' . $_SESSION['cookieid'] . '"';
				// $fmrChip = fFMPerformFind('petsafe', 'All Fields - Web_Payments', $aRequest);
				
				$odataQuery = $fm->buildODataQuery([
					'filter' => "microchip_no eq '".$_GET['chip']."' and cookie_transaction_id eq '".$_SESSION['cookieid']."'",
					'select' => ['content'],
					'count' => true
				]);
				$fmrChip = $fm->get('Web_Payments', $odataQuery ,$allPages = true );

				if (!$fmrChip["success"] || $fmrChip["data"]["count"] < 1){
					//not found in current transaction
				} else {
					$chip_error = '<span style="color:red">This Chip number is being used in the current transaction!<br/>Please enter a unique Microchip number for this pet registration.</span>';
				}
			}
		}
		echo $chip_error;
		die;
	}

	// check clinic no - ajax call
	if (isset($_GET['ajax_check_clinic_no'])) {
		$clinic_no_error = '';
		if ( empty($_GET['clinic_no']) or $_GET['clinic_no'] == '' ) {
			$clinic_no_error = '';
		} else {
			// $aRequest = array();
			// $aRequest['myob_account_no'] = '="' . $_GET['clinic_no'] . '"';
			// $aRequest['dont_show_on_web'] = '=';			// ?? what

			// $fmrCompany = fFMPerformFind('petsafe', 'Web - Companies', $aRequest);
        

			$odataQuery = $fm->buildODataQuery([
				'filter' => "myob_account_no eq '".$_GET['clinic_no']."'",
				'select' => ['content'],
				'count' => true
			]);
			$fmrCompany = $fm->get('Companies', $odataQuery ,$allPages = true );
		
			if (!$fmrCompany["success"] || $fmrCompany["data"]["count"] <= 0){
				// not found
				$clinic_no_error = '<input type="hidden" name="clinic_no" value="" /><span style="color:red">The clinic was not found.  Please ensure you have entered a valid Clinic ID.</span>';
			} else {
				$fmcCompany = $fmrCompany["data"]["value"][0];
				$clinic_no_error = '<input type="hidden" name="clinic_no" value="'.$fmcCompany['_pk_company_id'].'" />'. $fmcCompany['myob_account_no'] . ': ' . $fmcCompany['Company Name'];
			}
		}
		echo $clinic_no_error;
		die;
	}
	
	// get vets associated with a clinic - ajax call (logged in user must be main vet of the clinic selected)
	if (isset($_GET['ajax_get_clinic_vets'])) {
		$clinic_vets = '';
		if ( empty($_GET['clinic_no']) or $_GET['clinic_no'] == '' ) {
			$clinic_vets = '';
		} else {
			// $aRequest = array();
			// $aRequest['_sk_vet_id'] = $_SESSION['VetID'];
			// $aRequest['_sk_company_id'] = $_GET['clinic_no'];
			// $aRequest['vet_main_contact'] = "Yes";

			// $fmrVetMain = fFMPerformFind('petsafe', 'All Fields - Company_Vet_Relation', $aRequest);

			$odataQuery = $fm->buildODataQuery([
				'filter' => "_sk_vet_id eq ".$_SESSION['VetID']." and _sk_company_id eq ".$_GET['clinic_no']." and vet_main_contact eq 'Yes'",
				'select' => ['content'],
				'count' => true
			]);
			$fmrVetMain = $fm->get('Company_Vet_Relation', $odataQuery ,$allPages = true );

			if (!$fmrVetMain["success"] || $fmrVetMain["data"]["count"] <= 0){
				// not found
				$clinic_vets = '';
			} else {
				//$fmcVetMain = $fmrVetMain->getFirstRecord();
				//$clinic_no_error = '<input type="hidden" name="clinic_no" value="'.$fmcCompany->getField('_pk_company_id').'" />'. $fmcCompany->getField('myob_account_no') . ': ' . $fmcCompany->getField('Company Name');
				// Get list of all vets
				
				// $aRequest = array();
				// $aRequest['_sk_company_id'] = $_GET['clinic_no'];
	
				// $fmrVets = fFMPerformFind('petsafe', 'All Fields - Company_Vet_Relation', $aRequest);
			
				$odataQuery = $fm->buildODataQuery([
					'filter' => "_sk_company_id eq ".$_GET['clinic_no']."",		// ? Does this need to be string
					'select' => ['content'],
					'count' => true
				]);
				$fmrVets = $fm->get('Company_Vet_Relation', $odataQuery ,$allPages = true );

				if (!$fmrVets["success"] || $fmrVets["data"]["count"] <= 0){
					$clinic_vets = '';
				}else{
					$fmcVets = $fmrVets["data"]["value"];
					
					$vet_selected = '';
					
					foreach ($fmcVets as $vetRecord){
						// Selected vet defaults to logged in vet.
						$vet_selected = $vetRecord['_sk_vet_id'] == $_SESSION['VetID'] ? 'selected' : '';
						
						$clinic_vets .= '<option value="' . $vetRecord['_sk_vet_id'] . '" ' . $vet_selected . '>' . $vetRecord['vet_name_c'] . '</option>';
					}
					
					$clinic_vets = '<select name="implanting_vet" style="width:180px;">' . $clinic_vets . '</select>';
				}

			}
		}
		echo $clinic_vets;
		die;
	}

	// fill suburbs
	if (isset($_GET['hello_from_ajax1'])) {
		if ( empty($_GET['owner_state']) ) {
			$suburb_popup = '<select name="owner_suburb" disabled="disabled"></select>';
		} else {
			$suburbs = getSuburbs($_GET['owner_state']);
			$suburb_popup = popup($suburbs, 'owner_suburb', $selected_suburb,'onchange="setPostcodeValueList()"');
		}
		echo $suburb_popup;
		die;
	}

	// fill postcodes 
	if (isset($_GET['hello_from_ajax2'])) {
		if ( empty($_GET['owner_suburb']) ) {
			$postcode_popup = '<select name="owner_postcode" disabled="disabled"></select>';
		} else {
			$postcodes = getPostCodes($_GET['owner_state'], $_GET['owner_suburb']);
			if (count($postcodes) == 1){
				$selected_postcode = $postcodes[0];
			}
			$postcode_popup = popup($postcodes, 'owner_postcode', $selected_postcode);
		}
		echo $postcode_popup;
		die;
	}

	// fill suburbs - pets
	if (isset($_GET['hello_from_ajax1p'])) {
		if ( empty($_GET['pet_state']) ) {
			$petsuburb_popup = '<select name="pet_suburb" disabled="disabled"></select>';
		} else {
			$suburbs = getSuburbs($_GET['pet_state']);
			$petsuburb_popup = popup($suburbs, 'pet_suburb', $selected_petsuburb,'onchange="setPostcodeValueListPet()"');
		}
		echo $petsuburb_popup;
		die;
	}

	// fill postcodes - pets
	if (isset($_GET['hello_from_ajax2p'])) {
		if ( empty($_GET['pet_suburb']) ) {
			$petpostcode_popup = '<select name="pet_postcode" disabled="disabled"></select>';
		} else {
            $postcodes = getPostCodes($_GET['pet_state'], $_GET['pet_suburb']);
            if (count($postcodes) == 1){
				$selected_mailpostcode = $postcodes[0];
			}

			$petpostcode_popup = popup($postcodes, 'pet_postcode', $selected_petpostcode);
		}
		echo $petpostcode_popup;
		die;
	}

	// fill suburbs - mailing
	if (isset($_GET['hello_from_ajax1m'])) {
		if ( empty($_GET['mail_state']) ) {
			$mailsuburb_popup = '<select name="mail_suburb" disabled="disabled"></select>';
		} else {
			$suburbs = getSuburbs($_GET['mail_state']);
			$mailsuburb_popup = popup($suburbs, 'mail_suburb', $selected_mailsuburb,'onchange="setPostcodeValueListMail()"');
		}
		echo $mailsuburb_popup;
		die;
	}

	// fill postcodes - mailing
	if (isset($_GET['hello_from_ajax2m'])) {
		if ( empty($_GET['mail_suburb']) ) {
			$mailpostcode_popup = '<select name="mail_postcode" disabled="disabled"></select>';
		} else {
            $postcodes = getPostCodes($_GET['mail_state'], $_GET['mail_suburb']);
            if (count($postcodes) == 1){
				$selected_mailpostcode = $postcodes[0];
			}
			$mailpostcode_popup = popup($postcodes, 'mail_postcode', $selected_mailpostcode);
		}
		echo $mailpostcode_popup;
		die;
	}

	// retrieve states
    $states = ["ACT","NSW","NT","QLD","SA","TAS","WA","VIC"];

	// initialise lists on first load
	$state_popup = popup($states, 'owner_state', $selected_state,'onchange="setTypeValueList()"');
	$suburb_popup = '<div id="suburb_container"><select name="owner_suburb" disabled="disabled"></select></div>';
	$postcode_popup = '<div id="postcode_container"><select name="owner_postcode" disabled="disabled"></select></div>';
	$petstate_popup = popup($states, 'pet_state', $selected_petstate,'onchange="setTypeValueListPet()"');
	$petsuburb_popup = '<div id="petsuburb_container"><select name="pet_suburb" disabled="disabled"></select></div>';
	$petpostcode_popup = '<div id="petpostcode_container"><select name="pet_postcode" disabled="disabled"></select></div>';
	$mailstate_popup = popup($states, 'mail_state', $selected_mailstate,'onchange="setTypeValueListMail()"');
	$mailsuburb_popup = '<div id="mailsuburb_container"><select name="mail_suburb" disabled="disabled"></select></div>';
	$mailpostcode_popup = '<div id="mailpostcode_container"><select name="mail_postcode" disabled="disabled"></select></div>';

	// function to create select list dynamically
	// function popup($values, $name, $selected_value = '', $extras = '') {
	// 	$popup = '<select name="' . $name . '" ' . $extras . '>';
	// 	$popup.= '<option value="">- Please select -</option>';
	// 	foreach($values as $value) {
	// 		if ($value == $selected_value) {
	// 			$selected = 'selected="selected"';
	// 		} else {
	// 			$selected = '';
	// 		}
	// 		$popup.= '<option value="' . $value . '" ' . $selected . '>' . $value . '</option>';
	// 	}
	// 	$popup.= '</select>';
	// 	return $popup;
	// }
	
	//
    if($_SESSION['cookieid'] == ''){
        $_SESSION['rego_type'] = $rego_type;
    }
    
    if($_SESSION['VetID'] == '' && strtolower($_SESSION['rego_type']) == 'breeder'){
        $_SESSION['rego_type'] = 'owner';
    }
	
	// we need to "group" first registration by vet, since the main vet has the ability to select different vets from dropdown list.

	// first registration overall
	$first_registration = false;
	
	// first registration for vet.
	$first_registration_for_vet = false;
	
	// very first registration.
	if (($_SESSION['MemberID'] == '' and $_SESSION['VetID'] != '' and $_SESSION['cookieid'] == '') or ($_SESSION['LoggedIn'] == 0 and $_SESSION['cookieid'] == '')){
		$first_registration = true;
	}
	
	// check if different implanting vet was provided.
	// check if web payment record exists with the vet.
	if($_SESSION['VetID'] != '' and $_SESSION['cookieid'] != ''){
		$odataQuery = $fm->buildODataQuery([
			'filter' => "cookie_transaction_id eq ".$_SESSION['cookieid']." and _sk_vet_id eq ".$v."",
			'select' => ['content'],
			'count' => true
		]);
		$fmrTransaction = $fm->get('Web_Payments', $odataQuery, $allPages = true );

		// $aRequest = array();
		// $aRequest['cookie_transaction_id'] = '="' . $_SESSION['cookieid'] . '"';
		// $aRequest['_sk_vet_id'] = $v;
		// $fmrTransaction = fFMPerformFind('petsafe', 'All Fields - Web_Payments', $aRequest);
		
		if (!$fmrTransaction["success"] || $fmrTransaction["data"]["count"] < 1){
			// not found, registration is first one for this vet.
			$first_registration_for_vet = true;
		}
		else {
			// found!, registration is NOT the first one for this vet.
			$first_registration_for_vet = false;
		}	
	}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>

<head>
<?php require '../phpobjects/templates/common/page_head.php'; ?>

<script type="text/javascript" src="../javascripts/prototype.js"></script>
<script type="text/javascript" src="../javascripts/common.js"></script>

<style type="text/css">
	.instructions{display:block}
	.instructions *{
	display:block;
	height:1px;
	overflow:hidden;
	font-size:.01em;
	background:#99CC99}
	.instructions1{
	margin-left:3px;
	margin-right:3px;
	padding-left:1px;
	padding-right:1px;
	border-left:1px solid #d3e9d3;
	border-right:1px solid #d3e9d3;
	background:#b2d8b2}
	.instructions2{
	margin-left:1px;
	margin-right:1px;
	padding-right:1px;
	padding-left:1px;
	border-left:1px solid #f4f9f4;
	border-right:1px solid #f4f9f4;
	background:#acd5ac}
	.instructions3{
	margin-left:1px;
	margin-right:1px;
	border-left:1px solid #acd5ac;
	border-right:1px solid #acd5ac;}
	.instructions4{
	border-left:1px solid #d3e9d3;
	border-right:1px solid #d3e9d3}
	.instructions5{
	border-left:1px solid #b2d8b2;
	border-right:1px solid #b2d8b2}
	.instructionsfg{
	background:#99CC99;
	padding: 3px;}
	.pending-items{
		background-color: #4984EF;
		font-weight: normal;
		font-family: Arial;
		font-size: 13px;
		border-radius: 3px;
		padding: 5px 10px;
		display: inline-block;
		margin-bottom: 5px;
		color: white;
	}

	.rego_type{
		background-color: #ffea71;
		font-weight: bold;
		font-family: Arial;
		font-size: 13px;
		border-radius: 3px;
		padding: 5px 10px;
		margin-bottom: 5px;
	}

	.auto-password{
		display: inline-block;
		padding: 3px 5px;
		font-weight: bold;
		border: 1px solid #333;
		border-radius: 2px;
		background-color: #f0f0f0;
	}

	.clinic-id-locked{
		font-weight:bold;
		margin-top:10px;	
		border:1px solid black;
		padding:5px;
		border-radius:2px;
		display:inline-block;
	}

	#registration_form tr td{
		vertical-align: middle;
	}

	.registration-section-header{
		font-weight: bold;
		font-size: 14px;
		padding: 10px 5px;
		background: #f0f0f0;
		border-radius: 2px;
	}
</style>

<script type="text/javascript">
    window.onload = function(){
        reset_form();
    }

    function reset_form(){
        document.getElementById('frmregister').reset();
        
        window.setTimeout(function(){
            document.getElementById('microchip_no').focus();
        }, 0);
    }

	// handler to fill suburbs
	function setTypeValueList(){
		var state_popup = document.forms[0].elements['owner_state'];
		var selected_state = state_popup.value;
		var suburb_popup = document.forms[0].elements['owner_suburb'];
		var postcode_popup = document.forms[0].elements['owner_postcode'];
		suburb_popup.disabled = false;
		postcode_popup.options.length = 0;
		postcode_popup.disabled = true;
		suburb_popup.options[suburb_popup.length] = new Option('loading...','');
		suburb_popup.selectedIndex = suburb_popup.length-1;
		var url = 'register.php?hello_from_ajax1=true&owner_state='+selected_state;
		var target = 'suburb_container';
		var result = new Ajax.Updater(target, url,{method: 'get'});
		suburb_popup.focus();
	}

	// handler to fill postcodes
	function setPostcodeValueList(){
		var state_popup = document.forms[0].elements['owner_state'];
		var selected_state = state_popup.value;
		var suburb_popup = document.forms[0].elements['owner_suburb'];
		var selected_suburb = suburb_popup.value;
		var postcode_popup = document.forms[0].elements['owner_postcode'];
		postcode_popup.disabled = false;
		postcode_popup.options[postcode_popup.length] = new Option('loading...','');
		postcode_popup.selectedIndex = postcode_popup.length-1;
		var url = 'register.php?hello_from_ajax2=true&owner_suburb='+selected_suburb+'&owner_state='+selected_state;
		var target = 'postcode_container';
		var result = new Ajax.Updater(target, url,{method: 'get'});
		postcode_popup.focus();
	}

	// handler to fill suburbs - pets
	function setTypeValueListPet(){
		var state_popup = document.forms[0].elements['pet_state'];
		var selected_state = state_popup.value;
		var suburb_popup = document.forms[0].elements['pet_suburb'];
		var postcode_popup = document.forms[0].elements['pet_postcode'];
		suburb_popup.disabled = false;
		postcode_popup.options.length = 0;
		postcode_popup.disabled = true;
		suburb_popup.options[suburb_popup.length] = new Option('loading...','');
		suburb_popup.selectedIndex = suburb_popup.length-1;
		var url = 'register.php?hello_from_ajax1p=true&pet_state='+selected_state;
		var target = 'petsuburb_container';
		var result = new Ajax.Updater(target, url,{method: 'get'});
		suburb_popup.focus();
	}

	// handler to fill postcodes - pets
	function setPostcodeValueListPet(){
		var state_popup = document.forms[0].elements['pet_state'];
		var selected_state = state_popup.value;
		var suburb_popup = document.forms[0].elements['pet_suburb'];
		var selected_suburb = suburb_popup.value;
		var postcode_popup = document.forms[0].elements['pet_postcode'];
		postcode_popup.disabled = false;
		postcode_popup.options[postcode_popup.length] = new Option('loading...','');
		postcode_popup.selectedIndex = postcode_popup.length-1;
		var url = 'register.php?hello_from_ajax2p=true&pet_suburb='+selected_suburb+'&pet_state='+selected_state;
		var target = 'petpostcode_container';
		var result = new Ajax.Updater(target, url,{method: 'get'});
		postcode_popup.focus();
	}

	// handler to fill suburbs - mailing
	function setTypeValueListMail(){
		var state_popup = document.forms[0].elements['mail_state'];
		var selected_state = state_popup.value;
		var suburb_popup = document.forms[0].elements['mail_suburb'];
		var postcode_popup = document.forms[0].elements['mail_postcode'];
		suburb_popup.disabled = false;
		postcode_popup.options.length = 0;
		postcode_popup.disabled = true;
		suburb_popup.options[suburb_popup.length] = new Option('loading...','');
		suburb_popup.selectedIndex = suburb_popup.length-1;
		var url = 'register.php?hello_from_ajax1m=true&mail_state='+selected_state;
		var target = 'mailsuburb_container';
		var result = new Ajax.Updater(target, url,{method: 'get'});
		suburb_popup.focus();
	}

	// handler to fill postcodes - mailing
	function setPostcodeValueListMail(){
		var state_popup = document.forms[0].elements['mail_state'];
		var selected_state = state_popup.value;
		var suburb_popup = document.forms[0].elements['mail_suburb'];
		var selected_suburb = suburb_popup.value;
		var postcode_popup = document.forms[0].elements['mail_postcode'];
		postcode_popup.disabled = false;
		postcode_popup.options[postcode_popup.length] = new Option('loading...','');
		postcode_popup.selectedIndex = postcode_popup.length-1;
		var url = 'register.php?hello_from_ajax2m=true&mail_suburb='+selected_suburb+'&mail_state='+selected_state;
		var target = 'mailpostcode_container';
		var result = new Ajax.Updater(target, url,{method: 'get'});
		postcode_popup.focus();
	}

	function validateForm(myform) {
        myform = document.getElementById('frmregister');

		var error1 = 'Please complete the following mandatory field(s):\n';
		var error2 = 'Your password is too short.\nPlease re-enter your password - at least 3 characters.';
		var error3 = 'The two Petsafe Password fields do not match!\nPlease re-enter your password.';
		var error4 = 'Please enter a valid email address.';
		var error5 = 'The Microchip No must be 10 characters long and alphanumeric only (A-F and/or 0-9), OR 15 characters long and numeric only.';
		var error6 = 'Please enter a valid PetSafe tag number.';
		var error7 = 'Please enter a valid Microchip number.';
		var error8 = 'Your home phone number must be 10 digits long.';
		var error9 = 'Your work phone number must be 10 digits long.';
		var error10 = 'Your mobile phone number must be 10 digits long.';
		var error11 = 'Your fax number must be 10 digits long.';
		var error12 = 'Alt Person 1 phone number must be 10 digits long.';
		var mandatory_err = 0;

		// check mandatory fields
		// owner_firstname, owner_lastname, owner_suburb, owner_state, owner_homephone, 
		// owner_password1, owner_password2, pet_name, pet_suburb, pet_state
		if (trim(myform.petsafe_no.value) == '' && trim(myform.microchip_no.value) == ''){
			myform.petsafe_no.value = '';
			myform.microchip_no.value = '';
			error1 = error1 + '\n- PetSafe Tag number OR Microchip number is required';
			mandatory_err = 1;
		}
		
	<?php
		
		if ($_SESSION['MemberID'] == '' and $_SESSION['VetID'] != ''){ ?>	
			if(document.getElementById('clinic_dropdown')){
				//make sure a clinic is selected
				var clinic_no = document.getElementById('clinic_dropdown').value;
				
			} else {
			    //do nothing, no clinics associated with vet
			}
	<?php
		}
	?>
	
	
	<?php
	if ($first_registration === true || $first_registration_for_vet === true){
	?>
		if (myform.owner_title.selectedIndex == 0){
			error1 = error1 + '\n- Owner\'s Title';
			mandatory_err = 1;
		}
		if (trim(myform.owner_firstname.value) == ''){
			myform.owner_firstname.value = '';
			error1 = error1 + '\n- Owner\'s Given Name';
			mandatory_err = 1;
		}
		if (trim(myform.owner_lastname.value) == ''){
			myform.owner_lastname.value = '';
			error1 = error1 + '\n- Owner\'s Last Name';
			mandatory_err = 1;
		}
		if (trim(myform.owner_address.value) == ''){
			myform.owner_address.value = '';
			error1 = error1 + '\n- Owner\'s Street Address';
			mandatory_err = 1;
		}
		if (myform.owner_state.selectedIndex == 0){
			error1 = error1 + '\n- Owner\'s State';
			mandatory_err = 1;
		}
		if (myform.owner_suburb.selectedIndex == 0){
			error1 = error1 + '\n- Owner\'s Suburb';
			mandatory_err = 1;
		}
		if (myform.owner_postcode.selectedIndex == 0){
			error1 = error1 + '\n- Owner\'s Postcode';
			mandatory_err = 1;
		}
        //////////////
		if (trim(myform.owner_homephone.value) == ''){
			myform.owner_homephone.value = '';
			error1 = error1 + '\n- Owner\'s Telephone(H)';
			mandatory_err = 1;
		}
		if (trim(myform.owner_altperson1.value) == ''){
			myform.owner_altperson1.value = '';
			error1 = error1 + '\n- Alt Person 1 Name';
			mandatory_err = 1;
		}
		if (trim(myform.owner_altphone1.value) == ''){
			myform.owner_altphone1.value = '';
			error1 = error1 + '\n- Alt Person 1 Telephone';
			mandatory_err = 1;
		}
		
		<?php if(strtoupper($_SESSION['rego_type']) != 'BREEDER'){ ?>
		
		if (trim(myform.owner_password1.value) == '' || trim(myform.owner_password2.value) == ''){
			myform.owner_password1.value = '';
			myform.owner_password2.value = '';
			error1 = error1 + '\n- PetSafe Password';
			mandatory_err = 1;
		}
		
		<?php
		}
		?>
		

	<?php
	// end first registration validations
	}
	?>
	
		if (trim(myform.pet_name.value) == ''){
			myform.pet_name.value = '';
			error1 = error1 + '\n- Pet\'s Name';
			mandatory_err = 1;
		}
		if (trim(myform.pet_colour.value) == ''){
			myform.pet_colour.value = '';
			error1 = error1 + '\n- Pet\'s Colour';
			mandatory_err = 1;
		}
		if (trim(myform.pet_breed.value) == ''){
			myform.pet_breed.value = '';
			error1 = error1 + '\n- Pet\'s Breed';
			mandatory_err = 1;
		}
		
		if (trim(myform.pet_dob_dd.value) == '' || trim(myform.pet_dob_mm.value) == '' || trim(myform.pet_dob_yyyy.value) == ''){
			error1 = error1 + '\n- Pet\'s DOB';
			mandatory_err = 1;
		}
		else {
			// validate date
			if (! checkDate(myform.pet_dob_dd.value,myform.pet_dob_mm.value,myform.pet_dob_yyyy.value)){
				myform.pet_dob_dd.value = '';
				myform.pet_dob_mm.value = '';
				myform.pet_dob_yyyy.value = '';
				error1 = error1 + '\n- Pet\'s DOB (invalid date!)';
				mandatory_err = 1;
			}
			else {
				// do not allow future dates
				var sysDate = new Date(); 
				var dobDate = new Date(myform.pet_dob_mm.value+"/"+ myform.pet_dob_dd.value + "/"+myform.pet_dob_yyyy.value); 
				if (dobDate > sysDate) {
					error1 = error1 + '\n- Pet\'s DOB (date cannot be in the future!)';
					mandatory_err = 1;
				}
			}
		}
		
		// Check implant date is valid one of D M and Y are antered
		if(trim(myform.pet_implant_dd.value) != '' || trim(myform.pet_implant_mm.value) != '' || trim(myform.pet_implant_yyyy.value) != ''){
			if (!checkDate(myform.pet_implant_dd.value, myform.pet_implant_mm.value, myform.pet_implant_yyyy.value)){
				myform.pet_implant_dd.value = '';
				myform.pet_implant_mm.value = '';
				myform.pet_implant_yyyy.value = '';
				error1 = error1 + '\n- Pet\'s Implant Date (invalid date!)';
				mandatory_err = 1;
			} else {
				// do not allow future dates
				var sysDate = new Date(); 
				var dobDate = new Date(myform.pet_implant_mm.value + "/" + myform.pet_implant_dd.value + "/" + myform.pet_implant_yyyy.value); 
				if (dobDate > sysDate) {
					error1 = error1 + '\n- Pet\'s Implant Date (date cannot be in the future!)';
					mandatory_err = 1;
				}
			}
		}
		
		// Check implant date is after pet dob
		if(trim(myform.pet_implant_dd.value) != '' && trim(myform.pet_implant_mm.value) != '' && trim(myform.pet_implant_yyyy.value) != '' && trim(myform.pet_dob_dd.value) != ''&& trim(myform.pet_dob_mm.value) != ''&& trim(myform.pet_dob_yyyy.value) != ''){

				var implantDate = new Date(myform.pet_implant_yyyy.value,myform.pet_implant_mm.value,myform.pet_implant_dd.value); 
				var dobDate = new Date(myform.pet_dob_yyyy.value,myform.pet_dob_mm.value,myform.pet_dob_dd.value); 
				if (dobDate > implantDate) {
					error1 = error1 + '\n- Pet\'s Implant Date (date cannot be earlier than DOB!)';
					mandatory_err = 1;
				}
			
		}
		
		
		////////////////////////////////////
		if (! myform.match_petaddr.checked) {
			if (myform.pet_state.selectedIndex == 0){
				error1 = error1 + '\n- Pet\'s State';
				mandatory_err = 1;
			}
			if (myform.pet_suburb.selectedIndex == 0){
				error1 = error1 + '\n- Pet\'s Suburb';
				mandatory_err = 1;
			}
			if (myform.pet_postcode.selectedIndex == 0){
				error1 = error1 + '\n- Pet\'s Postcode';
				mandatory_err = 1;
			}
		}
		
		if (mandatory_err != 0){
			alert(error1);
			return false;
		}

		// check if chip num supplied is 10 or 15 chars long
		if (trim(myform.microchip_no.value) != '' && trim(myform.microchip_no.value).length != 10 && trim(myform.microchip_no.value).length != 15){
			alert(error5);
			myform.microchip_no.focus();
			return false;
		}

		// check if chip num is 10 chars long and is alphanumeric
		if (trim(myform.microchip_no.value).length == 10 && !(isAlphaNum(myform.microchip_no.value))){
			alert(error5);
			myform.microchip_no.focus();
			return false;
		}
		if (trim(myform.microchip_no.value).length == 10 && isNumeric(myform.microchip_no.value)){
			alert(error5);
			myform.microchip_no.focus();
			return false;
		}

		// check if chip num is 15 chars long and is numeric
		if (trim(myform.microchip_no.value).length == 15 && !(isNumeric(myform.microchip_no.value))){
			alert(error5);
			myform.microchip_no.focus();
			return false;
		}

		// check for tag duplication
		if (trim(document.getElementById('tag_err').innerHTML) != ''){
			alert(error6);
			myform.petsafe_no.focus();
			return false;
		}

		// check for chip duplication
		if (trim(document.getElementById('chip_err').innerHTML) != ''){
			alert(error7);
			myform.microchip_no.focus();
			return false;
		}

	<?php
	if ($first_registration === true || $first_registration_for_vet === true){
	?>
		// check if phone numbers, if defined, are 10 digits
		if (myform.owner_homephone.value.replace(/\D/g,'').length != 10){
			alert(error8);
			myform.owner_homephone.focus();
			return false;
		}
		if (trim(myform.owner_workphone.value) != '' && myform.owner_workphone.value.replace(/\D/g,'').length != 10){
			alert(error9);
			myform.owner_workphone.focus();
			return false;
		}
		if (trim(myform.owner_mobilephone.value) != '' && myform.owner_mobilephone.value.replace(/\D/g,'').length != 10){
			alert(error10);
			myform.owner_mobilephone.focus();
			return false;
		}
		if (trim(myform.owner_fax.value) != '' && myform.owner_fax.value.replace(/\D/g,'').length != 10){
			alert(error11);
			myform.owner_fax.focus();
			return false;
		}
		
		if (myform.owner_altphone1.value.replace(/\D/g,'').length != 10){
			alert(error12);
			myform.owner_altphone1.focus();
			return false;
		}

		<?php if(strtoupper($_SESSION['rego_type']) != 'BREEDER'){
		//password not required bor breeder rego as password is autogenerated
		?>
		
		// check if password is long enough
		if (myform.owner_password1.value.length < 3) {
			alert(error2);
			myform.owner_password1.value = '';
			myform.owner_password2.value = '';
			myform.owner_password1.focus();
			return false;
		}

		// check if passwords match
		if (myform.owner_password1.value != myform.owner_password2.value){
			alert(error3);
			myform.owner_password1.value = '';
			myform.owner_password2.value = '';
			myform.owner_password1.focus();
			return false;
		}
		<?php
		}
		?>
		
        // encouraged to enter email addresses on first registration
		if (trim(myform.owner_email.value) == ''){
			if (confirm('You have not provided an email address. We recommend that you do so you can recover your password.\nDo you wish to sign up without an email?')){
				return true;
			}
			else {
				myform.owner_email.focus();
				return false;

			}
		}
		else {
			return true;
		}
		
		//
		return true;
		//

	<?php
	}else{
		echo 'return true;';
	} 
	?>
} // end of validate function

	function checkEmail(){
		var owneremail = document.forms[0].elements['owner_email'];
		var selected_owneremail = owneremail.value;
		if (trim(selected_owneremail) == ''){
			document.getElementById('email_err').innerHTML = '';
		} else {
			var url = 'register.php?ajax_check_email=true&email='+selected_owneremail;
			var target = 'email_err';
			var result = new Ajax.Updater(target, url,{method: 'get'});
		}
	}

	function checkTag(){
		var pstag = document.forms[0].elements['petsafe_no'];
		var selected_tag = pstag.value;
		if (trim(selected_tag) == ''){
			document.getElementById('tag_err').innerHTML = '';
		} else {
			var url = 'register.php?ajax_check_tag=true&tag='+selected_tag;
			var target = 'tag_err';
			var result = new Ajax.Updater(target, url,{method: 'get'});
		}
	}

	function checkChip(){
		var chip = document.forms[0].elements['microchip_no'];
		var selected_chip = chip.value;
		if (trim(selected_chip) == ''){
			document.getElementById('chip_err').innerHTML = '';
		} else {
			var url = 'register.php?ajax_check_chip=true&chip='+selected_chip;
			var target = 'chip_err';
			var result = new Ajax.Updater(target, url,{method: 'get'});
		}
	}

	function checkClinic(){
		var clinic_no = document.forms[0].elements['clinic_no_selected'].value;
		if (trim(clinic_no) == 'other'){
			document.forms[0].elements['clinic_no_selected'].selectedIndex = 0;
			document.getElementById('clinic_vets').innerHTML = '';
			
			clinic_no_other = prompt('Please enter the Clinic ID');
			if (clinic_no_other == '') {
				return false;
			}
			else {
				document.forms[0].elements['clinic_no_other'].value = clinic_no_other;
				checkOtherClinic();
			}
		} else {
			document.forms[0].elements['clinic_no_other'].value = '';
			document.getElementById('clinic_no_err').innerHTML = '<input type="hidden" name="clinic_no" value="' + trim(clinic_no) + '" />';
			
			displayClinicVets(trim(clinic_no));
		}
	}
	
	function checkVet(){
		var vet_no = document.forms[0].elements['implanting_vet'].value;
		var rego_type = <?php echo "'" . $rego_type . "'"; ?>;
		
		var url = 'register.php?type=' + rego_type + '&v=' + vet_no;
		
		document.location = url;
		//alert(vet_no);
		
		return true;			// ! ????
		if (trim(vet_no) == 'other'){
			document.forms[0].elements['clinic_no_selected'].selectedIndex = 0;
			document.getElementById('clinic_vets').innerHTML = '';
			
			clinic_no_other = prompt('Please enter the Clinic ID');
			if (clinic_no_other == '') {
				return false;
			}
			else {
				document.forms[0].elements['clinic_no_other'].value = clinic_no_other;
				checkOtherClinic();
			}
		} else {
			document.forms[0].elements['clinic_no_other'].value = '';
			document.getElementById('clinic_no_err').innerHTML = '<input type="hidden" name="clinic_no" value="' + trim(clinic_no) + '" />';
			
			displayClinicVets(trim(clinic_no));
		}
	}
	
	function displayClinicVets(clinic_no){
		var url = 'register.php?ajax_get_clinic_vets=true&clinic_no='+clinic_no;
		var target = 'clinic_vets';
		
		document.getElementById('clinic_vets').innerHTML = '';
		var result = new Ajax.Updater(target, url,{method: 'get'});
		//console.log(result);
	}

	function checkOtherClinic(){
		var clinic_no = document.forms[0].elements['clinic_no_other'].value;
		if (trim(clinic_no) == ''){
			document.getElementById('clinic_no_err').innerHTML = '<input type="hidden" name="clinic_no" value="" />';
		} else {
			var url = 'register.php?ajax_check_clinic_no=true&clinic_no='+clinic_no;
			var target = 'clinic_no_err';
			var result = new Ajax.Updater(target, url,{method: 'get'});
            //console.log(result);
		}
	}
    
    function change_rego_type(){
        var rego_type = document.getElementById('cmb_rego_type').value;
        document.getElementById('flag_rego_type').value = rego_type;
        document.getElementById('frm_rego_type').submit();
    }

    function check_mailing_addr(e){
        if (e.checked){
            document.getElementById('mailaddr').style.display = 'none';
            document.getElementById('mailaddr').style.visibility = 'hidden';
        }else{
            document.getElementById('mailaddr').style.display = '';
            document.getElementById('mailaddr').style.visibility = 'visible';
            alert('Please enter mailing address if different from owner\'s address.');
        }
    }
    
    function check_pet_addr(e){
        if (e.checked){
            document.getElementById('petaddr').style.display = 'none';
            document.getElementById('petaddr').style.visibility = 'hidden';
        }else{
            document.getElementById('petaddr').style.display = '';
            document.getElementById('petaddr').style.visibility = 'visible';
            alert('Please enter pet\'s address if different from owner\'s address.');
        }
    }
</script>

</head>

<?php

require '../phpobjects/templates/common/page_header.php';
/*********************** Page Start **********************/
?>

<td valign="top">

<?php
	$fm = \Keysoft\FileMaker\Client::getInstance();			// * Init	

	$odataQuery = $fm->buildODataQuery([
		'select' => ['Savage'],
		'count' => true
	]);
	$fmrSavage = $fm->get('lists_Savage', $odataQuery, true);

	if (!$fmrSavage['success']) {
		echo '<pre>';
		print_r($fmrSavage);
		echo '</pre>';
		exit;
	}

	// Fetch all savage types into array
	$fmcSavage = $fmrSavage["data"]["value"];

	/****************** Fetch Rego help info ******************/
    // $aRequest = array();
    // if ($_SESSION['VetID'] != '') {
    //     $aRequest['code'] = '="RegistrationInfoVet"';
    // } else{
    //     $aRequest['code'] = '="RegistrationInfo"';
    // }

    // $fmrRegoInfo = fFMPerformFind('petsafe', 'Web - WebContent', $aRequest);
	// $fmcRegoInfo = $fmrRegoInfo["response"]["data"][0]['fieldData'];
	// $regoInfo = $fmcRegoInfo['Content'];

	$regoInfo = getWebContent($_SESSION['VetID'] != '' ? 'RegistrationInfoVet' : 'RegistrationInfo');

	/****************** Default values ***********************/
	$companyid = '';

	/****************** Validate cookie ***********************/
	// check if cookie id is in session - if yes, and if exists, then make sure its unpaid!
	// else init cookie id in session
	if ($_SESSION['cookieid'] != ''){
		// $aRequest = array();
		// $aRequest['cookie_transaction_id'] = '="' . $_SESSION['cookieid'] . '"';
		// $fmrTransaction = fFMPerformFind('petsafe', 'All Fields - Web_Payments', $aRequest);
		// if ($fmrTransaction === FALSE || $fmrTransaction["response"]["dataInfo"]["foundCount"] < 1){
		$odataQuery = $fm->buildODataQuery([
			'filter' => "microchip_no eq '".$_GET['chip']."' and cookie_transaction_id eq '".$_SESSION['cookieid']."'",
			'select' => ['content'],
			'count' => true
		]);
		$fmrTransaction = $fm->get('Web_Payments', $odataQuery ,$allPages = true );

		if (!$fmrTransaction["success"] || $fmrTransaction["data"]["count"] < 1){
			$_SESSION['cookieid'] = '';
			//echo 'trans not found';
		}
		else {
			$fmcTransaction = $fmrTransaction["data"]["value"][0];
			if (trim(fReformatDate($fmcTransaction['transaction_finish'])) != ''){
				$_SESSION['cookieid'] = '';
				//echo 'cookie removed';
			}
		}
	}

	/****************** Fetch Vet details if logged in ******************/
	if ($_SESSION['VetID'] != ''){
		// get vet details
		// $aRequest = array();
		// $aRequest['_pk_vet_id'] = '="' . $_SESSION['VetID'] . '"';

		// $fmrVet = fFMPerformFind('petsafe', 'All Fields - Vet', $aRequest);
		$fmcVet = getVetByVetID($_SESSION['VetID']);

		// get vet companies and fill select list for Clinic ID
		// $aRequest = array();
		// $aRequest['_sk_vet_id'] = '="' . $_SESSION['VetID'] . '"';
		// $aRequest['cvr_Companies::dont_show_on_web'] = '=';
		// $fmrVetCompanies = fFMPerformFind('petsafe', 'All Fields - Company_Vet_Relation', $aRequest);
		$fmrVetCompanies = getVetClinicsByVetID($_SESSION['VetID']);
	}

	echo '<br/><h2 class="greenheading" style="margin-bottom:5px;">New Registration</h2>';
    
    if($_SESSION['cookieid'] != ''){ ?>
        <a class="pending-items" href="register_cart.php" style="color:white;">There are pending items in the cart</a>
        <br/>
    <?php }
?>

<form action="register_submit.php" method="post" name="frmregister" id="frmregister">
<?php
if (strtolower($err_code) == 'incomplete'){
	echo '<span style="color:red; font-weight: bold;">Please complete all mandatory fields</span>';
}
?>


<table border="0" width="90%" cellspacing="0" cellpadding="3" id="registration_form">
    <?php 
    if ($_SESSION['VetID'] != ''){?>
        <tr>
            <td colspan="2">
                <div class="rego_type">
                    Registration Type:
                    <select onchange="change_rego_type();" id="cmb_rego_type" <?php if($_SESSION['cookieid'] != ''){echo 'disabled';} ?>>
                        <option value="owner" <?php if(strtolower($_SESSION['rego_type']) == 'owner'){echo 'selected';} ?>>Owner</option>
                        <option value="breeder" <?php if(strtolower($_SESSION['rego_type']) == 'breeder'){echo 'selected';} ?>>Breeder</option>
                    </select>
                    <?php if(strtoupper($rego_type) != strtoupper($_SESSION['rego_type']) && $_SESSION['cookieid'] != ''){ ?>
                        <br/><div style="font-weight:normal;">There is an ongoing registration of type: <?php echo strtoupper($_SESSION['rego_type']); ?></div>
                        <div style="font-weight:normal;">To change to a different type, <a href="register_cart.php" style="font-weight:bold; color:blue;">finish the current transaction</a></div>
                    <?php } ?>
                </div>
            </td>
        </tr>
    <?php
    }
    ?>
	<tr>
		<td valign="top">Microchip No:</td>
		<td valign="top"><input type="text" size="20" maxlength="15" value="" name="microchip_no" id="microchip_no" onblur="checkChip();" />
		<span style="color:red"><sup>*</sup></span>
		<br/>
		<span class="smalltext">Please only enter numeric characters or alphanumeric characters</span>
		<?php
		if (strtolower($err_code) == 'chipinuse'){
			echo '<div id="chip_err" style="color:red;">This Chip number is already attached to a Pet on our database!<br/>Please enter a unique Microchip number for this pet registration.</div>';
		} elseif (strtolower($err_code) == 'chipinusecurrtran') {
			echo '<div id="chip_err" style="color:red;">This Chip number is being used in the current transaction!<br/>Please enter a unique Microchip number for this pet registration.</div>';
		}else{
			echo '<div id="chip_err"></div>';
		}
		?>
		</td>
	</tr>
	<tr>
		<td valign="top" nowrap="nowrap">Petsafe Collar Tag No:</td>
		<td valign="top">
			<input type="text" size="20" maxlength="20" value="" name="petsafe_no" onblur="checkTag();" />
			<span style="color:red"><sup>*</sup></span>
			<br/>
			<span class="smalltext">Please enter at least ONE of the fields above</span>
			<?php
			if (strtolower($err_code) == 'taginuse'){
				echo '<div id="tag_err" style="color:red;">This Tag number is already attached to a Pet on our database!<br/>Please enter a unique Tag number for this pet registration.</div>';
			} else {
				echo '<div id="tag_err"></div>';
			}
			?>
		</td>
	</tr>
<?php

$clinic_note_html = '<span class="smalltext" style="color:red; font-weight:bold;">';
$clinic_note_html .= 'Important - Select Clinic to be recorded on chip data and accounts. You will be required to pay on Submit if registering Non-Prepaid chips and no Clinic ID Selected.';
$clinic_note_html .= '</span>';

if ($_SESSION['VetID'] != '' and $first_registration === true){
	// show Clinic ID field for vets only
	// clinic locked to the one selected on the first registration
?>
	<tr>
		<td valign="top">Clinic ID:</td>
		<td valign="bottom">
			<?php
			if (!$fmrVetCompanies['success'] || $fmrVetCompanies["data"]["count"] < 1){
				// show text box
                echo '<input type="hidden" name="clinic_no_selected" value="other" /><input type="text" size="20" value="" name="clinic_no_other" onblur="checkOtherClinic();" /><br/><div id="clinic_no_err" class="smalltext"><input type="hidden" name="clinic_no" value="" /></div>';
            } else {
				$fmcVetCompanies = $fmrVetCompanies["data"]["value"];
				
				echo '<select name="clinic_no_selected" id="clinic_dropdown" onchange="checkClinic()">';
				echo '<option value=""></option>';
				
				foreach ($fmcVetCompanies as $companyrecord){
					// get company details
					// $aRequest = array();
					// $aRequest['_pk_company_id'] = '="' . $companyrecord['_sk_company_id'] . '"';
					// $aRequest['dont_show_on_web'] = '=';

					// $fmrCompany = fFMPerformFind('petsafe', 'Web - Companies', $aRequest);

					$odataQuery = $fm->buildODataQuery([
						'filter' => "_pk_company_id eq {$companyrecord['_sk_company_id']} and dont_show_on_web eq null",
						'count'  => true
					]);
					$fmrCompany = $fm->get('Companies', $odataQuery, $allPages = true);

					$fmcCompany = $fmrCompany["data"]["value"][0];

					echo '<option value="' . $companyrecord['_sk_company_id'] . '">' . $fmcCompany['myob_account_no'] . ': ' . $fmcCompany['Company Name'] . '</option>';
				}
				echo '<option value="other">Other Clinic ...</option>';
				echo '</select>';
				echo '<input type="hidden" value="" name="clinic_no_other" /><br/>';
				echo '<div id="clinic_no_err" class="smalltext">';
				echo '<input type="hidden" name="clinic_no" value="" /></div>';
			}
			
			echo $clinic_note_html;
			?>
		</td>
	</tr>
<?php
}else if($_SESSION['VetID'] != '' and $first_registration === false){
	// Get clinic selected on first registration and display it.
	$fm = \Keysoft\FileMaker\Client::getInstance();
    $odataQuery = $fm->buildODataQuery([
		'filter' => "cookie_transaction_id eq '".$_SESSION['cookieid']."'",
		'select' => ['content'],
        'count' => true
    ]);
    $fmrPaymentRecord = $fm->get('Web_Payments', $odataQuery ,$allPages = true );

	// $aRequest = array();
	// $aRequest['cookie_transaction_id'] = '="' . $_SESSION['cookieid'] . '"';
	
	// $fmrPaymentRecord = fFMPerformFind('petsafe', 'All Fields - Web_Payments', $aRequest);

	$fmcPaymentRecord = $fmrPaymentRecord["data"]["value"][0];
	
	$selected_clinic_id = trim($fmcPaymentRecord['_sk_company_id']);
	$selected_clinic_name = $fmcPaymentRecord['web_payment_Company::company_name_with_myob_no_c'];
	
	echo '<tr>';
	echo '<td valign="top">Clinic ID:</td>';
	
	if($selected_clinic_id == ''){
		echo '<td><div class="clinic-id-locked">No clinic selected.</div>' . $clinic_note_html . '</td>';
	}else{
		echo '<td><div class="clinic-id-locked">' . $selected_clinic_name . '</div>' . $clinic_note_html . '</td>';
	}
	
	echo '</tr>';
}
?>


<?php
// Show option to choose vet
if ($_SESSION['VetID'] != ''){
?>
<tr class="vet-selection-row">
	<td valign="top"></td>
	<td>
    	<?php
		// if not first registration then get vets that belong to the first clinic selected (only if the logged in vet is the main vet of the clinic)
        if($first_registration === false){
			
			if($selected_clinic_id == ''){
				// no clinic selected
				// don't show anything
			}else{
				// clinic selected
				// check vet is main vet for clinic selected
				$clinic_vets = '';
				
				// $aRequest = array();
				// $aRequest['_sk_vet_id'] = $_SESSION['VetID'];
				// $aRequest['_sk_company_id'] = $selected_clinic_id;
				// $aRequest['vet_main_contact'] = "Yes";
	
				// $fmrVetMain = fFMPerformFind('petsafe', 'All Fields - Company_Vet_Relation', $aRequest);

				$odataQuery = $fm->buildODataQuery([
					'filter' => "_sk_vet_id eq ".$_SESSION['VetID']." and _sk_company_id eq ".$selected_clinic_id." and vet_main_contact eq 'Yes'",
					'count' => true
				]);
				$fmrVetMain = $fm->get('Company_Vet_Relation', $odataQuery ,$allPages = true );
	
				if ($fmrVetMain['success'] || $fmrVetMain["data"]["count"] <= 0){
					// not found
					$clinic_vets = '';
				} else {
					// Get list of all vets
					// $aRequest = array();
					// $aRequest['_sk_company_id'] = $selected_clinic_id;
		
					// $fmrVets = fFMPerformFind('petsafe', 'All Fields - Company_Vet_Relation', $aRequest);

					$odataQuery = $fm->buildODataQuery([
						'filter' => "_sk_company_id eq ".$selected_clinic_id,
						'count' => true
					]);
					$fmrVets = $fm->get('Company_Vet_Relation', $odataQuery ,$allPages = true );
					
					if ($fmrVets['success'] || $fmrVets["data"]["count"] <= 0){
						$clinic_vets = '';
					}else{
						$fmcVets = $fmrVets["data"]["value"];
						
						$vet_selected = '';
						
						foreach ($fmcVets as $vetRecord){
							//$v is the selected vet or the logged in person if non provided
							$vet_selected = $vetRecord['_sk_vet_id'] == $v ? 'selected' : '';
							
							$clinic_vets .= '<option value="' . $vetRecord['_sk_vet_id'] . '" ' . $vet_selected . '>' . $vetRecord['vet_name_c'] . '</option>';
						}
						
						$clinic_vets = '<select name="implanting_vet" style="width:180px;" onchange="checkVet();">' . $clinic_vets . '</select>';
					}
				}
				
				echo $clinic_vets;
			}
		}else{
			echo '<div id="clinic_vets" style="min-height:28px;"></div>';
		}
		?>
    </td>
</tr>
<?php
}
?>



<?php
// breeder locked to the one selected on the first registration
if($first_registration === true || $first_registration_for_vet === true){
?>
	<tr>
		<td colspan="1">
               Breeder ID / Source Code:
        </td>
		<td valign="top">
        	<input type="text" size="20" maxlength="15" value="" name="pet_breeder_id" style="width:180px;" />
			<br/>
			<span class="smalltext">(Mandatory for Victoria and Queensland)</span>
        </td>
	</tr>
<?php
}
?>



<?php
// owner detauls locked to the one selected on the first registration
if ($first_registration === true || $first_registration_for_vet === true){
// display owner detail fields for vets and for new users (1st pet) only
?>
    
    <tr>
		<td colspan="2">
            <div class="registration-section-header">
                <?php if(strtoupper($_SESSION['rego_type']) == 'BREEDER'){echo 'Breeder\'s '; }else{echo'Owner\'s '; } ?>Details
            </div>
        </td>
	</tr>
	<tr>
		<td>Name</td>
		<td valign="top">
			<table border="0" cellpadding="1">
				<tr>
					<td><span style="color:red"><sup>*</sup></span> Title</td>
					<td><span style="color:red"><sup>*</sup></span> Given Name</td>
					<td><span style="color:red"><sup>*</sup></span> Last Name</td>
				</tr>
				<tr>
					<td>
						<select name="owner_title">
							<option value=""></option>
							<option value="Dr">Dr</option>
							<option value="Mr">Mr</option>
							<option value="Mrs">Mrs</option>
							<option value="Ms">Ms</option>
						</select>
					</td>
					<td><input type="text" size="15" value="" name="owner_firstname" /></td>
					<td><input type="text" size="15" value="" name="owner_lastname" /></td>
				</tr>
			</table>
		</td>
	</tr>
	
	<tr>
		<td><span style="color:red"><sup>*</sup></span> Street Address</td>
		<td valign="top">
			Unit/Street No &nbsp;&nbsp;Street Name<br/>
			<input type="text" size="30" value="" name="owner_address" />
		</td>
	</tr>
	<tr>
		<td valign="top"><span style="color:red"><sup>*</sup></span> State</td>
		<td valign="top">
			<?php echo $state_popup ?>
            </td>
	</tr>
	<tr>
		<td valign="top"><span style="color:red"><sup>*</sup></span> Suburb</td>
		<td valign="top">
			<?php echo $suburb_popup ?>
            </td>
	</tr>
	<tr>
		<td valign="top"><span style="color:red"><sup>*</sup></span> Postcode</td>
		<td valign="top">
			<?php echo $postcode_popup ?>
            </td>
	</tr>
	<tr>
		<td colspan="2">&nbsp;</td>
	</tr>
	<tr>
		<td colspan="2"><input type="checkbox" name="match_mailaddr" checked value="1" onclick="check_mailing_addr(this);" /> Mailing address same as above</td>
	</tr>
	<tr>
		<td colspan="2">
			<div id="mailaddr" name="mailaddr" style="display:none;">
			<table width="100%" border="0">
			<tr>
				<td>Mailing Address</td>
				<td valign="top">
					<input type="text" size="30" value="" name="mail_address" />
				</td>
			</tr>
			<tr>
				<td valign="top">State</td>
				<td valign="top">
					<?php echo $mailstate_popup ?>
				<td>
			</tr>
			<tr>
				<td valign="top">Suburb</td>
				<td valign="top">
					<?php echo $mailsuburb_popup ?>
				<td>
			</tr>
			<tr>
				<td valign="top">Postcode</td>
				<td valign="top">
					<?php echo $mailpostcode_popup ?>
				<td>
			</tr>
			</table>
			</div>
		</td>
	</tr>
	<tr>
		<td colspan="2">&nbsp;</td>
	</tr>
	<tr>
		<td valign="top"><span style="color:red"><sup>*</sup></span> Tel (H)</td>
		<td valign="top">
			<input type="text" size="12" value="" name="owner_homephone" />
			&nbsp;
			Tel (W)
			<input type="text" size="12" value="" name="owner_workphone" />
		</td>
	</tr>
	<tr>
		<td valign="top">Mobile</td>
		<td valign="top">
			<input type="text" size="12" value="" name="owner_mobilephone" />
			&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
			Fax
			<input type="text" size="12" value="" name="owner_fax" />
		</td>
	</tr>
	<tr>
		<td valign="top">E-mail address</td>
		<td valign="top">
			<input type="text" size="40" value="" name="owner_email" />
			<div id="email_err"></div>
		</td>
	</tr>
	<tr>
		<td colspan="2">&nbsp;</td>
	</tr>
	<tr>
		<td valign="top"><span style="color:red"><sup>*</sup></span> Alternative person 1</td>
		<td valign="top">
			<input type="text" size="20" value="" name="owner_altperson1" />
			&nbsp;
			<span style="color:red"><sup>*</sup></span> Tel
			<input type="text" size="12" value="" name="owner_altphone1" />
		</td>
	</tr>
	<tr>
		<td valign="top">Alternative person 2</td>
		<td valign="top">
			<input type="text" size="20" value="" name="owner_altperson2" />
			&nbsp;&nbsp;&nbsp;
			Tel
			<input type="text" size="12" value="" name="owner_altphone2" />
		</td>
	</tr>
	<tr>
		<td colspan="2">&nbsp;</td>
	</tr>
    <?php if(strtoupper($_SESSION['rego_type']) == 'BREEDER'){ ?>
    <tr>
        <td colspan="2"><span class="auto-password">Breeder's password will be autogenerated</span></td>
    </tr>
    <?php }else{ ?>
	<tr>
		<td valign="top" nowrap="nowrap"><span style="color:red"><sup>*</sup></span> Enter your Petsafe Password</td>
		<td valign="top">
			<input type="password" size="15" maxlength="12" value="" name="owner_password1" />
		</td>
	</tr>
	<tr>
		<td valign="top"><span style="color:red"><sup>*</sup></span> Re-Enter Password</td>
		<td valign="top">
			<input type="password" size="15" maxlength="12" value="" name="owner_password2" />
		</td>
	</tr>
	<tr>
		<td valign="top">&nbsp;</td>
		<td valign="top" style="padding-right:25px;">
			The password can contain a combination of letters & numbers both in lower case
			and upper case. Please limit password to no more than 12 characters.
		</td>
	</tr>
    <?php } ?>
	<tr>
		<td colspan="2">&nbsp;</td>
	</tr>
	<tr>
		<td valign="top">Join PetSafe Mailing List?</td>
		<td valign="top">
			<input type="radio" name="mailing_list" checked="checked" value="Yes"/> Yes
			&nbsp;&nbsp;
			<input type="radio" name="mailing_list" value="No"/> No
			<br/>
			<span class="smalltext"><a href="privacysecurity.php" target="_blank"><b>Privacy Policy</b></a></span>
		</td>
	</tr>
<?php
}
?>
	<tr>
		<td colspan="2">
            <div class="registration-section-header">
                Pet's Details
            </div>
        </td>
	</tr>
	<tr>
		<td valign="top"><span style="color:red"><sup>*</sup></span> Pet's Name</td>
		<td valign="top">
			<input type="text" size="15" value="" name="pet_name" />
		</td>
	</tr>
	<tr>
		<td valign="top"><span style="color:red"><sup>*</sup></span> Species</td>
		<td valign="top">
			<input type="radio" name="pet_type" value="Dog" checked="checked" />Dog
			<input type="radio" name="pet_type" value="Cat" />Cat
            <input type="radio" name="pet_type" value="Horse" />Horse
			<input type="radio" name="pet_type" value="Other" />Other
		</td>
	</tr>
	<tr>
		<td valign="top"><span style="color:red"><sup>*</sup></span> Colour</td>
		<td valign="top">
			<input type="text" size="10" value="" name="pet_colour" />
			<span style="color:red"><sup>*</sup></span> Breed
			<input type="text" size="12" value="" name="pet_breed" />
		</td>
	</tr>
	<tr>
		<td valign="top"><span style="color:red"><sup>*</sup></span> DOB</td>
		<td valign="top">
			<input type="text" maxlength="2" size="2" value="" name="pet_dob_dd" />
			/
			<input type="text" maxlength="2" size="2" value="" name="pet_dob_mm" />
			/
			<input type="text" maxlength="4" size="4" value="" name="pet_dob_yyyy" />
			(DD/MM/YYYY)
			<br/>
			Sex
			<input type="radio" name="pet_sex" value="M" checked="checked" />M
			<input type="radio" name="pet_sex" value="F" />F
			&nbsp;
			Desexed
			<input type="radio" name="pet_desexed" value="Yes" checked="checked" />Yes
			<input type="radio" name="pet_desexed" value="No" />No
		</td>
	</tr>
	<tr>
		<td valign="top"> Implant Date</td>
		<td valign="top">
			<input type="text" maxlength="2" size="2" value="" name="pet_implant_dd" />
			/
			<input type="text" maxlength="2" size="2" value="" name="pet_implant_mm" />
			/
			<input type="text" maxlength="4" size="4" value="" name="pet_implant_yyyy" />
			(DD/MM/YYYY)
		</td>
	</tr>
	<tr>
		<td valign="top"> Distinguishing Marks</td>
		<td valign="top">
			<input type="text" value="" size="30" name="pet_distinguishing_marks" />
		</td>
	</tr>
	<tr>
		<td valign="top">Savage Status</td>
		<td valign="top">
			<select name="pet_savage">
<?php
				foreach ($fmcSavage as $savagetype)
	            {
					echo '<option value="' . $savagetype['Savage'] . '">' . $savagetype['Savage'] . '</option>';
				}
?>
			</select><br/>
		</td>
	</tr>
	<tr>
		<td colspan="2">&nbsp;</td>
	</tr>
	<tr>
		<td colspan="2"><input type="checkbox" name="match_petaddr" checked value="1" onclick="check_pet_addr(this);" /> Pet's address same as Owner's</td>
	</tr>
	<tr>
		<td colspan="2">
			<div id="petaddr" name="petaddr" style="display:none;">
			<table width="100%" border="0">
			<tr>
				<td>Street Address</td>
				<td valign="top">
					Unit/Street No &nbsp;&nbsp;Street Name<br/>
					<input type="text" size="30" value="" name="pet_address" />
				</td>
			</tr>
			<tr>
				<td valign="top"><span style="color:red"><sup>*</sup></span> State</td>
				<td valign="top">
					<?php echo $petstate_popup ?>
				</td>
			</tr>
			<tr>
				<td valign="top"><span style="color:red"><sup>*</sup></span> Suburb</td>
				<td valign="top">
					<?php echo $petsuburb_popup ?>
				</td>
			</tr>
			<tr>
				<td valign="top"><span style="color:red"><sup>*</sup></span> Postcode</td>
				<td valign="top">
					<?php echo $petpostcode_popup ?>
				</td>
			</tr>
			</table>
			</div>
		</td>
	</tr>
	<tr>
		<td valign="top"> Entered by</td>
		<td valign="top">
			<input type="text" value="" size="30" name="entered_by" />
		</td>
	</tr>
	<tr>
		<td valign="top" colspan="2">
			<br/>
            <input type="submit" value="Submit/Pay" style="padding:2px 3px;" class="button" onclick="javascript: if(!validateForm(this.form)) return false;" />

		</td>
	</tr>
</table>
</form>

<form method="get" id="frm_rego_type">
<input type="hidden" name="type" id="flag_rego_type"/>
</form>

<br/><br/>

</td>

<td valign="top">

<br/><br/>

<div style="width:400px;">
  <b class="instructions">
  <b class="instructions1"><b></b></b>
  <b class="instructions2"><b></b></b>
  <b class="instructions3"></b>
  <b class="instructions4"></b>
  <b class="instructions5"></b></b>

  <div class="instructionsfg">
    <?php echo html_entity_decode($regoInfo) . '<br />'; ?>
	<div style="position:relative;left:-50px;"><img src="<?php echo $gaPage['root_directory']; ?>/images/cockatoo_sm.png" /></div>
  </div>

  <b class="instructions">
  <b class="instructions5"></b>
  <b class="instructions4"></b>
  <b class="instructions3"></b>
  <b class="instructions2"><b></b></b>
  <b class="instructions1"><b></b></b></b>
</div>

<br/><br/>
<div><img src="<?php echo $gaPage['root_directory']; ?>/images/petsafe_com_au.jpg" />&nbsp;</div></td>
</td>



<?php
/************************ Page End ***********************/

require '../phpobjects/templates/common/page_footer.php';
?>

</html>
<?php fCleanup(); ?>