<commit_before>define(['vie', 'logger', 'tracker', 'underscore', 'jquery', 'backbone', 'view/detail/DetailView', 'voc'], function(VIE, Logger, tracker, _, $, Backbone, DetailView, Voc){
    return Backbone.View.extend({
        LOG: Logger.get('EntityView'),
        icons: {
            'sss:addPrivateCollectionItem': 'img/sss/addCollectionItem.png',
            'sss:addSharedCollectionItem': 'img/sss/addCollectionItem.png',
            'sss:changeCollectionByAddPrivateCollectionItem': 'img/sss/changeCollection.png', //changeCollectionAddPrivateCollectionItem
            'sss:changeCollectionByAddSharedCollectionItem': 'img/sss/changeCollection.png', //changeCollectionAddSharedCollectionItem
            //'appearsInSearchResult': 'img/sss/.png',
            'sss:subscribeCollection': 'img/sss/subscribeCollection.png',
            'sss:unSubscribeCollection': 'img/sss/unSubscribeCollection.png',
            'sss:createPrivateCollection': 'img/sss/addCollection.png',
            'sss:createSharedCollection': 'img/sss/addCollection.png',
            'sss:createPrivateRecord': 'img/sss/addDocument.png',
            'sss:createSharedRecord': 'img/sss/addDocument.png',
            'sss:rateEntity': 'img/sss/rate.png',
            'sss:discussEntity': 'img/sss/startDiscussion.png', //startDiscussion
            'sss:addDiscussionComment': 'img/sss/discuss.png',
            'sss:addPrivateTag': 'img/sss/addTag.png',
            'sss:addSharedTag': 'img/sss/addTag.png',
            'sss:removePrivateTag': 'img/sss/deleteTag.png',
            'sss:removeSharedTag': 'img/sss/deleteTag.png',
            'sss:renamePrivateCollectionItem': 'img/sss/renameCollectionItem.png',
            'sss:renameSharedCollectionItem': 'img/sss/renameCollectionItem.png',
            'sss:removePrivateCollectionItem': 'img/sss/removeCollectionItem.png',
            'sss:removeSharedCollectionItem': 'img/sss/removeCollectionItem.png',
            'sss:removePrivateCollection': 'img/sss/deleteCollection.png',
            'sss:removeSharedCollection': 'img/sss/deleteCollection.png',
            'sss:removePrivateRecord': 'img/sss/deleteDocument.png',
            'sss:removeSharedRecord': 'img/sss/deleteDocument.png',
            'sss:renameDiscussion': 'img/sss/renameDiscussion.png',
            'sss:changeCollectionByRemovePrivateCollectionItem': 'img/sss/changeCollection.png', //changeCollectionRemovePrivateCollectionItem
            'sss:changeCollectionByRemoveSharedCollectionItem': 'img/sss/changeCollection.png', //changeCollectionRemoveSharedCollectionItem
            //'newDiscussionByDiscussEntity': 'img/sss/.png'
            'sss:renamePrivateCollection':'img/sss/editCollection.png',
            'sss:renameSharedCollection':'img/sss/editCollection.png',
            'sss:renamePrivateRecord':'img/sss/editDocument.png',
            'sss:renameSharedRecord':'img/sss/editDocument.png',
            'sss:shareCollection':'img/sss/shareCollection.png',
            'sss:shareDocument':'img/sss/shareDocument.png',
            'sss:user' : 'img/sss/user1.png',
            'sss:coll' : 'img/sss/collection.png',
            'owl:Thing' : 'img/sss/thing.png',
            'sss:user/peter/' : 'img/sss/user2.png',
            'sss:user/paul/' : 'img/sss/user1.png',
            'sss:entity' : 'img/sss/entityLink.png',
            'sss:disc' : 'img/sss/discuss.png',
            'sss:discEntry' : 'img/sss/discuss.png',
            'sss:file' : 'img/sss/document.png',
            'sss:filePdf' : 'img/sss/entityFilePdf.png',
            'sss:filePng' : 'img/sss/entityImageJpg.png',
            'sss:fileDoc' : 'img/sss/entityFileDoc.png',
            'sss:rating' : 'img/sss/rate.png',
            'sss:tag' : 'img/evernote/tag.png',
            //'sss:userEvent' : 'img/sss/userEvent.png',
            //'sss:learnEp' : 'img/evernote/learnEp.png',
            //'sss:learnEpTimelineState' : 'img/evernote/learnEpTimelineState.png',
            //'sss:learnEpVersion' : 'img/evernote/learnEpVersion.png',
            //'sss:learnEpCircle' : 'img/evernote/learnEpCircle.png',
            //'sss:learnEpEntity' : 'img/evernote/learnEpEntity.png',

            'unknown' : 'img/sss/unknown.png',
            // EVERNOTE STUFF
            'sss:evernoteNotebook' : 'img/sss/collection.png',
            'sss:evernoteNote' : 'img/sss/evernoteNote.png',
            'sss:evernoteResource' : 'img/sss/evernoteResource.png',

            'sss:evernoteNotebookCreate' : 'img/sss/addCollection.png',
            'sss:evernoteNotebookUpdate' : 'img/sss/editCollection.png',
            'sss:evernoteNotebookShare' : 'img/sss/shareCollection.png',
            'sss:evernoteNotebookFollow' : 'img/sss/subscribeCollection.png',
            'sss:evernoteNoteCreate' : 'img/sss/addDocument.png',
            'sss:evernoteNoteUpdate' : 'img/sss/editDocument.png',
            'sss:evernoteNoteDelete' : 'img/sss/deleteDocument.png',
            'sss:evernoteNoteShare' : 'img/sss/shareDocument.png',
            'sss:evernoteNoteFollow' : 'img/sss/subscribeDocument.png',
            'sss:evernoteReminderDone' : 'img/sss/reminderDone.png',
            'sss:evernoteReminderCreate' : 'img/sss/reminder.png',
            'sss:evernoteResourceAdd' : 'img/sss/addCollectionItem.png',
            'sss:evernoteResourceFollow' : 'img/sss/subscribeResource.png',
            'sss:evernoteResourceShare' : 'img/sss/shareResource.png'

        },
        events : {
          'click' : '_click'
          //'contextmenu' : 'detailView'
        },
        initialize: function() {
            this.model.on('change', this.render,this );
        },
        click: function(e) {
            this.LOG.error('clicked', e);
            if( e.which === 1 ) {
                this.defer();
            } else if( e.which === 3) {
                this.detailView();
                return false;
            }
        },
        // click function to manage click/dblclick
        _click: function(e) {
            var el=$(this);
            this.LOG.debug('_click');
            if (this.alreadyclicked)
            {
                this.alreadyclicked=false; // reset
                clearTimeout(this.alreadyclickedTimeout); // prevent this from happening
                this.handleDblClick();
                var ev = $.Event("bnp:dblclickEntity", {
                    originalEvent : e,
                    entity : this.model
                });
                this.$el.trigger(ev);
            }
            else
            {
                this.alreadyclicked=true;
                var view = this;
                //view.detailView(e);
                this.alreadyclickedTimeout=setTimeout(function(){
                    view.alreadyclicked=false; // reset when it happens
                    view.LOG.debug('_click timeOut');
                    var ev = $.Event("bnp:clickEntity", {
                        originalEvent : e,
                        entity : view.model
                    });
                    view.$el.trigger(ev);
                },400); // <-- dblclick tolerance here
            }
            return false;
        },
        handleDblClick : function() {
            this.defer();
        },
        defer: function() {
            this.LOG.debug('defer');
            var resource = this.model.get(Voc.hasResource);
            if( !resource ) resource = this.model.getSubject();
            else resource = resource.getSubject();
            var lastChar = resource[resource.length-1];
            if( lastChar === '/') resource = resource.substring(0, resource.length-1);
            tracker.info(tracker.OPENRESOURCE, resource);
            this.LOG.log('open resource', resource);
            window.open(resource);
        },
        render: function() {
            var label,
                view_class;

            this.$el.attr({
              'class' : 'entity',
              'about' : this.model.getSubject()
            });
            label = this.model.get(Voc.label) || "";
            view_class = 'labelable';

            if( true === this.model.get(Voc.isUsed) ) {
                view_class += ' used';
            }

            if( label && label.isEntity ) label = label.getSubject();
            this.$el.html(//"
"+
                    "
"+
                    ""+
                        "" +
                        ""+label+""+
                        ""+
                    "
");
            this.LOG.debug('rendering ', this.model);
            this.draggable();
            return this;
        },
        detailView: function(e) {
            this.LOG.debug("clicked entity");
            this.LOG.debug("e", e);
            if( !e.currentTarget ) return;
            var id = $(e.currentTarget).attr('about');
            if( !id ) return;
            this.LOG.debug("id", id);
            if( id != this.model.getSubject() ) return;
            tracker.info(tracker.VIEWDETAILS, id);

            // --- ADD THE DETAIL VIEW --- //
            var detailViewId = "detailView" + id.replace(/[\\/:-\\.#]/g, '');
            if( !document.getElementById(detailViewId)) {
                $('body').append("
");
                var detailView = new DetailView({
                    model: this.model,
                    el: '#' + detailViewId
                });
            }
            this.model.trigger('showDetails', e);
            return false;

        },
        draggable: function() {
            var VIEW = this;
            this.$el.draggable({
                zIndex: 10000,
                helper: "clone",
                appendTo: "body",
                drag: function(event, ui) {
                    VIEW.LOG.debug('dragging');
                    var ev = event;
                    while (ev != null) {
                        if (ev.type == "mousemove")
                            ev.stopImmediatePropagation();
                        ev = ev.originalEvent;
                    }
                }
            });

        },
        getIcon: function(type) {
            var name,
                mimeType,
                file;
            // TODO: make clear use of URIs
            if( !type ) type = this.model.get('@type');
            if( !type ) return this.icons['unknown'];
            if( _.isArray(type)) {
                // decide which type to use
                var i, j, push;
                for( i = 0; i < type.length; i++ ){
                    push = true;
                    for( j = 0; j < type.length; j++ ){
                        if( i != j && type[i].subsumes(type[j])) {
                            push = false;
                            break;
                        }
                    }
                    if( push ) {
                        type = type[i];
                        break;
                    }
                }
            }
            if( _.isArray(type)) { type = type[0]; }
            name = this.model.vie.namespaces.curie(type.id);
            if( name === 'user' ) {
                name = this.model.vie.namespaces.curie(this.model.getSubject());
                if( !this.icons[name]) name = 'user';
            }

            if ( 'sss:file' === name || 'sss:evernoteResource' === name ) {
                mimeType  = this.model.get(Voc.hasMimeType);
                if ( mimeType ) {
                    switch( mimeType ) {
                        case 'application/pdf':
                            name = 'sss:filePdf';
                            break;
                        case 'image/png':
                            name = 'sss:filePng';
                            break;
                        case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
                        case 'application/msword':
                            name = 'sss:fileDoc';
                            break;
                    }
                } else {
                    file = this.model.get(Voc.file);
                    if( file && file.isEntity ) file = file.getSubject();
                    if( file ) {
                        switch(file.substring(file.length-4) ) {
                            case '.pdf':
                                name = 'sss:filePdf';
                                break;
                            case '.png':
                                name = 'sss:filePng';
                                break;
                            case 'docx':
                            case '.doc':
                                name = 'sss:fileDoc';
                                break;
                        }
                    }
                }
            }

            if( !this.icons[name]) return this.icons['unknown'];
            return this.icons[name];
        },
        /**
         * Returns the average width of an entity.
         * TODO fix hard-coded width
         */
        getWidth: function() {
            return 40;
        }
    });
});
<commit_msg>A bit better handling for entity icons.<commit_after>define(['vie', 'logger', 'tracker', 'underscore', 'jquery', 'backbone', 'view/detail/DetailView', 'voc'], function(VIE, Logger, tracker, _, $, Backbone, DetailView, Voc){
    return Backbone.View.extend({
        LOG: Logger.get('EntityView'),
        icons: {
            'sss:addPrivateCollectionItem': 'img/sss/addCollectionItem.png',
            'sss:addSharedCollectionItem': 'img/sss/addCollectionItem.png',
            'sss:changeCollectionByAddPrivateCollectionItem': 'img/sss/changeCollection.png', //changeCollectionAddPrivateCollectionItem
            'sss:changeCollectionByAddSharedCollectionItem': 'img/sss/changeCollection.png', //changeCollectionAddSharedCollectionItem
            //'appearsInSearchResult': 'img/sss/.png',
            'sss:subscribeCollection': 'img/sss/subscribeCollection.png',
            'sss:unSubscribeCollection': 'img/sss/unSubscribeCollection.png',
            'sss:createPrivateCollection': 'img/sss/addCollection.png',
            'sss:createSharedCollection': 'img/sss/addCollection.png',
            'sss:createPrivateRecord': 'img/sss/addDocument.png',
            'sss:createSharedRecord': 'img/sss/addDocument.png',
            'sss:rateEntity': 'img/sss/rate.png',
            'sss:discussEntity': 'img/sss/startDiscussion.png', //startDiscussion
            'sss:addDiscussionComment': 'img/sss/discuss.png',
            'sss:addPrivateTag': 'img/sss/addTag.png',
            'sss:addSharedTag': 'img/sss/addTag.png',
            'sss:removePrivateTag': 'img/sss/deleteTag.png',
            'sss:removeSharedTag': 'img/sss/deleteTag.png',
            'sss:renamePrivateCollectionItem': 'img/sss/renameCollectionItem.png',
            'sss:renameSharedCollectionItem': 'img/sss/renameCollectionItem.png',
            'sss:removePrivateCollectionItem': 'img/sss/removeCollectionItem.png',
            'sss:removeSharedCollectionItem': 'img/sss/removeCollectionItem.png',
            'sss:removePrivateCollection': 'img/sss/deleteCollection.png',
            'sss:removeSharedCollection': 'img/sss/deleteCollection.png',
            'sss:removePrivateRecord': 'img/sss/deleteDocument.png',
            'sss:removeSharedRecord': 'img/sss/deleteDocument.png',
            'sss:renameDiscussion': 'img/sss/renameDiscussion.png',
            'sss:changeCollectionByRemovePrivateCollectionItem': 'img/sss/changeCollection.png', //changeCollectionRemovePrivateCollectionItem
            'sss:changeCollectionByRemoveSharedCollectionItem': 'img/sss/changeCollection.png', //changeCollectionRemoveSharedCollectionItem
            //'newDiscussionByDiscussEntity': 'img/sss/.png'
            'sss:renamePrivateCollection':'img/sss/editCollection.png',
            'sss:renameSharedCollection':'img/sss/editCollection.png',
            'sss:renamePrivateRecord':'img/sss/editDocument.png',
            'sss:renameSharedRecord':'img/sss/editDocument.png',
            'sss:shareCollection':'img/sss/shareCollection.png',
            'sss:shareDocument':'img/sss/shareDocument.png',
            'sss:user' : 'img/sss/user1.png',
            'sss:coll' : 'img/sss/collection.png',
            'owl:Thing' : 'img/sss/thing.png',
            'sss:user/peter/' : 'img/sss/user2.png',
            'sss:user/paul/' : 'img/sss/user1.png',
            'sss:entity' : 'img/sss/entityLink.png',
            'sss:disc' : 'img/sss/discuss.png',
            'sss:discEntry' : 'img/sss/discuss.png',
            'sss:file' : 'img/sss/document.png',
            'sss:filePdf' : 'img/sss/entityFilePdf.png',
            'sss:filePng' : 'img/sss/entityImageJpg.png',
            'sss:fileDoc' : 'img/sss/entityFileDoc.png',
            'sss:rating' : 'img/sss/rate.png',
            'sss:tag' : 'img/evernote/tag.png',
            //'sss:userEvent' : 'img/sss/userEvent.png',
            //'sss:learnEp' : 'img/evernote/learnEp.png',
            //'sss:learnEpTimelineState' : 'img/evernote/learnEpTimelineState.png',
            //'sss:learnEpVersion' : 'img/evernote/learnEpVersion.png',
            //'sss:learnEpCircle' : 'img/evernote/learnEpCircle.png',
            //'sss:learnEpEntity' : 'img/evernote/learnEpEntity.png',

            'unknown' : 'img/sss/unknown.png',
            // EVERNOTE STUFF
            'sss:evernoteNotebook' : 'img/sss/collection.png',
            'sss:evernoteNote' : 'img/sss/evernoteNote.png',
            'sss:evernoteResource' : 'img/sss/evernoteResource.png',

            'sss:evernoteNotebookCreate' : 'img/sss/addCollection.png',
            'sss:evernoteNotebookUpdate' : 'img/sss/editCollection.png',
            'sss:evernoteNotebookShare' : 'img/sss/shareCollection.png',
            'sss:evernoteNotebookFollow' : 'img/sss/subscribeCollection.png',
            'sss:evernoteNoteCreate' : 'img/sss/addDocument.png',
            'sss:evernoteNoteUpdate' : 'img/sss/editDocument.png',
            'sss:evernoteNoteDelete' : 'img/sss/deleteDocument.png',
            'sss:evernoteNoteShare' : 'img/sss/shareDocument.png',
            'sss:evernoteNoteFollow' : 'img/sss/subscribeDocument.png',
            'sss:evernoteReminderDone' : 'img/sss/reminderDone.png',
            'sss:evernoteReminderCreate' : 'img/sss/reminder.png',
            'sss:evernoteResourceAdd' : 'img/sss/addCollectionItem.png',
            'sss:evernoteResourceFollow' : 'img/sss/subscribeResource.png',
            'sss:evernoteResourceShare' : 'img/sss/shareResource.png'

        },
        events : {
          'click' : '_click'
          //'contextmenu' : 'detailView'
        },
        initialize: function() {
            this.model.on('change', this.render,this );
        },
        click: function(e) {
            this.LOG.error('clicked', e);
            if( e.which === 1 ) {
                this.defer();
            } else if( e.which === 3) {
                this.detailView();
                return false;
            }
        },
        // click function to manage click/dblclick
        _click: function(e) {
            var el=$(this);
            this.LOG.debug('_click');
            if (this.alreadyclicked)
            {
                this.alreadyclicked=false; // reset
                clearTimeout(this.alreadyclickedTimeout); // prevent this from happening
                this.handleDblClick();
                var ev = $.Event("bnp:dblclickEntity", {
                    originalEvent : e,
                    entity : this.model
                });
                this.$el.trigger(ev);
            }
            else
            {
                this.alreadyclicked=true;
                var view = this;
                //view.detailView(e);
                this.alreadyclickedTimeout=setTimeout(function(){
                    view.alreadyclicked=false; // reset when it happens
                    view.LOG.debug('_click timeOut');
                    var ev = $.Event("bnp:clickEntity", {
                        originalEvent : e,
                        entity : view.model
                    });
                    view.$el.trigger(ev);
                },400); // <-- dblclick tolerance here
            }
            return false;
        },
        handleDblClick : function() {
            this.defer();
        },
        defer: function() {
            this.LOG.debug('defer');
            var resource = this.model.get(Voc.hasResource);
            if( !resource ) resource = this.model.getSubject();
            else resource = resource.getSubject();
            var lastChar = resource[resource.length-1];
            if( lastChar === '/') resource = resource.substring(0, resource.length-1);
            tracker.info(tracker.OPENRESOURCE, resource);
            this.LOG.log('open resource', resource);
            window.open(resource);
        },
        render: function() {
            var label,
                view_class;

            this.$el.attr({
              'class' : 'entity',
              'about' : this.model.getSubject()
            });
            label = this.model.get(Voc.label) || "";
            view_class = 'labelable';

            if( true === this.model.get(Voc.isUsed) ) {
                view_class += ' used';
            }

            if( label && label.isEntity ) label = label.getSubject();
            this.$el.html(//"
"+
                    "
"+
                    ""+
                        "" +
                        ""+label+""+
                        ""+
                    "
");
            this.LOG.debug('rendering ', this.model);
            this.draggable();
            return this;
        },
        detailView: function(e) {
            this.LOG.debug("clicked entity");
            this.LOG.debug("e", e);
            if( !e.currentTarget ) return;
            var id = $(e.currentTarget).attr('about');
            if( !id ) return;
            this.LOG.debug("id", id);
            if( id != this.model.getSubject() ) return;
            tracker.info(tracker.VIEWDETAILS, id);

            // --- ADD THE DETAIL VIEW --- //
            var detailViewId = "detailView" + id.replace(/[\\/:-\\.#]/g, '');
            if( !document.getElementById(detailViewId)) {
                $('body').append("
");
                var detailView = new DetailView({
                    model: this.model,
                    el: '#' + detailViewId
                });
            }
            this.model.trigger('showDetails', e);
            return false;

        },
        draggable: function() {
            var VIEW = this;
            this.$el.draggable({
                zIndex: 10000,
                helper: "clone",
                appendTo: "body",
                drag: function(event, ui) {
                    VIEW.LOG.debug('dragging');
                    var ev = event;
                    while (ev != null) {
                        if (ev.type == "mousemove")
                            ev.stopImmediatePropagation();
                        ev = ev.originalEvent;
                    }
                }
            });

        },
        getIcon: function(type) {
            var name,
                mimeType,
                file;
            // TODO: make clear use of URIs
            if( !type ) type = this.model.get('@type');
            if( !type ) return this.icons['unknown'];
            if( _.isArray(type)) {
                // decide which type to use
                var i, j, push;
                for( i = 0; i < type.length; i++ ){
                    push = true;
                    for( j = 0; j < type.length; j++ ){
                        if( i != j && type[i].subsumes(type[j])) {
                            push = false;
                            break;
                        }
                    }
                    if( push ) {
                        type = type[i];
                        break;
                    }
                }
            }
            if( _.isArray(type)) { type = type[0]; }
            name = this.model.vie.namespaces.curie(type.id);
            if( name === 'user' ) {
                name = this.model.vie.namespaces.curie(this.model.getSubject());
                if( !this.icons[name]) name = 'user';
            }

            if ( this.model.isof(Voc.FILE) || this.model.isof(Voc.EVERNOTE_RESOURCE) ) {
                mimeType  = this.model.get(Voc.hasMimeType);
                if ( mimeType ) {
                    switch( mimeType ) {
                        case 'application/pdf':
                            name = 'sss:filePdf';
                            break;
                        case 'image/png':
                            name = 'sss:filePng';
                            break;
                        case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
                        case 'application/msword':
                            name = 'sss:fileDoc';
                            break;
                    }
                } else {
                    file = this.model.get(Voc.file);
                    if( file && file.isEntity ) file = file.getSubject();
                    if( file ) {
                        switch(file.substring(file.length-4) ) {
                            case '.pdf':
                                name = 'sss:filePdf';
                                break;
                            case '.png':
                                name = 'sss:filePng';
                                break;
                            case 'docx':
                            case '.doc':
                                name = 'sss:fileDoc';
                                break;
                        }
                    }
                }
            }

            if( !this.icons[name]) return this.icons['unknown'];
            return this.icons[name];
        },
        /**
         * Returns the average width of an entity.
         * TODO fix hard-coded width
         */
        getWidth: function() {
            return 40;
        }
    });
});
<|endoftext|>


<commit_before>var display = require("../util/display");
var eb = require("../eventBus");
var template = require("../tmpl/analyze-group");
var CommentModel = require("../models/comment");
var Handlebones = require("handlebones");
var Utils = require("../util/utils");

var NUMBER_OF_REPRESENTATIVE_COMMENTS_TO_SHOW = 5;

var el_carouselSelector = "#carousel";

function bbCompare(propertyName, a, b) {
  var x = b.get(propertyName) - a.get(propertyName);
  return x;
}
function bbCompareAscending(propertyName, a, b) {
  return -bbCompare(propertyName, a, b);
}
function compareTieBreaker(a, b) {
  var x = bbCompare("stars", a, b);
  x = x || a.get("txt").length - b.get("txt").length; // shorter comments first
  x = x || bbCompare("created", a, b);
  // x = x || (b.get("txt").toLowerCase() < a.get("txt").toLowerCase()) ? 1 : -1; // alphabetic
  return x;
}
function sortRepness(a, b) {
  var x = bbCompare("repness", a, b);
  return x || compareTieBreaker(a, b);
}
function comparatorAgree(a, b) {
  var x = bbCompare("A", a, b);
  x = x || bbCompareAscending("D", a, b);
  return x || compareTieBreaker(a, b);
}
function comparatorDisagree(a, b) {
  var x = bbCompare("D", a, b);
  x = x || bbCompareAscending("A", a, b);
  return x || compareTieBreaker(a, b);
}
function comparatorDivisive(a, b) {
  var b_agrees = b.get("A");
  var b_disagrees = b.get("D");
  var a_agrees = a.get("A");
  var a_disagrees = a.get("D");
  var b_product = b_agrees * b_disagrees;
  var a_product = a_agrees * a_disagrees;
  var b_sum = b_agrees + b_disagrees + 1; // Add 1 to prevent divide-by-zero
  var a_sum = a_agrees + a_disagrees + 1; // Add 1 to prevent divide-by-zero
  var x = b_product/b_sum - a_product/a_sum;
  x = x || bbCompareAscending("A", a, b);
  return x || compareTieBreaker(a, b);
}

function comparatorStars(a, b) {
  var x = bbCompare("stars", a, b);
  return x || compareTieBreaker(a, b);
}

module.exports = Handlebones.View.extend({
    name: "analyze-global-view",
    template: template,
    tidsForGroup: null,
    events: {
      "click #sortAgree": "sortAgree",
      "click #sortDisagree": "sortDisagree",
      "click #sortDivisive": "sortDivisive",
      "keyup input": "updateSearch",
      "propertychange input": "updateSearch",
      submit: function(e) {
        e.preventDefault();
      },
      // "rendered:collection": function() {
      //   this.selectFirst();
      //   console.log('rendered:collection');
      // },
      rendered: function() {
        var that = this;
        var items = this.$(".query_result_item");
        items.on("mouseover", function() {
            $(this).addClass("hover");
        });
        items.on("mouseout", function() {
            $(this).removeClass("hover");
        });
      }
    },
    selectSortModes: function(chosenButtonSelector) {
      this.$("#sortAgree,#sortDisagree,#sortDivisive").removeClass("enabled");
      this.$(chosenButtonSelector).addClass("enabled");
    },
    selectFirst: function() {

    },
  searchEnabled: true,
  sortEnabled: true,

  groupInfo: function() {
    return this.parent.groupInfo();
  },

  // sort with the current comparator
  sort: function() {
    this.collection.sort();
    // this.selectFirst();
  },
  sortAgree: function(e) {
    this.collection.comparator = comparatorAgree;
    this.collection.sort();
    // this.selectFirst();
    this.selectSortModes("#sortAgree");
  },
  sortDisagree: function(e) {
    this.collection.comparator = comparatorDisagree;
    this.collection.sort();
    // this.selectFirst();
    this.selectSortModes("#sortDisagree");
  },
  sortDivisive: function(e) {
    this.collection.comparator = comparatorDivisive;
    this.collection.sort();
    // this.selectFirst();
    this.selectSortModes("#sortDivisive");
  },
  sortRepness: function(e) {
    // There are no buttons associated with this.
    this.collection.comparator = sortRepness;
    this.collection.sort();
    // this.selectFirst();
  },
  useCarousel: function() {
    return true;
    // return !Utils.isIE8() && display.xs();
  },
  hideCarousel: function() {
    // this.$("#commentListView").show();
    // this.$("#carousel").hide();
  },
  showCarousel: function() {
    this.$("#commentListView").hide();
    this.$("#carousel").show();
  },
  updateSearch: function(e) {
    this.searchString = e.target.value;
    this.deselectComments();
    // this.selectFirst();
  },
  deselectComments: function() {
    eb.trigger(eb.commentSelected, false);
  },
  renderWithCarousel: function(gid) {
    var that = this;
    $(el_carouselSelector).html("");
    // $(el_carouselSelector).css("overflow", "hidden");

    // $(el_carouselSelector).append("

");
    $(el_carouselSelector).append("

");

    var results = $("#smallWindow");
    results.addClass("owl-carousel");
    // results.css('background-color', 'yellow');

    if (results.data('owlCarousel')) {
      results.data('owlCarousel').destroy();
    }
    results.owlCarousel({
      items : NUMBER_OF_REPRESENTATIVE_COMMENTS_TO_SHOW, //3 items above 1000px browser width
      // itemsDesktop : [1000,5], //5 items between 1000px and 901px
      // itemsDesktopSmall : [900,3], // betweem 900px and 601px
      // itemsTablet: [600,2], //2 items between 600 and 0
      // itemsMobile : false // itemsMobile disabled - inherit from itemsTablet option
       singleItem : true,
       // autoHeight : true,
      afterInit : function(elem){
        var that = this;
        if (!display.xs()) {
          that.owlControls.prependTo(elem);
        }
      },
       afterMove: (function() {return function() {
          var tid = indexToTid[this.currentItem];
          setTimeout(function() {
              eb.trigger(eb.commentSelected, tid);
          }, 100);

      }}())
    });

    $(el_carouselSelector).on("click", function(e) {
      var owl = $("#smallWindow").data('owlCarousel');
      // var $comment = $(e);
      var index = $(e.target).data("idx");
      if (_.isNumber(index)) {
        owl.goTo(index);
      }
      // alert(e);
    });

    var indexToTid = [];

    var groupMode = gid !== -1;

    var info = that.groupInfo();
    _.each(this.collection.filter(function(item) {
        return _.contains(that.tidsForGroup, item.get('tid'));
      }),
      function(c) {
        var tid = c.get('tid');
        indexToTid.push(tid);
        var header;
        if (groupMode) {
          var v = info.votes[tid];
          var percent = (v.gA_total / info.count * 100) >> 0; // WARNING duplicated in analyze-comment.js
          header =
              "▲ " + percent + "%" +
              "("+ v.gA_total+"/"+info.count +") of this group agreed";
        } else {
          header =
            "▲ " + c.get("A") + "" +
            "▼ " + c.get("D") + "";
        }
        var html =
          "
" +
            "
" +
              header +
            "
" +
            c.get("txt") +
          "
";
        results.data('owlCarousel').addItem(html);
      });
      // Auto-select the first comment.
    eb.trigger(eb.commentSelected, indexToTid[0]);
    // $(el_carouselSelector).find(".query_result_item").first().trigger("click");
  },
  initialize: function(options) {
    var that = this;
    this.collection = options.collection;
    this.collection.comparator = comparatorAgree;

    var getTidsForGroup = options.getTidsForGroup;

    this.fetcher = options.fetcher;

    // TODO MOVE THIS LOGIC TO THE GROUP-SPECIFIC CODE...
    // this is getting crappy.

    function doFetch(gid) {
      that.collection.firstFetchPromise.then(function() {
        if (gid === -1) {
          that.$("#commentSearch").show();
          that.$("#commentSort").show();
          // that.$("#groupStats").hide();
          that.sortEnabled = true;
          that.searchEnabled = true;
          that.tidsForGroup = null;
          that.sortAgree();
          that.renderWithCarousel(gid);
          // that.selectFirst();
        } else {
          that.$("#commentSearch").hide();
          that.$("#commentSort").hide();
          // that.$("#groupStats").show();
          that.sortEnabled = false;
          that.searchEnabled = false;
          getTidsForGroup(gid, NUMBER_OF_REPRESENTATIVE_COMMENTS_TO_SHOW).then(function(o) {
            that.tidsForGroup = o.tids;
            that.collection.updateRepness(o.tidToR);
            that.sortRepness();
            that.renderWithCarousel(gid);
            // that.selectFirst();
          });
        }
      });
    } // End doFetch

    if (!_.isUndefined(options.gid)) {
      doFetch(options.gid);
    } else {
      eb.on(eb.clusterClicked, function(gid) {
        doFetch(gid);
      });
    }
  }
});
<commit_msg>add (currently disabled) CSS3 flag for carousel<commit_after>var display = require("../util/display");
var eb = require("../eventBus");
var template = require("../tmpl/analyze-group");
var CommentModel = require("../models/comment");
var Handlebones = require("handlebones");
var Utils = require("../util/utils");

var NUMBER_OF_REPRESENTATIVE_COMMENTS_TO_SHOW = 5;

var el_carouselSelector = "#carousel";

function bbCompare(propertyName, a, b) {
  var x = b.get(propertyName) - a.get(propertyName);
  return x;
}
function bbCompareAscending(propertyName, a, b) {
  return -bbCompare(propertyName, a, b);
}
function compareTieBreaker(a, b) {
  var x = bbCompare("stars", a, b);
  x = x || a.get("txt").length - b.get("txt").length; // shorter comments first
  x = x || bbCompare("created", a, b);
  // x = x || (b.get("txt").toLowerCase() < a.get("txt").toLowerCase()) ? 1 : -1; // alphabetic
  return x;
}
function sortRepness(a, b) {
  var x = bbCompare("repness", a, b);
  return x || compareTieBreaker(a, b);
}
function comparatorAgree(a, b) {
  var x = bbCompare("A", a, b);
  x = x || bbCompareAscending("D", a, b);
  return x || compareTieBreaker(a, b);
}
function comparatorDisagree(a, b) {
  var x = bbCompare("D", a, b);
  x = x || bbCompareAscending("A", a, b);
  return x || compareTieBreaker(a, b);
}
function comparatorDivisive(a, b) {
  var b_agrees = b.get("A");
  var b_disagrees = b.get("D");
  var a_agrees = a.get("A");
  var a_disagrees = a.get("D");
  var b_product = b_agrees * b_disagrees;
  var a_product = a_agrees * a_disagrees;
  var b_sum = b_agrees + b_disagrees + 1; // Add 1 to prevent divide-by-zero
  var a_sum = a_agrees + a_disagrees + 1; // Add 1 to prevent divide-by-zero
  var x = b_product/b_sum - a_product/a_sum;
  x = x || bbCompareAscending("A", a, b);
  return x || compareTieBreaker(a, b);
}

function comparatorStars(a, b) {
  var x = bbCompare("stars", a, b);
  return x || compareTieBreaker(a, b);
}

module.exports = Handlebones.View.extend({
    name: "analyze-global-view",
    template: template,
    tidsForGroup: null,
    events: {
      "click #sortAgree": "sortAgree",
      "click #sortDisagree": "sortDisagree",
      "click #sortDivisive": "sortDivisive",
      "keyup input": "updateSearch",
      "propertychange input": "updateSearch",
      submit: function(e) {
        e.preventDefault();
      },
      // "rendered:collection": function() {
      //   this.selectFirst();
      //   console.log('rendered:collection');
      // },
      rendered: function() {
        var that = this;
        var items = this.$(".query_result_item");
        items.on("mouseover", function() {
            $(this).addClass("hover");
        });
        items.on("mouseout", function() {
            $(this).removeClass("hover");
        });
      }
    },
    selectSortModes: function(chosenButtonSelector) {
      this.$("#sortAgree,#sortDisagree,#sortDivisive").removeClass("enabled");
      this.$(chosenButtonSelector).addClass("enabled");
    },
    selectFirst: function() {

    },
  searchEnabled: true,
  sortEnabled: true,

  groupInfo: function() {
    return this.parent.groupInfo();
  },

  // sort with the current comparator
  sort: function() {
    this.collection.sort();
    // this.selectFirst();
  },
  sortAgree: function(e) {
    this.collection.comparator = comparatorAgree;
    this.collection.sort();
    // this.selectFirst();
    this.selectSortModes("#sortAgree");
  },
  sortDisagree: function(e) {
    this.collection.comparator = comparatorDisagree;
    this.collection.sort();
    // this.selectFirst();
    this.selectSortModes("#sortDisagree");
  },
  sortDivisive: function(e) {
    this.collection.comparator = comparatorDivisive;
    this.collection.sort();
    // this.selectFirst();
    this.selectSortModes("#sortDivisive");
  },
  sortRepness: function(e) {
    // There are no buttons associated with this.
    this.collection.comparator = sortRepness;
    this.collection.sort();
    // this.selectFirst();
  },
  useCarousel: function() {
    return true;
    // return !Utils.isIE8() && display.xs();
  },
  hideCarousel: function() {
    // this.$("#commentListView").show();
    // this.$("#carousel").hide();
  },
  showCarousel: function() {
    this.$("#commentListView").hide();
    this.$("#carousel").show();
  },
  updateSearch: function(e) {
    this.searchString = e.target.value;
    this.deselectComments();
    // this.selectFirst();
  },
  deselectComments: function() {
    eb.trigger(eb.commentSelected, false);
  },
  renderWithCarousel: function(gid) {
    var that = this;
    $(el_carouselSelector).html("");
    // $(el_carouselSelector).css("overflow", "hidden");

    // $(el_carouselSelector).append("

");
    $(el_carouselSelector).append("

");

    var results = $("#smallWindow");
    results.addClass("owl-carousel");
    // results.css('background-color', 'yellow');

    if (results.data('owlCarousel')) {
      results.data('owlCarousel').destroy();
    }
    results.owlCarousel({
      items : NUMBER_OF_REPRESENTATIVE_COMMENTS_TO_SHOW, //3 items above 1000px browser width
      // itemsDesktop : [1000,5], //5 items between 1000px and 901px
      // itemsDesktopSmall : [900,3], // betweem 900px and 601px
      // itemsTablet: [600,2], //2 items between 600 and 0
      // itemsMobile : false // itemsMobile disabled - inherit from itemsTablet option
       singleItem : true,
       // autoHeight : true,
     //  transitionStyle: "fade", // this should enable CSS3 transitions
      afterInit : function(elem){
        var that = this;
        if (!display.xs()) {
          that.owlControls.prependTo(elem);
        }
      },
       afterMove: (function() {return function() {
          var tid = indexToTid[this.currentItem];
          setTimeout(function() {
              eb.trigger(eb.commentSelected, tid);
          }, 100);

      }}())
    });

    $(el_carouselSelector).on("click", function(e) {
      var owl = $("#smallWindow").data('owlCarousel');
      // var $comment = $(e);
      var index = $(e.target).data("idx");
      if (_.isNumber(index)) {
        owl.goTo(index);
      }
      // alert(e);
    });

    var indexToTid = [];

    var groupMode = gid !== -1;

    var info = that.groupInfo();
    _.each(this.collection.filter(function(item) {
        return _.contains(that.tidsForGroup, item.get('tid'));
      }),
      function(c) {
        var tid = c.get('tid');
        indexToTid.push(tid);
        var header;
        if (groupMode) {
          var v = info.votes[tid];
          var percent = (v.gA_total / info.count * 100) >> 0; // WARNING duplicated in analyze-comment.js
          header =
              "▲ " + percent + "%" +
              "("+ v.gA_total+"/"+info.count +") of this group agreed";
        } else {
          header =
            "▲ " + c.get("A") + "" +
            "▼ " + c.get("D") + "";
        }
        var html =
          "
" +
            "
" +
              header +
            "
" +
            c.get("txt") +
          "
";
        results.data('owlCarousel').addItem(html);
      });
      // Auto-select the first comment.
    eb.trigger(eb.commentSelected, indexToTid[0]);
    // $(el_carouselSelector).find(".query_result_item").first().trigger("click");
  },
  initialize: function(options) {
    var that = this;
    this.collection = options.collection;
    this.collection.comparator = comparatorAgree;

    var getTidsForGroup = options.getTidsForGroup;

    this.fetcher = options.fetcher;

    // TODO MOVE THIS LOGIC TO THE GROUP-SPECIFIC CODE...
    // this is getting crappy.

    function doFetch(gid) {
      that.collection.firstFetchPromise.then(function() {
        if (gid === -1) {
          that.$("#commentSearch").show();
          that.$("#commentSort").show();
          // that.$("#groupStats").hide();
          that.sortEnabled = true;
          that.searchEnabled = true;
          that.tidsForGroup = null;
          that.sortAgree();
          that.renderWithCarousel(gid);
          // that.selectFirst();
        } else {
          that.$("#commentSearch").hide();
          that.$("#commentSort").hide();
          // that.$("#groupStats").show();
          that.sortEnabled = false;
          that.searchEnabled = false;
          getTidsForGroup(gid, NUMBER_OF_REPRESENTATIVE_COMMENTS_TO_SHOW).then(function(o) {
            that.tidsForGroup = o.tids;
            that.collection.updateRepness(o.tidToR);
            that.sortRepness();
            that.renderWithCarousel(gid);
            // that.selectFirst();
          });
        }
      });
    } // End doFetch

    if (!_.isUndefined(options.gid)) {
      doFetch(options.gid);
    } else {
      eb.on(eb.clusterClicked, function(gid) {
        doFetch(gid);
      });
    }
  }
});
<|endoftext|>


<commit_before>(function($) {
	ALLOWKEY = true;
	LOADMORE = false;
	// using jQuery
	function getCookie(name) {
		var cookieValue = null;
		if (document.cookie && document.cookie != '') {
			var cookies = document.cookie.split(';');
			for (var i = 0; i < cookies.length; i++) {
				var cookie = $.trim(cookies[i]);
				// Does this cookie string begin with the name we want?
				if (cookie.substring(0, name.length + 1) == (name + '=')) {
					cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
					break;
				}
			}
		}
		return cookieValue;
	}
	var csrftoken = getCookie('csrftoken');

	function csrfSafeMethod(method) {
		// these HTTP methods do not require CSRF protection
		return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
	}
	$.ajaxSetup({
		crossDomain: false, // obviates need for sameOrigin test
		beforeSend: function(xhr, settings) {
			if (!csrfSafeMethod(settings.type)) {
				xhr.setRequestHeader("X-CSRFToken", csrftoken);
			}
		}
	});
	// 登录页面
	$("#id_captcha_1").addClass("form-control").css({
		width: '50%',
		display: 'inline-block'
	});
	if ($("#CAPTCHA")) {
		var new_a = $("");
		$("#id_captcha_1").attr("placeholder", "点击图片刷新");
		$("#CAPTCHA>img").css({
			width: '29%',
			height: '42px',
		});
		new_a.append($("#CAPTCHA>img"));
		$("#CAPTCHA").prepend(new_a);
		$("#CAPTCHA>a.recaptcha").click(function(event) {
			$.get($("#CAPTCHA").data('url'), function(data) {
				$("#CAPTCHA>a>img").attr('src', data.image_url);
				$("#id_captcha_0").val(data.key);
			}, 'json');
			return false;
		});
	}
	// 按钮效果
	$('.input-group').on('focus', '.form-control', function() {
		$(this).closest('.input-group, .form-group').addClass('focus');
	}).on('blur', '.form-control', function() {
		$(this).closest('.input-group, .form-group').removeClass('focus');
	});
	// 导航栏高亮
	var navid = $('#NAVID').data('nav');
	if (navid) {
		$(".nav.navbar-nav.main>li").removeClass('active');
		$("#" + navid).addClass("active");
		$("#" + navid).parent().parent().addClass("active");
	}
	// 键盘翻页
	$(document).keydown(function(e) {
		if (ALLOWKEY && !LOADMORE) {
			var prev = $(".prev_page_a").eq(0).attr("href");
			var next = $(".next_page_a").eq(0).attr("href");
			switch (e.which) {
				case 37:
					location.href = prev;
					break;
				case 39:
					location.href = next;
					break;
			}
		}
	});
	// 双击滚动
	scroller = false;
	$(".pagecontent").dblclick(function() {
		position = window.scrollY;
		if (scroller) {
			clearInterval(scroller);
			scroller = false;
		} else {
			scroller = setInterval(function() {
				window.scrollTo(0, position);
				position += 1;
			}, 40);
		}
		return false;
	});
	// 判断夜间模式
	if (DATA_DIC["invert"] && DATA_DIC["is_page"]) {
		$('.inv').toggleClass('invert');
		$('.navbar').toggleClass('navbar-inverse');
		$('.btn').toggleClass('transparent_class');
		$('.panel.panel-default .btn').removeClass('transparent_class');
	}
	// 切换夜间模式
	$(".btn.invert").die().live('click', function() {
		$('.inv').toggleClass('invert');
		$('.navbar').toggleClass('navbar-inverse');
		$('.btn').toggleClass('transparent_class');
		$('.panel.panel-default .btn').removeClass('transparent_class');
		$.get("./?invert=1", function(data) {}, 'json');
		return false;
	});
	// 加载gzip文件
	var load_zip = function(elements){
		elements.each(function(index){
			var this_ele = $(this);
			$.get(this_ele.data('pageurl'), function(data){
				console.log(this_ele);
				$(data).appendTo(this_ele);
				this_ele.removeClass('noload');
			});
		});
	}
	load_zip($(".pagecontent.noload"));
	// 加载后续章节
	$(".readnall").die().live('click', function() {
		var this_a = $(event.currentTarget);
		var page_number = this_a.data('pn');
		$.ajax({
			type: 'get',
			cache: 'false',
			url: '/nallpage/' + page_number + '/',
			dataType: 'json',
			success: function(data) {
				if (data.success) {
					LOADMORE = true;
					$('.nextbox').remove();
					$('#FIELD').append($(data.data));
					$('.col-md-12.text-center.pagebutton').remove();
					auto_width_pg();
					$(".PGDOWN").click(function() {
						window.scrollTo(0, window.scrollY + window.innerHeight - 20);
					});
					$(".PGUP").click(function() {
						window.scrollTo(0, window.scrollY - window.innerHeight + 20);
					});
					load_zip($(".pagecontent.noload"));
				}
			},
			beforeSend: function() {
				var target = $('.nextbox').eq(0);
				$('.nextbox a').hide();
				var opts = {
					lines: 15,
					length: 23,
					width: 4,
					radius: 20,
					corners: 0,
					rotate: 9,
					trail: 77,
					speed: 1.0,
					direction: 1,
					shadow: false,
					color: '#58d68d'
				};
				target.spin(opts);
			}
		})
	});
	// 添加书签
	$(".TBMABtn").die().live('click', function(event) {
		var this_a = $(event.currentTarget);
		var page_number = this_a.data('pn');
		$.post(DATA_DIC["add_bookmark_url"], {
			pageid: page_number
		}, function(data) {
			if (data.success) {
				$('#TBMA' + page_number).slideDown();
				setTimeout(function() {
					$('#TBMA' + page_number).slideUp()
				}, 2000);
			} else {
				$('#TBMAERR' + page_number).text(data.error_message);
				$('#TBMAERR' + page_number).slideDown();
				setTimeout(function() {
					$('#TBMAERR' + page_number).slideUp()
				}, 5000);
			}
		}, 'json');
		return false;
	});
	// 触屏翻页
	function auto_width_pg() {
		content_width_haf = parseInt($(".pagecontent").width() / 2);
		$(".PGDOWN").css("left", content_width_haf + 15);
		$(".PGDOWN").css("width", content_width_haf + "px");
		$(".PGUP").css("width", content_width_haf + "px");
	};
	auto_width_pg();
	$(".PGDOWN").click(function() {
		window.scrollTo(0, window.scrollY + window.innerHeight - 20);
	});
	$(".PGUP").click(function() {
		window.scrollTo(0, window.scrollY - window.innerHeight + 20);
	});
	// 更新图片章节
	$(".pagefixpic").die().live('click', function(event) {
		var this_a = $(event.currentTarget);
		$.post(this_a.data('url'), {}, function(data) {
			if (data.success) {
				var alert_window = this_a.parent().parent().find(".alert");
				alert_window.slideDown();
				setTimeout(function() {
					alert_window.slideUp()
				}, 10000);
				check_page_fn = function() {
					$.get(this_a.data('churl'), function(data) {
						if (data.success) {
							if (data.data.status === 'DONE') {
								clearInterval(check_page);
								location.reload(true);
							}
						} else {
							clearInterval(check_page);
							alert(data.error_message);
						}
					}, 'json');
				}
				check_page = setInterval(check_page_fn, 1500);
				check_page_fn();
			} else {
				alert(data.error_message);
			}
		}, 'json');
		return false;
	});
	// 编辑段落内容
	if ($(".modal").length) {
		$(".pagecontent>p").die().live('click', function(event) {
			var this_p = $(event.currentTarget);
			$(".modal").modal('toggle');
			ALLOWKEY = false;
			$("#Lineedit").find("textarea").val(this_p.text());
			$(document.getElementsByName("linenum")).val(this_p.data("parnum"));
			$(document.getElementsByName("pagenum")).val(this_p.parent().data("pagenum"));
			$("#Lineedit").unbind('submit');
			$("#Lineedit").submit(function() {
				$.post($("#Lineedit").attr("action"), $("#Lineedit").serializeArray(), function(data) {
					if (data.success) {
						$("#Savelinedone").text("保存成功!");
						$("#Savelinedone").slideDown();
						setTimeout(function() {
							$("#Savelinedone").slideUp();
							$(".modal").modal('toggle');
							ALLOWKEY = true;
						}, 1000);
						var page_div = this_p.parent();
						page_div.find('p').remove();
						$(data.data).appendTo(page_div);
					} else {
						$("#Savelinedone").text(data.error_message);
						$("#Savelinedone").slideDown();
						setTimeout(function() {
							$("#Savelinedone").slideUp();
						}, 2000);
					}
				}, 'json');
				return false;
			});
			$("#Delline").die().live('click', function() {
				var post_url = this_p.parent().data("dellurl");
				$.post(post_url, {
					"ln": this_p.data("parnum")
				}, function(data) {
					if (data.success) {
						$("#Savelinedone").text("删除成功!");
						$("#Savelinedone").slideDown();
						setTimeout(function() {
							$("#Savelinedone").slideUp();
							$(".modal").modal('toggle');
							ALLOWKEY = true;
						}, 1000);
						var page_div = this_p.parent();
						page_div.find('p').remove();
						$(data.data).appendTo(page_div);
					} else {
						$("#Savelinedone").text(data.error_message);
						$("#Savelinedone").slideDown();
						setTimeout(function() {
							$("#Savelinedone").slideUp();
						}, 2000);
					}
				}, 'json');
			});
		});
		$("#Closemodal").die().live('click', function() {
			$(".modal").modal('toggle');
			ALLOWKEY = true;
		});
	}
})(jQuery);
<commit_msg>fix 夜间模式 bug<commit_after>(function($) {
	ALLOWKEY = true;
	LOADMORE = false;
	// using jQuery
	function getCookie(name) {
		var cookieValue = null;
		if (document.cookie && document.cookie != '') {
			var cookies = document.cookie.split(';');
			for (var i = 0; i < cookies.length; i++) {
				var cookie = $.trim(cookies[i]);
				// Does this cookie string begin with the name we want?
				if (cookie.substring(0, name.length + 1) == (name + '=')) {
					cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
					break;
				}
			}
		}
		return cookieValue;
	}
	var csrftoken = getCookie('csrftoken');

	function csrfSafeMethod(method) {
		// these HTTP methods do not require CSRF protection
		return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
	}
	$.ajaxSetup({
		crossDomain: false, // obviates need for sameOrigin test
		beforeSend: function(xhr, settings) {
			if (!csrfSafeMethod(settings.type)) {
				xhr.setRequestHeader("X-CSRFToken", csrftoken);
			}
		}
	});
	// 登录页面
	$("#id_captcha_1").addClass("form-control").css({
		width: '50%',
		display: 'inline-block'
	});
	if ($("#CAPTCHA")) {
		var new_a = $("");
		$("#id_captcha_1").attr("placeholder", "点击图片刷新");
		$("#CAPTCHA>img").css({
			width: '29%',
			height: '42px',
		});
		new_a.append($("#CAPTCHA>img"));
		$("#CAPTCHA").prepend(new_a);
		$("#CAPTCHA>a.recaptcha").click(function(event) {
			$.get($("#CAPTCHA").data('url'), function(data) {
				$("#CAPTCHA>a>img").attr('src', data.image_url);
				$("#id_captcha_0").val(data.key);
			}, 'json');
			return false;
		});
	}
	// 按钮效果
	$('.input-group').on('focus', '.form-control', function() {
		$(this).closest('.input-group, .form-group').addClass('focus');
	}).on('blur', '.form-control', function() {
		$(this).closest('.input-group, .form-group').removeClass('focus');
	});
	// 导航栏高亮
	var navid = $('#NAVID').data('nav');
	if (navid) {
		$(".nav.navbar-nav.main>li").removeClass('active');
		$("#" + navid).addClass("active");
		$("#" + navid).parent().parent().addClass("active");
	}
	// 键盘翻页
	$(document).keydown(function(e) {
		if (ALLOWKEY && !LOADMORE) {
			var prev = $(".prev_page_a").eq(0).attr("href");
			var next = $(".next_page_a").eq(0).attr("href");
			switch (e.which) {
				case 37:
					location.href = prev;
					break;
				case 39:
					location.href = next;
					break;
			}
		}
	});
	// 双击滚动
	scroller = false;
	$(".pagecontent").dblclick(function() {
		position = window.scrollY;
		if (scroller) {
			clearInterval(scroller);
			scroller = false;
		} else {
			scroller = setInterval(function() {
				window.scrollTo(0, position);
				position += 1;
			}, 40);
		}
		return false;
	});
	// 判断夜间模式
	if (DATA_DIC["invert"] && DATA_DIC["is_page"]) {
		$('.inv').addClass('invert');
		$('.navbar').addClass('navbar-inverse');
		$('#FIELD .text-center .btn').addClass('transparent_class');
	}
	// 切换夜间模式
	$(".btn.invert").die().live('click', function() {
		$('.inv').toggleClass('invert');
		$('.navbar').toggleClass('navbar-inverse');
		$('#FIELD .text-center .btn').toggleClass('transparent_class');
		$.get("./?invert=1", function(data) {}, 'json');
		return false;
	});
	// 加载gzip文件
	var load_zip = function(elements){
		elements.each(function(index){
			var this_ele = $(this);
			$.get(this_ele.data('pageurl'), function(data){
				console.log(this_ele);
				$(data).appendTo(this_ele);
				this_ele.removeClass('noload');
			});
		});
	}
	load_zip($(".pagecontent.noload"));
	// 加载后续章节
	$(".readnall").die().live('click', function() {
		var this_a = $(event.currentTarget);
		var page_number = this_a.data('pn');
		$.ajax({
			type: 'get',
			cache: 'false',
			url: '/nallpage/' + page_number + '/',
			dataType: 'json',
			success: function(data) {
				if (data.success) {
					LOADMORE = true;
					$('.nextbox').remove();
					$('#FIELD').append($(data.data));
					$('.col-md-12.text-center.pagebutton').remove();
					auto_width_pg();
					$(".PGDOWN").click(function() {
						window.scrollTo(0, window.scrollY + window.innerHeight - 20);
					});
					$(".PGUP").click(function() {
						window.scrollTo(0, window.scrollY - window.innerHeight + 20);
					});
					load_zip($(".pagecontent.noload"));
				}
			},
			beforeSend: function() {
				var target = $('.nextbox').eq(0);
				$('.nextbox a').hide();
				var opts = {
					lines: 15,
					length: 23,
					width: 4,
					radius: 20,
					corners: 0,
					rotate: 9,
					trail: 77,
					speed: 1.0,
					direction: 1,
					shadow: false,
					color: '#58d68d'
				};
				target.spin(opts);
			}
		})
	});
	// 添加书签
	$(".TBMABtn").die().live('click', function(event) {
		var this_a = $(event.currentTarget);
		var page_number = this_a.data('pn');
		$.post(DATA_DIC["add_bookmark_url"], {
			pageid: page_number
		}, function(data) {
			if (data.success) {
				$('#TBMA' + page_number).slideDown();
				setTimeout(function() {
					$('#TBMA' + page_number).slideUp()
				}, 2000);
			} else {
				$('#TBMAERR' + page_number).text(data.error_message);
				$('#TBMAERR' + page_number).slideDown();
				setTimeout(function() {
					$('#TBMAERR' + page_number).slideUp()
				}, 5000);
			}
		}, 'json');
		return false;
	});
	// 触屏翻页
	function auto_width_pg() {
		content_width_haf = parseInt($(".pagecontent").width() / 2);
		$(".PGDOWN").css("left", content_width_haf + 15);
		$(".PGDOWN").css("width", content_width_haf + "px");
		$(".PGUP").css("width", content_width_haf + "px");
	};
	auto_width_pg();
	$(".PGDOWN").click(function() {
		window.scrollTo(0, window.scrollY + window.innerHeight - 20);
	});
	$(".PGUP").click(function() {
		window.scrollTo(0, window.scrollY - window.innerHeight + 20);
	});
	// 更新图片章节
	$(".pagefixpic").die().live('click', function(event) {
		var this_a = $(event.currentTarget);
		$.post(this_a.data('url'), {}, function(data) {
			if (data.success) {
				var alert_window = this_a.parent().parent().find(".alert");
				alert_window.slideDown();
				setTimeout(function() {
					alert_window.slideUp()
				}, 10000);
				check_page_fn = function() {
					$.get(this_a.data('churl'), function(data) {
						if (data.success) {
							if (data.data.status === 'DONE') {
								clearInterval(check_page);
								location.reload(true);
							}
						} else {
							clearInterval(check_page);
							alert(data.error_message);
						}
					}, 'json');
				}
				check_page = setInterval(check_page_fn, 1500);
				check_page_fn();
			} else {
				alert(data.error_message);
			}
		}, 'json');
		return false;
	});
	// 编辑段落内容
	if ($(".modal").length) {
		$(".pagecontent>p").die().live('click', function(event) {
			var this_p = $(event.currentTarget);
			$(".modal").modal('toggle');
			ALLOWKEY = false;
			$("#Lineedit").find("textarea").val(this_p.text());
			$(document.getElementsByName("linenum")).val(this_p.data("parnum"));
			$(document.getElementsByName("pagenum")).val(this_p.parent().data("pagenum"));
			$("#Lineedit").unbind('submit');
			$("#Lineedit").submit(function() {
				$.post($("#Lineedit").attr("action"), $("#Lineedit").serializeArray(), function(data) {
					if (data.success) {
						$("#Savelinedone").text("保存成功!");
						$("#Savelinedone").slideDown();
						setTimeout(function() {
							$("#Savelinedone").slideUp();
							$(".modal").modal('toggle');
							ALLOWKEY = true;
						}, 1000);
						var page_div = this_p.parent();
						page_div.find('p').remove();
						$(data.data).appendTo(page_div);
					} else {
						$("#Savelinedone").text(data.error_message);
						$("#Savelinedone").slideDown();
						setTimeout(function() {
							$("#Savelinedone").slideUp();
						}, 2000);
					}
				}, 'json');
				return false;
			});
			$("#Delline").die().live('click', function() {
				var post_url = this_p.parent().data("dellurl");
				$.post(post_url, {
					"ln": this_p.data("parnum")
				}, function(data) {
					if (data.success) {
						$("#Savelinedone").text("删除成功!");
						$("#Savelinedone").slideDown();
						setTimeout(function() {
							$("#Savelinedone").slideUp();
							$(".modal").modal('toggle');
							ALLOWKEY = true;
						}, 1000);
						var page_div = this_p.parent();
						page_div.find('p').remove();
						$(data.data).appendTo(page_div);
					} else {
						$("#Savelinedone").text(data.error_message);
						$("#Savelinedone").slideDown();
						setTimeout(function() {
							$("#Savelinedone").slideUp();
						}, 2000);
					}
				}, 'json');
			});
		});
		$("#Closemodal").die().live('click', function() {
			$(".modal").modal('toggle');
			ALLOWKEY = true;
		});
	}
})(jQuery);
<|endoftext|>