$(function(){

    var IDEALRATIO = 1.25;

    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);
    }
    
    /* 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);
    }

    /* Templates des éléments à insérer */
   
    var articleTemplate = _(
        '<div class="cluster-article" style="position: absolute; left: <%=x%>px; top: <%=y%>px; width: <%=w%>px; height: <%=h%>px; background: <%=color%>">'+
            '<%=label%>'+
        '</div>'
    ).template();
    var clusterTemplate = _( 
    '<div class="actu" style="left: <%=x%>px; top: <%=y%>px; width: <%=w%>px; height: <%=h%>px; background: <%=color%>">'+
        '<a href="#">'+
//            '<img src="img/home-visuel-<%-i%>.jpg" alt="" />'+
        '<%=articles%>'+
        '<div class="voile"></div>'+
        '</a>'+
        '<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>'+
    '</div>'
    ).template();


    var hTreemap = 600;//à définir
    $('#treemap').height(hTreemap);
    
    function showResults(results) {
        var data = _(results.clusters).map(function(cluster, i) {
            var hue = (i%6)/6
            return {
                label: cluster.title,
                value: parseFloat(cluster.weight),
                color: "rgb(" + hsvToRgb(hue,.8,.8).join(",") + ")",
                annotation_count: cluster.annotations.length,
                articles: _(cluster.documents).map(function(article, j) {
                    return {
                        label: article.title,
                        value: parseFloat(article.weight),
                        color: "rgb(" + hsvToRgb(hue,.8,.9-.1*(j%6)).join(",") + ")"
                    }
                })
            }
        });
        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, cluster.h);
            _(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);
    }
    
    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;
    });
    
    //redimensionnement d'image
/*
     $(".actu").each(function(k,v){
        var wActu = $(this).width();
        var hActu = $(this).height();
        var img = $(this).find('img');
        img.load(function(){
            var img = $(this);

            var wImg = img.width();
            var hImg = img.height();

            var ratioImg = wImg/hImg;
            img.css('height',hActu);
            img.css('width',hActu*ratioImg);
            wImg = img.width();
            hImg = img.height();

            if(wActu>wImg){
                var ratioImg = hImg/wImg;
                img.css('width', wActu);
                img.css('height',wActu*ratioImg);
                wImg = img.width();
                hImg = img.height();
            }

            if (wImg<wActu) {
                img.css('margin-left',(wActu-wImg)/2);
            }else{
                img.css('margin-left',-(wImg-wActu)/2);
            }
            if (hImg<hActu) {
                img.css('margin-top',(hActu-hImg)/2);
            }else{
                img.css('margin-top',-(hImg-hActu)/2);
            }
        });
    });
*/


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