<commit_before>/*
 * Copyright 2008-2013 Microarray Informatics Team, EMBL-European Bioinformatics Institute
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *
 * For further details of the Gene Expression Atlas project, including source code,
 * downloads and documentation, please see:
 *
 * http://gxa.github.com/gxa
 */

/*global $,jQuery,console,loadSliderAndPlot: false */
/*jslint browser:true */
/*jslint nomen: true*/

var heatmapModule = (function ($) {

    "use strict";

    function showTranscriptBreakdownFancyBox(){
        $.fancybox({
                href: '#transcript-breakdown',
                padding: 0,
                openEffect: 'elastic',
                closeEffect: 'elastic',
                helpers: {
                    overlay: {
                        locked: false
                    }
                }
            }
        );
    }

    function showCellText(div) {
        $(div).removeClass("hide_cell").addClass("show_cell");
    }

    function hideCellText(div) {
        $(div).removeClass("show_cell").addClass("hide_cell");
    }

    function showExpressionLevels() {
        $("div[data-color]").each(function () {
            showCellText(this);
        });
        $(".gradient-level-min").attr("style", 'white-space: nowrap;');
        $(".gradient-level-max").attr("style", 'white-space: nowrap;');
    }

    function hideExpressionLevels() {
        $("div[data-color]").each(function () {
            hideCellText(this);
        });
        $(".gradient-level-min").css("display", "none");
        $(".gradient-level-max").css("display", "none");
    }

    function initDisplayLevelsButton() { //binds toggle handler

        $("#display-levels").button()
            .toggle(
            function () {
                $(this).button('option', 'label', 'Hide levels');
                showExpressionLevels(this);
                $("#prefForm #displayLevels").val("true");
            },
            function () {
                $(this).button('option', 'label', 'Display levels');
                hideExpressionLevels(this);
                $("#prefForm #displayLevels").val("false");
            }
        );

        if ($("#prefForm #displayLevels").val() === "true") {
            $("#display-levels").click();
        }

    }

    function initHeatmapCellsClickHandling(experimentAccession, species, selectedFilterFactorsJson) { //binds heatmap cells click handler

        function buildPlotData(transcriptRates) {
            var data = [],
                index = 0;
            $.each(transcriptRates, function (key, value) {
                data[index++] = {label: key, data: Math.abs(value.toFixed(1)), color: (value < 0 ? 'white' : undefined)};
            });
            return data;
        }

        $("#heatmap-table td:has(div[data-color])").click(function () {

            //we need to identify gene and factorType for the cell being clicked
            var factorValue = $(this).find("div").attr("data-organism-part"),
                factorType = $("#queryFactorType").attr("value"),
                geneId = $(this).parent().find("td a:eq(0)").attr("id"),
                geneName = $(this).parent().find("td a:eq(0)").text();

            $('#transcript-breakdown').css('position','absolute')
                                      .css('left','-5000px')
            $('#transcript-breakdown').show();

            $.ajax({
                url: "json/transcripts/" + experimentAccession,
                type: "GET",
                data: {
                    'geneId': geneId,
                    'factorType': factorType,
                    'factorValue': factorValue,
                    'selectedFilterFactorsJson': JSON.stringify(selectedFilterFactorsJson)
                },
                datatype: 'json',
                success: function (data) {
                    var totalCount = data.totalTranscriptsCount,
                        plotData = buildPlotData(data.transcriptExpressions);

                    species = species.replace(" ", "_");

                    $.plot('#transcripts-pie', plotData, {
                        series: {
                            pie:{stroke: {
                                    color: "#d3d3d3"
                                },
                                show: true
                            }
                        },
                        legend: {

                            show: true,
                            labelFormatter: function (label) {
                                return label === "Others" ? "Others" :
                                    "<a class='transcriptid' href='http://www.ensembl.org/" + species + "/Transcript/Summary?g=" + geneId + ";t="
                                        + label + "' target='_blank'" + "title='View transcript in Ensembl'" + ">" +
                                        label + "</a>";
                            }
                        }
                    });

                    var s = '';
                    if (totalCount > 1) {
                        s = 's';
                    }

                    $('#transcript-breakdown-title').html("Expression Level Breakdown for " +
                        "<a id='geneid' href='http://www.ensembl.org/" + species + "/Gene/Summary?g=" + geneId +
                        "' target='_blank'" + "title='View gene in Ensembl'" + ">" +
                        geneName + "</a>" + " (" + totalCount + " transcript" + s + ") in " + factorValue);

                    //next line is required because the div is configured to stay in an invisible position (position:absolute; left:-5000px)
                    //in order to make it invisible during the show-up of fancybox
                    //all of this is required because of IE8 :( . It doesn' t allow painting canvas in a hidden div, so we need to first show the div, then paint in it, then reposition it, then fancybox it...
                    $('#transcript-breakdown').hide();
                    $('#transcript-breakdown').css('position','relative')
                                              .css('left','0px');

                    showTranscriptBreakdownFancyBox();
                }
            }).fail(function (data) {
                    console.log("ERROR:  " + data);
            });

        });
    }

    //there must be a cleaner way to do this, but I don't know it yet!
    function buildHeatmapCellTooltip(expressionLevel, tstatistic, foldChange) {<commit_msg>javascript refactorings<commit_after>/*
 * Copyright 2008-2013 Microarray Informatics Team, EMBL-European Bioinformatics Institute
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *
 * For further details of the Gene Expression Atlas project, including source code,
 * downloads and documentation, please see:
 *
 * http://gxa.github.com/gxa
 */

/*global $,jQuery,console,loadSliderAndPlot: false */
/*jslint browser:true */
/*jslint nomen: true*/

var heatmapModule = (function ($) {

    "use strict";

    function showTranscriptBreakdownFancyBox(){
        $.fancybox({
                href: '#transcript-breakdown',
                padding: 0,
                openEffect: 'elastic',
                closeEffect: 'elastic',
                helpers: {
                    overlay: {
                        locked: false
                    }
                }
            }
        );
    }

    function showCellText(div) {
        $(div).removeClass("hide_cell").addClass("show_cell");
    }

    function hideCellText(div) {
        $(div).removeClass("show_cell").addClass("hide_cell");
    }

    function showExpressionLevels() {
        $("div[data-color]").each(function () {
            showCellText(this);
        });
        $(".gradient-level-min").attr("style", 'white-space: nowrap;');
        $(".gradient-level-max").attr("style", 'white-space: nowrap;');
    }

    function hideExpressionLevels() {
        $("div[data-color]").each(function () {
            hideCellText(this);
        });
        $(".gradient-level-min").css("display", "none");
        $(".gradient-level-max").css("display", "none");
    }

    function initDisplayLevelsButton() { //binds toggle handler

        $("#display-levels").button()
            .toggle(
            function () {
                $(this).button('option', 'label', 'Hide levels');
                showExpressionLevels(this);
                $("#prefForm #displayLevels").val("true");
            },
            function () {
                $(this).button('option', 'label', 'Display levels');
                hideExpressionLevels(this);
                $("#prefForm #displayLevels").val("false");
            }
        );

        if ($("#prefForm #displayLevels").val() === "true") {
            $("#display-levels").click();
        }

    }

    function initHeatmapCellsClickHandling(experimentAccession, species, selectedFilterFactorsJson) { //binds heatmap cells click handler

        function buildPlotData(transcriptRates) {
            var data = [],
                index = 0;
            $.each(transcriptRates, function (key, value) {
                data[index++] = {label: key, data: Math.abs(value.toFixed(1)), color: (value < 0 ? 'white' : undefined)};
            });
            return data;
        }

        function paintPieChart(plotData, geneId){
            $.plot('#transcripts-pie', plotData, {
                series: {
                    pie:{stroke: {
                        color: "#d3d3d3"
                    },
                        show: true
                    }
                },
                legend: {
                    show: true,
                    labelFormatter: function (label) {
                        return label === "Others" ? "Others" :
                                "<a class='transcriptid' href='http://www.ensembl.org/" + species + "/Transcript/Summary?g=" + geneId + ";t="
                                + label + "' target='_blank'" + "title='View transcript in Ensembl'" + ">" +
                                label + "</a>";
                    }
                }
            });
        }

        //on click...
        $("#heatmap-table td:has(div[data-color])").click(function () {

            //gene and factor properties are extracted from gene and factor headers in the html table
            var factorValue = $(this).find("div").attr("data-organism-part"),
                factorType = $("#queryFactorType").attr("value"),
                geneId = $(this).parent().find("td a:eq(0)").attr("id"),
                geneName = $(this).parent().find("td a:eq(0)").text();

            $.ajax({
                url: "json/transcripts/" + experimentAccession,
                type: "GET",
                data: {
                    'geneId': geneId,
                    'factorType': factorType,
                    'factorValue': factorValue,
                    'selectedFilterFactorsJson': JSON.stringify(selectedFilterFactorsJson)
                },
                datatype: 'json',
                success: function (data) {
                    var totalCount = data.totalTranscriptsCount,
                        plotData = buildPlotData(data.transcriptExpressions);

                    species = species.replace(" ", "_");

                    $('#transcript-breakdown').css('position','absolute')
                        .css('left','-5000px')
                    $('#transcript-breakdown').show();

                    paintPieChart(plotData, geneId);

                    //next line is required because the div is configured to stay in an invisible position (position:absolute; left:-5000px)
                    //in order to make it invisible during the show-up of fancybox
                    //all of this is required because of IE8 :( . It doesn' t allow painting canvas in a hidden div, so we need to first show the div, then paint in it, then reposition it, then fancybox it...
                    $('#transcript-breakdown').hide();
                    $('#transcript-breakdown').css('position','relative')
                        .css('left','0px');

                    showTranscriptBreakdownFancyBox();

                    var s = '';
                    if (totalCount > 1) {
                        s = 's';
                    }

                    $('#transcript-breakdown-title').html("Expression Level Breakdown for " +
                        "<a id='geneid' href='http://www.ensembl.org/" + species + "/Gene/Summary?g=" + geneId +
                        "' target='_blank'" + "title='View gene in Ensembl'" + ">" +
                        geneName + "</a>" + " (" + totalCount + " transcript" + s + ") in " + factorValue);

                }
            }).fail(function (data) {
                    console.log("ERROR:  " + data);
            });

        });
    }

    //there must be a cleaner way to do this, but I don't know it yet!
    function buildHeatmapCellTooltip(expressionLevel, tstatistic, foldChange) {
{'fraction_non_alphanumeric': 0.13379930104842735, 'fraction_numerical': 0.004564581698880251, 'mean_word_length': 1.6010016694490818, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 6, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 12, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '819868', 'n_tokens_mistral': 3670, 'n_tokens_neox': 3377, 'n_words': 859}