#!/usr/bin/perl
$|=1;

#リクルート表示処理
=commentout
	初期設定はinit.plで行います
=cut

use CGI::Carp qw(fatalsToBrowser);
use lib '../master/lib';
#use CGI qw(:cgi-lib :cgi);
use CGI qw(:cgi);
use DBI;
use Jcode;
#use AE;
use AETmpl;
use AEPhone;

require 'init.pl';

$tmpl{'index'}	 = "tmp_index.html";
$offset	 = 0;
$limit	 = 5;

$cgifile = "disptopics.cgi";

foreach (param) {
	next unless $_;
	if (param("$_") =~ /\0/) {
		@{$_} = split(/\0/, param("$_"));
		@{$_} = map {jcode($data)->euc} @{$_};
	} else {
		${$_} = jcode(param("$_"))->euc;
	}
}

# テンプレート振り分け
if ($phone{'furiwake'} eq 'mobile') {
	foreach(keys %tmpl) {
		$tmpl{"$_"} =~ s/\.html/_m.html/;
	}
}

$dbh = DBI->connect($ds, $dbuser,dbpass) or exitError("Cannot connect.");

&read_tmpl($tmpl{'index'});
print "Content-type: text/html\n\n";

$content{'cgifile'}		 = $cgifile;

#hit
$sth = $dbh->prepare("select count(*) from topics");
$sth->execute;
if ($sth->errstr) { print $sth->errstr; }
while($ref = $sth->fetchrow_arrayref){
	($hit) = @$ref;
}

$content{'hit'}		 = $hit;
$content{'start'}	 = $hit ? $offset+1 : 0;
$content{'prev'}	 = ($offset-$limit >= 0) ? $offset-$limit : '';
$content{'end'}		 = ($offset+$limit < $hit) ? $offset+$limit : $hit;
$content{'next'}	 = ($offset+$limit < $hit) ? $offset+$limit : '';
$nextnum			 = ($hit-$offset-$limit < $limit) ? $hit-$offset-$limit : $limit;

$sth = $dbh->prepare("select * from topics
	order by date desc, num desc
	offset $offset limit $limit");
$sth->execute;
if ($sth->errstr) { print $sth->errstr; }

$html{'head'} =~ s/%(\w+)%/jcode($content{"$1"})->sjis/ge;
print $html{'head'};
undef $html{'head'};

while($ref = $sth->fetchrow_hashref){
	my %data = %$ref;
	my $body = $html{'body'};
	my ($syear, $smonth, $sday) = split(/-/, $data{'date'});

	$content{'sdate'}	 = sprintf("%4d年%02d月%02d日", $syear, $smonth, $sday);
	$content{'title'}	 = $data{'title'};
	($content{'cmt'}	 = $data{'cmt'}) =~ s/\r\n|\r|\n/<br>\n/g;
	$content{'url'}		 = qq{<a href="$data{'url'}">$data{'url'}</a>};

	$body =~ s/%(\w+)%/jcode($content{"$1"})->sjis/ge;
	print $body;
}
undef $html{'body'};

$content{'older'} = $content{'prev'} ne '' ?
	 qq{<input type="submit" name="submit" value="＜＜前$limit件">} : '';
$content{'newer'} = $content{'next'} ne '' ?
	 qq{<input type="submit" name="submit" value="次$nextnum件＞＞">} : '';

$html{'foot'} =~ s/%(\w+)%/jcode($content{"$1"})->sjis/ge;
print $html{'foot'};

$sth->finish if $sth;
$dbh->disconnect;

exit(0);
