--- loncom/interface/lonhtmlcommon.pm	2010/10/04 19:19:15	1.253.2.3
+++ loncom/interface/lonhtmlcommon.pm	2010/01/24 03:56:09	1.262
@@ -1,7 +1,7 @@
 # The LearningOnline Network with CAPA
 # a pile of common html routines
 #
-# $Id: lonhtmlcommon.pm,v 1.253.2.3 2010/10/04 19:19:15 raeburn Exp $
+# $Id: lonhtmlcommon.pm,v 1.262 2010/01/24 03:56:09 raeburn Exp $
 #
 # Copyright Michigan State University Board of Trustees
 #
@@ -66,7 +66,7 @@ use LONCAPA;
 sub coursepreflink {
    my ($text,$category)=@_;
    if (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
-      return '<a href="/adm/courseprefs?phase=display&actions='.$category.'">'.$text.'</a>';
+      return '<a href="'.&HTML::Entities::encode("/adm/courseprefs?phase=display&actions=$category",'<>&"').'">'.$text.'</a>';
    } else {
       return '';
    }
@@ -81,8 +81,6 @@ sub raw_href_to_link {
 ##############################################
 ##############################################
 
-=pod
-
 =item confirm_success
 
 Successful completion of an operation message
@@ -139,7 +137,6 @@ ENDDRAGMATH
 
 Javascript used to open pop-up window containing dragmath applet which 
 can be used to paste LaTeX into a textarea.
- 
 =cut
 
 sub dragmath_js {
@@ -383,7 +380,8 @@ dname_hour, dname_min, and dname_sec.
 
 The current setting for this time parameter.  A unix format time
 (time in seconds since the beginning of Jan 1st, 1970, GMT.  
-An undefined value is taken to indicate the value is the current time.
+An undefined value is taken to indicate the value is the current time
+unless it is requested to leave it empty. See $includeempty.
 Also, to be explicit, a value of 'now' also indicates the current time.
 
 =item $special
@@ -393,6 +391,9 @@ the date_setter.  See lonparmset for exa
 
 =item $includeempty 
 
+If it is set (true) and no date/time value is provided,
+the date/time fields are left empty.
+
 =item $state
 
 Specifies the initial state of the form elements.  Either 'disabled' or empty.
@@ -412,7 +413,11 @@ sub date_setter {
     my ($formname,$dname,$currentvalue,$special,$includeempty,$state,
         $no_hh_mm_ss,$defhour,$defmin,$defsec,$nolink) = @_;
     my $now = time;
-    my $wasdefined=1;
+
+    my $tzname;
+    my ($sec,$min,$hour,$mday,$month,$year) = ('', '', undef,''.''.'');
+    #other potentially useful values:    wkday,yrday,is_daylight_savings
+
     if (! defined($state) || $state ne 'disabled') {
         $state = '';
     }
@@ -420,33 +425,24 @@ sub date_setter {
         $no_hh_mm_ss = 0;
     }
     if ($currentvalue eq 'now') {
-	$currentvalue = $now;
+        $currentvalue = $now;
     }
-    if ((!defined($currentvalue)) || ($currentvalue eq '')) {
-	$wasdefined=0;
-	if ($includeempty) {
-	    $currentvalue = 0;
-	} else {
-	    $currentvalue = $now;
-	}
+    
+    # Default value: Set empty date field to current time
+    # unless empty inclusion is requested
+    if ((!$includeempty) && (!$currentvalue)) {
+        $currentvalue = $now;
     }
-    # other potentially useful values:     wkday,yrday,is_daylight_savings
-    my $tzname;
-    my ($sec,$min,$hour,$mday,$month,$year)=('','',undef,'','','');
+    # Do we have a date? Split it!
     if ($currentvalue) {
-        ($tzname,$sec,$min,$hour,$mday,$month,$year) = &get_timedates($currentvalue); 
-    }
-    unless ($wasdefined) {
-        ($tzname,$sec,$min,$hour,$mday,$month,$year) = &get_timedates($now);
-	if (($defhour) || ($defmin) || ($defsec)) {
-	    $sec=($defsec?$defsec:0);
-	    $min=($defmin?$defmin:0);
-	    $hour=($defhour?$defhour:0);
-	} elsif (!$includeempty) {
-	    $sec=0;
-	    $min=0;
-	    $hour=0;
-	}
+	($tzname,$sec,$min,$hour,$mday,$month,$year) = &get_timedates($currentvalue);
+
+        #No values provided for hour, min, sec? Use default 0
+        if (($defhour) || ($defmin) || ($defsec)) {
+            $sec  = ($defsec  ? $defsec  : 0);
+            $min  = ($defmin  ? $defmin  : 0);
+            $hour = ($defhour ? $defhour : 0);
+        }
     }
     my $result = "\n<!-- $dname date setting form -->\n";
     $result .= <<ENDJS;
@@ -1241,11 +1237,19 @@ ENDLINK
 }
 
 sub htmlareaheaders {
-    return if (&htmlareablocked());
-    return if (!&htmlareabrowser());
-    return (<<ENDHEADERS);
+	my $s="";
+	if (&htmlareabrowser()) {
+		$s.=(<<ENDEDITOR);
 <script type="text/javascript" src="/fckeditor/fckeditor.js"></script>
-ENDHEADERS
+<script type="text/javascript" src="/ckeditor/ckeditor.js"></script>
+ENDEDITOR
+	}
+    $s.=(<<ENDJQUERY);
+<script type="text/javascript" src="/adm/jQuery/js/jquery-1.3.2.min.js"></script>
+<script type="text/javascript" src="/adm/jQuery/js/jquery-ui-1.7.2.custom.min.js"></script>
+<link rel="stylesheet" type="text/css" href="/adm/jQuery/css/smoothness/jquery-ui-1.7.2.custom.css" />
+ENDJQUERY
+	return $s;
 }
 
 # ----------------------------------------------------------------- Preferences
@@ -1280,20 +1284,102 @@ sub htmlarea_lang {
 sub htmlareaselectactive {
     my @fields=@_;
     unless (&htmlareabrowser()) { return ''; }
-    if (&htmlareablocked()) { return '<br />'.&enablelink(@fields); }
-    my $output='<script type="text/javascript" defer="1">'."\n"
+    #if (&htmlareablocked()) { return '<br />'.&enablelink(@fields); }
+    my $output='<script type="text/javascript" defer="defer">'."\n"
               .'// <![CDATA['."\n";
     my $lang = &htmlarea_lang();
+    $output.='
+    
+    function containsBlockHtml(id) {
+		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);
+    	return (re >= 0);
+    }
+    
+    function startRichEditor(id) {
+    	CKEDITOR.replace(id, 
+    		{
+    			customConfig: "/ckeditor/loncapaconfig.js"
+    		}
+    	);
+    }
+    
+    function destroyRichEditor(id) {
+    	CKEDITOR.instances[id].destroy();
+    }
+    
+    function editorHandler(event) {
+    	var rawid = $(this).attr("id");
+    	var id = new RegExp("LC_rt_(.*)").exec(rawid)[1]
+    	event.preventDefault();
+    	if ($(this).hasClass("LC_enable_rt")) {
+    		startRichEditor(id);
+			$("#LC_rt_"+id).html("<b>&laquo; Plain text</b>");
+			$("#LC_rt_"+id).attr("title", "Disable rich text formatting and edit in plain text");
+			$("#LC_rt_"+id).addClass("LC_disable_rt");
+			$("#LC_rt_"+id).removeClass("LC_enable_rt");
+    	} else {
+			destroyRichEditor(id);
+			$("#LC_rt_"+id).html("<b>Rich formatting &raquo;</b>");
+			$("#LC_rt_"+id).attr("title", "Enable rich text formatting (bold, italic, etc.)");
+			$("#LC_rt_"+id).addClass("LC_enable_rt");
+			$("#LC_rt_"+id).removeClass("LC_disable_rt");
+		}
+	}
+    
+    $(document).ready(function(){
+		$(".LC_richAlwaysOn").each(function() {
+			startRichEditor($(this).attr("id"));
+		});
+		$(".LC_richDetectHtml").each(function() {
+			var id = $(this).attr("id");
+			if(containsBlockHtml(id)) {
+				$(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>");				
+				startRichEditor(id);
+				$("#LC_rt_"+id).click(editorHandler);				
+			}
+			else {
+				$(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>");
+				$("#LC_rt_"+id).click(editorHandler);
+			}
+		});
+		$(".LC_richDefaultOn").each(function() {
+			var id = $(this).attr("id");
+			$(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>");				
+			startRichEditor(id);
+			$("#LC_rt_"+id).click(editorHandler);
+		});
+		$(".LC_richDefaultOff").each(function() {
+			var id = $(this).attr("id");
+			$(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>");
+			$("#LC_rt_"+id).click(editorHandler);			
+		});
+		
+	});
+';
+    
     foreach my $field (@fields) {
-	$output.="
+	$output.='
+	
 {
-    var oFCKeditor = new FCKeditor('$field');
-    oFCKeditor.Config['CustomConfigurationsPath'] = 
-	'/fckeditor/loncapaconfig.js';    
-    oFCKeditor.ReplaceTextarea();
-    oFCKeditor.Config['AutoDetectLanguage'] = false;
-    oFCKeditor.Config['DefaultLanguage'] = '$lang';
-}";
+	$(document).ready(function() {
+		if (!($("#'.$field.'").hasClass("LC_richAlwaysOn"))) {
+			if (!($("#'.$field.'").hasClass("LC_richAlwaysOff"))) {
+				if (!($("#'.$field.'").hasClass("LC_richDetectHtml"))) {
+					if (!($("#'.$field.'").hasClass("LC_richDefaultOn"))) {
+						if (!($("#'.$field.'").hasClass("LC_richDefaultOff"))) {
+							var oFCKeditor = new FCKeditor("'.$field.'");
+							oFCKeditor.Config["CustomConfigurationsPath"] = 
+							"/fckeditor/loncapaconfig.js";    
+							oFCKeditor.ReplaceTextarea();
+							oFCKeditor.Config["AutoDetectLanguage"] = false;
+							oFCKeditor.Config["DefaultLanguage"] = "'.$lang.'";
+						}
+					}
+				}		
+			}
+		}
+    });
+}';
     }
     $output.="\nwindow.status='Activated Editfields';\n"
             .'// ]]>'."\n"
@@ -1378,62 +1464,51 @@ returns: nothing
         # The first one should be the course or a menu link
         if (!defined($menulink)) { $menulink=1; }
         if ($menulink) {
-            if ($menulink eq '_nomenu') {
-                return unless($last);
+            my $description = 'Menu';
+            my $no_mt_descr = 0;
+            if (exists($env{'request.course.id'}) && 
+                $env{'request.course.id'} ne '') {
+                $description = 
+                    $env{'course.'.$env{'request.course.id'}.'.description'};
+                $no_mt_descr = 1;
+            }
+            $menulink =  {  href   =>'/adm/menu',
+                            title  =>'Go to main menu',
+                            target =>'_top',
+                            text   =>$description,
+                            no_mt  =>$no_mt_descr, };
+            if($last) {
+                #$last set, so we have some crumbs
+                unshift(@Crumbs,$menulink);
             } else {
-                my $description = 'Menu';
-                my $no_mt_descr = 0;
-                if ((exists($env{'request.course.id'})) &&
-                    ($env{'request.course.id'} ne '') &&
-                    ($env{'course.'.$env{'request.course.id'}.'.description'} ne '')) {
-                    $description =
-                        $env{'course.'.$env{'request.course.id'}.'.description'};
-                    $no_mt_descr = 1;
-                }
-                $menulink =  {  href   =>'/adm/menu',
-                                title  =>'Go to main menu',
-                                target =>'_top',
-                                text   =>$description,
-                                no_mt  =>$no_mt_descr, };
-                if($last) {
-                    #$last set, so we have some crumbs
-                    unshift(@Crumbs,$menulink);
-                } else {
-                    #only menulink crumb present
-                    $last = $menulink;
-                }
+                #only menulink crumb present
+                $last = $menulink;
             }
         }
         my $links = join "", 
-                 map {
-                     $faq  = $_->{'faq'}  if (exists($_->{'faq'}));
-                     $bug  = $_->{'bug'}  if (exists($_->{'bug'}));
-                     $help = $_->{'help'} if (exists($_->{'help'}));
-
-                     my $result = $_->{no_mt} ? $_->{text} : mt($_->{text});
-
-                     if ($_->{href}){
-                         $result = htmltag( 'a', $result, 
-                                           { 
-                                               href   => $_->{href},
-                                               title  => $_->{no_mt} ? 
-                                                $_->{title} : mt($_->{title}),
-                                               target => $_->{target},
-                                           });
-                     }
+             map {
+                 $faq  = $_->{'faq'}  if (exists($_->{'faq'}));
+                 $bug  = $_->{'bug'}  if (exists($_->{'bug'}));
+                 $help = $_->{'help'} if (exists($_->{'help'}));
+
+                 my $result = $_->{no_mt} ? $_->{text} : mt($_->{text});
+
+                 if ($_->{href}){
+                     $result = htmltag( 'a', $result, 
+                       { href   => $_->{href},
+                         title  => $_->{no_mt} ? $_->{title} : mt($_->{title}),
+                         target => $_->{target}, });
+                 }
 
-                     $result = htmltag( 'li', "$result $crumbsymbol");
-                 } @Crumbs;
+                 $result = htmltag( 'li', "$result $crumbsymbol");
+             } @Crumbs;
 
         #should the last Element be translated?
 
-        my $lasttext = $last->{'no_mt'} ? $last->{'text'}
+        my $lasttext = $last->{'no_mt'} ? $last->{'text'} 
                      : mt( $last->{'text'} );
 
-        # last breadcrumb is the first order heading of a page
-        # for course breadcrumbs it's just bold
-        $links .= htmltag( 'li', htmltag($CourseBreadcrumbs ? 'b' : 'h1',
-                $lasttext), {title => $lasttext});
+        $links .= htmltag( 'li', htmltag('b', $lasttext), {title => $lasttext});
 
         my $icons = '';
         $faq  = $last->{'faq'}  if (exists($last->{'faq'}));
@@ -1493,24 +1568,24 @@ returns: nothing
 
 Adds $html to $category of the breadcrumb toolbar container.
 
-$html is usually a link to a page that invokes a function on the currently
+$html is usually a link to a page that invokes a function on the currently 
 displayed data (e.g. print when viewing a problem)
 
-Currently there are 3 possible values for $category:
+Currently there are 3 possible values for $category: 
 
-=over
+=over 
 
-=item navigation
+=item navigation 
 left of breadcrumbs line
 
-=item tools
+=item tools 
 right of breadcrumbs line
 
-=item advtools
-advanced tools shown in a separate box below breadcrumbs line
+=item advtools 
+advanced tools shown in a separate box below breadcrumbs line 
 
 =back
-
+ 
 returns: nothing
 
 =cut
@@ -1518,16 +1593,16 @@ returns: nothing
     sub add_breadcrumb_tool {
         my ($category, @html) = @_;
         return unless @html;
-        if (!defined(%tools)) {
+        if (!defined(%tools)) { 
             %tools = ( navigation => [], tools => [], advtools => []);
         }
 
         #this cleans data received from lonmenu::innerregister
         @html = grep {defined $_ && $_ ne ''} @html;
-        for (@html) {
-            s/align="(right|left)"//;
-            s/<span.*?\/span>// if $category ne 'advtools';
-        }
+        for (@html) { 
+            s/align="(right|left)"//; 
+            s/<span.*?\/span>// if $category ne 'advtools'; 
+        } 
 
         push @{$tools{$category}}, @html;
     }
@@ -1546,10 +1621,10 @@ returns: nothing
 
 =item render_tools(\$breadcrumbs)
 
-Creates html for breadcrumb tools (categories navigation and tools) and inserts
+Creates html for breadcrumb tools (categories navigation and tools) and inserts 
 \$breadcrumbs at the correct position.
 
-input: \$breadcrumbs - a reference to the string containing prepared
+input: \$breadcrumbs - a reference to the string containing prepared 
 breadcrumbs.
 
 returns: nothing
@@ -1560,20 +1635,20 @@ returns: nothing
         my ($breadcrumbs) = @_;
         return unless defined %tools;
 
-        my $navigation = list_from_array($tools{navigation},
+        my $navigation = list_from_array($tools{navigation}, 
                    { listattr => { class=>"LC_breadcrumb_tools_navigation" } });
-        my $tools = list_from_array($tools{tools},
+        my $tools = list_from_array($tools{tools}, 
                    { listattr => { class=>"LC_breadcrumb_tools_tools" } });
-        $$breadcrumbs = list_from_array([$navigation, $tools, $$breadcrumbs],
+        $$breadcrumbs = list_from_array([$navigation, $tools, $$breadcrumbs], 
                    { listattr => { class=>'LC_breadcrumb_tools_outerlist' } });
     }
 
 =item render_advtools(\$breadcrumbs)
 
-Creates html for advanced tools (category advtools) and inserts \$breadcrumbs
+Creates html for advanced tools (category advtools) and inserts \$breadcrumbs 
 at the correct position.
 
-input: \$breadcrumbs - a reference to the string containing prepared
+input: \$breadcrumbs - a reference to the string containing prepared 
 breadcrumbs (after render_tools call).
 
 returns: nothing
@@ -1581,7 +1656,7 @@ returns: nothing
 
     sub render_advtools {
         my ($breadcrumbs) = @_;
-        return unless     (defined $tools{'advtools'})
+        return unless     (defined $tools{'advtools'}) 
                       and (scalar(@{$tools{'advtools'}}) > 0);
 
         $$breadcrumbs .= Apache::loncommon::head_subbox(
@@ -1719,6 +1794,7 @@ ENDTWO
 
 } # End: row_count block for pick_box
 
+
 sub role_select_row {
     my ($roles,$title,$css_class,$show_separate_custom,$cdom,$cnum) = @_;
     my $crstype = 'Course';
@@ -2299,29 +2375,28 @@ sub scripttag {
 
 Constructs a XHTML list from \@array.
 
-input:
+input: 
 
 =over
 
-=item \@array
+=item \@array 
 
 A reference to the array containing text that will be wrapped in <li></li> tags.
 
-=item { listattr => {}, itemattr =>{} }
+=item { listattr => {}, itemattr =>{} } 
 
-Attributes for <ul> and <li> passed in as hash references.
+Attributes for <ul> and <li> passed in as hash references. 
 See htmltag() for more details.
 
 =back
+ 
+returns: XHTML list as String. 
 
-returns: XHTML list as String.
-
-=cut
+=cut   
 
 # \@items, {listattr => { class => 'abc', id => 'xyx' }, itemattr => {class => 'abc', id => 'xyx'}}
 sub list_from_array {
     my ($items, $args) = @_;
-    return unless scalar @$items;
     my ($ul, $li) = inittags( qw(ul li) );
     my $listitems = join '', map { $li->($_, $args->{itemattr}) } @$items;
     return $ul->( $listitems, $args->{listattr} );
@@ -2372,15 +2447,11 @@ sub generate_menu {
             # create the markup for the current $link and push it into @links.
             # each entry consists of an image and a text optionally followed 
             # by a help link.
-            my $src;
-            if ($$link{icon} ne '') {
-                $src = '/res/adm/pages/'.$$link{icon};
-            }
             push(@links,$li->(
                         $a->(
                             $img->("", {
                                 class => "LC_noBorder LC_middle",
-                                src   => $src,
+                                src   => "/res/adm/pages/$$link{icon}",
                                 alt   => mt(defined($$link{alttext}) ?
                                 $$link{alttext} : $$link{linktext})
                             }), {
@@ -2510,7 +2581,7 @@ sub end_funclist {
 
 Constructs a XHTML list from \@array with the first item being visually
 highlighted and set to the value of legend or 'Functions' if legend is
-empty.
+empty. 
 
 =over
 
@@ -2524,19 +2595,19 @@ A string that's used as visually highlig
 it's value evaluates to false.
 
 =back
-
-returns: XHTML list as string.
+ 
+returns: XHTML list as string. 
 
 =back
 
-=cut
+=cut  
 
 sub funclist_from_array {
     my ($items, $args) = @_;
     $args->{legend} ||= mt('Functions');
-    return list_from_array( [$args->{legend}, @$items],
+    return list_from_array( [$args->{legend}, @$items], 
                { listattr => {class => 'LC_funclist'} });
-}
+}   
 
 1;