Merge with 875e57f5f6ac74a1d6fb0e2623157fff254c338f
authorraph
Thu, 15 Jul 2010 17:08:45 +0200
changeset 296 6959c2875f47
parent 295 7c40b98f627f (diff)
parent 283 875e57f5f6ac (current diff)
child 297 173710f4b6d1
Merge with 875e57f5f6ac74a1d6fb0e2623157fff254c338f
buildout.cfg
--- a/buildout.cfg	Fri Jun 11 16:21:53 2010 +0200
+++ b/buildout.cfg	Thu Jul 15 17:08:45 2010 +0200
@@ -4,6 +4,9 @@
 	django
 	python
 	django-extensions
+	django-piston
+	omelette
+unzip = true
 develop = .
 
 [python]
@@ -23,12 +26,14 @@
 pythonpath = src
 	src/cm
 	${django-extensions:location}
+	${django-piston:location}
 eggs = 
 	django-flash
 	django-tagging
-	django-piston
+#	django-piston
+# api dependency
 #	django-css	
-	chardet
+#	chardet
 	feedparser
 	PIL
 	BeautifulSoup
@@ -44,4 +49,12 @@
 [django-extensions]
 recipe=zerokspot.recipe.git
 repository=git://github.com/django-extensions/django-extensions.git
-#rev=7c73978b55fcadbe2cd6f2abbefbedb5a85c2c8c
\ No newline at end of file
+#rev=7c73978b55fcadbe2cd6f2abbefbedb5a85c2c8c
+
+[django-piston]
+recipe = mercurialrecipe
+repository = http://bitbucket.org/jespern/django-piston
+
+[omelette]
+recipe = collective.recipe.omelette
+eggs = ${django:eggs}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/cm/api/handlers.py	Thu Jul 15 17:08:45 2010 +0200
@@ -0,0 +1,474 @@
+from piston.handler import AnonymousBaseHandler, BaseHandler
+from piston.utils import rc
+
+from cm.models import Text,TextVersion, Role, UserRole, Comment
+from cm.views import get_keys_from_dict, get_textversion_by_keys_or_404, get_text_by_keys_or_404, get_textversion_by_keys_or_404, redirect
+from cm.security import get_texts_with_perm, has_perm, get_viewable_comments, \
+    has_perm_on_text_api
+from cm.security import get_viewable_comments
+from cm.utils.embed import embed_html
+from cm.views.create import CreateTextContentForm, create_text
+from cm.views.texts import client_exchange, text_view_frame, text_view_comments, text_export
+from cm.views.feeds import text_feed
+from piston.utils import validate
+from settings import SITE_URL
+
+URL_PREFIX = SITE_URL + '/api'
+ 
+class AnonymousTextHandler(AnonymousBaseHandler):
+    type = "Text methods"
+    title = "Read text info"
+    fields = ('key', 'title', 'format', 'content', 'created', 'modified', 'nb_comments', 'nb_versions', 'embed_html', ('last_text_version', ('created','modified', 'format', 'title', 'content')))   
+    allowed_methods = ('GET', )   
+    model = Text
+    desc = """ Read text identified by `key`."""
+    args = None
+
+    @staticmethod
+    def endpoint():
+        return URL_PREFIX + '/text/{key}/'
+
+
+    @has_perm_on_text_api('can_view_text')
+    def read(self, request, key):
+        
+        text = get_text_by_keys_or_404(key)
+        setattr(text,'nb_comments',len(get_viewable_comments(request, text.last_text_version.comment_set.all(), text)))
+        setattr(text,'nb_versions',text.get_versions_number())
+        setattr(text,'embed_html',embed_html(text.key))
+
+        return text
+
+class TextHandler(BaseHandler):
+    type = "Text methods"    
+    anonymous = AnonymousTextHandler
+    allowed_methods = ('GET',)  
+    no_display = True 
+
+class AnonymousTextVersionHandler(AnonymousBaseHandler):
+    type = "Text methods"
+    title = "Read text version info"
+    fields = ('key', 'title', 'format', 'content', 'created', 'modified', 'nb_comments',)   
+    allowed_methods = ('GET', )   
+    model = Text
+    desc = """ Read text version identified by `version_key` inside text identified by `key`."""
+    args = None
+
+    @staticmethod
+    def endpoint():
+        return URL_PREFIX + '/text/{key}/{version_key}/'
+
+
+    @has_perm_on_text_api('can_view_text')
+    def read(self, request, key, version_key):
+        text_version = get_textversion_by_keys_or_404(version_key, key=key)
+        setattr(text_version,'nb_comments',len(get_viewable_comments(request, text_version.comment_set.all(), text_version.text)))
+
+        return text_version
+
+class TextVersionHandler(BaseHandler):
+    type = "Text methods"    
+    anonymous = AnonymousTextVersionHandler
+    fields = ('key', 'title', 'format', 'content', 'created', 'modified', 'nb_comments',)   
+    allowed_methods = ('GET', )   
+    model = Text
+    no_display = True 
+
+    @has_perm_on_text_api('can_view_text')
+    def read(self, request, key, version_key):
+        text_version = get_textversion_by_keys_or_404(version_key, key=key)
+        setattr(text_version,'nb_comments',len(get_viewable_comments(request, text_version.comment_set.all(), text_version.text)))
+
+        return text_version
+
+class AnonymousTextListHandler(AnonymousBaseHandler):
+    title = "List texts"    
+    type = "Text methods"    
+    fields = ('key', 'title', 'created', 'modified', 'nb_comments', 'nb_versions',)   
+    allowed_methods = ('GET',)   
+    model = Text
+    desc = """Lists texts on workspace."""        
+
+    @staticmethod
+    def endpoint():
+        return URL_PREFIX + '/text/'
+
+    def read(self, request):
+        order_by = '-id'
+        texts = get_texts_with_perm(request, 'can_view_text').order_by(order_by)        
+        return texts
+
+class TextListHandler(BaseHandler):
+    title = "Create text"    
+    type = "Text methods"    
+    allowed_methods = ('GET', 'POST')    
+    fields = ('key', 'title', 'created', 'modified', 'nb_comments', 'nb_versions',)   
+    model = Text
+    anonymous = AnonymousTextListHandler
+    desc = "Create a text with the provided parameters."
+    args = """<br/>
+`title`: title of the text<br/>
+`format`: format content ('markdown', 'html')<br/>
+`content`: content (in specified format)<br/>
+`anon_role`: role to give to anon users: null, 4: commentator, 5: observer<br/>
+        """
+     
+    @staticmethod
+    def endpoint():
+        return URL_PREFIX + '/text/'
+
+    def read(self, request):
+        order_by = '-id'
+        texts = get_texts_with_perm(request, 'can_view_text').order_by(order_by)        
+        return texts
+
+    def create(self, request):
+        form = CreateTextContentForm(request.POST)
+        if form.is_valid():
+            text = create_text(request.user, form.cleaned_data)
+            anon_role = request.POST.get('anon_role', None)
+            if anon_role:
+                userrole = UserRole.objects.create(user=None, role=Role.objects.get(id=anon_role), text=text)         
+            return {'key' : text.key , 'version_key' : text.last_text_version.key, 'created': text.created}
+        else:
+            resp = rc.BAD_REQUEST
+        return resp
+
+from cm.exception import UnauthorizedException
+from cm.views.texts import text_delete
+
+class TextDeleteHandler(BaseHandler):
+    type = "Text methods"
+    allowed_methods = ('POST', )    
+    title = "Delete text"    
+    desc = "Delete the text identified by `key`."
+
+    @staticmethod
+    def endpoint():
+        return URL_PREFIX + '/text/{key}/delete/'
+
+    def create(self, request, key):
+        """
+        Delete text identified by `key`.
+        """
+        try:
+            text_delete(request, key=key)
+        except UnauthorizedException:
+            return rc.FORBIDDEN
+        except KeyError:
+            return rc.BAD_REQUEST
+        return rc.DELETED
+
+from cm.views.texts import text_pre_edit
+ 
+class TextPreEditHandler(BaseHandler):
+    type = "Text methods"
+    allowed_methods = ('POST', )    
+    title = "Ask for edit impact"    
+    desc = "Returns the number of impacted comments."
+    args = """<br />
+`new_format`: new format content ('markdown', 'html')<br />        
+`new_content`: new content (in specified format)<br />    
+    """ 
+
+    @staticmethod
+    def endpoint():
+        return URL_PREFIX + '/text/{key}/pre_edit/'
+    
+    def create(self, request, key):
+        return text_pre_edit(request, key=key)
+
+from cm.views.texts import text_edit
+    
+class TextEditHandler(BaseHandler):
+    allowed_methods = ('POST', )    
+    type = "Text methods"
+    title = "Edit text"    
+    desc = "Update text identified by `key`."
+    args = """<br />
+`title`: new title of the text<br />
+`format`: new format content ('markdown', 'html')<br />
+`content`: new content (in specified format)<br />
+`note`: note to add to edit<br />
+`new_version`: boolean: should a new version of the text be created?<br />
+`keep_comments`: boolean: should existing comments be keep (if possible)?<br />
+    """ 
+    
+    @staticmethod
+    def endpoint():
+        return URL_PREFIX + '/text/{key}/edit/'
+    
+    
+    def create(self, request, key):
+        res = text_edit(request, key=key)
+        text = get_text_by_keys_or_404(key)
+        text_version = text.last_text_version
+        return {'version_key' : text_version.key , 'created': text_version.created}
+
+
+class AnonymousTextFeedHandler(AnonymousBaseHandler):
+    allowed_methods = ('GET',)    
+    type = "Text methods"
+    title = "Text feed"
+    desc = "Returns text RSS feed."
+    args = None
+    
+    @staticmethod
+    def endpoint():
+        return URL_PREFIX + '/text/{key}/feed/?'
+    
+    def read(self, request, key):
+        return text_feed(request, key=key)
+
+class TextFeedHandler(BaseHandler):    
+    type = "Text methods"
+    anonymous = AnonymousTextFeedHandler
+    allowed_methods = ('GET',)  
+    no_display = True
+
+    def read(self, request, key):
+        return text_feed(request, key=key)
+    
+class TextVersionRevertHandler(BaseHandler):
+    allowed_methods = ('POST', )    
+    type = "Text methods"
+    title = "Revert to specific text version"    
+    desc = "Revert to a text version (i.e. copy this text_version which becomes the last text_version)."
+    args = """<br />
+`key`: text's key<br />
+`version_key`: key of the version to revert to<br />
+    """ 
+    
+    @staticmethod
+    def endpoint():
+        return URL_PREFIX + '/text/{key}/{version_key}/revert/'
+    
+    
+    def create(self, request, key, version_key):
+        text_version = get_textversion_by_keys_or_404(version_key, key=key)
+        new_text_version = text_version.text.revert_to_version(version_key)
+        return {'version_key' : new_text_version.key , 'created': new_text_version.created}
+
+class TextVersionDeleteHandler(BaseHandler):
+    allowed_methods = ('POST', )    
+    type = "Text methods"
+    title = "Delete a specific text version"    
+    desc = "Delete a text version."
+    args = """<br />
+`key`: text's key<br />
+`version_key`: key of the version to delete<br />
+    """ 
+    
+    @staticmethod
+    def endpoint():
+        return URL_PREFIX + '/text/{key}/{version_key}/delete/'
+    
+    
+    def create(self, request, key, version_key):
+        text_version = get_textversion_by_keys_or_404(version_key, key=key)
+        text_version.delete()
+        return rc.ALL_OK    
+
+## client methods
+
+class AnonymousClientHandler(AnonymousBaseHandler):
+    allowed_methods = ('POST',)    
+    type = "Client methods"
+    title = "Handles client methods"
+    desc = "Handles client (ajax text view) methods."
+    args = """<br />
+post arguments
+    """ 
+    
+    @staticmethod
+    def endpoint():
+        return URL_PREFIX + '/client/'
+    
+    def create(self, request):
+        return client_exchange(request)
+
+class ClientHandler(BaseHandler):    
+    type = "Client methods"
+    anonymous = AnonymousClientHandler
+    allowed_methods = ('POST',)  
+    no_display = True 
+
+    def create(self, request):
+        return client_exchange(request)
+
+## embed methods
+from django.views.i18n import javascript_catalog
+from cm.urls import js_info_dict
+
+class JSI18NHandler(AnonymousBaseHandler):
+    allowed_methods = ('GET',)    
+    type = "Embed methods"
+    title = "Get js i18n dicts"
+    desc = ""
+    args = None
+    
+    @staticmethod
+    def endpoint():
+        return URL_PREFIX + '/jsi18n/'
+    
+    def read(self, request):
+        return javascript_catalog(request, **js_info_dict)
+
+
+class AnonymousCommentFrameHandler(AnonymousBaseHandler):
+    allowed_methods = ('GET',)    
+    type = "Embed methods"
+    title = "Displays embedable frame"
+    desc = ""
+    args = None
+    
+    @staticmethod
+    def endpoint():
+        return URL_PREFIX + '/text/{key}/comments_frame/?prefix=/api'
+    
+    def read(self, request, key):
+        return text_view_frame(request, key=key)
+
+class CommentFrameHandler(BaseHandler):    
+    type = "Embed methods"
+    anonymous = AnonymousCommentFrameHandler
+    allowed_methods = ('GET',)  
+    no_display = True 
+
+    def read(self, request, key):
+        return text_view_frame(request, key=key)
+
+class AnonymousCommentHandler(AnonymousBaseHandler):
+    allowed_methods = ('GET',)    
+    type = "Embed methods"
+    title = "Displays embedable frame"
+    no_display = True 
+    desc = ""
+    args = None
+    
+    @staticmethod
+    def endpoint():
+        return URL_PREFIX + '/text/{key}/comments/{version_key}/?'
+    
+    def read(self, request, key, version_key):
+        return text_view_comments(request, key=key, version_key=version_key)
+
+class CommentHandler(BaseHandler):    
+    type = "Embed methods"
+    anonymous = AnonymousCommentHandler
+    allowed_methods = ('GET',)  
+    no_display = True 
+
+    def read(self, request, key, version_key):
+        return text_view_comments(request, key=key, version_key=version_key)
+
+
+class AnonymousTextExportHandler(AnonymousBaseHandler):
+    allowed_methods = ('POST',)    
+    type = "Embed methods"
+    title = "undocumented"
+    no_display = True 
+    desc = ""
+    args = None
+    
+    @staticmethod
+    def endpoint():
+        return URL_PREFIX + ' undocumented'
+    
+    def create(self, request, key, format, download, whichcomments, withcolor):
+        return text_export(request, key, format, download, whichcomments, withcolor, adminkey=None)
+
+class TextExportHandler(BaseHandler):    
+    type = "Embed methods"
+    anonymous = AnonymousTextExportHandler
+    allowed_methods = ('POST',)  
+    no_display = True 
+
+    def create(self, request, key, format, download, whichcomments, withcolor):
+        return text_export(request, key, format, download, whichcomments, withcolor, adminkey=None)
+
+class AnonymousCommentsHandler(AnonymousBaseHandler):
+    allowed_methods = ('GET',)    
+    type = "Comment methods"
+    fields = ('id_key', 'title', 'format', 'content', 'created', 'name', ('text_version' , ('key', ('text', ('key',))) ))   
+    model = Comment    
+    title = "Get comments"
+    desc = "Get comments from the workspace, most recent first."
+    args = """<br />
+`keys`: (optional) comma separated keys : limit comments from these texts only<br />
+`name`: (optional) limit comments from this user only
+`limit`: (optional) limit number of comments returned
+    """ 
+    
+    @staticmethod
+    def endpoint():
+        return URL_PREFIX + '/comments/'
+    
+    def read(self, request):
+        name = request.GET.get('name', None)
+        limit = request.GET.get('limit', None)
+        keys = request.GET.get('keys', None)
+        query = Comment.objects.all()
+        if keys:            
+            query = query.filter(text_version__text__key__in=keys.split(','))
+        if name:
+            query = query.filter(name=name)
+        query = query.order_by('-created')
+        if limit:
+            query = query[:int(limit)]
+        return query
+
+class CommentsHandler(BaseHandler):    
+    type = "Comment methods"
+    anonymous = AnonymousCommentsHandler
+    allowed_methods = ('GET',)  
+    fields = ('id_key', 'title', 'format', 'content', 'created', 'name', ('text_version' , ('key', ('text', ('key',))) ))   
+    model = Comment
+    no_display = True 
+
+    def read(self, request):
+        name = request.GET.get('name', None)
+        limit = request.GET.get('limit', None)
+        keys = request.GET.get('keys', None)
+        query = Comment.objects.all()
+        if keys:            
+            query = query.filter(text_version__text__key__in=keys.split(','))
+        if name:
+            query = query.filter(name=name)
+        query = query.order_by('-created')
+        if limit:
+            query = query[:int(limit)]
+        return query
+    
+from piston.doc import documentation_view
+
+from piston.handler import handler_tracker
+from django.template import RequestContext
+from piston.doc import generate_doc
+from django.shortcuts import render_to_response
+
+def documentation(request):
+    """
+    Generic documentation view. Generates documentation
+    from the handlers you've defined.
+    """
+    docs = [ ]
+
+    for handler in handler_tracker:
+        doc = generate_doc(handler)
+        setattr(doc,'type', handler.type)
+        docs.append(doc)
+
+    def _compare(doc1, doc2): 
+       #handlers and their anonymous counterparts are put next to each other.
+       name1 = doc1.name.replace("Anonymous", "")
+       name2 = doc2.name.replace("Anonymous", "")
+       return cmp(name1, name2)    
+ 
+    #docs.sort(_compare)
+       
+    return render_to_response('api_doc.html', 
+        { 'docs': docs }, RequestContext(request))
+
+from piston.doc import generate_doc
+DocHandler = generate_doc(TextPreEditHandler)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/cm/api/urls.py	Thu Jul 15 17:08:45 2010 +0200
@@ -0,0 +1,54 @@
+from django.conf.urls.defaults import *
+
+from piston.resource import Resource
+from piston.authentication import HttpBasicAuthentication
+
+from cm.api.handlers import * 
+auth = HttpBasicAuthentication(realm='Comt API')
+
+text_handler = Resource(handler=TextHandler, authentication=auth)
+textversion_handler = Resource(handler=TextVersionHandler, authentication=auth)
+text_list_handler = Resource(handler=TextListHandler, authentication=auth)
+text_delete_handler = Resource(handler=TextDeleteHandler, authentication=auth)
+text_pre_edit_handler = Resource(handler=TextPreEditHandler, authentication=auth)
+text_edit_handler = Resource(handler=TextEditHandler, authentication=auth)
+text_feed_handler = Resource(handler=TextFeedHandler, authentication=auth)
+
+tv_revert_handler = Resource(handler=TextVersionRevertHandler, authentication=auth)
+tv_delete_handler = Resource(handler=TextVersionDeleteHandler, authentication=auth)
+
+text_export_handler = Resource(handler=TextExportHandler, authentication=auth)
+
+comments_handler = Resource(handler=CommentsHandler, authentication=auth)
+
+client_handler = Resource(handler=ClientHandler, authentication=auth)
+
+jsi8n_handler = Resource(handler=JSI18NHandler, authentication=None)
+
+comment_frame_handler = Resource(handler=CommentFrameHandler, authentication=auth)
+comment_handler = Resource(handler=CommentHandler, authentication=auth)
+
+#doc_handler = Resource(handler=DocHandler)
+
+urlpatterns = patterns('',
+   url(r'^text/(?P<key>\w*)/$', text_handler),
+   url(r'^text/$', text_list_handler),
+
+   url(r'^text/(?P<key>\w*)/(?P<version_key>\w*)/revert/$', tv_revert_handler),
+   url(r'^text/(?P<key>\w*)/(?P<version_key>\w*)/delete/$', tv_delete_handler),
+   
+   url(r'^text/(?P<key>\w*)/comments_frame/$', comment_frame_handler),
+   url(r'^text/(?P<key>\w*)/comments/(?P<version_key>\w*)/$', comment_handler),
+   
+   url(r'^text/(?P<key>\w*)/export/(?P<format>\w*)/(?P<download>\w*)/(?P<whichcomments>\w*)/(?P<withcolor>\w*)/$', text_export_handler),
+
+   url(r'^text/(?P<key>\w*)/feed/$', text_feed_handler),
+   url(r'^text/(?P<key>\w*)/delete/$', text_delete_handler),
+   url(r'^text/(?P<key>\w*)/pre_edit/$', text_pre_edit_handler),
+   url(r'^text/(?P<key>\w*)/edit/$', text_edit_handler),
+   url(r'^text/(?P<key>\w*)/(?P<version_key>\w*)/$', textversion_handler),
+   url(r'^comments/$', comments_handler),
+   url(r'^client/$', client_handler),
+   url(r'^jsi18n/$', jsi8n_handler),
+   url(r'^doc/$', documentation),
+)
--- a/src/cm/cm_settings.py	Fri Jun 11 16:21:53 2010 +0200
+++ b/src/cm/cm_settings.py	Thu Jul 15 17:08:45 2010 +0200
@@ -28,4 +28,7 @@
 TRACKING_HTML = get_setting('TRACKING_HTML', '')
 
 # Store IP (or not) in activity 
-STORE_ACTIVITY_IP = get_setting('STORE_ACTIVITY_IP', True)
\ No newline at end of file
+STORE_ACTIVITY_IP = get_setting('STORE_ACTIVITY_IP', True)
+
+# Show 'decorated' users in comments (not structural creator id) 
+DECORATED_CREATORS = get_setting('DECORATED_CREATORS', False)
\ No newline at end of file
--- a/src/cm/fixtures/test_content.yaml	Fri Jun 11 16:21:53 2010 +0200
+++ b/src/cm/fixtures/test_content.yaml	Thu Jul 15 17:08:45 2010 +0200
@@ -121,6 +121,19 @@
     mod_posteriori: True
     key: "textversion_key_1" 
     adminkey: "tv_adminkey_1" 
+
+- model : cm.textversion
+  pk: 0
+  fields:
+    created: "2009-01-14 04:01:12"
+    modified: "2009-01-14 04:01:12"
+    title: 'title 1, aposteriori moderation'
+    format: 'markdown'
+    content: 'zzz hhhh aaa bbb ccc ddd eee fff ggg'
+    text: 1
+    mod_posteriori: True
+    key: "textversion_key_0" 
+    adminkey: "tv_adminkey_0" 
     
 - model : cm.text
   pk: 1
@@ -360,6 +373,58 @@
     adminkey: "text_adminkey_3"
     user: 2    
 
+# text 4
+- model : cm.textversion
+  pk: 4
+  fields:
+    created: "2009-02-13 04:01:12"
+    modified: "2009-02-13 04:01:12"
+    title: 'title 4, public text'
+    format: 'markdown'
+    content: 'aaa bbb ccc ddd eee fff ggg'
+    text: 4
+    mod_posteriori: True
+    key: "textversion_key_4" 
+    adminkey: "tv_adminkey_4" 
+    
+- model : cm.text
+  pk: 4
+  fields:
+    created: "2009-02-13 04:01:12"
+    modified: "2009-02-13 04:01:12"
+    last_text_version: 4
+    title: 'title 4, public text'
+    state: "approved"
+    key: "text_key_4" 
+    adminkey: "text_adminkey_4" 
+    user: 1
+
+# text 5
+- model : cm.textversion
+  pk: 5
+  fields:
+    created: "2009-02-13 04:01:12"
+    modified: "2009-02-13 04:01:12"
+    title: 'title 5, public text'
+    format: 'markdown'
+    content: 'aaa bbb ccc ddd eee fff ggg'
+    text: 5
+    mod_posteriori: True
+    key: "textversion_key_5" 
+    adminkey: "tv_adminkey_5" 
+    
+- model : cm.text
+  pk: 5
+  fields:
+    created: "2009-02-13 04:01:12"
+    modified: "2009-02-13 04:01:12"
+    last_text_version: 5
+    title: 'title 5, public text'
+    state: "approved"
+    key: "text_key_5" 
+    adminkey: "text_adminkey_5" 
+    user: 1    
+    
 ############### userrole ############### 
 
 # user 1 is global Manager
@@ -426,6 +491,24 @@
     user: 4
     text: 2
 
+# user null (anon is Commentator on text 4)
+# userrole 8
+- model : cm.userrole
+  pk: 8
+  fields:
+    role: 4
+    user: null
+    text: 4
+    
+# user null (anon is Commentator on text 5)
+# userrole 9
+- model : cm.userrole
+  pk: 9
+  fields:
+    role: 4
+    user: null
+    text: 5
+    
 ############### comment ###############
 
 # comment 1 (visible on text 2)
--- a/src/cm/media/js/client/c_client-min.js	Fri Jun 11 16:21:53 2010 +0200
+++ b/src/cm/media/js/client/c_client-min.js	Thu Jul 15 17:08:45 2010 +0200
@@ -1,1 +1,1 @@
-hasPerm=function(a){return(-1!=CY.Array.indexOf(sv_user_permissions,a));};Layout=function(){};Layout.prototype={init:function(){},isInFrame:function(){return(!CY.Lang.isUndefined(parent)&&parent.location!=location&&CY.Lang.isFunction(parent.f_getFrameFilterData));},isInComentSite:function(){var b=false;try{if(!CY.Lang.isUndefined(sv_site_url)&&!CY.Lang.isUndefined(parent)&&!CY.Lang.isUndefined(parent.parent)){var a=new String(parent.parent.location);b=(a.indexOf(sv_site_url)==0);}}catch(c){b=false;}return b;},sliderValToPx:function(d){var a=CY.DOM.winWidth();if(this.isInFrame()){a=parent.$(parent).width();}var b=d/100;b=Math.min(b,gConf.sliderFixedMin);b=Math.max(b,gConf.sliderFixedMax);var c=b*a;return Math.floor(c);},getTopICommentsWidth:function(){return this.getTopICommentsWidthFromWidth(this.sliderValToPx(gPrefs.get("layout","comments_col_width")));},getTopICommentsWidthFromWidth:function(b){var a=b-(2*gConf.iCommentThreadPadding);return a-7;},setLeftColumnWidth:function(a){CY.get("#contentcolumn").setStyle("marginLeft",a+"px");CY.get("#leftcolumn").setStyle("width",a+"px");},parentInterfaceUnfreeze:function(){if(this.isInFrame()){parent.f_interfaceUnfreeze();}}};Preferences=function(){this.prefs={};};Preferences.prototype={init:function(){this._read();},_read:function(){for(var b in gConf.defaultPrefs){this.prefs[b]={};for(var a in gConf.defaultPrefs[b]){var c=null;if(b=="user"&&(a=="name"||a=="email")){c=CY.Cookie.get("user_"+a);}else{c=CY.Cookie.getSub(b,a);}this.prefs[b][a]=(c==null)?gConf.defaultPrefs[b][a]:c;}}},persist:function(b,a,d){var c={path:"/",expires:(new Date()).setFullYear(2100,0,1)};if(b=="user"&&(a=="name"||a=="email")){CY.Cookie.set("user_"+a,d,c);}else{CY.Cookie.setSub(b,a,d,c);}this.prefs[b][a]=d;},get:function(b,a){return this.prefs[b][a];},readDefault:function(b,a){return gConf.defaultPrefs[b][a];},reset:function(a){for(var b=0;b<a.length;b++){var d=a[b];for(var c in gConf.defaultPrefs[d]){this.persist(d,c,gConf.defaultPrefs[d][c]);}}}};gShowingAllComments=false;Sync=function(){this._q=null;this._iPreventClick=false;};Sync.prototype={init:function(a){this._q=new CY.AsyncQueue();},setPreventClickOn:function(){CY.log("setPreventClickOn !");if(gLayout.isInFrame()){parent.f_interfaceFreeze();}this._iPreventClick=true;},setPreventClickOff:function(){CY.log("setPreventClickOff !");if(gLayout.isInFrame()){parent.f_interfaceUnfreeze();}this._iPreventClick=false;},removeCommentRet:function(b){var d=b.successfull;var a=(d)?b.failure["iComment"]:b.success["iComment"];if(d){var c=b.returned["filterData"];if(gLayout.isInFrame()){parent.f_updateFilterData(c);}var f=gIComments.getTopPosition()[1];var e=gDb.getComment(a.commentId);this._q.add(function(){unpaintCommentScope(e);gIComments.close(e.id);gIComments.remove(e.id);if(e.reply_to_id!=null){gIComments.refresh(e.reply_to_id);}gDb.del(e);if(gLayout.isInFrame()){if(gDb.comments.length==0&&gDb.allComments.length!=0){parent.f_enqueueMsg(gettext("no filtered comments left"));parent.resetFilter();}else{var g=gDb.computeFilterResults();updateFilterResultsCount(g.nbDiscussions,g.nbComments,g.nbReplies);}}});this._animateTo(f);}this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this.resume();},moderateCommentRet:function(c){var e=c.successfull;var a=(e)?c.failure["iComment"]:c.success["iComment"];if(e){var b=c.returned;var f=b.comment;gDb.upd(f);var d=gLayout.isInFrame()&&!parent.f_isFrameFilterFieldsInit();if(d){parent.resetFilter();this._showSingleComment(f);}else{a.changeModeration(f);}}this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this.resume();},saveCommentRet:function(h){var i=h.successfull;if(i){var l=h.success["formId"];var g=h.returned;removeFormErrMsg(l);if("errors" in g){var k=g.errors;for(var d in k){addFormErrMsg(l,d,k[d]);}this._animateToTop();}else{var b=function(){return(gNewReply!=null)&&(l==gNewReply.ids["formId"]);};var c=function(){return(gICommentForm!=null)&&(l==gICommentForm.formId);};var e=function(){return(gEdit!=null)&&(l==gEdit.ids["formId"]);};if(c()){this.hideICommentForm(cleanICommentForm());}else{if(e()){this._hideEditForm();}else{if(b()){this._hideNewReplyForm();}}}if("ask_for_notification" in g){if(g.ask_for_notification){parent.f_yesNoDialog(gettext("Do you want to be notified of all replies in all discussions you participated in?"),gettext("Reply notification"),function(){var m={method:"POST",data:urlEncode({fun:"ownNotify",key:sv_key,version_key:sv_version_key,email:g.email,active:false})};CY.io(sv_client_url,m);},this,null,function(){var m={method:"POST",data:urlEncode({fun:"ownNotify",key:sv_key,version_key:sv_version_key,email:g.email,active:true})};CY.io(sv_client_url,m);},this,null);}}if("comment" in g){var f=g.comment;gDb.upd(f);var a=gLayout.isInFrame()&&!parent.f_isFrameFilterFieldsInit();if(a){parent.resetFilter();}else{if(f.reply_to_id==null){unpaintCommentScope(f);paintCommentScope(f);}}var j=g.filterData;if(gLayout.isInFrame()){parent.f_updateFilterData(j);updateResetFilterResultsCount();}if(b()){if(!a){this._insertReply(f);}}else{this._showSingleComment(f);}}else{this._animateToTop();}}}else{this._q.add({id:"expl",fn:function(){CY.log("in example .........");}});this._q.promote("expl");}this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this.resume();},example:function(){CY.log("in example .........");},moderateComment:function(a,b){var c=gDb.getComment(a.commentId);this._q.add({fn:CY.bind(this.setPreventClickOn,this)},{autoContinue:false,fn:CY.bind(doExchange,null,"editComment",{comment_key:c.key,state:b},null,this.moderateCommentRet,this,{iComment:a},gettext("could not save comment"))}).run();},_saveComment:function(b,a){this._q.add({fn:CY.bind(this.setPreventClickOn,this)},{autoContinue:false,fn:CY.bind(doExchange,null,b,{},a,this.saveCommentRet,this,{formId:a},gettext("could not save comment"))}).run();},editComment:function(){this._saveComment("editComment",gEdit.ids["formId"]);},saveComment:function(a){this._saveComment("addComment",a);},removeComment:function(a){checkForOpenedDialog(a,function(){if(gLayout.isInFrame()){parent.f_yesNoDialog(gettext("Are you sure you want to delete this comment?"),gettext("Warning"),function(){this.animateToTop();},this,null,function(){var b=gDb.getComment(a.commentId);this._q.add({fn:CY.bind(this.setPreventClickOn,this)},{autoContinue:false,fn:CY.bind(doExchange,null,"removeComment",{comment_key:b.key},null,this.removeCommentRet,this,{iComment:a},gettext("could not remove comment"))}).run();},this,null);}},this,null);},resume:function(b,a){this._q.run();},resetAutoContinue:function(a){this._q.getCallback(a).autoContinue=true;},hideICommentForm:function(a){this._q.add({autoContinue:false,fn:CY.bind(gICommentForm.animationHide.run,gICommentForm.animationHide)});if(a){this._q.add(a);}},showCommentForm:function(a){checkForOpenedDialog(null,function(){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});this._q.add({fn:function(){if(a==null){var b=getSelectionInfo();updateICommentFormSelection(b);}showICommentForm(a);}});this._q.add({autoContinue:false,fn:CY.bind(gICommentForm.animationShow.run,gICommentForm.animationShow)},{fn:CY.bind(this.setPreventClickOff,this)}).run();},this,null);},showEditForm:function(a){checkForOpenedDialog(null,function(){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});this._q.add({fn:function(){showEditForm(a);}});this._animateToTop();this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this._q.run();},this,null);},showReplyForm:function(a){checkForOpenedDialog(null,function(){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});this._q.add({fn:function(){instanciateNewReplyForm(a);}});this._animateToTop();this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this._q.run();},this,null);},cancelICommentForm:function(){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});this.hideICommentForm();this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this._q.run();},cancelEdit:function(){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});this._q.add({fn:function(){cancelEditForm();}});this._animateToTop();this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this._q.run();},cancelReply:function(){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});this._q.add({fn:function(){cancelNewReplyForm();}});this._animateToTop();this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this._q.run();},changeScopeFormClick:function(){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});this._q.add({fn:function(){changeScopeFormClick();}});this._animateToTop();this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this._q.run();},_hideNewReplyForm:function(){this._q.add({fn:function(){cleanNewReplyForm();cancelNewReplyForm();}});},_hideEditForm:function(){this._q.add({fn:function(){cancelEditForm();}});},_insertReply:function(a){this._q.add({fn:function(){var g=gDb.getComment(a.reply_to_id);var e=gDb.getThreads([g]);var c=e[e.length-2];var d=gIComments.insertAfter(c,a);var h=gIComments.getPosition(a.reply_to_id);d.setPosition(h);var b=gDb.getPath(a);var f=b[b.length-1];if(gIComments.isTopActive(f.id)){d.activate();}d.show();}});this._animateToTop();},_showSingleComment:function(d){if(d!=null){var c=gDb.getPath(d);var b=c[c.length-1];var a=0;if(d.start_wrapper!=-1){a=CY.get(".c-id-"+b.id).getY();}else{a=CY.get("document").get("scrollTop");}this._showComments([b.id],a,false);if(b.replies.length>0){this._animateTo(a);}}},showSingleComment:function(a){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});this._showSingleComment(a);this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this._q.run();},browse:function(a,b){var c=gIComments.browse(a,b);if(c!=null){this.showSingleComment(c);}},_showComments:function(c,b,a){this._q.add({fn:function(){gShowingAllComments=a;gIComments.hide();var d=CY.Array.map(c,function(g){return gDb.getComment(g);});var f=gDb.getThreads(d);gIComments.fetch(f);if(c.length>0){if(a){CY.get("document").set("scrollTop",0);}else{gIComments.activate(c[0]);var e=CY.get(".c-id-"+c[0]);if(e&&!e.inViewportRegion()){e.scrollIntoView(true);}}}gIComments.setPosition([gConf.iCommentLeftPadding,b]);gIComments.show();}});},_animateTo:function(a){this._q.add({fn:function(){gIComments.setAnimationToPositions(a);}},{id:"animationRun",autoContinue:false,fn:CY.bind(gIComments.runAnimations,gIComments)});},_animateToTop:function(){var a=gIComments.getTopPosition();if(a!=null){this._animateTo(a[1]);}},animateToTop:function(){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});this._animateToTop();this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this._q.run();},showAllComments:function(){checkForOpenedDialog(null,function(){gShowingAllComments=true;var a=CY.Array.map(gDb.comments,function(b){return b.id;});this.showComments(a,[0,0],true);},this,null);},showScopeRemovedComments:function(){checkForOpenedDialog(null,function(){gShowingAllComments=true;var b=CY.Array.filter(gDb.comments,function(c){return(c.start_wrapper==-1);});var a=CY.Array.map(b,function(d){return d.id;});this.showComments(a,[0,0],true);},this,null);},showComments:function(c,b,a){checkForOpenedDialog(null,function(){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});this._showComments(c,b[1],a);this._animateTo(b[1]);this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this._q.run();},this,null);},openComment:function(a){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});var b=gIComments.getTopPosition()[1];this._q.add({fn:function(){gIComments.open(a.commentId);gIComments.refresh(a.commentId);}});this._animateTo(b);this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this._q.run();},closeComment:function(a){checkForOpenedDialog(a,function(){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});var b=gIComments.getTopPosition()[1];this._q.add({fn:function(){var c=gDb.getComment(a.commentId);gIComments.close(a.commentId);if(c.reply_to_id!=null){gIComments.refresh(c.reply_to_id);}}});this._animateTo(b);this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this._q.run();},this,null);},activate:function(a){gIComments.activate(a.commentId);}};readyForAction=function(){return !gSync._iPreventClick;};getWrapperAncestor=function(a){var b=a;while(b!=null){if(CY.DOM.hasClass(b,"c-s")){return b;}b=b.parentNode;}return null;};hasWrapperAncestor=function(a){return(getWrapperAncestor(a)!=null);};getSelectionInfo=function(){var J=null,m=null,D=0,c=0,h="";if(window.getSelection){var r=window.getSelection();if(r.rangeCount>0){var l=r.getRangeAt(0);h=l.toString();if(h!=""){var E=document.createRange();E.setStart(r.anchorNode,r.anchorOffset);E.collapse(true);var B=document.createRange();B.setEnd(r.focusNode,r.focusOffset);B.collapse(false);var I=(B.compareBoundaryPoints(2,E)==1);J=(I)?r.anchorNode.parentNode:r.focusNode.parentNode;innerStartNode=(I)?r.anchorNode:r.focusNode;m=(I)?r.focusNode.parentNode:r.anchorNode.parentNode;innerEndNode=(I)?r.focusNode:r.anchorNode;D=(I)?r.anchorOffset:r.focusOffset;c=(I)?r.focusOffset:r.anchorOffset;if(!hasWrapperAncestor(m)&&hasWrapperAncestor(J)){var z=document.createRange();z.setStart(innerStartNode,D);var b=getWrapperAncestor(J);var q=b;z.setEndAfter(q);var f=parseInt(b.id.substring("sv_".length));while(z.toString().length<l.toString().length){f++;var t=CY.get("#sv_"+f);if(t){q=CY.Node.getDOMNode(t);z.setEndAfter(q);}else{break;}}m=q.lastChild;c=CY.DOM.getText(m).length;}else{if(!hasWrapperAncestor(J)&&hasWrapperAncestor(m)){var z=document.createRange();z.setEnd(innerEndNode,c);var g=getWrapperAncestor(m);var p=g;z.setStartBefore(p);var f=parseInt(g.id.substring("sv_".length));while(z.toString().length<l.toString().length){f--;var t=CY.get("#sv_"+f);if(t){p=CY.Node.getDOMNode(t);z.setStartBefore(p);}else{break;}}J=p.firstChild;D=0;}else{if(!hasWrapperAncestor(J)&&!hasWrapperAncestor(m)){var o=h.length;var n=[];for(var f=0;;f++){var G=CY.get("#sv_"+f);if(G==null){break;}else{var x=G.get("text");if(h.indexOf(x)==0){n.push(f);}}}var y=[];for(var f=0;;f++){var G=CY.get("#sv_"+f);if(G==null){break;}else{var x=G.get("text");if(h.indexOf(x)==(o-x.length)){y.push(f);}}}var w=false;for(var C=0;C<n.length;C++){for(var A=0;A<y.length;A++){var v=document.createRange();var k=CY.Node.getDOMNode(CY.get("#sv_"+n[C]));var F=CY.Node.getDOMNode(CY.get("#sv_"+y[A]));v.setStartBefore(k);v.setEndAfter(CY.Node.getDOMNode(F));if((-1<v.compareBoundaryPoints(0,l))&&(1>v.compareBoundaryPoints(2,l))){J=k.firstChild;D=0;m=F.lastChild;c=CY.DOM.getText(F).length;w=true;break;}}if(w){break;}}}}}E.detach();B.detach();}else{return null;}}else{return null;}}else{if(document.selection){var d=document.selection.createRange();if(d.text.length==0){return null;}var a=d.parentElement();var H=d.duplicate();var u=d.duplicate();H.collapse(true);u.collapse(false);J=H.parentElement();while(H.moveStart("character",-1)!=0){if(H.parentElement()!=J){break;}D++;}m=u.parentElement();while(u.moveEnd("character",-1)!=0){if(u.parentElement()!=m){break;}c++;}h=d.text;}}if(!hasWrapperAncestor(J)||!hasWrapperAncestor(m)){return null;}return{text:h,start:{elt:J,offset:D},end:{elt:m,offset:c}};};Db=function(){this.comments=null;this.allComments=null;this.commentsByDbId={};this.allCommentsByDbId={};this.ordered_comment_ids={};};Db.prototype={init:function(){this.allComments=CY.JSON.parse(sv_comments);if(sv_read_only){this.initToReadOnly();}this._computeAllCommentsByDbId();this._reorder();},_del:function(a,e,g){var f=e[g];for(var c=0;c<f.replies.length;c++){var d=f.replies[c].id;this._del(f.replies,e,d);c--;}for(var c=0,b=a.length;c<b;c++){if(a[c].id==g){a.splice(c,1);delete e[g];break;}}},del:function(b){var a=(b.reply_to_id==null)?this.comments:this.commentsByDbId[b.reply_to_id].replies;this._del(a,this.commentsByDbId,b.id);a=(b.reply_to_id==null)?this.allComments:this.allCommentsByDbId[b.reply_to_id].replies;this._del(a,this.allCommentsByDbId,b.id);this._reorder();},_reorder:function(){var n=[];for(var k=0,c=this.allComments.length;k<c;k++){var l=this.allComments[k];var r=false;for(var g=0,q=n.length;g<q;g++){var b=n[g];var f=this.allCommentsByDbId[b];if((l.start_wrapper<f.start_wrapper)||((l.start_wrapper==f.start_wrapper)&&(l.start_offset<f.start_offset))||((l.start_wrapper==f.start_wrapper)&&(l.start_offset==f.start_offset)&&(l.end_wrapper<f.end_wrapper))||((l.start_wrapper==f.start_wrapper)&&(l.start_offset==f.start_offset)&&(l.end_wrapper==f.end_wrapper)&&(l.end_offset<f.end_offset))){n.splice(g,0,l.id);r=true;break;}}if(!r){n.push(l.id);}}this.ordered_comment_ids.scope=n;n=[];var m={};for(var k=0,c=this.allComments.length;k<c;k++){var l=this.allComments[k];var o=l.modified;m[l.id]=o;for(var g=0,q=l.replies.length;g<q;g++){var e=l.replies[g];var d=e.modified;if(d>m[l.id]){m[l.id]=d;}}}for(var b in m){var h=this.allCommentsByDbId[b].id;var r=false;for(var k=0,c=n.length;k<c;k++){var p=n[k];if(m[b]<m[p]){n.splice(k,0,h);r=true;break;}}if(!r){n.push(h);}}this.ordered_comment_ids.modif_thread=n;},_upd:function(a,f,g){var e=false;for(var d=0,b=a.length;d<b;d++){if(a[d].id==g.id){a.splice(d,1,g);e=true;break;}}if(!e){a.push(g);}f[g.id]=g;},upd:function(c){var a=(c.reply_to_id==null)?this.allComments:this.allCommentsByDbId[c.reply_to_id].replies;this._upd(a,this.allCommentsByDbId,c);var b=CY.clone(c);a=(c.reply_to_id==null)?this.comments:this.commentsByDbId[c.reply_to_id].replies;this._upd(a,this.commentsByDbId,b);this._reorder();},initComments:function(a){this.comments=[];for(var d=0,c=this.allComments.length;d<c;d++){var b=CY.Array.indexOf(a,this.allComments[d].id);if(b!=-1){var e=CY.clone(this.allComments[d]);this.comments.push(e);}}this._computeCommentsByDbId();},_computeCommentsByDbId:function(){this.commentsByDbId={};var b=this.getThreads(this.comments);for(var a=0;a<b.length;a++){this.commentsByDbId[b[a].id]=b[a];}},_computeAllCommentsByDbId:function(){this.allCommentsByDbId={};var b=this.getThreads(this.allComments);for(var a=0;a<b.length;a++){this.allCommentsByDbId[b[a].id]=b[a];}},getThreads:function(c){var a=[];for(var b=0;b<c.length;b++){a.push(c[b]);if(c[b].replies.length>0){a=a.concat(this.getThreads(c[b].replies));}}return a;},_getPath:function(b,e){var a=[e];var d=e;while(d.reply_to_id!=null){d=b[d.reply_to_id];a.push(d);}return a;},getPath:function(a){return this._getPath(this.commentsByDbId,a);},getComment:function(a){return this.commentsByDbId[a];},getCommentByIdKey:function(a){for(var c in this.commentsByDbId){var b=this.commentsByDbId[c];if(b.id_key==a){return b;}}return null;},isChild:function(d,b){var c=this.commentsByDbId[d];var a=(d==b);while((!a)&&(c.reply_to_id!=null)){c=this.commentsByDbId[c.reply_to_id];a=(c.id==b);}return a;},initToReadOnly:function(f,c){for(var b=0,a=this.allComments.length;b<a;b++){var e=this.allComments[b];for(var d in e){if(0==d.indexOf("can_")&&typeof e[d]==="boolean"){e[d]=false;}}}},browsingIndex:function(b){var c={};for(var a in this.ordered_comment_ids){var d=CY.Array.filter(this.ordered_comment_ids[a],function(e){return(e in this.commentsByDbId);},this);c[a]=CY.Array.indexOf(d,b);}return c;},browse:function(b,f,c){var a=this.ordered_comment_ids[b];if(a.length>0){var g=-1;if((f=="prev")||(f=="next")){for(var e=0;e<a.length;e++){var h=a[e];if(h==c){g=(f=="prev")?e-1:e+1;g=(a.length+g)%a.length;break;}}if(g==-1){CY.error("internal error in db browse (was called with a dbId that isn't among the filtered ones)");return null;}}if(f=="last"){g=a.length-1;}if(f=="first"){g=0;}for(var e=g,d=0;(e>=0)&&(e<a.length);d++){var h=a[e];if(h in this.commentsByDbId){return this.commentsByDbId[h];}if((f=="prev")||(f=="last")){e=e-1;}else{e=e+1;}e=(a.length+e)%a.length;if(d>a.length){break;}}CY.error("internal error in db browse (could not find any filtered comment)");}return null;},computeFilterResults:function(n){var a={};if(n){for(key in n){if(key.indexOf("filter_")==0){a[key.substr("filter_".length)]=n[key];}}}else{if(gLayout.isInFrame()){a=parent.f_getFrameFilterData();}}var v=[];var w=[];var b="";if("name" in a){b=a.name;}this.filterByName(b,v,w);var p=[];var c=[];var C="";if("date" in a){C=a.date;}this.filterByDate(C,p,c);var g=[];var f=[];var t="";if("text" in a){t=a.text;}this.filterByText(t,g,f);var x=[];var m=[];var A="";if("tag" in a){A=a.tag;}this.filterByTag(A,x,m);var u=[];var e=[];var k="";if("state" in a){k=a.state;}this.filterByState(k,u,e);var d=[];var z=[];for(var y=0,j=v.length;y<j;y++){var s=v[y];if((CY.Array.indexOf(p,s)!=-1)&&(CY.Array.indexOf(g,s)!=-1)&&(CY.Array.indexOf(x,s)!=-1)&&(CY.Array.indexOf(u,s)!=-1)){d.push(s);}}for(var y=0,j=w.length;y<j;y++){var s=w[y];if((CY.Array.indexOf(c,s)!=-1)&&(CY.Array.indexOf(f,s)!=-1)&&(CY.Array.indexOf(m,s)!=-1)&&(CY.Array.indexOf(e,s)!=-1)){z.push(s);}}var q=z.length,l=d.length;var r=l;for(var y=0,j=z.length;y<j;y++){var s=z[y];var o=this.allCommentsByDbId[s];var B=this._getPath(this.allCommentsByDbId,o);var h=B[B.length-1];var s=h.id;if(CY.Array.indexOf(d,s)==-1){d.push(s);r++;}}return{commentIds:d,nbDiscussions:r,nbComments:l,nbReplies:q};},filterByText:function(c,f,b){var a=new RegExp(c,"gi");for(var e in this.allCommentsByDbId){var d=this.allCommentsByDbId[e];if(c==""||a.exec(d.title)!=null||a.exec(d.content)!=null){if(d.reply_to_id==null){f.push(d.id);}else{b.push(d.id);}}}},filterByName:function(a,c,b){for(var e in this.allCommentsByDbId){var d=this.allCommentsByDbId[e];if(a==""||d.name==a){if(d.reply_to_id==null){c.push(d.id);}else{b.push(d.id);}}}},filterByTag:function(i,e,b){var h=new RegExp("^"+i+"$","g");var g=new RegExp("^"+i+", ","g");var d=new RegExp(", "+i+", ","g");var c=new RegExp(", "+i+"$","g");for(var a in this.allCommentsByDbId){var f=this.allCommentsByDbId[a];if(i==""||h.exec(f.tags)||g.exec(f.tags)!=null||d.exec(f.tags)!=null||c.exec(f.tags)!=null){if(f.reply_to_id==null){e.push(f.id);}else{b.push(f.id);}}}},filterByState:function(c,a,b){for(var e in this.allCommentsByDbId){var d=this.allCommentsByDbId[e];if(c==""||d.state==c){if(d.reply_to_id==null){a.push(d.id);}else{b.push(d.id);}}}},filterByDate:function(b,d,a){var c=(b=="")?0:parseInt(b);for(var f in this.allCommentsByDbId){var e=this.allCommentsByDbId[f];if(e.modified>c){if(e.reply_to_id==null){d.push(e.id);}else{a.push(e.id);}}}},getCommentsAndRepliesCounts:function(d){var b=0;var f=0;var a=(d)?this.allComments:this.comments;var e=this.getThreads(a);for(var c=0;c<e.length;c++){if(e[c].reply_to_id==null){b++;}else{f++;}}return[b,f];},getCommentsNb:function(b){var a=(b)?this.allComments:this.comments;return this.getThreads(a).length;},getFilteredCommentIdsAsString:function(){var a="";for(var b in this.commentsByDbId){a=a+b+",";}return a;}};IComment=function(){this.commentId=null;var l=gLayout.getTopICommentsWidth();var a=gConf.iCommentLeftPadding;var r=gettext("change comment state to pending");var n=gettext("change comment state to approved");var e=gettext("change comment state to unapproved");var q=gettext("cancel changing the state of this comment");var c=gettext("pending");var d=gettext("approved");var m=gettext("unapproved");var b=gettext("cancel");var p=gettext("show replies");var s=gettext("change to:");var i=ngettext("reply","replies",1);var g=gettext("edit comment");var j=gettext("delete comment");var o=gettext("edit");var f=gettext("delete");var k=gettext("close");var h=gettext("show scope");var t=gettext("Comment is detached: it was created on a previous version and text it applied to has been modified or removed.");this.overlay=new CY.Overlay({zIndex:3,shim:false,visible:false,width:l,xy:[a,0],headerContent:'<div class="icomment-header"><div class="c-iactions"><a class="c-moderate c-action" title="">vis</a> <a class="c-edit c-action" title="'+g+'" alt="'+g+'">'+o+'</a> <a class="c-delete c-action" title="'+j+'" alt="'+j+'">'+f+'</a> </div><div class="c-state-actions displaynone">'+s+'&nbsp;<a class="c-state-pending c-action" title="'+r+'" alt="'+r+'">'+c+'</a> <a class="c-state-approved c-action" title="'+n+'" alt="'+n+'">'+d+'</a> <a class="c-state-unapproved c-action" title="'+e+'" alt="'+e+'">'+m+'</a> <a class="c-state-cancel c-action" title="'+q+'" alt="'+q+'">'+b+'</a> </div><div class="c-no-scope-msg">'+t+'</div><a class="c-show-scope c-action" title="'+h+'" alt="'+h+'"><em>-</em></a><a class="c-close c-action" title="'+k+'" alt="'+k+'"><em>X</em></a></div>',bodyContent:'<div class="icomment-body"><span class="c-content"></span><span class="c-ireplyactions"><a class="c-readreplies c-action" title="'+p+'" alt="'+p+'">'+p+'</a> <a class="c-reply c-action" title="'+i+'" alt="'+i+'">'+i+"</a>&nbsp;</span></div>"});this.overlay.get("contentBox").addClass("c-comment");this.overlay.render("#leftcolumn");this.animation=new CY.Anim({node:this.overlay.get("boundingBox"),duration:gPrefs.get("general","animduration"),easing:CY.Easing.easeOut});this.overlay.get("contentBox").query(".c-close").on("click",this.onCloseCommentClick,this);this.overlay.get("contentBox").query(".c-moderate").on("click",this.onModerateCommentClick,this);this.overlay.get("contentBox").query(".c-state-pending").on("click",this.onPendingCommentClick,this);this.overlay.get("contentBox").query(".c-state-approved").on("click",this.onApprovedCommentClick,this);this.overlay.get("contentBox").query(".c-state-unapproved").on("click",this.onUnapprovedCommentClick,this);this.overlay.get("contentBox").query(".c-state-cancel").on("click",this.onCancelStateChangeClick,this);this.overlay.get("contentBox").query(".c-edit").on("click",this.onEditCommentClick,this);this.overlay.get("contentBox").query(".c-delete").on("click",this.onDeleteCommentClick,this);this.overlay.get("contentBox").query(".c-reply").on("click",this.onReplyCommentClick,this);this.overlay.get("contentBox").query(".c-readreplies").on("click",this.onReadRepliesCommentClick,this);this.overlay.get("contentBox").query(".icomment-header").on("mouseenter",this.onMouseEnterHeader,this);this.overlay.get("contentBox").query(".icomment-header").on("mouseleave",this.onMouseLeaveHeader,this);this.overlay.get("contentBox").on("click",this.onCommentClick,this);};IComment.prototype={onCloseCommentClick:function(a){a.halt();if(readyForAction()&&this.isVisible()){gSync.closeComment(this);}},onModerateCommentClick:function(a){a.halt();if(readyForAction()&&this.isVisible()){this.overlay.get("contentBox").query(".c-iactions").addClass("displaynone");this.overlay.get("contentBox").query(".c-state-actions").removeClass("displaynone");}},onPendingCommentClick:function(a){a.halt();if(readyForAction()&&this.isVisible()){gSync.moderateComment(this,"pending");}},onApprovedCommentClick:function(a){a.halt();if(readyForAction()&&this.isVisible()){gSync.moderateComment(this,"approved");}},onUnapprovedCommentClick:function(a){a.halt();if(readyForAction()&&this.isVisible()){gSync.moderateComment(this,"unapproved");}},onCancelStateChangeClick:function(a){a.halt();if(readyForAction()&&this.isVisible()){this.overlay.get("contentBox").query(".c-iactions").removeClass("displaynone");this.overlay.get("contentBox").query(".c-state-actions").addClass("displaynone");}},onDeleteCommentClick:function(a){a.halt();if(readyForAction()&&this.isVisible()){gSync.removeComment(this);}},onEditCommentClick:function(a){a.halt();if(readyForAction()&&this.isVisible()){gSync.showEditForm(this);}},onReplyCommentClick:function(a){a.halt();if(readyForAction()&&this.isVisible()){gSync.showReplyForm(this);}},onReadRepliesCommentClick:function(a){a.halt();if(readyForAction()&&this.isVisible()){gSync.openComment(this);}},onCommentClick:function(d){if(readyForAction()&&this.isVisible()){if(d.target.get("target")=="_blank"){var b=d.target;var g=sv_site_url+sv_text_view_show_comment_url;if(b.get("href").indexOf(g)==0){var a=(new RegExp("comment_id_key=([^&]*)","g")).exec(b.get("href"));if(a!=null){var c=a[1];var f=gDb.getCommentByIdKey(c);if(f!=null){d.halt();if(!b.hasClass("c-permalink")){checkForOpenedDialog(null,function(){gSync.showSingleComment(f);});}}}}}else{if(gShowingAllComments){if(!this._isHostingAForm()){var f=gDb.getComment(this.commentId);checkForOpenedDialog(null,function(){if(f!=null){gSync.showSingleComment(f);}});}}else{gSync.activate(this);}}}},onMouseEnterHeader:function(){if(readyForAction()&&this.isVisible()){this.overlay.get("contentBox").query(".c-permalink").removeClass("displaynone");}},onMouseLeaveHeader:function(){if(readyForAction()&&this.isVisible()){this.overlay.get("contentBox").query(".c-permalink").addClass("displaynone");}},setWidth:function(a){this.overlay.get("boundingBox").setStyle("width",a+"px");},activate:function(){this.overlay.get("boundingBox").addClass("c-focus-comment");},deactivate:function(){this.overlay.get("boundingBox").removeClass("c-focus-comment");},hide:function(){if(gIComments.isTopActive(this.commentId)){if(!gIComments.activateVisibleNext()){gIComments.deactivate();}}if(this.isVisible()){this.overlay.hide();this.overlay.blur();}},hideContent:function(){this.overlay.get("contentBox").query(".icomment-header").addClass("displaynone");this.overlay.get("contentBox").query(".icomment-body").addClass("displaynone");},showContent:function(){this.overlay.get("contentBox").query(".icomment-header").removeClass("displaynone");this.overlay.get("contentBox").query(".icomment-body").removeClass("displaynone");},isVisible:function(){return this.overlay.get("visible");},show:function(){this.hideReadRepliesLnk();return this.overlay.show();},showReadRepliesLnk:function(){this.overlay.get("contentBox").query(".c-readreplies").removeClass("displaynone");},hideReadRepliesLnk:function(){this.overlay.get("contentBox").query(".c-readreplies").addClass("displaynone");},changeModeration:function(b){var a=this.overlay.get("contentBox").query(".c-moderate");a.set("innerHTML",gettext(b.state));a.removeClass("c-state-approved");a.removeClass("c-state-pending");a.removeClass("c-state-unapproved");a.addClass("c-state-"+b.state);this.overlay.get("contentBox").query(".c-iactions").removeClass("displaynone");this.overlay.get("contentBox").query(".c-state-actions").addClass("displaynone");},isfetched:function(){return(this.commentId!=null);},unfetch:function(){this.commentId=null;},fetch:function(h){this.commentId=h.id;var b=this.overlay.get("boundingBox");if(h.start_wrapper!=-1){b.addClass("c-has-scope");b.removeClass("c-has-no-scope");}else{b.addClass("c-has-no-scope");b.removeClass("c-has-scope");}if(h.reply_to_id!=null){b.addClass("c-is-reply");}else{b.removeClass("c-is-reply");}var f=interpolate(gettext("last modified on %(date)s"),{date:h.modified_user_str},true);var k=(h.modified==h.created)?"":'<a title="'+f+'"> * </a>';var i=gettext("Permalink to this comment");var n='<a class="c-permalink displaynone c-action" target="_blank" title="'+i+'" href="" >¶&nbsp;</a>';var j=interpolate(gettext("by %(name)s, created on %(date)s"),{name:h.name,date:h.created_user_str},true);var c='<span class="c-header"><div class="c-header-title">'+h.title+n+'</div><div class="c-infos">'+j+"</div></span>";var d=CY.Node.create(c);var o=b.query(".c-header");if(o==null){b.query(".icomment-header").insertBefore(d,b.one(".c-iactions"));}else{o.get("parentNode").replaceChild(d,o);}var g=CY.Node.create('<div class="c-tags"><span class="c-tags-infos">tags:</span>'+h.tags+"</div>");var m=b.query(".c-tags");if(m==null){b.query(".icomment-header").appendChild(g);}else{m.get("parentNode").replaceChild(g,m);}if(h.tags==""){g.addClass("displaynone");}var e=CY.Node.create('<span class="c-content">'+h.content_html+"</span>");var a=b.query(".c-content");if(a==null){b.query(".icomment-body").appendChild(e);}else{a.get("parentNode").replaceChild(e,a);}b.query(".c-permalink").set("href",sv_site_url+h.permalink);this.changeModeration(h);var l=b.queryAll(".c-content a");if(l!=null){l.setAttribute("target","_blank");}l=b.queryAll(".c-header-title a");if(l!=null){l.setAttribute("target","_blank");}this.permAdapt(h);},permAdapt:function(e){var b=this.overlay.get("contentBox").query(".c-delete");if(b){if(!e.can_delete){b.addClass("displaynone");}else{b.removeClass("displaynone");}}var a=this.overlay.get("contentBox").query(".c-edit");if(a){if(!e.can_edit){a.addClass("displaynone");}else{a.removeClass("displaynone");}}var d=this.overlay.get("contentBox").query(".c-reply");if(d){if(!hasPerm("can_create_comment")){d.addClass("displaynone");}else{d.removeClass("displaynone");}}var c=this.overlay.get("contentBox").query(".c-moderate");if(c){if(!e.can_moderate){c.addClass("displaynone");}else{c.removeClass("displaynone");}}},setThreadPad:function(a){this.overlay.get("contentBox").query(".yui-widget-hd").setStyle("paddingLeft",a+"px");this.overlay.get("contentBox").query(".yui-widget-bd").setStyle("paddingLeft",a+"px");},setPosition:function(b){var a=this.overlay.get("boundingBox");a.setStyle("opacity",1);a.setXY(b);},getPosition:function(b){var a=this.overlay.get("boundingBox");return a.getXY();},onAnimationEnd:function(){if(!CY.Lang.isUndefined(this["animation-handle"])&&!CY.Lang.isNull(this["animation-handle"])){this["animation-handle"].detach();this["animation-handle"]=null;}gIComments.signalAnimationEnd();if(gIComments.animationsEnded()){gIComments.whenAnimationsEnd();}},setAnimationToPosition:function(b){var a=this.overlay.get("boundingBox");if(gPrefs.get("general","animduration")<0.011){a.setXY(b);}this.animation.set("to",{xy:b});this.animation.set("duration",gPrefs.get("general","animduration"));this["animation-handle"]=this.animation.on("end",this.onAnimationEnd,this);return this.animation;},getHeight:function(){return this.overlay.get("boundingBox").get("offsetHeight");},scrollIntoView:function(){if(!this.overlay.get("contentBox").inViewportRegion()){this.overlay.get("contentBox").scrollIntoView(true);}},_isHostingAForm:function(){return(this.isVisible()&&((gNewReplyHost!=null&&gNewReplyHost==this)||(gEditICommentHost!=null&&gEditICommentHost==this)));}};gEditICommentHost=null;gEdit=null;dbgc=null;showEditForm=function(a){if(gEdit==null){gEdit={ids:{formId:CY.guid(),formTitleId:CY.guid(),nameInputId:CY.guid(),emailInputId:CY.guid(),titleInputId:CY.guid(),contentInputId:CY.guid(),tagsInputId:CY.guid(),formatInputId:CY.guid(),startWrapperInputId:CY.guid(),endWrapperInputId:CY.guid(),startOffsetInputId:CY.guid(),endOffsetInputId:CY.guid(),changeScopeInputId:CY.guid(),changeScopeInputWrapper:CY.guid(),selectionPlaceId:CY.guid(),keyId:CY.guid(),editCommentId:CY.guid(),currentSelId:CY.guid(),currentSelIdI:CY.guid(),addBtnId:CY.guid(),cancelBtnId:CY.guid()},handlers:{}};}gEditICommentHost=a;gEditICommentHost.hideContent();var c=getHtml(gEdit.ids);var b='<div class="icomment-edit-header">'+c.headerContent+"</div>";var e='<div class="icomment-edit-body">'+c.bodyContent+"</div>";gEditICommentHost.overlay.setStdModContent(CY.WidgetStdMod.HEADER,CY.Node.create(b),CY.WidgetStdMod.AFTER);gEditICommentHost.overlay.setStdModContent(CY.WidgetStdMod.BODY,CY.Node.create(e),CY.WidgetStdMod.AFTER);CY.get("#"+gEdit.ids["formTitleId"]).set("innerHTML",gettext("Edit comment"));var f=gDb.getComment(gEditICommentHost.commentId);CY.get("#"+gEdit.ids["editCommentId"]).set("value",f.id);CY.get("#"+gEdit.ids["keyId"]).set("value",f.key);CY.get("#"+gEdit.ids["changeScopeInputId"]+" input").set("checked",false);if(f.reply_to_id!=null){CY.get("#"+gEdit.ids["changeScopeInputId"]).addClass("displaynone");}changeScopeFormClick();CY.get("#"+gEdit.ids["nameInputId"]).set("value",f.name);CY.get("#"+gEdit.ids["emailInputId"]).set("value",f.email);if(f.logged_author){CY.get("#"+gEdit.ids["nameInputId"]).setAttribute("disabled",true);CY.get("#"+gEdit.ids["emailInputId"]).setAttribute("disabled",true);}CY.get("#"+gEdit.ids["titleInputId"]).set("value",f.title);CY.get("#"+gEdit.ids["contentInputId"]).set("value",f.content);CY.get("#"+gEdit.ids["tagsInputId"]).set("value",f.tags);CY.get("#"+gEdit.ids["formatInputId"]).set("value",gConf.defaultCommentFormat);var d=gLayout.getTopICommentsWidth();changeFormFieldsWidth(gEdit.ids["formId"],d);gEdit.handlers["addBtnId"]=CY.on("click",onEditSaveClick,"#"+gEdit.ids["addBtnId"]);gEdit.handlers["cancelBtnId"]=CY.on("click",onEditCancelClick,"#"+gEdit.ids["cancelBtnId"]);gEdit.handlers["changeScope"]=CY.on("click",onChangeScopeClick,"#"+gEdit.ids["changeScopeInputId"]);};onEditSaveClick=function(a){if(readyForAction()){gSync.editComment();}};onEditCancelClick=function(a){if(readyForAction()){gSync.cancelEdit();}};onChangeScopeClick=function(){if(readyForAction()){gSync.changeScopeFormClick();}else{var a=CY.get("#"+gEdit.ids["changeScopeInputId"]+" input");var b=a.get("checked");a.set("checked",!b);}};changeScopeFormClick=function(){var a=CY.get("#"+gEdit.ids["currentSelId"]);if(CY.get("#"+gEdit.ids["changeScopeInputId"]+" input").get("checked")){a.removeClass("displaynone");}else{a.addClass("displaynone");}};cancelEditForm=function(){if(gEditICommentHost!=null){for(var b in gEdit.handlers){if(gEdit.handlers[b]!=null){gEdit.handlers[b].detach();gEdit.handlers[b]=null;}}var a=gEditICommentHost.overlay.get("contentBox").query(".icomment-edit-body");a.get("parentNode").removeChild(a);a=gEditICommentHost.overlay.get("contentBox").query(".icomment-edit-header");a.get("parentNode").removeChild(a);gEditICommentHost.showContent();gEditICommentHost=null;}};var gtest={renaud:"RENAUD",random:Math.random(),bernard:"BERNARD",myFunc:function(){doExchange("theServerFun",{},null,this.myRetFunc,this,["foo","bar"]);},myRetFunc:function(a){CY.log("this.renaud : "+this.renaud);CY.log("this.random : "+this.random);CY.log("arg.returned : "+a.returned);CY.log(a.returned);CY.log("arg.success : "+a.success);CY.log(a.success);}};doExchange=function(h,e,g,f,d,c,b){e.fun=h;e.key=sv_key;e.version_key=sv_version_key;var a={method:"POST",data:urlEncode(e),on:{success:function(l,k,j){var i={};if(k.responseText){i=CY.JSON.parse(k.responseText);}if(gLayout.isInFrame()&&("msg" in i)){parent.f_enqueueMsg(i.msg);}j.returned=i;j.successfull=true;f.call(d,j);},failure:function(k,j,i){if(gLayout.isInFrame()){parent.f_enqueueErrorMsg(gettext("error:")+b);}i.successfull=false;f.call(d,i);}},arguments:{success:c,failure:c}};if(g!=null){a.form={id:g};}CY.io(sv_client_url,a);};warn_server=function(c){c.fun="warn";c.key=sv_key;c.version_key=sv_version_key;var b=CY.UA;var a={method:"POST",data:urlEncode(CY.merge(c,b))};CY.io("/client/",a);};paintCommentScope=function(b){if(b.reply_to_id==null&&b.start_wrapper!=-1){var a={start:{elt:document.getElementById("sv_"+b.start_wrapper),offset:b.start_offset},end:{elt:document.getElementById("sv_"+b.end_wrapper),offset:b.end_offset}};if(document.getElementById("sv_"+b.start_wrapper)==null){warn_server({from:"paintCommentScope",start_wrapper:b.start_wrapper});}else{if(document.getElementById("sv_"+b.end_wrapper)==null){warn_server({from:"paintCommentScope",end_wrapper:b.end_wrapper});}else{a.start=_convertSelectionFromCSToCC(a.start);a.end=_convertSelectionFromCSToCC(a.end);renderComment(a,b.id);}}}};getCommentIdsFromClasses=function(b){var a=[];var e=b.className.split(" ");for(var d=0,c=e.length;d<c;d++){if(e[d].indexOf("c-id-")==0){a.push(parseInt(e[d].substring("c-id-".length)));}}return a;};renderComment=function(d,c){var a=d.start["offset"];var b=d.end["offset"];var f=d.start["elt"];var e=d.end["elt"];if((f!=null)&&(e!=null)&&_getTextNodeContent(f)!=""&&_getTextNodeContent(e)!=""){markWholeNodesAsComments(f,e,c);markEndsAsComments(f,a,e,b,c);}};markWholeNodesAsComments=function(d,c,b){var a=_findCommonAncestor(d,c);_dynSpanToAnc(d,a,b,false);_dynSpanToAnc(c,a,b,true);_dynSpanInBetween(a,d,c,b);};_setTextNodeContent=function(a,b){CY.DOM.setText(a,b);};_getTextNodeContent=function(a){return CY.DOM.getText(a);};markEndsAsComments=function(d,i,l,j,h){var n=_getTextNodeContent(d).substring(0,i);var o=_getTextNodeContent(d).substring(i);var p=_getTextNodeContent(l).substring(0,j);var g=_getTextNodeContent(l).substring(j);var b=(d===l);if(o!=""){if(CY.DOM.hasClass(d,"c-c")){var f=null,k=null,c=null,a=null;var m=(b)?_getTextNodeContent(d).substring(i,j):o;if(b&&(g!="")){c=d;f=c;}if(m!=""){if(f==null){k=d;}else{k=_yuiCloneNode(d);f.parentNode.insertBefore(k,f);}f=k;}if(n!=""){if(f==null){a=d;}else{a=_yuiCloneNode(d);f.parentNode.insertBefore(a,f);}f=a;}if(c!=null){_setTextNodeContent(c,g);}if(k!=null){_setTextNodeContent(k,m);_addIdClass(k,h);}if(a!=null){_setTextNodeContent(a,n);}}}if((!b)&&(p!="")){if(CY.DOM.hasClass(l,"c-c")){var f=null,e=null,c=null;if(g!=""){c=l;f=l;}if(p!=""){if(f==null){e=l;}else{e=_yuiCloneNode(l);f.parentNode.insertBefore(e,f);}f=e;}if(c!=null){_setTextNodeContent(c,g);}if(e!=null){_addIdClass(e,h);_setTextNodeContent(e,p);}}}};_yuiCloneNode=function(b){var a=CY.Node.getDOMNode(CY.get("#"+b.id).cloneNode(true));a.id=CY.guid();return a;};_dynSpanToAnc=function(a,e,d,f){var g=a;while((g!=null)&&(g!==e)&&(g.parentNode!==e)){var b=null;if(f){b=g.previousSibling;}else{b=g.nextSibling;}if(b==null){g=g.parentNode;}else{g=b;_recAddComment(g,d);}}};_dynSpanInBetween=function(g,h,f,d){var b=h;var e=null;while(b){if(b.parentNode===g){e=b;break;}b=b.parentNode;}if(e!=null){b=f;var c=null;while(b){if(b.parentNode===g){c=b;break;}b=b.parentNode;}if(c!=null){b=e.nextSibling;while((b!=null)&&(b!==c)){_recAddComment(b,d);b=b.nextSibling;}}}};_bruteContains=function(a,b){while(b){if(a===b){return true;}b=b.parentNode;}return false;},_addIdClass=function(a,b){CY.DOM.addClass(a,"c-id-"+b);_updateCommentCounter(a);};_removeIdClass=function(a,b){CY.DOM.removeClass(a,"c-id-"+b);_updateCommentCounter(a);};_removeIdClasses=function(a){var b=_cgetRegExp("(?:^|\\s+)c-id-(?:\\d+)","g");a.className=a.className.replace(b," ");_updateCommentCounter(a);};_recAddComment=function(a,b){if(CY.DOM.hasClass(a,"c-c")){_addIdClass(a,b);}else{var d=a.firstChild;while(d!=null){_recAddComment(d,b);d=d.nextSibling;}}};_findCommonAncestor=function(c,a){if(_bruteContains(c,a)){return c;}else{var b=a;while((b!=null)&&!_bruteContains(b,c)){b=b.parentNode;}return b;}};_cregexCache={};_cgetRegExp=function(b,a){a=a||"";if(!_cregexCache[b+a]){_cregexCache[b+a]=new RegExp(b,a);}return _cregexCache[b+a];};_updateCommentCounter=function(b){var c=_cgetRegExp("(?:^|\\s+)c-id-(?:\\d+)","g");var d=b.className.match(c);var a=(d==null)?0:d.length;c=_cgetRegExp("(?:^|\\s+)c-count-(?:\\d+)","g");b.className=b.className.replace(c," ");CY.DOM.addClass(b,"c-count-"+a+" ");};_convertSelectionFromCCToCS=function(b){var d=b.offset;var a=b.elt.parentNode;var c=b.elt.previousSibling;while(c!=null){d+=_getTextNodeContent(c).length;c=c.previousSibling;}return{elt:a,offset:d};};_convertSelectionFromCSToCC=function(d){var a={elt:null,offset:-1};var f=null;var e=d.elt.firstChild;var c=0;while(e!=null){var b=c;c+=_getTextNodeContent(e).length;if(c>=d.offset){a.elt=e;a.offset=d.offset-b;break;}e=e.nextSibling;}return a;};unpaintCommentScope=function(k){var j=k.id;var r="c-id-"+j;var m=[];var t=CY.all("."+r);if(t!=null){for(var h=0,d=t.size();h<d;h++){var q=t.item(h);if(q.hasClass("c-c")){var l=CY.Node.getDOMNode(q);_removeIdClass(l,j);var f=getCommentIdsFromClasses(l);quicksort(f);var a=q.get("previousSibling");if(a!=null){var b=CY.Node.getDOMNode(a);var s=getCommentIdsFromClasses(b);quicksort(s);if(areSortedArraysEqual(f,s)){_setTextNodeContent(l,_getTextNodeContent(b)+_getTextNodeContent(l));m.push(b);}}var e=q.get("nextSibling");if(e!=null){var o=CY.Node.getDOMNode(e);var g=getCommentIdsFromClasses(o);quicksort(g);if(areSortedArraysEqual(f,g)){l.firstChild.data=l.firstChild.data+o.firstChild.data;m.push(o);}}}else{alert("HAS NO c-c ? : "+commentNode.get("id")+" , innerHTML :"+commentNode.get("innerHTML"));return;}}}for(var h=0,d=m.length;h<d;h++){m[h].parentNode.removeChild(m[h]);}};unpaintAllComments=function(){var k=CY.all(".c-s");var f=[];for(var e=0,a=k.size();e<a;e++){var h=k.item(e);var d=h.get("firstChild");var j=CY.Node.getDOMNode(h.get("firstChild"));_removeIdClasses(j);var b=d.get("nextSibling");while(b!=null){var g=CY.Node.getDOMNode(b);j.firstChild.data=j.firstChild.data+g.firstChild.data;f.push(g);b=b.get("nextSibling");}}for(var e=0,a=f.length;e<a;e++){f[e].parentNode.removeChild(f[e]);}};showScope=function(b){var a=CY.all(".c-id-"+b);if(a!=null){a.addClass("c-scope");}};hideScopeAnyway=function(){var a=CY.all(".c-scope");if(a!=null){a.removeClass("c-scope");}};hasPerm=function(b){return(-1!=CY.Array.indexOf(sv_user_permissions,b));};Layout=function(){};Layout.prototype={init:function(){},isInFrame:function(){return(!CY.Lang.isUndefined(parent)&&parent.location!=location&&CY.Lang.isFunction(parent.f_getFrameFilterData));},isInComentSite:function(){var d=false;try{if(!CY.Lang.isUndefined(sv_site_url)&&!CY.Lang.isUndefined(parent)&&!CY.Lang.isUndefined(parent.parent)){var e=new String(parent.parent.location);d=(e.indexOf(sv_site_url)==0);}}catch(f){d=false;}return d;},sliderValToPx:function(g){var f=CY.DOM.winWidth();if(this.isInFrame()){f=parent.$(parent).width();}var e=g/100;e=Math.min(e,gConf.sliderFixedMin);e=Math.max(e,gConf.sliderFixedMax);var h=e*f;return Math.floor(h);},getTopICommentsWidth:function(){return this.getTopICommentsWidthFromWidth(this.sliderValToPx(gPrefs.get("layout","comments_col_width")));},getTopICommentsWidthFromWidth:function(c){var d=c-(2*gConf.iCommentThreadPadding);return d-7;},setLeftColumnWidth:function(b){CY.get("#contentcolumn").setStyle("marginLeft",b+"px");CY.get("#leftcolumn").setStyle("width",b+"px");},parentInterfaceUnfreeze:function(){if(this.isInFrame()){parent.f_interfaceUnfreeze();}}};Preferences=function(){this.prefs={};};Preferences.prototype={init:function(){this._read();},_read:function(){for(var d in gConf.defaultPrefs){this.prefs[d]={};for(var e in gConf.defaultPrefs[d]){var f=null;if(d=="user"&&(e=="name"||e=="email")){f=CY.Cookie.get("user_"+e);}else{f=CY.Cookie.getSub(d,e);}this.prefs[d][e]=(f==null)?gConf.defaultPrefs[d][e]:f;}}},persist:function(e,f,g){var h={path:"/",expires:(new Date()).setFullYear(2100,0,1)};if(e=="user"&&(f=="name"||f=="email")){CY.Cookie.set("user_"+f,g,h);}else{CY.Cookie.setSub(e,f,g,h);}this.prefs[e][f]=g;},get:function(c,d){return this.prefs[c][d];},readDefault:function(c,d){return gConf.defaultPrefs[c][d];},reset:function(f){for(var e=0;e<f.length;e++){var g=f[e];for(var h in gConf.defaultPrefs[g]){this.persist(g,h,gConf.defaultPrefs[g][h]);}}}};gShowingAllComments=false;Sync=function(){this._q=null;this._iPreventClick=false;};Sync.prototype={init:function(b){this._q=new CY.AsyncQueue();},setPreventClickOn:function(){CY.log("setPreventClickOn !");if(gLayout.isInFrame()){parent.f_interfaceFreeze();}this._iPreventClick=true;},setPreventClickOff:function(){CY.log("setPreventClickOff !");if(gLayout.isInFrame()){parent.f_interfaceUnfreeze();}this._iPreventClick=false;},removeCommentRet:function(g){var k=g.successfull;var h=(k)?g.failure.iComment:g.success.iComment;if(k){var l=g.returned.filterData;if(gLayout.isInFrame()){parent.f_updateFilterData(l);}var i=gIComments.getTopPosition()[1];var j=gDb.getComment(h.commentId);this._q.add(function(){unpaintCommentScope(j);gIComments.close(j.id);gIComments.remove(j.id);if(j.reply_to_id!=null){gIComments.refresh(j.reply_to_id);}gDb.del(j);if(gLayout.isInFrame()){if(gDb.comments.length==0&&gDb.allComments.length!=0){parent.f_enqueueMsg(gettext("no filtered comments left"));parent.resetFilter();}else{var a=gDb.computeFilterResults();updateFilterResultsCount(a.nbDiscussions,a.nbComments,a.nbReplies);}}});this._animateTo(i);}this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this.resume();},moderateCommentRet:function(l){var j=l.successfull;var h=(j)?l.failure.iComment:l.success.iComment;if(j){var g=l.returned;var i=g.comment;gDb.upd(i);var k=gLayout.isInFrame()&&!parent.f_isFrameFilterFieldsInit();if(k){parent.resetFilter();this._showSingleComment(i);}else{h.changeModeration(i);}}this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this.resume();},saveCommentRet:function(q){var p=q.successfull;if(p){var m=q.success.formId;var r=q.returned;removeFormErrMsg(m);if("errors" in r){var n=r.errors;for(var u in n){addFormErrMsg(m,u,n[u]);}this._animateToTop();}else{var w=function(){return(gNewReply!=null)&&(m==gNewReply.ids.formId);};var v=function(){return(gICommentForm!=null)&&(m==gICommentForm.formId);};var t=function(){return(gEdit!=null)&&(m==gEdit.ids.formId);};if(v()){this.hideICommentForm(cleanICommentForm());}else{if(t()){this._hideEditForm();}else{if(w()){this._hideNewReplyForm();}}}if("ask_for_notification" in r){if(r.ask_for_notification){parent.f_yesNoDialog(gettext("Do you want to be notified of all replies in all discussions you participated in?"),gettext("Reply notification"),function(){var a={method:"POST",data:urlEncode({fun:"ownNotify",key:sv_key,version_key:sv_version_key,email:r.email,active:false})};CY.io(sv_client_url,a);},this,null,function(){var a={method:"POST",data:urlEncode({fun:"ownNotify",key:sv_key,version_key:sv_version_key,email:r.email,active:true})};CY.io(sv_client_url,a);},this,null);}}if("comment" in r){var s=r.comment;gDb.upd(s);var x=gLayout.isInFrame()&&!parent.f_isFrameFilterFieldsInit();if(x){parent.resetFilter();}else{if(s.reply_to_id==null){unpaintCommentScope(s);paintCommentScope(s);}}var o=r.filterData;if(gLayout.isInFrame()){parent.f_updateFilterData(o);updateResetFilterResultsCount();}if(w()){if(!x){this._insertReply(s);}}else{this._showSingleComment(s);}}else{this._animateToTop();}}}else{this._q.add({id:"expl",fn:function(){CY.log("in example .........");}});this._q.promote("expl");}this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this.resume();},example:function(){CY.log("in example .........");},moderateComment:function(e,d){var f=gDb.getComment(e.commentId);this._q.add({fn:CY.bind(this.setPreventClickOn,this)},{autoContinue:false,fn:CY.bind(doExchange,null,"editComment",{comment_key:f.key,state:d},null,this.moderateCommentRet,this,{iComment:e},gettext("could not save comment"))}).run();},_saveComment:function(c,d){this._q.add({fn:CY.bind(this.setPreventClickOn,this)},{autoContinue:false,fn:CY.bind(doExchange,null,c,{},d,this.saveCommentRet,this,{formId:d},gettext("could not save comment"))}).run();},editComment:function(){this._saveComment("editComment",gEdit.ids.formId);},saveComment:function(b){this._saveComment("addComment",b);},removeComment:function(b){checkForOpenedDialog(b,function(){if(gLayout.isInFrame()){parent.f_yesNoDialog(gettext("Are you sure you want to delete this comment?"),gettext("Warning"),function(){this.animateToTop();},this,null,function(){var a=gDb.getComment(b.commentId);this._q.add({fn:CY.bind(this.setPreventClickOn,this)},{autoContinue:false,fn:CY.bind(doExchange,null,"removeComment",{comment_key:a.key},null,this.removeCommentRet,this,{iComment:b},gettext("could not remove comment"))}).run();},this,null);}},this,null);},resume:function(c,d){this._q.run();},resetAutoContinue:function(b){this._q.getCallback(b).autoContinue=true;},hideICommentForm:function(b){this._q.add({autoContinue:false,fn:CY.bind(gICommentForm.animationHide.run,gICommentForm.animationHide)});if(b){this._q.add(b);}},showCommentForm:function(b){checkForOpenedDialog(null,function(){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});this._q.add({fn:function(){if(b==null){var a=getSelectionInfo();updateICommentFormSelection(a);}showICommentForm(b);}});this._q.add({autoContinue:false,fn:CY.bind(gICommentForm.animationShow.run,gICommentForm.animationShow)},{fn:CY.bind(this.setPreventClickOff,this)}).run();},this,null);},showEditForm:function(b){checkForOpenedDialog(null,function(){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});this._q.add({fn:function(){showEditForm(b);}});this._animateToTop();this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this._q.run();},this,null);},showReplyForm:function(b){checkForOpenedDialog(null,function(){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});this._q.add({fn:function(){instanciateNewReplyForm(b);}});this._animateToTop();this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this._q.run();},this,null);},cancelICommentForm:function(){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});this.hideICommentForm();this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this._q.run();},cancelEdit:function(){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});this._q.add({fn:function(){cancelEditForm();}});this._animateToTop();this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this._q.run();},cancelReply:function(){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});this._q.add({fn:function(){cancelNewReplyForm();}});this._animateToTop();this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this._q.run();},changeScopeFormClick:function(){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});this._q.add({fn:function(){changeScopeFormClick();}});this._animateToTop();this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this._q.run();},_hideNewReplyForm:function(){this._q.add({fn:function(){cleanNewReplyForm();cancelNewReplyForm();}});},_hideEditForm:function(){this._q.add({fn:function(){cancelEditForm();}});},_insertReply:function(b){this._q.add({fn:function(){var j=gDb.getComment(b.reply_to_id);var l=gDb.getThreads([j]);var n=l[l.length-2];var m=gIComments.insertAfter(n,b);var i=gIComments.getPosition(b.reply_to_id);m.setPosition(i);var a=gDb.getPath(b);var k=a[a.length-1];if(gIComments.isTopActive(k.id)){m.activate();}m.show();}});this._animateToTop();},_showSingleComment:function(g){if(g!=null){var h=gDb.getPath(g);var e=h[h.length-1];var f=0;if(g.start_wrapper!=-1){f=CY.get(".c-id-"+e.id).getY();}else{f=CY.get("document").get("scrollTop");}this._showComments([e.id],f,false);if(e.replies.length>0){this._animateTo(f);}}},showSingleComment:function(b){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});this._showSingleComment(b);this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this._q.run();},browse:function(e,d){var f=gIComments.browse(e,d);if(f!=null){this.showSingleComment(f);}},_showComments:function(f,d,e){this._q.add({fn:function(){gShowingAllComments=e;gIComments.hide();var c=CY.Array.map(f,function(h){return gDb.getComment(h);});var a=gDb.getThreads(c);gIComments.fetch(a);if(f.length>0){if(e){CY.get("document").set("scrollTop",0);}else{gIComments.activate(f[0]);var b=CY.get(".c-id-"+f[0]);if(b&&!b.inViewportRegion()){b.scrollIntoView(true);}}}gIComments.setPosition([gConf.iCommentLeftPadding,d]);gIComments.show();}});},_animateTo:function(b){this._q.add({fn:function(){gIComments.setAnimationToPositions(b);}},{id:"animationRun",autoContinue:false,fn:CY.bind(gIComments.runAnimations,gIComments)});},_animateToTop:function(){var b=gIComments.getTopPosition();if(b!=null){this._animateTo(b[1]);}},animateToTop:function(){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});this._animateToTop();this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this._q.run();},showAllComments:function(){checkForOpenedDialog(null,function(){gShowingAllComments=true;var b=CY.Array.map(gDb.comments,function(a){return a.id;});this.showComments(b,[0,0],true);},this,null);},showScopeRemovedComments:function(){checkForOpenedDialog(null,function(){gShowingAllComments=true;var c=CY.Array.filter(gDb.comments,function(a){return(a.start_wrapper==-1);});var d=CY.Array.map(c,function(a){return a.id;});this.showComments(d,[0,0],true);},this,null);},showComments:function(f,d,e){checkForOpenedDialog(null,function(){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});this._showComments(f,d[1],e);this._animateTo(d[1]);this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this._q.run();},this,null);},openComment:function(d){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});var c=gIComments.getTopPosition()[1];this._q.add({fn:function(){gIComments.open(d.commentId);gIComments.refresh(d.commentId);}});this._animateTo(c);this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this._q.run();},closeComment:function(b){checkForOpenedDialog(b,function(){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});var a=gIComments.getTopPosition()[1];this._q.add({fn:function(){var d=gDb.getComment(b.commentId);gIComments.close(b.commentId);if(d.reply_to_id!=null){gIComments.refresh(d.reply_to_id);}}});this._animateTo(a);this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this._q.run();},this,null);},activate:function(b){gIComments.activate(b.commentId);}};readyForAction=function(){return !gSync._iPreventClick;};getWrapperAncestor=function(d){var c=d;while(c!=null){if(CY.DOM.hasClass(c,"c-s")){return c;}c=c.parentNode;}return null;};hasWrapperAncestor=function(b){return(getWrapperAncestor(b)!=null);};getSelectionInfo=function(){var j=null,ac=null,T=0,aj=0,af="";if(window.getSelection){var V=window.getSelection();if(V.rangeCount>0){var ad=V.getRangeAt(0);af=ad.toString();if(af!=""){var R=document.createRange();R.setStart(V.anchorNode,V.anchorOffset);R.collapse(true);var W=document.createRange();W.setEnd(V.focusNode,V.focusOffset);W.collapse(false);var K=(W.compareBoundaryPoints(2,R)==1);j=(K)?V.anchorNode.parentNode:V.focusNode.parentNode;innerStartNode=(K)?V.anchorNode:V.focusNode;ac=(K)?V.focusNode.parentNode:V.anchorNode.parentNode;innerEndNode=(K)?V.focusNode:V.anchorNode;T=(K)?V.anchorOffset:V.focusOffset;aj=(K)?V.focusOffset:V.anchorOffset;if(!hasWrapperAncestor(ac)&&hasWrapperAncestor(j)){var e=document.createRange();e.setStart(innerStartNode,T);var ak=getWrapperAncestor(j);var X=ak;e.setEndAfter(X);var ah=parseInt(ak.id.substring("sv_".length));while(e.toString().length<ad.toString().length){ah++;var S=CY.get("#sv_"+ah);if(S){X=CY.Node.getDOMNode(S);e.setEndAfter(X);}else{break;}}ac=X.lastChild;aj=CY.DOM.getText(ac).length;}else{if(!hasWrapperAncestor(j)&&hasWrapperAncestor(ac)){var e=document.createRange();e.setEnd(innerEndNode,aj);var ag=getWrapperAncestor(ac);var Z=ag;e.setStartBefore(Z);var ah=parseInt(ag.id.substring("sv_".length));while(e.toString().length<ad.toString().length){ah--;var S=CY.get("#sv_"+ah);if(S){Z=CY.Node.getDOMNode(S);e.setStartBefore(Z);}else{break;}}j=Z.firstChild;T=0;}else{if(!hasWrapperAncestor(j)&&!hasWrapperAncestor(ac)){var aa=af.length;var ab=[];for(var ah=0;;ah++){var O=CY.get("#sv_"+ah);if(O==null){break;}else{var s=O.get("text");if(af.indexOf(s)==0){ab.push(ah);}}}var i=[];for(var ah=0;;ah++){var O=CY.get("#sv_"+ah);if(O==null){break;}else{var s=O.get("text");if(af.indexOf(s)==(aa-s.length)){i.push(ah);}}}var M=false;for(var U=0;U<ab.length;U++){for(var Y=0;Y<i.length;Y++){var N=document.createRange();var ae=CY.Node.getDOMNode(CY.get("#sv_"+ab[U]));var Q=CY.Node.getDOMNode(CY.get("#sv_"+i[Y]));N.setStartBefore(ae);N.setEndAfter(CY.Node.getDOMNode(Q));if((-1<N.compareBoundaryPoints(0,ad))&&(1>N.compareBoundaryPoints(2,ad))){j=ae.firstChild;T=0;ac=Q.lastChild;aj=CY.DOM.getText(Q).length;M=true;break;}}if(M){break;}}}}}R.detach();W.detach();}else{return null;}}else{return null;}}else{if(document.selection){var ai=document.selection.createRange();if(ai.text.length==0){return null;}var al=ai.parentElement();var L=ai.duplicate();var P=ai.duplicate();L.collapse(true);P.collapse(false);j=L.parentElement();while(L.moveStart("character",-1)!=0){if(L.parentElement()!=j){break;}T++;}ac=P.parentElement();while(P.moveEnd("character",-1)!=0){if(P.parentElement()!=ac){break;}aj++;}af=ai.text;}}if(!hasWrapperAncestor(j)||!hasWrapperAncestor(ac)){return null;}return{text:af,start:{elt:j,offset:T},end:{elt:ac,offset:aj}};};Db=function(){this.comments=null;this.allComments=null;this.commentsByDbId={};this.allCommentsByDbId={};this.ordered_comment_ids={};};Db.prototype={init:function(){this.allComments=CY.JSON.parse(sv_comments);if(sv_read_only){this.initToReadOnly();}this._computeAllCommentsByDbId();this._reorder();},_del:function(i,l,j){var k=l[j];for(var n=0;n<k.replies.length;n++){var m=k.replies[n].id;this._del(k.replies,l,m);n--;}for(var n=0,h=i.length;n<h;n++){if(i[n].id==j){i.splice(n,1);delete l[j];break;}}},del:function(c){var d=(c.reply_to_id==null)?this.comments:this.commentsByDbId[c.reply_to_id].replies;this._del(d,this.commentsByDbId,c.id);d=(c.reply_to_id==null)?this.allComments:this.allCommentsByDbId[c.reply_to_id].replies;this._del(d,this.allCommentsByDbId,c.id);this._reorder();},_reorder:function(){var t=[];for(var w=0,C=this.allComments.length;w<C;w++){var v=this.allComments[w];var a=false;for(var y=0,i=t.length;y<i;y++){var D=t[y];var z=this.allCommentsByDbId[D];if((v.start_wrapper<z.start_wrapper)||((v.start_wrapper==z.start_wrapper)&&(v.start_offset<z.start_offset))||((v.start_wrapper==z.start_wrapper)&&(v.start_offset==z.start_offset)&&(v.end_wrapper<z.end_wrapper))||((v.start_wrapper==z.start_wrapper)&&(v.start_offset==z.start_offset)&&(v.end_wrapper==z.end_wrapper)&&(v.end_offset<z.end_offset))){t.splice(y,0,v.id);a=true;break;}}if(!a){t.push(v.id);}}this.ordered_comment_ids.scope=t;t=[];var u={};for(var w=0,C=this.allComments.length;w<C;w++){var v=this.allComments[w];var s=v.modified;u[v.id]=s;for(var y=0,i=v.replies.length;y<i;y++){var A=v.replies[y];var B=A.modified;if(B>u[v.id]){u[v.id]=B;}}}for(var D in u){var x=this.allCommentsByDbId[D].id;var a=false;for(var w=0,C=t.length;w<C;w++){var j=t[w];if(u[D]<u[j]){t.splice(w,0,x);a=true;break;}}if(!a){t.push(x);}}this.ordered_comment_ids.modif_thread=t;},_upd:function(h,j,i){var k=false;for(var l=0,c=h.length;l<c;l++){if(h[l].id==i.id){h.splice(l,1,i);k=true;break;}}if(!k){h.push(i);}j[i.id]=i;},upd:function(f){var e=(f.reply_to_id==null)?this.allComments:this.allCommentsByDbId[f.reply_to_id].replies;this._upd(e,this.allCommentsByDbId,f);var d=CY.clone(f);e=(f.reply_to_id==null)?this.comments:this.commentsByDbId[f.reply_to_id].replies;this._upd(e,this.commentsByDbId,d);this._reorder();},initComments:function(g){this.comments=[];for(var i=0,j=this.allComments.length;i<j;i++){var f=CY.Array.indexOf(g,this.allComments[i].id);if(f!=-1){var h=CY.clone(this.allComments[i]);this.comments.push(h);}}this._computeCommentsByDbId();},_computeCommentsByDbId:function(){this.commentsByDbId={};var c=this.getThreads(this.comments);for(var d=0;d<c.length;d++){this.commentsByDbId[c[d].id]=c[d];}},_computeAllCommentsByDbId:function(){this.allCommentsByDbId={};var c=this.getThreads(this.allComments);for(var d=0;d<c.length;d++){this.allCommentsByDbId[c[d].id]=c[d];}},getThreads:function(f){var e=[];for(var d=0;d<f.length;d++){e.push(f[d]);if(f[d].replies.length>0){e=e.concat(this.getThreads(f[d].replies));}}return e;},_getPath:function(c,g){var f=[g];var h=g;while(h.reply_to_id!=null){h=c[h.reply_to_id];f.push(h);}return f;},getPath:function(b){return this._getPath(this.commentsByDbId,b);},getComment:function(b){return this.commentsByDbId[b];},getCommentByIdKey:function(e){for(var f in this.commentsByDbId){var d=this.commentsByDbId[f];if(d.id_key==e){return d;}}return null;},isChild:function(g,e){var h=this.commentsByDbId[g];var f=(g==e);while((!f)&&(h.reply_to_id!=null)){h=this.commentsByDbId[h.reply_to_id];f=(h.id==e);}return f;},initToReadOnly:function(i,l){for(var g=0,h=this.allComments.length;g<h;g++){var j=this.allComments[g];for(var k in j){if(0==k.indexOf("can_")&&typeof j[k]==="boolean"){j[k]=false;}}}},browsingIndex:function(e){var h={};for(var f in this.ordered_comment_ids){var g=CY.Array.filter(this.ordered_comment_ids[f],function(a){return(a in this.commentsByDbId);},this);h[f]=CY.Array.indexOf(g,e);}return h;},browse:function(i,m,p){var j=this.ordered_comment_ids[i];if(j.length>0){var l=-1;if((m=="prev")||(m=="next")){for(var n=0;n<j.length;n++){var k=j[n];if(k==p){l=(m=="prev")?n-1:n+1;l=(j.length+l)%j.length;break;}}if(l==-1){CY.error("internal error in db browse (was called with a dbId that isn't among the filtered ones)");return null;}}if(m=="last"){l=j.length-1;}if(m=="first"){l=0;}for(var n=l,o=0;(n>=0)&&(n<j.length);o++){var k=j[n];if(k in this.commentsByDbId){return this.commentsByDbId[k];}if((m=="prev")||(m=="last")){n=n-1;}else{n=n+1;}n=(j.length+n)%j.length;if(o>j.length){break;}}CY.error("internal error in db browse (could not find any filtered comment)");}return null;},computeFilterResults:function(R){var ad={};if(R){for(key in R){if(key.indexOf("filter_")==0){ad[key.substr("filter_".length)]=R[key];}}}else{if(gLayout.isInFrame()){ad=parent.f_getFrameFilterData();}}var G=[];var F=[];var ac="";if("name" in ad){ac=ad.name;}this.filterByName(ac,G,F);var P=[];var ab=[];var L="";if("date" in ad){L=ad.date;}this.filterByDate(L,P,ab);var X=[];var Y=[];var I="";if("text" in ad){I=ad.text;}this.filterByText(I,X,Y);var E=[];var S=[];var O="";if("tag" in ad){O=ad.tag;}this.filterByTag(O,E,S);var H=[];var Z=[];var U="";if("state" in ad){U=ad.state;}this.filterByState(U,H,Z);var aa=[];var i=[];for(var D=0,V=G.length;D<V;D++){var J=G[D];if((CY.Array.indexOf(P,J)!=-1)&&(CY.Array.indexOf(X,J)!=-1)&&(CY.Array.indexOf(E,J)!=-1)&&(CY.Array.indexOf(H,J)!=-1)){aa.push(J);}}for(var D=0,V=F.length;D<V;D++){var J=F[D];if((CY.Array.indexOf(ab,J)!=-1)&&(CY.Array.indexOf(Y,J)!=-1)&&(CY.Array.indexOf(S,J)!=-1)&&(CY.Array.indexOf(Z,J)!=-1)){i.push(J);}}var N=i.length,T=aa.length;var K=T;for(var D=0,V=i.length;D<V;D++){var J=i[D];var Q=this.allCommentsByDbId[J];var M=this._getPath(this.allCommentsByDbId,Q);var W=M[M.length-1];var J=W.id;if(CY.Array.indexOf(aa,J)==-1){aa.push(J);K++;}}return{commentIds:aa,nbDiscussions:K,nbComments:T,nbReplies:N};},filterByText:function(l,i,g){var h=new RegExp(l,"gi");for(var j in this.allCommentsByDbId){var k=this.allCommentsByDbId[j];if(l==""||h.exec(k.title)!=null||h.exec(k.content)!=null){if(k.reply_to_id==null){i.push(k.id);}else{g.push(k.id);}}}},filterByName:function(g,j,f){for(var h in this.allCommentsByDbId){var i=this.allCommentsByDbId[h];if(g==""||i.name==g){if(i.reply_to_id==null){j.push(i.id);}else{f.push(i.id);}}}},filterByTag:function(j,n,q){var k=new RegExp("^"+j+"$","g");var l=new RegExp("^"+j+", ","g");var o=new RegExp(", "+j+", ","g");var p=new RegExp(", "+j+"$","g");for(var r in this.allCommentsByDbId){var m=this.allCommentsByDbId[r];if(j==""||k.exec(m.tags)||l.exec(m.tags)!=null||o.exec(m.tags)!=null||p.exec(m.tags)!=null){if(m.reply_to_id==null){n.push(m.id);}else{q.push(m.id);}}}},filterByState:function(j,g,f){for(var h in this.allCommentsByDbId){var i=this.allCommentsByDbId[h];if(j==""||i.state==j){if(i.reply_to_id==null){g.push(i.id);}else{f.push(i.id);}}}},filterByDate:function(g,k,h){var l=(g=="")?0:parseInt(g);for(var i in this.allCommentsByDbId){var j=this.allCommentsByDbId[i];if(j.modified>l){if(j.reply_to_id==null){k.push(j.id);}else{h.push(j.id);}}}},getCommentsAndRepliesCounts:function(k){var g=0;var i=0;var h=(k)?this.allComments:this.comments;var j=this.getThreads(h);for(var l=0;l<j.length;l++){if(j[l].reply_to_id==null){g++;}else{i++;}}return[g,i];},getCommentsNb:function(c){var d=(c)?this.allComments:this.comments;return this.getThreads(d).length;},getFilteredCommentIdsAsString:function(){var d="";for(var c in this.commentsByDbId){d=d+c+",";}return d;}};IComment=function(){this.commentId=null;var C=gLayout.getTopICommentsWidth();var N=gConf.iCommentLeftPadding;var w=gettext("change comment state to pending");var A=gettext("change comment state to approved");var J=gettext("change comment state to unapproved");var x=gettext("cancel changing the state of this comment");var L=gettext("pending");var K=gettext("approved");var B=gettext("unapproved");var M=gettext("cancel");var y=gettext("show replies");var v=gettext("change to:");var F=ngettext("reply","replies",1);var H=gettext("edit comment");var E=gettext("delete comment");var z=gettext("edit");var I=gettext("delete");var D=gettext("close");var G=gettext("show scope");var u=gettext("Comment is detached: it was created on a previous version and text it applied to has been modified or removed.");this.overlay=new CY.Overlay({zIndex:3,shim:false,visible:false,width:C,xy:[N,0],headerContent:'<div class="icomment-header"><div class="c-iactions"><a class="c-moderate c-action" title="">vis</a> <a class="c-edit c-action" title="'+H+'" alt="'+H+'">'+z+'</a> <a class="c-delete c-action" title="'+E+'" alt="'+E+'">'+I+'</a> </div><div class="c-state-actions displaynone">'+v+'&nbsp;<a class="c-state-pending c-action" title="'+w+'" alt="'+w+'">'+L+'</a> <a class="c-state-approved c-action" title="'+A+'" alt="'+A+'">'+K+'</a> <a class="c-state-unapproved c-action" title="'+J+'" alt="'+J+'">'+B+'</a> <a class="c-state-cancel c-action" title="'+x+'" alt="'+x+'">'+M+'</a> </div><div class="c-no-scope-msg">'+u+'</div><a class="c-show-scope c-action" title="'+G+'" alt="'+G+'"><em>-</em></a><a class="c-close c-action" title="'+D+'" alt="'+D+'"><em>X</em></a></div>',bodyContent:'<div class="icomment-body"><span class="c-content"></span><span class="c-ireplyactions"><a class="c-readreplies c-action" title="'+y+'" alt="'+y+'">'+y+'</a> <a class="c-reply c-action" title="'+F+'" alt="'+F+'">'+F+"</a>&nbsp;</span></div>"});this.overlay.get("contentBox").addClass("c-comment");this.overlay.render("#leftcolumn");this.animation=new CY.Anim({node:this.overlay.get("boundingBox"),duration:gPrefs.get("general","animduration"),easing:CY.Easing.easeOut});this.overlay.get("contentBox").query(".c-close").on("click",this.onCloseCommentClick,this);this.overlay.get("contentBox").query(".c-moderate").on("click",this.onModerateCommentClick,this);this.overlay.get("contentBox").query(".c-state-pending").on("click",this.onPendingCommentClick,this);this.overlay.get("contentBox").query(".c-state-approved").on("click",this.onApprovedCommentClick,this);this.overlay.get("contentBox").query(".c-state-unapproved").on("click",this.onUnapprovedCommentClick,this);this.overlay.get("contentBox").query(".c-state-cancel").on("click",this.onCancelStateChangeClick,this);this.overlay.get("contentBox").query(".c-edit").on("click",this.onEditCommentClick,this);this.overlay.get("contentBox").query(".c-delete").on("click",this.onDeleteCommentClick,this);this.overlay.get("contentBox").query(".c-reply").on("click",this.onReplyCommentClick,this);this.overlay.get("contentBox").query(".c-readreplies").on("click",this.onReadRepliesCommentClick,this);this.overlay.get("contentBox").query(".icomment-header").on("mouseenter",this.onMouseEnterHeader,this);this.overlay.get("contentBox").query(".icomment-header").on("mouseleave",this.onMouseLeaveHeader,this);this.overlay.get("contentBox").on("click",this.onCommentClick,this);};IComment.prototype={onCloseCommentClick:function(b){b.halt();if(readyForAction()&&this.isVisible()){gSync.closeComment(this);}},onModerateCommentClick:function(b){b.halt();if(readyForAction()&&this.isVisible()){this.overlay.get("contentBox").query(".c-iactions").addClass("displaynone");this.overlay.get("contentBox").query(".c-state-actions").removeClass("displaynone");}},onPendingCommentClick:function(b){b.halt();if(readyForAction()&&this.isVisible()){gSync.moderateComment(this,"pending");}},onApprovedCommentClick:function(b){b.halt();if(readyForAction()&&this.isVisible()){gSync.moderateComment(this,"approved");}},onUnapprovedCommentClick:function(b){b.halt();if(readyForAction()&&this.isVisible()){gSync.moderateComment(this,"unapproved");}},onCancelStateChangeClick:function(b){b.halt();if(readyForAction()&&this.isVisible()){this.overlay.get("contentBox").query(".c-iactions").removeClass("displaynone");this.overlay.get("contentBox").query(".c-state-actions").addClass("displaynone");}},onDeleteCommentClick:function(b){b.halt();if(readyForAction()&&this.isVisible()){gSync.removeComment(this);}},onEditCommentClick:function(b){b.halt();if(readyForAction()&&this.isVisible()){gSync.showEditForm(this);}},onReplyCommentClick:function(b){b.halt();if(readyForAction()&&this.isVisible()){gSync.showReplyForm(this);}},onReadRepliesCommentClick:function(b){b.halt();if(readyForAction()&&this.isVisible()){gSync.openComment(this);}},onCommentClick:function(k){if(readyForAction()&&this.isVisible()){if(k.target.get("target")=="_blank"){var e=k.target;var i=sv_site_url+sv_text_view_show_comment_url;if(e.get("href").indexOf(i)==0){var h=(new RegExp("comment_id_key=([^&]*)","g")).exec(e.get("href"));if(h!=null){var l=h[1];var j=gDb.getCommentByIdKey(l);if(j!=null){k.halt();if(!e.hasClass("c-permalink")){checkForOpenedDialog(null,function(){gSync.showSingleComment(j);});}}}}}else{if(gShowingAllComments){if(!this._isHostingAForm()){var j=gDb.getComment(this.commentId);checkForOpenedDialog(null,function(){if(j!=null){gSync.showSingleComment(j);}});}}else{gSync.activate(this);}}}},onMouseEnterHeader:function(){if(readyForAction()&&this.isVisible()){this.overlay.get("contentBox").query(".c-permalink").removeClass("displaynone");}},onMouseLeaveHeader:function(){if(readyForAction()&&this.isVisible()){this.overlay.get("contentBox").query(".c-permalink").addClass("displaynone");}},setWidth:function(b){this.overlay.get("boundingBox").setStyle("width",b+"px");},activate:function(){this.overlay.get("boundingBox").addClass("c-focus-comment");},deactivate:function(){this.overlay.get("boundingBox").removeClass("c-focus-comment");},hide:function(){if(gIComments.isTopActive(this.commentId)){if(!gIComments.activateVisibleNext()){gIComments.deactivate();}}if(this.isVisible()){this.overlay.hide();this.overlay.blur();}},hideContent:function(){this.overlay.get("contentBox").query(".icomment-header").addClass("displaynone");this.overlay.get("contentBox").query(".icomment-body").addClass("displaynone");},showContent:function(){this.overlay.get("contentBox").query(".icomment-header").removeClass("displaynone");this.overlay.get("contentBox").query(".icomment-body").removeClass("displaynone");},isVisible:function(){return this.overlay.get("visible");},show:function(){this.hideReadRepliesLnk();return this.overlay.show();},showReadRepliesLnk:function(){this.overlay.get("contentBox").query(".c-readreplies").removeClass("displaynone");},hideReadRepliesLnk:function(){this.overlay.get("contentBox").query(".c-readreplies").addClass("displaynone");},changeModeration:function(c){var d=this.overlay.get("contentBox").query(".c-moderate");d.set("innerHTML",gettext(c.state));d.removeClass("c-state-approved");d.removeClass("c-state-pending");d.removeClass("c-state-unapproved");d.addClass("c-state-"+c.state);this.overlay.get("contentBox").query(".c-iactions").removeClass("displaynone");this.overlay.get("contentBox").query(".c-state-actions").addClass("displaynone");},isfetched:function(){return(this.commentId!=null);},unfetch:function(){this.commentId=null;},fetch:function(w){this.commentId=w.id;var C=this.overlay.get("boundingBox");if(w.start_wrapper!=-1){C.addClass("c-has-scope");C.removeClass("c-has-no-scope");}else{C.addClass("c-has-no-scope");C.removeClass("c-has-scope");}if(w.reply_to_id!=null){C.addClass("c-is-reply");}else{C.removeClass("c-is-reply");}var y=interpolate(gettext("last modified on %(date)s"),{date:w.modified_user_str},true);var t=(w.modified==w.created)?"":'<a title="'+y+'"> * </a>';var v=gettext("Permalink to this comment");var q='<a class="c-permalink displaynone c-action" target="_blank" title="'+v+'" href="" >¶&nbsp;</a>';var u=interpolate(gettext("by %(name)s, created on %(date)s"),{name:w.name,date:w.created_user_str},true);var B='<span class="c-header"><div class="c-header-title">'+w.title+q+'</div><div class="c-infos">'+u+"</div></span>";var A=CY.Node.create(B);var p=C.query(".c-header");if(p==null){C.query(".icomment-header").insertBefore(A,C.one(".c-iactions"));}else{p.get("parentNode").replaceChild(A,p);}var x=CY.Node.create('<div class="c-tags"><span class="c-tags-infos">tags:</span>'+w.tags+"</div>");var r=C.query(".c-tags");if(r==null){C.query(".icomment-header").appendChild(x);}else{r.get("parentNode").replaceChild(x,r);}if(w.tags==""){x.addClass("displaynone");}var z=CY.Node.create('<span class="c-content">'+w.content_html+"</span>");var D=C.query(".c-content");if(D==null){C.query(".icomment-body").appendChild(z);}else{D.get("parentNode").replaceChild(z,D);}C.query(".c-permalink").set("href",sv_site_url+w.permalink);this.changeModeration(w);var s=C.queryAll(".c-content a");if(s!=null){s.setAttribute("target","_blank");}s=C.queryAll(".c-header-title a");if(s!=null){s.setAttribute("target","_blank");}this.permAdapt(w);},permAdapt:function(h){var f=this.overlay.get("contentBox").query(".c-delete");if(f){if(!h.can_delete){f.addClass("displaynone");}else{f.removeClass("displaynone");}}var g=this.overlay.get("contentBox").query(".c-edit");if(g){if(!h.can_edit){g.addClass("displaynone");}else{g.removeClass("displaynone");}}var i=this.overlay.get("contentBox").query(".c-reply");if(i){if(!hasPerm("can_create_comment")){i.addClass("displaynone");}else{i.removeClass("displaynone");}}var j=this.overlay.get("contentBox").query(".c-moderate");if(j){if(!h.can_moderate){j.addClass("displaynone");}else{j.removeClass("displaynone");}}},setThreadPad:function(b){this.overlay.get("contentBox").query(".yui-widget-hd").setStyle("paddingLeft",b+"px");this.overlay.get("contentBox").query(".yui-widget-bd").setStyle("paddingLeft",b+"px");},setPosition:function(c){var d=this.overlay.get("boundingBox");d.setStyle("opacity",1);d.setXY(c);},getPosition:function(c){var d=this.overlay.get("boundingBox");return d.getXY();},onAnimationEnd:function(){if(!CY.Lang.isUndefined(this["animation-handle"])&&!CY.Lang.isNull(this["animation-handle"])){this["animation-handle"].detach();this["animation-handle"]=null;}gIComments.signalAnimationEnd();if(gIComments.animationsEnded()){gIComments.whenAnimationsEnd();}},setAnimationToPosition:function(c){var d=this.overlay.get("boundingBox");if(gPrefs.get("general","animduration")<0.011){d.setXY(c);}this.animation.set("to",{xy:c});this.animation.set("duration",gPrefs.get("general","animduration"));this["animation-handle"]=this.animation.on("end",this.onAnimationEnd,this);return this.animation;},getHeight:function(){return this.overlay.get("boundingBox").get("offsetHeight");},scrollIntoView:function(){if(!this.overlay.get("contentBox").inViewportRegion()){this.overlay.get("contentBox").scrollIntoView(true);}},_isHostingAForm:function(){return(this.isVisible()&&((gNewReplyHost!=null&&gNewReplyHost==this)||(gEditICommentHost!=null&&gEditICommentHost==this)));}};gEditICommentHost=null;gEdit=null;dbgc=null;showEditForm=function(h){if(gEdit==null){gEdit={ids:{formId:CY.guid(),formTitleId:CY.guid(),nameInputId:CY.guid(),emailInputId:CY.guid(),titleInputId:CY.guid(),contentInputId:CY.guid(),tagsInputId:CY.guid(),formatInputId:CY.guid(),startWrapperInputId:CY.guid(),endWrapperInputId:CY.guid(),startOffsetInputId:CY.guid(),endOffsetInputId:CY.guid(),changeScopeInputId:CY.guid(),changeScopeInputWrapper:CY.guid(),selectionPlaceId:CY.guid(),keyId:CY.guid(),editCommentId:CY.guid(),currentSelId:CY.guid(),currentSelIdI:CY.guid(),addBtnId:CY.guid(),cancelBtnId:CY.guid()},handlers:{}};}gEditICommentHost=h;gEditICommentHost.hideContent();var l=getHtml(gEdit.ids);var g='<div class="icomment-edit-header">'+l.headerContent+"</div>";var j='<div class="icomment-edit-body">'+l.bodyContent+"</div>";gEditICommentHost.overlay.setStdModContent(CY.WidgetStdMod.HEADER,CY.Node.create(g),CY.WidgetStdMod.AFTER);gEditICommentHost.overlay.setStdModContent(CY.WidgetStdMod.BODY,CY.Node.create(j),CY.WidgetStdMod.AFTER);CY.get("#"+gEdit.ids.formTitleId).set("innerHTML",gettext("Edit comment"));var i=gDb.getComment(gEditICommentHost.commentId);CY.get("#"+gEdit.ids.editCommentId).set("value",i.id);CY.get("#"+gEdit.ids.keyId).set("value",i.key);CY.get("#"+gEdit.ids.changeScopeInputId+" input").set("checked",false);if(i.reply_to_id!=null){CY.get("#"+gEdit.ids.changeScopeInputId).addClass("displaynone");}changeScopeFormClick();CY.get("#"+gEdit.ids.nameInputId).set("value",i.name);CY.get("#"+gEdit.ids.emailInputId).set("value",i.email);if(i.logged_author){CY.get("#"+gEdit.ids.nameInputId).setAttribute("disabled",true);CY.get("#"+gEdit.ids.emailInputId).setAttribute("disabled",true);}CY.get("#"+gEdit.ids.titleInputId).set("value",i.title);CY.get("#"+gEdit.ids.contentInputId).set("value",i.content);CY.get("#"+gEdit.ids.tagsInputId).set("value",i.tags);CY.get("#"+gEdit.ids.formatInputId).set("value",gConf.defaultCommentFormat);var k=gLayout.getTopICommentsWidth();changeFormFieldsWidth(gEdit.ids.formId,k);gEdit.handlers.addBtnId=CY.on("click",onEditSaveClick,"#"+gEdit.ids.addBtnId);gEdit.handlers.cancelBtnId=CY.on("click",onEditCancelClick,"#"+gEdit.ids.cancelBtnId);gEdit.handlers.changeScope=CY.on("click",onChangeScopeClick,"#"+gEdit.ids.changeScopeInputId);};onEditSaveClick=function(b){if(readyForAction()){gSync.editComment();}};onEditCancelClick=function(b){if(readyForAction()){gSync.cancelEdit();}};onChangeScopeClick=function(){if(readyForAction()){gSync.changeScopeFormClick();}else{var d=CY.get("#"+gEdit.ids.changeScopeInputId+" input");var c=d.get("checked");d.set("checked",!c);}};changeScopeFormClick=function(){var b=CY.get("#"+gEdit.ids.currentSelId);if(CY.get("#"+gEdit.ids.changeScopeInputId+" input").get("checked")){b.removeClass("displaynone");}else{b.addClass("displaynone");}};cancelEditForm=function(){if(gEditICommentHost!=null){for(var c in gEdit.handlers){if(gEdit.handlers[c]!=null){gEdit.handlers[c].detach();gEdit.handlers[c]=null;}}var d=gEditICommentHost.overlay.get("contentBox").query(".icomment-edit-body");d.get("parentNode").removeChild(d);d=gEditICommentHost.overlay.get("contentBox").query(".icomment-edit-header");d.get("parentNode").removeChild(d);gEditICommentHost.showContent();gEditICommentHost=null;}};var gtest={renaud:"RENAUD",random:Math.random(),bernard:"BERNARD",myFunc:function(){doExchange("theServerFun",{},null,this.myRetFunc,this,["foo","bar"]);},myRetFunc:function(b){CY.log("this.renaud : "+this.renaud);CY.log("this.random : "+this.random);CY.log("arg.returned : "+b.returned);CY.log(b.returned);CY.log("arg.success : "+b.success);CY.log(b.success);}};doExchange=function(k,n,l,m,o,p,i){n.fun=k;n.key=sv_key;n.version_key=sv_version_key;var j={method:"POST",data:urlEncode(n),on:{success:function(a,b,c){var d={};if(b.responseText){d=CY.JSON.parse(b.responseText);}if(gLayout.isInFrame()&&("msg" in d)){parent.f_enqueueMsg(d.msg);}c.returned=d;c.successfull=true;m.call(o,c);},failure:function(a,b,c){if(gLayout.isInFrame()){parent.f_enqueueErrorMsg(gettext("error:")+i);}c.successfull=false;m.call(o,c);}},arguments:{success:p,failure:p}};if(l!=null){j.form={id:l};}CY.io(sv_client_url,j);};warn_server=function(f){f.fun="warn";f.key=sv_key;f.version_key=sv_version_key;var d=CY.UA;var e={method:"POST",data:urlEncode(CY.merge(f,d))};CY.io("/client/",e);};paintCommentScope=function(c){if(c.reply_to_id==null&&c.start_wrapper!=-1){var d={start:{elt:document.getElementById("sv_"+c.start_wrapper),offset:c.start_offset},end:{elt:document.getElementById("sv_"+c.end_wrapper),offset:c.end_offset}};if(document.getElementById("sv_"+c.start_wrapper)==null){warn_server({from:"paintCommentScope",start_wrapper:c.start_wrapper});}else{if(document.getElementById("sv_"+c.end_wrapper)==null){warn_server({from:"paintCommentScope",end_wrapper:c.end_wrapper});}else{d.start=_convertSelectionFromCSToCC(d.start);d.end=_convertSelectionFromCSToCC(d.end);renderComment(d,c.id);}}}};getCommentIdsFromClasses=function(f){var g=[];var h=f.className.split(" ");for(var i=0,j=h.length;i<j;i++){if(h[i].indexOf("c-id-")==0){g.push(parseInt(h[i].substring("c-id-".length)));}}return g;};renderComment=function(k,l){var h=k.start.offset;var g=k.end.offset;var i=k.start.elt;var j=k.end.elt;if((i!=null)&&(j!=null)&&_getTextNodeContent(i)!=""&&_getTextNodeContent(j)!=""){markWholeNodesAsComments(i,j,l);markEndsAsComments(i,h,j,g,l);}};markWholeNodesAsComments=function(g,h,e){var f=_findCommonAncestor(g,h);_dynSpanToAnc(g,f,e,false);_dynSpanToAnc(h,f,e,true);_dynSpanInBetween(f,g,h,e);};_setTextNodeContent=function(d,c){CY.DOM.setText(d,c);};_getTextNodeContent=function(b){return CY.DOM.getText(b);};markEndsAsComments=function(C,x,u,w,y){var s=_getTextNodeContent(C).substring(0,x);var r=_getTextNodeContent(C).substring(x);var q=_getTextNodeContent(u).substring(0,w);var z=_getTextNodeContent(u).substring(w);var E=(C===u);if(r!=""){if(CY.DOM.hasClass(C,"c-c")){var A=null,v=null,D=null,F=null;var t=(E)?_getTextNodeContent(C).substring(x,w):r;if(E&&(z!="")){D=C;A=D;}if(t!=""){if(A==null){v=C;}else{v=_yuiCloneNode(C);A.parentNode.insertBefore(v,A);}A=v;}if(s!=""){if(A==null){F=C;}else{F=_yuiCloneNode(C);A.parentNode.insertBefore(F,A);}A=F;}if(D!=null){_setTextNodeContent(D,z);}if(v!=null){_setTextNodeContent(v,t);_addIdClass(v,y);}if(F!=null){_setTextNodeContent(F,s);}}}if((!E)&&(q!="")){if(CY.DOM.hasClass(u,"c-c")){var A=null,B=null,D=null;if(z!=""){D=u;A=u;}if(q!=""){if(A==null){B=u;}else{B=_yuiCloneNode(u);A.parentNode.insertBefore(B,A);}A=B;}if(D!=null){_setTextNodeContent(D,z);}if(B!=null){_addIdClass(B,y);_setTextNodeContent(B,q);}}}};_yuiCloneNode=function(c){var d=CY.Node.getDOMNode(CY.get("#"+c.id).cloneNode(true));d.id=CY.guid();return d;};_dynSpanToAnc=function(h,k,l,j){var i=h;while((i!=null)&&(i!==k)&&(i.parentNode!==k)){var c=null;if(j){c=i.previousSibling;}else{c=i.nextSibling;}if(c==null){i=i.parentNode;}else{i=c;_recAddComment(i,l);}}};_dynSpanInBetween=function(j,i,k,m){var a=i;var l=null;while(a){if(a.parentNode===j){l=a;break;}a=a.parentNode;}if(l!=null){a=k;var n=null;while(a){if(a.parentNode===j){n=a;break;}a=a.parentNode;}if(n!=null){a=l.nextSibling;while((a!=null)&&(a!==n)){_recAddComment(a,m);a=a.nextSibling;}}}};_bruteContains=function(d,c){while(c){if(d===c){return true;}c=c.parentNode;}return false;},_addIdClass=function(d,c){CY.DOM.addClass(d,"c-id-"+c);_updateCommentCounter(d);};_removeIdClass=function(d,c){CY.DOM.removeClass(d,"c-id-"+c);_updateCommentCounter(d);};_removeIdClasses=function(d){var c=_cgetRegExp("(?:^|\\s+)c-id-(?:\\d+)","g");d.className=d.className.replace(c," ");_updateCommentCounter(d);};_recAddComment=function(e,c){if(CY.DOM.hasClass(e,"c-c")){_addIdClass(e,c);}else{var f=e.firstChild;while(f!=null){_recAddComment(f,c);f=f.nextSibling;}}};_findCommonAncestor=function(f,e){if(_bruteContains(f,e)){return f;}else{var d=e;while((d!=null)&&!_bruteContains(d,f)){d=d.parentNode;}return d;}};_cregexCache={};_cgetRegExp=function(c,d){d=d||"";if(!_cregexCache[c+d]){_cregexCache[c+d]=new RegExp(c,d);}return _cregexCache[c+d];};_updateCommentCounter=function(e){var h=_cgetRegExp("(?:^|\\s+)c-id-(?:\\d+)","g");var g=e.className.match(h);var f=(g==null)?0:g.length;h=_cgetRegExp("(?:^|\\s+)c-count-(?:\\d+)","g");e.className=e.className.replace(h," ");CY.DOM.addClass(e,"c-count-"+f+" ");};_convertSelectionFromCCToCS=function(e){var g=e.offset;var f=e.elt.parentNode;var h=e.elt.previousSibling;while(h!=null){g+=_getTextNodeContent(h).length;h=h.previousSibling;}return{elt:f,offset:g};};_convertSelectionFromCSToCC=function(k){var h={elt:null,offset:-1};var i=null;var j=k.elt.firstChild;var l=0;while(j!=null){var g=l;l+=_getTextNodeContent(j).length;if(l>=k.offset){h.elt=j;h.offset=k.offset-g;break;}j=j.nextSibling;}return h;};unpaintCommentScope=function(v){var w=v.id;var c="c-id-"+w;var p=[];var E=CY.all("."+c);if(E!=null){for(var x=0,B=E.size();x<B;x++){var i=E.item(x);if(i.hasClass("c-c")){var u=CY.Node.getDOMNode(i);_removeIdClass(u,w);var z=getCommentIdsFromClasses(u);quicksort(z);var D=i.get("previousSibling");if(D!=null){var C=CY.Node.getDOMNode(D);var F=getCommentIdsFromClasses(C);quicksort(F);if(areSortedArraysEqual(z,F)){_setTextNodeContent(u,_getTextNodeContent(C)+_getTextNodeContent(u));p.push(C);}}var A=i.get("nextSibling");if(A!=null){var n=CY.Node.getDOMNode(A);var y=getCommentIdsFromClasses(n);quicksort(y);if(areSortedArraysEqual(z,y)){u.firstChild.data=u.firstChild.data+n.firstChild.data;p.push(n);}}}else{alert("HAS NO c-c ? : "+commentNode.get("id")+" , innerHTML :"+commentNode.get("innerHTML"));return;}}}for(var x=0,B=p.length;x<B;x++){p[x].parentNode.removeChild(p[x]);}};unpaintAllComments=function(){var c=CY.all(".c-s");var n=[];for(var o=0,r=c.size();o<r;o++){var l=c.item(o);var p=l.get("firstChild");var i=CY.Node.getDOMNode(l.get("firstChild"));_removeIdClasses(i);var q=p.get("nextSibling");while(q!=null){var m=CY.Node.getDOMNode(q);i.firstChild.data=i.firstChild.data+m.firstChild.data;n.push(m);q=q.get("nextSibling");}}for(var o=0,r=n.length;o<r;o++){n[o].parentNode.removeChild(n[o]);}};showScope=function(c){var d=CY.all(".c-id-"+c);if(d!=null){d.addClass("c-scope");}};hideScopeAnyway=function(){var b=CY.all(".c-scope");if(b!=null){b.removeClass("c-scope");}};gNewReplyHost=null;gNewReply=null;instanciateNewReplyForm=function(i){if(gNewReply==null){gNewReply={val:{name:gPrefs.get("user","name"),email:gPrefs.get("user","email"),title:"",content:"",tags:""},ids:{name:gPrefs.get("user","name"),email:gPrefs.get("user","email"),title:"",content:"",tags:"",formId:CY.guid(),nameInputId:CY.guid(),emailInputId:CY.guid(),titleInputId:CY.guid(),contentInputId:CY.guid(),keyInputId:CY.guid(),formatInputId:CY.guid(),tagsInputId:CY.guid(),parentCommentId:CY.guid(),addBtnId:CY.guid(),cancelBtnId:CY.guid()},handlers:{}};}gNewReplyHost=i;var b='<hr/><center><div class="c-header-title">'+gettext("New reply")+"</div></center>";var e=gFormHtml.formStart.replace("###",gNewReply.ids["formId"]);if(!sv_loggedIn){e=e+gFormHtml.nameInput.replace("###",gNewReply.ids["nameInputId"])+gFormHtml.emailInput.replace("###",gNewReply.ids["emailInputId"]);}e=e+gFormHtml.titleInput.replace("###",gNewReply.ids["titleInputId"])+gFormHtml.contentInput.replace("###",gNewReply.ids["contentInputId"])+gFormHtml.tagsInput.replace("###",gNewReply.ids["tagsInputId"]);e=e+gFormHtml.hidden.replace("###",gNewReply.ids["keyInputId"]).replace("???","comment_key");e=e+gFormHtml.hidden.replace("###",gNewReply.ids["formatInputId"]).replace("???","format");e=e+gFormHtml.hidden.replace("###",gNewReply.ids["parentCommentId"]).replace("???","reply_to_id");var h=gFormHtml.btns.replace("###",gNewReply.ids["addBtnId"]).replace("???",gNewReply.ids["cancelBtnId"]);gNewReplyHost.overlay.setStdModContent(CY.WidgetStdMod.FOOTER,b+e+h);var c=gNewReplyHost.overlay.getStdModNode(CY.WidgetStdMod.FOOTER);var f=gDb.getComment(i.commentId);var a="Re: ";var g=(gNewReply.val["title"]==""||gNewReply.val["title"].substring(0,a.length)==a)?a+f.title:gNewReply.val["title"];if(!sv_loggedIn){c.query(".n_name").set("value",gNewReply.val["name"]);c.query(".n_email").set("value",gNewReply.val["email"]);}c.query(".n_title").set("value",g);c.query(".n_content").set("value",gNewReply.val["content"]);c.query(".n_tags").set("value",gNewReply.val["tags"]);c.query("#"+gNewReply.ids["parentCommentId"]).set("value",i.commentId);c.query("#"+gNewReply.ids["formatInputId"]).set("value",gConf.defaultCommentFormat);gNewReplyHost.overlay.get("contentBox").query(".c-reply").addClass("displaynone");gNewReply.handlers["addBtnId"]=CY.on("click",onAddNewReplyClick,"#"+gNewReply.ids["addBtnId"]);gNewReply.handlers["cancelBtnId"]=CY.on("click",onCancelNewReplyClick,"#"+gNewReply.ids["cancelBtnId"]);var d=gLayout.getTopICommentsWidth();changeFormFieldsWidth(gNewReply.ids["formId"],d);};cleanNewReplyForm=function(){if(gNewReplyHost!=null){var a=gNewReplyHost.overlay.getStdModNode(CY.WidgetStdMod.FOOTER);a.queryAll(".comment_input").set("value","");}};cancelNewReplyForm=function(){if(gNewReplyHost!=null){for(var b in gNewReply.handlers){if(gNewReply.handlers[b]!=null){gNewReply.handlers[b].detach();gNewReply.handlers[b]=null;}}gNewReplyHost.overlay.get("contentBox").query(".c-reply").removeClass("displaynone");var a=gNewReplyHost.overlay.getStdModNode(CY.WidgetStdMod.FOOTER);if(!sv_loggedIn){gNewReply.val["name"]=a.query(".n_name").get("value");gNewReply.val["email"]=a.query(".n_email").get("value");}gNewReply.val["title"]=a.query(".n_title").get("value");gNewReply.val["content"]=a.query(".n_content").get("value");gNewReply.val["tags"]=a.query(".n_tags").get("value");a.set("innerHTML","");gNewReplyHost=null;}};onAddNewReplyClick=function(){if(!sv_loggedIn){var b=CY.get("#"+gNewReply.ids["nameInputId"]).get("value");gPrefs.persist("user","name",b);var a=CY.get("#"+gNewReply.ids["emailInputId"]).get("value");gPrefs.persist("user","email",a);}gSync.saveComment(gNewReply.ids["formId"]);};onCancelNewReplyClick=function(){gSync.cancelReply();};_changeIds=function(a,b){if(a.id){a.id=a.id+b;}var d=a.firstChild;while(d!=null){_changeIds(d,b);d=d.nextSibling;}};suffix=0;domDuplicate=function(a){var b=a.cloneNode(true);suffix++;_changeIds(b,"-"+suffix);return b;};getDuplicated=function(a){return document.getElementById(a.id+"-"+suffix);};logSel=function(a){log("text :"+a.text+", start id : "+a.start["elt"].id+" , start offset : "+a.start["offset"]+" , end id : "+a.end["elt"].id+"end offset : "+a.end["offset"]);};log=function(b){var a=document.getElementById("log");a.innerHTML=a.innerHTML+"<li>"+b+"</li>";};urlEncode=function(h){if(!h){return"";}var c=[];for(var f in h){var e=h[f],b=encodeURIComponent(f);var g=typeof e;if(g=="undefined"){c.push(b,"=&");}else{if(g!="function"&&g!="object"){c.push(b,"=",encodeURIComponent(e),"&");}else{if(CY.Lang.isArray(e)){if(e.length){for(var d=0,a=e.length;d<a;d++){c.push(b,"=",encodeURIComponent(e[d]===undefined?"":e[d]),"&");}}else{c.push(b,"=&");}}}}}c.pop();return c.join("");};urlDecode=function(f,h){if(!f||!f.length){return{};}var d={};var b=f.split("&");var c,a,j;for(var e=0,g=b.length;e<g;e++){c=b[e].split("=");a=decodeURIComponent(c[0]);j=decodeURIComponent(c[1]);if(h!==true){if(typeof d[a]=="undefined"){d[a]=j;}else{if(typeof d[a]=="string"){d[a]=[d[a]];d[a].push(j);}else{d[a].push(j);}}}else{d[a]=j;}}return d;};areSortedArraysEqual=function(b,a){if(b.length!=a.length){return false;}for(var d=0,c=b.length;d<c;d++){if(b[d]!=a[d]){return false;}}return true;};quicksort=function(a){_quicksort(a,0,a.length-1);};_quicksort=function(e,g,d){var a,c,f,b;if(d-g==1){if(e[g]>e[d]){b=e[g];e[g]=e[d];e[d]=b;}return;}a=e[parseInt((g+d)/2)];e[parseInt((g+d)/2)]=e[g];e[g]=a;c=g+1;f=d;do{while(c<=f&&e[c]<=a){c++;}while(e[f]>a){f--;}if(c<f){b=e[c];e[c]=e[f];e[f]=b;}}while(c<f);e[g]=e[f];e[f]=a;if(g<f-1){_quicksort(e,g,f-1);}if(f+1<d){_quicksort(e,f+1,d);}};IComments=function(){this._c=[];this._a=[];this._nbEndedAnim=0;this._topActiveCommentDbId=null;};IComments.prototype={init:function(a){for(var b=0;b<gConf.iCommentsInitAlloc;b++){this._c.push(new IComment());}},getIComment:function(a){return CY.Array.find(this._c,function(b){return(b.isfetched()&&b.commentId==a);});},insertAfter:function(a,d){var c=CY.Array.map(this._c,function(e){return e.commentId;});var b=CY.Array.indexOf(c,a.id);if(b!=-1){this._c.splice(b+1,0,new IComment());this._c[b+1].fetch(d);return this._c[b+1];}return null;},_remove:function(c){var d=CY.Array.map(c,function(e){return e.commentId;});for(var b=0;b<this._c.length;b++){var a=this._c[b];if(a.isfetched()&&CY.Array.indexOf(d,a.commentId)!=-1){a.unfetch();this._c.push(this._c.splice(b,1)[0]);b--;}}},_getChildren:function(a){return CY.Array.filter(this._c,function(b){return(b.isfetched()&&gDb.isChild(b.commentId,a));});},_getInvisibleChildren:function(a){return CY.Array.filter(this._getChildren(a),function(b){return(!b.isVisible());});},refresh:function(c){var b=this.getIComment(c);var a=this._getInvisibleChildren(c);if(a.length>0){b.showReadRepliesLnk();}else{b.hideReadRepliesLnk();}},remove:function(a){this._remove(this._getChildren(a));},close:function(a){CY.Array.each(this._getChildren(a),function(b){b.hide();});},open:function(a){CY.Array.each(this._getChildren(a),function(b){b.show();});},fetch:function(b){for(var a=0;a<b.length;a++){if(a==this._c.length){this._c.push(new IComment());}this._c[a].fetch(b[a]);}for(var a=b.length;a<this._c.length;a++){this._c[a].unfetch();}},setPosition:function(a){CY.each(this._c,function(b){b.setPosition(a);});},show:function(){CY.each(this._c,function(a){if(a.isfetched()){a.show();}});},hide:function(){this.deactivate();CY.each(this._c,function(a){if(a.commentId!=null){a.hide();}});},setWidth:function(c){var e=null;for(var b=0;b<this._c.length;b++){var a=this._c[b];a.setWidth(c);if(a.commentId!=null&&a.isVisible()){var d=a.getPosition();if(e==null){e=d[1];}d[1]=e;a.setPosition(d);e+=a.getHeight();}}},getTopPosition:function(){for(var b=0;b<this._c.length;b++){var a=this._c[b];if(a.commentId!=null&&a.isVisible()){return a.getPosition();}}return null;},getPosition:function(c){for(var b=0;b<this._c.length;b++){var a=this._c[b];if(a.commentId==c&&a.isVisible()){return a.getPosition();}}return null;},setAnimationToPositions:function(h){this._initAnimations();var c=(gPrefs.get("comments","threadpad")=="1")?gConf.iCommentThreadPadding:0;var f=h;for(var d=0;d<this._c.length;d++){var b=this._c[d];if(b.isfetched&&b.isVisible()){var a=gDb.getPath(gDb.getComment(b.commentId));var g=((a.length-1)*c)+gConf.iCommentLeftPadding;if(f==null){var e=b.getPosition();f=e[1];}this._a.push(b.setAnimationToPosition([g,f]));f+=b.getHeight();}}},_initAnimations:function(){this._a=[];this._nbEndedAnim=0;},runAnimations:function(){if(this._a.length==0){gSync.resetAutoContinue("animationRun");}else{CY.each(this._a,function(a){a.run();});}},whenAnimationsEnd:function(){gSync.resume();},animationsEnded:function(){return((this._a.length==0)||(this._a.length==this._nbEndedAnim));},signalAnimationEnd:function(){this._nbEndedAnim++;},isTopActive:function(a){return((a!=null)&&(this._topActiveCommentDbId==a));},isAnyActive:function(){return(this._topActiveCommentDbId!=null);},activate:function(f){if(this._topActiveCommentDbId!=null){this.deactivate();}var e=gDb.getComment(f);var b=gDb.getPath(e);var a=b[b.length-1];var c=this._getChildren(a.id);CY.Array.each(c,function(g){g.activate();});this._topActiveCommentDbId=a.id;if(gLayout.isInFrame()){var d=gDb.browsingIndex(this._topActiveCommentDbId);parent.$("#browse_by option").each(function(){var g=1+d[this.value];parent.$("#c_browse_indx_"+this.value).html(""+g);});}showScope(a.id);},deactivate:function(){if(this._topActiveCommentDbId!=null){parent.$("#browse_by option").each(function(){parent.$("#c_browse_indx_"+this.value).html("-");});hideScopeAnyway();var a=this._getChildren(this._topActiveCommentDbId);CY.Array.each(a,function(b){b.deactivate();});this._topActiveCommentDbId=null;}},activateVisibleNext:function(){if(this._topActiveCommentDbId!=null){for(var d=0;d<2;d++){var f=(d==0)?0:this._c.length-1;var a=false;for(var e=f;(e>=0)&&e<=(this._c.length-1);){var c=this._c[e];if(c.commentId!=null&&c.isVisible()){a=a||(gDb.isChild(c.commentId,this._topActiveCommentDbId));if(a&&(!gDb.isChild(c.commentId,this._topActiveCommentDbId))){this.activate(c.commentId);return true;}}e=(d==0)?e+1:e-1;}}}return false;},browse:function(b,c){var a=c;if((c=="prev")&&!this.isAnyActive()){a="last";}if((c=="next")&&!this.isAnyActive()){a="first";}return gDb.browse(b,a,this._topActiveCommentDbId);}};_afterDlg=function(d){var a=d[0];var c=d[1];var b=d[2];a.call(c,b);};_abortNewCommentConfirmed=function(a){if(isICommentFormVisible()){if(gLayout.isInFrame()){gSync.hideICommentForm({fn:function(){_afterDlg(a);}});gSync.resume();}}};_abortNewReplyConfirmed=function(a){if(gNewReplyHost!=null){if(gLayout.isInFrame()){cancelNewReplyForm();_afterDlg(a);}}};_abortNewEditConfirmed=function(a){if(gEditICommentHost!=null){if(gLayout.isInFrame()){cancelEditForm();_afterDlg(a);}}};checkForOpenedDialog=function(e,b,d,c){var a=[];if(e!=null){a=CY.Array.map(gDb.getThreads([gDb.getComment(e.commentId)]),function(f){return f.id;});}if(isICommentFormVisible()||(gNewReplyHost!=null&&(e==null||CY.Array.indexOf(a,gNewReplyHost.commentId)!=-1))||(gEditICommentHost!=null&&(e==null||CY.Array.indexOf(a,gEditICommentHost.commentId)!=-1))){if(gLayout.isInFrame()){if(isICommentFormVisible()){parent.f_yesNoDialog(gettext("New comment will be canceled, continue?"),gettext("Warning"),null,null,null,_abortNewCommentConfirmed,this,[b,d,c]);}else{if(gNewReplyHost!=null){parent.f_yesNoDialog(gettext("Started reply will be canceled, continue?"),gettext("Warning"),null,null,null,_abortNewReplyConfirmed,this,[b,d,c]);}else{if(gEditICommentHost!=null){parent.f_yesNoDialog(gettext("Started comment edition will be canceled, continue?"),gettext("Warning"),null,null,null,_abortNewEditConfirmed,this,[b,d,c]);}}}}}else{b.call(d,[]);}};gNoSelectionYet=gettext("No selection yet");gFormHtml={formStart:'<form id="###" onsubmit="return false;">',nameInput:gettext("Username:")+'<center><input id="###" name="name" class="n_name user_input" style="padding:1px;" type="text"></input></center>',emailInput:gettext("E-mail address:")+'<center><input id="###" name="email" class="n_email user_input" style="padding:1px;" type="text"></input></center>',titleInput:gettext("Title:")+'<center><input id="###" name="title" class="n_title comment_input" style="padding:1px;" type="text"></input></center>',contentInput:gettext("Content:")+'<center><textarea id="###" name="content" class="n_content comment_input" rows="10" style="padding:1px;"></textarea></center>',tagsInput:gettext("Tag:")+'<center><input id="###" name="tags" class="n_tags comment_input" style="padding:1px;" type="text"></input></center>',hidden:'<input id="###" class="comment_input" name="???" type="hidden" value=""></input>',formEnd:"</form>",changeScope:'<div id="###">'+gettext("Modify comment's scope:")+'<input type="checkbox" name="change_scope"></input></div>',headerTitle:'<center><div id="###" class="c-header-title"></div></center>',currentSel:'<div id="###">'+gettext("Comment will apply to this selection:")+'<br/><div class="current_sel"><div id="???" class="current_sel_ins">'+gNoSelectionYet+"</div></div>#hiddeninput#</div>",btns:'<center><input id="###" type="button" value="'+gettext("Save")+'" /><input id="???" type="button" value="'+gettext("Cancel")+'" /></center>',closeIcon:'<a id="###" class="c-close" title="'+gettext("close")+'"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</em></a>'};getHtml=function(f){ret={};ret.headerContent="";if("closeBtnId" in f){ret.headerContent+=gFormHtml.closeIcon.replace("###",f.closeBtnId);}ret.headerContent+=gFormHtml.headerTitle.replace("###",f.formTitleId);var b="";if("changeScopeInputId" in f){b=gFormHtml.changeScope.replace("###",f.changeScopeInputId);}var e="<center>"+gFormHtml.hidden.replace("###",f.selectionPlaceId).replace("???","selection_place")+"</center>";var a=gFormHtml.currentSel.replace("###",f.currentSelId).replace("???",f.currentSelIdI).replace("#hiddeninput#",e);var d=gFormHtml.btns.replace("###",f.addBtnId).replace("???",f.cancelBtnId);var c=gFormHtml.formStart.replace("###",f.formId)+b+a;if("nameInputId" in f){c=c+gFormHtml.nameInput.replace("###",f.nameInputId);}if("emailInputId" in f){c=c+gFormHtml.emailInput.replace("###",f.emailInputId);}c=c+gFormHtml.titleInput.replace("###",f.titleInputId)+gFormHtml.contentInput.replace("###",f.contentInputId)+gFormHtml.tagsInput.replace("###",f.tagsInputId);c=c+gFormHtml.hidden.replace("###",f.formatInputId).replace("???","format");c=c+gFormHtml.hidden.replace("###",f.startWrapperInputId).replace("???","start_wrapper");c=c+gFormHtml.hidden.replace("###",f.endWrapperInputId).replace("???","end_wrapper");c=c+gFormHtml.hidden.replace("###",f.startOffsetInputId).replace("???","start_offset");c=c+gFormHtml.hidden.replace("###",f.endOffsetInputId).replace("???","end_offset");c=c+gFormHtml.hidden.replace("###",f.keyId).replace("???","comment_key");c=c+gFormHtml.hidden.replace("###",f.editCommentId).replace("???","edit_comment_id");c=c+d+gFormHtml.formEnd;ret.bodyContent=c;return ret;};changeFormFieldsWidth=function(d,c){var a=(c-20)+"px";var b=CY.all("#"+d+" input[type='text']");if(b!=null){b.setStyle("width",a);}b=CY.all("#"+d+" textarea");if(b!=null){b.setStyle("width",a);}};addFormErrMsg=function(j,g,d){var f=document.getElementById(j);var b,h,c,a;for(b=0,a=f.elements.length;b<a;++b){h=f.elements[b];if(h.name==g){c=document.createElement("DIV");CY.DOM.addClass(c,"c-error");c.id=h.id+"-err";c.appendChild(document.createTextNode(d));if(h.parentNode.nextSibling){h.parentNode.parentNode.insertBefore(c,h.parentNode.nextSibling);}else{h.parentNode.parentNode.appendChild(c);}}}};removeFormErrMsg=function(b){var a=CY.all("#"+b+" .c-error");if(a!=null){a.each(function(c){c.get("parentNode").removeChild(c);});}};gICommentForm=null;instanciateICommentForm=function(){gICommentForm={position:[CY.WidgetPositionExt.LC,CY.WidgetPositionExt.LC],formId:CY.guid(),formTitleId:CY.guid(),titleInputId:CY.guid(),contentInputId:CY.guid(),tagsInputId:CY.guid(),formatInputId:CY.guid(),startWrapperInputId:CY.guid(),endWrapperInputId:CY.guid(),startOffsetInputId:CY.guid(),endOffsetInputId:CY.guid(),selectionPlaceId:CY.guid(),keyId:CY.guid(),currentSelId:CY.guid(),currentSelIdI:CY.guid(),addBtnId:CY.guid(),cancelBtnId:CY.guid(),closeBtnId:CY.guid()};if(!sv_loggedIn){gICommentForm.nameInputId=CY.guid();gICommentForm.emailInputId=CY.guid();}var c=getHtml(gICommentForm);var e=gLayout.getTopICommentsWidth();var b=new CY.Overlay({zIndex:3,shim:false,visible:false,headerContent:c.headerContent,bodyContent:c.bodyContent,xy:[10,10],width:e});b.get("contentBox").addClass("c-newcomment");b.render("#leftcolumn");if(!sv_loggedIn){CY.get("#"+gICommentForm.nameInputId).set("value",gPrefs.get("user","name"));CY.get("#"+gICommentForm.emailInputId).set("value",gPrefs.get("user","email"));}CY.get("#"+gICommentForm.formTitleId).set("innerHTML",gettext("New comment"));CY.get("#"+gICommentForm.formatInputId).set("value",gConf.defaultCommentFormat);CY.on("click",onSubmitICommentFormClick,"#"+gICommentForm.addBtnId);CY.on("click",onCancelICommentFormClick,"#"+gICommentForm.cancelBtnId);CY.on("click",onCancelICommentFormClick,"#"+gICommentForm.closeBtnId);gICommentForm.overlay=b;var d=null;d=new CY.Anim({node:b.get("boundingBox"),duration:0.3,easing:CY.Easing.easeOut});gICommentForm.animationHide=d;d.set("to",{opacity:0});gICommentForm["animationHide-handle"]=d.on("end",onICommentFormHideAnimEnd,gICommentForm);var a=null;a=new CY.Anim({node:b.get("boundingBox"),duration:0.3,easing:CY.Easing.easeOut});gICommentForm.animationShow=a;a.set("to",{opacity:1});gICommentForm["animationShow-handle"]=a.on("end",onICommentFormShowAnimEnd,gICommentForm);changeFormFieldsWidth(gICommentForm.formId,e);};cleanICommentForm=function(){CY.get("#"+gICommentForm.currentSelIdI).set("innerHTML",gNoSelectionYet);var a=gICommentForm.overlay.getStdModNode(CY.WidgetStdMod.BODY);a.queryAll(".comment_input").set("value","");CY.get("#"+gICommentForm.formatInputId).set("value",gConf.defaultCommentFormat);if(!sv_loggedIn){a.queryAll(".user_input").set("value","");}};onICommentFormHideAnimEnd=function(){this.overlay.hide();gSync.resume();};onICommentFormShowAnimEnd=function(){gSync.resume();};onSubmitICommentFormClick=function(){if(!sv_loggedIn){var b=CY.get("#"+gICommentForm.nameInputId).get("value");gPrefs.persist("user","name",b);var a=CY.get("#"+gICommentForm.emailInputId).get("value");gPrefs.persist("user","email",a);}gSync.saveComment(gICommentForm.formId);};onCancelICommentFormClick=function(){gSync.cancelICommentForm();};_updateICommentFormSelection=function(c,e,b,a){var d=CY.Node.get("#"+c.currentSelIdI);if(d!=null){d.set("innerHTML",e);}d=CY.get("#"+c.startWrapperInputId);if(d!=null){d.set("value",b.elt.id.substring("sv_".length));}d=CY.get("#"+c.startOffsetInputId);if(d!=null){d.set("value",b.offset);}d=CY.get("#"+c.endWrapperInputId);if(d!=null){d.set("value",a.elt.id.substring("sv_".length));}d=CY.get("#"+c.endOffsetInputId);if(d!=null){d.set("value",a.offset);}};updateICommentFormSelection=function(h){var i=(h==null)?"":h.text;if(i!=""){var f=i;var b=100;if(i.length>b){var a=i.substring(0,(i.substring(0,b/2)).lastIndexOf(" "));var d=i.substring(i.length-b/2);var c=d.substring(d.indexOf(" "));f=a+" ... "+c;}var e=_convertSelectionFromCCToCS(h.start);var g=_convertSelectionFromCCToCS(h.end);_updateICommentFormSelection(gICommentForm,f,e,g);if(gEdit!=null){_updateICommentFormSelection(gEdit.ids,f,e,g);}positionICommentForm();}};showICommentForm=function(){removeFormErrMsg(gICommentForm.formId);if(!sv_loggedIn){if(CY.get("#"+gICommentForm.nameInputId).get("value")==""){CY.get("#"+gICommentForm.nameInputId).set("value",gPrefs.get("user","name"));}if(CY.get("#"+gICommentForm.emailInputId).get("value")==""){CY.get("#"+gICommentForm.emailInputId).set("value",gPrefs.get("user","email"));}}gIComments.hide();positionICommentForm();gICommentForm.overlay.show();CY.get("#"+gICommentForm.titleInputId).focus();};isICommentFormVisible=function(){if(gICommentForm!=null){return gICommentForm.overlay.get("visible");}return false;};positionICommentForm=function(){if(gICommentForm!=null){var b=gICommentForm.overlay;var a=b.get("boundingBox");var c=a.get("offsetHeight");var e=a.get("winHeight");var d=gICommentForm.position;if(c>e){d=[CY.WidgetPositionExt.BL,CY.WidgetPositionExt.BL];}b.set("align",{points:d});a.setX(a.getX()+gConf.iCommentLeftPadding);}};c_persistPreference=function(b,a,c){gPrefs.persist(b,a,c);};c_readDefaultPreference=function(b,a){return gConf.defaultPrefs[b][a];};c_readPreference=function(b,a){return gPrefs.get(b,a);};c_resetPreferences=function(a){gPrefs.reset(a);};c_applyTextStyle=function(a){CY.use(a);};sliderValToPx=function(d){var a=CY.DOM.winWidth();if(gLayout.isInFrame()){a=parent.$(parent).width();}var b=d/100;b=Math.min(b,gConf.sliderFixedMin);b=Math.max(b,gConf.sliderFixedMax);var c=b*a;return Math.floor(c);};c_setCommentsColWidth=function(c){var a=sliderValToPx(c);gLayout.setLeftColumnWidth(a);var b=gLayout.getTopICommentsWidthFromWidth(a);gIComments.setWidth(b);gICommentForm.overlay.get("boundingBox").setStyle("width",b+"px");changeFormFieldsWidth(gICommentForm.formId,b);if(gNewReply){changeFormFieldsWidth(gNewReply.ids["formId"],b);}if(gEdit){changeFormFieldsWidth(gEdit.ids["formId"],b);}};CY=null;gPrefs=null;gLayout=null;gDb=null;gIComments=null;gSync=null;gGETValues=null;gConf={iCommentLeftPadding:4,iCommentThreadPadding:12,defaultCommentFormat:"markdown",sliderFixedMin:0.9,sliderFixedMax:0.1,iCommentsInitAlloc:2,defaultPrefs:{text:{style:"text-modern-style"},user:{name:"",email:""},general:{animduration:"0.4"},comments:{threadpad:"1"},layout:{comments_col_width:"25"}}};gTextStyles={"text-modern-style":gettext("modern"),"text-classic-style":gettext("classic"),"text-code-style":gettext("code")};YUI({base:sv_media_url+"/js/lib/yui/"+c_yui_base+"/build/",timeout:10000}).use("text-modern-style","cookie","json","overlay","io-form","async-queue","event-mouseenter","anim","collection",function(a){CY=a;gPrefs=new Preferences();gPrefs.init();gLayout=new Layout();gLayout.init();if(sv_withComments){gDb=new Db();gDb.init();gIComments=new IComments();gIComments.init();}gSync=new Sync();gSync.init();CY.on("domready",onDomReady,this);});_reinit=function(a){gIComments.hide();gDb.initComments(a.commentIds);unpaintAllComments();renderCommentScopes();updateFilterResultsCount(a.nbDiscussions,a.nbComments,a.nbReplies);};reinit=function(b){var a=gDb.computeFilterResults(b);_reinit(a);};hideAll=function(){_reinit({commentIds:[],nbDiscussions:0,nbComments:0,nbReplies:0});};updateFilterResultsCount=function(f,a,b){var e=gDb.getCommentsAndRepliesCounts(true);var g=e[0],d=e[1];var c=(a!=0||b!=0)&&(g!=a||d!=b);if(gLayout.isInFrame()){parent.f_updateFilterCountDetailed(c);parent.f_updateFilterCountResult(f,a,b,g,d);}};updateResetFilterResultsCount=function(){var c=gDb.getCommentsAndRepliesCounts(false);var a=c[0],b=c[1];var d=a;updateFilterResultsCount(d,a,b);};renderCommentScopes=function(){for(var a=0;a<gDb.comments.length;a++){var b=gDb.comments[a];paintCommentScope(b);}};onTextMouseUp=function(f){if(readyForAction()){var c=getSelectionInfo();if(c!=null){updateICommentFormSelection(c);if(gEditICommentHost!=null){var g=CY.get("#"+gEdit.ids["changeScopeInputId"]+" input").get("checked");if(g){gEditICommentHost.scrollIntoView();}}}else{var d=f.target;if(d.hasClass("c-c")){var b=CY.Node.getDOMNode(d);var a=getCommentIdsFromClasses(b);if(a.length>0){checkForOpenedDialog(null,function(){gSync.showComments(a,[f.pageX,f.pageY],false);});}}}}};gLastScrollTime=null;checkForAlignement=function(){var a=(new Date()).getTime();if((gLastScrollTime!=null)&&(a-gLastScrollTime)>200){positionICommentForm();gLastScrollTime=null;}};onFrameScroll=function(){gLastScrollTime=(new Date()).getTime();};browse=function(a,b){gSync.browse(a,b);};initialConnect=function(){CY.on("mouseup",onTextMouseUp,"#textcontainer");gTimer=CY.Lang.later(200,this,checkForAlignement,[],true);CY.on("scroll",onFrameScroll,window,this,true);CY.on("resize",onFrameScroll,window,this,true);};preventLinksInText=function(){var a=function(g){var c=g.target;var d=null;while(c!=null&&d==null){c=c.get("parentNode");d=c.get("href");}if(c!=null&&d!=null){var b=window.location.href;var f=b.indexOf("#");if(f!=-1){b=b.substring(0,f);}if(d.indexOf(b)==-1){window.open(c.get("href"));g.preventDefault();}}};CY.all("#textcontainer a").on("click",a);};onDomReady=function(b){preventLinksInText();var a=new CY.AsyncQueue();a.add({fn:function(){if(gLayout.isInComentSite()){parent.toInitialSize();}if(sv_withComments){instanciateICommentForm();}},timeout:5},{fn:function(){gGETValues=CY.JSON.parse(sv_get_params);CY.get("#maincontainer").setStyle("display","block");CY.get("#textcontainer").setStyle("display","block");var e=(sv_withComments)?gPrefs.get("layout","comments_col_width"):0;var d=sliderValToPx(e);gLayout.setLeftColumnWidth(d);if(gLayout.isInFrame()){parent.f_initFrame();parent.f_layoutFrames();if(sv_withComments){parent.f_fillTopToolbar();if(hasPerm("can_create_comment")){parent.$("#add_comment_btn").removeClass("initially_hidden");}parent.f_fillFilterTab();parent.f_fillPreferencesTab();var c=CY.JSON.parse(sv_filter_data);parent.f_updateFilterData(c);parent.f_setFilterValue(gGETValues);}parent.f_fillTextPreferencesTab();}if(gLayout.isInComentSite()){parent.$("#c_fullscreen_btn").show();}else{parent.$("#c_fullscreen_btn").hide();}},timeout:5},{fn:function(){if(sv_withComments){reinit(gGETValues);initialConnect();}},timeout:5},{fn:function(){if(gLayout.isInFrame()){parent.f_interfaceUnfreeze();parent.f_removeLoadingMsg();}if("comment_id_key" in gGETValues){var d=gGETValues.comment_id_key;var f=gDb.getCommentByIdKey(d);if(f!=null){var e=gDb.getPath(f);var c=e[e.length-1];gSync.showSingleComment(c);}}if("comments_auto_display" in gGETValues){gSync.showAllComments();}}});a.run();};
\ No newline at end of file
+hasPerm=function(a){return(-1!=CY.Array.indexOf(sv_user_permissions,a));};Layout=function(){};Layout.prototype={init:function(){},isInFrame:function(){return(!CY.Lang.isUndefined(parent)&&parent.location!=location&&CY.Lang.isFunction(parent.f_getFrameFilterData));},isInComentSite:function(){var b=false;try{if(!CY.Lang.isUndefined(sv_site_url)&&!CY.Lang.isUndefined(parent)&&!CY.Lang.isUndefined(parent.parent)){var a=new String(parent.parent.location);b=(a.indexOf(sv_site_url)==0);}}catch(c){b=false;}return b;},sliderValToPx:function(d){var a=CY.DOM.winWidth();if(this.isInFrame()){a=parent.$(parent).width();}var b=d/100;b=Math.min(b,gConf.sliderFixedMin);b=Math.max(b,gConf.sliderFixedMax);var c=b*a;return Math.floor(c);},getTopICommentsWidth:function(){return this.getTopICommentsWidthFromWidth(this.sliderValToPx(gPrefs.get("layout","comments_col_width")));},getTopICommentsWidthFromWidth:function(b){var a=b-(2*gConf.iCommentThreadPadding);return a-7;},setLeftColumnWidth:function(a){CY.get("#contentcolumn").setStyle("marginLeft",a+"px");CY.get("#leftcolumn").setStyle("width",a+"px");},parentInterfaceUnfreeze:function(){if(this.isInFrame()){parent.f_interfaceUnfreeze();}}};Preferences=function(){this.prefs={};};Preferences.prototype={init:function(){this._read();},_read:function(){for(var b in gConf.defaultPrefs){this.prefs[b]={};for(var a in gConf.defaultPrefs[b]){var c=null;if(b=="user"&&(a=="name"||a=="email")){c=CY.Cookie.get("user_"+a);}else{c=CY.Cookie.getSub(b,a);}this.prefs[b][a]=(c==null)?gConf.defaultPrefs[b][a]:c;}}},persist:function(b,a,d){var c={path:"/",expires:(new Date()).setFullYear(2100,0,1)};if(b=="user"&&(a=="name"||a=="email")){CY.Cookie.set("user_"+a,d,c);}else{CY.Cookie.setSub(b,a,d,c);}this.prefs[b][a]=d;},get:function(b,a){return this.prefs[b][a];},readDefault:function(b,a){return gConf.defaultPrefs[b][a];},reset:function(a){for(var b=0;b<a.length;b++){var d=a[b];for(var c in gConf.defaultPrefs[d]){this.persist(d,c,gConf.defaultPrefs[d][c]);}}}};gShowingAllComments=false;Sync=function(){this._q=null;this._iPreventClick=false;};Sync.prototype={init:function(a){this._q=new CY.AsyncQueue();},setPreventClickOn:function(){CY.log("setPreventClickOn !");if(gLayout.isInFrame()){parent.f_interfaceFreeze();}this._iPreventClick=true;},setPreventClickOff:function(){CY.log("setPreventClickOff !");if(gLayout.isInFrame()){parent.f_interfaceUnfreeze();}this._iPreventClick=false;},removeCommentRet:function(b){var d=b.successfull;var a=(d)?b.failure["iComment"]:b.success["iComment"];if(d){var c=b.returned["filterData"];if(gLayout.isInFrame()){parent.f_updateFilterData(c);}var f=gIComments.getTopPosition()[1];var e=gDb.getComment(a.commentId);this._q.add(function(){unpaintCommentScope(e);gIComments.close(e.id);gIComments.remove(e.id);if(e.reply_to_id!=null){gIComments.refresh(e.reply_to_id);}gDb.del(e);if(gLayout.isInFrame()){if(gDb.comments.length==0&&gDb.allComments.length!=0){parent.f_enqueueMsg(gettext("no filtered comments left"));parent.resetFilter();}else{var g=gDb.computeFilterResults();updateFilterResultsCount(g.nbDiscussions,g.nbComments,g.nbReplies);}}});this._animateTo(f);}this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this.resume();},moderateCommentRet:function(c){var e=c.successfull;var a=(e)?c.failure["iComment"]:c.success["iComment"];if(e){var b=c.returned;var f=b.comment;gDb.upd(f);var d=gLayout.isInFrame()&&!parent.f_isFrameFilterFieldsInit();if(d){parent.resetFilter();this._showSingleComment(f);}else{a.changeModeration(f);}}this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this.resume();},saveCommentRet:function(h){var i=h.successfull;if(i){var l=h.success["formId"];var g=h.returned;removeFormErrMsg(l);if("errors" in g){var k=g.errors;for(var d in k){addFormErrMsg(l,d,k[d]);}this._animateToTop();}else{var b=function(){return(gNewReply!=null)&&(l==gNewReply.ids["formId"]);};var c=function(){return(gICommentForm!=null)&&(l==gICommentForm.formId);};var e=function(){return(gEdit!=null)&&(l==gEdit.ids["formId"]);};if(c()){this.hideICommentForm(cleanICommentForm());}else{if(e()){this._hideEditForm();}else{if(b()){this._hideNewReplyForm();}}}if("ask_for_notification" in g){if(g.ask_for_notification){parent.f_yesNoDialog(gettext("Do you want to be notified of all replies in all discussions you participated in?"),gettext("Reply notification"),function(){var m={method:"POST",data:urlEncode({fun:"ownNotify",key:sv_key,version_key:sv_version_key,email:g.email,active:false})};CY.io(sv_client_url,m);},this,null,function(){var m={method:"POST",data:urlEncode({fun:"ownNotify",key:sv_key,version_key:sv_version_key,email:g.email,active:true})};CY.io(sv_client_url,m);},this,null);}}if("comment" in g){var f=g.comment;gDb.upd(f);var a=gLayout.isInFrame()&&!parent.f_isFrameFilterFieldsInit();if(a){parent.resetFilter();}else{if(f.reply_to_id==null){unpaintCommentScope(f);paintCommentScope(f);}}var j=g.filterData;if(gLayout.isInFrame()){parent.f_updateFilterData(j);updateResetFilterResultsCount();}if(b()){if(!a){this._insertReply(f);}}else{this._showSingleComment(f);}}else{this._animateToTop();}}}else{this._q.add({id:"expl",fn:function(){CY.log("in example .........");}});this._q.promote("expl");}this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this.resume();},example:function(){CY.log("in example .........");},moderateComment:function(a,b){var c=gDb.getComment(a.commentId);this._q.add({fn:CY.bind(this.setPreventClickOn,this)},{autoContinue:false,fn:CY.bind(doExchange,null,"editComment",{comment_key:c.key,state:b},null,this.moderateCommentRet,this,{iComment:a},gettext("could not save comment"))}).run();},_saveComment:function(b,a){this._q.add({fn:CY.bind(this.setPreventClickOn,this)},{autoContinue:false,fn:CY.bind(doExchange,null,b,{},a,this.saveCommentRet,this,{formId:a},gettext("could not save comment"))}).run();},editComment:function(){this._saveComment("editComment",gEdit.ids["formId"]);},saveComment:function(a){this._saveComment("addComment",a);},removeComment:function(a){checkForOpenedDialog(a,function(){if(gLayout.isInFrame()){parent.f_yesNoDialog(gettext("Are you sure you want to delete this comment?"),gettext("Warning"),function(){this.animateToTop();},this,null,function(){var b=gDb.getComment(a.commentId);this._q.add({fn:CY.bind(this.setPreventClickOn,this)},{autoContinue:false,fn:CY.bind(doExchange,null,"removeComment",{comment_key:b.key},null,this.removeCommentRet,this,{iComment:a},gettext("could not remove comment"))}).run();},this,null);}},this,null);},resume:function(b,a){this._q.run();},resetAutoContinue:function(a){this._q.getCallback(a).autoContinue=true;},hideICommentForm:function(a){this._q.add({autoContinue:false,fn:CY.bind(gICommentForm.animationHide.run,gICommentForm.animationHide)});if(a){this._q.add(a);}},showCommentForm:function(a){checkForOpenedDialog(null,function(){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});this._q.add({fn:function(){if(a==null){var b=getSelectionInfo();updateICommentFormSelection(b);}showICommentForm(a);}});this._q.add({autoContinue:false,fn:CY.bind(gICommentForm.animationShow.run,gICommentForm.animationShow)},{fn:CY.bind(this.setPreventClickOff,this)}).run();},this,null);},showEditForm:function(a){checkForOpenedDialog(null,function(){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});this._q.add({fn:function(){showEditForm(a);}});this._animateToTop();this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this._q.run();},this,null);},showReplyForm:function(a){checkForOpenedDialog(null,function(){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});this._q.add({fn:function(){instanciateNewReplyForm(a);}});this._animateToTop();this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this._q.run();},this,null);},cancelICommentForm:function(){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});this.hideICommentForm();this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this._q.run();},cancelEdit:function(){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});this._q.add({fn:function(){cancelEditForm();}});this._animateToTop();this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this._q.run();},cancelReply:function(){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});this._q.add({fn:function(){cancelNewReplyForm();}});this._animateToTop();this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this._q.run();},changeScopeFormClick:function(){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});this._q.add({fn:function(){changeScopeFormClick();}});this._animateToTop();this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this._q.run();},_hideNewReplyForm:function(){this._q.add({fn:function(){cleanNewReplyForm();cancelNewReplyForm();}});},_hideEditForm:function(){this._q.add({fn:function(){cancelEditForm();}});},_insertReply:function(a){this._q.add({fn:function(){var g=gDb.getComment(a.reply_to_id);var e=gDb.getThreads([g]);var c=e[e.length-2];var d=gIComments.insertAfter(c,a);var h=gIComments.getPosition(a.reply_to_id);d.setPosition(h);var b=gDb.getPath(a);var f=b[b.length-1];if(gIComments.isTopActive(f.id)){d.activate();}d.show();}});this._animateToTop();},_showSingleComment:function(d){if(d!=null){var c=gDb.getPath(d);var b=c[c.length-1];var a=0;if(d.start_wrapper!=-1){a=CY.get(".c-id-"+b.id).getY();}else{a=CY.get("document").get("scrollTop");}this._showComments([b.id],a,false);if(b.replies.length>0){this._animateTo(a);}}},showSingleComment:function(a){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});this._showSingleComment(a);this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this._q.run();},browse:function(a,b){var c=gIComments.browse(a,b);if(c!=null){this.showSingleComment(c);}},_showComments:function(c,b,a){this._q.add({fn:function(){gShowingAllComments=a;gIComments.hide();var d=CY.Array.map(c,function(g){return gDb.getComment(g);});var f=gDb.getThreads(d);gIComments.fetch(f);if(c.length>0){if(a){CY.get("document").set("scrollTop",0);}else{gIComments.activate(c[0]);var e=CY.get(".c-id-"+c[0]);if(e&&!e.inViewportRegion()){e.scrollIntoView(true);}}}gIComments.setPosition([gConf.iCommentLeftPadding,b]);gIComments.show();}});},_animateTo:function(a){this._q.add({fn:function(){gIComments.setAnimationToPositions(a);}},{id:"animationRun",autoContinue:false,fn:CY.bind(gIComments.runAnimations,gIComments)});},_animateToTop:function(){var a=gIComments.getTopPosition();if(a!=null){this._animateTo(a[1]);}},animateToTop:function(){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});this._animateToTop();this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this._q.run();},showAllComments:function(){checkForOpenedDialog(null,function(){gShowingAllComments=true;var a=CY.Array.map(gDb.comments,function(b){return b.id;});this.showComments(a,[0,0],true);},this,null);},showScopeRemovedComments:function(){checkForOpenedDialog(null,function(){gShowingAllComments=true;var b=CY.Array.filter(gDb.comments,function(c){return(c.start_wrapper==-1);});var a=CY.Array.map(b,function(d){return d.id;});this.showComments(a,[0,0],true);},this,null);},showComments:function(c,b,a){checkForOpenedDialog(null,function(){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});this._showComments(c,b[1],a);this._animateTo(b[1]);this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this._q.run();},this,null);},openComment:function(a){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});var b=gIComments.getTopPosition()[1];this._q.add({fn:function(){gIComments.open(a.commentId);gIComments.refresh(a.commentId);}});this._animateTo(b);this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this._q.run();},closeComment:function(a){checkForOpenedDialog(a,function(){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});var b=gIComments.getTopPosition()[1];this._q.add({fn:function(){var c=gDb.getComment(a.commentId);gIComments.close(a.commentId);if(c.reply_to_id!=null){gIComments.refresh(c.reply_to_id);}}});this._animateTo(b);this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this._q.run();},this,null);},activate:function(a){gIComments.activate(a.commentId);}};readyForAction=function(){return !gSync._iPreventClick;};getWrapperAncestor=function(a){var b=a;while(b!=null){if(CY.DOM.hasClass(b,"c-s")){return b;}b=b.parentNode;}return null;};hasWrapperAncestor=function(a){return(getWrapperAncestor(a)!=null);};getSelectionInfo=function(){var J=null,m=null,D=0,c=0,h="";if(window.getSelection){var r=window.getSelection();if(r.rangeCount>0){var l=r.getRangeAt(0);h=l.toString();if(h!=""){var E=document.createRange();E.setStart(r.anchorNode,r.anchorOffset);E.collapse(true);var B=document.createRange();B.setEnd(r.focusNode,r.focusOffset);B.collapse(false);var I=(B.compareBoundaryPoints(2,E)==1);J=(I)?r.anchorNode.parentNode:r.focusNode.parentNode;innerStartNode=(I)?r.anchorNode:r.focusNode;m=(I)?r.focusNode.parentNode:r.anchorNode.parentNode;innerEndNode=(I)?r.focusNode:r.anchorNode;D=(I)?r.anchorOffset:r.focusOffset;c=(I)?r.focusOffset:r.anchorOffset;if(!hasWrapperAncestor(m)&&hasWrapperAncestor(J)){var z=document.createRange();z.setStart(innerStartNode,D);var b=getWrapperAncestor(J);var q=b;z.setEndAfter(q);var f=parseInt(b.id.substring("sv_".length));while(z.toString().length<l.toString().length){f++;var t=CY.get("#sv_"+f);if(t){q=CY.Node.getDOMNode(t);z.setEndAfter(q);}else{break;}}m=q.lastChild;c=CY.DOM.getText(m).length;}else{if(!hasWrapperAncestor(J)&&hasWrapperAncestor(m)){var z=document.createRange();z.setEnd(innerEndNode,c);var g=getWrapperAncestor(m);var p=g;z.setStartBefore(p);var f=parseInt(g.id.substring("sv_".length));while(z.toString().length<l.toString().length){f--;var t=CY.get("#sv_"+f);if(t){p=CY.Node.getDOMNode(t);z.setStartBefore(p);}else{break;}}J=p.firstChild;D=0;}else{if(!hasWrapperAncestor(J)&&!hasWrapperAncestor(m)){var o=h.length;var n=[];for(var f=0;;f++){var G=CY.get("#sv_"+f);if(G==null){break;}else{var x=G.get("text");if(h.indexOf(x)==0){n.push(f);}}}var y=[];for(var f=0;;f++){var G=CY.get("#sv_"+f);if(G==null){break;}else{var x=G.get("text");if(h.indexOf(x)==(o-x.length)){y.push(f);}}}var w=false;for(var C=0;C<n.length;C++){for(var A=0;A<y.length;A++){var v=document.createRange();var k=CY.Node.getDOMNode(CY.get("#sv_"+n[C]));var F=CY.Node.getDOMNode(CY.get("#sv_"+y[A]));v.setStartBefore(k);v.setEndAfter(CY.Node.getDOMNode(F));if((-1<v.compareBoundaryPoints(0,l))&&(1>v.compareBoundaryPoints(2,l))){J=k.firstChild;D=0;m=F.lastChild;c=CY.DOM.getText(F).length;w=true;break;}}if(w){break;}}}}}E.detach();B.detach();}else{return null;}}else{return null;}}else{if(document.selection){var d=document.selection.createRange();if(d.text.length==0){return null;}var a=d.parentElement();var H=d.duplicate();var u=d.duplicate();H.collapse(true);u.collapse(false);J=H.parentElement();while(H.moveStart("character",-1)!=0){if(H.parentElement()!=J){break;}D++;}m=u.parentElement();while(u.moveEnd("character",-1)!=0){if(u.parentElement()!=m){break;}c++;}h=d.text;}}if(!hasWrapperAncestor(J)||!hasWrapperAncestor(m)){return null;}return{text:h,start:{elt:J,offset:D},end:{elt:m,offset:c}};};Db=function(){this.comments=null;this.allComments=null;this.commentsByDbId={};this.allCommentsByDbId={};this.ordered_comment_ids={};};Db.prototype={init:function(){this.allComments=CY.JSON.parse(sv_comments);if(sv_read_only){this.initToReadOnly();}this._computeAllCommentsByDbId();this._reorder();},_del:function(a,e,g){var f=e[g];for(var c=0;c<f.replies.length;c++){var d=f.replies[c].id;this._del(f.replies,e,d);c--;}for(var c=0,b=a.length;c<b;c++){if(a[c].id==g){a.splice(c,1);delete e[g];break;}}},del:function(b){var a=(b.reply_to_id==null)?this.comments:this.commentsByDbId[b.reply_to_id].replies;this._del(a,this.commentsByDbId,b.id);a=(b.reply_to_id==null)?this.allComments:this.allCommentsByDbId[b.reply_to_id].replies;this._del(a,this.allCommentsByDbId,b.id);this._reorder();},_reorder:function(){var n=[];for(var k=0,c=this.allComments.length;k<c;k++){var l=this.allComments[k];var r=false;for(var g=0,q=n.length;g<q;g++){var b=n[g];var f=this.allCommentsByDbId[b];if((l.start_wrapper<f.start_wrapper)||((l.start_wrapper==f.start_wrapper)&&(l.start_offset<f.start_offset))||((l.start_wrapper==f.start_wrapper)&&(l.start_offset==f.start_offset)&&(l.end_wrapper<f.end_wrapper))||((l.start_wrapper==f.start_wrapper)&&(l.start_offset==f.start_offset)&&(l.end_wrapper==f.end_wrapper)&&(l.end_offset<f.end_offset))){n.splice(g,0,l.id);r=true;break;}}if(!r){n.push(l.id);}}this.ordered_comment_ids.scope=n;n=[];var m={};for(var k=0,c=this.allComments.length;k<c;k++){var l=this.allComments[k];var o=l.modified;m[l.id]=o;for(var g=0,q=l.replies.length;g<q;g++){var e=l.replies[g];var d=e.modified;if(d>m[l.id]){m[l.id]=d;}}}for(var b in m){var h=this.allCommentsByDbId[b].id;var r=false;for(var k=0,c=n.length;k<c;k++){var p=n[k];if(m[b]<m[p]){n.splice(k,0,h);r=true;break;}}if(!r){n.push(h);}}this.ordered_comment_ids.modif_thread=n;},_upd:function(a,f,g){var e=false;for(var d=0,b=a.length;d<b;d++){if(a[d].id==g.id){a.splice(d,1,g);e=true;break;}}if(!e){a.push(g);}f[g.id]=g;},upd:function(c){var a=(c.reply_to_id==null)?this.allComments:this.allCommentsByDbId[c.reply_to_id].replies;this._upd(a,this.allCommentsByDbId,c);var b=CY.clone(c);a=(c.reply_to_id==null)?this.comments:this.commentsByDbId[c.reply_to_id].replies;this._upd(a,this.commentsByDbId,b);this._reorder();},initComments:function(a){this.comments=[];for(var d=0,c=this.allComments.length;d<c;d++){var b=CY.Array.indexOf(a,this.allComments[d].id);if(b!=-1){var e=CY.clone(this.allComments[d]);this.comments.push(e);}}this._computeCommentsByDbId();},_computeCommentsByDbId:function(){this.commentsByDbId={};var b=this.getThreads(this.comments);for(var a=0;a<b.length;a++){this.commentsByDbId[b[a].id]=b[a];}},_computeAllCommentsByDbId:function(){this.allCommentsByDbId={};var b=this.getThreads(this.allComments);for(var a=0;a<b.length;a++){this.allCommentsByDbId[b[a].id]=b[a];}},getThreads:function(c){var a=[];for(var b=0;b<c.length;b++){a.push(c[b]);if(c[b].replies.length>0){a=a.concat(this.getThreads(c[b].replies));}}return a;},_getPath:function(b,e){var a=[e];var d=e;while(d.reply_to_id!=null){d=b[d.reply_to_id];a.push(d);}return a;},getPath:function(a){return this._getPath(this.commentsByDbId,a);},getComment:function(a){return this.commentsByDbId[a];},getCommentByIdKey:function(a){for(var c in this.commentsByDbId){var b=this.commentsByDbId[c];if(b.id_key==a){return b;}}return null;},isChild:function(d,b){var c=this.commentsByDbId[d];var a=(d==b);while((!a)&&(c.reply_to_id!=null)){c=this.commentsByDbId[c.reply_to_id];a=(c.id==b);}return a;},initToReadOnly:function(f,c){for(var b=0,a=this.allComments.length;b<a;b++){var e=this.allComments[b];for(var d in e){if(0==d.indexOf("can_")&&typeof e[d]==="boolean"){e[d]=false;}}}},browsingIndex:function(b){var c={};for(var a in this.ordered_comment_ids){var d=CY.Array.filter(this.ordered_comment_ids[a],function(e){return(e in this.commentsByDbId);},this);c[a]=CY.Array.indexOf(d,b);}return c;},browse:function(b,f,c){var a=this.ordered_comment_ids[b];if(a.length>0){var g=-1;if((f=="prev")||(f=="next")){for(var e=0;e<a.length;e++){var h=a[e];if(h==c){g=(f=="prev")?e-1:e+1;g=(a.length+g)%a.length;break;}}if(g==-1){CY.error("internal error in db browse (was called with a dbId that isn't among the filtered ones)");return null;}}if(f=="last"){g=a.length-1;}if(f=="first"){g=0;}for(var e=g,d=0;(e>=0)&&(e<a.length);d++){var h=a[e];if(h in this.commentsByDbId){return this.commentsByDbId[h];}if((f=="prev")||(f=="last")){e=e-1;}else{e=e+1;}e=(a.length+e)%a.length;if(d>a.length){break;}}CY.error("internal error in db browse (could not find any filtered comment)");}return null;},computeFilterResults:function(n){var a={};if(n){for(key in n){if(key.indexOf("filter_")==0){a[key.substr("filter_".length)]=n[key];}}}else{if(gLayout.isInFrame()){a=parent.f_getFrameFilterData();}}var v=[];var w=[];var b="";if("name" in a){b=a.name;}this.filterByName(b,v,w);var p=[];var c=[];var C="";if("date" in a){C=a.date;}this.filterByDate(C,p,c);var g=[];var f=[];var t="";if("text" in a){t=a.text;}this.filterByText(t,g,f);var x=[];var m=[];var A="";if("tag" in a){A=a.tag;}this.filterByTag(A,x,m);var u=[];var e=[];var k="";if("state" in a){k=a.state;}this.filterByState(k,u,e);var d=[];var z=[];for(var y=0,j=v.length;y<j;y++){var s=v[y];if((CY.Array.indexOf(p,s)!=-1)&&(CY.Array.indexOf(g,s)!=-1)&&(CY.Array.indexOf(x,s)!=-1)&&(CY.Array.indexOf(u,s)!=-1)){d.push(s);}}for(var y=0,j=w.length;y<j;y++){var s=w[y];if((CY.Array.indexOf(c,s)!=-1)&&(CY.Array.indexOf(f,s)!=-1)&&(CY.Array.indexOf(m,s)!=-1)&&(CY.Array.indexOf(e,s)!=-1)){z.push(s);}}var q=z.length,l=d.length;var r=l;for(var y=0,j=z.length;y<j;y++){var s=z[y];var o=this.allCommentsByDbId[s];var B=this._getPath(this.allCommentsByDbId,o);var h=B[B.length-1];var s=h.id;if(CY.Array.indexOf(d,s)==-1){d.push(s);r++;}}return{commentIds:d,nbDiscussions:r,nbComments:l,nbReplies:q};},filterByText:function(c,f,b){var a=new RegExp(c,"gi");for(var e in this.allCommentsByDbId){var d=this.allCommentsByDbId[e];if(c==""||a.exec(d.title)!=null||a.exec(d.content)!=null){if(d.reply_to_id==null){f.push(d.id);}else{b.push(d.id);}}}},filterByName:function(a,c,b){for(var e in this.allCommentsByDbId){var d=this.allCommentsByDbId[e];if(a==""||d.name==a){if(d.reply_to_id==null){c.push(d.id);}else{b.push(d.id);}}}},filterByTag:function(i,e,b){var h=new RegExp("^"+i+"$","g");var g=new RegExp("^"+i+", ","g");var d=new RegExp(", "+i+", ","g");var c=new RegExp(", "+i+"$","g");for(var a in this.allCommentsByDbId){var f=this.allCommentsByDbId[a];if(i==""||h.exec(f.tags)||g.exec(f.tags)!=null||d.exec(f.tags)!=null||c.exec(f.tags)!=null){if(f.reply_to_id==null){e.push(f.id);}else{b.push(f.id);}}}},filterByState:function(c,a,b){for(var e in this.allCommentsByDbId){var d=this.allCommentsByDbId[e];if(c==""||d.state==c){if(d.reply_to_id==null){a.push(d.id);}else{b.push(d.id);}}}},filterByDate:function(b,d,a){var c=(b=="")?0:parseInt(b);for(var f in this.allCommentsByDbId){var e=this.allCommentsByDbId[f];if(e.modified>c){if(e.reply_to_id==null){d.push(e.id);}else{a.push(e.id);}}}},getCommentsAndRepliesCounts:function(d){var b=0;var f=0;var a=(d)?this.allComments:this.comments;var e=this.getThreads(a);for(var c=0;c<e.length;c++){if(e[c].reply_to_id==null){b++;}else{f++;}}return[b,f];},getCommentsNb:function(b){var a=(b)?this.allComments:this.comments;return this.getThreads(a).length;},getFilteredCommentIdsAsString:function(){var a="";for(var b in this.commentsByDbId){a=a+b+",";}return a;}};IComment=function(){this.commentId=null;var l=gLayout.getTopICommentsWidth();var a=gConf.iCommentLeftPadding;var r=gettext("change comment state to pending");var n=gettext("change comment state to approved");var e=gettext("change comment state to unapproved");var q=gettext("cancel changing the state of this comment");var c=gettext("pending");var d=gettext("approved");var m=gettext("unapproved");var b=gettext("cancel");var p=gettext("show replies");var s=gettext("change to:");var i=ngettext("reply","replies",1);var g=gettext("edit comment");var j=gettext("delete comment");var o=gettext("edit");var f=gettext("delete");var k=gettext("close");var h=gettext("show scope");var t=gettext("Comment is detached: it was created on a previous version and text it applied to has been modified or removed.");this.overlay=new CY.Overlay({zIndex:3,shim:false,visible:false,width:l,xy:[a,0],headerContent:'<div class="icomment-header"><div class="c-iactions"><a class="c-moderate c-action" title="">vis</a> <a class="c-edit c-action" title="'+g+'" alt="'+g+'">'+o+'</a> <a class="c-delete c-action" title="'+j+'" alt="'+j+'">'+f+'</a> </div><div class="c-state-actions displaynone">'+s+'&nbsp;<a class="c-state-pending c-action" title="'+r+'" alt="'+r+'">'+c+'</a> <a class="c-state-approved c-action" title="'+n+'" alt="'+n+'">'+d+'</a> <a class="c-state-unapproved c-action" title="'+e+'" alt="'+e+'">'+m+'</a> <a class="c-state-cancel c-action" title="'+q+'" alt="'+q+'">'+b+'</a> </div><div class="c-no-scope-msg">'+t+'</div><a class="c-show-scope c-action" title="'+h+'" alt="'+h+'"><em>-</em></a><a class="c-close c-action" title="'+k+'" alt="'+k+'"><em>X</em></a></div>',bodyContent:'<div class="icomment-body"><span class="c-content"></span><span class="c-ireplyactions"><a class="c-readreplies c-action" title="'+p+'" alt="'+p+'">'+p+'</a> <a class="c-reply c-action" title="'+i+'" alt="'+i+'">'+i+"</a>&nbsp;</span></div>"});this.overlay.get("contentBox").addClass("c-comment");this.overlay.render("#leftcolumn");this.animation=new CY.Anim({node:this.overlay.get("boundingBox"),duration:gPrefs.get("general","animduration"),easing:CY.Easing.easeOut});this.overlay.get("contentBox").query(".c-close").on("click",this.onCloseCommentClick,this);this.overlay.get("contentBox").query(".c-moderate").on("click",this.onModerateCommentClick,this);this.overlay.get("contentBox").query(".c-state-pending").on("click",this.onPendingCommentClick,this);this.overlay.get("contentBox").query(".c-state-approved").on("click",this.onApprovedCommentClick,this);this.overlay.get("contentBox").query(".c-state-unapproved").on("click",this.onUnapprovedCommentClick,this);this.overlay.get("contentBox").query(".c-state-cancel").on("click",this.onCancelStateChangeClick,this);this.overlay.get("contentBox").query(".c-edit").on("click",this.onEditCommentClick,this);this.overlay.get("contentBox").query(".c-delete").on("click",this.onDeleteCommentClick,this);this.overlay.get("contentBox").query(".c-reply").on("click",this.onReplyCommentClick,this);this.overlay.get("contentBox").query(".c-readreplies").on("click",this.onReadRepliesCommentClick,this);this.overlay.get("contentBox").query(".icomment-header").on("mouseenter",this.onMouseEnterHeader,this);this.overlay.get("contentBox").query(".icomment-header").on("mouseleave",this.onMouseLeaveHeader,this);this.overlay.get("contentBox").on("click",this.onCommentClick,this);};IComment.prototype={onCloseCommentClick:function(a){a.halt();if(readyForAction()&&this.isVisible()){gSync.closeComment(this);}},onModerateCommentClick:function(a){a.halt();if(readyForAction()&&this.isVisible()){this.overlay.get("contentBox").query(".c-iactions").addClass("displaynone");this.overlay.get("contentBox").query(".c-state-actions").removeClass("displaynone");}},onPendingCommentClick:function(a){a.halt();if(readyForAction()&&this.isVisible()){gSync.moderateComment(this,"pending");}},onApprovedCommentClick:function(a){a.halt();if(readyForAction()&&this.isVisible()){gSync.moderateComment(this,"approved");}},onUnapprovedCommentClick:function(a){a.halt();if(readyForAction()&&this.isVisible()){gSync.moderateComment(this,"unapproved");}},onCancelStateChangeClick:function(a){a.halt();if(readyForAction()&&this.isVisible()){this.overlay.get("contentBox").query(".c-iactions").removeClass("displaynone");this.overlay.get("contentBox").query(".c-state-actions").addClass("displaynone");}},onDeleteCommentClick:function(a){a.halt();if(readyForAction()&&this.isVisible()){gSync.removeComment(this);}},onEditCommentClick:function(a){a.halt();if(readyForAction()&&this.isVisible()){gSync.showEditForm(this);}},onReplyCommentClick:function(a){a.halt();if(readyForAction()&&this.isVisible()){gSync.showReplyForm(this);}},onReadRepliesCommentClick:function(a){a.halt();if(readyForAction()&&this.isVisible()){gSync.openComment(this);}},onCommentClick:function(d){if(readyForAction()&&this.isVisible()){if(d.target.get("target")=="_blank"){var b=d.target;var g=sv_site_url+sv_text_view_show_comment_url;if(b.get("href").indexOf(g)==0){var a=(new RegExp("comment_id_key=([^&]*)","g")).exec(b.get("href"));if(a!=null){var c=a[1];var f=gDb.getCommentByIdKey(c);if(f!=null){d.halt();if(!b.hasClass("c-permalink")){checkForOpenedDialog(null,function(){gSync.showSingleComment(f);});}}}}}else{if(gShowingAllComments){if(!this._isHostingAForm()){var f=gDb.getComment(this.commentId);checkForOpenedDialog(null,function(){if(f!=null){gSync.showSingleComment(f);}});}}else{gSync.activate(this);}}}},onMouseEnterHeader:function(){if(readyForAction()&&this.isVisible()&&(sv_prefix=="")){this.overlay.get("contentBox").query(".c-permalink").removeClass("displaynone");}},onMouseLeaveHeader:function(){if(readyForAction()&&this.isVisible()&&(sv_prefix=="")){this.overlay.get("contentBox").query(".c-permalink").addClass("displaynone");}},setWidth:function(a){this.overlay.get("boundingBox").setStyle("width",a+"px");},activate:function(){this.overlay.get("boundingBox").addClass("c-focus-comment");},deactivate:function(){this.overlay.get("boundingBox").removeClass("c-focus-comment");},hide:function(){if(gIComments.isTopActive(this.commentId)){if(!gIComments.activateVisibleNext()){gIComments.deactivate();}}if(this.isVisible()){this.overlay.hide();this.overlay.blur();}},hideContent:function(){this.overlay.get("contentBox").query(".icomment-header").addClass("displaynone");this.overlay.get("contentBox").query(".icomment-body").addClass("displaynone");},showContent:function(){this.overlay.get("contentBox").query(".icomment-header").removeClass("displaynone");this.overlay.get("contentBox").query(".icomment-body").removeClass("displaynone");},isVisible:function(){return this.overlay.get("visible");},show:function(){this.hideReadRepliesLnk();return this.overlay.show();},showReadRepliesLnk:function(){this.overlay.get("contentBox").query(".c-readreplies").removeClass("displaynone");},hideReadRepliesLnk:function(){this.overlay.get("contentBox").query(".c-readreplies").addClass("displaynone");},changeModeration:function(b){var a=this.overlay.get("contentBox").query(".c-moderate");a.set("innerHTML",gettext(b.state));a.removeClass("c-state-approved");a.removeClass("c-state-pending");a.removeClass("c-state-unapproved");a.addClass("c-state-"+b.state);this.overlay.get("contentBox").query(".c-iactions").removeClass("displaynone");this.overlay.get("contentBox").query(".c-state-actions").addClass("displaynone");},isfetched:function(){return(this.commentId!=null);},unfetch:function(){this.commentId=null;},fetch:function(h){this.commentId=h.id;var b=this.overlay.get("boundingBox");if(h.start_wrapper!=-1){b.addClass("c-has-scope");b.removeClass("c-has-no-scope");}else{b.addClass("c-has-no-scope");b.removeClass("c-has-scope");}if(h.reply_to_id!=null){b.addClass("c-is-reply");}else{b.removeClass("c-is-reply");}var f=interpolate(gettext("last modified on %(date)s"),{date:h.modified_user_str},true);var k=(h.modified==h.created)?"":'<a title="'+f+'"> * </a>';var i=gettext("Permalink to this comment");var n="";if(sv_prefix==""){n='<a class="c-permalink displaynone c-action" target="_blank" title="'+i+'" href="" >¶&nbsp;</a>';}var j=interpolate(gettext("by %(name)s, created on %(date)s"),{name:h.name,date:h.created_user_str},true);var c='<span class="c-header"><div class="c-header-title">'+h.title+n+'</div><div class="c-infos">'+j+"</div></span>";var d=CY.Node.create(c);var o=b.query(".c-header");if(o==null){b.query(".icomment-header").insertBefore(d,b.one(".c-iactions"));}else{o.get("parentNode").replaceChild(d,o);}var g=CY.Node.create('<div class="c-tags"><span class="c-tags-infos">tags:</span>'+h.tags+"</div>");var m=b.query(".c-tags");if(m==null){b.query(".icomment-header").appendChild(g);}else{m.get("parentNode").replaceChild(g,m);}if(h.tags==""){g.addClass("displaynone");}var e=CY.Node.create('<span class="c-content">'+h.content_html+"</span>");var a=b.query(".c-content");if(a==null){b.query(".icomment-body").appendChild(e);}else{a.get("parentNode").replaceChild(e,a);}if(sv_prefix==""){b.query(".c-permalink").set("href",sv_site_url+h.permalink);}this.changeModeration(h);var l=b.queryAll(".c-content a");if(l!=null){l.setAttribute("target","_blank");}l=b.queryAll(".c-header-title a");if(l!=null){l.setAttribute("target","_blank");}this.permAdapt(h);},permAdapt:function(e){var b=this.overlay.get("contentBox").query(".c-delete");if(b){if(!e.can_delete){b.addClass("displaynone");}else{b.removeClass("displaynone");}}var a=this.overlay.get("contentBox").query(".c-edit");if(a){if(!e.can_edit){a.addClass("displaynone");}else{a.removeClass("displaynone");}}var d=this.overlay.get("contentBox").query(".c-reply");if(d){if(!hasPerm("can_create_comment")){d.addClass("displaynone");}else{d.removeClass("displaynone");}}var c=this.overlay.get("contentBox").query(".c-moderate");if(c){if(!e.can_moderate){c.addClass("displaynone");}else{c.removeClass("displaynone");}}},setThreadPad:function(a){this.overlay.get("contentBox").query(".yui-widget-hd").setStyle("paddingLeft",a+"px");this.overlay.get("contentBox").query(".yui-widget-bd").setStyle("paddingLeft",a+"px");},setPosition:function(b){var a=this.overlay.get("boundingBox");a.setStyle("opacity",1);a.setXY(b);},getPosition:function(b){var a=this.overlay.get("boundingBox");return a.getXY();},onAnimationEnd:function(){if(!CY.Lang.isUndefined(this["animation-handle"])&&!CY.Lang.isNull(this["animation-handle"])){this["animation-handle"].detach();this["animation-handle"]=null;}gIComments.signalAnimationEnd();if(gIComments.animationsEnded()){gIComments.whenAnimationsEnd();}},setAnimationToPosition:function(b){var a=this.overlay.get("boundingBox");if(gPrefs.get("general","animduration")<0.011){a.setXY(b);}this.animation.set("to",{xy:b});this.animation.set("duration",gPrefs.get("general","animduration"));this["animation-handle"]=this.animation.on("end",this.onAnimationEnd,this);return this.animation;},getHeight:function(){return this.overlay.get("boundingBox").get("offsetHeight");},scrollIntoView:function(){if(!this.overlay.get("contentBox").inViewportRegion()){this.overlay.get("contentBox").scrollIntoView(true);}},_isHostingAForm:function(){return(this.isVisible()&&((gNewReplyHost!=null&&gNewReplyHost==this)||(gEditICommentHost!=null&&gEditICommentHost==this)));}};gEditICommentHost=null;gEdit=null;dbgc=null;showEditForm=function(a){if(gEdit==null){gEdit={ids:{formId:CY.guid(),formTitleId:CY.guid(),nameInputId:CY.guid(),emailInputId:CY.guid(),titleInputId:CY.guid(),contentInputId:CY.guid(),tagsInputId:CY.guid(),formatInputId:CY.guid(),startWrapperInputId:CY.guid(),endWrapperInputId:CY.guid(),startOffsetInputId:CY.guid(),endOffsetInputId:CY.guid(),changeScopeInputId:CY.guid(),changeScopeInputWrapper:CY.guid(),selectionPlaceId:CY.guid(),keyId:CY.guid(),editCommentId:CY.guid(),currentSelId:CY.guid(),currentSelIdI:CY.guid(),addBtnId:CY.guid(),cancelBtnId:CY.guid()},handlers:{}};}gEditICommentHost=a;gEditICommentHost.hideContent();var c=getHtml(gEdit.ids);var b='<div class="icomment-edit-header">'+c.headerContent+"</div>";var e='<div class="icomment-edit-body">'+c.bodyContent+"</div>";gEditICommentHost.overlay.setStdModContent(CY.WidgetStdMod.HEADER,CY.Node.create(b),CY.WidgetStdMod.AFTER);gEditICommentHost.overlay.setStdModContent(CY.WidgetStdMod.BODY,CY.Node.create(e),CY.WidgetStdMod.AFTER);CY.get("#"+gEdit.ids["formTitleId"]).set("innerHTML",gettext("Edit comment"));var f=gDb.getComment(gEditICommentHost.commentId);CY.get("#"+gEdit.ids["editCommentId"]).set("value",f.id);CY.get("#"+gEdit.ids["keyId"]).set("value",f.key);CY.get("#"+gEdit.ids["changeScopeInputId"]+" input").set("checked",false);if(f.reply_to_id!=null){CY.get("#"+gEdit.ids["changeScopeInputId"]).addClass("displaynone");}changeScopeFormClick();CY.get("#"+gEdit.ids["nameInputId"]).set("value",f.name);CY.get("#"+gEdit.ids["emailInputId"]).set("value",f.email);if(f.logged_author){CY.get("#"+gEdit.ids["nameInputId"]).setAttribute("disabled",true);CY.get("#"+gEdit.ids["emailInputId"]).setAttribute("disabled",true);}CY.get("#"+gEdit.ids["titleInputId"]).set("value",f.title);CY.get("#"+gEdit.ids["contentInputId"]).set("value",f.content);CY.get("#"+gEdit.ids["tagsInputId"]).set("value",f.tags);CY.get("#"+gEdit.ids["formatInputId"]).set("value",gConf.defaultCommentFormat);var d=gLayout.getTopICommentsWidth();changeFormFieldsWidth(gEdit.ids["formId"],d);gEdit.handlers["addBtnId"]=CY.on("click",onEditSaveClick,"#"+gEdit.ids["addBtnId"]);gEdit.handlers["cancelBtnId"]=CY.on("click",onEditCancelClick,"#"+gEdit.ids["cancelBtnId"]);gEdit.handlers["changeScope"]=CY.on("click",onChangeScopeClick,"#"+gEdit.ids["changeScopeInputId"]);};onEditSaveClick=function(a){if(readyForAction()){gSync.editComment();}};onEditCancelClick=function(a){if(readyForAction()){gSync.cancelEdit();}};onChangeScopeClick=function(){if(readyForAction()){gSync.changeScopeFormClick();}else{var a=CY.get("#"+gEdit.ids["changeScopeInputId"]+" input");var b=a.get("checked");a.set("checked",!b);}};changeScopeFormClick=function(){var a=CY.get("#"+gEdit.ids["currentSelId"]);if(CY.get("#"+gEdit.ids["changeScopeInputId"]+" input").get("checked")){a.removeClass("displaynone");}else{a.addClass("displaynone");}};cancelEditForm=function(){if(gEditICommentHost!=null){for(var b in gEdit.handlers){if(gEdit.handlers[b]!=null){gEdit.handlers[b].detach();gEdit.handlers[b]=null;}}var a=gEditICommentHost.overlay.get("contentBox").query(".icomment-edit-body");a.get("parentNode").removeChild(a);a=gEditICommentHost.overlay.get("contentBox").query(".icomment-edit-header");a.get("parentNode").removeChild(a);gEditICommentHost.showContent();gEditICommentHost=null;}};var gtest={renaud:"RENAUD",random:Math.random(),bernard:"BERNARD",myFunc:function(){doExchange("theServerFun",{},null,this.myRetFunc,this,["foo","bar"]);},myRetFunc:function(a){CY.log("this.renaud : "+this.renaud);CY.log("this.random : "+this.random);CY.log("arg.returned : "+a.returned);CY.log(a.returned);CY.log("arg.success : "+a.success);CY.log(a.success);}};doExchange=function(h,e,g,f,d,c,b){e.fun=h;e.key=sv_key;e.version_key=sv_version_key;var a={method:"POST",data:urlEncode(e),on:{success:function(l,k,j){var i={};if(k.responseText){i=CY.JSON.parse(k.responseText);}if(gLayout.isInFrame()&&("msg" in i)){parent.f_enqueueMsg(i.msg);}j.returned=i;j.successfull=true;f.call(d,j);},failure:function(k,j,i){if(gLayout.isInFrame()){parent.f_enqueueErrorMsg(gettext("error:")+b);}i.successfull=false;f.call(d,i);}},arguments:{success:c,failure:c}};if(g!=null){a.form={id:g};}CY.io(sv_client_url,a);};warn_server=function(c){c.fun="warn";c.key=sv_key;c.version_key=sv_version_key;var b=CY.UA;var a={method:"POST",data:urlEncode(CY.merge(c,b))};CY.io("/client/",a);};paintCommentScope=function(b){if(b.reply_to_id==null&&b.start_wrapper!=-1){var a={start:{elt:document.getElementById("sv_"+b.start_wrapper),offset:b.start_offset},end:{elt:document.getElementById("sv_"+b.end_wrapper),offset:b.end_offset}};if(document.getElementById("sv_"+b.start_wrapper)==null){warn_server({from:"paintCommentScope",start_wrapper:b.start_wrapper});}else{if(document.getElementById("sv_"+b.end_wrapper)==null){warn_server({from:"paintCommentScope",end_wrapper:b.end_wrapper});}else{a.start=_convertSelectionFromCSToCC(a.start);a.end=_convertSelectionFromCSToCC(a.end);renderComment(a,b.id);}}}};getCommentIdsFromClasses=function(b){var a=[];var e=b.className.split(" ");for(var d=0,c=e.length;d<c;d++){if(e[d].indexOf("c-id-")==0){a.push(parseInt(e[d].substring("c-id-".length)));}}return a;};renderComment=function(d,c){var a=d.start["offset"];var b=d.end["offset"];var f=d.start["elt"];var e=d.end["elt"];if((f!=null)&&(e!=null)&&_getTextNodeContent(f)!=""&&_getTextNodeContent(e)!=""){markWholeNodesAsComments(f,e,c);markEndsAsComments(f,a,e,b,c);}};markWholeNodesAsComments=function(d,c,b){var a=_findCommonAncestor(d,c);_dynSpanToAnc(d,a,b,false);_dynSpanToAnc(c,a,b,true);_dynSpanInBetween(a,d,c,b);};_setTextNodeContent=function(a,b){CY.DOM.setText(a,b);};_getTextNodeContent=function(a){return CY.DOM.getText(a);};markEndsAsComments=function(d,i,l,j,h){var n=_getTextNodeContent(d).substring(0,i);var o=_getTextNodeContent(d).substring(i);var p=_getTextNodeContent(l).substring(0,j);var g=_getTextNodeContent(l).substring(j);var b=(d===l);if(o!=""){if(CY.DOM.hasClass(d,"c-c")){var f=null,k=null,c=null,a=null;var m=(b)?_getTextNodeContent(d).substring(i,j):o;if(b&&(g!="")){c=d;f=c;}if(m!=""){if(f==null){k=d;}else{k=_yuiCloneNode(d);f.parentNode.insertBefore(k,f);}f=k;}if(n!=""){if(f==null){a=d;}else{a=_yuiCloneNode(d);f.parentNode.insertBefore(a,f);}f=a;}if(c!=null){_setTextNodeContent(c,g);}if(k!=null){_setTextNodeContent(k,m);_addIdClass(k,h);}if(a!=null){_setTextNodeContent(a,n);}}}if((!b)&&(p!="")){if(CY.DOM.hasClass(l,"c-c")){var f=null,e=null,c=null;if(g!=""){c=l;f=l;}if(p!=""){if(f==null){e=l;}else{e=_yuiCloneNode(l);f.parentNode.insertBefore(e,f);}f=e;}if(c!=null){_setTextNodeContent(c,g);}if(e!=null){_addIdClass(e,h);_setTextNodeContent(e,p);}}}};_yuiCloneNode=function(b){var a=CY.Node.getDOMNode(CY.get("#"+b.id).cloneNode(true));a.id=CY.guid();return a;};_dynSpanToAnc=function(a,e,d,f){var g=a;while((g!=null)&&(g!==e)&&(g.parentNode!==e)){var b=null;if(f){b=g.previousSibling;}else{b=g.nextSibling;}if(b==null){g=g.parentNode;}else{g=b;_recAddComment(g,d);}}};_dynSpanInBetween=function(g,h,f,d){var b=h;var e=null;while(b){if(b.parentNode===g){e=b;break;}b=b.parentNode;}if(e!=null){b=f;var c=null;while(b){if(b.parentNode===g){c=b;break;}b=b.parentNode;}if(c!=null){b=e.nextSibling;while((b!=null)&&(b!==c)){_recAddComment(b,d);b=b.nextSibling;}}}};_bruteContains=function(a,b){while(b){if(a===b){return true;}b=b.parentNode;}return false;},_addIdClass=function(a,b){CY.DOM.addClass(a,"c-id-"+b);_updateCommentCounter(a);};_removeIdClass=function(a,b){CY.DOM.removeClass(a,"c-id-"+b);_updateCommentCounter(a);};_removeIdClasses=function(a){var b=_cgetRegExp("(?:^|\\s+)c-id-(?:\\d+)","g");a.className=a.className.replace(b," ");_updateCommentCounter(a);};_recAddComment=function(a,b){if(CY.DOM.hasClass(a,"c-c")){_addIdClass(a,b);}else{var d=a.firstChild;while(d!=null){_recAddComment(d,b);d=d.nextSibling;}}};_findCommonAncestor=function(c,a){if(_bruteContains(c,a)){return c;}else{var b=a;while((b!=null)&&!_bruteContains(b,c)){b=b.parentNode;}return b;}};_cregexCache={};_cgetRegExp=function(b,a){a=a||"";if(!_cregexCache[b+a]){_cregexCache[b+a]=new RegExp(b,a);}return _cregexCache[b+a];};_updateCommentCounter=function(b){var c=_cgetRegExp("(?:^|\\s+)c-id-(?:\\d+)","g");var d=b.className.match(c);var a=(d==null)?0:d.length;c=_cgetRegExp("(?:^|\\s+)c-count-(?:\\d+)","g");b.className=b.className.replace(c," ");CY.DOM.addClass(b,"c-count-"+a+" ");};_convertSelectionFromCCToCS=function(b){var d=b.offset;var a=b.elt.parentNode;var c=b.elt.previousSibling;while(c!=null){d+=_getTextNodeContent(c).length;c=c.previousSibling;}return{elt:a,offset:d};};_convertSelectionFromCSToCC=function(d){var a={elt:null,offset:-1};var f=null;var e=d.elt.firstChild;var c=0;while(e!=null){var b=c;c+=_getTextNodeContent(e).length;if(c>=d.offset){a.elt=e;a.offset=d.offset-b;break;}e=e.nextSibling;}return a;};unpaintCommentScope=function(k){var j=k.id;var r="c-id-"+j;var m=[];var t=CY.all("."+r);if(t!=null){for(var h=0,d=t.size();h<d;h++){var q=t.item(h);if(q.hasClass("c-c")){var l=CY.Node.getDOMNode(q);_removeIdClass(l,j);var f=getCommentIdsFromClasses(l);quicksort(f);var a=q.get("previousSibling");if(a!=null){var b=CY.Node.getDOMNode(a);var s=getCommentIdsFromClasses(b);quicksort(s);if(areSortedArraysEqual(f,s)){_setTextNodeContent(l,_getTextNodeContent(b)+_getTextNodeContent(l));m.push(b);}}var e=q.get("nextSibling");if(e!=null){var o=CY.Node.getDOMNode(e);var g=getCommentIdsFromClasses(o);quicksort(g);if(areSortedArraysEqual(f,g)){l.firstChild.data=l.firstChild.data+o.firstChild.data;m.push(o);}}}else{alert("HAS NO c-c ? : "+commentNode.get("id")+" , innerHTML :"+commentNode.get("innerHTML"));return;}}}for(var h=0,d=m.length;h<d;h++){m[h].parentNode.removeChild(m[h]);}};unpaintAllComments=function(){var k=CY.all(".c-s");var f=[];for(var e=0,a=k.size();e<a;e++){var h=k.item(e);var d=h.get("firstChild");var j=CY.Node.getDOMNode(h.get("firstChild"));_removeIdClasses(j);var b=d.get("nextSibling");while(b!=null){var g=CY.Node.getDOMNode(b);j.firstChild.data=j.firstChild.data+g.firstChild.data;f.push(g);b=b.get("nextSibling");}}for(var e=0,a=f.length;e<a;e++){f[e].parentNode.removeChild(f[e]);}};showScope=function(b){var a=CY.all(".c-id-"+b);if(a!=null){a.addClass("c-scope");}};hideScopeAnyway=function(){var a=CY.all(".c-scope");if(a!=null){a.removeClass("c-scope");}};hasPerm=function(b){return(-1!=CY.Array.indexOf(sv_user_permissions,b));};Layout=function(){};Layout.prototype={init:function(){},isInFrame:function(){return(!CY.Lang.isUndefined(parent)&&parent.location!=location&&CY.Lang.isFunction(parent.f_getFrameFilterData));},isInComentSite:function(){var d=false;try{if(!CY.Lang.isUndefined(sv_site_url)&&!CY.Lang.isUndefined(parent)&&!CY.Lang.isUndefined(parent.parent)){var e=new String(parent.parent.location);d=(e.indexOf(sv_site_url)==0);}}catch(f){d=false;}return d;},sliderValToPx:function(g){var f=CY.DOM.winWidth();if(this.isInFrame()){f=parent.$(parent).width();}var e=g/100;e=Math.min(e,gConf.sliderFixedMin);e=Math.max(e,gConf.sliderFixedMax);var h=e*f;return Math.floor(h);},getTopICommentsWidth:function(){return this.getTopICommentsWidthFromWidth(this.sliderValToPx(gPrefs.get("layout","comments_col_width")));},getTopICommentsWidthFromWidth:function(c){var d=c-(2*gConf.iCommentThreadPadding);return d-7;},setLeftColumnWidth:function(b){CY.get("#contentcolumn").setStyle("marginLeft",b+"px");CY.get("#leftcolumn").setStyle("width",b+"px");},parentInterfaceUnfreeze:function(){if(this.isInFrame()){parent.f_interfaceUnfreeze();}}};Preferences=function(){this.prefs={};};Preferences.prototype={init:function(){this._read();},_read:function(){for(var d in gConf.defaultPrefs){this.prefs[d]={};for(var e in gConf.defaultPrefs[d]){var f=null;if(d=="user"&&(e=="name"||e=="email")){f=CY.Cookie.get("user_"+e);}else{f=CY.Cookie.getSub(d,e);}this.prefs[d][e]=(f==null)?gConf.defaultPrefs[d][e]:f;}}},persist:function(e,f,g){var h={path:"/",expires:(new Date()).setFullYear(2100,0,1)};if(e=="user"&&(f=="name"||f=="email")){CY.Cookie.set("user_"+f,g,h);}else{CY.Cookie.setSub(e,f,g,h);}this.prefs[e][f]=g;},get:function(c,d){return this.prefs[c][d];},readDefault:function(c,d){return gConf.defaultPrefs[c][d];},reset:function(f){for(var e=0;e<f.length;e++){var g=f[e];for(var h in gConf.defaultPrefs[g]){this.persist(g,h,gConf.defaultPrefs[g][h]);}}}};gShowingAllComments=false;Sync=function(){this._q=null;this._iPreventClick=false;};Sync.prototype={init:function(b){this._q=new CY.AsyncQueue();},setPreventClickOn:function(){CY.log("setPreventClickOn !");if(gLayout.isInFrame()){parent.f_interfaceFreeze();}this._iPreventClick=true;},setPreventClickOff:function(){CY.log("setPreventClickOff !");if(gLayout.isInFrame()){parent.f_interfaceUnfreeze();}this._iPreventClick=false;},removeCommentRet:function(g){var k=g.successfull;var h=(k)?g.failure.iComment:g.success.iComment;if(k){var l=g.returned.filterData;if(gLayout.isInFrame()){parent.f_updateFilterData(l);}var i=gIComments.getTopPosition()[1];var j=gDb.getComment(h.commentId);this._q.add(function(){unpaintCommentScope(j);gIComments.close(j.id);gIComments.remove(j.id);if(j.reply_to_id!=null){gIComments.refresh(j.reply_to_id);}gDb.del(j);if(gLayout.isInFrame()){if(gDb.comments.length==0&&gDb.allComments.length!=0){parent.f_enqueueMsg(gettext("no filtered comments left"));parent.resetFilter();}else{var a=gDb.computeFilterResults();updateFilterResultsCount(a.nbDiscussions,a.nbComments,a.nbReplies);}}});this._animateTo(i);}this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this.resume();},moderateCommentRet:function(l){var j=l.successfull;var h=(j)?l.failure.iComment:l.success.iComment;if(j){var g=l.returned;var i=g.comment;gDb.upd(i);var k=gLayout.isInFrame()&&!parent.f_isFrameFilterFieldsInit();if(k){parent.resetFilter();this._showSingleComment(i);}else{h.changeModeration(i);}}this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this.resume();},saveCommentRet:function(q){var p=q.successfull;if(p){var m=q.success.formId;var r=q.returned;removeFormErrMsg(m);if("errors" in r){var n=r.errors;for(var u in n){addFormErrMsg(m,u,n[u]);}this._animateToTop();}else{var w=function(){return(gNewReply!=null)&&(m==gNewReply.ids.formId);};var v=function(){return(gICommentForm!=null)&&(m==gICommentForm.formId);};var t=function(){return(gEdit!=null)&&(m==gEdit.ids.formId);};if(v()){this.hideICommentForm(cleanICommentForm());}else{if(t()){this._hideEditForm();}else{if(w()){this._hideNewReplyForm();}}}if("ask_for_notification" in r){if(r.ask_for_notification){parent.f_yesNoDialog(gettext("Do you want to be notified of all replies in all discussions you participated in?"),gettext("Reply notification"),function(){var a={method:"POST",data:urlEncode({fun:"ownNotify",key:sv_key,version_key:sv_version_key,email:r.email,active:false})};CY.io(sv_client_url,a);},this,null,function(){var a={method:"POST",data:urlEncode({fun:"ownNotify",key:sv_key,version_key:sv_version_key,email:r.email,active:true})};CY.io(sv_client_url,a);},this,null);}}if("comment" in r){var s=r.comment;gDb.upd(s);var x=gLayout.isInFrame()&&!parent.f_isFrameFilterFieldsInit();if(x){parent.resetFilter();}else{if(s.reply_to_id==null){unpaintCommentScope(s);paintCommentScope(s);}}var o=r.filterData;if(gLayout.isInFrame()){parent.f_updateFilterData(o);updateResetFilterResultsCount();}if(w()){if(!x){this._insertReply(s);}}else{this._showSingleComment(s);}}else{this._animateToTop();}}}else{this._q.add({id:"expl",fn:function(){CY.log("in example .........");}});this._q.promote("expl");}this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this.resume();},example:function(){CY.log("in example .........");},moderateComment:function(e,d){var f=gDb.getComment(e.commentId);this._q.add({fn:CY.bind(this.setPreventClickOn,this)},{autoContinue:false,fn:CY.bind(doExchange,null,"editComment",{comment_key:f.key,state:d},null,this.moderateCommentRet,this,{iComment:e},gettext("could not save comment"))}).run();},_saveComment:function(c,d){this._q.add({fn:CY.bind(this.setPreventClickOn,this)},{autoContinue:false,fn:CY.bind(doExchange,null,c,{},d,this.saveCommentRet,this,{formId:d},gettext("could not save comment"))}).run();},editComment:function(){this._saveComment("editComment",gEdit.ids.formId);},saveComment:function(b){this._saveComment("addComment",b);},removeComment:function(b){checkForOpenedDialog(b,function(){if(gLayout.isInFrame()){parent.f_yesNoDialog(gettext("Are you sure you want to delete this comment?"),gettext("Warning"),function(){this.animateToTop();},this,null,function(){var a=gDb.getComment(b.commentId);this._q.add({fn:CY.bind(this.setPreventClickOn,this)},{autoContinue:false,fn:CY.bind(doExchange,null,"removeComment",{comment_key:a.key},null,this.removeCommentRet,this,{iComment:b},gettext("could not remove comment"))}).run();},this,null);}},this,null);},resume:function(c,d){this._q.run();},resetAutoContinue:function(b){this._q.getCallback(b).autoContinue=true;},hideICommentForm:function(b){this._q.add({autoContinue:false,fn:CY.bind(gICommentForm.animationHide.run,gICommentForm.animationHide)});if(b){this._q.add(b);}},showCommentForm:function(b){checkForOpenedDialog(null,function(){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});this._q.add({fn:function(){if(b==null){var a=getSelectionInfo();updateICommentFormSelection(a);}showICommentForm(b);}});this._q.add({autoContinue:false,fn:CY.bind(gICommentForm.animationShow.run,gICommentForm.animationShow)},{fn:CY.bind(this.setPreventClickOff,this)}).run();},this,null);},showEditForm:function(b){checkForOpenedDialog(null,function(){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});this._q.add({fn:function(){showEditForm(b);}});this._animateToTop();this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this._q.run();},this,null);},showReplyForm:function(b){checkForOpenedDialog(null,function(){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});this._q.add({fn:function(){instanciateNewReplyForm(b);}});this._animateToTop();this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this._q.run();},this,null);},cancelICommentForm:function(){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});this.hideICommentForm();this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this._q.run();},cancelEdit:function(){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});this._q.add({fn:function(){cancelEditForm();}});this._animateToTop();this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this._q.run();},cancelReply:function(){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});this._q.add({fn:function(){cancelNewReplyForm();}});this._animateToTop();this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this._q.run();},changeScopeFormClick:function(){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});this._q.add({fn:function(){changeScopeFormClick();}});this._animateToTop();this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this._q.run();},_hideNewReplyForm:function(){this._q.add({fn:function(){cleanNewReplyForm();cancelNewReplyForm();}});},_hideEditForm:function(){this._q.add({fn:function(){cancelEditForm();}});},_insertReply:function(b){this._q.add({fn:function(){var j=gDb.getComment(b.reply_to_id);var l=gDb.getThreads([j]);var n=l[l.length-2];var m=gIComments.insertAfter(n,b);var i=gIComments.getPosition(b.reply_to_id);m.setPosition(i);var a=gDb.getPath(b);var k=a[a.length-1];if(gIComments.isTopActive(k.id)){m.activate();}m.show();}});this._animateToTop();},_showSingleComment:function(g){if(g!=null){var h=gDb.getPath(g);var e=h[h.length-1];var f=0;if(g.start_wrapper!=-1){f=CY.get(".c-id-"+e.id).getY();}else{f=CY.get("document").get("scrollTop");}this._showComments([e.id],f,false);if(e.replies.length>0){this._animateTo(f);}}},showSingleComment:function(b){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});this._showSingleComment(b);this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this._q.run();},browse:function(e,d){var f=gIComments.browse(e,d);if(f!=null){this.showSingleComment(f);}},_showComments:function(f,d,e){this._q.add({fn:function(){gShowingAllComments=e;gIComments.hide();var c=CY.Array.map(f,function(h){return gDb.getComment(h);});var a=gDb.getThreads(c);gIComments.fetch(a);if(f.length>0){if(e){CY.get("document").set("scrollTop",0);}else{gIComments.activate(f[0]);var b=CY.get(".c-id-"+f[0]);if(b&&!b.inViewportRegion()){b.scrollIntoView(true);}}}gIComments.setPosition([gConf.iCommentLeftPadding,d]);gIComments.show();}});},_animateTo:function(b){this._q.add({fn:function(){gIComments.setAnimationToPositions(b);}},{id:"animationRun",autoContinue:false,fn:CY.bind(gIComments.runAnimations,gIComments)});},_animateToTop:function(){var b=gIComments.getTopPosition();if(b!=null){this._animateTo(b[1]);}},animateToTop:function(){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});this._animateToTop();this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this._q.run();},showAllComments:function(){checkForOpenedDialog(null,function(){gShowingAllComments=true;var b=CY.Array.map(gDb.comments,function(a){return a.id;});this.showComments(b,[0,0],true);},this,null);},showScopeRemovedComments:function(){checkForOpenedDialog(null,function(){gShowingAllComments=true;var c=CY.Array.filter(gDb.comments,function(a){return(a.start_wrapper==-1);});var d=CY.Array.map(c,function(a){return a.id;});this.showComments(d,[0,0],true);},this,null);},showComments:function(f,d,e){checkForOpenedDialog(null,function(){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});this._showComments(f,d[1],e);this._animateTo(d[1]);this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this._q.run();},this,null);},openComment:function(d){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});var c=gIComments.getTopPosition()[1];this._q.add({fn:function(){gIComments.open(d.commentId);gIComments.refresh(d.commentId);}});this._animateTo(c);this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this._q.run();},closeComment:function(b){checkForOpenedDialog(b,function(){this._q.add({fn:CY.bind(this.setPreventClickOn,this)});var a=gIComments.getTopPosition()[1];this._q.add({fn:function(){var d=gDb.getComment(b.commentId);gIComments.close(b.commentId);if(d.reply_to_id!=null){gIComments.refresh(d.reply_to_id);}}});this._animateTo(a);this._q.add({fn:CY.bind(this.setPreventClickOff,this)});this._q.run();},this,null);},activate:function(b){gIComments.activate(b.commentId);}};readyForAction=function(){return !gSync._iPreventClick;};getWrapperAncestor=function(d){var c=d;while(c!=null){if(CY.DOM.hasClass(c,"c-s")){return c;}c=c.parentNode;}return null;};hasWrapperAncestor=function(b){return(getWrapperAncestor(b)!=null);};getSelectionInfo=function(){var j=null,ac=null,T=0,aj=0,af="";if(window.getSelection){var V=window.getSelection();if(V.rangeCount>0){var ad=V.getRangeAt(0);af=ad.toString();if(af!=""){var R=document.createRange();R.setStart(V.anchorNode,V.anchorOffset);R.collapse(true);var W=document.createRange();W.setEnd(V.focusNode,V.focusOffset);W.collapse(false);var K=(W.compareBoundaryPoints(2,R)==1);j=(K)?V.anchorNode.parentNode:V.focusNode.parentNode;innerStartNode=(K)?V.anchorNode:V.focusNode;ac=(K)?V.focusNode.parentNode:V.anchorNode.parentNode;innerEndNode=(K)?V.focusNode:V.anchorNode;T=(K)?V.anchorOffset:V.focusOffset;aj=(K)?V.focusOffset:V.anchorOffset;if(!hasWrapperAncestor(ac)&&hasWrapperAncestor(j)){var e=document.createRange();e.setStart(innerStartNode,T);var ak=getWrapperAncestor(j);var X=ak;e.setEndAfter(X);var ah=parseInt(ak.id.substring("sv_".length));while(e.toString().length<ad.toString().length){ah++;var S=CY.get("#sv_"+ah);if(S){X=CY.Node.getDOMNode(S);e.setEndAfter(X);}else{break;}}ac=X.lastChild;aj=CY.DOM.getText(ac).length;}else{if(!hasWrapperAncestor(j)&&hasWrapperAncestor(ac)){var e=document.createRange();e.setEnd(innerEndNode,aj);var ag=getWrapperAncestor(ac);var Z=ag;e.setStartBefore(Z);var ah=parseInt(ag.id.substring("sv_".length));while(e.toString().length<ad.toString().length){ah--;var S=CY.get("#sv_"+ah);if(S){Z=CY.Node.getDOMNode(S);e.setStartBefore(Z);}else{break;}}j=Z.firstChild;T=0;}else{if(!hasWrapperAncestor(j)&&!hasWrapperAncestor(ac)){var aa=af.length;var ab=[];for(var ah=0;;ah++){var O=CY.get("#sv_"+ah);if(O==null){break;}else{var s=O.get("text");if(af.indexOf(s)==0){ab.push(ah);}}}var i=[];for(var ah=0;;ah++){var O=CY.get("#sv_"+ah);if(O==null){break;}else{var s=O.get("text");if(af.indexOf(s)==(aa-s.length)){i.push(ah);}}}var M=false;for(var U=0;U<ab.length;U++){for(var Y=0;Y<i.length;Y++){var N=document.createRange();var ae=CY.Node.getDOMNode(CY.get("#sv_"+ab[U]));var Q=CY.Node.getDOMNode(CY.get("#sv_"+i[Y]));N.setStartBefore(ae);N.setEndAfter(CY.Node.getDOMNode(Q));if((-1<N.compareBoundaryPoints(0,ad))&&(1>N.compareBoundaryPoints(2,ad))){j=ae.firstChild;T=0;ac=Q.lastChild;aj=CY.DOM.getText(Q).length;M=true;break;}}if(M){break;}}}}}R.detach();W.detach();}else{return null;}}else{return null;}}else{if(document.selection){var ai=document.selection.createRange();if(ai.text.length==0){return null;}var al=ai.parentElement();var L=ai.duplicate();var P=ai.duplicate();L.collapse(true);P.collapse(false);j=L.parentElement();while(L.moveStart("character",-1)!=0){if(L.parentElement()!=j){break;}T++;}ac=P.parentElement();while(P.moveEnd("character",-1)!=0){if(P.parentElement()!=ac){break;}aj++;}af=ai.text;}}if(!hasWrapperAncestor(j)||!hasWrapperAncestor(ac)){return null;}return{text:af,start:{elt:j,offset:T},end:{elt:ac,offset:aj}};};Db=function(){this.comments=null;this.allComments=null;this.commentsByDbId={};this.allCommentsByDbId={};this.ordered_comment_ids={};};Db.prototype={init:function(){this.allComments=CY.JSON.parse(sv_comments);if(sv_read_only){this.initToReadOnly();}this._computeAllCommentsByDbId();this._reorder();},_del:function(i,l,j){var k=l[j];for(var n=0;n<k.replies.length;n++){var m=k.replies[n].id;this._del(k.replies,l,m);n--;}for(var n=0,h=i.length;n<h;n++){if(i[n].id==j){i.splice(n,1);delete l[j];break;}}},del:function(c){var d=(c.reply_to_id==null)?this.comments:this.commentsByDbId[c.reply_to_id].replies;this._del(d,this.commentsByDbId,c.id);d=(c.reply_to_id==null)?this.allComments:this.allCommentsByDbId[c.reply_to_id].replies;this._del(d,this.allCommentsByDbId,c.id);this._reorder();},_reorder:function(){var t=[];for(var w=0,C=this.allComments.length;w<C;w++){var v=this.allComments[w];var a=false;for(var y=0,i=t.length;y<i;y++){var D=t[y];var z=this.allCommentsByDbId[D];if((v.start_wrapper<z.start_wrapper)||((v.start_wrapper==z.start_wrapper)&&(v.start_offset<z.start_offset))||((v.start_wrapper==z.start_wrapper)&&(v.start_offset==z.start_offset)&&(v.end_wrapper<z.end_wrapper))||((v.start_wrapper==z.start_wrapper)&&(v.start_offset==z.start_offset)&&(v.end_wrapper==z.end_wrapper)&&(v.end_offset<z.end_offset))){t.splice(y,0,v.id);a=true;break;}}if(!a){t.push(v.id);}}this.ordered_comment_ids.scope=t;t=[];var u={};for(var w=0,C=this.allComments.length;w<C;w++){var v=this.allComments[w];var s=v.modified;u[v.id]=s;for(var y=0,i=v.replies.length;y<i;y++){var A=v.replies[y];var B=A.modified;if(B>u[v.id]){u[v.id]=B;}}}for(var D in u){var x=this.allCommentsByDbId[D].id;var a=false;for(var w=0,C=t.length;w<C;w++){var j=t[w];if(u[D]<u[j]){t.splice(w,0,x);a=true;break;}}if(!a){t.push(x);}}this.ordered_comment_ids.modif_thread=t;},_upd:function(h,j,i){var k=false;for(var l=0,c=h.length;l<c;l++){if(h[l].id==i.id){h.splice(l,1,i);k=true;break;}}if(!k){h.push(i);}j[i.id]=i;},upd:function(f){var e=(f.reply_to_id==null)?this.allComments:this.allCommentsByDbId[f.reply_to_id].replies;this._upd(e,this.allCommentsByDbId,f);var d=CY.clone(f);e=(f.reply_to_id==null)?this.comments:this.commentsByDbId[f.reply_to_id].replies;this._upd(e,this.commentsByDbId,d);this._reorder();},initComments:function(g){this.comments=[];for(var i=0,j=this.allComments.length;i<j;i++){var f=CY.Array.indexOf(g,this.allComments[i].id);if(f!=-1){var h=CY.clone(this.allComments[i]);this.comments.push(h);}}this._computeCommentsByDbId();},_computeCommentsByDbId:function(){this.commentsByDbId={};var c=this.getThreads(this.comments);for(var d=0;d<c.length;d++){this.commentsByDbId[c[d].id]=c[d];}},_computeAllCommentsByDbId:function(){this.allCommentsByDbId={};var c=this.getThreads(this.allComments);for(var d=0;d<c.length;d++){this.allCommentsByDbId[c[d].id]=c[d];}},getThreads:function(f){var e=[];for(var d=0;d<f.length;d++){e.push(f[d]);if(f[d].replies.length>0){e=e.concat(this.getThreads(f[d].replies));}}return e;},_getPath:function(c,g){var f=[g];var h=g;while(h.reply_to_id!=null){h=c[h.reply_to_id];f.push(h);}return f;},getPath:function(b){return this._getPath(this.commentsByDbId,b);},getComment:function(b){return this.commentsByDbId[b];},getCommentByIdKey:function(e){for(var f in this.commentsByDbId){var d=this.commentsByDbId[f];if(d.id_key==e){return d;}}return null;},isChild:function(g,e){var h=this.commentsByDbId[g];var f=(g==e);while((!f)&&(h.reply_to_id!=null)){h=this.commentsByDbId[h.reply_to_id];f=(h.id==e);}return f;},initToReadOnly:function(i,l){for(var g=0,h=this.allComments.length;g<h;g++){var j=this.allComments[g];for(var k in j){if(0==k.indexOf("can_")&&typeof j[k]==="boolean"){j[k]=false;}}}},browsingIndex:function(e){var h={};for(var f in this.ordered_comment_ids){var g=CY.Array.filter(this.ordered_comment_ids[f],function(a){return(a in this.commentsByDbId);},this);h[f]=CY.Array.indexOf(g,e);}return h;},browse:function(i,m,p){var j=this.ordered_comment_ids[i];if(j.length>0){var l=-1;if((m=="prev")||(m=="next")){for(var n=0;n<j.length;n++){var k=j[n];if(k==p){l=(m=="prev")?n-1:n+1;l=(j.length+l)%j.length;break;}}if(l==-1){CY.error("internal error in db browse (was called with a dbId that isn't among the filtered ones)");return null;}}if(m=="last"){l=j.length-1;}if(m=="first"){l=0;}for(var n=l,o=0;(n>=0)&&(n<j.length);o++){var k=j[n];if(k in this.commentsByDbId){return this.commentsByDbId[k];}if((m=="prev")||(m=="last")){n=n-1;}else{n=n+1;}n=(j.length+n)%j.length;if(o>j.length){break;}}CY.error("internal error in db browse (could not find any filtered comment)");}return null;},computeFilterResults:function(R){var ad={};if(R){for(key in R){if(key.indexOf("filter_")==0){ad[key.substr("filter_".length)]=R[key];}}}else{if(gLayout.isInFrame()){ad=parent.f_getFrameFilterData();}}var G=[];var F=[];var ac="";if("name" in ad){ac=ad.name;}this.filterByName(ac,G,F);var P=[];var ab=[];var L="";if("date" in ad){L=ad.date;}this.filterByDate(L,P,ab);var X=[];var Y=[];var I="";if("text" in ad){I=ad.text;}this.filterByText(I,X,Y);var E=[];var S=[];var O="";if("tag" in ad){O=ad.tag;}this.filterByTag(O,E,S);var H=[];var Z=[];var U="";if("state" in ad){U=ad.state;}this.filterByState(U,H,Z);var aa=[];var i=[];for(var D=0,V=G.length;D<V;D++){var J=G[D];if((CY.Array.indexOf(P,J)!=-1)&&(CY.Array.indexOf(X,J)!=-1)&&(CY.Array.indexOf(E,J)!=-1)&&(CY.Array.indexOf(H,J)!=-1)){aa.push(J);}}for(var D=0,V=F.length;D<V;D++){var J=F[D];if((CY.Array.indexOf(ab,J)!=-1)&&(CY.Array.indexOf(Y,J)!=-1)&&(CY.Array.indexOf(S,J)!=-1)&&(CY.Array.indexOf(Z,J)!=-1)){i.push(J);}}var N=i.length,T=aa.length;var K=T;for(var D=0,V=i.length;D<V;D++){var J=i[D];var Q=this.allCommentsByDbId[J];var M=this._getPath(this.allCommentsByDbId,Q);var W=M[M.length-1];var J=W.id;if(CY.Array.indexOf(aa,J)==-1){aa.push(J);K++;}}return{commentIds:aa,nbDiscussions:K,nbComments:T,nbReplies:N};},filterByText:function(l,i,g){var h=new RegExp(l,"gi");for(var j in this.allCommentsByDbId){var k=this.allCommentsByDbId[j];if(l==""||h.exec(k.title)!=null||h.exec(k.content)!=null){if(k.reply_to_id==null){i.push(k.id);}else{g.push(k.id);}}}},filterByName:function(g,j,f){for(var h in this.allCommentsByDbId){var i=this.allCommentsByDbId[h];if(g==""||i.name==g){if(i.reply_to_id==null){j.push(i.id);}else{f.push(i.id);}}}},filterByTag:function(j,n,q){var k=new RegExp("^"+j+"$","g");var l=new RegExp("^"+j+", ","g");var o=new RegExp(", "+j+", ","g");var p=new RegExp(", "+j+"$","g");for(var r in this.allCommentsByDbId){var m=this.allCommentsByDbId[r];if(j==""||k.exec(m.tags)||l.exec(m.tags)!=null||o.exec(m.tags)!=null||p.exec(m.tags)!=null){if(m.reply_to_id==null){n.push(m.id);}else{q.push(m.id);}}}},filterByState:function(j,g,f){for(var h in this.allCommentsByDbId){var i=this.allCommentsByDbId[h];if(j==""||i.state==j){if(i.reply_to_id==null){g.push(i.id);}else{f.push(i.id);}}}},filterByDate:function(g,k,h){var l=(g=="")?0:parseInt(g);for(var i in this.allCommentsByDbId){var j=this.allCommentsByDbId[i];if(j.modified>l){if(j.reply_to_id==null){k.push(j.id);}else{h.push(j.id);}}}},getCommentsAndRepliesCounts:function(k){var g=0;var i=0;var h=(k)?this.allComments:this.comments;var j=this.getThreads(h);for(var l=0;l<j.length;l++){if(j[l].reply_to_id==null){g++;}else{i++;}}return[g,i];},getCommentsNb:function(c){var d=(c)?this.allComments:this.comments;return this.getThreads(d).length;},getFilteredCommentIdsAsString:function(){var d="";for(var c in this.commentsByDbId){d=d+c+",";}return d;}};IComment=function(){this.commentId=null;var C=gLayout.getTopICommentsWidth();var N=gConf.iCommentLeftPadding;var w=gettext("change comment state to pending");var A=gettext("change comment state to approved");var J=gettext("change comment state to unapproved");var x=gettext("cancel changing the state of this comment");var L=gettext("pending");var K=gettext("approved");var B=gettext("unapproved");var M=gettext("cancel");var y=gettext("show replies");var v=gettext("change to:");var F=ngettext("reply","replies",1);var H=gettext("edit comment");var E=gettext("delete comment");var z=gettext("edit");var I=gettext("delete");var D=gettext("close");var G=gettext("show scope");var u=gettext("Comment is detached: it was created on a previous version and text it applied to has been modified or removed.");this.overlay=new CY.Overlay({zIndex:3,shim:false,visible:false,width:C,xy:[N,0],headerContent:'<div class="icomment-header"><div class="c-iactions"><a class="c-moderate c-action" title="">vis</a> <a class="c-edit c-action" title="'+H+'" alt="'+H+'">'+z+'</a> <a class="c-delete c-action" title="'+E+'" alt="'+E+'">'+I+'</a> </div><div class="c-state-actions displaynone">'+v+'&nbsp;<a class="c-state-pending c-action" title="'+w+'" alt="'+w+'">'+L+'</a> <a class="c-state-approved c-action" title="'+A+'" alt="'+A+'">'+K+'</a> <a class="c-state-unapproved c-action" title="'+J+'" alt="'+J+'">'+B+'</a> <a class="c-state-cancel c-action" title="'+x+'" alt="'+x+'">'+M+'</a> </div><div class="c-no-scope-msg">'+u+'</div><a class="c-show-scope c-action" title="'+G+'" alt="'+G+'"><em>-</em></a><a class="c-close c-action" title="'+D+'" alt="'+D+'"><em>X</em></a></div>',bodyContent:'<div class="icomment-body"><span class="c-content"></span><span class="c-ireplyactions"><a class="c-readreplies c-action" title="'+y+'" alt="'+y+'">'+y+'</a> <a class="c-reply c-action" title="'+F+'" alt="'+F+'">'+F+"</a>&nbsp;</span></div>"});this.overlay.get("contentBox").addClass("c-comment");this.overlay.render("#leftcolumn");this.animation=new CY.Anim({node:this.overlay.get("boundingBox"),duration:gPrefs.get("general","animduration"),easing:CY.Easing.easeOut});this.overlay.get("contentBox").query(".c-close").on("click",this.onCloseCommentClick,this);this.overlay.get("contentBox").query(".c-moderate").on("click",this.onModerateCommentClick,this);this.overlay.get("contentBox").query(".c-state-pending").on("click",this.onPendingCommentClick,this);this.overlay.get("contentBox").query(".c-state-approved").on("click",this.onApprovedCommentClick,this);this.overlay.get("contentBox").query(".c-state-unapproved").on("click",this.onUnapprovedCommentClick,this);this.overlay.get("contentBox").query(".c-state-cancel").on("click",this.onCancelStateChangeClick,this);this.overlay.get("contentBox").query(".c-edit").on("click",this.onEditCommentClick,this);this.overlay.get("contentBox").query(".c-delete").on("click",this.onDeleteCommentClick,this);this.overlay.get("contentBox").query(".c-reply").on("click",this.onReplyCommentClick,this);this.overlay.get("contentBox").query(".c-readreplies").on("click",this.onReadRepliesCommentClick,this);this.overlay.get("contentBox").query(".icomment-header").on("mouseenter",this.onMouseEnterHeader,this);this.overlay.get("contentBox").query(".icomment-header").on("mouseleave",this.onMouseLeaveHeader,this);this.overlay.get("contentBox").on("click",this.onCommentClick,this);};IComment.prototype={onCloseCommentClick:function(b){b.halt();if(readyForAction()&&this.isVisible()){gSync.closeComment(this);}},onModerateCommentClick:function(b){b.halt();if(readyForAction()&&this.isVisible()){this.overlay.get("contentBox").query(".c-iactions").addClass("displaynone");this.overlay.get("contentBox").query(".c-state-actions").removeClass("displaynone");}},onPendingCommentClick:function(b){b.halt();if(readyForAction()&&this.isVisible()){gSync.moderateComment(this,"pending");}},onApprovedCommentClick:function(b){b.halt();if(readyForAction()&&this.isVisible()){gSync.moderateComment(this,"approved");}},onUnapprovedCommentClick:function(b){b.halt();if(readyForAction()&&this.isVisible()){gSync.moderateComment(this,"unapproved");}},onCancelStateChangeClick:function(b){b.halt();if(readyForAction()&&this.isVisible()){this.overlay.get("contentBox").query(".c-iactions").removeClass("displaynone");this.overlay.get("contentBox").query(".c-state-actions").addClass("displaynone");}},onDeleteCommentClick:function(b){b.halt();if(readyForAction()&&this.isVisible()){gSync.removeComment(this);}},onEditCommentClick:function(b){b.halt();if(readyForAction()&&this.isVisible()){gSync.showEditForm(this);}},onReplyCommentClick:function(b){b.halt();if(readyForAction()&&this.isVisible()){gSync.showReplyForm(this);}},onReadRepliesCommentClick:function(b){b.halt();if(readyForAction()&&this.isVisible()){gSync.openComment(this);}},onCommentClick:function(k){if(readyForAction()&&this.isVisible()){if(k.target.get("target")=="_blank"){var e=k.target;var i=sv_site_url+sv_text_view_show_comment_url;if(e.get("href").indexOf(i)==0){var h=(new RegExp("comment_id_key=([^&]*)","g")).exec(e.get("href"));if(h!=null){var l=h[1];var j=gDb.getCommentByIdKey(l);if(j!=null){k.halt();if(!e.hasClass("c-permalink")){checkForOpenedDialog(null,function(){gSync.showSingleComment(j);});}}}}}else{if(gShowingAllComments){if(!this._isHostingAForm()){var j=gDb.getComment(this.commentId);checkForOpenedDialog(null,function(){if(j!=null){gSync.showSingleComment(j);}});}}else{gSync.activate(this);}}}},onMouseEnterHeader:function(){if(readyForAction()&&this.isVisible()&&(sv_prefix=="")){this.overlay.get("contentBox").query(".c-permalink").removeClass("displaynone");}},onMouseLeaveHeader:function(){if(readyForAction()&&this.isVisible()&&(sv_prefix=="")){this.overlay.get("contentBox").query(".c-permalink").addClass("displaynone");}},setWidth:function(b){this.overlay.get("boundingBox").setStyle("width",b+"px");},activate:function(){this.overlay.get("boundingBox").addClass("c-focus-comment");},deactivate:function(){this.overlay.get("boundingBox").removeClass("c-focus-comment");},hide:function(){if(gIComments.isTopActive(this.commentId)){if(!gIComments.activateVisibleNext()){gIComments.deactivate();}}if(this.isVisible()){this.overlay.hide();this.overlay.blur();}},hideContent:function(){this.overlay.get("contentBox").query(".icomment-header").addClass("displaynone");this.overlay.get("contentBox").query(".icomment-body").addClass("displaynone");},showContent:function(){this.overlay.get("contentBox").query(".icomment-header").removeClass("displaynone");this.overlay.get("contentBox").query(".icomment-body").removeClass("displaynone");},isVisible:function(){return this.overlay.get("visible");},show:function(){this.hideReadRepliesLnk();return this.overlay.show();},showReadRepliesLnk:function(){this.overlay.get("contentBox").query(".c-readreplies").removeClass("displaynone");},hideReadRepliesLnk:function(){this.overlay.get("contentBox").query(".c-readreplies").addClass("displaynone");},changeModeration:function(c){var d=this.overlay.get("contentBox").query(".c-moderate");d.set("innerHTML",gettext(c.state));d.removeClass("c-state-approved");d.removeClass("c-state-pending");d.removeClass("c-state-unapproved");d.addClass("c-state-"+c.state);this.overlay.get("contentBox").query(".c-iactions").removeClass("displaynone");this.overlay.get("contentBox").query(".c-state-actions").addClass("displaynone");},isfetched:function(){return(this.commentId!=null);},unfetch:function(){this.commentId=null;},fetch:function(w){this.commentId=w.id;var C=this.overlay.get("boundingBox");if(w.start_wrapper!=-1){C.addClass("c-has-scope");C.removeClass("c-has-no-scope");}else{C.addClass("c-has-no-scope");C.removeClass("c-has-scope");}if(w.reply_to_id!=null){C.addClass("c-is-reply");}else{C.removeClass("c-is-reply");}var y=interpolate(gettext("last modified on %(date)s"),{date:w.modified_user_str},true);var t=(w.modified==w.created)?"":'<a title="'+y+'"> * </a>';var v=gettext("Permalink to this comment");var q="";if(sv_prefix==""){q='<a class="c-permalink displaynone c-action" target="_blank" title="'+v+'" href="" >¶&nbsp;</a>';}var u=interpolate(gettext("by %(name)s, created on %(date)s"),{name:w.name,date:w.created_user_str},true);var B='<span class="c-header"><div class="c-header-title">'+w.title+q+'</div><div class="c-infos">'+u+"</div></span>";var A=CY.Node.create(B);var p=C.query(".c-header");if(p==null){C.query(".icomment-header").insertBefore(A,C.one(".c-iactions"));}else{p.get("parentNode").replaceChild(A,p);}var x=CY.Node.create('<div class="c-tags"><span class="c-tags-infos">tags:</span>'+w.tags+"</div>");var r=C.query(".c-tags");if(r==null){C.query(".icomment-header").appendChild(x);}else{r.get("parentNode").replaceChild(x,r);}if(w.tags==""){x.addClass("displaynone");}var z=CY.Node.create('<span class="c-content">'+w.content_html+"</span>");var D=C.query(".c-content");if(D==null){C.query(".icomment-body").appendChild(z);}else{D.get("parentNode").replaceChild(z,D);}if(sv_prefix==""){C.query(".c-permalink").set("href",sv_site_url+w.permalink);}this.changeModeration(w);var s=C.queryAll(".c-content a");if(s!=null){s.setAttribute("target","_blank");}s=C.queryAll(".c-header-title a");if(s!=null){s.setAttribute("target","_blank");}this.permAdapt(w);},permAdapt:function(h){var f=this.overlay.get("contentBox").query(".c-delete");if(f){if(!h.can_delete){f.addClass("displaynone");}else{f.removeClass("displaynone");}}var g=this.overlay.get("contentBox").query(".c-edit");if(g){if(!h.can_edit){g.addClass("displaynone");}else{g.removeClass("displaynone");}}var i=this.overlay.get("contentBox").query(".c-reply");if(i){if(!hasPerm("can_create_comment")){i.addClass("displaynone");}else{i.removeClass("displaynone");}}var j=this.overlay.get("contentBox").query(".c-moderate");if(j){if(!h.can_moderate){j.addClass("displaynone");}else{j.removeClass("displaynone");}}},setThreadPad:function(b){this.overlay.get("contentBox").query(".yui-widget-hd").setStyle("paddingLeft",b+"px");this.overlay.get("contentBox").query(".yui-widget-bd").setStyle("paddingLeft",b+"px");},setPosition:function(c){var d=this.overlay.get("boundingBox");d.setStyle("opacity",1);d.setXY(c);},getPosition:function(c){var d=this.overlay.get("boundingBox");return d.getXY();},onAnimationEnd:function(){if(!CY.Lang.isUndefined(this["animation-handle"])&&!CY.Lang.isNull(this["animation-handle"])){this["animation-handle"].detach();this["animation-handle"]=null;}gIComments.signalAnimationEnd();if(gIComments.animationsEnded()){gIComments.whenAnimationsEnd();}},setAnimationToPosition:function(c){var d=this.overlay.get("boundingBox");if(gPrefs.get("general","animduration")<0.011){d.setXY(c);}this.animation.set("to",{xy:c});this.animation.set("duration",gPrefs.get("general","animduration"));this["animation-handle"]=this.animation.on("end",this.onAnimationEnd,this);return this.animation;},getHeight:function(){return this.overlay.get("boundingBox").get("offsetHeight");},scrollIntoView:function(){if(!this.overlay.get("contentBox").inViewportRegion()){this.overlay.get("contentBox").scrollIntoView(true);}},_isHostingAForm:function(){return(this.isVisible()&&((gNewReplyHost!=null&&gNewReplyHost==this)||(gEditICommentHost!=null&&gEditICommentHost==this)));}};gEditICommentHost=null;gEdit=null;dbgc=null;showEditForm=function(h){if(gEdit==null){gEdit={ids:{formId:CY.guid(),formTitleId:CY.guid(),nameInputId:CY.guid(),emailInputId:CY.guid(),titleInputId:CY.guid(),contentInputId:CY.guid(),tagsInputId:CY.guid(),formatInputId:CY.guid(),startWrapperInputId:CY.guid(),endWrapperInputId:CY.guid(),startOffsetInputId:CY.guid(),endOffsetInputId:CY.guid(),changeScopeInputId:CY.guid(),changeScopeInputWrapper:CY.guid(),selectionPlaceId:CY.guid(),keyId:CY.guid(),editCommentId:CY.guid(),currentSelId:CY.guid(),currentSelIdI:CY.guid(),addBtnId:CY.guid(),cancelBtnId:CY.guid()},handlers:{}};}gEditICommentHost=h;gEditICommentHost.hideContent();var l=getHtml(gEdit.ids);var g='<div class="icomment-edit-header">'+l.headerContent+"</div>";var j='<div class="icomment-edit-body">'+l.bodyContent+"</div>";gEditICommentHost.overlay.setStdModContent(CY.WidgetStdMod.HEADER,CY.Node.create(g),CY.WidgetStdMod.AFTER);gEditICommentHost.overlay.setStdModContent(CY.WidgetStdMod.BODY,CY.Node.create(j),CY.WidgetStdMod.AFTER);CY.get("#"+gEdit.ids.formTitleId).set("innerHTML",gettext("Edit comment"));var i=gDb.getComment(gEditICommentHost.commentId);CY.get("#"+gEdit.ids.editCommentId).set("value",i.id);CY.get("#"+gEdit.ids.keyId).set("value",i.key);CY.get("#"+gEdit.ids.changeScopeInputId+" input").set("checked",false);if(i.reply_to_id!=null){CY.get("#"+gEdit.ids.changeScopeInputId).addClass("displaynone");}changeScopeFormClick();CY.get("#"+gEdit.ids.nameInputId).set("value",i.name);CY.get("#"+gEdit.ids.emailInputId).set("value",i.email);if(i.logged_author){CY.get("#"+gEdit.ids.nameInputId).setAttribute("disabled",true);CY.get("#"+gEdit.ids.emailInputId).setAttribute("disabled",true);}CY.get("#"+gEdit.ids.titleInputId).set("value",i.title);CY.get("#"+gEdit.ids.contentInputId).set("value",i.content);CY.get("#"+gEdit.ids.tagsInputId).set("value",i.tags);CY.get("#"+gEdit.ids.formatInputId).set("value",gConf.defaultCommentFormat);var k=gLayout.getTopICommentsWidth();changeFormFieldsWidth(gEdit.ids.formId,k);gEdit.handlers.addBtnId=CY.on("click",onEditSaveClick,"#"+gEdit.ids.addBtnId);gEdit.handlers.cancelBtnId=CY.on("click",onEditCancelClick,"#"+gEdit.ids.cancelBtnId);gEdit.handlers.changeScope=CY.on("click",onChangeScopeClick,"#"+gEdit.ids.changeScopeInputId);};onEditSaveClick=function(b){if(readyForAction()){gSync.editComment();}};onEditCancelClick=function(b){if(readyForAction()){gSync.cancelEdit();}};onChangeScopeClick=function(){if(readyForAction()){gSync.changeScopeFormClick();}else{var d=CY.get("#"+gEdit.ids.changeScopeInputId+" input");var c=d.get("checked");d.set("checked",!c);}};changeScopeFormClick=function(){var b=CY.get("#"+gEdit.ids.currentSelId);if(CY.get("#"+gEdit.ids.changeScopeInputId+" input").get("checked")){b.removeClass("displaynone");}else{b.addClass("displaynone");}};cancelEditForm=function(){if(gEditICommentHost!=null){for(var c in gEdit.handlers){if(gEdit.handlers[c]!=null){gEdit.handlers[c].detach();gEdit.handlers[c]=null;}}var d=gEditICommentHost.overlay.get("contentBox").query(".icomment-edit-body");d.get("parentNode").removeChild(d);d=gEditICommentHost.overlay.get("contentBox").query(".icomment-edit-header");d.get("parentNode").removeChild(d);gEditICommentHost.showContent();gEditICommentHost=null;}};var gtest={renaud:"RENAUD",random:Math.random(),bernard:"BERNARD",myFunc:function(){doExchange("theServerFun",{},null,this.myRetFunc,this,["foo","bar"]);},myRetFunc:function(b){CY.log("this.renaud : "+this.renaud);CY.log("this.random : "+this.random);CY.log("arg.returned : "+b.returned);CY.log(b.returned);CY.log("arg.success : "+b.success);CY.log(b.success);}};doExchange=function(k,n,l,m,o,p,i){n.fun=k;n.key=sv_key;n.version_key=sv_version_key;var j={method:"POST",data:urlEncode(n),on:{success:function(a,b,c){var d={};if(b.responseText){d=CY.JSON.parse(b.responseText);}if(gLayout.isInFrame()&&("msg" in d)){parent.f_enqueueMsg(d.msg);}c.returned=d;c.successfull=true;m.call(o,c);},failure:function(a,b,c){if(gLayout.isInFrame()){parent.f_enqueueErrorMsg(gettext("error:")+i);}c.successfull=false;m.call(o,c);}},arguments:{success:p,failure:p}};if(l!=null){j.form={id:l};}CY.io(sv_client_url,j);};warn_server=function(f){f.fun="warn";f.key=sv_key;f.version_key=sv_version_key;var d=CY.UA;var e={method:"POST",data:urlEncode(CY.merge(f,d))};CY.io("/client/",e);};paintCommentScope=function(c){if(c.reply_to_id==null&&c.start_wrapper!=-1){var d={start:{elt:document.getElementById("sv_"+c.start_wrapper),offset:c.start_offset},end:{elt:document.getElementById("sv_"+c.end_wrapper),offset:c.end_offset}};if(document.getElementById("sv_"+c.start_wrapper)==null){warn_server({from:"paintCommentScope",start_wrapper:c.start_wrapper});}else{if(document.getElementById("sv_"+c.end_wrapper)==null){warn_server({from:"paintCommentScope",end_wrapper:c.end_wrapper});}else{d.start=_convertSelectionFromCSToCC(d.start);d.end=_convertSelectionFromCSToCC(d.end);renderComment(d,c.id);}}}};getCommentIdsFromClasses=function(f){var g=[];var h=f.className.split(" ");for(var i=0,j=h.length;i<j;i++){if(h[i].indexOf("c-id-")==0){g.push(parseInt(h[i].substring("c-id-".length)));}}return g;};renderComment=function(k,l){var h=k.start.offset;var g=k.end.offset;var i=k.start.elt;var j=k.end.elt;if((i!=null)&&(j!=null)&&_getTextNodeContent(i)!=""&&_getTextNodeContent(j)!=""){markWholeNodesAsComments(i,j,l);markEndsAsComments(i,h,j,g,l);}};markWholeNodesAsComments=function(g,h,e){var f=_findCommonAncestor(g,h);_dynSpanToAnc(g,f,e,false);_dynSpanToAnc(h,f,e,true);_dynSpanInBetween(f,g,h,e);};_setTextNodeContent=function(d,c){CY.DOM.setText(d,c);};_getTextNodeContent=function(b){return CY.DOM.getText(b);};markEndsAsComments=function(C,x,u,w,y){var s=_getTextNodeContent(C).substring(0,x);var r=_getTextNodeContent(C).substring(x);var q=_getTextNodeContent(u).substring(0,w);var z=_getTextNodeContent(u).substring(w);var E=(C===u);if(r!=""){if(CY.DOM.hasClass(C,"c-c")){var A=null,v=null,D=null,F=null;var t=(E)?_getTextNodeContent(C).substring(x,w):r;if(E&&(z!="")){D=C;A=D;}if(t!=""){if(A==null){v=C;}else{v=_yuiCloneNode(C);A.parentNode.insertBefore(v,A);}A=v;}if(s!=""){if(A==null){F=C;}else{F=_yuiCloneNode(C);A.parentNode.insertBefore(F,A);}A=F;}if(D!=null){_setTextNodeContent(D,z);}if(v!=null){_setTextNodeContent(v,t);_addIdClass(v,y);}if(F!=null){_setTextNodeContent(F,s);}}}if((!E)&&(q!="")){if(CY.DOM.hasClass(u,"c-c")){var A=null,B=null,D=null;if(z!=""){D=u;A=u;}if(q!=""){if(A==null){B=u;}else{B=_yuiCloneNode(u);A.parentNode.insertBefore(B,A);}A=B;}if(D!=null){_setTextNodeContent(D,z);}if(B!=null){_addIdClass(B,y);_setTextNodeContent(B,q);}}}};_yuiCloneNode=function(c){var d=CY.Node.getDOMNode(CY.get("#"+c.id).cloneNode(true));d.id=CY.guid();return d;};_dynSpanToAnc=function(h,k,l,j){var i=h;while((i!=null)&&(i!==k)&&(i.parentNode!==k)){var c=null;if(j){c=i.previousSibling;}else{c=i.nextSibling;}if(c==null){i=i.parentNode;}else{i=c;_recAddComment(i,l);}}};_dynSpanInBetween=function(j,i,k,m){var a=i;var l=null;while(a){if(a.parentNode===j){l=a;break;}a=a.parentNode;}if(l!=null){a=k;var n=null;while(a){if(a.parentNode===j){n=a;break;}a=a.parentNode;}if(n!=null){a=l.nextSibling;while((a!=null)&&(a!==n)){_recAddComment(a,m);a=a.nextSibling;}}}};_bruteContains=function(d,c){while(c){if(d===c){return true;}c=c.parentNode;}return false;},_addIdClass=function(d,c){CY.DOM.addClass(d,"c-id-"+c);_updateCommentCounter(d);};_removeIdClass=function(d,c){CY.DOM.removeClass(d,"c-id-"+c);_updateCommentCounter(d);};_removeIdClasses=function(d){var c=_cgetRegExp("(?:^|\\s+)c-id-(?:\\d+)","g");d.className=d.className.replace(c," ");_updateCommentCounter(d);};_recAddComment=function(e,c){if(CY.DOM.hasClass(e,"c-c")){_addIdClass(e,c);}else{var f=e.firstChild;while(f!=null){_recAddComment(f,c);f=f.nextSibling;}}};_findCommonAncestor=function(f,e){if(_bruteContains(f,e)){return f;}else{var d=e;while((d!=null)&&!_bruteContains(d,f)){d=d.parentNode;}return d;}};_cregexCache={};_cgetRegExp=function(c,d){d=d||"";if(!_cregexCache[c+d]){_cregexCache[c+d]=new RegExp(c,d);}return _cregexCache[c+d];};_updateCommentCounter=function(e){var h=_cgetRegExp("(?:^|\\s+)c-id-(?:\\d+)","g");var g=e.className.match(h);var f=(g==null)?0:g.length;h=_cgetRegExp("(?:^|\\s+)c-count-(?:\\d+)","g");e.className=e.className.replace(h," ");CY.DOM.addClass(e,"c-count-"+f+" ");};_convertSelectionFromCCToCS=function(e){var g=e.offset;var f=e.elt.parentNode;var h=e.elt.previousSibling;while(h!=null){g+=_getTextNodeContent(h).length;h=h.previousSibling;}return{elt:f,offset:g};};_convertSelectionFromCSToCC=function(k){var h={elt:null,offset:-1};var i=null;var j=k.elt.firstChild;var l=0;while(j!=null){var g=l;l+=_getTextNodeContent(j).length;if(l>=k.offset){h.elt=j;h.offset=k.offset-g;break;}j=j.nextSibling;}return h;};unpaintCommentScope=function(v){var w=v.id;var c="c-id-"+w;var p=[];var E=CY.all("."+c);if(E!=null){for(var x=0,B=E.size();x<B;x++){var i=E.item(x);if(i.hasClass("c-c")){var u=CY.Node.getDOMNode(i);_removeIdClass(u,w);var z=getCommentIdsFromClasses(u);quicksort(z);var D=i.get("previousSibling");if(D!=null){var C=CY.Node.getDOMNode(D);var F=getCommentIdsFromClasses(C);quicksort(F);if(areSortedArraysEqual(z,F)){_setTextNodeContent(u,_getTextNodeContent(C)+_getTextNodeContent(u));p.push(C);}}var A=i.get("nextSibling");if(A!=null){var n=CY.Node.getDOMNode(A);var y=getCommentIdsFromClasses(n);quicksort(y);if(areSortedArraysEqual(z,y)){u.firstChild.data=u.firstChild.data+n.firstChild.data;p.push(n);}}}else{alert("HAS NO c-c ? : "+commentNode.get("id")+" , innerHTML :"+commentNode.get("innerHTML"));return;}}}for(var x=0,B=p.length;x<B;x++){p[x].parentNode.removeChild(p[x]);}};unpaintAllComments=function(){var c=CY.all(".c-s");var n=[];for(var o=0,r=c.size();o<r;o++){var l=c.item(o);var p=l.get("firstChild");var i=CY.Node.getDOMNode(l.get("firstChild"));_removeIdClasses(i);var q=p.get("nextSibling");while(q!=null){var m=CY.Node.getDOMNode(q);i.firstChild.data=i.firstChild.data+m.firstChild.data;n.push(m);q=q.get("nextSibling");}}for(var o=0,r=n.length;o<r;o++){n[o].parentNode.removeChild(n[o]);}};showScope=function(c){var d=CY.all(".c-id-"+c);if(d!=null){d.addClass("c-scope");}};hideScopeAnyway=function(){var b=CY.all(".c-scope");if(b!=null){b.removeClass("c-scope");}};gNewReplyHost=null;gNewReply=null;instanciateNewReplyForm=function(i){if(gNewReply==null){gNewReply={val:{name:gPrefs.get("user","name"),email:gPrefs.get("user","email"),title:"",content:"",tags:""},ids:{name:gPrefs.get("user","name"),email:gPrefs.get("user","email"),title:"",content:"",tags:"",formId:CY.guid(),nameInputId:CY.guid(),emailInputId:CY.guid(),titleInputId:CY.guid(),contentInputId:CY.guid(),keyInputId:CY.guid(),formatInputId:CY.guid(),tagsInputId:CY.guid(),parentCommentId:CY.guid(),addBtnId:CY.guid(),cancelBtnId:CY.guid()},handlers:{}};}gNewReplyHost=i;var b='<hr/><center><div class="c-header-title">'+gettext("New reply")+"</div></center>";var e=gFormHtml.formStart.replace("###",gNewReply.ids["formId"]);if(!sv_loggedIn){e=e+gFormHtml.nameInput.replace("###",gNewReply.ids["nameInputId"])+gFormHtml.emailInput.replace("###",gNewReply.ids["emailInputId"]);}e=e+gFormHtml.titleInput.replace("###",gNewReply.ids["titleInputId"])+gFormHtml.contentInput.replace("###",gNewReply.ids["contentInputId"])+gFormHtml.tagsInput.replace("###",gNewReply.ids["tagsInputId"]);e=e+gFormHtml.hidden.replace("###",gNewReply.ids["keyInputId"]).replace("???","comment_key");e=e+gFormHtml.hidden.replace("###",gNewReply.ids["formatInputId"]).replace("???","format");e=e+gFormHtml.hidden.replace("###",gNewReply.ids["parentCommentId"]).replace("???","reply_to_id");var h=gFormHtml.btns.replace("###",gNewReply.ids["addBtnId"]).replace("???",gNewReply.ids["cancelBtnId"]);gNewReplyHost.overlay.setStdModContent(CY.WidgetStdMod.FOOTER,b+e+h);var c=gNewReplyHost.overlay.getStdModNode(CY.WidgetStdMod.FOOTER);var f=gDb.getComment(i.commentId);var a="Re: ";var g=(gNewReply.val["title"]==""||gNewReply.val["title"].substring(0,a.length)==a)?a+f.title:gNewReply.val["title"];if(!sv_loggedIn){c.query(".n_name").set("value",gNewReply.val["name"]);c.query(".n_email").set("value",gNewReply.val["email"]);}c.query(".n_title").set("value",g);c.query(".n_content").set("value",gNewReply.val["content"]);c.query(".n_tags").set("value",gNewReply.val["tags"]);c.query("#"+gNewReply.ids["parentCommentId"]).set("value",i.commentId);c.query("#"+gNewReply.ids["formatInputId"]).set("value",gConf.defaultCommentFormat);gNewReplyHost.overlay.get("contentBox").query(".c-reply").addClass("displaynone");gNewReply.handlers["addBtnId"]=CY.on("click",onAddNewReplyClick,"#"+gNewReply.ids["addBtnId"]);gNewReply.handlers["cancelBtnId"]=CY.on("click",onCancelNewReplyClick,"#"+gNewReply.ids["cancelBtnId"]);var d=gLayout.getTopICommentsWidth();changeFormFieldsWidth(gNewReply.ids["formId"],d);};cleanNewReplyForm=function(){if(gNewReplyHost!=null){var a=gNewReplyHost.overlay.getStdModNode(CY.WidgetStdMod.FOOTER);a.queryAll(".comment_input").set("value","");}};cancelNewReplyForm=function(){if(gNewReplyHost!=null){for(var b in gNewReply.handlers){if(gNewReply.handlers[b]!=null){gNewReply.handlers[b].detach();gNewReply.handlers[b]=null;}}gNewReplyHost.overlay.get("contentBox").query(".c-reply").removeClass("displaynone");var a=gNewReplyHost.overlay.getStdModNode(CY.WidgetStdMod.FOOTER);if(!sv_loggedIn){gNewReply.val["name"]=a.query(".n_name").get("value");gNewReply.val["email"]=a.query(".n_email").get("value");}gNewReply.val["title"]=a.query(".n_title").get("value");gNewReply.val["content"]=a.query(".n_content").get("value");gNewReply.val["tags"]=a.query(".n_tags").get("value");a.set("innerHTML","");gNewReplyHost=null;}};onAddNewReplyClick=function(){if(!sv_loggedIn){var b=CY.get("#"+gNewReply.ids["nameInputId"]).get("value");gPrefs.persist("user","name",b);var a=CY.get("#"+gNewReply.ids["emailInputId"]).get("value");gPrefs.persist("user","email",a);}gSync.saveComment(gNewReply.ids["formId"]);};onCancelNewReplyClick=function(){gSync.cancelReply();};_changeIds=function(a,b){if(a.id){a.id=a.id+b;}var d=a.firstChild;while(d!=null){_changeIds(d,b);d=d.nextSibling;}};suffix=0;domDuplicate=function(a){var b=a.cloneNode(true);suffix++;_changeIds(b,"-"+suffix);return b;};getDuplicated=function(a){return document.getElementById(a.id+"-"+suffix);};logSel=function(a){log("text :"+a.text+", start id : "+a.start["elt"].id+" , start offset : "+a.start["offset"]+" , end id : "+a.end["elt"].id+"end offset : "+a.end["offset"]);};log=function(b){var a=document.getElementById("log");a.innerHTML=a.innerHTML+"<li>"+b+"</li>";};urlEncode=function(h){if(!h){return"";}var c=[];for(var f in h){var e=h[f],b=encodeURIComponent(f);var g=typeof e;if(g=="undefined"){c.push(b,"=&");}else{if(g!="function"&&g!="object"){c.push(b,"=",encodeURIComponent(e),"&");}else{if(CY.Lang.isArray(e)){if(e.length){for(var d=0,a=e.length;d<a;d++){c.push(b,"=",encodeURIComponent(e[d]===undefined?"":e[d]),"&");}}else{c.push(b,"=&");}}}}}c.pop();return c.join("");};urlDecode=function(f,h){if(!f||!f.length){return{};}var d={};var b=f.split("&");var c,a,j;for(var e=0,g=b.length;e<g;e++){c=b[e].split("=");a=decodeURIComponent(c[0]);j=decodeURIComponent(c[1]);if(h!==true){if(typeof d[a]=="undefined"){d[a]=j;}else{if(typeof d[a]=="string"){d[a]=[d[a]];d[a].push(j);}else{d[a].push(j);}}}else{d[a]=j;}}return d;};areSortedArraysEqual=function(b,a){if(b.length!=a.length){return false;}for(var d=0,c=b.length;d<c;d++){if(b[d]!=a[d]){return false;}}return true;};quicksort=function(a){_quicksort(a,0,a.length-1);};_quicksort=function(e,g,d){var a,c,f,b;if(d-g==1){if(e[g]>e[d]){b=e[g];e[g]=e[d];e[d]=b;}return;}a=e[parseInt((g+d)/2)];e[parseInt((g+d)/2)]=e[g];e[g]=a;c=g+1;f=d;do{while(c<=f&&e[c]<=a){c++;}while(e[f]>a){f--;}if(c<f){b=e[c];e[c]=e[f];e[f]=b;}}while(c<f);e[g]=e[f];e[f]=a;if(g<f-1){_quicksort(e,g,f-1);}if(f+1<d){_quicksort(e,f+1,d);}};IComments=function(){this._c=[];this._a=[];this._nbEndedAnim=0;this._topActiveCommentDbId=null;};IComments.prototype={init:function(a){for(var b=0;b<gConf.iCommentsInitAlloc;b++){this._c.push(new IComment());}},getIComment:function(a){return CY.Array.find(this._c,function(b){return(b.isfetched()&&b.commentId==a);});},insertAfter:function(a,d){var c=CY.Array.map(this._c,function(e){return e.commentId;});var b=CY.Array.indexOf(c,a.id);if(b!=-1){this._c.splice(b+1,0,new IComment());this._c[b+1].fetch(d);return this._c[b+1];}return null;},_remove:function(c){var d=CY.Array.map(c,function(e){return e.commentId;});for(var b=0;b<this._c.length;b++){var a=this._c[b];if(a.isfetched()&&CY.Array.indexOf(d,a.commentId)!=-1){a.unfetch();this._c.push(this._c.splice(b,1)[0]);b--;}}},_getChildren:function(a){return CY.Array.filter(this._c,function(b){return(b.isfetched()&&gDb.isChild(b.commentId,a));});},_getInvisibleChildren:function(a){return CY.Array.filter(this._getChildren(a),function(b){return(!b.isVisible());});},refresh:function(c){var b=this.getIComment(c);var a=this._getInvisibleChildren(c);if(a.length>0){b.showReadRepliesLnk();}else{b.hideReadRepliesLnk();}},remove:function(a){this._remove(this._getChildren(a));},close:function(a){CY.Array.each(this._getChildren(a),function(b){b.hide();});},open:function(a){CY.Array.each(this._getChildren(a),function(b){b.show();});},fetch:function(b){for(var a=0;a<b.length;a++){if(a==this._c.length){this._c.push(new IComment());}this._c[a].fetch(b[a]);}for(var a=b.length;a<this._c.length;a++){this._c[a].unfetch();}},setPosition:function(a){CY.each(this._c,function(b){b.setPosition(a);});},show:function(){CY.each(this._c,function(a){if(a.isfetched()){a.show();}});},hide:function(){this.deactivate();CY.each(this._c,function(a){if(a.commentId!=null){a.hide();}});},setWidth:function(c){var e=null;for(var b=0;b<this._c.length;b++){var a=this._c[b];a.setWidth(c);if(a.commentId!=null&&a.isVisible()){var d=a.getPosition();if(e==null){e=d[1];}d[1]=e;a.setPosition(d);e+=a.getHeight();}}},getTopPosition:function(){for(var b=0;b<this._c.length;b++){var a=this._c[b];if(a.commentId!=null&&a.isVisible()){return a.getPosition();}}return null;},getPosition:function(c){for(var b=0;b<this._c.length;b++){var a=this._c[b];if(a.commentId==c&&a.isVisible()){return a.getPosition();}}return null;},setAnimationToPositions:function(h){this._initAnimations();var c=(gPrefs.get("comments","threadpad")=="1")?gConf.iCommentThreadPadding:0;var f=h;for(var d=0;d<this._c.length;d++){var b=this._c[d];if(b.isfetched&&b.isVisible()){var a=gDb.getPath(gDb.getComment(b.commentId));var g=((a.length-1)*c)+gConf.iCommentLeftPadding;if(f==null){var e=b.getPosition();f=e[1];}this._a.push(b.setAnimationToPosition([g,f]));f+=b.getHeight();}}},_initAnimations:function(){this._a=[];this._nbEndedAnim=0;},runAnimations:function(){if(this._a.length==0){gSync.resetAutoContinue("animationRun");}else{CY.each(this._a,function(a){a.run();});}},whenAnimationsEnd:function(){gSync.resume();},animationsEnded:function(){return((this._a.length==0)||(this._a.length==this._nbEndedAnim));},signalAnimationEnd:function(){this._nbEndedAnim++;},isTopActive:function(a){return((a!=null)&&(this._topActiveCommentDbId==a));},isAnyActive:function(){return(this._topActiveCommentDbId!=null);},activate:function(f){if(this._topActiveCommentDbId!=null){this.deactivate();}var e=gDb.getComment(f);var b=gDb.getPath(e);var a=b[b.length-1];var c=this._getChildren(a.id);CY.Array.each(c,function(g){g.activate();});this._topActiveCommentDbId=a.id;if(gLayout.isInFrame()){var d=gDb.browsingIndex(this._topActiveCommentDbId);parent.$("#browse_by option").each(function(){var g=1+d[this.value];parent.$("#c_browse_indx_"+this.value).html(""+g);});}showScope(a.id);},deactivate:function(){if(this._topActiveCommentDbId!=null){parent.$("#browse_by option").each(function(){parent.$("#c_browse_indx_"+this.value).html("-");});hideScopeAnyway();var a=this._getChildren(this._topActiveCommentDbId);CY.Array.each(a,function(b){b.deactivate();});this._topActiveCommentDbId=null;}},activateVisibleNext:function(){if(this._topActiveCommentDbId!=null){for(var d=0;d<2;d++){var f=(d==0)?0:this._c.length-1;var a=false;for(var e=f;(e>=0)&&e<=(this._c.length-1);){var c=this._c[e];if(c.commentId!=null&&c.isVisible()){a=a||(gDb.isChild(c.commentId,this._topActiveCommentDbId));if(a&&(!gDb.isChild(c.commentId,this._topActiveCommentDbId))){this.activate(c.commentId);return true;}}e=(d==0)?e+1:e-1;}}}return false;},browse:function(b,c){var a=c;if((c=="prev")&&!this.isAnyActive()){a="last";}if((c=="next")&&!this.isAnyActive()){a="first";}return gDb.browse(b,a,this._topActiveCommentDbId);}};_afterDlg=function(d){var a=d[0];var c=d[1];var b=d[2];a.call(c,b);};_abortNewCommentConfirmed=function(a){if(isICommentFormVisible()){if(gLayout.isInFrame()){gSync.hideICommentForm({fn:function(){_afterDlg(a);}});gSync.resume();}}};_abortNewReplyConfirmed=function(a){if(gNewReplyHost!=null){if(gLayout.isInFrame()){cancelNewReplyForm();_afterDlg(a);}}};_abortNewEditConfirmed=function(a){if(gEditICommentHost!=null){if(gLayout.isInFrame()){cancelEditForm();_afterDlg(a);}}};checkForOpenedDialog=function(e,b,d,c){var a=[];if(e!=null){a=CY.Array.map(gDb.getThreads([gDb.getComment(e.commentId)]),function(f){return f.id;});}if(isICommentFormVisible()||(gNewReplyHost!=null&&(e==null||CY.Array.indexOf(a,gNewReplyHost.commentId)!=-1))||(gEditICommentHost!=null&&(e==null||CY.Array.indexOf(a,gEditICommentHost.commentId)!=-1))){if(gLayout.isInFrame()){if(isICommentFormVisible()){parent.f_yesNoDialog(gettext("New comment will be canceled, continue?"),gettext("Warning"),null,null,null,_abortNewCommentConfirmed,this,[b,d,c]);}else{if(gNewReplyHost!=null){parent.f_yesNoDialog(gettext("Started reply will be canceled, continue?"),gettext("Warning"),null,null,null,_abortNewReplyConfirmed,this,[b,d,c]);}else{if(gEditICommentHost!=null){parent.f_yesNoDialog(gettext("Started comment edition will be canceled, continue?"),gettext("Warning"),null,null,null,_abortNewEditConfirmed,this,[b,d,c]);}}}}}else{b.call(d,[]);}};gNoSelectionYet=gettext("No selection yet");gFormHtml={formStart:'<form id="###" onsubmit="return false;">',nameInput:gettext("Username:")+'<center><input id="###" name="name" class="n_name user_input" style="padding:1px;" type="text"></input></center>',emailInput:gettext("E-mail address:")+'<center><input id="###" name="email" class="n_email user_input" style="padding:1px;" type="text"></input></center>',titleInput:gettext("Title:")+'<center><input id="###" name="title" class="n_title comment_input" style="padding:1px;" type="text"></input></center>',contentInput:gettext("Content:")+'<center><textarea id="###" name="content" class="n_content comment_input" rows="10" style="padding:1px;"></textarea></center>',tagsInput:gettext("Tag:")+'<center><input id="###" name="tags" class="n_tags comment_input" style="padding:1px;" type="text"></input></center>',hidden:'<input id="###" class="comment_input" name="???" type="hidden" value=""></input>',formEnd:"</form>",changeScope:'<div id="###">'+gettext("Modify comment's scope:")+'<input type="checkbox" name="change_scope"></input></div>',headerTitle:'<center><div id="###" class="c-header-title"></div></center>',currentSel:'<div id="###">'+gettext("Comment will apply to this selection:")+'<br/><div class="current_sel"><div id="???" class="current_sel_ins">'+gNoSelectionYet+"</div></div>#hiddeninput#</div>",btns:'<center><input id="###" type="button" value="'+gettext("Save")+'" /><input id="???" type="button" value="'+gettext("Cancel")+'" /></center>',closeIcon:'<a id="###" class="c-close" title="'+gettext("close")+'"><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</em></a>'};getHtml=function(f){ret={};ret.headerContent="";if("closeBtnId" in f){ret.headerContent+=gFormHtml.closeIcon.replace("###",f.closeBtnId);}ret.headerContent+=gFormHtml.headerTitle.replace("###",f.formTitleId);var b="";if("changeScopeInputId" in f){b=gFormHtml.changeScope.replace("###",f.changeScopeInputId);}var e="<center>"+gFormHtml.hidden.replace("###",f.selectionPlaceId).replace("???","selection_place")+"</center>";var a=gFormHtml.currentSel.replace("###",f.currentSelId).replace("???",f.currentSelIdI).replace("#hiddeninput#",e);var d=gFormHtml.btns.replace("###",f.addBtnId).replace("???",f.cancelBtnId);var c=gFormHtml.formStart.replace("###",f.formId)+b+a;if("nameInputId" in f){c=c+gFormHtml.nameInput.replace("###",f.nameInputId);}if("emailInputId" in f){c=c+gFormHtml.emailInput.replace("###",f.emailInputId);}c=c+gFormHtml.titleInput.replace("###",f.titleInputId)+gFormHtml.contentInput.replace("###",f.contentInputId)+gFormHtml.tagsInput.replace("###",f.tagsInputId);c=c+gFormHtml.hidden.replace("###",f.formatInputId).replace("???","format");c=c+gFormHtml.hidden.replace("###",f.startWrapperInputId).replace("???","start_wrapper");c=c+gFormHtml.hidden.replace("###",f.endWrapperInputId).replace("???","end_wrapper");c=c+gFormHtml.hidden.replace("###",f.startOffsetInputId).replace("???","start_offset");c=c+gFormHtml.hidden.replace("###",f.endOffsetInputId).replace("???","end_offset");c=c+gFormHtml.hidden.replace("###",f.keyId).replace("???","comment_key");c=c+gFormHtml.hidden.replace("###",f.editCommentId).replace("???","edit_comment_id");c=c+d+gFormHtml.formEnd;ret.bodyContent=c;return ret;};changeFormFieldsWidth=function(d,c){var a=(c-20)+"px";var b=CY.all("#"+d+" input[type='text']");if(b!=null){b.setStyle("width",a);}b=CY.all("#"+d+" textarea");if(b!=null){b.setStyle("width",a);}};addFormErrMsg=function(j,g,d){var f=document.getElementById(j);var b,h,c,a;for(b=0,a=f.elements.length;b<a;++b){h=f.elements[b];if(h.name==g){c=document.createElement("DIV");CY.DOM.addClass(c,"c-error");c.id=h.id+"-err";c.appendChild(document.createTextNode(d));if(h.parentNode.nextSibling){h.parentNode.parentNode.insertBefore(c,h.parentNode.nextSibling);}else{h.parentNode.parentNode.appendChild(c);}}}};removeFormErrMsg=function(b){var a=CY.all("#"+b+" .c-error");if(a!=null){a.each(function(c){c.get("parentNode").removeChild(c);});}};gICommentForm=null;instanciateICommentForm=function(){gICommentForm={position:[CY.WidgetPositionExt.LC,CY.WidgetPositionExt.LC],formId:CY.guid(),formTitleId:CY.guid(),titleInputId:CY.guid(),contentInputId:CY.guid(),tagsInputId:CY.guid(),formatInputId:CY.guid(),startWrapperInputId:CY.guid(),endWrapperInputId:CY.guid(),startOffsetInputId:CY.guid(),endOffsetInputId:CY.guid(),selectionPlaceId:CY.guid(),keyId:CY.guid(),currentSelId:CY.guid(),currentSelIdI:CY.guid(),addBtnId:CY.guid(),cancelBtnId:CY.guid(),closeBtnId:CY.guid()};if(!sv_loggedIn){gICommentForm.nameInputId=CY.guid();gICommentForm.emailInputId=CY.guid();}var c=getHtml(gICommentForm);var e=gLayout.getTopICommentsWidth();var b=new CY.Overlay({zIndex:3,shim:false,visible:false,headerContent:c.headerContent,bodyContent:c.bodyContent,xy:[10,10],width:e});b.get("contentBox").addClass("c-newcomment");b.render("#leftcolumn");if(!sv_loggedIn){CY.get("#"+gICommentForm.nameInputId).set("value",gPrefs.get("user","name"));CY.get("#"+gICommentForm.emailInputId).set("value",gPrefs.get("user","email"));}CY.get("#"+gICommentForm.formTitleId).set("innerHTML",gettext("New comment"));CY.get("#"+gICommentForm.formatInputId).set("value",gConf.defaultCommentFormat);CY.on("click",onSubmitICommentFormClick,"#"+gICommentForm.addBtnId);CY.on("click",onCancelICommentFormClick,"#"+gICommentForm.cancelBtnId);CY.on("click",onCancelICommentFormClick,"#"+gICommentForm.closeBtnId);gICommentForm.overlay=b;var d=null;d=new CY.Anim({node:b.get("boundingBox"),duration:0.3,easing:CY.Easing.easeOut});gICommentForm.animationHide=d;d.set("to",{opacity:0});gICommentForm["animationHide-handle"]=d.on("end",onICommentFormHideAnimEnd,gICommentForm);var a=null;a=new CY.Anim({node:b.get("boundingBox"),duration:0.3,easing:CY.Easing.easeOut});gICommentForm.animationShow=a;a.set("to",{opacity:1});gICommentForm["animationShow-handle"]=a.on("end",onICommentFormShowAnimEnd,gICommentForm);changeFormFieldsWidth(gICommentForm.formId,e);};cleanICommentForm=function(){CY.get("#"+gICommentForm.currentSelIdI).set("innerHTML",gNoSelectionYet);var a=gICommentForm.overlay.getStdModNode(CY.WidgetStdMod.BODY);a.queryAll(".comment_input").set("value","");CY.get("#"+gICommentForm.formatInputId).set("value",gConf.defaultCommentFormat);if(!sv_loggedIn){a.queryAll(".user_input").set("value","");}};onICommentFormHideAnimEnd=function(){this.overlay.hide();gSync.resume();};onICommentFormShowAnimEnd=function(){gSync.resume();};onSubmitICommentFormClick=function(){if(!sv_loggedIn){var b=CY.get("#"+gICommentForm.nameInputId).get("value");gPrefs.persist("user","name",b);var a=CY.get("#"+gICommentForm.emailInputId).get("value");gPrefs.persist("user","email",a);}gSync.saveComment(gICommentForm.formId);};onCancelICommentFormClick=function(){gSync.cancelICommentForm();};_updateICommentFormSelection=function(c,e,b,a){var d=CY.Node.get("#"+c.currentSelIdI);if(d!=null){d.set("innerHTML",e);}d=CY.get("#"+c.startWrapperInputId);if(d!=null){d.set("value",b.elt.id.substring("sv_".length));}d=CY.get("#"+c.startOffsetInputId);if(d!=null){d.set("value",b.offset);}d=CY.get("#"+c.endWrapperInputId);if(d!=null){d.set("value",a.elt.id.substring("sv_".length));}d=CY.get("#"+c.endOffsetInputId);if(d!=null){d.set("value",a.offset);}};updateICommentFormSelection=function(h){var i=(h==null)?"":h.text;if(i!=""){var f=i;var b=100;if(i.length>b){var a=i.substring(0,(i.substring(0,b/2)).lastIndexOf(" "));var d=i.substring(i.length-b/2);var c=d.substring(d.indexOf(" "));f=a+" ... "+c;}var e=_convertSelectionFromCCToCS(h.start);var g=_convertSelectionFromCCToCS(h.end);_updateICommentFormSelection(gICommentForm,f,e,g);if(gEdit!=null){_updateICommentFormSelection(gEdit.ids,f,e,g);}positionICommentForm();}};showICommentForm=function(){removeFormErrMsg(gICommentForm.formId);if(!sv_loggedIn){if(CY.get("#"+gICommentForm.nameInputId).get("value")==""){CY.get("#"+gICommentForm.nameInputId).set("value",gPrefs.get("user","name"));}if(CY.get("#"+gICommentForm.emailInputId).get("value")==""){CY.get("#"+gICommentForm.emailInputId).set("value",gPrefs.get("user","email"));}}gIComments.hide();positionICommentForm();gICommentForm.overlay.show();CY.get("#"+gICommentForm.titleInputId).focus();};isICommentFormVisible=function(){if(gICommentForm!=null){return gICommentForm.overlay.get("visible");}return false;};positionICommentForm=function(){if(gICommentForm!=null){var b=gICommentForm.overlay;var a=b.get("boundingBox");var c=a.get("offsetHeight");var e=a.get("winHeight");var d=gICommentForm.position;if(c>e){d=[CY.WidgetPositionExt.BL,CY.WidgetPositionExt.BL];}b.set("align",{points:d});a.setX(a.getX()+gConf.iCommentLeftPadding);}};c_persistPreference=function(b,a,c){gPrefs.persist(b,a,c);};c_readDefaultPreference=function(b,a){return gConf.defaultPrefs[b][a];};c_readPreference=function(b,a){return gPrefs.get(b,a);};c_resetPreferences=function(a){gPrefs.reset(a);};c_applyTextStyle=function(a){CY.use(a);};sliderValToPx=function(d){var a=CY.DOM.winWidth();if(gLayout.isInFrame()){a=parent.$(parent).width();}var b=d/100;b=Math.min(b,gConf.sliderFixedMin);b=Math.max(b,gConf.sliderFixedMax);var c=b*a;return Math.floor(c);};c_setCommentsColWidth=function(c){var a=sliderValToPx(c);gLayout.setLeftColumnWidth(a);var b=gLayout.getTopICommentsWidthFromWidth(a);gIComments.setWidth(b);gICommentForm.overlay.get("boundingBox").setStyle("width",b+"px");changeFormFieldsWidth(gICommentForm.formId,b);if(gNewReply){changeFormFieldsWidth(gNewReply.ids["formId"],b);}if(gEdit){changeFormFieldsWidth(gEdit.ids["formId"],b);}};CY=null;gPrefs=null;gLayout=null;gDb=null;gIComments=null;gSync=null;gGETValues=null;gConf={iCommentLeftPadding:4,iCommentThreadPadding:12,defaultCommentFormat:"markdown",sliderFixedMin:0.9,sliderFixedMax:0.1,iCommentsInitAlloc:2,defaultPrefs:{text:{style:"text-modern-style"},user:{name:"",email:""},general:{animduration:"0.4"},comments:{threadpad:"1"},layout:{comments_col_width:"25"}}};gTextStyles={"text-modern-style":gettext("modern"),"text-classic-style":gettext("classic"),"text-code-style":gettext("code")};YUI({base:sv_media_url+"/js/lib/yui/"+c_yui_base+"/build/",timeout:10000}).use("text-modern-style","cookie","json","overlay","io-form","async-queue","event-mouseenter","anim","collection",function(a){CY=a;gPrefs=new Preferences();gPrefs.init();gLayout=new Layout();gLayout.init();if(sv_withComments){gDb=new Db();gDb.init();gIComments=new IComments();gIComments.init();}gSync=new Sync();gSync.init();CY.on("domready",onDomReady,this);});_reinit=function(a){gIComments.hide();gDb.initComments(a.commentIds);unpaintAllComments();renderCommentScopes();updateFilterResultsCount(a.nbDiscussions,a.nbComments,a.nbReplies);};reinit=function(b){var a=gDb.computeFilterResults(b);_reinit(a);};hideAll=function(){_reinit({commentIds:[],nbDiscussions:0,nbComments:0,nbReplies:0});};updateFilterResultsCount=function(f,a,b){var e=gDb.getCommentsAndRepliesCounts(true);var g=e[0],d=e[1];var c=(a!=0||b!=0)&&(g!=a||d!=b);if(gLayout.isInFrame()){parent.f_updateFilterCountDetailed(c);parent.f_updateFilterCountResult(f,a,b,g,d);}};updateResetFilterResultsCount=function(){var c=gDb.getCommentsAndRepliesCounts(false);var a=c[0],b=c[1];var d=a;updateFilterResultsCount(d,a,b);};renderCommentScopes=function(){for(var a=0;a<gDb.comments.length;a++){var b=gDb.comments[a];paintCommentScope(b);}};onTextMouseUp=function(f){if(readyForAction()){var c=getSelectionInfo();if(c!=null){updateICommentFormSelection(c);if(gEditICommentHost!=null){var g=CY.get("#"+gEdit.ids["changeScopeInputId"]+" input").get("checked");if(g){gEditICommentHost.scrollIntoView();}}}else{var d=f.target;if(d.hasClass("c-c")){var b=CY.Node.getDOMNode(d);var a=getCommentIdsFromClasses(b);if(a.length>0){checkForOpenedDialog(null,function(){gSync.showComments(a,[f.pageX,f.pageY],false);});}}}}};gLastScrollTime=null;checkForAlignement=function(){var a=(new Date()).getTime();if((gLastScrollTime!=null)&&(a-gLastScrollTime)>200){positionICommentForm();gLastScrollTime=null;}};onFrameScroll=function(){gLastScrollTime=(new Date()).getTime();};browse=function(a,b){gSync.browse(a,b);};initialConnect=function(){CY.on("mouseup",onTextMouseUp,"#textcontainer");gTimer=CY.Lang.later(200,this,checkForAlignement,[],true);CY.on("scroll",onFrameScroll,window,this,true);CY.on("resize",onFrameScroll,window,this,true);};preventLinksInText=function(){var a=function(g){var c=g.target;var d=null;while(c!=null&&d==null){c=c.get("parentNode");d=c.get("href");}if(c!=null&&d!=null){var b=window.location.href;var f=b.indexOf("#");if(f!=-1){b=b.substring(0,f);}if(d.indexOf(b)==-1){window.open(c.get("href"));g.preventDefault();}}};CY.all("#textcontainer a").on("click",a);};onDomReady=function(b){preventLinksInText();var a=new CY.AsyncQueue();a.add({fn:function(){if(gLayout.isInComentSite()){parent.toInitialSize();}if(sv_withComments){instanciateICommentForm();}},timeout:5},{fn:function(){gGETValues=CY.JSON.parse(sv_get_params);CY.get("#maincontainer").setStyle("display","block");CY.get("#textcontainer").setStyle("display","block");var e=(sv_withComments)?gPrefs.get("layout","comments_col_width"):0;var d=sliderValToPx(e);gLayout.setLeftColumnWidth(d);if(gLayout.isInFrame()){parent.f_initFrame();parent.f_layoutFrames();if(sv_withComments){parent.f_fillTopToolbar();if(hasPerm("can_create_comment")){parent.$("#add_comment_btn").removeClass("initially_hidden");}parent.f_fillFilterTab();parent.f_fillPreferencesTab();var c=CY.JSON.parse(sv_filter_data);parent.f_updateFilterData(c);parent.f_setFilterValue(gGETValues);}parent.f_fillTextPreferencesTab();}if(gLayout.isInComentSite()){parent.$("#c_fullscreen_btn").show();}else{parent.$("#c_fullscreen_btn").hide();}},timeout:5},{fn:function(){if(sv_withComments){reinit(gGETValues);initialConnect();}},timeout:5},{fn:function(){if(gLayout.isInFrame()){parent.f_interfaceUnfreeze();parent.f_removeLoadingMsg();}if("comment_id_key" in gGETValues){var d=gGETValues.comment_id_key;var f=gDb.getCommentByIdKey(d);if(f!=null){var e=gDb.getPath(f);var c=e[e.length-1];gSync.showSingleComment(c);}}if("comments_auto_display" in gGETValues){gSync.showAllComments();}}});a.run();};
\ No newline at end of file
--- a/src/cm/media/js/client/c_icomment.js	Fri Jun 11 16:21:53 2010 +0200
+++ b/src/cm/media/js/client/c_icomment.js	Thu Jul 15 17:08:45 2010 +0200
@@ -198,13 +198,13 @@
 	},	
 	
 	onMouseEnterHeader : function () {
-		if (readyForAction() && this.isVisible()) {
+		if (readyForAction() && this.isVisible() && (sv_prefix=="")) {
 			this.overlay.get('contentBox').query(".c-permalink").removeClass('displaynone');
 		}
 	},
 	
 	onMouseLeaveHeader : function () {
-		if (readyForAction() && this.isVisible()) {
+		if (readyForAction() && this.isVisible() && (sv_prefix=="")) {
 			this.overlay.get('contentBox').query(".c-permalink").addClass('displaynone');
 		}
 	},	
@@ -302,7 +302,10 @@
 		
 		var modifDateTooltip = (comment.modified == comment.created) ? '' : '<a title="' + titleInfos + '"> * </a>' ;
 		var permaTitle = gettext('Permalink to this comment') ;
-		var permalink = '<a class="c-permalink displaynone c-action" target="_blank" title="'+ permaTitle +'" href="" >¶&nbsp;</a>' ;
+		var permalink = "";
+		if (sv_prefix=="") {
+			permalink = '<a class="c-permalink displaynone c-action" target="_blank" title="'+ permaTitle +'" href="" >¶&nbsp;</a>' ;
+		}
 		
 		var infos = interpolate(gettext('by %(name)s, created on %(date)s'),{'name':comment.name, 'date':comment.created_user_str}, true) ;
 		
@@ -335,7 +338,9 @@
 			prevContentNode.get('parentNode').replaceChild(newContentNode, prevContentNode) ;
 
 		// PERMALINK
-		boundingBoxNode.query(".c-permalink").set("href",sv_site_url + comment.permalink) ;
+		if (sv_prefix=="") {
+			boundingBoxNode.query(".c-permalink").set("href",sv_site_url + comment.permalink) ;
+		}
 
 		// MODERATION
 		this.changeModeration(comment) ;
--- a/src/cm/middleware.py	Fri Jun 11 16:21:53 2010 +0200
+++ b/src/cm/middleware.py	Thu Jul 15 17:08:45 2010 +0200
@@ -2,6 +2,7 @@
 from django.conf import settings
 from django.http import HttpResponseServerError,HttpResponseRedirect
 from django.core.urlresolvers import reverse
+from urllib import urlencode
 
 class CmMiddleware(object):
     
@@ -11,7 +12,8 @@
             traceback.print_exc()
         if type(exception) == UnauthorizedException:
             if request.user.is_anonymous():
-                login_url = reverse('login') + '?next=%s' %request.META['PATH_INFO']
+                query = urlencode({'next': request.META['PATH_INFO'], 'q' : request.META['QUERY_STRING'] })
+                login_url = reverse('login') + '?'  + query
                 return HttpResponseRedirect(login_url)
             else:
                 redirect_url = reverse('unauthorized')
--- a/src/cm/models.py	Fri Jun 11 16:21:53 2010 +0200
+++ b/src/cm/models.py	Thu Jul 15 17:08:45 2010 +0200
@@ -62,8 +62,14 @@
     def update_denorm_fields(self):
         real_last_text_version = self.fetch_latest_version()
     
+        try:
+            last_text_version = self.last_text_version
+        except TextVersion.DoesNotExist:
+            # the text version has just been deleted
+            last_text_version = None
+            
         modif = False
-        if real_last_text_version and real_last_text_version != self.last_text_version:
+        if real_last_text_version and real_last_text_version != last_text_version:
             self.last_text_version = real_last_text_version
             modif = True
             
--- a/src/cm/models_base.py	Fri Jun 11 16:21:53 2010 +0200
+++ b/src/cm/models_base.py	Thu Jul 15 17:08:45 2010 +0200
@@ -57,13 +57,17 @@
         abstract = True
     
     def get_name(self):
-        if self.user:
+        from cm.cm_settings import DECORATED_CREATORS
+        
+        if self.user and not DECORATED_CREATORS:
             return self.user.username
         else:
             return self.name
 
     def get_email(self):
-        if self.user:
+        from cm.cm_settings import DECORATED_CREATORS
+        
+        if self.user and not DECORATED_CREATORS:
             return self.user.email
         else:
             return self.email
--- a/src/cm/security.py	Fri Jun 11 16:21:53 2010 +0200
+++ b/src/cm/security.py	Thu Jul 15 17:08:45 2010 +0200
@@ -7,7 +7,7 @@
 from django.http import HttpResponseRedirect
 from django.utils.http import urlquote
 from django.db.models import Q
-
+from piston.utils import rc
 import logging
 
 from cm.models import *
@@ -198,8 +198,7 @@
     def _dec(view_func):
         def _check_global_perm(request, *args, **kwargs):
             if must_be_logged_in and not is_authenticated(request):
-                login_url = reverse('login')
-                return HttpResponseRedirect('%s?%s=%s' % (login_url, redirect_field_name, urlquote(request.get_full_path())))
+                raise UnauthorizedException('Should be logged in')
             
             if has_perm(request, perm_name, text=None): 
                 return view_func(request, *args, **kwargs)
@@ -210,8 +209,14 @@
 
         return _check_global_perm
     return _dec    
+
+def has_perm_on_text_api(perm_name, must_be_logged_in=False, redirect_field_name=REDIRECT_FIELD_NAME):    
+    return _has_perm_on_text(perm_name, must_be_logged_in, redirect_field_name, api=True)
     
-def has_perm_on_text(perm_name, must_be_logged_in=False, redirect_field_name=REDIRECT_FIELD_NAME):    
+def has_perm_on_text(perm_name, must_be_logged_in=False, redirect_field_name=REDIRECT_FIELD_NAME, api=False):
+    return _has_perm_on_text(perm_name, must_be_logged_in, redirect_field_name, api)
+
+def _has_perm_on_text(perm_name, must_be_logged_in=False, redirect_field_name=REDIRECT_FIELD_NAME, api=False):    
     """
     decorator protection checking for perm for logged in user
     force logged in (i.e. redirect to connection screen if not if must_be_logged_in 
@@ -222,15 +227,23 @@
                 return view_func(request, *args, **kwargs)
 
             if must_be_logged_in and not is_authenticated(request):
-                login_url = reverse('login')
-                return HttpResponseRedirect('%s?%s=%s' % (login_url, redirect_field_name, urlquote(request.get_full_path())))
+                if not api:
+                    raise UnauthorizedException('Should be logged in')
+                else:
+                    return rc.FORBIDDEN
+
             
             if 'key' in kwargs: 
                 text = get_object_or_404(Text, key=kwargs['key'])                
             else:
                 raise Exception('no security check possible')
-                                    
-            if has_perm(request, perm_name, text=text): 
+                
+            # in api, the view has an object as first parameter, request is args[0]
+            if not api:                
+                req = request
+            else:                    
+                req = args[0]     
+            if has_perm(req, perm_name, text=text): 
                 return view_func(request, *args, **kwargs)
             #else:
                 # TODO: (? useful ?) if some user have the perm and not logged-in : redirect to login
@@ -238,7 +251,11 @@
                 #    return HttpResponseRedirect('%s?%s=%s' % (login_url, redirect_field_name, urlquote(request.get_full_path())))                    
             # else : unauthorized
             
-            raise UnauthorizedException('No perm %s' % perm_name)
+            if not api:
+                raise UnauthorizedException('No perm %s' % perm_name)
+            else:
+                return rc.FORBIDDEN
+
         _check_local_perm.__doc__ = view_func.__doc__
         _check_local_perm.__dict__ = view_func.__dict__
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/cm/templates/api_doc.html	Thu Jul 15 17:08:45 2010 +0200
@@ -0,0 +1,75 @@
+{% extends "site/layout/base_workspace.html" %}
+{% load com %}
+{% load i18n %}
+
+{% block title %}
+{% blocktrans %}API Documentation{% endblocktrans %}
+{% endblock %}
+
+{% block head %}
+{% endblock %}
+
+{% block content %}
+
+
+
+  <style type="text/css" media="screen">
+a.reflink {
+color:#C60F0F;
+font-size:0.8em;
+padding:0 4px;
+text-decoration:none;
+visibility:hidden;
+}
+
+:hover > a.reflink {
+visibility:visible;
+}
+  </style>
+
+
+<h1>API Documentation</h1>
+
+<h2>Presentation</h2>
+
+The API exposes method for external application to deal with content store in COMT.
+
+The authentification is done using <a href="http://fr.wikipedia.org/wiki/HTTP_Authentification">HTTP Authentification</a>.
+
+The default return format is 'json', add '?format=other_format' where other_format is 'json', 'xml', 'yaml' to change the results' format. 
+{% load markup %}
+
+		{% regroup docs by type as grouped_docs %}
+
+		
+		{% for dd in grouped_docs %}
+			<h2>{{ dd.grouper }}</h2>
+		    {% for doc in dd.list %}
+			{% if not doc.handler.no_display %}
+			<h3>{{ doc.handler.title }}&nbsp;<a href="#{{ doc.handler.title|iriencode }}" class="reflink" title="Permalink" name="{{ doc.handler.title|iriencode }}">¶</a></h3>
+			
+			<p>{{ doc.handler.desc }}</p>
+			<p>
+				{{ doc.doc|default:""|restructuredtext }}
+			</p>
+			
+			<p>
+				Endpoint: <b>{{ doc.handler.endpoint }}</b>
+			</p>
+			
+			<p>
+				Method: {% for meth in doc.allowed_methods %}<b>{{ meth }}</b>{% if not forloop.last %}, {% endif %}{% endfor %}
+			</p>
+
+			<p>
+				Args: {% if doc.handler.args %}{{ doc.handler.args|safe }}{% else %}None{% endif %}
+			</p>
+			
+					
+			<br />		
+			{% endif %}		
+			{% endfor %}
+		{% endfor %}
+	</body>
+</html>
+{% endblock %}
--- a/src/cm/templates/site/login_form.html	Fri Jun 11 16:21:53 2010 +0200
+++ b/src/cm/templates/site/login_form.html	Thu Jul 15 17:08:45 2010 +0200
@@ -27,6 +27,9 @@
 {% if request.GET.next %}
 <input type="hidden" name="next" value="{{ request.GET.next }}">
 {% endif %}
+{% if request.GET.q %}
+<input type="hidden" name="q" value="{{ request.GET.q }}">
+{% endif %}
 
 </form>
 
--- a/src/cm/templates/site/text_view_comments.html	Fri Jun 11 16:21:53 2010 +0200
+++ b/src/cm/templates/site/text_view_comments.html	Thu Jul 15 17:08:45 2010 +0200
@@ -64,11 +64,12 @@
 //initial comment db as json
 sv_comments = "{{ json_comments|escapejs }}";
 sv_filter_data = "{{ json_filter_datas|escapejs }}";
-sv_site_url = "{{ SITE_URL|escapejs }}";
+sv_site_url = "{% if request.GET.prefix %}{{ request.GET.prefix }}{% else %}{{ SITE_URL|escapejs }}{% endif %}";
+sv_prefix = "{% if request.GET.prefix %}{{ request.GET.prefix }}{% endif %}";
 
-sv_client_url = "{% url text-client-exchange %}?{{ request.GET.urlencode }}" ;
-sv_text_view_show_comment_url = "{% url text-view-show-comment text.key '' %}";
-sv_text_feed_url = "{% url text-feed text.key %}";
+sv_client_url = "{% if request.GET.prefix %}{{ request.GET.prefix }}{% endif %}{% url text-client-exchange %}?{{ request.GET.urlencode }}" ;
+sv_text_view_show_comment_url = "{% if request.GET.prefix %}{{ request.GET.prefix }}{% endif %}{% url text-view-show-comment text.key '' %}";
+sv_text_feed_url = "{% if request.GET.prefix %}{{ request.GET.prefix }}{% endif %}{% url text-feed text.key %}";
 
 sv_client_date_fmt = "{{ client_date_fmt.js_parse }}"; //"%Y-%m-%dT%H:%M:%S" ;
 sv_key = "{{ text.key|escapejs }}";
@@ -83,7 +84,7 @@
 
 --></script>
 
-<script type="text/javascript" src="{% url django.views.i18n.javascript_catalog %}"></script>
+<script type="text/javascript" src="{% if request.GET.prefix %}{{ request.GET.prefix }}{% endif %}{% url django.views.i18n.javascript_catalog %}"></script>
 {% if CLIENT_DEBUG  %}
 <script type="text/javascript" src="{{ CM_MEDIA_PREFIX }}js/client/c_permissions.js"></script> 
 <script type="text/javascript" src="{{ CM_MEDIA_PREFIX }}js/client/c_preferences.js"></script>
@@ -106,7 +107,7 @@
 <script type="text/javascript" src="{{ CM_MEDIA_PREFIX }}js/site/c_text_view_comments_to_frame.js"></script>
 <script type="text/javascript" src="{{ CM_MEDIA_PREFIX }}js/site/c_text_view_comments.js"></script> 
 {% else %}
-<script type="text/javascript" src="{{ CM_MEDIA_PREFIX }}js/client/c_client-min.js?1273842996"></script> 
+<script type="text/javascript" src="{{ CM_MEDIA_PREFIX }}js/client/c_client-min.js?1279203082"></script> 
 {% endif %}
 
 
--- a/src/cm/templates/site/text_view_frame.html	Fri Jun 11 16:21:53 2010 +0200
+++ b/src/cm/templates/site/text_view_frame.html	Thu Jul 15 17:08:45 2010 +0200
@@ -30,13 +30,13 @@
 
     <link type="text/css" href="{{ CM_MEDIA_PREFIX }}css/site/text_view_frame.css" rel="stylesheet" />
 
-    <script type="text/javascript" src="{% url django.views.i18n.javascript_catalog %}"></script>
+    <script type="text/javascript" src="{% if request.GET.prefix %}{{ request.GET.prefix }}{% endif %}{% url django.views.i18n.javascript_catalog %}"></script>
 {% if CLIENT_DEBUG %}
     <script type="text/javascript" src="{{ CM_MEDIA_PREFIX }}js/client/f_message.js"></script>
     <script type="text/javascript" src="{{ CM_MEDIA_PREFIX }}js/client/f_printDialog.js"></script>
     <script type="text/javascript" src="{{ CM_MEDIA_PREFIX }}js/site/f_text_view_frame.js"></script>
 {% else %}
-    <script type="text/javascript" src="{{ CM_MEDIA_PREFIX }}js/client/f_client-min.js?1273842996"></script> 
+    <script type="text/javascript" src="{{ CM_MEDIA_PREFIX }}js/client/f_client-min.js?1279203082"></script> 
 {% endif %}
     <style type="text/css">
         /*
@@ -59,6 +59,7 @@
 
 </head>
 <BODY>
+
     <DIV id="add_comment_btn" class="initially_hidden"> 
 		<img align="middle" src="{{ CM_MEDIA_PREFIX }}img/note_add_sop_mid.gif" alt="{% blocktrans %}add a comment{% endblocktrans %}" title="{% blocktrans %}add a comment{% endblocktrans %}"/>
     </DIV>
@@ -84,7 +85,8 @@
 	    {% url text-view-comments-version text.key text_version.key as frame_url %}
 	             <iframe id="text_view_comments" name="text_view_comments" class="ui-layout-center"
             width="100%" height="100%" frameborder="0" scrolling="auto"
-            src="{{ frame_url }}{{ frame_url|url_args }}{{ request.GET.urlencode }}"></iframe>
+            src="{% if request.GET.prefix %}{{ request.GET.prefix }}{% else %}{% endif %}{{ frame_url }}{{ frame_url|url_args }}{{ request.GET.urlencode }}"></iframe>
+             
              
 <!--  exemple de passage d'arguments        <iframe id="text_view_comments" name="text_view_comments" class="ui-layout-center"
             width="100%" height="100%" frameborder="0" scrolling="auto"
@@ -97,7 +99,7 @@
 <!--         <p id="validateTips">All form fields are required.</p> -->
 
 		{% url text-export text.key "FoRmAt" "DoWnLoAd" "WhIcHCoMmEnT" "WiThCoLoR" as export_url %}    
-        <form name="print_export_form" id="print_export_form" method="post" action="" target_action="{{ export_url }}{{ export_url|url_args }}{{ request.GET.urlencode }}">
+        <form name="print_export_form" id="print_export_form" method="post" action="" target_action="{% if request.GET.prefix %}{{ request.GET.prefix }}{% else %}{% endif %}{{ export_url }}{{ export_url|url_args }}{{ request.GET.urlencode }}">
 	        <fieldset>
                 <label for="p_comments">{% blocktrans %}Which comments?{% endblocktrans %}</label>
                 <select  name="p_comments" id="p_comments" />
--- a/src/cm/tests/__init__.py	Fri Jun 11 16:21:53 2010 +0200
+++ b/src/cm/tests/__init__.py	Thu Jul 15 17:08:45 2010 +0200
@@ -6,3 +6,4 @@
 from cm.tests.test_history import *
 from cm.tests.test_security import *
 from cm.tests.test_activity import *
+from cm.tests.test_api import *
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/cm/tests/test_api.py	Thu Jul 15 17:08:45 2010 +0200
@@ -0,0 +1,230 @@
+from django.test import TestCase
+from django.test.client import Client
+from django.core import management
+from datetime import datetime
+from cm.activity import *
+from cm.models import *
+from cm.security import *
+
+from django.http import HttpRequest, HttpResponse
+from django.utils import simplejson
+
+from cm.api.handlers import *
+
+#from piston.test import TestCase
+from piston.models import Consumer
+from piston.handler import BaseHandler
+from piston.utils import rc
+from piston.resource import Resource
+
+class FalseRequest(object):
+    def __init__(self, user):
+        self.user = user
+
+class APITest(TestCase):
+    fixtures = ['roles_generic', 'test_content', ]
+    
+    def test_text_get(self):
+        """
+        Anonymous api call
+        """
+        
+        resource = Resource(AnonymousTextHandler)
+        request = HttpRequest()
+        setattr(request, 'user' , None)
+        request.method = 'GET'
+        
+        # get public text
+        response = resource(request, key='text_key_4', emitter_format='json')
+        self.assertEquals(200, response.status_code) # 401: forbidden
+        response_data = simplejson.loads(response.content)
+        self.assertEquals(response_data.get('created'), '2009-02-13 04:01:12')
+        
+        # error: private text
+        response = resource(request, key='text_key_3', emitter_format='json')
+        self.assertEquals(401, response.status_code)
+
+
+    def test_text_get_logged_in(self):
+        """
+        Logged in as manager api call
+        """
+
+        resource = Resource(AnonymousTextHandler)
+        request = HttpRequest()
+        user = User.objects.get(pk=1)
+        setattr(request, 'user' , user)
+        request.method = 'GET'
+  
+        response = resource(request, key='text_key_3', emitter_format='json')
+        self.assertEquals(200, response.status_code)
+
+
+    def test_text_create(self):
+        request = FalseRequest(None) 
+        nb_anon_texts = get_texts_with_perm(request, 'can_view_text').count()
+        nb_texts = Text.objects.count()
+        
+        resource = Resource(TextListHandler)
+        
+        # create one private text 
+        request = HttpRequest()
+        user = User.objects.get(pk=1)
+        setattr(request, 'user' , user)
+        request.method = 'POST'
+        setattr(request, 'POST' , {'content':'test content', 'format':"markdown", 'title': 'my title'})
+        response = resource(request,)
+
+        self.assertEquals(200, response.status_code)
+        self.assertTrue('key' in simplejson.loads(response.content).keys())
+
+        request = FalseRequest(None) 
+        self.assertEqual(get_texts_with_perm(request, 'can_view_text').count(), nb_anon_texts) # NO more anon text
+        
+        # create one text with anon observer
+        request = HttpRequest()
+        user = User.objects.get(pk=1)
+        setattr(request, 'user' , user)
+        request.method = 'POST'
+        setattr(request, 'POST' , {'content':'test content', 'format':"markdown", 'title': 'my title', 'anon_role' : 4})
+        response = resource(request,)
+
+        self.assertEquals(200, response.status_code)
+        self.assertTrue('key' in simplejson.loads(response.content).keys())
+        
+        self.assertEquals(nb_texts + 2, Text.objects.count()) # 2 more texts should have been created
+
+        request = FalseRequest(None) 
+        self.assertEqual(get_texts_with_perm(request, 'can_view_text').count(), nb_anon_texts + 1) # one more anon accessible text available
+        
+    def test_list_text_get(self):
+        """
+        List texts anon
+        """
+        resource = Resource(AnonymousTextListHandler)
+        request = HttpRequest()
+        setattr(request, 'user' , None)
+        request.method = 'GET'
+  
+        response = resource(request, emitter_format='json')
+        self.assertEquals(200, response.status_code)
+        self.assertEquals(2, len(simplejson.loads(response.content)))
+
+    def test_list_text_logged_in(self):
+        """
+        List texts manager
+        """
+        resource = Resource(AnonymousTextListHandler)
+        request = HttpRequest()
+        user = User.objects.get(pk=1)
+        setattr(request, 'user' , user)
+        request.method = 'GET'
+  
+        response = resource(request, emitter_format='json')
+        self.assertEquals(200, response.status_code)
+        self.assertEquals(5, len(simplejson.loads(response.content)))
+
+    def test_delete_text_logged_in_works(self):
+        """
+        Delete text
+        """
+        nb_texts = Text.objects.count()
+        
+        resource = Resource(TextDeleteHandler)
+        request = HttpRequest()
+        user = User.objects.get(pk=1)
+        setattr(request, 'user' , user)
+        request.method = 'POST'
+        setattr(request, 'POST' , {})
+        setattr(request, 'flash' , {})
+  
+        response = resource(request, key='text_key_3', emitter_format='json')
+        self.assertEquals(204, response.status_code)
+
+        # one text deleted
+        self.assertEquals(nb_texts - 1, Text.objects.count())
+        
+    def test_delete_text_logged_in_fail(self):
+        """
+        Delete text (and fail: insufficient rights)
+        """
+        nb_texts = Text.objects.count()
+
+        resource = Resource(TextDeleteHandler)
+        request = HttpRequest()
+        user = User.objects.get(pk=3)
+        setattr(request, 'user' , user)
+        request.method = 'POST'
+        setattr(request, 'POST' , {})
+        setattr(request, 'flash' , {})
+  
+        response = resource(request, key='text_key_3', emitter_format='json')
+        self.assertEquals(401, response.status_code)
+        
+        # no text deleted
+        self.assertEquals(nb_texts, Text.objects.count())
+
+
+    def test_pre_edit(self):
+        """
+        Pre edit text: should return number of comments to remove
+        """
+        resource = Resource(TextPreEditHandler)
+        request = HttpRequest()
+        user = User.objects.get(pk=1) 
+        setattr(request, 'user' , user)
+        request.method = 'POST'
+        setattr(request, 'POST' , {'new_format' : 'markdown', 'new_content' : u'ggg'})
+        setattr(request, 'flash' , {})
+    
+        response = resource(request, key='text_key_2', emitter_format='json')
+        self.assertEquals(response.content, '{"nb_removed": 3}')
+
+    def test_edit(self):
+        """
+        Edit text
+        """
+        resource = Resource(TextEditHandler)
+        request = HttpRequest()
+        session = {}
+        setattr(request,'session',{})
+        
+        user = User.objects.get(pk=1) 
+        setattr(request, 'user' , user)
+        request.method = 'POST'
+        setattr(request, 'POST' , {'format' : 'markdown', 'content' : u'ggg', 'keep_comments' : True, 'new_version' : True, 'title' : 'new title'})
+        #setattr(request, 'flash' , {})
+    
+        response = resource(request, key='text_key_2', emitter_format='json')
+
+        self.assertEquals(Text.objects.get(pk=2).last_text_version.content , u'ggg')
+
+    def test_text_version(self):
+        """
+        Text version operation
+        """
+        from django.test.client import Client
+        c = Client()
+        
+        # revert to text version
+        self.assertEquals(Text.objects.get(pk=1).get_versions_number() , 2)
+
+        resource = Resource(TextVersionRevertHandler)
+        request = HttpRequest()
+        request.method = 'POST'
+        setattr(request, 'POST' , {})
+        
+        response = resource(request, key='text_key_1', version_key='textversion_key_0', emitter_format='json')
+
+        self.assertEquals(Text.objects.get(pk=1).get_versions_number() , 3)
+        
+        # delete text version
+
+        resource = Resource(TextVersionDeleteHandler)
+        request = HttpRequest()
+        request.method = 'POST'
+        setattr(request, 'POST' , {})
+        response = resource(request, key='text_key_1', version_key='textversion_key_0', emitter_format='json')
+        
+        
+        self.assertEquals(Text.objects.get(pk=1).get_versions_number() , 2)
--- a/src/cm/tests/test_security.py	Fri Jun 11 16:21:53 2010 +0200
+++ b/src/cm/tests/test_security.py	Thu Jul 15 17:08:45 2010 +0200
@@ -17,19 +17,19 @@
     def test_access_rights(self):
         # anon user sees no text
         request = FalseRequest(None)                
-        self.assertEqual(get_texts_with_perm(request, 'can_view_text').count(), 0)
+        self.assertEqual(get_texts_with_perm(request, 'can_view_text').count(), 2)
 
         # user 1 sees all texts
         user1 = UserProfile.objects.get(id=1).user        
         request = FalseRequest(user1)       
-        self.assertEqual(get_texts_with_perm(request, 'can_view_text').count(), 3)
+        self.assertEqual(get_texts_with_perm(request, 'can_view_text').count(), 5)
         
-        # user 2 sees only 2 texts
+        # user 2 sees only 4 texts
         user2 = UserProfile.objects.get(id=2).user
         request = FalseRequest(user2)        
-        self.assertEqual(get_texts_with_perm(request, 'can_view_text').count(), 2)
+        self.assertEqual(get_texts_with_perm(request, 'can_view_text').count(), 4)
 
-        # user 4 sees only 2 texts (global manager but commentator on text 4
+        # user 4 manages only 2 texts (global manager but commentator on text 4
         user4 = UserProfile.objects.get(id=4).user
         request = FalseRequest(user4)
         self.assertEqual(get_texts_with_perm(request, 'can_manage_text').count(), 2)
--- a/src/cm/urls.py	Fri Jun 11 16:21:53 2010 +0200
+++ b/src/cm/urls.py	Thu Jul 15 17:08:45 2010 +0200
@@ -157,3 +157,7 @@
 urlpatterns += patterns('',
     (r'^jsi18n/$', 'django.views.i18n.javascript_catalog', js_info_dict),
 )
+
+urlpatterns += patterns('',
+   (r'^api/', include('cm.api.urls')),
+)
--- a/src/cm/utils/comment_positioning.py	Fri Jun 11 16:21:53 2010 +0200
+++ b/src/cm/utils/comment_positioning.py	Thu Jul 15 17:08:45 2010 +0200
@@ -181,6 +181,8 @@
     for (wrapper_id, wrapper_data) in datas.items() :
         start_color = wrapper_data['start_color']
         offsets = sorted(wrapper_data['offsets'].items(), key=operator.itemgetter(0))
+
+        # TODO: html.find(id = "sv-%d"%wrapper_id) is None (?) when comment detached
         
         content = html.find(id = "sv-%d"%wrapper_id).contents[0]
         
--- a/src/cm/views/user.py	Fri Jun 11 16:21:53 2010 +0200
+++ b/src/cm/views/user.py	Thu Jul 15 17:08:45 2010 +0200
@@ -544,8 +544,12 @@
     
     display_message(request, _(u"You're logged in!"))
     next = request.POST.get('next', None)
+    q = request.POST.get('q', None)
     if next and next.startswith('/'):
-        return HttpResponseRedirect(next)
+        if q:
+            return HttpResponseRedirect(next + '?' + q)
+        else:
+            return HttpResponseRedirect(next)
     else:
         return HttpResponseRedirect(reverse('index'))