define([
    'app',
    'backbone',
    'backbone.marionette',
    'hbs!../templates/module',
    'underscore',
    'localforage',
    './BiddingStatsView',
    'bootstrap/tooltip'
  ],
  function (App, Backbone, Marionette, template, _, localforage, BiddingStatsView) {
    'use strict';

    var searchPreferences = {};

    return Marionette.LayoutView.extend({
      template: template,
      regions: {
        biddingStatsRegion: '#bidding-stats'
      },
      initialize: function () {

        if (this.model.get('section') === 'corspedia') {
          var formElements = {
            'faculty': '#faculty',
            'account': '#account',
            'student': 'input:radio[name="student-radios"]'
          };

          var defaults = {
            'faculty': 'Arts & Social Sciences',
            'account': 'P',
            'student': 'true'
          };

          var that = this;
          var loadedItems = 0;
          _.each(formElements, function (selector, item) {
            localforage.getItem(item, function (value) {
              if (!value) {
                value = defaults[item];
                localforage.setItem(item, value);
              }
              $(selector).val([value]);
              searchPreferences[item] = value;
              loadedItems++;
              if (loadedItems === _.keys(formElements).length) {
                that.showBiddingStatsRegion(true);
              }
            });
          });
        }
      },
      events: {
        'change #faculty, input:radio[name="student-radios"], #account': 'updateCorspedia',
        'click .show-full-desc': 'showFullDescription',
        'click #show-all-stats': 'showAllStats',
        'click .add': function(event) {
          var qtipContent;
          if (App.request('isModuleSelected', this.model.get('module').ModuleCode)) {
            qtipContent = 'Already added!';
          } else {
            qtipContent = 'Added!';
            App.request('addModule', this.model.get('module').ModuleCode);
          }
          $(event.currentTarget).qtip({
            content: qtipContent,
            show: {
              event: false,
              ready: true
            },
            hide: {
              event: false,
              inactive: 1000
            }
          });
        }
      },
      onShow: function () {
        var module = this.model.get('module');
        var code = module.ModuleCode;

        var disqusShortname = 'nusmods';

        (function () {
          if (typeof disqus_domain !== 'undefined') {
            DISQUSWIDGETS.domain = 'disqus.com';
          }
          DISQUSWIDGETS.forum = disqusShortname;
          DISQUSWIDGETS.getCount();
        })();

        if (this.model.get('section') === 'reviews') {
          // Only reset Disqus when showing reviews section
          if (!window.DISQUS) {
            (function() {
              var dsq = document.createElement('script');
              dsq.type = 'text/javascript';
              dsq.async = true;
              dsq.src = '//nusmods.disqus.com/embed.js';
              (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
            })();
          } else {
            DISQUS.reset({
              reload: true,
              config: function () {
                this.page.identifier = code;
                this.page.title = code + ' ' + module.ModuleTitle + ' · Reviews';
                this.page.url = 'http://nusmods.com/modules/' + code + '/reviews';
              }
            });
          }
        }
        $('.nm-help').tooltip();
      },
      showFullDescription: function () {
        $('.module-desc').addClass('module-desc-more');
        return false;
      },
      showAllStats: function () {
        this.showBiddingStatsRegion(false);
      },
      updateCorspedia: function ($ev) {
        var $target = $($ev.target);
        $target.blur();
        var property = $target.attr('data-pref-type');
        var value = $target.val();
        if (this.savePreference(property, value)) {
          searchPreferences[property] = value;
          this.showBiddingStatsRegion(true);
        }
      },
      showBiddingStatsRegion: function (displayFiltered) {
        var biddingStatsDeepCopy = $.extend(true, {},
          this.model.attributes.module.FormattedCorsBiddingStats);
        var biddingStatsModel = new Backbone.Model({stats: biddingStatsDeepCopy});
        var biddingStatsView = new BiddingStatsView({model: biddingStatsModel});

        var faculty = searchPreferences.faculty;
        var accountType = searchPreferences.account;
        var newStudent = searchPreferences.student === 'true';

        if (faculty && faculty !== 'default' && accountType && displayFiltered) {
          biddingStatsView.filterStats(faculty, accountType, newStudent);
        }

        this.biddingStatsRegion.show(biddingStatsView);
      },
      savePreference: function (property, value) {
        if (property === 'faculty' && value === 'default') {
          alert('You have to select a faculty.');
          localforage.getItem(property, function (value) {
            $('#faculty').val(value);
          });
          return false;
        }
        localforage.setItem(property, value);
        return true;
      }
    });
  });

@@ -2480,352 +2480,428 @@
     
-(function () %7B%0A          if (typeof disqus_domain !== 'undefined') %7B%0A            DISQUSWIDGETS.domain = 'disqus.com';%0A    
+if (this.model.get('section') === 'reviews') %7B%0A          // Only reset Disqus when showing reviews section%0A          var url = 'http://nusmods.com/modules/' + code + '/reviews';%0A
       
-%7D%0A
     
-      DISQUSWIDGETS.forum = disqusShortname;%0A          DISQUSWIDGETS.getCount();%0A        %7D)();%0A%0A        if (this.model.get('section') === 'reviews') %7B%0A          // Only reset Disqus when showing reviews section
+var title = code + ' ' + module.ModuleTitle + ' %C2%B7 Reviews';%0A          if (!window.DISQUS) %7B%0A            window.disqus_shortname = disqusShortname;%0A            window.disqus_identifier = code;%0A            window.disqus_title = title;
 %0A   
@@ -2907,37 +2907,43 @@
         
-if (!
+  
 window.
-DISQUS) %7B
+disqus_url = url;%0A
 %0A       
@@ -3482,182 +3482,329 @@
 e = 
-code + ' ' + module.ModuleTitle + ' %C2%B7 Reviews';%0A                this.page.url = 'http://nusmods.com/modules/' + code + '/reviews';%0A              %7D%0A            %7D);%0A          %7D
+title;%0A                this.page.url = url;%0A              %7D%0A            %7D);%0A          %7D%0A        %7D%0A%0A        (function () %7B%0A          if (typeof disqus_domain !== 'undefined') %7B%0A            DISQUSWIDGETS.domain = 'disqus.com';%0A          %7D%0A          DISQUSWIDGETS.forum = disqusShortname;%0A          DISQUSWIDGETS.getCount();
 %0A   
@@ -3801,32 +3801,37 @@
 unt();%0A        %7D
+)();%0A
 %0A        $('.nm-

Initialise disqus variables for first load