<commit_before>
window.current_plot_data=null;
window.current_plot_obj=null;
window.current_color_schemes=null;
window.current_instrument_list=null;
window.current_chemistries_list=null;
window.current_months_list=null;

$(function(){
    init_page_js();
    refresh_plot();
});

function refresh_plot(){
    var params=get_parameters();
    if (window.current_plot_data==null){
        get_plot_data(search_string=params[0], key=params[2], name=params[3], display_by=params[1], inst_type_filter=params[4], inst_filter=params[5], color_type=params[6]);
    }else{
        make_plot(key=params[2], name=params[3], display_by=params[1], inst_type_filter=params[4], inst_filter=params[5],  color_type=params[6]);
    }

}
function make_plot(key, name, display_by, filter_inst_type, filter_inst, color_type){
    var toplot={
        chart: {
            type : 'column'
        },
        title: {
            text : name+' of the recent flowcells'
        },
        legend : {
            enabled : false
        },
        yAxis: {
            min : 0,
            title : {
              text : name
            }
        },
        plotOptions : {
            series : {
                turboThreshold: 0
            },
            column : {
                groupPadding: 0.1
            }

        },
        tooltip: {
            useHTML: true,
            headerFormat: '\u25CF{point.key}
',
            pointFormat: '{series.name} : {point.y}'
        },
        credits: {
            enabled : false
        },
        xAxis: {
            type: 'category',
            labels: {
                rotation: -90,
                    style: {
                        fontSize: '9px',
                        fontFamily: 'Verdana, sans-serif'
                    }
            }
        },
        series: [{
            name : name,
            data:[]
        }],
    };
    serie=build_series(window.current_plot_data, key, name, display_by, filter_inst_type, filter_inst,  color_type);
    toplot.series[0].data=serie;
    $("#main_plot").highcharts(toplot);
    window.current_plot_obj=toplot;
}

function build_series(data, key, name, display_by, filter_inst_type, filter_inst,  color_type){
    var serie=[];
    var tmp=[];
    var col_color="";
    var flowcell_link="/flowcells"
    for (d in data){
        tmp=data[d].id.split('_');
        flowcell_link="/flowcells/"+tmp[0]+'_'+tmp[tmp.length-1];
        if (color_type=='chemver'){
            col_color=color_by_chemistry(data[d].instrument.substr(0,1)+data[d].cver);
        }else if (color_type == 'inst'){
            col_color=color_by_instrument(data[d].instrument);
        }else if (color_type == 'month'){
            col_color=color_by_month(data[d].id);
        }else{
            col_color=color_by_type(data[d].instrument);
        }
        if (filter_inst.length!=0){
            var skip=false;
            for (i in filter_inst){
                if (data[d].instrument.indexOf(filter_inst[i]) != -1){
                    skip=true;
                }
            }
            if (skip){
                continue;
            }
        }
        if (filter_inst_type.length!=0){
            var skip=false;
            for (i in filter_inst_type){
                if (data[d].instrument.indexOf(filter_inst_type[i]) != -1){
                    skip=true;
                }
            }
            if (skip){
                continue;
            }
        }
        if (display_by == "lane"){
            for (l in data[d].lanes){
                tmp=data[d].id.split('_');
                col_name=tmp[0]+'_'+tmp[tmp.length-1]+":"+data[d].lanes[l].lane;
                col={
                    name : col_name,
                    y : data[d].lanes[l][key],
                    color : col_color,
                    events : {
                        click : function(){window.open(flowcell_link)}
                    }
                };
                serie.push(col);
            }
        }else {
            //Default : by flowcell
            tmp=data[d].id.split('_');
            col_name=tmp[0]+'_'+tmp[tmp.length-1];
            col={
                name : col_name,
                y : data[d][key],
                color : col_color,
                events : {
                    click : function(){window.open(flowcell_link)}
                }
            };
            serie.push(col);
        }
    }
    return serie;
}

function get_plot_data(search_string="", key, name, display_by, filter_inst_type, filter_inst,  color_type){
        $.getJSON('/api/v1/flowcell_yield/'+search_string, function(data) {
            //update plot data
            window.current_plot_data=data;
            //update instrument list
            update_instrument_list();
            //update chemistry list
            update_chemistries_list();
            //update months list
            update_months_list();
            //update color schemes
            update_color_schemes(data);
            //set the instrument filters
            update_instrument_filters();
            //plot the damn data
            make_plot(key, name, display_by, filter_inst_type, color_type);
        });
}
function color_by_instrument(instrument){
    return current_color_schemes[1](window.current_instrument_list.indexOf(instrument)).hex();
}

function color_by_type(instrument){
    if (instrument.indexOf('E') != -1){
        return current_color_schemes[0](0).hex();
    } else if (instrument.indexOf('D') != -1){
        return current_color_schemes[0](1).hex();
    }else if (instrument.indexOf('M') != -1){
        return current_color_schemes[0](2).hex();
    }else{
      return "#c3c3c3";
    }
}
function color_by_month(id){
    return current_color_schemes[3](window.current_months_list.indexOf(id.substr(0,4))).hex()
}

function color_by_chemistry(chem){
    var id = Math.round(window.current_chemistries_list.indexOf(chem)*window.current_instrument_list.length/window.current_chemistries_list.length);
    return current_color_schemes[2](id).hex();
}

function get_parameters(){
     //first, the search string
     var search_string;
     var m_d_y;
     var first_half;
     var first_date;
     var second_half;
     var second_date;
     var dp=$('#inp_date_1').val();
     if (dp != ''){
         y_m_d=dp.split('-');
         first_half=y_m_d[0].substr(2,2) + y_m_d[1] + y_m_d[2];
     }else{
         first_date=new Date();
         first_date.setYear(first_date.getYear()-1);
         first_half=first_date.toISOString().substr(2,2) + first_date.toISOString().substr(5,2) + first_date.toISOString().substr(8,2);
     }
     dp=$('#inp_date_2').val();
     if (dp != ''){
        y_m_d=dp.split('-');
        second_half=y_m_d[0].substr(2,2) + y_m_d[1] + y_m_d[2];
     }else{
        second_date=new Date();
        second_half=second_date.toISOString().substr(2,2) + second_date.toISOString().substr(5,2) + second_date.toISOString().substr(8,2);
     }
     search_string=first_half + '-' + second_half;

     //then, the display type
     var display_type;
     if ($("#display_by_flowcell").hasClass('active')){
         display_type='flowcell'
     }else if($("#display_by_lane").hasClass('active')){
         display_type='lane'
     }
     //then, they key and name to display
     var key = $( "#key_select_form option:selected" ).val();
     var name= $( "#key_select_form option:selected" ).text();

     //The instrument_type_filter
     var inst_type_filter=[];
     $(".filter_inst_type").each(function(){
         if (! $(this).prop("checked")){
             inst_type_filter.push($(this).val());
         }
     });

     //the instrument filter
     var inst_filter=[];
     $(".filter_insts.disabled").each(function(){
         inst_filter.push($(this).attr('id').split('_')[2]);
     });
     //color type
     var color_by=$("#color_select option:selected").val();
     var ret=[search_string, display_type, key, name, inst_type_filter, inst_filter, color_by];

     return ret;
}

function init_page_js(){
    $('#datepick1').datepicker({autoclose: true,
    format: 'yyyy-mm-dd',
    todayBtn: true,
    todayHighlight: true,
    weekStart: 1,
    daysOfWeekHighlighted: "0,6" });
    $('#datepick2').datepicker({autoclose: true,
    format: 'yyyy-mm-dd',
    todayBtn: true,
    todayHighlight: true,
    weekStart: 1,
    daysOfWeekHighlighted: "0,6" });
     var my_date=new Date();
     $('#inp_date_2').val(my_date.toISOString().substr(0,10));
     my_date.setYear(my_date.getFullYear()-1);
     $('#inp_date_1').val(my_date.toISOString().substr(0,10));
    $('#submit_interval').click(function(e){
     e.preventDefault();
     window.current_plot_data=null;
     refresh_plot();
    });
    $("#display_type_buttons .btn").click(function(e){
        e.preventDefault();
        //datepicker messes up by adding eventlisteners to all buttons.
        e.stopImmediatePropagation()
        $("#display_type_buttons .btn").removeClass('active');
        $(this).addClass("active");
        if ($(this).text() == 'Lane'){
            $(".key_select_lane").each(function(){
                $(this).prop( "disabled", false);
            });
        } else{
            $(".key_select_lane").each(function(){
                $(this).prop( "disabled", true);
            });
        }
        refresh_plot();
    });
    $("#key_select_form").change(function(e){
        e.preventDefault();
        e.stopImmediatePropagation()
        refresh_plot();

    });
    $(".filter_inst_type").each(function(e){
        $(this).prop('checked', true);
    });
    $(".filter_inst_type").change(function(e){
        e.stopImmediatePropagation()
        refresh_plot();
    });
    $("#color_select").change(function(e){
        e.stopImmediatePropagation()
        refresh_plot();
    });
    refresh_plot();
}

function update_months_list(){
    window.current_months_list=[];
    for (d in window.current_plot_data){
        if (window.current_months_list.indexOf(window.current_plot_data[d].id.substr(0,4)) == -1){
            window.current_months_list.push(window.current_plot_data[d].id.substr(0,4));
        }
    }
}
function update_color_schemes(){
    var inst_type_cs=chroma.scale(['008ae5', 'green','pink']).domain([0, 2]);
    var chem_cs=chroma.scale(['pink', 'lightblue']).domain([0, 2]);
    var inst_cs=chroma.scale(['lightgreen', 'blue', 'red']).domain([0, window.current_instrument_list.length-1]);
    var month_cs=chroma.scale(['yellow', 'lightblue', 'pink', 'orange']).domain([0,window.current_months_list.length-1]);
    window.current_color_schemes=[inst_type_cs, inst_cs, chem_cs, month_cs];
}
function update_chemistries_list(){
    window.current_chemistries_list=[];
    var version="";
    for (d in window.current_plot_data){
        version = window.current_plot_data[d].instrument.substr(0,1) + window.current_plot_data[d].cver;
        if ( window.current_chemistries_list.indexOf(version) == -1){
            window.current_chemistries_list.push(version);
        }
    }
}

function update_instrument_list(){
    window.current_instrument_list=[];
    for (d in window.current_plot_data){
        if (window.current_instrument_list.indexOf(window.current_plot_data[d].instrument) == -1){
            window.current_instrument_list.push(window.current_plot_data[d].instrument);
        }
    }
}
function update_instrument_filters(){
    var html='
Filter out ';
    var my_inst_id='';
    var my_inst_name='';
    $.getJSON("/api/v1/instrument_names", function(data){
        for (i in window.current_instrument_list){
            my_inst_id=window.current_instrument_list[i];
            html+='
';
            for (d in data){
            my_inst_name='';
                if(my_inst_id.indexOf(data[d].key)!= -1){
                    my_inst_name=data[d].value;
                    break;
                }
            }
            if (my_inst_name==''){
                my_inst_name=my_inst_id;
            }
            html+=my_inst_name + "
";

            html+=" ";
        }
        html+="
";
        $("#inst_filter_div").html(html);

        $(".filter_insts").click(function(e){
            e.stopImmediatePropagation()
            if($(this).css('border-left').indexOf('rgb(195, 195, 195)')== -1){
                $(this).css('border-left', '5px solid #c3c3c3');
                $(this).addClass('disabled');
            }else{
                $(this).css('border-left', '5px solid '+color_by_instrument($(this).attr('id').split('_')[2]));
                $(this).removeClass('disabled');
            }
            refresh_plot();
        });
    });

}
<commit_msg>some fix that I forgot about<commit_after>
window.current_plot_data=null;
window.current_plot_obj=null;
window.current_color_schemes=null;
window.current_instrument_list=null;
window.current_chemistries_list=null;
window.current_months_list=null;

$(function(){
    init_page_js();
    refresh_plot();
});

function refresh_plot(){
    var params=get_parameters();
    if (window.current_plot_data==null){
        get_plot_data(search_string=params[0], key=params[2], name=params[3], display_by=params[1], inst_type_filter=params[4], inst_filter=params[5], color_type=params[6]);
    }else{
        make_plot(key=params[2], name=params[3], display_by=params[1], inst_type_filter=params[4], inst_filter=params[5],  color_type=params[6]);
    }

}
function make_plot(key, name, display_by, filter_inst_type, filter_inst, color_type){
    var toplot={
        chart: {
            type : 'column'
        },
        title: {
            text : name+' of the recent flowcells'
        },
        legend : {
            enabled : false
        },
        yAxis: {
            min : 0,
            title : {
              text : name
            }
        },
        plotOptions : {
            series : {
                turboThreshold: 0
            },
            column : {
                groupPadding: 0.1
            }

        },
        tooltip: {
            useHTML: true,
            headerFormat: '\u25CF{point.key}
',
            pointFormat: '{series.name} : {point.y}'
        },
        credits: {
            enabled : false
        },
        xAxis: {
            type: 'category',
            labels: {
                rotation: -90,
                    style: {
                        fontSize: '9px',
                        fontFamily: 'Verdana, sans-serif'
                    }
            }
        },
        series: [{
            name : name,
            data:[]
        }],
    };
    serie=build_series(window.current_plot_data, key, name, display_by, filter_inst_type, filter_inst,  color_type);
    toplot.series[0].data=serie;
    $("#main_plot").highcharts(toplot);
    window.current_plot_obj=toplot;
}

function build_series(data, key, name, display_by, filter_inst_type, filter_inst,  color_type){
    var serie=[];
    var tmp=[];
    var col_color="";
    var flowcell_link="/flowcells"
    for (d in data){
        tmp=data[d].id.split('_');
        flowcell_link="/flowcells/"+tmp[0]+'_'+tmp[tmp.length-1];
        if (color_type=='chemver'){
            col_color=color_by_chemistry(data[d].instrument.substr(0,1)+data[d].cver);
        }else if (color_type == 'inst'){
            col_color=color_by_instrument(data[d].instrument);
        }else if (color_type == 'month'){
            col_color=color_by_month(data[d].id);
        }else{
            col_color=color_by_type(data[d].instrument);
        }
        if (filter_inst.length!=0){
            var skip=false;
            for (i in filter_inst){
                if (data[d].instrument.indexOf(filter_inst[i]) != -1){
                    skip=true;
                }
            }
            if (skip){
                continue;
            }
        }
        if (filter_inst_type.length!=0){
            var skip=false;
            for (i in filter_inst_type){
                if (data[d].instrument.indexOf(filter_inst_type[i]) != -1){
                    skip=true;
                }
            }
            if (skip){
                continue;
            }
        }
        if (display_by == "lane"){
            var value=0;
            for (l in data[d].lanes){
                tmp=data[d].id.split('_');
                col_name=tmp[0]+'_'+tmp[tmp.length-1]+":"+data[d].lanes[l].lane;
                if (key in data[d].lanes[l]){
                    value=data[d].lanes[l][key];
                }
                col={
                    name : col_name,
                    y : value,
                    color : col_color,
                    events : {
                        click : function(){window.open(flowcell_link)}
                    }
                };
                serie.push(col);
            }
        }else {
            //Default : by flowcell
            tmp=data[d].id.split('_');
            col_name=tmp[0]+'_'+tmp[tmp.length-1];
            col={
                name : col_name,
                y : data[d][key],
                color : col_color,
                events : {
                    click : function(){window.open(flowcell_link)}
                }
            };
            serie.push(col);
        }
    }
    return serie;
}

function get_plot_data(search_string="", key, name, display_by, filter_inst_type, filter_inst,  color_type){
        $.getJSON('/api/v1/flowcell_yield/'+search_string, function(data) {
            //update plot data
            window.current_plot_data=data;
            //update instrument list
            update_instrument_list();
            //update chemistry list
            update_chemistries_list();
            //update months list
            update_months_list();
            //update color schemes
            update_color_schemes(data);
            //set the instrument filters
            update_instrument_filters();
            //plot the damn data
            make_plot(key, name, display_by, filter_inst_type, color_type);
        });
}
function color_by_instrument(instrument){
    return current_color_schemes[1](window.current_instrument_list.indexOf(instrument)).hex();
}

function color_by_type(instrument){
    if (instrument.indexOf('E') != -1){
        return current_color_schemes[0](0).hex();
    } else if (instrument.indexOf('D') != -1){
        return current_color_schemes[0](1).hex();
    }else if (instrument.indexOf('M') != -1){
        return current_color_schemes[0](2).hex();
    }else{
      return "#c3c3c3";
    }
}
function color_by_month(id){
    return current_color_schemes[3](window.current_months_list.indexOf(id.substr(0,4))).hex()
}

function color_by_chemistry(chem){
    var id = Math.round(window.current_chemistries_list.indexOf(chem)*window.current_instrument_list.length/window.current_chemistries_list.length);
    return current_color_schemes[2](id).hex();
}

function get_parameters(){
     //first, the search string
     var search_string;
     var m_d_y;
     var first_half;
     var first_date;
     var second_half;
     var second_date;
     var dp=$('#inp_date_1').val();
     if (dp != ''){
         y_m_d=dp.split('-');
         first_half=y_m_d[0].substr(2,2) + y_m_d[1] + y_m_d[2];
     }else{
         first_date=new Date();
         first_date.setYear(first_date.getYear()-1);
         first_half=first_date.toISOString().substr(2,2) + first_date.toISOString().substr(5,2) + first_date.toISOString().substr(8,2);
     }
     dp=$('#inp_date_2').val();
     if (dp != ''){
        y_m_d=dp.split('-');
        second_half=y_m_d[0].substr(2,2) + y_m_d[1] + y_m_d[2];
     }else{
        second_date=new Date();
        second_half=second_date.toISOString().substr(2,2) + second_date.toISOString().substr(5,2) + second_date.toISOString().substr(8,2);
     }
     search_string=first_half + '-' + second_half;

     //then, the display type
     var display_type;
     if ($("#display_by_flowcell").hasClass('active')){
         display_type='flowcell'
     }else if($("#display_by_lane").hasClass('active')){
         display_type='lane'
     }
     //then, they key and name to display
     var key = $( "#key_select_form option:selected" ).val();
     var name= $( "#key_select_form option:selected" ).text();

     //The instrument_type_filter
     var inst_type_filter=[];
     $(".filter_inst_type").each(function(){
         if (! $(this).prop("checked")){
             inst_type_filter.push($(this).val());
         }
     });

     //the instrument filter
     var inst_filter=[];
     $(".filter_insts.disabled").each(function(){
         inst_filter.push($(this).attr('id').split('_')[2]);
     });
     //color type
     var color_by=$("#color_select option:selected").val();
     var ret=[search_string, display_type, key, name, inst_type_filter, inst_filter, color_by];

     return ret;
}

function init_page_js(){
    $('#datepick1').datepicker({autoclose: true,
    format: 'yyyy-mm-dd',
    todayBtn: true,
    todayHighlight: true,
    weekStart: 1,
    daysOfWeekHighlighted: "0,6" });
    $('#datepick2').datepicker({autoclose: true,
    format: 'yyyy-mm-dd',
    todayBtn: true,
    todayHighlight: true,
    weekStart: 1,
    daysOfWeekHighlighted: "0,6" });
     var my_date=new Date();
     $('#inp_date_2').val(my_date.toISOString().substr(0,10));
     my_date.setYear(my_date.getFullYear()-1);
     $('#inp_date_1').val(my_date.toISOString().substr(0,10));
    $('#submit_interval').click(function(e){
     e.preventDefault();
     window.current_plot_data=null;
     refresh_plot();
    });
    $("#display_type_buttons .btn").click(function(e){
        e.preventDefault();
        //datepicker messes up by adding eventlisteners to all buttons.
        e.stopImmediatePropagation()
        $("#display_type_buttons .btn").removeClass('active');
        $(this).addClass("active");
        if ($(this).text() == 'Lane'){
            $(".key_select_lane").each(function(){
                $(this).prop( "disabled", false);
            });
        } else{
            $(".key_select_lane").each(function(){
                $(this).prop( "disabled", true);
            });
        }
        refresh_plot();
    });
    $("#key_select_form").change(function(e){
        e.preventDefault();
        e.stopImmediatePropagation()
        refresh_plot();

    });
    $(".filter_inst_type").each(function(e){
        $(this).prop('checked', true);
    });
    $(".filter_inst_type").change(function(e){
        e.stopImmediatePropagation()
        refresh_plot();
    });
    $("#color_select").change(function(e){
        e.stopImmediatePropagation()
        refresh_plot();
    });
    refresh_plot();
}

function update_months_list(){
    window.current_months_list=[];
    for (d in window.current_plot_data){
        if (window.current_months_list.indexOf(window.current_plot_data[d].id.substr(0,4)) == -1){
            window.current_months_list.push(window.current_plot_data[d].id.substr(0,4));
        }
    }
}
function update_color_schemes(){
    var inst_type_cs=chroma.scale(['008ae5', 'green','pink']).domain([0, 2]);
    var chem_cs=chroma.scale(['pink', 'lightblue']).domain([0, 2]);
    var inst_cs=chroma.scale(['lightgreen', 'blue', 'red']).domain([0, window.current_instrument_list.length-1]);
    var month_cs=chroma.scale(['yellow', 'lightblue', 'pink', 'orange']).domain([0,window.current_months_list.length-1]);
    window.current_color_schemes=[inst_type_cs, inst_cs, chem_cs, month_cs];
}
function update_chemistries_list(){
    window.current_chemistries_list=[];
    var version="";
    for (d in window.current_plot_data){
        version = window.current_plot_data[d].instrument.substr(0,1) + window.current_plot_data[d].cver;
        if ( window.current_chemistries_list.indexOf(version) == -1){
            window.current_chemistries_list.push(version);
        }
    }
}

function update_instrument_list(){
    window.current_instrument_list=[];
    for (d in window.current_plot_data){
        if (window.current_instrument_list.indexOf(window.current_plot_data[d].instrument) == -1){
            window.current_instrument_list.push(window.current_plot_data[d].instrument);
        }
    }
}
function update_instrument_filters(){
    var html='
Filter out ';
    var my_inst_id='';
    var my_inst_name='';
    $.getJSON("/api/v1/instrument_names", function(data){
        for (i in window.current_instrument_list){
            my_inst_id=window.current_instrument_list[i];
            html+='
';
            for (d in data){
            my_inst_name='';
                if(my_inst_id.indexOf(data[d].key)!= -1){
                    my_inst_name=data[d].value;
                    break;
                }
            }
            if (my_inst_name==''){
                my_inst_name=my_inst_id;
            }
            html+=my_inst_name + "
";

            html+=" ";
        }
        html+="
";
        $("#inst_filter_div").html(html);

        $(".filter_insts").click(function(e){
            e.stopImmediatePropagation()
            if($(this).css('border-left').indexOf('rgb(195, 195, 195)')== -1){
                $(this).css('border-left', '5px solid #c3c3c3');
                $(this).addClass('disabled');
            }else{
                $(this).css('border-left', '5px solid '+color_by_instrument($(this).attr('id').split('_')[2]));
                $(this).removeClass('disabled');
            }
            refresh_plot();
        });
    });

}
<|endoftext|>


<commit_before>// Arbitrary numbers chosen to ensure Long Portrait mode fits into Chrome on Android.
// Firefox uses less vertical space for the URL bar so Long Portrait will be available in both.
// 270 is six times 45, as board is twelve squares and logo is two.
// 73 is the remaining 3.24444 squares that can fit into the Chrome window.
// Scaled up until all values are integers for ease of reading.
const THRESHOLD_LongPortraitFitToWidth = 270/(45+270+73);
const THRESHOLD_LongPortraitFitToHeight = (45+270)/(45+270+73);
const THRESHOLD_ShortPortraitFitToWidth = (45+270)/(270+73);
const THRESHOLD_ShortPortraitFitToHeight = 1;
const THRESHOLD_ShortLandscapeFitToWidth = (270+73)/(45+270);
const THRESHOLD_ShortLandscapeFitToHeight = (45+270+73)/(45+270);
const THRESHOLD_LongLandscapeFitToWidth = (45+270+73)/270;

function reorganise() {
  ratio = window.innerWidth / window.innerHeight;
  if (ratio < THRESHOLD_LongPortraitFitToWidth) {arrange_LongPortraitFitToWidth();
  } else if (ratio < THRESHOLD_LongPortraitFitToHeight) {arrange_LongPortraitFitToHeight();
  } else if (ratio < THRESHOLD_ShortPortraitFitToWidth) {arrange_ShortPortraitFitToWidth();
  } else if (ratio < THRESHOLD_ShortPortraitFitToHeight) {arrange_ShortPortraitFitToHeight();
  } else if (ratio < THRESHOLD_ShortLandscapeFitToWidth) {arrange_ShortLandscapeFitToWidth();
  } else if (ratio < THRESHOLD_ShortLandscapeFitToHeight) {arrange_ShortLandscapeFitToHeight();
  } else if (ratio < THRESHOLD_LongLandscapeFitToWidth) {arrange_LongLandscapeFitToWidth();
  } else {arrange_LongLandscapeFitToHeight();
  }
}

function arrange_LongPortraitFitToWidth() {
  document.getElementById('div-title-west').style.display = 'none';
  document.getElementById('div-title-north').style.display = 'flex';
  document.getElementById('div-info-east').style.display = 'none';
  document.getElementById('div-info-south').style.display = 'inline';

  var w = window.innerWidth;
  document.getElementById('div-title-north').style.width = w.toString().concat('px');
  document.getElementById('div-title-north').style.height = (w/6).toString().concat('px');
  document.getElementById('div-board-area').style.width = w.toString().concat('px');
  document.getElementById('div-board-area').style.height = w.toString().concat('px');
  document.getElementById('div-info-south').style.width = w.toString().concat('px');
  document.getElementById('div-info-south').style.height = (window.innerHeight-w*7/6).toString().concat('px');
}

function arrange_LongPortraitFitToHeight() {
  document.getElementById('div-title-west').style.display = 'none';
  document.getElementById('div-title-north').style.display = 'flex';
  document.getElementById('div-info-east').style.display = 'none';
  document.getElementById('div-info-south').style.display = 'inline';

  var w = window.innerHeight * THRESHOLD_LongPortraitFitToWidth;
  document.getElementById('div-title-north').style.width = w.toString().concat('px');
  document.getElementById('div-title-north').style.height = (w/6).toString().concat('px');
  document.getElementById('div-board-area').style.width = w.toString().concat('px');
  document.getElementById('div-board-area').style.height = w.toString().concat('px');
  document.getElementById('div-info-south').style.width = w.toString().concat('px');
  document.getElementById('div-info-south').style.height = (window.innerHeight-w*7/6).toString().concat('px');
}

function arrange_ShortPortraitFitToWidth() {
  document.getElementById('div-title-north').style.display = 'none';
  document.getElementById('div-title-west').style.display = 'flex';
  document.getElementById('div-info-east').style.display = 'none';
  document.getElementById('div-info-south').style.display = 'inline';

  var w = window.innerWidth;
  document.getElementById('div-title-west').style.width = (w/7).toString().concat('px');
  document.getElementById('div-title-west').style.height = (w*6/7).toString().concat('px');
  document.getElementById('div-board-area').style.width = (w*6/7).toString().concat('px');
  document.getElementById('div-board-area').style.height = (w*6/7).toString().concat('px');
  document.getElementById('div-info-south').style.width = w.toString().concat('px');
  document.getElementById('div-info-south').style.height = (window.innerHeight-w*6/7).toString().concat('px');
}

function arrange_ShortPortraitFitToHeight() {
  document.getElementById('div-title-north').style.display = 'none';
  document.getElementById('div-title-west').style.display = 'flex';
  document.getElementById('div-info-east').style.display = 'none';
  document.getElementById('div-info-south').style.display = 'inline';

  var w = window.innerHeight * THRESHOLD_ShortPortraitFitToWidth;
  document.getElementById('div-title-west').style.width = (w/7).toString().concat('px');
  document.getElementById('div-title-west').style.height = (w*6/7).toString().concat('px');
  document.getElementById('div-board-area').style.width = (w*6/7).toString().concat('px');
  document.getElementById('div-board-area').style.height = (w*6/7).toString().concat('px');
  document.getElementById('div-info-south').style.width = w.toString().concat('px');
  document.getElementById('div-info-south').style.height = (window.innerHeight-w*6/7).toString().concat('px');
}

function arrange_ShortLandscapeFitToWidth() {
  document.getElementById('div-title-west').style.display = 'none';
  document.getElementById('div-title-north').style.display = 'flex';
  document.getElementById('div-info-south').style.display = 'none';
  document.getElementById('div-info-east').style.display = 'inline';

  var h = window.innerWidth * THRESHOLD_ShortPortraitFitToWidth;
  document.getElementById('div-title-north').style.width = (h*6/7).toString().concat('px');
  document.getElementById('div-title-north').style.height = (h/7).toString().concat('px');
  document.getElementById('div-board-area').style.width = (h*6/7).toString().concat('px');
  document.getElementById('div-board-area').style.height = (h*6/7).toString().concat('px');
  document.getElementById('div-info-east').style.width = (window.innerWidth-h*6/7).toString().concat('px');
  document.getElementById('div-info-east').style.height = (h*6/7).toString().concat('px');
}

function arrange_ShortLandscapeFitToHeight() {
  document.getElementById('div-title-west').style.display = 'none';
  document.getElementById('div-title-north').style.display = 'flex';
  document.getElementById('div-info-south').style.display = 'none';
  document.getElementById('div-info-east').style.display = 'inline';

  var h = window.innerHeight;
  document.getElementById('div-title-north').style.width = (h*6/7).toString().concat('px');
  document.getElementById('div-title-north').style.height = (h/7).toString().concat('px');
  document.getElementById('div-board-area').style.width = (h*6/7).toString().concat('px');
  document.getElementById('div-board-area').style.height = (h*6/7).toString().concat('px');
  document.getElementById('div-info-east').style.width = (window.innerWidth-h*6/7).toString().concat('px');
  document.getElementById('div-info-east').style.height = (h*6/7).toString().concat('px');
}

function arrange_LongLandscapeFitToWidth() {
  document.getElementById('div-title-north').style.display = 'none';
  document.getElementById('div-title-west').style.display = 'flex';
  document.getElementById('div-info-south').style.display = 'none';
  document.getElementById('div-info-east').style.display = 'inline';

  var h  = window.innerWidth * THRESHOLD_LongPortraitFitToWidth;
  document.getElementById('div-title-west').style.width = (h/6).toString().concat('px');
  document.getElementById('div-title-west').style.height = h.toString().concat('px');
  document.getElementById('div-board-area').style.width = h.toString().concat('px');
  document.getElementById('div-board-area').style.height = h.toString().concat('px');
  document.getElementById('div-info-east').style.width = (window.innerWidth-h*7/6).toString().concat('px');
  document.getElementById('div-info-east').style.height = h.toString().concat('px');
}

function arrange_LongLandscapeFitToHeight() {
  document.getElementById('div-title-north').style.display = 'none';
  document.getElementById('div-title-west').style.display = 'flex';
  document.getElementById('div-info-south').style.display = 'none';
  document.getElementById('div-info-east').style.display = 'inline';

  var h  = window.innerHeight;
  document.getElementById('div-title-west').style.width = (h/6).toString().concat('px');
  document.getElementById('div-title-west').style.height = h.toString().concat('px');
  document.getElementById('div-board-area').style.width = h.toString().concat('px');
  document.getElementById('div-board-area').style.height = h.toString().concat('px');
  document.getElementById('div-info-east').style.width = (window.innerWidth-h*7/6).toString().concat('px');
  document.getElementById('div-info-east').style.height = h.toString().concat('px');
}

function expand_to_full_screen() {
  try {
    document.getElementById('div-outer-vertical-flexbox').requestFullscreen();
  }
  catch (e) {
    try {
      document.getElementById('div-outer-vertical-flexbox').mozRequestFullScreen();
    }
    catch (e) {
      try {
        document.getElementById('div-outer-vertical-flexbox').webkitRequestFullscreen();
      }
      catch (e) {
        document.getElementById('div-outer-vertical-flexbox').msRequestFullscreen();
      }
    }
  }
}

function contract_from_full_screen() {
  try {
    document.exitFullscreen();
  }
  catch (e) {
    try {
      document.mozCancelFullScreen();
    }
    catch (e) {
      try {
        document.webkitExitFullscreen();
      }
      catch (e) {
        document.msExitFullscreen();
      }
    }
  }
}

function switch_buttons() {
  if (document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement || document.msFullscreenElement) {
    document.getElementById('button-full-screen-expand-north').style.display= 'none';
    document.getElementById('button-full-screen-expand-west').style.display= 'none';
    document.getElementById('button-full-screen-contract-north').style.display= 'inline';
    document.getElementById('button-full-screen-contract-west').style.display= 'inline';
  } else {
    document.getElementById('button-full-screen-contract-north').style.display= 'none';
    document.getElementById('button-full-screen-contract-west').style.display= 'none';
    document.getElementById('button-full-screen-expand-north').style.display= 'inline';
    document.getElementById('button-full-screen-expand-west').style.display= 'inline';
  }
}

function place_piece(x, y) {
  document.getElementById('div-tile-x' + x + '-y' + y).innerHTML = '<use xlink:href=\'images/logo-and-buttons.svg#player1-piece-image\'></use>';
}

function make_empty(x, y) {
  document.getElementById('div-tile-x' + x + '-y' + y).innerHTML = '';
}

function new_game() {
  for (y=3;y<9;y++) {
    for (x=4;x<8;x++){
      place_piece(x, y);
    }
  }
  for (y=4;y<8;y++) {
    for (x=5;x<7;x++){
      make_empty(x, y);
    }
  }
}

function confirm_new_game() {
  if (confirm('Abandon game and start a new one?')) {
    new_game()
  }
}

window.onresize = reorganise;
window.onload = reorganise;

document.onfullscreenchange = switch_buttons;
document.onmozfullscreenchange = switch_buttons;
document.onwebkitfullscreenchange = switch_buttons;
document.onmsfullscreenchange = switch_buttons;
<commit_msg>Create Game class<commit_after>// Arbitrary numbers chosen to ensure Long Portrait mode fits into Chrome on Android.
// Firefox uses less vertical space for the URL bar so Long Portrait will be available in both.
// 270 is six times 45, as board is twelve squares and logo is two.
// 73 is the remaining 3.24444 squares that can fit into the Chrome window.
// Scaled up until all values are integers for ease of reading.
const THRESHOLD_LongPortraitFitToWidth = 270/(45+270+73);
const THRESHOLD_LongPortraitFitToHeight = (45+270)/(45+270+73);
const THRESHOLD_ShortPortraitFitToWidth = (45+270)/(270+73);
const THRESHOLD_ShortPortraitFitToHeight = 1;
const THRESHOLD_ShortLandscapeFitToWidth = (270+73)/(45+270);
const THRESHOLD_ShortLandscapeFitToHeight = (45+270+73)/(45+270);
const THRESHOLD_LongLandscapeFitToWidth = (45+270+73)/270;

function reorganise() {
  ratio = window.innerWidth / window.innerHeight;
  if (ratio < THRESHOLD_LongPortraitFitToWidth) {arrange_LongPortraitFitToWidth();
  } else if (ratio < THRESHOLD_LongPortraitFitToHeight) {arrange_LongPortraitFitToHeight();
  } else if (ratio < THRESHOLD_ShortPortraitFitToWidth) {arrange_ShortPortraitFitToWidth();
  } else if (ratio < THRESHOLD_ShortPortraitFitToHeight) {arrange_ShortPortraitFitToHeight();
  } else if (ratio < THRESHOLD_ShortLandscapeFitToWidth) {arrange_ShortLandscapeFitToWidth();
  } else if (ratio < THRESHOLD_ShortLandscapeFitToHeight) {arrange_ShortLandscapeFitToHeight();
  } else if (ratio < THRESHOLD_LongLandscapeFitToWidth) {arrange_LongLandscapeFitToWidth();
  } else {arrange_LongLandscapeFitToHeight();
  }
}

function arrange_LongPortraitFitToWidth() {
  document.getElementById('div-title-west').style.display = 'none';
  document.getElementById('div-title-north').style.display = 'flex';
  document.getElementById('div-info-east').style.display = 'none';
  document.getElementById('div-info-south').style.display = 'inline';

  var w = window.innerWidth;
  document.getElementById('div-title-north').style.width = w.toString().concat('px');
  document.getElementById('div-title-north').style.height = (w/6).toString().concat('px');
  document.getElementById('div-board-area').style.width = w.toString().concat('px');
  document.getElementById('div-board-area').style.height = w.toString().concat('px');
  document.getElementById('div-info-south').style.width = w.toString().concat('px');
  document.getElementById('div-info-south').style.height = (window.innerHeight-w*7/6).toString().concat('px');
}

function arrange_LongPortraitFitToHeight() {
  document.getElementById('div-title-west').style.display = 'none';
  document.getElementById('div-title-north').style.display = 'flex';
  document.getElementById('div-info-east').style.display = 'none';
  document.getElementById('div-info-south').style.display = 'inline';

  var w = window.innerHeight * THRESHOLD_LongPortraitFitToWidth;
  document.getElementById('div-title-north').style.width = w.toString().concat('px');
  document.getElementById('div-title-north').style.height = (w/6).toString().concat('px');
  document.getElementById('div-board-area').style.width = w.toString().concat('px');
  document.getElementById('div-board-area').style.height = w.toString().concat('px');
  document.getElementById('div-info-south').style.width = w.toString().concat('px');
  document.getElementById('div-info-south').style.height = (window.innerHeight-w*7/6).toString().concat('px');
}

function arrange_ShortPortraitFitToWidth() {
  document.getElementById('div-title-north').style.display = 'none';
  document.getElementById('div-title-west').style.display = 'flex';
  document.getElementById('div-info-east').style.display = 'none';
  document.getElementById('div-info-south').style.display = 'inline';

  var w = window.innerWidth;
  document.getElementById('div-title-west').style.width = (w/7).toString().concat('px');
  document.getElementById('div-title-west').style.height = (w*6/7).toString().concat('px');
  document.getElementById('div-board-area').style.width = (w*6/7).toString().concat('px');
  document.getElementById('div-board-area').style.height = (w*6/7).toString().concat('px');
  document.getElementById('div-info-south').style.width = w.toString().concat('px');
  document.getElementById('div-info-south').style.height = (window.innerHeight-w*6/7).toString().concat('px');
}

function arrange_ShortPortraitFitToHeight() {
  document.getElementById('div-title-north').style.display = 'none';
  document.getElementById('div-title-west').style.display = 'flex';
  document.getElementById('div-info-east').style.display = 'none';
  document.getElementById('div-info-south').style.display = 'inline';

  var w = window.innerHeight * THRESHOLD_ShortPortraitFitToWidth;
  document.getElementById('div-title-west').style.width = (w/7).toString().concat('px');
  document.getElementById('div-title-west').style.height = (w*6/7).toString().concat('px');
  document.getElementById('div-board-area').style.width = (w*6/7).toString().concat('px');
  document.getElementById('div-board-area').style.height = (w*6/7).toString().concat('px');
  document.getElementById('div-info-south').style.width = w.toString().concat('px');
  document.getElementById('div-info-south').style.height = (window.innerHeight-w*6/7).toString().concat('px');
}

function arrange_ShortLandscapeFitToWidth() {
  document.getElementById('div-title-west').style.display = 'none';
  document.getElementById('div-title-north').style.display = 'flex';
  document.getElementById('div-info-south').style.display = 'none';
  document.getElementById('div-info-east').style.display = 'inline';

  var h = window.innerWidth * THRESHOLD_ShortPortraitFitToWidth;
  document.getElementById('div-title-north').style.width = (h*6/7).toString().concat('px');
  document.getElementById('div-title-north').style.height = (h/7).toString().concat('px');
  document.getElementById('div-board-area').style.width = (h*6/7).toString().concat('px');
  document.getElementById('div-board-area').style.height = (h*6/7).toString().concat('px');
  document.getElementById('div-info-east').style.width = (window.innerWidth-h*6/7).toString().concat('px');
  document.getElementById('div-info-east').style.height = (h*6/7).toString().concat('px');
}

function arrange_ShortLandscapeFitToHeight() {
  document.getElementById('div-title-west').style.display = 'none';
  document.getElementById('div-title-north').style.display = 'flex';
  document.getElementById('div-info-south').style.display = 'none';
  document.getElementById('div-info-east').style.display = 'inline';

  var h = window.innerHeight;
  document.getElementById('div-title-north').style.width = (h*6/7).toString().concat('px');
  document.getElementById('div-title-north').style.height = (h/7).toString().concat('px');
  document.getElementById('div-board-area').style.width = (h*6/7).toString().concat('px');
  document.getElementById('div-board-area').style.height = (h*6/7).toString().concat('px');
  document.getElementById('div-info-east').style.width = (window.innerWidth-h*6/7).toString().concat('px');
  document.getElementById('div-info-east').style.height = (h*6/7).toString().concat('px');
}

function arrange_LongLandscapeFitToWidth() {
  document.getElementById('div-title-north').style.display = 'none';
  document.getElementById('div-title-west').style.display = 'flex';
  document.getElementById('div-info-south').style.display = 'none';
  document.getElementById('div-info-east').style.display = 'inline';

  var h  = window.innerWidth * THRESHOLD_LongPortraitFitToWidth;
  document.getElementById('div-title-west').style.width = (h/6).toString().concat('px');
  document.getElementById('div-title-west').style.height = h.toString().concat('px');
  document.getElementById('div-board-area').style.width = h.toString().concat('px');
  document.getElementById('div-board-area').style.height = h.toString().concat('px');
  document.getElementById('div-info-east').style.width = (window.innerWidth-h*7/6).toString().concat('px');
  document.getElementById('div-info-east').style.height = h.toString().concat('px');
}

function arrange_LongLandscapeFitToHeight() {
  document.getElementById('div-title-north').style.display = 'none';
  document.getElementById('div-title-west').style.display = 'flex';
  document.getElementById('div-info-south').style.display = 'none';
  document.getElementById('div-info-east').style.display = 'inline';

  var h  = window.innerHeight;
  document.getElementById('div-title-west').style.width = (h/6).toString().concat('px');
  document.getElementById('div-title-west').style.height = h.toString().concat('px');
  document.getElementById('div-board-area').style.width = h.toString().concat('px');
  document.getElementById('div-board-area').style.height = h.toString().concat('px');
  document.getElementById('div-info-east').style.width = (window.innerWidth-h*7/6).toString().concat('px');
  document.getElementById('div-info-east').style.height = h.toString().concat('px');
}

function expand_to_full_screen() {
  try {
    document.getElementById('div-outer-vertical-flexbox').requestFullscreen();
  }
  catch (e) {
    try {
      document.getElementById('div-outer-vertical-flexbox').mozRequestFullScreen();
    }
    catch (e) {
      try {
        document.getElementById('div-outer-vertical-flexbox').webkitRequestFullscreen();
      }
      catch (e) {
        document.getElementById('div-outer-vertical-flexbox').msRequestFullscreen();
      }
    }
  }
}

function contract_from_full_screen() {
  try {
    document.exitFullscreen();
  }
  catch (e) {
    try {
      document.mozCancelFullScreen();
    }
    catch (e) {
      try {
        document.webkitExitFullscreen();
      }
      catch (e) {
        document.msExitFullscreen();
      }
    }
  }
}

function switch_buttons() {
  if (document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement || document.msFullscreenElement) {
    document.getElementById('button-full-screen-expand-north').style.display= 'none';
    document.getElementById('button-full-screen-expand-west').style.display= 'none';
    document.getElementById('button-full-screen-contract-north').style.display= 'inline';
    document.getElementById('button-full-screen-contract-west').style.display= 'inline';
  } else {
    document.getElementById('button-full-screen-contract-north').style.display= 'none';
    document.getElementById('button-full-screen-contract-west').style.display= 'none';
    document.getElementById('button-full-screen-expand-north').style.display= 'inline';
    document.getElementById('button-full-screen-expand-west').style.display= 'inline';
  }
}

class Game {
  constructor() {
    this.restart()
  }
  restart() {
    var square, x, y, t;
    this.board = [[0,0,0,0,0,0,0,0,0,0,0,0],
                  [0,0,0,0,0,0,0,0,0,0,0,0],
                  [0,0,0,0,0,0,0,0,0,0,0,0],
                  [0,0,0,0,0,0,0,0,0,0,0,0],
                  [0,0,0,0,0,0,0,0,0,0,0,0],
                  [0,0,0,0,0,0,0,0,0,0,0,0],
                  [0,0,0,0,0,0,0,0,0,0,0,0],
                  [0,0,0,0,0,0,0,0,0,0,0,0],
                  [0,0,0,0,0,0,0,0,0,0,0,0],
                  [0,0,0,0,0,0,0,0,0,0,0,0],
                  [0,0,0,0,0,0,0,0,0,0,0,0],
                  [0,0,0,0,0,0,0,0,0,0,0,0]
                 ];
    this.pieces.player1 = [];
    this.pieces.player2 = [];
    this.pieces.neutral = [];
    this.isolated_squares = [];
    this.adjacent_squares.player1 = [];
    this.adjacent_squares.player2 = [];
    this.highlighted_destination_squares = [];

    for (y = 0; y <= 11; y++) {
      for (x = 0; x <= 11; x++) {
        this.isolated_squares.push([x, y]);
      }
    }

    for (t = 0; t <= 1; t++) {
      square = this.isolated_squares[Math.floor(Math.random() * this.isolated_squares.length)];
      x = square[0];
      y = square[1];
      place_player1_piece(x, y);
      square = this.isolated_squares[Math.floor(Math.random() * this.isolated_squares.length)];
      x = square[0];
      y = square[1];
      place_player2_piece(x, y);
    }
    this.player_to_move = 0;
  }
  function place_player1_piece(x, y) {
    document.getElementById('div-tile-x' + x + '-y' + y).innerHTML = '<use xlink:href=\'images/logo-and-buttons.svg#player1-piece-image\'></use>';
    remove_isolated_squares(x, y);
  }
  function place_player2_piece(x, y) {
    document.getElementById('div-tile-x' + x + '-y' + y).innerHTML = '<use xlink:href=\'images/logo-and-buttons.svg#player2-piece-image\'></use>';
    remove_isolated_squares(x, y);
  }
  function place_neutral_piece(x, y) {
    document.getElementById('div-tile-x' + x + '-y' + y).innerHTML = '<use xlink:href=\'images/logo-and-buttons.svg#neutral-piece-image\'></use>';
    remove_isolated_squares(x, y);
  }
  function highlight_player1_piece(x, y) {
    document.getElementById('div-tile-x' + x + '-y' + y).innerHTML = '<use xlink:href=\'images/logo-and-buttons.svg#highlighted-player1-piece-image\'></use>';
  }
  function unhighlight_player1_piece(x, y) {
    document.getElementById('div-tile-x' + x + '-y' + y).innerHTML = '<use xlink:href=\'images/logo-and-buttons.svg#player1-piece-image\'></use>';
  }
  function highlight_empty_square(x, y) {
    document.getElementById('div-tile-x' + x + '-y' + y).innerHTML = '<use xlink:href=\'images/logo-and-buttons.svg#highlighted-empty-square-image\'></use>';
  }
  function unhighlight_empty_square(x, y) {
    document.getElementById('div-tile-x' + x + '-y' + y).innerHTML = '';
  }
  function make_square_empty(x, y) {
    document.getElementById('div-tile-x' + x + '-y' + y).innerHTML = '';
    add_isolated_squares(x, y);
  }
  function remove_isolated_squares(x, y) {
    var location;
    for (let target of [[x, y]].concat(this.neighbours([x, y])) {
      location = this.isolated_squares.indexOf(target);
      if (location > -1) {
        this.isolated_squares.splice(location, 1);
      }
    }
  }
  function add_isolated_squares(x, y) {
    var location;
    for (let target of [[x, y]].concat(this.neighbours([x, y])) {
      location = this.isolated_squares.indexOf(target);
      if (location === -1) {
        this.isolated_squares.push(target);
      }
    }
  }
  function neighbours(x, y) {   // Javascript % currently takes the sign of the dividend rather than the divisor, hence the +12s
    return [[x, (y - 1 + 12) % 12],
            [(x - 1 + 12) % 12, y],
            [(x + 1) % 12, y],
            [x, (y + 1) % 12]
           ];
  }
  function confirm_new_game() {
    if (confirm('Abandon game and start a new one?')) {
      restart();
    }
  }
}

function prepare() {
  game = new Game();
  reorganise();
  document.onfullscreenchange = switch_buttons;
  document.onmozfullscreenchange = switch_buttons;
  document.onwebkitfullscreenchange = switch_buttons;
  document.onmsfullscreenchange = switch_buttons;
  window.onresize = reorganise;
}

window.onload = prepare;
<|endoftext|>


<commit_before>var log = require('../../../log').logger('sbp');
var g2 = require('../../../g2');
var sb3_commands = require('../sb3_commands');
var config = require('../../../config');

// Note that jogs don't need to be stack breakers, they only are to be consistent with sb3 behavior
// and to improve performance by breaking up large files.  Down the road, if the sender is improved, these
// should be made back into inline commands.

// Jog (rapid) the X axis
exports.JX = function(args) {
	var x = args[0];
	if ( x !== this.cmd_posx ){
		if(isNaN(x)) { throw( "Invalid JX argument: " + x ); }
		this.cmd_posx = x;
		this.emit_move('G0',{"X":x});
	}
	setImmediate(callback);
};

// Jog (rapid) the Y axis
exports.JY = function(args, callback) {
	var y = args[0];
	if ( y !== this.cmd_posy ){
		if(isNaN(y)) { throw( "Invalid JY argument: " + y ); }
		this.cmd_posy = y;
		this.emit_move('G0',{"Y":y});
	}
	setImmediate(callback);
};

// Jog (rapid) the Z axis
exports.JZ = function(args, callback) {
	var z = args[0];
	if ( z !== this.cmd_posz ){
		if(isNaN(z)) { throw( "Invalid JZ argument: " + z ); }
		this.cmd_posz = z;
		this.emit_move('G0',{"Z":z});
	}
	setImmediate(callback);
};

// Jog (rapid) the A axis
exports.JA = function(args, callback) {
	var a = args[0];
	if ( a !== this.cmd_posa ){
		if(isNaN(a)) { throw( "Invalid JA argument: " + a ); }
		this.cmd_posa = a;
		this.emit_move('G0',{"A":a});
	}
	setImmediate(callback);
};

// Jog (rapid) the B axis
exports.JB = function(args, callback) {
	var b = args[0];
	if ( b !== this.cmd_posb ){
		if(isNaN(b)) { throw( "Invalid JB argument: " + b ); }
		this.cmd_posb = b;
		this.emit_move('G0',{"B":b});
	}
	setImmediate(callback);
};

// Jog (rapid) the C axis
exports.JC = function(args, callback) {
	var c = args[0];
	if ( c !== this.cmd_posc ){
		if(isNaN(c)) { throw( "Invalid JC argument: " + c ); }
		this.cmd_posc = c;
		this.emit_move('G0',{"C":c});
	}
	setImmediate(callback);

};

// Jog (rapid) 2 axes (XY).This is a modal command, any axis location that is left out
//   of the command will default to it's current position and not move
exports.J2 = function(args, callback) {
	log.debug(" J2");
    var params = process_jog.bind(this)(args);
    log.debug( "  J2 params = " + JSON.stringify(params) );
    log.debug( "     result = " + this.cmd_result );
	if ( this.cmd_result < 2 ){
		this.emit_move('G0',params);
	}
	setImmediate(callback);
};

// Jog (rapid) 3 axes (XYZ). This is a modal command, any axis location that is left out
//   of the command will default to it's current position and not move
exports.J3 = function(args, callback) {
    var params = process_jog.bind(this)(args);
	if ( this.cmd_result < 3 ){
		this.emit_move('G0',params);
	}
		setImmediate(callback);

};

// Jog (rapid) 4 axes (XYZA). This is a modal command, any axis location that is left out
//   of the command will default to it's current position and not move
exports.J4 = function(args,callback) {
    var params = process_jog.bind(this)(args);
    if ( this.cmd_result < 4 ){
		this.emit_move('G0',params);
	}
		setImmediate(callback);

};

// Jog (rapid) 5 axes (XYZAB). This is a modal command, any axis location that is left out
//   of the command will default to it's current position and not move
exports.J5 = function(args,callback) {
    var params = process_jog.bind(this)(args);
    if ( this.cmd_result < 5 ){
		this.emit_move('G0',params);
	}
		setImmediate(callback);

};

// Jog (rapid) 6 axes (XYZABC). This is a modal command, any axis location that is left out
//   of the command will default to it's current position and not move
exports.J6 = function(args, callback) {
    var params = process_jog.bind(this)(args);
    if ( this.cmd_result < 6 ){
		this.emit_move('G0',params);
	}
		setImmediate(callback);

};

process_jog = function(args) {
    log.debug(" process_jog: " + JSON.stringify(args));
	var params = {};
	this.cmd_result = 0;
	if( args[0] === 0 || args[0] && typeof args[0] === "number"){  //args[0] === 0 ||
		params.X = args[0];
		if ( params.X === this.cmd_posx ) { this.cmd_result += 1; }
	}
	if( args[1] === 0 || args[1] && typeof args[1] === "number"){  //args[1] === 0 ||
		params.Y = args[1];
		if ( params.Y === this.cmd_posy ) { this.cmd_result += 1; }
	}
	if(args[2] === 0 || args[2] && typeof args[2] === "number"){
		params.Z = args[2];
		if ( params.Z === this.cmd_posz ) { this.cmd_result += 1; }
	}
	if(args[3] === 0 || args[3] && typeof args[3] === "number"){
		params.A = args[3];
		if ( params.A === this.cmd_posa ) { this.cmd_result += 1; }
	}
	if(args[4] === 0 || args[4] && typeof args[4] === "number"){
		params.B = args[4];
		if ( params.B === this.cmd_posb ) { this.cmd_result += 1; }
	}
	if(args[5] === 0 || args[5] && typeof args[5] === "number"){
		params.C = args[5];
		if ( params.C === this.cmd_posc ) { this.cmd_result += 1; }
	}

	return params;
};

// Jog (rapid) XY to the Home position (0,0)
exports.JH = function(args,callback) {
	var x = 0;
	var y = 0;
	var safeZ = config.opensbp.get('safeZpullUp');

	this.machine.driver.get('posz', function(err, MPO) {
		var unitConv = 1;
		log.debug( "JH" );
	 	if ( this.machine.driver.status.unit === 'in' ) {  // inches
	 		unitConv = 0.039370079;
	 	}
	 	var z = MPO;
		log.debug("z = " + z);
	 	if ( z < safeZ ){
			this.emit_move('G0',{"Z":safeZ});
			this.emit_move('G0',{"X":x,"Y":y});
 		}
 		else{
 			this.emit_move('G0',{"X":x,"Y":y});
 		}
		this.cmd_posx = 0;
		this.cmd_posy = 0;
		this.cmd_posz = safeZ;
		callback();
	}.bind(this));
};

// Set the Jog (Rapid) speed for any of the 6 axes
exports.JS = function(args, callback) {
	var speed_change = 0.0;
	var g2_values = {};

	if (args[0] !== undefined) {
		speed_change = args[0];
		if(isNaN(speed_change)) { throw "Invalid JS-XY argument: " + speed_change; }
		g2_values.xvm = g2_values.yvm = (60 * speed_change);
	}
	if (args[1] !== undefined) {
		speed_change = args[1];
		if(isNaN(speed_change)) { throw "Invalid JS-Z argument: " + speed_change; }
		g2_values.zvm = (60 * speed_change);
	}
	if (args[2] !== undefined) {
		speed_change = args[2];
		if(isNaN(speed_change)) { throw "Invalid JS-A argument: " + speed_change; }
		g2_values.avm = (60 * speed_change);
	}
	if (args[3] !== undefined) {
		speed_change = args[3];
		if(isNaN(speed_change)) { throw "Invalid JS-B argument: " + speed_change; }
		g2_values.bvm = (60 * speed_change);
	}
	if (args[4] !== undefined) {
		speed_change = args[4];
		if(isNaN(speed_change)) { throw "Invalid JS-C argument: " + speed_change; }
		g2_values.cvm = (60 * speed_change);
	}
	// We have created the objects containing both the values to set on the G2 driver as well as for shopbot
	// Now send them to their appropriate places (shopbot first, followed by G2)
	config.driver.setMany(g2_values, function(err, values) {
		callback();
	});
};
<commit_msg>Fix bad merge.<commit_after>var log = require('../../../log').logger('sbp');
var g2 = require('../../../g2');
var sb3_commands = require('../sb3_commands');
var config = require('../../../config');

// Note that jogs don't need to be stack breakers, they only are to be consistent with sb3 behavior
// and to improve performance by breaking up large files.  Down the road, if the sender is improved, these
// should be made back into inline commands.

// Jog (rapid) the X axis
exports.JX = function(args) {
	var x = args[0];
	if ( x !== this.cmd_posx ){
		if(isNaN(x)) { throw( "Invalid JX argument: " + x ); }
		this.cmd_posx = x;
		this.emit_move('G0',{"X":x});
	}
};

// Jog (rapid) the Y axis
exports.JY = function(args) {
	var y = args[0];
	if ( y !== this.cmd_posy ){
		if(isNaN(y)) { throw( "Invalid JY argument: " + y ); }
		this.cmd_posy = y;
		this.emit_move('G0',{"Y":y});
	}
};

// Jog (rapid) the Z axis
exports.JZ = function(args) {
	var z = args[0];
	if ( z !== this.cmd_posz ){
		if(isNaN(z)) { throw( "Invalid JZ argument: " + z ); }
		this.cmd_posz = z;
		this.emit_move('G0',{"Z":z});
	}
};

// Jog (rapid) the A axis
exports.JA = function(args) {
	var a = args[0];
	if ( a !== this.cmd_posa ){
		if(isNaN(a)) { throw( "Invalid JA argument: " + a ); }
		this.cmd_posa = a;
		this.emit_move('G0',{"A":a});
	}
};

// Jog (rapid) the B axis
exports.JB = function(args) {
	var b = args[0];
	if ( b !== this.cmd_posb ){
		if(isNaN(b)) { throw( "Invalid JB argument: " + b ); }
		this.cmd_posb = b;
		this.emit_move('G0',{"B":b});
	}
};

// Jog (rapid) the C axis
exports.JC = function(args) {
	var c = args[0];
	if ( c !== this.cmd_posc ){
		if(isNaN(c)) { throw( "Invalid JC argument: " + c ); }
		this.cmd_posc = c;
		this.emit_move('G0',{"C":c});
	}
};

// Jog (rapid) 2 axes (XY).This is a modal command, any axis location that is left out
//   of the command will default to it's current position and not move
exports.J2 = function(args) {
	log.debug(" J2");
    var params = process_jog.bind(this)(args);
    log.debug( "  J2 params = " + JSON.stringify(params) );
    log.debug( "     result = " + this.cmd_result );
	if ( this.cmd_result < 2 ){
		this.emit_move('G0',params);
	}
};

// Jog (rapid) 3 axes (XYZ). This is a modal command, any axis location that is left out
//   of the command will default to it's current position and not move
exports.J3 = function(args) {
    var params = process_jog.bind(this)(args);
	if ( this.cmd_result < 3 ){
		this.emit_move('G0',params);
	}
};

// Jog (rapid) 4 axes (XYZA). This is a modal command, any axis location that is left out
//   of the command will default to it's current position and not move
exports.J4 = function(args) {
    var params = process_jog.bind(this)(args);
    if ( this.cmd_result < 4 ){
		this.emit_move('G0',params);
	}
};

// Jog (rapid) 5 axes (XYZAB). This is a modal command, any axis location that is left out
//   of the command will default to it's current position and not move
exports.J5 = function(args) {
    var params = process_jog.bind(this)(args);
    if ( this.cmd_result < 5 ){
		this.emit_move('G0',params);
	}
};

// Jog (rapid) 6 axes (XYZABC). This is a modal command, any axis location that is left out
//   of the command will default to it's current position and not move
exports.J6 = function(args) {
    var params = process_jog.bind(this)(args);
    if ( this.cmd_result < 6 ){
		this.emit_move('G0',params);
	}
};

process_jog = function(args) {
    log.debug(" process_jog: " + JSON.stringify(args));
	var params = {};
	this.cmd_result = 0;
	if( args[0] === 0 || args[0] && typeof args[0] === "number"){  //args[0] === 0 ||
		params.X = args[0];
		if ( params.X === this.cmd_posx ) { this.cmd_result += 1; }
	}
	if( args[1] === 0 || args[1] && typeof args[1] === "number"){  //args[1] === 0 ||
		params.Y = args[1];
		if ( params.Y === this.cmd_posy ) { this.cmd_result += 1; }
	}
	if(args[2] === 0 || args[2] && typeof args[2] === "number"){
		params.Z = args[2];
		if ( params.Z === this.cmd_posz ) { this.cmd_result += 1; }
	}
	if(args[3] === 0 || args[3] && typeof args[3] === "number"){
		params.A = args[3];
		if ( params.A === this.cmd_posa ) { this.cmd_result += 1; }
	}
	if(args[4] === 0 || args[4] && typeof args[4] === "number"){
		params.B = args[4];
		if ( params.B === this.cmd_posb ) { this.cmd_result += 1; }
	}
	if(args[5] === 0 || args[5] && typeof args[5] === "number"){
		params.C = args[5];
		if ( params.C === this.cmd_posc ) { this.cmd_result += 1; }
	}

	return params;
};

// Jog (rapid) XY to the Home position (0,0)
exports.JH = function(args,callback) {
	var x = 0;
	var y = 0;
	var safeZ = config.opensbp.get('safeZpullUp');

	this.machine.driver.get('posz', function(err, MPO) {
		var unitConv = 1;
		log.debug( "JH" );
	 	if ( this.machine.driver.status.unit === 'in' ) {  // inches
	 		unitConv = 0.039370079;
	 	}
	 	var z = MPO;
		log.debug("z = " + z);
	 	if ( z < safeZ ){
			this.emit_move('G0',{"Z":safeZ});
			this.emit_move('G0',{"X":x,"Y":y});
 		}
 		else{
 			this.emit_move('G0',{"X":x,"Y":y});
 		}
		this.cmd_posx = 0;
		this.cmd_posy = 0;
		this.cmd_posz = safeZ;
		callback();
	}.bind(this));
};

// Set the Jog (Rapid) speed for any of the 6 axes
exports.JS = function(args, callback) {
	var speed_change = 0.0;
	var g2_values = {};

	if (args[0] !== undefined) {
		speed_change = args[0];
		if(isNaN(speed_change)) { throw "Invalid JS-XY argument: " + speed_change; }
		g2_values.xvm = g2_values.yvm = (60 * speed_change);
	}
	if (args[1] !== undefined) {
		speed_change = args[1];
		if(isNaN(speed_change)) { throw "Invalid JS-Z argument: " + speed_change; }
		g2_values.zvm = (60 * speed_change);
	}
	if (args[2] !== undefined) {
		speed_change = args[2];
		if(isNaN(speed_change)) { throw "Invalid JS-A argument: " + speed_change; }
		g2_values.avm = (60 * speed_change);
	}
	if (args[3] !== undefined) {
		speed_change = args[3];
		if(isNaN(speed_change)) { throw "Invalid JS-B argument: " + speed_change; }
		g2_values.bvm = (60 * speed_change);
	}
	if (args[4] !== undefined) {
		speed_change = args[4];
		if(isNaN(speed_change)) { throw "Invalid JS-C argument: " + speed_change; }
		g2_values.cvm = (60 * speed_change);
	}
	// We have created the objects containing both the values to set on the G2 driver as well as for shopbot
	// Now send them to their appropriate places (shopbot first, followed by G2)
	config.driver.setMany(g2_values, function(err, values) {
		callback();
	});
};
<|endoftext|>


<commit_before>var bot;
module.exports.init = function(b) {
  bot = b;
};

module.exports.scoreboard = {};

var xplusplus = /(\w+)\+\+/;
var xplusplusfory = /(\w+)\+\+ (for)? (.*)/;

// Watch for messages of the following forms
// dru++
// dru++ for some reason
module.exports.msg = function(text, from, reply, raw) {
  var re;

  if (xplusplusfory.exec(text)) {
    var user = re[0],
      reason = re[2];

    this.scoreboard[user] = this.scoreboard[user] || { points: 0, reasons: [] };
    this.scoreboard[user]['points']++;
    this.scoreboard[user]['reasons'].push(reason);

  } elsif (xplusplus.exec(text)) {
    var user = re[0];

    this.scoreboard[user] = this.scoreboard[user] || { points: 0, reasons: [] };
    this.scoreboard[user]['points']++;
  }
};

module.exports.commands = {

  top10: function(r, parts, reply) {
    var users_and_scores = [],
      rank = 10;

    // yolo js
    for (var user in this.scoreboard) {
      users_and_scores.append([user, scoreboard[user]['points']]);
    }

    // Sort pairs by score: [["dru", 4], ["suroi", 53]]
    users_and_scores = users_and_scores.sort(function (a, b) {
    	return a[1] <= b[1];
    });

    for (var line_data in users_and_scores) {
    	reply("" + (11 - rank--) + ". " + line_data[0] + ": " + line_data[1] + " points!");
    	if (rank == 0) { break; }
    }
  },

  score: function(r, parts, reply) {
    var user = parts[0],
      points = 0;

    if (this.scoreboard[user]) {
    	points = this.scoreboard[user]['points'];
    }

    reply(user + " has "  + points + " points!");
    // #todo point reasons
  }

};
<commit_msg>responses<commit_after>var bot;
module.exports.init = function(b) {
  bot = b;
};

module.exports.scoreboard = {};

var xplusplus = /(\w+)\+\+/;
var xplusplusfory = /(\w+)\+\+ (for)? (.*)/;

// Watch for messages of the following forms
// dru++
// dru++ for some reason
module.exports.msg = function(text, from, reply, raw) {
  var re;

  if (xplusplusfory.exec(text)) {
    var user = re[0],
      reason = re[2];

    this.scoreboard[user] = this.scoreboard[user] || { points: 0, reasons: [] };
    this.scoreboard[user]['points']++;
    this.scoreboard[user]['reasons'].push(reason);

    reply(user + " now has " + this.scoreboard[user] + " points (nth place!), including 1 for " + reason); // #todo nth place

  } elsif (xplusplus.exec(text)) {
    var user = re[0];

    this.scoreboard[user] = this.scoreboard[user] || { points: 0, reasons: [] };
    this.scoreboard[user]['points']++;

    reply(user + " now has " + this.scoreboard[user] + " points (nth place!)"); // #todo nth place
  }
};

module.exports.commands = {

  top10: function(r, parts, reply) {
    var users_and_scores = [],
      rank = 10;

    // yolo js
    for (var user in this.scoreboard) {
      users_and_scores.append([user, scoreboard[user]['points']]);
    }

    // Sort pairs by score: [["dru", 4], ["suroi", 53]]
    users_and_scores = users_and_scores.sort(function (a, b) {
    	return a[1] <= b[1];
    });

    for (var line_data in users_and_scores) {
    	reply("" + (11 - rank--) + ". " + line_data[0] + ": " + line_data[1] + " points!");
    	if (rank == 0) { break; }
    }
  },

  score: function(r, parts, reply) {
    var user = parts[0],
      points = 0;

    if (this.scoreboard[user]) {
    	points = this.scoreboard[user]['points'];
    }

    reply(user + " has "  + points + " points!");
    // #todo point reasons
  }

};
<|endoftext|>


<commit_before>/*******************************************************************************
#      ____               __          __  _      _____ _       _               #
#     / __ \              \ \        / / | |    / ____| |     | |              #
#    | |  | |_ __   ___ _ __ \  /\  / /__| |__ | |  __| | ___ | |__   ___      #
#    | |  | | '_ \ / _ \ '_ \ \/  \/ / _ \ '_ \| | |_ | |/ _ \| '_ \ / _ \     #
#    | |__| | |_) |  __/ | | \  /\  /  __/ |_) | |__| | | (_) | |_) |  __/     #
#     \____/| .__/ \___|_| |_|\/  \/ \___|_.__/ \_____|_|\___/|_.__/ \___|     #
#           | |                                                                #
#           |_|                 _____ _____  _  __                             #
#                              / ____|  __ \| |/ /                             #
#                             | (___ | |  | | ' /                              #
#                              \___ \| |  | |  <                               #
#                              ____) | |__| | . \                              #
#                             |_____/|_____/|_|\_\                             #
#                                                                              #
#                              (c) 2010-2011 by                                #
#           University of Applied Sciences Northwestern Switzerland            #
#                     Institute of Geomatics Engineering                       #
#                           martin.christen@fhnw.ch                            #
********************************************************************************
*     Licensed under MIT License. Read the file LICENSE for more information   *
*******************************************************************************/

//------------------------------------------------------------------------
/**
 * Logos Node. Draw logos
 * @author Martin Christen martin.christen@fhnw.ch
 * @constructor
 */
function LogosNode()
{
      this.logo = null;
      this.compassbg = null;
      this.compassr = null;
      this.mx = 0;
      this.my = 0;
      this.btn = false;
      this.yaw = 0;
      this.longitude = 0;
      this.latitude = 0;
      this.elevation = 0;
      //------------------------------------------------------------------------
      this.OnChangeState = function()
      {

      }

      //------------------------------------------------------------------------
      this.OnRender = function()
      {
         this.logo.Blit(this.engine.width-72, this.engine.height-72,0,0,1,1,true);

         if (this.btn)
         {
            this.compassbg.Blit(this.mx-64, this.my-64,0,0,1,1,true);
            this.compassr.Blit(this.mx-64, this.my-64,0,this.yaw,1,1,true);
         }

         // draw position
         var lng = this.longitude.toFixed(6);
         var lat = this.latitude.toFixed(6);
         var elv = this.elevation.toFixed(2);
         this.engine.DrawText("Current position: (" + lng+ ", " + lat + "," + elv + ")",0,0,0.5);

      }

      //------------------------------------------------------------------------
      this.OnTraverse = function(ts)
      {
           this.yaw = ts.compassdirection*57.295779513082320876798154814105; //rad2deg
           this.longitude = ts.geoposition.longitude;
           this.latitude = ts.geoposition.latitude;
           this.elevation = ts.geoposition.elevation;
      }

      //------------------------------------------------------------------------
      this.OnInit = function()
      {
          this.logo = new Texture(this.engine);
          this.logo.LoadLogo();

          this.compassbg = new Texture(this.engine);
          this.compassbg.LoadCompassBackground();

          this.compassr = new Texture(this.engine);
          this.compassr.LoadCompassRose();
      }

      //------------------------------------------------------------------------
      this.OnExit = function()
      {

      }

      //------------------------------------------------------------------------
      this.OnRegisterEvents = function()
      {
         this.engine.eventhandler.AddMouseDownCallback(this, this.OnMouseDown);
         this.engine.eventhandler.AddMouseUpCallback(this, this.OnMouseUp);
      }
      //------------------------------------------------------------------------

      this.OnMouseDown = function(sender, button, x, y)
      {
         if (button == 0)
         {
            sender.mx = x;
            sender.my = sender.engine.height-y-1;
            sender.btn = true;
         }
      }

      this.OnMouseUp = function(sender, button, x, y)
      {
         if (button == 0)
         {
            sender.btn = false;
         }
      }
}

LogosNode.prototype = new Node();

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

<commit_msg>* compass is drawn correctly now (compass rose inside "glass")<commit_after>/*******************************************************************************
#      ____               __          __  _      _____ _       _               #
#     / __ \              \ \        / / | |    / ____| |     | |              #
#    | |  | |_ __   ___ _ __ \  /\  / /__| |__ | |  __| | ___ | |__   ___      #
#    | |  | | '_ \ / _ \ '_ \ \/  \/ / _ \ '_ \| | |_ | |/ _ \| '_ \ / _ \     #
#    | |__| | |_) |  __/ | | \  /\  /  __/ |_) | |__| | | (_) | |_) |  __/     #
#     \____/| .__/ \___|_| |_|\/  \/ \___|_.__/ \_____|_|\___/|_.__/ \___|     #
#           | |                                                                #
#           |_|                 _____ _____  _  __                             #
#                              / ____|  __ \| |/ /                             #
#                             | (___ | |  | | ' /                              #
#                              \___ \| |  | |  <                               #
#                              ____) | |__| | . \                              #
#                             |_____/|_____/|_|\_\                             #
#                                                                              #
#                              (c) 2010-2011 by                                #
#           University of Applied Sciences Northwestern Switzerland            #
#                     Institute of Geomatics Engineering                       #
#                           martin.christen@fhnw.ch                            #
********************************************************************************
*     Licensed under MIT License. Read the file LICENSE for more information   *
*******************************************************************************/

//------------------------------------------------------------------------
/**
 * Logos Node. Draw logos
 * @author Martin Christen martin.christen@fhnw.ch
 * @constructor
 */
function LogosNode()
{
      this.logo = null;
      this.compassbg = null;
      this.compassr = null;
      this.mx = 0;
      this.my = 0;
      this.btn = false;
      this.yaw = 0;
      this.longitude = 0;
      this.latitude = 0;
      this.elevation = 0;
      //------------------------------------------------------------------------
      this.OnChangeState = function()
      {

      }

      //------------------------------------------------------------------------
      this.OnRender = function()
      {
         this.logo.Blit(this.engine.width-72, this.engine.height-72,0,0,1,1,true);

         if (this.btn)
         {
            this.compassr.Blit(this.mx-64, this.my-64,0,this.yaw,1,1,true);
            this.compassbg.Blit(this.mx-64, this.my-64,0,0,1,1,true);
         }

         // draw position
         var lng = this.longitude.toFixed(6);
         var lat = this.latitude.toFixed(6);
         var elv = this.elevation.toFixed(2);
         this.engine.DrawText("Current position: (" + lng+ ", " + lat + "," + elv + ")",0,0,0.5);

      }

      //------------------------------------------------------------------------
      this.OnTraverse = function(ts)
      {
           this.yaw = ts.compassdirection*57.295779513082320876798154814105; //rad2deg
           this.longitude = ts.geoposition.longitude;
           this.latitude = ts.geoposition.latitude;
           this.elevation = ts.geoposition.elevation;
      }

      //------------------------------------------------------------------------
      this.OnInit = function()
      {
          this.logo = new Texture(this.engine);
          this.logo.LoadLogo();

          this.compassbg = new Texture(this.engine);
          this.compassbg.LoadCompassBackground();

          this.compassr = new Texture(this.engine);
          this.compassr.LoadCompassRose();
      }

      //------------------------------------------------------------------------
      this.OnExit = function()
      {

      }

      //------------------------------------------------------------------------
      this.OnRegisterEvents = function()
      {
         this.engine.eventhandler.AddMouseDownCallback(this, this.OnMouseDown);
         this.engine.eventhandler.AddMouseUpCallback(this, this.OnMouseUp);
      }
      //------------------------------------------------------------------------

      this.OnMouseDown = function(sender, button, x, y)
      {
         if (button == 0)
         {
            sender.mx = x;
            sender.my = sender.engine.height-y-1;
            sender.btn = true;
         }
      }

      this.OnMouseUp = function(sender, button, x, y)
      {
         if (button == 0)
         {
            sender.btn = false;
         }
      }
}

LogosNode.prototype = new Node();

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

<|endoftext|>


<commit_before>window.LinkBox = React.createClass(
{
	loadLinksFromServer: function()
	{
		if (window.store.searching)
		{
			this.setState({data: []});
			return;
		}

		$.ajax({
			url: this.props.url,
			data: {max: 5},
			dataType: 'json',
			cache: false,
			success: function(data)
			{
				if (window.store.searching)
				{
					this.setState({data: []});
					return;
				}

				this.setState({data: data});
			}.bind(this),

			error: function(xhr, status, err)
			{
				console.error(this.props.url, status, err.toString());
			}.bind(this)
		});
	},

	getInitialState: function()
	{
		return {data: []};
	},

	componentDidMount: function()
	{
		this.loadLinksFromServer();
		// Done only when not searching.  We'll put some flag, but we should get
		// some flux going.
		setInterval(this.loadLinksFromServer, this.props.pollInterval);
	},

	render: function()
	{
		return (

					<LinkList data={this.state.data} />

		);
	}
});

window.LinkList = React.createClass(
{
	render: function()
	{
		var linkNodes = this.props.data.map(function(link) {
			return (
					<Link key={link.added} link={link}>
					{link.description}
					</Link>
			);
		});

		return (

				{linkNodes}

		);
	}
});

window.Link = React.createClass(
{
	rawMarkup: function()
	{
		var rawMarkup = marked(this.props.children.toString(), {sanitize: true});
		return { __html: rawMarkup };
	},

	render: function()
	{
		var date = new Date(this.props.link.added);
		var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
					"Sep", "Oct", "Nov", "Dec"];

		return (

						{this.props.link.title}

							<nobr>{this.props.link.url}</nobr>

						 | Added

							{date.getDate()}
							{months[date.getMonth()]},
							{date.getFullYear()}

		);
	}
});
<commit_msg>Fixing minor UI quirk which broke the URL and date added.<commit_after>window.LinkBox = React.createClass(
{
	loadLinksFromServer: function()
	{
		if (window.store.searching)
		{
			this.setState({data: []});
			return;
		}

		$.ajax({
			url: this.props.url,
			data: {max: 5},
			dataType: 'json',
			cache: false,
			success: function(data)
			{
				if (window.store.searching)
				{
					this.setState({data: []});
					return;
				}

				this.setState({data: data});
			}.bind(this),

			error: function(xhr, status, err)
			{
				console.error(this.props.url, status, err.toString());
			}.bind(this)
		});
	},

	getInitialState: function()
	{
		return {data: []};
	},

	componentDidMount: function()
	{
		this.loadLinksFromServer();
		// Done only when not searching.  We'll put some flag, but we should get
		// some flux going.
		setInterval(this.loadLinksFromServer, this.props.pollInterval);
	},

	render: function()
	{
		return (

					<LinkList data={this.state.data} />

		);
	}
});

window.LinkList = React.createClass(
{
	render: function()
	{
		var linkNodes = this.props.data.map(function(link) {
			return (
					<Link key={link.added} link={link}>
					{link.description}
					</Link>
			);
		});

		return (

				{linkNodes}

		);
	}
});

window.Link = React.createClass(
{
	rawMarkup: function()
	{
		var rawMarkup = marked(this.props.children.toString(), {sanitize: true});
		return { __html: rawMarkup };
	},

	render: function()
	{
		var date = new Date(this.props.link.added);
		var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
					"Sep", "Oct", "Nov", "Dec"];

		return (

						{this.props.link.title}

							<nobr>{this.props.link.url}</nobr>
						 | Added
							{date.getDate()}
							{months[date.getMonth()]},
							{date.getFullYear()}

		);
	}
});
<|endoftext|>


<commit_before>/*
 * isAtRuleSupported
 * Feature test CSS at-rule support
 * @param {String} rule
 * @return {Boolean}
 */

(function(win){
    'use strict';

    var CSSRule = win.CSSRule,
    prefixes = ['MOZ_', 'WEBKIT_', 'O_', 'MS_', ''],
    atRe = /^@/,
    support,
    length;

    win.isAtRuleSupported = function(rule){
        // If the `CSSRule` interface doesn't exist, return undefined
        if(!win.CSSRule){
            return undefined;
        }
        support = false;
        // Convert the rule string to a form compatible with the `CSSRule` type constants:
        // https://wiki.csswg.org/spec/cssom-constants#cssruletype-enumeration
        rule = rule.replace(atRe, '').toUpperCase().split('-').join('_') + '_RULE';
        length = prefixes.length;
        while(!support && length--){
            // Starting with the unprefixed version, iterate over all the vendor
            // prefixes to determine browser support
            support = (prefixes[length] + rule) in CSSRule;
        }
        return support;
    };

})(this);<commit_msg>Fix documentation<commit_after>/*
 * isAtRuleSupported
 * Feature test CSS at-rule support
 * @param {String} rule
 * @return {Boolean|Undefined}
 */

(function(win){
    'use strict';

    var CSSRule = win.CSSRule,
    prefixes = ['MOZ_', 'WEBKIT_', 'O_', 'MS_', ''],
    atRe = /^@/,
    support,
    length;

    win.isAtRuleSupported = function(rule){
        // If the `CSSRule` interface doesn't exist, return undefined
        if(!win.CSSRule){
            return undefined;
        }
        support = false;
        // Convert the rule string to a form compatible with the `CSSRule` type constants:
        // https://wiki.csswg.org/spec/cssom-constants#cssruletype-enumeration
        rule = rule.replace(atRe, '').toUpperCase().split('-').join('_') + '_RULE';
        length = prefixes.length;
        while(!support && length--){
            // Starting with the unprefixed version, iterate over all the vendor
            // prefixes to determine browser support
            support = (prefixes[length] + rule) in CSSRule;
        }
        return support;
    };

})(this);<|endoftext|>


<commit_before>import { isArrayLike } from 'mobx';

export const getDisplayText = (list, value) => {
    const findInArray = (arr_list) => (arr_list.find(item => item.value === parseInt(value)) || {}).text;
    let text = '';
    if (isArrayLike(list)) {
        text = findInArray(list);
    } else {
        Object.keys(list).some(key => {
            text = findInArray(list[key]);
            return text;
        });
    }
    return text;
};

export const getItemFromValue = (list, value) => {
    const findInArray = (arr_list) => arr_list.findIndex(item => item.value === value);
    let item = {};
    if (isArrayLike(list)) {
        item = { number: findInArray(list), length: list.length };
    } else {
        Object.keys(list).some(key => {
            item = { number: findInArray(list[key]), length: list[key].length };
            return item;
        });
    }
    return item;
};

export const getValueFromIndex = (list, index) => {
    const findInArray = (arr_list) => arr_list[index];
    let result;
    if (isArrayLike(list)) {
        result = findInArray(list);
    } else {
        Object.keys(list).some(key => {
            result = findInArray(list[key]);
            return result.value;
        });
    }
    return result.value;
};

export const getPrevIndex = (index, length) => {
    const prev_index = (index - 1) < 0 ? (length - 1) : index - 1;
    return prev_index;
};

export const getNextIndex = (index, length) => {
    const next_index = (index + 1) === length ? 0 : index + 1;
    return next_index;
};
<commit_msg>Revert back changes<commit_after>import { isArrayLike } from 'mobx';

export const getDisplayText = (list, value) => {
    const findInArray = (arr_list) => (arr_list.find(item => item.value === value) || {}).text;
    let text = '';
    if (isArrayLike(list)) {
        text = findInArray(list);
    } else {
        Object.keys(list).some(key => {
            text = findInArray(list[key]);
            return text;
        });
    }
    return text;
};

export const getItemFromValue = (list, value) => {
    const findInArray = (arr_list) => arr_list.findIndex(item => item.value === value);
    let item = {};
    if (isArrayLike(list)) {
        item = { number: findInArray(list), length: list.length };
    } else {
        Object.keys(list).some(key => {
            item = { number: findInArray(list[key]), length: list[key].length };
            return item;
        });
    }
    return item;
};

export const getValueFromIndex = (list, index) => {
    const findInArray = (arr_list) => arr_list[index];
    let result;
    if (isArrayLike(list)) {
        result = findInArray(list);
    } else {
        Object.keys(list).some(key => {
            result = findInArray(list[key]);
            return result.value;
        });
    }
    return result.value;
};

export const getPrevIndex = (index, length) => {
    const prev_index = (index - 1) < 0 ? (length - 1) : index - 1;
    return prev_index;
};

export const getNextIndex = (index, length) => {
    const next_index = (index + 1) === length ? 0 : index + 1;
    return next_index;
};
<|endoftext|>