#!/usr/bin/perl

# This script is not finished.

#use utf8;
use strict;
use CGI;
use Encode;
use POSIX qw(
    ceil
    floor
);

use Opals::Context;
#use Mail::Sendmail;
use Opals::Template qw(
    tmpl_read
    tmpl_write
);

use Opals::Context;
use Opals::Template qw(
    tmpl_read
    tmpl_write
    tmpl_preference

);


use Opals::Mail qw(
    mail_send
);
use Opals::Session qw(
    SessionHdl_get
);
use Opals::MarcXmlParser; 
my $dbh = Opals::Context->dbh();
use Opals::Locale qw(
    loc_getMsgFile
    loc_write
);


my $dbh = Opals::Context->dbh();
END { $dbh->disconnect(); }

my $cgi = CGI->new;
my $input = $cgi->Vars();
my ($permission, $cookie, $template) = tmpl_read(
        {
            dbh             => $dbh,
            cgi             => $cgi,
            tmplFile        => 'util/bibsrc/save_sendbib.tmpl',
        }
);
my $op          = $cgi->param('op');
my $to          = $cgi->param('email');
my $title       = $cgi->param('title'); 
my $date        = $cgi->param('date'); 
 
my $sessionID = $cgi->cookie('globalSessionID');
my $pref    = tmpl_preference($dbh);
my $from    = $pref->{'emailAddress'};
my $smtp    = $pref->{'emailSmtp'};
my $pqf;
my $zid = $input->{'zid'};
($zid && $zid >= 0) || ($zid = 0);
if($op eq 'save'){
   $title = $cgi->cookie('bTitle');
   if($title eq ""){ 
        $title = "Bibliography";
   }
  $date  = $cgi->cookie('bDate');
   my $bib = $input->{'cont'};
   
   print "Content-Type:application/x-download\n";
   print "Content-Disposition:attachment;filename=bibliography.html\n\n";     
   print $bib;

}
else{
    if(!$to){
        $template->param(
            openForm =>1,
            email     =>$to
       );
    }
    else{
        my $bib = $input->{'cont'};
        $to =~ s/ +/,/g;
        $to =~ s/;+/,/g;
        $to =~ s/,+/,/g;
        $to =~ s/(^,|,$)//g;
        if (mail_send($pref, $to, 'Bibliography', $bib)){
           $template->param(done=>1);
         }
        else{
           $template->param(error=>1);
        }
        $template->param(email=>$to );
    }
    tmpl_write($dbh, $cgi, $cookie, $template);
}
#-----------------------------------------------------------------------------
#Mon, Jan 31, 2011 @ 14:42:04 EST
sub trimPunctuation{
    my($str)=@_;
    $str =~ s/[,;:.]+$//g;
    return $str;
}



