<commit_before>'use strict';

function draw(){
    buffer.clearRect(
      0,
      0,
      width,
      height
    );

    // Draw ground grass.
    buffer.fillStyle = '#131';
    buffer.fillRect(
      0,
      floor_position,
      width,
      y
    );

    buffer.fillStyle = split_state[0]
      ? '#323232'
      : '#646464';

    // Precalculate left wall split position.
    var precalc = (splits[0][0] * (1 / splits[0][2])) + x;

    // Draw left wall extra bit.
    if(player_position > 0){
        buffer.fillRect(
          0,
          0,
          1 + (player_position >= precalc ? precalc : player_position),
          height
        );
    }

    // Draw left wall closer than split.
    if(player_position < precalc){
        buffer.beginPath();
        buffer.moveTo(
          player_position,
          y - x
        );
        buffer.lineTo(
          precalc,
          (splits[0][1] * (1 / splits[0][2])) + y
        );
        buffer.lineTo(
          precalc,
          (splits[1][1] * (1 / splits[1][2])) + y
        );
        buffer.lineTo(
          player_position,
          y + x
        );
        buffer.closePath();
        buffer.fill();
    }

    // Draw left wall further than split.
    buffer.fillStyle = split_state[0]
      ? '#646464'
      : '#323232';
    buffer.beginPath();
    buffer.moveTo(
      precalc,
      (splits[0][1] * (1 / splits[0][2])) + y
    );
    buffer.lineTo(
      x,
      y
    );
    buffer.lineTo(
      precalc,
      (splits[1][1] * (1 / splits[1][2])) + y
    );
    buffer.closePath();
    buffer.fill();

    buffer.fillStyle = split_state[0]
      ? '#646464'
      : '#323232';

    // Precalculate right wall split position.
    precalc = (splits[2][0] * (1 / splits[2][2])) + x;

    // Draw right wall extra bit.
    if(player_position < 0){
        buffer.fillRect(
          width + player_position < precalc
            ? precalc - 1
            : width + player_position - 1,
          0,
          -player_position,
          height
        );
    }

    // Draw right wall closer than split.
    if(width + player_position > precalc){
        buffer.beginPath();
        buffer.moveTo(
          width + player_position,
          y - x
        );
        buffer.lineTo(
          precalc,
          (splits[2][1] * (1 / splits[2][2])) + y
        );
        buffer.lineTo(
          precalc,
          (splits[3][1] * (1 / splits[3][2])) + y
        );
        buffer.lineTo(
          width + player_position,
          y + x
        );
        buffer.closePath();
        buffer.fill();
    }

    // Draw right wall further than split.
    buffer.fillStyle = split_state[0]
      ? '#323232'
      : '#646464';

    buffer.beginPath();
    buffer.moveTo(
      precalc,
      (splits[2][1] * (1 / splits[2][2])) + y
    );
    buffer.lineTo(
      x,
      y
    );
    buffer.lineTo(
      precalc,
      (splits[3][1] * (1 / splits[3][2])) + y
    );
    buffer.closePath();
    buffer.fill();

    // If frame counter is enabled, draw current frame count.
    if(settings['frame-counter']){
        buffer.fillStyle = '#fff';
        buffer.font = '23pt sans-serif';
        buffer.fillText(
          frame_counter,
          5,
          25
        );
        buffer.fillText(
          best,
          5,
          50
        );
    }

    canvas.clearRect(
      0,
      0,
      width,
      height
    );
    canvas.drawImage(
      document.getElementById('buffer'),
      0,
      0
    );

    animationFrame = window.requestAnimationFrame(draw);
}

function logic(){
    frame_counter += 1;

    // Get player movement.
    player_dx = 0;
    if(key_left){
        player_dx += x / 20;
    }
    if(key_right){
        player_dx -= x / 20;
    }

    // Update player position.
    player_position += player_dx;

    // Make sure player stays in bounds.
    if(player_position > x / 1.5){
        player_position = x / 1.5;

    }else if(player_position < -x / 1.5){
        player_position = -x / 1.5;
    }

    // Move player forward by moving splits closer.
    for(var id in splits){
        splits[id][2] -= .05;

        // If splits reach player, reset splits.
        if(splits[id][2] < 0){
            splits[id][2] = 25;
            split_state[1] = true;
        }
    }

    // If it is time to reset split.
    if(split_state[1]){
        // Reset player position to start of new section.
        player_position = 0;

        // Switch split.
        split_state[1] = false;
        split_state[0] = !split_state[0];
    }
}

function reset(){
    if(!window.confirm('Reset settings?')){
        return;
    }

    document.getElementById('audio-volume').value = 1;
    document.getElementById('frame-counter').checked = true;
    document.getElementById('movement-keys').value = 'AD';
    document.getElementById('ms-per-frame').value = 25;
    document.getElementById('restart-key').value = 'H';

    save();
}

function reset_best(){
    if(!window.confirm('Reset best?')){
        return;
    }

    best = 0;
    frame_counter = 0;
    update_best();
    setmode(
      0,
      true
    );
}

function resize(){
    if(mode <= 0){
        return;
    }

    height = window.innerHeight;
    document.getElementById('buffer').height = height;
    document.getElementById('canvas').height = height;
    y = height / 2;

    floor_position = y * (mode - 1);

    width = window.innerWidth;
    document.getElementById('buffer').width = width;
    document.getElementById('canvas').width = width;
    x = width / 2;

}

// Save settings into window.localStorage if they differ from default.
function save(){
    if(document.getElementById('audio-volume').value == 1){
        window.localStorage.removeItem('FractalRunner-2D3D.htm-audio-volume');
        settings['audio-volume'] = 1;

    }else{
        settings['audio-volume'] = parseFloat(document.getElementById('audio-volume').value);
        window.localStorage.setItem(
          'FractalRunner-2D3D.htm-audio-volume',
          settings['audio-volume']
        );
    }

    if(document.getElementById('frame-counter').checked){
        window.localStorage.removeItem('FractalRunner-2D3D.htm-frame-counter');
        settings['frame-counter'] = true;

    }else{
        settings['frame-counter'] = false;
        window.localStorage.setItem(
          'FractalRunner-2D3D.htm-frame-counter',
          1
        );
    }

    if(document.getElementById('movement-keys').value == 'AD'){
        window.localStorage.removeItem('FractalRunner-2D3D.htm-movement-keys');
        settings['movement-keys'] = 'AD';

    }else{
        settings['movement-keys'] = document.getElementById('movement-keys').value;
        window.localStorage.setItem(
          'FractalRunner-2D3D.htm-movement-keys',
          settings['movement-keys']
        );
    }

    if(document.getElementById('ms-per-frame').value == 25
      || isNaN(document.getElementById('ms-per-frame').value)
      || document.getElementById('ms-per-frame').value < 1){
        window.localStorage.removeItem('FractalRunner-2D3D.htm-ms-per-frame');
        settings['ms-per-frame'] = 25;

    }else{
        settings['ms-per-frame'] = parseInt(document.getElementById('ms-per-frame').value);
        window.localStorage.setItem(
          'FractalRunner-2D3D.htm-ms-per-frame',
          settings['ms-per-frame']
        );
    }

    if(document.getElementById('restart-key').value === 'H'){
        window.localStorage.removeItem('FractalRunner-2D3D.htm-restart-key');
        settings['restart-key'] = 'H';

    }else{
        settings['restart-key'] = document.getElementById('restart-key').value;
        window.localStorage.setItem(
          'FractalRunner-2D3D.htm-restart-key',
          settings['restart-key']
        );
    }
}

function setmode(newmode, newgame){
    window.cancelAnimationFrame(animationFrame);
    window.clearInterval(interval);

    split_state = [
      false,
      false,
    ];

    mode = newmode;

    // New game mode.
    if(mode > 0){
        splits = [
          [-50, -50, 25],
          [-50, 50, 25],
          [50, -50, 25],
          [50, 50, 25],
        ];

        frame_counter = 0;
        player_dx = 0;
        player_position = 0;

        if(newgame){
            save();

            document.getElementById('page').innerHTML = '<canvas id=canvas></canvas><canvas id=buffer></canvas>';

            buffer = document.getElementById('buffer').getContext('2d');
            canvas = document.getElementById('canvas').getContext('2d');

            resize();
        }

        animationFrame = window.requestAnimationFrame(draw);
        interval = window.setInterval(
          'logic()',
          settings['ms-per-frame']
        );

        return;
    }

    // Main menu mode.
    buffer = 0;
    canvas = 0;

    document.getElementById('page').innerHTML = '

Cling to the Ground
Walled Corridor

Best: '
      + best
      + '
Reset Best

<input disabled style=border:0 value=ESC>Main Menu
<input id=movement-keys maxlength=2 value='
      + settings['movement-keys'] + '>Move ←→
<input id=restart-key maxlength=1 value='
      + settings['restart-key'] + '>Restart

<input id=audio-volume max=1 min=0 step=.01 type=range value='
      + settings['audio-volume'] + '>Audio
<input id=ms-per-frame value='
      + settings['ms-per-frame'] + '>ms/Frame
<input '
      + (settings['frame-counter'] ? 'checked ' : '') + 'id=frame-counter type=checkbox>Frame Counter
Reset Settings

';
}

function update_best(){
    if(frame_counter > best){
        best = frame_counter;
    }

    if(best > 0){
        window.localStorage.setItem(
          'FractalRunner-2D3D.htm-best',
          best
        );

    }else{
        window.localStorage.removeItem('FractalRunner-2D3D.htm-best');
    }
}

var animationFrame = 0;
var best = parseInt(window.localStorage.getItem('FractalRunner-2D3D.htm-best')) || 0;
var buffer = 0;
var canvas = 0;
var floor_position = 0;
var frame_counter = 0;
var height = 0;
var interval = 0;
var key_left = false;
var key_right = false;
var mode = 0;
var player_dx = 0;
var player_position = 0;
var settings = {
  'audio-volume': window.localStorage.getItem('FractalRunner-2D3D.htm-audio-volume') != null
    ? parseFloat(window.localStorage.getItem('FractalRunner-2D3D.htm-audio-volume'))
    : 1,
  'frame-counter': window.localStorage.getItem('FractalRunner-2D3D.htm-frame-counter') === null,
  'movement-keys': window.localStorage.getItem('FractalRunner-2D3D.htm-movement-keys') || 'AD',
  'ms-per-frame': parseFloat(window.localStorage.getItem('FractalRunner-2D3D.htm-ms-per-frame')) || 25,
  'restart-key': window.localStorage.getItem('FractalRunner-2D3D.htm-restart-key') || 'H',
};
var split_state = [];
var splits = [];
var width = 0;
var x = 0;
var y = 0;

window.onkeydown = function(e){
    if(mode <= 0){
        return;
    }

    var key = e.keyCode || e.which;

    // ESC: return to main menu.
    if(key === 27){
        update_best();
        setmode(
          0,
          true
        );
        return;
    }

    key = String.fromCharCode(key);

    if(key === settings['movement-keys'][0]){
        key_left = true;

    }else if(key === settings['movement-keys'][1]){
        key_right = true;

    }else if(key === settings['restart-key']){
        update_best();
        setmode(
          mode,
          false
        );
    }
};

window.onkeyup = function(e){
    var key = String.fromCharCode(e.keyCode || e.which);

    if(key === settings['movement-keys'][0]){
        key_left = false;

    }else if(key === settings['movement-keys'][1]){
        key_right = false;
    }
};

window.onload = function(e){
    setmode(
      0,
      true
    );
};

window.onresize = resize;
<commit_msg>limited scope of player_dx<commit_after>'use strict';

function draw(){
    buffer.clearRect(
      0,
      0,
      width,
      height
    );

    // Draw ground grass.
    buffer.fillStyle = '#131';
    buffer.fillRect(
      0,
      floor_position,
      width,
      y
    );

    buffer.fillStyle = split_state[0]
      ? '#323232'
      : '#646464';

    // Precalculate left wall split position.
    var precalc = (splits[0][0] * (1 / splits[0][2])) + x;

    // Draw left wall extra bit.
    if(player_position > 0){
        buffer.fillRect(
          0,
          0,
          1 + (player_position >= precalc ? precalc : player_position),
          height
        );
    }

    // Draw left wall closer than split.
    if(player_position < precalc){
        buffer.beginPath();
        buffer.moveTo(
          player_position,
          y - x
        );
        buffer.lineTo(
          precalc,
          (splits[0][1] * (1 / splits[0][2])) + y
        );
        buffer.lineTo(
          precalc,
          (splits[1][1] * (1 / splits[1][2])) + y
        );
        buffer.lineTo(
          player_position,
          y + x
        );
        buffer.closePath();
        buffer.fill();
    }

    // Draw left wall further than split.
    buffer.fillStyle = split_state[0]
      ? '#646464'
      : '#323232';
    buffer.beginPath();
    buffer.moveTo(
      precalc,
      (splits[0][1] * (1 / splits[0][2])) + y
    );
    buffer.lineTo(
      x,
      y
    );
    buffer.lineTo(
      precalc,
      (splits[1][1] * (1 / splits[1][2])) + y
    );
    buffer.closePath();
    buffer.fill();

    buffer.fillStyle = split_state[0]
      ? '#646464'
      : '#323232';

    // Precalculate right wall split position.
    precalc = (splits[2][0] * (1 / splits[2][2])) + x;

    // Draw right wall extra bit.
    if(player_position < 0){
        buffer.fillRect(
          width + player_position < precalc
            ? precalc - 1
            : width + player_position - 1,
          0,
          -player_position,
          height
        );
    }

    // Draw right wall closer than split.
    if(width + player_position > precalc){
        buffer.beginPath();
        buffer.moveTo(
          width + player_position,
          y - x
        );
        buffer.lineTo(
          precalc,
          (splits[2][1] * (1 / splits[2][2])) + y
        );
        buffer.lineTo(
          precalc,
          (splits[3][1] * (1 / splits[3][2])) + y
        );
        buffer.lineTo(
          width + player_position,
          y + x
        );
        buffer.closePath();
        buffer.fill();
    }

    // Draw right wall further than split.
    buffer.fillStyle = split_state[0]
      ? '#323232'
      : '#646464';

    buffer.beginPath();
    buffer.moveTo(
      precalc,
      (splits[2][1] * (1 / splits[2][2])) + y
    );
    buffer.lineTo(
      x,
      y
    );
    buffer.lineTo(
      precalc,
      (splits[3][1] * (1 / splits[3][2])) + y
    );
    buffer.closePath();
    buffer.fill();

    // If frame counter is enabled, draw current frame count.
    if(settings['frame-counter']){
        buffer.fillStyle = '#fff';
        buffer.font = '23pt sans-serif';
        buffer.fillText(
          frame_counter,
          5,
          25
        );
        buffer.fillText(
          best,
          5,
          50
        );
    }

    canvas.clearRect(
      0,
      0,
      width,
      height
    );
    canvas.drawImage(
      document.getElementById('buffer'),
      0,
      0
    );

    animationFrame = window.requestAnimationFrame(draw);
}

function logic(){
    frame_counter += 1;

    // Get player movement.
    var player_dx = 0;
    if(key_left){
        player_dx += x / 20;
    }
    if(key_right){
        player_dx -= x / 20;
    }

    // Update player position.
    player_position += player_dx;

    // Make sure player stays in bounds.
    if(player_position > x / 1.5){
        player_position = x / 1.5;

    }else if(player_position < -x / 1.5){
        player_position = -x / 1.5;
    }

    // Move player forward by moving splits closer.
    for(var id in splits){
        splits[id][2] -= .05;

        // If splits reach player, reset splits.
        if(splits[id][2] < 0){
            splits[id][2] = 25;
            split_state[1] = true;
        }
    }

    // If it is time to reset split.
    if(split_state[1]){
        // Reset player position to start of new section.
        player_position = 0;

        // Switch split.
        split_state[1] = false;
        split_state[0] = !split_state[0];
    }
}

function reset(){
    if(!window.confirm('Reset settings?')){
        return;
    }

    document.getElementById('audio-volume').value = 1;
    document.getElementById('frame-counter').checked = true;
    document.getElementById('movement-keys').value = 'AD';
    document.getElementById('ms-per-frame').value = 25;
    document.getElementById('restart-key').value = 'H';

    save();
}

function reset_best(){
    if(!window.confirm('Reset best?')){
        return;
    }

    best = 0;
    frame_counter = 0;
    update_best();
    setmode(
      0,
      true
    );
}

function resize(){
    if(mode <= 0){
        return;
    }

    height = window.innerHeight;
    document.getElementById('buffer').height = height;
    document.getElementById('canvas').height = height;
    y = height / 2;

    floor_position = y * (mode - 1);

    width = window.innerWidth;
    document.getElementById('buffer').width = width;
    document.getElementById('canvas').width = width;
    x = width / 2;

}

// Save settings into window.localStorage if they differ from default.
function save(){
    if(document.getElementById('audio-volume').value == 1){
        window.localStorage.removeItem('FractalRunner-2D3D.htm-audio-volume');
        settings['audio-volume'] = 1;

    }else{
        settings['audio-volume'] = parseFloat(document.getElementById('audio-volume').value);
        window.localStorage.setItem(
          'FractalRunner-2D3D.htm-audio-volume',
          settings['audio-volume']
        );
    }

    if(document.getElementById('frame-counter').checked){
        window.localStorage.removeItem('FractalRunner-2D3D.htm-frame-counter');
        settings['frame-counter'] = true;

    }else{
        settings['frame-counter'] = false;
        window.localStorage.setItem(
          'FractalRunner-2D3D.htm-frame-counter',
          1
        );
    }

    if(document.getElementById('movement-keys').value == 'AD'){
        window.localStorage.removeItem('FractalRunner-2D3D.htm-movement-keys');
        settings['movement-keys'] = 'AD';

    }else{
        settings['movement-keys'] = document.getElementById('movement-keys').value;
        window.localStorage.setItem(
          'FractalRunner-2D3D.htm-movement-keys',
          settings['movement-keys']
        );
    }

    if(document.getElementById('ms-per-frame').value == 25
      || isNaN(document.getElementById('ms-per-frame').value)
      || document.getElementById('ms-per-frame').value < 1){
        window.localStorage.removeItem('FractalRunner-2D3D.htm-ms-per-frame');
        settings['ms-per-frame'] = 25;

    }else{
        settings['ms-per-frame'] = parseInt(document.getElementById('ms-per-frame').value);
        window.localStorage.setItem(
          'FractalRunner-2D3D.htm-ms-per-frame',
          settings['ms-per-frame']
        );
    }

    if(document.getElementById('restart-key').value === 'H'){
        window.localStorage.removeItem('FractalRunner-2D3D.htm-restart-key');
        settings['restart-key'] = 'H';

    }else{
        settings['restart-key'] = document.getElementById('restart-key').value;
        window.localStorage.setItem(
          'FractalRunner-2D3D.htm-restart-key',
          settings['restart-key']
        );
    }
}

function setmode(newmode, newgame){
    window.cancelAnimationFrame(animationFrame);
    window.clearInterval(interval);

    split_state = [
      false,
      false,
    ];

    mode = newmode;

    // New game mode.
    if(mode > 0){
        splits = [
          [-50, -50, 25],
          [-50, 50, 25],
          [50, -50, 25],
          [50, 50, 25],
        ];

        frame_counter = 0;
        player_position = 0;

        if(newgame){
            save();

            document.getElementById('page').innerHTML = '<canvas id=canvas></canvas><canvas id=buffer></canvas>';

            buffer = document.getElementById('buffer').getContext('2d');
            canvas = document.getElementById('canvas').getContext('2d');

            resize();
        }

        animationFrame = window.requestAnimationFrame(draw);
        interval = window.setInterval(
          'logic()',
          settings['ms-per-frame']
        );

        return;
    }

    // Main menu mode.
    buffer = 0;
    canvas = 0;

    document.getElementById('page').innerHTML = '

Cling to the Ground
Walled Corridor

Best: '
      + best
      + '
Reset Best

<input disabled style=border:0 value=ESC>Main Menu
<input id=movement-keys maxlength=2 value='
      + settings['movement-keys'] + '>Move ←→
<input id=restart-key maxlength=1 value='
      + settings['restart-key'] + '>Restart

<input id=audio-volume max=1 min=0 step=.01 type=range value='
      + settings['audio-volume'] + '>Audio
<input id=ms-per-frame value='
      + settings['ms-per-frame'] + '>ms/Frame
<input '
      + (settings['frame-counter'] ? 'checked ' : '') + 'id=frame-counter type=checkbox>Frame Counter
Reset Settings

';
}

function update_best(){
    if(frame_counter > best){
        best = frame_counter;
    }

    if(best > 0){
        window.localStorage.setItem(
          'FractalRunner-2D3D.htm-best',
          best
        );

    }else{
        window.localStorage.removeItem('FractalRunner-2D3D.htm-best');
    }
}

var animationFrame = 0;
var best = parseInt(window.localStorage.getItem('FractalRunner-2D3D.htm-best')) || 0;
var buffer = 0;
var canvas = 0;
var floor_position = 0;
var frame_counter = 0;
var height = 0;
var interval = 0;
var key_left = false;
var key_right = false;
var mode = 0;
var player_position = 0;
var settings = {
  'audio-volume': window.localStorage.getItem('FractalRunner-2D3D.htm-audio-volume') != null
    ? parseFloat(window.localStorage.getItem('FractalRunner-2D3D.htm-audio-volume'))
    : 1,
  'frame-counter': window.localStorage.getItem('FractalRunner-2D3D.htm-frame-counter') === null,
  'movement-keys': window.localStorage.getItem('FractalRunner-2D3D.htm-movement-keys') || 'AD',
  'ms-per-frame': parseFloat(window.localStorage.getItem('FractalRunner-2D3D.htm-ms-per-frame')) || 25,
  'restart-key': window.localStorage.getItem('FractalRunner-2D3D.htm-restart-key') || 'H',
};
var split_state = [];
var splits = [];
var width = 0;
var x = 0;
var y = 0;

window.onkeydown = function(e){
    if(mode <= 0){
        return;
    }

    var key = e.keyCode || e.which;

    // ESC: return to main menu.
    if(key === 27){
        update_best();
        setmode(
          0,
          true
        );
        return;
    }

    key = String.fromCharCode(key);

    if(key === settings['movement-keys'][0]){
        key_left = true;

    }else if(key === settings['movement-keys'][1]){
        key_right = true;

    }else if(key === settings['restart-key']){
        update_best();
        setmode(
          mode,
          false
        );
    }
};

window.onkeyup = function(e){
    var key = String.fromCharCode(e.keyCode || e.which);

    if(key === settings['movement-keys'][0]){
        key_left = false;

    }else if(key === settings['movement-keys'][1]){
        key_right = false;
    }
};

window.onload = function(e){
    setmode(
      0,
      true
    );
};

window.onresize = resize;
<|endoftext|>


<commit_before>/*
#
# i2mx_image_manager.js - v0.1-Alpha
# Apache v2 License
#
*/

window.i2mx.ImageManager = new (function() {
    this.files = [];
    this.activeFiles = 0;

    this.event = {};
    this.event.addFiles = function() {
        var files = i2mx.Elements.fileInput().files;

        for(var i=0; i<files.length; i++) {
            i2mx.ImageManager.add(files[i]);
        }

        i2mx.ImageManager.render();

        i2mx.Elements.fileInput().value = ""; // Reset
    }

    this.event.removeFile = function(clickedButton) {
        var id = parseInt(clickedButton.target.getAttribute("data-image-id"));

        i2mx.ImageManager.files[id] = null; // Delete image
        i2mx.ImageManager.activeFiles--;

        i2mx.ImageManager.render();
    }

    this.event.visualizeFile = function(clickedButton) {
        var id = parseInt(clickedButton.target.getAttribute("data-image-id"));

        var fileReader = new FileReader();
        fileReader.onload = function(e) {
            document.getElementById("i2mx-img_mngr-current-image").src = e.target.result;
            document.getElementById("i2mx-img_mngr-visualize-image-div").style.display = "block";
        }

        fileReader.readAsDataURL(i2mx.ImageManager.files[id]);
    }

    this.event.hideImage = function(clickedButton) {
        var id = parseInt(clickedButton.target.getAttribute("data-image-id"));

        document.getElementById('i2mx-img_mngr-visualize-image-div').style.display = "none";
    }

    this.createImgHTML = function(img, id, ord) {
        // Create "Remove from list" button
        var imgDeleteBtn = document.createElement("input");
        imgDeleteBtn.type = "submit";
        imgDeleteBtn.classList.add("i2mx-img_mngr-remove-item-btn");
        imgDeleteBtn.classList.add("button-as-text");
        imgDeleteBtn.value = "Remove from list"
        imgDeleteBtn.setAttribute("data-image-id", id.toString());

        // Create "View" button
        var imgViewBtn = document.createElement("input");
        imgViewBtn.type = "submit";
        imgViewBtn.classList.add("i2mx-img_mngr-visualize-item-btn");
        imgViewBtn.classList.add("button-as-text");
        imgViewBtn.value = "View"
        imgViewBtn.setAttribute("data-image-id", id.toString());

        var newString = (ord) + " - (id="+id+") " + img.name + " (" +
            imgDeleteBtn.outerHTML + ") (" + imgViewBtn.outerHTML + ")
";

        return newString;
    }

    this.render = function() {
        var fileListEl = i2mx.Elements.imageList()
        var files = this.files;

        if(this.activeFiles == 0) {
            fileListEl.innerHTML = "Oops! There are no files here yet."
            return;
        }

        var newHTML = "";
        var ord = 0;
        for(id=0; id<files.length; id++) {
            if(i2mx.ImageManager.files[id] !== null) {
                var img = i2mx.ImageManager.files[id];
                newHTML += this.createImgHTML(img, id, ++ord)
            }
        }

        fileListEl.innerHTML = newHTML;

        var btns;

        btns = document.getElementsByClassName("i2mx-img_mngr-remove-item-btn");
        for(var id=0, btn; btn=btns[id]; id++) {
            btn.addEventListener("click", this.event.removeFile);
        }

        btns = document.getElementsByClassName("i2mx-img_mngr-visualize-item-btn");
        for(var id=0, btn; btn=btns[id]; id++) {
            btn.addEventListener("click", this.event.visualizeFile);
        }
    }

    this.add = function(file) {
        if(file.type.match('image.*')) {
            this.files.push(file);
            this.activeFiles++;
            return true;
        }

        console.log(file.name + " is not an image file!" + " (" +
            file.type + ")");

        return false;
    }

    this.load = function() {
        i2mx.Elements.addImageBtn().addEventListener("click", this.event.addFiles)
        i2mx.Elements.hideImageBtn().addEventListener("click", this.event.hideImage)
    };
});
<commit_msg>Alert when an non-image file can't be added<commit_after>/*
#
# i2mx_image_manager.js - v0.1-Alpha
# Apache v2 License
#
*/

window.i2mx.ImageManager = new (function() {
    this.files = [];
    this.activeFiles = 0;

    this.event = {};
    this.event.addFiles = function() {
        var files = i2mx.Elements.fileInput().files;

        for(var i=0; i<files.length; i++) {
            i2mx.ImageManager.add(files[i]);
        }

        i2mx.ImageManager.render();

        i2mx.Elements.fileInput().value = ""; // Reset
    }

    this.event.removeFile = function(clickedButton) {
        var id = parseInt(clickedButton.target.getAttribute("data-image-id"));

        i2mx.ImageManager.files[id] = null; // Delete image
        i2mx.ImageManager.activeFiles--;

        i2mx.ImageManager.render();
    }

    this.event.visualizeFile = function(clickedButton) {
        var id = parseInt(clickedButton.target.getAttribute("data-image-id"));

        var fileReader = new FileReader();
        fileReader.onload = function(e) {
            document.getElementById("i2mx-img_mngr-current-image").src = e.target.result;
            document.getElementById("i2mx-img_mngr-visualize-image-div").style.display = "block";
        }

        fileReader.readAsDataURL(i2mx.ImageManager.files[id]);
    }

    this.event.hideImage = function(clickedButton) {
        var id = parseInt(clickedButton.target.getAttribute("data-image-id"));

        document.getElementById('i2mx-img_mngr-visualize-image-div').style.display = "none";
    }

    this.createImgHTML = function(img, id, ord) {
        // Create "Remove from list" button
        var imgDeleteBtn = document.createElement("input");
        imgDeleteBtn.type = "submit";
        imgDeleteBtn.classList.add("i2mx-img_mngr-remove-item-btn");
        imgDeleteBtn.classList.add("button-as-text");
        imgDeleteBtn.value = "Remove from list"
        imgDeleteBtn.setAttribute("data-image-id", id.toString());

        // Create "View" button
        var imgViewBtn = document.createElement("input");
        imgViewBtn.type = "submit";
        imgViewBtn.classList.add("i2mx-img_mngr-visualize-item-btn");
        imgViewBtn.classList.add("button-as-text");
        imgViewBtn.value = "View"
        imgViewBtn.setAttribute("data-image-id", id.toString());

        var newString = (ord) + " - (id="+id+") " + img.name + " (" +
            imgDeleteBtn.outerHTML + ") (" + imgViewBtn.outerHTML + ")
";

        return newString;
    }

    this.render = function() {
        var fileListEl = i2mx.Elements.imageList()
        var files = this.files;

        if(this.activeFiles == 0) {
            fileListEl.innerHTML = "Oops! There are no files here yet."
            return;
        }

        var newHTML = "";
        var ord = 0;
        for(id=0; id<files.length; id++) {
            if(i2mx.ImageManager.files[id] !== null) {
                var img = i2mx.ImageManager.files[id];
                newHTML += this.createImgHTML(img, id, ++ord)
            }
        }

        fileListEl.innerHTML = newHTML;

        var btns;

        btns = document.getElementsByClassName("i2mx-img_mngr-remove-item-btn");
        for(var id=0, btn; btn=btns[id]; id++) {
            btn.addEventListener("click", this.event.removeFile);
        }

        btns = document.getElementsByClassName("i2mx-img_mngr-visualize-item-btn");
        for(var id=0, btn; btn=btns[id]; id++) {
            btn.addEventListener("click", this.event.visualizeFile);
        }
    }

    this.add = function(file) {
        if(file.type.match('image.*')) {
            this.files.push(file);
            this.activeFiles++;
            return true;
        }

        // TODO: Use a "dialog" element if available
        window.alert(file.name + " is not an image file! (MIME type: " + file.type + ")");

        return false;
    }

    this.load = function() {
        i2mx.Elements.addImageBtn().addEventListener("click", this.event.addFiles)
        i2mx.Elements.hideImageBtn().addEventListener("click", this.event.hideImage)
    };
});
<|endoftext|>


<commit_before>export default function sortTags(tags) {
  return tags.slice(0).sort((a, b) => {
    const aPos = a.position();
    const bPos = b.position();

    const aParent = a.parent();
    const bParent = b.parent();

    if (aPos === null && bPos === null) {
      return b.discussionsCount() - a.discussionsCount();
    } else if (bPos === null) {
      return -1;
    } else if (aPos === null) {
      return 1;
    } else if (aParent === bParent) {
      return aPos - bPos;
    } else if (aParent) {
      return aParent === b ? 1 : aParent.position() - bPos;
    } else if (bParent) {
      return bParent === a ? -1 : aPos - bParent.position();
    }

    return 0;
  });
}
<commit_msg>Refactor tag sorting algorithm<commit_after>export default function sortTags(tags) {
  return tags.slice(0).sort((a, b) => {
    const aPos = a.position();
    const bPos = b.position();

    // If they're both secondary tags, sort them by their discussions count,
    // descending.
    if (aPos === null && bPos === null)
      return b.discussionsCount() - a.discussionsCount();

    // If just one is a secondary tag, then the primary tag should
    // come first.
    if (bPos === null) return -1;
    if (aPos === null) return 1;

    // If we've made it this far, we know they're both primary tags. So we'll
    // need to see if they have parents.
    const aParent = a.parent();
    const bParent = b.parent();

    // If they both have the same parent, then their positions are local,
    // so we can compare them directly.
    if (aParent === bParent) return aPos - bPos;

    // If they are both child tags, then we will compare the positions of their
    // parents.
    else if (aParent && bParent)
      return aParent.position() - bParent.position();

    // If we are comparing a child tag with its parent, then we let the parent
    // come first. If we are comparing an unrelated parent/child, then we
    // compare both of the parents.
    else if (aParent)
      return aParent === b ? 1 : aParent.position() - bPos;

    else if (bParent)
      return bParent === a ? -1 : aPos - bParent.position();

    return 0;
  });
}
<|endoftext|>


<commit_before>/**
 * @namespace Lyria
 * Lyria namespace decleration
 */
;(function(window, Lyria, $, undefined) {
  'use strict';

  // Achievement "Singleton": Revealing module pattern
  Lyria.Achievements = function() {
    //Private object "array" stores all achievements
    var array = {},
    // Private
    _localStorageKey,
    // Initializes the achievements object with the some juicy
    initialize = function(localStorageKey) {
      // Saves localStorage key internally
      _localStorageKey = localStorageKey;

      // Loads achievements from local storage if any
      if(window.localStorage) {
        if(window.localStorage[_localStorageKey]) {
          array = JSON.parse(window.localStorage[_localStorageKey]);
        }
      }
    }, register = function(text, description, icon) {
      array[text] = {
        active: false
      };
      if( typeof (description) !== "undefined")
        array[text]["description"] = description;
      if( typeof (icon) !== "undefined")
        array[text]["icon"] = icon;
    }, getCount = function() {
      return Object.keys(array).length;
    },
    /**
     * Gets the number of how many achievements have been unlocked
     *
     * @returns {number} The exact number of unlocked achievements
     */
    getUnlockedCount = function() {
      var count = 0;
      for(var i in array) {
        if(array[i]["active"])
          count++;
      }
      return count;
    },
    /**
     * Lists all achievements in a list of
s
     *
     * @returns {string} The markup for the list
     */
    list = function() {
      // Locked achievements will be shown in a grey-ish color
      var result = "";
      for(var i in array) {
        if(array[i]["active"])
          result += '
' + i + '
' + array[i]["description"] + '

';
        else
          result += '
' + i + '
' + array[i]["description"] + '

';
      }

      return result;
    },
    /**
     * Displays an achievement if it hasn't been displayed yet
     *
     * @param {string} text
     */
    show = function(text) {
      // If someone forget to register an achievement
      if(array[text] === "undefined")
        register(text);

      if(!array[text]["active"]) {
        if(!array[text].icon)
          $('.status.achievement').css("background-image", "url(" + array[text].icon + ")");

        $('.achievement .text').html(text);
        $('.status.achievement').css({
          opacity: 0.0
        }).animate({
          opacity: 1.0,
          bottom: '8px'
        }, 750).delay(2500).animate({
          opacity: 0.0,
          bottom: '-80px'
        }, 750);

        array[text].active = true;
      }

      if(window.localStorage)
        window.localStorage[_localStorageKey] = JSON.stringify(array);
    };

    return {
      initialize: initialize,
      getCount: getCount,
      getUnlockedCount: getUnlockedCount,
      list: list,
      register: register,
      show: show
    };
  }();

})(this, this.Lyria = this.Lyria || {}, this.jQuery);
<commit_msg>AMD-ify achievements file<commit_after>/**
 * @namespace Lyria
 * Lyria namespace decleration
 */
define('lyria/achievements', ['root', 'jquery'], function(root, $) {
  'use strict';

  // Achievement "Singleton": Revealing module pattern
  var Achievements = function() {
    //Private object "array" stores all achievements
    var array = {},
    // Private
    _localStorageKey,
    // Initializes the achievements object with the some juicy
    initialize = function(localStorageKey) {
      // Saves localStorage key internally
      _localStorageKey = localStorageKey;

      // Loads achievements from local storage if any
      if(root.localStorage) {
        if(root.localStorage[_localStorageKey]) {
          array = JSON.parse(root.localStorage[_localStorageKey]);
        }
      }
    }, register = function(text, description, icon) {
      array[text] = {
        active: false
      };
      if( typeof (description) !== "undefined")
        array[text]["description"] = description;
      if( typeof (icon) !== "undefined")
        array[text]["icon"] = icon;
    }, getCount = function() {
      return Object.keys(array).length;
    },
    /**
     * Gets the number of how many achievements have been unlocked
     *
     * @returns {number} The exact number of unlocked achievements
     */
    getUnlockedCount = function() {
      var count = 0;
      for(var i in array) {
        if(array[i]["active"])
          count++;
      }
      return count;
    },
    /**
     * Lists all achievements in a list of
s
     *
     * @returns {string} The markup for the list
     */
    list = function() {
      // Locked achievements will be shown in a grey-ish color
      var result = "";
      for(var i in array) {
        if(array[i]["active"])
          result += '
' + i + '
' + array[i]["description"] + '

';
        else
          result += '
' + i + '
' + array[i]["description"] + '

';
      }

      return result;
    },
    /**
     * Displays an achievement if it hasn't been displayed yet
     *
     * @param {string} text
     */
    show = function(text) {
      // If someone forget to register an achievement
      if(array[text] === "undefined")
        register(text);

      if(!array[text]["active"]) {
        if(!array[text].icon)
          $('.status.achievement').css("background-image", "url(" + array[text].icon + ")");

        $('.achievement .text').html(text);
        $('.status.achievement').css({
          opacity: 0.0
        }).animate({
          opacity: 1.0,
          bottom: '8px'
        }, 750).delay(2500).animate({
          opacity: 0.0,
          bottom: '-80px'
        }, 750);

        array[text].active = true;
      }

      if(root.localStorage)
        root.localStorage[_localStorageKey] = JSON.stringify(array);
    };

    return {
      initialize: initialize,
      getCount: getCount,
      getUnlockedCount: getUnlockedCount,
      list: list,
      register: register,
      show: show
    };
  }();

  return Achievements;
});<|endoftext|>


<commit_before>// =====================================================================
// Simple Datepicker Directive
// ---------------------------
//
// Directive for date picking on textboxes. Just drop a few attributes
// and you're done!!
//
// Depends on JQuery 1.11+ and Moment.js 2.8.3+
//
// By Walter Staeblein .:. 2014 - 2015
// =====================================================================
(function() {

    var sdp_app = angular.module('ngSimpleDatePick', []);

    var sdp_id = 0;
    var isofmt = 'YYYY-MM-DD';

    sdp_app.directive('simpleDatePick', ['$compile', '$document', function($compile, $document) {
        return {
            restrict: 'A',
            require: 'ngModel',
            scope: {
                model: '=ngModel',
                chosendate: '=sdpDate',
                ondateselected: '&sdpOnDateSelected',
                sdpMin: '=',
                sdpMax: '='
            },
            compile: function(element, attributes) {

                var uid;
                var txt = '
' +
                            '
' +
                                '' +
                                '{{ actualDate.format("MMMM") | uppercase }}' +
                                '' +
                                '    ' +
                                '' +
                                '{{ actualDate.format("YYYY") }}' +
                                '' +
                                'x' +
                            '
' +
                            '
' +
                                '
' +
                                    '
' +
                                        '
' +
                                            '{{ dname }}	' +
                                        '
' +
                                    '
' +
                                    '
' +
                                        '
' +
                                            '{{ cell.day }}	' +
                                        '
' +
                                    '
' +
                                '
' +
                            '
' +
                            '
' +
                            '
Hoje
' +
                            '
Limpar
' +
                            '
' +
                        '
';

                return function($scope, element, attr, ngModel) {

                    ngModel.$parsers.push(function(value) {

                        var format = attr.sdpFormat || 'DD/MM/YYYY';

                        if (moment(value).isValid() == true) {
                            return moment(value).format(format);
                        } else {
                            return value;
                        }

                    });

                    sdp_id++;
                    uid = "sdp_id" + sdp_id;
                    txt = txt.replace('$$$', uid);
                    uid = '#' + uid;

                    var format = attr.sdpFormat || 'DD/MM/YYYY';

                    $scope.showFooter = attr.footer == undefined ? true : (attr.footer != '');
                    $scope.today = { disabled: false, date: moment() };

                    $scope.actualDate = moment($scope.model || $scope.chosendate, format);
                    if ($scope.actualDate.isValid() == false) { $scope.actualDate = moment(); }

                    // Compile the html, link it to our scope and append the result to the page's body
                    var linkFn = $compile(txt);
                    var content = linkFn($scope);
                    var body = $document.find('body').eq(0);
                    body.append(content);

                    // Answers the original div or input click event
                    element.on('click', function(evt) {

                        // Calculate the dropdown box's position
                        var elePos = $(element).offset();
                        var top = elePos.top + $(element).outerHeight() + 2;
                        var left = elePos.left;
                        $scope.initialDate = moment($scope.model || $scope.chosendate, format);

                        if (top < 0) { top = 0; }
                        if (left < 0) { left = 0; }

                        // Apply the changes in the current month and render the calendar
                        $scope.$apply(function() {
                            $scope.monthObj = renderMonth($scope.actualDate, $scope.sdpMin, $scope.sdpMax, $scope.initialDate, format);

                            $('.datepick:not(' + uid + ')').hide();

                            $(uid).fadeIn(400).css({ 'top': top, 'left': left });
                            evt.preventDefault();
                        })

                        return false;
                    });

                    // Dismisses the date picker box when the user clicks somewhere else
                    $document.on('click', function($event) { goAway(400); });

                    $scope.clearDate = function() {

                        $scope.model = '';
                        goAway(400);
                    }

                    // Answers a year navigation click
                    $scope.setYear = function(e, val) {
                        e.stopPropagation();
                        $scope.actualDate.add(val, 'y');
                        $scope.monthObj = renderMonth($scope.actualDate, $scope.sdpMin, $scope.sdpMax, $scope.initialDate, format);
                    }

                    // Answers a month navigation click
                    $scope.setMonth = function(e, val) {
                        e.stopPropagation();
                        $scope.actualDate.add(val, 'M');
                        $scope.monthObj = renderMonth($scope.actualDate, $scope.sdpMin, $scope.sdpMax, $scope.initialDate, format);
                    }

                    // Answers a date cell click
                    $scope.setDate = function(e, cell) {

                        e.stopPropagation();

                        if (!cell.disabled) {

                            $scope.$evalAsync(function() {
                                if ($(element).attr('sdp-date')) {
                                    $scope.chosendate = cell.date.format(format);
                                } else {
                                    $scope.model = cell.date.format(format);
                                }

                                if ($scope.ondateselected) {

                                    $scope.ondateselected({ seldate: cell.date.format(format) });
                                }
                            });
                            goAway(400);
                        }
                    }
                }

                // Dismisses the date picker box
                function goAway(speed) {

                    $('.datepick').fadeOut(speed);
                }

                // Renders a month of a year passed in dt.
                // min and max determines which cells can be selected
                // inidate is the date at the box when it was clicked
                // Format is the format in which to show dates
                function renderMonth(dt, min, max, inidate, format) {

                    var ini = moment(dt), m = ini.month(), y = ini.year();
                    var fim = ini.date(0);
                    var counter = ini.add(-ini.weekday(), 'd');

                    var dateObj = {};
                    var lines = [];
                    var wdn = [];
                    var tmp = counter.clone();
                    var idate = '';
                    if (inidate != undefined) { idate = inidate.format(isofmt); }

                    for (var i = 0; i < 7; i++) {
                        wdn.push(tmp.format('ddd').toUpperCase());
                        tmp.add(1, 'd');
                    }

                    if (min || max) {

                        var mindate = moment(min + ' 10:00:00', format + ' HH:mm:SS');
                        if (!mindate.isValid()) { mindate = moment(new Date(1970, 1, 1, 10)); }

                        var maxdate = moment(max + ' 10:00:00', format + ' HH:mm:SS');
                        if (!maxdate.isValid()) { maxdate = moment(new Date(2160, 12, 31, 10)); }
                    }

                    for (var l = 0; l < 6; l++) {

                        var line = [];

                        for (var c = 0; c < 7; c++) {
                            var dis = false;

                            if (min || max) {
                                var adate = counter.format(isofmt);
                                dis = !(adate >= mindate.format(isofmt) && adate <= maxdate.format(isofmt));
                                console.log(adate + ' ==> ' + mindate.format(isofmt));
                            }

                            var ctrfmt = counter.format(isofmt);
                            var obj = { date: counter.clone(),
                                day: counter.date(),
                                outofmonth: (counter.month() != m),
                                disabled: dis,
                                today: (moment().format(isofmt) == ctrfmt),
                                initial: (idate == ctrfmt)
                            };

                            line.push(obj);
                            counter.add(1, 'd');
                        }
                        lines.push(line);
                    }

                    dateObj.dates = lines;
                    dateObj.weekdays = wdn;
                    dateObj.month = m;
                    dateObj.year = y;

                    return dateObj;
                }
            }
        }
    } ]);

} ());
<commit_msg>Update ngSimpleDatePicker.js<commit_after>// =====================================================================
// Simple Datepicker Directive
// ---------------------------
//
// Directive for date picking on textboxes. Just drop a few attributes
// and you're done!!
//
// Depends on JQuery 1.11+ and Moment.js 2.8.3+
//
// By Walter Staeblein .:. 2014 - 2015
// =====================================================================
(function() {

    var sdp_app = angular.module('ngSimpleDatePick', []);

    var sdp_id = 0;
    var isofmt = 'YYYY-MM-DD';

    sdp_app.directive('simpleDatePick', ['$compile', '$document', function($compile, $document) {
        return {
            restrict: 'A',
            require: 'ngModel',
            scope: {
                model: '=ngModel',
                chosendate: '=sdpDate',
                ondateselected: '&sdpOnDateSelected',
                sdpMin: '=',
                sdpMax: '='
            },
            compile: function(element, attributes) {

                var uid;
                var txt = '
' +
                            '
' +
                                '' +
                                '{{ actualDate.format("MMMM") | uppercase }}' +
                                '' +
                                '    ' +
                                '' +
                                '{{ actualDate.format("YYYY") }}' +
                                '' +
                            '
' +
                            '
' +
                                '
' +
                                    '
' +
                                        '
' +
                                            '{{ dname }}	' +
                                        '
' +
                                    '
' +
                                    '
' +
                                        '
' +
                                            '{{ cell.day }}	' +
                                        '
' +
                                    '
' +
                                '
' +
                            '
' +
                            '
' +
                            '
Hoje
' +
                            '
Limpar
' +
                            '
' +
                        '
';

                return function($scope, element, attr, ngModel) {

                    ngModel.$parsers.push(function(value) {

                        var format = attr.sdpFormat || 'DD/MM/YYYY';

                        if (moment(value).isValid() == true) {
                            return moment(value).format(format);
                        } else {
                            return value;
                        }

                    });

                    sdp_id++;
                    uid = "sdp_id" + sdp_id;
                    txt = txt.replace('$$$', uid);
                    uid = '#' + uid;

                    var format = attr.sdpFormat || 'DD/MM/YYYY';

                    $scope.showFooter = attr.footer == undefined ? true : (attr.footer != '');
                    $scope.today = { disabled: false, date: moment() };

                    $scope.actualDate = moment($scope.model || $scope.chosendate, format);
                    if ($scope.actualDate.isValid() == false) { $scope.actualDate = moment(); }

                    // Compile the html, link it to our scope and append the result to the page's body
                    var linkFn = $compile(txt);
                    var content = linkFn($scope);
                    var body = $document.find('body').eq(0);
                    body.append(content);

                    // Answers the original div or input click event
                    element.on('click', function(evt) {

                        // Calculate the dropdown box's position
                        var elePos = $(element).offset();
                        var top = elePos.top + $(element).outerHeight() + 2;
                        var left = elePos.left;
                        $scope.initialDate = moment($scope.model || $scope.chosendate, format);

                        if (top < 0) { top = 0; }
                        if (left < 0) { left = 0; }

                        // Apply the changes in the current month and render the calendar
                        $scope.$apply(function() {
                            $scope.monthObj = renderMonth($scope.actualDate, $scope.sdpMin, $scope.sdpMax, $scope.initialDate, format);

                            $('.datepick:not(' + uid + ')').hide();

                            $(uid).fadeIn(400).css({ 'top': top, 'left': left });
                            evt.preventDefault();
                        })

                        return false;
                    });

                    // Dismisses the date picker box when the user clicks somewhere else
                    $document.on('click', function($event) { goAway(400); });

                    $scope.clearDate = function() {

                        $scope.model = '';
                        goAway(400);
                    }

                    // Answers a year navigation click
                    $scope.setYear = function(e, val) {
                        e.stopPropagation();
                        $scope.actualDate.add(val, 'y');
                        $scope.monthObj = renderMonth($scope.actualDate, $scope.sdpMin, $scope.sdpMax, $scope.initialDate, format);
                    }

                    // Answers a month navigation click
                    $scope.setMonth = function(e, val) {
                        e.stopPropagation();
                        $scope.actualDate.add(val, 'M');
                        $scope.monthObj = renderMonth($scope.actualDate, $scope.sdpMin, $scope.sdpMax, $scope.initialDate, format);
                    }

                    // Answers a date cell click
                    $scope.setDate = function(e, cell) {

                        e.stopPropagation();

                        if (!cell.disabled) {

                            $scope.$evalAsync(function() {
                                if ($(element).attr('sdp-date')) {
                                    $scope.chosendate = cell.date.format(format);
                                } else {
                                    $scope.model = cell.date.format(format);
                                }

                                if ($scope.ondateselected) {

                                    $scope.ondateselected({ seldate: cell.date.format(format) });
                                }
                            });
                            goAway(400);
                        }
                    }
                }

                // Dismisses the date picker box
                function goAway(speed) {

                    $('.datepick').fadeOut(speed);
                }

                // Renders a month of a year passed in dt.
                // min and max determines which cells can be selected
                // inidate is the date at the box when it was clicked
                // Format is the format in which to show dates
                function renderMonth(dt, min, max, inidate, format) {

                    var ini = moment(dt), m = ini.month(), y = ini.year();
                    var fim = ini.date(0);
                    var counter = ini.add(-ini.weekday(), 'd');

                    var dateObj = {};
                    var lines = [];
                    var wdn = [];
                    var tmp = counter.clone();
                    var idate = '';
                    if (inidate != undefined) { idate = inidate.format(isofmt); }

                    for (var i = 0; i < 7; i++) {
                        wdn.push(tmp.format('ddd').toUpperCase());
                        tmp.add(1, 'd');
                    }

                    if (min || max) {

                        var mindate = moment(min + ' 10:00:00', format + ' HH:mm:SS');
                        if (!mindate.isValid()) { mindate = moment(new Date(1970, 1, 1, 10)); }

                        var maxdate = moment(max + ' 10:00:00', format + ' HH:mm:SS');
                        if (!maxdate.isValid()) { maxdate = moment(new Date(2160, 12, 31, 10)); }
                    }

                    for (var l = 0; l < 6; l++) {

                        var line = [];

                        for (var c = 0; c < 7; c++) {
                            var dis = false;

                            if (min || max) {
                                var adate = counter.format(isofmt);
                                dis = !(adate >= mindate.format(isofmt) && adate <= maxdate.format(isofmt));
                                console.log(adate + ' ==> ' + mindate.format(isofmt));
                            }

                            var ctrfmt = counter.format(isofmt);
                            var obj = { date: counter.clone(),
                                day: counter.date(),
                                outofmonth: (counter.month() != m),
                                disabled: dis,
                                today: (moment().format(isofmt) == ctrfmt),
                                initial: (idate == ctrfmt)
                            };

                            line.push(obj);
                            counter.add(1, 'd');
                        }
                        lines.push(line);
                    }

                    dateObj.dates = lines;
                    dateObj.weekdays = wdn;
                    dateObj.month = m;
                    dateObj.year = y;

                    return dateObj;
                }
            }
        }
    } ]);

} ());
<|endoftext|>


<commit_before>/**
 * Simple Carousel
 * HTML Structure:
 * .crsl-items > .crsl-wrap > .crsl-item
 * @author @basilio
 * @version 0.2
 **/

(function($){
	$.fn.carousel = function(args){
		var defaults = {
			infinite : true,
			total : $(this).find('.crsl-item').length,
			visible : 1,
			index : 1,
			speed : 'fast',
			overflow : true,
			autoRotate : false,
			activeClass : 'crsl-active',
			navigationId : $(this).data('navigation'),
			itemWidth : $(this).width(),
			itemMinWidth : 320, // think in mobile!
			itemHeight : false,
			itemHeightEqual : false,
			gutter : 0,
			preventAnimatedQueue : false
		}
		return $(this).each( function(){
			// Set Object
			var obj = this;

			// Extend
			if( $.isEmptyObject(args) == false ) $.extend( defaults, args );

			if( defaults.overflow == true ){
				$(obj).css( { overflow: 'hidden' } );
			} else {
				$('html, body').css( { 'overflow-x': 'hidden' } );
			}
			$(obj).find('.crsl-item').css( { position : 'relative', float : 'left', overflow: 'hidden' } );
			$(obj).find('.crsl-item:first-child').addClass(defaults.activeClass);
			if( defaults.infinite ) $(obj).find('.crsl-item:first-child').before( $('.crsl-item:last-child', obj) );

			// Trigger Carousel Config
			$(window).ready(function(){
				// Config Call
				obj.config(defaults, obj);
				// Begin Carousel
				$(obj).trigger('beginCarousel', [defaults, obj]);
				// Resize End event
				$(window).resize(function(){
					if(this.resizeTO) clearTimeout(this.resizeTO);
					this.resizeTO = setTimeout(function(){
						$(this).trigger('resizeEnd');
					}, 100);
				});
			});

			// Auto Rotate Config
			if( defaults.autoRotate !== false ){
				obj.rotateTime = window.setInterval( function(){
					obj.rotate(defaults, obj);
				}, defaults.autoRotate);
			}

			// Bind ResizeEnd on Window: use for recall obj.config()
			$(window).bind('resizeEnd', function(){
				if( defaults.itemWidth !== $(obj).width() ){
					obj.config(defaults, obj);
				}
			});

			// Click Navigation
			$('#'+defaults.navigationId).delegate('.prev, .next', 'click', function(event){
				// Prevent default
				event.preventDefault();
				// Prepare execute
				obj.execute(defaults, obj, event, this);
				// Previous & next action
				if( $(this).hasClass('prev') && $('.crsl-wrap', obj).find('.crsl-item').index(itemActive) > 0 ){
					obj.previous(defaults, obj, itemActive);
				} else if( $(this).hasClass('next') && ( ( !defaults.infinite && ( (obj.wrapWidth-obj.wrapMargin) == defaults.itemWidth*defaults.total ) ) || ( defaults.infinite ) ) ){
					obj.next(defaults, obj, itemActive);
				}
			});

			// Keypress Navigation
			var overCarouselTest = false;
			$(window).on('mouseover', function(event){
				if (event.target) {
					var current = event.target;
				} else if (event.srcElement) {
					var current = event.srcElement;
				}
				if( $.contains(obj, current) || $(current).parents('.crsl-nav').attr('id') == $(obj).data('navigation') || $(current).parents('.crsl-items').data('navigation') == $(obj).data('navigation') ){
					overCarouselTest = true;
				} else {
					overCarouselTest = false;
				}
				return false;
			});
			$(window).on('keydown', function(event){
				// Prepare execute
				obj.execute(defaults, obj, event, this);
				// Previous & next action
				if( event.keyCode == 37 && overCarouselTest == true ){
					obj.previous(defaults, obj, itemActive);
				} else if( event.keyCode == 39 && overCarouselTest == true ){
					obj.next(defaults, obj, itemActive);
				}
				return;
			});

			// Prepare Execute
			obj.execute = function(defaults, obj, event, $this){
				// Stop rotate
				if( defaults.autoRotate !== false ){
					clearInterval(obj.rotateTime);
				}
				// Prevent Animate Event
				if( defaults.preventAnimatedQueue != false ){
					if( $('.'+defaults.preventAnimatedQueue+':animated').length > 0 ){
						return false;
					}
				}
				// Active
				itemActive = $(obj).find('.crsl-item.'+defaults.activeClass);
			}

			// Base Configuration:
			obj.config = function(defaults, obj){
				/**
				 * TO-DO: set visibleDefault elements to test how many items can be display on crsl-items
				 **/
				// Width Item
				defaults.itemWidth = Math.floor( ( $(obj).width() - defaults.gutter ) / defaults.visible );
				if( defaults.itemWidth <= defaults.itemMinWidth ) defaults.itemWidth = Math.floor( $(obj).width() - defaults.gutter );
				// Set Variables
				obj.wrapWidth = Math.floor( ( defaults.itemWidth + defaults.gutter ) * defaults.total );
				obj.wrapHeight = $(obj).find('.crsl-item').equalHeight(true);
				obj.wrapMargin = obj.wrapMarginDefault = defaults.infinite ? parseInt( ( defaults.itemWidth + defaults.gutter ) * -1 ) : 0 ;
				// Modify Styles
				$(obj).find('.crsl-wrap').css({ width: obj.wrapWidth+'px', height: obj.wrapHeight+'px', marginLeft: obj.wrapMargin });
				$(obj).find('.crsl-item').css({ width: defaults.itemWidth+'px', marginRight : defaults.gutter+'px' });
			}

			// Rotate Action
			obj.rotate = function(defaults, obj){
				// Prevent Animate Event
				if( defaults.preventAnimatedQueue != false ){
					if( $('.'+defaults.preventAnimatedQueue+':animated').length > 0 ){
						return false;
					}
				}
				// Active
				var itemActive = $(obj).find('.crsl-item.'+defaults.activeClass);
				obj.next(defaults, obj, itemActive);
			}

			// Previous Animate
			obj.previous = function(defaults, obj, itemActive){
				obj.wrapMargin = defaults.infinite ? obj.wrapMarginDefault + $(itemActive).outerWidth(true) : obj.wrapMargin + $(itemActive).outerWidth(true);
				var prevItemIndex = $(itemActive).index();
				var newItemActive = $(itemActive).prev('.crsl-item');
				var action = 'previous';
				// Animate
				$(obj).
					find('.crsl-wrap').
					animate({ marginLeft: obj.wrapMargin+'px' }, defaults.speed, function(){
						// Active
						$(itemActive).removeClass(defaults.activeClass);
						$(newItemActive).addClass(defaults.activeClass);
						if( defaults.infinite ){
							$(this).css({ marginLeft: obj.wrapMarginDefault }).find('.crsl-item:first-child').before( $('.crsl-item:last-child', obj) );
						} else {
							if( obj.wrapMargin >= obj.wrapMarginDefault ) $( '#'+defaults.navigationId ).find('.prev').addClass('prev-inactive');
							if( ( obj.wrapWidth - obj.wrapMargin ) == defaults.itemWidth*defaults.total ) $( '#'+defaults.navigationId ).find('.next').removeClass('next-inactive');
						}
					});
				// Trigger Carousel Exec
				$(obj).trigger('endCarousel', [defaults, obj, action]);
			}

			// Next Animate
			obj.next = function(defaults, obj, itemActive){
				obj.wrapMargin = defaults.infinite ? obj.wrapMarginDefault - $(itemActive).outerWidth(true) : obj.wrapMargin - $(itemActive).outerWidth(true);
				var nextItemIndex = $(itemActive).index();
				var newItemActive = $(itemActive).next('.crsl-item');
				var action = 'next';
				// Animate
				$(obj).
					find('.crsl-wrap').
					animate({ marginLeft: obj.wrapMargin+'px' }, defaults.speed, function(){
						// Active
						$(itemActive).removeClass(defaults.activeClass);
						$(newItemActive).addClass(defaults.activeClass);
						if( defaults.infinite ){
							$(this).css({ marginLeft: obj.wrapMarginDefault }).find('.crsl-item:last-child').after( $('.crsl-item:first-child', obj) );
						} else {
							if( obj.wrapMargin < obj.wrapMarginDefault ) $( '#'+defaults.navigationId ).find('.prev').removeClass('prev-inactive');
							if( ( obj.wrapWidth - obj.wrapMargin ) != defaults.itemWidth*defaults.total ) $( '#'+defaults.navigationId ).find('.next').addClass('next-inactive');
						}
					});
				// Trigger Carousel Exec
				$(obj).trigger('endCarousel', [defaults, obj, action]);
			}

			// Function Equal Heights
			$.fn.equalHeight = function(get){
				tallest = 0;
				$(this).each(function(){
					$(this).css({ 'height': 'auto' });
					if ( $(this).innerHeight(true) > tallest ) { tallest = $(this).innerHeight(true); };
				});
				if( get == true ) return tallest;
				else $(this).css({'height': tallest});
			}
		});
	}
})(jQuery);<commit_msg>sync cimmit<commit_after>/**
 * Simple Carousel
 * HTML Structure:
 * .crsl-items > .crsl-wrap > .crsl-item
 * @author @basilio
 * @version 0.2
 **/

(function($){
	$.fn.carousel = function(args){
		var defaults = {
			infinite : true,
			total : $(this).find('.crsl-item').length,
			visible : 1,
			index : 1,
			speed : 'fast',
			overflow : true,
			autoRotate : false,
			activeClass : 'crsl-active',
			navigationId : $(this).data('navigation'),
			itemWidth : $(this).width(),
			itemMinWidth : 320, // think in mobile!
			itemHeight : false,
			itemHeightEqual : false,
			gutter : 0,
			preventAnimatedQueue : false
		}
		return $(this).each( function(){
			// Set Object
			var obj = this;

			// Extend
			if( $.isEmptyObject(args) == false ) $.extend( defaults, args );

			if( defaults.overflow == true ){
				$(obj).css( { overflow: 'hidden' } );
			} else {
				$('html, body').css( { 'overflow-x': 'hidden' } );
			}
			$(obj).find('.crsl-item').css( { position : 'relative', float : 'left', overflow: 'hidden' } );
			$(obj).find('.crsl-item:first-child').addClass(defaults.activeClass);
			if( defaults.infinite ) $(obj).find('.crsl-item:first-child').before( $('.crsl-item:last-child', obj) );
			defaults.visibleDefault = defaults.visible;

			// Trigger Carousel Config
			$(window).ready(function(){
				// Config Call
				obj.config(defaults, obj);
				// Begin Carousel
				$(obj).trigger('beginCarousel', [defaults, obj]);
				// Resize End event
				$(window).resize(function(){
					if(this.resizeTO) clearTimeout(this.resizeTO);
					this.resizeTO = setTimeout(function(){
						$(this).trigger('resizeEnd');
					}, 100);
				});
			});

			// Auto Rotate Config
			if( defaults.autoRotate !== false ){
				obj.rotateTime = window.setInterval( function(){
					obj.rotate(defaults, obj);
				}, defaults.autoRotate);
			}

			// Bind ResizeEnd on Window: use for recall obj.config()
			$(window).bind('resizeEnd', function(){
				if( defaults.itemWidth !== $(obj).width() ){
					obj.config(defaults, obj);
				}
			});

			// Click Navigation
			$('#'+defaults.navigationId).delegate('.prev, .next', 'click', function(event){
				// Prevent default
				event.preventDefault();
				// Prepare execute
				obj.execute(defaults, obj, event, this);
				// Previous & next action
				if( $(this).hasClass('prev') && $('.crsl-wrap', obj).find('.crsl-item').index(itemActive) > 0 ){
					obj.previous(defaults, obj, itemActive);
				} else if( $(this).hasClass('next') && ( ( !defaults.infinite && ( (obj.wrapWidth-obj.wrapMargin) == defaults.itemWidth*defaults.total ) ) || ( defaults.infinite ) ) ){
					obj.next(defaults, obj, itemActive);
				}
			});

			// Keypress Navigation
			var overCarouselTest = false;
			$(window).on('mouseover', function(event){
				if (event.target) {
					var current = event.target;
				} else if (event.srcElement) {
					var current = event.srcElement;
				}
				if( $.contains(obj, current) || $(current).parents('.crsl-nav').attr('id') == $(obj).data('navigation') || $(current).parents('.crsl-items').data('navigation') == $(obj).data('navigation') ){
					overCarouselTest = true;
				} else {
					overCarouselTest = false;
				}
				return false;
			});
			$(window).on('keydown', function(event){
				// Prepare execute
				obj.execute(defaults, obj, event, this);
				// Previous & next action
				if( event.keyCode == 37 && overCarouselTest == true ){
					obj.previous(defaults, obj, itemActive);
				} else if( event.keyCode == 39 && overCarouselTest == true ){
					obj.next(defaults, obj, itemActive);
				}
				return;
			});

			// Prepare Execute
			obj.execute = function(defaults, obj, event, $this){
				// Stop rotate
				if( defaults.autoRotate !== false ){
					clearInterval(obj.rotateTime);
				}
				// Prevent Animate Event
				if( defaults.preventAnimatedQueue != false ){
					if( $('.'+defaults.preventAnimatedQueue+':animated').length > 0 ){
						return false;
					}
				}
				// Active
				itemActive = $(obj).find('.crsl-item.'+defaults.activeClass);
			}

			// Base Configuration:
			obj.config = function(defaults, obj){
				// Width Item
				defaults.itemWidth = Math.floor( ( $(obj).width() - defaults.gutter ) / defaults.visibleDefault );
				if( defaults.itemWidth <= defaults.itemMinWidth ){
					defaults.visible = defaults.visible - 1;
					defaults.itemWidth = Math.floor( ( $(obj).width() - defaults.gutter ) / defaults.visible );
				} else {
					if( defaults.visibleDefault > defaults.visible ){
						defaults.visible = defaults.visible + 1;
						defaults.itemWidth = Math.floor( ( $(obj).width() - defaults.gutter ) / defaults.visible );
					}
				}
				// Set Variables
				obj.wrapWidth = Math.floor( ( defaults.itemWidth + defaults.gutter ) * defaults.total );
				obj.wrapHeight = $(obj).find('.crsl-item').equalHeight(true);
				obj.wrapMargin = obj.wrapMarginDefault = defaults.infinite ? parseInt( ( defaults.itemWidth + defaults.gutter ) * -1 ) : 0 ;
				// Modify Styles
				$(obj).find('.crsl-wrap').css({ width: obj.wrapWidth+'px', height: obj.wrapHeight+'px', marginLeft: obj.wrapMargin });
				$(obj).find('.crsl-item').css({ width: defaults.itemWidth+'px', marginRight : defaults.gutter+'px' });
			}

			// Rotate Action
			obj.rotate = function(defaults, obj){
				// Prevent Animate Event
				if( defaults.preventAnimatedQueue != false ){
					if( $('.'+defaults.preventAnimatedQueue+':animated').length > 0 ){
						return false;
					}
				}
				// Active
				var itemActive = $(obj).find('.crsl-item.'+defaults.activeClass);
				obj.next(defaults, obj, itemActive);
			}

			// Previous Animate
			obj.previous = function(defaults, obj, itemActive){
				obj.wrapMargin = defaults.infinite ? obj.wrapMarginDefault + $(itemActive).outerWidth(true) : obj.wrapMargin + $(itemActive).outerWidth(true);
				var prevItemIndex = $(itemActive).index();
				var newItemActive = $(itemActive).prev('.crsl-item');
				var action = 'previous';
				// Animate
				$(obj).
					find('.crsl-wrap').
					animate({ marginLeft: obj.wrapMargin+'px' }, defaults.speed, function(){
						// Active
						$(itemActive).removeClass(defaults.activeClass);
						$(newItemActive).addClass(defaults.activeClass);
						if( defaults.infinite ){
							$(this).css({ marginLeft: obj.wrapMarginDefault }).find('.crsl-item:first-child').before( $('.crsl-item:last-child', obj) );
						} else {
							if( obj.wrapMargin >= obj.wrapMarginDefault ) $( '#'+defaults.navigationId ).find('.prev').addClass('prev-inactive');
							if( ( obj.wrapWidth - obj.wrapMargin ) == defaults.itemWidth*defaults.total ) $( '#'+defaults.navigationId ).find('.next').removeClass('next-inactive');
						}
					});
				// Trigger Carousel Exec
				$(obj).trigger('endCarousel', [defaults, obj, action]);
			}

			// Next Animate
			obj.next = function(defaults, obj, itemActive){
				obj.wrapMargin = defaults.infinite ? obj.wrapMarginDefault - $(itemActive).outerWidth(true) : obj.wrapMargin - $(itemActive).outerWidth(true);
				var nextItemIndex = $(itemActive).index();
				var newItemActive = $(itemActive).next('.crsl-item');
				var action = 'next';
				// Animate
				$(obj).
					find('.crsl-wrap').
					animate({ marginLeft: obj.wrapMargin+'px' }, defaults.speed, function(){
						// Active
						$(itemActive).removeClass(defaults.activeClass);
						$(newItemActive).addClass(defaults.activeClass);
						if( defaults.infinite ){
							$(this).css({ marginLeft: obj.wrapMarginDefault }).find('.crsl-item:last-child').after( $('.crsl-item:first-child', obj) );
						} else {
							if( obj.wrapMargin < obj.wrapMarginDefault ) $( '#'+defaults.navigationId ).find('.prev').removeClass('prev-inactive');
							if( ( obj.wrapWidth - obj.wrapMargin ) != defaults.itemWidth*defaults.total ) $( '#'+defaults.navigationId ).find('.next').addClass('next-inactive');
						}
					});
				// Trigger Carousel Exec
				$(obj).trigger('endCarousel', [defaults, obj, action]);
			}

			// Function Equal Heights
			$.fn.equalHeight = function(get){
				tallest = 0;
				$(this).each(function(){
					$(this).css({ 'height': 'auto' });
					if ( $(this).innerHeight(true) > tallest ) { tallest = $(this).innerHeight(true); };
				});
				if( get == true ) return tallest;
				else $(this).css({'height': tallest});
			}
		});
	}
})(jQuery);<|endoftext|>


<commit_before>var final_transcript = '';
var recognizing = false;
var recognition;

// reply processing
var two_line = /\n\n/g;
var one_line = /\n/g;
function linebreak(s) {
  return s.replace(two_line, '

').replace(one_line, '
');
}

var first_char = /\S/;
function capitalize(s) {
  return s.replace(first_char, function(m) { return m.toUpperCase(); });
}

function startConverting() {
  if (recognizing) {
    recognition.stop();
    return;
  }
  final_transcript = '';
  recognition.lang = 'en-US';
  recognition.start();
}

function show_result(){
     if(final_transcript.toLowerCase() == 'hello'){
                $('#hello_response').text("Hi! I'm Bhuvanesh")
                $('#hello_response').css('background-color', '#18bc9c');
            }
            else if(final_transcript.toLowerCase() == 'show me your picture'){
                $('#pic_response').append('');
            }
            else if(final_transcript.toLowerCase() == 'show expense report'){
//                 $("#report_img").css("display", "block");
                $('#report_img').animate({bottom: '-100px'});
            }
  final_transcript = "";
}

$( document ).ready(function() {
    if('webkitSpeechRecognition' in window){
        recognition = new webkitSpeechRecognition();
        recognition.continuous = false;
        recognition.interimResults = false;
        recognition.maxAlternatives = 1;

        recognition.onstart = function() {
            recognizing = true;
        };
        recognition.onend = function() {
            recognizing = false;
            recognition.start();

        };
        recognition.onspeechstart = function() {

        };

        recognition.onresult = function(event) {
            var interim_transcript = '';
            if (typeof(event.results) == 'undefined') {
            recognition.onend = null;
            recognition.stop();
            return;
            }
            for (var i = event.resultIndex; i < event.results.length; ++i) {
            if (event.results[i].isFinal) {
                final_transcript += event.results[i][0].transcript;
            } else {
                interim_transcript += event.results[i][0].transcript;
            }
            }
            final_transcript = capitalize(final_transcript);
            show_result();
        };

    }
    startConverting();
});
<commit_msg>Update speech_recognition.js<commit_after>var final_transcript = '';
var recognizing = false;
var recognition;

// reply processing
var two_line = /\n\n/g;
var one_line = /\n/g;
function linebreak(s) {
  return s.replace(two_line, '

').replace(one_line, '
');
}

var first_char = /\S/;
function capitalize(s) {
  return s.replace(first_char, function(m) { return m.toUpperCase(); });
}

function startConverting() {
  if (recognizing) {
    recognition.stop();
    return;
  }
  final_transcript = '';
  recognition.lang = 'en-US';
  recognition.start();
}

function show_result(){
     if(final_transcript.toLowerCase() == 'hello'){
                $('#hello_response').text("Hi! I'm Bhuvanesh")
                $('#hello_response').css('background-color', '#18bc9c');
            }
            else if(final_transcript.toLowerCase() == 'show me your picture'){
                $('#pic_response').append('');
            }
            else if(final_transcript.toLowerCase() == 'show expense report'){
                $("#report_img").css("display", "block");
                $('#report_img').animate({bottom: '-100px'});
            }
  final_transcript = "";
}

$( document ).ready(function() {
    if('webkitSpeechRecognition' in window){
        recognition = new webkitSpeechRecognition();
        recognition.continuous = false;
        recognition.interimResults = false;
        recognition.maxAlternatives = 1;

        recognition.onstart = function() {
            recognizing = true;
        };
        recognition.onend = function() {
            recognizing = false;
            recognition.start();

        };
        recognition.onspeechstart = function() {

        };

        recognition.onresult = function(event) {
            var interim_transcript = '';
            if (typeof(event.results) == 'undefined') {
            recognition.onend = null;
            recognition.stop();
            return;
            }
            for (var i = event.resultIndex; i < event.results.length; ++i) {
            if (event.results[i].isFinal) {
                final_transcript += event.results[i][0].transcript;
            } else {
                interim_transcript += event.results[i][0].transcript;
            }
            }
            final_transcript = capitalize(final_transcript);
            show_result();
        };

    }
    startConverting();
});
<|endoftext|>


<commit_before>var language = navigator.language || navigator.userLanguage;
load_language();

var now = new Date();
var gmt = now.getTimezoneOffset()*60*1000; //gmt in milliseconds
var last1week = new Date(now.getFullYear(),now.getMonth(),now.getDate()-6);
var last2week = new Date(now.getTime() - 2*7*24*60*60*1000);
var last3week = new Date(now.getTime() - 3*7*24*60*60*1000);
var last4week = new Date(now.getTime() - 4*7*24*60*60*1000);

document.getElementById("timezone1").innerHTML = lang("Local time: ") + gmtToString();
document.getElementById("timezone2").innerHTML = lang("Local time: ") + gmtToString();

//Array of Votes and initialization
var votesDay = [0,0,0,0,0,0,0];
var a_votesDay = [0,0,0,0,0,0,0];

var votes = new Array(7);
for(i=0;i<7;i++){
	votes[i] = new Array(24);
	for(j=0;j<24;j++){
		votes[i][j]=0;
	}
}

var a_votes = new Array(7);
for(i=0;i<7;i++){
	a_votes[i] = new Array(24);
	for(j=0;j<24;j++){
		a_votes[i][j]=0;
	}
}

var followersLoaded = 0;
var totalFollowers = 0;
var textFollowers = "";
nameDay = lang("nameDay");
nameHours = ['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23'];

var maxVotation = [0,0,0,0];
var maxVotationDay = 0;
var bestHour = [[0,0],[0,0],[0,0],[0,0]];
var bestDay = 0;
var refreshPlot = 10;
var refreshText = 5;
var firstPlot = true;
var firstText = true;

function loadFollowersActivity(){
	steem.api.getConfig(function(err, response){
		console.log(err, response);
	});

	var account = getQuery();

	steem.api.getAccounts([account], function(err, result){
		console.log(err, result);
		var info = JSON.parse(result[0].json_metadata);
		if(info.profile.hasOwnProperty('profile_image')){
			console.log(info.profile.profile_image + " extracted: " + extractUrlProfileImage(info.profile.profile_image));
			document.getElementById("profile_image").src = extractUrlProfileImage(info.profile.profile_image);
		}else{
			console.log("no photo");
		}
	});

	document.getElementById("labelAccount").innerHTML = "@" + account;
	document.getElementById("title-followers").innerHTML = lang("Followers of @") + account;
	//document.getElementById("title-activity-account").innerHTML = "Activity of @" + account;

	consultVotesAccount(account);

	steem.api.getFollowCount(account, function(err,result) {
		console.log("Number of followers: "+result.follower_count);
		totalFollowers = result.follower_count;
		document.getElementById("title-followers").innerHTML = lang("Followers of @") + account + ": "+totalFollowers;
		consultVotesFollowers(account,0);
	});
}

function consultVotesAccount(account){
	steem.api.getAccountVotes(account, function(err, result) {
		//console.log(err,result);
		//if (err) //error
		//look each vote and put it in the array regarding the time
		for(i=result.length-1;i>=0;i--){
			var timeUTC = new Date(result[i].time);
			var time = new Date(timeUTC.getTime() - gmt);
			if(timeToBreak(time,result.length-i)) break;
			var hours = time.getHours();
			var day = time.getDay();
			a_votes[day][hours]++;
			a_votesDay[day]++;
		}

		for(i=0;i<7;i++){
			var data = [{
				x: nameHours,
				y: a_votes[i],
				type: 'bar'
			}];
			var layout = { title: nameDay[i] };
			Plotly.newPlot('a-chart'+i, data,layout);
			document.getElementById("a-votesDay"+i).innerHTML = nameDay[i]+": "+a_votesDay[i]+lang(" votes");
		}
	});
}

function consultVotesFollowers(account, fromFollower){
	steem.api.getFollowers(account, fromFollower, 0, 21, function(err, result) {

		//look each for each Follower
		var finish = result.length-1;
		if(result.length == 1) finish=1; //last follower

		for(i=0;i<finish;i++){
			if(result[i].what[0] != 'blog') continue;
			textFollowers = textFollowers + link(result[i].follower) + " . . . . ";

			steem.api.getAccountVotes(result[i].follower, function(err, result) {
				//if (err) //error
				//look each vote and put it in the array regarding the time
				for(i=result.length-1;i>=0;i--){
					var timeUTC = new Date(result[i].time);
					var time = new Date(timeUTC.getTime() - gmt);
					if(timeToBreak(time,result.length-i)) break;
					var hours = time.getHours();
					var day = time.getDay();
					votes[day][hours]++;
					votesDay[day]++;
					for(j=0;j<4;j++){
						if(votes[day][hours] > maxVotation[j]){
							maxVotation[j] = votes[day][hours];
							bestHour[j] = [day,hours];
							break;
						}
					}
					if(votesDay[day] > maxVotationDay){
						maxVotationDay = votesDay[day];
						bestDay = day;
					}
				}

				followersLoaded++;

				refreshText--;
				if(firstText || refreshText==0 || followersLoaded==totalFollowers){
					var percentage = 100*followersLoaded/totalFollowers;
					var tPer = percentage.toFixed(2);
					var tBar = followersLoaded + "/" + totalFollowers;
					if(followersLoaded == totalFollowers) tBar = tBar + lang(". Complete");
					document.getElementById("progress-bar").innerHTML = tBar;
					document.getElementById("progress-bar").ariaValuenow = tPer;
					document.getElementById("progress-bar").style = "width: "+tPer+"%;";
					document.getElementById("followers").innerHTML = textFollowers;
					for(i=0;i<4;i++){
						document.getElementById("bestTime"+i).innerHTML = lang("Best Time #")+(i+1)+": " + nameDay[bestHour[i][0]] + lang(" at ") + bestHour[i][1] + " H";
					}
					firstText = false;
					refreshText = 5;
				}

				refreshPlot--;
				if(firstPlot || refreshPlot==0 || followersLoaded==totalFollowers){
					for(i=0;i<7;i++){
						var data = [{
							x: nameHours,
							y: votes[i],
							type: 'bar'
						}];
						var layout = { title: nameDay[i] };
						Plotly.newPlot('f-chart'+i, data,layout);
						document.getElementById("f-votesDay"+i).innerHTML = nameDay[i]+": "+votesDay[i]+lang(" votes");
					}
					firstPlot = false;
					refreshPlot = 10;
				}
			});
		}

		if(result.length>1){
			var lastFollower = result[result.length-1].follower;
			console.log("Consult from "+lastFollower);
			consultVotesFollowers(account, lastFollower);
		}else{
			console.log("Finished");
		}
	});
}

function timeToBreak(time,n){
	if(time < last4week) return true;
	return false;
}

function link(account){
	var url = "https://joticajulian.github.io/steem-activity/index.html";
	return "" + account + "";
}

function getQuery(){
	var kvp = document.location.search.substr(1).split('&');
	var account = '';
	var text = '';
	if(kvp != ''){
		var i = kvp.length;
		var x;
		while (i--) {
			x = kvp[i].split('=');
			if (x[0] == 'account'){
				account = x[1];
			}else if (x[0] == 'lang'){
				language = x[1];
				load_language();
			}
		}
	}
	return account;
}

function searchAccount(){
	var url = "https://joticajulian.github.io/steem-activity/index.html?lang="+language+"&account=" + document.getElementById("input-account").value;
	console.log("opening: "+url);
	window.open(url, "_self");
}

function extractUrlProfileImage(url){
	if(url.substring(0,8) == "![image]"){
		return url.substring(9, url.length - 1);
	}
	return url;
}

function load_language() {
  $(".is_ml").each(function() {
    $(this).html(lang($(this).attr("id")))
  })

  $(".is_ml_p").each(function() {
    $(this).attr('placeholder', lang($(this).attr("id")))
  })

  document.getElementById("timezone1").innerHTML = lang("Local time: ") + gmtToString();
  document.getElementById("timezone2").innerHTML = lang("Local time: ") + gmtToString();
  nameDay = lang("nameDay");
};

function lang(id){
	if(typeof label[language] === "undefined" ){
		return label["en"][id];
	}else if(typeof label[language][id] === "undefined"){
		return label["en"][id];
	}
	return label[language][id];
}

function gmtToString(){
	var text;
    var now = new Date();
    var gmt = now.getTimezoneOffset();

    if(gmt<=0) text = "GMT+";
	else text = "GMT-";

    var hour = Math.floor(Math.abs(gmt/60));
	var minute = Math.abs(gmt)%60;
	text += pad(hour,2) + ":" + pad(minute,2);
    return text;
}

function pad(num, size) {
    var s = num+"";
    while (s.length < size) s = "0" + s;
    return s;
}

document.getElementById('input-account').onkeydown = function(e){
   if(e.keyCode == 13){
	 e.preventDefault();
     searchAccount();
   }
};<commit_msg>from steemd to api<commit_after>var language = navigator.language || navigator.userLanguage;
load_language();

var now = new Date();
var gmt = now.getTimezoneOffset()*60*1000; //gmt in milliseconds
var last1week = new Date(now.getFullYear(),now.getMonth(),now.getDate()-6);
var last2week = new Date(now.getTime() - 2*7*24*60*60*1000);
var last3week = new Date(now.getTime() - 3*7*24*60*60*1000);
var last4week = new Date(now.getTime() - 4*7*24*60*60*1000);

document.getElementById("timezone1").innerHTML = lang("Local time: ") + gmtToString();
document.getElementById("timezone2").innerHTML = lang("Local time: ") + gmtToString();

//Array of Votes and initialization
var votesDay = [0,0,0,0,0,0,0];
var a_votesDay = [0,0,0,0,0,0,0];

var votes = new Array(7);
for(i=0;i<7;i++){
	votes[i] = new Array(24);
	for(j=0;j<24;j++){
		votes[i][j]=0;
	}
}

var a_votes = new Array(7);
for(i=0;i<7;i++){
	a_votes[i] = new Array(24);
	for(j=0;j<24;j++){
		a_votes[i][j]=0;
	}
}

var followersLoaded = 0;
var totalFollowers = 0;
var textFollowers = "";
nameDay = lang("nameDay");
nameHours = ['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23'];

var maxVotation = [0,0,0,0];
var maxVotationDay = 0;
var bestHour = [[0,0],[0,0],[0,0],[0,0]];
var bestDay = 0;
var refreshPlot = 10;
var refreshText = 5;
var firstPlot = true;
var firstText = true;

function loadFollowersActivity(){
	/*steem.api.getConfig(function(err, response){
		console.log(err, response);
	});*/
    steem.api.setOptions({ url: 'https://api.steemit.com'});

	var account = getQuery();

	steem.api.getAccounts([account], function(err, result){
		console.log(err, result);
		var info = JSON.parse(result[0].json_metadata);
		if(info.profile.hasOwnProperty('profile_image')){
			console.log(info.profile.profile_image + " extracted: " + extractUrlProfileImage(info.profile.profile_image));
			document.getElementById("profile_image").src = extractUrlProfileImage(info.profile.profile_image);
		}else{
			console.log("no photo");
		}
	});

	document.getElementById("labelAccount").innerHTML = "@" + account;
	document.getElementById("title-followers").innerHTML = lang("Followers of @") + account;
	//document.getElementById("title-activity-account").innerHTML = "Activity of @" + account;

	consultVotesAccount(account);

	steem.api.getFollowCount(account, function(err,result) {
		console.log("Number of followers: "+result.follower_count);
		totalFollowers = result.follower_count;
		document.getElementById("title-followers").innerHTML = lang("Followers of @") + account + ": "+totalFollowers;
		consultVotesFollowers(account,0);
	});
}

function consultVotesAccount(account){
	steem.api.getAccountVotes(account, function(err, result) {
		//console.log(err,result);
		//if (err) //error
		//look each vote and put it in the array regarding the time
		for(i=result.length-1;i>=0;i--){
			var timeUTC = new Date(result[i].time);
			var time = new Date(timeUTC.getTime() - gmt);
			if(timeToBreak(time,result.length-i)) break;
			var hours = time.getHours();
			var day = time.getDay();
			a_votes[day][hours]++;
			a_votesDay[day]++;
		}

		for(i=0;i<7;i++){
			var data = [{
				x: nameHours,
				y: a_votes[i],
				type: 'bar'
			}];
			var layout = { title: nameDay[i] };
			Plotly.newPlot('a-chart'+i, data,layout);
			document.getElementById("a-votesDay"+i).innerHTML = nameDay[i]+": "+a_votesDay[i]+lang(" votes");
		}
	});
}

function consultVotesFollowers(account, fromFollower){
	steem.api.getFollowers(account, fromFollower, 0, 21, function(err, result) {

		//look each for each Follower
		var finish = result.length-1;
		if(result.length == 1) finish=1; //last follower

		for(i=0;i<finish;i++){
			if(result[i].what[0] != 'blog') continue;
			textFollowers = textFollowers + link(result[i].follower) + " . . . . ";

			steem.api.getAccountVotes(result[i].follower, function(err, result) {
				//if (err) //error
				//look each vote and put it in the array regarding the time
				for(i=result.length-1;i>=0;i--){
					var timeUTC = new Date(result[i].time);
					var time = new Date(timeUTC.getTime() - gmt);
					if(timeToBreak(time,result.length-i)) break;
					var hours = time.getHours();
					var day = time.getDay();
					votes[day][hours]++;
					votesDay[day]++;
					for(j=0;j<4;j++){
						if(votes[day][hours] > maxVotation[j]){
							maxVotation[j] = votes[day][hours];
							bestHour[j] = [day,hours];
							break;
						}
					}
					if(votesDay[day] > maxVotationDay){
						maxVotationDay = votesDay[day];
						bestDay = day;
					}
				}

				followersLoaded++;

				refreshText--;
				if(firstText || refreshText==0 || followersLoaded==totalFollowers){
					var percentage = 100*followersLoaded/totalFollowers;
					var tPer = percentage.toFixed(2);
					var tBar = followersLoaded + "/" + totalFollowers;
					if(followersLoaded == totalFollowers) tBar = tBar + lang(". Complete");
					document.getElementById("progress-bar").innerHTML = tBar;
					document.getElementById("progress-bar").ariaValuenow = tPer;
					document.getElementById("progress-bar").style = "width: "+tPer+"%;";
					document.getElementById("followers").innerHTML = textFollowers;
					for(i=0;i<4;i++){
						document.getElementById("bestTime"+i).innerHTML = lang("Best Time #")+(i+1)+": " + nameDay[bestHour[i][0]] + lang(" at ") + bestHour[i][1] + " H";
					}
					firstText = false;
					refreshText = 5;
				}

				refreshPlot--;
				if(firstPlot || refreshPlot==0 || followersLoaded==totalFollowers){
					for(i=0;i<7;i++){
						var data = [{
							x: nameHours,
							y: votes[i],
							type: 'bar'
						}];
						var layout = { title: nameDay[i] };
						Plotly.newPlot('f-chart'+i, data,layout);
						document.getElementById("f-votesDay"+i).innerHTML = nameDay[i]+": "+votesDay[i]+lang(" votes");
					}
					firstPlot = false;
					refreshPlot = 10;
				}
			});
		}

		if(result.length>1){
			var lastFollower = result[result.length-1].follower;
			console.log("Consult from "+lastFollower);
			consultVotesFollowers(account, lastFollower);
		}else{
			console.log("Finished");
		}
	});
}

function timeToBreak(time,n){
	if(time < last4week) return true;
	return false;
}

function link(account){
	var url = "https://joticajulian.github.io/steem-activity/index.html";
	return "" + account + "";
}

function getQuery(){
	var kvp = document.location.search.substr(1).split('&');
	var account = '';
	var text = '';
	if(kvp != ''){
		var i = kvp.length;
		var x;
		while (i--) {
			x = kvp[i].split('=');
			if (x[0] == 'account'){
				account = x[1];
			}else if (x[0] == 'lang'){
				language = x[1];
				load_language();
			}
		}
	}
	return account;
}

function searchAccount(){
	var url = "https://joticajulian.github.io/steem-activity/index.html?lang="+language+"&account=" + document.getElementById("input-account").value;
	console.log("opening: "+url);
	window.open(url, "_self");
}

function extractUrlProfileImage(url){
	if(url.substring(0,8) == "![image]"){
		return url.substring(9, url.length - 1);
	}
	return url;
}

function load_language() {
  $(".is_ml").each(function() {
    $(this).html(lang($(this).attr("id")))
  })

  $(".is_ml_p").each(function() {
    $(this).attr('placeholder', lang($(this).attr("id")))
  })

  document.getElementById("timezone1").innerHTML = lang("Local time: ") + gmtToString();
  document.getElementById("timezone2").innerHTML = lang("Local time: ") + gmtToString();
  nameDay = lang("nameDay");
};

function lang(id){
	if(typeof label[language] === "undefined" ){
		return label["en"][id];
	}else if(typeof label[language][id] === "undefined"){
		return label["en"][id];
	}
	return label[language][id];
}

function gmtToString(){
	var text;
    var now = new Date();
    var gmt = now.getTimezoneOffset();

    if(gmt<=0) text = "GMT+";
	else text = "GMT-";

    var hour = Math.floor(Math.abs(gmt/60));
	var minute = Math.abs(gmt)%60;
	text += pad(hour,2) + ":" + pad(minute,2);
    return text;
}

function pad(num, size) {
    var s = num+"";
    while (s.length < size) s = "0" + s;
    return s;
}

document.getElementById('input-account').onkeydown = function(e){
   if(e.keyCode == 13){
	 e.preventDefault();
     searchAccount();
   }
};<|endoftext|>


<commit_before>
(function($) {

  $( document ).ready(function() {
    var url      = window.location.href;
    $.post( "http://api.storlyay.com/logevent", { event_name: "page_load", uid: url, urlreferr: document.referrer} );
  });

})(jQuery);
<commit_msg>fix analytics uid<commit_after>
(function($) {

  $( document ).ready(function() {
    var url      = window.location.search;
    $.post( "http://api.storlyay.com/logevent", { event_name: "page_load", uid: url, urlreferr: document.referrer} );
  });

})(jQuery);
<|endoftext|>