<commit_before>'use strict';

require('../qunit_extensions');

var documentStoreSeed = require('../../fixtures/collab/documentStoreSeed');
var changeStoreSeed = require('../../fixtures/collab/changeStoreSeed');
var DocumentStore = require('../../../collab/DocumentStore');
var ChangeStore = require('../../../collab/ChangeStore');
var DocumentEngine = require('../../../collab/DocumentEngine');
var twoParagraphs = require('../../fixtures/collab/two-paragraphs');
var insertParagraph = require('../../fixtures/collab/insertParagraph');
var insertText = require('../../fixtures/collab/insertText');
var CollabEngine = require('../../../collab/CollabEngine');

// Equivalent to the 'test-doc' that is in the backendseed.
var testDoc = twoParagraphs.createArticle();

// Example changes should be something that depends on existing content, so we
// properly play the rebase scenario
var exampleChange = insertParagraph(testDoc);

var documentStore = new DocumentStore();
var changeStore = new ChangeStore();

var documentEngine = new DocumentEngine({
  documentStore: documentStore,
  changeStore: changeStore,
  schemas: {
    'prose-article': {
      name: 'prose-article',
      version: '1.0.0',
      documentFactory: twoParagraphs
    }
  }
});

var fakeChange = {
  before: {
    selection: null
  },
  after: {
    selection: null,
  },
  ops: []
};

var collabEngine;

QUnit.module('collab/CollabEngine', {
  beforeEach: function(assert) {
    var done = assert.async();
    var newDocumentStoreSeed = JSON.parse(JSON.stringify(documentStoreSeed));
    var newChangeStoreSeed = JSON.parse(JSON.stringify(changeStoreSeed));
    documentStore.seed(newDocumentStoreSeed, function(err) {
      if (err) return console.error(err);
      changeStore.seed(newChangeStoreSeed, function(err) {
        if (err) return console.error(err);
        collabEngine = new CollabEngine(documentEngine);
        done();
      });
    });
  }
});

QUnit.test('New collaborator enters with latest version', function(assert) {
  var done = assert.async();

  collabEngine.connect({
    collaboratorId: 'collab-1',
    documentId: 'test-doc',
    version: 1,
    change: fakeChange
  }, function(err, result) {
    assert.isNullOrUndefined(err, 'Should not error');
    assert.equal(result.version, 1);
    assert.equal(result.changes.length, 0);
    done();
  });
});

QUnit.test('New collaborator enters with an outdated version', function(assert) {
  var done = assert.async();

  collabEngine.connect({
    collaboratorId: 'collab-1',
    documentId: 'test-doc',
    version: 0,
    change: fakeChange
  }, function(err, result) {
    assert.isNullOrUndefined(err, 'Should not error');
    assert.equal(result.version, 1);
    assert.equal(result.changes.length, 1);
    done();
  });
});

QUnit.test('New collaborator enters with a new fast-forward change', function(assert) {
  var done = assert.async();

  collabEngine.connect({
    collaboratorId: 'collab-1',
    documentId: 'test-doc',
    version: 1,
    change: exampleChange
  }, function(err, result) {
    assert.isNullOrUndefined(err, 'Should not error');
    assert.equal(result.version, 2);
    assert.equal(result.changes.length, 0);
    done();
  });
});

QUnit.test('New collaborator enters with a change that needs rebasing', function(assert) {
  var done = assert.async();

  // We simulate that by letting another user 'collab-2' makeing a text change
  // that affects a later text change of 'collab-1' - the one that needs rebasing.
  var insertTextChange1 = insertText(testDoc, 1, '!');
  var insertTextChange2 = insertText(testDoc, 5, '$$$'); // 5 is based on version 1, after rebasing should be 6

  collabEngine.connect({
    collaboratorId: 'collab-1',
    documentId: 'test-doc',
    version: 1,
    change: insertTextChange1
  }, function(err, result) {
    assert.isNullOrUndefined(err, 'Should not error');
    assert.equal(result.version, 2);

    collabEngine.connect({
      collaboratorId: 'collab-2',
      documentId: 'test-doc',
      version: 1,
      change: insertTextChange2
    }, function(err, result) {
      assert.isNullOrUndefined(err, 'Should not error');
      assert.equal(result.version, 3);
      assert.equal(result.changes.length, 1);

      assert.notDeepEqual(result.change, insertTextChange2, 'Tranformed change should differ from original change');
      done();
    });
  });
});

QUnit.test('Two collaborators connect', function(assert) {
  var done = assert.async();
  collabEngine.connect({
    collaboratorId: 'collab-1',
    documentId: 'test-doc',
    version: 1,
    change: fakeChange
  }, function(err, result) {
    assert.ok(result, 'connect result should be set');
    collabEngine.connect({
      collaboratorId: 'collab-2',
      documentId: 'test-doc',
      version: 1,
      change: fakeChange
    }, function(err, result) {
      assert.ok(result, 'connect result should be set');
      assert.isNullOrUndefined(err, 'Should not error');
      var collaboratorIds = collabEngine.getCollaboratorIds('test-doc', 'collab-2');
      // var collaborators = collabEngine.getCollaborators('test-doc', 'collab-2');
      assert.deepEqual(collaboratorIds, ['collab-1'], 'Should return one collaboratorId');
      collaboratorIds = collabEngine.getCollaboratorIds('test-doc', 'collab-1');
      assert.deepEqual(collaboratorIds, ['collab-2'], 'Should return one collaboratorId');
      done();
    });
  });
});

QUnit.test('Collaborator does a fast-forward commit', function(assert) {
  var done = assert.async();

  collabEngine.connect({
    collaboratorId: 'collab-1',
    documentId: 'test-doc',
    version: 1,
    change: fakeChange
  }, function(err, result) {
    assert.isNullOrUndefined(err, 'Should not error on enter');
    assert.ok(result, 'connect should produce a result object');
    collabEngine.commit({
      collaboratorId: 'collab-1',
      documentId: 'test-doc',
      change: exampleChange,
      version: 1
    }, function(err, commitResult) {
      assert.equal(commitResult.version, 2, 'Version should be 2 after commit');
      assert.deepEqual(commitResult.change, exampleChange, 'Change should be untouched');
      done();
    });
  });
});

QUnit.test('Collaborator does a commit that needs rebasing', function(assert) {
  // We may want to use a proper seed to simulate that scenario
  assert.ok(true, 'TODO: implement');
});
<commit_msg>Fix tests.<commit_after>'use strict';

require('../qunit_extensions');

var documentStoreSeed = require('../../fixtures/collab/documentStoreSeed');
var changeStoreSeed = require('../../fixtures/collab/changeStoreSeed');
var DocumentStore = require('../../../collab/DocumentStore');
var ChangeStore = require('../../../collab/ChangeStore');
var DocumentEngine = require('../../../collab/DocumentEngine');
var twoParagraphs = require('../../fixtures/collab/two-paragraphs');
var insertParagraph = require('../../fixtures/collab/insertParagraph');
var insertText = require('../../fixtures/collab/insertText');
var CollabEngine = require('../../../collab/CollabEngine');

// Equivalent to the 'test-doc' that is in the backendseed.
var testDoc = twoParagraphs.createArticle();

// Example changes should be something that depends on existing content, so we
// properly play the rebase scenario
var exampleChange = insertParagraph(testDoc);

var documentStore = new DocumentStore();
var changeStore = new ChangeStore();

var documentEngine = new DocumentEngine({
  documentStore: documentStore,
  changeStore: changeStore,
  schemas: {
    'prose-article': {
      name: 'prose-article',
      version: '1.0.0',
      documentFactory: twoParagraphs
    }
  }
});

var fakeChange = {
  before: {
    selection: null
  },
  after: {
    selection: null,
  },
  ops: []
};

var collabEngine;

QUnit.module('collab/CollabEngine', {
  beforeEach: function(assert) {
    var done = assert.async();
    var newDocumentStoreSeed = JSON.parse(JSON.stringify(documentStoreSeed));
    var newChangeStoreSeed = JSON.parse(JSON.stringify(changeStoreSeed));
    documentStore.seed(newDocumentStoreSeed, function(err) {
      if (err) return console.error(err);
      changeStore.seed(newChangeStoreSeed, function(err) {
        if (err) return console.error(err);
        collabEngine = new CollabEngine(documentEngine);
        done();
      });
    });
  }
});

QUnit.test('New collaborator enters with latest version', function(assert) {
  var done = assert.async();

  collabEngine.sync({
    collaboratorId: 'collab-1',
    documentId: 'test-doc',
    version: 1,
    change: fakeChange
  }, function(err, result) {
    assert.isNullOrUndefined(err, 'Should not error');
    assert.equal(result.version, 1);
    assert.equal(result.changes.length, 0);
    done();
  });
});

QUnit.test('New collaborator enters with an outdated version', function(assert) {
  var done = assert.async();

  collabEngine.sync({
    collaboratorId: 'collab-1',
    documentId: 'test-doc',
    version: 0,
    change: fakeChange
  }, function(err, result) {
    assert.isNullOrUndefined(err, 'Should not error');
    assert.equal(result.version, 1);
    assert.equal(result.changes.length, 1);
    done();
  });
});

QUnit.test('New collaborator enters with a new fast-forward change', function(assert) {
  var done = assert.async();

  collabEngine.sync({
    collaboratorId: 'collab-1',
    documentId: 'test-doc',
    version: 1,
    change: exampleChange
  }, function(err, result) {
    assert.isNullOrUndefined(err, 'Should not error');
    assert.equal(result.version, 2);
    assert.equal(result.changes.length, 0);
    done();
  });
});

QUnit.test('New collaborator enters with a change that needs rebasing', function(assert) {
  var done = assert.async();

  // We simulate that by letting another user 'collab-2' makeing a text change
  // that affects a later text change of 'collab-1' - the one that needs rebasing.
  var insertTextChange1 = insertText(testDoc, 1, '!');
  var insertTextChange2 = insertText(testDoc, 5, '$$$'); // 5 is based on version 1, after rebasing should be 6

  collabEngine.sync({
    collaboratorId: 'collab-1',
    documentId: 'test-doc',
    version: 1,
    change: insertTextChange1
  }, function(err, result) {
    assert.isNullOrUndefined(err, 'Should not error');
    assert.equal(result.version, 2);

    collabEngine.sync({
      collaboratorId: 'collab-2',
      documentId: 'test-doc',
      version: 1,
      change: insertTextChange2
    }, function(err, result) {
      assert.isNullOrUndefined(err, 'Should not error');
      assert.equal(result.version, 3);
      assert.equal(result.changes.length, 1);

      assert.notDeepEqual(result.change, insertTextChange2, 'Tranformed change should differ from original change');
      done();
    });
  });
});

QUnit.test('Two collaborators enter', function(assert) {
  var done = assert.async();
  collabEngine.sync({
    collaboratorId: 'collab-1',
    documentId: 'test-doc',
    version: 1,
    change: fakeChange
  }, function(err, result) {
    assert.ok(result, 'connect result should be set');
    collabEngine.sync({
      collaboratorId: 'collab-2',
      documentId: 'test-doc',
      version: 1,
      change: fakeChange
    }, function(err, result) {
      assert.ok(result, 'connect result should be set');
      assert.isNullOrUndefined(err, 'Should not error');
      var collaboratorIds = collabEngine.getCollaboratorIds('test-doc', 'collab-2');
      // var collaborators = collabEngine.getCollaborators('test-doc', 'collab-2');
      assert.deepEqual(collaboratorIds, ['collab-1'], 'Should return one collaboratorId');
      collaboratorIds = collabEngine.getCollaboratorIds('test-doc', 'collab-1');
      assert.deepEqual(collaboratorIds, ['collab-2'], 'Should return one collaboratorId');
      done();
    });
  });
});

QUnit.test('Collaborator does a fast-forward sync', function(assert) {
  var done = assert.async();

  collabEngine.sync({
    collaboratorId: 'collab-1',
    documentId: 'test-doc',
    version: 1,
    change: fakeChange
  }, function(err, result) {
    assert.isNullOrUndefined(err, 'Should not error on enter');
    assert.ok(result, 'connect should produce a result object');
    collabEngine.sync({
      collaboratorId: 'collab-1',
      documentId: 'test-doc',
      change: exampleChange,
      version: 1
    }, function(err, syncResult) {
      assert.equal(syncResult.version, 2, 'Version should be 2 after commit');
      assert.deepEqual(syncResult.change, exampleChange, 'Change should be untouched');
      done();
    });
  });
});

QUnit.test('Collaborator does a sync that needs rebasing', function(assert) {
  // We may want to use a proper seed to simulate that scenario
  assert.ok(true, 'TODO: implement');
});
<|endoftext|>


<commit_before>/**
 * Created by Lucas on 30/01/2017.
 */

document.addEventListener('contextmenu', event => event.preventDefault());

$(document).ready(function () {

    $('button#validate').click(function () {
        if ($('#largeur').val() != "" && $('hauteur').val() != "" && $('#bombs').val() != "") {
            largeur = parseInt($('#largeur').val());
            hauteur = parseInt($('#hauteur').val());
            bombs = parseInt($('#bombs').val());

            if (!isNaN(largeur) && !isNaN(hauteur) && !isNaN(bombs)){
                if (testParameters(largeur,hauteur,bombs)) {
                    initGameboard();
                }
            }
        }
    });

});

function testParameters(largeur, hauteur, bombs) {

    if ( ((largeur * hauteur)/3)*2 >= bombs ){
        if (largeur <= 40 && hauteur <= 50){
            return true;
        }
    }
    return false;
}

function initGameboard() {
    generateLayout(largeur, hauteur);
    grid = new Grid(largeur, hauteur);
    grid.addBombs(bombs);
    $('#nbbombes').text(grid.bombs + ' bombes');

    $('#menu').css('display', 'none');
    $('#gameboard').css('display', 'block');

    document.oncontextmenu = function () {
        return false;
    };

    $('#reset').click(function () {
        generateLayout(largeur, hauteur);
        grid = new Grid(largeur, hauteur);
        grid.addBombs(bombs);
        $('#nbbombes').text(grid.flags + ' bombes');

        $('td').each(function () {
            initEvents($(this));
        });

    });

    $('td').each(function () {
        initEvents($(this));
    });
}

function generateLayout(width, height) {
    $('table tbody').html('');
    for (var y = 0; y < height; y++) {
        var row = $("

");
        for (var x = 0; x < width; x++) {
            row.append($('	'))
        }
        $('table tbody').append(row);
    }
}

function initEvents(elem){

    elem.mousedown(function (event) {

        var x = parseInt(elem.attr("data-x"));
        var y = parseInt(elem.attr("data-y"));

        if (event.button == 0) {

            if (grid.cells[x][y].flagged) {
                console.log('Erreur, il y a un drapeau');
            } else {
                if (!grid.cells[x][y].shown) {
                    if (grid.cells[x][y].value == "B") {
                        elem.addClass("bomb");
                    } else if (grid.cells[x][y].value == 0) {
                        elem.addClass("empty");
                        cases = grid.reveal(x,y);
                        cases.forEach(function (el) {
                            if (el.value == 0) {
                                $('td[data-x="' + el.x + '"][data-y="' + el.y + '"]').addClass('empty');
                            } else {
                                $('td[data-x="' + el.x + '"][data-y="' + el.y + '"]').addClass('number');
                                $('td[data-x="' + el.x + '"][data-y="' + el.y + '"]').html(el.value);
                            }
                        })
                    } else {
                        elem.addClass("number");
                        elem.html(grid.cells[x][y].value)
                    }
                    grid.cells[x][y].shown = true;
                    gameOverLose(grid.cells[x][y].value);
                    gameOverWin();
                }
            }

        } else if (event.button == 2) {
            console.log('clic du bouton droit');
            if (!grid.cells[x][y].shown) {
                if (grid.cells[x][y].flagged) {
                    grid.cells[x][y].flagged = false;
                    elem.removeClass('flag');
                    grid.flags += 1;
                } else if (grid.flags > 0) {
                    grid.cells[x][y].flagged = true;
                    elem.addClass('flag');
                    grid.flags -= 1;
                } else if (grid.flags == 0) {
                    console.log('Nombre max de drapeau atteint !');
                }
                $('#nbbombes').text(grid.flags + ' bombes');
                console.log('Nombre de bombes : ' + grid.flags);
            }
        }
    });

    elem.dblclick(function () {
        console.log("test");

        var x = parseInt(elem.attr("data-x"));
        var y = parseInt(elem.attr("data-y"));

        if (grid.cells[x][y].flagged) {
            console.log('Erreur, il y a un drapeau');
        } else {
            if (grid.cells[x][y].shown) {

            }
        }

    })

}

function gameOverLose(elem){
  if (elem == 'B') {
    console.log('perdu');
    return true;
  }
}

function gameOverWin(){
  var i = 0;
  $('td').each(function () {
    if ($(this).hasClass('bomb')) {
      return false
    } else if(!$(this).hasClass('empty') && !$(this).hasClass('number')){
      i += 1;
    } else if($(this).hasClass('flag')){
      i += 1;
    }
  });
  if (i == grid.bombs) {
    console.log(i);
    console.log('gagné');
    return true;
  }
}
<commit_msg>Double click<commit_after>/**
 * Created by Lucas on 30/01/2017.
 */

document.addEventListener('contextmenu', event => event.preventDefault());

$(document).ready(function () {

    $('button#validate').click(function () {
        if ($('#largeur').val() != "" && $('hauteur').val() != "" && $('#bombs').val() != "") {
            largeur = parseInt($('#largeur').val());
            hauteur = parseInt($('#hauteur').val());
            bombs = parseInt($('#bombs').val());

            if (!isNaN(largeur) && !isNaN(hauteur) && !isNaN(bombs)){
                if (testParameters(largeur,hauteur,bombs)) {
                    initGameboard();
                }
            }
        }
    });

});

function testParameters(largeur, hauteur, bombs) {

    if ( ((largeur * hauteur)/3)*2 >= bombs ){
        if (largeur <= 40 && hauteur <= 50){
            return true;
        }
    }
    return false;
}

function initGameboard() {
    generateLayout(largeur, hauteur);
    grid = new Grid(largeur, hauteur);
    grid.addBombs(bombs);
    $('#nbbombes').text(grid.bombs + ' bombes');

    $('#menu').css('display', 'none');
    $('#gameboard').css('display', 'block');

    document.oncontextmenu = function () {
        return false;
    };

    $('#reset').click(function () {
        generateLayout(largeur, hauteur);
        grid = new Grid(largeur, hauteur);
        grid.addBombs(bombs);
        $('#nbbombes').text(grid.flags + ' bombes');

        $('td').each(function () {
            initEvents($(this));
        });

    });

    $('td').each(function () {
        initEvents($(this));
    });
}

function generateLayout(width, height) {
    $('table tbody').html('');
    for (var y = 0; y < height; y++) {
        var row = $("

");
        for (var x = 0; x < width; x++) {
            row.append($('	'))
        }
        $('table tbody').append(row);
    }
}

function initEvents(elem){

    elem.mousedown(function (event) {

        var x = parseInt(elem.attr("data-x"));
        var y = parseInt(elem.attr("data-y"));

        if (event.button == 0) {

            if (grid.cells[x][y].flagged) {
                console.log('Erreur, il y a un drapeau');
            } else {
                if (!grid.cells[x][y].shown) {
                    if (grid.cells[x][y].value == "B") {
                        elem.addClass("bomb");
                    } else if (grid.cells[x][y].value == 0) {
                        elem.addClass("empty");
                        cases = grid.reveal(x,y);
                        cases.forEach(function (el) {
                            if (el.value == 0) {
                                $('td[data-x="' + el.x + '"][data-y="' + el.y + '"]').addClass('empty');
                            } else {
                                $('td[data-x="' + el.x + '"][data-y="' + el.y + '"]').addClass('number');
                                $('td[data-x="' + el.x + '"][data-y="' + el.y + '"]').html(el.value);
                            }
                        })
                    } else {
                        elem.addClass("number");
                        elem.html(grid.cells[x][y].value)
                    }
                    grid.cells[x][y].shown = true;
                    gameOverLose(grid.cells[x][y].value);
                    gameOverWin();
                }
            }

        } else if (event.button == 2) {
            console.log('clic du bouton droit');
            if (!grid.cells[x][y].shown) {
                if (grid.cells[x][y].flagged) {
                    grid.cells[x][y].flagged = false;
                    elem.removeClass('flag');
                    grid.flags += 1;
                } else if (grid.flags > 0) {
                    grid.cells[x][y].flagged = true;
                    elem.addClass('flag');
                    grid.flags -= 1;
                } else if (grid.flags == 0) {
                    console.log('Nombre max de drapeau atteint !');
                }
                $('#nbbombes').text(grid.flags + ' bombes');
                console.log('Nombre de bombes : ' + grid.flags);
            }
        }
    });

    elem.dblclick(function () {
        console.log("test");

        var x = parseInt(elem.attr("data-x"));
        var y = parseInt(elem.attr("data-y"));

        if (grid.cells[x][y].flagged) {
            console.log('Erreur, il y a un drapeau');
        } else {
            if (grid.cells[x][y].shown) {

                cases = grid.reveal(x,y);
                console.log(cases);
                if (cases == false){

                } else {
                    cases.forEach(function (el) {
                        if (el.value == 0) {
                            $('td[data-x="' + el.x + '"][data-y="' + el.y + '"]').addClass('empty');
                        } else {
                            $('td[data-x="' + el.x + '"][data-y="' + el.y + '"]').addClass('number');
                            $('td[data-x="' + el.x + '"][data-y="' + el.y + '"]').html(el.value);
                        }
                    })
                }

            }
        }

    })

}

function gameOverLose(elem){
  if (elem == 'B') {
    console.log('perdu');
    return true;
  }
}

function gameOverWin(){
  var i = 0;
  $('td').each(function () {
    if ($(this).hasClass('bomb')) {
      return false
    } else if(!$(this).hasClass('empty') && !$(this).hasClass('number')){
      i += 1;
    } else if($(this).hasClass('flag')){
      i += 1;
    }
  });
  if (i == grid.bombs) {
    console.log(i);
    console.log('gagné');
    return true;
  }
}
<|endoftext|>


<commit_before>(function(window, document, undefined) {
    window.onload = init;
    function init() {

        //create an empty map
        var map = new Array(960);
        for(var i = 0; i < 960; i++) {
            map[i] = new Array(540);
        }

        //get the canvas
        var canvas = document.getElementById("mapcanvas");
        var c = canvas.getContext("2d");

       //functions for finding how many neighbors are walls
        function ncount(i,j) {
            var i1 = i+1;
            var i2 = i-1;
            var j1 = j+1;
            var j2 = j-1;
            var neighbors = 0;
            if(i1 < 960 && i2 >=0 && j1 < 540 && j2 >=0){
                if(map[i1][j1] == 1){
                    neighbors++;
                }
                if(map[i][j1] == 1){
                    neighbors++;
                }
                if(map[i2][j1] == 1){
                    neighbors++;
                }
                if(map[i1][j] == 1){
                    neighbors++;
                }
                if(map[i2][j] == 1){
                    neighbors++;
                }
                if(map[i1][j2] == 1){
                    neighbors++;
                }
                if(map[i][j2] == 1){
                    neighbors++;
                }
                if(map[i2][j2] == 1){
                    neighbors++;
                }
            }else{
                neighbors = 4;
            }
            return neighbors;
        }

        //when we click, assign values and then paint
        document.getElementById("startbtn").onclick = paint;
        var it = 1;
        function paint() {
            document.getElementById("iter").innerHTML = it;
            if(it == 1){
                //fill the values
                for(var i = 0; i< 960; i++) {
                    for(var j = 0; j < 540; j++) {
                        if(Math.random() < .45){
                            map[i][j] = 1;
                        } else {
                            map[i][j] = 0;
                        }
                    }
                }
            } else {
                for(var i = 0; i< 960; i++) {
                    for(var j = 0; j < 540; j++){
                        var nc = ncount(i,j);
                        switch(nc){
                            case 4:
                                break;
                            case 5:
                                map[i][j] = 1;
                                break;
                            case 6:
                                map[i][j] = 1;
                                break;
                            case 7:
                                map[i][j] = 1;
                                break;
                            case 8:
                                map[i][j] = 1;
                                break;
                            default:
                                map[i][j] = 0;
                        }
                    }
                }
            }

            //paint the map
            for(var i = 0; i < 960; i++) {
                for(var j = 0; j< 540; j++){
                    if(map[i][j] == 1){
                        c.fillStyle = "#FFFFFF";
                        c.fillRect(i, j, 1, 1);
                    }else {
                        c.fillStyle = "#000000";
                        c.fillRect(i, j, 1, 1);
                    }
                }
            }
            it++;

        }
    }
})(window, document, undefined);
<commit_msg>Update script.js<commit_after>(function(window, document, undefined) {
    window.onload = init;
    function init() {

        //create an empty map
        var map = new Array(960);
        for(var i = 0; i < 960; i++) {
            map[i] = new Array(540);
        }

        //get the canvas
        var canvas = document.getElementById("mapcanvas");
        var c = canvas.getContext("2d");

       //functions for finding how many neighbors are walls
        function ncount(i,j) {
            var i1 = i+1;
            var i2 = i-1;
            var j1 = j+1;
            var j2 = j-1;
            var neighbors = 0;
            if(i1 < 960 && i2 >=0 && j1 < 540 && j2 >=0){
                if(map[i1][j1] == 1){
                    neighbors++;
                }
                if(map[i][j1] == 1){
                    neighbors++;
                }
                if(map[i2][j1] == 1){
                    neighbors++;
                }
                if(map[i1][j] == 1){
                    neighbors++;
                }
                if(map[i2][j] == 1){
                    neighbors++;
                }
                if(map[i1][j2] == 1){
                    neighbors++;
                }
                if(map[i][j2] == 1){
                    neighbors++;
                }
                if(map[i2][j2] == 1){
                    neighbors++;
                }
            }else{
                neighbors = 4;
            }
            return neighbors;
        }

        //when we click, assign values and then paint
        document.getElementById("startbtn").onclick = paint;
        var it = 1;
        function paint() {
            document.getElementById("iter").innerHTML = it;
            if(it == 1){
                //fill the values
                for(var i = 0; i< 960; i++) {
                    for(var j = 0; j < 540; j++) {
                        if(Math.random() < .45){
                            map[i][j] = 1;
                        } else {
                            map[i][j] = 0;
                        }
                    }
                }
            } else {
                for(var i = 0; i< 960; i++) {
                    for(var j = 0; j < 540; j++){
                        var nc = ncount(i,j);
                        switch(nc){
                            case 4:
                                break;
                            case 5:
                                map[i][j] = 1;
                                break;
                            case 6:
                                map[i][j] = 1;
                                break;
                            case 7:
                                map[i][j] = 1;
                                break;
                            case 8:
                                map[i][j] = 1;
                                break;
                            default:
                                map[i][j] = 0;
                        }
                    }
                }
            }

            //paint the map
            for(var i = 0; i < 960; i++) {
                for(var j = 0; j< 540; j++){
                    if(map[i][j] == 1){
                        c.fillStyle = "#000000";
                        c.fillRect(i, j, 1, 1);
                    }else {
                        c.fillStyle = "#FFFFFF";
                        c.fillRect(i, j, 1, 1);
                    }
                }
            }
            it++;

        }
    }
})(window, document, undefined);
<|endoftext|>


<commit_before>//============== Eventhandler ==================//

$(window).load(function() {										// warte darauf, dass der Inhalt geladen wurde
	$(document).keydown(function(event) {
		if (event.keyCode === 27) {								// Escape wurde gedrueckt
			$('#zoomWrap').hide();								// verstecke das Bildfenster
		}
	});

	$('#cityform .submitForm').on('click', function() {
		$('#cityform').submit();
	});

	$('#newdataform').submit(function(event) {
		if ($('#formemail').val().substring($('#formemail').val().length-20, $('#formemail').val().length) !== "@beuth-hochschule.de") {		// wenn die letzten 20 Zeichen nicht dem String entsprechen
			event.preventDefault();																// Abbruch
			$('#formemail').popover('show');

		} else {
			event.preventDefault();
			var form = $('#newdataform');
			var formDate = $('#formdate').val();
			var formTemp = $('#formtemp').val();
			var formCity = $('#formcity :selected').text();
			var formComment = $('#formcomment').val();
			var formEmail = $('#formemail').val();
			$('#formemail').popover('hide');
			var entries = $('table tr').length;
			var entry = $('table tbody').append('
' +
				'' + formatDate(formDate) + '	' +
				'' + formTemp + '° C	' +
				'' + formCity + '	' +
				'	' +
				'' + formComment + '	' +
				'' +
					'<button type="button" class="btn btn-primary btn-xs editlink"></button>' +
					'<button type="button" class="btn btn-danger btn-xs deletelink" data-type="delete"></button>' +
				'	' +
				'' +
					'<button type="button" class="btn btn-success btn-xs savelink"></button>' +
					'<button type="button" class="btn btn-danger btn-xs deletelink" data-type="delete"></button>' +
				'	');
		}
	});

	$('#zoom a').on('click', function() {
		$('#zoomWrap').hide();
	});

	/*var trs = document.getElementsByTagName('tr');
	for (var x=0; x<trs.length; x++) {
		trs[x].addEventListener('mouseover', function() {
			var tds = this.getElementsByTagName('td');
			tds[10].style.visibility = 'visible';
		}, false);
		trs[x].addEventListener('mouseout', function() {
			var tds = this.getElementsByTagName('td');
			tds[10].style.visibility = 'hidden';
		}, false);
	}*/

	$('select').on('change', function() {
		if ($(this).find('option:selected').val() === "neuestadt") {								// wenn eine neue Stadt eingetragen werden soll
			var userInput = prompt("Geben Sie den Namen der neuen Stadt ein:");
			if (userInput !== "" && userInput !== null) {
				$(this).append(new Option(userInput, formatValue(userInput), true, true));						// erstelle neue Option mit der Benutzereingabe
			}
		}
	});

	$('table').on('click', '.zoomlink', function() {
		var img = $(this).find('img').attr('src');
		$('#zoomImage').attr('src', img);
		$('#zoomWrap').show();
	});

	$('table').on('click', '.editlink', function() {
		$(this).parent().parent().find('.editable').hide();
		$(this).parent().parent().find('.edit').show();
	});

	$('table').on('click', '.savelink', function() {
		var tr = $(this).parent().parent();
		tr.find('.editable.date').text(formatDate(tr.find('input[type=date]').val()));
		tr.find('.editable.temp').html(tr.find('input[type=number]').val() + " °C");
		tr.find('.editable.city').text(tr.find('select option:selected').text());
		tr.find('.editable.comment').text(tr.find('input[type=text]').val());
		tr.find('.edit').hide();
		tr.find('.editable').show();
	});

	$('table').on('click', '.deletelink', function(e) {
		e.preventDefault();
		//var el = $(this).parent();
		var id = $(this).parent().parent().attr('id');
		var title = $(this).attr('data-title');
		var msg = $(this).attr('data-message');
		var type = $(this).attr('data-type');
		$('#frm_submit').attr('data-form', '#'+id);
		if (msg === "" && type === 'delete') {
			title = "Löschen?";
			msg = "Diesen Eintrag wirklich löschen?";
		}

		$('#formConfirm')
			.find('#frm_body').html(msg)
			.end().find('#frm_submit').html("Ja")
			.end().find('#frm_cancel').html("Nein")
			.end().find('#frm_title').html(title)
			.end().modal('show');

		//$('#formConfirm').find('#frm_submit').attr('data-form', dataForm);
	});

	$('#formConfirm').on('click', '#frm_submit', function(e) {
		/*var id = $(this).attr('data-form');
		$(id).submit();*/
		var tr = $(this).attr('data-form');
		$(tr).remove();
	});

	initialize();
});

//============== Hauptfunktionen ===============//

function initialize() {
	$.backstretch("img/wetter_bg.jpg");

	/*$.backstretch([
		"img/wetter_bg.jpg",
		"img/wallpaper/wetter1.jpg",
		"img/wallpaper/wetter2.jpg",
		"img/wallpaper/wetter3.jpg",
		"img/wallpaper/wetter4.jpg",
		"img/wallpaper/wetter5.jpg",
		"img/wallpaper/wetter6.jpg",
		"img/wallpaper/wetter7.jpg"
	], {duration: 4000, fade: 750});*/

	var today = new Date();									// neues Datum erzeugen
	var dd = today.getDate();								// hole den Tag
	var mm = today.getMonth()+1;							// hole den Monat; +1 weil hier Januar mit 0 gezaehlt wird
	var yyyy = today.getFullYear();							// hole das Jahr
	$('#formdate').val(yyyy + "-" + mm + "-" + dd);			// formdate auf das heutige Datum setzen
	$('select').each(function() {
		addCities($(this));
	});
}

function addCities(select) {
	select.append(new Option("Stadt", "", true));						// damit man nicht alle Staedte mehrfach eintragen muss
	$('select [value=""]').attr('disabled', true);
	select.append(new Option("Berlin", "koeln"));
	select.append(new Option("Köln", "berlin"));
	select.append(new Option("Frankfurt", "frankfurt"));
	select.append(new Option("Hamburg", "hamburg"));
	select.append(new Option("München", "muenchen"));
	select.append(new Option("Neue Stadt...", "neuestadt"));
}

//============== Helferfunktionen ==============//

function formatValue(str) {									// ersetze alle dt. Umlaute und gib das Wort in Kleinbuchstaben zurueck
	return str.toLowerCase().replace(/\u00e4/g, "ae").replace(/\u00f6/g, "oe").replace(/\u00fc/g, "ue").replace(/\u00df/g, "ss").replace(/ /g, "_");
}

function formatDate(date) {									// uebersetze ein Datum vom ISO 8601-Format in die dt. Schreibweise und gib es zurueck
	return date.replace(/(\d\d\d\d)-(\d\d)-(\d\d)/i, "$3.$2.$1");
}<commit_msg>Added documentation, cleanup<commit_after>/**
* File script.js
*
* All scripts for the site
*
* @author Florian Keller
*/

$(window).load(function() {										// warte darauf, dass der Inhalt geladen wurde
	$(document).keydown(function(event) {
		if (event.keyCode === 27) {								// Escape wurde gedrueckt
			$('#zoomWrap').hide();								// verstecke das Bildfenster
		}
	});

	$('#cityform .submitForm').on('click', function() {
		$('#cityform').submit();
	});

	$('#newdataform').submit(function(event) {
		var formEmail = $('#formemail').val();
		if (formEmail.substring(formEmail.val().length-20,
								formEmail.val().length) !== "@beuth-hochschule.de") {		// wenn die letzten 20 Zeichen nicht dem String entsprechen
			event.preventDefault();																// Abbruch
			$('#formemail').popover('show');

		} else {
			event.preventDefault();
			var form = $('#newdataform');
			var formDate = $('#formdate').val();
			var formTemp = $('#formtemp').val();
			var formCity = $('#formcity :selected').text();
			var formComment = $('#formcomment').val();
			$('#formemail').popover('hide');
			var entries = $('table tr').length;
			var entry = $('table tbody').append('
' +
				'' + formatDate(formDate) + '	' +
				'' + formTemp + '° C	' +
				'' + formCity + '	' +
				'	' +
				'' + formComment + '	' +
				'' +
					'<button type="button" class="btn btn-primary btn-xs editlink"></button>' +
					'<button type="button" class="btn btn-danger btn-xs deletelink" data-type="delete"></button>' +
				'	' +
				'' +
					'<button type="button" class="btn btn-success btn-xs savelink"></button>' +
					'<button type="button" class="btn btn-danger btn-xs deletelink" data-type="delete"></button>' +
				'	');
		}
	});

	$('#zoom a').on('click', function() {
		$('#zoomWrap').hide();
	});

	/*var trs = document.getElementsByTagName('tr');
	for (var x=0; x<trs.length; x++) {
		trs[x].addEventListener('mouseover', function() {
			var tds = this.getElementsByTagName('td');
			tds[10].style.visibility = 'visible';
		}, false);
		trs[x].addEventListener('mouseout', function() {
			var tds = this.getElementsByTagName('td');
			tds[10].style.visibility = 'hidden';
		}, false);
	}*/

	$('select').on('change', function() {
		if ($(this).find('option:selected').val() === "neuestadt") {								// wenn eine neue Stadt eingetragen werden soll
			var userInput = prompt("Geben Sie den Namen der neuen Stadt ein:");
			if (userInput !== "" && userInput !== null) {
				$(this).append(new Option(userInput, formatValue(userInput), true, true));						// erstelle neue Option mit der Benutzereingabe
			}
		}
	});

	$('table').on('click', '.zoomlink', function() {
		var img = $(this).find('img').attr('src');
		$('#zoomImage').attr('src', img);
		$('#zoomWrap').show();
	});

	$('table').on('click', '.editlink', function() {
		$(this).parent().parent().find('.editable').hide();
		$(this).parent().parent().find('.edit').show();
	});

	$('table').on('click', '.savelink', function() {
		var tr = $(this).parent().parent();
		tr.find('.editable.date').text(formatDate(tr.find('input[type=date]').val()));
		tr.find('.editable.temp').html(tr.find('input[type=number]').val() + " °C");
		tr.find('.editable.city').text(tr.find('select option:selected').text());
		tr.find('.editable.comment').text(tr.find('input[type=text]').val());
		tr.find('.edit').hide();
		tr.find('.editable').show();
	});

	$('table').on('click', '.deletelink', function(e) {
		e.preventDefault();
		//var el = $(this).parent();
		var id = $(this).parent().parent().attr('id');
		var title = $(this).attr('data-title');
		var msg = $(this).attr('data-message');
		var type = $(this).attr('data-type');
		$('#frm_submit').attr('data-form', '#'+id);
		if (msg === "" && type === 'delete') {
			title = "Löschen?";
			msg = "Diesen Eintrag wirklich löschen?";
		}

		$('#formConfirm')
			.find('#frm_body').html(msg)
			.end().find('#frm_submit').html("Ja")
			.end().find('#frm_cancel').html("Nein")
			.end().find('#frm_title').html(title)
			.end().modal('show');

		//$('#formConfirm').find('#frm_submit').attr('data-form', dataForm);
	});

	$('#formConfirm').on('click', '#frm_submit', function(e) {
		/*var id = $(this).attr('data-form');
		$(id).submit();*/
		var tr = $(this).attr('data-form');
		$(tr).remove();
	});

	$.backstretch("img/wetter_bg.jpg");

	/*$.backstretch([
		"img/wetter_bg.jpg",
		"img/wallpaper/wetter1.jpg",
		"img/wallpaper/wetter2.jpg",
		"img/wallpaper/wetter3.jpg",
		"img/wallpaper/wetter4.jpg",
		"img/wallpaper/wetter5.jpg",
		"img/wallpaper/wetter6.jpg",
		"img/wallpaper/wetter7.jpg"
	], {duration: 4000, fade: 750});*/

	var today = new Date();									// neues Datum erzeugen
	var dd = today.getDate();								// hole den Tag
	var mm = today.getMonth()+1;							// hole den Monat; +1 weil hier Januar mit 0 gezaehlt wird
	var yyyy = today.getFullYear();							// hole das Jahr
	$('#formdate').val(yyyy + "-" + mm + "-" + dd);			// formdate auf das heutige Datum setzen
	$('select').each(function() {
		addCities($(this));
	});
});

function addCities(select) {
	select.append(new Option("Stadt", "", true));			// damit man nicht alle Staedte mehrfach eintragen muss
	$('select [value=""]').attr('disabled', true);
	select.append(new Option("Berlin", "koeln"));
	select.append(new Option("Köln", "berlin"));
	select.append(new Option("Frankfurt", "frankfurt"));
	select.append(new Option("Hamburg", "hamburg"));
	select.append(new Option("München", "muenchen"));
	select.append(new Option("Neue Stadt...", "neuestadt"));
}

/**
* Function formatValue
*
* Returns a String with umlauts replaced to ae, oe, etc.
*
* @param String str The string with umlauts
* @return The replaced string without umlauts
*/

function formatValue(str) {									// ersetze alle dt. Umlaute und gib das Wort in Kleinbuchstaben zurueck
	return str.toLowerCase().replace(/\u00e4/g, "ae").replace(/\u00f6/g, "oe").replace(/\u00fc/g, "ue").replace(/\u00df/g, "ss").replace(/ /g, "_");
}

/**
* Function formatDate
*
* Returns a date String in the dd.mm.yyyy format
*
* @param String date The date in the format yyyy-mm-dd
* @return The replaced date string
*/

function formatDate(date) {									// uebersetze ein Datum vom ISO 8601-Format in die dt. Schreibweise und gib es zurueck
	return date.replace(/(\d\d\d\d)-(\d\d)-(\d\d)/i, "$3.$2.$1");
}
<|endoftext|>


<commit_before>var textValue1 = "";                              //initiate global values
var textValue2 = "";
var trackLength = 0;

$( document ).ready(function() {                   //when page is fully loaded script can start
  trackLength = prompt("set the track length", "");
  setTrack(trackLength);
 });

function setTrack(length){
  for(i=0;i<trackLength;i++){
    $("#player1_strip").append("");
    $("#player2_strip").append("");
  }
};

$(document).keyup(function(){                     //add event listener
  var keyPressed = event.keyCode;                 //record what key was pressed
  movePlayer1(keyPressed);                        //pass to each player move function
  movePlayer2(keyPressed);
});

function winner(player){
    window.alert( player +  " WINS!!");
    location.reload();
  }

  function movePlayer1(keyPressed){                // this is how we move player 1
    if(keyPressed === 81) {                        //check if the key pressed was 'q'
      var x = document.querySelector('.active');   //

        if (x) {                                   //if x is a Truthy
          var nextX = x.nextElementSibling;        //get the next  in the table row
          nextX.setAttribute('class', 'active');    //set the class on the next  to "active"
          x.setAttribute('class', '');              //remove the class from the current
        }

        textValue1 = $(".active").text();            // extract the text value of the active class
        console.log(textValue1)
        if(textValue1 === "FINISH"){                // if it is the finish line
          winner("Player 1");                                 //run the winner function
        }

    }
  };

  function movePlayer2(keyPressed){         // this is how we move player 2
    if(keyPressed === 80) {                 //check if the key pressed was 'p'
      var x = document.querySelector('.active2'); //

        if (x) {                                    //if x is a Truthy
          var nextX = x.nextElementSibling;         //get the next  in the table row
          nextX.setAttribute('class', 'active2');    //set the class on the next  to "active"
          x.setAttribute('class', '');              //remove the class from the current
        }

        textValue = $(".active2").text();                       // extract the text value of the active class

        if(textValue === "FINISH"){                             // if it is the finish line
          winner("player 2");                                   //run the winner function
        }
    }
  };

<commit_msg>p1 and p2 and winner state functioning<commit_after>var trackLength = 0;                                  //initialize global variables
var movesP1 = 0;
var movesP2 = 0;

$( document ).ready(function() {                      //when page is fully loaded script can start
  trackLength = prompt("set the track length", "");   //prompt the user to set a track length
  setTrack(trackLength);                              //call the function that sets the track
 });

function setTrack(length){                            //this is how we set the track lenth
  for(i=0;i<trackLength;i++){                         //add another cell to the table untill the limit is reached
    $("#player1_strip").append("");
    $("#player2_strip").append("");
  }
};

$(document).keyup(function(){                         //add event listener
  var keyPressed = event.keyCode;                     //record what key was pressed
  movePlayer1(keyPressed);                            //pass to each player move function
  movePlayer2(keyPressed);
});

  function movePlayer1(keyPressed){                // this is how we move player 1
    if(keyPressed === 81) {                         //check if the key pressed was 'q'
      if(movesP1< trackLength){                       //check current moves are less than the track length
      var x = document.querySelector('.active');   //
        if (x) {                                   //if x is a Truthy
          var nextX = x.nextElementSibling;        //get the next  in the table row
          nextX.setAttribute('class', 'active');    //set the class on the next  to "active"
          x.setAttribute('class', '');              //remove the class from the current
          movesP1++;                                    //increase moves by 1
        }
      }
      else{
        winner("player1");                          //if number of moves is more than the track length print winner
      }
    }
  };

function movePlayer2(keyPressed){                // this is how we move player 1
    if(keyPressed === 80) {                         //check if the key pressed was 'q'
      if(movesP2 < trackLength){                       //check current moves are less than the track length
      var x = document.querySelector('.active2');   //
        if (x) {                                   //if x is a Truthy
          var nextX = x.nextElementSibling;        //get the next  in the table row
          nextX.setAttribute('class', 'active2');    //set the class on the next  to "active"
          x.setAttribute('class', '');              //remove the class from the current
        movesP2++;                                    //increase moves by 1
        }
      }
      else{
        winner("player 2");                          //if number of moves is more than the track length print winner
      }
    }
  };

 function winner(player){
    window.alert( player +  " WINS!!");
    location.reload();
  }

<|endoftext|>


<commit_before>/**
 * Author: Olaolu Olawuyi

 * Date Created: 20/08/2015

 * Last Modified: 28/02/2016

 * Twitter: @whizkydee, @webtwic

 * Github: https://github.com/webtwic/webtwic.github.io

*/

var Webtwic = Webtwic || {};

var browser = bowser;

var test_canvas = document.createElement("canvas");
var canvascheck = (test_canvas.getContext) ? true : false;

Webtwic = {
	// Basic Information about Webtwic
	name: "Webtwic",
	description: "A community for coding and tech tweaks where beginners and experts can learn.",
	repo: "https://github.com/whizkydee/whizkydee.github.io",
	author: "Olaolu Olawuyi",
	version: 1.07,

	// Start main functions for the object

	// Function to add browser name and version to body class
	_showBrowser: function( b ) {
		$("body").addClass(b + " " + b + parseInt(browser.version));
	},

	// Function to set attributes and values to elements
	_setAttr: function( elem, name, val ) {
		$(elem, this).attr(name, val);
	},

	// Function to push down .site-content
	_adjustSiteContent: function() {
		if ( $("body").hasClass("default-body") ) {
			$(".top-stripe").addClass("adjustedMargin");
			$("#header .logo").addClass("adjustedTop");
			$(".main-menu").addClass("adjustedMargin");
			$("#header").addClass("adjustSiteContent");
		} else if ( $("body").hasClass("secondary-body") ) {
			$(".site-content").addClass("adjustSiteContent");
			$(".secondary-header").addClass("adjustedMargin");
		}
	},

	// Function to push up .site-content to default state
	_undoSiteAdjust: function() {
		if ( $("body").hasClass("default-body") ) {
			$(".top-stripe").removeClass("adjustedMargin");
			$("#header .logo").removeClass("adjustedTop");
			$(".main-menu").removeClass("adjustedMargin");
			$("#header").removeClass("adjustSiteContent");
		} else if ( $("body").hasClass("secondary-body") ) {
			$(".secondary-header").removeClass("adjustedMargin");
		}
	},

	// Function to show Notifications before header
	_showNotif: function( text ) {
		text = (typeof text == "undefined") ? notif_text : text;
		Webtwic._adjustSiteContent();
		$("body").prepend(
			"
"+text+""+close_button+"
"
		);

		$(".close-button").on("click", function() {
			Webtwic._undoReset();
		});
	},

	// Function to hide Notifications
	_hideNotif: function() {
		$("#notifBanner").removeClass("notif_vis");
	},

	_resetSite: function() {
		Webtwic._showNotif();
		Webtwic._adjustSiteContent();
	},

	_undoReset: function() {
		Webtwic._hideNotif();
		Webtwic._undoSiteAdjust();
	},
}, WBT = Webtwic,
$$ = Webtwic,
close_button = "";
notif_text = "Some features which affect the functionality of webtwic are disabled in your browser. Please try refreshing the page or get a better browser.";

// Detect when the document is ready

jQuery(document).ready(function() {
	// Test for HTML5 support
	if ( window.Modernizr ) {
		if ( !Modernizr.canvas ) {
			Webtwic._showNotif ( "Oops. Looks like your browser doesn't support HTML5. Please get a better browser  for an awesome experience.");
		} else {
			// Do nothing.
		}
	} else if ( !window.Modernizr ) {
		if ( canvascheck == false ) {
			Webtwic._showNotif ( "Oops. Looks like your browser doesn't support HTML5. Please get a better browser  for an awesome experience.");
		} else {
			// Do nothing.
		}
	} else {
		// Do nothing.
	}

	// Define Variables
	var $scroll_top = $("a.scroll_top"),
	is_toggle_active = $(".hamburger").hasClass("is_active"),
	height = 200;

	// Performance Fixes

	// Start browser detection

	browser.ie = browser.msie;

	if ( browser.webkit ) {
		$("body").addClass("webkit");
	}
	if ( browser.chrome ) {
		Webtwic._showBrowser("chrome");
	}
	if ( browser.msedge ) {
		Webtwic._showBrowser("msedge");
	}
	if ( browser.firefox ) {
		Webtwic._showBrowser("firefox");
	}
	if ( browser.msie ) {
		Webtwic._showBrowser("ie");
	}
	if ( browser.safari ) {
		Webtwic._showBrowser("safari");
	}
	if ( browser.opera ) {
		Webtwic._showBrowser("opera");
	}

	/*
		TODO: Rebuild Performance fixes for attributes
		See history of Performance fixes.
		Also, check StackOverflow.
		See Issue #12
	*/

	if ( window.Modernizr ) {
		if ( !Modernizr.flexbox || !Modernizr.inlinesvg || !Modernizr.svg || !Modernizr.svgclippaths || !Modernizr.fontface || !Modernizr.boxshadow || !Modernizr.borderradius || !Modernizr.csstransforms ) {
			Webtwic._showNotif();
		} else {
			// Do nothing.
		}
	} else {
		// Do nothing.
	}

	// Start Main Page

	$("nav li ul.drop-nav").hide().removeClass("dropNavFallback");

	if ( $(window).width() > 860 ) {
		$("nav li.dropdown").hover(function() {
			$("ul.drop-nav", this).stop().slideDown("fast");
		}, function() {
			$("ul.drop-nav", this).stop().slideUp("fast");
		});
	}

	$(".active-item").append(
		"<svg viewBox='0 0 32 32' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'><path d='M 16.682,19.674c 0.010-0.012, 0.014-0.028, 0.024-0.040l 6.982-7.714c 0.39-0.434, 0.39-1.138,0-1.572 c-0.004-0.004-0.008-0.006-0.012-0.008C 23.496,10.13, 23.244,10, 22.964,10L 8.998,10 c-0.286,0-0.54,0.138-0.722,0.352L 8.272,10.348 c-0.39,0.434-0.39,1.138,0,1.572l 6.998,7.754C 15.66,20.108, 16.292,20.108, 16.682,19.674z'></path></svg>"
	);

	$("a.hamburger").click(function( e ) {
		$(this).toggleClass("is_active");

		e.preventDefault();
	});
	$(".mobile-header .mobile-nav").hide();

	$(window).scroll(function() {
		($(this).scrollTop() > height) ? $scroll_top.addClass("topVisible"): $scroll_top.removeClass("topVisible");
	});

	// Styles for homepage article-social

	$(".article .article-social a").hover(function() {
		$("span", this).eq(1).fadeIn(400);
	}, function() {
		$("span", this).eq(1).fadeOut(250);
	});

	// Functions for search-icon and ui-overlay-search

	$(".header-follow-search .search-wrap").on("click", function() {
		openUiOverlay();
	});

	$(".header-follow-search .close-icon").on("click", function(e) {
		e.preventDefault();
		closeUiOverlay();
	});

	$(".header-follow-search .close-icon").hover(
		function() {
			$(this).addClass("spin");
		},
		function() {
			$(this).removeClass("spin");
	});

	function openUiOverlay() {
		$(".ui-overlay-search").fadeIn(400).addClass("is_open");
	}

	function closeUiOverlay() {
		$(".ui-overlay-search").fadeOut(400).removeClass("is_open");
	}

	$(".ui-overlay-search .search-input input").focus(function() {
		$(".search-input").attr("data-focused", true);
		$(".search-input input").addClass("_is-focused");
		$("#__expand").addClass("visible");
	});

	$(".ui-overlay-search .search-input input").blur(function() {
		$(".search-input").attr("data-focused", false);
		$(".search-input input").removeClass("_is-focused");
		$("#__expand").removeClass("visible");
	});

	$(".post-meta .post-meta-inner .cta-btns a.is_inactive").on("click", function( e ) {
		e.preventDefault();
	});

	$(document).keydown(function( e ) {
    if ( e.keyCode == 27 ) {
        closeUiOverlay();
    } else {
		 // Do nothing.
	 }});

	 $(".mobile-nav").hide();

	// Functions for more-posts button click

	function addLoader() {
		$(".secondary-category-section .category-posts-column [data-clicked='false']").attr("data-clicked", "true").append("");
	}
	$(".secondary-category-section .category-posts-column [data-clicked='false']").on("click", function( e ) {
		$(this).css({
			"background": "#50ABF1",
			"color": "#fff"
		});
		addLoader();
		e.preventDefault();
	});

	$scroll_top.on("click", function( e ) {
		$("body,html").animate({
			scrollTop: 0
		}, 1000);

		e.preventDefault();
	});

});
<commit_msg>Update script.js<commit_after>/**
 * Author: Olaolu Olawuyi

 * Date Created: 20/08/2015

 * Last Modified: 28/02/2016

 * Twitter: @whizkydee, @webtwic

 * Github: https://github.com/webtwic/webtwic.github.io

*/

var Webtwic = Webtwic || {};

var browser = bowser;

var test_canvas = document.createElement("canvas");
var canvascheck = (test_canvas.getContext) ? true : false;

Webtwic = {
	// Basic Information about Webtwic
	name: "Webtwic",
	description: "A community for coding and tech tweaks where beginners and experts can learn.",
	repo: "https://github.com/whizkydee/whizkydee.github.io",
	author: "Olaolu Olawuyi",
	version: 1.07,

	// Start main functions for the object

	// Function to add browser name and version to body class
	_showBrowser: function( b ) {
		$("body").addClass(b + " " + b + parseInt(browser.version));
	},

	// Function to set attributes and values to elements
	_setAttr: function( elem, name, val ) {
		$(elem, this).attr(name, val);
	},

	// Function to push down .site-content
	_adjustSiteContent: function() {
		if ( $("body").hasClass("default-body") ) {
			$(".top-stripe").addClass("adjustedMargin");
			$("#header .logo").addClass("adjustedTop");
			$(".main-menu").addClass("adjustedMargin");
			$("#header").addClass("adjustSiteContent");
		} else if ( $("body").hasClass("secondary-body") ) {
			$(".site-content").addClass("adjustSiteContent");
			$(".secondary-header").addClass("adjustedMargin");
		}
	},

	// Function to push up .site-content to default state
	_undoSiteAdjust: function() {
		if ( $("body").hasClass("default-body") ) {
			$(".top-stripe").removeClass("adjustedMargin");
			$("#header .logo").removeClass("adjustedTop");
			$(".main-menu").removeClass("adjustedMargin");
			$("#header").removeClass("adjustSiteContent");
		} else if ( $("body").hasClass("secondary-body") ) {
			$(".secondary-header").removeClass("adjustedMargin");
		}
	},

	// Function to show Notifications before header
	_showNotif: function( text ) {
		text = (typeof text == "undefined") ? notif_text : text;
		Webtwic._adjustSiteContent();
		$("body").prepend(
			"
"+text+""+close_button+"
"
		);

		$(".close-button").on("click", function(e) {
			e.preventDefault();
			Webtwic._undoReset();
		});
	},

	// Function to hide Notifications
	_hideNotif: function() {
		$("#notifBanner").removeClass("notif_vis");
	},

	_resetSite: function() {
		Webtwic._showNotif();
		Webtwic._adjustSiteContent();
	},

	_undoReset: function() {
		Webtwic._hideNotif();
		Webtwic._undoSiteAdjust();
	},
}, WBT = Webtwic,

$$ = Webtwic,

close_button = "";

notif_text = "Some features which affect the functionality of webtwic are disabled in your browser. Please try refreshing the page or get a better browser.";

// Detect when the document is ready

jQuery(document).ready(function() {
	// Test for HTML5 support
	if ( window.Modernizr ) {
		if ( !Modernizr.canvas ) {
			Webtwic._showNotif ( "Oops. Looks like your browser doesn't support HTML5. Please get a better browser for an awesome experience.");
		} else {
			// Do nothing.
		}
	} else if ( !window.Modernizr ) {
		if ( canvascheck == false ) {
			Webtwic._showNotif ( "Oops. Looks like your browser doesn't support HTML5. Please get a better browser for an awesome experience.");
		} else {
			// Do nothing.
		}
	} else {
		// Do nothing.
	}

	// Define Variables
	var $scroll_top = $("a.scroll_top"),
	is_toggle_active = $(".hamburger").hasClass("is_active"),
	height = 200;

	// Performance Fixes

	// Start browser detection

	browser.ie = browser.msie;

	if ( browser.webkit ) {
		$("body").addClass("webkit");
	}
	if ( browser.chrome ) {
		Webtwic._showBrowser("chrome");
	}
	if ( browser.msedge ) {
		Webtwic._showBrowser("msedge");
	}
	if ( browser.firefox ) {
		Webtwic._showBrowser("firefox");
	}
	if ( browser.msie ) {
		Webtwic._showBrowser("ie");
	}
	if ( browser.safari ) {
		Webtwic._showBrowser("safari");
	}
	if ( browser.opera ) {
		Webtwic._showBrowser("opera");
	}

	/*
		TODO: Rebuild Performance fixes for attributes
		See history of Performance fixes.
		Also, check StackOverflow.
		See Issue #12
	*/

	if ( window.Modernizr ) {
		if ( !Modernizr.flexbox || !Modernizr.inlinesvg || !Modernizr.svg || !Modernizr.svgclippaths || !Modernizr.fontface || !Modernizr.boxshadow || !Modernizr.borderradius || !Modernizr.csstransforms ) {
			Webtwic._showNotif();
		} else {
			// Do nothing.
		}
	} else {
		// Do nothing.
	}

	// Start Main Page

	$("nav li ul.drop-nav").hide().removeClass("dropNavFallback");

	if ( $(window).width() > 860 ) {
		$("nav li.dropdown").hover(function() {
			$("ul.drop-nav", this).stop().slideDown("fast");
		}, function() {
			$("ul.drop-nav", this).stop().slideUp("fast");
		});
	}

	$(".active-item").append(
		"<svg viewBox='0 0 32 32' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'><path d='M 16.682,19.674c 0.010-0.012, 0.014-0.028, 0.024-0.040l 6.982-7.714c 0.39-0.434, 0.39-1.138,0-1.572 c-0.004-0.004-0.008-0.006-0.012-0.008C 23.496,10.13, 23.244,10, 22.964,10L 8.998,10 c-0.286,0-0.54,0.138-0.722,0.352L 8.272,10.348 c-0.39,0.434-0.39,1.138,0,1.572l 6.998,7.754C 15.66,20.108, 16.292,20.108, 16.682,19.674z'></path></svg>"
	);

	$("a.hamburger").click(function( e ) {
		$(this).toggleClass("is_active");

		e.preventDefault();
	});
	$(".mobile-header .mobile-nav").hide();

	$(window).scroll(function() {
		($(this).scrollTop() > height) ? $scroll_top.addClass("topVisible"): $scroll_top.removeClass("topVisible");
	});

	// Styles for homepage article-social

	$(".article .article-social a").hover(function() {
		$("span", this).eq(1).fadeIn(400);
	}, function() {
		$("span", this).eq(1).fadeOut(250);
	});

	// Functions for search-icon and ui-overlay-search

	$(".header-follow-search .search-wrap").on("click", function() {
		openUiOverlay();
	});

	$(".header-follow-search .close-icon").on("click", function(e) {
		e.preventDefault();
		closeUiOverlay();
	});

	$(".header-follow-search .close-icon").hover(
		function() {
			$(this).addClass("spin");
		},
		function() {
			$(this).removeClass("spin");
	});

	function openUiOverlay() {
		$(".ui-overlay-search").fadeIn(400).addClass("is_open");
	}

	function closeUiOverlay() {
		$(".ui-overlay-search").fadeOut(400).removeClass("is_open");
	}

	$(".ui-overlay-search .search-input input").focus(function() {
		$(".search-input").attr("data-focused", true);
		$(".search-input input").addClass("_is-focused");
		$("#__expand").addClass("visible");
	});

	$(".ui-overlay-search .search-input input").blur(function() {
		$(".search-input").attr("data-focused", false);
		$(".search-input input").removeClass("_is-focused");
		$("#__expand").removeClass("visible");
	});

	$(".post-meta .post-meta-inner .cta-btns a.is_inactive").on("click", function( e ) {
		e.preventDefault();
	});

	$(document).keydown(function( e ) {
    if ( e.keyCode == 27 ) {
        closeUiOverlay();
    } else {
		 // Do nothing.
	 }});

	 $(".mobile-nav").hide();

	// Functions for more-posts button click

	function addLoader() {
		$(".secondary-category-section .category-posts-column [data-clicked='false']").attr("data-clicked", "true").append("");
	}
	$(".secondary-category-section .category-posts-column [data-clicked='false']").on("click", function( e ) {
		$(this).css({
			"background": "#50ABF1",
			"color": "#fff"
		});
		addLoader();
		e.preventDefault();
	});

	$scroll_top.on("click", function( e ) {
		$("body,html").animate({
			scrollTop: 0
		}, 1000);

		e.preventDefault();
	});

});
<|endoftext|>


<commit_before>var socket = io.connect();
var $dele = $('#dele');
var $button1 = $('#button1');var counter=0;var moves=0;var gamecount=1;var playersname;var iden;
var visited1=0;
var visited2=0;
var visited3=0;
var visited4=0;
var visited5=0;
var visited6=0;
var visited7=0;
var visited8=0;
var visited9=0;
var ismoved=0;
var $button2 = $('#button2');
var $available=$('#available');
var $reset=$('#reset');
var $joinarea=$('#joinarea');
var $gamearea=$('#gamearea');
var $users=$('#users');
var $spot1=$('#spot1');
var $spot2=$('#spot2');
var $spot3=$('#spot3');
var $spot4=$('#spot4');
var $spot5=$('#spot5');
var $spot6=$('#spot6');
var $spot7=$('#spot7');
var $spot8=$('#spot8');
var $spot9=$('#spot9');
socket.on('available',function(data){
var html2='';
for(var i=0;i<data.length;i++)
{
html2+='
Game id:  '+data[i].id+'
';
}
$available.html(html2);
});
$button1.click(function(e){
e.preventDefault();
mbox.prompt("Enter Your name",function(result){
    socket.emit('create',result);
});
socket.on('created',function(data){
  $joinarea.hide();
  $gamearea.show();
    iden=data.id;
  var html1='
Game id:  '+data.id+'
';var list=data.list; var html2='';
  for(i=0;i<list.length;i++)
  {
    html2+='
'+list[i]+'
';
  }
  html1+=html2;
  $users.html(html1);
});
});
$button2.click(function(e){
e.preventDefault();
mbox.prompt("enter the id of game you want to enter:",function(result){
    socket.emit('join',result);
    socket.on('player2name',function(data){
      mbox.prompt("enter your name:",function(result){
        if(result)
        {socket.emit('gamestart',result);}
      });
    });
});
});

socket.on('joined',function(data){
$joinarea.hide();
$gamearea.show();
    iden=data.id;
var html1='
Game id:  '+data.id+'
';var list=data.list; var html2='';
for(i=0;i<list.length;i++)
{
  html2+='
'+list[i]+'
';
}
html1+=html2;
$users.html(html1);
  socket.emit('namelist',gamecount);
});

$dele.click(function(e){
    e.preventDefault();
    socket.emit('disconnect',iden);
    $gamearea.hide();
    $joinarea.show();

});
socket.on('display',function(data){
var html1='
Game id:  '+data.id+'
';var list=data.list; var html2='';
for(i=0;i<list.length;i++)
{
  html2+='
'+list[i]+'
';
}
html1+=html2;
$users.html(html1);
});
socket.on('firstmove',function(data){
mbox.alert(data[1]+" will make the first move",function(err,result){
  if (err) throw err;
});
});
$spot1.click(function(){
    if(visited1==0)
    {
  if(counter==0)
  {document.getElementById("spot1").innerHTML ="O";counter=counter+1;}
  else {
    document.getElementById("spot1").innerHTML = "X";counter=counter-1;
  }
   visited1=1;
  socket.emit('check',{area:"spot1",counter:counter,moves:moves,visited:visited1});

    }

});
socket.on('checked',function(data){
   data.visited=1;
if(data.counter==0)
{document.getElementById(data.area).innerHTML="X";}
else {
  document.getElementById(data.area).innerHTML="O";
}
    document.getElementById(data.area).click(false);
counter=data.counter;moves=data.moves+1;
if(($spot1.text()=="X"&&$spot2.text()=="X"&&$spot3.text()=="X")||($spot4.text()=="X"&&$spot5.text()=="X"&&$spot6.text()=="X")||($spot7.text()=="X"&&$spot8.text()=="X"&&$spot9.text()=="X")||($spot1.text()=="X"&&$spot4.text()=="X"&&$spot7.text()=="X")
||($spot2.text()=="X"&&$spot5.text()=="X"&&$spot8.text()=="X")||($spot3.text()=="X"&&$spot6.text()=="X"&&$spot9.text()=="X")||($spot1.text()=="X"&&$spot5.text()=="X"&&$spot9.text()=="X")||($spot3.text()=="X"&&$spot5.text()=="X"&&$spot7.text()=="X"))
{
    moves=0;counter=0;
  mbox.alert(playersname[(gamecount+1)%2]+" won the game!!..Press Reset to start new game",function(err,result){
    if (err) throw err;
  });
}
else if(($spot1.text()=="O"&&$spot2.text()=="O"&&$spot3.text()=="O")||($spot4.text()=="O"&&$spot5.text()=="O"&&$spot6.text()=="O")||($spot7.text()=="O"&&$spot8.text()=="O"&&$spot9.text()=="O")||($spot1.text()=="O"&&$spot4.text()=="O"&&$spot7.text()=="O")
||($spot2.text()=="O"&&$spot5.text()=="O"&&$spot8.text()=="O")||($spot3.text()=="O"&&$spot6.text()=="O"&&$spot9.text()=="O")||($spot1.text()=="O"&&$spot5.text()=="O"&&$spot9.text()=="O")||($spot3.text()=="O"&&$spot5.text()=="O"&&$spot7.text()=="O"))
{
    moves=0;counter=0;
    mbox.alert(playersname[gamecount]+" won the game!!..Press Reset to start new game",function(err,result){
      if (err) throw err;
    });
}
else if(moves==9)
{
  socket.emit('draw',gamecount);
  mbox.alert("the game resulted in draw",function(err,result){
    if (err) throw err;
    mbox.alert("Press Reset to start new game",function(err,result){
      if (err) throw err;
    });
  });
    socket.emit('namelist',gamecount);
}
});
socket.on('newgame1',function(data){
moves=0;counter=0;
});
$reset.click(function(e){
e.preventDefault();
$spot1.empty();$spot2.empty();$spot3.empty();$spot4.empty();$spot5.empty();$spot6.empty();$spot7.empty();$spot8.empty();$spot9.empty();
gamecount=gamecount+1;gamecount=gamecount%2;
    visited1=0;visited2=0;visited3=0;visited4=0;visited5=0;visited6=0;visited7=0;visited8=0;visited9=0;
mbox.alert(playersname[gamecount]+" will make first move",function(err,result){
  if (err) throw err;
});
});
socket.on('gotnamelist',function(data){
  playersname=data.list;
});
$spot2.click(function(){
     if(visited2==0)
    {
  if(counter==0)
  {document.getElementById("spot2").innerHTML ="O";counter=counter+1;}
  else {
    document.getElementById("spot2").innerHTML = "X";counter=counter-1;
  }
      visited2=1;
  socket.emit('check',{area:"spot2",counter:counter,moves:moves,visited:visited2});

    }
  });
$spot3.click(function(){
     if(visited3==0)
    {
  if(counter==0)
  {document.getElementById("spot3").innerHTML ="O";counter=counter+1;}
  else {
    document.getElementById("spot3").innerHTML = "X";counter=counter-1;
  }
     visited3=1;
  socket.emit('check',{area:"spot3",counter:counter,moves:moves,visited:visited3});

    }

});
$spot4.click(function(){
     if(visited4==0)
    {
  if(counter==0)
  {document.getElementById("spot4").innerHTML ="O";counter=counter+1;}
  else {
    document.getElementById("spot4").innerHTML = "X";counter=counter-1;
  }
     visited4=1;
  socket.emit('check',{area:"spot4",counter:counter,moves:moves,visited:visited4});

    }
});
$spot5.click(function(){
     if(visited5==0)
    {
  if(counter==0)
  {document.getElementById("spot5").innerHTML ="O";counter=counter+1;}
  else {
    document.getElementById("spot5").innerHTML = "X";counter=counter-1;
  }
      visited5=1;
  socket.emit('check',{area:"spot5",counter:counter,moves:moves,visited:visited5});

    }
});
$spot6.click(function(){
     if(visited6==0)
    {
  if(counter==0)
  {document.getElementById("spot6").innerHTML ="O";counter=counter+1;}
  else {
    document.getElementById("spot6").innerHTML = "X";counter=counter-1;
  }
      visited6=1;
  socket.emit('check',{area:"spot6",counter:counter,moves:moves,visited:visited6});

    }
});
$spot7.click(function(){
     if(visited7==0)
    {
  if(counter==0)
  {document.getElementById("spot7").innerHTML ="O";counter=counter+1;}
  else {
    document.getElementById("spot7").innerHTML = "X";counter=counter-1;
  }
       visited7=1;
  socket.emit('check',{area:"spot7",counter:counter,moves:moves,visited:visited7});

    }
                });
$spot8.click(function(){
     if(visited8==0)
    {
  if(counter==0)
  {document.getElementById("spot8").innerHTML ="O";counter=counter+1;}
  else {
    document.getElementById("spot8").innerHTML = "X";counter=counter-1;
  }
     visited8=1;
  socket.emit('check',{area:"spot8",counter:counter,moves:moves,visited:visited8});

    }
                });
$spot9.click(function(){
     if(visited9==0)
    {
  if(counter==0)
  {document.getElementById("spot9").innerHTML ="O";counter=counter+1;}
  else {
    document.getElementById("spot9").innerHTML = "X";counter=counter-1;
  }
    visited9=1;
  socket.emit('check',{area:"spot9",counter:counter,moves:moves,visited:visited9});

    }

});
socket.on('reset',function(data){counter=0;moves=0;gamecount=1;
$spot1.empty();$spot2.empty();$spot3.empty();$spot4.empty();$spot5.empty();$spot6.empty();$spot7.empty();$spot8.empty();$spot9.empty();
});
<commit_msg>Update script.js<commit_after>var socket = io.connect();
var $dele = $('#dele');
var $button1 = $('#button1');var counter=0;var moves=0;var gamecount=1;var playersname;var iden;
var visited1=0;
var visited2=0;
var visited3=0;
var visited4=0;
var visited5=0;
var visited6=0;
var visited7=0;
var visited8=0;
var visited9=0;
var ismoved=0;
var $button2 = $('#button2');
var $available=$('#available');
var $reset=$('#reset');
var $joinarea=$('#joinarea');
var $gamearea=$('#gamearea');
var $users=$('#users');
var $spot1=$('#spot1');
var $spot2=$('#spot2');
var $spot3=$('#spot3');
var $spot4=$('#spot4');
var $spot5=$('#spot5');
var $spot6=$('#spot6');
var $spot7=$('#spot7');
var $spot8=$('#spot8');
var $spot9=$('#spot9');
socket.on('available',function(data){
var html2='';
for(var i=0;i<data.length;i++)
{
html2+='
Game id:  '+data[i].id+'
';
}
$available.html(html2);
});
$button1.click(function(e){
e.preventDefault();
mbox.prompt("Enter Your name",function(result){
    socket.emit('create',result);
});
socket.on('created',function(data){
  $joinarea.hide();
  $gamearea.show();
    iden=data.id;
  var html1='
Game id:  '+data.id+'
';var list=data.list; var html2='';
  for(i=0;i<list.length;i++)
  {
    html2+='
'+list[i]+'
';
  }
  html1+=html2;
  $users.html(html1);
});
});
$button2.click(function(e){
e.preventDefault();
mbox.prompt("enter the id of game you want to enter:",function(result){
    socket.emit('join',result);
    socket.on('player2name',function(data){
      mbox.prompt("enter your name:",function(result){
        if(result)
        {socket.emit('gamestart',result);}
      });
    });
});
});

socket.on('joined',function(data){
$joinarea.hide();
$gamearea.show();
    iden=data.id;
var html1='
Game id:  '+data.id+'
';var list=data.list; var html2='';
for(i=0;i<list.length;i++)
{
  html2+='
'+list[i]+'
';
}
html1+=html2;
$users.html(html1);
  socket.emit('namelist',gamecount);
});

$dele.click(function(e){
    e.preventDefault();
    socket.emit('dismiss',iden);
    $gamearea.hide();
    $joinarea.show();

});
socket.on('display',function(data){
var html1='
Game id:  '+data.id+'
';var list=data.list; var html2='';
for(i=0;i<list.length;i++)
{
  html2+='
'+list[i]+'
';
}
html1+=html2;
$users.html(html1);
});
socket.on('firstmove',function(data){
mbox.alert(data[1]+" will make the first move",function(err,result){
  if (err) throw err;
});
});
$spot1.click(function(){
    if(visited1==0)
    {
  if(counter==0)
  {document.getElementById("spot1").innerHTML ="O";counter=counter+1;}
  else {
    document.getElementById("spot1").innerHTML = "X";counter=counter-1;
  }
   visited1=1;
  socket.emit('check',{area:"spot1",counter:counter,moves:moves,visited:visited1});

    }

});
socket.on('checked',function(data){
   data.visited=1;
if(data.counter==0)
{document.getElementById(data.area).innerHTML="X";}
else {
  document.getElementById(data.area).innerHTML="O";
}
    document.getElementById(data.area).click(false);
counter=data.counter;moves=data.moves+1;
if(($spot1.text()=="X"&&$spot2.text()=="X"&&$spot3.text()=="X")||($spot4.text()=="X"&&$spot5.text()=="X"&&$spot6.text()=="X")||($spot7.text()=="X"&&$spot8.text()=="X"&&$spot9.text()=="X")||($spot1.text()=="X"&&$spot4.text()=="X"&&$spot7.text()=="X")
||($spot2.text()=="X"&&$spot5.text()=="X"&&$spot8.text()=="X")||($spot3.text()=="X"&&$spot6.text()=="X"&&$spot9.text()=="X")||($spot1.text()=="X"&&$spot5.text()=="X"&&$spot9.text()=="X")||($spot3.text()=="X"&&$spot5.text()=="X"&&$spot7.text()=="X"))
{
    moves=0;counter=0;
  mbox.alert(playersname[(gamecount+1)%2]+" won the game!!..Press Reset to start new game",function(err,result){
    if (err) throw err;
  });
}
else if(($spot1.text()=="O"&&$spot2.text()=="O"&&$spot3.text()=="O")||($spot4.text()=="O"&&$spot5.text()=="O"&&$spot6.text()=="O")||($spot7.text()=="O"&&$spot8.text()=="O"&&$spot9.text()=="O")||($spot1.text()=="O"&&$spot4.text()=="O"&&$spot7.text()=="O")
||($spot2.text()=="O"&&$spot5.text()=="O"&&$spot8.text()=="O")||($spot3.text()=="O"&&$spot6.text()=="O"&&$spot9.text()=="O")||($spot1.text()=="O"&&$spot5.text()=="O"&&$spot9.text()=="O")||($spot3.text()=="O"&&$spot5.text()=="O"&&$spot7.text()=="O"))
{
    moves=0;counter=0;
    mbox.alert(playersname[gamecount]+" won the game!!..Press Reset to start new game",function(err,result){
      if (err) throw err;
    });
}
else if(moves==9)
{
  socket.emit('draw',gamecount);
  mbox.alert("the game resulted in draw",function(err,result){
    if (err) throw err;
    mbox.alert("Press Reset to start new game",function(err,result){
      if (err) throw err;
    });
  });
    socket.emit('namelist',gamecount);
}
});
socket.on('newgame1',function(data){
moves=0;counter=0;
});
$reset.click(function(e){
e.preventDefault();
$spot1.empty();$spot2.empty();$spot3.empty();$spot4.empty();$spot5.empty();$spot6.empty();$spot7.empty();$spot8.empty();$spot9.empty();
gamecount=gamecount+1;gamecount=gamecount%2;
    visited1=0;visited2=0;visited3=0;visited4=0;visited5=0;visited6=0;visited7=0;visited8=0;visited9=0;
mbox.alert(playersname[gamecount]+" will make first move",function(err,result){
  if (err) throw err;
});
});
socket.on('gotnamelist',function(data){
  playersname=data.list;
});
$spot2.click(function(){
     if(visited2==0)
    {
  if(counter==0)
  {document.getElementById("spot2").innerHTML ="O";counter=counter+1;}
  else {
    document.getElementById("spot2").innerHTML = "X";counter=counter-1;
  }
      visited2=1;
  socket.emit('check',{area:"spot2",counter:counter,moves:moves,visited:visited2});

    }
  });
$spot3.click(function(){
     if(visited3==0)
    {
  if(counter==0)
  {document.getElementById("spot3").innerHTML ="O";counter=counter+1;}
  else {
    document.getElementById("spot3").innerHTML = "X";counter=counter-1;
  }
     visited3=1;
  socket.emit('check',{area:"spot3",counter:counter,moves:moves,visited:visited3});

    }

});
$spot4.click(function(){
     if(visited4==0)
    {
  if(counter==0)
  {document.getElementById("spot4").innerHTML ="O";counter=counter+1;}
  else {
    document.getElementById("spot4").innerHTML = "X";counter=counter-1;
  }
     visited4=1;
  socket.emit('check',{area:"spot4",counter:counter,moves:moves,visited:visited4});

    }
});
$spot5.click(function(){
     if(visited5==0)
    {
  if(counter==0)
  {document.getElementById("spot5").innerHTML ="O";counter=counter+1;}
  else {
    document.getElementById("spot5").innerHTML = "X";counter=counter-1;
  }
      visited5=1;
  socket.emit('check',{area:"spot5",counter:counter,moves:moves,visited:visited5});

    }
});
$spot6.click(function(){
     if(visited6==0)
    {
  if(counter==0)
  {document.getElementById("spot6").innerHTML ="O";counter=counter+1;}
  else {
    document.getElementById("spot6").innerHTML = "X";counter=counter-1;
  }
      visited6=1;
  socket.emit('check',{area:"spot6",counter:counter,moves:moves,visited:visited6});

    }
});
$spot7.click(function(){
     if(visited7==0)
    {
  if(counter==0)
  {document.getElementById("spot7").innerHTML ="O";counter=counter+1;}
  else {
    document.getElementById("spot7").innerHTML = "X";counter=counter-1;
  }
       visited7=1;
  socket.emit('check',{area:"spot7",counter:counter,moves:moves,visited:visited7});

    }
                });
$spot8.click(function(){
     if(visited8==0)
    {
  if(counter==0)
  {document.getElementById("spot8").innerHTML ="O";counter=counter+1;}
  else {
    document.getElementById("spot8").innerHTML = "X";counter=counter-1;
  }
     visited8=1;
  socket.emit('check',{area:"spot8",counter:counter,moves:moves,visited:visited8});

    }
                });
$spot9.click(function(){
     if(visited9==0)
    {
  if(counter==0)
  {document.getElementById("spot9").innerHTML ="O";counter=counter+1;}
  else {
    document.getElementById("spot9").innerHTML = "X";counter=counter-1;
  }
    visited9=1;
  socket.emit('check',{area:"spot9",counter:counter,moves:moves,visited:visited9});

    }

});
socket.on('reset',function(data){counter=0;moves=0;gamecount=1;
$spot1.empty();$spot2.empty();$spot3.empty();$spot4.empty();$spot5.empty();$spot6.empty();$spot7.empty();$spot8.empty();$spot9.empty();
});
<|endoftext|>


<commit_before>"use strict";

module.exports = function( definitions ) {
	return function( name ) {
		if ( !definitions.hasOwnProperty( name ) ) {
			throw "unknown class " + name;
		}
		return definitions[ name ];
	};
};
<commit_msg>Makes sure the definition getter is only called once<commit_after>"use strict";

module.exports = function( definitions ) {
	var alreadyRequested = {};
	return function( name ) {
		if ( !definitions.hasOwnProperty( name ) ) {
			throw "unknown class " + name;
		}
		if ( alreadyRequested.hasOwnProperty( name ) ) {
			throw "class " + name + " was already requested earlier";
		}
		return definitions[ name ];
	};
};
<|endoftext|>


<commit_before>/**
 * Created by jitrixis on 26/07/2016.
 */
color = ["green", "blue", "red", "purple", "yellow"];
appCache = window.applicationCache;
cacheNotif = {
    "error":{
        ".cache-notice .cache-icon": "./vendor/schedule-app-core/img/icon-cache-error.svg",
        ".cache-notice .cache-text": "Votre navigateur ne supporte pas la fonctionnalité hors-ligne."
    },
    "busy":{
        ".cache-notice .cache-icon": "./vendor/schedule-app-core/img/icon-cache-busy.svg",
        ".cache-notice .cache-text": "Chargement en cours."
    },
    "warning":{
        ".cache-notice .cache-icon": "./vendor/schedule-app-core/img/icon-cache-warning.svg",
        ".cache-notice .cache-text": "Une mise à jour est disponible. Recharger la page."
    },
    "ok":{
        ".cache-notice .cache-icon": "./vendor/schedule-app-core/img/icon-cache-ok.svg",
        ".cache-notice .cache-text": "Regardez ce programme hors-ligne."
    },
    "offline":{
        ".cache-notice .cache-icon": "./vendor/schedule-app-core/img/icon-offline.svg",
        ".cache-notice .cache-text": "Vous êtes actuellement hors-ligne."
    }
};
cacheNotif["obsolete"] = cacheNotif["error"];
cacheNotif["cached"] = cacheNotif["ok"];
cacheNotif["noupdate"] = cacheNotif["ok"];
cacheNotif["online"] = cacheNotif["ok"];
cacheNotif["checking"] = cacheNotif["busy"];
cacheNotif["downloading"] = cacheNotif["busy"];
cacheNotif["progress"] = cacheNotif["busy"];
cacheNotif["updateready"] = cacheNotif["warning"];

// Fired after the first cache of the manifest.
appCache.addEventListener('cached', handleCacheEvent, false);

// Checking for an update. Always the first event fired in the sequence.
appCache.addEventListener('checking', handleCacheEvent, false);

// An update was found. The browser is fetching resources.
appCache.addEventListener('downloading', handleCacheEvent, false);

// The manifest returns 404 or 410, the download failed,
// or the manifest changed while the download was in progress.
appCache.addEventListener('error', handleCacheEvent, false);

// Fired after the first download of the manifest.
appCache.addEventListener('noupdate', handleCacheEvent, false);

// Fired if the manifest file returns a 404 or 410.
// This results in the application cache being deleted.
appCache.addEventListener('obsolete', handleCacheEvent, false);

// Fired for each resource listed in the manifest as it is being fetched.
appCache.addEventListener('progress', handleCacheEvent, false);

// Fired when the manifest resources have been newly redownloaded.
appCache.addEventListener('updateready', handleCacheEvent, false);

window.addEventListener("offline", handleCacheEvent, false);

window.addEventListener("online", handleCacheEvent, false);

function changeNotice(type, progress){
    if(cacheNotif.hasOwnProperty(type)){
        notif = cacheNotif[type];
        $.each(notif, function(selector, value) {
            if($(selector).prop("tagName") == "IMG"){
                $(selector).attr("src", value)
            }else {
                if(progress != -1){
                    $(selector).text(value + " ( " + Math.round(progress*100) + "% )");
                }else {
                    $(selector).text(value);
                }
            }
        });
    }
}

function handleCacheEvent(e) {
    if(e.type == "progress"){
        changeNotice(e.type, e.loaded / e.total);
    }else {
        changeNotice(e.type, -1);
    }
}

$( document ).ready(function () {
    switch (appCache.status) {
        case appCache.UNCACHED:
            changeNotice("error", -1);
            break;
        case appCache.IDLE:
            changeNotice("ok", -1);
            break;
        case appCache.CHECKING:
        case appCache.DOWNLOADING:
            changeNotice("busy", -1);
            break;
        case appCache.UPDATEREADY:
            changeNotice("warning", -1);
            break;
        case appCache.OBSOLETE:
            changeNotice("error", -1);
            break;
        default:
            changeNotice("error", -1);
            break;
    }
    if(!navigator.onLine){
        changeNotice("offline", -1);
    }
});

$("ul li a, #page-links a").click(function(){
    $("body").attr("data-theme", color[(color.indexOf($("body").attr("data-theme"))+1)%5])
});<commit_msg>#21 Interaction avec la bannière hors-ligne<commit_after>/**
 * Created by jitrixis on 26/07/2016.
 */
color = ["green", "blue", "red", "purple", "yellow"];
appCache = window.applicationCache;
cacheNotif = {
    "error":{
        ".cache-notice .cache-icon": "./vendor/schedule-app-core/img/icon-cache-error.svg",
        ".cache-notice .cache-text": "Votre navigateur ne supporte pas la fonctionnalité hors-ligne."
    },
    "busy":{
        ".cache-notice .cache-icon": "./vendor/schedule-app-core/img/icon-cache-busy.svg",
        ".cache-notice .cache-text": "Chargement en cours."
    },
    "warning":{
        ".cache-notice .cache-icon": "./vendor/schedule-app-core/img/icon-cache-warning.svg",
        ".cache-notice .cache-text": "Une mise à jour est disponible. Recharger la page."
    },
    "ok":{
        ".cache-notice .cache-icon": "./vendor/schedule-app-core/img/icon-cache-ok.svg",
        ".cache-notice .cache-text": "Regardez ce programme hors-ligne."
    },
    "offline":{
        ".cache-notice .cache-icon": "./vendor/schedule-app-core/img/icon-offline.svg",
        ".cache-notice .cache-text": "Vous êtes actuellement hors-ligne."
    }
};
cacheNotif["obsolete"] = cacheNotif["error"];
cacheNotif["cached"] = cacheNotif["ok"];
cacheNotif["noupdate"] = cacheNotif["ok"];
cacheNotif["online"] = cacheNotif["ok"];
cacheNotif["checking"] = cacheNotif["busy"];
cacheNotif["downloading"] = cacheNotif["busy"];
cacheNotif["progress"] = cacheNotif["busy"];
cacheNotif["updateready"] = cacheNotif["warning"];

// Fired after the first cache of the manifest.
appCache.addEventListener('cached', handleCacheEvent, false);

// Checking for an update. Always the first event fired in the sequence.
appCache.addEventListener('checking', handleCacheEvent, false);

// An update was found. The browser is fetching resources.
appCache.addEventListener('downloading', handleCacheEvent, false);

// The manifest returns 404 or 410, the download failed,
// or the manifest changed while the download was in progress.
appCache.addEventListener('error', handleCacheEvent, false);

// Fired after the first download of the manifest.
appCache.addEventListener('noupdate', handleCacheEvent, false);

// Fired if the manifest file returns a 404 or 410.
// This results in the application cache being deleted.
appCache.addEventListener('obsolete', handleCacheEvent, false);

// Fired for each resource listed in the manifest as it is being fetched.
appCache.addEventListener('progress', handleCacheEvent, false);

// Fired when the manifest resources have been newly redownloaded.
appCache.addEventListener('updateready', handleCacheEvent, false);

window.addEventListener("offline", handleCacheEvent, false);

window.addEventListener("online", handleCacheEvent, false);

function changeNotice(type, progress){
    if(cacheNotif.hasOwnProperty(type)){
        notif = cacheNotif[type];
        $.each(notif, function(selector, value) {
            if($(selector).prop("tagName") == "IMG"){
                $(selector).attr("src", value)
            }else {
                if(progress != -1){
                    $(selector).text(value + " ( " + Math.round(progress*100) + "% )");
                }else {
                    $(selector).text(value);
                }
            }
        });
    }
}

function handleCacheEvent(e) {
    if(e.type == "progress"){
        changeNotice(e.type, e.loaded / e.total);
    }else {
        changeNotice(e.type, -1);
    }
    if(e.type == "updateready"){
        appCache.swapCache();
    }
}

$( document ).ready(function () {
    switch (appCache.status) {
        case appCache.UNCACHED:
            changeNotice("error", -1);
            break;
        case appCache.IDLE:
            changeNotice("ok", -1);
            break;
        case appCache.CHECKING:
        case appCache.DOWNLOADING:
            changeNotice("busy", -1);
            break;
        case appCache.UPDATEREADY:
            changeNotice("warning", -1);
            break;
        case appCache.OBSOLETE:
            changeNotice("error", -1);
            break;
        default:
            changeNotice("error", -1);
            break;
    }
    if(!navigator.onLine){
        changeNotice("offline", -1);
    }
});

$("ul li a, #page-links a").click(function(){
    $("body").attr("data-theme", color[(color.indexOf($("body").attr("data-theme"))+1)%5])
});

$(".cache-notice").click(function(){
    appCache.update();
});<|endoftext|>