<commit_before>/* global define */
define(['jquery', 'handlebars', 'fastclick', 'proposal_app', 'handlebars_helpers', 'piwik'], function($, Handlebars, FastClick, ProposalApp){
  // 'use strict';

  // The template code
  var templateSource = $('#proposal-template').html();

  // compile the template
  var template = Handlebars.compile(templateSource);
  var supportProposalTemplate = Handlebars.compile(document.getElementById('support-proposal-template').innerHTML);
  var loginTemplate = Handlebars.compile(document.getElementById('login-template').innerHTML);
  var resultsTemplate = Handlebars.compile(document.getElementById('results-template').innerHTML);
  var articleTemplate = Handlebars.compile(document.getElementById('article-template').innerHTML);
  var calendarTemplate = Handlebars.compile(document.getElementById('calendar-template').innerHTML);

  // The div/container that we are going to display the results in
  var resultsPlaceholder = document.getElementById('proposal-result');

  var logged_in = false;

  var loginButton;

  var lastHash = window.location.hash;

  var host = 'http://login.dialoga.gov.br';
  var serpro_captcha_clienteId = 'fdbcdc7a0b754ee7ae9d865fda740f17';
  var dialoga_community = 19195;
  var proposal_discussion = '103358'; //participa
  var cat_saude = 180;
  // var cat_seguranca_publica = 182;
  // var cat_educacao = 181;
  // var cat_reducao_da_pobreza = 183;
  var recaptchaSiteKey = '<KEY>';

  // There are two modes for development
  // 1: Remote API
  // 2: Local API
  // For (1) use port 3000 -> rails s
  // For (2) use port 3001 -> rails s -p 3001
  //
  // For (2) set at /etc/hosts:
  //
  //127.0.0.1  participa.br
  //127.0.0.1  dialoga.gov.br
  //127.0.0.1  login.dialoga.gov.br
  //127.0.0.1  noosfero.com
  //Detects for localhost settings
  var patt = new RegExp(':300[0-2]/');
  var localDevelopment = false;

  if(patt.test(window.location.href)){
    localDevelopment = true;
    patt = new RegExp(':3000/');

    if(patt.test(window.location.href)){
      host = 'http://noosfero.com:3000';
    }else if (new RegExp(':3001/').test(window.location.href)){
      host = 'http://noosfero.com:3001';
      dialoga_community = 104;
      //    proposal_discussion = '413'; //Eugênio
      proposal_discussion = '392'; //Evandro
      recaptchaSiteKey = '<KEY>'; //http://noosfero.com/
      cat_saude = 23;
    } else { //ABNER
      host = 'http://local.abner.com:3002';
      dialoga_community = 105;
      proposal_discussion = '392'; //Evandro
      recaptchaSiteKey = '<KEY>'; //http://noosfero.com/
      cat_saude = 23;
    }
  }


  var BARRA_ADDED = false;
  var HIDE_BARRA_DO_GOVERNO = false;

  var Main;
  window.Main = Main = (function(){

    var API = {
      articles: '',
      proposals: '/api/v1/articles/{topic_id}/children',

    };

    API.getProposalsURL = function (topicId){
      return host + replace(API.proposals, '{topic_id}', topicId);
    };

    function replace(str, pattern, value){
      return str.replace(new RegExp(pattern, 'g'), value);
    }

    function fillSignupForm(signupForm, user) {
      signupForm.find('#signup-user_email').val(user.email);
      signupForm.find('#signup-user_email').attr('disabled', true);
      signupForm.find('#signup-user_name').val(user.login);
      signupForm.find('#user_oauth_signup_token').val(user.signup_token);
      signupForm.find('#user_oauth_providers').val(user.oauth_providers);
      signupForm.find('div.password').hide();
      signupForm.find('div.password-confirmation').hide();
      signupForm.find('#signup-user_password').attr('required', false);
      signupForm.find('#user_password_confirmation').attr('required', false);
    };

    return {
      private_token: null,
      getProposalId: function() {
        var regexProposals = /\d.*\/propostas\/*.*/;
        var proposalId = 0;

        var hasProposal = regexProposals.test(location.hash);
        if( hasProposal ){
          var regexExtractProposal = /propostas\/*.*/;
          proposalId = regexExtractProposal.exec(location.hash)[0].split('/')[1];

        }

        return proposalId;
      },
      loadRandomProposal: function (topic_id, force) {
          /*var private_token = window.Main.private_token;*/
          var $noProposals = $('.no-proposals');
          var $loading = $('.loading');
          var $randomProposal = $('.random-proposal');
          var $body = $(document.body);
          var contextMain = this;

          // reset view
          $noProposals.hide();
          $loading.show();
          $randomProposal.html('');

          var url = API.getProposalsURL(topic_id);
          var childId = this.getProposalId();

          if(childId !== 0 && !force){
            url += '/' + childId;
          }
          //url += '?private_token=' + private_token + '&limit=1&order=random()&_='+new Date().getTime()+'&fields=id,name,slug,abstract,created_by&content_type=ProposalsDiscussionPlugin::Proposal';
          url += '?limit=1&order=random()&_='+new Date().getTime()+'&fields=id,name,slug,abstract,created_by&content_type=ProposalsDiscussionPlugin::Proposal';

          $.getJSON(url).done(function( data ) {
            $loading.hide();
            $('.support-proposal .alert').hide();

            data.articles = data.articles || [data.article];
            if(data.articles.length === 0) {
              $noProposals.show();
              return;
            }

            var article = data.articles[0];
            var parentTitle = $('#proposal-item-'+topic_id).find('.proposal-header .title').text();
            article.parent = {id: topic_id, title: parentTitle};
            $randomProposal.html(supportProposalTemplate(article));
            $body.off('click', '.vote-actions .skip');
            $body.on('click', '.vote-actions .skip', function(e) {
              e.preventDefault();
              contextMain.loadRandomProposal(topic_id, true);
            });
            $body.off('click', '.vote-actions .vote-action');
            $body.on('click', '.vote-actions .vote-action', function(e) {
              e.preventDefault();

              //Helps to prevent more than one vote per proposal
              var $button = $(this);
              var $proposal = $button.closest('.random-proposal');

              if(!logged_in) {
                $(this).closest('.require-login-container').find('.button-send a').click();
                return;
              }

              if(ProposalApp.hasProposalbeenVoted(article.id)){
                // console.debug("Proposta " + article.id + " já havia sido votada");
                Main.displaySuccess($button.closest('.support-proposal .section-content'), 'Seu voto já foi computado nesta proposta', 800);
                contextMain.loadRandomProposal(topic_id, true);
                return;
              }

              $.ajax({
                type: 'post',
                url: host + '/api/v1/articles/' + article.id + '/vote',
                data: {
                  value: $(this).data('vote-value'),
                  private_token: Main.private_token
                }
              }).done(function(data) {
                if(data.vote) {
                  // Main.displaySuccess($button.closest('.support-proposal .section-content'), '', 800);
                  $proposal.find('.abstract').hide();
                  $proposal.find('.vote-actions .like').hide();
                  $proposal.find('.vote-actions .dislike').hide();
                  // $proposal.find('.vote-actions .vote-result').hide();
                  var $successPanel = $('.success-panel').clone();
                  $successPanel.find('.icon').addClass('icon-proposal-sent');
                  $successPanel.find('.message').html('Voto realizado com sucesso');
                  $successPanel.removeClass('hide');
                  $proposal.prepend($successPanel);
                  $successPanel.show();
                  // $successPanel.css('top', Math.max(0, (($proposal.height() - $successPanel.outerHeight()) / 2) + $proposal.offset().top) + 'px');
                  // $successPanel.css('left', Math.max(0, (($proposal.width() - $successPanel.outerWidth()) / 2) + $proposal.offset().left) + 'px');
                } else {
                  $proposal.find('.abstract').hide();
                  $proposal.find('.vote-actions .like').hide();
                  $proposal.find('.vote-actions .dislike').hide();

                  var $successPanel = $('.success-panel').clone();
                  // $successPanel.find('.icon').addClass('icon-proposal-sent');
                  $successPanel.find('.message').html('Seu voto já foi computado nesta proposta');
                  $successPanel.removeClass('hide');
                  $proposal.prepend($successPanel);
                  $successPanel.show();
                  // Main.displaySuccess($button.closest('.support-proposal .section-content'), , 800);
                  // $successPanel.find('.message').html('Seu voto já foi computado nesta proposta');
                }
                // ProposalApp.addVotedProposal(article.id);
                // contextMain.loadRandomProposal(topic_id, true);
              });
            });

            $body.off('click', '.vote-result');
            $body.on('click', '.vote-result', function(e) {
              // e.preventDefault();

              var $this = $(this);
              var $proposalDetail = $this.parents('.proposal-detail');
              var $resultsContainer = $proposalDetail.find('.results-container');

              if($resultsContainer.css('display') === 'none') {
                Main.loadRanking($resultsContainer, topic_id, 1);
              } else {
                $proposalDetail.find('.experience-proposal-container').show();
                $proposalDetail.find('.talk-proposal-container').show();
                $resultsContainer.hide();

                // remove '/resultados' from URL
                window.location.hash = window.location.hash.split('/resultados')[0];
                e.preventDefault();
              }
            });

          }).fail(function(){
            $loading.hide();
            $('.support-proposal .alert').show();
          });
      },
      loadRanking: function($resultsContainer, topic_id, page) {
        $resultsContainer.find('.loading').show();
        $resultsContainer.find('.results-content').hide();

        var per_page = 10;
        //var url = host + '/api/v1/proposals_discussion_plugin/' + topic_id + '/ranking' + '?private_token=' + Main.private_token + '&per_page='+per_page+'&page='+page;
        var url = host + '/api/v1/proposals_discussion_plugin/' + topic_id + '/ranking' + '?per_page='+per_page+'&page='+page;
        $.getJSON(url).done(function( data, stats, xhr ) {
          data.pagination = {
            total: parseInt(xhr.getResponseHeader('Total')),
            per_page: parseInt(xhr.getResponseHeader('Per-Page')),
            page: page,
          };

          // hack: add title to result table
          data.title = $resultsContainer.closest('.categories').find('.proposal-header .title').text();

          $resultsContainer.html(resultsTemplate(data));
          $resultsContainer.find('.loading').hide();
          $resultsContainer.find('.results-content').show();
          $('.timeago').timeago();
          $resultsContainer.show();

          $('.footable').footable();

          if(data.pagination.total > data.pagination.per_page) {
            $resultsContainer.find('.paging').pagination({
              items: data.pagination.total,
              itemsOnPage: data.pagination.per_page,
              currentPage: data.pagination.page,
              prevText: '«',
              nextText: '»',
              cssStyle: 'compact-theme',
              onPageClick: function(page, e) {
                Main.loadRanking($resultsContainer, topic_id, page);
                e.preventDefault();
              }
            });
          }
          $resultsContainer.find('.abstract-text .truncated').click(function() {
            $(this).toggleClass('truncated');
          });

          var scrollTop = $(document).height();
          var proposalOffset = $resultsContainer.offset();
          if(proposalOffset){
            scrollTop = proposalOffset.top;
          }

          // scroll to the end
          $('html, body').animate({scrollTop: scrollTop }, 'fast');
        });
        $('.experience-proposal-container').hide();
        $('.talk-proposal-container').hide();
      },
      loginCallback: function(loggedIn, token, user) {
        logged_in = loggedIn;
        $('.login .message').text('');
        var requireLoginContainer = loginButton.closest('.require-login-container');

        if(user && !Main.getUser()) {
          Main.setUser(user);
        }

        if(logged_in) {
          Main.showLogout();
          if(token){
            Main.private_token = token;
          }
          // requireLoginContainer = $('.require-login-container');
          requireLoginContainer.find('.require-login').show();
          requireLoginContainer.find('.require-login .message').show();
          requireLoginContainer.find('.login-container').hide();
          $.cookie('_dialoga_session', Main.private_token);
          $('#login-panel').hide();
        } else if (user) {
          // fluxo signup vindo das caixas de login dentro dos programas
          if(requireLoginContainer.length > 0){
            var loginContainer = requireLoginContainer.find('.login-container');
            loginContainer.show();
            loginContainer.find('.new-user').click();
            var $signupForm = loginContainer.find('#signup-form');
            fillSignupForm($signupForm, user);
          } else { //signup botão Entrar principal vindo de OAUTH
            $('#login-panel').find('a.new-user').click();
            var $signupForm = $('#login-panel #signup-form');
            fillSignupForm($signupForm, user);
          }
        } else {
          requireLoginContainer.find('.require-login').hide();
          requireLoginContainer.find('.login-container').show();
          Main.showLogin();
        }
      },
      guid: function() {
        function s4() {
          return Math.floor((1 + Math.random()) * 0x10000)
            .toString(16)
            .substring(1);
        }
        return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
      },
      display_article: function(article_id, backTo) {
        //var url = host + '/api/v1/articles/' + article_id + '?private_token=' + Main.private_token;
        var url = host + '/api/v1/articles/' + article_id;
        $.getJSON(url).done(function( data ) {
          $('#article-container .article-content').html(articleTemplate(data.article));
          $('#article-container').show();
          $('#proposal-categories').hide();
          $('#proposal-group').hide();
          $('nav').hide();
          $('#content').hide();
          $('.content').removeClass('background'); /* Remove class background*/
          $('#article-container .go-back').attr('href', backTo);
        });
      },
      // inicio Eduardo
      randomProposalByTheme: function(themeClasses) {
        $('#proposal-group .proposal-list .proposal-item').hide();
        $.each(themeClasses, function(i, themeClass) {
          var proposalsByTheme = $('#proposal-group .proposal-list .proposal-item').find('.' + themeClass);
          var randomizedIndex = Math.floor(Math.random() * proposalsByTheme.length);
          var proposalToShow = $(proposalsByTheme[randomizedIndex]).parents().filter('.proposal-item');
          $(proposalToShow).show();
        });
      },
      display_category_tab: function(){
        // $('#proposal-group').hide();
        this.randomProposalByTheme(['category-saude', 'category-seguranca-publica', 'category-educacao', 'category-reducao-da-pobreza']);
        $('#proposal-group').show(); /* Show random proposals*/
        $('.content').addClass('background'); /* Add class background */
        $('#proposal-categories').show();
        $('#nav-proposal-categories a').addClass('active');
        $('#nav-proposal-group a').removeClass('active');
        $('.proposal-category-items').hide();
        $('.proposal-category .arrow-box').hide();
        $('.proposal-detail').hide().removeClass('hide');
        $('#article-container').hide();

        $('#content').show();
        $('nav').show();

        this.computeBoxHeight();
      },
      display_proposals_tab: function(){
        // $('#proposal-categories').hide();
        // this.randomProposalByTheme(['category-saude', 'category-seguranca-publica', 'category-educacao', 'category-reducao-da-pobreza']);
        $('.proposal-item').show(); /* Show all programs */
        $('#proposal-group').show();
        $('#proposal-categories').show();
        $('.proposal-category-items').hide();
        $('.proposal-detail').hide().removeClass('hide');
        $('#nav-proposal-group a').addClass('active');
        $('#nav-proposal-categories a').removeClass('active');
        $('#content').show();
        $('.content').addClass('background'); /* Add class background */
        $('#article-container').hide();
        $('nav').show();
        $('html, body').animate({ scrollTop: $('#proposal-group').offset().top }, 'fast');

        this.computeBoxHeight();
      },
      // fim Eduardo
      display_proposal: function(proposal_id){
        $('#proposal-categories').hide();
        $('#proposal-group').hide();
        $('.proposal-category-items').hide(); /* Hide Category Items */
        $('.content').removeClass('background'); /* Remove class background*/
        $('nav').hide();
        $('#content').hide();
        $('#article-container').hide();
        // $('.make-proposal-form').hide();
        // $('.login-container').hide();
        $('.proposal-detail').hide().removeClass('hide'); // hide all proposals
        // $('.proposal-detail-base').hide();
        var $proposal = $('#' + proposal_id);
        $proposal.find('.proposal-detail-base').hide();
        $proposal.show();
        $proposal.find('.proposal-header').show();
        $proposal.find('.make-proposal-container').show();
        $proposal.find('.support-proposal-container').show();
        $proposal.find('.results-container').hide();
        $proposal.find('.results-container .loading').hide();
        $proposal.find('.results-container .results-content').hide();
        $proposal.find('.experience-proposal-container').show();
        $proposal.find('.talk-proposal-container').show();
        $proposal.find('.calendar').hide();
        var active_category = '';
        var category_id;
        switch($proposal.find('.categories').attr('class')) {
          case 'categories saude':
            active_category = 'saude';
            category_id = 180;
            break;
          case 'categories educacao':
            active_category = 'educacao';
            category_id = 181;
            break;
          case 'categories seguranca-publica':
            active_category = 'seguranca-publica';
            category_id = 182;
            break;
          case 'categories reducao-da-pobreza':
            active_category = 'reducao-da-pobreza';
            category_id = 183;
            break;
        }

        var topic_id = proposal_id.split('-').pop();
        this.loadRandomProposal(topic_id);
        Main.display_events(category_id, active_category);
      },
      display_proposal_detail: function(proposal_id){
        $('.content').removeClass('background'); /* Remove class background */
        $('#proposal-categories').hide();
        $('#proposal-group').hide();
        $('nav').hide();
        $('#content').hide();
        $('#article-container').hide();
        var $proposal = $('#proposal-item-' + proposal_id);
        $proposal.find('.proposal-header').hide();
        $proposal.find('.make-proposal-container').hide();
        $proposal.find('.support-proposal-container').hide();
        $proposal.find('.results-container').hide();
        $proposal.find('.experience-proposal-container').hide();
        $proposal.find('.talk-proposal-container').hide();
        $proposal.find('.body').show();
        $proposal.show();

        //var url = host + '/api/v1/articles/' + proposal_id + '?private_token=' + Main.private_token + '&fields=id,body&content_type=ProposalsDiscussionPlugin::Topic';
        var url = host + '/api/v1/articles/' + proposal_id + '?fields=id,body&content_type=ProposalsDiscussionPlugin::Topic';
        $.getJSON(url).done(function( data ) {
          $('#proposal-item-' + proposal_id + ' .body-content').replaceWith(data.article.body);
        })
        .fail(function( jqxhr, textStatus, error ) {
          var err = textStatus + ', ' + error;
          console.error( 'Request Failed: ' + err );
        });
      },
      display_proposal_by_category: function(item){
        var $item = $('#' + item);

        if($item.hasClass('proposal-category-items')){
          //Display Topics or Discussion by category
          $('nav').show();
          $('#content').show();
          $('#proposal-categories').show();
          $('#nav-proposal-categories a').addClass('active');
          $('#nav-proposal-group a').removeClass('active');
          $('#proposal-group').hide(); /* Hide section "Programas" */
          $('.content').addClass('background'); /* Add class background */
          $('.proposal-category-items').hide();
          $('.proposal-detail').hide().removeClass('hide');
          $item.toggle( 'blind', 200, function () {
            var itemOffset = $item.offset();
            if(itemOffset){
              $('html, body').animate({ scrollTop: itemOffset.top }, 'fast');
            }
          } );
          $('.proposal-category .arrow-box').hide();
          var categorySlug = $item.data('category');
          $('#proposal-category-' + categorySlug).find('.arrow-box').show();
<commit_msg>Hide article container when display proposals by category (fix #354)<commit_after>/* global define */
define(['jquery', 'handlebars', 'fastclick', 'proposal_app', 'handlebars_helpers', 'piwik'], function($, Handlebars, FastClick, ProposalApp){
  // 'use strict';

  // The template code
  var templateSource = $('#proposal-template').html();

  // compile the template
  var template = Handlebars.compile(templateSource);
  var supportProposalTemplate = Handlebars.compile(document.getElementById('support-proposal-template').innerHTML);
  var loginTemplate = Handlebars.compile(document.getElementById('login-template').innerHTML);
  var resultsTemplate = Handlebars.compile(document.getElementById('results-template').innerHTML);
  var articleTemplate = Handlebars.compile(document.getElementById('article-template').innerHTML);
  var calendarTemplate = Handlebars.compile(document.getElementById('calendar-template').innerHTML);

  // The div/container that we are going to display the results in
  var resultsPlaceholder = document.getElementById('proposal-result');

  var logged_in = false;

  var loginButton;

  var lastHash = window.location.hash;

  var host = 'http://login.dialoga.gov.br';
  var serpro_captcha_clienteId = 'fdbcdc7a0b754ee7ae9d865fda740f17';
  var dialoga_community = 19195;
  var proposal_discussion = '103358'; //participa
  var cat_saude = 180;
  // var cat_seguranca_publica = 182;
  // var cat_educacao = 181;
  // var cat_reducao_da_pobreza = 183;
  var recaptchaSiteKey = '<KEY>';

  // There are two modes for development
  // 1: Remote API
  // 2: Local API
  // For (1) use port 3000 -> rails s
  // For (2) use port 3001 -> rails s -p 3001
  //
  // For (2) set at /etc/hosts:
  //
  //127.0.0.1  participa.br
  //127.0.0.1  dialoga.gov.br
  //127.0.0.1  login.dialoga.gov.br
  //127.0.0.1  noosfero.com
  //Detects for localhost settings
  var patt = new RegExp(':300[0-2]/');
  var localDevelopment = false;

  if(patt.test(window.location.href)){
    localDevelopment = true;
    patt = new RegExp(':3000/');

    if(patt.test(window.location.href)){
      host = 'http://noosfero.com:3000';
    }else if (new RegExp(':3001/').test(window.location.href)){
      host = 'http://noosfero.com:3001';
      dialoga_community = 104;
      //    proposal_discussion = '413'; //Eugênio
      proposal_discussion = '392'; //Evandro
      recaptchaSiteKey = '<KEY>'; //http://noosfero.com/
      cat_saude = 23;
    } else { //ABNER
      host = 'http://local.abner.com:3002';
      dialoga_community = 105;
      proposal_discussion = '392'; //Evandro
      recaptchaSiteKey = '<KEY>'; //http://noosfero.com/
      cat_saude = 23;
    }
  }


  var BARRA_ADDED = false;
  var HIDE_BARRA_DO_GOVERNO = false;

  var Main;
  window.Main = Main = (function(){

    var API = {
      articles: '',
      proposals: '/api/v1/articles/{topic_id}/children',

    };

    API.getProposalsURL = function (topicId){
      return host + replace(API.proposals, '{topic_id}', topicId);
    };

    function replace(str, pattern, value){
      return str.replace(new RegExp(pattern, 'g'), value);
    }

    function fillSignupForm(signupForm, user) {
      signupForm.find('#signup-user_email').val(user.email);
      signupForm.find('#signup-user_email').attr('disabled', true);
      signupForm.find('#signup-user_name').val(user.login);
      signupForm.find('#user_oauth_signup_token').val(user.signup_token);
      signupForm.find('#user_oauth_providers').val(user.oauth_providers);
      signupForm.find('div.password').hide();
      signupForm.find('div.password-confirmation').hide();
      signupForm.find('#signup-user_password').attr('required', false);
      signupForm.find('#user_password_confirmation').attr('required', false);
    };

    return {
      private_token: null,
      getProposalId: function() {
        var regexProposals = /\d.*\/propostas\/*.*/;
        var proposalId = 0;

        var hasProposal = regexProposals.test(location.hash);
        if( hasProposal ){
          var regexExtractProposal = /propostas\/*.*/;
          proposalId = regexExtractProposal.exec(location.hash)[0].split('/')[1];

        }

        return proposalId;
      },
      loadRandomProposal: function (topic_id, force) {
          /*var private_token = window.Main.private_token;*/
          var $noProposals = $('.no-proposals');
          var $loading = $('.loading');
          var $randomProposal = $('.random-proposal');
          var $body = $(document.body);
          var contextMain = this;

          // reset view
          $noProposals.hide();
          $loading.show();
          $randomProposal.html('');

          var url = API.getProposalsURL(topic_id);
          var childId = this.getProposalId();

          if(childId !== 0 && !force){
            url += '/' + childId;
          }
          //url += '?private_token=' + private_token + '&limit=1&order=random()&_='+new Date().getTime()+'&fields=id,name,slug,abstract,created_by&content_type=ProposalsDiscussionPlugin::Proposal';
          url += '?limit=1&order=random()&_='+new Date().getTime()+'&fields=id,name,slug,abstract,created_by&content_type=ProposalsDiscussionPlugin::Proposal';

          $.getJSON(url).done(function( data ) {
            $loading.hide();
            $('.support-proposal .alert').hide();

            data.articles = data.articles || [data.article];
            if(data.articles.length === 0) {
              $noProposals.show();
              return;
            }

            var article = data.articles[0];
            var parentTitle = $('#proposal-item-'+topic_id).find('.proposal-header .title').text();
            article.parent = {id: topic_id, title: parentTitle};
            $randomProposal.html(supportProposalTemplate(article));
            $body.off('click', '.vote-actions .skip');
            $body.on('click', '.vote-actions .skip', function(e) {
              e.preventDefault();
              contextMain.loadRandomProposal(topic_id, true);
            });
            $body.off('click', '.vote-actions .vote-action');
            $body.on('click', '.vote-actions .vote-action', function(e) {
              e.preventDefault();

              //Helps to prevent more than one vote per proposal
              var $button = $(this);
              var $proposal = $button.closest('.random-proposal');

              if(!logged_in) {
                $(this).closest('.require-login-container').find('.button-send a').click();
                return;
              }

              if(ProposalApp.hasProposalbeenVoted(article.id)){
                // console.debug("Proposta " + article.id + " já havia sido votada");
                Main.displaySuccess($button.closest('.support-proposal .section-content'), 'Seu voto já foi computado nesta proposta', 800);
                contextMain.loadRandomProposal(topic_id, true);
                return;
              }

              $.ajax({
                type: 'post',
                url: host + '/api/v1/articles/' + article.id + '/vote',
                data: {
                  value: $(this).data('vote-value'),
                  private_token: Main.private_token
                }
              }).done(function(data) {
                if(data.vote) {
                  // Main.displaySuccess($button.closest('.support-proposal .section-content'), '', 800);
                  $proposal.find('.abstract').hide();
                  $proposal.find('.vote-actions .like').hide();
                  $proposal.find('.vote-actions .dislike').hide();
                  // $proposal.find('.vote-actions .vote-result').hide();
                  var $successPanel = $('.success-panel').clone();
                  $successPanel.find('.icon').addClass('icon-proposal-sent');
                  $successPanel.find('.message').html('Voto realizado com sucesso');
                  $successPanel.removeClass('hide');
                  $proposal.prepend($successPanel);
                  $successPanel.show();
                  // $successPanel.css('top', Math.max(0, (($proposal.height() - $successPanel.outerHeight()) / 2) + $proposal.offset().top) + 'px');
                  // $successPanel.css('left', Math.max(0, (($proposal.width() - $successPanel.outerWidth()) / 2) + $proposal.offset().left) + 'px');
                } else {
                  $proposal.find('.abstract').hide();
                  $proposal.find('.vote-actions .like').hide();
                  $proposal.find('.vote-actions .dislike').hide();

                  var $successPanel = $('.success-panel').clone();
                  // $successPanel.find('.icon').addClass('icon-proposal-sent');
                  $successPanel.find('.message').html('Seu voto já foi computado nesta proposta');
                  $successPanel.removeClass('hide');
                  $proposal.prepend($successPanel);
                  $successPanel.show();
                  // Main.displaySuccess($button.closest('.support-proposal .section-content'), , 800);
                  // $successPanel.find('.message').html('Seu voto já foi computado nesta proposta');
                }
                // ProposalApp.addVotedProposal(article.id);
                // contextMain.loadRandomProposal(topic_id, true);
              });
            });

            $body.off('click', '.vote-result');
            $body.on('click', '.vote-result', function(e) {
              // e.preventDefault();

              var $this = $(this);
              var $proposalDetail = $this.parents('.proposal-detail');
              var $resultsContainer = $proposalDetail.find('.results-container');

              if($resultsContainer.css('display') === 'none') {
                Main.loadRanking($resultsContainer, topic_id, 1);
              } else {
                $proposalDetail.find('.experience-proposal-container').show();
                $proposalDetail.find('.talk-proposal-container').show();
                $resultsContainer.hide();

                // remove '/resultados' from URL
                window.location.hash = window.location.hash.split('/resultados')[0];
                e.preventDefault();
              }
            });

          }).fail(function(){
            $loading.hide();
            $('.support-proposal .alert').show();
          });
      },
      loadRanking: function($resultsContainer, topic_id, page) {
        $resultsContainer.find('.loading').show();
        $resultsContainer.find('.results-content').hide();

        var per_page = 10;
        //var url = host + '/api/v1/proposals_discussion_plugin/' + topic_id + '/ranking' + '?private_token=' + Main.private_token + '&per_page='+per_page+'&page='+page;
        var url = host + '/api/v1/proposals_discussion_plugin/' + topic_id + '/ranking' + '?per_page='+per_page+'&page='+page;
        $.getJSON(url).done(function( data, stats, xhr ) {
          data.pagination = {
            total: parseInt(xhr.getResponseHeader('Total')),
            per_page: parseInt(xhr.getResponseHeader('Per-Page')),
            page: page,
          };

          // hack: add title to result table
          data.title = $resultsContainer.closest('.categories').find('.proposal-header .title').text();

          $resultsContainer.html(resultsTemplate(data));
          $resultsContainer.find('.loading').hide();
          $resultsContainer.find('.results-content').show();
          $('.timeago').timeago();
          $resultsContainer.show();

          $('.footable').footable();

          if(data.pagination.total > data.pagination.per_page) {
            $resultsContainer.find('.paging').pagination({
              items: data.pagination.total,
              itemsOnPage: data.pagination.per_page,
              currentPage: data.pagination.page,
              prevText: '«',
              nextText: '»',
              cssStyle: 'compact-theme',
              onPageClick: function(page, e) {
                Main.loadRanking($resultsContainer, topic_id, page);
                e.preventDefault();
              }
            });
          }
          $resultsContainer.find('.abstract-text .truncated').click(function() {
            $(this).toggleClass('truncated');
          });

          var scrollTop = $(document).height();
          var proposalOffset = $resultsContainer.offset();
          if(proposalOffset){
            scrollTop = proposalOffset.top;
          }

          // scroll to the end
          $('html, body').animate({scrollTop: scrollTop }, 'fast');
        });
        $('.experience-proposal-container').hide();
        $('.talk-proposal-container').hide();
      },
      loginCallback: function(loggedIn, token, user) {
        logged_in = loggedIn;
        $('.login .message').text('');
        var requireLoginContainer = loginButton.closest('.require-login-container');

        if(user && !Main.getUser()) {
          Main.setUser(user);
        }

        if(logged_in) {
          Main.showLogout();
          if(token){
            Main.private_token = token;
          }
          // requireLoginContainer = $('.require-login-container');
          requireLoginContainer.find('.require-login').show();
          requireLoginContainer.find('.require-login .message').show();
          requireLoginContainer.find('.login-container').hide();
          $.cookie('_dialoga_session', Main.private_token);
          $('#login-panel').hide();
        } else if (user) {
          // fluxo signup vindo das caixas de login dentro dos programas
          if(requireLoginContainer.length > 0){
            var loginContainer = requireLoginContainer.find('.login-container');
            loginContainer.show();
            loginContainer.find('.new-user').click();
            var $signupForm = loginContainer.find('#signup-form');
            fillSignupForm($signupForm, user);
          } else { //signup botão Entrar principal vindo de OAUTH
            $('#login-panel').find('a.new-user').click();
            var $signupForm = $('#login-panel #signup-form');
            fillSignupForm($signupForm, user);
          }
        } else {
          requireLoginContainer.find('.require-login').hide();
          requireLoginContainer.find('.login-container').show();
          Main.showLogin();
        }
      },
      guid: function() {
        function s4() {
          return Math.floor((1 + Math.random()) * 0x10000)
            .toString(16)
            .substring(1);
        }
        return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
      },
      display_article: function(article_id, backTo) {
        //var url = host + '/api/v1/articles/' + article_id + '?private_token=' + Main.private_token;
        var url = host + '/api/v1/articles/' + article_id;
        $.getJSON(url).done(function( data ) {
          $('#article-container .article-content').html(articleTemplate(data.article));
          $('#article-container').show();
          $('#proposal-categories').hide();
          $('#proposal-group').hide();
          $('nav').hide();
          $('#content').hide();
          $('.content').removeClass('background'); /* Remove class background*/
          $('#article-container .go-back').attr('href', backTo);
        });
      },
      // inicio Eduardo
      randomProposalByTheme: function(themeClasses) {
        $('#proposal-group .proposal-list .proposal-item').hide();
        $.each(themeClasses, function(i, themeClass) {
          var proposalsByTheme = $('#proposal-group .proposal-list .proposal-item').find('.' + themeClass);
          var randomizedIndex = Math.floor(Math.random() * proposalsByTheme.length);
          var proposalToShow = $(proposalsByTheme[randomizedIndex]).parents().filter('.proposal-item');
          $(proposalToShow).show();
        });
      },
      display_category_tab: function(){
        // $('#proposal-group').hide();
        this.randomProposalByTheme(['category-saude', 'category-seguranca-publica', 'category-educacao', 'category-reducao-da-pobreza']);
        $('#proposal-group').show(); /* Show random proposals*/
        $('.content').addClass('background'); /* Add class background */
        $('#proposal-categories').show();
        $('#nav-proposal-categories a').addClass('active');
        $('#nav-proposal-group a').removeClass('active');
        $('.proposal-category-items').hide();
        $('.proposal-category .arrow-box').hide();
        $('.proposal-detail').hide().removeClass('hide');
        $('#article-container').hide();

        $('#content').show();
        $('nav').show();

        this.computeBoxHeight();
      },
      display_proposals_tab: function(){
        // $('#proposal-categories').hide();
        // this.randomProposalByTheme(['category-saude', 'category-seguranca-publica', 'category-educacao', 'category-reducao-da-pobreza']);
        $('.proposal-item').show(); /* Show all programs */
        $('#proposal-group').show();
        $('#proposal-categories').show();
        $('.proposal-category-items').hide();
        $('.proposal-detail').hide().removeClass('hide');
        $('#nav-proposal-group a').addClass('active');
        $('#nav-proposal-categories a').removeClass('active');
        $('#content').show();
        $('.content').addClass('background'); /* Add class background */
        $('#article-container').hide();
        $('nav').show();
        $('html, body').animate({ scrollTop: $('#proposal-group').offset().top }, 'fast');

        this.computeBoxHeight();
      },
      // fim Eduardo
      display_proposal: function(proposal_id){
        $('#proposal-categories').hide();
        $('#proposal-group').hide();
        $('.proposal-category-items').hide(); /* Hide Category Items */
        $('.content').removeClass('background'); /* Remove class background*/
        $('nav').hide();
        $('#content').hide();
        $('#article-container').hide();
        // $('.make-proposal-form').hide();
        // $('.login-container').hide();
        $('.proposal-detail').hide().removeClass('hide'); // hide all proposals
        // $('.proposal-detail-base').hide();
        var $proposal = $('#' + proposal_id);
        $proposal.find('.proposal-detail-base').hide();
        $proposal.show();
        $proposal.find('.proposal-header').show();
        $proposal.find('.make-proposal-container').show();
        $proposal.find('.support-proposal-container').show();
        $proposal.find('.results-container').hide();
        $proposal.find('.results-container .loading').hide();
        $proposal.find('.results-container .results-content').hide();
        $proposal.find('.experience-proposal-container').show();
        $proposal.find('.talk-proposal-container').show();
        $proposal.find('.calendar').hide();
        var active_category = '';
        var category_id;
        switch($proposal.find('.categories').attr('class')) {
          case 'categories saude':
            active_category = 'saude';
            category_id = 180;
            break;
          case 'categories educacao':
            active_category = 'educacao';
            category_id = 181;
            break;
          case 'categories seguranca-publica':
            active_category = 'seguranca-publica';
            category_id = 182;
            break;
          case 'categories reducao-da-pobreza':
            active_category = 'reducao-da-pobreza';
            category_id = 183;
            break;
        }

        var topic_id = proposal_id.split('-').pop();
        this.loadRandomProposal(topic_id);
        Main.display_events(category_id, active_category);
      },
      display_proposal_detail: function(proposal_id){
        $('.content').removeClass('background'); /* Remove class background */
        $('#proposal-categories').hide();
        $('#proposal-group').hide();
        $('nav').hide();
        $('#content').hide();
        $('#article-container').hide();
        var $proposal = $('#proposal-item-' + proposal_id);
        $proposal.find('.proposal-header').hide();
        $proposal.find('.make-proposal-container').hide();
        $proposal.find('.support-proposal-container').hide();
        $proposal.find('.results-container').hide();
        $proposal.find('.experience-proposal-container').hide();
        $proposal.find('.talk-proposal-container').hide();
        $proposal.find('.body').show();
        $proposal.show();

        //var url = host + '/api/v1/articles/' + proposal_id + '?private_token=' + Main.private_token + '&fields=id,body&content_type=ProposalsDiscussionPlugin::Topic';
        var url = host + '/api/v1/articles/' + proposal_id + '?fields=id,body&content_type=ProposalsDiscussionPlugin::Topic';
        $.getJSON(url).done(function( data ) {
          $('#proposal-item-' + proposal_id + ' .body-content').replaceWith(data.article.body);
        })
        .fail(function( jqxhr, textStatus, error ) {
          var err = textStatus + ', ' + error;
          console.error( 'Request Failed: ' + err );
        });
      },
      display_proposal_by_category: function(item){
        var $item = $('#' + item);

        if($item.hasClass('proposal-category-items')){
          //Display Topics or Discussion by category
          $('nav').show();
          $('#content').show();
          $('#proposal-categories').show();
          $('#nav-proposal-categories a').addClass('active');
          $('#nav-proposal-group a').removeClass('active');
          $('#proposal-group').hide(); /* Hide section "Programas" */
          $('.content').addClass('background'); /* Add class background */
          $('.proposal-category-items').hide();
          $('.proposal-detail').hide().removeClass('hide');
          $('#article-container').hide();
          $item.toggle( 'blind', 200, function () {
            var itemOffset = $item.offset();
            if(itemOffset){
              $('html, body').animate({ scrollTop: itemOffset.top }, 'fast');
            }
          } );
          $('.proposal-category .arrow-box').hide();
          var categorySlug = $item.data('category');
          $('#proposal-category-' + categorySlug).find('.arrow-box').show();

{'fraction_non_alphanumeric': 0.17436199361427504, 'fraction_numerical': 0.008718099680713753, 'mean_word_length': 2.3097504309375703, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 8, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1713225', 'n_tokens_mistral': 12756, 'n_tokens_neox': 12315, 'n_words': 1990}