<commit_before>/* game namespace */
var game = {

    /**
     * an object where to store game global data
     */
    data : {
        // score
        score : 0
    },

    // Run on page load.
    "onload" : function () {

        // Initialize the video.
        if (!me.video.init("screen", 800, 576, true)) {
            alert("Your browser does not support HTML5 canvas.");
            return;
        }

        // add "#debug" to the URL to enable the debug Panel
        // if (document.location.hash === "#debug") {
        //     window.onReady(function () {
        //         me.plugin.register.defer(debugPanel, "debug");
        //     });
        // }

        // Initialize the audio.
        me.audio.init("mp3");

        // Set a callback to run when loading is complete.
        me.loader.onload = this.loaded.bind(this);

        // Load the resources.
        me.loader.preload(game.resources);

        // Initialize melonJS and display a loading screen.
        me.state.change(me.state.LOADING);
    },

    // Run on game resources loaded.
    "loaded" : function () {
        me.state.set(me.state.MENU, new game.TitleScreen());
        me.state.set(me.state.PLAY, new game.PlayScreen());
        // add our player entity in the entity pool
        me.entityPool.add("friend1", game.FriendEntity);
        me.entityPool.add("zombie1", game.ZombieEntity);
        me.state.transition("fade", "#FFFFFF", 250);

        // enable the keyboard
        me.input.bindKey(me.input.KEY.LEFT,  "left");
        me.input.bindKey(me.input.KEY.RIGHT, "right");
        me.input.bindKey(me.input.KEY.X,     "jump", true);

        // Start the game.
        me.state.change(me.state.MENU);

    }
};
<commit_msg>Update level01.tmx<commit_after>/* game namespace */
var game = {

    /**
     * an object where to store game global data
     */
    data : {
        // score
        score : 0
    },

    zombieInterval: 1000,

    // Run on page load.
    "onload" : function () {

        // Initialize the video.
        if (!me.video.init("screen", 800, 576, true)) {
            alert("Your browser does not support HTML5 canvas.");
            return;
        }

        // add "#debug" to the URL to enable the debug Panel
        // if (document.location.hash === "#debug") {
        //     window.onReady(function () {
        //         me.plugin.register.defer(debugPanel, "debug");
        //     });
        // }

        // Initialize the audio.
        me.audio.init("mp3");

        // Set a callback to run when loading is complete.
        me.loader.onload = this.loaded.bind(this);

        // Load the resources.
        me.loader.preload(game.resources);

        // Initialize melonJS and display a loading screen.
        me.state.change(me.state.LOADING);
    },

    // Run on game resources loaded.
    "loaded" : function () {
        me.state.set(me.state.MENU, new game.TitleScreen());
        me.state.set(me.state.PLAY, new game.PlayScreen());
        // add our player entity in the entity pool
        me.entityPool.add("friend1", game.FriendEntity);

        me.entityPool.add("zombie1", game.ZombieEntity, true);

        me.entityPool.add("zombie2", game.ZombieEntity, true);

        me.entityPool.add("zombie3", game.ZombieEntity, true);

        me.entityPool.add("zombie4", game.ZombieEntity, true);
        // setInterval(this.createZombie, this.zombieInterval);

        me.state.transition("fade", "#FFFFFF", 250);

        // enable the keyboard
        me.input.bindKey(me.input.KEY.LEFT,  "left");
        me.input.bindKey(me.input.KEY.RIGHT, "right");
        me.input.bindKey(me.input.KEY.X,     "jump", true);

        // Start the game.
        me.state.change(me.state.PLAY);

    },

    createZombie: function() {
        var min = 1;
        var max = 4;
        var random = Math.floor(Math.random() * (max - min + 1)) + min;
        var zombieObj = me.entityPool.newInstanceOf("zombie" + random);
        me.game.remove(zombieObj);
        me.entityPool.add("zombie" + random, game.ZombieEntity,true);
    }
};
<|endoftext|>


<commit_before>window.answer = newNumber()

$(document).on('submit', '#attempt', function(event) {
  guess(this.elements[0].value)
  this.elements[0].value = ''
  return false
})

$(document).on('click', '#restart', function(event) {
  restart()
  return false
})

function guess(number) {
  outcome = testAgainstAnswer(window.answer, number)
  counter = $('.guess').length + 1
  if(outcome[0] == 4) {
    window.guessHtml = $('.guess-area').html()
    $('.guess-area').html('♛
oh yeah!
' + number + ' is right!
you got it at the ' + nth(counter) + ' attempt.
' + feedback(counter) + '
Restart!')
  } else {
    $('#guesses').prepend('

attempt ' + counter + '

' + number + '

' + outcome[0] + 'a' + outcome[1] + 'b'  + '

')
  }
  return false
}

function restart() {
  console.log('')
  window.answer = newNumber()
  $('#guesses').html('')
  $('.guess-area').html(guessHtml)
}

function feedback(times) {
  if(times == 1) {
    return "Waaaat???"
  } else if (times == 2) {
    return "you cheated, right?"
  } else if (times == 3) {
    return "you lucky cat."
  } else if (times == 4) {
    return "I don't believe you, play again!"
  } else if (times == 5) {
    return "wow so good!"
  } else if (times <= 10) {
    return "you've got skills!"
  } else if (times <= 20) {
    return "good job yo!"
  } else if (times <= 30) {
    return "meh.. I think you can do better."
  } else if (times <= 40) {
    return "lolol wat?"
  } else if (times <=550) {
    return "some people got skills, some people..."
  } else {
    return "I don't think you know how to play this game.."
  }
}

function newNumber() {
  return (Math.random()).toString().slice(2,6)
}

function testAgainstAnswer(answer, attempt) {
  answer_arr  = answer.toString().split("")
  attempt_arr = attempt.split("")
  a = 0
  b = 0

  $.each(answer_arr, function(index, num) {
    if(attempt_arr[index] == answer_arr[index]) {
      answer_arr[index] = 'x'
      attempt_arr[index] = 'o'
      a+=1
    }
  })

  $.each(answer_arr, function(index, num) {
    if (answer_arr.indexOf(attempt_arr[index]) >= 0) {
      answer_arr[answer_arr.indexOf(attempt_arr[index])] = ''
      b+=1
    }
  })

  return [a, b]
}

// -----------------------------------------------

// Helpers
//
// Order of things
function nth(number) {
  ordered  = number.toString()
  leftover = number % 10
  if(number > 3 && number < 21) {
    ordered += 'th'
  } else if(leftover == 1) {
    ordered += 'st'
  } else if(leftover == 2) {
    ordered += 'nd'
  } else if(leftover == 3) {
    ordered += 'rd'
  } else {
    ordered += 'th'
  }
  return ordered
}
<commit_msg>Focus input<commit_after>window.answer = newNumber()

$(document).on('submit', '#attempt', function(event) {
  guess(this.elements[0].value)
  this.elements[0].value = ''
  return false
})

$(document).on('click', '#restart', function(event) {
  restart()
  return false
})

function guess(number) {
  outcome = testAgainstAnswer(window.answer, number)
  counter = $('.guess').length + 1
  if(outcome[0] == 4) {
    window.guessHtml = $('.guess-area').html()
    $('.guess-area').html('♛
oh yeah!
' + number + ' is right!
you got it at the ' + nth(counter) + ' attempt.
' + feedback(counter) + '
Restart!')
  } else {
    $('#guesses').prepend('

attempt ' + counter + '

' + number + '

' + outcome[0] + 'a' + outcome[1] + 'b'  + '

')
  }
  return false
}

function restart() {
  window.answer = newNumber()
  $('#guesses').html('')
  $('.guess-area').html(guessHtml)
  $('.attempt').focus()
}

function feedback(times) {
  if(times == 1) {
    return "Waaaat???"
  } else if (times == 2) {
    return "you cheated, right?"
  } else if (times == 3) {
    return "you lucky cat."
  } else if (times == 4) {
    return "I don't believe you, play again!"
  } else if (times == 5) {
    return "wow so good!"
  } else if (times <= 10) {
    return "you've got skills!"
  } else if (times <= 20) {
    return "good job yo!"
  } else if (times <= 30) {
    return "meh.. I think you can do better."
  } else if (times <= 40) {
    return "lolol wat?"
  } else if (times <=550) {
    return "some people got skills, some people..."
  } else {
    return "I don't think you know how to play this game.."
  }
}

function newNumber() {
  return (Math.random()).toString().slice(2,6)
}

function testAgainstAnswer(answer, attempt) {
  answer_arr  = answer.toString().split("")
  attempt_arr = attempt.split("")
  a = 0
  b = 0

  $.each(answer_arr, function(index, num) {
    if(attempt_arr[index] == answer_arr[index]) {
      answer_arr[index] = 'x'
      attempt_arr[index] = 'o'
      a+=1
    }
  })

  $.each(answer_arr, function(index, num) {
    if (answer_arr.indexOf(attempt_arr[index]) >= 0) {
      answer_arr[answer_arr.indexOf(attempt_arr[index])] = ''
      b+=1
    }
  })

  return [a, b]
}

// -----------------------------------------------

// Helpers
//
// Order of things
function nth(number) {
  ordered  = number.toString()
  leftover = number % 10
  if(number > 3 && number < 21) {
    ordered += 'th'
  } else if(leftover == 1) {
    ordered += 'st'
  } else if(leftover == 2) {
    ordered += 'nd'
  } else if(leftover == 3) {
    ordered += 'rd'
  } else {
    ordered += 'th'
  }
  return ordered
}
<|endoftext|>


<commit_before>var game = {
  colorblind: (localStorage.colorblind && JSON.parse(localStorage.colorblind)) || 'false',
  language: window.location.hash.substring(1) || 'en',
  difficulty: 'easy',
  level: parseInt(localStorage.level, 10) || 0,
  answers: (localStorage.answers && JSON.parse(localStorage.answers)) || {},
  solved: (localStorage.solved && JSON.parse(localStorage.solved)) || [],
  user: localStorage.user || '',
  changed: false,

  start: function() {
    // navigator.language can include '-'
    // ref: https://developer.mozilla.org/en-US/docs/Web/API/NavigatorLanguage/language
    var requestLang = window.navigator.language.split('-')[0];
    if (window.location.hash === '' && requestLang !== 'en' && messages.languageActive.hasOwnProperty(requestLang)) {
      game.language = requestLang;
      window.location.hash = requestLang;
    }

    game.translate();
    $('#level-counter .total').text(levels.length);
    $('#editor').show();
    $('#share').hide();
    $('#language').val(game.language);
    $('input[value="' + game.colorblind + '"]', '#colorblind').prop('checked', true);

    if (!localStorage.user) {
      game.user = '' + (new Date()).getTime() + Math.random().toString(36).slice(1);
      localStorage.setItem('user', game.user);
    }

    this.setHandlers();
    this.loadMenu();
    game.loadLevel(levels[game.level]);
  },

  setHandlers: function() {
    $('#next').on('click', function() {
      $('#code').focus();

      if ($(this).hasClass('disabled')) {
        if (!$('.frog').hasClass('animated')) {
          game.tryagain();
        }

        return;
      }

      $(this).removeClass('animated animation');
      $('.frog').addClass('animated bounceOutUp');
      $('.arrow, #next').addClass('disabled');

      setTimeout(function() {
        if (game.level >= levels.length - 1) {
          game.win();
        } else {
          game.next();
        }
      }, 2000);
    });

    $('#code').on('keydown', function(e) {
      if (e.keyCode === 13) {

        if (e.ctrlKey || e.metaKey) {
          e.preventDefault();
          game.check();
          $('#next').click();
          return;
        }

        var max = $(this).data('lines');
        var code = $(this).val();
        var trim = code.trim();
        var codeLength = code.split('\n').length;
        var trimLength = trim.split('\n').length;

        if (codeLength >= max) {

          if (codeLength === trimLength) {
            e.preventDefault();
            $('#next').click();
          } else {
            $('#code').focus().val('').val(trim);
          }
        }
      }
    }).on('input', game.debounce(game.check, 500))
    .on('input', function() {
      game.changed = true;
      $('#next').removeClass('animated animation').addClass('disabled');
    });

    $('#editor').on('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
      $(this).removeClass();
    });

    $('#labelReset').on('click', function() {
      var warningReset = messages.warningReset[game.language] || messages.warningReset.en;
      var r = confirm(warningReset);

      if (r) {
        game.level = 0;
        game.answers = {};
        game.solved = [];
        game.loadLevel(levels[0]);

        $('.level-marker').removeClass('solved');
      }
    });

    $('#labelSettings').on('click', function() {
      $('#levelsWrapper').hide();
      $('#settings .tooltip').toggle();
    })

    $('#language').on('change', function() {
      window.location.hash = $(this).val();
    });

    $('#difficulty').on('change', function() {
      game.difficulty = $('input:checked', '#difficulty').val();

      // setting height will prevent a slight jump when the animation starts
      var $instructions = $('#instructions');
      var height = $instructions.height();
      $instructions.css('height', height);

      var $markers = $('.level-marker');

      if (game.difficulty == 'hard' || game.difficulty == 'medium') {
        $instructions.slideUp();

        $markers.each(function() {
          var $marker = $(this);
          if ($marker[0].hasAttribute('title')) {
            $marker.attr('data-title', $marker.attr('title'));
            $marker.removeAttr('title');
          }
        });
      } else {
        $instructions.css('height', '').slideDown();

        $markers.each(function() {
          var $marker = $(this);
          if ($marker[0].hasAttribute('data-title')) {
            $marker.attr('title', $marker.attr('data-title'));
            $marker.removeAttr('data-title');
          }
        });
      }
    });

    $('#colorblind').on('change', function() {
      game.colorblind = $('input:checked', '#colorblind').val();

      if (game.colorblind == 'true') {
        $('.lilypad, .frog').addClass('cb-friendly');
      } else {
        $('.lilypad, .frog').removeClass('cb-friendly');
      }
    });

    $('body').on('click', function() {
      $('.tooltip').hide();
    });

    $('.tooltip, .toggle, #level-indicator').on('click', function(e) {
      e.stopPropagation();
    });

    $(window).on('beforeunload', function() {
      game.saveAnswer();
      localStorage.setItem('level', game.level);
      localStorage.setItem('answers', JSON.stringify(game.answers));
      localStorage.setItem('solved', JSON.stringify(game.solved));
      localStorage.setItem('colorblind', JSON.stringify(game.colorblind));
    }).on('hashchange', function() {
      game.language = window.location.hash.substring(1) || 'en';
      game.translate();

      $('#tweet iframe').remove();
      var html = 'Tweet ' +
                 'Follow @thomashpark';
      $('#tweet').html(html);
      twttr.widgets.load();

      if (game.language === 'en') {
        history.replaceState({}, document.title, './');
      }
    });
  },

  prev: function() {
    this.level--;

    var levelData = levels[this.level];
    this.loadLevel(levelData);
  },

  next: function() {
    if (this.difficulty === "hard") {
      this.level = Math.floor(Math.random()* levels.length)
    } else {
      this.level++
    }

    var levelData = levels[this.level];
    this.loadLevel(levelData);
  },

  loadMenu: function() {
    levels.forEach(function(level, i) {
      var levelMarker = $('').addClass('level-marker').attr({'data-level': i, 'title': level.name}).text(i+1);

      if ($.inArray(level.name, game.solved) !== -1) {
        levelMarker.addClass('solved');
      }

      levelMarker.appendTo('#levels');
    });

    $('.level-marker').on('click', function() {
      game.saveAnswer();

      var level = $(this).attr('data-level');
      game.level = parseInt(level, 10);
      game.loadLevel(levels[level]);
    });

    $('#level-indicator').on('click', function() {
      $('#settings .tooltip').hide();
      $('#levelsWrapper').toggle();
    });

    $('.arrow.left').on('click', function() {
      if ($(this).hasClass('disabled')) {
        return;
      }

      game.saveAnswer();
      game.prev();
    });

    $('.arrow.right').on('click', function() {
      if ($(this).hasClass('disabled')) {
        return;
      }

      game.saveAnswer();
      game.next();
    });
  },

  loadLevel: function(level) {
    $('#editor').show();
    $('#share').hide();
    $('#background, #pond').removeClass('wrap').attr('style', '').empty();
    $('#levelsWrapper').hide();
    $('.level-marker').removeClass('current').eq(this.level).addClass('current');
    $('#level-counter .current').text(this.level + 1);
    $('#before').text(level.before);
    $('#after').text(level.after);
    $('#next').removeClass('animated animation').addClass('disabled');

    var instructions = level.instructions[game.language] || level.instructions.en;
    $('#instructions').html(instructions);

    $('.arrow.disabled').removeClass('disabled');

    if (this.level === 0) {
      $('.arrow.left').addClass('disabled');
    }

    if (this.level === levels.length - 1) {
      $('.arrow.right').addClass('disabled');
    }

    var answer = game.answers[level.name];
    $('#code').val(answer).focus();

    this.loadDocs();

    var lines = Object.keys(level.style).length;
    $('#code').height(20 * lines).data("lines", lines);

    var string = level.board;
    var markup = '';
    var colors = {
      'g': 'green',
      'r': 'red',
      'y': 'yellow'
    };

    for (var i = 0; i < string.length; i++) {
      var c = string.charAt(i);
      var color = colors[c];

      var lilypad = $('
').addClass('lilypad ' + color + (this.colorblind == 'true' ? ' cb-friendly' : '')).data('color', color);
      var frog = $('
').addClass('frog ' + color + (this.colorblind == 'true' ? ' cb-friendly' : '')).data('color', color);

      $('
').addClass('bg').css(game.transform()).appendTo(lilypad);
      $('
').addClass('bg animated pulse infinite').appendTo(frog);

      $('#background').append(lilypad);
      $('#pond').append(frog);
    }

    var classes = level.classes;

    if (classes) {
      for (var rule in classes) {
        $(rule).addClass(classes[rule]);
      }
    }

    var selector = level.selector || '';
    $('#background ' + selector).css(level.style);

    game.changed = false;
    game.applyStyles();
    game.check();
  },

  loadDocs: function() {
    $('#instructions code').each(function() {
      var code = $(this);
      var text = code.text();

      if (text in docs) {
        code.addClass('help');
        code.on('mouseenter', function(e) {
          if($('#instructions .tooltip').length !== 0) {
            $('#instructions .tooltip').remove();
          }
          if ($('#instructions .tooltip').length === 0) {
            var html = docs[text][game.language] || docs[text].en;
            var tooltipX = code.offset().left;
            var tooltipY = code.offset().top + code.height() + 13;
            $('

').html(html).css({
              top: tooltipY,
              left: tooltipX
            }).appendTo($('#instructions'));

            $('#instructions .tooltip code').on('click', function(event) {
              var pName = text
              var pValue = event.target.textContent.split(' ')[0];
              pValue = pValue === "<integer>" ? 0 : pValue;
              game.writeCSS(pName, pValue)

              game.check();
            });
            $("code").css('cursor', 'pointer');
          }
        }).on('mouseleave', function() {
          $('#instructions .tooltip').on('mouseleave', function() {
            $('#tooltip').remove();
          });
        });
      }
    });
  },

  applyStyles: function() {
    var level = levels[game.level];
    var code = $('#code').val();
    var selector = level.selector || '';
    $('#pond ' +  selector).attr('style', code);
    game.saveAnswer();
  },

  check: function() {
    game.applyStyles();

    var level = levels[game.level];
    var lilypads = {};
    var frogs = {};
    var correct = true;

    $('.frog').each(function() {
      var position = $(this).position();
      position.top = Math.floor(position.top);
      position.left = Math.floor(position.left);

      var key = JSON.stringify(position);
      var val = $(this).data('color');
      frogs[key] = val;
    });

    $('.lilypad').each(function() {
      var position = $(this).position();
      position.top = Math.floor(position.top);
      position.left = Math.floor(position.left);

      var key = JSON.stringify(position);
      var val = $(this).data('color');

      if (!(key in frogs) || frogs[key] !== val) {
        correct = false;
      }
    });

    if (correct) {
      ga('send', {
        hitType: 'event',
        eventCategory: level.name,
        eventAction: 'correct',
        eventLabel: $('#code').val()
      });

      if ($.inArray(level.name, game.solved) === -1) {
        game.solved.push(level.name);
      }

      $('[data-level=' + game.level + ']').addClass('solved');
      $('#next').removeClass('disabled').addClass('animated animation');
    } else {
      ga('send', {
        hitType: 'event',
        eventCategory: level.name,
        eventAction: 'incorrect',
        eventLabel: $('#code').val()
      });

      game.changed = true;
      $('#next').removeClass('animated animation').addClass('disabled');
    }
  },

  saveAnswer: function() {
    var level = levels[this.level];
    game.answers[level.name] = $('#code').val();
  },

  tryagain: function() {
    $('#editor').addClass('animated shake');
  },

  win: function() {
    var solution = $('#code').val();

    this.loadLevel(levelWin);

    $('#editor').hide();
    $('#code').val(solution);
    $('#share').show();
    $('.frog .bg').removeClass('pulse').addClass('bounce');
  },

  transform: function() {
    var scale = 1 + ((Math.random() / 5) - 0.2);
    var rotate = 360 * Math.random();

    return {'transform': 'scale(' + scale + ') rotate(' + rotate + 'deg)'};
  },

  translate: function() {
    document.title = messages.title[game.language] || messages.title.en;
    $('html').attr('lang', game.language);

    var level = $('#editor').is(':visible') ? levels[game.level] : levelWin;
    var instructions = level.instructions[game.language] || level.instructions.en;
    $('#instructions').html(instructions);
    game.loadDocs();

    $('.translate').each(function() {
      var label = $(this).attr('id');
      if (messages[label]) {
        var text = messages[label][game.language] || messages[label].en;
	  }

      $('#' + label).text(text);
    });
  },

  debounce: function(func, wait, immediate) {
    var timeout;
    return function() {
      var context = this, args = arguments;
      var later = function() {
        timeout = null;
        if (!immediate) func.apply(context, args);
      };
      var callNow = immediate && !timeout;
      clearTimeout(timeout);
      timeout = setTimeout(later, wait);
      if (callNow) func.apply(context, args);
    };
  },

  writeCSS: function(pName, pValue){
    var tokens = $('#code').val().trim().split(/[\s:;]+/);
    var keywords = Object.keys(docs);
    var content = '';
    var filled = false;

    tokens.forEach(function (token, i){
      if (!keywords.includes(token)){
        return;
      }

      var append = content !== '' ? '\n' : '';
      if (token === pName && !filled)
      {
        filled = true;
        append += token + ': ' + pValue + ';';
      }
      else if (i + 1 < tokens.length){
        append += token + ': ' + tokens[i + 1] + ';';
      }

      content += append;
    });

    if (!filled){
      content += content !== '' ? '\n' : '';
      content += pName + ': ' + pValue + ';';
    }

    $('#code').val(content);
  }
};

$(document).ready(function() {
  game.start();
});
<commit_msg>modify the scope of application of cursor<commit_after>var game = {
  colorblind: (localStorage.colorblind && JSON.parse(localStorage.colorblind)) || 'false',
  language: window.location.hash.substring(1) || 'en',
  difficulty: 'easy',
  level: parseInt(localStorage.level, 10) || 0,
  answers: (localStorage.answers && JSON.parse(localStorage.answers)) || {},
  solved: (localStorage.solved && JSON.parse(localStorage.solved)) || [],
  user: localStorage.user || '',
  changed: false,

  start: function() {
    // navigator.language can include '-'
    // ref: https://developer.mozilla.org/en-US/docs/Web/API/NavigatorLanguage/language
    var requestLang = window.navigator.language.split('-')[0];
    if (window.location.hash === '' && requestLang !== 'en' && messages.languageActive.hasOwnProperty(requestLang)) {
      game.language = requestLang;
      window.location.hash = requestLang;
    }

    game.translate();
    $('#level-counter .total').text(levels.length);
    $('#editor').show();
    $('#share').hide();
    $('#language').val(game.language);
    $('input[value="' + game.colorblind + '"]', '#colorblind').prop('checked', true);

    if (!localStorage.user) {
      game.user = '' + (new Date()).getTime() + Math.random().toString(36).slice(1);
      localStorage.setItem('user', game.user);
    }

    this.setHandlers();
    this.loadMenu();
    game.loadLevel(levels[game.level]);
  },

  setHandlers: function() {
    $('#next').on('click', function() {
      $('#code').focus();

      if ($(this).hasClass('disabled')) {
        if (!$('.frog').hasClass('animated')) {
          game.tryagain();
        }

        return;
      }

      $(this).removeClass('animated animation');
      $('.frog').addClass('animated bounceOutUp');
      $('.arrow, #next').addClass('disabled');

      setTimeout(function() {
        if (game.level >= levels.length - 1) {
          game.win();
        } else {
          game.next();
        }
      }, 2000);
    });

    $('#code').on('keydown', function(e) {
      if (e.keyCode === 13) {

        if (e.ctrlKey || e.metaKey) {
          e.preventDefault();
          game.check();
          $('#next').click();
          return;
        }

        var max = $(this).data('lines');
        var code = $(this).val();
        var trim = code.trim();
        var codeLength = code.split('\n').length;
        var trimLength = trim.split('\n').length;

        if (codeLength >= max) {

          if (codeLength === trimLength) {
            e.preventDefault();
            $('#next').click();
          } else {
            $('#code').focus().val('').val(trim);
          }
        }
      }
    }).on('input', game.debounce(game.check, 500))
    .on('input', function() {
      game.changed = true;
      $('#next').removeClass('animated animation').addClass('disabled');
    });

    $('#editor').on('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
      $(this).removeClass();
    });

    $('#labelReset').on('click', function() {
      var warningReset = messages.warningReset[game.language] || messages.warningReset.en;
      var r = confirm(warningReset);

      if (r) {
        game.level = 0;
        game.answers = {};
        game.solved = [];
        game.loadLevel(levels[0]);

        $('.level-marker').removeClass('solved');
      }
    });

    $('#labelSettings').on('click', function() {
      $('#levelsWrapper').hide();
      $('#settings .tooltip').toggle();
    })

    $('#language').on('change', function() {
      window.location.hash = $(this).val();
    });

    $('#difficulty').on('change', function() {
      game.difficulty = $('input:checked', '#difficulty').val();

      // setting height will prevent a slight jump when the animation starts
      var $instructions = $('#instructions');
      var height = $instructions.height();
      $instructions.css('height', height);

      var $markers = $('.level-marker');

      if (game.difficulty == 'hard' || game.difficulty == 'medium') {
        $instructions.slideUp();

        $markers.each(function() {
          var $marker = $(this);
          if ($marker[0].hasAttribute('title')) {
            $marker.attr('data-title', $marker.attr('title'));
            $marker.removeAttr('title');
          }
        });
      } else {
        $instructions.css('height', '').slideDown();

        $markers.each(function() {
          var $marker = $(this);
          if ($marker[0].hasAttribute('data-title')) {
            $marker.attr('title', $marker.attr('data-title'));
            $marker.removeAttr('data-title');
          }
        });
      }
    });

    $('#colorblind').on('change', function() {
      game.colorblind = $('input:checked', '#colorblind').val();

      if (game.colorblind == 'true') {
        $('.lilypad, .frog').addClass('cb-friendly');
      } else {
        $('.lilypad, .frog').removeClass('cb-friendly');
      }
    });

    $('body').on('click', function() {
      $('.tooltip').hide();
    });

    $('.tooltip, .toggle, #level-indicator').on('click', function(e) {
      e.stopPropagation();
    });

    $(window).on('beforeunload', function() {
      game.saveAnswer();
      localStorage.setItem('level', game.level);
      localStorage.setItem('answers', JSON.stringify(game.answers));
      localStorage.setItem('solved', JSON.stringify(game.solved));
      localStorage.setItem('colorblind', JSON.stringify(game.colorblind));
    }).on('hashchange', function() {
      game.language = window.location.hash.substring(1) || 'en';
      game.translate();

      $('#tweet iframe').remove();
      var html = 'Tweet ' +
                 'Follow @thomashpark';
      $('#tweet').html(html);
      twttr.widgets.load();

      if (game.language === 'en') {
        history.replaceState({}, document.title, './');
      }
    });
  },

  prev: function() {
    this.level--;

    var levelData = levels[this.level];
    this.loadLevel(levelData);
  },

  next: function() {
    if (this.difficulty === "hard") {
      this.level = Math.floor(Math.random()* levels.length)
    } else {
      this.level++
    }

    var levelData = levels[this.level];
    this.loadLevel(levelData);
  },

  loadMenu: function() {
    levels.forEach(function(level, i) {
      var levelMarker = $('').addClass('level-marker').attr({'data-level': i, 'title': level.name}).text(i+1);

      if ($.inArray(level.name, game.solved) !== -1) {
        levelMarker.addClass('solved');
      }

      levelMarker.appendTo('#levels');
    });

    $('.level-marker').on('click', function() {
      game.saveAnswer();

      var level = $(this).attr('data-level');
      game.level = parseInt(level, 10);
      game.loadLevel(levels[level]);
    });

    $('#level-indicator').on('click', function() {
      $('#settings .tooltip').hide();
      $('#levelsWrapper').toggle();
    });

    $('.arrow.left').on('click', function() {
      if ($(this).hasClass('disabled')) {
        return;
      }

      game.saveAnswer();
      game.prev();
    });

    $('.arrow.right').on('click', function() {
      if ($(this).hasClass('disabled')) {
        return;
      }

      game.saveAnswer();
      game.next();
    });
  },

  loadLevel: function(level) {
    $('#editor').show();
    $('#share').hide();
    $('#background, #pond').removeClass('wrap').attr('style', '').empty();
    $('#levelsWrapper').hide();
    $('.level-marker').removeClass('current').eq(this.level).addClass('current');
    $('#level-counter .current').text(this.level + 1);
    $('#before').text(level.before);
    $('#after').text(level.after);
    $('#next').removeClass('animated animation').addClass('disabled');

    var instructions = level.instructions[game.language] || level.instructions.en;
    $('#instructions').html(instructions);

    $('.arrow.disabled').removeClass('disabled');

    if (this.level === 0) {
      $('.arrow.left').addClass('disabled');
    }

    if (this.level === levels.length - 1) {
      $('.arrow.right').addClass('disabled');
    }

    var answer = game.answers[level.name];
    $('#code').val(answer).focus();

    this.loadDocs();

    var lines = Object.keys(level.style).length;
    $('#code').height(20 * lines).data("lines", lines);

    var string = level.board;
    var markup = '';
    var colors = {
      'g': 'green',
      'r': 'red',
      'y': 'yellow'
    };

    for (var i = 0; i < string.length; i++) {
      var c = string.charAt(i);
      var color = colors[c];

      var lilypad = $('
').addClass('lilypad ' + color + (this.colorblind == 'true' ? ' cb-friendly' : '')).data('color', color);
      var frog = $('
').addClass('frog ' + color + (this.colorblind == 'true' ? ' cb-friendly' : '')).data('color', color);

      $('
').addClass('bg').css(game.transform()).appendTo(lilypad);
      $('
').addClass('bg animated pulse infinite').appendTo(frog);

      $('#background').append(lilypad);
      $('#pond').append(frog);
    }

    var classes = level.classes;

    if (classes) {
      for (var rule in classes) {
        $(rule).addClass(classes[rule]);
      }
    }

    var selector = level.selector || '';
    $('#background ' + selector).css(level.style);

    game.changed = false;
    game.applyStyles();
    game.check();
  },

  loadDocs: function() {
    $('#instructions code').each(function() {
      var code = $(this);
      var text = code.text();

      if (text in docs) {
        code.addClass('help');
        code.on('mouseenter', function(e) {
          if($('#instructions .tooltip').length !== 0) {
            $('#instructions .tooltip').remove();
          }
          if ($('#instructions .tooltip').length === 0) {
            var html = docs[text][game.language] || docs[text].en;
            var tooltipX = code.offset().left;
            var tooltipY = code.offset().top + code.height() + 13;
            $('

').html(html).css({
              top: tooltipY,
              left: tooltipX
            }).appendTo($('#instructions'));

            $('#instructions .tooltip code').on('click', function(event) {
              var pName = text
              var pValue = event.target.textContent.split(' ')[0];
              pValue = pValue === "<integer>" ? 0 : pValue;
              game.writeCSS(pName, pValue)

              game.check();
            });
            $("#instructions .tooltip code").css('cursor', 'pointer');
          }
        }).on('mouseleave', function() {
          $('#instructions .tooltip').on('mouseleave', function() {
            $('#tooltip').remove();
          });
        });
      }
    });
  },

  applyStyles: function() {
    var level = levels[game.level];
    var code = $('#code').val();
    var selector = level.selector || '';
    $('#pond ' +  selector).attr('style', code);
    game.saveAnswer();
  },

  check: function() {
    game.applyStyles();

    var level = levels[game.level];
    var lilypads = {};
    var frogs = {};
    var correct = true;

    $('.frog').each(function() {
      var position = $(this).position();
      position.top = Math.floor(position.top);
      position.left = Math.floor(position.left);

      var key = JSON.stringify(position);
      var val = $(this).data('color');
      frogs[key] = val;
    });

    $('.lilypad').each(function() {
      var position = $(this).position();
      position.top = Math.floor(position.top);
      position.left = Math.floor(position.left);

      var key = JSON.stringify(position);
      var val = $(this).data('color');

      if (!(key in frogs) || frogs[key] !== val) {
        correct = false;
      }
    });

    if (correct) {
      ga('send', {
        hitType: 'event',
        eventCategory: level.name,
        eventAction: 'correct',
        eventLabel: $('#code').val()
      });

      if ($.inArray(level.name, game.solved) === -1) {
        game.solved.push(level.name);
      }

      $('[data-level=' + game.level + ']').addClass('solved');
      $('#next').removeClass('disabled').addClass('animated animation');
    } else {
      ga('send', {
        hitType: 'event',
        eventCategory: level.name,
        eventAction: 'incorrect',
        eventLabel: $('#code').val()
      });

      game.changed = true;
      $('#next').removeClass('animated animation').addClass('disabled');
    }
  },

  saveAnswer: function() {
    var level = levels[this.level];
    game.answers[level.name] = $('#code').val();
  },

  tryagain: function() {
    $('#editor').addClass('animated shake');
  },

  win: function() {
    var solution = $('#code').val();

    this.loadLevel(levelWin);

    $('#editor').hide();
    $('#code').val(solution);
    $('#share').show();
    $('.frog .bg').removeClass('pulse').addClass('bounce');
  },

  transform: function() {
    var scale = 1 + ((Math.random() / 5) - 0.2);
    var rotate = 360 * Math.random();

    return {'transform': 'scale(' + scale + ') rotate(' + rotate + 'deg)'};
  },

  translate: function() {
    document.title = messages.title[game.language] || messages.title.en;
    $('html').attr('lang', game.language);

    var level = $('#editor').is(':visible') ? levels[game.level] : levelWin;
    var instructions = level.instructions[game.language] || level.instructions.en;
    $('#instructions').html(instructions);
    game.loadDocs();

    $('.translate').each(function() {
      var label = $(this).attr('id');
      if (messages[label]) {
        var text = messages[label][game.language] || messages[label].en;
	  }

      $('#' + label).text(text);
    });
  },

  debounce: function(func, wait, immediate) {
    var timeout;
    return function() {
      var context = this, args = arguments;
      var later = function() {
        timeout = null;
        if (!immediate) func.apply(context, args);
      };
      var callNow = immediate && !timeout;
      clearTimeout(timeout);
      timeout = setTimeout(later, wait);
      if (callNow) func.apply(context, args);
    };
  },

  writeCSS: function(pName, pValue){
    var tokens = $('#code').val().trim().split(/[\s:;]+/);
    var keywords = Object.keys(docs);
    var content = '';
    var filled = false;

    tokens.forEach(function (token, i){
      if (!keywords.includes(token)){
        return;
      }

      var append = content !== '' ? '\n' : '';
      if (token === pName && !filled)
      {
        filled = true;
        append += token + ': ' + pValue + ';';
      }
      else if (i + 1 < tokens.length){
        append += token + ': ' + tokens[i + 1] + ';';
      }

      content += append;
    });

    if (!filled){
      content += content !== '' ? '\n' : '';
      content += pName + ': ' + pValue + ';';
    }

    $('#code').val(content);
  }
};

$(document).ready(function() {
  game.start();
});
<|endoftext|>


<commit_before>var Game = function(startBoard) {
  this.completed = false;
  this.startBoard = startBoard;
  this.board = this.makeBoard(startBoard);
};

Game.prototype.makeBoard = function(stringBoard){
  if (stringBoard.length !== 16){
    alert("Starting boards must be 16 digits long, you silly hobbit!");
    return false
  } else {
    var board = [];
    for (var i = 0; i < stringBoard.length; i+=4) {
      var array = [];
      for (var j = i; j < i+4; j++) {
      array.push(parseInt(stringBoard[j]));
      }
    board.push(array);
    }
  }
  return board;
};

Game.prototype.toString = function(){
  // var boardString = this.board.toString().replace(/,/g, "");
  var boardString = this.board;
  for (var i = 0; i < boardString.length; i++) {
    boardString[i].push("\n");
  };
  console.log(boardString.join("").replace(/,/g, ""));
};
<commit_msg>Move left functionality<commit_after>var Game = function(startBoard) {
  this.completed = false;
  this.startBoard = startBoard;
  this.board = this.makeBoard(startBoard);
};

Game.prototype.makeBoard = function(stringBoard){
  if (stringBoard.length !== 16){
    alert("Starting boards must be 16 digits long, you silly hobbit!");
    return false
  } else {
    var board = [];
    for (var i = 0; i < stringBoard.length; i+=4) {
      var array = [];
      for (var j = i; j < i+4; j++) {
      array.push(parseInt(stringBoard[j]));
      }
    board.push(array);
    }
  }
  return board;
};

Game.prototype.toString = function(){
  // var boardString = this.board.toString().replace(/,/g, "");
  var boardString = this.board;
  for (var i = 0; i < boardString.length; i++) {
    boardString[i].push("\n");
  };
  console.log(boardString.join("").replace(/,/g, ""));
};

Game.prototype.moveLeft = function(){
  var self = this;
  var board = this.board;
  for (var i = 0; i < board.length; i++) {
    var row = board[i];
    var zeroless = row.filter(function(i) { return i !== 0}) // creates row without 0s

    for (var j = 0; j < zeroless.length; j++) {
      if (zeroless[j] === zeroless[j+1]) {
        zeroless[j] = zeroless[j] * 2;
        zeroless.splice(j+1, 1);
      } else {
        zeroless[j] = zeroless[j]
      } // (no change)
    }
    var counter = row.length - zeroless.length;
    for (var k = 0; k < counter; k++) {
      zeroless.push(0);
    }
    self.board[i] = zeroless;
  }
};

Game.prototype.move = function('right'){

}

Game.prototype.move = function('up'){

}

Game.prototype.move = function('down'){

}

<|endoftext|>


<commit_before>// _tick control
window.onfocus = function() {
  Game.inverval = 100;
};
window.onblur = function() {
  Game.inverval = 1;
};

// Game
var Game = {
  currency: 10,
  inverval: 100,
  workloadCounter: 0,

  // DOM elements
  count: undefined,
  roster: undefined,
  market: undefined,
  cpsDisplay: undefined,
  workloadDisplay: undefined,

  // Arrays
  workers: [],
  companies: [],

  // handle for setTimeout
  handle: undefined,

  init: function(_workers, _companies) {
    var self = this;

    this.count = $('#currency-display');
    this.roster = $('#roster-container');
    this.market = $('#market-container');
    this.cpsDisplay = $('#cps-display');
    this.workloadDisplay = $('#workload-display');

    $.each(_workers, function(index, _worker) {
      var newWorker = Worker(_worker).init();
      self.workers.push(newWorker);
    });

    $.each(_companies, function(index, _company) {
      var newCompany = Company(_company).init();
      self.companies.push(newCompany);
    });
    this.cps();
    this.workload();
  },

  _tick: function() {
    $.each(this.companies, function(index, company) {
      company.produce();
      company.check();
    });

    $.each(this.workers, function(index, worker) {
      worker.check();
    });

    this.count.text(this.currency.toFixed(2));
  },

  cps: function() {
    var cps = 0;
    $.each(this.companies, function(index, company) {
      cps += company.production * company.quantity;
    });

    this.cpsDisplay.text(cps);
  },

  workload: function() {
    var workload = 0;
    $.each(this.companies, function(index, company) {
      $.each(company.costHistory, function(cIndex, cost) {
        if (cIndex < company.quantity) {
          workload -= cost;
        }
      });
    });

    $.each(this.workers, function(index, worker) {
      workload += worker.production * worker.quantity;
    });

    this.workloadDisplay.text(workload);
    this.workloadCounter = workload;

    return workload;
  }
};

var Company = function(options) {
  return $.extend({
    quantity: 0,
    increase: 1.15,
    // costHistory: [],

    cost: function() {

      return Math.ceil(this.costHistory[this.quantity] * this.increase);
    },

    button: undefined,
    title: undefined,

    produce: function() {
      Game.currency += this.quantity * this.production / Game.inverval;
    },

    check: function() {
      this.card.toggleClass('disabled', this.costHistory[this.quantity] > Game.workloadCounter);
    },

    buy: function() {
      if (this.costHistory[this.quantity] <= Game.workload()) {

        this.costHistory.push(this.cost());
        this.quantity++;
        // this.cost = Math.ceil(this.cost * this.increase);

        // Update visuals
        // this.cost = Math.ceil(this.cost * this.increase);
        this.strongNumber.text(this.quantity);
        this.colBigCenter.html('' + this.name + '
 person' + this.costHistory[this.quantity] + '');
        Game.cps();
        Game.workload();

      };
    },

    init: function() {
      var self = this;
      var row = undefined;
      var card = undefined;
      var rowValign = undefined;
      var colSmallLeft = undefined;
      var picture = undefined;
      var colBigCenter = undefined;
      var content = undefined;
      var colSmallRight = undefined;
      var strongNumber = undefined;

      // Create card
      this.row = $('
', {
        class: "row"
      });
      this.card = $('
', {
        class: "card-panel hoverable flow-text superTooltipped noselect",
        "data-position": "left",
        "data-delay": "50",
        "data-tooltip": '
attach_moneyIncome +' + this.production + '/s
',
        click: function() {
          self.buy();
        }
      });
      this.rowValign = $('
', {
        class: "row valign-wrapper"
      });
      this.colSmallLeft = $('
', {
        class: "col s2"
      });
      this.picture = $('', {
        class: "circle responsive-img valign",
        src: "img/" + this.imgUrl
      });
      this.colBigCenter = $('
', {
        class: "col s7",
        html: '' + this.name + '
 person' + this.costHistory[this.quantity] + ''
      });
      this.colSmallRight = $('
', {
        class: "col s3"
      });
      this.strongNumber = $('', {
        class: "left",
        style: "opacity: 0.5;",
        text: this.quantity
      });

      // Build card
      Game.market.append(this.row.hide());
      this.row.append(this.card);
      this.card.append(this.rowValign);
      this.rowValign
        .append(this.colSmallLeft)
        .append(this.colBigCenter)
        .append(this.colSmallRight);
      this.colSmallRight.append(this.picture);
      this.colSmallLeft.append(this.strongNumber);

      // Show card
      this.row.fadeIn('slow');

      this.check();

      return this;
    }

  }, options);
};

// Workers
// TODO rework workers cost
var Worker = function(options) {
  return $.extend({
    quantity: 0,
    increase: 1.11,

    button: undefined,
    card: undefined,

    check: function() {
      this.card.toggleClass('disabled', this.cost > Game.currency);
    },

    buy: function() {
      if (this.cost <= Game.currency) {
        Game.currency -= this.cost;

        // Update visuals
        this.quantity++;
        this.cost = Math.ceil(this.cost * this.increase);
        this.strongNumber.text(this.quantity);
        this.colBigCenter.html('' + this.name + '
 attach_money' + this.cost + '');

        Game.cps();
        Game.workload();
      };
    },

    init: function() {
      var self = this;
      var row = undefined;
      var card = undefined;
      var rowValign = undefined;
      var colSmallLeft = undefined;
      var picture = undefined;
      var colBigCenter = undefined;
      var content = undefined;
      var colSmallRight = undefined;
      var strongNumber = undefined;

      // Create card
      this.row = $('
', {
        class: "row"
      });
      this.card = $('
', {
        class: "card-panel hoverable flow-text superTooltipped noselect",
        "data-position": "right",
        "data-delay": "50",
        "data-tooltip": '
personWorkload +' + this.production + '
',
        click: function() {
          self.buy();
        }
      });
      this.rowValign = $('
', {
        class: "row valign-wrapper"
      });
      this.colSmallLeft = $('
', {
        class: "col s3"
      });
      this.picture = $('', {
        class: "circle responsive-img valign",
        src: "img/" + this.imgUrl
      });
      this.colBigCenter = $('
', {
        class: "col s7",
        html: '' + this.name + '
 attach_money' + this.cost + ''
      });
      this.colSmallRight = $('
', {
        class: "col s2"
      });
      this.strongNumber = $('', {
        class: "right",
        style: "opacity: 0.5;",
        text: this.quantity
      });

      // Build card
      Game.roster.append(this.row.hide());
      this.row.append(this.card);
      this.card.append(this.rowValign);
      this.rowValign
        .append(this.colSmallLeft)
        .append(this.colBigCenter)
        .append(this.colSmallRight);
      this.colSmallLeft.append(this.picture);
      this.colSmallRight.append(this.strongNumber);

      // Show card
      this.row.fadeIn('slow');

      this.check();

      return this;
    }

  }, options);
};

_companies = [{
  name: "Small company",
  costHistory: [4],
  production: 1,
  imgUrl: "default_company.png"
}, {
  name: "Medium company",
  costHistory: [12],
  production: 3,
  imgUrl: "default_company.png"
}, {
  name: "Public sector dpt.",
  costHistory: [32],
  production: 10,
  imgUrl: "default_company.png"
}, {
  name: "Big company",
  costHistory: [64],
  production: 25,
  imgUrl: "default_company.png"
}, {
  name: "International company",
  costHistory: [128],
  production: 54,
  imgUrl: "default_company.png"
}];

_workers = [{
  name: "Intern",
  cost: 10,
  production: 4,
  imgUrl: "default_worker.png"
}, {
  name: "Junior employee",
  cost: 20,
  production: 6,
  imgUrl: "default_worker.png"
}, {
  name: "Senior employee",
  cost: 50,
  production: 8,
  imgUrl: "default_worker.png"
},{
  name: "Subcontractor",
  cost: 75,
  production: 10,
  imgUrl: "default_worker.png"
},{
  name: "Contractor",
  cost: 100,
  production: 12,
  imgUrl: "default_worker.png"
}];

Game.init(_workers, _companies);

(function refreshUI() {
  Game._tick();
  setTimeout(refreshUI, 1000 / Game.inverval);
})();

// Test for adding objects to both arrays
$('#currency-display').click(function() {
  _workers.push({
    name: "H4k3r",
    cost: 20,
    production: 20,
    imgUrl: "kuroi.jpg"
  });
  Game.workers.push(Worker(_workers[_workers.length - 1]).init());
  $('.superTooltipped').superTooltip();

  _companies.push({
    name: "Micro$oft",
    costHistory: [1000],
    production: 500,
    imgUrl: "kuroi.jpg"
  });
  Game.companies.push(Company(_companies[_companies.length - 1]).init());
  $('.superTooltipped').superTooltip();
});
<commit_msg>Rework workers cost<commit_after>// _tick control
window.onfocus = function() {
  Game.inverval = 100;
};
window.onblur = function() {
  Game.inverval = 1;
};

// Game
var Game = {
  currency: 10,
  inverval: 100,
  workloadCounter: 0,

  // DOM elements
  count: undefined,
  roster: undefined,
  market: undefined,
  cpsDisplay: undefined,
  workloadDisplay: undefined,

  // Arrays
  workers: [],
  companies: [],

  // handle for setTimeout
  handle: undefined,

  init: function(_workers, _companies) {
    var self = this;

    this.count = $('#currency-display');
    this.roster = $('#roster-container');
    this.market = $('#market-container');
    this.cpsDisplay = $('#cps-display');
    this.workloadDisplay = $('#workload-display');

    $.each(_workers, function(index, _worker) {
      var newWorker = Worker(_worker).init();
      self.workers.push(newWorker);
    });

    $.each(_companies, function(index, _company) {
      var newCompany = Company(_company).init();
      self.companies.push(newCompany);
    });
    this.cps();
    this.workload();
  },

  _tick: function() {
    $.each(this.companies, function(index, company) {
      company.produce();
      company.check();
    });

    $.each(this.workers, function(index, worker) {
      worker.check();
    });

    this.count.text(this.currency.toFixed(2));
  },

  cps: function() {
    var cps = 0;
    $.each(this.companies, function(index, company) {
      cps += company.production * company.quantity;
    });

    this.cpsDisplay.text(cps);
  },

  workload: function() {
    var workload = 0;
    $.each(this.companies, function(index, company) {
      $.each(company.costHistory, function(cIndex, cost) {
        if (cIndex < company.quantity) {
          workload -= cost;
        }
      });
    });

    $.each(this.workers, function(index, worker) {
      workload += worker.production * worker.quantity;
    });

    this.workloadDisplay.text(workload);
    this.workloadCounter = workload;

    return workload;
  }
};

var Company = function(options) {
  return $.extend({
    quantity: 0,
    increase: 1.15,

    cost: function() {
      return Math.ceil(this.costHistory[this.quantity] * this.increase);
    },

    button: undefined,
    title: undefined,

    produce: function() {
      Game.currency += this.quantity * this.production / Game.inverval;
    },

    check: function() {
      this.card.toggleClass('disabled', this.costHistory[this.quantity] > Game.workloadCounter);
    },

    buy: function() {
      if (this.costHistory[this.quantity] <= Game.workload()) {

        this.costHistory.push(this.cost());
        this.quantity++;

        // Update visuals
        this.strongNumber.text(this.quantity);
        this.colBigCenter.html('' + this.name + '
 person' + this.costHistory[this.quantity] + '');
        Game.cps();
        Game.workload();
      };
    },

    init: function() {
      var self = this;
      var row = undefined;
      var card = undefined;
      var rowValign = undefined;
      var colSmallLeft = undefined;
      var picture = undefined;
      var colBigCenter = undefined;
      var content = undefined;
      var colSmallRight = undefined;
      var strongNumber = undefined;

      // Create card
      this.row = $('
', {
        class: "row"
      });
      this.card = $('
', {
        class: "card-panel hoverable flow-text superTooltipped noselect",
        "data-position": "left",
        "data-delay": "50",
        "data-tooltip": '
attach_moneyIncome +' + this.production + '/s
',
        click: function() {
          self.buy();
        }
      });
      this.rowValign = $('
', {
        class: "row valign-wrapper"
      });
      this.colSmallLeft = $('
', {
        class: "col s2"
      });
      this.picture = $('', {
        class: "circle responsive-img valign",
        src: "img/" + this.imgUrl
      });
      this.colBigCenter = $('
', {
        class: "col s7",
        html: '' + this.name + '
 person' + this.costHistory[this.quantity] + ''
      });
      this.colSmallRight = $('
', {
        class: "col s3"
      });
      this.strongNumber = $('', {
        class: "left",
        style: "opacity: 0.5;",
        text: this.quantity
      });

      // Build card
      Game.market.append(this.row.hide());
      this.row.append(this.card);
      this.card.append(this.rowValign);
      this.rowValign
        .append(this.colSmallLeft)
        .append(this.colBigCenter)
        .append(this.colSmallRight);
      this.colSmallRight.append(this.picture);
      this.colSmallLeft.append(this.strongNumber);

      // Show card
      this.row.fadeIn('slow');

      this.check();

      return this;
    }

  }, options);
};

// Workers
var Worker = function(options) {
  return $.extend({
    quantity: 0,
    increase: 1.11,

    cost: function() {
      return Math.ceil(this.costHistory[this.quantity] * this.increase);
    },

    button: undefined,
    card: undefined,

    check: function() {
      this.card.toggleClass('disabled', this.costHistory[this.quantity] > Game.currency);
    },

    buy: function() {
      if (this.costHistory[this.quantity] <= Game.currency) {

        this.costHistory.push(this.cost());
        Game.currency -= this.costHistory[this.quantity];
        this.quantity++;

        // Update visuals
        this.strongNumber.text(this.quantity);
        this.colBigCenter.html('' + this.name + '
 attach_money' + this.costHistory[this.quantity] + '');

        Game.cps();
        Game.workload();
      };
    },

    init: function() {
      var self = this;
      var row = undefined;
      var card = undefined;
      var rowValign = undefined;
      var colSmallLeft = undefined;
      var picture = undefined;
      var colBigCenter = undefined;
      var content = undefined;
      var colSmallRight = undefined;
      var strongNumber = undefined;

      // Create card
      this.row = $('
', {
        class: "row"
      });
      this.card = $('
', {
        class: "card-panel hoverable flow-text superTooltipped noselect",
        "data-position": "right",
        "data-delay": "50",
        "data-tooltip": '
personWorkload +' + this.production + '
',
        click: function() {
          self.buy();
        }
      });
      this.rowValign = $('
', {
        class: "row valign-wrapper"
      });
      this.colSmallLeft = $('
', {
        class: "col s3"
      });
      this.picture = $('', {
        class: "circle responsive-img valign",
        src: "img/" + this.imgUrl
      });
      this.colBigCenter = $('
', {
        class: "col s7",
        html: '' + this.name + '
 attach_money' + this.costHistory[this.quantity] + ''
      });
      this.colSmallRight = $('
', {
        class: "col s2"
      });
      this.strongNumber = $('', {
        class: "right",
        style: "opacity: 0.5;",
        text: this.quantity
      });

      // Build card
      Game.roster.append(this.row.hide());
      this.row.append(this.card);
      this.card.append(this.rowValign);
      this.rowValign
        .append(this.colSmallLeft)
        .append(this.colBigCenter)
        .append(this.colSmallRight);
      this.colSmallLeft.append(this.picture);
      this.colSmallRight.append(this.strongNumber);

      // Show card
      this.row.fadeIn('slow');

      this.check();

      return this;
    }

  }, options);
};

_companies = [{
  name: "Small company",
  costHistory: [4],
  production: 1,
  imgUrl: "default_company.png"
}, {
  name: "Medium company",
  costHistory: [12],
  production: 3,
  imgUrl: "default_company.png"
}, {
  name: "Public sector dpt.",
  costHistory: [32],
  production: 10,
  imgUrl: "default_company.png"
}, {
  name: "Big company",
  costHistory: [64],
  production: 25,
  imgUrl: "default_company.png"
}, {
  name: "International company",
  costHistory: [128],
  production: 54,
  imgUrl: "default_company.png"
}];

_workers = [{
  name: "Intern",
  costHistory: [10],
  production: 4,
  imgUrl: "default_worker.png"
}, {
  name: "Junior employee",
  costHistory: [20],
  production: 6,
  imgUrl: "default_worker.png"
}, {
  name: "Senior employee",
  costHistory: [50],
  production: 8,
  imgUrl: "default_worker.png"
},{
  name: "Subcontractor",
  costHistory: [75],
  production: 10,
  imgUrl: "default_worker.png"
},{
  name: "Contractor",
  costHistory: [100],
  production: 12,
  imgUrl: "default_worker.png"
}];

Game.init(_workers, _companies);

(function refreshUI() {
  Game._tick();
  setTimeout(refreshUI, 1000 / Game.inverval);
})();

// Test for adding objects to both arrays
$('#currency-display').click(function() {
  _workers.push({
    name: "H4k3r",
    costHistory: [20],
    production: 20,
    imgUrl: "kuroi.jpg"
  });
  Game.workers.push(Worker(_workers[_workers.length - 1]).init());
  $('.superTooltipped').superTooltip();

  _companies.push({
    name: "Micro$oft",
    costHistory: [1000],
    production: 500,
    imgUrl: "kuroi.jpg"
  });
  Game.companies.push(Company(_companies[_companies.length - 1]).init());
  $('.superTooltipped').superTooltip();
});
<|endoftext|>


<commit_before>var gsbn = {

    slideWidth : null,
    dragging : false,

    // init: add message listeners and call the appropriate function based on the request
    init : function() {

      // If we already setup the resizing on this page, do nothing
      if (window.top.document.body.getAttribute("slide-resize-js") != null) {
        return;
      }

	    // Make sure this is the Speaker Notes tab
      if (!window.top.location.pathname.startsWith('/presentation/') || !window.top.location.pathname.endsWith('/present')) {
        return;
      }

      window.top.document.body.setAttribute("slide-resize-js", true);

      var getOptsResp = function(opts) {
        gsbn.addJS(opts);
      }
      gsbn.getOptions(getOptsResp);
    },

    addJS : function(opts) {
        // Run this JavaScript code in the Speaker Notes window
        // (I'm on Chrome on Windows so I press F12 to bring up the Developer Tools, go to Console, and run it there)
        var notesMaxWidth = parseInt(opts.notesMaxWidth) || gsbnCommon.defaultOpts.notesMaxWidth;
        var resizeSlidesRuleCount = 1;

        // The core logic to resize the slides
        var resizeSlides = function() {

          // Resize the current slide
          var fullWidth = window.top.innerWidth;
          if (gsbn.slideWidth === null) {
            var slideWidth = (fullWidth < notesMaxWidth * 2) ? fullWidth / 2 : fullWidth - notesMaxWidth;
          } else {
            var slideWidth = gsbn.slideWidth;
          }
          var sheet = window.top.document.styleSheets[0];
          sheet.insertRule(
            ".punch-viewer-speakernotes-side-panel," +
            ".punch-viewer-speakernotes-page-container," +
            ".punch-viewer-speakernotes-page," +
            ".punch-viewer-speakernotes-page > svg {" +
            "  width: " + slideWidth + "px !important; " +
            "  height:auto !important;" +
            "}", resizeSlidesRuleCount++);
          sheet.insertRule(
            ".punch-viewer-speakernotes-text-body-scrollable { position: static !important; }",
            resizeSlidesRuleCount++);
	        sheet.insertRule(
	          ".punch-viewer-speaker-qanda-content { position: static !important; }",
	          resizeSlidesRuleCount++);
	        sheet.insertRule(
	          ".punch-viewer-speaker-questions,.punch-viewer-speaker-series-list, .punch-viewer-speaker-series-intro-container, .punch-viewer-speaker-qanda-not-available { position: static !important; }",
	          resizeSlidesRuleCount++);
          sheet.insertRule(
            ".punch-viewer-speakernotes-timer-panel { position: fixed !important; }",
            resizeSlidesRuleCount++);
          sheet.insertRule(
            ".punch-viewer-speakernotes-text-body-scrollable, .punch-viewer-speakernotes-base { height: 100% !important; }",
            resizeSlidesRuleCount++);
          sheet.insertRule(
            "body[gsbn-dragging=true]{ cursor: e-resize; }",
            resizeSlidesRuleCount++);

          // Resize the next slide
          if (opts.nextSlide) {
            sheet.insertRule(
              ".punch-viewer-speakernotes-page-previous { vertical-align: top !important; }",
              resizeSlidesRuleCount++);

            var mainSlide = window.top.document.getElementsByClassName("punch-viewer-speakernotes-page-container")[0];
            var nextSlide = window.top.document.getElementsByClassName("punch-viewer-speakernotes-page-next")[0];
            var prevSlide = window.top.document.getElementsByClassName("punch-viewer-speakernotes-page-previous")[0];
            var ratio = mainSlide.scrollHeight / mainSlide.scrollWidth;

            var nextSlideWidth = slideWidth - prevSlide.offsetWidth -
                                 parseInt(window.top.getComputedStyle(prevSlide).marginRight) -
                                 parseInt(window.top.getComputedStyle(nextSlide).marginLeft) - 10;
            var nextSlideHeight = nextSlideWidth * ratio;
            sheet.insertRule(
              ".punch-viewer-speakernotes-page-next," +
              ".punch-viewer-speakernotes-page-next > iframe {" +
              "  width: " + nextSlideWidth + "px !important;" +
              "  height: " + nextSlideHeight + "px !important;" +
              "}",
              resizeSlidesRuleCount++
            );
            var nextSlideIFrame = nextSlide.getElementsByTagName("iframe")[0].contentWindow;
            if (nextSlideIFrame.document.getElementById("gsbn-next-style") != null) {
              nextSlideIFrame.document.getElementById("gsbn-next-style").remove();
            }
            style = nextSlideIFrame.document.createElement("STYLE");
            style.setAttribute('id', 'gsbn-next-style');
            style.setAttribute('type', 'text/css');
            style.innerHTML = ".punch-viewer-speakernotes-page, .punch-viewer-speakernotes-page svg {" +
                              "  width: " + nextSlideWidth + "px !important;" +
                              "  height: " + nextSlideHeight + "px !important; }";
            nextSlideIFrame.document.head.insertBefore(style, nextSlideIFrame.document.head.childNodes[0]);
          }
        };

        // Resize on page load and whenever the window is resized
        if (opts.autoResize) {
          window.top.onresize = resizeSlides;
          resizeSlides();
        }

        // Add a draggable element that allows the user to manually resize the windows
        var newItem = window.top.document.createElement("TD");
        newItem.setAttribute('id', 'gsbn-draggable');
        newItem.setAttribute('style', 'width: 5px; background: #666; cursor: e-resize; z-index: 10; position: relative;}');
        var mainPanel = window.top.document.getElementsByClassName("punch-viewer-speakernotes-main-panel")[0];
        mainPanel.parentNode.insertBefore(newItem, mainPanel);

        window.top.document.getElementById("gsbn-draggable").addEventListener("mousedown", function(ev){
          gsbn.dragging = true;
          window.top.document.getElementsByTagName('body')[0].setAttribute('gsbn-dragging', true);
        });
        window.top.document.addEventListener("mouseup", function(ev){
          gsbn.dragging = false;
          window.top.document.getElementsByTagName('body')[0].setAttribute('gsbn-dragging', false);
        });
        var mainSlidePanel = window.top.document.getElementsByClassName("punch-viewer-speakernotes-page-control")[0];
        var mainSlidePaddings = parseInt(window.top.getComputedStyle(mainSlidePanel).paddingLeft) +
                                parseInt(window.top.getComputedStyle(mainSlidePanel).paddingRight);
        window.top.document.addEventListener("mousemove", function(ev){
          if (!gsbn.dragging) return;
          gsbn.slideWidth = ev.clientX - mainSlidePaddings;
          resizeSlides();
        });
    },

    getOptions : function(cb) {
      chrome.storage.sync.get(gsbnCommon.defaultOpts, cb);
    }
}

gsbn.init();
<commit_msg>Fix speakernotes<commit_after>var gsbn = {

    slideWidth : null,
    dragging : false,

    // init: add message listeners and call the appropriate function based on the request
    init : function() {

      // If we already setup the resizing on this page, do nothing
      if (window.top.document.body.getAttribute("slide-resize-js") != null) {
        return;
      }

	    // Make sure this is the Speaker Notes tab
      if (!window.top.location.pathname.startsWith('/presentation/') || !window.top.location.pathname.endsWith('/present')) {
        return;
      }

      window.top.document.body.setAttribute("slide-resize-js", true);

      var getOptsResp = function(opts) {
        gsbn.addJS(opts);
      }
      gsbn.getOptions(getOptsResp);
    },

    addJS : function(opts) {
        // Run this JavaScript code in the Speaker Notes window
        // (I'm on Chrome on Windows so I press F12 to bring up the Developer Tools, go to Console, and run it there)
        var notesMaxWidth = parseInt(opts.notesMaxWidth) || gsbnCommon.defaultOpts.notesMaxWidth;
        var resizeSlidesRuleCount = 1;

        // The core logic to resize the slides
        var resizeSlides = function() {

          // Resize the current slide
          var fullWidth = window.top.innerWidth;
          if (gsbn.slideWidth === null) {
            var slideWidth = (fullWidth < notesMaxWidth * 2) ? fullWidth / 2 : fullWidth - notesMaxWidth;
          } else {
            var slideWidth = gsbn.slideWidth;
          }
          var sheet = window.top.document.styleSheets[0];
          sheet.insertRule(
            ".punch-viewer-speakernotes-side-panel," +
            ".punch-viewer-speakernotes-page-container," +
            ".punch-viewer-speakernotes-page," +
            ".punch-viewer-speakernotes-page > svg {" +
            "  width: " + slideWidth + "px !important; " +
            "  height:auto !important;" +
            "}", resizeSlidesRuleCount++);
          sheet.insertRule(
            ".punch-viewer-speakernotes-text-body-scrollable { position: static !important; }",
            resizeSlidesRuleCount++);
	        sheet.insertRule(
	          ".punch-viewer-speaker-qanda-content { position: static !important; }",
	          resizeSlidesRuleCount++);
	        sheet.insertRule(
	          ".punch-viewer-speaker-questions,.punch-viewer-speaker-series-list, .punch-viewer-speaker-series-intro-container, .punch-viewer-speaker-qanda-not-available { position: static !important; }",
	          resizeSlidesRuleCount++);
          sheet.insertRule(
            ".punch-viewer-speakernotes-timer-panel { position: fixed !important; }",
            resizeSlidesRuleCount++);
          sheet.insertRule(
            ".punch-viewer-speakernotes-text-body-scrollable, .punch-viewer-speakernotes-base { height: 100% !important; }",
            resizeSlidesRuleCount++);
          sheet.insertRule(
            "body[gsbn-dragging=true]{ cursor: e-resize; }",
            resizeSlidesRuleCount++);
	  sheet.insertRule(
	    "punch-viewer-speaker-empty-questions { position: static; }");
          // Resize the next slide
          if (opts.nextSlide) {
            sheet.insertRule(
              ".punch-viewer-speakernotes-page-previous { vertical-align: top !important; }",
              resizeSlidesRuleCount++);

            var mainSlide = window.top.document.getElementsByClassName("punch-viewer-speakernotes-page-container")[0];
            var nextSlide = window.top.document.getElementsByClassName("punch-viewer-speakernotes-page-next")[0];
            var prevSlide = window.top.document.getElementsByClassName("punch-viewer-speakernotes-page-previous")[0];
            var ratio = mainSlide.scrollHeight / mainSlide.scrollWidth;

            var nextSlideWidth = slideWidth - prevSlide.offsetWidth -
                                 parseInt(window.top.getComputedStyle(prevSlide).marginRight) -
                                 parseInt(window.top.getComputedStyle(nextSlide).marginLeft) - 10;
            var nextSlideHeight = nextSlideWidth * ratio;
            sheet.insertRule(
              ".punch-viewer-speakernotes-page-next," +
              ".punch-viewer-speakernotes-page-next > iframe {" +
              "  width: " + nextSlideWidth + "px !important;" +
              "  height: " + nextSlideHeight + "px !important;" +
              "}",
              resizeSlidesRuleCount++
            );
            var nextSlideIFrame = nextSlide.getElementsByTagName("iframe")[0].contentWindow;
            if (nextSlideIFrame.document.getElementById("gsbn-next-style") != null) {
              nextSlideIFrame.document.getElementById("gsbn-next-style").remove();
            }
            style = nextSlideIFrame.document.createElement("STYLE");
            style.setAttribute('id', 'gsbn-next-style');
            style.setAttribute('type', 'text/css');
            style.innerHTML = ".punch-viewer-speakernotes-page, .punch-viewer-speakernotes-page svg {" +
                              "  width: " + nextSlideWidth + "px !important;" +
                              "  height: " + nextSlideHeight + "px !important; }";
            nextSlideIFrame.document.head.insertBefore(style, nextSlideIFrame.document.head.childNodes[0]);
          }
        };

        // Resize on page load and whenever the window is resized
        if (opts.autoResize) {
          window.top.onresize = resizeSlides;
          resizeSlides();
        }

        // Add a draggable element that allows the user to manually resize the windows
        var newItem = window.top.document.createElement("TD");
        newItem.setAttribute('id', 'gsbn-draggable');
        newItem.setAttribute('style', 'width: 5px; background: #666; cursor: e-resize; z-index: 10; position: relative;}');
        var mainPanel = window.top.document.getElementsByClassName("punch-viewer-speakernotes-main-panel")[0];
        mainPanel.parentNode.insertBefore(newItem, mainPanel);

        window.top.document.getElementById("gsbn-draggable").addEventListener("mousedown", function(ev){
          gsbn.dragging = true;
          window.top.document.getElementsByTagName('body')[0].setAttribute('gsbn-dragging', true);
        });
        window.top.document.addEventListener("mouseup", function(ev){
          gsbn.dragging = false;
          window.top.document.getElementsByTagName('body')[0].setAttribute('gsbn-dragging', false);
        });
        var mainSlidePanel = window.top.document.getElementsByClassName("punch-viewer-speakernotes-page-control")[0];
        var mainSlidePaddings = parseInt(window.top.getComputedStyle(mainSlidePanel).paddingLeft) +
                                parseInt(window.top.getComputedStyle(mainSlidePanel).paddingRight);
        window.top.document.addEventListener("mousemove", function(ev){
          if (!gsbn.dragging) return;
          gsbn.slideWidth = ev.clientX - mainSlidePaddings;
          resizeSlides();
        });
    },

    getOptions : function(cb) {
      chrome.storage.sync.get(gsbnCommon.defaultOpts, cb);
    }
}

gsbn.init();
<|endoftext|>


<commit_before>'use strict';

/*
 * фильтр для локализации.
 * использование:
 *
 *  обычный текст:
 *  - {{'Привет, мир'|i18n}}
 *    в файле locales.js:
 *    var _locales = { 'ru-ru': { 'Привет, мир': 'Привет, мир' }, 'en-us': { 'Привет, мир': 'Hello, world' } };
 *
 *  переменные:
 *  - {{'%1 яблоко. Весёлый %2'|i18n:'Красное':'мальчик'}}
 *    в файле locales.js:
 *    var _locales = { 'ru-ru': { '%1 яблоко. Весёлый %2': '%1 яблоко. Весёлый %2' }, 'en-us': { '%1 яблоко. Весёлый %2': 'Apple is %1. Happy %2' } };
 *
 *  склонения:
 *  - {{'Всего %1 яблоко в %2 корзине'|i18n:'plural':4:'моей'}}
 *    в файле locales.js:
 *    var _locales = {
 *        'ru-ru': {
 *            'Всего %1 яблоко в %2 корзине': [
 *                'Всего %1 яблоко в %2 корзине',
 *                'Всего %1 яблока в %2 корзине',
 *                'Всего %1 яблок в %2 корзине'
 *            ]
 *        },
 *        'en-us': {
 *            'Всего %1 яблоко в %2 корзине': [
 *                'There is %1 apple in %2 basket',
 *                'There are %1 apples in %2 basket',
 *            ]
 *        }
 *    }
 *
 *  в js:
 *  - $filter('i18n')('Строка в js');
 *    в файле locales.js:
 *    var _locales = { 'ru-ru': { 'Строка в js': 'Строка в js' }, 'en-us': { 'Строка в js': 'String in js' } };
 *
 *  - $filter('i18n')('Текущая локаль: %1', $locale.id);
 *    var _locales = { 'ru-ru': { 'Текущая локаль: %1': 'Текущая локаль: %1' }, 'en-us': { 'Текущая локаль: %1': 'Current locale: %1' } };
 *
 */

angular.module('tanzFilters', []);

angular.module('tanzFilters', []).filter('i18n', function($locale) {
	return function(str) {
		var offset = 1;
		if (arguments[1] && arguments[1] === 'plural') {
			var n = arguments[2],
					plural;

			switch ($locale.id) {
				case 'en-us':
					plural = 0 + (n != 1);
					break;
				case 'ru-ru':
					plural = (n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
					break;
				default:
					plural = 0 + (n != 1);
			}

			str = _locales[$locale.id][str][plural] || str;
			offset = 2;
		} else {
			str = _locales[$locale.id][str] || str;
		}

		for (var i = offset; i < arguments.length; i++) {
			str = str.split('%' + (i - offset + 1)).join(arguments[i]);
		}

		return str;
	}
});<commit_msg>arabic, german and spanish locales support<commit_after>'use strict';

/*
 * фильтр для локализации.
 * использование:
 *
 *  обычный текст:
 *  - {{'Привет, мир'|i18n}}
 *    в файле locales.js:
 *    var _locales = { 'ru-ru': { 'Привет, мир': 'Привет, мир' }, 'en-us': { 'Привет, мир': 'Hello, world' } };
 *
 *  переменные:
 *  - {{'%1 яблоко. Весёлый %2'|i18n:'Красное':'мальчик'}}
 *    в файле locales.js:
 *    var _locales = { 'ru-ru': { '%1 яблоко. Весёлый %2': '%1 яблоко. Весёлый %2' }, 'en-us': { '%1 яблоко. Весёлый %2': 'Apple is %1. Happy %2' } };
 *
 *  склонения:
 *  - {{'Всего %1 яблоко в %2 корзине'|i18n:'plural':4:'моей'}}
 *    в файле locales.js:
 *    var _locales = {
 *        'ru-ru': {
 *            'Всего %1 яблоко в %2 корзине': [
 *                'Всего %1 яблоко в %2 корзине',
 *                'Всего %1 яблока в %2 корзине',
 *                'Всего %1 яблок в %2 корзине'
 *            ]
 *        },
 *        'en-us': {
 *            'Всего %1 яблоко в %2 корзине': [
 *                'There is %1 apple in %2 basket',
 *                'There are %1 apples in %2 basket',
 *            ]
 *        }
 *    }
 *
 *  в js:
 *  - $filter('i18n')('Строка в js');
 *    в файле locales.js:
 *    var _locales = { 'ru-ru': { 'Строка в js': 'Строка в js' }, 'en-us': { 'Строка в js': 'String in js' } };
 *
 *  - $filter('i18n')('Текущая локаль: %1', $locale.id);
 *    var _locales = { 'ru-ru': { 'Текущая локаль: %1': 'Текущая локаль: %1' }, 'en-us': { 'Текущая локаль: %1': 'Current locale: %1' } };
 *
 */

angular.module('tanzFilters', []);

angular.module('tanzFilters', []).filter('i18n', function($locale) {
	return function(str) {
		var offset = 1;
		if (arguments[1] && arguments[1] === 'plural') {
			var n = arguments[2],
					plural;

			switch ($locale.id) {
				case 'en-us':
				case 'de-de':
				case 'es-es':
					plural = 0 + (n != 1);
					break;
				case 'ru-ru':
					plural = (n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
					break;
				case 'ar':
					plural = n == 0 ? 0 : n == 1 ? 1 : n == 2 ? 2 : n % 100 >= 3 && n % 100 <= 10 ? 3 : n % 100 >= 11 ? 4 : 5;
				default:
					plural = 0 + (n != 1);
			}

			str = _locales[$locale.id][str][plural] || str;
			offset = 2;
		} else {
			str = _locales[$locale.id][str] || str;
		}

		for (var i = offset; i < arguments.length; i++) {
			str = str.split('%' + (i - offset + 1)).join(arguments[i]);
		}

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


<commit_before>(function($){
  $(function(){

    $('.button-collapse').sideNav();

  }); // end of document ready
})(jQuery); // end of jQuery name space

document.querySelectorAll('a[href^="#_"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
        e.preventDefault();

        document.querySelector(this.getAttribute('href')).scrollIntoView({
            behavior: 'smooth',
            block: 'start'
        });
    });
});

(function ($) {
$(document).ready(function() {

  $(document).on('click.card', '.card', function (e) {
    if ($(this).find('> .card-reveal').length) {
      if ($(e.target).is($('.card-reveal .card-title')) || $(e.target).is($('.card-reveal .card-title i'))) {
        // Make Reveal animate down and display none
        $(this).find('.card-reveal').velocity(
          {translateY: 0}, {
            duration: 225,
            queue: false,
            easing: 'easeInOutQuad',
            complete: function() { $(this).css({ display: 'none'}); }
          }
        );
        $(this).find('.card-content>span').attr('style', '');
      }
      else if ($(e.target).is($('.card .activator')) ||
               $(e.target).is($('.card .activator i')) ) {
        $(e.target).closest('.card').css('overflow', 'hidden');
        $(this).find('.card-reveal').css({ display: 'block'}).velocity("stop", false).velocity({translateY: '-100%'}, {duration: 300, queue: false, easing: 'easeInOutQuad'});
        $(this).find('.card-content>span').attr('style', 'color: rgba(0,0,0,0) !important');
      }
    }

    $('.card-reveal').closest('.card').css('overflow', 'hidden');

  });

   // Make Reveal animate up and display when mouseenter
  $(document).on('mouseenter.hover-reveal','.hover-reveal', function (e){
    $(e.target).closest('.card').css('overflow', 'hidden');
    $(this).find('.card-content>span').attr('style', 'color: rgba(0,0,0,0) !important');
    $(this).find('.card-reveal').css({ display: 'block'})
      .velocity("stop", false)
      .velocity({translateY: '-100%'},
      {duration: 300,
       queue: false,
       easing: 'easeInOutQuad'});
  });

  // Make Reveal animate down and display none when mouseleave
  $(document).on('mouseleave.hover-reveal','.hover-reveal', function (e){
    $(this).find('.card-reveal').velocity(
      {translateY: 0}, {
        duration: 225,
        queue: false,
        easing: 'easeInOutQuad',
        complete: function() { $(this).css({ display: 'none'}); }
      }
    );
    $(this).find('.card-content>span').attr('style', '');
  });

  $('li').on('click', function(){
      var clicked = $(this);
      $('li').each(function(){
          if($(this).hasClass('active')){
              $(this).removeClass('active');
          }
      });
      $(this).addClass('active');
  });

  $(window).scroll(function() {
    var div;
    if ($(this).scrollTop() + $(window).height() >= $('#_about').offset().top) {
      div = $('#nav-list > :eq(0)')[0];
    }
    if ($(this).scrollTop() + $(window).height() >= $('#_work_experience').offset().top) {
      div = $('#nav-list > :eq(1)')[0];
    }
    if ($(this).scrollTop() + $(window).height() >= $('#_projects').offset().top) {
      div = $('#nav-list > :eq(2)')[0];
    }
    if ($(this).scrollTop() + $(window).height() >= $('#_education').offset().top) {
      div = $('#nav-list > :eq(3)')[0];
    }
    // if ($(this).scrollTop() >= $('#_contact').offset().top - 100) {
    //   div = $('#nav-list > :eq(4)')[0];
    // }

    $('li').each(function(){
        if($(this).hasClass('active')){
            $(this).removeClass('active');
        }
    });
    $(div).addClass('active');
  });

  $(".dropdown-trigger").dropdown();

});
}( jQuery ));
<commit_msg>some mobile fixes but still gotta figure out why dropdown doeesn't vanish<commit_after>(function($){
  $(function(){

    $('.button-collapse').sideNav();

  }); // end of document ready
})(jQuery); // end of jQuery name space

document.querySelectorAll('a[href^="#_"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
        e.preventDefault();

        document.querySelector(this.getAttribute('href')).scrollIntoView({
            behavior: 'smooth',
            block: 'start'
        });
    });
});

(function ($) {
$(document).ready(function() {

  $(document).on('click.card', '.card', function (e) {
    if ($(this).find('> .card-reveal').length) {
      if ($(e.target).is($('.card-reveal .card-title')) || $(e.target).is($('.card-reveal .card-title i'))) {
        // Make Reveal animate down and display none
        $(this).find('.card-reveal').velocity(
          {translateY: 0}, {
            duration: 225,
            queue: false,
            easing: 'easeInOutQuad',
            complete: function() { $(this).css({ display: 'none'}); }
          }
        );
        $(this).find('.card-content>span').attr('style', '');
      }
      else if ($(e.target).is($('.card .activator')) ||
               $(e.target).is($('.card .activator i')) ) {
        $(e.target).closest('.card').css('overflow', 'hidden');
        $(this).find('.card-reveal').css({ display: 'block'}).velocity("stop", false).velocity({translateY: '-100%'}, {duration: 300, queue: false, easing: 'easeInOutQuad'});
        $(this).find('.card-content>span').attr('style', 'color: rgba(0,0,0,0) !important');
      }
    }

    $('.card-reveal').closest('.card').css('overflow', 'hidden');

  });

   // Make Reveal animate up and display when mouseenter
  $(document).on('mouseenter.hover-reveal','.hover-reveal', function (e){
    $(e.target).closest('.card').css('overflow', 'hidden');
    $(this).find('.card-content>span').attr('style', 'color: rgba(0,0,0,0) !important');
    $(this).find('.card-reveal').css({ display: 'block'})
      .velocity("stop", false)
      .velocity({translateY: '-100%'},
      {duration: 300,
       queue: false,
       easing: 'easeInOutQuad'});
  });

  // Make Reveal animate down and display none when mouseleave
  $(document).on('mouseleave.hover-reveal','.hover-reveal', function (e){
    $(this).find('.card-reveal').velocity(
      {translateY: 0}, {
        duration: 225,
        queue: false,
        easing: 'easeInOutQuad',
        complete: function() { $(this).css({ display: 'none'}); }
      }
    );
    $(this).find('.card-content>span').attr('style', '');
  });

  $('li').on('click', function(){
      var clicked = $(this);
      $('li').each(function(){
          if($(this).hasClass('active')){
              $(this).removeClass('active');
          }
      });
      $(this).addClass('active');
  });

  $(window).scroll(function() {
    var div_desktop;
    var div_mobile;
    if ($(this).scrollTop() + $(window).height() >= $('#_about').offset().top) {
      div_desktop = $('#nav-list > :eq(0)')[0];
      div_mobile = $('#nav-mobile > :eq(0)')[0];
    }
    if ($(this).scrollTop() + $(window).height() >= $('#_work_experience').offset().top) {
      div_desktop = $('#nav-list > :eq(1)')[0];
      div_mobile = $('#nav-mobile > :eq(1)')[0];
    }
    if ($(this).scrollTop() + $(window).height() >= $('#_projects').offset().top) {
      div_desktop = $('#nav-list > :eq(2)')[0];
      div_mobile = $('#nav-mobile > :eq(2)')[0];
    }
    if ($(this).scrollTop() + $(window).height() >= $('#_education').offset().top) {
      div_desktop = $('#nav-list > :eq(3)')[0];
      div_mobile = $('#nav-mobile > :eq(3)')[0];
    }
    // if ($(this).scrollTop() >= $('#_contact').offset().top - 100) {
    //   div = $('#nav-list > :eq(4)')[0];
    // }

    $('li').each(function(){
        if($(this).hasClass('active')){
            $(this).removeClass('active');
        }
    });
    $(div_desktop).addClass('active');
    $(div_mobile).addClass('active');
  });

  $("#nav-mobile-button").dropdown({"closeOnClick": false});

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


<commit_before>$(function(){

  "use strict";

  // Preloader
  $( window ).load(function() {
      $("#loading-img").fadeOut();
      $("#preloader").delay(400).fadeOut("slow");
  });

  $(document).ready(function(){

    // Create launch date for ticker
    // Date below denotes 10 January, 2015
    $(function () {
      var launchDay = new Date(2015, 1-1, 10);
      $('#ticker').countdown({
        until: launchDay
      });
    });

    // SVG Fallback for older browsers
    $(function() {
      if (!Modernizr.svg) {
        $(".logo img").attr('src', function(index, attr) {
          return attr.replace('svg', 'png');
        });
      }
    });

    // Placeholder initialise
    $('input, textarea').placeholder();

  });

});

<commit_msg>Update init.js<commit_after>$(function(){

  "use strict";

  // Preloader
  $( window ).load(function() {
      $("#loading-img").fadeOut();
      $("#preloader").delay(400).fadeOut("slow");
  });

  $(document).ready(function(){

    // Create launch date for ticker
    // Date below denotes 10 January, 2015
    $(function () {
      var launchDay = new Date(2015, 6, 10);
      $('#ticker').countdown({
        until: launchDay
      });
    });

    // SVG Fallback for older browsers
    $(function() {
      if (!Modernizr.svg) {
        $(".logo img").attr('src', function(index, attr) {
          return attr.replace('svg', 'png');
        });
      }
    });

    // Placeholder initialise
    $('input, textarea').placeholder();

  });

});

<|endoftext|>