package Opals::Portal;

require Exporter;
@ISA       = qw(Exporter);
# Symbols to be exported by default
#@EXPORT    = qw(
#    opl_
#);
# Symbols to be exported on request
@EXPORT_OK = qw(
    portal_getPortalTheme
    portal_setPortalTheme
    portal_addPortlet
    portal_updatePortlet
    portal_deletePortlet
    portal_deletePortlet_excl
    portal_updateLayout_width
    portal_getLayout
    portal_getNewItemList
    portal_getSearchForm
    portal_getRSS
    portal_getWebLink
    portal_getLibHours
    portal_getNewsEvent
    portal_getPathfinders
    portal_getWeather
    portal_getReaderReview
    portal_getLibCalendar
    portal_getProtalHTML
    portal_getPfShowcase
);
# Version number
$VERSION   = 0.01;      
use HTML::Template;
use Opals::Template_ajax qw(
    tmpl_read
    tmpl_write
    tmpl_preference
);
use Opals::Template qw(
    tmpl_getSearchFieldList
);

use Opals::Search qw(
    srch_searchRecord
    srch_buildNewItemSQLs
    srch_searchRecordSQL
);
use Opals::SolrIndex qw(
    slr_buildSReviewItemQuery
    slr_buildSNewItemQuery
    slr_search
);

use Opals::Circulation qw(
    circ_infoRecord
);
use Opals::BookCover qw(
    bookCover_getUrl
);
use Opals::Date qw(
    date_text
    date_parse
    date_nearestWorkday
);
use Opals::Pathfinder qw(
    pf_getPfList
    pf_getPfListByGrp
    pf_getRecById
);
use Opals::BookCover qw(
    bookCover_getUrl
    bookCover_amazon
    bookCover_google
    bookCover_syndetics

);
use Opals::Rating qw(
    cmntRating_getAvgRating
    cmntRating_numOfRating
);

use POSIX qw(
    ceil
    floor
);

use Opals::Locale qw(
    loc_getMsgFile
    loc_write
);
use Opals::RSSReader;

use Encode;
use LWP::UserAgent;
use HTTP::Request::Common;
use URI::Escape;


use HTML::Template;
#use utf8;
use strict;
 
use Time::localtime;

my $cgi = CGI->new;

################################################################################
sub portal_getPfShowcase{
    my($dbh,$pfIdList,$fieldsShow)=@_;
    my ($permission, $cookie, $template) = tmpl_read(
            {
                dbh             => $dbh,
                cgi             => $cgi,
                tmplFile        => 'ajax/portlet/inc/pfShowcase.inc',
            }
        );
    my $msgValMap ={};
    my $stdMsgMap            =loc_getMsgFile('homeTab.msg',$msgValMap);

    my @pArr=split(',',$pfIdList);
    my $pfList=[]; my $pRec;
    foreach my $pVal(@pArr){
        $pRec     =pf_getRecById($dbh,$pVal);
        push @$pfList,$pRec if(defined $pRec);
    }
    $template->param(pfList     =>$pfList,
                     pfIdList   =>$pfIdList
                    );
    loc_write($template,$stdMsgMap);
    return $template->output;

}
################################################################################
sub portal_getPathfinders{
    my($dbh,$nItemShow,$fieldsShow)=@_;
    my ($permission, $cookie, $template) = tmpl_read(
            {
                dbh             => $dbh,
                cgi             => $cgi,
                tmplFile        => 'ajax/portlet/pfList.tmpl',
            }
        );
    my $msgValMap ={};
    my $stdMsgMap            =loc_getMsgFile('homeTab.msg',$msgValMap);
    if(!defined $nItemShow || $nItemShow <=0){$nItemShow=5;}
    if(!defined $fieldsShow || $fieldsShow eq ''){$fieldsShow='title,description';}

   # my $pfList= pf_getPfList($dbh,'title','',0,$nItemShow);
    my $pfList= pf_getPfListByGrp($dbh,'subject',0,$nItemShow);
    if ($fieldsShow eq 'title'){
        $template->param(fieldsShow1=>1);
    }
    else{
        $template->param(fieldsShow2=>1);
    }
    $template->param(pfList=>$pfList,
                    nItemShow     =>$nItemShow,
                    );
  
    loc_write($template,$stdMsgMap);
    return $template->output;

}
################################################################################
sub portal_getNewsEvent{
    my($dbh,$nItemShow,$fieldsShow)=@_;
    my $tm = localtime;
    my $dateToday = sprintf("%04d-%02d-%02d", $tm->year+1900, ($tm->mon)+1, $tm->mday);
    my ($permission, $cookie, $template) = tmpl_read(
            {
                dbh             => $dbh,
                cgi             => $cgi,
                tmplFile        => 'ajax/portlet/newsEvent.tmpl',
            }
        );
    my $msgValMap ={};
    my $pageMsgMap           =loc_getMsgFile('/homeTab.msg',{});
    loc_write($template,$pageMsgMap);

    if(!defined $nItemShow) {$nItemShow =3;}
 #   if(!defined $fieldsShow){$fieldsShow ='title,description';} 
$fieldsShow ='description';
    my $sql_bk=(<<_SQL_);
    select * from  opl_newsEvents where expDate>=? order by expDate 
_SQL_

    my $sql=(<<_SQL_);
    select * from  opl_newsEvents where status='on' && (DATE_ADD(expDate,INTERVAL 1 DAY)> now() OR expDate is null OR expDate='0000-00-00') order by expDate desc 
_SQL_


  if($nItemShow >0){
        $sql .= " limit  $nItemShow";
    }
    
    my $sth = $dbh->prepare($sql);
    $sth->execute();
 
        my @newsEvent;
        while (my $rec = $sth->fetchrow_hashref) {
             push @newsEvent, $rec;
        }
        $sth->finish;
 
    if ($fieldsShow eq 'title'){
        $template->param(fieldsShow1=>1);
    }
    else{
        $template->param(fieldsShow2=>1);
    }
    $template->param(
        newsEventList =>\@newsEvent,
        nItemShow     =>$nItemShow,
    
    );
        return $template->output;


}
################################################################################
# Thu, Sep 29, 2011 @ 14:49:17 EDT
#
sub _getClosingDate1{
    my($dbh)=@_;
my $i=0;

    my @weekdayClosed;
    my $sth = $dbh->prepare(<<_STH_);
    select weekday 
    from  opl_openHours 
    where (open='' || open regexp 'close')  
_STH_
    $sth->execute;
    while (my $d = $sth->fetchrow_hashref) {
       push  @weekdayClosed,$d;                  
    }
    $sth->finish;

    # Set closing dates

    my @dateClosed;
    $sth = $dbh->prepare(<<_STH_);
select  *
from    opl_dateClosed
order by dClosed asc
_STH_
    $sth->execute;
    while (my $dClosed = $sth->fetchrow_hashref) {
        $dClosed->{'dClosedText'} = date_text($dClosed->{'dClosed'});
        $dClosed->{'pos'}=$i++;
        push @dateClosed, $dClosed;
    }
    $sth->finish;
    
    my $pref        = tmpl_preference($dbh);

    my $dateFirst = date_parse($pref->{'dateFirst'});
    my $dateLast  = date_parse($pref->{'dateLast'});
    my $nwd = date_nearestWorkday($dateFirst, $dateLast);
    my ($year, $month, $day) = $nwd->date();
    ($month > 9) || ($month = "0$month");
    ($day > 9) || ($day = "0$day");

    return(\@weekdayClosed,\@dateClosed,$year,$month,$day);
   
}
################################################################################
sub _getDateClosed{
    my ($dbh,$template) = @_;
    
    my $i=0;
    my $pref = tmpl_preference($dbh);
    my @weekdayClosed;
    my $sth = $dbh->prepare(<<_STH_);
    select weekday 
    from  opl_openHours 
    where (open='' || open regexp 'close')  
_STH_
    $sth->execute;
    while (my $d = $sth->fetchrow_hashref) {
       push  @weekdayClosed,$d;                  
    }
    $sth->finish;

    # Set closing dates

    my @dateClosed;
    $sth = $dbh->prepare(<<_STH_);
select  *
from    opl_dateClosed
order by dClosed asc
_STH_
    $sth->execute;
    while (my $dClosed = $sth->fetchrow_hashref) {
        $dClosed->{'dClosedText'} = date_text($dClosed->{'dClosed'});
        $dClosed->{'pos'}=$i++;
        push @dateClosed, $dClosed;
    }
    $sth->finish;

    my $dateFirst = date_parse($pref->{'dateFirst'});
    my $dateLast  = date_parse($pref->{'dateLast'});
    my $nwd = date_nearestWorkday($dateFirst, $dateLast);
    my ($year, $month, $day) = $nwd->date();
    ($month > 9) || ($month = "0$month");
    ($day > 9) || ($day = "0$day");
    $template->param(
        weekdayClosed => \@weekdayClosed,
        dateClosed => \@dateClosed,
        nearestWorkday => "$year-$month-$day",
    );

}
################################################################################
sub portal_getLibHours{
    my($dbh)=@_;    
    my ($permission, $cookie, $template) = tmpl_read(
            {
                dbh             => $dbh,
                cgi             => $cgi,
                tmplFile        => 'ajax/portlet/libHours.tmpl',
            }
        );

    my $msgValMap ={};
    my $stdMsgMap            =loc_getMsgFile('util/lHours.msg',$msgValMap);
    my $openingHours = listOpeningHr($dbh);
    foreach my $oh(@$openingHours){
        $oh->{'weekday'}=$stdMsgMap->{'weekday_' .$oh->{'weekday'}};
        $oh->{'openPeriod'}=scalar(@{$oh->{'hours'}});
    }
    $template->param(
        openingHours => $openingHours,

    );
    loc_write($template,$stdMsgMap);

    return $template->output;
}
################################################################################

sub listOpeningHr{
    my ($dbh) = @_;
    
    my $sth = $dbh->prepare(<<_STH_);
    select weekday,open,close from  opl_openHours order by weekday,id 
_STH_
    $sth->execute;
 
    my @oHoursList;
    my $preWd=-1;
    my $i=-1;
    while (my ($wd,$open,$close) = $sth->fetchrow_array) {
         $open = mil2AmPmTime($open);
         $close = mil2AmPmTime($close);
         if($wd !=$preWd){
             my @h=({'open'=>$open,'close'=>$close});
             push @oHoursList,{weekday=>$wd,hours=>\@h};
             $i++;
             $preWd=$wd;
         }
         else{
             push @{@oHoursList[$i]->{'hours'}},{'open'=>$open,'close'=>$close};
         }
    }
    $sth->finish;
    return \@oHoursList;

}
################################################################################
sub mil2AmPmTime{
    my ($time)=@_;
    return $time if($time !~ m/[\d]{1,2}:[\d]{1,2}/g);
    my $amPm ="AM";
    my @hr=split(':',$time);
    if(@hr[0]>=12){
        $amPm="PM";
        @hr[0] -=12 if(@hr[0]>12);
    }
    return sprintf("%02d:%02d %s",@hr[0],@hr[1],$amPm);

}
################################################################################
sub portal_getWebLink{
    my ($dbh,$nItemShow,$fieldsShow)=@_;

    if(!defined $nItemShow || $nItemShow <=0){$nItemShow=5;}
    if(!defined $fieldsShow || $fieldsShow eq ''){$fieldsShow='title,url,grade,subject';}
    my ($permission, $cookieList, $template) = tmpl_read(
            {
                dbh             => $dbh,
                cgi             => $cgi,
                tmplFile        => 'ajax/portlet/viewWeblink.tmpl',
            }
    );
    my $msgValMap ={};
    my $stdMsgMap  =loc_getMsgFile('homeTab.msg',$msgValMap);

    my $sql = " select * from   opl_webLinks order by title ";
    if($nItemShow >0){
        $sql .= " limit  $nItemShow";

    }
    my $sth = $dbh->prepare($sql);
       $sth->execute();
 
    my @webLinks;
    my $url;
    while (my $rec = $sth->fetchrow_hashref) {
        $url = $rec->{'url'};
        if($url !~ m/http:\/\/|https:\/\//i){
            $url = "http://" . $url;
            $rec->{'url'} = $url;
        }
        $rec->{'description'} =~ s/\n/<br>/g;
        $rec->{'title'} =~ s/'/\'/g;

        $rec->{'subject'}     =~ s/,/, /g;
        $rec->{'grade'}       =~ s/,/, /g;
         push @webLinks, $rec;
    }
    $sth->finish;

    if ($fieldsShow eq 'title,url,grade,subject'){
        $template->param(fieldsShow1    =>1,
                         showGrade      =>1,
                         showSubject    =>1);
    }
    elsif ($fieldsShow eq 'title,url,subject'){
        $template->param(fieldsShow2    =>1,
                         showSubject    =>1);
    }
    elsif ($fieldsShow eq 'title,url,grade'){
        $template->param(fieldsShow3    =>1,
                         showGrade      =>1);
    }
    else{
        $template->param(fieldsShow4=>1);
    }
    
    $template->param(
        webLinksList    => \@webLinks,
        nItemShow       =>$nItemShow,
    );

    loc_write($template,$stdMsgMap);
    my $wlMsgMap  =loc_getMsgFile('/util/weblink.msg',{});
    loc_write($template,$wlMsgMap);
    return $template->output;

}


################################################################################
sub portal_getRSS{
    my($dbh,$rssUrl,$nItemShow,$fieldsShow,$src)=@_;
    if(! defined $nItemShow || $nItemShow==0 || $nItemShow eq''){
        $nItemShow =3;
    }
    my $nItem2Show= $nItemShow;
    my $params={rssUrl=>$rssUrl,nItemShow=>$nItem2Show,fieldsShow=>$fieldsShow };
    my $rssReader=Opals::RSS->new();
    my $rss = $rssReader->read($params) if(defined $rssUrl && $rssUrl ne '');
    
    my ($permission, $cookie, $template) = tmpl_read(
            {
                dbh             => $dbh,
                cgi             => $cgi,
                tmplFile        => 'ajax/portlet/rss.tmpl',
            }
        );
    my $stdMsgMap  =loc_getMsgFile('homeTab.msg',{});
    loc_write($template,$stdMsgMap);
    if ($fieldsShow eq 'title'){
        $template->param(fieldsDisplay2=>1);
    }
    else{
        $template->param(fieldsDisplay1=>1);
    }
    $template->param(itemList   => $rss->{'itemList'}) if defined $rss->{'itemList'};
    $template->param(title      => $rss->{'channel'}->{'title'},
                     link       => $rss->{'channel'}->{'link'},
                     nItemShow  =>$nItemShow,
                     url        =>$rssUrl, 
                     portalEdit => ($src eq 'portalEdit') ? 1:0,
                     );
    return  $template->output;
}
################################################################################

sub portal_getSearchForm{
   my($dbh)=@_;
   my ($permission, $cookie, $template) = tmpl_read(
            {
                dbh             => $dbh,
                cgi             => $cgi,
                tmplFile        => 'search/searchFrm.inc',
            }
        );
    my ($sfList,$advSfList)=tmpl_getSearchFieldList($dbh);
    my $stdMsgMap  =loc_getMsgFile('search/standard.msg');
    $template->param(sfList=>$sfList,
                    inputSearch => $advSfList);
    loc_write($template,$stdMsgMap);
    return  $template->output;

}
#=======================================================
sub portal_getNewItemList1{
    my ($dbh,$nItemShow,$fieldsShow,$showBookCover,$src) = @_;
    my $rootDir   = Opals::Context->config('rootDir');
    my $template = HTML::Template->new(    
                filename            => "newitems.tmpl",
                path                => "$rootDir/htdocs/theme/opals/ajax/portlet/",
                global_vars         => 0,
                die_on_bad_params   => 0,
                cache               => 1,
                shared_cache        => 0,
                loop_context_vars   => 1,);
    my $pageMsgMap  =loc_getMsgFile('/homeTab.msg',{});
    loc_write($template,$pageMsgMap);

    my ($awsId,$awsSecretKey,$syndeticsId)=('','','');

    if(! defined $nItemShow || $nItemShow eq '' || $nItemShow == 0){
        $nItemShow =5;
    }
    my $pSize  = $nItemShow;

    my $input={sortAttr=>'' , sortOrder=>'' , range=>360,pSize => $pSize}; 

    my @recType     = $cgi->param('recType');
    my $filter;
    $filter->{'recType'}=\@recType;
    my ($recCount, $result) ;#=slr_getNewItemList($sParams);
    
    my $isbnList="";
    my $recRsPos =0;
    foreach my $record (@$result) {
            my $isbnTmpList="";
            if($record->{'isbn'}){
                $isbnTmpList .=join (",",@{$record->{'isbn'}}) . ",";
            }
            $isbnList .=$isbnTmpList;
            $record->{'isbnList'}=$isbnTmpList;
            $record->{'recRsPos'}=$recRsPos++;  
            $record->{'showBookCover_Y'}=1 if($showBookCover eq 'true');  
    }
    if($isbnList ne "" && $showBookCover eq 'true'){
        $awsId       =Opals::Context->preference('amazonId');
        $awsSecretKey=Opals::Context->preference('amazonSecreteKey');
        $syndeticsId =Opals::Context->preference('syndeticsId');
        if($syndeticsId && $syndeticsId ne''){$awsId ="";}
       if($syndeticsId ne''){
            foreach my $record (@$result) {
                my $isbnList="";
                foreach my $i(@{$record->{'isbn'}}){
                    $isbnList .= "," if($isbnList ne '');
                    $isbnList .= $i;
                }
                if($isbnList ne ''){
                    $record->{'bookcover'}="/bin/search/bookcover?size=sc&isbn=$isbnList" ;
                }
            }

        }

        elsif($awsId ne "" && $awsSecretKey ne ''){
             my $bookCoverUrls= bookCover_getUrl($isbnList,$awsId,$awsSecretKey);
             foreach my $record (@$result) {
               foreach my $isbn(@{$record->{'isbn'}}){
                     if($bookCoverUrls->{$isbn}){
                         $record->{'bookcover'}=$bookCoverUrls->{$isbn}->{'small'};
                     }
                 }

             }
        }
        else{
            foreach my $record (@$result) {
                my $isbnArr= $record->{'isbn'};
                if(defined $isbnArr && scalar(@$isbnArr)>0){
                    my $isbn="zzzz";
                    $isbn=@$isbnArr[0] ne ''? _fixISBN(@$isbnArr[0]):"zzzz";
                    $record->{'bookcover'}="http://books.google.com/books?printsec=frontcover&frontcover&img=1&zoom=1&vid=ISBN$isbn";
                }
            }

        }
    }
  
    if ($fieldsShow eq 'title'){
        $template->param(fieldsDisplay2=>1);
    }
    else{
        $template->param(fieldsDisplay1=>1);
    }
    if ($showBookCover eq 'true'){
        $template->param(showBookCover_Y=>1);
    }
    else{
        $template->param(showBookCover_N=>1);
    }
    $template->param(
        result              => \@$result,
        showAmazonCover     => ($awsId && $awsId ne '')  ?1:0,
        showSyndeticsCover  => ($syndeticsId && $syndeticsId ne '')  ?1:0,
        nItemShow           =>$nItemShow,
        searchPage          => ($src eq 'searchPage') ? 1:0,
        portalEdit          => ($src eq 'portalEdit') ? 1:0,
    );

    return $template->output;



   }

################################################################################
### Use SolrIndex.pm
### Wed, Aug 24, 2011 @ 09:11:35 EDT
sub portal_getNewItemList{
    my ($dbh,$nItemShow,$fieldsShow,$showBookCover,$src) = @_;
    my  $showLocation =Opals::Context->preference('showLocation');
    my $rootDir   = Opals::Context->config('rootDir');
    my $template = HTML::Template->new(    
                filename            => "newitems.tmpl",
                path                => "$rootDir/htdocs/theme/opals/ajax/portlet/",
                global_vars         => 0,
                die_on_bad_params   => 0,
                cache               => 1,
                shared_cache        => 0,
                loop_context_vars   => 1,);
    my $pageMsgMap  =loc_getMsgFile('/homeTab.msg',{});
    loc_write($template,$pageMsgMap);

    my ($awsId,$awsSecretKey,$syndeticsId)=('','','');

    if(! defined $nItemShow || $nItemShow eq '' || $nItemShow == 0){
        $nItemShow =5;
    }
    my $input={sortAttr=>'' , sortOrder=>'' , range=>365}; 
    my $pSize  = $nItemShow;
    my $offset      = 0 ;
    my $periodDays = 365;

    if (scalar ($input->{'range'}>0)){
      $periodDays =$input->{'range'};   
    }
    else{
        $input->{'range'}=$periodDays ;  
    }
    my $sortAttr  = $input->{'sortAttr'};
    my $sortOrder = $input->{'sortOrder'};
    if(!defined $sortAttr || $sortAttr eq '' ) {$sortAttr =9002; $sortOrder =1;}

    my $lQuery = slr_buildSNewItemQuery($input);
    my $rs=undef;

    $rs = slr_search({lQuery=>$lQuery,recFormat=>'briefNewItem',
                             sortAttr=>$sortAttr,sortDir=>$sortOrder,
                             offset=>$offset,size=>$pSize,
                             incCircStatus=>1});  

   
  
    my $isbnList="";
    my ($recCount, $result) =($rs->{'hits'},$rs->{'recordList'});
    $showBookCover = 'true';
    my $recRsPos =0;
    foreach my $record (@$result) {
            my $isbnTmpList="";
            if($record->{'isbn'}){
                $isbnTmpList .=join (",",@{$record->{'isbn'}}) . ",";
            }
            $isbnList .=$isbnTmpList;
            $record->{'isbnList'}=$isbnTmpList;
            $record->{'recRsPos'}=$recRsPos++;  
            $record->{'showBookCover_Y'}=1 if($showBookCover eq 'true'); 
            $record->{'showLocation'}= ($showLocation eq '1')?1:0;
    }

   getBookCover($result);
   getRating($result);
          
    if ($fieldsShow eq 'title'){
        $template->param(fieldsDisplay2=>1);
    }
    else{
        $template->param(fieldsDisplay1=>1);
    }
    if ($showBookCover eq 'true'){
        $template->param(showBookCover_Y=>1);
    }
    else{
        $template->param(showBookCover_N=>1);
    }
    $template->param(
        result              => \@$result,
        showAmazonCover     => ($awsId && $awsId ne '')  ?1:0,
        showSyndeticsCover  => ($syndeticsId && $syndeticsId ne '')  ?1:0,
        nItemShow           =>$nItemShow,
        searchPage          => ($src eq 'searchPage') ? 1:0,
        portalEdit          => ($src eq 'portalEdit') ? 1:0,
    );

    return $template->output;
   
    
}


################################################################################
sub portal_getNewItemList_bk{
    my ($dbh,$nItemShow,$fieldsShow,$showBookCover,$src) = @_;
    my $rootDir   = Opals::Context->config('rootDir');
    my $template = HTML::Template->new(    
                filename            => "newitems.tmpl",
                path                => "$rootDir/htdocs/theme/opals/ajax/portlet/",
                global_vars         => 0,
                die_on_bad_params   => 0,
                cache               => 1,
                shared_cache        => 0,
                loop_context_vars   => 1,);
    my $pageMsgMap  =loc_getMsgFile('/homeTab.msg',{});
    loc_write($template,$pageMsgMap);

    my ($awsId,$awsSecretKey,$syndeticsId)=('','','');

    if(! defined $nItemShow || $nItemShow eq '' || $nItemShow == 0){
        $nItemShow =5;
    }
    my $input={sortAttr=>'' , sortOrder=>'' , range=>360}; 
    my $pSize  = $nItemShow;
    my ($sql,$sql_count)= srch_buildNewItemSQLs($input);

    my $isbnList="";
    my ($recCount, $result) =srch_searchRecordSQL($dbh,'b',  $sql,$sql_count, 0, $pSize);
    
    my $recRsPos =0;
    foreach my $record (@$result) {
            my $isbnTmpList="";
            if($record->{'isbn'}){
                $isbnTmpList .=join (",",@{$record->{'isbn'}}) . ",";
            }
            $isbnList .=$isbnTmpList;
            $record->{'isbnList'}=$isbnTmpList;
            $record->{'recRsPos'}=$recRsPos++;  
            $record->{'showBookCover_Y'}=1 if($showBookCover eq 'true');  
    }
    if($isbnList ne "" && $showBookCover eq 'true'){
        $awsId       =Opals::Context->preference('amazonId');
        $awsSecretKey=Opals::Context->preference('amazonSecreteKey');
        $syndeticsId =Opals::Context->preference('syndeticsId');
        if($syndeticsId && $syndeticsId ne''){$awsId ="";}
       if($syndeticsId ne''){
            foreach my $record (@$result) {
                my $isbnList="";
                foreach my $i(@{$record->{'isbn'}}){
                    $isbnList .= "," if($isbnList ne '');
                    $isbnList .= $i;
                }
                if($isbnList ne ''){
                    $record->{'bookcover'}="/bin/search/bookcover?size=sc&isbn=$isbnList" ;
                }
            }

        }

        elsif($awsId ne "" && $awsSecretKey ne ''){
             my $bookCoverUrls= bookCover_getUrl($isbnList,$awsId,$awsSecretKey);
             foreach my $record (@$result) {
               foreach my $isbn(@{$record->{'isbn'}}){
                     if($bookCoverUrls->{$isbn}){
                         $record->{'bookcover'}=$bookCoverUrls->{$isbn}->{'small'};
                     }
                 }

             }
        }
        else{
            foreach my $record (@$result) {
                my $isbnArr= $record->{'isbn'};
                if(defined $isbnArr && scalar(@$isbnArr)>0){
                    my $isbn="zzzz";
                    $isbn=@$isbnArr[0] ne ''? _fixISBN(@$isbnArr[0]):"zzzz";
                    $record->{'bookcover'}="http://books.google.com/books?printsec=frontcover&frontcover&img=1&zoom=1&vid=ISBN$isbn";
                }
            }

        }
    }
  
    if ($fieldsShow eq 'title'){
        $template->param(fieldsDisplay2=>1);
    }
    else{
        $template->param(fieldsDisplay1=>1);
    }
    if ($showBookCover eq 'true'){
        $template->param(showBookCover_Y=>1);
    }
    else{
        $template->param(showBookCover_N=>1);
    }
    $template->param(
        result              => \@$result,
        showAmazonCover     => ($awsId && $awsId ne '')  ?1:0,
        showSyndeticsCover  => ($syndeticsId && $syndeticsId ne '')  ?1:0,
        nItemShow           =>$nItemShow,
        searchPage          => ($src eq 'searchPage') ? 1:0,
        portalEdit          => ($src eq 'portalEdit') ? 1:0,
    );

    return $template->output;
   
    
}
#////////////////////////////////////////////////////////////////////////////
sub _fixISBN{
    my($isbn)=@_;
    $isbn=~ m/([\D^x^X]*)([\dxX][\dxX -]{8,}[\dxX])([\D^x^X]*)/;
    $isbn= $2;
    $isbn=~ s/[- ]//g;
    return $isbn; 
}

#===============================================================================
#reference: http://developer.yahoo.com/weather/    
sub portal_getWeather_yahoo{
    my ($dbh,$woeid,$unit)= @_;
    my $rootDir   = Opals::Context->config('rootDir');
    my $yahooWeather="Not available";
    my $weatherTitle="Yahoo weather";
    my $weatherUrl="";
    my $template = HTML::Template->new(    
                filename            => "weather.tmpl",
                path                => "$rootDir/htdocs/theme/opals/ajax/portlet/",
                die_on_bad_params   => 0,
                cache               => 1,
                shared_cache        => 0,
                loop_context_vars   => 1,);

    
    if(!defined $unit || ($unit ne 'c' && $unit ne 'f' )){
        $unit="f";
    }
    my $url="http://weather.yahooapis.com/forecastrss?w=$woeid&u=$unit";
    my $userAgent = LWP::UserAgent->new(agent   => 'OPALS',
                                        timeout =>600);
    my $request = HTTP::Request->new(GET =>$url ); 
    my $response = $userAgent->request($request );
    if($response->is_success){
        my $xml=$response->content;
        if($xml =~ m/<title>(.*?)<\/title>/g){
            $weatherTitle=$1;
        }
        if($xml =~ m/<link>(.*?)<\/link>/g){
            $weatherUrl=$1;
        }
        if($xml =~ m/<description><!\[CDATA\[(.*?)\]\]><\/description>/s){
            $yahooWeather=$1;
        }
        
    }
    $template->param(title=>$weatherTitle,
                    link=>$weatherUrl,
                    yahooWeather=>$yahooWeather );
  
    return $template->output;
}

#===============================================================================
# From google secret api

sub portal_getWeather_bk{
    my ($dbh,$zipCode,$unit)= @_;
    $unit=uc($unit);
    my $rootDir   = Opals::Context->config('rootDir');
    my $yahooWeather="Not available";
    my ($city,$condition,$wind,$humidity,$icon,$temp)=("","","","","","");
    my $forecast_conditions=[];
    my $template = HTML::Template->new(    
                filename            => "weather.tmpl",
                path                => "$rootDir/htdocs/theme/opals/ajax/portlet/",
                die_on_bad_params   => 0,
                cache               => 1,
                shared_cache        => 0,
                loop_context_vars   => 1,);

     my $msgValMap ={};
    my $pageMsgMap           =loc_getMsgFile('/homeTab.msg',{});
    loc_write($template,$pageMsgMap);

    if(!defined $unit || ($unit ne 'C' && $unit ne 'F' )){
        $unit="F";
    }
    my $url="http://www.google.com/ig/api?weather=$zipCode";
    my $userAgent = LWP::UserAgent->new(agent   => 'OPALS',
                                        timeout =>600);
    my $request = HTTP::Request->new(GET =>$url ); 
    my $response = $userAgent->request($request );
    my $maxForcast=3;
    if($response->is_success){
        my $xml=$response->content;
        if($xml =~ m/<forecast_information>(.*?)<\/forecast_information>/g){
            my $fInfo=$1;
            if($fInfo =~ m/<city data="(.*?)"\/>/g){
                $city=$1;
            }
        }
        if($xml =~ m/<current_conditions>(.*?)<\/current_conditions>/s){
            my $forcast= getWeatherForcast($1);
            if($forcast){
                $condition=$forcast->{'condition'};
                $wind     =$forcast->{'wind_condition'};
                $humidity =$forcast->{'humidity'};
                $icon =$forcast->{'icon'};
                my $t =$forcast->{'temp_f'};
                   $t =fahrenheitToCelsius($t) if($unit =~ m/^C$/i);
                $temp =sprintf("%2d &deg;",$t);

            }
        }
        my $tmpXml =$xml;
        my $countForcast=0;
        while($tmpXml =~ m/<forecast_conditions>(.*?)<\/forecast_conditions>(.*)/s && $countForcast <$maxForcast){
            $tmpXml=$2;
            my $forcast= getWeatherForcast($1);
            push @$forecast_conditions,$forcast if($forcast );
        }
        foreach my $f(@$forecast_conditions){
            if($unit =~ m/^c$/i){
                $f->{'low'} =fahrenheitToCelsius($f->{'low'});
                $f->{'high'} =fahrenheitToCelsius($f->{'high'});
            }
        }

               
    }
    $template->param(zipCode=>$zipCode,
                    city=>$city,
                    condition=>$condition,
                    wind=>$wind,
                    humidity=>$humidity,
                    icon=>$icon,
                    temp=>"$temp $unit",
                    forecast_conditions=>$forecast_conditions,
                     );
  
    return $template->output;
}
#===============================================================================
# Fri, Aug 31, 2012 @ 10:35:03 EDT
#
sub getWoeid{
    my ($location)=@_;
    my $woeid="";
    my $url_woeid="http://query.yahooapis.com/v1/public/yql?q=select woeid from geo.places where text=\"$location\" limit 1&diagnostics=true&format=xml";
    my $userAgent = LWP::UserAgent->new(agent   => 'OPALS',
                                        timeout =>600);
    my $request = HTTP::Request->new(GET =>$url_woeid ); 
    my $response = $userAgent->request($request );
    my $maxForcast=3;
    if($response->is_success){
        my $xml=$response->content;        
        if($xml =~ m/<results>([\s|\r|\n]*)<place (.*?)>([\s|\r|\n]*)<woeid>(.*)<\/woeid><\/place><\/results>/g){
            $woeid=$4;
        }
    }
    return $woeid;

    
}

#===============================================================================
# Fri, Aug 31, 2012 @ 10:35:03 EDT
#
sub getWeather{
    my ($woeid,$unit)=@_;
    my $url_weather="http://query.yahooapis.com/v1/public/yql?q=select * from weather.forecast where woeid=\"$woeid\"";
    my $userAgent = LWP::UserAgent->new(agent   => 'OPALS',
                                        timeout =>600);
    my $request = HTTP::Request->new(GET =>$url_weather ); 
    my $response = $userAgent->request($request );
    my $maxForcast=3;
    my $w ={};
    if($response->is_success){
        my $xml=$response->content;   
        $w =parseYahooWeather($xml,$unit);
    }
    return $w;

}

#===============================================================================
# Fri, Aug 31, 2012 @ 10:35:03 EDT
#
sub parseYahooWeather{
    my ($xml,$unit)=@_;
    my $weather={};
    $weather->{"forcast"}=[];
    my $itemList=[];
   
    while($xml=~ s/(.*)(<image>(.*?)<\/image>)(.*)/$1$4/s){}
    
    while($xml=~ s/(.*)(<item>(.*?)<\/item>)(.*)/$1$4/s){
        push @$itemList,$2;
    }
    if($xml=~ s/(.*)(<link>(.*?)<\/link>)(.*)/$1$4/s){
        $weather->{'fullForcastLink'}=$3;
    }

    if($xml=~ s/(.*)(<yweather:location (.*?)\/>)(.*)/$1$4/s){
        my $locXml=$3;
        foreach my $f (qw(region city  country)){
            if($locXml =~ s/$f=\"(.*?)\"//gi){
                $weather->{'location'}->{$f}=$1;
            }
        }
    }
    
    if($xml=~ s/(.*)(<yweather:wind (.*?)\/>)(.*)/$1$4/s){
        my $windXml=$3;
        foreach my $f (qw(Direction Speed)){
            if($windXml =~ s/$f=\"(.*?)\"//gi){
                $weather->{"currentCond"}->{"wind$f"}=$1;
            }
        } 
        my $dirMap={0=>'N',1=>'NE',2=>'E',3=>'SE',4=>'S',5=>'SW',6=>'W',7=>'NW'};
        my $d =int($weather->{"currentCond"}->{"windDirection"});
        my $n =floor($d/90);
        my $r =$n+ $d%90>0?1:0;
        my $wd=($n+$r)%8;
        $weather->{"currentCond"}->{"windDirection"} = $dirMap->{$wd};

    }
    if($xml=~ s/(.*)(<yweather:atmosphere (.*?)\/>)(.*)/$1$4/s){
        my $aspXml=$3;
        if($aspXml =~ s/humidity=\"(.*?)\"//gi){
            $weather->{"currentCond"}->{'humidity'}=$1;
        }
       
    }
    my $itemXml=@$itemList[0];
    if($itemXml=~ s/(.*)(<yweather:condition (.*?)\/>)(.*)/$1$4/s){
        my $condXml=$3;
        foreach my $f (qw(code text temp )){
            if($condXml =~ s/$f=\"(.*?)\"//gi){
                $weather->{"currentCond"}->{"$f"}=$1;
            }
        }
        while($itemXml =~ s/(.*)(<yweather:forecast (.*?)\/>)(.*)//){
            my $condXml=$3;
            my $fc={};
            foreach my $f (qw(date day code high low text)){
                if($condXml =~ s/$f=\"(.*?)\"//gi){
                    $fc->{$f}=$1;
                }
            }
            $fc->{'day_of_week'}=$fc->{'day'};
            $fc->{'icon'}=sprintf("/theme/opals/image/%s.png", $fc->{'code'});
            push @{$weather->{"forcast"}} ,$fc;
        }
       
    }
    if(defined $unit && $unit eq 'metric'){
        $weather->{"currentCond"}->{"windSpeed"} =int($weather->{"currentCond"}->{"windSpeed"}/0.6214) ." kmph";
        $weather->{"currentCond"}->{"temp"} = fahrenheitToCelsius($weather->{"currentCond"}->{"temp"});
        $weather->{"currentCond"}->{"temp"} = sprintf("%2d &deg; C",$weather->{"currentCond"}->{"temp"});
        foreach my $fc(@{$weather->{"forcast"}}){
            $fc->{"high"}=fahrenheitToCelsius($fc->{"high"});
            $fc->{"high"}=sprintf("%2d ",$fc->{"high"});
            $fc->{"low"}=fahrenheitToCelsius($fc->{"low"});
            $fc->{"low"}=sprintf("%2d ",$fc->{"low"});
        }
    }
    else{
        $weather->{"currentCond"}->{"temp"} .= " &deg; F";
        $weather->{"currentCond"}->{"windSpeed"} .=" mph";
    }
    return $weather;
}

#===============================================================================
# Fri, Aug 31, 2012 @ 10:35:03 EDT
#
sub portal_getWeather{
    my ($dbh,$zipCode,$unit)= @_;
    $unit=uc($unit);
    my $rootDir   = Opals::Context->config('rootDir');
    my $yahooWeather="Not available";
    my ($city,$region,$country,$condition,$wind,$humidity,$icon,$temp)=("","","","","","","","");
    my ($windSpeed,$windDirection,$forcast)=("","",[]);
    my $forecast_conditions=[];
    my $template = HTML::Template->new(    
                filename            => "weather.tmpl",
                path                => "$rootDir/htdocs/theme/opals/ajax/portlet/",
                die_on_bad_params   => 0,
                cache               => 1,
                shared_cache        => 0,
                loop_context_vars   => 1,);

    my $msgValMap ={};
    my $pageMsgMap           =loc_getMsgFile('/homeTab.msg',{});
    loc_write($template,$pageMsgMap);
    my $unitSys=($unit eq "C")?"metric":"US";
    my $woeid= getWoeid($zipCode);
    if(!defined $woeid || $woeid eq ''){
        my $country = Opals::Context->preference('country');
        $woeid= getWoeid("$zipCode $country");
    }
    if($woeid ne ""){
        my $w    = getWeather($woeid,$unitSys);
        if($w){
            $city   = $w->{'location'}->{'city'};
            $region = $w->{'location'}->{'region'};
            $country= $w->{'location'}->{'country'};
            $city  .= ($region ne "")? ", " .$region : '';
            $city  .= ($country ne "")? " " .$country : '';
            
            $windDirection  = $w->{'currentCond'}->{'windDirection'};
            $windSpeed      = $w->{'currentCond'}->{'windSpeed'};

            $humidity   = $w->{'currentCond'}->{'humidity'};
            $temp       = $w->{'currentCond'}->{'temp'};
            $icon       = sprintf("/theme/opals/image/%s.png", $w->{'currentCond'}->{'code'});
            $condition  = $w->{'currentCond'}->{'text'};
            $forcast    = $w->{'forcast'};
            
        }
    }
    
    $template->param(zipCode=>$zipCode,
                    city=>$city,
                    condition=>$condition,
                    windSpeed=>$windSpeed,
                    windDirection=>$windDirection,
                    humidity=>$humidity,
                    icon=>$icon,
                    temp=>"$temp",
                     );
  
    $template->param(forecast_conditions=>$forcast) if(scalar(@$forcast)>0);
    return $template->output;
}
#===============================================================================

sub getWeatherForcast{
    my ($xml)=@_;
    my $forcast=undef;
    my @tags=qw(day_of_week condition wind_condition temp_f humidity high low icon);
    foreach my $t(@tags){
        if($xml =~ m/<$t data="(.*?)"\/>/s){
            $forcast->{$t}=$1;
        }
    }
    return  $forcast;
}
#===============================================================================
sub fahrenheitToCelsius{
    my($f)=@_;
    my $c =(5/9)*($f-32);
    return sprintf("%.0f",$c);
}
#===============================================================================
sub portal_updateLayout_width{
    my ($dbh,$tid,$row,$col,$width)=@_;
    my $doUpdate;
    if($width && $width ne 'NULL'){
        $doUpdate = $dbh->do("update opl_portalLayout set cWidth=$width where tid=$tid && colPos=$col && rowPos=$row");
        $doUpdate =1;
    }
    my $doReset  = $dbh->do("update opl_portlet set ordinal=null where  pid=1");
   return $doUpdate eq '0E0'?0:1;

}
#===============================================================================
sub portal_addPortlet {
    my ($dbh,$p) = @_;

    my $themeId =1;
    my $cid=getPortletCid($dbh,$themeId,$p->{'row'},$p->{'col'});

    my $sql_portlet = <<_STH_;
insert into    opl_portlet  set
                cid     = ?,
                ordinal = ?,
                type    = ?
_STH_

    my $sth  = $dbh->prepare($sql_portlet);
    my $portlet = $sth->execute($cid, $p->{'ordinal'},$p->{'type'});  
    my $pid = $dbh->{'mysql_insertid'};
    $sth->finish;

#-------------------- 
    my $sql_portletProp = <<_STH_;
insert into    opl_portletProp  set
                pid   = ?,
                var   = ?,
                val   = ?
_STH_

    my $sth  = $dbh->prepare($sql_portletProp);
    my $prop = $p->{'prop'};
    foreach my $var(keys %$prop){
        $sth->execute($pid, $var,$prop->{$var} );  
    }

    $sth->finish;

   return $pid;
}

#===============================================================================
sub portal_updatePortlet {
    my ($dbh,$p) = @_;
    my $pid = $p->{'pid'};
    my $themeId =1;
    my $cid=getPortletCid($dbh,$themeId,$p->{'row'},$p->{'col'});


#-------------------- 
    my $sql_portlet = <<_STH_;
update opl_portlet 
set    cid     = ?,
       ordinal = ?,
       type    = ?
where pid =?                
_STH_

    my $sth  = $dbh->prepare($sql_portlet);
    my $portlet = $sth->execute($cid, $p->{'ordinal'},
                               $p->{'type'},$pid );  
    $sth->finish;

#-------------------- 
    $dbh->do("delete from opl_portletProp where pid= $pid");
    my $sql_portletProp = <<_STH_;
insert into    opl_portletProp  set
                pid   = ?,
                var   = ?,
                val   = ?
_STH_

    my $sth  = $dbh->prepare($sql_portletProp);
    my $prop = $p->{'prop'};
    foreach my $var(keys %$prop){
        $sth->execute($pid, $var,$prop->{$var});  
    }

    $sth->finish;

    return $pid;
}

#===============================================================================
sub portal_deletePortlet {
    my ($dbh,$pid) = @_;

    $dbh->do("delete  from opl_portletProp  where pid= $pid");
    $dbh->do("delete  from opl_portlet where pid= $pid");

}


#===============================================================================
sub portal_deletePortlet_excl{
    my ($dbh,$pidList) = @_;
    my $pidListStr =join(",",@$pidList);
    $dbh->do("delete from opl_portlet where pid not in($pidListStr)");
    $dbh->do("delete from opl_portletProp where pid not in($pidListStr)");
    
}

#===============================================================================
sub portal_getLayout{
    my ($dbh) = @_;
    my $sth =$dbh->prepare(<<_SQL_) ;
    select  rowPos,colPos,ordinal,cWidth,cHeight,pid,type
    from    opl_portalTheme t inner join opl_portalLayout l using(tid) 
            left outer join opl_portlet p using(cid)
    where tid=?        
    order by rowPos,colPos,ordinal;
_SQL_

    $sth->execute(1);
    my ($i,$j,$k)=(0,0,0);
    my @layout=();
    my $layoutRows;
    my $portletList=[];
    while( my($rowPos,$colPos,$ordinal,$cWidth,$cHeight,$pid,$type)=$sth->fetchrow_array){
        if(defined $pid && $pid>0){
            my $prop = getPortletProp($dbh,$pid);
            
            push @$portletList,{pid=>$pid,
                                type=>$type,
                                width=>$cWidth,
                                height=>$cHeight,
                                row=>$rowPos ,
                                col=>$colPos,
                                ordinal=>$ordinal,
                                prop=>$prop};
            $layoutRows->{$rowPos}->{$colPos}->{'porletList'}->{$ordinal} ={pid=> $pid,type=>$type};
            foreach my $p(@$prop){
                $layoutRows->{$rowPos}->{$colPos}->{'porletList'}->{$ordinal}->{$p->{'var'}} =$p->{'val'};
            }
        }
        $layoutRows->{$rowPos}->{$colPos}->{'width'} = $cWidth;
        $layoutRows->{$rowPos}->{$colPos}->{'height'}= $cHeight;
    }


    my $tblId=0;
    foreach my $row(sort keys %$layoutRows){
        my $colList =undef;
        my $colNum=0;
        foreach my $col(sort keys %{$layoutRows->{$row}}){
            my $column ={colNum=>$colNum,width=>$layoutRows->{$row}->{$col}->{'width'}};
            my $portlet=undef;
            foreach my $o(sort {$a <=> $b} keys %{$layoutRows->{$row}->{$col}->{'porletList'}}){

                push @{$portlet},$layoutRows->{$row}->{$col}->{'porletList'}->{$o};

            }
            $column->{'portlet'}=$portlet if(defined $portlet);
            push @$colList,$column;
            $colNum++;
        }
        push @layout,{tblId=>$row,colList=>$colList};
    }
       
    $sth->finish;
    return (\@layout,$portletList);
}
################################################################################
sub getPortletProp{
  my($dbh,$pid)=@_;
    my $prop=[];
    
    my $sth = $dbh->prepare("select var,val from opl_portletProp where pid=?");
    $sth->execute($pid); 
    while( my ($var,$val) = $sth->fetchrow_array){
        push @$prop,{var=>$var,val=>$val};
    }
    $sth->finish;
    return $prop;

}
################################################################################
sub getPortletCid{
    my ($dbh,$tid,$row,$col)=@_;
    my ($cid)=$dbh->selectrow_array("select cid from opl_portalLayout where tid=$tid && colPos=$col && rowPos=$row ");
    return $cid?$cid:1;
}

################################################################################
sub  portal_getPortalTheme{
    my($dbh)=@_;
    my $themeId =1;
    my ($css)=$dbh->selectrow_array("select css from opl_portalTheme where tid=$themeId");
    return $css;   

}

################################################################################
sub  portal_setPortalTheme{
    my($dbh,$css)=@_;
    my $themeId =1;
    my ($doUpdate)=$dbh->do("update opl_portalTheme set css= '$css' where tid=$themeId");

   return $doUpdate eq '0E0'?0:1;
}



################################################################################
### Tue, Aug 23, 2011 @ 11:06:46 EDT
###
sub portal_getReaderReview{
   my ($dbh,$nItemShow,$fieldsShow,$showBookCover,$src) = @_;
    my $rootDir   = Opals::Context->config('rootDir');
    my $template = HTML::Template->new(    
                filename            => "reviewitems.tmpl",
                path                => "$rootDir/htdocs/theme/opals/ajax/portlet/",
                global_vars         => 0,
                die_on_bad_params   => 0,
                cache               => 1,
                shared_cache        => 0,
                loop_context_vars   => 1,);
    my $pageMsgMap  =loc_getMsgFile('/homeTab.msg',{});
    loc_write($template,$pageMsgMap);

    my ($awsId,$awsSecretKey,$syndeticsId)=('','','');

    if(! defined $nItemShow || $nItemShow eq '' || $nItemShow == 0){
        $nItemShow =5;
    }
    my $input={sortAttr=>'' , sortOrder=>'' , range=>365}; 
    my $pSize  = $nItemShow;
    my $offset      = 0 ;
    my $periodDays = 365;

    if (scalar ($input->{'range'}>0)){
      $periodDays =$input->{'range'};   
    }
    else{
        $input->{'range'}=$periodDays ;  
    }
    my $sortAttr  = $input->{'sortAttr'};
    my $sortOrder = $input->{'sortOrder'};
    if(!defined $sortAttr || $sortAttr eq '' ) {$sortAttr =9003; $sortOrder =1;}

    my $lQuery=slr_buildSReviewItemQuery($input);
    my $rs=undef;

    $rs = slr_search({lQuery=>$lQuery,recFormat=>'briefReviewItem',
                             sortAttr=>$sortAttr,sortDir=>$sortOrder,
                             offset=>$offset,size=>$pSize,
                             incCircStatus=>1});  

   

    my $isbnList="";
    my ($recCount, $result) =($rs->{'hits'},$rs->{'recordList'});
    $showBookCover = 'true';
    my $recRsPos =0;
    foreach my $record (@$result) {
            my $isbnTmpList="";
            if($record->{'isbn'}){
                $isbnTmpList .=join (",",@{$record->{'isbn'}}) . ",";
            }
            $isbnList .=$isbnTmpList;
            $record->{'isbnList'}=$isbnTmpList;
            $record->{'recRsPos'}=$recRsPos++;  
            $record->{'showBookCover_Y'}=1 if($showBookCover eq 'true');  
    }
   
   
   getBookCover($result);
   getRating($result);

    if ($fieldsShow eq 'title'){
        $template->param(fieldsDisplay2=>1);
    }
    else{
        $template->param(fieldsDisplay1=>1);
    }
    if ($showBookCover eq 'true'){
        $template->param(showBookCover_Y=>1);
    }
    else{
        $template->param(showBookCover_N=>1);
    }
    $template->param(
        result              => \@$result,
        showAmazonCover     => ($awsId && $awsId ne '')  ?1:0,
        showSyndeticsCover  => ($syndeticsId && $syndeticsId ne '')  ?1:0,
        nItemShow           =>$nItemShow,
        searchPage          => ($src eq 'searchPage') ? 1:0,
        portalEdit          => ($src eq 'portalEdit') ? 1:0,
    );

    return $template->output;

}

#=======================================================
#Tue, Oct 25, 2011 @ 12:18:01 EDT
#
sub portal_getLibCalendar{
    my($dbh,$showHolidays)=@_;
    my $tm = localtime;
    my $msgValMap ={};
    my $stdMsgMap            =loc_getMsgFile('util/lHours.msg',$msgValMap);
    my $dateToday = sprintf("%04d-%02d-%02d", $tm->year+1900, ($tm->mon)+1, $tm->mday);
    my ($permission, $cookie, $template) = tmpl_read(
            {
                dbh             => $dbh,
                cgi             => $cgi,
                tmplFile        => 'ajax/portlet/libCalendar.tmpl',
            }
        );
    _getDateClosed($dbh,$template);
     my $openingHours = listOpeningHr($dbh);
    foreach my $oh(@$openingHours){
        $oh->{'weekday'}=$stdMsgMap->{'weekday_' .$oh->{'weekday'}};
        $oh->{'openPeriod'}=scalar(@{$oh->{'hours'}});
    }

    $template->param(
        dateToday    => $dateToday, 
        openingHours => $openingHours,
    );

    loc_write($template,$stdMsgMap);

   
    return $template->output;
}
#================================================================
#Tue, Apr 17, 2012 @ 13:49:22 EDT
#
# add param $isPortalEdit on Thu, Aug 02, 2012 @ 13:42:02 EDT
#
#================================================================
sub portal_getProtalHTML{
    my($dbh,$pHtml,$fieldsShow,$isPortalEdit)=@_;
    my $tm = localtime;
    my $msgValMap ={};
    my $stdMsgMap            =loc_getMsgFile('homeTab.msg',$msgValMap);
    my $dateToday = sprintf("%04d-%02d-%02d", $tm->year+1900, ($tm->mon)+1, $tm->mday);
    my ($permission, $cookie, $template) = tmpl_read(
            {
                dbh             => $dbh,
                cgi             => $cgi,
                tmplFile        => 'ajax/portlet/portalHTML.tmpl',
            }
        );
    $template->param(
        fieldShow => $fieldsShow,
        pHtml      => $pHtml, 
    );

    loc_write($template,$stdMsgMap);

   
    return $template->output;
}


#=======================================================
sub getPortalHTML{
    my($dbh,$showHolidays)=@_;

}
#=======================================================
sub getBookCover{
    my($recList)=@_;
    my  $awsId =Opals::Context->preference('amazonId');
    my  $awsSecretKey =Opals::Context->preference('amazonSecreteKey');
    my  $syndeticsId =Opals::Context->preference('syndeticsId');
    if($syndeticsId ne''){
        bookCover_syndetics($recList);
    }
    elsif($awsId ne '' && $awsSecretKey ne ''){
        bookCover_amazon($recList,$awsId,$awsSecretKey);
    }
    else{
        bookCover_google($recList,'m');
    }

}
#////////////////////////////////////////////////////////////////////////////
sub getRating{
    my ($recList)=@_;
    my  $rating =Opals::Context->preference('rating'); 
    my $dbh = Opals::Context->dbh();

    if($rating && $rating ==2 ){
        foreach my $rec(@$recList){
            my $noReview  = cmntRating_numOfRating($dbh,$rec->{'rid'});
            my $avgRating = cmntRating_getAvgRating($dbh,$rec->{'rid'});
            my $numOfStars =floor($avgRating);
            my $fraction= $avgRating - $numOfStars ;
            if($fraction >0.25 && $fraction<0.75){
                $numOfStars += 0.5;
            }
            elsif($fraction >0.75){
                $numOfStars += 1;
            }

            my $avgRating = sprintf("%.2f", $avgRating);
            $rec->{'rateRec'} = $avgRating;
            $rec->{'numReview'} = $noReview;
            $rec->{'numOfStars'} = $numOfStars;
           }
    }
}

################################################################################
1;
