/* SOURCE : http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript */

/**
 * Converts an HSV color value to RGB. Conversion formula
 * adapted from http://en.wikipedia.org/wiki/HSV_color_space.
 * Assumes h, s, and v are contained in the set [0, 1] and
 * returns r, g, and b in the set [0, 255].
 *
 * @param   Number  h       The hue
 * @param   Number  s       The saturation
 * @param   Number  v       The value
 * @return  Array           The RGB representation
 */
function hsvToRgb(h, s, v){
    var r, g, b;

    var i = Math.floor(h * 6);
    var f = h * 6 - i;
    var p = v * (1 - s);
    var q = v * (1 - f * s);
    var t = v * (1 - (1 - f) * s);

    switch(i % 6){
        case 0: r = v, g = t, b = p; break;
        case 1: r = q, g = v, b = p; break;
        case 2: r = p, g = v, b = t; break;
        case 3: r = p, g = q, b = v; break;
        case 4: r = t, g = p, b = v; break;
        case 5: r = v, g = p, b = q; break;
    }

    return _([r * 255, g * 255, b * 255]).map(Math.floor);
}

$(function(){

    var IDEALRATIO = 1.33;

    function cuttree(data, x, y, w, h, cut, ratio, callback) {
        
        function f(subdata, subx, suby, subw, subh) {
            if (subdata.length == 1) {
                subdata[0].x = subx;
                subdata[0].y = suby;
                subdata[0].w = subw;
                subdata[0].h = subh;
            } else {
                callback(subdata, subx, suby, subw, subh)
            }
        }
        
        var first = _(data).first(cut), rest = _(data).rest(cut);
        if (!first.length || !rest.length) {
            return;
        }
        if (w/h > IDEALRATIO) {
            var leftw = w * ratio;
            f(first, x, y, leftw, h);
            f(rest, x + leftw, y, w - leftw, h);
        } else {
            var toph = h * ratio;
            f(first, x, y, w, toph);
            f(rest, x, y + toph, w, h - toph);
        }
    }

    function pivot(data, x, y, w, h) {
        if (data.length == 1) {
            data[0].x = x;
            data[0].y = x;
            data[0].w = w;
            data[0].h = h;
            return;
        }
        var cut = 1, cumul = 0, bestcumul = 0, total = _(data).reduce(function(a,b){return a+b.value},0), bestcut = Infinity;
        for (var i = 0; i < data.length - 1; i++) {
            cumul += data[i].value;
            var delta = Math.abs(cumul - total/2);
            if (delta < bestcut) {
                bestcut = delta;
                bestcumul = cumul;
                cut = i+1;
            } else {
                break;
            }
        }
        cuttree(data, x, y, w, h, cut, bestcumul / total, pivot);
    }

    function squarify(data, x, y, w, h) {
        if (data.length == 1) {
            data[0].x = x;
            data[0].y = x;
            data[0].w = w;
            data[0].h = h;
            return;
        }
        var cut = 1, cumul = 0, bestcumul = 0, total = _(data).reduce(function(a,b){return a+b.value},0), bestcut = Infinity;
        for (var i = 0; i < data.length - 1; i++) {
            cumul += data[i].value;
            cuttree(data, x, y, w, h, i+1, cumul / total, pivot);
            var ratio = Math.abs(Math.log(IDEALRATIO*data[0].h/data[0].w));
            if (ratio < bestcut) {
                bestcut = ratio;
                bestcumul = cumul;
                cut = i+1;
            } else {
                break;
            }
        }
        cuttree(data, x, y, w, h, cut, bestcumul / total, squarify);
    }
    

    /* Templates des éléments à insérer */
   
    var articleTemplate = _(
        '<div class="cluster-article" style="left: <%=x%>px; top: <%=y%>px; width: <%=w%>px; height: <%=h%>px;">'+
            '<img src="<%=image_url%>" />' +
        '</div>'
    ).template();
    var clusterTemplate = _( 
    '<div class="actu" style="left: <%=x%>px; top: <%=y%>px; width: <%=w - 1%>px; height: <%=h - 1%>px; background: #ffffff" data-cluster-id="<%=id%>">'+
        '<%=articles%>'+ // Pour l'image composite
        '<img src="<%=image_url%>" />' + // Pour l'image de cluster
        '<div class="voile"></div>'+
        '<div class="inner-actu">'+
            '<h2><a href="#"><%-label%></a></h2>'+
            '<div class="links">'+
                '<ul>'+
                    '<li><a href="#" title="<%=annotation_count%> Annotations sur ce cluster" class="file"><span><%=annotation_count%></span></a></li>'+
                '</ul>'+
            '</div>'+
        '</div>'+
        '<p class="abstract"><%= abstract %></p>'+
    '</div>'
    ).template();


    var hTreemap = 600;//à définir
    $('#treemap').height(hTreemap);
    
    function showResults(results) {
        var data = _(results.clusters).map(function(cluster, i) {
            var hue = (parseInt(cluster.id)%6)/6
            return {
                id: cluster.id,
                label: cluster.title,
                abstract : cluster.abstract,
                value: parseFloat(cluster.weight),
                color: "rgb(" + hsvToRgb(hue,.8,.8).join(",") + ")",
                annotation_count: cluster.annotations.length,
                image_url: cluster.url_image || false,
                articles: cluster.documents.filter(function(article) {
                    return !!article.url_image
                })
                .map(function(article, j) {
                    return {
                        value: parseFloat(article.weight),
                        image_url: article.url_image || false
                    }
                })
            }
        });
        data = _(data).sortBy(function(d) {
            return -d.value;
        });
        squarify(data,0,0,760,hTreemap);
        _(data).each(function(cluster) {
            squarify(cluster.articles, 0, 0, cluster.w - 1, cluster.h - 1);
            _(cluster.articles).sortBy(function(d) {
                return -d.value;
            });
            cluster.articles = _(cluster.articles).reduce(function(mem, a) {
                return mem + articleTemplate(a);
            }, "");
        });
        var treemapHtml = _(data).reduce(function(mem, d) {
            return mem + clusterTemplate(d);
        },"");
        $('#treemap #actus').html(treemapHtml);
        
        //redimensionnement d'image
        
        $(".actu img").each(function() {
            var img = $(this),
                div = $(this).parent();
            img.load(function() {
                var iw = img.width(),
                    ih = img.height(),
                    dw = div.width(),
                    dh = div.height(),
                    scale = Math.max(dw/iw, dh/ih),
                    niw = iw * scale,
                    nih = ih * scale;
                img.css({
                    width: niw,
                    height: nih,
                    "margin-left": (dw - niw) / 2,
                    "margin-top": (dh - nih) / 3
                });
            });
        });
        
        $(".actu").hover(
            function() {
                $("body").trigger("select-cluster", $(this).attr("data-cluster-id"));
            },
            function() {
                $("body").trigger("unselect-cluster", $(this).attr("data-cluster-id"));
            }
        )
        $("body").on("select-cluster", function(e, clusterid) {
            $(".actu[data-cluster-id='" + clusterid + "']").addClass("selected");
        });
        $("body").on("unselect-cluster", function(e, clusterid) {
            $(".actu[data-cluster-id='" + clusterid + "']").removeClass("selected");
        });
    }
    
    function renderJson(url) {
        $.getJSON(url, showResults);
    }
    
    renderJson("data/requete.json");
    
    $(".header-menu a").click(function() {
        if ($(this).text() == "INTERNATIONAL") {
            renderJson("data/requete_filtre_international.json");
        }
        if ($(this).text() == "FRANCE") {
            renderJson("data/requete_filtre_france.json");
        }
        if ($(this).hasClass("home")) {
            renderJson("data/requete.json")
        }
        return false;
    });


    $("#liste").hide();
})