#!/usr/bin/perl 

#Double feature finder by Will Carlough 12/01/02
#This is a cgi that that retrieves html from moviefone and parses it so that movies can be seen back to back at a given theatre.
push (@INC, '/usr/lib/perl5/site_perl/5.6.0/LWP');
use strict;
use LWP::UserAgent;
use CGI;
use CGI qw/escape/;
use HTTP::Cookies;
use Data::Dumper;

our ($allHtml, $theatres, $zip, $skip, $dups, $single, $specMovie1, $specMovie2, $url, $dfHeader, $dfHeader2, $dfSuffix, $hopTime, $printBool, $ua, $r, $i, $movieRE, $theatreRE, $site, %shows, %movies, $debug, $theatreMax, $useCache, $scope, $startScope, $endScope, $date, $inMovieId, $inTheatreId, $this, @colors, $searchType, $specTheatre, $q, %times, %theatreHash, $nextUrl, $groupBy, $all);

$debug = 0;
$useCache = 1; 
print STDERR "starting\n" if ($debug);
&initializeVars();

print $r->header;

if ($r->param("inter")) {
&printInter();
}
if (!($zip =~ /^\d{5}$/)) {
    &printHeader();
    &printHeader2();
    print "<h1 class='ooops'>Ooops, you must enter your ZIP code!</h1>";
    exit(0);
}
my $today; 
my $module = "Date::Manip";
my $lwpPrefix;
eval "use $module";
if ($@) { #rhl
    $today =  `date "+%Y%m%d"`;
    $today =~ s/\s//g;
    $lwpPrefix = '/home/redhea5/lwp';
} else { #local
    $today =  &UnixDate("today","%Y%m%d");
    $lwpPrefix = '/tmp';
}
my $cacheFile = "$lwpPrefix/$site/cache/${today}.${zip}.${date}.data";
if ((-e $cacheFile) && ($useCache)) {
    my $allData;
    open DATA_RO, $cacheFile;
    while (<DATA_RO>) {
	   $allData .= $_;
    }
    close DATA_RO;
    my %data = eval ($allData);
    %times = %{$data{times}};
    %shows = %{$data{shows}};
    %movies = %{$data{movies}};
    %theatreHash = %{$data{theatreHash}};
    print STDERR "Got from cache\n" if ($debug);
} else {
    if ($r->param("a") != 1){                   #if initial request, put up dummy page while moviefone page is retrieved
    &printInter();
	    }
    &initializeUa();
    $allHtml = getHtml($url);
    $allHtml =~ m%<a href=\"?([^<>\s\'\"]+)[^>]*>\s*Next%i;
    $nextUrl =  $1;
    $nextUrl =~ s%(.+)%http://movies.aol.com$1% if ($nextUrl);
    $i = 0;
    while ($allHtml =~ m%$theatreRE%gois) {   #separates theatres into separate html bits for each theatre
	if ($i > $theatreMax) {
	    last;
	}
	$$theatres[$i]{url} = $1;
	$$theatres[$i]{id} = $2;
	$$theatres[$i]{name} = $3;
	$$theatres[$i]{html} = $4;
	$$theatres[$i]{id} =~ s/\W//goi;
	$theatreHash{ $$theatres[$i]{id}  }{name} = $$theatres[$i]{name};
	print STDERR "found theatre $$theatres[$i]{name} \n" if ($debug);
	#print STDERR $$theatres[$i]{html} if ($debug);
	if ($site eq 'g') {
	    # ought to be fine
	} elsif ($site eq 'i') {
	    $$theatres[$i]{url} = 'http://imdb.com' . $$theatres[$i]{url};
	} else {
	    $$theatres[$i]{url} =~ s%(.*?)(/(?:showtimes|predir).*)%${1}http://movies.aol.com$2%;
	}
	$i++;
    }
    
    foreach my $theatre (@$theatres)  {       # separates theatre html into separate movies
	my $movieList;
	while ($$theatre{html} =~ m/$movieRE/igos ) {   #separates the movies and figures out the times
	    print STDERR "Found movie\n" if ($debug);
	    my $curMovie;
	    my $tempTimes = $6;
	    $$curMovie{url} = $1;
	    if (defined($3)) {
		$$curMovie{title} = $3;
	    } else { $$curMovie{title} = $4; }
	    $$curMovie{length} = $5;
	    $$curMovie{id} = $2;
	    $$curMovie{id} =~ s/\W//goi;
	    if ($site eq 'g') {
		$$curMovie{url} =~ s%^(/search.*)%http://www.google.com$1%;
		$$curMovie{length} =~ s/(\d+)hrs?\&nbsp\;(\d+)+.*/$1:${2}am/;
		$$curMovie{length} = &timeToMins($$curMovie{length})
		} elsif ($site eq 'i') {
		    $$curMovie{length} =~ s/(\d+)\s+hrs?\s+(\d+)+.*/$1:${2}am/;
		    $$curMovie{length} = &timeToMins($$curMovie{length});
		    #$$curMovie{rt} = &getRt($$curMovie{id});
		    } else {
			$$curMovie{url} =~ s%(.*?)(/predir.*)%${1}http://movies.aol.com$2%;
		    }
	    $movies{ $$curMovie{id} } = $curMovie; 
	    my (%curTimes, %realTimes);
	    while ($tempTimes =~ m%(?:<a href=[^>]*?/rg/showtimes/?location_cinema/([^\s\"<>]+)[^>]+>|<span[^>]+>+|</b>\s*|\|)\s*([\w:]+)%g) { #imdb specific
		my $url = $1;
		my $time = $2;
		if ($url) {
		    $url =~ s/a=10243/a=10252/; #probably gives imdb credit still
		    $url = 'forward.dff?url=' . escape($url);
		}
		$curTimes{$time} = ($url?$url:0);
	    }
	    #$tempTimes =~ s%<[^>]+>|\s*%%iog;
	    foreach my $time (keys %curTimes) {
		my $mins = timeToMins($time,1);
		$realTimes{$mins} = $curTimes{$time};
		print STDERR "$$curMovie{title} $time\n" if ($debug);
	    }
	    $curMovie->{times} = \%realTimes; #[ split /\||\&nbsp\;/, $tempTimes ];
	    
	    push(@$movieList, $curMovie);
	    
	}
	@$theatre{movieList} = $movieList;
    }
    foreach my $theatre (@$theatres) { # make show hash
	$$theatre{html} = undef;
	foreach my $movie (@{$theatre->{movieList}}) {
	    foreach my $time (keys %{$movie->{times}}) {
		my @after;
		my $show = { 'id' => $$movie{id}, 'time' => $time  };
		$times{$time} = 1;
		if (($time < $startScope) || !$startScope)  {
		    #$startScope = $time;
		}
		my $endTime = addMins($movie->{length}, $time);
		if ($endTime > $endScope) {
		    #$endScope = $endTime;
		}
		foreach my $nextMovie (@{$theatre->{movieList}}) {
		    foreach my $nextTime (keys %{$nextMovie->{times}}) {
			if ($$movie{length} && (&subtractMins($nextTime, $endTime) <= $hopTime) && (&subtractMins($nextTime, $endTime) >= 0) && &specMovie($movie->{title}, $nextMovie->{title})
			    && $$movie{id} ne $$nextMovie{id}) {
			    my $nextShow  = {'id' => $$nextMovie{id}, 'time' => $nextTime };
			    push @after , $nextShow; # add to the movies after this list
			    push @{$shows{$$theatre{id}}{$$nextMovie{id}}{$nextTime }{before}}, {'id' => $$movie{id}, 'time' => $time }; # add this show to the before list of the movie after it
			}
		    }
		}
		$shows{ $$theatre{id} }{ $$movie{id}  }{ $time }{after} = \@after; #push the after list
		$shows{ $$theatre{id} }{ $$movie{id}  }{ $time }{url} = $$movie{times}{$time};
	    }
	}
    }

    if ($useCache) {
	open ALLDATA, ">$cacheFile";
	my %data;
	$data{shows} = \%shows;
	$data{movies} = \%movies;
	$data{theatreHash} = \%theatreHash;
	$data{times} = \%times;
	my $dataText = Dumper \%data;
	$dataText =~ s/\$VAR1\s*=\s*\{|\}\;//g;
	print ALLDATA $dataText;
	close ALLDATA;
    }
}

&printHeader();
    foreach my $movieId (keys %movies) { #make the show hash for each movie
	foreach my $theatreId (keys %shows) {
	    if (defined($shows{$theatreId}{$movieId}))  {
		foreach my $time (keys %{$shows{$theatreId}{$movieId}}) {
		    $movies{$movieId}{shows}{$time}{$theatreId} = $shows{$theatreId}{$movieId}{$time};
		}
	    }
	}
    }

print '<style type="text/css" title="text/css">'; #make the movie styles
my $color = 0;
foreach my $movieId (sort byTitle keys %movies) {
    my $width = 100 * $movies{$movieId}{length} / $scope;
	$width =~ s/(\.\d{2})\d+/$1/;
    print ".movie-$movieId \{\n background: " . $colors[  ($color % $#colors) ] . ";\nwidth: ${width}%; \n}\n\n";
    $color++
}
foreach my $time (keys %times) {
        my $realTime = $time;
        if ($realTime < 240) {
            $realTime += 1440;
        }
        my $margin = 100 * ($realTime - $startScope) / $scope;
		$margin =~ s/(\.\d{2})\d+/$1/;
        print ".time-$time \{ margin-left: $margin\%; \}\n\n";
		#print ".time-$time \{ left: $margin\%; \}\n\n";
}
print '</style>';
&printHeader2();


#shows{theatreId}{movieId}{time}
#movies{movieId}{'shows'}{time}

if ($debug) {
    #print STDERR Dumper \%shows;
    #print STDERR Dumper \%movies;
    #print STDERR Dumper $theatres;
}
if (!$q && !$inTheatreId && !$inMovieId && !$all) {
    &printDisam();
 } else {
   print '<table class="scope"><tr><td>10</td><td>11</td><td>12pm</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td><td>8</td><td>9</td><td>10</td><td>11</td><td>12am</td><td class="last">1</td></tr></table>';
    
    print '<div class="flicks">';

    if ($groupBy ne 'time') {
		foreach my $theatreId (sort byName keys %theatreHash) { 
			if ((!$inTheatreId && !$specTheatre) || ($inTheatreId eq $theatreId) || ($specTheatre && ($theatreHash{$theatreId}{name} =~ /$specTheatre/i))) {
				foreach my $movieId (sort byTitle keys %{$shows{$theatreId}}) {
					if ((!$inMovieId && !$specMovie1) || ($inMovieId eq $movieId) || ($specMovie1 && ($movies{$movieId}{title} =~ /$specMovie1/i))) {
						if ($movies{$movieId}{length}) {
							foreach my $time (sort numerically keys %{$shows{$theatreId}{$movieId}}) {
								&printMovie($movieId, $theatreId, $time);
							}
						}
					}
				}
			}
		}
    } else {
		foreach my $time (sort numerically keys %times) {
			foreach my $movieId (keys %movies) {
				if ((!$inMovieId && !$specMovie1) || ($inMovieId eq $movieId) || ($specMovie1 && ($movies{$movieId}{title} =~ /$specMovie1/i))) {
					foreach my $theatreId (keys %{$movies{$movieId}{shows}{$time}}) {
						if ((!$inTheatreId && !$specTheatre) || ($inTheatreId eq $theatreId) || ($specTheatre && ($theatreHash{$theatreId}{name} =~ /$specTheatre/i))) {
							if (($theatreId eq $inTheatreId) || !$inTheatreId) {
								&printMovie($movieId, $theatreId, $time);
						    }
						}
				    }
				}
		    }
		}
    }

	print '</div>';

    if (!$printBool) {
    print "<div class='chunk'><h1 class='ooops'>No luck finding that movie!</h1></div>";
   &printDisam();
} else {
    print '<table class="scope"><tr><td>10</td><td>11</td><td>12pm</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td><td>8</td><td>9</td><td>10</td><td>11</td><td>12am</td><td class="last">1</td></tr></table>';
	print "<div class=\"chunk\"><a href=\"$this?zip=$zip&date=$date\">See a list of ALL nearby theaters and movies</a></div>";
}
}

#if ($specMovie1 || $inMovieId) { #print loop for one movie
#    foreach my $movieId (keys %movies) {
#        if ((($movies{$movieId}{title} =~ /$specMovie1/i) && $specMovie1)  || ( (!$specMovie1) && ($movieId eq $inMovieId) ) ) {
#	    my @lateShows;
#	    foreach my $time (sort numerically keys %{$movies{$movieId}{shows}}) {
#		if ($time <= 480 ) { # if show is before 8am save it for late show
#		    push @lateShows, $time;
#		} else {
#		    foreach my $theatreId (keys %{$movies{$movieId}{shows}{$time}}) {
#			&printMovie($movieId, $theatreId, $time);
#			$printBool = 1;
#		    }
#		}
#	    }
#	    foreach my $time (@lateShows) {
#		foreach my $theatreId (keys %{$movies{$movieId}{shows}{$time}}) {
#		    &printMovie($movieId, $theatreId, $time);
#		    $printBool = 1;
#		}
#	    }
#	}
#    }
#}
#else {
#    foreach my $theatreId (keys %theatreHash) { #print loop for all theatres
#	foreach my $movieId (keys %{$shows{$theatreId}}) {
#	    if ((!$inTheatreId && !$specTheatre) || ($theatreId eq $inTheatreId) || ($specTheatre && $theatreHash{ $theatreId }{'name'} =~ /$specTheatre/i)) { 
#		if ($movies{$movieId}{length}) {
#		    foreach my $time (sort numerically keys %{$shows{$theatreId}{$movieId}}) {
#			&printMovie($movieId, $theatreId, $time);
#		    }
#		}
#	    }
#	}
#   }
#} 
if ($nextUrl) {
    if (!($printBool)) {
	my $forward = makeUrl();
	print "<p>Please wait...<meta http-equiv=\"refresh\" content=\"0;URL=$forward\">";
    } else {
	my $forward = makeUrl(1);
	print "<a href=\"$forward\">Continue</a>\n";
    }
} elsif (!($printBool))  {
   # print "<BR><BR>We couldn't find any double features to your specifications.  <a href='/df.html'>Try again?</a><BR><BR><BR><BR>";
}
if (($printBool) || (!$nextUrl)) {
    print $dfSuffix;
}
print <<__EOGOOGLE__;
<script type="text/javascript"><!--
google_ad_client = "pub-6353160100952174";
google_ad_width = 728;
google_ad_height = 90;
google_ad_format = "728x90_as";
google_ad_type = "text_image";
google_ad_channel = "5413771607";
google_color_border = "010101";
google_color_bg = "010101";
google_color_link = "a9a9ab";
google_color_url = "a9a9ab";
google_color_text = "a9a9ab";
//--></script>
<center>
<script type="text/javascript"
  src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</center>
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-73618-3";
urchinTracker();
</script>
__EOGOOGLE__
print '
<div class="chunk">
	<a class="small" href="mailto:doublefeaturefinder@gmail.com">Contact</a>
</div>
';
print "</body></html>";
print STDERR "END\n";
exit(0);

sub numerically { $a <=> $b; }
sub printMovie {
    my $movieId = shift;
    my $theatreId = shift;
    my $mins = shift; 
    my $time = &minsToTime($mins); 
    $printBool = 1;
    my $after = $shows{$theatreId}{$movieId}{$mins}{after};
    my $before = $shows{$theatreId}{$movieId}{$mins}{before};
    print "<div class=\"reveal\" id=\"${theatreId}_${movieId}_${mins}\">";
    for (my $i = 0; $i <= $#$before; $i++) {
	&printSingle($$before[$i]{id},$theatreId,$$before[$i]{time},1);
    }

    &printSingle($movieId,$theatreId,$mins,0);

    for (my $i = 0; $i <= $#$after; $i++) {
	&printSingle($$after[$i]{id},$theatreId,$$after[$i]{time},1);
    }
    
    print "</div>";
}
sub printSingle {
    my $movieId = shift;
    my $theatreId = shift;
    my $mins = shift;
    my $wow = shift;
    my $time = &minsToTime($mins);
    my $endTime = &minsToTime($mins + $movies{$movieId}{length});
    print "<div class=\"flick movie-$movieId time-$mins " . ($wow?"wow":"") . "\">\n";
    print '<div class="title">' . (($inMovieId || $specMovie1) && !$wow?"":"<a href=\"$this?inMovieId=$movieId&zip=$zip&date=$date\">" ) . $movies{$movieId}{title} . (($inMovieId || $specMovie1) && !$wow ?"":"</a>") . " <!-- <em>$movies{$movieId}{length}min</em> rt: $movies{$movieId}{rt} -->" . "</div>\n";
    if (!$wow) {
        print '<div class="theater">' . ($inTheatreId ?"":"<a href=\"$this?inTheatreId=$theatreId&zip=$zip&date=$date\">") . $theatreHash{ $theatreId }{'name'} . ($inTheatreId?"":"</a>") . "</div>\n";
    }
    if ($shows{ $theatreId }{ $movieId }{ $mins }{url}) {
	print '<a class="buy" href="' .  $shows{ $theatreId }{ $movieId }{ $mins }{url}  . '">Buy!</a>';
    }
    print "\n<div class=\"time\">${time}</div>\n";
    if (!$wow) {
	my $count = 1;
	if ($shows{$theatreId}{$movieId}{$mins}{after}[0]) {$count++;}
	if ($shows{$theatreId}{$movieId}{$mins}{before}[0]) {$count++;}
	if ($count > 1) {
	    print "<div class=\"ff\"><a href=\"\" onclick=\"revealer('${theatreId}_${movieId}_${mins}', 'toggle'); toggleText(this); return false;\">Click for Double Features!</a></div>";
	}
    }
    print "</div>";
}
sub initializeVars {
    $r = new CGI();
    #$site = "m";
    #$site = "g";
    $site = "i";
    $this = $ENV{SCRIPT_NAME};
    $zip = $r->param("zip");
    $skip = $r->param("skip");
    $dups = $r->param("dups");
    $single = $r->param("single");
    $date = $r->param("date");
    $inMovieId = $r->param("inMovieId");
    $inTheatreId = $r->param("inTheatreId");
    $searchType = $r->param("searchType");
    $q = $r->param("q");
    if ($searchType eq 'theatres') {
	$specTheatre = $r->param("q");
    } else {
	$specMovie1 = $r->param("q");
    }
	if ($q) {
		$inMovieId = "";
		$inTheatreId = "";
	}
    $groupBy = $r->param("groupBy");
    if (!$groupBy) {
	$groupBy = 'time';
    } 
    $all = $r->param("all");
    
    $specMovie2 = $r->param("specMovie2");
    $theatreMax = 16;
    @colors = ('#ce9d00', '#993416', '#b31b34', '#8a0752', '#92499e', '#0047b6', '#007fac', '#009878', '#289728', '#9ea900', '#7c7369', '#7b858a', '#855723', '#9f2d20', '#6e2638', '#4189dd', '#6aa94e', '#b2bc00', '#7a52c7', '#d88497');
    # movieRE - 1:url 2:id  3/4:title 5:length 6:times
    # theatreRE - 1:url 2:id 3:name 4:html
    if ($site eq 'g') {
	$url = 'http://www.google.com/search?hl=en&lr=&q=movie%3A+' . $zip . '&btnG=Search';
	$movieRE = '<td valign=top>\s*<font size=-1>\s*<a[^>]*?href=[\'\"]?([^\s\'\">]*?q\=movie\:([^\&\=\'\">]+)+\d{5}[^\s\'\">]*)[^>]*>(([^<]*))(?:<[^>]+>|\s|&nbsp;)*([\w\&\;\s]*).*?<br>(.*?)</td>';
	$theatreRE = '<tr>\s*<td colspan=4>\s*<br>(?:<a[^>]*?href=[\'\"]?([^\s\'\">]+)[^>]*>)?(([^<]+))(.+?</td>)</tr>(?=<tr>\s*<td colspan=4>|</table><br></form><br><table)';
    } elsif ($site eq 'i') {
	$url = 'http://imdb.com/showtimes/location/' . $zip . '/' . $date;
	#$movieRE = '<a name="\w+" href="(/title/(\w+)/)"><b>(([^<]+))(?:<[^>]+>|\s|&nbsp;)+(\d+\s+hrs?\s+\d+\s+mins?).+?(?:Buy Tickets|Showtimes):\s*</b>\s*(.+?)<br><br>';
	$movieRE = '<a name="[\w\-]+"\s+href="((?:/title/|/showtimes/location/\d+/-)(\w+)/?)"><b>(([^<]+))(?:<[^>]+>|\s|&nbsp;)+(\d+\s+hrs?\s+\d+\s+mins?).+?(?:Buy Tickets|Showtimes):\s*(.+?)<br><br>';
	$theatreRE = '<a class="heading" href="(/showtimes/location/\d+/cinema/(\d+)[^<>\s\'\"]*)\">([^<]+)(.*?)(?:<td class="heading" bgcolor="#bbbbff">|</html>)';
    }
    else {
	$url = 'http://movies.aol.com/search/locationresults.adp?csz=' . $zip;
	$movieRE = '<h5>\s*<a[^>]*?href=\'?\"?([^\s\'\"]*?predir[^\s\'\"]*?movie.2fmain[^\s\'\"]*?mid%3d(\d+)[^\s\'\"]*)[^>]*>(?:([^<]+)|\s*<[^>]*?alt=\"([^\">]*)[^>]*>)</a>[^<]*(?:<[^>]+>|\s|&nbsp;?)+(?:\([\w\-]+,\s(\d+) min[^<]*)?(?:<[^>]+>|\s|&nbsp;?)*((?:[\d :\|apm]|</?(?:a|li)[^>]*>)+)';
	$theatreRE = '<h4>\s*<a href=\"(/predir[^>]+showtimes.2ftheater[^>]+?theaterId%3d(\d+)[^>\s\'\"]*)[^>]*>([^<]*)</a>(.+?Nearby Restaurants)';
    }
    if ($r->param("url")) {
	$url = $r->param("url");
    }

    $hopTime = 30;  # the maxiumum amount of time allowed between two movies
    if (($r->param("hopTime")) =~ m/^\d+$/) {$hopTime = $r->param("hopTime")};
    $printBool = 0;
    $i = 0;
    $startScope = 10*60;
    $endScope = 26*60;
    $scope = $endScope - $startScope;
}

sub initializeUa {
    $ua = new LWP::UserAgent;
    $ua->timeout(600);
    $ua->agent("Mozilla/4.0 (compatible; MSIE 5.0; Mac_powerPC)");
    if ($zip =~ /^\d{5}$/) {
	$ua->cookie_jar( HTTP::Cookies->new(
					    'file' => "$lwpPrefix/$site/cookies/$zip.lwp",
					    # where to read/write cookies
					    'autosave' => 1,
					    ));
    }
}

sub getHtml {  #the subroutine responsible for retrieving the html
    my $url = shift;
 
    my $request = new HTTP::Request('GET', $url);
    my $response = $ua->request($request);
    if ($response->is_success) {
        return $response->content();
    } else {
	my $error = "ERROR: Failed to get URL " . $url . ": HTTP Status = " . $response->code . "\n";
            return $error;
      }
}

sub specMovie {  #If the user wants to see a specific movie, this makes sure only double features of that movie will be displayed
    my $firstMovie = shift;
    my $secondMovie = shift;
    my $movieString = $firstMovie . $secondMovie;
    if (!$specMovie1) {return 1;}
    if ($movieString =~ m%$specMovie1%i) {
            if (!(defined($specMovie2))) { return 1;}
            if ($movieString =~ m%$specMovie2%i) {
        return 1; }
    } else {return 0;}
}

sub subtractMins {  # for subtracting times
    my $first = shift;
    my $second = shift;
    if ($second > $first) { $second = $second + 1440 } 
    my $total = $first - $second;
    return $total;
}

sub addMins {   # for adding times
    my $first = shift;
    my $second = shift;
    my $total = $first + $second;
    if ($total > 1440) {
	   $total = $total - 1440;
    }
    return $total;
}

sub minsToMilitary {
    my $input = shift;
    return &minsToTime($input, 1);
}
sub minsToTime {  # for computing time for user to see
    my $input = shift;
    my $military = shift;
    if ($input >= 1440) {
        $input -= 1440;
    }
    my $hour = ($input / 60);
    $hour =~ s%\.\d+%%;
    my $mins = ($input % 60);
    $mins =~ s%^(\d)$%0$1%;
    my $meridian;
    if (!$military) {
	if ($hour >= 12) {
	    $meridian = "pm";
	    $hour = $hour - 12;
	} else { $meridian = "am"; }
	if ($hour == 0) {
	    $hour = 12;
	}
    }
    my $time;
    if ($military) {
	$time = $hour . $mins;
    } else {
	$time = $hour . ":" . $mins . $meridian;
    }
    return $time;
}

sub timeToMins {   # for computing time on moviefone into computer usable format
    my $input = shift;
    my $wrap = shift;
    $input =~ m%(\d+):(\d+)(\w*)%;
    my $hours = $1;
    my $mins = $2;
    my $meridian = $3;
    if (!$meridian) {
	$meridian = 'pm';
    }
    if ($hours == 12) {
	$hours = 0;
    }
    if ($meridian eq "pm")
    {
	$hours = $hours + 12;
    }
        $hours = $hours * 60;
    my $output = $hours + $mins;
    if (($output < 180) && ($wrap)){
        $output +=1440;
    }
    return $output;
}

sub makeUrl {
    my $wait = shift;
    my $ret = "$this?zip=$zip";
    if ($r->param("a")) {
	if ($r->param("url")) {
	    $ret .= "\&url=" . escape($url);
	}
    } else {
	$ret .= "\&url=" . escape($nextUrl);
    }
    if (!$wait) {
	$ret .= "\&a=1";
    }
    #$ret .=  "\&dups=$dups" if $dups;
    #$ret .=  "\&single=$single" if $single;
    $ret .=  "\&specMovie1=$specMovie1" if $specMovie1;
    #$ret .=  "\&specMovie2=$specMovie2" if $specMovie2;
    #$ret .=  "\&hopTime=$hopTime" if ($hopTime != 30);
    $ret .= "\&searchType=$searchType";
    $ret .= "\&q=$q";
    $ret .= "\&date=$date";
    $ret .= "\&groupBy=$groupBy";
    $ret .= "\&inTheatreId=$inTheatreId" if $inTheatreId;
    $ret .= "\&inMovieId=$inMovieId" if $inMovieId;

    return $ret;
}

sub printHeader {
print  <<__EOHTML__;
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<title>Double Feature Finder</title>
</head>
<style type="text/css">
	\@import url("/style.css");
</style>
<script src="/flick.js" type="text/javascript">
</script>
__EOHTML__
}
sub printHeader2 {
print <<__EOHTML2__;
<body>	

<form>
	<table class="brand">
		<tr>
			<td class="logo">
				<a href="/"><img src="/img/logo_small.gif" /></a>
			</td>
			<td class="control">
__EOHTML2__
if ($q || !$zip || 1) {
#    print '<input type="radio" name="searchType" id="movies" value="movies"';

#    if (!$inTheatreId || $searchType ne 'theatres' ) {
#	print  "checked";
#    }
#    print  ' /> <label for="movies">See local showtimes for a specific <strong>movie</strong></label></div><div><input type="radio" name="searchType" id="theatres" value="theatres" '; 
#    if ($inTheatreId || $searchType eq 'theatres' ) {
#	print  "checked";
#    }
print  <<__EOHTML3__;
<table class="finder results">
<tr class="labels">
<td class="where">ZIP Code</td>
<td class="what">Movie Title</td>
<td class="when">Date</td>
<td class="how" rowspan="2">Order results by<br />
__EOHTML3__

print "<input type='radio' name='groupBy' id='time' value='time' " . ($groupBy eq 'time'? " checked":"") . "> <label for='time'><font size='-2'>Time</font></label> &nbsp;<br> <input type='radio' name='groupBy' id='movie' value='movie' " . ($groupBy ne 'time'? " checked":"") . "> <label for='movie'><font size='-2'>" . ($inTheatreId?"Movie":"Theater") . "</font></label>";

print  <<__EOHTML35__;
<input type="hidden" name="inMovieId" value="$inMovieId" />
<input type="hidden" name="inTheatreId" value="$inTheatreId" />
<input type="hidden" name="all" value="$all" />

</td>
<td class="go"></td>
</tr>
<tr class="inputs">
<td class="where"><input type="text" name="zip" id="zip" size="7" maxlength="5" value="$zip"/></td>
<td class="what"><input type="text" name="q" id="title" size="12" value="$q"/></td>
<td class="when">


__EOHTML35__

#} else {
#    print "<select name='inMovieId'><option value=''>Select a movie\n";
#    foreach my $movieId (sort byTitle keys %movies) {
#	if (!$inTheatreId || defined( $shows{$inTheatreId}{$movieId} ) ) {
#	    print "<option value='$movieId' " . ($inMovieId eq $movieId?" selected":"") . ">$movies{$movieId}{title}\n";
#	}
#    }
#    print "</select><div><select name='inTheatreId'><option value=''>or a theater";
#    foreach my $theatreId (sort byName keys %theatreHash) {
#	if (!$inMovieId || defined( $shows{$theatreId}{$inMovieId} ) ) {
#	    print "<option value='$theatreId' " . ($inTheatreId eq $theatreId?" selected":"") . "  >$theatreHash{$theatreId}{name}\n";
#	}
#    }
#    print '</select></div>';
    sub byTitle() {
	return $movies{$a}{title} cmp $movies{$b}{title};
    }
    sub byName() {
	return $theatreHash{$a}{name} cmp $theatreHash{$b}{name};
    }

}


print  <<__EOHTML4__;

<script languate="Javascript">
var today = new Date();
var i = 0;
var inDate = '$date';
var todayDate = (today.getYear()+1900)+'-'+(today.getMonth()+1)+'-'+today.getDate();
document.write('<select name="date"><option value="'+'" '+(todayDate == inDate ? " selected ":"")+' >'+'Today'+'</option>\\n');
day = new Date(today.getTime() + 24*60*60*1000);
while (i < 6) {
    var curDate = (day.getYear()+1900)+'-'+ (day.getMonth() <= 8 ? "0" : "" ) + (day.getMonth()+1)+'-'+ (day.getDate() <= 9 ? "0" : "") + day.getDate();
	document.write('<option value="'+curDate+'"'+(curDate == inDate ? " selected ":"")+'>'+(day.getMonth()+1)+'/'+day.getDate()+'</option>\\n');
	day =new Date(day.getTime() + 24*60*60*1000);
	i = i + 1;
}
document.write('</select>');
</script>
</td>
__EOHTML4__

#    print "<td class='how' valign='top'><input type='radio' name='groupBy' id='time' value='time' " . ($groupBy eq 'time'? " checked":"") . "> <label for='time'><font size='-2'>Time</font></label> &nbsp;<br> <input type='radio' name='groupBy' id='movie' value='movie' " . ($groupBy ne 'time'? " checked":"") . "> <label for='movie'><font size='-2'>" . ($inTheatreId?"Movie":"Theater") . "</font></label>";


print  <<__EOHTML5__;
</td>
<td class="go">
<input type="image" src="/img/b_go.gif" value="Go!" />
<input type="hidden" name="searchType" id="movies" value="movies" />
</td>
</tr>
</table>
</td>
</tr>
</table>
</form>
	<div class="content">

__EOHTML5__
}

sub printDisam {
   	print "<h2>Choose a theater or movie near you:</h2>";
    print "<table class=\"choose\"><tr><td><ul class=\"\"><li>Theaters:</li>\n";
    foreach my $theatreId (sort byName keys %theatreHash) {
	print "<li><a href='$this?zip=$zip&inTheatreId=$theatreId&date=$date'>$theatreHash{$theatreId}{name}</a></li>\n";
    }
    print "</ul></td><td><ul><li>Movies:</li>";
    foreach my $movieId (sort byTitle keys %movies) {
        print "<li><a href='$this?zip=$zip&inMovieId=$movieId&date=$date'>$movies{$movieId}{title}</a></li>\n";
    }
    print "</ul></td></tr></table>";
    print "<div class='chunk'><h3>You can also <a href='$this?zip=$zip&all=1'>see ALL theaters and movies</a> at once!</h3></div>";


}

sub printInter {
my $forward = makeUrl();
	print "<html><head><meta http-equiv=\"refresh\" content=\"0;URL=$forward\"></head>";
	print  <<__EOHTML6__;
<style type="text/css">
	\@import url("/style.css");
	body {
	font-size: 1em;
	text-align: center;
	}
	.about p {
	color: #ffd1a1;
	}
	table {
	background: #272926;
	margin: 0 auto;
	width: auto;
	}
	td {
	padding: 15px;
	text-align: left;
	vertical-align: top;
	}
		td.what {
		padding: 15px 0;
		}
		tr.label td {
		padding-bottom: 5px;
		}
		tr.inputs td {
		padding-top: 0;
		}
</style>
<body>	
<div class="chunk last">
	<img src="/img/dff_large.gif" alt="Double Feature Finder" />
</div>
<div class="chunk first about"><font size="+1">Please wait...</font></div><br><br><br><br><br>
<div class="chunk">
	<p class="tagline">\&ldquo;Never <strong>sneak</strong> into movies!&rdquo;</p>
</div>
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-73618-3";
urchinTracker();
</script>
</body>
</html>
__EOHTML6__
	exit(0);

}


sub getRt() {
	my $rtUrl = shift;
	$rtUrl =~ s%tt(\d+)%http://rottentomatoes.com/alias?type=imdbid&s=$1%;
	print STDERR $rtUrl if ($debug);  
    my $rtHtml = getHtml($rtUrl);
    if ($rtHtml =~ /critics_tomatometer_rotten.gif/) {
    	return -1;
    } elsif ($rtHtml =~ /critics_tomatometer_cf.gif/) {
    	return 1;
    } else {
    	return 0;
    }
}
