//$(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="http://localhost:8000/<%=query_id%>/<%=id%>/0/12/0"><%-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();
    
    /* Templates pour la vue liste */
   
    var clusterListeTemplate = _(
      '<div class="article" data-cluster-id="<%= id %>">'+
           '<div class="inner-article clearfix">'+
               '<h2><a href="http://localhost:8000/<%=query_id%>/<%=id%>/0/12/0" title="Lire l\'article" > <%= title %> »</a></h2>'+
			   '<p class="number-article">'+
                   '<a href="http://localhost:8000/<%=query_id%>/<%=id%>/0/12/0"><%= documents_number %> articles | <%= annotations.length %> annotations </a>'+
                   '<a title="ajouter une annotation" class="add-annotation" href="#"></a>'+
               '</p>'+
                '<div class="article-annotations">'+
                   '<a title="48 annotations" class="blue" href="#" style="width:20%;"></a>'+
                   '<a title="title" class="green" href="#" style="width:20%;"></a>'+
                   '<a title="title" class="red" href="#" style="width:40%;"></a>'+
                   '<a title="title" class="empty" href="#" style="width:20%;"></a>'+
               '</div>'+
               '<div class="article-content">'+
                   '<p class="resume"><%= abstract %></p>'+
                    '<ul class="links">'+
                       '<ul>'+
                       '<% _(documents).each(function(d) { print("<li><a href=\'" + d.url_document + "\'>" + d.title.replace(/(^.{30,60})[\s].+$/m,\'$1&hellip;\') + "</a></li>"); }) %>'+
                       '</ul>'+
                   '</ul>'+
               '</div>'+
           '</div>'+
       '</div>'
    ).template();
	
	var clusterListeTemplateDossierDoc = _(
      '<div class="article" data-cluster-id="<%= id %>">'+
           '<div class="inner-article clearfix">'+
               '<h2><a href="http://localhost:8000/documentary_files/<%=user%>/<%=id%>/0/12/<%=doc_id%>" title="Lire l\'article" > <%= title %> »</a></h2>'+
			   '<p class="number-article">'+
                   '<a href="http://localhost:8000/documentary_files/<%=user%>/<%=id%>/0/12/<%=doc_id%>"><%= documents_number %> articles | <%= annotations.length %> annotations </a>'+
                   '<a title="ajouter une annotation" class="add-annotation" href="#"></a>'+
               '</p>'+
                '<div class="article-annotations">'+
                   '<a title="48 annotations" class="blue" href="#" style="width:20%;"></a>'+
                   '<a title="title" class="green" href="#" style="width:20%;"></a>'+
                   '<a title="title" class="red" href="#" style="width:40%;"></a>'+
                   '<a title="title" class="empty" href="#" style="width:20%;"></a>'+
               '</div>'+
               '<div class="article-content">'+
                   '<p class="resume"><%= abstract %></p>'+
                    '<ul class="links">'+
                       '<ul>'+
                       '<% _(documents).each(function(d) { print("<li><a href=\'" + d.url_document + "\'>" + d.title.replace(/(^.{30,60})[\s].+$/m,\'$1&hellip;\') + "</a></li>"); }) %>'+
                       '</ul>'+
                   '</ul>'+
               '</div>'+
           '</div>'+
       '</div>'
    ).template();
	
	var clusterTemplateDossierDoc = _( 
    '<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="http://localhost:8000/documentary_files/<%=user%>/<%=id%>/0/12/<%=doc_id%>"><%-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 clusterListeTemplate = _(
      '<div class="article" data-cluster-id="<%= id %>">'+
           '<div class="inner-article clearfix">'+
               '<h2><a onClick="getDocumentsWithAnnotations();" title="Lire l\'article" style="cursor:pointer;"> <%= title %> »</a></h2> <form id="ajaxgetdocuments" method="post" action="/<%=query_id%>/<%=id%>/0/10"> <input type="hidden" id="requestType"  name="requestType" value="documents"/></form>'+
			   '<p class="number-article">'+
                   '<a href="http://localhost:8000/documents_cluster/<%=query_id%>/<%=id%>/0/10"><%= documents_number %> articles | <%= annotations.length %> annotations </a>'+
                   '<a title="ajouter une annotation" class="add-annotation" href="#"></a>'+
               '</p>'+
                '<div class="article-annotations">'+
                   '<a title="48 annotations" class="blue" href="#" style="width:20%;"></a>'+
                   '<a title="title" class="green" href="#" style="width:20%;"></a>'+
                   '<a title="title" class="red" href="#" style="width:40%;"></a>'+
                   '<a title="title" class="empty" href="#" style="width:20%;"></a>'+
               '</div>'+
               '<div class="article-content">'+
                   '<p class="resume"><%= abstract %></p>'+
                    '<ul class="links">'+
                       '<ul>'+
                       '<% _(documents).each(function(d) { print("<li><a href=\'" + d.url_document + "\'>" + d.title.replace(/(^.{30,60})[\s].+$/m,\'$1&hellip;\') + "</a></li>"); }) %>'+
                       '</ul>'+
                   '</ul>'+
               '</div>'+
           '</div>'+
       '</div>'
    ).template();
	*/
 var hTreemap = 600;//à définir
    $('#treemap').height(hTreemap);
    
    function showResults(results) 
	{
		
		if (typeof (results.clusters) == 'undefined')
		{
			$('#create-dossierDoc').hide();
		}
		else
		{
			$('#create-dossierDoc').show();
		}
		$(".articles").empty();
		$(".articles").html(_(results.clusters).reduce(function(mem, c) { return mem + clusterListeTemplate(c); },''));
        var data = _(results.clusters).map(function(cluster, i) {
            var hue = (parseInt(cluster.id)%6)/6
            return {
                id: cluster.id,
				query_id: cluster.query_id,
                label: cluster.title,
                abstract : cluster.abstract,
                value: parseFloat(cluster.weight),
                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').empty();
        $('#treemap #actus').html(treemapHtml);

        //redimensionnement d'image        
        $(".actu img").each(function() 
		{
			
			var img = $(this),
                div = $(this).parent();
            $(this).load(function() {
                var iw = $(this).width(),
                    ih = $(this).height(),
                    dw = $(this).parent().width(),
                    dh = $(this).parent().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
                });
            });
        });
        
     /*   $(".cluster").html(data.reduce(function(mem, c) {
            return mem + '<li><a href="http://localhost:8000/'+c.query_id+'/'+c.id+'/0/12/0" title="Afficher le cluster" data-cluster-id="' + c.id + '">' + c.label + '</a></li>'
        }, ''));
        
        $(".actu, .cluster a, .article").hover
		(
            function() 
			{
                $("body").trigger("select-cluster", $(this).attr("data-cluster-id"));
            },
            function() 
			{
                $("body").trigger("unselect-cluster", $(this).attr("data-cluster-id"));
            }
        )*/
		
        
    }
    
	 function showResultsDossierDoc(results) 
	 {
		$(".articles").empty();
		$(".articles").html(_(results.clusters).reduce(function(mem, c) { return mem + clusterListeTemplateDossierDoc(c); },''));
		 var data = _(results.clusters).map(function(cluster, i) {
			 var hue = (parseInt(cluster.id)%6)/6
            return {
                id: cluster.id,
				doc_id: cluster.doc_id,
				user: cluster.user,
                label: cluster.title,
                abstract : cluster.abstract,
                value: parseFloat(cluster.weight),
                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 + clusterTemplateDossierDoc(d);
        },"");
		$('#treemap #actus').empty();
        $('#treemap #actus').html(treemapHtml);

        //redimensionnement d'image        
        $(".actu img").each(function() 
		{
			var img = $(this),
                div = $(this).parent();
			var loadThisImage = 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
                });
            }
			if (this.width) {
				loadThisImage();
			} else {
            	img.load(loadThisImage);
			}
        });
  
        /*$("body").on("select-cluster", function(e, clusterid) {
            $(".actu[data-cluster-id='" + clusterid + "'], .cluster a[data-cluster-id='" + clusterid + "'], .article[data-cluster-id='" + clusterid + "']").addClass("selected");
        });
        $("body").on("unselect-cluster", function(e, clusterid) {
            $(".actu[data-cluster-id='" + clusterid + "'], .cluster a[data-cluster-id='" + clusterid + "'], .article[data-cluster-id='" + clusterid + "']").removeClass("selected");
        });*/
    }


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