<commit_before>'use strict';
exports.BattleStatuses = {
// ClassyZ
	simpleinnate: {
		effectType: 'Ability',
		onBoost: function (boost) {
			for (let i in boost) {
				boost[i] *= 2;
			}
		},
	},
	russianwinter: {
		effectType: 'Weather',
		duration: 0,
		onStart: function (battle, source, effect) {
			if (effect && effect.effectType === 'Ability') {
			this.effectData.duration = 0;
				this.add('-weather', 'Hail', '[from] ability: ' + effect, '[of] ' + source);
			} else {
				this.add('-weather', 'Hail');
			}
		},
		onResidualOrder: 1,
		onResidual: function () {
			this.add('-weather', 'Hail', '[upkeep]');
			if (this.isWeather('hail')) this.eachEvent('Weather');
		},
		onWeather: function (target) {
			if(!target.name=="Zmeeed")
			this.damage(target.maxhp / 4);
		},
		onEnd: function () {
			this.add('-weather', 'none');
		},
	},
};
<commit_msg>Update statuses.js<commit_after>'use strict';
exports.BattleStatuses = {
// ClassyZ
	simpleinnate: {
		effectType: 'Ability',
		onBoost: function (boost) {
			for (let i in boost) {
				boost[i] *= 2;
			}
		},
	},
	russianwinter: {
		effectType: 'Weather',
		duration: 0,
		onStart: function (battle, source, effect) {
			if (effect && effect.effectType === 'Ability') {
				this.add('-weather', 'Hail', '[from] ability: ' + effect, '[of] ' + source);
			} else {
				this.add('-weather', 'Hail');
			}
		},
		onResidualOrder: 1,
		onResidual: function () {
			this.add('-weather', 'Hail', '[upkeep]');
			if (this.isWeather('hail')) this.eachEvent('Weather');
		},
		onWeather: function (target) {
			if(!target.name=="Zmeeed")
			this.damage(target.maxhp / 4);
		},
		onEnd: function () {
			this.add('-weather', 'none');
		},
	},
};
<|endoftext|>


<commit_before>import { create } from "@storybook/theming"
import pjt from "../project.json"

const common = {
  brandTitle: pjt.setting.name
  //brandUrl: "https://example.com",
  //brandImage: "/favicon.png"
}

export const light = create({
  ...common,
  base: "light"
})
export const dark = create({
  ...common,
  base: "dark"
})
<commit_msg>Demo version<commit_after>import { create } from "@storybook/theming"
import pkg from "../package.json"
import pjt from "../project.json"

const common = {
  brandTitle: pjt.setting.name + " v" + pkg.version
  //brandUrl: "https://musubii.qranoko.jp/storybook",
  //brandImage: "/favicon.png"
}

export const light = create({
  ...common,
  base: "light"
})
export const dark = create({
  ...common,
  base: "dark"
})
<|endoftext|>


<commit_before>define( 'argumenta/widgets/Proposition',
[
    "require-jquery",
    "argumenta/widgets/Base",
    "argumenta/widgets/AddTag",
    "argumenta/widgets/Tags",
    "text!./Proposition/template.html.mustache"
],
function( $, Base, AddTag, Tags, Template ) {

    var Proposition = Base.module( {

        moduleID: 'Proposition',
        template: Template,
        defaults: {
            index: 'P'
        },

        init: function( options ) {
            this.initProposition( options );
        },

        prototype: {

            getType: function() {
                return 'proposition';
            },

            getSha1: function() {
                return this.element.data('sha1');
            },

            initProposition: function( options ) {
                var self = this;

                // Show or hide proposition details on click
                self.element.on('click', function(event) {

                    // Don't trigger background elements on click
                    var closestWidget = $(event.target).closest('div[class*="widget"]');
                    if ( ! closestWidget.is(self.element) ) {
                        event.stopPropagation();
                        return true;
                    }

                    // Don't expand on mouse release after dragging
                    if (self.element.hasClass('ui-state-just-dragged'))
                        return;

                    // Don't interfere with links
                    if ($(event.target).is('a')) {
                        return true;
                    }

                    self._toggleDetails();
                });

                // Bind AddTag button
                self._bindAddTagButton();

                // Make draggable
                self._makeDraggable();
            },

            _toggleDetails: function() {

                var self = this;

                self._toggleTags();
            },

            _toggleTags: function() {

                var self = this;

                if ( typeof self.tags === "undefined" ) {
                    self._initTags();
                }
                else {
                    self.tags.element.toggle( 300 );
                }
            },

            _toggleAddTag: function() {

                var self = this;

                // Initialize if addTag necessary
                if ( typeof self.addTag === "undefined" ) {
                    self._initAddTag();
                    self.addTag.element.hide();
                }

                // Fade in or out
                self.addTag.element.toggle( 300 );
            },

            _initAddTag: function() {

                var self = this;

                // Create a new widget targeting this proposition
                var addTag = new AddTag( {
                    target_type: 'proposition',
                    target_sha1: self.getSha1()
                } );

                // Replace the placeholder
                self.element.children('.add-tag-widget')
                            .replaceWith( addTag.element );

                // Save a reference to the nested widget
                self.addTag = addTag;
            },

            _initTags: function() {
                var self = this;
                var tagsContainer = self.element.children('.proposition-details')
                                                .children('.tags-widget-container');

                // Hide the container
                tagsContainer.hide();

                // Create a new Tags widget targeting this proposition
                var tags = new Tags( {
                    target_type: self.getType(),
                    target_sha1: self.getSha1(),
                    onLoad: function( tagsWidget ) {
                        // Append the element and reveal the container
                        tagsContainer.append( tagsWidget.element );
                        tagsContainer.show( 300 );
                    }
                } );

                // Save a reference to the nested widget
                self.tags = tags;
            },

            _bindAddTagButton: function() {

                var self = this;

                $('.addtag-link', self.element).first().on( 'click', function(event) {

                    self._toggleAddTag();

                    // Defocus the link
                    $(this).blur();

                    // Prevent default & stop propagation
                    return false;
                } );
            },

            _makeDraggable: function() {

                var self = this;

                this.element.draggable( {
                    helper: 'clone',
                    appendTo: $('.drag-container')[0] || $('body'),
                    revert: true,
                    cancel: 'span, input',
                    handle: self.element.children(".proposition-main"),
                    cursor: 'move',
                    opacity: 0.90,
                    start: function(event, ui) {
                        // Prevent other actions on drag
                        ui.helper.addClass('ui-state-just-dragged proposition-widget-drag');

                        // Fix clone size
                        ui.helper.css( {
                            'height': self.element.height() + 'px',
                            'width': self.element.width() + 'px'
                        } );

                        // Hide original
                        self.element.css('visibility', "hidden");
                    },
                    stop: function(event, ui) {
                        // Prevent other actions on drag, then cleanup
                        setTimeout(function() {ui.helper.removeClass('ui-state-just-dragged');}, 300);

                        // Reveal original
                        self.element.css('visibility', "");
                    }
                } );
            },

            // Overrides Base
            _renderUI: function() {
                var self = this;

                self._super('_renderUI');

                var textElem = self.element.find('.text').first();
                var textHtml = textElem.html();
                var newHtml  = textHtml.replace(/\r?\n|\r/g, '
');

                textElem.html( newHtml );

                return;
            },

            // Overrides Base
            _getViewOptions: function() {
                var self = this;
                var role_desc;

                switch ( self.options.index ) {
                    case 'P': role_desc = '';              break;
                    case 'C': role_desc = ' (Conclusion)'; break;
                    default : role_desc = ' (Premise)';    break;
                }

                var viewOptions = {
                    partial_sha1: self.options.sha1.substr(0, 20),
                    proposition_desc: 'Proposition' + role_desc,
                    details_desc: 'Proposition details\r\nSHA1: ' + self.options.sha1
                }
                return $.extend( viewOptions, self.options );
            }
        },

        "static": {

            // Get the type of a proposition element
            getType: function( proposition ) {
                return $(proposition).data('object_type');
            },

            // Get the sha1 of a proposition element
            getSha1: function( proposition ) {
                return $(proposition).data('sha1');
            }
        }
    } );

    return Proposition;
} );
<commit_msg>use data property in prop.getSha1()<commit_after>define( 'argumenta/widgets/Proposition',
[
    "require-jquery",
    "argumenta/widgets/Base",
    "argumenta/widgets/AddTag",
    "argumenta/widgets/Tags",
    "text!./Proposition/template.html.mustache"
],
function( $, Base, AddTag, Tags, Template ) {

    var Proposition = Base.module( {

        moduleID: 'Proposition',
        template: Template,
        defaults: {
            index: 'P'
        },

        init: function( options ) {
            this.initProposition( options );
        },

        prototype: {

            getType: function() {
                return 'proposition';
            },

            getSha1: function() {
                return this.data.sha1;
            },

            initProposition: function( options ) {
                var self = this;

                // Show or hide proposition details on click
                self.element.on('click', function(event) {

                    // Don't trigger background elements on click
                    var closestWidget = $(event.target).closest('div[class*="widget"]');
                    if ( ! closestWidget.is(self.element) ) {
                        event.stopPropagation();
                        return true;
                    }

                    // Don't expand on mouse release after dragging
                    if (self.element.hasClass('ui-state-just-dragged'))
                        return;

                    // Don't interfere with links
                    if ($(event.target).is('a')) {
                        return true;
                    }

                    self._toggleDetails();
                });

                // Bind AddTag button
                self._bindAddTagButton();

                // Make draggable
                self._makeDraggable();
            },

            _toggleDetails: function() {

                var self = this;

                self._toggleTags();
            },

            _toggleTags: function() {

                var self = this;

                if ( typeof self.tags === "undefined" ) {
                    self._initTags();
                }
                else {
                    self.tags.element.toggle( 300 );
                }
            },

            _toggleAddTag: function() {

                var self = this;

                // Initialize if addTag necessary
                if ( typeof self.addTag === "undefined" ) {
                    self._initAddTag();
                    self.addTag.element.hide();
                }

                // Fade in or out
                self.addTag.element.toggle( 300 );
            },

            _initAddTag: function() {

                var self = this;

                // Create a new widget targeting this proposition
                var addTag = new AddTag( {
                    target_type: 'proposition',
                    target_sha1: self.getSha1()
                } );

                // Replace the placeholder
                self.element.children('.add-tag-widget')
                            .replaceWith( addTag.element );

                // Save a reference to the nested widget
                self.addTag = addTag;
            },

            _initTags: function() {
                var self = this;
                var tagsContainer = self.element.children('.proposition-details')
                                                .children('.tags-widget-container');

                // Hide the container
                tagsContainer.hide();

                // Create a new Tags widget targeting this proposition
                var tags = new Tags( {
                    target_type: self.getType(),
                    target_sha1: self.getSha1(),
                    onLoad: function( tagsWidget ) {
                        // Append the element and reveal the container
                        tagsContainer.append( tagsWidget.element );
                        tagsContainer.show( 300 );
                    }
                } );

                // Save a reference to the nested widget
                self.tags = tags;
            },

            _bindAddTagButton: function() {

                var self = this;

                $('.addtag-link', self.element).first().on( 'click', function(event) {

                    self._toggleAddTag();

                    // Defocus the link
                    $(this).blur();

                    // Prevent default & stop propagation
                    return false;
                } );
            },

            _makeDraggable: function() {

                var self = this;

                this.element.draggable( {
                    helper: 'clone',
                    appendTo: $('.drag-container')[0] || $('body'),
                    revert: true,
                    cancel: 'span, input',
                    handle: self.element.children(".proposition-main"),
                    cursor: 'move',
                    opacity: 0.90,
                    start: function(event, ui) {
                        // Prevent other actions on drag
                        ui.helper.addClass('ui-state-just-dragged proposition-widget-drag');

                        // Fix clone size
                        ui.helper.css( {
                            'height': self.element.height() + 'px',
                            'width': self.element.width() + 'px'
                        } );

                        // Hide original
                        self.element.css('visibility', "hidden");
                    },
                    stop: function(event, ui) {
                        // Prevent other actions on drag, then cleanup
                        setTimeout(function() {ui.helper.removeClass('ui-state-just-dragged');}, 300);

                        // Reveal original
                        self.element.css('visibility', "");
                    }
                } );
            },

            // Overrides Base
            _renderUI: function() {
                var self = this;

                self._super('_renderUI');

                var textElem = self.element.find('.text').first();
                var textHtml = textElem.html();
                var newHtml  = textHtml.replace(/\r?\n|\r/g, '
');

                textElem.html( newHtml );

                return;
            },

            // Overrides Base
            _getViewOptions: function() {
                var self = this;
                var role_desc;

                switch ( self.options.index ) {
                    case 'P': role_desc = '';              break;
                    case 'C': role_desc = ' (Conclusion)'; break;
                    default : role_desc = ' (Premise)';    break;
                }

                var viewOptions = {
                    partial_sha1: self.options.sha1.substr(0, 20),
                    proposition_desc: 'Proposition' + role_desc,
                    details_desc: 'Proposition details\r\nSHA1: ' + self.options.sha1
                }
                return $.extend( viewOptions, self.options );
            }
        },

        "static": {

            // Get the type of a proposition element
            getType: function( proposition ) {
                return $(proposition).data('object_type');
            },

            // Get the sha1 of a proposition element
            getSha1: function( proposition ) {
                return $(proposition).data('sha1');
            }
        }
    } );

    return Proposition;
} );
<|endoftext|>


<commit_before>window.addEventListener("scroll",function() {
    if(window.scrollY > $("#keep-scrolling").offset().top && window.scrollY < $("#bottom-get-started").offset().top-20) {
       $('#features-navbar').fadeIn();
    }
    else {
       $('#features-navbar').fadeOut();
    }
 },false);

$('.marquee-left').marquee({
	//duration in milliseconds of the marquee
	duration: 10000,
	//gap in pixels between the tickers
	gap: 50,
	//time in milliseconds before the marquee will start animating
	delayBeforeStart: 0,
	//'left' or 'right'
	direction: 'left',
	//true or false - should the marquee be duplicated to show an effect of continues flow
    duplicated: true,
 // pauseOnHover: true //don't need until we add popovers
});

$('.marquee-right').marquee({
	//duration in milliseconds of the marquee
	duration: 10000,
	//gap in pixels between the tickers
	gap: 50,
	//time in milliseconds before the marquee will start animating
	delayBeforeStart: 0,
	//'left' or 'right'
	direction: 'right',
	//true or false - should the marquee be duplicated to show an effect of continues flow
    duplicated: true,
    // pauseOnHover: true //don't need until we add popovers
});

$(document).ready(function() {
    if(document.location.href.indexOf("display-extra=finals") > -1) {
		$("#finals").modal()
	}
});

window.onload = function() {
	var alert = document.querySelector("#whatsnew-alert");
	if (alert) {
		alert.addEventListener("click", function() {
			$("#welcomeback").modal();
		});
	}
};<commit_msg>remove unused js<commit_after>$('.marquee-left').marquee({
	//duration in milliseconds of the marquee
	duration: 10000,
	//gap in pixels between the tickers
	gap: 50,
	//time in milliseconds before the marquee will start animating
	delayBeforeStart: 0,
	//'left' or 'right'
	direction: 'left',
	//true or false - should the marquee be duplicated to show an effect of continues flow
	duplicated: true,
	// pauseOnHover: true //don't need until we add popovers
});

$('.marquee-right').marquee({
	//duration in milliseconds of the marquee
	duration: 10000,
	//gap in pixels between the tickers
	gap: 50,
	//time in milliseconds before the marquee will start animating
	delayBeforeStart: 0,
	//'left' or 'right'
	direction: 'right',
	//true or false - should the marquee be duplicated to show an effect of continues flow
	duplicated: true,
	// pauseOnHover: true //don't need until we add popovers
});
<|endoftext|>


<commit_before>App.addChild('Payment', _.extend({
  el: '#project_review #payment',

  events: {
    'click #payment_menu a' : 'onTabClick'
  },

  activate: function(){
    _this = this;

    this.loadPaymentChoices();

    $('#live_in_brazil').on('change', function(){
      _this.loadPaymentChoices();
    });
  },

  updatePaymentMethod: function() {
    var $selected_tab = this.$('#payment_menu a.selected');
    $.ajax({
      url: this.$el.data('update-info-path'),
      type: 'PUT',
      data: { contribution: { payment_method: $selected_tab.prop('id') } }
    });
  },

  hideNationalPayment: function() {
    this.$('#payment_menu a#MoIP').hide();
    this.$('.payments_type#MoIP_payment').hide();
  },

  selectInternationalPayment: function() {
    this.onTabClick({currentTarget: this.$('#payment_menu a#PayPal')});
  },

  loadPaymentChoices: function() {
    if(!$('#live_in_brazil').prop('checked')) {
      this.hideNationalPayment();
      this.selectInternationalPayment();
    } else {
      this.$('#payment_menu a#MoIP').show();
      this.onTabClick({currentTarget: this.$('#payment_menu a:first')});
    }

    this.on('selectTab', this.updatePaymentMethod);
  }
}, Skull.Tabs));

<commit_msg>just a quick fix, need to look at it with time [13732258]<commit_after>App.addChild('Payment', _.extend({
  el: '#project_review #payment',

  events: {
    'click #payment_menu a' : 'onTabClick'
  },

  activate: function(){
    _this = this;

    this.loadPaymentChoices();

    $('#live_in_brazil').on('change', function(){
      _this.loadPaymentChoices();
    });
    this.$('#payment_menu a').click(this.onTabClick);
  },

  updatePaymentMethod: function() {
    var $selected_tab = this.$('#payment_menu a.selected');
    $.ajax({
      url: this.$el.data('update-info-path'),
      type: 'PUT',
      data: { contribution: { payment_method: $selected_tab.prop('id') } }
    });
  },

  hideNationalPayment: function() {
    this.$('#payment_menu a#MoIP').hide();
    this.$('.payments_type#MoIP_payment').hide();
  },

  selectInternationalPayment: function() {
    this.onTabClick({currentTarget: this.$('#payment_menu a#PayPal')});
  },

  loadPaymentChoices: function() {
    if(!$('#live_in_brazil').prop('checked')) {
      this.hideNationalPayment();
      this.selectInternationalPayment();
    } else {
      this.$('#payment_menu a#MoIP').show();
      this.onTabClick({currentTarget: this.$('#payment_menu a:first')});
    }

    this.on('selectTab', this.updatePaymentMethod);
  }
}, Skull.Tabs));

<|endoftext|>


<commit_before>/* global angular */
;(function () {
  angular.module('resilienzManager')
    .controller('resilienzManager-Editor', ['$scope', 'resilienzManagerDataProvider', '$uibModalInstance', 'data', function ($scope, resilienzManagerDataProvider, $uibModalInstance, data) {
      var self = this
      self.cancel = function () {
        angular.element('#imgAreaSelect').imgAreaSelect({
          disable: true,
          hide: true,
          remove: true
        })
        $uibModalInstance.dismiss('cancel')
      }
      self.close = function () {
        // TODO: get image width, height
        var clientWidth = document.getElementById('imgAreaSelect').clientWidth
        var clientHeight = document.getElementById('imgAreaSelect').clientHeight
        resilienzManagerDataProvider.imageRescale(data.image, self.coords, clientWidth, clientHeight, data.width, data.height).then(function (something) {
          angular.element('#imgAreaSelect').imgAreaSelect({
            disable: true,
            hide: true,
            remove: true
          })
          $uibModalInstance.close(data.image)
        })
      }
      self.image = data.image
      self.imageToLoad = 'bookimages/' + self.image
      self.options = {
        enable: true,
        handles: true,
        hide: false,
        movable: true,
        resizable: true,
        show: true,
        aspectRatio: data.width + ':' + data.height,
        imageHeight: data.height,
        imageWidth: data.width,
        x1: 1,
        y1: 1,
        x2: 1 + data.width,
        y2: 1 + data.height
      }
      // http://odyniec.net/projects/imgareaselect/
      // https://github.com/eliyahen/ng-imgAreaSelect
    }])
}())
<commit_msg>aspectratio calc editor<commit_after>/* global angular */
;(function () {
  angular.module('resilienzManager')
    .controller('resilienzManager-Editor', ['$scope', 'resilienzManagerDataProvider', '$uibModalInstance', 'data', function ($scope, resilienzManagerDataProvider, $uibModalInstance, data) {
      var self = this
      self.orgWidth = document.getElementById('imgAreaSelect').naturalWidth
      self.orgHeight = document.getElementById('imgAreaSelect').naturalHeight
      self.cancel = function () {
        angular.element('#imgAreaSelect').imgAreaSelect({
          disable: true,
          hide: true,
          remove: true
        })
        $uibModalInstance.dismiss('cancel')
      }
      self.close = function () {
        // TODO: get image width, height
        var clientWidth = document.getElementById('imgAreaSelect').clientWidth
        var clientHeight = document.getElementById('imgAreaSelect').clientHeight
        resilienzManagerDataProvider.imageRescale(data.image, self.coords, clientWidth, clientHeight, self.orgWidth, self.orgHeight).then(function (something) {
          angular.element('#imgAreaSelect').imgAreaSelect({
            disable: true,
            hide: true,
            remove: true
          })
          $uibModalInstance.close(data.image)
        })
      }
      self.image = data.image
      self.imageToLoad = 'bookimages/' + self.image
      self.options = {
        enable: true,
        handles: true,
        hide: false,
        movable: true,
        resizable: true,
        show: true,
        aspectRatio: data.width + ':' + data.height,
        imageHeight: self.orgHeight,
        imageWidth: self.orgWidth,
        x1: 1,
        y1: 1,
        x2: 1 + data.width,
        y2: 1 + data.height
      }
      // http://odyniec.net/projects/imgareaselect/
      // https://github.com/eliyahen/ng-imgAreaSelect
    }])
}())
<|endoftext|>


<commit_before>
var categories = ['overall', 'fun', 'theme', 'innovation', 'humor', 'graphics', 'audio', 'mood'];
var builtTabs = [];
var author, rates, positions;

$(function(){
  attachEvents();
});

function attachEvents(){

  $('.loading').hide();
  $('.tabs-ctn, .tabs').hide();

  $('.tabs a').on('click', function(){
    var tab = $(this).attr('data-tab');
    $('.tab-content.active, .tabs a.active').removeClass('active');
    $('.tab-content.' + tab).add(this).addClass('active');
    buildTab(tab);
  });

  function updateShares(author){
    var twLink = 'https://twitter.com/intent/tweet?url=https%3A%2F%2Fldstats.info%2F{{author}}&hashtags=ldstats&text=Checkout+my+LudumDare+Stats';
    var fbLink = 'http://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fldstats.info%2F{{author}}&t=Checkout+my+LudumDare+Stats';
    var gpLink = 'https://plus.google.com/share?url=https%3A%2F%2Fldstats.info%2F{{author}}';

    $('.zocial.icon.twitter').attr('href', twLink.replace('{{author}}', author));
    $('.zocial.icon.facebook').attr('href', fbLink.replace('{{author}}', author));
    $('.zocial.icon.googleplus').attr('href', gpLink.replace('{{author}}', author));
  }

  function onFetch(atURL){
    var author = $('#username').val();
    if (author.trim().length){

      if (!atURL && window.history && window.history.pushState){
        window.history.pushState(null, null, "/" + author);
      }

      updateShares(author);

      $('.loading').show();
      clearView();
      fetchAuthor(author.trim());
    }
  }

  $('#fetch').on('click', onFetch)
  $('#username').on('keyup', function(e){
    if (e.keyCode === 13) onFetch();
  });

  if (window.run_author){
    $('#username').val(window.run_author);
    onFetch(true);
  }
}

function clearView(){
  window.builtTabs = [];
  $('.ct-chart-rates, .rates-data, .position-data, .categories').empty();
}

function fetchAuthor(author){
  $('.not-found').hide();
  $('.tabs-ctn, .tabs').hide();

  $.get('/api/authors/' + author)
    .done(function(author){
      $('.tabs-ctn, .tabs').show();

      window.author = author;
      window.rates = getData(categories.concat(["average"]), "scores");
      window.positions = getData(categories.concat(["total"]), "ranking");
      window.percents = getData(categories, "percents");

      var curr = $('.tabs a.active').attr('data-tab');
      buildTab(curr);
    })
    .fail(function() {
      $('.not-found').show();
    })
    .always(function() {
      $('.loading').hide();
    });
}

function buildTab(tab){
  if (builtTabs.indexOf(tab) === -1){

    switch (tab) {
      case "rates":
        buildRatesChart(window.rates);
        break;
      case "data":
        createDataTable('#rates-data', categories.concat(["average"]), window.rates, function(value){
          if (value >= 4){
            return ''+value+'	';
          }
        });
        break;
      case "standings":
        buildPositionsChart(window.positions);
        break;
      case "podium":
        createDataTable('#position-data', categories.concat(["total"]), window.positions, function(value){
          if (value > 0 && value <= 100){
            if (value < 4){
              return '

	';
            }
            return ''+value+'	';
          }
        });
        break;
      case "percents":
        createDataTable('#percents-data', categories, window.percents, function(value){
          if (value > 0 && value < 10) {
            return ''+value+'	';
          }
        });
        break;
      case "coolness":
        createDataTable('#coolness-data', ['coolness'], window.author.entries);
        break;
    }

    builtTabs.push(tab);
  }
}

function getData(categories, field) {
  return _.map(_.cloneDeep(window.author.entries), function(entry, i){

    var en = {
      ludum: entry.ludum,
      title: entry.title,
      link: entry.link,
      type: entry.type,
    };

    function getValue(name){
      return entry[field] && entry[field][name] && entry[field][name] || 0;
    }

    categories.forEach(function(category){
      var value = getValue(category);
      en[category] = value;
    });

    return en;
  });
}

function createDataTable(id, columns, entries, onCellValue, sort){
  sort = sort || { dir: 'asc', col: 'ludum' };
  var $table = $(id).empty();

  var _cols = '';
  _.times(columns.length+2, function(i){ _cols += '<colgroup/>'; })
  var $cols = $(_cols).appendTo($table);

  var $thead = $('
').appendTo($table);
  var $tbody = $('
').appendTo($table);

  var $theadTR = $(
    '
' +
      'LD	' +
      'Entry	' +
    '
');

  $theadTR.append(
    _.map(columns, function(category){
      return ''+category+'	';
    })
  );

  $thead.append($theadTR);

  var sEntries = _.sortByOrder(entries, [sort.col], [sort.dir]);

  var $rows = _.map(sEntries, function(entry, i){
    var $tr = $('
');
    $tr.append(''+entry.ludum+'	');
    $tr.append(''+entry.title+' ('+entry.type+')	');

    $tr.append(
      _.map(columns, function(category){
        var value = entry[category];
        return (onCellValue && onCellValue(value)) || ''+(value || '-')+'	';
      })
    );

    return $tr;
  });

  $tbody.append($rows);

  $thead
    .find('th[data-sort='+sort.col+']')
    .addClass('sorting').addClass(sort.dir)
    .append('
');

  $table
    .on('mouseover', 'td', function(){
      var i = $(this).prevAll('td').length;
      $(this).parent().addClass('cell-hover');

      if ($(this).index() > 1) {
        $($cols[i]).addClass('cell-hover');
      }
    })
    .on('mouseout', 'td', function(){
      var i = $(this).prevAll('td').length;
      $(this).parent().removeClass('cell-hover');
      $($cols[i]).removeClass('cell-hover');
    })
    .on('mouseleave', function(){
      $cols.removeClass('cell-hover');
    })
    .on('click', 'th', function(e){
      var th = $(this);
      var col = th.attr('data-sort');

      var isSame = th.hasClass('sorting');
      var dir = isSame && th.hasClass('asc') ? 'desc' : 'asc';

      $table.off();
      createDataTable(id, columns, entries, onCellValue, { dir: dir, col: col });
    });

  return $table;
}

function buildRatesChart(entries){
  var catsPlusAVG = categories.concat(["average"]);
  var aentries = _.sortBy(entries, 'ludum');

  var labels = _.map(aentries, function(entry){
    return 'LD' + entry.ludum;
  });

  var series = catsPlusAVG.map(function(category){
    return {
      name: category,
      data: _.map(aentries, function(entry){
        return entry[category] || null;
      })
    };
  });

  var chart = new Chartist.Line('.ct-chart-rates', {
    labels: labels,
    series: series
  }, {
    high: 5,
    low: 0,
    lineSmooth: Chartist.Interpolation.simple({
      divisor: 4
    }),
    chartPadding: {
      top: 20,
      right: 120,
      bottom: 20,
      left: 0
    },
    axisX: {
      showGrid: true,
      showLabel: true,
      offset: 20,
      labelOffset: {
        x: -20,
        y: 10
      },
    },
    axisY: {
      position: 'start',
      showGrid: true,
      showLabel: true,
      scaleMinSpace: 30,
    },
  });

  var $chart = $('.ct-chart-rates');

  var $toolTip = $chart
    .append('

')
    .find('.tooltip')
    .hide();

  $chart.on('mouseenter', '.ct-point', function() {
    var $point = $(this),
      value = $point.attr('ct:value'),
      seriesName = $point.parent().attr('ct:series-name');
    $toolTip.html(seriesName + '
' + value).show();
  });

  $chart.on('mouseleave', '.ct-point', function() {
    $toolTip.hide();
  });

  $chart.on('mousemove', function(event) {
    $toolTip.css({
      left: (event.offsetX || event.originalEvent.layerX) - $toolTip.width() / 2 - 10,
      top: (event.offsetY || event.originalEvent.layerY) - $toolTip.height() - 40
    });
  });

  var $categories = $('.rates .categories');

  $categories.empty().append(
    catsPlusAVG.map(function(category, i){
      var idx = String.fromCharCode(97 + i);
      var $li = $('
'+category+'
');

      if (category === "average"){
        $li.addClass('off');
      }

      $li.on('click', function(){
        var el = $(this);

        if (el.hasClass('off')){
          el.removeClass('off');
          $('g.ct-series-' + idx, '.ct-chart-rates').show();
          return;
        }

        el.addClass('off');
        $('g.ct-series-' + idx, '.ct-chart-rates').hide();
      });

      return $li;
    })
  );

  chart.on('created', function() {
    var i = catsPlusAVG.length-1;
    $('g.ct-series-' + String.fromCharCode(97 + i), '.ct-chart-rates').hide();
  });

}

function buildPositionsChart(entries){
  var catsPlusTotals = categories.concat(["total"]);
  var aentries = _.sortBy(entries, 'ludum');

  var labels = _.map(aentries, function(entry){
    return 'LD' + entry.ludum;
  });

  var series = catsPlusTotals.map(function(category){
    var name = category;
    if (name === "total") name = "total entries";

    return {
      name: name,
      data: _.map(aentries, function(entry){
        return (entry[category] && entry[category]*-1) || null;
      })
    };
  });

  var chart = new Chartist.Line('.ct-chart-standings', {
    labels: labels,
    series: series
  }, {
    high: -1,
    //low: -3000,
    chartPadding: {
      top: 20,
      right: 120,
      bottom: 20,
      left: 10
    },
    axisX: {
      showGrid: true,
      showLabel: true,
      offset: 20,
      labelOffset: {
        x: -20,
        y: 10
      },
    },
    axisY: {
      position: 'start',
      showGrid: true,
      showLabel: true,
      scaleMinSpace: 30,
      labelInterpolationFnc: function(value) {
        return Math.abs(value);
      }
    },
  });

  var $chart = $('.ct-chart-standings');

  var $toolTip = $chart
    .append('

')
    .find('.tooltip')
    .hide();

  $chart.on('mouseenter', '.ct-point', function() {
    var $point = $(this),
      value = $point.attr('ct:value'),
      seriesName = $point.parent().attr('ct:series-name');
    $toolTip.html(seriesName + '
' + Math.abs(value)).show();
  });

  $chart.on('mouseleave', '.ct-point', function() {
    $toolTip.hide();
  });

  $chart.on('mousemove', function(event) {
    $toolTip.css({
      left: (event.offsetX || event.originalEvent.layerX) - $toolTip.width() / 2 - 10,
      top: (event.offsetY || event.originalEvent.layerY) - $toolTip.height() - 40
    });
  });

  var $categories = $('.standings .categories');

  $categories.empty().append(
    catsPlusTotals.map(function(category, i){
      var idx = String.fromCharCode(97 + i);

      var name = category;
      var $li = $('
'+name+'
');

      $li.on('click', function(){
        var el = $(this);

        if (el.hasClass('off')){
          el.removeClass('off');
          $('g.ct-series-' + idx, '.ct-chart-standings').show();
          return;
        }

        el.addClass('off');
        $('g.ct-series-' + idx, '.ct-chart-standings').hide();
      });

      return $li;
    })
  );

}
<commit_msg>refactor. #6<commit_after>
var categories = ['overall', 'fun', 'theme', 'innovation', 'humor', 'graphics', 'audio', 'mood'];
var builtTabs = [];
var author, rates, positions;

$(function(){
  attachEvents();
});

function attachEvents(){

  $('.loading').hide();
  $('.tabs-ctn, .tabs').hide();

  $('.tabs a').on('click', function(){
    var tab = $(this).attr('data-tab');
    $('.tab-content.active, .tabs a.active').removeClass('active');
    $('.tab-content.' + tab).add(this).addClass('active');
    buildTab(tab);
  });

  function updateShares(author){
    var twLink = 'https://twitter.com/intent/tweet?url=https%3A%2F%2Fldstats.info%2F{{author}}&hashtags=ldstats&text=Checkout+my+LudumDare+Stats';
    var fbLink = 'http://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fldstats.info%2F{{author}}&t=Checkout+my+LudumDare+Stats';
    var gpLink = 'https://plus.google.com/share?url=https%3A%2F%2Fldstats.info%2F{{author}}';

    $('.zocial.icon.twitter').attr('href', twLink.replace('{{author}}', author));
    $('.zocial.icon.facebook').attr('href', fbLink.replace('{{author}}', author));
    $('.zocial.icon.googleplus').attr('href', gpLink.replace('{{author}}', author));
  }

  function onFetch(atURL){
    var author = $('#username').val();
    if (author.trim().length){

      if (!atURL && window.history && window.history.pushState){
        window.history.pushState(null, null, "/" + author);
      }

      updateShares(author);

      $('.loading').show();
      clearView();
      fetchAuthor(author.trim());
    }
  }

  $('#fetch').on('click', onFetch)
  $('#username').on('keyup', function(e){
    if (e.keyCode === 13) onFetch();
  });

  if (window.run_author){
    $('#username').val(window.run_author);
    onFetch(true);
  }
}

function clearView(){
  window.builtTabs = [];
  $('.ct-chart-rates, .rates-data, .position-data, .categories').empty();
}

function fetchAuthor(author){
  $('.not-found').hide();
  $('.tabs-ctn, .tabs').hide();

  $.get('/api/authors/' + author)
    .done(function(author){
      $('.tabs-ctn, .tabs').show();

      window.author = author;
      window.rates = getData(categories.concat(["average"]), "scores");
      window.positions = getData(categories.concat(["total"]), "ranking");
      window.percents = getData(categories, "percents");

      var curr = $('.tabs a.active').attr('data-tab');
      buildTab(curr);
    })
    .fail(function() {
      $('.not-found').show();
    })
    .always(function() {
      $('.loading').hide();
    });
}

function buildTab(tab){
  if (builtTabs.indexOf(tab) === -1){

    switch (tab) {
      case "rates":
        buildRatesChart(window.rates);
        break;
      case "data":
        createDataTable('#rates-data', categories.concat(["average"]), window.rates, function(value){
          if (value >= 4){
            return ''+value+'	';
          }
        });
        break;
      case "standings":
        buildPositionsChart(window.positions);
        break;
      case "podium":
        createDataTable('#position-data', categories.concat(["total"]), window.positions, function(value){
          if (value > 0 && value <= 100){
            if (value < 4){
              return '

	';
            }
            return ''+value+'	';
          }
        });
        break;
      case "percents":
        createDataTable('#percents-data', categories, window.percents, function(value){
          if (value > 0 && value < 10) {
            return ''+value+'	';
          }
        });
        break;
      case "coolness":
        createDataTable('#coolness-data', ['coolness'], window.author.entries);
        break;
    }

    builtTabs.push(tab);
  }
}

function getData(categories, field) {
  return _.map(_.cloneDeep(window.author.entries), function(entry, i){

    var en = {
      ludum: entry.ludum,
      title: entry.title,
      link: entry.link,
      type: entry.type,
    };

    function getValue(name){
      return entry[field] && entry[field][name] || 0;
    }

    categories.forEach(function(category){
      var value = getValue(category);
      en[category] = value;
    });

    return en;
  });
}

function createDataTable(id, columns, entries, onCellValue, sort){
  sort = sort || { dir: 'asc', col: 'ludum' };
  var $table = $(id).empty();

  var _cols = '';
  _.times(columns.length+2, function(i){ _cols += '<colgroup/>'; })
  var $cols = $(_cols).appendTo($table);

  var $thead = $('
').appendTo($table);
  var $tbody = $('
').appendTo($table);

  var $theadTR = $(
    '
' +
      'LD	' +
      'Entry	' +
    '
');

  $theadTR.append(
    _.map(columns, function(category){
      return ''+category+'	';
    })
  );

  $thead.append($theadTR);

  var sEntries = _.sortByOrder(entries, [sort.col], [sort.dir]);

  var $rows = _.map(sEntries, function(entry, i){
    var $tr = $('
');
    $tr.append(''+entry.ludum+'	');
    $tr.append(''+entry.title+' ('+entry.type+')	');

    $tr.append(
      _.map(columns, function(category){
        var value = entry[category];
        return (onCellValue && onCellValue(value)) || ''+(value || '-')+'	';
      })
    );

    return $tr;
  });

  $tbody.append($rows);

  $thead
    .find('th[data-sort='+sort.col+']')
    .addClass('sorting').addClass(sort.dir)
    .append('
');

  $table
    .on('mouseover', 'td', function(){
      var i = $(this).prevAll('td').length;
      $(this).parent().addClass('cell-hover');

      if ($(this).index() > 1) {
        $($cols[i]).addClass('cell-hover');
      }
    })
    .on('mouseout', 'td', function(){
      var i = $(this).prevAll('td').length;
      $(this).parent().removeClass('cell-hover');
      $($cols[i]).removeClass('cell-hover');
    })
    .on('mouseleave', function(){
      $cols.removeClass('cell-hover');
    })
    .on('click', 'th', function(e){
      var th = $(this);
      var col = th.attr('data-sort');

      var isSame = th.hasClass('sorting');
      var dir = isSame && th.hasClass('asc') ? 'desc' : 'asc';

      $table.off();
      createDataTable(id, columns, entries, onCellValue, { dir: dir, col: col });
    });

  return $table;
}

function buildRatesChart(entries){
  var catsPlusAVG = categories.concat(["average"]);
  var aentries = _.sortBy(entries, 'ludum');

  var labels = _.map(aentries, function(entry){
    return 'LD' + entry.ludum;
  });

  var series = catsPlusAVG.map(function(category){
    return {
      name: category,
      data: _.map(aentries, function(entry){
        return entry[category] || null;
      })
    };
  });

  var chart = new Chartist.Line('.ct-chart-rates', {
    labels: labels,
    series: series
  }, {
    high: 5,
    low: 0,
    lineSmooth: Chartist.Interpolation.simple({
      divisor: 4
    }),
    chartPadding: {
      top: 20,
      right: 120,
      bottom: 20,
      left: 0
    },
    axisX: {
      showGrid: true,
      showLabel: true,
      offset: 20,
      labelOffset: {
        x: -20,
        y: 10
      },
    },
    axisY: {
      position: 'start',
      showGrid: true,
      showLabel: true,
      scaleMinSpace: 30,
    },
  });

  var $chart = $('.ct-chart-rates');

  var $toolTip = $chart
    .append('

')
    .find('.tooltip')
    .hide();

  $chart.on('mouseenter', '.ct-point', function() {
    var $point = $(this),
      value = $point.attr('ct:value'),
      seriesName = $point.parent().attr('ct:series-name');
    $toolTip.html(seriesName + '
' + value).show();
  });

  $chart.on('mouseleave', '.ct-point', function() {
    $toolTip.hide();
  });

  $chart.on('mousemove', function(event) {
    $toolTip.css({
      left: (event.offsetX || event.originalEvent.layerX) - $toolTip.width() / 2 - 10,
      top: (event.offsetY || event.originalEvent.layerY) - $toolTip.height() - 40
    });
  });

  var $categories = $('.rates .categories');

  $categories.empty().append(
    catsPlusAVG.map(function(category, i){
      var idx = String.fromCharCode(97 + i);
      var $li = $('
'+category+'
');

      if (category === "average"){
        $li.addClass('off');
      }

      $li.on('click', function(){
        var el = $(this);

        if (el.hasClass('off')){
          el.removeClass('off');
          $('g.ct-series-' + idx, '.ct-chart-rates').show();
          return;
        }

        el.addClass('off');
        $('g.ct-series-' + idx, '.ct-chart-rates').hide();
      });

      return $li;
    })
  );

  chart.on('created', function() {
    var i = catsPlusAVG.length-1;
    $('g.ct-series-' + String.fromCharCode(97 + i), '.ct-chart-rates').hide();
  });

}

function buildPositionsChart(entries){
  var catsPlusTotals = categories.concat(["total"]);
  var aentries = _.sortBy(entries, 'ludum');

  var labels = _.map(aentries, function(entry){
    return 'LD' + entry.ludum;
  });

  var series = catsPlusTotals.map(function(category){
    var name = category;
    if (name === "total") name = "total entries";

    return {
      name: name,
      data: _.map(aentries, function(entry){
        return (entry[category] && entry[category]*-1) || null;
      })
    };
  });

  var chart = new Chartist.Line('.ct-chart-standings', {
    labels: labels,
    series: series
  }, {
    high: -1,
    //low: -3000,
    chartPadding: {
      top: 20,
      right: 120,
      bottom: 20,
      left: 10
    },
    axisX: {
      showGrid: true,
      showLabel: true,
      offset: 20,
      labelOffset: {
        x: -20,
        y: 10
      },
    },
    axisY: {
      position: 'start',
      showGrid: true,
      showLabel: true,
      scaleMinSpace: 30,
      labelInterpolationFnc: function(value) {
        return Math.abs(value);
      }
    },
  });

  var $chart = $('.ct-chart-standings');

  var $toolTip = $chart
    .append('

')
    .find('.tooltip')
    .hide();

  $chart.on('mouseenter', '.ct-point', function() {
    var $point = $(this),
      value = $point.attr('ct:value'),
      seriesName = $point.parent().attr('ct:series-name');
    $toolTip.html(seriesName + '
' + Math.abs(value)).show();
  });

  $chart.on('mouseleave', '.ct-point', function() {
    $toolTip.hide();
  });

  $chart.on('mousemove', function(event) {
    $toolTip.css({
      left: (event.offsetX || event.originalEvent.layerX) - $toolTip.width() / 2 - 10,
      top: (event.offsetY || event.originalEvent.layerY) - $toolTip.height() - 40
    });
  });

  var $categories = $('.standings .categories');

  $categories.empty().append(
    catsPlusTotals.map(function(category, i){
      var idx = String.fromCharCode(97 + i);

      var name = category;
      var $li = $('
'+name+'
');

      $li.on('click', function(){
        var el = $(this);

        if (el.hasClass('off')){
          el.removeClass('off');
          $('g.ct-series-' + idx, '.ct-chart-standings').show();
          return;
        }

        el.addClass('off');
        $('g.ct-series-' + idx, '.ct-chart-standings').hide();
      });

      return $li;
    })
  );

}
<|endoftext|>


<commit_before>/*
 *= require jquery
 *= require jquery_ujs
 *= require jquery-ui
 *= require jquery.jeditable
 *= require bootstrap
 *= require bootstrap-datepicker/core
 *= require_self
*/
function autoComplete(model, attribute, path) {
  jQuery('#' + attribute + '_auto_complete').autocomplete({
    delay: 200,
    minLength: 3,
    source: function(request, response) {
      jQuery.getJSON(path, { name: request.term }, response);
    },
    messages: {
      noResults: null,
      results: function() {}
    },
    focus: function(event, ui) {
      jQuery('#promoter_auto_complete').val(ui.item.first_name + ' ' + ui.item.last_name);
      return false;
    },
    select: function(event, ui) {
      jQuery('#promoter_auto_complete').val(ui.item.first_name + ' ' + ui.item.last_name);
      jQuery('#event_promoter_id').val(ui.item.id);
      jQuery('#event_promoter_id').change();
      return false;
    }
  })
  .data("ui-autocomplete")
  ._renderItem = function(ul, item) {
      var description = [];
      if (item !== undefined && item.team_name !== undefined && item.team_name !== '') {
        description.push(item.team_name);
      }
      if (item.city !== undefined && jQuery.trim(item.city) !== '') {
        description.push(jQuery.trim(item.city));
      }
      if (item.state !== undefined && jQuery.trim(item.state) !== '') {
        description.push(jQuery.trim(item.state));
      }

      return jQuery('

')
        .data( "item.autocomplete", item )
        .append('' + item.first_name + ' ' + item.last_name + '
' + description.join(', ') + "
")
        .appendTo( ul );
    };
}

function autoCompleteTeam(model, attribute, path) {
  jQuery(document).ready(function() {
    jQuery('#' + attribute + '_auto_complete').autocomplete({
      delay: 200,
      minLength: 3,
      source: function(request, response) {
        jQuery.getJSON(path, { name: request.term }, response);
      },
      messages: {
        noResults: null,
        results: function() {}
      },
      focus: function(event, ui) {
        jQuery('#team_auto_complete').val(ui.item.name);
        return false;
      },
      select: function(event, ui) {
        jQuery('#team_auto_complete').val(ui.item.name);
        jQuery('#event_team_id').val(ui.item.id);
        return false;
      }
    })
    .data("ui-autocomplete")
    ._renderItem = function(ul, item) {
        return jQuery('

')
          .data( "item.autocomplete", item )
          .append('' + item.name + '')
          .appendTo( ul );
      };
    ;
  });
}

function makeEditable() {
  jQuery('.editable').editable(
    function(value, settings) {
      var element = jQuery(this);
      element.find("input").attr("disabled", "disabled");
      element.addClass('saving');
      var ajaxoptions = {
        type    : 'POST',
        data    : {
          '_method': 'PATCH',
          name: element.data('attribute'),
          value: value
        },
        dataType: 'html',
        url     : element.data('url'),
        success : function(result, status, jqXHR) {
          if (jqXHR.getResponseHeader('Content-Type').indexOf('text/javascript') == -1) {
            element.html(result);
            element.removeClass('saving');
            if (!jQuery.trim(element.html())) {
              element.html(settings.placeholder);
            }
          }
          else {
            element.removeClass('saving');
            jQuery.globalEval(result);
          }
        },
        error   : function(xhr, status, error) {
          element.removeClass('saving');
          var originalColor = element.css('background-color');
          element.css({ 'background-color': 'rgb(255, 204, 204)' });
          element.animate({ 'background-color': originalColor }, 2000);
          element.html(element.data('original'));
        }
      };
      jQuery.ajax(ajaxoptions);
    },
    {
      cssclass: 'editor_field',
      method: 'POST',
      placeholder: '',
      select: true,
      onblur: 'ignore',
      onedit: function() {
        jQuery(this).addClass('editing');
        return true;
      },
      onreset: function() {
        jQuery(this).closest('.editing').removeClass('editing');
        return true;
      },
      callback: function(value, settings) {
        jQuery(this).closest('.editing').removeClass('editing');
        return true;
      }
    }
  );
}

jQuery(document).ready(function() {
  makeEditable();
  jQuery('.wants_focus:visible').select();
});
<commit_msg>Remove stray semicolon<commit_after>/*
 *= require jquery
 *= require jquery_ujs
 *= require jquery-ui
 *= require jquery.jeditable
 *= require bootstrap
 *= require bootstrap-datepicker/core
 *= require_self
*/
function autoComplete(model, attribute, path) {
  jQuery('#' + attribute + '_auto_complete').autocomplete({
    delay: 200,
    minLength: 3,
    source: function(request, response) {
      jQuery.getJSON(path, { name: request.term }, response);
    },
    messages: {
      noResults: null,
      results: function() {}
    },
    focus: function(event, ui) {
      jQuery('#promoter_auto_complete').val(ui.item.first_name + ' ' + ui.item.last_name);
      return false;
    },
    select: function(event, ui) {
      jQuery('#promoter_auto_complete').val(ui.item.first_name + ' ' + ui.item.last_name);
      jQuery('#event_promoter_id').val(ui.item.id);
      jQuery('#event_promoter_id').change();
      return false;
    }
  })
  .data("ui-autocomplete")
  ._renderItem = function(ul, item) {
      var description = [];
      if (item !== undefined && item.team_name !== undefined && item.team_name !== '') {
        description.push(item.team_name);
      }
      if (item.city !== undefined && jQuery.trim(item.city) !== '') {
        description.push(jQuery.trim(item.city));
      }
      if (item.state !== undefined && jQuery.trim(item.state) !== '') {
        description.push(jQuery.trim(item.state));
      }

      return jQuery('

')
        .data( "item.autocomplete", item )
        .append('' + item.first_name + ' ' + item.last_name + '
' + description.join(', ') + "
")
        .appendTo( ul );
    };
}

function autoCompleteTeam(model, attribute, path) {
  jQuery(document).ready(function() {
    jQuery('#' + attribute + '_auto_complete').autocomplete({
      delay: 200,
      minLength: 3,
      source: function(request, response) {
        jQuery.getJSON(path, { name: request.term }, response);
      },
      messages: {
        noResults: null,
        results: function() {}
      },
      focus: function(event, ui) {
        jQuery('#team_auto_complete').val(ui.item.name);
        return false;
      },
      select: function(event, ui) {
        jQuery('#team_auto_complete').val(ui.item.name);
        jQuery('#event_team_id').val(ui.item.id);
        return false;
      }
    })
    .data("ui-autocomplete")
    ._renderItem = function(ul, item) {
        return jQuery('

')
          .data( "item.autocomplete", item )
          .append('' + item.name + '')
          .appendTo( ul );
      };
  });
}

function makeEditable() {
  jQuery('.editable').editable(
    function(value, settings) {
      var element = jQuery(this);
      element.find("input").attr("disabled", "disabled");
      element.addClass('saving');
      var ajaxoptions = {
        type    : 'POST',
        data    : {
          '_method': 'PATCH',
          name: element.data('attribute'),
          value: value
        },
        dataType: 'html',
        url     : element.data('url'),
        success : function(result, status, jqXHR) {
          if (jqXHR.getResponseHeader('Content-Type').indexOf('text/javascript') == -1) {
            element.html(result);
            element.removeClass('saving');
            if (!jQuery.trim(element.html())) {
              element.html(settings.placeholder);
            }
          }
          else {
            element.removeClass('saving');
            jQuery.globalEval(result);
          }
        },
        error   : function(xhr, status, error) {
          element.removeClass('saving');
          var originalColor = element.css('background-color');
          element.css({ 'background-color': 'rgb(255, 204, 204)' });
          element.animate({ 'background-color': originalColor }, 2000);
          element.html(element.data('original'));
        }
      };
      jQuery.ajax(ajaxoptions);
    },
    {
      cssclass: 'editor_field',
      method: 'POST',
      placeholder: '',
      select: true,
      onblur: 'ignore',
      onedit: function() {
        jQuery(this).addClass('editing');
        return true;
      },
      onreset: function() {
        jQuery(this).closest('.editing').removeClass('editing');
        return true;
      },
      callback: function(value, settings) {
        jQuery(this).closest('.editing').removeClass('editing');
        return true;
      }
    }
  );
}

jQuery(document).ready(function() {
  makeEditable();
  jQuery('.wants_focus:visible').select();
});
<|endoftext|>


<commit_before>'use strict';

// Call this function when the page loads (the "ready" event)
$(document).ready(function() {
	initializePage();
})

/*
 * Function that is called when the document is ready.
 */
function initializePage() {

    $("#registerButton").click(register);

}

function register(e) {
	var word = document.getElementById("#username").value;
	alert(escape(word));
    window.location.href = "register";
}
<commit_msg>Changes.<commit_after>'use strict';

// Call this function when the page loads (the "ready" event)
$(document).ready(function() {
	initializePage();
})

/*
 * Function that is called when the document is ready.
 */
function initializePage() {

    $("#registerButton").click(register);

}

function register(e) {
	var word = document.getElementById("#username").value;
	alert("hi");
    window.location.href = "register";
}
<|endoftext|>


<commit_before>'use strict';

/**
 * @author      hustcer
 * @license     MIT
 * @copyright   TraceInvest.com
 * @create      07/08/2015
 * @example
 *      star -i 002065    // 查询东华软件高管交易信息
 *      star -i 300036    // 查询超图软件高管交易信息
 *      star -i 000060    // 查询中金岭南高管交易信息
 *      star -i 603993    // 查询洛阳钼业高管交易信息
 *      star -i 000768,002456,600118,601777,300036,000902 --span 3m
 * @see
 *      深中小板高管持股变动: http://www.szse.cn/main/sme/jgxxgk/djggfbd/
 *      深创业板高管持股变动: http://www.szse.cn/main/chinext/jgxxgk/djggfbd/
 *      深圳主板高管持股变动: http://www.szse.cn/main/mainboard/jgxxgk/djggfbd/
 *      上海主板高管持股变动: http://www.sse.com.cn/disclosure/listedinfo/credibility/change/
 */

let _       = require('lodash'),
    moment  = require('moment'),
    printf  = require('printf'),
    cheerio = require('cheerio'),
    numeral = require('numeral'),
    cmd     = require('commander');

let start   = new Date().getTime();
let conf    = require('./conf.js').conf;
let Iconv   = require('iconv').Iconv;
let iconv   = new Iconv('GBK', 'UTF-8//TRANSLIT//IGNORE');
let request = require('request');

let from = null;
let to   = null;
let ft   = conf.fmt;

numeral.language('chs', conf.numeral);
// switch between languages
numeral.language('chs');
numeral.defaultFormat(ft.common);

/**
 * 各类提示信息
 * @type {Object}
 */
const MSG = {
    NO_TRADING    : '在当前时间范围内无董监高交易记录！',
    PARAM_ERROR   : '参数输入错误，请检查后重试！',
    INPUT_ERROR   : '输入错误，当前只支持通过单只证券代码查询，请重新输入！',
    REQUEST_ERROR : '数据请求错误，请重试！错误信息：\n'
};

/**
 * 计算董监高交易信息汇总摘要数据
 * @param  {Array} tradings  Trading array.
 * @return {Object}          Trading summary.
 */
let calcSummary = function(tradings){
    if(tradings.length === 0){ return null; }

    let summary = {
        buyShare   : 0,
        sellShare  : 0,
        buyPrice   : 0,
        sellPrice  : 0,
        buyCost    : 0,
        sellProfit : 0,
        netBuyShare: 0,
        netBuyCost : 0
    };
    _.each(tradings, t => {
        if(t.CHANGE_NUM > 0){
            summary.buyShare += t.CHANGE_NUM;
            summary.buyCost  += t.CHANGE_NUM*t.CURRENT_AVG_PRICE;
        }else{
            summary.sellShare  += Math.abs(t.CHANGE_NUM);
            summary.sellProfit += Math.abs(t.CHANGE_NUM*t.CURRENT_AVG_PRICE);
        }
    });

    summary.buyPrice    = (summary.buyShare  !== 0) ? summary.buyCost/summary.buyShare     :'N/A';
    summary.sellPrice   = (summary.sellShare !== 0) ? summary.sellProfit/summary.sellShare :'N/A';
    summary.netBuyShare = summary.buyShare - summary.sellShare;
    summary.netBuyCost  = summary.buyCost  - summary.sellProfit;

    summary.buyShare    = numeral(summary.buyShare).format();
    summary.sellShare   = numeral(summary.sellShare).format();
    summary.netBuyShare = numeral(summary.netBuyShare).format();
    summary.buyPrice    = numeral(summary.buyPrice).format(ft.flot);
    summary.sellPrice   = numeral(summary.sellPrice).format(ft.flot);
    summary.buyCost     = numeral(summary.buyCost).format(ft.money);
    summary.netBuyCost  = numeral(summary.netBuyCost).format(ft.money);
    summary.sellProfit  = numeral(summary.sellProfit).format(ft.money);

    return summary;
};

/**
 * Get trading data from html segment.
 * @param  {String} html Html string
 * @return {Array}      Trading records.
 */
let getTradings = function(html){
    let data = [];
    let $    = cheerio.load(html, {decodeEntities:false});
    let $td  = null;
    $('tr.cls-data-tr').each(function(){
        $td = $('td', this);
        data.push({
            COMPANY_CODE      : $td.eq(0).html(),
            COMPANY_ABBR      : $td.eq(1).html(),
            NAME              : $td.eq(2).html(),
            FORM_DATE         : $td.eq(3).html(),
            CHANGE_NUM        :+$td.eq(4).html(),
            CURRENT_AVG_PRICE :+$td.eq(5).html(),
            CHANGE_REASON     : $td.eq(6).html(),
            _RATIO            :+$td.eq(7).html(),
            HOLDSTOCK_NUM     :+$td.eq(8).html(),
            _INSIDER          : $td.eq(9).html(),
            DUTY              : $td.eq(10).html(),
            _RELATION         : $td.eq(11).html()
        });
    });
    return data;
};

let padding = function(str, length, direction){
    if(str.length < length){
        if(direction === 'left'){
            str = ' '.repeat((length - str.length)) + str;
        }
        str += ' '.repeat((length - str.length));
    }
    return str;
};

/**
 * Display insider trading details of specified symbol code
 * @param  {String} code     symbol code
 * @param  {Object} summary  Trading summary
 * @param  {Array} tradings  Trading records
 */
let displayDetail = function(code, summary, tradings){
    // console.log(JSON.stringify(summary, null, 4));
    // console.log(JSON.stringify(tradings, null, 4));
    if(from && to){
        console.log(('\n董监高近期交易信息，证券代码：'+ code + ', 从: ' + from + ', 到: '+ to + ' '.repeat(50)).em.underline);
    }else{
        console.log(('\n董监高近期交易信息，证券代码：'+ code + ' '.repeat(80)).em.underline);
    }
    if(!summary){
        console.log(MSG.NO_TRADING.info);
        return false;
    }
    console.log('净增持股数：' , printf('%7s', summary.netBuyShare), ' '.repeat(9),
                '净增持额：'  , printf('%9s', summary.netBuyCost));
    console.log('总增持股数：' , printf('%7s', summary.buyShare), ' '.repeat(9),
                '增持均价：'  , printf('%6s', summary.buyPrice), ' '.repeat(9),
                '总增持额：'  , printf('%9s', summary.buyCost));
    console.log('总减持股数：' , printf('%7s', summary.sellShare), ' '.repeat(9),
                '减持均价：'  , printf('%6s', summary.sellPrice), ' '.repeat(9),
                '总减持额：'  , printf('%9s', summary.sellProfit));

    console.log(('\n交易详情:'+' '.repeat(102)).header.underline);

    let market = conf.market[code.substr(0,3)];
    if(market === 'sz'){
        console.log((printf(conf.insider.sz.TH, '证券简称', '代码', '交易人', '变动股数', '均价',
                                                '结存股数', '填报日期', '变动原因', '高管姓名', '关系',
                                                '职务') + ' '.repeat(5)).underline);
        _.each(tradings, t => {
            t.NAME          = padding(t.NAME, 3);
            t.CHANGE_NUM    = numeral(t.CHANGE_NUM).format();
            t.HOLDSTOCK_NUM = _.isNaN(t.HOLDSTOCK_NUM)? '-' : numeral(t.HOLDSTOCK_NUM).format();
            t.FORM_DATE     = t.FORM_DATE.replace(/\-/g, '/');
            t._INSIDER      = padding(t._INSIDER, 3);
            console.log(printf(conf.insider.sz.TD, t.COMPANY_ABBR, t.COMPANY_CODE, t.NAME,
                               t.CHANGE_NUM, t.CURRENT_AVG_PRICE, t.HOLDSTOCK_NUM, t.FORM_DATE,
                               t.CHANGE_REASON, t._INSIDER, t._RELATION, t.DUTY));
        });
        return false;
    }
    console.log((printf(conf.insider.sh.TH, '证券简称', '代码', '交易人', '变动股数', '均价',
                                            '结存股数', '变动日期', '填报日期', '变动原因', '职务') +
                                            ' '.repeat(10)).underline);
    _.each(tradings, t => {
        t.NAME          = padding(t.NAME, 3);
        t.CHANGE_NUM    = numeral(t.CHANGE_NUM).format();
        t.HOLDSTOCK_NUM = numeral(t.HOLDSTOCK_NUM).format();
        t.CHANGE_DATE   = t.CHANGE_DATE.replace(/\-/g, '/');
        t.FORM_DATE     = t.FORM_DATE.replace(/\-/g, '/');
        console.log(printf(conf.insider.sh.TD, t.COMPANY_ABBR, t.COMPANY_CODE, t.NAME,
                           t.CHANGE_NUM, t.CURRENT_AVG_PRICE, t.HOLDSTOCK_NUM, t.CHANGE_DATE,
                           t.FORM_DATE, t.CHANGE_REASON, t.DUTY));
    });
};

/**
 * Get query options from code and cmd input
 * @param  {String} code Symbol code
 * @return {Object}      Query options
 */
let getOption = function(code){

    let market = conf.market[code.substr(0,3)];
    let option = conf.insider[market];
    let spanM  = cmd.span || option.span;
    option.qs[option.codeKey] = code;
    if(market === 'sz'){
        option.qs.CATALOGID = option.catalog[code.substr(0,3)];
    }
    if(spanM){
        let span = parseInt(spanM);
        span = span > 24 ? 24: span;
        span = span < 1 ?   1: span;
        option.qs[option.endKey]   = moment().format(ft.outDate);
        option.qs[option.beginKey] = moment().subtract(span, 'month').format(ft.outDate);
    }
    if(cmd.from){
        if(moment(cmd.from, ft.inDate).isValid()){
            option.qs[option.beginKey] = moment(cmd.from, ft.inDate).format(ft.outDate);
        }else{
            console.error(MSG.PARAM_ERROR.em);
            return false;
        }
    }
    if(cmd.to){
        if(moment(cmd.to, ft.inDate).isValid()){
            option.qs[option.endKey] = moment(cmd.to, ft.inDate).format(ft.outDate);
        }else{
            console.error(MSG.PARAM_ERROR.em);
            return false;
        }
    }
    from = moment(option.qs[option.beginKey]).format(ft.inDate);
    to   = moment(option.qs[option.endKey]).format(ft.inDate);
    // console.log(JSON.stringify(option.qs, null, 4));
    return option;
};

/**
 * Query insider tradings from the specified symbol code
 * @param {String}      code    Symbol code of specified company.
 * @param {Function}    cb      Callback function
 */
let queryInsider = function(code, cb) {
    if(!Number.isInteger(Number(code))){
        console.error(MSG.INPUT_ERROR);
        return false;
    }
    let market = conf.market[code.substr(0,3)];
    let option = getOption(code);

    request(option, function(e, r, body){
        let tradings = [];
        if(e || (r && r.statusCode !== 200)){
            console.error(MSG.REQUEST_ERROR, printf(JSON.stringify(e||r, null, 4).error));
            return false;
        }
        if(market === 'sz'){
            let html = iconv.convert(body).toString();
            tradings = getTradings(html);

        }else{
            let Common = require('./common.js').Common;
            tradings   = Common.parseJsonP(body).result;
            _.each(tradings, t => {
                t.CHANGE_NUM        = +t.CHANGE_NUM;
                t.HOLDSTOCK_NUM     = +t.HOLDSTOCK_NUM;
                // t.CURRENT_AVG_PRICE could be null, check symbol code: 600056 frome 2006/06/01
                t.CURRENT_AVG_PRICE = +t.CURRENT_AVG_PRICE || 0;
                return t;
            });
        }
        let summary  = calcSummary(tradings);
        displayDetail(code, summary, tradings);

        let end      = new Date().getTime();
        console.log(' '.repeat(111).underline.yellow);

        console.log(' '.repeat(35) + 'Done!'.header, '操作耗时:', ((end - start) + ' ms').em,
                    ', 总交易记录：' + (tradings.length+'').em,
                    ' '.repeat(15),'By TraceInvest.com\n' );

        if(_.isFunction(cb)){ cb(); }
    });
};

exports.Insider = {
    queryInsider : queryInsider
};
<commit_msg>Refactor insider trading query<commit_after>'use strict';

/**
 * @author      hustcer
 * @license     MIT
 * @copyright   TraceInvest.com
 * @create      07/08/2015
 * @example
 *      star -i 002065    // 查询东华软件高管交易信息
 *      star -i 300036    // 查询超图软件高管交易信息
 *      star -i 000060    // 查询中金岭南高管交易信息
 *      star -i 603993    // 查询洛阳钼业高管交易信息
 *      star -i 000768,002456,600118,601777,300036,000902 --span 3m
 * @see
 *      深中小板高管持股变动: http://www.szse.cn/main/sme/jgxxgk/djggfbd/
 *      深创业板高管持股变动: http://www.szse.cn/main/chinext/jgxxgk/djggfbd/
 *      深圳主板高管持股变动: http://www.szse.cn/main/mainboard/jgxxgk/djggfbd/
 *      上海主板高管持股变动: http://www.sse.com.cn/disclosure/listedinfo/credibility/change/
 */

let _       = require('lodash'),
    moment  = require('moment'),
    printf  = require('printf'),
    cheerio = require('cheerio'),
    numeral = require('numeral'),
    cmd     = require('commander');

let start   = new Date().getTime();
let conf    = require('./conf.js').conf;
let Iconv   = require('iconv').Iconv;
let iconv   = new Iconv('GBK', 'UTF-8//TRANSLIT//IGNORE');
let request = require('request');

let from = null;
let to   = null;
let ft   = conf.fmt;

numeral.language('chs', conf.numeral);
// switch between languages
numeral.language('chs');
numeral.defaultFormat(ft.common);

/**
 * 各类提示信息
 * @type {Object}
 */
const MSG = {
    NO_TRADING    : '在当前时间范围内无董监高交易记录！',
    PARAM_ERROR   : '参数输入错误，请检查后重试！',
    INPUT_ERROR   : '输入错误，当前只支持通过单只证券代码查询，请重新输入！',
    REQUEST_ERROR : '数据请求错误，请重试！错误信息：\n'
};

/**
 * 计算董监高交易信息汇总摘要数据
 * @param  {Array} tradings  Trading array.
 * @return {Object}          Trading summary.
 */
let calcSummary = function(tradings){
    if(tradings.length === 0){ return null; }

    let summary = {
        buyShare   : 0,
        sellShare  : 0,
        buyPrice   : 0,
        sellPrice  : 0,
        buyCost    : 0,
        sellProfit : 0,
        netBuyShare: 0,
        netBuyCost : 0
    };
    _.each(tradings, t => {
        if(t.CHANGE_NUM > 0){
            summary.buyShare += t.CHANGE_NUM;
            summary.buyCost  += t.CHANGE_NUM*t.CURRENT_AVG_PRICE;
        }else{
            summary.sellShare  += Math.abs(t.CHANGE_NUM);
            summary.sellProfit += Math.abs(t.CHANGE_NUM*t.CURRENT_AVG_PRICE);
        }
    });

    summary.buyPrice    = (summary.buyShare  !== 0) ? summary.buyCost/summary.buyShare     :'N/A';
    summary.sellPrice   = (summary.sellShare !== 0) ? summary.sellProfit/summary.sellShare :'N/A';
    summary.netBuyShare = summary.buyShare - summary.sellShare;
    summary.netBuyCost  = summary.buyCost  - summary.sellProfit;

    summary.buyShare    = numeral(summary.buyShare).format();
    summary.sellShare   = numeral(summary.sellShare).format();
    summary.netBuyShare = numeral(summary.netBuyShare).format();
    summary.buyPrice    = numeral(summary.buyPrice).format(ft.flot);
    summary.sellPrice   = numeral(summary.sellPrice).format(ft.flot);
    summary.buyCost     = numeral(summary.buyCost).format(ft.money);
    summary.netBuyCost  = numeral(summary.netBuyCost).format(ft.money);
    summary.sellProfit  = numeral(summary.sellProfit).format(ft.money);

    return summary;
};

/**
 * Get trading data from html segment.
 * @param  {String} html Html string
 * @return {Array}      Trading records.
 */
let getTradings = function(html){
    let data = [];
    let $    = cheerio.load(html, {decodeEntities:false});
    let $td  = null;
    $('tr.cls-data-tr').each(function(){
        $td = $('td', this);
        data.push({
            COMPANY_CODE      : $td.eq(0).html(),
            COMPANY_ABBR      : $td.eq(1).html(),
            NAME              : $td.eq(2).html(),
            FORM_DATE         : $td.eq(3).html(),
            CHANGE_NUM        :+$td.eq(4).html(),
            CURRENT_AVG_PRICE :+$td.eq(5).html(),
            CHANGE_REASON     : $td.eq(6).html(),
            _RATIO            :+$td.eq(7).html(),
            HOLDSTOCK_NUM     :+$td.eq(8).html(),
            _INSIDER          : $td.eq(9).html(),
            DUTY              : $td.eq(10).html(),
            _RELATION         : $td.eq(11).html()
        });
    });
    return data;
};

let padding = function(str, length, direction){
    if(str.length < length){
        if(direction === 'left'){
            str = ' '.repeat((length - str.length)) + str;
        }
        str += ' '.repeat((length - str.length));
    }
    return str;
};

/**
 * Display insider trading details of specified symbol code
 * @param  {String} code     symbol code
 * @param  {Object} summary  Trading summary
 * @param  {Array} tradings  Trading records
 */
let displayDetail = function(code, summary, tradings){
    // console.log(JSON.stringify(summary, null, 4));
    // console.log(JSON.stringify(tradings, null, 4));
    if(from && to){
        console.log(('\n董监高近期交易信息，证券代码：'+ code + ', 从: ' + from + ', 到: '+ to + ' '.repeat(50)).em.underline);
    }else{
        console.log(('\n董监高近期交易信息，证券代码：'+ code + ' '.repeat(80)).em.underline);
    }
    if(!summary){
        console.log(MSG.NO_TRADING.info);
        return false;
    }
    console.log('净增持股数：' , printf('%7s', summary.netBuyShare), ' '.repeat(9),
                '净增持额：'  , printf('%9s', summary.netBuyCost));
    console.log('总增持股数：' , printf('%7s', summary.buyShare), ' '.repeat(9),
                '增持均价：'  , printf('%6s', summary.buyPrice), ' '.repeat(9),
                '总增持额：'  , printf('%9s', summary.buyCost));
    console.log('总减持股数：' , printf('%7s', summary.sellShare), ' '.repeat(9),
                '减持均价：'  , printf('%6s', summary.sellPrice), ' '.repeat(9),
                '总减持额：'  , printf('%9s', summary.sellProfit));

    console.log(('\n交易详情:'+' '.repeat(102)).header.underline);

    let market = conf.market[code.substr(0,3)];
    market === 'sz' ? displaySZTradings(tradings):displaySHTradings(tradings);
};

/**
 * Display ShangHai market insider trading records.
 * @param  {Array} tradings   Insider trading records array
 */
let displaySHTradings = function(tradings){
    console.log((printf(conf.insider.sh.TH, '证券简称', '代码', '交易人', '变动股数', '均价',
                                            '结存股数', '变动日期', '填报日期', '变动原因', '职务') +
                                            ' '.repeat(10)).underline);
    _.each(tradings, t => {
        t.NAME          = padding(t.NAME, 3);
        t.CHANGE_NUM    = numeral(t.CHANGE_NUM).format();
        t.HOLDSTOCK_NUM = numeral(t.HOLDSTOCK_NUM).format();
        t.CHANGE_DATE   = t.CHANGE_DATE.replace(/\-/g, '/');
        t.FORM_DATE     = t.FORM_DATE.replace(/\-/g, '/');
        console.log(printf(conf.insider.sh.TD, t.COMPANY_ABBR, t.COMPANY_CODE, t.NAME,
                           t.CHANGE_NUM, t.CURRENT_AVG_PRICE, t.HOLDSTOCK_NUM, t.CHANGE_DATE,
                           t.FORM_DATE, t.CHANGE_REASON, t.DUTY));
    });
};

/**
 * Display ShenZhen market insider trading records.
 * @param  {Array} tradings   Insider trading records array
 */
let displaySZTradings = function(tradings){
    console.log((printf(conf.insider.sz.TH, '证券简称', '代码', '交易人', '变动股数', '均价',
                                            '结存股数', '填报日期', '变动原因', '高管姓名', '关系',
                                            '职务') + ' '.repeat(5)).underline);
    _.each(tradings, t => {
        t.NAME          = padding(t.NAME, 3);
        t.CHANGE_NUM    = numeral(t.CHANGE_NUM).format();
        t.HOLDSTOCK_NUM = _.isNaN(t.HOLDSTOCK_NUM)? '-' : numeral(t.HOLDSTOCK_NUM).format();
        t.FORM_DATE     = t.FORM_DATE.replace(/\-/g, '/');
        t._INSIDER      = padding(t._INSIDER, 3);
        console.log(printf(conf.insider.sz.TD, t.COMPANY_ABBR, t.COMPANY_CODE, t.NAME,
                           t.CHANGE_NUM, t.CURRENT_AVG_PRICE, t.HOLDSTOCK_NUM, t.FORM_DATE,
                           t.CHANGE_REASON, t._INSIDER, t._RELATION, t.DUTY));
    });
};

/**
 * Get query options from code and cmd input
 * @param  {String} code Symbol code
 * @return {Object}      Query options
 */
let getOption = function(code){

    let market = conf.market[code.substr(0,3)];
    let option = conf.insider[market];
    let spanM  = cmd.span || option.span;
    option.qs[option.codeKey] = code;
    if(market === 'sz'){
        option.qs.CATALOGID = option.catalog[code.substr(0,3)];
    }
    if(spanM){
        let span = parseInt(spanM);
        span = span > 24 ? 24: span;
        span = span < 1 ?   1: span;
        option.qs[option.endKey]   = moment().format(ft.outDate);
        option.qs[option.beginKey] = moment().subtract(span, 'month').format(ft.outDate);
    }
    if(cmd.from){
        if(moment(cmd.from, ft.inDate).isValid()){
            option.qs[option.beginKey] = moment(cmd.from, ft.inDate).format(ft.outDate);
        }else{
            console.error(MSG.PARAM_ERROR.em);
            return false;
        }
    }
    if(cmd.to){
        if(moment(cmd.to, ft.inDate).isValid()){
            option.qs[option.endKey] = moment(cmd.to, ft.inDate).format(ft.outDate);
        }else{
            console.error(MSG.PARAM_ERROR.em);
            return false;
        }
    }
    from = moment(option.qs[option.beginKey]).format(ft.inDate);
    to   = moment(option.qs[option.endKey]).format(ft.inDate);
    // console.log(JSON.stringify(option.qs, null, 4));
    return option;
};

/**
 * Query insider tradings from the specified symbol code
 * @param {String}      code    Symbol code of specified company.
 * @param {Function}    cb      Callback function
 */
let queryInsider = function(code, cb) {
    if(!Number.isInteger(Number(code))){
        console.error(MSG.INPUT_ERROR);
        return false;
    }
    let market = conf.market[code.substr(0,3)];
    let option = getOption(code);

    request(option, function(e, r, body){
        let tradings = [];
        if(e || (r && r.statusCode !== 200)){
            console.error(MSG.REQUEST_ERROR, printf(JSON.stringify(e||r, null, 4).error));
            return false;
        }
        if(market === 'sz'){
            let html = iconv.convert(body).toString();
            tradings = getTradings(html);

        }else{
            let Common = require('./common.js').Common;
            tradings   = Common.parseJsonP(body).result;
            _.each(tradings, t => {
                t.CHANGE_NUM        = +t.CHANGE_NUM;
                t.HOLDSTOCK_NUM     = +t.HOLDSTOCK_NUM;
                // t.CURRENT_AVG_PRICE could be null, check symbol code: 600056 frome 2006/06/01
                t.CURRENT_AVG_PRICE = +t.CURRENT_AVG_PRICE || 0;
                return t;
            });
        }
        let summary  = calcSummary(tradings);
        displayDetail(code, summary, tradings);

        let end      = new Date().getTime();
        console.log(' '.repeat(111).underline.yellow);

        console.log(' '.repeat(35) + 'Done!'.header, '操作耗时:', ((end - start) + ' ms').em,
                    ', 总交易记录：' + (tradings.length+'').em,
                    ' '.repeat(15),'By TraceInvest.com\n' );

        if(_.isFunction(cb)){ cb(); }
    });
};

exports.Insider = {
    queryInsider : queryInsider
};
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .

function add_to_cart(id, title, price)
{
	var key = 'product_' + id;
	var x=window.localStorage.getItem(key);
	if(JSON.parse(x)==null){
		x=[id, title, price, 1];

	} else {
		x=JSON.parse(x);
		x[3]=x[3]*1+1;
	}
	window.localStorage.setItem(key, JSON.stringify(x));
	update_orders_link();
}

function update_orders_input()
{
	var orders = cart_get_orders();
	$('#orders_input').val(orders);
}

function update_orders_button()
{
	var text = 'Cart (' + cart_get_number_of_items() + ')';
	$('#orders_button').val(text);
}

function update_orders_link()
{
    var text = 'Cart (' + cart_get_number_of_items() + ')';
    $('#orders_link').html(text);
}

function cart_get_number_of_items()
{
	var cnt = 0;
	for(var i =0; i < window.localStorage.length; i++)
	{
		var key = window.localStorage.key(i);
		var value = window.localStorage.getItem(key);
		value=JSON.parse(value);
		if(key.indexOf('product_')==0)
		{
			cnt = cnt + value[3]*1;
		}
	}
	return cnt;
}

function cart_get_orders()
{
	var orders = '';
	for(var i =0; i < window.localStorage.length; i++)
	{
		var key = window.localStorage.key(i);
		var value = window.localStorage.getItem(key);
		value=JSON.parse(value);
		if(key.indexOf('product_')==0)
		{
			orders= orders + key + '=' + value[3] + ',';
		}
	}
	return orders;
}

function add_order_table()
{
	if (cart_get_number_of_items()==0){
		var table = document.getElementById("OrdersTable");
	    var header = table.createTHead();
	    var row = header.insertRow(0);
	    var cell1 = row.insertCell(0);
	    cell1.innerHTML = "Empty cart";
	} else {
		var total_price='';
		var table = document.getElementById("OrdersTable");
	    var header = table.createTHead();
	    var row = header.insertRow(0);
	    var cell1 = row.insertCell(0);
	    var cell2 = row.insertCell(1);
	    var cell3 = row.insertCell(2);
	    var cell4 = row.insertCell(3);
	    var cell5 = row.insertCell(4);
	    cell1.innerHTML = "#";
	    cell2.innerHTML = "Pin";
	    cell3.innerHTML = "Price";
	    cell4.innerHTML = "Quantity";
	    cell5.innerHTML = "Sum Price";
	    for(var i =0; i < window.localStorage.length; i++)
		{
			var key = window.localStorage.key(i);
			var value = window.localStorage.getItem(key);
			value=JSON.parse(value);
			if(key.indexOf('product_')==0)
			{
				var row = table.insertRow(i+1);
				var cell1 = row.insertCell(0);
	    		var cell2 = row.insertCell(1);
	    		var cell3 = row.insertCell(2);
	    		var cell4 = row.insertCell(3);
	    		var cell5 = row.insertCell(4);
	    		cell1.innerHTML = '' + (i+1) + '';
	    		cell2.innerHTML = ''+value[1]+'';
	    		cell3.innerHTML = value[2] + ' $';
	    		cell4.innerHTML = ' ' +value[3]+ ' ';
	    		cell5.innerHTML = value[2]*value[3] +' $  ' + ' ';
	    		total_price=total_price*1+value[2]*value[3];

			}
		}
		var row = table.insertRow();
		var cell1 = row.insertCell(0);
	    var cell2 = row.insertCell(1);
	    var cell3 = row.insertCell(2);
	    var cell4 = row.insertCell(3);
	    var cell5 = row.insertCell(4);
	    cell1.innerHTML = "";
	    cell2.innerHTML = "";
	    cell3.innerHTML = "";
	    cell4.innerHTML = "Total Quantity: " + cart_get_number_of_items();
	    cell5.innerHTML = "Total price: " + total_price + ' $';
	}
}

function decrease_quantity(id)
{
	var key = 'product_' + id;
	var x=window.localStorage.getItem(key);
	x=JSON.parse(x);
	if(x[3]==0){
		localStorage.removeItem(key);
	} else{
		x[3]=x[3]*1-1;
		window.localStorage.setItem(key, JSON.stringify(x));
	}
	location.reload();
}

function increase_quantity(id)
{
	var key = 'product_' + id;
	var x=window.localStorage.getItem(key);
	x=JSON.parse(x);
	x[3]=x[3]*1+1;
	window.localStorage.setItem(key, JSON.stringify(x));
	location.reload();
}

function delete_product(id)
{
	var key = 'product_' + id;
	localStorage.removeItem(key);
	location.reload();
}<commit_msg>add total price function js<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .

function add_to_cart(id, title, price)
{
	var key = 'product_' + id;
	var x=window.localStorage.getItem(key);
	if(JSON.parse(x)==null){
		x=[id, title, price, 1];

	} else {
		x=JSON.parse(x);
		x[3]=x[3]*1+1;
	}
	window.localStorage.setItem(key, JSON.stringify(x));
	update_orders_link();
}

function update_orders_input()
{
	var orders = cart_get_orders();
	$('#orders_input').val(orders);
}

function update_order_price_input()
{
	var price = cart_total_price();
	$('#order_price').val(price);
}

function update_orders_button()
{
	var text = 'Cart (' + cart_get_number_of_items() + ')';
	$('#orders_button').val(text);
}

function update_orders_link()
{
    var text = 'Cart (' + cart_get_number_of_items() + ')';
    $('#orders_link').html(text);
}

function cart_get_number_of_items()
{
	var cnt = 0;
	for(var i =0; i < window.localStorage.length; i++)
	{
		var key = window.localStorage.key(i);
		var value = window.localStorage.getItem(key);
		value=JSON.parse(value);
		if(key.indexOf('product_')==0)
		{
			cnt = cnt + value[3]*1;
		}
	}
	return cnt;
}

function cart_total_price()
{
	var total_price = 0;
	for(var i =0; i < window.localStorage.length; i++)
	{
		var key = window.localStorage.key(i);
		var value = window.localStorage.getItem(key);
		value=JSON.parse(value);
		if(key.indexOf('product_')==0)
		{
			total_price=total_price*1+value[2]*value[3];
		}
	}
	return total_price;
}

function cart_get_orders()
{
	var orders = '';
	for(var i =0; i < window.localStorage.length; i++)
	{
		var key = window.localStorage.key(i);
		var value = window.localStorage.getItem(key);
		value=JSON.parse(value);
		if(key.indexOf('product_')==0)
		{
			orders= orders + key + '=' + value[3] + ',';
		}
	}
	return orders;
}

function add_order_table()
{
	if (cart_get_number_of_items()==0){
		var table = document.getElementById("OrdersTable");
	    var header = table.createTHead();
	    var row = header.insertRow(0);
	    var cell1 = row.insertCell(0);
	    cell1.innerHTML = "Empty cart";
	} else {
		//var total_price='';
		var table = document.getElementById("OrdersTable");
	    var header = table.createTHead();
	    var row = header.insertRow(0);
	    var cell1 = row.insertCell(0);
	    var cell2 = row.insertCell(1);
	    var cell3 = row.insertCell(2);
	    var cell4 = row.insertCell(3);
	    var cell5 = row.insertCell(4);
	    cell1.innerHTML = "#";
	    cell2.innerHTML = "Pin";
	    cell3.innerHTML = "Price";
	    cell4.innerHTML = "Quantity";
	    cell5.innerHTML = "Sum Price";
	    for(var i =0; i < window.localStorage.length; i++)
		{
			var key = window.localStorage.key(i);
			var value = window.localStorage.getItem(key);
			value=JSON.parse(value);
			if(key.indexOf('product_')==0)
			{
				var row = table.insertRow(i+1);
				var cell1 = row.insertCell(0);
	    		var cell2 = row.insertCell(1);
	    		var cell3 = row.insertCell(2);
	    		var cell4 = row.insertCell(3);
	    		var cell5 = row.insertCell(4);
	    		cell1.innerHTML = '' + (i+1) + '';
	    		cell2.innerHTML = ''+value[1]+'';
	    		cell3.innerHTML = value[2] + ' $';
	    		cell4.innerHTML = ' ' +value[3]+ ' ';
	    		cell5.innerHTML = value[2]*value[3] +' $  ' + ' ';
	    		//total_price=total_price*1+value[2]*value[3];

			}
		}
		var row = table.insertRow();
		var cell1 = row.insertCell(0);
	    var cell2 = row.insertCell(1);
	    var cell3 = row.insertCell(2);
	    var cell4 = row.insertCell(3);
	    var cell5 = row.insertCell(4);
	    cell1.innerHTML = "";
	    cell2.innerHTML = "";
	    cell3.innerHTML = "";
	    cell4.innerHTML = "Total Quantity: " + cart_get_number_of_items();
	    cell5.innerHTML = "Total price: " + cart_total_price() + ' $';
	}
}

function decrease_quantity(id)
{
	var key = 'product_' + id;
	var x=window.localStorage.getItem(key);
	x=JSON.parse(x);
	if(x[3]==0){
		localStorage.removeItem(key);
	} else{
		x[3]=x[3]*1-1;
		window.localStorage.setItem(key, JSON.stringify(x));
	}
	location.reload();
}

function increase_quantity(id)
{
	var key = 'product_' + id;
	var x=window.localStorage.getItem(key);
	x=JSON.parse(x);
	x[3]=x[3]*1+1;
	window.localStorage.setItem(key, JSON.stringify(x));
	location.reload();
}

function delete_product(id)
{
	var key = 'product_' + id;
	localStorage.removeItem(key);
	location.reload();
}<|endoftext|>