/*
 * Communication section
 */
var ws = new WebSocket('ws://' + window.location.origin.split('//')[1] + '/socket');

var morphology_callback = function(msg) {};
var graph_callback = function(msg) {};
var shapeplot_callback = function(msg) {};

function send_message(msg) {
    ws.send(JSON.stringify(msg));
}

// solution for getting matching ids modified from
// http://stackoverflow.com/questions/3239598/how-can-i-get-the-id-of-an-element-using-jquery
function matched_ids(condition) {
    var retval = [];
    $(condition).each(function(){
        retval.push($(this).prop('id'));
    })
    return retval;
}

$(function() {
    if ('WebSocket' in window) {
        ws.onopen = function() {
            onready();
            
            // set the on-change event for all settings
            $('.settings input').change(function() {
                var message = {'command': 'setfields'};
                var ids = matched_ids('.settings input');
                for (var i = 0; i < ids.length; i++) {
                    message[ids[i]] = parseFloat($('#' + ids[i]).val());
                }
                send_message(message);
            });
        };
        ws.onmessage = function (evt) {
            var message = JSON.parse(evt.data);
            // TODO: do things depending on message.command
            if (message.command == 'setmorphology') {
                morphology_callback(message);
            } else if (message.command == 'setgraph') {
                graph_callback(message);
            } else if (message.command == 'setshapeplot') {
                shapeplot_callback(message);
            } else if (message.command == 'setfields') {
                var data = message.data;
                var keys = Object.keys(data);
                for (i = 0; i < keys.length; i++) {
                    $('#' + keys[i]).val(data[keys[i]]);
                }
            } else {
                console.log('message received');
                console.log(message);
            }
        };
        ws.onclose = function() { 
            document.write('Server connection lost; try refreshing the page.');
        };
    } else {
        document.write('Sorry, but this browser does not support websockets.');
    }
});

/*
 * graphics support, neuronweb overrides
 */
var neuronviewer_lookup = {};

function AddNeuronViewer(id, data, cellviews) {
    neuron_colors_[id] = undefined;
    neuron_data_[id] = data;
    neuron_viewer_views_[id] = cellviews;
    var panel_id = AddButtonSet(id, ['X-Y', 'X-Z', 'Y-Z'], {selected:0, callback: function(a) {neuron_view_[id] = a; redraw_neuron(id);}});
    // center the button set
    $('#' + id + ' form').css('text-align', 'center');
    var flot_id = AddChart(id, {contextmenu: false, doplot: false, aspectratio: 1});
    neuronviewer_lookup[id] = flot_id;
    redraw_neuron(id);
    // a space for putting things below the graph
    $('#' + id).append('<div id="below' + id + '" style="display:none;"></div>');
    $('#' + id).resize(function() {
        $('#placeholder' + flot_id).height(max(250, $('#' + id).height() - $('#' + panel_id).height() - $('#below' + id).height() - 50));        
        plottedFlot['placeholder' + flot_id].draw();
    });
    return id;
}


// override a function from myDialog
function redraw_neuron(id) {
    /* view == 0: x-y plane
     * view == 1: x-z plane
     * view == 2: y-z plane
     */
    data = neuron_data_[id];
    view = neuron_view_[id];
    if (view == undefined) view = 0;
    colors = neuron_colors_[id];
    var plot_data = [];
    $.each(data, function(i, segment) {
        var color = 'black';
        if (colors != undefined) color = colors[i];
        var local_plot_data = [];
        $.each(segment, function(j, pt) {
            local_plot_data.push(project_pt(pt, view));
        });
        plot_data.push({data: local_plot_data, color: color});
    });
    if (neuron_markers_[id] != undefined) {
        var local_plot_data = [];
        $.each(neuron_markers_[id], function(i, pt) {
            local_plot_data.push(project_pt(pt, view));
        });
        plot_data.push({data: local_plot_data, points: {show: true}, color: 'red'});
    }
    var xmin = data.xmin;
    var xmax = data.xmax;
    var ymin = data.ymin;
    var ymax = data.ymax;
    var cellviews = neuron_viewer_views_[id];
    if (cellviews != undefined) {
        if (cellviews.length == 3) {
            if (cellviews[view].length == 4) {
                xmin = cellviews[view][0];
                ymin = cellviews[view][1];
                xmax = cellviews[view][2];
                ymax = cellviews[view][3];
            }
        }
    }
    // really want the neuronviewer id
    id = neuronviewer_lookup[id];
    console.log('id =', id);
    plottedFlot['placeholder' + id] = $.plot($('#placeholder' + id), plot_data, {
        yaxis: {min: ymin, max: ymax, show: false}, 
        aspectratio: {ratioXY: 1},
        xaxis: {min: xmin, max: xmax},
        zoom:  {interactive: true},
        pan:   {interactive: true},
        grid:  {show: true, hoverable: true}
    });
    
}

