/*jslint browser: true */
/*globals $, tangelo, d3 */

var app = {};
app.redgreen = d3.scale.linear()
    .domain([-1, 0, 1])
    .range(["red", "black", "green"]);

function plotMicroarray(data, exp, spots, cmap) {
    var svg,
        width = 20,
        height = 10,
        expmap = {},
        spotmap = {};

    $.each(spots, function (i, v) {
        spotmap[v] = i;
    });

    $.each(exp, function (i, v) {
        expmap[v] = i;
    });

    svg = d3.select("#microarray")
        .append("svg")
        .attr("width", width * exp.length)
        .attr("height", height * spots.length);

    svg.selectAll("rect")
        .data(data)
        .enter()
        .append("rect")
        .attr("width", width)
        .attr("height", height)
        .attr("x", function (d) {
            return expmap[d.experiment] * width;
        })
        .attr("y", function (d) {
            return spotmap[d.spot] * height;
        })
        .style("fill", "black")
        .each(function (d) {
            var msg,
                cfg;

            msg = "";
            msg += "<b>Experiment:</b> " + d.experiment + "<br>\n";
            msg += "<b>Locus:</b> " + d.locus + "<br>\n";
            msg += "<b>Spot:</b> " + d.spot + "<br>\n";
            msg += "<b>Channel 1</b>: " + d.ch1mean + "<br>\n";
            msg += "<b>Channel 2</b>: " + d.ch2mean;

            cfg = {
                html: true,
                container: "body",
                placement: "right",
                trigger: "hover",
                content: msg,
                delay: {
                    show: 0,
                    hide: 0
                }
            };

            $(this).popover(cfg);
        })
        .transition()
        .duration(500)
        .style("fill", function (d) {
            return cmap(d.balance);
        });
}

$(function () {
    "use strict";

    // Retrieve microarray data from the data service.
    d3.json("data/data/data?take=100", function (error, data) {
        if (error) {
            tangelo.fatalError("microarray.js", error);
        }

        d3.json("data/data/experiments", function (error, experiments) {
            if (error) {
                tangelo.fatalError("microarray.js", error);
            }

            d3.json("data/data/spots?take=100", function (error, spots) {
                if (error) {
                    tangelo.fatalError("microarray.js", error);
                }

                plotMicroarray(data, experiments, spots, app.redgreen);
            });
        });
    });
});
