#! /usr/bin/perl
#########################################################################
# ImmoEngine-PageMirror/1.81 UN!X (29.04.2008) - Commercial		#
#									#
#									#
# Needed Packages (or newer):						#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~						#
# = Included in Perl:							#
#   ~~~~~~~~~~~~~~~~~							#
#   - perl		5.6.0		- [1]				#
#   - strict		1.01		- [1]				#
#   - Fcntl		1.03		- [1]				#
#   - POSIX		?.??		- [1]				#
#   - locale		?.??		- [1]				#
#   - CGI		?.??		- [1]				#
#   - CGI::Carp		?.??		- [1]				#
#   - CGI::Cookie	?.??		- [1]				#
#   - File::Path	1.05		- [1]				#
#									#
# = Additional needed Packages:						#
#   ~~~~~~~~~~~~~~~~~~~~~~~~~~~						#
#   - mod_perl		1.26		- [2]				#
#   - Apache		1.27		- [2]				#
#   - Time::HiRes	1.20		- [3]				#
#   - URI::Escape	3.20		- [4]				#
#   - Date::Calc	5.0		- [5]				#
#   - HTML::Entities	1.15		- [6]				#
#   - Digest::CRC	0.09		- [7]				#
#   - Digest::MD5	2.24		- [8]				#
#   - DBI		1.14		- [9]				#
#   - Image::Magick	5.24		- [10]				#
#									#
# (1)  http://www.cpan.org/ports/index.html				#
# (2)  http://perl.apache.org/dist/mod_perl-1.26.tar.gz			#
# (3)  http://cpan.org/authors/id/DEWEG/Time-HiRes-01.20.tar.gz		#
# (4)  http://cpan.org/authors/id/G/GA/GAAS/URI-1.19.tar.gz		#
# (5)  http://cpan.org/authors/id/STBEY/Date-Calc-5.0.tar.gz		#
# (6)  http://cpan.org/authors/id/G/GA/GAAS/HTML-Parser-3.28.tar.gz	#
# (7)  http://cpan.org/authors/id/O/OL/OLIMAUL/Digest-CRC-0.09.tar.gz	#
# (8)  									#
# (9)  http://cpan.org/authors/id/T/TI/TIMB/DBI-1.14.tar.gz		#
# (10) http://www.imagemagick.org/					#
#									#
# Copyright (c) 2001-2008 by Michael Diekmann, All Rights Reserved.	#
#########################################################################
#									#
#	   C o n f i g u r a t i o n   b e g i n s   h e r e		#
#/---------------------------------------------------------------------\#
my $PortalDomain = 'Bremerhaven-Immo.de';				# without "www."!!!

my %cfg = (
	# Config for Engine
	MailOnError			=> '400|401|403|405|406|408|409|410|415|500|501|503|505',
	MailProg			=> '/usr/lib/sendmail -oi -t -f %r',	# %r will be replaced with an email-address
#	MailProg			=> '/var/qmail/bin/qmail-inject -f %r',	# %r will be replaced with an email-address

	HtmlTemplateLayout		=> '/.templates/',
	ThousandsSeperator		=> '.',
	DecimalPoint			=> ',',


	# Config for Database-Connection
	DB_Interface			=> 'DBI',				# DBI is recommend.
	DB_Driver			=> 'mysql',				# Currently only MySQL is supported
	DB_DriverSpecials		=> 'mysql_enable_utf8=1',		# Add more with ";" separated
	DB_Server			=> 'database.ips-siedenburg.de',	# Host where Database-Server is running on
	DB_Port				=> '3306',				# Port where Database-Server is listening on
	DB_Name				=> 'ImmoEngine',			# Name of the Database
	DB_User				=> 'ieID37_RO',				# Username for Login
	DB_Password			=> 'sobifuxa',				# Password for Login
	DB_RaiseError			=> '0',					# Database-Server RaiseError
	DB_PrintError			=> '1',					# Database-Server PrintError


	# Config for Mirror
	CustomerId			=> '37',				# This is the CustomerId, DO NOT CHANGE!!!
	ShowObjectCounter		=> '1',					# Should the Counter of Object be showed?
	ShowMaxEntries			=> '10',				# On listing the Content at each page
	MailAddress			=> 'buero@vosshans.de',			# Only for test
	MailAddressWebmaster		=> 'buero@vosshans.de',			# Only for test
	MirrorHomepageUrl		=> 'www.vosshans.de',
	ImageUploadUrl			=> "http://www.$PortalDomain/.images-uploaded/",	# Starting from $ENV{'DOCUMENT_ROOT'}
	LogoUploadUrl			=> "http://www.$PortalDomain/.logos-uploaded/",		# Starting from $ENV{'DOCUMENT_ROOT'}
	UploadImageExtention		=> '.jpg',
	ImageTypes			=> 'Titelbild,Grundriß,Optional,Energiepass',	# Order: 0,1,2,3

	DefaultCharacterSet		=> 'UTF-8',
	DefaultMimeCharset		=> 'UTF-8',
	DefaultMimeEncoding		=> 'quoted-printable',

	CookieExpires			=> '157680000',				# Seconds: How long should the User-Cookie should saved in seconds? Currenty 5 years
	TransmitMethodEndUser		=> 'GET',

	# Change if you know what you´re doing!
	Alarm				=> 600,					# Change to 600 (10 min.) on Production-Server (needed so high for Uploads!)
	DEBUG				=> 0,					# Turn DEBUGGING on?
	JumpIntoCategorieIfOnlyOne	=> 1,

	# Attention! DO NEVER USE e.g. $ENV{'DOCUMENT_ROOT'}!!!!
	DOCUMENT_ROOT			=> '/var/www/vhosts/vosshans.de/httpdocs/',
);

#\---------------------------------------------------------------------/#
#	     C o n f i g u r a t i o n   e n d s   h e r e		#
#									#
#########################################################################
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! #
# !!! DOT NOT EDIT ANYTHING BELOW THIS LINE OR SUPPORT WILL BE LOST !!! #
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! #
#########################################################################

	package ImmoEngine::PageMirror;

	my %error_codes = (
		'001'	=> 'Pfad existiert, aber kein Inhalt hinterlegt',
		'400'	=> 'Fehlerhafte Anfrage',
		'401'	=> 'Nicht autorisiert',
		'402'	=> 'Zugriff nur nach Bezahlung',
		'403'	=> 'Zugriff eingeschränkt',
		'404'	=> 'Ressource nicht gefunden',
		'405'	=> 'Zugriffsmethode nicht erlaubt',
		'406'	=> 'Nicht akzeptabel',
		'407'	=> 'Proxy erfordert Autorisierung',
		'408'	=> 'Zeitüberschreitung',
		'409'	=> 'Konflikt',
		'410'	=> 'Nicht mehr vorhanden',
		'411'	=> 'Längenangabe erforderlich',
		'412'	=> 'Voraussetzung nicht erfüllt',
		'413'	=> 'Anforderung zu lang',
		'414'	=> 'Anforderungs-URI zu lang',
		'415'	=> 'Nicht unterstütztes Medien-Typ',
		'500'	=> 'Interner Server Fehler',
		'501'	=> 'Nicht Implementiert',
		'502'	=> 'Bad Gateway',
		'503'	=> 'Service Unavailable',
		'504'	=> 'Gateway Time-out',
		'505'	=> 'HTTP Version nicht unterstützt',
		'506'	=> 'Variant Also Varies',
	);

	my %Month = (
		'1'	=> 'Januar',
		'2'	=> 'Februar',
		'3'	=> 'März',
		'4'	=> 'April',
		'5'	=> 'Mai',
		'6'	=> 'Juni',
		'7'	=> 'Juli',
		'8'	=> 'August',
		'9'	=> 'September',
		'10'	=> 'Oktober',
		'11'	=> 'November',
		'12'	=> 'Dezember',
	);

	require 5.6.0;
	use strict 1.01;
	use Fcntl 1.03 qw(:DEFAULT :flock);
	use POSIX qw(locale_h strtod);
	use locale;
	use DBI 1.14;
	use CGI qw/:standard/;						# Used in get_query() for $q->upload()
	use CGI::Carp ('fatalsToBrowser');
	use CGI::Cookie;
	use Email::Valid 0.15;
	use MIME::Lite;
	use MIME::Words qw(encode_mimewords);

	use URI::Escape 3.20;
	use HTML::Entities 1.15;
	use Digest::MD5;
	use Date::Pcalc qw(Add_Delta_Days);
	setpriority (0, 0, 10);

	my $VERSION = '1.81';

#	binmode(STDOUT, ":encoding(utf8)");


	# "die" and "exit" goes to own sub
	local $SIG{'__DIE__'} = $SIG{'QUIT'} = sub {
		sql_close();						# Disconnect from Database
		print STDERR @_;
		exit();
	};

	# Harakiri if needed
	local $SIG{'ALRM'} = sub {
		sql_close();						# Disconnect from Database
		print STDERR "$0: Timed out (reached $cfg{'Alarm'} sec.)";
		exit();
	};
	alarm($cfg{'Alarm'});

	# Reset the $^T variable, so -M file test give the correct time (needed for mod_perl).
	local $^T = time;


	# Get querys.
	my $q = new CGI;
	my %query = get_query();
	$query{'Limit'} = 0 unless $query{'Limit'};			# Preset Limit


	# Load the Cookie-Data to know:
	#	1. What Portal-Design we must load (only needed for /Admin/ !!!)
	#	2. What VisitorId (VID) and VisitorPasswd (VPD)
	my %cookie = convert_cookie();


	# Connect to Database
	sql_connect();

	# Make sure we send them in "utf8"
	sql_do("SET NAMES utf8");
	sql_do("SET CHARACTER SET utf8");


	my $today = sprintf("%04d-%02d-%02d", reverse Date() );
	my $time = sprintf("%02d:%02d:%02d", Time() );

	# Load the Template
	my $HtmlTemplate = undef;
	if (($query{'Action'} eq 'Preview') || ($query{'Action'} eq 'Print')) {
		$HtmlTemplate = read_file("$cfg{'HtmlTemplateLayout'}Print.html");
	}
	elsif ($query{'Action'} eq 'Floorplan') {
		$HtmlTemplate = read_file("$cfg{'HtmlTemplateLayout'}Floorplan.html");
	}
	elsif ($query{'Action'} eq 'EnergyCertificate') {
		$HtmlTemplate = read_file("$cfg{'HtmlTemplateLayout'}EnergyCertificate.html");
	}
	else {
		$HtmlTemplate = read_file("$cfg{'HtmlTemplateLayout'}Default.html");
	}

	# Set the needed Cookie
	my %set_cookies = undef;

	# Here we count all Estates in the DB for the CategorieGroups
	my ($rent_counter, $buy_counter, $industry_counter);
	if (($cfg{'ShowObjectCounter'}) || ($cfg{'DEMO_MODE'})) {
		$rent_counter = sql_selectall("SELECT COUNT(EstateId) FROM Estate WHERE CategorieGroupId='1' AND Active='1' AND EndDate>='$today' AND CustomerId='$cfg{'CustomerId'}'");
		$buy_counter = sql_selectall("SELECT COUNT(EstateId) FROM Estate WHERE CategorieGroupId='2' AND Active='1' AND EndDate>='$today' AND CustomerId='$cfg{'CustomerId'}'");
		$industry_counter = sql_selectall("SELECT COUNT(EstateId) FROM Estate WHERE CategorieGroupId='3' AND Active='1' AND EndDate>='$today' AND CustomerId='$cfg{'CustomerId'}'");
	}


	# Send HTTP-Header
	http_header('0', 'text/html', %set_cookies);




	# Get the Content
	my $content = undef;
	my %db_content = ();
	if ($query{'Action'} eq 'SelectCategorie') {
		$content .= SelectCategorie();
	}
	elsif ($query{'Action'} eq 'ShowCategorie') {
		$content .= ShowCategorie();
	}
	elsif ($query{'Action'} eq 'ShowSynopsis') {
		$content .= ShowSynopsis();
	}
	elsif ($query{'Action'} eq 'Floorplan') {
		$content .= ShowFloorplan($query{'EstateId'}, $query{'ImageId'});
	}
	elsif ($query{'Action'} eq 'EnergyCertificate') {
		$content .= ShowEnergyCertificate($query{'EstateId'}, $query{'ImageId'});
	}
	elsif ($query{'Action'} eq 'Contact') {
		$content .= ContactForm();
	}
	elsif ($query{'Action'} eq 'Send') {
		$content .= CheckForm();
	}
	elsif ($query{'Action'} eq 'Print') {
		$content .= ShowSynopsis('Print');
	}
	else {
		if ( ($rent_counter) && (!$buy_counter) && (!$industry_counter) ) {
			$query{'CategorieGroupId'} = 1;
			$content .= SelectCategorie();
		}
		elsif ( (!$rent_counter) && ($buy_counter) && (!$industry_counter) ) {
			$query{'CategorieGroupId'} = 2;
			$content .= SelectCategorie();
		}
		elsif ( (!$rent_counter) && (!$buy_counter) && ($industry_counter) ) {
			$query{'CategorieGroupId'} = 3;
			$content .= SelectCategorie();
		}
		else {
			$content .= ShowMainpage();
		}
	}


	$HtmlTemplate =~ s/__PORTAL_DOMAIN__/$PortalDomain/g;
	$HtmlTemplate =~ s/__VERSION__/Project::ImmoEngine\/$VERSION by www.aikon-media.de/g;
	$HtmlTemplate =~ s/__CHARSET__/$cfg{'DefaultCharacterSet'}/g;


	$content .= "<br><br><div style=\"font-family:'Tahoma','Arial','Sans';font-size:8pt;color:#EEEEEE;background-color:#2F5697;padding:5px;padding-left:10px\">Powered by <a href=\"http://www.$PortalDomain/\" target=\"_blank\" title=\"ImmoMirror/$VERSION &copy; 2003-2008 $PortalDomain\" style=\"font-family:'Tahoma','Arial','Sans';font-size:8pt;color:#EEEEEE;\">$PortalDomain</a></div><br>\n";
	if ($content) {
		$HtmlTemplate =~ s/__CONTENT__/$content/;
	}
	else {
		$HtmlTemplate =~ s/__CONTENT__//;
	}





	# Print the HTML-Site
	print "$HtmlTemplate\n";
	$HtmlTemplate = undef;

	# Disconnect from Database
	sql_close();

	close(STDERR);
	exit();

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub get_query {
	my %in = ();
	my %seen = ();
	my @names = $q->param();
	@names = grep { ! $seen{$_}++ } @names;

	foreach my $name (@names) {
		$name =~ s/\0//g;					# Remove all NULL-Bytes from the Keys
		if ($seen{$name}) {
			$in{$name} = join('|', $q->param($name) );
		}
		else {
			$in{$name} = $q->param($name);
		}
		$in{$name} =~ s/\0//g;					# Remove all NULL-Bytes from the Values
	}
	return %in;
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub http_header ($$%) {
	my $expires = shift;
	my $content_type = shift;
    	my (%cookie) = @_;

	print "Date: ". gmtime(time) ." GMT\n";
	print "Last-Modified: ". gmtime(time) ." GMT\n";
	print "Expires: ". gmtime(time + $expires) ." GMT\n";
	print "Server: ". $ENV{'SERVER_SOFTWARE'} ."\n";
	print "Pragma: no-cache\n";
	print "Cache-Control: private\n";
	print "Content-Type: ". $content_type ."; charset=\"$cfg{'DefaultCharacterSet'}\"\n\n";
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub read_file ($) {
	my $file = $ENV{'DOCUMENT_ROOT'} . shift;

	if ((-f "$file") && (-R "$file")) {
		my $out = undef;
		sysopen(FILE, "$file", O_RDONLY) || warn "$ENV{'SCRIPT_FILENAME'}: sysopen $file: $!" && return undef;
			flock(FILE, LOCK_SH);
			while (<FILE>) {
				$out .= $_;
			}
		close(FILE);
		return $out;
	}
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub error_page ($) {
	my $error_number = shift;

my $content = <<EOL;

<!-- BEGIN ERROR_DOCUMENT -->
<h1>$error_number - $error_codes{"$error_number"}</h1>
<h3>$ENV{'REQUEST_URI'}</h3>
<p>
EOL
	if ($error_number =~ /^($cfg{'MailOnError'})$/) {
		my $body = undef;
		foreach my $key (sort (keys %ENV)) {
			$body .= "$key". '.' x (36 - length($key)) .": $ENV{$key}\n";
		}
		send_error_mail(
			$cfg{'MailAddressWebmaster'},									# From
			$cfg{'MailAddressWebmaster'},									# To
			"[$ENV{'SERVER_NAME'}] Error \"$error_codes{$error_number}\" ($error_number) occurred!",	# Subject
			$body,												# Body
		);
		$content .= "<p>Der Portal-Betreiber wurde soeben per Email über diese Fehlermeldung informiert!</p>";
	}

	$content .= 'Datum: '. sprintf("%02d.%02d.%04d", Date() ) ."<br>\n";
	$content .= 'Uhrzeit: '. sprintf("%02d:%02d:%02d", Time() ) ."<br>\n";
	$content .= "Ihre IP-Adresse: $ENV{'REMOTE_ADDR'}<br>\n";
	$content .= "Ihre Browser: $ENV{'HTTP_USER_AGENT'}<br>\n";

$content .= <<EOL;
</p>
<!-- END ERROR_DOCUMENT -->

EOL
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub encode_entities {
	local @_ = @_;
	foreach (@_) {
		$_ = HTML::Entities::encode($_, "\200-\377");
	}
	return wantarray ? @_ : "@_";
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub send_error_mail ($$$$) {
	my $from = shift;
	my $to = shift;
	my $subject = shift;
	my $body = shift;

	# Secure $to and $from
	$to =~ tr/\r\n\t\f\0//d;
	$from =~ tr/\r\n\t\f\0//d;

	my $mailer = $cfg{'MailProg'};
	$mailer =~ s/\%r/$to/g;

        open(MAIL, "| $mailer") || warn "$ENV{'SCRIPT_FILENAME'}: pipe $mailer: $!\n" && return 0;
                print MAIL ("To: $to\n");
                print MAIL ("From: $from\n");
                print MAIL ("Subject: $subject\n");
	        print MAIL ("X-Mailer: Project::ImmoEngine/$VERSION produced by http://www.aikon-media.de/\n\n");

		print MAIL "$body\n";
	close(MAIL);
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub log_err ($) {
	my $msg = shift;
	print STDERR sprintf("%02d-%02d-%04d %02d:%02d:%02d", Date(), Time() ) ." $msg\n";
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub color_switch ($) {
	# This function return 1 or 2 for corresponding CSS-Class
	# "table-field1" and "table-field2"
	my $num = shift;
	my $x = ($num / 2);
	return 1 if ( $x == int($x) );
	return 2;
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub remove_cookie {
	%set_cookies = (
			'User-VID'	=> {
				Name	=> 'VID',
				Domain	=> ".$PortalDomain",
				Path	=> '/',
				Expires	=> (time - $cfg{'CookieExpires'}),
				Secure	=> 0,
			},
			'User-VPD'	=> {
				Name	=> 'VPD',
				Domain	=> ".$PortalDomain",
				Path	=> '/',
				Expires	=> (time - $cfg{'CookieExpires'}),
				Secure	=> 0,
			}
	);
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub create_cookie {
	# Create an new User in Table >PortalVisitor<
	my $vpd = Digest::MD5->new->add("$today $time $ENV{'REMOTE_ADDRESS'} $$ $^O")->hexdigest;
	my (undef, $vid) = sql_do("INSERT INTO PortalVisitor (VisitorPassword,PortalId,Date,Time) VALUES ('$vpd','$cfg{'PortalId'}','". sprintf("%04d-%02d-%02d", reverse Date() ) ."','". sprintf("%02d:%02d:%02d", Time() ) ."')");
	%set_cookies = (
			'User-VID'	=> {
				Name	=> 'VID',
				Value	=> $vid,
				Domain	=> ".$PortalDomain",
				Path	=> '/',
				Expires	=> (time + $cfg{'CookieExpires'}),
				Secure	=> 0,
			},
			'User-VPD'	=> {
				Name	=> 'VPD',
				Value	=> $vpd,
				Domain	=> ".$PortalDomain",
				Path	=> '/',
				Expires	=> (time + $cfg{'CookieExpires'}),
				Secure	=> 0,
			}
	);
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub key_spacer ($) {
	my $key = shift;

	my $string = $key . " " x (20 - length($key));
	return $string;
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub add_points ($$) {
	local $_ = shift;
	my $num = shift;
	$_ = reverse $_;
	s/(\d{$num,$num})/$1\./g;
	$_ = reverse $_;
	s/^\.//o;
	return $_;
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub add_spaces ($$) {
	local $_ = shift;
	my $num = shift;
	$_ = reverse $_;
	s/(\d{$num,$num})/$1 /g;
	$_ = reverse $_;
	s/^ //o;
	return $_;
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub add_seperator ($$) {
	local $_ = shift;
	my $where = shift || 3;
	$_ = reverse $_;
	s/(\d{$where,$where})/$1$cfg{'ThousandsSeperator'}/g;
	$_ = reverse $_;
	s/^\Q$cfg{'ThousandsSeperator'}\E?//;
	return $_;
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub round ($) {
	local $_ = shift;
	my $x = int($_);
	if (($_ >= 0) && (($_ - $x) >= 0.5)) {
		$x++;
	}
	elsif (($_ < 0) && (($x - $_) >= 0.5)) {
		$x--;
	}
	return $x;
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub round_up ($) {
	local $_ = shift;
	my $x = int($_);
	$x++ if (($_ - $x) > 0);
	return $x;
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub trim ($$) {
	# Arg 1: The string
	# Arg 2: Length at the string should cutted

	my $string = shift;
	my $trim_at_lenght = shift;
	if (length($string) > $trim_at_lenght) {
		$string =~ s/^(.{$trim_at_lenght}).*/$1\.\.\./s;
	}
	return $string;
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub generate_object_id (@) {
	push(@_, "abcdefghijklmnopqrstuvwxyz");
	return abs sprintf("%010d", crc32( join('', @_) ) );
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub convert_cookie {
	my %cookie_out = ();
	my %cookie = fetch CGI::Cookie;
	foreach my $key (keys %cookie) {
		$cookie_out{$key} = $cookie{$key}->value;
	}
	return %cookie_out;
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub convert_price ($) {
	my $cents = shift;
	return add_seperator( sprintf("%.2f", $cents / 100), 3);
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub convert_level ($) {
	my $level = shift;
	return 'Souterrain' if ($level == -3);
	return 'Erdgeschoß' if ($level == -2);
	return 'Hochparterre' if ($level == -1);
	return 'Dachgeschoß' if ($level == 999);
	return $level .'. OG';
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub convert_square_meter ($) {
	my $cm = shift;
	return add_seperator( sprintf("%.2f", $cm / 100), 3);
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub Time {
	return reverse ((localtime(time))[0,1,2]);
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub Date {
	my ($day, $month, $year) = (localtime(time))[3,4,5];
	return $day, ($month + 1), ($year + 1900);
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub sql_connect {
	my $DB_Interface = shift;
	my $DB_Driver = shift;
	my $DB_Name = shift;
	my $DB_Server = shift;
	my $DB_Port = shift;
	my $DB_DriverSpecials = shift;
	my $DB_User = shift;
	my $DB_Password = shift;
	my $DB_PrintError = shift;
	my $DB_RaiseError = shift;

	use vars qw($dbh $sth $sql_errstr);
	local $SIG{'HUP'} = $SIG{'PIPE'} = $SIG{'INT'} = \&sql_close;

	if ($DB_Interface) {
		# Use the giving Data for Connection
		$dbh = DBI->connect(
			"$DB_Interface:$DB_Driver:$DB_Name:$DB_Server:$DB_Port;$DB_DriverSpecials",
			$DB_User,
			$DB_Password,
			{
				PrintError => $DB_PrintError,
				RaiseError => $DB_RaiseError
			}
		) || &sql_error(100, $DBI::errstr);
	}
	else {
		# Use the default Data for Connection
		$dbh = DBI->connect(
			"$cfg{'DB_Interface'}:$cfg{'DB_Driver'}:$cfg{'DB_Name'}:$cfg{'DB_Server'}:$cfg{'DB_Port'};$cfg{'DB_DriverSpecials'}",
			$cfg{'DB_User'},
			$cfg{'DB_Password'},
			{
				PrintError => $cfg{'DB_PrintError'},
				RaiseError => $cfg{'DB_RaiseError'}
			}
		) || &sql_error(100, $DBI::errstr);
	}
	if ($cfg{'DEBUG'} == 1) {
		$dbh->trace(1);
	}
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub sql_subconnect {
	my $DB_Interface = shift;
	my $DB_Driver = shift;
	my $DB_Name = shift;
	my $DB_Server = shift;
	my $DB_Port = shift;
	my $DB_DriverSpecials = shift;
	my $DB_User = shift;
	my $DB_Password = shift;
	my $DB_PrintError = shift;
	my $DB_RaiseError = shift;

	use vars qw($dbh1 $sth1 $sql_errstr);
	local $SIG{'HUP'} = $SIG{'PIPE'} = $SIG{'INT'} = \&sql_subclose;

	if ($DB_Interface) {
		# Use the giving Data for Connection
		$dbh1 = DBI->connect(
			"$DB_Interface:$DB_Driver:$DB_Name:$DB_Server:$DB_Port;$DB_DriverSpecials",
			$DB_User,
			$DB_Password,
			{
				PrintError => $DB_PrintError,
				RaiseError => $DB_RaiseError
			}
		) || &sql_error(100, $DBI::errstr);
	}
	else {
		# Use the default Data for Connection
		$dbh1 = DBI->connect(
			"$cfg{'DB_Interface'}:$cfg{'DB_Driver'}:$cfg{'DB_Name'}:$cfg{'DB_Server'}:$cfg{'DB_Port'};$cfg{'DB_DriverSpecials'}",
			$cfg{'DB_User'},
			$cfg{'DB_Password'},
			{
				PrintError => $cfg{'DB_PrintError'},
				RaiseError => $cfg{'DB_RaiseError'}
			}
		) || &sql_error(100, $DBI::errstr);
	}
	if ($cfg{'DEBUG'} == 1) {
		$dbh1->trace(1);
	}
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub sql_close {
	sql_finish();
	if (defined $dbh) {
		($dbh->disconnect() || warn $dbh->errstr);
		$dbh = undef;
	}
}


#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub sql_subclose {
	sql_subfinish();
	if (defined $dbh1) {
		($dbh1->disconnect() || warn $dbh1->errstr);
		$dbh1 = undef;
	}
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub sql_error ($$) {
	my $error_code = shift;
	my $error_string = shift;

	my %errors = (
		'100' => 'No Connection',
		'200' => 'Unusable Query',
		'300' => 'No Results',
		'400' => 'Unusable Call',
	);
	warn "$0: $errors{$error_code} - ($error_string)";
	$sql_errstr = "$errors{$error_code} - ($error_string)";
	&sql_close;
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub sql_suberror ($$) {
	my $error_code = shift;
	my $error_string = shift;

	my %errors = (
		'100' => 'No Connection',
		'200' => 'Unusable Query',
		'300' => 'No Results',
		'400' => 'Unusable Call',
	);
	warn "$0: $errors{$error_code} - ($error_string)";
	$sql_errstr = "$errors{$error_code} - ($error_string)";
	&sql_subclose;
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub sql_finish {
	$sth->finish() if (defined $sth);
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub sql_subfinish {
	$sth1->finish() if (defined $sth1);
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub sql_query ($) {
	my $statement = shift;
	$sth = $dbh->prepare("$statement") || &sql_error(200, $dbh->errstr);
	return $sth->execute() || &sql_error(200, $dbh->errstr);
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub sql_subquery ($) {
	my $statement = shift;
	$sth1 = $dbh1->prepare("$statement") || &sql_error(200, $dbh1->errstr);
	return $sth1->execute() || &sql_error(200, $dbh1->errstr);
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub sql_query_cached ($) {
	my $statement = shift;
	$sth = $dbh->prepare_cached("$statement") || &sql_error(200, $dbh->errstr);
	return $sth->execute() || &sql_error(200, $dbh->errstr);
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub sql_count_and_query ($) {
	my $statement = shift;

	# Remove all "\r", "\n", "\t" and "\s+", otherwise we can not count correkt.
	$statement =~ s/\r|\n|\t/ /g;
	$statement =~ s/ +/ /g;

	# Manipulate the statement for counting results.
	my $count_statement = $statement;
	$count_statement =~ s/SELECT (.*) FROM/SELECT COUNT(*) FROM/oi;

	# Remove "LIMIT *", otherwise the counting is wrong.
	$count_statement =~ s/LIMIT[\s\t]+\d+,\d+//i;
	my ($row_count) = $dbh->selectrow_array($count_statement) || 0;

	# Get the Data.
	$sth = $dbh->prepare("$statement") || &sql_error(200, $dbh->errstr);
	$sth->execute() || &sql_error(200, $dbh->errstr);
	return $row_count;
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub sql_count ($) {
	my $statement = shift;
	my ($row_count) = $dbh->selectrow_array($statement) || 0;
	sql_finish();
	return $row_count;
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub sql_fastinsert ($@) {
	my $statement = shift;

	my @result_id = ();
	$sth = $dbh->prepare("$statement");
	foreach (@_) {
		my $result = $sth->execute( $_ ) || &sql_error(200, $dbh->errstr);
		push(@result_id, $result, $dbh->{'mysql_insertid'} );
	}
	return @result_id;
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub sql_fastinsert_array ($@) {
	my $statement = shift;

	my @result_id = ();
	$sth = $dbh->prepare("$statement");
	my $i = 0;
	while ( $_[$i] ne '' ) {
		my $result = $sth->execute( $_[$i], $_[$i+1] ) || &sql_error(200, $dbh->errstr);
		push(@result_id, $result, $dbh->{'mysql_insertid'} );
		$i += 2;
	}
	return @result_id;
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub sql_do ($) {
	my $statement = shift;
	my $result = $dbh->do("$statement") || &sql_error(200, $dbh->errstr);
	return $result, $dbh->{'mysql_insertid'};
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub sql_subdo ($) {
	my $statement = shift;
	my $result = $dbh1->do("$statement") || &sql_error(200, $dbh1->errstr);
	return $result, $dbh1->{'mysql_insertid'};
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub sql_selectall ($) {
	my $statement = shift;
	my @all_rows = ();
	my $array_ref = $dbh->selectall_arrayref($statement);
	&sql_error(200, $dbh->errstr) if ($dbh->errstr);
	foreach my $row (@$array_ref) {
		push(@all_rows, @$row);
	}
	sql_finish();
	return wantarray ? @all_rows : "@all_rows";
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub sql_subselectall ($) {
	my $statement = shift;
	my @all_rows = ();
	my $array_ref = $dbh1->selectall_arrayref($statement);
	&sql_error(200, $dbh1->errstr) if ($dbh1->errstr);
	foreach my $row (@$array_ref) {
		push(@all_rows, @$row);
	}
	sql_subfinish();
	return wantarray ? @all_rows : "@all_rows";
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub sql_selectall_hash ($$) {
	my $statement = shift;
	my $key_fields = shift;
	my %all_rows = ();
	my $array_ref = $dbh->selectall_arrayref($statement);
	&sql_error(200, $dbh->errstr) if ($dbh->errstr);
	foreach my $row (@$array_ref) {
		my $i = 0;
		foreach my $key ( split(',', $key_fields) ) {
			$all_rows{$key} = @$row[$i];
			$i++;
		}
	}
	sql_finish();
	return %all_rows;
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub sql_bindcolumns (@) {
	$sth->bind_columns(undef, @_) || &sql_error(400, $dbh->errstr);
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub sql_subbindcolumns (@) {
	$sth1->bind_columns(undef, @_) || &sql_error(400, $dbh1->errstr);
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub sql_fetch {
	return $sth->fetch();
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub sql_subfetch () {
	return $sth1->fetch();
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub sql_last_inserted_id {
	return ($cfg{'DB_Driver'} eq 'mysql') ? $sth->{'mysql_insertid'} || $dbh->{'mysql_insertid'} : 0;
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub sql_quote ($) {
	my $string = shift;
	if (defined $dbh) {
		return $dbh->quote($string);
	}
	return undef;
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub sql_test {
	return (defined $dbh) ? 1 : 0;
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub sql_getcolumns ($) {
	# Get all names of the columns on giving table
	my $table = shift;
	if ($table) {
		my @table_columns = ();
		my @table_describtion = sql_selectall("SHOW COLUMNS FROM $table");
		my $i = 0;
		while ( $table_describtion[$i] ) {
			push(@table_columns, $table_describtion[$i]);
			$i += 6;
		}
		undef @table_describtion;
		@table_columns = sort @table_columns;
		return wantarray ? @table_columns : join(',', @table_columns);
	}
	return undef;
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub sendmail ($$$$) {
	my $to = shift;
	my $from = shift;
	my $subject = shift;
	my $body = shift;

	my $mailer = $cfg{'MailProg'};
	$mailer =~ s/\%r/$cfg{'MailAddress'}/g;

	my $msg = new MIME::Lite;
	$msg = MIME::Lite->build(
			Encoding	=> $cfg{'DefaultMimeEncoding'},
			From		=> encode_mimewords("$from", Encoding => 'Q', Charset => $cfg{'MimeCharset'}),
			To		=> encode_mimewords("$to", Encoding => 'Q', Charset => $cfg{'MimeCharset'}),
			Subject		=> encode_mimewords("$subject", Encoding => 'Q', Charset => $cfg{'MimeCharset'}),
			Data		=> "$body",

	);
	$msg->attr('content-type'		=> 'text/plain' );
	$msg->attr('content-type.charset'	=> $cfg{'DefaultMimeCharset'} );
	$msg->replace('X-Mailer'		=> "ImmoEngine::$cfg{'PortalDomain'}/$VERSION produced by http://www.aikon-media.de/");

	open(MAIL, "| $mailer") || die "$ENV{'SCRIPT_FILENAME'}: pipe $mailer: $!";
		print MAIL $msg->as_string;
	close(MAIL);
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub ShowMainpage {
	my $html_out = undef;
$html_out .= <<EOL;
<script language="JavaScript" type="text/javascript">
<!--
	if (document.images) {
		// Rubrik "Startseite"
		x01a = new Image(191,143);
		x01a.src = 'http://www.$PortalDomain/.mirror-images/$cfg{"CustomerId"}/mieten-color.jpg';
		x01b = new Image(191,143);
		x01b.src = 'http://www.$PortalDomain/.mirror-images/$cfg{"CustomerId"}/mieten-bw.jpg';

		x02a = new Image(191,143);
		x02a.src = 'http://www.$PortalDomain/.mirror-images/$cfg{"CustomerId"}/kaufen-color.jpg';
		x02b = new Image(191,143);
		x02b.src = 'http://www.$PortalDomain/.mirror-images/$cfg{"CustomerId"}/kaufen-bw.jpg';

		x03a = new Image(191,143);
		x03a.src = 'http://www.$PortalDomain/.mirror-images/$cfg{"CustomerId"}/gewerbe-color.jpg';
		x03b = new Image(191,143);
		x03b.src = 'http://www.$PortalDomain/.mirror-images/$cfg{"CustomerId"}/gewerbe-bw.jpg';
	}
//-->
</script>
<table border="0" width="100%" cellspacing="1" cellpadding="3">
<tr class="startpage-head">
<th width="25%" class="white-only" style="font-size:13pt">Mieten</th>
<th width="25%" class="white-only" style="font-size:13pt">Kaufen</th>
<th width="25%" class="white-only" style="font-size:13pt">Gewerbe/Industrie</th>
</tr>
<tr class="startpage-fields">
<td valign="top">
<!-- FIELD BEGIN, MAX IMAGE WIDTH: 188px -->

EOL
	# $rent_counter will be counted in index.pl, on line ~ 266
	$html_out .= "<p align=\"center\">";
	if (($rent_counter) || ($cfg{'DEMO_MODE'})) {
		$html_out .= "<a href=\"$ENV{'SCRIPT_NAME'}?Action=SelectCategorie&amp;CategorieGroupId=1\" onMouseOver=\"on('x01')\" onMouseOut=\"off('x01')\" style=\"background-color:transparent;border:none\">";
	}
	$html_out .= "<img name=\"x01\" src=\"http://www.$PortalDomain/.mirror-images/$cfg{'CustomerId'}/mieten-color.jpg\" border=\"0\" width=\"191\" height=\"143\" alt=\"\" class=\"img-border\">";
	if (($rent_counter) || ($cfg{'DEMO_MODE'})) {
		$html_out .= "</a>";
	}
	$html_out .= "</p>\n";
	$html_out .= "<table border=\"0\" width=\"100%\" cellspacing=\"0\" cellpadding=\"1\">";
	$html_out .= "<tr>\n";
	if ($rent_counter) {
		$html_out .= "<td><a href=\"$ENV{'SCRIPT_NAME'}?Action=SelectCategorie&amp;CategorieGroupId=1\" onMouseOver=\"on('x01')\" onMouseOut=\"off('x01')\" class=\"startpage-fields-a\">&raquo; mehr...</a></td>";
	}
	else {
		$html_out .= "<td>&nbsp;</td>\n";
	}
	$html_out .= "<td align=\"right\" class=\"object-counter\">";

	if ($cfg{'ShowObjectCounter'}) {
		$html_out .= add_points($rent_counter, 3);
		if ($rent_counter == 1) {
			$html_out .= " Objekt";
		}
		else {
			$html_out .= " Objekte";
		}
	}

	$html_out .= "</td>";
	$html_out .= "</tr>";
	$html_out .= "</table>";

$html_out .= <<EOL;

<!-- FIELD END -->
</td>
<td valign="top">
<!-- FIELD BEGIN, MAX IMAGE WIDTH: 188px -->

EOL
	# $buy_counter will be counted in index.pl, on line ~ 266
	$html_out .= "<p align=\"center\">";
	if (($buy_counter) || ($cfg{'DEMO_MODE'})) {
		$html_out .= "<a href=\"$ENV{'SCRIPT_NAME'}?Action=SelectCategorie&amp;CategorieGroupId=2\" onMouseOver=\"on('x02')\" onMouseOut=\"off('x02')\" style=\"background-color:transparent;border:none\">";
	}
	$html_out .= "<img name=\"x02\" src=\"http://www.$PortalDomain/.mirror-images/$cfg{'CustomerId'}/kaufen-color.jpg\" border=\"0\" width=\"191\" height=\"143\" alt=\"\" class=\"img-border\">";
	if (($buy_counter) || ($cfg{'DEMO_MODE'})) {
		$html_out .= "</a>";
	}
	$html_out .= "</p>\n";
	$html_out .= "<table border=\"0\" width=\"100%\" cellspacing=\"0\" cellpadding=\"1\">";
	$html_out .= "<tr>\n";
	if ($buy_counter) {
		$html_out .= "<td><a href=\"$ENV{'SCRIPT_NAME'}?Action=SelectCategorie&amp;CategorieGroupId=2\" onMouseOver=\"on('x02')\" onMouseOut=\"off('x02')\" class=\"startpage-fields-a\">&raquo; mehr...</a></td>";
	}
	else {
		$html_out .= "<td>&nbsp;</td>\n";
	}
	$html_out .= "<td align=\"right\" class=\"object-counter\">";

	if ($cfg{'ShowObjectCounter'}) {
		$html_out .= add_points($buy_counter, 3);
		if ($buy_counter == 1) {
			$html_out .= " Objekt";
		}
		else {
			$html_out .= " Objekte";
		}
	}

	$html_out .= "</td>";
	$html_out .= "</tr>";
	$html_out .= "</table>";

$html_out .= <<EOL;

<!-- FIELD END -->

</td>
<td valign="top">
<!-- FIELD BEGIN, MAX IMAGE WIDTH: 188px -->

EOL
	# $industry_counter will be counted in index.pl, on line ~ 266
	$html_out .= "<p align=\"center\">";
	if (($industry_counter) || ($cfg{'DEMO_MODE'})) {
		$html_out .= "<a href=\"$ENV{'SCRIPT_NAME'}?Action=SelectCategorie&amp;CategorieGroupId=3\" onMouseOver=\"on('x03')\" onMouseOut=\"off('x03')\" style=\"background-color:transparent;border:none\">";
	}
	$html_out .= "<img name=\"x03\" src=\"http://www.$PortalDomain/.mirror-images/$cfg{'CustomerId'}/gewerbe-color.jpg\" border=\"0\" width=\"191\" height=\"143\" alt=\"\" class=\"img-border\">";
	if (($industry_counter) || ($cfg{'DEMO_MODE'})) {
		$html_out .= "</a>";
	}
	$html_out .= "</p>\n";
	$html_out .= "<table border=\"0\" width=\"100%\" cellspacing=\"0\" cellpadding=\"1\">";
	$html_out .= "<tr>\n";
	if ($industry_counter) {
		$html_out .= "<td><a href=\"$ENV{'SCRIPT_NAME'}?Action=SelectCategorie&amp;CategorieGroupId=3\" onMouseOver=\"on('x03')\" onMouseOut=\"off('x03')\" class=\"startpage-fields-a\">&raquo; mehr...</a></td>";
	}
	else {
	$html_out .= "<td>&nbsp;</td>\n";
	}
	$html_out .= "<td align=\"right\" class=\"object-counter\">";

	if ($cfg{'ShowObjectCounter'}) {
		$html_out .= add_points($industry_counter, 3);
		if ($industry_counter == 1) {
			$html_out .= " Objekt";
		}
		else {
			$html_out .= " Objekte";
		}
	}

	$html_out .= "</td>";
	$html_out .= "</tr>";
	$html_out .= "</table>";

$html_out .= <<EOL;

<!-- FIELD END -->

</td>
</tr>
</table>
EOL

	return $html_out;
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub SelectCategorie {
	my $html_out = undef;

	if ($query{'CategorieGroupId'} == 1) {
		# Categorie "Rent"
		$html_out .= "<h1>Mietobjekte ausgewählt</h1>\n";
	}
	elsif ($query{'CategorieGroupId'} == 2) {
		# Categorie "Buy"
		$html_out .= "<h1>Kaufobjekte ausgewählt</h1>\n";
	}
	elsif ($query{'CategorieGroupId'} == 3) {
		# Categorie "Industry"
		$html_out .= "<h1>Gewerbe- / Industrieobjekte ausgewählt</h1>\n";
	}

	if ($cfg{'ShowObjectCounter'}) {
		my $counter = sql_selectall("SELECT COUNT(EstateId) FROM Estate WHERE CategorieGroupId='$query{'CategorieGroupId'}' AND Active='1' AND EndDate>='$today' AND CustomerId='$cfg{'CustomerId'}'");
		$html_out .= "<p><b>Info:</b> ". add_points($counter, 3);
		if ($counter == 1) {
			$html_out .= " Objekt in der Datenbank</p>\n";
		}
		else {
			$html_out .= " Objekte in der Datenbank</p>\n";
		}
	}

$html_out .= <<EOL;
<table border="0" width="100%" cellspacing="1" cellpadding="3">
<tr>
<td width="33%" style="font-size:1px">&nbsp;</td>
<td width="33%" style="font-size:1px">&nbsp;</td>
<td width="33%" style="font-size:1px">&nbsp;</td>
</tr>
<tr class="table-header">
<td colspan="3">Bitte wählen Sie die gewünschte Kategorie aus:</td>
</tr>
EOL

	my @categorie_count = ();
	if ($cfg{'JumpIntoCategorieIfOnlyOne'} == 1) {
		(@categorie_count) = sql_selectall("SELECT CategorieId,COUNT(CategorieId) FROM Estate WHERE CategorieGroupId='$query{'CategorieGroupId'}' AND Active='1' AND CustomerId='$cfg{'CustomerId'}' AND EndDate>='$today' GROUP BY CategorieId");
	}
	else {
		push(@categorie_count, 1, 2, 3, 4);
	}
	# If scalar(@categorie_count) return greater then 2, then we have more then
	# one Categorie und we give the user the chance to select one.
	# Otherwise we jump directly into the Categorie, because there is only one.
	if ( scalar(@categorie_count) > 2 ) {

		my ($CategorieId, $Categorie, $Count);
		sql_query("SELECT c.CategorieId,c.Categorie,COUNT(e.CategorieId) FROM Categorie AS c, Estate AS e WHERE c.CategorieGroupId='$query{'CategorieGroupId'}' AND c.Active='1' AND CustomerId='$cfg{'CustomerId'}' AND (c.CategorieId=e.CategorieId AND e.Active='1' AND EndDate>='$today') GROUP BY c.CategorieId ORDER BY c.SortOrder");
		sql_bindcolumns( \($CategorieId, $Categorie, $Count) );

		my $object_counter = 1;
		my @CategorieIds = ();						# This is needed to generate the JavaScript below!
		my $td_switch = 1;
		my $color_switch = 1;
		my $color_switch2 = 2;
		while ( sql_fetch() ) {
			next unless $Count;					# If the Categorie has no Content, we then skip this Categorie
			push(@CategorieIds, $CategorieId, $Categorie);		# Insert the $CategorieId for the JavaScript
			if ($td_switch == 1) {
				$html_out .= "<tr class=\"table-field$color_switch\">\n";
			}

			$html_out .= "<td align=\"center\">\n\n";

			$html_out .= "<b style=\"font-size:11pt\">$Categorie</b><br>\n";
			$html_out .= "<a href=\"$ENV{'SCRIPT_NAME'}?Action=ShowCategorie&amp;CategorieId=$CategorieId&amp;CategorieGroupId=$query{'CategorieGroupId'}\" onMouseOver=\"on('a". sprintf("%02d", $CategorieId) ."')\" onMouseOut=\"off('a". sprintf("%02d", $CategorieId) ."')\" style=\"background-color:transparent;border:none\"><img name=\"a". sprintf("%02d", $CategorieId) ."\" src=\"http://www.$PortalDomain/.images/system/symbols/$CategorieId.jpg\" width=\"154\" height=\"100\" alt=\"$Categorie\" title=\"$Categorie\" class=\"img-list\"></a><br>\n";
			$html_out .= "<table border=\"0\" width=\"100%\" cellspacing=\"1\" cellpadding=\"0\">\n";
			$html_out .= "<tr>\n";
			$html_out .= "<td width=\"50%\" align=\"left\" style=\"vertical-align:middle\" class=\"object-counter\">";

		# ObjectCounter BEGIN
			if ($cfg{'ShowObjectCounter'}) {
				if ($Count == 1) {
		 			$html_out .= add_points($Count, 3) ." Objekt";
				}
				else {
		 			$html_out .= add_points($Count, 3) ." Objekte";
				}
			}
		# ObjectCounter END

			$html_out .= "</td>\n";
			$html_out .= "<td width=\"50%\" align=\"right\">\n";

		# Show-Button BEGIN
			$html_out .= "<form action=\"$ENV{'SCRIPT_NAME'}\" method=\"$cfg{'TransmitMethodEndUser'}\" name=\"ShowCategorie$object_counter\">\n";
			$html_out .= "<input type=\"hidden\" name=\"Action\" value=\"ShowCategorie\">\n";
			$html_out .= "<input type=\"hidden\" name=\"CategorieId\" value=\"$CategorieId\">\n";
			$html_out .= "<input type=\"hidden\" name=\"CategorieGroupId\" value=\"$query{'CategorieGroupId'}\">\n";
			$html_out .= "<input type=\"image\" src=\"http://www.$PortalDomain/.images/system/buttons/show.gif\" border=\"0\" width=\"100\" height=\"20\" alt=\"Kategorie $Categorie anzeigen\" title=\"Kategorie $Categorie anzeigen\" onMouseOver=\"on('a". sprintf("%02d", $CategorieId) ."')\" onMouseOut=\"off('a". sprintf("%02d", $CategorieId) ."')\"";
			# Reversed here becaus we already switched the switch above
			if ($color_switch == 0) {
				$html_out .= " class=\"input-img-button1\">\n";
			}
			else {
				$html_out .= " class=\"input-img-button2\">\n";
			}
		# Show-Button END

			$html_out .= "</td>\n";
			$html_out .= "</form>\n";
			$html_out .= "</tr>\n";
			$html_out .= "</table>\n\n";

			$html_out .= "</td>\n";
			$td_switch++;

			if ($td_switch == 4) {				# Nr. 4, because the counter is set before here
				if ($color_switch == 1) {
				$color_switch = 2;
					$color_switch2 = 1;
				}
				else {
					$color_switch = 1;
					$color_switch2 = 2;
				}
				$html_out .= "</tr>\n";
				$td_switch = 1;
			}

			# This holds the Counter for all the single Forms to submit the right one!
			$object_counter++;
		}

		if (($td_switch <= 3) && ($td_switch != 1)) {
			if ($td_switch == 1) {
				$html_out .= "<tr class=\"table-field$color_switch\">\n";
			}
			for ( $td_switch..3 ) {
				$html_out .= "<td>&nbsp;</td>\n";
			}
			$html_out .= "</tr>\n";
		}
		$html_out .= "</table>\n";

		# Generate the JavaScript, so the Images can be switched
		$html_out .= "<script language=\"JavaScript\">\n";
		$html_out .= "<!--\n";
		$html_out .= "if (document.images) {\n\n";
		my $i = 0;
		while ( $CategorieIds[$i] ) {
			my $idf = sprintf("%02d", $CategorieIds[$i]);
			$html_out .= "\t//  Rubrik \"$CategorieIds[$i+1]\"\n";
			$html_out .= "\ta". $idf ."a = new Image(154,100);\n";
			$html_out .= "\ta". $idf ."a.src = 'http://www.$PortalDomain/.images/system/symbols/$CategorieIds[$i].jpg';\n";
			$html_out .= "\ta". $idf ."b = new Image(154,100);\n";
			$html_out .= "\ta". $idf ."b.src = 'http://www.$PortalDomain/.images/system/symbols/$CategorieIds[$i]-bw.jpg';\n\n";
			$i += 2;
		}
		$html_out .= "}\n";
		$html_out .= "//-->\n";
		$html_out .= "</script>\n";
		undef @CategorieIds;
	}
	else {
		$query{'CategorieId'} = $categorie_count[0];
		$html_out = ShowCategorie();
	}

	return $html_out;
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub ShowCategorie {
	my $html_out = undef;

	if ($query{'CategorieGroupId'} == 1) {
		# Categorie "Rent"
		$html_out .= "<h1>Mietobjekte ausgewählt</h1>\n";
	}
	elsif ($query{'CategorieGroupId'} == 2) {
		# Categorie "Buy"
		$html_out .= "<h1>Kaufobjekte ausgewählt</h1>\n";
	}
	elsif ($query{'CategorieGroupId'} == 3) {
		# Categorie "Industry"
		$html_out .= "<h1>Gewerbe- / Industrieobjekte ausgewählt</h1>\n";
	}

	# Get the current Name of selected "Categorie"
	my ($Categorie) = sql_selectall("SELECT Categorie FROM Categorie WHERE CategorieGroupId='$query{'CategorieGroupId'}' AND Active='1' AND CategorieId='$query{'CategorieId'}'");
	$html_out .= "<b>Kategorie: $Categorie</b></h3>\n";


	if ($cfg{'ShowObjectCounter'}) {
		my $counter = sql_selectall("SELECT COUNT(EstateId) FROM Estate WHERE CategorieGroupId='1' AND CategorieId='1' AND CustomerId='$cfg{'CustomerId'}' AND Active='1'");
		$html_out .= "<p><b>Info:</b> ". add_points($counter, 3);
		if ($counter == 1) {
		$html_out .= " Objekt in der Datenbank</p>\n";
		}
		else {
			$html_out .= " Objekte in der Datenbank</p>\n";
		}
	}

$html_out .= <<EOL;
<form action="$ENV{'SCRIPT_NAME'}" method="$cfg{'TransmitMethodEndUser'}" name="SelectionForm">
<input type="hidden" name="Action" value="ShowCategorie">
<input type="hidden" name="CategorieId" value="$query{'CategorieId'}">
<input type="hidden" name="CategorieGroupId" value="$query{'CategorieGroupId'}">

<table border="0" width="100%" cellspacing="1" cellpadding="3">
<tr class="button-green-top">
<td>Einschränkungen nach Ort:</td>
<td>Sortieren nach:</td>
</tr>
<tr class="button-green">
<td style="vertical-align:top" width="40%">
<select name="CityId" size="1" style="width:250px" onChange="ChangeDistrictId(this.value, '$query{'CityId'}')">
EOL
	# This is the Selectbox for selecting the City
	my @CityTMP = sql_selectall("SELECT c.CityId,c.CityName,COUNT(e.CityId) FROM City AS c, Estate AS e WHERE e.CustomerId='$cfg{'CustomerId'}' AND c.CityId=e.CityId AND e.Active='1' AND e.EndDate>='$today' AND e.CategorieGroupId='$query{'CategorieGroupId'}' AND e.CategorieId='$query{'CategorieId'}' GROUP BY e.CityId ORDER BY c.CityName");
	my @City = ('0', 'Keine Einschränkung', '0', @CityTMP);
	undef @CityTMP;

	my $i = 0;
	while ($City[$i] ne '') {
		my $counter = undef;
		$html_out .= "<option value=\"$City[$i]\"";
		$html_out .= " selected" if ($City[$i] == $query{'CityId'});
		$html_out .= ">$City[$i+1]";
		$html_out .= " ($City[$i+2])" if (($cfg{'ShowObjectCounter'}) && ($City[$i+2]));
		$html_out .= "</option>\n";
		$i += 3;
	}
	undef @City;

$html_out .= <<EOL;
</select>
EOL
	# This is the Selectbox for selecting the District
	if ($query{'CityId'}) {
		$html_out .= "<br>";

		$html_out .= "<select name=\"DistrictId\" size=\"1\" style=\"width:250px\">\n";
		$html_out .= "<option value=\"0\">Keine Einschränkung</option>\n";

		my @District = sql_selectall("SELECT d.DistrictId,d.District,COUNT(e.DistrictId) FROM District AS d, Estate AS e WHERE e.CustomerId='$cfg{'CustomerId'}' AND e.CityId='$query{'CityId'}' AND (d.DistrictId=e.DistrictId AND e.CategorieGroupId='$query{'CategorieGroupId'}' AND e.CategorieId='$query{'CategorieId'}' AND e.Active='1' AND e.EndDate>='$today') GROUP BY e.DistrictId ORDER BY d.District");
		my $last_sign = undef;
		for ( qw(A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) ) {
			my $i = 0;
			while ($District[$i]) {

				# This is need, because we cannot compare "Ä" and "A" if not equal
				my ($DistrictSign) = ($District[$i+1] =~ /^(.{1}).*$/);
				$DistrictSign = uc($DistrictSign);
				$DistrictSign =~ y/ÄÖÜ/AOU/;

				if ($DistrictSign eq $_) {
					if ($last_sign ne $_) {
						$html_out .= "</optgroup>\n" if ($last_sign);
						$html_out .= "<optgroup label=\"$_\">\n";
						$html_out .= "\t<option value=\"$District[$i]\"";
						$html_out .= " selected" if ($District[$i] == $query{'DistrictId'});
						$html_out .= ">$District[$i+1]";
						$html_out .= " ($District[$i+2])" if $cfg{'ShowObjectCounter'};
						$html_out .= "</option>\n";
						$last_sign = $_;
					}
					elsif ($last_sign eq $_) {
						$html_out .= "\t<option value=\"$District[$i]\"";
						$html_out .= " selected" if ($District[$i] == $query{'DistrictId'});
						$html_out .= ">$District[$i+1]";
						$html_out .= " ($District[$i+2])" if $cfg{'ShowObjectCounter'};
						$html_out .= "</option>\n";
					}
				}
				$i += 3;
			}
		}
		undef @District;
		$html_out .= "</select>\n";
	}

$html_out .= <<EOL;
</td>
<td style="vertical-align:bottom" width="50%">

<table border="0" width="100%" cellspacing="0" cellpadding="0" style="vertical-align:bottom">
<tr>
<td style="vertical-align:bottom" width="33%">
<select name="OrderBy" size="1" style="width:100px">
EOL
	my %OrderBy = ();
	if ($query{'CategorieGroupId'} == 1) {
		%OrderBy = (
			Rooms		=> 'Räume',
			LivingAreaQM	=> 'Fläche',
			RentalCold	=> 'Kaltmiete',
			Level		=> 'Etage',
			CityName	=> 'Ort/Stadteil',
			EstateStreet	=> 'Straße',
		);
	}
	elsif ($query{'CategorieGroupId'} == 2) {
		%OrderBy = (
			Rooms		=> 'Räume',
			LivingAreaQM	=> 'Fläche',
			PurchasePrice	=> 'Kaufpreis',
			Level		=> 'Etage',
			CityName	=> 'Ort/Stadteil',
			EstateStreet	=> 'Straße',
		);
	}
	elsif ($query{'CategorieGroupId'} == 3) {
		%OrderBy = (
			Rooms		=> 'Räume',
			LivingAreaQM	=> 'Fläche',
			RentalCold	=> 'Kaltmiete',
			PurchasePrice	=> 'Kaufpreis',
			Level		=> 'Etage',
			CityName	=> 'Ort/Stadteil',
			EstateStreet	=> 'Straße',
		);
	}


	# If unset, we set OrderBy to "RentalCold"
	if (! $query{'OrderBy'}) {
		if ($query{'CategorieGroupId'} == 1) {
			$query{'OrderBy'} = 'RentalCold';
		}
		elsif ($query{'CategorieGroupId'} == 2) {
			$query{'OrderBy'} = 'PurchasePrice';
		}
		elsif ($query{'CategorieGroupId'} == 3) {
			$query{'OrderBy'} = 'PurchasePrice';
		}
	}

	# This is needed, because we sort with these statement but never trust the User!
	my $found = 0;
	foreach (keys %OrderBy) {
		if ($query{'OrderBy'} eq $_) {
			$found = 1;
		}
	}
	if (! $found) {
		$query{'OrderBy'} = 'CityName';
	}

	foreach my $value (sort values %OrderBy) {
		foreach (keys %OrderBy) {
			if ($OrderBy{$_} eq $value) {
				$html_out .= "<option value=\"$_\"";
				if ($query{'OrderBy'} eq $_) {
					$html_out .= " selected";
				}
				$html_out .= ">$OrderBy{$_}</option>\n";
			}
		}
	}

$html_out .= <<EOL;
</select>
</td>
<td style="vertical-align:bottom" width="34%">
<select name="Order" size="1" style="width:100px">
EOL
	my %Order = (
		'ASC'	=> 'aufsteigend',
		'DESC'	=> 'absteigend',
	);

	# If unset, we set Order to "ASC"
	if (! $query{'Order'}) {
		$query{'Order'} = 'ASC';
	}

	# This is needed, because we sort with these statement but never trust the User!
	my $found = 0;
	foreach (keys %Order) {
		if ($query{'Order'} eq $_) {
			$found = 1;
		}
	}
	if (! $found) {
		$query{'Order'} = 'ASC';
	}

	foreach (reverse sort keys %Order) {
		$html_out .= "<option value=\"$_\"";
		if ($query{'Order'} eq $_) {
			$html_out .= " selected";
		}
		$html_out .= ">$Order{$_}</option>\n";
	}

$html_out .= <<EOL;
</select>
</td>
<td align="center" style="vertical-align:bottom" width="33%">
<input type="image" src="http://www.$PortalDomain/.images/system/buttons/show.gif" border="0" width="100" height="20" alt="Anzeigen" title="Anzeigen" class="input-img-button1">
</td>
</tr>
</table>

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

<table border="0" width="100%" cellspacing="1" cellpadding="0">
<tr class="table-header">
<th width="26%" style="padding:3px">Bild</th>
<th width="38%" style="padding:3px">Beschreibung</th>
<th width="38%" style="padding:3px">Details</th>
</tr>
EOL
	if ($query{'OrderBy'} eq 'CityName') {
		$query{'OrderBy'} .= ', District';
	}
	elsif ($query{'OrderBy'} eq 'EstateStreet') {
		$query{'OrderBy'} = 'Cityname, EstateStreet, EstateStreetNumber';
	}

	my $ResultCount = undef;
	if ($query{'DistrictId'}) {
		# Count the Objects (active), needed for more_pages()
		$ResultCount = sql_selectall("SELECT COUNT(Active) FROM Estate WHERE Active='1' AND CategorieId='$query{'CategorieId'}' AND EndDate>='$today' AND CityId='$query{'CityId'}' AND DistrictId='$query{'DistrictId'}' AND ObjectRented='0' AND ObjectMarketed='0' AND CustomerId='$cfg{'CustomerId'}'");

		# Select the Estates
		sql_query("SELECT EstateId,CustomerId,ShowAddress,EstateStreet,EstateStreetNumber,e.PostalCode,c.CityName,d.District,ConstructionArea,IndustrialPark,Rooms,LivingAreaQM,LandAreaQM,Level,InteriorEquipmentIds,Announcetitle,RentalCold,PurchasePrice FROM Estate AS e INNER JOIN City AS c LEFT JOIN District AS d ON d.DistrictId=e.DistrictId WHERE Active='1' AND CategorieId='$query{'CategorieId'}' AND EndDate>='$today' AND ObjectRented='0' AND ObjectMarketed='0' AND e.CityId='$query{'CityId'}' AND e.DistrictId='$query{'DistrictId'}' AND c.CityId=e.CityId AND CustomerId='$cfg{'CustomerId'}' ORDER BY $query{'OrderBy'} $query{'Order'} LIMIT $query{'Limit'},$cfg{'ShowMaxEntries'}");
	}
	elsif ($query{'CityId'}) {
		# Count the Objects (active), needed for more_pages()
		$ResultCount = sql_selectall("SELECT COUNT(Active) FROM Estate WHERE Active='1' AND CategorieId='$query{'CategorieId'}' AND EndDate>='$today' AND CityId='$query{'CityId'}' AND ObjectRented='0' AND ObjectMarketed='0' AND CustomerId='$cfg{'CustomerId'}'");

		# Select the Estates
		sql_query("SELECT EstateId,CustomerId,ShowAddress,EstateStreet,EstateStreetNumber,e.PostalCode,c.CityName,d.District,ConstructionArea,IndustrialPark,Rooms,LivingAreaQM,LandAreaQM,Level,InteriorEquipmentIds,Announcetitle,RentalCold,PurchasePrice FROM Estate AS e INNER JOIN City AS c LEFT JOIN District AS d ON d.DistrictId=e.DistrictId WHERE Active='1' AND CategorieId='$query{'CategorieId'}' AND EndDate>='$today' AND ObjectRented='0' AND ObjectMarketed='0' AND e.CityId='$query{'CityId'}' AND c.CityId=e.CityId AND CustomerId='$cfg{'CustomerId'}' ORDER BY $query{'OrderBy'} $query{'Order'} LIMIT $query{'Limit'},$cfg{'ShowMaxEntries'}");
	}
	else {
		# Count the Objects (active), needed for more_pages() below
		$ResultCount = sql_selectall("SELECT COUNT(Active) FROM Estate WHERE Active='1' AND CategorieId='$query{'CategorieId'}' AND EndDate>='$today' AND ObjectRented='0' AND ObjectMarketed='0' AND CustomerId='$cfg{'CustomerId'}'");

		# Select the Estates
		sql_query("SELECT EstateId,CustomerId,ShowAddress,EstateStreet,EstateStreetNumber,e.PostalCode,c.CityName,d.District,ConstructionArea,IndustrialPark,Rooms,LivingAreaQM,LandAreaQM,Level,InteriorEquipmentIds,Announcetitle,RentalCold,PurchasePrice FROM Estate AS e INNER JOIN City AS c LEFT JOIN District AS d ON d.DistrictId=e.DistrictId WHERE Active='1' AND CategorieId='$query{'CategorieId'}' AND EndDate>='$today' AND ObjectRented='0' AND ObjectMarketed='0' AND c.CityId=e.CityId AND CustomerId='$cfg{'CustomerId'}' ORDER BY $query{'OrderBy'} $query{'Order'} LIMIT $query{'Limit'},$cfg{'ShowMaxEntries'}");
	}

	sql_subconnect();

	my $i = 0;
	my $color_switch = 0;
	my ($EstateId, $CustomerId, $ShowAddress, $EstateStreet, $EstateStreetNumber, $PostalCode, $CityName, $District, $ConstructionArea, $IndustrialPark, $Rooms, $LivingAreaQM, $LandAreaQM, $Level, $InteriorEquipmentIds, $Announcetitle, $RentalCold, $PurchasePrice);
	sql_bindcolumns( \($EstateId, $CustomerId, $ShowAddress, $EstateStreet, $EstateStreetNumber, $PostalCode, $CityName, $District, $ConstructionArea, $IndustrialPark, $Rooms, $LivingAreaQM, $LandAreaQM, $Level, $InteriorEquipmentIds, $Announcetitle, $RentalCold, $PurchasePrice) );
	while ( sql_fetch() ) {

		# Prepare the Data for viewing
		my ($room, $small_room) = split('\.', $Rooms );
		$Rooms = $room;
		$Rooms .= " ½" if $small_room;

		if ($color_switch == 0) {
			$html_out .= "<tr class=\"table-field1\">\n";
			$color_switch = 1;
		}
		else {
			$html_out .= "<tr class=\"table-field2\">\n";
			$color_switch = 0;
		}

	# Image BEGIN
		$html_out .= "<td>";
		# Title (0), Floorplan (1) or Optional (2)
		# Select the Image with ImageTyp=0 (Title) OR ImageTyp=2 (The newest optinal image)
		my ($ImageId, $ImageTitle, $ImageWidthThumb, $ImageHeightThumb) = sql_subselectall("SELECT ImageId,ImageTitle,ImageWidthThumb,ImageHeightThumb FROM Images WHERE ImageTyp='0' AND EstateId='$EstateId' ORDER BY ImageId LIMIT 1");
		if ( $ImageId ) {
			my $img = "$cfg{'ImageUploadUrl'}CustomerId-$cfg{'CustomerId'}/EstateId-$EstateId/$ImageId-thumb$cfg{'UploadImageExtention'}";
			$html_out .= "<a href=\"$ENV{'SCRIPT_NAME'}?Action=ShowSynopsis&amp;CategorieGroupId=$query{'CategorieGroupId'}&amp;CategorieId=$query{'CategorieId'}&amp;CityId=$query{'CityId'}&amp;DistrictId=$query{'DistrictId'}&amp;Limit=$query{'Limit'}&amp;EstateId=$EstateId\" style=\"background-color:transparent;border:none\"><img src=\"$img\" width=\"$ImageWidthThumb\" height=\"$ImageHeightThumb\" alt=\"$ImageTitle\" title=\"$ImageTitle\" class=\"img-list\"></a>";
		}
		else {
			my ($ImageId, $ImageTitle, $ImageWidthThumb, $ImageHeightThumb) = sql_subselectall("SELECT ImageId,ImageTitle,ImageWidthThumb,ImageHeightThumb FROM Images WHERE ImageTyp='2' AND EstateId='$EstateId' ORDER BY ImageId LIMIT 1");
			if ( $ImageId ) {
				my $img = "$cfg{'ImageUploadUrl'}CustomerId-$cfg{'CustomerId'}/EstateId-$EstateId/$ImageId-thumb$cfg{'UploadImageExtention'}";
				$html_out .= "<a href=\"$ENV{'SCRIPT_NAME'}?Action=ShowSynopsis&amp;CategorieGroupId=$query{'CategorieGroupId'}&amp;CategorieId=$query{'CategorieId'}&amp;CityId=$query{'CityId'}&amp;DistrictId=$query{'DistrictId'}&amp;Limit=$query{'Limit'}&amp;EstateId=$EstateId\" style=\"background-color:transparent;border:none\"><img src=\"$img\" width=\"$ImageWidthThumb\" height=\"$ImageHeightThumb\" alt=\"$ImageTitle\" title=\"$ImageTitle\" class=\"img-list\"></a>";
			}
			else {
				$html_out .= "&nbsp;";
			}
		}
		$html_out .= "</td>\n";
	# END

	# Address BEGIN
		$html_out .= "<td>";
		$html_out .= "<div style=\"position:relative; width:100%; height:114px\">";
		$html_out .= "<div style=\"position:absolute; width:95%; top:0px; margin:4px\">";
		$html_out .= "<b>$Announcetitle</b><br>\n" if ($Announcetitle);
		if ($cfg{'AddressNotRequiredForGroup'} !~ /^($query{'CategorieId'})$/ ) {
			if ($CityName) {
				if ($ShowAddress) {
					$html_out .= "$EstateStreet $EstateStreetNumber<br>\n";
				}
				$html_out .= "$PostalCode $CityName";
				$html_out .= " ($District)" if $District;
			}
			else {
				$html_out .= "Keine Adresse angegeben!";
			}
			$html_out .= "<br>\nGewerbegebiet: $IndustrialPark" if ( $IndustrialPark );
			$html_out .= "<br>\nGebiet: $ConstructionArea" if ( $ConstructionArea );
			# END ShowAddress
		}
		$html_out .= "</div>\n";
		$html_out .= "<div style=\"position:absolute; bottom:0px; width:95%; margin:4px\">\n";
		my %IEid = ();
		foreach my $id ( split(/,/, $InteriorEquipmentIds) ) {
			$IEid{$id} = 1 if ($id == 37);
			$IEid{$id} = 1 if ($id == 35);
			$IEid{$id} = 1 if ($id == 49);
			$IEid{$id} = 1 if ($id == 44);
			$IEid{$id} = 1 if ($id == 39);
			$IEid{$id} = 1 if ($id == 41);
		}

		foreach my $id (37,35,49,44,39,41) {
			if ( $IEid{$id} ) {
				$html_out .= "<img style=\"margin-right:3px; margin-top:3px\" src=\"http://www.$PortalDomain/.images/system/Ausstattungen/Einbaukueche.png\" border=\"0\" width=\"34\" height=\"11\" alt=\"Einbauküche vorhanden\" title=\"Einbauküche vorhanden\">" if ($id == 37);
				$html_out .= "<img style=\"margin-right:3px; margin-top:3px\" src=\"http://www.$PortalDomain/.images/system/Ausstattungen/Balkon.png\" border=\"0\" width=\"54\" height=\"11\" alt=\"Balkon vorhanden\" title=\"Balkon vorhanden\">" if ($id == 35);
				$html_out .= "<img style=\"margin-right:3px; margin-top:3px\" src=\"http://www.$PortalDomain/.images/system/Ausstattungen/Loggia.png\" border=\"0\" width=\"54\" height=\"11\" alt=\"Loggia vorhanden\" title=\"Loggia vorhanden\">" if ($id == 49);
				$html_out .= "<img style=\"margin-right:3px; margin-top:3px\" src=\"http://www.$PortalDomain/.images/system/Ausstattungen/Terrasse.png\" border=\"0\" width=\"68\" height=\"11\" alt=\"Terrasse vorhanden\" title=\"Terrasse vorhanden\">" if ($id == 44);
				$html_out .= "<img style=\"margin-right:3px; margin-top:3px\" src=\"http://www.$PortalDomain/.images/system/Ausstattungen/Aufzug.png\" border=\"0\" width=\"54\" height=\"11\" alt=\"Aufzug/Fahrstuhl vorhanden\" title=\"Aufzug/Fahrstuhl vorhanden\">" if ($id == 39);
				$html_out .= "<img style=\"margin-right:3px; margin-top:3px\" src=\"http://www.$PortalDomain/.images/system/Ausstattungen/Garten.png\" border=\"0\" width=\"54\" height=\"11\" alt=\"Garten vorhanden\" title=\"Garten vorhanden\">" if ($id == 41);
			}
		}
		undef %IEid;
		$html_out .= "</div>";
		$html_out .= "</div>\n";
		$html_out .= "</td>\n";
	# END

	# Detail-Table BEGIN
		$html_out .= "<td>\n";
		$html_out .= "<div style=\"position:relative; width:95%; height:114px\">";
		$html_out .= "<div style=\"position:absolute; top:0px; width:100%; margin:4px\">";
		if ($query{'CategorieGroupId'} == 1) {
			# Miete
			$html_out .= "<table border=\"0\" width=\"100%\" cellspacing=\"0\" cellpadding=\"2\">\n";
			$html_out .= "<tr class=\"font-white\"><td width=\"60%\">Räume:</td><td width=\"40%\" align=\"right\">$Rooms</td></tr>\n" if $Rooms;
			$html_out .= "<tr class=\"font-white\"><td width=\"60%\">Wohnfläche ca.:</td><td width=\"40%\" align=\"right\">". add_points(sprintf("%.2f", $LivingAreaQM / 100), 3) ." m²</td></tr>\n" if $LivingAreaQM;
			$html_out .= "<tr class=\"font-white\"><td width=\"60%\">Grundstück ca.:</td><td width=\"40%\" align=\"right\">". add_points(sprintf("%.2f", $LandAreaQM / 100), 3) ." m²</td></tr>\n" if $LandAreaQM;
			$html_out .= "<tr class=\"font-white\"><td width=\"60%\">Kaltmiete:</td><td width=\"40%\" align=\"right\">". convert_price($RentalCold) ." €</td></tr>\n" if $RentalCold;
			$html_out .= "<tr class=\"font-white\"><td width=\"60%\">Lage:</td><td width=\"40%\" align=\"right\">". convert_level($Level) ."</td></tr>\n" if $Level;
			$html_out .= "</table>\n";
		}
		elsif ($query{'CategorieGroupId'} == 2) {
			# Kauf
			$html_out .= "<table border=\"0\" width=\"100%\" cellspacing=\"0\" cellpadding=\"2\">\n";
			$html_out .= "<tr class=\"font-white\"><td width=\"60%\">Räume:</td><td width=\"40%\" align=\"right\">$Rooms</td></tr>\n" if $Rooms;
			$html_out .= "<tr class=\"font-white\"><td width=\"60%\">Wohnfläche ca.:</td><td width=\"40%\" align=\"right\">". add_points(sprintf("%.2f", $LivingAreaQM / 100), 3) ." m²</td></tr>\n" if $LivingAreaQM;
			$html_out .= "<tr class=\"font-white\"><td width=\"60%\">Grundstück ca.:</td><td width=\"40%\" align=\"right\">". add_points(sprintf("%.2f", $LandAreaQM / 100), 3) ." m²</td></tr>\n" if $LandAreaQM;
			$html_out .= "<tr class=\"font-white\"><td width=\"60%\">Kaufpreis:</td><td width=\"40%\" align=\"right\">". convert_price($PurchasePrice) ." €</td></tr>\n" if $PurchasePrice;
			$html_out .= "<tr class=\"font-white\"><td width=\"60%\">Lage:</td><td width=\"40%\" align=\"right\">". convert_level($Level) ."</td></tr>\n" if $Level;
			$html_out .= "</table>\n";
		}
		elsif ($query{'CategorieGroupId'} == 3) {
			# Gewerbe/Industrie
			$html_out .= "<table border=\"0\" width=\"100%\" cellspacing=\"0\" cellpadding=\"2\">\n";
			$html_out .= "<tr class=\"font-white\"><td width=\"60%\">Räume:</td><td width=\"40%\" align=\"right\">$Rooms</td></tr>\n" if $Rooms;
			$html_out .= "<tr class=\"font-white\"><td width=\"60%\">Nutzfläche ca.:</td><td width=\"40%\" align=\"right\">". add_points(sprintf("%.2f", $LivingAreaQM / 100), 3) ." m²</td></tr>\n" if $LivingAreaQM;
			$html_out .= "<tr class=\"font-white\"><td width=\"60%\">Grundstück ca.:</td><td width=\"40%\" align=\"right\">". add_points(sprintf("%.2f", $LandAreaQM / 100), 3) ." m²</td></tr>\n" if $LandAreaQM;
			$html_out .= "<tr class=\"font-white\"><td width=\"60%\">Kaltmiete:</td><td width=\"40%\" align=\"right\">". convert_price($RentalCold) ." €</td></tr>\n" if $RentalCold;
			$html_out .= "<tr class=\"font-white\"><td width=\"60%\">Kaufpreis:</td><td width=\"40%\" align=\"right\">". convert_price($PurchasePrice) ." €</td></tr>\n" if $PurchasePrice;
			$html_out .= "<tr class=\"font-white\"><td width=\"60%\">Lage:</td><td width=\"40%\" align=\"right\">". convert_level($Level) ."</td></tr>\n" if $Level;
			$html_out .= "</table>\n";
		}
		$html_out .= "</div>\n";

		$html_out .= "<div style=\"position:absolute; bottom:0px; width:100%; margin:4px\">";
		$html_out .= "<table border=\"0\" width=\"100%\" cellspacing=\"0\" cellpadding=\"0\">\n";
		$html_out .= "<tr>\n";

	# Button "View" BEGIN
		$html_out .= "<td align=\"right\">\n";
		$html_out .= "<form action=\"$ENV{'SCRIPT_NAME'}\" method=\"$cfg{'TransmitMethodEndUser'}\" name=\"ShowSynopsis$i\" accept-charset=\"$cfg{'DefaultCharacterSet'}\">\n";
		$html_out .= "<input type=\"hidden\" name=\"Action\" value=\"ShowSynopsis\">\n";
		$html_out .= "<input type=\"hidden\" name=\"CategorieGroupId\" value=\"$query{'CategorieGroupId'}\">\n";
		$html_out .= "<input type=\"hidden\" name=\"CategorieId\" value=\"$query{'CategorieId'}\">\n";
		$html_out .= "<input type=\"hidden\" name=\"CityId\" value=\"$query{'CityId'}\">\n";
		$html_out .= "<input type=\"hidden\" name=\"DistrictId\" value=\"$query{'DistrictId'}\">\n";
		$html_out .= "<input type=\"hidden\" name=\"Limit\" value=\"$query{'Limit'}\">\n";
		$html_out .= "<input type=\"hidden\" name=\"EstateId\" value=\"$EstateId\">\n";
		$html_out .= "<input type=\"image\" src=\"http://www.$PortalDomain/.images/system/buttons/view.gif\" border=\"0\" width=\"100\" height=\"20\" alt=\"Exposé anschauen\" title=\"Exposé anschauen\"";
		# Reversed here because we already switched the switch above
		if ($color_switch == 0) {
			$html_out .= " class=\"input-img-button2\">\n";
		}
		else {
			$html_out .= " class=\"input-img-button1\">\n";
		}
		$html_out .= "</td>\n";
		$html_out .= "</tr>\n";
		$html_out .= "</table>\n";
		$html_out .= "</form>\n";
		$html_out .= "</div>\n";
	# Button "View" END

		$html_out .= "</div>\n";
		$html_out .= "</td>\n";
		$html_out .= "</tr>\n";
	# END
	}
	sql_subclose();

$html_out .= <<EOL;
</table><br>
EOL

	# If there is more the on pages:
	$html_out .= more_pages($ResultCount);

	return $html_out;
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub more_pages ($) {
	my $count_objects = shift;

	my $html_out = undef;
	if ($count_objects > $cfg{'ShowMaxEntries'}) {
		my $page_count = round_up($count_objects / $cfg{'ShowMaxEntries'});
		$page_count -= 1;

		$html_out .= "<table border=\"0\" width=\"100%\" cellspacing=\"1\" cellpadding=\"3\">\n";
		$html_out .= "<tr>\n";
		$html_out .= "<td class=\"table-field1\" style=\"padding-top:7px\">\n";

		if ($query{'OrderBy'} =~ /^CityName/) {
			$query{'OrderBy'} = 'CityName';
		}
		elsif ($query{'OrderBy'} =~ /EstateStreetNumber$/) {
			$query{'OrderBy'} = 'EstateStreet';
		}

		# "Back"-Button
		$html_out .= "<table border=\"0\" width=\"100%\" cellspacing=\"0\" cellpadding=\"0\">\n";
		$html_out .= "<tr>\n";
		$html_out .= "<form action=\"$ENV{'SCRIPT_NAME'}\" method=\"$cfg{'TransmitMethodEndUser'}\">\n";
		$html_out .= "<input type=\"hidden\" name=\"Action\" value=\"ShowCategorie\">\n";
		$html_out .= "<input type=\"hidden\" name=\"CategorieId\" value=\"$query{'CategorieId'}\">\n";
		$html_out .= "<input type=\"hidden\" name=\"CityId\" value=\"$query{'CityId'}\">\n";
		$html_out .= "<input type=\"hidden\" name=\"DistrictId\" value=\"$query{'DistrictId'}\">\n";
		$html_out .= "<input type=\"hidden\" name=\"OrderBy\" value=\"$query{'OrderBy'}\">\n";
		$html_out .= "<input type=\"hidden\" name=\"Limit\" value=\"". ($query{'Limit'}-$cfg{'ShowMaxEntries'}) ."\">\n";
		$html_out .= "<td>";
		$html_out .= "<input type=\"image\" src=\"http://www.$PortalDomain/.images/system/buttons/back.gif\" border=\"0\" width=\"90\" height=\"20\" alt=\"Zurück\" title=\"Zurück\"";
		$html_out .= " class=\"input-img-button1\"";
		unless ( ($query{'Limit'}-$cfg{'ShowMaxEntries'}) >= 0) {
			$html_out .= " disabled style=\"width:90px;cursor:default\">";
		}
		else {
			$html_out .= " style=\"width:90px\">";
		}
		$html_out .= "</td>\n";
		$html_out .= "</form>\n";

		# "Next"-Button
		$html_out .= "<form action=\"$ENV{'SCRIPT_NAME'}\" method=\"$cfg{'TransmitMethodEndUser'}\">\n";
		$html_out .= "<input type=\"hidden\" name=\"Action\" value=\"ShowCategorie\">\n";
		$html_out .= "<input type=\"hidden\" name=\"CategorieId\" value=\"$query{'CategorieId'}\">\n";
		$html_out .= "<input type=\"hidden\" name=\"CityId\" value=\"$query{'CityId'}\">\n";
		$html_out .= "<input type=\"hidden\" name=\"DistrictId\" value=\"$query{'DistrictId'}\">\n";
		$html_out .= "<input type=\"hidden\" name=\"OrderBy\" value=\"$query{'OrderBy'}\">\n";
		$html_out .= "<input type=\"hidden\" name=\"Limit\" value=\"". ($query{'Limit'}+$cfg{'ShowMaxEntries'}) ."\">\n";
		$html_out .= "<td>";
		$html_out .= "<input type=\"image\" src=\"http://www.$PortalDomain/.images/system/buttons/next.gif\" border=\"0\" width=\"90\" height=\"20\" alt=\"Weiter\" title=\"Weiter\"";
		$html_out .= " class=\"input-img-button1\"";
		unless ( ($query{'Limit'}/$cfg{'ShowMaxEntries'}) < $page_count ) {
			$html_out .= " disabled style=\"width:90px;cursor:default\">";
		}
		else {
			$html_out .= " style=\"width:90px\">";
		}
		$html_out .= "</td>\n";
		$html_out .= "</form>\n";

		$html_out .= "<td>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;</td>\n";		# Spacer

		# "Jump-to-Page"-Button
		$html_out .= "<form action=\"$ENV{'SCRIPT_NAME'}\" method=\"$cfg{'TransmitMethodEndUser'}\" name=\"goto\">\n";
		$html_out .= "<input type=\"hidden\" name=\"Action\" value=\"ShowCategorie\">\n";
		$html_out .= "<input type=\"hidden\" name=\"CategorieId\" value=\"$query{'CategorieId'}\">\n";
		$html_out .= "<input type=\"hidden\" name=\"CityId\" value=\"$query{'CityId'}\">\n";
		$html_out .= "<input type=\"hidden\" name=\"DistrictId\" value=\"$query{'DistrictId'}\">\n";
		$html_out .= "<input type=\"hidden\" name=\"OrderBy\" value=\"$query{'OrderBy'}\">\n";
		$html_out .= "<td>";
		$html_out .= "<input type=\"image\" src=\"http://www.$PortalDomain/.images/system/buttons/goto.gif\" border=\"0\" width=\"100\" height=\"20\" alt=\"Gehe zu Seite:\" title=\"Gehe zu Seite:\" class=\"input-img-button1\">";
		$html_out .= "</td>";
		$html_out .= "<td>&nbsp;&nbsp;&nbsp;&nbsp;</td>\n";		# Spacer
		$html_out .= "<td>";
		$html_out .= "<select name=\"Limit\" size=\"1\" style=\"width:30px\" onChange=\"document.goto.submit()\">\n";
		for (0..$page_count) {
			my $new_limit = $cfg{'ShowMaxEntries'} * $_;
			$html_out .= "<option value=\"$new_limit\"";
			$html_out .= " selected" if ($new_limit == $query{'Limit'});
			$html_out .= ">". ($_ + 1) ."</option>\n";
		}
		$html_out .= "</select>\n";
		$html_out .= "</td>\n";
		$html_out .= "</form>\n";
		$html_out .= "<td width=\"50%\" align=\"right\">\n";
		$html_out .= "&nbsp;\n";
		$html_out .= "</td>\n";
		$html_out .= "</tr>\n";
		$html_out .= "</table>\n\n";

		$html_out .= "</td>\n";
		$html_out .= "</tr>\n";
		$html_out .= "</table>\n";
	}

	return $html_out;
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub ShowSynopsis ($) {
	my $action = shift;
	my $html_out = undef;

	# Get all names of the columns
	my $table_columns = sql_getcolumns('Estate');

	# Remove all other signs, only Nums needed
	$query{'EstateId'} =~ s/[^\d]//g;

	# Load the Object-Data
	%db_content = sql_selectall_hash("SELECT $table_columns FROM Estate WHERE EstateId='$query{'EstateId'}'", "$table_columns");
	$db_content{'PostalCode'} = '' if ($db_content{'PostalCode'} eq '00000');

	if (($db_content{'Active'}) && ($db_content{'ObjectRented'} != 1) && ($db_content{'ObjectMarked'} != 1) && ($query{'EstateId'}) && ($db_content{'EstateId'} == $query{'EstateId'})) {
		$html_out .= ViewObject($action);
	}
	else {
		$html_out .= "<h1>Es ist eine Fehler aufgetreten!</h1>\n";
		$html_out .= "<h3>Dieses Objekt konnte nicht gefunden werden!</h3>\n";
		$html_out .= "<p>Vielleicht ist dieses Objekt nicht mehr verfügbar oder\n";
		$html_out .= "die angegebene Immo-Id ist fehlerhaft (wenn Sie die Schnellansicht genutzt haben)!</p>\n";
		$html_out .= "<p>Sie können aber dennoch Ihrer gewünschte Immobilie finden, indem Sie in der linken\n";
		$html_out .= "Navigationsleiste - unter der Rubrik <b>Inhalt</b> - die von Ihnen gewünschte Kategorie (z.B. <a href=\"/User/Browse/Rent/\">Mieten</a>, <a href=\"/User/Browse/Buy/\">Kaufen</a> oder <a href=\"/User/Browse/Industry/\">Gewerbe-/Industrie</a>)\n";
		$html_out .= "auswählen.</p>\n";
		$html_out .= "<p>Alternativ können Sie auch die Funktion <a href=\"/User/Search/\">Suchen</a> nutzen um die gewünschte Immobilie aufzufinden.</p>\n";
	}

	return $html_out;
}


#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub ViewObject ($) {
	my $action = shift;
	my $html_out = undef;

	# Prepare the Data for viewing to the User
	my ($room, $small_room) = split('\.', $db_content{'Rooms'} );
	$db_content{'Rooms'} = $room;
	$db_content{'Rooms'} .= " ½" if $small_room;

	$db_content{'Description'} =~ s/\n/<br>/g;
	$db_content{'Location'} =~ s/\n/<br>/g;

	if ( $db_content{'AssetValueDate'} ne '0000-00-00' ) {
		my ($Year, $Month, $Day) = split('-', $db_content{'AssetValueDate'});
		my $today_short = $today;
		$today_short =~ s/\-//g;
		if ("$Year$Month$Day" <= "$today_short") {
			$db_content{'AssetValueDate'} = "sofort";
		}
		else {
			$db_content{'AssetValueDate'} = "$Day. ". $Month{ sprintf("%d", $Month) } ." $Year";
		}
		undef $today_short;
	}
	elsif ( $db_content{'AssetValue'} ) {
		$db_content{'AssetValueDate'} = $db_content{'AssetValue'};
	}

$html_out .= <<EOL;
<!-- PAGE BREAK BEGIN -->
<div style="page-break-after:always">

<h1>$db_content{'Announcetitle'}</h1>
<!-- BEGIN Object-Table -->
<table border="0" width="100%" cellspacing="1" cellpadding="0">
<tr>
<td width="45%" rowspan="2">
<!-- BEGIN Object-Data -->
EOL
	$html_out .= "<table border=\"0\" width=\"100%\" cellspacing=\"1\" cellpadding=\"3\">\n";
	$html_out .= "<tr class=\"table-header\">";
	$html_out .= "<td colspan=\"2\" class=\"headline\">Objektübersicht</td>";
	$html_out .= "</tr>\n";

	my $color_count = 2;
	if ($db_content{'Rooms'}) {
		$html_out .= "<tr class=\"table-field". color_switch($color_count) ."\"><td width=\"40%\">Räume:</td><td width=\"60%\" align=\"right\">$db_content{'Rooms'}</td></tr>\n";
		$color_count++;
	}
	if ($db_content{'LivingAreaQM'}) {
		$html_out .= "<tr class=\"table-field". color_switch($color_count) ."\"><td width=\"40%\">Fläche ca.:</td><td width=\"60%\" align=\"right\">". convert_square_meter($db_content{'LivingAreaQM'}) ." m²</td></tr>\n";
		$color_count++;
	}
	if ($db_content{'LandAreaQM'}) {
		$html_out .= "<tr class=\"table-field". color_switch($color_count) ."\"><td width=\"40%\">Grundstück ca.:</td><td width=\"60%\" align=\"right\">". convert_square_meter($db_content{'LandAreaQM'}) ." m²</td></tr>\n";
		$color_count++;
	}
	if ($db_content{'ProductionAreaQM'}) {
		$html_out .= "<tr class=\"table-field". color_switch($color_count) ."\"><td width=\"40%\">Produktionsfläche ca.:</td><td width=\"60%\" align=\"right\">". convert_square_meter($db_content{'ProductionAreaQM'}) ." m²</td></tr>\n";
		$color_count++;
	}
	if ($db_content{'BesideAreaQM'}) {
		$html_out .= "<tr class=\"table-field". color_switch($color_count) ."\"><td width=\"40%\">Nebenfläche ca.:</td><td width=\"60%\" align=\"right\">". convert_square_meter($db_content{'BesideAreaQM'}) ." m²</td></tr>\n";
		$color_count++;
	}
	if ($db_content{'CarParkingSpaceIncluded'}) {
		$html_out .= "<tr class=\"table-field". color_switch($color_count) ."\"><td width=\"40%\">PKW-Stellplätze:</td><td width=\"60%\" align=\"right\">$db_content{'CarParkingSpaceIncluded'}</td></tr>\n";
		$color_count++;
	}
	if ($db_content{'AssetValueDate'} ne '0000-00-00') {
		$html_out .= "<tr class=\"table-field". color_switch($color_count) ."\"><td>Frei ab:</td><td align=\"right\">$db_content{'AssetValueDate'}</td></tr>\n";
		$color_count++;
	}
	if ($db_content{'Level'}) {
		$html_out .= "<tr class=\"table-field". color_switch($color_count) ."\"><td>Etage:</td><td align=\"right\">";
		$html_out .= convert_level($db_content{'Level'});
		$html_out .= " (von $db_content{'LevelTotal'})" if ($db_content{'LevelTotal'});
		$html_out .= "</td></tr>\n";
		$color_count++;
	}
	elsif ($db_content{'LevelTotal'}) {
		$html_out .= "<tr class=\"table-field". color_switch($color_count) ."\"><td>Etage(n):</td><td align=\"right\">";
		$html_out .= "$db_content{'LevelTotal'} (insgesamt)";
		$html_out .= "</td></tr>\n";
		$color_count++;
	}
	if ($db_content{'ObjectTypeId'}) {
		my $objecttype = sql_selectall("SELECT ObjectType FROM ObjectType WHERE ObjectTypeId='$db_content{'ObjectTypeId'}'");
		$html_out .= "<tr class=\"table-field". color_switch($color_count) ."\"><td>Objektart:</td><td align=\"right\">$objecttype</td></tr>\n";
		$color_count++;
	}
	if ($db_content{'ObjectStateId'}) {
		my $objectstate = sql_selectall("SELECT ObjectState FROM ObjectState WHERE ObjectStateId='$db_content{'ObjectStateId'}'");
		$html_out .= "<tr class=\"table-field". color_switch($color_count) ."\"><td>Objektzustand:</td><td align=\"right\">$objectstate</td></tr>\n";
		$color_count++;
	}
	if ($db_content{'YearOfConstruction'}) {
		$html_out .= "<tr class=\"table-field". color_switch($color_count) ."\"><td>Baujahr:</td><td align=\"right\">$db_content{'YearOfConstruction'}</td></tr>\n";
		$color_count++;
	}
	if ($db_content{'HandicappedRight'}) {
		$html_out .= "<tr class=\"table-field". color_switch($color_count) ."\"><td>Behindertengerecht:</td><td align=\"right\">Ja</td></tr>\n";
		$color_count++;
	}


	$html_out .= "\n<!-- END Object-Data -->\n";
	$html_out .= "<tr><td colspan=\"2\">&nbsp;</td></tr>\n";
	$html_out .= "<!-- BEGIN Object-Costs -->\n\n";
	$html_out .= "<tr class=\"table-header\"><td colspan=\"2\"><span class=\"headline\">Kostenübersicht</span></td></tr>\n";


	if ($db_content{'RentalCold'}) {
		$html_out .= "<tr class=\"table-field". color_switch($color_count) ."\"><td>Kaltmiete:</td><td align=\"right\">". convert_price($db_content{'RentalCold'}) ." &euro;</td></tr>\n";
		$color_count++;
	}
	if ($db_content{'AdditionalCosts'}) {
		$html_out .= "<tr class=\"table-field". color_switch($color_count) ."\"><td>Nebenkosten ca.:</td><td align=\"right\">". convert_price($db_content{'AdditionalCosts'}) ." &euro;</td></tr>\n";
		$color_count++;
	}
	if ($db_content{'HeatingCost'}) {
		$html_out .= "<tr class=\"table-field". color_switch($color_count) ."\"><td>Heizkosten ca.:</td><td align=\"right\">". convert_price($db_content{'HeatingCost'}) ." &euro;</td></tr>\n";
		$color_count++;
	}
	if ($db_content{'RentalWarm'}) {
		$html_out .= "<tr class=\"table-field". color_switch($color_count) ."\"><td>Warmmiete ca.:</td><td align=\"right\">". convert_price($db_content{'RentalWarm'}) ." &euro;</td></tr>\n";
		$color_count++;
	}
	if ($db_content{'PurchasePrice'}) {
		$html_out .= "<tr class=\"table-field". color_switch($color_count) ."\"><td>Kaufpreis:</td><td align=\"right\">". convert_price($db_content{'PurchasePrice'}) ." &euro;</td></tr>\n";
		$color_count++;
	}
	if ($db_content{'CarParkingSpacePrice'}) {
		$html_out .= "<tr class=\"table-field". color_switch($color_count) ."\"><td>Preis je PKW-Stellplatz:</td><td align=\"right\">". convert_price($db_content{'CarParkingSpacePrice'}) ." &euro;</td></tr>\n";
		$color_count++;
	}
	if ($db_content{'RentalDepositation'}) {
		$html_out .= "<tr class=\"table-field". color_switch($color_count) ."\"><td>Mietsicherheit:</td><td align=\"right\">$db_content{'RentalDepositation'}</td></tr>\n";
		$color_count++;
	}
	if ($db_content{'CooperativeSocietyRatesQuantity'}) {
		$html_out .= "<tr class=\"table-field". color_switch($color_count) ."\"><td>Genossenschaftsanteile:</td><td align=\"right\">". $db_content{'CooperativeSocietyRatesQuantity'} ." Anteile</td></tr>\n";
		$color_count++;
	}
	if ($db_content{'CooperativeSocietyRatesPrice'}) {
		$html_out .= "<tr class=\"table-field". color_switch($color_count) ."\"><td>Preis je Genossenschaftsanteil:</td><td align=\"right\">". convert_price($db_content{'CooperativeSocietyRatesPrice'}) ." &euro;</td></tr>\n";
		$color_count++;
	}
	if ($db_content{'BrokersFee'}) {
		$html_out .= "<tr class=\"table-field". color_switch($color_count) ."\"><td>Maklercourtage:</td><td align=\"right\">$db_content{'BrokersFee'}</td></tr>\n";
		$color_count++;
	}


	$html_out .= "<!-- END Object-Costs -->\n";

	if ( $db_content{'InteriorEquipmentIds'} ) {
		$html_out .= "<tr><td colspan=\"2\">&nbsp;</td></tr>\n";

		$html_out .= "<!-- BEGIN Object-Content -->\n";
		$html_out .= "<tr class=\"table-header\">\n";
		$html_out .= "<td colspan=\"2\"><span class=\"headline\">Ausstattungsmerkmale</span></td>\n";
		$html_out .= "</tr>\n";
		$html_out .= "<tr class=\"table-field1\">";
		$html_out .= "<td colspan=\"2\">";
		my @InteriorEquipment = sql_selectall("SELECT Interior FROM InteriorEquipment WHERE InteriorId REGEXP '^(". join('|', split(',',$db_content{'InteriorEquipmentIds'}) ) .")\$' ORDER BY Interior");
		foreach my $Interior (@InteriorEquipment) {
			$html_out .= "$Interior, ";
		}
		$html_out =~ s/, $//;
		$html_out .= "</td>";
		$html_out .= "</tr>\n";
		$html_out .= "\n<!-- END Object-Content -->\n";
	}
	$html_out .= "</table></p>\n";
	$html_out .= "<!-- END Object-Table -->\n\n";


	# BEGIN ShowAddress
#	my ($EstatePostalCode, $EstateCityName, $EstateDistrict) = sql_selectall("SELECT pc.PostalCode,c.CityName,d.District FROM City AS c LEFT JOIN District AS d ON d.CityId=c.CityId AND d.DistrictId='$db_content{'DistrictId'}' WHERE c.CityId='$db_content{'CityId'}'");
	my ($EstateCityName, $CityNameAddition, $EstateDistrict) = sql_selectall("SELECT c.CityName,c.CityNameAddition,d.District FROM Estate AS e LEFT JOIN City AS c ON e.CityId=c.CityId LEFT JOIN District AS d ON e.DistrictId=d.DistrictId WHERE e.EstateId='$db_content{'EstateId'}' LIMIT 1");
	$html_out .= "<p><b>Adresse:</b><br>";
	if ($db_content{'ShowAddress'}) {
		$html_out .= "$db_content{'EstateStreet'} $db_content{'EstateStreetNumber'}<br>";
	}
	else {
		$html_out .= "Die vollständige Adresse erhalten Sie vom Anbieter.<br>";
	}
	$html_out .= $db_content{'PostalCode'} ? "$db_content{'PostalCode'} " : "$db_content{'PostalCodeAlt'} ";
	$html_out .= $EstateCityName ? "$EstateCityName " : "$db_content{'CityAlt'} ";
	$html_out .= "$CityNameAddition " if $CityNameAddition && $cfg{'ShowCityNameAddition'};
	$html_out .= "($EstateDistrict)" if $EstateDistrict;
	$html_out .= "<br>\nGewerbegebiet: $db_content{'IndustrialPark'}" if ( $db_content{'IndustrialPark'} );
	$html_out .= "<br>\nGebiet: $db_content{'ConstructionArea'}" if ( $db_content{'ConstructionArea'} );
	$html_out .= "</p>\n\n";
	# END ShowAddress


	# Change the PageTitle to the "Announcetitle" and add PostalCode and City
	if ($db_content{'Announcetitle'} ne '') {
		$cfg{'PortalClaim'} = "$db_content{'Announcetitle'} / $db_content{'PostalCode'} $EstateCityName";
		$cfg{'PortalClaim'} .= " ($EstateDistrict)" if $EstateDistrict;
	}
	else {
		if ($query{'CategorieGroupId'} == 1) {
			# Categorie "Rent"
			$cfg{'PortalClaim'} = "Wohnungen und Immobilien zur Miete/Pacht / $db_content{'PostalCode'} $EstateCityName";
			$cfg{'PortalClaim'} .= " ($EstateDistrict)" if $EstateDistrict;
		}
		elsif ($query{'CategorieGroupId'} == 2) {
			# Categorie "Buy"
			$cfg{'PortalClaim'} = "Wohnungen und Immobilien zum Kauf / $db_content{'PostalCode'} $EstateCityName";
			$cfg{'PortalClaim'} .= " ($EstateDistrict)" if $EstateDistrict;
		}
		elsif ($query{'CategorieGroupId'} == 3) {
			# Categorie "Industry"
			$cfg{'PortalClaim'} = "Gewerbe- / Industrieobjekte zum Kauf oder zur Miete/Pacht / $db_content{'PostalCode'} $EstateCityName";
			$cfg{'PortalClaim'} .= " ($EstateDistrict)" if $EstateDistrict;
		}
	}


	# BEGIN View Table "Id-Nr."
	$html_out .= "<p><table border=\"0\" width=\"100%\" cellspacing=\"0\" cellpadding=\"0\">\n";
	$html_out .= "<tr>\n";

	$html_out .= "<td width=\"50%\"><b>Immo-Id:</b><br>". add_points($db_content{'EstateId'}, 4) ."</td>\n";
	if ($db_content{'InternalId'}) {
		$html_out .= "<td width=\"50%\"><b>Anbieter-Objekt-Nr.:</b><br>$db_content{'InternalId'}</td>\n";
	}
	else {
		$html_out .= "<td width=\"50%\">&nbsp;</td>\n";
	}
	$html_out .= "</tr>\n";
	$html_out .= "</table>\n\n";
	# END View Table "Id-Nr."


	$html_out .= "</td>\n";
	$html_out .= "<td width=\"55%\" height=\"5%\" style=\"padding-left:15px\">\n";

	if ($db_content{'JudicialSale'}) {
		$html_out .= "<div class=\"judicial-sale\"> &nbsp; Zwangsversteigerung &nbsp; </div>\n";
	}

	if ($action ne 'Print') {
	# BEGIN Code for the Images in viewing Object
		my ($ImageId, $ImageTyp, $ImageTitle, $ImageWidthOrig, $ImageHeightOrig);
		sql_query("SELECT ImageId,ImageTyp,ImageTitle,ImageWidthOrig,ImageHeightOrig FROM Images WHERE EstateId='$query{'EstateId'}' AND (ImageTyp='2' OR ImageTyp='0') ORDER BY ImageId,ImageTyp ASC");
		sql_bindcolumns( \($ImageId, $ImageTyp, $ImageTitle, $ImageWidthOrig, $ImageHeightOrig) );

		my ($first_ImageId, $first_ImageTitle, $first_ImageWidthOrig, $first_ImageHeightOrig);
		my $i = 1;
		while ( sql_fetch() ) {
			if ($i == 1) {
				($first_ImageId, $first_ImageTitle, $first_ImageWidthOrig, $first_ImageHeightOrig) = ($ImageId, $ImageTitle, $ImageWidthOrig, $ImageHeightOrig);
				$html_out .= "<script language=\"JavaScript\" type=\"text/javascript\">\n";
				$html_out .= "<!--\n";
				$html_out .= "if (document.images) {\n";
			}
			$ImageTitle = 'Ohne Titel' if (! $ImageTitle);
			$html_out .= "	i". sprintf("%02d", $i) ."b = new Image($ImageWidthOrig,$ImageHeightOrig);\n";
			$html_out .= "	i". sprintf("%02d", $i) ."b.src = '$cfg{'ImageUploadUrl'}CustomerId-$cfg{'CustomerId'}/EstateId-$db_content{'EstateId'}/$ImageId-orig$cfg{'UploadImageExtention'}';\n";
			$html_out .= "	i". sprintf("%02d", $i) ."b.title = '$ImageTitle';\n\n";
			$i++;
		}
		if ($i > 1) {
			$html_out .= "}\n";
			$html_out .= "//-->\n";
			$html_out .= "</script>\n";
		}
		sql_finish();

		# Show the first Image
		$html_out .= "<img name=\"img0\" src=\"$cfg{'ImageUploadUrl'}CustomerId-$cfg{'CustomerId'}/EstateId-$db_content{'EstateId'}/$first_ImageId-orig$cfg{'UploadImageExtention'}\" width=\"$first_ImageWidthOrig\" height=\"$first_ImageHeightOrig\" alt=\"$first_ImageTitle\" title=\"$first_ImageTitle\" class=\"img-list\"><br>\n";

		# $i still holds the quantity of Images, but counting from 1, also do we -1!
		if ($i > 2) {
			$html_out .= "Bilder: ";
			for ( 1..($i-1) ) {
				$html_out .= "<a href=\"javascript:void(0)\" onClick=\"switchImage('img0','i". sprintf("%02d", $_) ."');return false\" alt=\"Bild-Nr. $_ anzeigen\" title=\"Bild-Nr. $_ anzeigen\">$_</a> ";
			}
		}

		if ($db_content{'GeocodeId'}) {
			# The "Action=Roadmap" is not needed by the Script in "/User/Roadmap/", but needed by
			# index.pl for selecting the correct HTML-Template.
			$html_out .= "<br><a href=\"javascript:void(0)\" onClick=\"roadmap('http://www.$PortalDomain/User/Maps/?Action=Roadmap&EstateId=$db_content{'EstateId'}');return false\">Straßenkarte</a>";
		}

		my $floorplan = 0;
		my (@ImageId) = sql_selectall("SELECT ImageId FROM Images WHERE EstateId='$query{'EstateId'}' AND ImageTyp='1'");
		if ( scalar(@ImageId) ) {

			# This is needed by "EnergyCert" for finding out if we have to set a Point before!
			$floorplan = 1;

 			$html_out .= " &#0149; " if $db_content{'GeocodeId'};

			# The "Action=Floorplan" is not needed by the Script in "/User/Floorplan/", but needed by
			# index.pl for selecting the correct HTML-Template.
			$html_out .= "<a href=\"javascript:void(0)\" onClick=\"floorplan('$ENV{'SCRIPT_NAME'}?Action=Floorplan&EstateId=$db_content{'EstateId'}";
			foreach (@ImageId) {
				$html_out .= "&ImageId=$_";
			}
			$html_out .= "');return false\">Grundriß</a>\n";
		}
		undef @ImageId;

		my (@ImageId) = sql_selectall("SELECT ImageId FROM Images WHERE EstateId='$query{'EstateId'}' AND ImageTyp='3'");
		if ( scalar(@ImageId) ) {
 			$html_out .= " &#0149; " if ($db_content{'GeocodeId'} || $floorplan);

			# The "Action=Floorplan" is not needed by the Script in "/User/EnergyCertificate/", but needed by
			# index.pl for selecting the correct HTML-Template.
			$html_out .= "<a href=\"javascript:void(0)\" onClick=\"floorplan('$ENV{'SCRIPT_NAME'}?Action=EnergyCertificate&EstateId=$db_content{'EstateId'}";
			foreach (@ImageId) {
				$html_out .= "&ImageId=$_";
			}
			$html_out .= "');return false\">Energiepass</a>\n";
		}
		undef @ImageId;
	# END Code for the Images
	}
	else {
	# BEGIN Code for the Images in Print-Preview
		my ($ImageId, $ImageTyp, $ImageTitle, $ImageWidthOrig, $ImageHeightOrig) = sql_selectall("SELECT ImageId,ImageTyp,ImageTitle,ImageWidthOrig,ImageHeightOrig FROM Images WHERE EstateId='$query{'EstateId'}' AND (ImageTyp='2' OR ImageTyp='0') ORDER BY ImageTyp ASC LIMIT 1");
		$html_out .= "<p><img src=\"$cfg{'ImageUploadUrl'}CustomerId-$cfg{'CustomerId'}/EstateId-$db_content{'EstateId'}/$ImageId-orig$cfg{'UploadImageExtention'}\" width=\"$ImageWidthOrig\" height=\"$ImageHeightOrig\" alt=\"$ImageTitle\" title=\"$ImageTitle\" class=\"img-list\"><br>\n";
		$html_out .= "<b>Bild-Titel:</b> $ImageTitle" if $ImageTitle;
		$html_out .= "</p>\n";

	# END Code for the Images in Print-Preview
	}

	$html_out .= "</td>\n";
	$html_out .= "</tr>\n";
	$html_out .= "<tr>\n";
	$html_out .= "<td style=\"padding-left:15px;padding-top:10px;\">\n";

	$html_out .= "<p align=\"justify\"><b>Beschreibung</b><br>$db_content{'Description'}</p>\n" if $db_content{'Description'};
	$html_out .= "<p align=\"justify\"><b>Lage</b><br>$db_content{'Location'}</p>\n" if $db_content{'Location'};

	$html_out .= "</td>\n";
	$html_out .= "</tr>\n";
	$html_out .= "<tr>\n";
	$html_out .= "<td colspan=\"2\">&nbsp;</td>\n";
	$html_out .= "</tr>\n";
	$html_out .= "<tr>\n";
	$html_out .= "<td valign=\"top\">\n";
	$html_out .= "<b>Anbieter:</b><br>\n";

	# BEGIN Customer-Logo
	my ($Company, $CompanyAddition1, $CompanyAddition2, $Address, $Title, $Firstname, $Lastname, $Street, $StreetNumber, $PostalCode, $City, $PhonePrefix, $Phone, $FaxPrefix, $Fax, $Email, $Homepage, $LogoWidth, $LogoHeight);
	if ( $db_content{'PersonId'} ) {
		($Company, $CompanyAddition1, $CompanyAddition2, $Address, $Title, $Firstname, $Lastname, $Street, $StreetNumber, $PostalCode, $City, $PhonePrefix, $Phone, $FaxPrefix, $Fax, $Email, $Homepage, $LogoWidth, $LogoHeight) = sql_selectall("SELECT c.Company,c.CompanyAddition1,c.CompanyAddition2,cp.Address,cp.Title,cp.Firstname,cp.Lastname,cp.Street,cp.StreetNumber,cp.PostalCode,cp.City,cp.PhonePrefix,cp.Phone,cp.FaxPrefix,cp.Fax,cp.Email,cp.Homepage,c.LogoWidth,c.LogoHeight FROM `Customer_$cfg{'DB_User'}` AS c, `CustomerContactPerson_$cfg{'DB_User'}` AS cp WHERE c.CustomerId='$cfg{'CustomerId'}' AND cp.PersonId='$db_content{'PersonId'}' LIMIT 1");
	}

	if (! $Company) {
		($Company, $CompanyAddition1, $CompanyAddition2, $Address, $Title, $Firstname, $Lastname, $Street, $StreetNumber, $PostalCode, $City, $PhonePrefix, $Phone, $FaxPrefix, $Fax, $Email, $Homepage, $LogoWidth, $LogoHeight) = sql_selectall("SELECT c.Company,c.CompanyAddition1,c.CompanyAddition2,cp.Address,cp.Title,cp.Firstname,cp.Lastname,cp.Street,cp.StreetNumber,cp.PostalCode,cp.City,cp.PhonePrefix,cp.Phone,cp.FaxPrefix,cp.Fax,cp.Email,cp.Homepage,c.LogoWidth,c.LogoHeight FROM `Customer_$cfg{'DB_User'}` AS c, `CustomerContactPerson_$cfg{'DB_User'}` AS cp WHERE c.CustomerId='$cfg{'CustomerId'}' AND cp.CustomerId=c.CustomerId ORDER BY cp.PersonId LIMIT 1");
	}



	$html_out .= "</td>\n";
	$html_out .= "<td style=\"padding-left:15px\">\n";

	# BEGIN Table Customer-Address
	$Phone = add_spaces($Phone, 2);
	$Fax = add_spaces($Fax, 2);

	$html_out .= "<br><b>$Company</b><br>\n";
	$html_out .= "$CompanyAddition1<br>\n" if $CompanyAddition1;
	$html_out .= "$CompanyAddition2<br>\n" if $CompanyAddition2;
	$html_out .= "$Street $StreetNumber<br>\n" if ($Street);
	$html_out .= "$PostalCode $City<br>\n" if (($PostalCode) || ($City));
	$html_out .= "<br>\n";
	$html_out .= "Telefon: ($PhonePrefix) $Phone<br>\n" if $Phone;
	$html_out .= "Telefax: ($FaxPrefix) $Fax<br>\n" if $Fax;
	$html_out .= "<br>\n";
	$html_out .= "Ansprechpartner: $Address $Title $Firstname $Lastname" if ($Lastname);
	$html_out .= "<br>\n";

# BEGIN Customer Contact-Buttons
	if (($action eq '') || ($action ne 'Print') || ($action eq 'ViewPhone')) {
$html_out .= <<EOL;
<br>
<table border="0" width="98%" cellspacing="0" cellpadding="0" style="position:static; bottom:0px;">
<tr>
<td width="33%">
EOL
		if ($Email) {
$html_out .= <<EOL;
<form action="$ENV{'SCRIPT_NAME'}" method="$cfg{'TransmitMethodEndUser'}">
<input type="hidden" name="Action" value="Contact">
<input type="hidden" name="CustomerId" value="$cfg{'CustomerId'}">
<input type="hidden" name="EstateId" value="$db_content{'EstateId'}">
<input type="image" src="http://www.$PortalDomain/.images/system/buttons/email.gif" border="0" width="100" height="20" alt="Kontakt per Email mit dem Anbieter aufnehmen" title="Kontakt per Email mit dem Anbieter aufnehmen" class="input-img-button">
</form>
EOL
		}
		else {
			$html_out .= "&nbsp;";
		}

		$html_out .= "</td>\n";
		$html_out .= "<td width=\"33%\" align=\"center\">\n";
		$html_out .= "&nbsp;";
		$html_out .= "</td>\n";
		$html_out .= "<td width=\"33%\" align=\"right\">\n";
		$html_out .= "&nbsp;";
		$html_out .= "</td>\n";
		$html_out .= "</tr>\n";
		$html_out .= "</table>\n";
	}
# END Customer Contact-Buttons


	# END Table Customer-Address

	$html_out .= "</td>\n";
	$html_out .= "</tr>\n";
	$html_out .= "</table><br>\n";


	# Show the Buttons not at the Print-Preview!
	if ($action ne 'Print') {
	# BEGIN Function-Buttons
		$html_out .= "<table border=\"0\" width=\"100%\" cellspacing=\"0\" cellpadding=\"0\">\n";
		$html_out .= "<tr class=\"table-field1\">\n";
		$html_out .= "<td align=\"right\">\n\n";

		$html_out .= "<table border=\"0\" cellspacing=\"0\" cellpadding=\"5\">\n";
		$html_out .= "<tr>\n";

		# BEGIN Print-Button
		$html_out .= "<td align=\"right\">\n";
		$html_out .= "<form action=\"$ENV{'SCRIPT_NAME'}\" method=\"$cfg{'TransmitMethodEndUser'}\" target=\"_new\">\n";
		$html_out .= "<input type=\"hidden\" name=\"Action\" value=\"Print\">\n";
		$html_out .= "<input type=\"hidden\" name=\"EstateId\" value=\"$query{'EstateId'}\">\n";
		$html_out .= "<input type=\"image\" src=\"http://www.$PortalDomain/.images/system/buttons/print.gif\" border=\"0\" width=\"100\" height=\"20\" alt=\"Dieses Objekt ausdrucken\" title=\"Dieses Objekt ausdrucken\" class=\"input-img-button1\">\n";
		$html_out .= "</td>\n";
		$html_out .= "</form>\n";
		# BEGIN Print-Button

		$html_out .= "</tr>\n";
		$html_out .= "</table>\n";

		$html_out .= "</td>\n";
		$html_out .= "</tr>\n";
		$html_out .= "</table>\n";

		$html_out .= "\n<!-- PAGE BREAK END -->\n";
		$html_out .= "</div>\n";
	# END Function-Buttons
	}
	else {
		# Show the next Pages with all other Images, Floorplan, Roadmap and so on.
		$html_out .= "\n<!-- PAGE BREAK END -->\n";
		$html_out .= "</div>\n";

	# BEGIN Code for the Images in viewing Object
		my ($ImageId, $ImageTyp, $ImageTitle, $ImageWidthOrig, $ImageHeightOrig);
		my $result = sql_query("SELECT ImageId,ImageTyp,ImageTitle,ImageWidthOrig,ImageHeightOrig FROM Images WHERE EstateId='$query{'EstateId'}' AND (ImageTyp='2' OR ImageTyp='0') ORDER BY ImageTyp ASC");

		if (( $result ne '0E0') && ( $result >= 2 )) {
			sql_bindcolumns( \($ImageId, $ImageTyp, $ImageTitle, $ImageWidthOrig, $ImageHeightOrig) );

			$html_out .= "<!-- PAGE BREAK BEGIN -->\n";
			$html_out .= "<div style=\"page-break-after:auto\">\n";

			my $i = 0;
			my $columns = 1;
			$html_out .= "\n<table border=\"0\" width=\"100%\" cellspacing=\"0\" cellpadding=\"5\">\n";
			while ( sql_fetch() ) {
				# The First-Image will be ignored, because it is already showed above
				if ($i == 0) {
					$i++;
					next;
				}

				if ($columns == 1) {
					$html_out .= "<tr>\n";
					$columns++;
				}

				$html_out .= "<td><img src=\"$cfg{'ImageUploadUrl'}CustomerId-$cfg{'CustomerId'}/EstateId-$db_content{'EstateId'}/$ImageId-orig$cfg{'UploadImageExtention'}\" width=\"$ImageWidthOrig\" height=\"$ImageHeightOrig\" alt=\"$ImageTitle\" title=\"$ImageTitle\" class=\"img-list\"><br>";
				$html_out .= "<b>Bild-Titel:</b> $ImageTitle</td>\n";
				if ($columns == 3) {
					$html_out .= "</tr>\n";
					$columns = 0;
				}
				$columns++;
				$i++;
			}
			sql_finish();

			for ($columns..3) {
				$html_out .= "<td>&nbsp;</td>\n";
			}
			$html_out .= "</tr>\n";
			$html_out .= "</table>\n\n";

			$html_out .= "\n<!-- PAGE BREAK END -->\n";
			$html_out .= "</div>\n";
		}
	# END Code for the Images

		# Show the Roadmap if there is one.
		if ( $db_content{'GeocodeId'} ) {
			$html_out .= "<!-- PAGE BREAK BEGIN -->\n";
			$html_out .= "<div style=\"page-break-before:always\">\n";

			$html_out .= "<iframe src=\"http://www.$PortalDomain/User/Maps/?Action=Roadmap&EstateId=$db_content{'EstateId'}\" width=\"642\" height=\"642\" scrolling=\"no\" marginheight=\"0\" marginwidth=\"0\" frameborder=\"0\" name=\"Map\"></iframe>\n";

			$html_out .= "\n<!-- PAGE BREAK END -->\n";
			$html_out .= "</div>\n";
		}

		# Show the Floorplan if there is one.
		my (@ImageId) = sql_selectall("SELECT ImageId FROM Images WHERE EstateId='$query{'EstateId'}' AND ImageTyp='1'");
		if ( scalar(@ImageId) ) {
			$html_out .= "<!-- PAGE BREAK BEGIN -->\n";
			$html_out .= "<div style=\"page-break-before:always\">\n";

			$html_out .= ShowFloorplan($query{'EstateId'}, join('|', @ImageId) );

			$html_out .= "\n<!-- PAGE BREAK END -->\n";
			$html_out .= "</div>\n";
		}

		# Show the EnergyCertificate if there is one.
		my (@ImageId) = sql_selectall("SELECT ImageId FROM Images WHERE EstateId='$query{'EstateId'}' AND ImageTyp='3'");
		if ( scalar(@ImageId) ) {
			$html_out .= "<!-- PAGE BREAK BEGIN -->\n";
			$html_out .= "<div style=\"page-break-before:always\">\n";

			$html_out .= ShowEnergyCertificate($query{'EstateId'}, join('|', @ImageId) );

			$html_out .= "\n<!-- PAGE BREAK END -->\n";
			$html_out .= "</div>\n";
		}
	}

	return $html_out;
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub ShowFloorplan ($$) {
	my $EstateId = shift;
	my $GivenImageIds = shift;

	my $html_out = undef;

	my ($ImageId, $EstateId, $ImageTitle, $ImageWidthOrig, $ImageHeightOrig);
	if ($GivenImageIds =~ /\|/) {
		($ImageId, $EstateId, $ImageTitle, $ImageWidthOrig, $ImageHeightOrig) = sql_query("SELECT ImageId,EstateId,ImageTitle,ImageWidthOrig,ImageHeightOrig FROM Images WHERE ImageId REGEXP \"^($GivenImageIds)\$\"");
	}
	else {
		($ImageId, $EstateId, $ImageTitle, $ImageWidthOrig, $ImageHeightOrig) = sql_query("SELECT ImageId,EstateId,ImageTitle,ImageWidthOrig,ImageHeightOrig FROM Images WHERE ImageId='$GivenImageIds'");
	}
	sql_bindcolumns( \($ImageId, $EstateId, $ImageTitle, $ImageWidthOrig, $ImageHeightOrig) );
	while ( sql_fetch() ) {
		$html_out .= "<br><br><b>Grundriß-Titel: $ImageTitle</b><br>\n";
		$html_out .= "<table border=\"0\" width=\"100%\" cellspacing=\"0\" cellpadding=\"0\" align=\"center\">\n";
		$html_out .= "<tr>\n";
		$html_out .= "<td>\n";

		$html_out .= "<img src=\"$cfg{'ImageUploadUrl'}CustomerId-$cfg{'CustomerId'}/EstateId-$EstateId/$ImageId-orig$cfg{'UploadImageExtention'}\" width=\"$ImageWidthOrig\" height=\"$ImageHeightOrig\" alt=\"$ImageTitle\" title=\"$ImageTitle\" class=\"img-list\">\n";

		$html_out .= "</td>\n";
		$html_out .= "</tr>\n";
		$html_out .= "</table>\n";
	}
	sql_finish();
	return $html_out;
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub ShowEnergyCertificate ($$) {
	my $EstateId = shift;
	my $GivenImageIds = shift;

	my $html_out = undef;

	my ($ImageId, $EstateId, $ImageTitle, $ImageWidthOrig, $ImageHeightOrig);
	if ($GivenImageIds =~ /\|/) {
		($ImageId, $EstateId, $ImageTitle, $ImageWidthOrig, $ImageHeightOrig) = sql_query("SELECT ImageId,EstateId,ImageTitle,ImageWidthOrig,ImageHeightOrig FROM Images WHERE ImageId REGEXP \"^($GivenImageIds)\$\"");
	}
	else {
		($ImageId, $EstateId, $ImageTitle, $ImageWidthOrig, $ImageHeightOrig) = sql_query("SELECT ImageId,EstateId,ImageTitle,ImageWidthOrig,ImageHeightOrig FROM Images WHERE ImageId='$GivenImageIds'");
	}
	sql_bindcolumns( \($ImageId, $EstateId, $ImageTitle, $ImageWidthOrig, $ImageHeightOrig) );
	while ( sql_fetch() ) {
		$html_out .= "<br><br><b>Energie-Zertifikat-Titel: $ImageTitle</b><br>\n";
		$html_out .= "<table border=\"0\" width=\"100%\" cellspacing=\"0\" cellpadding=\"0\" align=\"center\">\n";
		$html_out .= "<tr>\n";
		$html_out .= "<td>\n";

		$html_out .= "<img src=\"$cfg{'ImageUploadUrl'}CustomerId-$cfg{'CustomerId'}/EstateId-$EstateId/$ImageId-orig$cfg{'UploadImageExtention'}\" width=\"$ImageWidthOrig\" height=\"$ImageHeightOrig\" alt=\"$ImageTitle\" title=\"$ImageTitle\" class=\"img-list\">\n";

		$html_out .= "</td>\n";
		$html_out .= "</tr>\n";
		$html_out .= "</table>\n";
	}
	sql_finish();
	return $html_out;
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub CheckForm {
	my $isOk = 0;
	my @EmptyKeys = ();
	my @Keys = qw(Address Firstname Lastname Street StreetNumber PostalCode City PhonePrefix Phone Email);
	my $key_count = scalar(@Keys);
	foreach my $key (@Keys) {
		if ($key eq 'Email') {
			if (( $query{'Email'} ) && ( Email::Valid->address(-address => $query{'Email'}, -fqdn => 0, -tldcheck => 0) )) {
				$isOk++;
			}
			else {
				push(@EmptyKeys, $key, ($Email::Valid::Details || 1) );
			}
		}
		else {
			if ( $query{"$key"} ) {
				$isOk++;
			}
			else {
				push(@EmptyKeys, $key, 1);
			}
		}
	}
	if ($isOk == $key_count) {
		return PrepareMail();
	}
	else {
		return ContactForm(@EmptyKeys);
	}
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub PrepareMail {
	my $html_out = undef;

	if ($query{'Email'}) {

		# Get all names of the columns
		my $table_columns = sql_getcolumns('Estate');

		# Load the Object-Data
		%db_content = sql_selectall_hash("SELECT $table_columns FROM Estate WHERE EstateId='$query{'EstateId'}'", "$table_columns");
		$db_content{'PostalCode'} = '' if ($db_content{'PostalCode'} eq '00000');

my $body = <<EOL;
Vielen Dank für die Nutzung von $cfg{'MirrorHomepageUrl'}!

Wir haben Ihre Anfrage bereits an den zuständigen Ansprechpartner per
Email versendet. Dieser wird schnellstmöglich mit Ihnen Kontakt
aufnehmen und Ihnen die gewünschten Informationen oder den
Besichtigungstermin nennen!

Mit freundlichen Grüßen Ihr $cfg{'MirrorHomepageUrl'}-Team


Informationen zur ausgewählten Immobilie:
------------------------------------------------------------------------
EOL
		# BEGIN ShowAddress
#		my ($EstatePostalCode, $EstateCityName, $EstateDistrict) = sql_selectall("SELECT pc.PostalCode,c.CityName,d.District FROM City AS c LEFT JOIN District AS d ON d.CityId=c.CityId AND d.DistrictId='$db_content{'DistrictId'}' LEFT JOIN PostalCode AS pc ON pc.PostalCodeId='$db_content{'PostalCodeId'}' WHERE c.CityId='$db_content{'CityId'}'");
		my ($EstateCityName, $CityNameAddition, $EstateDistrict) = sql_selectall("SELECT c.CityName,c.CityNameAddition,d.District FROM Estate AS e LEFT JOIN City AS c ON e.CityId=c.CityId LEFT JOIN District AS d ON e.DistrictId=d.DistrictId WHERE e.EstateId='$db_content{'EstateId'}' LIMIT 1");

		$body .= "Objekt-Adresse:\n";
		if ($db_content{'ShowAddress'}) {
			$body .= "$db_content{'EstateStreet'} $db_content{'EstateStreetNumber'}\n";
		}
		else {
			$body .= "Die vollständige Adresse erhalten Sie vom Anbieter.\n";
		}
		$body .= $db_content{'PostalCode'} ? "$db_content{'PostalCode'} " : "$db_content{'PostalCodeAlt'} ";
		$body .= $EstateCityName ? "$EstateCityName " : "$db_content{'CityAlt'} ";
		$body .= "$CityNameAddition " if $CityNameAddition && $cfg{'ShowCityNameAddition'};
		$body .= "($EstateDistrict)" if $EstateDistrict;
		# END ShowAddress

$body .= <<EOL;
------------------------------------------------------------------------


Hier können Sie das Online-Exposé für dieses Objekt anschauen:
http://www.$PortalDomain/User/Synopsis/?EstateId=$query{'EstateId'}



Nachfolgend sehen Sie nochmal Ihre Angaben:
------------------------------------------------------------------------
EOL

		$body .= "Immo-Id..............: $query{'EstateId'} (für die Schnellansicht!)\n\n";

		$body .= "Unternehmen..........: $query{'Company'}\n\n",
		$body .= "Anrede...............: $query{'Address'}\n";
		$body .= "Name.................: ";
		$body .= "$query{'Title'} " if $query{'Title'};
		$body .= "$query{'Firstname'} $query{'Lastname'}\n\n";

		$body .= "Strasse..............: $query{'Street'} $query{'StreetNumber'}\n";
		$body .= "PLZ / Ort............: $query{'PostalCode'} $query{'City'}\n\n";

		$body .= "Telefon..............: ($query{'PhonePrefix'}) ". add_spaces($query{'Phone'}, 2) ."\n";
		$body .= "Telefax..............: ($query{'FaxPrefix'}) ". add_spaces($query{'Fax'}, 2) ."\n" if $query{'Fax'};
		$body .= "Mobil................: $query{'MobilPrefix'} - ". add_spaces($query{'Mobil'}, 2) ."\n" if $query{'Mobil'};

		$body .= "\n";
		$body .= "Email................: $query{'Email'}\n\n";

		$body .= "Besichtigungstermin..: $query{'Besichtigungstermin'}\n" if $query{'Besichtigungstermin'};
		$body .= "Informationen........: $query{'Informationen'}\n" if $query{'Informationen'};
		$body .= "\n";
		$body .= "Erreichbar...........: ". join(', ', split('\|', $query{'ContactDate'}) ) ."\n" if $query{'ContactDate'};
		$body .= "In der Zeit von......: $query{'ContactTimeFrom'} bis $query{'ContactTimeTo'}\n" if (($query{'ContactTimeFrom'}) || ($query{'ContactTimeTo'}));

$body .= <<EOL;

Nachricht............:
----------------------
$query{'Message'}
------------------------------------------------------------------------
EOL
		# Send the Mail to the Sender.
		sendmail(
			$query{'Email'},				# To:
			$cfg{'MailAddress'},				# From:
			"Kontakt über $cfg{'MirrorHomepageUrl'}",	# Subject:
			$body,						# Body
		);
	}


	# This Email goes to the Immo-AP
	my ($Address, $Firstname, $Lastname, $Email);
	if ( $db_content{'PersonId'} ) {
		($Address, $Firstname, $Lastname, $Email) = sql_selectall("SELECT cp.Address,cp.Firstname,cp.Lastname,cp.Email FROM `Customer_$cfg{'DB_User'}` AS c, `CustomerContactPerson_$cfg{'DB_User'}` AS cp WHERE c.CustomerId='$cfg{'CustomerId'}' AND cp.PersonId='$db_content{'PersonId'}' LIMIT 1");
	}
	else {
		($Address, $Firstname, $Lastname, $Email) = sql_selectall("SELECT cp.Address,cp.Firstname,cp.Lastname,cp.Email FROM `Customer_$cfg{'DB_User'}` AS c, `CustomerContactPerson_$cfg{'DB_User'}` AS cp WHERE c.CustomerId='$cfg{'CustomerId'}' AND cp.CustomerId=c.CustomerId LIMIT 1");
	}

my $body .= <<EOL;

Guten Tag $Address $Firstname $Lastname!

Diese Email erhalten Sie, weil ein Interessent auf einer Ihrer
eingestellten Exposés in dem Immo-Portal $cfg{'MirrorHomepageUrl'} Interesse
zeigt.

Bitte nehmen Sie schnellstmöglich Kontakt mit dem Interessenten auf!


Es handelt sich dabei um folgendes Objekt:
------------------------------------------------------------------------
Immo-Id..............: $query{'EstateId'}
Ihre interne Id......: $db_content{'InternalId'}
------------------------------------------------------------------------


Hier können Sie das Online-Exposé für dieses Objekt anschauen:
http://www.$PortalDomain/User/Synopsis/?EstateId=$query{'EstateId'}



Folgende Kontaktinformationen wurden getätig:
------------------------------------------------------------------------
EOL
	$body .= "Unternehmen..........: $query{'Company'}\n\n";

	$body .= "Anrede...............: $query{'Address'}\n";
	$body .= "Name.................: ";
	$body .= "$query{'Title'} " if $query{'Title'};
	$body .= "$query{'Firstname'} $query{'Lastname'}\n";

	$body .= "Strasse..............: $query{'Street'} $query{'StreetNumber'}\n";
	$body .= "PLZ / Ort............: $query{'PostalCode'} $query{'City'}\n\n";

	$body .= "Telefon..............: ($query{'PhonePrefix'}) ". add_spaces($query{'Phone'}, 2) ."\n";
	$body .= "Telefax..............: ($query{'FaxPrefix'}) ". add_spaces($query{'Fax'}, 2) ."\n" if $query{'Fax'};
	$body .= "Mobil................: $query{'MobilPrefix'} - ". add_spaces($query{'Mobil'}, 2) ."\n" if $query{'Mobil'};

	$body .= "\n";
	$body .= "Email................: $query{'Email'}\n\n";

	$body .= "Besichtigungstermin..: $query{'Besichtigungstermin'}\n" if $query{'Besichtigungstermin'};
	$body .= "Informationen........: $query{'Informationen'}\n" if $query{'Informationen'};
	$body .= "\n";
	$body .= "Erreichbar...........: ". join(', ', split('\|', $query{'ContactDate'}) ) ."\n" if $query{'ContactDate'};
	$body .= "In der Zeit von......: $query{'ContactTimeFrom'} bis $query{'ContactTimeTo'}\n" if (($query{'ContactTimeFrom'}) || ($query{'ContactTimeTo'}));

$body .= <<EOL;

Nachricht............:
----------------------
$query{'Message'}
------------------------------------------------------------------------


Mit freundlichen Grüßen Ihr $cfg{'MirrorHomepageUrl'}-Team
EOL

	# Send the Mail to the Object-Contact
	sendmail(
		$Email,										# To:
		$cfg{'MailAddress'},								# From:
		"Kontakt über $cfg{'MirrorHomepageUrl'} wegen Immo-Id: $query{'EstateId'}",	# Subject:
		$body,										# Body
	);

$html_out .= <<EOL;
<h1>Kontaktaufnahme mit dem Immobilien-Anbieter</h1>
<h3>Vielen Dank für Ihre Anfrage!</h3>

<p>Wir haben Ihre Anfrage bereits an den zuständigen Ansprechpartner per
Email versendet. Dieser wird schnellstmöglich mit Ihnen Kontakt
aufnehmen und Ihnen die gewünschten Informationen oder den
Besichtigungstermin nennen!</p>
EOL

	return $html_out;
}

#///////////////////////////////////////////////////////////////////////#
#									#
#///////////////////////////////////////////////////////////////////////#

sub ContactForm (@) {
    	my (%empty_fields) = @_;

	my $html_out = undef;

	# Get all names of the columns
	my $table_columns = sql_getcolumns('Estate');
	my %db_content = sql_selectall_hash("SELECT $table_columns FROM Estate WHERE EstateId='$query{'EstateId'}'", "$table_columns");
	$db_content{'PostalCode'} = '' if ($db_content{'PostalCode'} eq '00000');

$html_out .= <<EOL;
<h1>Kontaktaufnahme mit dem Immobilien-Anbieter</h1>
<h3>Nutzen Sie dieses Formular mit dem Immobilien-Anbieter in Kontakt zu treten</h3>

<p>Füllen Sie bitte alle Felder aus, somit können Sie sicherstellen, dass
Ihre Anfrage schnellstmöglich beantwortet werden kann. Pflichtfelder sind
mit einen Sternchen (*) markiert.</p>
EOL
	my $error_count = 0;
	foreach my $key (keys %empty_fields) {
		$error_count += $empty_fields{$key} if ($empty_fields{$key} =~ /^[0-9]+$/);
	}
	if ($error_count > 0) {
		$html_out .= "<p class=\"red\">Es wurden nicht alle Pflichtfelder ausgefüllt, bitte füllen Sie alle Pflichtfelder aus!<br>\n";
		$html_out .= "Pflichtfelder die nicht ausgefüllt wurden, sind rot markiert. Bitte füllen Sie diese aus.</p>\n";
	}
	if ( $empty_fields{'Email'} ) {
		$html_out .= "<p class=\"red\">Die Email-Adresse die Sie angegeben haben ist fehlerhaft, bitte überprüfen Sie Ihre Angaben!<br>\n";
		if ( $empty_fields{'Email'} eq 'rfc822' ) {
			$html_out .= "Detailbeschreibung: Die Email-Adresse ist keine nach RFC-822 gültige und syntaktisch korrekte Email-Adresse!\n";
		}
		elsif ( $empty_fields{'Email'} eq 'tldcheck' ) {
			$html_out .= "Detailbeschreibung: Die Email-Adresse enthält eine ungültige Top-Level-Domain!\n";
		}
		elsif ( $empty_fields{'Email'} eq 'mxcheck' ) {
			$html_out .= "Detailbeschreibung: Die Email-Adresse hat keine Gegenstelle, die Emails für diese Domain annimmt, kann also nicht zugestellt werden!\n";
		}
		$html_out .= "</p>\n";
	}

$html_out .= <<EOL;
<table border="0" width="100%" cellspacing="1" cellpadding="5">
<tr class="table-header">
<td colspan="3">Zu folgendem Objekt möchten Sie Kontakt mit dem Immobilien-Anbieter aufnehmen:</td>
</tr>
<tr class="table-field1">
EOL
	# BEGIN ShowAddress
#	my ($EstatePostalCode, $EstateCityName, $EstateDistrict) = sql_selectall("SELECT pc.PostalCode,c.CityName,d.District FROM City AS c LEFT JOIN District AS d ON d.CityId=c.CityId AND d.DistrictId='$db_content{'DistrictId'}' LEFT JOIN PostalCode AS pc ON pc.PostalCodeId='$db_content{'PostalCodeId'}' WHERE c.CityId='$db_content{'CityId'}'");
	my ($EstateCityName, $CityNameAddition, $EstateDistrict) = sql_selectall("SELECT c.CityName,c.CityNameAddition,d.District FROM Estate AS e LEFT JOIN City AS c ON e.CityId=c.CityId LEFT JOIN District AS d ON e.DistrictId=d.DistrictId WHERE e.EstateId='$db_content{'EstateId'}' LIMIT 1");
	$html_out .= "<td width=\"40%\"><b>Objekt-Adresse:</b><br>";
	if ($db_content{'ShowAddress'}) {
		$html_out .= "$db_content{'EstateStreet'} $db_content{'EstateStreetNumber'}<br>";
	}
	else {
		$html_out .= "Die vollständige Adresse erhalten Sie vom Anbieter.<br>";
	}
	$html_out .= $db_content{'PostalCode'} ? "$db_content{'PostalCode'} " : "$db_content{'PostalCodeAlt'} ";
	$html_out .= $EstateCityName ? "$EstateCityName " : "$db_content{'CityAlt'} ";
	$html_out .= "$CityNameAddition " if $CityNameAddition && $cfg{'ShowCityNameAddition'};
	$html_out .= "($EstateDistrict)" if $EstateDistrict;
	# END ShowAddress

	my ($Address, $Title, $Firstname, $Lastname);
	if ( $db_content{'PersonId'} ) {
		($Address, $Title, $Firstname, $Lastname) = sql_selectall("SELECT cp.Address,cp.Title,cp.Firstname,cp.Lastname FROM `CustomerContactPerson_$cfg{'DB_User'}` AS cp LEFT JOIN Customer AS c ON c.CustomerId=cp.CustomerId WHERE c.CustomerId='$cfg{'CustomerId'}' AND cp.PersonId='$db_content{'PersonId'}' LIMIT 1");
	}
	else {
		($Address, $Title, $Firstname, $Lastname) = sql_selectall("SELECT cp.Address,cp.Title,cp.Firstname,cp.Lastname FROM `Customer_$cfg{'DB_User'}` AS c, `CustomerContactPerson_$cfg{'DB_User'}` AS cp WHERE c.CustomerId='$cfg{'CustomerId'}' AND cp.CustomerId=c.CustomerId ORDER BY cp.PersonId LIMIT 1");
	}

	$html_out .= "<td width=\"35%\"><b>Ansprechpartner:</b><br>$Address $Firstname $Lastname</td>\n";

	$html_out .= "<td width=\"25%\"><b>Immo-Id:</b><br> ". add_points($db_content{'EstateId'}, 4) ."</td>\n";

$html_out .= <<EOL;
</tr>
</table>

<form action="$ENV{'SCRIPT_NAME'}" method="POST">
<input type="hidden" name="Action" value="Send">
<input type="hidden" name="CustomerId" value="$cfg{'CustomerId'}">
<input type="hidden" name="EstateId" value="$db_content{'EstateId'}">

<table border="0" width="100%" cellspacing="1" cellpadding="3">
<tr>
<td width="34%">&nbsp;</td>
<td width="33%">&nbsp;</td>
<td width="33%">&nbsp;</td>
</tr>
<tr>
<td colspan="3" class="table-header">Ihre Kontaktinformationen</td>
</tr>
<tr class="table-field1">
<td>Unternehmen</td>
<td colspan="2"><input type="text" name="Company" value="$query{'Company'}" size="28" style="width:260px"></td>
</tr>

<tr class="table-field2">
EOL
	$html_out .= "<td>";
	if ($empty_fields{'Address'}) {
		$html_out .= "<span class=\"red-noline\">Anrede</span>";
	}
	else {
		$html_out .= "Anrede";
	}
	$html_out .= " *</td>\n";

$html_out .= <<EOL;
<td colspan="2">
<select size="1" name="Address">
EOL
	foreach my $key ('','Frau','Herr') {
		$html_out .= "<option value=\"$key\"";
		$html_out .= " selected" if ($query{'Address'} eq $key);
		$html_out .= ">$key</option>\n";
	}


$html_out .= <<EOL;
</select>
</td>
</tr>
<tr class="table-field1">
<td>Titel</td>
<td colspan="2"><input type="text" name="Title" value="$query{'Title'}" size="5" style="width:127px"></td>
</tr>
<tr class="table-field2">
EOL
	$html_out .= "<td>";
	if ($empty_fields{'Firstname'}) {
		$html_out .= "<span class=\"red-noline\">Vorname</span>";
	}
	else {
		$html_out .= "Vorname";
	}
	$html_out .= ", ";
	if ($empty_fields{'Lastname'}) {
		$html_out .= "<span class=\"red-noline\">Nachname</span>";
	}
	else {
		$html_out .= "Nachname";
	}
	$html_out .= " *</td>\n";

$html_out .= <<EOL;
<td colspan="2"><input type="text" name="Firstname" value="$query{'Firstname'}" size="13" style="width:127px"> <input type="text" name="Lastname" value="$query{'Lastname'}" size="13" style="width:128px"></td>
</tr>
<tr class="table-field1">
EOL
	$html_out .= "<td>";
	if ($empty_fields{'Street'}) {
		$html_out .= "<span class=\"red-noline\">Straße</span>";
	}
	else {
		$html_out .= "Straße";
	}
	$html_out .= ", ";
	if ($empty_fields{'StreetNumber'}) {
		$html_out .= "<span class=\"red-noline\">Nr.</span>";
	}
	else {
		$html_out .= "Nr.";
	}
	$html_out .= " *</td>\n";

$html_out .= <<EOL;
<td colspan="2"><input type="text" name="Street" value="$query{'Street'}" size="23" style="width:200px"> <input type="text" name="StreetNumber" value="$query{'StreetNumber'}" size="3" style="width:55px"></td>
</tr>
<tr class="table-field2">
EOL
	$html_out .= "<td>";
	if ($empty_fields{'PostalCode'}) {
		$html_out .= "<span class=\"red-noline\">Postleitzahl</span>";
	}
	else {
		$html_out .= "Postleitzahl";
	}
	$html_out .= ", ";
	if ($empty_fields{'City'}) {
		$html_out .= "<span class=\"red-noline\">Ort</span>";
	}
	else {
		$html_out .= "Ort";
	}
	$html_out .= " *</td>\n";

$html_out .= <<EOL;
<td colspan="2"><input type="text" name="PostalCode" value="$query{'PostalCode'}" size="5" style="width:55px"> <input type="text" name="City" value="$query{'City'}" size="21" style="width:200px"></td>
</tr>

<tr><td colspan="3">&nbsp;</td></tr>

<tr class="table-field1">
EOL
	$html_out .= "<td>";
	if ($empty_fields{'PhonePrefix'}) {
		$html_out .= "<span class=\"red-noline\">Vorwahl</span>";
	}
	else {
		$html_out .= "Vorwahl";
	}
	$html_out .= ", ";
	if ($empty_fields{'Phone'}) {
		$html_out .= "<span class=\"red-noline\">Telefon</span>";
	}
	else {
		$html_out .= "Telefon";
	}
	$html_out .= " *</td>\n";

$html_out .= <<EOL;
<td colspan="2"><input type="text" name="PhonePrefix" value="$query{'PhonePrefix'}" size="5" style="width:55px"> <input type="text" name="Phone" value="$query{'Phone'}" size="21" style="width:200px"></td>
</tr>
<tr class="table-field2">
<td>Vorwahl, Telefax</td>
<td colspan="2"><input type="text" name="FaxPrefix" value="$query{'FaxPrefix'}" size="5" style="width:55px"> <input type="text" name="Fax" value="$query{'Fax'}"size="21" style="width:200px"></td>
</tr>
<tr class="table-field1">
<td>Vorwahl, Mobil</td>
<td colspan="2"><input type="text" name="MobilPrefix" value="$query{'MobilPrefix'}" size="5" style="width:55px"> <input type="text" name="Mobil" value="$query{'Mobil'}" size="21" style="width:200px"></td>
</tr>
<tr class="table-field2">
EOL
	$html_out .= "<td>";
	if ($empty_fields{'Email'}) {
		$html_out .= "<span class=\"red-noline\">Email</span>";
	}
	else {
		$html_out .= "Email";
	}
	$html_out .= " *</td>\n";

$html_out .= <<EOL;
<td colspan="2"><input type="text" name="Email" value="$query{'Email'}" size="28" style="width:260px"></td>
</tr>

<tr><td colspan="3"><br><br></td></tr>

<tr>
<td colspan="3" class="table-header">Sie möchten...</td>
</tr>
<tr class="table-field1">
<td>...einen Besichtigungstermin vereinbaren?</td>
<td colspan="2">
EOL

	$html_out .= "<input type=\"radio\" name=\"Besichtigungstermin\" value=\"vereinbaren\" style=\"border:none\"";
	$html_out .= " checked" if $query{'Besichtigungstermin'};
	$html_out .= "> Ja<br>\n";
	$html_out .= "<input type=\"radio\" name=\"Besichtigungstermin\" value=\"\" style=\"border:none\"";
	$html_out .= " checked" unless $query{'Besichtigungstermin'};
	$html_out .= "> Nein<br>\n";

$html_out .= <<EOL;
</td>
</tr>
<tr class="table-field2">
<td>...weitere Informationen anfordern?</td>
<td colspan="2">
EOL

	$html_out .= "<input type=\"radio\" name=\"Informationen\" value=\"anfordern\" style=\"border:none\"";
	$html_out .= " checked" if $query{'Informationen'};
	$html_out .= "> Ja<br>\n";
	$html_out .= "<input type=\"radio\" name=\"Informationen\" value=\"\" style=\"border:none\"";
	$html_out .= " checked" unless $query{'Informationen'};
	$html_out .= "> Nein<br>\n";

$html_out .= <<EOL;
</td>
</tr>

<tr><td colspan="3"><br><br></td></tr>

<tr>
<td colspan="3" class="table-header">Wann sind Sie am besten telefonisch zu erreichen?</td>
</tr>
<tr class="table-field1">
<td>Am...</td>
<td colspan="2">
EOL
#	for ( qw(Montag Dienstag Mittwoch Donnerstag Freitag Samstag Sonntag) ) {
	for ( qw(Montag Dienstag Mittwoch Donnerstag Freitag) ) {
		$html_out .= "<input type=\"checkbox\" name=\"ContactDate\" value=\"$_\" style=\"border:none\"";
		$html_out .= " checked" if ($_ =~ /^(?:$query{'ContactDate'})$/);
		$html_out .= "> $_<br>\n";
	}

$html_out .= <<EOL;
</td>
</tr>
<tr class="table-field2">
<td>In der Zeit von...</td>
<td colspan="2">
<select name="ContactTimeFrom" size="1" style="width:80px">
EOL
	for (7..21) {
		my $hour = $_;
		for ( qw(0 15 30 45) ) {
			my $contact_time = sprintf("%02d:%02d", $hour, $_);
			$html_out .= "<option value=\"$contact_time:00\"";
			$html_out .= " selected" if ($query{'ContactTimeFrom'} eq "$contact_time:00");
			$html_out .= ">$contact_time</option>\n";
		}
	}

$html_out .= <<EOL;
</select>
Uhr, bis...
<select name="ContactTimeTo" size="1" style="width:80px">
EOL
	for (7..21) {
		my $hour = $_;
		for ( qw(0 15 30 45) ) {
			my $contact_time = sprintf("%02d:%02d", $hour, $_);
			$html_out .= "<option value=\"$contact_time:00\"";
			$html_out .= " selected" if ($query{'ContactTimeTo'} eq "$contact_time:00");
			$html_out .= ">$contact_time</option>\n";
		}
	}

$html_out .= <<EOL;
</select>
Uhr.
</td>
</tr>

<tr><td colspan="3"><br><br></td></tr>

<tr>
<td colspan="3" class="table-header">Ihre Nachricht/Fragen</td>
</tr>
<tr class="table-field1">
EOL
	if (! $query{'Message'}) {
		$query{'Message'} = "Guten Tag $Address $Firstname $Lastname!\n\n";
	}

$html_out .= <<EOL;
<td colspan="3" align="center"><textarea name="Message" cols="50" rows="10" wrap="virtual" style="width:570px; height:120px; margin-top:8px; margin-bottom:8px;">$query{'Message'}</textarea></td>
</tr>
</table>

<br><br>

<table border="0" width="100%" cellspacing="0" cellpadding="3">
<tr>
<td colspan="2" class="table-header">Dieses Formular senden oder zurücksetzen</td>
</tr>
<tr class="table-field1">
<td width="50%" align="center"><br><input type="submit" value="Senden" class="submit-buttons"><br>&nbsp;</td>
<td width="50%" align="center"><br><input type="reset" value="Zurücksetzen" class="submit-buttons"><br>&nbsp;</td>
</tr>
</table>

</form>
EOL

	return $html_out;
}
