<?php

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

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

function properties_insert(){
	global $Translation;

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

	$data['property_name'] = makeSafe($_REQUEST['property_name']);
		if($data['property_name'] == empty_lookup_value){ $data['property_name'] = ''; }
	$data['type'] = makeSafe($_REQUEST['type']);
		if($data['type'] == empty_lookup_value){ $data['type'] = ''; }
	$data['number_of_units'] = makeSafe($_REQUEST['number_of_units']);
		if($data['number_of_units'] == empty_lookup_value){ $data['number_of_units'] = ''; }
	$data['owner'] = makeSafe($_REQUEST['owner']);
		if($data['owner'] == empty_lookup_value){ $data['owner'] = ''; }
	$data['operating_account'] = makeSafe($_REQUEST['operating_account']);
		if($data['operating_account'] == empty_lookup_value){ $data['operating_account'] = ''; }
	$data['property_reserve'] = makeSafe($_REQUEST['property_reserve']);
		if($data['property_reserve'] == empty_lookup_value){ $data['property_reserve'] = ''; }
	$data['lease_term'] = makeSafe($_REQUEST['lease_term']);
		if($data['lease_term'] == empty_lookup_value){ $data['lease_term'] = ''; }
	$data['country'] = makeSafe($_REQUEST['country']);
		if($data['country'] == empty_lookup_value){ $data['country'] = ''; }
	$data['street'] = makeSafe($_REQUEST['street']);
		if($data['street'] == empty_lookup_value){ $data['street'] = ''; }
	$data['City'] = makeSafe($_REQUEST['City']);
		if($data['City'] == empty_lookup_value){ $data['City'] = ''; }
	$data['State'] = makeSafe($_REQUEST['State']);
		if($data['State'] == empty_lookup_value){ $data['State'] = ''; }
	$data['ZIP'] = makeSafe($_REQUEST['ZIP']);
		if($data['ZIP'] == empty_lookup_value){ $data['ZIP'] = ''; }
	$data['photo'] = PrepareUploadedFile('photo', 2048000,'jpg|jpeg|gif|png', false, '');
	if($data['photo']) createThumbnail($data['photo'], getThumbnailSpecs('properties', 'photo', 'tv'));
	if($data['photo']) createThumbnail($data['photo'], getThumbnailSpecs('properties', 'photo', 'dv'));
	if($data['property_name']== ''){
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">" . $Translation['error:'] . " 'Property Name': " . $Translation['field not null'] . '<br><br>';
		echo '<a href="" onclick="history.go(-1); return false;">'.$Translation['< back'].'</a></div>';
		exit;
	}
	if($data['type']== ''){
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">" . $Translation['error:'] . " 'Type': " . $Translation['field not null'] . '<br><br>';
		echo '<a href="" onclick="history.go(-1); return false;">'.$Translation['< back'].'</a></div>';
		exit;
	}

	/* for empty upload fields, when saving a copy of an existing record, copy the original upload field */
	if($_REQUEST['SelectedID']){
		$res = sql("select * from properties where id='" . makeSafe($_REQUEST['SelectedID']) . "'", $eo);
		if($row = db_fetch_assoc($res)){
			if(!$data['photo']) $data['photo'] = makeSafe($row['photo']);
		}
	}

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

	$o = array('silentErrors' => true);
	sql('insert into `properties` set       `property_name`=' . (($data['property_name'] !== '' && $data['property_name'] !== NULL) ? "'{$data['property_name']}'" : 'NULL') . ', `type`=' . (($data['type'] !== '' && $data['type'] !== NULL) ? "'{$data['type']}'" : 'NULL') . ', `number_of_units`=' . (($data['number_of_units'] !== '' && $data['number_of_units'] !== NULL) ? "'{$data['number_of_units']}'" : 'NULL') . ', ' . ($data['photo'] != '' ? "`photo`='{$data['photo']}'" : '`photo`=NULL') . ', `owner`=' . (($data['owner'] !== '' && $data['owner'] !== NULL) ? "'{$data['owner']}'" : 'NULL') . ', `country`=' . (($data['country'] !== '' && $data['country'] !== NULL) ? "'{$data['country']}'" : 'NULL') . ', `street`=' . (($data['street'] !== '' && $data['street'] !== NULL) ? "'{$data['street']}'" : 'NULL') . ', `City`=' . (($data['City'] !== '' && $data['City'] !== NULL) ? "'{$data['City']}'" : 'NULL') . ', `State`=' . (($data['State'] !== '' && $data['State'] !== NULL) ? "'{$data['State']}'" : 'NULL') . ', `ZIP`=' . (($data['ZIP'] !== '' && $data['ZIP'] !== NULL) ? "'{$data['ZIP']}'" : 'NULL'), $o);
	if($o['error']!=''){
		echo $o['error'];
		echo "<a href=\"properties_view.php?addNew_x=1\">{$Translation['< back']}</a>";
		exit;
	}

	$recID = db_insert_id(db_link());

	// hook: properties_after_insert
	if(function_exists('properties_after_insert')){
		$res = sql("select * from `properties` 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(!properties_after_insert($data, getMemberInfo(), $args)){ return $recID; }
	}

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

	return $recID;
}

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

	// mm: can member delete record?
	$arrPerm=getTablePermissions('properties');
	$ownerGroupID=sqlValue("select groupID from membership_userrecords where tableName='properties' and pkValue='$selected_id'");
	$ownerMemberID=sqlValue("select lcase(memberID) from membership_userrecords where tableName='properties' 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: properties_before_delete
	if(function_exists('properties_before_delete')){
		$args=array();
		if(!properties_before_delete($selected_id, $skipChecks, getMemberInfo(), $args))
			return $Translation['Couldn\'t delete this record'];
	}

	// child table: applications_leases
	$res = sql("select `id` from `properties` where `id`='$selected_id'", $eo);
	$id = db_fetch_row($res);
	$rires = sql("select count(1) from `applications_leases` where `property`='".addslashes($id[0])."'", $eo);
	$rirow = db_fetch_row($rires);
	if($rirow[0] && !$AllowDeleteOfParents && !$skipChecks){
		$RetMsg = $Translation["couldn't delete"];
		$RetMsg = str_replace("<RelatedRecords>", $rirow[0], $RetMsg);
		$RetMsg = str_replace("<TableName>", "applications_leases", $RetMsg);
		return $RetMsg;
	}elseif($rirow[0] && $AllowDeleteOfParents && !$skipChecks){
		$RetMsg = $Translation["confirm delete"];
		$RetMsg = str_replace("<RelatedRecords>", $rirow[0], $RetMsg);
		$RetMsg = str_replace("<TableName>", "applications_leases", $RetMsg);
		$RetMsg = str_replace("<Delete>", "<input type=\"button\" class=\"button\" value=\"".$Translation['yes']."\" onClick=\"window.location='properties_view.php?SelectedID=".urlencode($selected_id)."&delete_x=1&confirmed=1';\">", $RetMsg);
		$RetMsg = str_replace("<Cancel>", "<input type=\"button\" class=\"button\" value=\"".$Translation['no']."\" onClick=\"window.location='properties_view.php?SelectedID=".urlencode($selected_id)."';\">", $RetMsg);
		return $RetMsg;
	}

	// child table: property_photos
	$res = sql("select `id` from `properties` where `id`='$selected_id'", $eo);
	$id = db_fetch_row($res);
	$rires = sql("select count(1) from `property_photos` where `property`='".addslashes($id[0])."'", $eo);
	$rirow = db_fetch_row($rires);
	if($rirow[0] && !$AllowDeleteOfParents && !$skipChecks){
		$RetMsg = $Translation["couldn't delete"];
		$RetMsg = str_replace("<RelatedRecords>", $rirow[0], $RetMsg);
		$RetMsg = str_replace("<TableName>", "property_photos", $RetMsg);
		return $RetMsg;
	}elseif($rirow[0] && $AllowDeleteOfParents && !$skipChecks){
		$RetMsg = $Translation["confirm delete"];
		$RetMsg = str_replace("<RelatedRecords>", $rirow[0], $RetMsg);
		$RetMsg = str_replace("<TableName>", "property_photos", $RetMsg);
		$RetMsg = str_replace("<Delete>", "<input type=\"button\" class=\"button\" value=\"".$Translation['yes']."\" onClick=\"window.location='properties_view.php?SelectedID=".urlencode($selected_id)."&delete_x=1&confirmed=1';\">", $RetMsg);
		$RetMsg = str_replace("<Cancel>", "<input type=\"button\" class=\"button\" value=\"".$Translation['no']."\" onClick=\"window.location='properties_view.php?SelectedID=".urlencode($selected_id)."';\">", $RetMsg);
		return $RetMsg;
	}

	// child table: units
	$res = sql("select `id` from `properties` where `id`='$selected_id'", $eo);
	$id = db_fetch_row($res);
	$rires = sql("select count(1) from `units` where `property`='".addslashes($id[0])."'", $eo);
	$rirow = db_fetch_row($rires);
	if($rirow[0] && !$AllowDeleteOfParents && !$skipChecks){
		$RetMsg = $Translation["couldn't delete"];
		$RetMsg = str_replace("<RelatedRecords>", $rirow[0], $RetMsg);
		$RetMsg = str_replace("<TableName>", "units", $RetMsg);
		return $RetMsg;
	}elseif($rirow[0] && $AllowDeleteOfParents && !$skipChecks){
		$RetMsg = $Translation["confirm delete"];
		$RetMsg = str_replace("<RelatedRecords>", $rirow[0], $RetMsg);
		$RetMsg = str_replace("<TableName>", "units", $RetMsg);
		$RetMsg = str_replace("<Delete>", "<input type=\"button\" class=\"button\" value=\"".$Translation['yes']."\" onClick=\"window.location='properties_view.php?SelectedID=".urlencode($selected_id)."&delete_x=1&confirmed=1';\">", $RetMsg);
		$RetMsg = str_replace("<Cancel>", "<input type=\"button\" class=\"button\" value=\"".$Translation['no']."\" onClick=\"window.location='properties_view.php?SelectedID=".urlencode($selected_id)."';\">", $RetMsg);
		return $RetMsg;
	}

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

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

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

function properties_update($selected_id){
	global $Translation;

	// mm: can member edit record?
	$arrPerm=getTablePermissions('properties');
	$ownerGroupID=sqlValue("select groupID from membership_userrecords where tableName='properties' and pkValue='".makeSafe($selected_id)."'");
	$ownerMemberID=sqlValue("select lcase(memberID) from membership_userrecords where tableName='properties' 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['property_name'] = makeSafe($_REQUEST['property_name']);
		if($data['property_name'] == empty_lookup_value){ $data['property_name'] = ''; }
	if($data['property_name']==''){
		echo StyleSheet() . "\n\n<div class=\"alert alert-danger\">{$Translation['error:']} 'Property Name': {$Translation['field not null']}<br><br>";
		echo '<a href="" onclick="history.go(-1); return false;">'.$Translation['< back'].'</a></div>';
		exit;
	}
	$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:']} 'Type': {$Translation['field not null']}<br><br>";
		echo '<a href="" onclick="history.go(-1); return false;">'.$Translation['< back'].'</a></div>';
		exit;
	}
	$data['number_of_units'] = makeSafe($_REQUEST['number_of_units']);
		if($data['number_of_units'] == empty_lookup_value){ $data['number_of_units'] = ''; }
	$data['owner'] = makeSafe($_REQUEST['owner']);
		if($data['owner'] == empty_lookup_value){ $data['owner'] = ''; }
	$data['operating_account'] = makeSafe($_REQUEST['operating_account']);
		if($data['operating_account'] == empty_lookup_value){ $data['operating_account'] = ''; }
	$data['property_reserve'] = makeSafe($_REQUEST['property_reserve']);
		if($data['property_reserve'] == empty_lookup_value){ $data['property_reserve'] = ''; }
	$data['lease_term'] = makeSafe($_REQUEST['lease_term']);
		if($data['lease_term'] == empty_lookup_value){ $data['lease_term'] = ''; }
	$data['country'] = makeSafe($_REQUEST['country']);
		if($data['country'] == empty_lookup_value){ $data['country'] = ''; }
	$data['street'] = makeSafe($_REQUEST['street']);
		if($data['street'] == empty_lookup_value){ $data['street'] = ''; }
	$data['City'] = makeSafe($_REQUEST['City']);
		if($data['City'] == empty_lookup_value){ $data['City'] = ''; }
	$data['State'] = makeSafe($_REQUEST['State']);
		if($data['State'] == empty_lookup_value){ $data['State'] = ''; }
	$data['ZIP'] = makeSafe($_REQUEST['ZIP']);
		if($data['ZIP'] == empty_lookup_value){ $data['ZIP'] = ''; }
	$data['selectedID']=makeSafe($selected_id);
	if($_REQUEST['photo_remove'] == 1){
		$data['photo'] = '';
	}else{
		$data['photo'] = PrepareUploadedFile('photo', 2048000, 'jpg|jpeg|gif|png', false, "");
		if($data['photo']) createThumbnail($data['photo'], getThumbnailSpecs('properties', 'photo', 'tv'));
		if($data['photo']) createThumbnail($data['photo'], getThumbnailSpecs('properties', 'photo', 'dv'));
	}

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

	$o=array('silentErrors' => true);
	sql('update `properties` set       `property_name`=' . (($data['property_name'] !== '' && $data['property_name'] !== NULL) ? "'{$data['property_name']}'" : 'NULL') . ', `type`=' . (($data['type'] !== '' && $data['type'] !== NULL) ? "'{$data['type']}'" : 'NULL') . ', `number_of_units`=' . (($data['number_of_units'] !== '' && $data['number_of_units'] !== NULL) ? "'{$data['number_of_units']}'" : 'NULL') . ', ' . ($data['photo']!='' ? "`photo`='{$data['photo']}'" : ($_REQUEST['photo_remove'] != 1 ? '`photo`=`photo`' : '`photo`=NULL')) . ', `owner`=' . (($data['owner'] !== '' && $data['owner'] !== NULL) ? "'{$data['owner']}'" : 'NULL') . ', `country`=' . (($data['country'] !== '' && $data['country'] !== NULL) ? "'{$data['country']}'" : 'NULL') . ', `street`=' . (($data['street'] !== '' && $data['street'] !== NULL) ? "'{$data['street']}'" : 'NULL') . ', `City`=' . (($data['City'] !== '' && $data['City'] !== NULL) ? "'{$data['City']}'" : 'NULL') . ', `State`=' . (($data['State'] !== '' && $data['State'] !== NULL) ? "'{$data['State']}'" : 'NULL') . ', `ZIP`=' . (($data['ZIP'] !== '' && $data['ZIP'] !== NULL) ? "'{$data['ZIP']}'" : 'NULL') . " where `id`='".makeSafe($selected_id)."'", $o);
	if($o['error']!=''){
		echo $o['error'];
		echo '<a href="properties_view.php?SelectedID='.urlencode($selected_id)."\">{$Translation['< back']}</a>";
		exit;
	}


	// hook: properties_after_update
	if(function_exists('properties_after_update')){
		$res = sql("SELECT * FROM `properties` 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(!properties_after_update($data, getMemberInfo(), $args)){ return; }
	}

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

}

function properties_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('properties');
	if(!$arrPerm[1] && $selected_id==''){ return ''; }
	$AllowInsert = ($arrPerm[1] ? true : false);
	// print preview?
	$dvprint = false;
	if($selected_id && $_REQUEST['dvprint_x'] != ''){
		$dvprint = true;
	}

	$filterer_owner = thisOr(undo_magic_quotes($_REQUEST['filterer_owner']), '');

	// populate filterers, starting from children to grand-parents

	// unique random identifier
	$rnd1 = ($dvprint ? rand(1000000, 9999999) : '');
	// 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/properties.type.csv')){
		$type_data = addslashes(implode('', @file(dirname(__FILE__).'/hooks/properties.type.csv')));
		$combo_type->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($type_data)));
		$combo_type->ListData = $combo_type->ListItem;
	}else{
		$combo_type->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Residential;;Commercial;;Condo/Townhome;;Multi-Family;;Single-Family;;stores;;office;;shops")));
		$combo_type->ListData = $combo_type->ListItem;
	}
	$combo_type->SelectName = 'type';
	$combo_type->AllowNull = false;
	// combobox: owner
	$combo_owner = new DataCombo;
	// combobox: operating_account
	$combo_operating_account = new Combo;
	$combo_operating_account->ListType = 0;
	$combo_operating_account->MultipleSeparator = ', ';
	$combo_operating_account->ListBoxHeight = 10;
	$combo_operating_account->RadiosPerLine = 1;
	if(is_file(dirname(__FILE__).'/hooks/properties.operating_account.csv')){
		$operating_account_data = addslashes(implode('', @file(dirname(__FILE__).'/hooks/properties.operating_account.csv')));
		$combo_operating_account->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($operating_account_data)));
		$combo_operating_account->ListData = $combo_operating_account->ListItem;
	}else{
		$combo_operating_account->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Operating bank account;;Security deposit bank account")));
		$combo_operating_account->ListData = $combo_operating_account->ListItem;
	}
	$combo_operating_account->SelectName = 'operating_account';
	// combobox: country
	$combo_country = new Combo;
	$combo_country->ListType = 0;
	$combo_country->MultipleSeparator = ', ';
	$combo_country->ListBoxHeight = 10;
	$combo_country->RadiosPerLine = 1;
	if(is_file(dirname(__FILE__).'/hooks/properties.country.csv')){
		$country_data = addslashes(implode('', @file(dirname(__FILE__).'/hooks/properties.country.csv')));
		$combo_country->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($country_data)));
		$combo_country->ListData = $combo_country->ListItem;
	}else{
		$combo_country->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("Afghanistan;;Albania;;Algeria;;American Samoa;;Andorra;;Angola;;Anguilla;;Antarctica;;Antigua, Barbuda;;Argentina;;Armenia;;Aruba;;Australia;;Austria;;Azerbaijan;;Bahamas;;Bahrain;;Bangladesh;;Barbados;;Belarus;;Belgium;;Belize;;Benin;;Bermuda;;Bhutan;;Bolivia;;Bosnia, Herzegovina;;Botswana;;Bouvet Is.;;Brazil;;Brunei Darussalam;;Bulgaria;;Burkina Faso;;Burundi;;Cambodia;;Cameroon;;Canada;;Canary Is.;;Cape Verde;;Cayman Is.;;Central African Rep.;;Chad;;Channel Islands;;Chile;;China;;Christmas Is.;;Cocos Is.;;Colombia;;Comoros;;Congo, D.R. Of;;Congo;;Cook Is.;;Costa Rica;;Croatia;;Cuba;;Cyprus;;Czech Republic;;Denmark;;Djibouti;;Dominica;;Dominican Republic;;Ecuador;;Egypt;;El Salvador;;Equatorial Guinea;;Eritrea;;Estonia;;Ethiopia;;Falkland Is.;;Faroe Is.;;Fiji;;Finland;;France;;French Guiana;;French Polynesia;;French Territories;;Gabon;;Gambia;;Georgia;;Germany;;Ghana;;Gibraltar;;Greece;;Greenland;;Grenada;;Guadeloupe;;Guam;;Guatemala;;Guernsey;;Guinea-bissau;;Guinea;;Guyana;;Haiti;;Heard, Mcdonald Is.;;Honduras;;Hong Kong;;Hungary;;Iceland;;India;;Indonesia;;Iran;;Iraq;;Ireland;;Israel;;Italy;;Ivory Coast;;Jamaica;;Japan;;Jersey;;Jordan;;Kazakhstan;;Kenya;;Kiribati;;Korea, D.P.R Of;;Korea, Rep. Of;;Kuwait;;Kyrgyzstan;;Lao Peoples D.R.;;Latvia;;Lebanon;;Lesotho;;Liberia;;Libyan Arab Jamahiriya;;Liechtenstein;;Lithuania;;Luxembourg;;Macao;;Macedonia, F.Y.R Of;;Madagascar;;Malawi;;Malaysia;;Maldives;;Mali;;Malta;;Mariana Islands;;Marshall Islands;;Martinique;;Mauritania;;Mauritius;;Mayotte;;Mexico;;Micronesia;;Moldova;;Monaco;;Mongolia;;Montserrat;;Morocco;;Mozambique;;Myanmar;;Namibia;;Nauru;;Nepal;;Netherlands Antilles;;Netherlands;;New Caledonia;;New Zealand;;Nicaragua;;Niger;;Nigeria;;Niue;;Norfolk Island;;Norway;;Oman;;Pakistan;;Palau;;Palestinian Terr.;;Panama;;Papua New Guinea;;Paraguay;;Peru;;Philippines;;Pitcairn;;Poland;;Portugal;;Puerto Rico;;Qatar;;Reunion;;Romania;;Russian Federation;;Rwanda;;Samoa;;San Marino;;Sao Tome, Principe;;Saudi Arabia;;Senegal;;Seychelles;;Sierra Leone;;Singapore;;Slovakia;;Slovenia;;Solomon Is.;;Somalia;;South Africa;;South Georgia;;South Sandwich Is.;;Spain;;Sri Lanka;;St. Helena;;St. Kitts, Nevis;;St. Lucia;;St. Pierre, Miquelon;;St. Vincent, Grenadines;;Sudan;;Suriname;;Svalbard, Jan Mayen;;Swaziland;;Sweden;;Switzerland;;Syrian Arab Republic;;Taiwan;;Tajikistan;;Tanzania;;Thailand;;Timor-leste;;Togo;;Tokelau;;Tonga;;Trinidad, Tobago;;Tunisia;;Turkey;;Turkmenistan;;Turks, Caicoss;;Tuvalu;;Uganda;;Ukraine;;United Arab Emirates;;United Kingdom;;United States;;Uruguay;;Uzbekistan;;Vanuatu;;Vatican City;;Venezuela;;Viet Nam;;Virgin Is. British;;Virgin Is. U.S.;;Wallis, Futuna;;Western Sahara;;Yemen;;Yugoslavia;;Zambia;;Zimbabwe")));
		$combo_country->ListData = $combo_country->ListItem;
	}
	$combo_country->SelectName = 'country';
	// combobox: State
	$combo_State = new Combo;
	$combo_State->ListType = 0;
	$combo_State->MultipleSeparator = ', ';
	$combo_State->ListBoxHeight = 10;
	$combo_State->RadiosPerLine = 1;
	if(is_file(dirname(__FILE__).'/hooks/properties.State.csv')){
		$State_data = addslashes(implode('', @file(dirname(__FILE__).'/hooks/properties.State.csv')));
		$combo_State->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions($State_data)));
		$combo_State->ListData = $combo_State->ListItem;
	}else{
		$combo_State->ListItem = explode('||', entitiesToUTF8(convertLegacyOptions("AL;;AK;;AS;;AZ;;AR;;CA;;CO;;CT;;DE;;DC;;FM;;FL;;GA;;GU;;HI;;ID;;IL;;IN;;IA;;KS;;KY;;LA;;ME;;MH;;MD;;MA;;MI;;MN;;MS;;MO;;MT;;NE;;NV;;NH;;NJ;;NM;;NY;;NC;;ND;;MP;;OH;;OK;;OR;;PW;;PA;;PR;;RI;;SC;;SD;;TN;;TX;;UT;;VT;;VI;;VA;;WA;;WV;;WI;;WY")));
		$combo_State->ListData = $combo_State->ListItem;
	}
	$combo_State->SelectName = 'State';

	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='properties' and pkValue='".makeSafe($selected_id)."'");
		$ownerMemberID=sqlValue("select lcase(memberID) from membership_userrecords where tableName='properties' 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 `properties` where `id`='".makeSafe($selected_id)."'", $eo);
		if(!($row = db_fetch_array($res))){
			return error_message($Translation['No records found'], 'properties_view.php', false);
		}
		$urow = $row; /* unsanitized data */
		$hc = new CI_Input();
		$row = $hc->xss_clean($row); /* sanitize data */
		$combo_type->SelectedData = $row['type'];
		$combo_owner->SelectedData = $row['owner'];
		$combo_operating_account->SelectedData = $row['operating_account'];
		$combo_country->SelectedData = $row['country'];
		$combo_State->SelectedData = $row['State'];
	}else{
		$combo_type->SelectedText = ( $_REQUEST['FilterField'][1]=='3' && $_REQUEST['FilterOperator'][1]=='<=>' ? (get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1]) : "");
		$combo_owner->SelectedData = $filterer_owner;
		$combo_operating_account->SelectedText = ( $_REQUEST['FilterField'][1]=='7' && $_REQUEST['FilterOperator'][1]=='<=>' ? (get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1]) : "");
		$combo_country->SelectedText = ( $_REQUEST['FilterField'][1]=='10' && $_REQUEST['FilterOperator'][1]=='<=>' ? (get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1]) : "");
		$combo_State->SelectedText = ( $_REQUEST['FilterField'][1]=='13' && $_REQUEST['FilterOperator'][1]=='<=>' ? (get_magic_quotes_gpc() ? stripslashes($_REQUEST['FilterValue'][1]) : $_REQUEST['FilterValue'][1]) : "");
	}
	$combo_type->Render();
	$combo_owner->HTML = '<span id="owner-container' . $rnd1 . '"></span><input type="hidden" name="owner" id="owner' . $rnd1 . '" value="' . html_attr($combo_owner->SelectedData) . '">';
	$combo_owner->MatchText = '<span id="owner-container-readonly' . $rnd1 . '"></span><input type="hidden" name="owner" id="owner' . $rnd1 . '" value="' . html_attr($combo_owner->SelectedData) . '">';
	$combo_operating_account->Render();
	$combo_country->Render();
	$combo_State->Render();

	ob_start();
	?>

	<script>
		// initial lookup values
		AppGini.current_owner__RAND__ = { text: "", value: "<?php echo addslashes($selected_id ? $urow['owner'] : $filterer_owner); ?>"};

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

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


							if(typeof(owner_update_autofills__RAND__) == 'function') owner_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: 'properties', f: 'owner' }; },
					results: function(resp, page){ return resp; }
				},
				escapeMarkup: function(str){ return str; }
			}).on('change', function(e){
				AppGini.current_owner__RAND__.value = e.added.id;
				AppGini.current_owner__RAND__.text = e.added.text;
				$j('[name="owner"]').val(e.added.id);
				if(e.added.id == '<?php echo empty_lookup_value; ?>'){ $j('.btn[id=rental_owners_view_parent]').hide(); }else{ $j('.btn[id=rental_owners_view_parent]').show(); }


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

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

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

		<?php }else{ ?>

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

					if(typeof(owner_update_autofills__RAND__) == 'function') owner_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/properties_templateDVP.html';
		$templateCode = @file_get_contents($template_file);
	}else{
		$template_file = is_file("./{$TemplateDV}") ? "./{$TemplateDV}" : './templates/properties_templateDV.html';
		$templateCode = @file_get_contents($template_file);
	}

	// process form title
	$templateCode = str_replace('<%%DETAIL_VIEW_TITLE%%>', 'Property details', $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 properties_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 properties_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 properties_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('#property_name').replaceWith('<div class=\"form-control-static\" id=\"property_name\">' + (jQuery('#property_name').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('input[name=type]').parent().html('<div class=\"form-control-static\">' + jQuery('input[name=type]:checked').next().text() + '</div>')\n";
		$jsReadOnly .= "\tjQuery('#number_of_units').replaceWith('<div class=\"form-control-static\" id=\"number_of_units\">' + (jQuery('#number_of_units').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#photo').replaceWith('<div class=\"form-control-static\" id=\"photo\">' + (jQuery('#photo').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#owner').prop('disabled', true).css({ color: '#555', backgroundColor: '#fff' });\n";
		$jsReadOnly .= "\tjQuery('#owner_caption').prop('disabled', true).css({ color: '#555', backgroundColor: 'white' });\n";
		$jsReadOnly .= "\tjQuery('#country').replaceWith('<div class=\"form-control-static\" id=\"country\">' + (jQuery('#country').val() || '') + '</div>'); jQuery('#country-multi-selection-help').hide();\n";
		$jsReadOnly .= "\tjQuery('#street').replaceWith('<div class=\"form-control-static\" id=\"street\">' + (jQuery('#street').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#City').replaceWith('<div class=\"form-control-static\" id=\"City\">' + (jQuery('#City').val() || '') + '</div>');\n";
		$jsReadOnly .= "\tjQuery('#State').replaceWith('<div class=\"form-control-static\" id=\"State\">' + (jQuery('#State').val() || '') + '</div>'); jQuery('#State-multi-selection-help').hide();\n";
		$jsReadOnly .= "\tjQuery('#ZIP').replaceWith('<div class=\"form-control-static\" id=\"ZIP\">' + (jQuery('#ZIP').val() || '') + '</div>');\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(type)%%>', $combo_type->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(type)%%>', $combo_type->SelectedData, $templateCode);
	$templateCode = str_replace('<%%COMBO(owner)%%>', $combo_owner->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(owner)%%>', $combo_owner->MatchText, $templateCode);
	$templateCode = str_replace('<%%URLCOMBOTEXT(owner)%%>', urlencode($combo_owner->MatchText), $templateCode);
	$templateCode = str_replace('<%%COMBO(operating_account)%%>', $combo_operating_account->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(operating_account)%%>', $combo_operating_account->SelectedData, $templateCode);
	$templateCode = str_replace('<%%COMBO(country)%%>', $combo_country->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(country)%%>', $combo_country->SelectedData, $templateCode);
	$templateCode = str_replace('<%%COMBO(State)%%>', $combo_State->HTML, $templateCode);
	$templateCode = str_replace('<%%COMBOTEXT(State)%%>', $combo_State->SelectedData, $templateCode);

	/* lookup fields array: 'lookup field name' => array('parent table name', 'lookup field caption') */
	$lookup_fields = array(  'owner' => array('rental_owners', 'Owner'));
	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(property_name)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(type)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(number_of_units)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(photo)%%>', ($noUploads ? '' : '<input type=hidden name=MAX_FILE_SIZE value=2048000>'.$Translation['upload image'].' <input type="file" name="photo" id="photo">'), $templateCode);
	if($AllowUpdate && $row['photo'] != ''){
		$templateCode = str_replace('<%%REMOVEFILE(photo)%%>', '<br><input type="checkbox" name="photo_remove" id="photo_remove" value="1"> <label for="photo_remove" style="color: red; font-weight: bold;">'.$Translation['remove image'].'</label>', $templateCode);
	}else{
		$templateCode = str_replace('<%%REMOVEFILE(photo)%%>', '', $templateCode);
	}
	$templateCode = str_replace('<%%UPLOADFILE(owner)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(operating_account)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(property_reserve)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(lease_term)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(country)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(street)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(City)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(State)%%>', '', $templateCode);
	$templateCode = str_replace('<%%UPLOADFILE(ZIP)%%>', '', $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(property_name)%%>', safe_html($urow['property_name']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(property_name)%%>', html_attr($row['property_name']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(property_name)%%>', urlencode($urow['property_name']), $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(number_of_units)%%>', safe_html($urow['number_of_units']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(number_of_units)%%>', html_attr($row['number_of_units']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(number_of_units)%%>', urlencode($urow['number_of_units']), $templateCode);
		$row['photo'] = ($row['photo'] != '' ? $row['photo'] : 'blank.gif');
		if( $dvprint) $templateCode = str_replace('<%%VALUE(photo)%%>', safe_html($urow['photo']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(photo)%%>', html_attr($row['photo']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(photo)%%>', urlencode($urow['photo']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(owner)%%>', safe_html($urow['owner']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(owner)%%>', html_attr($row['owner']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(owner)%%>', urlencode($urow['owner']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(operating_account)%%>', safe_html($urow['operating_account']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(operating_account)%%>', html_attr($row['operating_account']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(operating_account)%%>', urlencode($urow['operating_account']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(property_reserve)%%>', safe_html($urow['property_reserve']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(property_reserve)%%>', html_attr($row['property_reserve']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(property_reserve)%%>', urlencode($urow['property_reserve']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(lease_term)%%>', safe_html($urow['lease_term']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(lease_term)%%>', html_attr($row['lease_term']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(lease_term)%%>', urlencode($urow['lease_term']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(country)%%>', safe_html($urow['country']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(country)%%>', html_attr($row['country']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(country)%%>', urlencode($urow['country']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(street)%%>', safe_html($urow['street']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(street)%%>', html_attr($row['street']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(street)%%>', urlencode($urow['street']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(City)%%>', safe_html($urow['City']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(City)%%>', html_attr($row['City']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(City)%%>', urlencode($urow['City']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(State)%%>', safe_html($urow['State']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(State)%%>', html_attr($row['State']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(State)%%>', urlencode($urow['State']), $templateCode);
		if( $dvprint) $templateCode = str_replace('<%%VALUE(ZIP)%%>', safe_html($urow['ZIP']), $templateCode);
		if(!$dvprint) $templateCode = str_replace('<%%VALUE(ZIP)%%>', html_attr($row['ZIP']), $templateCode);
		$templateCode = str_replace('<%%URLVALUE(ZIP)%%>', urlencode($urow['ZIP']), $templateCode);
	}else{
		$templateCode = str_replace('<%%VALUE(id)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(id)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(property_name)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(property_name)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(type)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(type)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(number_of_units)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(number_of_units)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(photo)%%>', 'blank.gif', $templateCode);
		$templateCode = str_replace('<%%VALUE(owner)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(owner)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(operating_account)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(operating_account)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(property_reserve)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(property_reserve)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(lease_term)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(lease_term)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(country)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(country)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(street)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(street)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(City)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(City)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(State)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(State)%%>', urlencode(''), $templateCode);
		$templateCode = str_replace('<%%VALUE(ZIP)%%>', '', $templateCode);
		$templateCode = str_replace('<%%URLVALUE(ZIP)%%>', urlencode(''), $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('properties');
	if($selected_id){
		$jdata = get_joined_record('properties', $selected_id);
		if($jdata === false) $jdata = get_defaults('properties');
		$rdata = $row;
	}
	$cache_data = array(
		'rdata' => array_map('nl2br', array_map('addslashes', $rdata)),
		'jdata' => array_map('nl2br', array_map('addslashes', $jdata))
	);
	$templateCode .= loadView('properties-ajax-cache', $cache_data);

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

	return $templateCode;
}
?>