File:  [LON-CAPA] / loncom / interface / lonhtmlcommon.pm
Revision 1.356: download - view: text, annotated - select for diffs
Wed Jan 15 17:52:04 2014 UTC (10 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: version_2_11_0_RC3, version_2_11_0_RC2, version_2_11_0, HEAD
- Use minified jquery.countdown javascript file.

    1: # The LearningOnline Network with CAPA
    2: # a pile of common html routines
    3: #
    4: # $Id: lonhtmlcommon.pm,v 1.356 2014/01/15 17:52:04 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ######################################################################
   29: ######################################################################
   30: 
   31: =pod
   32: 
   33: =head1 NAME
   34: 
   35: Apache::lonhtmlcommon - routines to do common html things
   36: 
   37: =head1 SYNOPSIS
   38: 
   39: Referenced by other mod_perl Apache modules.
   40: 
   41: =head1 INTRODUCTION
   42: 
   43: lonhtmlcommon is a collection of subroutines used to present information
   44: in a consistent html format, or provide other functionality related to
   45: html.
   46: 
   47: =head2 General Subroutines
   48: 
   49: =over 4
   50: 
   51: =cut 
   52: 
   53: ######################################################################
   54: ######################################################################
   55: 
   56: package Apache::lonhtmlcommon;
   57: 
   58: use strict;
   59: use Time::Local;
   60: use Time::HiRes;
   61: use Apache::lonlocal;
   62: use Apache::lonnet;
   63: use HTML::Entities();
   64: use LONCAPA qw(:DEFAULT :match);
   65: 
   66: sub java_not_enabled {
   67:     if (($env{'browser.mobile'}) && ($env{'browser.mobile'} =~ /^ipad|ipod|iphone$/i)) {
   68:         return "\n".'<span class="LC_error">'.
   69:                &mt('The required Java applet could not be started, because Java is not supported by your mobile device.').
   70:                "</span>\n";
   71:     } else {
   72:         return "\n".'<span class="LC_error">'.
   73:                &mt('The required Java applet could not be started. Please make sure to have Java installed and active in your browser.').
   74:                "</span>\n";
   75:     }
   76: }
   77: 
   78: sub coursepreflink {
   79:    my ($text,$category)=@_;
   80:    if (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
   81:       return '<a target="_top" href="'.&HTML::Entities::encode("/adm/courseprefs?phase=display&actions=$category",'<>&"').'"><span class="LC_setting">'.$text.'</span></a>';
   82:    } else {
   83:       return '';
   84:    }
   85: }
   86: 
   87: sub raw_href_to_link {
   88:    my ($message)=@_;
   89:    $message=~s/(https?\:\/\/[^\s\'\"\<]+)([\s\<]|$)/<a href="$1"><tt>$1<\/tt><\/a>$2/gi;
   90:    return $message;
   91: }
   92: 
   93: sub entity_encode {
   94:     my ($text)=@_;
   95:     return &HTML::Entities::encode($text, '<>&"');
   96: }
   97: 
   98: sub direct_parm_link {
   99:     my ($linktext,$symb,$filter,$part,$target)=@_;
  100:     $symb=&entity_encode($symb);
  101:     $filter=&entity_encode($filter);
  102:     $part=&entity_encode($part);
  103:     if (($symb) && (&Apache::lonnet::allowed('opa')) && ($target ne 'tex')) {
  104:        return "<a target='_top' href='/adm/parmset?symb=$symb&amp;filter=$filter&amp;part=$part'><span class='LC_setting'>$linktext</span></a>";
  105:     } else {
  106:        return $linktext;
  107:     }
  108: }
  109: ##############################################
  110: ##############################################
  111: 
  112: =item &confirm_success()
  113: 
  114: Successful completion of an operation message
  115: 
  116: =cut
  117: 
  118: sub confirm_success {
  119:    my ($message,$failure)=@_;
  120:    if ($failure) {
  121:       return '<span class="LC_error" style="font-size: inherit;">'."\n"
  122:             .'<img src="/adm/lonIcons/navmap.wrong.gif" alt="'.&mt('Error').'" /> '."\n"
  123:             .$message."\n"
  124:             .'</span>'."\n";
  125:    } else {
  126:       return '<span class="LC_success">'."\n"
  127:             .'<img src="/adm/lonIcons/navmap.correct.gif" alt="'.&mt('OK').'" /> '."\n"
  128:             .$message."\n"
  129:             .'</span>'."\n";
  130:    }
  131: }
  132: 
  133: ##############################################
  134: ##############################################
  135: 
  136: =pod
  137: 
  138: =item &dragmath_button()
  139: 
  140: Creates a button that launches a dragmath popup-window, in which an 
  141: expression can be edited and pasted as LaTeX into a specified textarea. 
  142: 
  143:   textarea - Name of the textarea to edit.
  144:   helpicon - If true, show a help icon to the right of the button.
  145: 
  146: =cut
  147: 
  148: sub dragmath_button {
  149:     my ($textarea,$helpicon) = @_;
  150:     my $help_text; 
  151:     if ($helpicon) {
  152:         $help_text = &Apache::loncommon::help_open_topic('Authoring_Math_Editor',undef,undef,undef,undef,'mathhelpicon_'.$textarea);
  153:     }
  154:     my $buttontext=&mt('Edit Math');
  155:     return <<ENDDRAGMATH;
  156:                 <input type="button" value="$buttontext" onclick="javascript:mathedit('$textarea',document)" />$help_text
  157: ENDDRAGMATH
  158: }
  159: 
  160: ##############################################
  161: 
  162: =pod
  163: 
  164: =item &dragmath_js()
  165: 
  166: Javascript used to open pop-up window containing dragmath applet which 
  167: can be used to paste LaTeX into a textarea.
  168: 
  169: =cut
  170: 
  171: sub dragmath_js {
  172:     my ($popup) = @_;
  173:     return <<ENDDRAGMATHJS;
  174:                 <script type="text/javascript">
  175:                 // <![CDATA[
  176:                   function mathedit(textarea, doc) {
  177:                      targetEntry = textarea;
  178:                      targetDoc   = doc;
  179:                      newwin  = window.open("/adm/dragmath/$popup.html","","width=565,height=500,resizable");
  180:                   }
  181:                 // ]]>
  182:                 </script>
  183: 
  184: ENDDRAGMATHJS
  185: }
  186: 
  187: ##############################################
  188: ##############################################
  189: 
  190: =pod
  191: 
  192: =item &dependencies_button()
  193: 
  194: Creates a button that launches a popup-window, in which dependencies  
  195: for the web page in the main window can be added to, replaced or deleted.  
  196: 
  197: =cut
  198: 
  199: sub dependencies_button {
  200:     my $buttontext=&mt('Manage Dependencies');
  201:     return <<"END";
  202:                 <input type="button" value="$buttontext" onclick="javascript:dependencycheck();" />
  203: END
  204: }
  205: 
  206: ##############################################
  207: 
  208: =pod
  209: 
  210: =item &dependencycheck_js()
  211: 
  212: Javascript used to open pop-up window containing interface to manage 
  213: dependencies for a web page uploaded diretcly to a course.
  214: 
  215: =cut
  216: 
  217: sub dependencycheck_js {
  218:     my ($symb,$title,$url,$folderpath,$uri) = @_;
  219:     my $link;
  220:     if ($symb) {
  221:         $link = '/adm/dependencies?symb='.&HTML::Entities::encode($symb,'<>&"');
  222:     } elsif ($folderpath) {
  223:         $link = '/adm/dependencies?folderpath='.&HTML::Entities::encode($folderpath,'<>&"');
  224:          $url = $uri;
  225:     } elsif ($uri =~ m{^/public/$match_domain/$match_courseid/syllabus$}) {
  226:         $link = '/adm/dependencies';
  227:     }
  228:     $link .= (($link=~/\?/)?'&amp;':'?').'title='.
  229:              &HTML::Entities::encode($title,'<>&"');
  230:     if ($url) {
  231:         $link .= '&url='.&HTML::Entities::encode($url,'<>&"');
  232:     }
  233:     return <<ENDJS;
  234:                 <script type="text/javascript">
  235:                 // <![CDATA[
  236:                   function dependencycheck() {
  237:                      depwin  = window.open("$link","","width=750,height=500,resizable,scrollbars=yes");
  238:                   }
  239:                 // ]]>
  240:                 </script>
  241: ENDJS
  242: }
  243: 
  244: ##############################################
  245: ##############################################
  246: 
  247: =pod
  248: 
  249: =item &authorbombs()
  250: 
  251: =cut
  252: 
  253: ##############################################
  254: ##############################################
  255: 
  256: sub authorbombs {
  257:     my $url=shift;
  258:     $url=&Apache::lonnet::declutter($url);
  259:     my ($udom,$uname)=($url=~m{^($LONCAPA::domain_re)/($LONCAPA::username_re)/});
  260:     my %bombs=&Apache::lonmsg::all_url_author_res_msg($uname,$udom);
  261:     foreach my $bomb (keys(%bombs)) {
  262: 	if ($bomb =~ /^$udom\/$uname\//) {
  263: 	    return '<a href="/adm/bombs/'.$url.
  264: 		'"><img src="'.&Apache::loncommon::lonhttpdurl('/adm/lonMisc/bomb.gif').'" alt="'.&mt('Bomb').'" border="0" /></a>'.
  265: 		&Apache::loncommon::help_open_topic('About_Bombs');
  266: 	}
  267:     }
  268:     return '';
  269: }
  270: 
  271: ##############################################
  272: ##############################################
  273: 
  274: sub recent_filename {
  275:     my $area=shift;
  276:     return 'nohist_recent_'.&escape($area);
  277: }
  278: 
  279: sub store_recent {
  280:     my ($area,$name,$value,$freeze)=@_;
  281:     my $file=&recent_filename($area);
  282:     my %recent=&Apache::lonnet::dump($file);
  283:     if (scalar(keys(%recent))>20) {
  284: # remove oldest value
  285: 	my $oldest=time();
  286: 	my $delkey='';
  287: 	foreach my $item (keys(%recent)) {
  288: 	    my $thistime=(split(/\&/,$recent{$item}))[0];
  289: 	    if (($thistime ne "always_include") && ($thistime<$oldest)) {
  290: 		$oldest=$thistime;
  291: 		$delkey=$item;
  292: 	    }
  293: 	}
  294: 	&Apache::lonnet::del($file,[$delkey]);
  295:     }
  296: # store new value
  297:     my $timestamp;
  298:     if ($freeze) {
  299:         $timestamp = "always_include";
  300:     } else {
  301:         $timestamp = time();
  302:     }   
  303:     &Apache::lonnet::put($file,{ $name => 
  304: 				 $timestamp.'&'.&escape($value) });
  305: }
  306: 
  307: sub remove_recent {
  308:     my ($area,$names)=@_;
  309:     my $file=&recent_filename($area);
  310:     return &Apache::lonnet::del($file,$names);
  311: }
  312: 
  313: sub select_recent {
  314:     my ($area,$fieldname,$event)=@_;
  315:     my %recent=&Apache::lonnet::dump(&recent_filename($area));
  316:     my $return="\n<select name='$fieldname'".
  317: 	($event?" onchange='$event'":'').
  318: 	">\n<option value=''>--- ".&mt('Recent')." ---</option>";
  319:     foreach my $value (sort(keys(%recent))) {
  320: 	unless ($value =~/^error\:/) {
  321: 	    my $escaped = &Apache::loncommon::escape_url($value);
  322: 	    &Apache::loncommon::inhibit_menu_check(\$escaped);
  323:             if ($area eq 'residx') {
  324:                 next if ((!&Apache::lonnet::allowed('bre',$value)) && (!&Apache::lonnet::allowed('bro',$value)));
  325:             }
  326: 	    $return.="\n<option value='$escaped'>".
  327: 		&unescape((split(/\&/,$recent{$value}))[1]).
  328: 		'</option>';
  329: 	}
  330:     }
  331:     $return.="\n</select>\n";
  332:     return $return;
  333: }
  334: 
  335: sub get_recent {
  336:     my ($area, $n) = @_;
  337:     my %recent=&Apache::lonnet::dump(&recent_filename($area));
  338: 
  339: # Create hash with key as time and recent as value
  340: # Begin filling return_hash with any 'always_include' option
  341:     my %time_hash = ();
  342:     my %return_hash = ();
  343:     foreach my $item (keys(%recent)) {
  344:         my ($thistime,$thisvalue)=(split(/\&/,$recent{$item}));
  345:         if ($thistime eq 'always_include') {
  346:             $return_hash{$item} = &unescape($thisvalue);
  347:             $n--;
  348:         } else {
  349:             $time_hash{$thistime} = $item;
  350:         }
  351:     }
  352: 
  353: # Sort by decreasing time and return key value pairs
  354:     my $idx = 1;
  355:     foreach my $item (reverse(sort(keys(%time_hash)))) {
  356:        $return_hash{$time_hash{$item}} =
  357:                   &unescape((split(/\&/,$recent{$time_hash{$item}}))[1]);
  358:        if ($n && ($idx++ >= $n)) {last;}
  359:     }
  360: 
  361:     return %return_hash;
  362: }
  363: 
  364: sub get_recent_frozen {
  365:     my ($area) = @_;
  366:     my %recent=&Apache::lonnet::dump(&recent_filename($area));
  367: 
  368: # Create hash with all 'frozen' items
  369:     my %return_hash = ();
  370:     foreach my $item (keys(%recent)) {
  371:         my ($thistime,$thisvalue)=(split(/\&/,$recent{$item}));
  372:         if ($thistime eq 'always_include') {
  373:             $return_hash{$item} = &unescape($thisvalue);
  374:         }
  375:     }
  376:     return %return_hash;
  377: }
  378: 
  379: 
  380: 
  381: =pod
  382: 
  383: =item &textbox()
  384: 
  385: =cut
  386: 
  387: ##############################################
  388: ##############################################
  389: sub textbox {
  390:     my ($name,$value,$size,$special) = @_;
  391:     $size = 40 if (! defined($size));
  392:     $value = &HTML::Entities::encode($value,'<>&"');
  393:     my $Str = '<input type="text" name="'.$name.'" size="'.$size.'" '.
  394:         'value="'.$value.'" '.$special.' />';
  395:     return $Str;
  396: }
  397: 
  398: ##############################################
  399: ##############################################
  400: 
  401: =pod
  402: 
  403: =item &checkbox()
  404: 
  405: =cut
  406: 
  407: ##############################################
  408: ##############################################
  409: sub checkbox {
  410:     my ($name,$checked,$value) = @_;
  411:     my $Str = '<input type="checkbox" name="'.$name.'" ';
  412:     if (defined($value)) {
  413:         $Str .= 'value="'.$value.'"';
  414:     } 
  415:     if ($checked) {
  416:         $Str .= ' checked="checked"';
  417:     }
  418:     $Str .= ' />';
  419:     return $Str;
  420: }
  421: 
  422: 
  423: =pod
  424: 
  425: =item &radiobutton()
  426: 
  427: =cut
  428: 
  429: ##############################################
  430: ##############################################
  431: sub radio {
  432:     my ($name,$checked,$value) = @_;
  433:     my $Str = '<input type="radio" name="'.$name.'" ';
  434:     if (defined($value)) {
  435:         $Str .= 'value="'.$value.'"';
  436:     } 
  437:     if ($checked eq $value) {
  438:         $Str .= ' checked="checked"';
  439:     }
  440:     $Str .= ' />';
  441:     return $Str;
  442: }
  443: 
  444: ##############################################
  445: ##############################################
  446: 
  447: =pod
  448: 
  449: =item &date_setter()
  450: 
  451: &date_setter returns html and javascript for a compact date-setting form.
  452: To retrieve values from it, use &get_date_from_form.
  453: 
  454: Inputs
  455: 
  456: =over 4
  457: 
  458: =item $dname 
  459: 
  460: The name to prepend to the form elements.  
  461: The form elements defined will be dname_year, dname_month, dname_day,
  462: dname_hour, dname_min, and dname_sec.
  463: 
  464: =item $currentvalue
  465: 
  466: The current setting for this time parameter.  A unix format time
  467: (time in seconds since the beginning of Jan 1st, 1970, GMT.  
  468: An undefined value is taken to indicate the value is the current time
  469: unless it is requested to leave it empty. See $includeempty.
  470: Also, to be explicit, a value of 'now' also indicates the current time.
  471: 
  472: =item $special
  473: 
  474: Additional html/javascript to be associated with each element in
  475: the date_setter.  See lonparmset for example usage.
  476: 
  477: =item $includeempty 
  478: 
  479: If it is set (true) and no date/time value is provided,
  480: the date/time fields are left empty.
  481: 
  482: =item $state
  483: 
  484: Specifies the initial state of the form elements.  Either 'disabled' or empty.
  485: Defaults to empty, which indiciates the form elements are not disabled. 
  486: 
  487: =back
  488: 
  489: Bugs
  490: 
  491: The method used to restrict user input will fail in the year 2400.
  492: 
  493: =cut
  494: 
  495: ##############################################
  496: ##############################################
  497: sub date_setter {
  498:     my ($formname,$dname,$currentvalue,$special,$includeempty,$state,
  499:         $no_hh_mm_ss,$defhour,$defmin,$defsec,$nolink) = @_;
  500:     my $now = time;
  501: 
  502:     my $tzname;
  503:     my ($sec,$min,$hour,$mday,$month,$year) = ('', '', undef,''.''.'');
  504:     #other potentially useful values:    wkday,yrday,is_daylight_savings
  505: 
  506:     if (! defined($state) || $state ne 'disabled') {
  507:         $state = '';
  508:     }
  509:     if (! defined($no_hh_mm_ss)) {
  510:         $no_hh_mm_ss = 0;
  511:     }
  512:     if ($currentvalue eq 'now') {
  513:         $currentvalue = $now;
  514:     }
  515:     
  516:     # Default value: Set empty date field to current time
  517:     # unless empty inclusion is requested
  518:     if ((!$includeempty) && (!$currentvalue)) {
  519:         $currentvalue = $now;
  520:     }
  521:     # Do we have a date? Split it!
  522:     if ($currentvalue) {
  523: 	($tzname,$sec,$min,$hour,$mday,$month,$year) = &get_timedates($currentvalue);
  524: 
  525:         #No values provided for hour, min, sec? Use default 0
  526:         if (($defhour) || ($defmin) || ($defsec)) {
  527:             $sec  = ($defsec  ? $defsec  : 0);
  528:             $min  = ($defmin  ? $defmin  : 0);
  529:             $hour = ($defhour ? $defhour : 0);
  530:         }
  531:     }
  532:     my $result = "\n<!-- $dname date setting form -->\n";
  533:     $result .= <<ENDJS;
  534: <script type="text/javascript">
  535: // <![CDATA[
  536:     function $dname\_checkday() {
  537:         var day   = document.$formname.$dname\_day.value;
  538:         var month = document.$formname.$dname\_month.value;
  539:         var year  = document.$formname.$dname\_year.value;
  540:         var valid = true;
  541:         if (day < 1) {
  542:             document.$formname.$dname\_day.value = 1;
  543:         } 
  544:         if (day > 31) {
  545:             document.$formname.$dname\_day.value = 31;
  546:         }
  547:         if ((month == 1)  || (month == 3)  || (month == 5)  ||
  548:             (month == 7)  || (month == 8)  || (month == 10) ||
  549:             (month == 12)) {
  550:             if (day > 31) {
  551:                 document.$formname.$dname\_day.value = 31;
  552:                 day = 31;
  553:             }
  554:         } else if (month == 2 ) {
  555:             if ((year % 4 == 0) && (year % 100 != 0)) {
  556:                 if (day > 29) {
  557:                     document.$formname.$dname\_day.value = 29;
  558:                 }
  559:             } else if (day > 29) {
  560:                 document.$formname.$dname\_day.value = 28;
  561:             }
  562:         } else if (day > 30) {
  563:             document.$formname.$dname\_day.value = 30;
  564:         }
  565:     }
  566:     
  567:     function $dname\_disable() {
  568:         document.$formname.$dname\_month.disabled=true;
  569:         document.$formname.$dname\_day.disabled=true;
  570:         document.$formname.$dname\_year.disabled=true;
  571:         document.$formname.$dname\_hour.disabled=true;
  572:         document.$formname.$dname\_minute.disabled=true;
  573:         document.$formname.$dname\_second.disabled=true;
  574:     }
  575: 
  576:     function $dname\_enable() {
  577:         document.$formname.$dname\_month.disabled=false;
  578:         document.$formname.$dname\_day.disabled=false;
  579:         document.$formname.$dname\_year.disabled=false;
  580:         document.$formname.$dname\_hour.disabled=false;
  581:         document.$formname.$dname\_minute.disabled=false;
  582:         document.$formname.$dname\_second.disabled=false;        
  583:     }
  584: 
  585:     function $dname\_opencalendar() {
  586:         if (! document.$formname.$dname\_month.disabled) {
  587:             var calwin=window.open(
  588: "/adm/announcements?pickdate=yes&formname=$formname&element=$dname&month="+
  589: document.$formname.$dname\_month.value+"&year="+
  590: document.$formname.$dname\_year.value,
  591:              "LONCAPAcal",
  592:               "height=350,width=350,scrollbars=yes,resizable=yes,menubar=no");
  593:         }
  594: 
  595:     }
  596: // ]]>
  597: </script>
  598: ENDJS
  599:     $result .= '  <span class="LC_nobreak">';
  600:     my $monthselector = qq{<select name="$dname\_month" $special $state onchange="javascript:$dname\_checkday()" >};
  601:     # Month
  602:     my @Months = qw/January February  March     April   May      June 
  603:                     July    August    September October November December/;
  604:     # Pad @Months with a bogus value to make indexing easier
  605:     unshift(@Months,'If you can read this an error occurred');
  606:     if ($includeempty) { $monthselector.="<option value=''></option>"; }
  607:     for(my $m = 1;$m <=$#Months;$m++) {
  608:         $monthselector .= qq{      <option value="$m"};
  609:         $monthselector .= ' selected="selected"' if ($m-1 eq $month);
  610:         $monthselector .= '> '.&mt($Months[$m]).' </option>'."\n";
  611:     }
  612:     $monthselector.= '  </select>';
  613:     # Day
  614:     my $dayselector = qq{<input type="text" name="$dname\_day" $state value="$mday" size="3" $special onchange="javascript:$dname\_checkday()" />};
  615:     # Year
  616:     my $yearselector = qq{<input type="text" name="$dname\_year" $state value="$year" size="5" $special onchange="javascript:$dname\_checkday()" />};
  617:     #
  618:     my $hourselector = qq{<select name="$dname\_hour" $special $state >};
  619:     if ($includeempty) { 
  620:         $hourselector.=qq{<option value=''></option>};
  621:     }
  622:     for (my $h = 0;$h<24;$h++) {
  623:         $hourselector .= qq{<option value="$h"};
  624:         $hourselector .= ' selected="selected"' if (defined($hour) && $hour == $h);
  625:         $hourselector .= ">";
  626:         my $timest='';
  627:         if ($h == 0) {
  628:             $timest .= "12 am";
  629:         } elsif($h == 12) {
  630:             $timest .= "12 noon";
  631:         } elsif($h < 12) {
  632:             $timest .= "$h am";
  633:         } else {
  634:             $timest .= $h-12 ." pm";
  635:         }
  636:         $timest=&mt($timest);
  637:         $hourselector .= $timest." </option>\n";
  638:     }
  639:     $hourselector .= "  </select>\n";
  640:     my $minuteselector = qq{<input type="text" name="$dname\_minute" $special $state value="$min" size="3" />};
  641:     my $secondselector= qq{<input type="text" name="$dname\_second" $special $state value="$sec" size="3" />};
  642:     my $cal_link;
  643:     if (!$nolink) {
  644:         $cal_link = qq{<a href="javascript:$dname\_opencalendar()">};
  645:     }
  646:     #
  647:     my $tzone = ' '.$tzname.' ';
  648:     if ($no_hh_mm_ss) {
  649:         $result .= &mt('[_1] [_2] [_3] ',
  650:                        $monthselector,$dayselector,$yearselector).
  651:                    $tzone;
  652:         if (!$nolink) {
  653:             $result .= &mt('[_1]Select Date[_2]',$cal_link,'</a>');
  654:         }
  655:     } else {
  656:         $result .= &mt('[_1] [_2] [_3] [_4] [_5]m [_6]s ',
  657:                       $monthselector,$dayselector,$yearselector,
  658:                       $hourselector,$minuteselector,$secondselector).
  659:                    $tzone;
  660:         if (!$nolink) {
  661:             $result .= &mt('[_1]Select Date[_2]',$cal_link,'</a>');
  662:         }
  663:     }
  664:     $result .= "</span>\n<!-- end $dname date setting form -->\n";
  665:     return $result;
  666: }
  667: 
  668: sub get_timedates {
  669:     my ($epoch) = @_;
  670:     my $dt = DateTime->from_epoch(epoch => $epoch)
  671:                      ->set_time_zone(&Apache::lonlocal::gettimezone());
  672:     my $tzname = $dt->time_zone_short_name();
  673:     my $sec = $dt->second;
  674:     my $min = $dt->minute;
  675:     my $hour = $dt->hour;
  676:     my $mday = $dt->day;
  677:     my $month = $dt->month;
  678:     if ($month) {
  679:         $month --;
  680:     }
  681:     my $year = $dt->year;
  682:     return ($tzname,$sec,$min,$hour,$mday,$month,$year);
  683: }
  684: 
  685: sub build_url {
  686:     my ($base, $fields)=@_;
  687:     my $url;
  688:     $url = $base.'?';
  689:     foreach my $key (keys(%$fields)) {
  690:         $url.=&escape($key).'='.&escape($$fields{$key}).'&amp;';
  691:     }
  692:     $url =~ s/&amp;$//;
  693:     return $url;
  694: }
  695: 
  696: 
  697: ##############################################
  698: ##############################################
  699: 
  700: =pod
  701: 
  702: =item &get_date_from_form()
  703: 
  704: get_date_from_form retrieves the date specified in an &date_setter form.
  705: 
  706: Inputs:
  707: 
  708: =over 4
  709: 
  710: =item $dname
  711: 
  712: The name passed to &date_setter, which prefixes the form elements.
  713: 
  714: =item $defaulttime
  715: 
  716: The unix time to use as the default in case of poor inputs.
  717: 
  718: =back
  719: 
  720: Returns: Unix time represented in the form.
  721: 
  722: =cut
  723: 
  724: ##############################################
  725: ##############################################
  726: sub get_date_from_form {
  727:     my ($dname) = @_;
  728:     my ($sec,$min,$hour,$day,$month,$year);
  729:     #
  730:     if (defined($env{'form.'.$dname.'_second'})) {
  731:         my $tmpsec = $env{'form.'.$dname.'_second'};
  732:         if (($tmpsec =~ /^\d+$/) && ($tmpsec >= 0) && ($tmpsec < 60)) {
  733:             $sec = $tmpsec;
  734:         }
  735: 	if (!defined($tmpsec) || $tmpsec eq '') { $sec = 0; }
  736:     } else {
  737:         $sec = 0;
  738:     }
  739:     if (defined($env{'form.'.$dname.'_minute'})) {
  740:         my $tmpmin = $env{'form.'.$dname.'_minute'};
  741:         if (($tmpmin =~ /^\d+$/) && ($tmpmin >= 0) && ($tmpmin < 60)) {
  742:             $min = $tmpmin;
  743:         }
  744: 	if (!defined($tmpmin) || $tmpmin eq '') { $min = 0; }
  745:     } else {
  746:         $min = 0;
  747:     }
  748:     if (defined($env{'form.'.$dname.'_hour'})) {
  749:         my $tmphour = $env{'form.'.$dname.'_hour'};
  750:         if (($tmphour =~ /^\d+$/) && ($tmphour >= 0) && ($tmphour < 24)) {
  751:             $hour = $tmphour;
  752:         }
  753:     } else {
  754:         $hour = 0;
  755:     }
  756:     if (defined($env{'form.'.$dname.'_day'})) {
  757:         my $tmpday = $env{'form.'.$dname.'_day'};
  758:         if (($tmpday =~ /^\d+$/) && ($tmpday > 0) && ($tmpday < 32)) {
  759:             $day = $tmpday;
  760:         }
  761:     }
  762:     if (defined($env{'form.'.$dname.'_month'})) {
  763:         my $tmpmonth = $env{'form.'.$dname.'_month'};
  764:         if (($tmpmonth =~ /^\d+$/) && ($tmpmonth > 0) && ($tmpmonth < 13)) {
  765:             $month = $tmpmonth;
  766:         }
  767:     }
  768:     if (defined($env{'form.'.$dname.'_year'})) {
  769:         my $tmpyear = $env{'form.'.$dname.'_year'};
  770:         if (($tmpyear =~ /^\d+$/) && ($tmpyear >= 1970)) {
  771:             $year = $tmpyear;
  772:         }
  773:     }
  774:     if (($year<1970) || ($year>2037)) { return undef; }
  775:     if (defined($sec) && defined($min)   && defined($hour) &&
  776:         defined($day) && defined($month) && defined($year)) {
  777:         my $timezone = &Apache::lonlocal::gettimezone();
  778:         my $dt = DateTime->new( year   => $year,
  779:                                 month  => $month,
  780:                                 day    => $day,
  781:                                 hour   => $hour,
  782:                                 minute => $min,
  783:                                 second => $sec,
  784:                                 time_zone => $timezone,
  785:                               );
  786:         my $epoch_time  = $dt->epoch;
  787:         if ($epoch_time ne '') {
  788:             return $epoch_time;
  789:         } else {
  790:             return undef;
  791:         }
  792:     } else {
  793:         return undef;
  794:     }
  795: }
  796: 
  797: ##############################################
  798: ##############################################
  799: 
  800: =pod
  801: 
  802: =item &pjump_javascript_definition()
  803: 
  804: Returns javascript defining the 'pjump' function, which opens up a
  805: parameter setting wizard.
  806: 
  807: =cut
  808: 
  809: ##############################################
  810: ##############################################
  811: sub pjump_javascript_definition {
  812:     my $Str = <<END;
  813:     function pjump(type,dis,value,marker,ret,call,hour,min,sec) {
  814:         openMyModal("/adm/rat/parameter.html?type="+escape(type)
  815:                  +"&value="+escape(value)+"&marker="+escape(marker)
  816:                  +"&return="+escape(ret)
  817:                  +"&call="+escape(call)+"&name="+escape(dis)
  818:                  +"&defhour="+escape(hour)+"&defmin="+escape(min)
  819:                  +"&defsec="+escape(sec)+"&modal=1",350,350,'no');
  820:     }
  821: END
  822:     return $Str;
  823: }
  824: 
  825: ##############################################
  826: ##############################################
  827: 
  828: =pod
  829: 
  830: =item &javascript_nothing()
  831: 
  832: Return an appropriate null for the users browser.  This is used
  833: as the first arguement for window.open calls when you want a blank
  834: window that you can then write to.
  835: 
  836: =cut
  837: 
  838: ##############################################
  839: ##############################################
  840: sub javascript_nothing {
  841:     # mozilla and other browsers work with "''", but IE on mac does not.
  842:     my $nothing = "''";
  843:     my $user_browser;
  844:     my $user_os;
  845:     $user_browser = $env{'browser.type'} if (exists($env{'browser.type'}));
  846:     $user_os      = $env{'browser.os'}   if (exists($env{'browser.os'}));
  847:     if (! defined($user_browser) || ! defined($user_os)) {
  848:         (undef,$user_browser,undef,undef,undef,$user_os) = 
  849:                            &Apache::loncommon::decode_user_agent();
  850:     }
  851:     if ($user_browser eq 'explorer' && $user_os =~ 'mac') {
  852:         $nothing = "'javascript:void(0);'";
  853:     }
  854:     return $nothing;
  855: }
  856: 
  857: ##############################################
  858: ##############################################
  859: sub javascript_docopen {
  860:     my ($mimetype) = @_;
  861:     $mimetype ||= 'text/html';
  862:     # safari does not understand document.open() and loads "text/html"
  863:     my $nothing = "''";
  864:     my $user_browser;
  865:     my $user_os;
  866:     $user_browser = $env{'browser.type'} if (exists($env{'browser.type'}));
  867:     $user_os      = $env{'browser.os'}   if (exists($env{'browser.os'}));
  868:     if (! defined($user_browser) || ! defined($user_os)) {
  869:         (undef,$user_browser,undef,undef,undef,$user_os) = 
  870:                            &Apache::loncommon::decode_user_agent();
  871:     }
  872:     if ($user_browser eq 'safari' && $user_os =~ 'mac') {
  873:         $nothing = "document.clear()";
  874:     } else {
  875: 	$nothing = "document.open('$mimetype','replace')";
  876:     }
  877:     return $nothing;
  878: }
  879: 
  880: 
  881: ##############################################
  882: ##############################################
  883: 
  884: =pod
  885: 
  886: =item &StatusOptions()
  887: 
  888: Returns html for a selection box which allows the user to choose the
  889: enrollment status of students.  The selection box name is 'Status'.
  890: 
  891: Inputs:
  892: 
  893: $status: the currently selected status.  If undefined the value of
  894: $env{'form.Status'} is taken.  If that is undefined, a value of 'Active'
  895: is used.
  896: 
  897: $formname: The name of the form.  If defined the onchange attribute of
  898: the selection box is set to document.$formname.submit().
  899: 
  900: $size: the size (number of lines) of the selection box.
  901: 
  902: $onchange: javascript to use when the value is changed.  Enclosed in 
  903: double quotes, ""s, not single quotes.
  904: 
  905: Returns: a perl string as described.
  906: 
  907: =cut
  908: 
  909: ##############################################
  910: ##############################################
  911: sub StatusOptions {
  912:     my ($status, $formName,$size,$onchange,$mult)=@_;
  913:     $size = 1 if (!defined($size));
  914:     if (! defined($status)) {
  915:         $status = 'Active';
  916:         $status = $env{'form.Status'} if (exists($env{'form.Status'}));
  917:     }
  918: 
  919:     my $Str = '';
  920:     $Str .= '<select name="Status"';
  921:     if (defined($mult)){
  922:         $Str .= ' multiple="multiple" ';
  923:     }
  924:     if(defined($formName) && $formName ne '' && ! defined($onchange)) {
  925:         $Str .= ' onchange="document.'.$formName.'.submit()"';
  926:     }
  927:     if (defined($onchange)) {
  928:         $Str .= ' onchange="'.$onchange.'"';
  929:     }
  930:     $Str .= ' size="'.$size.'" ';
  931:     $Str .= '>'."\n";
  932:     foreach my $type (['Active',  &mt('Currently Has Access')],
  933: 		      ['Future',  &mt('Will Have Future Access')],
  934: 		      ['Expired', &mt('Previously Had Access')],
  935: 		      ['Any',     &mt('Any Access Status')]) {
  936: 	my ($name,$label) = @$type;
  937: 	$Str .= '<option value="'.$name.'" ';
  938: 	if ($status eq $name) {
  939: 	    $Str .= 'selected="selected" ';
  940: 	}
  941: 	$Str .= '>'.$label.'</option>'."\n";
  942:     }
  943: 
  944:     $Str .= '</select>'."\n";
  945: }
  946: 
  947: ########################################################
  948: ########################################################
  949: 
  950: =pod
  951: 
  952: =item Progess Window Handling Routines
  953: 
  954: These routines handle the creation, update, increment, and closure of 
  955: progress windows.  The progress window reports to the user the number
  956: of items completed and an estimate of the time required to complete the rest.
  957: 
  958: =over 4
  959: 
  960: 
  961: =item &Create_PrgWin()
  962: 
  963: Writes javascript to the client to open a progress window and returns a
  964: data structure used for bookkeeping.
  965: 
  966: Inputs
  967: 
  968: =over 4
  969: 
  970: =item $r Apache request
  971: 
  972: =item $number_to_do The total number of items being processed.
  973: 
  974: =back
  975: 
  976: Returns a hash containing the progress state data structure.
  977: 
  978: 
  979: =item &Update_PrgWin()
  980: 
  981: Updates the text in the progress indicator.  Does not increment the count.
  982: See &Increment_PrgWin.
  983: 
  984: Inputs:
  985: 
  986: =over 4
  987: 
  988: =item $r Apache request
  989: 
  990: =item $prog_state Pointer to the data structure returned by &Create_PrgWin
  991: 
  992: =item $displaystring The string to write to the status indicator
  993: 
  994: =back
  995: 
  996: Returns: none
  997: 
  998: 
  999: =item Increment_PrgWin()
 1000: 
 1001: Increment the count of items completed for the progress window by $step or 1 if no step is provided.
 1002: 
 1003: Inputs:
 1004: 
 1005: =over 4
 1006: 
 1007: =item $r Apache request
 1008: 
 1009: =item $prog_state Pointer to the data structure returned by Create_PrgWin
 1010: 
 1011: =item $extraInfo A description of the items being iterated over.  Typically
 1012: 'student'.
 1013: 
 1014: =item $step (optional) counter step. Will be set to default 1 if ommited. step must be greater than 0 or empty.
 1015: 
 1016: =back
 1017: 
 1018: Returns: none
 1019: 
 1020: 
 1021: =item &Close_PrgWin()
 1022: 
 1023: Closes the progress window.
 1024: 
 1025: Inputs:
 1026: 
 1027: =over 4 
 1028: 
 1029: =item $r Apache request
 1030: 
 1031: =item $prog_state Pointer to the data structure returned by Create_PrgWin
 1032: 
 1033: =back
 1034: 
 1035: Returns: none
 1036: 
 1037: =back
 1038: 
 1039: =cut
 1040: 
 1041: ########################################################
 1042: ########################################################
 1043: 
 1044: 
 1045: # Create progress
 1046: sub Create_PrgWin {
 1047:     my ($r,$number_to_do)=@_;
 1048:     my %prog_state;
 1049:     $prog_state{'done'}=0;
 1050:     $prog_state{'firststart'}=&Time::HiRes::time();
 1051:     $prog_state{'laststart'}=&Time::HiRes::time();
 1052:     $prog_state{'max'}=$number_to_do;
 1053:     &Apache::loncommon::LCprogressbar($r); 
 1054:     return %prog_state;
 1055: }
 1056: 
 1057: # update progress
 1058: sub Update_PrgWin {
 1059:     my ($r,$prog_state,$displayString)=@_;
 1060:     &Apache::loncommon::LCprogressbarUpdate($r,undef,$displayString);
 1061:     $$prog_state{'laststart'}=&Time::HiRes::time();
 1062: }
 1063: 
 1064: # increment progress state
 1065: sub Increment_PrgWin {
 1066:     my ($r,$prog_state,$extraInfo,$step)=@_;
 1067:     $step = $step > 0 ? $step : 1;
 1068:     $$prog_state{'done'} += $step;
 1069: 
 1070:     # Catch (max modulo step) <> 0
 1071:     my $current = $$prog_state{'done'};
 1072:     my $last = ($$prog_state{'max'} - $current);
 1073:     if ($last <= 0) {
 1074:         $last = 1;
 1075:         $current = $$prog_state{'max'};
 1076:     }
 1077: 
 1078:     my $time_est= (&Time::HiRes::time() - $$prog_state{'firststart'})/
 1079:         $current * $last;
 1080:     $time_est = int($time_est);
 1081:     #
 1082:     my $min = int($time_est/60);
 1083:     my $sec = $time_est % 60;
 1084: 
 1085:     my $lasttime = &Time::HiRes::time()-$$prog_state{'laststart'};
 1086:     if ($lasttime > 9) {
 1087:         $lasttime = int($lasttime);
 1088:     } elsif ($lasttime < 0.01) {
 1089:         $lasttime = 0;
 1090:     } else {
 1091:         $lasttime = sprintf("%3.2f",$lasttime);
 1092:     }
 1093: 
 1094:     $sec = 0 if ($min >= 10); # Don't show seconds if remaining time >= 10 min.
 1095:     $sec = 1 if ( ($min == 0) && ($sec == 0) ); # Little cheating: pretend to have 1 second remaining instead of 0 to have something to display
 1096: 
 1097:     my $timeinfo =
 1098:         &mt('[_1]/[_2]:'
 1099:            .' [quant,_3,minute,minutes,] [quant,_4,second ,seconds ,]remaining'
 1100:            .' ([quant,_5,second] for '.$extraInfo.')',
 1101:             $current,
 1102:             $$prog_state{'max'},
 1103:             $min,
 1104:             $sec,
 1105:             $lasttime);
 1106:     my $percent=0;
 1107:     if ($$prog_state{'max'}) {
 1108:        $percent=int(100.*$current/$$prog_state{'max'});
 1109:     }
 1110:     &Apache::loncommon::LCprogressbarUpdate($r,$percent,$timeinfo);
 1111:     $$prog_state{'laststart'}=&Time::HiRes::time();
 1112: }
 1113: 
 1114: # close Progress Line
 1115: sub Close_PrgWin {
 1116:     my ($r,$prog_state)=@_;
 1117:     &Apache::loncommon::LCprogressbarClose($r);
 1118:     undef(%$prog_state);
 1119: }
 1120: 
 1121: 
 1122: # ------------------------------------------------------- Puts directory header
 1123: 
 1124: sub crumbs {
 1125:     my ($uri,$target,$prefix,$form,$skiplast)=@_;
 1126: # You cannot crumbnify uploaded or adm resources
 1127:     if ($uri=~/^\/*(uploaded|adm)\//) { return &mt('(Internal Course/Group Content)'); }
 1128:     if ($target) {
 1129:         $target = ' target="'.
 1130:                   &Apache::loncommon::escape_single($target).'"';
 1131:     }
 1132:     my $output='<span class="LC_filename">';
 1133:     $output.=$prefix.'/';
 1134:     if (($env{'user.adv'}) || ($env{'user.author'})) {
 1135:         my $path=$prefix.'/';
 1136:         foreach my $dir (split('/',$uri)) {
 1137:             if (! $dir) { next; }
 1138:             $path .= $dir;
 1139:             if ($path eq $uri) {
 1140:                 if ($skiplast) {
 1141:                     $output.=$dir;
 1142:                     last;
 1143:                 } 
 1144:             } else {
 1145:                 $path.='/'; 
 1146:             }
 1147:             my $href_path = &HTML::Entities::encode($path,'<>&"');
 1148:             &Apache::loncommon::inhibit_menu_check(\$href_path);
 1149:             if ($form) {
 1150:                 my $href = 'javascript:'.$form.".action='".$href_path."';".$form.'.submit();';
 1151:                 $output.=qq{<a href="$href"$target>$dir</a>/};
 1152:             } else {
 1153:                 $output.=qq{<a href="$href_path"$target>$dir</a>/};
 1154:             }
 1155:         }
 1156:     } else {
 1157:         foreach my $dir (split('/',$uri)) {
 1158:             if (! $dir) { next; }
 1159:             $output.=$dir.'/';
 1160:         }
 1161:     }
 1162:     if ($uri !~ m|/$|) { $output=~s|/$||; }
 1163:     $output.='</span>';
 1164: 
 1165: 
 1166:     return $output;
 1167: }
 1168: 
 1169: # --------------------- A function that generates a window for the spellchecker
 1170: 
 1171: sub spellheader {
 1172:     my $start_page=
 1173: 	&Apache::loncommon::start_page('Speller Suggestions',undef,
 1174: 				       {'only_body'   => 1,
 1175: 					'js_ready'    => 1,
 1176: 					'bgcolor'     => '#DDDDDD',
 1177: 				        'add_entries' => {
 1178: 					    'onload' => 
 1179:                                                'document.forms.spellcheckform.submit()',
 1180:                                              }
 1181: 				        });
 1182:     my $end_page=
 1183: 	&Apache::loncommon::end_page({'js_ready'  => 1}); 
 1184: 
 1185:     my $nothing=&javascript_nothing();
 1186:     return (<<ENDCHECK);
 1187: <script type="text/javascript"> 
 1188: // <![CDATA[
 1189: //<!-- BEGIN LON-CAPA Internal
 1190: var checkwin;
 1191: 
 1192: function spellcheckerwindow(string) {
 1193:     var esc_string = string.replace(/\"/g,'&quot;');
 1194:     checkwin=window.open($nothing,'spellcheckwin','height=320,width=280,resizable=yes,scrollbars=yes,location=no,menubar=no,toolbar=no');
 1195:     checkwin.document.writeln('$start_page<form name="spellcheckform" action="/adm/spellcheck" method="post"><input type="hidden" name="text" value="'+esc_string+'" /><\\/form>$end_page');
 1196:     checkwin.document.close();
 1197: }
 1198: // END LON-CAPA Internal -->
 1199: // ]]>
 1200: </script>
 1201: ENDCHECK
 1202: }
 1203: 
 1204: # ---------------------------------- Generate link to spell checker for a field
 1205: 
 1206: sub spelllink {
 1207:     my ($form,$field)=@_;
 1208:     my $linktext=&mt('Check Spelling');
 1209:     return (<<ENDLINK);
 1210: <a href="javascript:if (typeof(document.$form.onsubmit)!='undefined') { if (document.$form.onsubmit!=null) { document.$form.onsubmit();}};spellcheckerwindow(this.document.forms.$form.$field.value);">$linktext</a>
 1211: ENDLINK
 1212: }
 1213: 
 1214: # ------------------------------------------------- Output headers for CKEditor
 1215: 
 1216: sub htmlareaheaders {
 1217: 	my $s="";
 1218: 	if (&htmlareabrowser()) {
 1219: 		$s.=(<<ENDEDITOR);
 1220: <script type="text/javascript" src="/ckeditor/ckeditor.js"></script>
 1221: ENDEDITOR
 1222: 	}
 1223:     $s.=(<<ENDJQUERY);
 1224: <script type="text/javascript" src="/adm/jQuery/js/jquery-1.6.2.min.js"></script>
 1225: <script type="text/javascript" src="/adm/jQuery/js/jquery-ui-1.8.16.custom.min.js"></script>
 1226: <link rel="stylesheet" type="text/css" href="/adm/jQuery/css/smoothness/jquery-ui-1.8.16.custom.css" />
 1227: <script type="text/javascript" src="/adm/jpicker/js/jpicker-1.1.6.min.js" >
 1228: </script>
 1229: <link rel="stylesheet" type="text/css" href="/adm/jpicker/css/jPicker-1.1.6.min.css" />
 1230: <script type="text/javascript" src="/adm/countdown/js/jquery.countdown.min.js"></script>
 1231: <link rel="stylesheet" type="text/css" href="/adm/countdown/css/jquery.countdown.css" />
 1232: 
 1233: <script type="text/javascript" src="/adm/spellchecker/js/jquery.spellchecker.min.js"></script>
 1234: <link rel="stylesheet" type="text/css" href="/adm/spellchecker/css/spellchecker.css" />
 1235: <script type="text/javascript" src="/adm/nicescroll/jquery.nicescroll.min.js"></script>
 1236: 
 1237: ENDJQUERY
 1238: 	return $s;
 1239: }
 1240: 
 1241: # ----------------------------------------------------------------- Preferences
 1242: 
 1243: # ------------------------------------------------- lang to use in html editor
 1244: sub htmlarea_lang {
 1245:     my $lang='en';
 1246:     if (&mt('htmlarea_lang') ne 'htmlarea_lang') {
 1247: 	$lang=&mt('htmlarea_lang');
 1248:     }
 1249:     return $lang;
 1250: }
 1251: 
 1252: # return javacsript to activate elements of .colorchooser with jpicker:
 1253: # Caller is responsible for enclosing this in <script> tags:
 1254: #
 1255: sub color_picker {
 1256:     return '
 1257: $(document).ready(function(){
 1258:     $.fn.jPicker.defaults.images.clientPath="/adm/jpicker/images/";
 1259:     $(".colorchooser").jPicker({window: { position: {x: "screenCenter", y: "bottom"}}});
 1260: });';
 1261: }
 1262: 
 1263: # ----------------------------------------- Script to activate only some fields
 1264: 
 1265: sub htmlareaselectactive {
 1266:     my ($args) = @_; 
 1267:     unless (&htmlareabrowser()) { return ''; }
 1268:     my $output='<script type="text/javascript" defer="defer">'."\n"
 1269:               .'// <![CDATA['."\n"
 1270:               .'//<!-- BEGIN LON-CAPA Internal'."\n";
 1271:     my $lang = &htmlarea_lang();
 1272:     my $fullpage = 'false';
 1273:     my ($dragmath_prefix,$dragmath_helpicon,$dragmath_whitespace);
 1274:     if (ref($args) eq 'HASH') {
 1275:         if (exists($args->{'lang'})) {
 1276:             if ($args->{'lang'} ne '') {
 1277:                 $lang = $args->{'lang'};
 1278:             }
 1279:         }
 1280:         if (exists($args->{'fullpage'})) { 
 1281:             if ($args->{'fullpage'} eq 'true') {
 1282:                 $fullpage = $args->{'fullpage'};
 1283:             }
 1284:         }
 1285:         if (exists($args->{'dragmath'})) {
 1286:             if ($args->{'dragmath'} ne '') {
 1287:                 $dragmath_prefix = $args->{'dragmath'};
 1288:                 $dragmath_helpicon=&Apache::loncommon::lonhttpdurl("/adm/help/help.png");
 1289:                 $dragmath_whitespace=&Apache::loncommon::lonhttpdurl("/adm/lonIcons/transparent1x1.gif");
 1290:             }
 1291:         }
 1292:     }
 1293: 
 1294:     my %lt = &Apache::lonlocal::texthash(
 1295:               'plain'       => 'Plain text',
 1296:               'rich'        => 'Rich formatting',
 1297:               'plain_title' => 'Disable rich text formatting and edit in plain text',
 1298:               'rich_title'  => 'Enable rich text formatting (bold, italic, etc.)',
 1299:           );
 1300: 
 1301:     $output.='
 1302:     
 1303:     function containsBlockHtml(id) {
 1304: 		var re = $("#"+id).html().search(/(?:\&lt\;|\<)(br|h1|h2|h3|h4|h5|h6|p|ol|ul|table|pre|address|blockquote|center|div)[\s]*((?:[\/]*[\s]*(?:\&gt\;|\>)|(?:\&gt\;|\>)[\s\S]*(?:\&lt\;|\<)\/[\s]*\1[\s]*\(?:\&gt\;|\>))/im);
 1305:     	return (re >= 0);
 1306:     }
 1307:     
 1308:     function startRichEditor(id) {
 1309:     	CKEDITOR.replace(id, 
 1310:     		{
 1311:     			customConfig: "/ckeditor/loncapaconfig.js",
 1312:                         language : "'.$lang.'",
 1313:                         fullPage : '.$fullpage.',
 1314:     		}
 1315:     	);
 1316:     }
 1317:     
 1318:     function destroyRichEditor(id) {
 1319:     	CKEDITOR.instances[id].destroy();
 1320:     }
 1321:     
 1322:     function editorHandler(event) {
 1323:     	var rawid = $(this).attr("id");
 1324:     	var id = new RegExp("LC_rt_(.*)").exec(rawid)[1];
 1325:     	event.preventDefault();
 1326:     	var rt_enabled  = $(this).hasClass("LC_enable_rt");
 1327:         if (rt_enabled) {
 1328:     		startRichEditor(id);
 1329: 			$("#LC_rt_"+id).html("<b>&laquo; '.$lt{'plain'}.'</b>");
 1330: 			$("#LC_rt_"+id).attr("title", "'.$lt{'plain_title'}.'");
 1331: 			$("#LC_rt_"+id).addClass("LC_disable_rt");
 1332: 			$("#LC_rt_"+id).removeClass("LC_enable_rt");
 1333:     	} else {
 1334: 			destroyRichEditor(id);
 1335: 			$("#LC_rt_"+id).html("<b>'.$lt{'rich'}.' &raquo;</b>");
 1336: 			$("#LC_rt_"+id).attr("title", "'.$lt{'rich_title'}.'");
 1337: 			$("#LC_rt_"+id).addClass("LC_enable_rt");
 1338: 			$("#LC_rt_"+id).removeClass("LC_disable_rt");
 1339: 	}';
 1340:     if ($dragmath_prefix ne '') {
 1341:         $output .= "\n                 var visible = '';
 1342:                                        if (rt_enabled) {
 1343:                                            visible = 'none';
 1344:                                        }
 1345:                                        editmath_visibility(id,visible);\n";
 1346:     }
 1347:     $output .= '
 1348:     }
 1349:     $(document).ready(function(){
 1350: 		$(".LC_richAlwaysOn").each(function() {
 1351: 			startRichEditor($(this).attr("id"));
 1352: 		});
 1353: 		$(".LC_richDetectHtml").each(function() {
 1354: 			var id = $(this).attr("id");
 1355:                         var rt_enabled = containsBlockHtml(id);
 1356: 			if(rt_enabled) {
 1357: 				$(this).before("<div><a href=\"#\" id=\"LC_rt_"+id+"\" title=\"'.$lt{'plain_title'}.'\" class=\"LC_disable_rt\"><b>&laquo; '.$lt{'plain'}.'</b></a></div>");				
 1358: 				startRichEditor(id);
 1359: 				$("#LC_rt_"+id).click(editorHandler);
 1360: 			}
 1361: 			else {
 1362: 				$(this).before("<div><a href=\"#\" id=\"LC_rt_"+id+"\" title=\"'.$lt{'rich_title'}.'\" class=\"LC_enable_rt\"><b>'.$lt{'rich'}.' &raquo;</b></a></div>");
 1363: 				$("#LC_rt_"+id).click(editorHandler);
 1364: 			}';
 1365:     if ($dragmath_prefix ne '') {
 1366:         $output .= "\n                 var visible = '';
 1367:                                        if (rt_enabled) {
 1368:                                            visible = 'none';
 1369:                                        }
 1370:                                        editmath_visibility(id,visible);\n";
 1371:     }
 1372:     $output .= '
 1373: 		});
 1374: 		$(".LC_richDefaultOn").each(function() {
 1375: 			var id = $(this).attr("id");
 1376: 			$(this).before("<div><a href=\"#\" id=\"LC_rt_"+id+"\" title=\"'.$lt{'plain_title'}.'\" class=\"LC_disable_rt\"><b>&laquo; '.$lt{'plain'}.'</b></a></div>");				
 1377: 			startRichEditor(id);
 1378: 			$("#LC_rt_"+id).click(editorHandler);
 1379: 		});
 1380: 		$(".LC_richDefaultOff").each(function() {
 1381: 			var id = $(this).attr("id");
 1382: 			$(this).before("<div><a href=\"#\" id=\"LC_rt_"+id+"\" title=\"'.$lt{'rich_title'}.'\" class=\"LC_enable_rt\"><b>'.$lt{'rich'}.' &raquo;</b></a></div>");
 1383: 			$("#LC_rt_"+id).click(editorHandler);
 1384: 		});
 1385: 
 1386: 
 1387: 	});
 1388: ';
 1389:     $output .= &color_picker;
 1390: 
 1391:     # Code to put a due date countdown in 'duedatecountdown' span.
 1392:     # This is currently located in the breadcrumb headers.
 1393:     # note that the dueDateLayout is internatinoalized below.
 1394:     # Here document is used to support the substitution into the javascript below.
 1395:     # ..which unforunately necessitates escaping the $'s in the javascript.
 1396:     # There are several times of importance
 1397:     #
 1398:     # serverDueDate -  The absolute time at which the problem expires.
 1399:     # serverTime    -  The server's time when the problem finished computing.
 1400:     # clientTime    -  The client's time...as close to serverTime as possible.
 1401:     #                  The clientTime will be slightly later due to
 1402:     #                  1. The latency between problem computation and 
 1403:     #                     the first network action.
 1404:     #                  2. The time required between the page load-start and the actual
 1405:     #                     initial javascript execution that got clientTime.
 1406:     # These are used as follows:
 1407:     #   The difference between clientTime and serverTime are used to 
 1408:     #   correct for differences in clock settings between the browser's system and the
 1409:     #   server's.
 1410:     #
 1411:     #   The difference between clientTime and the time at which the ready() method
 1412:     #   starts executing is used to estimate latencies for page load and submission.
 1413:     #   Since this is an estimate, it is doubled.  The latency estimate + one minute
 1414:     #   is used to determine when the countdown timer turns red to warn the user
 1415:     #   to think about submitting.
 1416: 
 1417:     my $dueDateLayout = &mt('Due in: {dn} {dl} {hnn}{sep}{mnn}{sep}{snn} [_1]',
 1418:                             "<span id='submitearly'></span>");
 1419:     my $early = '- <b>'.&mt('Submit Early').'</b>';
 1420:     my $pastdue = '- <b>'.&mt('Past Due').'</b>';
 1421:     $output .= <<JAVASCRIPT;
 1422: 
 1423:     var documentReadyTime;
 1424: 
 1425: \$(document).ready(function() {
 1426:    if (typeof(dueDate) != "undefined") {
 1427:        documentReadyTime = (new Date()).getTime();
 1428:       \$("#duedatecountdown").countdown({until: dueDate, compact: true, 
 1429:          layout: "$dueDateLayout",
 1430:          onTick: function (periods) {
 1431: 	    var latencyEstimate = (documentReadyTime - clientTime) * 2;
 1432:             if(\$.countdown.periodsToSeconds(periods) < (300 + latencyEstimate)) {
 1433:                \$("#submitearly").html("$early");
 1434:                if (\$.countdown.periodsToSeconds(periods) < 1) {
 1435:                     \$("#submitearly").html("$pastdue");
 1436:                }
 1437:             }
 1438:             if(\$.countdown.periodsToSeconds(periods) < (60 + latencyEstimate)) {
 1439:                \$(this).css("color", "red");   //Highlight last minute.
 1440:             }
 1441:          }
 1442:       });
 1443:    }
 1444: });
 1445: 
 1446:     /* This code describes the spellcheck options that will be used for
 1447:        items with class 'spellchecked'.  It is necessary for those objects'
 1448:        to explicitly request checking (e.g. onblur is a nice event for that).
 1449:      */
 1450:      \$(document).ready(function() {
 1451: 	 \$(".spellchecked").spellchecker({
 1452: 	   url: "/ajax/spellcheck",
 1453: 	   lang: "en",                      
 1454: 	   engine: "pspell",
 1455: 	   suggestionBoxPosition: "below",
 1456: 	   innerDocument: true
 1457: 					  });
 1458: 	 \$("textarea.spellchecked").spellchecker({
 1459: 	   url: "/ajax/spellcheck",
 1460: 	   lang: "en",                      
 1461: 	   engine: "pspell",
 1462: 	   suggestionBoxPosition: "below",
 1463: 	   innerDocument: true
 1464: 					  });
 1465: 
 1466: 			});
 1467: 
 1468:     /* the muli colored editor can generate spellcheck with language 'none'
 1469:        to disable spellcheck as well
 1470:     */
 1471:     function doSpellcheck(element, lang) {
 1472: 	if (lang != 'none') {
 1473:  	    \$(element).spellchecker('option', {lang: lang});
 1474: 	    \$(element).spellchecker('check');
 1475:         }
 1476:     }
 1477: 
 1478: 
 1479: JAVASCRIPT
 1480:     if ($dragmath_prefix ne '') {
 1481:         $output .= '
 1482: 
 1483:      function editmath_visibility(id,value) {
 1484: 
 1485:          if ((id == "") || (id == null)) {
 1486:              return;
 1487:          }
 1488:          var mathid = "'.$dragmath_prefix.'_"+id;
 1489:          mathele = document.getElementById(mathid);
 1490:          if (mathele == null) {
 1491:              return;
 1492:          }
 1493:          mathele.style.display = value;
 1494:          var mathhelpicon = "'.$dragmath_prefix.'helpicon'.'_"+id;
 1495:          mathhelpiconele = document.getElementById(mathhelpicon);
 1496:          if (mathhelpiconele == null) {
 1497:              return;
 1498:          }
 1499:          if (value == "none") {
 1500:              mathhelpiconele.src = "'.$dragmath_whitespace.'";
 1501:          } else {
 1502:              mathhelpiconele.src = "'.$dragmath_helpicon.'";
 1503:          }
 1504:      }
 1505: ';
 1506: 
 1507:     }
 1508:     $output.="\nwindow.status='Activated Editfields';\n"
 1509:             .'// END LON-CAPA Internal -->'."\n"
 1510:             .'// ]]>'."\n"
 1511:             .'</script>';
 1512:     return $output;
 1513: }
 1514: 
 1515: # --------------------------------------------------------------------- Blocked
 1516: 
 1517: sub htmlareablocked {
 1518:     unless ($env{'environment.wysiwygeditor'} eq 'on') { return 1; }
 1519:     return 0;
 1520: }
 1521: 
 1522: # ---------------------------------------- Browser capable of running HTMLArea?
 1523: 
 1524: sub htmlareabrowser {
 1525:     return 1;
 1526: }
 1527: 
 1528: #
 1529: # Should the "return to content" link be shown?
 1530: #
 1531: 
 1532: sub show_return_link {
 1533: 
 1534:     unless ($env{'request.course.id'}) { return 0; }
 1535:     if ($env{'request.noversionuri'}=~m{^/priv/} ||
 1536:         $env{'request.uri'}=~m{^/priv/}) { return 1; }
 1537:     return if ($env{'request.noversionuri'} eq '/adm/supplemental');
 1538: 
 1539:     if (($env{'request.noversionuri'} =~ m{^/adm/(viewclasslist|navmaps)($|\?)})
 1540:         || ($env{'request.noversionuri'} =~ m{^/adm/.*/aboutme($|\?)})) {
 1541: 
 1542:         return if ($env{'form.register'});
 1543:     }
 1544:     return (($env{'request.noversionuri'}=~m{^/(res|public)/} &&
 1545:              $env{'request.symb'} eq '')
 1546:             ||
 1547:             ($env{'request.noversionuri'}=~ m{^/cgi-bin/printout.pl})
 1548:             ||
 1549:             (($env{'request.noversionuri'}=~/^\/adm\//) &&
 1550:              ($env{'request.noversionuri'}!~/^\/adm\/wrapper\//) &&
 1551:              ($env{'request.noversionuri'}!~
 1552:               m{^/adm/.*/(smppg|bulletinboard)($|\?)})
 1553:            ));
 1554: }
 1555: 
 1556: 
 1557: ##
 1558: #   Set the dueDate variable...note this is done in the timezone
 1559: #   of the browser.
 1560: #
 1561: # @param epoch relative time at which the problem is due.
 1562: #
 1563: # @return the javascript fragment to set the date:
 1564: #
 1565: sub set_due_date {
 1566:     my $dueStamp = shift;
 1567:     my $duems    = $dueStamp * 1000; # Javascript Date object needs ms not seconds.
 1568: 
 1569:     my $now = time()*1000;
 1570: 
 1571:     # This slightly obscure bit of javascript sets the dueDate variable
 1572:     # to the time in the browser at which the problem was due.  
 1573:     # The code should correct for gross differences between the server
 1574:     # and client's time setting
 1575: 
 1576:      return <<"END";
 1577: 
 1578: <script type="text/javascript">
 1579:   //<![CDATA[
 1580: var serverDueDate = $duems;
 1581: var serverTime    = $now;
 1582: var clientTime    = (new Date()).getTime();
 1583: var dueDate       = new Date(serverDueDate + (clientTime - serverTime));
 1584: 
 1585:   //]]>
 1586: </script>
 1587: 
 1588: END
 1589: }
 1590: ##
 1591: # Sets the time at which the problem finished computing.
 1592: # This just updates the serverTime and clientTime variables above.
 1593: # Calling this in e.g. end_problem provides a better estimate of the
 1594: # difference beetween the server and client time setting as 
 1595: # the difference contains less of the latency/problem compute time.
 1596: #
 1597: sub set_compute_end_time {
 1598: 
 1599:     my $now = time()*1000;	# Javascript times are in ms.
 1600:     return <<"END";
 1601: 
 1602: <script type="text/javascript">
 1603: //<![CDATA[
 1604: serverTime = $now;
 1605: clientTime = (new Date()).getTime();
 1606: //]]>
 1607: </script>
 1608: 
 1609: END
 1610: }
 1611: 
 1612: ############################################################
 1613: ############################################################
 1614: 
 1615: =pod
 1616: 
 1617: =item &breadcrumbs()
 1618: 
 1619: Compiles the previously registered breadcrumbs into an series of links.
 1620: Additionally supports a 'component', which will be displayed on the
 1621: right side of the breadcrumbs enclosing div (without a link).
 1622: A link to help for the component will be included if one is specified.
 1623: 
 1624: All inputs can be undef without problems.
 1625: 
 1626: Inputs: $component (the text on the right side of the breadcrumbs trail),
 1627:         $component_help
 1628:         $menulink (boolean, controls whether to include a link to /adm/menu)
 1629:         $helplink (if 'nohelp' don't include the orange help link)
 1630:         $css_class (optional name for the class to apply to the table for CSS)
 1631:         $no_mt (optional flag, 1 if &mt() is _not_ to be applied to $component
 1632:            when including the text on the right.
 1633: Returns a string containing breadcrumbs for the current page.
 1634: 
 1635: =item &clear_breadcrumbs()
 1636: 
 1637: Clears the previously stored breadcrumbs.
 1638: 
 1639: =item &add_breadcrumb()
 1640: 
 1641: Pushes a breadcrumb on the stack of crumbs.
 1642: 
 1643: input: $breadcrumb, a hash reference.  The keys 'href','title', and 'text'
 1644: are required.  If present the keys 'faq' and 'bug' will be used to provide
 1645: links to the FAQ and bug sites. If the key 'no_mt' is present the 'title' 
 1646: and 'text' values won't be sent through &mt()
 1647: 
 1648: returns: nothing    
 1649: 
 1650: =cut
 1651: 
 1652: ############################################################
 1653: ############################################################
 1654: {
 1655:     my @Crumbs;
 1656:     my %tools = ();
 1657:     
 1658:     sub breadcrumbs {
 1659:         my ($component,$component_help,$menulink,$helplink,$css_class,$no_mt, 
 1660:             $CourseBreadcrumbs) = @_;
 1661:         #
 1662:         $css_class ||= 'LC_breadcrumbs';
 1663: 
 1664:         # Make the faq and bug data cascade
 1665:         my $faq  = '';
 1666:         my $bug  = '';
 1667:         my $help = '';
 1668:         # Crumb Symbol
 1669:         my $crumbsymbol = '&raquo;';
 1670:         # The last breadcrumb does not have a link, so handle it separately.
 1671:         my $last = pop(@Crumbs);
 1672:         #
 1673:         # The first one should be the course or a menu link
 1674:         if (!defined($menulink)) { $menulink=1; }
 1675:         if ($menulink) {
 1676:             my $description = 'Menu';
 1677:             my $no_mt_descr = 0;
 1678:             if ((exists($env{'request.course.id'})) && 
 1679:                 ($env{'request.course.id'} ne '') && 
 1680:                 ($env{'course.'.$env{'request.course.id'}.'.description'} ne '')) {
 1681:                 $description = 
 1682:                     $env{'course.'.$env{'request.course.id'}.'.description'};
 1683:                 $no_mt_descr = 1;
 1684:                 if ($env{'request.noversionuri'} =~ 
 1685:                     m{^/public/($match_domain)/($match_courseid)/syllabus$}) {
 1686:                     unless (($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1) &&
 1687:                             ($env{'course.'.$env{'request.course.id'}.'.num'} eq $2)) {
 1688:                         $description = 'Menu';
 1689:                         $no_mt_descr = 0;
 1690:                     }
 1691:                 }
 1692:             }
 1693:             $menulink =  {  href   =>'/adm/menu',
 1694:                             title  =>'Go to main menu',
 1695:                             target =>'_top',
 1696:                             text   =>$description,
 1697:                             no_mt  =>$no_mt_descr, };
 1698:             if($last) {
 1699:                 #$last set, so we have some crumbs
 1700:                 unshift(@Crumbs,$menulink);
 1701:             } else {
 1702:                 #only menulink crumb present
 1703:                 $last = $menulink;
 1704:             }
 1705:         }
 1706:         my $links;
 1707:         if ((&show_return_link) && (!$CourseBreadcrumbs) && (ref($last) eq 'HASH')) {
 1708:             my $alttext = &mt('Go Back');
 1709:             my $hashref = { href => '/adm/flip?postdata=return:',
 1710:                             title => &mt('Back to most recent content resource'),
 1711:                             class => 'LC_menubuttons_link',
 1712:                           };
 1713:             if ($env{'request.noversionuri'} eq '/adm/searchcat') {
 1714:                 $hashref->{'target'} = '_top'; 
 1715:             }
 1716:             $links=&htmltag( 'a','<img src="/res/adm/pages/tolastloc.png" alt="'.$alttext.'" class="LC_icon" />',
 1717:                              $hashref);
 1718:             $links=&htmltag('li',$links);
 1719:         }
 1720:         $links.= join "", 
 1721:              map {
 1722:                  $faq  = $_->{'faq'}  if (exists($_->{'faq'}));
 1723:                  $bug  = $_->{'bug'}  if (exists($_->{'bug'}));
 1724:                  $help = $_->{'help'} if (exists($_->{'help'}));
 1725: 
 1726:                  my $result = $_->{no_mt} ? $_->{text} : &mt($_->{text});
 1727: 
 1728:                  if ($_->{href}){
 1729:                      $result = &htmltag( 'a', $result, 
 1730:                        { href   => $_->{href},
 1731:                          title  => $_->{no_mt} ? $_->{title} : &mt($_->{title}),
 1732:                          target => $_->{target}, });
 1733:                  }
 1734: 
 1735:                  $result = &htmltag( 'li', "$result $crumbsymbol");
 1736:              } @Crumbs;
 1737: 
 1738:         #should the last Element be translated?
 1739: 
 1740:         my $lasttext = $last->{'no_mt'} ? $last->{'text'} 
 1741:                      : mt( $last->{'text'} );
 1742: 
 1743:         # last breadcrumb is the first order heading of a page
 1744:         # for course breadcrumbs it's just bold
 1745: 
 1746:         if ($lasttext ne '') {
 1747:             $links .= &htmltag( 'li', htmltag($CourseBreadcrumbs ? 'b' : 'h1',
 1748:                     $lasttext), {title => $lasttext});
 1749:         }
 1750: 
 1751:         my $icons = '';
 1752:         $faq  = $last->{'faq'}  if (exists($last->{'faq'}));
 1753:         $bug  = $last->{'bug'}  if (exists($last->{'bug'}));
 1754:         $help = $last->{'help'} if (exists($last->{'help'}));
 1755:         $component_help=($component_help?$component_help:$help);
 1756: #        if ($faq ne '') {
 1757: #            $icons .= &Apache::loncommon::help_open_faq($faq);
 1758: #        }
 1759: #        if ($bug ne '') {
 1760: #            $icons .= &Apache::loncommon::help_open_bug($bug);
 1761: #        }
 1762:         if ($faq ne '' || $component_help ne '' || $bug ne '') {
 1763:             $icons .= &Apache::loncommon::help_open_menu($component,
 1764:                                                          $component_help,
 1765:                                                          $faq,$bug);
 1766:         }
 1767:         #
 1768: 
 1769: 		
 1770:         if ($links ne '') {
 1771:             unless ($CourseBreadcrumbs) {
 1772:                 $links = &htmltag('ol',  $links, { id => "LC_MenuBreadcrumbs"   });
 1773:             } else {
 1774:                 $links = &htmltag('ul',  $links, { class => "LC_CourseBreadcrumbs" });
 1775:             }
 1776:         }
 1777: 
 1778: 
 1779:         if ($component) {
 1780:             $links = &htmltag('span', 
 1781:                              ( $no_mt ? $component : mt($component) ).
 1782:                              ( $icons ? $icons : '' ),
 1783:                              { class => 'LC_breadcrumbs_component' } )
 1784:                              .$links 
 1785: ;
 1786:         }
 1787:         my $nav_and_tools = 0;
 1788:         foreach my $item ('navigation','tools') {
 1789:             if (ref($tools{$item}) eq 'ARRAY') {
 1790:                 $nav_and_tools += scalar(@{$tools{$item}})
 1791:             }
 1792:         }
 1793:         if (($links ne '') || ($nav_and_tools)) {
 1794:             &render_tools(\$links);
 1795:             $links = &htmltag('div', $links, 
 1796:                               { id => "LC_breadcrumbs" }) unless ($CourseBreadcrumbs) ;
 1797:         }
 1798:         my $adv_tools = 0;
 1799:         if (ref($tools{'advtools'}) eq 'ARRAY') {
 1800:             $adv_tools = scalar(@{$tools{'advtools'}});
 1801:         }
 1802:         if (($links ne '') || ($adv_tools)) {
 1803:             &render_advtools(\$links);
 1804:         }
 1805: 
 1806:         # Return the @Crumbs stack to what we started with
 1807:         push(@Crumbs,$last);
 1808:         shift(@Crumbs);
 1809: 
 1810: 
 1811:         # Return the breadcrumb's line
 1812: 
 1813:     
 1814: 
 1815:         return "$links";
 1816:     }
 1817: 
 1818:     sub clear_breadcrumbs {
 1819:         undef(@Crumbs);
 1820:         undef(%tools);
 1821:     }
 1822: 
 1823:     sub add_breadcrumb {
 1824:         push(@Crumbs,@_);
 1825:     }
 1826:     
 1827: =item &add_breadcrumb_tool($category, $html)
 1828: 
 1829: Adds $html to $category of the breadcrumb toolbar container.
 1830: 
 1831: $html is usually a link to a page that invokes a function on the currently 
 1832: displayed data (e.g. print when viewing a problem)
 1833: 
 1834: Currently there are 3 possible values for $category: 
 1835: 
 1836: =over 
 1837: 
 1838: =item navigation 
 1839: left of breadcrumbs line
 1840: 
 1841: =item tools 
 1842: remaining items in right of breadcrumbs line
 1843: 
 1844: =item advtools 
 1845: advanced tools shown in a separate box below breadcrumbs line 
 1846: 
 1847: =back
 1848:  
 1849: returns: nothing
 1850: 
 1851: =cut
 1852: 
 1853:     sub add_breadcrumb_tool {
 1854:         my ($category, @html) = @_;
 1855:         return unless @html;
 1856:         if (!keys(%tools)) { 
 1857:             %tools = ( navigation => [], tools => [], advtools => []);
 1858:         }
 1859: 
 1860:         #this cleans data received from lonmenu::innerregister
 1861:         @html = grep {defined $_ && $_ ne ''} @html;
 1862:         for (@html) { 
 1863:             s/align="(right|left)"//; 
 1864: #            s/<span.*?\/span>// if $category ne 'advtools'; 
 1865:         } 
 1866: 
 1867:         push @{$tools{$category}}, @html;
 1868:     }
 1869: 
 1870: =item &clear_breadcrumb_tools()
 1871: 
 1872: Clears the breadcrumb toolbar container.
 1873: 
 1874: returns: nothing
 1875: 
 1876: =cut
 1877: 
 1878:     sub clear_breadcrumb_tools {
 1879:         undef(%tools);
 1880:     }
 1881: 
 1882: =item &render_tools(\$breadcrumbs)
 1883: 
 1884: Creates html for breadcrumb tools (categories navigation and tools) and inserts 
 1885: \$breadcrumbs at the correct position.
 1886: 
 1887: input: \$breadcrumbs - a reference to the string containing prepared 
 1888: breadcrumbs.
 1889: 
 1890: returns: nothing
 1891: 
 1892: =cut
 1893: 
 1894: #TODO might split this in separate functions for each category
 1895:     sub render_tools {
 1896:         my ($breadcrumbs) = @_;
 1897:         return unless (keys(%tools));
 1898: 
 1899:         my $navigation = list_from_array($tools{navigation}, 
 1900:                    { listattr => { class=>"LC_breadcrumb_tools_navigation" } });
 1901:         my $tools = list_from_array($tools{tools}, 
 1902:                    { listattr => { class=>"LC_breadcrumb_tools_tools" } });
 1903:         $$breadcrumbs = list_from_array([$navigation, $tools, $$breadcrumbs], 
 1904:                    { listattr => { class=>'LC_breadcrumb_tools_outerlist' } });
 1905:     }
 1906: 
 1907: =pod
 1908: 
 1909: =item &render_advtools(\$breadcrumbs)
 1910: 
 1911: Creates html for advanced tools (category advtools) and inserts \$breadcrumbs 
 1912: at the correct position.
 1913: 
 1914: input: \$breadcrumbs - a reference to the string containing prepared 
 1915: breadcrumbs (after render_tools call).
 1916: 
 1917: returns: nothing
 1918: 
 1919: =cut
 1920: 
 1921:     sub render_advtools {
 1922:         my ($breadcrumbs) = @_;
 1923:         return unless     (defined $tools{'advtools'}) 
 1924:                       and (scalar(@{$tools{'advtools'}}) > 0);
 1925: 
 1926:         $$breadcrumbs .= Apache::loncommon::head_subbox(
 1927:                             funclist_from_array($tools{'advtools'}) );
 1928:     }
 1929: 
 1930: } # End of scope for @Crumbs
 1931: 
 1932: sub docs_breadcrumbs {
 1933:     my ($allowed,$crstype,$contenteditor,$title,$precleared)=@_;
 1934:     my ($folderpath,@folders,$supplementalflag);
 1935:     @folders = split('&',$env{'form.folderpath'});
 1936:     if ($env{'form.folderpath'} =~ /^supplemental/) {
 1937:         $supplementalflag = 1;
 1938:     }
 1939:     my $plain='';
 1940:     my $container = 'sequence';
 1941:     my ($randompick,$isencrypted,$ishidden,$is_random_order) = (-1,0,0,0);
 1942:     my @docs_crumbs;
 1943:     while (@folders) {
 1944:         my $folder=shift(@folders);
 1945:         my $foldername=shift(@folders);
 1946:         if ($folderpath) {$folderpath.='&';}
 1947:         $folderpath.=$folder.'&'.$foldername;
 1948:         my $url;
 1949:         if ($allowed) {
 1950:             $url = '/adm/coursedocs?folderpath=';
 1951:         } else {
 1952:             $url = '/adm/supplemental?folderpath=';
 1953:         }
 1954:         $url .= &escape($folderpath);
 1955:         my $name=&unescape($foldername);
 1956: # each of randompick number, hidden, encrypted, random order, is_page 
 1957: # are appended with ":"s to the foldername
 1958:         $name=~s/\:(\d*)\:(\w*)\:(\w*):(\d*)\:?(\d*)$//;
 1959:         unless ($supplementalflag) {
 1960:             if ($contenteditor) { 
 1961:                 if ($1 ne '') {
 1962:                     $randompick=$1;
 1963:                 } else {
 1964:                     $randompick=-1;
 1965:                 }
 1966:                 if ($2) { $ishidden=1; }
 1967:                 if ($3) { $isencrypted=1; }
 1968:                 if ($4 ne '') { $is_random_order = 1; }
 1969:                 if ($5 == 1) {$container = 'page'; }
 1970:             }
 1971:         }
 1972:         if ($folder eq 'supplemental') {
 1973:             $name = &mt('Supplemental Content');
 1974:         }
 1975:         if ($contenteditor) {
 1976:             $plain.=$name.' &gt; ';
 1977:         }
 1978:         push(@docs_crumbs,
 1979:                           {'href'  => $url,
 1980:                            'title' => $name,
 1981:                            'text'  => $name,
 1982:                            'no_mt' => 1,
 1983:                           });
 1984:     }
 1985:     if ($title) {
 1986:         push(@docs_crumbs,
 1987:                           {'title' => $title,
 1988:                            'text'  => $title,
 1989:                            'no_mt' => 1,}
 1990:                           );
 1991:     }
 1992:     if (wantarray) {
 1993:         unless ($precleared) {
 1994:             &clear_breadcrumbs();
 1995:         }
 1996:         &add_breadcrumb(@docs_crumbs);
 1997:         if ($contenteditor) {
 1998:             $plain=~s/\&gt\;\s*$//;
 1999:         }
 2000:         my $menulink = 0;
 2001:         if (!$allowed && !$contenteditor) {
 2002:             $menulink = 1;
 2003:         }
 2004:         return (&breadcrumbs(undef,undef,$menulink,'nohelp',undef,undef,
 2005:                              $contenteditor),
 2006:                              $randompick,$ishidden,$isencrypted,$plain,
 2007:                              $is_random_order,$container);
 2008:     } else {
 2009:         return \@docs_crumbs;
 2010:     }
 2011: }
 2012: 
 2013: ############################################################
 2014: ############################################################
 2015: 
 2016: # Nested table routines.
 2017: #
 2018: # Routines to display form items in a multi-row table with 2 columns.
 2019: # Uses nested tables to divide form elements into segments.
 2020: # For examples of use see loncom/interface/lonnotify.pm 
 2021: #
 2022: # Can be used in following order: ...
 2023: # &start_pick_box()
 2024: # row1
 2025: # row2
 2026: # row3   ... etc.
 2027: # &submit_row()
 2028: # &end_pick_box()
 2029: #
 2030: # where row1, row 2 etc. are chosen from &role_select_row,&course_select_row,
 2031: # &status_select_row and &email_default_row
 2032: #
 2033: # Can also be used in following order:
 2034: #
 2035: # &start_pick_box()
 2036: # &row_title()
 2037: # &row_closure()
 2038: # &row_title()
 2039: # &row_closure()  ... etc.
 2040: # &submit_row()
 2041: # &end_pick_box()
 2042: #
 2043: # In general a &submit_row() call should proceed the call to &end_pick_box(),
 2044: # as this routine adds a button for form submission.
 2045: # &submit_row() does not require a &row_closure after it.
 2046: #  
 2047: # &start_pick_box() creates a bounding table with 1-pixel wide black border.
 2048: # rows should be placed between calls to &start_pick_box() and &end_pick_box.
 2049: #
 2050: # &row_title() adds a title in the left column for each segment.
 2051: # &row_closure() closes a row with a 1-pixel wide black line.
 2052: #
 2053: # &role_select_row() provides a select box from which to choose 1 or more roles 
 2054: # &course_select_row provides ways of picking groups of courses
 2055: #    radio buttons: all, by category or by picking from a course picker pop-up
 2056: #      note: by category option is only displayed if a domain has implemented 
 2057: #                selection by year, semester, department, number etc.
 2058: #
 2059: # &status_select_row() provides a select box from which to choose 1 or more
 2060: #  access types (current access, prior access, and future access)  
 2061: #
 2062: # &email_default_row() provides text boxes for default e-mail suffixes for
 2063: #  different authentication types in a domain.
 2064: #
 2065: # &row_title() and &row_closure() are called internally by the &*_select_row
 2066: # routines, but can also be called directly to start and end rows which have 
 2067: # needs that are not accommodated by the *_select_row() routines.    
 2068: 
 2069: { # Start: row_count block for pick_box
 2070: my @row_count;
 2071: 
 2072: sub start_pick_box {
 2073:     my ($css_class,$id) = @_;
 2074:     if (defined($css_class)) {
 2075: 	$css_class = 'class="'.$css_class.'"';
 2076:     } else {
 2077: 	$css_class= 'class="LC_pick_box"';
 2078:     }
 2079:     my $table_id;
 2080:     if (defined($id)) {
 2081:         $table_id = ' id="'.$id.'"';
 2082:     }
 2083:     unshift(@row_count,0);
 2084:     my $output = <<"END";
 2085:  <table $css_class $table_id>
 2086: END
 2087:     return $output;
 2088: }
 2089: 
 2090: sub end_pick_box {
 2091:     shift(@row_count);
 2092:     my $output = <<"END";
 2093:        </table>
 2094: END
 2095:     return $output;
 2096: }
 2097: 
 2098: sub row_headline {
 2099:     my $output = <<"END";
 2100:            <tr><td colspan="2">
 2101: END
 2102:     return $output;
 2103: }
 2104: 
 2105: sub row_title {
 2106:     my ($title,$css_title_class,$css_value_class, $css_value_furtherAttributes) = @_;
 2107:     $row_count[0]++;
 2108:     my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
 2109:     $css_title_class ||= 'LC_pick_box_title';
 2110:     $css_title_class = 'class="'.$css_title_class.'"';
 2111: 
 2112:     $css_value_class ||= 'LC_pick_box_value';
 2113: 
 2114:     if ($title ne '') {
 2115:         $title .= ':';
 2116:     }
 2117:     my $output = <<"ENDONE";
 2118:            <tr class="LC_pick_box_row" $css_value_furtherAttributes> 
 2119:             <td $css_title_class>
 2120: 	       $title
 2121:             </td>
 2122:             <td class="$css_value_class $css_class">
 2123: ENDONE
 2124:     return $output;
 2125: }
 2126: 
 2127: sub row_closure {
 2128:     my ($no_separator) =@_;
 2129:     my $output = <<"ENDTWO";
 2130:             </td>
 2131:            </tr>
 2132: ENDTWO
 2133:     if (!$no_separator) {
 2134:         $output .= <<"ENDTWO";
 2135:            <tr>
 2136:             <td colspan="2" class="LC_pick_box_separator">
 2137:             </td>
 2138:            </tr>
 2139: ENDTWO
 2140:     }
 2141:     return $output;
 2142: }
 2143: 
 2144: } # End: row_count block for pick_box
 2145: 
 2146: sub role_select_row {
 2147:     my ($roles,$title,$css_class,$show_separate_custom,$cdom,$cnum) = @_;
 2148:     my $crstype = 'Course';
 2149:     if ($cdom ne '' && $cnum ne '') {
 2150:         $crstype = &Apache::loncommon::course_type($cdom.'_'.$cnum);
 2151:     }
 2152:     my $output;
 2153:     if (defined($title)) {
 2154:         $output = &row_title($title,$css_class);
 2155:     }
 2156:     $output .= qq|
 2157:                                   <select name="roles" multiple="multiple">\n|;
 2158:     foreach my $role (@$roles) {
 2159:         my $plrole;
 2160:         if ($role eq 'ow') {
 2161:             $plrole = &mt('Course Owner');
 2162:         } elsif ($role eq 'cr') {
 2163:             if ($show_separate_custom) {
 2164:                 if ($cdom ne '' && $cnum ne '') {
 2165:                     my %course_customroles = &course_custom_roles($cdom,$cnum);
 2166:                     foreach my $crrole (sort(keys(%course_customroles))) {
 2167:                         my ($plcrrole) = ($crrole =~ m|^cr/[^/]+/[^/]+/(.+)$|);
 2168:                         $output .= '  <option value="'.$crrole.'">'.$plcrrole.
 2169:                                    '</option>';
 2170:                     }
 2171:                 }
 2172:             } else {
 2173:                 $plrole = &mt('Custom Role');
 2174:             }
 2175:         } else {
 2176:             $plrole=&Apache::lonnet::plaintext($role,$crstype);
 2177:         }
 2178:         if (($role ne 'cr') || (!$show_separate_custom)) {
 2179:             $output .= '  <option value="'.$role.'">'.$plrole.'</option>';
 2180:         }
 2181:     }
 2182:     $output .= qq|                </select>\n|;
 2183:     if (defined($title)) {
 2184:         $output .= &row_closure();
 2185:     }
 2186:     return $output;
 2187: }
 2188: 
 2189: sub course_select_row {
 2190:     my ($title,$formname,$totcodes,$codetitles,$idlist,$idlist_titles,
 2191: 	$css_class,$crstype,$standardnames) = @_;
 2192:     my $output = &row_title($title,$css_class);
 2193:     $output .= &course_selection($formname,$totcodes,$codetitles,$idlist,$idlist_titles,$crstype,$standardnames);
 2194:     $output .= &row_closure();
 2195:     return $output;
 2196: }
 2197: 
 2198: sub course_selection {
 2199:     my ($formname,$totcodes,$codetitles,$idlist,$idlist_titles,$crstype,$standardnames) = @_;
 2200:     my $output = qq|
 2201: <script type="text/javascript">
 2202: // <![CDATA[
 2203:     function coursePick (formname) {
 2204:         for  (var i=0; i<formname.coursepick.length; i++) {
 2205:             if (formname.coursepick[i].value == 'category') {
 2206:                 courseSet('');
 2207:             }
 2208:             if (!formname.coursepick[i].checked) {
 2209:                 if (formname.coursepick[i].value == 'specific') {
 2210:                     formname.coursetotal.value = 0;
 2211:                     formname.courselist = '';
 2212:                 }
 2213:             }
 2214:         }
 2215:     }
 2216:     function setPick (formname) {
 2217:         for  (var i=0; i<formname.coursepick.length; i++) {
 2218:             if (formname.coursepick[i].value == 'category') {
 2219:                 formname.coursepick[i].checked = true;
 2220:             }
 2221:             formname.coursetotal.value = 0;
 2222:             formname.courselist = '';
 2223:         }
 2224:     }
 2225: // ]]>
 2226: </script>
 2227:     |;
 2228: 
 2229:     my ($allcrs,$pickspec);
 2230:     if ($crstype eq 'Community') {
 2231:         $allcrs = &mt('All communities');
 2232:         $pickspec = &mt('Pick specific communities:');
 2233:     } else {
 2234:         $allcrs = &mt('All courses');
 2235:         $pickspec = &mt('Pick specific course(s):');
 2236:     }
 2237: 
 2238:     my $courseform='<b>'.&Apache::loncommon::selectcourse_link
 2239:                      ($formname,'pickcourse','pickdomain','coursedesc','',1,$crstype).'</b>';
 2240:         $output .= '<label><input type="radio" name="coursepick" value="all" onclick="coursePick(this.form)" />'.$allcrs.'</label><br />';
 2241:     if ($totcodes > 0) {
 2242:         my $numtitles = @$codetitles;
 2243:         if ($numtitles > 0) {
 2244:             $output .= '<label><input type="radio" name="coursepick" value="category" onclick="coursePick(this.form);alert('."'".&mt('Choose categories, from left to right')."'".')" />'.&mt('Pick courses by category:').'</label><br />';
 2245:             $output .= '<table><tr><td>'.$$codetitles[0].'<br />'."\n".
 2246:                '<select name="'.$standardnames->[0].
 2247:                '" onchange="setPick(this.form);courseSet('."'$$codetitles[0]'".')">'."\n".
 2248:                ' <option value="-1" />Select'."\n";
 2249:             my @items = ();
 2250:             my @longitems = ();
 2251:             if ($$idlist{$$codetitles[0]} =~ /","/) {
 2252:                 @items = split(/","/,$$idlist{$$codetitles[0]});
 2253:             } else {
 2254:                 $items[0] = $$idlist{$$codetitles[0]};
 2255:             }
 2256:             if (defined($$idlist_titles{$$codetitles[0]})) {
 2257:                 if ($$idlist_titles{$$codetitles[0]} =~ /","/) {
 2258:                     @longitems = split(/","/,$$idlist_titles{$$codetitles[0]});
 2259:                 } else {
 2260:                     $longitems[0] = $$idlist_titles{$$codetitles[0]};
 2261:                 }
 2262:                 for (my $i=0; $i<@longitems; $i++) {
 2263:                     if ($longitems[$i] eq '') {
 2264:                         $longitems[$i] = $items[$i];
 2265:                     }
 2266:                 }
 2267:             } else {
 2268:                 @longitems = @items;
 2269:             }
 2270:             for (my $i=0; $i<@items; $i++) {
 2271:                 $output .= ' <option value="'.$items[$i].'">'.$longitems[$i].'</option>';
 2272:             }
 2273:             $output .= '</select></td>';
 2274:             for (my $i=1; $i<$numtitles; $i++) {
 2275:                 $output .= '<td>'.$$codetitles[$i].'<br />'."\n".
 2276:                           '<select name="'.$standardnames->[$i].
 2277:                           '" onchange="courseSet('."'$$codetitles[$i]'".')">'."\n".
 2278:                           '<option value="-1">&lt;-Pick '.$$codetitles[$i-1].'</option>'."\n".
 2279:                           '</select>'."\n".
 2280:                           '</td>';
 2281:             }
 2282:             $output .= '</tr></table><br />';
 2283:         }
 2284:     }
 2285:     $output .=
 2286:         '<label><input type="radio" name="coursepick" value="specific"'
 2287:        .' onclick="coursePick(this.form);opencrsbrowser('."'".$formname."','dccourse','dcdomain','coursedesc','','1','$crstype'".')" />'
 2288:        .$pickspec.'</label>'
 2289:        .' '.$courseform.'&nbsp;&nbsp;'
 2290:        .&mt('[_1] selected.',
 2291:                 '<input type="text" value="0" size="4" name="coursetotal" readonly="readonly" />'
 2292:                .'<input type="hidden" name="courselist" value="" />')
 2293:        .'<br />'."\n";
 2294:     return $output;
 2295: }
 2296: 
 2297: sub status_select_row {
 2298:     my ($types,$title,$css_class) = @_;
 2299:     my $output; 
 2300:     if (defined($title)) {
 2301:         $output = &row_title($title,$css_class,'LC_pick_box_select');
 2302:     }
 2303:     $output .= qq|
 2304:                                     <select name="types" multiple="multiple">\n|;
 2305:     foreach my $status_type (sort(keys(%{$types}))) {
 2306:         $output .= '  <option value="'.$status_type.'">'.$$types{$status_type}.'</option>';
 2307:     }
 2308:     $output .= qq|                   </select>\n|; 
 2309:     if (defined($title)) {
 2310:         $output .= &row_closure();
 2311:     }
 2312:     return $output;
 2313: }
 2314: 
 2315: sub email_default_row {
 2316:     my ($authtypes,$title,$descrip,$css_class) = @_;
 2317:     my $output = &row_title($title,$css_class);
 2318:     $output .= $descrip.
 2319: 	&Apache::loncommon::start_data_table().
 2320: 	&Apache::loncommon::start_data_table_header_row().
 2321: 	'<th>'.&mt('Authentication Method').'</th>'.
 2322: 	'<th align="right">'.&mt('Username -> e-mail conversion').'</th>'."\n".
 2323: 	&Apache::loncommon::end_data_table_header_row();
 2324:     my $rownum = 0;
 2325:     foreach my $auth (sort(keys(%{$authtypes}))) {
 2326:         my ($userentry,$size);
 2327:         if ($auth =~ /^krb/) {
 2328:             $userentry = '';
 2329:             $size = 25;
 2330:         } else {
 2331:             $userentry = 'username@';
 2332:             $size = 15;
 2333:         }
 2334:         $output .= &Apache::loncommon::start_data_table_row().
 2335: 	    '<td>  '.$$authtypes{$auth}.'</td>'.
 2336: 	    '<td align="right">'.$userentry.
 2337: 	    '<input type="text" name="'.$auth.'" size="'.$size.'" /></td>'.
 2338: 	    &Apache::loncommon::end_data_table_row();
 2339:     }
 2340:     $output .= &Apache::loncommon::end_data_table();
 2341:     $output .= &row_closure();
 2342:     return $output;
 2343: }
 2344: 
 2345: 
 2346: sub submit_row {
 2347:     my ($title,$cmd,$submit_text,$css_class) = @_;
 2348:     my $output = &row_title($title,$css_class,'LC_pick_box_submit');
 2349:     $output .= qq|
 2350:              <br />
 2351:              <input type="hidden" name="command" value="$cmd" />
 2352:              <input type="submit" value="$submit_text"/> &nbsp;
 2353:              <br /><br />
 2354:             \n|;
 2355:     return $output;
 2356: }
 2357: 
 2358: sub course_custom_roles {
 2359:     my ($cdom,$cnum) = @_;
 2360:     my %returnhash=();
 2361:     my %coursepersonnel=&Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
 2362:     foreach my $person (sort(keys(%coursepersonnel))) {
 2363:         my ($role) = ($person =~ /^([^:]+):/);
 2364:         my ($end,$start) = split(/:/,$coursepersonnel{$person});
 2365:         if ($end == -1 && $start == -1) {
 2366:             next;
 2367:         }
 2368:         if ($role =~ m|^cr/[^/]+/[^/]+/[^/]|) {
 2369:             $returnhash{$role} ++;
 2370:         }
 2371:     }
 2372:     return %returnhash;
 2373: }
 2374: 
 2375: 
 2376: sub resource_info_box {
 2377:    my ($symb,$onlyfolderflag,$stuvcurrent,$stuvdisp)=@_;
 2378:    my $return='';
 2379:    if ($stuvcurrent ne '') {
 2380:        $return = '<div class="LC_left_float">';
 2381:    }
 2382:    if ($symb) {
 2383:        $return.=&Apache::loncommon::start_data_table();
 2384:        my ($map,$id,$resource)=&Apache::lonnet::decode_symb($symb);
 2385:        my $folder=&Apache::lonnet::gettitle($map);
 2386:        $return.=&Apache::loncommon::start_data_table_row().
 2387:                     '<th align="left">'.&mt('Folder:').'</th><td>'.$folder.'</td>'.
 2388:                     &Apache::loncommon::end_data_table_row();
 2389:        unless ($onlyfolderflag) {
 2390:           $return.=&Apache::loncommon::start_data_table_row().
 2391:                     '<th align="left">'.&mt('Resource:').'</th><td>'.&Apache::lonnet::gettitle($symb).'</td>'.
 2392:                     &Apache::loncommon::end_data_table_row();
 2393:        }
 2394:        if ($stuvcurrent ne '') {
 2395:            $return .= &Apache::loncommon::start_data_table_row().
 2396:                     '<th align="left">'.&mt("Student's current version:").'</th><td>'.$stuvcurrent.'</td>'.
 2397:                     &Apache::loncommon::end_data_table_row();
 2398:        }
 2399:        if ($stuvdisp ne '') {
 2400:            $return .= &Apache::loncommon::start_data_table_row().
 2401:                     '<th align="left">'.&mt("Student's version displayed:").'</th><td>'.$stuvdisp.'</td>'.
 2402:                     &Apache::loncommon::end_data_table_row();
 2403:        }
 2404:        $return.=&Apache::loncommon::end_data_table();
 2405:     } else {
 2406:        $return='<p><span class="LC_error">'.&mt('No context provided.').'</span></p>';
 2407:     }
 2408:     if ($stuvcurrent ne '') {
 2409:         $return .= '</div>';
 2410:     }
 2411:     return $return;
 2412: }
 2413: 
 2414: # display_usage
 2415: # 
 2416: # Generates a div containing a block, filled to show percentage of current quota used
 2417: #
 2418: # Quotas available for user portfolios, group portfolios, authoring spaces, and course
 2419: # content stored directly within a course (i.e., excluding published content).
 2420: #
 2421: 
 2422: sub display_usage {
 2423:     my ($current_disk_usage,$disk_quota) = @_;
 2424:     my $usage = $current_disk_usage/1000;
 2425:     my $quota = $disk_quota/1000;
 2426:     my $percent;
 2427:     if ($disk_quota == 0) {
 2428:         $percent = 100.0;
 2429:     } else {
 2430:         $percent = 100*($current_disk_usage/$disk_quota);
 2431:     }
 2432:     $usage = sprintf("%.2f",$usage);
 2433:     $quota = sprintf("%.2f",$quota);
 2434:     $percent = sprintf("%.0f",$percent);
 2435:     my ($color,$cssclass);
 2436:     if ($percent <= 60) {
 2437:         $color = '#00A000';
 2438:     } elsif ($percent > 60 && $percent < 90) {
 2439:         $color = '#FFD300';
 2440:         $cssclass = 'class="LC_warning"';
 2441:     } elsif( $percent >= 90) {
 2442:         $color = '#FF0000';
 2443:         $cssclass = 'class="LC_error"';
 2444:     }
 2445:     my $prog_width = $percent;
 2446:     if ($prog_width > 100) {
 2447:         $prog_width = 100;
 2448:     }
 2449:     return '
 2450:   <div id="meter1" align="left" '.$cssclass.'>'.&mt('Currently using [_1] of the [_2] available.',$usage.' MB <span style="font-weight:bold;">('.$percent.'%)</span>',$quota.' MB')."\n".
 2451: '   <div id="meter2" style="display:block; margin-top:5px; margin-bottom:5px; margin-left:0px; margin-right:0px; width:400px; border:1px solid #000000; height:10px;">'."\n".
 2452: '    <div id="meter3" style="display:block; background-color:'.$color.'; width:'.$prog_width.'%; height:10px; color:#000000; margin:0px;"></div>'."\n".
 2453: '   </div>'."\n".
 2454: '  </div>';
 2455: }
 2456: 
 2457: ##############################################
 2458: ##############################################
 2459: 
 2460: # topic_bar
 2461: #
 2462: # Generates a div containing an (optional) number with a white background followed by a 
 2463: # title with a background color defined in the corresponding CSS: LC_topic_bar
 2464: # Inputs:
 2465: # 1. number to display.
 2466: #    If input for number is empty only the title will be displayed. 
 2467: # 2. title text to display.
 2468: # 3. optional id for the <div>
 2469: # Outputs - a scalar containing html mark-up for the div.
 2470: 
 2471: sub topic_bar {
 2472:     my ($num,$title,$id) = @_;
 2473:     my $number = '';
 2474:     if ($num ne '') {
 2475:         $number = '<span>'.$num.'</span>';
 2476:     }
 2477:     if ($id ne '') {
 2478:         $id = 'id="'.$id.'"';
 2479:     }
 2480:     return '<div class="LC_topic_bar" '.$id.'>'.$number.$title.'</div>';
 2481: }
 2482: 
 2483: ##############################################
 2484: ##############################################
 2485: # echo_form_input
 2486: #
 2487: # Generates html markup to add form elements from the referrer page
 2488: # as hidden form elements (values encoded) in the new page.
 2489: #
 2490: # Intended to support two types of use 
 2491: # (a) to allow backing up to earlier pages in a multi-page 
 2492: # form submission process using a breadcrumb trail.
 2493: #
 2494: # (b) to allow the current page to be reloaded with form elements
 2495: # set on previous page to remain unchanged.  An example would
 2496: # be where the a page containing a dynamically-built table of data is 
 2497: # is to be redisplayed, with only the sort order of the data changed. 
 2498: #  
 2499: # Inputs:
 2500: # 1. Reference to array of form elements in the submitted form on 
 2501: # the referrer page which are to be excluded from the echoed elements.
 2502: #
 2503: # 2. Reference to array of regular expressions, which if matched in the  
 2504: # name of the form element n the referrer page will be omitted from echo. 
 2505: #
 2506: # Outputs: A scalar containing the html markup for the echoed form
 2507: # elements (all as hidden elements, with values encoded). 
 2508: 
 2509: 
 2510: sub echo_form_input {
 2511:     my ($excluded,$regexps) = @_;
 2512:     my $output = '';
 2513:     foreach my $key (keys(%env)) {
 2514:         if ($key =~ /^form\.(.+)$/) {
 2515:             my $name = $1;
 2516:             my $match = 0;
 2517:             if (ref($excluded) eq 'ARRAY') {    
 2518:                 next if (grep(/^\Q$name\E$/,@{$excluded}));
 2519:             }
 2520:             if (ref($regexps) eq 'ARRAY') {
 2521:                 if (@{$regexps} > 0) {
 2522:                     foreach my $regexp (@{$regexps}) {
 2523:                         if ($name =~ /$regexp/) {
 2524:                             $match = 1;
 2525:                             last;
 2526:                         }
 2527:                     }
 2528:                 }
 2529:             }
 2530:             next if ($match);
 2531:             if (ref($env{$key}) eq 'ARRAY') {
 2532:                 foreach my $value (@{$env{$key}}) {
 2533:                     $value = &HTML::Entities::encode($value,'<>&"');
 2534:                     $output .= '<input type="hidden" name="'.$name.
 2535:                                '" value="'.$value.'" />'."\n";
 2536:                 }
 2537:             } else {
 2538:                 my $value = &HTML::Entities::encode($env{$key},'<>&"');
 2539:                 $output .= '<input type="hidden" name="'.$name.
 2540:                            '" value="'.$value.'" />'."\n";
 2541:             }
 2542:         }
 2543:     }
 2544:     return $output;
 2545: }
 2546: 
 2547: ##############################################
 2548: ##############################################
 2549: # set_form_elements
 2550: #
 2551: # Generates javascript to set form elements to values based on
 2552: # corresponding values for the same form elements when the page was
 2553: # previously submitted.
 2554: #     
 2555: # Last submission values are read from hidden form elements in referring 
 2556: # page which have the same name, i.e., generated by &echo_form_input(). 
 2557: #
 2558: # Intended to be called by onload event.
 2559: #
 2560: # Inputs:
 2561: # (a) Reference to hash of echoed form elements to be set.
 2562: #
 2563: # In the hash, keys are the form element names, and the values are the
 2564: # element type (selectbox, radio, checkbox or text -for textbox, textarea or
 2565: # hidden).
 2566: #
 2567: # (b) Optional reference to hash of stored elements to be set.
 2568: #
 2569: # If the page being displayed is a page which permits modification of
 2570: # previously stored data, e.g., the first page in a multi-page submission,
 2571: # then if stored is supplied, form elements will be set to the last stored
 2572: # values.  If user supplied values are also available for the same elements
 2573: # these will replace the stored values. 
 2574: #        
 2575: # Output:
 2576: #  
 2577: # javascript function - set_form_elements() which sets form elements,
 2578: # expects an argument: formname - the name of the form according to 
 2579: # the DOM, e.g., document.compose
 2580: 
 2581: sub set_form_elements {
 2582:     my ($elements,$stored) = @_;
 2583:     my %values;
 2584:     my $output .= 'function setFormElements(courseForm) {
 2585: ';
 2586:     if (defined($stored)) {
 2587:         foreach my $name (keys(%{$stored})) {
 2588:             if (exists($$elements{$name})) {
 2589:                 if (ref($$stored{$name}) eq 'ARRAY') {
 2590:                     $values{$name} = $$stored{$name};
 2591:                 } else {
 2592:                     @{$values{$name}} = ($$stored{$name});
 2593:                 }
 2594:             }
 2595:         }
 2596:     }
 2597: 
 2598:     foreach my $key (keys(%env)) {
 2599:         if ($key =~ /^form\.(.+)$/) {
 2600:             my $name = $1;
 2601:             if (exists($$elements{$name})) {
 2602:                 @{$values{$name}} = &Apache::loncommon::get_env_multiple($key);
 2603:             }
 2604:         }
 2605:     }
 2606: 
 2607:     foreach my $name (keys(%values)) {
 2608:         for (my $i=0; $i<@{$values{$name}}; $i++) {
 2609:             $values{$name}[$i] = &HTML::Entities::decode($values{$name}[$i],'<>&"');
 2610:             $values{$name}[$i] =~ s/([\r\n\f]+)/\\n/g;
 2611:             $values{$name}[$i] =~ s/"/\\"/g;
 2612:         }
 2613:         if (($$elements{$name} eq 'text') || ($$elements{$name} eq 'hidden')) {
 2614:             my $numvalues = @{$values{$name}};
 2615:             if ($numvalues > 1) {
 2616:                 my $valuestring = join('","',@{$values{$name}});
 2617:                 $output .= qq|
 2618:   var textvalues = new Array ("$valuestring");
 2619:   var total = courseForm.elements['$name'].length;
 2620:   if (total > $numvalues) {
 2621:       total = $numvalues;
 2622:   }    
 2623:   for (var i=0; i<total; i++) {
 2624:       courseForm.elements['$name']\[i].value = textvalues[i];
 2625:   }
 2626: |;
 2627:             } else {
 2628:                 $output .= qq|
 2629:   courseForm.elements['$name'].value = "$values{$name}[0]";
 2630: |;
 2631:             }
 2632:         } else {
 2633:             $output .=  qq|
 2634:   var elementLength = courseForm.elements['$name'].length;
 2635:   if (elementLength==undefined) {
 2636: |;
 2637:             foreach my $value (@{$values{$name}}) {
 2638:                 if ($$elements{$name} eq 'selectbox') {
 2639:                     $output .=  qq|
 2640:       if (courseForm.elements['$name'].options[0].value == "$value") {
 2641:           courseForm.elements['$name'].options[0].selected = true;
 2642:       }|;
 2643:                 } elsif (($$elements{$name} eq 'radio') ||
 2644:                          ($$elements{$name} eq 'checkbox')) {
 2645:                     $output .= qq|
 2646:       if (courseForm.elements['$name'].value == "$value") {
 2647:           courseForm.elements['$name'].checked = true;
 2648:       } else {
 2649:           courseForm.elements['$name'].checked = false;
 2650:       }|;
 2651:                 }
 2652:             }
 2653:             $output .= qq|
 2654:   }
 2655:   else {
 2656:       for (var i=0; i<courseForm.elements['$name'].length; i++) {
 2657: |;
 2658:             if ($$elements{$name} eq 'selectbox') {
 2659:                 $output .=  qq|
 2660:           courseForm.elements['$name'].options[i].selected = false;|;
 2661:             } elsif (($$elements{$name} eq 'radio') || 
 2662:                      ($$elements{$name} eq 'checkbox')) {
 2663:                 $output .= qq|
 2664:           courseForm.elements['$name']\[i].checked = false;|; 
 2665:             }
 2666:             $output .= qq|
 2667:       }
 2668:       for (var j=0; j<courseForm.elements['$name'].length; j++) {
 2669: |;
 2670:             foreach my $value (@{$values{$name}}) {
 2671:                 if ($$elements{$name} eq 'selectbox') {
 2672:                     $output .=  qq|
 2673:           if (courseForm.elements['$name'].options[j].value == "$value") {
 2674:               courseForm.elements['$name'].options[j].selected = true;
 2675:           }|;
 2676:                 } elsif (($$elements{$name} eq 'radio') ||
 2677:                          ($$elements{$name} eq 'checkbox')) { 
 2678:                       $output .= qq|
 2679:           if (courseForm.elements['$name']\[j].value == "$value") {
 2680:               courseForm.elements['$name']\[j].checked = true;
 2681:           }|;
 2682:                 }
 2683:             }
 2684:             $output .= qq|
 2685:       }
 2686:   }
 2687: |;
 2688:         }
 2689:     }
 2690:     $output .= "
 2691:     return;
 2692: }\n";
 2693:     return $output;
 2694: }
 2695: 
 2696: ##############################################
 2697: ##############################################
 2698: 
 2699: sub file_submissionchk_js {
 2700:     my ($turninpaths,$multiples) = @_;
 2701:     my $overwritewarn = &mt('File(s) you uploaded for your submission will overwrite existing file(s) submitted for this item').'\\n'.
 2702:                       &mt('Continue submission and overwrite the file(s)?');
 2703:     my $delfilewarn = &mt('You have indicated you wish to remove some files previously included in your submission.').'\\n'.
 2704:                       &mt('Continue submission with these files removed?');
 2705:     my ($turninpathtext,$multtext,$arrayindexofjs);
 2706:     if (ref($turninpaths) eq 'HASH') {
 2707:         foreach my $key (sort(keys(%{$turninpaths}))) {
 2708:             $turninpathtext .= "    if (prefix == '$key') {\n".
 2709:                                "        return '$turninpaths->{$key}';\n".
 2710:                                "    }\n";
 2711:         }
 2712:     }
 2713:     $turninpathtext .= "    return '';\n";
 2714:     if (ref($multiples) eq 'HASH') {
 2715:         foreach my $key (sort(keys(%{$multiples}))) {
 2716:             $multtext .= "    if (prefix == '$key') {\n".
 2717:                          "        return '$multiples->{$key}';\n".
 2718:                          "    }\n";
 2719:         }
 2720:     }
 2721:     $multtext .= "    return '';\n";
 2722: 
 2723:     $arrayindexofjs = &Apache::loncommon::javascript_array_indexof();
 2724:     return <<"ENDSCRIPT";
 2725: <script type="text/javascript">
 2726: // <![CDATA[
 2727: 
 2728: function file_submission_check(formname,path,multiresp) {
 2729:     var elemnum = formname.elements.length;
 2730:     if (elemnum == 0) {
 2731:         return true;
 2732:     }
 2733:     var alloverwrites = [];
 2734:     var alldelconfirm = [];
 2735:     var result = [];
 2736:     var submitter;
 2737:     var subprefix;
 2738:     var allsub = getIndexByName(formname,'all_submit');
 2739:     if (allsub == -1) {
 2740:         var idx = getIndexByName(formname,'submitted');
 2741:         if (idx != -1) {
 2742:             var subval = String(formname.elements[idx].value);
 2743:             submitter = subval.replace(/^part_/,'');
 2744:             result = overwritten_check(formname,path,multiresp,submitter);
 2745:             alloverwrites.push.apply(alloverwrites,result['overwrite']);
 2746:             alldelconfirm.push.apply(alldelconfirm,result['delete']);
 2747:         }
 2748:     } else {
 2749:         if (formname.elements[allsub].type == 'submit') {
 2750:             var partsub = /^\\d+\\.\\d+_submit_.+\$/;
 2751:             var allprefixes = [];
 2752:             var allparts = [];
 2753:             for (var i=0; i<formname.elements.length; i++) {
 2754:                 if (formname.elements[i].type == 'submit') {
 2755:                     var elemname = formname.elements[i].name;
 2756:                     var subname = String(elemname);
 2757:                     var savesub = String(elemname);
 2758:                     if (partsub.test(subname)) {
 2759:                         var prefix = subname.replace(/_submit_.+\$/,'');
 2760:                         if (allprefixes.indexOf(prefix) == -1) {
 2761:                             allprefixes.push(prefix);
 2762:                             allparts[prefix] = [];
 2763:                         }
 2764:                         var part = savesub.replace(/^\\d+\\.\\d+_submit_/,'');
 2765:                         allparts[prefix].push(part);
 2766:                     }
 2767:                 }
 2768:             }
 2769:             for (var k=0; k<allprefixes.length; k++) {
 2770:                 var idx = getIndexByName(formname,allprefixes[k]+'_submitted');
 2771:                 if (idx > -1) {
 2772:                     if (formname.elements[idx].value != 'yes') {
 2773:                         submitterval = formname.elements[idx].value;
 2774:                         submitter = submitterval.replace(/^part_/,'');
 2775:                         subprefix = allprefixes[k];
 2776:                         result = overwritten_check(formname,path,multiresp,submitter,subprefix);
 2777:                         alloverwrites.push.apply(alloverwrites,result['overwrite']);
 2778:                         alldelconfirm.push.apply(alldelconfirm,result['delete']);
 2779:                         break;
 2780:                     }
 2781:                 }
 2782:             }
 2783:             if (submitter == '' || submitter == undefined) {
 2784:                 for (var m=0; m<allprefixes.length; m++) {
 2785:                     for (var n=0; n<allparts[allprefixes[m]].length; n++) {
 2786:                         var result = overwritten_check(formname,path,multiresp,allparts[allprefixes[m]][n],allprefixes[m]);
 2787:                         alloverwrites.push.apply(alloverwrites,result['overwrite']);
 2788:                         alldelconfirm.push.apply(alldelconfirm,result['delete']);
 2789:                     }
 2790:                 }
 2791:             }
 2792:         }
 2793:     }
 2794:     if (alloverwrites.length > 0) {
 2795:         if (!confirm("$overwritewarn")) {
 2796:             for (var n=0; n<alloverwrites.length; n++) {
 2797:                 formname.elements[alloverwrites[n]].value = "";
 2798:             }
 2799:             return false;
 2800:         }
 2801:     }
 2802:     if (alldelconfirm.length > 0) {
 2803:         if (!confirm("$delfilewarn")) {
 2804:             for (var p=0; p<alldelconfirm.length; p++) {
 2805:                 formname.elements[alldelconfirm[p]].checked = false;
 2806:             }
 2807:             return false;
 2808:         }
 2809:     }
 2810:     return true;
 2811: }
 2812: 
 2813: function getIndexByName(formname,item) {
 2814:     for (var i=0;i<formname.elements.length;i++) {
 2815:         if (formname.elements[i].name == item) {
 2816:             return i;
 2817:         }
 2818:     }
 2819:     return -1;
 2820: }
 2821: 
 2822: function overwritten_check(formname,path,multiresp,part,prefix) {
 2823:     var result = [];
 2824:     result['overwrite'] = [];
 2825:     result['delete'] = [];
 2826:     var elemnum = formname.elements.length;
 2827:     if (elemnum == 0) {
 2828:         return result;
 2829:     }
 2830:     var uploadstr;
 2831:     var deletestr;
 2832:     if ((prefix != undefined) && (prefix != '')) {
 2833:         var prepend = prefix+'_';
 2834:         uploadstr = new RegExp("^"+prepend+"HWFILE"+part+".+\$");
 2835:         deletestr = new RegExp("^"+prepend+"HWFILE"+part+".+_\\\\d+_delete\$");
 2836:         multiresp = check_for_multiples(prepend);
 2837:         path = check_for_turninpath(prepend);
 2838:     } else {
 2839:         uploadstr = new RegExp("^HWFILE"+part+".+\$");
 2840:         deletestr = new RegExp("^HWFILE"+part+".+_\\\\d+_delete\$");
 2841:     }
 2842:     var alluploads = [];
 2843:     var allchecked = [];
 2844:     var allskipdel = [];
 2845:     var fnametrim = /[^\\/\\\\]+\$/;
 2846:     for (var i=0; i<formname.elements.length; i++) {
 2847:         var id = formname.elements[i].id;
 2848:         if (id != '') {
 2849:             if (uploadstr.test(id)) {
 2850:                 if (formname.elements[i].type == 'file') {
 2851:                     alluploads.push(id);
 2852:                 } else {
 2853:                     if (deletestr.test(id)) {
 2854:                         if (formname.elements[i].type == 'checkbox') {
 2855:                             if (formname.elements[i].checked) {
 2856:                                 allchecked.push(id);
 2857:                             }
 2858:                         }
 2859:                     }
 2860:                 }
 2861:             }
 2862:         }
 2863:     }
 2864:     for (var j=0; j<alluploads.length; j++) {
 2865:         var delstr = new RegExp("^"+alluploads[j]+"_\\\\d+_delete\$");
 2866:         var delboxes = [];
 2867:         for (var k=0; k<formname.elements.length; k++) {
 2868:             var id = formname.elements[k].id;
 2869:             if ((id != '') && (id != undefined)) {
 2870:                 if (delstr.test(id)) {
 2871:                     if (formname.elements[k].type == 'checkbox') {
 2872:                         delboxes.push(id);
 2873:                     }
 2874:                 }
 2875:             }
 2876:         }
 2877:         if (delboxes.length > 0) {
 2878:             if ((formname.elements[alluploads[j]].value != undefined) &&
 2879:                 (formname.elements[alluploads[j]].value != '')) {
 2880:                 var filepath = formname.elements[alluploads[j]].value;
 2881:                 var newfilename = fnametrim.exec(filepath);
 2882:                 if (newfilename != null) {
 2883:                     var filename = String(newfilename);
 2884:                     var nospaces = filename.replace(/\\s+/g,'_');
 2885:                     var nospecials = nospaces.replace(/[^\\/\\w\\.\\-]/g,'');
 2886:                     var cleanfilename = nospecials.replace(/\\.(\\d+\\.)/g,"_\$1");
 2887:                     if (cleanfilename != '') {
 2888:                         var fullpath = path+"/"+cleanfilename;
 2889:                         if (multiresp == 1) {
 2890:                             var partid = String(alluploads[i]);
 2891:                             var subdir = partid.replace(/^\\d*.?\\d*_?HWFILE/,'');
 2892:                             if (subdir != "" && subdir != undefined) {
 2893:                                 fullpath = path+"/"+subdir+"/"+cleanfilename;
 2894:                             }
 2895:                         }
 2896:                         for (var m=0; m<delboxes.length; m++) {
 2897:                             if (fullpath == formname.elements[delboxes[m]].value) {
 2898:                                 if (formname.elements[delboxes[m]].checked) {
 2899:                                     allskipdel.push(delboxes[m]);
 2900:                                 } else {
 2901:                                     result['overwrite'].push(alluploads[j]);
 2902:                                 }
 2903:                                 break;
 2904:                             }
 2905:                         }
 2906:                     }
 2907:                 }
 2908:             }
 2909:         }
 2910:     }
 2911:     if (allchecked.length > 0) {
 2912:         if (allskipdel.length > 0) {
 2913:             for (var n=0; n<allchecked.length; n++) {
 2914:                 if (allskipdel.indexOf(allchecked[n]) == -1) {
 2915:                     result['delete'].push(allchecked[n]);
 2916:                 }
 2917:             }
 2918:         } else {
 2919:             result['delete'].push.apply(result['delete'],allchecked);
 2920:         }
 2921:     }
 2922:     return result;
 2923: }
 2924: 
 2925: function check_for_multiples(prefix) {
 2926: $multtext
 2927: }
 2928: 
 2929: function check_for_turninpath(prefix) {
 2930: $turninpathtext
 2931: }
 2932: 
 2933: // ]]>
 2934: </script>
 2935: 
 2936: $arrayindexofjs
 2937: 
 2938: ENDSCRIPT
 2939: }
 2940: 
 2941: ##############################################
 2942: ##############################################
 2943: 
 2944: sub resize_scrollbox_js {
 2945:     my ($context,$tabidstr,$tid) = @_;
 2946:     my (%names,$paddingwfrac,$offsetwfrac,$offsetv,$minw,$minv);
 2947:     if ($context eq 'docs') {
 2948:         %names = (
 2949:                    boxw   => 'contenteditor',
 2950:                    item   => 'contentlist',
 2951:                    header => 'uploadfileresult',
 2952:                    scroll => 'contentscroll',
 2953:                    boxh   => 'contenteditor',
 2954:                  );
 2955:         $paddingwfrac = 0.09;
 2956:         $offsetwfrac = 0.015;
 2957:         $offsetv = 20;
 2958:         $minw = 250;
 2959:         $minv = 200;
 2960:     } elsif ($context eq 'params') {
 2961:         %names = (
 2962:                    boxw   => 'parameditor',
 2963:                    item   => 'mapmenuinner',
 2964:                    header => 'parmstep1',
 2965:                    scroll => 'mapmenuscroll',
 2966:                    boxh   => 'parmlevel',
 2967:                  );
 2968:         $paddingwfrac = 0.2;
 2969:         $offsetwfrac = 0.015;
 2970:         $offsetv = 80;
 2971:         $minw = 100;
 2972:         $minv = 100; 
 2973:     }
 2974:     my $viewport_js = &Apache::loncommon::viewport_geometry_js();
 2975:     my $output = '
 2976: 
 2977: window.onresize=callResize;
 2978: 
 2979: ';
 2980:     if ($context eq 'docs') {
 2981:         if ($env{'form.active'}) {
 2982:             $output .= "\nvar activeTab = '$env{'form.active'}$tid';\n";
 2983:         } else {
 2984:             $output .= "\nvar activeTab = '';\n";
 2985:         }
 2986:     }
 2987:     $output .=  <<"FIRST";
 2988: 
 2989: $viewport_js
 2990: 
 2991: function resize_scrollbox(scrollboxname,chkw,chkh) {
 2992:     var scrollboxid = 'div_'+scrollboxname;
 2993:     var scrolltableid = 'table_'+scrollboxname;
 2994:     var scrollbox;
 2995:     var scrolltable;
 2996:     var ismobile = '$env{'browser.mobile'}';
 2997: 
 2998:     if (document.getElementById("$names{'boxw'}") == null) {
 2999:         return;
 3000:     }
 3001: 
 3002:     if (document.getElementById(scrollboxid) == null) {
 3003:         return;
 3004:     } else {
 3005:         scrollbox = document.getElementById(scrollboxid);
 3006:     }
 3007: 
 3008: 
 3009:     if (document.getElementById(scrolltableid) == null) {
 3010:         return;
 3011:     } else {
 3012:         scrolltable = document.getElementById(scrolltableid);
 3013:     }
 3014: 
 3015:     init_geometry();
 3016:     var vph = Geometry.getViewportHeight();
 3017:     var vpw = Geometry.getViewportWidth();
 3018: 
 3019: FIRST
 3020:     if ($context eq 'docs') {
 3021:         $output .= "
 3022:     var alltabs = ['$tabidstr'];
 3023: ";
 3024:     } elsif ($context eq 'params') {
 3025:         $output .= "
 3026:     if (document.getElementById('$names{'boxh'}') == null) {
 3027:         return;
 3028:     }
 3029: ";
 3030:     }
 3031:     $output .= <<"SECOND";
 3032:     var listwchange;
 3033:     var scrollchange;
 3034:     if (chkw == 1) {
 3035:         var boxw = document.getElementById("$names{'boxw'}").offsetWidth;
 3036:         var itemw;
 3037:         var itemid = document.getElementById("$names{'item'}");
 3038:         if (itemid != null) {
 3039:             itemw = itemid.offsetWidth;
 3040:         }
 3041:         var itemwstart = itemw;
 3042: 
 3043:         var scrollboxw = scrollbox.offsetWidth;
 3044:         var scrollboxscrollw = scrollbox.scrollWidth;
 3045:         var scrollstart = scrollboxw;
 3046: 
 3047:         var offsetw = parseInt(vpw * $offsetwfrac);
 3048:         var paddingw = parseInt(vpw * $paddingwfrac);
 3049: 
 3050:         var minscrollboxw = $minw;
 3051:         var maxcolw = 0;
 3052: SECOND
 3053:     if ($context eq 'docs') {
 3054:         $output .= <<"DOCSONE";
 3055:         var actabw = 0;
 3056:         for (var i=0; i<alltabs.length; i++) {
 3057:             if (activeTab == alltabs[i]) {
 3058:                 actabw = document.getElementById(alltabs[i]).offsetWidth;
 3059:                 if (actabw > maxcolw) {
 3060:                     maxcolw = actabw;
 3061:                 }
 3062:             } else {
 3063:                 if (document.getElementById(alltabs[i]) != null) {
 3064:                     var thistab = document.getElementById(alltabs[i]);
 3065:                     thistab.style.visibility = 'hidden';
 3066:                     thistab.style.display = 'block';
 3067:                     var tabw = document.getElementById(alltabs[i]).offsetWidth;
 3068:                     thistab.style.display = 'none';
 3069:                     thistab.style.visibility = '';
 3070:                     if (tabw > maxcolw) {
 3071:                         maxcolw = tabw;
 3072:                     }
 3073:                 }
 3074:             }
 3075:         }
 3076: DOCSONE
 3077:     } elsif ($context eq 'params') {
 3078:         $output .= <<"PARAMSONE";
 3079:         var parmlevelrows = new Array();
 3080:         var mapmenucells = new Array();
 3081:         parmlevelrows = document.getElementById("$names{'boxh'}").rows;
 3082:         var numrows = parmlevelrows.length;
 3083:         if (numrows > 1) {
 3084:             mapmenucells = parmlevelrows[2].getElementsByTagName('td');
 3085:         }
 3086:         maxcolw = mapmenucells[0].offsetWidth;
 3087: PARAMSONE
 3088:     }
 3089:     $output .= <<"THIRD";
 3090:         if (maxcolw > 0) {
 3091:             var newscrollboxw;
 3092:             if (maxcolw+paddingw+scrollboxscrollw<boxw) {
 3093:                 newscrollboxw = boxw-paddingw-maxcolw;
 3094:                 if (newscrollboxw < minscrollboxw) {
 3095:                     newscrollboxw = minscrollboxw;
 3096:                 }
 3097:                 scrollbox.style.width = newscrollboxw+"px";
 3098:                 if (newscrollboxw != scrollboxw) {
 3099:                     var newitemw = newscrollboxw-offsetw;
 3100:                     itemid.style.width = newitemw+"px";
 3101:                 }
 3102:             } else {
 3103:                 newscrollboxw = boxw-paddingw-maxcolw;
 3104:                 if (newscrollboxw < minscrollboxw) {
 3105:                     newscrollboxw = minscrollboxw;
 3106:                 }
 3107:                 scrollbox.style.width = newscrollboxw+"px";
 3108:                 if (newscrollboxw != scrollboxw) {
 3109:                     var newitemw = newscrollboxw-offsetw;
 3110:                     itemid.style.width = newitemw+"px";
 3111:                 }
 3112:             }
 3113: 
 3114:             if (newscrollboxw != scrollboxw) {
 3115:                 var newscrolltablew = newscrollboxw+offsetw;
 3116:                 scrolltable.style.width = newscrolltablew+"px";
 3117:             }
 3118:         }
 3119: 
 3120:         if (newscrollboxw != scrollboxw) {
 3121:             scrollchange = 1;
 3122:         }
 3123: 
 3124:         if (itemid.offsetWidth != itemwstart) {
 3125:             listwchange = 1;
 3126:         }
 3127:     }
 3128:     if ((chkh == 1) || (listwchange)) {
 3129:         var itemid = document.getElementById("$names{'item'}");
 3130:         if (itemid != null) {
 3131:             itemh = itemid.offsetHeight;
 3132:         }
 3133:         var primaryheight = document.getElementById('LC_nav_bar').offsetHeight;
 3134:         var secondaryheight;
 3135:         if (document.getElementById('LC_secondary_menu') != null) { 
 3136:             secondaryheight = document.getElementById('LC_secondary_menu').offsetHeight;
 3137:         }
 3138:         var crumbsheight = document.getElementById('LC_breadcrumbs').offsetHeight;
 3139:         var dccidheight = 0;
 3140:         if (document.getElementById('dccid') != null) {
 3141:             dccidheight = document.getElementById('dccid').offsetHeight;
 3142:         }
 3143:         var headerheight = 0;
 3144:         if (document.getElementById("$names{'header'}") != null) {
 3145:             headerheight = document.getElementById("$names{'header'}").offsetHeight;
 3146:         }
 3147:         var tabbedheight = document.getElementById("tabbededitor").offsetHeight;
 3148:         var boxheight = document.getElementById("$names{'boxh'}").offsetHeight;
 3149:         var freevspace = vph-(primaryheight+secondaryheight+crumbsheight+dccidheight+headerheight+tabbedheight+boxheight);
 3150: 
 3151:         var scrollboxheight = scrollbox.offsetHeight;
 3152:         var scrollboxscrollheight = scrollbox.scrollHeight;
 3153:         var scrollboxh = scrollboxheight;
 3154: 
 3155:         var minvscrollbox = $minv;
 3156:         var offsetv = $offsetv;
 3157:         var newscrollboxheight;
 3158:         if (freevspace < 0) {
 3159:             newscrollboxheight = scrollboxheight+freevspace-offsetv;
 3160:             if (newscrollboxheight < minvscrollbox) {
 3161:                 newscrollboxheight = minvscrollbox;
 3162:             }
 3163:             scrollbox.style.height = newscrollboxheight + "px";
 3164:         } else {
 3165:             if (scrollboxscrollheight > scrollboxheight) {
 3166:                 if (freevspace > offsetv) {
 3167:                     newscrollboxheight = scrollboxheight+freevspace-offsetv;
 3168:                     if (newscrollboxheight < minvscrollbox) {
 3169:                         newscrollboxheight = minvscrollbox;
 3170:                     }
 3171:                     scrollbox.style.height = newscrollboxheight+"px";
 3172:                 }
 3173:             }
 3174:         }
 3175:         scrollboxheight = scrollbox.offsetHeight;
 3176:         var itemh = document.getElementById("$names{'item'}").offsetHeight;
 3177: 
 3178:         if (scrollboxscrollheight <= scrollboxheight) {
 3179:             if ((itemh+offsetv)<scrollboxheight) {
 3180:                 newscrollheight = itemh+offsetv;
 3181:                 scrollbox.style.height = newscrollheight+"px";
 3182:             }
 3183:         }
 3184:         var newscrollboxh = scrollbox.offsetHeight;
 3185:         if (scrollboxh != newscrollboxh) {
 3186:             scrollchange = 1;
 3187:         }
 3188:     }
 3189:     if (ismobile && scrollchange) {
 3190:         \$("#div_$names{'scroll'}").getNiceScroll().onResize();
 3191:     }
 3192:     return;
 3193: }
 3194: 
 3195: function callResize() {
 3196:     var timer;
 3197:     clearTimeout(timer);
 3198:     timer=setTimeout('resize_scrollbox("$names{'scroll'}","1","1")',500);
 3199: }
 3200: 
 3201: THIRD
 3202:     return $output;
 3203: }
 3204: 
 3205: ##############################################
 3206: ##############################################
 3207: 
 3208: sub javascript_jumpto_resource {
 3209:     my $confirm_switch = &mt("Editing requires switching to the resource's home server.").'\n'.
 3210:                          &mt('Switch server?');
 3211:     return (<<ENDUTILITY)
 3212: 
 3213: function go(url) {
 3214:    if (url!='' && url!= null) {
 3215:        currentURL = null;
 3216:        currentSymb= null;
 3217:        window.location.href=url;
 3218:    }
 3219: }
 3220: 
 3221: function need_switchserver(url) {
 3222:     if (url!='' && url!= null) {
 3223:         if (confirm("$confirm_switch")) {
 3224:             go(url);
 3225:         }
 3226:     }
 3227:     return;
 3228: }
 3229: 
 3230: ENDUTILITY
 3231: 
 3232: }
 3233: 
 3234: sub jump_to_editres {
 3235:     my ($cfile,$home,$switchserver,$forceedit,$forcereg,$symb,$folderpath,
 3236:         $title,$idx,$suppurl,$todocs) = @_;
 3237:     my $jscall;
 3238:     if ($switchserver) {
 3239:         if ($home) {
 3240:             $cfile = '/adm/switchserver?otherserver='.$home.'&amp;role='.
 3241:                      &HTML::Entities::encode($env{'request.role'},'"<>&');
 3242:             if ($symb) {
 3243:                 $cfile .= '&amp;symb='.&HTML::Entities::encode($symb,'"<>&');
 3244:             } elsif ($folderpath) {
 3245:                 $cfile .= '&amp;folderpath='.&HTML::Entities::encode($folderpath,'"<>&');
 3246:             }
 3247:             if ($forceedit) {
 3248:                 $cfile .= '&amp;forceedit=1';
 3249:             }
 3250:             if ($forcereg) {
 3251:                 $cfile .= '&amp;register=1';
 3252:             }
 3253:             $jscall = "need_switchserver('$cfile');";
 3254:         }
 3255:     } else {
 3256:         unless ($cfile =~ m{^/priv/}) {
 3257:             if ($symb) {
 3258:                 $cfile .= (($cfile=~/\?/)?'&amp;':'?')."symb=$symb";
 3259:             } elsif ($folderpath) {
 3260:                 $cfile .= (($cfile=~/\?/)?'&amp;':'?').
 3261:                           'folderpath='.&HTML::Entities::encode(&escape($folderpath),'"<>&');
 3262:                 if ($title) {
 3263:                     $cfile .= (($cfile=~/\?/)?'&amp;':'?').
 3264:                               'title='.&HTML::Entities::encode(&escape($title),'"<>&');
 3265:                 }
 3266:                 if ($idx) {
 3267:                     $cfile .= (($cfile=~/\?/)?'&amp;':'?').'idx='.$idx;
 3268:                 }
 3269:                 if ($suppurl) {
 3270:                     $cfile .= (($cfile=~/\?/)?'&amp;':'?').
 3271:                               'suppurl='.&HTML::Entities::encode(&escape($suppurl));
 3272:                 }
 3273:             }
 3274:             if ($forceedit) {
 3275:                 $cfile .= (($cfile=~/\?/)?'&amp;':'?').'forceedit=1';
 3276:             }
 3277:             if ($forcereg) {
 3278:                 $cfile .= (($cfile=~/\?/)?'&amp;':'?').'register=1';
 3279:             }
 3280:             if ($todocs) {
 3281:                $cfile .= (($cfile=~/\?/)?'&amp;':'?').'todocs=1';
 3282:             }
 3283:         }
 3284:         $jscall = "go('$cfile')";
 3285:     }
 3286:     return $jscall;
 3287: }
 3288: 
 3289: ##############################################
 3290: ##############################################
 3291: 
 3292: # javascript_valid_email
 3293: #
 3294: # Generates javascript to validate an e-mail address.
 3295: # Returns a javascript function which accetps a form field as argumnent, and
 3296: # returns false if field.value does not satisfy two regular expression matches
 3297: # for a valid e-mail address.  Backwards compatible with old browsers without
 3298: # support for javascript RegExp (just checks for @ in field.value in this case). 
 3299: 
 3300: sub javascript_valid_email {
 3301:     my $scripttag .= <<'END';
 3302: function validmail(field) {
 3303:     var str = field.value;
 3304:     if (window.RegExp) {
 3305:         var reg1str = "(@.*@)|(\\.\\.)|(@\\.)|(\\.@)|(^\\.)";
 3306:         var reg2str = "^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$"; //"
 3307:         var reg1 = new RegExp(reg1str);
 3308:         var reg2 = new RegExp(reg2str);
 3309:         if (!reg1.test(str) && reg2.test(str)) {
 3310:             return true;
 3311:         }
 3312:         return false;
 3313:     }
 3314:     else
 3315:     {
 3316:         if(str.indexOf("@") >= 0) {
 3317:             return true;
 3318:         }
 3319:         return false;
 3320:     }
 3321: }
 3322: END
 3323:     return $scripttag;
 3324: }
 3325: 
 3326: 
 3327: # USAGE: htmltag(element, content, {attribute => value,...});
 3328: #
 3329: # EXAMPLES: 
 3330: #  - htmltag('a', 'this is an anchor', {href  => 'www.example.com', 
 3331: #                                       title => 'this is a title'})
 3332: #
 3333: #  - You might want to set up needed tags like: 
 3334: #
 3335: #     my $h3  = sub { return htmltag( "h3",  @_ ) };
 3336: #
 3337: #    ... and use them: $h3->("This is a headline")
 3338: #
 3339: #  - To set up a couple of tags, see sub inittags
 3340: #
 3341: # NOTES:
 3342: # - Empty elements, such as <br/> are correctly terminated, 
 3343: #   i.e. htmltag('br') returns <br/> 
 3344: # - Empty attributes (title="") are filtered out.
 3345: # - The function will not check for deprecated attributes.
 3346: #
 3347: # OUTPUT: content enclosed in xhtml conform tags
 3348: sub htmltag{
 3349:     return
 3350:         qq|<$_[0]|
 3351:         . join( '', map { qq| $_="${$_[2]}{$_}"| if ${$_[2]}{$_} } keys %{ $_[2] } )
 3352:         . ($_[1] ? qq|>$_[1]</$_[0]>| : qq|/>|). "\n";
 3353: };
 3354: 
 3355: 
 3356: # USAGE: inittags(@tags);
 3357: #
 3358: # EXAMPLES:
 3359: #  - my ($h1, $h2, $h3) = inittags( qw( h1 h2 h3 ) )
 3360: #    $h1->("This is a headline") #Returns: <h1>This is a headline</h1>
 3361: #
 3362: # NOTES: See sub htmltag for further information.
 3363: #
 3364: # OUTPUT: List of subroutines. 
 3365: sub inittags {
 3366:     my @tags = @_;
 3367:     return map { my $tag = $_;
 3368:                  sub { return htmltag( $tag, @_ ) }
 3369:                } @tags;
 3370: }
 3371: 
 3372: 
 3373: # USAGE: scripttag(scriptcode, [start|end|both]);
 3374: #
 3375: # EXAMPLES: 
 3376: #  - scripttag("alert('Hello World!')", 'both') 
 3377: #    returns:
 3378: #    <script type="text/javascript">
 3379: #    // BEGIN LON-CAPA Internal
 3380: #    alert(Hello World!')
 3381: #    // END LON-CAPA Internal
 3382: #    </script>
 3383: #
 3384: # NOTES:
 3385: # - works currently only for javascripts
 3386: #
 3387: # OUTPUT: 
 3388: # Scriptcode properly enclosed in <script> and CDATA tags (and LC
 3389: # Internal markers if 2nd argument is given)
 3390: sub scripttag {
 3391:     my ( $content, $marker ) = @_;
 3392:     return unless defined $content;
 3393: 
 3394:     my $begin = "\n// BEGIN LON-CAPA Internal\n";
 3395:     my $end   = "\n// END LON-CAPA Internal\n";
 3396: 
 3397:     if ($marker) {
 3398:         $content  = $begin . $content if $marker eq 'start' or $marker eq 'both';
 3399:         $content .= $end              if $marker eq 'end'   or $marker eq 'both';
 3400:     }
 3401: 
 3402:     $content = "\n// <![CDATA[\n$content\n// ]]>\n";
 3403: 
 3404:     return htmltag('script', $content, {type => 'text/javascript'});
 3405: };
 3406: 
 3407: =pod
 3408: 
 3409: =item &list_from_array( \@array, { listattr =>{}, itemattr =>{} } )
 3410: 
 3411: Constructs a XHTML list from \@array.
 3412: 
 3413: input: 
 3414: 
 3415: =over
 3416: 
 3417: =item \@array 
 3418: 
 3419: A reference to the array containing text that will be wrapped in <li></li> tags.
 3420: 
 3421: =item { listattr => {}, itemattr =>{} } 
 3422: 
 3423: Attributes for <ul> and <li> passed in as hash references. 
 3424: See htmltag() for more details.
 3425: 
 3426: =back
 3427:  
 3428: returns: XHTML list as String. 
 3429: 
 3430: =cut   
 3431: 
 3432: # \@items, {listattr => { class => 'abc', id => 'xyx' }, itemattr => {class => 'abc', id => 'xyx'}}
 3433: sub list_from_array {
 3434:     my ($items, $args) = @_;
 3435:     return unless (ref($items) eq 'ARRAY');
 3436:     return unless scalar @$items;
 3437:     my ($ul, $li) = inittags( qw(ul li) );
 3438:     my $listitems = join '', map { $li->($_, $args->{itemattr}) } @$items;
 3439:     return $ul->( $listitems, $args->{listattr} );
 3440: }
 3441: 
 3442: 
 3443: ##############################################
 3444: ##############################################
 3445: 
 3446: # generate_menu
 3447: #
 3448: # Generates html markup for a menu. 
 3449: #
 3450: # Inputs:
 3451: # An array of following structure:
 3452: #   ({	categorytitle => 'Categorytitle',
 3453: #	items => [
 3454: #		    {	
 3455: #           linktext    =>	'Text to be displayed',
 3456: #			url	        =>	'URL the link is pointing to, i.e. /adm/site?action=dosomething',
 3457: #			permission  =>	'Contains permissions as returned from lonnet::allowed(),
 3458: #					         must evaluate to true in order to activate the link',
 3459: #			icon        =>  'icon filename',
 3460: #			alttext	    =>	'alt text for the icon',
 3461: #			help	    =>	'Name of the corresponding helpfile',
 3462: #			linktitle   =>	'Description of the link (used for title tag)'
 3463: #		    },
 3464: #		    ...
 3465: #		]
 3466: #   }, 
 3467: #   ...
 3468: #   )
 3469: #
 3470: # Outputs: A scalar containing the html markup for the menu.
 3471: 
 3472: sub generate_menu {
 3473:     my @menu = @_;
 3474:     # subs for specific html elements
 3475:     my ($h3, $div, $ul, $li, $a, $img) = inittags( qw(h3 div ul li a img) ); 
 3476:     
 3477:     my @categories; # each element represents the entire markup for a category
 3478:    
 3479:     foreach my $category (@menu) {
 3480:         my @links;  # contains the links for the current $category
 3481:         foreach my $link (@{$$category{items}}) {
 3482:             next unless $$link{permission};
 3483:             
 3484:             # create the markup for the current $link and push it into @links.
 3485:             # each entry consists of an image and a text optionally followed 
 3486:             # by a help link.
 3487:             my $src;
 3488:             if ($$link{icon} ne '') {
 3489:                 $src = '/res/adm/pages/'.$$link{icon};
 3490:             }
 3491:             push(@links,$li->(
 3492:                         $a->(
 3493:                             $img->("", {
 3494:                                 class => "LC_noBorder LC_middle",
 3495:                                 src   => $src,
 3496:                                 alt   => mt(defined($$link{alttext}) ?
 3497:                                 $$link{alttext} : $$link{linktext})
 3498:                             }), {
 3499:                             href  => $$link{url},
 3500:                             title => mt($$link{linktitle}),
 3501:                             class => 'LC_menubuttons_link'
 3502:                             }).
 3503:                         $a->(mt($$link{linktext}), {
 3504:                             href  => $$link{url},
 3505:                             title => mt($$link{linktitle}),
 3506:                             class => "LC_menubuttons_link"
 3507:                             }).
 3508:                          (defined($$link{help}) ? 
 3509:                          Apache::loncommon::help_open_topic($$link{help}) : ''),
 3510:                          {class => "LC_menubuttons_inline_text"}));
 3511:         }
 3512: 
 3513:         # wrap categorytitle in <h3>, concatenate with 
 3514:         # joined and in <ul> tags wrapped @links
 3515:         # and wrap everything in an enclosing <div> and push it into
 3516:         # @categories
 3517:         # such that each element looks like:
 3518:         # <div><h3>title</h3><ul><li>...</li>...</ul></div>
 3519:         # the category won't be added if there aren't any links
 3520:         push(@categories, 
 3521:             $div->($h3->(mt($$category{categorytitle}), {class=>"LC_hcell"}).
 3522:             $ul->(join('' ,@links),  {class =>"LC_ListStyleNormal" }),
 3523:             {class=>"LC_Box LC_400Box"})) if scalar(@links);
 3524:     }
 3525: 
 3526:     # wrap the joined @categories in another <div> (column layout)
 3527:     return $div->(join('', @categories), {class => "LC_columnSection"});
 3528: }
 3529: 
 3530: ##############################################
 3531: ##############################################
 3532: 
 3533: =pod
 3534: 
 3535: =item &start_funclist()
 3536: 
 3537: Start list of available functions
 3538: 
 3539: Typically used to offer a simple list of available functions
 3540: at top or bottom of page.
 3541: All available functions/actions for the current page
 3542: should be included in this list.
 3543: 
 3544: If the optional headline text is not provided, a default text will be used.
 3545: 
 3546: 
 3547: Related routines:
 3548: =over 4
 3549: add_item_funclist
 3550: end_funclist
 3551: =back
 3552: 
 3553: 
 3554: Inputs: (optional) headline text
 3555: 
 3556: Returns: HTML code with function list start
 3557: 
 3558: =cut
 3559: 
 3560: ##############################################
 3561: ##############################################
 3562: 
 3563: sub start_funclist {
 3564:     my($legendtext)=@_;
 3565:     $legendtext=&mt('Functions') if !$legendtext;
 3566:     return '<ul class="LC_funclist"><li style="font-weight:bold; margin-left:0.8em;">'.$legendtext.'</li>'."\n";
 3567: }
 3568: 
 3569: 
 3570: ##############################################
 3571: ##############################################
 3572: 
 3573: =pod
 3574: 
 3575: =item &add_item_funclist()
 3576: 
 3577: Adds an item to the list of available functions
 3578: 
 3579: Related routines:
 3580: =over 4
 3581: start_funclist
 3582: end_funclist
 3583: =back
 3584: 
 3585: Inputs: content item with text and link to function
 3586: 
 3587: Returns: HTML code with list item for funclist
 3588: 
 3589: =cut
 3590: 
 3591: ##############################################
 3592: ##############################################
 3593: 
 3594: sub add_item_funclist {
 3595:     my($content) = @_;
 3596:     return '<li>'.$content.'</li>'."\n";
 3597: }
 3598: 
 3599: =pod
 3600: 
 3601: =item &end_funclist()
 3602: 
 3603: End list of available functions
 3604: 
 3605: Related routines:
 3606: =over 4
 3607: start_funclist
 3608: add_item_funclist
 3609: =back
 3610: 
 3611: Inputs: ./.
 3612: 
 3613: Returns: HTML code with function list end
 3614: =cut
 3615: 
 3616: sub end_funclist {
 3617:     return "</ul>\n";
 3618: }
 3619: 
 3620: =pod
 3621: 
 3622: =item &funclist_from_array( \@array, {legend => 'text for legend'} )
 3623: 
 3624: Constructs a XHTML list from \@array with the first item being visually
 3625: highlighted and set to the value of legend or 'Functions' if legend is
 3626: empty. 
 3627: 
 3628: =over
 3629: 
 3630: =item \@array
 3631: 
 3632: A reference to the array containing text that will be wrapped in <li></li> tags.
 3633: 
 3634: =item { legend => 'text' }
 3635: 
 3636: A string that's used as visually highlighted first item. 'Functions' is used if
 3637: it's value evaluates to false.
 3638: 
 3639: =back
 3640:  
 3641: returns: XHTML list as string. 
 3642: 
 3643: =back
 3644: 
 3645: =cut  
 3646: 
 3647: sub funclist_from_array {
 3648:     my ($items, $args) = @_;
 3649:     return unless(ref($items) eq 'ARRAY');
 3650:     $args->{legend} ||= mt('Functions');
 3651:     return list_from_array( [$args->{legend}, @$items], 
 3652:                { listattr => {class => 'LC_funclist'} });
 3653: }   
 3654: 
 3655: =pod
 3656: 
 3657: =item &actionbox( \@array )
 3658: 
 3659: Constructs a XHTML list from \@array with the first item being visually
 3660: highlighted and set to the value 'Actions'. The list is wrapped in a division.
 3661: 
 3662: The actionlist is used to offer contextual actions, mostly at the bottom
 3663: of a page, on which the outcome of an processed action is shown,
 3664: e.g. a file operation in Authoring Space.
 3665: 
 3666: =over
 3667: 
 3668: =item \@array
 3669: 
 3670: A reference to the array containing text. Details: sub funclist_from_array
 3671: 
 3672: =back
 3673:  
 3674: Returns: XHTML div as string. 
 3675: 
 3676: =back
 3677: 
 3678: =cut  
 3679: 
 3680: sub actionbox {
 3681:     my ($items) = @_;
 3682:     return unless(ref($items) eq 'ARRAY');
 3683:     return
 3684:         '<div class="LC_actionbox">'
 3685:        .&funclist_from_array($items, {legend => &mt('Actions')})
 3686:        .'</div>';
 3687: }
 3688: 
 3689: 1;
 3690: 
 3691: __END__

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>