<commit_before>module.exports = function() {
    return {
        context: Mix.paths.root(),

        mode: Mix.inProduction() ? 'production' : 'development',

        entry: {},

        output: {},

        module: { rules: [] },

        plugins: [],

        stats: {
            hash: false,
            version: false,
            timings: false,
            children: false,
            errorDetails: false,
            chunks: false,
            modules: false,
            reasons: false,
            source: false,
            publicPath: false
        },

        performance: {
            hints: false
        },

        devtool: Config.sourcemaps,

        devServer: {
            headers: {
                'Access-Control-Allow-Origin': '*'
            },
            contentBase: path.resolve(Config.publicPath),
            historyApiFallback: true,
            noInfo: true,
            compress: true,
            quiet: true
        }
    };
};
<commit_msg>Tweak compile stats<commit_after>module.exports = function() {
    return {
        context: Mix.paths.root(),

        mode: Mix.inProduction() ? 'production' : 'development',

        entry: {},

        output: {},

        module: { rules: [] },

        plugins: [],

        stats: {
            hash: false,
            version: false,
            timings: false,
            children: false,
            errorDetails: false,
            entrypoints: false,
            performance: Mix.inProduction(),
            chunks: false,
            modules: false,
            reasons: false,
            source: false,
            publicPath: false,
            builtAt: false
        },

        performance: {
            hints: false
        },

        devtool: Config.sourcemaps,

        devServer: {
            headers: {
                'Access-Control-Allow-Origin': '*'
            },
            contentBase: path.resolve(Config.publicPath),
            historyApiFallback: true,
            noInfo: true,
            compress: true,
            quiet: true
        }
    };
};
<|endoftext|>


<commit_before>/**
 * IAS History Extension
 * An IAS extension to enable browser history
 * http://infiniteajaxscroll.com
 *
 * This file is part of the Infinite AJAX Scroll package
 *
 * Copyright 2014 Webcreate (Jeroen Fiege)
 */

var IASHistoryExtension = function (options) {
  options = $.extend({}, this.defaults, options);

  this.ias = null;
  this.prevSelector = options.prev;
  this.prevUrl = null;
  this.listeners = {
    prev: new IASCallbacks()
  };

  /**
   * @private
   * @param pageNum
   * @param scrollOffset
   * @param url
   */
  this.onPageChange = function (pageNum, scrollOffset, url) {
    var state = {};

    history.replaceState(state, document.title, url);
  };

  /**
   * @private
   * @param currentScrollOffset
   * @param scrollThreshold
   */
  this.onScroll = function (currentScrollOffset, scrollThreshold) {
    var firstItemScrollThreshold = this.getScrollThresholdFirstItem();

    if (!this.prevUrl) {
      return;
    }

    currentScrollOffset -= this.ias.$scrollContainer.height();

    if (currentScrollOffset <= firstItemScrollThreshold) {
      this.prev();
    }
  };

  /**
   * Returns the url for the next page
   *
   * @private
   */
  this.getPrevUrl = function (container) {
    if (!container) {
      container = this.ias.$container;
    }

    // always take the last matching item
    return $(this.prevSelector, container).last().attr('href');
  };

  /**
   * Returns scroll threshold. This threshold marks the line from where
   * IAS should start loading the next page.
   *
   * @private
   * @return {number}
   */
  this.getScrollThresholdFirstItem = function () {
    var $firstElement;

    $firstElement = this.ias.getFirstItem();

    // if the don't have a first element, the DOM might not have been loaded,
    // or the selector is invalid
    if (0 === $firstElement.size()) {
      return -1;
    }

    return ($firstElement.offset().top);
  };

  /**
   * Renders items
   *
   * @private
   * @param items
   * @param callback
   */
  this.renderBefore = function (items, callback) {
    var ias = this.ias,
        $firstItem = ias.getFirstItem(),
        count = 0;

    ias.fire('render', [items]);

    $(items).hide(); // at first, hide it so we can fade it in later

    $firstItem.before(items);

    $(items).fadeIn(400, function () {
      if (++count < items.length) {
        return;
      }

      ias.fire('rendered', [items]);

      if (callback) {
        callback();
      }
    });
  };

  return this;
};

/**
 * @public
 */
IASHistoryExtension.prototype.initialize = function (ias) {
  var self = this;

  this.ias = ias;

  // expose the extensions listeners
  jQuery.extend(ias.listeners, this.listeners);

  ias.prev = function() {
    self.prev();
  };

  this.prevUrl = this.getPrevUrl();
};

/**
 * Bind to events
 *
 * @public
 * @param ias
 */
IASHistoryExtension.prototype.bind = function (ias) {
  var self = this;

  ias.on('pageChange', $.proxy(this.onPageChange, this));
  ias.on('scroll', $.proxy(this.onScroll, this));
  ias.on('ready', function () {
    var currentScrollOffset = ias.getCurrentScrollOffset(ias.$scrollContainer),
        firstItemScrollThreshold = self.getScrollThresholdFirstItem();

    currentScrollOffset -= ias.$scrollContainer.height();

    if (currentScrollOffset <= firstItemScrollThreshold) {
      self.prev();
    }
  });
};

/**
 * Load the prev page
 *
 * @public
 */
IASHistoryExtension.prototype.prev = function () {
  var url = this.prevUrl,
      self = this,
      ias = this.ias;

  if (!url) {
    return false;
  }

  ias.unbind();

  var promise = ias.fire('prev', [url]);

  promise.done(function () {
    ias.load(url, function (data, items) {
      self.renderBefore(items, function () {
        self.prevUrl = self.getPrevUrl(data);

        ias.bind();

        if (self.prevUrl) {
          self.prev();
        }
      });
    });
  });

  promise.fail(function () {
    ias.bind();
  });

  return true;
};

/**
 * @public
 */
IASHistoryExtension.prototype.defaults = {
  prev: ".prev"
};
<commit_msg>added browser support check for html5 history<commit_after>/**
 * IAS History Extension
 * An IAS extension to enable browser history
 * http://infiniteajaxscroll.com
 *
 * This file is part of the Infinite AJAX Scroll package
 *
 * Copyright 2014 Webcreate (Jeroen Fiege)
 */

var IASHistoryExtension = function (options) {
  options = $.extend({}, this.defaults, options);

  this.ias = null;
  this.prevSelector = options.prev;
  this.prevUrl = null;
  this.listeners = {
    prev: new IASCallbacks()
  };

  /**
   * @private
   * @param pageNum
   * @param scrollOffset
   * @param url
   */
  this.onPageChange = function (pageNum, scrollOffset, url) {
    var state = {};

    if (!window.history || !window.history.replaceState) {
      return;
    }

    history.replaceState(state, document.title, url);
  };

  /**
   * @private
   * @param currentScrollOffset
   * @param scrollThreshold
   */
  this.onScroll = function (currentScrollOffset, scrollThreshold) {
    var firstItemScrollThreshold = this.getScrollThresholdFirstItem();

    if (!this.prevUrl) {
      return;
    }

    currentScrollOffset -= this.ias.$scrollContainer.height();

    if (currentScrollOffset <= firstItemScrollThreshold) {
      this.prev();
    }
  };

  /**
   * Returns the url for the next page
   *
   * @private
   */
  this.getPrevUrl = function (container) {
    if (!container) {
      container = this.ias.$container;
    }

    // always take the last matching item
    return $(this.prevSelector, container).last().attr('href');
  };

  /**
   * Returns scroll threshold. This threshold marks the line from where
   * IAS should start loading the next page.
   *
   * @private
   * @return {number}
   */
  this.getScrollThresholdFirstItem = function () {
    var $firstElement;

    $firstElement = this.ias.getFirstItem();

    // if the don't have a first element, the DOM might not have been loaded,
    // or the selector is invalid
    if (0 === $firstElement.size()) {
      return -1;
    }

    return ($firstElement.offset().top);
  };

  /**
   * Renders items
   *
   * @private
   * @param items
   * @param callback
   */
  this.renderBefore = function (items, callback) {
    var ias = this.ias,
        $firstItem = ias.getFirstItem(),
        count = 0;

    ias.fire('render', [items]);

    $(items).hide(); // at first, hide it so we can fade it in later

    $firstItem.before(items);

    $(items).fadeIn(400, function () {
      if (++count < items.length) {
        return;
      }

      ias.fire('rendered', [items]);

      if (callback) {
        callback();
      }
    });
  };

  return this;
};

/**
 * @public
 */
IASHistoryExtension.prototype.initialize = function (ias) {
  var self = this;

  this.ias = ias;

  // expose the extensions listeners
  jQuery.extend(ias.listeners, this.listeners);

  // expose prev method
  ias.prev = function() {
    self.prev();
  };

  this.prevUrl = this.getPrevUrl();
};

/**
 * Bind to events
 *
 * @public
 * @param ias
 */
IASHistoryExtension.prototype.bind = function (ias) {
  var self = this;

  ias.on('pageChange', $.proxy(this.onPageChange, this));
  ias.on('scroll', $.proxy(this.onScroll, this));
  ias.on('ready', function () {
    var currentScrollOffset = ias.getCurrentScrollOffset(ias.$scrollContainer),
        firstItemScrollThreshold = self.getScrollThresholdFirstItem();

    currentScrollOffset -= ias.$scrollContainer.height();

    if (currentScrollOffset <= firstItemScrollThreshold) {
      self.prev();
    }
  });
};

/**
 * Load the prev page
 *
 * @public
 */
IASHistoryExtension.prototype.prev = function () {
  var url = this.prevUrl,
      self = this,
      ias = this.ias;

  if (!url) {
    return false;
  }

  ias.unbind();

  var promise = ias.fire('prev', [url]);

  promise.done(function () {
    ias.load(url, function (data, items) {
      self.renderBefore(items, function () {
        self.prevUrl = self.getPrevUrl(data);

        ias.bind();

        if (self.prevUrl) {
          self.prev();
        }
      });
    });
  });

  promise.fail(function () {
    ias.bind();
  });

  return true;
};

/**
 * @public
 */
IASHistoryExtension.prototype.defaults = {
  prev: ".prev"
};
<|endoftext|>


<commit_before>/*jshint multistr: true */

var player;
var vid;
var videos=[];
var current=0;
var hash;
var ui_pinned=false;
var after_id;
var chanShowTimeOut;
var infoShowTimeOut;
var lastFetchedChannel;
// Suggestions Welcome! Please Sort Alphabetically
// Except First two.
var channels=[
        'YoutubeHaiku',
        'Videos',

        'AccidentalComedy',
        'ArtisanVideos',
        'AwfulCommercials',
        'CombatFootage',
        'CommercialCuts',
        'ContagiousLaughter',
        'ConTalks',
        'CookingVideos',
        'Cringe',
        'CuriousVideos',
        'DeepIntoYouTube',
        'Documentaries',
        'EducativeVideos',
        'FastWorkers',
        'fifthworldvideos',
        'FightPorn',
        'FuckingWithNature',
        'HappyCrowds',
        'IdiotsFightingThings',
        'InterdimensionalCable',
        'Lectures',
        'MealtimeVideos',
        'MotivationVideos',
        'Music',
        'ObscureMedia',
        'Playitagainsam',
        'PrematureCelebration',
        'PublicFreakout',
        'RoadCam',
        'StandUpComedy',
        'StreetFights',
        'SweetJustice',
        'TheWayWeWereOnVideo',
        'Trailers',
        'UnexpectedThugLife',
        'VideoPorn',
        'Vids',
        'Virtualfreakout',
        'WoahTube',
];
var subreddit=channels[0];
// autoplay video
function onPlayerReady(event) {
    event.target.playVideo();
}

function showChannelName () {
    try{clearTimeout(chanShowTimeOut);}catch(e){}
    $("#channel-name").hide();
    $("#channel-name").text("/r/"+window.location.hash.substring(1));
    $("#channel-name").show();
    chanShowTimeOut = setTimeout(function() { $("#channel-name").hide(); }, 5000);
}

function togglePin () {
    ui_pinned=!ui_pinned;
}

// when video ends
function onPlayerStateChange(event) {
    if(event.data === 0) {
        nextVideo();
    }
}

function nextVideo () {
    try{
        player.destroy();
    }catch(e){}
    showLoading();
    playVideo(videos[current]);
    current+=1;
    if(current>videos.length-1){
        fetchRedditPage (subreddit,after_id);
    }
}

function showLoading () {
    $('#title').html(''); //
    $('#desc').html('');
}

function previousVideo () {
    if(current>0){
        try{
            player.destroy();
        }catch(e){}
        $('#title').html('');//
        $('#desc').html("");
        current-=1;
        playVideo(videos[current]);
        if(current>videos.length-1){
            fetchRedditPage (subreddit,after_id);
        }
    }
}

$(document).ready(function() {
    showLoading();
    $("#info").hide();
    for (var i = 0; i < channels.length; i++) {
        $('#channels-list').html($('#channels-list').html()+'
r/'+channels[i]+'
');
    }

    hash = window.location.hash.substring(1);
    if(!hash)
        window.location.hash=subreddit;
    else{
        subreddit=hash;
        fetchRedditPage(subreddit);
    }
    showChannelName();

    // prevent missing videos from stopping
    // auto playback
    setInterval(function(){
        if(player)
            if(player.getPlayerState()==-1)
                nextVideo();
    },10000);
    // fast scrolling / long press down-up
    // to change channels handler.
    // this will run every 500ms to see if
    // the running channels is infact the channel we wanted
    setInterval(function(){
        if(lastFetchedChannel!=subreddit){
            changeChannel(subreddit);
        }
    },500);

});

$(window).on('hashchange', function() {
    changeChannel(window.location.hash.substring(1));
});

$(window).keydown(function (e) {
  if (e.keyCode === 39) {
    e.preventDefault();
    nextVideo();
  }else if (e.keyCode === 37) {
    e.preventDefault();
    previousVideo();
  }else if (e.keyCode === 99|| e.keyCode === 67) {
    e.preventDefault();
    toggleChannels();
  }else if (e.keyCode === 27) {
    e.preventDefault();
    closeChannels();
  }else if (e.keyCode === 38) {
    e.preventDefault();
    channelUp();
  }else if (e.keyCode === 40) {
    e.preventDefault();
    channelDown();
  }else if (e.keyCode === 32 || e.keyCode === 75|| e.keyCode === 107) {
    e.preventDefault();
    togglePlay();
  }
});

function toggleChannels () {
    $("#channels").fadeToggle();
}

function closeChannels() {
    $('#channels').fadeOut();
}

function changeChannel (_channel) {
    showLoading();
    //closeChannels();
    subreddit = _channel;
    if(player)
        player.destroy();
    videos=[];
    current=0;
    after_id=null;
    fetchRedditPage(subreddit);
}

function channelUp () {
    chnum = channels.indexOf(subreddit);
    chnum-=1;
    if(chnum>=0){
        window.location.hash=channels[chnum];
        changeChannelIndicator(channels[chnum]);
    }
    showChannelName ();
}

function channelDown () {
    chnum = channels.indexOf(subreddit);
    chnum+=1;
    if(chnum<channels.length){
        window.location.hash=channels[chnum];
        changeChannelIndicator(channels[chnum]);
    }
    showChannelName ();
}

function changeChannelIndicator (ch) {
    $(".channel-button").removeClass('selected-channel');
    $("#"+ch+"-button").addClass('selected-channel');
}

function fetchRedditPage (_subreddit,after) {
    changeChannelIndicator(_subreddit);
    var link='https://www.reddit.com/r/'+_subreddit+'.json?after='+after;
    $.get(link,function(s){
        for (var i = 0; i < s.data.children.length; i++) {
            try{
                var video={};
                if(s.data.children[i].data.domain.indexOf('youtu')!=-1 ){
                    video.type='youtube.com';
                    embed_code=s.data.children[i].data.media.oembed.html;
                    if(embed_code.split('embed/').length>1)
                        video.id=embed_code.split('embed/')[1].split('?')[0];
                    else
                        video.id = s.data.children[i].data.media.oembed.url.split("v=")[1];
                    video.title=s.data.children[i].data.media.oembed.title;
                    video.author=s.data.children[i].data.author;
                    video.score=s.data.children[i].data.score;
                    video.channel=_subreddit;
                    video.permalink=s.data.children[i].data.permalink;
                    videos.push(video);
                }

            }catch(e){
                //TODO: help! i need more video embed support!
                //I think Vines should be easy
                console.log(e,'Currently not supported: ',s.data.children[i]);
            }
        }
        if(!after_id){
            playVideo(videos[current]);
            current+=1;
        }

        after_id=s.data.after;
    });
}

function togglePlay () {
    if(player.getPlayerState()==2){
        player.playVideo();
        $("#playbutton").removeClass();
        $("#playbutton").addClass('ic-button fa fa-pause');
    }
    else if(player.getPlayerState()==1){
        player.pauseVideo();
        $("#playbutton").removeClass();
        $("#playbutton").addClass('ic-button fa fa-play');
    }

}

// This function checks if the specified event is supported by the browser.
// Source: http://perfectionkills.com/detecting-event-support-without-browser-sniffing/
function isEventSupported(eventName) {
    var el = document.createElement('div');
    eventName = 'on' + eventName;
    var isSupported = (eventName in el);
    if (!isSupported) {
        el.setAttribute(eventName, 'return;');
        isSupported = typeof el[eventName] == 'function';
    }
    el = null;
    return isSupported;
}

$(document).ready(function() {
    // Check which wheel event is supported. Don't use both as it would fire each event
    // in browsers where both events are supported.
    var wheelEvent = isEventSupported('mousewheel') ? 'mousewheel' : 'wheel';

    // Now bind the event to the desired element
    $('#veil').on(wheelEvent, function(e) {
        var oEvent = e.originalEvent,
            delta  = oEvent.deltaY || oEvent.wheelDelta;

        // deltaY for wheel event
        // wheelData for mousewheel event

        if (delta > 0) {
            channelDown();
        } else {
            channelUp();
        }
    });
});

function playVideo (video) {
    $("#info").hide();
    if(video)
        lastFetchedChannel=video.channel;
      player = new YT.Player('player', {
      height: $(window).height(),
      width: $(window).width(),
      videoId: video.id,
      playerVars: {
             'controls': 0,
             'rel' : 0,
             'showinfo':0,
             'iv_load_policy':3,
             'autoplay': 1,
      },
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
    showInfo(video);
}

function openInYouTube (id) {
    player.pauseVideo();
    var time = Math.floor(player.getCurrentTime());
    if(time/60>0)
        time=Math.floor(time/60)+"m"+(time%60)+"s";
    window.open("http://www.youtube.com/watch?t="+time+"&v="+id, "_blank");
}

function showInfo (video) {
    try{clearTimeout(infoShowTimeOut);}catch(e){}
    infoShowTimeOut=setTimeout(function() { $("#info").show(); },100);
    $('#title').html(video.title);
    // &nbsp&nbsp
    // un pinning ui
    $('#desc').html('&nbsp&nbsp\
        &nbsp·\
        &nbsp&nbsp&nbsp\
        &nbsp&nbsp\
         · /r/\
        '+video.channel+" · /u/"+video.author+' ·  '+video.score);
    $("#infolink").attr("href", "http://www.reddit.com"+video.permalink);
}<commit_msg>Added code to prevent duplication of videos<commit_after>/*jshint multistr: true */

var player;
var vid;
var videos=[];
var current=0;
var hash;
var ui_pinned=false;
var after_id;
var chanShowTimeOut;
var infoShowTimeOut;
var lastFetchedChannel;
// Suggestions Welcome! Please Sort Alphabetically
// Except First two.
var channels=[
        'YoutubeHaiku',
        'Videos',

        'AccidentalComedy',
        'ArtisanVideos',
        'AwfulCommercials',
        'CombatFootage',
        'CommercialCuts',
        'ContagiousLaughter',
        'ConTalks',
        'CookingVideos',
        'Cringe',
        'CuriousVideos',
        'DeepIntoYouTube',
        'Documentaries',
        'EducativeVideos',
        'FastWorkers',
        'fifthworldvideos',
        'FightPorn',
        'FuckingWithNature',
        'HappyCrowds',
        'IdiotsFightingThings',
        'InterdimensionalCable',
        'Lectures',
        'MealtimeVideos',
        'MotivationVideos',
        'Music',
        'ObscureMedia',
        'Playitagainsam',
        'PrematureCelebration',
        'PublicFreakout',
        'RoadCam',
        'StandUpComedy',
        'StreetFights',
        'SweetJustice',
        'TheWayWeWereOnVideo',
        'Trailers',
        'UnexpectedThugLife',
        'VideoPorn',
        'Vids',
        'Virtualfreakout',
        'WoahTube',
];
var subreddit=channels[0];
// autoplay video
function onPlayerReady(event) {
    event.target.playVideo();
}

function videoExistsInQueue (id) {
    for (var i = 0; i < videos.length; i++) {
        if(videos[i].id==id)
            return true;
    };
    return false;
}

function showChannelName () {
    try{clearTimeout(chanShowTimeOut);}catch(e){}
    $("#channel-name").hide();
    $("#channel-name").text("/r/"+window.location.hash.substring(1));
    $("#channel-name").show();
    chanShowTimeOut = setTimeout(function() { $("#channel-name").hide(); }, 5000);
}

function togglePin () {
    ui_pinned=!ui_pinned;
}

// when video ends
function onPlayerStateChange(event) {
    if(event.data === 0) {
        nextVideo();
    }
}

function nextVideo () {
    try{
        player.destroy();
    }catch(e){}
    showLoading();
    playVideo(videos[current]);
    current+=1;
    if(current>videos.length-1){
        fetchRedditPage (subreddit,after_id);
    }
}

function showLoading () {
    $('#title').html(''); //
    $('#desc').html('');
}

function previousVideo () {
    if(current>0){
        try{
            player.destroy();
        }catch(e){}
        $('#title').html('');//
        $('#desc').html("");
        current-=1;
        playVideo(videos[current]);
        if(current>videos.length-1){
            fetchRedditPage (subreddit,after_id);
        }
    }
}

$(document).ready(function() {
    showLoading();
    $("#info").hide();
    for (var i = 0; i < channels.length; i++) {
        $('#channels-list').html($('#channels-list').html()+'
r/'+channels[i]+'
');
    }

    hash = window.location.hash.substring(1);
    if(!hash)
        window.location.hash=subreddit;
    else{
        subreddit=hash;
        fetchRedditPage(subreddit);
    }
    showChannelName();

    // prevent missing videos from stopping
    // auto playback
    setInterval(function(){
        if(player)
            if(player.getPlayerState()==-1)
                nextVideo();
    },10000);
    // fast scrolling / long press down-up
    // to change channels handler.
    // this will run every 500ms to see if
    // the running channels is infact the channel we wanted
    setInterval(function(){
        if(lastFetchedChannel!=subreddit){
            changeChannel(subreddit);
        }
    },500);

});

$(window).on('hashchange', function() {
    changeChannel(window.location.hash.substring(1));
});

$(window).keydown(function (e) {
  if (e.keyCode === 39) {
    e.preventDefault();
    nextVideo();
  }else if (e.keyCode === 37) {
    e.preventDefault();
    previousVideo();
  }else if (e.keyCode === 99|| e.keyCode === 67) {
    e.preventDefault();
    toggleChannels();
  }else if (e.keyCode === 27) {
    e.preventDefault();
    closeChannels();
  }else if (e.keyCode === 38) {
    e.preventDefault();
    channelUp();
  }else if (e.keyCode === 40) {
    e.preventDefault();
    channelDown();
  }else if (e.keyCode === 32 || e.keyCode === 75|| e.keyCode === 107) {
    e.preventDefault();
    togglePlay();
  }
});

function toggleChannels () {
    $("#channels").fadeToggle();
}

function closeChannels() {
    $('#channels').fadeOut();
}

function changeChannel (_channel) {
    showLoading();
    //closeChannels();
    subreddit = _channel;
    if(player)
        player.destroy();
    videos=[];
    current=0;
    after_id=null;
    fetchRedditPage(subreddit);
}

function channelUp () {
    chnum = channels.indexOf(subreddit);
    chnum-=1;
    if(chnum>=0){
        window.location.hash=channels[chnum];
        changeChannelIndicator(channels[chnum]);
    }
    showChannelName ();
}

function channelDown () {
    chnum = channels.indexOf(subreddit);
    chnum+=1;
    if(chnum<channels.length){
        window.location.hash=channels[chnum];
        changeChannelIndicator(channels[chnum]);
    }
    showChannelName ();
}

function changeChannelIndicator (ch) {
    $(".channel-button").removeClass('selected-channel');
    $("#"+ch+"-button").addClass('selected-channel');
}

function fetchRedditPage (_subreddit,after) {
    changeChannelIndicator(_subreddit);
    var link='https://www.reddit.com/r/'+_subreddit+'.json?after='+after;
    $.get(link,function(s){
        for (var i = 0; i < s.data.children.length; i++) {
            try{
                var video={};
                if(s.data.children[i].data.domain.indexOf('youtu')!=-1 ){
                    video.type='youtube.com';
                    embed_code=s.data.children[i].data.media.oembed.html;
                    if(embed_code.split('embed/').length>1)
                        video.id=embed_code.split('embed/')[1].split('?')[0];
                    else
                        video.id = s.data.children[i].data.media.oembed.url.split("v=")[1];
                    video.title=s.data.children[i].data.media.oembed.title;
                    video.author=s.data.children[i].data.author;
                    video.score=s.data.children[i].data.score;
                    video.channel=_subreddit;
                    video.permalink=s.data.children[i].data.permalink;
                    if(!videoExistsInQueue(video.id))
                        videos.push(video);
                }

            }catch(e){
                //TODO: help! i need more video embed support!
                //I think Vines should be easy
                console.log(e,'Currently not supported: ',s.data.children[i]);
            }
        }
        if(!after_id){
            playVideo(videos[current]);
            current+=1;
        }

        after_id=s.data.after;
    });
}

function togglePlay () {
    if(player.getPlayerState()==2){
        player.playVideo();
        $("#playbutton").removeClass();
        $("#playbutton").addClass('ic-button fa fa-pause');
    }
    else if(player.getPlayerState()==1){
        player.pauseVideo();
        $("#playbutton").removeClass();
        $("#playbutton").addClass('ic-button fa fa-play');
    }

}

// This function checks if the specified event is supported by the browser.
// Source: http://perfectionkills.com/detecting-event-support-without-browser-sniffing/
function isEventSupported(eventName) {
    var el = document.createElement('div');
    eventName = 'on' + eventName;
    var isSupported = (eventName in el);
    if (!isSupported) {
        el.setAttribute(eventName, 'return;');
        isSupported = typeof el[eventName] == 'function';
    }
    el = null;
    return isSupported;
}

$(document).ready(function() {
    // Check which wheel event is supported. Don't use both as it would fire each event
    // in browsers where both events are supported.
    var wheelEvent = isEventSupported('mousewheel') ? 'mousewheel' : 'wheel';

    // Now bind the event to the desired element
    $('#veil').on(wheelEvent, function(e) {
        var oEvent = e.originalEvent,
            delta  = oEvent.deltaY || oEvent.wheelDelta;

        // deltaY for wheel event
        // wheelData for mousewheel event

        if (delta > 0) {
            channelDown();
        } else {
            channelUp();
        }
    });
});

function playVideo (video) {
    $("#info").hide();
    if(video)
        lastFetchedChannel=video.channel;
      player = new YT.Player('player', {
      height: $(window).height(),
      width: $(window).width(),
      videoId: video.id,
      playerVars: {
             'controls': 0,
             'rel' : 0,
             'showinfo':0,
             'iv_load_policy':3,
             'autoplay': 1,
      },
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
    showInfo(video);
}

function openInYouTube (id) {
    player.pauseVideo();
    var time = Math.floor(player.getCurrentTime());
    if(time/60>0)
        time=Math.floor(time/60)+"m"+(time%60)+"s";
    window.open("http://www.youtube.com/watch?t="+time+"&v="+id, "_blank");
}

function showInfo (video) {
    try{clearTimeout(infoShowTimeOut);}catch(e){}
    infoShowTimeOut=setTimeout(function() { $("#info").show(); },100);
    $('#title').html(video.title);
    // &nbsp&nbsp
    // un pinning ui
    $('#desc').html('&nbsp&nbsp\
        &nbsp·\
        &nbsp&nbsp&nbsp\
        &nbsp&nbsp\
         · /r/\
        '+video.channel+" · /u/"+video.author+' ·  '+video.score);
    $("#infolink").attr("href", "http://www.reddit.com"+video.permalink);
}<|endoftext|>


<commit_before>/**
 * Module: rem - v1.2.5
 * Description: A polyfill to parse CSS links and rewrite pixel equivalents into head for non supporting browsers
 * Date Built: 2014-06-26
 * Copyright (c) 2014  | Chuck Carpenter <chuck.carpenter@me.com>,Lucas Serven <lserven@gmail.com>;
**/
!function(e){"use strict";var t=function(){var e=document.createElement("div");return e.style.cssText="font-size: 1rem;",/rem/.test(e.style.fontSize)},n=function(){for(var e=document.getElementsByTagName("link"),t=[],n=0;n<e.length;n++)"stylesheet"===e[n].rel.toLowerCase()&&null===e[n].getAttribute("data-norem")&&t.push(e[n].href);return t},r=function(){0===m.length&&(m=n());for(var e=0;e<m.length;e++)l(m[e],o,m[e],e)},o=function(e,t){if(v.push(e.responseText),y.push(t),y.length===m.length){for(var n=0;n<y.length;n++)a(v[n],y[n]);(m=f.slice(0)).length>0?(y=[],v=[],f=[],r()):i()}},a=function(e,t){for(var n,r=u(e).replace(/\/\*[\s\S]*?\*\//g,""),o=/[\w\d\s\-\/\\\[\]:,.'"*()<>+~%#^$_=|@]+\{[\w\d\s\-\/\\%#:!;,.'"*()]+\d*\.?\d+rem[\w\d\s\-\/\\%#:!;,.'"*()]*\}/g,a=r.match(o),i=/\d*\.?\d+rem/g,s=r.match(i),c=/(.*\/)/,l=c.exec(t)[0],d=/@import (?:url\()?['"]?([^'\)"]*)['"]?\)?[^;]*/gm;null!==(n=d.exec(e));)f.push(l+n[1]);null!==a&&0!==a.length&&(g=g.concat(a),p=p.concat(s))},i=function(){for(var e=/[\w\d\s\-\/\\%#:,.'"*()]+\d*\.?\d+rem[\w\d\s\-\/\\%#:!,.'"*()]*[;}]/g,t=0;t<g.length;t++){h+=g[t].substr(0,g[t].indexOf("{")+1);for(var n=g[t].match(e),r=0;r<n.length;r++)h+=n[r],r===n.length-1&&"}"!==h[h.length-1]&&(h+="\n}")}s()},s=function(){for(var e=0;e<p.length;e++)w[e]=Math.round(parseFloat(p[e].substr(0,p[e].length-3)*b))+"px";c()},c=function(){for(var e=0;e<w.length;e++)w[e]&&(h=h.replace(p[e],w[e]));var t=document.createElement("style");t.setAttribute("type","text/css"),t.id="remReplace",document.getElementsByTagName("head")[0].appendChild(t),t.styleSheet?t.styleSheet.cssText=h:t.appendChild(document.createTextNode(h))},l=function(t,n,r){try{var o=e.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP")||new ActiveXObject("Msxml2.XMLHTTP"):new XMLHttpRequest;o.open("GET",t,!0),o.onreadystatechange=function(){4===o.readyState&&n(o,r)},o.send(null)}catch(a){if(e.XDomainRequest){var i=new XDomainRequest;i.open("get",t),i.onload=function(){n(i,r)},i.onerror=function(){return!1},i.send()}}},d=function(){return e.matchMedia||e.msMatchMedia?!0:!1},u=function(e){return d()||(e=e.replace(/@media[\s\S]*?\}\s*\}/g,"")),e};if(!t()){var h="",m=[],f=[],g=[],p=[],v=[],y=[],w=[],b="";b=function(){var e,t=document,n=t.documentElement,r=t.body||t.createElement("body"),o=!t.body,a=t.createElement("div"),i=r.style.fontSize;return o&&n.appendChild(r),a.style.cssText="width:1em; position:absolute; visibility:hidden; padding: 0;",r.style.fontSize="1em",r.appendChild(a),e=a.offsetWidth,o?n.removeChild(r):(r.removeChild(a),r.style.fontSize=i),e}(),r()}}(window);
<commit_msg>Update rem.min.js<commit_after>/**
 * Module: rem - v1.2.5
 * Description: A polyfill to parse CSS links and rewrite pixel equivalents into head for non supporting browsers
 * Date Built: 2014-06-26
 * Copyright (c) 2014  | Chuck Carpenter <chuck.carpenter@me.com>,Lucas Serven <lserven@gmail.com>;
**/
!function(e){"use strict";var t=function(){var e=document.createElement("div");return e.style.cssText="font-size: 1rem;",/rem/.test(e.style.fontSize)},n=function(){for(var e=document.getElementsByTagName("link"),t=[],n=0;n<e.length;n++)"stylesheet"===e[n].rel.toLowerCase()&&null===e[n].getAttribute("data-norem")&&t.push(e[n].href);return t},r=function(){for(var e=0;e<h.length;e++)l(h[e],o)},o=function(e,t){if(p.push(e.responseText),v.push(t),v.length===h.length){for(var n=0;n<v.length;n++)a(p[n],v[n]);(h=m.slice(0)).length>0?(v=[],p=[],m=[],r()):s()}},a=function(e,t){for(var n,r=d(e).replace(/\/\*[\s\S]*?\*\//g,""),o=/[\w\d\s\-\/\\\[\]:,.'"*()<>+~%#^$_=|@]+\{[\w\d\s\-\/\\%#:!;,.'"*()]+\d*\.?\d+rem[\w\d\s\-\/\\%#:!;,.'"*()]*\}/g,a=r.match(o),s=/\d*\.?\d+rem/g,i=r.match(s),c=/(.*\/)/,l=c.exec(t)[0],u=/@import (?:url\()?['"]?([^'\)"]*)['"]?\)?[^;]*/gm;null!==(n=u.exec(e));)m.push(l+n[1]);null!==a&&0!==a.length&&(f=f.concat(a),g=g.concat(i))},s=function(){for(var e=/[\w\d\s\-\/\\%#:,.'"*()]+\d*\.?\d+rem[\w\d\s\-\/\\%#:!,.'"*()]*[;}]/g,t=0;t<f.length;t++){u+=f[t].substr(0,f[t].indexOf("{")+1);for(var n=f[t].match(e),r=0;r<n.length;r++)u+=n[r],r===n.length-1&&"}"!==u[u.length-1]&&(u+="\n}")}i()},i=function(){for(var e=0;e<g.length;e++)y[e]=Math.round(parseFloat(g[e].substr(0,g[e].length-3)*w))+"px";c()},c=function(){for(var e=0;e<y.length;e++)y[e]&&(u=u.replace(g[e],y[e]));var t=document.createElement("style");t.setAttribute("type","text/css"),t.id="remReplace",document.getElementsByTagName("head")[0].appendChild(t),t.styleSheet?t.styleSheet.cssText=u:t.appendChild(document.createTextNode(u))},l=function(t,n){try{var r=e.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP")||new ActiveXObject("Msxml2.XMLHTTP"):new XMLHttpRequest;r.open("GET",t,!0),r.onreadystatechange=function(){4===r.readyState&&n(r,t)},r.send(null)}catch(o){if(e.XDomainRequest){var a=new XDomainRequest;a.open("get",t),a.onload=function(){n(a,t)},a.onerror=function(){return!1},a.send()}}},d=function(t){return e.matchMedia||e.msMatchMedia||(t=t.replace(/@media[\s\S]*?\}\s*\}/g,"")),t};if(!t()){var u="",h=n(),m=[],f=[],g=[],p=[],v=[],y=[],w="";w=function(){var e,t=document,n=t.documentElement,r=t.body||t.createElement("body"),o=!t.body,a=t.createElement("div"),s=r.style.fontSize;return o&&n.appendChild(r),a.style.cssText="width:1em; position:absolute; visibility:hidden; padding: 0;",r.style.fontSize="1em",r.appendChild(a),e=a.offsetWidth,o?n.removeChild(r):(r.removeChild(a),r.style.fontSize=s),e}(),r()}}(window);
<|endoftext|>


<commit_before>var mostPopularTemplateSrc = $("#most-popular-template").html();
var mostPopularTemplate = Handlebars.compile(mostPopularTemplateSrc);

var getSmasherPopularity = function (callback) {
	$.getJSON("http://fantasysmashbros.com/popular/popular.json", callback);
};

var renderPopularity = function (data) {
	var game = $("input[type=radio][name=game]:checked").val();
	var lastUpdated = data.lastUpdated;
	var pops = data[game];
	var numParticipants = pops.numParticipants;
	var freqs = pops.freqs;
	freqs.forEach(function (player) {
		player.scoreSpread = calculateScoreSpread(player.popularity);
	});
	var context = {numParticipants: numParticipants, freqs: freqs, lastUpdated: lastUpdated};
	var renderedTemplate = mostPopularTemplate(context);
    $("#most-popular-view").html(renderedTemplate);
    var mp = $("#most-popular");
    attachToggleListenersNoBtn(mp);
    adjustPageHeight();
};

var outcomesTemplateSrc = $("#outcomes-template").html();
var outcomesTemplate = Handlebars.compile(outcomesTemplateSrc);

var getStandings = function (game, playerData, callback) {
	var BASEURL = "https://raw.githubusercontent.com/andrewyang96/FantasySmashBros/master/outcome/";
	$.getJSON(BASEURL + game + ".json", function (data) {
		callback(data, playerData);
	});
};

var renderStandings = function (data, playerData) {
	var playerObjs = [];
	var game = $("input[type=radio][name=game]:checked").val();
	// Convert array of IDs to playerObjs
	data.forEachDone(function (key, i, arr, done) {
        var playerObj = playerData[key];
        if (!playerObj.handle) {
            // Assign empty player handle to empty string
            playerObj.handle = "";
        }
        playerObj.id = key;
        // Calculate popularity
        ref.child(game).child("freqs").child(key).once("value", function (snap) {
            var players = snap.val();
            if (players) {
                var numPlayers = Object.keys(players).length;
                playerObj.popularity = round((numPlayers / numParticipants) * 100, 2);
            } else {
                playerObj.popularity = 0;
            }
            playerObj.scoreSpread = calculateScoreSpread(playerObj.popularity);
            playerObjs.push(playerObj);
            done();
        });
    }, this, function () {
        var context = {players: playerObjs};
        var renderedTemplate = outcomesTemplate(context);
        $("#outcomes-view").html(renderedTemplate);
        attachToggleListenersNoBtn($("#outcomes-view"));
        adjustPageHeight();
    });
};

var adjustPageHeight = function () {
    // Reset height first
    $(".col").css({
        height: ""
    });
    var pageHeight = $(document).height();
    $(".col").css({
        height: pageHeight
    });
};

var attachToggleListenersNoBtn = function (olElement) {
    olElement.find("li").each(function () {
        // Store heights beforehand
        $(this).data("fullHeight", $(this).outerHeight());
        var previewEl = $(this).find(".preview");
        var previewRelTop = previewEl.offset().top - $(this).offset().top;
        var previewHeight = previewEl.outerHeight(true);
        $(this).data("previewHeight", previewRelTop + previewHeight);
        $(this).css({
            height: $(this).data("previewHeight")
        });
        // Attach click listener to expand button
        var playerEl = $(this);
        var toggleBtn = $(this).find(".toggle-button");
        toggleBtn.on("click", function () {
            if (playerEl.hasClass("expanded")) {
                // Already expanded, need to shrink
                playerEl.removeClass("expanded");
                $(this).html("▼");
                playerEl.animate({
                    height: playerEl.data("previewHeight")
                }, 200);
            } else {
                // Was shrunk, need to expand
                playerEl.addClass("expanded");
                $(this).html("▲");
                playerEl.animate({
                    height: playerEl.data("fullHeight")
                }, 200);
            }
        });
    });
};

$("#game-choice-form").change(function () {
	var game = $("input[type=radio][name=game]:checked").val();
	getPlayerData(game, function (data) {
		getSmasherPopularity(renderPopularity);
	    getStandings(game, data, renderStandings);
		var ID = getUserID(); // Code stops here if not logged in
		ref.child(game).child("choices").child(ID).once("value", function (snapshot) {
		    var newChoices = snapshot.val();
		    renderChoices(newChoices, data);
		});
	});
});

var getPlayerData = function (game, callback) {
	var BASEURL = "https://raw.githubusercontent.com/andrewyang96/FantasySmashBros/master/data/";
    var url = BASEURL + game + ".json";
    $.getJSON(url, callback);
};

Array.prototype.forEachDone = function(fn, scope, lastfn) {
    for(var i = 0, c = 0, len = this.length; i < len; i++) {
        fn.call(scope, this[i], i, this, function() { // fn should be set up as fn(num, i, arr, done)
            ++c === len && lastfn();
        });
    }
};

function round(num, places) {
    var multiplier = Math.pow(10, places);
    return Math.round(num * multiplier) / multiplier;
}

$(document).ready(function () {
	attemptLogin();
	getSmasherPopularity(renderPopularity);
});<commit_msg>Fix glitches<commit_after>var mostPopularTemplateSrc = $("#most-popular-template").html();
var mostPopularTemplate = Handlebars.compile(mostPopularTemplateSrc);

var getSmasherPopularity = function (callback) {
	$.getJSON("http://fantasysmashbros.com/popular/popular.json", callback);
};

var renderPopularity = function (data) {
	var game = $("input[type=radio][name=game]:checked").val();
	var lastUpdated = data.lastUpdated;
	var pops = data[game];
	var numParticipants = pops.numParticipants;
	var freqs = pops.freqs;
	freqs.forEach(function (player) {
		player.scoreSpread = calculateScoreSpread(player.popularity);
	});
	var context = {numParticipants: numParticipants, freqs: freqs, lastUpdated: lastUpdated};
	var renderedTemplate = mostPopularTemplate(context);
    $("#most-popular-view").html(renderedTemplate);
    var mp = $("#most-popular");
    attachToggleListenersNoBtn(mp);
    adjustPageHeight();
};

var outcomesTemplateSrc = $("#outcomes-template").html();
var outcomesTemplate = Handlebars.compile(outcomesTemplateSrc);

var getStandings = function (game, playerData, callback) {
	var BASEURL = "https://raw.githubusercontent.com/andrewyang96/FantasySmashBros/master/outcome/";
	$.getJSON(BASEURL + game + ".json", function (data) {
		callback(data, playerData);
	});
};

var renderStandings = function (data, playerData) {
	var playerObjs = [];
	var game = $("input[type=radio][name=game]:checked").val();
	ref.child(game).child("participants").once("value", function (snapshot) {
            // First get participants
            var participants = snapshot.val();
            var numParticipants = Infinity;
            if (participants) {
                numParticipants = Object.keys(participants).length;
            }
		// Convert array of IDs to playerObjs
		data.forEachDone(function (key, i, arr, done) {
	        var playerObj = playerData[key];
	        if (!playerObj.handle) {
	            // Assign empty player handle to empty string
	            playerObj.handle = "";
	        }
	        playerObj.id = key;
	        // Calculate popularity
	        ref.child(game).child("freqs").child(key).once("value", function (snap) {
	            var players = snap.val();
	            if (players) {
	                var numPlayers = Object.keys(players).length;
	                playerObj.popularity = round((numPlayers / numParticipants) * 100, 2);
	            } else {
	                playerObj.popularity = 0;
	            }
	            playerObj.scoreSpread = calculateScoreSpread(playerObj.popularity);
	            playerObjs.push(playerObj);
	            done();
	        });
	    }, this, function () {
	        var context = {players: playerObjs};
	        var renderedTemplate = outcomesTemplate(context);
	        $("#outcomes-view").html(renderedTemplate);
	        attachToggleListenersNoBtn($("#outcomes-view"));
	        adjustPageHeight();
	    });
	});
};

var adjustPageHeight = function () {
    // Reset height first
    $(".col").css({
        height: ""
    });
    var pageHeight = $(document).height();
    $(".col").css({
        height: pageHeight
    });
};

var attachToggleListenersNoBtn = function (olElement) {
    olElement.find("li").each(function () {
        // Store heights beforehand
        $(this).data("fullHeight", $(this).outerHeight());
        var previewEl = $(this).find(".preview");
        var previewRelTop = previewEl.offset().top - $(this).offset().top;
        var previewHeight = previewEl.outerHeight(true);
        $(this).data("previewHeight", previewRelTop + previewHeight);
        $(this).css({
            height: $(this).data("previewHeight")
        });
        // Attach click listener to expand button
        var playerEl = $(this);
        var toggleBtn = $(this).find(".toggle-button");
        toggleBtn.on("click", function () {
            if (playerEl.hasClass("expanded")) {
                // Already expanded, need to shrink
                playerEl.removeClass("expanded");
                $(this).html("▼");
                playerEl.animate({
                    height: playerEl.data("previewHeight")
                }, 200);
            } else {
                // Was shrunk, need to expand
                playerEl.addClass("expanded");
                $(this).html("▲");
                playerEl.animate({
                    height: playerEl.data("fullHeight")
                }, 200);
            }
        });
    });
};

$("#game-choice-form").change(function () {
	var game = $("input[type=radio][name=game]:checked").val();
	getPlayerData(game, function (data) {
		getSmasherPopularity(renderPopularity);
	    getStandings(game, data, renderStandings);
		var ID = getUserID(); // Code stops here if not logged in
		ref.child(game).child("choices").child(ID).once("value", function (snapshot) {
		    var newChoices = snapshot.val();
		    renderChoices(newChoices, data);
		});
	});
});

var getPlayerData = function (game, callback) {
	var BASEURL = "https://raw.githubusercontent.com/andrewyang96/FantasySmashBros/master/data/";
    var url = BASEURL + game + ".json";
    $.getJSON(url, callback);
};

Array.prototype.forEachDone = function(fn, scope, lastfn) {
    for(var i = 0, c = 0, len = this.length; i < len; i++) {
        fn.call(scope, this[i], i, this, function() { // fn should be set up as fn(num, i, arr, done)
            ++c === len && lastfn();
        });
    }
};

function round(num, places) {
    var multiplier = Math.pow(10, places);
    return Math.round(num * multiplier) / multiplier;
}

$(document).ready(function () {
	attemptLogin();
	var game = $("input[type=radio][name=game]:checked").val();
	getPlayerData(game, function (data) {
		getSmasherPopularity(renderPopularity);
	    getStandings(game, data, renderStandings);
		var ID = getUserID(); // Code stops here if not logged in
		ref.child(game).child("choices").child(ID).once("value", function (snapshot) {
		    var newChoices = snapshot.val();
		    renderChoices(newChoices, data);
		});
	});
});<|endoftext|>


<commit_before>//TODO investigate the use of a single call to the backend (should be faster but less flexible)

// callback function called to populate the page from the ROOT file
// called when ROOT is ready
function createmyGUI() {
    window.drawings = new Array();
    window.filename = QueryString.result;
    $.getJSON( "../data/ResultsAnalysisReport.json?salt="+makeid(), createGUI);
}

function makeid()
{
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for( var i=0; i < 5; i++ )
        text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text;
}

// actually build the GUI after reading json
function createGUI(data) {
    window.data = data;
    // fill in the combo box
    loadAvailableResults(data);
    // set the filename: 1. from URL (above); 2. from the combo
    if(window.filename === undefined) {
        window.filename = data.SelectedResults[$('#inputFile')[0].selectedIndex][1]
    }
    if(window.filename === "") return;
    // set data-id of the button to the result id
    $('#SAMADhi').attr("data-id", data.SelectedResults[$('#inputFile')[0].selectedIndex][0]["result_id"]);
    // open the ROOT file
    new JSROOT.TFile(window.filename, onFileOpen);
}

// called when the file is open
function onFileOpen(file) {
    window.fileStructure = parseDirectory(file,file,"",buildFileStructure);
    var activeDir = QueryString.dir;
    var histoGrid = $("#histoGrid");
    var renderLocally = [ "TH1F"  ];
    if($("#renderLocal").is(':checked')) {
	    renderLocally.push("TCanvas");
    }
    window.activeDownloads = 1000; // keep track of the callbacks - start with big number, subtract it at the end of the loop
    if(activeDir != undefined) {
        file.ReadDirectory(activeDir,function(dir) {
	    $("#pleasewait").modal();
            dirkeys = dir.fKeys;
            for(var i=0;i<dirkeys.length;i++) {
	        if($.inArray( dirkeys[i].fClassName, renderLocally)!== -1) {
		    window.activeDownloads++;
                    // prepare the html container
		    $('<div/>', {class:"col-lg-3 col-sm-4 col-xs-12"})
			.append($('<div/>',{class:"thumbnail well drawing", id:"drawing_"+dirkeys[i].fName}))
				.appendTo(histoGrid);
		    var element = $("#drawing_"+dirkeys[i].fName);
		    element.height(element.width()*0.75);
                    // draw in it
                    file.ReadObject(activeDir+"/"+dirkeys[i].fName, function(obj) {
			try {
                        	JSROOT.draw("drawing_"+obj.fName, obj, "");
			} catch(err) { } // ignore
			window.drawings["drawing_"+obj.fName] = obj;
			var svgElement = $("#drawing_"+obj.fName+" svg");
			var ratio = svgElement.height()/svgElement.width();
			var padding_tot = Number(svgElement.parent().css("padding-left").replace("px",""))+Number(svgElement.parent().css("padding-right").replace("px",""));
			svgElement.width(svgElement.parent().width()-padding_tot);
			svgElement.height(svgElement.width()*ratio);
			window.activeDownloads--;
	    		if(window.activeDownloads==0) $("#pleasewait").modal("hide"); // if last callback, remove the modal
                    });
		} else if($.inArray( dirkeys[i].fClassName, [ "TCanvas" ]  )!== -1) { // this can be used to all objects not handled by JSROOT
		        window.activeDownloads++;
			encodedfile = encodeURIComponent("/var/www/html/WebAccess/pages/"+window.filename)
			encodedcanvas = encodeURIComponent(activeDir+"/"+dirkeys[i].fName)
			$.ajax({
				url:       "/cgi-bin/getCanvas.py?file="+encodedfile+"&canvas="+encodedcanvas,
				cache:     false,
				dataType:  "text",
				success:   function(result) {
					var element = $('<div/>', {class:"col-lg-3 col-sm-4 col-xs-12"})
						.append($('<div/>',{class:"thumbnail well drawing"})
							.append(result));
					var name = element.find(".drawing").comments().html()
					element.find(".drawing").attr("id","drawing_"+name);
					element.appendTo(histoGrid);
					var svgElement = element.find("svg");
					var ratio = svgElement.height()/svgElement.width();
					var padding_tot = Number(svgElement.parent().css("padding-left").replace("px",""))+Number(svgElement.parent().css("padding-right").replace("px",""));
					svgElement.width(svgElement.parent().width()-padding_tot);
					svgElement.height(svgElement.width()*ratio);
				window.activeDownloads--;
	    			if(window.activeDownloads==0) $("#pleasewait").modal("hide"); // if last callback, remove the modal
				}
			});
	       	}
            }
	    window.activeDownloads -= 1000; // done with the loop. From now on, this contains the #active callbacks.
	    if(window.activeDownloads==0) $("#pleasewait").modal("hide"); // if no more callback, remove the modal
        });
    }
}

// recursively parse the file to build the directory structure
var parseDirectoryCount = 0;
function parseDirectory(dir,file,path, callback) {
	var keys = dir.fKeys;
	var structure = [];
	var lastItem = false;
	for (i = 0; i < keys.length; i++) {
		lastItem = (i===keys.length-1);
		if(keys[i].fClassName=="TDirectory") {
	                parseDirectoryCount++;
			file.ReadObject(path+"/"+keys[i].fName, function(obj) {
				structure.push({ name:obj.dir_name, title:obj.fTitle, content:parseDirectory(obj,file,"/"+obj.dir_name,callback) });
				parseDirectoryCount--;
				if(parseDirectoryCount===0 && lastItem && callback) callback();
			});
		}
	}
	return structure;
}

// once the file has been parsed, build the HTML
function buildFileStructure() {
	window.fileStructure.sort(function(a,b){ return a.name>b.name; });
	$("#fileTree").html($("<li/>").html($("<a/>").attr('href','#').html("ROOT file")));
	generateHtmlTree($("#fileTree").find("li"),window.fileStructure);
	$('#fileTree').treed();
}

// recursive function to convert the structure into HTML
function generateHtmlTree(rootElement,tree){
	// create a <ul> and move in there
	rootElement.append($("<ul/>"));
	rootElement = rootElement.find("ul");
	// for each element, create a <li>.
	for (var i = 0; i < tree.length; i++) {
		// if there are subdirs, call recursively
		if(tree[i].content.length>0) {
			rootElement.append($("<li/>").html(tree[i].title));
			generateHtmlTree(rootElement.find("li").last(),tree[i].content);
		} else {
			rootElement.append($("<li/>").html($("<a/>").attr('href','?result='+encodeURIComponent(window.filename)+"&render="+$("#renderLocal").is(':checked')+'&dir='+tree[i].name).html(tree[i].title)));
		}
	}
}

// load the json with available results
function loadAvailableResults(data) {
	var results = data.SelectedResults;
	var inputs = $("#inputFile");
	for(var i=0;i<results.length;i++){
		inputs.append($("<option/>").html(results[i][0]['path']));
		if(results[i][1]===window.filename) {
			$('#inputFile')[0].selectedIndex = i;
		}
	}
}

$(window).resize(resizeAll);
function resizeAll() {
	if($(".drawing").is(":visible")) {
		var refwidth = $(".drawing").width();
		var refheight = $(".drawing").height();
		var elements = $(".drawing svg");
		for (var i=0;i<elements.size();i++) {
			var ratio = elements.eq(i).width()/elements.eq(i).height();
			elements.eq(i).width(elements.eq(i).parent().width()-10);
			elements.eq(i).height(elements.eq(i).width()/ratio);
			elements.eq(i).parent().height(elements.eq(i).parent().width()/ratio);
		}
	}
	var modal = $("#modal_plot");
	if(modal.is(":visible")){
		var svgElement = $("#modal_plot >svg");
		var ratio = svgElement.height()/svgElement.width();
		var padding_tot = Number(svgElement.parent().css("padding-left").replace("px",""))+Number(svgElement.parent().css("padding-right").replace("px",""));
		svgElement.width(svgElement.parent().width()-padding_tot);
		svgElement.height(svgElement.width()*ratio);
	}
}

// register event handlers
$(function(){
     // sets the toggle to the appropriate value
     $("<input/>").attr("type","checkbox").attr("data-toggle","toggle")
                  .attr("data-width","100%")
                  .attr("data-on","Render canvases using JSROOT")
                  .attr("data-off","Render canvases on the server")
                  .attr("id","renderLocal").prop("checked",QueryString.render==="true").appendTo($("#renderLocalContainer"));
     $("#renderLocal").bootstrapToggle();
     $('#histoGrid').on('dblclick',function(e) {
	 // check that we actually clicked on a plot and get its name
	 var hit = e.target.closest(".drawing");
	 if(hit==null) return;
	 var id = e.target.closest(".drawing").id;
	 var name = id.substring(8,id.length);
	 // prepare the modal window
	 // title
	 $('#myModalLabel').html(name);
	 $('#myModalLabel').attr("drawing",id);
	 // display
	 $("#histoZoom").toggle(400);
	 $("#histoGrid").toggle(400);
	 // wait for the modal to appear before drawing
	 window.setTimeout(drawModal,500);
     });
     $('#histoZoom').on('dblclick',function(e) {
	 // display
	 $("#histoZoom").toggle(400);
	 $("#histoGrid").toggle(400);
	 window.setTimeout(resizeAll,500);
     });
     $('#inputFile').on('change',function(e){
	 var newfilename = window.data.SelectedResults[$('#inputFile')[0].selectedIndex][1];
	 window.location=window.location.origin+window.location.pathname+"?result="+encodeURIComponent(newfilename)+"&render="+$("#renderLocal").is(':checked');
     });
     $('#SAMADhi').click(function(){
        var id = $('#SAMADhi').attr("data-id");
	window.open("http://cp3.irmp.ucl.ac.be/~delaere/level2/SAMADhi/index.php?-table=result&-action=browse&-cursor=0&-skip=0&-limit=30&-mode=list&-recordid=result%3Fresult_id%3D"+id);
     });
     $("#SAMADhi").mouseup(function(){
	$(this).blur();
     });
     $("#renderLocal").change(function(){
       var value = $("#renderLocal").is(':checked');
       $("#fileTree a").each(function(){
        if(value) {
	  this.setAttribute("href",this.getAttribute("href").replace("render=false","render=true"));
	} else {
	  this.setAttribute("href",this.getAttribute("href").replace("render=true","render=false"));
        }
       });
       $("#histoGrid").html("");
       new JSROOT.TFile(window.filename, onFileOpen);
     });
});

// draw the modal window
function drawModal() {
	var id = $('#myModalLabel').attr("drawing");
	$("#modal_plot").html("");
        if(!$("#renderLocal").is(':checked')) {
		// drawback of this method: we cannot interact with the zoomed plot
		$("#"+id+" >svg").clone().appendTo($("#modal_plot"));
		var svgElement = $("#modal_plot >svg");
		var ratio = svgElement.height()/svgElement.width();
		var padding_tot = Number(svgElement.parent().css("padding-left").replace("px",""))+Number(svgElement.parent().css("padding-right").replace("px",""));
		svgElement.width(svgElement.parent().width()-padding_tot);
		svgElement.height(svgElement.width()*ratio);
	} else {
		// slower and uses object stored in memory, but the plot is interactive
		var objModal = window.drawings[id];
		JSROOT.redraw("modal_plot", objModal, "");
        }
}

// decode the URL
var QueryString = function () {
  // This function is anonymous, is executed immediately and
  // the return value is assigned to QueryString!
  var query_string = {};
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
        // If first entry with this name
    if (typeof query_string[pair[0]] === "undefined") {
      query_string[pair[0]] = decodeURIComponent(pair[1]);
        // If second entry with this name
    } else if (typeof query_string[pair[0]] === "string") {
      var arr = [ query_string[pair[0]],decodeURIComponent(pair[1]) ];
      query_string[pair[0]] = arr;
        // If third or later entry with this name
    } else {
      query_string[pair[0]].push(decodeURIComponent(pair[1]));
    }
  }
    return query_string;
}();
<commit_msg>caching of the file structure<commit_after>// callback function called to populate the page from the ROOT file
// called when ROOT is ready
function createmyGUI() {
    window.drawings = new Array();
    window.filename = QueryString.result;
    $.getJSON( "../data/ResultsAnalysisReport.json?salt="+makeid(), createGUI);
}

function makeid()
{
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for( var i=0; i < 5; i++ )
        text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text;
}

// actually build the GUI after reading json
function createGUI(data) {
    window.data = data;
    // fill in the combo box
    loadAvailableResults(data);
    // set the filename: 1. from URL (above); 2. from the combo
    if(window.filename === undefined) {
        window.filename = data.SelectedResults[$('#inputFile')[0].selectedIndex][1]
    }
    if(window.filename === "") return;
    // set data-id of the button to the result id
    $('#SAMADhi').attr("data-id", data.SelectedResults[$('#inputFile')[0].selectedIndex][0]["result_id"]);
    // open the ROOT file
    new JSROOT.TFile(window.filename, onFileOpen);
}

// called when the file is open
function onFileOpen(file) {
    $("#pleasewait").modal();
    try {
	var prevFilename = localStorage.getItem("results_rootFileName");
	if(window.filename === prevFilename) {
		var prevFileStructure = localStorage.getItem("results_fileStructure");
		window.fileStructure = prevFileStructure ? prevFileStructure : parseDirectory(file,file,"",buildFileStructure);
	} else {
    		window.fileStructure = parseDirectory(file,file,"",buildFileStructure);
	}
	localStorage.setItem("results_rootFileName", window.filename);
	localStorage.setItem("results_fileStructure", window.fileStructure);
    } catch(err) { $("#pleasewait").modal("hide"); }
    $("#pleasewait").modal("hide");
    var activeDir = QueryString.dir;
    var histoGrid = $("#histoGrid");
    var renderLocally = [ "TH1F"  ];
    if($("#renderLocal").is(':checked')) {
	    renderLocally.push("TCanvas");
    }
    window.activeDownloads = 1000; // keep track of the callbacks - start with big number, subtract it at the end of the loop
    if(activeDir != undefined) {
        file.ReadDirectory(activeDir,function(dir) {
	    $("#pleasewait").modal();
            dirkeys = dir.fKeys;
            for(var i=0;i<dirkeys.length;i++) {
	        if($.inArray( dirkeys[i].fClassName, renderLocally)!== -1) {
		    window.activeDownloads++;
                    // prepare the html container
		    $('<div/>', {class:"col-lg-3 col-sm-4 col-xs-12"})
			.append($('<div/>',{class:"thumbnail well drawing", id:"drawing_"+dirkeys[i].fName}))
				.appendTo(histoGrid);
		    var element = $("#drawing_"+dirkeys[i].fName);
		    element.height(element.width()*0.75);
                    // draw in it
                    file.ReadObject(activeDir+"/"+dirkeys[i].fName, function(obj) {
			try {
                        	JSROOT.draw("drawing_"+obj.fName, obj, "");
			} catch(err) { } // ignore
			window.drawings["drawing_"+obj.fName] = obj;
			var svgElement = $("#drawing_"+obj.fName+" svg");
			var ratio = svgElement.height()/svgElement.width();
			var padding_tot = Number(svgElement.parent().css("padding-left").replace("px",""))+Number(svgElement.parent().css("padding-right").replace("px",""));
			svgElement.width(svgElement.parent().width()-padding_tot);
			svgElement.height(svgElement.width()*ratio);
			window.activeDownloads--;
	    		if(window.activeDownloads==0) $("#pleasewait").modal("hide"); // if last callback, remove the modal
                    });
		} else if($.inArray( dirkeys[i].fClassName, [ "TCanvas" ]  )!== -1) { // this can be used to all objects not handled by JSROOT
		        window.activeDownloads++;
			encodedfile = encodeURIComponent("/var/www/html/WebAccess/pages/"+window.filename)
			encodedcanvas = encodeURIComponent(activeDir+"/"+dirkeys[i].fName)
			$.ajax({
				url:       "/cgi-bin/getCanvas.py?file="+encodedfile+"&canvas="+encodedcanvas,
				cache:     false,
				dataType:  "text",
				success:   function(result) {
					var element = $('<div/>', {class:"col-lg-3 col-sm-4 col-xs-12"})
						.append($('<div/>',{class:"thumbnail well drawing"})
							.append(result));
					var name = element.find(".drawing").comments().html()
					element.find(".drawing").attr("id","drawing_"+name);
					element.appendTo(histoGrid);
					var svgElement = element.find("svg");
					var ratio = svgElement.height()/svgElement.width();
					var padding_tot = Number(svgElement.parent().css("padding-left").replace("px",""))+Number(svgElement.parent().css("padding-right").replace("px",""));
					svgElement.width(svgElement.parent().width()-padding_tot);
					svgElement.height(svgElement.width()*ratio);
				window.activeDownloads--;
	    			if(window.activeDownloads==0) $("#pleasewait").modal("hide"); // if last callback, remove the modal
				}
			});
	       	}
            }
	    window.activeDownloads -= 1000; // done with the loop. From now on, this contains the #active callbacks.
	    if(window.activeDownloads==0) $("#pleasewait").modal("hide"); // if no more callback, remove the modal
        });
    }
}

// recursively parse the file to build the directory structure
var parseDirectoryCount = 0;
function parseDirectory(dir,file,path, callback) {
	var keys = dir.fKeys;
	var structure = [];
	var lastItem = false;
	for (i = 0; i < keys.length; i++) {
		lastItem = (i===keys.length-1);
		if(keys[i].fClassName=="TDirectory") {
	                parseDirectoryCount++;
			file.ReadObject(path+"/"+keys[i].fName, function(obj) {
				structure.push({ name:obj.dir_name, title:obj.fTitle, content:parseDirectory(obj,file,"/"+obj.dir_name,callback) });
				parseDirectoryCount--;
				if(parseDirectoryCount===0 && lastItem && callback) callback();
			});
		}
	}
	return structure;
}

// once the file has been parsed, build the HTML
function buildFileStructure() {
	window.fileStructure.sort(function(a,b){ return a.name>b.name; });
	$("#fileTree").html($("<li/>").html($("<a/>").attr('href','#').html("ROOT file")));
	generateHtmlTree($("#fileTree").find("li"),window.fileStructure);
	$('#fileTree').treed();
}

// recursive function to convert the structure into HTML
function generateHtmlTree(rootElement,tree){
	// create a <ul> and move in there
	rootElement.append($("<ul/>"));
	rootElement = rootElement.find("ul");
	// for each element, create a <li>.
	for (var i = 0; i < tree.length; i++) {
		// if there are subdirs, call recursively
		if(tree[i].content.length>0) {
			rootElement.append($("<li/>").html(tree[i].title));
			generateHtmlTree(rootElement.find("li").last(),tree[i].content);
		} else {
			rootElement.append($("<li/>").html($("<a/>").attr('href','?result='+encodeURIComponent(window.filename)+"&render="+$("#renderLocal").is(':checked')+'&dir='+tree[i].name).html(tree[i].title)));
		}
	}
}

// load the json with available results
function loadAvailableResults(data) {
	var results = data.SelectedResults;
	var inputs = $("#inputFile");
	for(var i=0;i<results.length;i++){
		inputs.append($("<option/>").html(results[i][0]['path']));
		if(results[i][1]===window.filename) {
			$('#inputFile')[0].selectedIndex = i;
		}
	}
}

$(window).resize(resizeAll);
function resizeAll() {
	if($(".drawing").is(":visible")) {
		var refwidth = $(".drawing").width();
		var refheight = $(".drawing").height();
		var elements = $(".drawing svg");
		for (var i=0;i<elements.size();i++) {
			var ratio = elements.eq(i).width()/elements.eq(i).height();
			elements.eq(i).width(elements.eq(i).parent().width()-10);
			elements.eq(i).height(elements.eq(i).width()/ratio);
			elements.eq(i).parent().height(elements.eq(i).parent().width()/ratio);
		}
	}
	var modal = $("#modal_plot");
	if(modal.is(":visible")){
		var svgElement = $("#modal_plot >svg");
		var ratio = svgElement.height()/svgElement.width();
		var padding_tot = Number(svgElement.parent().css("padding-left").replace("px",""))+Number(svgElement.parent().css("padding-right").replace("px",""));
		svgElement.width(svgElement.parent().width()-padding_tot);
		svgElement.height(svgElement.width()*ratio);
	}
}

// register event handlers
$(function(){
     // sets the toggle to the appropriate value
     $("<input/>").attr("type","checkbox").attr("data-toggle","toggle")
                  .attr("data-width","100%")
                  .attr("data-on","Render canvases using JSROOT")
                  .attr("data-off","Render canvases on the server")
                  .attr("id","renderLocal").prop("checked",QueryString.render==="true").appendTo($("#renderLocalContainer"));
     $("#renderLocal").bootstrapToggle();
     $('#histoGrid').on('dblclick',function(e) {
	 // check that we actually clicked on a plot and get its name
	 var hit = e.target.closest(".drawing");
	 if(hit==null) return;
	 var id = e.target.closest(".drawing").id;
	 var name = id.substring(8,id.length);
	 // prepare the modal window
	 // title
	 $('#myModalLabel').html(name);
	 $('#myModalLabel').attr("drawing",id);
	 // display
	 $("#histoZoom").toggle(400);
	 $("#histoGrid").toggle(400);
	 // wait for the modal to appear before drawing
	 window.setTimeout(drawModal,500);
     });
     $('#histoZoom').on('dblclick',function(e) {
	 // display
	 $("#histoZoom").toggle(400);
	 $("#histoGrid").toggle(400);
	 window.setTimeout(resizeAll,500);
     });
     $('#inputFile').on('change',function(e){
	 var newfilename = window.data.SelectedResults[$('#inputFile')[0].selectedIndex][1];
	 window.location=window.location.origin+window.location.pathname+"?result="+encodeURIComponent(newfilename)+"&render="+$("#renderLocal").is(':checked');
     });
     $('#SAMADhi').click(function(){
        var id = $('#SAMADhi').attr("data-id");
	window.open("http://cp3.irmp.ucl.ac.be/~delaere/level2/SAMADhi/index.php?-table=result&-action=browse&-cursor=0&-skip=0&-limit=30&-mode=list&-recordid=result%3Fresult_id%3D"+id);
     });
     $("#SAMADhi").mouseup(function(){
	$(this).blur();
     });
     $("#renderLocal").change(function(){
       var value = $("#renderLocal").is(':checked');
       $("#fileTree a").each(function(){
        if(value) {
	  this.setAttribute("href",this.getAttribute("href").replace("render=false","render=true"));
	} else {
	  this.setAttribute("href",this.getAttribute("href").replace("render=true","render=false"));
        }
       });
       $("#histoGrid").html("");
       new JSROOT.TFile(window.filename, onFileOpen);
     });
});

// draw the modal window
function drawModal() {
	var id = $('#myModalLabel').attr("drawing");
	$("#modal_plot").html("");
        if(!$("#renderLocal").is(':checked')) {
		// drawback of this method: we cannot interact with the zoomed plot
		$("#"+id+" >svg").clone().appendTo($("#modal_plot"));
		var svgElement = $("#modal_plot >svg");
		var ratio = svgElement.height()/svgElement.width();
		var padding_tot = Number(svgElement.parent().css("padding-left").replace("px",""))+Number(svgElement.parent().css("padding-right").replace("px",""));
		svgElement.width(svgElement.parent().width()-padding_tot);
		svgElement.height(svgElement.width()*ratio);
	} else {
		// slower and uses object stored in memory, but the plot is interactive
		var objModal = window.drawings[id];
		JSROOT.redraw("modal_plot", objModal, "");
        }
}

// decode the URL
var QueryString = function () {
  // This function is anonymous, is executed immediately and
  // the return value is assigned to QueryString!
  var query_string = {};
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
        // If first entry with this name
    if (typeof query_string[pair[0]] === "undefined") {
      query_string[pair[0]] = decodeURIComponent(pair[1]);
        // If second entry with this name
    } else if (typeof query_string[pair[0]] === "string") {
      var arr = [ query_string[pair[0]],decodeURIComponent(pair[1]) ];
      query_string[pair[0]] = arr;
        // If third or later entry with this name
    } else {
      query_string[pair[0]].push(decodeURIComponent(pair[1]));
    }
  }
    return query_string;
}();
<|endoftext|>


<commit_before>/* load given 'page' into the main_content section */
function loadContent(page){

  // - set defoult values for the files we want to load - //
  var content = "";
  var leftPane = "";

  // - set these content
  switch(page){
    case "about":
      content = "pages/about.html";
      break;
    case "project_detail":
      content = "pages/project_detail.html";
      break;
    case "projects":
      content = "pages/parjects.html";
      break;
    default:
      content = "pages/home.html";
  }

  //load selected content into #content section of index.html
  $(document.ready(function(){
    $('#main_content').load(content);
  }));
}

/* load header, navbar, and footer from include files */
function initializeStaticElements(){

  console.log("initializing static elements...");

  $(document).ready(function(){
    $('#main_navbar').load('includes/navbar.html');
    $('#main_footer').load('includes/footer.html');
  });

  console.log("static elements initialized.");
}
<commit_msg>[bugfix] extra ')'<commit_after>/* load given 'page' into the main_content section */
function loadContent(page){

  // - set defoult values for the files we want to load - //
  var content = "";
  var leftPane = "";

  // - set these content
  switch(page){
    case "about":
      content = "pages/about.html";
      break;
    case "project_detail":
      content = "pages/project_detail.html";
      break;
    case "projects":
      content = "pages/parjects.html";
      break;
    default:
      content = "pages/home.html";
  }

  //load selected content into #content section of index.html
  $(document).ready(function(){
    $('#main_content').load(content);
  });
}

/* load header, navbar, and footer from include files */
function initializeStaticElements(){

  console.log("initializing static elements...");

  $(document).ready(function(){
    $('#main_navbar').load('includes/navbar.html');
    $('#main_footer').load('includes/footer.html');
  });

  console.log("static elements initialized.");
}
<|endoftext|>


<commit_before>/*
Copyright (c) 2014 - 2017 David Meyer

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

// Config Vars
const img1            = "img/special.png";
const img2            = "img/special2.png";
const imgElement      = "awesome";        // The element id for the title image.
const audioElement    = "playitagain";
const titleSound      = "sounds/duh.mp3";
const dir             = "sounds/";        // The directory of all the audio clips.
const ext             = ".mp3";
const takes           = 3;                // There are 3 takes for each audio clip.

// Instance Vars
let ip          = "";
let sounds      = new Array();
let curSound    = null;
let START_POINT = -1;
let END_POINT   = -1;

/*
* The main init function, called upon ip retrieval
*/
const main = (json)=> {
    // Getting the IP
    ip = json.ip; //".0123456789"
    END_POINT = ip.length;

    // Set up sounds 0 - 9
    for (let i = 0; i <= 9; i++) {
        // Nested array for random sounds 1 - 3
        sounds[i.toString()] = new Array();
        for (let j = 1; j <= takes; j++) { // Add random sounds 1 - 3 for this digit
            sounds[i.toString()][j] = dir + i + "-" + j + ext;
        }
    }

    // Set up special char sounds
    sounds['.'] = new Array();
    sounds['starting'] = new Array();
    sounds['ending'] = new Array();

    for (let i = 1; i <= takes; i++) {
        sounds['.'][i] = dir + "dot-" + i + ext;
        sounds['starting'][i] = dir + "starting-" + i + ext;
        sounds['ending'][i] = dir + "ending-" + i + ext;
    }
}

/*
* Handles playing audio from specified source.
* Includes onend callback.
*/
const playAudio = (src, onend)=> {
    const audio = document.getElementById(audioElement);
    audio.src = src;
    audio.play();
    audio.onended = ()=> {
        onend();
    };
}

/*
* This function increments through the IP and plays the random associated sounds.
*/
const playIP = (i, onend)=> {
    // If past all the chars in IP, we're done.
    if (i > END_POINT) return;

    // Randomly selected sound file number.
    const rand = Math.floor(Math.random() * takes) + 1;

    // Determine current position in IP.
    switch (i) {
        case START_POINT:
            curSound = sounds['starting'][rand];
            break;
        case END_POINT:
            curSound = sounds['ending'][rand];
            onend();
            break;
        default:
            curSound = sounds[ip.charAt(i)][rand];
    }

    // Begin playing sounds. Iterate on complete.
    playAudio(curSound, playIP.bind(null, i+1, onend));
}

/*
* Switches the two title images.
*/
const switchImg = (playing)=> {
    let currentImage = document.getElementById(imgElement);
    currentImage.src = (playing) ? img2 : img1;
    (playing) ? currentImage.classList.add('animate') : currentImage.classList.remove('animate');
}

/*
* Plays the title sound of the page.
*/
const playTitleSound = ()=> {
    // Is sound already playing? If so, get out of here!
    if (curSound != null && !curSound.ended) return;

    // Change title image to playing state.
    switchImg(true);

    // Play sound and change title image to default state on complete.
    playAudio(titleSound, switchImg.bind(null, false));
}

/*
* Triggered by user action on click.
* Handles switching the title image and playing the IP.
*/
const onButtonClick = ()=> {
    // Is sound already playing? If so, get out of here!
    if (curSound != null && !curSound.ended) return;

    // Change title image to playing state.
    switchImg(true);

    // Play the IP and change title image to default state on complete.
    playIP(START_POINT, switchImg.bind(null, false));
}
<commit_msg>Add a config variable for rocking<commit_after>/*
Copyright (c) 2014 - 2017 David Meyer

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

// Config Vars
const img1            = "img/special.png";
const img2            = "img/special2.png";
const imgElement      = "awesome";        // The element id for the title image.
const audioElement    = "playitagain";
const titleSound      = "sounds/duh.mp3";
const dir             = "sounds/";        // The directory of all the audio clips.
const ext             = ".mp3";
const takes           = 3;                // There are 3 takes for each audio clip.
const rocking         = true;             // Enable or Disable the rocking animation
// Instance Vars
let ip          = "";
let sounds      = new Array();
let curSound    = null;
let START_POINT = -1;
let END_POINT   = -1;

/*
* The main init function, called upon ip retrieval
*/
const main = (json)=> {
    // Getting the IP
    ip = json.ip; //".0123456789"
    END_POINT = ip.length;

    // Set up sounds 0 - 9
    for (let i = 0; i <= 9; i++) {
        // Nested array for random sounds 1 - 3
        sounds[i.toString()] = new Array();
        for (let j = 1; j <= takes; j++) { // Add random sounds 1 - 3 for this digit
            sounds[i.toString()][j] = dir + i + "-" + j + ext;
        }
    }

    // Set up special char sounds
    sounds['.'] = new Array();
    sounds['starting'] = new Array();
    sounds['ending'] = new Array();

    for (let i = 1; i <= takes; i++) {
        sounds['.'][i] = dir + "dot-" + i + ext;
        sounds['starting'][i] = dir + "starting-" + i + ext;
        sounds['ending'][i] = dir + "ending-" + i + ext;
    }
}

/*
* Handles playing audio from specified source.
* Includes onend callback.
*/
const playAudio = (src, onend)=> {
    const audio = document.getElementById(audioElement);
    audio.src = src;
    audio.play();
    audio.onended = ()=> {
        onend();
    };
}

/*
* This function increments through the IP and plays the random associated sounds.
*/
const playIP = (i, onend)=> {
    // If past all the chars in IP, we're done.
    if (i > END_POINT) return;

    // Randomly selected sound file number.
    const rand = Math.floor(Math.random() * takes) + 1;

    // Determine current position in IP.
    switch (i) {
        case START_POINT:
            curSound = sounds['starting'][rand];
            break;
        case END_POINT:
            curSound = sounds['ending'][rand];
            onend();
            break;
        default:
            curSound = sounds[ip.charAt(i)][rand];
    }

    // Begin playing sounds. Iterate on complete.
    playAudio(curSound, playIP.bind(null, i+1, onend));
}

/*
* Switches the two title images.
*/
const switchImg = (playing)=> {
    let currentImage = document.getElementById(imgElement);
    currentImage.src = (playing) ? img2 : img1;
    (playing && rocking) ? currentImage.classList.add('animate') : currentImage.classList.remove('animate');
}

/*
* Plays the title sound of the page.
*/
const playTitleSound = ()=> {
    // Is sound already playing? If so, get out of here!
    if (curSound != null && !curSound.ended) return;

    // Change title image to playing state.
    switchImg(true);

    // Play sound and change title image to default state on complete.
    playAudio(titleSound, switchImg.bind(null, false));
}

/*
* Triggered by user action on click.
* Handles switching the title image and playing the IP.
*/
const onButtonClick = ()=> {
    // Is sound already playing? If so, get out of here!
    if (curSound != null && !curSound.ended) return;

    // Change title image to playing state.
    switchImg(true);

    // Play the IP and change title image to default state on complete.
    playIP(START_POINT, switchImg.bind(null, false));
}
<|endoftext|>


<commit_before>/************************************
* scanner.js
* MIT License (c) 2014 David Leonard
* drksephy.github.io
*************************************/

'use strict';

/**********************
* Scanner constructor *
**********************/

function Scanner(){
    this.tokens     = []
    this.curr_row   = 1
    this.curr_col   = 1
    this.curr_token = ''
    this.curr_val   = '';

}

Scanner.prototype.generateToken = function(tokenName){

    if(this.curr_token){
        var token = {
            'token': tokenName,
            'value': this.curr_val,
            'row'  : this.curr_row,
            'col'  : this.curr_col
        }
        this.tokens.push(token);
    }

    /*
    document.getElementById('tokens').innerHTML += "
";
    document.getElementById('tokens').innerHTML += "" + token.value + "	";
    document.getElementById('tokens').innerHTML += "" + token.value + "	";
    document.getElementById('tokens').innerHTML += "" + token.row + "	";
    document.getElementById('tokens').innerHTML += "" + token.col + "	";
    document.getElementById('tokens').innerHTML += "
";
    */

    return;
}

// Resets values of token
Scanner.prototype.reset = function(){
    this.curr_val = '';
    this.curr_token = '';
    return;
}

// Default printer method
Scanner.prototype.printer = function(){
    console.log("Printer method");
}

// Retrieves value from table
Scanner.prototype.lookup = function(table, key){
    return table[key];
}

// Returns ascii value of character
Scanner.prototype.toAscii = function(char){
    return char.charCodeAt();
}

// Returns lowercase string
Scanner.prototype.toLower = function(char){
    return char.toLowerCase();
}

// Returns uppercase string
Scanner.prototype.toUpper = function(char){
    return char.toUpperCase();
}

// Handles whitespace character
Scanner.prototype.setSpace = function(char){
    // TODO
    return;
}

// Handles comments
Scanner.prototype.setComment = function(char){
    // TODO
    return;
}

// Handles numerical characters
Scanner.prototype.setDigit = function(char){
    // TODO
    return;
}

// Handles newline characters
Scanner.prototype.setLine = function(char){
    // TODO
    return;
}

// Main scanner function
function scan(){
    // Get input text from textarea
    var program = document.getElementById("program").value;
    document.getElementById("demo").innerHTML = program;
    // Initalize scanner
    var scanner = new Scanner();

    // Begin scanning input text
    for(var i = 0; i < program.length; i++){
        character = scanner.toUpper(program[i]);
        ascii = scanner.toAscii(program[i]);

        if(ascii == '10'){
            // Handle case for newline character
            Scanner.setLine(ascii);
        }
        /*
        scanner.curr_col += 1;
        // Check if character is newline or space
        if(scanner.toAscii(program[i]) != '32' && scanner.toAscii(program[i]) != '10'){
            // Build up current token value
            scanner.curr_val += program[i]
        }
        console.log(scanner.curr_val);
        // Check if current token value is a keyword...
        if(scanner.toUpper(scanner.curr_val) in keywords){
            console.log("Hello")
            scanner.generateToken(scanner.lookup(keywords, scanner.toUpper(scanner.curr_val)));
            scanner.curr_val = '';
        }
        if(scanner.toAscii(program[i]) == '10'){
            scanner.curr_row += 1;
        }
        console.log(scanner.toAscii(program[i]));
        // console.log(scanner.curr_val);
        */

    }
    console.log(scanner.tokens);

}

var keywords = {
    'BEGIN'     : 'TK_BEGIN',
    'BREAK'     : 'TK_BREAK',
    'CONST'     : 'TK_CONST',
    'DO'        : 'TK_DO',
    'DOWNTO'    : 'TK_DOWNTO',
    'ELSE'      : 'TK_ELSE',
    'END'       : 'TK_END',
    'END.'      : 'TK_END_CODE',
    'FOR'       : 'TK_FOR',
    'FUNCTION'  : 'TK_FUNCTION',
    'IDENTIFIER': 'TK_IDENTIFIER',
    'IF'        : 'TK_IF',
    'LABEL'     : 'TK_LABEL',
    'PROGRAM'   : 'TK_PROGRAM',
    'REPEAT'    : 'TK_REPEAT',
    'STRING'    : 'TK_STRING',
    'THEN'      : 'TK_THEN',
    'TO'        : 'TK_TO',
    'TYPE'      : 'TK_TYPE',
    'VAR'       : 'TK_VAR',
    'UNTIL'     : 'TK_UNTIL',
    'WHILE'     : 'TK_WHILE',
    'INTEGER'   : 'TK_ID_INTEGER',
    'REAL'      : 'TK_ID_REAL',
    'CHAR'      : 'TK_ID_CHAR',
    'BOOLEAN'   : 'TK_ID_BOOLEAN',
    'OF'        : 'TK_OF'
}

var operators = {
    '+'         : 'TK_PLUS',
    '-'         : 'TK_MINUS',
    '*'         : 'TK_MULT',
    '/'         : 'TK_DIV_FLOAT',
    'DIV'       : 'TK_DIV',
    'MOD'       : 'TK_MOD',
    ':'         : 'TK_COLON',
    '='         : 'TK_EQUALS',
    ':='        : 'TK_ASSIGNMENT',
    '>'         : 'TK_GREATER',
    '<'         : 'TK_LESS',
    '>='        : 'TK_GREATER_EQUALS',
    '<='        : 'TK_LESS_EQUALS',
    '!'         : 'TK_EXCLAMATION',
    '!='        : 'TK_NOT_EQUALS',
    'AND'       : 'TK_AND',
    'XOR'       : 'TK_XOR',
    'OR'        : 'TK_OR',
    'NOT'       : 'TK_NOT',
    ';'         : 'TK_SEMICOLON',
    '('         : 'TK_OPEN_PARENTHESIS',
    ')'         : 'TK_CLOSE_PARENTHESIS',
    '\''        : 'TK_QUOTE',
    '(*'        : 'TK_BEGIN_COMMENT',
    '*)'        : 'TK_END_COMMENT',
    ','         : 'TK_COMMA',
    '~'         : 'TK_RANGE',
    'ARRAY'     : 'TK_ARRAY',
    '['         : 'TK_OPEN_BRACKET',
    ']'         : 'TK_CLOSE_BRACKET'
}

var SYSTEM = {
    'WRITELN'   : 'TK_WRITELN',
    'ABS'       : 'TK_ABS'
}<commit_msg>scanner.js: Updating parameters to generateToken method<commit_after>/************************************
* scanner.js
* MIT License (c) 2014 David Leonard
* drksephy.github.io
*************************************/

'use strict';

/**********************
* Scanner constructor *
**********************/

function Scanner(){
    this.tokens     = []
    this.curr_row   = 1
    this.curr_col   = 1
    this.curr_token = ''
    this.curr_val   = '';

}

Scanner.prototype.generateToken = function(){

    if(this.curr_token){
        var token = {
            'value': this.curr_val,
            'row'  : this.curr_row,
            'col'  : this.curr_col
        }
        this.tokens.push(token);
    }

    /*
    document.getElementById('tokens').innerHTML += "
";
    document.getElementById('tokens').innerHTML += "" + token.value + "	";
    document.getElementById('tokens').innerHTML += "" + token.value + "	";
    document.getElementById('tokens').innerHTML += "" + token.row + "	";
    document.getElementById('tokens').innerHTML += "" + token.col + "	";
    document.getElementById('tokens').innerHTML += "
";
    */

    return;
}

// Resets values of token
Scanner.prototype.reset = function(){
    this.curr_val = '';
    this.curr_token = '';
    return;
}

// Default printer method
Scanner.prototype.printer = function(){
    console.log("Printer method");
}

// Retrieves value from table
Scanner.prototype.lookup = function(table, key){
    return table[key];
}

// Returns ascii value of character
Scanner.prototype.toAscii = function(char){
    return char.charCodeAt();
}

// Returns lowercase string
Scanner.prototype.toLower = function(char){
    return char.toLowerCase();
}

// Returns uppercase string
Scanner.prototype.toUpper = function(char){
    return char.toUpperCase();
}

// Handles whitespace character
Scanner.prototype.setSpace = function(char){
    // TODO
    return;
}

// Handles comments
Scanner.prototype.setComment = function(char){
    // TODO
    return;
}

// Handles numerical characters
Scanner.prototype.setDigit = function(char){
    // TODO
    return;
}

// Handles newline characters
Scanner.prototype.setLine = function(char){
    Scanner.prototype.generateToken
    return;
}

// Main scanner function
function scan(){
    // Get input text from textarea
    var program = document.getElementById("program").value;
    document.getElementById("demo").innerHTML = program;
    // Initalize scanner
    var scanner = new Scanner();

    // Begin scanning input text
    for(var i = 0; i < program.length; i++){
        character = scanner.toUpper(program[i]);
        ascii = scanner.toAscii(program[i]);

        if(ascii == '10'){
            // Handle case for newline character
            Scanner.setLine(ascii);
        }
        /*
        scanner.curr_col += 1;
        // Check if character is newline or space
        if(scanner.toAscii(program[i]) != '32' && scanner.toAscii(program[i]) != '10'){
            // Build up current token value
            scanner.curr_val += program[i]
        }
        console.log(scanner.curr_val);
        // Check if current token value is a keyword...
        if(scanner.toUpper(scanner.curr_val) in keywords){
            console.log("Hello")
            scanner.generateToken(scanner.lookup(keywords, scanner.toUpper(scanner.curr_val)));
            scanner.curr_val = '';
        }
        if(scanner.toAscii(program[i]) == '10'){
            scanner.curr_row += 1;
        }
        console.log(scanner.toAscii(program[i]));
        // console.log(scanner.curr_val);
        */

    }
    console.log(scanner.tokens);

}

var keywords = {
    'BEGIN'     : 'TK_BEGIN',
    'BREAK'     : 'TK_BREAK',
    'CONST'     : 'TK_CONST',
    'DO'        : 'TK_DO',
    'DOWNTO'    : 'TK_DOWNTO',
    'ELSE'      : 'TK_ELSE',
    'END'       : 'TK_END',
    'END.'      : 'TK_END_CODE',
    'FOR'       : 'TK_FOR',
    'FUNCTION'  : 'TK_FUNCTION',
    'IDENTIFIER': 'TK_IDENTIFIER',
    'IF'        : 'TK_IF',
    'LABEL'     : 'TK_LABEL',
    'PROGRAM'   : 'TK_PROGRAM',
    'REPEAT'    : 'TK_REPEAT',
    'STRING'    : 'TK_STRING',
    'THEN'      : 'TK_THEN',
    'TO'        : 'TK_TO',
    'TYPE'      : 'TK_TYPE',
    'VAR'       : 'TK_VAR',
    'UNTIL'     : 'TK_UNTIL',
    'WHILE'     : 'TK_WHILE',
    'INTEGER'   : 'TK_ID_INTEGER',
    'REAL'      : 'TK_ID_REAL',
    'CHAR'      : 'TK_ID_CHAR',
    'BOOLEAN'   : 'TK_ID_BOOLEAN',
    'OF'        : 'TK_OF'
}

var operators = {
    '+'         : 'TK_PLUS',
    '-'         : 'TK_MINUS',
    '*'         : 'TK_MULT',
    '/'         : 'TK_DIV_FLOAT',
    'DIV'       : 'TK_DIV',
    'MOD'       : 'TK_MOD',
    ':'         : 'TK_COLON',
    '='         : 'TK_EQUALS',
    ':='        : 'TK_ASSIGNMENT',
    '>'         : 'TK_GREATER',
    '<'         : 'TK_LESS',
    '>='        : 'TK_GREATER_EQUALS',
    '<='        : 'TK_LESS_EQUALS',
    '!'         : 'TK_EXCLAMATION',
    '!='        : 'TK_NOT_EQUALS',
    'AND'       : 'TK_AND',
    'XOR'       : 'TK_XOR',
    'OR'        : 'TK_OR',
    'NOT'       : 'TK_NOT',
    ';'         : 'TK_SEMICOLON',
    '('         : 'TK_OPEN_PARENTHESIS',
    ')'         : 'TK_CLOSE_PARENTHESIS',
    '\''        : 'TK_QUOTE',
    '(*'        : 'TK_BEGIN_COMMENT',
    '*)'        : 'TK_END_COMMENT',
    ','         : 'TK_COMMA',
    '~'         : 'TK_RANGE',
    'ARRAY'     : 'TK_ARRAY',
    '['         : 'TK_OPEN_BRACKET',
    ']'         : 'TK_CLOSE_BRACKET'
}

var SYSTEM = {
    'WRITELN'   : 'TK_WRITELN',
    'ABS'       : 'TK_ABS'
}<|endoftext|>