<commit_before>/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/* Copyright 2012 Mozilla Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/* globals PDFJS, PDFView */

'use strict';

var PDFHistory = {
  initialized: false,
  initialDestination: null,

  initialize: function pdfHistoryInitialize(fingerprint) {
    if (PDFJS.disableHistory || PDFView.isViewerEmbedded) {
      // The browsing history is only enabled when the viewer is standalone,
      // i.e. not when it is embedded in a web page.
      return;
    }
    this.initialized = true;
    this.reInitialized = false;
    this.allowHashChange = true;
    this.historyUnlocked = true;

    this.previousHash = window.location.hash.substring(1);
    this.currentBookmark = '';
    this.currentPage = 0;
    this.updatePreviousBookmark = false;
    this.previousBookmark = '';
    this.previousPage = 0;
    this.nextHashParam = '';

    this.fingerprint = fingerprint;
    this.currentUid = this.uid = 0;
    this.current = {};

    var state = window.history.state;
    if (this._isStateObjectDefined(state)) {
      // This corresponds to navigating back to the document
      // from another page in the browser history.
      if (state.target.dest) {
        this.initialDestination = state.target.dest;
      } else {
        PDFView.initialBookmark = state.target.hash;
      }
      this.currentUid = state.uid;
      this.uid = state.uid + 1;
      this.current = state.target;
    } else {
      // This corresponds to the loading of a new document.
      if (state && state.fingerprint &&
          this.fingerprint !== state.fingerprint) {
        // Reinitialize the browsing history when a new document
        // is opened in the web viewer.
        this.reInitialized = true;
      }
      window.history.replaceState({ fingerprint: this.fingerprint }, '');
    }

    var self = this;
    window.addEventListener('popstate', function pdfHistoryPopstate(evt) {
      evt.preventDefault();
      evt.stopPropagation();

      if (!self.historyUnlocked) {
        return;
      }
      if (evt.state) {
        // Move back/forward in the history.
        self._goTo(evt.state);
      } else {
        // Handle the user modifying the hash of a loaded document.
        self.previousHash = window.location.hash.substring(1);

        // If the history is empty when the hash changes,
        // update the previous entry in the browser history.
        if (self.uid === 0) {
          var previousParams = (self.previousHash && self.currentBookmark &&
                                self.previousHash !== self.currentBookmark) ?
            { hash: self.currentBookmark, page: self.currentPage } :
            { page: 1 };
          self.historyUnlocked = false;
          self.allowHashChange = false;
          window.history.back();
          self._pushToHistory(previousParams, false, true);
          window.history.forward();
          self.historyUnlocked = true;
        }
        self._pushToHistory({ hash: self.previousHash }, false, true);
        self._updatePreviousBookmark();
      }
    }, false);

    function pdfHistoryBeforeUnload() {
      var previousParams = self._getPreviousParams(null, true);
      if (previousParams) {
        var replacePrevious = (!self.current.dest &&
                               self.current.hash !== self.previousHash);
        self._pushToHistory(previousParams, false, replacePrevious);
        self._updatePreviousBookmark();
      }
      // Remove the event listener when navigating away from the document,
      // since 'beforeunload' prevents Firefox from caching the document.
      window.removeEventListener('beforeunload', pdfHistoryBeforeUnload, false);
    }
    window.addEventListener('beforeunload', pdfHistoryBeforeUnload, false);

    window.addEventListener('pageshow', function pdfHistoryPageShow(evt) {
      // If the entire viewer (including the PDF file) is cached in the browser,
      // we need to reattach the 'beforeunload' event listener since
      // the 'DOMContentLoaded' event is not fired on 'pageshow'.
      window.addEventListener('beforeunload', pdfHistoryBeforeUnload, false);
    }, false);
  },

  _isStateObjectDefined: function pdfHistory_isStateObjectDefined(state) {
    return (state && state.uid >= 0 &&
            state.fingerprint && this.fingerprint === state.fingerprint &&
            state.target && state.target.hash) ? true : false;
  },

  get isHashChangeUnlocked() {
    if (!this.initialized) {
      return true;
    }
    // If the current hash changes when moving back/forward in the history,
    // this will trigger a 'popstate' event *as well* as a 'hashchange' event.
    // Since the hash generally won't correspond to the exact the position
    // stored in the history's state object, triggering the 'hashchange' event
    // can thus corrupt the browser history.
    //
    // When the hash changes during a 'popstate' event, we *only* prevent the
    // first 'hashchange' event and immediately reset allowHashChange.
    // If it is not reset, the user would not be able to change the hash.

    var temp = this.allowHashChange;
    this.allowHashChange = true;
    return temp;
  },

  _updatePreviousBookmark: function pdfHistory_updatePreviousBookmark() {
    if (this.updatePreviousBookmark &&
        this.currentBookmark && this.currentPage) {
      this.previousBookmark = this.currentBookmark;
      this.previousPage = this.currentPage;
      this.updatePreviousBookmark = false;
    }
  },

  updateCurrentBookmark: function pdfHistoryUpdateCurrentBookmark(bookmark,
                                                                  pageNum) {
    if (this.initialized) {
      this.currentBookmark = bookmark.substring(1);
      this.currentPage = pageNum | 0;
      this._updatePreviousBookmark();
    }
  },

  updateNextHashParam: function pdfHistoryUpdateNextHashParam(param) {
    if (this.initialized) {
      this.nextHashParam = param;
    }
  },

  push: function pdfHistoryPush(params, isInitialBookmark) {
    if (!(this.initialized && this.historyUnlocked)) {
      return;
    }
    if (params.dest && !params.hash) {
      params.hash = (this.current.hash && this.current.dest &&
                     this.current.dest === params.dest) ?
        this.current.hash :
        PDFView.getDestinationHash(params.dest).split('#')[1];
    }
    if (params.page) {
      params.page |= 0;
    }
    if (isInitialBookmark) {
      var target = window.history.state.target;
      if (!target) {
        // Invoked when the user specifies an initial bookmark,
        // thus setting PDFView.initialBookmark, when the document is loaded.
        this._pushToHistory(params, false);
        this.previousHash = window.location.hash.substring(1);
      }
      this.updatePreviousBookmark = this.nextHashParam ? false : true;
      if (target) {
        // If the current document is reloaded,
        // avoid creating duplicate entries in the history.
        this._updatePreviousBookmark();
      }
      return;
    }
    if (this.nextHashParam && this.nextHashParam === params.hash) {
      this.nextHashParam = null;
      this.updatePreviousBookmark = true;
      return;
    }

    if (params.hash) {
      if (this.current.hash) {
        if (this.current.hash !== params.hash) {
          this._pushToHistory(params, true);
        } else {
          if (!this.current.page && params.page) {
            this._pushToHistory(params, false, true);
          }
          this.updatePreviousBookmark = true;
        }
      } else {
        this._pushToHistory(params, true);
      }
    } else if (this.current.page && params.page &&
               this.current.page !== params.page) {
      this._pushToHistory(params, true);
    }
  },

  _getPreviousParams: function pdfHistory_getPreviousParams(onlyCheckPage,
                                                            beforeUnload) {
    if (!(this.currentBookmark && this.currentPage)) {
      return null;
    } else if (this.updatePreviousBookmark) {
      this.updatePreviousBookmark = false;
    }
    if (this.uid > 0 && !(this.previousBookmark && this.previousPage)) {
      // Prevent the history from getting stuck in the current state,
      // effectively preventing the user from going back/forward in the history.
      //
      // This happens if the current position in the document didn't change when
      // the history was previously updated. The reasons for this are either:
      // 1. The current zoom value is such that the document does not need to,
      //    or cannot, be scrolled to display the destination.
      // 2. The previous destination is broken, and doesn't actally point to a
      //    position within the document.
      //    (This is either due to a bad PDF generator, or the user making a
      //     mistake when entering a destination in the hash parameters.)
      return null;
    }
    if ((!this.current.dest && !onlyCheckPage) || beforeUnload) {
      if (this.previousBookmark === this.currentBookmark) {
        return null;
      }
    } else if (this.current.page || onlyCheckPage) {
      if (this.previousPage === this.currentPage) {
        return null;
      }
    } else {
      return null;
    }
    var params = { hash: this.currentBookmark, page: this.currentPage };
    if (PDFView.isPresentationMode) {
      params.hash = null;
    }
    return params;
  },

  _stateObj: function pdfHistory_stateObj(params) {
    return { fingerprint: this.fingerprint, uid: this.uid, target: params };
  },

  _pushToHistory: function pdfHistory_pushToHistory(params,
                                                    addPrevious, overwrite) {
    if (!this.initialized) {
      return;
    }
    if (!params.hash && params.page) {
      params.hash = ('page=' + params.page);
    }
    if (addPrevious && !overwrite) {
      var previousParams = this._getPreviousParams();
      if (previousParams) {
        var replacePrevious = (!this.current.dest &&
                               this.current.hash !== this.previousHash);
        this._pushToHistory(previousParams, false, replacePrevious);
      }
    }
    if (overwrite || this.uid === 0) {
      window.history.replaceState(this._stateObj(params), '');
    } else {
      window.history.pushState(this._stateObj(params), '');
    }
    this.currentUid = this.uid++;
    this.current = params;
    this.updatePreviousBookmark = true;
  },

  _goTo: function pdfHistory_goTo(state) {
    if (!(this.initialized && this.historyUnlocked &&
          this._isStateObjectDefined(state))) {
      return;
    }
    if (!this.reInitialized && state.uid < this.currentUid) {
      var previousParams = this._getPreviousParams(true);
      if (previousParams) {
        this._pushToHistory(this.current, false);
        this._pushToHistory(previousParams, false);
        this.currentUid = state.uid;
        window.history.back();
        return;
      }
    }
    this.historyUnlocked = false;

    if (state.target.dest) {
      PDFView.navigateTo(state.target.dest);
    } else {
      PDFView.setHash(state.target.hash);
    }
    this.currentUid = state.uid;
    if (state.uid > this.uid) {
      this.uid = state.uid;
    }
    this.current = state.target;
    this.updatePreviousBookmark = true;

    var currentHash = window.location.hash.substring(1);
    if (this.previousHash !== currentHash) {
      this.allowHashChange = false;
    }
    this.previousHash = currentHash;

    this.historyUnlocked = true;
  },

  back: function pdfHistoryBack() {
    this.go(-1);
  },

  forward: function pdfHistoryForward() {
    this.go(1);
  },

  go: function pdfHistoryGo(direction) {
    if (this.initialized && this.historyUnlocked) {
      var state = window.history.state;
      if (direction === -1 && state && state.uid > 0) {
        window.history.back();
      } else if (direction === 1 && state && state.uid < (this.uid - 1)) {
        window.history.forward();
      }
    }
  }
};
<commit_msg>[PDFHistory] Prevent the history from skipping entries in certain edge cases, when specifying an initialBookmark in the hash parameters on document load<commit_after>/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/* Copyright 2012 Mozilla Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/* globals PDFJS, PDFView */

'use strict';

var PDFHistory = {
  initialized: false,
  initialDestination: null,

  initialize: function pdfHistoryInitialize(fingerprint) {
    if (PDFJS.disableHistory || PDFView.isViewerEmbedded) {
      // The browsing history is only enabled when the viewer is standalone,
      // i.e. not when it is embedded in a web page.
      return;
    }
    this.initialized = true;
    this.reInitialized = false;
    this.allowHashChange = true;
    this.historyUnlocked = true;

    this.previousHash = window.location.hash.substring(1);
    this.currentBookmark = '';
    this.currentPage = 0;
    this.updatePreviousBookmark = false;
    this.previousBookmark = '';
    this.previousPage = 0;
    this.nextHashParam = '';

    this.fingerprint = fingerprint;
    this.currentUid = this.uid = 0;
    this.current = {};

    var state = window.history.state;
    if (this._isStateObjectDefined(state)) {
      // This corresponds to navigating back to the document
      // from another page in the browser history.
      if (state.target.dest) {
        this.initialDestination = state.target.dest;
      } else {
        PDFView.initialBookmark = state.target.hash;
      }
      this.currentUid = state.uid;
      this.uid = state.uid + 1;
      this.current = state.target;
    } else {
      // This corresponds to the loading of a new document.
      if (state && state.fingerprint &&
          this.fingerprint !== state.fingerprint) {
        // Reinitialize the browsing history when a new document
        // is opened in the web viewer.
        this.reInitialized = true;
      }
      window.history.replaceState({ fingerprint: this.fingerprint }, '');
    }

    var self = this;
    window.addEventListener('popstate', function pdfHistoryPopstate(evt) {
      evt.preventDefault();
      evt.stopPropagation();

      if (!self.historyUnlocked) {
        return;
      }
      if (evt.state) {
        // Move back/forward in the history.
        self._goTo(evt.state);
      } else {
        // Handle the user modifying the hash of a loaded document.
        self.previousHash = window.location.hash.substring(1);

        // If the history is empty when the hash changes,
        // update the previous entry in the browser history.
        if (self.uid === 0) {
          var previousParams = (self.previousHash && self.currentBookmark &&
                                self.previousHash !== self.currentBookmark) ?
            { hash: self.currentBookmark, page: self.currentPage } :
            { page: 1 };
          self.historyUnlocked = false;
          self.allowHashChange = false;
          window.history.back();
          self._pushToHistory(previousParams, false, true);
          window.history.forward();
          self.historyUnlocked = true;
        }
        self._pushToHistory({ hash: self.previousHash }, false, true);
        self._updatePreviousBookmark();
      }
    }, false);

    function pdfHistoryBeforeUnload() {
      var previousParams = self._getPreviousParams(null, true);
      if (previousParams) {
        var replacePrevious = (!self.current.dest &&
                               self.current.hash !== self.previousHash);
        self._pushToHistory(previousParams, false, replacePrevious);
        self._updatePreviousBookmark();
      }
      // Remove the event listener when navigating away from the document,
      // since 'beforeunload' prevents Firefox from caching the document.
      window.removeEventListener('beforeunload', pdfHistoryBeforeUnload, false);
    }
    window.addEventListener('beforeunload', pdfHistoryBeforeUnload, false);

    window.addEventListener('pageshow', function pdfHistoryPageShow(evt) {
      // If the entire viewer (including the PDF file) is cached in the browser,
      // we need to reattach the 'beforeunload' event listener since
      // the 'DOMContentLoaded' event is not fired on 'pageshow'.
      window.addEventListener('beforeunload', pdfHistoryBeforeUnload, false);
    }, false);
  },

  _isStateObjectDefined: function pdfHistory_isStateObjectDefined(state) {
    return (state && state.uid >= 0 &&
            state.fingerprint && this.fingerprint === state.fingerprint &&
            state.target && state.target.hash) ? true : false;
  },

  get isHashChangeUnlocked() {
    if (!this.initialized) {
      return true;
    }
    // If the current hash changes when moving back/forward in the history,
    // this will trigger a 'popstate' event *as well* as a 'hashchange' event.
    // Since the hash generally won't correspond to the exact the position
    // stored in the history's state object, triggering the 'hashchange' event
    // can thus corrupt the browser history.
    //
    // When the hash changes during a 'popstate' event, we *only* prevent the
    // first 'hashchange' event and immediately reset allowHashChange.
    // If it is not reset, the user would not be able to change the hash.

    var temp = this.allowHashChange;
    this.allowHashChange = true;
    return temp;
  },

  _updatePreviousBookmark: function pdfHistory_updatePreviousBookmark() {
    if (this.updatePreviousBookmark &&
        this.currentBookmark && this.currentPage) {
      this.previousBookmark = this.currentBookmark;
      this.previousPage = this.currentPage;
      this.updatePreviousBookmark = false;
    }
  },

  updateCurrentBookmark: function pdfHistoryUpdateCurrentBookmark(bookmark,
                                                                  pageNum) {
    if (this.initialized) {
      this.currentBookmark = bookmark.substring(1);
      this.currentPage = pageNum | 0;
      this._updatePreviousBookmark();
    }
  },

  updateNextHashParam: function pdfHistoryUpdateNextHashParam(param) {
    if (this.initialized) {
      this.nextHashParam = param;
    }
  },

  push: function pdfHistoryPush(params, isInitialBookmark) {
    if (!(this.initialized && this.historyUnlocked)) {
      return;
    }
    if (params.dest && !params.hash) {
      params.hash = (this.current.hash && this.current.dest &&
                     this.current.dest === params.dest) ?
        this.current.hash :
        PDFView.getDestinationHash(params.dest).split('#')[1];
    }
    if (params.page) {
      params.page |= 0;
    }
    if (isInitialBookmark) {
      var target = window.history.state.target;
      if (!target) {
        // Invoked when the user specifies an initial bookmark,
        // thus setting PDFView.initialBookmark, when the document is loaded.
        this._pushToHistory(params, false);
        this.previousHash = window.location.hash.substring(1);
      }
      this.updatePreviousBookmark = this.nextHashParam ? false : true;
      if (target) {
        // If the current document is reloaded,
        // avoid creating duplicate entries in the history.
        this._updatePreviousBookmark();
      }
      return;
    }
    if (this.nextHashParam) {
      if (this.nextHashParam === params.hash) {
        this.nextHashParam = null;
        this.updatePreviousBookmark = true;
        return;
      } else {
        this.nextHashParam = null;
      }
    }

    if (params.hash) {
      if (this.current.hash) {
        if (this.current.hash !== params.hash) {
          this._pushToHistory(params, true);
        } else {
          if (!this.current.page && params.page) {
            this._pushToHistory(params, false, true);
          }
          this.updatePreviousBookmark = true;
        }
      } else {
        this._pushToHistory(params, true);
      }
    } else if (this.current.page && params.page &&
               this.current.page !== params.page) {
      this._pushToHistory(params, true);
    }
  },

  _getPreviousParams: function pdfHistory_getPreviousParams(onlyCheckPage,
                                                            beforeUnload) {
    if (!(this.currentBookmark && this.currentPage)) {
      return null;
    } else if (this.updatePreviousBookmark) {
      this.updatePreviousBookmark = false;
    }
    if (this.uid > 0 && !(this.previousBookmark && this.previousPage)) {
      // Prevent the history from getting stuck in the current state,
      // effectively preventing the user from going back/forward in the history.
      //
      // This happens if the current position in the document didn't change when
      // the history was previously updated. The reasons for this are either:
      // 1. The current zoom value is such that the document does not need to,
      //    or cannot, be scrolled to display the destination.
      // 2. The previous destination is broken, and doesn't actally point to a
      //    position within the document.
      //    (This is either due to a bad PDF generator, or the user making a
      //     mistake when entering a destination in the hash parameters.)
      return null;
    }
    if ((!this.current.dest && !onlyCheckPage) || beforeUnload) {
      if (this.previousBookmark === this.currentBookmark) {
        return null;
      }
    } else if (this.current.page || onlyCheckPage) {
      if (this.previousPage === this.currentPage) {
        return null;
      }
    } else {
      return null;
    }
    var params = { hash: this.currentBookmark, page: this.currentPage };
    if (PDFView.isPresentationMode) {
      params.hash = null;
    }
    return params;
  },

  _stateObj: function pdfHistory_stateObj(params) {
    return { fingerprint: this.fingerprint, uid: this.uid, target: params };
  },

  _pushToHistory: function pdfHistory_pushToHistory(params,
                                                    addPrevious, overwrite) {
    if (!this.initialized) {
      return;
    }
    if (!params.hash && params.page) {
      params.hash = ('page=' + params.page);
    }
    if (addPrevious && !overwrite) {
      var previousParams = this._getPreviousParams();
      if (previousParams) {
        var replacePrevious = (!this.current.dest &&
                               this.current.hash !== this.previousHash);
        this._pushToHistory(previousParams, false, replacePrevious);
      }
    }
    if (overwrite || this.uid === 0) {
      window.history.replaceState(this._stateObj(params), '');
    } else {
      window.history.pushState(this._stateObj(params), '');
    }
    this.currentUid = this.uid++;
    this.current = params;
    this.updatePreviousBookmark = true;
  },

  _goTo: function pdfHistory_goTo(state) {
    if (!(this.initialized && this.historyUnlocked &&
          this._isStateObjectDefined(state))) {
      return;
    }
    if (!this.reInitialized && state.uid < this.currentUid) {
      var previousParams = this._getPreviousParams(true);
      if (previousParams) {
        this._pushToHistory(this.current, false);
        this._pushToHistory(previousParams, false);
        this.currentUid = state.uid;
        window.history.back();
        return;
      }
    }
    this.historyUnlocked = false;

    if (state.target.dest) {
      PDFView.navigateTo(state.target.dest);
    } else {
      PDFView.setHash(state.target.hash);
    }
    this.currentUid = state.uid;
    if (state.uid > this.uid) {
      this.uid = state.uid;
    }
    this.current = state.target;
    this.updatePreviousBookmark = true;

    var currentHash = window.location.hash.substring(1);
    if (this.previousHash !== currentHash) {
      this.allowHashChange = false;
    }
    this.previousHash = currentHash;

    this.historyUnlocked = true;
  },

  back: function pdfHistoryBack() {
    this.go(-1);
  },

  forward: function pdfHistoryForward() {
    this.go(1);
  },

  go: function pdfHistoryGo(direction) {
    if (this.initialized && this.historyUnlocked) {
      var state = window.history.state;
      if (direction === -1 && state && state.uid > 0) {
        window.history.back();
      } else if (direction === 1 && state && state.uid < (this.uid - 1)) {
        window.history.forward();
      }
    }
  }
};
<|endoftext|>


<commit_before>// Load all tabs
const tabs = getElementsByClassName('hero-slide-container')
const literalNumbers = ['one', 'two', 'three', 'four', 'five', 'six']

// Preload images and randomly rotate
const fadeInSlide = slideNumber => {
	// Hero Image
	const hero = getElementByClassName('hero-slide', slideNumber)
	hero.classList.add('fade')
	// Slide in Hero Text
	setTimeout(() => {
		for (let i = 0; i < 3; i++) {
			const title = getElementByClassName('hero-title ' + literalNumbers[i], slideNumber)
			title.classList.add('fade-slide')
		}
	}, 500)
	// Slide in Hero Button
	setTimeout(() => {
		const heroButton = getElementByClassName('hero-button', slideNumber)
		heroButton.classList.add('fade-slide')
	}, 800)
	// Slide in Hero Arrows
	setTimeout(() => {
		const heroArrows = getElementByClassName('hero-arrows', slideNumber)
		heroArrows.classList.add('fade-slide')
	}, 1100)
}

const resetSlide = slideNumber => {
	// Hide Hero Text
	for (let i = 0; i < 3; i++) {
		const title = getElementByClassName('hero-title ' + literalNumbers[i], slideNumber)
		title.classList.remove('fade-slide')
	}
	// Hide Hero Button
	const heroButton = getElementByClassName('hero-button', slideNumber)
	heroButton.classList.remove('fade-slide')
	// Hide Hero Arrows
	const heroArrows = getElementByClassName('hero-arrows', slideNumber)
	heroArrows.classList.remove('fade-slide')
}

const getSlideNumber = () => {
	let obj
	for (let i = 0; i < tabs.length; i++) {
		if (tabs[i].classList.contains('w--tab-active')) {
			obj = i === tabs.length - 1
				? { current: i, next: 0 }
				: { current: i, next: i + 1 }
		}
	}
	return obj
}

const transitionSlides = i => {
	console.log(i)
	const slideNumber = getSlideNumber()
	// Deactivate current tab
	tabs[slideNumber.current].classList.remove('w--tab-active')
	// Activate new tab
	tabs[slideNumber.next].classList.add('w--tab-active')
	// Fade in new slide
	fadeInSlide(slideNumber.next)
	// Reset current slide
	resetSlide(slideNumber.current)
}

// Begin
if (window.location.pathname === '/') {

	fadeInSlide(0)

	// Add event listener to cycle through all hero messages on arrow click
	const rightArrows = getElementsByClassName('hero-arrow right')
	for (let i = 0; i < rightArrows.length - 1; i++) {
		rightArrows[i].addEventListener('click', () => transitionSlides(i))
	}

}<commit_msg>Hero.<commit_after>// Load all tabs
const tabs = getElementsByClassName('hero-slide-container')
const literalNumbers = ['one', 'two', 'three', 'four', 'five', 'six']

// Preload images and randomly rotate
const fadeInSlide = slideNumber => {
	// Hero Image
	const hero = getElementByClassName('hero-slide', slideNumber)
	hero.classList.add('fade')
	// Slide in Hero Text
	setTimeout(() => {
		for (let i = 0; i < 3; i++) {
			const title = getElementByClassName('hero-title ' + literalNumbers[i], slideNumber)
			title.classList.add('fade-slide')
		}
	}, 500)
	// Slide in Hero Button
	setTimeout(() => {
		const heroButton = getElementByClassName('hero-button', slideNumber)
		heroButton.classList.add('fade-slide')
	}, 800)
	// Slide in Hero Arrows
	setTimeout(() => {
		const heroArrows = getElementByClassName('hero-arrows', slideNumber)
		heroArrows.classList.add('fade-slide')
	}, 1100)
}

const resetSlide = slideNumber => {
	// Hide Hero Text
	for (let i = 0; i < 3; i++) {
		const title = getElementByClassName('hero-title ' + literalNumbers[i], slideNumber)
		title.classList.remove('fade-slide')
	}
	// Hide Hero Button
	const heroButton = getElementByClassName('hero-button', slideNumber)
	heroButton.classList.remove('fade-slide')
	// Hide Hero Arrows
	const heroArrows = getElementByClassName('hero-arrows', slideNumber)
	heroArrows.classList.remove('fade-slide')
}

const getSlideNumber = () => {
	let obj
	for (let i = 0; i < tabs.length; i++) {
		if (tabs[i].classList.contains('w--tab-active')) {
			obj = i === tabs.length - 1
				? { current: i, next: 0 }
				: { current: i, next: i + 1 }
		}
	}
	return obj
}

const transitionSlides = () => {
	const slideNumber = getSlideNumber()
	// Deactivate current tab
	tabs[slideNumber.current].classList.remove('w--tab-active')
	// Activate new tab
	tabs[slideNumber.next].classList.add('w--tab-active')
	// Fade in new slide
	fadeInSlide(slideNumber.next)
	// Reset current slide
	resetSlide(slideNumber.current)
}

// Begin
if (window.location.pathname === '/') {

	fadeInSlide(0)

	// Add event listener to cycle through all hero messages on arrow click
	const rightArrows = getElementsByClassName('hero-arrow right')
	for (let i = 0; i < rightArrows.length - 1; i++) {
		console.log(rightArrows[i])
		rightArrows[i].addEventListener('click', () => transitionSlides())
	}

}<|endoftext|>


<commit_before>/*!
 * Bootstrap Markdown Editor v2.0.0 (https://github.com/inacho/bootstrap-markdown-editor)
 * Copyright 2016 Ignacio de Tomás <nacho@inacho.es>
 * Licensed under MIT (https://github.com/inacho/bootstrap-markdown-editor/blob/master/LICENSE)
 */

!function(a){"use strict";function b(b,c,d,e,f){f.show();var g=new FormData,h=0;for(h=0;h<c.length;h++)g.append("file"+h,c[h]);a.ajax({url:b,type:"POST",contentType:!1,data:g,processData:!1,cache:!1,dataType:"json"}).done(function(a){var b="";a.length>1&&(b="\n");for(var c=0;ce&&(c=d-e,b.css("height",c+"px"))}function d(a,b){a.commands.addCommand({name:"bold",bindKey:{win:"Ctrl-B",mac:"Command-B"},exec:function(a){var c=a.session.getTextRange(a.getSelectionRange());""===c?b.insertSnippet(a,"**${1:text}**"):b.insertSnippet(a,"**"+c+"**")},readOnly:!1}),a.commands.addCommand({name:"italic",bindKey:{win:"Ctrl-I",mac:"Command-I"},exec:function(a){var c=a.session.getTextRange(a.getSelectionRange());""===c?b.insertSnippet(a,"*${1:text}*"):b.insertSnippet(a,"*"+c+"*")},readOnly:!1}),a.commands.addCommand({name:"link",bindKey:{win:"Ctrl-K",mac:"Command-K"},exec:function(a){var c=a.session.getTextRange(a.getSelectionRange());""===c?b.insertSnippet(a,"[${1:text}](http://$2)"):b.insertSnippet(a,"["+c+"](http://$1)")},readOnly:!1})}function e(a,b){0===a.getCursorPosition().column?(a.navigateLineStart(),a.insert(b+" ")):(a.navigateLineStart(),a.insert(b+" "),a.navigateLineEnd())}function f(b,c){var d="";return d+='

',d+='
',d+='
',d+='
',d+='<button type="button" data-mdtooltip="tooltip" title="'+c.label.btnHeader1+'" class="md-btn btn btn-sm btn-default" data-btn="h1">H1</button>',d+='<button type="button" data-mdtooltip="tooltip" title="'+c.label.btnHeader2+'" class="md-btn btn btn-sm btn-default" data-btn="h2">H2</button>',d+='<button type="button" data-mdtooltip="tooltip" title="'+c.label.btnHeader3+'" class="md-btn btn btn-sm btn-default" data-btn="h3">H3</button>',d+="
",d+='
',d+='<button type="button" data-mdtooltip="tooltip" title="'+c.label.btnBold+'" class="md-btn btn btn-sm btn-default" data-btn="bold"></button>',d+='<button type="button" data-mdtooltip="tooltip" title="'+c.label.btnItalic+'" class="md-btn btn btn-sm btn-default" data-btn="italic"></button>',d+="
",d+='
',d+='<button type="button" data-mdtooltip="tooltip" title="'+c.label.btnList+'" class="md-btn btn btn-sm btn-default" data-btn="ul"></button>',d+='<button type="button" data-mdtooltip="tooltip" title="'+c.label.btnOrderedList+'" class="md-btn btn btn-sm btn-default" data-btn="ol"></button>',d+="
",d+='
',d+='<button type="button" data-mdtooltip="tooltip" title="'+c.label.btnLink+'" class="md-btn btn btn-sm btn-default" data-btn="link"></button>',d+='<button type="button" data-mdtooltip="tooltip" title="'+c.label.btnImage+'" class="md-btn btn btn-sm btn-default" data-btn="image"></button>',c.imageUpload===!0&&(d+='
<input class="md-input-upload" type="file" multiple accept=".jpg,.jpeg,.png,.gif">
'),d+="
",c.fullscreen===!0&&(d+='
',d+='<button type="button" class="md-btn btn btn-sm btn-default" data-btn="fullscreen"> '+c.label.btnFullscreen+"</button>",d+="
"),c.preview===!0&&(d+='
',d+='<button type="button" class="md-btn btn btn-sm btn-default btn-edit active" data-btn="edit"> '+c.label.btnEdit+"</button>",d+='<button type="button" class="md-btn btn btn-sm btn-default btn-preview" data-btn="preview"> '+c.label.btnPreview+"</button>",d+="
"),d+="
",d+="
",d+='
'+a("
").text(b).html()+"
",d+='

'}var g={init:function(g){var h,i=a.extend(!0,{},a.fn.markdownEditor.defaults,g),j=this,k=!1,l=!1;j.addClass("md-textarea-hidden"),h=a("
"),j.after(h),h.addClass("md-container").html(f(j.val(),i)),"function"==typeof a().tooltip&&h.find('[data-mdtooltip="tooltip"]').tooltip({container:"body"});var m=h.find(".md-editor"),n=h.find(".md-preview"),o=h.find(".md-loading");h.css({width:i.width}),m.css({width:i.width,height:i.height,fontSize:i.fontSize}),n.css({width:i.width,height:i.height});var p,q=ace.edit(m[0]);return q.setTheme("ace/theme/"+i.theme),q.getSession().setMode("ace/mode/markdown"),q.getSession().setUseWrapMode(!0),q.getSession().setUseSoftTabs(i.softTabs),q.getSession().on("change",function(){j.val(q.getSession().getValue())}),q.setHighlightActiveLine(!1),q.setShowPrintMargin(!1),q.renderer.setShowGutter(!1),ace.config.loadModule("ace/ext/language_tools",function(){p=ace.require("ace/snippets").snippetManager,d(q,p)}),i.imageUpload&&(h.find(".md-input-upload").on("change",function(){var c=a(this).get(0).files;c.length&&b(i.uploadPath,a(this).get(0).files,q,p,o)}),h.on("dragenter",function(a){a.stopPropagation(),a.preventDefault()}),h.on("dragover",function(a){a.stopPropagation(),a.preventDefault()}),h.on("drop",function(a){a.preventDefault();var c=a.originalEvent.dataTransfer.files;b(i.uploadPath,c,q,p,o)})),i.fullscreen===!0&&a(window).resize(function(){l===!0&&c(k===!1?m:n)}),h.find(".md-btn").click(function(){var b=a(this).data("btn"),d=q.session.getTextRange(q.getSelectionRange());"h1"===b?e(q,"#"):"h2"===b?e(q,"##"):"h3"===b?e(q,"###"):"ul"===b?e(q,"*"):"ol"===b?e(q,"1."):"bold"===b?q.execCommand("bold"):"italic"===b?q.execCommand("italic"):"link"===b?q.execCommand("link"):"image"===b?""===d?p.insertSnippet(q,"![${1:text}](http://$2)"):p.insertSnippet(q,"!["+d+"](http://$1)"):"edit"===b?(k=!1,n.hide(),m.show(),h.find(".btn-edit").addClass("active"),h.find(".btn-preview").removeClass("active"),l===!0&&c(m)):"preview"===b?(k=!0,n.html('
'+i.label.loading+"...
"),i.onPreview(q.getSession().getValue(),function(a){n.html(a)}),m.hide(),n.show(),h.find(".btn-preview").addClass("active"),h.find(".btn-edit").removeClass("active"),l===!0&&c(n)):"fullscreen"===b&&(l===!0?(l=!1,a("body, html").removeClass("md-body-fullscreen"),h.removeClass("md-fullscreen"),m.css("height",i.height),n.css("height",i.height)):(l=!0,a("body, html").addClass("md-body-fullscreen"),h.addClass("md-fullscreen"),c(k===!1?m:n)),q.resize()),q.focus()}),this},content:function(){var a=ace.edit(this.find(".md-editor")[0]);return a.getSession().getValue()},setContent:function(a){var b=ace.edit(this.find(".md-editor")[0]);b.setValue(a,1)}};a.fn.markdownEditor=function(b){return g[b]?g[b].apply(this,Array.prototype.slice.call(arguments,1)):"object"!=typeof b&&b?void a.error("Method "+b+" does not exist on jQuery.markdownEditor"):g.init.apply(this,arguments)},a.fn.markdownEditor.defaults={width:"100%",height:"400px",fontSize:"14px",theme:"tomorrow",softTabs:!0,fullscreen:!0,imageUpload:!1,uploadPath:"",preview:!1,onPreview:function(a,b){b(a)},label:{btnHeader1:"Header 1",btnHeader2:"Header 2",btnHeader3:"Header 3",btnBold:"Bold",btnItalic:"Italic",btnList:"Unordered list",btnOrderedList:"Ordered list",btnLink:"Link",btnImage:"Insert image",btnUpload:"Upload image",btnEdit:"Edit",btnPreview:"Preview",btnFullscreen:"Fullscreen",loading:"Loading"}}}(jQuery);<commit_msg>Compiled JS<commit_after>/*!
 * Bootstrap Markdown Editor v2.0.0 (https://github.com/inacho/bootstrap-markdown-editor)
 * Copyright 2016 Ignacio de Tomás <nacho@inacho.es>
 * Licensed under MIT (https://github.com/inacho/bootstrap-markdown-editor/blob/master/LICENSE)
 */

!function(a){"use strict";function b(b,c,d,e,f){f.show();var g=new FormData,h=0;for(h=0;h<c.length;h++)g.append("file"+h,c[h]);a.ajax({url:b,type:"POST",contentType:!1,data:g,processData:!1,cache:!1,dataType:"json"}).done(function(a){var b="";a.length>1&&(b="\n");for(var c=0;ce&&(c=d-e,b.css("height",c+"px"))}function d(a,b){a.commands.addCommand({name:"bold",bindKey:{win:"Ctrl-B",mac:"Command-B"},exec:function(a){var c=a.session.getTextRange(a.getSelectionRange());""===c?b.insertSnippet(a,"**${1:text}**"):b.insertSnippet(a,"**"+c+"**")},readOnly:!1}),a.commands.addCommand({name:"italic",bindKey:{win:"Ctrl-I",mac:"Command-I"},exec:function(a){var c=a.session.getTextRange(a.getSelectionRange());""===c?b.insertSnippet(a,"*${1:text}*"):b.insertSnippet(a,"*"+c+"*")},readOnly:!1}),a.commands.addCommand({name:"link",bindKey:{win:"Ctrl-K",mac:"Command-K"},exec:function(a){var c=a.session.getTextRange(a.getSelectionRange());""===c?b.insertSnippet(a,"[${1:text}](http://$2)"):b.insertSnippet(a,"["+c+"](http://$1)")},readOnly:!1})}function e(a,b){0===a.getCursorPosition().column?(a.navigateLineStart(),a.insert(b+" ")):(a.navigateLineStart(),a.insert(b+" "),a.navigateLineEnd())}function f(b,c){var d="";return d+='

',d+='
',d+='
',d+='
',d+='<button type="button" data-mdtooltip="tooltip" title="'+c.label.btnHeader1+'" class="md-btn btn btn-sm btn-default" data-btn="h1">H1</button>',d+='<button type="button" data-mdtooltip="tooltip" title="'+c.label.btnHeader2+'" class="md-btn btn btn-sm btn-default" data-btn="h2">H2</button>',d+='<button type="button" data-mdtooltip="tooltip" title="'+c.label.btnHeader3+'" class="md-btn btn btn-sm btn-default" data-btn="h3">H3</button>',d+="
",d+='
',d+='<button type="button" data-mdtooltip="tooltip" title="'+c.label.btnBold+'" class="md-btn btn btn-sm btn-default" data-btn="bold"></button>',d+='<button type="button" data-mdtooltip="tooltip" title="'+c.label.btnItalic+'" class="md-btn btn btn-sm btn-default" data-btn="italic"></button>',d+="
",d+='
',d+='<button type="button" data-mdtooltip="tooltip" title="'+c.label.btnList+'" class="md-btn btn btn-sm btn-default" data-btn="ul"></button>',d+='<button type="button" data-mdtooltip="tooltip" title="'+c.label.btnOrderedList+'" class="md-btn btn btn-sm btn-default" data-btn="ol"></button>',d+="
",d+='
',d+='<button type="button" data-mdtooltip="tooltip" title="'+c.label.btnLink+'" class="md-btn btn btn-sm btn-default" data-btn="link"></button>',d+='<button type="button" data-mdtooltip="tooltip" title="'+c.label.btnImage+'" class="md-btn btn btn-sm btn-default" data-btn="image"></button>',c.imageUpload===!0&&(d+='
<input class="md-input-upload" type="file" multiple accept=".jpg,.jpeg,.png,.gif">
'),d+="
",c.fullscreen===!0&&(d+='
',d+='<button type="button" class="md-btn btn btn-sm btn-default" data-btn="fullscreen"> '+c.label.btnFullscreen+"</button>",d+="
"),c.preview===!0&&(d+='
',d+='<button type="button" class="md-btn btn btn-sm btn-default btn-edit active" data-btn="edit"> '+c.label.btnEdit+"</button>",d+='<button type="button" class="md-btn btn btn-sm btn-default btn-preview" data-btn="preview"> '+c.label.btnPreview+"</button>",d+="
"),d+="
",d+="
",d+='
'+a("
").text(b).html()+"
",d+='

'}var g={init:function(g){var h,i=a.extend(!0,{},a.fn.markdownEditor.defaults,g),j=this,k=!1,l=!1;j.addClass("md-textarea-hidden"),h=a("
"),j.after(h),h.addClass("md-container").html(f(j.val(),i)),"function"==typeof a().tooltip&&h.find('[data-mdtooltip="tooltip"]').tooltip({container:"body"});var m=h.find(".md-editor"),n=h.find(".md-preview"),o=h.find(".md-loading");h.css({width:i.width}),m.css({height:i.height,fontSize:i.fontSize}),n.css({height:i.height});var p,q=ace.edit(m[0]);return q.setTheme("ace/theme/"+i.theme),q.getSession().setMode("ace/mode/markdown"),q.getSession().setUseWrapMode(!0),q.getSession().setUseSoftTabs(i.softTabs),q.getSession().on("change",function(){j.val(q.getSession().getValue())}),q.setHighlightActiveLine(!1),q.setShowPrintMargin(!1),q.renderer.setShowGutter(!1),ace.config.loadModule("ace/ext/language_tools",function(){p=ace.require("ace/snippets").snippetManager,d(q,p)}),i.imageUpload&&(h.find(".md-input-upload").on("change",function(){var c=a(this).get(0).files;c.length&&b(i.uploadPath,a(this).get(0).files,q,p,o)}),h.on("dragenter",function(a){a.stopPropagation(),a.preventDefault()}),h.on("dragover",function(a){a.stopPropagation(),a.preventDefault()}),h.on("drop",function(a){a.preventDefault();var c=a.originalEvent.dataTransfer.files;b(i.uploadPath,c,q,p,o)})),i.fullscreen===!0&&a(window).resize(function(){l===!0&&c(k===!1?m:n)}),h.find(".md-btn").click(function(){var b=a(this).data("btn"),d=q.session.getTextRange(q.getSelectionRange());"h1"===b?e(q,"#"):"h2"===b?e(q,"##"):"h3"===b?e(q,"###"):"ul"===b?e(q,"*"):"ol"===b?e(q,"1."):"bold"===b?q.execCommand("bold"):"italic"===b?q.execCommand("italic"):"link"===b?q.execCommand("link"):"image"===b?""===d?p.insertSnippet(q,"![${1:text}](http://$2)"):p.insertSnippet(q,"!["+d+"](http://$1)"):"edit"===b?(k=!1,n.hide(),m.show(),h.find(".btn-edit").addClass("active"),h.find(".btn-preview").removeClass("active"),l===!0&&c(m)):"preview"===b?(k=!0,n.html('
'+i.label.loading+"...
"),i.onPreview(q.getSession().getValue(),function(a){n.html(a)}),m.hide(),n.show(),h.find(".btn-preview").addClass("active"),h.find(".btn-edit").removeClass("active"),l===!0&&c(n)):"fullscreen"===b&&(l===!0?(l=!1,a("body, html").removeClass("md-body-fullscreen"),h.removeClass("md-fullscreen"),m.css("height",i.height),n.css("height",i.height)):(l=!0,a("body, html").addClass("md-body-fullscreen"),h.addClass("md-fullscreen"),c(k===!1?m:n)),q.resize()),q.focus()}),this},content:function(){var a=ace.edit(this.find(".md-editor")[0]);return a.getSession().getValue()},setContent:function(a){var b=ace.edit(this.find(".md-editor")[0]);b.setValue(a,1)}};a.fn.markdownEditor=function(b){return g[b]?g[b].apply(this,Array.prototype.slice.call(arguments,1)):"object"!=typeof b&&b?void a.error("Method "+b+" does not exist on jQuery.markdownEditor"):g.init.apply(this,arguments)},a.fn.markdownEditor.defaults={width:"100%",height:"400px",fontSize:"14px",theme:"tomorrow",softTabs:!0,fullscreen:!0,imageUpload:!1,uploadPath:"",preview:!1,onPreview:function(a,b){b(a)},label:{btnHeader1:"Header 1",btnHeader2:"Header 2",btnHeader3:"Header 3",btnBold:"Bold",btnItalic:"Italic",btnList:"Unordered list",btnOrderedList:"Ordered list",btnLink:"Link",btnImage:"Insert image",btnUpload:"Upload image",btnEdit:"Edit",btnPreview:"Preview",btnFullscreen:"Fullscreen",loading:"Loading"}}}(jQuery);<|endoftext|>


<commit_before>/*
 * AdminLTE JS
 *
 */

/*
$(function() {
    "use strict";

    //Add hover support for touch devices
    $('.btn').bind('touchstart', function() {
        $(this).addClass('hover');
    }).bind('touchend', function() {
        $(this).removeClass('hover');
    });

    //Activate tooltips
    $("[data-toggle='tooltip']").tooltip();

    $("[data-widget='collapse']").click(function() {
        //Find the box parent
        var box = $(this).parents(".box").first();
        //Find the body and the footer
        var bf = box.find(".box-body, .box-footer");
        if (!box.hasClass("collapsed-box")) {
            box.addClass("collapsed-box");
            //Convert minus into plus
            $(this).children(".fa-minus").removeClass("fa-minus").addClass("fa-plus");
            bf.slideUp();
        } else {
            box.removeClass("collapsed-box");
            //Convert plus into minus
            $(this).children(".fa-plus").removeClass("fa-plus").addClass("fa-minus");
            bf.slideDown();
        }
    });

    $('.btn-group[data-toggle="btn-toggle"]').each(function() {
        var group = $(this);
        $(this).find(".btn").click(function(e) {
            group.find(".btn.active").removeClass("active");
            $(this).addClass("active");
            e.preventDefault();
        });
    });

    $("[data-widget='remove']").click(function() {
        //Find the box parent
        var box = $(this).parents(".box").first();
        box.slideUp();
    });
});
*/
/* Specific script for back office */
$( function(){
	var nCounter = "";
	var nMax = "";

	// Count effect
	$('.small-box .inner h3').each( function () {
		nCounter = $(this).text();
		var sVal = "";
		var thisTXT = $(this).text().split("/");
		if ( thisTXT.length > 1 ){
			nCounter = thisTXT[0];
			sVal = " / " + thisTXT[1];
		}
		if ( $.isNumeric( nCounter ) ) {
			$(this).prop('Counter',0).animate({
				Counter: nCounter
			}, {
				duration: 1000,
				easing: 'swing',
				step: function (now) {
					$(this).text( Math.ceil(now) + sVal );
				}
			});
		}
	});

	// Count effect dyn-info
	$('.info-box .info-box-number').each( function () {
		nCounter = $(this).text();
		var sVal = "";
		var thisTXT = $(this).text().split("/");

		if ( thisTXT.length > 1 ){
			nCounter = thisTXT[0];
			nMax = thisTXT[1]
			sVal = " / " + thisTXT[1];
		}

		if ( $.isNumeric( nCounter ) && $.isNumeric( nMax ) ) {
			$(this).prop('Counter',0).animate({
				Counter: nCounter
			}, {
				duration: 1000,
				easing: 'swing',
				step: function (now) {
					$(this).text( Math.ceil(now) + sVal );
					var pg = "width:" + ( Math.ceil(now) / nMax * 100 ) + "%" ;
					$(this).next().children().attr("style",  pg );
				}
			});
		}
	});

	//Make the dashboard widgets sortable Using jquery UI
	$(".lutece-dashboard").sortable({
	    placeholder: "sort-highlight",
	    connectWith: ".lutece-dashboard",
	    handle: ".box-header, .info-box-icon",
	    forcePlaceholderSize: true,
	    zIndex: 999999
	  });
	  $(".lutece-dashboard .box-header, .lutece-dashboard .info-box-icon").css("cursor", "move");

		//Make the table tr sortable Using jquery UI
		/*
		$('table.table-sortable tbody').sortable({
	    helper: fixWidthHelper
	}).disableSelection();
  $("table.table-sortable tr").css("cursor", "move");

	function fixWidthHelper(e, ui) {
	    ui.children().each(function() {
	        $(this).width($(this).width());
	    });
	    return ui;
	}*/

	// File Input Style
	$(":file").addClass("filestyle");
	$(":file").filestyle({buttonText: " Parcourir"});

	/** 	MENUS		 **/
	/** MENU TO ACTIVATE **/
	if( $("header").attr("data-menu")=="top" ){
            $("#menu-top").attr("id","menu-left");
	} else if( $("header").attr("data-menu")=="right") {
            $("#top").toggle();
            $("#menu-right").toggleClass("visible-xs");
	} else {
            $("#menu-left").toggleClass("visible-xs");
            $("#top").toggle();
	}

	/** MENU RIGHT **/
		var $lateral_menu_trigger = $('#menu-right'),$content_wrapper = $('#admin-wrapper'),$navigation = $('header');

		//open-close lateral menu clicking on the menu icon
		$lateral_menu_trigger.on('click', function(event){
			event.preventDefault();

			$lateral_menu_trigger.toggleClass('is-clicked');
			$navigation.toggleClass('lateral-menu-is-open');
			$content_wrapper.toggleClass('lateral-menu-is-open').one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function(){
				// firefox transitions break when parent overflow is changed, so we need to wait for the end of the trasition to give the body an overflow hidden
				$('body').toggleClass('overflow-hidden');
			});
			$('#cd-lateral-nav').toggleClass('lateral-menu-is-open');

			//check if transitions are not supported - i.e. in IE9
			if($('html').hasClass('no-csstransitions')) {
				$('body').toggleClass('overflow-hidden');
			}
		});

		//close lateral menu clicking outside the menu itself
		$content_wrapper.on('click', function(event){
		if( !$(event.target).is('#menu-right, #menu-right span') ) {
				$lateral_menu_trigger.removeClass('is-clicked');
				$navigation.removeClass('lateral-menu-is-open');
				$content_wrapper.removeClass('lateral-menu-is-open').one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function(){
					$('body').removeClass('overflow-hidden');
				});
				$('#cd-lateral-nav').removeClass('lateral-menu-is-open');
				//check if transitions are not supported
				if($('html').hasClass('no-csstransitions')) {
					$('body').removeClass('overflow-hidden');
				}
			}
		});

		//open (or close) submenu items in the lateral menu. Close all the other open submenu items.
		$('.item-has-children').children('a').on('click', function(event){
			event.preventDefault();
			$(this).toggleClass('submenu-open').next('.sub-menu').slideToggle(200).end().parent('.item-has-children').siblings('.item-has-children').children('a').removeClass('submenu-open').next('.sub-menu').slideUp(200);
		});

	/** END MENU RIGHT **/

	/** MENU LEFT **/
		// Off Canvas Menu Begin
		// Calling the function
		$(function() {
			$('#menu-left').click(function( e ) {
				toggleNavigation();
				e.preventDefault();
			});

			$('#nav>h2#title').click(function( e ) {
				toggleNavigation();
			});
		});

		// The toggleNav function itself
		function toggleNavigation() {
			if ($('#admin-wrapper').hasClass('display-nav')) {
				// Close Nav
				$('#admin-wrapper').removeClass('display-nav');
			} else {
				// Open Nav
				$('#admin-wrapper').addClass('display-nav');
			}
		}

		// Sliding codes
		$("#toggle > li > div").click(function (e) {
			e.preventDefault();
			if (false == $(this).next().is(':visible')) {
				$('#toggle ul').slideUp();
			}
			var $currIcon=$(this).find("span.the-btn");
			$("span.the-btn").not($currIcon).addClass('fa-plus').removeClass('fa-minus');
			$currIcon.toggleClass('fa-minus fa-plus');
			$(this).next().slideToggle();
			$("#toggle > li > div").removeClass("active");
			$(this).addClass('active');
		});
		// Off Canvas Menu End

	/** END MENU LEFT **/
	/** 	END MENUS		 **/

	$(".portlet-type").on('click', function(e) {
		// Stop the link default behaviour.
		e.preventDefault();
		// Set the iframe src with the clicked link href.
		$('#preview').attr('src', $(this).children().attr('href') );
	});

	// Admin responsive preview
	function _fix() {
		var h = $(window).height();
        var w = $(window).width();
        $("#preview").css({
			width: (w - 30) + "px",
            height: (h - 50) + "px"
			});
        }
		_fix();
        $(window).resize(function() {
			_fix();
        });

        function iframe_width(width) {
			$("#preview").animate({width: width}, 500);
        }

        $("#display-full").click(function(e){
			e.preventDefault();
            iframe_width("100%");
        });

        $("#display-940").click(function(e){
			e.preventDefault();
            iframe_width("940px");
        });

        $("#display-480").click(function(e){
			e.preventDefault();
            iframe_width("480px");
        });

	// Admin Preview fullscreen
	if ( $("#fullscreen").length > 0 ){
		$("#fullscreen").on('click', function(e) {
			// Stop the link default behaviour.
			e.preventDefault();
			// Set the iframe src with the clicked link href.
			$('body').toggleClass("bs-fixed-body");
			$('.content-header').toggle();
			$('.page-header').toggle();
			$('header').toggle();
			$(this).children().toggleClass('fa-arrows-alt').toggleClass('fa-remove');

		});
	}

	// Filter function
	var nb=0;
    $("#search_elements").on("keyup", function () {
        var search = $("#search_elements").val();
		if ( $("select#items_per_page").length > 0 ){
			var s1 = parseInt($("select#items_per_page:first option:selected").val());
			var s2 = parseInt($("select#items_per_page:first").attr("data-max-item"));

			if( s1 < s2 && nb ==0 ) {
				nb++;
				$(this).parent().after('Attention : Vous n\'avez pas sélectionner l\'ensemble des lignes  !! <button id="showall" class="btn btn-primary btn-xs">Tous afficher</button>')
				$("button#showall").click( function(){
					$("select#items_per_page:first").prop("")
				});
			 }
		}
        $(".element-box").each(function (index) {
            var elementName = $(this).attr("data-element").toLowerCase();
            if (elementName.match(search) == null) {
                $(this).parent().slideUp(200).fadeOut(500);
            } else {
                $(this).parent().slideDown(200).fadeIn(500);
            }
        });
    });

});
<commit_msg>LUTECE-2152: avoid default bootstrap filestyle plugin behaviour  for file inputs using a class 'noBootstrapFilestyle'<commit_after>/*
 * AdminLTE JS
 *
 */

/*
$(function() {
    "use strict";

    //Add hover support for touch devices
    $('.btn').bind('touchstart', function() {
        $(this).addClass('hover');
    }).bind('touchend', function() {
        $(this).removeClass('hover');
    });

    //Activate tooltips
    $("[data-toggle='tooltip']").tooltip();

    $("[data-widget='collapse']").click(function() {
        //Find the box parent
        var box = $(this).parents(".box").first();
        //Find the body and the footer
        var bf = box.find(".box-body, .box-footer");
        if (!box.hasClass("collapsed-box")) {
            box.addClass("collapsed-box");
            //Convert minus into plus
            $(this).children(".fa-minus").removeClass("fa-minus").addClass("fa-plus");
            bf.slideUp();
        } else {
            box.removeClass("collapsed-box");
            //Convert plus into minus
            $(this).children(".fa-plus").removeClass("fa-plus").addClass("fa-minus");
            bf.slideDown();
        }
    });

    $('.btn-group[data-toggle="btn-toggle"]').each(function() {
        var group = $(this);
        $(this).find(".btn").click(function(e) {
            group.find(".btn.active").removeClass("active");
            $(this).addClass("active");
            e.preventDefault();
        });
    });

    $("[data-widget='remove']").click(function() {
        //Find the box parent
        var box = $(this).parents(".box").first();
        box.slideUp();
    });
});
*/
/* Specific script for back office */
$( function(){
	var nCounter = "";
	var nMax = "";

	// Count effect
	$('.small-box .inner h3').each( function () {
		nCounter = $(this).text();
		var sVal = "";
		var thisTXT = $(this).text().split("/");
		if ( thisTXT.length > 1 ){
			nCounter = thisTXT[0];
			sVal = " / " + thisTXT[1];
		}
		if ( $.isNumeric( nCounter ) ) {
			$(this).prop('Counter',0).animate({
				Counter: nCounter
			}, {
				duration: 1000,
				easing: 'swing',
				step: function (now) {
					$(this).text( Math.ceil(now) + sVal );
				}
			});
		}
	});

	// Count effect dyn-info
	$('.info-box .info-box-number').each( function () {
		nCounter = $(this).text();
		var sVal = "";
		var thisTXT = $(this).text().split("/");

		if ( thisTXT.length > 1 ){
			nCounter = thisTXT[0];
			nMax = thisTXT[1]
			sVal = " / " + thisTXT[1];
		}

		if ( $.isNumeric( nCounter ) && $.isNumeric( nMax ) ) {
			$(this).prop('Counter',0).animate({
				Counter: nCounter
			}, {
				duration: 1000,
				easing: 'swing',
				step: function (now) {
					$(this).text( Math.ceil(now) + sVal );
					var pg = "width:" + ( Math.ceil(now) / nMax * 100 ) + "%" ;
					$(this).next().children().attr("style",  pg );
				}
			});
		}
	});

	//Make the dashboard widgets sortable Using jquery UI
	$(".lutece-dashboard").sortable({
	    placeholder: "sort-highlight",
	    connectWith: ".lutece-dashboard",
	    handle: ".box-header, .info-box-icon",
	    forcePlaceholderSize: true,
	    zIndex: 999999
	  });
	  $(".lutece-dashboard .box-header, .lutece-dashboard .info-box-icon").css("cursor", "move");

		//Make the table tr sortable Using jquery UI
		/*
		$('table.table-sortable tbody').sortable({
	    helper: fixWidthHelper
	}).disableSelection();
  $("table.table-sortable tr").css("cursor", "move");

	function fixWidthHelper(e, ui) {
	    ui.children().each(function() {
	        $(this).width($(this).width());
	    });
	    return ui;
	}*/

	// File Input Style
	$(":file").not(".noBootstrapFilestyle")
                .addClass("filestyle")
                .filestyle({buttonText: " Parcourir"});

	/** 	MENUS		 **/
	/** MENU TO ACTIVATE **/
	if( $("header").attr("data-menu")=="top" ){
            $("#menu-top").attr("id","menu-left");
	} else if( $("header").attr("data-menu")=="right") {
            $("#top").toggle();
            $("#menu-right").toggleClass("visible-xs");
	} else {
            $("#menu-left").toggleClass("visible-xs");
            $("#top").toggle();
	}

	/** MENU RIGHT **/
		var $lateral_menu_trigger = $('#menu-right'),$content_wrapper = $('#admin-wrapper'),$navigation = $('header');

		//open-close lateral menu clicking on the menu icon
		$lateral_menu_trigger.on('click', function(event){
			event.preventDefault();

			$lateral_menu_trigger.toggleClass('is-clicked');
			$navigation.toggleClass('lateral-menu-is-open');
			$content_wrapper.toggleClass('lateral-menu-is-open').one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function(){
				// firefox transitions break when parent overflow is changed, so we need to wait for the end of the trasition to give the body an overflow hidden
				$('body').toggleClass('overflow-hidden');
			});
			$('#cd-lateral-nav').toggleClass('lateral-menu-is-open');

			//check if transitions are not supported - i.e. in IE9
			if($('html').hasClass('no-csstransitions')) {
				$('body').toggleClass('overflow-hidden');
			}
		});

		//close lateral menu clicking outside the menu itself
		$content_wrapper.on('click', function(event){
		if( !$(event.target).is('#menu-right, #menu-right span') ) {
				$lateral_menu_trigger.removeClass('is-clicked');
				$navigation.removeClass('lateral-menu-is-open');
				$content_wrapper.removeClass('lateral-menu-is-open').one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function(){
					$('body').removeClass('overflow-hidden');
				});
				$('#cd-lateral-nav').removeClass('lateral-menu-is-open');
				//check if transitions are not supported
				if($('html').hasClass('no-csstransitions')) {
					$('body').removeClass('overflow-hidden');
				}
			}
		});

		//open (or close) submenu items in the lateral menu. Close all the other open submenu items.
		$('.item-has-children').children('a').on('click', function(event){
			event.preventDefault();
			$(this).toggleClass('submenu-open').next('.sub-menu').slideToggle(200).end().parent('.item-has-children').siblings('.item-has-children').children('a').removeClass('submenu-open').next('.sub-menu').slideUp(200);
		});

	/** END MENU RIGHT **/

	/** MENU LEFT **/
		// Off Canvas Menu Begin
		// Calling the function
		$(function() {
			$('#menu-left').click(function( e ) {
				toggleNavigation();
				e.preventDefault();
			});

			$('#nav>h2#title').click(function( e ) {
				toggleNavigation();
			});
		});

		// The toggleNav function itself
		function toggleNavigation() {
			if ($('#admin-wrapper').hasClass('display-nav')) {
				// Close Nav
				$('#admin-wrapper').removeClass('display-nav');
			} else {
				// Open Nav
				$('#admin-wrapper').addClass('display-nav');
			}
		}

		// Sliding codes
		$("#toggle > li > div").click(function (e) {
			e.preventDefault();
			if (false == $(this).next().is(':visible')) {
				$('#toggle ul').slideUp();
			}
			var $currIcon=$(this).find("span.the-btn");
			$("span.the-btn").not($currIcon).addClass('fa-plus').removeClass('fa-minus');
			$currIcon.toggleClass('fa-minus fa-plus');
			$(this).next().slideToggle();
			$("#toggle > li > div").removeClass("active");
			$(this).addClass('active');
		});
		// Off Canvas Menu End

	/** END MENU LEFT **/
	/** 	END MENUS		 **/

	$(".portlet-type").on('click', function(e) {
		// Stop the link default behaviour.
		e.preventDefault();
		// Set the iframe src with the clicked link href.
		$('#preview').attr('src', $(this).children().attr('href') );
	});

	// Admin responsive preview
	function _fix() {
		var h = $(window).height();
        var w = $(window).width();
        $("#preview").css({
			width: (w - 30) + "px",
            height: (h - 50) + "px"
			});
        }
		_fix();
        $(window).resize(function() {
			_fix();
        });

        function iframe_width(width) {
			$("#preview").animate({width: width}, 500);
        }

        $("#display-full").click(function(e){
			e.preventDefault();
            iframe_width("100%");
        });

        $("#display-940").click(function(e){
			e.preventDefault();
            iframe_width("940px");
        });

        $("#display-480").click(function(e){
			e.preventDefault();
            iframe_width("480px");
        });

	// Admin Preview fullscreen
	if ( $("#fullscreen").length > 0 ){
		$("#fullscreen").on('click', function(e) {
			// Stop the link default behaviour.
			e.preventDefault();
			// Set the iframe src with the clicked link href.
			$('body').toggleClass("bs-fixed-body");
			$('.content-header').toggle();
			$('.page-header').toggle();
			$('header').toggle();
			$(this).children().toggleClass('fa-arrows-alt').toggleClass('fa-remove');

		});
	}

	// Filter function
	var nb=0;
    $("#search_elements").on("keyup", function () {
        var search = $("#search_elements").val();
		if ( $("select#items_per_page").length > 0 ){
			var s1 = parseInt($("select#items_per_page:first option:selected").val());
			var s2 = parseInt($("select#items_per_page:first").attr("data-max-item"));

			if( s1 < s2 && nb ==0 ) {
				nb++;
				$(this).parent().after('Attention : Vous n\'avez pas sélectionner l\'ensemble des lignes  !! <button id="showall" class="btn btn-primary btn-xs">Tous afficher</button>')
				$("button#showall").click( function(){
					$("select#items_per_page:first").prop("")
				});
			 }
		}
        $(".element-box").each(function (index) {
            var elementName = $(this).attr("data-element").toLowerCase();
            if (elementName.match(search) == null) {
                $(this).parent().slideUp(200).fadeOut(500);
            } else {
                $(this).parent().slideDown(200).fadeIn(500);
            }
        });
    });

});
<|endoftext|>


<commit_before>angular.module('main').controller('InformationCtrl', function(
    $scope, $rootScope, $anchorScroll, $location, $route, $http, $modal,
    $backend, QueriesService, years, periods, entities
) {
    $scope.service = (new QueriesService($backend.API_URL + '/_queries/public/api'));
    $scope.year = ($route.current.params.year ? parseInt($route.current.params.year) : null);
    $scope.period = ($route.current.params.period ? $route.current.params.period : null);
    $scope.cik = ($route.current.params.cik ? $route.current.params.cik : null);
    $scope.reports = [];
    $scope.showtab = [];
    $scope.years = years;
	$scope.periods = periods;
    $scope.entities = entities;

	$scope.computeUsage = function() {
		$scope.usage = [];
		years.forEach(function(year) {
			$scope.usage.push({ used: false, periods: [ { used: false }, { used: false }, { used: false }, { used: false } ] });
		});

		$http({
			method: 'GET',
			url: $backend.API_URL + '/_queries/public/FYandFPByCIK.jq',
			params: { _method: 'POST', cik: $scope.cik, "token" : $scope.token },
			cache: true
		})
		.success(function (data, status, headers, config)
		{
			if (data && data.filings)
			{
				data.filings.forEach(function(filing) {
					$scope.usage[$scope.years.indexOf(filing.fiscalYear)].used = true;
					$scope.usage[$scope.years.indexOf(filing.fiscalYear)].periods[$scope.periods.indexOf(filing.fiscalPeriod == "Q4" ? "FY" : filing.fiscalPeriod)].used = true;
				});
				$scope.adjustYearPeriod();
			}
			else $scope.$emit("error", status, data);
		})
		.error(function(data, status) {
			$scope.$emit("error", status, data);
		});
	};

	$scope.adjustYearPeriod = function() {
		if ($scope.year && !$scope.usage[$scope.years.indexOf($scope.year)].used)
			$scope.year = null;

		if (!$scope.year)
			for (var i = 0; i < $scope.years.length; i++)
				if ($scope.usage[i].used)
				{
					$scope.year = $scope.years[i];
					$scope.period = $scope.periods[0];
					break;
				}

		if ($scope.period && !$scope.usage[$scope.years.indexOf($scope.year)].periods[$scope.periods.indexOf($scope.period)].used)
			$scope.period = null;

		if (!$scope.period)
		{
			var pers = $scope.usage[$scope.years.indexOf($scope.year)].periods;
			for (var i = 0; i < pers.length; i++)
				if (pers[i].used) {
					$scope.period = $scope.periods[i];
					break;
				}
		}
	};

    $scope.selectEntity = function(item) {
        $scope.cik = item.cik;
        $scope.name = item.name;
        $scope.ticker = item.tickers[0];
		$scope.year = null;
		$scope.period = null;
        $scope.change();
    };

	$scope.setYear = function(year, used) {
		if (used)
		{
			$scope.year = year;
			$scope.adjustYearPeriod();
			$scope.change();
		}
	};

	$scope.setPeriod = function(period, used) {
		if (used)
		{
			$scope.period = period;
			$scope.adjustYearPeriod();
			$scope.change();
		}
	};

    $scope.change = function ()
    {
		if ($scope.year && $scope.period)
			$scope.goto("/information/" + $scope.cik + "/" + $scope.year + "/" + $scope.period);
		else
		{
			$scope.goto("/information/" + $scope.cik);
			$http({
					method: 'GET',
					url: $backend.API_URL + '/_queries/public/LatestFYandFPByCIK.jq',
					params: { _method: 'POST', cik: $scope.cik, "token" : $scope.token },
					cache: true
				})
				.success(function (data, status, headers, config)
				{
					if (data && data.latestFYPeriod)
					{
						$scope.year = data.latestFYPeriod.fiscalYear;
						$scope.period = data.latestFYPeriod.fiscalPeriod;
						$scope.goto("/information/" + $scope.cik + "/" + $scope.year + "/" + $scope.period);
					}
					else
						$scope.$emit("error", status, data);
				})
				.error(function (data, status, headers, config)
				{
					$scope.$emit("error", status, data);
				});
		};
    };

    $scope.getComponent = function ()
    {
        $scope.reports = [];
        if (!$scope.cik || !$scope.year || !$scope.period) return;
        $http({
                method: 'GET',
                url: $backend.API_URL + '/_queries/public/FactsForReportSchema.jq',
                params: { _method: 'POST', cik: $scope.cik, fiscalYearFocus: $scope.year, fiscalPeriodFocus: $scope.period, reportSchema: 'FundamentalAccountingConcepts', "token" : $scope.token },
				cache: true
            })
            .success(function (data, status, headers, config)
            {
                var root = data[0]["Trees"]["fac:FundamentalAccountingConceptsLineItems"]["To"]["fac:FundamentalAccountingConceptsHierarchy"]["To"];

                var prepareReport = function(list, array) {
                    for (var key in list) {
                        if (list.hasOwnProperty(key)) {
                            var item = {};
                            item.label = list[key]["Label"] ? list[key]["Label"] : "";
                            if (list[key]["Facts"] && list[key]["Facts"].length > 0)
                            {
                                item.type = list[key]["Facts"][0]["Type"];
                                if (list[key]["Facts"][0]["Type"] == "NumericValue") {
                                    var num = list[key]["Facts"][0]["Value"];
                                    if (!num) num = "0";
                                    item.value = parseFloat(num).toLocaleString();
                                }
                                else
                                    item.value = list[key]["Facts"][0]["Value"];

								item.auditLabel = "";
								item.auditValue = "";
								if (list[key]["Facts"][0]["AuditTrails"] && list[key]["Facts"][0]["AuditTrails"].length > 0)
								{
									switch(list[key]["Facts"][0]["AuditTrails"][0]["Type"]) {
										case 'concept-maps:concept-maps':
											item.auditLabel = list[key]["Facts"][0]["AuditTrails"][0]["Label"];
											item.auditValue = list[key]["Facts"][0]["AuditTrails"][0]["Data"]["OriginalConcept"];
											break;

										case 'hypercubes:dimension-default':
											item.auditLabel = list[key]["Facts"][0]["AuditTrails"][0]["Label"];
											item.auditValue = list[key]["Facts"][0]["AuditTrails"][0]["Data"]["Dimension"];
											break;
									}
								}
                            }
                            else {
                                item.value = '';
                                item.type = '';
								item.auditLabel = '';
								item.auditValue = '';
                            }
                            array.push(item);
                        }
                    }
                };

                for (var report in root) {
                    if (root.hasOwnProperty(report) && report != "fac:KeyRatiosHierarchy") {
                        var obj = { name: root[report]["Label"].toString().replace(" [Hierarchy]", ""), items: [] };
                        prepareReport(root[report]["To"], obj.items);
                        $scope.reports.push(obj);
                        $scope.showtab.push(true);
                    }
                };
            }
        )
        .error(function (data, status, headers, config)
        {
			$scope.$emit("error", status, data);
        });
    };

    $scope.openEntityDetails = function(){
        var modalInstance = $modal.open({
            templateUrl: '/views/entity_details.html',
            controller: 'EntityDetailsCtrl',
            resolve: {
                name: function(){ return $scope.name; },
                cik: function(){ return $scope.cik; },
                ticker: function(){ return $scope.ticker; },
                result: function () {
                    return $scope.service.listEntities({ $method: 'POST', cik: $scope.cik, token: $scope.token });
                }
            }
        });
    };

    if ($route.current.params.cik) {
        $scope.entities.forEach(function(entity) {
            if (entity.cik == $route.current.params.cik){
				if ($scope.year && $scope.period)
				{
					$scope.cik = entity.cik;
					$scope.name = entity.name;
					$scope.ticker = entity.tickers[0];
					$scope.computeUsage();
				}
				else {
					$scope.year = null;
					$scope.period = null;
					$scope.change();
				}
			}
        });
    }
    $scope.getComponent();
});<commit_msg>Fix warnings<commit_after>'use strict';

angular.module('main')
.controller('InformationCtrl', function(
    $scope, $rootScope, $anchorScroll, $location, $route, $http, $modal,
    $backend, QueriesService, years, periods, entities
) {
    $scope.service = (new QueriesService($backend.API_URL + '/_queries/public/api'));
    $scope.year = ($route.current.params.year ? parseInt($route.current.params.year, 10) : null);
    $scope.period = ($route.current.params.period ? $route.current.params.period : null);
    $scope.cik = ($route.current.params.cik ? $route.current.params.cik : null);
    $scope.reports = [];
    $scope.showtab = [];
    $scope.years = years;
	$scope.periods = periods;
    $scope.entities = entities;

	$scope.computeUsage = function() {
		$scope.usage = [];
		years.forEach(function() {
			$scope.usage.push({ used: false, periods: [ { used: false }, { used: false }, { used: false }, { used: false } ] });
		});

		$http({
			method: 'GET',
			url: $backend.API_URL + '/_queries/public/FYandFPByCIK.jq',
			params: { _method: 'POST', cik: $scope.cik, 'token' : $scope.token },
			cache: true
		})
		.success(function (data) {
			if (data && data.filings) {
				data.filings.forEach(function(filing) {
					$scope.usage[$scope.years.indexOf(filing.fiscalYear)].used = true;
					$scope.usage[$scope.years.indexOf(filing.fiscalYear)].periods[$scope.periods.indexOf(filing.fiscalPeriod === 'Q4' ? 'FY' : filing.fiscalPeriod)].used = true;
				});
				$scope.adjustYearPeriod();
			} else {
                $scope.$emit('error', status, data);
            }
		})
		.error(function(data, status) {
			$scope.$emit('error', status, data);
		});
	};

	$scope.adjustYearPeriod = function() {
        var i;
		if ($scope.year && !$scope.usage[$scope.years.indexOf($scope.year)].used) {
            $scope.year = null;
        }
		if (!$scope.year) {
			for (i = 0; i < $scope.years.length; i++) {
				if ($scope.usage[i].used) {
					$scope.year = $scope.years[i];
					$scope.period = $scope.periods[0];
					break;
				}
            }
        }
		if ($scope.period && !$scope.usage[$scope.years.indexOf($scope.year)].periods[$scope.periods.indexOf($scope.period)].used) {
            $scope.period = null;
        }

		if (!$scope.period) {
			var pers = $scope.usage[$scope.years.indexOf($scope.year)].periods;
			for (i = 0; i < pers.length; i++) {
				if (pers[i].used) {
					$scope.period = $scope.periods[i];
					break;
				}
            }
		}
	};

    $scope.selectEntity = function(item) {
        $scope.cik = item.cik;
        $scope.name = item.name;
        $scope.ticker = item.tickers[0];
		$scope.year = null;
		$scope.period = null;
        $scope.change();
    };

	$scope.setYear = function(year, used) {
		if (used) {
            $scope.year = year;
			$scope.adjustYearPeriod();
			$scope.change();
		}
	};

	$scope.setPeriod = function(period, used) {
		if (used) {
			$scope.period = period;
			$scope.adjustYearPeriod();
			$scope.change();
		}
	};

    $scope.change = function () {
		if ($scope.year && $scope.period) {
			$scope.goto('/information/' + $scope.cik + '/' + $scope.year + '/' + $scope.period);
        } else {
			$scope.goto('/information/' + $scope.cik);
			$http({
                method: 'GET',
				url: $backend.API_URL + '/_queries/public/LatestFYandFPByCIK.jq',
				params: { _method: 'POST', cik: $scope.cik, 'token' : $scope.token },
				cache: true
            })
            .success(function (data, status) {
                if (data && data.latestFYPeriod) {
                    $scope.year = data.latestFYPeriod.fiscalYear;
				    $scope.period = data.latestFYPeriod.fiscalPeriod;
				    $scope.goto('/information/' + $scope.cik + '/' + $scope.year + '/' + $scope.period);
				} else {
				    $scope.$emit('error', status, data);
                }
            })
            .error(function (data, status) {
                $scope.$emit('error', status, data);
            });
		}
    };

    $scope.getComponent = function () {
        $scope.reports = [];
        if (!$scope.cik || !$scope.year || !$scope.period) {
            return;
        }
        $http({
            method: 'GET',
            url: $backend.API_URL + '/_queries/public/FactsForReportSchema.jq',
            params: { _method: 'POST', cik: $scope.cik, fiscalYearFocus: $scope.year, fiscalPeriodFocus: $scope.period, reportSchema: 'FundamentalAccountingConcepts', 'token' : $scope.token },
            cache: true
        })
        .success(function (data) {
            var root = data[0].Trees['fac:FundamentalAccountingConceptsLineItems'].To['fac:FundamentalAccountingConceptsHierarchy'].To;
            var prepareReport = function(list, array) {
                for (var key in list) {
                    if (list.hasOwnProperty(key)) {
                        var item = {};
                        item.label = list[key].Label ? list[key].Label : '';
                        if (list[key].Facts && list[key].Facts.length > 0) {
                            item.type = list[key].Facts[0].Type;
                            if(list[key].Facts[0].Type === 'NumericValue') {
                                var num = list[key].Facts[0].Value;
                                if (!num) {
                                    num = '0';
                                }
                                item.value = parseFloat(num).toLocaleString();
                            } else {
                                item.value = list[key].Facts[0].Value;
                            }
				            item.auditLabel = '';
				            item.auditValue = '';
				            if (list[key].Facts[0].AuditTrails && list[key].Facts[0].AuditTrails.length > 0) {
                                switch(list[key].Facts[0].AuditTrails[0].Type) {
                                case 'concept-maps:concept-maps':
				                    item.auditLabel = list[key].Facts[0].AuditTrails[0].Label;
								    item.auditValue = list[key].Facts[0].AuditTrails[0].Data.OriginalConcept;
								    break;
				                case 'hypercubes:dimension-default':
				                    item.auditLabel = list[key].Facts[0].AuditTrails[0].Label;
				                    item.auditValue = list[key].Facts[0].AuditTrails[0].Data.Dimension;
								    break;
				                }
				            }
                        } else {
                            item.value = '';
                            item.type = '';
				            item.auditLabel = '';
				            item.auditValue = '';
                        }
                        array.push(item);
                    }
                }
            };

            for (var report in root) {
                if (root.hasOwnProperty(report) && report !== 'fac:KeyRatiosHierarchy') {
                    var obj = { name: root[report].Label.toString().replace(' [Hierarchy]', ''), items: [] };
                    prepareReport(root[report].To, obj.items);
                    $scope.reports.push(obj);
                    $scope.showtab.push(true);
                }
            }
        })
        .error(function (data, status) {
            $scope.$emit('error', status, data);
        });
    };

    $scope.openEntityDetails = function(){
        $modal.open({
            templateUrl: '/views/entity_details.html',
            controller: 'EntityDetailsCtrl',
            resolve: {
                name: function(){ return $scope.name; },
                cik: function(){ return $scope.cik; },
                ticker: function(){ return $scope.ticker; },
                result: function () {
                    return $scope.service.listEntities({ $method: 'POST', cik: $scope.cik, token: $scope.token });
                }
            }
        });
    };

    if ($route.current.params.cik) {
        $scope.entities.forEach(function(entity) {
            if (entity.cik === $route.current.params.cik) {
				if ($scope.year && $scope.period) {
					$scope.cik = entity.cik;
					$scope.name = entity.name;
					$scope.ticker = entity.tickers[0];
					$scope.computeUsage();
				} else {
					$scope.year = null;
					$scope.period = null;
					$scope.change();
				}
			}
        });
    }
    $scope.getComponent();
});<|endoftext|>


<commit_before>
/**
 * @author huwb / http://huwbowles.com/
 *
 * God-rays (crepuscular rays)
 *
 * Similar implementation to the one used by Crytek for CryEngine 2 [Sousa2008].
 * Blurs a mask generated from the depth map along radial lines emanating from the light
 * source. The blur repeatedly applies a blur filter of increasing support but constant
 * sample count to produce a blur filter with large support.
 *
 * My implementation performs 3 passes, similar to the implementation from Sousa. I found
 * just 6 samples per pass produced acceptible results. The blur is applied three times,
 * with decreasing filter support. The result is equivalent to a single pass with
 * 6*6*6 = 216 samples.
 *
 * References:
 *
 * Sousa2008 - Crysis Next Gen Effects, GDC2008, http://www.crytek.com/sites/default/files/GDC08_SousaT_CrysisEffects.ppt
 */

/*
 * Modified by rscanlon to be more like a projector
 */

THREE.ShaderGodRays = {

    /**
     * The god-ray generation shader.
     *
     * First pass:
     *
     * The input is the depth map. I found that the output from the
     * THREE.MeshDepthMaterial material was directly suitable without
     * requiring any treatment whatsoever.
     *
     * The depth map is blurred along radial lines towards the "sun". The
     * output is written to a temporary render target (I used a 1/4 sized
     * target).
     *
     * Pass two & three:
     *
     * The results of the previous pass are re-blurred, each time with a
     * decreased distance between samples.
     */

    'godrays_generate': {

        uniforms: {

            tInput: {
                type: "t",
                value: null
            },
            fStepSize: {
                type: "f",
                value: 1.0
            },

            vSunPositionScreenSpace: {
                type: "v2",
                value: new THREE.Vector2( 0.0, 0.0 )
            }

        },

        vertexShader: [

            "varying vec2 vUv;",

            "void main() {",

                "vUv = uv;",
                "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",

            "}"

        ].join("\n"),

        fragmentShader: [

            "#define TAPS_PER_PASS 6.0",

            "varying vec2 vUv;",

            "uniform sampler2D tInput;",

            "uniform vec2 vSunPositionScreenSpace;",
            "uniform float fStepSize;", // filter step size

            "void main() {",

                // delta from current pixel to "sun" position

                "vec2 delta = -1.0 * (vSunPositionScreenSpace - vUv);", // MODIFIED BY RSCANLON TO BE NEGATIVE 1
                "float dist = length( delta );",

                // Step vector (uv space)

                "vec2 stepv = fStepSize * delta / dist;",

                // Number of iterations between pixel and sun

                "float iters = dist/fStepSize;",

                "vec2 uv = vUv.xy;",
                "vec4 col = vec4(0.0,0.0,0.0,0.0);",

                // This breaks ANGLE in Chrome 22
                //  - see http://code.google.com/p/chromium/issues/detail?id=153105

                /*
                // Unrolling didnt do much on my hardware (ATI Mobility Radeon 3450),
                // so i've just left the loop

                "for ( float i = 0.0; i < TAPS_PER_PASS; i += 1.0 ) {",

                    // Accumulate samples, making sure we dont walk past the light source.

                    // The check for uv.y < 1 would not be necessary with "border" UV wrap
                    // mode, with a black border colour. I don't think this is currently
                    // exposed by three.js. As a result there might be artifacts when the
                    // sun is to the left, right or bottom of screen as these cases are
                    // not specifically handled.

                    "col += ( i <= iters && uv.y < 1.0 ? texture2D( tInput, uv ).r : 0.0 );",
                    "uv += stepv;",

                "}",
                */

                // Unrolling loop manually makes it work in ANGLE

                "if ( 0.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv );",
                "uv += stepv;",

                "if ( 1.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv );",
                "uv += stepv;",

                "if ( 2.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv );",
                "uv += stepv;",

                "if ( 3.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv );",
                "uv += stepv;",

                "if ( 4.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv );",
                "uv += stepv;",

                "if ( 5.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv );",
                "uv += stepv;",

                // Should technically be dividing by 'iters', but 'TAPS_PER_PASS' smooths out
                // objectionable artifacts, in particular near the sun position. The side
                // effect is that the result is darker than it should be around the sun, as
                // TAPS_PER_PASS is greater than the number of samples actually accumulated.
                // When the result is inverted (in the shader 'godrays_combine', this produces
                // a slight bright spot at the position of the sun, even when it is occluded.

                // "gl_FragColor = base;",
                // "if ( base.rgb == 0.0 ) {",
                "   gl_FragColor = vec4(col/8.0);",
                "   gl_FragColor.a = 1.0;",
                // "} else {",
                // "   gl_FragColor.a = 0.0;",
                // "}",

            "}"

        ].join("\n")

    },

    /**
     * Additively applies god rays from texture tGodRays to a background (tColors).
     * fGodRayIntensity attenuates the god rays.
     */

    'godrays_combine': {

        uniforms: {

            tColors: {
                type: "t",
                value: null
            },

            tGodRays: {
                type: "t",
                value: null
            },

            fGodRayIntensity: {
                type: "f",
                value: 0.69
            },

            vSunPositionScreenSpace: {
                type: "v2",
                value: new THREE.Vector2( 0.5, 0.5 )
            }

        },

        vertexShader: [

            "varying vec2 vUv;",

            "void main() {",

                "vUv = uv;",
                "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",

            "}"

            ].join("\n"),

        fragmentShader: [

            "varying vec2 vUv;",

            "uniform sampler2D tColors;",
            "uniform sampler2D tGodRays;",

            "uniform vec2 vSunPositionScreenSpace;",
            "uniform float fGodRayIntensity;",

            "void main() {",

                // Since THREE.MeshDepthMaterial renders foreground objects white and background
                // objects black, the god-rays will be white streaks. Therefore value is inverted
                // before being combined with tColors

                "gl_FragColor = texture2D( tColors, vUv ) + 30.0*texture2D( tGodRays, vUv );", //changed by rscanlon
                // "gl_FragColor.a = texture2D( tColors, vUv ) + texture2D( tGodRays, vUv );", //changed by rscanlon
                //

                "if (texture2D( tColors, vUv).a > 0.0){",
                "  gl_FragColor = texture2D(tColors, vUv);",
                "}",

                "gl_FragColor.a = (texture2D(tGodRays, vUv).r + texture2D(tGodRays,vUv).g + texture2D(tGodRays, vUv).b + texture2D(tColors, vUv).a);",

            "}"

        ].join("\n")

    },

    /**
     * A dodgy sun/sky shader. Makes a bright spot at the sun location. Would be
     * cheaper/faster/simpler to implement this as a simple sun sprite.
     */

    'godrays_fake_sun': {

        uniforms: {

            vSunPositionScreenSpace: {
                type: "v2",
                value: new THREE.Vector2( 0.0, 0.0 )
            },

            fAspect: {
                type: "f",
                value: 1.0
            },

            sunColor: {
                type: "c",
                value: new THREE.Color( 0xffee00 )
            },

            bgColor: {
                type: "c",
                value: new THREE.Color( 0x000000 )
            }

        },

        vertexShader: [

            "varying vec2 vUv;",

            "void main() {",

                "vUv = uv;",
                "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",

            "}"

        ].join("\n"),

        fragmentShader: [

            "varying vec2 vUv;",

            "uniform vec2 vSunPositionScreenSpace;",
            "uniform float fAspect;",

            "uniform vec3 sunColor;",
            "uniform vec3 bgColor;",

            "void main() {",

                "vec2 diff = vUv - vSunPositionScreenSpace;",

                // Correct for aspect ratio

                "diff.x *= fAspect;",

                "float prop = clamp( length( diff ) / 0.5, 0.0, 1.0 );",
                "prop = 0.35 * pow( 1.0 - prop, 3.0 );",

                "gl_FragColor.xyz = mix( sunColor, bgColor, 1.0 - prop );",
                "gl_FragColor.w = 1.0;",

            "}"

        ].join("\n")

    }

};
<commit_msg>bring down the opacity a tad<commit_after>
/**
 * @author huwb / http://huwbowles.com/
 *
 * God-rays (crepuscular rays)
 *
 * Similar implementation to the one used by Crytek for CryEngine 2 [Sousa2008].
 * Blurs a mask generated from the depth map along radial lines emanating from the light
 * source. The blur repeatedly applies a blur filter of increasing support but constant
 * sample count to produce a blur filter with large support.
 *
 * My implementation performs 3 passes, similar to the implementation from Sousa. I found
 * just 6 samples per pass produced acceptible results. The blur is applied three times,
 * with decreasing filter support. The result is equivalent to a single pass with
 * 6*6*6 = 216 samples.
 *
 * References:
 *
 * Sousa2008 - Crysis Next Gen Effects, GDC2008, http://www.crytek.com/sites/default/files/GDC08_SousaT_CrysisEffects.ppt
 */

/*
 * Modified by rscanlon to be more like a projector
 */

THREE.ShaderGodRays = {

    /**
     * The god-ray generation shader.
     *
     * First pass:
     *
     * The input is the depth map. I found that the output from the
     * THREE.MeshDepthMaterial material was directly suitable without
     * requiring any treatment whatsoever.
     *
     * The depth map is blurred along radial lines towards the "sun". The
     * output is written to a temporary render target (I used a 1/4 sized
     * target).
     *
     * Pass two & three:
     *
     * The results of the previous pass are re-blurred, each time with a
     * decreased distance between samples.
     */

    'godrays_generate': {

        uniforms: {

            tInput: {
                type: "t",
                value: null
            },
            fStepSize: {
                type: "f",
                value: 1.0
            },

            vSunPositionScreenSpace: {
                type: "v2",
                value: new THREE.Vector2( 0.0, 0.0 )
            }

        },

        vertexShader: [

            "varying vec2 vUv;",

            "void main() {",

                "vUv = uv;",
                "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",

            "}"

        ].join("\n"),

        fragmentShader: [

            "#define TAPS_PER_PASS 6.0",

            "varying vec2 vUv;",

            "uniform sampler2D tInput;",

            "uniform vec2 vSunPositionScreenSpace;",
            "uniform float fStepSize;", // filter step size

            "void main() {",

                // delta from current pixel to "sun" position

                "vec2 delta = -1.0 * (vSunPositionScreenSpace - vUv);", // MODIFIED BY RSCANLON TO BE NEGATIVE 1
                "float dist = length( delta );",

                // Step vector (uv space)

                "vec2 stepv = fStepSize * delta / dist;",

                // Number of iterations between pixel and sun

                "float iters = dist/fStepSize;",

                "vec2 uv = vUv.xy;",
                "vec4 col = vec4(0.0,0.0,0.0,0.0);",

                // This breaks ANGLE in Chrome 22
                //  - see http://code.google.com/p/chromium/issues/detail?id=153105

                /*
                // Unrolling didnt do much on my hardware (ATI Mobility Radeon 3450),
                // so i've just left the loop

                "for ( float i = 0.0; i < TAPS_PER_PASS; i += 1.0 ) {",

                    // Accumulate samples, making sure we dont walk past the light source.

                    // The check for uv.y < 1 would not be necessary with "border" UV wrap
                    // mode, with a black border colour. I don't think this is currently
                    // exposed by three.js. As a result there might be artifacts when the
                    // sun is to the left, right or bottom of screen as these cases are
                    // not specifically handled.

                    "col += ( i <= iters && uv.y < 1.0 ? texture2D( tInput, uv ).r : 0.0 );",
                    "uv += stepv;",

                "}",
                */

                // Unrolling loop manually makes it work in ANGLE

                "if ( 0.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv );",
                "uv += stepv;",

                "if ( 1.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv );",
                "uv += stepv;",

                "if ( 2.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv );",
                "uv += stepv;",

                "if ( 3.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv );",
                "uv += stepv;",

                "if ( 4.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv );",
                "uv += stepv;",

                "if ( 5.0 <= iters && uv.y < 1.0 ) col += texture2D( tInput, uv );",
                "uv += stepv;",

                // Should technically be dividing by 'iters', but 'TAPS_PER_PASS' smooths out
                // objectionable artifacts, in particular near the sun position. The side
                // effect is that the result is darker than it should be around the sun, as
                // TAPS_PER_PASS is greater than the number of samples actually accumulated.
                // When the result is inverted (in the shader 'godrays_combine', this produces
                // a slight bright spot at the position of the sun, even when it is occluded.

                // "gl_FragColor = base;",
                // "if ( base.rgb == 0.0 ) {",
                "   gl_FragColor = vec4(col/8.0);",
                "   gl_FragColor.a = 1.0;",
                // "} else {",
                // "   gl_FragColor.a = 0.0;",
                // "}",

            "}"

        ].join("\n")

    },

    /**
     * Additively applies god rays from texture tGodRays to a background (tColors).
     * fGodRayIntensity attenuates the god rays.
     */

    'godrays_combine': {

        uniforms: {

            tColors: {
                type: "t",
                value: null
            },

            tGodRays: {
                type: "t",
                value: null
            },

            fGodRayIntensity: {
                type: "f",
                value: 0.69
            },

            vSunPositionScreenSpace: {
                type: "v2",
                value: new THREE.Vector2( 0.5, 0.5 )
            }

        },

        vertexShader: [

            "varying vec2 vUv;",

            "void main() {",

                "vUv = uv;",
                "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",

            "}"

            ].join("\n"),

        fragmentShader: [

            "varying vec2 vUv;",

            "uniform sampler2D tColors;",
            "uniform sampler2D tGodRays;",

            "uniform vec2 vSunPositionScreenSpace;",
            "uniform float fGodRayIntensity;",

            "void main() {",

                // Since THREE.MeshDepthMaterial renders foreground objects white and background
                // objects black, the god-rays will be white streaks. Therefore value is inverted
                // before being combined with tColors

                "gl_FragColor = texture2D( tColors, vUv ) + 30.0*texture2D( tGodRays, vUv );", //changed by rscanlon
                // "gl_FragColor.a = texture2D( tColors, vUv ) + texture2D( tGodRays, vUv );", //changed by rscanlon
                //

                "if (texture2D( tColors, vUv).a > 0.0){",
                "  gl_FragColor = texture2D(tColors, vUv);",
                "}",

                "gl_FragColor.a = (texture2D(tGodRays, vUv).r + texture2D(tGodRays,vUv).g + texture2D(tGodRays, vUv).b + texture2D(tColors, vUv).a / 2.0);",

            "}"

        ].join("\n")

    },

    /**
     * A dodgy sun/sky shader. Makes a bright spot at the sun location. Would be
     * cheaper/faster/simpler to implement this as a simple sun sprite.
     */

    'godrays_fake_sun': {

        uniforms: {

            vSunPositionScreenSpace: {
                type: "v2",
                value: new THREE.Vector2( 0.0, 0.0 )
            },

            fAspect: {
                type: "f",
                value: 1.0
            },

            sunColor: {
                type: "c",
                value: new THREE.Color( 0xffee00 )
            },

            bgColor: {
                type: "c",
                value: new THREE.Color( 0x000000 )
            }

        },

        vertexShader: [

            "varying vec2 vUv;",

            "void main() {",

                "vUv = uv;",
                "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",

            "}"

        ].join("\n"),

        fragmentShader: [

            "varying vec2 vUv;",

            "uniform vec2 vSunPositionScreenSpace;",
            "uniform float fAspect;",

            "uniform vec3 sunColor;",
            "uniform vec3 bgColor;",

            "void main() {",

                "vec2 diff = vUv - vSunPositionScreenSpace;",

                // Correct for aspect ratio

                "diff.x *= fAspect;",

                "float prop = clamp( length( diff ) / 0.5, 0.0, 1.0 );",
                "prop = 0.35 * pow( 1.0 - prop, 3.0 );",

                "gl_FragColor.xyz = mix( sunColor, bgColor, 1.0 - prop );",
                "gl_FragColor.w = 1.0;",

            "}"

        ].join("\n")

    }

};
<|endoftext|>