<commit_before>$.fn.DataTable.ColVis.prototype._fnDomColumnButton = function(i) {
    var
        that = this,
        column = this.s.dt.aoColumns[i],
        dt = this.s.dt;

    var title = this.s.fnLabel === null ?
        column.sTitle :
        this.s.fnLabel(i, column.sTitle, column.nTh);

    return $(
            '
' +
            '' +
            '<input type="checkbox" />' +
            '' + title + '' +
            '' +
            '
'
        )
        .click(function(e) {
            var showHide = !$('input', this).is(":checked");
            if (e.target.nodeName.toLowerCase() !== "li") {
                showHide = !showHide;
            }

            /* Need to consider the case where the initialiser created more than one table - change the
             * API index that DataTables is using
             */
            var oldIndex = $.fn.dataTableExt.iApiIndex;
            $.fn.dataTableExt.iApiIndex = that._fnDataTablesApiIndex.call(that);

            // Optimisation for server-side processing when scrolling - don't do a full redraw
            if (dt.oFeatures.bServerSide) {
                that.s.dt.oInstance.fnSetColumnVis(i, showHide, false);
                that.s.dt.oInstance.fnAdjustColumnSizing(false);
                if (dt.oScroll.sX !== "" || dt.oScroll.sY !== "") {
                    that.s.dt.oInstance.oApi._fnScrollDraw(that.s.dt);
                }
                that._fnDrawCallback();
            } else {
                that.s.dt.oInstance.fnSetColumnVis(i, showHide);
            }

            $.fn.dataTableExt.iApiIndex = oldIndex; /* Restore */

            if ( (e.target.nodeName.toLowerCase() === 'input' || e.target.nodeName.toLowerCase() === 'li') && that.s.fnStateChange !== null ) {
                that.s.fnStateChange.call(that, i, showHide);
            }
        })[0];
};

function calculate() {
    var attacker, defender, setName, setTier;
    var selectedTiers = getSelectedTiers();
    var setOptions = getSetOptions();
    var dataSet = [];
    for (var i = 0; i < setOptions.length; i++) {
        if (setOptions[i].id && typeof setOptions[i].id !== "undefined") {
            setName = setOptions[i].id.substring(setOptions[i].id.indexOf("(") + 1, setOptions[i].id.lastIndexOf(")"));
            setTier = setName.substring(0, setName.indexOf(" "));
            if (_.contains(selectedTiers, setTier)) {
                attacker = (mode === "one-vs-all") ? new Pokemon($("#p1")) : new Pokemon(setOptions[i].id);
                defender = (mode === "one-vs-all") ? new Pokemon(setOptions[i].id) : new Pokemon($("#p1"));
                var field = new Field();
                var damageResults = calculateMovesOfAttacker(attacker, defender, field);
                var result, minDamage, maxDamage, minPercent, maxPercent;
                var defenderSide = field.getSide( ~~(mode === "one-vs-all") );
                var highestMaxPercent = -1;
                var data = [
                    setOptions[i].id,
                    (mode === "one-vs-all") ? defender.type1 : attacker.type1,
                    (mode === "one-vs-all") ? defender.type2 : attacker.type2,
                    (mode === "one-vs-all") ? defender.ability : attacker.ability,
                    (mode === "one-vs-all") ? defender.item : attacker.item
                ];
                for (var n = 0; n < 4; n++) {
                    result = damageResults[n];
                    minDamage = result.damage[0] * attacker.moves[n].hits;
                    maxDamage = result.damage[result.damage.length-1] * attacker.moves[n].hits;
                    minPercent = Math.floor(minDamage * 1000 / defender.maxHP) / 10;
                    maxPercent = Math.floor(maxDamage * 1000 / defender.maxHP) / 10;
                    result.koChanceText = attacker.moves[n].bp === 0 ? 'nice move'
                            : getKOChanceText(result.damage, defender, defenderSide, attacker.moves[n].hits, attacker.ability === 'Bad Dreams');
                    if (maxPercent > highestMaxPercent) {
                        highestMaxPercent = maxPercent;
                        while (data.length > 5) { data.pop(); }
                        data.push( attacker.moves[n].name.replace("Hidden Power", "HP") );
                        data.push( minPercent + " - " + maxPercent + "%" );
                        data.push( result.koChanceText );
                    } else if (maxPercent === highestMaxPercent) {
                        data[5] += (attacker.moves[n].name === "(No Move)") ? "" : " & " + attacker.moves[n].name.replace("Hidden Power", "HP");
                    }
                }
                dataSet.push(data);
            }
        }
    }

    table.clear();
    table.rows.add(dataSet).draw();
}

function getSelectedTiers() {
    var selectedTiers = $('.tiers input:checked').map(function () {
        return this.id;
    }).get();
    return selectedTiers;
}

var calculateMovesOfAttacker;
$(".gen").change(function () {
    $(".tiers input").prop("checked", false);
    $("#singles-format").attr("disabled", false);
    switch(gen) {
        case 1:
            calculateMovesOfAttacker = CALCULATE_MOVES_OF_ATTACKER_RBY;
            break;
        case 2:
            calculateMovesOfAttacker = CALCULATE_MOVES_OF_ATTACKER_GSC;
            break;
        case 3:
            calculateMovesOfAttacker = CALCULATE_MOVES_OF_ATTACKER_ADV;
            break;
        case 4:
            calculateMovesOfAttacker = CALCULATE_MOVES_OF_ATTACKER_DPP;
            break;
        default:
            calculateMovesOfAttacker = CALCULATE_MOVES_OF_ATTACKER_BW;
            break;
    }
    adjustTierBorderRadius();

    if ( $.fn.DataTable.isDataTable("#holder-2")  ) {
        table.clear();
        constructDataTable();

        var honkalculator = "<button style='position:absolute' class='bs-btn bs-btn-default'>Honkalculate</button>";
        $("#holder-2_wrapper").prepend(honkalculator);

        var dtHeadTop = $(".sorting").offset().top;
        var dtWrapperToHead = dtHeadTop - $("#holder-2_wrapper").offset().top;
        var fieldsetToDTHead = dtHeadTop - ( $(".holder-0").offset().top + $(".holder-0 .panel-title").outerHeight()/2 );
        var buttonOffset = (dtWrapperToHead - fieldsetToDTHead / 2) - $(".bs-btn").outerHeight()/2;
        $(".bs-btn").css({ "top": buttonOffset });
        $(".bs-btn").click(function() {
            calculate();
        });
    }
});

function adjustTierBorderRadius() {
    var squaredLeftCorner = { "border-top-left-radius": 0, "border-bottom-left-radius": 0 };
    var roundedLeftCorner = { "border-top-left-radius": "8px", "border-bottom-left-radius": "8px" };
    if (gen <= 2) {
        $("#UU").next("label").css(roundedLeftCorner);
    } else {
            $("#UU").next("label").css(squaredLeftCorner);
            $("#NU").next("label").css(roundedLeftCorner);

            if (gen > 3) {
                $("#NU").next("label").css(squaredLeftCorner);
                $("#LC").next("label").css(roundedLeftCorner);

                if (gen > 4) {
                    $("#LC").next("label").css(squaredLeftCorner);
                    $("#Doubles").next("label").css(roundedLeftCorner);

                    if (gen > 5) {
                        $("#Doubles").next("label").css(squaredLeftCorner);
                    }
                }
            }
    }
}

$(".mode").change(function() {
    if ( $("#one-vs-one").prop("checked") ) {
        window.location.replace( "index.html" );
  } else {
        window.location.replace( "calc_bc.html?mode=" + $(this).attr("id") );
  }
});

$(".tiers label").mouseup(function() {
    var oldID = $('.tiers input:checked').attr("id");
    var newID = $(this).attr("for");
    if ((oldID === "Doubles" || oldID === "VGC14") && (newID !== oldID)) {
        $("#singles-format").attr("disabled", false);
        $("#singles-format").prop("checked", true);
    }
    if ((oldID === "VGC14" || oldID === "LC") && (newID !== "VGC14" && newID !== "LC")) {
        $('.level').val("100");
        $('.level').keyup();
        $('.level').popover({
            content: "Level has been reset to 100",
            placement: "right"
        }).popover('show');
        setTimeout(function(){ $('.level').popover('destroy') }, 3000);
    }
});

$(".tiers input").change(function() {
    var type = $(this).attr("type");
    var id = $(this).attr("id");
    $(".tiers input").not(":" + type).prop("checked", false); // deselect all radios if a checkbox is checked, and vice-versa

    if (gen === 1 && $("#OU").prop("checked")) {
        $("#UU").prop("checked", true);
    }

    if (id === "Doubles" || id === "VGC14") {
        $("#doubles-format").prop("checked", true);
        $("#singles-format").attr("disabled", true);
    }

    if (id === "LC" && $('.level').val() !== "5") {
        $('.level').val("5");
        $('.level').popover({
            content: "Level has been set to 5",
            placement: "right"
        }).popover('show');
        setTimeout(function(){ $('.level').popover('destroy') }, 1350);
    }

    if (id === "VGC14" && $('.level').val() !== "50") {
        $('.level').val("50");
        $('.level').popover({
            content: "Level has been set to 50",
            placement: "right"
        }).popover('show');
        setTimeout(function(){ $('.level').popover('destroy') }, 1350);
    }
});

$(".set-selector").change(function() {
    var selectedTier = getSelectedTiers()[0];
    if (selectedTier === "LC" && $('.level').val() !== "5") {
        $('.level').val("5");
        $('.level').popover({
            content: "Level has been set to 5",
            placement: "right"
        }).popover('show');
        setTimeout(function(){ $('.level').popover('destroy') }, 1350);
    }

    if (selectedTier === "VGC14" && $('.level').val() !== "50") {
        $('.level').val("50");
        $('.level').popover({
            content: "Level has been set to 50",
            placement: "right"
        }).popover('show');
        setTimeout(function(){ $('.level').popover('destroy') }, 1350);
    }
});

var table;
function constructDataTable() {
    var dtWidth = $(window).width() - $("#holder-2").offset().left;
    dtWidth -= 2 * parseFloat($(".holder-0").css("padding-right"));
    table = $("#holder-2").DataTable( {
        destroy: true,
        columnDefs: [
            {
                targets: (gen > 2) ? [] : (gen === 2) ? [3] : [3, 4],
                visible: false,
                searchable: false
            }
        ],
        dom: 'C<"clear">frtiS',
        colVis: {
            exclude: (gen > 2) ? [0, 5, 6] : (gen === 2) ? [0, 3, 5, 6] : [0, 3, 4, 5, 6],
            stateChange: function(iColumn, bVisible) {
                var column = table.settings()[0].aoColumns[iColumn];
                if (column.bSearchable !== bVisible) {
                    column.bSearchable = bVisible;
                    table.rows().invalidate();
                }
            }
        },
        scrollX: dtWidth,
        scrollY: dtHeight,
        scrollCollapse: true
    } );
    $(".dataTables_wrapper").width(dtWidth);
}

function getBottomOffset(obj) {
    return obj.offset().top + obj.outerHeight();
}

var mode, dtHeight;
$(document).ready(function() {
    var url = window.location.href;
    mode = url.substring(url.indexOf('=') + 1, url.length);
    $("#" + mode).prop("checked", true);
    $("#holder-2 th:first").text( (mode === "one-vs-all") ? "Defender" : "Attacker" );
    $("#holder-2").show();

    setDTHeight();
    constructDataTable();

    var honkalculator = "<button style='position:absolute' class='bs-btn bs-btn-default'>Honkalculate</button>";
    $("#holder-2_wrapper").prepend(honkalculator);

    var dtHeadTop = $(".sorting").offset().top;
    var dtWrapperToHead = dtHeadTop - $("#holder-2_wrapper").offset().top;
    var fieldsetToDTHead = dtHeadTop - ( $(".holder-0").offset().top + $(".holder-0 .panel-title").outerHeight()/2 );
    var buttonOffset = (dtWrapperToHead - fieldsetToDTHead / 2) - $(".bs-btn").outerHeight()/2;
    $(".bs-btn").css({ "top": buttonOffset });
    $(".bs-btn").click(function() {
        calculate();
    });
});

function setDTHeight() {
    $("#holder-2").DataTable( {
        dom: 'C<"clear">frti'
    });

    var theadBottomOffset = getBottomOffset($(".sorting"));
    var heightUnderDT = getBottomOffset($(".holder-0")) - getBottomOffset($("#holder-2 tbody"));
    dtHeight = $(document).height() - theadBottomOffset - heightUnderDT;
}<commit_msg>Recalculate stats when tier changed.<commit_after>$.fn.DataTable.ColVis.prototype._fnDomColumnButton = function(i) {
    var
        that = this,
        column = this.s.dt.aoColumns[i],
        dt = this.s.dt;

    var title = this.s.fnLabel === null ?
        column.sTitle :
        this.s.fnLabel(i, column.sTitle, column.nTh);

    return $(
            '
' +
            '' +
            '<input type="checkbox" />' +
            '' + title + '' +
            '' +
            '
'
        )
        .click(function(e) {
            var showHide = !$('input', this).is(":checked");
            if (e.target.nodeName.toLowerCase() !== "li") {
                showHide = !showHide;
            }

            /* Need to consider the case where the initialiser created more than one table - change the
             * API index that DataTables is using
             */
            var oldIndex = $.fn.dataTableExt.iApiIndex;
            $.fn.dataTableExt.iApiIndex = that._fnDataTablesApiIndex.call(that);

            // Optimisation for server-side processing when scrolling - don't do a full redraw
            if (dt.oFeatures.bServerSide) {
                that.s.dt.oInstance.fnSetColumnVis(i, showHide, false);
                that.s.dt.oInstance.fnAdjustColumnSizing(false);
                if (dt.oScroll.sX !== "" || dt.oScroll.sY !== "") {
                    that.s.dt.oInstance.oApi._fnScrollDraw(that.s.dt);
                }
                that._fnDrawCallback();
            } else {
                that.s.dt.oInstance.fnSetColumnVis(i, showHide);
            }

            $.fn.dataTableExt.iApiIndex = oldIndex; /* Restore */

            if ( (e.target.nodeName.toLowerCase() === 'input' || e.target.nodeName.toLowerCase() === 'li') && that.s.fnStateChange !== null ) {
                that.s.fnStateChange.call(that, i, showHide);
            }
        })[0];
};

function calculate() {
    var attacker, defender, setName, setTier;
    var selectedTiers = getSelectedTiers();
    var setOptions = getSetOptions();
    var dataSet = [];
    for (var i = 0; i < setOptions.length; i++) {
        if (setOptions[i].id && typeof setOptions[i].id !== "undefined") {
            setName = setOptions[i].id.substring(setOptions[i].id.indexOf("(") + 1, setOptions[i].id.lastIndexOf(")"));
            setTier = setName.substring(0, setName.indexOf(" "));
            if (_.contains(selectedTiers, setTier)) {
                attacker = (mode === "one-vs-all") ? new Pokemon($("#p1")) : new Pokemon(setOptions[i].id);
                defender = (mode === "one-vs-all") ? new Pokemon(setOptions[i].id) : new Pokemon($("#p1"));
                var field = new Field();
                var damageResults = calculateMovesOfAttacker(attacker, defender, field);
                var result, minDamage, maxDamage, minPercent, maxPercent;
                var defenderSide = field.getSide( ~~(mode === "one-vs-all") );
                var highestMaxPercent = -1;
                var data = [
                    setOptions[i].id,
                    (mode === "one-vs-all") ? defender.type1 : attacker.type1,
                    (mode === "one-vs-all") ? defender.type2 : attacker.type2,
                    (mode === "one-vs-all") ? defender.ability : attacker.ability,
                    (mode === "one-vs-all") ? defender.item : attacker.item
                ];
                for (var n = 0; n < 4; n++) {
                    result = damageResults[n];
                    minDamage = result.damage[0] * attacker.moves[n].hits;
                    maxDamage = result.damage[result.damage.length-1] * attacker.moves[n].hits;
                    minPercent = Math.floor(minDamage * 1000 / defender.maxHP) / 10;
                    maxPercent = Math.floor(maxDamage * 1000 / defender.maxHP) / 10;
                    result.koChanceText = attacker.moves[n].bp === 0 ? 'nice move'
                            : getKOChanceText(result.damage, defender, defenderSide, attacker.moves[n].hits, attacker.ability === 'Bad Dreams');
                    if (maxPercent > highestMaxPercent) {
                        highestMaxPercent = maxPercent;
                        while (data.length > 5) { data.pop(); }
                        data.push( attacker.moves[n].name.replace("Hidden Power", "HP") );
                        data.push( minPercent + " - " + maxPercent + "%" );
                        data.push( result.koChanceText );
                    } else if (maxPercent === highestMaxPercent) {
                        data[5] += (attacker.moves[n].name === "(No Move)") ? "" : " & " + attacker.moves[n].name.replace("Hidden Power", "HP");
                    }
                }
                dataSet.push(data);
            }
        }
    }

    table.clear();
    table.rows.add(dataSet).draw();
}

function getSelectedTiers() {
    var selectedTiers = $('.tiers input:checked').map(function () {
        return this.id;
    }).get();
    return selectedTiers;
}

var calculateMovesOfAttacker;
$(".gen").change(function () {
    $(".tiers input").prop("checked", false);
    $("#singles-format").attr("disabled", false);
    switch(gen) {
        case 1:
            calculateMovesOfAttacker = CALCULATE_MOVES_OF_ATTACKER_RBY;
            break;
        case 2:
            calculateMovesOfAttacker = CALCULATE_MOVES_OF_ATTACKER_GSC;
            break;
        case 3:
            calculateMovesOfAttacker = CALCULATE_MOVES_OF_ATTACKER_ADV;
            break;
        case 4:
            calculateMovesOfAttacker = CALCULATE_MOVES_OF_ATTACKER_DPP;
            break;
        default:
            calculateMovesOfAttacker = CALCULATE_MOVES_OF_ATTACKER_BW;
            break;
    }
    adjustTierBorderRadius();

    if ( $.fn.DataTable.isDataTable("#holder-2")  ) {
        table.clear();
        constructDataTable();

        var honkalculator = "<button style='position:absolute' class='bs-btn bs-btn-default'>Honkalculate</button>";
        $("#holder-2_wrapper").prepend(honkalculator);

        var dtHeadTop = $(".sorting").offset().top;
        var dtWrapperToHead = dtHeadTop - $("#holder-2_wrapper").offset().top;
        var fieldsetToDTHead = dtHeadTop - ( $(".holder-0").offset().top + $(".holder-0 .panel-title").outerHeight()/2 );
        var buttonOffset = (dtWrapperToHead - fieldsetToDTHead / 2) - $(".bs-btn").outerHeight()/2;
        $(".bs-btn").css({ "top": buttonOffset });
        $(".bs-btn").click(function() {
            calculate();
        });
    }
});

function adjustTierBorderRadius() {
    var squaredLeftCorner = { "border-top-left-radius": 0, "border-bottom-left-radius": 0 };
    var roundedLeftCorner = { "border-top-left-radius": "8px", "border-bottom-left-radius": "8px" };
    if (gen <= 2) {
        $("#UU").next("label").css(roundedLeftCorner);
    } else {
            $("#UU").next("label").css(squaredLeftCorner);
            $("#NU").next("label").css(roundedLeftCorner);

            if (gen > 3) {
                $("#NU").next("label").css(squaredLeftCorner);
                $("#LC").next("label").css(roundedLeftCorner);

                if (gen > 4) {
                    $("#LC").next("label").css(squaredLeftCorner);
                    $("#Doubles").next("label").css(roundedLeftCorner);

                    if (gen > 5) {
                        $("#Doubles").next("label").css(squaredLeftCorner);
                    }
                }
            }
    }
}

$(".mode").change(function() {
    if ( $("#one-vs-one").prop("checked") ) {
        window.location.replace( "index.html" );
  } else {
        window.location.replace( "calc_bc.html?mode=" + $(this).attr("id") );
  }
});

$(".tiers label").mouseup(function() {
    var oldID = $('.tiers input:checked').attr("id");
    var newID = $(this).attr("for");
    if ((oldID === "Doubles" || oldID === "VGC14") && (newID !== oldID)) {
        $("#singles-format").attr("disabled", false);
        $("#singles-format").prop("checked", true);
    }
    if ((oldID === "VGC14" || oldID === "LC") && (newID !== "VGC14" && newID !== "LC")) {
        $('.level').val("100");
        $('.level').keyup();
        $('.level').popover({
            content: "Level has been reset to 100",
            placement: "right"
        }).popover('show');
        setTimeout(function(){ $('.level').popover('destroy') }, 3000);
    }
});

$(".tiers input").change(function() {
    var type = $(this).attr("type");
    var id = $(this).attr("id");
    $(".tiers input").not(":" + type).prop("checked", false); // deselect all radios if a checkbox is checked, and vice-versa

    if (gen === 1 && $("#OU").prop("checked")) {
        $("#UU").prop("checked", true);
    }

    if (id === "Doubles" || id === "VGC14") {
        $("#doubles-format").prop("checked", true);
        $("#singles-format").attr("disabled", true);
    }

    if (id === "LC" && $('.level').val() !== "5") {
        $('.level').val("5");
        $('.level').keyup();
        $('.level').popover({
            content: "Level has been set to 5",
            placement: "right"
        }).popover('show');
        setTimeout(function(){ $('.level').popover('destroy') }, 1350);
    }

    if (id === "VGC14" && $('.level').val() !== "50") {
        $('.level').val("50");
        $('.level').keyup();
        $('.level').popover({
            content: "Level has been set to 50",
            placement: "right"
        }).popover('show');
        setTimeout(function(){ $('.level').popover('destroy') }, 1350);
    }
});

$(".set-selector").change(function() {
    var selectedTier = getSelectedTiers()[0];
    if (selectedTier === "LC" && $('.level').val() !== "5") {
        $('.level').val("5");
        $('.level').keyup();
        $('.level').popover({
            content: "Level has been set to 5",
            placement: "right"
        }).popover('show');
        setTimeout(function(){ $('.level').popover('destroy') }, 1350);
    }

    if (selectedTier === "VGC14" && $('.level').val() !== "50") {
        $('.level').val("50");
        $('.level').keyup();
        $('.level').popover({
            content: "Level has been set to 50",
            placement: "right"
        }).popover('show');
        setTimeout(function(){ $('.level').popover('destroy') }, 1350);
    }
});

var table;
function constructDataTable() {
    var dtWidth = $(window).width() - $("#holder-2").offset().left;
    dtWidth -= 2 * parseFloat($(".holder-0").css("padding-right"));
    table = $("#holder-2").DataTable( {
        destroy: true,
        columnDefs: [
            {
                targets: (gen > 2) ? [] : (gen === 2) ? [3] : [3, 4],
                visible: false,
                searchable: false
            }
        ],
        dom: 'C<"clear">frtiS',
        colVis: {
            exclude: (gen > 2) ? [0, 5, 6] : (gen === 2) ? [0, 3, 5, 6] : [0, 3, 4, 5, 6],
            stateChange: function(iColumn, bVisible) {
                var column = table.settings()[0].aoColumns[iColumn];
                if (column.bSearchable !== bVisible) {
                    column.bSearchable = bVisible;
                    table.rows().invalidate();
                }
            }
        },
        scrollX: dtWidth,
        scrollY: dtHeight,
        scrollCollapse: true
    } );
    $(".dataTables_wrapper").width(dtWidth);
}

function getBottomOffset(obj) {
    return obj.offset().top + obj.outerHeight();
}

var mode, dtHeight;
$(document).ready(function() {
    var url = window.location.href;
    mode = url.substring(url.indexOf('=') + 1, url.length);
    $("#" + mode).prop("checked", true);
    $("#holder-2 th:first").text( (mode === "one-vs-all") ? "Defender" : "Attacker" );
    $("#holder-2").show();

    setDTHeight();
    constructDataTable();

    var honkalculator = "<button style='position:absolute' class='bs-btn bs-btn-default'>Honkalculate</button>";
    $("#holder-2_wrapper").prepend(honkalculator);

    var dtHeadTop = $(".sorting").offset().top;
    var dtWrapperToHead = dtHeadTop - $("#holder-2_wrapper").offset().top;
    var fieldsetToDTHead = dtHeadTop - ( $(".holder-0").offset().top + $(".holder-0 .panel-title").outerHeight()/2 );
    var buttonOffset = (dtWrapperToHead - fieldsetToDTHead / 2) - $(".bs-btn").outerHeight()/2;
    $(".bs-btn").css({ "top": buttonOffset });
    $(".bs-btn").click(function() {
        calculate();
    });
});

function setDTHeight() {
    $("#holder-2").DataTable( {
        dom: 'C<"clear">frti'
    });

    var theadBottomOffset = getBottomOffset($(".sorting"));
    var heightUnderDT = getBottomOffset($(".holder-0")) - getBottomOffset($("#holder-2 tbody"));
    dtHeight = $(document).height() - theadBottomOffset - heightUnderDT;
}
<|endoftext|>


<commit_before>$(document).ready(function() {
  var $body = $('body');
  var className = 'dial-congress';
  var senateData;

  var scan = function() {
    console.log('dial-congress scanning...');

    var t0 = performance.now();
    var context = document.body;
    var instance = new Mark(context);
    var i = 0;

    function scanForSenator() {
      var senator = senateData[i];
      var title = '(Senator|((?!([A-Z0-9])).|^)Sen.|Congressman|Congresswoman)\\s*';
      var optionalTitle = '(' + title + ')?';
      var wildCardMiddle = '\\s*?(\'|")?(?:\\w*).?(\'|")?\\s*?';
      var upToTwoWildCardMiddles = '\\s' + wildCardMiddle + wildCardMiddle;
      var firstLast = optionalTitle + senator.firstName + upToTwoWildCardMiddles + senator.lastName;
      var titleLast = title + senator.lastName;
      var lastFirst = senator.lastName + ',\\s*' + senator.firstName;
      var nicknames = '';

      function getNicknameString (nickname, lastName) {
        return '|' + optionalTitle + nickname + upToTwoWildCardMiddles + lastName + '|' + senator.lastName + ',\\s*' + nickname;
      }

      if (senator.nicknames) {
        if (Array.isArray(senator.nicknames)) {
          for (var j = 0; j < senator.nicknames.length; j++) {
            nicknames += getNicknameString(senator.nicknames[j], senator.lastName);
          }
        } else if (typeof senator.nicknames === 'string') {
          nicknames += getNicknameString(senator.nicknames[j], senator.lastName);
        }
      }

      var regExpString = firstLast + '|' + lastFirst + '|' + titleLast + nicknames;
      var regExp = new RegExp(regExpString, 'ig');

      console.log('looking for ' + senator.firstName + ' ' + senator.lastName);

      instance.markRegExp(regExp, {
        element: 'span',
        className: className,
        each: function(el) {
          el.setAttribute('title', senator.party + '/' + senator.state + ': ' + senator.phone);

          $(el).tooltipster({
            interactive: true,
            theme: ['tooltipster-noir', 'tooltipster-noir-customized']
          });
        }
      });

      if (i < senateData.length - 1) {
        i++;
        setTimeout(scanForSenator, 5);
      } else {
        console.log('dial-congress total scan time: ' + (performance.now() - t0));
      }
    }

    scanForSenator();
  }

  $.when(
    $.get(chrome.extension.getURL('js/senate.json'), function(data) {
      senateData = JSON.parse(data);
    })
  ).then(function() {
    scan();
  })
});
<commit_msg>Remove unused jQuery body var<commit_after>$(document).ready(function() {
  var className = 'dial-congress';
  var senateData;

  var scan = function() {
    console.log('dial-congress scanning...');

    var t0 = performance.now();
    var context = document.body;
    var instance = new Mark(context);
    var i = 0;

    function scanForSenator() {
      var senator = senateData[i];
      var title = '(Senator|((?!([A-Z0-9])).|^)Sen.|Congressman|Congresswoman)\\s*';
      var optionalTitle = '(' + title + ')?';
      var wildCardMiddle = '\\s*?(\'|")?(?:\\w*).?(\'|")?\\s*?';
      var upToTwoWildCardMiddles = '\\s' + wildCardMiddle + wildCardMiddle;
      var firstLast = optionalTitle + senator.firstName + upToTwoWildCardMiddles + senator.lastName;
      var titleLast = title + senator.lastName;
      var lastFirst = senator.lastName + ',\\s*' + senator.firstName;
      var nicknames = '';

      function getNicknameString (nickname, lastName) {
        return '|' + optionalTitle + nickname + upToTwoWildCardMiddles + lastName + '|' + senator.lastName + ',\\s*' + nickname;
      }

      if (senator.nicknames) {
        if (Array.isArray(senator.nicknames)) {
          for (var j = 0; j < senator.nicknames.length; j++) {
            nicknames += getNicknameString(senator.nicknames[j], senator.lastName);
          }
        } else if (typeof senator.nicknames === 'string') {
          nicknames += getNicknameString(senator.nicknames[j], senator.lastName);
        }
      }

      var regExpString = firstLast + '|' + lastFirst + '|' + titleLast + nicknames;
      var regExp = new RegExp(regExpString, 'ig');

      console.log('looking for ' + senator.firstName + ' ' + senator.lastName);

      instance.markRegExp(regExp, {
        element: 'span',
        className: className,
        each: function(el) {
          el.setAttribute('title', senator.party + '/' + senator.state + ': ' + senator.phone);

          $(el).tooltipster({
            interactive: true,
            theme: ['tooltipster-noir', 'tooltipster-noir-customized']
          });
        }
      });

      if (i < senateData.length - 1) {
        i++;
        setTimeout(scanForSenator, 5);
      } else {
        console.log('dial-congress total scan time: ' + (performance.now() - t0));
      }
    }

    scanForSenator();
  }

  $.when(
    $.get(chrome.extension.getURL('js/senate.json'), function(data) {
      senateData = JSON.parse(data);
    })
  ).then(function() {
    scan();
  })
});
<|endoftext|>


<commit_before>var currentModule = 0;
var tickerSeconds = 0;
var loadNextModule = false;
var modifiedDuration = -1;
var entries = new Array();
var loadedScripts = new Array();

$(document).ready(function() {

    $.getJSON( "datafeeds/getModules.php", function( data ) {
        $.each( data, function( key, entry ) {
            entries.push(entry);
        });
        entries.sort(compareEntries);

        buildMenuEntries();
        updateActiveMenuTab();
        updateContentBlock(entries[0]);
        updateDisplayInfo(entries[currentModule]);
        loadScripts();
        updateLoop(); // Start update loop

    });

    $(".cube").css({
        "-webkit-transform": "translateZ(-"+(window.innerWidth-10)/2+"px)"
    })
    updateCubeBounds();
});

/* Comparable for sorting entries after priority order */
function compareEntries(a, b) {
    if (a.order > b.order)
        return -1;
    if (a.order  0 ? modifiedDuration : entries[currentModule].airTime);

    if((tickerSeconds >= tickerMaxCount || loadNextModule == true) && entries.length > 1) {
        currentModule += 1;         // GoTo next module
        if(currentModule >= entries.length) {
            currentModule = 0;
        }

        updateContentBlock(entries[currentModule]);  // Load module, entry
        updateDisplayInfo(entries[currentModule]);
        updateActiveMenuTab();

        cubeRotateTo(currentModule % 4);

        tickerSeconds = 0;          // Reset ticker
        modifiedDuration = -1;
        loadNextModule = false;
    }

    tickerSeconds+=1;
    // Infinite loop
    setTimeout('updateLoop()', 1000);
}

function updateContentBlock(entry) {
    var pluginUrl = "modules/"+entry.folder;
    var currentBox;
    var currentSlide;
    switch (currentModule % 4) {
        case 0:
            currentBox = '.contentBox';
            currentSlide = '.front-pane';
            break;
        case 1:
            currentBox = '.contentBoxTwo';
            currentSlide = '.right-pane';
            break;
        case 2:
            currentBox = '.contentBoxThree';
            currentSlide = '.back-pane';
            break;
        case 3:
            currentBox = '.contentBoxFour';
            currentSlide = '.left-pane';
            break;
    }

    fadeAll();
    $(currentBox).fadeOut(300, function() {
        $(currentSlide).fadeIn();
        $(currentBox).load(pluginUrl, function() {
            $(currentBox).fadeIn();
            if(entry.scripts != null) {
                manageScripts(entry);
            }
        });
    });
}

function fadeAll() {
    var panes = ['.front-pane', '.right-pane', '.back-pane', '.right-pane'];
    $.each(panes, function(key, value) {
       $(value).fadeOut(1000);
    });
}

function loadScripts() {
    $.each(entries, function(key, entry) {
        var pluginUrl = "modules/"+entry.folder;
        if(entry.scripts != null) {
            $.each(entry.scripts, function(k, script) {
                $.getScript(pluginUrl+ "/" + script);
            });
        }
    });
}

function updateActiveMenuTab() {
    $(".navigation li").each(function(index) {
        $( this ).removeClass("selected");
        if(currentModule == index) {
            $( this ).addClass("selected");
        }
    });
}

function buildMenuEntries() {
    $.each(entries, function(key, entry) {
        $("ul.navigation").append("
" + entry.name +"
");
    });
}

function updateDisplayInfo(entry) {
    /*
    * Requires default options.
    **/

    if(entry.screenSettings.showHeader) {
        $(".heading").slideDown();
    }

    if(!entry.screenSettings.showHeader) {
        $(".heading").slideUp();
    }
}

function manageScripts(entry) {
    $.each(loadedScripts, function(key, value) {
        if(value.folder != entry.folder) {
            value.obj.stop();
            console.log("Stopping: " + value.folder);
        }
    });

    $.each(loadedScripts, function(key, value) {
        if(value.folder == entry.folder) {
            value.obj.start();
            console.log("Starting: " + value.folder);
        }
    });
}

function gotoNextModule() {
    loadNextModule = true;
}

function updateDuration(duration) {
    modifiedDuration = duration;
}

window.addListner = function(ref, folder) {
    loadedScripts.push({"obj": ref, "folder":folder});
}

$( window ).resize(function() {
    updateCubeBounds();
});

var halfWidth = 0;
function cubeRotateTo(side) {
    var cubeRotY = 0;
    if(side == 0) {
        cubeRotY = 0;
    } else if(side == 1) {
        cubeRotY = -90;
    } else if(side == 2) {
        cubeRotY = -180;
    } else if(side == 3) {
        cubeRotY = -270;
    }
    $(".cube").css({
        "-webkit-transform": "translateZ(-"+halfWidth+"px) rotateY("+cubeRotY+"deg)"
    });
}

function updateCubeBounds() {
    var headerHight = 150;
    var footerHight = 0;

    var width = window.innerWidth - 10;
    halfWidth = width / 2;
    var height = window.innerHeight;

    $(".cube").css({
        "width": width
    });
    $(".cube div").css({
        "width": width,
        "height": (height - headerHight - footerHight)
    });
    $(".depth div.back-pane").css({
        "-webkit-transform": "translateZ(-"+halfWidth+"px) rotateY(180deg)",
        "-moz-transform" : "translateZ(-"+halfWidth+"px) rotateY(180deg)",
        "-ms-transform" : "translateZ(-"+halfWidth+"px) rotateY(180deg)",
        "transform" : "translateZ(-"+halfWidth+"px) rotateY(180deg)"
    });

    $(".depth div.front-pane").css({
        "-webkit-transform": "translateZ("+halfWidth+"px) rotateY(0deg)",
        "-moz-transform" : "translateZ("+halfWidth+"px) rotateY(0deg)",
        "-ms-transform" : "translateZ("+halfWidth+"px) rotateY(0deg)",
        "transform" : "translateZ("+halfWidth+"px) rotateY(0deg)"
    });

    $(".depth div.right-pane").css({
        "-webkit-transform": "rotateY(-270deg) translateX("+halfWidth+"px)",
        "-webkit-transform-origin" : "top right",

        "-moz-transform" : "rotateY(-270deg) translateX("+halfWidth+"px)",
        "-moz-transform-origin" : "top right",

        "-ms-transform" : "rotateY(-270deg) translateX("+halfWidth+"px)",
        "-ms-transform-origin" : "top right",

        "transform" : "rotateY(-270deg) translateX("+halfWidth+"px)",
        "transform-origin" : "top right"
    });

    $(".depth div.left-pane").css({
        "-webkit-transform": "rotateY(270deg) translateX(-"+halfWidth+"px)",
        "-webkit-transform-origin" : " center left",

        "-moz-transform" : "rotateY(270deg) translateX(-"+halfWidth+"px)",
        "-moz-transform-origin" : "center left",

        "-ms-transform" : "rotateY(270deg) translateX(-"+halfWidth+"px)",
        "-ms-transform-origin" : "center left",

        "transform" : "rotateY(270deg) translateX(-"+halfWidth+"px)",
        "transform-origin" : "center left"
    });

}<commit_msg>Bug fix, all slides are now faded<commit_after>var currentModule = 0;
var tickerSeconds = 0;
var loadNextModule = false;
var modifiedDuration = -1;
var entries = new Array();
var loadedScripts = new Array();

$(document).ready(function() {

    $.getJSON( "datafeeds/getModules.php", function( data ) {
        $.each( data, function( key, entry ) {
            entries.push(entry);
        });
        entries.sort(compareEntries);

        buildMenuEntries();
        updateActiveMenuTab();
        updateContentBlock(entries[0]);
        updateDisplayInfo(entries[currentModule]);
        loadScripts();
        updateLoop(); // Start update loop

    });

    $(".cube").css({
        "-webkit-transform": "translateZ(-"+(window.innerWidth-10)/2+"px)"
    })
    updateCubeBounds();
});

/* Comparable for sorting entries after priority order */
function compareEntries(a, b) {
    if (a.order > b.order)
        return -1;
    if (a.order  0 ? modifiedDuration : entries[currentModule].airTime);

    if((tickerSeconds >= tickerMaxCount || loadNextModule == true) && entries.length > 1) {
        currentModule += 1;         // GoTo next module
        if(currentModule >= entries.length) {
            currentModule = 0;
        }

        updateContentBlock(entries[currentModule]);  // Load module, entry
        updateDisplayInfo(entries[currentModule]);
        updateActiveMenuTab();

        cubeRotateTo(currentModule % 4);

        tickerSeconds = 0;          // Reset ticker
        modifiedDuration = -1;
        loadNextModule = false;
    }

    tickerSeconds+=1;
    // Infinite loop
    setTimeout('updateLoop()', 1000);
}

function updateContentBlock(entry) {
    var pluginUrl = "modules/"+entry.folder;
    var currentBox;
    var currentSlide;
    switch (currentModule % 4) {
        case 0:
            currentBox = '.contentBox';
            currentSlide = '.front-pane';
            break;
        case 1:
            currentBox = '.contentBoxTwo';
            currentSlide = '.right-pane';
            break;
        case 2:
            currentBox = '.contentBoxThree';
            currentSlide = '.back-pane';
            break;
        case 3:
            currentBox = '.contentBoxFour';
            currentSlide = '.left-pane';
            break;
    }

    fadeAll();
    $(currentBox).fadeOut(300, function() {
        $(currentSlide).fadeIn();
        $(currentBox).load(pluginUrl, function() {
            $(currentBox).fadeIn();
            if(entry.scripts != null) {
                manageScripts(entry);
            }
        });
    });
}

function fadeAll() {
    var panes = ['.front-pane', '.right-pane', '.back-pane', '.left-pane'];
    $.each(panes, function(key, value) {
       $(value).fadeOut(1000);
    });
}

function loadScripts() {
    $.each(entries, function(key, entry) {
        var pluginUrl = "modules/"+entry.folder;
        if(entry.scripts != null) {
            $.each(entry.scripts, function(k, script) {
                $.getScript(pluginUrl+ "/" + script);
            });
        }
    });
}

function updateActiveMenuTab() {
    $(".navigation li").each(function(index) {
        $( this ).removeClass("selected");
        if(currentModule == index) {
            $( this ).addClass("selected");
        }
    });
}

function buildMenuEntries() {
    $.each(entries, function(key, entry) {
        $("ul.navigation").append("
" + entry.name +"
");
    });
}

function updateDisplayInfo(entry) {
    /*
    * Requires default options.
    **/

    if(entry.screenSettings.showHeader) {
        $(".heading").slideDown();
    }

    if(!entry.screenSettings.showHeader) {
        $(".heading").slideUp();
    }
}

function manageScripts(entry) {
    $.each(loadedScripts, function(key, value) {
        if(value.folder != entry.folder) {
            value.obj.stop();
            console.log("Stopping: " + value.folder);
        }
    });

    $.each(loadedScripts, function(key, value) {
        if(value.folder == entry.folder) {
            value.obj.start();
            console.log("Starting: " + value.folder);
        }
    });
}

function gotoNextModule() {
    loadNextModule = true;
}

function updateDuration(duration) {
    modifiedDuration = duration;
}

window.addListner = function(ref, folder) {
    loadedScripts.push({"obj": ref, "folder":folder});
}

$( window ).resize(function() {
    updateCubeBounds();
});

var halfWidth = 0;
function cubeRotateTo(side) {
    var cubeRotY = 0;
    if(side == 0) {
        cubeRotY = 0;
    } else if(side == 1) {
        cubeRotY = -90;
    } else if(side == 2) {
        cubeRotY = -180;
    } else if(side == 3) {
        cubeRotY = -270;
    }
    $(".cube").css({
        "-webkit-transform": "translateZ(-"+halfWidth+"px) rotateY("+cubeRotY+"deg)"
    });
}

function updateCubeBounds() {
    var headerHight = 150;
    var footerHight = 0;

    var width = window.innerWidth - 10;
    halfWidth = width / 2;
    var height = window.innerHeight;

    $(".cube").css({
        "width": width
    });
    $(".cube div").css({
        "width": width,
        "height": (height - headerHight - footerHight)
    });
    $(".depth div.back-pane").css({
        "-webkit-transform": "translateZ(-"+halfWidth+"px) rotateY(180deg)",
        "-moz-transform" : "translateZ(-"+halfWidth+"px) rotateY(180deg)",
        "-ms-transform" : "translateZ(-"+halfWidth+"px) rotateY(180deg)",
        "transform" : "translateZ(-"+halfWidth+"px) rotateY(180deg)"
    });

    $(".depth div.front-pane").css({
        "-webkit-transform": "translateZ("+halfWidth+"px) rotateY(0deg)",
        "-moz-transform" : "translateZ("+halfWidth+"px) rotateY(0deg)",
        "-ms-transform" : "translateZ("+halfWidth+"px) rotateY(0deg)",
        "transform" : "translateZ("+halfWidth+"px) rotateY(0deg)"
    });

    $(".depth div.right-pane").css({
        "-webkit-transform": "rotateY(-270deg) translateX("+halfWidth+"px)",
        "-webkit-transform-origin" : "top right",

        "-moz-transform" : "rotateY(-270deg) translateX("+halfWidth+"px)",
        "-moz-transform-origin" : "top right",

        "-ms-transform" : "rotateY(-270deg) translateX("+halfWidth+"px)",
        "-ms-transform-origin" : "top right",

        "transform" : "rotateY(-270deg) translateX("+halfWidth+"px)",
        "transform-origin" : "top right"
    });

    $(".depth div.left-pane").css({
        "-webkit-transform": "rotateY(270deg) translateX(-"+halfWidth+"px)",
        "-webkit-transform-origin" : " center left",

        "-moz-transform" : "rotateY(270deg) translateX(-"+halfWidth+"px)",
        "-moz-transform-origin" : "center left",

        "-ms-transform" : "rotateY(270deg) translateX(-"+halfWidth+"px)",
        "-ms-transform-origin" : "center left",

        "transform" : "rotateY(270deg) translateX(-"+halfWidth+"px)",
        "transform-origin" : "center left"
    });

}<|endoftext|>


<commit_before>// Read the CodeMirror from the page and send it to the pageAction
chrome.runtime.onMessage.addListener(
	function(request, sender, sendResponse) {
		if (request.action == "request-widget-html") {

			var block = document.querySelectorAll('CodeMirror pre'),
					content = '';

			[].forEach.call(document.querySelectorAll('.CodeMirror pre'), function(item) {
				content += item.textContent + "\n";
			});

			sendResponse({html: content});
		}
	});
<commit_msg>:fire: remove obsolete code<commit_after>// Read the CodeMirror from the page and send it to the pageAction
chrome.runtime.onMessage.addListener(
	function(request, sender, sendResponse) {
		if (request.action == "request-widget-html") {

			var content = '';

			[].forEach.call(document.querySelectorAll('.CodeMirror pre'), function(item) {
				content += item.textContent + "\n";
			});

			sendResponse({html: content});
		}
	});
<|endoftext|>


<commit_before>'use strict';

/**
 * Implements decode methods for dpt types
 */
function Decoder() {
}

/**
 * decode eis 8 / dpt 2 values
 */
Decoder.prototype.decodeDPT2 = function (buffer) {
    return buffer.readUInt8(0) & 0x3;
};

/**
 * decode eis 2 / dpt 3 values
 */
Decoder.prototype.decodeDPT3 = function (buffer) {
    return buffer.readUInt8(0) & 0xf;
};

/**
 * decode eis 13 / dpt 4 values
 */
Decoder.prototype.decodeDPT4 = function (buffer) {
    let value = buffer.readUInt8(0);
    if (value <= 127) {
        value = buffer.toString('ascii', 0);
    } else {
        value = buffer.toString('utf8', 0);
    }
    return value;
};

/**
 * decode eis 14 / dpt 5 values
 */
Decoder.prototype.decodeDPT5 = function (buffer) {
    return buffer.readUInt8(0);
};

/**
 * decode eis 14 / dpt 6 values
 */
Decoder.prototype.decodeDPT6 = function (buffer) {
    return buffer.readInt8(0);
};

/**
 * decode EIS 10 / dpt 7 values
 */
Decoder.prototype.decodeDPT7 = function (buffer) {
    return buffer.readUInt16BE(0);
};

/**
 * decode EIS 10.001 / dpt 8 values
 */
Decoder.prototype.decodeDPT8 = function (buffer) {
    return buffer.readInt16BE(0);
};

/**
 * decode eis 5 / dpt 9 values
 */
Decoder.prototype.decodeDPT9 = function (buffer) {
    let value = buffer.readUInt16BE(0);

    const sign = (value & 0x8000) >> 15;
    const exp = (value & 0x7800) >> 11;
    let mant = (value & 0x07ff);

    if (sign !== 0) {
        mant = -(~(mant - 1) & 0x07ff);
    }
    value = (1 << exp) * 0.01 * mant;
    return value;
};

/**
 * decode eis 3 / dpt 10 values
 */
Decoder.prototype.decodeDPT10 = function (buffer) {

    const value = new Date();

    const weekDay = (buffer[0] & 0xe0) >> 5;
    const hour = buffer[0] & 0x1f;
    const min = buffer[1] & 0x3f;
    const sec = buffer[2] & 0x3f;

    value.setHours(hour);
    value.setMinutes(min);
    value.setSeconds(sec);
    const currentDay = value.getDay();
    if (weekDay == 0) {
        // no change
    } else if (currentDay == weekDay) {
        // weekday fits
        if (value < Date.now()) {
            // same weekday but earlier time => date must be one week later
            value.setDate(value.getDate() + 7);
        }
    } else {
        // wrong weekday
        if (currentDay < weekDay) {
            // later weekday
            value.setDate(value.getDate() - currentDay + weekDay);
        } else {
            // earlier weekday => weekday one week later
            value.setDate(value.getDate() - currentDay + weekDay + 7);
        }
    }
    return value.toUTCString();
};

/**
 * decode eis 4 / dpt 11 values
 */
Decoder.prototype.decodeDPT11 = function (buffer) {

    const day = buffer[0] & 0x1f;
    const mon = buffer[1] & 0xf - 1; // month 0...11
    let year = buffer[2] & 0x7f;

    if (year < 90) {
        year += 2000;
    } else {
        year += 1900;
    }

    return new Date(year, mon, day).toUTCString();
};

/**
 * decode eis 11 / dpt 12 values
 */
Decoder.prototype.decodeDPT12 = function (buffer) {
    return buffer.readUInt32BE(0);
};

/**
 * decode eis 11.001 / dpt 13 values
 */
Decoder.prototype.decodeDPT13 = function (buffer) {
    return buffer.readInt32BE(0);
};

/**
 * decode eis 9 / dpt 14 values
 */
Decoder.prototype.decodeDPT14 = function (buffer) {
    return buffer.readFloatBE(0);
};

Decoder.prototype.decodeDPT16 = function (buffer) {
    let value = '';
    for (let i = 0; i < buffer.length; i++) {
        value += String.fromCharCode(buffer.readUInt8(i));
    }
    return value;
};

/**
 * decode value
 */
Decoder.prototype.decode = function (len, data, callback) {

    let err = null;
    let type = 'DPT1';
    let value = null;

    // eis 1 / dpt 1.xxx
    if (len === 8) {
        value = data - 64;
        if (value > 1) {
            value = value - 64;
        }
    }

    // eis 6 / dpt 5.xxx
    // assumption
    if (len === 9) {
        type = 'DPT5';
        if (data.length === 1) {
            value = this.decodeDPT5(data);
        } else {
            err = new Error('Invalid data len for DPT5');
        }
    }

    // eis 5 / dpt 9.xxx
    // assumption
    if (len === 10) {
        type = 'DPT9';
        if (data.length === 2) {
            value = this.decodeDPT9(data);
        }
        else {
            err = new Error('Invalid data len for DPT9');
        }
    }

    if (callback) {
        callback(err, type, value);
    }
};

module.exports = Decoder;
<commit_msg>corrected calculation order for month<commit_after>'use strict';

/**
 * Implements decode methods for dpt types
 */
function Decoder() {
}

/**
 * decode eis 8 / dpt 2 values
 */
Decoder.prototype.decodeDPT2 = function (buffer) {
    return buffer.readUInt8(0) & 0x3;
};

/**
 * decode eis 2 / dpt 3 values
 */
Decoder.prototype.decodeDPT3 = function (buffer) {
    return buffer.readUInt8(0) & 0xf;
};

/**
 * decode eis 13 / dpt 4 values
 */
Decoder.prototype.decodeDPT4 = function (buffer) {
    let value = buffer.readUInt8(0);
    if (value <= 127) {
        value = buffer.toString('ascii', 0);
    } else {
        value = buffer.toString('utf8', 0);
    }
    return value;
};

/**
 * decode eis 14 / dpt 5 values
 */
Decoder.prototype.decodeDPT5 = function (buffer) {
    return buffer.readUInt8(0);
};

/**
 * decode eis 14 / dpt 6 values
 */
Decoder.prototype.decodeDPT6 = function (buffer) {
    return buffer.readInt8(0);
};

/**
 * decode EIS 10 / dpt 7 values
 */
Decoder.prototype.decodeDPT7 = function (buffer) {
    return buffer.readUInt16BE(0);
};

/**
 * decode EIS 10.001 / dpt 8 values
 */
Decoder.prototype.decodeDPT8 = function (buffer) {
    return buffer.readInt16BE(0);
};

/**
 * decode eis 5 / dpt 9 values
 */
Decoder.prototype.decodeDPT9 = function (buffer) {
    let value = buffer.readUInt16BE(0);

    const sign = (value & 0x8000) >> 15;
    const exp = (value & 0x7800) >> 11;
    let mant = (value & 0x07ff);

    if (sign !== 0) {
        mant = -(~(mant - 1) & 0x07ff);
    }
    value = (1 << exp) * 0.01 * mant;
    return value;
};

/**
 * decode eis 3 / dpt 10 values
 */
Decoder.prototype.decodeDPT10 = function (buffer) {

    const value = new Date();

    const weekDay = (buffer[0] & 0xe0) >> 5;
    const hour = buffer[0] & 0x1f;
    const min = buffer[1] & 0x3f;
    const sec = buffer[2] & 0x3f;

    value.setHours(hour);
    value.setMinutes(min);
    value.setSeconds(sec);
    const currentDay = value.getDay();
    if (weekDay == 0) {
        // no change
    } else if (currentDay == weekDay) {
        // weekday fits
        if (value < Date.now()) {
            // same weekday but earlier time => date must be one week later
            value.setDate(value.getDate() + 7);
        }
    } else {
        // wrong weekday
        if (currentDay < weekDay) {
            // later weekday
            value.setDate(value.getDate() - currentDay + weekDay);
        } else {
            // earlier weekday => weekday one week later
            value.setDate(value.getDate() - currentDay + weekDay + 7);
        }
    }
    return value.toUTCString();
};

/**
 * decode eis 4 / dpt 11 values
 */
Decoder.prototype.decodeDPT11 = function (buffer) {

    const day = buffer[0] & 0x1f;
    const mon = (buffer[1] & 0xf) - 1; // month 0...11
    let year = buffer[2] & 0x7f;

    if (year < 90) {
        year += 2000;
    } else {
        year += 1900;
    }

    return new Date(year, mon, day).toUTCString();
};

/**
 * decode eis 11 / dpt 12 values
 */
Decoder.prototype.decodeDPT12 = function (buffer) {
    return buffer.readUInt32BE(0);
};

/**
 * decode eis 11.001 / dpt 13 values
 */
Decoder.prototype.decodeDPT13 = function (buffer) {
    return buffer.readInt32BE(0);
};

/**
 * decode eis 9 / dpt 14 values
 */
Decoder.prototype.decodeDPT14 = function (buffer) {
    return buffer.readFloatBE(0);
};

Decoder.prototype.decodeDPT16 = function (buffer) {
    let value = '';
    for (let i = 0; i < buffer.length; i++) {
        value += String.fromCharCode(buffer.readUInt8(i));
    }
    return value;
};

/**
 * decode value
 */
Decoder.prototype.decode = function (len, data, callback) {

    let err = null;
    let type = 'DPT1';
    let value = null;

    // eis 1 / dpt 1.xxx
    if (len === 8) {
        value = data - 64;
        if (value > 1) {
            value = value - 64;
        }
    }

    // eis 6 / dpt 5.xxx
    // assumption
    if (len === 9) {
        type = 'DPT5';
        if (data.length === 1) {
            value = this.decodeDPT5(data);
        } else {
            err = new Error('Invalid data len for DPT5');
        }
    }

    // eis 5 / dpt 9.xxx
    // assumption
    if (len === 10) {
        type = 'DPT9';
        if (data.length === 2) {
            value = this.decodeDPT9(data);
        }
        else {
            err = new Error('Invalid data len for DPT9');
        }
    }

    if (callback) {
        callback(err, type, value);
    }
};

module.exports = Decoder;
<|endoftext|>


<commit_before>(function($){

	if(typeof(window.EMMA) === 'undefined') {
            window.EMMA = {};
    }

    EMMA.sliderTimer = null;
    EMMA.logoSliderTimer = null;

// Fix Placeholder
function fixPlaceholder() {
	jQuery.support.placeholder = false;
	var test = document.createElement('input');
	if('placeholder' in test) jQuery.support.placeholder = true;
	if(!$.support.placeholder) {
		var active = document.activeElement;
		$('input,textarea').focus(function () {
			if ($(this).attr('placeholder') != '' && $(this).val() == $(this).attr('placeholder')) {
				$(this).val('').removeClass('hasPlaceholder');
			}
		}).blur(function () {
			if ($(this).attr('placeholder') != '' && ($(this).val() == '' || $(this).val() == $(this).attr('placeholder'))) {
				$(this).val($(this).attr('placeholder')).addClass('hasPlaceholder');
			}
		});
		$('input,textarea').blur();
		$(active).focus();
		$('form').submit(function () { $(this).find('.hasPlaceholder').each(function() { $(this).val(''); }); });
	}
}

// Slider
function initSlider() {
	// Main Slider
	sliderFunction('.slidecontrol','slidecontainer','slide',638,8000);
	// Logoslider
	sliderFunction('#logoslidecontrols','logoslidercontainer','logoslide',960,16000);
}
function sliderFunction(controls,container,slide,width,interval) {

	$(controls+' div').click(function() {
		if ($(this).hasClass('prev')) {
			$('#'+container+' .'+slide+':last').detach().prependTo('#'+container);
			$('#'+container).animate({marginLeft: '-='+width+'px'},0);
			$('#'+container).animate({marginLeft: '+='+width+'px'},1000);
		} else {
			$('#'+container).animate({marginLeft: '-='+width+'px'},1000,function() {
				$('#'+container+' .'+slide+':first').detach().appendTo('#'+container);
				$('#'+container).animate({marginLeft: '+='+width+'px'},0);
			});
		}
	});

    // mouseover to stop sliding
    $('div#slider').mouseover(function(){
        clearInterval(EMMA.sliderTimer); // stops interval, ie, turn off sliding
    }).mouseout(function(){
        autoSlider('.slidecontrol','slidecontainer','slide',638, interval);
    });

    $('div#logoslider').mouseover(function(){
        clearInterval(EMMA.logoSliderTimer); // stops interval, ie, turn off sliding
    }).mouseout(function(){
        autoSlider('#logoslidecontrols','logoslidercontainer','logoslide',960, interval);
    });

    // auto slide in defined time interval for both slides and logos
    if ( slide == 'slide' ){
        autoSlider('.slidecontrol','slidecontainer','slide',638, interval);
    }
    else {
        autoSlider('#logoslidecontrols','logoslidercontainer','logoslide',960, interval);
    }
}
function autoSlider(controls,container,slide,width,interval){

    if (slide == 'slide' ){
        if(EMMA.sliderTimer){
            clearInterval(EMMA.sliderTimer);
        }
        EMMA.sliderTimer = setInterval(function() {
            $('#'+container).animate({marginLeft: '-='+width+'px'},1000,function() {
		        $('#'+container+' .'+slide+':first').detach().appendTo('#'+container);
		        $('#'+container).animate({marginLeft: '+='+width+'px'},0);
	        });
        }, interval);
    }
    else {
        if(EMMA.logoSliderTimer){
            clearInterval(EMMA.logoSliderTimer);
        }
        EMMA.logoSliderTimer = setInterval(function() {
            $('#'+container).animate({marginLeft: '-='+width+'px'},1000,function() {
		        $('#'+container+' .'+slide+':first').detach().appendTo('#'+container);
		        $('#'+container).animate({marginLeft: '+='+width+'px'},0);
	        });
        }, interval);
    }
}

// Sidenavi
function initSideNavi() {
	if (!$('html').hasClass('ie7')) {
		// Helper for sidenavi rollover
		$('#block-menu-block-2 .expanded > a').each(function() { $(this).prepend('

'); });
		$('.helpclicker').live('click',function(e) {
			e.preventDefault();
			$(this).closest('li').toggleClass('active-trail');
		});
		$('.helpclicker').live('mouseover mouseout',function(e) { $(this).closest('li').toggleClass('over'); });
		// Helper for toggling content elements
		$('.togglehead .helper').live('mouseover mouseout',function(e) { $(this).closest('.togglehead').toggleClass('over'); });
	}
}

// various actions
function initActions() {
	// Toggle help box on frontpage
	$('#togglehelp').click(function() { $('#stooltip').toggle(); });
	// Animated Scrolling to top
	$("#toplink").click(function(e){ e.preventDefault(); $('html,body').animate({scrollTop:0}, 1500); });
	// Kill .error when focusing a input field
	$('.error input').live('focus',function() {
		$(this).closest('.form-item').removeClass('error');
	});
}

// Tabcontent
function initTabContent() {
	if ($('.field-collection-item-field-tab').length > 0) {
		var container = $('.field-collection-item-field-tab').eq(0);
		$(container).before('

');
		$('.field-collection-item-field-tab').each(function() {
			var title = $('.title',this).text();
			$('#tabs ul').append('
'+title+'
');
			$('.title',this).remove();
		});
		$('#tabs a').live('click',function(e) {
			e.preventDefault();
			var index = $(this).index('#tabs a');
			$('#tabs a').removeClass('active');
			$(this).addClass('active');
			$('.field-collection-item-field-tab').hide();
			$('.field-collection-item-field-tab').eq(index).show();
		});
		$('#tabs a:first').trigger('click');
	}
}

// Togglebox
function initToggleContent() {
	$('.togglehead').live('click',function(e) {
		$(this).closest('.toggle').toggleClass('active');
		$(this).next('.togglecontent').toggle('fast');
	});
}

// Autoheight of boxes
function autoHeightFront() {
	var aboutHeight = $('#box-abouttext .boxcontent').innerHeight();
	var smallHeight = (aboutHeight - 105) / 2;
	$('#box-partnership .boxcontent').css('min-height',smallHeight+'px')
}

// Content margin, when no special Boxes inside the main node
function initContentMargin() {
	var headBox   = $('#block-system-main .node:first .head').length;
	var innerBoxes = $('#block-system-main .innerbox').length;
	var teaserBox = $('.view-subpages-teaser').length;
	if (teaserBox == 1 && innerBoxes == 0 && headBox == 0) {
		$('#block-system-main').addClass('margbottom');
	}
}

// span Tooltips
function initTooltips() {
	$('.tooltip').live('mouseenter',function(e) {
		var offset = $(this).offset();
		var spanwidth = $(this).width();
		$('body').append('
'+$(this).attr('data-tooltip')+'

');
		var w = $('#tip').width();
		var h = $('#tip').height();
		$('#tip').css({top: (offset.top-h-30)+'px',left: (offset.left+(spanwidth/2)-(w/2))+'px'});
		$('#tip .bubble').css({marginLeft: w/2-5+'px'});
	});
	$('.tooltip').live('mouseleave',function() { $('#tip').remove(); });
}

// Parse Contents to improve user experience
function parseContent() {
	// Check if tables in the content have a thead
	$('.region-content table').each(function() {
		if ($('thead',this).length == 0) { $(this).addClass('nothead');	}
	});
	// Count toggleboxes
	$('.toggle:first').addClass('first');
	$('.toggle:last').addClass('last');
}

function customiseReadMoreText(){

	// hacking 'Read more' text for some pages
	var readMores = {
		'biomart': {
			'path': '/resources-and-services/access-emma-mouse-resources',
			'url': 'https://www.emmanet.org/biomart/martview/',
			'label': 'Search EMMA Biomart',
			'title': 'Advanced BioMart search'
		},
		'submission': {
			'path': '/resources-and-services/deposit-mice-emma-repository',
			'url': '/emma/publicSubmission/submissionForm.emma',
			'label': 'Submit mice to EMMA',
			'title': 'Submission form'
		}
	};
	for ( var i in readMores ){
		if ( window.location.pathname == readMores[i].path ){
		    $('div.view-content div h3').find('a').each(function(){
		        if ( $(this).text() == readMores[i].title ){
		            //resources-and-services/access-emma-mouse-resources/advanced-biomart-search
		            var url = readMores[i].url;
		            $(this).attr('href', url);
		            $(this).parent().siblings('p.more').find('a').text(readMores[i].label).attr('href', url);
		       }
		    });
		}
	}
}

$(document).ready(function() {

	initTabContent();
	initToggleContent();
	initSideNavi();
	initContentMargin();
	initSlider();
	initActions();
	initTooltips();
	parseContent();
	fixPlaceholder();
	customiseReadMoreText();

	if ($('body').hasClass('front')) { autoHeightFront(); }

});

})(jQuery);
jQuery.noConflict();
<commit_msg>added meeting tool url hack<commit_after>(function($){

	if(typeof(window.EMMA) === 'undefined') {
            window.EMMA = {};
    }

    EMMA.sliderTimer = null;
    EMMA.logoSliderTimer = null;

// Fix Placeholder
function fixPlaceholder() {
	jQuery.support.placeholder = false;
	var test = document.createElement('input');
	if('placeholder' in test) jQuery.support.placeholder = true;
	if(!$.support.placeholder) {
		var active = document.activeElement;
		$('input,textarea').focus(function () {
			if ($(this).attr('placeholder') != '' && $(this).val() == $(this).attr('placeholder')) {
				$(this).val('').removeClass('hasPlaceholder');
			}
		}).blur(function () {
			if ($(this).attr('placeholder') != '' && ($(this).val() == '' || $(this).val() == $(this).attr('placeholder'))) {
				$(this).val($(this).attr('placeholder')).addClass('hasPlaceholder');
			}
		});
		$('input,textarea').blur();
		$(active).focus();
		$('form').submit(function () { $(this).find('.hasPlaceholder').each(function() { $(this).val(''); }); });
	}
}

// Slider
function initSlider() {
	// Main Slider
	sliderFunction('.slidecontrol','slidecontainer','slide',638,8000);
	// Logoslider
	sliderFunction('#logoslidecontrols','logoslidercontainer','logoslide',960,16000);
}
function sliderFunction(controls,container,slide,width,interval) {

	$(controls+' div').click(function() {
		if ($(this).hasClass('prev')) {
			$('#'+container+' .'+slide+':last').detach().prependTo('#'+container);
			$('#'+container).animate({marginLeft: '-='+width+'px'},0);
			$('#'+container).animate({marginLeft: '+='+width+'px'},1000);
		} else {
			$('#'+container).animate({marginLeft: '-='+width+'px'},1000,function() {
				$('#'+container+' .'+slide+':first').detach().appendTo('#'+container);
				$('#'+container).animate({marginLeft: '+='+width+'px'},0);
			});
		}
	});

    // mouseover to stop sliding
    $('div#slider').mouseover(function(){
        clearInterval(EMMA.sliderTimer); // stops interval, ie, turn off sliding
    }).mouseout(function(){
        autoSlider('.slidecontrol','slidecontainer','slide',638, interval);
    });

    $('div#logoslider').mouseover(function(){
        clearInterval(EMMA.logoSliderTimer); // stops interval, ie, turn off sliding
    }).mouseout(function(){
        autoSlider('#logoslidecontrols','logoslidercontainer','logoslide',960, interval);
    });

    // auto slide in defined time interval for both slides and logos
    if ( slide == 'slide' ){
        autoSlider('.slidecontrol','slidecontainer','slide',638, interval);
    }
    else {
        autoSlider('#logoslidecontrols','logoslidercontainer','logoslide',960, interval);
    }
}
function autoSlider(controls,container,slide,width,interval){

    if (slide == 'slide' ){
        if(EMMA.sliderTimer){
            clearInterval(EMMA.sliderTimer);
        }
        EMMA.sliderTimer = setInterval(function() {
            $('#'+container).animate({marginLeft: '-='+width+'px'},1000,function() {
		        $('#'+container+' .'+slide+':first').detach().appendTo('#'+container);
		        $('#'+container).animate({marginLeft: '+='+width+'px'},0);
	        });
        }, interval);
    }
    else {
        if(EMMA.logoSliderTimer){
            clearInterval(EMMA.logoSliderTimer);
        }
        EMMA.logoSliderTimer = setInterval(function() {
            $('#'+container).animate({marginLeft: '-='+width+'px'},1000,function() {
		        $('#'+container+' .'+slide+':first').detach().appendTo('#'+container);
		        $('#'+container).animate({marginLeft: '+='+width+'px'},0);
	        });
        }, interval);
    }
}

// Sidenavi
function initSideNavi() {
	if (!$('html').hasClass('ie7')) {
		// Helper for sidenavi rollover
		$('#block-menu-block-2 .expanded > a').each(function() { $(this).prepend('

'); });
		$('.helpclicker').live('click',function(e) {
			e.preventDefault();
			$(this).closest('li').toggleClass('active-trail');
		});
		$('.helpclicker').live('mouseover mouseout',function(e) { $(this).closest('li').toggleClass('over'); });
		// Helper for toggling content elements
		$('.togglehead .helper').live('mouseover mouseout',function(e) { $(this).closest('.togglehead').toggleClass('over'); });
	}
}

// various actions
function initActions() {
	// Toggle help box on frontpage
	$('#togglehelp').click(function() { $('#stooltip').toggle(); });
	// Animated Scrolling to top
	$("#toplink").click(function(e){ e.preventDefault(); $('html,body').animate({scrollTop:0}, 1500); });
	// Kill .error when focusing a input field
	$('.error input').live('focus',function() {
		$(this).closest('.form-item').removeClass('error');
	});
}

// Tabcontent
function initTabContent() {
	if ($('.field-collection-item-field-tab').length > 0) {
		var container = $('.field-collection-item-field-tab').eq(0);
		$(container).before('

');
		$('.field-collection-item-field-tab').each(function() {
			var title = $('.title',this).text();
			$('#tabs ul').append('
'+title+'
');
			$('.title',this).remove();
		});
		$('#tabs a').live('click',function(e) {
			e.preventDefault();
			var index = $(this).index('#tabs a');
			$('#tabs a').removeClass('active');
			$(this).addClass('active');
			$('.field-collection-item-field-tab').hide();
			$('.field-collection-item-field-tab').eq(index).show();
		});
		$('#tabs a:first').trigger('click');
	}
}

// Togglebox
function initToggleContent() {
	$('.togglehead').live('click',function(e) {
		$(this).closest('.toggle').toggleClass('active');
		$(this).next('.togglecontent').toggle('fast');
	});
}

// Autoheight of boxes
function autoHeightFront() {
	var aboutHeight = $('#box-abouttext .boxcontent').innerHeight();
	var smallHeight = (aboutHeight - 105) / 2;
	$('#box-partnership .boxcontent').css('min-height',smallHeight+'px')
}

// Content margin, when no special Boxes inside the main node
function initContentMargin() {
	var headBox   = $('#block-system-main .node:first .head').length;
	var innerBoxes = $('#block-system-main .innerbox').length;
	var teaserBox = $('.view-subpages-teaser').length;
	if (teaserBox == 1 && innerBoxes == 0 && headBox == 0) {
		$('#block-system-main').addClass('margbottom');
	}
}

// span Tooltips
function initTooltips() {
	$('.tooltip').live('mouseenter',function(e) {
		var offset = $(this).offset();
		var spanwidth = $(this).width();
		$('body').append('
'+$(this).attr('data-tooltip')+'

');
		var w = $('#tip').width();
		var h = $('#tip').height();
		$('#tip').css({top: (offset.top-h-30)+'px',left: (offset.left+(spanwidth/2)-(w/2))+'px'});
		$('#tip .bubble').css({marginLeft: w/2-5+'px'});
	});
	$('.tooltip').live('mouseleave',function() { $('#tip').remove(); });
}

// Parse Contents to improve user experience
function parseContent() {
	// Check if tables in the content have a thead
	$('.region-content table').each(function() {
		if ($('thead',this).length == 0) { $(this).addClass('nothead');	}
	});
	// Count toggleboxes
	$('.toggle:first').addClass('first');
	$('.toggle:last').addClass('last');
}

function customiseReadMoreText(){

	// hacking 'Read more' text for some pages
	var readMores = {
		'biomart': {
			'path': '/resources-and-services/access-emma-mouse-resources',
			'url': 'https://www.emmanet.org/biomart/martview/',
			'label': 'Search EMMA Biomart',
			'title': 'Advanced BioMart search'
		},
		'submission': {
			'path': '/resources-and-services/deposit-mice-emma-repository',
			'url': '/emma/publicSubmission/submissionForm.emma',
			'label': 'Submit mice to EMMA',
			'title': 'Submission form'
		},
        'meetings': {
			'path': '/infrafrontier-research-infrastructure/public-relations',
			'url': '/meetingtool',
			'label': 'Meeting tool',
			'title': 'Meeting Registration'
		},
	};
	for ( var i in readMores ){
		if ( window.location.pathname == readMores[i].path ){
		    $('div.view-content div h3').find('a').each(function(){
		        if ( $(this).text() == readMores[i].title ){
		            //resources-and-services/access-emma-mouse-resources/advanced-biomart-search
		            var url = readMores[i].url;
		            $(this).attr('href', url);
		            $(this).parent().siblings('p.more').find('a').text(readMores[i].label).attr('href', url);
		       }
		    });
		}
	}
}

$(document).ready(function() {

	initTabContent();
	initToggleContent();
	initSideNavi();
	initContentMargin();
	initSlider();
	initActions();
	initTooltips();
	parseContent();
	fixPlaceholder();
	customiseReadMoreText();

	if ($('body').hasClass('front')) { autoHeightFront(); }

});

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


<commit_before>var selectat = null;
var utilizator = null;
var scroll_blocat = true;

var websocket = new WebSocket("ws://localhost:8080");

websocket.onopen = function(data) {
    trimite_ajax(
            {
                'operatie': 'id_utilizator'
            },
            function(data) {
                data = $.parseJSON(data);
                utilizator = data;
                console.log("Gasit utilizator: " + data.nume + " id = " + data.id);
                date_init = {
                    'operatie': 'initializare',
                    'id_utilizator': utilizator.id,
                    'nume_utilizator': utilizator.nume
                };
                websocket.send(JSON.stringify(date_init));
            });
    console.log("Conexiune realizata cu succes: " + JSON.stringify(data));
};
websocket.onmessage = function(raspuns) {
   // data = JSON.parse(data);
    text = raspuns.data;
    console.log("Primit mesaj: " + raspuns.data);
    data = JSON.parse(text);

    if(data.operatie === 'trimitere') {
        if(selectat && selectat.id === data.id_expeditor) {
            adauga_mesaj(data.text, data.id_expeditor);
            console.log("Adaugat mesaj: conversatie curenta, text = " + data.text);
        } else {
            var element = element_lista(data.id_expeditor);
            element.addClass('mesaj-nou');

            console.log("Adaugat mesaj: alta conversatie");
        }
    } else if (data.operatie === 'stare_utilizator') {
        actualizare_utilizator({'id': data.id, 'stare': data.tip});
    } else {
        console.error("Eroare (websocket.onmessage): \n\
            data.operatie nu este de tipul cunoscut");
    }
};
websocket.onclose = function(data) {
    console.log("Conexiunea se inchide: " + data);
};
websocket.onerror = function(data) {
    console.error("Eroare in websocket: " + data);
};

function trimite_ajax (date, func) {
    $.ajax({
        type: 'POST',
        url: "php/procese_ajax.php",
        data: date,
        success: func,
        error: function(a, b, c) {
            console.log(a, b, c);
        }
    });
}

function element_lista(id) {
    return $("#_u_" + id);
}

function actualizare_utilizator (u) {
    var p_id = "_u_"+u.id;
    if($('#' + p_id).length === 0) {
        $('<p/>', {
            id: p_id,
            click: function(){ selecteaza(u); },
            text: u.nume
        }).appendTo($("div#list-wrap"));
    }
    if(u.stare === 'online') {
        element_lista(u.id).addClass('online').removeClass('offline');
    } else if(u.stare === 'offline') {
        element_lista(u.id).removeClass('online').addClass('offline');
    }
}

function lista_utilizatori() {
    trimite_ajax(
            {'operatie': 'utilizatori'},
            function (data) {
                data = $.parseJSON(data);
                utilizatori = data;
                for(var i=0; i<data.length; i++) {
                    actualizare_utilizator(data[i]);
                }
            });
}

function selecteaza(u) {
    $('#chat-titlu').text(u.nume);
    var p = element_lista(u.id);
    if(selectat)
        element_lista(selectat.id).removeClass('selectat');
    selectat = u;
    element_lista(selectat.id).addClass('selectat').removeClass('mesaj-nou');
    $('#casuta').val('');
    incarca_mesaje();
}

function tasta_jos(k) {
    var text = $(this).val();
    text = $.trim(text);

    if(!selectat || text.length >= $(this).attr('maxlength')) {
        event.preventDefault();
        $(this).val('');
    } else if(k.keyCode === 13) {
        trimite(text);
        $(this).val('');
    }
}

function tasta_sus(k) {
    if(k.keyCode === 13) {
        $(this).val('');
        event.preventDefault();
    }
}

function trimite(mesaj) {
    date = {
                'operatie': 'trimitere',
                'id_expeditor': utilizator.id,
                'id_destinatar': selectat.id,
                'nume_destinatar': selectat.nume,
                'text': mesaj
            };
    websocket.send(JSON.stringify(date));
    adauga_mesaj(mesaj, utilizator.id);
    //console.log("datele de trimis sunt " + JSON.stringify(date));
    trimite_ajax(
            date,
            function(data)
            {

               // console.log("Mesaj trimis " + data);
               // incarca_mesaje();
            });

}

function adauga_mesaj(text_mesaj, expeditor) {
    $('<p/>', {
        text: text_mesaj,
        id: 'mesaj',
        class: (expeditor === selectat.id ? 'mesajul-lor': 'mesajul-meu')
    }).appendTo($('#zona-mesaje'));
    $('#zona-mesaje').scrollHeight = $('#zona-mesaje').scrollTop;
}

function incarca_mesaje() {
    if(!selectat) return;
    while($('#mesaj').length > 0) {
        $('#mesaj').remove();
    }

    trimite_ajax(
            {
                'operatie': 'mesaje',
                'cu': selectat.id
            },
            function(data) {
                data = $.parseJSON(data);
                for(var i = 0; i<data.length; i++) {
                    adauga_mesaj(data[i].text, data[i].expeditor);
                }
            });
}

function init() {
    lista_utilizatori();
}

<commit_msg>adauga animatie la scroll-ul automat cand este adaugat un mesaj<commit_after>var selectat = null;
var utilizator = null;
var scroll_blocat = true;

var websocket = new WebSocket("ws://localhost:8080");

websocket.onopen = function(data) {
    trimite_ajax(
            {
                'operatie': 'id_utilizator'
            },
            function(data) {
                data = $.parseJSON(data);
                utilizator = data;
                console.log("Gasit utilizator: " + data.nume + " id = " + data.id);
                date_init = {
                    'operatie': 'initializare',
                    'id_utilizator': utilizator.id,
                    'nume_utilizator': utilizator.nume
                };
                websocket.send(JSON.stringify(date_init));
            });
    console.log("Conexiune realizata cu succes: " + JSON.stringify(data));
};
websocket.onmessage = function(raspuns) {
   // data = JSON.parse(data);
    text = raspuns.data;
    console.log("Primit mesaj: " + raspuns.data);
    data = JSON.parse(text);

    if(data.operatie === 'trimitere') {
        if(selectat && selectat.id === data.id_expeditor) {
            adauga_mesaj(data.text, data.id_expeditor);
            console.log("Adaugat mesaj: conversatie curenta, text = " + data.text);
        } else {
            var element = element_lista(data.id_expeditor);
            element.addClass('mesaj-nou');

            console.log("Adaugat mesaj: alta conversatie");
        }
    } else if (data.operatie === 'stare_utilizator') {
        actualizare_utilizator({'id': data.id, 'stare': data.tip});
    } else {
        console.error("Eroare (websocket.onmessage): \n\
            data.operatie nu este de tipul cunoscut");
    }
};
websocket.onclose = function(data) {
    console.log("Conexiunea se inchide: " + data);
};
websocket.onerror = function(data) {
    console.error("Eroare in websocket: " + data);
};

function trimite_ajax (date, func) {
    $.ajax({
        type: 'POST',
        url: "php/procese_ajax.php",
        data: date,
        success: func,
        error: function(a, b, c) {
            console.log(a, b, c);
        }
    });
}

function element_lista(id) {
    return $("#_u_" + id);
}

function actualizare_utilizator (u) {
    var p_id = "_u_"+u.id;
    if($('#' + p_id).length === 0) {
        $('<p/>', {
            id: p_id,
            click: function(){ selecteaza(u); },
            text: u.nume
        }).appendTo($("div#list-wrap"));
    }
    if(u.stare === 'online') {
        element_lista(u.id).addClass('online').removeClass('offline');
    } else if(u.stare === 'offline') {
        element_lista(u.id).removeClass('online').addClass('offline');
    }
}

function lista_utilizatori() {
    trimite_ajax(
            {'operatie': 'utilizatori'},
            function (data) {
                data = $.parseJSON(data);
                utilizatori = data;
                for(var i=0; i<data.length; i++) {
                    actualizare_utilizator(data[i]);
                }
            });
}

function selecteaza(u) {
    $('#chat-titlu').text(u.nume);
    //var p = element_lista(u.id);
    if(selectat)
        element_lista(selectat.id).removeClass('selectat');
    selectat = u;
    element_lista(selectat.id).addClass('selectat').removeClass('mesaj-nou');
    $('#casuta').val('');
    incarca_mesaje();
}

function tasta_jos(k) {
    var text = $(this).val();
    text = $.trim(text);

    if(!selectat || text.length >= $(this).attr('maxlength')) {
        event.preventDefault();
        $(this).val('');
    } else if(k.keyCode === 13) {
        trimite(text);
        $(this).val('');
    }
}

function tasta_sus(k) {
    if(k.keyCode === 13) {
        $(this).val('');
        event.preventDefault();
    }
}

function trimite(mesaj) {
    date = {
                'operatie': 'trimitere',
                'id_expeditor': utilizator.id,
                'id_destinatar': selectat.id,
                'nume_destinatar': selectat.nume,
                'text': mesaj
            };
    websocket.send(JSON.stringify(date));
    adauga_mesaj(mesaj, utilizator.id);
    //console.log("datele de trimis sunt " + JSON.stringify(date));
    trimite_ajax(
            date,
            function(data)
            {

               // console.log("Mesaj trimis " + data);
               // incarca_mesaje();
            });

}

function adauga_mesaj(text_mesaj, expeditor) {
    $('<p/>', {
        text: text_mesaj,
        id: 'mesaj',
        class: (expeditor === selectat.id ? 'mesajul-lor': 'mesajul-meu')
    }).appendTo($('#zona-mesaje'));
    //$('#zona-mesaje').scrollHeight = $('#zona-mesaje').scrollTop;
    $("#zona-mesaje").animate({ scrollTop: $('#zona-mesaje')[0].scrollHeight}, 150);
}

function incarca_mesaje() {
    if(!selectat) return;
    while($('#mesaj').length > 0) {
        $('#mesaj').remove();
    }

    trimite_ajax(
            {
                'operatie': 'mesaje',
                'cu': selectat.id
            },
            function(data) {
                data = $.parseJSON(data);
                for(var i = 0; i<data.length; i++) {
                    adauga_mesaj(data[i].text, data[i].expeditor);
                }
            });
}

function init() {
    lista_utilizatori();
}

<|endoftext|>


<commit_before>$(function () {

	var dotnet_repo_class = 'repo-container element ArcGIS Runtime SDK .NET C# XAML DotNet';
	var ios_repo_class = 'repo-container element ArcGIS Runtime iOS Mobile Objective-C';
	var android_repo_class = 'repo-container element ArcGIS Runtime Android Mobile Java';
	var js_repo_class = 'repo-container element ArcGIS Web Mapping JavaScript';

	var dotnet_header_class = 'repo-header DotNet';
	var ios_header_class = 'repo-header Objective-C';
	var android_header_class = 'repo-header Java';
	var js_header_class = 'repo-header JavaScript';

	var dotnet_h3_class = 'repo-language DotNet';
	var ios_h3_class = 'repo-language Objective-C';
	var android_h3_class = 'repo-language Java';
	var js_h3_class = 'repo-language JavaScript';

	var language;

	var container_div = $('<div/>').addClass('container smaller');
	var content_div = $('<div/>').attr("id", 'content');

	var data_filter = [];

	// リポジトリの取得
    $.get('https://api.github.com/users/EsriJapan/repos').then(function (repos) {
    	console.log(repos);

    	// ループ（リポジトリ配列）
        for (var i = 0; i < repos.length; i++) {
        	// リポジトリ名⇒フィルタリング用のクラスを作成⇒配列
        	var repo_name = repos[i].name;
        	var name_split = repo_name.split("-")
        	for (var j = 0; j < name_split.length; j++) {
        		// 同名のタグ候補がある場合（あるいはesrijapan.github.io）は無視
        		var sametag = false;
        		for(var k = 0;  k < data_filter.length; k++) {
        			if(data_filter[k] === name_split[j]) {
        				sametag = true;
        			}
							else if(name_split[j] === "esrijapan.github.io") {
								sametag = true;
							}
        		}
        		// 同名のタグ候補が無い場合
        		if(sametag === false) {
        			// フィルタリング用クラス配列にプッシュ
        			data_filter.push(name_split[j]);
        		}
        	}

        	// リポジトリの言語
        	if(repos[i].language == 'C#' || repos[i].language == 'Objective-C' || repos[i].language == 'Java' || repos[i].language == 'JavaScript' || repos[i].language == 'HTML') {
        		console.log(repos[i]);
        		var repo_class;
	        	var header_class;
	        	var h3_class;
	        	// フィルタリング用の追加クラスを作成
	        	var add_class = repos[i].name.replace(/-/g, " ");
	        	// リポジトリの言語で分岐
	        	switch (repos[i].language){
				  case 'C#':
				    repo_class = dotnet_repo_class;
				    header_class = dotnet_header_class;
				    h3_class = dotnet_h3_class;
				    language = '.NET';
				    break;
				  case 'Objective-C':
				    repo_class = ios_repo_class;
				    header_class = ios_header_class;
				    h3_class = ios_h3_class;
				    language = 'Objective-C';
				    break;
				  case 'Java':
				    repo_class = android_repo_class;
				    header_class = android_header_class;
				    h3_class = android_h3_class;
				    language = 'Java';
				    break;
				  case 'JavaScript':
				    repo_class = js_repo_class;
				    header_class = js_header_class;
				    h3_class = js_h3_class;
				    language = 'JavaScript';
				    break;
				  case 'HTML':
				    repo_class = js_repo_class;
				    header_class = js_header_class;
				    h3_class = js_h3_class;
				    language = 'JavaScript';
				    break;
				}
				// フィルタリング用のクラスを追加
				repo_class = repo_class + " " + add_class;

		        // タグの生成
		        var repo_container_div = $('<div/>').addClass(repo_class);
		        var repo_div = $('<div/>').addClass('repo');
		        var repo_header_div = $('<div/>').addClass(header_class);
		        var repo_title_h2 = $('<h2/>').addClass('repo-title');
		        var repo_link_a = $('<a/>').attr("href", repos[i].html_url).text(repos[i].name);
		        var repo_language_h3 = $('<h3/>').addClass(h3_class).text(language);
		        var repo_description = $('<p/>').addClass('repo-description').text(repos[i].description);

		        repo_title_h2.append(repo_link_a);
		        repo_header_div.append(repo_title_h2);
		        repo_header_div.append(repo_language_h3);
		        repo_div.append(repo_header_div);
		        repo_div.append(repo_description);
		        repo_container_div.append(repo_div);

		        content_div.append(repo_container_div);
		        //console.log($('div#content.isotope'));
        	}
        };

        // タグの登録（リポジトリ カード）
        container_div.append(content_div);
        $('div#page').append(container_div);

        // フィルタリング用クラス配列からタグの生成（データフィルタリング）
        console.log(data_filter);
    	for (var ii = 0; ii < data_filter.length; ii++) {
    		var df_option = $('<option/>').attr("data-filter", data_filter[ii]).text(data_filter[ii]);
    		console.log($('optgroup[label=タグ]'));
    		$('optgroup[label=タグ]').append(df_option);
    	}

        // github.js
        $(".chzn-select").chosen();var e=$("#content");e.isotope({itemSelector:".element",layoutMode:"masonry"}),$(".repo-language").click(function(){var e=this.innerHTML.replace(/ /g,"");return $("select").val(e).trigger("liszt:updated").change(),window.location.hash=e,!1}),$("select").change(function(){var t=[],n=[];t=$("select option:selected"),t.each(function(){$(this).data("filter");n.push("."+$(this).data("filter"))});var i=n.join("");return e.isotope({filter:i}),window.location.hash=n.join(",").replace(/\./g,""),!1}),$(window).smartresize(function(){e.isotope("reLayout")}),$(document).ready(function(){var e=window.location.hash;null!==e&&""!=e&&($("select").val(e.replace(/#/,"").split(",")),$("select").trigger("liszt:updated").change())}),$(document).ready(function(){function e(e){window.clearInterval(n),e&&(n=setInterval(t,o))}function t(){$("select").val(c[a]),$("select").trigger("liszt:updated").change(),a<c.length-1?a++:a=0}var n,i=!1,o=3e3,a=0,c=["JavaScript","ActionScript","Objective-C","Java","Python","DotNet","iOS","C-Sharp","Android","QuickStart","Local-Government","Bootstrap","Mapping","GeoJSON","Mobile","Code-Challenge","Utility","Storytelling","Geocoding","ArcGIS","Hadoop","Web","Social","Analysis","Offline","Runtime","Dashboard","Public",""];$("#home-banner").dblclick(function(){i=!i,e(i)}),$(document).keydown(function(t){38===t.which&&t.shiftKey&&i?o>1e3&&(o-=1e3):40===t.which&&t.shiftKey&&i&&5e3>o&&(o+=1e3),i&&e(i)})})

    });

});
<commit_msg>fix filterling<commit_after>$(function () {

	var dotnet_repo_class = 'repo-container element ArcGIS Runtime SDK .NET C# XAML DotNet';
	var ios_repo_class = 'repo-container element ArcGIS Runtime iOS Mobile Objective-C';
	var android_repo_class = 'repo-container element ArcGIS Runtime Android Mobile Java';
	var js_repo_class = 'repo-container element ArcGIS Web Mapping JavaScript';

	var dotnet_header_class = 'repo-header DotNet';
	var ios_header_class = 'repo-header Objective-C';
	var android_header_class = 'repo-header Java';
	var js_header_class = 'repo-header JavaScript';

	var dotnet_h3_class = 'repo-language DotNet';
	var ios_h3_class = 'repo-language Objective-C';
	var android_h3_class = 'repo-language Java';
	var js_h3_class = 'repo-language JavaScript';

	var language;

	var container_div = $('<div/>').addClass('container smaller');
	var content_div = $('<div/>').attr("id", 'content');

	var data_filter = [];

	// リポジトリの取得
    $.get('https://api.github.com/users/EsriJapan/repos').then(function (repos) {
    	console.log(repos);

    	// ループ（リポジトリ配列）
        for (var i = 0; i < repos.length; i++) {
        	// リポジトリ名⇒フィルタリング用のクラスを作成⇒配列
        	var repo_name = repos[i].name;
        	var name_split = repo_name.split("-")

        	// esrijapan.github.io は非表示
        	if(repo_name !== "esrijapan.github.io") {

	        	for (var j = 0; j < name_split.length; j++) {
	        		// 同名のタグ候補がある場合（あるいはesrijapan.github.io）は無視
	        		var sametag = false;
	        		for(var k = 0;  k < data_filter.length; k++) {
	        			if(data_filter[k] === name_split[j]) {
	        				sametag = true;
	        			}
	        		}
	        		// 同名のタグ候補が無い場合
	        		if(sametag === false) {
	        			// フィルタリング用クラス配列にプッシュ
	        			data_filter.push(name_split[j]);
	        		}
	        	}

	        	// リポジトリの言語
	        	if(repos[i].language == 'C#' || repos[i].language == 'Objective-C' || repos[i].language == 'Java' || repos[i].language == 'JavaScript' || repos[i].language == 'HTML') {
	        		console.log(repos[i]);
	        		var repo_class;
		        	var header_class;
		        	var h3_class;
		        	// フィルタリング用の追加クラスを作成
		        	var add_class = repos[i].name.replace(/-/g, " ");
		        	// リポジトリの言語で分岐
		        	switch (repos[i].language){
					  case 'C#':
					    repo_class = dotnet_repo_class;
					    header_class = dotnet_header_class;
					    h3_class = dotnet_h3_class;
					    language = '.NET';
					    break;
					  case 'Objective-C':
					    repo_class = ios_repo_class;
					    header_class = ios_header_class;
					    h3_class = ios_h3_class;
					    language = 'Objective-C';
					    break;
					  case 'Java':
					    repo_class = android_repo_class;
					    header_class = android_header_class;
					    h3_class = android_h3_class;
					    language = 'Java';
					    break;
					  case 'JavaScript':
					    repo_class = js_repo_class;
					    header_class = js_header_class;
					    h3_class = js_h3_class;
					    language = 'JavaScript';
					    break;
					  case 'HTML':
					    repo_class = js_repo_class;
					    header_class = js_header_class;
					    h3_class = js_h3_class;
					    language = 'JavaScript';
					    break;
					}
					// フィルタリング用のクラスを追加
					repo_class = repo_class + " " + add_class;

			        // タグの生成
			        var repo_container_div = $('<div/>').addClass(repo_class);
			        var repo_div = $('<div/>').addClass('repo');
			        var repo_header_div = $('<div/>').addClass(header_class);
			        var repo_title_h2 = $('<h2/>').addClass('repo-title');
			        var repo_link_a = $('<a/>').attr("href", repos[i].html_url).text(repos[i].name);
			        var repo_language_h3 = $('<h3/>').addClass(h3_class).text(language);
			        var repo_description = $('<p/>').addClass('repo-description').text(repos[i].description);

			        repo_title_h2.append(repo_link_a);
			        repo_header_div.append(repo_title_h2);
			        repo_header_div.append(repo_language_h3);
			        repo_div.append(repo_header_div);
			        repo_div.append(repo_description);
			        repo_container_div.append(repo_div);

			        content_div.append(repo_container_div);
			        //console.log($('div#content.isotope'));
	        	}

	        }
        };

        // タグの登録（リポジトリ カード）
        container_div.append(content_div);
        $('div#page').append(container_div);

        // フィルタリング用クラス配列からタグの生成（データフィルタリング）
        console.log(data_filter);
    	for (var ii = 0; ii < data_filter.length; ii++) {
    		var df_option = $('<option/>').attr("data-filter", data_filter[ii]).text(data_filter[ii]);
    		console.log($('optgroup[label=タグ]'));
    		$('optgroup[label=タグ]').append(df_option);
    	}

        // github.js
        $(".chzn-select").chosen();var e=$("#content");e.isotope({itemSelector:".element",layoutMode:"masonry"}),$(".repo-language").click(function(){var e=this.innerHTML.replace(/ /g,"");return $("select").val(e).trigger("liszt:updated").change(),window.location.hash=e,!1}),$("select").change(function(){var t=[],n=[];t=$("select option:selected"),t.each(function(){$(this).data("filter");n.push("."+$(this).data("filter"))});var i=n.join("");return e.isotope({filter:i}),window.location.hash=n.join(",").replace(/\./g,""),!1}),$(window).smartresize(function(){e.isotope("reLayout")}),$(document).ready(function(){var e=window.location.hash;null!==e&&""!=e&&($("select").val(e.replace(/#/,"").split(",")),$("select").trigger("liszt:updated").change())}),$(document).ready(function(){function e(e){window.clearInterval(n),e&&(n=setInterval(t,o))}function t(){$("select").val(c[a]),$("select").trigger("liszt:updated").change(),a<c.length-1?a++:a=0}var n,i=!1,o=3e3,a=0,c=["JavaScript","ActionScript","Objective-C","Java","Python","DotNet","iOS","C-Sharp","Android","QuickStart","Local-Government","Bootstrap","Mapping","GeoJSON","Mobile","Code-Challenge","Utility","Storytelling","Geocoding","ArcGIS","Hadoop","Web","Social","Analysis","Offline","Runtime","Dashboard","Public",""];$("#home-banner").dblclick(function(){i=!i,e(i)}),$(document).keydown(function(t){38===t.which&&t.shiftKey&&i?o>1e3&&(o-=1e3):40===t.which&&t.shiftKey&&i&&5e3>o&&(o+=1e3),i&&e(i)})})

    });

});
<|endoftext|>


<commit_before>var helpers = {};

helpers.escapeRegExp = function(string) {
	return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
};

helpers.getParameterByName = function(name, href) {
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( href );
	if (results == null) {
	  return "";
	} else {
	  return decodeURIComponent(results[1].replace(/\+/g, " "));
	}
};

helpers.getUniqueId = function(callback) {
	cpal.storage.getKey("uniqueId", function(result) {
		if (result != undefined) {
			callback(result);
		} else {
			var newid = randomString(24);
			cpal.storage.setKey("uniqueId", newid, function() {
				callback(newId);
			});
		}
	});
};

helpers.randomString = function(len, charSet) {
	charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
	var randomString = '';
	for (var i = 0; i < len; i++) {
		var randomPoz = Math.floor(Math.random() * charSet.length);
		randomString += charSet.substring(randomPoz,randomPoz+1);
	}
	return randomString;
};

helpers.testURL = function(url) {
	var saveView = "";
	if (window.location.href.indexOf("view.php") != -1) {
		saveView = helpers.getParameterByName("view", window.location.href);
	}
	var saveViewing = "";
	if (window.location.href.indexOf("index.php") != -1) {
		saveViewing = helpers.getParameterByName("viewing", window.location.href);
	}
	var testThing = window.location.href.replace("http://", "")
										.replace("https://", "")
										.replace("courses2015.dalton.org/")
										.replace("undefined", "")
										.replace("index.php", "")
										.replace(window.location.search, "")
										.replace(/#.*$/, "")
										.replace("?", "")
										+ (saveView != "" ? ("?view=" + saveView) : "")
										+ (saveViewing != "" ? ("?viewing=" + saveViewing) : "");
	return testThing.indexOf(url) > -1;
};

window.helpers = helpers;

// Prototype:

String.prototype.replaceAll = function(search, replace) {
	// If replace is null, return original string; otherwise, it will replace search string with 'undefined'.

	if(!replace) {
		return this;
	}

	return this.replace(new RegExp(helpers.escapeRegExp(search), 'g'), replace);
};<commit_msg>Id -> ID<commit_after>var helpers = {};

helpers.escapeRegExp = function(string) {
	return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
};

helpers.getParameterByName = function(name, href) {
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( href );
	if (results == null) {
	  return "";
	} else {
	  return decodeURIComponent(results[1].replace(/\+/g, " "));
	}
};

helpers.getUniqueID = function(callback) {
	cpal.storage.getKey("uniqueId", function(result) {
		if (result != undefined) {
			callback(result);
		} else {
			var newid = randomString(24);
			cpal.storage.setKey("uniqueId", newid, function() {
				callback(newId);
			});
		}
	});
};

helpers.randomString = function(len, charSet) {
	charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
	var randomString = '';
	for (var i = 0; i < len; i++) {
		var randomPoz = Math.floor(Math.random() * charSet.length);
		randomString += charSet.substring(randomPoz,randomPoz+1);
	}
	return randomString;
};

helpers.testURL = function(url) {
	var saveView = "";
	if (window.location.href.indexOf("view.php") != -1) {
		saveView = helpers.getParameterByName("view", window.location.href);
	}
	var saveViewing = "";
	if (window.location.href.indexOf("index.php") != -1) {
		saveViewing = helpers.getParameterByName("viewing", window.location.href);
	}
	var testThing = window.location.href.replace("http://", "")
										.replace("https://", "")
										.replace("courses2015.dalton.org/")
										.replace("undefined", "")
										.replace("index.php", "")
										.replace(window.location.search, "")
										.replace(/#.*$/, "")
										.replace("?", "")
										+ (saveView != "" ? ("?view=" + saveView) : "")
										+ (saveViewing != "" ? ("?viewing=" + saveViewing) : "");
	return testThing.indexOf(url) > -1;
};

window.helpers = helpers;

// Prototype:

String.prototype.replaceAll = function(search, replace) {
	// If replace is null, return original string; otherwise, it will replace search string with 'undefined'.

	if(!replace) {
		return this;
	}

	return this.replace(new RegExp(helpers.escapeRegExp(search), 'g'), replace);
};<|endoftext|>