    /***************************************
        This file was created originally by
        Anton Kaiser & Isac Algström
        Last checked 2016-03-23
    ***************************************/

    // Width and height of visualization
    var width = 1250;
    var height = 510;

    var drawDatacount = 0;

    // Bar parameters
    var barWidth = 5;
    var spaceBetweenBars = 6;

    // ColorCubes parameters
    var spaceBetweenColorCubes = 100;
    var colorCubeDimension = 8;
    var colorArray = [1, 2, 3, 4, 5, 6, 7, 8];

    // showId will contain allowed Id:s 
    var showId = [];

    var filterChoice = [0,0,0,0,0,0,0,0,0];
    //Gender variables
    var menCheck = 0;
    var womenCheck = 0;
    
    //CivilState variables
    var married = 0;
    var single = 0;
    var widow = 0;
    var divorced = 0;

    // Scales for X and Y
    var X_axisScale = d3.scale.linear() // Ny range från domän
            .domain([0, 200])
            .range([0, width]);

    var Y_axisScale = d3.scale.linear()
            .domain([0,10])
            .range([height, 0]);

    // Scale used for bars
    var  heightScale = d3.scale.linear()
            .domain([0, 3450])
            .range([0, 460]);

    // ColorScales for bars
    var colorScale = d3.scale.linear()
            .domain([0, height])
            .range(["green","teal"]);

    var colorScaleTwo = d3.scale.linear()
            .domain([0, 100])
            .range(["green","red"]);

    var colorPsychOpen = d3.scale.linear()
            .domain([0, 3])
            .range(["#000099","#4d94ff"]);

    var colorPsychClose = d3.scale.linear()
            .domain([0, 3])
            .range(["red","#ff5050"]);

    var colorSocialCont = d3.scale.linear()
            .domain([0, 7])
            .range(["#008000","#66cc99"]);

    var colorCrime = d3.scale.linear()
            .domain([0, 4])
            .range(["#800080","#d65cad"]);

    var colorMedicine = d3.scale.linear()
            .domain([0, 5])
            .range(["teal","#85e0e0"]);

    // X- and Y-axis
    var X_axis = d3.svg.axis()
            .ticks(5)
            .scale(X_axisScale)

    var Y_axis = d3.svg.axis()
            .ticks(10)
            .tickFormat(function(i){return "År " + i;})
            .scale(Y_axisScale)
            .orient("left");

    // Canvas to draw visualization on
    var canvas = d3.select("body")
            .append("svg")
            .attr("width", width)
            .attr("height", height+140)
            .append("g")
            .attr("transform", "translate(40,20)");

function fillArray(){

        d3.csv("facts.csv", function(fData){

        var personLane = canvas.selectAll("rect")

        var personZ = personLane.select("rect")
                .data(fData)
                .enter()
                .append("rect")
                .attr("height",function(d,i){ 
                    
                    if(filterChoice[0] == 2 && d.Gender == 2){
                        //console.log("Women showId = " + d.Id);
                        showId.push(d.Id);
                    }
                    else if(filterChoice[0] == 1 && d.Gender == 1){
                        //console.log("Men showId = " + d.Id);
                        showId.push(d.Id);
                    }
                    else if(filterChoice[0] == 3){
                        //console.log("Men and Women showId = " + d.Id);
                        showId.push(d.Id);
                    }
                    else if(filterChoice[0] == 0){};
                });
     });
    drawData();
};

function drawData(){
    
    // Clear canvas before draw
    canvas.selectAll("*").remove();

    // Apply X-axis to canvas and translate
    canvas.append("g")
            .attr("transform","translate(0,506)")
            .call(X_axis);

    // Apply Y-axis to canvas and translate
    canvas.append("g")
            .attr("transform","translate(17,0)")
            .call(Y_axis);

        //console.log("drawDatacount = " + drawDatacount);
    d3.csv("events.csv", function(data){

        // Lanes to append variables to
        var personLanes = canvas.selectAll("rect")

        // Create rectangle for every Id in .csv
        var personId = personLanes.select("rect")
                .data(data)
                .enter()
                .append("rect")
                .attr("width",1)
                .filter(function(d,i){ return (d.Id == inArray(d.Id, showId)); })
                .attr("height",function(d){ return (0); })
                .attr("fill","")
                .attr("x", function(d){ return (d.Id * spaceBetweenBars + 12); })
                .attr("y", function(d) { return (height-4); });

        // Create rectangle for every Id with Somatic in .csv
        var personSomatic = personLanes.select("rect")
                .data(data) // Data is the data from .csv
                .enter()
                .append("rect") // Declare bar as rectangle
                .attr("width",5) // Width of bar
                .filter(function(d,i){ return (d.Id == inArray(d.Id, showId)); })
                .attr("height",function(d,i){ // Height of bar

                    if(d.Somatic != 0){ // If ID has Somatic return correct height of bar
                      
                        return heightScale(getNumberOfDays(d.Start, d.End));
                    }
                    else return 0; // If Id does NOT have Somatic height is zero
                    
                })
                .attr("fill", function(d){
                return "blue";
                 }) // Set color on bar
                .attr("x", function(d){
                
                return (d.Id * spaceBetweenBars + 12);}) // Put rectangle at correct x-position
                .attr("y", function(d) { // Put rectangle at correct y-position
                    if(d.Somatic != 0){
                        return 510-heightScale(getNumberOfDays(d.Start,d.End))
                                -heightScale(getNumberOfDays(d.FirstPsychosis,d.Start));
                    }
                    else return 0;
                });
        
       // Create rectangle for every ID with PsychOpen in .csv
        var personPsychOpen = personLanes.select("rect")
                .data(data)
                .enter()
                .append("rect")
                .attr("width",5)
                .filter(function(d,i){ return (d.Id == inArray(d.Id, showId)); })
                .attr("height",function(d){
                    if(d.PsychOpen != 0){
                        return heightScale(getNumberOfDays(d.Start, d.End));
                    }
                    else return 0;
                })
                .attr("fill", function(d) {
                    return colorPsychOpen(d.PsychOpen);}
                )
                .attr("x", function(d){
                    return (d.Id * spaceBetweenBars + 12);})
                .attr("y", function(d) {
                    if(d.PsychOpen != 0){
                        return 510-heightScale(getNumberOfDays(d.Start,d.End))
                                -heightScale(getNumberOfDays(d.FirstPsychosis,d.Start));
                    }
                    else return 0;
                });

   // Create rectangle for every ID with SocialCont in .csv
        var personSocialCont = personLanes.select("rect")
                .data(data)
                .enter()
                .append("rect")
                .attr("width",5)
                .filter(function(d,i){ return (d.Id == inArray(d.Id, showId)); })
                .attr("height",function(d){
                    if(d.SocialCont != 0){
                        return heightScale(getNumberOfDays(d.Start, d.End));
                    }
                    else return 0;
                })
                .attr("fill", function(d) {
                    return colorSocialCont(d.SocialCont);}
                )
                .attr("x", function(d){
                    return (d.Id * spaceBetweenBars + 12);})
                .attr("y", function(d) {
                    if(d.SocialCont != 0){
                        return 510-heightScale(getNumberOfDays(d.Start,d.End))
                                -heightScale(getNumberOfDays(d.FirstPsychosis,d.Start));
                    }
                    else return 0;
                });

      // Create rectangle for every ID with Crime in .csv
        var personCrime = personLanes.select("rect")
                .data(data)
                .enter()
                .append("rect")
                .attr("width",5)
                .filter(function(d,i){ return (d.Id == inArray(d.Id, showId)); })
                .attr("height",function(d){
                    if(d.Crime != 0){
                        return heightScale(getNumberOfDays(d.Start, d.End));
                    }
                    else return 0;
                })
                .attr("fill", function(d){return colorCrime(d.Crime);})
                .attr("x", function(d){
                    return (d.Id * spaceBetweenBars + 12);})
                .attr("y", function(d) {
                    if(d.Crime != 0){
                        return 510-heightScale(getNumberOfDays(d.Start,d.End))
                                +-heightScale(getNumberOfDays(d.FirstPsychosis,d.Start));
                    }
                    else return 0;
                });
        
        // Create rectangle for every ID with Dead in .csv
        var personDead = personLanes.select("rect")
                .data(data)
                .enter()
                .append("rect")
                .attr("width",5)
                .filter(function(d,i){ return (d.Id == inArray(d.Id, showId)); })
                .attr("height",function(d){
                    if(d.Dead == 1){
                        return heightScale(getNumberOfDays(d.Start, d.End));
                    }
                    else return 0;
                })
                .attr("fill", "yellow")
                .attr("x", function(d){
                    return (d.Id * spaceBetweenBars + 12);})
                .attr("y", function(d) {
                    if(d.Dead == 1){
                        return 510-heightScale(getNumberOfDays(d.Start,d.End))
                                -heightScale(getNumberOfDays(d.FirstPsychosis,d.Start));
                    }
                    else return 0;
                });

        // Create rectangle for every ID with Medicine in .csv
        var personMedicine = personLanes.select("rect")
                .data(data)
                .enter()
                .append("rect")
                .attr("width",5)
                .filter(function(d,i){ return (d.Id == inArray(d.Id, showId)); })
                .attr("height",function(d){
                    if(d.Medicine != 0){
                        return heightScale(getNumberOfDays(d.Start, d.End));
                    } else return 0;
                })
                .attr("fill", function(d) {
                    return colorMedicine(d.Medicine);}
                )
                .attr("x", function(d){
                    return (d.Id * spaceBetweenBars + 12);})
                .attr("y", function(d) {
                    if(d.Medicine != 0){
                        return 510-heightScale(getNumberOfDays(d.Start,d.End))
                                -heightScale(getNumberOfDays(d.FirstPsychosis,d.Start));
                    }
                    else return 0;
                });

        // Create rectangle for every ID with PsychClose in .csv
        var personPsychClose = personLanes.select("rect")
                .data(data)
                .enter()
                .append("rect")
                .attr("width",5)
                .filter(function(d,i){ return (d.Id == inArray(d.Id, showId)); })
                .attr("height",function(d){
                    if(d.PsychClose != 0){
                        return heightScale(getNumberOfDays(d.Start, d.End));
                    }
                    else return 0;
                })
                .attr("fill", function(d) {
                    return colorPsychClose(d.PsychClose);}
                )
                .attr("x", function(d){
                    return (d.Id * spaceBetweenBars + 12);})
                .attr("y", function(d) {
                    if(d.PsychClose != 0){
                        return 510-heightScale(getNumberOfDays(d.Start,d.End))
                                -heightScale(getNumberOfDays(d.FirstPsychosis,d.Start));
                    }
                    else return 0;
                });
        });
        clearArray();
    }

    // Apply X-axis to canvas and translate
    canvas.append("g")
            .attr("transform","translate(0,506)")
            .call(X_axis);

    // Apply Y-axis to canvas and translate
    canvas.append("g")
            .attr("transform","translate(17,0)")
            .call(Y_axis);

    // Return number of days between two dates (Start, end)
    function getNumberOfDays(start, end)
    {
        var days = 0;
        var msToDays = 1000*3600*24;
        var startDate = start.split('-');
        var endDate = end.split('-');
        var d1 = new Date(startDate[0],startDate[1],startDate[2]);
        var d2 = new Date(endDate[0],endDate[1],endDate[2]);

        days = Math.ceil((d2-d1)/msToDays);
        return days;
    };

    function inArray(elem,array){
    var Id = 0;
    //console.log("array.length in function inArray = " + array.length);
        for(var i = 0 ; i < array.length;i++)
        {
            if(array[i] == elem){

                Id = elem;
                return Id;}
        }
        return 0;
    };

    function setMenCheck(){

        if (filterChoice[0] == 0) { filterChoice[0] = 1; }
        else if(filterChoice[0] == 2) { filterChoice[0] = 3; }
        else if (filterChoice[0] == 3) { filterChoice[0] = 2; }
        else { filterChoice[0] = 0}

        fillArray();
    };

    function clearArray(){
 
        showId.length = 0;
    };

    function setMarried(){
   
        if (married == 0) { married = 1; }
        else { married = 0; }

        fillArray();
    };

     function setSingle(){

        if (single == 0) { single = 1; }
        else { single = 0; }

        fillArray();
    };

     function setWidow(){

        if (widow == 0) { widow = 1; }
        else { widow = 0; }
        
        fillArray();
    };

    function setDivorced(){
 
        if (divorced == 0){ divorced = 1; }
        else { divorced = 0; }

        fillArray();
    };

    function setWomenCheck(){

        if (filterChoice[0] == 0) { filterChoice[0] = 2; }
        else if(filterChoice[0] == 1) { filterChoice[0] = 3; }
        else if (filterChoice[0] == 3) { filterChoice[0] = 1; }
        else { filterChoice[0] = 0}

        fillArray();
    };