Index: /trunk/trac-hacks/irclogsplugin/irclogs/web_ui.py
===================================================================
--- /trunk/trac-hacks/irclogsplugin/irclogs/web_ui.py	(revision 237)
+++ /trunk/trac-hacks/irclogsplugin/irclogs/web_ui.py	(revision 237)
@@ -0,0 +1,363 @@
+# -*- coding: utf-8 -*-
+import os
+import re
+import calendar
+import pytz
+import time
+
+from time import strptime
+from trac.util.datefmt import localtz
+from datetime import datetime
+from calendar import month_name
+
+from trac.core import *
+from trac.perm import IPermissionRequestor
+from trac.config import Option, ListOption
+from trac.web.chrome import INavigationContributor, ITemplateProvider, \
+                            add_stylesheet, add_script
+from trac.web.main import IRequestHandler
+from trac.util.html import escape, html, Markup
+from trac.util.text import to_unicode
+from trac.util.datefmt import utc
+from pyndexter import Framework, READWRITE
+from pyndexter.util import quote
+
+from genshi.builder import tag
+
+class IrcLogsView(Component):
+    implements(INavigationContributor, ITemplateProvider, IRequestHandler, \
+               IPermissionRequestor)
+    _url_re = re.compile(r'^/irclogs(/(?P<year>\d{4})(/(?P<month>\d{2})'
+                         r'(/(?P<day>\d{2}))?)?)?(/(?P<feed>feed)(/(?P<feed_count>\d+?))?)?/?$')
+# TODO: make the line format somewhat configurable
+# Uncomment the following line if using a pipe as a divider and a space
+# between the date adn time.  Make sure to comment out the existing
+# _line_re.
+#    _line_re = re.compile('%s %s \|  (%s)$' % (
+    _line_re = re.compile('%sT%s  (%s)$' % (
+        r'(?P<date>\d{4}-\d{2}-\d{2})',
+        r'(?P<time>\d{2}:\d{2}:\d{2})',
+        '|'.join([
+            r'(<(?P<c_nickname>.*?)> (?P<c_text>.*?))',
+            r'(\* (?P<a_nickname>.*?) (?P<a_text>.*?))',
+            r'(\*\*\* (?P<s_nickname>.*?) (?P<s_text>.*?))'
+        ]))
+    )
+    charset = Option('irclogs', 'charset', 'utf-8',
+                     doc='Channel charset')
+    file_format = Option('irclogs', 'file_format', '#channel.%Y-%m-%d.log',
+                     doc='Format of a logfile for a given day. Must '
+                             'include %Y, %m and %d. Example: '
+                             '#channel.%Y-%m-%d.log')
+    path = Option('irclogs', 'path', '',
+                  doc='The path where the irc logfiles are')
+    navbutton = Option('irclogs', 'navigation_button', '',
+                     doc="""If not empty an button with this value as caption 
+                            is added to the navigation bar, pointing to the 
+                            irc plugin""")
+    prefix = Option('irclogs', 'prefix', '', doc='IRC Channel name')
+
+    search_db_path = Option('irclogs', 'search_db_path', 
+                            '/tmp/irclogs.idx', 
+                     doc="""A path to the directory where the search index 
+                           resides.  Example: /tmp/irclogs.idx""")
+
+    hidden_users = ListOption('irclogs', 'hidden_users', '', 
+                     doc='A list of users that should be hidden by default')
+
+    # ITemplateProvider methods
+    def get_templates_dirs(self):
+        from pkg_resources import resource_filename
+        return [resource_filename(__name__, 'templates')]
+
+    def get_htdocs_dirs(self):
+        from pkg_resources import resource_filename
+        return [('irclogs', resource_filename(__name__, 'htdocs'))]
+
+    # INavigationContributor methods
+    def get_active_navigation_item(self, req):
+        if self.navbutton.strip():
+            return 'irclogs'
+
+    def get_navigation_items(self, req):
+        if req.perm.has_permission('IRCLOGS_VIEW'):
+            title = self.navbutton.strip()
+            if title:
+                yield 'mainnav', 'irclogs', html.a(title, href=req.href.irclogs())
+
+    # IPermissionHandler methods
+    def get_permission_actions(self):
+        return ['IRCLOGS_VIEW']
+
+    # IRequestHandler methods
+    def match_request(self, req):
+        m = self._url_re.search(req.path_info)
+        if m is None:
+            return False
+        req.args.update(m.groupdict())
+        return True
+
+    def _to_unicode(self, iterable):
+        for line in iterable:
+            yield to_unicode(line, self.charset)
+
+    def _get_file_re(self):
+        return re.compile(r'^%s$' % re.escape(self.file_format)
+              .replace('\\%Y', '(?P<year>\d{4})')
+              .replace('\\%m', '(?P<month>\d{2})')
+              .replace('\\%d', '(?P<day>\d{2})')
+        )
+
+    def _get_filename(self, year, month, day):
+        return os.path.join(self.path, self.file_format
+                .replace('%Y', str(year))
+                .replace('%m', str(month))
+                .replace('%d', str(day))
+        )
+
+    def _render_lines(self, iterable, tz=None):
+        dummy = lambda: {}
+        result = []
+        for line in iterable:
+            d = getattr(self._line_re.search(line), 'groupdict', dummy)()
+            for mode in ('channel', 'action', 'server'):
+                prefix = mode[0]
+                text = d.get('%s_text' % prefix)
+                if not text is None:
+                    nick = d['%s_nickname' % prefix]
+                    break
+            else:
+                continue
+            
+            if nick in self.hidden_users:
+                hidden = "hidden_user"
+            else:
+                hidden = ""
+
+            if not tz is None:
+                utc = pytz.utc
+                server_dt = self._get_tz_datetime(d['date'], d['time'])
+                local_dt = tz.normalize(server_dt.astimezone(tz))
+                local_time = local_dt.strftime("%H:%M:%S")
+                local_date = local_dt.strftime("%Y-%m-%d")
+                utc_dt = utc.normalize(server_dt.astimezone(utc)). \
+                    strftime("UTC%Y-%m-%dT%H:%M:%S")
+            else:
+                local_date = d['date']
+                local_time = d['time']
+                utc_dt = d['time']
+
+            result.append({
+                'date':         local_date,
+                'hidden_user':  hidden,
+                'time':         local_time,
+                'utc_dt':       utc_dt,
+                'mode':         mode,
+                'text':         text,
+                'nickname':     nick,
+                'nickcls':      'nick-%d' % (sum(ord(c) for c in nick) % 8),
+            })
+        return result
+
+    def _generate_calendar(self, req, entries):
+        if not req.args['year'] is None:
+            year = int(req.args['year'])
+        else:
+            year = datetime.now().year
+        if not req.args['month'] is None:
+            month = int(req.args['month'])
+        else:
+            month = datetime.now().month
+        if not req.args['day'] is None:
+            today = int(req.args['day'])
+        else:
+            today = -1
+        this_month_entries = entries.get(year, {}).get(month, {})
+
+        weeks = []
+        for week in calendar.monthcalendar(year, month):
+            w = []
+            for day in week:
+                if not day:
+                    w.append({
+                        'empty':    True
+                    })
+                else:
+                    w.append({
+                        'caption':  day,
+                        'href':     req.href('irclogs', year,
+                                             '%02d' % month, '%02d' % day),
+                        'today':    day == today,
+                        'has_log':  day in this_month_entries
+                    })
+            weeks.append(w)
+
+        next_month_year = year
+        next_month = int(month) + 1
+        if next_month > 12:
+            next_month_year += 1
+            next_month = 1
+        if today > -1:
+            next_month_href = req.href('irclogs', next_month_year,
+                                       '%02d' % next_month, '%02d' % today)
+        else:
+            next_month_href = req.href('irclogs', next_month_year,
+                                       '%02d' % next_month)
+
+        prev_month_year = year
+        prev_month = int(month) - 1
+        if prev_month < 1:
+            prev_month_year -= 1
+            prev_month = 12
+        if today > -1:
+            prev_month_href = req.href('irclogs', prev_month_year,
+                                       '%02d' % prev_month, '%02d' % today)
+        else:
+            prev_month_href = req.href('irclogs', prev_month_year,
+                                       '%02d' % prev_month)
+
+        return {
+            'weeks':        weeks,
+            'year':         {
+                'caption':      year,
+                'href':         req.href('irclogs', year)
+            },
+            'month':        {
+                'caption':      month_name[month],
+                'href':         req.href('irclogs', year, '%02d' % month)
+            },
+            'next_year':    {
+                'caption':      str(year + 1),
+                'href':         req.href('irclogs', year + 1)
+            },
+            'prev_year':    {
+                'caption':      str(year - 1),
+                'href':         req.href('irclogs', year - 1)
+            },
+            'next_month':   {
+                'caption':      '%02d' % next_month,
+                'href':         next_month_href
+            },
+            'prev_month':   {
+                'caption':      '%02d' % prev_month,
+                'href':         prev_month_href
+            },
+        }
+
+    def _get_tz_datetime(self, date, time):
+        return datetime(*strptime(date + "T" +  time, 
+                                  "%Y-%m-%dT%H:%M:%S")[0:6]). \
+                                  replace(tzinfo=localtz)
+
+    def process_request(self, req):
+        req.perm.assert_permission('IRCLOGS_VIEW')
+        add_stylesheet(req, 'irclogs/style.css')
+        add_stylesheet(req, 'irclogs/datePicker.css')
+        add_script(req, 'irclogs/date.js')
+        add_script(req, 'irclogs/jquery.datePicker.js')
+        add_script(req, 'irclogs/irclogs.js')
+        file_re = self._get_file_re()
+
+        context = {}
+        entries = {}
+        context['cal'] = self._generate_calendar(req, entries)
+
+        # list all log files to know what dates are available
+
+        try:
+            files = os.listdir(self.path)
+        except OSError, e:
+            code, message = e
+            context['error'] = True
+            context['message'] = '%s: %s' % (message, e.filename)
+            return 'irclogs.html', context, None
+        
+        if len(files) == 0:
+           context['error'] = True
+           context['message'] = 'No logs exist yet. ' \
+                                'Contact your system administrator.'
+           return 'irclogs.html', context, None
+        
+        files.sort()
+        first_found = True
+        for fn in files:
+            m = file_re.search(fn)
+            if m is None:
+                continue 
+            d = m.groupdict()
+            y = entries.setdefault(int(d['year']), {})
+            m = y.setdefault(int(d['month']), {})
+            m[int(d['day'])] = True
+            if first_found is True:
+                context['start_date'] = '%s/%s/%s' % (d['month'], 
+                                                      d['day'],
+                                                      d['year'])
+                first_found = False
+
+        # default to today if no date is selected
+        # or build lists of available dates if no date is given
+        if req.args['year'] is None:
+            today = datetime.now()
+            req.args['year'] = today.year
+            req.args['month'] = '%02d' % today.month
+            req.args['day'] = '%02d' % today.day
+        elif req.args['month'] is None:
+            months = entries.get(int(req.args['year']), {}).keys()
+            months.sort()
+            context['months'] = [{
+                'caption':      month_name[m],
+                'href':         req.href('irclogs', req.args['year'],
+                                         '%02d' % m)
+            } for m in months]
+            context['year'] = req.args['year']
+            context['viewmode'] = 'months'
+        elif req.args['day'] is None:
+            year = entries.get(int(req.args['year']), {})
+            days = year.get(int(req.args['month']), {}).keys()
+            days.sort()
+            context['days'] = [{
+                'caption':      d,
+                'href':         req.href('irclogs', req.args['year'],
+                                         req.args['month'], '%02d' % d)
+            } for d in days]
+            context['year'] = req.args['year']
+            context['month'] = month_name[int(req.args['month'])]
+            context['viewmode'] = 'days'
+
+        # generate calendar according to log files found
+
+
+        # if day is given, read logfile and build irc log for display
+
+        if req.args['day'] is not None:
+            logfile = self._get_filename(req.args['year'], req.args['month'],
+                                         req.args['day'])
+            context['day'] = req.args['day']
+            context['month'] = req.args['month']
+            context['month_name'] = month_name[int(req.args['month'])]
+            context['year'] = req.args['year']
+            context['viewmode'] = 'day'
+            context['current_date'] = '%s/%s/%s' % (req.args['month'], 
+                                                    req.args['day'], 
+                                                    req.args['year'])
+            context['int_month'] = int(req.args['month'])-1
+
+            if not os.path.exists(logfile):
+                context['missing'] = True
+            else:
+                context['missing'] = False
+                f = file(logfile)
+                try:
+                    context['lines'] = self._render_lines(self._to_unicode(f),
+                                                          req.tz)
+                finally:
+                    f.close()
+
+        # handle if display type is html or an external feed
+        if req.args['feed'] is not None:
+            if not context['missing']:
+                context['lines'] = context['lines'] \
+                                    [:int(req.args.get('feed_count',10))]
+            return 'irclogs_feed.html', context, None 
+        else:
+            return 'irclogs.html', context, None
Index: /trunk/trac-hacks/irclogsplugin/irclogs/htdocs/jquery.dimensions.js
===================================================================
--- /trunk/trac-hacks/irclogsplugin/irclogs/htdocs/jquery.dimensions.js	(revision 17)
+++ /trunk/trac-hacks/irclogsplugin/irclogs/htdocs/jquery.dimensions.js	(revision 17)
@@ -0,0 +1,119 @@
+/* Copyright (c) 2007 Paul Bakaus (paul.bakaus@googlemail.com) and Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
+ * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
+ * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
+ *
+ * $LastChangedDate: 2007-12-20 08:46:55 -0600 (Thu, 20 Dec 2007) $
+ * $Rev: 4259 $
+ *
+ * Version: 1.2
+ *
+ * Requires: jQuery 1.2+
+ */
+
+(function($){
+	
+$.dimensions = {
+	version: '1.2'
+};
+
+// Create innerHeight, innerWidth, outerHeight and outerWidth methods
+$.each( [ 'Height', 'Width' ], function(i, name){
+	
+	// innerHeight and innerWidth
+	$.fn[ 'inner' + name ] = function() {
+		if (!this[0]) return;
+		
+		var torl = name == 'Height' ? 'Top'    : 'Left',  // top or left
+		    borr = name == 'Height' ? 'Bottom' : 'Right'; // bottom or right
+		
+		return this.is(':visible') ? this[0]['client' + name] : num( this, name.toLowerCase() ) + num(this, 'padding' + torl) + num(this, 'padding' + borr);
+	};
+	
+	// outerHeight and outerWidth
+	$.fn[ 'outer' + name ] = function(options) {
+		if (!this[0]) return;
+		
+		var torl = name == 'Height' ? 'Top'    : 'Left',  // top or left
+		    borr = name == 'Height' ? 'Bottom' : 'Right'; // bottom or right
+		
+		options = $.extend({ margin: false }, options || {});
+		
+		var val = this.is(':visible') ? 
+				this[0]['offset' + name] : 
+				num( this, name.toLowerCase() )
+					+ num(this, 'border' + torl + 'Width') + num(this, 'border' + borr + 'Width')
+					+ num(this, 'padding' + torl) + num(this, 'padding' + borr);
+		
+		return val + (options.margin ? (num(this, 'margin' + torl) + num(this, 'margin' + borr)) : 0);
+	};
+});
+
+// Create scrollLeft and scrollTop methods
+$.each( ['Left', 'Top'], function(i, name) {
+	$.fn[ 'scroll' + name ] = function(val) {
+		if (!this[0]) return;
+		
+		return val != undefined ?
+		
+			// Set the scroll offset
+			this.each(function() {
+				this == window || this == document ?
+					window.scrollTo( 
+						name == 'Left' ? val : $(window)[ 'scrollLeft' ](),
+						name == 'Top'  ? val : $(window)[ 'scrollTop'  ]()
+					) :
+					this[ 'scroll' + name ] = val;
+			}) :
+			
+			// Return the scroll offset
+			this[0] == window || this[0] == document ?
+				self[ (name == 'Left' ? 'pageXOffset' : 'pageYOffset') ] ||
+					$.boxModel && document.documentElement[ 'scroll' + name ] ||
+					document.body[ 'scroll' + name ] :
+				this[0][ 'scroll' + name ];
+	};
+});
+
+$.fn.extend({
+	position: function() {
+		var left = 0, top = 0, elem = this[0], offset, parentOffset, offsetParent, results;
+		
+		if (elem) {
+			// Get *real* offsetParent
+			offsetParent = this.offsetParent();
+			
+			// Get correct offsets
+			offset       = this.offset();
+			parentOffset = offsetParent.offset();
+			
+			// Subtract element margins
+			offset.top  -= num(elem, 'marginTop');
+			offset.left -= num(elem, 'marginLeft');
+			
+			// Add offsetParent borders
+			parentOffset.top  += num(offsetParent, 'borderTopWidth');
+			parentOffset.left += num(offsetParent, 'borderLeftWidth');
+			
+			// Subtract the two offsets
+			results = {
+				top:  offset.top  - parentOffset.top,
+				left: offset.left - parentOffset.left
+			};
+		}
+		
+		return results;
+	},
+	
+	offsetParent: function() {
+		var offsetParent = this[0].offsetParent;
+		while ( offsetParent && (!/^body|html$/i.test(offsetParent.tagName) && $.css(offsetParent, 'position') == 'static') )
+			offsetParent = offsetParent.offsetParent;
+		return $(offsetParent);
+	}
+});
+
+function num(el, prop) {
+	return parseInt($.curCSS(el.jquery?el[0]:el,prop,true))||0;
+};
+
+})(jQuery);
Index: /trunk/trac-hacks/irclogsplugin/irclogs/htdocs/datePicker.css
===================================================================
--- /trunk/trac-hacks/irclogsplugin/irclogs/htdocs/datePicker.css	(revision 17)
+++ /trunk/trac-hacks/irclogsplugin/irclogs/htdocs/datePicker.css	(revision 17)
@@ -0,0 +1,123 @@
+
+
+table.jCalendar {
+	border: 1px solid #000;
+	background: #aaa;
+    border-collapse: separate;
+    border-spacing: 2px;
+}
+table.jCalendar th {
+	background: #333;
+	color: #fff;
+	font-weight: bold;
+	padding: 3px 5px;
+	font-family: arial, sans-serif;
+	font-size: 10px;
+}
+table.jCalendar td {
+	background: #ccc;
+	color: #000;
+	padding: 3px 5px;
+	text-align: center;
+	font-family: arial, sans-serif;
+	font-size: 10px;
+
+}
+table.jCalendar td.other-month {
+	background: #ddd;
+	color: #aaa;
+}
+table.jCalendar td.today {
+	background: #666;
+	color: #fff;
+}
+table.jCalendar td.selected {
+	background: #f66;
+	color: #fff;
+}
+table.jCalendar td.selected:hover {
+	background: #f33;
+	color: #fff;
+}
+table.jCalendar td:hover, table.jCalendar td.dp-hover {
+	background: #fff;
+	color: #000;
+}
+table.jCalendar td.disabled, table.jCalendar td.disabled:hover {
+	background: #bbb;
+	color: #888;
+}
+
+/* For the popup */
+
+/* NOTE - you will probably want to style a.dp-choose-date - see how I did it in demo.css */
+
+div.dp-popup {
+	position: relative;
+	background: #ccc;
+	font-size: 10px;
+	font-family: arial, sans-serif;
+	padding: 2px;
+	width: 171px;
+	line-height: 1.2em;
+}
+div#dp-popup {
+	position: absolute;
+	z-index: 199;
+}
+div.dp-popup h2 {
+	font-size: 12px;
+	text-align: center;
+	margin: 2px 0;
+	padding: 0;
+}
+a#dp-close {
+	font-size: 11px;
+	padding: 4px 0;
+	text-align: center;
+	display: block;
+}
+a#dp-close:hover {
+	text-decoration: underline;
+}
+div.dp-popup a {
+	color: #000;
+	text-decoration: none;
+	padding: 3px 2px 0;
+}
+div.dp-popup div.dp-nav-prev {
+	position: absolute;
+	top: 2px;
+	left: 4px;
+	width: 100px;
+}
+div.dp-popup div.dp-nav-prev a {
+	float: left;
+}
+/* Opera needs the rules to be this specific otherwise it doesn't change the cursor back to pointer after you have disabled and re-enabled a link */
+div.dp-popup div.dp-nav-prev a, div.dp-popup div.dp-nav-next a {
+	cursor: pointer;
+}
+div.dp-popup div.dp-nav-prev a.disabled, div.dp-popup div.dp-nav-next a.disabled {
+	cursor: default;
+}
+div.dp-popup div.dp-nav-next {
+	position: absolute;
+	top: 2px;
+	right: 4px;
+	width: 100px;
+}
+div.dp-popup div.dp-nav-next a {
+	float: right;
+}
+div.dp-popup a.disabled {
+	cursor: default;
+	color: #aaa;
+}
+div.dp-popup td {
+	cursor: pointer;
+}
+div.dp-popup td.disabled {
+	cursor: default;
+}
+
Index: /trunk/trac-hacks/irclogsplugin/irclogs/htdocs/jquery.dimensions.min.js
===================================================================
--- /trunk/trac-hacks/irclogsplugin/irclogs/htdocs/jquery.dimensions.min.js	(revision 17)
+++ /trunk/trac-hacks/irclogsplugin/irclogs/htdocs/jquery.dimensions.min.js	(revision 17)
@@ -0,0 +1,12 @@
+/* Copyright (c) 2007 Paul Bakaus (paul.bakaus@googlemail.com) and Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
+ * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
+ * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
+ *
+ * $LastChangedDate: 2007-12-20 08:43:48 -0600 (Thu, 20 Dec 2007) $
+ * $Rev: 4257 $
+ *
+ * Version: 1.2
+ *
+ * Requires: jQuery 1.2+
+ */
+(function($){$.dimensions={version:'1.2'};$.each(['Height','Width'],function(i,name){$.fn['inner'+name]=function(){if(!this[0])return;var torl=name=='Height'?'Top':'Left',borr=name=='Height'?'Bottom':'Right';return this.is(':visible')?this[0]['client'+name]:num(this,name.toLowerCase())+num(this,'padding'+torl)+num(this,'padding'+borr);};$.fn['outer'+name]=function(options){if(!this[0])return;var torl=name=='Height'?'Top':'Left',borr=name=='Height'?'Bottom':'Right';options=$.extend({margin:false},options||{});var val=this.is(':visible')?this[0]['offset'+name]:num(this,name.toLowerCase())+num(this,'border'+torl+'Width')+num(this,'border'+borr+'Width')+num(this,'padding'+torl)+num(this,'padding'+borr);return val+(options.margin?(num(this,'margin'+torl)+num(this,'margin'+borr)):0);};});$.each(['Left','Top'],function(i,name){$.fn['scroll'+name]=function(val){if(!this[0])return;return val!=undefined?this.each(function(){this==window||this==document?window.scrollTo(name=='Left'?val:$(window)['scrollLeft'](),name=='Top'?val:$(window)['scrollTop']()):this['scroll'+name]=val;}):this[0]==window||this[0]==document?self[(name=='Left'?'pageXOffset':'pageYOffset')]||$.boxModel&&document.documentElement['scroll'+name]||document.body['scroll'+name]:this[0]['scroll'+name];};});$.fn.extend({position:function(){var left=0,top=0,elem=this[0],offset,parentOffset,offsetParent,results;if(elem){offsetParent=this.offsetParent();offset=this.offset();parentOffset=offsetParent.offset();offset.top-=num(elem,'marginTop');offset.left-=num(elem,'marginLeft');parentOffset.top+=num(offsetParent,'borderTopWidth');parentOffset.left+=num(offsetParent,'borderLeftWidth');results={top:offset.top-parentOffset.top,left:offset.left-parentOffset.left};}return results;},offsetParent:function(){var offsetParent=this[0].offsetParent;while(offsetParent&&(!/^body|html$/i.test(offsetParent.tagName)&&$.css(offsetParent,'position')=='static'))offsetParent=offsetParent.offsetParent;return $(offsetParent);}});function num(el,prop){return parseInt($.curCSS(el.jquery?el[0]:el,prop,true))||0;};})(jQuery);
Index: /trunk/trac-hacks/irclogsplugin/irclogs/htdocs/jquery.datePicker.js
===================================================================
--- /trunk/trac-hacks/irclogsplugin/irclogs/htdocs/jquery.datePicker.js	(revision 17)
+++ /trunk/trac-hacks/irclogsplugin/irclogs/htdocs/jquery.datePicker.js	(revision 17)
@@ -0,0 +1,1058 @@
+/**
+ * Copyright (c) 2007 Kelvin Luck (http://www.kelvinluck.com/)
+ * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
+ * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
+ *
+ * $Id: jquery.datePicker.js 3739 2007-10-25 13:55:30Z kelvin.luck $
+ **/
+
+(function($){
+    
+	$.fn.extend({
+/**
+ * Render a calendar table into any matched elements.
+ * 
+ * @param Object s (optional) Customize your calendars.
+ * @option Number month The month to render (NOTE that months are zero based). Default is today's month.
+ * @option Number year The year to render. Default is today's year.
+ * @option Function renderCallback A reference to a function that is called as each cell is rendered and which can add classes and event listeners to the created nodes. Default is no callback.
+ * @option Number showHeader Whether or not to show the header row, possible values are: $.dpConst.SHOW_HEADER_NONE (no header), $.dpConst.SHOW_HEADER_SHORT (first letter of each day) and $.dpConst.SHOW_HEADER_LONG (full name of each day). Default is $.dpConst.SHOW_HEADER_SHORT.
+ * @option String hoverClass The class to attach to each cell when you hover over it (to allow you to use hover effects in IE6 which doesn't support the :hover pseudo-class on elements other than links). Default is dp-hover. Pass false if you don't want a hover class.
+ * @type jQuery
+ * @name renderCalendar
+ * @cat plugins/datePicker
+ * @author Kelvin Luck (http://www.kelvinluck.com/)
+ *
+ * @example $('#calendar-me').renderCalendar({month:0, year:2007});
+ * @desc Renders a calendar displaying January 2007 into the element with an id of calendar-me.
+ *
+ * @example
+ * var testCallback = function($td, thisDate, month, year)
+ * {
+ * if ($td.is('.current-month') && thisDate.getDay() == 4) {
+ *		var d = thisDate.getDate();
+ *		$td.bind(
+ *			'click',
+ *			function()
+ *			{
+ *				alert('You clicked on ' + d + '/' + (Number(month)+1) + '/' + year);
+ *			}
+ *		).addClass('thursday');
+ *	} else if (thisDate.getDay() == 5) {
+ *		$td.html('Friday the ' + $td.html() + 'th');
+ *	}
+ * }
+ * $('#calendar-me').renderCalendar({month:0, year:2007, renderCallback:testCallback});
+ * 
+ * @desc Renders a calendar displaying January 2007 into the element with an id of calendar-me. Every Thursday in the current month has a class of "thursday" applied to it, is clickable and shows an alert when clicked. Every Friday on the calendar has the number inside replaced with text.
+ **/
+		renderCalendar  :   function(s)
+		{
+			var dc = function(a)
+			{
+				return document.createElement(a);
+			};
+			
+			s = $.extend(
+				{
+					month			: null,
+					year			: null,
+					renderCallback	: null,
+					showHeader		: $.dpConst.SHOW_HEADER_SHORT,
+					dpController	: null,
+					hoverClass		: 'dp-hover'
+				}
+				, s
+			);
+			
+			if (s.showHeader != $.dpConst.SHOW_HEADER_NONE) {
+				var headRow = $(dc('tr'));
+				for (var i=Date.firstDayOfWeek; i<Date.firstDayOfWeek+7; i++) {
+					var weekday = i%7;
+					var day = Date.dayNames[weekday];
+					headRow.append(
+						jQuery(dc('th')).attr({'scope':'col', 'abbr':day, 'title':day, 'class':(weekday == 0 || weekday == 6 ? 'weekend' : 'weekday')}).html(s.showHeader == $.dpConst.SHOW_HEADER_SHORT ? day.substr(0, 1) : day)
+					);
+				}
+			};
+			
+			var calendarTable = $(dc('table'))
+									.attr(
+										{
+											'cellspacing':2,
+											'className':'jCalendar'
+										}
+									)
+									.append(
+										(s.showHeader != $.dpConst.SHOW_HEADER_NONE ? 
+											$(dc('thead'))
+												.append(headRow)
+											:
+											dc('thead')
+										)
+									);
+			var tbody = $(dc('tbody'));
+			
+			var today = (new Date()).zeroTime();
+			
+			var month = s.month == undefined ? today.getMonth() : s.month;
+			var year = s.year || today.getFullYear();
+			
+			var currentDate = new Date(year, month, 1);
+			
+			
+			var firstDayOffset = Date.firstDayOfWeek - currentDate.getDay() + 1;
+			if (firstDayOffset > 1) firstDayOffset -= 7;
+			var weeksToDraw = Math.ceil(( (-1*firstDayOffset+1) + currentDate.getDaysInMonth() ) /7);
+			currentDate.addDays(firstDayOffset-1);
+			
+			var doHover = function()
+			{
+				if (s.hoverClass) {
+					$(this).addClass(s.hoverClass);
+				}
+			};
+			var unHover = function()
+			{
+				if (s.hoverClass) {
+					$(this).removeClass(s.hoverClass);
+				}
+			};
+			
+			var w = 0;
+			while (w++<weeksToDraw) {
+				var r = jQuery(dc('tr'));
+				for (var i=0; i<7; i++) {
+					var thisMonth = currentDate.getMonth() == month;
+					var d = $(dc('td'))
+								.text(currentDate.getDate() + '')
+								.attr('className', (thisMonth ? 'current-month ' : 'other-month ') +
+													(currentDate.isWeekend() ? 'weekend ' : 'weekday ') +
+													(thisMonth && currentDate.getTime() == today.getTime() ? 'today ' : '')
+								)
+								.hover(doHover, unHover)
+							;
+					if (s.renderCallback) {
+						s.renderCallback(d, currentDate, month, year);
+					}
+					r.append(d);
+					currentDate.addDays(1);
+				}
+				tbody.append(r);
+			}
+			calendarTable.append(tbody);
+			
+			return this.each(
+				function()
+				{
+					$(this).empty().append(calendarTable);
+				}
+			);
+		},
+/**
+ * Create a datePicker associated with each of the matched elements.
+ *
+ * The matched element will receive a few custom events with the following signatures:
+ *
+ * dateSelected(event, date, $td, status)
+ * Triggered when a date is selected. event is a reference to the event, date is the Date selected, $td is a jquery object wrapped around the TD that was clicked on and status is whether the date was selected (true) or deselected (false)
+ * 
+ * dpClosed(event, selected)
+ * Triggered when the date picker is closed. event is a reference to the event and selected is an Array containing Date objects.
+ *
+ * dpMonthChanged(event, displayedMonth, displayedYear)
+ * Triggered when the month of the popped up calendar is changed. event is a reference to the event, displayedMonth is the number of the month now displayed (zero based) and displayedYear is the year of the month.
+ *
+ * dpDisplayed(event, $datePickerDiv)
+ * Triggered when the date picker is created. $datePickerDiv is the div containing the date picker. Use this event to add custom content/ listeners to the popped up date picker.
+ *
+ * @param Object s (optional) Customize your date pickers.
+ * @option Number month The month to render when the date picker is opened (NOTE that months are zero based). Default is today's month.
+ * @option Number year The year to render when the date picker is opened. Default is today's year.
+ * @option String startDate The first date date can be selected.
+ * @option String endDate The last date that can be selected.
+ * @option Boolean inline Whether to create the datePicker as inline (e.g. always on the page) or as a model popup. Default is false (== modal popup)
+ * @option Boolean createButton Whether to create a .dp-choose-date anchor directly after the matched element which when clicked will trigger the showing of the date picker. Default is true.
+ * @option Boolean showYearNavigation Whether to display buttons which allow the user to navigate through the months a year at a time. Default is true.
+ * @option Boolean closeOnSelect Whether to close the date picker when a date is selected. Default is true.
+ * @option Boolean displayClose Whether to create a "Close" button within the date picker popup. Default is false.
+ * @option Boolean selectMultiple Whether a user should be able to select multiple dates with this date picker. Default is false.
+ * @option Boolean clickInput If the matched element is an input type="text" and this option is true then clicking on the input will cause the date picker to appear.
+ * @option Number verticalPosition The vertical alignment of the popped up date picker to the matched element. One of $.dpConst.POS_TOP and $.dpConst.POS_BOTTOM. Default is $.dpConst.POS_TOP.
+ * @option Number horizontalPosition The horizontal alignment of the popped up date picker to the matched element. One of $.dpConst.POS_LEFT and $.dpConst.POS_RIGHT.
+ * @option Number verticalOffset The number of pixels offset from the defined verticalPosition of this date picker that it should pop up in. Default in 0.
+ * @option Number horizontalOffset The number of pixels offset from the defined horizontalPosition of this date picker that it should pop up in. Default in 0.
+ * @option (Function|Array) renderCallback A reference to a function (or an array of seperate functions) that is called as each cell is rendered and which can add classes and event listeners to the created nodes. Each callback function will receive four arguments; a jquery object wrapping the created TD, a Date object containing the date this TD represents, a number giving the currently rendered month and a number giving the currently rendered year. Default is no callback.
+ * @option String hoverClass The class to attach to each cell when you hover over it (to allow you to use hover effects in IE6 which doesn't support the :hover pseudo-class on elements other than links). Default is dp-hover. Pass false if you don't want a hover class.
+ * @type jQuery
+ * @name datePicker
+ * @cat plugins/datePicker
+ * @author Kelvin Luck (http://www.kelvinluck.com/)
+ *
+ * @example $('input.date-picker').datePicker();
+ * @desc Creates a date picker button next to all matched input elements. When the button is clicked on the value of the selected date will be placed in the corresponding input (formatted according to Date.format).
+ *
+ * @example demo/index.html
+ * @desc See the projects homepage for many more complex examples...
+ **/
+		datePicker : function(s)
+		{			
+			if (!$.event._dpCache) $.event._dpCache = [];
+			
+			// initialise the date picker controller with the relevant settings...
+			s = $.extend(
+				{
+					month				: undefined,
+					year				: undefined,
+					startDate			: undefined,
+					endDate				: undefined,
+					inline				: false,
+					renderCallback		: [],
+					createButton		: true,
+					showYearNavigation	: true,
+					closeOnSelect		: true,
+					displayClose		: false,
+					selectMultiple		: false,
+					clickInput			: false,
+					verticalPosition	: $.dpConst.POS_TOP,
+					horizontalPosition	: $.dpConst.POS_LEFT,
+					verticalOffset		: 0,
+					horizontalOffset	: 0,
+					hoverClass			: 'dp-hover'
+				}
+				, s
+			);
+			
+			return this.each(
+				function()
+				{
+					var $this = $(this);
+					var alreadyExists = true;
+					
+					if (!this._dpId) {
+						this._dpId = $.event.guid++;
+						$.event._dpCache[this._dpId] = new DatePicker(this);
+						alreadyExists = false;
+					}
+					
+					if (s.inline) {
+						s.createButton = false;
+						s.displayClose = false;
+						s.closeOnSelect = false;
+						$this.empty();
+					}
+					
+					var controller = $.event._dpCache[this._dpId];
+					
+					controller.init(s);
+					
+					if (!alreadyExists && s.createButton) {
+						// create it!
+						controller.button = $('<a href="#" class="dp-choose-date" title="' + $.dpText.TEXT_CHOOSE_DATE + '">' + $.dpText.TEXT_CHOOSE_DATE + '</a>')
+								.bind(
+									'click',
+									function()
+									{
+										$this.dpDisplay(this);
+										this.blur();
+										return false;
+									}
+								);
+
+						$this.after(controller.button);
+					}
+					if (!alreadyExists && $this.is(':text')) {
+						$this
+							.bind(
+								'dateSelected',
+								function(e, selectedDate, $td)
+								{
+									this.value = selectedDate.asString();
+								}
+							).bind(
+								'change',
+								function()
+								{
+									var d = Date.fromString(this.value);
+									if (d) {
+										controller.setSelected(d, true, true);
+									}
+								}
+							);
+						if (s.clickInput) {
+							$this.bind(
+								'click',
+								function()
+								{
+									$this.dpDisplay();
+								}
+							);
+						}
+						var d = Date.fromString(this.value);
+						if (this.value != '' && d) {
+							controller.setSelected(d, true, true);
+						}
+					}
+					
+					$this.addClass('dp-applied');
+					
+				}
+			)
+		},
+/**
+ * Disables or enables this date picker
+ *
+ * @param Boolean s Whether to disable (true) or enable (false) this datePicker
+ * @type jQuery
+ * @name dpSetDisabled
+ * @cat plugins/datePicker
+ * @author Kelvin Luck (http://www.kelvinluck.com/)
+ *
+ * @example $('.date-picker').datePicker();
+ * $('.date-picker').dpSetDisabled(true);
+ * @desc Prevents this date picker from displaying and adds a class of dp-disabled to it (and it's associated button if it has one) for styling purposes. If the matched element is an input field then it will also set the disabled attribute to stop people directly editing the field.
+ **/
+		dpSetDisabled : function(s)
+		{
+			return _w.call(this, 'setDisabled', s);
+		},
+/**
+ * Updates the first selectable date for any date pickers on any matched elements.
+ *
+ * @param String d A string representing the first selectable date (formatted according to Date.format).
+ * @type jQuery
+ * @name dpSetStartDate
+ * @cat plugins/datePicker
+ * @author Kelvin Luck (http://www.kelvinluck.com/)
+ *
+ * @example $('.date-picker').datePicker();
+ * $('.date-picker').dpSetStartDate('01/01/2000');
+ * @desc Creates a date picker associated with all elements with a class of "date-picker" then sets the first selectable date for each of these to the first day of the millenium.
+ **/
+		dpSetStartDate : function(d)
+		{
+			return _w.call(this, 'setStartDate', d);
+		},
+/**
+ * Updates the last selectable date for any date pickers on any matched elements.
+ *
+ * @param String d A string representing the last selectable date (formatted according to Date.format).
+ * @type jQuery
+ * @name dpSetEndDate
+ * @cat plugins/datePicker
+ * @author Kelvin Luck (http://www.kelvinluck.com/)
+ *
+ * @example $('.date-picker').datePicker();
+ * $('.date-picker').dpSetEndDate('01/01/2010');
+ * @desc Creates a date picker associated with all elements with a class of "date-picker" then sets the last selectable date for each of these to the first Janurary 2010.
+ **/
+		dpSetEndDate : function(d)
+		{
+			return _w.call(this, 'setEndDate', d);
+		},
+/**
+ * Gets a list of Dates currently selected by this datePicker. This will be an empty array if no dates are currently selected or NULL if there is no datePicker associated with the matched element.
+ *
+ * @type Array
+ * @name dpGetSelected
+ * @cat plugins/datePicker
+ * @author Kelvin Luck (http://www.kelvinluck.com/)
+ *
+ * @example $('.date-picker').datePicker();
+ * alert($('.date-picker').dpGetSelected());
+ * @desc Will alert an empty array (as nothing is selected yet)
+ **/
+		dpGetSelected : function()
+		{
+			var c = _getController(this[0]);
+			if (c) {
+				return c.getSelected();
+			}
+			return null;
+		},
+/**
+ * Selects or deselects a date on any matched element's date pickers. Deselcting is only useful on date pickers where selectMultiple==true. Selecting will only work if the passed date is within the startDate and endDate boundries for a given date picker.
+ *
+ * @param String d A string representing the date you want to select (formatted according to Date.format).
+ * @param Boolean v Whether you want to select (true) or deselect (false) this date. Optional - default = true.
+ * @param Boolean m Whether you want the date picker to open up on the month of this date when it is next opened. Optional - default = true.
+ * @type jQuery
+ * @name dpSetSelected
+ * @cat plugins/datePicker
+ * @author Kelvin Luck (http://www.kelvinluck.com/)
+ *
+ * @example $('.date-picker').datePicker();
+ * $('.date-picker').dpSetSelected('01/01/2010');
+ * @desc Creates a date picker associated with all elements with a class of "date-picker" then sets the selected date on these date pickers to the first Janurary 2010. When the date picker is next opened it will display Janurary 2010.
+ **/
+		dpSetSelected : function(d, v, m)
+		{
+			if (v == undefined) v=true;
+			if (m == undefined) m=true;
+			return _w.call(this, 'setSelected', Date.fromString(d), v, m);
+		},
+/**
+ * Sets the month that will be displayed when the date picker is next opened. If the passed month is before startDate then the month containing startDate will be displayed instead. If the passed month is after endDate then the month containing the endDate will be displayed instead.
+ *
+ * @param Number m The month you want the date picker to display. Optional - defaults to the currently displayed month.
+ * @param Number y The year you want the date picker to display. Optional - defaults to the currently displayed year.
+ * @type jQuery
+ * @name dpSetDisplayedMonth
+ * @cat plugins/datePicker
+ * @author Kelvin Luck (http://www.kelvinluck.com/)
+ *
+ * @example $('.date-picker').datePicker();
+ * $('.date-picker').dpSetDisplayedMonth(10, 2008);
+ * @desc Creates a date picker associated with all elements with a class of "date-picker" then sets the selected date on these date pickers to the first Janurary 2010. When the date picker is next opened it will display Janurary 2010.
+ **/
+		dpSetDisplayedMonth : function(m, y)
+		{
+			return _w.call(this, 'setDisplayedMonth', Number(m), Number(y));
+		},
+/**
+ * Displays the date picker associated with the matched elements. Since only one date picker can be displayed at once then the date picker associated with the last matched element will be the one that is displayed.
+ *
+ * @param HTMLElement e An element that you want the date picker to pop up relative in position to. Optional - default behaviour is to pop up next to the element associated with this date picker.
+ * @type jQuery
+ * @name dpDisplay
+ * @cat plugins/datePicker
+ * @author Kelvin Luck (http://www.kelvinluck.com/)
+ *
+ * @example $('#date-picker').datePicker();
+ * $('#date-picker').dpDisplay();
+ * @desc Creates a date picker associated with the element with an id of date-picker and then causes it to pop up.
+ **/
+		dpDisplay : function(e)
+		{
+			return _w.call(this, 'display', e);
+		},
+/**
+ * Sets a function or array of functions that is called when each TD of the date picker popup is rendered to the page
+ *
+ * @param (Function|Array) a A function or an array of functions that are called when each td is rendered. Each function will receive four arguments; a jquery object wrapping the created TD, a Date object containing the date this TD represents, a number giving the currently rendered month and a number giving the currently rendered year.
+ * @type jQuery
+ * @name dpSetRenderCallback
+ * @cat plugins/datePicker
+ * @author Kelvin Luck (http://www.kelvinluck.com/)
+ *
+ * @example $('#date-picker').datePicker();
+ * $('#date-picker').dpSetRenderCallback(function($td, thisDate, month, year)
+ * {
+ * 	// do stuff as each td is rendered dependant on the date in the td and the displayed month and year
+ * });
+ * @desc Creates a date picker associated with the element with an id of date-picker and then creates a function which is called as each td is rendered when this date picker is displayed.
+ **/
+		dpSetRenderCallback : function(a)
+		{
+			return _w.call(this, 'setRenderCallback', a);
+		},
+/**
+ * Sets the position that the datePicker will pop up (relative to it's associated element)
+ *
+ * @param Number v The vertical alignment of the created date picker to it's associated element. Possible values are $.dpConst.POS_TOP and $.dpConst.POS_BOTTOM
+ * @param Number h The horizontal alignment of the created date picker to it's associated element. Possible values are $.dpConst.POS_LEFT and $.dpConst.POS_RIGHT
+ * @type jQuery
+ * @name dpSetPosition
+ * @cat plugins/datePicker
+ * @author Kelvin Luck (http://www.kelvinluck.com/)
+ *
+ * @example $('#date-picker').datePicker();
+ * $('#date-picker').dpSetPosition($.dpConst.POS_BOTTOM, $.dpConst.POS_RIGHT);
+ * @desc Creates a date picker associated with the element with an id of date-picker and makes it so that when this date picker pops up it will be bottom and right aligned to the #date-picker element.
+ **/
+		dpSetPosition : function(v, h)
+		{
+			return _w.call(this, 'setPosition', v, h);
+		},
+/**
+ * Sets the offset that the popped up date picker will have from it's default position relative to it's associated element (as set by dpSetPosition)
+ *
+ * @param Number v The vertical offset of the created date picker.
+ * @param Number h The horizontal offset of the created date picker.
+ * @type jQuery
+ * @name dpSetOffset
+ * @cat plugins/datePicker
+ * @author Kelvin Luck (http://www.kelvinluck.com/)
+ *
+ * @example $('#date-picker').datePicker();
+ * $('#date-picker').dpSetOffset(-20, 200);
+ * @desc Creates a date picker associated with the element with an id of date-picker and makes it so that when this date picker pops up it will be 20 pixels above and 200 pixels to the right of it's default position.
+ **/
+		dpSetOffset : function(v, h)
+		{
+			return _w.call(this, 'setOffset', v, h);
+		},
+/**
+ * Closes the open date picker associated with this element.
+ *
+ * @type jQuery
+ * @name dpClose
+ * @cat plugins/datePicker
+ * @author Kelvin Luck (http://www.kelvinluck.com/)
+ *
+ * @example $('.date-pick')
+ *		.datePicker()
+ *		.bind(
+ *			'focus',
+ *			function()
+ *			{
+ *				$(this).dpDisplay();
+ *			}
+ *		).bind(
+ *			'blur',
+ *			function()
+ *			{
+ *				$(this).dpClose();
+ *			}
+ *		);
+ * @desc Creates a date picker and makes it appear when the relevant element is focused and disappear when it is blurred.
+ **/
+		dpClose : function()
+		{
+			return _w.call(this, '_closeCalendar', false, this[0]);
+		},
+		// private function called on unload to clean up any expandos etc and prevent memory links...
+		_dpDestroy : function()
+		{
+			// TODO - implement this?
+		}
+	});
+	
+	// private internal function to cut down on the amount of code needed where we forward
+	// dp* methods on the jQuery object on to the relevant DatePicker controllers...
+	var _w = function(f, a1, a2, a3)
+	{
+		return this.each(
+			function()
+			{
+				var c = _getController(this);
+				if (c) {
+					c[f](a1, a2, a3);
+				}
+			}
+		);
+	};
+	
+	function DatePicker(ele)
+	{
+		this.ele = ele;
+		
+		// initial values...
+		this.displayedMonth		=	null;
+		this.displayedYear		=	null;
+		this.startDate			=	null;
+		this.endDate			=	null;
+		this.showYearNavigation	=	null;
+		this.closeOnSelect		=	null;
+		this.displayClose		=	null;
+		this.selectMultiple		=	null;
+		this.verticalPosition	=	null;
+		this.horizontalPosition	=	null;
+		this.verticalOffset		=	null;
+		this.horizontalOffset	=	null;
+		this.button				=	null;
+		this.renderCallback		=	[];
+		this.selectedDates		=	{};
+		this.inline				=	null;
+		this.context			=	'#dp-popup';
+	};
+	$.extend(
+		DatePicker.prototype,
+		{	
+			init : function(s)
+			{
+				this.setStartDate(s.startDate);
+				this.setEndDate(s.endDate);
+				this.setDisplayedMonth(Number(s.month), Number(s.year));
+				this.setRenderCallback(s.renderCallback);
+				this.showYearNavigation = s.showYearNavigation;
+				this.closeOnSelect = s.closeOnSelect;
+				this.displayClose = s.displayClose;
+				this.selectMultiple = s.selectMultiple;
+				this.verticalPosition = s.verticalPosition;
+				this.horizontalPosition = s.horizontalPosition;
+				this.hoverClass = s.hoverClass;
+				this.setOffset(s.verticalOffset, s.horizontalOffset);
+				this.inline = s.inline;
+				if (this.inline) {
+					this.context = this.ele;
+					this.display();
+				}
+			},
+			setStartDate : function(d)
+			{
+				if (d) {
+					this.startDate = Date.fromString(d);
+				}
+				if (!this.startDate) {
+					this.startDate = (new Date()).zeroTime();
+				}
+				this.setDisplayedMonth(this.displayedMonth, this.displayedYear);
+			},
+			setEndDate : function(d)
+			{
+				if (d) {
+					this.endDate = Date.fromString(d);
+				}
+				if (!this.endDate) {
+					this.endDate = (new Date('12/31/2999')); // using the JS Date.parse function which expects mm/dd/yyyy
+				}
+				if (this.endDate.getTime() < this.startDate.getTime()) {
+					this.endDate = this.startDate;
+				}
+				this.setDisplayedMonth(this.displayedMonth, this.displayedYear);
+			},
+			setPosition : function(v, h)
+			{
+				this.verticalPosition = v;
+				this.horizontalPosition = h;
+			},
+			setOffset : function(v, h)
+			{
+				this.verticalOffset = parseInt(v) || 0;
+				this.horizontalOffset = parseInt(h) || 0;
+			},
+			setDisabled : function(s)
+			{
+				$e = $(this.ele);
+				$e[s ? 'addClass' : 'removeClass']('dp-disabled');
+				if (this.button) {
+					$but = $(this.button);
+					$but[s ? 'addClass' : 'removeClass']('dp-disabled');
+					$but.attr('title', s ? '' : $.dpText.TEXT_CHOOSE_DATE);
+				}
+				if ($e.is(':text')) {
+					$e.attr('disabled', s ? 'disabled' : '');
+				}
+			},
+			setDisplayedMonth : function(m, y)
+			{
+				if (this.startDate == undefined || this.endDate == undefined) {
+					return;
+				}
+				var s = new Date(this.startDate.getTime());
+				s.setDate(1);
+				var e = new Date(this.endDate.getTime());
+				e.setDate(1);
+				
+				var t;
+				if ((!m && !y) || (isNaN(m) && isNaN(y))) {
+					// no month or year passed - default to current month
+					t = new Date().zeroTime();
+					t.setDate(1);
+				} else if (isNaN(m)) {
+					// just year passed in - presume we want the displayedMonth
+					t = new Date(y, this.displayedMonth, 1);
+				} else if (isNaN(y)) {
+					// just month passed in - presume we want the displayedYear
+					t = new Date(this.displayedYear, m, 1);
+				} else {
+					// year and month passed in - that's the date we want!
+					t = new Date(y, m, 1)
+				}
+				
+				// check if the desired date is within the range of our defined startDate and endDate
+				if (t.getTime() < s.getTime()) {
+					t = s;
+				} else if (t.getTime() > e.getTime()) {
+					t = e;
+				}
+				this.displayedMonth = t.getMonth();
+				this.displayedYear = t.getFullYear();
+			},
+			setSelected : function(d, v, moveToMonth)
+			{
+				if (this.selectMultiple == false) {
+					this.selectedDates = {};
+					$('td.selected', this.context).removeClass('selected');
+				}
+				if (moveToMonth) {
+					this.setDisplayedMonth(d.getMonth(), d.getFullYear());
+				}
+				this.selectedDates[d.toString()] = v;
+			},
+			isSelected : function(d)
+			{
+				return this.selectedDates[d.toString()];
+			},
+			getSelected : function()
+			{
+				var r = [];
+				for(s in this.selectedDates) {
+					if (this.selectedDates[s] == true) {
+						r.push(Date.parse(s));
+					}
+				}
+				return r;
+			},
+			display : function(eleAlignTo)
+			{
+				if ($(this.ele).is('.dp-disabled')) return;
+				/* OPTAROS FORK: calendar should render in the same position regardless of which element is clicked */
+				//eleAlignTo = eleAlignTo || this.ele;
+				if (!eleAlignTo)
+				  eleAlignTo = $(this.ele).next();
+				var c = this;
+				var $ele = $(eleAlignTo);
+				var eleOffset = $ele.offset();
+				
+				var $createIn;
+				var attrs;
+				var attrsCalendarHolder;
+				var cssRules;
+				
+				if (c.inline) {
+					$createIn = $(this.ele);
+					attrs = {
+						'id'		:	'calendar-' + this.ele._dpId,
+						'className'	:	'dp-popup dp-popup-inline'
+					};
+					cssRules = {
+					};
+				} else {
+					$createIn = $('body');
+					attrs = {
+						'id'		:	'dp-popup',
+						'className'	:	'dp-popup'
+					};
+					cssRules = {
+						'top'	:	eleOffset.top + c.verticalOffset,
+						'left'	:	eleOffset.left + c.horizontalOffset
+					};
+					
+					var _checkMouse = function(e)
+					{
+						var el = e.target;
+						var cal = $('#dp-popup')[0];
+						
+						while (true){
+							if (el == cal) {
+								return true;
+							} else if (el == document) {
+								c._closeCalendar();
+								return false;
+							} else {
+								el = $(el).parent()[0];
+							}
+						}
+					};
+					this._checkMouse = _checkMouse;
+				
+					this._closeCalendar(true);
+				}
+				
+				
+				$createIn
+					.append(
+						$('<div></div>')
+							.attr(attrs)
+							.css(cssRules)
+							.append(
+								$('<h2></h2>'),
+								$('<div class="dp-nav-prev"></div>')
+									.append(
+										$('<a class="dp-nav-prev-year" href="#" title="' + $.dpText.TEXT_PREV_YEAR + '">&lt;&lt;</a>')
+											.bind(
+												'click',
+												function()
+												{
+													return c._displayNewMonth.call(c, this, 0, -1);
+												}
+											),
+										$('<a class="dp-nav-prev-month" href="#" title="' + $.dpText.TEXT_PREV_MONTH + '">&lt;</a>')
+											.bind(
+												'click',
+												function()
+												{
+													return c._displayNewMonth.call(c, this, -1, 0);
+												}
+											)
+									),
+								$('<div class="dp-nav-next"></div>')
+									.append(
+										$('<a class="dp-nav-next-year" href="#" title="' + $.dpText.TEXT_NEXT_YEAR + '">&gt;&gt;</a>')
+											.bind(
+												'click',
+												function()
+												{
+													return c._displayNewMonth.call(c, this, 0, 1);
+												}
+											),
+										$('<a class="dp-nav-next-month" href="#" title="' + $.dpText.TEXT_NEXT_MONTH + '">&gt;</a>')
+											.bind(
+												'click',
+												function()
+												{
+													return c._displayNewMonth.call(c, this, 1, 0);
+												}
+											)
+									),
+								$('<div></div>')
+									.attr('className', 'dp-calendar')
+							)
+							.bgIframe()
+						);
+					
+				var $pop = this.inline ? $('.dp-popup', this.context) : $('#dp-popup');
+				
+				if (this.showYearNavigation == false) {
+					$('.dp-nav-prev-year, .dp-nav-next-year', c.context).css('display', 'none');
+				}
+				if (this.displayClose) {
+					$pop.append(
+						$('<a href="#" id="dp-close">' + $.dpText.TEXT_CLOSE + '</a>')
+							.bind(
+								'click',
+								function()
+								{
+									c._closeCalendar();
+									return false;
+								}
+							)
+					);
+				}
+				c._renderCalendar();
+				
+				$(this.ele).trigger('dpDisplayed', $pop);
+				
+				if (!c.inline) {
+					if (this.verticalPosition == $.dpConst.POS_BOTTOM) {
+						$pop.css('top', eleOffset.top + $ele.height() - $pop.height() + c.verticalOffset);
+					}
+					if (this.horizontalPosition == $.dpConst.POS_RIGHT) {
+						$pop.css('left', eleOffset.left + $ele.width() - $pop.width() + c.horizontalOffset);
+					}
+					$(document).bind('mousedown', this._checkMouse);
+				}
+			},
+			setRenderCallback : function(a)
+			{
+				if (a && typeof(a) == 'function') {
+					a = [a];
+				}
+				this.renderCallback = this.renderCallback.concat(a);
+			},
+			cellRender : function ($td, thisDate, month, year) {
+				var c = this.dpController;
+				var d = new Date(thisDate.getTime());
+				
+				// add our click handlers to deal with it when the days are clicked...
+				
+				$td.bind(
+					'click',
+					function()
+					{
+						var $this = $(this);
+						if (!$this.is('.disabled')) {
+							c.setSelected(d, !$this.is('.selected') || !c.selectMultiple);
+							var s = c.isSelected(d);
+							$(c.ele).trigger('dateSelected', [d, $td, s]);
+							$(c.ele).trigger('change');
+							if (c.closeOnSelect) {
+								c._closeCalendar();
+							} else {
+								$this[s ? 'addClass' : 'removeClass']('selected');
+							}
+						}
+					}
+				);
+				
+				if (c.isSelected(d)) {
+					$td.addClass('selected');
+				}
+				
+				// call any extra renderCallbacks that were passed in
+				for (var i=0; i<c.renderCallback.length; i++) {
+					c.renderCallback[i].apply(this, arguments);
+				}
+				
+				
+			},
+			// ele is the clicked button - only proceed if it doesn't have the class disabled...
+			// m and y are -1, 0 or 1 depending which direction we want to go in...
+			_displayNewMonth : function(ele, m, y) 
+			{
+				if (!$(ele).is('.disabled')) {
+					this.setDisplayedMonth(this.displayedMonth + m, this.displayedYear + y);
+					this._clearCalendar();
+					this._renderCalendar();
+					$(this.ele).trigger('dpMonthChanged', [this.displayedMonth, this.displayedYear]);
+				}
+				ele.blur();
+				return false;
+			},
+			_renderCalendar : function()
+			{
+				// set the title...
+				$('h2', this.context).html(Date.monthNames[this.displayedMonth] + ' ' + this.displayedYear);
+				
+				// render the calendar...
+				$('.dp-calendar', this.context).renderCalendar(
+					{
+						month			: this.displayedMonth,
+						year			: this.displayedYear,
+						renderCallback	: this.cellRender,
+						dpController	: this,
+						hoverClass		: this.hoverClass
+					}
+				);
+				
+				// update the status of the control buttons and disable dates before startDate or after endDate...
+				// TODO: When should the year buttons be disabled? When you can't go forward a whole year from where you are or is that annoying?
+				if (this.displayedYear == this.startDate.getFullYear() && this.displayedMonth == this.startDate.getMonth()) {
+					$('.dp-nav-prev-year', this.context).addClass('disabled');
+					$('.dp-nav-prev-month', this.context).addClass('disabled');
+					$('.dp-calendar td.other-month', this.context).each(
+						function()
+						{
+							var $this = $(this);
+							if (Number($this.text()) > 20) {
+								$this.addClass('disabled');
+							}
+						}
+					);
+					var d = this.startDate.getDate();
+					$('.dp-calendar td.current-month', this.context).each(
+						function()
+						{
+							var $this = $(this);
+							if (Number($this.text()) < d) {
+								$this.addClass('disabled');
+							}
+						}
+					);
+				} else {
+					$('.dp-nav-prev-year', this.context).removeClass('disabled');
+					$('.dp-nav-prev-month', this.context).removeClass('disabled');
+					var d = this.startDate.getDate();
+					if (d > 20) {
+						// check if the startDate is last month as we might need to add some disabled classes...
+						var sd = new Date(this.startDate.getTime());
+						sd.addMonths(1);
+						if (this.displayedYear == sd.getFullYear() && this.displayedMonth == sd.getMonth()) {
+							$('dp-calendar td.other-month', this.context).each(
+								function()
+								{
+									var $this = $(this);
+									if (Number($this.text()) < d) {
+										$this.addClass('disabled');
+									}
+								}
+							);
+						}
+					}
+				}
+				if (this.displayedYear == this.endDate.getFullYear() && this.displayedMonth == this.endDate.getMonth()) {
+					$('.dp-nav-next-year', this.context).addClass('disabled');
+					$('.dp-nav-next-month', this.context).addClass('disabled');
+					$('.dp-calendar td.other-month', this.context).each(
+						function()
+						{
+							var $this = $(this);
+							if (Number($this.text()) < 14) {
+								$this.addClass('disabled');
+							}
+						}
+					);
+					var d = this.endDate.getDate();
+					$('.dp-calendar td.current-month', this.context).each(
+						function()
+						{
+							var $this = $(this);
+							if (Number($this.text()) > d) {
+								$this.addClass('disabled');
+							}
+						}
+					);
+				} else {
+					$('.dp-nav-next-year', this.context).removeClass('disabled');
+					$('.dp-nav-next-month', this.context).removeClass('disabled');
+					var d = this.endDate.getDate();
+					if (d < 13) {
+						// check if the endDate is next month as we might need to add some disabled classes...
+						var ed = new Date(this.endDate.getTime());
+						ed.addMonths(-1);
+						if (this.displayedYear == ed.getFullYear() && this.displayedMonth == ed.getMonth()) {
+							$('.dp-calendar td.other-month', this.context).each(
+								function()
+								{
+									var $this = $(this);
+									if (Number($this.text()) > d) {
+										$this.addClass('disabled');
+									}
+								}
+							);
+						}
+					}
+				}
+			},
+			_closeCalendar : function(programatic, ele)
+			{
+				if (!ele || ele == this.ele)
+				{
+					$(document).unbind('mousedown', this._checkMouse);
+					this._clearCalendar();
+					$('#dp-popup a').unbind();
+					$('#dp-popup').empty().remove();
+					if (!programatic) {
+						$(this.ele).trigger('dpClosed', [this.getSelected()]);
+					}
+				}
+			},
+			// empties the current dp-calendar div and makes sure that all events are unbound
+			// and expandos removed to avoid memory leaks...
+			_clearCalendar : function()
+			{
+				// TODO.
+				$('.dp-calendar td', this.context).unbind();
+				$('.dp-calendar', this.context).empty();
+			}
+		}
+	);
+	
+	// static constants
+	$.dpConst = {
+		SHOW_HEADER_NONE	:	0,
+		SHOW_HEADER_SHORT	:	1,
+		SHOW_HEADER_LONG	:	2,
+		POS_TOP				:	0,
+		POS_BOTTOM			:	1,
+		POS_LEFT			:	0,
+		POS_RIGHT			:	1
+	};
+	// localisable text
+	$.dpText = {
+		TEXT_PREV_YEAR		:	'Previous year',
+		TEXT_PREV_MONTH		:	'Previous month',
+		TEXT_NEXT_YEAR		:	'Next year',
+		TEXT_NEXT_MONTH		:	'Next month',
+		TEXT_CLOSE			:	'Close',
+		TEXT_CHOOSE_DATE	:	'&nbsp;&nbsp;&nbsp;'
+	};
+	// version
+	$.dpVersion = '$Id: jquery.datePicker.js 3739 2007-10-25 13:55:30Z kelvin.luck $';
+
+	function _getController(ele)
+	{
+		if (ele._dpId) return $.event._dpCache[ele._dpId];
+		return false;
+	};
+	
+	// make it so that no error is thrown if bgIframe plugin isn't included (allows you to use conditional
+	// comments to only include bgIframe where it is needed in IE without breaking this plugin).
+	if ($.fn.bgIframe == undefined) {
+		$.fn.bgIframe = function() {return this; };
+	};
+
+
+	// clean-up
+	$(window)
+		.bind('unload', function() {
+			var els = $.event._dpCache || [];
+			for (var i in els) {
+				$(els[i].ele)._dpDestroy();
+			}
+		});
+		
+	
+})(jQuery);
Index: /trunk/trac-hacks/irclogsplugin/irclogs/htdocs/style.css
===================================================================
--- /trunk/trac-hacks/irclogsplugin/irclogs/htdocs/style.css	(revision 108)
+++ /trunk/trac-hacks/irclogsplugin/irclogs/htdocs/style.css	(revision 108)
@@ -0,0 +1,145 @@
+div.irclogs div.wrapper {
+    padding: 1em;
+}
+
+div.irclogs table.irclog {
+    border-collapse: collapse;
+    border: 2px solid #ccc;
+    margin-top: 1em;
+    width: 100%;
+}
+
+div.irclogs table.irclog td {
+    padding: 0.3em;
+    border: 1px dotted #bbb;
+}
+
+div.irclogs table.irclog td.time {
+    text-align: left;
+    font-family: monospace;
+    color: #aaa;
+    background-color: #f2f2f2;
+    width: 2.3em;
+    vertical-align: topM
+}
+
+div.irclogs table.irclog td.time a {
+    color: #aaa;
+    text-decoration: none;
+}
+
+div.irclogs table.irclog td.left {
+    text-align: right;
+    font-family: monospace;
+    width: 4em;
+    vertical-align: top;
+}
+
+div.irclogs table.irclog td.right {
+    text-align: left;
+    font-family: monospace;
+    white-space: pre-wrap;
+    white-space: -moz-pre-wrap;
+    white-space: -pre-wrap;
+    white-space: -o-pre-wrap;
+    word-wrap: break-word;
+    _white-space: pre;
+    vertical-align: top;
+}
+
+div.irclogs table.irclog tr.action td.left,
+div.irclogs table.irclog tr.action td.right {
+    color: #0c0;
+    font-style: italic;
+}
+
+div.irclogs table.irclog tr.server td.left,
+div.irclogs table.irclog tr.server td.right {
+    color: #555;
+    font-style: italic;
+}
+
+div.irclogs .nick-0 {color: #555555; }
+div.irclogs .nick-1 {color: #2F8C74; }
+div.irclogs .nick-2 {color: #4545E6; }
+div.irclogs .nick-3 {color: #B037B0; }
+div.irclogs .nick-4 {color: #C33B3B; }
+div.irclogs .nick-5 {color: #1A5555; }
+div.irclogs .nick-6 {color: #D9A641; }
+div.irclogs .nick-7 {color: #3DCC3D; }
+div.irclogs .nick-8 {color: #C73232; }
+
+
+div.irclogs table .has_log {
+    background-color: #f2f2f2;
+}
+div.irclogs table .today {
+    background-color: #ddd;
+    font-weight: bold;
+}
+
+div.irclogs table.minical {
+    background-color: white;
+    border: 2px solid #ccc;
+    padding: 1em;
+    float: right;
+}
+
+div.irclogs table.minical tr.head th {
+    font-weight: bold;
+    border-bottom: 2px solid #ddd;
+}
+
+div.irclogs table.minical tr.days {
+    font-size: 0.8em;
+}
+
+a.dp-choose-date {
+        width: 16px;
+	height: 16px;
+	padding: 0;
+	margin: 5px 0px;
+	text-indent: -2000px;
+	overflow: hidden;
+	background: url(calendar.png) no-repeat; 
+}
+a.dp-choose-date.dp-disabled {
+	background-position: 0 -20px;
+	cursor: default;
+	text-size: 10px;
+}
+input.dp-applied {
+	display: none;
+}
+
+div.irclogs div.navcal {
+	position: relative;
+	float: right;
+	top: -15px;
+}
+
+div.navcal a.previous {
+	margin-right: 20px;
+}
+
+div.navcal a.next {
+	margin-left: 20px;
+}
+
+div.navcal a.link-datepicker {
+	margin-right: 4px;
+}
+
+div.irclogs input#showactions {
+	float: left;
+}
+div#irclog-controls {
+  display: none;
+  padding-left: 10px; 
+  padding-right: 10px;
+  margin-bottom: -15px;
+}
+.irclogs tr.server, .irclogs tr.hidden_user {
+  display:none;
+}
+
Index: /trunk/trac-hacks/irclogsplugin/irclogs/htdocs/date.js
===================================================================
--- /trunk/trac-hacks/irclogsplugin/irclogs/htdocs/date.js	(revision 17)
+++ /trunk/trac-hacks/irclogsplugin/irclogs/htdocs/date.js	(revision 17)
@@ -0,0 +1,467 @@
+/*
+ * Date prototype extensions. Doesn't depend on any
+ * other code. Doens't overwrite existing methods.
+ *
+ * Adds dayNames, abbrDayNames, monthNames and abbrMonthNames static properties and isLeapYear,
+ * isWeekend, isWeekDay, getDaysInMonth, getDayName, getMonthName, getDayOfYear, getWeekOfYear,
+ * setDayOfYear, addYears, addMonths, addDays, addHours, addMinutes, addSeconds methods
+ *
+ * Copyright (c) 2006 JÃ¶rn Zaefferer and Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
+ *
+ * Additional methods and properties added by Kelvin Luck: firstDayOfWeek, dateFormat, zeroTime, asString, fromString -
+ * I've added my name to these methods so you know who to blame if they are broken!
+ * 
+ * Dual licensed under the MIT and GPL licenses:
+ *   http://www.opensource.org/licenses/mit-license.php
+ *   http://www.gnu.org/licenses/gpl.html
+ *
+ */
+
+/**
+ * An Array of day names starting with Sunday.
+ * 
+ * @example dayNames[0]
+ * @result 'Sunday'
+ *
+ * @name dayNames
+ * @type Array
+ * @cat Plugins/Methods/Date
+ */
+Date.dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
+
+/**
+ * An Array of abbreviated day names starting with Sun.
+ * 
+ * @example abbrDayNames[0]
+ * @result 'Sun'
+ *
+ * @name abbrDayNames
+ * @type Array
+ * @cat Plugins/Methods/Date
+ */
+Date.abbrDayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
+
+/**
+ * An Array of month names starting with Janurary.
+ * 
+ * @example monthNames[0]
+ * @result 'January'
+ *
+ * @name monthNames
+ * @type Array
+ * @cat Plugins/Methods/Date
+ */
+Date.monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
+
+/**
+ * An Array of abbreviated month names starting with Jan.
+ * 
+ * @example abbrMonthNames[0]
+ * @result 'Jan'
+ *
+ * @name monthNames
+ * @type Array
+ * @cat Plugins/Methods/Date
+ */
+Date.abbrMonthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
+
+/**
+ * The first day of the week for this locale.
+ *
+ * @name firstDayOfWeek
+ * @type Number
+ * @cat Plugins/Methods/Date
+ * @author Kelvin Luck
+ */
+Date.firstDayOfWeek = 1;
+
+/**
+ * The format that string dates should be represented as (e.g. 'dd/mm/yyyy' for UK, 'mm/dd/yyyy' for US, 'yyyy-mm-dd' for Unicode etc).
+ *
+ * @name format
+ * @type String
+ * @cat Plugins/Methods/Date
+ * @author Kelvin Luck
+ */
+Date.format = 'dd/mm/yyyy';
+//Date.format = 'mm/dd/yyyy';
+//Date.format = 'yyyy-mm-dd';
+//Date.format = 'dd mmm yy';
+
+/**
+ * The first two numbers in the century to be used when decoding a two digit year. Since a two digit year is ambiguous (and date.setYear
+ * only works with numbers < 99 and so doesn't allow you to set years after 2000) we need to use this to disambiguate the two digit year codes.
+ *
+ * @name format
+ * @type String
+ * @cat Plugins/Methods/Date
+ * @author Kelvin Luck
+ */
+Date.fullYearStart = '20';
+
+(function() {
+
+	/**
+	 * Adds a given method under the given name 
+	 * to the Date prototype if it doesn't
+	 * currently exist.
+	 *
+	 * @private
+	 */
+	function add(name, method) {
+		if( !Date.prototype[name] ) {
+			Date.prototype[name] = method;
+		}
+	};
+	
+	/**
+	 * Checks if the year is a leap year.
+	 *
+	 * @example var dtm = new Date("01/12/2008");
+	 * dtm.isLeapYear();
+	 * @result true
+	 *
+	 * @name isLeapYear
+	 * @type Boolean
+	 * @cat Plugins/Methods/Date
+	 */
+	add("isLeapYear", function() {
+		var y = this.getFullYear();
+		return (y%4==0 && y%100!=0) || y%400==0;
+	});
+	
+	/**
+	 * Checks if the day is a weekend day (Sat or Sun).
+	 *
+	 * @example var dtm = new Date("01/12/2008");
+	 * dtm.isWeekend();
+	 * @result false
+	 *
+	 * @name isWeekend
+	 * @type Boolean
+	 * @cat Plugins/Methods/Date
+	 */
+	add("isWeekend", function() {
+		return this.getDay()==0 || this.getDay()==6;
+	});
+	
+	/**
+	 * Check if the day is a day of the week (Mon-Fri)
+	 * 
+	 * @example var dtm = new Date("01/12/2008");
+	 * dtm.isWeekDay();
+	 * @result false
+	 * 
+	 * @name isWeekDay
+	 * @type Boolean
+	 * @cat Plugins/Methods/Date
+	 */
+	add("isWeekDay", function() {
+		return !this.isWeekend();
+	});
+	
+	/**
+	 * Gets the number of days in the month.
+	 * 
+	 * @example var dtm = new Date("01/12/2008");
+	 * dtm.getDaysInMonth();
+	 * @result 31
+	 * 
+	 * @name getDaysInMonth
+	 * @type Number
+	 * @cat Plugins/Methods/Date
+	 */
+	add("getDaysInMonth", function() {
+		return [31,(this.isLeapYear() ? 29:28),31,30,31,30,31,31,30,31,30,31][this.getMonth()];
+	});
+	
+	/**
+	 * Gets the name of the day.
+	 * 
+	 * @example var dtm = new Date("01/12/2008");
+	 * dtm.getDayName();
+	 * @result 'Saturday'
+	 * 
+	 * @example var dtm = new Date("01/12/2008");
+	 * dtm.getDayName(true);
+	 * @result 'Sat'
+	 * 
+	 * @param abbreviated Boolean When set to true the name will be abbreviated.
+	 * @name getDayName
+	 * @type String
+	 * @cat Plugins/Methods/Date
+	 */
+	add("getDayName", function(abbreviated) {
+		return abbreviated ? Date.abbrDayNames[this.getDay()] : Date.dayNames[this.getDay()];
+	});
+
+	/**
+	 * Gets the name of the month.
+	 * 
+	 * @example var dtm = new Date("01/12/2008");
+	 * dtm.getMonthName();
+	 * @result 'Janurary'
+	 *
+	 * @example var dtm = new Date("01/12/2008");
+	 * dtm.getMonthName(true);
+	 * @result 'Jan'
+	 * 
+	 * @param abbreviated Boolean When set to true the name will be abbreviated.
+	 * @name getDayName
+	 * @type String
+	 * @cat Plugins/Methods/Date
+	 */
+	add("getMonthName", function(abbreviated) {
+		return abbreviated ? Date.abbrMonthNames[this.getMonth()] : Date.monthNames[this.getMonth()];
+	});
+
+	/**
+	 * Get the number of the day of the year.
+	 * 
+	 * @example var dtm = new Date("01/12/2008");
+	 * dtm.getDayOfYear();
+	 * @result 11
+	 * 
+	 * @name getDayOfYear
+	 * @type Number
+	 * @cat Plugins/Methods/Date
+	 */
+	add("getDayOfYear", function() {
+		var tmpdtm = new Date("1/1/" + this.getFullYear());
+		return Math.floor((this.getTime() - tmpdtm.getTime()) / 86400000);
+	});
+	
+	/**
+	 * Get the number of the week of the year.
+	 * 
+	 * @example var dtm = new Date("01/12/2008");
+	 * dtm.getWeekOfYear();
+	 * @result 2
+	 * 
+	 * @name getWeekOfYear
+	 * @type Number
+	 * @cat Plugins/Methods/Date
+	 */
+	add("getWeekOfYear", function() {
+		return Math.ceil(this.getDayOfYear() / 7);
+	});
+
+	/**
+	 * Set the day of the year.
+	 * 
+	 * @example var dtm = new Date("01/12/2008");
+	 * dtm.setDayOfYear(1);
+	 * dtm.toString();
+	 * @result 'Tue Jan 01 2008 00:00:00'
+	 * 
+	 * @name setDayOfYear
+	 * @type Date
+	 * @cat Plugins/Methods/Date
+	 */
+	add("setDayOfYear", function(day) {
+		this.setMonth(0);
+		this.setDate(day);
+		return this;
+	});
+	
+	/**
+	 * Add a number of years to the date object.
+	 * 
+	 * @example var dtm = new Date("01/12/2008");
+	 * dtm.addYears(1);
+	 * dtm.toString();
+	 * @result 'Mon Jan 12 2009 00:00:00'
+	 * 
+	 * @name addYears
+	 * @type Date
+	 * @cat Plugins/Methods/Date
+	 */
+	add("addYears", function(num) {
+		this.setFullYear(this.getFullYear() + num);
+		return this;
+	});
+	
+	/**
+	 * Add a number of months to the date object.
+	 * 
+	 * @example var dtm = new Date("01/12/2008");
+	 * dtm.addMonths(1);
+	 * dtm.toString();
+	 * @result 'Tue Feb 12 2008 00:00:00'
+	 * 
+	 * @name addMonths
+	 * @type Date
+	 * @cat Plugins/Methods/Date
+	 */
+	add("addMonths", function(num) {
+		var tmpdtm = this.getDate();
+		
+		this.setMonth(this.getMonth() + num);
+		
+		if (tmpdtm > this.getDate())
+			this.addDays(-this.getDate());
+		
+		return this;
+	});
+	
+	/**
+	 * Add a number of days to the date object.
+	 * 
+	 * @example var dtm = new Date("01/12/2008");
+	 * dtm.addDays(1);
+	 * dtm.toString();
+	 * @result 'Sun Jan 13 2008 00:00:00'
+	 * 
+	 * @name addDays
+	 * @type Date
+	 * @cat Plugins/Methods/Date
+	 */
+	add("addDays", function(num) {
+		this.setDate(this.getDate() + num);
+		return this;
+	});
+	
+	/**
+	 * Add a number of hours to the date object.
+	 * 
+	 * @example var dtm = new Date("01/12/2008");
+	 * dtm.addHours(24);
+	 * dtm.toString();
+	 * @result 'Sun Jan 13 2008 00:00:00'
+	 * 
+	 * @name addHours
+	 * @type Date
+	 * @cat Plugins/Methods/Date
+	 */
+	add("addHours", function(num) {
+		this.setHours(this.getHours() + num);
+		return this;
+	});
+
+	/**
+	 * Add a number of minutes to the date object.
+	 * 
+	 * @example var dtm = new Date("01/12/2008");
+	 * dtm.addMinutes(60);
+	 * dtm.toString();
+	 * @result 'Sat Jan 12 2008 01:00:00'
+	 * 
+	 * @name addMinutes
+	 * @type Date
+	 * @cat Plugins/Methods/Date
+	 */
+	add("addMinutes", function(num) {
+		this.setMinutes(this.getMinutes() + num);
+		return this;
+	});
+	
+	/**
+	 * Add a number of seconds to the date object.
+	 * 
+	 * @example var dtm = new Date("01/12/2008");
+	 * dtm.addSeconds(60);
+	 * dtm.toString();
+	 * @result 'Sat Jan 12 2008 00:01:00'
+	 * 
+	 * @name addSeconds
+	 * @type Date
+	 * @cat Plugins/Methods/Date
+	 */
+	add("addSeconds", function(num) {
+		this.setSeconds(this.getSeconds() + num);
+		return this;
+	});
+	
+	/**
+	 * Sets the time component of this Date to zero for cleaner, easier comparison of dates where time is not relevant.
+	 * 
+	 * @example var dtm = new Date();
+	 * dtm.zeroTime();
+	 * dtm.toString();
+	 * @result 'Sat Jan 12 2008 00:01:00'
+	 * 
+	 * @name zeroTime
+	 * @type Date
+	 * @cat Plugins/Methods/Date
+	 * @author Kelvin Luck
+	 */
+	add("zeroTime", function() {
+		this.setMilliseconds(0);
+		this.setSeconds(0);
+		this.setMinutes(0);
+		this.setHours(0);
+		return this;
+	});
+	
+	/**
+	 * Returns a string representation of the date object according to Date.format.
+	 * (Date.toString may be used in other places so I purposefully didn't overwrite it)
+	 * 
+	 * @example var dtm = new Date("01/12/2008");
+	 * dtm.asString();
+	 * @result '12/01/2008' // (where Date.format == 'dd/mm/yyyy'
+	 * 
+	 * @name asString
+	 * @type Date
+	 * @cat Plugins/Methods/Date
+	 * @author Kelvin Luck
+	 */
+	add("asString", function() {
+		var r = Date.format;
+		return r
+			.split('yyyy').join(this.getFullYear())
+			.split('yy').join((this.getFullYear() + '').substring(2))
+			.split('mmm').join(this.getMonthName(true))
+			.split('mm').join(_zeroPad(this.getMonth()+1))
+			.split('dd').join(_zeroPad(this.getDate()));
+	});
+	
+	/**
+	 * Returns a new date object created from the passed String according to Date.format or false if the attempt to do this results in an invalid date object
+	 * (We can't simple use Date.parse as it's not aware of locale and I chose not to overwrite it incase it's functionality is being relied on elsewhere)
+	 *
+	 * @example var dtm = Date.fromString("12/01/2008");
+	 * dtm.toString();
+	 * @result 'Sat Jan 12 2008 00:00:00' // (where Date.format == 'dd/mm/yyyy'
+	 * 
+	 * @name fromString
+	 * @type Date
+	 * @cat Plugins/Methods/Date
+	 * @author Kelvin Luck
+	 */
+	Date.fromString = function(s)
+	{
+		var f = Date.format;
+		var d = new Date('01/01/1977');
+		var iY = f.indexOf('yyyy');
+		if (iY > -1) {
+			d.setFullYear(Number(s.substr(iY, 4)));
+		} else {
+			// TODO - this doesn't work very well - are there any rules for what is meant by a two digit year?
+			d.setFullYear(Number(Date.fullYearStart + s.substr(f.indexOf('yy'), 2)));
+		}
+		var iM = f.indexOf('mmm');
+		if (iM > -1) {
+			var mStr = s.substr(iM, 3);
+			for (var i=0; i<Date.abbrMonthNames.length; i++) {
+				if (Date.abbrMonthNames[i] == mStr) break;
+			}
+			d.setMonth(i);
+		} else {
+			d.setMonth(Number(s.substr(f.indexOf('mm'), 2)) - 1);
+		}
+		d.setDate(Number(s.substr(f.indexOf('dd'), 2)));
+		if (isNaN(d.getTime())) {
+			return false;
+		}
+		return d;
+	};
+	
+	// utility method
+	var _zeroPad = function(num) {
+		var s = '0'+num;
+		return s.substring(s.length-2)
+		//return ('0'+num).substring(-2); // doesn't work on IE :(
+	};
+	
+})();
Index: /trunk/trac-hacks/irclogsplugin/irclogs/htdocs/jquery.timer.js
===================================================================
--- /trunk/trac-hacks/irclogsplugin/irclogs/htdocs/jquery.timer.js	(revision 17)
+++ /trunk/trac-hacks/irclogsplugin/irclogs/htdocs/jquery.timer.js	(revision 17)
@@ -0,0 +1,75 @@
+﻿/*
+ *
+ *	jQuery Timer plugin v0.1
+ *		Matt Schmidt [http://www.mattptr.net]
+ *
+ *	Licensed under the BSD License:
+ *		http://mattptr.net/license/license.txt
+ *
+ */
+ 
+ jQuery.timer = function (interval, callback)
+ {
+ /**
+  *
+  * timer() provides a cleaner way to handle intervals  
+  *
+  *	@usage
+  * $.timer(interval, callback);
+  *
+  *
+  * @example
+  * $.timer(1000, function (timer) {
+  * 	alert("hello");
+  * 	timer.stop();
+  * });
+  * @desc Show an alert box after 1 second and stop
+  * 
+  * @example
+  * var second = false;
+  *	$.timer(1000, function (timer) {
+  *		if (!second) {
+  *			alert('First time!');
+  *			second = true;
+  *			timer.reset(3000);
+  *		}
+  *		else {
+  *			alert('Second time');
+  *			timer.stop();
+  *		}
+  *	});
+  * @desc Show an alert box after 1 second and show another after 3 seconds
+  *
+  * 
+  */
+
+	var interval = interval || 100;
+
+	if (!callback)
+		return false;
+	
+	_timer = function (interval, callback) {
+		this.stop = function () {
+			clearInterval(self.id);
+		};
+		
+		this.internalCallback = function () {
+			callback(self);
+		};
+		
+		this.reset = function (val) {
+			if (self.id)
+				clearInterval(self.id);
+			
+			var val = val || 100;
+			this.id = setInterval(this.internalCallback, val);
+		};
+		
+		this.interval = interval;
+		this.id = setInterval(this.internalCallback, this.interval);
+		
+		var self = this;
+	};
+	
+	return new _timer(interval, callback);
+ };
Index: /trunk/trac-hacks/irclogsplugin/irclogs/htdocs/irclogs.js
===================================================================
--- /trunk/trac-hacks/irclogsplugin/irclogs/htdocs/irclogs.js	(revision 243)
+++ /trunk/trac-hacks/irclogsplugin/irclogs/htdocs/irclogs.js	(revision 243)
@@ -0,0 +1,37 @@
+irclogs_setup = function(param_current_date,param_start_date,param_int_month,param_base_path) {
+        var $=jQuery;
+        $('#showactions').click( function() {
+            if ($(this).attr("checked")) {
+                $('.server, .hidden_user').show();
+            } else {
+                $('.server, .hidden_user').hide();
+            }
+        } );
+        Date.format = "yyyy/mm/dd/";
+        $('.next').attr('href', param_base_path+'/irclogs/' + new Date(param_current_date).addDays(1).asString());
+        $('.previous').attr('href',param_base_path+'/irclogs/' + new Date(param_current_date).addDays(-1).asString());
+        Date.format = 'mm/dd/yyyy';
+        $('.date-pick').datePicker({
+            horizontalOffset: -160, 
+            verticalOffset:20, 
+            clickInput: true, 
+            startDate: param_start_date, 
+            endDate:(new Date()).asString(), 
+            displayedMonth: Number(param_int_month)
+        })
+            .val( new Date(param_current_date).asString() )
+            .trigger( 'change' );
+        $('.date-pick').each(function() {
+            $(this).bind('dateSelected', function(e, selectedDate, td) {
+                Date.format = "yyyy/mm/dd/";
+                window.location.href = param_base_path+"/irclogs/" + selectedDate.asString()
+            } );
+        });
+        $('.link-datepicker').click(function(){
+            $('.date-pick').trigger('click');
+        });
+        hidden_count = $(".server:hidden").length + $(".channel:hidden").length;
+        $('#showactions').after("&nbsp;Show announcements (" + hidden_count  + ")");
+        // controls are hidden unless JS is enabled
+        $('#irclog-controls').show();
+    };
Index: /trunk/trac-hacks/irclogsplugin/irclogs/htdocs/jquery.dimensions.pack.js
===================================================================
--- /trunk/trac-hacks/irclogsplugin/irclogs/htdocs/jquery.dimensions.pack.js	(revision 17)
+++ /trunk/trac-hacks/irclogsplugin/irclogs/htdocs/jquery.dimensions.pack.js	(revision 17)
@@ -0,0 +1,12 @@
+/* Copyright (c) 2007 Paul Bakaus (paul.bakaus@googlemail.com) and Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
+ * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
+ * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
+ *
+ * $LastChangedDate: 2007-12-20 08:43:48 -0600 (Thu, 20 Dec 2007) $
+ * $Rev: 4257 $
+ *
+ * Version: 1.2
+ *
+ * Requires: jQuery 1.2+
+ */
+eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('(5($){$.19={P:\'1.2\'};$.u([\'j\',\'w\'],5(i,d){$.q[\'O\'+d]=5(){p(!3[0])6;g a=d==\'j\'?\'s\':\'m\',e=d==\'j\'?\'D\':\'C\';6 3.B(\':y\')?3[0][\'L\'+d]:4(3,d.x())+4(3,\'n\'+a)+4(3,\'n\'+e)};$.q[\'I\'+d]=5(b){p(!3[0])6;g c=d==\'j\'?\'s\':\'m\',e=d==\'j\'?\'D\':\'C\';b=$.F({t:Z},b||{});g a=3.B(\':y\')?3[0][\'8\'+d]:4(3,d.x())+4(3,\'E\'+c+\'w\')+4(3,\'E\'+e+\'w\')+4(3,\'n\'+c)+4(3,\'n\'+e);6 a+(b.t?(4(3,\'t\'+c)+4(3,\'t\'+e)):0)}});$.u([\'m\',\'s\'],5(i,b){$.q[\'l\'+b]=5(a){p(!3[0])6;6 a!=W?3.u(5(){3==h||3==r?h.V(b==\'m\'?a:$(h)[\'U\'](),b==\'s\'?a:$(h)[\'T\']()):3[\'l\'+b]=a}):3[0]==h||3[0]==r?S[(b==\'m\'?\'R\':\'Q\')]||$.N&&r.M[\'l\'+b]||r.A[\'l\'+b]:3[0][\'l\'+b]}});$.q.F({z:5(){g a=0,f=0,o=3[0],8,9,7,v;p(o){7=3.7();8=3.8();9=7.8();8.f-=4(o,\'K\');8.k-=4(o,\'J\');9.f+=4(7,\'H\');9.k+=4(7,\'Y\');v={f:8.f-9.f,k:8.k-9.k}}6 v},7:5(){g a=3[0].7;G(a&&(!/^A|10$/i.16(a.15)&&$.14(a,\'z\')==\'13\'))a=a.7;6 $(a)}});5 4(a,b){6 12($.11(a.17?a[0]:a,b,18))||0}})(X);',62,72,'|||this|num|function|return|offsetParent|offset|parentOffset|||||borr|top|var|window||Height|left|scroll|Left|padding|elem|if|fn|document|Top|margin|each|results|Width|toLowerCase|visible|position|body|is|Right|Bottom|border|extend|while|borderTopWidth|outer|marginLeft|marginTop|client|documentElement|boxModel|inner|version|pageYOffset|pageXOffset|self|scrollTop|scrollLeft|scrollTo|undefined|jQuery|borderLeftWidth|false|html|curCSS|parseInt|static|css|tagName|test|jquery|true|dimensions'.split('|'),0,{}))
Index: /trunk/trac-hacks/irclogsplugin/irclogs/__init__.py
===================================================================
--- /trunk/trac-hacks/irclogsplugin/irclogs/__init__.py	(revision 190)
+++ /trunk/trac-hacks/irclogsplugin/irclogs/__init__.py	(revision 190)
@@ -0,0 +1,5 @@
+import web_ui
+import macros
+import search
+import wiki
+from console import update_irc_search
Index: /trunk/trac-hacks/irclogsplugin/irclogs/console.py
===================================================================
--- /trunk/trac-hacks/irclogsplugin/irclogs/console.py	(revision 193)
+++ /trunk/trac-hacks/irclogsplugin/irclogs/console.py	(revision 193)
@@ -0,0 +1,34 @@
+#
+# Usage: python <script> <database directory> <directory to index>
+# Example: 
+#   python update_irc_search.py /tmp/irclogs.idx /var/oforge/irclogs/Channel
+#
+
+import os
+import sys
+import shutil
+import pyndexter
+from pyndexter import Framework, READWRITE
+from pyndexter.util import quote
+
+
+def update_irc_search():
+    args = sys.argv
+    
+    index_path = args[1]
+    log_path = args[2]
+    
+    files = os.listdir(args[2])
+    
+    for file in files:
+        try:
+            if os.path.isdir("%s/%s.idx" % (index_path, file)):
+                output = shutil.rmtree("%s/%s.idx" % (index_path, file))
+            framework = Framework('builtin://%s/%s.idx' % 
+                                  (quote(index_path), quote(file)), mode=READWRITE)
+            framework.add_source('file://%s/%s' % (quote(log_path), quote(file)))
+            framework.update()
+            framework.close()
+        except Exception, e:
+            code, message = e
+            print 'Error %s: %s' % (code, message)
Index: /trunk/trac-hacks/irclogsplugin/irclogs/wiki.py
===================================================================
--- /trunk/trac-hacks/irclogsplugin/irclogs/wiki.py	(revision 107)
+++ /trunk/trac-hacks/irclogsplugin/irclogs/wiki.py	(revision 107)
@@ -0,0 +1,31 @@
+import re
+
+from trac.core import *
+from trac.wiki import IWikiSyntaxProvider
+from trac.wiki.formatter import system_message
+from trac.util.html import html
+
+class IrcLogWiki(Component):
+    """Creates a link to the IRC log viewer for a particular date
+       including the anchor to the message timestamp"""
+    implements(IWikiSyntaxProvider) 
+
+    date_re = re.compile(r'^UTC(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})')
+
+    # IWikiSyntaxProvider methods
+    def get_wiki_syntax(self):
+        return []
+    
+    def get_link_resolvers(self):
+        yield ('irclog', self._format_link)
+
+    def _format_link(self, formatter, ns, target, label):
+       m = self.date_re.match(target)
+       if not m:
+           return system_message('Invalid IRC Log Link: '
+                         'Must be of the format UTCYYYY-MM-DDTHH:MM:SS %s')
+       return html.a(label, title=label, 
+                     href=formatter.href.irclogs(m.group('year'),
+                                                 m.group('month'),
+                                                 m.group('day'),) + 
+                            '#%s' % target)
Index: /trunk/trac-hacks/irclogsplugin/irclogs/macros.py
===================================================================
--- /trunk/trac-hacks/irclogsplugin/irclogs/macros.py	(revision 107)
+++ /trunk/trac-hacks/irclogsplugin/irclogs/macros.py	(revision 107)
@@ -0,0 +1,78 @@
+import os
+import re
+from datetime import datetime
+from trac.web.chrome import add_stylesheet, add_script, Chrome
+from trac.wiki.macros import WikiMacroBase
+from trac.wiki.formatter import system_message
+from trac.wiki.api import parse_args
+from web_ui import IrcLogsView
+
+class IrcLogLiveMacro(WikiMacroBase):
+    """Displays a live in-page feed of the current IRC log.  
+    Can take 2 parameters:
+     * polling frequency (seconds) default to 60
+     * number of messages displayed - defaults to 10
+    """
+    def expand_macro(self, formatter, name, content):
+
+        args, kw = parse_args(content)
+        poll_frequency = args and args[0] or 60
+        count = args and args[1] or 10
+
+        if not (0==len(args) or 2==len(args)):
+            return system_message('Incorrect arguments: ' 
+                'Must be of the format (poll frequency, lines to display)')
+
+        add_stylesheet(formatter.req, 'irclogs/style.css')
+        add_script(formatter.req, 'irclogs/jquery.timer.js')
+
+        data = Chrome(self.env).populate_data(formatter.req, 
+                                    {'poll_frequency':int(poll_frequency)*1000,
+                                     'count':count})
+        return Chrome(self.env).load_template('macro_live.html') \
+                                    .generate(**data)
+
+class IrcLogQuoteMacro(WikiMacroBase):
+    """Display contents of a logged IRC chat.  Takes parameters 
+    of the UTC timestamp of the message and the number of messages to show.
+    `[[IrcLogsQuote(UTCYYYY-MM-DDTHH:MM:SS,message_count]])`
+    
+    To get the UTC timestamp, click on the time displayed in the IRC 
+    log view page and copy the anchor from your browsers location bar.
+    """
+
+    date_re = re.compile(r'^UTC(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})'
+                         'T(?P<time>\d{2}:\d{2}:\d{2})')
+    
+    def expand_macro(self, formatter, name, content):
+        args, kw = parse_args(content)
+        utc_dt = args and args[0] or None
+        if not utc_dt:
+            return system_message('IrcLogQuote: Timestamp required')
+        d = self.date_re.match(utc_dt)
+        if not d:
+            return system_message('IrcLogQuote: Invalid timestamp format')
+        offset = int(args and len(args)>1 and args[1] or 10)
+
+        irclogs =  IrcLogsView(self.env)        
+        logfile = irclogs._get_filename(d.group('year'),
+                                        d.group('month'),
+                                        d.group('day'))
+        if (not os.path.isfile(logfile)):
+            return system_message('IrcLogQuote: No log file for this date')
+        iterable = irclogs._to_unicode(file(logfile))
+        lines = irclogs._render_lines(iterable, formatter.req.tz)
+
+        filtered_lines = [line for line in lines 
+                                if unicode(line['utc_dt']) >= utc_dt
+                                    and line['mode'] == 'channel'
+                                    and line['hidden_user'] != 'hidden_user']
+        
+        add_stylesheet(formatter.req, 'irclogs/style.css')
+        data = Chrome(self.env).populate_data(formatter.req, 
+                                    {'lines':filtered_lines[:offset],
+                                     'excerpt_date':d.groupdict(),
+                                     'utc_dt':utc_dt})
+        return Chrome(self.env).load_template('macro_quote.html') \
+                                    .generate(**data)
+    
Index: /trunk/trac-hacks/irclogsplugin/irclogs/search.py
===================================================================
--- /trunk/trac-hacks/irclogsplugin/irclogs/search.py	(revision 106)
+++ /trunk/trac-hacks/irclogsplugin/irclogs/search.py	(revision 106)
@@ -0,0 +1,85 @@
+import pytz
+import web_ui
+
+from trac.util.datefmt import localtz
+from trac.core import *
+from trac.search import ISearchSource
+from trac.config import Option
+
+from pyndexter import Framework, READWRITE
+from pyndexter.util import quote
+
+class IrcLogsSearch(Component):
+    implements(ISearchSource)
+
+    def get_search_filters(self, req):
+        if not req.perm.has_permission('IRCLOGS_VIEW'):
+            return []
+        return [('irclogs', 'IRC Logs', True)]
+
+
+    def get_search_results(self, req, terms, filters):
+        def _cut_line(text, size):
+            if len(text) > size:
+                return text[:size] + '...'
+            return text
+        if not 'irclogs' in filters:
+            return
+        
+        irclogs = web_ui.IrcLogsView(self.env)
+        
+        framework = Framework('builtin://%s/%s.idx' % 
+                        (quote(irclogs.search_db_path), 
+                         quote(irclogs.prefix)), mode=READWRITE)
+        framework.add_source('file://%s' % quote(irclogs.path))
+        tz = req.tz
+        utc = pytz.utc
+        unicode_terms = []
+        for term in terms:
+            unicode_terms.append(unicode(term))
+
+        for hit in framework.search(' '.join(terms)):
+            path = hit.uri.path
+            server_dt = self.find_anchor(irclogs, hit.current.content, terms)
+
+            if server_dt is None:
+                continue
+
+            utc_dt = utc.normalize(server_dt.astimezone(utc))
+            user_dt = tz.normalize(server_dt.astimezone(tz))
+            user_time = user_dt.strftime("%H:%M:%S")
+            anchor = utc_dt.strftime("#UTC%Y-%m-%dT%H:%M:%S")
+            year, month, day, hour, minute, second = \
+                path[-14:-10], path[-9:-7], path[-6:-4], user_time[0:2], \
+                user_time[3:5], user_time[6:8]
+            timestamp = user_dt.replace(tzinfo=localtz)
+            yield req.href('/irclogs/%s/%s/%s' % (year, month, day)) + anchor, \
+                           'IRC: %s logs for %s-%s-%s' % \
+                           (irclogs.prefix, year, month, day), \
+                           timestamp, 'irclog', \
+                           hit.excerpt(unicode_terms)
+        framework.close()
+
+    def find_anchor(self, irclogs, text, terms):
+        dummy = lambda: {}
+        pos = 0
+        for l in text.split('\n'):
+            for t in terms:
+                if t in l:
+                    d = getattr(irclogs._line_re.search(l), 
+                                'groupdict', dummy)()
+                    server_dt = irclogs._get_tz_datetime(d['date'], d['time'])
+                    return server_dt
+                continue
+            continue
+        return None
+
+    def index_logs(self):
+        irclogs = web_ui.IrcLogsView(self.env)
+        framework = Framework('builtin://%s/%s.idx' % 
+                              (quote(irclogs.search_db_path), 
+                               quote(irclogs.prefix)))
+        framework.add_source('file://%s' % quote(irclogs.path))
+        framework.update()
+        framework.close()
+
Index: /trunk/trac-hacks/irclogsplugin/irclogs/templates/macro_quote.html
===================================================================
--- /trunk/trac-hacks/irclogsplugin/irclogs/templates/macro_quote.html	(revision 108)
+++ /trunk/trac-hacks/irclogsplugin/irclogs/templates/macro_quote.html	(revision 108)
@@ -0,0 +1,13 @@
+<html xmlns="http://www.w3.org/1999/xhtml"
+      xmlns:py="http://genshi.edgewall.org/"
+      xmlns:xi="http://www.w3.org/2001/XInclude"
+      py:strip="True">
+
+  <xi:include href="irclogs_macros.html" />
+
+<div class="irclogs quote">
+Chat Excerpt from <a href="${href('irclogs',excerpt_date.year,excerpt_date.month,excerpt_date.day)}#${utc_dt}">${excerpt_date.month}/${excerpt_date.day}/${excerpt_date.year}</a>
+
+${irclog_table(lines,page_href=href('irclogs',excerpt_date.year,excerpt_date.month,excerpt_date.day))}
+</div>
+</html>
Index: /trunk/trac-hacks/irclogsplugin/irclogs/templates/macro_live.html
===================================================================
--- /trunk/trac-hacks/irclogsplugin/irclogs/templates/macro_live.html	(revision 108)
+++ /trunk/trac-hacks/irclogsplugin/irclogs/templates/macro_live.html	(revision 108)
@@ -0,0 +1,13 @@
+<html xmlns="http://www.w3.org/1999/xhtml"
+      xmlns:py="http://genshi.edgewall.org/"
+      py:strip="True">
+<div class="irclogs" id="liveirclog"><p>Loading the IRC log...</p></div>
+<script type="text/javascript">
+  jQuery(document).ready(function($) {
+    $('#liveirclog').load("${href('irclogs','feed',count)}");
+    $.timer($poll_frequency, function(timer) {
+      $('#liveirclog').load("${href('irclogs','feed',count)}");
+    });
+  });
+</script>
+</html>
Index: /trunk/trac-hacks/irclogsplugin/irclogs/templates/irclogs.html
===================================================================
--- /trunk/trac-hacks/irclogsplugin/irclogs/templates/irclogs.html	(revision 237)
+++ /trunk/trac-hacks/irclogsplugin/irclogs/templates/irclogs.html	(revision 237)
@@ -0,0 +1,98 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
+  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml"
+      xmlns:py="http://genshi.edgewall.org/"
+      xmlns:xi="http://www.w3.org/2001/XInclude">
+  <xi:include href="layout.html" />
+  <xi:include href="irclogs_macros.html" />
+  
+ <head>
+ <title>Team Chat Logs</title>
+</head>
+  <body> 
+  <div id="content" class="irclogs">
+      <h1>Team Chat Logs</h1>
+      <div id="content" class="error" py:if="error">
+        <div class="message">${message}</div>
+      </div>
+      <div id="nojscal" style="display: block;">
+        <table class="minical">
+          <tr class="head">
+            <th colspan="7">${year} ${int_month}</th>
+          </tr>
+          <tr class="days">
+            <th>Mo</th>
+            <th>Tu</th>
+            <th>We</th>
+            <th>Th</th>
+            <th>Fr</th>
+            <th>Sa</th>
+            <th>Su</th>
+          </tr>
+          <tr class="week" py:for="week in cal.weeks">
+            <py:for each="day in week">
+              <td py:if="day.empty" class="empty">&nbsp;</td>
+              <td py:if="not day.empty" class="${day.has_log and 'has' or 'non'}_log">
+                <a href="${day.href}">${day.caption}</a>
+              </td>
+            </py:for>
+          </tr>
+          <tr class="nav">
+            <td><a href="${cal.prev_year.href}">&lt;&lt;</a></td>
+            <td><a href="${cal.prev_month.href}">&lt;</a></td>
+            <td colspan="3">&nbsp;</td>
+            <td><a href="${cal.next_month.href}">&gt;</a></td>
+            <td><a href="${cal.next_year.href}">&gt;&gt;</a></td>
+          </tr>
+        </table>
+      </div>
+      <py:choose test="viewmode">
+        <py:when test="'years'">
+          <h2>Years</h2>
+          <ul class="years">
+            <li py:for="year in years"><a href="${year.href}">${year.caption}</a></li>
+          </ul>
+        </py:when>
+        <py:when test="'months'">
+          <h2>Logs for ${year}</h2>
+          <ul class="months">
+            <li py:for="month in months"><a href="${month.href}">${month.caption} ${year}</a></li>
+          </ul>
+        </py:when>
+        <py:when test="'days'">
+          <h2>Logs for ${month} ${year}</h2>
+          <ul class="days">
+            <li py:for="day in days"><a href="${day.href}">${month} ${day.caption}, ${year}</a></li>
+          </ul>
+        </py:when>
+        <py:when test="'day'"> 
+          <h2>${month_name} ${day}, ${year}</h2>
+          <div id="irclog-controls">
+            <input type="checkbox" id="showactions" py:if="not missing" style="display: none;"></input>
+            <div id="jscal" style="display: none;">
+              <div class="navcal">
+                <a href="#" class="previous">&lt;&lt;</a> 
+                <a class="link-datepicker" href="#">Select Date</a><input class="date-pick" value="${current_date}"/>
+                <a href="#" class="next">&gt;&gt;</a>
+              </div>
+            </div>
+          <br style="clear:both"/>
+          </div>
+          <div py:if="missing">
+            No logfile for this day.
+          </div>
+          ${irclog_table(lines,'searchable')}
+        </py:when>
+      </py:choose>
+      <script type="text/javascript">
+        jQuery(document).ready(function($) {
+            irclogs_setup('${current_date}','${start_date}','${int_month}','${req.base_path}');
+            $('#jscal')[0].style.display = 'block';
+            $('#nojscal')[0].style.display = 'none';
+            $('#showactions')[0].style.display = 'block';
+        });
+      </script>        
+      <br style="clear:both" />
+    </div>
+  </body>
+</html>
Index: /trunk/trac-hacks/irclogsplugin/irclogs/templates/irclogs_feed.html
===================================================================
--- /trunk/trac-hacks/irclogsplugin/irclogs/templates/irclogs_feed.html	(revision 108)
+++ /trunk/trac-hacks/irclogsplugin/irclogs/templates/irclogs_feed.html	(revision 108)
@@ -0,0 +1,10 @@
+<html xmlns="http://www.w3.org/1999/xhtml"
+      xmlns:py="http://genshi.edgewall.org/"
+      xmlns:xi="http://www.w3.org/2001/XInclude">
+  <xi:include href="irclogs_macros.html" />
+
+<div py:if="missing" style="padding:5px;">No chat logs for today</div>
+<div class="irclog">
+${irclog_table(lines,page_href=href('irclogs',year,month,day))}
+</div>
+</html>
Index: /trunk/trac-hacks/irclogsplugin/irclogs/templates/irclogs_macros.html
===================================================================
--- /trunk/trac-hacks/irclogsplugin/irclogs/templates/irclogs_macros.html	(revision 108)
+++ /trunk/trac-hacks/irclogsplugin/irclogs/templates/irclogs_macros.html	(revision 108)
@@ -0,0 +1,16 @@
+<div xmlns="http://www.w3.org/1999/xhtml"
+     xmlns:xi="http://www.w3.org/2001/XInclude"
+     xmlns:py="http://genshi.edgewall.org/" py:strip="">
+
+  <py:def function="irclog_table(lines, extra_classes='', page_href='', missing=False)">
+      <table class="irclog ${extra_classes}" py:if="not missing">
+        <tr py:for="line in lines" class="${line.mode} ${line.hidden_user}" >
+          <td class="time">[<a href="${page_href}#${line.utc_dt}" title="${line.utc_dt}" id="${line.utc_dt}">${line.time}</a>]</td>
+          <td class="left" py:if="line.mode in ('action', 'server')">*</td>
+          <td class="left" py:if="line.mode == 'channel'">&lt;<span class="${line.nickcls}">${line.nickname}</span>&gt;</td>
+          <td class="right">${line.mode != 'channel' and line.nickname + ' ' or '' }${line.text}</td>
+        </tr>
+      </table>
+  </py:def>
+
+</div>
Index: /trunk/trac-hacks/irclogsplugin/setup.py
===================================================================
--- /trunk/trac-hacks/irclogsplugin/setup.py	(revision 562)
+++ /trunk/trac-hacks/irclogsplugin/setup.py	(revision 562)
@@ -0,0 +1,28 @@
+from setuptools import setup
+
+PACKAGE = 'irclogs'
+VERSION = '0.2'
+
+setup(
+    name=PACKAGE,
+    version=VERSION,
+    description='Display Supybot IRC Logs',
+    author='Armin Ronacher',
+    author_email='armin.ronacher@active-4.com',
+    url='http://trac.pocoo.org/',
+    license='BSD',
+    packages=['irclogs'],
+    classifiers=[
+        'Framework :: Trac',
+        'License :: OSI Approved :: BSD License',
+    ],
+    package_data={
+        'irclogs' : ['templates/*.html', 'htdocs/*.css', 
+                     'htdocs/*.js', 'htdocs/*.png']
+    },
+    entry_points = {
+        'trac.plugins': ['irclogs = irclogs'],
+        'console_scripts': ['update-irc-search = irclogs.console:update_irc_search',],
+    },
+    install_requires = ['pyndexter>=0.2'],
+)
