<commit_before>'use strict';
/**
 * @file
 * Currently the main entrypoint served on /work.
 * Provides the work view for the enduser.
 */
import React from 'react';

// import components
// import {WorkDisplay} from 'dbc-react-workview';
// import Loader from '../Loader.component.js';
// import reflux actions and stores
import workAction from '../../actions/Work.action.js';
import workStore from '../../stores/Work.store.js';
import Covers from '../Cover.component.js';

const Work = React.createClass({
  propTypes: {
    id: React.PropTypes.string,
    work: React.PropTypes.object
  },

  getInitialState() {
    return {
      id: this.props.id,
      work: workStore.getStore()
    };
  },

  getWork() {
    let result = {
      id: this.state.id
    };
    workAction(result);
  },

  updateWork(work) {
    this.setState({work});
  },

  componentDidMount: function () {
    this.getWork();
    workStore.listen(this.updateWork);
  },

  render() {
    const {id, work, info} = this.state; // eslint-disable-line
    let general,
      title,
      creators,
      description,
      series,
      subjects,
      languages,
      specific,
      specifics;

    if (work.info.hits === '0') {
      return (
Værket blev ikke fundet
);
    }

    if (work.result.length === 0) {
      return (
);
    }

    general = work.result.general;
    title = general.title;
    if (general.hasOwnProperty('creators')) {
      creators = general.creators.map((creator) => {
        let search_creator = '/search?phrase.creator=' + creator;
        return (
{creator}
);
      });
    }
    if (general.hasOwnProperty('description')) {
      description = general.description;
    }
    if (general.hasOwnProperty('series')) {
      let series_title = general.series.replace(/ ; .*/, '');
      series_title = series_title.replace(/Samhørende: /, '');
      series_title = series_title.replace(/.* del af: /, '');
      let series_link = '/search?phrase.titleSeries=' + series_title;
      series = {general.series};
    }
    if (general.hasOwnProperty('subjects')) {
      subjects = general.subjects.map((subject) => {
        let search_subject = '/search?phrase.subject=' + subject;
        return (
{subject}
);
      });
    }
    if (general.hasOwnProperty('languages')) {
      languages = general.languages.map((language) => {
        return (
{language}
);
      });
    }
    specific = work.result.specific;
    let order_button = specific.map((tw) => {
      let order_ids = [];
      order_ids.push(tw.identifiers);
      let order_link = '/order?ids=' + order_ids + '&title=' + title + '&type=' + tw.type;
      return (Bestil {tw.type});
    });
    specifics = specific.map((tw) => {
      let identifiers = [];
      identifiers.push(tw.identifiers);
      let dates = (

);
      if (tw.dates[0] !== null) {
        dates = tw.dates.map((date) => {
          return (
{date}
);
        });
      }
      return (

{tw.type}

      {dates}

);
    });
    return (

        <Covers pids={work.result.specific[0].identifiers} />

        {order_button}

{title}

{creators}

{description}

{series}

{subjects}

{languages}

        {specifics}

    );
  }
});

export default Work;
<commit_msg>url encoding of search links<commit_after>'use strict';
/**
 * @file
 * Currently the main entrypoint served on /work.
 * Provides the work view for the enduser.
 */
import React from 'react';

// import components
// import {WorkDisplay} from 'dbc-react-workview';
// import Loader from '../Loader.component.js';
// import reflux actions and stores
import workAction from '../../actions/Work.action.js';
import workStore from '../../stores/Work.store.js';
import Covers from '../Cover.component.js';

const Work = React.createClass({
  propTypes: {
    id: React.PropTypes.string,
    work: React.PropTypes.object
  },

  getInitialState() {
    return {
      id: this.props.id,
      work: workStore.getStore()
    };
  },

  getWork() {
    let result = {
      id: this.state.id
    };
    workAction(result);
  },

  updateWork(work) {
    this.setState({work});
  },

  componentDidMount: function () {
    this.getWork();
    workStore.listen(this.updateWork);
  },

  render() {
    const {id, work, info} = this.state; // eslint-disable-line
    let general,
      title,
      creators,
      description,
      series,
      subjects,
      languages,
      specific,
      specifics;

    if (work.info.hits === '0') {
      return (
Værket blev ikke fundet
);
    }

    if (work.result.length === 0) {
      return (
);
    }

    general = work.result.general;
    title = general.title;
    if (general.hasOwnProperty('creators')) {
      creators = general.creators.map((creator) => {
        let search_creator = '/search?phrase.creator=' + encodeURIComponent(creator);
        return (
{creator}
);
      });
    }
    if (general.hasOwnProperty('description')) {
      description = general.description;
    }
    if (general.hasOwnProperty('series')) {
      let series_title = general.series.replace(/ ; .*/, '');
      series_title = series_title.replace(/Samhørende: /, '');
      series_title = series_title.replace(/.* del af: /, '');
      let series_link = '/search?phrase.titleSeries=' + encodeURIComponent(series_title);
      series = {general.series};
    }
    if (general.hasOwnProperty('subjects')) {
      subjects = general.subjects.map((subject) => {
        let search_subject = '/search?phrase.subject=' + encodeURIComponent(subject);
        return (
{subject}
);
      });
    }
    if (general.hasOwnProperty('languages')) {
      languages = general.languages.map((language) => {
        return (
{language}
);
      });
    }
    specific = work.result.specific;
    let order_button = specific.map((tw) => {
      let order_ids = [];
      order_ids.push(tw.identifiers);
      let order_link = '/order?ids=' + order_ids + '&title=' + encodeURIComponent(title) + '&type=' + tw.type;
      return (Bestil {tw.type});
    });
    specifics = specific.map((tw) => {
      let identifiers = [];
      identifiers.push(tw.identifiers);
      let dates = (

);
      if (tw.dates[0] !== null) {
        dates = tw.dates.map((date) => {
          return (
{date}
);
        });
      }
      return (

{tw.type}

      {dates}

);
    });
    return (

        <Covers pids={work.result.specific[0].identifiers} />

        {order_button}

{title}

{creators}

{description}

{series}

{subjects}

{languages}

        {specifics}

    );
  }
});

export default Work;
<|endoftext|>


<commit_before>'use strict';

/* Controllers */
app.controller('mainCtrl', ['$scope', '$rootScope', '$http', '$timeout', '$q',
  function mainCtrl($scope, $rootScope, $http, $timeout, $q) {

  $scope.searchMode = 'orderDate';

  function addSuccessMessage(HTTPstatus, message) {
    if (!$scope.successList) {
      $scope.successList = [];
    };
    var successObject = { 'status': HTTPstatus, 'message': message };
    $scope.successList.push(successObject);
    $timeout(function() {
      $scope.successList.splice(successObject, 1);
    }, 5000);
  }

  function addErrorMessage(HTTPstatus, message) {
    if (!$scope.errorList) {
      $scope.errorList = [];
    };
    var errorObject = { 'status': HTTPstatus, 'message': message };
    $scope.errorList.push(errorObject);
    $timeout(function() {
      $scope.errorList.splice(errorObject, 1);
    }, 20000);
  }

  function quickSort(l, r, scope) {
    if (l<r) {
      var pivot = getPivot(l, r, scope);
      quickSort(l, pivot-1, scope);
      quickSort(pivot+1, r, scope);
    };
  };

  function getPivot(l, r, scope) {
    var i = l;
    var j = r-1;
    var pivot = $scope.data.messages[r][scope];
    do {
      while ( ($scope.data.messages[i][scope] <= pivot) && (i < r) ) {
        i++;
      };
      while ( ($scope.data.messages[j][scope] >= pivot) && (j > l) ) {
        j--;
      };
      if (i<j) {
        var temp = $scope.data.messages[i];
        $scope.data.messages[i] = $scope.data.messages[j];
        $scope.data.messages[j] = temp;
      };
    } while(i<j);
    if ($scope.data.messages[i][scope] > pivot) {
      var temp = $scope.data.messages[i];
      $scope.data.messages[i] = $scope.data.messages[r];
      $scope.data.messages[r] = temp;
    };
    return i;
  };

  function strcmp(a, b) {
      a = a.toString(), b = b.toString();
      for (var i=0,n=Math.max(a.length, b.length); i<n && a.charAt(i) === b.charAt(i); ++i);
      if (i === n) return 0;
      return a.charAt(i) > b.charAt(i) ? -1 : 1;
  }

  function FUUUUUUUUUUUUU(ferk) {
    // rage level over 9000!!!!!11!!111!1
    // this method propagates the sorted position because the sorting function somehow couldnt
    // also its put same day messages in the same spot
    var pos = 0;
    var prev = 0;
    angular.forEach($scope.data.messages, function(message, key) {
      if (key==0) {
        message[ferk+'Position'] = key;
        prev = message[ferk];
      } else {
        if ( strcmp(message[ferk], prev) == 0 ) {
          message[ferk+'Position'] = pos;
        } else {
          pos++;
          message[ferk+'Position'] = pos;
        };
        prev = message[ferk];
      };
    });
  };

  function sortAll() {
      var i = 0;
      angular.forEach($scope.data.messages, function(message, key) {
          if (message.data === undefined) {  } else {
            message.orderDate = 99990000;
            message.noticeDate = 99990000;
            message.trackingDate = 99990000;
            message.receivedDate = 99990000;
            message.orderDatePosition = i;
            message.noticeDatePosition = i;
            message.trackingDatePosition = i;
            message.receivedDatePosition = i;
            message.postDate = i;
            i++;
            if (message.data.orderDate.year != 'n/a') {
              message.orderDate = parseInt(message.data.orderDate.year)*10000 + parseInt(message.data.orderDate.month)*100 + parseInt(message.data.orderDate.day);
            };
            if (message.data.notice.year != 'n/a') {
              message.noticeDate = parseInt(message.data.notice.year)*10000 + parseInt(message.data.notice.month)*100 + parseInt(message.data.notice.day);
            };
            if (message.data.tracking.year != 'n/a') {
              message.trackingDate = parseInt(message.data.tracking.year)*10000 + parseInt(message.data.tracking.month)*100 + parseInt(message.data.tracking.day);
            };
            if (message.data.received.year != 'n/a') {
              message.receivedDate = parseInt(message.data.received.year)*10000 + parseInt(message.data.received.month)*100 + parseInt(message.data.received.day);
            };
            if ( strcmp(message.data.color, "Stainless Steel") == 0 ) {
              message.data.color = 'Steel';
            };
          };
      });
      quickSort(0, i-1, 'orderDate');
      FUUUUUUUUUUUUU('orderDate');
      quickSort(0, i-1, 'noticeDate');
      FUUUUUUUUUUUUU('noticeDate');
      quickSort(0, i-1, 'trackingDate');
      FUUUUUUUUUUUUU('trackingDate');
      quickSort(0, i-1, 'receivedDate');
      FUUUUUUUUUUUUU('receivedDate');

  };

	$scope.update = function() {

    $scope.timetag = new Date().getTime();
    //$http.get('http://boredrich.de/makiscrape/fetchMakistats.pl').
    $http.get('http://boredrich.de/makiscrape/makiscrape.json?'+$scope.timetag).
      success(function(data, status, headers, config) {
        addSuccessMessage(status, "JSON successfully loaded.");
        $scope.status = status;
        data.messages.splice(0, 1);
        $scope.data = data;
        sortAll();
      }).
      error(function(data, status, headers, config) {
        addErrorMessage(status, "An error occured.");
        $scope.status = status;
        $scope.data = data;
        console.log(data);
      });
  };

  $scope.update();

  $scope.getCount = function(scope) {
    var count = 0;
    if ($scope.data) {
      angular.forEach($scope.data.messages, function(message, key) {
          if (message.data === undefined) {  } else {
            message.orderDate = 99990000;
            message.noticeDate = 99990000;
            message.trackingDate = 99990000;
            message.receivedDate = 99990000;
            if (message.data.orderDate.year != 'n/a') {
              message.orderDate = parseInt(message.data.orderDate.year)*10000 + parseInt(message.data.orderDate.month)*100 + parseInt(message.data.orderDate.day);
            };
            if (message.data.notice.year != 'n/a') {
              message.noticeDate = parseInt(message.data.notice.year)*10000 + parseInt(message.data.notice.month)*100 + parseInt(message.data.notice.day);
            };
            if (message.data.tracking.year != 'n/a') {
              message.trackingDate = parseInt(message.data.tracking.year)*10000 + parseInt(message.data.tracking.month)*100 + parseInt(message.data.tracking.day);
            };
            if (message.data.received.year != 'n/a') {
              message.receivedDate = parseInt(message.data.received.year)*10000 + parseInt(message.data.received.month)*100 + parseInt(message.data.received.day);
            };
            if (message.data[scope].year != 'n/a') {
              //messages.splice(key, 1);
              //console.log(message.data.notice);
              count++;
            };
          };
      });
    };
    return count;
  };

  $scope.log = function(text) {
    console.log(text);
  };

  function ifDateAvail(message, key) {
    if (message.data[key].year != 'n/a') {
      return message.data[key].year+'-'+message.data[key].month+'-'+message.data[key].day;
    } else {
      return '';
    }
  };

  $scope.getCsvHeader = function() {
    return ['Name', 'Type', 'Ramen', 'Color', 'Country', 'Shipping', 'Order', 'Notice', 'Tracking', 'Received', 'LastEdited', 'Link', 'OriginalPost'];
  };
  $scope.getCsvArray = function() {
    var array = [];
    if ($scope.data) {
      angular.forEach($scope.data.messages, function(message, key) {
        var orderDate = ifDateAvail(message, 'orderDate');
        var notice = ifDateAvail(message, 'notice');
        var tracking = ifDateAvail(message, 'tracking');
        var received = ifDateAvail(message, 'received');
        array.push({  a: message.poster,
                      b: message.data.type,
                      c: message.data.ramen,
                      d: message.data.color,
                      e: message.data.country,
                      f: message.data.shipping,
                      g: orderDate,
                      h: notice,
                      i: tracking,
                      j: received,
                      k: message.data.lastEdited.year+'-'+message.data.lastEdited.month+'-'+message.data.lastEdited.day,
                      l: message.link,
                      m: message.content});
      });
    };
    return array;
  };

  $scope.searchFn = function(message) {
    if ($scope.searchMode == 'orderDate') {
      return message.orderDatePosition;
    } else if ($scope.searchMode == 'noticeDate') {
      return (message.noticeDatePosition*1000 + message.orderDatePosition);
    } else if ($scope.searchMode == 'trackingDate') {
      return (message.trackingDatePosition*1000000 + message.noticeDatePosition*1000 + message.orderDatePosition);
    } else if ($scope.searchMode == 'receivedDate') {
      return message.receivedDatePosition*1000000000 + message.trackingDatePosition*1000000 + message.noticeDatePosition*1000 + message.orderDatePosition;
    } else if ($scope.searchMode == 'poster') {
      return message.poster;
    };
    return message.postDate;
  };

}]);<commit_msg>count bugfix<commit_after>'use strict';

/* Controllers */
app.controller('mainCtrl', ['$scope', '$rootScope', '$http', '$timeout', '$q',
  function mainCtrl($scope, $rootScope, $http, $timeout, $q) {

  $scope.searchMode = 'orderDate';

  function addSuccessMessage(HTTPstatus, message) {
    if (!$scope.successList) {
      $scope.successList = [];
    };
    var successObject = { 'status': HTTPstatus, 'message': message };
    $scope.successList.push(successObject);
    $timeout(function() {
      $scope.successList.splice(successObject, 1);
    }, 5000);
  }

  function addErrorMessage(HTTPstatus, message) {
    if (!$scope.errorList) {
      $scope.errorList = [];
    };
    var errorObject = { 'status': HTTPstatus, 'message': message };
    $scope.errorList.push(errorObject);
    $timeout(function() {
      $scope.errorList.splice(errorObject, 1);
    }, 20000);
  }

  function quickSort(l, r, scope) {
    if (l<r) {
      var pivot = getPivot(l, r, scope);
      quickSort(l, pivot-1, scope);
      quickSort(pivot+1, r, scope);
    };
  };

  function getPivot(l, r, scope) {
    var i = l;
    var j = r-1;
    var pivot = $scope.data.messages[r][scope];
    do {
      while ( ($scope.data.messages[i][scope] <= pivot) && (i < r) ) {
        i++;
      };
      while ( ($scope.data.messages[j][scope] >= pivot) && (j > l) ) {
        j--;
      };
      if (i<j) {
        var temp = $scope.data.messages[i];
        $scope.data.messages[i] = $scope.data.messages[j];
        $scope.data.messages[j] = temp;
      };
    } while(i<j);
    if ($scope.data.messages[i][scope] > pivot) {
      var temp = $scope.data.messages[i];
      $scope.data.messages[i] = $scope.data.messages[r];
      $scope.data.messages[r] = temp;
    };
    return i;
  };

  function strcmp(a, b) {
      a = a.toString(), b = b.toString();
      for (var i=0,n=Math.max(a.length, b.length); i<n && a.charAt(i) === b.charAt(i); ++i);
      if (i === n) return 0;
      return a.charAt(i) > b.charAt(i) ? -1 : 1;
  }

  function FUUUUUUUUUUUUU(ferk) {
    // rage level over 9000!!!!!11!!111!1
    // this method propagates the sorted position because the sorting function somehow couldnt
    // also its put same day messages in the same spot
    var pos = 0;
    var prev = 0;
    angular.forEach($scope.data.messages, function(message, key) {
      if (key==0) {
        message[ferk+'Position'] = key;
        prev = message[ferk];
      } else {
        if ( strcmp(message[ferk], prev) == 0 ) {
          message[ferk+'Position'] = pos;
        } else {
          pos++;
          message[ferk+'Position'] = pos;
        };
        prev = message[ferk];
      };
    });
  };

  function sortAll() {
      var i = 0;
      angular.forEach($scope.data.messages, function(message, key) {
          if (message.data === undefined) {  } else {
            message.orderDate = 99990000;
            message.noticeDate = 99990000;
            message.trackingDate = 99990000;
            message.receivedDate = 99990000;
            message.orderDatePosition = i;
            message.noticeDatePosition = i;
            message.trackingDatePosition = i;
            message.receivedDatePosition = i;
            message.postDate = i;
            i++;
            if (message.data.orderDate.year != 'n/a') {
              message.orderDate = parseInt(message.data.orderDate.year)*10000 + parseInt(message.data.orderDate.month)*100 + parseInt(message.data.orderDate.day);
            };
            if (message.data.notice.year != 'n/a') {
              message.noticeDate = parseInt(message.data.notice.year)*10000 + parseInt(message.data.notice.month)*100 + parseInt(message.data.notice.day);
            };
            if (message.data.tracking.year != 'n/a') {
              message.trackingDate = parseInt(message.data.tracking.year)*10000 + parseInt(message.data.tracking.month)*100 + parseInt(message.data.tracking.day);
            };
            if (message.data.received.year != 'n/a') {
              message.receivedDate = parseInt(message.data.received.year)*10000 + parseInt(message.data.received.month)*100 + parseInt(message.data.received.day);
            };
            if ( strcmp(message.data.color, "Stainless Steel") == 0 ) {
              message.data.color = 'Steel';
            };
          };
      });
      quickSort(0, i-1, 'orderDate');
      FUUUUUUUUUUUUU('orderDate');
      quickSort(0, i-1, 'noticeDate');
      FUUUUUUUUUUUUU('noticeDate');
      quickSort(0, i-1, 'trackingDate');
      FUUUUUUUUUUUUU('trackingDate');
      quickSort(0, i-1, 'receivedDate');
      FUUUUUUUUUUUUU('receivedDate');

  };

	$scope.update = function() {

    $scope.timetag = new Date().getTime();
    //$http.get('http://boredrich.de/makiscrape/fetchMakistats.pl').
    $http.get('http://boredrich.de/makiscrape/makiscrape.json?'+$scope.timetag).
      success(function(data, status, headers, config) {
        addSuccessMessage(status, "JSON successfully loaded.");
        $scope.status = status;
        data.messages.splice(0, 1);
        $scope.data = data;
        sortAll();
      }).
      error(function(data, status, headers, config) {
        addErrorMessage(status, "An error occured.");
        $scope.status = status;
        $scope.data = data;
        console.log(data);
      });
  };

  $scope.update();

  $scope.getCount = function(scope) {
    var count = 0;
    if ($scope.data) {
      angular.forEach($scope.data.messages, function(message, key) {
          if (message.data === undefined) {  } else {
            message.orderDate = 99990000;
            message.noticeDate = 99990000;
            message.trackingDate = 99990000;
            message.receivedDate = 99990000;
            if (message.data.orderDate.year != 'n/a') {
              message.orderDate = parseInt(message.data.orderDate.year)*10000 + parseInt(message.data.orderDate.month)*100 + parseInt(message.data.orderDate.day);
            };
            if (message.data.notice.year != 'n/a') {
              message.noticeDate = parseInt(message.data.notice.year)*10000 + parseInt(message.data.notice.month)*100 + parseInt(message.data.notice.day);
            };
            if (message.data.tracking.year != 'n/a') {
              message.trackingDate = parseInt(message.data.tracking.year)*10000 + parseInt(message.data.tracking.month)*100 + parseInt(message.data.tracking.day);
            };
            if (message.data.received.year != 'n/a') {
              message.receivedDate = parseInt(message.data.received.year)*10000 + parseInt(message.data.received.month)*100 + parseInt(message.data.received.day);
            };
            if (message.data[scope].year != 'n/a') {
              //messages.splice(key, 1);
              //console.log(message.data.notice);
              count++;
            } else if ( (scope == 'notice') && ( (message.data.tracking.year != 'n/a') || (message.data.received.year != 'n/a') ) ) {
              count++;
            } else if ( (scope == 'tracking') && (message.data.received.year != 'n/a') ) {
              count++;
            };
          };
      });
    };
    return count;
  };

  $scope.log = function(text) {
    console.log(text);
  };

  function ifDateAvail(message, key) {
    if (message.data[key].year != 'n/a') {
      return message.data[key].year+'-'+message.data[key].month+'-'+message.data[key].day;
    } else {
      return '';
    }
  };

  $scope.getCsvHeader = function() {
    return ['Name', 'Type', 'Ramen', 'Color', 'Country', 'Shipping', 'Order', 'Notice', 'Tracking', 'Received', 'LastEdited', 'Link', 'OriginalPost'];
  };
  $scope.getCsvArray = function() {
    var array = [];
    if ($scope.data) {
      angular.forEach($scope.data.messages, function(message, key) {
        var orderDate = ifDateAvail(message, 'orderDate');
        var notice = ifDateAvail(message, 'notice');
        var tracking = ifDateAvail(message, 'tracking');
        var received = ifDateAvail(message, 'received');
        array.push({  a: message.poster,
                      b: message.data.type,
                      c: message.data.ramen,
                      d: message.data.color,
                      e: message.data.country,
                      f: message.data.shipping,
                      g: orderDate,
                      h: notice,
                      i: tracking,
                      j: received,
                      k: message.data.lastEdited.year+'-'+message.data.lastEdited.month+'-'+message.data.lastEdited.day,
                      l: message.link,
                      m: message.content});
      });
    };
    return array;
  };

  $scope.searchFn = function(message) {
    if ($scope.searchMode == 'orderDate') {
      return message.orderDatePosition;
    } else if ($scope.searchMode == 'noticeDate') {
      return (message.noticeDatePosition*1000 + message.orderDatePosition);
    } else if ($scope.searchMode == 'trackingDate') {
      return (message.trackingDatePosition*1000000 + message.noticeDatePosition*1000 + message.orderDatePosition);
    } else if ($scope.searchMode == 'receivedDate') {
      return message.receivedDatePosition*1000000000 + message.trackingDatePosition*1000000 + message.noticeDatePosition*1000 + message.orderDatePosition;
    } else if ($scope.searchMode == 'poster') {
      return message.poster;
    };
    return message.postDate;
  };

}]);<|endoftext|>


<commit_before>(function(global) {

var LITERAL = '[a-zA-Z0-9-]';
var SEPARATORS = { modSeparator: '_', elemSeparator: '__' };
var REGEX = buildRegex(SEPARATORS, LITERAL);

function buildRegex(separators, literal) {
    var word = literal + '+';
    var block = '(' + word + ')';
    var mod = '(?:' + separators.modSeparator + '(' + word + '))?';
    var elem = '(?:' + separators.elemSeparator + '(' + word + '))?';

    return new RegExp(['^', block, mod, mod, elem, mod, mod, '$'].join(''));
}

function parse(str, regex) {
    var executed = regex.exec(str);
    var modKey = executed[2] || executed[5];
    var modValue = executed[3] || executed[6];

    if (modKey && modValue === undefined) {
        modValue = true;
    }

    return {
        block: executed[1],
        elem: executed[4],
        modKey: modKey,
        modValue: modValue
    };
}

function stringify(obj, separators) {
    var buf = [obj.block];

    if (obj.elem) {
        buf.push(separators.elemSeparator + obj.elem);
    }

    if (obj.modKey) {
        buf.push(separators.modSeparator + obj.modKey);

        if (obj.modValue) {
            buf.push(separators.modSeparator + obj.modValue);
        }
    }

    return buf.join('');
}

var BEMNaming = function (options) {
    options || (options = {});

    this._separators = {};
    this._separators.modSeparator = options.modSeparator || SEPARATORS.modSeparator;
    this._separators.elemSeparator = options.elemSeparator || SEPARATORS.elemSeparator;
    this._literal = options.literal || LITERAL;
    this._regex = buildRegex(this._separators, this._literal);
};

BEMNaming.prototype.parse = function (str) {
    return parse(str, this._regex);
};

BEMNaming.prototype.stringify = function (obj) {
    return stringify(obj, this._separators);
};

var naming = {
    BEMNaming: BEMNaming,

    parse: function (str) {
        return parse(str, REGEX);
    },

    stringify: function (obj) {
        return stringify(obj, SEPARATORS);
    }
};

var defineAsGlobal = true;
if(typeof exports === 'object') {
    module.exports = naming;
    defineAsGlobal = false;
}

if(typeof modules === 'object') {
    modules.define('bem-naming', function(provide) {
        provide(naming);
    });
    defineAsGlobal = false;
}

if(typeof define === 'function') {
    define(function(require, exports, module) {
        module.exports = naming;
    });
    defineAsGlobal = false;
}

defineAsGlobal && (global.naming = naming);

})(this);
<commit_msg>Refactoring<commit_after>(function(global) {

var LITERAL = '[a-zA-Z0-9-]',
    MOD_SEPARATOR = '_',
    ELEM_SEPARATOR = '__';

var BEMNaming = function (options) {
    options || (options = {});

    this._separators = {};
    this._separators.modSeparator = options.modSeparator || MOD_SEPARATOR;
    this._separators.elemSeparator = options.elemSeparator || ELEM_SEPARATOR;
    this._literal = options.literal || LITERAL;

    this._buildRegex();
};

BEMNaming.prototype.parse = function (str) {
    var executed = this._regex.exec(str),
        modKey = executed[2] || executed[5],
        modValue = executed[3] || executed[6];

    if (modKey && modValue === undefined) {
        modValue = true;
    }

    return {
        block: executed[1],
        elem: executed[4],
        modKey: modKey,
        modValue: modValue
    };
};

BEMNaming.prototype.stringify = function (obj) {
    var buf = [obj.block];

    if (obj.elem) {
        buf.push(this._separators.elemSeparator + obj.elem);
    }

    if (obj.modKey) {
        buf.push(this._separators.modSeparator + obj.modKey);

        if (obj.modValue) {
            buf.push(this._separators.modSeparator + obj.modValue);
        }
    }

    return buf.join('');
};

BEMNaming.prototype._buildRegex = function () {
    var word = this._literal + '+',
        block = '(' + word + ')',
        mod = '(?:' + this._separators.modSeparator + '(' + word + '))?',
        elem = '(?:' + this._separators.elemSeparator + '(' + word + '))?';

    this._regex = new RegExp(['^', block, mod, mod, elem, mod, mod, '$'].join(''));
}

var defineAsGlobal = true,
    oldSchoolNaming = new BEMNaming({
        modSeparator: MOD_SEPARATOR,
        elemSeparator: ELEM_SEPARATOR,
        literal: LITERAL
    }),
    naming = {
        BEMNaming: BEMNaming,
        parse: oldSchoolNaming.parse.bind(oldSchoolNaming),
        stringify: oldSchoolNaming.stringify.bind(oldSchoolNaming)
    };

if(typeof exports === 'object') {
    module.exports = naming;
    defineAsGlobal = false;
}

if(typeof modules === 'object') {
    modules.define('bem-naming', function(provide) {
        provide(naming);
    });
    defineAsGlobal = false;
}

if(typeof define === 'function') {
    define(function(require, exports, module) {
        module.exports = naming;
    });
    defineAsGlobal = false;
}

defineAsGlobal && (global.naming = naming);

})(this);
<|endoftext|>


<commit_before>/**
 * Player Entity
 */
game.PlayerEntity = me.Entity.extend({

    /* -----

    constructor

    ------ */

    init: function(x, y, settings) {
        settings['height'] = 75;
        // call the constructor
        this._super(me.Entity, 'init', [x, y, settings]);

        // set the default horizontal & vertical speed (accel vector)
        this.body.setVelocity(3, 3);

        // set the display to follow our position on both axis
        me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);

        // ensure the player is updated even when outside of the viewport
        this.alwaysUpdate = true;

        // define a basic walking animation (using all frames)
        this.renderable.addAnimation("walk",  [0]);
    },

    /* -----

    update the player pos

    ------ */
    update: function(dt) {
        if (me.input.isKeyPressed('left') && me.input.isKeyPressed('up')) {
            this.renderable.angle = Math.PI * 1.75;
            this.body.vel.y -= this.body.accel.y * me.timer.tick;
            this.body.vel.x -= this.body.accel.x * me.timer.tick;
        }
        else if (me.input.isKeyPressed('left') && me.input.isKeyPressed('down')) {
            this.renderable.angle = Math.PI * -0.75;
            this.body.vel.y += this.body.accel.y * me.timer.tick;
            this.body.vel.x -= this.body.accel.x * me.timer.tick;
        }
        else if (me.input.isKeyPressed('right') && me.input.isKeyPressed('up')) {
            this.renderable.angle = Math.PI * 0.25;
            this.body.vel.y -= this.body.accel.y * me.timer.tick;
            this.body.vel.x += this.body.accel.x * me.timer.tick;
        }
        else if (me.input.isKeyPressed('right') && me.input.isKeyPressed('down')) {
            this.renderable.angle = Math.PI * -1.25;
            this.body.vel.y += this.body.accel.y * me.timer.tick;
            this.body.vel.x += this.body.accel.x * me.timer.tick;
        }
        else if (me.input.isKeyPressed('left')) {
            // flip the sprite on horizontal axis
            // this.renderable.flipX(true);
            // update the entity velocity
            this.renderable.angle = Math.PI * -0.5;
            this.body.vel.x -= this.body.accel.x * me.timer.tick;
            this.body.vel.y = 0;
            // change to the walking animation
            // if (!this.renderable.isCurrentAnimation("walk")) {
            //     this.renderable.setCurrentAnimation("walk");
            // }
        } else if (me.input.isKeyPressed('right')) {
            // console.log(this.renderable)
            this.renderable.angle = Math.PI * 0.5;
            this.body.vel.y = 0;
            // unflip the sprite
            // this.renderable.flipX(true);
            // this.renderable.flipY(true);
            // update the entity velocity
            this.body.vel.x += this.body.accel.x * me.timer.tick;
        }
        else if (me.input.isKeyPressed('up')) {
            this.body.vel.y -= this.body.accel.y * me.timer.tick;
            this.body.vel.x = 0;
            this.renderable.angle = 0;
        }
        else if (me.input.isKeyPressed('down')) {
            this.body.vel.y += this.body.accel.y * me.timer.tick;
            this.body.vel.x = 0;
            this.renderable.angle = Math.PI;
        }
        else {
            // this.body.vel.x = 0;
            this.body.vel.y = 0;
            this.body.vel.x = 0;
            this.renderable.setCurrentAnimation("walk");
        }

        if (me.input.isKeyPressed("shoot")) {
            me.game.world.addChild(me.pool.pull("laser", this.pos.x + (this.width / 2 - game.Laser.width / 2), this.pos.y - game.Laser.height))
        }

        // if (me.input.isKeyPressed('jump')) {
        //     // make sure we are not already jumping or falling
        //     if (!this.body.jumping && !this.body.falling) {
        //         // set current vel to the maximum defined value
        //         // gravity will then do the rest
        //         this.body.vel.y = -this.body.maxVel.y * me.timer.tick;
        //         // set the jumping flag
        //         this.body.jumping = true;
        //     }

        // }

        // apply physics to the body (this moves the entity)
        this.body.update(dt);

        // handle collisions against other shapes
        me.collision.check(this);

        // return true if we moved or if the renderable was updated
        return (this._super(me.Entity, 'update', [dt]) || this.body.vel.x !== 0 || this.body.vel.y !== 0);
    },

    /**
     * colision handler
     * (called when colliding with other objects)
     */
    onCollision : function (response, other) {
        // Make all other objects solid
        return true;
    }
});

game.Laser = me.Renderable.extend({
    init: function (x, y) {
        this._super(me.Renderable, "init", [x, y, game.Laser.width, game.Laser.height]);
        this.z = 5;
        this.body = new me.Body(this, ([
            new me.Polygon(0, 0, [
                new me.Vector2d(0, 0),
                new me.Vector2d(this.width, 0),
                new me.Vector2d(this.width, this.height),
                new me.Vector2d(0, this.height)
            ])
        ]));
        this.body.updateBounds();
        this.body.setVelocity(0, 20);
    },

    draw: function (renderer) {
        var color = renderer.getColor();
        renderer.setColor('#5EFF7E');
        renderer.fillRect(this.pos.x, this.pos.y, this.width, this.height);
        renderer.setColor(color);
    },

    update: function (time) {
        this._super(me.Renderable, "update", [time]);
        this.body.vel.y -= this.body.accel.y * me.timer.tick;
        if (this.pos.y + this.height <= 0) {
            me.game.world.removeChild(this);
        }

        this.body.update();

        return true;
    },
    onCollision: function(response, other) {
        if(response.a.name === 'mainplayer') {
            console.log('response', response)
            console.log('other', other)
            return false;
        }
        return true;
    }
});

game.Laser.width = 5;
game.Laser.height = 28;<commit_msg>laser direction - WIP<commit_after>var playerData = {};

game.PlayerEntity = me.Entity.extend({
    init: function(x, y, settings) {
        settings['height'] = 75;
        // call the constructor
        this._super(me.Entity, 'init', [x, y, settings]);

        // set the default horizontal & vertical speed (accel vector)
        this.body.setVelocity(3, 3);

        // set the display to follow our position on both axis
        me.game.viewport.follow(this.pos, me.game.viewport.AXIS.BOTH);

        // ensure the player is updated even when outside of the viewport
        this.alwaysUpdate = true;

        // define a basic walking animation (using all frames)
        this.renderable.addAnimation("walk",  [0]);
    },

    /* -----

    update the player pos

    ------ */
    update: function(dt) {
        if (me.input.isKeyPressed('left') && me.input.isKeyPressed('up')) {
            this.renderable.angle = Math.PI * 1.75;
            this.body.vel.y -= this.body.accel.y * me.timer.tick;
            this.body.vel.x -= this.body.accel.x * me.timer.tick;
            playerData.orientation = 'northWest';
        }
        else if (me.input.isKeyPressed('left') && me.input.isKeyPressed('down')) {
            this.renderable.angle = Math.PI * -0.75;
            this.body.vel.y += this.body.accel.y * me.timer.tick;
            this.body.vel.x -= this.body.accel.x * me.timer.tick;
            playerData.orientation = 'southWest';
        }
        else if (me.input.isKeyPressed('right') && me.input.isKeyPressed('up')) {
            this.renderable.angle = Math.PI * 0.25;
            this.body.vel.y -= this.body.accel.y * me.timer.tick;
            this.body.vel.x += this.body.accel.x * me.timer.tick;
            playerData.orientation = 'northEast';
        }
        else if (me.input.isKeyPressed('right') && me.input.isKeyPressed('down')) {
            this.renderable.angle = Math.PI * -1.25;
            this.body.vel.y += this.body.accel.y * me.timer.tick;
            this.body.vel.x += this.body.accel.x * me.timer.tick;
            playerData.orientation = 'southEast';
        }
        else if (me.input.isKeyPressed('left')) {
            // flip the sprite on horizontal axis
            // this.renderable.flipX(true);
            // update the entity velocity
            this.renderable.angle = Math.PI * -0.5;
            this.body.vel.x -= this.body.accel.x * me.timer.tick;
            this.body.vel.y = 0;
            playerData.orientation = 'west';
            // change to the walking animation
            // if (!this.renderable.isCurrentAnimation("walk")) {
            //     this.renderable.setCurrentAnimation("walk");
            // }
        } else if (me.input.isKeyPressed('right')) {
            // console.log(this.renderable)
            this.renderable.angle = Math.PI * 0.5;
            this.body.vel.y = 0;
            // unflip the sprite
            // this.renderable.flipX(true);
            // this.renderable.flipY(true);
            // update the entity velocity
            this.body.vel.x += this.body.accel.x * me.timer.tick;
            playerData.orientation = 'east';
        }
        else if (me.input.isKeyPressed('up')) {
            this.body.vel.y -= this.body.accel.y * me.timer.tick;
            this.body.vel.x = 0;
            this.renderable.angle = 0;
            playerData.orientation = 'north';
        }
        else if (me.input.isKeyPressed('down')) {
            this.body.vel.y += this.body.accel.y * me.timer.tick;
            this.body.vel.x = 0;
            this.renderable.angle = Math.PI;
            playerData.orientation = 'south';
        }
        else {
            // this.body.vel.x = 0;
            this.body.vel.y = 0;
            this.body.vel.x = 0;
            this.renderable.setCurrentAnimation("walk");
        }

        if (me.input.isKeyPressed("shoot")) {
            me.game.world.addChild(me.pool.pull("laser", this.pos.x + (this.width / 2 - game.Laser.width / 2), this.pos.y - game.Laser.height))
        }

        // if (me.input.isKeyPressed('jump')) {
        //     // make sure we are not already jumping or falling
        //     if (!this.body.jumping && !this.body.falling) {
        //         // set current vel to the maximum defined value
        //         // gravity will then do the rest
        //         this.body.vel.y = -this.body.maxVel.y * me.timer.tick;
        //         // set the jumping flag
        //         this.body.jumping = true;
        //     }

        // }

        // apply physics to the body (this moves the entity)
        this.body.update(dt);

        // handle collisions against other shapes
        me.collision.check(this);

        // return true if we moved or if the renderable was updated
        return (this._super(me.Entity, 'update', [dt]) || this.body.vel.x !== 0 || this.body.vel.y !== 0);
    },

    /**
     * colision handler
     * (called when colliding with other objects)
     */
    onCollision : function (response, other) {
        // Make all other objects solid
        return true;
    }
});

game.Laser = me.Renderable.extend({
    init: function (x, y) {
        var lazerCords = this.calcLaserOrientation(x, y, playerData.orientation);
        this._super(me.Renderable, "init", [lazerCords.x, lazerCords.y, game.Laser.width, game.Laser.height]);
        this.z = 5;
        var body = this.calcLaserShape();
        this.body = body;

        // this.body = new me.Body(this, ([
        //     new me.Polygon(0, 0, [
        //         new me.Vector2d(0, 0),
        //         new me.Vector2d(this.width, 0),
        //         new me.Vector2d(this.width, this.height),
        //         new me.Vector2d(0, this.height)
        //     ])
        // ]));
        console.log('this.body', this.body.entity)
        console.log('this.body', this.body.entity.body.shapes[0].points)
        this.body.updateBounds();
        this.body.setVelocity(0, 20);
    },

    calcLaserOrientation: function(x, y, playerOrientation) {
      if(playerOrientation === 'south') {
        return {x: x, y: y + 110};
      }
      if(playerOrientation === 'north') {
        return {x: x, y: y - 10};
      }
      if(playerOrientation === 'west') {
        console.log('getting here')
        return {x: x - 60, y: y + 40};
      }
      else {
        return {x: x, y: y}
      }
    },
    calcLaserShape: function() {
      return new me.Body(this, ([
            new me.Polygon(0, 0, [
                new me.Vector2d(-this.height, 0),
                new me.Vector2d(this.height, 0),
                new me.Vector2d(-this.height, this.width),
                new me.Vector2d(this.height, this.width)
            ])
        ]));
    },
    calcLaserDirectionDelta: function(velx, vely, accelX, accelY, playerOrientation, tick) {
      if(playerOrientation === 'south') {
        this.body.setVelocity(0, 20);
        var updatedVelX = 0;
        var updatedVelY = vely + (accelY * tick);
        return {velx: updatedVelX, vely: updatedVelY};
      }
      if(playerOrientation === 'north') {
        this.body.setVelocity(0, 20);
        var updatedVelX = 0;
        var updatedVelY = vely - (accelY * tick);
        return {velx: updatedVelX, vely: updatedVelY};
      }
      if(playerOrientation === 'west') {
        this.body.setVelocity(20, 0);
        var updatedVelX = velx - (accelX * tick);
        var updatedVelY = 0;
        console.log('updatedVelY', updatedVelY)
        return {velx: updatedVelX, vely: updatedVelY};
      }
    },

    draw: function (renderer) {
        var color = renderer.getColor();
        renderer.setColor('#5EFF7E');
        renderer.fillRect(this.pos.x, this.pos.y, this.width, this.height);
        renderer.setColor(color);
    },

    update: function (time) {
        this._super(me.Renderable, "update", [time]);
        var deltas = this.calcLaserDirectionDelta(this.body.vel.x, this.body.vel.y, this.body.accel.x, this.body.accel.y, playerData.orientation, me.timer.tick);
        // this.body.vel.y += this.body.accel.y * me.timer.tick;
        this.body.vel.y = deltas.vely;
        this.body.vel.x = deltas.velx;
        // console.log('this.body.vel.y', this.body.vel.y);
        // this.body.vel.x -= this.body.accel.y * me.timer.tick;

        if (this.pos.y + this.height <= 0) {
            me.game.world.removeChild(this);
        }

        this.body.update();

        return true;
    },
    onCollision: function(response, other) {
        if(response.a.name === 'mainplayer') {
            // console.log('response', response)
            // console.log('other', other)
            return false;
        }
        return true;
    }
});

game.Laser.width = 5;
game.Laser.height = 28;<|endoftext|>


<commit_before>odoo.define('web_tour.Tip', function(require) {
"use strict";

var core = require('web.core');
var Widget = require('web.Widget');

var Tip = Widget.extend({
    template: "Tip",
    events: {
        mouseenter: "_to_info_mode",
        mouseleave: "_to_bubble_mode",
    },
    /**
     * @param {info} [Object] description of the tip, containing the following keys:
     *  - content [String] the html content of the tip
     *  - event_handlers [Object] description of optional event handlers to bind to the tip:
     *    - event [String] the event name
     *    - selector [String] the jQuery selector on which the event should be bound
     *    - handler [function] the handler
     *  - position [String] tip's position ('top', 'right', 'left' or 'bottom'), default 'right'
     *  - width [int] the width in px of the tip when opened, default 270
     *  - space [int] space in px between anchor and tip, default 10
     *  - overlay [Object] x and y values for the number of pixels the mouseout detection area
     *    overlaps the opened tip, default {x: 50, y: 50}
     */
    init: function(parent, info) {
        this._super(parent);
        this.info = _.defaults(info, {
            position: "right",
            width: 270,
            space: 10,
            overlay: {
                x: 50,
                y: 50,
            },
        });
        this.position = {
            top: "50%",
            left: "50%",
        };
    },
    /**
     * @param {$anchor} [JQuery] the node on which the tip should be placed
     */
    attach_to: function ($anchor) {
        this.$anchor = $anchor;
        this.$ideal_location = this._get_ideal_location();

        var position = this.$ideal_location.css("position");
        if (position === "static") {
            this.$ideal_location.addClass("o_tooltip_parent");
        }

        return this.appendTo(this.$ideal_location);
    },
    start: function() {
        this.$tooltip_overlay = this.$(".o_tooltip_overlay");
        this.$tooltip_content = this.$(".o_tooltip_content");
        this.init_width = this.$el.innerWidth();
        this.init_height = this.$el.innerHeight();
        this.double_border_width = this.$el.outerWidth() - this.init_width;
        this.content_width = this.$tooltip_content.outerWidth(true);
        this.content_height = this.$tooltip_content.outerHeight(true);
        this.$window = $(window);

        this.$tooltip_content.css({
            width: "100%",
            height: "100%",
        });

        _.each(this.info.event_handlers, (function(data) {
            this.$tooltip_content.on(data.event, data.selector, data.handler);
        }).bind(this));
        this._bind_anchor_events();

        this._reposition();
        this.$el.css("opacity", 1);
        core.bus.on("resize", this, _.debounce(function () {
            if (this.tip_opened) {
                this._to_bubble_mode(true);
            }
            this._reposition();
        }, 500));

        this.$el.on("transitionend oTransitionEnd webkitTransitionEnd", (function () {
            if (!this.tip_opened && this.$el.parent()[0] === document.body) {
                this.$el.detach();
                this.$el.css(this.position);
                this.$el.appendTo(this.$ideal_location);
            }
        }).bind(this));

        return this._super.apply(this, arguments);
    },
    destroy: function () {
        this._unbind_anchor_events();
        clearTimeout(this.timerIn);
        clearTimeout(this.timerOut);

        // Do not remove the parent class if it contains other tooltips
        if (this.$ideal_location.children(".o_tooltip").not(this.$el[0]).length === 0) {
            this.$ideal_location.removeClass("o_tooltip_parent");
        }

        return this._super.apply(this, arguments);
    },
    update: function ($anchor) {
        if (!$anchor.is(this.$anchor)) {
            this._unbind_anchor_events();
            this.$anchor = $anchor;
            this.$ideal_location = this._get_ideal_location();
            if (this.$el.parent()[0] !== document.body) {
                this.$el.appendTo(this.$ideal_location);
            }
            this._bind_anchor_events();
        }
        this._reposition();
    },
    _get_ideal_location: function () {
        var $location = this.$anchor;
        var o;
        var p;
        do {
            $location = $location.parent();
            o = $location.css("overflow");
            p = $location.css("position");
        } while ((o === "visible" || o === "hidden") && p !== "fixed" && $location[0] !== document.body);

        return $location;
    },
    _reposition: function () {
        if (this.tip_opened) return;
        this.$el.removeClass("o_animated");

        this.$el.position({
            my: this._get_spaced_inverted_position(this.info.position),
            at: this.info.position,
            of: this.$anchor,
            collision: "none",
        });

        var offset = this.$el.offset();
        this.$tooltip_overlay.css({
            top: -Math.min((this.info.position === "bottom" ? this.info.space : this.info.overlay.y), offset.top),
            right: -Math.min((this.info.position === "left" ? this.info.space : this.info.overlay.x), this.$window.width() - (offset.left + this.init_width + this.double_border_width)),
            bottom: -Math.min((this.info.position === "top" ? this.info.space : this.info.overlay.y), this.$window.height() - (offset.top + this.init_height + this.double_border_width)),
            left: -Math.min((this.info.position === "right" ? this.info.space : this.info.overlay.x), offset.left),
        });

        this.position = this.$el.position();

        this.$el.addClass("o_animated");
    },
    _bind_anchor_events: function () {
        this.consume_event = Tip.getConsumeEventType(this.$anchor);
        this.$anchor.on(this.consume_event + ".anchor", (function (e) {
            if (e.type !== "mousedown" || e.which === 1) { // only left click
                this.trigger("tip_consumed");
                this._unbind_anchor_events();
            }
        }).bind(this));
        this.$anchor.on('mouseenter.anchor', this._to_info_mode.bind(this));
        this.$anchor.on('mouseleave.anchor', this._to_bubble_mode.bind(this));
    },
    _unbind_anchor_events: function () {
        this.$anchor.off(".anchor");
    },
    _get_spaced_inverted_position: function (position) {
        if (position === "right") return "left+" + this.info.space;
        if (position === "left") return "right-" + this.info.space;
        if (position === "bottom") return "top+" + this.info.space;
        return "bottom-" + this.info.space;
    },
    _to_info_mode: function (force) {
        if (this.timerOut !== undefined) {
            clearTimeout(this.timerOut);
            this.timerOut = undefined;
            return;
        }
        if (this.tip_opened) {
            return;
        }

        if (force === true) {
            this._build_info_mode();
        } else {
            this.timerIn = setTimeout(this._build_info_mode.bind(this), 100);
        }
    },
    _build_info_mode: function () {
        clearTimeout(this.timerIn);
        this.timerIn = undefined;

        this.tip_opened = true;

        var offset = this.$el.offset();

        if (this.$el.parent()[0] !== document.body) {
            this.$el.detach();
            this.$el.css(offset);
            this.$el.appendTo(document.body);
        }

        var mbLeft = 0;
        var mbTop = 0;
        var overflow = false;
        var posVertical = (this.info.position === "top" || this.info.position === "bottom");
        if (posVertical) {
            overflow = (offset.left + this.content_width + this.double_border_width + this.info.overlay.x > this.$window.width());
        } else {
            overflow = (offset.top + this.content_height + this.double_border_width + this.info.overlay.y > this.$window.height());
        }
        if (posVertical && overflow || this.info.position === "left") {
            mbLeft -= (this.content_width - this.init_width);
        }
        if (!posVertical && overflow || this.info.position === "top") {
            mbTop -= (this.content_height - this.init_height);
        }

        this.$el.toggleClass("inverse", overflow);
        this.$el.removeClass("o_animated").addClass("active");
        this.$el.css({
            width: this.content_width,
            height: this.content_height,
            "margin-left": mbLeft,
            "margin-top": mbTop,
        });
    },
    _to_bubble_mode: function (force) {
        if (this.timerIn !== undefined) {
            clearTimeout(this.timerIn);
            this.timerIn = undefined;
            return;
        }
        if (!this.tip_opened) {
            return;
        }

        if (force === true) {
            this._build_bubble_mode();
        } else {
            this.timerOut = setTimeout(this._build_bubble_mode.bind(this), 300);
        }
    },
    _build_bubble_mode: function () {
        clearTimeout(this.timerOut);
        this.timerOut = undefined;

        this.tip_opened = false;

        this.$el.removeClass("active").addClass("o_animated");
        this.$el.css({
            width: this.init_width,
            height: this.init_height,
            margin: 0,
        });
    },
});

Tip.getConsumeEventType = function ($element) {
    if ($element.is("textarea") || $element.filter("input").is(function () {
        return !!$(this).attr("type").match(/^(email|number|password|search|tel|text|url)$/);
    })) {
        return "input";
    }
    return "mousedown";
};

return Tip;

});
<commit_msg>[FIX] web_tour: ideal tip location for html and body element<commit_after>odoo.define('web_tour.Tip', function(require) {
"use strict";

var core = require('web.core');
var Widget = require('web.Widget');

var Tip = Widget.extend({
    template: "Tip",
    events: {
        mouseenter: "_to_info_mode",
        mouseleave: "_to_bubble_mode",
    },
    /**
     * @param {info} [Object] description of the tip, containing the following keys:
     *  - content [String] the html content of the tip
     *  - event_handlers [Object] description of optional event handlers to bind to the tip:
     *    - event [String] the event name
     *    - selector [String] the jQuery selector on which the event should be bound
     *    - handler [function] the handler
     *  - position [String] tip's position ('top', 'right', 'left' or 'bottom'), default 'right'
     *  - width [int] the width in px of the tip when opened, default 270
     *  - space [int] space in px between anchor and tip, default 10
     *  - overlay [Object] x and y values for the number of pixels the mouseout detection area
     *    overlaps the opened tip, default {x: 50, y: 50}
     */
    init: function(parent, info) {
        this._super(parent);
        this.info = _.defaults(info, {
            position: "right",
            width: 270,
            space: 10,
            overlay: {
                x: 50,
                y: 50,
            },
        });
        this.position = {
            top: "50%",
            left: "50%",
        };
    },
    /**
     * @param {$anchor} [JQuery] the node on which the tip should be placed
     */
    attach_to: function ($anchor) {
        this.$anchor = $anchor;
        this.$ideal_location = this._get_ideal_location();

        var position = this.$ideal_location.css("position");
        if (position === "static") {
            this.$ideal_location.addClass("o_tooltip_parent");
        }

        return this.appendTo(this.$ideal_location);
    },
    start: function() {
        this.$tooltip_overlay = this.$(".o_tooltip_overlay");
        this.$tooltip_content = this.$(".o_tooltip_content");
        this.init_width = this.$el.innerWidth();
        this.init_height = this.$el.innerHeight();
        this.double_border_width = this.$el.outerWidth() - this.init_width;
        this.content_width = this.$tooltip_content.outerWidth(true);
        this.content_height = this.$tooltip_content.outerHeight(true);
        this.$window = $(window);

        this.$tooltip_content.css({
            width: "100%",
            height: "100%",
        });

        _.each(this.info.event_handlers, (function(data) {
            this.$tooltip_content.on(data.event, data.selector, data.handler);
        }).bind(this));
        this._bind_anchor_events();

        this._reposition();
        this.$el.css("opacity", 1);
        core.bus.on("resize", this, _.debounce(function () {
            if (this.tip_opened) {
                this._to_bubble_mode(true);
            }
            this._reposition();
        }, 500));

        this.$el.on("transitionend oTransitionEnd webkitTransitionEnd", (function () {
            if (!this.tip_opened && this.$el.parent()[0] === document.body) {
                this.$el.detach();
                this.$el.css(this.position);
                this.$el.appendTo(this.$ideal_location);
            }
        }).bind(this));

        return this._super.apply(this, arguments);
    },
    destroy: function () {
        this._unbind_anchor_events();
        clearTimeout(this.timerIn);
        clearTimeout(this.timerOut);

        // Do not remove the parent class if it contains other tooltips
        if (this.$ideal_location.children(".o_tooltip").not(this.$el[0]).length === 0) {
            this.$ideal_location.removeClass("o_tooltip_parent");
        }

        return this._super.apply(this, arguments);
    },
    update: function ($anchor) {
        if (!$anchor.is(this.$anchor)) {
            this._unbind_anchor_events();
            this.$anchor = $anchor;
            this.$ideal_location = this._get_ideal_location();
            if (this.$el.parent()[0] !== document.body) {
                this.$el.appendTo(this.$ideal_location);
            }
            this._bind_anchor_events();
        }
        this._reposition();
    },
    _get_ideal_location: function () {
        var $location = this.$anchor;
        if ($location.is("html,body")) {
            return $(document.body);
        }

        var o;
        var p;
        do {
            $location = $location.parent();
            o = $location.css("overflow");
            p = $location.css("position");
        } while ((o === "visible" || o === "hidden") && p !== "fixed" && $location[0] !== document.body);

        return $location;
    },
    _reposition: function () {
        if (this.tip_opened) return;
        this.$el.removeClass("o_animated");

        this.$el.position({
            my: this._get_spaced_inverted_position(this.info.position),
            at: this.info.position,
            of: this.$anchor,
            collision: "none",
        });

        var offset = this.$el.offset();
        this.$tooltip_overlay.css({
            top: -Math.min((this.info.position === "bottom" ? this.info.space : this.info.overlay.y), offset.top),
            right: -Math.min((this.info.position === "left" ? this.info.space : this.info.overlay.x), this.$window.width() - (offset.left + this.init_width + this.double_border_width)),
            bottom: -Math.min((this.info.position === "top" ? this.info.space : this.info.overlay.y), this.$window.height() - (offset.top + this.init_height + this.double_border_width)),
            left: -Math.min((this.info.position === "right" ? this.info.space : this.info.overlay.x), offset.left),
        });

        this.position = this.$el.position();

        this.$el.addClass("o_animated");
    },
    _bind_anchor_events: function () {
        this.consume_event = Tip.getConsumeEventType(this.$anchor);
        this.$anchor.on(this.consume_event + ".anchor", (function (e) {
            if (e.type !== "mousedown" || e.which === 1) { // only left click
                this.trigger("tip_consumed");
                this._unbind_anchor_events();
            }
        }).bind(this));
        this.$anchor.on('mouseenter.anchor', this._to_info_mode.bind(this));
        this.$anchor.on('mouseleave.anchor', this._to_bubble_mode.bind(this));
    },
    _unbind_anchor_events: function () {
        this.$anchor.off(".anchor");
    },
    _get_spaced_inverted_position: function (position) {
        if (position === "right") return "left+" + this.info.space;
        if (position === "left") return "right-" + this.info.space;
        if (position === "bottom") return "top+" + this.info.space;
        return "bottom-" + this.info.space;
    },
    _to_info_mode: function (force) {
        if (this.timerOut !== undefined) {
            clearTimeout(this.timerOut);
            this.timerOut = undefined;
            return;
        }
        if (this.tip_opened) {
            return;
        }

        if (force === true) {
            this._build_info_mode();
        } else {
            this.timerIn = setTimeout(this._build_info_mode.bind(this), 100);
        }
    },
    _build_info_mode: function () {
        clearTimeout(this.timerIn);
        this.timerIn = undefined;

        this.tip_opened = true;

        var offset = this.$el.offset();

        if (this.$el.parent()[0] !== document.body) {
            this.$el.detach();
            this.$el.css(offset);
            this.$el.appendTo(document.body);
        }

        var mbLeft = 0;
        var mbTop = 0;
        var overflow = false;
        var posVertical = (this.info.position === "top" || this.info.position === "bottom");
        if (posVertical) {
            overflow = (offset.left + this.content_width + this.double_border_width + this.info.overlay.x > this.$window.width());
        } else {
            overflow = (offset.top + this.content_height + this.double_border_width + this.info.overlay.y > this.$window.height());
        }
        if (posVertical && overflow || this.info.position === "left") {
            mbLeft -= (this.content_width - this.init_width);
        }
        if (!posVertical && overflow || this.info.position === "top") {
            mbTop -= (this.content_height - this.init_height);
        }

        this.$el.toggleClass("inverse", overflow);
        this.$el.removeClass("o_animated").addClass("active");
        this.$el.css({
            width: this.content_width,
            height: this.content_height,
            "margin-left": mbLeft,
            "margin-top": mbTop,
        });
    },
    _to_bubble_mode: function (force) {
        if (this.timerIn !== undefined) {
            clearTimeout(this.timerIn);
            this.timerIn = undefined;
            return;
        }
        if (!this.tip_opened) {
            return;
        }

        if (force === true) {
            this._build_bubble_mode();
        } else {
            this.timerOut = setTimeout(this._build_bubble_mode.bind(this), 300);
        }
    },
    _build_bubble_mode: function () {
        clearTimeout(this.timerOut);
        this.timerOut = undefined;

        this.tip_opened = false;

        this.$el.removeClass("active").addClass("o_animated");
        this.$el.css({
            width: this.init_width,
            height: this.init_height,
            margin: 0,
        });
    },
});

Tip.getConsumeEventType = function ($element) {
    if ($element.is("textarea") || $element.filter("input").is(function () {
        return !!$(this).attr("type").match(/^(email|number|password|search|tel|text|url)$/);
    })) {
        return "input";
    }
    return "mousedown";
};

return Tip;

});
<|endoftext|>


<commit_before>'use strict';
/**
 * @file
 * Currently the main entrypoint served on /work.
 * Provides the work view for the enduser.
 */
import React from 'react';

// import components
// import {WorkDisplay} from 'dbc-react-workview';
// import Loader from '../Loader.component.js';
// import reflux actions and stores
import workAction from '../../actions/Work.action.js';
import workStore from '../../stores/Work.store.js';
import Covers from '../Cover.component.js';

const Work = React.createClass({
  propTypes: {
    pid: React.PropTypes.string,
    work: React.PropTypes.object,
  },

  getInitialState() {
    return {
      pid: this.props.pid,
      work: workStore.getStore()
    };
  },

  getWork() {
    let result = {
      pid: this.state.pid
    };
    workAction(result);
  },

  updateWork(work) {
    this.setState({work});
  },

  componentDidMount: function () {
    this.getWork();
    workStore.listen(this.updateWork);
  },

  render() {
    const {pid, work, coverImages} = this.state; // eslint-disable-line
    let general,
      title,
      creators,
      description,
      series,
      subjects,
      languages,
      specific,
      specifics;
    if (work.result.length === 0) {
      return (
);
    }

    general = work.result.general;
    title = general.title;
    if (general.hasOwnProperty('creators')) {
      creators = general.creators.map((creator) => {
        return (
{creator}
);
      });
    }
    if (general.hasOwnProperty('description')) {
      description = general.description;
    }
    if (general.hasOwnProperty('series')) {
      series = general.series;
    }
    if (general.hasOwnProperty('subjects')) {
      subjects = general.subjects.map((subject) => {
        return (
{subject}
);
      });
    }
    if (general.hasOwnProperty('languages')) {
      languages = general.languages.map((language) => {
        return (
{language}
);
      });
    }
    specific = work.result.specific;
    specifics = specific.map((tw) => {
      let identifiers = [];
      identifiers.push(tw.identifiers);
      let dates = tw.dates.map((date) => {
        return (
{date}
);
      });
      return (

{tw.type}

      {dates}

);
    });
  return (

      <Covers pids={work.result.specific[0].identifiers} />

{title}

{creators}

{description}

{series}

{subjects}

{languages}

      {specifics}

  );
  }
});

export default Work;
<commit_msg>remember to LINT!<commit_after>'use strict';
/**
 * @file
 * Currently the main entrypoint served on /work.
 * Provides the work view for the enduser.
 */
import React from 'react';

// import components
// import {WorkDisplay} from 'dbc-react-workview';
// import Loader from '../Loader.component.js';
// import reflux actions and stores
import workAction from '../../actions/Work.action.js';
import workStore from '../../stores/Work.store.js';
import Covers from '../Cover.component.js';

const Work = React.createClass({
  propTypes: {
    pid: React.PropTypes.string,
    work: React.PropTypes.object
  },

  getInitialState() {
    return {
      pid: this.props.pid,
      work: workStore.getStore()
    };
  },

  getWork() {
    let result = {
      pid: this.state.pid
    };
    workAction(result);
  },

  updateWork(work) {
    this.setState({work});
  },

  componentDidMount: function () {
    this.getWork();
    workStore.listen(this.updateWork);
  },

  render() {
    const {pid, work, coverImages} = this.state; // eslint-disable-line
    let general,
      title,
      creators,
      description,
      series,
      subjects,
      languages,
      specific,
      specifics;
    if (work.result.length === 0) {
      return (
);
    }

    general = work.result.general;
    title = general.title;
    if (general.hasOwnProperty('creators')) {
      creators = general.creators.map((creator) => {
        return (
{creator}
);
      });
    }
    if (general.hasOwnProperty('description')) {
      description = general.description;
    }
    if (general.hasOwnProperty('series')) {
      series = general.series;
    }
    if (general.hasOwnProperty('subjects')) {
      subjects = general.subjects.map((subject) => {
        return (
{subject}
);
      });
    }
    if (general.hasOwnProperty('languages')) {
      languages = general.languages.map((language) => {
        return (
{language}
);
      });
    }
    specific = work.result.specific;
    specifics = specific.map((tw) => {
      let identifiers = [];
      identifiers.push(tw.identifiers);
      let dates = tw.dates.map((date) => {
        return (
{date}
);
      });
      return (

{tw.type}

      {dates}

);
    });
    return (

        <Covers pids={work.result.specific[0].identifiers} />

{title}

{creators}

{description}

{series}

{subjects}

{languages}

        {specifics}

    );
  }
});

export default Work;
<|endoftext|>


<commit_before>window.app = {
    isMobile : false,
    chooseDevice : function()
    {
        app.isMobile = false;
        if ( Math.max(document.documentElement.clientWidth, window.innerWidth || 0) <= 480 ) {
            app.isMobile = true;
        }
    },
    initialize : function ()
    {
        this.chooseDevice();
    },
    ready : function(fn)
    {
        if ( document.readyState != 'loading' ) {
            fn();
        } else if (document.addEventListener) {
            document.addEventListener('DOMContentLoaded', fn);
        } else {
            document.attachEvent('onreadystatechange', function () {
                if ( document.readyState != 'loading' ) {
                    fn();
                }
            });
        }
    },
    addEvent : function (evnt, elem, func)
    {
        if ( !elem ) {
            return false;
        }

        if (elem.addEventListener) {
            elem.addEventListener(evnt,func,false);
        } else if (elem.attachEvent) {
            elem.attachEvent("on"+evnt, func);
        } else {
            elem[evnt] = func;
        }
    },
    addClass : function(el, className)
    {
        if ( el.classList ) {
            el.classList.add(className);
        } else {
            el.className += ' ' + className;
        }
    },
    hasClass : function(el, className)
    {
        return ( el.classList ) ? el.classList.contains(className) : new RegExp('(^| )' + className + '( |$)', 'gi').test(el.className);
    },
    removeClass : function(el, className)
    {
        if ( el.classList ) {
            el.classList.remove(className);
        } else {
            el.className = el.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' ');
        }
    }
};

app.extends = {
    enableSideBar : function()
    {
        app.addClass(document.querySelector('body'), 'enable-side-bar');
    },
    disableSideBar : function()
    {
        app.removeClass(document.querySelector('body'), 'enable-side-bar');
    },
    shareThis : function(shareTo)
    {
        var link = null,
            shareLink = encodeURI(window.location.href),
            shareTitle = encodeURI(window.document.title),
            shareBody = encodeURI(( document.querySelector('.post > .content') === null ) ? '' : document.querySelector('.post > .content').textContent.trim().substring(0, 120));

        if ( shareBody ) {
            if ( document.querySelector('.post > .content').textContent.trim().length > 120 ) {
                shareBody = shareBody + '...';
            }
        }

        if ( shareTo === 'facebook' ) {
            link = 'https://www.facebook.com/sharer.php?u=' + shareLink;
        } else if ( shareTo === 'twitter' ) {
            link = 'https://twitter.com/share?url=' + shareLink+ '&text='+shareBody;
        } else if ( shareTo === 'google-plus' ) {
            link = 'https://plus.google.com/share?url=' + shareLink;
        } else if ( shareTo === 'weibo' ) {
            link = 'http://service.weibo.com/share/share.php?content=utf-8&url=' + shareLink + '&title=' + shareTitle;
        }

        window.open(link);
    }
};

app.ready(function()
{
    app.initialize();

    if ( navigator.userAgent.toLowerCase().indexOf('android') > -1 ) {
        document.getElementById('metaViewport').setAttribute('content', 'width='+screen.width+', initial-scale=1.0, maximum-scale=1.0, user-scalable=no');
    }

    window.addEventListener('copy', function (e) {
        document.execCommand('copy');
        e.preventDefault();
        e.clipboardData.setData('text/plain', document.getSelection() + "\n\n[출처]" + document.URL +"  [Hax0r blog]");
   }, false);

    var stie = site;
    (function() {
        var d = document, s = d.createElement('script');
        s.src = '//' + site.disqusId + '.disqus.com/embed.js';
        s.setAttribute('data-timestamp', +new Date());
        (d.head || d.body).appendChild(s);
    })();

    if ( !app.isMobile ) {
        document.querySelector('.header > h1 > a').innerHTML = ( page.title ) ? page.title : site.name;
        setTimeout(function () {
            if ( document.documentElement.getAttribute('data-page') !== 'default' ) {
                app.addClass(document.querySelector('.header > h1'), 'want-to-concentrate');
            }
            app.addEvent('mouseenter', document.querySelector('.header > h1'), function(e)
            {
                if (app.hasClass(document.querySelector('body'), 'throttle')) {
                    return;
                }
                app.removeClass(document.querySelector('.header > h1'), 'want-to-concentrate');
            });

            app.addEvent('mouseleave', document.querySelector('.header > h1'), function(e)
            {
                if (app.hasClass(document.querySelector('body'), 'throttle')) {
                    return;
                }
                app.addClass(document.querySelector('.header > h1'), 'want-to-concentrate');
            });
        }, 1600);
    }

    if ( document.documentElement.getAttribute('data-page') === 'post' ) {
        document.getElementById('app').addEventListener("scroll", function (event) {
            var currentScrollSize = document.getElementById('app').scrollTop;
            var headerHeight = document.querySelector('.header').offsetHeight
            var dropPoint = document.querySelector('.post-title').offsetHeight + document.querySelector('.content-container').offsetTop + headerHeight;
            var bodyElement = document.querySelector('body');
            if (currentScrollSize >= dropPoint) {
                document.querySelector('.content-container').style.top = headerHeight + 'px';
                app.addClass(bodyElement, 'throttle');
                app.removeClass(document.querySelector('.header > h1'), 'want-to-concentrate');
            } else {
                app.removeClass(bodyElement, 'throttle');
                document.querySelector('.content-container').style.top = '0px';
                app.removeClass(document.querySelector('.header > h1'), 'want-to-concentrate');
                setTimeout(function() {
                    app.addClass(document.querySelector('.header > h1'), 'want-to-concentrate');
                }, 1000);
            }
        }, false);
    }

    app.addEvent('resize', window, function(e)
    {
        app.initialize();
        app.chooseDevice();
    });

    app.addEvent('click', document.querySelector('header > .left > a'), function(e)
    {
        e.preventDefault();

        if ( app.hasClass(document.querySelector('body'), 'enable-side-bar') ) {
            app.extends.disableSideBar();
        } else {
            app.extends.enableSideBar();
        }
    });

    var shareButtons = document.querySelectorAll('header > .right a, header > .right button');

    for ( var i = 0; i < shareButtons.length; i++ ) {
        app.addEvent('click', shareButtons[i], function(e)
        {
            e.preventDefault();
            var sharing = e.currentTarget.getAttribute('data-sharing');

            if ( sharing === 'another' && app.hasClass(e.currentTarget, 'opened') ) {
                app.removeClass(e.currentTarget, 'opened');
            } else if ( sharing === 'another' && !app.hasClass(e.currentTarget, 'opened') ) {
                app.addClass(e.currentTarget, 'opened');
            } else {
                app.extends.shareThis(sharing);
            }

            ga("send", "event", {
                eventCategory: "Outbound Link, Share to",
                eventAction: "click",
                eventLabel: sharing,
                transport: "beacon"
            });
        });
    }
});<commit_msg>chore: space ref when copy<commit_after>window.app = {
    isMobile : false,
    chooseDevice : function()
    {
        app.isMobile = false;
        if ( Math.max(document.documentElement.clientWidth, window.innerWidth || 0) <= 480 ) {
            app.isMobile = true;
        }
    },
    initialize : function ()
    {
        this.chooseDevice();
    },
    ready : function(fn)
    {
        if ( document.readyState != 'loading' ) {
            fn();
        } else if (document.addEventListener) {
            document.addEventListener('DOMContentLoaded', fn);
        } else {
            document.attachEvent('onreadystatechange', function () {
                if ( document.readyState != 'loading' ) {
                    fn();
                }
            });
        }
    },
    addEvent : function (evnt, elem, func)
    {
        if ( !elem ) {
            return false;
        }

        if (elem.addEventListener) {
            elem.addEventListener(evnt,func,false);
        } else if (elem.attachEvent) {
            elem.attachEvent("on"+evnt, func);
        } else {
            elem[evnt] = func;
        }
    },
    addClass : function(el, className)
    {
        if ( el.classList ) {
            el.classList.add(className);
        } else {
            el.className += ' ' + className;
        }
    },
    hasClass : function(el, className)
    {
        return ( el.classList ) ? el.classList.contains(className) : new RegExp('(^| )' + className + '( |$)', 'gi').test(el.className);
    },
    removeClass : function(el, className)
    {
        if ( el.classList ) {
            el.classList.remove(className);
        } else {
            el.className = el.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' ');
        }
    }
};

app.extends = {
    enableSideBar : function()
    {
        app.addClass(document.querySelector('body'), 'enable-side-bar');
    },
    disableSideBar : function()
    {
        app.removeClass(document.querySelector('body'), 'enable-side-bar');
    },
    shareThis : function(shareTo)
    {
        var link = null,
            shareLink = encodeURI(window.location.href),
            shareTitle = encodeURI(window.document.title),
            shareBody = encodeURI(( document.querySelector('.post > .content') === null ) ? '' : document.querySelector('.post > .content').textContent.trim().substring(0, 120));

        if ( shareBody ) {
            if ( document.querySelector('.post > .content').textContent.trim().length > 120 ) {
                shareBody = shareBody + '...';
            }
        }

        if ( shareTo === 'facebook' ) {
            link = 'https://www.facebook.com/sharer.php?u=' + shareLink;
        } else if ( shareTo === 'twitter' ) {
            link = 'https://twitter.com/share?url=' + shareLink+ '&text='+shareBody;
        } else if ( shareTo === 'google-plus' ) {
            link = 'https://plus.google.com/share?url=' + shareLink;
        } else if ( shareTo === 'weibo' ) {
            link = 'http://service.weibo.com/share/share.php?content=utf-8&url=' + shareLink + '&title=' + shareTitle;
        }

        window.open(link);
    }
};

app.ready(function()
{
    app.initialize();

    if ( navigator.userAgent.toLowerCase().indexOf('android') > -1 ) {
        document.getElementById('metaViewport').setAttribute('content', 'width='+screen.width+', initial-scale=1.0, maximum-scale=1.0, user-scalable=no');
    }

    window.addEventListener('copy', function (e) {
        document.execCommand('copy');
        e.preventDefault();
        e.clipboardData.setData('text/plain', document.getSelection() + "\n\n[출처] " + document.URL +"  [Hax0r blog]");
   }, false);

    var stie = site;
    (function() {
        var d = document, s = d.createElement('script');
        s.src = '//' + site.disqusId + '.disqus.com/embed.js';
        s.setAttribute('data-timestamp', +new Date());
        (d.head || d.body).appendChild(s);
    })();

    if ( !app.isMobile ) {
        document.querySelector('.header > h1 > a').innerHTML = ( page.title ) ? page.title : site.name;
        setTimeout(function () {
            if ( document.documentElement.getAttribute('data-page') !== 'default' ) {
                app.addClass(document.querySelector('.header > h1'), 'want-to-concentrate');
            }
            app.addEvent('mouseenter', document.querySelector('.header > h1'), function(e)
            {
                if (app.hasClass(document.querySelector('body'), 'throttle')) {
                    return;
                }
                app.removeClass(document.querySelector('.header > h1'), 'want-to-concentrate');
            });

            app.addEvent('mouseleave', document.querySelector('.header > h1'), function(e)
            {
                if (app.hasClass(document.querySelector('body'), 'throttle')) {
                    return;
                }
                app.addClass(document.querySelector('.header > h1'), 'want-to-concentrate');
            });
        }, 1600);
    }

    if ( document.documentElement.getAttribute('data-page') === 'post' ) {
        document.getElementById('app').addEventListener("scroll", function (event) {
            var currentScrollSize = document.getElementById('app').scrollTop;
            var headerHeight = document.querySelector('.header').offsetHeight
            var dropPoint = document.querySelector('.post-title').offsetHeight + document.querySelector('.content-container').offsetTop + headerHeight;
            var bodyElement = document.querySelector('body');
            if (currentScrollSize >= dropPoint) {
                document.querySelector('.content-container').style.top = headerHeight + 'px';
                app.addClass(bodyElement, 'throttle');
                app.removeClass(document.querySelector('.header > h1'), 'want-to-concentrate');
            } else {
                app.removeClass(bodyElement, 'throttle');
                document.querySelector('.content-container').style.top = '0px';
                app.removeClass(document.querySelector('.header > h1'), 'want-to-concentrate');
                setTimeout(function() {
                    app.addClass(document.querySelector('.header > h1'), 'want-to-concentrate');
                }, 1000);
            }
        }, false);
    }

    app.addEvent('resize', window, function(e)
    {
        app.initialize();
        app.chooseDevice();
    });

    app.addEvent('click', document.querySelector('header > .left > a'), function(e)
    {
        e.preventDefault();

        if ( app.hasClass(document.querySelector('body'), 'enable-side-bar') ) {
            app.extends.disableSideBar();
        } else {
            app.extends.enableSideBar();
        }
    });

    var shareButtons = document.querySelectorAll('header > .right a, header > .right button');

    for ( var i = 0; i < shareButtons.length; i++ ) {
        app.addEvent('click', shareButtons[i], function(e)
        {
            e.preventDefault();
            var sharing = e.currentTarget.getAttribute('data-sharing');

            if ( sharing === 'another' && app.hasClass(e.currentTarget, 'opened') ) {
                app.removeClass(e.currentTarget, 'opened');
            } else if ( sharing === 'another' && !app.hasClass(e.currentTarget, 'opened') ) {
                app.addClass(e.currentTarget, 'opened');
            } else {
                app.extends.shareThis(sharing);
            }

            ga("send", "event", {
                eventCategory: "Outbound Link, Share to",
                eventAction: "click",
                eventLabel: sharing,
                transport: "beacon"
            });
        });
    }
});<|endoftext|>