#!/usr/bin/perl

require "/home/dave/public_html/pagelib.pl";
$questions = read_questions();
headers();
init();
head();
body();
foot();

sub body {
    if($params{pause}) { $params{page} = 'main'; }
    if($params{page} eq "survey") { survey(); }
    elsif($params{page} eq "gameshow") { gameshow(); }
    elsif($params{page} eq "stats") { stats(); }
    elsif($params{page} eq "about") { about(); }
    elsif($params{page} eq "clear") { clear(); }
    elsif($params{page} eq "print") { print_page(); }
    else { menu(); }
}

sub listqs {
    
}

sub menu {
  print "<br>\n";
  print "<font size=+1><b>Lego Trivia!</b></font><br>\n";
  print "<br>\n";
  print "<table>\n";
  print "<tr><td><a href=\"$ENV{SCRIPT_NAME}?page=gameshow\">Game Show Trivia</a></td><td>Play the Lego Game Show! Answer trivia in the style of the Lego Game Show.</tr>\n";
  print "<tr><td><a href=\"$ENV{SCRIPT_NAME}?page=survey\">Random Trivia</a></td><td>The same trivia questions, but in no particular order, just trivia for the sake of trivia.</tr>\n";
  print "<tr><td><a href=\"$ENV{SCRIPT_NAME}?page=stats\">My Stats</a></td><td>How am I doing so far?</tr>\n";
  print "<tr><td><a href=\"$ENV{SCRIPT_NAME}?page=stats&qdetail=1\">Questions</a></td><td>See a list of questions answered so far.</tr>\n";
  print "<tr><td><a href=\"$ENV{SCRIPT_NAME}?page=clear\">Reset</a></td><td>Clear my question history!</tr>\n";
  print "<tr><td><a href=\"$ENV{SCRIPT_NAME}?page=about\">About the Trivia</a></td><td>Who's responsible for this stuff anyway? What's the deal?</tr>\n";
  print "</table>\n";
}

sub clear {
    triviatabs();
    print "<br>\n";
    print "Do you really want to clear your stats?<br>\n";
    print "<table width=100\%>\n";
    print "<tr><td width=50\% align=right>\n";
    print "<form>\n";
    print "<input type=hidden name=page value=\"main\">\n";
    print "<input type=hidden name=resetme value=\"resetme\">\n";
    print "<input type=submit value=\"Yes, I want to try for a better score\">\n";
    print "</form>\n";
    print "</td>\n";
    print "<td width=50\% align=left>\n";
    print "<form>\n";
    print "<input type=hidden name=page value=\"main\">\n";
    print "<input type=submit value=\"No, I was just kidding!\">\n";
    print "</form>\n";
    print "</td></tr>\n";
    print "</table>\n";
}

sub survey {
  print "<br>\n";
  if(!$params{survey}) {
    print "<font size=+1><b>Instructions</b></font><br><br>\n";
    print qq`
Ok. Here's how it works: We'll ask you random Lego Trivia. You
answer. Then we'll show you the correct answer, and you'll have
to guage yourself as to whether or not you got the question right
or not. We won't try and make that call, because quite frankly,
we don't really have the time to grade everyone by hand, and it
wouldn't be as quick.<br>
<br>
<b>What if the answer is actually wrong?</b><br>
<br>
These questions aren't perfect, so if you have any corrections,
or notice any mistakes, you can let us know, and we'll try and
correct them. Some of the questions, however, are dated, and
will be sure to change as time goes on, so we're less likely to
update those answers. But the upside is that if you got the
question right, even if our answer was wrong, you can still
count yourself as getting it right. Yes, yes, that means you
CAN cheat if you're an underhanded 3vil fleeb, but then you
won't get that wonderful rewarding feeling of knowing you did
the right thing. But I suppose if you're an underhanded 3vil
fleeb, you wouldn't care anyway.<br>
<br>
<b>What if I didn't understand the question, or if I got it
kinda right, or accidentally answered the question before
reading it?</b><br>
<br>
Just for you, we've included an "ignore" button. If you don't
think you got a question right or wrong, just hit the "ignore"
button, and it won't be counted for or against your overall
score.<br>
<br>
<b>Can I come back to it later?</b><br>
<br>
Sorta-- because we'd rather not keep your information on our
server, all your score is kept on a cookie on your computer.
If you erase your cookies, log on with a different computer,
or if your cookie expires, the score's lost. But that doesn't
stop you from starting again.<br>
<br>
<form>
<input type=hidden name=page value="survey">
<input type=hidden name=survey value="go">
<b>Ok, Ready?</b>
<input type=submit value="Go!">
</form>
`;
    return;
  }
  if($params{qnum}) {
      #evaluate the answer
      my($qnum) = $params{qnum};
      print "<b>Level:</b> $questions->{$qnum}{level}<br>\n";
      print "<b>Q.</b> $questions->{$qnum}{question}<br>\n";
      print "<b>A.</b> $questions->{$qnum}{answer}<br>\n";
      print "<b>Your Answer:</b> $params{answer}<br>\n";
      print "<table><tr>\n";
      print "<td>\n";
      print "<form name=cform>\n";
      print "<input type=hidden name=survey value=\"1\">\n";
      print "<input type=hidden name=\"answered\" value=\"$qnum\">\n";
      print "<input type=hidden name=\"page\" value=\"survey\">\n";
      print "<input type=hidden name=\"correct\" value=\"C\">\n";
      print "<input type=submit name=\"cont\" value=\"Correct & Continue\"><br>\n";
      print "<input type=submit name=\"pause\" value=\"Correct & Pause\"><br>\n";
      print "</form>\n";
      print "</td>\n";
      print "<td>\n";
      print "<form name=cform>\n";
      print "<input type=hidden name=survey value=\"1\">\n";
      print "<input type=hidden name=\"answered\" value=\"$qnum\">\n";
      print "<input type=hidden name=\"page\" value=\"survey\">\n";
      print "<input type=hidden name=\"correct\" value=\"K\">\n";
      print "<input type=submit name=\"cont\" value=\"Ignore & Continue\"><br>\n";
      print "<input type=submit name=\"pause\" value=\"Ignore & Pause\"><br>\n";
      print "</form>\n";
      print "</td>\n";
      print "<td>\n";
      print "<form name=cform>\n";
      print "<input type=hidden name=survey value=\"1\">\n";
      print "<input type=hidden name=\"answered\" value=\"$qnum\">\n";
      print "<input type=hidden name=\"page\" value=\"survey\">\n";
      print "<input type=hidden name=\"correct\" value=\"W\">\n";
      print "<input type=submit name=\"cont\" value=\"Wrong & Continue\"><br>\n";
      print "<input type=submit name=\"pause\" value=\"Wrong & Pause\"><br>\n";
      print "</form>\n";
      print "</td>\n";
      print "</tr></table>\n";
  } else {
      #try and ask a new question
      my($max) = 0;
      foreach $qnum (keys %{$questions}) {
	  next if($questions->{$qnum}{asked});
	  if($questions->{$qnum}{rand} > $questions->{$max}{rand}) {
	      $max = $qnum;
	  }
      }
      if(!$max) {
	  #you've answered everything!
	  print "You've answered all our questions!<br>\n";
	  print "<br>\n";
	  menu();
	  return;
      } else {
	  #ask the question
	  print "<form name=sform>\n";
	  print "<b>Level:</b> $questions->{$max}{level}\n";
	  print "&nbsp;" x 20;
	  print "<input type=text name=seconds size=2 value=\"60\"> seconds remain<br>\n";
	  print "<b>Q.</b> $questions->{$max}{question}<br>\n";
	  print "<input type=hidden name=survey value=\"1\">\n";
	  print "<input type=hidden name=page value=\"survey\">\n";
	  print "<input type=hidden name=asked value=\"$max\">\n";
	  print "<input type=hidden name=qnum value=\"$max\">\n";
	  print "<input type=text name=answer value=\"\" size=30>\n";
	  print "<input type=submit value=\"Answer\">\n";
      	  print "</form>\n";
	  js_timer();
      }
  }
}

sub gameshow {
    print "<br>\n";
    if(!$params{survey}) {
	print "<font size=+1><b>Instructions</b></font><br><br>\n";
	print qq`
You\'ll start off at level 1, and hopefully climb the ladder
all the way up to level 6. How? By answering trivia questions!
As you might guess, each level corresponds to the approximate
level of difficulty of the question. So as you continue the game,
the questions get much trickier.<br>
<br>
Each time you get a question right, you go up 1 level. And each
time you get a question wrong, you get a strike! And just like
baseball or Family Feud, once you get 3 strikes, the game\'s over
(but feel free to come back and play agian!).<br>
<br>
For each question, however, YOU get to be the judge of whether
or not you got it right or wrong (mostly because automatically
scoring text answers is tough, and we\'d rather not score your
answers all by hand).
<br>
<b>What if I didn\'t understand the question, or if I got it
kinda right, or accidentally answered the question before
reading it?</b><br>
<br>
Um.. tough. If you\'re worried about it, try the \"Random Trivia\"
section version. There, you can actually score a question as
\"ignore\" so that it won\'t count against you in the event that
there was a technical problem or if you otherwise think that
the question or answer wasn\'t fair. Here in the Game Show
version, it\'s either right or wrong. No halfway.<br>
<br>
<b>What if the answer is actually wrong?</b><br>
<br>
These questions aren\'t perfect, so if you have any corrections,
or notice any mistakes, you can let us know, and we\'ll try and
correct them. Some of the questions, however, are dated, and
will be sure to change as time goes on, so we\'re less likely to
update those answers. But the upside is that if you got the
question right, even if our answer was wrong, you can still
count yourself as getting it right. Yes, yes, that means you
CAN cheat if you\'re an underhanded 3vil fleeb, but then you
won\'t get that wonderful rewarding feeling of knowing you did
the right thing. But I suppose if you\'re an underhanded 3vil
fleeb, you wouldn\'t care anyway.<br>
<br>
<b>Can I come back to it later?</b><br>
<br>
Sorta-- because we\'d rather not keep your information on our
server, all your score is kept on a cookie on your computer.
If you erase your cookies, log on with a different computer,
or if your cookie expires, the score\'s lost. But that doesn\'t
stop you from starting again.<br>
<br>
<form>
<input type=hidden name=page value=\"gameshow\">
<input type=hidden name=survey value=\"go\">
<input type=hidden name=resetgame value=\"1\">
<b>Ok, Ready?</b>
<input type=submit value=\"Go!\">
</form>`;
      return;
  }
  if($cur_lev > 6 || $strikes > 2) {
      print "Congratulations! You made it to level ".($cur_lev-1)."!<br><br>\n";
      print qq`
<table width=100\%>
<tr><td align=right width=50\%>
<form>
<input type=hidden name=page value=\"gameshow\">
<input type=hidden name=survey value=\"go\">
<input type=hidden name=resetgame value=\"1\">
<input type=submit value=\"Play Again!\">
</form>
</td><td align=left width=50\%>
<form>
<input type=hidden name=page value=\"main\">
<input type=hidden name=resetgame value=\"1\">
<input type=submit value=\"Nah.\">
</form>
</td></tr>
</table>
`;
      return;
  }
  if($params{qnum}) {
      #evaluate the answer
      my($qnum) = $params{qnum};
      print "<b>Level:</b> $cur_lev";
      if($cur_lev != $questions->{$qnum}{level}) {
         print "(Actual Level: $questions->{$qnum}{level})";
      }
      print "<br>\n";
      print "<table width=100\%>\n";
      print "<tr><td width=5\% align=left valign=center><b>Strikes:</b></td><td width=45\%>";
      for($i=0;$i<$strikes;$i++) {
        print "<img src=\"images/redx.gif\" height=32 width=32>";
      }
      print "</td><td width=50\% align=right>";
      print "<input type=text name=seconds size=2 value=\"$params{seconds}\"> seconds remain\n";
      print "</td></tr></table><br>\n";


      print "<b>Q.</b> $questions->{$qnum}{question}<br>\n";
      print "<b>A.</b> $questions->{$qnum}{answer}<br>\n";
      print "<b>Your Answer:</b> $params{answer}<br>\n";
      print "<table><tr>\n";
      print "<td>\n";
      print "<form name=cform>\n";
      print "<input type=hidden name=survey value=\"1\">\n";
      print "<input type=hidden name=\"answered\" value=\"$qnum\">\n";
      print "<input type=hidden name=\"levelup\" value=\"1\">\n";
      print "<input type=hidden name=\"page\" value=\"gameshow\">\n";
      print "<input type=hidden name=\"correct\" value=\"C\">\n";
      print "<input type=submit name=\"cont\" value=\"Correct & Continue\"><br>\n";
      print "<input type=submit name=\"pause\" value=\"Correct & Exit\"><br>\n";
      print "</form>\n";
      print "</td>\n";
      print "<td>\n";
      print "<form name=wform>\n";
      print "<input type=hidden name=survey value=\"1\">\n";
      print "<input type=hidden name=\"strike\" value=\"1\">\n";
      print "<input type=hidden name=\"answered\" value=\"$qnum\">\n";
      print "<input type=hidden name=\"page\" value=\"gameshow\">\n";
      print "<input type=hidden name=\"correct\" value=\"W\">\n";
      print "<input type=submit name=\"cont\" value=\"Wrong & Continue\"><br>\n";
      print "<input type=submit name=\"pause\" value=\"Wrong & Exit\"><br>\n";
      print "</form>\n";
      print "</td>\n";
      print "</tr></table>\n";
  } else {
      #try and ask a new question
      my($max) = 0;
      foreach $qnum (keys %{$questions}) {
	  next if($questions->{$qnum}{asked});
          next if($questions->{$qnum}{level} != $cur_lev);
	  if($questions->{$qnum}{rand} > $questions->{$max}{rand}) {
	      $max = $qnum;
	  }
      }
      if(!$max) {
          $max = get_rq($questions,$cur_lev-1);
          if(!$max) { $max = get_rq($questions,$cur_lev+1); }
          if(!$max) { $max = get_rq($questions,$cur_lev-2); }
          if(!$max) { $max = get_rq($questions,$cur_lev+2); }
          if(!$max) { $max = get_rq($questions,$cur_lev-3); }
          if(!$max) { $max = get_rq($questions,$cur_lev+3); }
          if(!$max) { $max = get_rq($questions,$cur_lev-4); }
          if(!$max) { $max = get_rq($questions,$cur_lev+4); }
          if(!$max) { $max = get_rq($questions,$cur_lev-5); }
          if(!$max) { $max = get_rq($questions,$cur_lev+5); }
          if(!$max) {
            #we're out of questions!
            print "We ran out of questions to ask you!<br>\n";
            print "<br>\n";
            menu();
            return;
          }
      }
	  #ask the question
	  print "<form name=sform>\n";
	  print "<b>Level:</b> $cur_lev";
          if($cur_lev != $questions->{$max}{level}) {
            print " (Actual Level: $questions->{$max}{level})\n";
          }
          print "<br>\n";
          print "<table width=100\%>\n";
          print "<tr><td width=5\% align=left valign=center><b>Strikes:</b></td><td width=45\%>";
          for($i=0;$i<$strikes;$i++) {
            print "<img src=\"images/redx.gif\" height=32 width=32>";
          }
          print "</td><td width=50\% align=right>";
	  print "<input type=text name=seconds size=2 value=\"60\"> seconds remain\n";
          print "</td></tr></table><br>\n";
	  print "<b>Q.</b> $questions->{$max}{question}<br><br>\n";
	  print "<input type=hidden name=survey value=\"1\">\n";
	  print "<input type=hidden name=page value=\"gameshow\">\n";
	  print "<input type=hidden name=asked value=\"$max\">\n";
	  print "<input type=hidden name=qnum value=\"$max\">\n";
	  print "<input type=text name=answer value=\"\" size=30>\n";
	  print "<input type=submit value=\"Answer\">\n";
      	  print "</form>\n";
	  js_timer();
      
  }
}

sub triviatabs {
    print "<br>\n";
    print "<table border=1 width=100\%><tr>\n";
    print "<td><a href=\"$ENV{SCRIPT_NAME}?page=main\">Main</a></td>\n";
    print "<td><a href=\"$ENV{SCRIPT_NAME}?page=gameshow\">Game Show Trivia</a></td>\n";
    print "<td><a href=\"$ENV{SCRIPT_NAME}?page=survey\">Random Trivia</a></td>\n";
    print "<td><a href=\"$ENV{SCRIPT_NAME}?page=stats\">My Stats</a></td>\n";
    print "<td><a href=\"$ENV{SCRIPT_NAME}?page=stats&qdetail=1\">Questions</a></td>\n";
    print "<td><a href=\"$ENV{SCRIPT_NAME}?page=clear\">Reset</a></td>\n";
    print "<td><a href=\"$ENV{SCRIPT_NAME}?page=about\">About the Trivia</a></td>\n";
    print "</tr></table>\n";
}

sub log_cookie {
    $file = "/home/dave/public_html/projectx/answers/ck$ENV{REMOTE_ADDR}";
    if(open(FILE,">> $file")) {
	print FILE "$cookie\n";
	close FILE;
    }
}

sub stats {
    log_cookie();
    my($wrong,$correct,$total) = (0,0,0);
    my(%levstat,%catstat);
    triviatabs();
    print "<br>\n";
    for($i=0;$i<length $cookie;$i++) {
	$s = substr($cookie,$i,1);
	my($qi) = $i+1;
	my(@cats) = keys %{$questions->{$qi}{categories}};
	if($s eq "W") {
	    foreach my $c (@cats) {
		$catstats{$c}{wrong}++;
	    }
	    $questions->{$qi}{correct} = -1;
	    $levstat{$questions->{$qi}{level}}{wrong}++;
	    $wrong++;
	}
	if($s eq "C") {
	    foreach my $c (@cats) {
		$catstats{$c}{correct}++;
	    }
	    $questions->{$qi}{correct} = 1;
	    $levstat{$questions->{$qi}{level}}{correct}++;
	    $correct++;
	}
	if($s =~ /[WACK]/) {
	    foreach my $c (@cats) {
		$catstats{$c}{asked}++;
	    }
	    $levstat{$questions->{$qi}{level}}{asked}++;
	    $total++;
	}
    }
    if($params{qdetail}) {
	#we need FULL screen here.
	print "</td></tr></table>\n";
	print "<table border=1 width=100\%>\n";
	print "<tr>\n";
	print "<th>Level</th>\n";
	print "<th>Correct?</th>\n";
	print "<th>Question</th>\n";
	print "<th>Answer</th>\n";
	print "<th>Categories</th>\n";
	print "</tr>\n";
	foreach $qn (sort {$questions->{$a}{level} <=> $questions->{$b}{level} || $a <=> $b} (keys %{$questions})) {
	    my($q) = $questions->{$qn};
	    next unless($q->{asked} || $params{view_all});
	    print "<tr>\n";
	    print "<td>$q->{level}</td>\n";
	    print "<td";
	    if($q->{correct} > 0) { print " bgcolor=#80FF40>Correct"; }
	    elsif($q->{correct} < 0) { print " bgcolor=#FF6060>Wrong"; }
	    else { print ">&nbsp;"; }
	    print "</td>\n";
	    print "<td>$q->{question}</td>\n";
	    print "<td>$q->{answer}</td>\n";
	    print "<td>".join("<br>\n",(map { s/ /\&nbsp;/g; $_ } (keys %{$q->{categories}})))."</td>\n";
	    print "</tr>\n";
	}
	print "</table>\n";
	print "<table width=640><tr><td>\n";
    } else {
	print "<table border=1>\n";
	print "<tr><th colspan=4>Overall</th></tr>\n";
	print "<tr><th>\%</td><th>Right</td><th>Wrong</td><th>Asked</td></tr>\n";
	print "<tr>\n";
	print "<td>";
	if($correct || $wrong) {
	    print sprintf("%.2f",(100*($correct/($correct+$wrong))));
	} else {
	    print "NA";
	}
	print "</td>\n";
	print "<td>$correct</td>\n";
	print "<td>$wrong</td>\n";
	print "<td>$total</td>\n";
	print "</tr>\n";
	print "</table>\n";
	print "<br>\n";
	print "<table border=1>\n";
	print "<tr><th>Level</td><th>\%</td><th>Right</td><th>Wrong</td><th>Asked</td></tr>\n";
	foreach my $l (sort keys %levstat) {
	    print "<tr><td>$l</td>";
	    if($levstat{$l}{correct} || $levstat{$l}{wrong}) {
		my($avg) = ($levstat{$l}{correct}/($levstat{$l}{correct}+$levstat{$l}{wrong}));
		print "<td>".sprintf("%.2f",(100*$avg))."</td>\n";
	    } else {
		print "<td>NA</td>\n";
	    }
	    print "<td>".($levstat{$l}{correct} || '0')."</td>\n";
	    print "<td>".($levstat{$l}{wrong} || '0')."</td>\n";
	    print "<td>".($levstat{$l}{asked} || '0')."</td>\n";
	    print "</tr>\n";
	}
	print "</table>\n";
	print "<br>\n";
	print "<table border=1>\n";
	print "<tr><th>Category</td><th>\%</td><th>Right</td><th>Wrong</td><th>Asked</td></tr>\n";
	foreach my $cat (sort keys %catstats) {
	    print "<tr><td>$cat trivia</td>";
	    if($catstats{$cat}{correct} || $catstats{$cat}{wrong}) {
		my($avg) = ($catstats{$cat}{correct}/($catstats{$cat}{correct}+$catstats{$cat}{wrong}));
		print "<td>".sprintf("%.2f",(100*$avg))."</td>\n";
	    } else {
		print "<td>NA</td>\n";
	    }
	    print "<td>".($catstats{$cat}{correct} || '0')."</td>\n";
	    print "<td>".($catstats{$cat}{wrong} || '0')."</td>\n";
	    print "<td>".($catstats{$cat}{asked} || '0')."</td>\n";
	    print "</tr>\n";
	}
	print "</table>\n";
    }
}

sub print_page {
    print qq`<style>
    body {
	font-family: Verdana, Arial, Helvetica, sans-serif;
	font-size: x-small;
    }
td {
    font-family: Verdana, Arial, Helvetica, sans-serif;
    font-size: x-small;
}
th {
    font-family: Verdana, Arial, Helvetica, sans-serif;
    font-size: x-small;
}

</style>`;
    foreach my $qn (sort {$questions->{$a}{level} <=> $questions->{$b}{level} || $a <=> $b} (keys %{$questions})) {
	my($q) = $questions->{$qn};
	print "<table width=100\%>\n";
	print "<tr>\n";
	print "<td rowspan=2 valign=top><img src=\"images/spacer.gif\" width=1></td>\n";
	#print "<td rowspan=2 valign=top bgcolor=\"#00FF00\"><img src=\"images/tlicon2.gif\" width=5></td>\n";
	print "<td></td>\n";
	print "<td rowspan=3 bgcolor=\"#BFBFBF\" width=1><img src=\"images/spacer.gif\" width=1></td>\n";
	print "<td align=right><font style=\"font-size: xx-small; font-family: Verdana, Arial, Helvetica, sans-serif;\">Level: <b>$q->{level}</b></font></td>\n";
	print "</tr>\n";
	print "<tr valign=top>";
	print "<td><b><font style=\"font-size: x-small; font-family: Verdana, Arial, Helvetica, sans-serif;\">Q. $q->{question}</b><br><hr>A. $q->{answer}</font></td>";
	print "<td width=120><font style=\"font-size: xx-small; font-family: Verdana, Arial, Helvetica, sans-serif;\"><b>Categories</b><hr>".join("<br>\n",(map { s/ /\&nbsp;/g; $_ } (keys %{$q->{categories}})))."</font></td>\n";
	print "</tr>\n";
	print "</table>\n";
	print "<hr>\n";
    }
}

sub about {
    triviatabs();
    print qq`
<br>
<b>What's the deal here? What's this about a "game show", anyway?</b><br>
<br>
At BrickFest 2004, we had the 1st ever (to our knowledge) Lego Trivia Game
Show, complete with tons of trivia, Mindstorms buzzers, and of course a bevy
of cool Lego prizes (and some Bionicle, too). This is an attempt to bring the
Game Show experience to some of you who might not have had a chance to
participate at BrickFest, and also in general, just to have fun, anyway.<br>
<br>
<b>Who's responsible for this stuff?</b><br>
<br>
Well, Dave Eaton's the prinicpal offender. He came up with the idea, most of
the questions, most of the answers, did some research with AFOLs before the
game, hosted the game show, and wrote this handy-dandy online version. If
you've got a correction or a question, <a href="mailto:dave\@suave.net">let
him know</a>.<br>
<br>
But he was not alone. In order to rank questions, and to get corrections to
some, he enlisted the aid of 11 other AFOLs. So special thanks to Dan Boger,
Jenn Boger, Joe Comeau, Tom Duggan, Doug Eaton (no, no relation, just a
baffling coincidence), Don Heyse, Matthew Miller, Chris Phillips, Clark
Stephens, Shaun Sullivan, and Teddy Welsh for helping out!<br>
<br>
Also, a special thanks to Jake McKee for some help with finding a few obscure
answers, and perhaps most importantly a big thanks to BrickFest 2004 and its
organizers for allowing the show to happen, and for funding the prizes!<br>
<br>
<b>So, what happened on the game show?</b><br>
<br>
Well, we had "Contestant's Row" just like on The Price Is Right-- Audience
members got called at random from at hat, and filled up the 3 seats in the
front row. All 3 were asked a random Lego question (random question level
1-3), and the 1st to buzz in on their Mindstorms buzzer with the correct
answer got called up on stage to play the Lego Game Show. All in all, we
had 17 people get called up from the audience, and 15 people who actually
got up on stage to do some time in the hotseat.<br>
<br>
Of the people who got called up, we had:<br>
Consolation Prizes: 5 people (got none right or didn't get on stage)<br>
Level 1: 2 people<br>
Level 2: 2 people<br>
Level 3: 2 people<br>
Level 4: 5 people<br>
Level 5: 1 person (Go Tom!)<br>
Level 6: nobody (Level 6's are HARD!)<br>
<br>
Prizes were given for all levels, although no additional prizes were given
away for getting to Level 6. Level 6 was solely for the honor and glory
that comes with being a trivia-know-it-all. Prizes ranged from roughly \$2.00
(consolation prizes) all the way up to \$100 (level 5/6 prizes).<br>
<br>
<b>How hard are the questions?</b><br>
<br>
Really, really, hard. Most of the AFOLs who took our preliminary survey only
got 30-40\% correct, and as you can see from the statistics of the Game Show,
there were a fair number of people that didn't make it very far up the
ladder. Don't feel bad if you get a lot wrong-- these are questions are both
to test you and to help you learn useless facts about Lego.<br>
<br>
The questions also come from a variety of places. We tried to cover all the
major areas of the hobby, from the products Lego makes to the fan community
to the company history. There's questions about Lego CAD, major fan sites,
people's MOC's, world records, and everything in between. We learned a lot
in coming up with the questions, and don't expect anyone in their right mind
to come up with 100\% of the answers without doing some research.<br>
<br>
Here's a rough key of relative ease of the questions:<br>
Level 1 - Pretty easy. Most AFOLs <i>should</i> know these questions if they don't
already.<br>
Level 2 - Tricky. If you've been involved in the Lego community, you probably
know most, but not all of these.<br>
Level 3 - Hard. You'll need some experience to get these answers.<br>
Level 4 - Very hard. To get these right, you'll have to know your stuff
pretty well.<br>
Level 5 - Nearly Impossible. The very most knowledgable AFOLs will get many
if not most of these wrong.<br>
Level 6 - Insane. Nobody knows these. Count yourself as a Grand Pope of
Trivia if you know these.<br>

`;
}

sub get_rq {
    my($questions,$lev) = @_;
    my($max) = '';
    foreach my $qnum (keys %{$questions}) {
	next if($questions->{$qnum}{asked});
	next if($questions->{$qnum}{level} != ($lev));
	if($questions->{$qnum}{rand} > $questions->{$max}{rand}) {
	    $max = $qnum;
	}
    }
    return $max;
}

sub init {
  $new_user = 1;
  foreach (keys %{$questions}) {
    my $asked = substr($cookie,$questions->{$_}{number}-1,1);
    if($asked eq "C") {
      $questions->{$_}{asked} = 1;
      $questions->{$_}{correct} = "C";
      $new_user = 0;
    } elsif($asked eq "W") {
      $questions->{$_}{asked} = 1;
      $questions->{$_}{correct} = "W";
      $new_user = 0;
    } elsif($asked eq "A") {
      $questions->{$_}{asked} = "1";
      $new_user = 0;
    } elsif($asked eq "K") {
      $questions->{$_}{asked} = 1;
      $questions->{$_}{correct} = "K";
      $new_user = 0;
    } else {
      $questions->{$_}{asked} = 0;
    }
  }
}

sub headers {
  my(@cook) = split /; /,$ENV{HTTP_COOKIE};
  my(%cookies);
  foreach (@cook) {
    if(/^([^=]+)=(.*)$/) {
      $cookies{$1} = $2;
    }
  }
  my(@lt) = localtime();
  $lt[5]+=1901;
  $lt[4];
  my $dayname = ("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")[$lt[6]];
  my $monname = ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")[$lt[4]];
  my $cookie_expire = "$dayname, $lt[3]-$monname-$lt[5] 23:00:00 GMT";

  if(!defined($cookies{'legotrivia'})) {
    if($params{'new_user'}) {
      print "Content-Type: text/html\n\n";
      print "You'll need to turn on cookies in your browser in order to take the Lego Trivia Survey. Please turn cookies on and <a href=\"$ENV{SCRIPT_NAME}\">try again</a>.\n";
      exit(0);
    }
    print "Set-Cookie: legotrivia=".("_" x (scalar (keys %{$questions})))."; expires=$cookie_expire\n";
    print "Status: 302 Moved Temporarily\n";
    print "Location: $ENV{SCRIPT_NAME}?new_user=1\n\n";
    exit(0);
  }
  $cookie = $cookies{'legotrivia'};
  if($params{resetme}) {
      $cookie =~ s/./_/g;
  }
  if($params{asked}) {
    substr($cookie,$params{asked}-1,1) = "A";
  }
  if($params{answered}) {
    $params{correct} ||= "?";
    substr($cookie,$params{answered}-1,1) = $params{correct};
  }
  print "Set-Cookie: legotrivia=$cookie; expires=$cookie_expire\n";
  $gscookie = $cookies{'gameshow'};
  if($gscookie =~ /\d/) {
      $cur_lev = substr($gscookie,0,1);
      $strikes = substr($gscookie,1,1);
      if($params{strike}) {
	  $strikes++;
	  substr($gscookie,1,1) = $strikes;
      }
      if($params{levelup}) {
	  $cur_lev++;
	  substr($gscookie,0,1) = $cur_lev;
      }
  } else {
      $gscookie = '10';
  }
  if($params{resetgame}) {
      $gscookie = '10';
  }
  $cur_lev = substr($gscookie,0,1);
  $strikes = substr($gscookie,1,1);
  print "Set-Cookie: gameshow=$gscookie; expires=$cookie_expire\n";
  print "Content-Type: text/html\n\n";
}

sub read_questions {
  my $qfile = "/home/dave/public_html/projectx/updated_questions.txt";
  if(!open(FILE,$qfile)) {
    die("Content-Type: text/html\n\nError! Couldn't open $qfile!");
  }
  my(%questions);
  while(<FILE>) {
    if(/^(\d+)\t(\d+)\t([^\t]+)\t([^\t]+)\t([^\t]+)\s*$/) {
      my($qnum,$level,$catss,$ques,$ans) = ($1,$2,$3,$4,$5);
      $ans =~ s/\\n/\n/g;
      $ques =~ s/\\n/\n/g;
      my($rand) = int rand 1000;
      %{$questions{$qnum}} = (
			      rand => $rand,
			      number => $qnum,
			      level => $level,
			      question => $ques,
			      answer => $ans,
			      );
      foreach (split /,/,$catss) {
	$questions{$qnum}{categories}{$_} = 1;
      }
    }
  }
  return \%questions;
}

sub js_timer {
    print qq`
<script language="Javascript">

  var t1 = new Date();
  var timeleft = 60;
  var alldone = 0;
  setTimeout("clocktick()",1000);

  this.document.sform.answer.focus();

  if(navigator.appName.indexOf("etscape") != -1 || navigator.appName.indexOf("ozilla") != -1) {
    document.captureEvents(Event.KEYPRESS);
    document.onkeypress = checkenter;
  }

  function clocktick() {
    if(alldone >= 1) { return; }
    timeleft--;
    if(timeleft <= 0) {
      this.document.sform.seconds.value = "0";
      //get ok/cancel value for going on
      var next = confirm("Time's up! Would you like to continue to the next question?") ? 1 : 0;
      submit_answer(next);
    } else {
      this.document.sform.seconds.value = timeleft.toString();
      setTimeout("clocktick()",1000);
    }
  }

  function checkenter(myevent) {
    var key;
    if(myevent) {
      //netscape
      key = myevent.which;
    } else {
      //msie
      if(window.event) {
        key = window.event.keyCode;
      } else {
        key = "?";
      }
    }
    if(key==13 || key==10) {
      submit_answer(1);
    }
  }

  function submit_answer(flag) {
    var t2 = new Date();
    var diff = t2.getTime() - t1.getTime();
    diff /= 1000;
    //diff = 60 - timeleft;
    var page = (flag) ? '$params{page}' : 'main';
    var inc = 0;

    var answer = this.document.forms[0].answer.value;

    var qnum = this.document.forms[0].qnum.value;
    this.document.location='$ENV{SCRIPT_NAME}?page='+page+'&answer='+escape(answer)+'&asked='+qnum+'&qnum='+qnum+'&responsetime='+diff+'&survey=1';
  }
  </script>
`;
}

sub js_funcs {
    print qq`
function Get_Cookie(name) {
    var start = document.cookie.indexOf(name+"=");
    var len = start+name.length+1;
    if ((!start) && (name != document.cookie.substring(0,name.length))) return null;
    if (start == -1) return null;
    var end = document.cookie.indexOf(";",len);
    if (end == -1) end = document.cookie.length;
    return unescape(document.cookie.substring(len,end));
}

function Set_Cookie(name,value,expires,path,domain,secure) {
    document.cookie = name + "=" +escape(value) +
        ( (expires) ? ";expires=" + expires.toGMTString() : "") +
        ( (path) ? ";path=" + path : "") + 
        ( (domain) ? ";domain=" + domain : "") +
        ( (secure) ? ";secure" : "");
}
`;
}




