File:  [LON-CAPA] / loncom / interface / lonhtmlcommon.pm
Revision 1.318: download - view: text, annotated - select for diffs
Mon Jun 4 16:59:00 2012 UTC (12 years ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 1320. Show "return to last location" link from Authoring Space when
  "Edit" icon/link was used in course.

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

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