#!/usr/bin/perl -w

package TV::cgi;
use Date::Manip;
use HTML::Entities;  
use CGI qw(:standard :html3);
use Pg;
use CGI;
use rondje;
use dbq;
$R = new rondje;
$R->{color}="#FF8000";
$R->{"style"}="itesf";

$:=1;
$color="#FF8000";
&initprut;
$fsbf="file:";
$nowm=&ParseDate("now");
$debug=$Q->param(Debug);
&OptionForm;
&pg_connect;
$query = &BouwQuery;
$s= new dbq; 

if ($Q->param(Interval)){
    $s->doq($query);
}else{
    $s->doq("select * from programs where endtime > '$nowm' and timed < '$nowm' order by timed");
}
print "Query = \"",$s->{query},"\" " if ($Q->param(ShowSql));
print "\n nu fore i rows:",$s->{rown} if ($debug);
if ($debug){
    foreach  $i ($Q->param  ){
	print " $i=", $Q->param($i),"<br>\n";
    }
}
print "</pre>\n";
$dateflip=1 if ($s->{query} =~ /order by timed/i);
$dateflip=1 if ($s->{query} =~ /order by endtime/i);

&CheckFav($s) if ($Q->param(WarnFav));
&SpuiHtml($s);
&PrintClockJS if ($Q->param(Interval) eq "now");
&PrintBottom;
print $R->combot;

    print <<GROK;
<layer name="popup" onMouseOut="this.visibility='hide';" visibility="hide"></layer>
GROK





print "</form></body></html>\n\n";

#-----------------------------------------------------------------------------

sub SpuiHtml{
    my ($s) = shift;
    *id=$s->{id};
    my ($begindlas)="iouewoiruoiruoiewuroi";
    $nexttime="9999999999999999999999";
    foreach $i (@id){
	($begind,$begint) = $s->{timed}{$i} =~ /(\d\d\d\d\d\d\d\d)(\d\d:\d\d):\d\d/;
	($endd) = $s->{endtime}{$i} =~ /\d\d\d\d\d\d\d\d(\d\d:\d\d):\d\d/; 
	$nexttime = $s->{endtime}{$i} if ($s->{endtime}{$i} lt $nexttime);
	print "<br><h2>",&UnixDate($s->{timed}{$i},"%a %e %b %Y"),"</h2>\n" if (($begindlas ne $begind) && ($dateflip));
	print "<table border=0 cellspacing=0 cellpadding=0>\n\t<tr><td bgcolor=\"#ff8000\">\n";
	print &UnixDate($s->{timed}{$i},"%a %e %b %Y"),"\n" unless ($dateflip);
#	print "\t<a href=\"$fsbf", $s->{localf}{$i},"\"\n\t";
#	print" onclick=\"return js_title_menu('",
#	&toencode($s->{name}{$i}),
#	"','",$s->{zender}{$i},"','",
#	$s->{localf}{$i},"',event)\"",
#	">";
	my $utitle=&toencode($s->{name}{$i});
	print <<GROK;
	<a href="fav?ptitle=$utitle&action=edit"><b>$begint</b></a>
GROK
	print $s->{zender}{$i};
	
	print " </td><td>\n ";
	print "<a href=\"",$s->{nameurl}{$i},"\">"  if ( $s->{nameurl}{$i} );    
	print $s->{name}{$i};
	print "</a>\n" if ( $s->{nameurl}{$i} );  
	print " <i>",$s->{namesub}{$i},"</i>" if ( $s->{namesub}{$i} );
	print " <font size=-2>tot $endd</font>";
	print "</td></tr>\n";
	if ( $s->{descr}{$i} ){
	    print "\n\t<tr><td> </td><td>";
	    print $s->{descr}{$i};
	    print "</td></tr>\n";
	}
	print "</table>\n";
	$begindlas=$begind;
    }
}



sub cmp_eq {

    my $cmp = shift;
    my $ret = shift;
    my $msg;

    if ("$cmp" eq "$ret") {
       # print "ok $cnt\n";
    } else {
        $msg = $conn->errorMessage;
        print "not ok $cnt: $cmp, $ret\n$msg\n";
        exit;
    }
    $cnt++;
}

sub cmp_ne {

    my $cmp = shift;
    my $ret = shift;
    my $msg;

    if ("$cmp" ne "$ret") {
        #print "ok $cnt\n";
    } else {
        $msg = $conn->errorMessage;
        print "not ok $cnt: $cmp, $ret\n$msg\n";
        exit;
    }
    $cnt++;
}
                           


sub pg_connect{
    $PGRES_EMPTY_QUERY    = 0 ;
    $PGRES_COMMAND_OK     = 1 ;
    $PGRES_TUPLES_OK      = 2 ;
    $PGRES_COPY_OUT       = 3 ;
    $PGRES_COPY_IN        = 4 ;
    $PGRES_BAD_RESPONSE   = 5 ;
    $PGRES_NONFATAL_ERROR = 6 ;
    $PGRES_FATAL_ERROR    = 7 ;
    $| = 1;
    $dbname = 'tv';
    $cnt    = 2;
    $conn = Pg::connectdb("dbname=$dbname");
    #$db = $conn->db;
#    $user = $conn->user;
 #   $port = $conn->port;
#	$user = $user;
    #print "db: $db, $user, $port\n";
}














#------------------------------------------------------------------------








sub initprut{
    $Q = new CGI;
    $Qself = $Q->self_url;    
    #$Qselfs = $Q->url;
    print $Q->header(-type=>'text/html',
                         -expires=>'+5min');
    print <<GROK;
<HTML>
<HEAD>
<LINK REV="made" HREF="mailto:jipp\@xs4all.nl (Jip de Kort)">
<TITLE>tv</TITLE>
<meta name="begun" content="Tue Jun  9 05:06:42 MET DST 1998">
GROK

&PrintPopJS;
    print<<GROK;

</head>
<BODY
BGCOLOR=#FFFFFF TEXT=#000000 
>
GROK
}



sub OptionForm{
    $clockform="<INPUT bgcolor=\"$color\" type=text NAME=clock2 SIZE=25>" if ($Q->param(Interval)  eq "now");
  



    $popupt =  $Q->popup_menu(
			-name=>"Interval",
			-"values"=>['now','+15 min','+1 hour','+3 hours','+1 day','+1 week','+1 month','+1 year','+100 year','whenever','-15 min','-1 hour','-1 day','-1 week','-1 month','-1 year','-100 year'],
			-default=>$Q->{Interval},
			);
    $popupz =  $Q->popup_menu(
			-name=>"Zender",
			-"values"=>['All','BBC1','BBC2','NED1'],
			-default=>$Q->{Zender},
			);
    $popups =  $Q->popup_menu(
			-name=>"SearchOnField",
			-"values"=>['All','name','zender','descr'],
			-default=>$Q->{SearchOnField},
			);
    $zoekding=*Q->{Search} if ($Q->{Search}) ;
    $sortorder = $Q->popup_menu(
				-name=>"SortOrder",
				-"values"=>['timed','zender','name','endtime','descr'],
				-default=>$Q->{SortOrder},
				);
    
print <<GROK;


<FORM NAME="opform" ACTION="$Qself" METHOD="get">
GROK
    $R->{align}="middle";
    print $R->begin;
    $popupz = "" unless ($popupz);
    $popupt = "" unless ($popupt);
    $zoekding = "" unless ($zoekding);
    print <<GROK;
     <font size=-2>
     When: $popupt Zender: $popupz 
     Zoek <input type=text name="Search" size=13 value=$zoekding> in $popups
	 Sort $sortorder
     <input type=submit value=GO>
     </font>
GROK
    print $R->end;

    print "\n<center>$clockform</center>" if $clockform;


    #end
}


sub PrintPopJS{
    print <<GROK;
<script>
function js_title_menu(name,zender,localf,d) {
    if( parseInt(navigator.appVersion) < 4 ){
        return true;
    }
    l = document.layers['popup'];
    l = null;
    l = document.layers['popup'];
     l.src = "fav.pl?name="+name+"&zender="+zender+"&localf="+localf;
l.top = d.target.y - 6;
    l.left = d.target.x - 6;
    if( l.left + l.clipWidth > window.width ){
        l.left = window.width - l.clipWidth;
    }
    l.src = "fav.pl?name="+name+"&zender="+zender+"&localf="+localf;

    l.visibility="show";
    return false;
}


function js_options_menu(d) {
    if( parseInt(navigator.appVersion) < 4 ){
        return true;
    }
    l = document.layers['oppopup'];
    l.top = d.target.y - 6;
    l.left = d.target.x - 6;
    if( l.left + l.clipWidth > window.width ){
        l.left = window.width - l.clipWidth;
    }
    l.visibility="show";
    return false;
}
event = 0;
initialLayer = "<TABLE BORDER=1 CELLSPACING=1 CELLPADDING=1><TR><TD><B>Page loading...please wait.</B></TD></TR></TABLE>";

</script>
GROK
}

sub PrintClockJS{
    $nexttime = &UnixDate($nexttime,"%H:%M");
print <<GROK;
    <script LANGUAGE="JavaScript">
<!--- hide this
    // copyright (c) 1996, Author 
function get_tz(x) {
    tzoff = x.getTimezoneOffset()/60; // get hour offset
	sgn = (tzoff < 0); // get sign
    tzoff = Math.abs(tzoff); // take absolute value
tzoff = Math.ceil(tzoff); // get nearest whole hour (corrects a Netscape bug)
  tzoff = (sgn)?-tzoff:tzoff; // restore sign
  return(tzoff);
}
now = new Date();
tzoff = get_tz(now);
sgn = (tzoff < 0)?"-":"+";
q = Math.abs(tzoff);
idl = (tzoff * 3600000.0)+ 54000000.0 ; // get offset to GMT +01 in milliseconds, the first time zone
// -->
</script>



<script LANGUAGE="JavaScript">
<!-- hide from old browsers
// copyright (c) 1996, Author 
var disp_ampm = 0;
var disp_dst = 0;
var start = 1;
daynames = "Zondag   Maandag  Dinsdag  Woensdag Donderdag  Vrijdag  Zaterdag ";
function set_dst(x) {
  month = x.getMonth()+1; // Jan = 0, so add 1
  if ((month >= 4) && (month <= 10)) { // set default Daylight Savings Time for these months
    disp_dst = 1;
  }
}
function ldg_zero(x) {
  if (x < 10) {
    x = "0" + x;
  }
  return(x);
}
function format_date(x) {
  month = x.getMonth()+1; // Jan = 0, so add 1
  dom = x.getDate(); // day of month
  dow = x.getDay(); // day of week
  year = x.getYear();
  hour = x.getHours();
  year = (year > 50)?1900+year:2000+year;
  ampm = "";
  if(disp_ampm) {
    ampm = (hour > 11)?"PM":"AM";
    hour %= 12;
    hour = (hour < 1)?hour+12:hour;
  }
  hour = ldg_zero(hour);
  minute = ldg_zero(x.getMinutes());
  second = ldg_zero(x.getSeconds());
  dow3 = dow * 9;
  dt = "";
  if (disp_dst) {
    dt = "Z.tijd";
  }
  return(daynames.substring(dow3,dow3+9)+" "+month+"/"+dom+"/"+year+" "+hour+":"+minute+":"+second+" "+ampm+" ");
}
function update_clock() {
  now = new Date();
  if(start) {
    set_dst(now);
    start = 0;
  }
  q = idl; // set var q to previously calculated first time zone offset
  if(disp_dst) {
    q -= 3600000.0; // add 1 hour for DST
  }
  now.setTime(now.getTime() ); // set clock to GMT +11
  for(i = 0;i < 1;i++) { // cycle through 24 time zones
  //  document.opform.clock.value = format_date(now); // skip the 4 radio buttons in the form now.setTime(now.getTime() + 3600000.0);
  }


nulang = ldg_zero(now.getHours())+":"+ldg_zero(now.getMinutes())+"."+ldg_zero(now.getSeconds());
nu = ldg_zero(now.getHours())+":"+ldg_zero(now.getMinutes());

if (nu == "$nexttime") {
        window.location.reload();
    }  
  if (nu == "$nexttime"+"00.01"){
      window.location.reload();
  }
  dinges = "now: "+nu+" next: "+"$nexttime"; 
  document.opform.clock2.value = dinges; 
  
  setTimeout('update_clock()', 59000);
}
update_clock();
// end hide -->
</SCRIPT>
GROK
}



sub BouwQuery{
    my ($qwhere,$searcht,$i,$searchf,$query);
    if ($Q->param(Search)){
	$searcht = $Q->param(Search);
	$searcht =~ s/([A-Za-z])/\[\L$1\U$1\]/gi;
	$qwhere .="( ";
	if ($Q->param(SearchOnField) ne "All"){
	    $searchf = $Q->param(SearchOnField);
	    $qwhere .= "".$searchf." ~ '$searcht' ";
	}
	if ($Q->param(SearchOnField) eq "All"){
	    foreach $i ("name","zender","descr","namesub"){
		$qwhere .= "$i ~ '$searcht' OR ";
	    }
	    $qwhere =~ s/OR\s$//;
	}
	$qwhere .=") ";
    }
    if ($Q->param(Zender)){
	if ($Q->param(Zender) ne "All"){
	    $qwhere .= " AND " if ($qwhere);
	    $qwhere .= " (zender = '".$Q->param(Zender)."') ";
	}
    }
    if ($Q->param(Interval) && $Q->param(Interval) ne "whenever"){
	$qwhere .= " AND " if ($qwhere);
	if ($Q->param(Interval) eq "now"){
	    $qwhere .= "endtime > '$nowm' AND timed < '$nowm'";
	}else{
	    if ($Q->param(Interval) =~ /^\-/){
		$qwhere .= " (timed < '$nowm' AND timed > '";
		$qwhere .= &DateCalc($nowm,$Q->param(Interval));
		$qwhere .= "') ";
	    }
	    if ($Q->param(Interval) =~ /^\+/){
		$qwhere .= " (timed > '$nowm' AND timed < '";
		$qwhere .= &DateCalc($nowm,$Q->param(Interval));
		$qwhere .= "') ";
	    }
		
	}
    }
    $query = "where ".$qwhere;
    $query =~ s/^\(//;
    $query =~ s/\)$//;
    $query =~ s/where\s$//;
    
    $query = "select * from programs ".$query;
    $query .=" order by ".$Q->param(SortOrder)." ";
    print "Query: ",$query if ($debug);
    return $query;
 }
sub toencode{
    my($toencode) = @_;
    $toencode=~s/([^a-zA-Z0-9_\-.])/uc sprintf("%%%02x",ord($1))/eg;
    return $toencode;
}



sub PrintBottom{
    @ops = ('Debug','ShowSql','WarnFav');
    $R->{align}="right";    
    print $R->begin;
    foreach $i (@ops){
	print	$Q->checkbox(-name=>$i,
			     ),br;
    }
    print $Q->submit;
    print $R->end;
}


sub CheckFav{
   # my ($s) = shift;
   # my ($f,$c);
   # use lib '/usr/share/plexus/sobject' ;
   # use SharedObjectClient ;
   # tie %favs, SharedObject,'PersistentHash','favs' ;
   # *id=$s->{id};
   # foreach $i (@id){
#	$name=$s->{name}{$i};
#	if ($favs{$name}){
#	    $f .= $name." ".$favs{$name}.br."\n";
#	    $c++;
#	}
 #   }
  #  if ($f){
#	$R->{align}="right";
#	print $R->begin;
#	print "<b><center>Fav</center></b>\n";
#	print $f if ($f);
#	print "</p>\n",$R->end;
#    }
#    untie %favs;
}

#ruim op please
undef($conn);
#Pg::PQfinish($conn);
1;
