<commit_before>function _resize() {
    // I couldn't figure out how to do this in CSS: resize the table
    // so that it takes as much space as it can without expanding the
    // page horizontally.
    var space = parseInt($("#lava-breadcrumbs").outerWidth() - $("#outer-table").outerWidth());
    space -= $("#lava-content").outerWidth() - $("#lava-content").width();
    var table = $("#results-table"), scroller=$("#scroller");
    var atRight = scroller.width() + scroller.scrollLeft() >= table.attr('scrollWidth');
    scroller.width(scroller.width() + space);
    if (atRight) scroller.scrollLeft(table.attr('scrollWidth'));
}
function _fixRowHeights () {
    var index = 0;
    var nameRows = $("#test-run-names > tbody > tr");
    var resultRows = $("#results-table > tbody > tr");
    for (; index < nameRows.length; index++) {
        var nameRow = $(nameRows[index]);
        var resultRow = $(resultRows[index]);
        var nameRowHeight = parseInt(nameRow.css('height'));
        var resultRowHeight = parseInt(resultRow.css('height'));
        nameRow.css('height', Math.max(nameRowHeight, resultRowHeight));
        resultRow.css('height', Math.max(nameRowHeight, resultRowHeight));
    }
}

function update_filters(column_data, test_run_names) {
    for (iter in column_data) {
	build_number = column_data[iter]["number"].split('.')[0];
	$("#build_number_start").append($('<option>', {
	    value: build_number,
	    text: build_number
	}));
	$("#build_number_end").append($('<option>', {
	    value: build_number,
	    text: build_number
	}));
    }
    $("#build_number_end option:last").attr("selected", true);

    for (iter in test_run_names) {
	selected = false;
	if (column_data[column_data.length-1]["test_runs"][test_run_names[iter]]) {
	    selected = true;
	}
	$("#test_select").append($('<option>', {
	    value: test_run_names[iter],
	    text: test_run_names[iter],
	    selected: selected
	}));
    }
}

function update_table(column_data, table_data, test_run_names) {

    if ($("#test_select").val() == null) {
	alert("Please select at least one test.");
	return false;
    }

    if ($("#build_number_start").val() > $("#build_number_end").val()) {
	alert("End build number must be greater then the start build number.");
	return false;
    }

    // Create row headlines.
    test_name_rows = "
Date
";
    for (iter in test_run_names) {
	if ($("#test_select").val().indexOf(test_run_names[iter]) >= 0) {
	    test_name = test_run_names[iter];
	    if (test_name.length > 20) {
		test_name = test_name.substring(0,20) + "...";
	    }
	    test_name_rows += "
" + test_name + "
";
	}
    }
    $("#test-run-names tbody").html(test_name_rows);

    // Create column headlines.
    result_table_head = "
";
    for (iter in column_data) {
	build_number = column_data[iter]["number"].split('.')[0];

	if (build_number <= $("#build_number_end").val() && build_number >= $("#build_number_start").val()) {
	    link = '' + build_number.split(' ')[0] + '';
	    result_table_head += "" + link + "	";
	}
    }
    result_table_head += "
";
    $("#results-table thead").html(result_table_head);

    // Create table body
    result_table_body = "
";
    for (iter in column_data) {
	build_number = column_data[iter]["number"].split('.')[0];
	build_date = column_data[iter]["date"].split('.')[0];

	if (build_number <= $("#build_number_end").val() && build_number >= $("#build_number_start").val()) {
	    result_table_body += "" + build_date.split(' ')[0] + "	";
	}

    }
    result_table_body += "
";

    for (cnt in test_run_names) {
	test = test_run_names[cnt];
	if ($("#test_select").val().indexOf(test) >= 0) {
	    result_table_body += "
";
	    row = table_data[test];

	    for (iter in row) {
		build_number = column_data[iter]["number"].split('.')[0];
		if (build_number <= $("#build_number_end").val() && build_number >= $("#build_number_start").val()) {
		    result_table_body += '';
		    if (row[iter]["uuid"]) {
			result_table_body += '' + row[iter]["passes"] + '/' + row[iter]["total"] + '';
			result_table_body += '';
			for (bug_id in row[iter]["bug_ids"]) {
			    bug = row[iter]["bug_ids"];
			    result_table_body += '[' + bug[bug_id] + ']';
			}
			result_table_body += '[+]';
			result_table_body += '';

		    } else {
			result_table_body += "—";
		    }
		    result_table_body += "	";
		}
	    }
	    result_table_body += "
";
	}
    }

    $("#results-table tbody").html(result_table_body);
    $("#scroller").scrollLeft($("#scroller")[0].scrollWidth);

    update_plot(column_data, table_data, test_run_names);
}

function update_plot(column_data, table_data, test_run_names) {

    // Get the plot data.

    data = [];
    for (test in table_data) {

	if ($("#test_select").val().indexOf(test) >= 0) {
	    row_data = [];

	    row = table_data[test];
	    for (iter in row) {
		build_number = column_data[iter]["number"].split('.')[0];
		if (build_number <= $("#build_number_end").val() && build_number >= $("#build_number_start").val()) {
		    if (row[iter]["cls"]) {
			if ($('input:radio[name=graph_type]:checked').val() == "number") {
			    row_data.push([iter, row[iter]["passes"]]);
			} else {
			    row_data.push([iter, 100*row[iter]["passes"]/row[iter]["total"]]);
			}
		    }
		}
	    }
	    data.push({label: test, data: row_data});
	}
    }

    // Get all build numbers to be used as tick labels.
    build_numbers = [];
    for (test in table_data) {
	row = table_data[test];
	for (iter in row) {
	    build_number = column_data[iter]["number"].split('.')[0];
	    if (build_number <= $("#build_number_end").val() && build_number >= $("#build_number_start").val()) {
		build_numbers.push(build_number.split(' ')[0]);
	    }
	}
	// Each test has the same number of build numbers.
	break;
    }

    var options = {
	series: {
	    lines: { show: true },
	    points: { show: false }
	},
	legend: {
	    show: true,
	    position: "ne",
	    margin: 3,
	    container: "#legend-container",
	},
	xaxis: {
	    tickFormatter: function (val, axis) {
		return build_numbers[val];
	    },
	},
	yaxis: {
	    tickDecimals: 0,
	},
    };

    if ($('input:radio[name=graph_type]:checked').val() == "percentage") {
	options["yaxis"]["max"] = 100;
    }

    $.plot($("#outer-container #inner-container"), data, options);
}

$(window).ready(
    function () {
        // Hook up the event and run resize ASAP (looks jumpy in FF if you
        // don't run it here).
        $(window).resize(_resize);
        $("#scroller").scrollLeft(100000);
        _resize();
        _fixRowHeights();

        function _submit() {
            $(this).submit();
        }
        var add_bug_dialog = $('#add-bug-dialog').dialog(
            {
                autoOpen: false,
                buttons: {'Cancel': function () {$(this).dialog('close');}, 'OK': _submit },
                modal: true,
                title: "Link bug to XXX"
            });
        var go_to_bug_dialog = $("#go-to-bug-dialog").dialog(
            {
                autoOpen: false,
                buttons: {'Cancel': function () {$(this).dialog('close');}, 'Remove link': _submit},
                modal: true,
                title: "Link bug to XXX"
            });

        function get_testrun_and_buildnumber (element) {
            var cell = element.closest('td');
            var row = cell.closest('tr');
            var testrun = $($("#test-run-names > tbody > tr")[row.index()]).text();
            var header_cells = element.closest('table').find('thead > tr > th');
            var buildnumber = $(header_cells[cell.index()]).text();
            return {testrun: $.trim(testrun), buildnumber: $.trim(buildnumber)};
        }

        function find_previous_bugs (element) {
            var td = $(element).closest('td');
            var bugs = [];
            var start = td;
            while ((td = td.prev()) && td.size()) {
                td.find(".bug-link").each(
                    function (index, link) {
                        var bug_id = $(link).data('bug-id');
                        if (bugs.indexOf(bug_id) < 0) bugs.push(bug_id);
                    });
            }
            var already_linked = [];
            start.find(".bug-link").each(
                function (index, link) {
                    var bug_id = $(link).data('bug-id');
                    if (bugs.indexOf(bug_id) >= 0) {
                        bugs.splice(bugs.indexOf(bug_id), 1);
                        already_linked.push(bug_id);
                    }
                });
            return {bugs:bugs, already_linked:already_linked};
        }

        $('a.add-bug-link').click(
            function (e) {
                e.preventDefault();

                var previous = find_previous_bugs($(this));
                var prev_div = add_bug_dialog.find('div.prev');
                var names = get_testrun_and_buildnumber($(this));

                if (previous.bugs.length) {
                    var html = '';
                    prev_div.show();
                    html = '
Use a bug previously linked to ' + names.testrun + ':

';
                    for (var i = 0; i < previous.already_linked.length; i++) {
                        html += '
' + previous.already_linked[i] + ' (already linked)
';
                    }
                    for (var i = 0; i < previous.bugs.length; i++) {
                        html += '
' +
                            previous.bugs[i] + '
';
                    }
                    html += '
';
                    html += "
Or enter another bug number:
";
                    prev_div.html(html);
                    prev_div.find('a').click(
                        function (e) {
                            e.preventDefault();
                            add_bug_dialog.find('input[name=bug]').val($(this).data('bug-id'));
                            add_bug_dialog.submit();
                        });
                } else {
                    prev_div.hide();
                }

                var title = "Link a bug to the '" + names.testrun +
                    "' run of build " + names.buildnumber;
                add_bug_dialog.find('input[name=uuid]').val($(this).closest('td').data('uuid'));
                add_bug_dialog.dialog('option', 'title', title);
                add_bug_dialog.dialog('open');
            });

        $("a.bug-link").click(
            function (e) {
                e.preventDefault();
                var names = get_testrun_and_buildnumber($(this));
                var title = "Bug linked to the '" + names.testrun +
                    "' run of build " + names.buildnumber;
                go_to_bug_dialog.find('input[name=uuid]').val($(this).closest('td').data('uuid'));
                go_to_bug_dialog.find('input[name=bug]').val($(this).data('bug-id'));
                go_to_bug_dialog.find('a').attr('href', $(this).attr('href'));
                go_to_bug_dialog.find('a').text('View bug ' + $(this).data('bug-id'));
                go_to_bug_dialog.dialog('option', 'title', title);
                go_to_bug_dialog.dialog('open');
            });
    });
// Because what resize does depends on the final sizes of elements,
// run it again after everything is loaded (things end up wrong in
// chromium if you don't do this).
$(window).load(_resize);
$(window).load(_fixRowHeights);
$(window).load(function() {update_filters(columns, test_names);});
$(window).load(function() {update_table(columns, chart_data, test_names);});
<commit_msg>Fix 'undefined' problem for x axis labels.<commit_after>function _resize() {
    // I couldn't figure out how to do this in CSS: resize the table
    // so that it takes as much space as it can without expanding the
    // page horizontally.
    var space = parseInt($("#lava-breadcrumbs").outerWidth() - $("#outer-table").outerWidth());
    space -= $("#lava-content").outerWidth() - $("#lava-content").width();
    var table = $("#results-table"), scroller=$("#scroller");
    var atRight = scroller.width() + scroller.scrollLeft() >= table.attr('scrollWidth');
    scroller.width(scroller.width() + space);
    if (atRight) scroller.scrollLeft(table.attr('scrollWidth'));
}
function _fixRowHeights () {
    var index = 0;
    var nameRows = $("#test-run-names > tbody > tr");
    var resultRows = $("#results-table > tbody > tr");
    for (; index < nameRows.length; index++) {
        var nameRow = $(nameRows[index]);
        var resultRow = $(resultRows[index]);
        var nameRowHeight = parseInt(nameRow.css('height'));
        var resultRowHeight = parseInt(resultRow.css('height'));
        nameRow.css('height', Math.max(nameRowHeight, resultRowHeight));
        resultRow.css('height', Math.max(nameRowHeight, resultRowHeight));
    }
}

function update_filters(column_data, test_run_names) {
    for (iter in column_data) {
	build_number = column_data[iter]["number"].split('.')[0];
	$("#build_number_start").append($('<option>', {
	    value: build_number,
	    text: build_number
	}));
	$("#build_number_end").append($('<option>', {
	    value: build_number,
	    text: build_number
	}));
    }
    $("#build_number_end option:last").attr("selected", true);

    for (iter in test_run_names) {
	selected = false;
	if (column_data[column_data.length-1]["test_runs"][test_run_names[iter]]) {
	    selected = true;
	}
	$("#test_select").append($('<option>', {
	    value: test_run_names[iter],
	    text: test_run_names[iter],
	    selected: selected
	}));
    }
}

function update_table(column_data, table_data, test_run_names) {

    if ($("#test_select").val() == null) {
	alert("Please select at least one test.");
	return false;
    }

    if ($("#build_number_start").val() > $("#build_number_end").val()) {
	alert("End build number must be greater then the start build number.");
	return false;
    }

    // Create row headlines.
    test_name_rows = "
Date
";
    for (iter in test_run_names) {
	if ($("#test_select").val().indexOf(test_run_names[iter]) >= 0) {
	    test_name = test_run_names[iter];
	    if (test_name.length > 20) {
		test_name = test_name.substring(0,20) + "...";
	    }
	    test_name_rows += "
" + test_name + "
";
	}
    }
    $("#test-run-names tbody").html(test_name_rows);

    // Create column headlines.
    result_table_head = "
";
    for (iter in column_data) {
	build_number = column_data[iter]["number"].split('.')[0];

	if (build_number <= $("#build_number_end").val() && build_number >= $("#build_number_start").val()) {
	    link = '' + build_number.split(' ')[0] + '';
	    result_table_head += "" + link + "	";
	}
    }
    result_table_head += "
";
    $("#results-table thead").html(result_table_head);

    // Create table body
    result_table_body = "
";
    for (iter in column_data) {
	build_number = column_data[iter]["number"].split('.')[0];
	build_date = column_data[iter]["date"].split('.')[0];

	if (build_number <= $("#build_number_end").val() && build_number >= $("#build_number_start").val()) {
	    result_table_body += "" + build_date.split(' ')[0] + "	";
	}

    }
    result_table_body += "
";

    for (cnt in test_run_names) {
	test = test_run_names[cnt];
	if ($("#test_select").val().indexOf(test) >= 0) {
	    result_table_body += "
";
	    row = table_data[test];

	    for (iter in row) {
		build_number = column_data[iter]["number"].split('.')[0];
		if (build_number <= $("#build_number_end").val() && build_number >= $("#build_number_start").val()) {
		    result_table_body += '';
		    if (row[iter]["uuid"]) {
			result_table_body += '' + row[iter]["passes"] + '/' + row[iter]["total"] + '';
			result_table_body += '';
			for (bug_id in row[iter]["bug_ids"]) {
			    bug = row[iter]["bug_ids"];
			    result_table_body += '[' + bug[bug_id] + ']';
			}
			result_table_body += '[+]';
			result_table_body += '';

		    } else {
			result_table_body += "—";
		    }
		    result_table_body += "	";
		}
	    }
	    result_table_body += "
";
	}
    }

    $("#results-table tbody").html(result_table_body);
    $("#scroller").scrollLeft($("#scroller")[0].scrollWidth);

    update_plot(column_data, table_data, test_run_names);
}

function update_plot(column_data, table_data, test_run_names) {

    // Get the plot data.

    data = [];
    for (test in table_data) {

	if ($("#test_select").val().indexOf(test) >= 0) {
	    row_data = [];

	    row = table_data[test];
	    for (iter in row) {
		build_number = column_data[iter]["number"].split('.')[0];
		if (build_number <= $("#build_number_end").val() && build_number >= $("#build_number_start").val()) {
		    if (row[iter]["cls"]) {
			if ($('input:radio[name=graph_type]:checked').val() == "number") {
			    row_data.push([iter, row[iter]["passes"]]);
			} else {
			    row_data.push([iter, 100*row[iter]["passes"]/row[iter]["total"]]);
			}
		    }
		}
	    }
	    data.push({label: test, data: row_data});
	}
    }

    // Get all build numbers to be used as tick labels.
    build_numbers = [];
    for (test in table_data) {
	row = table_data[test];
	for (iter in row) {
	    build_numbers.push(column_data[iter]["number"].split(' ')[0]);
	}
	// Each test has the same number of build numbers.
	break;
    }

    var options = {
	series: {
	    lines: { show: true },
	    points: { show: false }
	},
	legend: {
	    show: true,
	    position: "ne",
	    margin: 3,
	    container: "#legend-container",
	},
	xaxis: {
	    tickDecimals: 0,
	    tickFormatter: function (val, axis) {
		return build_numbers[val];
	    },
	},
	yaxis: {
	    tickDecimals: 0,
	},
    };

    if ($('input:radio[name=graph_type]:checked').val() == "percentage") {
	options["yaxis"]["max"] = 100;
    }

    $.plot($("#outer-container #inner-container"), data, options);
}

$(window).ready(
    function () {
        // Hook up the event and run resize ASAP (looks jumpy in FF if you
        // don't run it here).
        $(window).resize(_resize);
        $("#scroller").scrollLeft(100000);
        _resize();
        _fixRowHeights();

        function _submit() {
            $(this).submit();
        }
        var add_bug_dialog = $('#add-bug-dialog').dialog(
            {
                autoOpen: false,
                buttons: {'Cancel': function () {$(this).dialog('close');}, 'OK': _submit },
                modal: true,
                title: "Link bug to XXX"
            });
        var go_to_bug_dialog = $("#go-to-bug-dialog").dialog(
            {
                autoOpen: false,
                buttons: {'Cancel': function () {$(this).dialog('close');}, 'Remove link': _submit},
                modal: true,
                title: "Link bug to XXX"
            });

        function get_testrun_and_buildnumber (element) {
            var cell = element.closest('td');
            var row = cell.closest('tr');
            var testrun = $($("#test-run-names > tbody > tr")[row.index()]).text();
            var header_cells = element.closest('table').find('thead > tr > th');
            var buildnumber = $(header_cells[cell.index()]).text();
            return {testrun: $.trim(testrun), buildnumber: $.trim(buildnumber)};
        }

        function find_previous_bugs (element) {
            var td = $(element).closest('td');
            var bugs = [];
            var start = td;
            while ((td = td.prev()) && td.size()) {
                td.find(".bug-link").each(
                    function (index, link) {
                        var bug_id = $(link).data('bug-id');
                        if (bugs.indexOf(bug_id) < 0) bugs.push(bug_id);
                    });
            }
            var already_linked = [];
            start.find(".bug-link").each(
                function (index, link) {
                    var bug_id = $(link).data('bug-id');
                    if (bugs.indexOf(bug_id) >= 0) {
                        bugs.splice(bugs.indexOf(bug_id), 1);
                        already_linked.push(bug_id);
                    }
                });
            return {bugs:bugs, already_linked:already_linked};
        }

        $('a.add-bug-link').click(
            function (e) {
                e.preventDefault();

                var previous = find_previous_bugs($(this));
                var prev_div = add_bug_dialog.find('div.prev');
                var names = get_testrun_and_buildnumber($(this));

                if (previous.bugs.length) {
                    var html = '';
                    prev_div.show();
                    html = '
Use a bug previously linked to ' + names.testrun + ':

';
                    for (var i = 0; i < previous.already_linked.length; i++) {
                        html += '
' + previous.already_linked[i] + ' (already linked)
';
                    }
                    for (var i = 0; i < previous.bugs.length; i++) {
                        html += '
' +
                            previous.bugs[i] + '
';
                    }
                    html += '
';
                    html += "
Or enter another bug number:
";
                    prev_div.html(html);
                    prev_div.find('a').click(
                        function (e) {
                            e.preventDefault();
                            add_bug_dialog.find('input[name=bug]').val($(this).data('bug-id'));
                            add_bug_dialog.submit();
                        });
                } else {
                    prev_div.hide();
                }

                var title = "Link a bug to the '" + names.testrun +
                    "' run of build " + names.buildnumber;
                add_bug_dialog.find('input[name=uuid]').val($(this).closest('td').data('uuid'));
                add_bug_dialog.dialog('option', 'title', title);
                add_bug_dialog.dialog('open');
            });

        $("a.bug-link").click(
            function (e) {
                e.preventDefault();
                var names = get_testrun_and_buildnumber($(this));
                var title = "Bug linked to the '" + names.testrun +
                    "' run of build " + names.buildnumber;
                go_to_bug_dialog.find('input[name=uuid]').val($(this).closest('td').data('uuid'));
                go_to_bug_dialog.find('input[name=bug]').val($(this).data('bug-id'));
                go_to_bug_dialog.find('a').attr('href', $(this).attr('href'));
                go_to_bug_dialog.find('a').text('View bug ' + $(this).data('bug-id'));
                go_to_bug_dialog.dialog('option', 'title', title);
                go_to_bug_dialog.dialog('open');
            });
    });
// Because what resize does depends on the final sizes of elements,
// run it again after everything is loaded (things end up wrong in
// chromium if you don't do this).
$(window).load(_resize);
$(window).load(_fixRowHeights);
$(window).load(function() {update_filters(columns, test_names);});
$(window).load(function() {update_table(columns, chart_data, test_names);});
<|endoftext|>


<commit_before>function _resize() {
    // I couldn't figure out how to do this in CSS: resize the table
    // so that it takes as much space as it can without expanding the
    // page horizontally.
    var space = parseInt($("#lava-breadcrumbs").outerWidth() - $("#outer-table").outerWidth());
    space -= $("#lava-content").outerWidth() - $("#lava-content").width();
    var table = $("#results-table"), scroller=$("#scroller");
    var atRight = scroller.width() + scroller.scrollLeft() >= table.attr('scrollWidth');
    scroller.width(scroller.width() + space);
    if (atRight) scroller.scrollLeft(table.attr('scrollWidth'));
}
function _fixRowHeights () {
    var index = 0;
    var nameRows = $("#test-run-names > tbody > tr");
    var resultRows = $("#results-table > tbody > tr");
    for (; index < nameRows.length; index++) {
        var nameRow = $(nameRows[index]);
        var resultRow = $(resultRows[index]);
        var nameRowHeight = parseInt(nameRow.css('height'));
        var resultRowHeight = parseInt(resultRow.css('height'));
        nameRow.css('height', Math.max(nameRowHeight, resultRowHeight));
        resultRow.css('height', Math.max(nameRowHeight, resultRowHeight));
    }
}

function update_filters(column_data, test_run_names) {
    for (iter in column_data) {
	build_number = column_data[iter]["number"].split('.')[0];
	$("#build_number_start").append($('<option>', {
	    value: build_number,
	    text: build_number
	}));
	$("#build_number_end").append($('<option>', {
	    value: build_number,
	    text: build_number
	}));
    }
    $("#build_number_end option:last").attr("selected", true);

    for (iter in test_run_names) {
	$("#test_select").append($('<option>', {
	    value: test_run_names[iter],
	    text: test_run_names[iter],
	    selected: true
	}));
    }
}

function update_table(column_data, table_data, test_run_names) {

    if ($("#test_select").val() == null) {
	alert("Please select at least one test.");
	return false;
    }

    if ($("#build_number_start").val() > $("#build_number_end").val()) {
	alert("End build number must be greater then the start build number.");
	return false;
    }

    // Create row headlines.
    test_name_rows = "
Date
";
    for (iter in test_run_names) {
	if ($("#test_select").val().indexOf(test_run_names[iter]) >= 0) {
	    test_name_rows += "
" + test_run_names[iter] + "
";
	}
    }
    $("#test-run-names tbody").html(test_name_rows);

    // Create column headlines.
    result_table_head = "
";
    for (iter in column_data) {
	build_number = column_data[iter]["number"].split('.')[0];

	if (build_number <= $("#build_number_end").val() && build_number >= $("#build_number_start").val()) {
	    link = '' + build_number + '';
	    result_table_head += "" + link + "	";
	}
    }
    result_table_head += "
";
    $("#results-table thead").html(result_table_head);

    // Create table body
    result_table_body = "
";
    for (iter in column_data) {
	build_number = column_data[iter]["number"].split('.')[0];
	build_date = column_data[iter]["date"].split('.')[0];

	if (build_number <= $("#build_number_end").val() && build_number >= $("#build_number_start").val()) {
	    result_table_body += "" + build_date + "	";
	}

    }
    result_table_body += "
";

    for (test in table_data) {
	if ($("#test_select").val().indexOf(test) >= 0) {
	    result_table_body += "
";
	    row = table_data[test];

	    for (iter in row) {
		build_number = column_data[iter]["number"].split('.')[0];
		if (build_number <= $("#build_number_end").val() && build_number >= $("#build_number_start").val()) {
		    result_table_body += '';
		    if (row[iter]["cls"]) {
			result_table_body += '' + row[iter]["passes"] + '/' + row[iter]["total"] + '';
			result_table_body += '';
			for (bug_id in row[iter]["bug_ids"]) {
			    bug = row[iter]["bug_ids"];
			    result_table_body += '[' + bug[bug_id] + ']';
			}
			result_table_body += '[+]';
			result_table_body += '';

		    } else {
			result_table_body += "—";
		    }
		    result_table_body += "	";
		}
	    }
	    result_table_body += "
";
	}
    }

    $("#results-table tbody").html(result_table_body);

    update_plot(column_data, table_data, test_run_names);
}

function update_plot(column_data, table_data, test_run_names) {

    var data = [];
    xticks = [];

    for (test in table_data) {

	if ($("#test_select").val().indexOf(test) >= 0) {
	    row = table_data[test];
	    for (iter in row) {
		build_number = column_data[iter]["number"].split('.')[0];
		if (build_number <= $("#build_number_end").val() && build_number >= $("#build_number_start").val()) {
		    xticks.push([iter, build_number]);
		    if (row[iter]["cls"]) {
			data.push([iter, row[iter]["passes"]]);
		    }
		}
	    }
	}
    }

    var options = {
	series: {
	    lines: { show: true },
	    points: { show: false }
	},
	legend: {
	    show: true,
	    position: "ne",
	    margin: 3,
	},
	xaxis: {
	    ticks: xticks,
	},
	yaxis: {
	    tickDecimals: 0,
	},

    };

    $.plot($("#outer-container #inner-container"),
	   [
	       {
		   data:data,points:{symbol: "circle"}
	       }
	   ], options);

}

$(window).ready(
    function () {
        // Hook up the event and run resize ASAP (looks jumpy in FF if you
        // don't run it here).
        $(window).resize(_resize);
        $("#scroller").scrollLeft(100000);
        _resize();
        _fixRowHeights();

        function _submit() {
            $(this).submit();
        }
        var add_bug_dialog = $('#add-bug-dialog').dialog(
            {
                autoOpen: false,
                buttons: {'Cancel': function () {$(this).dialog('close');}, 'OK': _submit },
                modal: true,
                title: "Link bug to XXX"
            });
        var go_to_bug_dialog = $("#go-to-bug-dialog").dialog(
            {
                autoOpen: false,
                buttons: {'Cancel': function () {$(this).dialog('close');}, 'Remove link': _submit},
                modal: true,
                title: "Link bug to XXX"
            });

        function get_testrun_and_buildnumber (element) {
            var cell = element.closest('td');
            var row = cell.closest('tr');
            var testrun = $($("#test-run-names > tbody > tr")[row.index()]).text();
            var header_cells = element.closest('table').find('thead > tr > th');
            var buildnumber = $(header_cells[cell.index()]).text();
            return {testrun: $.trim(testrun), buildnumber: $.trim(buildnumber)};
        }

        function find_previous_bugs (element) {
            var td = $(element).closest('td');
            var bugs = [];
            var start = td;
            while ((td = td.prev()) && td.size()) {
                td.find(".bug-link").each(
                    function (index, link) {
                        var bug_id = $(link).data('bug-id');
                        if (bugs.indexOf(bug_id) < 0) bugs.push(bug_id);
                    });
            }
            var already_linked = [];
            start.find(".bug-link").each(
                function (index, link) {
                    var bug_id = $(link).data('bug-id');
                    if (bugs.indexOf(bug_id) >= 0) {
                        bugs.splice(bugs.indexOf(bug_id), 1);
                        already_linked.push(bug_id);
                    }
                });
            return {bugs:bugs, already_linked:already_linked};
        }

        $('a.add-bug-link').click(
            function (e) {
                e.preventDefault();

                var previous = find_previous_bugs($(this));
                var prev_div = add_bug_dialog.find('div.prev');
                var names = get_testrun_and_buildnumber($(this));

                if (previous.bugs.length) {
                    var html = '';
                    prev_div.show();
                    html = '
Use a bug previously linked to ' + names.testrun + ':

';
                    for (var i = 0; i < previous.already_linked.length; i++) {
                        html += '
' + previous.already_linked[i] + ' (already linked)
';
                    }
                    for (var i = 0; i < previous.bugs.length; i++) {
                        html += '
' +
                            previous.bugs[i] + '
';
                    }
                    html += '
';
                    html += "
Or enter another bug number:
";
                    prev_div.html(html);
                    prev_div.find('a').click(
                        function (e) {
                            e.preventDefault();
                            add_bug_dialog.find('input[name=bug]').val($(this).data('bug-id'));
                            add_bug_dialog.submit();
                        });
                } else {
                    prev_div.hide();
                }

                var title = "Link a bug to the '" + names.testrun +
                    "' run of build " + names.buildnumber;
                add_bug_dialog.find('input[name=uuid]').val($(this).closest('td').data('uuid'));
                add_bug_dialog.dialog('option', 'title', title);
                add_bug_dialog.dialog('open');
            });

        $("a.bug-link").click(
            function (e) {
                e.preventDefault();
                var names = get_testrun_and_buildnumber($(this));
                var title = "Bug linked to the '" + names.testrun +
                    "' run of build " + names.buildnumber;
                go_to_bug_dialog.find('input[name=uuid]').val($(this).closest('td').data('uuid'));
                go_to_bug_dialog.find('input[name=bug]').val($(this).data('bug-id'));
                go_to_bug_dialog.find('a').attr('href', $(this).attr('href'));
                go_to_bug_dialog.find('a').text('View bug ' + $(this).data('bug-id'));
                go_to_bug_dialog.dialog('option', 'title', title);
                go_to_bug_dialog.dialog('open');
            });
    });
// Because what resize does depends on the final sizes of elements,
// run it again after everything is loaded (things end up wrong in
// chromium if you don't do this).
$(window).load(_resize);
$(window).load(_fixRowHeights);
$(window).load(function() {update_filters(columns, test_names);});
$(window).load(function() {update_table(columns, chart_data, test_names);});
<commit_msg>Additional improvments for displaying multiple tests.<commit_after>function _resize() {
    // I couldn't figure out how to do this in CSS: resize the table
    // so that it takes as much space as it can without expanding the
    // page horizontally.
    var space = parseInt($("#lava-breadcrumbs").outerWidth() - $("#outer-table").outerWidth());
    space -= $("#lava-content").outerWidth() - $("#lava-content").width();
    var table = $("#results-table"), scroller=$("#scroller");
    var atRight = scroller.width() + scroller.scrollLeft() >= table.attr('scrollWidth');
    scroller.width(scroller.width() + space);
    if (atRight) scroller.scrollLeft(table.attr('scrollWidth'));
}
function _fixRowHeights () {
    var index = 0;
    var nameRows = $("#test-run-names > tbody > tr");
    var resultRows = $("#results-table > tbody > tr");
    for (; index < nameRows.length; index++) {
        var nameRow = $(nameRows[index]);
        var resultRow = $(resultRows[index]);
        var nameRowHeight = parseInt(nameRow.css('height'));
        var resultRowHeight = parseInt(resultRow.css('height'));
        nameRow.css('height', Math.max(nameRowHeight, resultRowHeight));
        resultRow.css('height', Math.max(nameRowHeight, resultRowHeight));
    }
}

function update_filters(column_data, test_run_names) {
    for (iter in column_data) {
	build_number = column_data[iter]["number"].split('.')[0];
	$("#build_number_start").append($('<option>', {
	    value: build_number,
	    text: build_number
	}));
	$("#build_number_end").append($('<option>', {
	    value: build_number,
	    text: build_number
	}));
    }
    $("#build_number_end option:last").attr("selected", true);

    for (iter in test_run_names) {
	$("#test_select").append($('<option>', {
	    value: test_run_names[iter],
	    text: test_run_names[iter],
	    selected: true
	}));
    }
}

function update_table(column_data, table_data, test_run_names) {

    if ($("#test_select").val() == null) {
	alert("Please select at least one test.");
	return false;
    }

    if ($("#build_number_start").val() > $("#build_number_end").val()) {
	alert("End build number must be greater then the start build number.");
	return false;
    }

    // Create row headlines.
    test_name_rows = "
Date
";
    for (iter in test_run_names) {
	if ($("#test_select").val().indexOf(test_run_names[iter]) >= 0) {
	    test_name_rows += "
" + test_run_names[iter] + "
";
	}
    }
    $("#test-run-names tbody").html(test_name_rows);

    // Create column headlines.
    result_table_head = "
";
    for (iter in column_data) {
	build_number = column_data[iter]["number"].split('.')[0];

	if (build_number <= $("#build_number_end").val() && build_number >= $("#build_number_start").val()) {
	    link = '' + build_number + '';
	    result_table_head += "" + link + "	";
	}
    }
    result_table_head += "
";
    $("#results-table thead").html(result_table_head);

    // Create table body
    result_table_body = "
";
    for (iter in column_data) {
	build_number = column_data[iter]["number"].split('.')[0];
	build_date = column_data[iter]["date"].split('.')[0];

	if (build_number <= $("#build_number_end").val() && build_number >= $("#build_number_start").val()) {
	    result_table_body += "" + build_date + "	";
	}

    }
    result_table_body += "
";

    for (test in table_data) {
	if ($("#test_select").val().indexOf(test) >= 0) {
	    result_table_body += "
";
	    row = table_data[test];

	    for (iter in row) {
		build_number = column_data[iter]["number"].split('.')[0];
		if (build_number <= $("#build_number_end").val() && build_number >= $("#build_number_start").val()) {
		    result_table_body += '';
		    if (row[iter]["cls"]) {
			result_table_body += '' + row[iter]["passes"] + '/' + row[iter]["total"] + '';
			result_table_body += '';
			for (bug_id in row[iter]["bug_ids"]) {
			    bug = row[iter]["bug_ids"];
			    result_table_body += '[' + bug[bug_id] + ']';
			}
			result_table_body += '[+]';
			result_table_body += '';

		    } else {
			result_table_body += "—";
		    }
		    result_table_body += "	";
		}
	    }
	    result_table_body += "
";
	}
    }

    $("#results-table tbody").html(result_table_body);

    update_plot(column_data, table_data, test_run_names);
}

function update_plot(column_data, table_data, test_run_names) {

    data = [];
    xticks = [];

    for (test in table_data) {

	if ($("#test_select").val().indexOf(test) >= 0) {
	    row_data = [];

	    row = table_data[test];
	    for (iter in row) {
		build_number = column_data[iter]["number"].split('.')[0];
		if (build_number <= $("#build_number_end").val() && build_number >= $("#build_number_start").val()) {
		    xticks.push([iter, build_number]);
		    if (row[iter]["cls"]) {
			row_data.push([iter, row[iter]["passes"]]);
		    }
		}
	    }
	    data.push({label: test, data: row_data});
	}
    }

    var options = {
	series: {
	    lines: { show: true },
	    points: { show: false }
	},
	legend: {
	    show: true,
	    position: "ne",
	    margin: 3,
	},
	xaxis: {
	    ticks: xticks,
	},
	yaxis: {
	    tickDecimals: 0,
	},
    };

    $.plot($("#outer-container #inner-container"), data, options);
}

$(window).ready(
    function () {
        // Hook up the event and run resize ASAP (looks jumpy in FF if you
        // don't run it here).
        $(window).resize(_resize);
        $("#scroller").scrollLeft(100000);
        _resize();
        _fixRowHeights();

        function _submit() {
            $(this).submit();
        }
        var add_bug_dialog = $('#add-bug-dialog').dialog(
            {
                autoOpen: false,
                buttons: {'Cancel': function () {$(this).dialog('close');}, 'OK': _submit },
                modal: true,
                title: "Link bug to XXX"
            });
        var go_to_bug_dialog = $("#go-to-bug-dialog").dialog(
            {
                autoOpen: false,
                buttons: {'Cancel': function () {$(this).dialog('close');}, 'Remove link': _submit},
                modal: true,
                title: "Link bug to XXX"
            });

        function get_testrun_and_buildnumber (element) {
            var cell = element.closest('td');
            var row = cell.closest('tr');
            var testrun = $($("#test-run-names > tbody > tr")[row.index()]).text();
            var header_cells = element.closest('table').find('thead > tr > th');
            var buildnumber = $(header_cells[cell.index()]).text();
            return {testrun: $.trim(testrun), buildnumber: $.trim(buildnumber)};
        }

        function find_previous_bugs (element) {
            var td = $(element).closest('td');
            var bugs = [];
            var start = td;
            while ((td = td.prev()) && td.size()) {
                td.find(".bug-link").each(
                    function (index, link) {
                        var bug_id = $(link).data('bug-id');
                        if (bugs.indexOf(bug_id) < 0) bugs.push(bug_id);
                    });
            }
            var already_linked = [];
            start.find(".bug-link").each(
                function (index, link) {
                    var bug_id = $(link).data('bug-id');
                    if (bugs.indexOf(bug_id) >= 0) {
                        bugs.splice(bugs.indexOf(bug_id), 1);
                        already_linked.push(bug_id);
                    }
                });
            return {bugs:bugs, already_linked:already_linked};
        }

        $('a.add-bug-link').click(
            function (e) {
                e.preventDefault();

                var previous = find_previous_bugs($(this));
                var prev_div = add_bug_dialog.find('div.prev');
                var names = get_testrun_and_buildnumber($(this));

                if (previous.bugs.length) {
                    var html = '';
                    prev_div.show();
                    html = '
Use a bug previously linked to ' + names.testrun + ':

';
                    for (var i = 0; i < previous.already_linked.length; i++) {
                        html += '
' + previous.already_linked[i] + ' (already linked)
';
                    }
                    for (var i = 0; i < previous.bugs.length; i++) {
                        html += '
' +
                            previous.bugs[i] + '
';
                    }
                    html += '
';
                    html += "
Or enter another bug number:
";
                    prev_div.html(html);
                    prev_div.find('a').click(
                        function (e) {
                            e.preventDefault();
                            add_bug_dialog.find('input[name=bug]').val($(this).data('bug-id'));
                            add_bug_dialog.submit();
                        });
                } else {
                    prev_div.hide();
                }

                var title = "Link a bug to the '" + names.testrun +
                    "' run of build " + names.buildnumber;
                add_bug_dialog.find('input[name=uuid]').val($(this).closest('td').data('uuid'));
                add_bug_dialog.dialog('option', 'title', title);
                add_bug_dialog.dialog('open');
            });

        $("a.bug-link").click(
            function (e) {
                e.preventDefault();
                var names = get_testrun_and_buildnumber($(this));
                var title = "Bug linked to the '" + names.testrun +
                    "' run of build " + names.buildnumber;
                go_to_bug_dialog.find('input[name=uuid]').val($(this).closest('td').data('uuid'));
                go_to_bug_dialog.find('input[name=bug]').val($(this).data('bug-id'));
                go_to_bug_dialog.find('a').attr('href', $(this).attr('href'));
                go_to_bug_dialog.find('a').text('View bug ' + $(this).data('bug-id'));
                go_to_bug_dialog.dialog('option', 'title', title);
                go_to_bug_dialog.dialog('open');
            });
    });
// Because what resize does depends on the final sizes of elements,
// run it again after everything is loaded (things end up wrong in
// chromium if you don't do this).
$(window).load(_resize);
$(window).load(_fixRowHeights);
$(window).load(function() {update_filters(columns, test_names);});
$(window).load(function() {update_table(columns, chart_data, test_names);});
<|endoftext|>


<commit_before>/* global define */

(function (global) {
  'use strict'

  // Constructor
  function MenuButton (button) {
    // Save a reference to the element
    this.button = button

    // Add (initial) button semantics
    this.button.setAttribute('aria-haspopup', true)
    this.button.setAttribute('aria-expanded', false)

    // Get the menu
    this.menuId = this.button.getAttribute('data-inclusive-menu-opens')
    this.menu = document.getElementById(this.menuId)

    // If the menu doesn't exist
    // exit with an error referencing the missing
    // menu's id
    if (!this.menu) {
      throw new Error('#' + this.menuId + ' menu missing')
    }

    // Add menu semantics
    this.menu.setAttribute('role', 'menu')

    // Hide menu initially
    this.menu.hidden = true

    // Get the menu items
    this.menuItems = this.menu.querySelectorAll('button')

    if (this.menuItems.length < 1) {
      throw new Error('The #' + this.menuId + ' menu has no menu items')
    }

    this.firstItem = this.menuItems[0]
    this.lastItem = this.menuItems[this.menuItems.length - 1]

    var focusNext = function (currentItem, startItem) {
      // Determine which item is the startItem (first or last)
      var goingDown = startItem === this.firstItem

      // helper function for getting next legitimate element
      function move (elem) {
        return (goingDown ? elem.nextElementSibling : elem.previousElementSibling) || startItem
      }

      // make first move
      var nextItem = move(currentItem)

      // if the menuitem is disabled move on
      while (nextItem.disabled) {
        nextItem = move(nextItem)
      }

      // focus the first one that's not disabled
      nextItem.focus()
    }.bind(this)

    Array.prototype.forEach.call(this.menuItems, function (menuItem) {
      // Disable menu button if all menu items are disabled
      var active = Array.prototype.filter.call(this.menuItems, function (item) {
        return !item.disabled
      })
      if (active.length < 1) {
        this.button.disabled = true
        return
      }

      // Add menu item semantics
      menuItem.setAttribute('role', 'menuitem')

      // Prevent tab focus on menu items
      menuItem.setAttribute('tabindex', '-1')

      // Handle key presses for menuItem
      menuItem.addEventListener('keydown', function (e) {
        // Go to next/previous item if it exists
        // or loop around

        if (e.keyCode === 40) {
          e.preventDefault()
          focusNext(menuItem, this.firstItem)
        }

        if (e.keyCode === 38) {
          e.preventDefault()
          focusNext(menuItem, this.lastItem)
        }

        // Close on escape or tab
        if (e.keyCode === 27 || e.keyCode === 9) {
          this.toggle()
        }

        // If escape, refocus menu button
        if (e.keyCode === 27) {
          e.preventDefault()
          this.button.focus()
        }
      }.bind(this))

      menuItem.addEventListener('click', function (e) {
        // pass menu item node to select method
        this.select(menuItem)

        // close menu and focus menu button
        this.close()
        this.button.focus()
      }.bind(this))
    }.bind(this))

    // Handle button click
    this.button.addEventListener('click', this.toggle.bind(this))

    // Also toggle on down arrow
    this.button.addEventListener('keydown', function (e) {
      if (e.keyCode === 40) {
        if (this.menu.hidden) {
          this.open()
        } else {
          this.menu.querySelector(':not([disabled])').focus()
        }
      }

      // close menu on up arrow
      if (e.keyCode === 38) {
        this.close()
      }
    }.bind(this))

    // initiate listeners object for public events
    this._listeners = {}
  }

  // Open method
  MenuButton.prototype.open = function () {
    this.button.setAttribute('aria-expanded', true)
    this.menu.hidden = false
    this.menu.querySelector(':not([disabled])').focus()

    // fire open event
    this._fire('open')

    return this
  }

  // Close method
  MenuButton.prototype.close = function () {
    this.button.setAttribute('aria-expanded', false)
    this.menu.hidden = true

    // fire open event
    this._fire('close')

    return this
  }

  // Toggle method
  MenuButton.prototype.toggle = function () {
    var expanded = this.button.getAttribute('aria-expanded') === 'true'
    return expanded ? this.close() : this.open()
  }

  MenuButton.prototype.select = function (choice) {
    // fire open event
    this._fire('choose', choice)

    return this
  }

  MenuButton.prototype._fire = function (type, data) {
    var listeners = this._listeners[type] || []

    listeners.forEach(function (listener) {
      listener(data)
    })
  }

  MenuButton.prototype.on = function (type, handler) {
    if (typeof this._listeners[type] === 'undefined') {
      this._listeners[type] = []
    }

    this._listeners[type].push(handler)

    return this
  }

  // Export MenuButton
  if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
    module.exports = MenuButton
  } else if (typeof define === 'function' && define.amd) {
    define('MenuButton', [], function () {
      return MenuButton
    })
  } else if (typeof global === 'object') {
    // attach to window
    global.MenuButton = MenuButton
  }
}(this))
<commit_msg>renamed select method to choose<commit_after>/* global define */

(function (global) {
  'use strict'

  // Constructor
  function MenuButton (button) {
    // Save a reference to the element
    this.button = button

    // Add (initial) button semantics
    this.button.setAttribute('aria-haspopup', true)
    this.button.setAttribute('aria-expanded', false)

    // Get the menu
    this.menuId = this.button.getAttribute('data-inclusive-menu-opens')
    this.menu = document.getElementById(this.menuId)

    // If the menu doesn't exist
    // exit with an error referencing the missing
    // menu's id
    if (!this.menu) {
      throw new Error('#' + this.menuId + ' menu missing')
    }

    // Add menu semantics
    this.menu.setAttribute('role', 'menu')

    // Hide menu initially
    this.menu.hidden = true

    // Get the menu item buttons
    this.menuItems = this.menu.querySelectorAll('button')

    if (this.menuItems.length < 1) {
      throw new Error('The #' + this.menuId + ' menu has no menu items')
    }

    this.firstItem = this.menuItems[0]
    this.lastItem = this.menuItems[this.menuItems.length - 1]

    var focusNext = function (currentItem, startItem) {
      // Determine which item is the startItem (first or last)
      var goingDown = startItem === this.firstItem

      // helper function for getting next legitimate element
      function move (elem) {
        return (goingDown ? elem.nextElementSibling : elem.previousElementSibling) || startItem
      }

      // make first move
      var nextItem = move(currentItem)

      // if the menuitem is disabled move on
      while (nextItem.disabled) {
        nextItem = move(nextItem)
      }

      // focus the first one that's not disabled
      nextItem.focus()
    }.bind(this)

    Array.prototype.forEach.call(this.menuItems, function (menuItem) {
      // Disable menu button if all menu items are disabled
      var active = Array.prototype.filter.call(this.menuItems, function (item) {
        return !item.disabled
      })
      if (active.length < 1) {
        this.button.disabled = true
        return
      }

      // Add menu item semantics
      menuItem.setAttribute('role', 'menuitem')

      // Prevent tab focus on menu items
      menuItem.setAttribute('tabindex', '-1')

      // Handle key presses for menuItem
      menuItem.addEventListener('keydown', function (e) {
        // Go to next/previous item if it exists
        // or loop around

        if (e.keyCode === 40) {
          e.preventDefault()
          focusNext(menuItem, this.firstItem)
        }

        if (e.keyCode === 38) {
          e.preventDefault()
          focusNext(menuItem, this.lastItem)
        }

        // Close on escape or tab
        if (e.keyCode === 27 || e.keyCode === 9) {
          this.toggle()
        }

        // If escape, refocus menu button
        if (e.keyCode === 27) {
          e.preventDefault()
          this.button.focus()
        }
      }.bind(this))

      menuItem.addEventListener('click', function (e) {
        // pass menu item node to select method
        this.select(menuItem)

        // close menu and focus menu button
        this.close()
        this.button.focus()
      }.bind(this))
    }.bind(this))

    // Handle button click
    this.button.addEventListener('click', this.toggle.bind(this))

    // Also toggle on down arrow
    this.button.addEventListener('keydown', function (e) {
      if (e.keyCode === 40) {
        if (this.menu.hidden) {
          this.open()
        } else {
          this.menu.querySelector(':not([disabled])').focus()
        }
      }

      // close menu on up arrow
      if (e.keyCode === 38) {
        this.close()
      }
    }.bind(this))

    // initiate listeners object for public events
    this._listeners = {}
  }

  // Open method
  MenuButton.prototype.open = function () {
    this.button.setAttribute('aria-expanded', true)
    this.menu.hidden = false
    this.menu.querySelector(':not([disabled])').focus()

    // fire open event
    this._fire('open')

    return this
  }

  // Close method
  MenuButton.prototype.close = function () {
    this.button.setAttribute('aria-expanded', false)
    this.menu.hidden = true

    // fire open event
    this._fire('close')

    return this
  }

  // Toggle method
  MenuButton.prototype.toggle = function () {
    var expanded = this.button.getAttribute('aria-expanded') === 'true'
    return expanded ? this.close() : this.open()
  }

  MenuButton.prototype.choose = function (choice) {
    // fire open event
    this._fire('choose', choice)

    return this
  }

  MenuButton.prototype._fire = function (type, data) {
    var listeners = this._listeners[type] || []

    listeners.forEach(function (listener) {
      listener(data)
    })
  }

  MenuButton.prototype.on = function (type, handler) {
    if (typeof this._listeners[type] === 'undefined') {
      this._listeners[type] = []
    }

    this._listeners[type].push(handler)

    return this
  }

  // Export MenuButton
  if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
    module.exports = MenuButton
  } else if (typeof define === 'function' && define.amd) {
    define('MenuButton', [], function () {
      return MenuButton
    })
  } else if (typeof global === 'object') {
    // attach to window
    global.MenuButton = MenuButton
  }
}(this))
<|endoftext|>


<commit_before>Number.prototype.mod = function(n) {
return ((this%n)+n)%n;
}

function viewModel () {
	var self = this;

	self.holes = ko.observableArray([]);
	self.course_id = ko.observable();
	self.courseName = ko.observable();
	self.courseAlias = ko.observable();
	self.courseCrYellowMen = ko.observable();
	self.courseSlYellowMen = ko.observable();
	self.courseCrRedMen = ko.observable();
	self.courseSlRedMen = ko.observable();
	self.courseCrBlueMen = ko.observable();
	self.courseSlBlueMen = ko.observable();
	self.courseCrWhiteMen = ko.observable();
	self.courseSlWhiteMen = ko.observable();

	self.courseCrRedLadies = ko.observable();
	self.courseSlRedLadies = ko.observable();
	self.courseCrYellowLadies = ko.observable();
	self.courseSlYellowLadies = ko.observable();
	self.courseCrBlueLadies = ko.observable();
	self.courseSlBlueLadies = ko.observable();

	self.showHoles = ko.observable(false);

	self.redTeeEnabled = ko.observable(true);
	self.blueTeeEnabled = ko.observable(true);
	self.yellowTeeEnabled = ko.observable(true);
	self.whiteTeeEnabled = ko.observable(true);

	self.redTeeEnabledLadies = ko.observable(true);
	self.blueTeeEnabledLadies = ko.observable(true);
	self.yellowTeeEnabledLadies = ko.observable(true);

	self.courseNumberOfHoles = ko.observable();

	self.courseList = ko.observableArray([]);

	self.courseData = ko.observableArray([]);
	self.courseHoles = ko.observableArray([]);

	self.showHoleToggle = ko.observable(false);
	self.saveSuccess = ko.observable(false);

	self.resetForm = function() {
		self.courseName = ko.observable();
		self.courseAlias = ko.observable();
		self.courseCrYellowMen = ko.observable();
		self.courseSlYellowMen = ko.observable();
		self.courseCrRedMen = ko.observable();
		self.courseSlRedMen = ko.observable();
		self.courseCrBlueMen = ko.observable();
		self.courseSlBlueMen = ko.observable();
		self.courseCrWhiteMen = ko.observable();
		self.courseSlWhiteMen = ko.observable();

		self.courseCrRedLadies = ko.observable();
		self.courseSlRedLadies = ko.observable();
		self.courseCrYellowLadies = ko.observable();
		self.courseSlYellowLadies = ko.observable();
		self.courseCrBlueLadies = ko.observable();
		self.courseSlBlueLadies = ko.observable();
		self.holes.removeAll();
		self.saveSuccess(false);
	}

	self.newCourse = function() {
		self.resetForm();

		for (var i = 0; i < 18; i++) {
			self.holes.push({
				hole_number: ko.observable(i+1),
				hole_par: ko.observable(0),
				hole_hcp: ko.observable(),
				hole_length_yellow: ko.observable(0),
				hole_length_blue: ko.observable(0),
				hole_length_red: ko.observable(0),
				hole_length_white: ko.observable(0),
			});
			self.course_id("new");

			self.showHoleToggle(true);
		}
	};

	self.saveCourse = function() {
//		alert (self.course_id());

		// use normal tees if championship tees aren't set.
		if (self.blueTeeEnabled() == false) {
			self.courseCrBlueMen(self.courseCrRedMen());
			self.courseSlBlueMen(self.courseSlRedMen());
			self.courseCrBlueLadies(self.courseCrRedLadies());
			self.courseSlBlueLadies(self.courseSlRedLadies());
		}

		if (self.whiteTeeEnabled() == false) {
			self.courseCrWhiteMen(self.courseCrYellowMen());
			self.courseSlWhiteMen(self.courseSlYellowMen());
		}

		var data = {
			course_id		: self.course_id(),
			courseName		: self.courseName(),
			courseAlias		: self.courseAlias(),
			crRedMen 		: self.courseCrRedMen(),
			crBlueMen 		: self.courseCrBlueMen(),
			crYellowMen		: self.courseCrYellowMen(),
			crWhiteMen		: self.courseCrWhiteMen(),
			slRedMen		: self.courseSlRedMen(),
			slBlueMen		: self.courseSlBlueMen(),
			slYellowMen		: self.courseSlYellowMen(),
			slWhiteMen		: self.courseSlWhiteMen(),

			crRedLadies		: self.courseCrRedLadies(),
			crBlueLadies	: self.courseCrBlueLadies(),
			crYellowLadies 	: self.courseCrYellowLadies(),
			slRedLadies		: self.courseSlRedLadies(),
			slBlueLadies	: self.courseSlBlueLadies(),
			slYellowLadies 	: self.courseSlYellowLadies(),
		};

		apexEventProxy.saveCourseData(
			{ data : data },
			function (data) {
				// response

				var course_id = data.course_id;

				if (self.blueTeeEnabled() == false) {
					for (var i = 0; i < self.holes().length; i++) {
					self.holes()[i].hole_length_blue(self.holes()[i].hole_length_red());
					}
				}
				if (self.whiteTeeEnabled() == false) {
					for (var i = 0; i < self.holes().length; i++) {
					self.holes()[i].hole_length_white(self.holes()[i].hole_length_yellow());
					}
				}

				var data = ko.toJSON(self.holes());

				apexEventProxy.saveHoleData(
					{ data : data,
					  course_id : course_id },
					function (data) {
//						alert ("success");
						self.saveSuccess(true);
					}
				);
			}
		);
	};

	self.coursePar = ko.computed(function() {
		var s = 0;
		for (var i = 0; i < self.holes().length; i++) {
			s = s + parseInt(self.holes()[i].hole_par());
			}
		return s;
	});

	self.courseLengthRed = ko.computed(function() {
		var s = 0;
		for (var i = 0; i < self.holes().length; i++) {
			s = s + parseInt(self.holes()[i].hole_length_red());
			}
		return s;
	});

	self.courseLengthBlue = ko.computed(function() {
		var s = 0;
		for (var i = 0; i < self.holes().length; i++) {
			s = s + parseInt(self.holes()[i].hole_length_blue());
			}
		return s;
	});

	self.courseLengthYellow = ko.computed(function() {
		var s = 0;
		for (var i = 0; i < self.holes().length; i++) {
			s = s + parseInt(self.holes()[i].hole_length_yellow());
			}
		return s;
	});

	self.courseLengthWhite = ko.computed(function() {
		var s = 0;
		for (var i = 0; i < self.holes().length; i++) {
			s = s + parseInt(self.holes()[i].hole_length_white());
			}
		return s;
	});

	self.getCourseGeneralData = function (course_id) {
		self.resetForm();
		self.showHoleToggle(false);
		var data = { course_id : course_id };
		apexEventProxy.getCourseData(
			{ data : data },
			function (data) {
				self.courseName(data.course.name);
				self.courseAlias(data.course.alias);

				self.courseCrYellowMen(data.course.crYellowMen);
				self.courseSlYellowMen(data.course.slYellowMen);

				self.courseCrYellowLadies(data.course.crYellowLadies);
				self.courseSlYellowLadies(data.course.slYellowLadies);

				self.courseCrBlueMen(data.course.crBlueMen);
				self.courseSlBlueMen(data.course.slBlueMen);

				self.courseCrBlueLadies(data.course.crBlueLadies);
				self.courseSlBlueLadies(data.course.slBlueLadies);

				self.courseCrRedMen(data.course.crRedMen);
				self.courseSlRedMen(data.course.slRedMen);

				self.courseCrRedLadies(data.course.crRedLadies);
				self.courseSlRedLadies(data.course.slRedLadies);

				self.courseCrWhiteMen(data.course.crWhiteMen);
				self.courseSlWhiteMen(data.course.slWhiteMen);
			}
		);
		self.course_id(course_id);
		self.getHoleData(course_id);

	};

	self.getHoleData = function(course_id) {

		self.holes.removeAll();

		var data = { course_id : course_id };
		apexEventProxy.getHoleData(
			{ data : data },
			function (data) {
				for (var i = 0, m = data.holes.length; i < m; i++) {
					self.holes.push({
						hole_number: ko.observable(data.holes[i].hole_number),
						hole_par: ko.observable(data.holes[i].par),
						hole_hcp: ko.observable(data.holes[i].hcp),
						hole_length_yellow: ko.observable(data.holes[i].length_yellow),
						hole_length_blue: ko.observable(data.holes[i].length_blue),
						hole_length_red: ko.observable(data.holes[i].length_red),
						hole_length_white: ko.observable(data.holes[i].length_white),
					});
				}
			}
//				self.setHoleData();
		);
	};

	self.getCourseList = ko.computed(function (callback) {
		var a;
		apexEventProxy.getCourseList(
		{ a : a },
		function(data) {
//			alert(data.courses[0].name);
			for (var i = 0, m = data.courses.length; i < m; i++) {
				self.courseList.push(data.courses[i]);
				}
			}
		);
	});

	self.getCourseList();

	self.saveGolfer = function (callback) {
		var data = {
			handicap: self.playerExactHcp(),
			tee: self.playerDefaultTee(),
			gender: self.playerGender()
		};
		apexEventProxy.saveGolferData(
			{ data : data },
			function (data) {
				$.mobile.changePage('#f_page', { transition: "slidefade" });
			}
		);
	};

	self.getGolferData = function (callback) {
			var a;
			apexEventProxy.getGolferData(
			{ a : a },
			function(data) {
				self.playerName(data.golfer.name);
				self.playerExactHcp(data.golfer.handicap);
				self.playerDefaultTee(data.golfer.tee);
				self.playerGender(data.golfer.gender);
			}
		);
	};
}

$(document).ready(function() {

	window.vm = new viewModel();
	ko.applyBindings(vm);
});
<commit_msg>Parsley.js -käyttöön, 9/18 -reikäisen kentän valinta.<commit_after>Number.prototype.mod = function(n) {
return ((this%n)+n)%n;
}

function viewModel () {
	var self = this;

	self.holes = ko.observableArray([]);
	self.course_id = ko.observable();
	self.courseName = ko.observable();
	self.courseAlias = ko.observable();
	self.courseCrYellowMen = ko.observable();
	self.courseSlYellowMen = ko.observable();
	self.courseCrRedMen = ko.observable();
	self.courseSlRedMen = ko.observable();
	self.courseCrBlueMen = ko.observable();
	self.courseSlBlueMen = ko.observable();
	self.courseCrWhiteMen = ko.observable();
	self.courseSlWhiteMen = ko.observable();

	self.courseCrRedLadies = ko.observable();
	self.courseSlRedLadies = ko.observable();
	self.courseCrYellowLadies = ko.observable();
	self.courseSlYellowLadies = ko.observable();
	self.courseCrBlueLadies = ko.observable();
	self.courseSlBlueLadies = ko.observable();

	self.showHoles = ko.observable(false);

	self.redTeeEnabled = ko.observable(true);
	self.blueTeeEnabled = ko.observable(true);
	self.yellowTeeEnabled = ko.observable(true);
	self.whiteTeeEnabled = ko.observable(true);

	self.redTeeEnabledLadies = ko.observable(true);
	self.blueTeeEnabledLadies = ko.observable(true);
	self.yellowTeeEnabledLadies = ko.observable(true);

	self.courseNumberOfHoles = ko.observable();

	self.courseList = ko.observableArray([]);

	self.courseData = ko.observableArray([]);
	self.courseHoles = ko.observableArray([]);

	self.showHoleToggle = ko.observable(false);
	self.saveSuccess = ko.observable(false);
	self.saveFailure = ko.observable(false);

	self.noOfHoles = ko.observable(0);

	self.nippedHoles = ko.observable([]);

	self.resetForm = function() {

		self.courseName = ko.observable();
		self.courseAlias = ko.observable();
		self.courseCrYellowMen = ko.observable();
		self.courseSlYellowMen = ko.observable();
		self.courseCrRedMen = ko.observable();
		self.courseSlRedMen = ko.observable();
		self.courseCrBlueMen = ko.observable();
		self.courseSlBlueMen = ko.observable();
		self.courseCrWhiteMen = ko.observable();
		self.courseSlWhiteMen = ko.observable();

		self.courseCrRedLadies = ko.observable();
		self.courseSlRedLadies = ko.observable();
		self.courseCrYellowLadies = ko.observable();
		self.courseSlYellowLadies = ko.observable();
		self.courseCrBlueLadies = ko.observable();
		self.courseSlBlueLadies = ko.observable();

		self.holes.removeAll();
		self.saveSuccess(false);
	}

	self.newCourse = function() {
		self.resetForm();

		while (self.holes().length < 18) {

//		for (var i = 0; i < 18; i++) {
			self.holes.push({
				hole_number: ko.observable(self.holes().length + 1),
				hole_par: ko.observable(0),
				hole_hcp: ko.observable(),
				hole_length_yellow: ko.observable(0),
				hole_length_blue: ko.observable(0),
				hole_length_red: ko.observable(0),
				hole_length_white: ko.observable(0),
			});

		}
		self.course_id("new");
		self.noOfHoles("18");
		self.showHoleToggle(true);

	};

	self.holeNumToggle = ko.computed(function() {
		if (self.noOfHoles() == 18) {
//			if (self.holes().length < 18) {
/*				if (self.nippedHoles().length > 1) {
					for (var i = 0; i < self.nippedHoles().length; i++) {
						self.holes.push(self.nippedHoles()[i]);
					}
				} */
//				else {
					var i = 0;
					while (self.holes().length < 18) {
//						console.log(self.holes().length);
	//					console.log("lengthening");
						self.holes.push({
							hole_number: ko.observable(self.holes().length + 1),
							hole_par: ko.observable(0),
							hole_hcp: ko.observable(),
							hole_length_yellow: ko.observable(0),
							hole_length_blue: ko.observable(0),
							hole_length_red: ko.observable(0),
							hole_length_white: ko.observable(0),
						});
	//				}
	//			}
			}
		}

		else if (self.noOfHoles() == 9) {
//			console.log("hurkadurka");
			while (self.holes().length > 9) {
//				self.nippedHoles().push(self.holes.pop());
				self.holes.pop();
//				console.log("shortening");
//				i++;

			}
		}
	});

	self.saveCourse = function() {

		var form = $('#form').parsley();
		var form2 = $('#formi2').parsley();

//		$('#formi2').parsley('addItem', '#transparentInput');

		$('#formi2').parsley( 'validate' );
		$('#form').parsley( 'validate' );

		var valid = $('#form').parsley('isValid')
		var valid2 = $('#formi2').parsley('isValid')

		console.log("form " + valid);
		console.log("formi2 " + valid2);

		if (valid == false || valid2 == false) {
			self.saveFailure(true);
			return false;
		}

		// use normal tees if championship tees aren't set.
		if (self.blueTeeEnabled() == false) {
			self.courseCrBlueMen(self.courseCrRedMen());
			self.courseSlBlueMen(self.courseSlRedMen());
			self.courseCrBlueLadies(self.courseCrRedLadies());
			self.courseSlBlueLadies(self.courseSlRedLadies());
		}

		if (self.whiteTeeEnabled() == false) {
			self.courseCrWhiteMen(self.courseCrYellowMen());
			self.courseSlWhiteMen(self.courseSlYellowMen());
		}

		var data = {
			course_id		: self.course_id(),
			courseName		: self.courseName(),
			courseAlias		: self.courseAlias(),
			crRedMen 		: self.courseCrRedMen(),
			crBlueMen 		: self.courseCrBlueMen(),
			crYellowMen		: self.courseCrYellowMen(),
			crWhiteMen		: self.courseCrWhiteMen(),
			slRedMen		: self.courseSlRedMen(),
			slBlueMen		: self.courseSlBlueMen(),
			slYellowMen		: self.courseSlYellowMen(),
			slWhiteMen		: self.courseSlWhiteMen(),

			crRedLadies		: self.courseCrRedLadies(),
			crBlueLadies	: self.courseCrBlueLadies(),
			crYellowLadies 	: self.courseCrYellowLadies(),
			slRedLadies		: self.courseSlRedLadies(),
			slBlueLadies	: self.courseSlBlueLadies(),
			slYellowLadies 	: self.courseSlYellowLadies(),
		};

		apexEventProxy.saveCourseData(
			{ data : data },
			function (data) {
				// response

				var course_id = data.course_id;

				if (self.blueTeeEnabled() == false) {
					for (var i = 0; i < self.holes().length; i++) {
					self.holes()[i].hole_length_blue(self.holes()[i].hole_length_red());
					}
				}
				if (self.whiteTeeEnabled() == false) {
					for (var i = 0; i < self.holes().length; i++) {
					self.holes()[i].hole_length_white(self.holes()[i].hole_length_yellow());
					}
				}

				var data = ko.toJSON(self.holes());

				apexEventProxy.saveHoleData(
					{ data : data,
					  course_id : course_id },
					function (data) {
//						alert ("success");
						self.saveFailure(false);
						self.saveSuccess(true);
					}
				);
			}
		);
	};

	self.coursePar = ko.computed(function() {
		var s = 0;
		for (var i = 0; i < self.holes().length; i++) {
			s = s + parseInt(self.holes()[i].hole_par());
			}
		return s;
	});

	self.courseLengthRed = ko.computed(function() {
		var s = 0;
		for (var i = 0; i < self.holes().length; i++) {
			s = s + parseInt(self.holes()[i].hole_length_red());
			}
		return s;
	});

	self.courseLengthBlue = ko.computed(function() {
		var s = 0;
		for (var i = 0; i < self.holes().length; i++) {
			s = s + parseInt(self.holes()[i].hole_length_blue());
			}
		return s;
	});

	self.courseLengthYellow = ko.computed(function() {
		var s = 0;
		for (var i = 0; i < self.holes().length; i++) {
			s = s + parseInt(self.holes()[i].hole_length_yellow());
			}
		return s;
	});

	self.courseLengthWhite = ko.computed(function() {
		var s = 0;
		for (var i = 0; i < self.holes().length; i++) {
			s = s + parseInt(self.holes()[i].hole_length_white());
			}
		return s;
	});

	self.getCourseGeneralData = function (course_id) {
		self.resetForm();
		self.showHoleToggle(false);
		var data = { course_id : course_id };
		apexEventProxy.getCourseData(
			{ data : data },
			function (data) {
				self.courseName(data.course.name);
				self.courseAlias(data.course.alias);

				self.courseCrYellowMen(data.course.crYellowMen);
				self.courseSlYellowMen(data.course.slYellowMen);

				self.courseCrYellowLadies(data.course.crYellowLadies);
				self.courseSlYellowLadies(data.course.slYellowLadies);

				self.courseCrBlueMen(data.course.crBlueMen);
				self.courseSlBlueMen(data.course.slBlueMen);

				self.courseCrBlueLadies(data.course.crBlueLadies);
				self.courseSlBlueLadies(data.course.slBlueLadies);

				self.courseCrRedMen(data.course.crRedMen);
				self.courseSlRedMen(data.course.slRedMen);

				self.courseCrRedLadies(data.course.crRedLadies);
				self.courseSlRedLadies(data.course.slRedLadies);

				self.courseCrWhiteMen(data.course.crWhiteMen);
				self.courseSlWhiteMen(data.course.slWhiteMen);
			}
		);
		self.course_id(course_id);
		self.getHoleData(course_id);

	};

	self.getHoleData = function(course_id) {

		self.noOfHoles(0);
		self.holes.removeAll();

		var data = { course_id : course_id };
		apexEventProxy.getHoleData(
			{ data : data },
			function (data) {
				for (var i = 0, m = data.holes.length; i < m; i++) {
					self.holes.push({
						hole_number: ko.observable(data.holes[i].hole_number),
						hole_par: ko.observable(data.holes[i].par),
						hole_hcp: ko.observable(data.holes[i].hcp),
						hole_length_yellow: ko.observable(data.holes[i].length_yellow),
						hole_length_blue: ko.observable(data.holes[i].length_blue),
						hole_length_red: ko.observable(data.holes[i].length_red),
						hole_length_white: ko.observable(data.holes[i].length_white),
					});
				}

			}
//				self.setHoleData();
		);
	};

	self.getCourseList = ko.computed(function (callback) {
		var a;
		apexEventProxy.getCourseList(
		{ a : a },
		function(data) {
//			alert(data.courses[0].name);
			for (var i = 0, m = data.courses.length; i < m; i++) {
				self.courseList.push(data.courses[i]);
				}
			}
		);
	});

	self.getCourseList();

	self.saveGolfer = function (callback) {
		var data = {
			handicap: self.playerExactHcp(),
			tee: self.playerDefaultTee(),
			gender: self.playerGender()
		};
		apexEventProxy.saveGolferData(
			{ data : data },
			function (data) {
				$.mobile.changePage('#f_page', { transition: "slidefade" });
			}
		);
	};

	self.getGolferData = function (callback) {
			var a;
			apexEventProxy.getGolferData(
			{ a : a },
			function(data) {
				self.playerName(data.golfer.name);
				self.playerExactHcp(data.golfer.handicap);
				self.playerDefaultTee(data.golfer.tee);
				self.playerGender(data.golfer.gender);
			}
		);
	};
}

$(document).ready(function() {

	window.vm = new viewModel();
	ko.applyBindings(vm);
});
<|endoftext|>


<commit_before>define([
	'jquery',
], function( $ ) {

	var maroon = '#ad1d45';
	var amaranth = '#d9195c';
	var cerise = '#d62d75';
	var razzmatazz = '#ee2178';
	var illusion = '#f7b0cf';
	var pixels = [
			// Row 1
			{x:1, y: 0, color: maroon},
			{x:2, y: 0, color: amaranth},
			{x:4, y: 0, color: amaranth},
			{x:5, y: 0, color: cerise},

			// Row 2
			{x:0, y: 1, color: amaranth},
			{x:1, y: 1, color: razzmatazz},
			{x:2, y: 1, color: razzmatazz},
			{x:3, y: 1, color: amaranth},
			{x:4, y: 1, color: razzmatazz},
			{x:5, y: 1, color: illusion},
			{x:6, y: 1, color: maroon},

			// Row 3
			{x:0, y: 2, color: cerise},
			{x:1, y: 2, color: amaranth},
			{x:2, y: 2, color: amaranth},
			{x:3, y: 2, color: maroon},
			{x:4, y: 2, color: amaranth},
			{x:5, y: 2, color: cerise},
			{x:6, y: 2, color: maroon},

			// Row 4
			{x:1, y: 3, color: maroon},
			{x:2, y: 3, color: razzmatazz},
			{x:3, y: 3, color: amaranth},
			{x:4, y: 3, color: razzmatazz},
			{x:5, y: 3, color: amaranth},

			// Row 5
			{x:2, y: 4, color: amaranth},
			{x:3, y: 4, color: cerise},
			{x:4, y: 4, color: amaranth},

			// Row 6
			{x:3, y: 5, color: razzmatazz},
		];

	function getRandomElement(array) {
		return array[Math.floor(Math.random() * array.length)];
	}

	var Heart = function(heart) {
		this.heart = $(heart);
		if (Modernizr.svg) {
			this.init();
		}
	};

	Heart.prototype = {
		init: function() {
			this.pixels = pixels.map(function (pixel) {
				return new Rectangle(pixel);
			});
			this.fadePixels();
			this.draw();
			var heart = this;
			window.setInterval(function () {
				heart.moveFadedPixel();
			}, 5000);
		},
		fadePixels: function () {
			var percent = this.heart.data('percent');
			var fadedCount = Math.ceil(this.pixels.length * (100 - percent) / 100);
			for (var i = 0; i < fadedCount; i++) {
				getRandomElement(this.visiblePixels()).hide();
			}
		},
		hiddenPixels: function () {
			return this.pixels.filter(function (p) { return p.isHidden; });
		},
		visiblePixels: function () {
			return this.pixels.filter(function (p) { return !p.isHidden; });
		},
		moveFadedPixel: function () {
			var hiddenPixels = this.hiddenPixels();
			var visiblePixels = this.visiblePixels();
			if (hiddenPixels.length && visiblePixels.length) {
				var oldPixel = getRandomElement(hiddenPixels).show();
				var newPixel = getRandomElement(visiblePixels).hide();
			}
		},
		draw: function() {
			this.pixels.forEach(function (p) {
				document.getElementById('pixels').appendChild(p.element);
			});
		}
	};

	var Rectangle = function (opts) {
	var namespace = 'http://www.w3.org/2000/svg';
		this.element = document.createElementNS(namespace, 'rect');
		this.size = 71;
		this.init(opts);
	};

	Rectangle.prototype = {
		init: function(opts) {
			this.isHidden = false;
			this.setAttr('x', opts.x * this.size);
			this.setAttr('y', opts.y * this.size);
			this.setAttr('width', this.size);
			this.setAttr('height', this.size);
			this.setAttr('fill', opts.color);
		},
		setAttr: function(name, value) {
			this.element.setAttributeNS(null, name, value);
		},
		hide: function () {
			this.isHidden = true;
			this.setAttr('class', 'faded');
		},
		show: function () {
			this.isHidden = false;
			this.setAttr('class', '');
		}
	};

	// Export a single instance of our module:
	return new Heart('.heart');
});
<commit_msg>Fixed selector for fundraising heart JS<commit_after>define([
	'jquery',
], function( $ ) {

	var maroon = '#ad1d45';
	var amaranth = '#d9195c';
	var cerise = '#d62d75';
	var razzmatazz = '#ee2178';
	var illusion = '#f7b0cf';
	var pixels = [
			// Row 1
			{x:1, y: 0, color: maroon},
			{x:2, y: 0, color: amaranth},
			{x:4, y: 0, color: amaranth},
			{x:5, y: 0, color: cerise},

			// Row 2
			{x:0, y: 1, color: amaranth},
			{x:1, y: 1, color: razzmatazz},
			{x:2, y: 1, color: razzmatazz},
			{x:3, y: 1, color: amaranth},
			{x:4, y: 1, color: razzmatazz},
			{x:5, y: 1, color: illusion},
			{x:6, y: 1, color: maroon},

			// Row 3
			{x:0, y: 2, color: cerise},
			{x:1, y: 2, color: amaranth},
			{x:2, y: 2, color: amaranth},
			{x:3, y: 2, color: maroon},
			{x:4, y: 2, color: amaranth},
			{x:5, y: 2, color: cerise},
			{x:6, y: 2, color: maroon},

			// Row 4
			{x:1, y: 3, color: maroon},
			{x:2, y: 3, color: razzmatazz},
			{x:3, y: 3, color: amaranth},
			{x:4, y: 3, color: razzmatazz},
			{x:5, y: 3, color: amaranth},

			// Row 5
			{x:2, y: 4, color: amaranth},
			{x:3, y: 4, color: cerise},
			{x:4, y: 4, color: amaranth},

			// Row 6
			{x:3, y: 5, color: razzmatazz},
		];

	function getRandomElement(array) {
		return array[Math.floor(Math.random() * array.length)];
	}

	var Heart = function(heart) {
		this.heart = $(heart);
		if (Modernizr.svg) {
			this.init();
		}
	};

	Heart.prototype = {
		init: function() {
			this.pixels = pixels.map(function (pixel) {
				return new Rectangle(pixel);
			});
			this.fadePixels();
			this.draw();
			var heart = this;
			window.setInterval(function () {
				heart.moveFadedPixel();
			}, 5000);
		},
		fadePixels: function () {
			var percent = this.heart.data('percent');
			var fadedCount = Math.ceil(this.pixels.length * (100 - percent) / 100);
			for (var i = 0; i < fadedCount; i++) {
				getRandomElement(this.visiblePixels()).hide();
			}
		},
		hiddenPixels: function () {
			return this.pixels.filter(function (p) { return p.isHidden; });
		},
		visiblePixels: function () {
			return this.pixels.filter(function (p) { return !p.isHidden; });
		},
		moveFadedPixel: function () {
			var hiddenPixels = this.hiddenPixels();
			var visiblePixels = this.visiblePixels();
			if (hiddenPixels.length && visiblePixels.length) {
				var oldPixel = getRandomElement(hiddenPixels).show();
				var newPixel = getRandomElement(visiblePixels).hide();
			}
		},
		draw: function() {
			this.pixels.forEach(function (p) {
				document.getElementById('pixels').appendChild(p.element);
			});
		}
	};

	var Rectangle = function (opts) {
	var namespace = 'http://www.w3.org/2000/svg';
		this.element = document.createElementNS(namespace, 'rect');
		this.size = 71;
		this.init(opts);
	};

	Rectangle.prototype = {
		init: function(opts) {
			this.isHidden = false;
			this.setAttr('x', opts.x * this.size);
			this.setAttr('y', opts.y * this.size);
			this.setAttr('width', this.size);
			this.setAttr('height', this.size);
			this.setAttr('fill', opts.color);
		},
		setAttr: function(name, value) {
			this.element.setAttributeNS(null, name, value);
		},
		hide: function () {
			this.isHidden = true;
			this.setAttr('class', 'faded');
		},
		show: function () {
			this.isHidden = false;
			this.setAttr('class', '');
		}
	};

	// Export a single instance of our module:
	return new Heart('.fundraising-heart');
});
<|endoftext|>


<commit_before>// Inserts shortcut buttons after all of the following:
//     <input type="text" class="vDateField">
//     <input type="text" class="vTimeField">

var DateTimeShortcuts = {
    calendars: [],
    calendarInputs: [],
    clockInputs: [],
    calendarDivName1: 'calendarbox', // name of calendar
 that gets toggled
    calendarDivName2: 'calendarin',  // name of
 that contains calendar
    clockDivName: 'clockbox',        // name of clock
 that gets toggled

    init: function() {
        var inputs = document.getElementsByTagName('input');
        for (var i=0; i<inputs.length; i++) {
            var inp = inputs[i];
            if (inp.getAttribute('type') == 'text' && inp.className.match(/vTimeField/)) {
                DateTimeShortcuts.addClock(inp);
            }
            else if (inp.getAttribute('type') == 'text' && inp.className.match(/vDateField/)) {
                DateTimeShortcuts.addCalendar(inp);
            }
        }
    },

    // Add clock widget to a given field
    addClock: function(inp) {
        var num = DateTimeShortcuts.clockInputs.length;
        DateTimeShortcuts.clockInputs[num] = inp;

        // Shortcut links (clock icon and "Now" link)
        var shortcuts_span = document.createElement('span');
        inp.parentNode.insertBefore(shortcuts_span, inp.nextSibling);
        var now_link = document.createElement('a');
        now_link.setAttribute('href', "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", new Date().getHourMinute());");
        now_link.appendChild(document.createTextNode('Now'));
        var clock_link = document.createElement('a');
        clock_link.setAttribute('href', 'javascript:DateTimeShortcuts.openClock(' + num + ');');
        quickElement('img', clock_link, '', 'src', 'http://media.ljworld.com/img/admin/icon_clock.gif', 'alt', 'Clock');
        shortcuts_span.appendChild(document.createTextNode('\240'));
        shortcuts_span.appendChild(now_link);
        shortcuts_span.appendChild(document.createTextNode('\240|\240'));
        shortcuts_span.appendChild(clock_link);

        // Create clock link div
        //
        // Markup looks like:
        //

        //
Choose a time

        //

        //
Now

        //
Midnight

        //
6 a.m.

        //
Noon

        //

        //
Cancel

        //

        var clock_box = document.createElement('div');
        clock_box.style.display = 'none';
        clock_box.style.position = 'absolute';
        clock_box.style.left = findPosX(clock_link) + 17 + 'px';
        clock_box.style.top = findPosY(clock_link) - 30 + 'px';
        clock_box.className = 'clockbox module';
        clock_box.setAttribute('id', DateTimeShortcuts.clockDivName + num);
        document.body.appendChild(clock_box);
        addEvent(clock_box, 'click', DateTimeShortcuts.cancelEventPropagation);

        quickElement('h2', clock_box, 'Choose a time');
        time_list = quickElement('ul', clock_box, '', 'class', 'timelist');
        quickElement("a", quickElement("li", time_list, ""), "Now", "href", "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", new Date().getHourMinute());")
        quickElement("a", quickElement("li", time_list, ""), "Midnight", "href", "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", '00:00');")
        quickElement("a", quickElement("li", time_list, ""), "6 a.m.", "href", "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", '06:00');")
        quickElement("a", quickElement("li", time_list, ""), "Noon", "href", "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", '12:00');")

        cancel_p = quickElement('p', clock_box, '', 'class', 'calendar-cancel');
        quickElement('a', cancel_p, 'Cancel', 'href', 'javascript:DateTimeShortcuts.dismissClock(' + num + ');');
    },

    openClock: function(num) {
        document.getElementById(DateTimeShortcuts.clockDivName + num).style.display = 'block';
        addEvent(window, 'click', function() { DateTimeShortcuts.dismissClock(num); return true; });
    },

    dismissClock: function(num) {
       document.getElementById(DateTimeShortcuts.clockDivName + num).style.display = 'none';
       window.onclick = null;
    },

    handleClockQuicklink: function(num, val) {
       DateTimeShortcuts.clockInputs[num].value = val;
       DateTimeShortcuts.dismissClock(num);
    },

    // Add calendar widget to a given field.
    addCalendar: function(inp) {
        var num = DateTimeShortcuts.calendars.length;

        DateTimeShortcuts.calendarInputs[num] = inp;

        // Shortcut links (calendar icon and "Today" link)
        var shortcuts_span = document.createElement('span');
        inp.parentNode.insertBefore(shortcuts_span, inp.nextSibling);
        var today_link = document.createElement('a');
        today_link.setAttribute('href', 'javascript:DateTimeShortcuts.handleCalendarQuickLink(' + num + ', 0);');
        today_link.appendChild(document.createTextNode('Today'));
        var cal_link = document.createElement('a');
        cal_link.setAttribute('href', 'javascript:DateTimeShortcuts.openCalendar(' + num + ');');
        quickElement('img', cal_link, '', 'src', 'http://media.ljworld.com/img/admin/icon_calendar.gif', 'alt', 'Calendar');
        shortcuts_span.appendChild(document.createTextNode('\240'));
        shortcuts_span.appendChild(today_link);
        shortcuts_span.appendChild(document.createTextNode('\240|\240'));
        shortcuts_span.appendChild(cal_link);

        // Create calendarbox div.
        //
        // Markup looks like:
        //
        //

        //

        //           ‹
        //           › February 2003
        //

        //

        //
        //

        //

        //          Yesterday | Today | Tomorrow
        //

        //
Cancel

        //

        var cal_box = document.createElement('div');
        cal_box.style.display = 'none';
        cal_box.style.position = 'absolute';
        cal_box.style.left = findPosX(cal_link) + 17 + 'px';
        cal_box.style.top = findPosY(cal_link) - 75 + 'px';
        cal_box.className = 'calendarbox module';
        cal_box.setAttribute('id', DateTimeShortcuts.calendarDivName1 + num);
        document.body.appendChild(cal_box);
        addEvent(cal_box, 'click', DateTimeShortcuts.cancelEventPropagation);

        // next-prev links
        var cal_nav = quickElement('div', cal_box, '');
        quickElement('a', cal_nav, '<', 'class', 'calendarnav-previous', 'href', 'javascript:DateTimeShortcuts.drawPrev('+num+');');
        quickElement('a', cal_nav, '>', 'class', 'calendarnav-next',     'href', 'javascript:DateTimeShortcuts.drawNext('+num+');');
        cal_box.appendChild(cal_nav);

        // main box
        var cal_main = quickElement('div', cal_box, '', 'id', DateTimeShortcuts.calendarDivName2 + num);
        cal_main.className = 'calendar';
        DateTimeShortcuts.calendars[num] = new Calendar(DateTimeShortcuts.calendarDivName2 + num, DateTimeShortcuts.handleCalendarCallback(num));
        DateTimeShortcuts.calendars[num].drawCurrent();

        // calendar shortcuts
        var shortcuts = quickElement('div', cal_box, '', 'class', 'calendar-shortcuts');
        quickElement('a', shortcuts, 'Yesterday', 'href', 'javascript:DateTimeShortcuts.handleCalendarQuickLink(' + num + ', -1);');
        shortcuts.appendChild(document.createTextNode('\240|\240'));
        quickElement('a', shortcuts, 'Today', 'href', 'javascript:DateTimeShortcuts.handleCalendarQuickLink(' + num + ', 0);');
        shortcuts.appendChild(document.createTextNode('\240|\240'));
        quickElement('a', shortcuts, 'Tomorrow', 'href', 'javascript:DateTimeShortcuts.handleCalendarQuickLink(' + num + ', +1);');

        // cancel bar
        var cancel_p = quickElement('p', cal_box, '', 'class', 'calendar-cancel');
        quickElement('a', cancel_p, 'Cancel', 'href', 'javascript:DateTimeShortcuts.dismissCalendar(' + num + ');');
    },

    openCalendar: function(num) {
        document.getElementById(DateTimeShortcuts.calendarDivName1+num).style.display = 'block';
        addEvent(window, 'click', function() { DateTimeShortcuts.dismissCalendar(num); return true; });
    },

    dismissCalendar: function(num) {
        document.getElementById(DateTimeShortcuts.calendarDivName1+num).style.display = 'none';
    },

    drawPrev: function(num) {
        DateTimeShortcuts.calendars[num].drawPreviousMonth();
    },

    drawNext: function(num) {
        DateTimeShortcuts.calendars[num].drawNextMonth();
    },

    handleCalendarCallback: function(num) {
        return "function(y, m, d) { DateTimeShortcuts.calendarInputs["+num+"].value = y+'-'+m+'-'+d; document.getElementById(DateTimeShortcuts.calendarDivName1+"+num+").style.display='none';}";
    },

    handleCalendarQuickLink: function(num, offset) {
       var d = new Date();
       d.setDate(d.getDate() + offset)
       DateTimeShortcuts.calendarInputs[num].value = d.getISODate();
       DateTimeShortcuts.dismissCalendar(num);
    },

    cancelEventPropagation: function(e) {
        if (!e) var e = window.event;
        e.cancelBubble = true;
        if (e.stopPropagation) e.stopPropagation();
    }

}

addEvent(window, 'load', DateTimeShortcuts.init);
<commit_msg>Removed media.ljworld.com reference from admin_media/js/admin/DateTimeShortcuts.js<commit_after>// Inserts shortcut buttons after all of the following:
//     <input type="text" class="vDateField">
//     <input type="text" class="vTimeField">

var DateTimeShortcuts = {
    calendars: [],
    calendarInputs: [],
    clockInputs: [],
    calendarDivName1: 'calendarbox', // name of calendar
 that gets toggled
    calendarDivName2: 'calendarin',  // name of
 that contains calendar
    clockDivName: 'clockbox',        // name of clock
 that gets toggled
    admin_media_prefix: '',
    init: function() {
        // Deduce admin_media_prefix by looking at the


<commit_before>(function(){
    "use strict";
    angular
        .module("dockyard.core")
        .controller("githubOauthCtrl", ["$location", "dataService", sidebarService, githubOauthCtrl]);

    /**************************
     *        Controllers      *
     ***************************/
    function githubOauthCtrl($location, dataService) {
        var vm  = this;

        sidebarService.hide();

        active();

        function active() {
            dataService.githubOauth().then(function (msg) {
                //TODO github oauth
            })
        }

    } // github oauth ctrl end

})();<commit_msg>Fix oauth sidebarService<commit_after>(function(){
    "use strict";
    angular
        .module("dockyard.core")
        .controller("githubOauthCtrl", ["$location", "dataService", sidebarService, githubOauthCtrl]);

    /**************************
     *        Controllers      *
     ***************************/
    function githubOauthCtrl($location, dataService, sidebarService) {
        var vm  = this;

        sidebarService.hide();

        active();

        function active() {
            dataService.githubOauth().then(function (msg) {
                //TODO github oauth
            })
        }

    } // github oauth ctrl end

})();<|endoftext|>