<?php

// Data functions (insert, update, delete, form) for table applications_leases

// This script and data application were generated by AppGini 5.70
// Download AppGini for free from https://bigprof.com/appgini/download/

function applications_leases_insert(){
	global $Translation;

	// mm: can member insert record?
	$arrPerm=getTablePermissions('applications_leases');
	if(!$arrPerm[1]){
		return false;
	}

	$data['tenants'] = makeSafe($_REQUEST['tenants']);
		if($data['tenants'] == empty_lookup_value){ $data['tenants'] = ''; }
	$data['status'] = makeSafe($_REQUEST['status']);
		if($data['status'] == empty_lookup_value){ $data['status'] = ''; }
	$data['property'] = makeSafe($_REQUEST['property']);
		if($data['property'] == empty_lookup_value){ $data['property'] = ''; }
	$data['unit'] = makeSafe($_REQUEST['unit']);
		if($data['unit'] == empty_lookup_value){ $data['unit'] = ''; }
	$data['type'] = makeSafe($_REQUEST['type']);
		if($data['type'] == empty_lookup_value){ $data['type'] = ''; }
	$data['total_number_of_occupants'] = makeSafe($_REQUEST['total_number_of_occupants']);
		if($data['total_number_of_occupants'] == empty_lookup_value){ $data['total_number_of_occupants'] = ''; }
	$data['start_date'] = intval($_REQUEST['start_dateYear']) . '-' . intval($_REQUEST['start_dateMonth']) . '-' . intval($_REQUEST['start_dateDay']);
	$data['start_date'] = parseMySQLDate($data['start_date'], '1');
	$data['end_date'] = intval($_REQUEST['end_dateYear']) . '-' . intval($_REQUEST['end_dateMonth']) . '-' . intval($_REQUEST['end_dateDay']);
	$data['end_date'] = parseMySQLDate($data['end_date'], '1');
	$data['recurring_charges_frequency'] = makeSafe($_REQUEST['recurring_charges_frequency']);
		if($data['recurring_charges_frequency'] == empty_lookup_value){ $data['recurring_charges_frequency'] = ''; }
	$data['next_due_date'] = intval($_REQUEST['next_due_dateYear']) . '-' . intval($_REQUEST['next_due_dateMonth']) . '-' . intval($_REQUEST['next_due_dateDay']);
	$data['next_due_date'] = parseMySQLDate($data['next_due_date'], '1');
	$data['rent'] = makeSafe($_REQUEST['rent']);
		if($data['rent'] == empty_lookup_value){ $data['rent'] = ''; }
	$data['security_deposit'] = makeSafe($_REQUEST['security_deposit']);
		if($data['security_deposit'] == empty_lookup_value){ $data['security_deposit'] = ''; }
	$data['security_deposit_date'] = intval($_REQUEST['security_deposit_dateYear']) . '-' . intval($_REQUEST['security_deposit_dateMonth']) . '-' . intval($_REQUEST['security_deposit_dateDay']);
	$data['security_deposit_date'] = parseMySQLDate($data['security_deposit_date'], '');
	$data['emergency_contact'] = br2nl(makeSafe($_REQUEST['emergency_contact']));
	$data['co_signer_details'] = br2nl(makeSafe($_REQUEST['co_signer_details']));
	$data['notes'] = makeSafe($_REQUEST['notes']);
		if($data['notes'] == empty_lookup_value){ $data['notes'] = ''; }
	$data['agreement'] = makeSafe($_REQUEST['agreement']);
		if($data['agreement'] == empty_lookup_value){ $data['agreement'] = ''; }
	if($data['status'] == '') $data['status'] = "Application";
	if($data['status']== ''){
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">" . $Translation['error:'] . " 'Application status': " . $Translation['field not null'] . '<br><br>';
		echo '<a href="" onclick="history.go(-1); return false;">'.$Translation['< back'].'</a></div>';
		exit;
	}
	if($data['type'] == '') $data['type'] = "Fixed";
	if($data['type']== ''){
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">" . $Translation['error:'] . " 'Lease type': " . $Translation['field not null'] . '<br><br>';
		echo '<a href="" onclick="history.go(-1); return false;">'.$Translation['< back'].'</a></div>';
		exit;
	}
	if($data['recurring_charges_frequency'] == '') $data['recurring_charges_frequency'] = "Monthly";
	if($data['recurring_charges_frequency']== ''){
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">" . $Translation['error:'] . " 'Recurring charges frequency': " . $Translation['field not null'] . '<br><br>';
		echo '<a href="" onclick="history.go(-1); return false;">'.$Translation['< back'].'</a></div>';
		exit;
	}

	// hook: applications_leases_before_insert
	if(function_exists('applications_leases_before_insert')){
		$args=array();
		if(!applications_leases_before_insert($data, getMemberInfo(), $args)){ return false; }
	}

	$o = array('silentErrors' => true);
	sql('insert into `applications_leases` set       `tenants`=' . (($data['tenants'] !== '' && $data['tenants'] !== NULL) ? "'{$data['tenants']}'" : 'NULL') . ', `status`=' . (($data['status'] !== '' && $data['status'] !== NULL) ? "'{$data['status']}'" : 'NULL') . ', `property`=' . (($data['property'] !== '' && $data['property'] !== NULL) ? "'{$data['property']}'" : 'NULL') . ', `unit`=' . (($data['unit'] !== '' && $data['unit'] !== NULL) ? "'{$data['unit']}'" : 'NULL') . ', `type`=' . (($data['type'] !== '' && $data['type'] !== NULL) ? "'{$data['type']}'" : 'NULL') . ', `total_number_of_occupants`=' . (($data['total_number_of_occupants'] !== '' && $data['total_number_of_occupants'] !== NULL) ? "'{$data['total_number_of_occupants']}'" : 'NULL') . ', `start_date`=' . (($data['start_date'] !== '' && $data['start_date'] !== NULL) ? "'{$data['start_date']}'" : 'NULL') . ', `end_date`=' . (($data['end_date'] !== '' && $data['end_date'] !== NULL) ? "'{$data['end_date']}'" : 'NULL') . ', `recurring_charges_frequency`=' . (($data['recurring_charges_frequency'] !== '' && $data['recurring_charges_frequency'] !== NULL) ? "'{$data['recurring_charges_frequency']}'" : 'NULL') . ', `next_due_date`=' . (($data['next_due_date'] !== '' && $data['next_due_date'] !== NULL) ? "'{$data['next_due_date']}'" : 'NULL') . ', `rent`=' . (($data['rent'] !== '' && $data['rent'] !== NULL) ? "'{$data['rent']}'" : 'NULL') . ', `security_deposit`=' . (($data['security_deposit'] !== '' && $data['security_deposit'] !== NULL) ? "'{$data['security_deposit']}'" : 'NULL') . ', `security_deposit_date`=' . (($data['security_deposit_date'] !== '' && $data['security_deposit_date'] !== NULL) ? "'{$data['security_deposit_date']}'" : 'NULL') . ', `emergency_contact`=' . (($data['emergency_contact'] !== '' && $data['emergency_contact'] !== NULL) ? "'{$data['emergency_contact']}'" : 'NULL') . ', `co_signer_details`=' . (($data['co_signer_details'] !== '' && $data['co_signer_details'] !== NULL) ? "'{$data['co_signer_details']}'" : 'NULL') . ', `notes`=' . (($data['notes'] !== '' && $data['notes'] !== NULL) ? "'{$data['notes']}'" : 'NULL') . ', `agreement`=' . (($data['agreement'] !== '' && $data['agreement'] !== NULL) ? "'{$data['agreement']}'" : 'NULL'), $o);
	if($o['error']!=''){
		echo $o['error'];
		echo "<a href=\"applications_leases_view.php?addNew_x=1\">{$Translation['< back']}</a>";
		exit;
	}

	$recID = db_insert_id(db_link());

	// hook: applications_leases_after_insert
	if(function_exists('applications_leases_after_insert')){
		$res = sql("select * from `applications_leases` where `id`='" . makeSafe($recID, false) . "' limit 1", $eo);
		if($row = db_fetch_assoc($res)){
			$data = array_map('makeSafe', $row);
		}
		$data['selectedID'] = makeSafe($recID, false);
		$args=array();
		if(!applications_leases_after_insert($data, getMemberInfo(), $args)){ return $recID; }
	}

	// mm: save ownership data
	set_record_owner('applications_leases', $recID, getLoggedMemberID());

	return $recID;
}

function applications_leases_delete($selected_id, $AllowDeleteOfParents=false, $skipChecks=false){
	// insure referential integrity ...
	global $Translation;
	$selected_id=makeSafe($selected_id);

	// mm: can member delete record?
	$arrPerm=getTablePermissions('applications_leases');
	$ownerGroupID=sqlValue("select groupID from membership_userrecords where tableName='applications_leases' and pkValue='$selected_id'");
	$ownerMemberID=sqlValue("select lcase(memberID) from membership_userrecords where tableName='applications_leases' and pkValue='$selected_id'");
	if(($arrPerm[4]==1 && $ownerMemberID==getLoggedMemberID()) || ($arrPerm[4]==2 && $ownerGroupID==getLoggedGroupID()) || $arrPerm[4]==3){ // allow delete?
		// delete allowed, so continue ...
	}else{
		return $Translation['You don\'t have enough permissions to delete this record'];
	}

	// hook: applications_leases_before_delete
	if(function_exists('applications_leases_before_delete')){
		$args=array();
		if(!applications_leases_before_delete($selected_id, $skipChecks, getMemberInfo(), $args))
			return $Translation['Couldn\'t delete this record'];
	}

	sql("delete from `applications_leases` where `id`='$selected_id'", $eo);

	// hook: applications_leases_after_delete
	if(function_exists('applications_leases_after_delete')){
		$args=array();
		applications_leases_after_delete($selected_id, getMemberInfo(), $args);
	}

	// mm: delete ownership data
	sql("delete from membership_userrecords where tableName='applications_leases' and pkValue='$selected_id'", $eo);
}

function applications_leases_update($selected_id){
	global $Translation;

	// mm: can member edit record?
	$arrPerm=getTablePermissions('applications_leases');
	$ownerGroupID=sqlValue("select groupID from membership_userrecords where tableName='applications_leases' and pkValue='".makeSafe($selected_id)."'");
	$ownerMemberID=sqlValue("select lcase(memberID) from membership_userrecords where tableName='applications_leases' and pkValue='".makeSafe($selected_id)."'");
	if(($arrPerm[3]==1 && $ownerMemberID==getLoggedMemberID()) || ($arrPerm[3]==2 && $ownerGroupID==getLoggedGroupID()) || $arrPerm[3]==3){ // allow update?
		// update allowed, so continue ...
	}else{
		return false;
	}

	$data['tenants'] = makeSafe($_REQUEST['tenants']);
		if($data['tenants'] == empty_lookup_value){ $data['tenants'] = ''; }
	$data['status'] = makeSafe($_REQUEST['status']);
		if($data['status'] == empty_lookup_value){ $data['status'] = ''; }
	if($data['status']==''){
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">{$Translation['error:']} 'Application status': {$Translation['field not null']}<br><br>";
		echo '<a href="" onclick="history.go(-1); return false;">'.$Translation['< back'].'</a></div>';
		exit;
	}
	$data['property'] = makeSafe($_REQUEST['property']);
		if($data['property'] == empty_lookup_value){ $data['property'] = ''; }
	$data['unit'] = makeSafe($_REQUEST['unit']);
		if($data['unit'] == empty_lookup_value){ $data['unit'] = ''; }
	$data['type'] = makeSafe($_REQUEST['type']);
		if($data['type'] == empty_lookup_value){ $data['type'] = ''; }
	if($data['type']==''){
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">{$Translation['error:']} 'Lease type': {$Translation['field not null']}<br><br>";
		echo '<a href="" onclick="history.go(-1); return false;">'.$Translation['< back'].'</a></div>';
		exit;
	}
	$data['total_number_of_occupants'] = makeSafe($_REQUEST['total_number_of_occupants']);
		if($data['total_number_of_occupants'] == empty_lookup_value){ $data['total_number_of_occupants'] = ''; }
	$data['start_date'] = intval($_REQUEST['start_dateYear']) . '-' . intval($_REQUEST['start_dateMonth']) . '-' . intval($_REQUEST['start_dateDay']);
	$data['start_date'] = parseMySQLDate($data['start_date'], '1');
	$data['end_date'] = intval($_REQUEST['end_dateYear']) . '-' . intval($_REQUEST['end_dateMonth']) . '-' . intval($_REQUEST['end_dateDay']);
	$data['end_date'] = parseMySQLDate($data['end_date'], '1');
	$data['recurring_charges_frequency'] = makeSafe($_REQUEST['recurring_charges_frequency']);
		if($data['recurring_charges_frequency'] == empty_lookup_value){ $data['recurring_charges_frequency'] = ''; }
	if($data['recurring_charges_frequency']==''){
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">{$Translation['error:']} 'Recurring charges frequency': {$Translation['field not null']}<br><br>";
		echo '<a href="" onclick="history.go(-1); return false;">'.$Translation['< back'].'</a></div>';
		exit;
	}
	$data['next_due_date'] = intval($_REQUEST['next_due_dateYear']) . '-' . intval($_REQUEST['next_due_dateMonth']) . '-' . intval($_REQUEST['next_due_dateDay']);
	$data['next_due_date'] = parseMySQLDate($data['next_due_date'], '1');
	$data['rent'] = makeSafe($_REQUEST['rent']);
		if($data['rent'] == empty_lookup_value){ $data['rent'] = ''; }
	$data['security_deposit'] = makeSafe($_REQUEST['security_deposit']);
		if($data['security_deposit'] == empty_lookup_value){ $data['security_deposit'] = ''; }
	$data['security_deposit_date'] = intval($_REQUEST['security_deposit_dateYear']) . '-' . intval($_REQUEST['security_deposit_dateMonth']) . '-' . intval($_REQUEST['security_deposit_dateDay']);
	$data['security_deposit_date'] = parseMySQLDate($data['security_deposit_date'], '');
	$data['emergency_contact'] = br2nl(makeSafe($_REQUEST['emergency_contact']));
	$data['co_signer_details'] = br2nl(makeSafe($_REQUEST['co_signer_details']));
	$data['notes'] = makeSafe($_REQUEST['notes']);
		if($data['notes'] == empty_lookup_value){ $data['notes'] = ''; }
	$data['agreement'] = makeSafe($_REQUEST['agreement']);
		if($data['agreement'] == empty_lookup_value){ $data['agreement'] = ''; }
	$data['selectedID']=makeSafe($selected_id);

	// hook: applications_leases_before_update
	if(function_exists('applications_leases_before_update')){
		$args=array();
		if(!applications_leases_before_update($data, getMemberInfo(), $args)){ return false; }
	}

	$o=array('silentErrors' => true);
	sql('update `applications_leases` set       `tenants`=' . (($data['tenants'] !== '' && $data['tenants'] !== NULL) ? "'{$data['tenants']}'" : 'NULL') . ', `status`=' . (($data['status'] !== '' && $data['status'] !== NULL) ? "'{$data['status']}'" : 'NULL') . ', `property`=' . (($data['property'] !== '' && $data['property'] !== NULL) ? "'{$data['property']}'" : 'NULL') . ', `unit`=' . (($data['unit'] !== '' && $data['unit'] !== NULL) ? "'{$data['unit']}'" : 'NULL') . ', `type`=' . (($data['type'] !== '' && $data['type'] !== NULL) ? "'{$data['type']}'" : 'NULL') . ', `total_number_of_occupants`=' . (($data['total_number_of_occupants'] !== '' && $data['total_number_of_occupants'] !== NULL) ? "'{$data['total_number_of_occupants']}'" : 'NULL') . ', `start_date`=' . (($data['start_date'] !== '' && $data['start_date'] !== NULL) ? "'{$data['start_date']}'" : 'NULL') . ', `end_date`=' . (($data['end_date'] !== '' && $data['end_date'] !== NULL) ? "'{$data['end_date']}'" : 'NULL') . ', `recurring_charges_frequency`=' . (($data['recurring_charges_frequency'] !== '' && $data['recurring_charges_frequency'] !== NULL) ? "'{$data['recurring_charges_frequency']}'" : 'NULL') . ', `next_due_date`=' . (($data['next_due_date'] !== '' && $data['next_due_date'] !== NULL) ? "'{$data['next_due_date']}'" : 'NULL') . ', `rent`=' . (($data['rent'] !== '' && $data['rent'] !== NULL) ? "'{$data['rent']}'" : 'NULL') . ', `security_deposit`=' . (($data['security_deposit'] !== '' && $data['security_deposit'] !== NULL) ? "'{$data['security_deposit']}'" : 'NULL') . ', `security_deposit_date`=' . (($data['security_deposit_date'] !== '' && $data['security_deposit_date'] !== NULL) ? "'{$data['security_deposit_date']}'" : 'NULL') . ', `emergency_contact`=' . (($data['emergency_contact'] !== '' && $data['emergency_contact'] !== NULL) ? "'{$data['emergency_contact']}'" : 'NULL') . ', `co_signer_details`=' . (($data['co_signer_details'] !== '' && $data['co_signer_details'] !== NULL) ? "'{$data['co_signer_details']}'" : 'NULL') . ', `notes`=' . (($data['notes'] !== '' && $data['notes'] !== NULL) ? "'{$data['notes']}'" : 'NULL') . ', `agreement`=' . (($data['agreement'] !== '' && $data['agreement'] !== NULL) ? "'{$data['agreement']}'" : 'NULL') . " where `id`='".makeSafe($selected_id)."'", $o);
	if($o['error']!=''){
		echo $o['error'];
		echo '<a href="applications_leases_view.php?SelectedID='.urlencode($selected_id)."\">{$Translation['< back']}</a>";
		exit;
	}


	// hook: applications_leases_after_update
	if(function_exists('applications_leases_after_update')){
		$res = sql("SELECT * FROM `applications_leases` WHERE `id`='{$data['selectedID']}' LIMIT 1", $eo);
		if($row = db_fetch_assoc($res)){
			$data = array_map('makeSafe', $row);
		}
		$data['selectedID'] = $data['id'];
		$args = array();
		if(!applications_leases_after_update($data, getMemberInfo(), $args)){ return; }
	}

	// mm: update ownership data
	sql("update membership_userrecords set dateUpdated='".time()."' where tableName='applications_leases' and pkValue='".makeSafe($selected_id)."'", $eo);

}

function applications_leases_form($selected_id = '', $AllowUpdate = 1, $AllowInsert = 1, $AllowDelete = 1, $ShowCancel = 0, $TemplateDV = '', $TemplateDVP = ''){
	// function to return an editable form for a table records
	// and fill it with data of record whose ID is $selected_id. If $selected_id
	// is empty, an empty form is shown, with only an 'Add New'
	// button displayed.

	global $Translation;

	// mm: get table permissions
	$arrPerm=getTablePermissions('applications_leases');
	if(!$arrPerm[1] && $selected_id==''){ return ''; }
	$AllowInsert = ($arrPerm[1] ? true : false);
	// print preview?
	$dvprint = false;
	if($selected_id && $_REQUEST['dvprint_x'] != ''){
		$dvprint = true;
	}

	$filterer_tenants = thisOr(undo_magic_quotes($_REQUEST['filterer_tenants']), '');
	$filterer_property = thisOr(undo_magic_quotes($_REQUEST['filterer_property']), '');
	$filterer_unit = thisOr(undo_magic_quotes($_REQUEST['filterer_unit']), '');

	// populate filterers, starting from children to grand-parents
	if($filterer_unit && !$filterer_property) $filterer_property = sqlValue("select property from units where id='" . makeSafe($filterer_unit) . "'");

	// unique random identifier
	$rnd1 = ($dvprint ? rand(1000000, 9999999) : '');
	// combobox: tenants
	$combo_tenants = new DataCombo;
	// combobox: status
	$combo_status = new Combo;
	$combo_status->ListType = 2;
	$combo_status->MultipleSeparator = ', ';
	$combo_status->ListBoxHeight = 10;
	$combo_status->RadiosPerLine = 1;
	if(is_file(dirname(__FILE__).'/hooks/applications_leases.status.csv')){
		$status_data = addslashes(implode('', @file(dirname(__FILE__).'/hooks/applications_leases.status.csv')));
		$combo_status->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($status_data)));
		$combo_status->ListData = $combo_status->ListItem;
	}else{
		$combo_status->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Application;;Lease;;Historical lease")));
		$combo_status->ListData = $combo_status->ListItem;
	}
	$combo_status->SelectName = 'status';
	$combo_status->AllowNull = false;
	// combobox: property
	$combo_property = new DataCombo;
	// combobox: unit, filterable by: property
	$combo_unit = new DataCombo;
	// combobox: type
	$combo_type = new Combo;
	$combo_type->ListType = 2;
	$combo_type->MultipleSeparator = ', ';
	$combo_type->ListBoxHeight = 10;
	$combo_type->RadiosPerLine = 1;
	if(is_file(dirname(__FILE__).'/hooks/applications_leases.type.csv')){
		$type_data = addslashes(implode('', @file(dirname(__FILE__).'/hooks/applications_leases.type.csv')));
		$combo_type->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($type_data)));
		$combo_type->ListData = $combo_type->ListItem;
	}else{
		$combo_type->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Fixed;;Fixed with rollover;;At-will")));
		$combo_type->ListData = $combo_type->ListItem;
	}
	$combo_type->SelectName = 'type';
	$combo_type->AllowNull = false;
	// combobox: start_date
	$combo_start_date = new DateCombo;
	$combo_start_date->DateFormat = "mdy";
	$combo_start_date->MinYear = 1900;
	$combo_start_date->MaxYear = 2100;
	$combo_start_date->DefaultDate = parseMySQLDate('1', '1');
	$combo_start_date->MonthNames = $Translation['month names'];
	$combo_start_date->NamePrefix = 'start_date';
	// combobox: end_date
	$combo_end_date = new DateCombo;
	$combo_end_date->DateFormat = "mdy";
	$combo_end_date->MinYear = 1900;
	$combo_end_date->MaxYear = 2100;
	$combo_end_date->DefaultDate = parseMySQLDate('1', '1');
	$combo_end_date->MonthNames = $Translation['month names'];
	$combo_end_date->NamePrefix = 'end_date';
	// combobox: recurring_charges_frequency
	$combo_recurring_charges_frequency = new Combo;
	$combo_recurring_charges_frequency->ListType = 0;
	$combo_recurring_charges_frequency->MultipleSeparator = ', ';
	$combo_recurring_charges_frequency->ListBoxHeight = 10;
	$combo_recurring_charges_frequency->RadiosPerLine = 1;
	if(is_file(dirname(__FILE__).'/hooks/applications_leases.recurring_charges_frequency.csv')){
		$recurring_charges_frequency_data = addslashes(implode('', @file(dirname(__FILE__).'/hooks/applications_leases.recurring_charges_frequency.csv')));
		$combo_recurring_charges_frequency->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($recurring_charges_frequency_data)));
		$combo_recurring_charges_frequency->ListData = $combo_recurring_charges_frequency->ListItem;
	}else{
		$combo_recurring_charges_frequency->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Daily;;Weekly;;Every two weeks;;Monthly;;Every two months;;Quarterly;;Every six months;;Yearly;;One time")));
		$combo_recurring_charges_frequency->ListData = $combo_recurring_charges_frequency->ListItem;
	}
	$combo_recurring_charges_frequency->SelectName = 'recurring_charges_frequency';
	$combo_recurring_charges_frequency->AllowNull = false;
	// combobox: next_due_date
	$combo_next_due_date = new DateCombo;
	$combo_next_due_date->DateFormat = "mdy";
	$combo_next_due_date->MinYear = 1900;
	$combo_next_due_date->MaxYear = 2100;
	$combo_next_due_date->DefaultDate = parseMySQLDate('1', '1');
	$combo_next_due_date->MonthNames = $Translation['month names'];
	$combo_next_due_date->NamePrefix = 'next_due_date';
	// combobox: security_deposit_date
	$combo_security_deposit_date = new DateCombo;
	$combo_security_deposit_date->DateFormat = "mdy";
	$combo_security_deposit_date->MinYear = 1900;
	$combo_security_deposit_date->MaxYear = 2100;
	$combo_security_deposit_date->DefaultDate = parseMySQLDate('', '');
	$combo_security_deposit_date->MonthNames = $Translation['month names'];
	$combo_security_deposit_date->NamePrefix = 'security_deposit_date';

	if($selected_id){
		// mm: check member permissions
		if(!$arrPerm[2]){
			return "";
		}
		// mm: who is the owner?
		$ownerGroupID=sqlValue("select groupID from membership_userrecords where tableName='applications_leases' and pkValue='".makeSafe($selected_id)."'");
		$ownerMemberID=sqlValue("select lcase(memberID) from membership_userrecords where tableName='applications_leases' and pkValue='".makeSafe($selected_id)."'");
		if($arrPerm[2]==1 && getLoggedMemberID()!=$ownerMemberID){
			return "";
		}
		if($arrPerm[2]==2 && getLoggedGroupID()!=$ownerGroupID){
			return "";
		}

		// can edit?
		if(($arrPerm[3]==1 && $ownerMemberID==getLoggedMemberID()) || ($arrPerm[3]==2 && $ownerGroupID==getLoggedGroupID()) || $arrPerm[3]==3){
			$AllowUpdate=1;
		}else{
			$AllowUpdate=0;
		}

		$res = sql("select * from `applications_leases` where `id`='".makeSafe($selected_id)."'", $eo);
		if(!($row = db_fetch_array($res))){
			return error_message($Translation['No records found'], 'applications_leases_view.php', false);
		}
		$urow = $row; /* unsanitized data */
		$hc = new CI_Input();
		$row = $hc->xss_clean($row); /* sanitize data */
		$combo_tenants->SelectedData = $row['tenants'];
		$combo_status->SelectedData = $row['status'];
		$combo_property->SelectedData = $row['property'];
		$combo_unit->SelectedData = $row['unit'];
		$combo_type->SelectedData = $row['type'];
		$combo_start_date->DefaultDate = $row['start_date'];
		$combo_end_date->DefaultDate = $row['end_date'];
		$combo_recurring_charges_frequency->SelectedData = $row['recurring_charges_frequency'];
		$combo_next_due_date->DefaultDate = $row['next_due_date'];
		$combo_security_deposit_date->DefaultDate = $row['security_deposit_date'];
	}else{
		$combo_tenants->SelectedData = $filterer_tenants;
		$combo_status->SelectedText = ( $_REQUEST['FilterField'][1]=='3' && $_REQUEST['FilterOperator'][1]=='<=>' ? (get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1]) : "Application");
		$combo_property->SelectedData = $filterer_property;
		$combo_unit->SelectedData = $filterer_unit;
		$combo_type->SelectedText = ( $_REQUEST['FilterField'][1]=='6' && $_REQUEST['FilterOperator'][1]=='<=>' ? (get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1]) : "Fixed");
		$combo_recurring_charges_frequency->SelectedText = ( $_REQUEST['FilterField'][1]=='10' && $_REQUEST['FilterOperator'][1]=='<=>' ? (get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1]) : "Monthly");
	}
	$combo_tenants->HTML = '<span id="tenants-container' . $rnd1 . '"></span><input type="hidden" name="tenants" id="tenants' . $rnd1 . '" value="' . html_attr($combo_tenants->SelectedData) . '">';
	$combo_tenants->MatchText = '<span id="tenants-container-readonly' . $rnd1 . '"></span><input type="hidden" name="tenants" id="tenants' . $rnd1 . '" value="' . html_attr($combo_tenants->SelectedData) . '">';
	$combo_status->Render();
	$combo_property->HTML = '<span id="property-container' . $rnd1 . '"></span><input type="hidden" name="property" id="property' . $rnd1 . '" value="' . html_attr($combo_property->SelectedData) . '">';
	$combo_property->MatchText = '<span id="property-container-readonly' . $rnd1 . '"></span><input type="hidden" name="property" id="property' . $rnd1 . '" value="' . html_attr($combo_property->SelectedData) . '">';
	$combo_unit->HTML = '<span id="unit-container' . $rnd1 . '"></span><input type="hidden" name="unit" id="unit' . $rnd1 . '" value="' . html_attr($combo_unit->SelectedData) . '">';
	$combo_unit->MatchText = '<span id="unit-container-readonly' . $rnd1 . '"></span><input type="hidden" name="unit" id="unit' . $rnd1 . '" value="' . html_attr($combo_unit->SelectedData) . '">';
	$combo_type->Render();
	$combo_recurring_charges_frequency->Render();

	ob_start();
	?>

	<script>
		// initial lookup values
		AppGini.current_tenants__RAND__ = { text: "", value: "<?php echo addslashes($selected_id ? $urow['tenants'] : $filterer_tenants); ?>"};
		AppGini.current_property__RAND__ = { text: "", value: "<?php echo addslashes($selected_id ? $urow['property'] : $filterer_property); ?>"};
		AppGini.current_unit__RAND__ = { text: "", value: "<?php echo addslashes($selected_id ? $urow['unit'] : $filterer_unit); ?>"};

		jQuery(function() {
			setTimeout(function(){
				if(typeof(tenants_reload__RAND__) == 'function') tenants_reload__RAND__();
				if(typeof(property_reload__RAND__) == 'function') property_reload__RAND__();
				<?php echo (!$AllowUpdate || $dvprint ? 'if(typeof(unit_reload__RAND__) == \'function\') unit_reload__RAND__(AppGini.current_property__RAND__.value);' : ''); ?>
			}, 10); /* we need to slightly delay client-side execution of the above code to allow AppGini.ajaxCache to work */
		});
		function tenants_reload__RAND__(){
		<?php if(($AllowUpdate || $AllowInsert) && !$dvprint){ ?>

			$j("#tenants-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					$j.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: AppGini.current_tenants__RAND__.value, t: 'applications_leases', f: 'tenants' },
						success: function(resp){
							c({
								id: resp.results[0].id,
								text: resp.results[0].text
							});
							$j('[name="tenants"]').val(resp.results[0].id);
							$j('[id=tenants-container-readonly__RAND__]').html('<span id="tenants-match-text">' + resp.results[0].text + '</span>');
							if(resp.results[0].id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=applicants_and_tenants_view_parent]').hide(); }else{ $j('.btn[id=applicants_and_tenants_view_parent]').show(); }


							if(typeof(tenants_update_autofills__RAND__) == 'function') tenants_update_autofills__RAND__();
						}
					});
				},
				width: '100%',
				formatNoMatches: function(term){ return '<?php echo addslashes($Translation['No matches found!']); ?>'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { s: term, p: page, t: 'applications_leases', f: 'tenants' }; },
					results: function(resp, page){ return resp; }
				},
				escapeMarkup: function(str){ return str; }
			}).on('change', function(e){
				AppGini.current_tenants__RAND__.value = e.added.id;
				AppGini.current_tenants__RAND__.text = e.added.text;
				$j('[name="tenants"]').val(e.added.id);
				if(e.added.id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=applicants_and_tenants_view_parent]').hide(); }else{ $j('.btn[id=applicants_and_tenants_view_parent]').show(); }


				if(typeof(tenants_update_autofills__RAND__) == 'function') tenants_update_autofills__RAND__();
			});

			if(!$j("#tenants-container__RAND__").length){
				$j.ajax({
					url: 'ajax_combo.php',
					dataType: 'json',
					data: { id: AppGini.current_tenants__RAND__.value, t: 'applications_leases', f: 'tenants' },
					success: function(resp){
						$j('[name="tenants"]').val(resp.results[0].id);
						$j('[id=tenants-container-readonly__RAND__]').html('<span id="tenants-match-text">' + resp.results[0].text + '</span>');
						if(resp.results[0].id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=applicants_and_tenants_view_parent]').hide(); }else{ $j('.btn[id=applicants_and_tenants_view_parent]').show(); }

						if(typeof(tenants_update_autofills__RAND__) == 'function') tenants_update_autofills__RAND__();
					}
				});
			}

		<?php }else{ ?>

			$j.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: AppGini.current_tenants__RAND__.value, t: 'applications_leases', f: 'tenants' },
				success: function(resp){
					$j('[id=tenants-container__RAND__], [id=tenants-container-readonly__RAND__]').html('<span id="tenants-match-text">' + resp.results[0].text + '</span>');
					if(resp.results[0].id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=applicants_and_tenants_view_parent]').hide(); }else{ $j('.btn[id=applicants_and_tenants_view_parent]').show(); }

					if(typeof(tenants_update_autofills__RAND__) == 'function') tenants_update_autofills__RAND__();
				}
			});
		<?php } ?>

		}
		function property_reload__RAND__(){
		<?php if(($AllowUpdate || $AllowInsert) && !$dvprint){ ?>

			$j("#property-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					$j.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { id: AppGini.current_property__RAND__.value, t: 'applications_leases', f: 'property' },
						success: function(resp){
							c({
								id: resp.results[0].id,
								text: resp.results[0].text
							});
							$j('[name="property"]').val(resp.results[0].id);
							$j('[id=property-container-readonly__RAND__]').html('<span id="property-match-text">' + resp.results[0].text + '</span>');
							if(resp.results[0].id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=properties_view_parent]').hide(); }else{ $j('.btn[id=properties_view_parent]').show(); }

						if(typeof(unit_reload__RAND__) == 'function') unit_reload__RAND__(AppGini.current_property__RAND__.value);

							if(typeof(property_update_autofills__RAND__) == 'function') property_update_autofills__RAND__();
						}
					});
				},
				width: '100%',
				formatNoMatches: function(term){ return '<?php echo addslashes($Translation['No matches found!']); ?>'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { s: term, p: page, t: 'applications_leases', f: 'property' }; },
					results: function(resp, page){ return resp; }
				},
				escapeMarkup: function(str){ return str; }
			}).on('change', function(e){
				AppGini.current_property__RAND__.value = e.added.id;
				AppGini.current_property__RAND__.text = e.added.text;
				$j('[name="property"]').val(e.added.id);
				if(e.added.id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=properties_view_parent]').hide(); }else{ $j('.btn[id=properties_view_parent]').show(); }

						if(typeof(unit_reload__RAND__) == 'function') unit_reload__RAND__(AppGini.current_property__RAND__.value);

				if(typeof(property_update_autofills__RAND__) == 'function') property_update_autofills__RAND__();
			});

			if(!$j("#property-container__RAND__").length){
				$j.ajax({
					url: 'ajax_combo.php',
					dataType: 'json',
					data: { id: AppGini.current_property__RAND__.value, t: 'applications_leases', f: 'property' },
					success: function(resp){
						$j('[name="property"]').val(resp.results[0].id);
						$j('[id=property-container-readonly__RAND__]').html('<span id="property-match-text">' + resp.results[0].text + '</span>');
						if(resp.results[0].id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=properties_view_parent]').hide(); }else{ $j('.btn[id=properties_view_parent]').show(); }

						if(typeof(property_update_autofills__RAND__) == 'function') property_update_autofills__RAND__();
					}
				});
			}

		<?php }else{ ?>

			$j.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: AppGini.current_property__RAND__.value, t: 'applications_leases', f: 'property' },
				success: function(resp){
					$j('[id=property-container__RAND__], [id=property-container-readonly__RAND__]').html('<span id="property-match-text">' + resp.results[0].text + '</span>');
					if(resp.results[0].id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=properties_view_parent]').hide(); }else{ $j('.btn[id=properties_view_parent]').show(); }

					if(typeof(property_update_autofills__RAND__) == 'function') property_update_autofills__RAND__();
				}
			});
		<?php } ?>

		}
		function unit_reload__RAND__(filterer_property){
		<?php if(($AllowUpdate || $AllowInsert) && !$dvprint){ ?>

			$j("#unit-container__RAND__").select2({
				/* initial default value */
				initSelection: function(e, c){
					$j.ajax({
						url: 'ajax_combo.php',
						dataType: 'json',
						data: { filterer_property: filterer_property, id: AppGini.current_unit__RAND__.value, t: 'applications_leases', f: 'unit' },
						success: function(resp){
							c({
								id: resp.results[0].id,
								text: resp.results[0].text
							});
							$j('[name="unit"]').val(resp.results[0].id);
							$j('[id=unit-container-readonly__RAND__]').html('<span id="unit-match-text">' + resp.results[0].text + '</span>');
							if(resp.results[0].id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=units_view_parent]').hide(); }else{ $j('.btn[id=units_view_parent]').show(); }


							if(typeof(unit_update_autofills__RAND__) == 'function') unit_update_autofills__RAND__();
						}
					});
				},
				width: '100%',
				formatNoMatches: function(term){ return '<?php echo addslashes($Translation['No matches found!']); ?>'; },
				minimumResultsForSearch: 10,
				loadMorePadding: 200,
				ajax: {
					url: 'ajax_combo.php',
					dataType: 'json',
					cache: true,
					data: function(term, page){ return { filterer_property: filterer_property, s: term, p: page, t: 'applications_leases', f: 'unit' }; },
					results: function(resp, page){ return resp; }
				},
				escapeMarkup: function(str){ return str; }
			}).on('change', function(e){
				AppGini.current_unit__RAND__.value = e.added.id;
				AppGini.current_unit__RAND__.text = e.added.text;
				$j('[name="unit"]').val(e.added.id);
				if(e.added.id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=units_view_parent]').hide(); }else{ $j('.btn[id=units_view_parent]').show(); }


				if(typeof(unit_update_autofills__RAND__) == 'function') unit_update_autofills__RAND__();
			});

			if(!$j("#unit-container__RAND__").length){
				$j.ajax({
					url: 'ajax_combo.php',
					dataType: 'json',
					data: { id: AppGini.current_unit__RAND__.value, t: 'applications_leases', f: 'unit' },
					success: function(resp){
						$j('[name="unit"]').val(resp.results[0].id);
						$j('[id=unit-container-readonly__RAND__]').html('<span id="unit-match-text">' + resp.results[0].text + '</span>');
						if(resp.results[0].id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=units_view_parent]').hide(); }else{ $j('.btn[id=units_view_parent]').show(); }

						if(typeof(unit_update_autofills__RAND__) == 'function') unit_update_autofills__RAND__();
					}
				});
			}

		<?php }else{ ?>

			$j.ajax({
				url: 'ajax_combo.php',
				dataType: 'json',
				data: { id: AppGini.current_unit__RAND__.value, t: 'applications_leases', f: 'unit' },
				success: function(resp){
					$j('[id=unit-container__RAND__], [id=unit-container-readonly__RAND__]').html('<span id="unit-match-text">' + resp.results[0].text + '</span>');
					if(resp.results[0].id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=units_view_parent]').hide(); }else{ $j('.btn[id=units_view_parent]').show(); }

					if(typeof(unit_update_autofills__RAND__) == 'function') unit_update_autofills__RAND__();
				}
			});
		<?php } ?>

		}
	</script>
	<?php

	$lookups = str_replace('__RAND__', $rnd1, ob_get_contents());
	ob_end_clean();


	// code for template based detail view forms

	// open the detail view template
	if($dvprint){
		$template_file = is_file("./{$TemplateDVP}") ? "./{$TemplateDVP}" : './templates/applications_leases_templateDVP.html';
		$templateCode = @file_get_contents($template_file);
	}else{
		$template_file = is_file("./{$TemplateDV}") ? "./{$TemplateDV}" : './templates/applications_leases_templateDV.html';
		$templateCode = @file_get_contents($template_file);
	}

	// process form title
	$templateCode = str_replace('<%%DETAIL_VIEW_TITLE%%>', 'Application/Lease Info', $templateCode);
	$templateCode = str_replace('<%%RND1%%>', $rnd1, $templateCode);
	$templateCode = str_replace('<%%EMBEDDED%%>', ($_REQUEST['Embedded'] ? 'Embedded=1' : ''), $templateCode);
	// process buttons
	if($AllowInsert){
		if(!$selected_id) $templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button type="submit" class="btn btn-success" id="insert" name="insert_x" value="1" onclick="return applications_leases_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save New'] . '</button>', $templateCode);
		$templateCode = str_replace('<%%INSERT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="insert" name="insert_x" value="1" onclick="return applications_leases_validateData();"><i class="glyphicon glyphicon-plus-sign"></i> ' . $Translation['Save As Copy'] . '</button>', $templateCode);
	}else{
		$templateCode = str_replace('<%%INSERT_BUTTON%%>', '', $templateCode);
	}

	// 'Back' button action
	if($_REQUEST['Embedded']){
		$backAction = 'AppGini.closeParentModal(); return false;';
	}else{
		$backAction = '$j(\'form\').eq(0).attr(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;';
	}

	if($selected_id){
		if(!$_REQUEST['Embedded']) $templateCode = str_replace('<%%DVPRINT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="dvprint" name="dvprint_x" value="1" onclick="$$(\'form\')[0].writeAttribute(\'novalidate\', \'novalidate\'); document.myform.reset(); return true;" title="' . html_attr($Translation['Print Preview']) . '"><i class="glyphicon glyphicon-print"></i> ' . $Translation['Print Preview'] . '</button>', $templateCode);
		if($AllowUpdate){
			$templateCode = str_replace('<%%UPDATE_BUTTON%%>', '<button type="submit" class="btn btn-success btn-lg" id="update" name="update_x" value="1" onclick="return applications_leases_validateData();" title="' . html_attr($Translation['Save Changes']) . '"><i class="glyphicon glyphicon-ok"></i> ' . $Translation['Save Changes'] . '</button>', $templateCode);
		}else{
			$templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
		}
		if(($arrPerm[4]==1 && $ownerMemberID==getLoggedMemberID()) || ($arrPerm[4]==2 && $ownerGroupID==getLoggedGroupID()) || $arrPerm[4]==3){ // allow delete?
			$templateCode = str_replace('<%%DELETE_BUTTON%%>', '<button type="submit" class="btn btn-danger" id="delete" name="delete_x" value="1" onclick="return confirm(\'' . $Translation['are you sure?'] . '\');" title="' . html_attr($Translation['Delete']) . '"><i class="glyphicon glyphicon-trash"></i> ' . $Translation['Delete'] . '</button>', $templateCode);
		}else{
			$templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
		}
		$templateCode = str_replace('<%%DESELECT_BUTTON%%>', '<button type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '" title="' . html_attr($Translation['Back']) . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>', $templateCode);
	}else{
		$templateCode = str_replace('<%%UPDATE_BUTTON%%>', '', $templateCode);
		$templateCode = str_replace('<%%DELETE_BUTTON%%>', '', $templateCode);
		$templateCode = str_replace('<%%DESELECT_BUTTON%%>', ($ShowCancel ? '<button type="submit" class="btn btn-default" id="deselect" name="deselect_x" value="1" onclick="' . $backAction . '" title="' . html_attr($Translation['Back']) . '"><i class="glyphicon glyphicon-chevron-left"></i> ' . $Translation['Back'] . '</button>' : ''), $templateCode);
	}

	// set records to read only if user can't insert new records and can't edit current record
	if(($selected_id && !$AllowUpdate && !$AllowInsert) || (!$selected_id && !$AllowInsert)){
		$jsReadOnly .= "\tjQuery('#tenants').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\tjQuery('#tenants_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
		$jsReadOnly .= "\tjQuery('input[name=status]').parent().html('<div class=\"form-control-static\">' + jQuery('input[name=status]:checked').next().text() + '</div>')\n";
		$jsReadOnly .= "\tjQuery('#property').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\tjQuery('#property_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
		$jsReadOnly .= "\tjQuery('#unit').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\tjQuery('#unit_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
		$jsReadOnly .= "\tjQuery('input[name=type]').parent().html('<div class=\"form-control-static\">' + jQuery('input[name=type]:checked').next().text() + '</div>')\n";
		$jsReadOnly .= "\tjQuery('#total_number_of_occupants').replaceWith('<div class=\"form-control-static\" id=\"total_number_of_occupants\">' + (jQuery('#total_number_of_occupants').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#start_date').prop('readonly', true);\n";
		$jsReadOnly .= "\tjQuery('#start_dateDay, #start_dateMonth, #start_dateYear').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\tjQuery('#end_date').prop('readonly', true);\n";
		$jsReadOnly .= "\tjQuery('#end_dateDay, #end_dateMonth, #end_dateYear').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\tjQuery('#recurring_charges_frequency').replaceWith('<div class=\"form-control-static\" id=\"recurring_charges_frequency\">' + (jQuery('#recurring_charges_frequency').val() || '') + '</div>'); jQuery('#recurring_charges_frequency-multi-selection-help').hide();\n";
		$jsReadOnly .= "\tjQuery('#next_due_date').prop('readonly', true);\n";
		$jsReadOnly .= "\tjQuery('#next_due_dateDay, #next_due_dateMonth, #next_due_dateYear').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\tjQuery('#rent').replaceWith('<div class=\"form-control-static\" id=\"rent\">' + (jQuery('#rent').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#security_deposit').replaceWith('<div class=\"form-control-static\" id=\"security_deposit\">' + (jQuery('#security_deposit').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#security_deposit_date').prop('readonly', true);\n";
		$jsReadOnly .= "\tjQuery('#security_deposit_dateDay, #security_deposit_dateMonth, #security_deposit_dateYear').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\tjQuery('#emergency_contact').replaceWith('<div class=\"form-control-static\" id=\"emergency_contact\">' + (jQuery('#emergency_contact').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#co_signer_details').replaceWith('<div class=\"form-control-static\" id=\"co_signer_details\">' + (jQuery('#co_signer_details').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#agreement').prop('disabled', true);\n";
		$jsReadOnly .= "\tjQuery('.select2-container').hide();\n";

		$noUploads = true;
	}elseif($AllowInsert){
		$jsEditable .= "\tjQuery('form').eq(0).data('already_changed', true);"; // temporarily disable form change handler
			$jsEditable .= "\tjQuery('form').eq(0).data('already_changed', false);"; // re-enable form change handler
	}

	// process combos
	$templateCode = str_replace('<%%COMBO(tenants)%%>', $combo_tenants->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(tenants)%%>', $combo_tenants->MatchText, $templateCode);
	$templateCode = str_replace('<%%URLCOMBOTEXT(tenants)%%>', urlencode($combo_tenants->MatchText), $templateCode);
	$templateCode = str_replace('<%%COMBO(status)%%>', $combo_status->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(status)%%>', $combo_status->SelectedData, $templateCode);
	$templateCode = str_replace('<%%COMBO(property)%%>', $combo_property->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(property)%%>', $combo_property->MatchText, $templateCode);
	$templateCode = str_replace('<%%URLCOMBOTEXT(property)%%>', urlencode($combo_property->MatchText), $templateCode);
	$templateCode = str_replace('<%%COMBO(unit)%%>', $combo_unit->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(unit)%%>', $combo_unit->MatchText, $templateCode);
	$templateCode = str_replace('<%%URLCOMBOTEXT(unit)%%>', urlencode($combo_unit->MatchText), $templateCode);
	$templateCode = str_replace('<%%COMBO(type)%%>', $combo_type->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(type)%%>', $combo_type->SelectedData, $templateCode);
	$templateCode = str_replace('<%%COMBO(start_date)%%>', ($selected_id && !$arrPerm[3] ? '<div class="form-control-static">' . $combo_start_date->GetHTML(true) . '</div>' : $combo_start_date->GetHTML()), $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(start_date)%%>', $combo_start_date->GetHTML(true), $templateCode);
	$templateCode = str_replace('<%%COMBO(end_date)%%>', ($selected_id && !$arrPerm[3] ? '<div class="form-control-static">' . $combo_end_date->GetHTML(true) . '</div>' : $combo_end_date->GetHTML()), $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(end_date)%%>', $combo_end_date->GetHTML(true), $templateCode);
	$templateCode = str_replace('<%%COMBO(recurring_charges_frequency)%%>', $combo_recurring_charges_frequency->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(recurring_charges_frequency)%%>', $combo_recurring_charges_frequency->SelectedData, $templateCode);
	$templateCode = str_replace('<%%COMBO(next_due_date)%%>', ($selected_id && !$arrPerm[3] ? '<div class="form-control-static">' . $combo_next_due_date->GetHTML(true) . '</div>' : $combo_next_due_date->GetHTML()), $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(next_due_date)%%>', $combo_next_due_date->GetHTML(true), $templateCode);
	$templateCode = str_replace('<%%COMBO(security_deposit_date)%%>', ($selected_id && !$arrPerm[3] ? '<div class="form-control-static">' . $combo_security_deposit_date->GetHTML(true) . '</div>' : $combo_security_deposit_date->GetHTML()), $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(security_deposit_date)%%>', $combo_security_deposit_date->GetHTML(true), $templateCode);

	/* lookup fields array: 'lookup field name' => array('parent table name', 'lookup field caption') */
	$lookup_fields = array(  'tenants' => array('applicants_and_tenants', 'Applicant/ Tenant'), 'property' => array('properties', 'Property'), 'unit' => array('units', 'Unit applied for'));
	foreach($lookup_fields as $luf => $ptfc){
		$pt_perm = getTablePermissions($ptfc[0]);

		// process foreign key links
		if($pt_perm['view'] || $pt_perm['edit']){
			$templateCode = str_replace("<%%PLINK({$luf})%%>", '<button type="button" class="btn btn-default view_parent hspacer-md" id="' . $ptfc[0] . '_view_parent" title="' . html_attr($Translation['View'] . ' ' . $ptfc[1]) . '"><i class="glyphicon glyphicon-eye-open"></i></button>', $templateCode);
		}

		// if user has insert permission to parent table of a lookup field, put an add new button
		if($pt_perm['insert'] && !$_REQUEST['Embedded']){
			$templateCode = str_replace("<%%ADDNEW({$ptfc[0]})%%>", '<button type="button" class="btn btn-success add_new_parent hspacer-md" id="' . $ptfc[0] . '_add_new" title="' . html_attr($Translation['Add New'] . ' ' . $ptfc[1]) . '"><i class="glyphicon glyphicon-plus-sign"></i></button>', $templateCode);
		}
	}

	// process images
	$templateCode = str_replace('<%%UPLOADFILE(id)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(tenants)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(status)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(property)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(unit)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(type)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(total_number_of_occupants)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(start_date)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(end_date)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(recurring_charges_frequency)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(next_due_date)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(rent)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(security_deposit)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(security_deposit_date)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(emergency_contact)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(co_signer_details)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(notes)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(agreement)%%>', '', $templateCode);

	// process values
	if($selected_id){
		if( $dvprint) $templateCode = str_replace('<%%VALUE(id)%%>', safe_html($urow['id']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(id)%%>', html_attr($row['id']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(id)%%>', urlencode($urow['id']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(tenants)%%>', safe_html($urow['tenants']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(tenants)%%>', html_attr($row['tenants']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(tenants)%%>', urlencode($urow['tenants']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(status)%%>', safe_html($urow['status']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(status)%%>', html_attr($row['status']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(status)%%>', urlencode($urow['status']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(property)%%>', safe_html($urow['property']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(property)%%>', html_attr($row['property']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(property)%%>', urlencode($urow['property']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(unit)%%>', safe_html($urow['unit']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(unit)%%>', html_attr($row['unit']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(unit)%%>', urlencode($urow['unit']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(type)%%>', safe_html($urow['type']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(type)%%>', html_attr($row['type']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(type)%%>', urlencode($urow['type']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(total_number_of_occupants)%%>', safe_html($urow['total_number_of_occupants']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(total_number_of_occupants)%%>', html_attr($row['total_number_of_occupants']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(total_number_of_occupants)%%>', urlencode($urow['total_number_of_occupants']), $templateCode);
		$templateCode = str_replace('<%%VALUE(start_date)%%>', @date('m/d/Y', @strtotime(html_attr($row['start_date']))), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(start_date)%%>', urlencode(@date('m/d/Y', @strtotime(html_attr($urow['start_date'])))), $templateCode);
		$templateCode = str_replace('<%%VALUE(end_date)%%>', @date('m/d/Y', @strtotime(html_attr($row['end_date']))), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(end_date)%%>', urlencode(@date('m/d/Y', @strtotime(html_attr($urow['end_date'])))), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(recurring_charges_frequency)%%>', safe_html($urow['recurring_charges_frequency']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(recurring_charges_frequency)%%>', html_attr($row['recurring_charges_frequency']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(recurring_charges_frequency)%%>', urlencode($urow['recurring_charges_frequency']), $templateCode);
		$templateCode = str_replace('<%%VALUE(next_due_date)%%>', @date('m/d/Y', @strtotime(html_attr($row['next_due_date']))), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(next_due_date)%%>', urlencode(@date('m/d/Y', @strtotime(html_attr($urow['next_due_date'])))), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(rent)%%>', safe_html($urow['rent']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(rent)%%>', html_attr($row['rent']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(rent)%%>', urlencode($urow['rent']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(security_deposit)%%>', safe_html($urow['security_deposit']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(security_deposit)%%>', html_attr($row['security_deposit']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(security_deposit)%%>', urlencode($urow['security_deposit']), $templateCode);
		$templateCode = str_replace('<%%VALUE(security_deposit_date)%%>', @date('m/d/Y', @strtotime(html_attr($row['security_deposit_date']))), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(security_deposit_date)%%>', urlencode(@date('m/d/Y', @strtotime(html_attr($urow['security_deposit_date'])))), $templateCode);
		if($dvprint || (!$AllowUpdate && !$AllowInsert)){
			$templateCode = str_replace('<%%VALUE(emergency_contact)%%>', safe_html($urow['emergency_contact']), $templateCode);
		}else{
			$templateCode = str_replace('<%%VALUE(emergency_contact)%%>', html_attr($row['emergency_contact']), $templateCode);
		}
		$templateCode = str_replace('<%%URLVALUE(emergency_contact)%%>', urlencode($urow['emergency_contact']), $templateCode);
		if($dvprint || (!$AllowUpdate && !$AllowInsert)){
			$templateCode = str_replace('<%%VALUE(co_signer_details)%%>', safe_html($urow['co_signer_details']), $templateCode);
		}else{
			$templateCode = str_replace('<%%VALUE(co_signer_details)%%>', html_attr($row['co_signer_details']), $templateCode);
		}
		$templateCode = str_replace('<%%URLVALUE(co_signer_details)%%>', urlencode($urow['co_signer_details']), $templateCode);
		if($AllowUpdate || $AllowInsert){
			$templateCode = str_replace('<%%HTMLAREA(notes)%%>', '<textarea name="notes" id="notes" rows="5">' . html_attr($row['notes']) . '</textarea>', $templateCode);
		}else{
			$templateCode = str_replace('<%%HTMLAREA(notes)%%>', '<div id="notes" class="form-control-static">' . $row['notes'] . '</div>', $templateCode);
		}
		$templateCode = str_replace('<%%VALUE(notes)%%>', nl2br($row['notes']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(notes)%%>', urlencode($urow['notes']), $templateCode);
		$templateCode = str_replace('<%%CHECKED(agreement)%%>', ($row['agreement'] ? "checked" : ""), $templateCode);
	}else{
		$templateCode = str_replace('<%%VALUE(id)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(id)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(tenants)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(tenants)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(status)%%>', 'Application', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(status)%%>', urlencode('Application'), $templateCode);
		$templateCode = str_replace('<%%VALUE(property)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(property)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(unit)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(unit)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(type)%%>', 'Fixed', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(type)%%>', urlencode('Fixed'), $templateCode);
		$templateCode = str_replace('<%%VALUE(total_number_of_occupants)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(total_number_of_occupants)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(start_date)%%>', '1', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(start_date)%%>', urlencode('1'), $templateCode);
		$templateCode = str_replace('<%%VALUE(end_date)%%>', '1', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(end_date)%%>', urlencode('1'), $templateCode);
		$templateCode = str_replace('<%%VALUE(recurring_charges_frequency)%%>', 'Monthly', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(recurring_charges_frequency)%%>', urlencode('Monthly'), $templateCode);
		$templateCode = str_replace('<%%VALUE(next_due_date)%%>', '1', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(next_due_date)%%>', urlencode('1'), $templateCode);
		$templateCode = str_replace('<%%VALUE(rent)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(rent)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(security_deposit)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(security_deposit)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(security_deposit_date)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(security_deposit_date)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(emergency_contact)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(emergency_contact)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(co_signer_details)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(co_signer_details)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%HTMLAREA(notes)%%>', '<textarea name="notes" id="notes" rows="5"></textarea>', $templateCode);
		$templateCode = str_replace('<%%CHECKED(agreement)%%>', '', $templateCode);
	}

	// process translations
	foreach($Translation as $symbol=>$trans){
		$templateCode = str_replace("<%%TRANSLATION($symbol)%%>", $trans, $templateCode);
	}

	// clear scrap
	$templateCode = str_replace('<%%', '<!-- ', $templateCode);
	$templateCode = str_replace('%%>', ' -->', $templateCode);

	// hide links to inaccessible tables
	if($_REQUEST['dvprint_x'] == ''){
		$templateCode .= "\n\n<script>\$j(function(){\n";
		$arrTables = getTableList();
		foreach($arrTables as $name => $caption){
			$templateCode .= "\t\$j('#{$name}_link').removeClass('hidden');\n";
			$templateCode .= "\t\$j('#xs_{$name}_link').removeClass('hidden');\n";
		}

		$templateCode .= $jsReadOnly;
		$templateCode .= $jsEditable;

		if(!$selected_id){
		}

		$templateCode.="\n});</script>\n";
	}

	// ajaxed auto-fill fields
	$templateCode .= '<script>';
	$templateCode .= '$j(function() {';


	$templateCode.="});";
	$templateCode.="</script>";
	$templateCode .= $lookups;

	// handle enforced parent values for read-only lookup fields

	// don't include blank images in lightbox gallery
	$templateCode = preg_replace('/blank.gif" data-lightbox=".*?"/', 'blank.gif"', $templateCode);

	// don't display empty email links
	$templateCode=preg_replace('/<a .*?href="mailto:".*?<\/a>/', '', $templateCode);

	/* default field values */
	$rdata = $jdata = get_defaults('applications_leases');
	if($selected_id){
		$jdata = get_joined_record('applications_leases', $selected_id);
		if($jdata === false) $jdata = get_defaults('applications_leases');
		$rdata = $row;
	}
	$cache_data = array(
		'rdata' => array_map('nl2br', array_map('addslashes', $rdata)),
		'jdata' => array_map('nl2br', array_map('addslashes', $jdata))
	);
	$templateCode .= loadView('applications_leases-ajax-cache', $cache_data);

	// hook: applications_leases_dv
	if(function_exists('applications_leases_dv')){
		$args=array();
		applications_leases_dv(($selected_id ? $selected_id : FALSE), getMemberInfo(), $templateCode, $args);
	}

	return $templateCode;
}
?>