#!/usr/bin/perl

use	strict;
use	HTML::Parser ();
use	LWP;
use	HTTP::Request::Common;
use	Jcode;
use	POSIX qw(strftime);

my $MailAddress = 'shin@opus.or.jp';
my	%timetables = (
		"首里識名線牧志廻り" => "http://okinawa.0152.jp/new_schedule/jikoku.php?id=35&no=1&day=weekday&rosen_no=1",
		"松川線泊廻り" => "http://okinawa.0152.jp/new_schedule/jikoku.php?id=22&no=4&day=weekday&rosen_no=3",
		"識名線牧志廻り" => "http://okinawa.0152.jp/new_schedule/jikoku.php?id=34&no=5&day=weekday&rosen_no=5",
		);

my %t;
my $t;
my $f = 0;

my %timetable;
foreach my $i (keys %timetables) {
	&get_tables($timetables{$i});
	$f = 1;
}
foreach my $j (keys %t) {
	print "$j: ",$t{$j},"\n";
}

my	$tr = 0;
my	$td = 0;

exit 0;

sub	get_tables {
	my ($url) = shift;

	my $ua = LWP::UserAgent->new;
	$ua->agent("UserAgent=" . $ua->agent);
	$ua->from("$MailAddress");
	my $request = HTTP::Request->new(GET => $url);
	$request->headers->last_modified(0);
	my $response = $ua->request($request);
	my $title = '';

	if (! $response->is_success) {
		print "error $url\n";
		return %t;
	}

	my $body = $response->content;
	$body = Jcode->new($body)->h2z->euc;

	 # Create parser object
	my $p = HTML::Parser->new( api_version => 3,
		start_h => [\&start_h, "tagname, attr"],
		end_h => [\&end_h, "tagname, attr"],
		text_h => [\&text_h, "dtext"],
		marked_sections => 1,
		);

	$p->parse($body);
	$p->eof;

	return %t;
}

sub end_h
{
	my ($tagname,$self) = @_;

	if ($tagname eq 'tr') {
		$tr = 0;
		$td = 0;
	}
}

sub start_h
{
	my ($tagname,$self) = @_;

	if ($tagname eq 'tr') {
		$tr++;
	}elsif ($tagname eq 'td') {
		$td++;
	}
}

sub text_h
{
	my ($dtext) = shift;

	if ($td == 1) {
		$t = $dtext;
	}elsif ($td == 2) {
		if ($f == 0) {
			$t{$t} = $dtext;
		}else{
			$t{$t} .= "||$dtext";
		}
	}
}
