<commit_before>// Main js file.

// global app information
var global = null;

var selectedDistro = null;

// load apps.json, with a deferred object.
function getapps(d1, distro) {

    addDistro(distro);

    var json = null;
    var file = "distro/" + distro + ".json";

    console.log("Getting file " + file);

    $.ajax({

        "url": file,
        "dataType": "json",
        "success": function (data) {
            json = data;
        }

    }).done(function() {
        d1.resolve(json);
    });
}

// set up package manager here.
function addDistro(distro) {

    var option = "";

    $("#apps").empty();

    if ($("input[name='yes']").is(':checked')) {

        switch(distro) {
            case "ubuntu":
            case "debian":
            case "fedora":
                option += " -y";
                break;

            case "arch":
                option += " --noconfirm";
                break;

            case "global":
                break;

            default:
                console.log("Distro: " + distro + " not supported, please implement if possible.");
                break;
        }
    }

    switch(distro) {
        case "ubuntu":
        case "debian":
            $("#apps").append("sudo apt-get install" + option);
            break;

        case "fedora":
            $("#apps").append("sudo yum install" + option);
            break;

        case "arch":
            $("#apps").append("sudo pacman -S" + option);
            break;

        case "global":
            break;

        default:
            console.log("Distro: " + distro + " not supported, please implement.");
            break;
    }
}

// generates the category list, apps referes to a json
function distroSelect(distro) {

    selectedDistro = distro;

    var d = $.Deferred();
    getapps(d, distro);

    $.when(d).done(function(apps) {

        console.log("done getting distro: " + distro + ", generating apps");

        // remove all elements in app-choice before generating
        $("#app-choice").empty();

        var types = [];

        // generate the categories
        for (var i = 0; i < global.length; i++) {

            var categoryGlobal = global[i];
            var categoryDistro = apps[i];
            types.push($.extend(true, categoryGlobal, categoryDistro));
        }

        //console.log(types);

        // 0. selects 1st array
        $.each(types, function (array, category) {
            // 1. selects category
            $.each(category, function (categoryName, application) {
                //console.log(categoryName);
                html = "

" + categoryName + "
";
                // 2. selects app
                $.each(application, function (appName, applicationDetails) {
                    //console.log("2: " + appName + "=" + subObject);
                    var appIcon = null;
                    var appProg = null;
                    // 3. selects app values
                    $.each(applicationDetails, function (name, value) {
                        //console.log("3: " + name + "=" + value);

                        switch(name) {
                            case "icon":
                                appImg = value;
                                break;
                            case "program":
                                appProg = value;
                                break;
                        }
                    });

                    html += "<input type=\"checkbox\" name=\"appProg\" value=\"" + appProg + "\"> ";
                    html += "";
                    html += "" + appName + "
";
                });

                html += "
";
                $("#app-choice").append(html);
            });
        });
    });
}

function appendAppList(appList) {
    addDistro(selectedDistro);

    for (app in appList) {
        //console.log(app);
        $("#apps").append(" " + appList[app]);
    }
}

function updateAppArea() {

    var appList = [];

    $("input[name='appProg']").each(function() {

        if ($(this).is(":checked")) {
            //console.log(this.value);
            appList.push(this.value);
        }
    });

    //console.log(appList);
    appendAppList(appList);
}

$(document).ready(function() {

    // select ubuntu radio in case it's cached, may change later
    $("#ubuntu-select").prop("checked", true);

    // generate the global first
    var d = $.Deferred();
    getapps(d, "global");

    $.when(d).done(function(globalapps) {

        console.log("done getting global");
        global = globalapps;
        distroSelect("ubuntu");
    });

});

// generates the application picker
$("#distro-choice input").click(function() {
    distroSelect(this.value);
});

// adds the app to the textarea
$("body").on("click", ".category input", function() {
    updateAppArea();
});

$("body").on("click", "input[name='yes']", function() {
    updateAppArea();
})

// highlights the textarea
$("#apps").click(function() {
    this.select();
})<commit_msg>fixed variable name<commit_after>// Main js file.

// global app information
var global = null;

var selectedDistro = null;

// load apps.json, with a deferred object.
function getapps(d1, distro) {

    addDistro(distro);

    var json = null;
    var file = "distro/" + distro + ".json";

    console.log("Getting file " + file);

    $.ajax({

        "url": file,
        "dataType": "json",
        "success": function (data) {
            json = data;
        }

    }).done(function() {
        d1.resolve(json);
    });
}

// set up package manager here.
function addDistro(distro) {

    var option = "";

    $("#apps").empty();

    if ($("input[name='yes']").is(':checked')) {

        switch(distro) {
            case "ubuntu":
            case "debian":
            case "fedora":
                option += " -y";
                break;

            case "arch":
                option += " --noconfirm";
                break;

            case "global":
                break;

            default:
                console.log("Distro: " + distro + " not supported, please implement if possible.");
                break;
        }
    }

    switch(distro) {
        case "ubuntu":
        case "debian":
            $("#apps").append("sudo apt-get install" + option);
            break;

        case "fedora":
            $("#apps").append("sudo yum install" + option);
            break;

        case "arch":
            $("#apps").append("sudo pacman -S" + option);
            break;

        case "global":
            break;

        default:
            console.log("Distro: " + distro + " not supported, please implement.");
            break;
    }
}

// generates the category list, apps referes to a json
function distroSelect(distro) {

    selectedDistro = distro;

    var d = $.Deferred();
    getapps(d, distro);

    $.when(d).done(function(apps) {

        console.log("done getting distro: " + distro + ", generating apps");

        // remove all elements in app-choice before generating
        $("#app-choice").empty();

        var types = [];

        // generate the categories
        for (var i = 0; i < global.length; i++) {

            var categoryGlobal = global[i];
            var categoryDistro = apps[i];
            types.push($.extend(true, categoryGlobal, categoryDistro));
        }

        //console.log(types);

        // 0. selects 1st array
        $.each(types, function (array, category) {
            // 1. selects category
            $.each(category, function (categoryName, application) {
                //console.log(categoryName);
                html = "

" + categoryName + "
";
                // 2. selects app
                $.each(application, function (appName, applicationDetails) {
                    //console.log("2: " + appName + "=" + subObject);
                    var appIcon = null;
                    var appProg = null;
                    // 3. selects app values
                    $.each(applicationDetails, function (name, value) {
                        //console.log("3: " + name + "=" + value);

                        switch(name) {
                            case "icon":
                                appIcon = value;
                                break;
                            case "program":
                                appProg = value;
                                break;
                        }
                    });

                    html += "<input type=\"checkbox\" name=\"appProg\" value=\"" + appProg + "\"> ";
                    html += "";
                    html += "" + appName + "
";
                });

                html += "
";
                $("#app-choice").append(html);
            });
        });
    });
}

function appendAppList(appList) {
    addDistro(selectedDistro);

    for (app in appList) {
        //console.log(app);
        $("#apps").append(" " + appList[app]);
    }
}

function updateAppArea() {

    var appList = [];

    $("input[name='appProg']").each(function() {

        if ($(this).is(":checked")) {
            //console.log(this.value);
            appList.push(this.value);
        }
    });

    //console.log(appList);
    appendAppList(appList);
}

$(document).ready(function() {

    // select ubuntu radio in case it's cached, may change later
    $("#ubuntu-select").prop("checked", true);

    // generate the global first
    var d = $.Deferred();
    getapps(d, "global");

    $.when(d).done(function(globalapps) {

        console.log("done getting global");
        global = globalapps;
        distroSelect("ubuntu");
    });

});

// generates the application picker
$("#distro-choice input").click(function() {
    distroSelect(this.value);
});

// adds the app to the textarea
$("body").on("click", ".category input", function() {
    updateAppArea();
});

$("body").on("click", "input[name='yes']", function() {
    updateAppArea();
})

// highlights the textarea
$("#apps").click(function() {
    this.select();
})<|endoftext|>


<commit_before>data = [
    {
        "date": "2016-10-31",
        "question_value": "V2hhdCBpcyAxICsxPw",
        "question_type": "text",
        "answer_value": "Mg",
        "answer_type": "text",
        "story_value": "T25jZSB1cG9uIGEgdGltZS4uLg",
        "story_type": "text"
    },
    {
        "date": "2016-10-31",
        "question_value": "V2hhdCBpcyAxICsxPw",
        "question_type": "text",
        "answer_value": "Mg",
        "answer_type": "text",
        "story_value": "T25jZSB1cG9uIGEgdGltZS4uLg",
        "story_type": "text"
    }
];

function render(){
    suffix = "==";
    $('#question').text(atob(data[0]["question_value"]+suffix));

    $('#answer').text();
}

$( document ).ready(function() {
    render();
});
<commit_msg>Update main.js<commit_after>data = [
    {
        "date": "2016-10-31",
        "question_value": "V2hhdCBpcyAxICsxPw",
        "question_type": "text",
        "answer_value": "Mg",
        "answer_type": "text",
        "story_value": "T25jZSB1cG9uIGEgdGltZS4uLg",
        "story_type": "text"
    },
    {
        "date": "2016-10-31",
        "question_value": "V2hhdCBpcyAxICsxPw",
        "question_type": "text",
        "answer_value": "Mg",
        "answer_type": "text",
        "story_value": "T25jZSB1cG9uIGEgdGltZS4uLg",
        "story_type": "text"
    }
];

function render(){
    suffix = "==";
    $('#question').text(atob(data[0]["question_value"]+suffix));

    $('#answer').text();

    if ($('#answer').atob(val.()+suffix) == (data[0]["answer_value"]))
        $('#story').text(atob(data[0]["story_value"]+suffix));
        $('#story').show();
}

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


<commit_before>var $,
    i,
    j,
    k,
    questions,
    answerKey,
    userAnswer,
    selected,
    score;

questions = [
    {question: "What is my middle name?",
    choices: ["Sylvester", "Patrick", "Aaron", "David"],
    answer:1
    },
    {question: "How old am I?",
    choices: ["29", "27", "30", "28"],
    answer:0
    },
    {question: "In what state was I born?",
    choices: ["Idaho", "Tampa", "North Carolina", "California"],
    answer:3
    },
    {question: "I served in this branch of the military:",
    choices: ["Air Force", "Army", "Navy", "Marines"],
    answer:0
    },
    {question: "This is my nervous habit:",
    choices: ["Blinking too much", "Poor eye contact", "Cracking knuckles", "I'm never nervous"],
    answer:2
    },
    {question: "What is my trail name?",
    choices: ["Landlocked", "Ambassador", "Moonbeam", "Young Man Winter"],
    answer:1
    },
    {question: "How many siblings to I have?",
    choices: ["0", "1", "3", "4"],
    answer:3
    },
    {question: "All of these are my hobbies except:",
    choices: ["Stamp collecting", "Playing guitar", "Programming", "Board Games"],
    answer:0
    },
    {question: "What is my favorite movie?",
    choices: ["Titanic", "The Matrix", "The Royal Tenenbaums", "Inception"],
    answer:2
    },
    {question: "What is my favorite work of fiction?",
    choices: ["A Wizard of Earthsea", "Harry Potter (all of them)", "The Lord of the Rings", "The Bible"],
    answer:0
    }
];

answerKey = [];
userAnswer = [];
i = 0;
score = 10;

questions.forEach(function(element){
    answerKey.push(element.answer);
});

console.log(answerKey);

$(document).ready( function() {

    var quiz = $("#quiz");

    $('#quiz-form').on('change', function() {
        selected = ($('input[name=question]:checked').val());
    });

    // @lob Add functionality to reset :checked after each Next button, but keep selected
    // answers in memory to be shown when Prev button is used

    // @lob Add checkbox verification; Next button only advances if an answer is selected;
    // otherwise, alert error

    $('#btn-next').on('click', function() {
        if (i < answerKey.length-1) {
            if (!isNaN(selected)) {
                userAnswer.splice(i, 1, selected);
                i += 1;
                quiz.find('.quiz-question').show().html('
' + '
' + questions[i].question + '
');
                $('#choice1').next().html('' + questions[i].choices[0] + '').addClass('checked');
                $('#choice2').next().html('' + questions[i].choices[1] + '');
                $('#choice3').next().html('' + questions[i].choices[2] + '');
                $('#choice4').next().html('' + questions[i].choices[3] + '');
            } else {
                alert('Please select an answer.');
            }
        } else {
            userAnswer.push(selected);
            quiz.find('.quiz-question').hide();
            quiz.find('.quiz-choices').hide();
            $("#finish").show();
            $("#btn-next").hide();
            $("#btn-prev").hide();
            $("#btn-submit").show();
            }
    });

    $('#btn-prev').on('click', function() {
        if (i > 0) {
            i -= 1;
            quiz.find('.quiz-question').show().html('
' + '
' + questions[i].question + '
');
            $('#choice1').next().html('' + questions[i].choices[0] + '');
            $('#choice2').next().html('' + questions[i].choices[1] + '');
            $('#choice3').next().html('' + questions[i].choices[2] + '');
            $('#choice4').next().html('' + questions[i].choices[3] + '');
        }
    });

    $('#btn-submit').on('click', function() {
        for (k = 0; k < answerKey.length; k++) {
            console.log('Starting score ' + score);
            if (answerKey[k] != userAnswer[k]) {
                score -= 1;
                console.log('You missed one. Current score: ' + score);
            } else {
                console.log(score);
            }
        }
        $('#btn-submit').hide();
        $("#finish").hide();
        $("#grade").show();
        $("#grade-percent").text((score/(answerKey.length))*100 + '%');
        if (score === 10) {
            $("#ten").show();
        } else if (score === 9) {
            $("#nine").show();
        } else if (score === 8) {
            $("#eight").show();
        } else if (score === 7) {
            $("#seven").show();
        } else if (score === 6) {
            $("#six").show();
        } else if (score === 5) {
            $("#five").show();
        } else if (score === 4) {
            $("#four").show();
        } else if (score === 3) {
            $("#three").show();
        } else if (score === 2) {
            $("#two").show();
        } else if (score === 1) {
            $("#one").show();
        } else {
            $("#zero").show();
        }
    });

    quiz.find('.quiz-choices').show();
    quiz.find('.quiz-question').show().html('
' + '
' + questions[i].question + '
');
    $('#choice1').next().html(''+questions[i].choices[0]+'');
    $('#choice2').next().html(''+questions[i].choices[1]+'');
    $('#choice3').next().html(''+questions[i].choices[2]+'');
    $('#choice4').next().html(''+questions[i].choices[3]+'');
});<commit_msg>add getSelected(); remove debug code<commit_after>var $,
    i,
    j,
    k,
    questions,
    answerKey,
    userAnswer,
    selected,
    score;

questions = [
    {question: "What is my middle name?",
    choices: ["Sylvester", "Patrick", "Aaron", "David"],
    answer:1
    },
    {question: "How old am I?",
    choices: ["29", "27", "30", "28"],
    answer:0
    },
    {question: "In what state was I born?",
    choices: ["Idaho", "Tampa", "North Carolina", "California"],
    answer:3
    },
    {question: "I served in this branch of the military:",
    choices: ["Air Force", "Army", "Navy", "Marines"],
    answer:0
    },
    {question: "This is my nervous habit:",
    choices: ["Blinking too much", "Poor eye contact", "Cracking knuckles", "I'm never nervous"],
    answer:2
    },
    {question: "What is my trail name?",
    choices: ["Landlocked", "Ambassador", "Moonbeam", "Young Man Winter"],
    answer:1
    },
    {question: "How many siblings to I have?",
    choices: ["0", "1", "3", "4"],
    answer:3
    },
    {question: "All of these are my hobbies except:",
    choices: ["Stamp collecting", "Playing guitar", "Programming", "Board Games"],
    answer:0
    },
    {question: "What is my favorite movie?",
    choices: ["Titanic", "The Matrix", "The Royal Tenenbaums", "Inception"],
    answer:2
    },
    {question: "What is my favorite work of fiction?",
    choices: ["A Wizard of Earthsea", "Harry Potter (all of them)", "The Lord of the Rings", "The Bible"],
    answer:0
    }
];

answerKey = [];
userAnswer = [];
i = 0;
score = 10;

questions.forEach(function(element){
    answerKey.push(element.answer);
});

$(document).ready( function() {

    var quiz = $("#quiz");

    function getSelected() {
        selected = false;
        $('#quiz-form').on('change', function() {
            selected = ($('input[name=question]:checked').val());
        });
    }
    getSelected();

    // @lob Keep selected answers in memory to be shown when Prev button is used; currently,
    // it resets it to 'checked', false

    // @lob Add checkbox verification; Next button only advances if an answer is selected;
    // otherwise, alert error

    // @lob Add missed questions review after grade is shown

    $('#btn-next').on('click', function() {
        if (i < answerKey.length-1) {
            if (selected) {
                userAnswer.splice(i, 1, selected);
                i += 1;
                quiz.find('.quiz-question').show().html('
' + '
' + questions[i].question + '
');
                $('#choice1').prop('checked', false).next().html('' + questions[i].choices[0] + '');
                $('#choice2').prop('checked', false).next().html('' + questions[i].choices[1] + '');
                $('#choice3').prop('checked', false).next().html('' + questions[i].choices[2] + '');
                $('#choice4').prop('checked', false).next().html('' + questions[i].choices[3] + '');
            } else {
                alert('Please select an answer.');
            }
        } else {
            userAnswer.push(selected);
            quiz.find('.quiz-question').hide();
            quiz.find('.quiz-choices').hide();
            $("#finish").show();
            $("#btn-next").hide();
            $("#btn-prev").hide();
            $("#btn-submit").show();
            }
        getSelected();
    });

    $('#btn-prev').on('click', function() {
        if (i > 0) {
            i -= 1;
            quiz.find('.quiz-question').show().html('
' + '
' + questions[i].question + '
');
            $('#choice1').next().html('' + questions[i].choices[0] + '');
            $('#choice2').next().html('' + questions[i].choices[1] + '');
            $('#choice3').next().html('' + questions[i].choices[2] + '');
            $('#choice4').next().html('' + questions[i].choices[3] + '');
        }
    });

    $('#btn-submit').on('click', function() {
        // @lob Update this loop as an array.forEach
        for (k = 0; k < answerKey.length; k++) {
            if (answerKey[k] != userAnswer[k]) {
                score -= 1;
            }
        }
        $('#btn-submit').hide();
        $("#finish").hide();
        $("#grade").show();
        $("#grade-percent").text((score/(answerKey.length))*100 + '%');
        if (score === 10) {
            $("#ten").show();
        } else if (score === 9) {
            $("#nine").show();
        } else if (score === 8) {
            $("#eight").show();
        } else if (score === 7) {
            $("#seven").show();
        } else if (score === 6) {
            $("#six").show();
        } else if (score === 5) {
            $("#five").show();
        } else if (score === 4) {
            $("#four").show();
        } else if (score === 3) {
            $("#three").show();
        } else if (score === 2) {
            $("#two").show();
        } else if (score === 1) {
            $("#one").show();
        } else {
            $("#zero").show();
        }
    });

    quiz.find('.quiz-choices').show();
    quiz.find('.quiz-question').show().html('
' + '
' + questions[i].question + '
');
    $('#choice1').next().html(''+questions[i].choices[0]+'');
    $('#choice2').next().html(''+questions[i].choices[1]+'');
    $('#choice3').next().html(''+questions[i].choices[2]+'');
    $('#choice4').next().html(''+questions[i].choices[3]+'');
});<|endoftext|>


<commit_before>'use strict';

var AV = AV || {};

AV.main = (function() {
  var blocks = [];
  var matrix = [];
  for (var i = 0; i< AV.consts.totalWidth; i++) {
    matrix.push([]);
  }

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

  var drawGrid = function() {
    var start = 0;
    // vertical
    for (var i = 0; i < AV.consts.cellsX; i++) {
      ctx.beginPath();
      ctx.moveTo(start-0.5, 0);
      ctx.lineTo(start-0.5, AV.consts.totalHeight);
      ctx.stroke();
      start += AV.consts.cellSize;
    }

    start = 0;
    //horizontal
    for (i = 0; i < AV.consts.cellsY; i++) {
      ctx.beginPath();
      ctx.moveTo(0, start-0.5);
      ctx.lineTo(AV.consts.totalWidth, start-0.5);
      ctx.stroke();
      start += AV.consts.cellSize;
    }
  };

  var block;

  var init = function() {
    canvas.width = AV.consts.totalWidth;
    canvas.height = AV.consts.totalHeight;
    createNewBlock();
    tick();
  };

  var clearCanvas = function(){
    ctx.clearRect(0, 0, AV.consts.totalWidth, AV.consts.totalHeight);
    drawGrid();
  };

  var tick = function() {
    clearCanvas();
    block.update();
    block.draw();
    blocks.forEach(function(b){
      b.draw();
    });
    requestAnimationFrame(tick);
  };

  var createNewBlock = function() {
    block = new AV.block(
      ~~(Math.random()*AV.consts.cellsX)*AV.consts.cellSize, 0);
  };

  var calculateMatrixPosition = function(b) {
    var halfSize = ~~(AV.consts.cellSize/2);
    return {
      x: ~~((b.x+halfSize) / AV.consts.cellSize),
      y: ~~((b.y+halfSize) / AV.consts.cellSize)
    }
  };

  var addToMatrix = function(b) {
    var coords = calculateMatrixPosition(b);
    console.log(coords);
    matrix[coords.x][coords.y] = b;
  };

  var addToStack = function(b) {
    blocks.push(b);
  };

  return {
    init: init,
    ctx: ctx,
    createNewBlock: createNewBlock,
    addToStack: addToStack,
    addToMatrix: addToMatrix,
    get blocks() { return blocks; }
  };
})();

AV.main.init();
<commit_msg>[ATLASV] - :crying_cat_face: lint<commit_after>'use strict';

var AV = AV || {};

AV.main = (function() {
  var blocks = [];
  var matrix = [];
  for (var i = 0; i< AV.consts.totalWidth; i++) {
    matrix.push([]);
  }

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

  var drawGrid = function() {
    var start = 0;
    // vertical
    for (var i = 0; i < AV.consts.cellsX; i++) {
      ctx.beginPath();
      ctx.moveTo(start-0.5, 0);
      ctx.lineTo(start-0.5, AV.consts.totalHeight);
      ctx.stroke();
      start += AV.consts.cellSize;
    }

    start = 0;
    //horizontal
    for (i = 0; i < AV.consts.cellsY; i++) {
      ctx.beginPath();
      ctx.moveTo(0, start-0.5);
      ctx.lineTo(AV.consts.totalWidth, start-0.5);
      ctx.stroke();
      start += AV.consts.cellSize;
    }
  };

  var block;

  var init = function() {
    canvas.width = AV.consts.totalWidth;
    canvas.height = AV.consts.totalHeight;
    createNewBlock();
    tick();
  };

  var clearCanvas = function(){
    ctx.clearRect(0, 0, AV.consts.totalWidth, AV.consts.totalHeight);
    drawGrid();
  };

  var tick = function() {
    clearCanvas();
    block.update();
    block.draw();
    blocks.forEach(function(b){
      b.draw();
    });
    requestAnimationFrame(tick);
  };

  var createNewBlock = function() {
    block = new AV.block(
      ~~(Math.random()*AV.consts.cellsX)*AV.consts.cellSize, 0);
  };

  var calculateMatrixPosition = function(b) {
    var halfSize = ~~(AV.consts.cellSize/2);
    return {
      x: ~~((b.x+halfSize) / AV.consts.cellSize),
      y: ~~((b.y+halfSize) / AV.consts.cellSize)
    };
  };

  var addToMatrix = function(b) {
    var coords = calculateMatrixPosition(b);
    console.log(coords);
    matrix[coords.x][coords.y] = b;
  };

  var addToStack = function(b) {
    blocks.push(b);
  };

  return {
    init: init,
    ctx: ctx,
    createNewBlock: createNewBlock,
    addToStack: addToStack,
    addToMatrix: addToMatrix,
    get blocks() { return blocks; }
  };
})();

AV.main.init();
<|endoftext|>


<commit_before>'use strict';

var L = require('leaflet');
var geo = require('./geolocation.js');
var itinerary = require('./itCalculation.js');
var getToilets = require('./getJSON.js');
var addInfos = require('./addInfos.js');
var U = require('./utilities.js');

// set map options
var BORDEAUX_COORDS = [44.84, -0.57];
var map = L.map('map', {
    center: BORDEAUX_COORDS,
    zoom: 12,
    minZoom: 12 // minZoom is set b/c there is no sense to zoom out of Bordeaux
});

map.setMaxBounds(map.getBounds()); // MaxBounds are set because there is no sense to pan out of Bordeaux

L.tileLayer('http://api.tiles.mapbox.com/v3/ourson.k0i572pc/{z}/{x}/{y}.png', {
    attribution: '© OpenStreetMap contributors'
}).addTo(map);

var typologieToCSSClass = {
    "Urinoir": "urinoir",
    "Sanitaire automatique": "sanitaire",
    "Sanitaire automatique avec urinoir": "sanitaire",
    "Chalet de nécessité": "sanitaire"
};

var filterMap = {
    "urinoir-filter": "urinoir",
    "sanitaire-filter": "sanitaire",
    "handi-filter": "handicap",
};

var drawables = {
    user: undefined,
    singleGroup: L.layerGroup(),
    closestGroup: L.layerGroup(),
    urinoirGroup: L.layerGroup(),
    sanitaireGroup: L.layerGroup(),
    handiGroup: L.layerGroup(),
    toiletGroup: L.layerGroup()
};

// Get user position
function updatePosition(position){
    var latitude  = position.coords.latitude;
    var longitude = position.coords.longitude;

    var icon = L.divIcon({
            className: "user",
            iconSize: new L.Point(72, 72),
            iconAnchor: new L.Point(36, 36),
            html: ''
        });

    var marker;

    if(marker)
        map.removeLayer(marker);

    marker = L.marker([latitude, longitude], {icon: icon});
    drawables.user = marker;

    // Add click event on user position
    marker.addEventListener('click', function(){
        drawables.singleGroup.clearLayers();
        updateClosest(drawables.closestGroup);
    });

    updateClosest(marker);

    return {
        lat: latitude,
        lng: longitude
    };
}

function displayModes(){

    map.removeLayer(drawables.toiletGroup);
    map.removeLayer(drawables.handiGroup);
    map.removeLayer(drawables.urinoirGroup);
    map.removeLayer(drawables.sanitaireGroup);

    modes.forEach(function(mode){
        switch (mode) {
            case 'urinoir':
                console.log('mode ', mode);
                drawables.urinoirGroup.addTo(map);
                break;
            case 'sanitaire':
                console.log('mode ', mode);
                drawables.sanitaireGroup.addTo(map);
                break;
            case 'handicap':
                console.log('mode ', mode);
                drawables.handiGroup.addTo(map);
                break;
            default:
                drawables.toiletGroup.addTo(map);
                break;
        }
    });
}

function setMarker(toilet){
    // Add icons from FontAwesome
    var myHtml = '';
    var groups = [drawables.toiletGroup];

    if (toilet.class === 'sanitaire') {
        myHtml += '\n';
        groups.push(drawables.sanitaireGroup);
    }
    else {
        myHtml += '\n';
        groups.push(drawables.urinoirGroup);
    }

    if (toilet.handicap === true){
        myHtml += '

\n';
        groups.push(drawables.handiGroup);
    }

    var icon = L.divIcon({
        className: "icon",
        iconSize: new L.Point(46, 46),
        iconAnchor: new L.Point(23, 23),
        html: myHtml
    });

    toilet.marker = L.marker([toilet.lat, toilet.lng], {icon: icon});
    return groups;
}

function addClicBehaviour(list, position){
    list.forEach(function(toilette){

        // Add click event on toilet
        toilette.marker.addEventListener('click', function(){
            map.removeLayer(drawables.closestGroup);
            drawables.singleGroup.clearLayers();

            itinerary(position, toilette)
                .then(function(result){
                    var infos = addInfos(result, 1);

                    infos.polyline.addTo(drawables.singleGroup);
                    infos.marker.addTo(drawables.singleGroup);

                    updateClosest(drawables.singleGroup);

                }).catch(function(err){console.error(err);});
        });
    });
}

function calculateBounds(lats, lngs){
    // Fits the map so all shortest routes are displayed
    var north = U.getMaxOfArray(lats),
        south = U.getMinOfArray(lats),
        east = U.getMaxOfArray(lngs),
        west = U.getMinOfArray(lngs);

    console.log("north ", north);
    var southWest = L.latLng(south, west),
        northEast = L.latLng(north, east);

    return L.latLngBounds(southWest, northEast);
}

function updateClosest(item, boundaries){
    if (boundaries){
        map.fitBounds(boundaries, {
            paddingTopLeft: [0, 110],
            paddingBottomRight: [0, 50]
        });
    }

    map.removeLayer(drawables.closestGroup);
    map.removeLayer(drawables.singleGroup);

    item.addTo(map);
}

function filterToilets(list, types){
    var filtered = [];

    list.forEach(function(toilette){
        if (types.indexOf(toilette.class) !== -1){
            filtered.push(toilette);
        }
        if ((types.indexOf('handicap') !== -1) && toilette.handicap){
            if (filtered.indexOf(toilette) === -1){ // check if toilette isn't already added
                filtered.push(toilette);
            }
        }
    });

    return filtered;
}

function deactivateMode(dom){
    dom.className = 'filter inactive';

    var index = modes.indexOf(filterMap[dom.id]);
    if (index > -1){
        modes.splice(index, 1);
        displayModes();

        if (modes.length === 0){
            activateAllModes(modes);
        }
    }
}

function activateMode(dom){
    dom.className = 'filter active';
    var id = dom.id;
    modes.push(filterMap[id]);
    displayModes();
}

function activateAllModes(){
    modes = ['urinoir', 'sanitaire', 'handicap'];
    filterButtons[0].className = 'filter active';
    filterButtons[1].className = 'filter active';
    filterButtons[2].className = 'filter active';
    displayModes();
}

function deactivateAllModes(){
    modes = [];
    filterButtons[0].className = 'filter inactive';
    filterButtons[1].className = 'filter inactive';
    filterButtons[2].className = 'filter inactive';
}

function addClicFilter(toilettes, position){
    // // for each doesn't seem to work with an array of DOM elements...
    // filterButtons.forEach(function(){
    //  console.log('test');
    // });

    // For 'urinoir'
    filterButtons[0].addEventListener('click', function(){
        if (modes.length === 3){ // if all is selected (default), click selects rather than deselects
            deactivateAllModes();
            activateMode(this);
        }
        else {
            if (this.className === 'filter active'){
                deactivateMode(this);
            }
            else {
                activateMode(this);
            }
        }

        var selection = filterToilets(toilettes, modes);
        findClosest(selection, position);
    });

    // For 'sanitaire'
    filterButtons[1].addEventListener('click', function(){
        if (modes.length === 3){ // if all is selected (default), click selects rather than deselects
            deactivateAllModes();
            activateMode(this);
        }
        else {
            if (this.className === 'filter active'){
                deactivateMode(this);
            }
            else {
                activateMode(this);
            }
        }

        var selection = filterToilets(toilettes, modes);
        findClosest(selection, position);
    });

    // For 'handi'
    filterButtons[2].addEventListener('click', function(){
        if (modes.length === 3){ // if all is selected (default), click selects rather than deselects
            deactivateAllModes();
            activateMode(this);
        }
        else {
            if (this.className === 'filter active'){
                deactivateMode(this);
            }
            else {
                activateMode(this);
            }
        }

        var selection = filterToilets(toilettes, modes);
        findClosest(selection, position);
    });
}

function findClosest(list, position){

    drawables.singleGroup.clearLayers();
    drawables.closestGroup.clearLayers();

    list.forEach(function(toilette){
        // Calculate rough distance b/w user and toilet
        toilette.d = Math.hypot(toilette.lat - position.lat, toilette.lng - position.lng);
    });

    list.sort(function (a, b) {
        return (a.d - b.d);
    });

    var closestToilettes = list.slice(0, 3);

    var closestLats = closestToilettes.map(function(t){return t.lat;}),
        closestLngs = closestToilettes.map(function(t){return t.lng;});

    closestLats.push(position.lat);
    closestLngs.push(position.lng);

    // console.log('list ', list);
    // console.log('position ', position);

    var itinerariesPs = closestToilettes.map(function(t){ return itinerary(position, t); });

    var bounds = calculateBounds(closestLats, closestLngs);

    // When all itineraries are computed
    Promise.all(itinerariesPs).then(function(toilets){

        toilets.sort(function (a, b) {
            return -(a.routes[0].legs[0].distance.value - b.routes[0].legs[0].distance.value);
        });

        // Calculate itineraries for 3 closest toilets
        toilets.forEach(function(toilet, i){

            var infos = addInfos(toilet, i);
            infos.polyline.addTo(drawables.closestGroup);
            infos.marker.addTo(drawables.closestGroup);

        });

        // Draw infos on closest toilets
        updateClosest(drawables.closestGroup, bounds);

    }).catch(function(err){console.error(err);});
}

/// MAIN CODE

// Get toilets position
var toilettesP = getToilets('data/toilettes.json')
    .then(function(data){
        console.log('raw', data);

        return data["d"].map(function(t){
            var test = typologieToCSSClass[t["typologie"]];
            var option = t["options"] ? true: false;
            if (!test)
                console.error(t);
            else {
                return {
                    lng: parseFloat(t["x_long"]),
                    lat: parseFloat(t["y_lat"]),
                    nom: t["nom"],
                    // typologie: t["typologie"],
                    class: typologieToCSSClass[t["typologie"]],
                    handicap: option,
                    marker: undefined
                };
            }
        });
    });

var modes = ['urinoir', 'sanitaire', 'handicap'];

// render points on map regardless of geolocation
toilettesP
    .then(function(toilettes){
        toilettes.forEach(function(element){
            var groups = setMarker(element);

            groups.forEach(function(group){
                element.marker.addTo(group);
            });

        });

        displayModes();
    });

// var closestUrinoirs = undefined;
// var closestSanitaires = undefined;
// var closestHandis = undefined;

var position = geo(updatePosition);
var filterButtons = document.getElementsByClassName('filter');

// When user and toilet positions are available:
Promise.all([toilettesP, position])
    .then(function(values){
        var toilettes = values[0],
            position = values[1];

        addClicFilter(toilettes, position);

        addClicBehaviour(toilettes, position);

        findClosest(toilettes, position);
    })
    .catch(function(err){console.error(err);});

//////////////////////////

<commit_msg>some refactoring<commit_after>'use strict';

var L = require('leaflet');
var geo = require('./geolocation.js');
var itinerary = require('./itCalculation.js');
var getToilets = require('./getJSON.js');
var addInfos = require('./addInfos.js');
var U = require('./utilities.js');

// set map options
var BORDEAUX_COORDS = [44.84, -0.57];
var map = L.map('map', {
    center: BORDEAUX_COORDS,
    zoom: 12,
    minZoom: 12 // minZoom is set b/c there is no sense to zoom out of Bordeaux
});

map.setMaxBounds(map.getBounds()); // MaxBounds are set because there is no sense to pan out of Bordeaux

L.tileLayer('http://api.tiles.mapbox.com/v3/ourson.k0i572pc/{z}/{x}/{y}.png', {
    attribution: '© OpenStreetMap contributors'
}).addTo(map);

var typologieToCSSClass = {
    "Urinoir": "urinoir",
    "Sanitaire automatique": "sanitaire",
    "Sanitaire automatique avec urinoir": "sanitaire",
    "Chalet de nécessité": "sanitaire"
};

var filterMap = {
    "urinoir-filter": "urinoir",
    "sanitaire-filter": "sanitaire",
    "handi-filter": "handicap",
};

var drawables = {
    user: undefined,
    singleGroup: L.layerGroup(),
    closestGroup: L.layerGroup(),
    urinoirGroup: L.layerGroup(),
    sanitaireGroup: L.layerGroup(),
    handiGroup: L.layerGroup(),
    toiletGroup: L.layerGroup()
};

// Get user position
function updatePosition(position){
    var latitude  = position.coords.latitude;
    var longitude = position.coords.longitude;

    var icon = L.divIcon({
            className: "user",
            iconSize: new L.Point(72, 72),
            iconAnchor: new L.Point(36, 36),
            html: ''
        });

    var marker;

    if(marker)
        map.removeLayer(marker);

    marker = L.marker([latitude, longitude], {icon: icon});
    drawables.user = marker;

    // Add click event on user position
    marker.addEventListener('click', function(){
        drawables.singleGroup.clearLayers();
        updateClosest(drawables.closestGroup);
    });

    updateClosest(marker);

    return {
        lat: latitude,
        lng: longitude
    };
}

function displayModes(){

    map.removeLayer(drawables.toiletGroup);
    map.removeLayer(drawables.handiGroup);
    map.removeLayer(drawables.urinoirGroup);
    map.removeLayer(drawables.sanitaireGroup);

    modes.forEach(function(mode){
        switch (mode) {
            case 'urinoir':
                console.log('mode ', mode);
                drawables.urinoirGroup.addTo(map);
                break;
            case 'sanitaire':
                console.log('mode ', mode);
                drawables.sanitaireGroup.addTo(map);
                break;
            case 'handicap':
                console.log('mode ', mode);
                drawables.handiGroup.addTo(map);
                break;
            default:
                drawables.toiletGroup.addTo(map);
                break;
        }
    });
}

function setMarker(toilet){
    // Add icons from FontAwesome
    var myHtml = '';
    var groups = [drawables.toiletGroup];

    if (toilet.class === 'sanitaire') {
        myHtml += '\n';
        groups.push(drawables.sanitaireGroup);
    }
    else {
        myHtml += '\n';
        groups.push(drawables.urinoirGroup);
    }

    if (toilet.handicap === true){
        myHtml += '

\n';
        groups.push(drawables.handiGroup);
    }

    var icon = L.divIcon({
        className: "icon",
        iconSize: new L.Point(46, 46),
        iconAnchor: new L.Point(23, 23),
        html: myHtml
    });

    toilet.marker = L.marker([toilet.lat, toilet.lng], {icon: icon});
    return groups;
}

function addClicBehaviour(list, position){
    list.forEach(function(toilette){

        // Add click event on toilet
        toilette.marker.addEventListener('click', function(){
            map.removeLayer(drawables.closestGroup);
            drawables.singleGroup.clearLayers();

            itinerary(position, toilette)
                .then(function(result){
                    var infos = addInfos(result, 1);

                    infos.polyline.addTo(drawables.singleGroup);
                    infos.marker.addTo(drawables.singleGroup);

                    updateClosest(drawables.singleGroup);

                }).catch(function(err){console.error(err);});
        });
    });
}

function calculateBounds(lats, lngs){
    // Fits the map so all shortest routes are displayed
    var north = U.getMaxOfArray(lats),
        south = U.getMinOfArray(lats),
        east = U.getMaxOfArray(lngs),
        west = U.getMinOfArray(lngs);

    console.log("north ", north);
    var southWest = L.latLng(south, west),
        northEast = L.latLng(north, east);

    return L.latLngBounds(southWest, northEast);
}

function updateClosest(item, boundaries){
    if (boundaries){
        map.fitBounds(boundaries, {
            paddingTopLeft: [0, 110],
            paddingBottomRight: [0, 50]
        });
    }

    map.removeLayer(drawables.closestGroup);
    map.removeLayer(drawables.singleGroup);

    item.addTo(map);
}

function filterToilets(list, types){
    var filtered = [];

    list.forEach(function(toilette){
        if (types.indexOf(toilette.class) !== -1){
            filtered.push(toilette);
        }
        if ((types.indexOf('handicap') !== -1) && toilette.handicap){
            if (filtered.indexOf(toilette) === -1){ // check if toilette isn't already added
                filtered.push(toilette);
            }
        }
    });

    return filtered;
}

function deactivateMode(dom, modes){
    dom.className = 'filter inactive';

    var index = modes.indexOf(filterMap[dom.id]);
    if (index > -1){
        modes.splice(index, 1);
        displayModes();

        if (modes.length === 0){
            activateAllModes(modes);
        }
    }
}

function activateMode(dom, modes){
    dom.className = 'filter active';
    var id = dom.id;
    modes.push(filterMap[id]);
    displayModes();

    return modes;
}

function activateAllModes(modes){
    modes = ['urinoir', 'sanitaire', 'handicap'];
    filterButtons[0].className = 'filter active';
    filterButtons[1].className = 'filter active';
    filterButtons[2].className = 'filter active';
    displayModes();

    return modes;
}

function deactivateAllModes(modes){
    modes = [];
    filterButtons[0].className = 'filter inactive';
    filterButtons[1].className = 'filter inactive';
    filterButtons[2].className = 'filter inactive';

    return modes;
}

function addClicFilter(toilettes, position){
    // // for each doesn't seem to work with an array of DOM elements...
    // filterButtons.forEach(function(){
    //  console.log('test');
    // });

    // For 'urinoir'
    filterButtons[0].addEventListener('click', function(){
        if (modes.length === 3){ // if all is selected (default), click selects rather than deselects
            deactivateAllModes();
            activateMode(this);
        }
        else {
            if (this.className === 'filter active'){
                deactivateMode(this);
            }
            else {
                activateMode(this);
            }
        }

        var selection = filterToilets(toilettes, modes);
        findClosest(selection, position);
    });

    // For 'sanitaire'
    filterButtons[1].addEventListener('click', function(){
        if (modes.length === 3){ // if all is selected (default), click selects rather than deselects
            deactivateAllModes();
            activateMode(this);
        }
        else {
            if (this.className === 'filter active'){
                deactivateMode(this);
            }
            else {
                activateMode(this);
            }
        }

        var selection = filterToilets(toilettes, modes);
        findClosest(selection, position);
    });

    // For 'handi'
    filterButtons[2].addEventListener('click', function(){
        if (modes.length === 3){ // if all is selected (default), click selects rather than deselects
            deactivateAllModes();
            activateMode(this);
        }
        else {
            if (this.className === 'filter active'){
                deactivateMode(this);
            }
            else {
                activateMode(this);
            }
        }

        var selection = filterToilets(toilettes, modes);
        findClosest(selection, position);
    });
}

function findClosest(list, position){

    drawables.singleGroup.clearLayers();
    drawables.closestGroup.clearLayers();

    list.forEach(function(toilette){
        // Calculate rough distance b/w user and toilet
        toilette.d = Math.hypot(toilette.lat - position.lat, toilette.lng - position.lng);
    });

    list.sort(function (a, b) {
        return (a.d - b.d);
    });

    var closestToilettes = list.slice(0, 3);

    var closestLats = closestToilettes.map(function(t){return t.lat;}),
        closestLngs = closestToilettes.map(function(t){return t.lng;});

    closestLats.push(position.lat);
    closestLngs.push(position.lng);

    // console.log('list ', list);
    // console.log('position ', position);

    var itinerariesPs = closestToilettes.map(function(t){ return itinerary(position, t); });

    var bounds = calculateBounds(closestLats, closestLngs);

    // When all itineraries are computed
    Promise.all(itinerariesPs).then(function(toilets){

        toilets.sort(function (a, b) {
            return -(a.routes[0].legs[0].distance.value - b.routes[0].legs[0].distance.value);
        });

        // Calculate itineraries for 3 closest toilets
        toilets.forEach(function(toilet, i){

            var infos = addInfos(toilet, i);
            infos.polyline.addTo(drawables.closestGroup);
            infos.marker.addTo(drawables.closestGroup);

        });

        // Draw infos on closest toilets
        updateClosest(drawables.closestGroup, bounds);

    }).catch(function(err){console.error(err);});
}

/// MAIN CODE

// Get toilets position
var toilettesP = getToilets('data/toilettes.json')
    .then(function(data){
        console.log('raw', data);

        return data["d"].map(function(t){
            var test = typologieToCSSClass[t["typologie"]];
            var option = t["options"] ? true: false;
            if (!test)
                console.error(t);
            else {
                return {
                    lng: parseFloat(t["x_long"]),
                    lat: parseFloat(t["y_lat"]),
                    nom: t["nom"],
                    // typologie: t["typologie"],
                    class: typologieToCSSClass[t["typologie"]],
                    handicap: option,
                    marker: undefined
                };
            }
        });
    });

var modes = ['urinoir', 'sanitaire', 'handicap'];

// render points on map regardless of geolocation
toilettesP
    .then(function(toilettes){
        toilettes.forEach(function(element){
            var groups = setMarker(element);

            groups.forEach(function(group){
                element.marker.addTo(group);
            });

        });

        displayModes();
    });

// var closestUrinoirs = undefined;
// var closestSanitaires = undefined;
// var closestHandis = undefined;

var position = geo(updatePosition);
var filterButtons = document.getElementsByClassName('filter');

// When user and toilet positions are available:
Promise.all([toilettesP, position])
    .then(function(values){
        var toilettes = values[0],
            position = values[1];

        addClicFilter(toilettes, position);

        addClicBehaviour(toilettes, position);

        findClosest(toilettes, position);
    })
    .catch(function(err){console.error(err);});

//////////////////////////

<|endoftext|>


<commit_before>function parseDateRange(string) {
	var vals = string.split(' - ');
	return moment(vals[0], 'MM DD YYYY').twix(vals[1], 'MM DD YYYY');
}

function getDateRanges() {
	return $('.date-range').map(function (i, inputEl) {
		return parseDateRange($(inputEl).val());
	}).get();
}

$( document ).ready( function(){

		var cppMaxEarning = 54900;
		var cppExemptAmount = 3500;
		var eiMaxEarning = 50800;
		var cppPerc =  0.0495;
		var eiPerc = 0.0192;

		var year = 2016;
		var jan1 = new Date(year, 00, 01);
		var day  = moment(new Date (date('16 weeks',jan1))).format("MMMM Do") ;

		var payPeriods = [4, 2, 2, 1];

		$("#submitButton").click(function(e){
			e.preventDefault();

			if (!validateDateRanges()){
				return;
			}

			var ytd =  parseInt($("#ytdInput").val().replace(/[^0-9.]/g, ''));

			var compensation = parseInt($("#compensationInput").val().replace(/,/g, ''));

			//console.log(compensation);
			if(isNaN(compensation)){
				var dayOfYear = moment().dayOfYear();

				compensation = 365/dayOfYear * ytd;

			}
			compensation = isNaN(compensation) ? 0 : compensation;

			var numPays = parseInt($("#numPaysSelect").val());

			var amountPerPay= compensation / numPays;
			var resultCPP =   (cppMaxEarning-cppExemptAmount) / amountPerPay;
			var resultEI =  eiMaxEarning / amountPerPay;

			var weeksOfPayCPP = Math.round(resultCPP*payPeriods[$("#numPaysSelect")[0].selectedIndex]);
			var weeksOfPayEI = Math.round(resultEI*payPeriods[$("#numPaysSelect")[0].selectedIndex]);

			var ranges = getDateRanges();

			function payoffDateReducer (acc, range, i, arr) {
				if (acc.payoffDate) {
					return acc;
				} else if (acc.weeksRemaining <= range.length('weeks')) {
					return {
						weeksRemaining: 0,
						payoffDate: range.start().add(acc.weeksRemaining, 'weeks')
					};
				} else {
					return {
						weeksRemaining: acc.weeksRemaining - range.length('weeks'),
						payoffDate: undefined
					};
				}
			}

			var dayCpp = ranges
				.reduce(payoffDateReducer, {weeksRemaining: weeksOfPayCPP, payoffDate: undefined})
				.payoffDate;

			var dayEI = ranges
				.reduce(payoffDateReducer, {weeksRemaining: weeksOfPayEI, payoffDate: undefined})
				.payoffDate;

			$("#results").removeClass("alert alert-danger");

			if(compensation< eiMaxEarning){

					$("#results").html("I'm sorry, it looks like this calculator doesn't think you'll max out your CPP or EI. You need to make at least $" +  eiMaxEarning + " in a year.");

					$("#results").addClass("alert alert-danger");
			} else {

				var response = "Your CPP contribution is $" + Math.round(amountPerPay*cppPerc) + " per pay and your EI contribution is $" + Math.round(amountPerPay*eiPerc) + ". " +

				"

You should max out your CPP Contributions on your " + nth(Math.ceil(resultCPP))+ " pay. "+
				"
You should max out your EI Contributions on your " + nth(Math.ceil(resultEI))+ " pay. ";

				if (dayCpp && dayEI) {
					response += "

Very very roughly this means " +dayCpp.format("MMMM Do") + " for CPP and " + dayEI.format("MMMM Do")+ " for EI."
				} else {
					response += "

";
					if (!dayCpp && !dayEI) {
						response += "It looks like you might not have enough pay periods to max out CPP nor EI contributions.";
					} else if (!dayCpp) {
						response += "It looks like you might not have enough pay periods to max out CPP contributions. Very very roughly your EI will max out on " + dayEI.format("MMMM Do");
					} else if (!dayEI) {
						response += "It looks like you might not have enough pay periods to max out EI contributions. Very very roughly your EI will max out on " + dayCpp.format("MMMM Do");
					}
				}

				$("#results").html(response);
		}

			$("#results").css("visibility","visible");

			ga('send','event', 'submitClick',numPays,"Number of pays per year");

		});

		var seasonGroupTemplate = $('#seasonGroupTemplate').html();

		var dateRangePickerOptions = {
			autoApply: true,
			startDate: moment('01-01-' + year, 'MM DD YYYY'),
			endDate: moment('12-31-' + year, 'MM DD YYYY'),
		};

		function getInvalidateDateRanges () {
			return getDateRanges().filter(function (range, i, array) {
				return array.reduce(function (isOverlapping, otherRange, j) {
					if (i === j) {
						return false;
					}
					return range.overlaps(otherRange);
				}, false);
			});
		};

		function warnInvalidDateRanges () {
			$("#results").addClass("alert alert-danger");
			$("#results").html("Your work periods are overlapping");
			$("#results").css("visibility","visible");
		}

		function validateDateRanges () {
			var isValid = !getInvalidateDateRanges().length;
			if (!isValid) {
				warnInvalidDateRanges();
			}
			return isValid;
		}

		function initDateRange ($input) {
			$input.daterangepicker(dateRangePickerOptions);
			$input.on('change', function (e) {
				validateDateRanges();
			})
		}

		initDateRange($('.date-range'));

		$('.add-season-btn').click(function () {
			if (!validateDateRanges()) {
				return;
			}
			var seasonFragment = $(seasonGroupTemplate);
			initDateRange(seasonFragment.find('.date-range'))
			$('.seasonal-options').append(seasonFragment);
			return false;
		});

		$('.seasonal-options').on('click', '.remove-season-btn', function (e) {
			$(e.target).closest('.seasons-group').remove();
		});

		function nth(d) {

			var suffix;

		  if(d>3 && d<21) suffix= 'th'; // thanks kennebec

		  switch (d % 10) {
		        case 1:  suffix= "st"
		        break;
		        case 2:  suffix = "nd"
		         break;
		        case 3:  suffix= "rd"
		         break;
		        default: suffix= "th"
		         break;
		    }
		  if(d>10 && d<14){
		  	suffix = suffix= "th";
		  }

		    return d+suffix;
		}

} )<commit_msg>fix problems with having $ in textfiel<commit_after>function parseDateRange(string) {
	var vals = string.split(' - ');
	return moment(vals[0], 'MM DD YYYY').twix(vals[1], 'MM DD YYYY');
}

function getDateRanges() {
	return $('.date-range').map(function (i, inputEl) {
		return parseDateRange($(inputEl).val());
	}).get();
}

$( document ).ready( function(){

		var cppMaxEarning = 54900;
		var cppExemptAmount = 3500;
		var eiMaxEarning = 50800;
		var cppPerc =  0.0495;
		var eiPerc = 0.0192;

		var year = 2016;
		var jan1 = new Date(year, 00, 01);
		var day  = moment(new Date (date('16 weeks',jan1))).format("MMMM Do") ;

		var payPeriods = [4, 2, 2, 1];

		$("#submitButton").click(function(e){
			e.preventDefault();

			if (!validateDateRanges()){
				return;
			}

			var ytd =  parseInt($("#ytdInput").val().replace(/[^0-9.]/g, ''));

			var compensation = parseInt($("#compensationInput").val().replace(/[^0-9.]/g, ''));

			//console.log(compensation);
			if(isNaN(compensation)){
				var dayOfYear = moment().dayOfYear();

				compensation = 365/dayOfYear * ytd;

			}
			compensation = isNaN(compensation) ? 0 : compensation;

			var numPays = parseInt($("#numPaysSelect").val());

			var amountPerPay= compensation / numPays;
			var resultCPP =   (cppMaxEarning-cppExemptAmount) / amountPerPay;
			var resultEI =  eiMaxEarning / amountPerPay;

			var weeksOfPayCPP = Math.round(resultCPP*payPeriods[$("#numPaysSelect")[0].selectedIndex]);
			var weeksOfPayEI = Math.round(resultEI*payPeriods[$("#numPaysSelect")[0].selectedIndex]);

			var ranges = getDateRanges();

			function payoffDateReducer (acc, range, i, arr) {
				if (acc.payoffDate) {
					return acc;
				} else if (acc.weeksRemaining <= range.length('weeks')) {
					return {
						weeksRemaining: 0,
						payoffDate: range.start().add(acc.weeksRemaining, 'weeks')
					};
				} else {
					return {
						weeksRemaining: acc.weeksRemaining - range.length('weeks'),
						payoffDate: undefined
					};
				}
			}

			var dayCpp = ranges
				.reduce(payoffDateReducer, {weeksRemaining: weeksOfPayCPP, payoffDate: undefined})
				.payoffDate;

			var dayEI = ranges
				.reduce(payoffDateReducer, {weeksRemaining: weeksOfPayEI, payoffDate: undefined})
				.payoffDate;

			$("#results").removeClass("alert alert-danger");

			if(compensation< eiMaxEarning){

					$("#results").html("I'm sorry, it looks like this calculator doesn't think you'll max out your CPP or EI. You need to make at least $" +  eiMaxEarning + " in a year.");

					$("#results").addClass("alert alert-danger");
			} else {

				var response = "Your CPP contribution is $" + Math.round(amountPerPay*cppPerc) + " per pay and your EI contribution is $" + Math.round(amountPerPay*eiPerc) + ". " +

				"

You should max out your CPP Contributions on your " + nth(Math.ceil(resultCPP))+ " pay. "+
				"
You should max out your EI Contributions on your " + nth(Math.ceil(resultEI))+ " pay. ";

				if (dayCpp && dayEI) {
					response += "

Very very roughly this means " +dayCpp.format("MMMM Do") + " for CPP and " + dayEI.format("MMMM Do")+ " for EI."
				} else {
					response += "

";
					if (!dayCpp && !dayEI) {
						response += "It looks like you might not have enough pay periods to max out CPP nor EI contributions.";
					} else if (!dayCpp) {
						response += "It looks like you might not have enough pay periods to max out CPP contributions. Very very roughly your EI will max out on " + dayEI.format("MMMM Do");
					} else if (!dayEI) {
						response += "It looks like you might not have enough pay periods to max out EI contributions. Very very roughly your EI will max out on " + dayCpp.format("MMMM Do");
					}
				}

				$("#results").html(response);
		}

			$("#results").css("visibility","visible");

			ga('send','event', 'submitClick',numPays,"Number of pays per year");

		});

		var seasonGroupTemplate = $('#seasonGroupTemplate').html();

		var dateRangePickerOptions = {
			autoApply: true,
			startDate: moment('01-01-' + year, 'MM DD YYYY'),
			endDate: moment('12-31-' + year, 'MM DD YYYY'),
		};

		function getInvalidateDateRanges () {
			return getDateRanges().filter(function (range, i, array) {
				return array.reduce(function (isOverlapping, otherRange, j) {
					if (i === j) {
						return false;
					}
					return range.overlaps(otherRange);
				}, false);
			});
		};

		function warnInvalidDateRanges () {
			$("#results").addClass("alert alert-danger");
			$("#results").html("Your work periods are overlapping");
			$("#results").css("visibility","visible");
		}

		function validateDateRanges () {
			var isValid = !getInvalidateDateRanges().length;
			if (!isValid) {
				warnInvalidDateRanges();
			}
			return isValid;
		}

		function initDateRange ($input) {
			$input.daterangepicker(dateRangePickerOptions);
			$input.on('change', function (e) {
				validateDateRanges();
			})
		}

		initDateRange($('.date-range'));

		$('.add-season-btn').click(function () {
			if (!validateDateRanges()) {
				return;
			}
			var seasonFragment = $(seasonGroupTemplate);
			initDateRange(seasonFragment.find('.date-range'))
			$('.seasonal-options').append(seasonFragment);
			return false;
		});

		$('.seasonal-options').on('click', '.remove-season-btn', function (e) {
			$(e.target).closest('.seasons-group').remove();
		});

		function nth(d) {

			var suffix;

		  if(d>3 && d<21) suffix= 'th'; // thanks kennebec

		  switch (d % 10) {
		        case 1:  suffix= "st"
		        break;
		        case 2:  suffix = "nd"
		         break;
		        case 3:  suffix= "rd"
		         break;
		        default: suffix= "th"
		         break;
		    }
		  if(d>10 && d<14){
		  	suffix = suffix= "th";
		  }

		    return d+suffix;
		}

} )
<|endoftext|>


<commit_before>// Stores the width of each bar in pixels
var barWidth = 15;
// Stores the spacing between each line bar in pixels
var barSpacing = 10;

// Quotes about wastage of time
var timeQuotes = [
    "when you kill time, remember that it has no resurrection",
    "the trouble is, you think you have time",
    "time is what we want most, but what we use worst",
    "wasting your time is the subtlest form of suicide",
    "procrastination is the foundation of all disasters",
    "the bad news is time flies. the good news is you're the pilot",
    "you can manage your life by only your time",
    "it is not the time for you to dream, it is the time for you to accomplish the mission",
    "time is much more valuable than money",
    "if time were to take on human form, would she be your taskmaster or freedom fighter?"
];

$(document).ready(function(){

    var backgroundPage = chrome.extension.getBackgroundPage();
    while(backgroundPage === null){
      backgroundPage = chrome.extension.getBackgroundPage();
    }

    chrome.storage.local.get("sitesLocked", function(result){
        if(backgroundPage !== null && backgroundPage.isFirstRun) {
            $('.settingsPanel').addClass('is-visible');
            $('.tracksiteInput').addClass('inputEnabled');
            $('.lockBtn').remove();
            $('.buttonsContainer').append("");
            $('.done').css({"float" : "none" , "margin" : "0 auto"})
        }else if(result.sitesLocked){
            //remove all the buttons
            $('.done').remove();
            $('.editBtn').remove();
            $('.lockBtn').remove();
            $('.tracksiteInput').removeClass("inputEnabled");
            $('.tracksiteInput').addClass("inputDisabled");
            $('.tracksiteInput').prop("disabled", true);
        } else {
            $('.done').remove();
            $('.tracksiteInput').css({"border": "none"});
            $('.tracksiteInput').prop("disabled", true);
            $('.tracksiteInput').removeClass('inputEnabled');
            $('.tracksiteInput').addClass('inputDisabled');
            $('.buttonsContainer').append("");
        }

    });

    // Try to update the data from the localStorage if we can about the sites that are being tracked
    if(chrome.extension.getBackgroundPage().isFirstRun){
        chrome.storage.local.get("trackData", function(result){
               var sitesBeingTracked = JSON.parse(result.trackData);
               document.getElementById("firstSite").value = sitesBeingTracked[0];
               document.getElementById("secondSite").value = sitesBeingTracked[1];
               document.getElementById("thirdSite").value = sitesBeingTracked[2];
               document.getElementById("fourthSite").value = (sitesBeingTracked[3] === undefined) ? "" : sitesBeingTracked[3];
               document.getElementById("fifthSite").value = (sitesBeingTracked[4] === undefined) ? "" : sitesBeingTracked[4];
        });
    } else {
        chrome.storage.local.get("trackData", function(result){
            var sitesBeingTracked = JSON.parse(result.trackData);
            var inputFieldIds = ["firstSite", "secondSite", "thirdSite", "fourthSite", "fifthSite"];
            var inputIdPos = 0;
            for(var i = 0 ; i < 5 ;i++){
                if(sitesBeingTracked[i] != "") {
                    document.getElementById(inputFieldIds[inputIdPos]).value = sitesBeingTracked[i];
                    inputIdPos++;
                }
            }
        });
    }

    displayFacebookAndTwitterTime();

    // Updates the visible time in real time
    setInterval(function(){
         displayFacebookAndTwitterTime();
     }, 1000);

    // For the settings panel to become visible
    $('.settings').on('click', function(event){
        $('.settingsPanel').addClass('is-visible');
    });

    $('.settingsPanel').on('click', function(event){
        // This function registers click on the side panel
        if($(event.target).is('.done')) {
            $('.editBtn').remove();
            if(chrome.extension.getBackgroundPage().isFirstRun){
                $('.settingsPanel').removeClass('is-visible');
            }

            var firstSiteBeingTracked = document.getElementById("firstSite").value;
            var secondSiteBeingTracked = document.getElementById("secondSite").value;
            var thirdSiteBeingTracked = document.getElementById("thirdSite").value;
            var fourthSiteBeingTracked = document.getElementById("fourthSite").value;
            var fifthSiteBeingTracked = document.getElementById("fifthSite").value;

            // Now whoever of them are not null we will need to push there value into the array
            var sitesBeingTracked = [firstSiteBeingTracked, secondSiteBeingTracked, thirdSiteBeingTracked, fourthSiteBeingTracked, fifthSiteBeingTracked];
            var sitesBeingTrackedStorable = JSON.stringify(sitesBeingTracked);
            chrome.storage.local.set({"trackData" : sitesBeingTrackedStorable}, function(){});
            chrome.extension.getBackgroundPage().isFirstRun = false;
            $('.tracksiteInput').removeClass('inputEnabled');
            $('.tracksiteInput').addClass('inputSaved');
            var delay = 300;
            setTimeout(function() {
                $('.tracksiteInput').removeClass('inputSaved');
            }, delay);
            $('.tracksiteInput').addClass('inputDisabled');
            $('.tracksiteInput').prop("disabled", true);
            $('.done').remove();
            $('.lockBtn').remove();
            $('.buttonsContainer').append("").on('click', function(){
                $('.tracksiteInput').prop("disabled", false);
                $('.tracksiteInput').removeClass('inputDisabled');
                $('.tracksiteInput').addClass("inputEnabled");
                $('.done').remove();
                $('.editBtn').remove();
                $('.lockBtn').remove();
                $('.buttonsContainer').append("");
            });

        }

        if($(event.target).is('.settingsPanel') && !chrome.extension.getBackgroundPage().isFirstRun) {
            chrome.storage.local.get("sitesLocked", function(result){
                if(!result.sitesLocked) {
                    $('.settingsPanel').removeClass('is-visible');
                    $('.editBtn').remove();
                    $('.tracksiteInput').removeClass('inputEnabled');
                    $('.tracksiteInput').addClass('inputDisabled');
                    $('.tracksiteInput').prop("disabled", true);
                    $('.done').remove();
                    $('.lockBtn').remove();
                    $('.buttonsContainer').append("").on('click', function(){
                        $('.tracksiteInput').prop("disabled", false);
                        $('.tracksiteInput').addClass("inputEnabled");
                        $('.done').remove();
                        $('.editBtn').remove();
                        $('.lockBtn').remove();
                        $('.buttonsContainer').append("");
                    });
                }else{
                    $('.settingsPanel').removeClass('is-visible');
                }

            });
        }

        if($(event.target).is('.lockBtn')) {
            vex.defaultOptions.className = 'vex-theme-top';
            vex.dialog.confirm({
                message: 'You sure?

 Clicking OK will permanently lock list of your choices, disallowing any further edits.
 You cannot undo this action.',
                callback : function(value){
                    if(value){
                        chrome.storage.local.set({"sitesLocked" : true}, function(){});
                        $('.editBtn').remove();
                        $('.lockBtn').remove();
                        $('.done').remove();
                        $('.tracksiteInput').removeClass("inputEnabled");
                        $('.tracksiteInput').addClass("inputDisabled");
                        $('.tracksiteInput').prop("disabled", true);
                    }
                }
            });
        }

        if($(event.target).is('.editBtn')){
            $('.tracksiteInput').prop("disabled", false);
            $('.tracksiteInput').removeClass('inputDisabled');
            $('.tracksiteInput').addClass("inputEnabled");
            $('.editBtn').remove();
            $('.lockBtn').remove();
            $('.done').remove();
            $('.buttonsContainer').append("");
        }
    });

    // Reposition the elements on the page
    var windowHeight = $(window).height();
    $(".container").css({
        "height" : windowHeight * 0.36,
        "margin-top" : windowHeight * 0.25
    });

    // Update the page with a random quote on each reload
    if(chrome.extension.getBackgroundPage().totalTimeOnWebsites > 0){
        var randomQuote = timeQuotes[Math.floor(Math.random() * timeQuotes.length)];
        var trackerDisplay = document.getElementById("websites");
        trackerDisplay.innerHTML = randomQuote;
    }else{
        var trackerDisplay = document.getElementById("websites");
        trackerDisplay.innerHTML = "going great!";
    }

    var forLabels = [];
    var forValues = [];
    // Get the data from the chrome local storage thing
    chrome.storage.local.get(null, function(extDatas){
        for(var prop in extDatas){
            if(prop.lastIndexOf("timeData", 0) === 0){
                forLabels.push(prop);
                forValues.push(extDatas[prop]);
            }
        }

        var barChartData = {
                labels : [].concat(forLabels),
                datasets : [
                    {
                        fillColor : "rgba(220,220,220,0.6)",
                        data : [].concat(forValues)
                    }
                ],

                getNumData : function(){
                    return Number(this.labels.length);
                }
        }

        var chartView = document.getElementById("myChart");
        var ctx = chartView.getContext("2d");
        window.myBar = new Chart(ctx).Bar(barChartData, {
            responsive : false,
            barShowStroke : false,
            scaleShowGridLines : false,
            showScale : false,
            showTooltips :false,
            barValueSpacing  : 13
        });

        var totalWidthBars = barWidth * barChartData.getNumData();
        var totalWidthSpacing = barSpacing * (barChartData.getNumData() - 1);
        var totalWidthChart = totalWidthBars + totalWidthSpacing;
        var left = ($(window).width() - totalWidthChart)/2;

        $("#myChart").css({
            "width": totalWidthChart,
            "height" : "50%",
            "left" : left
        });
    });

});

$(window).resize(function(){
    var totalWidthChart = $("#myChart").width();
    var left = ($(window).width() - totalWidthChart)/2;

    var windowHeight = $(window).height();
    var windowWidth  = $(window).width();

    $("#myChart").css({
        "width": totalWidthChart,
        "height" :  windowHeight * 0.5,
        "left" : left
    });

    $(".container").css({
        "height" : windowHeight * 0.36,
        "margin-top" : windowHeight * 0.25
    });
});

/*
* Function : displayFacebookAndTwitterTime();
* -------------------------------------------
* This function has a little name problem the thing is that this function
* shows the time for facebook twitter and google plus but due to
* evolution over the times the name has stuck
*/
function displayFacebookAndTwitterTime() {
    var backgroundPage = chrome.extension.getBackgroundPage();
    if(backgroundPage != null){
        var totalTimeSpent = chrome.extension.getBackgroundPage().totalTimeOnWebsites;
        var div = document.getElementById("actualTime");
        div.innerHTML = getReadableTime(totalTimeSpent);
        var storageName = "timeData" + chrome.extension.getBackgroundPage().numDaysSinceUTC();
        var dataToBeWritten = {};
        dataToBeWritten[storageName] = totalTimeSpent;
        dataToBeWritten["today"] = chrome.extension.getBackgroundPage().numDaysSinceUTC();
        chrome.storage.local.set(dataToBeWritten, function(){});
    }
}

/*
* Function : getReadableTime();
* Usage : var readableTime = getReadableTime(2000);
* --------------------------------------------------
* This function takes in the number of seconds as arguments and then
* converts those number of seconds into hours and minutes respectively
* and returns a string that holds the proper time in the format of '3 hours 45 minutes and 3 seconds'
*/
function getReadableTime(totalSeconds) {
    var seconds = totalSeconds % 60;
    var minutes = (Math.floor(totalSeconds/60))%60;
    var hours = (Math.floor(totalSeconds/3600));
    var readableTime = '';
    if (hours > 1)
        readableTime += hours + ' hours ';
    else if(hours == 1)
        readableTime += hours + ' hour '
    if (minutes > 1)
        readableTime += minutes + ' minutes and ' ;
    else if(minutes == 1)
        readableTime += minutes + ' minute and '
    if(seconds == 1){
        readableTime += seconds + ' second ';
    }else{
        readableTime += seconds + ' seconds ';
    }
    return readableTime;
}<commit_msg>more quotes<commit_after>// Stores the width of each bar in pixels
var barWidth = 15;
// Stores the spacing between each line bar in pixels
var barSpacing = 10;

// Quotes about wastage of time
var timeQuotes = [
    "when you kill time, remember that it has no resurrection",
    "the trouble is, you think you have time",
    "time is what we want most, but what we use worst",
    "wasting your time is the subtlest form of suicide",
    "procrastination is the foundation of all disasters",
    "the bad news is time flies. the good news is you're the pilot",
    "you can manage your life by only your time",
    "it is not the time for you to dream, it is the time for you to accomplish the mission",
    "time is much more valuable than money",
    "if time were to take on human form, would she be your taskmaster or freedom fighter?",
    "lack of direction, not lack of time, is the problem. we all have twenty-four hour days",
    "if you spend too much time thinking about a thing, you’ll never get it done",
    "the best time to start was last year. failing that, today will do"
];

$(document).ready(function(){

    var backgroundPage = chrome.extension.getBackgroundPage();
    while(backgroundPage === null){
      backgroundPage = chrome.extension.getBackgroundPage();
    }

    chrome.storage.local.get("sitesLocked", function(result){
        if(backgroundPage !== null && backgroundPage.isFirstRun) {
            $('.settingsPanel').addClass('is-visible');
            $('.tracksiteInput').addClass('inputEnabled');
            $('.lockBtn').remove();
            $('.buttonsContainer').append("");
            $('.done').css({"float" : "none" , "margin" : "0 auto"})
        }else if(result.sitesLocked){
            //remove all the buttons
            $('.done').remove();
            $('.editBtn').remove();
            $('.lockBtn').remove();
            $('.tracksiteInput').removeClass("inputEnabled");
            $('.tracksiteInput').addClass("inputDisabled");
            $('.tracksiteInput').prop("disabled", true);
        } else {
            $('.done').remove();
            $('.tracksiteInput').css({"border": "none"});
            $('.tracksiteInput').prop("disabled", true);
            $('.tracksiteInput').removeClass('inputEnabled');
            $('.tracksiteInput').addClass('inputDisabled');
            $('.buttonsContainer').append("");
        }

    });

    // Try to update the data from the localStorage if we can about the sites that are being tracked
    if(chrome.extension.getBackgroundPage().isFirstRun){
        chrome.storage.local.get("trackData", function(result){
               var sitesBeingTracked = JSON.parse(result.trackData);
               document.getElementById("firstSite").value = sitesBeingTracked[0];
               document.getElementById("secondSite").value = sitesBeingTracked[1];
               document.getElementById("thirdSite").value = sitesBeingTracked[2];
               document.getElementById("fourthSite").value = (sitesBeingTracked[3] === undefined) ? "" : sitesBeingTracked[3];
               document.getElementById("fifthSite").value = (sitesBeingTracked[4] === undefined) ? "" : sitesBeingTracked[4];
        });
    } else {
        chrome.storage.local.get("trackData", function(result){
            var sitesBeingTracked = JSON.parse(result.trackData);
            var inputFieldIds = ["firstSite", "secondSite", "thirdSite", "fourthSite", "fifthSite"];
            var inputIdPos = 0;
            for(var i = 0 ; i < 5 ;i++){
                if(sitesBeingTracked[i] != "") {
                    document.getElementById(inputFieldIds[inputIdPos]).value = sitesBeingTracked[i];
                    inputIdPos++;
                }
            }
        });
    }

    displayFacebookAndTwitterTime();

    // Updates the visible time in real time
    setInterval(function(){
         displayFacebookAndTwitterTime();
     }, 1000);

    // For the settings panel to become visible
    $('.settings').on('click', function(event){
        $('.settingsPanel').addClass('is-visible');
    });

    $('.settingsPanel').on('click', function(event){
        // This function registers click on the side panel
        if($(event.target).is('.done')) {
            $('.editBtn').remove();
            if(chrome.extension.getBackgroundPage().isFirstRun){
                $('.settingsPanel').removeClass('is-visible');
            }

            var firstSiteBeingTracked = document.getElementById("firstSite").value;
            var secondSiteBeingTracked = document.getElementById("secondSite").value;
            var thirdSiteBeingTracked = document.getElementById("thirdSite").value;
            var fourthSiteBeingTracked = document.getElementById("fourthSite").value;
            var fifthSiteBeingTracked = document.getElementById("fifthSite").value;

            // Now whoever of them are not null we will need to push there value into the array
            var sitesBeingTracked = [firstSiteBeingTracked, secondSiteBeingTracked, thirdSiteBeingTracked, fourthSiteBeingTracked, fifthSiteBeingTracked];
            var sitesBeingTrackedStorable = JSON.stringify(sitesBeingTracked);
            chrome.storage.local.set({"trackData" : sitesBeingTrackedStorable}, function(){});
            chrome.extension.getBackgroundPage().isFirstRun = false;
            $('.tracksiteInput').removeClass('inputEnabled');
            $('.tracksiteInput').addClass('inputSaved');
            var delay = 300;
            setTimeout(function() {
                $('.tracksiteInput').removeClass('inputSaved');
            }, delay);
            $('.tracksiteInput').addClass('inputDisabled');
            $('.tracksiteInput').prop("disabled", true);
            $('.done').remove();
            $('.lockBtn').remove();
            $('.buttonsContainer').append("").on('click', function(){
                $('.tracksiteInput').prop("disabled", false);
                $('.tracksiteInput').removeClass('inputDisabled');
                $('.tracksiteInput').addClass("inputEnabled");
                $('.done').remove();
                $('.editBtn').remove();
                $('.lockBtn').remove();
                $('.buttonsContainer').append("");
            });

        }

        if($(event.target).is('.settingsPanel') && !chrome.extension.getBackgroundPage().isFirstRun) {
            chrome.storage.local.get("sitesLocked", function(result){
                if(!result.sitesLocked) {
                    $('.settingsPanel').removeClass('is-visible');
                    $('.editBtn').remove();
                    $('.tracksiteInput').removeClass('inputEnabled');
                    $('.tracksiteInput').addClass('inputDisabled');
                    $('.tracksiteInput').prop("disabled", true);
                    $('.done').remove();
                    $('.lockBtn').remove();
                    $('.buttonsContainer').append("").on('click', function(){
                        $('.tracksiteInput').prop("disabled", false);
                        $('.tracksiteInput').addClass("inputEnabled");
                        $('.done').remove();
                        $('.editBtn').remove();
                        $('.lockBtn').remove();
                        $('.buttonsContainer').append("");
                    });
                }else{
                    $('.settingsPanel').removeClass('is-visible');
                }

            });
        }

        if($(event.target).is('.lockBtn')) {
            vex.defaultOptions.className = 'vex-theme-top';
            vex.dialog.confirm({
                message: 'You sure?

 Clicking OK will permanently lock list of your choices, disallowing any further edits.
 You cannot undo this action.',
                callback : function(value){
                    if(value){
                        chrome.storage.local.set({"sitesLocked" : true}, function(){});
                        $('.editBtn').remove();
                        $('.lockBtn').remove();
                        $('.done').remove();
                        $('.tracksiteInput').removeClass("inputEnabled");
                        $('.tracksiteInput').addClass("inputDisabled");
                        $('.tracksiteInput').prop("disabled", true);
                    }
                }
            });
        }

        if($(event.target).is('.editBtn')){
            $('.tracksiteInput').prop("disabled", false);
            $('.tracksiteInput').removeClass('inputDisabled');
            $('.tracksiteInput').addClass("inputEnabled");
            $('.editBtn').remove();
            $('.lockBtn').remove();
            $('.done').remove();
            $('.buttonsContainer').append("");
        }
    });

    // Reposition the elements on the page
    var windowHeight = $(window).height();
    $(".container").css({
        "height" : windowHeight * 0.36,
        "margin-top" : windowHeight * 0.25
    });

    // Update the page with a random quote on each reload
    if(chrome.extension.getBackgroundPage().totalTimeOnWebsites > 0){
        var randomQuote = timeQuotes[Math.floor(Math.random() * timeQuotes.length)];
        var trackerDisplay = document.getElementById("websites");
        trackerDisplay.innerHTML = randomQuote;
    }else{
        var trackerDisplay = document.getElementById("websites");
        trackerDisplay.innerHTML = "going great!";
    }

    var forLabels = [];
    var forValues = [];
    // Get the data from the chrome local storage thing
    chrome.storage.local.get(null, function(extDatas){
        for(var prop in extDatas){
            if(prop.lastIndexOf("timeData", 0) === 0){
                forLabels.push(prop);
                forValues.push(extDatas[prop]);
            }
        }

        var barChartData = {
                labels : [].concat(forLabels),
                datasets : [
                    {
                        fillColor : "rgba(220,220,220,0.6)",
                        data : [].concat(forValues)
                    }
                ],

                getNumData : function(){
                    return Number(this.labels.length);
                }
        }

        var chartView = document.getElementById("myChart");
        var ctx = chartView.getContext("2d");
        window.myBar = new Chart(ctx).Bar(barChartData, {
            responsive : false,
            barShowStroke : false,
            scaleShowGridLines : false,
            showScale : false,
            showTooltips :false,
            barValueSpacing  : 13
        });

        var totalWidthBars = barWidth * barChartData.getNumData();
        var totalWidthSpacing = barSpacing * (barChartData.getNumData() - 1);
        var totalWidthChart = totalWidthBars + totalWidthSpacing;
        var left = ($(window).width() - totalWidthChart)/2;

        $("#myChart").css({
            "width": totalWidthChart,
            "height" : "50%",
            "left" : left
        });
    });

});

$(window).resize(function(){
    var totalWidthChart = $("#myChart").width();
    var left = ($(window).width() - totalWidthChart)/2;

    var windowHeight = $(window).height();
    var windowWidth  = $(window).width();

    $("#myChart").css({
        "width": totalWidthChart,
        "height" :  windowHeight * 0.5,
        "left" : left
    });

    $(".container").css({
        "height" : windowHeight * 0.36,
        "margin-top" : windowHeight * 0.25
    });
});

/*
* Function : displayFacebookAndTwitterTime();
* -------------------------------------------
* This function has a little name problem the thing is that this function
* shows the time for facebook twitter and google plus but due to
* evolution over the times the name has stuck
*/
function displayFacebookAndTwitterTime() {
    var backgroundPage = chrome.extension.getBackgroundPage();
    if(backgroundPage != null){
        var totalTimeSpent = chrome.extension.getBackgroundPage().totalTimeOnWebsites;
        var div = document.getElementById("actualTime");
        div.innerHTML = getReadableTime(totalTimeSpent);
        var storageName = "timeData" + chrome.extension.getBackgroundPage().numDaysSinceUTC();
        var dataToBeWritten = {};
        dataToBeWritten[storageName] = totalTimeSpent;
        dataToBeWritten["today"] = chrome.extension.getBackgroundPage().numDaysSinceUTC();
        chrome.storage.local.set(dataToBeWritten, function(){});
    }
}

/*
* Function : getReadableTime();
* Usage : var readableTime = getReadableTime(2000);
* --------------------------------------------------
* This function takes in the number of seconds as arguments and then
* converts those number of seconds into hours and minutes respectively
* and returns a string that holds the proper time in the format of '3 hours 45 minutes and 3 seconds'
*/
function getReadableTime(totalSeconds) {
    var seconds = totalSeconds % 60;
    var minutes = (Math.floor(totalSeconds/60))%60;
    var hours = (Math.floor(totalSeconds/3600));
    var readableTime = '';
    if (hours > 1)
        readableTime += hours + ' hours ';
    else if(hours == 1)
        readableTime += hours + ' hour '
    if (minutes > 1)
        readableTime += minutes + ' minutes and ' ;
    else if(minutes == 1)
        readableTime += minutes + ' minute and '
    if(seconds == 1){
        readableTime += seconds + ' second ';
    }else{
        readableTime += seconds + ' seconds ';
    }
    return readableTime;
}<|endoftext|>


<commit_before>var _ = require('lodash');
var board = [
    ['R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R'],
    ['P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'],
    [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
    [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
    [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
    [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
    ['p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'],
    ['r', 'n', 'b', 'q', 'k', 'b', 'n', 'r'],
];

function print(board){
  // Before any rows are printed, print the `<table>`...
  console.log('
');

  _.forEach(board, function(row, rank){
      // Before any cells are printed...
      console.log({
          'row': "
" // print the table row
      });
      _.forEach(row, function(square, file){
            console.log({
                'file': '	', // td for each square
                'square': square // shows blank space or letter for piece
            })
      }); // END foreach(row)
    console.log({
          'row': "
"
      });
      // After all the cells are printed...
  }); // END foreach(board)
  // After all the rows are printed...
  console.log('
 ');
}

print(board);<commit_msg>@jaredstevick @johnalxndr things<commit_after>function print(){
    document.write('
');

    _.times(8, function(){
        document.write('
');
        _.times(8, function(){
            document.write('	');
        });
        document.write('
');
    });

    document.write('
');
}

print();<|endoftext|>


<commit_before>$( document ).ready(function() {
    /* slide transitions */
    var pauseTime = 4000;
    var transitionTime = 3000;
    var initialTimeout = window.setTimeout(fadeOutSlide1, pauseTime);
    var slideCompleted = new Array();
    var lightningTravelTime = 3000;
    var lightningWaitTime = 1000;
    var thisLightning;
    var thisLightningWidth;
    var lightningCounter = 1;
    var rightSpawnNumber = 4;

    function fadeOutSlide1(){
    	fadeOut($("#slide-1"));
    	reveal($("#slide-2"));
    	var afterSlide1Timeout = window.setTimeout(revealSlide3, pauseTime);
    }

    function revealSlide3(){
    	reveal($("#slide-3"));
        var afterSlide3Timeout = window.setTimeout(revealBubble, pauseTime*2);
    }

    function revealBubble(){
        reveal($("#bubble"));
    }

    function fadeOut(target){
    	target.fadeTo(transitionTime,0,'swing',
    		function(){
    			target.addClass('hidden');
    		}
    	);
    }

    function reveal(target){
    	//target.removeClass('hidden');
    	target.fadeTo(transitionTime,1,'swing', function(){

            //add this slide id to the array listing completed slide names
            slideCompleted.push(target[0].id);
        });
    }

    /*lightning*/
    var lightning = new Array();

    /*lightning right*/
    var lightningRight = new Array();

    /*prototype lightning definition*/
	lightning.push($(".lightningLeft"));
    lightningRight.push($(".lightningRight"));

    var w0 = parseInt(lightning[0].css("width"), 10);
    var h0 = parseInt(lightning[0].css("height"), 10);
    var minWidth = w0 / 4;
    /* initial left position of prototype lightnings*/
    var l0 = parseInt(lightning[0].css("left"));
    var r0 = parseInt(lightningRight[0].css("left"));

    /*spawning and moving next lightning*/
    function newLightning(direction){
        var endLeftPos ;
        if (direction == 'left'){
            thisLightning = lightning[0].clone();
            lightning.push(thisLightning);
            endLeftPos = windowWidth;
        } else if (direction == 'right'){
            thisLightning = lightningRight[0].clone();
            lightningRight.push(thisLightning);
            endLeftPos = w0*(-1);
        }

        thisLightningWidth = getRandomInt(minWidth, w0);

        thisLightning.css("width", thisLightningWidth);
        thisLightning.css("height", thisLightningWidth / (w0/h0));
        thisLightning.css("top", getRandomInt(0, windowHeight)*1.5);
        thisLightning.attr('id', 'lightning-'+lightningCounter);

        thisLightning.appendTo(lightning[0].parent());

        //moving it after creating it
        thisLightning.animate({left: endLeftPos}, lightningTravelTime*(thisLightningWidth/w0), 'swing', function(){
                //remove this lightning from DOM
                this.remove();
                //remove this lightning from array
                if (direction == 'left'){
                    lightning.splice($.inArray(thisLightning, lightning),1);
                } else if (direction == 'right'){
                    lightningRight.splice($.inArray(thisLightning, lightningRight),1);
                }
        });

        lightningCounter ++;

        //track google analytics event
        ga('send', 'event', 'lightning', direction, 'Easter Eggs');

        //run left lightning again after random time
        if(direction == 'left'){
            window.setTimeout(function(){
                newLightning(direction);
            }, getRandomInt(0,lightningWaitTime));
        }

    }

    // run this function only once. Start the lightning moving and get rid of the functions to reposition the speech bubble
    $('#kepler a').one( 'click', function(){
        //$window.off('resize');
        $window.off('scroll');
        fadeOut($('#bubble'));
        //moveLightning();
        newLightning('left');
        //newLightning();
        $('#keplerImg').unwrap();

        //track google analytics event
        ga('send', 'event', 'Kepler', 'click', 'Easter Eggs');

        //don't follow the link
        return false;
    });

    //spawn lightning swimming from the right when lightning is clicked
    $('#slide-2').on('click', '.lightning', function(){
        for (count = 0; count < rightSpawnNumber; count++){
            newLightning('right');
        }
    });

    	/*reusable generic functions*/
    function getRandomInt (min, max) {
	    return Math.floor(Math.random()*(max-min+1)+min);
	}

    /*positioning bubble*/
    var $window = $(window),
        $bubble = $('#bubble'),
        windowHeight,
        windowWidth,
        bubbleTop;

    function recalculateWindow(){
        windowHeight = $window.height();
        windowWidth = $window.width();
        bubbleTop = $bubble.offset().top;
        //console.log('recalculate ran');
    }

    function toggleOffscreen(){
        $bubble.toggleClass('offscreen', ($window.scrollTop() + windowHeight) < bubbleTop);
        //console.log('scroll ran');
    }

    // run recalculate once on start
    recalculateWindow();
    //run recalculate again on each window resize
    $window.on('resize', recalculateWindow);

    //run toggleOffscreen on each scroll event
    $window.on('scroll', toggleOffscreen);

});
<commit_msg>varying number of lightning based on size clicked<commit_after>$( document ).ready(function() {
    /* slide transitions */
    var pauseTime = 4000;
    var transitionTime = 3000;
    var initialTimeout = window.setTimeout(fadeOutSlide1, pauseTime);
    var slideCompleted = new Array();
    var lightningTravelTime = 3000;
    var lightningWaitTime = 1000;
    var thisLightning;
    var thisLightningWidth;
    var lightningCounter = 1;

    function fadeOutSlide1(){
    	fadeOut($("#slide-1"));
    	reveal($("#slide-2"));
    	var afterSlide1Timeout = window.setTimeout(revealSlide3, pauseTime);
    }

    function revealSlide3(){
    	reveal($("#slide-3"));
        var afterSlide3Timeout = window.setTimeout(revealBubble, pauseTime*2);
    }

    function revealBubble(){
        reveal($("#bubble"));
    }

    function fadeOut(target){
    	target.fadeTo(transitionTime,0,'swing',
    		function(){
    			target.addClass('hidden');
    		}
    	);
    }

    function reveal(target){
    	//target.removeClass('hidden');
    	target.fadeTo(transitionTime,1,'swing', function(){

            //add this slide id to the array listing completed slide names
            slideCompleted.push(target[0].id);
        });
    }

    /*lightning*/
    var lightning = new Array();

    /*lightning right*/
    var lightningRight = new Array();

    /*prototype lightning definition*/
	lightning.push($(".lightningLeft"));
    lightningRight.push($(".lightningRight"));

    var w0 = parseInt(lightning[0].css("width"), 10);
    var h0 = parseInt(lightning[0].css("height"), 10);
    var minWidth = w0 / 4;
    /* initial left position of prototype lightnings*/
    var l0 = parseInt(lightning[0].css("left"));
    var r0 = parseInt(lightningRight[0].css("left"));

    /*spawning and moving next lightning*/
    function newLightning(direction){
        var endLeftPos ;
        if (direction == 'left'){
            thisLightning = lightning[0].clone();
            lightning.push(thisLightning);
            endLeftPos = windowWidth;
        } else if (direction == 'right'){
            thisLightning = lightningRight[0].clone();
            lightningRight.push(thisLightning);
            endLeftPos = w0*(-1);
        }

        thisLightningWidth = getRandomInt(minWidth, w0);

        thisLightning.css("width", thisLightningWidth);
        thisLightning.css("height", thisLightningWidth / (w0/h0));
        thisLightning.css("top", getRandomInt(0, windowHeight)*1.5);
        thisLightning.attr('id', 'lightning-'+lightningCounter);

        thisLightning.appendTo(lightning[0].parent());

        //moving it after creating it
        thisLightning.animate({left: endLeftPos}, lightningTravelTime*(thisLightningWidth/w0), 'swing', function(){
                //remove this lightning from DOM
                this.remove();
                //remove this lightning from array
                if (direction == 'left'){
                    lightning.splice($.inArray(thisLightning, lightning),1);
                } else if (direction == 'right'){
                    lightningRight.splice($.inArray(thisLightning, lightningRight),1);
                }
        });

        lightningCounter ++;

        //track google analytics event
        ga('send', 'event', 'lightning', direction, 'Easter Eggs');

        //run left lightning again after random time
        if(direction == 'left'){
            window.setTimeout(function(){
                newLightning(direction);
            }, getRandomInt(0,lightningWaitTime));
        }

    }

    // run this function only once. Start the lightning moving and get rid of the functions to reposition the speech bubble
    $('#kepler a').one( 'click', function(){
        //$window.off('resize');
        $window.off('scroll');
        fadeOut($('#bubble'));
        //moveLightning();
        newLightning('left');
        //newLightning();
        $('#keplerImg').unwrap();

        //track google analytics event
        ga('send', 'event', 'Kepler', 'click', 'Easter Eggs');

        //don't follow the link
        return false;
    });

    //spawn lightning swimming from the right when lightning is clicked
    $('#slide-2').on('click', '.lightning', function(){
        var clickedLightningID = this.id;
        //console.log(parseInt(($('#'+clickedLightningID).css('width'))));
        var sizeClicked = parseInt(($('#'+clickedLightningID).css('width')));

        for (count = 0; count <= (w0-sizeClicked)/5; count++){
            newLightning('right');
        }
    });

    	/*reusable generic functions*/
    function getRandomInt (min, max) {
	    return Math.floor(Math.random()*(max-min+1)+min);
	}

    /*positioning bubble*/
    var $window = $(window),
        $bubble = $('#bubble'),
        windowHeight,
        windowWidth,
        bubbleTop;

    function recalculateWindow(){
        windowHeight = $window.height();
        windowWidth = $window.width();
        bubbleTop = $bubble.offset().top;
        //console.log('recalculate ran');
    }

    function toggleOffscreen(){
        $bubble.toggleClass('offscreen', ($window.scrollTop() + windowHeight) < bubbleTop);
        //console.log('scroll ran');
    }

    // run recalculate once on start
    recalculateWindow();
    //run recalculate again on each window resize
    $window.on('resize', recalculateWindow);

    //run toggleOffscreen on each scroll event
    $window.on('scroll', toggleOffscreen);

});
<|endoftext|>