#!/usr/bin/perl
use DBI;
use CGI qw/:standard/;

$table=param(tbl);
$table=~s/\W//g;

my $x,$y,$sid;
my $search=1;
$path="http://mmaketchup.homeunix.org/students";
#$path="http://mmaketchup.hopto.org/students";

$dbh=DBI->connect("DBI:mysql:database=mc;host=localhost","bill","passw0rd");
while($search==1)
#do
{
    $x=int(rand(65536));
    $dbh->{RaiseError} = 1;
    eval {$dbh->do("insert into giveme_token set random=$x;");};
    if($@ eq "")
    {
#        $y=$dbh->selectrow_array("select count(*) from giveme_token where random=$x;");
#        if($y==1) {
$sid=$x;$search=0;last;
#        $search=0;$sid=$dbh->selectrow_array("select id from giveme_token where random=$x;");last;
#        }
    }
}
#while($search==1)
$dbh->do("INSERT INTO open_sessions SET id=$sid,turn=0,table_name=\'$table\';");
$dbh->disconnect;

#HTML
print"Content-type: text/html;charset=utf-8;\n\n";
print"<html>";
print"<head>\n";
print"<title>AskMe 3.0</title>\n";
print"<script type=\"text/javascript\">\n";
print"function Redirect()
{
var r=2,c=2;
if(screen.width>=640){c=2;};
if(screen.width>=800){c=2;};
if(screen.width>=1024){c=3;};
if(screen.width>=1280){c=4;};
if(screen.width>=1600){c=5;};
if(screen.width>=1680){c=5;};

if(screen.height>=480){r=2;};
if(screen.height>=600){r=2;};
if(screen.height>=768){r=3;};
if(screen.height>=800){r=3;};
if(screen.height>=1024){r=4;};
if(screen.height>=1050){r=4;};
if(screen.height>=1200){r=5;};

//string=\"w:\"+screen.width+\"h:\"+screen.height;
//alert(string);
window.location=\"$path/mc.pl?session_id=$sid&r=\"+r+\"&c=\"+c;}";
print"</script>\n";
print"</head>\n";
print"<body onload=\"Redirect();\" vlaign=center>\n<table width=100% height=100%><tr><td valign=center align=center>";
#print"$@<br>";
print"Ждать... Ждать... Ждать... (сервер у меня медленный)<br>";
print"<a href=\"$path/mc.pl?session_id=$sid&r=2&c=2\">$path/mc.pl?session_id=$sid&r=2&c=2</a><br>нажимать только если очень долго автоматически не загружает следующую страницу";
print"</td></tr></table></body></html>\n";
